text
stringlengths 2
6.14k
|
|---|
/*
* Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var href = parent.window.location.href
var PARAM_ID = "webappName";
$(function () {
var qs = gadgetUtil.getQueryString();
if (qs[PARAM_ID] != null) {
$("#txtSearch").val(qs[PARAM_ID]);
}
$("#txtSearch").attr('placeholder', 'Search webapps ...');
gadgetUtil.fetchData(CONTEXT, {
action: 'apps-list',
start_time: gadgetUtil.timeFrom(),
end_time: gadgetUtil.timeTo()
}, onData, onError);
function onData(response) {
// Add all applications text to the list
if (response.message) {
response.message.push(ALL_APPLICATIONS_TEXT);
}
$('.typeahead').typeahead({
hint: true,
highlight: true,
minLength: 0
}, {
name: 'proxyName',
source: substringMatcher(response.message)
}).on('typeahead:selected',function (evt, item) {
var href = parent.window.location.href;
if (jQuery.isEmptyObject(qs)) {
href = href + "?" + PARAM_ID + "=" + item;
} else if (qs[PARAM_ID]) {
href = href.replace(new RegExp('(webappName=)[^\\&]+'), '$1' + item)
} else {
href = href + "&" + PARAM_ID + "=" + item;
}
parent.window.location = href;
}).on('typeahead:open',function (evt, item) {
wso2.gadgets.controls.resizeGadget({
height: "200px"
});
}).on('typeahead:close',function (evt, item) {
wso2.gadgets.controls.restoreGadget();
}).focus().blur();
}
function onError(error) {
}
var substringMatcher = function (strs) {
return function findMatches(q, cb) {
var matches, substringRegex;
// an array that will be populated with substring matches
matches = [];
// regex used to determine if a string contains the substring `q`
substrRegex = new RegExp(q, 'i');
// iterate through the pool of strings and for any string that
// contains the substring `q`, add it to the `matches` array
$.each(strs, function (i, str) {
if (substrRegex.test(str)) {
matches.push(str);
}
});
cb(matches);
};
};
});
|
msuParts["colortheme"] = function(ScratchUserscript){
var settingsDlg = $("<div></div>");
ScratchUserscript.registerPart("Color Theme", "Changes the colors of the Scratch page.", settingsDlg);
var isEnabled = ScratchUserscript.isPartEnabled("colortheme");
var custom = {
main: "#25B36A",
dark: "#128C4D",
text: "#FFFFFF"
};
var preset = {
green: ["#99CD4E", "#7EA840", "#fff"],
orange: ["#ED6332", "#AD4723", "#fff"],
seafoam: ["#25B36A", "#128C4D", "#fff"],
purple: ["#8943E6", "#591DA8", "#fff"],
pink: ["#E34BA1", "#A6246E", "#fff"],
custom: []
};
var settings = {
none: true,
green: false,
seafoam: false,
orange: false,
purple: false,
pink: false,
custom: false
};
var labels = {
none: "Default Scratch Theme",
green: "Green",
seafoam: "Sea Foam",
orange: "Orange",
purple: "Purple",
pink: "Pink",
custom: "Custom"
};
settings = ScratchUserscript.readSetting("colortheme", "settings", settings);
if(ScratchUserscript.MODE_DEV) console.log(settings);
custom = ScratchUserscript.readSetting("colortheme", "custom", custom);
updateChanges = function(){
for(x in settings){
if($("#msu-ct"+x+"btn").is(":checked")){
settings[x] = true;
} else {
settings[x] = false;
}
}
custom['main'] = $("#msu-ct-main").val();
custom['dark'] = $("#msu-ct-dark").val();
custom['text'] = $("#msu-ct-text").val();
ScratchUserscript.writeSetting("colortheme", "settings", settings);
ScratchUserscript.writeSetting("colortheme", "custom", custom);
};
settingsDlg.append("<b>Select a theme:</b><br/>");
for(x in settings){ // much more concise than adding individual settings one by one I would say
settingsDlg.append("<input type='radio' name='msu-ct-radio' id='msu-ct"+x+"btn' /> \
<label for='msu-ct"+x+"btn' \
style='display: inline;margin-right:1em;'>\
"+labels[x]+"</label><br/>");
if(settings[x]) $("#msu-ct"+x+"btn").attr("checked", "checked");
}
settingsDlg.append("<b>Custom colors (choose 'Custom'; hex colors only please):</b><br/>");
settingsDlg.append("<label for='msu-ct-main'>Main color:</label><input type='text' id='msu-ct-main' /><br/>");
settingsDlg.append("<label for='msu-ct-dark'>Dark color:</label><input type='text' id='msu-ct-dark' /><br/>");
settingsDlg.append("<label for='msu-ct-text'>Text color:</label><input type='text' id='msu-ct-text' /><br/>");
settingsDlg.find("input").bind("change cut paste keyup", updateChanges);
$("#msu-ct-main").val(custom['main']);
$("#msu-ct-dark").val(custom['dark']);
$("#msu-ct-text").val(custom['text']);
if(!isEnabled || settings.none) return;
// begin actual script
preset.custom = [custom['main'], custom['dark'], custom['text']];
var sel = "custom";
for(x in settings){
if(settings.hasOwnProperty(x) && settings[x]){
sel = x;
}
}
var css = GM_getResourceText("theme");
css = css.replace(/\$([a-zA-Z0-9\-]+)/g, function(match, p1, offset, string){
if(p1.indexOf("main-color") > -1) return preset[sel][0];
if(p1.indexOf("main-dark") > -1) return preset[sel][1];
return preset[sel][2];
});
GM_addStyle(css);
};
|
/**
* Copyright 2015 Muhammad bin Rosli
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @author Muhammad Rosli <muhd7rosli@live.com>
*/
var simpleApp = angular.module('simpleApp', ['ngRoute', 'ngResource']);
var routeConfig = function($routeProvider){
$routeProvider
.when('/',{
controller: 'SimpleController',
templateUrl: 'partials/home.html'
})
.when('/login',{
controller: 'LoginController',
templateUrl: 'partials/login.html'
})
.when('/home',{
controller: 'SimpleController',
templateUrl: 'partials/home.html'
})
.otherwise({redirectTo: '/'});
};
routeConfig.$inject = ['$routeProvider'];
simpleApp.config(routeConfig);
var SimpleController = function($scope, $http){
$scope.greeting = {"info" : "Loading"};
$http({
method: 'GET',
url: '/wildfly-javaee7-angularjs/rest/helloworld',
headers: {
'Content-Type': 'application/json'
}
}).success(function (data) {
// this callback will be called asynchronously
// when the response is available
$scope.greeting = data;
});
};
SimpleController.$inject = ['$scope', '$http'];
var LoginController = function($scope){
};
LoginController.$inject = ['$scope'];
simpleApp.controller('SimpleController', SimpleController);
simpleApp.controller('LoginController', LoginController);
|
"use strict";
/**
* TurboCommons is a general purpose and cross-language library that implements frequently used and generic software development tasks.
*
* Website : -> http://www.turbocommons.org
* License : -> Licensed under the Apache License, Version 2.0. You may not use this file except in compliance with the License.
* License Url : -> http://www.apache.org/licenses/LICENSE-2.0
* CopyRight : -> Copyright 2015 Edertone Advanded Solutions (08211 Castellar del Vallès, Barcelona). http://www.edertone.com
*/
QUnit.module("ConversionUtilsTest", {
beforeEach : function() {
window.ConversionUtils = org_turbocommons.ConversionUtils;
},
afterEach : function() {
delete window.ConversionUtils;
}
});
/**
* stringToBase64
*/
QUnit.test("stringToBase64", function(assert){
assert.ok(ConversionUtils.stringToBase64(undefined) === '');
assert.ok(ConversionUtils.stringToBase64(null) === '');
assert.ok(ConversionUtils.stringToBase64('') === '');
// Try correct values
assert.ok(ConversionUtils.stringToBase64('f') === 'Zg==');
assert.ok(ConversionUtils.stringToBase64('fo') === 'Zm8=');
assert.ok(ConversionUtils.stringToBase64('foo') === 'Zm9v');
assert.ok(ConversionUtils.stringToBase64('foob') === 'Zm9vYg==');
assert.ok(ConversionUtils.stringToBase64('fooba') === 'Zm9vYmE=');
assert.ok(ConversionUtils.stringToBase64('foobar') === 'Zm9vYmFy');
assert.ok(ConversionUtils.stringToBase64("line1\nline2\nline3") === 'bGluZTEKbGluZTIKbGluZTM=');
assert.ok(ConversionUtils.stringToBase64('{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }') === 'eyAwLCAxLCAyLCAzLCA0LCA1LCA2LCA3LCA4LCA5IH0=');
assert.ok(ConversionUtils.stringToBase64('AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz') === 'QWFCYkNjRGRFZUZmR2dIaElpSmpLa0xsTW1Obk9vUHBRcVJyU3NUdFV1VnZXd1h4WXlaeg==');
// Try some wrong values
assert.throws(function(){
ConversionUtils.stringToBase64([]);
});
assert.throws(function(){
ConversionUtils.stringToBase64(98345);
});
assert.throws(function(){
ConversionUtils.stringToBase64(Qunit);
});
});
/**
* base64ToString
*/
QUnit.test("base64ToString", function(assert){
assert.ok(ConversionUtils.base64ToString(undefined) === '');
assert.ok(ConversionUtils.base64ToString(null) === '');
assert.ok(ConversionUtils.base64ToString('') === '');
// Try correct values
assert.ok(ConversionUtils.base64ToString('Zg==') === 'f');
assert.ok(ConversionUtils.base64ToString('Zm8=') === 'fo');
assert.ok(ConversionUtils.base64ToString('Zm9v') === 'foo');
assert.ok(ConversionUtils.base64ToString('Zm9vYg==') === 'foob');
assert.ok(ConversionUtils.base64ToString('Zm9vYmE=') === 'fooba');
assert.ok(ConversionUtils.base64ToString('Zm9vYmFy') === 'foobar');
// Try some random values encoded with stringToBase64
for(var i = 0; i < 50; i++){
var s = Math.random().toString(36).substring(20);
assert.ok(ConversionUtils.base64ToString(ConversionUtils.stringToBase64(s)) === s);
}
// Try some wrong values
assert.throws(function(){
ConversionUtils.base64ToString([]);
});
assert.throws(function(){
ConversionUtils.base64ToString(98345);
});
assert.throws(function(){
ConversionUtils.base64ToString(Qunit);
});
});
|
var structnx__geneve__table__mod =
[
[ "command", "structnx__geneve__table__mod.html#a395138574e2cd1b118951dedd1725ef0", null ],
[ "pad", "structnx__geneve__table__mod.html#a3b9349c917e6edb98f27f1dd6e0e75db", null ]
];
|
define(['template'], function (template) {
function anonymous($data,$filename) {
'use strict';
$data=$data||{};
var $utils=template.utils,$helpers=$utils.$helpers,$escape=$utils.$escape,id=$data.id,$out='';$out+=' <div class="comp-box di-o_o-line">\r\n <div class=" di-o_o-item" data-o_o-di="';
$out+=$escape(id);
$out+='-vu-form-calendar">\r\n </div>\r\n</div>';
return $out;
}
return { render: anonymous };
});
|
exports.definition = {
config: {
"columns": {
"image":"text",
"title":"text"
},
"adapter": {
"type": "sql",
"collection_name": "catagoriesModel"
}
}
}
|
var Project = function () {
var self = this;
this.name = ko.observable("");
}
|
/*
* jQuery Easing Compatibility v1 - http://gsgd.co.uk/sandbox/jquery.easing.php
*
* Adds compatibility for applications that use the pre 1.2 easing names
*
* Copyright (c) 2007 George Smith
* Licensed under the MIT License:
* http://www.opensource.org/licenses/mit-license.php
*/
jQuery.extend( jQuery.easing,
{
easeIn: function (x, t, b, c, d) {
return jQuery.easing.easeInQuad(x, t, b, c, d);
},
easeOut: function (x, t, b, c, d) {
return jQuery.easing.easeOutQuad(x, t, b, c, d);
},
easeInOut: function (x, t, b, c, d) {
return jQuery.easing.easeInOutQuad(x, t, b, c, d);
},
expoin: function(x, t, b, c, d) {
return jQuery.easing.easeInExpo(x, t, b, c, d);
},
expoout: function(x, t, b, c, d) {
return jQuery.easing.easeOutExpo(x, t, b, c, d);
},
expoinout: function(x, t, b, c, d) {
return jQuery.easing.easeInOutExpo(x, t, b, c, d);
},
bouncein: function(x, t, b, c, d) {
return jQuery.easing.easeInBounce(x, t, b, c, d);
},
bounceout: function(x, t, b, c, d) {
return jQuery.easing.easeOutBounce(x, t, b, c, d);
},
bounceinout: function(x, t, b, c, d) {
return jQuery.easing.easeInOutBounce(x, t, b, c, d);
},
elasin: function(x, t, b, c, d) {
return jQuery.easing.easeInElastic(x, t, b, c, d);
},
elasout: function(x, t, b, c, d) {
return jQuery.easing.easeOutElastic(x, t, b, c, d);
},
elasinout: function(x, t, b, c, d) {
return jQuery.easing.easeInOutElastic(x, t, b, c, d);
},
backin: function(x, t, b, c, d) {
return jQuery.easing.easeInBack(x, t, b, c, d);
},
backout: function(x, t, b, c, d) {
return jQuery.easing.easeOutBack(x, t, b, c, d);
},
backinout: function(x, t, b, c, d) {
return jQuery.easing.easeInOutBack(x, t, b, c, d);
}
});
|
'use strict';
// Run this program with valgrind or efence with --expose_gc to expose the
// problem.
// Flags: --expose_gc
var common = require('../common');
var assert = require('assert');
var HTTPParser = process.binding('http_parser').HTTPParser;
var kOnHeaders = HTTPParser.kOnHeaders | 0;
var kOnHeadersComplete = HTTPParser.kOnHeadersComplete | 0;
var kOnBody = HTTPParser.kOnBody | 0;
var kOnMessageComplete = HTTPParser.kOnMessageComplete | 0;
var headersComplete = 0;
var messagesComplete = 0;
function flushPool() {
new Buffer(Buffer.poolSize - 1);
gc();
}
function demoBug(part1, part2) {
flushPool();
var parser = new HTTPParser('REQUEST');
parser.headers = [];
parser.url = '';
parser[kOnHeaders] = function(headers, url) {
parser.headers = parser.headers.concat(headers);
parser.url += url;
};
parser[kOnHeadersComplete] = function(info) {
headersComplete++;
console.log('url', info.url);
};
parser[kOnBody] = function(b, start, len) { };
parser[kOnMessageComplete] = function() {
messagesComplete++;
};
// We use a function to eliminate references to the Buffer b
// We want b to be GCed. The parser will hold a bad reference to it.
(function() {
var b = Buffer(part1);
flushPool();
console.log('parse the first part of the message');
parser.execute(b, 0, b.length);
})();
flushPool();
(function() {
var b = Buffer(part2);
console.log('parse the second part of the message');
parser.execute(b, 0, b.length);
parser.finish();
})();
flushPool();
}
demoBug('POST /1', '/22 HTTP/1.1\r\n' +
'Content-Type: text/plain\r\n' +
'Content-Length: 4\r\n\r\n' +
'pong');
demoBug('POST /1/22 HTTP/1.1\r\n' +
'Content-Type: tex', 't/plain\r\n' +
'Content-Length: 4\r\n\r\n' +
'pong');
process.on('exit', function() {
assert.equal(2, headersComplete);
assert.equal(2, messagesComplete);
console.log('done!');
});
|
;
(function(win, undef) {
var conf = {
"index": [{
'name': 'scroll',
'path': '../build/common/scoll_hack/scroll.js',
'seq': 0
}, {
'name': 'index',
'path': '../build/page/ing/index.js',
'seq': 1
}, {
'name': 'common',
'path': '../build/common/common.js'
},{
'name': 'tlog',
'path': '../build/common/tLog/tlog.js'
}]
};
win.res = conf;
})(window);
|
/**
* Created by yfyuan on 2016/10/28.
*/
'use strict';
cBoard.service('chartRadarService', function () {
this.render = function (containerDom, option, scope, persist) {
return new CBoardEChartRender(containerDom, option).chart(null, persist);
};
this.parseOption = function (_data) {
var chartConfig = _data.chartConfig;
var casted_keys = _data.keys;
var casted_values = _data.series;
var aggregate_data = _data.data;
var string_keys = _.map(casted_keys, function (key) {
return key.join('-');
});
var string_values = _.map(casted_values, function (value) {
return value.join('-');
});
var data = [];
var max;
var indicator = [];
if (chartConfig.asRow) {
for (var i = 0; i < string_keys.length; i++) {
var d = {value: [], name: string_keys[i]};
for (var j = 0; j < casted_values.length; j++) {
d.value[j] = aggregate_data[j][i];
var n = Number(aggregate_data[j][i]);
if (_.isUndefined(max) || n > max) {
max = n;
}
}
data.push(d);
}
for (var j = 0; j < casted_values.length; j++) {
indicator.push({name: casted_values[j], max: max * 1.05});
}
} else {
for (var i = 0; i < string_values.length; i++) {
var d = {value: [], name: string_values[i]};
for (var j = 0; j < string_keys.length; j++) {
d.value[j] = aggregate_data[i][j];
var n = Number(aggregate_data[i][j]);
if (_.isUndefined(max) || n > max) {
max = n;
}
}
data.push(d);
}
for (var j = 0; j < string_keys.length; j++) {
indicator.push({name: string_keys[j], max: max * 1.05});
}
}
var echartOption = {
tooltip: {
trigger: 'item'
},
toolbox: false,
legend: {
orient: 'vertical',
left: 'left',
data: chartConfig.asRow ? string_keys : string_values
},
radar: {
indicator: indicator
},
series: [{
name: 'radar',
type: 'radar',
itemStyle: {
emphasis: {
areaStyle: {color: 'rgba(0,250,0,0.3)'}
}
},
data: data
}]
};
updateEchartOptions(chartConfig.option, echartOption);
return echartOption;
};
});
|
//// [implicitAnyGenericTypeInference.ts]
interface Comparer<T> {
compareTo<U>(x: T, y: U): U;
}
var c: Comparer<any>;
c = { compareTo: (x, y) => { return y; } };
var r = c.compareTo(1, '');
//// [implicitAnyGenericTypeInference.js]
var c;
c = { compareTo: function (x, y) { return y; } };
var r = c.compareTo(1, '');
|
import Ember from 'ember';
import moment from 'moment';
import { FORM_DATE_FORMAT } from 'open-event-frontend/utils/dictionary/date-time';
const { $, Mixin, merge, run: { debounce } } = Ember;
export default Mixin.create({
actions: {
mutateOne(param, value) {
this.set(param, value[0]);
}
},
autoScrollToErrors : true,
autoScrollSpeed : 200,
getForm() {
return this.get('$form');
},
onValid(callback) {
this.getForm().form('validate form');
if (this.getForm().form('is valid')) {
callback();
}
},
didRender() {
this._super(...arguments);
debounce(this, () => {
const defaultFormRules = {
onFailure: formErrors => {
if (this.autoScrollToErrors) {
// Scroll to the first error message
if (formErrors.length > 0) {
$('html,body').animate({
scrollTop: this.$(`div:contains('${formErrors[0]}')`).offset().top
}, this.autoScrollSpeed);
}
}
}
};
const $popUps = this.$('.has.popup');
if ($popUps) {
$popUps.popup({
hoverable: true
});
}
const $checkBoxes = this.$('.ui.checkbox:not(.ember-view)');
if ($checkBoxes) {
$checkBoxes.checkbox();
}
let $form = this.$('.ui.form');
if ($form) {
$form = $form.first();
if (this.get('getValidationRules') && $form) {
$form.form(merge(defaultFormRules, this.getValidationRules()));
}
if ($form && this) {
this.set('$form', $form);
}
}
}, 400);
},
didInsertElement() {
this._super(...arguments);
$.fn.form.settings.rules.date = (value, format = FORM_DATE_FORMAT) => {
if (value && value.length > 0 && format) {
return moment(value, format).isValid();
}
return true;
};
},
willDestroyElement() {
this._super(...arguments);
const $popUps = this.$('.has.popup');
if ($popUps) {
$popUps.popup('destroy');
}
}
});
|
var React = require('react');
var CardRepository = require('./CardRepository');
var CardStore = require('./CardStore').instance;
var CardUpdateActionCreator = require('./CardUpdateActionCreator');
function getStateFromStores() {
return {
body: CardStore.getCardText()
}
}
var Card = React.createClass({
getInitialState: function() {
return getStateFromStores();
},
componentDidMount: function() {
CardStore.addChangeListener(this.handleStoreEvent);
},
handleStoreEvent: function() {
this.setState(getStateFromStores());
},
handleChange: function(event) {
CardUpdateActionCreator.cardUpdated(event.target.value);
},
render: function() {
return (
<label>
<textarea defaultValue={this.state.body}
onChange={this.handleChange} />
</label>
);
}
});
module.exports = Card;
|
var a02717 =
[
[ "QSPLINE", "a02717.html#a550dbc1b50898c27be5237d72812d1c7", null ],
[ "QSPLINE", "a02717.html#a388e310940b30950a7a5f32a9e4a41c2", null ],
[ "QSPLINE", "a02717.html#ac9ee7256ceae55a1fdbba01fb6103f54", null ],
[ "~QSPLINE", "a02717.html#a7619e90d02d5127754c93073378a738a", null ],
[ "QSPLINE", "a02717.html#af79e3ad5c225e40126555bd88566d2bc", null ],
[ "extrapolate", "a02717.html#a2459d3e247a16f9f01d6b77597193812", null ],
[ "move", "a02717.html#a3d1808becf8a69d00747b444d9c76cf6", null ],
[ "operator=", "a02717.html#a947d537ad3fd5ef782bc81055b291dcf", null ],
[ "overlap", "a02717.html#af5a1e056b6b5c0348b640b5eaa987184", null ],
[ "plot", "a02717.html#a76779877e010949e0055ed273801619d", null ],
[ "plot", "a02717.html#af57ba3f496f4e836f9cdb4fe6108e27d", null ],
[ "step", "a02717.html#aaebd602e34d8b7f4e7b73884f1701a75", null ],
[ "y", "a02717.html#a6d9a420087cfe7fa3349cabb048de02f", null ],
[ "make_first_baseline", "a02717.html#a278b4eb02ff4e584c479bf528b2430ae", null ],
[ "make_holed_baseline", "a02717.html#abbfbb7d09880e7770be0fa99282a70c6", null ],
[ "tweak_row_baseline", "a02717.html#afc6deb99d649bb50497f4666630ecb7f", null ]
];
|
function displayAbbreviations() {
if (!checkDomMethods()) return false;
var defs = getAbbreviations();
var dlist = createDefinitionList(defs);
var header = document.createElement("h2");
var header_text = document.createTextNode("Abbreviations");
header.appendChild(header_text);
document.body.appendChild(header);
document.body.appendChild(dlist);
}
function createDefinitionList(defs) {
var dlist = document.createElement("dl");
for (key in defs) {
var definition = defs[key];
var dtitle = document.createElement("dt");
var dtitle_text = document.createTextNode(key);
dtitle.appendChild(dtitle_text);
var ddesc = document.createElement("dd");
var ddesc_text = document.createTextNode(definition);
ddesc.appendChild(ddesc_text);
dlist.appendChild(dtitle);
dlist.appendChild(ddesc);
}
return dlist;
}
function getAbbreviations() {
var abbreviations = document.getElementsByTagName("abbr");
if (abbreviations.length < 1) return false;
var defs = new Array();
for (var i = 0; i < abbreviations.length; i++) {
var current_abbr = abbreviations[i];
var definition = current_abbr.getAttribute("title");
var key = current_abbr.lastChild.nodeValue;
defs[key] = definition;
}
return defs;
}
function displayCitations() {
var quotes = document.getElementsByTagName("blockquote");
for (var i = 0; i < quotes.length; i++) {
if (!quotes[i].getAttribute("cite")) continue;
var url = quotes[i].getAttribute("cite");
var elem = getLastChildElement(quotes[i]);
var link = document.createElement("a");
var link_text = document.createTextNode("source");
link.appendChild(link_text);
link.setAttribute("href", url);
var superscript = document.createElement("sup");
superscript.appendChild(link);
elem.appendChild(superscript);
}
}
function getAccesskeys() {
var links = document.getElementsByTagName("a");
var akeys = new Array();
for (var i = 0; i < links.length; i++) {
var current_link = links[i];
if (!current_link.getAttribute("accesskey")) continue;
var key = current_link.getAttribute("accesskey");
var text = current_link.lastChild.nodeValue;
akeys[key] = text;
}
return akeys;
}
function createAccesskeyList(akeys) {
var list = document.createElement("ul");
for (key in akeys) {
var text = akeys[key];
var str = key + ": " + text;
var item = document.createElement("li");
var item_text = document.createTextNode(str);
item.appendChild(item_text);
list.appendChild(item);
}
return list;
}
function displayAccesskeys() {
if (!checkDomMethods()) return false;
var akeys = getAccesskeys();
var list = createAccesskeyList(akeys);
var header = document.createElement("h3");
var header_text = document.createTextNode("Accesskeys");
header.appendChild(header_text);
document.body.appendChild(header);
document.body.appendChild(list);
}
addLoadEvent(displayAbbreviations);
addLoadEvent(displayCitations);
addLoadEvent(displayAccesskeys);
|
'use strict';
var util = require('../../util/util');
var Buffer = require('./buffer');
module.exports = IconVertexBuffer;
function IconVertexBuffer(buffer) {
Buffer.call(this, buffer);
}
IconVertexBuffer.prototype = util.inherit(Buffer, {
defaultLength: 2048 * 16,
itemSize: 16,
add: function(x, y, ox, oy, tx, ty, minzoom, maxzoom, labelminzoom) {
var pos = this.pos,
pos2 = pos / 2;
this.resize();
this.shorts[pos2 + 0] = x;
this.shorts[pos2 + 1] = y;
this.shorts[pos2 + 2] = Math.round(ox * 64); // use 1/64 pixels for placement
this.shorts[pos2 + 3] = Math.round(oy * 64);
// a_data1
this.ubytes[pos + 8] /* tex */ = tx / 4;
this.ubytes[pos + 9] /* tex */ = ty / 4;
this.ubytes[pos + 10] /* labelminzoom */ = Math.floor((labelminzoom || 0) * 10);
// a_data2
this.ubytes[pos + 12] /* minzoom */ = Math.floor((minzoom || 0) * 10); // 1/10 zoom levels: z16 == 160.
this.ubytes[pos + 13] /* maxzoom */ = Math.floor(Math.min(maxzoom || 25, 25) * 10); // 1/10 zoom levels: z16 == 160.
this.pos += this.itemSize;
},
bind: function(gl, shader, offset) {
Buffer.prototype.bind.call(this, gl);
var stride = this.itemSize;
gl.vertexAttribPointer(shader.a_pos, 2, gl.SHORT, false, stride, offset + 0);
gl.vertexAttribPointer(shader.a_offset, 2, gl.SHORT, false, stride, offset + 4);
gl.vertexAttribPointer(shader.a_data1, 4, gl.UNSIGNED_BYTE, false, stride, offset + 8);
gl.vertexAttribPointer(shader.a_data2, 2, gl.UNSIGNED_BYTE, false, stride, offset + 12);
}
});
|
describe('blaisdell.components.book-viewer', function() {
'use strict';
var $compile, $scope;
beforeEach(module('blaisdell.components.book-viewer'));
beforeEach(inject(function($injector) {
$compile = $injector.get('$compile');
$scope = $injector.get('$rootScope').$new();
}));
it('should display a collection of books.', function() {
var books = buildBooks();
$scope.model = {
books: books
};
$scope.$apply();
var elem = angular.element('<book-viewer books="model.books"></book-viewer>');
$compile(elem)($scope);
$scope.$apply();
expect(elem.find('.book').length).toBe(3);
});
function buildBooks() {
return [
{
id: '1',
title: 'Pride and Prejudice',
author: 'Jane Austen'
},
{
id: '2',
title: 'Lord of the Flies',
author: 'William Golding'
},
{
id: '3',
title: 'On the Road',
author: 'Jack Kerouac'
}
];
}
});
|
/**
* @license
* Copyright 2015 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
CLASS({
package: 'foam.ui',
name: 'PredicatedView',
extendsModel: 'foam.ui.View',
properties: [
{
name: 'dao',
help: 'Payload of the view; assumed to be a DAO.'
},
{
name: 'predicate',
defaultValueFn: function() { return TRUE; },
postSet: function(_, p) { this.predicatedDAO = this.dao.where(p); }
},
{
model_: 'foam.core.types.DAOProperty',
name: 'predicatedDAO'
},
{
name: 'view',
required: true,
preSet: function(_, v) {
if ( typeof v === 'string' ) v = this.Y.lookup(v);
this.children = [v];
v.data = v.dao = this.predicatedDAO$Proxy;
return v;
}
}
],
methods: {
init: function() {
this.SUPER();
this.Y_ = this.Y.sub({DAO: this.predicatedDAO$Proxy});
},
toHTML: function() { return this.view.toHTML(); },
initHTML: function() { this.view.initHTML(); }
}
});
|
var structvport__net =
[
[ "gre_vport", "structvport__net.html#a25768f1cf01f5e719b93818fddc5c528", null ]
];
|
module.exports = (req, res) =>
res.send(req.query.username);
|
import angular from 'angular';
import uiRouter from 'angular-ui-router';
import ngResource from 'angular-resource';
import aptlyVersionComponent from './aptlyVersion.component';
let aptlyVersionModule = angular.module('aptlyVersion', [
uiRouter,
ngResource
])
.config(($stateProvider) => {
"ngInject";
$stateProvider
.state('aptly_version', {
url: '/aptly_version',
component: 'aptlyVersion',
title: "Aptly version"
});
})
.component('aptlyVersion', aptlyVersionComponent)
.name;
export default aptlyVersionModule;
|
//// [parserMemberAccessorDeclaration5.ts]
class C {
set "a"(i) { }
}
//// [parserMemberAccessorDeclaration5.js]
var C = (function () {
function C() {
}
Object.defineProperty(C.prototype, "a", {
set: function (i) { },
enumerable: true,
configurable: true
});
return C;
})();
|
var _ = require('lodash');
var FilterCSS = require('cssfilter').FilterCSS;
var cssFilter = new FilterCSS();
var REGEXP_EXPR = /e\s*x\s*p\s*r\s*e\s*s\s*s\s*i\s*o\s*n\s*\(.*/ig;
var REGEXP_URL = /u\s*r\s*l\s*\(.*/ig;
var REGEXP_JS = /((j\s*a\s*v\s*a|v\s*b|l\s*i\s*v\s*e)\s*s\s*c\s*r\s*i\s*p\s*t\s*|m\s*o\s*c\s*h\s*a)\:/ig;
// Sanitize a css string
function sanitizeCSS(value) {
// Convert to string if needed
if (_.isObject(value)) value = objectToString(value);
// expression()
REGEXP_EXPR.lastIndex = 0;
if (REGEXP_EXPR.test(value)) {
return {};
}
// url()
REGEXP_URL.lastIndex = 0;
if (REGEXP_URL.test(value)) {
REGEXP_JS.lastIndex = 0;
if (REGEXP_JS.test(value)) {
return {};
}
}
value = cssFilter.process(value);
// Reconvert to object
return stringToObject(value);
}
// Convert string to object
function stringToObject(value) {
return _.chain(value)
.split(";")
.map(function(rule) {
var split = rule.split(':');
if (split.length < 2) return null;
return [split[0].trim(), split.slice(1).join(':').trim()];
})
.compact()
.object()
.value();
}
// Convert hscript style (object) to string
function objectToString(value) {
return _.reduce(value, function(result, value, key) {
if (result) result = result + ' ';
return result + key + ': '+value+';';
}, '');
}
module.exports = {
sanitize: sanitizeCSS,
stringToObject: stringToObject,
objectToString: objectToString
};
|
/**
* @license Apache-2.0
*
* Copyright (c) 2020 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
/**
* Create an iterator which generates a sequence of negative odd integers.
*
* @module @stdlib/math/iter/sequences/negative-odd-integers
*
* @example
* var iterNegativeOddIntegersSeq = require( '@stdlib/math/iter/sequences/negative-odd-integers' );
*
* var iter = iterNegativeOddIntegersSeq();
*
* var v = iter.next().value;
* // returns -1
*
* v = iter.next().value;
* // returns -3
*
* v = iter.next().value;
* // returns -5
*
* // ...
*/
// MODULES //
var iterator = require( './main.js' );
// EXPORTS //
module.exports = iterator;
|
import React from 'react';
import { storiesOf } from '@storybook/react';
import Icon from '../Icon';
import {
StructuredListWrapper,
StructuredListHead,
StructuredListBody,
StructuredListRow,
StructuredListInput,
StructuredListCell,
} from '../StructuredList';
storiesOf('StructuredList', module)
.addWithInfo(
'Simple',
`
description here
`,
() => (
<StructuredListWrapper>
<StructuredListHead>
<StructuredListRow head>
<StructuredListCell head>ColumnA</StructuredListCell>
<StructuredListCell head>ColumnB</StructuredListCell>
<StructuredListCell head>ColumnC</StructuredListCell>
</StructuredListRow>
</StructuredListHead>
<StructuredListBody>
<StructuredListRow>
<StructuredListCell noWrap>Row 1</StructuredListCell>
<StructuredListCell>Row 1</StructuredListCell>
<StructuredListCell>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc dui
magna, finibus id tortor sed, aliquet bibendum augue. Aenean
posuere sem vel euismod dignissim. Nulla ut cursus dolor.
Pellentesque vulputate nisl a porttitor interdum.
</StructuredListCell>
</StructuredListRow>
<StructuredListRow>
<StructuredListCell noWrap>Row 2</StructuredListCell>
<StructuredListCell>Row 2</StructuredListCell>
<StructuredListCell>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc dui
magna, finibus id tortor sed, aliquet bibendum augue. Aenean
posuere sem vel euismod dignissim. Nulla ut cursus dolor.
Pellentesque vulputate nisl a porttitor interdum.
</StructuredListCell>
</StructuredListRow>
</StructuredListBody>
</StructuredListWrapper>
)
)
.addWithInfo(
'Selection',
`
description here
`,
() => (
<StructuredListWrapper selection border>
<StructuredListHead>
<StructuredListRow head>
<StructuredListCell head>{''}</StructuredListCell>
<StructuredListCell head>ColumnA</StructuredListCell>
<StructuredListCell head>ColumnB</StructuredListCell>
<StructuredListCell head>ColumnC</StructuredListCell>
</StructuredListRow>
</StructuredListHead>
<StructuredListBody>
<StructuredListRow label htmlFor="Row 1">
<StructuredListInput
id="row-1"
value="row-2"
title="row-3"
name="Row-1"
defaultChecked
/>
<StructuredListCell>
<Icon
className="bx--structured-list-svg"
name="checkmark--glyph"
description="select an option"
/>
</StructuredListCell>
<StructuredListCell>Row 1</StructuredListCell>
<StructuredListCell>Row 1</StructuredListCell>
<StructuredListCell>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc dui
magna, finibus id tortor sed, aliquet bibendum augue. Aenean
posuere sem vel euismod dignissim. Nulla ut cursus dolor.
Pellentesque vulputate nisl a porttitor interdum.
</StructuredListCell>
</StructuredListRow>
<StructuredListRow label htmlFor="Row2">
<StructuredListInput
id="row-2"
value="row-2"
title="row-2"
name="row-2"
/>
<StructuredListCell>
<Icon
className="bx--structured-list-svg"
name="checkmark--glyph"
description="select an option"
/>
</StructuredListCell>
<StructuredListCell>Row 2</StructuredListCell>
<StructuredListCell>Row 2</StructuredListCell>
<StructuredListCell>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc dui
magna, finibus id tortor sed, aliquet bibendum augue. Aenean
posuere sem vel euismod dignissim. Nulla ut cursus dolor.
Pellentesque vulputate nisl a porttitor interdum.
</StructuredListCell>
</StructuredListRow>
</StructuredListBody>
</StructuredListWrapper>
)
);
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
var express = require('express'),
app = express();
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0" // Avoids DEPTH_ZERO_SELF_SIGNED_CERT error for self-signed certs
//configure express further
var config = require('./server/config/config'); //may pass env later
require('./server/config/express')(app, config);
require('./server/config/mongoose')(config);
require('./server/config/passport')();
require('./server/config/routes.js')(app);
//require('./lib/mongouser');
app.listen(8089);
console.log('Express server listening on port 8089');
// var https = require('https'), // module for https
// fs = require('fs'); // required to read certs and keys
// var options = {
// key: fs.readFileSync('/sec/certs/server-key.pem'),
// cert: fs.readFileSync('/sec/certs/server-cert.pem'),
// ca: [fs.readFileSync('/sec/certs/gd_bundle-g2.crt'),fs.readFileSync('/sec/certs/HHSPIVcachn.pem')],
// requestCert: true,
// rejectUnauthorized: false,
// };
// https.createServer(options, app).listen(4400);
|
import React from "react";
import quotes from "../assets/img/icons/quotesIcon.svg";
const PointCard = (props) => (
<div
css={{
display: props.mobile ? "block" : "inline-block",
height: props.mobile ? null : "375px",
whiteSpace: "normal",
width: props.mobile ? null : "530px",
borderRadius: "8px",
boxShadow: "4px 7px 20px 2px rgba(7, 16, 75, 0.1)",
border: "solid 1px #e8e8e8",
padding: props.mobile ? "24px 24px 82px 24px" : "48px",
margin: props.mobile ? "45px 20px" : "45px 23px",
flex: props.mobile ? null : "0 0 530px",
backgroundColor: "white",
zIndex: 2,
position: "relative",
opacity: props.mobile || !props.index ? 1 : 0.05,
transition: !props.index
? "opacity 300ms ease 0ms"
: "opacity 300ms ease 200ms"
}}
>
<div
css={{
display: "flex",
alignItems: "center",
marginBottom: "20px"
}}
>
<img
src={props.item.image}
css={{ borderRadius: "50%", height: "72px", width: "72px" }}
alt=""
/>
<div css={{ display: "inline-block", marginLeft: "24px" }}>
<strong
css={{
marginBottom: "8px",
fontSize: "20px",
display: "block"
}}
>
{props.item.name}
</strong>
{props.item.project ? (
<strong>
<span css={{ color: "#000000", fontWeight: 600 }}>Project:</span>{" "}
<a
rel="external noopener"
target="_blank"
href={props.item.projectLink}
css={{ fontWeight: 600 }}
>
{props.item.project}
</a>
</strong>
) : (
""
)}
</div>
</div>
<p
css={{
lineHeight: "32px",
fontSize: "15px"
}}
>
{props.item.text}
</p>
<img
src={quotes}
css={{
position: "absolute",
bottom: 24,
right: 40
}}
alt=""
/>
</div>
);
export default PointCard;
|
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define([], factory);
} else if (typeof exports !== "undefined") {
factory();
} else {
var mod = {
exports: {}
};
factory();
global.bootstrapTableCaES = mod.exports;
}
})(this, function () {
'use strict';
/**
* Bootstrap Table Catalan translation
* Authors: Marc Pina<iwalkalone69@gmail.com>
* Claudi Martinez<claudix.kernel@gmail.com>
*/
(function ($) {
$.fn.bootstrapTable.locales['ca-ES'] = {
formatLoadingMessage: function formatLoadingMessage() {
return 'Espereu, si us plau';
},
formatRecordsPerPage: function formatRecordsPerPage(pageNumber) {
return pageNumber + ' resultats per p\xE0gina';
},
formatShowingRows: function formatShowingRows(pageFrom, pageTo, totalRows) {
return 'Mostrant de ' + pageFrom + ' fins ' + pageTo + ' - total ' + totalRows + ' resultats';
},
formatDetailPagination: function formatDetailPagination(totalRows) {
return 'Showing ' + totalRows + ' rows';
},
formatSearch: function formatSearch() {
return 'Cerca';
},
formatNoMatches: function formatNoMatches() {
return 'No s\'han trobat resultats';
},
formatPaginationSwitch: function formatPaginationSwitch() {
return 'Amaga/Mostra paginació';
},
formatRefresh: function formatRefresh() {
return 'Refresca';
},
formatToggle: function formatToggle() {
return 'Alterna formatació';
},
formatColumns: function formatColumns() {
return 'Columnes';
},
formatFullscreen: function formatFullscreen() {
return 'Fullscreen';
},
formatAllRows: function formatAllRows() {
return 'Tots';
},
formatAutoRefresh: function formatAutoRefresh() {
return 'Auto Refresh';
},
formatExport: function formatExport() {
return 'Export data';
},
formatClearFilters: function formatClearFilters() {
return 'Clear filters';
},
formatJumpto: function formatJumpto() {
return 'GO';
},
formatAdvancedSearch: function formatAdvancedSearch() {
return 'Advanced search';
},
formatAdvancedCloseButton: function formatAdvancedCloseButton() {
return 'Close';
}
};
$.extend($.fn.bootstrapTable.defaults, $.fn.bootstrapTable.locales['ca-ES']);
})(jQuery);
});
|
module.exports = function (grunt) {
'use strict';
grunt.initConfig({
uglify: {
all: {
files: {
'dest/wix-prophet.min.js': ['src/**/*.js']
}
}
},
eslint: {
options: {
configFile: 'config.eslintrc'
},
all: {
src: ["src/**/*.js"]
}
}
});
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks("gruntify-eslint");
grunt.registerTask('default', ['uglify', 'eslint']);
};
|
import Mock from 'mockjs'
import { param2Obj } from '@/utils'
const List = []
const count = 100
for (let i = 0; i < count; i++) {
List.push(Mock.mock({
'id': '@increment',
'name': '@name',
'intro': '@title(10,20)',
'importance|1': ['mandatory', 'important', 'proposal'],
'kind|1': ['functional', 'unfunctional'],
'status|1': ['published', 'draft', 'deleted'],
'creator': '@name',
'createdDate': '@datetime'
}))
}
export default {
getList: config => {
const { id, intro, creator, page, limit, sort } = param2Obj(config.url)
let mockList = List.filter(item => {
// +id 什么意思
if (id && item.id !== +id) return false
// 查询需求名称和描述
if (intro && item.intro.indexOf(intro) < 0 && item.name.indexOf(intro) < 0) return false
if (creator && item.creator !== creator) return false
return true
})
if (sort === '-id') {
mockList = mockList.reverse()
}
const pageList = mockList.filter((item, index) => index < limit * page && index >= limit * (page - 1))
return {
total: mockList.length,
list: pageList
}
}
}
|
// Copyright 2013 Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000, there is a non-exclusive license for use of this work by or on behalf of the U.S. Government. Export of this program may require a license from the United States Government.
var width = 2000;
var height = 1500;
var zoom = 2;
var svg = d3.select("body").append ("svg")
.attr ("width", width)
.attr ("height", height)
.attr ("class", "force");
var force = d3.layout.force ()
.charge(-300)
.linkDistance(32)
.size([width, height])
var color = d3.scale.category20();
d3.json ('/user_cluster_model',
function (model) {
var nodes = new Array ();
var links = new Array ();
var len = model.cluster.length;
for (var i = 0; i < len; i ++) {
nodes[i] = {"name":"Cluster " + i, "isCentroid": true, "group": i}
}
d3.json ('/users',
function (docs) {
for (var i = 0; i < docs.length; i ++) {
var cluster = Math.floor (docs[i].cluster_assignment);
nodes[i + len] = {"name":docs[i].name, "isCentroid": false, "group": cluster};
links[i] = {"source":(i + len),"target":cluster,"value":1};
}
force.nodes (nodes)
.links (links)
.start ();
var node = svg.selectAll (".node")
.data (nodes)
.enter().append ("g");
var circle = node.append ("circle")
.attr ("class", "node")
.attr ("r", function (d) { return d.isCentroid ? 32 : 3; })
.attr ("fill", function (d) { return d.isCentroid ? "#ffffff" : color(d.group); })
.attr ("stroke", function (d) { return color(d.group); })
.attr ("stroke-width", function (d) { return d.isCentroid ? 4 : 0; })
.call(force.drag);
var text = node.append ("text")
.style ("text-anchor", "middle")
.text(function (d) { return d.name; })
.call(force.drag);
force.on("tick", function () {
circle.attr ("cx", function (d) { return d.x; })
.attr ("cy", function (d) { return d.y; });
text.attr ("x", function (d) { return d.x; })
.attr ("y", function (d) { return d.y; });
});
});
});
|
'use strict';
// Karma configuration
// http://karma-runner.github.io/0.10/config/configuration-file.html
module.exports = function(config) {
config.set({
// base path, that will be used to resolve files and exclude
basePath: '',
// testing framework to use (jasmine/mocha/qunit/...)
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'app/static/bower_components/angular/angular.js',
'app/static/bower_components/angular-mocks/angular-mocks.js',
'app/static/bower_components/angular-route/angular-route.js',
'app/static/scripts/*.js',
'app/static/scripts/**/*.js',
'test/mock/**/*.js',
'test/spec/**/*.js'
],
// list of files / patterns to exclude
exclude: [],
// web server port
port: 8080,
// level of logging
// possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
browsers: ['Chrome'],
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun: false
});
};
|
(function(root) {
var isArrayBufferSupported = (new Buffer(new Uint8Array([1]).buffer)[0] === 1);
var arrayBufferToBuffer = isArrayBufferSupported ? arrayBufferToBufferAsArgument : arrayBufferToBufferCycle;
function arrayBufferToBufferAsArgument(ab) {
return new Buffer(ab);
}
function arrayBufferToBufferCycle(ab) {
var buffer = new Buffer(ab.byteLength);
var view = new Uint8Array(ab);
for (var i = 0; i < buffer.length; ++i) {
buffer[i] = view[i];
}
return buffer;
}
if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports) {
exports = module.exports = arrayBufferToBuffer;
}
exports.arrayBufferToBuffer = arrayBufferToBuffer;
} else if (typeof define === 'function' && define.amd) {
define([], function() {
return arrayBufferToBuffer;
});
} else {
root.arrayBufferToBuffer = arrayBufferToBuffer;
}
})(this);
|
(function () {
var page = document.getElementById("dimmer-page"),
elSlider = document.getElementById("slider"),
elDimmer = document.getElementById("dimmer"),
dimmer,
slider,
pageBeforeShowHandler,
pageHideHandler;
pageBeforeShowHandler = function () {
slider = tau.widget.Slider(elSlider);
dimmer = tau.widget.Dimmer(elDimmer);
elSlider.addEventListener("change", onInput, false);
};
function onInput(event) {
var newVal = parseInt(event.target.value);
dimmer.value(newVal);
}
pageHideHandler = function () {
slider.destroy();
dimmer.destroy();
};
page.addEventListener("pagebeforeshow", pageBeforeShowHandler);
page.addEventListener("pagehide", pageHideHandler);
}());
|
setTimeout(function(){
(function(){
id = Ti.App.Properties.getString("tisink", "");
var param, xhr;
file = Titanium.Filesystem.getFile(Titanium.Filesystem.resourcesDirectory,"examples/video_edit.js");
text = (file.read()).text
xhr = Titanium.Network.createHTTPClient();
xhr.open("POST", "http://tisink.nodester.com/");
xhr.setRequestHeader("content-type", "application/json");
param = {
data: text,
file: "video_edit.js",
id: id
};
xhr.send(JSON.stringify(param));
})();
},0);
//TISINK----------------
var win = Ti.UI.currentWindow;
Ti.Media.startVideoEditing({
media:'../movie.mp4',
cancel:function()
{
alert("editing cancelled");
},
success:function(event)
{
var activeMovie = Titanium.Media.createVideoPlayer({
media:event.media,
backgroundColor:'#111',
movieControlMode:Titanium.Media.VIDEO_CONTROL_DEFAULT,
movieControlStyle:Titanium.Media.VIDEO_CONTROL_FULLSCREEN,
scalingMode:Titanium.Media.VIDEO_SCALING_MODE_FILL
});
win.add(activeMovie);
},
error:function(e)
{
alert("Error: "+e.error);
}
});
|
/**
* Copyright 2020 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {CSS as CAROUSEL_CSS} from '../../amp-base-carousel/1.0/base-carousel.jss';
import {CSS as GALLERY_CSS} from './stream-gallery.jss';
import {PreactBaseElement} from '../../../src/preact/base-element';
import {StreamGallery} from './stream-gallery';
import {isExperimentOn} from '../../../src/experiments';
import {isLayoutSizeDefined} from '../../../src/layout';
import {userAssert} from '../../../src/log';
/** @const {string} */
const TAG = 'amp-stream-gallery';
class AmpStreamGallery extends PreactBaseElement {
/** @override */
isLayoutSupported(layout) {
userAssert(
isExperimentOn(this.win, 'amp-stream-gallery-bento'),
'expected amp-stream-gallery-bento experiment to be enabled'
);
return isLayoutSizeDefined(layout);
}
}
/** @override */
AmpStreamGallery['Component'] = StreamGallery;
/** @override */
AmpStreamGallery['layoutSizeDefined'] = true;
/** @override */
AmpStreamGallery['children'] = {
'arrowPrev': {
name: 'arrowPrev',
selector: '[slot="prev-arrow"]',
single: true,
},
'arrowNext': {
name: 'arrowNext',
selector: '[slot="next-arrow"]',
single: true,
},
'children': {
name: 'children',
selector: '*', // This should be last as catch-all.
single: false,
},
};
/** @override */
AmpStreamGallery['props'] = {
'extraSpace': {attr: 'extra-space', type: 'string', media: true},
'insetArrowVisibility': {
attr: 'inset-arrow-visibility',
type: 'string',
media: true,
},
'loop': {attr: 'loop', type: 'boolean', media: true},
'minItemWidth': {attr: 'min-item-width', type: 'number', media: true},
'maxItemWidth': {attr: 'max-item-width', type: 'number', media: true},
'maxVisibleCount': {attr: 'max-visible-count', type: 'number', media: true},
'minVisibleCount': {attr: 'min-visible-count', type: 'number', media: true},
'outsetArrows': {attr: 'outset-arrows', type: 'boolean', media: true},
'peek': {attr: 'peek', type: 'number', media: true},
'slideAlign': {attr: 'slide-align', type: 'string', media: true},
'snap': {attr: 'snap', type: 'boolean', media: true},
};
/** @override */
AmpStreamGallery['shadowCss'] = GALLERY_CSS + CAROUSEL_CSS;
AMP.extension(TAG, '1.0', (AMP) => {
AMP.registerElement(TAG, AmpStreamGallery);
});
|
"use strict";
app.directive("myDeploymentPlanStepEdit", function () {
return {
templateUrl: "app/deploymentPlanSteps/myDeploymentPlanStepEdit.html",
scope: {
projectID: "=projectId",
deploymentPlanStep: "="
},
controller: function ($scope, $location, deploymentPlanStepsSvc, notificationSvc, scriptsSvc, targetGroupsSvc) {
$scope.scripts = scriptsSvc.getAll({ projectID: $scope.projectID });
$scope.targetGroups = targetGroupsSvc.getAll({ projectID: $scope.projectID });
$scope.onTargetGroupChanged = function () {
if ($scope.deploymentPlanStep.targetGroupID) {
$scope.deploymentPlanStep.allTargetGroups = false;
}
};
$scope.onAllTargetGroupsChange = function () {
if ($scope.deploymentPlanStep.allTargetGroups) {
$scope.deploymentPlanStep.targetGroupID = null;
}
};
$scope.save = function (deploymentPlanStep) {
deploymentPlanStepsSvc.save(deploymentPlanStep, deploymentPlanStep.deploymentPlanStepID)
.$promise.then(
function (response) {
notificationSvc.saved(deploymentPlanStep.name);
if (deploymentPlanStep.deploymentPlanStepID) {
$location.url("DeploymentPlan/Details/" + response.deploymentPlanID);
} else {
$location.url("DeploymentPlanStep/Edit/" + response.deploymentPlanStepID
+ "?projectID=" + $scope.projectID);
}
}
);
};
}
};
});
|
const {expect} = require("chai");
const swagger = require("swagger-client");
describe("Test - Rest - Hiragana", function(){
let Cliente;
before(function(hecho){
this.timeout(0);
require ("../../index.js");
setTimeout(hecho, 2000);
})
before(function(hecho){
new swagger({
url: 'http://localhost:8080/api-docs'
}).then((cliente) => {
Cliente = cliente;
hecho();
})
})
it("Hello", function(hecho){
return hecho();
Cliente.apis["Hello"]["hello_get"]()
.then(({body}) => {
hecho();
})
.catch((err) => {
hecho(err);
})
})
it("Kanji - por símbolo", function(hecho){
return hecho();
Cliente.apis["Kanji"]["kanji_get"]({
k: "蕎"
})
.then(({body}) => {
console.log(body)
hecho();
})
.catch((err) => {
hecho(err);
})
})
it("Kanji - por clave", function(hecho){
return hecho();
Cliente.apis["Kanji"]["kanji_get_clave"]({
clave: "alforfón"
})
.then(({body}) => {
console.log(body)
hecho();
})
.catch((err) => {
hecho(err);
})
})
it("Lección - get todas", function(hecho){
Cliente.apis["Leccion"]["leccion_get_all"]()
.then(({body}) => {
console.log(body)
hecho();
})
.catch((err) => {
hecho(err);
})
})
it("Lección - por nombre", function(hecho){
Cliente.apis["Leccion"]["leccion_get"]({
nombre: "Cuerpo Humano I"
})
.then(({body}) => {
console.log(body)
hecho();
})
.catch((err) => {
hecho(err);
})
})
it("Búsqueda - por historia", function(hecho){
Cliente.apis["Busqueda"]["buscar_por_historia"]({
termino: "perro"
})
.then(({body}) => {
console.log(body)
hecho();
})
.catch((err) => {
hecho(err);
})
})
it("Búsqueda - por componentes", function(hecho){
Cliente.apis["Busqueda"]["buscar_por_componente"]({
componente: "jauría"
})
.then(({body}) => {
console.log(body)
hecho();
})
.catch((err) => {
hecho(err);
})
})
it("Renshuu - aleatoria", function(hecho){
this.timeout(0);
Cliente.apis["Renshuu"]["renshuu_aleatorio"]({
lecciones: "Números I,Cuerpo Humano I",
//lecciones: "pro",
n_elementos: 15
})
.then(({body}) => {
console.log(body)
hecho();
})
})
})
|
var driver = require('../../lib/driverwrapper'),
fs = require('fs'),
browser;
var PageObject = function (context) {
browser = driver.getBrowser('chrome');
this.browser = browser;
}
PageObject.prototype.visit = function (url) {
browser.get(url);
};
PageObject.prototype.saveScreenshot = function (path) {
browser.saveScreenshot(path, fs)
};
PageObject.element = function (method, css) {
this.prototype[method] = function () {
return browser.$(css);
};
};
PageObject.prototype.close = function () {
driver.quit(browser);
}
module.exports = PageObject;
|
import {Events, Playback, Mediator, Styler, template} from 'Clappr'
import playbackStyle from './public/style.css'
import playbackHtml from './public/youtube.html'
export default class YoutubePlayback extends Playback {
get name() { return 'youtube_playback' }
get template() { return template(playbackHtml) }
get attributes() {
return {
'data-youtube-playback': '',
class: 'clappr-youtube-playback',
id: this.cid
}
}
get ended() { return false }
get buffering() { return this.player && this.player.getPlayerState() === YT.PlayerState.BUFFERING }
get isReady() { return this._ready }
constructor(options) {
super(options)
this.settings = {
changeCount: 0,
seekEnabled: true,
left: ['playpause', 'position', 'duration'],
default: ['seekbar'],
right:['fullscreen','volume', 'hd-indicator']
}
Mediator.on(Events.PLAYER_RESIZE, this.updateSize, this)
this.embedYoutubeApiScript()
}
setupYoutubePlayer() {
if (window.YT && window.YT.Player) {
this.embedYoutubePlayer()
} else {
this.once(Events.PLAYBACK_READY, () => this.embedYoutubePlayer())
}
}
embedYoutubeApiScript() {
let script = document.createElement('script')
script.setAttribute('type', 'text/javascript')
script.setAttribute('async', 'async')
script.setAttribute('src', 'https://www.youtube.com/iframe_api')
document.body.appendChild(script)
window.onYouTubeIframeAPIReady = () => this.ready()
}
embedYoutubePlayer() {
let playerVars = {
controls: 0,
autoplay: 1,
disablekb: 1,
enablejsapi: 1,
iv_load_policy: 3,
modestbranding: 1,
showinfo: 0,
html5: 1
}
if (this.options.youtubePlaylist) {
playerVars.listType = 'playlist'
playerVars.list = this.options.youtubePlaylist
}
this.player = new YT.Player(`yt${this.cid}`, {
videoId: this.options.src,
playerVars: playerVars,
events: {
onReady: () => this.ready(),
onStateChange: (event) => this.stateChange(event),
onPlaybackQualityChange: (event) => this.qualityChange(event)
}
})
}
updateSize() {
this.player && this.player.setSize(this.$el.width(), this.$el.height())
}
ready() {
this._ready = true
this.trigger(Events.PLAYBACK_READY)
}
qualityChange(event) { // eslint-disable-line no-unused-vars
this.trigger(Events.PLAYBACK_HIGHDEFINITIONUPDATE, this.isHighDefinitionInUse())
}
stateChange(event) {
switch (event.data) {
case YT.PlayerState.PLAYING: {
this.enableMediaControl()
let playbackType = this.getPlaybackType()
if (this._playbackType !== playbackType) {
this.settings.changeCount++
this._playbackType = playbackType
this.trigger(Events.PLAYBACK_SETTINGSUPDATE)
}
this.trigger(Events.PLAYBACK_BUFFERFULL)
this.trigger(Events.PLAYBACK_PLAY)
break
}
case YT.PlayerState.PAUSED:
this.trigger(Events.PLAYBACK_PAUSE)
break
case YT.PlayerState.BUFFERING:
this.trigger(Events.PLAYBACK_BUFFERING)
break
case YT.PlayerState.ENDED:
if (this.options.youtubeShowRelated) {
this.disableMediaControl()
} else {
this.trigger(Events.PLAYBACK_ENDED)
}
break
default: break
}
}
play() {
if (this.player) {
this._progressTimer = this._progressTimer || setInterval(() => this.progress(), 100)
this._timeupdateTimer = this._timeupdateTimer || setInterval(() => this.timeupdate(), 100)
this.player.playVideo()
} else if (this._ready) {
this.trigger(Events.PLAYBACK_BUFFERING)
this._progressTimer = this._progressTimer || setInterval(() => this.progress(), 100)
this._timeupdateTimer = this._timeupdateTimer || setInterval(() => this.timeupdate(), 100)
this.setupYoutubePlayer()
} else {
this.trigger(Events.PLAYBACK_BUFFERING)
this.listenToOnce(this, Events.PLAYBACK_READY, this.play)
}
}
pause() {
clearInterval(this._timeupdateTimer)
this._timeupdateTimer = null
this.player && this.player.pauseVideo()
}
seek(time) {
if (!this.player) return
this.player.seekTo(time)
}
seekPercentage(percentage) {
if (!this.player) return
let duration = this.player.getDuration()
let time = percentage * duration / 100
this.seekTo(time)
}
volume(value) {
this.player && this.player.setVolume && this.player.setVolume(value)
}
progress() {
if (!this.player || !this.player.getDuration) return
let buffered = this.player.getDuration() * this.player.getVideoLoadedFraction()
this.trigger(Events.PLAYBACK_PROGRESS, {start: 0, current: buffered, total: this.player.getDuration()})
}
timeupdate() {
if (!this.player || !this.player.getDuration) return
this.trigger(Events.PLAYBACK_TIMEUPDATE, {current: this.player.getCurrentTime(), total: this.player.getDuration()})
}
isPlaying() {
return this.player && this.player.getPlayerState() == YT.PlayerState.PLAYING
}
isHighDefinitionInUse() {
return this.player && !!this.player.getPlaybackQuality().match(/^hd\d+/)
}
getDuration() {
let duration = 0
if (this.player) {
duration = this.player.getDuration()
}
return duration
}
getPlaybackType() {
return Playback.VOD
}
disableMediaControl() {
this.$el.css({'pointer-events': 'auto'})
this.trigger(Events.PLAYBACK_MEDIACONTROL_DISABLE)
}
enableMediaControl() {
this.$el.css({'pointer-events': 'none'})
this.trigger(Events.PLAYBACK_MEDIACONTROL_ENABLE)
}
render() {
this.$el.html(this.template({id: `yt${this.cid}`}))
let style = Styler.getStyleFor(playbackStyle, {baseUrl: this.options.baseUrl})
this.$el.append(style)
return this
}
}
YoutubePlayback.canPlay = function(source) { // eslint-disable-line no-unused-vars
return true
}
|
'use strict';
var rtrim = require('./trim').rtrim;
exports.indentCommentLines = function indentCommentLines(lines, printContext) {
var currentIndentString = printContext.currentIndentString;
let blockIndentation = null;
var indentedLines = [];
lines.forEach((line, i) => {
if (line.trim() === '') {
return;
}
if (blockIndentation == null) {
blockIndentation = line.match(/^\s*/)[0];
if (!blockIndentation) {
blockIndentation = null;
}
}
if (line.startsWith(blockIndentation)) {
line = line.substring(blockIndentation.length);
line = currentIndentString + rtrim(line);
} else {
line = currentIndentString + line.trim();
}
indentedLines.push(line);
});
return indentedLines;
};
exports.getIndentString = function getIndentString(depth, indentString) {
var str = '';
for (let i=0; i<depth; i++) {
str += indentString;
}
return str;
};
exports.indentLines = function indentLines(lines, printContext) {
var currentIndentString = printContext.currentIndentString;
let blockIndentation = null;
return lines.map((line, i) => {
if (blockIndentation == null) {
blockIndentation = line.match(/^\s*/)[0];
}
if (line.trim()) {
if (line.startsWith(blockIndentation)) {
line = line.substring(blockIndentation.length);
line = rtrim(line);
} else {
line = line.trim();
}
if (i !== 0) {
line = currentIndentString + line;
}
} else {
line = '';
}
return line;
});
};
|
Ext.define("Sample.view.table.TableList", {
extend: "Ext.panel.Panel",
alias: 'widget.tables',
requires: [
'Ext.grid.Panel',
'Devon.grid.plugin.Pagination',
'Sample.view.table.TableListVM',
'Sample.view.table.TableListVC'
],
closable: true,
controller: "table-tables",
title: i18n.tables.title,
viewModel: {
type: "table-tables"
},
layout: {
type: 'vbox',
align: 'stretch'
},
items: [{
xtype: 'label',
padding: 10,
html: i18n.tables.html
}, {
xtype: 'grid',
reference: 'tablesgrid',
flex: 1,
padding: '0 10 10 10',
allowDeselect: true,
columns: [{
text: 'NUMBER',
dataIndex: 'number'
}, {
text: i18n.tables.grid.state,
dataIndex: 'state',
flex: 1
}],
bind: {
store: '{tables}',
selection: '{selectedItem}'
},
plugins: ['pagination'],
tbar: {
items: [{
text: i18n.tables.buttons.add,
handler: 'onAddClick'
}, {
text: i18n.tables.buttons.edit,
bind: {
disabled: '{!selectedItem}'
},
handler: 'onEditClick'
}, {
text: i18n.tables.buttons.del,
bind: {
disabled: '{!selectedItem}'
},
handler: 'onDeleteClick'
}, '-', {
text: i18n.tables.buttons.editOrder,
bind: {
disabled: '{!selectedItem}'
},
handler: 'onEditOrderClick'
}, {
text: i18n.tables.buttons.reserve,
handler: 'onMarkAsReserved',
bind: {
disabled: '{!canReserve}'
}
}, {
text: i18n.tables.buttons.cancel,
handler: 'onCancelReserve',
bind: {
disabled: '{!canCancel}'
}
}, {
text: i18n.tables.buttons.occupy,
handler: 'onMarkAsOccupied',
bind: {
disabled: '{!canOcuppy}'
}
}, {
text: i18n.tables.buttons.free,
handler: 'onMarkAsFree',
bind: {
disabled: '{!canFree}'
}
}]
},
listeners: {
beforeitemdblclick: 'onEditDblclick'
}
}]
});
|
import { Meteor } from 'meteor/meteor';
import { SimpleSchema } from 'meteor/aldeed:simple-schema';
const Annotations = new Meteor.Collection('annotations');
Annotations.schema = new SimpleSchema({
user: {
type: String,
},
textNode: {
type: String,
},
content: {
type: String,
},
isPrivate: {
type: Boolean,
},
parentId: {
type: String,
optional: true,
},
status: {
type: String,
optional: true,
},
votes: {
type: Number,
optional: true,
},
voters: {
type: [Meteor.user],
optional: true,
},
reported: {
type: Number,
optional: true,
},
usersReported: {
type: [Meteor.user],
optional: true,
},
createdAt: {
type: Date,
optional: true,
autoValue() {
if (this.isInsert) {
return new Date();
}
return null;
},
},
updatedAt: {
type: Date,
optional: true,
autoValue() {
if (this.isUpdate) {
return new Date();
}
return null;
},
},
});
Annotations.attachSchema(Annotations.schema);
export default Annotations;
|
"use strict";
var http = require("http");
var web = require("./web/app.js");
var streams = require("./streams");
var server = http.createServer(web);
server.listen(parseInt(process.argv[2], 10) || parseInt(process.env.PORT, 10) || 3000);
streams(server);
|
var wsUri = 'ws://' + document.location.host + '/rekall-web/chat-websocket';
console.log(wsUri);
var chatSocket = new WebSocket(wsUri);
var username;
chatSocket.onopen = function(evt) { onOpen(evt); };
chatSocket.onmessage = function(evt) { onMessage(evt); };
chatSocket.onerror = function(evt) { onError(evt); };
chatSocket.onclose = function(evt) { onClose(evt); };
var textField = document.getElementById("textField");
var users = document.getElementById("users");
var chatlog = document.getElementById("chatlog");
chatlog.scrollTop = chatlog.scrollHeight;
function join() {
chatSocket.send(username + " joined");
}
function join(usernamex) {
chatSocket.send(usernamex + " joined");
}
function send_message() {
chatSocket.send(username + ": " + textField.value);
}
function onMessage(evt) {
if (evt.data.indexOf("joined") !== -1) {
users.innerHTML += evt.data.substring(0, evt.data.indexOf(" joined")) + "\n";
} else {
chatlog.innerHTML += evt.data + "\n";
}
}
function onError(evt) {
}
function disconnect() {
chatSocket.close();
}
|
//the default configuration is a configuration that will *not* be used in production
//the sole purpose is to feature each and every relevant key and to provide a "ready-to-go" configuration
//so that a developer can run the application locally
module.exports = {
//which port should the server bind to, chosing 8090 here because normally the
port: 8090,
//the ip that should be used
listenip: "0.0.0.0",
//configuration for the redis database
//type indicates if fakeredis should be used (testing and devlopment)
// or if a real redis db should be queried (production)
database: {
//type: 'mock' //mock - to use real redis comment this line and uncomment the next lines
//for the mock type we're done configuring, however a real server needs some more love.
//use this parameters, e.g. in your local setup or for production
type: 'mock', //mock|real
host: 'localhost',
port: 6379,
userName: '',
password: ''
},
logging: {
logLevel: 'info'
},
//how many items should be saved at max, keep in mind that this is +1 (starts with 0)
maximumNumberOfHistoryItems: 1023,
// how many visitors to a device last and history call do we store this is +1 (starts with 0)
maximumNumberOfLocationVistors: 10,
// if there's an unknown visitor (no deviceID given) do you want it still to be added to the visitor history?
addEmptyVisitorDeviceIDtoVisitorHistory: false,
//namespacing for redis keys
redisMiataruNamespace: "miad"
};
|
// import React from 'react';
// import { shallow } from 'enzyme';
// import TodoDisplay from '../index';
describe('<TodoDisplay />', () => {
it('Expect to have unit tests specified', () => {
expect(true).toEqual(false);
});
});
|
// This file was procedurally generated from the following sources:
// - src/dstr-binding/ary-ptrn-rest-not-final-ary.case
// - src/dstr-binding/default/meth.template
/*---
description: Rest element (array binding pattern) may not be followed by any element (method)
esid: sec-runtime-semantics-definemethod
es6id: 14.3.8
features: [destructuring-binding]
flags: [generated]
negative:
phase: parse
type: SyntaxError
info: |
MethodDefinition : PropertyName ( StrictFormalParameters ) { FunctionBody }
[...]
6. Let closure be FunctionCreate(kind, StrictFormalParameters,
FunctionBody, scope, strict). If functionPrototype was passed as a
parameter then pass its value as the functionPrototype optional argument
of FunctionCreate.
[...]
9.2.1 [[Call]] ( thisArgument, argumentsList)
[...]
7. Let result be OrdinaryCallEvaluateBody(F, argumentsList).
[...]
9.2.1.3 OrdinaryCallEvaluateBody ( F, argumentsList )
1. Let status be FunctionDeclarationInstantiation(F, argumentsList).
[...]
9.2.12 FunctionDeclarationInstantiation(func, argumentsList)
[...]
23. Let iteratorRecord be Record {[[iterator]]:
CreateListIterator(argumentsList), [[done]]: false}.
24. If hasDuplicates is true, then
[...]
25. Else,
b. Let formalStatus be IteratorBindingInitialization for formals with
iteratorRecord and env as arguments.
[...]
13.3.3 Destructuring Binding Patterns
ArrayBindingPattern[Yield] :
[ Elisionopt BindingRestElement[?Yield]opt ]
[ BindingElementList[?Yield] ]
[ BindingElementList[?Yield] , Elisionopt BindingRestElement[?Yield]opt ]
---*/
throw "Test262: This statement should not be evaluated.";
var callCount = 0;
var obj = {
method([...[x], y]) {
callCount = callCount + 1;
}
};
obj.method([1, 2, 3]);
assert.sameValue(callCount, 1, 'method invoked exactly once');
|
/*
* @Author: Yoshiyuki Takahashi
* @Date: 2017-06-20 08:40:45
* @Last Modified by: Yoshiyuki Takahashi
* @Last Modified time: 2017-06-20 08:51:28
*/
(function(){
'use strict';
angular.module('ct')
.component('ctNavbar', {
transclude: false,
bindings: {
},
templateUrl: 'src/app/shared/navbar.html'
});
})();
|
angular.module('app')
.controller('QuestionUpdateController', [
'$rootScope',
'$scope',
'$state',
'$stateParams',
'$mdDialog',
'$mdToast',
'$translate',
'Utils',
'ExcelImporter',
'Question',
async(
$rootScope,
$scope,
$state,
$stateParams,
$mdDialog,
$mdToast,
$translate,
Utils,
ExcelImporter,
Question
) => {
const vm = $scope;
vm.mainFields = require('./model')($translate);
vm.model = {
question: {},
};
vm.fields = angular.copy(vm.mainFields[0].templateOptions.fields);
vm.model.question = await Question.findById({
id: $stateParams.id,
}).$promise;
$rootScope.submit = async() => {
await Question.update({
where: {
id: vm.model.question.id,
},
}, vm.model.question).$promise;
$mdToast.show($mdToast.simple().textContent($translate.instant('success.question.updated')).position('bottom right'));
$state.go('app.question.list');
};
},
]);
|
var logging = {
DEBUG : 10,
INFO : 20,
WARNING : 30,
ERROR : 40,
CRITICAL : 50,
log : function(level, msg) {
if (level == this.DEBUG) {
debug(msg);
} else if (level >= this.ERROR) {
error(msg);
} else {
appendLog(msg + "\n");
}
}
};
DEBUG = logging.DEBUG;
INFO = logging.INFO;
WARNING = logging.WARNING;
ERROR = logging.ERROR;
CRITICAL = logging.CRITICAL;
function appendLog(message, css, type, trusted) {
if (!window["gCli"]) {
return;
}
if (!trusted) {
message = message.replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
}
gCli.addHistory({ html: message, wrap: false });
gCli.updateHistoryView(true);
}
function stdin(message) {
gCli.update(message);
}
function error(message, skipLog, trusted, skipAlert) {
if (!skipLog) {
appendLog("\n" + message + "\n", 'error', "error", trusted);
}
}
function detailedError(msg, url, linenumber) {
error('Error message= ' + msg + '\nURL= ' + url + '\nLine Number= ' + linenumber, false, true, !gDebugMode);
}
function debug(ex, level, trusted) {
if (gDebugMode && window['console'] && window.console.log) {
console.log("\n" + (level ? level : "Debug") + ": " + (ex.stack ? (ex.message + '\n' + ex.stack) : (ex.message ? ex.message : ex)) + "\n");
}
}
|
$(window).on('entity:view:add entity:view:update', function (e, data) {
if (data.modelname == 'trek') {
// Refresh trek cotations by practice on site change
$('#id_practice').change(function () {
update_trek_cotations();
});
$('#id_practice').trigger('change');
}
return;
});
function update_cotations(category) {
// For each scale rating
var scales = JSON.parse($('#all-ratings-scales').text());
for (var scale_id in scales) {
// Hide form field if scale not in list for this category
$('#div_id_rating_scale_' + scale_id).prop('hidden', !(scale_id in category['scales']));
$('#id_rating_scale_' + scale_id + '_chosen').width('100%');
}
}
function hide_all_cotations() {
// For each scale rating
var scales = JSON.parse($('#all-ratings-scales').text());
for (var scale_id in scales) {
// Hide form fields
$('#div_id_rating_scale_' + scale_id).prop('hidden', true);
}
}
function update_trek_cotations() {
var practices = JSON.parse($('#practices').text());
var practice = $('#id_practice').val();
var types = practice ? practices[practice]['types'] : {};
// Refresh cotation selectors
if (practice == "") {
hide_all_cotations();
} else {
update_cotations(practices[practice]);
}
}
|
/*
The files in this directory are part of node-ansible-test, a javascript-based library.
Copyright (C) 2016 Daniel Bush
This program is distributed under the terms of the BSD-2-Clause License.
*/
'use strict';
// Example hook.
module.exports = function () {
this.BeforeFeatures(function (features, cb) {
console.log('before features');
cb();
});
this.BeforeFeature(function (feature, cb) {
console.log('before feature');
cb();
});
this.Before(function (scenario, cb) {
console.log('before scenario');
cb();
});
this.After(function (scenario, cb) {
console.log('after scenario');
cb();
});
this.AfterFeature(function (feature, cb) {
console.log('after feature');
cb();
});
this.AfterFeatures(function (features, cb) {
console.log('after features');
cb();
});
};
|
var color_names = [
"aliceblue",
"antiquewhite",
"aqua",
"aquamarine",
"azure",
"beige",
"bisque",
"black",
"blanchedalmond",
"blue",
"blueviolet",
"brown",
"burlywood",
"cadetblue",
"chartreuse",
"chocolate",
"coral",
"cornflowerblue",
"cornsilk",
"crimson",
"cyan",
"darkblue",
"darkcyan",
"darkgoldenrod",
"darkgray",
"darkgreen",
"darkgrey",
"darkkhaki",
"darkmagenta",
"darkolivegreen",
"darkorange",
"darkorchid",
"darkred",
"darksalmon",
"darkseagreen",
"darkslateblue",
"darkslategray",
"darkslategrey",
"darkturquoise",
"darkviolet",
"deeppink",
"deepskyblue",
"dimgray",
"dimgrey",
"dodgerblue",
"firebrick",
"floralwhite",
"forestgreen",
"fuchsia",
"gainsboro",
"ghostwhite",
"gold",
"goldenrod",
"gray",
"green",
"greenyellow",
"grey",
"honeydew",
"hotpink",
"indianred",
"indigo",
"ivory",
"khaki",
"lavender",
"lavenderblush",
"lawngreen",
"lemonchiffon",
"lightblue",
"lightcoral",
"lightcyan",
"lightgoldenrodyellow",
"lightgray",
"lightgreen",
"lightgrey",
"lightpink",
"lightsalmon",
"lightseagreen",
"lightskyblue",
"lightslategray",
"lightslategrey",
"lightsteelblue",
"lightyellow",
"lime",
"limegreen",
"linen",
"magenta",
"maroon",
"mediumaquamarine",
"mediumblue",
"mediumorchid",
"mediumpurple",
"mediumseagreen",
"mediumslateblue",
"mediumspringgreen",
"mediumturquoise",
"mediumvioletred",
"midnightblue",
"mintcream",
"mistyrose",
"moccasin",
"navajowhite",
"navy",
"oldlace",
"olive",
"olivedrab",
"orange",
"orangered",
"orchid",
"palegoldenrod",
"palegreen",
"paleturquoise",
"palevioletred",
"papayawhip",
"peachpuff",
"peru",
"pink",
"plum",
"powderblue",
"purple",
"red",
"rosybrown",
"royalblue",
"saddlebrown",
"salmon",
"sandybrown",
"seagreen",
"seashell",
"sienna",
"silver",
"skyblue",
"slateblue",
"slategray",
"slategrey",
"snow",
"springgreen",
"steelblue",
"tan",
"teal",
"thistle",
"tomato",
"turquoise",
"violet",
"wheat",
"white",
"whitesmoke",
"yellow",
"yellowgreen"
];
export default {
isColor: c => color_names.indexOf(c) !== -1
};
|
var deploy = 'http://cp01-qa-lvyou-001.cp01.baidu.com:8080';
//hack的方法,整理成相对路径
var cdndomain = '../../..';
fis.config.merge({
modules : {
postprocessor : {
js : 'jswrapper,require-async',
html: 'require-async'
},
postpackager : ['autoload', 'simple']
},
settings : {
postprocessor : {
jswrapper : {
type : 'amd'
}
},
spriter: {
csssprites: {
margin: 50
}
}
},
roadmap : {
domain: {
'**.js': cdndomain,
'**.css': cdndomain,
'image': cdndomain,
'**.less': cdndomain
}
},
pack:{
'pkg/modules-combine.js': [
'/modules/**.js', '/widgets/ui/**.js'
],
'pkg/plan-detail-combine.js': [
'/widgets/plan/detail/**.js'
],
'pkg/plan-summary-combine.js': [
'/widgets/plan/summary/**.js'
]
},
deploy: {
remote: [{
receiver: deploy + '/static/receiver.php',
from: '/static',
subOnly : true,
to: '/home/lv/webroot/static',
exclude: /.*\.(?:svn|cvs|tar|rar|psd).*/
},{
receiver: deploy + '/static/receiver.php',
from: '/page',
subOnly : true,
to: '/home/lv/webroot/static/<%=config.preName%>',
exclude: /.*\.(?:svn|cvs|tar|rar|psd).*/
}]
}
});
fis.config.set('roadmap.path', [
{
reg : /^\/pkg\/(.*\.(?:css|js))$/i,
isMod:false,
release: '/static/pkg/$1'
},{
reg: /^\/lib\/(.*\.js)$/i,
//非组件化
isMod : false,
//发布到/static/js/xxx目录下
release: '/static/lib/$1'
},{
//一级同名组件,可以引用短路径,比如modules/jquery/juqery.js
//直接引用为var $ = require('jquery');
reg : /^\/modules\/([^\/]+)\/\1\.(js)$/i,
//是组件化的,会被jswrapper包装
isMod : true,
//id为文件夹名
id : '$1',
release: '/static/modules/$1/$1' + '.js'
},{
//modules目录下的其他文件
reg : /^\/modules\/(.*)\.(js)$/i,
//是组件化的,会被jswrapper包装
isMod : true,
//id是去掉modules和.js后缀中间的部分
id : '$1',
release: '/static/modules/$1' + '.js'
},{
//widgets
reg : /^\/widgets\/(.*)\.(js)$/i,
//是组件化的,会被jswrapper包装
isMod : true,
//id是去掉modules和.js后缀中间的部分
id : '$1',
release: '/static/widgets/$1' + '.js'
},{
reg:/^\/widgets\/(.*)\.(eot|svg|ttf|woff)$/i,
release: '/static/widgets/$1' + '.$2',
url: '/static/<%=config.preName%>/static/widgets/$1' + '.$2',
useDomain: false
},{
//图片
reg : /^\/widgets\/(.*\.(?:png|gif|webp))$/i,
isMod:false,
release: '/static/widgets/$1'
},{
//html
reg : /^\/widgets\/(.*\.(?:html))$/i,
isMod:false,
release: '/static/widgets/$1'
},{
reg : /^\/widgets\/(.*)\.(?:css|less)$/i,
release: '/static/widgets/$1' + '.css'
},{
//其他css文件
reg : "**.css",
//css文件会做csssprite处理
useSprite : true
}, {
//readme文件,不要发布
reg : /\/readme.md$/i,
release : false
}
]);
//将资源依赖文件map.js内联输出
fis.config.set('settings.postpackager.autoload.useInlineMap', true);
fis.config.set('modules.parser.less', 'less');
//将less文件编译为css
fis.config.set('roadmap.ext.less', 'css');
fis.config.set('modules.spriter', 'csssprites');
|
/**
* Created by Praveen on 16/12/2015.
*/
import React, { Component } from 'react';
import Tooltip from 'rc-tooltip';
import * as actionCreators from '../actions/actionCreators';
const tooltipStyles = {
height: 20,
width: 100,
textAlign: 'center'
};
export default class FilesIconBar extends Component {
constructor(props) {
super(props);
this.state = {
selectedAll: false
}
}
handleSelectAll(event) {
let {files, dispatch} = this.props;
if(!this.state.selectedAll) {
files.map(file => dispatch(actionCreators.selectFile({
name: file.name
})));
} else {
files.map(file => dispatch(actionCreators.deSelectFile({
name: file.name
})));
}
this.setState({
selectedAll: !this.state.selectedAll
});
}
static areAllFilesSelected(selectedFiles, files) {
return (files.length > 0 && files.length === selectedFiles.length);
}
render() {
let {files, selectedFiles} = this.props;
let checkBoxIconName = this.constructor.areAllFilesSelected(selectedFiles, files) ? 'check_box' : 'check_box_outline_blank';
return(
<div className="row">
<div className="large-12 small-12 medium-12 columns ax-icon-bar-adjust-height">
<div className="icon-bar three-up">
<Tooltip
placement="bottom"
mouseEnterDelay={0}
mouseLeaveDelay={0.1}
overlay={<div style={tooltipStyles}><strong>Select All</strong></div>}
transitionName={'rc-tooltip-zoom'}>
<a className="item"
role="button"
onClick={this.handleSelectAll.bind(this)}>
<i className="material-icons">{checkBoxIconName}</i>
</a>
</Tooltip>
<Tooltip
placement="bottom"
mouseEnterDelay={0}
mouseLeaveDelay={0.1}
overlay={<div style={tooltipStyles}><strong>Export</strong></div>}
transitionName={'rc-tooltip-zoom'}>
<a className="item"
role="button">
<i className="material-icons">launch</i>
</a>
</Tooltip>
<Tooltip
placement="bottom"
mouseEnterDelay={0}
mouseLeaveDelay={0.1}
overlay={<div style={tooltipStyles}><strong>Analysis</strong></div>}
transitionName={'rc-tooltip-zoom'}>
<a className="item"
role="button">
<i className="material-icons">equalizer</i>
</a>
</Tooltip>
</div>
</div>
</div>
);
}
}
|
app.updateRoute = function(force_update) {
var searchable_uid = m.route.param('searchable_uid')
var field_uid = m.route.param('field_uid')
var query = m.route.param('query')
if (m.route() != '/') {
if (app.switchToSearchable(searchable_uid) && field_uid) {
app.changeToField(field_uid)
}
if (query) {
document.getElementById('search').value = query
app.search_input(query)
app.submitSearch()
}
}
}
app.getURL = function() {
var url = "/search/"
+ app.currentSearchable().uid + "/field/"
+ app.selected_field()
var query = app.search_input()
if (query) {
url = url + "/query/" + query
}
return url
}
|
BoxParser.createSampleEntryCtor(BoxParser.SAMPLE_ENTRY_TYPE_METADATA, "wvtt", function(stream) {
this.parseHeader(stream);
this.parseFooter(stream);
});
|
import mux from '@expo/mux';
import Constants from 'expo-constants';
import getInstallationIdAsync from 'expo/build/environment/getInstallationIdAsync';
import React from 'react';
import { NativeModules, StyleSheet, Text, View } from 'react-native';
import { v4 as uuidV4 } from 'uuid';
const logUrl = Constants.manifest.logUrl;
const sessionId = uuidV4();
const { ExpoNativeModuleIntrospection } = NativeModules;
if (!ExpoNativeModuleIntrospection) {
console.warn(
'Looks like there is no `ExpoNativeModuleIntrospection` module. Please make sure you are running this app on iOS.'
);
}
export default class App extends React.Component {
async componentDidMount() {
const moduleSpecs = await _getExpoModuleSpecsAsync();
const code = `module.exports = ${JSON.stringify(moduleSpecs)};`;
const message = `
------------------------------COPY THE TEXT BELOW------------------------------
${code}
------------------------------END OF TEXT TO COPY------------------------------
`;
await _sendRawLogAsync(message, logUrl);
}
render() {
return (
<View style={styles.container}>
<Text>
Check your console and copy the relevant logs into jest-expo/src/expoModules.js and format
it nicely with prettier
</Text>
</View>
);
}
}
/**
* Sends a log message without truncating it.
*/
async function _sendRawLogAsync(message, logUrl) {
const headers = {
'Content-Type': 'application/json',
Connection: 'keep-alive',
'Proxy-Connection': 'keep-alive',
Accept: 'application/json',
'Device-Id': await getInstallationIdAsync(),
'Session-Id': sessionId,
};
if (Constants.deviceName) {
headers['Device-Name'] = Constants.deviceName;
}
await fetch(logUrl, {
method: 'POST',
headers,
body: JSON.stringify([
{
count: 0,
level: 'info',
body: [message],
includesStack: false,
},
]),
});
}
async function _getExpoModuleSpecsAsync() {
const whitelist = /^(Expo(?:nent)?|AIR|CTK|Lottie|Reanimated|RN|NativeUnimoduleProxy)(?![a-z])/;
const moduleNames = await ExpoNativeModuleIntrospection.getNativeModuleNamesAsync();
const expoModuleNames = moduleNames.filter(moduleName => whitelist.test(moduleName)).sort();
const specPromises = {};
for (const moduleName of expoModuleNames) {
specPromises[moduleName] = _getModuleSpecAsync(moduleName, NativeModules[moduleName]);
}
return await mux(specPromises);
}
async function _getModuleSpecAsync(moduleName, module) {
if (!module) {
return {};
}
const moduleDescription = await ExpoNativeModuleIntrospection.introspectNativeModuleAsync(
moduleName
);
const spec = _addFunctionTypes(_mockify(module), moduleDescription.methods);
if (moduleName === 'NativeUnimoduleProxy') {
spec.exportedMethods.mock = _sortObject(module.exportedMethods);
spec.viewManagersNames.mock = module.viewManagersNames.sort();
spec.modulesConstants.type = 'mock';
spec.modulesConstants.mockDefinition = Object.keys(module.modulesConstants)
.sort()
.reduce(
(spec, moduleName) => ({
...spec,
[moduleName]: module.modulesConstants[moduleName]
? _mockify(module.modulesConstants[moduleName])
: undefined,
}),
{}
);
}
return spec;
}
const _mockify = (obj, context) =>
Object.keys(obj)
.sort()
.reduce((spec, key) => {
const value = obj[key];
const type = Array.isArray(value) ? 'array' : typeof value;
const mock = type !== 'function' ? _mockifyValue(value, { context, key }) : undefined;
return { ...spec, [key]: { type, mock } };
}, {});
const _addFunctionTypes = (spec, methods) =>
Object.keys(methods)
.sort()
.reduce(
(spec, methodName) => ({
...spec,
[methodName]: {
...spec[methodName],
functionType: methods[methodName].type,
},
}),
spec
);
const _sortObject = obj =>
Object.keys(obj)
.sort()
.reduce(
(acc, el) => ({
...acc,
[el]: obj[el],
}),
{}
);
function _mockifyValue(value) {
// Include only values that generally don't contain sensitive data
return value === null || typeof value === 'boolean' || typeof value === 'number'
? value
: undefined;
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
padding: 20,
},
});
|
var cdb = require('cartodb.js');
var template = require('./input-ramp-content-view.tpl');
var RampListView = require('./input-ramp-list-view');
module.exports = cdb.core.View.extend({
events: {
'click .js-back': '_onClickBack',
'click .js-quantification': '_onClickQuantification',
'click .js-bins': '_onClickBins'
},
initialize: function (opts) {
if (!opts.bins) throw new Error('bins is required');
if (!opts.attribute) throw new Error('attribute is required');
if (!opts.quantification) throw new Error('quantification is required');
this._bins = opts.bins;
this._attribute = opts.attribute;
this._quantification = opts.quantification;
},
render: function () {
this.clearSubViews();
this.$el.empty();
var view = new RampListView({
bins: this._bins,
showSearch: false
});
this.$el.append(template({
bins: this._bins,
attribute: this._attribute,
quantification: this._quantification
}));
view.on('selectItem', function (item) {
this.trigger('selectItem', item);
}, this);
this.$('.js-content').append(view.render().$el);
return this;
},
_onClickBack: function (e) {
this.killEvent(e);
this.trigger('back', this);
},
_onClickQuantification: function (e) {
this.killEvent(e);
this.trigger('selectQuantification', this);
},
_onClickBins: function (e) {
this.killEvent(e);
this.trigger('selectBins', this);
}
});
|
import { _app } from '/imports/lib/core.js';
import { Meteor } from 'meteor/meteor';
import { Template } from 'meteor/templating';
import './logout.js';
import './login.jade';
Template.login.onRendered(function() {
window.IS_RENDERED = true;
});
Template.login.helpers({
unlist() {
return _app.unlist.get();
},
secured() {
return _app.secured.get();
},
serviceConfiguration() {
return _app.serviceConfiguration.get();
}
});
Template.login.events({
'click [data-login-meteor]'(e) {
e.preventDefault();
Meteor.loginWithMeteorDeveloperAccount();
},
'click [data-login-github]'(e) {
e.preventDefault();
Meteor.loginWithGithub();
},
'click [data-login-twitter]'(e) {
e.preventDefault();
Meteor.loginWithTwitter({});
},
'click [data-login-facebook]'(e) {
e.preventDefault();
Meteor.loginWithFacebook({});
},
'click [data-change-unlist]'(e) {
e.preventDefault();
_app.unlist.set(!_app.unlist.get());
return false;
},
'click [data-change-secured]'(e) {
e.preventDefault();
_app.secured.set(!_app.secured.get());
return false;
}
});
|
'use strict';
var http = require('http');
var path = require('path');
var fs = require('fs');
var mime = require('mime');
function send404 (response) {
response.writeHead(404, {'Content-type' : 'text/plain'});
response.write('Error 404: Resource not found');
response.end();
}
function sendPage (response, filePath, fileContents) {
response.writeHead(200, { 'Content-type': mime.lookup(path.basename(filePath)) });
response.end(fileContents);
}
function serverWorking (response, absPath) {
fs.exists(absPath, function (exists) {
if (exists) {
fs.readFile(absPath, function (e, data) {
if (e) send404(response);
else sendPage(response, absPath, data);
});
} else send404(response);
});
}
var server = http.createServer(function (request, response) {
var filePath;
if (request.url === '/') filePath = 'index.html';
else filePath = request.url;
serverWorking(response, './' + filePath);
});
server.listen(process.env.PORT || 80);
console.log('Please go to http://127.0.0.1');
|
angular.module('acmplugin').controller('InstanceCtrl', ['$scope', '$routeParams', '$location', 'camundaService', function($scope, $routeParams, $location, camundaService) {
'use strict';
// retrieve all case instances.
camundaService.caseInstances().then(function(data) {
$scope.caseInstances = data;
});
// retrieve all case instances.
camundaService.processInstances().then(function(data) {
$scope.processInstances = data;
});
// flag for active instances only
$scope.activeVersionsOnly = true;
// flag for active instances only
$scope.activeVersionsOnly2 = true;
// retrieve a instance by instanceId
var loadCaseInstance = function(instanceId) {
camundaService.caseInstance(instanceId).then(function(instance) {
// load all versions of the same key
$scope.selectedInstance = instance;
// variables
camundaService.caseIntanceVariables($scope.selectedInstance.id).then(function(variables) {
var data = [];
for (var key in variables) {
if (variables.hasOwnProperty(key)) {
data.push({
name : key,
type: variables[key].type,
value: variables[key].value });
}
}
$scope.caseInstanceVariables = data;
});
// executions
camundaService.caseExecutions($scope.selectedInstance.id).then(function(executions) {
$scope.caseInstanceExecutions = executions;
});
// tasks
camundaService.tasks($scope.selectedInstance.id).then(function(tasks) {
$scope.tasks = tasks;
});
});
}
// only load if case definition id is selected.
if ($routeParams.instanceId) {
// starts execution of a task
$scope.startExecution = function(caseExecutionId) {
camundaService.startExecution(caseExecutionId).then(function(result) {
$scope.ExecutionStartResult = result;
loadCaseInstance($routeParams.instanceId);
});
};
// completes execution of a task
$scope.completeExecution = function(caseExecutionId) {
camundaService.completeExecution(caseExecutionId).then(function(result) {
loadCaseInstance($routeParams.instanceId);
});
};
// opens human task form
$scope.openTaskForm = function(task) {
// console.log(task);
$location.path('/task/' + task.id);
};
loadCaseInstance($routeParams.instanceId);
} else {
$scope.selectedInstance = null;
}
}]);
|
var fs = require("fs");
var contents = fs.readFileSync("./dist/worker.js");
var out = "module.exports={file:" + JSON.stringify(contents.toString()) + "}";
fs.writeFileSync("./dist/worker.js", out);
|
import React from 'react'
import { connect } from 'cerebral-view-react'
import NewTodoForm from '../NewTodo'
import TodosList from '../List'
import TodosFooter from '../Footer'
import visibleTodosRefs from '../../computed/visibleTodosRefs'
export default connect({
todos: 'app.todos',
isSaving: 'app.isSaving',
visibleTodosRefs: visibleTodosRefs()
},
function App (props) {
return (
<div id='todoapp-wrapper'>
<section className='todoapp'>
<header className='header'>
<h1>todos</h1>
<NewTodoForm />
</header>
{props.visibleTodosRefs.length ? <TodosList /> : null}
{Object.keys(props.todos).length ? <TodosFooter /> : null}
</section>
<footer className='info'>
<p>
Double-click to edit a todo
</p>
</footer>
</div>
)
}
)
|
var eventCenter = require('../eventCenter');
var postgres = require('../postgres');
function prepareQueryValues(resultSet) {
//
// Prepare parametrized query
//
var params = '';
var values = [];
var count = 1;
resultSet.objects.forEach(function(object) {
// Construct params string
params += '($'+(count++)+
"::timestamp AT TIME ZONE 'UTC', $"+(count++)+
'::float8, $'+(count++)+
'::int4, $'+(count++)+
'::int4, $'+(count++)+
'::int4, $'+(count++)+
'::int4, $'+(count++)+
'::int8, $'+(count++)+
'::bool, $'+(count++)+
"::timestamp AT TIME ZONE 'UTC', $"+(count++)+
'::int2, $'+(count++)+
'::bool, $'+(count++)+
'::varchar, $'+(count++)+
'::varchar, $'+(count++)+
'::int4, $'+(count++)+
'::int4, $'+(count++)+
'::int4, $'+(count++)+
'::int4, $'+(count++)+
'::bool),';
// Add object's values to array
values.push(object.generatedAt,
object.price,
object.volRemaining,
object.volEntered,
object.minVolume,
object.range,
object.orderID,
object.bid,
object.issueDate,
object.duration,
object.isSuspicious,
null,
object.ipHash,
object.regionID,
object.typeID,
object.stationID,
object.solarSystemID,
true);
});
// Cut last comma
params = params.slice(0, -1);
return {
params: params,
values: values
};
}
function composeQuery(objects) {
// Concatenate upsert query
var query = 'INSERT INTO market_data_orders AS orders (generated_at, ' +
'price, ' +
'volume_remaining, ' +
'volume_entered, ' +
'minimum_volume, ' +
'order_range, ' +
'id, ' +
'is_bid, ' +
'issue_date, ' +
'duration, ' +
'is_suspicious, ' +
'message_key, ' +
'uploader_ip_hash, ' +
'mapregion_id, ' +
'invtype_id, ' +
'stastation_id, ' +
'mapsolarsystem_id, ' +
'is_active) ' +
'VALUES ' + objects.params + ' ' +
'ON CONFLICT (id) DO UPDATE SET ' +
'price = excluded.price, ' +
'volume_remaining = excluded.volume_remaining, ' +
'generated_at = excluded.generated_at, ' +
'issue_date = excluded.issue_date, ' +
'is_suspicious = excluded.is_suspicious, ' +
'uploader_ip_hash = excluded.uploader_ip_hash, ' +
'is_active = \'t\' ' +
'WHERE orders.id = excluded.id AND orders.generated_at < excluded.generated_at;';
return query;
}
function executeQuery(resultSet, callback) {
// Filter orders from citadels
resultSet.objects = resultSet.objects.filter(function(order){
return order.stationID < 1000000000000;
});
// Prepare parametrized format
var objects = prepareQueryValues(resultSet);
// Compose query
var query = composeQuery(objects);
// Get connection from pool
postgres(function(err, pgClient, done) {
if (err) {
// Return connection to pool
done();
err.module = 'pgConnect';
// Handle errors
return callback(err, null);
} else {
// Execute query
pgClient.query(query, objects.values, function(err, result) {
// Return connection to pool
done();
if(err && err.code === '23503') {
console.log('SDE Outdated: '.yellow + err.detail);
} else if (err) {
err.module = 'orderStore#executeQuery';
} else {
// Fire events
eventCenter.emit('updatedOrders', {inserted: result.rowCount, updated: objects.values.length - result.rowCount});
}
// Return callback
callback(err, result);
});
}
});
}
exports = module.exports = function(resultSet, callback) {
//
// Stores orders
//
if(resultSet.objects.length === 0) {
// SKIP EMPTY MESSAGES
return callback(null, resultSet);
} else {
executeQuery(resultSet, function(err, result) {
// Handle errors
if (err) {
return callback(err, null);
} else {
return callback(null, resultSet);
}
});
}
};
|
/**
* Created by rhett on 10/27/15.
*/
'use strict';
var email = require('./email');
var noop = function () {
};
module.exports = {
sendEmails: function(){
/*
This is what the send would look like if it were to be used
*/
//email.send('test', {
// subject: 'test subject'
//}, {
// to : 'rng2ml@gmail.com',
// subject: 'test subject'
//},
//function(err, res){
// if (err) {
// throw err;
// } else {
// console.log(res);
// }
//});
console.log('Sending email...');
email.render('test', {
subject: 'test subject'
}, function(err, res){
console.log('... Email sent with:');
if (err) {
console.log('an error');
console.error(err.stack);
throw err;
} else {
console.log('no errors, ');
console.log(res);
}
});
},
init: function () {
module.exports.sendEmails();
}
};
|
/*
* Copyright (c) 2019 Renata Hodovan, Akos Kiss.
*
* Licensed under the BSD 3-Clause License
* <LICENSE.rst or https://opensource.org/licenses/BSD-3-Clause>.
* This file may not be copied, modified, or distributed except
* according to those terms.
*/
/* global fz */
$(document).ready(function () {
'use strict';
$('#stats-tab').addClass('active');
function statRowFormatter (value, data) {
var statRow = document.importNode($('#stat-card-template').prop('content').cloneNode(true), true).children[0];
$(statRow).find('.fuzzer').text(data.fuzzer);
$(statRow).find('.exec').text(data.exec);
$(statRow).find('.issues').text(data.issues);
$(statRow).find('.unique').text(data.unique);
return $(statRow)[0].outerHTML;
}
function statRowDetailFormatter (index, row) {
var mainDiv = document.createElement('div');
for (var detail of row.subconfigs) {
var statRowDetail = document.importNode($('#stat-row-template').prop('content').cloneNode(true), true).children[0];
if (detail.subconfig !== null) {
$(statRowDetail).find('.config-ref').attr('href', `/configs/${detail.subconfig}`);
}
$(statRowDetail).find('.config-ref').text(detail.subconfig === null ? 'N/A' : `${detail.subconfig}`);
$(statRowDetail).find('.sut').text(row.sut);
$(statRowDetail).find('.exec').text(detail.exec);
$(statRowDetail).find('.issues').text(detail.issues);
$(statRowDetail).find('.unique').text(detail.unique);
$(statRowDetail).appendTo($(mainDiv));
}
return mainDiv.outerHTML;
}
var bst = $('#stats-table').bootstrapTable(fz.utils.bstOptions({
columnNames: ['fuzzer', 'exec', 'issues', 'unique', 'sut'],
formatter: statRowFormatter,
detailFormatter: statRowDetailFormatter,
sortName: 'exec',
sortOrder: 'desc',
cookieIdTable: 'statTableCookie',
getRows: fz.api.getStats,
showAll: true,
})).data()['bootstrap.table'];
fz.notifications.onmessage['refresh_stats'] = function () {
bst.refresh({ silent: true });
};
});
|
// Add your requirements
var restify = require('restify');
var builder = require('botbuilder');
// Setup Restify Server
var server = restify.createServer();
server.listen(process.env.PORT || 3000, function()
{
console.log('%s listening to %s', server.name, server.url);
});
var appId = process.env.MY_APP_ID;
var appPassword = process.env.MY_APP_PASSWORD;
// Create chat bot
var connector = new builder.ChatConnector
({ appId: appId, appPassword: appPassword });
var bot = new builder.UniversalBot(connector);
const restifyBodyParser = require('restify-plugins').bodyParser;
server.use(restifyBodyParser({ mapParams: true }));
server.post('/sftest', function(req, res) {
var fs = require('fs');
fs.appendFile("sf.log", 'Body: ' + JSON.stringify(req.body) + '\r\n*********************************\r\nHEADERS: ' + JSON.stringify(req.headers) + '\r\n*********************************\r\n', function(err) {
if(err) {
res.send({err: err});
}
console.log("The file was saved!");
res.send({result:0});
});
});
server.post('/api/messages', connector.listen());
server.get('/', restify.plugins.serveStatic({ directory: __dirname, default: '/index.html'}));
// Add a global LUIS recognizer to the bot by using the endpoint URL of the LUIS app
var model = process.env.LUIS_MODEL;
//bot.recognizer(new builder.LuisRecognizer(model));
var recognizer = new builder.LuisRecognizer(model);
var intents = new builder.IntentDialog({ recognizers: [recognizer] });
intents.matches('Greet', (session, args) => {
session.send('Hi!');
})
.matches('PurchaseSomething', (session, args) => {
//sendSMSPlivo(session.message.text);
session.send("Purchase?");
})
.matches('None', (session, args) => {
//sendSMSPlivo(session.message.text);
session.send("Hrm.. I didn't understand that. Can you say it differently");
})
.onDefault((session) => {
session.send('Sorry, I did not understand \'%s\'.', session.message.text);
});
// intents.matches('Greet', [
// function (session, args, next) {
// session.send("Helllllooooo");
// next();
// },
// function (session, results) {
// if (results.response) {
// // ... save task
// session.send("Ok... '%s' task.", results.response);
// } else {
// session.send("Ok");
// }
// }]);
// intents.matches('None', [
// function (session, args, next) {
// session.send("I didnt understand");
// next();
// },
// function (session, results) {
// if (results.response) {
// // ... save task
// session.send("Ok... '%s' task.", results.response);
// } else {
// session.send("Ok");
// }
// }]);
// intents.onDefault((session) => {
// session.send('Sorry, I did not understand \'%s\'.', session.message.text);
// });
bot.dialog('/', intents);
// Create bot dialogs
// bot.dialog('/', function (session) {
// session.send("You said - yes you said: %s", session.message.text);
// });
function sendSMS(msg) {
var twilio = require('twilio');
var accountSid = process.env.TWILIO_ACCOUNT;
var authToken = process.env.TWILIO_TOKEN;
var twilio = require('twilio');
var client = new twilio(accountSid, authToken);
client.messages.create({
body: msg,
to: process.env.TWILIO_TO_NUMBER,
from: process.env.TWILIO_FROM_NUMBER,
}, function(err, message) {
console.log(message.sid);
});
}
function sendSMSPlivo() {
var plivo = require('plivo');
var p = plivo.RestAPI({
authId: process.env.PLIVO_ID,
authToken: process.env.PLIVO_TOKEN
});
var params = {
'src': process.env.PLIVO_FROM, // Sender's phone number with country code
'dst' : process.env.PLIVO_TO, // Receiver's phone Number with country code
'text' : "Hi, message from Plivo", // Your SMS Text Message - English
'url' : "http://ynet.co.il/", // The URL to which with the status of the message is sent
'method' : "GET" // The method used to call the url
};
// Prints the complete response
p.send_message(params, function (status, response) {
console.log('Status: ', status);
console.log('API Response:\n', response);
});
}
|
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* @name: S15.5.4.14_A2_T7;
* @section: 15.5.4.14;
* @assertion: String.prototype.split (separator, limit) returns an Array object into which substrings of the result of converting this object to a string have
* been stored. The substrings are determined by searching from left to right for occurrences of
* separator; these occurrences are not part of any substring in the returned array, but serve to divide up
* the string value. The value of separator may be a string of any length or it may be a RegExp object;
* @description: Call split(void 0), instance is "thisundefinedisundefinedaundefinedstringundefinedobject";
*/
var __string = "thisundefinedisundefinedaundefinedstringundefinedobject";
var __expected = ["this", "is", "a", "string", "object"];
var __split = __string.split(void 0);
//////////////////////////////////////////////////////////////////////////////
//CHECK#1
if (__split.constructor !== Array) {
$ERROR('#1: var __string = "thisundefinedisundefinedaundefinedstringundefinedobject"; var __expected = ["this", "is", "a", "string", "object"]; __split = __string.split(void 0); __split.constructor === Array. Actual: '+__split.constructor );
}
//
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//CHECK#2
if (__split.length !== __expected.length) {
$ERROR('#2: var __string = "thisundefinedisundefinedaundefinedstringundefinedobject"; var __expected = ["this", "is", "a", "string", "object"]; __split = __string.split(void 0); __split.length === __expected.length. Actual: '+__split.length );
}
//
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//CHECK#3
for ( var i = 0; i < __expected.length; i++ ) {
if (__expected[i]!==__split[i]) {
$ERROR('#3.'+i+': var __string = "thisundefinedisundefinedaundefinedstringundefinedobject"; var __expected = ["this", "is", "a", "string", "object"]; __split = __string.split(void 0); __expected['+i+']==='+__split[i]+'. Actual: '+__expected[i]);
}
}
//
//////////////////////////////////////////////////////////////////////////////
|
/*
This file is part of Ext JS 5.0.1.1255
Copyright (c) 2011-2014 Sencha Inc
Contact: http://www.sencha.com/contact
Commercial Usage
Licensees holding valid commercial licenses may use this file in accordance with the Commercial
Software License Agreement provided with the Software or, alternatively, in accordance with the
terms contained in a written agreement between you and Sencha.
If you are unsure which license is appropriate for your use, please contact the sales department
at http://www.sencha.com/contact.
Version: 5.0.1.1255 Build date: 2014-08-05 20:18:44 (2852ec9b146a917f790d13cfa9b9c2fa041fccf8)
*/
|
/*
CryptoJS v3.1
code.google.com/p/crypto-js
(c) 2009-2013 by Jeff Mott. All rights reserved.
code.google.com/p/crypto-js/wiki/License
*/
CryptoJS.pad.AnsiX923={pad:function(a,d){var b=a.sigBytes,c=4*d,c=c-b%c,b=b+c-1;a.clamp();a.words[b>>>2]|=c<<24-8*(b%4);a.sigBytes+=c},unpad:function(a){a.sigBytes-=a.words[a.sigBytes-1>>>2]&255}};
|
/**
* Copyright (c) 2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule Heap
* @typechecks
* @preventMunge
*/
"use strict";
/*
* @param {*} a
* @param {*} b
* @return {boolean}
*/
function defaultComparator(a, b) {
return a < b;
}
function Heap(items, comparator) {
this._items = items || [];
this._size = this._items.length;
this._comparator = comparator || defaultComparator;
this._heapify();
}
/*
* @return {boolean}
*/
Heap.prototype.empty=function() {
return this._size === 0;
};
/*
* @return {*}
*/
Heap.prototype.pop=function() {
if (this._size === 0){
return;
}
var elt = this._items[0];
var lastElt = this._items.pop();
this._size--;
if (this._size > 0) {
this._items[0] = lastElt;
this._sinkDown(0);
}
return elt;
};
/*
* @param {*} item
*/
Heap.prototype.push=function(item) {
this._items[this._size++] = item;
this._bubbleUp(this._size - 1);
};
/*
* @return {number}
*/
Heap.prototype.size=function() {
return this._size;
};
/*
* @return {*}
*/
Heap.prototype.peek=function() {
if (this._size === 0) {
return;
}
return this._items[0];
};
Heap.prototype._heapify=function() {
for (var index = Math.floor((this._size + 1)/ 2); index >= 0; index--) {
this._sinkDown(index);
}
};
/*
* @parent {number} index
*/
Heap.prototype._bubbleUp=function(index) {
var elt = this._items[index];
while (index > 0) {
var parentIndex = Math.floor((index + 1) / 2) - 1;
var parentElt = this._items[parentIndex];
// if parentElt < elt, stop
if (this._comparator(parentElt, elt)) {
return;
}
// swap
this._items[parentIndex] = elt;
this._items[index] = parentElt;
index = parentIndex;
}
};
/*
* @parent {number} index
*/
Heap.prototype._sinkDown=function(index) {
var elt = this._items[index];
while (true) {
var leftChildIndex = 2 * (index + 1) - 1;
var rightChildIndex = 2 * (index + 1);
var swapIndex = -1;
if (leftChildIndex < this._size) {
var leftChild = this._items[leftChildIndex];
if (this._comparator(leftChild, elt)) {
swapIndex = leftChildIndex;
}
}
if (rightChildIndex < this._size) {
var rightChild = this._items[rightChildIndex];
if (this._comparator(rightChild, elt)) {
if (swapIndex === -1 ||
this._comparator(rightChild, this._items[swapIndex])) {
swapIndex = rightChildIndex;
}
}
}
// if we don't have a swap, stop
if (swapIndex === -1) {
return;
}
this._items[index] = this._items[swapIndex];
this._items[swapIndex] = elt;
index = swapIndex;
}
};
module.exports = Heap;
|
// Copyright 2015 The Vanadium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
/**
* Support for mouse move event in mercury.
*/
var hg = require('mercury');
var extend = require('xtend');
module.exports = hg.BaseEvent(handleMouseMove);
function handleMouseMove(ev, broadcast) {
var data = this.data;
// Add absolute and relative X position to the existing data object.
broadcast(extend(data, {
x: ev.layerX,
f: ev.layerX / ev.currentTarget.scrollWidth
}));
}
|
(function(){
window.DraftModel = new JazzRecord.Model({
table: 'drafts',
columns: {
account_id: 'string',
text: 'text',
updated_at: 'string',
updated_at_unixtime: 'int'
},
// events: {
// onSave: function(){
// var now = new Date();
// this.updated_at = now.toString();
// this.updated_at_unixtime = +now;
// }
// },
// recordMethods: {},
modelMethods: {
findById: function(id){
return this.findBy('id', id);
},
countByAccountId: function(account_id){
return this.count({account_id: account_id});
}
}
});
})();
|
// Load modules
var Boom = require('boom');
var Hoek = require('hoek');
var jwt = require('jsonwebtoken');
var Joi = require('joi');
var optionsSchema = Joi.object().keys({
key: Joi.alternatives().try(Joi.binary(), Joi.func()).required(),
validateFunc: Joi.func(),
algorithms: Joi.array().items(Joi.string()),
audience: Joi.alternatives().try(Joi.string(), Joi.array().items(Joi.string())),
issuer: Joi.alternatives().try(Joi.string(), Joi.array().items(Joi.string())),
subject: Joi.string()
}).label('jwt auth strategy options');
// Declare internals
var internals = {};
function register(server, options) {
server.auth.scheme('jwt', internals.implementation);
};
internals.implementation = function (server, options) {
var validationResult = Joi.validate(options, optionsSchema);
if (validationResult.error) {
throw new Error(validationResult.error.message);
}
var settings = Hoek.clone(options);
var scheme = {
authenticate: async function (request, h) {
var req = request.raw.req;
var authorization = req.headers.authorization;
if (!authorization) {
throw Boom.unauthorized(null, 'Bearer');
}
var parts = authorization.split(/\s+/);
if (parts.length !== 2) {
throw Boom.badRequest('Bad HTTP authentication header format', 'Bearer');
}
if (parts[0].toLowerCase() !== 'bearer') {
throw Boom.unauthorized(null, 'Bearer');
}
if (parts[1].split('.').length !== 3) {
throw Boom.badRequest('Bad HTTP authentication header format', 'Bearer');
}
var token = parts[1];
var getKey = typeof settings.key === 'function' ?
settings.key :
function (req, token) { return { key: settings.key }; };
let keyResult;
try {
keyResult = await getKey(request, token);
} catch (err) {
throw Boom.boomify(err, { override: false });
}
const { key, extraInfo } = keyResult;
let decoded;
try {
decoded = jwt.verify(token, key, settings);
} catch (err) {
throw Boom.unauthorized('JSON Web Token validation failed: ' + err.message, 'Bearer');
}
if (!settings.validateFunc) {
return h.authenticated({ credentials: decoded });
}
const validateResult = await settings.validateFunc(decoded, extraInfo);
const { isValid, credentials } = validateResult;
if (!isValid) {
throw Boom.unauthorized('Invalid token', 'Bearer');
}
if (!credentials || typeof credentials !== 'object') {
throw Boom.badImplementation('Bad credentials object received for jwt auth validation');
}
// Authenticated
return h.authenticated({ credentials });
}
};
return scheme;
};
module.exports = {
pkg: require('../package.json'),
register,
}
|
'use strict'
global.config = require('./config');
var dx_package = require('./package');
exports.printInfo = function() {
console.log("dx-js version : " + dx_package.version);
}
exports.createDiscoveryServer = function(port) {
return require('./lib/net/discovery-server').create(port);
}
exports.createDiscoveryClient = function(port) {
return require('./lib/net/discovery-client').create(port);
}
exports.createPacketServer = function(port) {
return require('./lib/net/packet-server').create(port);
}
exports.createPacketClient = function(port) {
return require('./lib/net/packet-client').create(port);
}
exports.Header = require('./lib/packet/header');
exports.Packet = require('./lib/packet/packet');
exports.DataType = require('./lib/packet/data-type');
exports.Code = require('./lib/packet/code');
exports.Type = require('./lib/packet/type');
|
var webpack = require('webpack');
var path = require('path');
var ManifestPlugin = require('webpack-manifest-plugin');
var ChunkManifestPlugin = require('chunk-manifest-webpack-plugin');
var __DEV__ = process.env.NODE_ENV !== 'production';
module.exports = {
entry: {
bundle: './client'
},
devtool: __DEV__ ? 'inline-source-map' : null,
node: {
// Mock Node.js modules that Babel require()s but that we don't
// particularly care about.
fs: 'empty',
module: 'empty',
net: 'empty'
},
output: {
filename: __DEV__ ? 'bundle.js' : 'bundle-[hash].js',
chunkFilename: __DEV__ ?
'bundle-[name].js' :
'bundle-[name]-[chunkhash].js',
path: path.join(__dirname, '/public/js'),
publicPath: '/js'
},
module: {
loaders: [
{
test: /\.jsx?$/,
include: [
path.join(__dirname, 'client/'),
path.join(__dirname, 'common/')
],
loaders: __DEV__ ? ['react-hot', 'babel'] : [ 'babel' ]
},
{
test: /\.json$/,
loaders: [
'json-loader'
]
}
]
},
externals: {
codemirror: 'CodeMirror',
'loop-protect': 'loopProtect'
},
plugins: [
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify(__DEV__ ? 'development' : 'production')
},
__DEVTOOLS__: !__DEV__
}),
// Use browser version of visionmedia-debug
new webpack.NormalModuleReplacementPlugin(
/debug\/node/,
'debug/browser'
),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurenceOrderPlugin(true)
]
};
if (!__DEV__) {
module.exports.plugins.push(
new ManifestPlugin({ fileName: 'react-manifest.json' }),
new ChunkManifestPlugin({
filename: 'chunk-manifest.json',
manifestVariable: 'webpackManifest'
})
);
} else {
module.exports.plugins.push(
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
);
}
|
/*
* zindexCenter
* author: ronglin
* create date: 2012.4.9
* description: a manager singleton register to top scope for z-index css property
*/
(function ($, undefined) {
var isWindowExist = function (win) {
var exist = true;
try {
var o = win.document.body.childNodes; // try to access
} catch (ex) {
exist = false;
}
return exist;
};
var zindexCenter = function (config) {
$.extend(this, config);
this.initialize();
};
zindexCenter.prototype = {
mapping: null, winUnload: null,
constructor: zindexCenter,
initialize: function () {
var self = this;
this.mapping = [];
this.winUnload = function () {
var win = this;
setTimeout(function () {
self.refresh(win);
}, 32);
};
},
refresh: function (win) {
var len = this.mapping.length, item, equal, exist;
for (var i = len - 1; i > -1; i--) {
item = this.mapping[i];
equal = (item.win === win);
exist = isWindowExist(item.win);
if (exist && equal) {
$(item.win).unbind('unload', this.winUnload);
}
if (!exist || equal) {
this.mapping.splice(i, 1);
}
}
},
refreshAll: function () {
var len = this.mapping.length, item;
for (var i = len - 1; i > -1; i--) {
item = this.mapping[i];
if (isWindowExist(item.win)) {
$(item.win).unbind('unload', this.winUnload);
}
}
this.mapping = [];
},
queryWinZMax: function (win) {
var zmax, cur;
$(win.document.body).find('*').each(function () {
cur = parseInt($(this).css('z-index'));
zmax = cur > (zmax || 0) ? cur : zmax;
});
return zmax || 0;
},
getDomOwner: function (el) {
// scopes
var o = $(el), dom = o.get(0), doc = dom.ownerDocument;
var win = doc.parentWindow || doc.defaultView; // ie and opera has 'parentWindow' others 'defaultView'
// ret
return win;
},
getMax: function (win, set) {
// if newest
set = set || {};
if (set.newest === true) {
return this.queryWinZMax(win);
}
// query cache
var ret = undefined;
$.each(this.mapping, function () {
if (this.win === win) {
ret = this.ret;
}
});
if (ret !== undefined) {
return ret;
}
// query max z-index
ret = this.queryWinZMax(win);
// some browser plugin use a z-index:2147483647(max integer number of 32bit platform).
// when this function increase z-index base on this number, it may cause number overflow issue.
var threshold = 2147483647 - 10000; // leave 10000 for our component used.
ret = (ret >= threshold) ? threshold : ret;
// store cache
this.mapping.push({
win: win,
ret: ret
});
// bind refresh
if (win !== top) {// the singleton is register in top window, so top window don't need to do self refreshing.
$(win).bind('unload', this.winUnload);
}
// ret
return ret;
},
restoreOld: function (el) {
var o = $(el), zold = o.attr('zold');
if (!zold) {
return o;
} else {
return o.css('z-index', (parseInt(zold) || 0)).removeAttr('zold');
}
},
setTop: function (el, set) {
// get
var win = this.getDomOwner(el);
var max = this.getMax(win, set);
// apply
this.restoreOld(el);
var o = $(el), old = parseInt(o.css('z-index')) || 0;
return o.attr('zold', old).css('z-index', old + max);
},
remove: function () {
this.refreshAll();
this.mapping = undefined;
this.winUnload = undefined;
}
};
// register
var singleton = top.zindexCenter;
if (!singleton) {
singleton = top.zindexCenter = new zindexCenter();
$(top).bind('unload', function () { singleton.remove(); });
}
if (window.yardi) {
yardi.zindexCenter = singleton;
yardi.zTop = function (el) { return singleton.setTop(el); }
yardi.zOld = function (el) { return singleton.restoreOld(el); }
}
})(jQuery);
|
define(
//begin v1.x content
{
"eraAbbr": [
"före R.K.",
"R.K."
]
}
//end v1.x content
);
|
define(
'bolt.loader.executor.Evaller',
[
],
function () {
var execute = function (data, onsuccess, onfailure) {
var define = Function('return this;')().define;
try {
eval(data);
} catch(e) {
onfailure(e);
return;
}
onsuccess();
};
return {
execute: execute
};
}
);
|
var searchData=
[
['gradient',['gradient',['../class_positional_data.html#a2aa73f7333432a8b32d2036f4c940ff3',1,'PositionalData']]]
];
|
module.exports = function configure (utils) {
function parse (row, callback) {
var keys = [ 'Timestamp', 'Raw-Values',
'Raw-Upload ID', 'Index', 'Raw-Device Type' ];
var fields = utils.pluck(row, keys);
var details = utils.details(fields['Raw-Values'] || '');
var device = fields['Raw-Device Type'];
var index = parseInt(fields.Index) + 1;
var key = [ fields['Raw-Upload ID'], index, device ].join(' ');
var data = {
value: details.BOLUS_ESTIMATE
, smbg: details.BG_INPUT
, carbs: details.CARB_INPUT
, carb_units: details.CARB_UNITS
, carb_ratio: details.CARB_RATIO
, sensitivity: details.INSULIN_SENSITIVITY
, recommended: details.BOLUS_ESTIMATE
, correction: details.CORRECTION_ESTIMATE
, food: details.FOOD_ESTIMATE
, joinKey: utils.hash(key)
, type: 'wizard'
, deviceTime: utils.reformatISO(fields.Timestamp)
};
return callback(null, data);
}
function isValid (data) {
return (
!isNaN(data.value)
&& data.type == "wizard"
);
}
var pattern = /BolusWizard/g;
var stream = utils.pipeline(utils.split( ), utils.map(parse), utils.validator(isValid));
var parser = { pattern: pattern, stream: stream, parse: parse };
return parser;
}
|
(function () {
'use strict';
var expect;
if(typeof window === 'object' && window.expect) {
expect = window.expect;
}
else {
expect = require('chai').expect;
}
describe('Protolib.destroy', function () {
var lib;
before(function () {
if(typeof window !== 'object') {
lib = (require('../')).get('_');
}
else {
lib = window.protolib;
}
});
it('It should remove the handle from Object.prototype and free the ProtoLib instance for garbage collection', function () {
var ProtoLib = typeof window === 'object' && window.ProtoLib ? window.ProtoLib : require('../');
var lib2 = ProtoLib.get('_');
expect(lib2).to.equal(lib);
expect(ProtoLib.destroy('_')).to.equal(ProtoLib);
expect((5)._).to.be.an('undefined');
expect('string'._).to.be.an('undefined');
var lib3 = ProtoLib.get('_');
expect(lib3).to.not.equal(lib);
expect(lib3).to.not.equal(lib2);
expect((5)._).to.be.an('object');
expect('string'._).to.be.an('object');
expect((5)._.choose).to.be.a('function');
expect('string'._.reverse).to.be.a('function');
});
});
}());
|
'use strict';
var response = require('xhr-response')
, statuscode = require('xhr-status')
, one = require('one-time')
, fail = require('failure');
/**
* Simple nope function that assigned to XHR requests as part of a clean-up
* operation.
*
* @api private
*/
function nope() {}
/**
* Attach various of event listeners to a given XHR request.
*
* @param {XHR} xhr A XHR request that requires listening.
* @param {EventEmitter} ee EventEmitter that receives events.
* @api public
*/
function loads(xhr, ee) {
var onreadystatechange
, onprogress
, ontimeout
, onabort
, onerror
, onload
, timer;
/**
* Error listener.
*
* @param {Event} evt Triggered error event.
* @api private
*/
onerror = xhr.onerror = one(function onerror(evt) {
var status = statuscode(xhr)
, err = fail(new Error('Network request failed'), status);
ee.emit('error', err);
ee.emit('end', err, status);
});
/**
* Fix for FireFox's odd abort handling behaviour. When you press ESC on an
* active request it triggers `error` instead of abort. The same is called
* when an HTTP request is canceled onunload.
*
* @see https://bugzilla.mozilla.org/show_bug.cgi?id=768596
* @see https://bugzilla.mozilla.org/show_bug.cgi?id=880200
* @see https://code.google.com/p/chromium/issues/detail?id=153570
* @param {Event} evt Triggerd abort event
* @api private
*/
onabort = xhr.onabort = function onabort(evt) {
onerror(evt);
};
/**
* ReadyStateChange listener.
*
* @param {Event} evt Triggered readyState change event.
* @api private
*/
onreadystatechange = xhr.onreadystatechange = function change(evt) {
var target = evt.target;
if (4 === target.readyState) return onload(evt);
};
/**
* The connection has timed out.
*
* @api private
*/
ontimeout = xhr.ontimeout = one(function timeout(evt) {
ee.emit('timeout', evt);
//
// Make sure that the request is aborted when there is a timeout. If this
// doesn't trigger an error, the next call will.
//
if (xhr.abort) xhr.abort();
onerror(evt);
});
//
// Fallback for implementations that did not ship with timer support yet.
// Microsoft's XDomainRequest was one of the first to ship with `.timeout`
// support so we all XHR implementations before that require a polyfill.
//
// @see https://bugzilla.mozilla.org/show_bug.cgi?id=525816
//
if (xhr.timeout) timer = setTimeout(ontimeout, +xhr.timeout);
/**
* IE needs have it's `onprogress` function assigned to a unique function. So,
* no touchy touchy here!
*
* @param {Event} evt Triggered progress event.
* @api private
*/
onprogress = xhr.onprogress = function progress(evt) {
var status = statuscode(xhr)
, data;
ee.emit('progress', evt, status);
if (xhr.readyState >= 3 && status.code === 200 && (data = response(xhr))) {
ee.emit('stream', data);
}
};
/**
* Handle load events an potential data events for when there was no streaming
* data.
*
* @param {Event} evt Triggered load event.
* @api private
*/
onload = xhr.onload = one(function load(evt) {
var status = statuscode(xhr)
, data = response(xhr);
if (status.code < 100 || status.code > 599) return onerror(evt);
if (data) ee.emit('stream', data);
ee.emit('end', undefined, status);
});
//
// Properly clean up the previously assigned event listeners and timers to
// prevent potential data leaks and unwanted `stream` events.
//
ee.once('end', function cleanup() {
xhr.onreadystatechange = onreadystatechange =
xhr.onprogress = onprogress =
xhr.ontimeout = ontimeout =
xhr.onerror = onerror =
xhr.onabort = onabort =
xhr.onload = onload = nope;
if (timer) clearTimeout(timer);
});
return xhr;
}
//
// Expose all the things.
//
module.exports = loads;
|
var Cull = function (renderableObjects)
{
if (this.disableCull)
{
return renderableObjects;
}
var cameraMatrix = this.matrix.matrix;
var mva = cameraMatrix[0];
var mvb = cameraMatrix[1];
var mvc = cameraMatrix[2];
var mvd = cameraMatrix[3];
/* First Invert Matrix */
var determinant = (mva * mvd) - (mvb * mvc);
if (!determinant)
{
return renderableObjects;
}
var mve = cameraMatrix[4];
var mvf = cameraMatrix[5];
var scrollX = this.scrollX;
var scrollY = this.scrollY;
var cameraW = this.width;
var cameraH = this.height;
var culledObjects = this.culledObjects;
var length = renderableObjects.length;
determinant = 1 / determinant;
culledObjects.length = 0;
for (var index = 0; index < length; ++index)
{
var object = renderableObjects[index];
if (!object.hasOwnProperty('width'))
{
culledObjects.push(object);
continue;
}
var objectW = object.width;
var objectH = object.height;
var objectX = (object.x - (scrollX * object.scrollFactorX)) - (objectW * object.originX);
var objectY = (object.y - (scrollY * object.scrollFactorY)) - (objectH * object.originY);
var tx = (objectX * mva + objectY * mvc + mve);
var ty = (objectX * mvb + objectY * mvd + mvf);
var tw = ((objectX + objectW) * mva + (objectY + objectH) * mvc + mve);
var th = ((objectX + objectW) * mvb + (objectY + objectH) * mvd + mvf);
var cullW = cameraW + objectW;
var cullH = cameraH + objectH;
if (tx > -objectW || ty > -objectH || tx < cullW || ty < cullH ||
tw > -objectW || th > -objectH || tw < cullW || th < cullH)
{
culledObjects.push(object);
}
}
return culledObjects;
};
module.exports = Cull;
|
import React, {Component} from 'react';
import Header from '../components/Header';
import {connect} from 'react-redux';
import {Link} from 'react-router';
import TemplForm from '../components/TemplForm';
import {requestTempl} from '../actions';
class TemplatePreview extends Component {
constructor(props) {
super(props);
this.editor = null;
this.renderEditor = this.renderEditor.bind(this);
}
componentDidMount() {
const {dispatch, location} = this.props;
let templId = location.query.templ;
dispatch(requestTempl(templId));
this.renderEditor(this.props.templ);
}
componentWillReceiveProps(nextProps) {
if (this.props.templ !== nextProps.templ) {
this.renderEditor(nextProps.templ);
}
}
componentWillUnmount() {
this.editor.destroy();
}
renderEditor(templ) {
this.editor = ace.edit("editor");
this.editor.setTheme("ace/theme/monokai");
this.editor.getSession().setMode("ace/mode/html");
this.editor.session.setOptions({
tabSize: 2,
useSoftTabs: true
});
this.editor.$blockScrolling = Infinity;
this.editor.setValue(templ);
this.editor.setReadOnly(true);
}
render() {
return (
<div>
<h4>{this.props.templInfo.name} <small>{this.props.templInfo.author}</small></h4>
<div id="editor"></div>
</div>
);
}
}
function mapStateToProps(state) {
const {template} = state;
return {
templ: template.templ,
templInfo: template.templInfo
};
}
export default connect(mapStateToProps)(TemplatePreview);
|
var Type = require("@kaoscript/runtime").Type;
module.exports = function() {
function foobar() {
return "foobar";
}
let x = foobar();
if(Type.isValue(x)) {
console.log(x);
}
};
|
define(['../internal/baseIsMatch', '../internal/bindCallback', '../internal/isStrictComparable', '../object/keys'], function(baseIsMatch, bindCallback, isStrictComparable, keys) {
/** Used for native method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Performs a deep comparison between `object` and `source` to determine if
* `object` contains equivalent property values. If `customizer` is provided
* it is invoked to compare values. If `customizer` returns `undefined`
* comparisons are handled by the method instead. The `customizer` is bound
* to `thisArg` and invoked with three arguments; (value, other, index|key).
*
* **Note:** This method supports comparing properties of arrays, booleans,
* `Date` objects, numbers, `Object` objects, regexes, and strings. Functions
* and DOM nodes are **not** supported. Provide a customizer function to extend
* support for comparing other values.
*
* @static
* @memberOf _
* @category Lang
* @param {Object} source The object to inspect.
* @param {Object} source The object of property values to match.
* @param {Function} [customizer] The function to customize comparing values.
* @param {*} [thisArg] The `this` binding of `customizer`.
* @returns {boolean} Returns `true` if `object` is a match, else `false`.
* @example
*
* var object = { 'user': 'fred', 'age': 40 };
*
* _.isMatch(object, { 'age': 40 });
* // => true
*
* _.isMatch(object, { 'age': 36 });
* // => false
*
* // using a customizer callback
* var object = { 'greeting': 'hello' };
* var source = { 'greeting': 'hi' };
*
* _.isMatch(object, source, function(value, other) {
* return _.every([value, other], RegExp.prototype.test, /^h(?:i|ello)$/) || undefined;
* });
* // => true
*/
function isMatch(object, source, customizer, thisArg) {
var props = keys(source),
length = props.length;
customizer = typeof customizer == 'function' && bindCallback(customizer, thisArg, 3);
if (!customizer && length == 1) {
var key = props[0],
value = source[key];
if (isStrictComparable(value)) {
return object != null && value === object[key] && hasOwnProperty.call(object, key);
}
}
var values = Array(length),
strictCompareFlags = Array(length);
while (length--) {
value = values[length] = source[props[length]];
strictCompareFlags[length] = isStrictComparable(value);
}
return baseIsMatch(object, props, values, strictCompareFlags, customizer);
}
return isMatch;
});
|
var path = require('path');
var fs = require('fs');
var configFile = path.join(__dirname, 'config.json');
console.log('Loading configuration from ' + configFile);
var config = JSON.parse(fs.readFileSync(configFile));
var LedManager = require('./ledManager.js');
var led = new LedManager(config);
// test colors
led.setColor(0, 0, 0, 0);
led.setColor(1, 0, 0, 1000);
setTimeout(function() {
led.setColor(0, 1, 0, 1000);
setTimeout(function() {
led.setColor(0, 0, 1, 1000);
setTimeout(function() {
led.setCycle([
{ state: { red: 1, green: 0, blue: 0 }, duration: 200 },
{ state: { red: 1, green: 0, blue: 0 }, duration: 1000 },
{ state: { red: 0.625, green: 0.125, blue: 0.9375 }, duration: 200 },
{ state: { red: 1, green: 0, blue: 0 }, duration: 200 },
{ state: { red: 1, green: 0, blue: 0 }, duration: 1000 },
{ state: { red: 1, green: 0.5, blue: 0 }, duration: 200 }
]);
console.log('ran last command');
}, 700);
}, 700);
}, 700);
|
var EntityBase = require('./EntityBase');
var ReportFilter = require('./ReportFilter');
var Report = EntityBase.extend({
defaults: {
/**
*The date when the report was executed
*/
ReportDate: null,
/**
* The URL to download the report
*/
DownloadURL: null,
/**
* A URL that will be pinged when the report is ready to download (works in a similar way to the hooks)
*/
CallbackURL: null,
/**
* The format of the report download { CSV }
*/
DownloadFormat: null,
/**
* Report type {TRANSACTION}
*/
ReportType: null,
/**
* The column to sort against and direction
*/
Sort: null,
/**
* Whether the report should be limited to the first 10 lines (and therefore quicker to execute)
*/
Preview: null,
Filters: null,
/**
* A list of columns/infos to show in the report
*/
Columns: null,
/**
* The result code
*/
ResultCode: null,
ResultMessage: null
},
getSubObjects: function () {
return {
'Filters': ReportFilter
}
}
});
module.exports = Report;
|
import React, { Component } from 'react'
import './style.scss'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import config from '../../config'
class Counter extends Component {
constructor(props) {
super(props)
}
render() {
const { counter } = this.props
const { increment, decrement, incrementAsync } = this.props.actions
return (
<div className="Counter">
<p>hola mundo</p>
<div className="classCSS">es una prueba css</div>
<div className="hola">hopla</div>
<div className="alert alert-primary" role="alert">
This is a primary alert—check it out!
</div>
<div className="btn-group" role="group" aria-label="Basic example">
<button type="button" className="btn btn-secondary">
Left
</button>
<button type="button" className="btn btn-secondary">
Middle
</button>
<button type="button" className="btn btn-secondary">
Right
</button>
</div>
<div className="container">
<div className="row justify-content-md-center">
<div className="col col-lg-2">1 of 3</div>
<div className="col-md-auto">Variable width content</div>
<div className="col col-lg-2">3 of 3</div>
</div>
<div className="row">
<div className="col">1 of 3</div>
<div className="col-md-auto">Variable width content</div>
<div className="col col-lg-2">3 of 3</div>
</div>
</div>
<p>Counter</p>
<button
type="button"
className="btn btn-primary"
onClick={() => increment()}>
Increment
</button>
<button onClick={() => decrement()}>Decrement</button>
<button onClick={() => incrementAsync()}>
Increment after 1 second
</button>
<hr />
<div>Clicked: {counter.num} times</div>
<img src="/img/icon.png" />
<div className="imageCss" />
</div>
)
}
}
export default connect(
state => ({
counter: state.counter
}),
dispatch => ({
actions: bindActionCreators(
{
increment: () => ({ type: 'INCREMENT' }),
decrement: () => ({ type: 'DECREMENT' }),
incrementAsync: () => ({ type: 'INCREMENT_ASYNC' })
},
dispatch
)
})
)(Counter)
|
/*
* neuron.js: Creates and manages jobs and job results.
*
* (C) 2010 Donovan Buck, Charlie Robbins, & the Contributors.
* MIT LICENSE
*
*/
var neuron = exports;
//
// Expose version
//
neuron.version = require('../package').version;
//
// ### Export Components
// Export each of the core prototypes exposed by neuron.
//
neuron.JobManager = require('./neuron/job-manager').JobManager;
neuron.Job = require('./neuron/job').Job;
neuron.Worker = require('./neuron/worker').Worker;
neuron.WorkerCache = require('./neuron/worker-cache').WorkerCache;
//
// ### function randomString (bits)
// #### @bits {int} Number of bits for the random string to have (base64)
// randomString returns a pseude-random ASCII string which contains at least the specified number of bits of entropy
// the return value is a string of length ⌈bits/6⌉ of characters from the base64 alphabet
//
neuron.randomString = function (bits) {
var chars, rand, i, ret;
chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
ret = '';
//
// in v8, Math.random() yields 32 pseudo-random bits (in spidermonkey it gives 53)
//
while (bits > 0) {
rand = Math.floor(Math.random()*0x100000000) // 32-bit integer
// base 64 means 6 bits per character, so we use the top 30 bits from rand to give 30/6=5 characters.
for (i=26; i>0 && bits>0; i-=6, bits-=6) {
ret+=chars[0x3F & rand >>> i];
}
}
return ret;
};
|
import React from "react";
const Button = () => "Button" + React;
export default Button;
|
require('..')()
.use(function plugin0() {
this.add('init:plugin0', function init0() {
throw new Error('error0')
})
})
|
angular.module('rosieApp.header', [
'ui.router',
'ui.bootstrap'
])
|
var extend = require('util')._extend;
var async = require('async');
module.exports = exports = TestDataBuilder;
/**
* Build many Model instances in one async call.
*
* Usage:
* ```js
* // The context object to hold the created models.
* // You can use `this` in mocha test instead.
* var context = {};
*
* var ref = TestDataBuilder.ref;
* new TestDataBuilder()
* .define('application', Application, {
* pushSettings: { stub: { } }
* })
* .define('device', Device, {
* appId: ref('application.id'),
* deviceType: 'android'
* })
* .define('notification', Notification)
* .buildTo(context, function(err) {
* // test models are available as
* // context.application
* // context.device
* // context.notification
* });
* ```
* @constructor
*/
function TestDataBuilder() {
this._definitions = [];
}
/**
* Define a new model instance.
* @param {string} name Name of the instance.
* `buildTo()` will save the instance created as context[name].
* @param {constructor} Model Model class/constructor.
* @param {Object.<string, Object>=} properties
* Properties to set in the object.
* Intelligent default values are supplied by the builder
* for required properties not listed.
* @return TestDataBuilder (fluent interface)
*/
TestDataBuilder.prototype.define = function(name, Model, properties) {
this._definitions.push({
name: name,
model: Model,
properties: properties
});
return this;
};
/**
* Reference the value of a property from a model instance defined before.
* @param {string} path Generally in the form '{name}.{property}', where {name}
* is the name passed to `define()` and {property} is the name of
* the property to use.
*/
TestDataBuilder.ref = function(path) {
return new Reference(path);
};
/**
* Asynchronously build all models defined via `define()` and save them in
* the supplied context object.
* @param {Object.<string, Object>} context The context to object to populate.
* @param {function(Error)} callback Callback.
*/
TestDataBuilder.prototype.buildTo = function(context, callback) {
this._context = context;
async.eachSeries(
this._definitions,
this._buildObject.bind(this),
callback);
};
TestDataBuilder.prototype._buildObject = function(definition, callback) {
var defaultValues = this._gatherDefaultPropertyValues(definition.model);
var values = extend(defaultValues, definition.properties || {});
var resolvedValues = this._resolveValues(values);
definition.model.create(resolvedValues, function(err, result) {
if (err) {
console.error(
'Cannot build object %j - %s\nDetails: %j',
definition,
err.message,
err.details);
} else {
this._context[definition.name] = result;
}
callback(err);
}.bind(this));
};
TestDataBuilder.prototype._resolveValues = function(values) {
var result = {};
for (var key in values) {
var val = values[key];
if (val instanceof Reference) {
val = values[key].resolveFromContext(this._context);
}
result[key] = val;
}
return result;
};
var valueCounter = 0;
TestDataBuilder.prototype._gatherDefaultPropertyValues = function(Model) {
var result = {};
Model.forEachProperty(function createDefaultPropertyValue(name) {
var prop = Model.definition.properties[name];
if (!prop.required) return;
switch (prop.type) {
case String:
result[name] = 'a test ' + name + ' #' + (++valueCounter);
break;
case Number:
result[name] = 1230000 + (++valueCounter);
break;
case Date:
result[name] = new Date(
2222, 12, 12, // yyyy, mm, dd
12, 12, 12, // hh, MM, ss
++valueCounter // milliseconds
);
break;
case Boolean:
// There isn't much choice here, is it?
// Let's use "false" to encourage users to be explicit when they
// require "true" to turn some flag/behaviour on
result[name] = false;
break;
// TODO: support nested structures - array, object
}
});
return result;
};
/**
* Placeholder for values that will be resolved during build.
* @param path
* @constructor
* @private
*/
function Reference(path) {
this._path = path;
}
Reference.prototype.resolveFromContext = function(context) {
var elements = this._path.split('.');
var result = elements.reduce(
function(obj, prop) {
return obj[prop];
},
context
);
return result;
};
|
import Vue from 'vue'
import BootstrapVue from 'bootstrap-vue'
Vue.use(BootstrapVue)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.