text
stringlengths 2
6.14k
|
|---|
import React from 'react';
import IconBase from '@suitejs/icon-base';
function MdBusiness(props) {
return (
<IconBase viewBox="0 0 48 48" {...props}>
<path d="M24 14h20v28H4V6h20v8zM12 38v-4H8v4h4zm0-8v-4H8v4h4zm0-8v-4H8v4h4zm0-8v-4H8v4h4zm8 24v-4h-4v4h4zm0-8v-4h-4v4h4zm0-8v-4h-4v4h4zm0-8v-4h-4v4h4zm20 24V18H24v4h4v4h-4v4h4v4h-4v4h16zm-4-16h-4v4h4v-4zm0 8h-4v4h4v-4z" />
</IconBase>
);
}
export default MdBusiness;
|
var path = require('path');
var test = require('ava');
var postcss = require('postcss');
var colorblindPlugin = require('..');
var colorNames = require('css-color-names');
var colorblind = require('color-blind');
var onecolor = require('onecolor');
var getProcessor = require('./_getProcessor');
var testPostCSS = require('./_testPostCSS');
var getFixture = require('./_getFixture');
function testColorMutation (t, color, method) {
if (!method) {
method = 'deuteranopia';
}
return testPostCSS(
t,
getFixture(color),
getFixture(colorblind[method.toLowerCase().trim()](color)),
{method: method}
);
}
['#123', '#000', '#fff', '#f06d06'].forEach(function(hex, index) {
test(
'should transform hex (' + (index + 1) + ')',
testColorMutation,
hex
);
});
[{
from: '#1234',
hex: '#123',
alpha: '0.27',
}, {
from: '#9344ABCD',
hex: '#9344AB',
alpha: '0.8',
}, {
from: '#FFFFFFFF',
hex: '#FFFFFF',
alpha: '1',
}, {
from: '#0000',
hex: '#000',
alpha: '0',
}, {
from: 'rgba(30, 50, 200, 1)',
hex: '#1E32C8',
alpha: 1,
}, {
from: 'rgba(100, 200, 0, 0)',
hex: '#64C800',
alpha: 0,
}, {
from: 'rgba(150,50,50,.4)',
hex: '#963232',
alpha: .4,
}, {
from: 'hsla(30, 50%, 50%, 1)',
hex: '#BF8040',
alpha: 1,
}, {
from: 'hsla(100, 80%, 30%, 0)',
hex: '#388A0F',
alpha: 0,
}, {
from: 'hsla(150,50%,50%,.4)',
hex: '#40BF80',
alpha: .4,
}].forEach(function(map, index) {
test(
`should transform ${map.from} (${index + 1})`,
testPostCSS,
getFixture(map.from),
getFixture(onecolor(colorblind.deuteranopia(map.hex)).alpha(map.alpha).cssa())
);
});
var solidColors = {
/* hex/rgb */
'#1E32C8': 'rgb(30, 50, 200)',
'#64C800': 'rgb(100, 200, 0)',
'#963232': 'rgb(150,50,50)',
/* hex/hsl */
'#BF8040': 'hsl(30, 50%, 50%)',
'#388A0F': 'hsl(100, 80%, 30%)',
'#40BF80': 'hsl(150,50%,50%)',
}
Object.keys(solidColors).forEach(function(key, index) {
var out = solidColors[key];
test(
`should transform ${out} (${index + 1})`,
testPostCSS,
getFixture(out),
getFixture(onecolor(colorblind.deuteranopia(key)).css())
);
});
var keywordMap = {
mediumSeaGreen: '#3CB371',
PapayaWhip: '#FFEFD5',
thistle: '#D8BFD8',
BlanchedAlmond: '#FFEBCD',
rebeccaPurple: '#639',
};
Object.keys(keywordMap).forEach(function(keyword, index) {
var hex = keywordMap[keyword];
test(
'should transform named color (' + (index + 1) + ')',
testColorMutation,
keyword
);
});
test(
'should do a simple hex deuteranopia transform',
testColorMutation,
`#FFCC00`
);
test(
'should do a simple hex achromatopsia transform',
testColorMutation,
`#D929E2`,
'achromatopsia'
);
test(
'should do a simple named color deuteranopia transform',
testPostCSS,
`.some-color { border: 3px red solid; font-size: 12px }`,
`.some-color { border: 3px ${colorblind.deuteranopia(colorNames.red)} solid; font-size: 12px }`
);
test(
'should do a multi tritanopia transform',
testPostCSS,
`.some-color { border: 3px #D929E2 solid; color: lime }`,
`.some-color { border: 3px ${colorblind.tritanopia('#D929E2')} solid; color: ${colorblind.tritanopia('lime')} }`,
{method: 'tritanopia'}
);
test(
'should work inside gradients',
testPostCSS,
`.some-color { background: linear-gradient(#000000, hsla(120, 30%, 80%, .8)) }`,
`.some-color { background: linear-gradient(#000000, ${onecolor(colorblind.deuteranopia('#bddbbd')).alpha('0.8').cssa()}) }`
);
test('should process images and yield an inlined data url', t => {
return getProcessor().process(`a{background:url(${path.join(__dirname, 'fixture.jpg')})}`).then(function(result) {
t.deepEqual(result.css.indexOf('data:image/jpeg;base64'), 17);
});
});
test(
'should handle weird capitalization of method names',
testColorMutation,
'#FFCC00',
'DEuTerAnopiA'
);
test(
'should handle weird whitespace',
testColorMutation,
'#FFCC00',
' deuteranopia '
);
test(
'should handle capitalized color names',
testColorMutation,
'ALICebLuE'
);
test('should throw an error on a bad method name', function(t) {
t.throws(function () {
return testPostCSS(t, 'h1{}', 'h1{}', {method:'bad method name'})
});
});
|
/*
* opLoadBalancer.js: lbaas APIs
* for Openstack networking
*
* (C) 2015 Hopebaytech
*
* P. Hsuan
*/
var urlJoin = require('url-join');
var _ = require('lodash');
var lbaasHealthMonitorPath = '/lb/health_monitors';
// Declaring variables for helper functions defined later
var _convertcreateToWireFormat;
/***
Health monitor list (GET)
***/
exports.getHealthMonitors = function (options, callback) {
var self = this;
if (typeof options === 'function') {
callback = options;
options = {};
}
var getlbaasOpts = {
path: lbaasHealthMonitorPath,
};
this._request(getlbaasOpts, function (err, body) {
if (err) {
return callback(err);
}
else if (!body || !body.health_monitors || !(body.health_monitors instanceof Array)) {
return new Error('Malformed API Response');
}
return callback(err, body.health_monitors.map(function (lbaasvip) {
return new self.models.HealthMonitor(self, lbaasvip);
}));
});
};
/**
show Health Monitor
*/
exports.getHealthMonitor = function (option, callback) {
var self = this,
monitorID = option instanceof this.models.HealthMonitor ? option.id : option;
self.emit('log::trace', 'Getting details for lbaas health monitor', monitorID);
this._request({
path: urlJoin(lbaasHealthMonitorPath, monitorID),
method: 'GET'
}, function (err, body) {
if (err) {
return callback(err);
}
if (!body ||!body.health_monitor) {
return new Error('Malformed API Response');
}
callback(err, new self.models.HealthMonitor(self, body.health_monitor));
});
};
/*
create Health monitor
{
"health_monitor":{
"admin_state_up": true,
"delay": "1",
"expected_codes": "200,201,202",
"http_method": "GET",
"max_retries": 5,
"pool_id": "74aa2010-a59f-4d35-a436-60a6da882819",
"timeout": 1,
"type": "HTTP",
"url_path": "/index.html"
}
}
*/
exports.createHealthMonitor = function (options, callback) {
var self = this,
monitor = typeof options === 'object' ? options : {};
var monitor_create = _convertcreateToWireFormat(monitor);
var creatmonitorOpts = {
method: 'POST',
path: lbaasHealthMonitorPath,
body: { 'health_monitor' : monitor_create}
};
self.emit('log::trace', 'Creating Health Monitor', monitor);
this._request(creatmonitorOpts, function (err,body) {
return err
? callback(err)
: callback(err, new self.models.HealthMonitor(self, body.health_monitor));
});
};
/*
update Health monitor
*/
exports.updateHealthMonitor = function (options, callback) {
var self = this,
monitor = typeof options === 'object' ? options : {};
var monitor_update = _.pick(monitor, ['delay', 'timeout', 'max_retries', 'http_method', 'url_path', 'expected_codes', 'admin_state_up']);
var updateMonitorOpts = {
method: 'PUT',
path: urlJoin(lbaasHealthMonitorPath, monitor.id),
contentType: 'application/json',
body: { 'health_monitor' : monitor_update}
};
self.emit('log::trace', 'update health monitor', monitor);
this._request(updateMonitorOpts, function (err,body) {
return err
? callback(err)
: callback(err, new self.models.HealthMonitor(self, body.health_monitor));
});
};
/*
Delete Health monitor
*/
exports.destroyHealthMonitor = function (options, callback) {
var self = this,
monitorID = options instanceof this.models.HealthMonitor ? options.id : options;
console.log(urlJoin(lbaasHealthMonitorPath, monitorID));
self.emit('log::trace', 'Deleting lbaas health monitor', monitorID);
this._request({
path: urlJoin(lbaasHealthMonitorPath, monitorID),
contentType: 'application/json',
method: 'DELETE'
}, function (err) {
if (err) {
return callback(err);
}
callback(err, monitorID);
});
};
/*
convert create to wire format
*/
_convertcreateToWireFormat = function (details){
var wireFormat = {};
wireFormat.type = details.type || null;
wireFormat.delay = details.delay || null;
wireFormat.timeout = details.timeout || null;
wireFormat.max_retries = details.max_retries || null;
if(wireFormat.type === 'HTTP' || wireFormat.type === 'HTTPS')
{
wireFormat.http_method = details.http_method || null;
wireFormat.url_path = details.url_path || null;
wireFormat.expected_codes = details.expected_codes || null;
}
return wireFormat;
};
|
let deserialize = require('./src/deserialize');
let serialize = require('./src/serialize');
let prettyHrtime = require('pretty-hrtime');
let Instruction = require('./src/Instruction');
let start = process.hrtime(), data;
let tree = [
new Instruction('test', { a: 1, b: 2, c: 3 })
];
let sMethods = {
'test': ({ a, b, c }) => [a, b, c]
};
let dsMethods = {
'test': ([a, b, c]) => ({ a, b, c })
};
for (let i = 0; i < 10000; i++) {
data = serialize(
tree, sMethods
);
}
let end = process.hrtime(start);
let stime = prettyHrtime(end, {precise:true});
setTimeout(() => console.log('data is', data));
setTimeout(() => console.log(`serialization 10000x took ${stime}`));
let result;
start = process.hrtime();
for(let i = 0; i < 10000; i++) {
result = deserialize(data, dsMethods);
}
end = process.hrtime(start);
let dtime = prettyHrtime(end, {precise:true});
setTimeout(() => console.log('result is', result));
setTimeout(() => console.log(`deserialization 10000x took ${dtime}`));
|
const { exitChrome } = require('./chrome-launcher')
async function exit () {
await exitChrome()
process.exit(0)
}
async function exitWithError () {
await exitChrome()
process.exit(1)
}
module.exports = {
exit,
exitWithError
}
|
(bbn_resolve) => {
((bbn) => {
let script = document.createElement('script');
script.innerHTML = `<div :class="componentClass">
<div class="bbn-hidden" v-if="$slots.default" ref="slot">
<slot></slot>
</div>
<div :class="getComponentName() + '-content'">
<div v-for="(li, idx) in filteredData"
v-if="!pageable || ((idx >= start) && (idx < start + currentLimit))"
:key="li.key"
:class="['bbn-w-25', 'bbn-mobile-w-50', getComponentName() + '-items']">
<component v-if="currentComponent"
:is="currentComponent"
v-bind="componentOptions"
:source="li.data"
:index="li.index"
@remove="remove(idx)"
:key="li.key">
</component>
<component v-else
:is="li.data && li.data.url && !li.data[children] ? 'a' : 'span'"
@click.prevent="() => {}"
class="bbn-block bbn-padded"
:title="li.data[sourceText]"
:href="li.data && li.data.url ? li.data.url : null"
:key="li.key">
<span class="bbn-top-left"
v-if="selection || (mode === 'options')">
<i v-if="li.data.selected"
class="nf nf-fa-check"></i>
</span>
<img v-if="li.data.image"
:src="li.data.image"
class="bbn-bottom-space">
<p class="bbn-large"
v-html="li.data[sourceText]"/>
<p v-if="li.data.price"
:class="componentClass + '-price'"
v-html="li.data.price"/>
<p v-if="li.data.desc"
:class="componentClass + '-desc'"
v-html="li.data.desc"/>
</component>
</div>
</div>
<div class="bbn-w-100 bbn-c"
v-if="pageable && (numPages > 1)">
<div class="bbn-iblock">
<bbn-pager :element="_self"
:extra-controls="false"
:numeric-selector="false"
:buttons="false"/>
</div>
</div>
</div>
`;
script.setAttribute('id', 'bbn-tpl-component-block-list');
script.setAttribute('type', 'text/x-template');document.body.insertAdjacentElement('beforeend', script);
let css = document.createElement('link');
css.setAttribute('rel', 'stylesheet');
css.setAttribute('href', bbn.vue.libURL + 'dist/js/components/block-list/block-list.css');
document.head.insertAdjacentElement('beforeend', css);
/**
* @file bbn-combo component
* @description The easy-to-implement bbn-combo component allows you to choose a single value from a user-supplied list or to write new.
* @copyright BBN Solutions
* @author BBN Solutions
* @created 10/02/2017.
*/
(function(bbn){
"use strict";
Vue.component('bbn-block-list', {
/**
* @mixin bbn.vue.basicComponent
* @mixin bbn.vue.listComponent
* @mixin bbn.vue.componentInsideComponent
*/
mixins: [
bbn.vue.basicComponent,
bbn.vue.listComponent,
bbn.vue.componentInsideComponent
],
mounted(){
this.ready = true;
}
});
})(bbn);
if (bbn_resolve) {bbn_resolve("ok");}
})(bbn);
}
|
var utils = {}
var config = require('./configuration');
var models = require('./models');
var User = models.User;
var Email = models.Email;
var extend = require('util')._extend;
var countries = require('country-data').countries;
function get_permission_checker(permission) {
var required = permission.split('/');
var allowed = config.permissions;
for(var i = 0; i < required.length; i++)
{
if(typeof allowed == 'undefined') {
console.log("Permission checker for unspecified permission requested: " + permission);
return function(username) {
return false;
}
};
allowed = allowed[required[i]];
}
// This function return is so we can make it optimized for require_permission
return function(username) {
if(allowed.indexOf('*anonymous*') != -1)
{
return true;
}
else if((allowed.indexOf('*authenticated*') != -1) && (username != null))
{
return true;
}
else if(allowed.indexOf(username) != -1)
{
return true;
}
else
{
return false;
}
};
};
utils.get_permission_checker = get_permission_checker;
utils.has_permission = function(permission, options) {
if(get_permission_checker(permission)(options.data.root.session.currentUser))
{
return options.fn(this);
}
else
{
return options.inverse(this);
}
};
utils.require_permission = function(permission) {
if(typeof permission === 'string') {
permission = [permission];
}
var checkers = [];
for(var perm in permission) {
perm = permission[perm];
checkers.push(get_permission_checker(perm));
}
return function(req, res, next) {
var has_one = false;
for(var checker in checkers) {
checker = checkers[checker];
if(checker(req.session.currentUser)) {
has_one = true;
break;
}
}
if(has_one)
{
next();
}
else
{
console.log("Unauthorized request: " + req.session.currentUser + " needed " + permission);
res.status(401).render('auth/no_permission', { required_permission: JSON.stringify(permission) });
}
};
};
utils.require_login = function(req, res, next) {
if(req.session.currentUser == null) {
res.status(401).render('auth/no_permission', { required_permission: 'Login' });
} else {
next();
}
};
utils.require_feature = function(feature) {
if(config[feature]['enabled']) {
return function(req, res, next) {
next();
}
} else {
return function(req, res, next) {
res.render('auth/no_permission', { required_permission: 'Feature disabled' });
}
}
};
utils.get_user = function(req, res, next) {
if(!req.session.currentUser) {
next();
return;
}
User.find({
where: {
email: req.session.currentUser
}
})
.catch(function(error) {
res.status(500).send('Error retrieving user object');
})
.then(function(user) {
if(user) {
req.user = user;
res.locals.user = user;
next();
} else {
next();
}
});
}
utils.require_user = function(req, res, next) {
if(!req.session.currentUser) {
res.status(401).render('auth/no_permission', { required_permission: 'Login' });
return;
}
if(!req.user) {
// Redirect to register
res.redirect(302, '/authg/register?origin=' + req.originalUrl);
} else {
next();
}
};
utils.send_email = function(req, res, recipient, template, variables, cb) {
if(recipient == null) {
recipient = req.user.id;
} else {
recipient = recipient.id;
}
variables.layout = false;
req.app.render('email/' + template, variables, function(err, html) {
if(!!err) {
console.log('Error rendering email: ' + err);
res.status(500).send('Error rendering email');
return null;
} else {
var split = html.split('\n');
var subject = split[0];
var contents = split.slice(2).join('\n');
var info = {
UserId: recipient,
sent: false,
subject: subject,
body: contents
};
Email.create(info)
.catch(function(err) {
console.log('Error saving email: ' + err);
res.status(500).send('Error sending email');
return null;
})
.then(function(err, email) {
cb();
});
}
});
};
utils.get_reg_fields = function (request, registration, skip_internal) {
var fields = {};
for(var field in config['registration']['fields']) {
if (skip_internal && config['registration']['fields'][field]['internal'])
continue;
fields[field] = extend({}, config['registration']['fields'][field]);
if(fields[field]['type'] == 'country') {
fields[field]['type'] = 'select';
var options = fields[field]['options'];
if (options === undefined)
options = [];
for(var country in countries.all) {
options.push(countries.all[country].name);
};
fields[field]['options'] = options;
}
};
if(request)
console.log(request.body);
for(field in fields) {
if(request && ('field_' + field) in request.body) {
fields[field].value = request.body['field_' + field];
} else if(registration != null) {
for(var info in registration.RegistrationInfos) {
info = registration.RegistrationInfos[info];
if(info.field == field) {
fields[field].value = info.value;
}
}
} else {
fields[field].value = '';
}
};
return fields;
}
module.exports = utils;
|
import _extends from "@babel/runtime/helpers/extends";
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/objectWithoutPropertiesLoose";
var _excluded = ["items", "disabled", "className", "name", "error", "variant", "design", "label", "children", "size", "fontWeight", "paragraphStyle", "labelProps"],
_excluded2 = ["id", "className"];
import React from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';
import classNames from 'classnames';
import { RadioButton } from '../../form/radio-button';
import { pxToRem } from '../../../helpers/utils/typography';
import { Label } from '../../form/label';
var StyledRadioButtonSet = styled.fieldset.withConfig({
displayName: "radio-button-set__StyledRadioButtonSet",
componentId: "sc-1bde3vb-0"
})(["margin:0;padding:0;border:0;line-height:1.3rem;& > legend{padding:0;}.k-Form-RadioButtonSet__label{margin-bottom:", ";}.k-Form-RadioButtonSet__radioContainer{display:flex;flex-direction:column;gap:", " 0;.k-Form-RadioButtonSet__radioButton.k-Form-RadioButton{margin:0;}}"], pxToRem(10), pxToRem(5));
export var RadioButtonSet = function RadioButtonSet(_ref) {
var items = _ref.items,
disabled = _ref.disabled,
className = _ref.className,
name = _ref.name,
error = _ref.error,
variant = _ref.variant,
design = _ref.design,
label = _ref.label,
children = _ref.children,
size = _ref.size,
fontWeight = _ref.fontWeight,
paragraphStyle = _ref.paragraphStyle,
labelProps = _ref.labelProps,
props = _objectWithoutPropertiesLoose(_ref, _excluded);
return /*#__PURE__*/React.createElement(StyledRadioButtonSet, _extends({
className: classNames('k-Form-RadioButtonSet', className, "k-Form-RadioButtonSet--" + variant),
disabled: disabled
}, props), label && /*#__PURE__*/React.createElement(Label, _extends({
tag: "legend"
}, labelProps, {
className: classNames('k-Form-RadioButtonSet__label', labelProps.className)
}), label), children && !label && /*#__PURE__*/React.createElement("legend", null, children), /*#__PURE__*/React.createElement("div", {
className: "k-Form-RadioButtonSet__radioContainer"
}, items.map(function (_ref2) {
var id = _ref2.id,
className = _ref2.className,
itemProps = _objectWithoutPropertiesLoose(_ref2, _excluded2);
return /*#__PURE__*/React.createElement(RadioButton, _extends({
id: id,
variant: variant,
design: design,
error: error,
size: size,
fontWeight: fontWeight,
paragraphStyle: paragraphStyle,
name: name,
key: id
}, itemProps, {
className: classNames('k-Form-RadioButtonSet__radioButton', className)
}));
})));
};
RadioButtonSet.propTypes = {
name: PropTypes.string.isRequired,
error: PropTypes.bool,
label: PropTypes.string,
items: PropTypes.arrayOf(PropTypes.shape({
text: PropTypes.string.isRequired,
id: PropTypes.string.isRequired,
defaultChecked: PropTypes.bool
})),
size: PropTypes.oneOf(['small', 'regular', 'big']),
variant: PropTypes.oneOf(['andromeda', 'orion']),
design: PropTypes.oneOf(['disc', 'check']),
disabled: PropTypes.bool,
labelProps: PropTypes.object,
fontWeight: PropTypes.oneOf(['light', 'regular', 'bold']),
paragraphStyle: false
};
RadioButtonSet.defaultProps = {
name: 'radioButtonSet',
error: false,
label: null,
items: [{
text: 'filter 1',
children: 'lorem ipsum dolor',
defaultChecked: true,
id: 'myRadioButton' // Replace by a real value
}],
variant: 'orion',
design: 'disc',
disabled: false,
labelProps: {},
size: 'regular',
fontWeight: 'regular',
paragraphStyle: false
};
|
// HINT TASK
// =============================================================================
"use strict";
var taskName = 'hint';
var gulp = require('gulp');
var jshint = require('gulp-jshint');
var config = require('./config');
require('jshint-stylish');
gulp.task('hint', function() {
return gulp.src(config.lint.src)
.pipe(plumber())
.pipe(jshint())
.pipe(jshint.reporter('jshint-stylish'));
});
gulp.task('lint', function() {
return gulp.src(config.lint.src)
.pipe(plumber())
.pipe(jshint());
});
|
var votesControllers = angular.module('votesControllers', []);
votesControllers.controller('VotesCtrl', ['$scope','$routeParams','$location', '$http','$rootScope','$cookies','GetVotes','GetLastVotes','GetVotesById',
function($scope,$routeParams,$location, $http,$rootScope,$cookies,GetVotes,GetLastVotes,GetVotesById) {
$scope.summoner=$routeParams.summoner;
$scope.loading_data=true;
var pagin=0;
$('#decrease_pagination').hide();
$scope.votes;
$scope.pagination=1;
$scope.game_mode;
$scope.no_game=false;
$scope.stats;
$scope.messages;
$scope.profile_name;
$scope.show_recent_votes=true;
$scope.loading_votes=true
$scope.league;
$scope.skip=0;
$scope.pagination_number=1;
var json_data={data:{name:$scope.summoner,pagination:$scope.pagination}};
GetVotes.query(json_data,function(data) {
console.log(data);
$scope.votes=data;
var matchid;
setTimeout(function(){
for (var i = 0; i < data.length; i++) {
matchid=data[i].match_id;
console.log(matchid);
$("#"+ data[i].match_id).hover(function () {
$("#"+ this.id +"_stats").slideToggle("fast");
});
}
}, 1000);
pagin=$scope.votes.length/5;
if ( $scope.pagination_number>pagin-1) {
setTimeout(function(){
$('#increase_pagination').fadeOut();
console.log(pagin);
}, 1000);
}
$scope.loading_data=false;
var json_data={data:{name:$scope.summoner,match_id:data[0].match_id}};
// GetLastVotes.query(json_data,function(data) {
// console.log(data);
// $scope.messages=data[0][0];
// $scope.stats=data[2][0];
// $scope.loading_votes=false;
// });
// $(document).ready(function() {
// $("#champ-panel").hide();
// });
});
$scope.votesById=function(target)
{
$('#p2').css("visibility","visible");
$scope.loading_votes=true;
var json_data={data:{name:$scope.summoner,match_id:target}};
GetVotesById.query(json_data,function(data) {
$scope.show_recent_votes=false;
$('#p2').css("visibility","hidden");
$scope.messages=data[0][0];
$scope.stats=data[2][0];
console.log($scope.stats);
$scope.loading_votes=false;
});
}
$scope.increase_pagination=function()
{
console.log(pagin);
if ( $scope.pagination_number>pagin-1) {
console.log(pagin);
$('#increase_pagination').fadeOut()
}
$scope.skip+=5;
$scope.pagination_number++;
$('#decrease_pagination').fadeIn()
}
$scope.decrease_pagination=function()
{
$('#increase_pagination').fadeIn()
$scope.skip-=5;
$scope.pagination_number--;
if ($scope.pagination_number==1) {
$('#decrease_pagination').fadeOut();
}
}
}]);
|
var content_output2 = '<h2> Output In File JS test2 </h2>'
+ '<p>getAllParams: ' + JSON.stringify(PaserCurrentFileJs.getAllParams())
+ '<p>getAllAttributes: ' + JSON.stringify(PaserCurrentFileJs.getAllAttributes())
+ '<p>getValueParam param1: ' + JSON.stringify(PaserCurrentFileJs.getValueParam('param1'))
+ '<p>getValueParam param2: ' + JSON.stringify(PaserCurrentFileJs.getValueParam('param2'))
+ '<p>getValueAttribute attr-param1: ' + JSON.stringify(PaserCurrentFileJs.getValueAttribute('attr-param1'))
+ '<p>getValueAttribute attr-param2: ' + JSON.stringify(PaserCurrentFileJs.getValueAttribute('attr-param2'))
+ '<p>-----------------------------------------------------------------------------';
document.write(content_output2);
|
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(['exports', '@uirouter/core', './ui-view-spinner', './content-cache'], factory);
} else if (typeof exports !== "undefined") {
factory(exports, require('@uirouter/core'), require('./ui-view-spinner'), require('./content-cache'));
} else {
var mod = {
exports: {}
};
factory(mod.exports, global.core, global.uiViewSpinner, global.contentCache);
global.uiViewController = mod.exports;
}
})(this, function (exports, _core, _uiViewSpinner, _contentCache) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _uiViewSpinner2 = _interopRequireDefault(_uiViewSpinner);
var _contentCache2 = _interopRequireDefault(_contentCache);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var _createClass = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function (Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
}();
var UiViewController = function () {
function UiViewController($animate, $state, $element, $scope, $q) {
_classCallCheck(this, UiViewController);
this.onDestroyCallbacks = [];
$animate.enabled($element, false);
this.$state = $state;
this.$element = $element;
var spinner = _uiViewSpinner2.default.attachTo($element);
var _$element$data = $element.data('$uiView'),
$cfg = _$element$data.$cfg;
this.deps = $cfg && $cfg.viewDecl.resolve || [];
if ($cfg) {
$element.html(_contentCache2.default.get($cfg.viewDecl) || undefined);
}
this.$scope = $scope;
if (this.deps.length) {
var resolveCtx = $cfg.path && new _core.ResolveContext($cfg.path);
$scope.$watchGroup(this.deps.map(function (token) {
return function () {
return resolveCtx.getResolvable(token).get(resolveCtx);
};
}), function (promises) {
spinner.show();
if (!(0, _core.any)(function (p) {
return p !== undefined;
})(promises)) {
return;
}
$q.all(promises).finally(function () {
return spinner.hide();
});
});
}
}
_createClass(UiViewController, [{
key: '$onDestroy',
value: function $onDestroy() {
var $uiView = this.$element.data('$uiView');
if (!$uiView || !$uiView.$cfg) return;
var $cfg = $uiView.$cfg;
var $element = this.$element;
var trans = this.$state.transition;
if (trans) {
var entering = trans.entering();
var exiting = trans.exiting().filter(function (node) {
return entering.indexOf(node) === -1;
});
if (exiting.indexOf($cfg.viewDecl.$context.self) !== -1) {
_contentCache2.default.delete($cfg.viewDecl);
} else {
_contentCache2.default.set($cfg.viewDecl, $element.html());
}
}
this.onDestroyCallbacks.forEach(function (fn) {
return fn();
});
}
}, {
key: 'onDestroy',
value: function onDestroy(fn) {
this.onDestroyCallbacks.push(fn);
}
}]);
return UiViewController;
}();
exports.default = UiViewController;
UiViewController.$inject = ['$animate', '$state', '$element', '$scope', '$q'];
});
|
Package.describe({
name: 'iron:url',
summary: 'Url utilities and support for compiling a url into a regular expression.',
version: '1.1.0',
git: 'https://github.com/iron-meteor/iron-url'
});
Package.on_use(function (api) {
api.versionsFrom('METEOR@0.9.2');
api.use('underscore');
api.use('iron:core@1.0.11');
api.imply('iron:core');
api.add_files('lib/compiler.js');
api.add_files('lib/url.js');
});
Package.on_test(function (api) {
api.use('iron:url');
api.use('tinytest');
api.use('test-helpers');
api.add_files('test/url_test.js', ['client', 'server']);
});
|
module.exports = {
moduleFileExtensions: ['js', 'json', 'vue'],
transform: {
'^.+\\.js$': 'babel-jest',
'^.+\\.vue$': '@vue/vue3-jest',
},
testMatch: ['**/tests/**/*.test.js'],
};
|
// COPYRIGHT © 2017 Esri
//
// All rights reserved under the copyright laws of the United States
// and applicable international laws, treaties, and conventions.
//
// This material is licensed for use under the Esri Master License
// Agreement (MLA), and is bound by the terms of that agreement.
// You may redistribute and use this code without modification,
// provided you adhere to the terms of the MLA and include this
// copyright notice.
//
// See use restrictions at http://www.esri.com/legal/pdfs/mla_e204_e300/english
//
// For additional information, contact:
// Environmental Systems Research Institute, Inc.
// Attn: Contracts and Legal Services Department
// 380 New York Street
// Redlands, California, USA 92373
// USA
//
// email: contracts@esri.com
//
// See http://js.arcgis.com/4.4/esri/copyright.txt for details.
define(["require","exports","../../core/tsSupport/declareExtendsHelper","../../core/tsSupport/decorateHelper","../../core/accessorSupport/decorators","../../core/Accessor","../../portal/Portal"],function(r,t,e,o,p,s,l){var n=a=function(r){function t(){var t=null!==r&&r.apply(this,arguments)||this;return t.portal=null,t}return e(t,r),t.prototype.clone=function(){return new a({name:this.name,styleUrl:this.styleUrl,styleName:this.styleName,portal:this.portal})},t}(p.declared(s));o([p.property({type:String})],n.prototype,"name",void 0),o([p.property({type:String})],n.prototype,"styleUrl",void 0),o([p.property({type:String})],n.prototype,"styleName",void 0),o([p.property({type:l})],n.prototype,"portal",void 0),n=a=o([p.subclass("esri.symbols.support.StyleOrigin")],n);var a;return n});
|
var SOURCE_FOLDER = __dirname + '/src/';
var DIST_FOLDER = __dirname + '/dist/';
var BUNDLE_NAME = 'visible.min.js';
var webpack = require('webpack');
module.exports = {
entry: SOURCE_FOLDER + '/visible.js',
target: 'web',
output: {
library: 'visible',
path: DIST_FOLDER,
filename: BUNDLE_NAME,
publicPath: '/'
},
externals: [
{
visible: "visible"
}
],
plugins: [
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
},
output: {
comments: false,
semicolons: true
}
})
],
module: {
loaders: [
{ test: /\.(js|jsx)$/, exclude: /(bower_components|node_modules)/, loader: 'babel-loader' }
]
},
devServer: {
port: 8080,
host: '0.0.0.0',
lazy: true,
contentBase: SOURCE_FOLDER,
stats: { colors: true }
}
};
|
var express = require('express');
var router = express.Router();
var mkdirp = require('mkdirp');
var fs = require("fs");
var file = __dirname + "/../database/panoinfo.db";
var exists = fs.existsSync(file);
var sqlite3 = require("sqlite3").verbose();
var db = new sqlite3.Database(file);
/* GET users listing. */
router.get('/', function(req, res, next) {
var panoinfoPath = __dirname + "/../public/panoinfo";
mkdirp(panoinfoPath);
db.all("SELECT info FROM panoinfo", function(err, rows) {
for (var i = 0; i < rows.length; i++) {
var data = JSON.parse(rows[i].info);
console.log(data.location.pano)
var filePath = panoinfoPath + '/' + data.location.pano;
fs.writeFile(filePath, rows[i].info)
};
});
res.send('');
});
module.exports = router;
|
import arrays from './arrays';
import core from './core';
export default {
core,
arrays,
};
|
import React, { Component } from 'react'
import { Card, CardTitle, Divider } from "material-ui";
import Build from 'material-ui/svg-icons/action/build'
import Header from './basic/Header'
import Paragraph from './basic/Paragraph'
class NotFoundCard extends Component {
constructor(props) {
super(props);
}
render() {
return (
<Card zDepth={2}
style={{
padding: "35px"
}}>
<CardTitle>
<Header text="404 Not Found">
<Build style={{
paddingRight: "20px"
}} />
</Header>
</CardTitle>
<Divider />
<Paragraph text=" We tried really hard, but we couldn't find this page anywhere." />
<Paragraph text="We suggest you go back. There is nothing to see here."/>
</Card>
)
}
}
export default NotFoundCard
|
var palloc_8h =
[
[ "palloc_t", "dc/d36/structpalloc__t.html", "dc/d36/structpalloc__t" ],
[ "MAX_PALLOC", "dc/df7/palloc_8h.html#ae98cf2dde32dd7752510faa08edec1ef", null ],
[ "PALLOC_MAX_BLOCKS", "dc/df7/palloc_8h.html#a6acb1947dc49f45d9429e9cc660ce2b1", null ],
[ "PALLOC_SIZE", "dc/df7/palloc_8h.html#a8399f294aa979d4bcd17fc199326234c", null ],
[ "palloc", "dc/df7/palloc_8h.html#ab8008be59211cc4129d9fed478ba32ac", null ],
[ "pfree", "dc/df7/palloc_8h.html#a955b5e8e3baff742271da3ff44669e43", null ],
[ "pgetusable", "dc/df7/palloc_8h.html#a4d92f3937b1e63849c7466119e561b7f", null ],
[ "pinit", "dc/df7/palloc_8h.html#acea7f1b315e15a2d1024c45b87b6276d", null ],
[ "ptotalsize", "dc/df7/palloc_8h.html#a5a2279e2e824d45690599172b2436807", null ],
[ "pusedmem", "dc/df7/palloc_8h.html#a0988517ae62414ef09cf2694c4b02b75", null ]
];
|
module.exports = function(grunt) {
grunt.registerTask('default', ['compileAssets', 'watch']);
};
|
////////////////////////////////////////////////////////////////////////////////
//API routes
/* Instantiate Express Module*/
var express = require('express');
/* Instantiate Express Router*/
var router = express.Router();
//Instantiate Image model
var Image = require('../models/image_model.js');
//Instantiate User model
var User = require('../models/user_model.js');
////////////////////////////////////////////////////////////////////////////////
/* API */
router.get('/', function(req, res, next) {
res.setHeader(
'Content-Type',
'application/json',
'charset=utf-8'
);
res.send(200, JSON.stringify({
"message": "Requires Authentication",
"documentation_url": "https://developer.blobber.com/v1"
}));
});
///////////////////////////////////////////////////////////////////////////////
module.exports = router;
////////////////////////////////////////////////////////////////////////////////
|
function recordObj(){
this.id = '';
this.time = '';
this.value = new Object();
}
module.exports = recordObj;
|
// PMASETools Cards -- data model
// Loaded on both the client and the server
///////////////////////////////////////////////////////////////////////////////
// Cards
/*
Each card is represented by a document in the Cards collection:
x, y: Number (screen coordinates in the interval [0, 1])
text, description: String
Eventually:
owner: user id
*/
Cards = new Meteor.Collection("cards");
Cards.allow({
insert: function (userId, card) {
return false; // no cowboy inserts -- use createCard method
},
update: function (userId, card, fields, modifier) {
/* no users yet
if (userId !== card.owner)
return false; // not the owner
*/
var allowed = ["text", "description", "x", "y"];
if (_.difference(fields, allowed).length)
return false; // tried to write to forbidden field
// A good improvement would be to validate the type of the new
// value of the field (and if a string, the length.) In the
// future Meteor will have a schema system to makes that easier.
return true;
},
remove: function (userId, party) {
// cant remove yet
return false;
}
});
var NonEmptyString = Match.Where(function (x) {
check(x, String);
return x.length !== 0;
});
var Coordinate = Match.Where(function (x) {
check(x, Number);
return x >= 0 && x <= 500;
});
Meteor.methods({
// options should include: text, description, x, y
createCard: function (options) {
check(options, {
text: NonEmptyString,
// description: NonEmptyString,
x: Coordinate,
y: Coordinate
});
// tweak as necessary, showing some data validation
if (options.text.length > 100)
throw new Meteor.Error(413, "Text too long");
// if (options.description.length > 1000)
// throw new Meteor.Error(413, "Description too long");
/* no users yet
if (! this.userId)
throw new Meteor.Error(403, "You must be logged in");
*/
return Cards.insert({
// owner: this.userId,
x: options.x,
y: options.y,
text: options.text,
// description: options.description,
});
},
});
///////////////////////////////////////////////////////////////////////////////
// Users - Coming soon
/*
displayName = function (user) {
if (user.profile && user.profile.name)
return user.profile.name;
return user.emails[0].address;
};
var contactEmail = function (user) {
if (user.emails && user.emails.length)
return user.emails[0].address;
if (user.services && user.services.facebook && user.services.facebook.email)
return user.services.facebook.email;
return null;
};
*/
|
var express = require('express');
var router = express.Router();
db = new Firebase('https://codherjs.firebaseio.com/');
dbTweets = db.child('tweets');
/* GET home page. */
router.get('/', function(req, res) {
res.render('index', { tweets: [] });
// dbTweets.on('child_added', function(snapshot) {
// res.render('index', { tweets: snapshot.val()});
// });
});
module.exports = router;
|
'use strict';
// Use Applicaion configuration module to register a new module
ApplicationConfiguration.registerModule('trainingsessions');
|
#! /usr/bin/env node
/*
* This is the Command Line Implementation of the `emptydir` module
*
* Command Line Argument Processing
* emptydir dirA dirB - empties the directories
* emptydir --version - show version
* emptydir --help - show this help message
* emptydir -v - be verbose in emptying the directory
*/
module.exports.run = run;
var emptydir = require('./emptydir'),
version = require('./package.json').version;
// Prints sucess and error messages
function print(path, error) {
if (error) {
process.stdout.write('FAIL\t' + path + '\t->' + error.code + '\n');
return;
}
process.stdout.write('OKAY\t' + path + '\n');
}
// Missing operand
var missing_operand = [
'emptydir: missing operand',
'Try \'emptydir --help\' for more information',
'\n'
];
// Invalid Options
var invalid_option = [
'emptydir: invalid_option',
'Try \'emptydir --help\' for more information',
'\n'
];
// Help Information
var help_info = [
'emptydir\n',
'Lets you recursively delete files in directories while maintaining the the directory structure\n',
' --help \t\t Show this help message',
' --version \t\t Show version information',
' -v, --verbose \t\t Be verbose while deleting',
'\nExample:\n\n\temptydir -v my_dir/ old_file',
'\n'
]
// Commandline runner
function run(args, options){
args = args || [];
if (!options) options = {};
missing_operand = options['missing_operand'] || '';
help_info = options['help_info'] || '';
version_info = options['version_info'] || '';
invalid_option = options['invalid_option'] || '';
// Shift twice to remove the node executable and filename
args.shift();
args.shift();
if (args.length == 0) {
process.stdout.write(missing_operand);
return missing_operand;
} else{
// 1 option commands
if (args.length == 1) {
if (args[0] == '--version') {
process.stdout.write(version_info);
return help_info;
} else if (args[0] == '--help') {
process.stdout.write(help_info);
return help_info;
}
}
// Are we verbose?
var verbose = false;
var new_args = [];
args.forEach(function (arg) {
if (arg == '--verbose' || arg == '-v') {
verbose = true;
} else{
new_args.push(arg);
}
});
args = new_args;
if (args.length == 0) {
process.stdout.write(missing_operand);
return missing_operand;
}
// Invalid option?
args_string = args.toString();
if (args_string.match(/^-/) || args_string.match(/,-/)) {
process.stdout.write(invalid_option);
return invalid_option;
}
// Lets get to Work
if (verbose) {
args.forEach(function (path) {
emptydir.emptyDirs('./' + path, function (error, w_path) {
if (error) {
print(w_path, error);
return;
}
print(w_path);
});
});
} else {
args.forEach(function (path) {
emptydir.emptyDir('./' + path, function (errors, w_path) {
if (errors) {
errors.forEach(function (error) {
print(error.path, error);
});
}
});
});
}
}
}
// Calls function and passes parameters
run(
process.argv,
{
'missing_operand': missing_operand.join('\n'),
'help_info': help_info.join('\n'),
'version_info': 'emptydir ' + version + '\n',
'invalid_option': invalid_option.join('\n')
}
);
/*
* NOTES FOR PROGRAMMER:
* This CLI should be as independent as possible, without requiring any
* external module
*
* Using emptydir.emptyDirs() causes an error when verbose is turned off.
* This is not Fixed yet. Try fix this behavior.
*/
|
import { schema } from 'normalizr';
const user = new schema.Entity('users');
const messages = new schema.Entity('messages', {
user,
});
export const message = new schema.Entity('message', {
user,
});
export const messagesList = [messages];
export default messagesList;
|
var zrUtil = require('zrender/lib/core/util');
// FIXME 公用?
/**
* @param {Array.<module:echarts/data/List>} datas
* @param {string} statisticType 'average' 'sum'
* @inner
*/
function dataStatistics(datas, statisticType) {
var dataNameMap = {};
var dims = ['value'];
zrUtil.each(datas, function (data) {
data.each(dims, function (value, idx) {
// Add prefix to avoid conflict with Object.prototype.
var mapKey = 'ec-' + data.getName(idx);
dataNameMap[mapKey] = dataNameMap[mapKey] || [];
if (!isNaN(value)) {
dataNameMap[mapKey].push(value);
}
});
});
return datas[0].map(dims, function (value, idx) {
var mapKey = 'ec-' + datas[0].getName(idx);
var sum = 0;
var min = Infinity;
var max = -Infinity;
var len = dataNameMap[mapKey].length;
for (var i = 0; i < len; i++) {
min = Math.min(min, dataNameMap[mapKey][i]);
max = Math.max(max, dataNameMap[mapKey][i]);
sum += dataNameMap[mapKey][i];
}
var result;
if (statisticType === 'min') {
result = min;
}
else if (statisticType === 'max') {
result = max;
}
else if (statisticType === 'average') {
result = sum / len;
}
else {
result = sum;
}
return len === 0 ? NaN : result;
});
}
module.exports = function (ecModel) {
var seriesGroups = {};
ecModel.eachSeriesByType('map', function (seriesModel) {
var hostGeoModel = seriesModel.getHostGeoModel();
var key = hostGeoModel ? 'o' + hostGeoModel.id : 'i' + seriesModel.getMapType();
(seriesGroups[key] = seriesGroups[key] || []).push(seriesModel);
});
zrUtil.each(seriesGroups, function (seriesList, key) {
var data = dataStatistics(
zrUtil.map(seriesList, function (seriesModel) {
return seriesModel.getData();
}),
seriesList[0].get('mapValueCalculation')
);
for (var i = 0; i < seriesList.length; i++) {
seriesList[i].originalData = seriesList[i].getData();
}
// FIXME Put where?
for (var i = 0; i < seriesList.length; i++) {
seriesList[i].seriesGroup = seriesList;
seriesList[i].needsDrawMap = i === 0 && !seriesList[i].getHostGeoModel();
seriesList[i].setData(data.cloneShallow());
seriesList[i].mainSeries = seriesList[0];
}
});
};
|
// @flow
import React, { PureComponent as Component } from "react";
import Slider from "rc-slider/lib/Slider";
import { A, Icon } from "../common";
type Props = {
nodeId: number,
currentLine: Array<number>,
onChangeCurrentNode: (number) => any,
};
export default class BoardNav extends Component<Props> {
componentDidMount() {
document.addEventListener("keydown", this._onKeyDown);
}
componentWillUnmount() {
document.removeEventListener("keydown", this._onKeyDown);
}
render() {
let { nodeId, currentLine } = this.props;
if (typeof nodeId !== "number" || !currentLine) {
return <div className="BoardNav" />;
}
let moveNum = currentLine.indexOf(nodeId);
return (
<div className="BoardNav">
<div className="BoardNav-slide-container">
<div className="BoardNav-slide">
<Slider
min={0}
max={currentLine.length - 1}
step={1}
value={moveNum}
onChange={this._onChangeMoveNum}
/>
</div>
<div className="BoardNav-move">Move {moveNum}</div>
</div>
<div className="BoardNav-step">
<A className="BoardNav-prev" onClick={this._onPrev}>
<Icon name="chevron-left" />
</A>
<A className="BoardNav-next" onClick={this._onNext}>
<Icon name="chevron-right" />
</A>
</div>
</div>
);
}
_onChangeMoveNum = (val: number) => {
let { currentLine } = this.props;
let nodeId = currentLine[val];
this.props.onChangeCurrentNode(nodeId);
};
_onPrev = () => {
let { nodeId, currentLine } = this.props;
let idx = currentLine.indexOf(nodeId);
if (idx > 0) {
this.props.onChangeCurrentNode(currentLine[idx - 1]);
}
};
_onNext = () => {
let { nodeId, currentLine } = this.props;
let idx = currentLine.indexOf(nodeId);
if (idx < currentLine.length - 1) {
this.props.onChangeCurrentNode(currentLine[idx + 1]);
}
};
_onLast = () => {
let { currentLine } = this.props;
this.props.onChangeCurrentNode(currentLine[currentLine.length - 1]);
};
_onFirst = () => {
let { currentLine } = this.props;
this.props.onChangeCurrentNode(currentLine[0]);
};
_onKeyDown = (e: Object) => {
let node = e.target;
while (node) {
if (
node.nodeName === "INPUT" ||
node.nodeName === "SELECT" ||
node.nodeName === "TEXTAREA"
) {
if (node.value) {
return;
}
}
node = node.parentNode;
}
if (e.key === "ArrowLeft" || e.keyCode === 37) {
this._onPrev();
} else if (e.key === "ArrowRight" || e.keyCode === 39) {
this._onNext();
} else if (e.key === "ArrowUp" || e.keyCode === 38) {
this._onLast();
} else if (e.key === "ArrowDown" || e.keyCode === 40) {
this._onFirst();
}
};
}
|
/*global VisSense,it,expect*/
/* jshint undef: false */
describe('VisSense Globals', function () {
'use strict';
it('should have a `noConflict` method', function () {
expect(VisSense.noConflict).toBeDefined();
var _oldValue = VisSense;
var newCustomNameForVisSense = VisSense.noConflict();
expect(VisSense).not.toBeDefined();
expect(newCustomNameForVisSense).toBe(_oldValue);
// restore original state
window.VisSense = newCustomNameForVisSense.noConflict();
});
});
|
(function(win, doc, glue) {
'use strict';
function setStyles(collection, name, value) {
collection.each(function(element) {
element.style[name] = value;
});
}
function getStyle(element, property) {
var propertyValue, re = /(\-([a-z]){1})/g;
// Support both camelCase and dashed property names
property = property.replace(/([A-Z])/g, '-glue1').toLowerCase();
/* istanbul ignore else */
if (win.getComputedStyle /* && !glue.isTest*/) {
propertyValue = win.getComputedStyle(element, null).getPropertyValue(property);
} else if (doc.documentElement.currentStyle) {
if (property === 'float') {
property = 'styleFloat';
}
if (re.test(property)) {
property = property.replace(re, function() {
return arguments[2].toUpperCase();
});
}
propertyValue = element.currentStyle[property] ? element.currentStyle[property] : null;
}
return propertyValue;
}
function createXPath(node, path) {
var sibling, len, details = '',
name, selectorString;
path = path || [];
function isElement(obj) {
return obj.nodeType === 1;
}
/* istanbul ignore else - */
if (node.parentNode) {
path = createXPath(node.parentNode, path);
}
/* istanbul ignore else - */
if (node.previousSibling) {
len = 1;
sibling = node.previousSibling;
do {
if (isElement(sibling) && sibling.nodeName === node.nodeName) {
len++;
}
sibling = sibling.previousSibling;
} while (sibling);
if (len === 1) {
len = null;
}
} else if (node.nextSibling) {
sibling = node.nextSibling;
do {
if (isElement(sibling) && sibling.nodeName === node.nodeName) {
len = 1;
sibling = null;
} else {
len = null;
sibling = sibling.previousSibling;
}
} while (sibling);
}
if (isElement(node)) {
name = node.nodeName.toLowerCase();
/* istanbul ignore else - */
if (node.id) {
details = "#" + node.id;
} else if (node.className) {
details = "." + node.className;
} else if (len !== null) {
details = ":nth-of-type(" + len + ")";
}
path.push(name + details);
}
return path;
}
function css(context, property, value){
var collection = context,
isString = glue.isString(property),
isObject = glue.isPlainObject(property),
prop;
/* istanbul ignore else */
if (!collection.length || (!isString && !isObject)) {
return context;
} else if (isString) {
if (value === undefined) {
return getStyle(context[0], property);
} else {
setStyles(collection, property, value);
}
} else if (isObject) {
for (prop in property) { /* istanbul ignore else */
if (property.hasOwnProperty(prop)) {
setStyles(collection, prop, property[prop]);
}
}
}
return context;
}
function html(context, htmlString) {
if (htmlString) {
context.each(function(element) {
this.innerHTML = htmlString;
});
return context;
} else {
return context[0].innerHTML;
}
}
function createSelector(context, selector){
return createXPath(context).join(' ').substring(5) + ' ' + selector;
}
function parseHTML(element){
var div = doc.createElement('div');
div.innerHTML = element;
return div.firstChild;
}
function toggleDisplay(context, status){
var display = 'display', none = 'none';
if(status) {
context.css(display, status);
return context;
} else {
if (context.css(display) === none) {
context.css(display, 'block');
} else {
context.css(display, none);
}
return context;
}
}
function attr(context, name, value) {
if (!value) {
return context[0].getAttribute(name);
} else {
context[0].setAttribute(name, value);
return context;
}
}
function append(context, elementString){
var domObject = glue.parseHTML(elementString);
context[0].appendChild(domObject);
return context;
}
function prepend(context, elementString){
var domObject = glue.parseHTML(elementString),
parent = context[0];
parent.insertBefore(domObject, parent.firstChild);
return context;
}
function remove(context) {
context.each(function() {
var parent = this.parentNode;
parent.removeChild(this);
});
return context;
}
function find(context, selector){
var baseSelector = glue.getSelector();
if (glue.isString(selector) && glue.isString(baseSelector)) {
return glue(baseSelector + ' ' + selector);
} else {
return glue(context.selectorify(selector));
}
}
glue.fn.selectorify = function(selector) {
return createSelector(this, selector);
};
glue.parseHTML = function(element) {
return parseHTML(element);
};
glue.fn.extend({
css: function(property, value) {
return css(this, property, value);
},
html: function(htmlString) {
return html(this, htmlString);
},
hide: function() {
return toggleDisplay(this, 'none');
},
show: function() {
return toggleDisplay(this, 'block');
},
toggle: function() {
return toggleDisplay(this);
},
attr: function(name, value) {
return attr(this, name, value);
},
append: function(elementString) {
return append(this, elementString);
},
prepend: function(elementString) {
return prepend(this, elementString);
},
remove: function() {
return remove(this);
},
find: function(selector) {
return find(this, selector);
}
});
}(window, document, glue));
|
'use strict';
var myAppControllers = angular.module('myAppControllers',[]);
myAppControllers.controller('ContentQuery', ['$scope', 'Content', '$routeParams',
function($scope, Content, $routeParams){
$scope.contentItems = Content.query();
$scope.contentPath = $routeParams.contentId;
//$scope.picked = $scope.contentOptions[0];
}]);
myAppControllers.controller('ContentCtrl', ['$scope', '$routeParams', 'Content',
function($scope, $routeParams, Content){
$scope.pageContent = Content.get({contentId: $routeParams.contentId});
}]);
|
(function() {
'use strict';
angular.module('ShoppingListCheckOff', [])
.controller('ToBuyController', ToBuyController)
.controller('AlreadyBoughtController', AlreadyBoughtController)
.service('ShoppingListCheckOffService', ShoppingListCheckOffService);
ToBuyController.$inject = ['ShoppingListCheckOffService'];
function ToBuyController(ShoppingListCheckOffService) {
var toBuyCtrl = this;
toBuyCtrl.buyList = ShoppingListCheckOffService.getToBuyItems();
toBuyCtrl.buyItem = function(index) {
ShoppingListCheckOffService.changeItem(index);
};
}
AlreadyBoughtController.$inject = ['ShoppingListCheckOffService'];
function AlreadyBoughtController(ShoppingListCheckOffService) {
var boughtCtrl = this;
boughtCtrl.boughtList = ShoppingListCheckOffService.getBoughtItems();
}
function ShoppingListCheckOffService() {
var service = this;
var toBuyItems = [{ name: "cookies", quantity: 10 }, { name: "breads", quantity: 2 }, { name: "muffins", quantity: 3 }, { name: "steaks", quantity: 5 }, { name: "fruits", quantity: 20 }];
var boughtItems = [];
service.getToBuyItems = function() {
return toBuyItems;
};
service.getBoughtItems = function() {
return boughtItems;
};
service.changeItem = function(index) {
boughtItems.push(toBuyItems[index]);
toBuyItems.splice(index, 1);
}
}
})();
|
import Parser from 'ember-graphql-adapter/parser';
import Generator from 'ember-graphql-adapter/generator';
import ArgumentSet from 'ember-graphql-adapter/types/argument-set';
import { Field, Operation } from 'ember-graphql-adapter/types';
export default {
compile(model, store, options) {
options = options || {};
let operationType = options['operationType']; // TODO: Must be query or mutation
let operationName = options['operationName'];
let operation = new Operation(operationType, operationName);
let rootFieldQuery = options['rootFieldQuery'] || {};
let rootFieldName = options['rootFieldName'] || model.modelName;
let rootFieldAlias = options['rootFieldAlias'];
let rootField = new Field(rootFieldName, rootFieldAlias, ArgumentSet.fromQuery(rootFieldQuery));
Parser.parse(model, store, operation, rootField, options);
return Generator.generate(operation);
}
};
|
import * as React from 'react';
import TopLayoutCompany from 'docs/src/modules/components/TopLayoutCompany';
import {
demos,
docs,
demoComponents,
} from 'docs/src/pages/careers/react-engineer.md?@mui/markdown';
export default function Page() {
return <TopLayoutCompany demos={demos} docs={docs} demoComponents={demoComponents} />;
}
|
// The client ID is obtained from the {{ Google Cloud Console }}
// at {{ https://cloud.google.com/console }}.
// If you run this code from a server other than http://localhost,
// you need to register your own client ID.
var OAUTH2_CLIENT_ID = '111436808615-d7mam74ms4a49846vpq7iqmn8ihu6mdu.apps.googleusercontent.com';
var OAUTH2_SCOPES = [
'https://www.googleapis.com/auth/youtube'
];
// Upon loading, the Google APIs JS client automatically invokes this callback.
googleApiClientReady = function() {
gapi.auth.init(function() {
window.setTimeout(checkAuth, 1);
});
}
// Attempt the immediate OAuth 2.0 client flow as soon as the page loads.
// If the currently logged-in Google Account has previously authorized
// the client specified as the OAUTH2_CLIENT_ID, then the authorization
// succeeds with no user intervention. Otherwise, it fails and the
// user interface that prompts for authorization needs to display.
function checkAuth() {
gapi.auth.authorize({
client_id: OAUTH2_CLIENT_ID,
scope: OAUTH2_SCOPES,
immediate: true
}, handleAuthResult);
}
// Handle the result of a gapi.auth.authorize() call.
function handleAuthResult(authResult) {
if (authResult && !authResult.error) {
// Authorization was successful. Hide authorization prompts and show
// content that should be visible after authorization succeeds.
$('.pre-auth').hide();
$('.post-auth').show();
loadAPIClientInterfaces();
} else {
// Make the #login-link clickable. Attempt a non-immediate OAuth 2.0
// client flow. The current function is called when that flow completes.
$('#login-link').click(function() {
gapi.auth.authorize({
client_id: OAUTH2_CLIENT_ID,
scope: OAUTH2_SCOPES,
immediate: false
}, handleAuthResult);
});
}
}
// Load the client interfaces for the YouTube Analytics and Data APIs, which
// are required to use the Google APIs JS client. More info is available at
// https://developers.google.com/api-client-library/javascript/dev/dev_jscript#loading-the-client-library-and-the-api
function loadAPIClientInterfaces() {
gapi.client.load('youtube', 'v3', function() {
handleAPILoaded();
});
}
|
module( "max test" );
test('숫자 순차 배열의 최대값',function(){
var fn = Pascal.max([1,2,,3,4,5,10]);
deepEqual(fn, 10, "Pascal.fact([1,2,,3,4,5,10]) === 10");
});
test('순서 없는 숫자 배열의 최대값',function(){
var fn = Pascal.max([1,-2,-3,4,5,-10]);
deepEqual(fn, 5, "Pascal.fact(1,-2,-3,4,5,-10]) === 5");
});
test('문자열이 포함된 배열의 최대값',function(){
var fn = Pascal.max(['hello',1,-2,-3,4,5,-10]);
deepEqual(fn, 5, "Pascal.fact('hello',1,-2,-3,4,5,-10]) === 5");
});
test('숫자형 문자열이 포함된 배열의 최대값',function(){
var fn = Pascal.max(['1000',1,-2,-3,4,5,-10]);
deepEqual(fn, 1000, "Pascal.fact('-1000',1,-2,-3,4,5,-10]) === 1000");
});
|
'use strict';
// load gulp and gulp plugins
var gulp = require("gulp");
var $ = require('gulp-load-plugins')();
// load node modules
var del = require('del');
var fs = require('fs');
var runSequence = require('run-sequence');
var browserSync = require('browser-sync');
//
// Gulp config
//
// Override defaults with custom local config
try {
var localConfig = require('./gulpconfig.json');
} catch (err) {
var localConfig = {
bs: {
proxy: "www.bubs.dev",
logLevel: "info",
tunnel: "",
open: false
}
};
}
// Build themeDir variable based on current theme from config file, fallback to default
var themeRoot = 'wp-content/themes/';
var theme = localConfig.activeTheme || 'timber';
var themeDir = themeRoot + theme;
// Defaults
var config = {
theme: themeDir,
assets: themeDir + '/assets',
dist: themeDir + '/dist',
dev: themeDir + '/dev',
output: themeDir + '/dev', // default to dev
static: themeDir + '/static',
init: './_init'
};
// in production tasks, we set this to true
var isProduction = false;
// Error Handling
var handleErrors = function() {
var args = Array.prototype.slice.call(arguments);
$.notify.onError({
title: 'Compile Error',
message: '<%= error.message %>'
}).apply(this, args);
if ( isProduction ) {
// Tell Travis to Stop Bro
process.exit(1);
}
this.emit('end');
};
//
// Gulp Tasks
//
gulp.task('styles', function() {
var sassOptions = {
outputStyle: 'expanded'
};
var sourcemapsOptions = {
debug: true
};
var nanoOptions = {
autoprefixer: {
browsers: ['> 1%', 'last 2 versions', 'IE >= 8'],
add: true
}
};
return gulp.src(config.assets + '/scss/*.scss')
.pipe($.if(!isProduction, $.sourcemaps.init()))
.pipe($.sass(sassOptions).on('error', handleErrors))
.pipe($.if(isProduction, $.cssnano(nanoOptions)))
.pipe($.if(!isProduction, $.sourcemaps.write(sourcemapsOptions)))
.pipe(gulp.dest( config.output + '/css' ))
.pipe(browserSync.stream());
});
gulp.task('scripts', function() {
var assets = $.useref({
searchPath: './'
}).on('error', handleErrors);
var uglifyOptions = {
mangle: false,
compress: {
drop_console: true
}
};
return gulp.src( config.theme + '/views/layout.twig' )
.pipe(assets)
.pipe($.if('*.js', $.uglify(uglifyOptions).on('error', handleErrors)))
.pipe(gulp.dest( config.output ));
});
// copy unmodified files
gulp.task('copy', function (cb) {
return gulp.src( config.assets + '/{img,fonts}/**/*', {base: config.assets})
.pipe($.changed( config.output ))
.pipe(gulp.dest( config.output ));
});
// loops through the generated html and replaces all references to static versions
gulp.task('rev', function (cb) {
return gulp.src( config.dist + '/{css,js,fonts,img}/**/*' )
.pipe($.rev())
.pipe($.revCssUrl())
.pipe(gulp.dest( config.static ))
.pipe($.rev.manifest())
.pipe(gulp.dest( config.static ))
});
gulp.task('staticHeaders', function() {
return gulp.src( config.init + '/static.htaccess', { base: '' } )
.pipe($.rename(".htaccess"))
.pipe(gulp.dest( config.static ));
});
// clean output directory
gulp.task('clean', function (cb) {
return del([config.dev, config.static, config.dist], cb);
});
gulp.task('browser-sync', function() {
browserSync.init(null, {
proxy: localConfig.bs.proxy,
open: localConfig.bs.open || true,
tunnel: localConfig.bs.tunnel || false,
logLevel: localConfig.bs.logLevel || 'info'
});
});
gulp.task('watch', function() {
gulp.watch([config.theme + '/**/*.{twig,php}'], browserSync.reload);
gulp.watch([config.assets + '/scss/**/*.scss'], ['styles']);
gulp.watch([config.assets + '/js/**/*.js'], ['scripts', browserSync.reload]);
gulp.watch([config.assets + '/{img,fonts}/**'], ['copy', browserSync.reload]);
});
//
// Multi-step tasks
//
// build production files
gulp.task('release', function (cb) {
isProduction = true;
config.output = config.dist;
runSequence('clean', ['styles', 'scripts', 'copy'], ['rev', 'staticHeaders'], cb);
});
gulp.task('default', function (cb) {
runSequence('clean', ['styles', 'scripts', 'copy'], ['watch', 'browser-sync'], cb);
});
|
/*global io,data*/
(function(){
// give up and resort to `target=_blank`
// if we're not modern enough
if (!document.body.getBoundingClientRect
|| !document.body.querySelectorAll
|| !window.postMessage) {
return;
}
// the id for the script we capture
var id;
// listen on setup event from the parent
// to set up the id
window.addEventListener('message', function onmsg(e){
if (/^slackin:/.test(e.data)) {
id = e.data.replace(/^slackin:/, '');
document.body.addEventListener('click', function(ev){
var el = ev.target;
while (el && 'A' != el.nodeName) el = el.parentNode;
if (el && '_blank' == el.target) {
ev.preventDefault();
parent.postMessage('slackin-click:' + id, '*');
}
});
window.removeEventListener('message', onmsg);
// notify initial width
refresh();
}
});
// notify parent about current width
var button = document.querySelector('.slack-button');
var lastWidth;
function refresh(){
var width = button.getBoundingClientRect().width;
if (top != window && window.postMessage) {
var but = document.querySelector('.slack-button');
var width = Math.ceil(but.getBoundingClientRect().width);
if (lastWidth != width) {
lastWidth = width;
parent.postMessage('slackin-width:' + id + ':' + width, '*');
}
}
}
// initialize realtime events asynchronously
var script = document.createElement('script');
script.src = 'https://cdn.socket.io/socket.io-1.3.2.js';
script.onload = function(){
// use dom element for better cross browser compatibility
var url = document.createElement('a');
url.href = window.location;
var socket = io({path: (url.pathname + '/socket.io').replace('//','/')});
var count = document.getElementsByClassName('slack-count')[0];
socket.on('data', function(users){
for (var i in users) update(i, users[i]);
});
socket.on('total', function(n){ update('total', n) });
socket.on('active', function(n){ update('active', n) });
var anim;
function update(key, n) {
if (n != data[key]) {
data[key] = n;
var str = '';
if (data.active) str = data.active + '/';
if (data.total) str += data.total;
if (!str.length) str = '–';
if (anim) clearTimeout(anim);
count.innerHTML = str;
count.className = 'slack-count anim';
anim = setTimeout(function(){
count.className = 'slack-count';
}, 200);
refresh();
}
}
};
document.body.appendChild(script);
})();
|
import React from 'react';
import PropTypes from 'prop-types';
import { View } from 'react-native';
import { Text } from 'native-base';
import Colors from '../../../native-base-theme/variables/commonColor';
const Messages = ({ message, type }) => (
<View
style={{
backgroundColor:
type === 'error' ? Colors.brandDanger : type === 'success' ? Colors.brandSuccess : Colors.brandInfo,
paddingVertical: 10,
paddingHorizontal: 5,
}}
>
<Text style={{ color: '#fff', textAlign: 'center' }}>{message}</Text>
</View>
);
Messages.propTypes = {
message: PropTypes.string,
type: PropTypes.oneOf(['error', 'success', 'info']),
};
Messages.defaultProps = {
message: 'An unexpected error came up',
type: 'error',
};
export default Messages;
|
function updateImprovementsDisplay(i) {
updateDisplay(
'desc_improvements',
`improvements: ${i}`
);
}
function updateGenerationsDisplay(g) {
updateDisplay(
'desc_generations',
`generations: ${g}`
);
}
function updateBestSimilarityDisplay(s) {
updateDisplay(
'best_desc_similarity',
`${s}% similar`
);
}
function updateScratchSimilarityDisplay(s) {
updateDisplay(
'scratch_desc_similarity',
`${s}% similar`
);
}
function updateScratchPhaseIdDisplay(id, n) {
updateDisplay(
'scratch_desc_phasenum',
`phase: ${id + 1} / ${n}`
);
}
function updateScratchTemperatureDisplay(t) {
updateDisplay(
'scratch_desc_temp',
`temperature: ${t}`
);
}
function updateScratchPhasePercentageDisplay(tries, max) {
const percentDone = (100 * tries / max).toFixed()
updateDisplay(
'scratch_desc_phase_percentage',
`phase progress: ${percentDone}%`
);
}
function updateDisplay(name, value) {
document.getElementById(name).innerHTML = value;
}
export {
updateImprovementsDisplay,
updateGenerationsDisplay,
updateBestSimilarityDisplay,
updateScratchSimilarityDisplay,
updateScratchPhaseIdDisplay,
updateScratchTemperatureDisplay,
updateScratchPhasePercentageDisplay,
};
|
import { createAction } from "redux-actions";
export default createAction("MARK_BLOCK");
|
/*
This is the example config file used to demonstrate
turning leds of different types and protocols on and off.
*/
// converts a number to a hex
function toHex(c) {
var hex = c.toString(16);
hex = hex.length == 1 ? "0" + hex : hex;
return "0x" + hex;
}
// formats an input to be received by a tri-color gpio led
function triGpioColor(c) {
if(c === 1) return 1;
if(c === 0) return 0;
var isArray = Array.isArray(c);
if(isArray && this._component.name === 'red') return c[0] === 255 ? 1 : 0;
if(isArray && this._component.name === 'blue') return c[1] === 255 ? 1: 0;
if(isArray && this._component.name === 'green') return c[2] === 255 ? 1: 0;
return c;
}
// formats the input to be received by the blinkM led
function blinkMInput(c) {
if(c === 1) return [255, 255, 255];
if(c === 0) return [0, 0, 0];
return [c[0] ,c[1],c[2]];
}
// formats the input to be received by a 5050led (apa102)
var apaIdx = 0;
function apa102Input(c, cmd) {
if(c === 1) return [0xff, 0xff, 0xff, 0xff];
else if(c === 0) return [0xff, 0x00, 0x00, 0x00];
return [0xff, toHex(c[2]), toHex(c[1]), toHex(c[0])];
}
module.exports = {
"name":"hello-world-leds",
"i2c-path": '/dev/i2c-1',
"components" : [{"type":"led", "name":"blue", "direction": "out",
"address":17, "interface": "gpio", "formatInput" : triGpioColor},
{"type":"led","name":"green", "address":27, "direction": "out",
"interface": "gpio", formatInput: triGpioColor},
{"type":"led","name":"red","address":22, "direction": "out",
"interface": "gpio", formatInput: triGpioColor },
{type:"led",path: 1, address: 0x09, "name":"blinkm",
interface: "i2c",
init: {type: 'write', cmd: 0x6f},
set:{type: 'write', cmd:0x6e , formatInput: blinkMInput}},
{type: "led", interface: "spi", name: "apa102",
address: "/dev/spidev0.0", set: [
{val: new Buffer(32).fill(0)},{formatInput: apa102Input}]}
]
};
|
const merge = require('webpack-merge');
const common = require('./webpack.common.js');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
module.exports = merge(common, {
module: {
rules: [{
test: /\.css$/,
use: ExtractTextPlugin.extract({
use: 'css-loader',
fallback: 'style-loader',
}),
}],
},
plugins: [
new webpack.optimize.UglifyJsPlugin(),
new ExtractTextPlugin({
filename: 'css/[name].css?[hash]-[chunkhash]-[contenthash]-[name]',
}),
],
});
|
const Request = require('request');
const env2 = require('env2');
const HapiCookie = require('hapi-auth-cookie');
env2('./config.env');
module.exports = {
path: '/welcome',
method: 'GET',
handler: (req, rep) => {
const accessUrl = `https://github.com/login/oauth/access_token`;
Request.post({
headers: {
// as recommended by the API documentation
Accept: `application/json`
},
url: accessUrl,
form: {
client_id: process.env.CLIENT_ID,
client_secret: process.env.CLIENT_SECRET,
code: req.query.code
}
}, (err, res, body) => {
if (err) throw err;
let parsed = JSON.parse(body);
const userToken = {
access_token: parsed.access_token
};
Request.get({
headers: {
'User-Agent': 'GitPom',
// as recommended by the API documentation
Accept: `application/json`,
Authorization: `token ${userToken.access_token}`
},
url: `https://api.github.com/user`
}, (err, res, body) => {
if (err) throw err;
parsed = JSON.parse(body);
const userDetails = {
userName: parsed.login,
avatarUrl: parsed.avatar_url
};
// set the cookie containing the token, the username and the avatar url
req.cookieAuth.set(Object.assign(userToken, userDetails));
rep(`<a id="continue" href="/"></a>
<script>
window.addEventListener('load', function(){
document.getElementById("continue").click();
})
</script>`);
});
});
}
};
|
describe('Events:', function() {
var it_prepends_to_the_jobs_list_view = function() {
it('prepends to the jobs list view', function() {
expect_text('#jobs li:first-child', this.data.repository.name + ' #' + this.data.number)
});
};
var it_removes_the_job_from_the_jobs_list_view = function() {
it('removes the job from the jobs list view', function() {
expect($('#jobs li.empty').attr('style').match('display: none')).toBeFalsy();
});
};
describe('the job queue', function() {
beforeEach(function() {
this.repository = INIT_DATA.repositories[1];
go_to('#!/' + this.repository.name)
});
describe('an incoming event for the current build', function() {
describe('build:queued', function() {
beforeEach(function() {
this.data = build_queued_data(this.repository, { number: 2 });
Travis.app.trigger('build:queued', this.data);
waitsFor(jobs_list_populated(1));
});
it_prepends_to_the_jobs_list_view();
});
describe('build:started', function() {
beforeEach(function() {
this.data = build_started_data(this.repository);
Travis.app.trigger('build:started', this.data);
});
it_removes_the_job_from_the_jobs_list_view();
});
});
});
});
|
const {npmPublishPackage, npmPublishAll} = require(`../../utils/publish`);
module.exports = {
command: `package <packageName>`,
desc: `Publish a package to NPM`,
builder: {},
handler: ({packageName}) => {
if (packageName) {
switch (packageName.toLowerCase()) {
case `all`:
return npmPublishAll();
default:
return npmPublishPackage(packageName);
}
}
return false;
}
};
|
/**
* A Node.js module object. Every Node.js module receives a reference to
* itself through a local variable named "module", and its global context.
*
* @external module
* @see https://nodejs.org/api/modules.html#modules_the_module_object
*/
/**
* The Node.js built-in "path" module.
*
* @external path
* @see https://nodejs.org/api/path.html
*/
/**
* @member external:path.posix
* @see https://nodejs.org/api/path.html#path_path_posix
*/
/**
* @member external:path.win32
* @see https://nodejs.org/api/path.html#path_path_win32
*/
/**
* The Node.js built-in "util" module.
*
* @external util
* @see https://nodejs.org/api/util.html
*/
/**
* @see https://nodejs.org/api/util.html#util_util_format_format_args
*
* @function external:util.format
* @param {string} format - A printf-like format string.
* @param {...*} args - Replacement values.
*/
/**
* A Moment.js date time object.
*
* @external moment
* @see https://momentjs.com/docs/
*/
/**
* A lignin plug-in.
*
* @global
* @class Plugin
* @param {string} id - An instance identifier, provided for auditing.
* @param {Object} options - The options available to the configuration,
* used to construct the new plug-in instance.
* @param {ConfigurationState} context - The global logging configuration,
* used to resolve references to level names, filter names and plugin names.
*/
/**
* Performs asynchronous initialization. Since plug-ins may depend on
* configured filters and appenders, a recursive dependency resolution
* strategy is employed, as follows.
*
* <ol>
* <li>Attempt to invoke this method for all filters, then appenders.</li>
* <li>Those not responding are assumed to have initialized synchronously
* from the constructor.</li>
* <li>Those resolving to a truthy value or <code>undefined</code> are assumed
* properly initialized.</li>
* <li>Those resolving to any other value are assumed not yet able to
* initialize due to missing dependencies, and will be retried later.</li>
* <li>If all filters and appenders had finished initializing, configuration
* will proceed to initializing loggers.</li>
* <li>If some filters or appenders had finished initializing at this
* iteration, all plug-in instances that could not initialize at the previous
* iteration are retried with the same rules.</li>
* <li>If no filters or appenders could initialize in this iteration, while
* some are still pending initialization, an error will be thrown to indicate
* that their initialization conditions cannot be satisfied.</li>
* </ol>
*
* @method Plugin#setup
* @returns {boolean|Promise.<boolean>} A promise of initialization
* completion.
*/
/**
* Releases resources held by this instance. If implemented, it will be
* invoked before releasing the plug-in (for reconfiguration or termination),
* and be awaited for (if possible).
*
* @method Plugin#close
* @returns {Promise} A promise of termination completion.
*/
/**
* Filters a logging message. A filter plug-in must implement this method.
* It may transform, select or replace messages received by loggers and
* appenders.
*
* <ul>
* <li>If a message is dropped from a logger, it will not be received by
* subsequent filters, current appenders and parent loggers.</li>
* <li>If a message is replaced or transformed in a logger, the changes will
* be visible to subsequent filters, current appenders and parent
* loggers.</li>
* <li>Appenders are implemented by plug-ins, which may define their own
* processing rules for filters. It is recommended that implementors follow
* similar rules: changes should only be visible to subsequent filters first
* (if using a filter chain), then finally to the appender itself.</li>
* </ul>
*
* @method Plugin#filter
* @param {record} record - The message to process.
* @returns {Promise.<?record>} A promise for the original or replaced
* message for further processing, or <code>null</code> to prevent it from
* being further processed. Rejections will generate error events, instead of
* being logged anywhere, to prevent rejection loops. The original message
* and the offending plug-in will be part of the event data for auditing.
*/
/**
* Appends the message to some medium. An appender plug-in must implement this
* method. Appenders should not mutate the received log records, but that
* requirement will not be enforced. The logger will attempt to deliver a
* clone of the original log record, to prevent mutations from affecting other
* appenders, but some custom data in the record may not be cloneable or may
* not clone deeply enough for all use cases.
*
* @method Plugin#append
* @param {record} record - The message to record.
* @returns {Promise} A promise of completion. Rejections will generate
* error events, instead of being logged anywhere, to prevent rejection loops.
* The original message and the offending plug-in will be part of the event
* data for auditing.
*/
/**
* A log record. It is generated by loggers, and contains some standard fields
* for processing by filters and appenders. Other non-standard fields may be
* added by filters. If the record itself or any of its nested objects
* implement a <code>clone</code> method, it will be used to generate a clone
* of that object for appenders.
*
* @typedef {Object} record
* @property {string} message - The formatted message to be logged.
* @property {string} level - The name of the verbosity level at which the
* message was recorded.
* @property {external:moment} timestamp - The date and time of when the
* record was generated.
* @property {string} category - The name of the logger from which this record
* originated.
*/
|
/*
* The MainMenu state displays the game menu and enters the Game state after the user clicks the screen.
*/
Game.MainMenu = function(game) {
};
Game.MainMenu.prototype = {
create: function() {
this.add.sprite(0, 0, 'titlepage');
this.loadingText = this.add.text(510, 520, 'Click to start playing', {
font: '24px monospace',
fill: '#fff'
});
this.loadingText.anchor.setTo(0.5, 0.5);
},
update: function() {
if (this.input.activePointer.isDown) {
// The user is clicking, so enter the Game state where the actual game is played
this.state.start('Game');
}
}
};
|
const Path = require('path');
const webpack = require('webpack');
// Import the core config
const webpackConfig = require('@silverstripe/webpack-config');
const {
resolveJS,
externalJS,
moduleJS,
pluginJS,
moduleCSS,
pluginCSS,
} = webpackConfig;
const ENV = process.env.NODE_ENV;
const PATHS = {
MODULES: 'node_modules',
FILES_PATH: '../',
ROOT: Path.resolve(),
SRC: Path.resolve('client/src'),
DIST: Path.resolve('client/dist'),
THIRDPARTY: Path.resolve('thirdparty'),
};
const config = [
{
name: 'js',
entry: {
'segment-field': `${PATHS.SRC}/bundles/segment-field.js`,
},
output: {
path: PATHS.DIST,
filename: 'js/[name].js',
},
devtool: (ENV !== 'production') ? 'source-map' : '',
resolve: resolveJS(ENV, PATHS),
externals: externalJS(ENV, PATHS),
module: moduleJS(ENV, PATHS),
plugins: pluginJS(ENV, PATHS),
},
{
name: 'css',
entry: {
'segment-field': `${PATHS.SRC}/styles/segment-field.scss`,
},
output: {
path: PATHS.DIST,
filename: 'styles/[name].css'
},
devtool: (ENV !== 'production') ? 'source-map' : '',
module: moduleCSS(ENV, PATHS),
plugins: pluginCSS(ENV, PATHS),
},
];
module.exports = config;
|
export const getMockState = {
withNoNotes: ()=>({
byId: {},
ids: [],
openNoteId: null
}),
withOneNote: ()=>({
byId: {
'id-123': {
id: 'id-123',
content: 'Hello World',
timestamp: 1
}
},
ids: ['id-123'],
openNoteId: 'id-123'
}),
withTwoNotes: ()=>({
byId: {
'id-123': {
id: 'id-123',
content: 'Hello World',
timestamp: 1
},
'id-456': {
id: 'id-456',
content: 'Hello World 456',
timestamp: 2
}
},
ids: ['id-123', 'id-456'],
openNoteId: 'id-456'
}),
withNoOpenNotes: ()=>({
byId: {
'id-123': {
id: 'id-123',
content: 'Hello World',
timestamp: 1
}
},
ids: ['id-123'],
openNoteId: null
})
};
|
'use strict';
const path = require('path');
const { logError } = require('./util/logger');
const config = {
user: process.env.MC_USER,
pass: process.env.MC_PASS,
serverHost: process.env.MC_SERVER_HOST || 'simpvp.net',
serverPort: process.env.MC_SERVER_PORT || 25565,
logFilePath: process.env.LOG_FILE_PATH || path.join(__dirname, '..', 'data', 'master.log'),
markovOrder: 2
};
Object.keys(config).forEach((key) => {
if (!config[key]) {
logError(`WARNING: Missing configuration value: ${key}`);
}
});
module.exports = config;
|
'use strict';
angular.module(
'webtypesetting.questions',
[ 'sf.services', 'palaso.ui.listview', 'palaso.ui.typeahead', 'ui.bootstrap' ]
)
.controller('QuestionsCtrl', ['$scope', 'questionsService', '$routeParams', 'sessionService', 'linkService', 'breadcrumbService',
function($scope, questionsService, $routeParams, ss, linkService, bcs) {
var projectId = $routeParams.projectId;
var textId = $routeParams.textId;
$scope.projectId = projectId;
$scope.textId = textId;
$scope.projectName = $routeParams.projectName;
$scope.textName = $routeParams.textName;
// Rights
$scope.rights = {};
$scope.rights.deleteOther = false;
$scope.rights.create = false;
$scope.rights.editOther = false; //ss.hasRight(ss.realm.SITE(), ss.domain.PROJECTS, ss.operation.EDIT_OTHER);
$scope.rights.showControlBar = $scope.rights.deleteOther || $scope.rights.create || $scope.rights.editOther;
// Listview Selection
$scope.newQuestionCollapsed = true;
$scope.selected = [];
$scope.updateSelection = function(event, item) {
var selectedIndex = $scope.selected.indexOf(item);
var checkbox = event.target;
if (checkbox.checked && selectedIndex == -1) {
$scope.selected.push(item);
} else if (!checkbox.checked && selectedIndex != -1) {
$scope.selected.splice(selectedIndex, 1);
}
};
$scope.isSelected = function(item) {
return item != null && $scope.selected.indexOf(item) >= 0;
};
// Listview Data
$scope.questions = [];
$scope.queryQuestions = function() {
console.log("queryQuestions()");
questionsService.list(projectId, textId, function(result) {
if (result.ok) {
$scope.questions = result.data.entries;
$scope.questionsCount = result.data.count;
$scope.enhanceDto($scope.questions);
$scope.text = result.data.text;
$scope.project = result.data.project;
$scope.text.url = linkService.text(projectId, textId);
bcs.updateMap('project', $scope.project.id, $scope.project.name);
bcs.updateMap('text', $scope.text.id, $scope.text.title);
var rights = result.data.rights;
$scope.rights.deleteOther = ss.hasRight(rights, ss.domain.QUESTIONS, ss.operation.DELETE_OTHER);
$scope.rights.create = ss.hasRight(rights, ss.domain.QUESTIONS, ss.operation.CREATE);
$scope.rights.editOther = ss.hasRight(rights, ss.domain.TEXTS, ss.operation.EDIT_OTHER);
$scope.rights.showControlBar = $scope.rights.deleteOther || $scope.rights.create || $scope.rights.editOther;
}
});
};
// Remove
$scope.removeQuestions = function() {
console.log("removeQuestions()");
var questionIds = [];
for(var i = 0, l = $scope.selected.length; i < l; i++) {
questionIds.push($scope.selected[i].id);
}
if (l == 0) {
// TODO ERROR
return;
}
questionsService.remove(projectId, questionIds, function(result) {
if (result.ok) {
$scope.selected = []; // Reset the selection
$scope.queryQuestions();
// TODO
}
});
};
// Add
$scope.addQuestion = function() {
console.log("addQuestion()");
var model = {};
model.id = '';
model.textRef = textId;
model.title = $scope.questionTitle;
model.description = $scope.questionDescription;
questionsService.update(projectId, model, function(result) {
if (result.ok) {
$scope.queryQuestions();
}
});
};
// Fake data to make the page look good while it's being designed. To be
// replaced by real data once the appropriate API functions are writen.
var fakeData = {
answerCount: -3,
viewsCount: -27,
unreadAnswers: -1,
unreadComments: -5
};
$scope.getAnswerCount = function(question) {
return question.answerCount;
};
$scope.getViewsCount = function(question) {
return fakeData.viewsCount;
};
$scope.getUnreadAnswers = function(question) {
return fakeData.unreadAnswers;
};
$scope.getUnreadComments = function(question) {
return fakeData.unreadComments;
};
$scope.enhanceDto = function(items) {
for (var i in items) {
items[i].url = linkService.question(projectId, textId, items[i].id);
}
};
}])
.controller('QuestionsSettingsCtrl', ['$scope', 'textService', 'sessionService', '$routeParams', function($scope, textService, ss, $routeParams) {
var projectId = $routeParams.projectId;
var textId = $routeParams.textId;
var dto;
$scope.projectId = projectId;
$scope.textId = textId;
$scope.editedText = {
id: textId,
}
// Get name from text service. This really should be in the DTO, but this will work for now.
// TODO: Move this to the DTO (or BreadcrumbHelper?) so we don't have to do a second server round-trip. RM 2013-08
var text;
textService.settings_dto($scope.projectId, $scope.textId, function(result) {
if (result.ok) {
$scope.dto = result.data;
$scope.textTitle = $scope.dto.text.title;
$scope.editedText.title = $scope.dto.text.title;
$scope.rights = {
editOther: ss.hasRight($scope.dto.rights, ss.domain.TEXTS, ss.operation.EDIT_OTHER),
};
}
});
$scope.updateText = function(newText) {
if (!newText.content) {
delete newText.content;
}
textService.update($scope.projectId, newText, function(result) {
if (result.ok) {
$scope.textTitle = newText.title;
$scope.showMessage = true;
}
});
}
}])
;
|
"use strict";
let merge = (nums, index, length, increasing) => {
if (length > 1) {
let half = Math.floor(length / 2);
for (let i = index; i < index + half; i++) {
if ((nums[i] > nums[i + half] && increasing) ||
(nums[i] < nums[i + half] && !increasing)) {
[nums[i], nums[i + half]] = [nums[i + half], nums[i]];
}
}
merge(nums, index, half, increasing);
merge(nums, index + half, half, increasing);
}
}
let bitonicSort = (nums, index = 0, length = nums.length, increasing = true) => {
if (length > 1) {
let half = Math.floor(length / 2);
bitonicSort(nums, index, half, true);
bitonicSort(nums, index + half, half, false);
merge(nums, index, length, increasing);
}
}
let nums = [1, 5, 77, 34, 2, 18, 19, 20, 21, 10, 43, 99, 101, 77, 75, 71]; // Must be pow of 2
console.log(nums);
bitonicSort(nums);
console.log(nums);
|
// ***********************************
// Firebase & jQuery HTML5 chat
// ***********************************
var messagesRef = new Firebase('https://cesarstechinsights.firebaseio.com');
// When the user presses enter on the message input, write the message to firebase.
$('#messageInput').keypress(function (e) {
if (e.keyCode == 13) {
var name = $('#nameInput').val();
var text = $('#messageInput').val();
messagesRef.push({name:name, text:text});
$('#messageInput').val('');
}
});
// Add a callback that is triggered for each chat message.
messagesRef.limit(40).on('child_added', function (snapshot) {
var message = snapshot.val();
$('<div/>')
.text(message.text)
.prepend($('<strong/>')
.text(message.name+': '))
.appendTo($('#messagesDiv'));
});
|
module.exports = {
name: "datastore",
ns: "nedb",
description: "Nedb Datastore",
phrases: {
active: "Creating datastore"
},
dependencies: {
npm: {
nedb: require('nedb')
}
},
ports: {
input: {
options: {
title: "Options",
type: "object",
required: false,
properties: {
filename: {
type: "string",
description: "path to the file where the data is persisted. If left blank, the datastore is automatically considered in-memory only. It cannot end with a ~ which is used in the temporary files NeDB uses to perform crash-safe writes",
required: false
},
inMemoryOnly: {
Title: "In Memory only",
type: "boolean",
description: "In Memory Only",
"default": false
},
onload: {
title: "Onload",
type: "function",
description: "if you use autoloading, this is the handler called after the loadDatabase. It takes one error argument. If you use autoloading without specifying this handler, and an error happens during load, an error will be thrown.",
required: false
},
afterSerialization: {
title: "After serialization",
type: "function",
description: "hook you can use to transform data after it was serialized and before it is written to disk. Can be used for example to encrypt data before writing database to disk. This function takes a string as parameter (one line of an NeDB data file) and outputs the transformed string, which must absolutely not contain a \n character (or data will be lost)",
required: false
},
beforeDeserialization: {
title: "Before Deserialization",
type: "function",
description: "reverse of afterSerialization. Make sure to include both and not just one or you risk data loss. For the same reason, make sure both functions are inverses of one another. Some failsafe mechanisms are in place to prevent data loss if you misuse the serialization hooks: NeDB checks that never one is declared without the other, and checks that they are reverse of one another by testing on random strings of various lengths. In addition, if too much data is detected as corrupt, NeDB will refuse to start as it could mean you're not using the deserialization hook corresponding to the serialization hook used before (see below)",
required: false
},
corruptAlertThreshold: {
type: "number",
description: "between 0 and 1, defaults to 10%. NeDB will refuse to start if more than this percentage of the datafile is corrupt. 0 means you don't tolerate any corruption, 1 means you don't care",
minValue: 0,
maxValue: 1,
required: false
}
}
}
},
output: {
db: {
title: "Database",
type: "Datastore"
},
error: {
title: "Error",
type: "Error"
}
}
},
fn: function datastore(input, $, output, state, done, cb, on, nedb) {
var r = function() {
var db = new nedb($.options);
db.loadDatabase(function(err) {
if (err) {
output({
error: $.create(err)
});
} else {
output({
db: $.create(db)
});
}
});
}.call(this);
return {
output: output,
state: state,
on: on,
return: r
};
}
}
|
import React from "react";
import { Link } from "react-imvc/component";
import Layout from "../component/Layout";
export default function View({ state }) {
return (
<Layout>
{state.contents.map(({ type, list }) => {
return (
<div key={type}>
<h2>
{type}
</h2>
<List data={list} />
</div>
);
})}
</Layout>
);
}
function List({ data }) {
return (
<ul>
{data.map(item => <ListItem key={item.url} {...item} />)}
</ul>
);
}
function ListItem({ title, url, raw, ...rest }) {
return (
<li>
{!!raw &&
<a href={url} {...rest}>
{title}
</a>}
{!raw &&
<Link to={url} {...rest}>
{title}
</Link>}
</li>
);
}
|
var sha1sum = require('sha1sum')
module.exports = function (emitter, state) {
//vvv will all be refactored out.
//using this right now, to get a MVP going.
//later, replace with a merkle tree.
//track changes in doc...
emitter.on('open', function (doc) {
function onUpdate () {
console.log('update', doc.key, sha1sum(doc.sources))
emitter.emit('_change', doc.key, sha1sum(doc.sources))
}
doc.on('_update', onUpdate)
doc.once('dispose', function () {
doc.removeListener('_update', onUpdate)
})
})
emitter.on('_change', function (key, hash) {
state[key] = hash
})
//refactor this out to use a correctly commutative datastructure here.
return function syncState(kv) {
var STATE = '__state'
kv.has(STATE, function (_, stat) {
//there is a little race condition here,
//because this isn't append only.
//FIX ME after mvp.
function onReady() {
console.log('ON READY', state)
var s = kv.put(STATE)
function write(k,v) {
console.log('STATE', k, v)
s.write([k, v])
}
for(var k in state)
write(k, state[k])
emitter.on('_change', write)
emitter.ready = true
emitter.emit('ready')
}
if(stat) {
//read the file...
kv.get(STATE)
.on('data', function (data) {
var key = data.shift()
var value = data.shift()
state[key] = value
})
.on('error', function () {
console.log('ERRO')
})
.once('close', onReady)
} else
onReady()
})
}
//^^^ replace with merkle tree.
}
|
var expect = require("chai").expect,
proxyquire = require("proxyquire"),
sinon = require("sinon");
var models = {};
var app = sinon.stub();
var auth = { authenticated: sinon.stub() };
var get = app.get = sinon.stub();
var post = app.post = sinon.stub();
var Country = models.Country = sinon.stub();
var Vote = models.Vote = sinon.stub();
var vote = proxyquire("../routes/vote", {
"../models": models,
"./auth": auth
});
describe("routes/vote", function() {
var req = {}, res = {};
var spy = res.render = sinon.spy();
var display, submit;
before(function() {
vote(app);
display = get.args[0][2];
submit = post.args[0][2];
});
beforeEach(function() {
spy.reset();
});
describe("GET voting page", function() {
var countries = [ { id: 1, name: "Narnia" },
{ id: 2, name: "Transylvania" }];
var promise = sinon.stub();
promise.then = sinon.stub();
beforeEach(function() {
Country.findAll = sinon.stub();
Country.findAll.returns(promise);
promise.then.callsArgWith(0, countries);
});
it("should render voting page", function() {
display(req, res);
expect(spy.calledOnce).to.equal(true);
expect(spy.args[0][0]).to.equal("vote");
});
it("should set page title and navbarActive properties", function() {
display(req, res);
var locals = spy.args[0][1];
expect(locals).to.have.property("title").that.equals("Vote");
expect(locals).to.have.property("navbarActive").that.equals("Vote");
});
it("should include countries in the response", function() {
display(req, res);
var locals = spy.args[0][1];
expect(locals).to.have.property("countries").that.deep.equals(countries);
});
it("should order the countries by name", function() {
display(req, res);
var call = Country.findAll.getCall(0);
expect(call.args[0]).to.have.property("order").that.equals("name ASC");
});
});
describe("POST /submit", function() {
var votes = [ { id: 1, score: 12 },
{ id: 2, score: 10 },
{ id: 3, score: 8 } ];
var req = {};
req.body = { data: JSON.stringify(votes) };
res.send = sinon.stub();
res.sendStatus = sinon.stub();
res.status = sinon.stub().returns(res);
var promise = sinon.stub();
promise.then = sinon.stub();
promise.catch = sinon.stub();
Vote.create = sinon.stub().returns(promise);
var user = req.user = {};
user.getGroup = sinon.stub().returns(promise);
var group = {id: 1};
beforeEach(function() {
Vote.create.reset();
Vote.create.returns(promise);
promise.then.reset();
promise.then.onFirstCall().yields([group]).returns(promise);
promise.then.yields();
});
it("should insert all the votes", function() {
submit(req, res);
expect(Vote.create.callCount).to.equal(votes.length);
for (var i = 0; i < Vote.create.callCount; i++) {
var call = Vote.create.getCall(i);
expect(call.calledWith(sinon.match({
CountryId: votes[i].id,
score: votes[i].score
})));
}
});
it("should respond OK if no error thrown", function() {
submit(req, res);
expect(res.sendStatus.calledWith(200)).to.equal(true);
});
it("should respond with an error message if there is an error", function() {
var err = "test error";
promise.then.onSecondCall().yields([err]);
submit(req, res);
expect(res.status.calledWith(500)).to.equal(true);
expect(res.send.calledOnce).to.equal(true);
});
});
});
|
export default class Topic {
constructor({text, likes = 0}) {
this.text = text;
this.likes = likes;
}
addLike() {
this.likes++;
}
removeLike() {
this.likes--;
}
}
|
import_module('Athena.Math');
v1 = new Athena.Math.Vector3(10, 20, 30);
v = v1.negate();
CHECK_CLOSE(-10, v.x);
CHECK_CLOSE(-20, v.y);
CHECK_CLOSE(-30, v.z);
|
'use strict';
/**
* Gulp Task - browserify
*/
var gulp = require('gulp'),
gulpif = require('gulp-if'),
config = require('../config.json'),
sourcemaps = require('gulp-sourcemaps'),
source = require('vinyl-source-stream'),
buffer = require('vinyl-buffer'),
browserify = require('browserify'),
watchify = require('watchify'),
browserSync = require('browser-sync'),
handleErrors = require('../utils/handle-errors');
gulp.task('browserify', function() {
var bundler = browserify(config.src + 'app/app.js', watchify.args),
bundle = function() {
return bundler
.bundle()
.on('error', handleErrors)
.pipe(source('main.js'))
.pipe(buffer())
.pipe(sourcemaps.init({loadMaps: false}))
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest(config.dist + config.javascript))
.pipe(gulpif(global.isWatching, browserSync.reload({stream: true})));
};
if (global.isWatching) {
bundler = watchify(bundler);
bundler.on('update', bundle);
}
return bundle();
});
|
import assert from 'assert';
import Extractor from '../src/extractor';
describe('Sentence word extraction', () => {
it('.match', function() {
let e = new Extractor([ 'what', 'is', 'the', 'weather', 'in', 'vancouver' ]);
let tag = {
label: 'location',
start: 5,
end: 5
};
let match = e.match(tag, ['weather', 'in', 'berlin']);
assert.deepEqual(match, { tag: [ 'berlin' ], start: 2, matches: 2 });
match = e.match(tag, ['weather', 'nowhere']);
assert.deepEqual(match, { tag: null, start: -1, matches: 0 });
match = e.match(tag, ['in', 'nowhere']);
assert.deepEqual(match, { tag: [ 'nowhere' ], start: 1, matches: 1 });
match = e.match(tag, ['weather', 'in', 'berlin', 'weather', 'in', 'chicago'], 2);
assert.deepEqual(match, { tag: [ 'chicago' ], start: 5, matches: 2 });
});
it('.match until the end of the sentence', function() {
let e = new Extractor([ 'say', 'hi', 'to', 'the', 'world' ]);
let tag = {
label: 'subject',
start: 4,
end: -1
};
let match = e.match(tag, ['say', 'hi', 'to', 'the', 'whole', 'wide', 'world']);
assert.deepEqual(match, {
tag: [ 'whole', 'wide', 'world' ],
start: 4,
matches: 4
});
});
it('.extract does basic sentence word matching', () => {
let e = new Extractor([ 'what', 'is', 'the', 'weather', 'in', 'vancouver' ]);
e.tag({
label: 'location',
start: 5,
end: 5
});
let result = e.extract([ 'hey', 'do', 'you', 'happen', 'to',
'know', 'the', 'weather', 'in', 'berlin' ]);
assert.deepEqual(result, { location: ['berlin'] });
result = e.extract([ 'what', '\'', 's', 'the', 'weather', 'in', 'chicago' ]);
assert.deepEqual(result, { location: [ 'chicago' ] });
});
it('.extract takes the best match and can match nothing', function() {
let e = new Extractor([ 'what', 'is', 'the', 'weather', 'in', 'vancouver' ]);
e.tag({
label: 'location',
start: 5,
end: 5
});
let result = e.extract([ 'weather', 'in', 'chicago',
'know', 'the', 'weather', 'in', 'berlin', 'weather', 'in', 'nuremberg' ]);
assert.deepEqual(result, { location: ['berlin'] });
result = e.extract([ 'weather', 'nowhere' ]);
assert.deepEqual(result, { location: null });
});
it('.extract multiple tag matching', function() {
let e = new Extractor([ 'what', 'is', 'the', 'weather', 'in',
'berlin', 'and', 'say', 'hi', 'to', 'the', 'world' ]);
e.tag({
label: 'location',
start: 5,
end: 5
});
e.tag({
label: 'subject',
start: 11,
end: -1
});
let result = e.extract([ 'do', 'you', 'know', 'the', 'weather', 'in',
'berlin', 'and', 'can', 'you', 'say', 'hi', 'to', 'the', 'wide', 'world' ]);
assert.deepEqual(result, { location: [ 'berlin' ], subject: [ 'wide', 'world' ]});
result = e.extract([ 'the', 'weather', 'in', 'tokyo' ]);
assert.deepEqual(result, { location: [ 'tokyo' ], subject: null });
result = e.extract(['say', 'hi', 'to', 'the', 'awesome', 'team']);
assert.deepEqual(result, { location: null, subject: ['awesome', 'team'] });
});
it.skip('.extract multiple tag matching uses previous tags', function() {
let e = new Extractor([ 'what', 'is', 'the', 'weather', 'in',
'nuremberg', 'tomorrow' ]);
e.tag({
label: 'location',
start: 5,
end: 5
});
e.tag({
label: 'time',
start: 6,
end: -1
});
// TODO
});
});
|
const filters = require('./filters');
const formats = require('./formats');
const tags = require('./tags');
const config = {
bootstrapNodes: [
{ address: 'router.bittorrent.com', port: 6881 },
{ address: 'dht.transmissionbt.com', port: 6881 },
],
crawler: {
address: '0.0.0.0',
port: 6881,
},
db: {
/*
* SQLITE DB
* client: 'sqlite3',
* connection: {
* filename: './db.sqlite3',
* },
* useNullAsDefault: true,
*/
client: 'mysql',
connection: {
database: 'alphareign',
host: '127.0.0.1',
password: 'alphareign',
user: 'root',
},
},
debug: false,
elasticsearch: {
host: '127.0.0.1',
port: 9200,
},
filters,
formats,
search: {
// Seconds between every bulk insert
frequency: 60,
// Amount of torrents to update in elasticsearch at once
limit: 1000,
},
tags,
tracker: {
// Minutes before we should try and update a torrent again
age: 360,
// Seconds between every scrape
frequency: 1,
host: 'udp://tracker.opentrackr.org:1337/announce',
limit: 75,
},
};
module.exports = config;
|
{
var progressSpy = jasmine.createSpy("progress");
var instance = axios.create({
onUploadProgress: progressSpy
});
instance.get("/foo");
getAjaxRequest().then(function(request) {
done();
});
}
|
/*!
* express-outdatedhtml
*
* Make sites outdated by replace the new HTML5 element names,
* such as 'canvas', 'section', etc. with proven ones like 'div'.
* This is happening on the fly by parsing
* the view render results string of the Express framework.
* Of course only if an outdated browser is detected,
* in this case the Internet Explorer smaller than 9,
* so the browser can handle the retrieved HTML correctly.
*
* Copyright(c) 2011 Felix Gertz <nihil.baxter.dev@gmail.com>
*
* MIT Licensed
*/
/*
* The key in this map is the replacement
* for an matching HTML5-element-name in the according value array.
*/
var replacemap = {
"div": ['canvas','section','summary', 'header','footer', 'nav', 'menu', 'aside', 'article', 'hgroup', 'figure', 'figcaption'],
"span": ['time', 'mark']
};
var useragent = require('useragent');
/**
* If the user-agent is an Internet Explorer smaller then 9,
* this function returns a callback that can be passed
* to the Express 'render'-function as third argument.
*
* The callback replaces HTML5 element names (canvas, section, ..)
* in the Express 'render'-'result'-string
* with proven element names (div, span) defined in the replacemap
* to gain old browser compatibility.
* Then sends the result.
*
* @param req Request object
* @param res Response object
* @param force Force execution of replacement, even if no matching user-agent is found. (optional)
* @param rendercallback Pass another Express render callback (optional)
*/
exports.makeoutdated = function(req, res, force, rendercallback) {
if(typeof force === 'function') {
rendercallback = force;
force = false;
}
var agent = useragent.parse(req.headers['user-agent']);
// Looking for IE smaller then major release 9
if(force || (agent.family == 'IE' && parseInt(agent.major) < 9))
return function(err, result) {
for(replacement in replacemap) {
var elements = replacemap[replacement].join("|");
result = result.
replace(new RegExp("<(?:"+elements+")", "gi"), "<"+replacement).
replace(new RegExp("(?:"+elements+")>", "gi"), replacement+">");
}
if(typeof rendercallback !== 'function')
res.send(result);
else
rendercallback(err, result);
};
// Nothing happens
return function(err, result) {
if(typeof rendercallback !== 'function')
res.send(result);
else
rendercallback(err, result);
};
};
|
var Backbone = require('backbone');
exports = module.exports = Backbone.Model.extend({
idAttribute: '_id',
defaults: {
roles: {
admin: false,
agent: false,
user: true,
app: false,
},
business: {
stage: 'test',
types: {
verify: false,
base: false,
whole: false
},
times: {
verify: 0,
vase: 0,
whole: 0
},
limit: -1,
expired: new Date()
},
app: {
app_id: '',
app_secret: '',
apis: {
verify: false,
base: false,
whole: false
}
},
balance: 0,
enable: true,
},
});
|
var express = require('express');
var router = express.Router();
var spider = require("./spider");
router.get("/info",function(req,res,next){
spider(`/product/iteminfo?device=iphone&channel=h5&swidth=375&sheight=667&zoneId=1479&v=2.3.0&terminal=wap&page=https%3A%2F%2Fm.haoshiqi.net%2F%23detail%3Fsid%3D14369%26channel_id%3Dh5&skuId=${req.query.id}`,function(data){
res.send(data);
});
})
router.get("/detail",function(req,res,next){
spider(`/product/productdetail?device=iphone&channel=h5&swidth=375&sheight=667&zoneId=1479&v=2.3.0&terminal=wap&page=https%3A%2F%2Fm.haoshiqi.net%2F%23detail%3Fsid%3D14435%26channel_id%3Dh5&productId=${req.query.id}`,function(data){
res.send(JSON.parse(data).data.graphicDetail); //返回产品的详细图片信息
});
})
module.exports =router;
|
module.exports = function(mode) {
return {
test: /\.js$/,
loader: "eslint-loader",
exclude: /node_modules/
};
};
|
// Math.random() devuelve número aleatorio entre 0 y 1.
var numero = Math.random();
if (numero <= 0.5){
console.log('\n' + numero + ' MENOR que 0,5 \n');
}
else{
console.log('\n' + numero + ' MAYOR que 0.5 \n');´
}
|
/**
* @venus-library jasmine
* @venus-include ../vendor/Reflection.js/reflection.min.js
* @venus-code ../src/functions.js
*/
describe('functions', function () {
it('should create two sub-objects of window', function () {
namespace('Foo.Bar');
expect(window.Foo).not.toBe(undefined);
expect(window.Foo.Bar).not.toBe(undefined);
delete window.Foo;
});
it('should create two sub-objects of own object', function () {
var custom = {};
namespace.call(custom, 'Foo.Bar');
expect(custom.Foo).not.toBe(undefined);
expect(custom.Foo.Bar).not.toBe(undefined);
});
it('should return nested value', function () {
var obj = {
foo: {
bar: {
baz: 'foobar'
}
}
};
expect(objectGetter.call(obj, 'foo.bar.baz')).toEqual('foobar');
});
it('should return undefined in case of unknown path', function () {
var obj = {};
expect(objectGetter.call(obj, 'foo.bar')).toEqual(undefined);
});
it('should set a nested value', function () {
var obj = {};
objectSetter.call(obj, 'foo.bar.baz', 'foobar');
expect(obj.foo.bar.baz).toEqual('foobar');
});
it('should return the value via the specific getter', function () {
var mock = function () {this.foo = 24;},
data = {};
mock.prototype = Object.create(Object.prototype, {
getFoo: {value: function () {return 42;}}
});
data.bar = new mock();
expect(reflectedObjectGetter.call(data, 'bar.foo')).toEqual(42);
});
it('should return the value via the generic getter', function () {
var mock = function () {this.foo = 24;},
data = {};
mock.prototype = Object.create(Object.prototype, {
get: {value: function (prop) {return prop;}}
});
data.bar = new mock();
expect(reflectedObjectGetter.call(data, 'bar.foo')).toEqual('foo');
});
it('should return the value via the property', function () {
var mock = function () {this.foo = 24;},
data = {};
data.bar = new mock();
expect(reflectedObjectGetter.call(data, 'bar.foo')).toEqual(24);
});
});
|
// https://sourceforge.net/rest/p/nagios
|
const regAttr = /="*'*\{*([_a-z\-0-9$]+)}*'*"*/;
const regStart = /^\[/;
const $ = window.rb.$;
/**
* Finds attribute linked elements on the first element in collection.
* @function external:"jQuery.fn".attrLinked
* @param {String} attributeSelector Attribute selector pattern to search for. ("[aria-controls="${id}"]")
* @returns {jQueryfiedObject}
*
* @example
*
* //<div id="yo"></div>
* //<a data-target="yo"></a>
*
* $('#yo').attrLinked('data-target={id}'); // returns '[data-target="yo"]' elements.
* $('#yo').attrLinked('data-target={id}').attrLinked('id={data-target}'); // returns '[id="yo"]' elements.
*/
$.fn.attrLinked = function (attributeSelector) {
let newCollection;
let elem = this.get(0);
if (elem) {
const valueAttr = attributeSelector.match(regAttr);
if(valueAttr){
let value = elem[valueAttr[1]];
if(!value || typeof value != 'string'){
value = elem.getAttribute(valueAttr[1]) || '';
}
if(!regStart.test(attributeSelector)){
attributeSelector = `[${attributeSelector}]`;
}
newCollection = $(attributeSelector.replace(regAttr, `="${value}"`));
}
}
return newCollection || $([]);
};
|
import React, { Component } from 'react' ;
import { connect } from 'reslice' ;
import Footer from './footer' ;
import AddTodo from './addtodo' ;
import TodoList from './todolist' ;
/**
* Top-level component. Embeds the AddTodo, TodoList and Footer
* (application) components. These are each passed their slice of
* the tree. Note that this requires the top-level of the store
* to have been correctly constructed (in ducks.js).
**/
class App extends Component {
onAddTodo = () => {
this.props.onAddTodo () ;
}
render () {
let { slice, filter } = this.props ;
return (
<div>
<AddTodo slice={ slice.addtodo } onAddTodo={ this.onAddTodo }/>
<TodoList slice={ slice.todolist } filter={ filter }/>
<Footer slice={ slice.footer } />
</div>
) ;
}
}
/**
* Map in state props. This being reslice, the slice is the argument,
* rather than the entire state tree. The currently selected filter is
* required, which is exposed via a selector function on the footer
* slice of the state tree.
**/
function mapStateToProps (slice) {
return {
filter: slice.footer.getFilter(),
} ;
}
/**
* Map in dispatcher props, here for the onAddTodo action. This is
* mapped to an action which is exposed as a method on the Apps
* slice (which is the slice argument to the function).
**/
function mapDispatchToProps (dispatch, slice) {
return {
onAddTodo: () => dispatch(slice.onAddTodo()),
} ;
}
export default connect(mapStateToProps, mapDispatchToProps)(App) ;
|
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
var _slicedToArray = (function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i['return']) _i['return'](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError('Invalid attempt to destructure non-iterable instance'); } }; })();
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
exports['default'] = catchErrors;
function catchErrors(_ref) {
var filename = _ref.filename;
var components = _ref.components;
var imports = _ref.imports;
var _imports = _slicedToArray(imports, 3);
var React = _imports[0];
var ErrorReporter = _imports[1];
var reporterOptions = _imports[2];
if (!React || !React.Component) {
throw new Error('imports[0] for react-transform-catch-errors does not look like React.');
}
if (typeof ErrorReporter !== 'function') {
throw new Error('imports[1] for react-transform-catch-errors does not look like a React component.');
}
return function wrapToCatchErrors(ReactClass, componentId) {
var originalRender = ReactClass.prototype.render;
ReactClass.prototype.render = function tryRender() {
try {
return originalRender.apply(this, arguments);
} catch (err) {
setTimeout(function () {
if (typeof console.reportErrorsAsExceptions !== 'undefined') {
var prevReportErrorAsExceptions = console.reportErrorsAsExceptions;
// We're in React Native. Don't throw.
// Stop react-native from triggering its own error handler
console.reportErrorsAsExceptions = false;
// Log an error
console.error(err);
// Reactivate it so other errors are still handled
console.reportErrorsAsExceptions = prevReportErrorAsExceptions;
} else {
throw err;
}
});
return React.createElement(ErrorReporter, _extends({
error: err,
filename: filename
}, reporterOptions));
}
};
return ReactClass;
};
}
module.exports = exports['default'];
|
/**
* @fileoverview Rule to flag use of Thai character
* @author Chang, Che-Jen
*/
'use strict';
// ------------------------------------------------------------------------------
// Requirements
// ------------------------------------------------------------------------------
const rule = require('../../../lib/rules/no-thai-character');
const RuleTester = require('eslint').RuleTester;
// ------------------------------------------------------------------------------
// Tests
// ------------------------------------------------------------------------------
const ruleTester = new RuleTester();
ruleTester.run('no-thai-character', rule, {
valid: [
'console.log("english");',
{
code: 'var str = `中文`;',
env: { es6: true },
},
'// ความคิดเห็นบรรทัดเดียว',
'/* หลายสายความคิดเห็น */',
{
code: `
import ตัวระบุ0 from 'xyz';
ตัวระบุ1 = { ตัวระบุ2: 0 };
var ตัวระบุ3 = function ตัวระบุ4() {};
this.ตัวระบุ5 = 0;
a[ตัวระบุ6] = 0;
export default ตัวระบุ7;
`,
parserOptions: {
ecmaVersion: 6,
sourceType: 'module',
},
},
],
invalid: [
{
code: 'var tpl = <Hello title=\'สวัสดี\'>คอมโพเนนท์</Hello>',
parserOptions: {
ecmaFeatures: {
jsx: true,
},
},
errors: [{
message: 'Using Thai characters: \'สวัสดี\'', type: 'Literal',
}, {
message: 'Using Thai characters: คอมโพเนนท์', type: 'JSXText',
}],
},
{
code: 'var tl = `อักษรแม่แบบ`',
env: { es6: true },
errors: [{ message: 'Using Thai characters: อักษรแม่แบบ', type: 'TemplateElement' }],
},
{
code: 'console.log(\'english\' + \'ไทย\');',
errors: [{ message: 'Using Thai characters: \'ไทย\'', type: 'Literal' }],
},
{
code: 'var str = \'ตัวแปร\'.substr(0, 1);',
errors: [{ message: 'Using Thai characters: \'ตัวแปร\'', type: 'Literal' }],
},
{
code: 'var obj = { \'key\': \'วัตถุ\' };',
errors: [{ message: 'Using Thai characters: \'วัตถุ\'', type: 'Literal' }],
},
{
code: 'var func = function(v){return v;}; func(\'ฟังก์ชัน\');',
errors: [{ message: 'Using Thai characters: \'ฟังก์ชัน\'', type: 'Literal' }],
},
{
code: 'var ary = ["อาร์เรย์"];',
errors: [{ message: 'Using Thai characters: "อาร์เรย์"', type: 'Literal' }],
},
{
code: `
import ตัวระบุ0 from 'xyz';
ตัวระบุ1 = { ตัวระบุ2: 0 };
var ตัวระบุ3 = function ตัวระบุ4() {};
this.ตัวระบุ5 = 0;
a[ตัวระบุ6] = 0;
export default ตัวระบุ7;
`,
parserOptions: {
ecmaVersion: 6,
sourceType: 'module',
},
options: [{
includeIdentifier: true,
}],
errors: [{
message: 'Using Thai characters: ตัวระบุ0',
type: 'Identifier',
}, {
message: 'Using Thai characters: ตัวระบุ1',
type: 'Identifier',
}, {
message: 'Using Thai characters: ตัวระบุ2',
type: 'Identifier',
}, {
message: 'Using Thai characters: ตัวระบุ3',
type: 'Identifier',
}, {
message: 'Using Thai characters: ตัวระบุ4',
type: 'Identifier',
}, {
message: 'Using Thai characters: ตัวระบุ5',
type: 'Identifier',
}, {
message: 'Using Thai characters: ตัวระบุ6',
type: 'Identifier',
}, {
message: 'Using Thai characters: ตัวระบุ7',
type: 'Identifier',
}],
},
],
});
|
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
info: >
The production CharacterClass :: [ [lookahead \notin {^}] ClassRanges ]
evaluates by evaluating ClassRanges to obtain a CharSet and returning
that CharSet and the boolean false
es5id: 15.10.2.13_A1_T17
description: Execute /[]/.exec("a[b\n[]\tc]d") and check results
---*/
__executed = /[]/.exec("a[b\n[]\tc]d");
//CHECK#1
if (__executed !== null) {
$ERROR('#1: /[]/.exec("a[b\\n[]\\tc]d") === false');
}
|
/* eslint-env mocha */
var assert = require('assert')
var resolveEnv = require('./')
var cases = [
['Simple test', 'Simple test', {}],
['Hello $NAME!', 'Hello world!', { NAME: 'world' }],
['[ $a1, $a2 ]', '[ 4, 8 ]', { a1: '4', a2: '8' }],
['http://$HOST:$PORT/', 'http://google.com:80/', { HOST: 'google.com', PORT: '80' }],
['${BIRD}s', 'Birds', { BIRD: 'Bird' }],
['${PART1}${PART2}', 'AB', { PART1: 'A', PART2: 'B' }],
['http://$HOST:$PORT$PATH?$QUERY', 'http://google.com:80/search?q=hello',
{ HOST: 'google.com', PORT: '80', PATH: '/search', QUERY: 'q=hello' }],
['mongodb://$DB_PORT_27017_TCP_ADDR:$DB_PORT_27017_TCP_PORT', 'mongodb://127.0.0.1:27017',
{ DB_PORT_27017_TCP_ADDR: '127.0.0.1', DB_PORT_27017_TCP_PORT: '27017' }]
]
describe('resolveEnv', function () {
cases.forEach(function (info) {
it('should resolve ' + info[0], function () {
var origEnv = process.env
process.env = info[2]
var actual = resolveEnv(info[0])
process.env = origEnv
assert.equal(actual, info[1])
})
})
})
|
import { inverse } from 'dummy/helpers/inverse';
import { module, test } from 'qunit';
module('Unit | Helper | inverse');
// Replace this with your real tests.
test('it works', function(assert) {
let result = inverse([42]);
assert.ok(result);
});
|
var PRAHA = {coordinates: [50.051611, 14.407032], type:"Point"}
module.exports = function(map) {
var geocoder = new google.maps.Geocoder();
var addrInputEl = document.getElementById('geoJumper');
addrInputEl.addEventListener('keydown', function codeAddress(ev) {
if (ev.keyCode === 13) {
var address = document.getElementById('geoJumper').value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var loc = results[0].geometry.location;
map.moveTo([loc.lat(), loc.lng()]);
console.log("success");
} else {
map.moveTo(PRAHA.coordinates);
// alert('Geocode was not successful for the following reason: ' + status);
}
});
}
}
);
};
|
'use strict';
module.exports = function (grunt) {
var files = [
"jsyg-wrapper/JSYG-wrapper.js",
"jsyg-point/JSYG.Point.js",
"jsyg-vect/JSYG.Vect.js",
"jsyg-matrix/JSYG.Matrix.js",
"jsyg-strutils/JSYG-strutils.js",
"jsyg-utils/JSYG-utils.js",
"jsyg-events/JSYG.Events.js",
"jsyg-stdconstruct/JSYG.StdConstruct.js"
];
var rep = "node_modules";
files = files.map(function(file) { return rep+"/"+file; });
files.push("JSYG.js");
grunt.initConfig({
concat: {
options: {
separator: '\n\n',
},
dist: {
src: files,
dest: 'dist/JSYG.js'
},
}
});
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.registerTask('default', ['concat']);
};
|
'use babel';
import RspecCopy from '../lib/main';
describe('RunInIterm', function() {
let workspaceElement;
beforeEach(function() {
workspaceElement = atom.views.getView(atom.workspace);
atom.packages.activatePackage('run-in-iterm');
});
describe('when the run-in-iterm:run event is triggered', function() {
it('run command on iTerm and send event', function() {
waitsFor('event', function(done) {
workspaceElement.addEventListener('run-in-iterm:run', function() {
done();
});
atom.commands.dispatch(workspaceElement, 'run-in-iterm:run');
});
});
});
});
|
// Upload Demo
// -----------------------------------
(function(window, document, $, undefined){
$(function () {
'use strict';
// Initialize the jQuery File Upload widget:
$('#fileupload').fileupload({
// Uncomment the following to send cross-domain cookies:
//xhrFields: {withCredentials: true},
// url: 'server/upload'
});
// Enable iframe cross-domain access via redirect option:
$('#fileupload').fileupload(
'option',
'redirect',
window.location.href.replace(
/\/[^\/]*$/,
'/cors/result.html?%s'
)
);
// Load existing files:
$('#fileupload').addClass('fileupload-processing');
$.ajax({
// Uncomment the following to send cross-domain cookies:
//xhrFields: {withCredentials: true},
url: $('#fileupload').fileupload('option', 'url'),
dataType: 'json',
context: $('#fileupload')[0]
}).always(function () {
$(this).removeClass('fileupload-processing');
}).done(function (result) {
$(this).fileupload('option', 'done')
.call(this, $.Event('done'), {result: result});
});
});
})(window, document, window.jQuery);
|
import nearestVector from 'ml-nearest-vector';
/**
* Calculates the distance matrix for a given array of points
* @ignore
* @param {Array<Array<number>>} data - the [x,y,z,...] points to cluster
* @param {function} distance - Distance function to use between the points
* @return {Array<Array<number>>} - matrix with the distance values
*/
export function calculateDistanceMatrix(data, distance) {
var distanceMatrix = new Array(data.length);
for (var i = 0; i < data.length; ++i) {
for (var j = i; j < data.length; ++j) {
if (!distanceMatrix[i]) {
distanceMatrix[i] = new Array(data.length);
}
if (!distanceMatrix[j]) {
distanceMatrix[j] = new Array(data.length);
}
const dist = distance(data[i], data[j]);
distanceMatrix[i][j] = dist;
distanceMatrix[j][i] = dist;
}
}
return distanceMatrix;
}
/**
* Updates the cluster identifier based in the new data
* @ignore
* @param {Array<Array<number>>} data - the [x,y,z,...] points to cluster
* @param {Array<Array<number>>} centers - the K centers in format [x,y,z,...]
* @param {Array <number>} clusterID - the cluster identifier for each data dot
* @param {function} distance - Distance function to use between the points
* @return {Array} the cluster identifier for each data dot
*/
export function updateClusterID(data, centers, clusterID, distance) {
for (var i = 0; i < data.length; i++) {
clusterID[i] = nearestVector(centers, data[i], {
distanceFunction: distance
});
}
return clusterID;
}
/**
* Update the center values based in the new configurations of the clusters
* @ignore
* @param {Array<Array<number>>} prevCenters - Centroids from the previous iteration
* @param {Array <Array <number>>} data - the [x,y,z,...] points to cluster
* @param {Array <number>} clusterID - the cluster identifier for each data dot
* @param {number} K - Number of clusters
* @return {Array} he K centers in format [x,y,z,...]
*/
export function updateCenters(prevCenters, data, clusterID, K) {
const nDim = data[0].length;
// copy previous centers
var centers = new Array(K);
var centersLen = new Array(K);
for (var i = 0; i < K; i++) {
centers[i] = new Array(nDim);
centersLen[i] = 0;
for (var j = 0; j < nDim; j++) {
centers[i][j] = 0;
}
}
// add the value for all dimensions of the point
for (var l = 0; l < data.length; l++) {
centersLen[clusterID[l]]++;
for (var dim = 0; dim < nDim; dim++) {
centers[clusterID[l]][dim] += data[l][dim];
}
}
// divides by length
for (var id = 0; id < K; id++) {
for (var d = 0; d < nDim; d++) {
if (centersLen[id]) {
centers[id][d] /= centersLen[id];
} else {
centers[id][d] = prevCenters[id][d];
}
}
}
return centers;
}
/**
* The centers have moved more than the tolerance value?
* @ignore
* @param {Array<Array<number>>} centers - the K centers in format [x,y,z,...]
* @param {Array<Array<number>>} oldCenters - the K old centers in format [x,y,z,...]
* @param {function} distanceFunction - Distance function to use between the points
* @param {number} tolerance - Allowed distance for the centroids to move
* @return {boolean}
*/
export function hasConverged(centers, oldCenters, distanceFunction, tolerance) {
for (var i = 0; i < centers.length; i++) {
if (distanceFunction(centers[i], oldCenters[i]) > tolerance) {
return false;
}
}
return true;
}
|
// nehan.tip.js
// Copyright(c) 2014-, Watanabe Masaki
// license: MIT
/**
plugin name: tip
description: create link that shows popup message when clicked.
tag_name: tip
close_tag: required
attributes:
- title: tip title
example:
<tip title="this is tip title">this text is popuped when clicked.</tip>
*/
Nehan.setStyle("tip", {
"display":"inline",
"background-color":"gold",
"color":"green",
// <tip title='cilck me'>some text</tip>
// => <a href='#' data-title='click me' data-content='some text'>click me</a>
"onload":function(selector_context){
var markup = selector_context.getMarkup();
var tip_title = markup.getAttr("title");
var tip_content = markup.getContent();
markup.setAlias("a");
markup.setAttr("href", "#" + tip_title);
markup.setData("title", tip_title);
markup.setData("content", tip_content);
markup.setContent(tip_title);
},
"oncreate":function(context){
var tip_content = context.box.style.getMarkupData("content");
context.dom.onclick = function(){
alert(tip_content);
return false;
};
}
});
|
// import third-party CSS
import 'bootstrap/dist/css/bootstrap.css';
import 'bootstrap/dist/css/bootstrap-theme.css';
import 'font-awesome/css/font-awesome.min.css';
import 'react-flex/index.css';
// import our own main CSS
import 'src/views/styles/styles.scss';
// import JS
// import 'bootstrap'; // bootstrap JS
import React from 'react';
import ReactDOM from 'react-dom';
import { AppContainer } from 'react-hot-loader';
import { browserHistory } from 'react-router';
import {
syncHistoryWithStore
} from 'react-router-redux';
import {
firebaseConfigs,
reduxFirebaseConfig
} from 'src/config/firebase.cfg'
import configureStore from './core/store';
import Root from './views/root';
import firebase from 'firebase';
import { getFirebase } from 'react-redux-firebase';
import { LoadOverlay } from 'src/views/components/overlays';
// choose config
let firebaseConfig;
if (process.env.NODE_ENV !== 'production') {
firebaseConfig = firebaseConfigs.test;
}
else {
firebaseConfig = firebaseConfigs.production;
}
// GO!
const store = configureStore(firebaseConfig, reduxFirebaseConfig);
const syncedHistory = syncHistoryWithStore(browserHistory, store);
const rootElement = document.getElementById('root');
console.log(`starting app using database "${firebaseConfig.projectId}"`);
if (module.hot) {
module.hot.accept('./views/root', () => {
render(require('./views/root').default);
});
}
// show a message while logging in
ReactDOM.render(
<LoadOverlay message="logging in..." className="color-lightred" />,
rootElement
);
// Wait until after authentication has finished before rendering the root
getFirebase().auth().onAuthStateChanged(function onAuthStateChanged(authData) {
// done! Let's kick this thing into gear!
// try {
ReactDOM.render(
<AppContainer>
<Root history={syncedHistory} store={store} />
</AppContainer>,
rootElement
);
// console.log("render success");
// }
// catch (err) {
// console.error(err.stack);
// }
});
//reduxFirebaseConfig.onAuthStateChanged = function onAuthStateChanged(authData) {
|
var React = require('react');
var Recommend = require('./recommend/index');
var ItemList = require('./itemList/index');
var Header = require('./header/index');
var Promo = require('./promo/index');
class Floor extends React.Component {
render() {
var {
imgUrl, title, originPrice, price
} = this.props;
return (<div className="m-floor">
<Header name="生鲜水果" links ={[{href:'www.taobao.com',word:'苹果'}]}/>
<ItemList />
<Recommend bgColor="#8dd514" words={[{href:'www.taobao.com',word:'水果'},{href:'www.taobao.com',word:'水果'}]} banner={{href:'www.taobao.com',imgUrl:'//img.alicdn.com/imgextra/i1/1910146537/TB2Y.NWfXXXXXbjXpXXXXXXXXXX_!!1910146537.jpg'}}/>
<Promo promos={[{href:'//www.taobao.com',imgUrl:'//img.alicdn.com/imgextra/i1/1910146537/TB2Ob4vfXXXXXclXpXXXXXXXXXX_!!1910146537.jpg'},{href:'//www.taobao.com',imgUrl:'//img.alicdn.com/imgextra/i1/1910146537/TB2Ob4vfXXXXXclXpXXXXXXXXXX_!!1910146537.jpg'}]}/>
</div>);
}
}
module.exports = Floor;
|
import React from 'react';
import { connect } from 'react-redux';
import { importLocations } from 'lib/actions/library';
const ImportPanel = ( props ) => {
const onImport = () => props.importLocations( this.textInput.value );
const saveRef = input => this.textInput = input;
return (
<div className="import form-horizontal">
<div className="form-group">
<label htmlFor="import__text" className="import__text__label">Location Data (as JSON)</label>
<textarea className="import__text form-control" id="import__text" rows="10" ref={ saveRef } />
</div>
<div className="form-group">
<button className="btn btn-lg btn-primary" onClick={ onImport }>Import Locations</button>
</div>
</div>
);
};
export default connect( null, { importLocations } )( ImportPanel );
|
/*!
* Angular Material Design
* https://github.com/angular/material
* @license MIT
* v1.0.0-rc5-master-6b1d758
*/
(function( window, angular, undefined ){
"use strict";
/**
* @ngdoc module
* @name material.components.subheader
* @description
* SubHeader module
*
* Subheaders are special list tiles that delineate distinct sections of a
* list or grid list and are typically related to the current filtering or
* sorting criteria. Subheader tiles are either displayed inline with tiles or
* can be associated with content, for example, in an adjacent column.
*
* Upon scrolling, subheaders remain pinned to the top of the screen and remain
* pinned until pushed on or off screen by the next subheader. @see [Material
* Design Specifications](https://www.google.com/design/spec/components/subheaders.html)
*
* > To improve the visual grouping of content, use the system color for your subheaders.
*
*/
angular
.module('material.components.subheader', [
'material.core',
'material.components.sticky'
])
.directive('mdSubheader', MdSubheaderDirective);
/**
* @ngdoc directive
* @name mdSubheader
* @module material.components.subheader
*
* @restrict E
*
* @description
* The `<md-subheader>` directive is a subheader for a section. By default it is sticky.
* You can make it not sticky by applying the `md-no-sticky` class to the subheader.
*
*
* @usage
* <hljs lang="html">
* <md-subheader>Online Friends</md-subheader>
* </hljs>
*/
function MdSubheaderDirective($mdSticky, $compile, $mdTheming, $mdUtil) {
return {
restrict: 'E',
replace: true,
transclude: true,
template: (
'<div class="md-subheader">' +
' <div class="md-subheader-inner">' +
' <span class="md-subheader-content"></span>' +
' </div>' +
'</div>'
),
link: function postLink(scope, element, attr, controllers, transclude) {
$mdTheming(element);
var outerHTML = element[0].outerHTML;
function getContent(el) {
return angular.element(el[0].querySelector('.md-subheader-content'));
}
// Transclude the user-given contents of the subheader
// the conventional way.
transclude(scope, function(clone) {
getContent(element).append(clone);
});
// Create another clone, that uses the outer and inner contents
// of the element, that will be 'stickied' as the user scrolls.
if (!element.hasClass('md-no-sticky')) {
transclude(scope, function(clone) {
// If the user adds an ng-if or ng-repeat directly to the md-subheader element, the
// compiled clone below will only be a comment tag (since they replace their elements with
// a comment) which cannot be properly passed to the $mdSticky; so we wrap it in our own
// DIV to ensure we have something $mdSticky can use
var wrapperHtml = '<div class="md-subheader-wrapper">' + outerHTML + '</div>';
var stickyClone = $compile(wrapperHtml)(scope);
// Append the sticky
$mdSticky(scope, element, stickyClone);
// Delay initialization until after any `ng-if`/`ng-repeat`/etc has finished before
// attempting to create the clone
$mdUtil.nextTick(function() {
getContent(stickyClone).append(clone);
});
});
}
}
}
}
MdSubheaderDirective.$inject = ["$mdSticky", "$compile", "$mdTheming", "$mdUtil"];
})(window, window.angular);
|
(function(){
var app = angular.module('postal', []);
app.controller('ResultsController',function(){
this.items = saves;
});
//I think this is the code needed to read in data from a JSON file, it doesn't work locally because of browser security. ReQuires a small change to the html
app.controller('findResults',function($scope,$http){
$http.get('monthly_sample.json')
.then(function(res){
$scope.monthly_sample = res.data
});
});
var saves = [
{
month: "1st September 2014",
amount: 280,
},
{
month:"1st October 2014",
amount: 210,
},
{
month:"1st November 2014",
amount:210,
},
{
month:"1st December 2014",
amount:140,
},
{
month:"1st January 2015",
amount:80,
},
];
})();
|
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M10 12c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zM6 8c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm0 8c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm12-8c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm-4 8c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm4-4c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm-4-4c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm-4-4c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2z" />
, 'GrainSharp');
|
export default function isNumber(e) { return typeof e === 'number'; }
|
/*
*Chris Samuel
* ksamuel.chris@icloud.com
*
* October 5, 2015
*
* Filename : Footer.js
*
* */
import React from 'react';
import {Link} from 'react-router';
import FooterStore from '../stores/FooterStore'
import FooterActions from '../actions/FooterActions';
class Footer extends React.Component {
constructor(props) {
super(props);
this.state = FooterStore.getState();
this.onChange = this.onChange.bind(this);
}
componentDidMount() {
FooterStore.listen(this.onChange);
FooterActions.getTopCharacters();
}
componentWillUnmount() {
FooterStore.unlisten(this.onChange);
}
onChange(state) {
this.setState(state);
}
render() {
let leaderboardCharacters = this.state.characters.map((character) => {
return (
<li key={character.characterId}>
<Link to={'/characters/' + character.characterId}>
<img className='thumb-md' src={'http://image.eveonline.com/Character/' + character.characterId + '_128.jpg'} />
</Link>
</li>
)
});
return (
<footer>
<div className='container'>
<div className='row'>
<div className='col-sm-5'>
<h3 className='lead'><strong>Information</strong> and <strong>Copyright</strong></h3>
<p>Powered by <strong>Node.js</strong>, <strong>MongoDB</strong> and <strong>React</strong> with Flux architecture and server-side rendering.</p>
<p>You may view the <a href='https://github.com/Alayode/facesOfspace'>Source Code</a> behind this project on GitHub.</p>
<p>© 2015 Kayode Alayode.</p>
</div>
<div className='col-sm-7 hidden-xs'>
<h3 className='lead'><strong>Leaderboard</strong> Top 5 Characters</h3>
<ul className='list-inline'>
{leaderboardCharacters}
</ul>
</div>
</div>
</div>
</footer>
);
}
}
export default Footer;
|
const BaseBundle = require('./base');
class TransactionBundle extends BaseBundle {
constructor (config) {
super(config);
this.get('/', this.index.bind(this));
this.post('/', this.create.bind(this));
}
async index (ctx) {
let entries = await this.ledger.getTransactions();
return { entries };
}
async create (ctx) {
const body = await ctx.parse();
let entry = await this.ledger.post(body);
ctx.status = 201;
ctx.set('Location', `${ctx.originalUrl}/${entry.id}`);
return { entry };
}
}
module.exports = TransactionBundle;
|
'use strict';
var agitoHttpRedirection = function() {
var action = {};
/**
* @type {String}
*/
action.name = 'http-redirection';
/**
* @type {String}
*/
action.protocol = 'http';
/**
* @param {http.ClientRequest} request - The HTTP request
* @param {http.ServerResponse} response - The HTTP response
* @param {Options} options - Action option
*/
action.fn = function(request, response, options) {
response.statusCode = options.code || 301;
response.setHeader('Location', options.target);
response.end();
};
return function() {
this.actions.push(action);
return this.done();
};
};
module.exports = agitoHttpRedirection;
|
import React from 'react';
import { withTheme } from '@material-ui/core';
const MuiColorChit = (props) => {
let { theme } = props;
let chitStyle = {
flexGrow: 0,
flexShrink: 0,
width: props.size === "small" ? '16px' : '24px',
height: props.size === "small" ? '16px' : '24px',
borderRadius: '50%',
background: props.color
}
let containerStyle = {
flexGrow: 0,
flexShrink: 0,
display: 'flex',
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
margin: props.isSelected ? '0px' : '8px',
width: props.isSelected ? '32px' : '24px',
height: props.isSelected ? '32px' : '24px',
borderRadius: '50%',
background: theme.palette.action.selected,
transition: theme.transitions.create(['width', 'height', 'margin']),
}
containerStyle.width = props.size === "small" ? '16px' : containerStyle.width;
containerStyle.height = props.size === "small" ? '16px' : containerStyle.height;
return (
<div
style={containerStyle}
onClick={props.onClick} >
<div
style={chitStyle}/>
</div>
)
};
export default withTheme()(MuiColorChit);
|
/**
* @author maurobuselli@gmail.com
*/
(function () {
'use strict';
angular.module('AngularPanelsApp.pages.form', ['ui.select', 'ngSanitize'])
.config(routeConfig);
/** @ngInject */
function routeConfig($stateProvider) {
$stateProvider
.state('form', {
url: '/form',
template : '<ui-view autoscroll="true" autoscroll-body-top></ui-view>',
abstract: true,
title: 'Form Elements',
sidebarMeta: {
icon: 'ion-compose',
order: 250,
},
})
.state('form.inputs', {
url: '/inputs',
templateUrl: 'app/pages/form/inputs/inputs.html',
title: 'Form Inputs',
sidebarMeta: {
order: 0,
},
})
.state('form.layouts', {
url: '/layouts',
templateUrl: 'app/pages/form/layouts/layouts.html',
title: 'Form Layouts',
sidebarMeta: {
order: 100,
},
})
.state('form.wizard',
{
url: '/wizard',
templateUrl: 'app/pages/form/wizard/wizard.html',
controller: 'WizardCtrl',
controllerAs: 'vm',
title: 'Form Wizard',
sidebarMeta: {
order: 200,
},
});
}
})();
|
/* eslint-disable */
/**
* This script will extract the internationalization messages from all components
and package them in the translation json files in the translations file.
*/
const fs = require('fs');
const nodeGlob = require('glob');
const transform = require('babel-core').transform;
const animateProgress = require('./helpers/progress');
const addCheckmark = require('./helpers/checkmark');
const pkg = require('../../package.json');
const presets = pkg.babel.presets;
const plugins = pkg.babel.plugins || [];
// const i18n = require('../../app/i18n');
// default locale for translations management, not for users!!
const DEFAULT_LOCALE='en';
// import { DEFAULT_LOCALE } from '../../app/containers/App/constants';
require('shelljs/global');
// Glob to match all js files except test files
const FILES_TO_PARSE = 'app/**/!(*.test).js';
// important:
// just english language, rest of them via crowdin!!!!!!!!
// const locales = i18n.appLocales;
const locales = ['en']
const newLine = () => process.stdout.write('\n');
// Progress Logger
let progress;
const task = (message) => {
progress = animateProgress(message);
process.stdout.write(message);
return (error) => {
if (error) {
process.stderr.write(error);
}
clearTimeout(progress);
return addCheckmark(() => newLine());
}
}
// Wrap async functions below into a promise
const glob = (pattern) => new Promise((resolve, reject) => {
nodeGlob(pattern, (error, value) => (error ? reject(error) : resolve(value)));
});
const readFile = (fileName) => new Promise((resolve, reject) => {
fs.readFile(fileName, (error, value) => (error ? reject(error) : resolve(value)));
});
const writeFile = (fileName, data) => new Promise((resolve, reject) => {
fs.writeFile(fileName, data, (error, value) => (error ? reject(error) : resolve(value)));
});
// Store existing translations into memory
const oldLocaleMappings = [];
const localeMappings = [];
// Loop to run once per locale
for (const locale of locales) {
oldLocaleMappings[locale] = {};
localeMappings[locale] = {};
// File to store translation messages into
const translationFileName = `app/translations/${locale}.json`;
try {
// Parse the old translation message JSON files
const messages = JSON.parse(fs.readFileSync(translationFileName));
const messageKeys = Object.keys(messages);
for (const messageKey of messageKeys) {
oldLocaleMappings[locale][messageKey] = messages[messageKey];
}
} catch (error) {
if (error.code !== 'ENOENT') {
process.stderr.write(
`There was an error loading this translation file: ${translationFileName}
\n${error}`
);
}
}
}
/* push `react-intl` plugin to the existing plugins that are already configured in `package.json`
Example:
```
"babel": {
"plugins": [
["transform-object-rest-spread", { "useBuiltIns": true }]
],
"presets": [
"latest",
"react"
]
}
```
*/
plugins.push(['react-intl'])
const extractFromFile = async (fileName) => {
try {
const code = await readFile(fileName);
// Use babel plugin to extract instances where react-intl is used
const { metadata: result } = await transform(code, { presets, plugins }); // object-shorthand
for (const message of result['react-intl'].messages) {
for (const locale of locales) {
const oldLocaleMapping = oldLocaleMappings[locale][message.id];
// Merge old translations into the babel extracted instances where react-intl is used
const newMsg = ( locale === DEFAULT_LOCALE) ? message.defaultMessage : '';
localeMappings[locale][message.id] = (oldLocaleMapping)
? oldLocaleMapping
: newMsg;
}
}
} catch (error) {
process.stderr.write(`Error transforming file: ${fileName}\n${error}`);
}
};
(async function main() {
const memoryTaskDone = task('Storing language files in memory');
const files = await glob(FILES_TO_PARSE);
memoryTaskDone()
const extractTaskDone = task('Run extraction on all files');
// Run extraction on all files that match the glob on line 16
await Promise.all(files.map((fileName) => extractFromFile(fileName)));
extractTaskDone()
// Make the directory if it doesn't exist, especially for first run
mkdir('-p', 'app/translations');
for (const locale of locales) {
const translationFileName = `app/translations/${locale}.json`;
try {
const localeTaskDone = task(
`Writing translation messages for ${locale} to: ${translationFileName}`
);
// Sort the translation JSON file so that git diffing is easier
// Otherwise the translation messages will jump around every time we extract
let messages = {};
Object.keys(localeMappings[locale]).sort().forEach(function(key) {
messages[key] = localeMappings[locale][key];
});
// Write to file the JSON representation of the translation messages
const prettified = `${JSON.stringify(messages, null, 2)}\n`;
await writeFile(translationFileName, prettified);
localeTaskDone();
} catch (error) {
localeTaskDone(
`There was an error saving this translation file: ${translationFileName}
\n${error}`
);
}
}
process.exit()
}());
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
let _ = require('lodash');
let async = require('async');
const pip_services3_commons_node_1 = require("pip-services3-commons-node");
const pip_services3_commons_node_2 = require("pip-services3-commons-node");
const pip_services3_facade_node_1 = require("pip-services3-facade-node");
class SmsOperationsV1 extends pip_services3_facade_node_1.FacadeOperations {
constructor() {
super();
this._dependencyResolver.put('sms', new pip_services3_commons_node_2.Descriptor('pip-services-sms', 'client', '*', '*', '1.0'));
}
setReferences(references) {
super.setReferences(references);
this._smsClient = this._dependencyResolver.getOneRequired('sms');
}
sendMessageOperation() {
return (req, res) => {
this.sendMessage(req, res);
};
}
sendMessage(req, res) {
let recipientId = req.param('recipient_id');
let recipientName = req.param('recipient_name');
let recipientPhone = req.param('recipient_phone');
let language = req.param('language');
let parameters = new pip_services3_commons_node_1.ConfigParams(this.getFilterParams(req));
let message = req.body || {};
if (recipientId != null) {
let recipient = {
id: recipientId,
name: recipientName,
phone: recipientPhone,
language: language
};
this._smsClient.sendMessageToRecipient(null, recipient, message, parameters, this.sendEmptyResult(req, res));
}
else {
this._smsClient.sendMessage(null, message, parameters, this.sendEmptyResult(req, res));
}
}
}
exports.SmsOperationsV1 = SmsOperationsV1;
//# sourceMappingURL=SmsOperationsV1.js.map
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.