text
stringlengths 2
6.14k
|
|---|
import React from 'react';
import {storiesOf} from '@storybook/react';
// import {action} from '@storybook/addon-actions';
import {withInfo} from '@storybook/addon-info';
import StackedBarChart from 'sentry-ui/stackedBarChart';
storiesOf('StackedBarChart', module).add(
'default',
withInfo('')(() => (
<div style={{height: 400}}>
<StackedBarChart
series={[
{
data: [{x: 1461099600, y: 31734}, {x: 1461103200, y: 36790}],
label: 'received',
},
{
data: [{x: 1461099600, y: 2867}, {x: 1461103200, y: 2742}],
label: 'rejected',
},
{
data: [{x: 1461099600, y: 0}, {x: 1461103200, y: 0}],
label: 'blacklisted',
},
]}
className="dashboard-barchart standard-barchart"
height="100%"
label="events"
barClasses={['received', 'blacklisted', 'rejected']}
/>
</div>
))
);
|
/**
* Created by praba on 2/12/2016.
*/
//JS file for physicins page
Polymer({
is: "physicins-page",
ready:function()
{
//Setting current page in session for fetching labels dynamically
localStorage.setItem("curr_sess_showpage","physicins-page");
//calling webcomponent service to fetch labels for current page
this.$.ID_Webcomponent_Service.callWebcomponentService();
//To initially show current logged role state items requesting service component to make req to the server
this.$.gs.physicreadService();
}
});
|
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict';
const common = require('../common');
const assert = require('assert');
if (!common.hasCrypto) {
common.skip('missing crypto');
return;
}
const crypto = require('crypto');
function test() {
const odd = Buffer.alloc(39, 'A');
const c = crypto.createDiffieHellman(32);
c.setPrivateKey(odd);
c.generateKeys();
}
// FIPS requires a length of at least 1024
if (!common.hasFipsCrypto) {
assert.doesNotThrow(function() { test(); });
} else {
assert.throws(function() { test(); }, /key size too small/);
}
|
/**
* Copyright 2014, Yahoo! Inc.
* Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
'use strict';
var createStore = require('fluxible/addons').createStore;
var routesConfig= require('../configs/routes')
var ApplicationStore = createStore({
storeName: 'ApplicationStore',
handlers: {
'CHANGE_ROUTE_SUCCESS' : 'handleNavigate',
'UPDATE_PAGE_TITLE' : 'updatePageTitle'
},
initialize: function () {
this.currentPageName = null;
this.currentPage = null;
this.currentRoute = null;
this.pages = routesConfig;
this.pageTitle = '';
},
handleNavigate: function (route) {
if (this.currentRoute && (this.currentRoute.url === route.url)) {
return;
}
var pageName = route.config.page;
var page = this.pages[pageName];
this.currentPageName = pageName;
this.currentPage = page;
this.currentRoute = route;
this.emitChange();
},
updatePageTitle: function (title) {
this.pageTitle = title.pageTitle;
this.emitChange();
},
getCurrentPageName: function () {
return this.currentPageName;
},
getPageTitle: function () {
return this.pageTitle;
},
getState: function () {
return {
currentPageName: this.currentPageName,
currentPage: this.currentPage,
pages: this.pages,
route: this.currentRoute,
pageTitle: this.pageTitle
};
},
dehydrate: function () {
return this.getState();
},
rehydrate: function (state) {
this.currentPageName = state.currentPageName;
this.currentPage = state.currentPage;
this.pages = state.pages;
this.currentRoute = state.route;
this.pageTitle = state.pageTitle;
}
});
module.exports = ApplicationStore;
|
function tryDecode(array)
{
var IV=[], message='';
var key = localStorage.aeskey;
if (!key)
key = '00112233445566778899aabbccddeeff';
var key = CryptoJS.enc.Hex.parse(key);
for (i = 0; i < array.length; ++i)
message = message + array[i];
if (message.length < 64)
return;
IV = message.slice(0,32);
IV = CryptoJS.enc.Hex.parse(IV);
message=message.slice(32);
message=message.slice(0,Math.floor(message.length/32)*32);
message=message + '00000000000000000000000000000000';
message = CryptoJS.enc.Hex.parse(message);
var aesDecryptor = CryptoJS.algo.AES.createDecryptor(key, {iv: IV, padding: CryptoJS.pad.NoPadding});
var decoded = aesDecryptor.process(message);
decoded = decoded.toString();
var eyecatcher = decoded.slice(0,8);
if (eyecatcher == 'facef00d')
{
var length = decoded.substr(8,8);
length = parseInt(length,16);
if (((length * 2) + 16) < decoded.length)
{
var messageHex = decoded.substr(16,length * 2);
var messageBuf = CryptoJS.enc.Hex.parse(messageHex);
var printMessage = messageBuf.toString(CryptoJS.enc.Utf8);
var notification = webkitNotifications.createNotification(
chrome.extension.getURL('icon48.png'),
'snique',
printMessage
);
notification.show();
}
}
//var finish = aesDecryptor.finalize();
//console.log("finish=" + finish);
if (array.length > 1)
{
array.shift();
tryDecode(array);
}
}
chrome.extension.onConnect.addListener(function(port)
{
var srcArray = [];
var xhrArray = [];
var srcETags = {};
port.onMessage.addListener(function(msg)
{
var src = msg.src;
if (!((src.substr(0,5) == "http:") || (src.substr(0,6) == "https:")))
src = msg.base + '/' + src;
srcArray.push(src);
xhr = new XMLHttpRequest();
xhr.open('HEAD',src,false);
xhr.onreadystatechange = function()
{
if (xhr.readyState >= XMLHttpRequest.HEADERS_RECEIVED)
{
var ETag = xhr.getResponseHeader("ETag");
if (!((ETag == undefined) || (ETag == null) || (ETag.length < 2)))
{
srcETags[src] = ETag;
}
}
};
xhrArray.push(xhr);
xhr.send();
});
port.onDisconnect.addListener(function()
{
var srcBytes = [];
for (i = 0; i < srcArray.length; ++i)
{
var ETag = srcETags[srcArray[i]];
if (!((ETag == undefined) || (ETag == null) || (ETag.length < 2)))
{
ETag = ETag.replace(/[^abcdefABCDEF0123456789]/g,'');
ETag = ETag.substring(0,Math.floor(ETag.length / 2) * 2);
var bytes = CryptoJS.enc.Hex.parse(ETag);
srcBytes.push(bytes);
}
}
tryDecode(srcBytes);
});
});
|
define([
"intern!object",
"intern/chai!assert",
"delite/register",
"deliteful/Button"
], function (registerSuite, assert, register, Button) {
var container, html = "<button is='d-button' id='b1' textDir='ltr'>" +
"\u05d0\u05d1\u05d2 ABC</button>" +
"<button is='d-button' id='b2' textDir='rtl'>ABC \u05d0\u05d1\u05d2</button>" +
"<button is='d-button' id='b3' title='ABC \u05d0\u05d1\u05d2' textDir='auto'>" +
"\u05d0\u05d1\u05d2 ABC</button>" +
"<button is='d-button' id='b4' label='ABC \u05d2\u05d1\u05d0' textDir='auto'>" +
"\u05d0\u05d1\u05d2 ABC</button>";
registerSuite({
name: "deliteful/Button (bidi)",
setup: function () {
container = document.createElement("div");
document.body.appendChild(container);
},
markup: {
beforeEach: function () {
container.innerHTML = html;
register.parse(container);
},
"ltr": function () {
var b1 = document.getElementById("b1");
assert.strictEqual("\u202a\u05d0\u05d1\u05d2 ABC\u202c", b1.labelNode.textContent,
"ltr: wrong displayed value for 'label'");
assert.strictEqual("\u202a\u05d0\u05d1\u05d2 ABC\u202c", b1.title,
"ltr: wrong default value for 'title'");
},
"rtl": function () {
var b2 = document.getElementById("b2");
assert.strictEqual("\u202bABC \u05d0\u05d1\u05d2\u202c", b2.labelNode.textContent,
"rtl: wrong displayed value for 'label'");
assert.strictEqual("\u202bABC \u05d0\u05d1\u05d2\u202c", b2.title,
"rtl: wrong default value for 'title'");
},
"auto": function () {
var b3 = document.getElementById("b3");
assert.strictEqual("\u202b\u05d0\u05d1\u05d2 ABC\u202c", b3.labelNode.textContent,
"auto: wrong displayed value for 'label'");
assert.strictEqual("\u202aABC \u05d0\u05d1\u05d2\u202c", b3.title, "auto: wrong value for 'title'");
},
"auto2": function () {
var b4 = document.getElementById("b4");
assert.strictEqual("\u202aABC \u05d2\u05d1\u05d0\u202c", b4.labelNode.textContent,
"auto2: wrong displayed value for 'label'");
assert.strictEqual("\u202aABC \u05d2\u05d1\u05d0\u202c", b4.title,
"auto2: wrong value for 'title'");
},
afterEach: function () {
container.innerHTML = "";
}
},
dynChanges: {
beforeEach: function () {
container.innerHTML = html;
},
"textDir": function () {
var b1 = new Button({id: "b1", label: "\u05d0\u05d1\u05d2 ABC",
title: "ABC \u05d0\u05d1\u05d2"});
container.appendChild(b1);
b1.attachedCallback();
b1.textDir = "ltr";
b1.deliver();
assert.strictEqual("\u202a\u05d0\u05d1\u05d2 ABC\u202c", b1.labelNode.textContent,
"ltr: wrong displayed value for 'label'");
assert.strictEqual("\u202aABC \u05d0\u05d1\u05d2\u202c", b1.title,
"ltr: wrong default value for 'title'");
b1.textDir = "rtl";
b1.deliver();
assert.strictEqual("\u202b\u05d0\u05d1\u05d2 ABC\u202c", b1.labelNode.textContent,
"rtl: wrong displayed value for 'label'");
assert.strictEqual("\u202bABC \u05d0\u05d1\u05d2\u202c", b1.title,
"rtl: wrong default value for 'title'");
b1.textDir = "auto";
b1.deliver();
assert.strictEqual("\u202b\u05d0\u05d1\u05d2 ABC\u202c", b1.labelNode.textContent,
"auto: wrong displayed value for 'label'");
assert.strictEqual("\u202aABC \u05d0\u05d1\u05d2\u202c", b1.title,
"auto: wrong default value for 'title'");
},
"label": function () {
var b2 = new Button({id: "b2"});
container.appendChild(b2);
b2.attachedCallback();
b2.textDir = "rtl";
b2.label = "ABC \u05d0\u05d1\u05d2";
b2.deliver();
assert.strictEqual("\u202bABC \u05d0\u05d1\u05d2\u202c", b2.labelNode.textContent,
"label: wrong displayed rtl value");
b2.textDir = "ltr";
b2.label = "\u05d0\u05d1\u05d2 ABC";
b2.deliver();
assert.strictEqual("\u202a\u05d0\u05d1\u05d2 ABC\u202c", b2.labelNode.textContent,
"label: wrong displayed ltr value");
},
"title": function () {
var b3 = new Button({id: "b3"});
container.appendChild(b3);
b3.attachedCallback();
b3.textDir = "auto";
b3.title = "\u05d0\u05d1\u05d2 ABC";
b3.deliver();
assert.strictEqual("\u202b\u05d0\u05d1\u05d2 ABC\u202c", b3.title,
"title: wrong value for 'auto' (1)");
b3.textDir = "ltr";
b3.title = "ABC \u05d0\u05d1\u05d2";
b3.deliver();
assert.strictEqual("\u202aABC \u05d0\u05d1\u05d2\u202c", b3.title,
"title: wrong value for 'auto' (2)");
},
afterEach: function () {
container.innerHTML = "";
}
},
teardown: function () {
container.parentNode.removeChild(container);
}
});
});
|
import { Start } from './components/start';
import { About } from './components/about';
import { Contact } from './components/contact';
@RouteConfig([
{ path: '/', component: Start, as: 'start'}
{ path: '/about', component: About, as: 'about'}
{ path: '/contact', component: Contact, as: 'contact'}
])
class App {
....
}
|
// Generated by CoffeeScript 1.10.0
(function() {
var preloaded,
indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };
preloaded = [];
arcs.preload = function(images) {
var i, img, len, results;
if (typeof images === 'string') {
images = [images];
}
results = [];
for (i = 0, len = images.length; i < len; i++) {
img = images[i];
if (indexOf.call(preloaded, img) >= 0) {
continue;
}
$('<img />').attr('src', img).hide().appendTo('body');
results.push(preloaded.push(img));
}
return results;
};
}).call(this);
|
import m from 'mithril';
export function view(ctrl, Body) {
return <html>
<head>
<title>readings</title>
<meta charset="utf-8" />
<meta name="description" content="A platform to present written information about specific topics" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="//fonts.googleapis.com/icon?family=Material+Icons" />
<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Roboto:300,400,500,700" />
<link rel="stylesheet" href="/assets/readings.css" />
</head>
<body class="mdl-base mdl-color--grey-100 mdl-color-text--grey-700">
<Body />
</body>
<script src="/assets/material.js" />
<script src="/assets/readings.js" />
</html>;
}
|
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* @name: S15.5.4.14_A4_T5;
* @section: 15.5.4.14;
* @assertion: String.prototype.split (separator, limit) returns an Array object into which substrings of the result of converting this object to a string have
* been stored. If separator is a regular expression then
* inside of SplitMatch helper the [[Match]] method of R is called giving it the arguments corresponding;
* @description: Arguments are regexp /l/ and 3, and instance is String("hello");
*/
var __string = new String("hello");
var __re = /l/;
var __split = __string.split(__re,3);
//////////////////////////////////////////////////////////////////////////////
//CHECK#1
if (__split.constructor !== Array) {
$ERROR('#1: var __string = new String("hello"); var __re = /l/; __split = __string.split(__re,3); __split.constructor === Array. Actual: '+__split.constructor );
}
//
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//CHECK#2
if (__split.length !== 3) {
$ERROR('#2: var __string = new String("hello"); var __re = /l/; __split = __string.split(__re,3); __split.length === 3. Actual: '+__split.length );
}
//
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//CHECK#3
if (__split[0] !== "he") {
$ERROR('#3: var __string = new String("hello"); var __re = /l/; __split = __string.split(__re,3); __split[0] === "he". Actual: '+__split[0]);
}
//
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//CHECK#4
if (__split[1] !== "") {
$ERROR('#4: var __string = new String("hello"); var __re = /l/; __split = __string.split(__re,3); __split[1] === "". Actual: '+__split[1]);
}
//
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//CHECK#5
if (__split[2] !== "o") {
$ERROR('#5: var __string = new String("hello"); var __re = /l/; __split = __string.split(__re,3); __split[2] === "o". Actual: '+__split[2] );
}
//
//////////////////////////////////////////////////////////////////////////////
|
/* eslint-env jest */
import React from 'react'
import { fireEvent, cleanup } from '@testing-library/react'
import { renderWithIntl } from '../../../../test/helpers/render'
import StreetMetaWidthMenu from '../StreetMetaWidthMenu'
describe('StreetMetaWidthMenu', () => {
afterEach(cleanup)
it('renders (metric units, default width selected)', () => {
const wrapper = renderWithIntl(
<StreetMetaWidthMenu
street={{
units: 0,
width: 60,
occupiedWidth: 10
}}
onChange={jest.fn()}
/>
)
expect(wrapper.asFragment()).toMatchSnapshot()
})
it('renders (metric units, custom width selected)', () => {
const wrapper = renderWithIntl(
<StreetMetaWidthMenu
street={{
units: 0,
width: 10,
occupiedWidth: 10
}}
onChange={jest.fn()}
/>
)
expect(wrapper.asFragment()).toMatchSnapshot()
})
it('renders (imperial units, default width selected)', () => {
const wrapper = renderWithIntl(
<StreetMetaWidthMenu
street={{
units: 1,
width: 60,
occupiedWidth: 10
}}
onChange={jest.fn()}
/>
)
expect(wrapper.asFragment()).toMatchSnapshot()
})
it('calls onChange handler when selection changed', () => {
const handleChange = jest.fn((value) => value)
const wrapper = renderWithIntl(
<StreetMetaWidthMenu
street={{
units: 0,
width: 40,
occupiedWidth: 10
}}
editable
onChange={handleChange}
/>
)
fireEvent.change(wrapper.getByRole('listbox'), { target: { value: 40 } })
// Return value is a string from <option value=""> attribute
expect(handleChange).toHaveReturnedWith('40')
})
})
|
/*
Copyright (c) 2010, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
http://developer.yahoo.com/yui/license.html
version: 3.7.3
build: 3.7.3
*/
YUI.add("lang/datatable-sort",function(e){e.Intl.add("datatable-sort","",{asc:"Ascending",desc:"Descending",sortBy:"Sort by {column}",reverseSortBy:"Reverse sort by {column}"})},"3.7.3");
|
'use strict';
//# sourceMappingURL=index.js.map
|
import attach from "@unction/attach"
import isArray from "@unction/isarray"
import isObject from "@unction/isobject"
import reduceWithValueKey from "@unction/reducewithvaluekey"
export default function mapValuesWithValueKey (unction: ValueType => ValueType): Function {
return function mapValuesWithValueKeyUnction (iterable: IterableType): IterableType {
const reducedWithUnction = reduceWithValueKey(
(accumulated: AccumulatedType): Function => (value: ValueType): Function => (key: KeyType): IterableType => attach(key)(unction(value)(key))(accumulated)
)
if (isArray(iterable)) {
return reducedWithUnction(
[]
)(
iterable
)
}
if (isObject(iterable)) {
return reducedWithUnction(
{}
)(
iterable
)
}
throw new Error("Couldn't figure out how to map over this iterable")
}
}
|
import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M3 17v2h6v-2H3zM3 5v2h10V5H3zm10 16v-2h8v-2h-8v-2h-2v6h2zM7 9v2H3v2h4v2h2V9H7zm14 4v-2H11v2h10zm-6-4h2V7h4V5h-4V3h-2v6z" />
, 'Tune');
|
import { clickable, create, hasClass, isVisible, text } from 'ember-cli-page-object';
import { pageObjectFillInFroalaEditor, pageObjectFroalaEditorValue } from 'ilios-common';
import meshManager from './manage-objective-descriptors';
import competencyManager from './manage-objective-competency';
import meshDescriptors from './objective-list-item-descriptors';
import competency from './objective-list-item-competency';
import taxonomyManager from 'ilios-common/page-objects/components/taxonomy-manager';
import selectedTerms from 'ilios-common/page-objects/components/objective-list-item-terms';
const definition = {
scope: '[data-test-program-year-objective-list-item]',
hasRemoveConfirmation: hasClass('confirm-removal'),
toggleExpandCollapse: clickable('[data-test-toggle-expand]'),
description: {
scope: '[data-test-description]',
openEditor: clickable('[data-test-edit]'),
editorContents: pageObjectFroalaEditorValue('[data-test-html-editor]'),
edit: pageObjectFillInFroalaEditor('[data-test-html-editor]'),
save: clickable('.done'),
validationError: text('.validation-error-message'),
hasValidationError: isVisible('.validation-error-message'),
},
competency,
meshDescriptors,
remove: clickable('[data-icon="trash"]', { scope: '[data-test-actions]' }),
hasTrashCan: isVisible('[data-icon="trash"]', { scope: '[data-test-actions]' }),
activate: clickable('[data-test-activate]', { scope: '[data-test-actions]' }),
isActive: isVisible('[data-icon="lightbulb-on"]', { scope: '[data-test-actions]' }),
deactivate: clickable('[data-test-deactivate]', { scope: '[data-test-actions]' }),
isInactive: isVisible('[data-icon="lightbulb-slash"]', { scope: '[data-test-actions]' }),
confirmRemoval: {
scope: '[data-test-confirm-removal]',
confirm: clickable('[data-test-confirm]'),
cancel: clickable('[data-test-cancel]'),
},
meshManager,
competencyManager,
selectedTerms,
taxonomyManager,
};
export default definition;
export const component = create(definition);
|
define(["exports", "foo"], function (_exports, _foo) {
"use strict";
Object.defineProperty(_exports, "__esModule", {
value: true
});
_exports.default = void 0;
_exports.default = _foo.foo;
});
|
import { Template } from 'meteor/templating';
import './DiscussionTabbar.html';
Template.discussionsTabbar.helpers({
close() {
const { data } = Template.instance();
const { tabBar } = data;
return () => tabBar.close();
},
});
|
import { IsolatedInlineNodeComponent, TextPropertyEditor } from 'substance'
export default class TestInlineNodeComponent extends IsolatedInlineNodeComponent {
getClassNames () {
return 'sc-test-inline sc-inline-node'
}
renderContent ($$) {
const node = this.props.node
return $$('span').append(
$$(TextPropertyEditor, {
tagName: 'span',
path: [node.id, 'content'],
withoutBreak: true,
disabled: this.isDisabled()
}).ref('editor')
)
}
}
|
'use strict';
var PbWatcher = require('../');
var watchIntervalMs = 250;
PbWatcher(function(data){
console.log('Clipboard changed to : "%s"', data);
}, watchIntervalMs);
|
import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M21 3h-6.18C14.4 1.84 13.3 1 12 1s-2.4.84-2.82 2H3v18h18V3zm-9 0c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zm-2 14l-4-4 1.41-1.41L10 14.17l6.59-6.59L18 9l-8 8z" />
, 'AssignmentTurnedInSharp');
|
var React = require('react/addons');
React.createElement('div', getProps(), 'foo');
|
OC.L10N.register(
"files_versions",
{
"Versions" : "Versións",
"Failed to revert {file} to revision {timestamp}." : "Non foi posíbel reverter {file} á revisión {timestamp}.",
"_%n byte_::_%n bytes_" : ["%n byte","%n bytes"],
"Restore" : "Restabelecer",
"No other versions available" : "Non hai outras versións dispoñíbeis"
},
"nplurals=2; plural=(n != 1);");
|
import {GraphQLNonNull, GraphQLID} from 'graphql'
import {unlockRetroSurveyForUser} from 'src/server/actions/retroSurveyLockUnlock'
import userCan from 'src/common/util/userCan'
import {Project} from 'src/server/services/dataService/models'
import {LGNotAuthorizedError} from 'src/server/util/error'
import {ProjectSummary} from 'src/server/graphql/schemas'
export default {
type: ProjectSummary,
args: {
memberId: {
type: new GraphQLNonNull(GraphQLID),
description: 'The memberId of the member whose survey should be unlocked',
},
projectId: {
type: new GraphQLNonNull(GraphQLID),
description: 'The projects id of the survey to unlock for this given member',
},
},
async resolve(source, {memberId, projectId}, {rootValue: {currentUser}}) {
if (!userCan(currentUser, 'lockAndUnlockSurveys')) {
throw new LGNotAuthorizedError()
}
await unlockRetroSurveyForUser(memberId, projectId)
return {
project: await Project.get(projectId)
}
}
}
|
exports.config = {
framework: 'jasmine',
seleniumAddress: 'http://localhost:4444/wd/hub',
baseUrl: 'http://localhost:8100',
capabilities: {
// You can use other browsers
// like firefox, phantoms, safari, IE (-_-)
'browserName': 'chrome'
},
specs: [
// We are going to make this file in a minute
'test/e2e/*.spec.js'
],
jasmineNodeOpts: {
showColors: true,
defaultTimeoutInterval: 30000,
isVerbose: true,
includeStackTrace: true
},
allScriptsTimeout: 20000
onPrepare: function() {
browser.driver.get('http://localhost:8100');
// require('protractor-http-mock').config = {
// rootDirectory: __dirname, // default value: process.cwd()
// protractorConfig: 'protractor.config.js' // default value: 'protractor.conf'
// };
}
};
|
import React from "react";
import ReactDOM from 'react-dom';
import _ from "lodash";
import {Key} from "../utils.js";
var Prompt = React.createClass({
contextTypes: {
returnFocus: React.PropTypes.func
},
propTypes: {
options: React.PropTypes.array.isRequired,
done: React.PropTypes.func.isRequired,
prompt: React.PropTypes.string
},
componentDidMount: function () {
ReactDOM.findDOMNode(this).focus();
},
onKeyDown: function (e) {
e.stopPropagation();
e.preventDefault();
var opts = this.getOptions();
for (var i = 0; i < opts.length; i++) {
var k = opts[i].key;
if (Key[k.toUpperCase()] === e.keyCode) {
this.done(k);
return;
}
}
if (e.keyCode === Key.ESC || e.keyCode === Key.ENTER) {
this.done(false);
}
},
onClick: function (e) {
this.done(false);
},
done: function (ret) {
this.props.done(ret);
this.context.returnFocus();
},
getOptions: function () {
var opts = [];
var keyTaken = function (k) {
return _.includes(_.pluck(opts, "key"), k);
};
for (var i = 0; i < this.props.options.length; i++) {
var opt = this.props.options[i];
if (_.isString(opt)) {
var str = opt;
while (str.length > 0 && keyTaken(str[0])) {
str = str.substr(1);
}
opt = {
text: opt,
key: str[0]
};
}
if (!opt.text || !opt.key || keyTaken(opt.key)) {
throw "invalid options";
} else {
opts.push(opt);
}
}
return opts;
},
render: function () {
var opts = this.getOptions();
opts = _.map(opts, function (o) {
var prefix, suffix;
var idx = o.text.indexOf(o.key);
if (idx !== -1) {
prefix = o.text.substring(0, idx);
suffix = o.text.substring(idx + 1);
} else {
prefix = o.text + " (";
suffix = ")";
}
var onClick = function (e) {
this.done(o.key);
e.stopPropagation();
}.bind(this);
return <span
key={o.key}
className="option"
onClick={onClick}>
{prefix}
<strong className="text-primary">{o.key}</strong>{suffix}
</span>;
}.bind(this));
return <div tabIndex="0" onKeyDown={this.onKeyDown} onClick={this.onClick} className="prompt-dialog">
<div className="prompt-content">
{this.props.prompt || <strong>Select: </strong> }
{opts}
</div>
</div>;
}
});
export default Prompt;
|
/** @license MIT License (c) copyright 2010-2016 original author or authors */
/** @author Brian Cavalier */
/** @author John Hann */
import Stream from '../Stream'
import Map from '../fusion/Map'
import Pipe from '../sink/Pipe'
/**
* Transform each value in the stream by applying f to each
* @param {function(*):*} f mapping function
* @param {Stream} stream stream to map
* @returns {Stream} stream containing items transformed by f
*/
export function map (f, stream) {
return new Stream(Map.create(f, stream.source))
}
/**
* Replace each value in the stream with x
* @param {*} x
* @param {Stream} stream
* @returns {Stream} stream containing items replaced with x
*/
export function constant (x, stream) {
return map(function () {
return x
}, stream)
}
/**
* Perform a side effect for each item in the stream
* @param {function(x:*):*} f side effect to execute for each item. The
* return value will be discarded.
* @param {Stream} stream stream to tap
* @returns {Stream} new stream containing the same items as this stream
*/
export function tap (f, stream) {
return new Stream(new Tap(f, stream.source))
}
function Tap (f, source) {
this.source = source
this.f = f
}
Tap.prototype.run = function (sink, scheduler) {
return this.source.run(new TapSink(this.f, sink), scheduler)
}
function TapSink (f, sink) {
this.sink = sink
this.f = f
}
TapSink.prototype.end = Pipe.prototype.end
TapSink.prototype.error = Pipe.prototype.error
TapSink.prototype.event = function (t, x) {
var f = this.f
f(x)
this.sink.event(t, x)
}
|
var Detector = require('./vendor/Detector.js');
if ( Detector.webgl )
renderer = new THREE.WebGLRenderer( {antialias:true} ); // if browser suports webgl use webgl renderer
else
renderer = new THREE.CanvasRenderer(); // fallback
renderer.setSize(window.innerWidth, window.innerHeight); // set renderer size based on window size
renderer.shadowMapEnabled = true; // Shadows allowed
module.exports = renderer;
|
var _assoc = require('./_assoc');
var _dissoc = require('./_dissoc');
var _slice = require('./_slice');
module.exports = function _dissocPath(path, obj) {
switch (path.length) {
case 0:
return obj;
case 1:
return _dissoc(path[0], obj);
default:
var head = path[0];
var tail = _slice(path, 1);
return obj[head] == null ? obj : _assoc(head, _dissocPath(tail, obj[head]), obj);
}
};
|
var exec = require("cordova/exec");
var AppPreferences = function () {};
var AppPreferencesError = function(code, message) {
this.code = code || null;
this.message = message || '';
};
AppPreferencesError.NO_PROPERTY = 0;
AppPreferencesError.NO_PREFERENCE_ACTIVITY = 1;
AppPreferences.prototype.get = function(key,success,fail) {
cordova.exec(success,fail,"applicationPreferences","get",[key]);
};
AppPreferences.prototype.set = function(key,value,success,fail) {
cordova.exec(success,fail,"applicationPreferences","set",[key, value]);
};
AppPreferences.prototype.load = function(success,fail) {
cordova.exec(success,fail,"applicationPreferences","load",[]);
};
AppPreferences.prototype.show = function(activity,success,fail) {
cordova.exec(success,fail,"applicationPreferences","show",[activity]);
};
AppPreferences.prototype.clear = function(success,fail) {
cordova.exec(success,fail,"applicationPreferences","clear", []);
};
AppPreferences.prototype.remove = function(keyToRemove, success,fail) {
cordova.exec(success,fail,"applicationPreferences","remove", [keyToRemove]);
};
var appPreferences = new AppPreferences();
module.exports = appPreferences;
|
// Karma configuration
// Generated on Sat Oct 18 2014 22:09:29 GMT-0400 (EDT)
var webpackConfig = require( "./webpack.config.js" );
var _ = require( "lodash" );
_.extend( webpackConfig, {
cache: true,
watch: false,
debug: true,
devtool: "inline-source-map"
} );
var reporters = [ "spec" ];
delete webpackConfig.output;
delete webpackConfig.entry;
module.exports = function( config ) {
config.set( {
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: "",
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: [ "mocha" ],
// list of files / patterns to load in the browser
files: [
"spec/helpers/phantomjs-shims.js",
"spec/helpers/karma-setup.js",
"spec/**/*.spec.*"
],
// list of files to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
"spec/**/*.spec.*": [ "webpack", "sourcemap" ],
"spec/helpers/karma-setup.js": [ "webpack", "sourcemap" ]
},
webpack: webpackConfig,
// test results reporter to use
// possible values: "dots", "progress"
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: reporters,
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: [ "Chrome" /*, "Safari", "Firefox" */ ],
webpackServer: {
quiet: true,
stats: {
colors: true
}
},
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false
} );
};
|
if(!employees) {
employees = [];
}
employees.push({
id:1, name: 'Lulu Hodges'
});
|
'use strict';
describe('testFilter', function () {
var filter;
beforeEach(module('a8m.test'));
beforeEach(inject(function ($filter) {
filter = $filter('test');
}));
it('should test a string with given pattern', function() {
expect(filter('15/12/2003', '^[0-9]{2}[/]{1}[0-9]{2}[/]{1}[0-9]{4}$', 'i')).toEqual(true);
expect(filter('foobarbaz', '^[a-z]{3,}$')).toEqual(true);
expect(filter('FOOBARBAZ', '^[a-z]{3,}$', 'i')).toEqual(true);
expect(filter('FOOBARBAZ', '^[a-z]{3,}$')).toEqual(false);
expect(filter('foobarbaz', '\\W')).toEqual(false);
expect(filter('foobarbaz', '\\w')).toEqual(true);
expect(filter('1a/bb/2003', '^[0-9]{2}[/]{1}[0-9]{2}[/]{1}[0-9]{4}$', 'i')).toEqual(false);
});
it('should get a !string and not touch it', function() {
expect(filter({})).toEqual({});
expect(filter([])).toEqual([]);
expect(filter(1)).toEqual(1);
expect(filter(!1)).toBeFalsy();
});
});
|
import { Schema, Config } from '../../';
import schema from './schema'
Config({
database: {
adapter: 'postgresql',
host: '127.0.0.1',
user: /*'postgres',//*/ 'Z80',
database: 'moon',
password: ''
},
server: {
port: 8088,
dist: __dirname + '/../dist'
}
});
Schema(schema);
|
'use strict';
var common = require('../common');
var Transform = require('../../').Transform;
module.exports = function (t) {
t.test('transform split objectmode', function (t) {
t.plan(10);
var parser = new Transform({ readableObjectMode : true });
t.ok(parser._readableState.objectMode, 'parser 1');
t.notOk(parser._writableState.objectMode, 'parser 2');
t.equals(parser._readableState.highWaterMark, 16, 'parser 3');
t.equals(parser._writableState.highWaterMark, (16 * 1024), 'parser 4');
parser._transform = function(chunk, enc, callback) {
callback(null, { val : chunk[0] });
};
var parsed;
parser.on('data', function(obj) {
parsed = obj;
});
parser.end(Buffer.from([42]));
parser.on('end', function() {
t.equals(parsed.val, 42, 'parser ended');
});
var serializer = new Transform({ writableObjectMode : true });
t.notOk(serializer._readableState.objectMode, 'serializer 1');
t.ok(serializer._writableState.objectMode, 'serializer 2');
t.equals(serializer._readableState.highWaterMark, (16 * 1024), 'serializer 3');
t.equals(serializer._writableState.highWaterMark, 16, 'serializer 4');
serializer._transform = function(obj, _, callback) {
callback(null, Buffer.from([obj.val]));
};
var serialized;
serializer.on('data', function(chunk) {
serialized = chunk;
});
serializer.write({ val : 42 });
serializer.on('end', function() {
t.equals(serialized[0], 42, 'searlizer ended');
});
setImmediate(function () {
serializer.end();
});
});
}
|
let addEmp167 = (employees) => {
employees.push(
{id:167, name: 'Norman Atkins'}
)
return employees;
};
export {addEmp167};
|
function OneCard(context) {
this.context_ = context;
}
OneCard.prototype.exchange = function () {
console.log(this);
}
suite('Base access', function() {
test('need auth', function(done) {
var request = require('request');
var card = new OneCard("hello");
var responseProcessor = _.bind(card.exchange, card)
request('http://192.168.1.230/a_ajxtmn.cgi',
function (error, response, body) {
if (!error) {
done();
assert.equal(403, response.statusCode);
responseProcessor();
card.exchange();
}
});
});
})
suite('nextPrime', function() {
test('nextPrime should return the next prime number', function() {
var Person = {
name: "Tim",
age: 28,
greeting: function () {
return "Hello " + this.name + ". Wow, you are " + this.age + " years old.";
}
};
Person.greeting();
var greeting = Person.greeting;
// BAD!
//console.log(greeting()); // Will get undefined for `this.name` and `this.age`
});
});
|
// import config from './config';
import messages from '../client/messages';
const initialLocale = 'en';
export default {
$pendingActions: {},
auth: {
form: {
fields: {
email: '',
password: ''
},
error: null
}
},
i18n: {
formats: {},
locales: initialLocale,
messages: messages[initialLocale]
},
newTodo: {
title: ''
},
todos: [
{id: 1, title: 'consider ‘stop doing’ app'},
{id: 2, title: 'relax'}
],
user: {
authData: null
}
};
|
'use strict';
module.exports.install = function(admin){
admin.menu.addBefore('account', {
id:'users',
name:'User Management',
icon:'fa fa-users',
href:'#/users',
allowRoles:['admin']
});
// admin angular module dependencies
admin.modules.push('neAdmin.users');
// admin routes
admin.routes[ '/users' ] = { templateUrl: admin.basePath + 'views/users.html', controller:'UsersCtrl', reloadOnSearch:false };
// include styles
// admin.styles.push('css/mystyle.css');
// 3rd-party tools & libs, such as ase editor, or jquery, ...
// admin.libs.push('js/somelibrary.js');
// admin scripts, will be loaded
// admin.scripts.push('controllers/users-ctrl.js');
framework.rest(admin.basePath + 'users', 'User', [
{ route:'/', collection:'all', flags:[ 'get' ], count:true },
{ route:'/exists', collection:'exists', flags:['get'] },
{ route:'/{id}', collection:'one', flags:[ 'get' ] },
{ route:'/', instance:'create', afterValidation:hashPass, flags:[ 'post', 'json' ] },
{ route:'/{id}', instance:'create', flags:[ 'post', 'json' ] },
{ route:'/{id}', instance:'update', afterValidation:disableSelfDisable, flags:[ 'put', 'json' ] },
{ route:'/{id}', instance:'remove', afterValidation:disableSelfRemove, flags:[ 'delete' ] },
{ route:'/{id}/resetpass', instance:'resetPass', flags:[ 'post', 'json' ] },
], ['authorize','!admin']);
function hashPass(ctx, next){
ctx.model.hashPass();
next();
}
function disableSelfRemove(ctx, next){
if(ctx.params.id === this.user.id){
this.status = 400;
this.json({ data:{ id:['selfRemove'] } });
}
else next();
}
function disableSelfDisable(ctx, next){
if(ctx.body.disabled && ctx.params.id === this.user.id){
this.status = 400;
this.json({ data:{ id:['selfDisable'] } });
}
else next();
}
};
|
/*
* GET users listing.
*/
exports.index = function(req, res){
res.render('user/index', { title: '/ My Apps'});
};
|
(function (angular) {
"use strict";
angular.module("mfl.reports.controllers", [
"mfl.reports.controllers.base",
"mfl.reports.controllers.facilities",
"mfl.reports.controllers.facility_reporting",
"mfl.reports.controllers.chu_reporting",
"mfl.reports.updowngrades.controllers",
"ui.bootstrap.buttons"
]);
})(window.angular);
|
git://github.com/viljamis/ResponsiveSlides.js.git
|
/**
* Imports
*/
import test from 'tape'
import PixelGradient from '.'
/**
* <Pixel Gradient/> tests
*/
test('<PixelGradient/> should work', t => {
})
|
var WorkerInstance = require("../lib/workers/WorkerInstance.js").WorkerInstance,
EventEmitter = require("events").EventEmitter;
exports.WorkerPrototypeTests = {
setUp: function(done) {
done();
},
"Worker has a EventEmitter in prototype chain": function(test) {
test.expect(1);
var worker = new WorkerInstance(function() {});
test.equal(worker instanceof EventEmitter, true, "should inherits from EventEmitter");
test.done();
},
"Worker should have events on start and finish" : function(test) {
test.expect(2);
var started = false,
finished = false,
worker = new WorkerInstance(function() {});
worker.once("task-started", function() { started = true ; });
worker.once("task-finished", function() { finished = true ; });
worker.spawn();
test.equal(started, true, "task-started event should be invoked");
test.equal(finished, true, "task-finished event should be invoked");
test.done();
},
"Worker should return last transaction ID from task-finished" : function(test) {
test.expect(1);
var lastTransactionId = -1,
worker = new WorkerInstance(function() { return 667; });
worker.once("task-finished", function(result) { lastTransactionId = result; });
worker.spawn();
test.equal(lastTransactionId, 667, "task-finished event should return last transaction Id");
test.done();
},
"Worker should invoke die event always - successful case" : function(test) {
test.expect(1);
var die = false,
worker = new WorkerInstance(function() { return 667; });
worker.once("die", function() { die = true; });
worker.spawn();
test.equal(die, true, "die event should occure after successful execution");
test.done();
},
"Worker should invoke die event always - invalid case" : function(test) {
test.expect(2);
var error = null,
die = false,
worker = new WorkerInstance(function() { throw "Error"; });
worker.once("die", function(err) {
die = true;
error = err;
});
worker.spawn();
test.equal(die, true, "die event should occure after invalid execution");
test.equal(error, "Error", "die event should return exception object");
test.done();
}
};
|
var util = require( 'util' );
var url = require( 'url' );
var browser = require('../airplay').createBrowser();
var media = {
url : 'http://commondatastorage.googleapis.com/gtv-videos-bucket/big_buck_bunny_1080p.mp4',
file: '/Users/carlos/Desktop/a.mp4',
subtitles: [{
language: 'en-US',
url: 'http://carlosguerrero.com/captions_styled.vtt',
name: 'English',
},
{
language: 'es-ES',
url: 'http://carlosguerrero.com/captions_styled_es.vtt',
name: 'Spanish',
}
],
cover: {
title: 'Big Bug Bunny',
url: 'http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/images/BigBuckBunny.jpg'
},
subtitles_style: {
backgroundColor: '#FFFFFFFF', // see http://dev.w3.org/csswg/css-color/#hex-notation
foregroundColor: '#000FFFF', // see http://dev.w3.org/csswg/css-color/#hex-notation
edgeType: 'DROP_SHADOW', // can be: "NONE", "OUTLINE", "DROP_SHADOW", "RAISED", "DEPRESSED"
edgeColor: '#AA00FFFF', // see http://dev.w3.org/csswg/css-color/#hex-notation
fontScale: 1.5, // transforms into "font-size: " + (fontScale*100) +"%"
fontStyle: 'BOLD_ITALIC', // can be: "NORMAL", "BOLD", "BOLD_ITALIC", "ITALIC",
fontFamily: 'Droid Sans',
fontGenericFamily: 'CURSIVE', // can be: "SANS_SERIF", "MONOSPACED_SANS_SERIF", "SERIF", "MONOSPACED_SERIF", "CASUAL", "CURSIVE", "SMALL_CAPITALS",
windowColor: '#AA00FFFF', // see http://dev.w3.org/csswg/css-color/#hex-notation
windowRoundedCornerRadius: 10, // radius in px
windowType: 'ROUNDED_CORNERS' // can be: "NONE", "NORMAL", "ROUNDED_CORNERS"
}
}
browser.on( 'deviceOn', function( device ) {
console.log( 'device online: ' + device.id );
var hls = require( '../airplay' ).createHLS();
hls.on( 'start', function () {
console.info( '[HLS] start: %s', hls.getURI() );
});
hls.on( 'stop', function () {
console.info( '[HLS] stop: %s', hls.getURI() );
});
hls.on( 'request', function ( req ) {
// var uri = url.parse( req.url, true );
console.info( '[HLS] request: %s', req.url );
});
hls.on( 'process', function ( d ) {
console.info( '[HLS] segment process: %s, %s, %s', d.index, d.file, d.out.toString() );
});
hls.on( 'segment', function ( d ) {
console.info( '[HLS] segment created: %s, %s, %s', d.index, d.file, d.out );
});
hls.on( 'open', function ( d ) {
console.info( '[HLS] opend: %s, %s', d.file, util.inspect( d.info ) );
});
hls.on( 'error', function ( err ) {
console.info( '[HLS] segment error: ', util.inspect( err ) );
});
hls.on( 'NoFFMPEG', function ( err ) {
device.simpleplay(media.url, 0, function(){
console.log("Playing using normal streaming method (not HLS)")
})
});
hls.start( 7001 );
hls.open( media.file, function ( info ) {
device.simpleplay( hls.getURI(), '0.000000', function ( res ) {
console.info( '开始播放啦: ', res );
setTimeout(function(){
device.status( function ( info ) {
console.info( 'AppleTV 状态:', info ? info : '未播放' );
if ( info ) {
console.log(info)
}
});
}, 4000);
});
});
// device.status( function ( info ) {
// console.info( 'AppleTV 状态:', info ? info : '未播放' );
// });
});
browser.on( 'deviceOff', function( device ) {
console.log( 'device offline: ' + device.id );
});
browser.start();
// setTimeout(
// function(){
// console.info( browser.getDevices( true ) );
// },
// 2000
// );
|
import createSvgIcon from './utils/createSvgIcon';
import { jsx as _jsx } from "react/jsx-runtime";
export default createSvgIcon( /*#__PURE__*/_jsx("path", {
d: "M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zM4 12c0-4.42 3.58-8 8-8 1.85 0 3.55.63 4.9 1.69L5.69 16.9C4.63 15.55 4 13.85 4 12zm8 8c-1.85 0-3.55-.63-4.9-1.69L18.31 7.1C19.37 8.45 20 10.15 20 12c0 4.42-3.58 8-8 8z"
}), 'Block');
|
"use strict";
var jsx = require('jsx-runtime');
var hasOwn = Object.prototype.hasOwnProperty;
var emptyTags = require('empty-tags').reduce(function(map, tag) {
map[tag] = true;
return map;
}, Object.create(null));
var SVG_NS = 'http://www.w3.org/2000/svg';
var HTML_NS = 'http://www.w3.org/1999/xhtml';
var renderer = jsx.register('DOM', {
before: function(element) {
this.scope.namespaces = [];
return element;
},
tags: {
'*': {
enter: function(tag, props) {
var namespaces = this.scope.namespaces;
if (tag === 'svg') {
namespaces.unshift(SVG_NS);
} else if (tag === 'foreignObject') {
namespaces.unshift(HTML_NS);
}
var element;
if (namespaces.length) {
element = document.createElementNS(namespaces[0], tag);
} else {
element = document.createElement(tag);
}
applyProps(element, props);
return element;
},
leave: function(parent, tag) {
if (
tag === 'svg' && this.scope.namespaces[0] === SVG_NS ||
tag === 'foreignObject' && this.scope.namespaces[0] === HTML_NS
) {
this.scope.namespaces.shift();
}
return parent;
},
child: function(child, parent) {
if (child instanceof Element) {
// do nothing
} else {
child = document.createTextNode(child + '');
}
parent.appendChild(child);
return parent;
},
children: function(children, parent, tag) {
if (typeof emptyTags[tag.toLowerCase()] !== 'undefined') {
throw new Error('Tag <' + tag + ' /> cannot have children');
}
return children;
}
}
}
});
module.exports = renderer;
function applyStyle(element, style) {
if (typeof style === 'string') {
element.setAttribute('style', style);
return;
}
var elementStyle = element.style;
for (var key in style) {
if (!hasOwn.call(style, key)) continue;
elementStyle[key] = style[key];
}
}
function applyProps(element, props) {
for (var key in props) {
if (!hasOwn.call(props, key)) continue;
var val = props[key];
switch (key) {
case 'style': applyStyle(element, val); break;
case 'class': element.className = val; break;
case 'for': element.cssFor = val; break;
case 'innerHTML':
case 'outerHTML':
case 'textContent':
case 'innerText':
case 'text':
console.warn('Direct manipulation of tags content is not allowed');
break;
default: {
if (key.indexOf('-') !== -1) {
element.setAttribute(key, val);
} else {
element[key] = val;
}
}
}
}
}
|
(function(){
'use strict';
/**
* @ngdoc directive
* @name mdtCell
* @restrict E
* @requires mdtTable
* @requires mdtRow
*
* @description
* Representing a cell which should be placed inside `mdt-row` element directive.
*
* @param {boolean=} htmlContent if set to true, then html content can be placed into the content of the directive.
* @param {string=} editableField if set, then content can be editable.
*
* Available modes are:
*
* - "smallEditDialog" - A simple, one-field edit dialog on click
* - "largeEditDialog" - A complex, flexible edit edit dialog on click
*
* @param {string=} editableFieldTitle if set, then it sets the title of the dialog. (only for `largeEditDialog`)
* @param {number=} editableFieldMaxLength if set, then it sets the maximum length of the field.
*
*
* @example
* <pre>
* <mdt-table>
* <mdt-header-row>
* <mdt-column>Product name</mdt-column>
* <mdt-column>Price</mdt-column>
* <mdt-column>Details</mdt-column>
* </mdt-header-row>
*
* <mdt-row ng-repeat="product in ctrl.products">
* <mdt-cell>{{product.name}}</mdt-cell>
* <mdt-cell>{{product.price}}</mdt-cell>
* <mdt-cell html-content="true">
* <a href="productdetails/{{product.id}}">more details</a>
* </mdt-cell>
* </mdt-row>
* </mdt-table>
* </pre>
*/
function mdtCellDirective($interpolate){
return {
restrict: 'E',
replace: true,
transclude: true,
require: '^mdtRow',
link: function($scope, element, attr, mdtRowCtrl, transclude){
var attributes = {
htmlContent: attr.htmlContent ? attr.htmlContent : false,
editableField: attr.editableField ? attr.editableField : false,
editableFieldTitle: attr.editableFieldTitle ? attr.editableFieldTitle : false,
editableFieldMaxLength: attr.editableFieldMaxLength ? attr.editableFieldMaxLength : false
};
transclude(function (clone) {
if(attr.htmlContent){
mdtRowCtrl.addToRowDataStorage(clone, attributes);
}else{
//TODO: better idea?
var cellValue = $interpolate(clone.html())($scope.$parent);
mdtRowCtrl.addToRowDataStorage(cellValue, attributes);
}
});
}
};
}
angular
.module('mdDataTable')
.directive('mdtCell', mdtCellDirective);
}());
|
var util = require("util");
var request = require("request");
var BaseTrigger = require("./baseTrigger.js").BaseTrigger;
var TinyCache = require( "tinycache" );
var cache1 = new TinyCache();
var cache2 = new TinyCache();
/*
Trigger that automatically looks up users on reddit when they join.
options:
cacheJoinedTime - If the user joined the chat previously within this many ms, trigger will not fire. Defaults to 1 hour.
cacheDataTime - data will be cached for this long to reduce wait for obtaining data. Defaults to 1 hour.
*/
var RedditOnJoinTrigger = function() {
RedditOnJoinTrigger.super_.apply(this, arguments);
};
util.inherits(RedditOnJoinTrigger, BaseTrigger);
var type = "RedditOnJoinTrigger";
exports.triggerType = type;
exports.create = function(name, chatBot, options) {
var trigger = new RedditOnJoinTrigger(type, name, chatBot, options);
trigger.respectsMute = false;
trigger.options.cacheJoinedTime = trigger.options.cacheTime || 1 * 60 * 60 * 1000;
trigger.options.cacheDataTime = trigger.options.cacheTime || 1 * 60 * 60 * 1000;
trigger.allowMessageTriggerAfterResponse = true;
return trigger;
};
RedditOnJoinTrigger.prototype._respondToEnteredMessage = function(roomId, userId) {
if(cache1.get(userId)===null) {
cache1.put(userId,"sent",this.options.cacheJoinedTime);
return this._respond(roomId,userId);
} else {
return false;
}
}
RedditOnJoinTrigger.prototype._respond = function(roomId,userToCheck) {
if(!this.options.redditapiurl) {
this.winston.error(this.chatBot.name+"/"+this.name+": Reddit API Url not defined! Cannot look up user!");
return false;
}
var steamid = ""+userToCheck+"";
if (steamid) {
var that = this;
var cachedResult=cache2.get(steamid);
if(cachedResult===null) {
that.winston.info(that.chatBot.name+"/"+that.name+": Checking reddit for " + steamid);
request.get({method:"GET",encoding:"utf8",uri:that.options.redditapiurl+"steamid/"+steamid,json:true,followAllRedirects:true}, function(error, response, body) {
if (error) {
try { that.winston.warn(that.chatBot.name+"/"+that.name+": Code " + response.statusCode + " from redditapi for steamid " + steamid); } catch (err) { that.winston.error(that.chatBot.name+"/"+that.name,err.stack) }
return;
}
var redditinfo = body;
redditinfo.steamid = redditinfo.steamid.replace("https://steamcommunity.com/profiles/","");
var result = that._getParsedResultForJoin(redditinfo, steamid);
if (result) {
that._sendMessageAfterDelay(roomId, result);
cache2.put(steamid,result,that.options.cacheDataTime);
}
});
} else {
that._sendMessageAfterDelay(toId, cachedResult);
}
return true;
}
return false;
}
RedditOnJoinTrigger.prototype._displayName = function(steamid) {
if(this.chatBot.steamFriends.personaStates && steamid in this.chatBot.steamFriends.personaStates) {
return this.chatBot.steamFriends.personaStates[steamid].player_name + "/"+steamid;
} else {
return steamid;
}
}
RedditOnJoinTrigger.prototype._getParsedResultForJoin = function(redditinput, steamid) {
if (redditinput && redditinput.success) {
var message="";
if(redditinput.success && redditinput.banstatus) {
message = this._displayName(steamid)
+ " has been BANNED from /r/SGS."
+ (redditinput.reddit ? ("\nReddit profile: https://www.reddit.com/user/"+redditinput.reddit) : "")
+ "\nSteam Profile: https://steamcommunity.com/profiles/"+steamid
+ "\nSteamrep: https://steamrep.com/profiles/" + steamid
+ (redditinput.banreason ? ("\nReddit Ban Reason: " + redditinput.banreason) : "");
} else if(redditinput.success && redditinput.flair && redditinput.flair.substr(0,3) === "mod") {
message = "Welcome, " + this._displayName(steamid)
+ " AKA /u/" + redditinput.reddit
+ ", moderator(?) of /r/SGS! Your (raw) flair is " + redditinput.flair;
} else if(redditinput.success) {
var flair = ". Your current flair level is ";
if(redditinput.flair==="tier0") { flair+= "White, with no recorded trades in /r/SGS.";
} else if(redditinput.flair==="tier1") { flair+= "Gray, with 1+ SGS trades.";
} else if(redditinput.flair==="tier2") { flair+= "Blue, with 5+ SGS trades.";
} else if(redditinput.flair==="tier3") { flair+= "Red, with 10+ SGS trades.";
} else if(redditinput.flair==="tier4") { flair+= "Green, with 20+ SGS trades.";
} else if(redditinput.flair==="tier5") { flair+= "Purple, with 50+ SGS trades.";
} else if(redditinput.flair==="white") { flair+= "White, with no recorded trades in /r/SGS.";
} else if(redditinput.flair==="gray") { flair+= "Gray, with 1+ SGS trades.";
} else if(redditinput.flair==="blue") { flair+= "Blue, with 5+ SGS trades.";
} else if(redditinput.flair==="red") { flair+= "Red, with 10+ SGS trades.";
} else if(redditinput.flair==="green") { flair+= "Green, with 20+ SGS trades.";
} else if(redditinput.flair==="purple") { flair+= "Purple, with 50+ SGS trades.";
} else { flair += "not a level I understand. The raw data I got was '"+redditinput.flair+"'."; }
message = "Welcome, " + this._displayName(steamid)
+ " AKA /u/" + redditinput.reddit + flair;
}
return message;
}
return null;
}
|
import {} from 'moogose';
|
/**
* api 接口请求
*/
C.api = function(url,get,post,callback,errorback){
//gost_loading.show();
if(post!=null){
var geturl = '';
for(var p in get){
geturl += p+'='+get[p]+'&';
}
url += '?' + geturl.substring(0,geturl.length-1);//去掉末尾的 & 字符
C.ajax.post(url,post,function(err,DATA){
if(err){
return errorback?errorback():0;
}
dealBackData(DATA,callback,errorback);
},'html');
}else{ //没有post参数
C.ajax.get(url,get,function(err,DATA){
if(err){
return errorback?errorback():0;
}
dealBackData(DATA,callback,errorback);
},'html');
}
//处理接口返回的数据
function dealBackData(DATA,callback,errorback){
eval(' var JsonOb = '+DATA+';');
//{"code":"","msg":"","data":[]}
if(JsonOb.code==200){
callback?callback(JsonOb):0;//正常状态调用回调
}else{
errorback?errorback(JsonOb):0; //错误处理
}
}
};
|
'use strict';
/* eslint-disable global-require */
require('../bin/pixi');
describe('PIXI', function ()
{
it('should exist as a global object', function ()
{
expect(PIXI).to.be.an('object');
});
require('./core');
require('./interaction');
});
|
'use babel';
import CallStackEntry from './call-stack-entry';
import {DELIMITER, ASSIGN_SYMBOL} from '../messaging/message-utils';
export default function callStackFromString(string) {
const callStack = [];
if (string) {
const splitted = string.split(DELIMITER);
for (const elem of splitted) {
const innerSplitted = elem.split(ASSIGN_SYMBOL);
const entry = new CallStackEntry(innerSplitted[0], innerSplitted[1]);
callStack.unshift(entry);
}
}
return callStack;
}
|
var gulp = require('gulp'),
jshintStylish = require('jshint-stylish'),
gutil = require('gulp-util'),// Currently unused, but gulp strongly suggested I install...
jshint = require('gulp-jshint'),
jsHintOptions = {
"trailing": true,
"nonbsp": true,
"noarg": true,
"latedef": true,
"sub": true,
"smarttabs": true,
"evil": true,
"esnext": true,
"node": true,
"eqeqeq": false,
"globals": {
"fs": false,
"Config": false,
"ResourceMonitor": false,
"toId": false,
"toUserid": false,
"toName": false,
"sanitize": false,
"string": false,
"clampIntRange": false,
"LoginServer": false,
"Users": false,
"Rooms": false,
"Verifier": false,
"CommandParser": false,
"Simulator": false,
"Tournaments": false,
"Dnsbl": false,
"Cidr": false,
"Sockets": false,
"Tools": false,
"TeamValidator": false
}
};
gulp.task('lint', function() {
var directories = ['./*.js', './data/*.js', './mods/*.js', './config/*.js'];
console.log("\n\n*** Linting JavaScript Files ***\n\n");
gulp.src(directories)
.pipe(jshint(jsHintOptions))
.pipe(jshint.reporter(jshintStylish));
});
gulp.task('default', ['lint']);
|
'use strict';
import Model from './lib/Model';
export default Model;
|
const {
Container,
Help,
commands
} = require('../../index.js');
const Commit = require('./commit');
const Fetch = require('./fetch');
const Pull = require('./pull');
const Remote = require('./remote');
const Submodule = require('./submodule');
class Git extends Container {}
Git.define({
title: 'git',
help: 'the simple content tracker',
commands: {
'?': 'help',
help: Help,
commit: Commit,
fetch: Fetch,
pull: Pull,
remote: Remote,
submodule: Submodule,
version: commands.Version
},
logo: true
});
module.exports = Git;
|
'use strict'
var test = require('tape')
var util = require('util')
var redeyed = require('..')
function inspect(obj) {
return util.inspect(obj, false, 5, true)
}
test('adding custom asserts ... ', function(t) {
t.constructor.prototype.assertSurrounds = function(code, opts, expected) {
var result = redeyed(code, opts).code
this.equals(result, expected, inspect(code) + ' => ' + inspect(expected))
return this
}
t.end()
})
test('\nbefore/after config, keywords', function(t) {
var opts001 = { Keyword: { _default: { _before: '*', _after: '&' } } }
t.test('\n# ' + inspect(opts001), function(t) {
t.assertSurrounds('this', opts001, '*this&')
t.assertSurrounds('if (a == 1) return', opts001, '*if& (a == 1) *return&')
t.assertSurrounds('var n = new Test();', opts001, '*var& n = *new& Test();')
t.end()
})
var opts002 = {
Keyword: {
'function': { _before: '^' }
, 'return': { _before: '(', _after: ')' }
, _default: { _before: '*', _after: '&' }
}
}
t.test('\n# ' + inspect(opts002), function(t) {
t.assertSurrounds(
[ 'function foo (bar) {'
, ' var a = 3;'
, ' return bar + a;'
, '}'
].join('\n')
, opts002
, [ '^function& foo (bar) {'
, ' *var& a = 3;'
, ' (return) bar + a;'
, '}'
].join('\n'))
t.end()
})
t.end()
})
|
var assert = require("assert");
var Lib = require("./../ramda");
describe("contains", function() {
var contains = Lib.contains;
it("returns true if an element is in a list", function() {
assert.equal(contains(7, [1,2,3,9,8,7,100,200,300]), true);
});
it("returns false if an element is not in a list", function() {
assert.equal(contains(99, [1,2,3,9,8,7,100,200,300]), false);
});
it("returns false for the empty list", function() {
assert.equal(contains(1, []), false);
});
});
describe('uniq', function() {
var uniq = Lib.uniq;
it('returns a set from any array (i.e. purges duplicate elements)', function() {
var arr = [1,2,3,1,2,3,1,2,3];
assert.deepEqual(uniq(arr), [1,2,3]);
});
it('returns an empty array for an empty array', function() {
assert.deepEqual(uniq([]), []);
});
});
describe('isSet', function() {
var isSet = Lib.isSet;
it('returns true if a list is composed of unique elements', function() {
var arr = [1,2,3,1,2,3,1,2,3];
assert.equal(isSet(arr), false);
assert.equal(isSet([3,1,4,2,5,7,9]), true);
});
it('returns true for an empty array', function() {
assert.equal(isSet([]), true);
});
});
|
var browserSync = require('browser-sync'),
changed = require('gulp-changed'),
config = {},
gulp = require('gulp');
config.server = require('./../../config/server');
config.path = require('./../../config/path');
gulp.task('pages', function () {
var result = gulp.src(config.path.views.src)
.pipe(changed(config.path.views.dist))
.pipe(gulp.dest(config.path.views.dist));
if (config.server.enabled === true) {
result.pipe(browserSync.reload({stream: true}));
}
});
|
/**
* node-compress-commons
*
* Copyright (c) 2014 Chris Talkington, contributors.
* Licensed under the MIT license.
* https://github.com/archiverjs/node-compress-commons/blob/master/LICENSE-MIT
*/
var Stream = require('stream').Stream;
var PassThrough = require('readable-stream').PassThrough;
var util = module.exports = {};
util.isStream = function(source) {
return source instanceof Stream;
};
util.normalizeInputSource = function(source) {
if (source === null) {
return Buffer.alloc(0);
} else if (typeof source === 'string') {
return Buffer.from(source);
} else if (util.isStream(source) && !source._readableState) {
var normalized = new PassThrough();
source.pipe(normalized);
return normalized;
}
return source;
};
|
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* @name: S12.11_A3_T2;
* @section: 12.11;
* @assertion: Syntax constructions of switch statement;
* @description: Checking if execution of "switch {}" fails;
* @negative;
*/
function SwitchTest(value){
var result = 0;
switch {
case 0:
result += 2;
default:
result += 32;
break;
}
return result;
}
var x = SwitchTest(0);
|
function BlockSet(blockType) {
this.blocks = new Array();
this.blockType = blockType;
this.currIndex = 0;
this.useHotKeys = true;
// HACK: get focus onto something on the page so we can use keyboard shortcuts
var dummy = createElement("a");
insertBefore(dummy, document.body.firstChild);
dummy.focus();
this.addAllBlocks(document.body);
this.setCurrIndex(this.currIndex);
}
var CLASS = BlockSet.prototype;
CLASS.currBlock = function() { return this.blocks[this.currIndex]; }
CLASS.addBlock = function(block, refBlock) {
// Insert block after refBlock
if(!block) return;
var i = refBlock ? indexOf(this.blocks, refBlock) : -1;
if(i == -1)
add(this.blocks, block);
else
this.blocks.splice(i+1, 0, block);
return block;
}
CLASS.findBlock = function(name) {
for(var i = 0; i < this.blocks.length; i++)
if(this.blocks[i].name == name) return this.blocks[i];
return null;
}
CLASS.getBlock = function(type, recycle, block) {
if(!type) type = "unknown";
// If recycle, return the block of the given type
// If such block doesn't exist, create it
if(recycle) {
// Find existing one
for(var i = 0; i < this.blocks.length; i++)
if(this.blocks[i].type == type)
return this.blocks[i];
}
// Create a new one
for(var q = 0; ; q++) {
var name = type+(q?q:"");
if(!this.findBlock(name)) {
if(!block) block = lastInArray(this.blocks);
var blockDiv = this.createBlockDivAfter(type, name, block);
return this.addBlock(new this.blockType(this, blockDiv), block);
}
}
}
CLASS.createBlockDivAfter = function(type, name, block) {
// Create a block div after the given block's
var blockDiv = createDiv();
blockDiv.setAttribute("id", name+".block");
blockDiv.setAttribute("type", type);
insertManyAfter([createElement("p"), blockDiv], block.blockDiv);
return blockDiv;
}
CLASS.addAllBlocks = function(node) {
// Find all the blocks under node
for(var childNode = node.firstChild; childNode; childNode = childNode.nextSibling) {
if(!Block.isBlock(childNode)) continue;
var block = new this.blockType(this, childNode);
block.prepare();
this.addBlock(block);
}
}
CLASS.setCurrIndex = function(newIndex) {
//alert(newIndex + " " + this.currIndex + " " + this.blocks.length);
if(newIndex < 0 || newIndex >= this.blocks.length) return;
this.blocks[this.currIndex].setSelected(false);
this.blocks[newIndex].setSelected(true);
this.currIndex = newIndex;
}
// View the beginning of the current block
CLASS.viewBeginCurrBlock = function() {
keepCtrlInView(this.currBlock().blockDiv, 0);
}
CLASS.setCurrBlock = function(block) {
for(var i = 0; i < this.blocks.length; i++)
if(this.blocks[i] == block) { this.setCurrIndex(i); return; }
}
CLASS.removeCurrBlock = function() {
this.removeBlock(this.currBlock());
}
CLASS.removeBlock = function(block) {
if(!block) return;
block.die();
var index = indexOf(this.blocks, block);
this.blocks = removeAt(this.blocks, index);
this.currIndex = min(this.blocks.length-1, this.currIndex);
this.setCurrIndex(this.currIndex);
}
CLASS.onKeyPress = function(event) {
if(!this.useHotKeys) return false;
var hotkey = eventToHotkey(event);
if(hotkey == "ctrl-f") { this.setCurrIndex(this.currIndex+1); return true; }
else if(hotkey == "ctrl-b") { this.setCurrIndex(this.currIndex-1); return true; }
else if(hotkey == "ctrl-shift-d") { this.removeCurrBlock(); return true; }
else if(this.currBlock()) {
return this.currBlock().onKeyPress(event); // Dispatch to current block
}
this.viewBeginCurrBlock();
}
|
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
import _extends from "@babel/runtime/helpers/esm/extends";
import * as React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import { unstable_composeClasses as composeClasses } from '@material-ui/unstyled';
import experimentalStyled from '../styles/experimentalStyled';
import useThemeProps from '../styles/useThemeProps';
import AddIcon from '../internal/svg-icons/Add';
import speedDialIconClasses, { getSpeedDialIconUtilityClass } from './speedDialIconClasses';
import { jsx as _jsx } from "react/jsx-runtime";
import { jsxs as _jsxs } from "react/jsx-runtime";
const useUtilityClasses = styleProps => {
const {
classes,
open,
openIcon
} = styleProps;
const slots = {
root: ['root'],
icon: ['icon', open && 'iconOpen', openIcon && open && 'iconWithOpenIconOpen'],
openIcon: ['openIcon', open && 'openIconOpen']
};
return composeClasses(slots, getSpeedDialIconUtilityClass, classes);
};
const SpeedDialIconRoot = experimentalStyled('span', {
name: 'MuiSpeedDialIcon',
slot: 'Root',
overridesResolver: (props, styles) => {
const {
styleProps
} = props;
return _extends({
[`& .${speedDialIconClasses.icon}`]: _extends({}, styles.icon, styleProps.open && styles.iconOpen, styleProps.open && styleProps.openIcon && styles.iconWithOpenIconOpen),
[`& .${speedDialIconClasses.openIcon}`]: _extends({}, styles.openIcon, styleProps.open && styles.openIconOpen)
}, styles.root);
}
})(({
theme,
styleProps
}) => ({
height: 24,
[`& .${speedDialIconClasses.icon}`]: _extends({
transition: theme.transitions.create(['transform', 'opacity'], {
duration: theme.transitions.duration.short
})
}, styleProps.open && _extends({
transform: 'rotate(45deg)'
}, styleProps.openIcon && {
opacity: 0
})),
[`& .${speedDialIconClasses.openIcon}`]: _extends({
position: 'absolute',
transition: theme.transitions.create(['transform', 'opacity'], {
duration: theme.transitions.duration.short
}),
opacity: 0,
transform: 'rotate(-45deg)'
}, styleProps.open && {
transform: 'rotate(0deg)',
opacity: 1
})
}));
const SpeedDialIcon = /*#__PURE__*/React.forwardRef(function SpeedDialIcon(inProps, ref) {
const props = useThemeProps({
props: inProps,
name: 'MuiSpeedDialIcon'
});
const {
className,
icon: iconProp,
openIcon: openIconProp
} = props,
other = _objectWithoutPropertiesLoose(props, ["className", "icon", "open", "openIcon"]);
const styleProps = _extends({}, props);
const classes = useUtilityClasses(styleProps);
function formatIcon(icon, newClassName) {
if ( /*#__PURE__*/React.isValidElement(icon)) {
return /*#__PURE__*/React.cloneElement(icon, {
className: newClassName
});
}
return icon;
}
return /*#__PURE__*/_jsxs(SpeedDialIconRoot, _extends({
className: clsx(classes.root, className),
ref: ref,
styleProps: styleProps
}, other, {
children: [openIconProp ? formatIcon(openIconProp, classes.openIcon) : null, iconProp ? formatIcon(iconProp, classes.icon) : /*#__PURE__*/_jsx(AddIcon, {
className: classes.icon
})]
}));
});
process.env.NODE_ENV !== "production" ? SpeedDialIcon.propTypes
/* remove-proptypes */
= {
// ----------------------------- Warning --------------------------------
// | These PropTypes are generated from the TypeScript type definitions |
// | To update them edit the d.ts file and run "yarn proptypes" |
// ----------------------------------------------------------------------
/**
* Override or extend the styles applied to the component.
*/
classes: PropTypes.object,
/**
* @ignore
*/
className: PropTypes.string,
/**
* The icon to display.
*/
icon: PropTypes.node,
/**
* @ignore
* If `true`, the component is shown.
*/
open: PropTypes.bool,
/**
* The icon to display in the SpeedDial Floating Action Button when the SpeedDial is open.
*/
openIcon: PropTypes.node,
/**
* The system prop that allows defining system overrides as well as additional CSS styles.
*/
sx: PropTypes.object
} : void 0;
SpeedDialIcon.muiName = 'SpeedDialIcon';
export default SpeedDialIcon;
|
/* friendlyDateRanges.js tests */
var test = require('tape'),
friendly = require('../friendlyDateRanges');
test('tests', function (t) {
t.deepEqual(friendly(['2022-09-05', '2023-09-04']), ['September 5th, 2022','September 4th, 2023']);
t.deepEqual(friendly(['2017-01-01', '2017-01-01']), ['January 1st, 2017'], 'since we do not duplicate only return once');
t.deepEqual(friendly(['2016-03-01', '2016-05-05']), ['March 1st','May 5th, 2016']);
t.deepEqual(friendly(['2015-12-01', '2017-02-03']), ['December 1st, 2015','February 3rd, 2017']);
t.deepEqual(friendly(['2015-12-01', '2016-02-03']), ['December 1st','February 3rd'], 'one month apart can be inferred it is the next year');
t.deepEqual(friendly(['2015-07-01', '2015-07-04']), ['July 1st','4th'], 'ending month should be omitted since it is already mentioned');
t.end();
});
|
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* @name: S11.12_A4_T2;
* @section: 11.12;
* @assertion: If ToBoolean(x) is true, return y;
* @description: Type(y) and Type(z) are number primitives;
*/
//CHECK#1
if ((1 ? 0 : 1) !== 0) {
$ERROR('#1: (1 ? 0 : 1) === 0');
}
//CHECK#2
var y = new Number(1);
if ((1 ? y : 0) !== y) {
$ERROR('#2: (var y = new Number(1); (1 ? y : 0) === y');
}
//CHECK#3
var y = new Number(NaN);
if ((y ? y : 1) !== y) {
$ERROR('#3: (var y = new Number(NaN); (y ? y : 1) === y');
}
|
const webpack = require('webpack');
const loaders = require("./helpers/webpack.loaders.config");
const preloaders = require("./helpers/webpack.preloaders.config");
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
module.exports = {
entry: ['./src/app/app.module.js'],
output: {
filename: 'build.js',
path: './dist'
},
resolve: {
root: __dirname,
extensions: ['', '.js', '.json']
},
resolveLoader: {
modulesDirectories: ["node_modules"]
},
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html',
inject: 'body',
hash: true
}),
new CopyWebpackPlugin([{
from: './src/assets/img/',
to: 'assets/img/'
}])
],
module:{
preloaders: preloaders,
loaders: loaders
}
};
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.checkWineVersion = undefined;
var _bluebirdLst;
function _load_bluebirdLst() {
return _bluebirdLst = require("bluebird-lst");
}
/** @private */
let checkWineVersion = exports.checkWineVersion = (() => {
var _ref2 = (0, (_bluebirdLst || _load_bluebirdLst()).coroutine)(function* (checkPromise) {
function wineError(prefix) {
return `${prefix}, please see https://electron.build/multi-platform-build#${process.platform === "linux" ? "linux" : "macos"}`;
}
let wineVersion;
try {
wineVersion = (yield checkPromise).trim();
} catch (e) {
if (e.code === "ENOENT") {
throw new Error(wineError("wine is required"));
} else {
throw new Error(`Cannot check wine version: ${e}`);
}
}
if (wineVersion.startsWith("wine-")) {
wineVersion = wineVersion.substring("wine-".length);
}
const spaceIndex = wineVersion.indexOf(" ");
if (spaceIndex > 0) {
wineVersion = wineVersion.substring(0, spaceIndex);
}
const suffixIndex = wineVersion.indexOf("-");
if (suffixIndex > 0) {
wineVersion = wineVersion.substring(0, suffixIndex);
}
if (wineVersion.split(".").length === 2) {
wineVersion += ".0";
}
if ((_semver || _load_semver()).lt(wineVersion, "1.8.0")) {
throw new Error(wineError(`wine 1.8+ is required, but your version is ${wineVersion}`));
}
});
return function checkWineVersion(_x2) {
return _ref2.apply(this, arguments);
};
})();
//# sourceMappingURL=wine.js.map
exports.execWine = execWine;
exports.prepareWindowsExecutableArgs = prepareWindowsExecutableArgs;
var _lazyVal;
function _load_lazyVal() {
return _lazyVal = require("lazy-val");
}
var _path = _interopRequireWildcard(require("path"));
var _semver;
function _load_semver() {
return _semver = _interopRequireWildcard(require("semver"));
}
var _binDownload;
function _load_binDownload() {
return _binDownload = require("./binDownload");
}
var _bundledTool;
function _load_bundledTool() {
return _bundledTool = require("./bundledTool");
}
var _macosVersion;
function _load_macosVersion() {
return _macosVersion = require("./macosVersion");
}
var _util;
function _load_util() {
return _util = require("./util");
}
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
const wineExecutable = new (_lazyVal || _load_lazyVal()).Lazy((0, (_bluebirdLst || _load_bluebirdLst()).coroutine)(function* () {
const isUseSystemWine = (0, (_util || _load_util()).isEnvTrue)(process.env.USE_SYSTEM_WINE);
if (isUseSystemWine) {
(0, (_util || _load_util()).debug)("Using system wine is forced");
} else if (process.platform === "darwin") {
const osVersion = yield (0, (_macosVersion || _load_macosVersion()).getMacOsVersion)();
let version = null;
let checksum = null;
if ((_semver || _load_semver()).gte(osVersion, "10.13.0")) {
version = "2.0.2-mac-10.13";
// noinspection SpellCheckingInspection
checksum = "v6r9RSQBAbfvpVQNrEj48X8Cw1181rEGMRatGxSKY5p+7khzzy/0tOdfHGO8cU+GqYvH43FAKMK8p6vUfCqSSA==";
} else if ((_semver || _load_semver()).gte(osVersion, "10.12.0")) {
version = "2.0.1-mac-10.12";
// noinspection SpellCheckingInspection
checksum = "IvKwDml/Ob0vKfYVxcu92wxUzHu8lTQSjjb8OlCTQ6bdNpVkqw17OM14TPpzGMIgSxfVIrQZhZdCwpkxLyG3mg==";
}
if (version != null) {
const wineDir = yield (0, (_binDownload || _load_binDownload()).getBinFromGithub)("wine", version, checksum);
return {
path: _path.join(wineDir, "bin/wine"),
env: Object.assign({}, process.env, { WINEDEBUG: "-all,err+all", WINEDLLOVERRIDES: "winemenubuilder.exe=d", WINEPREFIX: _path.join(wineDir, "wine-home"), DYLD_FALLBACK_LIBRARY_PATH: (0, (_bundledTool || _load_bundledTool()).computeEnv)(process.env.DYLD_FALLBACK_LIBRARY_PATH, [_path.join(wineDir, "lib")]) })
};
}
}
yield checkWineVersion((0, (_util || _load_util()).exec)("wine", ["--version"]));
return { path: "wine" };
}));
/** @private */
function execWine(file, args) {
let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : (_bundledTool || _load_bundledTool()).EXEC_TIMEOUT;
if (process.platform === "win32") {
return (0, (_util || _load_util()).exec)(file, args, options);
} else {
return wineExecutable.value.then(wine => (0, (_util || _load_util()).exec)(wine.path, [file].concat(args), wine.env == null ? options : Object.assign({ env: wine.env }, options)));
}
}
/** @private */
function prepareWindowsExecutableArgs(args, exePath) {
if (process.platform !== "win32") {
args.unshift(exePath);
}
return args;
}
|
/*
* Preloader state
* ===============
*
* Takes care of loading the main game assets, including graphics and sound
* effects, while displaying a busy splash screen.
*/
import assets from '../assets';
export default class Preloader extends Phaser.State {
preload() {
this.showSplashScreen();
this.load.pack('game', null, assets);
}
create() {
// Here is a good place to initialize plugins dependent of any game asset.
// Don't forget to `import` them first. Example:
//this.game.myPlugin = this.plugins.add(MyPlugin/*, ... parameters ... */);
this.state.start('Game');
}
// --------------------------------------------------------------------------
showSplashScreen() {
this.add.image(0, 0, 'splash-screen');
this.load.setPreloadSprite(this.add.image(82, 282, 'progress-bar'));
}
}
|
var deepEquals = require("assert").deepEqual,
CSSwhat = require("../");
var tests = [
["div", [ [ { type: 'tag', name: 'div' } ] ], "simple tag"],
["*", [ [ { type: 'universal' } ] ], "universal"],
//traversal
["div div", [ [ { type: 'tag', name: 'div' },
{ type: 'descendant' },
{ type: 'tag', name: 'div' } ] ], "descendant"],
["div\t \n \tdiv", [ [ { type: 'tag', name: 'div' },
{ type: 'descendant' },
{ type: 'tag', name: 'div' } ] ], "descendant /w whitespace"],
["div + div", [ [ { type: 'tag', name: 'div' },
{ type: 'adjacent' },
{ type: 'tag', name: 'div' } ] ], "adjacent"],
["div ~ div", [ [ { type: 'tag', name: 'div' },
{ type: 'sibling' },
{ type: 'tag', name: 'div' } ] ], "sibling"],
//attributes
[".foo", [ [ { type: 'class', value: 'foo' } ] ], "simple class"],
["[name^='foo[']",[[{"type":"attribute","name":"name","action":"start","value":"foo[","ignoreCase":false}]],"escaped attribute"],
["[name^='foo[bar]']",[[{"type":"attribute","name":"name","action":"start","value":"foo[bar]","ignoreCase":false}]],"escaped attribute"],
["[name$='[bar]']",[[{"type":"attribute","name":"name","action":"end","value":"[bar]","ignoreCase":false}]],"escaped attribute"],
["[href *= 'google']",[[{"type":"attribute","name":"href","action":"any","value":"google","ignoreCase":false}]],"escaped attribute"],
["[name=foo\\.baz]",[[{"type":"attribute","name":"name","action":"equals","value":"foo.baz","ignoreCase":false}]],"escaped attribute"],
["[name=foo\\[bar\\]]",[[{"type":"attribute","name":"name","action":"equals","value":"foo[bar]","ignoreCase":false}]],"escaped attribute"],
["[xml\\:test]",[[{"type":"attribute","name":"xml:test","action":"exists","value":"","ignoreCase":false}]],"escaped attribute"]
//TODO
];
tests.forEach(function(arr){
arr[0] = CSSwhat(arr[0]);
deepEquals.apply(null, arr);
console.log(arr[2], "passed");
});
|
'use strict';
const app = require('APP')
, debug = require('debug')(`${app.name}:oauth`)
, {STRING, JSON} = require('sequelize');
module.exports = db => {
const OAuth = db.define('oauths', {
uid: STRING,
provider: STRING,
// OAuth v2 fields
accessToken: STRING,
refreshToken: STRING,
// OAuth v1 fields
token: STRING,
tokenSecret: STRING,
// The whole profile as JSON
profileJson: JSON,
}, {
// Further reading on indexes:
// 1. Sequelize and indexes: http://docs.sequelizejs.com/en/2.0/docs/models-definition/#indexes
// 2. Postgres documentation: https://www.postgresql.org/docs/9.1/static/indexes.html
indexes: [{fields: ['uid'], unique: true}],
});
// OAuth.V2 is a default argument for the OAuth.setupStrategy method - it's our callback function that will execute when the user has successfully logged in
OAuth.V2 = (accessToken, refreshToken, profile, done) =>
OAuth.findOrCreate({
where: {
provider: profile.provider,
uid: profile.id,
}
})
.spread(oauth => {
debug(profile);
debug('provider:%s will log in user:{name=%s uid=%s}',
profile.provider,
profile.displayName,
profile.id
);
oauth.profileJson = profile;
oauth.accessToken = accessToken;
// db.Promise.props is a Bluebird.js method; basically like "all" but for an object whose properties might contain promises.
// Docs: http://bluebirdjs.com/docs/api/promise.props.html
return db.Promise.props({
oauth,
user: oauth.getUser(),
_saveProfile: oauth.save(),
});
})
.then(({ oauth, user }) => user ||
OAuth.User.create({
name: profile.displayName,
})
.then(user => db.Promise.props({
user,
_setOauthUser: oauth.setUser(user)
}))
.then(({user}) => user)
)
.then(user => done(null, user))
.catch(done);
// setupStrategy is a wrapper around passport.use, and is called in authentication routes in server/auth.js
OAuth.setupStrategy =
({
provider,
strategy,
config,
oauth = OAuth.V2,
passport
}) => {
const undefinedKeys = Object.keys(config)
.map(k => config[k])
.filter(value => typeof value === 'undefined');
if (undefinedKeys.length) {
for (const key in config) {
if (!config[key]) debug('provider:%s: needs environment var %s', provider, key);
}
debug('provider:%s will not initialize', provider);
return;
}
debug('initializing provider:%s', provider);
passport.use(new strategy(config, oauth));
};
return OAuth;
};
module.exports.associations = (OAuth, {User}) => {
// Create a static association between the OAuth and User models.
// This lets us refer to OAuth.User above, when we need to create
// a user.
OAuth.User = User;
OAuth.belongsTo(User);
};
|
version https://git-lfs.github.com/spec/v1
oid sha256:0b9064d20bf15213644250009c06870ba3f05cf808535299aa3262698753a950
size 1301
|
'use strict';
const assert = require('./../../assert');
const common = require('./../../common');
let battle;
describe('Grassy Terrain', function () {
afterEach(function () {
battle.destroy();
});
it('should change the current terrain to Grassy Terrain for five turns', function () {
battle = common.createBattle();
battle.setPlayer('p1', {team: [{species: "Florges", ability: 'symbiosis', moves: ['mist', 'grassyterrain']}]});
battle.setPlayer('p2', {team: [{species: "Florges", ability: 'symbiosis', moves: ['mist']}]});
battle.makeChoices('move grassyterrain', 'move mist');
assert.ok(battle.field.isTerrain('grassyterrain'));
battle.makeChoices('move mist', 'move mist');
assert.ok(battle.field.isTerrain('grassyterrain'));
battle.makeChoices('move mist', 'move mist');
assert.ok(battle.field.isTerrain('grassyterrain'));
battle.makeChoices('move mist', 'move mist');
assert.ok(battle.field.isTerrain('grassyterrain'));
battle.makeChoices('move mist', 'move mist');
assert.ok(battle.field.isTerrain(''));
});
it('should halve the base power of Earthquake, Bulldoze, Magnitude', function () {
battle = common.createBattle();
battle.setPlayer('p1', {team: [{species: "Shaymin", ability: 'naturalcure', moves: ['grassyterrain']}]});
battle.setPlayer('p2', {team: [{species: "Shaymin-Sky", ability: 'serenegrace', moves: ['leechseed']}]});
battle.makeChoices('move grassyterrain', 'move leechseed');
assert.strictEqual(battle.runEvent('BasePower', battle.p2.active[0], battle.p1.active[0], Dex.getMove('earthquake'), 100, true), 50);
assert.strictEqual(battle.runEvent('BasePower', battle.p1.active[0], battle.p2.active[0], Dex.getMove('earthquake'), 100, true), 50);
assert.strictEqual(battle.runEvent('BasePower', battle.p2.active[0], battle.p1.active[0], Dex.getMove('bulldoze'), 60, true), 30);
assert.strictEqual(battle.runEvent('BasePower', battle.p1.active[0], battle.p2.active[0], Dex.getMove('bulldoze'), 60, true), 30);
});
it('should increase the base power of Grass-type attacks used by grounded Pokemon', function () {
battle = common.createBattle();
battle.setPlayer('p1', {team: [{species: "Shaymin", ability: 'naturalcure', moves: ['grassyterrain']}]});
battle.setPlayer('p2', {team: [{species: "Shaymin-Sky", ability: 'serenegrace', moves: ['leechseed']}]});
battle.makeChoices('move grassyterrain', 'move leechseed');
let basePower;
let move = Dex.getMove('gigadrain');
basePower = battle.runEvent('BasePower', battle.p1.active[0], battle.p2.active[0], move, move.basePower, true);
assert.strictEqual(basePower, battle.modify(move.basePower, 1.5));
basePower = battle.runEvent('BasePower', battle.p2.active[0], battle.p1.active[0], move, move.basePower, true);
assert.strictEqual(basePower, move.basePower);
});
it('should heal grounded Pokemon by 1/16 of their max HP', function () {
battle = common.createBattle();
battle.setPlayer('p1', {team: [{species: "Shaymin", ability: 'naturalcure', moves: ['grassyterrain', 'dragonrage']}]});
battle.setPlayer('p2', {team: [{species: "Magneton", ability: 'magnetpull', moves: ['magnetrise', 'dragonrage']}]});
battle.makeChoices('move grassyterrain', 'move magnetrise');
battle.makeChoices('move dragonrage', 'move dragonrage');
assert.strictEqual(battle.p1.active[0].hp, battle.p1.active[0].maxhp - 40 + Math.floor(battle.p1.active[0].maxhp / 16));
assert.strictEqual(battle.p2.active[0].hp, battle.p2.active[0].maxhp - 40);
});
it('should not affect Pokemon in a semi-invulnerable state', function () {
battle = common.createBattle();
battle.setPlayer('p1', {team: [{species: "Smeargle", ability: 'owntempo', moves: ['dragonrage', 'skydrop']}]});
battle.setPlayer('p2', {team: [{species: "Sableye", ability: 'prankster', moves: ['dragonrage', 'grassyterrain']}]});
battle.makeChoices('move dragonrage', 'move dragonrage');
battle.makeChoices('move skydrop', 'move grassyterrain');
assert.strictEqual(battle.p1.active[0].hp, battle.p1.active[0].maxhp - 40);
assert.strictEqual(battle.p2.active[0].hp, battle.p2.active[0].maxhp - 40);
});
it('should cause Nature Power to become Energy Ball', function () {
battle = common.createBattle();
battle.setPlayer('p1', {team: [{species: "Whimsicott", ability: 'prankster', moves: ['grassyterrain']}]});
battle.setPlayer('p2', {team: [{species: "Shuckle", ability: 'sturdy', moves: ['naturepower']}]});
battle.makeChoices('move grassyterrain', 'move naturepower');
let resultMove = toID(battle.log[battle.lastMoveLine].split('|')[3]);
assert.strictEqual(resultMove, 'energyball');
});
});
|
/* global console, LAMBDA */
(function() {
"use strict";
var L = LAMBDA;
var question = {};
var RP14part1 = {
init: function() {
var vs = "uvxyz";
var maxDepth = 6;
var minDepth = 4;
// David: all of these helper functions are duplicated in
// RP14part2.js. Because...
// When I moved them to a separate JS file that I loaded (with
// use-require) in both RP14part1.html and RP14part2.html,
// OpenDSA did not like it (error on loading the shared JS file)
function pickRndCharacter(c,s) {
var list = s.split("")
.map(function (e,i) { return (e===c ? i : -1) ; });
list = list.filter(function (x) { return x >= 0; });
return list[L.getRnd(0,list.length-1)];
}
function findMatchingParen(s,index) {
s = s.split("");
var count = 0;
for(var i=index+1; i<s.length; i++) {
if (s[i] === ')') {
if (count === 0) {
return i;
} else {
count--;
}
} else {
if (s[i] === '(') {
count++;
}
}
}
throw new Error("Could not find closing paren for the one " +
"at position " + index + " in " + s);
}
function removeParenPair(s) {
var openParen = pickRndCharacter('(',s);
var closeParen = findMatchingParen(s,openParen);
return s.substring(0,openParen) +
s.substring(openParen+1,closeParen) +
s.substring(closeParen+1);
}
function removeDot(s) {
var dot = pickRndCharacter('.',s);
return s.substring(0,dot) + " " + s.substring(dot+1);
}
function addParens(s) {
var n = s.length;
var closing = n-1;
while (s[closing] === ')') {
closing--;
}
var p1 = L.getRnd(0,closing-1);
var p2 = L.getRnd(closing+1,n-1);
// do not insert in front of a space or a dot
if (s[p1] === " " || s[p1] === ".") {
p1++;
}
// do not insert after a lambda
if (p1>0 && s[p1-1] === "\u03BB" ) {
p1 += 2;
}
return s.substring(0,p1) + "(" +
s.substring(p1,p2) + ")" + s.substring(p2);
}
function getSyntaxError(minDepth,maxDepth,vs) {
var s = L.printExp( L.getRndExp(1,minDepth,maxDepth,vs,""));
var rnd = L.getRnd(1,3);
question.answer = "True";
switch (rnd) {
case 1:
if (s.indexOf('(') !== -1) {
s = removeParenPair(s);
question.answer = "False";
}
// leave s unchanged if it does not contain any parens
break;
case 2:
if (s.indexOf('.') !== -1) {
s = removeDot(s);
question.answer = "False";
}
// leave s unchanged if it does not contain any dot
break;
case 3:
s = addParens(s);
question.answer = "False";
break;
}
return s;
}// getSyntaxError function
if (L.getRnd(0,1) === 0) {
// syntactically correct lambda exp
this.expression =
L.printExp( L.getRndExp(1,minDepth,maxDepth,vs,""));
this.answer = "True";
} else {
this.expression = getSyntaxError(minDepth,maxDepth,vs);
this.answer = question.answer;
}
} //init
};// RP14part1
window.RP14part1 = window.RP14part1 || RP14part1;
}());
|
'use strict';
angular.module('core').directive('featuredProjects', function () {
return {
restrict: 'EA',
templateUrl: 'modules/core/client/directives/views/featured-projects.html',
controller: function ($scope, $http) {
(function getFeaturedProjs() {
$http.get('/api/v1/featured', { cache: true })
.then(function successCallback(resolved) {
$scope.featuredProjects = resolved.data;
}, function errorCallback(rejected) {
return console.log('rejected:\n', rejected);
});
})();
}
};
});
|
'use strict';
var createPluginError, failOnWarningReporter, failReporter, loadReporter, reporter, reporterStream, through2;
through2 = require('through2');
createPluginError = require('./utils').createPluginError;
reporterStream = function(reporterType) {
return through2.obj(function(file, enc, cb) {
var c, ref, rpt;
c = file.coffeelint;
if (!c || (c.errorCount === (ref = c.warningCount) && ref === 0)) {
this.push(file);
return cb();
}
rpt = new reporterType(file.coffeelint.results);
rpt.publish();
this.push(file);
return cb();
});
};
failReporter = function() {
return through2.obj(function(file, enc, cb) {
if (!file.coffeelint || file.coffeelint.success) {
this.push(file);
return cb();
}
this.emit('error', createPluginError("CoffeeLint failed for " + file.relative));
return cb();
});
};
failOnWarningReporter = function() {
return through2.obj(function(file, enc, cb) {
var c, ref;
c = file.coffeelint;
if (!c || (c.errorCount === (ref = c.warningCount) && ref === 0)) {
this.push(file);
return cb();
}
this.emit('error', createPluginError("CoffeeLint failed for " + file.relative));
return cb();
});
};
reporter = function(type) {
if (type === 'fail') {
return failReporter();
}
if (type === 'failOnWarning') {
return failOnWarningReporter();
}
if (type == null) {
type = 'coffeelint-stylish';
}
reporter = loadReporter(type);
if (typeof reporter !== 'function') {
throw createPluginError(type + " is not a valid reporter");
}
return reporterStream(reporter);
};
loadReporter = function(reporter) {
if (typeof reporter === 'function') {
return reporter;
}
if (typeof reporter === 'string') {
try {
return require("coffeelint/lib/reporters/" + reporter);
} catch (undefined) {}
try {
return require(reporter);
} catch (undefined) {}
}
};
module.exports = reporter;
|
// Copyright: 2015 AlignAlytics
// License: "https://github.com/PMSI-AlignAlytics/dimple/blob/master/MIT-LICENSE.txt"
// Source: /src/chart/methods/_handleTransition.js
this._handleTransition = function (input, duration, chart, series) {
var returnShape = null;
if (duration === 0) {
returnShape = input;
} else {
returnShape = input.transition()
.duration(duration)
.delay(chart._getDelay(duration, chart, series));
dimple._ease(returnShape, chart.ease);
}
return returnShape;
};
|
const path = require('path');
const ip = require('ip');
module.exports = app => {
const exports = {};
exports.view = {
cache: false
};
exports.static = {
maxAge: 0 // maxAge 缓存,默认 1 年
};
exports.development = {
watchDirs: [], // 指定监视的目录(包括子目录),当目录下的文件变化的时候自动重载应用,路径从项目根目录开始写
ignoreDirs: ['app/web', 'public', 'config/manifest.json'] // 指定过滤的目录(包括子目录)
};
exports.logview = {
dir: path.join(app.baseDir, 'logs')
};
exports.webpack = {
browser: false,
webpackConfigList: require('easywebpack-vue').getWebpackConfig()
};
const localIP = ip.address();
const domainWhiteList = [];
[7001, 9000, 9001].forEach(port => {
domainWhiteList.push(`http://localhost:${port}`);
domainWhiteList.push(`http://127.0.0.1:${port}`);
domainWhiteList.push(`http://${localIP}:${port}`);
});
exports.security = { domainWhiteList };
return exports;
};
|
/* global React */
/* global ReactQuill */
'use strict';
var Editor = React.createClass({
getInitialState: function() {
return {
theme: 'snow',
enabled: true,
readOnly: false,
value: '<h1>It works!</h1>',
events: []
};
},
formatRange: function(range) {
return range
? [range.start, range.end].join(',')
: 'none';
},
onTextareaChange: function(event) {
var value = event.target.value;
this.setState({ value:value });
},
onEditorChange: function(value, delta, source) {
this.setState({
value: value,
events: [
'text-change('+this.state.value+' -> '+value+')'
].concat(this.state.events)
});
},
onEditorChangeSelection: function(range, source) {
this.setState({
selection: range,
events: [
'selection-change('+
this.formatRange(this.state.selection)
+' -> '+
this.formatRange(range)
+')'
].concat(this.state.events)
});
},
onToggle: function() {
this.setState({ enabled: !this.state.enabled });
},
onToggleReadOnly: function() {
this.setState({ readOnly: !this.state.readOnly });
},
render: function() {
return (
React.DOM.div({},
this.renderToolbar(),
React.DOM.hr(),
this.renderSidebar(),
this.state.enabled && ReactQuill({
theme: this.state.theme,
value: this.state.value,
readOnly: this.state.readOnly,
onChange: this.onEditorChange,
onChangeSelection: this.onEditorChangeSelection
})
)
);
},
renderToolbar: function() {
var state = this.state;
var enabled = state.enabled;
var readOnly = state.readOnly;
var selection = this.formatRange(state.selection);
return (
React.DOM.div({},
React.DOM.button({
onClick: this.onToggle },
enabled? 'Disable' : 'Enable'
),
React.DOM.button({
onClick: this.onToggleReadOnly },
'Set ' + (readOnly? 'read/Write' : 'read-only')
),
React.DOM.button({
disabled: true },
'Selection: ('+selection+')'
)
)
);
},
renderSidebar: function() {
return (
React.DOM.div({
style: { overflow:'hidden', float:'right' }},
React.DOM.textarea({
style: { display:'block', width:300, height:300 },
value: this.state.value,
onChange: this.onTextareaChange
}),
React.DOM.textarea({
style: { display:'block', width:300, height:300 },
value: this.state.events.join('\n')
})
)
);
}
});
Editor = React.createFactory(Editor);
ReactQuill = React.createFactory(ReactQuill);
ReactDOM.render(
Editor(),
document.getElementById('app')
);
|
import React from 'react'
import Icon from 'react-icon-base'
const FaMixcloud = props => (
<Icon viewBox="0 0 40 40" {...props}>
<g><path d="m28.8 23.5q0-1-0.6-1.8t-1.5-1.2q-0.1 0.8-0.4 1.6-0.1 0.4-0.5 0.6t-0.8 0.3q-0.2 0-0.4-0.1-0.5-0.1-0.8-0.6t-0.1-1.1q0.4-1.2 0.4-2.5 0-2.1-1-3.9t-2.9-2.9-4-1.1q-2.4 0-4.3 1.3t-3 3.4q1.9 0.5 3.3 1.8 0.4 0.4 0.4 1t-0.4 0.9-0.9 0.4-1-0.4q-1.3-1.3-3.1-1.3-1.9 0-3.2 1.3t-1.3 3.2 1.3 3.1 3.2 1.3h18.3q1.4 0 2.3-0.9t1-2.4z m2.7 0q0 2.5-1.8 4.3t-4.2 1.7h-18.3q-3 0-5.1-2.1t-2.1-5q0-2.7 1.8-4.7t4.3-2.4q1.1-3.2 3.9-5.2t6.2-2q4.1 0 7.1 2.8t3.5 6.8q2 0.4 3.3 2.1t1.4 3.7z m4.4 0q0 3.1-1.7 5.6-0.4 0.6-1.2 0.6-0.4 0-0.7-0.2-0.5-0.3-0.6-0.9t0.2-1q1.3-1.8 1.3-4.1t-1.3-4q-0.3-0.5-0.2-1t0.6-0.9 1-0.2 0.9 0.6q1.7 2.5 1.7 5.5z m4.4 0q0 4.3-2.3 7.8-0.4 0.6-1.1 0.6-0.4 0-0.8-0.2-0.4-0.4-0.5-0.9t0.2-1q1.9-2.9 1.9-6.3 0-3.4-1.9-6.2-0.3-0.5-0.2-1t0.5-0.9q0.5-0.3 1-0.2t0.9 0.6q2.3 3.5 2.3 7.7z"/></g>
</Icon>
)
export default FaMixcloud
|
module.exports = function() {
return {
files: [
"src/**/*.js",
"spec/testUtil.js",
{
pattern: "spec/**/*.jsx",
instrument: false,
load: false,
ignore: false
}
],
tests: ["spec/**/*.js", "!spec/tests.js", "!spec/testUtil.js"],
env: {
type: "node",
runner: "node"
},
setup: function(wallaby) {
var plugin = require("./src/index");
require("@babel/register")({
presets: ["@babel/preset-react"],
plugins: [plugin],
cache: false
});
}
};
};
|
'use strict';
angular.module('scenarioEditor.manageView', ['ngRoute', 'scenarioServices'])
.config(['$routeProvider', function ($routeProvider) {
$routeProvider.when('/manageView', {
templateUrl: '/scenario/manageView/',
controller: 'manageCtrl'
});
}])
.controller('manageCtrl', ['$scope', '$http', 'triggerService', 'scenarioService', 'charService', function ($scope, $http, triggerService, scenarioService, charService) {
$scope.pendingTrigger = null;
$scope.triggerPending = false;
$scope.fetchTriggers = function () {
triggerService.fetchTriggers();
};
$scope.triggers = function () {
return triggerService.triggers();
};
$scope.dataTypes = function () {
return triggerService.dataTypes();
};
$scope.addTrigger = function () {
$scope.pendingTrigger = new TriggerResource();
$scope.triggerPending = true;
};
$scope.scenario = function () {
return scenarioService.scenario();
};
$scope.scenarioTypes = function(){
return SCENARIO_TYPES;
};
$scope.scenarioOrders = function(){
return SCENARIO_ORDER;
};
$scope.submitTrigger = function () {
if ($scope.pendingTrigger.id == -1) {
for (var i = 0; i < triggerService.triggers().length; i++) {
if ($scope.pendingTrigger.type == triggerService.triggers()[i].type) {
$scope.$emit('showMessage', ['Trigger Name Must Be Unique', 'danger']);
return;
}
}
triggerService.createTrigger($scope.pendingTrigger);
} else {
triggerService.updateTrigger($scope.pendingTrigger);
}
$scope.triggerPending = false;
$scope.pendingTrigger = null;
};
$scope.addArgument = function () {
if ($scope.pendingTrigger != null) {
$scope.pendingTrigger.args.push(new TriggerArgumentResource());
}
};
$scope.deleteTrigger = function (trigger) {
triggerService.deleteTrigger(trigger);
if ($scope.pendingTrigger != null && $scope.pendingTrigger) {
$scope.pendingTrigger = null;
$scope.triggerPending = false;
}
};
$scope.editTrigger = function (trigger) {
$scope.pendingTrigger = trigger;
$scope.triggerPending = true;
};
$scope.getDependsOnOptions = function(arg, trigger){
var options = [];
if(arg.dataType == "CHARACTER_STATE"){
for(var i = 0; i < trigger.args.length; i++){
if(trigger.args[i].dataType == "CHARACTER"){
options.push(trigger.args[i]);
}
}
}
return options;
};
$scope.showDependsOn = function(arg){
return arg.dataType == "CHARACTER_STATE";
}
}]);
|
/**
* fs.watch wrapper that among other things checks SHA1
* of the file to prevent multiple callback calls.
*
* Related: http://stackoverflow.com/q/12978924/1637178
*
* Usage is the same as fs.watch
*
* var onFileChange = require("on-file-change");
*
* // same as fs.watch
* onFileChange("myAwesomeFile.txt", function()
* {
* console.log("Awesome file change!");
* });
*
* @author Jan Święcki <jan.swiecki@gmail.com>
*/
module.exports = (function()
{
var crypto = require("crypto");
var fs = require("fs");
var hashSums = {};
var fileWatchers = {};
var getSha1 = function(string)
{
return crypto.createHash("sha1").update(string).digest("hex");
}
var getSha1FromFile = function(path)
{
if(fs.existsSync(path))
{
return getSha1(fs.readFileSync(path));
}
else
{
// if file is moved/deleted then do nothing
return hashSums[path];
}
}
// actual onFileChange function
return function(path, callback)
{
function hasDifferentHash()
{
var h = getSha1FromFile(path);
if(h !== hashSums[path])
{
hashSums[path] = h;
return true;
}
else
{
return false;
}
}
function init()
{
if(! fs.existsSync(path))
{
console.error("Path "+path+" does not exists");
return false;
}
else
{
hashSums[path] || (hashSums[path] = getSha1FromFile(path));
// Try to prevent many events to fire at the same time.
// When someone is making many almost simultaneous file saves
// then SHA1 is sometimes not calculated properly. It happens
// probably because halfly saved file is being read. In that
// case the only thing we could try to do is to create file lock
// in NodeJS that is included by Operating System while saving file.
// Later I will try to experiment with fs-ext flock
// (https://github.com/baudehlo/node-fs-ext).
var execute = true;
fileWatchers[path] = fs.watch(path, function(event)
{
if(execute === true && event === 'change' && hasDifferentHash())
{
execute = false;
fileWatchers[path].close();
callback(path);
init();
}
});
}
}
if(typeof callback === 'function')
{
if(init() === false)
{
throw new Error("Cannot initialize");
}
return {
"close": fileWatchers[path].close
};
}
else
{
throw new Error("No callback for onFileChange");
}
}
}());
|
// Backbone.BabySitter
// -------------------
// v0.0.5
//
// Copyright (c)2013 Derick Bailey, Muted Solutions, LLC.
// Distributed under MIT license
//
// http://github.com/babysitterjs/backbone.babysitter
// Backbone.ChildViewContainer
// ---------------------------
//
// Provide a container to store, retrieve and
// shut down child views.
define(function(require){return
Backbone.ChildViewContainer = (function(Backbone, _){
// Container Constructor
// ---------------------
var Container = function(initialViews){
this._views = {};
this._indexByModel = {};
this._indexByCollection = {};
this._indexByCustom = {};
this._updateLength();
this._addInitialViews(initialViews);
};
// Container Methods
// -----------------
_.extend(Container.prototype, {
// Add a view to this container. Stores the view
// by `cid` and makes it searchable by the model
// and/or collection of the view. Optionally specify
// a custom key to store an retrieve the view.
add: function(view, customIndex){
var viewCid = view.cid;
// store the view
this._views[viewCid] = view;
// index it by model
if (view.model){
this._indexByModel[view.model.cid] = viewCid;
}
// index it by collection
if (view.collection){
this._indexByCollection[view.collection.cid] = viewCid;
}
// index by custom
if (customIndex){
this._indexByCustom[customIndex] = viewCid;
}
this._updateLength();
},
// Find a view by the model that was attached to
// it. Uses the model's `cid` to find it, and
// retrieves the view by it's `cid` from the result
findByModel: function(model){
var viewCid = this._indexByModel[model.cid];
return this.findByCid(viewCid);
},
// Find a view by the collection that was attached to
// it. Uses the collection's `cid` to find it, and
// retrieves the view by it's `cid` from the result
findByCollection: function(col){
var viewCid = this._indexByCollection[col.cid];
return this.findByCid(viewCid);
},
// Find a view by a custom indexer.
findByCustom: function(index){
var viewCid = this._indexByCustom[index];
return this.findByCid(viewCid);
},
// Find by index. This is not guaranteed to be a
// stable index.
findByIndex: function(index){
return _.values(this._views)[index];
},
// retrieve a view by it's `cid` directly
findByCid: function(cid){
return this._views[cid];
},
// Remove a view
remove: function(view){
var viewCid = view.cid;
// delete model index
if (view.model){
delete this._indexByModel[view.model.cid];
}
// delete collection index
if (view.collection){
delete this._indexByCollection[view.collection.cid];
}
// delete custom index
var cust;
for (var key in this._indexByCustom){
if (this._indexByCustom.hasOwnProperty(key)){
if (this._indexByCustom[key] === viewCid){
cust = key;
break;
}
}
}
if (cust){
delete this._indexByCustom[cust];
}
// remove the view from the container
delete this._views[viewCid];
// update the length
this._updateLength();
},
// Call a method on every view in the container,
// passing parameters to the call method one at a
// time, like `function.call`.
call: function(method, args){
args = Array.prototype.slice.call(arguments, 1);
this.apply(method, args);
},
// Apply a method on every view in the container,
// passing parameters to the call method one at a
// time, like `function.apply`.
apply: function(method, args){
var view;
// fix for IE < 9
args = args || [];
_.each(this._views, function(view, key){
if (_.isFunction(view[method])){
view[method].apply(view, args);
}
});
},
// Update the `.length` attribute on this container
_updateLength: function(){
this.length = _.size(this._views);
},
// set up an initial list of views
_addInitialViews: function(views){
if (!views){ return; }
var view, i,
length = views.length;
for (i=0; i<length; i++){
view = views[i];
this.add(view);
}
}
});
// Borrowing this code from Backbone.Collection:
// http://backbonejs.org/docs/backbone.html#section-106
//
// Mix in methods from Underscore, for iteration, and other
// collection related features.
var methods = ['forEach', 'each', 'map', 'find', 'detect', 'filter',
'select', 'reject', 'every', 'all', 'some', 'any', 'include',
'contains', 'invoke', 'toArray', 'first', 'initial', 'rest',
'last', 'without', 'isEmpty', 'pluck'];
_.each(methods, function(method) {
Container.prototype[method] = function() {
var views = _.values(this._views);
var args = [views].concat(_.toArray(arguments));
return _[method].apply(_, args);
};
});
// return the public API
return Container;
})(Backbone, _);});
|
typeof console !== 'undefined' && console.log && console.log('unit-test.js loaded');
|
/// <reference path="../typings/index.d.ts" />
export * from './zone_utils';
export * from './mongo_cursor_observer';
export * from './mongo_cursor_differ';
export * from './meteor_reactive';
export * from './providers';
|
'use strict';
describe('Service: resEidolon', function () {
// load the service's module
beforeEach(module('tbsApp'));
// instantiate service
var resEidolon;
beforeEach(inject(function (_resEidolon_) {
resEidolon = _resEidolon_;
}));
it('should do something', function () {
expect(!!resEidolon).toBe(true);
});
});
|
import {
messages,
ruleName,
} from ".."
import rules from "../../../rules"
import { testRule } from "../../../testUtils"
const rule = rules[ruleName]
testRule(rule, {
ruleName,
config: ["always"],
accept: [ {
code: "a {}",
description: "first node ignored",
}, {
code: "@media { a {} }",
description: "nested node ignored",
}, {
code: "b {}\n\na {}",
}, {
code: "b {}\r\n\r\na {}",
description: "CRLF",
}, {
code: "b {}\n\r\na {}",
description: "Mixed",
}, {
code: "b {}\n \t\n\na {}",
}, {
code: "b {}\n\n\ta {}",
}, {
code: "b {}\r\n\r\n\ta {}",
description: "CRLF",
} ],
reject: [ {
code: "b {} a {}",
message: messages.expected,
}, {
code: "b {}\na {}",
message: messages.expected,
}, {
code: "b {}\n\n/* comment here*/\na {}",
message: messages.expected,
}, {
code: "b {}\r\n\r\n/* comment here*/\r\na {}",
description: "CRLF",
message: messages.expected,
} ],
})
testRule(rule, {
ruleName,
config: [ "always", { except: ["after-single-line-comment"] } ],
skipBasicChecks: true,
accept: [ {
code: "/**\n * comment\n*/\n\na {}",
}, {
code: "/* comment */\na {}",
} ],
reject: [ {
code: "/**\n * comment\n*/\na {}",
message: messages.expected,
}, {
code: "/* comment */\n\na {}",
message: messages.rejected,
} ],
})
testRule(rule, {
ruleName,
config: [ "always", { ignore: ["after-comment"] } ],
skipBasicChecks: true,
accept: [ {
code: "/* foo */\na {}",
}, {
code: "/* foo */\n\na {}",
}, {
code: "/* foo */\r\n\r\na {}",
description: "CRLF",
} ],
reject: [{
code: "b {} a {}",
message: messages.expected,
}],
})
testRule(rule, {
ruleName,
config: ["never"],
accept: [ {
code: "\n\na {}",
description: "first node ignored",
}, {
code: "\r\n\r\na {}",
description: "first node ignored and CRLF",
}, {
code: "@media {\n\na {} }",
description: "nested node ignored",
}, {
code: "b {}\na {}",
}, {
code: "b {}\n \t\na {}",
}, {
code: "b {}\r\n \t\r\na {}",
description: "CRLF",
}, {
code: "b {}\ta {}",
} ],
reject: [ {
code: "b {}\n\na {}",
message: messages.rejected,
}, {
code: "b {}\t\n\n\ta {}",
message: messages.rejected,
}, {
code: "b {}\t\r\n\r\n\ta {}",
description: "CRLF",
message: messages.rejected,
}, {
code: "b {}\n\n/* comment here*/\n\na {}",
message: messages.rejected,
} ],
})
testRule(rule, {
ruleName,
config: [ "never", { except: ["after-single-line-comment"] } ],
skipBasicChecks: true,
accept: [ {
code: "/**\n * comment\n*/\na {}",
}, {
code: "/* comment */\n\na {}",
} ],
reject: [ {
code: "/**\n * comment\n*/\n\na {}",
message: messages.rejected,
}, {
code: "/* comment */\na {}",
message: messages.expected,
} ],
})
testRule(rule, {
ruleName,
config: [ "never", { ignore: ["after-comment"] } ],
skipBasicChecks: true,
accept: [ {
code: "/* foo */\na {}",
}, {
code: "/* foo */\r\na {}",
description: "CRLF",
}, {
code: "/* foo */\n\na {}",
} ],
reject: [ {
code: "b {}\n\na {}",
message: messages.rejected,
}, {
code: "b {}\r\n\r\na {}",
description: "CRLF",
message: messages.rejected,
} ],
})
testRule(rule, {
ruleName,
config: ["always-multi-line"],
accept: [ {
code: "a {}",
description: "first node ignored",
}, {
code: "@media { a\n{} }",
description: "nested node ignored",
}, {
code: "b {}\na {}",
description: "single-line ignored",
}, {
code: "b\n{}\n\na\n{}",
}, {
code: "b\r\n{}\r\n\r\na\r\n{}",
description: "CRLF",
}, {
code: "b\n{}\n \t\n\na\n{}",
}, {
code: "b {}\n\n\ta\n{}",
}, {
code: "b {}\r\n\r\n\ta\r\n{}",
description: "CRLF",
} ],
reject: [ {
code: "b {} a\n{}",
message: messages.expected,
}, {
code: "b\n{}\na\n{}",
message: messages.expected,
}, {
code: "b\r\n{}\r\na\r\n{}",
description: "CRLF",
message: messages.expected,
}, {
code: "b {}\n\n/* comment here*/\na\n{}",
message: messages.expected,
} ],
})
testRule(rule, {
ruleName,
config: ["never-multi-line"],
accept: [ {
code: "\n\na\n{}",
description: "first node ignored",
}, {
code: "@media\n{\n\na\n{} }",
description: "nested node ignored",
}, {
code: "@media\r\n{\r\n\r\na\r\n{} }",
description: "nested node ignored and CRLF",
}, {
code: "b {}\n\na {}",
description: "single-line ignored",
}, {
code: "b\n{}\n \t\na\n{}",
}, {
code: "b\r\n{}\r\n \t\r\na\r\n{}",
description: "CRLF",
}, {
code: "b {}\ta\n{}",
} ],
reject: [ {
code: "b {}\n\na\n{}",
message: messages.rejected,
}, {
code: "b {}\t\n\n\ta\n{}",
message: messages.rejected,
}, {
code: "b {}\t\r\n\r\n\ta\r\n{}",
description: "CRLF",
message: messages.rejected,
}, {
code: "b {}\n\n/* comment here*/\n\na\n{}",
message: messages.rejected,
}, {
code: "b {}\r\n\r\n/* comment here*/\r\n\r\na\r\n{}",
description: "CRLF",
message: messages.rejected,
} ],
})
testRule(rule, {
ruleName,
syntax: "less",
config: ["always"],
accept: [{
code: "a {}\n.mixin-call() {}",
description: "ignore non-ouputting Less class mixin definition",
}],
})
|
import React from "react"
import classnames from "classnames"
import { SHOW_ALL, SHOW_COMPLETED, SHOW_ACTIVE } from "../constants/TodoFilters"
import { observer } from "mobx-react-lite"
const FILTER_TITLES = {
[SHOW_ALL]: "All",
[SHOW_ACTIVE]: "Active",
[SHOW_COMPLETED]: "Completed"
}
function Footer({ store }) {
function renderTodoCount() {
const { activeCount } = store
const itemWord = activeCount === 1 ? "item" : "items"
return (
<span className="todo-count">
<strong>{activeCount || "No"}</strong> {itemWord} left
</span>
)
}
function renderFilterLink(filter) {
const title = FILTER_TITLES[filter]
const selectedFilter = store.filter
return (
// eslint-disable-next-line
<a
className={classnames({ selected: filter === selectedFilter })}
style={{ cursor: "pointer" }}
onClick={() => store.setFilter(filter)}
>
{title}
</a>
)
}
function renderClearButton() {
const { completedCount, clearCompleted } = store
if (completedCount > 0) {
return (
<button className="clear-completed" onClick={() => clearCompleted()}>
Clear completed
</button>
)
}
}
return (
<footer className="footer">
{renderTodoCount()}
<ul className="filters">
{[SHOW_ALL, SHOW_ACTIVE, SHOW_COMPLETED].map((filter) => (
<li key={filter}>{renderFilterLink(filter)}</li>
))}
</ul>
{renderClearButton()}
</footer>
)
}
export default observer(Footer)
|
var _recentDataOpts = {
limit: 5,
sort: {
createTimeMillis: -1
}
};
Template.dataHome.helpers({
recentDatasets: function () {
return Collections.Datasets.find({}, _recentDataOpts);
}
});
Template.dataHome.events({
});
|
import { combineReducers } from 'redux';
import data from 'reducers/data';
import errors from 'reducers/errors';
import loading from 'reducers/loading';
jest.mock('redux');
jest.mock('reducers/data');
jest.mock('reducers/errors');
jest.mock('reducers/loading');
describe('reducer index', () => {
it('combines all my reducers', () => {
// neccessary because the combining is done on export
require('reducers'); // eslint-disable-line global-require
expect(combineReducers).lastCalledWith({ data, errors, loading });
});
});
|
Elm.Native.TestUtil = {};
Elm.Native.TestUtil.make = function (localRuntime) {
localRuntime.Native = localRuntime.Native || {};
localRuntime.Native.TestUtil = localRuntime.Native.TestUtil || {};
if (!localRuntime.Native.TestUtil.values) {
var Task = Elm.Native.Task.make(localRuntime);
var Signal = Elm.Native.Signal.make(localRuntime);
var sample = function (signal) {
// Use closure to track value
var val = signal.value;
var handler = function (value) {
val = value;
};
// We construct a new "output" node, because otherwise the incoming
// signal may be pruned by trimDeadNodes() in Runtime.js
// (if trimDeadNodes() sees that it is not otherwise used).
var output = Signal.output("sample-" + signal.name, handler, signal);
return Task.asyncFunction(function (callback) {
// Need to return the value inside setTimeout, because
// otherwise we can be called out-of-order ... that is, a
// previous `Task.andThen` which updated a Signal may not have
// actually completed yet unless we do this inside a timeout.
localRuntime.setTimeout(function () {
callback(Task.succeed(val));
}, 0);
});
};
localRuntime.Native.TestUtil.values = {
sample: sample
};
}
return localRuntime.Native.TestUtil.values;
};
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = memoize;
var _identity = require('lodash/identity');
var _identity2 = _interopRequireDefault(_identity);
var _slice = require('./internal/slice');
var _slice2 = _interopRequireDefault(_slice);
var _setImmediate = require('./internal/setImmediate');
var _setImmediate2 = _interopRequireDefault(_setImmediate);
var _initialParams = require('./internal/initialParams');
var _initialParams2 = _interopRequireDefault(_initialParams);
var _wrapAsync = require('./internal/wrapAsync');
var _wrapAsync2 = _interopRequireDefault(_wrapAsync);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function has(obj, key) {
return key in obj;
}
/**
* Caches the results of an async function. When creating a hash to store
* function results against, the callback is omitted from the hash and an
* optional hash function can be used.
*
* If no hash function is specified, the first argument is used as a hash key,
* which may work reasonably if it is a string or a data type that converts to a
* distinct string. Note that objects and arrays will not behave reasonably.
* Neither will cases where the other arguments are significant. In such cases,
* specify your own hash function.
*
* The cache of results is exposed as the `memo` property of the function
* returned by `memoize`.
*
* @name memoize
* @static
* @memberOf module:Utils
* @method
* @category Util
* @param {AsyncFunction} fn - The async function to proxy and cache results from.
* @param {Function} hasher - An optional function for generating a custom hash
* for storing results. It has all the arguments applied to it apart from the
* callback, and must be synchronous.
* @returns {AsyncFunction} a memoized version of `fn`
* @example
*
* var slow_fn = function(name, callback) {
* // do something
* callback(null, result);
* };
* var fn = async.memoize(slow_fn);
*
* // fn can now be used as if it were slow_fn
* fn('some name', function() {
* // callback
* });
*/
function memoize(fn, hasher) {
var memo = Object.create(null);
var queues = Object.create(null);
hasher = hasher || _identity2.default;
var _fn = (0, _wrapAsync2.default)(fn);
var memoized = (0, _initialParams2.default)(function memoized(args, callback) {
var key = hasher.apply(null, args);
if (has(memo, key)) {
(0, _setImmediate2.default)(function () {
callback.apply(null, memo[key]);
});
} else if (has(queues, key)) {
queues[key].push(callback);
} else {
queues[key] = [callback];
_fn.apply(null, args.concat(function () /*args*/{
var args = (0, _slice2.default)(arguments);
memo[key] = args;
var q = queues[key];
delete queues[key];
for (var i = 0, l = q.length; i < l; i++) {
q[i].apply(null, args);
}
}));
}
});
memoized.memo = memo;
memoized.unmemoized = fn;
return memoized;
}
module.exports = exports['default'];
|
export const Server = {
loadJSON: function(url, json_data, done=()=>{}, error=()=>{}) {
let response = {};
switch(url) {
case '/your/path/to/action':
fetch('/your/path/to/data.json')
.then(response => {
return response.json();
})
.then(data => {
response = data;
});
break;
}
setTimeout(() => {
done(response);
}, 500);
},
saveJSON: function(url, json_data, done=()=>{}, error=()=>{}) {
let response = true;
switch(url) {
case '/your/path/to/action':
response = { id: Math.floor(Math.random() * (1000000 - 1000 + 1)) + 1000 };
break;
}
setTimeout(() => {
done(response);
}, 500);
}
};
|
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @generated SignedSource<<713bfba9717046b5de96c3132c59fb0c>>
* @flow
* @lightSyntaxTransform
* @nogrep
*/
/* eslint-disable */
'use strict';
/*::
import type { ConcreteRequest } from 'relay-runtime';
type RelayReaderTestCreatesFragmentPointersWithVariableArgumentsUserProfile$ref = any;
export type RelayReaderTestCreatesFragmentPointersWithVariableArgumentsUserQueryVariables = {||};
export type RelayReaderTestCreatesFragmentPointersWithVariableArgumentsUserQueryResponse = {|
+me: ?{|
+$fragmentRefs: RelayReaderTestCreatesFragmentPointersWithVariableArgumentsUserProfile$ref,
|},
|};
export type RelayReaderTestCreatesFragmentPointersWithVariableArgumentsUserQuery = {|
variables: RelayReaderTestCreatesFragmentPointersWithVariableArgumentsUserQueryVariables,
response: RelayReaderTestCreatesFragmentPointersWithVariableArgumentsUserQueryResponse,
|};
*/
var node/*: ConcreteRequest*/ = {
"fragment": {
"argumentDefinitions": [],
"kind": "Fragment",
"metadata": null,
"name": "RelayReaderTestCreatesFragmentPointersWithVariableArgumentsUserQuery",
"selections": [
{
"alias": null,
"args": null,
"concreteType": "User",
"kind": "LinkedField",
"name": "me",
"plural": false,
"selections": [
{
"args": null,
"kind": "FragmentSpread",
"name": "RelayReaderTestCreatesFragmentPointersWithVariableArgumentsUserProfile"
}
],
"storageKey": null
}
],
"type": "Query",
"abstractKey": null
},
"kind": "Request",
"operation": {
"argumentDefinitions": [],
"kind": "Operation",
"name": "RelayReaderTestCreatesFragmentPointersWithVariableArgumentsUserQuery",
"selections": [
{
"alias": null,
"args": null,
"concreteType": "User",
"kind": "LinkedField",
"name": "me",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "id",
"storageKey": null
},
{
"alias": null,
"args": null,
"concreteType": "Image",
"kind": "LinkedField",
"name": "profilePicture",
"plural": false,
"selections": [
{
"alias": null,
"args": null,
"kind": "ScalarField",
"name": "uri",
"storageKey": null
}
],
"storageKey": null
}
],
"storageKey": null
}
]
},
"params": {
"cacheID": "67244ccc67f3b73bf01392a31b0627a6",
"id": null,
"metadata": {},
"name": "RelayReaderTestCreatesFragmentPointersWithVariableArgumentsUserQuery",
"operationKind": "query",
"text": "query RelayReaderTestCreatesFragmentPointersWithVariableArgumentsUserQuery {\n me {\n ...RelayReaderTestCreatesFragmentPointersWithVariableArgumentsUserProfile\n id\n }\n}\n\nfragment RelayReaderTestCreatesFragmentPointersWithVariableArgumentsUserProfile on User {\n id\n ...RelayReaderTestCreatesFragmentPointersWithVariableArgumentsUserProfilePicture_273SL1\n}\n\nfragment RelayReaderTestCreatesFragmentPointersWithVariableArgumentsUserProfilePicture_273SL1 on User {\n profilePicture {\n uri\n }\n}\n"
}
};
if (__DEV__) {
(node/*: any*/).hash = "7a9eaa1476798159533ae048a3ff048a";
}
module.exports = node;
|
import Ember from 'ember';
export default Ember.Component.extend({
session: Ember.inject.service('session'),
actions: {
invalidateSession: function() {
this.get('session').invalidate();
}
}
});
|
var Entity = require('./entity');
var Globals = require('./globals');
/*
Bullet entity.
*/
module.exports = function () {
"use strict";
this.velocity = 0.0;
this.damage = 1;
this.till_death = Globals.BULLET_LIVE_TIME;
this.type = Globals.BULLET_ENTITY;
this.radius = Globals.BULLET_RADIUS;
this.owner = null;
};
module.exports.prototype = new Entity();
|
/**
* ClusterStatus module.
* @module components/ClusterStatus
*/
import ClusterStatus from './cluster-status.component.jsx';
/**
* The ClusterStatus component
* @return {object} The ClusterStatus component.
*/
module.exports = ClusterStatus;
|
require('dotenv').config();
const path = require('path');
const cp = require('child_process');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const S3Plugin = require('webpack-s3-plugin');
const RollbarSourcemapPlugin = require('../../dist/RollbarSourceMapPlugin');
const rollbarClientAccessToken = process.env.ROLLBAR_CLIENT_TOKEN;
const rollbarServerAccessToken = process.env.ROLLBAR_SERVER_TOKEN;
const bucket = process.env.AWS_S3_BUCKET;
const s3Options = {
accessKeyId: process.env.AWS_ACCESS_KEY_ID,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
region: process.env.AWS_REGION
};
const basePath = 'assets';
const publicPath = `https://s3-${s3Options.region}.amazonaws.com/${bucket}/${basePath}`;
let version;
try {
version = cp.execSync('git rev-parse HEAD', {
cwd: __dirname,
encoding: 'utf8'
});
} catch (err) {
console.log('Error getting revision', err); // eslint-disable-line no-console
process.exit(1);
}
module.exports = {
mode: 'production',
devtool: 'hidden-source-map',
entry: {
app: './src/index'
},
output: {
path: path.join(__dirname, 'dist'),
publicPath,
filename: '[name]-[chunkhash].js',
chunkFilename: '[name]-[chunkhash].js'
},
optimization: {
minimize: true,
splitChunks: {
chunks: 'initial'
}
},
plugins: [
new webpack.DefinePlugin({
/* eslint-disable quote-props */
'process.env': {
NODE_ENV: JSON.stringify(process.env.NODE_ENV)
},
/* eslint-enable quote-props */
__ROLLBAR_ACCESS_TOKEN__: JSON.stringify(rollbarClientAccessToken),
__GIT_REVISION__: JSON.stringify(version)
}),
new HtmlWebpackPlugin({ template: 'src/index.html' }),
// Publish minified source
new S3Plugin({
include: /\.js$/,
basePath,
s3Options,
s3UploadOptions: {
Bucket: bucket,
ACL: 'public-read',
ContentType: 'application/javascript'
}
}),
// Publish sourcemap, but keep it private
new S3Plugin({
include: /\.map$/,
basePath: `${basePath}`,
s3Options,
s3UploadOptions: {
Bucket: bucket,
ACL: 'private',
ContentType: 'application/json'
}
}),
// Upload emitted sourcemaps to rollbar
new RollbarSourcemapPlugin({
accessToken: rollbarServerAccessToken,
version,
publicPath
})
],
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
include: path.join(__dirname, 'src'),
use: [
{
loader: 'babel-loader',
options: {
babelrc: false,
presets: [
'@babel/preset-react',
[
'@babel/preset-env',
{ targets: { browsers: ['last 2 versions'] } }
]
]
}
}
]
}
]
}
};
|
/**
* Copyright 2016 Facebook, Inc.
*
* You are hereby granted a non-exclusive, worldwide, royalty-free license to
* use, copy, modify, and distribute this software in source code or binary
* form for use in connection with the web services and APIs provided by
* Facebook.
*
* As with any software that integrates with the Facebook platform, your use
* of this software is subject to the Facebook Developer Principles and
* Policies [http://developers.facebook.com/policy/]. This copyright notice
* shall be included in all copies or substantial portions of the software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE
*
* @providesModule F8FriendGoing
* @flow
*/
'use strict';
var ProfilePicture = require('../../common/ProfilePicture');
var React = require('React');
var StyleSheet = require('StyleSheet');
var { Text } = require('F8Text');
var View = require('View');
var Image = require('Image');
var F8Touchable = require('F8Touchable');
import type {FriendsSchedule} from '../../reducers/friendsSchedules';
class F8FriendGoing extends React.Component {
props: {
onPress: () => void;
friend: FriendsSchedule;
};
render() {
return (
<F8Touchable onPress={this.props.onPress}>
<View style={styles.container}>
<ProfilePicture userID={this.props.friend.id} size={18} />
<Text style={styles.name}>
{this.props.friend.name}
</Text>
<Image source={require('../../common/img/disclosure.png')} />
</View>
</F8Touchable>
);
}
}
var styles = StyleSheet.create({
container: {
flexDirection: 'row',
alignItems: 'center',
paddingVertical: 10,
backgroundColor: 'white',
},
name: {
marginLeft: 10,
fontSize: 15,
flex: 1,
},
});
module.exports = F8FriendGoing;
|
/**
* Copyright <%= year %> Telerik AD
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
(function(f, define){
define([], f);
})(function(){
/*
* Kendo UI Web v2012.1.322 (http://kendoui.com)
* Copyright 2012 Telerik AD. All rights reserved.
*
* Kendo UI Web commercial licenses may be obtained at http://kendoui.com/web-license
* If you do not own a commercial license, this file shall be governed by the
* GNU General Public License (GPL) version 3.
* For GPL requirements, please review: http://www.gnu.org/copyleft/gpl.html
*/
(function( window, undefined ) {
var kendo = window.kendo || (window.kendo = { cultures: {} });
kendo.cultures["ru-UA"] = {
name: "ru-UA",
numberFormat: {
pattern: ["-n"],
decimals: 2,
",": " ",
".": ",",
groupSize: [3],
percent: {
pattern: ["-n%","n%"],
decimals: 2,
",": " ",
".": ",",
groupSize: [3],
symbol: "%"
},
currency: {
pattern: ["-n$","n$"],
decimals: 2,
",": " ",
".": ",",
groupSize: [3],
symbol: "₴"
}
},
calendars: {
standard: {
days: {
names: ["воскресенье","понедельник","вторник","среда","четверг","пятница","суббота"],
namesAbbr: ["Вс","Пн","Вт","Ср","Чт","Пт","Сб"],
namesShort: ["Вс","Пн","Вт","Ср","Чт","Пт","Сб"]
},
months: {
names: ["Январь","Февраль","Март","Апрель","Май","Июнь","Июль","Август","Сентябрь","Октябрь","Ноябрь","Декабрь",""],
namesAbbr: ["янв","фев","мар","апр","май","июн","июл","авг","сен","окт","ноя","дек",""]
},
AM: [""],
PM: [""],
patterns: {
d: "dd.MM.yyyy",
D: "d MMMM yyyy 'г.'",
F: "d MMMM yyyy 'г.' H:mm:ss",
g: "dd.MM.yyyy H:mm",
G: "dd.MM.yyyy H:mm:ss",
m: "MMMM dd",
M: "MMMM dd",
s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss",
t: "H:mm",
T: "H:mm:ss",
u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'",
y: "MMMM yyyy",
Y: "MMMM yyyy"
},
"/": ".",
":": ":",
firstDay: 1
}
}
}
})(this);
return window.kendo;
}, typeof define == 'function' && define.amd ? define : function(_, f){ f(); });
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.