text
stringlengths 2
6.14k
|
|---|
import React, { Component, PropTypes } from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import CSSModules from 'react-css-modules';
import s from './StoryWrapper.css';
class ButtonGroup extends Component {
render() {
return <span {...this.props} styleName='ButtonGroup'>{this.props.children}</span>
}
}
ButtonGroup = withStyles(s)(
CSSModules(s, {
allowMultiple: true,
errorWhenNotFound: false
})(
ButtonGroup
)
)
class Button extends Component {
render() {
return <button {...this.props} styleName={'Button bsStyle_' + this.props.bsStyle}>{this.props.children}</button>
}
}
Button = withStyles(s)(
CSSModules(s, {
allowMultiple: true,
errorWhenNotFound: false
})(
Button
)
)
class ButtonToolbar extends Component {
render() {
return <span {...this.props} styleName='ButtonToolbar'>{this.props.children}</span>
}
}
export class StoryWrapper extends Component {
constructor(props){
super(props)
this.state = {
bg: 0,
inner: 0,
center: true
}
}
setCenter(center) {
return (e) => {
this.setState({center})
}
}
setInner(inner) {
return (e) => {
this.setState({inner})
}
}
setBg(bg) {
return (e) => {
this.setState({bg})
}
}
render() {
const bgs = [
'//mcheck.mgbeta.ru/images/bg3.jpg',
'//pp.vk.me/c629529/v629529020/1dd4a/JjiHPoWVrMM.jpg',
'//cdn.mgbeta.ru/frz/bg/bg1.jpg',
'//cdn.mgbeta.ru/frz/bg/bg2.jpg',
'//cdn.mgbeta.ru/frz/bg/bg3.jpg',
'//cdn.mgbeta.ru/frz/bg/bg4.jpg',
'//cdn.mgbeta.ru/frz/bg/bg5.jpg',
'//cdn.mgbeta.ru/frz/bg/bg6.jpg',
'',
]
const inner = [
'no',
'w300',
'w600',
'w900',
'w100',
'padding',
]
return <div styleName={'Wrapper Wrapper_inner_' + inner[this.state.inner] + (this.state.center ? ' Wrapper_center' : '')} style={{ background: 'url("https://pp.vk.me/c629529/v629529020/1dd4a/JjiHPoWVrMM.jpg") no-repeat center center fixed', height:'100%', backgroundSize: 'cover', backgroundImage: 'url(' + bgs[this.state.bg] + ')' }}>
<link href='//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css' rel="stylesheet" />
<link href='//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css' rel="stylesheet" />
<div style={{position:'absolute', right: 0, top: 0}}>
<ButtonToolbar>
<ButtonGroup>
<Button onClick={this.setCenter(!this.state.center)} bsStyle={this.state.center ? 'primary' : 'default'}>center</Button>
</ButtonGroup>
<ButtonGroup>
{ inner.map( (inner, i) =>
<Button key={i} onClick={this.setInner(i)} bsStyle={this.state.inner == i ? 'primary' : 'default'}>{inner}</Button>
)}
</ButtonGroup>
<ButtonGroup>
{ bgs.map( (bg, i) =>
<Button key={i} onClick={this.setBg(i)} bsStyle={this.state.bg == i ? 'primary' : 'default'}>{i + 1}</Button>
)}
</ButtonGroup>
</ButtonToolbar>
</div>
<div styleName='Wrapper__wrap' >
<div styleName='Wrapper__content' >
{this.props.children}
</div>
</div>
</div>
}
}
export default withStyles(s)(
CSSModules(s, {
allowMultiple: true,
errorWhenNotFound: false
})(
StoryWrapper
)
)
|
var activityLog = [];
function main() {
siteService.createSite(args.preset, args.url, args.title, args.description, args.visibility);
activityLog.push("Created site with preset '" + args.preset + "', site '" + args.url + "'");
model.activityLog = activityLog;
}
main();
|
import bowser from 'bowser';
import {
STATS,
MQA_STATS
} from '../constants';
/**
* @description MQAProcessor handles interval data for MQA
* @export
* @class MQAProcessor
*/
class MQAProcessor {
/**
* @constructor
* @public
* @memberof MQAProcessor
*/
constructor() {
this.data = {
videoReceive: [],
audioTransmit: [],
audioReceive: [],
videoTransmit: []
};
this.intervalNumber = 1;
}
/**
* @param {String} id
* @param {Array<WebRTCData>} interval - a slice of metrics history
* @returns {undefined}
* @memberof MQAProcessor
*/
process(id, interval) {
let rtcCandidatePair, rtcOutVideo, rtpOutVideo; // TODO: , rtcInVideo, rtpInVideo, rtcOutAudio, rtcInAudio, rtpInAudio, rtpOutAudio; // TODO:
let vsTransmit;
const {
videoReceive, audioTransmit, audioReceive, videoTransmit
} = this.data;
const sumValue = interval[0]; // the head is the last interval value, webRTC spec has some values automatically summed
if (sumValue) {
rtcCandidatePair = sumValue.rtcCandidatePair;
}
switch (id) {
case STATS.AUDIO_SENDER_ID:
audioTransmit.push();
break;
case STATS.AUDIO_RECEIVER_ID:
audioReceive.push();
break;
case STATS.VIDEO_SENDER_ID:
videoTransmit.push();
break;
case STATS.VIDEO_RECEIVER_ID:
videoReceive.push();
break;
case STATS.SHARE_SENDER_ID:
if (sumValue) {
rtcOutVideo = sumValue.rtcOutVideo;
rtpOutVideo = sumValue.rtpOutVideo;
}
vsTransmit = {...MQA_STATS.DEFAULT_SHARE_SENDER_STATS};
if (bowser.name.toLowerCase() === 'firefox') {
vsTransmit.common.remoteLossRate = rtpOutVideo ? rtpOutVideo.pliCount / (interval.length * this.intervalNumber) : 0;
vsTransmit.common.rtpPackets = rtpOutVideo ? rtpOutVideo.packetsSent / (interval.length * this.intervalNumber) : 0;
vsTransmit.streams[0].common.transmittedFrameRate = rtcOutVideo ? rtcOutVideo.framesEncoded / (interval.length * this.intervalNumber) : 0;
vsTransmit.streams[0].common.rtpPackets = rtpOutVideo ? rtpOutVideo.packetsSent / (interval.length * this.intervalNumber) : 0;
}
else {
vsTransmit.common.availableBitRate = rtcCandidatePair ? rtcCandidatePair.availableOutgoingBitrate : 0;
vsTransmit.common.remoteLossRate = rtpOutVideo ? rtpOutVideo.pliCount / (interval.length * this.intervalNumber) : 0;
vsTransmit.common.roundTripTime = rtcCandidatePair ? rtcCandidatePair.totalRoundTripTime / (interval.length * this.intervalNumber) : 0;
vsTransmit.common.rtpPackets = rtpOutVideo ? rtpOutVideo.packetsSent / (interval.length * this.intervalNumber) : 0;
vsTransmit.streams[0].common.rtpPackets = rtpOutVideo ? rtpOutVideo.packetsSent / (interval.length * this.intervalNumber) : 0;
vsTransmit.streams[0].common.transmittedBitrate = rtcCandidatePair ? rtcCandidatePair.availableOutgoingBitrate : 0;
vsTransmit.streams[0].common.transmittedFrameRate = rtcOutVideo ? rtcOutVideo.framesSent / (interval.length * this.intervalNumber) : 0;
vsTransmit.streams[0].transmittedHeight = rtcOutVideo ? rtcOutVideo.frameHeight : 0;
vsTransmit.streams[0].transmittedKeyFrames = rtcOutVideo ? rtcOutVideo.hugeFramesSent : 0;
vsTransmit.streams[0].transmittedWidth = rtcOutVideo ? rtcOutVideo.frameWidth : 0;
}
videoTransmit.push(vsTransmit);
break;
default:
break;
}
this.data.intervalMetadata = this.data.intervalMetadata || {...MQA_STATS.intervalMetadata};
}
/**
* get the data payload for media quality events after they all have been processed
* wait to call this until after you have all the data from the interval you want
* this method clears the data as a side effect
* @returns {Object}
* @memberof MQAProcessor
*/
getData() {
this.intervalNumber += 1;
const payload = {...this.data, intervalNumber: this.intervalNumber};
this.data = {
videoReceive: [],
audioTransmit: [],
audioReceive: [],
videoTransmit: []
};
return payload;
}
}
export default MQAProcessor;
|
CKEDITOR.plugins.add( 'nuitblanche',
{
init: function( editor )
{
this.initAddPlayer(editor);
this.initAddRaceImage(editor);
this.initAddClanWar(editor);
},
initAddPlayer: function ( editor )
{
editor.addCommand('addPlayer', new CKEDITOR.dialogCommand( 'addPlayerDialog' ) );
CKEDITOR.dialog.add( 'addPlayerDialog', function(editor)
{
return {
title : 'Insert a player',
minWidth : 400,
minHeight : 200,
contents :
[
{
id : 'tab1',
label : 'Player selection',
elements :
[
{
type : 'text',
id : 'player',
label : 'Pick player user name',
validate : CKEDITOR.dialog.validate.notEmpty( "Player field cannot be empty" )
}
]
}
],
onOk : function()
{
var dialog = this;
var player = dialog.getValueOf( 'tab1', 'player' );
editor.insertHtml( '\n<span class="player-data">{player:' + player + '}</span>\n' );
}
};
});
editor.ui.addButton('AddPlayer',
{
label: 'Insert a player',
command: 'addPlayer',
icon: this.path + 'images/player.png'
});
},
initAddRaceImage: function ( editor )
{
editor.addCommand('addRaceImage', new CKEDITOR.dialogCommand( 'addRaceImageDialog' ) );
CKEDITOR.dialog.add( 'addRaceImageDialog', function(editor)
{
return {
title : 'Insert a race image',
minWidth : 400,
minHeight : 200,
contents :
[
{
id : 'sc2',
label : 'StarCraft 2',
elements :
[
{
type : 'select',
id : 'race',
label : 'Pick race',
items: [
['random', 'random'],
['protoss', 'protoss'],
['terran', 'terran'],
['zerg', 'zerg']
],
validate : CKEDITOR.dialog.validate.notEmpty( "Race field cannot be empty" )
}
]
}
],
onOk : function()
{
var dialog = this;
var race = dialog.getValueOf( 'sc2', 'race' );
editor.insertHtml( '\n<img src="/bundles/ihqsnuitblanche/images/ico/' + race + '_icon.png" class="race-icon" />\n' );
}
};
});
editor.ui.addButton('AddRaceImage',
{
label: 'Insert a race icon',
command: 'addRaceImage',
icon: '/bundles/ihqsnuitblanche/images/ico/random_icon.png'
});
},
initAddClanWar: function ( editor )
{
editor.addCommand('addClanWar', new CKEDITOR.dialogCommand( 'addClanWarDialog' ) );
CKEDITOR.dialog.add( 'addClanWarDialog', function(editor)
{
return {
title : 'Insert a clan war result',
minWidth : 400,
minHeight : 200,
contents :
[
{
id : 'tab1',
label : 'Pick clan war id',
elements :
[
{
type : 'text',
id : 'war',
label : 'Clan War',
validate : CKEDITOR.dialog.validate.notEmpty( "Clan War field cannot be empty" )
}
]
}
],
onOk : function()
{
var dialog = this;
var war = dialog.getValueOf( 'tab1', 'war' );
editor.insertHtml( '\n<div class="news-war">{war:' + war + '}</div>\n' );
}
};
});
editor.ui.addButton('AddClanWar',
{
label: 'Insert a clan war result',
command: 'addClanWar',
icon: this.path + 'images/war.png'
});
}
});
|
/*
* JavaScript / Canvas teaching framwork
* (C)opyright Kristian Hildebrand, khildebrand@beuth-hochschule.de
*
* Module: BufferGeometry
*
* BufferGeometry Vertex-Arrays and Vertex-Attributes
* stored in float32 arrays for the given attributes.
* In our cases we assume all attributes have
* numItems*3 size e.g. position (x, y, z), color (r, g, b)
*
* BufferGeometry is (at least for now) used to render Points with
* vertexcolors.
* Therefore we add a point material (THREE.PointsMaterial) and point container (THREE.Points).
*
*/
/* requireJS module definition */
define(["three"],
(function (THREE) {
"use strict";
var BufferGeometry = function (point, line, triangle, solid, wf) {
this.isPoint = point || false;
this.isLine = line || false;
this.isTriangle = triangle || false;
this.isSolid = solid || false;
this.isWireframe = wf || false;
this.mesh = undefined;
this.geometry = new THREE.BufferGeometry();
/**
* Adds a vertex attribute, we assume each element has three components, e.g.
* [position_x0, position_y0, position_z0, position_x1, position_y1, position_z1,...]
* AddAttribute updates the mesh.
*
* @param name vertex attributes name, e.g. position, color, normal
* @param buffer
*/
this.addAttribute = function (name, buffer) {
this.geometry.addAttribute(name, new THREE.BufferAttribute(buffer, 3));
this.geometry.computeBoundingSphere();
this.mesh = this.setMesh(this.geometry);
}
this.getMesh = function () {
return this.mesh;
}
this.setIndex = function (indices) {
this.geometry.setIndex(new THREE.BufferAttribute(indices, 1));
}
this.setMesh = function (geo) {
if (this.isPoint) {
var mat = new THREE.PointsMaterial({
color: 0xaaaaaa,
size: 10, vertexColors: THREE.VertexColors
});
return new THREE.Points(geo, mat);
} else if (this.isLine) {
var mat = new THREE.LineBasicMaterial({vertexColors: THREE.VertexColors});
return new THREE.Line(geo, mat);
} else if (this.isTriangle) {
var mat = new THREE.MeshPhongMaterial({
color: 0xaaaaaa, specular: 0xffffff, shininess: 250,
side: 2, vertexColors: THREE.VertexColors
});
return new THREE.Mesh(geo, mat);
} else if (this.isSolid && !this.isWireframe) {
var mat = new THREE.MeshLambertMaterial({color: 0x2194ce, emissive: 0x000000, side: 2});
return new THREE.Mesh(geo, mat);
} else if (this.isWireframe && !this.isSolid) {
var mat = new THREE.MeshLambertMaterial({color: 0x0000ff, wireframe: true});
return new THREE.Mesh(geo, mat);
}else if(this.isWireframe && this.isSolid){
var materials = [
new THREE.MeshLambertMaterial({color: 0xcc0000, emissive: 0x000000, side: 2}),
new THREE.MeshLambertMaterial({color: 0x000000, wireframe: true})
];
return new THREE.SceneUtils.createMultiMaterialObject(geo, materials);
} else {
return new THREE.PointsMaterial({
color: 0xaaaaaa,
size: 10, vertexColors: THREE.VertexColors
});
}
}
};
return BufferGeometry;
}));
|
'use strict';
const expect = require('chai').use(require('chai-string')).expect;
const RSVP = require('rsvp');
const request = RSVP.denodeify(require('request'));
const AddonTestApp = require('ember-cli-addon-tests').AddonTestApp;
describe('head content acceptance', function() {
this.timeout(300000);
let app;
before(function() {
app = new AddonTestApp();
return app.create('head-content', {
skipNpm: true
})
.then(addDependencies)
.then(function() {
return app.startServer({
command: 'serve'
});
});
});
after(function() {
return app.stopServer();
});
it('/ Has head content replaced', function() {
return request({
url: 'http://localhost:49741/',
headers: {
'Accept': 'text/html'
}})
.then(function(response) {
expect(response.statusCode).to.equal(200);
expect(response.headers["content-type"]).to.equalIgnoreCase("text/html; charset=utf-8");
expect(response.body).to.contain('<meta property="og:title" content="Head Data Title">');
expect(response.body).to.not.contain('<!-- EMBER_CLI_FASTBOOT_HEAD -->');
});
});
});
function addDependencies(app) {
app.editPackageJSON(function(pkg) {
pkg['devDependencies']['ember-cli-head'] = "0.3.1";
});
return app.run('npm', 'install');
}
|
'use strict';
// Configuring the Articles module
angular.module('functionaries').run(['Menus',
function(Menus) {
// Set top bar menu items
Menus.addMenuItem('topbar', 'Funcionarios', 'functionaries', 'dropdown', '/functionaries(/create)?');
Menus.addSubMenuItem('topbar', 'functionaries', 'Lista Funcionarios', 'functionaries');
Menus.addSubMenuItem('topbar', 'functionaries', 'Nuevo Funcionario', 'functionaries/create');
}
]);
|
function Animal(name){
this.name = name;
}
Animal.prototype.move = function(meters){
alert(this.name + " moved "+meters+"m.");
};
// Simplistic extend function just for this demo
Animal.extend = function(protoProps) {
var child = function(){
return Animal.apply(this, arguments);
};
var Surrogate = function(){
this.constructor = child;
};
Surrogate.prototype = Animal.prototype;
child.prototype = new Surrogate;
for(var key in protoProps){
if(protoProps.hasOwnProperty(key)){
child.prototype[key] = protoProps[key];
}
}
return child;
};
|
// Lifted from Ruby RDoc
function toggleSource( id ) {
var elem
var link
if( document.getElementById )
{
elem = document.getElementById( id )
link = document.getElementById( "l_" + id )
}
else if ( document.all )
{
elem = eval( "document.all." + id )
link = eval( "document.all.l_" + id )
}
else
return false;
if( elem.style.display == "block" )
{
elem.style.display = "none"
link.innerHTML = "Show duplicate lines source code"
}
else
{
elem.style.display = "block"
link.innerHTML = "Hide duplicate lines source code"
}
}
|
/**
@module ember
*/
import { get } from 'ember-metal';
/**
Finds an element in the context of the app's container element. A simple alias
for `app.$(selector)`.
Example:
```javascript
var $el = find('.my-selector');
```
With the `context` param:
```javascript
var $el = find('.my-selector', '.parent-element-class');
```
@method find
@param {String} selector jQuery string selector for element lookup
@param {String} [context] (optional) jQuery selector that will limit the selector
argument to find only within the context's children
@return {Object} jQuery object representing the results of the query
@public
*/
export default function find(app, selector, context) {
let $el;
context = context || get(app, 'rootElement');
$el = app.$(selector, context);
return $el;
}
|
var container, store;
var run = Ember.run;
module("unit/store/serializer_for - DS.Store#serializerFor", {
setup: function() {
store = createStore({ person: DS.Model.extend() });
container = store.container;
},
teardown: function() {
run(function() {
container.destroy();
store.destroy();
});
}
});
test("Calling serializerFor looks up 'serializer:<type>' from the container", function() {
var PersonSerializer = DS.JSONSerializer.extend();
container.register('serializer:person', PersonSerializer);
ok(store.serializerFor('person') instanceof PersonSerializer, "serializer returned from serializerFor is an instance of the registered Serializer class");
});
test("Calling serializerFor with a type that has not been registered looks up the default ApplicationSerializer", function() {
var ApplicationSerializer = DS.JSONSerializer.extend();
container.register('serializer:application', ApplicationSerializer);
ok(store.serializerFor('person') instanceof ApplicationSerializer, "serializer returned from serializerFor is an instance of ApplicationSerializer");
});
test("Calling serializerFor with a type that has not been registered and in an application that does not have an ApplicationSerializer looks up the default Ember Data serializer", function() {
ok(store.serializerFor('person') instanceof DS.JSONSerializer, "serializer returned from serializerFor is an instance of DS.JSONSerializer");
});
|
/*globals define, DEBUG, WebGMEGlobal, _*/
/*jshint browser: true*/
/**
* @author rkereskenyi / https://github.com/rkereskenyi
* @author nabana / https://github.com/nabana
*/
define(['lib/jquery/' + (DEBUG ? 'jquery.layout' : 'jquery.layout.min'),
'js/logger',
'./DefaultLayout',
'text!./templates/DefaultLayout.html',
'text!./VehicleForgeLayoutConfig.json'
], function (_jQueryLayout,
Logger,
DefaultLayout,
vehicleForgeLayoutTemplate,
VehicleForgeLayoutConfigJSON) {
'use strict';
var VehicleForgeLayout,
CONFIG = JSON.parse(VehicleForgeLayoutConfigJSON);
VehicleForgeLayout = function () {
this._logger = Logger.create('gme:Layouts:VehicleForgeLayout', WebGMEGlobal.gmeConfig.client.log);
//call parent's constructor
DefaultLayout.apply(this, [{
logger: this._logger,
panels: CONFIG.panels,
template: vehicleForgeLayoutTemplate
}]);
};
//inherit from PanelBaseWithHeader
_.extend(VehicleForgeLayout.prototype, DefaultLayout.prototype);
VehicleForgeLayout.prototype._onWestResize = function () {
var len = this._westPanels.length,
w = this._westPanel.width(),
h = this._westPanel.height(),
pHeight = Math.floor(h / len),
i;
for (i = 0; i < len; i += 1) {
this._westPanels[i].setSize(w, pHeight);
}
};
return VehicleForgeLayout;
});
|
'use strict';
const { Pattern } = require('hexo-util');
const moment = require('moment-timezone');
const micromatch = require('micromatch');
const DURATION_MINUTE = 1000 * 60;
function isMatch(path, patterns) {
if (!patterns) return false;
return micromatch.isMatch(path, patterns);
}
function isTmpFile(path) {
const last = path[path.length - 1];
return last === '%' || last === '~';
}
function isHiddenFile(path) {
return /(^|\/)[_.]/.test(path);
}
function isExcludedFile(path, config) {
if (isTmpFile(path)) return true;
if (isMatch(path, config.exclude)) return true;
if (isHiddenFile(path) && !isMatch(path, config.include)) return true;
return false;
}
exports.ignoreTmpAndHiddenFile = new Pattern(path => {
if (isTmpFile(path) || isHiddenFile(path)) return false;
return true;
});
exports.isTmpFile = isTmpFile;
exports.isHiddenFile = isHiddenFile;
exports.isExcludedFile = isExcludedFile;
exports.toDate = date => {
if (!date || moment.isMoment(date)) return date;
if (!(date instanceof Date)) {
date = new Date(date);
}
if (isNaN(date.getTime())) return;
return date;
};
exports.timezone = (date, timezone) => {
if (moment.isMoment(date)) date = date.toDate();
const offset = date.getTimezoneOffset();
const ms = date.getTime();
const target = moment.tz.zone(timezone).utcOffset(ms);
const diff = (offset - target) * DURATION_MINUTE;
return new Date(ms - diff);
};
exports.isMatch = isMatch;
|
version https://git-lfs.github.com/spec/v1
oid sha256:3550a1488d756d6bba42e75ad504d09db118f962acc2aade993b220ba8cf708d
size 15972
|
/*
The MIT License (MIT)
Copyright (c) 2014 NTHUOJ team
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
var editor;
var adjustEditorSize;
$(function () {
editor = CodeMirror.fromTextArea(document.getElementById('code_editor'), {
mode: 'text/x-c++src',
theme: 'solarized light',
keyMap: 'sublime',
placeholder: 'Code goes here...',
// line settings
lineNumbers: true,
lineWrapping: true,
styleActiveLine: true,
// indent settings
indentUnit: 4,
indentWithTabs: true,
matchBrackets: true,
autoCloseBrackets: true,
showCursorWhenSelecting: true
});
var adjustEditorSize = function (editor) {
// Adjust editor size according to the line count
lineCount = editor.lineCount()
lineHeight = $('.CodeMirror-gutter-wrapper').height()
editorWidth = $('.CodeMirror').width()
editorHeight = Math.max(400, Math.min(lineCount*lineHeight + 50, 2000))
editor.setSize(editorWidth, editorHeight)
}
var fire;
var sublimePatch = function (editor, key) {
// Fix sublime keybinding can't use Backspace
if(fire && editor.getCursor().ch == 0 && key == 'Backspace') {
editor.execCommand('delCharBefore');
fire = false;
}
fire = editor.getCursor().ch == 0;
}
// Adjust editor size on load
adjustEditorSize(editor)
// Adjust editor size on change
editor.on('change', adjustEditorSize)
editor.on('keyHandled', sublimePatch)
$('#fileinput').bootstrapFileInput();
$('#fileinput').change(function(evt) {
//Retrieve the first (and only!) File from the FileList object
var file = evt.target.files[0];
if (file) {
if (file.size > 10000) {
alert('You can\'t upload file over 10000 bytes.');
} else {
var reader = new FileReader();
reader.onload = function(e) {
var contents = e.target.result;
try {
editor.getDoc().setValue(contents);
} catch (e) {
}
};
reader.readAsText(file);
}
} else {
alert('Failed to load file');
}
})
})
|
"use strict";
var _asyncToGenerator = function (fn) {
return function () {
var gen = fn.apply(this, arguments);
return new Promise(function (resolve, reject) {
function step(getNext) {
var next;
try {
next = getNext();
} catch (e) {
reject(e);
return;
}
if (next.done) {
resolve(next.value);
return;
}
Promise.resolve(next.value).then(function (v) {
step(function () {
return gen.next(v);
});
}, function (e) {
step(function () {
return gen["throw"](e);
});
});
}
step(function () {
return gen.next();
});
});
};
};
var foo = _asyncToGenerator(function* () {
var wat = yield bar();
});
|
{
id: 'music.baidu.yinyueyun',
name: '音乐云下载',
host: 'yinyueyun.baidu.com',
noSubHost: true,
path: '/',
onStart: function () {
H.waitUntil('userModel.set', function () {
unsafeExec(function (scriptName, hookBatch) {
var bakUserSetInfo = userModel.set;
userModel.set = function (key, val, opts) {
if (key === 'userInfo' && val) {
val.vip = val.golden = true;
}
return bakUserSetInfo.apply(userModel, arguments);
};
// Force update user data via hook
userModel.set('userInfo', userModel.get('userInfo'));
});
});
}
}
|
"use strict";
/*Dispatch provides functionality to run multiple asynchronous functions
in sequence. These functions can use the express.js style middleware
interface.
*/
module.exports = function Dispatch() {
var self = this; //hold scope reference
this.processQueue = null; //Queue for middleware and route
this.res = null; //Hold response object
this.req = null; //Hold request object
//Execute queue / dispatch callbacks
this.exec = function exec(req, res, routeQueue){
self.config = self.config || {}; //Read config object
self.processQueue = self.processQueue || routeQueue;
var queue = self.processQueue;
self.req = self.req || req;
self.res = self.res || res;
if(queue.length){ //If we are still in our queue
var params = queue[0].params; //Set our params
queue.shift().func //Call our first queue task
.apply(self, [].concat.apply([self.req, self.res, self.exec],params));
}
return false; //Begin teardown
};
};
|
'use strict';
// Notes controller
angular.module('notes').controller('NotesController', ['$scope', '$stateParams', '$location', 'Authentication', 'Notes',
function($scope, $stateParams, $location, Authentication, Notes ) {
$scope.authentication = Authentication;
// Create new Note
$scope.create = function() {
// Create new Note object
var note = new Notes ({
name: this.name
});
// Redirect after save
note.$save(function(response) {
$location.path('notes/' + response._id);
// Clear form fields
$scope.name = '';
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
// Remove existing Note
$scope.remove = function( note ) {
if ( note ) { note.$remove();
for (var i in $scope.notes ) {
if ($scope.notes [i] === note ) {
$scope.notes.splice(i, 1);
}
}
} else {
$scope.note.$remove(function() {
$location.path('notes');
});
}
};
// Update existing Note
$scope.update = function() {
var note = $scope.note ;
note.$update(function() {
$location.path('notes/' + note._id);
}, function(errorResponse) {
$scope.error = errorResponse.data.message;
});
};
// Find a list of Notes
$scope.find = function() {
$scope.notes = Notes.query();
};
// Find existing Note
$scope.findOne = function() {
$scope.note = Notes.get({
noteId: $stateParams.noteId
});
};
}
]);
|
/* Imports for global scope */
d3 = Package.d3.d3;
_ = Package.underscore._;
Accounts = Package['accounts-base'].Accounts;
RouteController = Package['iron-router'].RouteController;
Route = Package['iron-router'].Route;
Router = Package['iron-router'].Router;
IronLocation = Package['iron-router'].IronLocation;
$ = Package.jquery.$;
jQuery = Package.jquery.jQuery;
AutoForm = Package.autoform.AutoForm;
Roles = Package.roles.Roles;
moment = Package.moment.moment;
Packmeteor = Package.packmeteor.Packmeteor;
Meteor = Package.meteor.Meteor;
WebApp = Package.webapp.WebApp;
Log = Package.logging.Log;
Deps = Package.deps.Deps;
Session = Package.session.Session;
DDP = Package.livedata.DDP;
UI = Package.ui.UI;
Handlebars = Package.ui.Handlebars;
Spacebars = Package.spacebars.Spacebars;
Template = Package.templating.Template;
check = Package.check.check;
Match = Package.check.Match;
Random = Package.random.Random;
EJSON = Package.ejson.EJSON;
FS = Package['cfs-base-package'].FS;
SimpleSchema = Package['simple-schema'].SimpleSchema;
SchemaRegEx = Package['simple-schema'].SchemaRegEx;
MongoObject = Package['simple-schema'].MongoObject;
HTML = Package.htmljs.HTML;
|
module.exports = {
entry: './entry.js',
output: {
filename: 'bundle.js'
},
module: {
loaders: [{
test: /\.less$/,
loader: 'style-loader!css-loader!less-loader'
}]
}
};
|
/**
* Copyright 2016-2017 aixigo AG
* Released under the MIT license.
* http://laxarjs.org/license
*/
'use strict';
import { expect } from 'chai';
import * as laxarTooling from '../src/index';
describe( 'laxar-tooling', () => {
it( 'exports the artifactCollector', () => {
expect( laxarTooling.artifactCollector ).to.respondTo( 'create' );
} );
it( 'exports the artifactValidator', () => {
expect( laxarTooling.artifactValidator ).to.respondTo( 'create' );
} );
it( 'exports the assetResolver', () => {
expect( laxarTooling.assetResolver ).to.respondTo( 'create' );
} );
it( 'exports the artifactListing', () => {
expect( laxarTooling.artifactListing ).to.respondTo( 'create' );
} );
it( 'exports the serialize function', () => {
expect( laxarTooling ).to.respondTo( 'serialize' );
} );
} );
|
var request = require('./request');
var redis = require('./redis');
var util = require('util');
var config = require('../config/weixin');
var phantom = require('phantom');
function Salt() {
this.apiUrl = config.api.getEncryptSalt;
this.cacheId = config.saltCachePolicy.cacheId;
this.lifeTime = config.saltCachePolicy.lifeTime;
}
Salt.prototype.get = function*() {
return yield redis.get(this.cacheId);
}
Salt.prototype.save = function*(salt) {
yield redis.setex(this.cacheId, this.lifeTime, salt);
}
Salt.prototype.collect = function*(headers) {
var result =
yield request(this.apiUrl, {
headers: headers
});
if (!result.error && result.statusCode == 200) {
console.log(this.apiUrl);
var match = result.body.match(/SogouEncrypt\.setKv\(\"(.*?)\"\)/);
if (match && match[1]) {
sale = match[1].replace('","', ',');
return sale;
}
}
return '';
}
Salt.prototype.destroy = function*() {
return yield redis.del(this.cacheId);
}
module.exports = new Salt();
|
var util2 = require('./util2');
var myutil = {};
myutil.shadow = function(a, b) {
for (var k in a) {
if (typeof b[k] === 'undefined') {
b[k] = a[k];
}
}
return b;
};
myutil.defun = function(fn, fargs, fbody) {
if (!fbody) {
fbody = fargs;
fargs = [];
}
return new Function('return function ' + fn + '(' + fargs.join(', ') + ') {' + fbody + '}')();
};
myutil.slog = function() {
var args = [];
for (var i = 0, ii = arguments.length; i < ii; ++i) {
args[i] = util2.toString(arguments[i]);
}
return args.join(' ');
};
myutil.toObject = function(key, value) {
if (typeof key === 'object') {
return key;
}
var obj = {};
obj[key] = value;
return obj;
};
myutil.flag = function(flags) {
if (typeof flags === 'boolean') {
return flags;
}
for (var i = 1, ii = arguments.length; i < ii; ++i) {
if (flags[arguments[i]]) {
return true;
}
}
return false;
};
myutil.toFlags = function(flags) {
if (typeof flags === 'string') {
flags = myutil.toObject(flags, true);
} else {
flags = !!flags;
}
return flags;
};
/**
* Returns an absolute path based on a root path and a relative path.
*/
myutil.abspath = function(root, path) {
if (!path) {
path = root;
}
if (path.match(/^\/\//)) {
var m = root && root.match(/^(\w+:)\/\//);
path = (m ? m[1] : 'http:') + path;
}
if (root && !path.match(/^\w+:\/\//)) {
path = root + path;
}
return path;
};
/**
* Converts a name to a C constant name format of UPPER_CASE_UNDERSCORE.
*/
myutil.toCConstantName = function(x) {
x = x.toUpperCase();
x = x.replace(/[- ]/g, '_');
return x;
};
module.exports = myutil;
|
var searchData=
[
['window',['Window',['../classlm_1_1_window.html',1,'lm']]]
];
|
describe('Mixin', function() {
var IdMixin = {
getId: function() {
return this._riot_id
}
}
var OptsMixin = {
getOpts: function() {
return this.opts
},
setOpts: function(options, update) {
this.opts = options
if (!update) {
this.update()
}
return this
}
}
var MixinWithInit = {
init: function() {
this.message = 'initialized'
},
message: 'not yet'
}
it('Will mount a tag and provide mixed-in methods', function() {
var mix = document.createElement('my-mixin')
document.body.appendChild(mix)
riot.tag('my-mixin', '<span>some tag</span>', function(opts) {
this.mixin(IdMixin)
})
var tag = riot.mount('my-mixin')[0]
expect(tag._riot_id).to.be(tag.getId())
tag.unmount()
})
it('Will mount a tag and provide mixed-in methods from an function constructor instance', function() {
var mix = document.createElement('my-mixin')
document.body.appendChild(mix)
function RootMixin() {
this.getRoot = function() {
return this.root
}
}
var rootmixin = new RootMixin()
riot.tag('my-mixin', '<span>some tag</span>', function(opts) {
this.mixin(rootmixin)
})
var tag = riot.mount('my-mixin')[0]
expect(tag.root).to.be(tag.getRoot())
tag.unmount()
})
it('Will mount two tags, each having separate mix-in methods', function() {
var one = document.createElement('my-mixin2'),
two = document.createElement('my-mixin2')
one.setAttribute('id', 'one')
two.setAttribute('id', 'two')
document.body.appendChild(one)
document.body.appendChild(two)
riot.tag('my-mixin2', '<span>some tag</span>', function(opts) {
this.mixin(IdMixin)
})
var first = riot.mount('#one')[0],
second = riot.mount('#two')[0]
expect(first._riot_id).to.be(first.getId())
expect(second._riot_id).to.be(second.getId())
expect(first._riot_id).not.to.be(second._riot_id)
expect(first.getId()).not.to.be(second.getId())
first.unmount()
second.unmount()
})
it('Will mount a tag with multiple mixins mixed-in', function() {
var mix = document.createElement('my-mixin')
document.body.appendChild(mix)
riot.tag('my-mixin', '<span>some tag</span>', function(opts) {
this.mixin(IdMixin, OptsMixin)
})
var tag = riot.mount('my-mixin')[0],
newOpts = {'some': 'option', 'value': Math.random()}
expect(tag._riot_id).to.be(tag.getId())
expect(tag.opts).to.be(tag.getOpts())
tag.setOpts(newOpts)
expect(tag.opts).to.be(tag.getOpts())
tag.unmount()
})
it('Will mount a parent tag with a mixin and a sub-tag wtih a mixin', function() {
var mix = document.createElement('my-mixin')
document.body.appendChild(mix)
riot.tag('my-mixin', '<span>some tag</span><sub-mixin></sub-mixin>', function(opts) {
this.mixin(IdMixin, OptsMixin)
})
riot.tag('sub-mixin', '<span>sub mixin</span>', function(opts) {
this.mixin(IdMixin)
})
var tag = riot.mount('my-mixin')[0]
expect(tag._riot_id).to.be(tag.getId())
expect(tag.tags['sub-mixin']).not.to.be('undefined')
expect(tag.tags['sub-mixin']._riot_id).to.be(tag.tags['sub-mixin'].getId())
expect(tag.getId()).not.to.be(tag.tags['sub-mixin'].getId())
tag.unmount()
})
it('binds this-reference to the tag object', function() {
var mix = document.createElement('my-mixin')
document.body.appendChild(mix)
riot.tag('my-mixin', '<span>some tag { getId() }</span>', function(opts) {
this.mixin(IdMixin)
})
var tag = riot.mount('my-mixin')[0]
expect(tag.root.innerHTML).to.be('<span>some tag ' + tag._riot_id + '</span>')
tag.unmount()
})
it('initializes the mixin', function() {
var mix = document.createElement('my-mixin')
document.body.appendChild(mix)
riot.tag('my-mixin', '<span>some tag</span>', function(opts) {
this.mixin(MixinWithInit)
})
var tag = riot.mount('my-mixin')[0]
expect(tag.message).to.be('initialized')
tag.unmount()
})
it('register a mixin to Riot and load mixin to a tag', function() {
var mix = document.createElement('my-mixin')
document.body.appendChild(mix)
riot.mixin('idMixin', IdMixin) // register mixin
riot.tag('my-mixin', '<span>some tag</span>', function(opts) {
this.mixin('idMixin') // load mixin
})
var tag = riot.mount('my-mixin')[0]
expect(tag._riot_id).to.be(tag.getId())
tag.unmount()
})
})
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.throttle = exports.takeLatest = exports.takeEvery = undefined;
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
exports.takeEveryHelper = takeEveryHelper;
exports.takeLatestHelper = takeLatestHelper;
exports.throttleHelper = throttleHelper;
var _channel = require('./channel');
var _utils = require('./utils');
var _io = require('./io');
var _buffers = require('./buffers');
var done = { done: true, value: undefined };
var qEnd = {};
function fsmIterator(fsm, q0) {
var name = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'iterator';
var updateState = void 0,
qNext = q0;
function next(arg, error) {
if (qNext === qEnd) {
return done;
}
if (error) {
qNext = qEnd;
throw error;
} else {
updateState && updateState(arg);
var _fsm$qNext = fsm[qNext](),
_fsm$qNext2 = _slicedToArray(_fsm$qNext, 3),
q = _fsm$qNext2[0],
output = _fsm$qNext2[1],
_updateState = _fsm$qNext2[2];
qNext = q;
updateState = _updateState;
return qNext === qEnd ? done : output;
}
}
return (0, _utils.makeIterator)(next, function (error) {
return next(null, error);
}, name, true);
}
function safeName(patternOrChannel) {
if (_utils.is.channel(patternOrChannel)) {
return 'channel';
} else if (Array.isArray(patternOrChannel)) {
return String(patternOrChannel.map(function (entry) {
return String(entry);
}));
} else {
return String(patternOrChannel);
}
}
function takeEveryHelper(patternOrChannel, worker) {
for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
args[_key - 2] = arguments[_key];
}
var yTake = { done: false, value: (0, _io.take)(patternOrChannel) };
var yFork = function yFork(ac) {
return { done: false, value: _io.fork.apply(undefined, [worker].concat(args, [ac])) };
};
var action = void 0,
setAction = function setAction(ac) {
return action = ac;
};
return fsmIterator({
q1: function q1() {
return ['q2', yTake, setAction];
},
q2: function q2() {
return action === _channel.END ? [qEnd] : ['q1', yFork(action)];
}
}, 'q1', 'takeEvery(' + safeName(patternOrChannel) + ', ' + worker.name + ')');
}
function takeLatestHelper(patternOrChannel, worker) {
for (var _len2 = arguments.length, args = Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) {
args[_key2 - 2] = arguments[_key2];
}
var yTake = { done: false, value: (0, _io.take)(patternOrChannel) };
var yFork = function yFork(ac) {
return { done: false, value: _io.fork.apply(undefined, [worker].concat(args, [ac])) };
};
var yCancel = function yCancel(task) {
return { done: false, value: (0, _io.cancel)(task) };
};
var task = void 0,
action = void 0;
var setTask = function setTask(t) {
return task = t;
};
var setAction = function setAction(ac) {
return action = ac;
};
return fsmIterator({
q1: function q1() {
return ['q2', yTake, setAction];
},
q2: function q2() {
return action === _channel.END ? [qEnd] : task ? ['q3', yCancel(task)] : ['q1', yFork(action), setTask];
},
q3: function q3() {
return ['q1', yFork(action), setTask];
}
}, 'q1', 'takeLatest(' + safeName(patternOrChannel) + ', ' + worker.name + ')');
}
function throttleHelper(delayLength, pattern, worker) {
for (var _len3 = arguments.length, args = Array(_len3 > 3 ? _len3 - 3 : 0), _key3 = 3; _key3 < _len3; _key3++) {
args[_key3 - 3] = arguments[_key3];
}
var action = void 0,
channel = void 0;
var yActionChannel = { done: false, value: (0, _io.actionChannel)(pattern, _buffers.buffers.sliding(1)) };
var yTake = function yTake() {
return { done: false, value: (0, _io.take)(channel) };
};
var yFork = function yFork(ac) {
return { done: false, value: _io.fork.apply(undefined, [worker].concat(args, [ac])) };
};
var yDelay = { done: false, value: (0, _io.call)(_utils.delay, delayLength) };
var setAction = function setAction(ac) {
return action = ac;
};
var setChannel = function setChannel(ch) {
return channel = ch;
};
return fsmIterator({
q1: function q1() {
return ['q2', yActionChannel, setChannel];
},
q2: function q2() {
return ['q3', yTake(), setAction];
},
q3: function q3() {
return action === _channel.END ? [qEnd] : ['q4', yFork(action)];
},
q4: function q4() {
return ['q2', yDelay];
}
}, 'q1', 'throttle(' + safeName(pattern) + ', ' + worker.name + ')');
}
var deprecationWarning = function deprecationWarning(helperName) {
return 'import ' + helperName + ' from \'redux-saga\' has been deprecated in favor of import ' + helperName + ' from \'redux-saga/effects\'.\nThe latter will not work with yield*, as helper effects are wrapped automatically for you in fork effect.\nTherefore yield ' + helperName + ' will return task descriptor to your saga and execute next lines of code.';
};
var takeEvery = exports.takeEvery = (0, _utils.deprecate)(takeEveryHelper, deprecationWarning('takeEvery'));
var takeLatest = exports.takeLatest = (0, _utils.deprecate)(takeLatestHelper, deprecationWarning('takeLatest'));
var throttle = exports.throttle = (0, _utils.deprecate)(throttleHelper, deprecationWarning('throttle'));
|
'use strict';
const MiddlewareError = require('../MiddlewareError');
/**
* A parameter error.
*/
class ParameterError extends MiddlewareError {
/**
* Creates a new parameter error.
* @param {DiscordCommandRequest} request - The request.
*/
constructor(request) {
const command = request.getRoute().getCommand().getId();
super(`Missing required parameters for command '${command}' (user: ${request.getMessage().author.tag})`, request);
this.name = 'ParameterError';
Error.captureStackTrace(this, this.constructor);
}
}
module.exports = ParameterError;
|
var express = require('express');
var mongoose = require('mongoose');
var favicon = require('serve-favicon');
var app = express();
app.set('port', (process.env.PORT || 8443));
var fs = require('fs');
var https = require('https');
var privateKey = fs.readFileSync(__dirname + '/server.key');
var certificate = fs.readFileSync(__dirname + '/server.cert');
var credentials = {key: privateKey, cert: certificate};
var db = process.env.MONGOLAB_URI || 'mongodb://localhost/vcp';
mongoose.connect(db);
// routing handled in middleware
require('./config/middleware.js')(app, express);
// serve favicon
app.use(favicon(__dirname + '/../client/assets/favicon.ico'));
//Did not get Heroku working with https
// var httpsServer = https.createServer(credentials, app);
app.listen(app.get('port'));
console.log('Listening to port ' + app.get('port'));
module.exports = app;
|
const util = require('util');
const LOG_LEVEL = Object.freeze({
TRACE: 10,
DEBUG: 20,
INFO: 30,
WARN: 40,
ERROR: 50
});
function isValidLevel(level) {
const configuredLogLevel = process.env.NODE_LOG_LEVEL || 'info';
return LOG_LEVEL[level] >= LOG_LEVEL[configuredLogLevel.toUpperCase()];
}
function log(level) {
if (!isValidLevel(level)) {
return;
}
const args = Array.from(arguments).slice(1);
const errors = args.filter(x => x instanceof Error);
const objects = args.filter(x => !(x instanceof Error) && x instanceof Object);
const message = args.filter(x => !(x instanceof Object)).join(' ');
const output = [
new Date().toISOString(),
level,
message
];
console.log(output.join(' '));
errors.forEach(x => console.log(' ' + x.stack));
objects.forEach(x => console.log(' ' + util.inspect(x)));
}
const logger = {
trace: log.bind(null, 'TRACE'),
debug: log.bind(null, 'DEBUG'),
info: log.bind(null, 'INFO'),
warn: log.bind(null, 'WARN'),
error: log.bind(null, 'ERROR')
};
module.exports = logger;
|
import React from 'react'
import { render } from 'react-dom'
import { Router, Route, IndexRoute, Link, IndexLink, browserHistory } from 'react-router'
const ACTIVE = { color: 'red' }
const App = ({ children }) => (
<div>
<h1>APP!</h1>
<ul>
<li><Link to="/" activeStyle={ACTIVE}>/</Link></li>
<li><IndexLink to="/" activeStyle={ACTIVE}>/ IndexLink</IndexLink></li>
<li><Link to="/users" activeStyle={ACTIVE}>/users</Link></li>
<li><IndexLink to="/users" activeStyle={ACTIVE}>/users IndexLink</IndexLink></li>
<li><Link to="/users/ryan" activeStyle={ACTIVE}>/users/ryan</Link></li>
<li><Link to={{ pathname: '/users/ryan', query: { foo: 'bar' } }}
activeStyle={ACTIVE}>/users/ryan?foo=bar</Link></li>
<li><Link to="/about" activeStyle={ACTIVE}>/about</Link></li>
</ul>
{children}
</div>
)
const Index = () => (
<div>
<h2>Index!</h2>
</div>
)
const Users = ({ children }) => (
<div>
<h2>Users</h2>
{children}
</div>
)
const UsersIndex = () => (
<div>
<h3>UsersIndex</h3>
</div>
)
const User = ({ params: { id } }) => (
<div>
<h3>User {id}</h3>
</div>
)
const About = () => (
<div>
<h2>About</h2>
</div>
)
render((
<Router history={browserHistory}>
<Route path="/" component={App}>
<IndexRoute component={Index}/>
<Route path="/about" component={About}/>
<Route path="users" component={Users}>
<IndexRoute component={UsersIndex}/>
<Route path=":id" component={User}/>
</Route>
</Route>
</Router>
), document.getElementById('example'))
|
import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M7 14H5v5h5v-2H7v-3zm-2-4h2V7h3V5H5v5zm12 7h-3v2h5v-5h-2v3zM14 5v2h3v3h2V5h-5z" />
, 'FullscreenSharp');
|
import L from 'leaflet';
import {
projectPatternOnPointPath,
parseRelativeOrAbsoluteValue,
} from './patternUtils.js';
import './L.Symbol.js';
const isCoord = c =>
(c instanceof L.LatLng) ||
(Array.isArray(c) && c.length === 2 && typeof c[0] === 'number');
const isCoordArray = ll => Array.isArray(ll) && isCoord(ll[0]);
L.PolylineDecorator = L.FeatureGroup.extend({
options: {
patterns: []
},
initialize: function(paths, options) {
L.FeatureGroup.prototype.initialize.call(this);
L.Util.setOptions(this, options);
this._map = null;
this._paths = this._initPaths(paths);
this._bounds = this._initBounds();
this._patterns = this._initPatterns(this.options.patterns);
},
/**
* Deals with all the different cases. input can be one of these types:
* array of LatLng, array of 2-number arrays, Polyline, Polygon,
* array of one of the previous.
*/
_initPaths: function(input, isPolygon) {
if (isCoordArray(input)) {
// Leaflet Polygons don't need the first point to be repeated, but we do
const coords = isPolygon ? input.concat([input[0]]) : input;
return [coords];
}
if (input instanceof L.Polyline) {
// we need some recursivity to support multi-poly*
return this._initPaths(input.getLatLngs(), (input instanceof L.Polygon));
}
if (Array.isArray(input)) {
// flatten everything, we just need coordinate lists to apply patterns
return input.reduce((flatArray, p) =>
flatArray.concat(this._initPaths(p, isPolygon)),
[]);
}
return [];
},
// parse pattern definitions and precompute some values
_initPatterns: function(patternDefs) {
return patternDefs.map(this._parsePatternDef);
},
/**
* Changes the patterns used by this decorator
* and redraws the new one.
*/
setPatterns: function(patterns) {
this.options.patterns = patterns;
this._patterns = this._initPatterns(this.options.patterns);
this.redraw();
},
/**
* Changes the patterns used by this decorator
* and redraws the new one.
*/
setPaths: function(paths) {
this._paths = this._initPaths(paths);
this._bounds = this._initBounds();
this.redraw();
},
/**
* Parse the pattern definition
*/
_parsePatternDef: function(patternDef, latLngs) {
return {
symbolFactory: patternDef.symbol,
// Parse offset and repeat values, managing the two cases:
// absolute (in pixels) or relative (in percentage of the polyline length)
offset: parseRelativeOrAbsoluteValue(patternDef.offset),
endOffset: parseRelativeOrAbsoluteValue(patternDef.endOffset),
repeat: parseRelativeOrAbsoluteValue(patternDef.repeat),
};
},
onAdd: function (map) {
this._map = map;
this._draw();
this._map.on('moveend', this.redraw, this);
},
onRemove: function (map) {
this._map.off('moveend', this.redraw, this);
this._map = null;
L.FeatureGroup.prototype.onRemove.call(this, map);
},
/**
* As real pattern bounds depends on map zoom and bounds,
* we just compute the total bounds of all paths decorated by this instance.
*/
_initBounds: function() {
const allPathCoords = this._paths.reduce((acc, path) => acc.concat(path), []);
return L.latLngBounds(allPathCoords);
},
getBounds: function() {
return this._bounds;
},
/**
* Returns an array of ILayers object
*/
_buildSymbols: function(latLngs, symbolFactory, directionPoints) {
return directionPoints.map((directionPoint, i) =>
symbolFactory.buildSymbol(directionPoint, latLngs, this._map, i, directionPoints.length)
);
},
/**
* Compute pairs of LatLng and heading angle,
* that define positions and directions of the symbols on the path
*/
_getDirectionPoints: function(latLngs, pattern) {
if (latLngs.length < 2) {
return [];
}
const pathAsPoints = latLngs.map(latLng => this._map.project(latLng));
return projectPatternOnPointPath(pathAsPoints, pattern)
.map(point => ({
latLng: this._map.unproject(L.point(point.pt)),
heading: point.heading,
}));
},
redraw: function() {
if (!this._map) {
return;
}
this.clearLayers();
this._draw();
},
/**
* Returns all symbols for a given pattern as an array of FeatureGroup
*/
_getPatternLayers: function(pattern) {
const mapBounds = this._map.getBounds().pad(0.1);
return this._paths.map(path => {
const directionPoints = this._getDirectionPoints(path, pattern)
// filter out invisible points
.filter(point => mapBounds.contains(point.latLng));
return L.featureGroup(this._buildSymbols(path, pattern.symbolFactory, directionPoints));
});
},
/**
* Draw all patterns
*/
_draw: function () {
this._patterns
.map(pattern => this._getPatternLayers(pattern))
.forEach(layers => { this.addLayer(L.featureGroup(layers)); });
}
});
/*
* Allows compact syntax to be used
*/
L.polylineDecorator = function (paths, options) {
return new L.PolylineDecorator(paths, options);
};
|
// The format of ```data``` structure:
// {
// 'data': [{'x':1, 'y':2}, {'x':3, 'y':4} ...],
// 'videoID' : ''
// }
if (!String.prototype.format) {
String.prototype.format = function() {
var args = arguments;
return this.replace(/{(\d+)}/g, function(match, number) {
return typeof args[number] != 'undefined'
? args[number]
: match
;
});
};
}
$.getJSON("/assets/json/segResultData.json", function(data) {
draw(data["1"], 1);
draw(data["2"], 2);
draw(data["3"], 3);
draw(data["4"], 4);
draw(data["5"], 5);
draw(data["6"], 6);
draw(data["7"], 7);
draw(data["8"], 8);
draw(data["9"], 9);
draw(data["10"], 10);
draw(data["11"], 11);
draw(data["12"], 12);
});
function draw(data, idx) {
nv.addGraph(
function() {
var chart = nv.models.lineChart()
.margin({left: 50}) //Adjust chart margins to give the x-axis some breathing room.
.useInteractiveGuideline(false) //We want nice looking tooltips and a guideline!
.duration(0) //how fast do you want the lines to transition?
.showLegend(true) //Show the legend, allowing users to turn on/off line series.
.showYAxis(true) //Show the y-axis
.showXAxis(true) //Show the x-axis
;
chart.xAxis //Chart x-axis settings
.axisLabel('#days after uploading')
.tickFormat(d3.format(',r'));
chart.yAxis //Chart y-axis settings
.axisLabel('viewcount')
.tickFormat(d3.format('d'));
d3.select("#chart{0} svg".format(idx))
.datum(data["data"])
.call(chart);
//Update the chart when window resizes.
nv.utils.windowResize(function() { chart.update(); });
return chart;
}
);
// set title
$("#title{0}".format(idx)).text("videoID: " + data["videoID"]).attr("href", "https://www.youtube.com/watch?v=" + data["videoID"]);
}
function process_data (data, idx) {
var ret = []; // return value
// add viewcount
var ii = 0;
var viewcount = [];
for (ii = 0; ii < data['viewcount'].length; ii++) {
viewcount.push({x: ii+1, y: data['viewcount'][ii]});
}
ret.push({
values: viewcount,
key: 'viewcount',
color: '#3399FF'
});
// add segments
if ( idx >= 0 ) {
var segInfo = data["segInfo"][idx];
var seg = [];
var k = 0;
var j = 0;
var si;
var startDay = 0;
for (k=0; k < segInfo.length; k++)
{
si = segInfo[k];
seg = [];
for ( j = 0; j < si.length; j++ )
{
seg.push({x:startDay+j+1, y: si[j]});
}
ret.push({
values: seg,
key: String.format('s{0}', k+1),
color: colorList[k%2],
'stroke-width': 5
});
startDay += si.length;
}
}
return ret;
}
|
(function (lib, img, cjs) {
var p; // shortcut to reference prototypes
// library properties:
lib.properties = {
width: 320,
height: 416,
fps: 24,
color: "#FFFFFF",
manifest: [{"src":"images/aaa.png","id":"aaa"},{"src":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAG0AAACUCAYAAACZZaeHAAABbElEQVR4nO3RwQkAIBDAsNP9d9YZfEkhmaDQNWfOkLJ/B/DOtCDTgkwLMi3ItCDTgkwLMi3ItCDTgkwLMi3ItCDTgkwLMi3ItCDTgkwLMi3ItCDTgkwLMi3ItCDTgkwLMi3ItCDTgkwLMi3ItCDTgkwLMi3ItCDTgkwLMi3ItCDTgkwLMi3ItCDTgkwLMi3ItCDTgkwLMi3ItCDTgkwLMi3ItCDTgkwLMi3ItCDTgkwLMi3ItCDTgkwLMi3ItCDTgkwLMi3ItCDTgkwLMi3ItCDTgkwLMi3ItCDTgkwLMi3ItCDTgkwLMi3ItCDTgkwLMi3ItCDTgkwLMi3ItCDTgkwLMi3ItCDTgkwLMi3ItCDTgkwLMi3ItCDTgkwLMi3ItCDTgkwLMi3ItCDTgkwLMi3ItCDTgkwLMi3ItCDTgkwLMi3ItCDTgkwLMi3ItCDTgkwLMi3ItCDTgkwLMi3ItCDTgkwLMi3ItCDTgi56SAMmqagYwwAAAABJRU5ErkJggg==","id":"bbb","type":"image"}]
};
// stage content:
(lib.Untitled = function(mode,startPosition,loop) {
this.initialize(mode,startPosition,loop,{});
// timeline functions:
this.frame_0 = function() {
var mage = this.moge.cloneWithSharingCache();
mage.x = 10;
this.addChild(mage);
}
// actions tween:
this.timeline.addTween(cjs.Tween.get(this).call(this.frame_0).wait(3));
// レイヤー 1
this.instance = new lib.bbb();
this.instance.setTransform(41,182);
this.instance_1 = new lib.aaa();
this.instance_1.setTransform(138,95);
this.timeline.addTween(cjs.Tween.get({}).to({state:[{t:this.instance_1},{t:this.instance}]}).wait(3));
}).prototype = p = new cjs.MovieClip();
p.nominalBounds = new cjs.Rectangle(201,303,143,235);
// symbols:
(lib.aaa = function() {
this.initialize(img.aaa);
}).prototype = p = new cjs.Bitmap();
p.nominalBounds = new cjs.Rectangle(0,0,46,79);
(lib.bbb = function() {
this.initialize(img.bbb);
}).prototype = p = new cjs.Bitmap();
p.nominalBounds = new cjs.Rectangle(0,0,109,148);
})(lib = lib||{}, images = images||{}, createjs = createjs||{});
var lib, images, createjs;
|
/*
* rate-test.js: Tests for the Rate reactor stream.
*
* (C) 2012, Nodejitsu Inc.
*
*/
var assert = require('assert'),
vows = require('vows'),
godot = require('../../lib/godot'),
macros = require('../macros').reactor;
vows.describe('godot/reactor/rate').addBatch({
"Godot rate": macros.shouldEmitData(
godot
.reactor()
.rate(50),
'pings',
1,
60,
function (all) {
assert.equal(all[0].metric, 1)
}
)
}).export(module);
|
define(['./_baseToString', './_castSlice', './_charsEndIndex', './_stringToArray', './toString'], function(baseToString, castSlice, charsEndIndex, stringToArray, toString) {
/** Used as a safe reference for `undefined` in pre-ES5 environments. */
var undefined;
/** Used to match leading and trailing whitespace. */
var reTrimEnd = /\s+$/;
/**
* Removes trailing whitespace or specified characters from `string`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category String
* @param {string} [string=''] The string to trim.
* @param {string} [chars=whitespace] The characters to trim.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
* @returns {string} Returns the trimmed string.
* @example
*
* _.trimEnd(' abc ');
* // => ' abc'
*
* _.trimEnd('-_-abc-_-', '_-');
* // => '-_-abc'
*/
function trimEnd(string, chars, guard) {
string = toString(string);
if (string && (guard || chars === undefined)) {
return string.replace(reTrimEnd, '');
}
if (!string || !(chars = baseToString(chars))) {
return string;
}
var strSymbols = stringToArray(string),
end = charsEndIndex(strSymbols, stringToArray(chars)) + 1;
return castSlice(strSymbols, 0, end).join('');
}
return trimEnd;
});
|
/* global describe, beforeEach, spyOn, expect, it, $, */
describe("Testing the alert service.", function () {
var scope, windowMock, createController, alertService;
beforeEach(function(){
angular.mock.module('trevor');
angular.mock.module('templates');
inject(function ($injector, AlertService) {
scope = $injector.get('$rootScope');
windowMock = $injector.get('$window');
alertService = AlertService;
});
});
it("Should raise a NATIVE alert.", function () {
var alert_msg = "Hello! I'm an alert!";
windowMock.navigator = {
notification: {
alert: function(data){
return false;
}
}
};
spyOn(windowMock.navigator.notification, 'alert').and.callThrough();
alertService.raiseAlert(alert_msg);
expect(windowMock.navigator.notification.alert).toHaveBeenCalled();
});
it("Should raise a NORMAL alert.", function () {
var alert_msg = "Hello! I'm an alert!";
windowMock.navigator = {
notification: false
};
spyOn(windowMock, 'alert').and.callThrough();
alertService.raiseAlert(alert_msg);
expect(windowMock.alert).toHaveBeenCalled();
});
});
|
var searchData=
[
['default_5fmac',['DEFAULT_MAC',['../group___hardware___m_a_c___a_p_is.html#gga4ea198f6b2879d432a068b4c3b27a387ac96ef4c7905cdf892863fe401b7abe7f',1,'esp_system.h']]],
['dhcp_5fstarted',['DHCP_STARTED',['../group___misc___a_p_is.html#gga9e40444d24f71f875b15136edec8fc47af861d0338581584e3be0abd10af2d0ff',1,'esp_misc.h']]],
['dhcp_5fstopped',['DHCP_STOPPED',['../group___misc___a_p_is.html#gga9e40444d24f71f875b15136edec8fc47a7c9cbdc204a9ed4b2a46cec8daeacfb8',1,'esp_misc.h']]],
['download_5ftimeout_5ferror',['DOWNLOAD_TIMEOUT_ERROR',['../group__system__upgrade___a_p_is.html#gga1e8876da5916ec8c91b126453fad76f9ab77f735cf673bbd1db50c9c99aede597',1,'upgrade.h']]]
];
|
import Component from '@glimmer/component';
import {isEmpty} from '@ember/utils';
/**
* Renders one random error message when passed a DS.Errors object
* and a property name. The message will be one of the ones associated with
* that specific property. If there are no errors associated with the property,
* nothing will be rendered.
* @param {DS.Errors} errors The DS.Errors object
* @param {string} property The property name
*/
export default class GhErrorMessage extends Component {
get message() {
let {property, errors} = this.args;
let messages = [];
let index;
if (!isEmpty(errors) && errors.get(property)) {
errors.get(property).forEach((error) => {
messages.push(error);
});
index = Math.floor(Math.random() * messages.length);
return messages[index].message;
}
return '';
}
}
|
'use strict';
module.exports = {
app: {
title: 'BSP-NYC',
description: 'Full-Stack JavaScript with MongoDB, Express, AngularJS, and Node.js',
keywords: 'MongoDB, Express, AngularJS, Node.js'
},
port: process.env.PORT || 3000,
templateEngine: 'swig',
sessionSecret: 'MEAN',
sessionCollection: 'sessions',
assets: {
lib: {
css: [
'public/lib/bootstrap/dist/css/bootstrap.css',
'public/lib/bootstrap/dist/css/bootstrap-theme.css',
],
js: [
'public/lib/angular/angular.js',
'public/lib/angular-resource/angular-resource.js',
'public/lib/angular-cookies/angular-cookies.js',
'public/lib/angular-animate/angular-animate.js',
'public/lib/angular-touch/angular-touch.js',
'public/lib/angular-sanitize/angular-sanitize.js',
'public/lib/angular-ui-router/release/angular-ui-router.js',
'public/lib/angular-ui-utils/ui-utils.js',
'public/lib/angular-bootstrap/ui-bootstrap-tpls.js'
]
},
css: [
'public/modules/**/css/*.css'
],
js: [
'public/config.js',
'public/application.js',
'public/modules/*/*.js',
'public/modules/*/*[!tests]*/*.js'
],
tests: [
'public/lib/angular-mocks/angular-mocks.js',
'public/modules/*/tests/*.js'
]
}
};
|
var searchData=
[
['basevalue',['BaseValue',['../class_drachenhorn_1_1_xml_1_1_sheet_1_1_skills_1_1_base_value.html#a939e0231f08b547ea974de457e731400',1,'Drachenhorn::Xml::Sheet::Skills::BaseValue']]]
];
|
var recognizer = new webkitSpeechRecognition();
recognizer.lang = "en";
recognizer.continuous = true;
//recognizer.interimResults = true;
recognizer.onresult = function(event) {
if (event.results.length > 0) {
var result = event.results[event.results.length - 1];
charlieResponse(result[0].transcript);
console.log(result[0].transcript);
}
};
recognizer.start();
var charlieResponse = function(speech) {
if (speech == 'Charlie Charlie can we play')
moveYes();
else if (speech.indexOf("Charlie") > -1 && speech.split(' ').length > 2) {
Math.random() < 0.5 ? moveYes() : moveNo();
} else {
moveNo();
}
setInterval(function() {
back()
}, 3000);
};
var moveYes = function() {
document.getElementById("verticalPen").className = "verticalPenAnimationTrue";
};
var moveNo = function() {
document.getElementById("verticalPen").className = "verticalPenAnimationFalse";
};
var back = function() {
document.getElementById("verticalPen").className = "verticalPenStopped";
};
|
import SimpleAreaChart from './SimpleAreaChart';
import StackedAreaChart from './StackedAreaChart';
import AreaChartConnectNulls from './AreaChartConnectNulls';
import CardinalAreaChart from './CardinalAreaChart';
import PercentAreaChart from './PercentAreaChart';
import SynchronizedAreaChart from './SynchronizedAreaChart';
import TinyAreaChart from './TinyAreaChart';
import AreaChartFillByValue from './AreaChartFillByValue';
export default {
SimpleAreaChart,
StackedAreaChart,
TinyAreaChart,
PercentAreaChart,
CardinalAreaChart,
AreaChartConnectNulls,
SynchronizedAreaChart,
AreaChartFillByValue,
};
|
var assert = require('assert');
var ServiceNode = require('lib/serviceDiscovery/node').ServiceNode;
describe('ServiceNode', function () {
describe('Constructor', function () {
it('should accept all the arguments', function (done) {
var host = 'test.local';
var port = '5678';
var addresses = [
'1.2.3.4'
];
var metadata = {
pid: 1234,
game: 'test',
version: '5.6.7'
};
var service = new ServiceNode(host, port, addresses, metadata);
assert.strictEqual(service.host, host);
assert.strictEqual(service.port, port);
assert.deepEqual(service.addresses, addresses);
assert.deepEqual(service.data, metadata);
done();
});
it('should build the default value for optional argument', function (done) {
var host = 'test.local';
var port = '5678';
var addresses = [
'1.2.3.4'
];
var service = new ServiceNode(host, port, addresses);
assert.strictEqual(service.host, host);
assert.strictEqual(service.port, port);
assert.deepEqual(service.addresses, addresses);
assert.deepEqual(service.data, {});
done();
});
});
describe('getIp()', function () {
it('should return null if there is no address', function (done) {
var service = new ServiceNode(null, null, []);
var ip = service.getIp();
assert.strictEqual(ip, null);
done();
});
it('should return the IP in the specified version', function (done) {
var service = new ServiceNode(null, null, [
'127.0.0.1',
'::1'
]);
var ip = service.getIp(4);
assert.strictEqual(ip, '127.0.0.1');
ip = service.getIp(6);
assert.strictEqual(ip, '::1');
done();
});
it('should filter the address list with the given network list', function (done) {
var service, ip;
var network = [
'10.0.0.0/8',
'172.16.0.0/12',
'192.168.0.0/16',
'127.0.0.0/8'
];
service = new ServiceNode(null, null, [
'1.2.3.4',
'5.6.7.8',
'10.20.30.40',
'::1'
]);
ip = service.getIp(4, network);
assert.strictEqual(ip, '10.20.30.40');
service = new ServiceNode(null, null, [
'1.2.3.4',
'5.6.7.8',
'172.16.32.64',
'::1'
]);
ip = service.getIp(4, network);
assert.strictEqual(ip, '172.16.32.64');
service = new ServiceNode(null, null, [
'1.2.3.4',
'5.6.7.8',
'192.168.144.120',
'::1'
]);
ip = service.getIp(4, network);
assert.strictEqual(ip, '192.168.144.120');
service = new ServiceNode(null, null, [
'1.2.3.4',
'5.6.7.8',
'127.0.0.1',
'::1'
]);
ip = service.getIp(4, network);
assert.strictEqual(ip, '127.0.0.1');
done();
});
});
});
|
(function(global) {
'use strict';
/**
* This class has properties that are to draw text on canvas.
* @param {string} text This argument is text that is drawn on canvas.
* @param {Point} point This argument is the instance of Point for text position.
* @param {TextStyle} textStyle This argument is the instance of TextStyle.
* @constructor
* @implements {Drawable}
*/
function Text(text, point, textStyle) {
// Call interface constructor
Mocks.ArtCanvas.Drawable.call(this);
this.text = String(text);
this.point = new Mocks.ArtCanvas.Point(0, 0);
this.textStyle = null;
if (point instanceof Mocks.ArtCanvas.Point) {
this.point = point;
}
if (textStyle instanceof Mocks.ArtCanvas.TextStyle) {
this.textStyle = textStyle;
}
}
/** @implements {Drawable} */
Text.prototype = Object.create(Mocks.ArtCanvas.Drawable.prototype);
Text.prototype.constructor = Text;
/**
* This method is getter for text that is drawn on canvas.
* @return {string} This is returned as text that is drawn on canvas.
*/
Text.prototype.getText = function() {
return this.text;
};
/**
* This method is getter for the instance of Point.
* @return {Point} This is returned as the instance of Point.
*/
Text.prototype.getPoint = function() {
return this.point;
};
/**
* This method is getter for the instance of TextStyle.
* @return {TextStyle} This is returned as the instance of TextStyle.
*/
Text.prototype.getTextStyle = function() {
return this.textStyle;
};
/** @override */
Text.prototype.draw = function(context) {
var font = this.textStyle.getFont();
var color = this.textStyle.getColor();
var heldColor = context.fillStyle;
context.font = font.getFontString();
context.fillStyle = color;
context.fillText(this.text, this.point.getX(), this.point.getY());
context.fillStyle = heldColor;
};
/** @override */
Text.prototype.getCenterPoint = function(context) {
var font = this.textStyle.getFont();
var fontSize = parseInt(font.getSize());
var centerX = this.point.getX() + (context.measureText(this.text).width / 2);
var centerY = this.point.getY() + (fontSize / 2);
return new Mocks.ArtCanvas.Point(centerX, centerY);
};
// Export
global.Text = Text;
})(window);
|
/*
JOTPOT OS
Copyright (c) 2017 Jacob O'Toole
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
let tasks = new Array() ;
let taskTypes = ["task-min","task-blur","task-focus"] ;
let currentlyFocused = -1 ;
if (cs.taskbarPosition === "bottom") {
taskbar.style.bottom = "0px" ;
desktop.style.top = "0px" ;
}
else if (cs.taskbarPosition === "top") {
taskbar.style.top = "0px" ;
desktop.style.bottom = "0px" ;
}
taskbar.style.backgroundColor = cs.taskbarBG ;
function toggleAll() {
windows.classList.toggle("min-all") ;
taskbar.classList.toggle("min-all") ;
document.getElementById("down_button").classList.toggle("acc-up-button") ;
}
document.getElementById("down_button").addEventListener("click",toggleAll) ;
//Use garbCollect function from windows.js
function addTask(up,title,focusFunc,pointer,hidden=false) {
let thisItem = document.createElement("div") ;
thisItem.classList.add("task") ;
thisItem.innerText = title ;
thisItem.classList.add(taskTypes[up]) ;
thisItem.addEventListener("click",_=>focusFunc("task")) ;
let task = {
set up(v) {
thisItem.classList.remove(taskTypes[up]) ;
up = v ;
thisItem.classList.add(taskTypes[up]) ;
},
get up() {
return up ;
},
elem:thisItem,
set title(v) {
thisItem.innerText = v ;
},
get title() {
return thisItem.innerText ;
},
pointer:pointer
} ;
if (hidden) {
thisItem.style.display = "none" ;
}
task.show =_=> {
thisItem.style.display = "inline-block" ;
} ;
task.hide =_=> {
thisItem.style.display = "none" ;
} ;
taskbar.appendChild(thisItem) ;
let index = tasks.push(task) - 1 ;
task.index = index ;
return task ;
}
function removeTask(task) {
taskbar.removeChild(task.elem) ;
tasks[task.index] = null ;
console.info("Rememer to call garbCollect after removeing a task!") ;
}
|
stage.loadFile('data://3pqr.pdb').then(function (o) {
o.addRepresentation('line')
o.addRepresentation('licorice', { radius: 0.3, sele: 'ring' })
o.addRepresentation('spacefill', { radius: 0.5, sele: 'aromaticRing' })
stage.autoView()
})
|
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import Header from '../components/header';
import { ActionCreators } from '../actions';
function mapStateToProps (state) {
const {
crimeDataRequested,
crimeData,
startingLocation,
endingLocation,
} = state;
return {
crimeDataRequested,
crimeData,
startingLocation,
endingLocation,
};
}
function mapDispatchToProps(dispatch) {
return bindActionCreators(ActionCreators, dispatch);
}
export default connect(mapStateToProps, mapDispatchToProps)(Header);
|
'use strict';
describe('Filter: job1Average', function () {
// load the filter's module
beforeEach(module('tbsApp'));
// initialize a new instance of the filter before each test
var job1Average;
beforeEach(inject(function ($filter) {
job1Average = $filter('job1Average');
}));
it('should return the input prefixed with "job1Average filter:"', function () {
var text = 'angularjs';
expect(job1Average(text)).toBe('job1Average filter: ' + text);
});
});
|
import typescript from 'rollup-plugin-typescript2';
import { baseConfig, plugins } from './base';
const env = process.env.NODE_ENV;
const filename = 'react-handsontable.js';
export const cjsConfig = {
output: {
format: env,
indent: false,
file: `./commonjs/${filename}`,
exports: 'named'
},
plugins: baseConfig.plugins,
};
|
/*jshint latedef:false */
var path = require('path'),
util = require('util'),
yeoman = require('../../../../');
module.exports = Generator;
function Generator() {
yeoman.generators.NamedBase.apply(this, arguments);
this.sourceRoot(path.join(__dirname, '../templates'));
// XXX default and banner to be implemented
this.argument('attributes', { type: Array, defaults: [], banner: 'field[:type] field[:type]' });
// parse back the attributes provided, build an array of attr
this.attrs = this.attributes.map(function(attr) {
var parts = attr.split(':');
return {
name: parts[0],
type: parts[1] || 'string'
};
});
this.appname = path.basename(process.cwd());
}
util.inherits(Generator, yeoman.generators.NamedBase);
Generator.prototype.createModelFiles = function createModelFiles() {
this.template('model.js', path.join('app/scripts/models', this.name + '-model.js'));
};
|
/*
* Focasearch
* Copyright 2014
* By @UTAustin
*
* Licensed under the MIT license. Please see LICENSE for more information.
*
*/
var FS={};window.onkeypress=function(e){e=e||window.event;var n=e.which||e.keyCode,o=String.fromCharCode(n);o.match(/[a-zA-Z0-9]/gi)&&FS.search_field.focus()},window.onkeyup=function(e){e=e||window.event;var n=e.which||e.keyCode;switch(parseInt(n)){case 27:FS.search_field.blur(),FS.search_field.value=""}},window.onload=function(){FS.search_field=document.getElementById("focasearch")};
|
var searchData=
[
['emplace',['emplace',['../classnsSdD_1_1CList.html#aef008f6b0cd75aa5c5e455df86bdeda6',1,'nsSdD::CList']]],
['emplace_5fback',['emplace_back',['../classnsSdD_1_1CList.html#a0ebfc3b0a8eae9e41806a0c26ff5c219',1,'nsSdD::CList']]],
['emplace_5ffront',['emplace_front',['../classnsSdD_1_1CList.html#ac6ed40bdbc813658193defa7e55b94d0',1,'nsSdD::CList']]],
['empty',['empty',['../classnsSdD_1_1CList.html#ad9c0ecbdedb0a8ad28625874f3c11c4d',1,'nsSdD::CList']]],
['end',['end',['../classnsSdD_1_1CList.html#ae1ed05415dfeb92174e030f9de754dc2',1,'nsSdD::CList']]],
['erase',['erase',['../classnsSdD_1_1CList.html#afa235a3273103e76c13c58d54a1cdf3c',1,'nsSdD::CList::erase(iterator del) noexcept'],['../classnsSdD_1_1CList.html#a4cb7fe2e6e4d3189b3a87f43ec6d4961',1,'nsSdD::CList::erase(iterator first, iterator last) noexcept']]]
];
|
version https://git-lfs.github.com/spec/v1
oid sha256:3a91d8c7df8b55b82f25317479c996bedb2e03ed24470b99573fb8b0074dbe26
size 4419
|
//>>built
define("dojo-data-model/sync",[],function(){return function(a,b,c,d){var f=a.watch(b,function(a,b,e){c.get(d)!==e&&c.set(d,e)}),g=c.watch(d,function(c,d,e){a.get(b)!==e&&a.set(b,e)});c.set(d,a.get(b));return{remove:function(){f.remove();g.remove()}}}});
//@ sourceMappingURL=sync.js.map
|
import { lazyReducerEnhancer } from '../lib'
import { createStore, combineReducers } from 'redux'
test('lazyReducerEnhancer', () => {
const syncReducers = {
first: (state = null, action) => {
return state
},
second: (state = null, action) => {
return state
}
}
const lazyReducers1 = {
a: (state = null, action) => {
return state
},
b: (state = null, action) => {
return state
}
}
const lazyReducers2 = {
c: (state = null, action) => {
return state
},
d: (state = null, action) => {
return state
}
}
const lazyReducers3 = {
d: (state = null, action) => {
return state
},
e: (state = null, action) => {
return state
}
}
const store = createStore(combineReducers(syncReducers), {}, lazyReducerEnhancer(syncReducers))
expect(store.getSyncReducers()).toBe(syncReducers)
store.addLazyReducers(lazyReducers1)
const l1 = store.getLazyReducers()
expect(
['a', 'b'].reduce((acc, cur) => {
return acc && Object.keys(l1).indexOf(cur) > -1
}, true)
).toBe(true)
expect(Object.keys(l1).length).toBe(2)
store.addLazyReducers(lazyReducers2)
const l2 = store.getLazyReducers()
expect(
['a', 'b', 'c', 'd'].reduce((acc, cur) => {
return acc && Object.keys(l2).indexOf(cur) > -1
}, true)
).toBe(true)
expect(Object.keys(l2).length).toBe(4)
store.addLazyReducers(lazyReducers3)
const l3 = store.getLazyReducers()
expect(
['a', 'b', 'c', 'd', 'e'].reduce((acc, cur) => {
return acc && Object.keys(l3).indexOf(cur) > -1
}, true)
).toBe(true)
expect(Object.keys(l3).length).toBe(5)
})
|
version https://git-lfs.github.com/spec/v1
oid sha256:2753d459041b30ce3087baad69fff1f5abffb3141d2bff98d429ecb1e98ee78a
size 948
|
import React from 'react';
import { mount } from 'enzyme';
import { StaticFiles } from '../StaticFiles';
import { staticfile } from './fixtures';
function setup(files=[staticfile]) {
const actions = {
fetchStaticFiles: jest.fn(),
uploadStaticFiles: jest.fn(),
deleteStaticFile: jest.fn(),
search: jest.fn()
};
const component = mount(
<StaticFiles
files={files}
isFetching={false}
{...actions} />
);
return {
component: component,
actions: actions,
h1: component.find('h1').last(),
info: component.find('.preview-info'),
previewContainer: component.find('.preview-container')
};
}
describe('Containers::StaticFiles', () => {
it('should render correctly', () => {
const { h1, info, previewContainer } = setup();
expect(h1.text()).toBe('Static Files');
expect(info.node).toBeFalsy();
expect(previewContainer.node).toBeTruthy();
});
it('should render correctly when there are not any files', () => {
const { info, previewContainer } = setup([]);
expect(info.node).toBeTruthy();
expect(previewContainer.node).toBeFalsy();
});
it('should call fetchStaticFiles action after mounted', () => {
const { actions } = setup();
expect(actions.fetchStaticFiles).toHaveBeenCalled();
});
});
|
(function(root, tests) {
if (typeof define === "function" && define.amd)
define(["expect", "object-observe"], tests);
else if (typeof exports === "object")
tests(require("benchmark"), global, require("../dist/object-observe.js"));
else tests(root.Benchmark, root);
})(this, function(Benchmark, root) {
"use strict";
root.generateObject = function(numberOfProperties) {
var object = {};
for (var i = 0; i < numberOfProperties; i++)
object["prop" + i] = i;
return object;
}
var padspace = (new Array(81)).join(" ");
function padL(text, length) {
return (padspace + text).slice(-length);
}
function padR(text, length) {
return (text + padspace).slice(0, length);
}
var onDOM = typeof document !== "undefined";
if (onDOM) {
var parent = document.getElementsByTagName("tbody")[0];
var initBench = function() {
var row = this.row = document.createElement("tr"),
cell = document.createElement("td");
cell.innerHTML = this.props;
row.appendChild(cell);
cell = document.createElement("td");
cell.innerHTML = this.objects;
row.appendChild(cell);
cell = document.createElement("td");
cell.className = "changes";
cell.innerHTML = this.name;
row.appendChild(cell);
this.cells = [];
cell = document.createElement("td");
cell.className = "samples";
this.cells.push(cell);
row.appendChild(cell);
cell = document.createElement("td");
cell.className = "count";
this.cells.push(cell);
row.appendChild(cell);
cell = document.createElement("td");
cell.className = "frequency";
this.cells.push(cell);
row.appendChild(cell);
parent.appendChild(row);
},
onCycle = function() {
this.cells[0].innerHTML = ++this.samples;
this.cells[1].innerHTML = this.count;
this.cells[2].innerHTML = this.hz.toFixed(2);
};
} else {
var writeOut = typeof process === "undefined" || !process.stdout || !process.stdout.isTTY
? function(text) { console.log(text); }
: function(text) { process.stdout.write(text); };
writeOut("\x1b[1;37mProperties Objects Changes Samples Loops FPS (Hz)\n");
writeOut( "---------------------------------------------------------------------");
var initBench = function() {
writeOut("\n\x1b[1;30m" + padL(this.props, 10) + " " + padL(this.objects, 7) + " " + padR(this.name, 48));
},
onCycle = function() {
writeOut("\x1b[38D\x1b[1;31m" + padL(++this.samples, 9) + "\x1b[1;36m" + padL(this.count, 12)
+ "\x1b[1;32m" + padL(this.hz.toFixed(2), 17) + "\x1b[0;37m");
};
}
function errorBench(e) {
console.log(e);
}
var benches = [];
function generateBenchGroup(props, objects) {
var propsPerObject = props / objects;
var options = {
setup: "\
var handler = function() {};\n\
var objects = [];\n\
for (var i = 0; i < " + objects + "; i++) {\n\
objects[i] = generateObject(" + propsPerObject + ");\n\
Object.observe(objects[i], handler);\n\
}\n",
teardown: "\
for (var i = 0; i < " + objects + "; i++)\
Object.unobserve(objects[i], handler);\n",
props: props,
objects: objects,
onStart: initBench,
onCycle: onCycle,
onError: errorBench,
onComplete: nextBench,
async: true,
samples: 0
};
var midIndex = objects >> 1,
midProp = "prop" + (propsPerObject >> 1);
benches.push(new Benchmark("none", "\
Object.deliverChangeRecords(handler);\n", options));
benches.push(new Benchmark("one", "\
objects[" + midIndex + "]." + midProp + "++;\n\
Object.deliverChangeRecords(handler);\n", options));
benches.push(new Benchmark("all", "\
for (var i = 0; i < " + objects + "; i++)\n\
for (var j = 0; j < " + propsPerObject + "; j++)\n\
objects[i][\"prop\" + j]++;\n\
Object.deliverChangeRecords(handler);\n", options));
}
generateBenchGroup(10, 1);
generateBenchGroup(10, 2);
generateBenchGroup(100, 1);
generateBenchGroup(100, 20);
generateBenchGroup(1000, 1);
generateBenchGroup(1000, 200);
var index = 0;
function nextBench() {
if (index >= benches.length) return;
benches[index++].run();
}
nextBench();
});
|
/* global SITE: false */
'use strict';
(function(){
var scrollVisibilityElements = document.querySelectorAll('.js-component-scroll-visibility');
var components = [];
[].slice.call( scrollVisibilityElements ).forEach( function(el) {
components.push( new SITE.ElementScrollVisibility( el ) );
});
})();
|
"use strict";
var utils = require("../utils");
var log = require("npmlog");
module.exports = function (defaultFuncs, api, ctx) {
return function resolvePhotoUrl(photoID, callback) {
if (!callback) {
throw { error: "resolvePhotoUrl: need callback" };
}
defaultFuncs
.get("https://www.facebook.com/mercury/attachments/photo", ctx.jar, { photo_id: photoID })
.then(utils.parseAndCheckLogin(ctx, defaultFuncs))
.then(resData => {
if (resData.error) {
throw resData;
}
var photoUrl = resData.jsmods.require[0][3][0];
return callback(null, photoUrl);
})
.catch(err => {
log.error("resolvePhotoUrl", err);
return callback(err);
});
};
};
|
/*
* Globalize Culture uz-Latn
*
* http://github.com/jquery/globalize
*
* Copyright Software Freedom Conservancy, Inc.
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* This file was generated by the Globalize Culture Generator
* Translation: bugs found in this file need to be fixed in the generator
*/
(function( window, undefined ) {
var Globalize;
if ( typeof require !== "undefined"
&& typeof exports !== "undefined"
&& typeof module !== "undefined" ) {
// Assume CommonJS
Globalize = require( "globalize" );
} else {
// Global variable
Globalize = window.Globalize;
}
Globalize.addCultureInfo( "uz-Latn", "default", {
name: "uz-Latn",
englishName: "Uzbek (Latin)",
nativeName: "U'zbek",
language: "uz-Latn",
numberFormat: {
",": " ",
".": ",",
percent: {
pattern: ["-n%","n%"],
",": " ",
".": ","
},
currency: {
pattern: ["-n $","n $"],
decimals: 0,
",": " ",
".": ",",
symbol: "so'm"
}
},
calendars: {
standard: {
firstDay: 1,
days: {
names: ["yakshanba","dushanba","seshanba","chorshanba","payshanba","juma","shanba"],
namesAbbr: ["yak.","dsh.","sesh.","chr.","psh.","jm.","sh."],
namesShort: ["ya","d","s","ch","p","j","sh"]
},
months: {
names: ["yanvar","fevral","mart","aprel","may","iyun","iyul","avgust","sentyabr","oktyabr","noyabr","dekabr",""],
namesAbbr: ["yanvar","fevral","mart","aprel","may","iyun","iyul","avgust","sentyabr","oktyabr","noyabr","dekabr",""]
},
AM: null,
PM: null,
patterns: {
d: "dd/MM yyyy",
D: "yyyy 'yil' d-MMMM",
t: "HH:mm",
T: "HH:mm:ss",
f: "yyyy 'yil' d-MMMM HH:mm",
F: "yyyy 'yil' d-MMMM HH:mm:ss",
M: "d-MMMM",
Y: "MMMM yyyy"
}
}
}
});
}( this ));
|
'use strict';
import fs from 'fs';
import path from 'path';
import foldero from 'foldero';
import jade from 'jade';
import yaml from 'js-yaml';
export default function(gulp, plugins, args, config, taskTarget, browserSync) {
let dirs = config.directories;
let dest = path.join(taskTarget);
let dataPath = path.join(dirs.source, dirs.data);
// Jade template compile
gulp.task('jade', () => {
let siteData = {};
if (fs.existsSync(dataPath)) {
// Convert directory to JS Object
siteData = foldero(dataPath, {
recurse: true,
whitelist: '(.*/)*.+\.(json|ya?ml)$',
loader: function loadAsString(file) {
let json = {};
try {
if (path.extname(file).match(/^.ya?ml$/)) {
json = yaml.safeLoad(fs.readFileSync(file, 'utf8'));
}
else {
json = JSON.parse(fs.readFileSync(file, 'utf8'));
}
}
catch(e) {
console.log('Error Parsing DATA file: ' + file);
console.log('==== Details Below ====');
console.log(e);
}
return json;
}
});
}
// Add --debug option to your gulp task to view
// what data is being loaded into your templates
if (args.debug) {
console.log('==== DEBUG: site.data being injected to templates ====');
console.log(siteData);
console.log('\n==== DEBUG: package.json config being injected to templates ====');
console.log(config);
}
return gulp.src([
path.join(dirs.source, '**/*.jade'),
'!' + path.join(dirs.source, '{**/\_*,**/\_*/**}')
])
.pipe(plugins.changed(dest))
.pipe(plugins.plumber())
.pipe(plugins.jade({
jade: jade,
pretty: true,
locals: {
config: config,
debug: true,
site: {
data: siteData
}
}
}))
.pipe(plugins.htmlmin({
collapseBooleanAttributes: true,
conservativeCollapse: true,
removeCommentsFromCDATA: true,
removeEmptyAttributes: true,
removeRedundantAttributes: true
}))
.pipe(gulp.dest(dest))
.on('end', browserSync.reload);
});
}
|
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
'use strict';
// TODO: Use an opaque type once ESLint et al support the syntax
export type ExpirationTime = number;
const NoWork = 0;
const Sync = 1;
const Never = 2147483647; // Max int32: Math.pow(2, 31) - 1
const UNIT_SIZE = 10;
const MAGIC_NUMBER_OFFSET = 2;
exports.Sync = Sync;
exports.NoWork = NoWork;
exports.Never = Never;
// 1 unit of expiration time represents 10ms.
function msToExpirationTime(ms: number): ExpirationTime {
// Always add an offset so that we don't clash with the magic number for NoWork.
return ((ms / UNIT_SIZE) | 0) + MAGIC_NUMBER_OFFSET;
}
exports.msToExpirationTime = msToExpirationTime;
function ceiling(num: number, precision: number): number {
return (((num / precision) | 0) + 1) * precision;
}
function computeExpirationBucket(
currentTime: ExpirationTime,
expirationInMs: number,
bucketSizeMs: number,
): ExpirationTime {
return ceiling(
currentTime + expirationInMs / UNIT_SIZE,
bucketSizeMs / UNIT_SIZE,
);
}
exports.computeExpirationBucket = computeExpirationBucket;
|
import React from 'react'
describe('(View) Board', () => {
it('should exist', () => {
})
})
|
function RoundGrouperViewModel(domainModel, viewController){
var self = this;
var LOGGER = new Logger('RoundGrouperViewModel',log4javascript.Level.TRACE);
var domainModel = domainModel;
var viewController = viewController;
self.courses = [];
self.roundGroups = ko.observableArray([]);
self.requireAll = ko.observable(true);
self.setCourses = function(courses){
self.courses = courses;
};
self.getCourses = function(){ return self.courses; };
self.toggleRoundGroup = function(roundGroup){
roundGroup.selected(!roundGroup.selected());
LOGGER.info((roundGroup.selected() ? "Enabled" : "Disabled") + " round group " + roundGroup.id + " with " + roundGroup.rounds().length + " rounds. Enabled round groups: " + filterSelectedRoundGroups(self.roundGroups()).length);
viewController.roundListViewModel.filterByRoundGroups(filterSelectedRoundGroups(self.roundGroups()));
viewController.powerTableViewModel.populate(viewController.playerListViewModel.getSelectedPlayers(),viewController.roundListViewModel.filteredRounds());
};
self.toggleRequireAll = function(value){
viewController.roundListViewModel.requireAllParticipants = self.requireAll();
viewController.playerListViewModel.update();
return true;
};
self.addRound = function(round){
var targetGroup = self.getRoundGroupFor(round);
targetGroup.rounds.push(round);
};
self.updateRounds = function(rounds){
LOGGER.info("Grouping " + rounds.length + " rounds under course list");
$.each(self.roundGroups(), function(i,roundgroup) {
//RoundGrouperLogger.debug(roundgroup.rounds().length);
roundgroup.rounds.removeAll();
});
$.each(rounds, function(i,round) {
self.addRound(round)
});
}
self.removeAllRounds = function(){
$.each(self.roundGroups(), function(i,roundGroup){ roundGroup.rounds = []; });
};
self.getRoundGroupFor = function(round){
var roundGroup = $.grep(self.roundGroups(),
function(roundGroup){
return round.getCourseId() == roundGroup.id;
})[0];
if(roundGroup){
return roundGroup;
}else{
var courseId = round.getCourseId();
var par = domainModel.getCourse(courseId).getPar();
roundGroup = new RoundGroup(courseId, par);
self.roundGroups.push(roundGroup);
return roundGroup;
}
};
}
function filterSelectedRoundGroups(roundGroups){
var selectedGroups = $.grep(roundGroups, function(roundGroup) { return roundGroup.selected(); });
return selectedGroups;
}
|
/*
* winston-udp-test.js: Tests for instances of the UDP transport
*/
var vows = require('vows');
var assert = require('assert');
var winston = require('winston');
var helpers = require('winston/test/helpers');
var UDP = require('../lib/winston-udp').UDP;
function assertUDP (transport) {
assert.instanceOf(transport, UDP);
assert.isFunction(transport.log);
}
var transport = new (UDP)();
vows.describe('winston-udp').addBatch({
"An instance of the UDP Transport": {
"should have the proper methods defined": function () {
assertUDP(transport);
},
"the log() method": helpers.testNpmLevels(transport, "should log messages to UDP", function (ign, err, logged) {
assert.isTrue(!err);
assert.isTrue(logged);
})
}
}).addBatch({
"Tear down": { 'UDP Client': function () {transport.closeClient()}}
}).export(module);
|
var request = require('request').defaults({ jar: true, strictSSL: false });
var cheerio = require('cheerio');
var moment = require('moment');
var async = require('async');
var vm = require('vm');
module.exports = fetch;
function fetch(urls, cb) {
fetchCountries(urls.country, function(err, data) {
if (err) return cb(err);
fetchConsulates(urls.consulate, data, function(err, data) {
if (err) return cb(err);
fetchAvailableDates(urls.agenda, data, function(err, data) {
if (err) return cb(err);
cb(null, data);
});
});
});
}
function fetchCountries(url, cb) {
request.post({
url: url,
form: { untramite: 'RES' }
}, function(err, httpResponse, bodyString) {
if (err) return cb(err);
var $;
var countryOptions = [];
try {
$ = cheerio.load(bodyString, { xmlMode: true });
} catch (error) {
err.bodyString = bodyString;
return cb(error);
}
$('option').each(function (i, el) {
el = $(el);
/*
Intentional use of coercion, for values like `'0'`
*/
if (el.val() != false) {
countryOptions.push({
countryCode: el.val(),
countryName: el.text()
});
}
});
return cb(null, countryOptions);
});
}
function fetchConsulates(url, countries, cb) {
async.map(countries, bridge, function(err, consulates) {
if (err) return cb(err);
return cb(null, [].concat.apply([], consulates));
});
function bridge(country, cb) {
getCountryCounsulates(url, country, cb);
}
}
function getCountryCounsulates(url, country, cb) {
request.post({
url: url,
form: { untramite: 'RES', unpais: country.countryCode }
}, function(err, httpResponse, bodyString) {
if (err) return cb(err);
var $;
var consulateOptions = [];
try {
$ = cheerio.load(bodyString, { xmlMode: true });
} catch (error) {
err.bodyString = bodyString;
return cb(error);
}
$('option').each(function (i, el) {
el = $(el);
/*
Intentional use of coercion, for values like `'0'`
*/
if (el.val() != false) {
consulateOptions.push({
consulateCode: el.val(),
consulateName: el.text(),
countryCode: country.countryCode,
countryName: country.countryName
});
}
});
return cb(null, consulateOptions);
});
}
function fetchAvailableDates(url, consulates, cb) {
async.map(consulates, bridge, function(err, dates) {
if (err) return cb(err);
return cb(null, dates);
});
function bridge(consulate, cb) {
getConsulateAvailableDates(url, consulate, cb);
}
}
function getConsulateAvailableDates(url, consulate, cb) {
/*
Isolated cookies for each consulate request
*/
var jar = request.jar();
/*
Start today
*/
var currentDate = moment();
request.get({
url: url,
qs: { recurso: 'RES', agenda: consulate.consulateCode },
jar: jar
}, function(err, httpResponse, bodyString) {
if (err) return cb(err);
paginateCalendar(url, consulate, currentDate, jar, 3, cb);
});
}
function paginateCalendar(url, consulate, currentDate, jar, maxEmptyMonths, cb) {
consulate.freeDays = consulate.freeDays || [];
consulate.busyDays = consulate.busyDays || [];
request.post({
url: url,
form: {
AJAXREQUEST: '_viewRoot',
form: 'form',
j_id42: 'RES',
calendarioInputDate: '',
calendarioInputCurrentDate: currentDate.format('MM/YYYY'),
'javax.faces.ViewState': 'j_id1',
form_link_hidden_:"calendario",
calendario:"calendario",
ajaxSingle:"calendario",
calendarioPreloadCurrentDate:"true"
},
jar: jar
}, function(err, httpResponse, bodyString) {
if (err) return cb(err);
var $;
var jsString;
var monthData;
var freeDays;
var busyDays;
try {
$ = cheerio.load(bodyString, { xmlMode: true });
} catch (error) {
err.bodyString = bodyString;
return cb(error);
}
jsString = $('#_ajax\\:data').html().replace(/<\!\[CDATA\[(.*?)\]\]>/, '$1');
try {
monthData = vm.runInThisContext('localVar = ' + jsString +';');
} catch (error) {
err.bodyString = bodyString;
return cb(error);
}
monthData.days.forEach(function(el, i) {
el.date = moment([currentDate.year(), currentDate.month(), i + 1]);
});
freeDays = monthData.days.filter(function (el) { return el.styleClass === 'diaConCupo'; });
busyDays = monthData.days.filter(function (el) { return el.styleClass === 'diaSinCupo'; });
consulate.freeDays = consulate.freeDays.concat(freeDays);
consulate.busyDays = consulate.busyDays.concat(busyDays);
if (freeDays.length + busyDays.length === 0) { maxEmptyMonths--; }
if (!maxEmptyMonths) {
return cb(null, consulate);
} else {
paginateCalendar(url, consulate, currentDate.add(1, 'months'), jar, maxEmptyMonths, cb);
}
});
}
|
file:/home/charlike/dev/glob-fs/fixtures/a/f7.js
|
'use strict'
const config = require('../config')
const logger = require('../logger')
const moment = require('moment')
class UpdateDirtyNoteJob {
constructor (realtime) {
this.realtime = realtime
}
start () {
if (this.timer) return
this.timer = setInterval(this.updateDirtyNotes.bind(this), 1000)
}
stop () {
if (!this.timer) return
clearInterval(this.timer)
this.timer = undefined
}
updateDirtyNotes () {
const notes = this.realtime.getNotePool()
Object.keys(notes).forEach((key) => {
const note = notes[key]
this.updateDirtyNote(note)
.catch((err) => {
logger.error('updateDirtyNote: updater error', err)
})
})
}
async updateDirtyNote (note) {
const notes = this.realtime.getNotePool()
if (!note.server.isDirty) return
if (config.debug) logger.info('updateDirtyNote: updater found dirty note: ' + note.id)
note.server.isDirty = false
try {
const _note = await this.updateNoteAsync(note)
// handle when note already been clean up
if (!notes[note.id] || !notes[note.id].server) return
if (!_note) {
this.realtime.io.to(note.id).emit('info', {
code: 404
})
logger.error('updateDirtyNote: note not found: ', note.id)
this.realtime.disconnectSocketOnNote(note)
}
note.updatetime = moment(_note.lastchangeAt).valueOf()
this.realtime.emitCheck(note)
} catch (err) {
logger.error('updateDirtyNote: note not found: ', note.id)
this.realtime.io.to(note.id).emit('info', {
code: 404
})
this.realtime.disconnectSocketOnNote(note)
throw err
}
}
updateNoteAsync (note) {
return new Promise((resolve, reject) => {
this.realtime.updateNote(note, (err, _note) => {
if (err) {
return reject(err)
}
return resolve(_note)
})
})
}
}
exports.UpdateDirtyNoteJob = UpdateDirtyNoteJob
|
/* jshint -W117, -W030, -W074 */
(function () {
'use strict';
angular
.module('app.about')
.controller('AboutController', AboutController);
AboutController.$inject = ['$http'];
/* @ngInject */
function AboutController($http) {
var vm = this;
var splitByEquals = document.location.search.split('=');
// I could check for "id" here
var lastPiece = splitByEquals[splitByEquals.length - 1];
vm.url = '/data/product/' + lastPiece;
$http.get(vm.url).success(function (response) {
vm.result = response.results[0];
vm.meta = response.meta;
});
}
})();
|
import React from 'react'
import Icon from 'react-icon-base'
const MdPlaylistAdd = props => (
<Icon viewBox="0 0 40 40" {...props}>
<g><path d="m3.4 26.6v-3.2h13.2v3.2h-13.2z m26.6-3.2h6.6v3.2h-6.6v6.8h-3.4v-6.8h-6.6v-3.2h6.6v-6.8h3.4v6.8z m-6.6-13.4v3.4h-20v-3.4h20z m0 6.6v3.4h-20v-3.4h20z"/></g>
</Icon>
)
export default MdPlaylistAdd
|
(function() {
var Ext = window.Ext4 || window.Ext;
Ext.define('Rally.apps.releaseplanning.ReleasePlanningApp', {
extend: 'Rally.app.App',
requires: [
'Rally.data.util.PortfolioItemHelper',
'Rally.ui.gridboard.planning.TimeboxGridBoard',
'Rally.ui.gridboard.plugin.GridBoardAddNew',
'Rally.ui.gridboard.plugin.GridBoardFieldPicker',
'Rally.ui.gridboard.plugin.GridBoardCustomFilterControl'
],
launch: function() {
Rally.data.util.PortfolioItemHelper.loadTypeOrDefault({
defaultToLowest: true,
requester: this,
success: function (piTypeDef) {
this._buildGridBoard(piTypeDef.get('TypePath'));
},
scope: this
});
},
_buildGridBoard: function (piTypePath) {
var boardFieldBlacklist = [
'AcceptedLeafStoryCount',
'AcceptedLeafStoryPlanEstimateTotal',
'DirectChildrenCount',
'LeafStoryCount',
'LeafStoryPlanEstimateTotal',
'LastUpdateDate',
'State',
'UnEstimatedLeafStoryCount'
],
context = this.getContext();
this.gridboard = this.add({
xtype: 'rallytimeboxgridboard',
cardBoardConfig: {
columnConfig: {
columnStatusConfig: {
pointField: 'PreliminaryEstimate.Value'
}
},
listeners: {
filter: this._onBoardFilter,
filtercomplete: this._onBoardFilterComplete,
scope: this
}
},
context: context,
endDateField: 'ReleaseDate',
listeners: {
load: this._onLoad,
toggle: this._publishContentUpdated,
recordupdate: this._publishContentUpdatedNoDashboardLayout,
recordcreate: this._publishContentUpdatedNoDashboardLayout,
preferencesaved: this._publishPreferenceSaved,
scope: this
},
modelNames: [piTypePath],
plugins: [
{
ptype: 'rallygridboardaddnew',
rankScope: 'BACKLOG',
addNewControlConfig: {
stateful: true,
stateId: context.getScopedStateId('release-planning-add-new')
}
},
{
ptype: 'rallygridboardcustomfiltercontrol',
filterChildren: false,
filterControlConfig: {
margin: '3 9 3 30',
blackListFields: ['PortfolioItemType', 'Release'],
whiteListFields: ['Milestones'],
modelNames: [piTypePath],
stateful: true,
stateId: context.getScopedStateId('release-planning-custom-filter-button')
},
showOwnerFilter: true,
ownerFilterControlConfig: {
stateful: true,
stateId: context.getScopedStateId('release-planning-owner-filter')
}
},
{
ptype: 'rallygridboardfieldpicker',
boardFieldBlackList: boardFieldBlacklist,
boardFieldDefaults: this._getDefaultFields(),
headerPosition: 'left'
}
],
startDateField: 'ReleaseStartDate',
timeboxType: 'Release'
});
},
_onLoad: function() {
this._publishContentUpdated();
this.recordComponentReady();
if (Rally.BrowserTest) {
Rally.BrowserTest.publishComponentReady(this);
}
},
_onBoardFilter: function() {
this.setLoading(true);
},
_onBoardFilterComplete: function() {
this.setLoading(false);
},
_publishContentUpdated: function() {
this.fireEvent('contentupdated');
},
_publishContentUpdatedNoDashboardLayout: function() {
this.fireEvent('contentupdated', {dashboardLayout: false});
},
_publishPreferenceSaved: function(record) {
this.fireEvent('preferencesaved', record);
},
_getDefaultFields: function() {
return ['Discussion', 'PreliminaryEstimate', 'UserStories', 'Milestones'];
}
});
})();
|
define(['./identity', './_overRest', './_setToString'], function(identity, overRest, setToString) {
/**
* The base implementation of `_.rest` which doesn't validate or coerce arguments.
*
* @private
* @param {Function} func The function to apply a rest parameter to.
* @param {number} [start=func.length-1] The start position of the rest parameter.
* @returns {Function} Returns the new function.
*/
function baseRest(func, start) {
return setToString(overRest(func, start, identity), func + '');
}
return baseRest;
});
|
(function() {
'use strict';
angular.module('app')
.config(ProjectStateConfig);
/**
* @ngInject
*/
function ProjectStateConfig($stateProvider) {
$stateProvider
.state('root.project', {
url: '/projects/:project',
resolve: {
project: function($stateParams, ProjectRepository) {
return ProjectRepository.findOne($stateParams.project);
},
languages: function($stateParams, LanguageRepository) {
return LanguageRepository.findByProject($stateParams.project);
},
resources: function($stateParams, ResourceRepository) {
return ResourceRepository.findByProject($stateParams.project);
}
},
views: {
'main': {
controller: 'ProjectController',
templateUrl: 'views/project/layout.html',
},
'toolbar-title': {
controller: 'ProjectTitleController',
templateUrl: 'views/project/toolbar-title.html'
}
}
})
}
})();
|
/* jshint expr:true */
/* global describe, it */
'use strict';
var expect = require('chai').expect;
var Request = require('../../lib/Request');
describe('Request', function() {
describe('#constructor', function() {
it('throws an error with a bad request', function() {
var req = {
method : 123,
params : []
};
function makeReq() {
return new Request(req);
}
expect(makeReq).to.throw(Object);
});
it('pulls out request data correctly', function() {
var headers = { Authorization : 'Bearer 12345' };
var req = {
content : {
method : 'math.add',
params : { x : 1, y : 2 },
jsonrpc : '2.0'
},
properties : {
headers : headers
}
};
var request = new Request(req);
expect(request.headers).to.equal(headers);
expect(request.properties).to.be.an.object;
expect(request.params.x).to.equal(1);
expect(request.content).to.be.an.object;
});
});
});
|
(function(cornerstoneTools) {
'use strict';
function drawCircle(context, start, color, lineWidth) {
var handleRadius = 6;
context.beginPath();
context.strokeStyle = color;
context.lineWidth = lineWidth;
context.arc(start.x, start.y, handleRadius, 0, 2 * Math.PI);
context.stroke();
}
// Module exports
cornerstoneTools.drawCircle = drawCircle;
})(cornerstoneTools);
|
var Lexer = require('./lexer'),
converter = require('./converter');
module.exports = Parser;
function Parser () { }
Parser.prototype.parse = function (src) {
var lexer = new Lexer(),
tokens = lexer.lex(src),
slides = [],
slide = createSlide(),
tag,
classes;
tokens.forEach(function (token) {
switch (token.type) {
case 'text':
case 'code':
case 'fences':
appendTo(slide, token.text);
break;
case 'content_start':
tag = token.block ? 'div' : 'span';
classes = token.classes.join(' ');
appendTo(slide, '<' + tag + ' class="' + classes + '">');
break;
case 'content_end':
tag = token.block ? 'div' : 'span';
appendTo(slide, '</' + tag + '>');
break;
case 'separator':
slides.push(slide);
slide = createSlide();
slide.properties.continued = (token.text === '--').toString();
break;
case 'notes_separator':
slide.notes = '';
break;
}
});
slides.push(slide);
slides.forEach(function (slide) {
slide.source = extractProperties(slide.source, slide.properties);
});
return slides;
};
function createSlide () {
return {
source: '',
properties: {
continued: 'false'
}
};
}
function appendTo (slide, content) {
if (slide.notes !== undefined) {
slide.notes += content;
}
else {
slide.source += content;
}
}
function extractProperties (source, properties) {
var propertyFinder = /^\n*([-\w]+):([^$\n]*)/i
, match
;
while ((match = propertyFinder.exec(source)) !== null) {
source = source.substr(0, match.index) +
source.substr(match.index + match[0].length);
properties[match[1].trim()] = match[2].trim();
propertyFinder.lastIndex = match.index;
}
return source;
}
|
(function () {
'use strict';
describe('Admin Activities List Controller Tests', function () {
// Initialize global variables
var ActivitiesListController,
$scope,
$httpBackend,
$state,
Authentication,
ActivitiesService,
mockActivity;
// The $resource service augments the response object with methods for updating and deleting the resource.
// If we were to use the standard toEqual matcher, our tests would fail because the test values would not match
// the responses exactly. To solve the problem, we define a new toEqualData Jasmine matcher.
// When the toEqualData matcher compares two objects, it takes only object properties into
// account and ignores methods.
beforeEach(function () {
jasmine.addMatchers({
toEqualData: function (util, customEqualityTesters) {
return {
compare: function (actual, expected) {
return {
pass: angular.equals(actual, expected)
};
}
};
}
});
});
// Then we can start by loading the main application module
beforeEach(module(ApplicationConfiguration.applicationModuleName));
// The injector ignores leading and trailing underscores here (i.e. _$httpBackend_).
// This allows us to inject a service but then attach it to a variable
// with the same name as the service.
beforeEach(inject(function ($controller, $rootScope, _$state_, _$httpBackend_, _Authentication_, _ActivitiesService_) {
// Set a new global scope
$scope = $rootScope.$new();
// Point global variables to injected services
$httpBackend = _$httpBackend_;
$state = _$state_;
Authentication = _Authentication_;
ActivitiesService = _ActivitiesService_;
// create mock activity
mockActivity = new ActivitiesService({
id: 12345,
name: 'An Activity about MEAN',
description: 'MEAN rocks!'
});
// Mock logged in user
Authentication.user = {
roles: ['user', 'admin']
};
// Initialize the Activities List controller.
ActivitiesListController = $controller('ActivitiesListController as vm', {
$scope: $scope
});
// Spy on state go
spyOn($state, 'go');
}));
describe('Instantiate', function () {
var mockActivityList;
beforeEach(function () {
mockActivityList = [mockActivity, mockActivity];
});
it('should send a GET request and return all activities', inject(function (ActivitiesService) {
// Set POST response
$httpBackend.expectGET('api/activities').respond(mockActivityList);
$httpBackend.flush();
// Test form inputs are reset
expect($scope.vm.activities.length).toEqual(2);
expect($scope.vm.activities[0]).toEqual(mockActivity);
expect($scope.vm.activitys[1]).toEqual(mockActivity);
}));
});
});
}());
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _reactIconBase = require('react-icon-base');
var _reactIconBase2 = _interopRequireDefault(_reactIconBase);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var MdSettingsInputComposite = function MdSettingsInputComposite(props) {
return _react2.default.createElement(
_reactIconBase2.default,
_extends({ viewBox: '0 0 40 40' }, props),
_react2.default.createElement(
'g',
null,
_react2.default.createElement('path', { d: 'm28.4 26.6v-3.2h10v3.2q0 1.7-1 2.9t-2.4 1.8v7.1h-3.4v-7.1q-3.2-1.1-3.2-4.7z m-6.8-23.2v6.6h3.4v10h-10v-10h3.4v-6.6q0-0.7 0.4-1.3t1.2-0.5 1.2 0.5 0.4 1.3z m13.4 6.6h3.4v10h-10v-10h3.2v-6.6q0-0.7 0.5-1.3t1.3-0.5 1.1 0.5 0.5 1.3v6.6z m-33.4 16.6v-3.2h10v3.2q0 3.6-3.2 4.7v7.1h-3.4v-7.1q-1.5-0.5-2.4-1.8t-1-2.9z m13.4 0v-3.2h10v3.2q0 1.7-0.9 2.9t-2.5 1.8v7.1h-3.2v-7.1q-1.5-0.5-2.5-1.8t-0.9-2.9z m-6.6-23.2v6.6h3.2v10h-10v-10h3.4v-6.6q0-0.7 0.5-1.3t1.1-0.5 1.3 0.5 0.5 1.3z' })
)
);
};
exports.default = MdSettingsInputComposite;
module.exports = exports['default'];
|
import { assert } from 'chai';
import mockup from 'tests/mockup/mockup';
import IntersectionVisitor from 'osgUtil/IntersectionVisitor';
import SphereIntersector from 'osgUtil/SphereIntersector';
import KdTreeBuilder from 'osg/KdTreeBuilder';
import BoundingSphere from 'osg/BoundingSphere';
import Node from 'osg/Node';
import Geometry from 'osg/Geometry';
import BufferArray from 'osg/BufferArray';
import DrawArrays from 'osg/DrawArrays';
import primitiveSet from 'osg/primitiveSet';
import { mat4 } from 'osg/glMatrix';
import { vec3 } from 'osg/glMatrix';
import MatrixTransform from 'osg/MatrixTransform';
import Shape from 'osg/shape';
import ReaderParser from 'osgDB/readerParser';
export default function() {
test('SphereIntersector simple test', function() {
var spi = new SphereIntersector();
var bs = new BoundingSphere();
bs.set(vec3.fromValues(0.0, 0.0, 0.0), 2.0);
// testing the same sphere
spi.set(vec3.fromValues(0.0, 0.0, 0.0), 2.0);
spi.setCurrentTransformation(mat4.create());
assert.isOk(spi.intersectBoundingSphere(bs), 'hit success');
// moving a bit also should hit
spi.set(vec3.fromValues(2.0, 2.0, 0.0), 2.0);
spi.setCurrentTransformation(mat4.create());
assert.isOk(spi.intersectBoundingSphere(bs), 'hit success');
// This should fail
spi.set(vec3.fromValues(3.0, 3.0, 0.0), 1.0);
spi.setCurrentTransformation(mat4.create());
assert.isOk(!spi.intersectBoundingSphere(bs), 'hit failed');
});
// quad center at (0, 0, 0) with dege 0.5
// lines is grid with same center and 6 lines
// points are : one in (0, 0, 0) and the other on picking path
// picking is (0.1, 0.3, 0) with radius 0.15
var createSceneGeometry = function() {
var scene = new Node();
var cx, cy, cz, wx, wy, wz, hx, hy, hz;
cx = cy = -0.5;
wx = hy = 1.0;
cz = wy = wz = hx = hz = 0.0;
var tris = Shape.createTexturedQuadGeometry(cx, cy, cz, wx, wy, wz, hx, hy, hz, 1.0, 1.0);
var lines = Shape.createGridGeometry(cx, cy, cz, wx, wy, wz, hx, hy, hz, 1, 1);
var points = new Geometry();
var pverts = new Float32Array([0.0, 0.0, 0.0, 0.1, 0.3, 0.0]);
points.getAttributes().Vertex = new BufferArray(BufferArray.ARRAY_BUFFER, pverts, 3);
points.getPrimitives().push(new DrawArrays(primitiveSet.POINTS, 0, 2));
scene.addChild(tris);
scene.addChild(lines);
scene.addChild(points);
return scene;
};
test('SphereIntersector with 2 branches', function() {
// right branch should be picked
// left branch shouldn't be picked
//
// scene
// |
// tr1 (5 0 0)
// | \
// | tr2 (-5 0 0)
// | /
// scene geom
var rootScene = new Node();
var sceneGeom = createSceneGeometry();
var tr1 = new MatrixTransform();
mat4.fromTranslation(tr1.getMatrix(), [5.0, 0.0, 0.0]);
var tr2 = new MatrixTransform();
mat4.fromTranslation(tr2.getMatrix(), [-5.0, 0.0, 0.0]);
rootScene.addChild(tr1);
tr1.addChild(sceneGeom);
tr1.addChild(tr2);
tr2.addChild(sceneGeom);
var lsi = new SphereIntersector();
lsi.set(vec3.fromValues(0.1, 0.3, 0.0), 0.15);
var iv = new IntersectionVisitor();
iv.setIntersector(lsi);
var testPick = function() {
lsi.reset();
iv.reset();
rootScene.accept(iv);
// no kd tree
var inters = lsi._intersections;
assert.isOk(inters.length === 3, 'Hits should be 3 and result is ' + inters.length);
var npath = inters[0]._nodePath;
assert.isOk(npath.length === 5, 'NodePath should be 5 and result is ' + npath.length);
var prims = { point: 0, line: 0, triangle: 0 };
for (var i = 0; i < inters.length; ++i) {
if (inters[i]._i3 >= 0) prims.triangle++;
else if (inters[i]._i2 >= 0) prims.line++;
else if (inters[i]._i1 >= 0) prims.point++;
}
var one = prims.point === 1 && prims.line === 1 && prims.triangle === 1;
assert.isOk(one, 'Check pick primitive');
};
testPick();
// with kd tree
var treeBuilder = new KdTreeBuilder({ _targetNumTrianglesPerLeaf: 0 });
treeBuilder.apply(rootScene);
testPick();
});
test('SphereIntersector with mockup scene', function() {
// mockup scene is a sphere centered in 0 with radius ~50
var rootScene = ReaderParser.parseSceneGraph(mockup.getScene());
var lsi = new SphereIntersector();
lsi.set(vec3.fromValues(100, 0, 0), 100.0);
var iv = new IntersectionVisitor();
iv.setIntersector(lsi);
var testPick = function() {
lsi.reset();
iv.reset();
rootScene.accept(iv);
// no kd tree
var inters = lsi._intersections;
assert.isOk(inters.length === 670, 'Hits should be 670 and result is ' + inters.length);
var npath = inters[0]._nodePath;
assert.isOk(npath.length === 5, 'NodePath should be 5 and result is ' + npath.length);
var points = [];
var triangles = [];
var lines = [];
for (var i = 0; i < inters.length; ++i) {
var int = inters[i];
if (int._i3 >= 0) triangles.push(int);
else if (int._i2 >= 0) lines.push(int);
else if (int._i1 >= 0) points.push(int);
}
var one = points.length === 0 && lines.length === 0 && triangles.length === 670;
assert.isOk(one, 'Check pick primitive');
};
testPick();
// with kd tree
var treeBuilder = new KdTreeBuilder({ _targetNumTrianglesPerLeaf: 0 });
treeBuilder.apply(rootScene);
testPick();
});
}
|
var client = new WebTorrent()
client.add('magnet:?xt=urn:btih:13991928788f049b05a6260d62e1d743571fba75&dn=bird1.jpg&tr=udp://exodus.desync.com:6969&tr=udp://tracker.coppersurfer.tk:6969&tr=udp://tracker.internetwarriors.net:1337&tr=udp://tracker.leechers-paradise.org:6969&tr=udp://tracker.openbittorrent.com:80&tr=wss://tracker.btorrent.xyz&tr=wss://tracker.fastcast.nz&tr=wss://tracker.openwebtorrent.com&tr=wss://tracker.webtorrent.io', function(torrent) {
var file = torrent.files[0];
var elementsArray = [].slice.call(document.getElementsByClassName('13991928788f049b05a6260d62e1d743571fba75'))
if (elementsArray.length) {
elementsArray.forEach(function(element) {
file.renderTo(element)
})
}
})
client.add('magnet:?xt=urn:btih:a6022e9ea276cf01325d9ff68b6d77c2d6a74a78&dn=bird2.jpg&tr=udp://exodus.desync.com:6969&tr=udp://tracker.coppersurfer.tk:6969&tr=udp://tracker.internetwarriors.net:1337&tr=udp://tracker.leechers-paradise.org:6969&tr=udp://tracker.openbittorrent.com:80&tr=wss://tracker.btorrent.xyz&tr=wss://tracker.fastcast.nz&tr=wss://tracker.openwebtorrent.com&tr=wss://tracker.webtorrent.io', function(torrent) {
var file = torrent.files[0];
var elementsArray = [].slice.call(document.getElementsByClassName('a6022e9ea276cf01325d9ff68b6d77c2d6a74a78'));
if (elementsArray.length) {
elementsArray.forEach(function(element) {
file.renderTo(element)
})
}
})
client.add('magnet:?xt=urn:btih:e297b89c4383a4573a9ef92916cd970b7674f9de&dn=bird3.jpg&tr=udp://exodus.desync.com:6969&tr=udp://tracker.coppersurfer.tk:6969&tr=udp://tracker.internetwarriors.net:1337&tr=udp://tracker.leechers-paradise.org:6969&tr=udp://tracker.openbittorrent.com:80&tr=wss://tracker.btorrent.xyz&tr=wss://tracker.fastcast.nz&tr=wss://tracker.openwebtorrent.com&tr=wss://tracker.webtorrent.io', function(torrent) {
var file = torrent.files[0];
var elementsArray = [].slice.call(document.getElementsByClassName('e297b89c4383a4573a9ef92916cd970b7674f9de'));
if (elementsArray.length) {
elementsArray.forEach(function(element) {
file.renderTo(element)
})
}
})
|
// eslint-disable-next-line no-constant-condition, no-empty
while(1) {}
|
var expect = require('chai').expect;
var observeDeep = require('../observe-deep');
describe('deepObserve', function() {
var observed;
var nested;
function observer(changesTriggered) {
changes.push(changesTriggered);
}
var changes;
var deliver;
beforeEach(function() {
nested = {};
observed = {nested: nested};
changes = [];
deliver = observeDeep(observed, observer);
});
it('should throw when cyclic object is detected', function() {
//TODO implement
});
it("should be able to watch simple object and it's values same as regular Object.observe, deliver function should be returned", function(done) {
observed.a = 1;
observed.a = 2;
delete observed.a;
setTimeout(function() {
expect(changes.length).to.equal(1);
}, 1);
setTimeout(function() {
observed.b = 0;
}, 4);
setTimeout(function() {
expect(changes.length).to.equal(2);
expect(changes[0].length).to.equal(3);
expect(changes[0][0].type).to.equal('add');
done();
}, 10);
});
it('should watch an object assigned to the root object and stop watching it when it is deleted', function(done) {
var another = {};
observed.a = another;
setTimeout(function() {
another.propOnAnother = 'value on another';
observed.b = 0;
}, 1);
setTimeout(function() {
expect(changes.length).to.equal(3);
expect(changes[0].length).to.equal(1);
expect(changes[0][0].type).to.equal('add');
console.log("willDelete");
delete observed.a;
}, 10);
setTimeout(function() {
another.c = 1; //should not trigger a change, because another has been deleted from observed
}, 12);
setTimeout(function() {
console.log("changes", changes);
expect(changes.length).to.equal(4);
done();
}, 15)
});
it('should stop watching a nested object when it is overwritten with another one', function(done) {
var another = {};
observed.nested = another;
setTimeout(function() {
nested.a = 3;
setTimeout(function() {
expect(changes.length).to.equal(1);
done();
});
});
});
it('should allow one object to be observed separately as part of two trees', function() {
});
it('should still observe/unobserve when one object is assigned on two different properties', function(done) {
observed.nestedSecond = nested;
setTimeout(function() {
nested.a = 3;
setTimeout(function() {
expect(changes.length).to.equal(2);
setTimeout(function(){
delete observed.nested;
setTimeout(function(){
nested.b = 4;
setTimeout(function(){
expect(changes.length).to.equal(4);
done();
});
});
});
});
});
});
});
|
'use strict';
let _ = require('lodash');
let request = require('request');
let helpers = require('../helpers');
let path = require('path');
let zmq = require('zmq');
let checkpoint = helpers.checkpoint;
let toss = helpers.toss;
let PromiseManager = helpers.PromiseManager;
module.exports = function (config) {
let client = {};
let promiseManager = new PromiseManager(config);
let responseHandlerMap = {};
checkpoint(config, 'Config is required for micron http client')
.and(config.host, 'Host is required for micron http client')
.and(config.port, 'Port is required for micron http client');
let standardizeReqOpts = helpers.standardizeReqOpts(config);
let buildOpts = function (method, path, opts) {
checkpoint(path, 'Path/Namespace is required for request');
opts = standardizeReqOpts.prime(opts);
opts.path = path;
opts.method = method;
return opts;
};
let autoReconnect = true;
let errorHandler = config.catch || function (e) {
console.error(e.stack);
};
//
// Bind the socket
//
let socket = zmq.socket('req');
socket.identity = 'client' + process.pid;
socket.bindSync('tcp://' + config.host + ':' + (config.port || 80));
socket.on('message', function (message) {
let json;
try {
json = JSON.parse(message.toString('utf8')) || {};
} catch (e) {
errorHandler(e);
}
let handler = responseHandlerMap[json.id];
if (_.isFunction(handler)) {
delete json.id;
handler(json);
} else {
errorHandler('Socket could not map response to request: ' + message);
}
});
//
// Core request
//
client.request = function (opts) {
return new Promise(function (resolve, reject) {
opts = standardizeReqOpts.finalize(opts);
let timeoutMessage = '[' + opts.method.toUpperCase() + '] ' + config.host + ':' + config.port;
let promise = promiseManager.manage(resolve, reject, ('ZeroMQ Request Timeout: ' + timeoutMessage + path.join('/', opts.path)));
opts.id = promise.id;
opts.query = opts.query || opts.qs;
delete opts.qs;
socket.send(JSON.stringify(opts));
responseHandlerMap[promise.id] = function (response) {
if (!promise.isResolved) {
promise.resolve({
success: (response.status >= 200 && response.status < 300),
status: response.status || 500,
data: response.data
});
}
};
});
};
//
// Status
//
client.status = function (timeout) {
return client.request(buildOpts('get', 'status', _.defaultsDeep(opts, {
qs: {
shallow: true
}
})));
};
//
// Create/Post
//
client.create = client.post = function (path, opts) {
return client.request(buildOpts('post', path, opts));
};
//
// Read/Get
//
client.read = client.get = function (path, opts) {
return client.request(buildOpts('get', path, opts));
};
//
// Update/Put
//
client.update = client.put = function (path, opts) {
return client.request(buildOpts('put', path, opts));
};
//
// Destroy/Delete
//
client.destroy = client.delete = function (path, opts) {
return client.request(buildOpts('delete', path, opts));
};
//
// Close
//
client.close = function () {
autoReconnect = false;
socket.close();
};
return client;
};
|
(function() {
'use strict';
module.exports = function( gulp ) {
gulp.task( 'watch', function () {
gulp.watch( 'front-end/resources/css/stylus/app.styl', ['stylus'] );
});
};
}());
|
define(function(require, exports, module) {
'use strict';
var Helper = require('../core/Helper').Class,
List = require('../core/List'),
Utils = require('../core/Utils');
/**
* @extends Helper
* @constructor
*/
function LocationHelper(context) {
Helper.call(this, context);
this.state = require('./State').$get(context);
}
LocationHelper.prototype = Object.create(Helper.prototype);
LocationHelper.prototype.createUrl = function() {
return '/dictionary/location';
};
/**
* @param {ILocationFilterOptions} options
* @returns {function(ILocation)}
*/
LocationHelper.prototype.filter = function(options) {
var uniqueNPAs = [];
options = Utils.extend({
stateId: '',
onlyUniqueNPA: false
}, options);
return List.filter([
{
condition: options.stateId,
filterFn: function(item, opts) {
return (this.state.getId(item.state) == opts.condition);
}.bind(this)
},
{
condition: options.onlyUniqueNPA,
filterFn: function(item, opts) {
if (uniqueNPAs.indexOf(item.npa) == -1) {
uniqueNPAs.push(item.npa);
return true;
} else {
return false;
}
}
}
]);
};
/**
* @param {IListComparatorOptions} [options]
* @returns {comparator}
*/
LocationHelper.prototype.comparator = function(options) {
options = Utils.extend({
sortBy: 'npa'
}, options);
if (options.sortBy == 'nxx') {
/**
* @param {ILocation} item
* @returns {number}
*/
options.extractFn = function(item) {
return (parseInt(item.npa) * 1000000) + parseInt(item.nxx);
};
options.compareFn = List.numberComparator;
}
return List.comparator(options);
};
module.exports = {
Class: LocationHelper,
/**
* @param {Context} context
* @returns {LocationHelper}
*/
$get: function(context) {
return context.createSingleton('LocationHelper', function() {
return new LocationHelper(context);
});
}
};
/**
* @typedef {object} ILocation
* @property {string} id
* @property {string} uri
* @property {string} name
* @property {string} isoCode
* @property {string} npa
* @property {string} nxx
* @property {IState} state
*/
/**
* @typedef {object} ILocationFilterOptions
* @property {string} stateId
* @property {boolean} onlyUniqueNPA
*/
});
|
(function() {
var parts = document.location.search.slice( 1 ).split( "&" ),
length = parts.length,
i = 0,
current,
version,
url;
for ( ; i < length; i++ ) {
current = parts[ i ].split( "=" );
if ( current[ 0 ] === "jquery" ) {
version = current[ 1 ];
break;
}
}
if ( version === "git" ) {
url = "http://code.jquery.com/jquery-git.js";
} else {
url = "../../jquery-" + ( version || "1.10.2" ) + ".js";
}
document.write( "<script src='" + url + "'></script>" );
}() );
|
// core
import ArrayInputNode from './core/ArrayInputNode.js';
import AttributeNode from './core/AttributeNode.js';
import BypassNode from './core/BypassNode.js';
import CodeNode from './core/CodeNode.js';
import ContextNode from './core/ContextNode.js';
import ExpressionNode from './core/ExpressionNode.js';
import FunctionCallNode from './core/FunctionCallNode.js';
import FunctionNode from './core/FunctionNode.js';
import InputNode from './core/InputNode.js';
import Node from './core/Node.js';
import NodeAttribute from './core/NodeAttribute.js';
import NodeBuilder from './core/NodeBuilder.js';
import NodeCode from './core/NodeCode.js';
import NodeFrame from './core/NodeFrame.js';
import NodeFunctionInput from './core/NodeFunctionInput.js';
import NodeKeywords from './core/NodeKeywords.js';
import NodeUniform from './core/NodeUniform.js';
import NodeVar from './core/NodeVar.js';
import NodeVary from './core/NodeVary.js';
import PropertyNode from './core/PropertyNode.js';
import TempNode from './core/TempNode.js';
import VarNode from './core/VarNode.js';
import VaryNode from './core/VaryNode.js';
// accessors
import CameraNode from './accessors/CameraNode.js';
import MaterialNode from './accessors/MaterialNode.js';
import MaterialReferenceNode from './accessors/MaterialReferenceNode.js';
import ModelNode from './accessors/ModelNode.js';
import ModelViewProjectionNode from './accessors/ModelViewProjectionNode.js';
import NormalNode from './accessors/NormalNode.js';
import Object3DNode from './accessors/Object3DNode.js';
import PointUVNode from './accessors/PointUVNode.js';
import PositionNode from './accessors/PositionNode.js';
import ReferenceNode from './accessors/ReferenceNode.js';
import SkinningNode from './accessors/SkinningNode.js';
import UVNode from './accessors/UVNode.js';
// inputs
import ColorNode from './inputs/ColorNode.js';
import FloatNode from './inputs/FloatNode.js';
import IntNode from './inputs/IntNode.js';
import Matrix3Node from './inputs/Matrix3Node.js';
import Matrix4Node from './inputs/Matrix3Node.js';
import TextureNode from './inputs/TextureNode.js';
import Vector2Node from './inputs/Vector2Node.js';
import Vector3Node from './inputs/Vector3Node.js';
import Vector4Node from './inputs/Vector4Node.js';
// display
import ColorSpaceNode from './display/ColorSpaceNode.js';
import NormalMapNode from './display/NormalMapNode.js';
// math
import MathNode from './math/MathNode.js';
import OperatorNode from './math/OperatorNode.js';
import CondNode from './math/CondNode.js';
// lights
import LightContextNode from './lights/LightContextNode.js';
import LightNode from './lights/LightNode.js';
import LightsNode from './lights/LightsNode.js';
// utils
import ArrayElementNode from './utils/ArrayElementNode.js';
import ConvertNode from './utils/ConvertNode.js';
import JoinNode from './utils/JoinNode.js';
import SplitNode from './utils/SplitNode.js';
import SpriteSheetUVNode from './utils/SpriteSheetUVNode.js';
import OscNode from './utils/OscNode.js';
import TimerNode from './utils/TimerNode.js';
// procedural
import CheckerNode from './procedural/CheckerNode.js';
// core
export * from './core/constants.js';
// functions
export * from './functions/BSDFs.js';
// materials
export * from './materials/Materials.js';
// shader node
export * from './ShaderNode.js';
export {
// core
ArrayInputNode,
AttributeNode,
BypassNode,
CodeNode,
ContextNode,
ExpressionNode,
FunctionCallNode,
FunctionNode,
InputNode,
Node,
NodeAttribute,
NodeBuilder,
NodeCode,
NodeFrame,
NodeFunctionInput,
NodeKeywords,
NodeUniform,
NodeVar,
NodeVary,
PropertyNode,
TempNode,
VarNode,
VaryNode,
// accessors
CameraNode,
MaterialNode,
MaterialReferenceNode,
ModelNode,
ModelViewProjectionNode,
NormalNode,
Object3DNode,
PointUVNode,
PositionNode,
ReferenceNode,
SkinningNode,
UVNode,
// inputs
ColorNode,
FloatNode,
IntNode,
Matrix3Node,
Matrix4Node,
TextureNode,
Vector2Node,
Vector3Node,
Vector4Node,
// display
ColorSpaceNode,
NormalMapNode,
// math
MathNode,
OperatorNode,
CondNode,
// lights
LightContextNode,
LightNode,
LightsNode,
// utils
ArrayElementNode,
ConvertNode,
JoinNode,
SplitNode,
SpriteSheetUVNode,
OscNode,
TimerNode,
// procedural
CheckerNode
};
|
window.c.AdminInputAction = (function(m, h, c) {
return {
controller: function(args) {
var builder = args.data,
complete = m.prop(false),
error = m.prop(false),
fail = m.prop(false),
data = {},
item = args.item,
key = builder.property,
forceValue = builder.forceValue || null,
newValue = m.prop(forceValue);
h.idVM.id(item[builder.updateKey]);
var l = m.postgrest.loaderWithToken(builder.model.patchOptions(h.idVM.parameters(), data));
var updateItem = function(res) {
_.extend(item, res[0]);
complete(true);
error(false);
};
var submit = function() {
data[key] = newValue();
l.load().then(updateItem, function() {
complete(true);
error(true);
});
return false;
};
var unload = function(el, isinit, context) {
context.onunload = function() {
complete(false);
error(false);
newValue(forceValue);
};
};
return {
complete: complete,
error: error,
l: l,
newValue: newValue,
submit: submit,
toggler: h.toggleProp(false, true),
unload: unload
};
},
view: function(ctrl, args) {
var data = args.data,
btnValue = (ctrl.l()) ? 'por favor, aguarde...' : data.callToAction;
return m('.w-col.w-col-2', [
m('button.btn.btn-small.btn-terciary', {
onclick: ctrl.toggler.toggle
}, data.outerLabel), (ctrl.toggler()) ?
m('.dropdown-list.card.u-radius.dropdown-list-medium.zindex-10', {
config: ctrl.unload
}, [
m('form.w-form', {
onsubmit: ctrl.submit
}, (!ctrl.complete()) ? [
m('label', data.innerLabel), (data.forceValue === undefined) ?
m('input.w-input.text-field[type="text"][placeholder="' + data.placeholder + '"]', {
onchange: m.withAttr('value', ctrl.newValue),
value: ctrl.newValue()
}) : '',
m('input.w-button.btn.btn-small[type="submit"][value="' + btnValue + '"]')
] : (!ctrl.error()) ? [
m('.w-form-done[style="display:block;"]', [
m('p', data.successMessage)
])
] : [
m('.w-form-error[style="display:block;"]', [
m('p', 'Houve um problema na requisição. ' + data.errorMessage)
])
])
]) : ''
]);
}
};
}(window.m, window.c.h, window.c));
|
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2022 Photon Storm Ltd.
* @license {@link https://opensource.org/licenses/MIT|MIT License}
*/
/**
* Returns the top coordinate from the bounds of the Game Object.
*
* @function Phaser.Display.Bounds.GetTop
* @since 3.0.0
*
* @param {Phaser.GameObjects.GameObject} gameObject - The Game Object to get the bounds value from.
*
* @return {number} The top coordinate of the bounds of the Game Object.
*/
var GetTop = function (gameObject)
{
return gameObject.y - (gameObject.height * gameObject.originY);
};
module.exports = GetTop;
|
/**
* Loading Directive
* @see http://tobiasahlin.com/spinkit/
*/
angular
.module('RDash')
.directive('rdLoading', rdLoading);
function rdLoading() {
var directive = {
restrict: 'AE',
template: `<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
width="24px" height="30px" viewBox="0 0 24 30" style="margin-top:10px;enable-background:new 0 0 50 50;" xml:space="preserve">
<rect x="0" y="10" width="4" height="10" fill="#333" opacity="0.2">
<animate attributeName="opacity" attributeType="XML" values="0.2; 1; .2" begin="0s" dur="0.6s" repeatCount="indefinite" />
<animate attributeName="height" attributeType="XML" values="10; 20; 10" begin="0s" dur="0.6s" repeatCount="indefinite" />
<animate attributeName="y" attributeType="XML" values="10; 5; 10" begin="0s" dur="0.6s" repeatCount="indefinite" />
</rect>
<rect x="8" y="10" width="4" height="10" fill="#333" opacity="0.2">
<animate attributeName="opacity" attributeType="XML" values="0.2; 1; .2" begin="0.15s" dur="0.6s" repeatCount="indefinite" />
<animate attributeName="height" attributeType="XML" values="10; 20; 10" begin="0.15s" dur="0.6s" repeatCount="indefinite" />
<animate attributeName="y" attributeType="XML" values="10; 5; 10" begin="0.15s" dur="0.6s" repeatCount="indefinite" />
</rect>
<rect x="16" y="10" width="4" height="10" fill="#333" opacity="0.2">
<animate attributeName="opacity" attributeType="XML" values="0.2; 1; .2" begin="0.3s" dur="0.6s" repeatCount="indefinite" />
<animate attributeName="height" attributeType="XML" values="10; 20; 10" begin="0.3s" dur="0.6s" repeatCount="indefinite" />
<animate attributeName="y" attributeType="XML" values="10; 5; 10" begin="0.3s" dur="0.6s" repeatCount="indefinite" />
</rect>
</svg>`
};
return directive;
}
|
/******************************************
Export
******************************************/
oT.export = {};
oT.export.asFormat = function( format ){
if (format === 'md') {
var p = document.getElementById('textbox').innerHTML;
var clean = $.htmlClean(p, {format:true, removeTags: ["div", "span", "img", "pre", "text"]});
var x = toMarkdown( clean );
return x.replace(/\t/gm,"");
} else if (format === 'txt') {
var p = document.getElementById('textbox').innerHTML;
var clean = $.htmlClean(p, {format:true, removeTags:["div", "span", "img", "em", "strong", "p", "pre", "text"]});
return clean.replace(/\t/gm,"");
} else if (format === 'html') {
var p = document.getElementById('textbox').innerHTML;
return p.replace('\n','');
}
}
oT.export.placeButton = function ( format ){
if (format === 'otr') {
var doc = oT.export.createJsonFile();
var a = document.getElementById('x-otr');
a.download = exportText.name() + ".otr";
a.href = "data:text/plain;base64," + exportText.utf8_to_b64( doc );
}
}
var exportText = {
utf8_to_b64 : function( str ) {
return window.btoa(unescape(encodeURIComponent( str )));
},
// element choose element to append button to
mdButton : function(element) {
var md = oT.export.asFormat('md');
var a = document.getElementById('x-md');
a.download = exportText.name() + ".md";
a.href = "data:text/plain;base64," + exportText.utf8_to_b64( md );
},
txtButton : function(element) {
var txt = oT.export.asFormat('txt');
var a = document.getElementById('x-txt');
a.download = exportText.name() + ".txt";
a.href = "data:text/plain;base64," + exportText.utf8_to_b64( txt );
},
name : function(){
var d = new Date();
var fileName = document.webL10n.get('file-name');
return fileName + " " + d.toUTCString();
}
}
function placeExportPanel(){
exportText.mdButton();
exportText.txtButton();
oT.export.placeButton('otr');
gd.handleClientLoad();
var origin = $('#icon-exp').offset();
var right = parseInt( $('body').width() - origin.left + 25 );
var top = parseInt( origin.top ) - 50;
$('.export-panel')
.css({'right': right,'top': top})
.addClass('active');
}
function hideExportPanel(){
$('.export-panel').removeClass('active');
$('.export-block-gd')[0].outerHTML = gd.button();
}
exportText.createBlob = function(){
var p = document.getElementById('textbox').innerHTML;
var aFileParts = [p];
var oBlob = new Blob(aFileParts, {type : 'text/html'}); // the blob
return oBlob;
}
exportText.reader= function(){
var reader = new FileReader();
var blob = exportText.createBlob();
reader.readAsBinaryString(blob);
return reader;
}
oT.export.createJsonFile = function(){
var result = {};
result.text = oT.export.asFormat('html');
if (oT.player !== null){
result.media = oT.player.title;
if (oT.player.getTime) {
result['media-time'] = oT.player.getTime();
}
if (oT.media.ytEl) {
result['media-source'] = oT.media._ytEl.getVideoUrl();
} else {
result['media-source'] = '';
}
} else {
result.media = '';
result['media-source'] = '';
result['media-time'] = '';
}
return JSON.stringify(result);
};
|
module.exports = require("npm:qs@4.0.0/lib/index");
|
/*
* @name गीत
* @frame 720, 430
* @description एक गाना बजाएं।
* आपको शामिल करने की आवश्यकता होगी
* <a href="http://p5js.org/reference/#/libraries/p5.sound">p5.sound
* पुस्तकालय</a> इस उदाहरण के लिए अपने स्वयं के प्रोजेक्ट में काम करने के लिए।
*/
// एक पैमाने के मिडी नोट
let notes = [ 60, 62, 64, 65, 67, 69, 71];
// स्वचालित रूप से गाना बजाने के लिए
let index = 0;
let song = [
{ note: 4, duration: 400, display: "D" },
{ note: 0, duration: 200, display: "G" },
{ note: 1, duration: 200, display: "A" },
{ note: 2, duration: 200, display: "B" },
{ note: 3, duration: 200, display: "C" },
{ note: 4, duration: 400, display: "D" },
{ note: 0, duration: 400, display: "G" },
{ note: 0, duration: 400, display: "G" }
];
let trigger = 0;
let autoplay = false;
let osc;
function setup() {
createCanvas(720, 400);
let div = createDiv("Click to play notes or ")
div.id("instructions");
let button = createButton("play song automatically.");
button.parent("instructions");
// ट्रिगर स्वचालित रूप से खेल रहा है
button.mousePressed(function() {
if (!autoplay) {
index = 0;
autoplay = true;
}
});
// एक त्रिकोण थरथरानवाला
osc = new p5.TriOsc();
// शुरू करें
osc.start();
osc.amp(0);
}
// एक नोट खेलने के लिए एक समारोह
function playNote(note, duration) {
osc.freq(midiToFreq(note));
// इसे फीका करें
osc.fade(0.5,0.2);
// यदि हम एक अवधि निर्धारित करते हैं, तो इसे फीका कर दें
if (duration) {
setTimeout(function() {
osc.fade(0,0.2);
}, duration-50);
}
}
function draw() {
// यदि हम ऑटोप्ले कर रहे हैं और यह अगले नोट के लिए समय है
if (autoplay && millis() > trigger){
playNote(notes[song[index].note], song[index].duration);
trigger = millis() + song[index].duration;
// अगले नोट पर जाएं
index ++;
// हम अंत में हैं, ऑटोप्ले करना बंद करें।
} else if (index >= song.length) {
autoplay = false;
}
// एक कीबोर्ड बनाएं
// प्रत्येक कुंजी की चौड़ाई
let w = width / notes.length;
for (let i = 0; i < notes.length; i++) {
let x = i * w;
// यदि माउस कुंजी के ऊपर है
if (mouseX > x && mouseX < x + w && mouseY < height) {
// अगर हम क्लिक कर रहे हैं
if (mouseIsPressed) {
fill(100,255,200);
// या बस लुढ़कना
} else {
fill(127);
}
} else {
fill(200);
}
// या अगर हम गाना बजा रहे हैं, तो इसे भी हाइलाइट करें
if (autoplay && i === song[index-1].note) {
fill(100,255,200);
}
// कुंजी ड्रा करें
rect(x, 0, w-1, height-1);
}
}
// जब हम क्लिक करते हैं
function mousePressed(event) {
if(event.button == 0 && event.clientX < width && event.clientY < height) {
// माउस को प्रमुख इंडेक्स पर मैप करें
let key = floor(map(mouseX, 0, width, 0, notes.length));
playNote(notes[key]);
}
}
// जब हम रिलीज करते हैं तो इसे फीका कर दें
function mouseReleased() {
osc.fade(0,0.5);
}
|
import React from 'react';
import { Meteor } from 'meteor/meteor';
import { withRouter } from 'react-router';
import {
Col,
Row,
Grid,
Icon,
Button,
Checkbox,
ButtonGroup,
} from '@sketchpixy/rubix';
@withRouter
export default class Todo extends React.Component {
toggleCompletion() {
let { _id } = this.props.todo;
let completed = this.input.checked;
Meteor.call('todos.setChecked', _id, completed);
}
removeTodo() {
let { _id } = this.props.todo;
Meteor.call('todos.remove', _id);
}
editTodo() {
this.props.router.push(`/todo/edit/${this.props.todo._id}`);
}
render() {
let { todo, completed } = this.props.todo;
let style = {
textDecoration: completed ? 'line-through' : null
};
return (
<Grid>
<Row className='todo-item'>
<Col sm={8}>
<Checkbox onChange={::this.toggleCompletion} style={style} inputRef={(input) => { this.input = input; }} checked={completed} >
{todo}
</Checkbox>
</Col>
<Col sm={4} className='text-right'>
<Button bsStyle='red' className='remove-sm' onClick={::this.removeTodo} style={{marginRight: 12.5}}>Remove</Button>
<Button bsStyle='green' className='remove-sm' onlyOnHover onClick={::this.editTodo}>Edit</Button>
</Col>
</Row>
</Grid>
);
}
}
|
'use strict';
angular.module('copayApp.controllers').controller('importLegacyController',
function($rootScope, $scope, $log, $timeout, notification, legacyImportService, profileService, go, lodash, bitcore) {
var self = this;
self.messages = [];
self.fromCloud = true;
self.server = "https://insight.bitpay.com:443/api/email";
$rootScope.$on('Local/ImportStatusUpdate', function(event, status) {
$timeout(function() {
$log.debug(status);
self.messages.unshift({
message: status,
});
var op = 1;
lodash.each(self.messages, function(m) {
if (op < 0.1) op = 0.1;
m.opacity = op;
op = op - 0.15;
});
}, 100);
});
self.scan = function(ids) {
$log.debug('### Scaning: ' + ids)
var i = 0;
lodash.each(ids, function(id) {
$rootScope.$emit('Local/WalletImported', id);
if (++i == ids.length) {
go.walletHome();
};
});
};
self.import = function(form) {
var username = form.username.$modelValue;
var password = form.password.$modelValue;
var serverURL = form.server.$modelValue;
var fromCloud = form.fromCloud.$modelValue;
self.error = null;
self.importing = true;
$timeout(function() {
legacyImportService.import(username, password, serverURL, fromCloud, function(err, ids, toScanIds) {
if (err || !ids || !ids.length) {
self.importing = false;
self.error = err || 'Failed to import wallets';
return;
}
notification.success( ids.length + ' wallets imported. Funds scanning in progress. Hold on to see updated balance.');
self.scan(toScanIds);
});
}, 100);
};
// TODO destroy event...
});
|
var Action = require('../../../fsmpack/statemachine/actions/Action');
function CopyJointTransformAction() {
Action.apply(this, arguments);
this.everyFrame = true;
}
CopyJointTransformAction.prototype = Object.create(Action.prototype);
CopyJointTransformAction.prototype.constructor = CopyJointTransformAction;
CopyJointTransformAction.external = {
key: 'Copy Joint Transform',
name: 'Copy Joint Transform',
type: 'animation',
description: 'Copies a joint\'s transform from another entity, and applies it to this entity. This entity must be a child of an entity with an animation component.',
parameters: [{
name: 'Joint',
key: 'jointIndex',
type: 'int',
control: 'jointSelector',
'default': null,
description: 'Joint transform to copy.'
}],
transitions: []
};
CopyJointTransformAction.prototype.update = function (fsm) {
if (this.jointIndex === null) { return; }
var entity = fsm.getOwnerEntity();
var parent = entity.transformComponent.parent;
if (!parent) { return; }
parent = parent.entity;
if (!parent.animationComponent || !parent.animationComponent._skeletonPose) { return; }
var pose = parent.animationComponent._skeletonPose;
var jointTransform = pose._globalTransforms[this.jointIndex];
if (!jointTransform) { return; }
entity.transformComponent.transform.matrix.copy(jointTransform.matrix);
jointTransform.matrix.getTranslation(entity.transformComponent.transform.translation);
jointTransform.matrix.getScale(entity.transformComponent.transform.scale);
jointTransform.matrix.getRotation(entity.transformComponent.transform.rotation);
updateWorldTransform(entity.transformComponent);
entity.transformComponent.setUpdated();
};
function updateWorldTransform(transformComponent) {
transformComponent.sync();
var entity = transformComponent.entity;
if (entity && entity.meshDataComponent && entity.meshRendererComponent) {
entity.meshRendererComponent.updateBounds(
entity.meshDataComponent.modelBound,
transformComponent.sync().worldTransform
);
}
for (var i = 0; i < transformComponent.children.length; i++) {
updateWorldTransform(transformComponent.children[i]);
}
}
module.exports = CopyJointTransformAction;
|
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z" /><path d="M6.5 17.5l7.51-3.49L17.5 6.5 9.99 9.99 6.5 17.5zm5.5-6.6c.61 0 1.1.49 1.1 1.1s-.49 1.1-1.1 1.1-1.1-.49-1.1-1.1.49-1.1 1.1-1.1z" /></g></React.Fragment>
, 'ExploreOutlined');
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.