text
stringlengths 2
6.14k
|
|---|
import createApi from 'api/create-api';
export default createApi('supporter_admin');
export const PublicSupporterApi = createApi('supporter_public');
|
'use strict';
const func = require('..').handle;
const test = require('tape');
const fixture = { log: { info: console.log } };
test('Unit: handles an HTTP GET', t => {
t.plan(1);
// Invoke the function, which should complete without error.
const result = func({ ...fixture, method: 'GET', query: { name: 'tiger' } });
t.deepEqual(result, { query: { name: 'tiger' } });
t.end();
});
test('Unit: handles an HTTP POST', t => {
t.plan(1);
// Invoke the function, which should complete without error.
const result = func({ ...fixture, method: 'POST', body: { name: 'tiger' } });
t.deepEqual(result, { body: { name: 'tiger' } });
t.end();
});
test('Unit: responds with error code if neither GET or POST', t => {
t.plan(1);
const result = func(fixture);
t.deepEqual(result, { statusCode: 405, statusMessage: 'Method not allowed' });
t.end();
});
|
//// [contextuallyTypingOrOperator2.ts]
var v: { a: (_: string) => number } = { a: s => s.length } || { a: s => 1 };
var v2 = (s: string) => s.length || function (s) { s.aaa };
//// [contextuallyTypingOrOperator2.js]
var v = { a: function (s) { return s.length; } } || { a: function (s) { return 1; } };
var v2 = function (s) { return s.length || function (s) { s.aaa; }; };
|
// Place all the behaviors and hooks related to the matching controller here.
// All this logic will automatically be available in application.js.
$(document).on("ready", function(){
// mixItUp
$('#Container').mixItUp({
callbacks: {
onMixEnd: function(state){
$('.js-no-games').hide();
},
onMixFail: function(state){
$('.js-no-games').show();
}
}
});
// Filter buttons
$('.js-show-all').on("click", function(){
$('.js-arena').hide();
$('.js-day').hide();
})
$('.js-filter-arena').on("click", function(){
$('.js-day').hide();
$('.js-arena').show();
})
$('.js-filter-day').on("click", function(){
$('.js-arena').hide();
$('.js-day').show();
})
if ($('body').hasClass("load-map")) {
//Maps
var directionsDisplay = new google.maps.DirectionsRenderer();
var directionsService = new google.maps.DirectionsService();
function getCurrentLocation() {
if(navigator.geolocation)
navigator.geolocation.getCurrentPosition(calcRoute);
}
function calcRoute(position) {
var origin = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var arena_lat = $('.js-game-coords').data("lat");
var arena_lng = $('.js-game-coords').data("lng");
var destination = new google.maps.LatLng(arena_lat, arena_lng);
var request = {
origin: origin,
destination: destination,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
getCurrentLocation();
var handler = Gmaps.build('Google');
handler.buildMap({ internal: {id: 'geolocation'}}, function(){
directionsDisplay.setMap(handler.getMap());
});
}
})
|
describe('ConfigService', function() {
beforeEach(function() {
module('app');
module('app.services');
});
var config, $httpBackend;
beforeEach(inject(function(_$httpBackend_, _config_) {
$httpBackend = _$httpBackend_;
config = _config_;
}));
it('should get app configuration and pass it to your method', function() {
var apiRoot = 'http://8.8.4.4:8080';
var expectedResponse = [{ apiRoot: apiRoot }];
$httpBackend.expectGET('config.json').respond(200, expectedResponse);
var onSuccess = function(configResponse) {
expect(configResponse[0].apiRoot).toEqual(apiRoot);
};
var onFailure = function() {
throw new Error('should not execute this!');
};
config.get().then(onSuccess, onFailure);
$httpBackend.flush();
});
it('should execute your fallback in case of an error', function() {
var expectedResponse = [{}, {}, {}];
$httpBackend.expectGET('config.json').respond(500, expectedResponse);
var onSuccess = function(configResponse) {
throw new Error('should not execute this!');
};
var onFailure = function(reason) {
expect(reason.status).toEqual(500);
expect(reason.data).toEqual(expectedResponse);
};
config.get().then(onSuccess, onFailure);
$httpBackend.flush();
});
});
|
$(function(){
function initSparkline2(){
$('#sparkline2').sparkline([2,4,8],{
type: 'pie',
width: '100px',
height: '100px',
sliceColors: ['#F5CB7B', '#FAEEE5', '#f0f0f0']
});
}
/* Inspired by Lee Byron's test data generator. */
function _stream_layers(n, m, o) {
if (arguments.length < 3) o = 0;
function bump(a) {
var x = 1 / (.1 + Math.random()),
y = 2 * Math.random() - .5,
z = 10 / (.1 + Math.random());
for (var i = 0; i < m; i++) {
var w = (i / m - y) * z;
a[i] += x * Math.exp(-w * w);
}
}
return d3.range(n).map(function() {
var a = [], i;
for (i = 0; i < m; i++) a[i] = o + o * Math.random();
for (i = 0; i < 5; i++) bump(a);
return a.map(function(d, i) {
return {x: i, y: Math.max(0, d)};
});
});
}
function testData(stream_names, pointsCount) {
var now = new Date().getTime(),
day = 1000 * 60 * 60 * 24, //milliseconds
daysAgoCount = 60,
daysAgo = daysAgoCount * day,
daysAgoDate = now - daysAgo,
pointsCount = pointsCount || 45, //less for better performance
daysPerPoint = daysAgoCount / pointsCount;
return _stream_layers(stream_names.length, pointsCount, .1).map(function(data, i) {
return {
key: stream_names[i],
values: data.map(function(d,j){
return {
x: daysAgoDate + d.x * day * daysPerPoint,
y: Math.floor(d.y * 100) //just a coefficient,
}
})
};
});
}
function initNvd32(){
nv.addGraph(function() {
var chart = nv.models.multiBarChart()
.margin({left: 28, bottom: 30, right: 0})
.color(['#F7653F', '#ddd']);
chart.xAxis
.showMaxMin(false)
.ticks(1000)
.tickFormat(function(d) { return d3.time.format('%b %d')(new Date(d)) });
chart.yAxis
.showMaxMin(false)
.ticks(0)
.tickFormat(d3.format(',f'));
// chart.controls.margin({left: 0});
d3.select('#nvd32 svg')
.style('height', '300px')
.datum(testData(['Uploads', 'Downloads'], 10).map(function(el, i){
el.area = true;
return el;
}))
.transition().duration(500)
.call(chart)
;
SingApp.onResize(chart.update);
return chart;
});
}
/*function initMorris3(lbl1,val1,val2,val3,val4){
$('#morris3').css({height: 280});
Morris.Donut({
element: 'morris3',
data: [
{label: lbl1, value: val1},
{label: "Upload Sales", value: val2},
{label: "In-Store Sales", value: val3},
{label: "Mail-Order Sales", value: val4}
],
colors: ['#F7653F', '#F8C0A2', '#e6e6e6', '#a6a6a6']
});
}*/
function pageLoad(){
$('.widget').widgster();
$('.sparkline').each(function(){
$(this).sparkline('html', $(this).data());
});
//initFlot();
//initRickshaw();
//initSparkline1();
initSparkline2();
//initNvd31();
initNvd32();
//initMorris1();
//initMorris2();
//initMorris3();
//initEasyPie();
//initFlotBar();
}
pageLoad();
//SingApp.onPageLoad(pageLoad);
});
|
(function () {
'use strict';
angular
.module('app')
.service('data', data);
data.$inject = ['Spotify', '$q', 'dataRepository', 'sortFilter', 'toastr'];
function data(Spotify, $q, dataRepository, sortFilter, toastr) {
var service = this;
service.audioPlayer = new Audio();
service.userTracksId = 'user-tracks';
service.playlistList = [];
service.initPlaylistList = initPlaylistList;
service.checkedPlaylistList = [];
service.trackList = [];
service.displayedPlaylistTrackList = [];
service.filteredTrackList = [];
service.user = {};
service.userOptions = {};
service.updateCheckedPlaylistList = updateCheckedPlaylistList;
service.insertToTrackList = insertToTrackList;
service.updateTrackList = updateTrackList;
service.isProcessing = false;
service.isLoggedIn = false;
service.isLoadingDone = false;
function updateCheckedPlaylistList(doNotUpdateTrackList) {
service.checkedPlaylistList = _.filter(service.playlistList, function (playlist) {
return playlist.isChecked;
});
updateCheckedPlaylistIds();
if (!doNotUpdateTrackList) {
updateTrackList();
}
};
function insertToTrackList(trackToAddList) {
_.each(trackToAddList, function (trackToAdd) {
var existingTrack = _.find(service.trackList, function (track) {
return track.uri == trackToAdd.uri;
});
if (!existingTrack) {
service.trackList.push(trackToAdd);
} else {
existingTrack.containingPlaylistList.push({ id: trackToAdd.containingPlaylistList[0].id, addedAt: trackToAdd.containingPlaylistList[0].addedAt });
existingTrack.mostRecentAddedAt = existingTrack.mostRecentAddedAt > trackToAdd.mostRecentAddedAt ? existingTrack.mostRecentAddedAt : trackToAdd.mostRecentAddedAt;
existingTrack.leastRecentAddedAt = existingTrack.leastRecentAddedAt < trackToAdd.leastRecentAddedAt ? existingTrack.leastRecentAddedAt : trackToAdd.leastRecentAddedAt;
}
});
if (_.every(service.playlistList, function (playlist) {
return playlist.isReady;
})) {
updateTrackList();
}
};
var shownMessage = false;
function updateTrackList() {
var tracksToDisplay = _.filter(service.trackList, function (track) {
return _.some(service.checkedPlaylistList, function (checkedPlaylist) {
var containingPlaylistIdList = _.map(track.containingPlaylistList, function (containingPlaylist) { return containingPlaylist.id; });
return containingPlaylistIdList.indexOf(checkedPlaylist.id) !== -1;
});
});
service.displayedPlaylistTrackList = tracksToDisplay;
service.filteredTrackList = sortFilter.reSort(sortFilter.filterLocals(service.displayedPlaylistTrackList));
service.isProcessing = false;
if (!shownMessage) {
toastr.info('Select from which playlists you wish to see songs on the list on the left.<br />' +
'Add or remove songs from a playlist by clicking <i class="fa fa-plus fa-fw"></i> or <i class="fa fa-check fa-fw"></i><br />' +
'You can order the songs by the time it was added overall, or added in a specific playlist by clicking <i class="fa fa-calendar-o fa-fw fa-lg"></i>', 'Welcome!', {
allowHtml: true,
iconClass: 'welcome-toast',
progressBar: true,
timeOut: 40000,
extendedTimeOut: 20000
});
shownMessage = true;
}
};
function initPlaylistList() {
var savedTracks = {
name: "Saved Songs",
isSavedTracks: true,
trackList: [],
isOwned: true,
id: service.userTracksId,
totalLoadedTracks: 0
}
service.playlistList = [savedTracks];
}
function updateCheckedPlaylistIds() {
service.userOptions.checkedPlaylistIdList = _.map(service.checkedPlaylistList, function (playlist) {
return playlist.id;
});
dataRepository.setUserOptions(service.userOptions);
}
}
})();
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _getOwnPropertyDescriptor = require('babel-runtime/core-js/object/get-own-property-descriptor');
var _getOwnPropertyDescriptor2 = _interopRequireDefault(_getOwnPropertyDescriptor);
var _apply = require('babel-runtime/core-js/reflect/apply');
var _apply2 = _interopRequireDefault(_apply);
var _assign = require('babel-runtime/core-js/object/assign');
var _assign2 = _interopRequireDefault(_assign);
var _dec, _dec2, _desc, _value, _obj; /**!
*
* Copyright (c) 2015 Cisco Systems, Inc. See LICENSE file.
* @private
*/
var _sparkPlugin = require('../../../lib/spark-plugin');
var _sparkPlugin2 = _interopRequireDefault(_sparkPlugin);
var _common = require('./common');
var _common2 = _interopRequireDefault(_common);
var _storage = require('../../../lib/storage');
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) {
var desc = {};
Object['ke' + 'ys'](descriptor).forEach(function (key) {
desc[key] = descriptor[key];
});
desc.enumerable = !!desc.enumerable;
desc.configurable = !!desc.configurable;
if ('value' in desc || desc.initializer) {
desc.writable = true;
}
desc = decorators.slice().reverse().reduce(function (desc, decorator) {
return decorator(target, property, desc) || desc;
}, desc);
if (context && desc.initializer !== void 0) {
desc.value = desc.initializer ? desc.initializer.call(context) : void 0;
desc.initializer = undefined;
}
if (desc.initializer === void 0) {
Object['define' + 'Property'](target, property, desc);
desc = null;
}
return desc;
}
/**
* @class
* @extends CredentialsBase
*/
var Credentials = _sparkPlugin2.default.extend((0, _assign2.default)({}, _common2.default, (_dec = (0, _storage.persist)('authorization'), _dec2 = (0, _storage.persist)('clientAuthorization'), (_obj = {
initialize: function initialize() {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return (0, _apply2.default)(_common2.default.initialize || _sparkPlugin2.default.prototype.initialize, this, args);
}
}, (_applyDecoratedDescriptor(_obj, 'initialize', [_dec, _dec2], (0, _getOwnPropertyDescriptor2.default)(_obj, 'initialize'), _obj)), _obj))));
exports.default = Credentials;
//# sourceMappingURL=node.js.map
|
module.exports = function (grunt) {
// *************************************************************************
// REQUIRE PATHS
// Add any paths here you want shortened. Relative to the 'js' dir.
// *************************************************************************
var amdModulePaths = {
'pubsub': './lib/vendors/jquery/pubsub'
};
// *************************************************************************
// GRUNT CONFIG
// You shouldn't need to edit anything below here
// *************************************************************************
var _ = require('lodash-node'),
requirePathsForJquery1build = _.merge({'jquery': './lib/vendors/jquery/jquery-1.9.1'}, amdModulePaths),
requirePathsForJquery2build = _.merge({'jquery': './lib/vendors/jquery/jquery-2.0.3'}, amdModulePaths),
requireJsDefaults = {
options: {
baseUrl: './source/js',
optimize: 'uglify2',
preserveLicenseComments: false
}
},
legacyIeConfig = _.merge({
options: {
paths: requirePathsForJquery1build,
generateSourceMaps: false,
out: './content/<%= config.services.default %>/js/all-legacyie.js',
name: './app'
}
}, requireJsDefaults),
allHtml5Config = _.merge({
options: {
paths: requirePathsForJquery2build,
generateSourceMaps: true,
out: './content/<%= config.services.default %>/js/all-html5.js',
name: './app'
}
}, requireJsDefaults),
liteConfig = _.merge({
options: {
paths: requirePathsForJquery2build,
generateSourceMaps: false,
name: './lib/vendors/almond/almond',
out: './content/<%= config.services.default %>/js/lite.js',
include: ['app--lite'],
insertRequire: ['app--lite'],
wrap: true
}
}, requireJsDefaults);
grunt.config(['amdModulePaths'], amdModulePaths);
grunt.config(['requirejs', 'jquery1'], legacyIeConfig);
grunt.config(['requirejs', 'jquery2'], allHtml5Config);
grunt.config(['requirejs', 'lite'], liteConfig);
};
|
(function() {
var animate, animctrl, curpos, data, hoverIn, hoverOut, lock, lockbut, mousePress, mouseScroll, newpos, onAttributeChanged, open, openbut;
var __slice = Array.prototype.slice;
print("Hello I want to control a door!");
engine.ImportExtension("qt.core");
engine.ImportExtension("qt.gui");
openbut = new QPushButton();
lockbut = new QPushButton();
openbut.text = "o init";
lockbut.text = "l init";
openbut.show();
lockbut.show();
data = me.dynamiccomponent;
animctrl = me.animationcontroller;
animctrl.EnableAnimation("open", false);
curpos = 0;
newpos = 0;
onAttributeChanged = function() {
var args, locked, opened;
args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
print("door.coffee onAttributeChanged", args);
opened = data.GetAttribute('opened');
locked = data.GetAttribute('locked');
openbut.text = opened ? "Close" : "Open";
lockbut.text = locked ? "Unlock" : "Lock";
openbut.enabled = !(locked && !opened);
return newpos = opened ? 0 : 1;
};
animate = function(dtime) {
var diff, dir, speed;
if (newpos !== curpos) {
diff = Math.abs(newpos - curpos);
dir = newpos < curpos ? -1 : 1;
speed = 1;
curpos += dir * (Math.min(diff, dtime * speed));
animctrl.SetAnimWeight("open", 1 - curpos);
return print(curpos + " - " + diff);
}
};
onAttributeChanged();
data.AttributeChanged.connect(onAttributeChanged);
frame.Updated.connect(animate);
open = function() {
var locked, opened;
print("door.coffee open button clicked!");
opened = data.GetAttribute('opened');
locked = data.GetAttribute('locked');
if (opened || !locked) {
opened = !opened;
return data.SetAttribute('opened', opened);
} else {
return print("Can't open a locked door!");
}
};
lock = function() {
var locked;
print("door.coffee lock button clicked!");
locked = data.GetAttribute('locked');
locked = !locked;
print(locked);
return data.SetAttribute('locked', locked);
};
openbut.clicked.connect(open);
lockbut.clicked.connect(lock);
hoverIn = function() {
print("hovering in to over door");
return print(me.dynamiccomponent.GetAttribute('opened'));
};
hoverOut = function() {
return print("hovering out from over door");
};
mousePress = function() {
return open();
};
mouseScroll = function() {
var args;
args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
return print("mouse scroll:", args);
};
me.Action("MouseHoverIn").Triggered.connect(hoverIn);
me.Action("MouseHoverOut").Triggered.connect(hoverOut);
me.Action("MousePress").Triggered.connect(mousePress);
me.Action("MouseScroll").Triggered.connect(mouseScroll);
}).call(this);
|
var a01244 =
[
[ "BAD_PRIORITY", "a01244.html#a3fd320d93290a64ff24687ec596f1f61", null ],
[ "MAX_NUM_SEAMS", "a01244.html#aec46796fda71456341a9591d1b42b5f8", null ],
[ "MAX_OLD_SEAMS", "a01244.html#a5ea8c0b3acc90ffdddd848229167cc01", null ],
[ "NO_FULL_PRIORITY", "a01244.html#a149d8b9e54f546955de3fa68bf5bf521", null ],
[ "SPLIT_CLOSENESS", "a01244.html#a137ecd53cc1a098b2943e48aff99c6b6", null ]
];
|
/*
* Copyright 2012, Mozilla Foundation and contributors
*
* 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.
*/
'use strict';
var Promise = require('../../util/promise').Promise;
exports.items = [
{
item: 'command',
name: 'sleep',
description: 'Wait for a while',
params: [
{
name: 'length',
type: { name: 'number', min: 1 },
description: 'How long to wait (s)'
}
],
returnType: 'string',
exec: function(args, context) {
return new Promise(function(resolve, reject) {
setTimeout(function() {
resolve('Done');
}, args.length * 1000);
});
}
}
];
|
/**
*
* Copyright 2015 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import AppController from './controller/AppController';
import ServiceWorkerController from './controller/ServiceWorkerController';
new AppController();
new ServiceWorkerController();
|
'use strict'
var split = require('split2')
var createStreamThrottle = require('../../util/throttle')
function InputStdin (config, eventEmitter) {
this.config = config
this.eventEmitter = eventEmitter
}
InputStdin.prototype.start = function () {
var context = {name: 'input.stdin', sourceName: this.config.sourceName || 'unknown'}
var eventEmitter = this.eventEmitter
process.stdin.pipe(createStreamThrottle(this.config.maxInputRate)).pipe(split()).on('data', function emitLine (data) {
eventEmitter.emit('data.raw', data, context)
}).on('error', console.error)
if (this.config.stdinExitEnabled || this.config.configFile && this.config.configFile.input && this.config.configFile.input.stdin && this.config.configFile.input.stdin.stdinExitEnabled) {
process.stdin.once('end', function () {
eventEmitter.emit('input.stdin.end', null, context)
})
} else {
// terminate on EOF from stdin deactivated
process.stdin.on('error', function (err) {
console.log('stdin error ' + err)
})
}
}
InputStdin.prototype.stop = function (cb) {
cb()
}
module.exports = InputStdin
|
import React from "react";
import PropTypes from "prop-types";
//Components
import { Title, Text, Button, Link } from "../../atoms/index";
//Styles
import styled from "styled-components";
const Confirmation = ({ className, show, title, description, actionProps, ...props }) => {
return (
<div
className={`card mx-auto animated zoomInUp ${className}`}
style={{ display: show ? "inline" : "none" }}
>
<div className="card-body">
<Title>{title}</Title>
<Text>{description}</Text>
<div className="text-right">
<Link className="cancelAction" onClick={() => props.onCancel()}>
{props.onCancelText}
</Link>
<Button
className="btn"
onClick={() => props.onConfirmation()}
color={props.onConfirmationColor}
{...actionProps}
>
{props.onConfirmationText}
</Button>
</div>
</div>
</div>
);
};
Confirmation.defaultProps = {
title: "Form Title",
description: "Form Date",
onConfirmationText: "Delete",
onCancelText: "Cancel",
onConfirmationColor: "red",
show: false
};
Confirmation.propTypes = {
className: PropTypes.string,
title: PropTypes.string,
description: PropTypes.string,
onConfirmationText: PropTypes.string,
onConfirmationColor: PropTypes.string,
onCancelText: PropTypes.string,
show: PropTypes.bool.isRequired,
onConfirmation: PropTypes.func,
onCancel: PropTypes.func
};
export default styled(Confirmation)`
width: 20rem;
position: absolute;
left: 0;
right: 0;
z-index: 9999;
box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
.cancelAction {
margin-right: 10px;
}
`;
|
"use strict";
$( document ).ready(function() {
var $metricsEl = $('#metricsSection');
var metricsOffsetTop = 0;
var metricsHeight = 0;
var windowHeight = $(window).height();
var duration = 4000;
var decimal_places = 1;
var decimal_factor = Math.pow(10, decimal_places);
var isCompleted = false;
var scrollTop = 0;
calculateDimensions();
checkForStart();
function doubleNumberStep(now, tween) {
var floored_number = Math.floor(now) / decimal_factor,
target = $(tween.elem);
floored_number = floored_number.toFixed(decimal_places);
target.text(floored_number);
}
function init(el, number, isDouble) {
if (!$(el).length) return;
isDouble = isDouble !== undefined? isDouble : false;
var opts = {
number: isDouble? number * decimal_factor : number,
easing: 'easeInOut',
}
if (isDouble) {
opts.numberStep = doubleNumberStep;
}
$(el).animateNumber(opts, duration);
}
function calculateDimensions() {
metricsOffsetTop = $metricsEl.offset().top;
metricsHeight = $metricsEl.height();
windowHeight = $(window).height();
}
function startAnimation() {
if (isCompleted) return;
isCompleted = true;
init('#numberHectares', 26);
init('#numberDays', 4629);
init('#numberTons', 6.5, true);
init('#numberCars', 1.3, true);
}
function checkForStart() {
if ((scrollTop + windowHeight / 2) > metricsOffsetTop || (scrollTop + windowHeight) > (metricsOffsetTop + metricsHeight)){
startAnimation();
}
}
$(window).resize(function() {
calculateDimensions();
scrollTop = $(this).scrollTop();
checkForStart();
});
$(window).scroll(function() {
scrollTop = $(this).scrollTop();
checkForStart();
});
});
|
/*globals _, data, DataFixer */
var DataService = (function (DataFixer) {
'use strict';
var DataService = function () {
var dataFixer = new DataFixer();
dataFixer.applyCorrections(data.moves);
};
DataService.prototype.getAllPlayers = function (callback) {
callback(data.characters);
};
DataService.prototype.getPlayer = function (id, callback) {
id = parseInt(id, 10);
_.each(data.characters, function (value) {
if (value.id === id) {
callback(value);
}
});
};
DataService.prototype.getPlayerMoves = function (id, callback) {
id = parseInt(id, 10);
_.each(data.moves, function (value) {
if (value.id === id) {
callback(value);
}
});
};
DataService.prototype.getKombatKodes = function (callback) {
callback(data.kodes);
};
return DataService;
}(DataFixer));
|
'use strict';
/**
* @memberOf model
*/
class ContentKind
{
/**
*
*/
static get UNKNOWN()
{
return '*';
}
/**
*
*/
static get CSS()
{
return 'css';
}
/**
* @inheritDoc
*/
static get JS()
{
return 'js';
}
/**
* @inheritDoc
*/
static get MACRO()
{
return 'macro';
}
/**
* @inheritDoc
*/
static get EXAMPLE()
{
return 'example';
}
/**
* @inheritDoc
*/
static get DATAMODEL()
{
return 'datamodel';
}
/**
* @inheritDoc
*/
static get TEXT()
{
return 'text';
}
}
/**
* Public
* @ignore
*/
module.exports = ContentKind;
|
var searchData=
[
['read_5flines',['read_lines',['../de/d16/classadmin_1_1shell.html#a088a4609cf54f76ee4c838eea157fbc9',1,'admin::shell']]],
['remove',['remove',['../de/d16/classadmin_1_1shell.html#ad4f8d9280283a993eec0bc5dcade6d99',1,'admin::shell']]],
['restart_5finit_5fservice',['restart_init_service',['../de/d16/classadmin_1_1shell.html#ab6f38a2fae6ea2cc870c1de2d6cb6017',1,'admin::shell']]],
['root',['root',['../d6/dae/classadmin_1_1www.html#a970be68a3aafd5e7847083f756041f51',1,'admin::www']]],
['run',['run',['../db/de4/classadmin_1_1www_1_1uwsgi.html#ab5860b95c90e736ad96fb7273efa10a5',1,'admin::www::uwsgi']]]
];
|
import { shallowMount, createLocalVue } from '@vue/test-utils'
import Vuex from 'vuex'
import VueMoment from 'vue-moment'
import PersonNotes from '@/registry/components/people/PersonNotes'
import fakePerson from '../fakePerson'
const localVue = createLocalVue()
localVue.use(Vuex)
localVue.use(VueMoment)
describe('PersonNotes.vue', () => {
let store
let getters
let mutations
let actions
beforeEach(() => {
getters = {
loading: () => false,
error: () => null,
user: () => null,
currentDriller: jest.fn().mockReturnValue(fakePerson),
drillers: () => [],
userRoles: () => ({ registry: { edit: true, view: true, approve: true } })
}
store = new Vuex.Store({ getters, actions, mutations })
})
it('renders and has a title', () => {
const wrapper = shallowMount(PersonNotes, {
store,
localVue,
stubs: ['router-link', 'router-view'],
mocks: {
$route: {params: {person_guid: 'aaaa-4444-bbbb-1111'}}
}
})
expect(wrapper.find('#notesSectionTitle').text()).toEqual('Notes')
})
it('displays notes', () => {
// our fake person has 1 note, so $person-note-0 should render
const wrapper = shallowMount(PersonNotes, {
store,
localVue,
stubs: ['router-link', 'router-view'],
mocks: {
$route: {params: {person_guid: 'aaaa-4444-bbbb-1111'}}
}
})
expect(wrapper.find('#person-note-0').text()).toContain('A new note')
expect(wrapper.find('#person-note-0').text()).toContain('Test User')
})
})
|
$(document).ready(function()
{
$.setAjaxJSONER('.jsoner', function(response){ bootbox.alert(response.message, function(){location.href = response.locate; return true;});});
$.setAjaxJSONER('.switcher', function(response){ bootbox.alert(response.message, function(){location.href = response.locate; return false;});});
/* remove empty element */
$('.speaker > ul > li > span:empty').closest('li').remove();
});
|
/*
* created @ 2012 08 02
*
* creator fvi@
*
*
*
*/
exports.LogoutACS = function() {
var Cloud = require('ti.cloud');
Cloud.Users.logout(function(e) {
if (e.success) {
} else {
// alert('Error:\\n' +((e.error && e.message) || JSON.stringify(e)));
}
});
}
|
import keymirror from 'keymirror';
var actionTypes = keymirror({
LOG_IN: null,
LOG_IN_SUCCESS: null,
LOG_IN_FAIL: null,
IDENTIFY: null,
IDENTIFY_SUCCESS: null,
IDENTIFY_FAIL: null,
LOG_OUT: null,
LOG_OUT_SUCCESS: null,
LOG_OUT_FAIL: null,
ADD_TOAST: null,
REMOVE_TOAST: null,
REMOVE_ALL_TOASTS: null,
GET_TC: null,
GET_TC_SUCCESS: null,
GET_TC_FAIL: null,
GET_TEST_CASES: null,
GET_TEST_CASES_SUCCESS: null,
GET_TEST_CASES_FAIL: null,
GET_QUERIES: null,
GET_QUERIES_SUCCESS: null,
GET_QUERIES_FAIL: null,
ACCEPT_TC: null,
ACCEPT_TC_SUCCESS: null,
ACCEPT_TC_FAIL: null,
REJECT_TC: null,
REJECT_TC_SUCCESS: null,
REJECT_TC_FAIL: null
});
export default actionTypes;
|
var a00591 =
[
[ "SVMutex", "a00591.html#a89972af36deeecb0eef35ce4b27a8a0d", null ],
[ "Lock", "a00591.html#ac2a19e2b7ce47e75ee1f72870574e41f", null ],
[ "Unlock", "a00591.html#aa70f2446491c0de56b69eba6dd877f31", null ]
];
|
var app = angular.module('app');
app.factory('ticketFactory',[ '$http', '$rootScope', function($http,$rootScope){
var ticketFactory = {};
ticketFactory.getCantidadTickets = function(callback){
$http.get($rootScope.serverUrl + "/ticket/cantidad").success(function(data){
callback(data.cantidad);
}).error(function(data){
callback(0);
});
};
ticketFactory.getAllTickets = function(callback){
$http.get($rootScope.serverUrl + "/ticket/list").success(function(data){
callback(data);
}).error(function(data){
callback([]);
});
};
ticketFactory.addTicket = function(ticket,success,error){
$http.post($rootScope.serverUrl+"/ticket","json="+JSON.stringify(ticket)).success(function(data){
success(data);
}).error(function(data){
error(data);
});
};
ticketFactory.addTicketPorAccesorio = function(ticket,success,error){
$http.post($rootScope.serverUrl+"/ticket","json="+JSON.stringify(ticket)).success(function(data){
success(data);
}).error(function(data){
error(data);
});
};
ticketFactory.get_Ticket = function(ticket, callback){
$http.get($rootScope.serverUrl + "/ticket/ticket/"+ticket).success(function(data){
callback(data);
}).error(function(data){
callback([]);
});
};
ticketFactory.saveTicket = function(ticket,success,error){
$http.put($rootScope.serverUrl+"/ticket","json="+JSON.stringify(ticket)).success(function(data){
success(data);
}).error(function(data){
error(data);
});
};
ticketFactory.deleteTicket = function(ticket,success,error){
//"json="+JSON.stringify(cliente)
$http({
method: 'DELETE',
url: $rootScope.serverUrl+"/ticket",
data: JSON.stringify(ticket)
}).success(function(data){
success(data);
}).error(function(data){
error(data);
});
};
ticketFactory.getPagedTickets = function(page,amount,estados,callback){
$http.get($rootScope.serverUrl + "/ticket/paginado/"+page+"/"+amount+"?estados="+JSON.stringify(estados)).success(function(data){
callback(data);
}).error(function(data){
callback([]);
});
};
ticketFactory.searchTickets = function(data,page,cantidad,callback){
ticket = {
taller: data,
num_ticket: data,
fecha: data,
equipo: data,
modelo: data,
marca: data,
imei: data,
cliente: data,
costo_reparacion: data,
tecnico: data,
avisado: data,
estado: data
};
$http.get($rootScope.serverUrl + "/ticket/search/"+page+"/"+cantidad+"?json="+JSON.stringify(ticket)+"?estados="+JSON.stringify(estados)).success(function(data){
callback(data);
}).error(function(data){
callback([]);
});
};
ticketFactory.searchCantidadTickets = function(data,callback){
ticket = {
taller: data,
num_ticket: data,
fecha: data,
equipo: data,
modelo: data,
marca: data,
imei: data,
cliente: data,
costo_reparacion: data,
tecnico: data,
avisado: data,
estado: data
};
console.log(ticket);
$http.get($rootScope.serverUrl + "/ticket/searchcantidad?json="+JSON.stringify(ticket)).success(function(data){
callback(data.cantidad);
}).error(function(data){
callback([]);
});
};
return ticketFactory;
}]);
|
import Ember from 'ember';
import ResetScrollMixin from '../mixins/reset-scroll';
import Analytics from '../mixins/analytics';
/**
* @module ember-preprints
* @submodule routes
*/
/**
* @class Resource Deleted Route Handler
*/
export default Ember.Route.extend(Analytics, ResetScrollMixin, {
});
|
export default function IosNotificationV1Mixin(M) {
Object.assign(M.prototype, {
/**
* @returns {Object}
*/
getUriTemplateVars() {
return {
_id: `${this.get('_id', '')}`,
};
}
});
}
|
let app = require('../../../index.js');
let discord = require('discord.js-commando');
let logger = app.logger;
let client = app.client;
module.exports = class RoleCommand extends discord.Command {
constructor(client) {
super(client, {
name: 'role',
aliases: ['role'],
group: 'everyone',
memberName: 'role',
description: 'Gibt die Rollen und Rollen-IDs des angefragten Nutzers aus',
throttling: {
usages: 3,
duration: 60
},
args: [
{
key: 'member',
label: 'user',
prompt: 'Wessen Rollen möchtest du sehen?\n',
type: 'member'
}
]
});
}
async run(msg, args) {
var roles = '\nHier sind die Rollen von `' + args.member.displayName + '`:\n';
function getRole (roleId) {
var foundRole;
client.channels.forEach(function(channel) {
if (channel.id === app.config.discord.channelId) {
channel.guild.roles.forEach(function(role) {
if (role.id === roleId) {
foundRole = role;
}
});
}
});
return foundRole;
}
roles += '```\n';
args.member._roles.forEach(function(roleId) {
let role = getRole(roleId);
roles += role.name + ': ' + role.id + '\n';
});
roles += '```\n';
return msg.reply(roles);
}
};
|
(function(){
var bhtransviz = window.bhtransviz || {};
window.bhtransviz = bhtransviz;
// index of each node
bhtransviz.nodes = {};
// number of nodes
bhtransviz.n = 0;
// graph connections
bhtransviz.matrix = [];
// max number of connections
bhtransviz.max = 0;
// draw the visualization
bhtransviz.draw = function() {
// variables
var margin = { top: 10, right: 20, bottom: 10, left: 20 };
var width = 600,
height = 600;
var grid = width/bhtransviz.n;
// color scale
var colorScale = d3.scale.quantize()
.domain([1,10])
.range(d3.range(0,9).map(function(i) { return 'q' + i + '-9'; }));
// matrix
var svg = d3.select('#viz').append('svg')
.attr('width', width)
.attr('height', height)
.append('g')
.attr('class', 'routes YlOrRd');
svg.append('rect')
.attr('class', 'background')
.attr('width', width)
.attr('height', height);
// draws each column
var column = svg.selectAll('.column')
.data(bhtransviz.matrix)
.enter().append('g')
.attr('class', 'column')
.attr('transform', function(d, i) {
return 'translate(' + grid*i + ',0)';
}).each(drawColumn);
// legend
var legend = d3.select('#legend').append('svg')
.attr('width', width)
.attr('height', 18)
.append('g')
.attr('class', 'legend YlOrRd');
legend.selectAll('.legend-item')
.data(colorScale.range())
.enter().append('rect')
.attr("width", 18)
.attr("height", 18)
.attr("x", 20)
.attr('class', function(d) { return d; })
.attr("transform", function(d, i) { return "translate(" + i * 20 + ", 0)"; });
legend.append("text")
.attr("x", 0)
.attr("y", 15)
.attr('class', 'legend-text')
.text('1');
legend.append("text")
.attr("x", 210)
.attr("y", 15)
.attr('class', 'legend-text')
.text('> 10');
function drawColumn(column) {
var cell = d3.select(this).selectAll('.cell')
.data(column.filter(function(d) { return d.z.length > 0; }))
.enter().append('rect')
.attr('y', function(d) { return grid*d.y; })
.attr('width', grid)
.attr('height', grid)
.attr('class', function(d) { return 'cell ' + colorScale(d.z.length); })
.on('mouseover', mouseover)
.on('mouseout', mouseout);
}
function mouseover(cell) {
// from neighborhood
d3.select('#tooltip-from')
.text(bhtransviz.nodes[cell.x].name);
// to neighborhood
d3.select('#tooltip-to')
.text(bhtransviz.nodes[cell.y].name);
// grouping bus lines
var busLines = d3.nest()
.key(function(d) { return d.COD_LINH; })
.entries(cell.z);
// number of lines
d3.select('#tooltip-connections')
.text(busLines.length);
// bus list
var list = d3.select('#bus-list')
.selectAll('li')
.data(busLines);
// enter bus code
list.enter()
.append('li')
.attr('class', 'cod-linh')
.text(function(d) {
return d.key;
});
// enter + update
list.text(function(d) {
return d.key;
});
// enter line/subline name
list.selectAll('div')
.data(function(d) {
return d.values;
})
.enter()
.append('div')
.attr('class', 'nom-subl')
.text(function(d) {
return d.NOM_LINH + ' - ' + d.NOM_SUBL;
});
// exit
list.exit().remove();
d3.select('#detail').classed('hidden', false);
}
function mouseout() {
d3.select('#detail').classed('hidden', true);
}
}
d3.json('/data/graph.json', function(error, data) {
if (error) {
console.error(error);
}
else {
// load data
bhtransviz.nodes = data.nodes;
bhtransviz.n = bhtransviz.nodes.length;
// format matrix as an array of arrays
bhtransviz.nodes.forEach(function(node, i) {
bhtransviz.matrix[i] = d3.range(bhtransviz.n).map(function(j) { return {x: i, y: j, z: []}; });
});
for (m in data.matrix) {
for (n in data.matrix[m]) {
m = +m;
n = +n;
bhtransviz.matrix[n][m].z = data.matrix[m][n];
if (bhtransviz.max < bhtransviz.matrix[n][m].z.length) { bhtransviz.max = bhtransviz.matrix[n][m].z.length; }
}
}
// draw visualziation
bhtransviz.draw()
}
});
})();
|
// Ionic Starter App
// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
var app = angular.module('starter', ['ionic', 'ionic-material']);
app.run(function ($ionicPlatform) {
$ionicPlatform.ready(function () {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if (window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if (window.StatusBar) {
StatusBar.styleDefault();
}
});
});
app.config(function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state('app', {
url: '/app',
abstract: true,
templateUrl: 'templates/menu.html'
})
.state('app.schedule-main', {
url: '/schedule-main',
views: {
'menuContent': {
templateUrl: 'templates/schedule-main.html',
controller: 'MainScheduleCtrl'
}
}
})
.state('app.schedule-makercon', {
url: '/schedule-makercon',
views: {
'menuContent': {
templateUrl: 'templates/schedule-makercon.html',
controller: 'MakerConScheduleCtrl'
}
}
})
.state('app.schedule-linux', {
url: '/schedule-linux',
views: {
'menuContent': {
templateUrl: 'templates/schedule-linux.html',
controller: 'LinuxScheduleCtrl'
}
}
})
.state('app.saved-sessions', {
url: '/saved-sessions',
cache: false,
views: {
'menuContent': {
templateUrl: 'templates/saved-sessions.html',
controller: 'SavedSessionsCtrl'
}
}
})
.state('app.map', {
url: '/map',
views: {
'menuContent': {
templateUrl: 'templates/map.html'
}
}
})
.state('app.about', {
url: '/about',
views: {
'menuContent': {
templateUrl: 'templates/about.html'
}
}
})
.state('app.register', {
url: '/register',
views: {
'menuContent': {
templateUrl: 'templates/register.html'
}
}
})
;
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/app/schedule-main');
});
app.run(function ($rootScope, $ionicPopup, $window) {
$rootScope.showEventDetails = function (event) {
if (!event.abstract) {
$ionicPopup.alert({
title: 'Error',
template: 'No info available for this session :('
});
return;
}
$ionicPopup.alert({
title: event.title,
template: event.abstract
});
};
$rootScope.saveEvent = function (event) {
//$ionicPopup.
var savedEvents = $window.localStorage['saved-events'];
if (!savedEvents) {
savedEvents = '[]';
}
savedEvents = JSON.parse(savedEvents);
if (_.find(savedEvents, {'speaker': event.speaker, 'title': event.title})) {
$ionicPopup.alert({
template: 'Session already saved!'
});
} else {
savedEvents.push(event);
$window.localStorage['saved-events'] = JSON.stringify(savedEvents);
$ionicPopup.alert({
title: 'Session saved',
template: "Find all the sessions you've saved in the side menu"
});
}
};
});
|
var Observable = require("FuseJS/Observable");
var GeoLocation = require("FuseJS/GeoLocation");
var Model = require('Sanntidsappen/Model');
var StopsList = require('Assets/Stops');
var search_string = Observable('');
var search_results = Observable();
var distancePresent = Observable();
var stops = Observable();
search_string.onValueChanged(function (item) {
distancePresent.value = false;
if (item.length > 2) {
search_results.replaceAll(StopsList.filter(function (stop) {
return stop.name.toUpperCase().indexOf(search_string.value.toUpperCase()) > -1;
}));
stops.replaceAll(search_results)
}
else {
search_results.clear();
}
});
// GeoLocations
// Gets nearest stops using the devices current location
var continuousLocation = GeoLocation.observe('changed')
var intervalMs = 1000;
var desiredAccuracyInMeters = 20;
GeoLocation.startListening(intervalMs, desiredAccuracyInMeters);
continuousLocation.onValueChanged(function (val) {
if (search_results.length === 0) {
if (val && val.latitude && val.longitude) {
stops = Model.GetNearestStops(val.latitude, val.longitude).inner();
distancePresent.value = true;
} else {
stops.replaceAll(StopsList.slice(33, 50));
distancePresent.value = false;
}
}
});
module.exports = {
distancePresent,
search_string: search_string,
search_results: search_results,
stops: stops
}
|
// Copyright 2019 Mathias Bynens. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
author: Mathias Bynens
description: >
Unicode property escapes for `Script=Myanmar`
info: |
Generated by https://github.com/mathiasbynens/unicode-property-escapes-tests
Unicode v12.1.0
esid: sec-static-semantics-unicodematchproperty-p
features: [regexp-unicode-property-escapes]
includes: [regExpUtils.js]
---*/
const matchSymbols = buildString({
loneCodePoints: [],
ranges: [
[0x001000, 0x00109F],
[0x00A9E0, 0x00A9FE],
[0x00AA60, 0x00AA7F]
]
});
testPropertyEscapes(
/^\p{Script=Myanmar}+$/u,
matchSymbols,
"\\p{Script=Myanmar}"
);
testPropertyEscapes(
/^\p{Script=Mymr}+$/u,
matchSymbols,
"\\p{Script=Mymr}"
);
testPropertyEscapes(
/^\p{sc=Myanmar}+$/u,
matchSymbols,
"\\p{sc=Myanmar}"
);
testPropertyEscapes(
/^\p{sc=Mymr}+$/u,
matchSymbols,
"\\p{sc=Mymr}"
);
const nonMatchSymbols = buildString({
loneCodePoints: [],
ranges: [
[0x00DC00, 0x00DFFF],
[0x000000, 0x000FFF],
[0x0010A0, 0x00A9DF],
[0x00A9FF, 0x00AA5F],
[0x00AA80, 0x00DBFF],
[0x00E000, 0x10FFFF]
]
});
testPropertyEscapes(
/^\P{Script=Myanmar}+$/u,
nonMatchSymbols,
"\\P{Script=Myanmar}"
);
testPropertyEscapes(
/^\P{Script=Mymr}+$/u,
nonMatchSymbols,
"\\P{Script=Mymr}"
);
testPropertyEscapes(
/^\P{sc=Myanmar}+$/u,
nonMatchSymbols,
"\\P{sc=Myanmar}"
);
testPropertyEscapes(
/^\P{sc=Mymr}+$/u,
nonMatchSymbols,
"\\P{sc=Mymr}"
);
|
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
info: The production x |= y is the same as x = x | y
es5id: 11.13.2_A4.11_T2.4
description: >
Type(x) is different from Type(y) and both types vary between
Number (primitive or object) and Undefined
---*/
//CHECK#1
x = 1;
x |= undefined;
if (x !== 1) {
$ERROR('#1: x = 1; x |= undefined; x === 1. Actual: ' + (x));
}
//CHECK#2
x = undefined;
x |= 1;
if (x !== 1) {
$ERROR('#2: x = undefined; x |= 1; x === 1. Actual: ' + (x));
}
//CHECK#3
x = new Number(1);
x |= undefined;
if (x !== 1) {
$ERROR('#3: x = new Number(1); x |= undefined; x === 1. Actual: ' + (x));
}
//CHECK#4
x = undefined;
x |= new Number(1);
if (x !== 1) {
$ERROR('#4: x = undefined; x |= new Number(1); x === 1. Actual: ' + (x));
}
|
"use strict";
//include all required helper files
const express = require('express');
const router = express.Router();
const cms = require('../../cms.js');
const mongoose = require('mongoose');
const Shuttle = require("../../schema/shuttle.js");
const helperLib = require("../../helper.js").helpers;
const eventEmitter = require('../../app').eventEmitter;
const helper = new helperLib();
module.exports = router;
router.post('/', (req, res) => {
//checks if the user is logged in
if (!req.session || !req.session.cas_user) {
res.status(401);
res.send("You must be logged in to complete this action.");
return;
}
var rcs_id = req.session.cas_user.toLowerCase();
//checks if user is an administrator
if (helper.isAdmin(rcs_id)) {
var shuttleID = req.body.id;
//if so, find the shuttle and change it to inactive
Shuttle.findOneAndUpdate({
_id: shuttleID
}, {
isActive: false
}, (err) => {
if (err) {
res.send("There was an issue cancelling shuttle " + shuttleID);
return;
}
var webSocketResponse = {type: "cancel_shuttle", shuttleID: shuttleID};
eventEmitter.emit('websocket-admin', JSON.stringify(webSocketResponse));
eventEmitter.emit('websocket', JSON.stringify(webSocketResponse));
res.send("Shuttle " + shuttleID + " sucessfully cancelled.");
return;
});
} else {
//if the user is not an admin, deny access
res.status(403);
res.send("You don't seem authorized for this action.");
}
});
|
/* Copyright (c) 2012, Ben Trask
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE AUTHORS ''AS IS'' AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
/* This is incomplete and unused. It was designed to replace "EasyIndex" with a real, scalable data structure. */
var fs = require("../external/fs+");
var ReadWriteQueue = require("./ReadWriteQueue");
function asyncLoop(func/* (next) */) { // TODO: Put this somewhere too.
var called, finished;
for(;;) {
called = false;
finished = false;
func(function next() {
called = true;
if(finished) asyncLoop(func);
});
finished = true;
if(!called) break;
}
}
function equalBuffers(a, b) {
var l = a.length; // We assume the buffers are equal length.
for(var i = 0; i < l; ++i) if(a[i] !== b[i]) return false;
return true;
}
function queueable(callback, func) {
return function(done) {
func(function(arg1, arg2, etc) {
done();
if(callback) callback.apply(this, arguments);
});
};
}
function PersistentIndex(path, bytes) {
var a = this;
a.path = path;
a.bytes = bytes;
a.fd = null;
a.length = null;
a.queue = new ReadWriteQueue();
}
PersistentIndex.prototype.open = function(callback/* (err) */) {
var a = this;
a.queue.write(queueable(callback, function(callback) {
if(null !== a.fd) return callback(new Error("PersistentIndex already open"));
fs.open(a.path, "ax+", function(err, fd) {
if(err) return callback(err);
fs.fstat(fd, function(err, stats) {
if(err) return callback(err);
a.fd = fd;
a.length = stats.size / a.bytes;
callback(null);
});
});
}));
};
PersistentIndex.prototype.close = function(callback/* (err) */) {
var a = this;
a.queue.write(queueable(callback, function(callback) {
if(null === a.fd) return callback(new Error("PersistentIndex already closed"));
fs.close(a.fd, function(err) {
if(err) return callback(err);
a.fd = null;
callback(null);
});
}));
};
PersistentIndex.prototype.append = function(buffer, callback/* (err) */) {
var a = this;
a.queue.write(queueable(callback, function(callback) {
var l = a.length * a.bytes;
if(a.bytes !== buffer.length) return callback(new Error("PersistentIndex appending wrong sized value"));
fs.writeAll(a.fd, buffer, 0, buffer.length, l, function(err) {
if(err) return callback(err);
++a.length;
callback(null);
});
}));
};
PersistentIndex.prototype.read = function(index, length, callback/* (err, buffer) */) {
var a = this;
a.queue.read(queueable(callback, function(callback) {
if(length <= 0) return callback(new Error("PersistentIndex read with invalid length"), null);
if(index < 0) return callback(new Error("PersistentIndex read below bounds"), null);
if(index+length > a.length) return callback(new Error("PersistentIndex read beyond bounds"), null);
var buffer = new Buffer(length * a.bytes);
fs.readAll(a.fd, buffer, 0, buffer.length, index * a.bytes, function(err) {
if(err) return callback(err, null);
callback(null, buffer);
});
}));
};
PersistentIndex.intersect = function(array, result, callback) {
array.sort(function(a, b) {
return a.length - b.length;
});
};
function intersect(a, indexA, lengthA, b, indexB, lengthB, target, callback/* (err) */) {
if(!lengthA || !lengthB) return callback(null);
a.queue.read(queueable(callback, function(callback) {
var middle = Math.floor(lengthA / 2) + indexA;
var offset = 0;
var sign = 1;
var iA = middle;
asyncLoop(function(next) {
if(iA < 0 || iA >= indexA+lengthA) return callback(err);
a.read(iA, 1, function(err, pivot) {
linearSearch(b, indexB, lengthB, pivot, function(err, iB) {
if(err) return callback(err);
if(-1 === iB) {
++offset;
iA = middle + offset*sign;
sign *= -1;
return next();
}
intersect(a, indexA, ia, b, indexB, ib, function(err) {
target.append(pivot);
intersect(a, indexA+iA+1, lengthA-iA-1, b, indexB+iB+1, lengthB-iB-1, callback);
});
});
});
});
}));
}
function linearSearch(a, index, length, val, callback/* (err, index) */) {
a.queue.read(queueable(callback, function(callback) {
var i = index;
asyncLoop(function(next) {
if(i >= index+length) return callback(null, -1);
a.read(i, 1, function(err, buffer) {
if(err) return callback(err, null);
if(equalBuffers(val, buffer)) return callback(null, i);
++i;
next();
});
});
}));
}
|
/**
* @license Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.editorConfig = function( config ) {
// Define changes to default configuration here. For example:
// config.language = 'fr';
// config.uiColor = '#AADC6E';
config.language = 'ru';
config.allowedContent = true;
/*config.toolbar = [
{ name: 'document', items: [ 'Source'] },
{ name: 'clipboard', items: [ 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo','RemoveFormat' ] },
{ name: 'basicstyles', items: [ 'Bold', 'Italic','Underline','Strike','-','Subscript','Superscript' ] },
{ name: 'fomated', items: [ 'Format','Font','FontSize','JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock','Link','Unlink','Anchor','Image','Flash','NumberedList','BulletedList','CreateDiv' ] }
];*/
};
|
editArea.add_lang("en",{
new: "New Document"
});
|
$(function() {
function request_permission() {
// Try to get permission to show Notifications
if (window.Notification && Notification.permission !== "granted") {
Notification.requestPermission(function (status) {
if (Notification.permission !== status) {
Notification.permission = status;
}
});
}
}
$('#request_permission').click(function(){ request_permission(); return false; });
function notify(input) {
var icon_url = "/static/img/notification_medium.png";
var title = input.show.user.names + " started streaming";
if (input.show.name) {
var body = "Show: " + input.show.name;
}
else {
var body = "Show has no name ;_;";
}
if (window.Notification && Notification.permission === "granted") {
var n = new Notification(title, {body: body, icon: icon_url, tag: 'show_start'});
}
}
setTimeout(function() {
$(document).on('show_started', notify);
$(document).on('show_changed', notify);
}, 5000);
});
|
/**
* @license
* Copyright (c) 2017 The expand.js authors. All rights reserved.
* This code may only be used under the BSD style license found at https://expandjs.github.io/LICENSE.txt
* The complete set of authors may be found at https://expandjs.github.io/AUTHORS.txt
* The complete set of contributors may be found at https://expandjs.github.io/CONTRIBUTORS.txt
*/
const _isArray = require('lodash/isArray'),
isVoid = require('./isVoid'),
xnor = require('./xnor');
/**
* Checks if `value` is an instance of `Array`.
*
* ```js
* XP.isArray([1, 2, 3]);
* // => true
*
* XP.isArray([], true);
* // => false
*
* XP.isArray(function () { return arguments; }());
* // => false
* ```
*
* @function isArray
* @since 1.0.0
* @category tester
* @description Checks if `value` is an instance of `Array`
* @source https://github.com/expandjs/expandjs/blog/master/lib/isArray.js
*
* @param {*} value The target value
* @param {boolean} [notEmpty] Specifies if `value` must be not empty
* @returns {boolean} Returns `true` or `false` based on the check
*/
module.exports = function isArray(value, notEmpty) {
// Returning
return _isArray(value) && (isVoid(notEmpty) || xnor(value.length, notEmpty));
};
|
/**
* @license
* Copyright (c) 2018 The Polymer Project Authors. All rights reserved.
* This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
* The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
* The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
* Code distributed by Google as part of the polymer project is also
* subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
*/
/* eslint-env node */
module.exports = {
staticFileGlobs: [
'src/**/*',
'manifest.json',
'data/*',
'images/*'
],
runtimeCaching: [
{
urlPattern: /\/@webcomponents\/webcomponentsjs\//,
handler: 'fastest'
}
],
navigateFallback: 'index.html',
navigateFallbackWhitelist: [/^(?!.*\.html$|\/data\/).*/]
};
|
/* **
* super百变魔方脚本
* author: revege
* time: 2016-01-04 19:42:26
*/
function resetSuper(){
// 初始化百变魔方下的a
resetSuperA();
// 初始化百变魔方下的表单提交
resetSuperForm();
}
// 初始化百变魔方下的a标签
function resetSuperA(){
$("#super").find("a").click(function(){
var src = $(this).attr("href");
if($(this).attr("mini") == "act"){
SuperAdel(src);
}else{
SuperAget(src);
}
return false;
});
}
// Super a普通获取方法
function SuperAget(src){
messages(2, "正在载入",111);
$.ajax({
type : 'GET',
url : src,
success : function(msg){
messages(1, "载入成功",0.5);
$("#super").html(msg);
$("#super").attr("href",src);
resetSuper();
}
});
}
// Super a 删除方法
function SuperAdel(src){
if(confirm("请确定?")){
messages(2,"请稍等");
$.ajax({
type : 'GET',
url : src,
dataType : 'json',
success : function(msg){
if(msg.statu == "success"){
messages(1,msg.des);
// 重置super
SuperAget($("#super").attr("href"));
}else{
messages(0,msg.des);
}
}
});
}
}
// 初始化百变魔方下的表单
function resetSuperForm(){
$("#super").find("form").submit(function(){
messages(2,"请稍等"); // 载入模式
// 获取数据
var src = $(this).attr("action");
var method = $(this).attr("method") ? $(this).attr("method") : "POST";
var data = $(this).serialize();
// 查看提交表单类型 提交/搜索
if($(this).attr("name") === "serch"){
var thisrc = src + "?" + data;
messages(1,"查询成功!");
SuperAget(thisrc);
}else{
// close submit
var sbumit = $(this).find("input[type='submit']");
sbumit.attr('disabled', 'disabled');
// send ajax
$.ajax({
type : method,
data : data,
url : src,
dataType: 'json',
success : function(msg){
if(msg.statu === "error"){
messages(0,msg.des);
sbumit.removeAttr('disabled');
}else{
messages(1,msg.des);
// 重置super
$("#super").attr("href",msg.jump);
$.ajax({
type : 'GET',
url : msg.jump,
success : function(msg){
$("#super").html(msg);
resetSuper();
}
});
}
}
});
}
return false;
});
}
function submit(formName){
$("form[name = '"+ formName +"']").submit();
}
|
var fs = require('fs');
var os = require('os');
module.exports = _touch
function _touch(filepath){
fs.closeSync(fs.openSync(filepath, 'w'));
}
// exports = _touch ;
|
module.exports = function config(grunt, config) {
config.selenium.test.env.push('IDENTITY="<%= userCfg.authentication.identity %>"');
config.selenium.test.env.push('CREDENTIAL="<%= userCfg.authentication.credential %>"');
};
|
import { showcaseConverter } from "@times-components/storybook";
import showcase from "./edition-puzzle-tiles.showcase";
showcaseConverter(module, showcase);
|
/**
* Copyright (c) 2016, Foothill-De Anza Community College District
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
'use strict';
let BannerOperations = require('../../BannerOperations.js');
let CollegeManager = require('../../CollegeManager.js');
let Logger = require('fhda-pubsub-logging')('ws-action-get-canv-courses');
let WebsocketUtils = require('../../WebsocketUtils.js');
/**
* Handle a websocket request to get a list of Canvas courses currently
* associated with the identified user.
* @param {Object} data Event data payload
* @param {Function} respond Callback function to send a response back to the client
* @return {Promise} Resolved when the operation is complete
*/
module.exports = async function (data, respond) {
// Capture audit record
await BannerOperations.recordWebAudit(
this.decoded_token.aud,
'canvas:getCourses',
data,
this.conn.remoteAddress);
// Lookup college configuration
let college = CollegeManager[data.college];
await college
.canvasApi.getCoursesForUser(
data.term,
this.decoded_token.aud,
data.withSections,
['teacher'])
.map(course => {
// Decorate course with promise to check on content migrations
course.migrations = college.canvasApi.listActiveMigrations(course.id);
// Resolve
return Promise.props(course);
})
.tap(result => {
Logger.info('Result of getting courses from Canvas', result);
respond(result);
})
.catch(WebsocketUtils.handleError.bind(
this,
'A serious error occurred while attempting to lookup course memberships in Canvas',
Logger,
respond
));
};
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Component = Component;
var _react = _interopRequireDefault(require("react"));
var _useTheme = _interopRequireDefault(require("./useTheme"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* 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.
*
* @flow
*/
function Component() {
const theme = (0, _useTheme.default)();
return /*#__PURE__*/_react.default.createElement("div", null, "theme: ", theme);
}
//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIkNvbXBvbmVudFdpdGhFeHRlcm5hbEN1c3RvbUhvb2tzLmpzIl0sIm5hbWVzIjpbIkNvbXBvbmVudCIsInRoZW1lIl0sIm1hcHBpbmdzIjoiOzs7Ozs7O0FBU0E7O0FBQ0E7Ozs7QUFWQTs7Ozs7Ozs7QUFZTyxTQUFTQSxTQUFULEdBQXFCO0FBQzFCLFFBQU1DLEtBQUssR0FBRyx3QkFBZDtBQUVBLHNCQUFPLHFEQUFhQSxLQUFiLENBQVA7QUFDRCIsInNvdXJjZXNDb250ZW50IjpbIi8qKlxuICogQ29weXJpZ2h0IChjKSBGYWNlYm9vaywgSW5jLiBhbmQgaXRzIGFmZmlsaWF0ZXMuXG4gKlxuICogVGhpcyBzb3VyY2UgY29kZSBpcyBsaWNlbnNlZCB1bmRlciB0aGUgTUlUIGxpY2Vuc2UgZm91bmQgaW4gdGhlXG4gKiBMSUNFTlNFIGZpbGUgaW4gdGhlIHJvb3QgZGlyZWN0b3J5IG9mIHRoaXMgc291cmNlIHRyZWUuXG4gKlxuICogQGZsb3dcbiAqL1xuXG5pbXBvcnQgUmVhY3QgZnJvbSAncmVhY3QnO1xuaW1wb3J0IHVzZVRoZW1lIGZyb20gJy4vdXNlVGhlbWUnO1xuXG5leHBvcnQgZnVuY3Rpb24gQ29tcG9uZW50KCkge1xuICBjb25zdCB0aGVtZSA9IHVzZVRoZW1lKCk7XG5cbiAgcmV0dXJuIDxkaXY+dGhlbWU6IHt0aGVtZX08L2Rpdj47XG59XG4iXX0=
|
/**
* Copyright (c) 2011-2021 Berkeley Model United Nations. All rights reserved.
* Use of this source code is governed by a BSD License (see LICENSE).
+*/
//@flow
"use strict";
import React from "react";
import type { Note } from "utils/types";
// $FlowFixMe
require("css/notes/NoteConversationPreview.less");
type NoteConversationPreviewProps = {
recipient_name: ?string,
country: string,
last_message: ?Note,
};
type NoteConversationPreviewState = {
selected: ?string,
};
class NoteConversationPreview extends React.Component<
NoteConversationPreviewProps,
NoteConversationPreviewState
> {
constructor(props: NoteConversationPreviewProps) {
super(props);
this.state = {
selected: null,
};
}
render(): React$Element<any> {
const last_message_string = this.props.last_message
? this.props.last_message.msg
: "";
const textClass =
this.props.country == this.props.recipient_name
? "countryNameSelected"
: "countryName";
return (
<div className="conversationPreview">
<div className="conversationPreviewText">
<div className={textClass}>{this.props.country}</div>
{last_message_string}
</div>
</div>
);
}
}
export { NoteConversationPreview };
|
import { DEFAULT_LOCALE, LOCALE_KEY } from './../../../constants';
// action types
export const CHANGE_LOCALE_SUCCESS = 'LOCALE/CHANGE_LOCALE';
// action creators
export const changeLocaleSuccess = locale => ({
type: CHANGE_LOCALE_SUCCESS,
locale,
});
// thunks
export const changeLocale = locale => async dispatch => {
dispatch(changeLocaleSuccess(locale));
};
// reducer
const initialState = DEFAULT_LOCALE;
export default (state = initialState, action) => {
switch (action.type) {
case CHANGE_LOCALE_SUCCESS: {
return action.locale;
}
default: {
return state;
}
}
};
|
function onb1(){
alert("hello");
}
|
(function ($) {
$.executePost = function (postModel, sync, hideSpinner) {
if (!hideSpinner) {
$.showSpinner();
}
var request = $.ajax({
url: postModel.action,
method: postModel.method,
data: postModel.data,
async: sync !== 1,
//contentType:"application/json; charset=utf-8",
dataType: postModel.dataType
});
request.done(function (response) {
if (!hideSpinner) {
$.hideSpinner();
}
if (response.status) {
if (typeof response.data === "string") {
response.data = JSON.parse(response.data);
}
if (postModel.successMsg) {
$.showMsg("success", postModel.successMsg, postModel.success(response.data));
}else{
postModel.success(response.data);
}
} else {
if (response.message) {
$.showMsg("error", response.message);
} else if (postModel.errorMsg) {
$.showMsg("error", postModel.errorMsg);
} else {
$.showMsg("error", "Ocurrió un error en la transacción.");
}
}
});
request.fail(function (jqXHR, textStatus) {
if (!hideSpinner) {
$.hideSpinner();
}
$.showMsg("error", jqXHR.responseText);
});
}
$.executePostValid = function (postModel) {
postModel.data = $(postModel.form).serialize();
//console.log($(postModel.form).valid());
if ($(postModel.form).valid() && $(postModel.form).valid()) {
$.executePost(postModel);
}
}
$.preparePostValid = function (postModel) {
$(postModel.btn).click(function (e) {
$.executePostValid(postModel);
});
}
$.executeFetch = function (postModel) {
$.executePost(postModel);
}
$.executeSyncFetch = function (postModel) {
$.executePost(postModel, 1, true);
}
})(jQuery);
|
var $ = require('jquery');
var subscriptionTemplate = require('text!./subscription.html');
/**
* Composition plan for the data-newsletter-subscription feature.
* @module
*/
module.exports = initNewsletterSubscription;
/**
* Injects the newsletter subscriptioniframe and makes it visible only
* after it has fully loaded.
* @returns {{destroy: Function}}
*/
function initNewsletterSubscription() {
// The iframe was previously inline in layout.html, and thus loaded
// its content synchronously, delaying DOMReady. Since most of the site's
// JavaScript-driven features can't fully initialize until DOMReady, this was
// delaying lots of feature initialization that could have been proceeding
// in parallel. By injecting it dynamically, it doesn't block DOMReady.
$(function() {
var subscription = $(subscriptionTemplate);
subscription
.appendTo($('.footer-newsletter--wrapper'))
.find('iframe')
.load(function() {
// This should use an oocss state, like .loading instead
// of bootstrap's .invisible, but going with .invisible until
// there's time for CSS refactoring
subscription.removeClass('invisible');
});
});
return {
destroy: function() {}
};
}
|
var searchData=
[
['renderloopinterval',['RenderLoopInterval',['../namespacens_game_1_1ns_config.html#a177402f6759e85b27f51aa9e073de896',1,'nsGame::nsConfig']]],
['roundcount',['RoundCount',['../structns_game_1_1_s_game_mode.html#a7565197ae8453df86f14d5cb0d40d19c',1,'nsGame::SGameMode']]],
['run',['Run',['../namespacens_game.html#a65ba644eceafea8b89f17e95c481d201',1,'nsGame::Run()'],['../namespacens_menu.html#a6320374997c73f3c7ec9e62e7976129e',1,'nsMenu::Run()']]]
];
|
var test = require('test');
var extensionRe = /([^\/]+)\.extension$/;
var ExtensionLoader = function (config, load) {
return function (id, module) {
var match = extensionRe.exec(id);
if (match) {
module.redirect = id + "/" + match[1];
return module;
} else {
return load(id, module);
}
};
};
var config = {};
config.makeLoader = function (config) {
return ExtensionLoader(config, require.config.makeLoader(config));
};
return require.loadPackage(module.directory, config)
.then(function (packageRequire) {
return packageRequire.async("a.extension");
})
.then(function (aExports) {
test.assert(aExports === 10, 'require with extension loader');
test.print('DONE', 'info');
});
|
import React from 'react'
import PropTypes from 'prop-types'
import Scrollchor from 'react-scrollchor'
import Waypoint from 'react-waypoint'
import { text2paraJsx, splitIntoSpansJsx } from '../../lib'
import {
PetitionCard,
Details,
Container,
SignColumn,
InfoColumn,
MobileSign,
FloatingSignButton
} from 'GiraffeUI/petition'
import PetitionMessage from 'Theme/petition-message'
import { Share } from './petition-share'
import SignatureAddForm from '../../containers/signature-add-form'
import SignatureList from '../../containers/signature-list'
import CobrandLogo from '../../containers/cobrand-logo'
const Petition = ({
petition: p,
query,
user,
adminLink,
petitionBy,
isFloatingSignVisible,
scrollToSignFormProps,
hideFloatingSign,
showFloatingSign,
setRef
}) => (
<Container>
<PetitionMessage petition={p} isFwd={query.fwd} />
<InfoColumn>
<PetitionCard
heading={splitIntoSpansJsx(p.title)}
currentSignatures={p.total_signatures}
goalSignatures={p.signature_goal}
renderShare={<Share className='petition-card' user={user} petition={p} />}
renderSignersButton={({ className, CaretRight }) => (
<Scrollchor
className={className}
to='#comments'
animate={{ offset: -150 }}
disableHistory
>
MOST RECENT SIGNERS <CaretRight />
</Scrollchor>
)}
>
<p className='pt-3'>To be delivered to {p.target.map(t => t.name).join(', ')}</p>
{adminLink && (
<a style={{ position: 'absolute', top: 10, right: 10 }} href={adminLink}>
zoom ✎
</a>
)}
{p.featured_image_url && <PetitionCard.Media imageUrl={p.featured_image_url} />}
{p.summary && (
<PetitionCard.Description>
{text2paraJsx(p.summary)}
</PetitionCard.Description>
)}
</PetitionCard>
<MobileSign>
<Waypoint onEnter={hideFloatingSign} onLeave={showFloatingSign} topOffset='57px'>
<SignatureAddForm
id='mobile-sign'
setRef={setRef({ isMobile: true })}
petition={p}
query={query}
/>
</Waypoint>
</MobileSign>
<Details>
<Details.Narrative heading='Background'>
{/* eslint-disable-next-line react/no-danger */}
<div dangerouslySetInnerHTML={{ __html: p.description }} />
</Details.Narrative>
<Details.Comments heading='Most Recent Signers'>
<SignatureList petition={p} signatureCount={p.total_signatures} />
</Details.Comments>
<Details.Author
name={petitionBy}
logo={<CobrandLogo />}
link={`/contact_creator.html?petition_id=${p.petition_id}`}
/>
<Share className='petition-details' hasLabels user={user} petition={p} />
<Details.Disclaimer entity={p.entity} />
</Details>
</InfoColumn>
<SignColumn>
<Waypoint onEnter={hideFloatingSign} onLeave={showFloatingSign} topOffset='120px'>
<SignatureAddForm
id='desktop-sign'
setRef={setRef({ isMobile: false })}
petition={p}
query={query}
/>
</Waypoint>
</SignColumn>
<FloatingSignButton
getScrollProps={scrollToSignFormProps}
visible={isFloatingSignVisible}
/>
</Container>
)
Petition.propTypes = {
petition: PropTypes.object.isRequired,
user: PropTypes.object,
adminLink: PropTypes.oneOfType([PropTypes.bool, PropTypes.string]),
query: PropTypes.object,
petitionBy: PropTypes.string,
setRef: PropTypes.func,
scrollToSignFormProps: PropTypes.func,
isFloatingSignVisible: PropTypes.bool,
hideFloatingSign: PropTypes.func,
showFloatingSign: PropTypes.func
}
export default Petition
|
import React from 'react';
export class Columns extends React.PureComponent {
render() {
return (
<Container
columns={this.props.columns.length}
ratios={this.props.columns.map(([, v]) => v)}
>
{this.props.columns.map(([column], key) => {
return <Column key={key}>{column}</Column>;
})}
</Container>
);
}
}
export class Container extends React.Component {
createColumnStyle(width) {
return {
float: 'left',
boxSizing: 'border-box',
width: width.toString() + '%',
};
}
get containerStyle() {
return {
content: '',
display: 'table',
width: '100%',
};
}
get columnStyles() {
let { columns, ratios } = this.props;
let result = [];
ratios = ratios || [];
if (!columns) {
return result;
}
if (ratios.length) {
// sum of rations
const total = ratios.reduce((a, b) => a + b, 0);
// percentage widths of each column
const widths = ratios.map((column) => (column / total) * 100);
// give each column the correct width
widths.map((width) => result.push(this.createColumnStyle(width)));
return result;
} else {
// give each column an equal share
return [
...Array(columns)
.fill()
.map(() => this.createColumnStyle(100 / columns)),
];
}
}
render() {
let { children } = this.props;
return (
<div className='container' style={this.containerStyle}>
{React.Children.map(children || [], (child, key) => {
let columnStyle = {};
if (this.columnStyles.length >= key) {
columnStyle = this.columnStyles[key];
}
return (
<div key={key} style={columnStyle || {}}>
{child}
</div>
);
})}
</div>
);
}
}
export class Column extends React.PureComponent {
render() {
const { className } = this.props;
let _className = 'column';
if (className) {
_className = _className + ' ' + className;
}
return <div className={_className}>{this.props.children}</div>;
}
}
|
var A = 1;
var foo = function()
/*: () / (&A |-> _:Int) -> Int / (&A |-> _:Int) */
{ return A; };
var i = foo(); assert (typeof i == "number");
assert (typeof foo() == "number");
|
$(".fileinput-button").each(function(){
imageupload($(this));
});
$(document).on('click', ".fileinput-remove", function(){
if ($(this).hasClass('disabled')) return;
removeImage($(this));
});
$(document).on('click', ".sel-part-button", function(){
$($(this).data('target')).data('button', $(this));
});
$('body').on('click','[data-img-choose]',function(){
var self = $(this);
var modal = self.parents('.modal');
var button = modal.data('button');
modal.modal('hide');
if(self.attr('data-id')){
$.ajax({
url: "/images/participant/" + self.attr('data-id'),
dataType: "json",
success: function (data) {
if (data.success) {
var r = data.result;
setImage(button, data.filename, data.src);
} else {
addUploadError(button, data.error);
}
},
error: function (e, data) {
alert("Ошибка сервера");
}
});
}
});
$(document).on('keyup','.participant-filter',(function(){
var buff;
var delay = 300;
var blockClass = '.media-list';
var elemClass = '.media';
var valClass = '.media-heading';
var titleClass = 'h3';
return function(){
var self = $(this);
var modal = self.parents('.modal');
var blocks = modal.find(blockClass);
clearTimeout(buff);
buff = setTimeout(function(){
$.each(blocks,function(iB, block){
var currBlock = $(block);
var elements = currBlock.find(elemClass);
var hidden = true;
$.each(elements, function(iE, element){
var currElement = $(element);
var isMatch = currElement.find(valClass).text().match(new RegExp(self.val(),'ig'));
if(isMatch){
hidden = false;
currElement.fadeIn(0);
}else{
currElement.fadeOut(0);
}
});
if(hidden){
currBlock.fadeOut(0);
currBlock.prev(titleClass).fadeOut(0);
}else{
currBlock.fadeIn(0);
currBlock.prev(titleClass).fadeIn(0);
}
});
},delay);
};
})());
function addUploadError(button, error)
{
var container = button.parents('.form-group');
container.addClass('has-error');
container.find(".help-block-error").text(error);
}
function removeImage(button)
{
var container = button.parents('.form-group');
container.removeClass('has-error').find(".help-block-error").text('');
container.find(".uploaded-image").html('');
container.find('.input-filename').val('');
container.find(".fileinput-remove").addClass('disabled');
}
function setImage(button, filename, src)
{
button.parents('.form-group').removeClass('has-error').find(".help-block-error").text('');
button.find('.input-filename').val(filename);
if (filename) {
var img = new Image();
img.src = src;
img.onload = function(){addSizes(this);};
button.parents('.form-group').find(".uploaded-image").html(img);
button.parents('.form-group').find(".fileinput-remove").removeClass('disabled');
} else {
removeImage(button);
}
}
function imageupload(button)
{
var type = button.data('type');
var container = button.parents('.form-group');
button.fileupload({
url: "/images/upload/" + type,
dataType: "json",
done: function (e, data) {
if (data.result.success) {
var r = data.result;
setImage(button, r.filename, r.src);
} else {
addUploadError(button, data.result.error);
}
},
error: function (e, data) {
alert("Ошибка сервера");
}
});
}
|
const Backbone = require('backbone');
const checkAndBuildOpts = require('builder/helpers/required-opts');
const REQUIRED_OPTS = [
'configModel'
];
module.exports = Backbone.Model.extend({
initialize: function (opts) {
checkAndBuildOpts(opts, REQUIRED_OPTS, this);
},
isUserAuthentication: function () {
return !!this._configModel.get('oauth_bigquery');
},
isServiceAuthentication: function () {
return this._configModel.get('bigquery_uses_service_auth');
},
hasAnyAuthMethod: function () {
return this.isUserAuthentication() || this.isServiceAuthentication();
}
});
|
(function() {
'use strict';
angular.module('GNAdmin.skills', []);
}());
|
/**
* Garp cookie helper utilities
*/
if (typeof Garp === 'undefined') {
var Garp = {};
}
Garp.Cookie = {};
/**
* Grab a Cookie
* @param {Object} name
*/
Garp.Cookie.get = function(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0, cal = ca.length; i < cal; ++i) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1, c.length);
}
if (c.indexOf(nameEQ) === 0) {
return c.substring(nameEQ.length, c.length);
}
}
return null;
};
/**
* Set a cookie
* @param {Object} name
* @param {Object} value
* @param {Date} expiration date
* @param {String} domain
*/
Garp.Cookie.set = function(name, value, date, domain) {
value = escape(value) + "; path=/";
if (domain) {
value += '; domain=' + escape(domain);
}
value += (!date ? "" : "; expires=" + date.toGMTString());
document.cookie = name + "=" + value;
};
Garp.Cookie.remove = function(name) {
Garp.setCookie(name,'',new Date('1900'));
};
|
var Backbone = require('backbone');
require('backbone-forms');
var ExportImageFormModel = require('../../../../../javascripts/cartodb3/editor/export-image-pane/export-image-form-model');
describe('editor/layers/layer-content-views/analyses/analysis-form-models/centroid-form-model', function () {
beforeEach(function () {
this.model = new ExportImageFormModel({
userModel: new Backbone.Model(),
hasGoogleBasemap: false,
format: '.png',
x: 10,
y: 100,
width: 300,
height: 200
});
});
it('should generate schema', function () {
expect(this.model.schema).toBeDefined();
});
it('should show a validation error when width is too big', function () {
this.model.set({ width: 200000 });
var form = new Backbone.Form({
model: this.model
});
var validation = form.getEditor('width').validate();
expect(validation.message).toBe('editor.export-image.invalid-dimension');
});
it('should show a validation error when height is too big', function () {
this.model.set({ height: 200000 });
var form = new Backbone.Form({
model: this.model
});
var validation = form.getEditor('height').validate();
expect(validation.message).toBe('editor.export-image.invalid-dimension');
});
it('should have generated form fields', function () {
expect(Object.keys(this.model.schema).length).toBe(3);
});
});
|
'use strict';
const { startsWith, over, lensIndex, replace } = require('ramda');
const aliases = (obj) => {
const propNames = Object.getOwnPropertyNames(obj);
return propNames
.filter(startsWith('fantasy-land/'))
.reduce((accumulator, propName) => {
accumulator.push([propName, obj[propName]]);
return accumulator;
}, [])
.map(over(lensIndex(0), replace('fantasy-land/', '')));
};
/* eslint-disable no-param-reassign */
const aliasesForType = (type) => {
aliases(type).forEach(([alias, fn]) => {
type[alias] = fn;
});
aliases(type.prototype).forEach(([alias, fn]) => {
type.prototype[alias] = fn;
});
};
/* eslint-enable */
module.exports = {
aliases,
aliasesForType,
};
|
import React from 'react';
import {withInfo} from '@storybook/addon-info';
import styled from '@emotion/styled';
import UserMisery from 'app/components/userMisery';
export default {
title: 'DataVisualization/ScoreBar/UserMisery',
};
export const Default = withInfo(
'Visualization of user misery to allow users to more easily understand performance at a glance'
)(() => (
<Container>
<UserMisery
bars={10}
barHeight={20}
miseryLimit={300}
miserableUsers={75}
totalUsers={100}
/>
</Container>
));
Default.story = {
name: 'default',
};
export const Large = withInfo('Both length and height of the component can be modified')(
() => (
<Container>
<UserMisery
bars={40}
barHeight={30}
miseryLimit={300}
miserableUsers={75}
totalUsers={100}
/>
</Container>
)
);
Large.story = {
name: 'large',
};
export const Empty = withInfo('Empty state')(() => (
<Container>
<UserMisery
bars={10}
barHeight={20}
miseryLimit={300}
miserableUsers={0}
totalUsers={0}
/>
</Container>
));
Empty.story = {
name: 'empty',
};
export const NearEmpty = withInfo(
'Nearly empty state will still show 1 bar if there are any miserable users'
)(() => (
<Container>
<UserMisery
bars={10}
barHeight={20}
miseryLimit={300}
miserableUsers={1}
totalUsers={1000}
/>
</Container>
));
NearEmpty.story = {
name: 'near empty',
};
export const Full = withInfo('Full state')(() => (
<Container>
<UserMisery
bars={10}
barHeight={20}
miseryLimit={300}
miserableUsers={1000}
totalUsers={1000}
/>
</Container>
));
Full.story = {
name: 'full',
};
const Container = styled('div')`
display: inline-block;
`;
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.requestAnimationFrame = exports.cancelAnimationFrame = undefined;
exports.default = function (fn) {
return raf.call(root, fn);
};
var _performanceNow = require("./performanceNow.js");
var _performanceNow2 = _interopRequireDefault(_performanceNow);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var root = typeof window === "undefined" ? global : window;
var vendors = ["moz", "webkit"];
var suffix = "AnimationFrame";
var raf = root["request" + suffix];
var caf = root["cancel" + suffix] || root["cancelRequest" + suffix];
for (var i = 0; !raf && i < vendors.length; i++) {
raf = root[vendors[i] + "Request" + suffix];
caf = root[vendors[i] + "Cancel" + suffix] || root[vendors[i] + "CancelRequest" + suffix];
}
// Some versions of FF have rAF but not cAF
if (!raf || !caf) {
var last = 0,
id = 0,
queue = [],
frameDuration = 1000 / 60;
raf = function raf(callback) {
if (queue.length === 0) {
var _now = (0, _performanceNow2.default)(),
next = Math.max(0, frameDuration - (_now - last));
last = next + _now;
setTimeout(function () {
var cp = queue.slice(0);
// Clear queue here to prevent
// callbacks from appending listeners
// to the current frame's queue
queue.length = 0;
for (var i = 0; i < cp.length; i++) {
if (!cp[i].cancelled) {
try {
cp[i].callback(last);
} catch (e) {
setTimeout(function () {
throw e;
}, 0);
}
}
}
}, Math.round(next));
}
queue.push({
handle: ++id,
callback: callback,
cancelled: false
});
return id;
};
caf = function caf(handle) {
for (var i = 0; i < queue.length; i++) {
if (queue[i].handle === handle) {
queue[i].cancelled = true;
}
}
};
}
var cancelAnimationFrame = exports.cancelAnimationFrame = function cancelAnimationFrame() {
caf.apply(root, arguments);
};
var requestAnimationFrame = exports.requestAnimationFrame = function requestAnimationFrame(fn) {
return raf.call(root, fn);
};
|
import { createElement } from 'lwc';
import GeModalPrompt from 'c/geModalPrompt';
describe('c-ge-modal-prompt', () => {
afterEach(() => {
clearDOM();
});
function flushPromises() {
return new Promise((resolve) => setImmediate(resolve));
}
const setup = (variant='warning') => {
const element = createElement('c-ge-modal-prompt', {
is: GeModalPrompt
});
element.variant = variant;
element.title = 'This is a title';
element.message = 'This is a message';
element.buttonText = 'This is a button';
document.body.appendChild(element);
return element;
}
describe('component render', () => {
it('renders the modal title', async () => {
const element = setup();
await flushPromises();
const headerElement = element.shadowRoot.querySelector('h1');
const text = headerElement.innerHTML;
expect(text).toBe('This is a title');
});
it('renders the modal message', async () => {
const element = setup();
await flushPromises();
const bodyElement = element.shadowRoot.querySelector('h2');
const text = bodyElement.innerHTML;
expect(text).toBe('This is a message');
});
it('renders the computed warning variant class', async () => {
const element = setup('warning');
await flushPromises();
const headerElements = element.shadowRoot.querySelectorAll('.slds-theme_warning');
expect(headerElements.length).toBe(1);
});
it('renders the computed default variant class with unsupported variant option', async () => {
const element = setup('nonsense');
await flushPromises();
const headerElements = element.shadowRoot.querySelectorAll('.slds-theme_default');
expect(headerElements.length).toBe(1);
});
});
});
|
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId])
/******/ return installedModules[moduleId].exports;
/******/
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // identity function for calling harmony imports with the correct context
/******/ __webpack_require__.i = function(value) { return value; };
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "./";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 2);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports) {
// removed by extract-text-webpack-plugin
/***/ }),
/* 1 */
/***/ (function(module, exports) {
/***/ }),
/* 2 */
/***/ (function(module, exports, __webpack_require__) {
__webpack_require__(1);
module.exports = __webpack_require__(0);
/***/ })
/******/ ]);
|
'use strict';
var _extend = require('lodash/object/extend');
function GLTools() {}
GLTools.prototype.CreateFrameBufferTex = function(gl, sizeX, sizeY, linear) {
linear = linear || false;
var fb = gl.createFramebuffer();
var tex = gl.createTexture();
gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
fb.width = sizeX;
fb.height = sizeY;
gl.bindTexture(gl.TEXTURE_2D, tex);
if (linear) {
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
}
else {
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
}
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, fb.width, fb.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);
gl.bindTexture(gl.TEXTURE_2D, null);
gl.bindFramebuffer(gl.FRAMEBUFFER, null);
return [fb, tex];
};
GLTools.prototype.BuildShader = function(gl, inShader) {
var shader = {};
shader.error = false;
shader.obj = null;
shader.attributes = inShader.attributes;
shader.parameters = inShader.parameters;
if (inShader.type === 'x-shader/x-fragment') {
shader.obj = gl.createShader(gl.FRAGMENT_SHADER);
}
else if (inShader.type === 'x-shader/x-vertex') {
shader.obj = gl.createShader(gl.VERTEX_SHADER);
}
else {
shader.error = true;
return;
}
gl.shaderSource(shader.obj, inShader.code);
gl.compileShader(shader.obj);
if (!gl.getShaderParameter(shader.obj, gl.COMPILE_STATUS)) {
shader.error = true;
console.log('Build ' + inShader.name + ' : Failed ! ');
console.log(gl.getShaderInfoLog(shader.obj));
}
return shader;
};
GLTools.prototype.MakeProgram = function(inVertexName, inFragmentName, inAssets) {
if (!inAssets.shaderData) {
console.log('invalid shader data');
return null;
}
if (!(inVertexName in inAssets.shaderData)) {
console.log(inVertexName + ' not in shader data');
return null;
}
if (!(inFragmentName in inAssets.shaderData)) {
console.log(inFragmentName + ' not in shader data');
return null;
}
var vert = inAssets.shaderData[inVertexName];
vert.name = inVertexName;
var frag = inAssets.shaderData[inFragmentName];
frag.name = inFragmentName;
var gl = inAssets.ctx;
var vertObj = this.BuildShader(gl, vert);
var fragObj = this.BuildShader(gl, frag);
if (vertObj.error || fragObj.error) {
return null;
}
var shaderProgram = gl.createProgram();
shaderProgram.error = false;
shaderProgram.attr = {};
shaderProgram.params = {};
var attributes = {};
var parameters = {};
_extend(attributes, vertObj.attributes);
_extend(parameters, vertObj.parameters);
_extend(attributes, fragObj.attributes);
_extend(parameters, fragObj.parameters);
gl.attachShader(shaderProgram, vertObj.obj);
gl.attachShader(shaderProgram, fragObj.obj);
gl.linkProgram(shaderProgram);
if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
console.log('Could not link programm with ' + inVertexName + ' and ' + inFragmentName);
shaderProgram.error = true;
return;
}
gl.useProgram(shaderProgram);
for (var key in attributes) {
shaderProgram.attr[key] = gl.getAttribLocation(shaderProgram, attributes[key]);
}
for (key in parameters) {
shaderProgram.params[key] = {};
shaderProgram.params[key].name = gl.getUniformLocation(shaderProgram, parameters[key][0]);
shaderProgram.params[key].fct = parameters[key][1];
}
return shaderProgram;
};
// ------------------------------------------------------------------//
module.exports = GLTools;
|
function getUuid() {
var ret = "",
value;
for (var i = 0; i < 32; i++) {
value = (Math.random() * 16) | 0;
// Insert the hypens
if (i > 4 && i < 21 && !(i % 4)) {
ret += "-";
}
// Add the next random character
ret += (i === 12 ? 4 : i === 16 ? (value & 3) | 8 : value).toString(16);
}
return ret;
}
export default getUuid;
|
/*
* Copyright 2013 The Toolkitchen Authors. All rights reserved.
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file.
*/
/**
* This event denotes the beginning of a series of tracking events.
*
* @for Events
* @event trackstart
* @param {Number} dx Pixels moved in the x direction since trackstart.
* @param {Number} dy Pixes moved in the y direction since trackstart.
* @param {Number} ddx Pixels moved in the x direction since the last track.
* @param {Number} ddy Pixles moved in the y direction since the last track.
* @param {Number} xDirection The last x axis direction of the pointer.
* @param {Number} yDirection The last y axis direction of the pointer.
* @param {Object} trackInfo A shared object between all tracking events.
* @param {String} pointerType The type of pointer that make the track gesture.
*/
/**
*
* This event fires for all pointer movement being tracked.
*
* @for Events
* @event track
* @param {Number} dx Pixels moved in the x direction since trackstart.
* @param {Number} dy Pixes moved in the y direction since trackstart.
* @param {Number} ddx Pixels moved in the x direction since the last track.
* @param {Number} ddy Pixles moved in the y direction since the last track.
* @param {Number} xDirection The last x axis direction of the pointer.
* @param {Number} yDirection The last y axis direction of the pointer.
* @param {Object} trackInfo A shared object between all tracking events.
* @param {String} pointerType The type of pointer that make the track gesture.
*/
/**
* This event fires when the pointer is no longer being tracked.
*
* @for Events
* @event trackend
* @param {Number} dx Pixels moved in the x direction since trackstart.
* @param {Number} dy Pixes moved in the y direction since trackstart.
* @param {Number} ddx Pixels moved in the x direction since the last track.
* @param {Number} ddy Pixles moved in the y direction since the last track.
* @param {Number} xDirection The last x axis direction of the pointer.
* @param {Number} yDirection The last y axis direction of the pointer.
* @param {Object} trackInfo A shared object between all tracking events.
* @param {String} pointerType The type of pointer that make the track gesture.
*/
(function(scope) {
var dispatcher = scope.dispatcher;
var pointermap = new scope.PointerMap;
var track = {
events: [
'pointerdown',
'pointermove',
'pointerup',
'pointercancel'
],
WIGGLE_THRESHOLD: 4,
clampDir: function(inDelta) {
return inDelta > 0 ? 1 : -1;
},
calcPositionDelta: function(inA, inB) {
var x = 0, y = 0;
if (inA && inB) {
x = inB.clientX - inA.clientX;
y = inB.clientY - inA.clientY;
}
return {x: x, y: y};
},
fireTrack: function(inType, inEvent, inTrackingData) {
var t = inTrackingData;
var d = this.calcPositionDelta(t.downEvent, inEvent);
var dd = this.calcPositionDelta(t.lastMoveEvent, inEvent);
if (dd.x) {
t.xDirection = this.clampDir(dd.x);
}
if (dd.y) {
t.yDirection = this.clampDir(dd.y);
}
var e = dispatcher.makeEvent(inType, {
dx: d.x,
dy: d.y,
ddx: dd.x,
ddy: dd.y,
xDirection: t.xDirection,
yDirection: t.yDirection,
trackInfo: t.trackInfo,
pointerType: inEvent.pointerType
});
t.lastMoveEvent = inEvent;
dispatcher.dispatchEvent(e, t.downTarget);
},
pointerdown: function(inEvent) {
if (inEvent.isPrimary) {
var p = {
downEvent: inEvent,
downTarget: inEvent.target,
trackInfo: {},
lastMoveEvent: null,
xDirection: 0,
yDirection: 0,
tracking: false
};
pointermap.set(inEvent.pointerId, p);
}
},
pointermove: function(inEvent) {
var p = pointermap.get(inEvent.pointerId);
if (p) {
if (!p.tracking) {
var d = this.calcPositionDelta(p.downEvent, inEvent);
var move = d.x * d.x + d.y * d.y;
// start tracking only if finger moves more than WIGGLE_THRESHOLD
if (move > this.WIGGLE_THRESHOLD) {
p.tracking = true;
this.fireTrack('trackstart', p.downEvent, p);
this.fireTrack('track', inEvent, p);
}
} else {
this.fireTrack('track', inEvent, p);
}
}
},
pointerup: function(inEvent) {
var p = pointermap.get(inEvent.pointerId);
if (p) {
if (p.tracking) {
this.fireTrack('trackend', inEvent, p);
}
pointermap.delete(inEvent.pointerId);
}
},
pointercancel: function(inEvent) {
this.pointerup(inEvent);
}
};
dispatcher.registerRecognizer('track', track);
})(window.PointerGestures);
|
// Generate halton sequence
// https://en.wikipedia.org/wiki/Halton_sequence
function halton(index, base) {
var result = 0;
var f = 1 / base;
var i = index;
while (i > 0) {
result = result + f * (i % base);
i = Math.floor(i / base);
f = f / base;
}
return result;
}
export default halton;
|
import _ from 'lodash'
export const getStructuresById = state => state.structures.byDatasetId;
export const getStructureById = (state, id) => {
let dataSetId = null;
if (_.has(state.datasets.byId, id)) {
dataSetId = id;
}
else if (_.has(state.datasets.mdbIdToId, id)) {
dataSetId = state.datasets.mdbIdToId[id];
}
if (_.has(state.structures.byDatasetId, dataSetId)) {
// For now we only have a single structure, so just pick the first.
return state.structures.byDatasetId[dataSetId][0];
}
return null;
}
|
/*!
Infusion Module System
Copyright 2014 Lucendo Development Ltd.
Licensed under the Educational Community License (ECL), Version 2.0 or the New
BSD license. You may not use this file except in compliance with one these
Licenses.
You may obtain a copy of the ECL 2.0 License and BSD License at
https://github.com/fluid-project/infusion/raw/master/Infusion-LICENSE.txt
*/
/* jshint node:true */
/* global fluid, path */
"use strict";
// An extremely simple base for the module system that just has the functionality of
// tracking base directories for loaded modules, and the ability to interpolate paths
// of the form ${module}/further-path
fluid.registerNamespace("fluid.module");
fluid.module.modules = {};
/** A module which has just loaded will call this API to register itself into
* the Fluid module loader's records. The call will generally take the form:
* <code>fluid.module.register("my-module", __dirname, require)</code>
*/
fluid.module.register = function (name, baseDir, moduleRequire) {
fluid.log(fluid.logLevel.WARN, "Registering module " + name + " from path " + baseDir);
fluid.module.modules[name] = {
baseDir: fluid.module.canonPath(baseDir),
require: moduleRequire
};
};
fluid.module.pathsToRoot = function (baseDir) {
var segs = baseDir.split(path.sep);
var paths = fluid.accumulate(segs.slice(1), function (seg, total) {
var top = total[total.length - 1];
total.push(top + path.sep + seg);
return total;
}, [segs[0]]);
return paths.slice(1);
};
fluid.module.hasPackage = function (dir) {
var packagePath = dir + path.sep + "package.json";
try {
return require(packagePath);
} catch (e) {
return null;
}
};
// A simple precursor of our eventual global module inspection system. This simply inspects the path
// to root for any readable package.json files, and extracts their "name" field as a moral identifier
// of a module's presence. Eventually our registry will include versions and be indexed from the
// requestor's viewpoint - in the further future it will be mapped directly into an IoC tree
fluid.module.preInspect = function (root) {
var paths = fluid.module.pathsToRoot(root || __dirname);
var packages = fluid.transform(paths, fluid.module.hasPackage);
var names = fluid.getMembers(packages, "name");
fluid.each(names, function (name, index) {
if (name && !fluid.module.modules[name]) {
fluid.module.register(name, paths[index], null); // TODO: fabricate a "require" too - so far unused
}
});
};
/** Canonicalise a path by replacing all backslashes with forward slashes
* (the latter are always valid when supplied to Windows APIs)
*/
fluid.module.canonPath = function (path) {
return path.replace(/\\/g, "/");
};
/** Resolve a path expression which may begin with a module reference of the form,
* say, ${module-name}, into an absolute path relative to that module, using the
* database of base directories registered previously with fluid.module.register.
* If the path does not begin with such a module reference, it is returned unchanged.
*/
fluid.module.resolvePath = function (path) {
if (path.indexOf("${") === 0) {
var ic = path.indexOf("}");
if (ic === -1) {
fluid.fail("Malformed context path without }: ", path);
} else {
var context = path.substring(2, ic);
var record = fluid.module.modules[context];
if (!record) {
fluid.fail("Unrecognised module " + context + ": loaded modules are " + fluid.keys(fluid.module.modules).join(", "));
}
return record.baseDir + path.substring(ic + 1);
}
} else {
return path;
}
};
|
var edit_tb = '<div draggable="true" id="edit_tb">\
{{=select}} - <button>Save</button>\
</div>';
edit_tb = new t(edit_tb);
var edit_select = '<select id="region_select" onchange="edit_region()">\
<option>Select a Region to Edit</option>\
{{@regions}}<option value="{{=_key}}">{{=_val.dname}}</option>{{/@regions}}\
</select>';
edit_select = new t(edit_select);
function load_edit_tools () {
if (jQuery.cookie('PIZZA_EDIT') == 'ON') {
var select = edit_select.render({regions: pizzaContext});
jQuery('body').append(edit_tb.render({select: select}));
var dm = document.getElementById('edit_tb');
dm.addEventListener('dragstart',drag_start,false);
document.body.addEventListener('dragover',drag_over,false);
document.body.addEventListener('drop',drop,false);
}
}
function edit_region () {
var key = jQuery("#region_select").val();
if (key != "") {
if (pizzaContext[key].etype == 'rich') {
jQuery('#id_' + key).redactor({ focus: true });
}
}
}
function drag_start(event) {
var style = window.getComputedStyle(event.target, null);
event.dataTransfer.setData("text/plain",
(parseInt(style.getPropertyValue("left"),10) - event.clientX) + ',' + (parseInt(style.getPropertyValue("top"),10) - event.clientY));
}
function drag_over(event) {
event.preventDefault();
return false;
}
function drop(event) {
var offset = event.dataTransfer.getData("text/plain").split(',');
var dm = document.getElementById('edit_tb');
dm.style.left = (event.clientX + parseInt(offset[0],10)) + 'px';
dm.style.top = (event.clientY + parseInt(offset[1],10)) + 'px';
event.preventDefault();
return false;
}
|
window.SVGContent = (function() {
"use strict";
SVGContent.parse = function(c, ei_info) {
var tag = c[0].tagName;
var format = c.attr('format');
if ( tag != _ei.outlang.syntax.content || format != _ei.outlang.syntax.svgcontent ) return null;
var outclass = c.attr(_ei.outlang.syntax.outclass) || ei_info.outclass;
return new SVGContent({
content: c,
outclass: outclass
});
}
function SVGContent(options) {
this.content = $("<div></div>");
var svgEnv = $(options.content).find("> svg");
if ( svgEnv.length != 1 ) {
throw "an svg conetnt environment must include exactly one svg environemt inside";
}
svgEnv = svgEnv.prop('outerHTML');
svgEnv = $(svgEnv);
svgEnv.css("overflow","auto");
this.content.append( svgEnv );
svgEnv.svg();
}
SVGContent.prototype = {
constructor: SVGContent,
"getDOM":
function() {
return this.content;
}
}
return SVGContent;
})();
|
var RotateAroundXY = require('./RotateAroundXY');
var RotateAroundPoint = function (line, point, angle)
{
return RotateAroundXY(line, point.x, point.y, angle);
};
module.exports = RotateAroundPoint;
|
'use strict';
var Promise = require('bluebird');
var setImmediate = require('set-immediate-shim');
var fnName = require('fn-name');
var assert = require('./assert');
function Test(title, fn) {
if (!(this instanceof Test)) {
return new Test(title, fn);
}
if (typeof title !== 'string') {
fn = title;
title = null;
}
this.title = title || fnName(fn) || '[anonymous]';
this.fn = fn;
this.assertCount = 0;
this.planCount = null;
this.duration = null;
// store the time point before test execution
// to calculate the total time spent in test
this._timeStart = null;
}
module.exports = Test;
Test.prototype._assert = function () {
this.assertCount++;
if (this.assertCount === this.planCount) {
setImmediate(this.exit.bind(this));
}
};
Object.keys(assert).forEach(function (el) {
Test.prototype[el] = function () {
this._assert();
try {
assert[el].apply(assert, arguments);
} catch (err) {
this.assertError = err;
}
};
});
Test.prototype.plan = function (count) {
if (typeof count !== 'number') {
throw new TypeError('Expected a number');
}
this.planCount = count;
// in case the `planCount` doesn't match `assertCount,
// we need the stack of this function to throw with a useful stack
this.planStack = new Error().stack;
};
Test.prototype.run = function () {
this.promise = {};
// TODO: refactor this to avoid storing the promise
return new Promise(function (resolve, reject) {
this.promise.resolve = resolve;
this.promise.reject = reject;
if (!this.fn) {
return this.exit();
}
this._timeStart = Date.now();
try {
var ret = this.fn(this);
if (ret && typeof ret.then === 'function') {
ret.then(this.exit.bind(this)).catch(function (err) {
this.assertError = new assert.AssertionError({
actual: err,
message: 'Promise rejected → ' + err,
operator: 'promise'
});
this.exit();
}.bind(this));
}
} catch (err) {
this.assertError = err;
this.exit();
}
}.bind(this));
};
Test.prototype.end = function () {
if (this.endCalled) {
throw new Error('.end() called more than once');
}
this.endCalled = true;
this.exit();
};
Test.prototype.exit = function () {
// calculate total time spent in test
this.duration = Date.now() - this._timeStart;
if (!this.assertError && this.planCount !== null && this.planCount !== this.assertCount) {
this.assertError = new assert.AssertionError({
actual: this.assertCount,
expected: this.planCount,
message: 'Assertion count does not match planned',
operator: 'plan'
});
this.assertError.stack = this.planStack;
}
if (!this.ended) {
this.ended = true;
setImmediate(function () {
if (this.assertError) {
return this.promise.reject(this.assertError);
}
this.promise.resolve(this);
}.bind(this));
}
};
|
const cron = require("node-cron");
const pruneEvents = eventsCollection => {
const now = new Date();
const oneWeekAgo = new Date(now.getTime() - 1000 * 60 * 60 * 24 * 7);
eventsCollection
.chain()
.find({
"meta.created": {
$lt: oneWeekAgo.getTime()
}
})
.limit(1000000)
.remove();
};
const schedule = eventsCollection => {
cron.schedule("0 2 * * *", () => pruneEvents(eventsCollection)); // run 2am every day
};
module.exports = eventsCollection => ({
schedule: () => schedule(eventsCollection)
});
|
'use strict';
var xmpp = require('node-xmpp-server'),
Stanza = require('node-xmpp-core').Stanza,
mongoose = require('mongoose'),
settings = require('./../config'),
auth = require('./../auth/index'),
all = require('require-tree'),
Stanza = require('node-xmpp-core').Stanza,
XmppConnection = require('./xmpp-connection');
var allArray = function(path) {
var modules = all(path);
return Object.keys(modules).map(function(key) {
return modules[key];
});
};
var XmppConnection = require('./xmpp-connection'),
msgProcessors = allArray('./msg-processors'),
eventListeners = allArray('./events');
function xmppStart(core) {
var options = {
port: settings.xmpp.port,
domain: settings.xmpp.host
};
if (settings.xmpp.tls && settings.xmpp.tls.enable) {
options.tls = {
keyPath: settings.xmpp.tls.key,
certPath: settings.xmpp.tls.cert
};
}
var c2s = new xmpp.C2SServer(options);
c2s.on('connect', function(client) {
client.on('authenticate', function(opts, cb) {
auth.authenticate(opts.jid.local, opts.password,
function(err, user) {
if (err || !user) {
return cb(false);
}
// TODO: remove?
client.user = user;
var conn = new XmppConnection(user, client);
core.presence.connect(conn);
cb(null, opts);
});
});
client.on('online', function() {
});
client.on('stanza', function(stanza) {
var handled = msgProcessors.some(function(Processor) {
var processor = new Processor(client, stanza, core);
return processor.run();
});
if (handled) {
return;
}
if (settings.xmpp.debug.unhandled) {
// Print unhandled request
console.log(' ');
console.log(stanza.root().toString().red);
}
if (stanza.name !== 'iq') {
return;
}
var msg = new Stanza.Iq({
type: 'error',
id: stanza.attrs.id,
to: stanza.attrs.from,
from: stanza.attrs.to
});
msg.c('not-implemented', {
code: 501,
type: 'CANCEL'
}).c('feature-not-implemented', {
xmlns: 'urn:ietf:params:xml:n:xmpp-stanzas'
});
if (settings.xmpp.debug.unhandled) {
console.log(msg.root().toString().green);
}
client.send(msg);
});
// On Disconnect event. When a client disconnects
client.on('disconnect', function() {
});
});
eventListeners.forEach(function(EventListener) {
var listener = new EventListener(core);
core.on(listener.on, listener.then);
});
}
module.exports = xmppStart;
|
module.exports = function(grunt) {
grunt.loadNpmTasks('grunt-contrib-sass');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.initConfig({
sass: {
dist: {
files: {
'out/app.css': 'src/app.scss'
}
}
},
watch: {
files: ['src/*', 'src/*/*', '*.html', '../_lang/*'],
tasks: ['sass'],
options: {
livereload: true
}
}
});
};
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "some exports", {
enumerable: true,
get: function () {
return _foo.foo;
}
});
var _foo = require("foo");
|
'use strict';
/**
* This contains all the core commands that kalabox can run on every machine
*/
module.exports = function(kbox) {
// Prints out the config.
kbox.tasks.add(function(task) {
task.path = ['config'];
task.description = 'Display the kbox configuration.';
task.func = function() {
var config = kbox.core.config.getGlobalConfig();
console.log(JSON.stringify(config, null, ' '));
};
});
kbox.whenApp(function(app) {
kbox.tasks.add(function(task) {
task.path = [app.name, 'config'];
task.description = 'Display the kbox application\'s configuration.';
task.func = function() {
console.log(JSON.stringify(app.config, null, ' '));
};
});
});
};
|
import React from 'react'
import Icon from 'react-icon-base'
const TiWeatherShower = props => (
<Icon viewBox="0 0 40 40" {...props}>
<g><path d="m28.3 30c-0.9 0-1.6-0.7-1.6-1.7s0.7-1.6 1.6-1.6c2.8 0 5-2.3 5-5s-2.2-5-5-5c-0.4 0-0.8 0-1.3 0.2l-1.8 0.5-0.3-1.8c-0.6-3.3-3.3-5.6-6.6-5.6-3.6 0-6.6 3-6.6 6.7 0 0.4 0 0.9 0.1 1.3l0.4 2-2.4 0c-1.6 0-3.1 1.5-3.1 3.3s1.5 3.4 3.3 3.4c0.9 0 1.7 0.7 1.7 1.6s-0.8 1.7-1.7 1.7c-3.7 0-6.7-3-6.7-6.7 0-3.1 2.2-5.7 5-6.4 0-0.1 0-0.2 0-0.2 0-5.5 4.5-10 10-10 4.3 0 8.1 2.7 9.4 6.7 4.9-0.4 9 3.5 9 8.3 0 4.6-3.8 8.3-8.4 8.3z m-10.8 0l1.7-5 1.6 5c0.3 0.9-0.2 1.9-1.1 2.2-0.9 0.3-1.9-0.2-2.2-1.1-0.1-0.4-0.1-0.8 0-1.1z m5 3.3l1.7-5 1.6 5c0.3 1-0.2 1.9-1.1 2.3-0.9 0.3-1.9-0.2-2.2-1.2-0.1-0.3-0.1-0.7 0-1.1z m-10 0l1.7-5 1.6 5c0.3 1-0.2 1.9-1.1 2.3-0.9 0.3-1.9-0.2-2.2-1.2-0.1-0.3-0.1-0.7 0-1.1z"/></g>
</Icon>
)
export default TiWeatherShower
|
version https://git-lfs.github.com/spec/v1
oid sha256:84de344f6bda6881c9363abe2733bb548b5bb1eb52075214f32f14725d5e5203
size 44790
|
version https://git-lfs.github.com/spec/v1
oid sha256:4213863ba80ac8657fdda4e5782321baf6e03940eb1fa55eb3ba0dfc2395138a
size 3000
|
const PrintDialog = {
selector: '.js-print-dialog',
init() {
document.addEventListener('DOMContentLoaded', this.contentLoaded.bind(this))
},
contentLoaded() {
const printLinks = document.querySelectorAll(this.selector)
Array.from(printLinks).forEach((link) => {
link.addEventListener('click', this.handleClick.bind(this))
})
},
handleClick(event) {
event.preventDefault()
window.print()
},
}
module.exports = PrintDialog
|
'use strict';
module.exports.definition = {
set: function (v) {
this.setProperty('text-underline', v);
},
get: function () {
return this.getPropertyValue('text-underline');
},
enumerable: true
};
|
/**
* This bot example shows the basic usage of the mineflayer-pvp plugin for guarding a defined area from nearby mobs.
*/
if (process.argv.length < 4 || process.argv.length > 6) {
console.log('Usage : node guard.js <host> <port> [<name>] [<password>]')
process.exit(1)
}
const mineflayer = require('mineflayer')
const { pathfinder, Movements, goals } = require('mineflayer-pathfinder')
const pvp = require('mineflayer-pvp').plugin
const bot = mineflayer.createBot({
host: process.argv[2],
port: parseInt(process.argv[3]),
username: process.argv[4] ? process.argv[4] : 'Guard',
password: process.argv[5]
})
bot.loadPlugin(pathfinder)
bot.loadPlugin(pvp)
let guardPos = null
// Assign the given location to be guarded
function guardArea (pos) {
guardPos = pos
// We we are not currently in combat, move to the guard pos
if (!bot.pvp.target) {
moveToGuardPos()
}
}
// Cancel all pathfinder and combat
function stopGuarding () {
guardPos = null
bot.pvp.stop()
bot.pathfinder.setGoal(null)
}
// Pathfinder to the guard position
function moveToGuardPos () {
const mcData = require('minecraft-data')(bot.version)
bot.pathfinder.setMovements(new Movements(bot, mcData))
bot.pathfinder.setGoal(new goals.GoalBlock(guardPos.x, guardPos.y, guardPos.z))
}
// Called when the bot has killed it's target.
bot.on('stoppedAttacking', () => {
if (guardPos) {
moveToGuardPos()
}
})
// Check for new enemies to attack
bot.on('physicsTick', () => {
if (!guardPos) return // Do nothing if bot is not guarding anything
// Only look for mobs within 16 blocks
const filter = e => e.type === 'mob' && e.position.distanceTo(bot.entity.position) < 16 &&
e.mobType !== 'Armor Stand' // Mojang classifies armor stands as mobs for some reason?
const entity = bot.nearestEntity(filter)
if (entity) {
// Start attacking
bot.pvp.attack(entity)
}
})
// Listen for player commands
bot.on('chat', (username, message) => {
// Guard the location the player is standing
if (message === 'guard') {
const player = bot.players[username]
if (!player) {
bot.chat("I can't see you.")
return
}
bot.chat('I will guard that location.')
guardArea(player.entity.position)
}
// Stop guarding
if (message === 'stop') {
bot.chat('I will no longer guard this area.')
stopGuarding()
}
})
|
define('jqueryui/effects/transfer', ['jquery','jqueryui/effects/core'], function (jQuery) {
/*
* jQuery UI Effects Transfer 1.8.14
*
* Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* http://docs.jquery.com/UI/Effects/Transfer
*
* Depends:
* jquery.effects.core.js
*/
(function( $, undefined ) {
$.effects.transfer = function(o) {
return this.queue(function() {
var elem = $(this),
target = $(o.options.to),
endPosition = target.offset(),
animation = {
top: endPosition.top,
left: endPosition.left,
height: target.innerHeight(),
width: target.innerWidth()
},
startPosition = elem.offset(),
transfer = $('<div class="ui-effects-transfer"></div>')
.appendTo(document.body)
.addClass(o.options.className)
.css({
top: startPosition.top,
left: startPosition.left,
height: elem.innerHeight(),
width: elem.innerWidth(),
position: 'absolute'
})
.animate(animation, o.duration, o.options.easing, function() {
transfer.remove();
(o.callback && o.callback.apply(elem[0], arguments));
elem.dequeue();
});
});
};
})(jQuery);
});
|
import React from 'react'
import Icon from 'react-icon-base'
const MdLightbulbOutline = props => (
<Icon viewBox="0 0 40 40" {...props}>
<g><path d="m24.8 21.8c2.2-1.6 3.6-4.1 3.6-6.8 0-4.6-3.8-8.4-8.4-8.4s-8.4 3.8-8.4 8.4c0 2.7 1.4 5.2 3.6 6.8l1.4 1v3.8h6.8v-3.8z m-4.8-18.4c6.4 0 11.6 5.2 11.6 11.6 0 4-1.9 7.4-5 9.5v3.9c0 0.9-0.7 1.6-1.6 1.6h-10c-0.9 0-1.6-0.7-1.6-1.6v-3.9c-3.1-2.1-5-5.5-5-9.5 0-6.4 5.2-11.6 11.6-11.6z m-5 31.6v-1.6h10v1.6c0 0.9-0.7 1.6-1.6 1.6h-6.8c-0.9 0-1.6-0.7-1.6-1.6z"/></g>
</Icon>
)
export default MdLightbulbOutline
|
'use strict';
var findTestPath = require('../../lib/find-test-path')
, pg = require('path').resolve(__dirname, '../__playground/lib') + '/';
module.exports = function (t, a, d) {
var l, data, paths = [pg + 'module.js', '/wrong/path', pg + 'dir'];
l = t(paths);
data = [];
l('data', function () {
data.push(arguments);
});
l('end', function () {
d({
File: function (t, a, d) {
var o = data[0];
a(o[0], paths[0], "Path");
a(o[1], paths[0], "File");
a(o[3], global, "Context");
findTestPath(o[1])(function (p) {
a(p, o[2], "Test path");
}).done(d);
},
"Wrong path": function () {
var o = data[1];
a(o[0], paths[1], "Path");
a.ok(o[1] instanceof Error, "Error");
},
Directory: function () {
a(data.length, 6, "Files length");
return {
"File #1": function (t, a, d) {
var o = data[2];
// console.log(o);
a(o[0], paths[2], "Path");
a(o[3], global, "Context");
findTestPath(o[1])(function (p) {
a(p, o[2], "Test path");
}).done(d);
},
"File #2": function (t, a, d) {
var o = data[5];
a(o[0], paths[2], "Path");
a(o[3], global, "Context");
findTestPath(o[1])(function (p) {
a(p, o[2], "Test path");
}).done(d);
}
};
}
});
});
};
|
module.exports = require('./lib/bolts');
|
exports.name = "date_setDate";
exports.call = function(date, dayValue) {
this.expectNumber(dayValue);
var d = new Date(date);
d.setUTCDate(dayValue);
return d.getTime();
};
|
import { combineReducers } from 'redux';
import getModuleStatusReducer from '../../lib/getModuleStatusReducer';
import messageStoreStatus from './messageStoreStatus';
export function getMessageStoreStatusReducer(types) {
return (state = messageStoreStatus.idle, { type }) => {
switch (type) {
case types.sync:
return messageStoreStatus.syncing;
case types.syncError:
case types.syncSuccess:
return messageStoreStatus.idle;
default:
return state;
}
};
}
export default function getMessageStoreReducer(types) {
return combineReducers({
status: getModuleStatusReducer(types),
messageStoreStatus: getMessageStoreStatusReducer(types),
});
}
|
define( [
"../core",
"../var/document",
"../data/var/dataPriv",
"../data/var/acceptData",
"../var/hasOwn",
"../event"
], function( jQuery, document, dataPriv, acceptData, hasOwn ) {
var rfocusMorph = /^(?:focusinfocus|focusoutblur)$/;
jQuery.extend( jQuery.event, {
trigger: function( event, data, elem, onlyHandlers ) {
var i, cur, tmp, bubbleType, ontype, handle, special,
eventPath = [ elem || document ],
type = hasOwn.call( event, "type" ) ? event.type : event,
namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split( "." ) : [];
cur = tmp = elem = elem || document;
// Don't do events on text and comment nodes
if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
return;
}
// focus/blur morphs to focusin/out; ensure we're not firing them right now
if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
return;
}
if ( type.indexOf( "." ) > -1 ) {
// Namespaced trigger; create a regexp to match event type in handle()
namespaces = type.split( "." );
type = namespaces.shift();
namespaces.sort();
}
ontype = type.indexOf( ":" ) < 0 && "on" + type;
// Caller can pass in a jQuery.Event object, Object, or just an event type string
event = event[ jQuery.expando ] ?
event :
new jQuery.Event( type, typeof event === "object" && event );
// Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true)
event.isTrigger = onlyHandlers ? 2 : 3;
event.namespace = namespaces.join( "." );
event.rnamespace = event.namespace ?
new RegExp( "(^|\\.)" + namespaces.join( "\\.(?:.*\\.|)" ) + "(\\.|$)" ) :
null;
// Clean up the event in case it is being reused
event.result = undefined;
if ( !event.target ) {
event.target = elem;
}
// Clone any incoming data and prepend the event, creating the handler arg list
data = data == null ?
[ event ] :
jQuery.makeArray( data, [ event ] );
// Allow special events to draw outside the lines
special = jQuery.event.special[ type ] || {};
if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) {
return;
}
// Determine event propagation path in advance, per W3C events spec (#9951)
// Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) {
bubbleType = special.delegateType || type;
if ( !rfocusMorph.test( bubbleType + type ) ) {
cur = cur.parentNode;
}
for ( ; cur; cur = cur.parentNode ) {
eventPath.push( cur );
tmp = cur;
}
// Only add window if we got to document (e.g., not plain obj or detached DOM)
if ( tmp === ( elem.ownerDocument || document ) ) {
eventPath.push( tmp.defaultView || tmp.parentWindow || window );
}
}
// Fire handlers on the event path
i = 0;
while ( ( cur = eventPath[ i++ ] ) && !event.isPropagationStopped() ) {
event.type = i > 1 ?
bubbleType :
special.bindType || type;
// jQuery handler
handle = ( dataPriv.get( cur, "events" ) || {} )[ event.type ] &&
dataPriv.get( cur, "handle" );
if ( handle ) {
handle.apply( cur, data );
}
// Native handler
handle = ontype && cur[ ontype ];
if ( handle && handle.apply && acceptData( cur ) ) {
event.result = handle.apply( cur, data );
if ( event.result === false ) {
event.preventDefault();
}
}
}
event.type = type;
// If nobody prevented the default action, do it now
if ( !onlyHandlers && !event.isDefaultPrevented() ) {
if ( ( !special._default ||
special._default.apply( eventPath.pop(), data ) === false ) &&
acceptData( elem ) ) {
// Call a native DOM method on the target with the same name name as the event.
// Don't do default actions on window, that's where global variables be (#6170)
if ( ontype && jQuery.isFunction( elem[ type ] ) && !jQuery.isWindow( elem ) ) {
// Don't re-trigger an onFOO event when we call its FOO() method
tmp = elem[ ontype ];
if ( tmp ) {
elem[ ontype ] = null;
}
// Prevent re-triggering of the same event, since we already bubbled it above
jQuery.event.triggered = type;
elem[ type ]();
jQuery.event.triggered = undefined;
if ( tmp ) {
elem[ ontype ] = tmp;
}
}
}
}
return event.result;
},
// Piggyback on a donor event to simulate a different one
simulate: function( type, elem, event ) {
var e = jQuery.extend(
new jQuery.Event(),
event,
{
type: type,
isSimulated: true
// Previously, `originalEvent: {}` was set here, so stopPropagation call
// would not be triggered on donor event, since in our own
// jQuery.event.stopPropagation function we had a check for existence of
// originalEvent.stopPropagation method, so, consequently it would be a noop.
//
// But now, this "simulate" function is used only for events
// for which stopPropagation() is noop, so there is no need for that anymore.
//
<<<<<<< HEAD
// For the 1.x branch though, guard for "click" and "submit"
=======
// For the compat branch though, guard for "click" and "submit"
>>>>>>> 74ac078b58e4a4d3a88601450b2ba78bfdfc8b37
// events is still used, but was moved to jQuery.event.stopPropagation function
// because `originalEvent` should point to the original event for the constancy
// with other events and for more focused logic
}
);
jQuery.event.trigger( e, null, elem );
if ( e.isDefaultPrevented() ) {
event.preventDefault();
}
}
} );
jQuery.fn.extend( {
trigger: function( type, data ) {
return this.each( function() {
jQuery.event.trigger( type, data, this );
} );
},
triggerHandler: function( type, data ) {
var elem = this[ 0 ];
if ( elem ) {
return jQuery.event.trigger( type, data, elem, true );
}
}
} );
return jQuery;
} );
|
$(function(){
var nameFlag = false;
var pswFlag = false;
var yzFlag = false;
$(".log_form").bind("submit",function(){
var userName = $(".name").val();
var psw = $("input[type='password']").val();
// var code = $()
if(nameFlag == true&&pswFlag ==true&&yzFlag ==true){
console.log('登录成功');
}else{
if(userName == ''){
$(".yz_ts").html("<div>请输入手机号</div>");
}else if(!(/^1[3|4|5|6|7|8|9][0-9]\d{4,8}$/.test(userName))){
$(".yz_ts").html("<div>请输入正确的手机号</div>");
}else{
if(psw == ''){
$(".yz_ts").html("<div>请输入密码</div>");
}else{
if(c.validate()){
return true;
}else{
$(".yz_ts").html("<div>验证码错误</div>");
}
}
}
return false;
}
});
});
// 验证码
var inp = document.getElementById('inputCode');
var code = document.getElementById('code');
var submit = document.getElementById('sub');
document.getElementById('hyz').onclick = function(){
c.init();
}
//======================插件引用主体
var c = new KinerCode({
len: 4,//需要产生的验证码长度
// chars: ["1+2","3+15","6*8","8/4","22-15"],//问题模式:指定产生验证码的词典,若不给或数组长度为0则试用默认字典
chars: [
1, 2, 3, 4, 5, 6, 7, 8, 9, 0,
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
],//经典模式:指定产生验证码的词典,若不给或数组长度为0则试用默认字典
question: false,//若给定词典为算数题,则此项必须选择true,程序将自动计算出结果进行校验【若选择此项,则可不配置len属性】,若选择经典模式,必须选择false
copy: false,//是否允许复制产生的验证码
bgColor: "gray",//背景颜色[与背景图任选其一设置]
// bgImg: "skin/img/code.png",//若选择背景图片,则背景颜色失效
randomBg: false,//若选true则采用随机背景颜色,此时设置的bgImg和bgColor将失效
inputArea: inp,//输入验证码的input对象绑定【 HTMLInputElement 】
codeArea: code,//验证码放置的区域【HTMLDivElement 】
click2refresh: true,//是否点击验证码刷新验证码
false2refresh: true,//在填错验证码后是否刷新验证码
validateObj: submit,//触发验证的对象,若不指定则默认为已绑定的输入框inputArea
// validateEven: "blur",//触发验证的方法名,如click,blur等
validateFn: function (result, code) {//验证回调函数
if (result) {
$(".yz_ts div").remove();
} else {
if (this.opt.question) {
$(".yz_ts").html("<div>请输入验证码</div>");
} else {
$(".yz_ts").html("<div>验证码错误</div>");
}
}
}
});
function notLogin(){
alert('暂未开通');
}
// am-field-valid insertAfter
|
$(document).ready(function() {
$('a.log_in').click(function() {
//lấy giá trị thuộc tính href - chính là phần tử "#login-box"
var loginBox = $(this).attr('href');
//cho hiện hộp đăng nhập trong 300ms
$(loginBox).fadeIn("slow");
// thêm phần tử id="over" vào cuối thẻ body
$('body').append('<div id="over"></div>');
$('#over').fadeIn(300);
return false;
});
// khi click đóng hộp thoại
$(document).on('click', "a.close, #over", function() {
$('#over, .login').fadeOut(300 , function() {
$('#over').remove();
});
return false;
});
});
|
import Vue from 'vue';
import VueEcho from 'vue-echo';
window.io = require('socket.io-client');
Vue.use(VueEcho, {
broadcaster: 'socket.io',
host: process.env.MIX_ECHO_HOST
});
|
import AuYearPickerContent from './_year-picker-content.js'
import datePicker from '../../mixins/_date-picker.js'
const AuYearPickerPanel = Vue.extend({
template: require('./_year-picker-panel.jade'),
mixins: [datePicker],
components: {
AuYearPickerContent
},
props: {
value: Date,
default () {
return null
}
},
computed: {
model: {
get () {
return this.value
},
set (value) {
this.$emit('input', value)
this.$emit('close')
}
}
},
mounted () {
this.$refs.yearContent.$on('change', (value) => {
this.model = value
})
this.$refs.yearContent.$on('change.temp', (value) => {
this.$emit('change.temp', value)
})
},
methods: {
reset () {
this.$refs.yearContent.reset()
}
}
})
export default AuYearPickerPanel
|
if (navigator.serviceWorker) {
navigator.serviceWorker.register('./service-worker.js', {scope: './'})
.then(function (registration) {
console.log(registration);
})
.catch(function (e) {
console.error(e);
})
} else {
console.log('Service Worker is not supported in this browser.')
}
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.PivotConfigurator = undefined;
var _dec, _dec2, _dec3, _class;
var _aureliaDependencyInjection = require('aurelia-dependency-injection');
var _aureliaTemplating = require('aurelia-templating');
var _widgetBase = require('../common/widget-base');
var _decorators = require('../common/decorators');
var _constants = require('../common/constants');
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var PivotConfigurator = exports.PivotConfigurator = (_dec = (0, _aureliaTemplating.customElement)(_constants.constants.elementPrefix + 'pivot-configurator'), _dec2 = (0, _decorators.generateBindables)('kendoPivotConfigurator'), _dec3 = (0, _aureliaDependencyInjection.inject)(Element, _widgetBase.WidgetBase), _dec(_class = _dec2(_class = _dec3(_class = function () {
function PivotConfigurator(element, widgetBase) {
_classCallCheck(this, PivotConfigurator);
this.element = element;
this.widgetBase = widgetBase.control('kendoPivotConfigurator').useElement(this.element).linkViewModel(this);
}
PivotConfigurator.prototype.subscribe = function subscribe(event, callback) {
return this.widgetBase.subscribe(event, callback);
};
PivotConfigurator.prototype.bind = function bind(ctx, overrideCtx) {
this.widgetBase.useParentCtx(overrideCtx);
};
PivotConfigurator.prototype.attached = function attached() {
if (!this.kNoInit) {
this.recreate();
}
};
PivotConfigurator.prototype.recreate = function recreate() {
this.kWidget = this.widgetBase.recreate();
};
PivotConfigurator.prototype.destroy = function destroy() {
this.widgetBase.destroy(this.kWidget);
};
PivotConfigurator.prototype.detached = function detached() {
this.destroy();
};
return PivotConfigurator;
}()) || _class) || _class) || _class);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.