code stringlengths 2 1.05M |
|---|
/**
* Created by mugen on 6/14/16.
*/
export class Pipe {
constructor (handler, stream) {
this.handler = handler;
this.stream = stream;
this.state = 1;
}
carry (data) {
if (this.state === 1) {
this.handler(data);
}
return !!this.state;
}
open () {
this.state = 1;
}
close () {
this.state = 0;
}
unlink () {
this.stream.pipes.splice(this.stream.pipes.indexOf(this), 1);
return this;
}
} |
'use strict'
module.exports = require('quiver-util/tape')
|
jQuery(document).ready(function($) {
MenuDragDrop.init();
});
|
// @flow
import * as React from 'react'
import styled from 'styled-components'
import { debounce } from 'lodash'
import Slider from 'material-ui/Slider'
import { FormattedMessage } from 'react-intl'
import messages from './messages'
export type Props = {
setMinBookmarks: (value: number) => void,
minBookmarks: number,
}
type State = {
minBookmarks: number,
}
class ColumnHeaderSetting extends React.PureComponent<Props, State> {
state: State = {
minBookmarks: 0,
}
componentWillMount() {
this.setState({ minBookmarks: this.props.minBookmarks })
}
handleSlider = (event: Event, value: number) => {
this.setState({ minBookmarks: value })
this._sendBookmark()
}
_sendBookmark = debounce(() => {
this.props.setMinBookmarks(this.state.minBookmarks)
}, 400)
render() {
const { minBookmarks } = this.state
return (
<Wrap>
<FormattedMessage {...messages.bookmarkFilter} /> {minBookmarks}
<Slider
min={0}
max={1000}
step={10}
defaultValue={minBookmarks}
value={minBookmarks}
onChange={this.handleSlider}
/>
</Wrap>
)
}
}
const Wrap = styled.div`
display: flex;
justify-content: center;
flex-direction: column;
color: #eee;
`
export default ColumnHeaderSetting
|
/**
* Created by chriswillingham on 2/6/14.
*/
var BaseView = Backbone.View.extend({
scope: {},
template: function(){
return '<h1>PLACEHOLDER</h1>';
},
initialize: function(){
},
getScope: function(){
return this.scope;
},
render: function(){
// this.unrender();
console.log("RENDERING");
var html = this.template(this.getScope());
this.$el.html(html);
return this;
},
unrender: function(){
// this.$el.html('');
},
bindTo: function(source, event, callback) {
source.bind(event, callback, this);
this.bindings = this.bindings || [];
this.bindings.push({ source: source, event: event, callback: callback });
},
unbindFromAll: function() {
_.each(this.bindings, function(binding) {
binding.source.unbind(binding.event, binding.callback);
});
this.bindings = []
},
leave: function() {
this.trigger('leave');
this.unbind();
this.unbindFromAll();
//COMPLETELY UNBIND THE VIEW
this.undelegateEvents();
$(this.el).removeData().unbind();
//Remove view from DOM
this.remove();
Backbone.View.prototype.remove.call(this);
}
}); |
"use strict";
const ports = {};
chrome.runtime.onConnect.addListener(function(port) {
ports[port.name] = port;
port.onDisconnect.addListener(function() {
delete ports[port.name];
ports[port.name] = null;
});
});
const userMenu = chrome.contextMenus.create({
title: "このユーザーの投稿を全削除(はてなスペース)",
id: "add-user",
documentUrlPatterns: [ "http://space.hatena.ne.jp/~/*" ],
contexts: [ "link" ],
onclick: function(info, tab) {
const url = info.linkUrl;
const regex = /^http:\/\/space.hatena.ne.jp\/(.*)\/$/;
if (regex.test(url)) {
const user = url.match(regex)[1];
for (let portId in ports) {
if (!ports[portId]) continue;
ports[portId].postMessage({
type: "delete",
user: user
});
}
} else {
throw new Error("Not user");
}
}
});
|
function mandelbrot(x,y,scale,angle,iterations) {
iterations=Math.min(15,Math.abs(iterations));
// use a single shader.
// another implementation used one shaderi source per int(iterations), but Odroid XU4 crashed on that. On U3, it was fine.
gl.mandelbrot = gl.mandelbrot || new Shader(null, '\
uniform sampler2D texture;\
uniform vec4 xform;\
uniform vec2 center;\
uniform float iterations; \
varying vec2 texCoord;\
mat2 mat=mat2(xform.xy,xform.zw);\
void main() {\
vec2 c=mat*(texCoord-center);\
vec2 z; \
vec2 nz=c; \
for (int iter = 0;iter <= 15; iter++){ \
if(iter>=int(iterations)) break; \
z = nz; \
nz = vec2(z.x*z.x-z.y*z.y, 2.0*z.x*z.y) + c ; \
} \
vec2 pos=mix(z,nz,fract(iterations));\
gl_FragColor = texture2D(texture, pos/8.0+vec2(0.5,0.5));\
}\
');
simpleShader.call(this, gl.mandelbrot, {
xform: [
Math.cos(angle)*scale, Math.sin(angle)*scale,
-Math.sin(angle)*scale, Math.cos(angle)*scale
],
iterations : iterations,
center: [x-this.width/2,y-this.height/2], // TODO remove this fix to cope with UI values top-left origin
texSize: [this.width, this.height]
});
return this;
}
|
/**
* Angularjs Controller - Raptor.js
* Generado automaticamente
*/
angular.module('ngPortalApp')
.controller("config", function ($scope, $http, $mdToast) {
$('[data-toggle="tooltip"]').tooltip();
$scope.databases={
'postgres':{
name:"postgres",
port:5432
},
'mysql':{
name: "mysql",
port: 3306
},
'sqlite':{
name:"sqlite",
port:"",
},
'mssql':{
name:"mssql",
port:1433
},
'mariadb':{
name:"mariadb",
port:3306
}};
$scope.onChange=function(){
$scope.config.portDB=$scope.databases[$scope.config.driver].port;
}
$scope.submitForm = function () {
$scope.config._csrf = Raptor.getCsrfToken();
$http.post('/raptor/orm/save', $scope.config, { ignoreRequest: true })
.then(function (response) {
$mdToast.show(
$mdToast.simple()
.action('Cerrar')
.highlightAction(true)
.textContent(response.data.msg)
.position('top right')
.hideDelay(9000))
.then(function (response) {
})
}, function (response) {
$mdToast.show(
$mdToast.simple()
.action('Cerrar')
.highlightAction(true)
.textContent(response.data.error)
.position('top right')
.hideDelay(9000))
.then(function (response) {
})
})
}
}); |
'use strict';
angular.module('exampleApp', [])
.controller('defaultCtrl', ['$scope', '$http',
'$interval', '$timeout', '$log',
function($scope, $http, $interval, $timeout, $log){
$scope.counter = 0;
$scope.incrementCounter = function(){
$scope.counter++;
$http.get('productData.json').then((resp) => {
let data = resp.data;
$scope.products = data;
$log.log('There are ' + data.length + ' items');
});
$scope.intervalCounter = 0;
$scope.timerCounter = 0;
$interval(() => {
$scope.intervalCounter++;
}, 5000, 10);
$timeout(() => {
$scope.timerCounter++;
}, 5000);
};
}]).filter('labelCase', function(){
return function(value, reverse){
if(angular.isString(value)){
let intermediate = reverse? value.toUpperCase() : value.toLowerCase();
return (reverse? intermediate[0].toLowerCase() : intermediate[0].toUpperCase())
+ intermediate.substr(1);
}else{
return value;
}
};
}).directive('unorderedList', function(){
return function linkFunc(scope, element, attrs){
let data = scope[attrs['unorderedList']];
if(angular.isArray(data)){
let listElem = angular.element('<ul>');
element.append(listElem);
data.forEach(function(item, index){
listElem.append(angular.element('<li>').text(item.name));
});
}
};
}).factory('counterService', function(){
let counter = 0;
return {
incrementCounter: function(){
counter++;
},
getCounter: function(){
return counter;
}
};
}); |
/*! test_admin 2015-12-02 */
"use strict";angular.module("ui.jp",["oc.lazyLoad","ui.load"]).value("uiJpConfig",{}).directive("uiJp",["uiJpConfig","MODULE_CONFIG","$ocLazyLoad","uiLoad","$timeout",function(a,b,c,d,e){return{restrict:"A",compile:function(c,f){var g=a&&a[f.uiJp];return function(a,c,f){function h(){var b=[];return f.uiOptions?(b=a.$eval("["+f.uiOptions+"]"),angular.isObject(g)&&angular.isObject(b[0])&&(b[0]=angular.extend({},g,b[0]))):g&&(b=[g]),b}function i(){e(function(){c[f.uiJp]&&c[f.uiJp].apply(c,h())},0,!1)}function j(){f.uiRefresh&&a.$watch(f.uiRefresh,function(){i()})}f.ngModel&&c.is("select,input,textarea")&&c.bind("change",function(){c.trigger("input")});var k=!1;angular.forEach(b,function(a){a.name==f.uiJp&&(k=a.files)}),k?d.load(k).then(function(){i(),j()})["catch"](function(){}):(i(),j())}}}}]); |
/*!
* Color Thief v2.0
* by Lokesh Dhakar - http://www.lokeshdhakar.com
*
* License
* -------
* Creative Commons Attribution 2.5 License:
* http://creativecommons.org/licenses/by/2.5/
*
* Thanks
* ------
* Nick Rabinowitz - For creating quantize.js.
* John Schulz - For clean up and optimization. @JFSIII
* Nathan Spady - For adding drag and drop support to the demo page.
*
*/
/*
CanvasImage Class
Class that wraps the html image element and canvas.
It also simplifies some of the canvas context manipulation
with a set of helper functions.
*/
var CanvasImage = function (image) {
this.canvas = document.createElement('canvas');
this.context = this.canvas.getContext('2d');
document.body.appendChild(this.canvas);
this.width = this.canvas.width = image.width;
this.height = this.canvas.height = image.height;
this.context.drawImage(image, 0, 0, this.width, this.height);
};
CanvasImage.prototype.clear = function () {
this.context.clearRect(0, 0, this.width, this.height);
};
CanvasImage.prototype.update = function (imageData) {
this.context.putImageData(imageData, 0, 0);
};
CanvasImage.prototype.getPixelCount = function () {
return this.width * this.height;
};
CanvasImage.prototype.getImageData = function () {
return this.context.getImageData(0, 0, this.width, this.height);
};
CanvasImage.prototype.removeCanvas = function () {
this.canvas.parentNode.removeChild(this.canvas);
};
var ColorThief = function () {};
/*
* getColor(sourceImage[, quality])
* returns {r: num, g: num, b: num}
*
* Use the median cut algorithm provided by quantize.js to cluster similar
* colors and return the base color from the largest cluster.
*
* Quality is an optional argument. It needs to be an integer. 0 is the highest quality settings.
* 10 is the default. There is a trade-off between quality and speed. The bigger the number, the
* faster a color will be returned but the greater the likelihood that it will not be the visually
* most dominant color.
*
* */
ColorThief.prototype.getColor = function(sourceImage, quality) {
var palette = this.getPalette(sourceImage, 5, quality);
var dominantColor = palette[0];
return dominantColor;
};
/*
* getPalette(sourceImage[, colorCount, quality])
* returns array[ {r: num, g: num, b: num}, {r: num, g: num, b: num}, ...]
*
* Use the median cut algorithm provided by quantize.js to cluster similar colors.
*
* colorCount determines the size of the palette; the number of colors returned. If not set, it
* defaults to 10.
*
* BUGGY: Function does not always return the requested amount of colors. It can be +/- 2.
*
* quality is an optional argument. It needs to be an integer. 0 is the highest quality settings.
* 10 is the default. There is a trade-off between quality and speed. The bigger the number, the
* faster the palette generation but the greater the likelihood that colors will be missed.
*
*
*/
ColorThief.prototype.getPalette = function(sourceImage, colorCount, quality) {
if (typeof colorCount === 'undefined') {
colorCount = 10;
}
if (typeof quality === 'undefined') {
quality = 10;
}
// Create custom CanvasImage object
var image = new CanvasImage(sourceImage);
var imageData = image.getImageData();
var pixels = imageData.data;
var pixelCount = image.getPixelCount();
// Store the RGB values in an array format suitable for quantize function
var pixelArray = [];
for (var i = 0, offset, r, g, b, a; i < pixelCount; i = i + quality) {
offset = i * 4;
r = pixels[offset + 0];
g = pixels[offset + 1];
b = pixels[offset + 2];
a = pixels[offset + 3];
// If pixel is mostly opaque and not white
if (a >= 125) {
if (!(r > 250 && g > 250 && b > 250)) {
pixelArray.push([r, g, b]);
}
}
}
// Send array to quantize function which clusters values
// using median cut algorithm
var cmap = MMCQ.quantize(pixelArray, colorCount);
var palette = cmap.palette();
// Clean up
image.removeCanvas();
return palette;
};
/*!
* quantize.js Copyright 2008 Nick Rabinowitz.
* Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
*/
// fill out a couple protovis dependencies
/*!
* Block below copied from Protovis: http://mbostock.github.com/protovis/
* Copyright 2010 Stanford Visualization Group
* Licensed under the BSD License: http://www.opensource.org/licenses/bsd-license.php
*/
if (!pv) {
var pv = {
map: function(array, f) {
var o = {};
return f ? array.map(function(d, i) { o.index = i; return f.call(o, d); }) : array.slice();
},
naturalOrder: function(a, b) {
return (a < b) ? -1 : ((a > b) ? 1 : 0);
},
sum: function(array, f) {
var o = {};
return array.reduce(f ? function(p, d, i) { o.index = i; return p + f.call(o, d); } : function(p, d) { return p + d; }, 0);
},
max: function(array, f) {
return Math.max.apply(null, f ? pv.map(array, f) : array);
}
};
}
/**
* Basic Javascript port of the MMCQ (modified median cut quantization)
* algorithm from the Leptonica library (http://www.leptonica.com/).
* Returns a color map you can use to map original pixels to the reduced
* palette. Still a work in progress.
*
* @author Nick Rabinowitz
* @example
// array of pixels as [R,G,B] arrays
var myPixels = [[190,197,190], [202,204,200], [207,214,210], [211,214,211], [205,207,207]
// etc
];
var maxColors = 4;
var cmap = MMCQ.quantize(myPixels, maxColors);
var newPalette = cmap.palette();
var newPixels = myPixels.map(function(p) {
return cmap.map(p);
});
*/
var MMCQ = (function() {
// private constants
var sigbits = 5,
rshift = 8 - sigbits,
maxIterations = 1000,
fractByPopulations = 0.75;
// get reduced-space color index for a pixel
function getColorIndex(r, g, b) {
return (r << (2 * sigbits)) + (g << sigbits) + b;
}
// Simple priority queue
function PQueue(comparator) {
var contents = [],
sorted = false;
function sort() {
contents.sort(comparator);
sorted = true;
}
return {
push: function(o) {
contents.push(o);
sorted = false;
},
peek: function(index) {
if (!sorted) sort();
if (index===undefined) index = contents.length - 1;
return contents[index];
},
pop: function() {
if (!sorted) sort();
return contents.pop();
},
size: function() {
return contents.length;
},
map: function(f) {
return contents.map(f);
},
debug: function() {
if (!sorted) sort();
return contents;
}
};
}
// 3d color space box
function VBox(r1, r2, g1, g2, b1, b2, histo) {
var vbox = this;
vbox.r1 = r1;
vbox.r2 = r2;
vbox.g1 = g1;
vbox.g2 = g2;
vbox.b1 = b1;
vbox.b2 = b2;
vbox.histo = histo;
}
VBox.prototype = {
volume: function(force) {
var vbox = this;
if (!vbox._volume || force) {
vbox._volume = ((vbox.r2 - vbox.r1 + 1) * (vbox.g2 - vbox.g1 + 1) * (vbox.b2 - vbox.b1 + 1));
}
return vbox._volume;
},
count: function(force) {
var vbox = this,
histo = vbox.histo;
if (!vbox._count_set || force) {
var npix = 0,
i, j, k;
for (i = vbox.r1; i <= vbox.r2; i++) {
for (j = vbox.g1; j <= vbox.g2; j++) {
for (k = vbox.b1; k <= vbox.b2; k++) {
index = getColorIndex(i,j,k);
npix += (histo[index] || 0);
}
}
}
vbox._count = npix;
vbox._count_set = true;
}
return vbox._count;
},
copy: function() {
var vbox = this;
return new VBox(vbox.r1, vbox.r2, vbox.g1, vbox.g2, vbox.b1, vbox.b2, vbox.histo);
},
avg: function(force) {
var vbox = this,
histo = vbox.histo;
if (!vbox._avg || force) {
var ntot = 0,
mult = 1 << (8 - sigbits),
rsum = 0,
gsum = 0,
bsum = 0,
hval,
i, j, k, histoindex;
for (i = vbox.r1; i <= vbox.r2; i++) {
for (j = vbox.g1; j <= vbox.g2; j++) {
for (k = vbox.b1; k <= vbox.b2; k++) {
histoindex = getColorIndex(i,j,k);
hval = histo[histoindex] || 0;
ntot += hval;
rsum += (hval * (i + 0.5) * mult);
gsum += (hval * (j + 0.5) * mult);
bsum += (hval * (k + 0.5) * mult);
}
}
}
if (ntot) {
vbox._avg = [~~(rsum/ntot), ~~(gsum/ntot), ~~(bsum/ntot)];
} else {
// console.log('empty box');
vbox._avg = [
~~(mult * (vbox.r1 + vbox.r2 + 1) / 2),
~~(mult * (vbox.g1 + vbox.g2 + 1) / 2),
~~(mult * (vbox.b1 + vbox.b2 + 1) / 2)
];
}
}
return vbox._avg;
},
contains: function(pixel) {
var vbox = this,
rval = pixel[0] >> rshift;
gval = pixel[1] >> rshift;
bval = pixel[2] >> rshift;
return (rval >= vbox.r1 && rval <= vbox.r2 &&
gval >= vbox.g1 && gval <= vbox.g2 &&
bval >= vbox.b1 && bval <= vbox.b2);
}
};
// Color map
function CMap() {
this.vboxes = new PQueue(function(a,b) {
return pv.naturalOrder(
a.vbox.count()*a.vbox.volume(),
b.vbox.count()*b.vbox.volume()
);
});
}
CMap.prototype = {
push: function(vbox) {
this.vboxes.push({
vbox: vbox,
color: vbox.avg()
});
},
palette: function() {
return this.vboxes.map(function(vb) { return vb.color; });
},
size: function() {
return this.vboxes.size();
},
map: function(color) {
var vboxes = this.vboxes;
for (var i=0; i<vboxes.size(); i++) {
if (vboxes.peek(i).vbox.contains(color)) {
return vboxes.peek(i).color;
}
}
return this.nearest(color);
},
nearest: function(color) {
var vboxes = this.vboxes,
d1, d2, pColor;
for (var i=0; i<vboxes.size(); i++) {
d2 = Math.sqrt(
Math.pow(color[0] - vboxes.peek(i).color[0], 2) +
Math.pow(color[1] - vboxes.peek(i).color[1], 2) +
Math.pow(color[2] - vboxes.peek(i).color[2], 2)
);
if (d2 < d1 || d1 === undefined) {
d1 = d2;
pColor = vboxes.peek(i).color;
}
}
return pColor;
},
forcebw: function() {
// XXX: won't work yet
var vboxes = this.vboxes;
vboxes.sort(function(a,b) { return pv.naturalOrder(pv.sum(a.color), pv.sum(b.color));});
// force darkest color to black if everything < 5
var lowest = vboxes[0].color;
if (lowest[0] < 5 && lowest[1] < 5 && lowest[2] < 5)
vboxes[0].color = [0,0,0];
// force lightest color to white if everything > 251
var idx = vboxes.length-1,
highest = vboxes[idx].color;
if (highest[0] > 251 && highest[1] > 251 && highest[2] > 251)
vboxes[idx].color = [255,255,255];
}
};
// histo (1-d array, giving the number of pixels in
// each quantized region of color space), or null on error
function getHisto(pixels) {
var histosize = 1 << (3 * sigbits),
histo = new Array(histosize),
index, rval, gval, bval;
pixels.forEach(function(pixel) {
rval = pixel[0] >> rshift;
gval = pixel[1] >> rshift;
bval = pixel[2] >> rshift;
index = getColorIndex(rval, gval, bval);
histo[index] = (histo[index] || 0) + 1;
});
return histo;
}
function vboxFromPixels(pixels, histo) {
var rmin=1000000, rmax=0,
gmin=1000000, gmax=0,
bmin=1000000, bmax=0,
rval, gval, bval;
// find min/max
pixels.forEach(function(pixel) {
rval = pixel[0] >> rshift;
gval = pixel[1] >> rshift;
bval = pixel[2] >> rshift;
if (rval < rmin) rmin = rval;
else if (rval > rmax) rmax = rval;
if (gval < gmin) gmin = gval;
else if (gval > gmax) gmax = gval;
if (bval < bmin) bmin = bval;
else if (bval > bmax) bmax = bval;
});
return new VBox(rmin, rmax, gmin, gmax, bmin, bmax, histo);
}
function medianCutApply(histo, vbox) {
if (!vbox.count()) return;
var rw = vbox.r2 - vbox.r1 + 1,
gw = vbox.g2 - vbox.g1 + 1,
bw = vbox.b2 - vbox.b1 + 1,
maxw = pv.max([rw, gw, bw]);
// only one pixel, no split
if (vbox.count() == 1) {
return [vbox.copy()];
}
/* Find the partial sum arrays along the selected axis. */
var total = 0,
partialsum = [],
lookaheadsum = [],
i, j, k, sum, index;
if (maxw == rw) {
for (i = vbox.r1; i <= vbox.r2; i++) {
sum = 0;
for (j = vbox.g1; j <= vbox.g2; j++) {
for (k = vbox.b1; k <= vbox.b2; k++) {
index = getColorIndex(i,j,k);
sum += (histo[index] || 0);
}
}
total += sum;
partialsum[i] = total;
}
}
else if (maxw == gw) {
for (i = vbox.g1; i <= vbox.g2; i++) {
sum = 0;
for (j = vbox.r1; j <= vbox.r2; j++) {
for (k = vbox.b1; k <= vbox.b2; k++) {
index = getColorIndex(j,i,k);
sum += (histo[index] || 0);
}
}
total += sum;
partialsum[i] = total;
}
}
else { /* maxw == bw */
for (i = vbox.b1; i <= vbox.b2; i++) {
sum = 0;
for (j = vbox.r1; j <= vbox.r2; j++) {
for (k = vbox.g1; k <= vbox.g2; k++) {
index = getColorIndex(j,k,i);
sum += (histo[index] || 0);
}
}
total += sum;
partialsum[i] = total;
}
}
partialsum.forEach(function(d,i) {
lookaheadsum[i] = total-d;
});
function doCut(color) {
var dim1 = color + '1',
dim2 = color + '2',
left, right, vbox1, vbox2, d2, count2=0;
for (i = vbox[dim1]; i <= vbox[dim2]; i++) {
if (partialsum[i] > total / 2) {
vbox1 = vbox.copy();
vbox2 = vbox.copy();
left = i - vbox[dim1];
right = vbox[dim2] - i;
if (left <= right)
d2 = Math.min(vbox[dim2] - 1, ~~(i + right / 2));
else d2 = Math.max(vbox[dim1], ~~(i - 1 - left / 2));
// avoid 0-count boxes
while (!partialsum[d2]) d2++;
count2 = lookaheadsum[d2];
while (!count2 && partialsum[d2-1]) count2 = lookaheadsum[--d2];
// set dimensions
vbox1[dim2] = d2;
vbox2[dim1] = vbox1[dim2] + 1;
// console.log('vbox counts:', vbox.count(), vbox1.count(), vbox2.count());
return [vbox1, vbox2];
}
}
}
// determine the cut planes
return maxw == rw ? doCut('r') :
maxw == gw ? doCut('g') :
doCut('b');
}
function quantize(pixels, maxcolors) {
// short-circuit
if (!pixels.length || maxcolors < 2 || maxcolors > 256) {
// console.log('wrong number of maxcolors');
return false;
}
// XXX: check color content and convert to grayscale if insufficient
var histo = getHisto(pixels),
histosize = 1 << (3 * sigbits);
// check that we aren't below maxcolors already
var nColors = 0;
histo.forEach(function() { nColors++; });
if (nColors <= maxcolors) {
// XXX: generate the new colors from the histo and return
}
// get the beginning vbox from the colors
var vbox = vboxFromPixels(pixels, histo),
pq = new PQueue(function(a,b) { return pv.naturalOrder(a.count(), b.count()); });
pq.push(vbox);
// inner function to do the iteration
function iter(lh, target) {
var ncolors = 1,
niters = 0,
vbox;
while (niters < maxIterations) {
vbox = lh.pop();
if (!vbox.count()) { /* just put it back */
lh.push(vbox);
niters++;
continue;
}
// do the cut
var vboxes = medianCutApply(histo, vbox),
vbox1 = vboxes[0],
vbox2 = vboxes[1];
if (!vbox1) {
// console.log("vbox1 not defined; shouldn't happen!");
return;
}
lh.push(vbox1);
if (vbox2) { /* vbox2 can be null */
lh.push(vbox2);
ncolors++;
}
if (ncolors >= target) return;
if (niters++ > maxIterations) {
// console.log("infinite loop; perhaps too few pixels!");
return;
}
}
}
// first set of colors, sorted by population
iter(pq, fractByPopulations * maxcolors);
// Re-sort by the product of pixel occupancy times the size in color space.
var pq2 = new PQueue(function(a,b) {
return pv.naturalOrder(a.count()*a.volume(), b.count()*b.volume());
});
while (pq.size()) {
pq2.push(pq.pop());
}
// next set - generate the median cuts using the (npix * vol) sorting.
iter(pq2, maxcolors - pq2.size());
// calculate the actual colors
var cmap = new CMap();
while (pq2.size()) {
cmap.push(pq2.pop());
}
return cmap;
}
return {
quantize: quantize
};
})();
angular.module('app', [])
.controller('MainController', function($scope, $http, $timeout) {
$scope.connect = function() {
$http({
url:"http://172.17.104.18/api",
method: "POST",
data: JSON.stringify({"devicetype":"test user","username":"newdeveloper"})
}).success(function(response) {
console.log(response)
});
}
$scope.off = function() {
for (var i = 1; i <= numLights; i++) {
$http({
url:"http://172.17.104.18/api/newdeveloper/lights/" + i + "/state",
method: "PUT",
data: JSON.stringify({"on":false})
}).success(function(response) {
console.log(response)
});
}
}
$scope.continue = false;
numLights = 3
$scope.on = function() {
for (var i = 1; i <= numLights; i++) {
$http({
url:"http://172.17.104.18/api/newdeveloper/lights/" + i + "/state",
method: "PUT",
data: JSON.stringify({"on":true})
}).success(function(response) {
console.log(response)
});
}
}
$scope.update = function() {
chrome.tabs.getSelected(null, function(tab) {
tab_id = tab.id;
tab_url = tab.url;
image = chrome.tabs.captureVisibleTab(null, {'format':'jpeg'}, function(dataUrl) {
var imgObj = new Image()
imgObj.src = dataUrl
var colorThief = new ColorThief();
rgb = colorThief.getColor(imgObj);
console.log(rgb)
xy = rgbToXY(rgb[0], rgb[1], rgb[2])
for (var i = 1; i <= numLights; i++) {
$http({
url:"http://172.17.104.18/api/newdeveloper/lights/" + i + "/state",
method: "PUT",
data: JSON.stringify({"on":true, "bri": 255, "xy": xy, "sat": 255})
}).success(function(response) {
console.log(response)
});
}
});
// console.log(tab.url);
});
}
// Function to replicate setInterval using $timeout service.
$scope.intervalFunction = function(){
$timeout(function() {
$scope.update();
$scope.intervalFunction();
}, 5000)
};
$scope.intervalFunction();
function rgbToXY(r, g, b){
r /= 255;
g /= 255;
b /= 255;
if (r > 0.04045) {
r = Math.pow((r + 0.055) / (1.0 + 0.055), 2.4);
} else {
r = r / 12.92;
}
if (g > 0.04045) {
g = Math.pow((g + 0.055) / (1.0 + 0.055), 2.4);
} else {
g = g / 12.92;
}
if (b > 0.04045) {
b = Math.pow((b + 0.55) / (1.0 + 0.55), 2.4);
} else {
b = b / 12.92;
}
X = r * 0.649926 + g * 0.103455 + b * 0.197109;
Y = r * 0.234327 + g * 0.743075 + b * 0.022598;
Z = r * 0.0 + g * 0.053077 + b * 1.035763;
x = X / (X + Y + Z);
y = Y / (X + Y + Z);
return [x, y];
}
// $http.get("/outputs").success(function(data) {
// $scope.outputs = data.response
// });
// var myHue;
// myHue = hue;
// myHue.setup({
// username: "newdeveloper"
// });
// return myHue.getLights().then(function(lights) {
// var changeBrightness, lazyChangeBrightness;
// $scope.lights = lights;
// $scope.setLightStateOn = function(light, state) {
// return myHue.setLightState(light, {
// on: state
// }).then(function() {
// return $scope.lights[light].state.on = state;
// });
// };
// $scope.triggerAlert = function(light, alert) {
// return myHue.setLightState(light, {
// "alert": alert
// });
// };
// $scope.setEffect = function(light, effect) {
// return myHue.setLightState(light, {
// "effect": effect
// }).then(function() {
// return $scope.lights[light].state.effect = effect;
// });
// };
// changeBrightness = function(light, value) {
// return myHue.setLightState(light, {
// "bri": value
// });
// };
// lazyChangeBrightness = _.debounce(changeBrightness, 600);
// $scope.changeBrightness = function(light, value) {
// return lazyChangeBrightness(light, value);
// };
// return myHue.getGroups().then(function(groups) {
// $scope.groups = groups;
// $scope.deleteGroup = function(group) {
// return myHue.deleteGroup(group).then(function() {
// return delete $scope.groups[group];
// });
// };
// return $scope.setGroupStateOn = function(group, state) {
// return myHue.setGroupState(group, {
// on: state
// }).then(function() {
// $scope.groups[group].action.on = state;
// return angular.forEach($scope.groups[group].lights, function(value) {
// return $scope.lights[value].state.on = state;
// });
// });
// };
// });
// });
});
|
import React, {Component} from 'react';
import classNames from 'classnames';
import moment from 'moment';
import PropTypes from 'prop-types';
import {Container} from './container';
import {Content} from './content';
import {Icon} from './icon';
export class Post extends Component {
render() {
let {
abstract,
body,
createdDate,
mode,
subTitle,
title
} = this.props;
return (
<Content>
<h1 className={classNames('title', 'has-text-weight-bold')}>
{title}
</h1>
<h2 className="subtitle">{subTitle}</h2>
<h6>{`by Matt on ${moment(createdDate).format('MM/DD/YYYY hh:mm a')}`}</h6>
<p>
{`${body} `}
<a>read more...</a>
</p>
</Content>
);
}
static propTypes = {
mode: PropTypes.oneOf(['compact', 'full'])
};
} |
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CADStatusMapModule = void 0;
const _ = require("lodash");
const helpers_1 = require("../helpers");
async function CADStatusMapModule(mongoose) {
const Schema = mongoose.Schema;
const ToStatusIdSchema = (0, helpers_1.createSchema)(Schema, {
statusId: {
type: Number,
default: 0,
required: true,
min: 0,
},
userEnabled: {
type: Boolean,
},
}, {
_id: false,
id: false,
});
// Using hook instead of default values,
// so we keep the db value if no value was sent by the API/CAD
ToStatusIdSchema.pre("save", function (next) {
if (_.isUndefined(this.userEnabled) || _.isNull(this.userEnabled)) {
this.userEnabled = false;
}
next();
});
// Update static items (keep in sync with the lib/cad-status-map/updateDocument!)
const modelSchema = (0, helpers_1.createSchema)(Schema, {
departmentId: {
type: String,
default: "",
required: true,
index: true,
},
modifiedDate: {
type: Number,
default: 0,
min: 1,
},
modified: {
type: Date,
default: helpers_1.currentDate,
},
fromStatusId: {
type: Number,
default: 0,
required: true,
min: 0,
},
toStatusIds: {
type: [ToStatusIdSchema],
required: true,
},
}, {
collection: "massive_cad_status_map",
});
modelSchema.set("autoIndex", false);
return (0, helpers_1.createModel)(mongoose, "CADStatusMap", modelSchema);
}
exports.CADStatusMapModule = CADStatusMapModule;
exports.default = CADStatusMapModule;
//# sourceMappingURL=cad-status-map.js.map |
///////////////////////////////////////////////////////////////////////////////
// Plugin generador de tags //
///////////////////////////////////////////////////////////////////////////////
$(document).ready(function () {
"use strict";
var pluginName = "fwNotify";
var note = $('<div class="alert"></div>');
var defaults = {
type: 'success',
closable: true,
transition: 'fade',
fadeOut: {
enabled: true,
delay: 3000
},
message: {
html: false,
text: 'This is a message.'
},
onClose: function () {},
onClosed: function () {}
};
function Plugin(element, options) {
this.element = element;
this.options = $.extend({}, defaults, options);
this._defaults = defaults;
this._name = pluginName;
this.note = note;
this.init();
}
Plugin.prototype = {
init: function () {
var that = this;
var self = $(that.element);
self.bind("destroyed", $.proxy(that.teardown, that));
self.addClass(that._name);
// Setup from options
if(this.options.transition)
if(this.options.transition == 'fade')
this.note.addClass('in').addClass(this.options.transition)
else this.note.addClass(this.options.transition)
else this.note.addClass('fade').addClass('in')
if(this.options.type)
this.note.addClass('alert-' + this.options.type)
else this.note.addClass('alert-success')
if(typeof this.options.message === 'object')
if(this.options.message.html)
this.note.html(this.options.message.html)
else if(this.options.message.text)
this.note.text(this.options.message.text)
else
this.note.html(this.options.message)
if(this.options.closable)
this.note.prepend($('<a class="close pull-right" data-dismiss="alert" href="#">×</a>'))
this.note = this.create(this.options.type, this.options.message.html, "");
return this;
},
create: function(title, message, time) {
return $('<div class="popup white swing"><span class="title">'+"Aviso"+'</span><p>' + message + '<br /> '+ time +'</p><a href="#" class="close">X</a></div>');
},
show: function () {
var self = this;
console.log("show")
if(this.options.fadeOut.enabled)
setTimeout(function(){
self.hide();
}, this.options.fadeOut.delay || 3000);
console.log(this.note)
$(this.element).append(this.note);
this.note.addClass('animated')
this.note.on('click', '.close', function(){
console.log("closed");
self.hide();
self.options.onClosed();
});
},
hide: function () {
var self = this;
if(this.options.fadeOut.enabled) {
console.log("fadeee")
this.note.removeClass('swing').addClass('bounceOutUp animated');
setTimeout(function(){
self.note.remove();
}, 1000);
self.destroy();
}
else {
self.options.onClose();
this.note.removeClass('swing').addClass('bounceOutDown animated');
setTimeout(function(){
self.note.remove();
}, 800);
self.destroy();
}
},
destroy: function() {
$(this.element).unbind("destroyed", this.teardown);
this.options.onClosed();
this.teardown();
return true;
},
teardown: function() {
$.removeData($(this.element)[0], this._name);
$(this.element).removeClass(this._name);
this.unbind();
this.element = null;
return this.element;
},
bind: function() { },
unbind: function() { }
};
$.fn[pluginName] = function (options) {
return this.each(function () {
if (!$.data(this, pluginName)) {
$.data(this, pluginName, new Plugin(this, options));
}
});
};
}); |
version https://git-lfs.github.com/spec/v1
oid sha256:736231d29be12d4dd1757a9b78451cd52cf1b7cf3e81852d808a0b12f54589fb
size 465
|
System.register(['./query-language/query-language'], function(exports_1, context_1) {
"use strict";
var __moduleName = context_1 && context_1.id;
function configure(aurelia) {
aurelia.globalResources('./query-language/query-language');
}
exports_1("configure", configure);
var exportedNames_1 = {
'configure': true
};
function exportStar_1(m) {
var exports = {};
for(var n in m) {
if (n !== "default"&& !exportedNames_1.hasOwnProperty(n)) exports[n] = m[n];
}
exports_1(exports);
}
return {
setters:[
function (query_language_1_1) {
exportStar_1(query_language_1_1);
}],
execute: function() {
}
}
});
|
/*
* Case insensitive regexp compilation has bad performance behavior at
* least up to Duktape 1.3.0. Basic test for that behavior.
*/
function test() {
var i;
var src = [];
for (i = 0; i < 1e2; i++) {
// Use a RegExp constructor call rather than a literal to ensure the
// RegExp is compiled on every loop.
var re = new RegExp('[\\u0000-\\uffff]', 'i');
}
}
try {
test();
} catch (e) {
print(e.stack || e);
throw e;
}
|
module.exports = {
createRandomWord : function(length) {
var consonants = 'bcdfghjklmnpqrstvwxyz',
vowels = 'aeiou',
rand = function(limit) {
return Math.floor(Math.random() * limit);
},
i, word = '', length = parseInt(length, 10),
consonants = consonants.split(''),
vowels = vowels.split('');
for (i = 0; i < length / 2; i++) {
var randConsonant = consonants[rand(consonants.length)],
randVowel = vowels[rand(vowels.length)];
word += (i === 0) ? randConsonant.toUpperCase() : randConsonant;
word += i * 2 < length - 1 ? randVowel : '';
}
return word;
}
};
// Found online @ http://james.padolsey.com/javascript/random-word-generator/
|
const {
assign
} = require('lodash')
const {
readFileSync,
writeFileSync
} = require('fs')
const DEFAULT_BOUNDS = {
height: 800,
width: 1024
}
module.exports = configPath => {
return {
get (name) {
let data = {}
try {
data = JSON.parse(readFileSync(configPath, 'utf8'))
} catch (e) {
// do nothing
}
if (data && data[name] && data[name].bounds) {
return data[name].bounds
}
return DEFAULT_BOUNDS
},
set (name, bounds) {
bounds = bounds || DEFAULT_BOUNDS
let data = {}
try {
data = JSON.parse(readFileSync(configPath, 'utf8'))
} catch (e) {
// do nothing
}
data[name] = data[name] || {}
assign(data[name], {
bounds
})
writeFileSync(configPath, JSON.stringify(data))
}
}
}
|
var class_wanzyee_studio_1_1_extension_1_1_delegate_extension =
[
[ "Notify", "class_wanzyee_studio_1_1_extension_1_1_delegate_extension.html#a5f5abc58b5018d592c9a7624eb90cba8", null ]
]; |
/**
* Broadcast updates to client when the model changes
*/
'use strict';
var game = require('./game.model');
exports.register = function(socket) {
game.schema.post('save', function (doc) {
onSave(socket, doc);
});
game.schema.post('remove', function (doc) {
onRemove(socket, doc);
});
}
function onSave(socket, doc, cb) {
socket.emit('game:save', doc);
}
function onRemove(socket, doc, cb) {
socket.emit('game:remove', doc);
}
|
import memoize from 'lru-memoize';
import {createValidator, required, maxLength, atLeastOneValueMustBeChecked} from './validation';
var toyValidation = createValidator({
name: [required, maxLength(60)]
}, {categories: [atLeastOneValueMustBeChecked]});
export default memoize(10)(toyValidation); |
require('proof')(4, okay => {
const DOMStringList = require('../living/generated/DOMStringList')
const globalObject = {}
DOMStringList.install(globalObject, [ 'Window' ])
const list = DOMStringList.create(globalObject, [], { array: [ 'a', 'b', 'c' ] })
okay(list.contains('b'), 'contains')
okay(! list.contains('z'), 'does not contain')
okay(list.item(1), 'b', 'item')
okay(list[1], 'indexed get')
})
|
/**
* Created by Maurizio on 05/01/2017.
*/
$(function () {
console.log("Modifica Statistiche Calciatore");
$("form.modifica_statistiche_calciatore").submit(modificaStatisticheHandler);
});
function modificaStatisticheHandler(event) {
event.preventDefault();
console.log("ModificaStatisticheCalciatore Handler...");
var $form = $(this);
console.log($form);
var params = $($form).serialize();
console.log(params);
var url = $($form).attr("action");
$.ajax({
url: url,
type: "POST",
dataType: "json",
cache: false,
data: params,
success: function (response, textStatus, jqXHR) {
console.log("SUCCESS Modifica Statistiche Calciatore Handler.");
console.log(response);
console.log(textStatus);
console.log(jqXHR);
var executed = response.executed;
console.log(executed);
var statistiche = response.statistiche;
console.log(statistiche);
if (executed) {
showSuccess("Statistiche modificate con successo.");
//$($form)[0].reset();
//$($form).parent().parent().parent().remove();
} else {
showWarning("Errore nell'inserimento delle statistiche.");
}
}
,
error: function (jqXHR, textStatus, errorThrown) {
console.log("ERROR Inserisci Statistiche Calciatore Handler.");
console.log(textStatus);
console.log(jqXHR.status);
console.log(jqXHR.responseText);
console.log(errorThrown);
}
});
} |
#!/usr/bin/env node
var ottomatonBrowserPath = require.resolve('..');
// Inject browser actions into the otto context
process.argv.splice(2, 0, ottomatonBrowserPath);
require('ottomaton/lib/bin/otto');
|
var BandSpeed = BS = _ = (function($, exports) {
//================================================================================
//====================================Variables===================================
//================================================================================
var request, timeout,
//Callbacks
onPingCall, onDownCall, onUpCall, onStartCall, onCompCall, onErrorCall,
isRunning = false,
isBusy = false,
//Reusable
isLatency = false,
type = '',
url = '',
data = null,
//Temp
time, load, moving,
count = 0,
total = 0;
//================================================================================
//===================================Initialize===================================
//================================================================================
exports.Test = function() {
isRunning = true;
exports.Ping();
};
exports.Ping = function() {
isLatency = true;
type = 'GET';
url = 'https://bandspeed.github.io/src/Data/5MB.zip';
data = null;
Request();
};
exports.Download = function() {
isLatency = false;
type = 'GET';
url = 'https://bandspeed.github.io/src/Data/20MB.zip';
data = null;
Request();
};
exports.Upload = function() {
isLatency = false;
type = 'POST';
url = 'https://posttestserver.com/post.php';
data = Data(20);
Request();
};
//================================================================================
//====================================Callback====================================
//================================================================================
//Ping
exports.onPing = function(callback, ping) {
if (typeof callback === 'function') {
onPingCall = callback;
//Error Handling
try { callback(ping); } catch (ex) {
callback();
}
}
};
//Download
exports.onDownload = function(callback, dLoad, dTotal, dSpeed) {
if (typeof callback === 'function') {
onDownCall = callback;
try { callback(dLoad, dTotal, dSpeed); } catch (ex) {
try { callback(dLoad, dTotal); } catch (ex) {
try { callback(dLoad); } catch (ex) {
callback();
}}}
}
};
//Upload
exports.onUpload = function(callback, uLoad, uTotal, uSpeed) {
if (typeof callback === 'function') {
onUpCall = callback;
try { callback(uLoad, uTotal, uSpeed); } catch (ex) {
try { callback(uLoad, uTotal); } catch (ex) {
try { callback(uLoad); } catch (ex) {
callback();
}}}
}
};
//Start
exports.onStart = function(callback, sType, sStatus) {
if (typeof callback === 'function') {
onStartCall = callback;
try { callback(sType, sStatus); } catch (ex) {
try { callback(sType); } catch (ex) {
callback();
}}
}
};
//Complete
exports.onComplete = function(callback, cType) {
if (typeof callback === 'function') {
onCompCall = callback;
try { callback(cType); } catch (ex) {
callback();
}
}
};
//Error
exports.onError = function(callback, eType, eStatus, eError) {
if (typeof callback === 'function') {
onErrorCall = callback;
try { callback(eType, eStatus, eError); } catch (ex) {
try { callback(eType, eStatus); } catch (ex) {
try { callback(eType); } catch (ex) {
callback();
}}}
}
};
//================================================================================
//======================================Setup=====================================
//================================================================================
function Setup() {
var oldRequest = $.ajaxSettings.xhr;
$.ajaxSetup({
cache: false,
async: true,
processData: false,
crossDomain: true,
contentType: 'text/plain',
xhrFields: { withCredentials: false },
xhr: function() {
//Variables
var newRequest = oldRequest(),
that = this;
//Validate that the functions exsist
if (newRequest && newRequest.addEventListener && newRequest.upload) {
//Download Progress
if (that.download) {
//Event Listener that runs a function each time the progress changes
newRequest.addEventListener('progress', function(event) {
that.download(event);
}, false);
}
//Upload Progress
if (that.upload) {
//Event Listener that runs a function each time the progress changes
newRequest.upload.addEventListener('progress', function(event) {
that.upload(event);
}, false);
}
}
return newRequest;
}
});
}
Setup();
//================================================================================
//=====================================Process====================================
//================================================================================
//Request
function Request() {
Reset();
request = $.ajax({
type: type,
url: url,
data: data,
beforeSend: Before,
complete: Complete,
error: Error,
download: function(event) {
if (event.lengthComputable) {
if (isLatency == true) {
//Ping
if (!timeout) {
Timeout(5);
}
count++;
total += Time(time);
} else {
//Download
if (!timeout) {
Timeout(20);
}
//Reaction Time: Milliseconds > Seconds
var latency = Time(time) / 1000,
//Conversions:
//Bits > Bytes
bits = Load(event.loaded) * 8,
//Bytes per Reaction Time
bps = bits / latency,
//Bytes ps > Kilobytes ps
kbps = bps / 1024,
//Kilobytes ps > Megabytes ps
mbps = kbps / 1024;
//Prevents Infinity values
if (isFinite(mbps) && !isNaN(mbps)) {
var value = Average(mbps, moving);
//Callback
exports.onDownload(onDownCall, event.loaded, event.total, value.toFixed(2));
Output(value);
if (typeof BandMeter !== 'undefined') {
BandMeter.Update(value);
}
if (typeof BandGraph !== 'undefined') {
BandGraph.Update(value);
}
}
}
}
},
upload: function(event) {
//Upload
if (event.lengthComputable) {
if (!timeout) {
Timeout(20);
}
//Reaction Time: Milliseconds > Seconds
var latency = Time(time) / 1000,
//Conversions:
//Bits > Bytes
bits = Load(event.loaded) * 8,
//Bytes per Reaction Time
bps = bits / latency,
//Bytes ps > Kilobytes ps
kbps = bps / 1024,
//Kilobytes ps > Megabytes ps
mbps = kbps / 1024;
//Prevents Infinity values
if (isFinite(mbps) && !isNaN(mbps)) {
var value = Average(mbps, moving);
//Callback
exports.onUpload(onUpCall, event.loaded, event.total, value.toFixed(2));
Output(value);
if (typeof BandMeter !== 'undefined') {
BandMeter.Update(value);
}
if (typeof BandGraph !== 'undefined') {
BandGraph.Update(value);
}
}
}
}
});
}
//Before
function Before(xhr) {
if (isBusy == true) {
//End requested Request
xhr.abort();
}
isBusy = true;
//Callback
if (isLatency == true) {
exports.onStart(onStartCall, 'Ping', xhr.status);
} else if (type == 'GET') {
exports.onStart(onStartCall, 'Download', xhr.status);
} else {
exports.onStart(onStartCall, 'Upload', xhr.status);
}
}
//Complete
function Complete(xhr, status) {
if (typeof BandMeter !== 'undefined') {
BandMeter.Complete();
}
if (isRunning == true && isBusy == false) {
if (isLatency == true) {
//Callback
exports.onPing(onPingCall, Average().toFixed(0));
Output(Average());
exports.Download();
} else if (type == 'GET') {
//Callback
exports.onComplete(onCompCall, 'Download');
exports.Upload();
} else {
//Callback
exports.onComplete(onCompCall, 'Upload');
isRunning = false;
}
} else {
if (isBusy == true) {
if (isLatency == true) {
//Callback
exports.onPing(onPingCall, Average().toFixed(0));
Output(Average());
} else if (type == 'GET') {
//Callback
exports.onComplete(onCompCall, 'Download');
} else {
//Callback
exports.onComplete(onCompCall, 'Upload');
}
}
}
}
//Error
function Error(xhr, status, error) {
if (error == 'abort') {
isBusy = false;
Complete(xhr, status);
} else {
//Callback
if (isLatency == true) {
exports.onStart(onStartCall, 'Ping', status, error);
} else if (type == 'GET') {
exports.onStart(onStartCall, 'Download', status, error);
} else {
exports.onStart(onStartCall, 'Upload', status, error);
}
}
}
//================================================================================
//=====================================Function===================================
//================================================================================
//Timeout
function Timeout(seconds) {
timeout = setTimeout(function() {
request.abort();
}, seconds * 1000);
}
//Output
function Output(value) {
if (isLatency == true) {
$('#bandspeed-ping').html(value.toFixed(0) + ' ms');
} else if (type == 'GET') {
$('#bandspeed-download').html(value.toFixed(2) + ' Mbps');
} else {
$('#bandspeed-upload').html(value.toFixed(2) + ' Mbps');
}
}
//Time
function Time(start, end) {
if (!start) {
start = (new Date()).getTime();
}
end = (new Date()).getTime();
time = end;
return end - start;
}
//Load
function Load(newer, old) {
if (!load) {
load = newer;
}
old = load;
load = newer;
return newer - old;
}
//Average
function Average(newer, old) {
if (isLatency == false) {
if (!moving) {
moving = [newer, newer, newer];
}
old = moving;
moving = [old[1], old[2], newer];
var sum = old[0] + old[1] + old[2];
count++;
total += sum / old.length;
}
return total / count;
}
//Data
function Data(size) {
//Variables
const length = size * 1024 * 1024;
var data = '';
//Appending data
while (data.length <= length) {
//1 Character = 1 Byte
data += 'a';
}
//Return Data
return data;
}
//Reset
function Reset() {
timeout = undefined;
time = undefined;
load = undefined;
moving = undefined;
count = 0;
total = 0;
}
//================================================================================
//=====================================Exports====================================
//================================================================================
return exports;
})(jQuery, {});
//================================================================================
//=================================Google Analytics===============================
//================================================================================
!function(e,t,a,n,c,s,o){e.GoogleAnalyticsObject=c,e[c]=e[c]||function(){(e[c].q=e[c].q||[]).push(arguments)},e[c].l=1*new Date,s=t.createElement(a),o=t.getElementsByTagName(a)[0],s.async=1,s.src=n,o.parentNode.insertBefore(s,o)}(window,document,"script","https://www.google-analytics.com/analytics.js","ga"),ga("create","UA-81209724-2","auto"),ga("send","pageview");
|
var element = {
nome: 'Andsssersonsss',
idade: 20
};
|
/**
Address editable input.
Internally value stored as {city: "Moscow", street: "Lenina", building: "15"}
@class address
@extends abstractinput
@final
@example
<a href="#" id="address" data-type="address" data-pk="1">awesome</a>
<script>
$(function(){
$('#address').editable({
url: '/post',
title: 'Enter city, street and building #',
value: {
city: "Moscow",
street: "Lenina",
building: "15"
}
});
});
</script>
**/
(function ($) {
var Address = function (options) {
this.init('address', options, Address.defaults);
};
//inherit from Abstract input
$.fn.editableutils.inherit(Address, $.fn.editabletypes.abstractinput);
$.extend(Address.prototype, {
/**
Renders input from tpl
@method render()
**/
render: function() {
this.$input = this.$tpl.find('input');
},
/**
Default method to show value in element. Can be overwritten by display option.
@method value2html(value, element)
**/
value2html: function(value, element) {
if(!value) {
$(element).empty();
return;
}
var html = $('<div>').text(value.city).html() + ', ' + $('<div>').text(value.street).html() + ' st., bld. ' + $('<div>').text(value.building).html();
$(element).html(html);
},
/**
Gets value from element's html
@method html2value(html)
**/
html2value: function(html) {
/*
you may write parsing method to get value by element's html
e.g. "Moscow, st. Lenina, bld. 15" => {city: "Moscow", street: "Lenina", building: "15"}
but for complex structures it's not recommended.
Better set value directly via javascript, e.g.
editable({
value: {
city: "Moscow",
street: "Lenina",
building: "15"
}
});
*/
return null;
},
/**
Converts value to string.
It is used in internal comparing (not for sending to server).
@method value2str(value)
**/
value2str: function(value) {
var str = '';
if(value) {
for(var k in value) {
str = str + k + ':' + value[k] + ';';
}
}
return str;
},
/*
Converts string to value. Used for reading value from 'data-value' attribute.
@method str2value(str)
*/
str2value: function(str) {
/*
this is mainly for parsing value defined in data-value attribute.
If you will always set value by javascript, no need to overwrite it
*/
return str;
},
/**
Sets value of input.
@method value2input(value)
@param {mixed} value
**/
value2input: function(value) {
this.$input.filter('[name="city"]').val(value.city);
this.$input.filter('[name="street"]').val(value.street);
this.$input.filter('[name="building"]').val(value.building);
},
/**
Returns value of input.
@method input2value()
**/
input2value: function() {
return {
city: this.$input.filter('[name="city"]').val(),
street: this.$input.filter('[name="street"]').val(),
building: this.$input.filter('[name="building"]').val()
};
},
/**
Activates input: sets focus on the first field.
@method activate()
**/
activate: function() {
this.$input.filter('[name="city"]').focus();
},
/**
Attaches handler to submit form in case of 'showbuttons=false' mode
@method autosubmit()
**/
autosubmit: function() {
this.$input.keydown(function (e) {
if (e.which === 13) {
$(this).closest('form').submit();
}
});
}
});
Address.defaults = $.extend({}, $.fn.editabletypes.abstractinput.defaults, {
tpl: '<div class="editable-address"><label><span>City: </span><input type="text" name="city" class="input-small"></label></div>'+
'<div class="editable-address"><label><span>Street: </span><input type="text" name="street" class="input-small"></label></div>'+
'<div class="editable-address"><label><span>Building: </span><input type="text" name="building" class="input-mini"></label></div>',
inputclass: ''
});
$.fn.editabletypes.address = Address;
}(window.jQuery)); |
function insertMealsPins(map, data){
var infowindows = new Array (); // creates an array to hold the info windows for each restaurant
for (var i = data["meals"].length - 1; i >= 0; i--) {
var pins, html, attendees, pinLatLng, pinMarkers, button;
pins = data["meals"][i];
if (pins["restaurant"]["attending"]) {
var button = '<div id="meal-pin" data-meal-id='+ pins['id']+'><input type="submit" name="commit" value="Remove this Meal!" class="btn btn-danger remove"></div>';
} else if ( pins["restaurant"]["hosting"] ) {
var button = '<div id="meal-pin" data-meal-id='+ pins['id']+'><input type="submit" name="commit" value="Cancel This Meal!" class="btn btn-danger cancel"></div>';
} else {
var button = '<div id="meal-pin" data-meal-id='+ pins['id']+'><input type="submit" name="commit" value="Join This Meal!" class="btn btn-info join"></div>';
}
var date = new Date(pins['date']).toString();
html = '<h4>'+pins['restaurant']['name']+'</h4>' +'<p>'+ date +'</p>'+'<p>'+pins['restaurant']['address_line1']+'</p>'
if ( pins['restaurant']['phone'] ) {
html += '<p>'+ pins['restaurant']['phone']+'</p>';
}
if ( pins['restaurant']['menu'] ) {
html += '<a href="' + pins['restaurant']['menu']+ '">Menu</a>';
}
html += button;
// attendees = "<p>Attending:</p>"
// pins["attendees"].forEach(function(attendee){
// attendees += "<p>" + attendee + "</p>"
// })
// if ( pins["attendees"].length === 0 ) {
// attendees += "No one attending yet!"
// };
// html += attendees;
pinLatLng = new google.maps.LatLng(parseFloat(pins['restaurant']['lat']), parseFloat(pins['restaurant']['lng']));
pinMarkers = new google.maps.Marker({position: pinLatLng, map: map, animation: google.maps.Animation.Drop});
infowindows[i] = new google.maps.InfoWindow();
infowindows[i].setContent(html);
var prevOpenWindow = false;
google.maps.event.addListener(pinMarkers, "click", (function(pinMarkers, i) {
return function() {
if (prevOpenWindow) {
prevOpenWindow.close();
}
prevOpenWindow = infowindows[i];
infowindows[i].open(map, pinMarkers);
};
})(pinMarkers, i));
}
}
|
/**
* Socket Configuration
*
* These configuration options provide transparent access to Sails' encapsulated
* pubsub/socket server for complete customizability.
*
* For more information on using Sails with Sockets, check out:
* http://sailsjs.org/#documentation
*/
module.exports.sockets = {
// This custom onConnect function will be run each time AFTER a new socket connects
// (To control whether a socket is allowed to connect, check out `authorization` config.)
// Keep in mind that Sails' RESTful simulation for sockets
// mixes in socket.io events for your routes and blueprints automatically.
onConnect: function( session, socket) {
// By default: do nothing
// This is a good place to subscribe a new socket to a room, inform other users that
// someone new has come online, or any other custom socket.io logic
// If a user is logged in, subscribe to them
// sails.log.debug( "socket.id" );
// sails.log.debug( socket.id );
// sails.log.debug( "session" );
// sails.log.debug( session );
if( session.user ){
OnlineUser.find( { userId : session.user.id } , function( err, existsUser ){
if( !existsUser || existsUser.socketId != socket.id ){
OnlineUser.create({ socketId: socket.id , userId: session.user.id , name: session.user.name } , function( err , onlineUser ){
sails.log.debug( "I am online " , session.user.name );
sails.log.debug( "UserId " , session.user.id );
if(err) { sails.log.debug(err) };
});
}
});
//Annouce to friend you are online
Friend.find( { friendIds : session.user.id , accepted : ['A','W']} , function( err , friends ) {
// sails.log.debug( "onlineFriends" );
if( friends && friends.length > 0 ){
var friendIdList = [];
for( var i = 0; i < friends.length ; i++){
if( friends[i].friendIds[0] != session.user.id ){
friendIdList.push( friends[i].friendIds[0] )
}else{
friendIdList.push( friends[i].friendIds[1] )
}
}
//Find online friends
var io = sails.io;
// sails.log.debug( friendIdList );
OnlineUser.find( { userId : friendIdList } , function( err, onlineFriends ){
sails.log.debug( "say onlineFriends" );
onlineFriends.forEach( function( item ) {
io.sockets.socket( item.socketId ).emit( "newOnlineFriend" , { userId : session.user.id , name : session.user.name } );
});
});
}
});
//NOW JOIN THE ONLINE ROOM
socket.join('onlineRoom');
}
},
// This custom onDisconnect function will be run each time a socket disconnects
onDisconnect: function(session, socket) {
// By default: do nothing
// This is a good place to broadcast a disconnect message, or any other custom socket.io logic
if( session.user ){
var io = sails.io;
sails.log.debug( "say offline" , session.user.name );
sails.log.debug( "say offline userId" , session.user.id );
io.sockets.emit( "userGetOffline", { userId : session.user.id });
OnlineUser.destroy({ userId: session.user.id }).done( function( err ){
if(err) { sails.log.debug(err) };
});
}
},
// `transports`
//
// A array of allowed transport methods which the clients will try to use.
// The flashsocket transport is disabled by default
// You can enable flashsockets by adding 'flashsocket' to this list:
transports: [
'websocket',
'htmlfile',
'xhr-polling',
'jsonp-polling'
],
// Use this option to set the datastore socket.io will use to manage rooms/sockets/subscriptions:
// default: memory
adapter: 'memory',
// Node.js (and consequently Sails.js) apps scale horizontally.
// It's a powerful, efficient approach, but it involves a tiny bit of planning.
// At scale, you'll want to be able to copy your app onto multiple Sails.js servers
// and throw them behind a load balancer.
//
// One of the big challenges of scaling an application is that these sorts of clustered
// deployments cannot share memory, since they are on physically different machines.
// On top of that, there is no guarantee that a user will "stick" with the same server between
// requests (whether HTTP or sockets), since the load balancer will route each request to the
// Sails server with the most available resources. However that means that all room/pubsub/socket
// processing and shared memory has to be offloaded to a shared, remote messaging queue (usually Redis)
//
// Luckily, Socket.io (and consequently Sails.js) apps support Redis for sockets by default.
// To enable a remote redis pubsub server:
// adapter: 'redis',
// host: '127.0.0.1',
// port: 6379,
// db: 'sails',
// pass: '<redis auth password>'
// Worth mentioning is that, if `adapter` config is `redis`,
// but host/port is left unset, Sails will try to connect to redis
// running on localhost via port 6379
// `authorization`
//
// Global authorization for Socket.IO access,
// this is called when the initial handshake is performed with the server.
//
// By default (`authorization: true`), when a socket tries to connect, Sails verifies
// that a valid cookie was sent with the upgrade request. If the cookie doesn't match
// any known user session, a new user session is created for it.
//
// However, in the case of cross-domain requests, it is possible to receive a connection
// upgrade request WITHOUT A COOKIE (for certain transports)
// In this case, there is no way to keep track of the requesting user between requests,
// since there is no identifying information to link him/her with a session.
//
// If you don't care about keeping track of your socket users between requests,
// you can bypass this cookie check by setting `authorization: false`
// which will disable the session for socket requests (req.session is still accessible
// in each request, but it will be empty, and any changes to it will not be persisted)
//
// On the other hand, if you DO need to keep track of user sessions,
// you can pass along a ?cookie query parameter to the upgrade url,
// which Sails will use in the absense of a proper cookie
// e.g. (when connection from the client):
// io.connect('http://localhost:1337?cookie=smokeybear')
//
// (Un)fortunately, the user's cookie is (should!) not accessible in client-side js.
// Using HTTP-only cookies is crucial for your app's security.
// Primarily because of this situation, as well as a handful of other advanced
// use cases, Sails allows you to override the authorization behavior
// with your own custom logic by specifying a function, e.g:
/*
authorization: function authorizeAttemptedSocketConnection(reqObj, cb) {
// Any data saved in `handshake` is available in subsequent requests
// from this as `req.socket.handshake.*`
//
// to allow the connection, call `cb(null, true)`
// to prevent the connection, call `cb(null, false)`
// to report an error, call `cb(err)`
}
*/
authorization: true,
// Match string representing the origins that are allowed to connect to the Socket.IO server
origins: '*:*',
// Should we use heartbeats to check the health of Socket.IO connections?
heartbeats: true,
// When client closes connection, the # of seconds to wait before attempting a reconnect.
// This value is sent to the client after a successful handshake.
'close timeout': 60,
// The # of seconds between heartbeats sent from the client to the server
// This value is sent to the client after a successful handshake.
'heartbeat timeout': 60,
// The max # of seconds to wait for an expcted heartbeat before declaring the pipe broken
// This number should be less than the `heartbeat timeout`
'heartbeat interval': 25,
// The maximum duration of one HTTP poll-
// if it exceeds this limit it will be closed.
'polling duration': 20,
// Enable the flash policy server if the flashsocket transport is enabled
// 'flash policy server': true,
// By default the Socket.IO client will check port 10843 on your server
// to see if flashsocket connections are allowed.
// The Adobe Flash Player normally uses 843 as default port,
// but Socket.io defaults to a non root port (10843) by default
//
// If you are using a hosting provider that doesn't allow you to start servers
// other than on port 80 or the provided port, and you still want to support flashsockets
// you can set the `flash policy port` to -1
'flash policy port': 10843,
// Used by the HTTP transports. The Socket.IO server buffers HTTP request bodies up to this limit.
// This limit is not applied to websocket or flashsockets.
'destroy buffer size': '10E7',
// Do we need to destroy non-socket.io upgrade requests?
'destroy upgrade': true,
// Should Sails/Socket.io serve the `socket.io.js` client?
// (as well as WebSocketMain.swf for Flash sockets, etc.)
'browser client': true,
// Cache the Socket.IO file generation in the memory of the process
// to speed up the serving of the static files.
'browser client cache': true,
// Does Socket.IO need to send a minified build of the static client script?
'browser client minification': false,
// Does Socket.IO need to send an ETag header for the static requests?
'browser client etag': false,
// Adds a Cache-Control: private, x-gzip-ok="", max-age=31536000 header to static requests,
// but only if the file is requested with a version number like /socket.io/socket.io.v0.9.9.js.
'browser client expires': 315360000,
// Does Socket.IO need to GZIP the static files?
// This process is only done once and the computed output is stored in memory.
// So we don't have to spawn a gzip process for each request.
'browser client gzip': false,
// Optional override function to serve all static files,
// including socket.io.js et al.
// Of the form :: function (req, res) { /* serve files */ }
'browser client handler': false,
// Meant to be used when running socket.io behind a proxy.
// Should be set to true when you want the location handshake to match the protocol of the origin.
// This fixes issues with terminating the SSL in front of Node
// and forcing location to think it's wss instead of ws.
'match origin protocol': false,
// Direct access to the socket.io MQ store config
// The 'adapter' property is the preferred method
// (`undefined` indicates that Sails should defer to the 'adapter' config)
store: undefined,
// A logger instance that is used to output log information.
// (`undefined` indicates deferment to the main Sails log config)
logger: undefined,
// The amount of detail that the server should output to the logger.
// (`undefined` indicates deferment to the main Sails log config)
'log level': undefined,
// Whether to color the log type when output to the logger.
// (`undefined` indicates deferment to the main Sails log config)
'log colors': undefined,
// A Static instance that is used to serve the socket.io client and its dependencies.
// (`undefined` indicates use default)
'static': undefined,
// The entry point where Socket.IO starts looking for incoming connections.
// This should be the same between the client and the server.
resource: '/socket.io'
}; |
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var assets = require('connect-assets');
var routes = require('./routes/index');
var users = require('./routes/users');
var position = require('./routes/position');
var app = express();
var APP_HOST = "0.0.0.0";
var APP_PORT = 8888;
app.listen(APP_PORT, APP_HOST, function() {
console.log("Web server listening on " + APP_HOST + ":" + APP_PORT);
});
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'bower_components')));
app.use('/', routes);
app.use('/users', users);
app.use('/position', position);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
|
const expect = require('chai').expect;
const isLetter = require('../src/isLetter');
// 测试
describe('isLetter字母的测试集合', function() {
// 'ABC'
it('isLetter(\'ABC\') 等于 true', function() {
expect(isLetter('ABC')).to.be.equal(true);
});
// ''
it('isLetter(\'\') 等于 false', function() {
expect(isLetter('')).to.be.equal(false);
});
// ' '
it('isLetter(\' \') 等于 false', function() {
expect(isLetter('')).to.be.equal(false);
});
// 'ABC3'
it('isLetter(\'ABC3\') 等于 false', function() {
expect(isLetter('ABC3')).to.be.equal(false);
});
// 'A A'
it('isLetter(\'A A\') 等于 false', function() {
expect(isLetter('A A')).to.be.equal(false);
});
});
|
module.exports = function(grunt){
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
less: {
development: {
options: {
compress: false,
optimization: 2,
ieCompat:true
},
files: {
"css/main.css": "less/main.less" // destination file and source file
}
}
},
concat: {
options: {
separator: '\r\t',
},
dist: {
src: [
'node_modules/jquery/dist/jquery.min.js',
'node_modules/angular/angular.min.js',
'node_modules/angular/modules/ng-infinite-scroll.min.js',
'app/flickr_Mod/module.js',
'app/flickr_Mod/service.js',
'app/flickr_Mod/directive.js',
'app/history_Mod/module.js',
'app/history_Mod/service.js',
'app/history_Mod/directive.js',
'app/btq_Mod/module.js',
'app/btq_Mod/ui-service.js',
'app/btq_Mod/directive.js',
'app/btq_Mod/controller.js'
],
dest: 'app/main.js',
},
},
watch: {
styles: {
files: ['less/**/*.less'], // which files to watch
tasks: ['less'],
options: {
nospawn: true
}
},
concat: {
files: ['app/**/*.js'],
tasks: ['concat'],
options: {
nospawn: true
}
}
}
});
grunt.loadNpmTasks('grunt-contrib-less');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.registerTask('default', ['less','concat','watch']);
} |
'use strict';
var tabject = require('../');
console.log(tabject(process, { maxValueLength: 100, excludeKeys: [ 'env' ] }));
|
import React from 'react';
import PropTypes from 'prop-types';
import { injectIntl, intlShape, defineMessages, FormattedMessage } from 'react-intl';
import Typography from '@material-ui/core/Typography';
import { languageLabel } from '../../../LanguageRegistry';
import SmoochBotMainMenuSection from './SmoochBotMainMenuSection';
const messages = defineMessages({
privacyStatement: {
id: 'smoochBotMainMenu.privacyStatement',
defaultMessage: 'Privacy statement',
description: 'Menu label used in the tipline bot',
},
});
const SmoochBotMainMenu = ({
value,
languages,
intl,
onChange,
}) => {
const resources = value.smooch_custom_resources || [];
const handleChangeTitle = (newValue, menu) => {
onChange({ smooch_menu_title: newValue }, menu);
};
const handleChangeMenuOptions = (newOptions, menu) => {
onChange({ smooch_menu_options: newOptions }, menu);
};
return (
<React.Fragment>
<Typography variant="subtitle2" component="div">
<FormattedMessage id="smoochBotMainMenu.mainMenu" defaultMessage="Main menu" description="Title of the tipline bot main menu settings page." />
</Typography>
<Typography component="div" variant="body2">
<FormattedMessage
id="smoochBotMainMenu.subtitle"
defaultMessage="The menu of your bot, asking the user to choose between a set of options. The second section is optional. Please note that on WhatsApp you can have at maximum 10 menu options across all sections."
description="Subtitle displayed in tipline settings page for the main menu."
/>
</Typography>
<SmoochBotMainMenuSection
number={1}
value={value.smooch_state_main}
resources={resources}
onChangeTitle={(newValue) => { handleChangeTitle(newValue, 'smooch_state_main'); }}
onChangeMenuOptions={(newOptions) => { handleChangeMenuOptions(newOptions, 'smooch_state_main'); }}
/>
<SmoochBotMainMenuSection
number={2}
value={value.smooch_state_secondary}
resources={resources}
onChangeTitle={(newValue) => { handleChangeTitle(newValue, 'smooch_state_secondary'); }}
onChangeMenuOptions={(newOptions) => { handleChangeMenuOptions(newOptions, 'smooch_state_secondary'); }}
optional
/>
<SmoochBotMainMenuSection
number={3}
value={
languages.length > 1 ?
{
smooch_menu_title: <FormattedMessage id="smoochBotMainMenu.languagesAndPrivacy" defaultMessage="Languages and Privacy" description="Title of the main menu third section of the tipline where there is more than one supported language" />,
smooch_menu_options: languages.map(l => ({ smooch_menu_option_label: languageLabel(l) })).concat({ smooch_menu_option_label: intl.formatMessage(messages.privacyStatement) }),
} :
{
smooch_menu_title: <FormattedMessage id="smoochBotMainMenu.privacy" defaultMessage="Privacy" description="Title of the main menu third section of the tipline when there is only one supported language" />,
smooch_menu_options: [{ smooch_menu_option_label: intl.formatMessage(messages.privacyStatement) }],
}
}
onChangeTitle={() => {}}
onChangeMenuOptions={() => {}}
readOnly
/>
</React.Fragment>
);
};
SmoochBotMainMenu.defaultProps = {
value: {},
languages: [],
};
SmoochBotMainMenu.propTypes = {
value: PropTypes.object,
languages: PropTypes.arrayOf(PropTypes.string),
intl: intlShape.isRequired,
onChange: PropTypes.func.isRequired,
};
export default injectIntl(SmoochBotMainMenu);
|
/*! commands/site-settings.js */
var CP = CP || {};
CP.CommandList = CP.CommandList || [];
(function (constants, util) {
'use strict';
var strings = constants.Strings,
siteType = constants.SiteTypes;
CP.CommandList = CP.CommandList.concat([
{
command: strings.siteSettings + ': ' + strings.usersAndPermissions + ': People and groups',
fn: function () {
util.goToPage(strings.layouts + 'people.aspx');
}
},
{
command: strings.siteSettings + ': ' + strings.usersAndPermissions + ': Site permissions',
fn: function () {
util.goToPage(strings.layouts + 'user.aspx');
}
},
{
command: strings.siteSettings + ': ' + strings.usersAndPermissions + ': Site collection administrators',
fn: function () {
util.goToPage(strings.layouts + 'mngsiteadmin.aspx');
}
},
{
command: strings.siteSettings + ': ' + strings.usersAndPermissions + ': Site app permissions',
fn: function () {
util.goToPage(strings.layouts + 'appprincipals.aspx?Scope=Web');
}
},
{
command: strings.siteSettings + ': ' + strings.webDesignerGalleries + ': Site columns',
fn: function () {
util.goToPage(strings.layouts + 'mngfield.aspx');
}
},
{
command: strings.siteSettings + ': ' + strings.webDesignerGalleries + ': Site content types',
fn: function () {
util.goToPage(strings.layouts + 'mngctype.aspx');
}
},
{
command: strings.siteSettings + ': ' + strings.webDesignerGalleries + ': Web parts',
fn: function () {
util.goToPage('/_catalogs/wp/Forms/AllItems');
}
},
{
command: strings.siteSettings + ': ' + strings.webDesignerGalleries + ': List templates',
fn: function () {
util.goToPage('/_catalogs/lt/Forms/AllItems');
}
},
{
command: strings.siteSettings + ': ' + strings.webDesignerGalleries + ': Master pages',
fn: function () {
util.goToPage('/_catalogs/masterpage/Forms/AllItems');
}
},
{
command: strings.siteSettings + ': ' + strings.webDesignerGalleries + ': Themes',
fn: function () {
util.goToPage('/_catalogs/theme/Forms/AllItems');
}
},
{
command: strings.siteSettings + ': ' + strings.webDesignerGalleries + ': Solutions',
fn: function () {
util.goToPage('/_catalogs/solutions/Forms/AllItems');
}
},
{
command: strings.siteSettings + ': ' + strings.webDesignerGalleries + ': Composed looks',
fn: function () {
util.goToPage('/_catalogs/design/AllItems.aspx');
}
},
{
command: strings.siteSettings + ': ' + strings.siteAdmin + ': Regional settings',
fn: function () {
util.goToPage(strings.layouts + 'regionalsetng.aspx');
}
},
{
command: strings.siteSettings + ': ' + strings.siteAdmin + ': Language settings',
fn: function () {
util.goToPage(strings.layouts + 'muisetng.aspx');
}
},
{
command: strings.siteSettings + ': ' + strings.siteAdmin + ': Site libraries and lists',
fn: function () {
util.goToPage(strings.layouts + 'mcontent.aspx');
}
},
{
command: strings.siteSettings + ': ' + strings.siteAdmin + ': User alerts',
fn: function () {
util.goToPage(strings.layouts + 'sitesubs.aspx');
}
},
{
command: strings.siteSettings + ': ' + strings.siteAdmin + ': RSS',
fn: function () {
util.goToPage(strings.layouts + 'siterss.aspx');
}
},
{
command: strings.siteSettings + ': ' + strings.siteAdmin + ': Sites and workspaces',
fn: function () {
util.goToPage(strings.layouts + 'mngsubwebs.aspx');
}
},
{
command: strings.siteSettings + ': ' + strings.siteAdmin + ': Workflow settings',
fn: function () {
util.goToPage(strings.layouts + 'wrksetng.aspx');
}
},
{
command: strings.siteSettings + ': ' + strings.siteAdmin + ': Site output cache',
exclude: [siteType.collab],
fn: function () {
util.goToPage(strings.layouts + 'areacachesettings.aspx');
}
},
{
command: strings.siteSettings + ': ' + strings.siteAdmin + ': Site Closure and Deletion',
exclude: [siteType.pub],
fn: function () {
util.goToPage(strings.layouts + 'ProjectPolicyAndLifecycle.asp');
}
},
{
command: strings.siteSettings + ': ' + strings.siteAdmin + ': Popularity Trends',
exclude: [siteType.collab],
fn: function () {
util.goToPage('/_layouts/15/Reporting.aspx?Category=AnalyticsSite');
}
},
{
command: strings.siteSettings + ': ' + strings.siteAdmin + ': Content and structure',
exclude: [siteType.collab],
fn: function () {
util.goToPage('/_layouts/15/sitemanager.aspx?Source={WebUrl}_layouts/15/settings.aspx');
}
},
{
command: strings.siteSettings + ': ' + strings.siteAdmin + ': Manage catalog connections',
exclude: [siteType.collab],
fn: function () {
util.goToPage('/_layouts/15/ManageCatalogSources.aspx');
}
},
{
command: strings.siteSettings + ': ' + strings.siteAdmin + ': Content and structure logs',
exclude: [siteType.collab],
fn: function () {
util.goToPage('/_layouts/15/SiteManager.aspx?lro=all');
}
},
{
command: strings.siteSettings + ': ' + strings.siteAdmin + ': Site variation settings',
exclude: [siteType.collab],
fn: function () {
util.goToPage('/_layouts/15/VariationsSiteSettings.aspx');
}
},
{
command: strings.siteSettings + ': ' + strings.siteAdmin + ': Translation Status',
exclude: [siteType.collab],
fn: function () {
util.goToPage('/_layouts/15/RedirectPage.aspx?Target={SiteCollectionUrl}Translation Status');
}
},
{
command: strings.siteSettings + ': ' + strings.siteAdmin + ': Term store management',
fn: function () {
util.goToPage(strings.layouts + 'termstoremanager.aspx');
}
},
{
command: strings.siteSettings + ': Search: Result Sources',
fn: function () {
util.goToPage(strings.layouts + 'manageresultsources.aspx?level=site');
}
},
{
command: strings.siteSettings + ': Search: Result Types',
fn: function () {
util.goToPage(strings.layouts + 'manageresulttypes.aspx');
}
},
{
command: strings.siteSettings + ': Search: Query Rules',
fn: function () {
util.goToPage(strings.layouts + 'listqueryrules.aspx');
}
},
{
command: strings.siteSettings + ': Search: Schema',
fn: function () {
util.goToPage(strings.layouts + 'listmanagedproperties.aspx');
}
},
{
command: strings.siteSettings + ': Search: Search Settings',
fn: function () {
util.goToPage('/_layouts/enhancedSea/ch/aspx?level');
}
},
{
command: strings.siteSettings + ': Search: Searchable columns',
exclude: [siteType.collab],
fn: function () {
util.goToPage(strings.layouts + 'NoCrawlSettings.aspx');
}
},
{
command: strings.siteSettings + ': Search: Search and offline availability',
fn: function () {
util.goToPage(strings.layouts + 'srchvis.aspx');
}
},
{
command: strings.siteSettings + ': Search: Configuration Import',
fn: function () {
util.goToPage(strings.layouts + 'importsearchconfiguration.aspx');
}
},
{
command: strings.siteSettings + ': Search: Configuration Import',
fn: function () {
util.goToPage(strings.layouts + 'importsearchconfiguration.aspx');
}
},
{
command: strings.siteSettings + ': Search: Configuration Export',
fn: function () {
util.goToPage(strings.layouts + 'exportsearchconfiguration.aspx');
}
},
{
command: strings.siteSettings + ': ' + strings.lookAndFeel + ': Design Manager',
fn: function () {
util.goToPage(strings.layouts + 'RedirectPage.aspx?Target={SiteCollectionUrl}{LayoutsFolder}DesignSite.aspx');
}
},
{
command: strings.siteSettings + ': ' + strings.lookAndFeel + ': Master page',
fn: function () {
util.goToPage(strings.layouts + 'ChangeSiteMasterPage.aspx');
}
},
{
command: strings.siteSettings + ': ' + strings.lookAndFeel + ': Title, description, and logo',
fn: function () {
util.goToPage(strings.layouts + 'prjsetng.aspx');
}
},
{
command: strings.siteSettings + ': ' + strings.lookAndFeel + ': Quick launch',
exclude: [siteType.pub],
fn: function () {
util.goToPage(strings.layouts + 'quiklnch.aspx.aspx');
}
},
{
command: strings.siteSettings + ': ' + strings.lookAndFeel + ': Top link bar',
exclude: [siteType.pub],
fn: function () {
util.goToPage(strings.layouts + 'topnav.aspx.aspx');
}
},
{
command: strings.siteSettings + ': ' + strings.lookAndFeel + ': Page layouts and site templates',
exclude: [siteType.collab],
fn: function () {
util.goToPage(strings.layouts + 'AreaTemplateSettings.aspx');
}
},
{
command: strings.siteSettings + ': ' + strings.lookAndFeel + ': Welcome Page',
exclude: [siteType.collab],
fn: function () {
util.goToPage(strings.layouts + 'AreaWelcomePage.aspx');
}
},
{
command: strings.siteSettings + ': ' + strings.lookAndFeel + ': Device Channels',
exclude: [siteType.collab],
fn: function () {
util.goToPage(strings.layouts + 'RedirectPage.aspx?Target={SiteCollectionUrl}DeviceChannels');
}
},
{
command: strings.siteSettings + ': ' + strings.lookAndFeel + ': Tree view',
fn: function () {
util.goToPage(strings.layouts + 'navoptions.aspx');
}
},
{
command: strings.siteSettings + ': ' + strings.lookAndFeel + ': Change the look',
fn: function () {
util.goToPage(strings.layouts + 'designgallery.aspx');
}
},
{
command: strings.siteSettings + ': ' + strings.lookAndFeel + ': Import Design Package',
exclude: [siteType.collab],
fn: function () {
util.goToPage(strings.layouts + 'DesignPackageInstall.aspx');
}
},
{
command: strings.siteSettings + ': ' + strings.lookAndFeel + ': Navigation',
exclude: [siteType.collab],
fn: function () {
util.goToPage(strings.layouts + 'AreaNavigationSettings.aspx');
}
},
{
command: strings.siteSettings + ': ' + strings.lookAndFeel + ': Image Renditions',
exclude: [siteType.collab],
fn: function () {
util.goToPage(strings.layouts + 'ImageRenditionSettings.aspx');
}
},
{
command: strings.siteSettings + ': Site Actions: Manage site features',
fn: function () {
util.goToPage(strings.layouts + 'ManageFeatures.aspx');
}
},
{
command: strings.siteSettings + ': Site Actions: Save site as template',
exclude: [siteType.pub],
fn: function () {
util.goToPage(strings.layouts + 'savetmpl.aspx');
}
},
{
command: strings.siteSettings + ': Site Actions: Enable search configuration export',
exclude: [siteType.pub],
fn: function () {
util.goToPage(strings.layouts + 'Enablesearchconfigsettings.aspx');
}
},
{
command: strings.siteSettings + ': Site Actions: Reset to site definition',
fn: function () {
util.goToPage(strings.layouts + 'reghost.aspx');
}
},
{
command: strings.siteSettings + ': Site Actions: Delete this site',
fn: function () {
util.goToPage(strings.layouts + 'deleteweb.aspx');
}
},
{
command: strings.siteSettings + ': ' + strings.siteCollectionAdmin + ': Recycle bin',
fn: function () {
util.goToPage(strings.layouts + 'AdminRecycleBin.aspx');
}
},
{
command: strings.siteSettings + ': ' + strings.siteCollectionAdmin + ': Search Result Sources',
fn: function () {
util.goToPage(strings.layouts + 'manageresultsources.aspx?level=sitecol');
}
},
{
command: strings.siteSettings + ': ' + strings.siteCollectionAdmin + ': Search Result Types',
fn: function () {
util.goToPage(strings.layouts + 'manageresulttypes.aspx?level=sitecol');
}
},
{
command: strings.siteSettings + ': ' + strings.siteCollectionAdmin + ': Search Query Rules',
fn: function () {
util.goToPage(strings.layouts + 'listqueryrules.aspx?level=sitecol');
}
},
{
command: strings.siteSettings + ': ' + strings.siteCollectionAdmin + ': Search Schema',
fn: function () {
util.goToPage(strings.layouts + 'listmanagedproperties.aspx?level=sitecol');
}
},
{
command: strings.siteSettings + ': ' + strings.siteCollectionAdmin + ': Search Settings',
fn: function () {
util.goToPage('/_layouts/enhancedSearch.aspx?level=sitecol');
}
},
{
command: strings.siteSettings + ': ' + strings.siteCollectionAdmin + ': Search Configuration Import',
fn: function () {
util.goToPage(strings.layouts + 'importsearchconfiguration.aspx?level=sitecol');
}
},
{
command: strings.siteSettings + ': ' + strings.siteCollectionAdmin + ': Search Configuration Export',
fn: function () {
util.goToPage(strings.layouts + 'exportsearchconfiguration.aspx?level=sitecol');
}
},
{
command: strings.siteSettings + ': ' + strings.siteCollectionAdmin + ': Site collection features',
fn: function () {
util.goToPage(strings.layouts + 'ManageFeatures.aspx?Scope=Site');
}
},
{
command: strings.siteSettings + ': ' + strings.siteCollectionAdmin + ': Site hierarchy',
fn: function () {
util.goToPage(strings.layouts + 'vsubwebs.aspx');
}
},
{
command: strings.siteSettings + ': ' + strings.siteCollectionAdmin + ': Search engine optimization settings',
exclude: [siteType.collab],
fn: function () {
util.goToPage(strings.layouts + 'SEOSettings.aspx');
}
},
{
command: strings.siteSettings + ': ' + strings.siteCollectionAdmin + ': Site collection navigation',
fn: function () {
util.goToPage(strings.layouts + 'SiteNavigationSettings.aspx');
}
},
{
command: strings.siteSettings + ': ' + strings.siteCollectionAdmin + ': Site collection audit settings',
fn: function () {
util.goToPage(strings.layouts + 'AuditSettings.aspx');
}
},
{
command: strings.siteSettings + ': ' + strings.siteCollectionAdmin + ': Audit log reports',
fn: function () {
util.goToPage(strings.layouts + 'Reporting.aspx?Category=Auditing');
}
},
{
command: strings.siteSettings + ': ' + strings.siteCollectionAdmin + ': Portal site connection',
fn: function () {
util.goToPage(strings.layouts + 'portal.aspx');
}
},
{
command: strings.siteSettings + ': ' + strings.siteCollectionAdmin + ': Content Type Policy Templates',
fn: function () {
util.goToPage(strings.layouts + 'Policylist.aspx');
}
},
{
command: strings.siteSettings + ': ' + strings.siteCollectionAdmin + ': Storage Metrics',
exclude: [siteType.collab],
fn: function () {
util.goToPage(strings.layouts + 'storman.aspx');
}
},
{
command: strings.siteSettings + ': ' + strings.siteCollectionAdmin + ': Site collection app permissions',
fn: function () {
util.goToPage(strings.layouts + 'appprincipals.aspx');
}
},
{
command: strings.siteSettings + ': ' + strings.siteCollectionAdmin + ': Content type publishing',
fn: function () {
util.goToPage(strings.layouts + 'contenttypesyndicationhubs.aspx');
}
},
{
command: strings.siteSettings + ': ' + strings.siteCollectionAdmin + ': Site collection output cache',
exclude: [siteType.collab],
fn: function () {
util.goToPage(strings.layouts + 'sitecachesettings.aspx');
}
},
{
command: strings.siteSettings + ': ' + strings.siteCollectionAdmin + ': Popularity and Search Reports',
fn: function () {
util.goToPage(strings.layouts + 'Reporting.aspx?Category=AnalyticsSiteCollection');
}
},
{
command: strings.siteSettings + ': ' + strings.siteCollectionAdmin + ': Variations Settings',
exclude: [siteType.collab],
fn: function () {
util.goToPage(strings.layouts + 'VariationSettings.aspx');
}
},
{
command: strings.siteSettings + ': ' + strings.siteCollectionAdmin + ': Variation labels',
exclude: [siteType.collab],
fn: function () {
util.goToPage(strings.layouts + 'VariationLabels.aspx');
}
},
{
command: strings.siteSettings + ': ' + strings.siteCollectionAdmin + ': Translatable columns',
exclude: [siteType.collab],
fn: function () {
util.goToPage(strings.layouts + 'SiteTranslatableColumns.aspx');
}
},
{
command: strings.siteSettings + ': ' + strings.siteCollectionAdmin + ': Variation logs',
exclude: [siteType.collab],
fn: function () {
util.goToPage(strings.layouts + 'VariationLogs.aspx');
}
},
{
command: strings.siteSettings + ': ' + strings.siteCollectionAdmin + ': Suggested Content Browser Locations',
exclude: [siteType.collab],
fn: function () {
util.goToPage('/PublishedLinks/');
}
},
{
command: strings.siteSettings + ': ' + strings.siteCollectionAdmin + ': HTML Field Security',
fn: function () {
util.goToPage(strings.layouts + 'HtmlFieldSecurity.aspx');
}
},
{
command: strings.siteSettings + ': ' + strings.siteCollectionAdmin + ': SharePoint Designer Settings',
fn: function () {
util.goToPage(strings.layouts + 'SharePointDesignerSettings.aspx');
}
},
{
command: strings.siteSettings + ': ' + strings.siteCollectionAdmin + ': Site collection health checks',
fn: function () {
util.goToPage(strings.layouts + 'sitehealthcheck.aspx');
}
},
{
command: strings.siteSettings + ': ' + strings.siteCollectionAdmin + ': Site collection upgrade',
fn: function () {
util.goToPage(strings.layouts + 'siteupgrade.aspx');
}
}
]);
})(CP.Constants, CP.Util);
|
export default {
food: {
festivalMenuEmpty: 'Festival menu is empty for now. We will publish it later.'
}
}
|
import create from './index.tpl'
import './index.styl'
export default create({
props: {
source: {
type: Object,
default: () => ({
html: '',
javascript: '',
css: ''
})
},
defIndex: {
type: Number,
default: 0
}
},
data() {
return {
languages: [
'html',
'javascript',
'css'
],
index: this.defIndex,
}
},
watch: {
index() {
this.toogle()
},
defIndex(newVal) {
this.index = newVal
}
},
mounted() {
this.setTabMainHeight()
},
methods: {
setTabMainHeight() {
let maxHeight = 0
const nodes = this.$refs.tabMain.childNodes
;[].forEach.call(nodes, (node) => {
if (node.nodeType === 1) {
let offsetHeight = node.offsetHeight
if (offsetHeight > maxHeight) {
maxHeight = offsetHeight
}
}
})
this.$refs.tabMain.style.height = maxHeight + 'px'
this.toogle()
},
toogle() {
let nodes = [].slice.call(this.$refs.tabMain.childNodes)
nodes.filter(
node => node.nodeType === 1
).forEach((node, k) =>
node.style.display = this.index === k ? 'block' : 'none'
)
}
}
})
|
var casper = require('casper').create();
casper.start('http://casperjs.azurewebsites.net', function(){
this.waitForSelector('#countrySelect', function(){
this.echo(this.getTitle());
});
});
casper.then(function(){
this.waitUntilVisible('#countrySelect', function(){
this.clickLabel('Info','a');
});
});
casper.then(function() {
this.waitUntilVisible('#info-form', function(){
this.fill('form#info-form', {
'FirstName': 'John',
'LastName': 'Smith'
});
this.evaluate(function(){
$('input[type="submit"]').click();
return;
});
});
});
casper.then(function() {
this.waitFor(function check() {
return this.evaluate(function(){
return ($("#response").text().length > 0);
});
}, function then()
{
this.echo('The text is' + this.fetchText('#response'));
});
});
casper.run(function(){
this.echo(this.getTitle());
this.echo('finished');
this.exit();
}); |
import * as topojson from 'topojson-client';
import reach from '../../constants/reach.js';
import utils from '../utils/index.js';
import sources from '../../constants/sources.js';
function sourceRoads({ map }) {
return fetch(reach.ROADS)
.then((response) => response.json())
.then((topo) => {
const layerName = Object.keys(topo.objects)[0];
const { features } = topojson.feature(topo, topo.objects[layerName]);
const newFeatures = features.map(modifyFeatures);
utils.addSourceToMap({ features: newFeatures, map, sourceId: sources.ROADS });
});
}
function modifyFeatures(feature) {
const newFeature = feature;
return newFeature;
}
export default sourceRoads;
|
var User = require('../index');
var expect = require('chai').expect;
var noop = require('101/noop');
var Model = require('../lib/models/base');
var Collection = require('../lib/collections/base');
var mockClient = {
post: noop,
patch: noop,
del: noop
};
var modelOpts = {
client: mockClient
};
function collectionOpts (qs) {
var opts = {};
opts.qs = qs;
opts.client = mockClient;
return opts;
}
describe('collection destroy', function () {
var ctx = {};
before(function (done) {
Model.prototype.urlPath = 'path';
done();
});
after(function (done) {
delete Model.prototype.urlPath;
done();
});
before(function (done) {
Model.prototype.urlPath = 'path';
Collection.prototype.urlPath = 'path';
Collection.prototype.Model = Model;
done();
});
after(function (done) {
delete Model.prototype.urlPath;
delete Collection.prototype.urlPath;
delete Collection.prototype.Model;
done();
});
beforeEach(function (done) {
ctx.model = new Model({ _id: '1' }, modelOpts);
ctx.collection = new Collection([ ctx.model ], collectionOpts());
done();
});
afterEach(function (done) {
ctx = {};
done();
});
it('should destroy a model and assume success', function (done) {
ctx.collection.destroy(ctx.model, noop);
expect(ctx.collection.models.length).to.equal(0);
done();
});
it('should destroy a model and revert on error', function (done) {
ctx.model.client.del = function (url, opts, cb) {
cb(new Error());
};
ctx.collection.destroy(ctx.model, noop);
expect(ctx.collection.models.length).to.equal(1);
done();
});
}); |
const emojiFromWord = require("emoji-from-word")
, countWordsArray = require("count-words-array")
;
/**
* emojiFromText
*
* @name emojiFromText
* @function
* @param {String} s The input text.
* @param {Boolean} f If `true`, only the first object from array will be returned.
* @return {Array} An array of objects containing:
*
* - `name` (String): The word name.
* - `score` (Number): The match score.
* - `match` (Match): A [`Match`](https://github.com/IonicaBizau/emoji-from-word#matchinput) instance.
*
* The array is ordered by score.
*/
module.exports = function emojiFromText(s, f) {
if (f) {
return emojiFromText(s)[0];
}
var w = countWordsArray(s, true);
w.forEach(c => {
c.match = emojiFromWord(c.name)
if (!c.match.emoji_name) {
c.match = emojiFromWord("memo")
c.match.score = 0.2;
}
c.score = (
c.match.score * 4
+ c.name.length * 2
+ c.count * 3
+ c.match.emoji_name.length * 0.5
) / 4;
})
w.sort((a, b) => {
return a.score < b.score ? 1 : -1;
});
return w;
};
|
const debug = require("debug")("ferreiro:setup:database");
const mongoose = require("mongoose");
const bluebird = require("bluebird");
const env = require("../env");
const mongoDB = env.DB_URI;
module.exports = () => {
//Set up default mongoose connection
mongoose.Promise = bluebird;
mongoose.connect(
mongoDB,
{
useMongoClient: true,
},
(error) => {
if (error) {
throw error;
}
debug("Successfully connected to MongoDB");
}
);
};
|
const initialCode = `
// import
const { createApp } = Frint;
const { render, observe, streamProps } = FrintReact;
const { createStore, combineReducers } = FrintStore;
// constants
const INCREMENT_COUNTER = 'INCREMENT_COUNTER';
const DECREMENT_COUNTER = 'DECREMENT_COUNTER';
// actions
function incrementCounter() {
return {
type: INCREMENT_COUNTER
};
}
function decrementCounter() {
return {
type: DECREMENT_COUNTER
};
}
// reducers
const INITIAL_STATE = {
value: 0
};
function counterReducer(state = INITIAL_STATE, action) {
switch (action.type) {
case INCREMENT_COUNTER:
return Object.assign({}, {
value: state.value + 1
});
case DECREMENT_COUNTER:
return Object.assign({}, {
value: state.value - 1
});
default:
return state;
}
}
const rootReducer = combineReducers({
counter: counterReducer,
});
// component
const Root = observe(function (app) {
const store = app.get('store');
return streamProps({})
.set(
store.getState$(),
state => ({ counter: state.counter.value })
)
.setDispatch({
increment: incrementCounter,
decrement: decrementCounter,
}, store)
.get$();
})(function (props) {
const { counter, increment, decrement } = props;
return (
<div>
<p>Counter value: <code>{counter}</code></p>
<div>
<button
className="button button-primary"
onClick={() => increment()}
>
+
</button>
<button
className="button"
onClick={() => decrement()}
>
-
</button>
</div>
</div>
);
});
// App
const App = createApp({
name: 'MyTestApp',
providers: [
{
name: 'component',
useValue: Root
},
{
name: 'store',
useFactory: ({ app }) => {
const Store = createStore({
initialState: {
counter: {
value: 5,
}
},
reducer: rootReducer,
deps: { app },
});
return new Store();
},
deps: ['app'],
},
]
});
// render
const app = new App();
render(app, document.getElementById('root'));
`.trim();
// editor
const editor = ace.edit('editor');
editor.setTheme('ace/theme/chrome');
editor.getSession().setMode('ace/mode/javascript');
editor.getSession().setTabSize(4);
editor.getSession().setUseSoftTabs(true);
editor.setShowPrintMargin(false);
function renderToRoot() {
ReactDOM.unmountComponentAtNode(document.getElementById('root'));
const input = editor.getValue();
try {
const output = Babel.transform(input, {
presets: [
'es2015',
'react',
]
}).code;
eval(output);
updateUrlHash(input);
} catch (error) {
throw error;
}
}
function parseHashParams(hash) {
const params = hash
.split('#?')[1];
if (!params) {
return {};
}
return params
.split('&')
.map(function (item) {
const kv = item.split('=');
const key = kv[0];
const value = kv[1];
return { [key]: value };
})
.reduce(function (acc, val) {
return Object.assign({}, acc, val);
}, {});
}
function updateUrlHash(code = null) {
const currentHashParams= parseHashParams(location.hash);
currentHashParams.code = escape(code);
const stringifiedParams = Object.keys(currentHashParams)
.map(function (key) {
return key + '=' + currentHashParams[key];
})
.join('&');
if (history.pushState) {
history.pushState(null, null, '#?' + stringifiedParams);
}
}
(function () {
// get code from URL on first page-load
const parsedParams = parseHashParams(location.hash);
if (typeof parsedParams.code !== 'undefined') {
editor.setValue(unescape(parsedParams.code));
} else {
editor.setValue(initialCode);
}
// re-render on changes
editor.getSession().on('change', _.debounce(function (e) {
renderToRoot();
}, 300));
// initial render
renderToRoot();
})();
|
/**
* Module dependencies.
*/
// var path = require('path');
var development = require('./env/development');
// var test = require('./env/test');
// var production = require('./env/production');
// var defaults = {
// root: path.normalize(__dirname + '/..')
// };
/**
* Expose
*/
module.exports = {
development: development,
// test: Object.assign({}, test, defaults),
// production: Object.assign({}, production, defaults)
}[process.env.NODE_ENV || 'development'];
|
const { GraphQLEnumType } = require('graphql')
const CODES = {
ab: 'Abkhaz',
aa: 'Afar',
af: 'Afrikaans',
ak: 'Akan',
sq: 'Albanian',
am: 'Amharic',
ar: 'Arabic',
an: 'Aragonese',
hy: 'Armenian',
as: 'Assamese',
av: 'Avaric',
ae: 'Avestan',
ay: 'Aymara',
az: 'Azerbaijani',
bm: 'Bambara',
ba: 'Bashkir',
eu: 'Basque',
be: 'Belarusian',
bn: 'Bengali',
bh: 'Bihari',
bi: 'Bislama',
bs: 'Bosnian',
br: 'Breton',
bg: 'Bulgarian',
my: 'Burmese',
ca: 'Catalan',
ch: 'Chamorro',
ce: 'Chechen',
ny: 'Chichewa',
zh: 'Chinese',
cv: 'Chuvash',
kw: 'Cornish',
co: 'Corsican',
cr: 'Cree',
hr: 'Croatian',
cs: 'Czech',
da: 'Danish',
dv: 'Divehi',
nl: 'Dutch',
dz: 'Dzongkha',
en: 'English',
eo: 'Esperanto',
et: 'Estonian',
ee: 'Ewe',
fo: 'Faroese',
fj: 'Fijian',
fi: 'Finnish',
fr: 'French',
ff: 'Fula',
gl: 'Galician',
ka: 'Georgian',
de: 'German',
el: 'Greek',
gn: 'Guaraní',
gu: 'Gujarati',
ht: 'Haitian',
ha: 'Hausa',
he: 'Hebrew',
hz: 'Herero',
hi: 'Hindi',
ho: 'Hiri Motu',
hu: 'Hungarian',
ia: 'Interlingua',
id: 'Indonesian',
ie: 'Interlingue',
ga: 'Irish',
ig: 'Igbo',
ik: 'Inupiaq',
io: 'Ido',
is: 'Icelandic',
it: 'Italian',
iu: 'Inuktitut',
ja: 'Japanese',
jv: 'Javanese',
kl: 'Kalaallisut',
kn: 'Kannada',
kr: 'Kanuri',
ks: 'Kashmiri',
kk: 'Kazakh',
km: 'Khmer',
ki: 'Kikuyu',
rw: 'Kinyarwanda',
ky: 'Kyrgyz',
kv: 'Komi',
kg: 'Kongo',
ko: 'Korean',
ku: 'Kurdish',
kj: 'Kwanyama',
la: 'Latin',
lb: 'Luxembourgish',
lg: 'Ganda',
li: 'Limburgish',
ln: 'Lingala',
lo: 'Lao',
lt: 'Lithuanian',
lu: 'Luba-Katanga',
lv: 'Latvian',
gv: 'Manx',
mk: 'Macedonian',
mg: 'Malagasy',
ms: 'Malay',
ml: 'Malayalam',
mt: 'Maltese',
mi: 'Māori',
mr: 'Marathi (Marāṭhī)',
mh: 'Marshallese',
mn: 'Mongolian',
na: 'Nauruan',
nv: 'Navajo',
nd: 'Northern Ndebele',
ne: 'Nepali',
ng: 'Ndonga',
nb: 'Norwegian Bokmål',
nn: 'Norwegian Nynorsk',
no: 'Norwegian',
ii: 'Nuosu',
nr: 'Southern Ndebele',
oc: 'Occitan',
oj: 'Ojibwe',
cu: 'Old Church SlavonicChurch SlavonicOld Bulgarian',
om: 'Oromo',
or: 'Oriya',
os: 'Ossetian',
pa: '(Eastern) Punjabi',
pi: 'Pāli',
fa: 'Persian',
pl: 'Polish',
ps: 'Pashto',
pt: 'Portuguese',
qu: 'Quechua',
rm: 'Romansh',
rn: 'Kirundi',
ro: 'Romanian',
ru: 'Russian',
sa: 'Sanskrit (Saṁskṛta)',
sc: 'Sardinian',
sd: 'Sindhi',
se: 'Northern Sami',
sm: 'Samoan',
sg: 'Sango',
sr: 'Serbian',
gd: 'Scottish Gaelic',
sn: 'Shona',
si: 'Sinhalese',
sk: 'Slovak',
sl: 'Slovene',
so: 'Somali',
st: 'Southern Sotho',
es: 'Spanish',
su: 'Sundanese',
sw: 'Swahili',
ss: 'Swati',
sv: 'Swedish',
ta: 'Tamil',
te: 'Telugu',
tg: 'Tajik',
th: 'Thai',
ti: 'Tigrinya',
bo: 'Tibetan Standard',
tk: 'Turkmen',
tl: 'Tagalog',
tn: 'Tswana',
to: 'Tonga',
tr: 'Turkish',
ts: 'Tsonga',
tt: 'Tatar',
tw: 'Twi',
ty: 'Tahitian',
ug: 'Uyghur',
uk: 'Ukrainian',
ur: 'Urdu',
uz: 'Uzbek',
ve: 'Venda',
vi: 'Vietnamese',
vo: 'Volapük',
wa: 'Walloon',
cy: 'Welsh',
wo: 'Wolof',
fy: 'Western Frisian',
xh: 'Xhosa',
yi: 'Yiddish',
yo: 'Yoruba',
za: 'Zhuang',
zu: 'Zulu'
}
exports.CODES = CODES
const values = {}
for (let code in CODES) {
values[code] = {
description: CODES[code],
value: code
}
}
exports.ISOLanguage = new GraphQLEnumType({
name: 'ISO639_1',
description: 'languages',
values
})
|
Dagaz.Controller.persistense = "none";
ZRF = {
JUMP: 0,
IF: 1,
FORK: 2,
FUNCTION: 3,
IN_ZONE: 4,
FLAG: 5,
SET_FLAG: 6,
POS_FLAG: 7,
SET_POS_FLAG: 8,
ATTR: 9,
SET_ATTR: 10,
PROMOTE: 11,
MODE: 12,
ON_BOARD_DIR: 13,
ON_BOARD_POS: 14,
PARAM: 15,
LITERAL: 16,
VERIFY: 20
};
Dagaz.Model.BuildDesign = function(design) {
design.checkVersion("z2j", "2");
design.checkVersion("animate-captures", "false");
design.checkVersion("smart-moves", "true");
design.checkVersion("show-blink", "false");
design.checkVersion("show-hints", "false");
design.addDirection("w");
design.addDirection("e");
design.addDirection("s");
design.addDirection("n");
design.addPlayer("You", [1, 0, 3, 2]);
design.addPosition("a5", [0, 1, 5, 0]);
design.addPosition("b5", [-1, 1, 5, 0]);
design.addPosition("c5", [-1, 0, 5, 0]);
design.addPosition("d5", [0, 1, 2, 3]);
design.addPosition("e5", [0, 1, 2, 3]);
design.addPosition("a4", [0, 1, 5, -5]);
design.addPosition("b4", [-1, 1, 5, -5]);
design.addPosition("c4", [-1, 0, 5, -5]);
design.addPosition("d4", [0, 1, 2, 3]);
design.addPosition("e4", [0, 1, 2, 3]);
design.addPosition("a3", [0, 1, 0, -5]);
design.addPosition("b3", [-1, 1, 0, -5]);
design.addPosition("c3", [-1, 1, 5, -5]);
design.addPosition("d3", [-1, 1, 5, 0]);
design.addPosition("e3", [-1, 0, 5, 0]);
design.addPosition("a2", [0, 1, 2, 3]);
design.addPosition("b2", [0, 1, 2, 3]);
design.addPosition("c2", [0, 1, 5, -5]);
design.addPosition("d2", [-1, 1, 5, -5]);
design.addPosition("e2", [-1, 0, 5, -5]);
design.addPosition("a1", [0, 1, 2, 3]);
design.addPosition("b1", [0, 1, 2, 3]);
design.addPosition("c1", [0, 1, 0, -5]);
design.addPosition("d1", [-1, 1, 0, -5]);
design.addPosition("e1", [-1, 0, 0, -5]);
design.addZone("white-goal", 1, [10, 5, 0, 11, 6, 1, 7, 2]);
design.addZone("black-goal", 1, [22, 17, 23, 18, 13, 24, 19, 14]);
design.addCommand(0, ZRF.FUNCTION, 24); // from
design.addCommand(0, ZRF.PARAM, 0); // $1
design.addCommand(0, ZRF.FUNCTION, 22); // navigate
design.addCommand(0, ZRF.FUNCTION, 1); // empty?
design.addCommand(0, ZRF.FUNCTION, 20); // verify
design.addCommand(0, ZRF.FUNCTION, 25); // to
design.addCommand(0, ZRF.FUNCTION, 28); // end
design.addCommand(1, ZRF.FUNCTION, 24); // from
design.addCommand(1, ZRF.PARAM, 0); // $1
design.addCommand(1, ZRF.FUNCTION, 22); // navigate
design.addCommand(1, ZRF.FUNCTION, 1); // empty?
design.addCommand(1, ZRF.FUNCTION, 0); // not
design.addCommand(1, ZRF.FUNCTION, 20); // verify
design.addCommand(1, ZRF.PARAM, 1); // $2
design.addCommand(1, ZRF.FUNCTION, 22); // navigate
design.addCommand(1, ZRF.FUNCTION, 1); // empty?
design.addCommand(1, ZRF.FUNCTION, 20); // verify
design.addCommand(1, ZRF.FUNCTION, 25); // to
design.addCommand(1, ZRF.FUNCTION, 28); // end
design.addPiece("White", 0);
design.addMove(0, 0, [0], 0);
design.addMove(0, 1, [0, 0], 0);
design.addMove(0, 0, [3], 0);
design.addMove(0, 1, [3, 3], 0);
design.addPiece("Black", 1);
design.addMove(1, 0, [1], 0);
design.addMove(1, 1, [1, 1], 0);
design.addMove(1, 0, [2], 0);
design.addMove(1, 1, [2, 2], 0);
design.setup("You", "White", 22);
design.setup("You", "White", 17);
design.setup("You", "White", 23);
design.setup("You", "White", 18);
design.setup("You", "White", 13);
design.setup("You", "White", 24);
design.setup("You", "White", 19);
design.setup("You", "White", 14);
design.setup("You", "Black", 10);
design.setup("You", "Black", 5);
design.setup("You", "Black", 0);
design.setup("You", "Black", 11);
design.setup("You", "Black", 6);
design.setup("You", "Black", 1);
design.setup("You", "Black", 7);
design.setup("You", "Black", 2);
}
Dagaz.View.configure = function(view) {
view.defBoard("Board");
view.defPiece("YouWhite", "You White");
view.defPiece("YouBlack", "You Black");
view.defPosition("a5", 2, 2, 68, 68);
view.defPosition("b5", 70, 2, 68, 68);
view.defPosition("c5", 138, 2, 68, 68);
view.defPosition("d5", 206, 2, 68, 68);
view.defPosition("e5", 274, 2, 68, 68);
view.defPosition("a4", 2, 70, 68, 68);
view.defPosition("b4", 70, 70, 68, 68);
view.defPosition("c4", 138, 70, 68, 68);
view.defPosition("d4", 206, 70, 68, 68);
view.defPosition("e4", 274, 70, 68, 68);
view.defPosition("a3", 2, 138, 68, 68);
view.defPosition("b3", 70, 138, 68, 68);
view.defPosition("c3", 138, 138, 68, 68);
view.defPosition("d3", 206, 138, 68, 68);
view.defPosition("e3", 274, 138, 68, 68);
view.defPosition("a2", 2, 206, 68, 68);
view.defPosition("b2", 70, 206, 68, 68);
view.defPosition("c2", 138, 206, 68, 68);
view.defPosition("d2", 206, 206, 68, 68);
view.defPosition("e2", 274, 206, 68, 68);
view.defPosition("a1", 2, 274, 68, 68);
view.defPosition("b1", 70, 274, 68, 68);
view.defPosition("c1", 138, 274, 68, 68);
view.defPosition("d1", 206, 274, 68, 68);
view.defPosition("e1", 274, 274, 68, 68);
}
|
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var ObjectId = Schema.Types.ObjectId;
var timestamp = require('mongoose-timestamp');
var ActivityStatusSchema = new Schema({
isPassed: {
type: Boolean,
default: false
},
problems: {
type: Boolean,
default: false
},
videos: {
type: Boolean,
default: false
},
from: {
type: String,
enum: ['pc', 'mobile'],
default: 'pc'
},
user: { type: ObjectId, ref: 'User'},
rooms: [
{ type: ObjectId, ref: 'Room'}
],
schools: { type: ObjectId, ref: 'School' },
chapter: { type: ObjectId, ref: 'Chapter' },
topic: { type: ObjectId, ref: 'Topic' },
task: { type: ObjectId, ref: 'Task' },
activity: { type: ObjectId, ref: 'Activity' }
}, { collection: 'activity_status' });
ActivityStatusSchema.plugin(timestamp);
mongoose.model('ActivityStatus', ActivityStatusSchema);
module.exports = ActivityStatusSchema; |
(function(root, undefined) {
"use strict";
/* draglune main */
var callback;
// Base function.
var draglune = function () {
};
draglune.makeFileDrop = function(o, b) {
if (!(o && o.nodeType && o.nodeType === 1 && b && b instanceof Function)) {
return false;
}
o.addEventListener("dragover", function (e) {
e.preventDefault();
});
o.addEventListener("dragenter", function (e) {
e.preventDefault();
});
o.addEventListener("drop", function (e) {
b(e.dataTransfer.files);
e.preventDefault();
});
return true;
};
draglune.readFromDrop = function(o, b) {
callback = b;
var r = draglune.makeFileDrop(o, reader);
if (!r || !FileReader) {
return false;
}
};
var reader = function(fileList) {
var textArray = [];
fileList.foreach(function (file, index, array) {
if(file.type === 'text/plain'){
var reader = new FileReader();
reader.readAsText(file);
reader.addEventListener('load', function(){
textArray.push(reader.result);
if (index == array.length) {
callback(textArray);
}
}, false);
}
});
};
// Version.
draglune.VERSION = '0.0.0';
// Export to the root, which is probably `window`.
root.draglune = draglune;
}(this));
|
import { composeWithTracker } from 'react-komposer';
import { Meteor } from 'meteor/meteor';
import { Giveaway } from '../../components/giveaways/giveaway';
import { Loading } from '../../components/loading';
import { Giveaways } from '../../../api/giveaways/giveaways';
const composer = (props, onData) => {
if (Meteor.subscribe('giveaway-by-id', props.gaId).ready()) {
onData(null, {
ga: Giveaways.findOne(props.gaId),
});
}
};
export default composeWithTracker(composer, Loading)(Giveaway);
|
const express = require('express');
const PaginationController = require('./pagination.controller');
const router = express.Router();
const curdy = require('./../../../../../../index');
router.use('/', curdy.generateRoutes(PaginationController));
module.exports = router;
|
/**
* Created by peter on 9/15/16.
*/
// ==UserScript==
// @name Axel Episodes
// @namespace http://v.numag.net/grease/
// @description grab all episodes for axel download
// @include http://hyper.numag.net/*/
// @include http://amsterdam.hikerlink.org/youtube/*/
// @include http://riku.numag.net/youtube/*/
// ==/UserScript==
(function () {
function $x() {
var x='';
var node=document;
var type=0;
var fix=true;
var i=0;
var cur;
function toArray(xp) {
var final=[], next;
while (next=xp.iterateNext()) {
final.push(next);
}
return final;
}
while (cur=arguments[i++]) {
switch (typeof cur) {
case "string": x+=(x=='') ? cur : " | " + cur; continue;
case "number": type=cur; continue;
case "object": node=cur; continue;
case "boolean": fix=cur; continue;
}
}
if (fix) {
if (type==6) type=4;
if (type==7) type=5;
}
// selection mistake helper
if (!/^\//.test(x)) x="//"+x;
// context mistake helper
if (node!=document && !/^\./.test(x)) x="."+x;
var result=document.evaluate(x, node, null, type, null);
if (fix) {
// automatically return special type
switch (type) {
case 1: return result.numberValue;
case 2: return result.stringValue;
case 3: return result.booleanValue;
case 8:
case 9: return result.singleNodeValue;
}
}
return fix ? toArray(result) : result;
};
var elmNewContent = document.createElement('div');
elmNewContent.textContent = $x("/html/body/pre/a/@href").slice(1).map(function (element) {
return 'x256 ' + window.location.href + element.value;
}).join([separator = '; ']);
elmNewContent.setAttribute("style", "color: #5fba7d; font-family: 'Raleway',sans-serif; font-size: 12px; font-weight: 500; line-height: 16px; margin: 0 0 24px; ");
document.body.appendChild(elmNewContent);
})();
|
'use strict';
var SockJS = require('../sockjs-stream'),
_URL = require('url');
function buildBuilder (client, opts) {
var wsOpt = {
protocol: 'mqttv3.1'
},
host = opts.hostname || 'localhost',
port = String(opts.port || 80),
path = opts.path || '/',
url = opts.protocol + '://' + host + ':' + port + path;
if ('wss' === opts.protocol) {
if (opts.hasOwnProperty('rejectUnauthorized')) {
wsOpt.rejectUnauthorized = opts.rejectUnauthorized;
}
}
return websocket(url/*, wsOpt*/);
}
function buildBuilderBrowser (mqttClient, opts) {
var url,
parsed = _URL.parse(document.URL);
if (!opts.protocol) {
if ('https:' === parsed.protocol) {
opts.protocol = 'https';
} else {
opts.protocol = 'http';
}
}
if (!opts.hostname) {
opts.hostnme = opts.host;
}
if (!opts.hostname) {
opts.hostname = parsed.hostname;
if (!opts.port) {
opts.port = parsed.port;
}
}
if (!opts.port) {
if ('https' === opts.protocol) {
opts.port = 443;
} else {
opts.port = 80;
}
}
if(opts.protocol == 'sockjss') opts.protocol = 'https';
else opts.protocol = 'http';
if (!opts.path) {
opts.path = '/';
}
url = opts.protocol + '://' + opts.hostname + ':' + opts.port + opts.path;
//変更
return SockJS(url);
}
if ('browser' !== process.title) {
module.exports = buildBuilder;
} else {
module.exports = buildBuilderBrowser;
}
|
import Ember from 'ember';
import config from '../config/environment';
export default Ember.Service.extend({
upload(file) {
const data = new FormData();
data.append(`value`, file);
return Ember.$.ajax({
data,
method: `POST`,
cache: false,
processData: false,
contentType: false,
url: `${config.apiHost}/api/containers/${config.containerName}/upload`,
});
},
destroyImage(file) {
const url = file.replace(`download`, `files`);
return Ember.$.ajax({
method: `DELETE`,
url,
});
},
deserializeResponse(response) {
const data = response.result.files.value[0];
return `${config.apiHost}/api/containers/${data.container}/download/${data.name}`;
},
requestError(err) {
// Handle request errors here
console.log(err);
},
});
|
angular.module('resources.applicant', [
'services.djangorestresource',
])
.factory('applicantFactory', [
'DjangoRestResource',
function($resource) {
return $resource('/api/applicants/:applicant_id/', {
applicant_id: "@id_no"
},
{
query: {}
});
}
]) |
$(document).ready(function () {
var pagetop = $('#pagetop');
var menu = $('#menu');
var menuButton = $('#menu-btn');
document.documentElement.clientWidth;
var windowWidth = window.innerWidth;
var windowHeight = window.innerHeight;
$(window).resize(function () {
document.documentElement.clientWidth;
if (windowWidth == window.innerWidth) {
return;
}
windowWidth = window.innerWidth;
windowHeight = window.innerHeight;
if (windowWidth <= 640) {
menu.css('display', 'none');
}
else {
menu.css('display', 'block');
}
});
$(window).scroll(function () {
if ($(this).scrollTop() > 1) {
pagetop.fadeIn();
}
else {
pagetop.fadeOut();
}
});
pagetop.click(function () {
$('body, html').animate({
scrollTop: 0
}, 500);
});
menuButton.click(function () {
menu.slideToggle('slow');
});
});
//GoogleAnalytics
(function (i, s, o, g, r, a, m) {
i['GoogleAnalyticsObject'] = r;
i[r] = i[r] || function () {
(i[r].q = i[r].q || []).push(arguments)
},
i[r].l = 1 * new Date();
a = s.createElement(o),
m = s.getElementsByTagName(o)[0];
a.async = 1;
a.src = g;
m.parentNode.insertBefore(a, m)
})(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga');
ga('create', 'UA-84301135-1', 'auto');
ga('send', 'pageview'); |
var gulp = require('gulp');
var path = require('path');
var ts = require('gulp-typescript');
var mocha = require('gulp-mocha');
gulp.task('build', function() {
var tsProject = ts.createProject(path.resolve('./tsconfig.json'));
return gulp
.src(path.resolve('./src/**/*.ts'))
.pipe(ts(tsProject))
.pipe(gulp.dest('./output'))
});
gulp.task('test', ['build'], function() {
return gulp.src('./output/**/*tests*.js', { read: false })
.pipe(mocha({}));
});
gulp.task('default', ['build', 'test']);
|
SIP.LoggerFactory.prototype.debug =
SIP.LoggerFactory.prototype.log =
SIP.LoggerFactory.prototype.warn =
SIP.LoggerFactory.prototype.error = function f() {};
describe('ClientContext', function() {
var ClientContext;
var ua;
var method;
var target;
var body;
var contentType;
beforeEach(function(){
spyOn(SIP, 'OutgoingRequest');
SIP.OutgoingRequest.send = jasmine.createSpy('send');
ua = new SIP.UA({uri: 'alice@example.com', wsServers: 'ws:server.example.com'});
ua.transport = jasmine.createSpyObj('transport', ['disconnect']);
method = SIP.C.INVITE;
target = 'alice@example.com';
body = '{"foo":"bar"}';
contentType = 'application/json';
ClientContext = new SIP.ClientContext(ua,method,target, {
body: body,
contentType: contentType
});
});
afterEach(function () {
ua.stop();
});
it('sets the ua', function() {
expect(ClientContext.ua).toBe(ua);
});
it('sets the logger', function() {
expect(ClientContext.logger).toBe(ua.getLogger('sip.clientcontext'));
});
it('sets the method', function() {
expect(ClientContext.method).toBe(method);
});
it('sets the body', function () {
expect(ClientContext.body).toBe('{"foo":"bar"}');
});
it('has no body by default', function () {
expect(new SIP.ClientContext(ua,method,target).body).not.toBeDefined();
});
it('sets the contentType', function () {
expect(ClientContext.contentType).toBe('application/json');
});
it('has no contentType by default', function () {
expect(new SIP.ClientContext(ua,method,target).contentType).not.toBeDefined();
});
it('initializes data', function() {
expect(ClientContext.data).toBeDefined();
});
it('initializes events', function() {
expect(ClientContext.checkEvent('progress')).toBeTruthy();
expect(ClientContext.checkEvent('accepted')).toBeTruthy();
expect(ClientContext.checkEvent('rejected')).toBeTruthy();
expect(ClientContext.checkEvent('failed')).toBeTruthy();
});
it('checks that the target is not undefined', function() {
expect(function () { new SIP.ClientContext(ua,method); }).toThrowError('Not enough arguments');
});
it('checks that the target is valid', function() {
spyOn(ClientContext.ua, 'normalizeTarget');
expect(function() { new SIP.ClientContext(ua,method,'alice@example.com'); }).toThrowError('Invalid target: alice@example.com');
});
it('creates a new outgoing request', function() {
expect(SIP.OutgoingRequest).toHaveBeenCalled();
expect(ClientContext.request).toBeDefined();
});
describe('.send', function() {
var options = {};
it('calls the send method', function() {
spyOn(SIP,'RequestSender').and.callFake(function() {
return {'send': SIP.OutgoingRequest.send};
});
ClientContext.send(options);
expect(SIP.OutgoingRequest.send).toHaveBeenCalled();
});
it('returns itself', function() {
spyOn(SIP,'RequestSender').and.callFake(function() {
return {'send': SIP.OutgoingRequest.send};
});
expect(ClientContext.send(options)).toBe(ClientContext);
});
});
describe('.receiveResponse', function() {
beforeEach(function() {
response = SIP.Parser.parseMessage('SIP/2.0 200 OK\r\nTo: <sip:james@onsnip.onsip.com>;tag=1ma2ki9411\r\nFrom: "test1" <sip:test1@onsnip.onsip.com>;tag=58312p20s2\r\nCall-ID: upfrf7jpeb3rmc0gnnq1\r\nCSeq: 9059 INVITE\r\nContact: <sip:gusgt9j8@vk3dj582vbu9.invalid;transport=ws>\r\nContact: <sip:gusgt9j8@vk3dj582vbu9.invalid;transport=ws>\r\nSupported: outbound\r\nContent-Type: application/sdp\r\nContent-Length: 11\r\n\r\na= sendrecv\r\n', ua);
});
it('emits progress on a 1xx response', function() {
spyOn(ClientContext, 'emit');
for (var i = 100; i < 200; i++) {
response.status_code = i;
ClientContext.receiveResponse(response);
expect(ClientContext.emit).toHaveBeenCalledWith('progress', response, SIP.C.REASON_PHRASE[response.status_code]|| '');
ClientContext.emit.calls.reset();
}
});
it('emits accepted on a 2xx response', function() {
spyOn(ClientContext, 'emit');
for (var i = 200; i < 300; i++) {
response.status_code = i;
ClientContext.receiveResponse(response);
expect(ClientContext.emit).toHaveBeenCalledWith('accepted', response, SIP.C.REASON_PHRASE[response.status_code]|| '');
ClientContext.emit.calls.reset();
}
});
it('emits rejected and failed on all other responses',function() {
spyOn(ClientContext, 'emit');
for (i = 300; i < 700; i++) {
response.status_code = i;
ClientContext.receiveResponse(response);
expect(ClientContext.emit).toHaveBeenCalledWith('rejected', response, SIP.C.REASON_PHRASE[response.status_code]|| '');
expect(ClientContext.emit).toHaveBeenCalledWith('failed', response, SIP.C.REASON_PHRASE[response.status_code]|| '');
ClientContext.emit.calls.reset();
}
});
});
describe('.onRequestTimeout', function() {
it('emits failed with a status code 0, null response, and request timeout cause', function() {
spyOn(ClientContext, 'emit');
ClientContext.onRequestTimeout();
expect(ClientContext.emit).toHaveBeenCalledWith('failed', null, SIP.C.causes.REQUEST_TIMEOUT);
});
});
describe('.onTransportError', function() {
it('emits failed with a status code 0, null response, and connection error cause', function() {
spyOn(ClientContext, 'emit');
ClientContext.onTransportError();
expect(ClientContext.emit).toHaveBeenCalledWith('failed',null,SIP.C.causes.CONNECTION_ERROR);
});
});
describe('.cancel', function () {
it('calls request.cancel', function () {
ClientContext.request = jasmine.createSpyObj('request', ['cancel']);
ClientContext.cancel();
expect(ClientContext.request.cancel).toHaveBeenCalled();
});
it('emits a cancel event', function() {
spyOn(ClientContext, 'emit');
ClientContext.request = jasmine.createSpyObj('request', ['cancel']);
ClientContext.cancel();
expect(ClientContext.emit).toHaveBeenCalledWith('cancel');
});
});
});
|
var fs = require('fs'),
read = fs.readFileSync;
var priv = __dirname+"/private/";
var config = {
"production": process.env.NODE_ENV == "production"
};
config.lite = {
prod: {
cert: priv+'lite/prod.crt.pem',
key: priv+'lite/prod.key.pem',
gateway: 'gateway.push.apple.com'
}, sandbox: {
cert: priv+'lite/dev.crt.pem',
key: priv+'lite/dev.key.pem',
gateway: 'gateway.sandbox.push.apple.com'
}
};
config.full = {
prod: {
cert: priv+'full/prod.crt.pem',
key: priv+'full/prod.key.pem',
gateway: 'gateway.push.apple.com'
}, sandbox: {
cert: priv+'full/dev.crt.pem',
key: priv+'full/dev.key.pem',
gateway: 'gateway.sandbox.push.apple.com'
}
}
console.log ("Is production: %s", config.production);
module.exports = config; |
var Combinatorics = require('js-combinatorics');
var Numbered = require('numbered');
// Util functions for generating schema and utterances
// ===================================================
// Convert a number range like 5-10 into an array of english words
function expandNumberRange(start, end, by) {
by = by || 1; //incrementing by 0 is a bad idea
var converted = [];
for (var i=start; i<=end; i+=by) {
converted.push( Numbered.stringify(i).replace(/-/g,' ') );
}
return converted;
}
// Determine if a curly brace expression is a Slot name literal
// Returns true if expression is of the form {-|Name}, false otherwise
function isSlotLiteral(braceExpression) {
return braceExpression.substring(0, 3) == "{-|";
}
// Recognize shortcuts in utterance definitions and swap them out with the actual values
function expandShortcuts(str, slots, dictionary) {
// If the string is found in the dictionary, just provide the matching values
if (typeof dictionary=="object" && typeof dictionary[str]!="undefined") {
return dictionary[str];
}
// Numbered ranges, ex: 5-100 by 5
var match = str.match(/(\d+)\s*-\s*(\d+)(\s+by\s+(\d+))?/);
if (match) {
return expandNumberRange(+match[1],+match[2],+match[4]);
}
return [str];
}
var slotIndexes = [];
function expandSlotValues (variations, slotSampleValues) {
var i;
var slot;
for (slot in slotSampleValues) {
var sampleValues = slotSampleValues[slot];
var idx = -1;
if (typeof slotIndexes[slot] !== "undefined") {
idx = slotIndexes[slot];
}
var newVariations = [];
// make sure we have enough variations that we can get through the sample values
// at least once for each alexa-app utterance... this isn't strictly as
// minimalistic as it could be.
//
// our *real* objective is to make sure that each sampleValue gets used once per
// intent, but each intent spans multiple utterances; it would require heavy
// restructuring of the way the utterances are constructed to keep track of
// whether every slot was given each sample value once within an Intent's set
// of utterances. So we take the easier route, which generates more utterances
// in the output (but still many less than we would get if we did the full
// cartesian product).
if (variations.length < sampleValues.length) {
var mod = variations.length;
var xtraidx = 0;
while (variations.length < sampleValues.length) {
variations.push (variations[xtraidx]);
xtraidx = (xtraidx + 1) % mod;
}
}
variations.forEach (function (variation, j) {
var newVariation = [];
variation.forEach (function (value, k) {
if (value == "slot-" + slot) {
idx = (idx + 1) % sampleValues.length;
slotIndexes[slot] = idx;
value = sampleValues[idx];
}
newVariation.push (value);
});
newVariations.push (newVariation);
});
variations = newVariations;
}
return variations;
}
// Generate a list of utterances from a template
function generateUtterances(str, slots, dictionary, exhaustiveUtterances) {
var placeholders=[], utterances=[], slotmap={}, slotValues=[];
// First extract sample placeholders values from the string
str = str.replace(/\{([^\}]+)\}/g, function(match,p1) {
if (isSlotLiteral(match)) {
return match;
}
var expandedValues=[], slot, values = p1.split("|");
// If the last of the values is a SLOT name, we need to keep the name in the utterances
if (values && values.length && values.length>1 && slots && typeof slots[values[values.length-1]]!="undefined") {
slot = values.pop();
}
values.forEach(function(val,i) {
Array.prototype.push.apply(expandedValues,expandShortcuts(val,slots,dictionary));
});
if (slot) {
slotmap[slot] = placeholders.length;
}
// if we're dealing with minimal utterances, we will delay the expansion of the
// values for the slots; all the non-slot expansions need to be fully expanded
// in the cartesian product
if (!exhaustiveUtterances && slot)
{
placeholders.push( [ "slot-" + slot ] );
slotValues[slot] = expandedValues;
}
else
{
placeholders.push( expandedValues );
}
return "{"+(slot || placeholders.length-1)+"}";
});
// Generate all possible combinations using the cartesian product
if (placeholders.length>0) {
var variations = Combinatorics.cartesianProduct.apply(Combinatorics,placeholders).toArray();
if (!exhaustiveUtterances)
{
variations = expandSlotValues (variations, slotValues);
}
// Substitute each combination back into the original string
variations.forEach(function(values) {
// Replace numeric placeholders
var utterance = str.replace(/\{(\d+)\}/g,function(match,p1){
return values[p1];
});
// Replace slot placeholders
utterance = utterance.replace(/\{(.*?)\}/g,function(match,p1){
return (isSlotLiteral(match)) ? match : "{"+values[slotmap[p1]]+"|"+p1+"}";
});
utterances.push( utterance );
});
}
else {
utterances = [str];
}
// Convert all {-|Name} to {Name} and +Name+ to {Name} to accomodate slot literals and optional slot literals
for (var idx in utterances) {
utterances[idx] = utterances[idx].replace(/\{\-\|/g, "{");
var strArray = utterances[idx].split(" ");
var strTemp = "";
var strTemp2 = "";
utterances[idx] = strArray.forEach(function(item){
strTemp = item.replace(/\+(.*?)/, "{");
strTemp = strTemp.replace(/\+$/, "}");
strTemp2 += " " + strTemp;
});
utterances[idx] = strTemp2;
utterances[idx] = utterances[idx].trim();
}
// // Convert all {-|Name} to {Name} to accomodate slot literals
// for (var idx in utterances) {
// utterances[idx] = utterances[idx].replace(/\{\-\|/g, "{");
// }
return utterances;
}
module.exports = generateUtterances;
|
import { h } from 'omi';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(h("path", {
d: "M4 14h4v-4H4v4zm0 5h4v-4H4v4zM4 9h4V5H4v4zm5 5h12v-4H9v4zm0 5h12v-4H9v4zM9 5v4h12V5H9z"
}), 'ViewList'); |
/**
* BOOK.js
*
* @description :: TODO: You might write a short summary of how this model works and what it represents here.
* @docs :: http://sailsjs.org/#!documentation/models
*/
module.exports = {
attributes: {
}
};
|
"use strict";
module.exports = function(str, firstAppend){
if (typeof str === 'number'){
return str + 1;
}
if (typeof str !== 'string'){
return '1';
}
if (str.length === 0) {
return '1';
}
var name = str.replace(/\d+$/, '');
var number = str.split('').reduce(function(res, letter){
if (letter.match(/^\d$/)) {
res += letter;
}
else {
res = '';
}
return res;
}, '');
if(number !== '') {
return name + (Number(number) + 1);
}
if (typeof firstAppend === 'number') {
return name + ' ' + firstAppend;
}
if (typeof firstAppend !== 'string') {
return name + ' 2';
}
if (firstAppend.match(/\d$/)) {
return name + firstAppend;
}
return name + firstAppend +'2';
};
|
import React, {Component} from 'react';
import { connect } from 'react-redux';
import Chart from '../components/chart';
import googleMap from '../components/google_Maps.js';
class WeatherList extends Component {
renderWeather(cityData) {
const name = cityData.city.name;
const temps = cityData.list.map(tempArray => tempArray.main.temp);
const pressure = cityData.list.map(presArray => presArray.main.pressure);
const humidity = cityData.list.map(humArray => humArray.main.humidity);
const { lon, lat } = cityData.city.coord;
return (
<tr key={name}>
<td> <googleMap lon={lon} lat={lat} /> </td>
<td> <Chart
data={temps.map(temp => temp - 273.15)}
color="green"
unit="(°C)" /></td>
<td> <Chart data={pressure} color="red" unit="(hPa)" /></td>
<td> <Chart data={humidity} color="blue" unit="(%)" /></td>
</tr>
)
}
render() {
return (
<table className="table table-hover">
<thead>
<tr>
<th> City </th>
<th> Temperature (°C) </th>
<th> Pressure (hPa) </th>
<th> Humidity (%) </th>
</tr>
</thead>
<tbody>
{this.props.weather.map(this.renderWeather)}
</tbody>
</table>
);
}
}
function mapStateToProps(state) {
return {weather: state.weather}
}
export default connect(mapStateToProps) (WeatherList)
|
exports.ContextProvider = require('./lib/providers/Context').default
exports.ExecutionProvider = require('./lib/providers/Execution').default
exports.PropsProvider = require('./lib/providers/Props').default
exports.PathProvider = require('./lib/providers/Path').default
exports.ReduxProvider = require('./lib/providers/Redux').default
|
module.exports = {
addSourcesTasks: stub()
}; |
/* global io */
'use strict';
angular.module('appManagerApp')
.factory('socket', function(socketFactory) {
// socket.io now auto-configures its connection when we ommit a connection url
var ioSocket = io('', {
// Send auth token on connection, you will need to DI the Auth service above
// 'query': 'token=' + Auth.getToken()
path: '/socket.io-client'
});
var socket = socketFactory({
ioSocket: ioSocket
});
return {
socket: socket,
/**
* Register listeners to sync an array with updates on a model
*
* Takes the array we want to sync, the model name that socket updates are sent from,
* and an optional callback function after new items are updated.
*
* @param {String} modelName
* @param {Array} array
* @param {Function} cb
*/
syncUpdates: function (modelName, array, cb) {
cb = cb || angular.noop;
/**
* Syncs item creation/updates on 'model:save'
*/
socket.on(modelName + ':save', function (item) {
var oldItem = _.find(array, {_id: item._id});
var index = array.indexOf(oldItem);
var event = 'created';
// replace oldItem if it exists
// otherwise just add item to the collection
if (oldItem) {
array.splice(index, 1, item);
event = 'updated';
} else {
array.push(item);
}
cb(event, item, array);
});
/**
* Syncs removed items on 'model:remove'
*/
socket.on(modelName + ':remove', function (item) {
var event = 'deleted';
_.remove(array, {_id: item._id});
cb(event, item, array);
});
},
/**
* Removes listeners for a models updates on the socket
*
* @param modelName
*/
unsyncUpdates: function (modelName) {
socket.removeAllListeners(modelName + ':save');
socket.removeAllListeners(modelName + ':remove');
}
};
});
|
const snekfetch = require('snekfetch');
const { RichEmbed } = require('discord.js');
module.exports = {
commands: [
'neko',
'nekos'
],
usage: 'neko',
description: 'OwO',
category: 'Fun',
execute: (bot, msg) => {
msg.edit('', {
embed: new RichEmbed()
.setColor(0x5B8DEA)
.setTitle('Random Nekos')
.setImage(bot.getNeko('neko'))
.setFooter(`${bot.config.strings.github} | Image by nekos.life`)
});
}
};
|
// ==UserScript==
// @name Liquipedia Spoiler Hider
// @namespace www.lux01.co.uk
// @description Hides tournament spoilers on the Liquipedia
// @include http://wiki.teamliquid.net/*
// @exclude http://wiki.teamliquid.net/hearthstone/*
// @version 1.0.1a
// @grant none
// @copyright 2015, William Woodhead (www.lux01.co.uk)
// @license MIT License
// @homepageURL https://github.com/lux01/liquipedia_spoilers
// ==/UserScript==
var matchWonFile = 'GreenCheck.png';
function hide_spoilers() {
// Disable the bold winner names
$('.bracket-team-top, .bracket-team-middle, .bracket-team-bottom, .bracket-player-top, .bracket-player-bottom').parent().each(function() {
$(this).css('font-weight','normal').off();
});
// Disable the mouse over highlight events
$('.bracket-team-top, .bracket-team-middle, .bracket-team-bottom, .bracket-player-top, .bracket-player-bottom').off();
// Hide the match results in the popup
$('.bracket-game-details .matches').hide();
// Not all the wikis use .matches so we have got to improvise
$('.bracket-game-details').children('div:not(:first-child):not(:last-child)').hide();
// Hide spoiler team names, icons and scores on the playoff tables
$('.bracket-team-top, .bracket-team-middle, .bracket-team-bottom').each(function() {
$('.team-template-image', this).hide();
$('.team-template-text', this).hide();
$('.bracket-score', this).hide();
});
// SC2 doesn't use teams, it uses players
$('.bracket-player-top, .bracket-team-middle, .bracket-player-bottom').each(function() {
$(this).data('old-color', $(this).css('background-color'));
$(this).css('background-color','rgb(242,232,184)');
$('span, img, .bracket-score', this).hide();
});
// Calculate how many "watch" icons are shown and generate dummy ones
$('.bracket-game-details').each(function() {
// Since we can't rely on there being the right number of vods not to spoil things
// or the vod might not be split into game parts, we will just individually reveal vod
// links on demand.
// First we work out how many games there might be
var lefties = $(this).find('.matches .left .check').filter(function(index) {
return $('img', this).attr('src').endsWith(matchWonFile);
}).length;
var righties = $(this).find('.matches .right .check').filter(function(index) {
return $('img', this).attr('src').endsWith(matchWonFile);
}).length;
var bestOf = 2 * Math.max(lefties, righties) - 1;
var showNext = $(document.createElement('button')).text('Show next VOD').data('shown', 1);
$(this).find('.icons .plainlinks:gt(0), .bracket-icons .plainlinks:gt(0)').hide();
$(this).find('.bracket-icons > :not(a, .plainlinks), .bracket-icons > a[href^="http://www.hltv.org/"], .bracket-icons > a[href^="https://www.hltv.org/""]').hide();
var showSpoilersButton = $(document.createElement('button')).text('Show spoilers');
showNext.click(function(evt) {
var shown = $(evt.target).data('shown');
var parent = $(evt.target).closest('.bracket-game-details');
$('span.plainlinks:lt(' + ($(evt.target).data('shown') + 1) + ')', parent).show();
$(evt.target).data('shown', shown + 1);
var numLinks = $('span.plainlinks', parent).length;
if(shown + 1 > numLinks || (bestOf > 0 && shown + 1 == bestOf))
$(evt.target).remove();
});
showSpoilersButton.click(function(evt) {
var bgds = $(evt.target).closest('.bracket-game-details');
$('.matches', bgds).show();
$('.plainlinks', bgds).show();
$('.icons .plainlinks:gt(0), .bracket-icons .plainlinks:gt(0)', bgds).show();
$('.bracket-icons > :not(.plainlinks)', bgds).show();
var game = $(evt.target).parent().parent().parent();
$('.team-template-image, .team-template-text, .bracket-score', game).show();
$('.bracket-player-top, .bracket-player-bottom', game).show()
$('img, span, .bracket-score', game).show();
$('.bracket-player-top, .bracket-player-bottom', game).each(function () {
$(this).css('background-color', $(this).data('old-color'));
});
$('.bracket-game-details', game).children('div').show();
$(showNext).remove();
$(showSpoilersButton).remove();
});
var showSpoilersDiv = $(document.createElement('div'));
showSpoilersDiv.append(showNext);
showSpoilersDiv.append(showSpoilersButton);
showSpoilersDiv.insertAfter($('div:last', this));
});
// Remove the click behaviour from the info button and make the entire
// panel do its job instead
$('.bracket-game .icon').off();
$('.bracket-game').each(function() {
var parent = this;
$(this).click(function (evt) {
// Hide all the rest
$('.bracket-game-details').hide();
// Find ours
var ourDetails = $('.bracket-game-details', parent);
if(ourDetails.data('visible')) {
ourDetails.hide();
ourDetails.data('visible', false);
} else {
ourDetails.show();
ourDetails.data('visible', true);
}
});
});
// Tournament info box spoilers
$('.infobox-center span[title="First Place"]').parent().hide();
$('.infobox-center span[title="Second Place"]').parent().hide();
$('.infobox-center span[title="Third Place"]').parent().hide();
$('.infobox-center span[title="Fourth Place"]').parent().hide();
$('.infobox-center span[title="Semifinalist(s)"]').parent().hide();
// Create the show spoilers button for the infobox
var showSpoilersInfoBoxContainer = $(document.createElement('div')).css('text-align', 'center');
var showSpoilersInfoBoxDiv = $(document.createElement('div')).attr('class', 'infobox-center');
var showSpoilersInfoBoxButton = $(document.createElement('button')).text('Show spoilers');
showSpoilersInfoBoxButton.click(function () {
$('.infobox-center span[title="First Place"]').parent().show();
$('.infobox-center span[title="Second Place"]').parent().show();
$('.infobox-center span[title="Third Place"]').parent().show();
$('.infobox-center span[title="Fourth Place"]').parent().show();
$('.infobox-center span[title="Semifinalist(s)"]').parent().show();
showSpoilersInfoBoxContainer.remove();
});
showSpoilersInfoBoxDiv.append(showSpoilersInfoBoxButton);
showSpoilersInfoBoxContainer.append(showSpoilersInfoBoxDiv);
$('.infobox-center span[title="First Place"]').parent().parent().append(showSpoilersInfoBoxContainer);
// Hide the prizepool table
$('table.prizepooltable').hide();
var showSpoilersPrizePool = $(document.createElement('button')).text('Show prize pool');
showSpoilersPrizePool.click(function() {
$('table.prizepooltable').show();
showSpoilersPrizePool.remove();
});
showSpoilersPrizePool.insertAfter($('table.prizepooltable'));
}
window.addEventListener('load', function() {
console.log("Liquipedia spoiler hider: loading...");
hide_spoilers();
console.log("Liquipedia spoiler hider: loaded!");
}, false);
|
'use strict';
/**
* practice Node.js project
*
* @author William Wang <wangmuming_0218@126.com>
*/
import {expect} from 'chai';
import {session} from '../test';
describe('topic', function(){
// it('list', async function(){
//
// const list = await request.get('/api/topic/list');
// console.log(list);
//
// });
it('create topic', async function(){
const request = session();
{
const ret = await request.post('/api/login',{
name: 'test0',
password: '12345678',
});
console.log(ret);
expect(ret.token).to.be.a('string');
}
{
const ret = await request.post('/api/topic/add', {
title: '哈哈哈哈',
content: '哈哈哈哈',
tags: 'test'
});
console.log(ret);
expect(ret.topic.title).to.equal('哈哈哈哈');
expect(ret.topic.content).to.equal('哈哈哈哈');
expect(ret.topic.tags).to.have.members(['test']);
}
});
});
|
var $ = global.jQuery;
module.exports = MainVerticalShift;
function MainVerticalShift(opts) {
if (!(this instanceof MainVerticalShift)) {
return new MainVerticalShift(opts);
}
// console.log('MainVerticalShift initialized.');
var hexagonHeight = $('.hexagon').eq(0).height();
var hexagonOuterHeight = $('.hexagons').eq(1).outerHeight();
var headerHeight = $('.nav').outerHeight();
var topOffsetHeight;
var sectionOffsetHeight;
setFirstHexMargin();
setSectionMargin();
$(window).resize(function() {
hexagonHeight = $('.hexagon').eq(0).height();
hexagonOuterHeight = $('.hexagons').eq(1).outerHeight();
setFirstHexMargin();
setSectionMargin();
});
function setFirstHexMargin() {
topOffsetHeight = (-hexagonHeight / 2) + headerHeight;
$('.hexagons').eq(0).css('margin-top', topOffsetHeight);
}
function setSectionMargin() {
sectionOffsetHeight = hexagonOuterHeight - (hexagonHeight / 2) + headerHeight;
$('.section__container').css({
marginTop: -sectionOffsetHeight,
paddingTop: sectionOffsetHeight
});
}
}
|
import React from 'react';
import { StyleSheet, Text, View, TextInput, Button, StatusBar } from 'react-native';
import { SearchBar } from 'react-native-elements'
export let SEARCH_QUERY = ''
const Home = ({ navigation: { navigate }}) => {
console.log('Home rendered!!')
return (
<View style={{flex: 1}}>
<StatusBar hidden />
<View style={[{flex: 3, backgroundColor: 'lightblue'}, styles.container]}>
<Text>Aurity Code Challenge</Text>
<Text>Github Search App.</Text>
</View>
<View style={{flex: 4, backgroundColor: 'grey'}} >
<View style={{flex:1}}>
<SearchBar
lightTheme
onChangeText={(text) => SEARCH_QUERY = text}
placeholder='Search Github'
/>
<Button
onPress={() => navigate('ReposList')}
title="Search"
/>
</View>
</View>
<View style={{flex:1, flexDirection: 'row'}}>
<View style={{flex: 1, backgroundColor: 'cyan'}} />
<View style={{flex: 1, backgroundColor: 'skyblue'}} />
</View>
</View>
)
}
const styles = StyleSheet.create({
container: {
alignItems: 'center',
justifyContent: 'center',
},
});
export default Home |
import ascii from "ascii-art";
ascii.Figlet.fontPath = `${__dirname}/../../figlet-fonts/`;
export default function subtitle(message = "Sub-Title", figletFont = "standard") {
this.debug("subtitle", message, figletFont);
this.then((stimpak, done) => {
ascii.font(message, figletFont, renderedMessage => {
this.write(`\n${renderedMessage}`);
done();
});
});
return this;
}
|
import Vue from 'vue';
Vue.directive('field', {
bind(el, { expression: field }, { context: block }) {
if(typeof field === 'string') {
block.fieldElements[field] = el;
}
else if(Array.isArray(field)) {
field.forEach((f) => block.fieldElements[f] = el)
}
}
});
|
const func = require('../src/longest-consecutive-sequence');
const assert = require('assert');
describe('longest-consecutive-sequence', function () {
describe('#longestConsecutive()', function () {
it("should return 4 when numbers are [100, 4, 200, 1, 3, 2]", function () {
let ret = func([100, 4, 200, 1, 3, 2]);
assert.equal(ret, 4);
});
});
}); |
const CHAMPION_LOAD = 'CHAMPION_LOAD';
const CHAMPION_LOAD_SUCCESS = 'CHAMPION_LOAD_SUCCESS';
const CHAMPION_LOAD_FAIL = 'CHAMPION_LOAD_FAIL';
const initialState = {
loaded: false
};
export default function reducer(state = initialState, action = {}) {
switch (action.type) {
case CHAMPION_LOAD:
return {
...state,
loading: true
};
case CHAMPION_LOAD_SUCCESS:
return {
...state,
loading: false,
loaded: true,
data: action.result,
error: null
};
case CHAMPION_LOAD_FAIL:
return {
...state,
loading: false,
loaded: false,
data: null,
error: action.error
};
default:
return state;
}
}
export function isLoaded(globalState) {
return globalState.champions && globalState.champions.loaded;
}
export function load() {
return {
types: [CHAMPION_LOAD, CHAMPION_LOAD_SUCCESS, CHAMPION_LOAD_FAIL],
promise: (client) => client.get('/champions?limit=10')
};
}
|
/*globals angular */
'use strict';
/**
* Routes each URL Request to a specific html page,
* each html page is connected to a specific controller which handles the logic
*
* protected: If page may only be shown if user is logged In
* hideIfLoggedIn: for Login/Signup pages -> May not be shown if user is logged In already
*/
angular.module('afsApp').config(['$routeProvider',
function ($routeProvider) {
$routeProvider
.when('/home', {
templateUrl: 'views/home.html',
controller: 'HomeCtrl',
protected: true
})
.when('/signup', {
templateUrl: 'views/signup.html',
controller: 'UserCtrl',
hideIfLoggedIn: true
})
.when('/login', {
templateUrl: 'views/login.html',
controller: 'UserCtrl',
hideIfLoggedIn: true
})
.when('/newSurvey', {
templateUrl: 'views/newSurvey.html',
controller: 'FormCtrl',
protected: true
})
.when('/preview', {
templateUrl: 'views/preview.html',
controller: 'FormCtrl',
protected: true
})
.when('/contact', {
templateUrl: 'views/contact.html',
controller: 'UserCtrl'
})
.when('/publish/:token', {
templateUrl: 'views/publish.html',
controller: 'PublishCtrl',
protected: true
})
.when('/profile', {
templateUrl: 'views/profile.html',
controller: 'UserCtrl',
protected: true
})
.when('/participate/:token',{
templateUrl: 'views/participate.html',
controller: 'AnswerCtrl'
})
.when('/noSurvey',{
templateUrl: 'views/surveys/noSurvey.html',
controller: 'AnswerCtrl'
})
.when('/thanks',{
templateUrl: 'views/surveys/thanks.html',
controller: 'AnswerCtrl'
})
.when('/results/:token/:title',{
templateUrl: 'views/surveys/results.html',
controller: 'AnswerCtrl',
protected: true
})
.when('/error',{
templateUrl: 'views/error.html',
controller: 'NavCtrl'
})
.otherwise({
redirectTo: '/login'
});
}]);
|
// wrapper for THREE.SVGRenderer trying to optimize creation of many small SVG elements
THREE.CreateSVGRenderer = function(as_is, precision, doc) {
function Create(document) {
// now include original THREE.SVGRenderer
//
|
const uniqueValidator = require('mongoose-unique-validator')
module.exports = schema => uniqueValidator(schema, {})
|
'use strict';
var mongoose = require('mongoose');
var productModel = function () {
//Define a super simple schema for our products.
var productSchema = mongoose.Schema({
name: String,
price: Number
});
//Verbose toString method
productSchema.methods.whatAmI = function () {
var greeting = this.name ?
'Hello, I\'m a ' + this.name + ' and I\'m worth $' + this.price
: 'I don\'t have a name :(';
console.log(greeting);
};
//Format the price of the product to show a dollar sign, and two decimal places
productSchema.methods.prettyPrice = function () {
return '$' + this.price.toFixed(2);
};
return mongoose.model('Product', productSchema);
};
module.exports = new productModel(); |
/*
* systems-api-version-test.js: Tests for the 'system' resource's RESTful API.
*
* (C) 2010, Nodejitsu Inc.
*
*/
var assert = require('assert'),
apiEasy = require('api-easy'),
helpers = require('../../helpers'),
fixtures = require('../../fixtures/systems'),
systems = fixtures.systems,
missing = fixtures.missing;
var testSystem = systems[0],
fixtureOne = missing[0],
port = 9002;
testSystem.version = '0.1.2';
var suite = apiEasy.describe('composer/resources/systems/api/versions').addBatch(
helpers.macros.requireComposer(port)
);
helpers.testApi(suite, port)
.discuss('With a new version')
.put('/systems/test-system', testSystem)
.expect(200)
.next()
.undiscuss()
.get('/systems/test-system')
.expect(200)
.expect('should respond with both versions', function (err, res, body) {
assert.isNull(err);
var result = JSON.parse(body);
assert.isObject(result.system);
assert.isObject(result.system.versions);
assert.equal(result.system.name, 'test-system');
assert.include(result.system.versions, '0.0.0');
assert.include(result.system.versions, '0.1.2');
})
.discuss('With an existing version')
.put('/systems/test-system', testSystem)
.expect(400)
.undiscuss()
.next()
.del('/systems/test-system/v0.0.0')
.expect(200)
.next()
.undiscuss()
.get('/systems/test-system')
.expect(200)
.expect('Should not have the deleted version', function (err, res, body) {
assert.isNull(err);
var system = JSON.parse(body).system;
assert.isObject(system);
assert.isObject(system.versions);
assert.equal(system.name, 'test-system');
assert.include(system.versions, '0.1.2');
assert.lengthOf(Object.keys(system.versions), 1);
})
.export(module); |
/**
* Created by kdban on 4/8/2016.
*/
var $ = require('jquery');
var Logger = require('polyball/shared/Logger');
var appendNameToList = function (listElement, localID) {
return function (spectatorOrPlayer) {
if (spectatorOrPlayer == null) {
return;
}
var listItem = $('<li>').text(spectatorOrPlayer.client.name);
if (spectatorOrPlayer.id === localID) {
var localElement = $('<span>').addClass('localClient').text(' (you)');
listItem.append(localElement);
}
listElement.append(listItem);
};
};
/**
*
* @param {Object} config
* @property {string} config.appendTo - css selector for the element to append the renderer to
* @constructor
*/
module.exports.SpectatorListRenderer = function (config) {
$.get('hudcomponents/spectatorList.html', function (data) {
Logger.debug('Injecting spectator list.');
$(config.appendTo).append(data);
});
this.render = function (spectators, localID) {
var spectatorList = $('.spectatorList');
spectatorList.empty();
spectators.forEach(appendNameToList(spectatorList, localID));
};
};
module.exports.PlayerQueueListRenderer = function (config) {
$.get('hudcomponents/playerQueue.html', function (data) {
Logger.debug('Injecting player queue.');
$(config.appendTo).append(data);
});
this.render = function (playerQueue, localID) {
var playerQueueList = $('.playerQueue');
playerQueueList.empty();
if (playerQueue.length === 0) {
playerQueueList.append(
$('<li>').addClass('grayed').text('No players queued.')
);
}
playerQueue.forEach(appendNameToList(playerQueueList, localID));
};
}; |
// Karma configuration
// Generated on Sat May 02 2015 15:36:20 GMT+0530 (India Standard Time)
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jspm', 'mocha', 'chai'],
jspm: {
// Edit this to your needs
loadFiles: ['lib/**/*.js', 'test/**/*.js']
},
// list of files / patterns to load in the browser
files: [
],
// list of files to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'lib/**/*.js': ['babel', 'coverage']
},
// transpile with babel since the coverage reporter throws error on ES6 syntax
babelPreprocessor: {
options: {
modules: 'system'
}
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['mocha', 'coverage'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher , 'ChromeCanary', 'Firefox', 'Safari', 'PhantomJS', 'Opera', 'IE'
browsers: ['Chrome'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false
});
};
|
var normalize = require("./lib/normalize.js")
var error = require("./lib/error.js")
module.exports = enumDropdown
function enumDropdown(opts) {
opts = normalize("enumDropdown", opts)
if (!opts.options) {
throw new Error("enumDropdown(opts): opts.options is required " +
JSON.stringify(opts))
}
return [".enum-dropdown.form-elem" + (opts.selector || ""), [
opts.label ? ["label.label", { "for": opts.id }, [ opts.label ]] : null,
["select.input", {
name: opts.name,
id: opts.id,
"data-marker": "form." + opts.marker
}, [
["option", { selected: true, value: "" }, opts.placeholder],
{ fragment: opts.options.map(function (option) {
if (typeof option === "string") {
option = { text: option, value: option }
}
return ["option", {
value: option.value,
selected: !!(opts.value && option.value === opts.value)
}, option.text]
}) }
]],
error(opts.marker)
]]
}
|
(function() {
"use strict";
function $$route$recognizer$dsl$$Target(path, matcher, delegate) {
this.path = path;
this.matcher = matcher;
this.delegate = delegate;
}
$$route$recognizer$dsl$$Target.prototype = {
to: function(target, callback) {
var delegate = this.delegate;
if (delegate && delegate.willAddRoute) {
target = delegate.willAddRoute(this.matcher.target, target);
}
this.matcher.add(this.path, target);
if (callback) {
if (callback.length === 0) { throw new Error("You must have an argument in the function passed to `to`"); }
this.matcher.addChild(this.path, target, callback, this.delegate);
}
return this;
}
};
function $$route$recognizer$dsl$$Matcher(target) {
this.routes = {};
this.children = {};
this.target = target;
}
$$route$recognizer$dsl$$Matcher.prototype = {
add: function(path, handler) {
this.routes[path] = handler;
},
addChild: function(path, target, callback, delegate) {
var matcher = new $$route$recognizer$dsl$$Matcher(target);
this.children[path] = matcher;
var match = $$route$recognizer$dsl$$generateMatch(path, matcher, delegate);
if (delegate && delegate.contextEntered) {
delegate.contextEntered(target, match);
}
callback(match);
}
};
function $$route$recognizer$dsl$$generateMatch(startingPath, matcher, delegate) {
return function(path, nestedCallback) {
var fullPath = startingPath + path;
if (nestedCallback) {
nestedCallback($$route$recognizer$dsl$$generateMatch(fullPath, matcher, delegate));
} else {
return new $$route$recognizer$dsl$$Target(startingPath + path, matcher, delegate);
}
};
}
function $$route$recognizer$dsl$$addRoute(routeArray, path, handler) {
var len = 0;
for (var i=0, l=routeArray.length; i<l; i++) {
len += routeArray[i].path.length;
}
path = path.substr(len);
var route = { path: path, handler: handler };
routeArray.push(route);
}
function $$route$recognizer$dsl$$eachRoute(baseRoute, matcher, callback, binding) {
var routes = matcher.routes;
for (var path in routes) {
if (routes.hasOwnProperty(path)) {
var routeArray = baseRoute.slice();
$$route$recognizer$dsl$$addRoute(routeArray, path, routes[path]);
if (matcher.children[path]) {
$$route$recognizer$dsl$$eachRoute(routeArray, matcher.children[path], callback, binding);
} else {
callback.call(binding, routeArray);
}
}
}
}
var $$route$recognizer$dsl$$default = function(callback, addRouteCallback) {
var matcher = new $$route$recognizer$dsl$$Matcher();
callback($$route$recognizer$dsl$$generateMatch("", matcher, this.delegate));
$$route$recognizer$dsl$$eachRoute([], matcher, function(route) {
if (addRouteCallback) { addRouteCallback(this, route); }
else { this.add(route); }
}, this);
};
var $$route$recognizer$$specials = [
'/', '.', '*', '+', '?', '|',
'(', ')', '[', ']', '{', '}', '\\'
];
var $$route$recognizer$$escapeRegex = new RegExp('(\\' + $$route$recognizer$$specials.join('|\\') + ')', 'g');
function $$route$recognizer$$isArray(test) {
return Object.prototype.toString.call(test) === "[object Array]";
}
// A Segment represents a segment in the original route description.
// Each Segment type provides an `eachChar` and `regex` method.
//
// The `eachChar` method invokes the callback with one or more character
// specifications. A character specification consumes one or more input
// characters.
//
// The `regex` method returns a regex fragment for the segment. If the
// segment is a dynamic of star segment, the regex fragment also includes
// a capture.
//
// A character specification contains:
//
// * `validChars`: a String with a list of all valid characters, or
// * `invalidChars`: a String with a list of all invalid characters
// * `repeat`: true if the character specification can repeat
function $$route$recognizer$$StaticSegment(string) { this.string = string; }
$$route$recognizer$$StaticSegment.prototype = {
eachChar: function(callback) {
var string = this.string, ch;
for (var i=0, l=string.length; i<l; i++) {
ch = string.charAt(i);
callback({ validChars: ch });
}
},
regex: function() {
return this.string.replace($$route$recognizer$$escapeRegex, '\\$1');
},
generate: function() {
return this.string;
}
};
function $$route$recognizer$$DynamicSegment(name) { this.name = name; }
$$route$recognizer$$DynamicSegment.prototype = {
eachChar: function(callback) {
callback({ invalidChars: "/", repeat: true });
},
regex: function() {
return "([^/]+)";
},
generate: function(params) {
return params[this.name];
}
};
function $$route$recognizer$$StarSegment(name) { this.name = name; }
$$route$recognizer$$StarSegment.prototype = {
eachChar: function(callback) {
callback({ invalidChars: "", repeat: true });
},
regex: function() {
return "(.+)";
},
generate: function(params) {
return params[this.name];
}
};
function $$route$recognizer$$EpsilonSegment() {}
$$route$recognizer$$EpsilonSegment.prototype = {
eachChar: function() {},
regex: function() { return ""; },
generate: function() { return ""; }
};
function $$route$recognizer$$parse(route, names, types) {
// normalize route as not starting with a "/". Recognition will
// also normalize.
if (route.charAt(0) === "/") { route = route.substr(1); }
var segments = route.split("/"), results = [];
for (var i=0, l=segments.length; i<l; i++) {
var segment = segments[i], match;
if (match = segment.match(/^:([^\/]+)$/)) {
results.push(new $$route$recognizer$$DynamicSegment(match[1]));
names.push(match[1]);
types.dynamics++;
} else if (match = segment.match(/^\*([^\/]+)$/)) {
results.push(new $$route$recognizer$$StarSegment(match[1]));
names.push(match[1]);
types.stars++;
} else if(segment === "") {
results.push(new $$route$recognizer$$EpsilonSegment());
} else {
results.push(new $$route$recognizer$$StaticSegment(segment));
types.statics++;
}
}
return results;
}
// A State has a character specification and (`charSpec`) and a list of possible
// subsequent states (`nextStates`).
//
// If a State is an accepting state, it will also have several additional
// properties:
//
// * `regex`: A regular expression that is used to extract parameters from paths
// that reached this accepting state.
// * `handlers`: Information on how to convert the list of captures into calls
// to registered handlers with the specified parameters
// * `types`: How many static, dynamic or star segments in this route. Used to
// decide which route to use if multiple registered routes match a path.
//
// Currently, State is implemented naively by looping over `nextStates` and
// comparing a character specification against a character. A more efficient
// implementation would use a hash of keys pointing at one or more next states.
function $$route$recognizer$$State(charSpec) {
this.charSpec = charSpec;
this.nextStates = [];
}
$$route$recognizer$$State.prototype = {
get: function(charSpec) {
var nextStates = this.nextStates;
for (var i=0, l=nextStates.length; i<l; i++) {
var child = nextStates[i];
var isEqual = child.charSpec.validChars === charSpec.validChars;
isEqual = isEqual && child.charSpec.invalidChars === charSpec.invalidChars;
if (isEqual) { return child; }
}
},
put: function(charSpec) {
var state;
// If the character specification already exists in a child of the current
// state, just return that state.
if (state = this.get(charSpec)) { return state; }
// Make a new state for the character spec
state = new $$route$recognizer$$State(charSpec);
// Insert the new state as a child of the current state
this.nextStates.push(state);
// If this character specification repeats, insert the new state as a child
// of itself. Note that this will not trigger an infinite loop because each
// transition during recognition consumes a character.
if (charSpec.repeat) {
state.nextStates.push(state);
}
// Return the new state
return state;
},
// Find a list of child states matching the next character
match: function(ch) {
// DEBUG "Processing `" + ch + "`:"
var nextStates = this.nextStates,
child, charSpec, chars;
// DEBUG " " + debugState(this)
var returned = [];
for (var i=0, l=nextStates.length; i<l; i++) {
child = nextStates[i];
charSpec = child.charSpec;
if (typeof (chars = charSpec.validChars) !== 'undefined') {
if (chars.indexOf(ch) !== -1) { returned.push(child); }
} else if (typeof (chars = charSpec.invalidChars) !== 'undefined') {
if (chars.indexOf(ch) === -1) { returned.push(child); }
}
}
return returned;
}
/** IF DEBUG
, debug: function() {
var charSpec = this.charSpec,
debug = "[",
chars = charSpec.validChars || charSpec.invalidChars;
if (charSpec.invalidChars) { debug += "^"; }
debug += chars;
debug += "]";
if (charSpec.repeat) { debug += "+"; }
return debug;
}
END IF **/
};
/** IF DEBUG
function debug(log) {
console.log(log);
}
function debugState(state) {
return state.nextStates.map(function(n) {
if (n.nextStates.length === 0) { return "( " + n.debug() + " [accepting] )"; }
return "( " + n.debug() + " <then> " + n.nextStates.map(function(s) { return s.debug() }).join(" or ") + " )";
}).join(", ")
}
END IF **/
// This is a somewhat naive strategy, but should work in a lot of cases
// A better strategy would properly resolve /posts/:id/new and /posts/edit/:id.
//
// This strategy generally prefers more static and less dynamic matching.
// Specifically, it
//
// * prefers fewer stars to more, then
// * prefers using stars for less of the match to more, then
// * prefers fewer dynamic segments to more, then
// * prefers more static segments to more
function $$route$recognizer$$sortSolutions(states) {
return states.sort(function(a, b) {
if (a.types.stars !== b.types.stars) { return a.types.stars - b.types.stars; }
if (a.types.stars) {
if (a.types.statics !== b.types.statics) { return b.types.statics - a.types.statics; }
if (a.types.dynamics !== b.types.dynamics) { return b.types.dynamics - a.types.dynamics; }
}
if (a.types.dynamics !== b.types.dynamics) { return a.types.dynamics - b.types.dynamics; }
if (a.types.statics !== b.types.statics) { return b.types.statics - a.types.statics; }
return 0;
});
}
function $$route$recognizer$$recognizeChar(states, ch) {
var nextStates = [];
for (var i=0, l=states.length; i<l; i++) {
var state = states[i];
nextStates = nextStates.concat(state.match(ch));
}
return nextStates;
}
var $$route$recognizer$$oCreate = Object.create || function(proto) {
function F() {}
F.prototype = proto;
return new F();
};
function $$route$recognizer$$RecognizeResults(queryParams) {
this.queryParams = queryParams || {};
}
$$route$recognizer$$RecognizeResults.prototype = $$route$recognizer$$oCreate({
splice: Array.prototype.splice,
slice: Array.prototype.slice,
push: Array.prototype.push,
length: 0,
queryParams: null
});
function $$route$recognizer$$findHandler(state, path, queryParams) {
var handlers = state.handlers, regex = state.regex;
var captures = path.match(regex), currentCapture = 1;
var result = new $$route$recognizer$$RecognizeResults(queryParams);
for (var i=0, l=handlers.length; i<l; i++) {
var handler = handlers[i], names = handler.names, params = {};
for (var j=0, m=names.length; j<m; j++) {
params[names[j]] = captures[currentCapture++];
}
result.push({ handler: handler.handler, params: params, isDynamic: !!names.length });
}
return result;
}
function $$route$recognizer$$addSegment(currentState, segment) {
segment.eachChar(function(ch) {
var state;
currentState = currentState.put(ch);
});
return currentState;
}
function $$route$recognizer$$decodeQueryParamPart(part) {
// http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.1
part = part.replace(/\+/gm, '%20');
return decodeURIComponent(part);
}
// The main interface
var $$route$recognizer$$RouteRecognizer = function() {
this.rootState = new $$route$recognizer$$State();
this.names = {};
};
$$route$recognizer$$RouteRecognizer.prototype = {
add: function(routes, options) {
var currentState = this.rootState, regex = "^",
types = { statics: 0, dynamics: 0, stars: 0 },
handlers = [], allSegments = [], name;
var isEmpty = true;
for (var i=0, l=routes.length; i<l; i++) {
var route = routes[i], names = [];
var segments = $$route$recognizer$$parse(route.path, names, types);
allSegments = allSegments.concat(segments);
for (var j=0, m=segments.length; j<m; j++) {
var segment = segments[j];
if (segment instanceof $$route$recognizer$$EpsilonSegment) { continue; }
isEmpty = false;
// Add a "/" for the new segment
currentState = currentState.put({ validChars: "/" });
regex += "/";
// Add a representation of the segment to the NFA and regex
currentState = $$route$recognizer$$addSegment(currentState, segment);
regex += segment.regex();
}
var handler = { handler: route.handler, names: names };
handlers.push(handler);
}
if (isEmpty) {
currentState = currentState.put({ validChars: "/" });
regex += "/";
}
currentState.handlers = handlers;
currentState.regex = new RegExp(regex + "$");
currentState.types = types;
if (name = options && options.as) {
this.names[name] = {
segments: allSegments,
handlers: handlers
};
}
},
handlersFor: function(name) {
var route = this.names[name], result = [];
if (!route) { throw new Error("There is no route named " + name); }
for (var i=0, l=route.handlers.length; i<l; i++) {
result.push(route.handlers[i]);
}
return result;
},
hasRoute: function(name) {
return !!this.names[name];
},
generate: function(name, params) {
var route = this.names[name], output = "";
if (!route) { throw new Error("There is no route named " + name); }
var segments = route.segments;
for (var i=0, l=segments.length; i<l; i++) {
var segment = segments[i];
if (segment instanceof $$route$recognizer$$EpsilonSegment) { continue; }
output += "/";
output += segment.generate(params);
}
if (output.charAt(0) !== '/') { output = '/' + output; }
if (params && params.queryParams) {
output += this.generateQueryString(params.queryParams, route.handlers);
}
return output;
},
generateQueryString: function(params, handlers) {
var pairs = [];
var keys = [];
for(var key in params) {
if (params.hasOwnProperty(key)) {
keys.push(key);
}
}
keys.sort();
for (var i = 0, len = keys.length; i < len; i++) {
key = keys[i];
var value = params[key];
if (value == null) {
continue;
}
var pair = encodeURIComponent(key);
if ($$route$recognizer$$isArray(value)) {
for (var j = 0, l = value.length; j < l; j++) {
var arrayPair = key + '[]' + '=' + encodeURIComponent(value[j]);
pairs.push(arrayPair);
}
} else {
pair += "=" + encodeURIComponent(value);
pairs.push(pair);
}
}
if (pairs.length === 0) { return ''; }
return "?" + pairs.join("&");
},
parseQueryString: function(queryString) {
var pairs = queryString.split("&"), queryParams = {};
for(var i=0; i < pairs.length; i++) {
var pair = pairs[i].split('='),
key = $$route$recognizer$$decodeQueryParamPart(pair[0]),
keyLength = key.length,
isArray = false,
value;
if (pair.length === 1) {
value = 'true';
} else {
//Handle arrays
if (keyLength > 2 && key.slice(keyLength -2) === '[]') {
isArray = true;
key = key.slice(0, keyLength - 2);
if(!queryParams[key]) {
queryParams[key] = [];
}
}
value = pair[1] ? $$route$recognizer$$decodeQueryParamPart(pair[1]) : '';
}
if (isArray) {
queryParams[key].push(value);
} else {
queryParams[key] = value;
}
}
return queryParams;
},
recognize: function(path) {
var states = [ this.rootState ],
pathLen, i, l, queryStart, queryParams = {},
isSlashDropped = false;
queryStart = path.indexOf('?');
if (queryStart !== -1) {
var queryString = path.substr(queryStart + 1, path.length);
path = path.substr(0, queryStart);
queryParams = this.parseQueryString(queryString);
}
path = decodeURI(path);
// DEBUG GROUP path
if (path.charAt(0) !== "/") { path = "/" + path; }
pathLen = path.length;
if (pathLen > 1 && path.charAt(pathLen - 1) === "/") {
path = path.substr(0, pathLen - 1);
isSlashDropped = true;
}
for (i=0, l=path.length; i<l; i++) {
states = $$route$recognizer$$recognizeChar(states, path.charAt(i));
if (!states.length) { break; }
}
// END DEBUG GROUP
var solutions = [];
for (i=0, l=states.length; i<l; i++) {
if (states[i].handlers) { solutions.push(states[i]); }
}
states = $$route$recognizer$$sortSolutions(solutions);
var state = solutions[0];
if (state && state.handlers) {
// if a trailing slash was dropped and a star segment is the last segment
// specified, put the trailing slash back
if (isSlashDropped && state.regex.source.slice(-5) === "(.+)$") {
path = path + "/";
}
return $$route$recognizer$$findHandler(state, path, queryParams);
}
}
};
$$route$recognizer$$RouteRecognizer.prototype.map = $$route$recognizer$dsl$$default;
$$route$recognizer$$RouteRecognizer.VERSION = '0.1.5';
var $$route$recognizer$$default = $$route$recognizer$$RouteRecognizer;
/* global define:true module:true window: true */
if (typeof define === 'function' && define['amd']) {
define(function() { return $$route$recognizer$$default; });
} else if (typeof module !== 'undefined' && module['exports']) {
module['exports'] = $$route$recognizer$$default;
} else if (typeof this !== 'undefined') {
this['RouteRecognizer'] = $$route$recognizer$$default;
}
}).call(this);
|
import React from 'react'
import {mount} from 'enzyme'
import interactiveMarkdown from '../interactive-markdown'
function flushAllPromises() {
return new Promise(resolve => setTimeout(resolve, 200))
}
test('parses interactive pragmas into CodePreviews', async() => {
const markdown = `
# hello world
I am some content
~~~interactive {clickToRender: true, summary: 'I am the summary'}
render(<button onClick={() => alert('Hello World')}>Hello World</button>)
~~~
I am some more content
`
const elements = interactiveMarkdown(markdown)
const wrapper = mount(
<div>
{elements}
</div>,
)
expect(wrapper).toMatchSnapshot()
wrapper.find('details').simulate('click')
wrapper.find('details').first().node.open = true
await flushAllPromises()
expect(wrapper).toMatchSnapshot()
})
|
/*
* Super simple AJAX forms powered by Formspree -- http://jdp.org.uk/ajax/2015/05/20/ajax-forms-without-jquery.html
*/
var message = {};
message.loading = 'Laden ...';
message.success = 'Vielen Dank!';
message.failure = 'Fehler!';
var form = document.forms[0];
var submitForm = document.getElementById('submit-form');
var statusMessage = document.createElement('span');
// Set up the AJAX request
var request = new XMLHttpRequest();
request.open('POST', '//formspree.io/lets@dance.agency', true);
request.setRequestHeader('accept', 'application/json');
// Listen for the form being submitted
form.addEventListener('submit', function(evt) {
evt.preventDefault();
// Create a new FormData object passing in the form's key value pairs (that was easy!)
var formData = new FormData(form);
// Send the formData
request.send(formData);
// Watch for changes to request.readyState and update the statusMessage accordingly
request.onreadystatechange = function () {
// <4 = waiting on response from server
if (request.readyState < 4) {
statusMessage.className = 'btn btn--loading loading mono-ui';
statusMessage.innerHTML = message.loading;
submitForm.parentNode.replaceChild(statusMessage, submitForm);
// 4 = Response from server has been completely loaded.
} else if (request.readyState === 4) {
// 200 - 299 = successful
if (request.status === 200 && request.status < 300) {
statusMessage.className = 'btn btn--success mono-ui';
statusMessage.innerHTML = message.success;
submitForm.parentNode.replaceChild(statusMessage, submitForm);
} else {
statusMessage.className = 'btn btn--error mono-ui';
statusMessage.innerHTML = message.failure;
submitForm.parentNode.replaceChild(statusMessage, submitForm);
}
}
};
});
|
$( document ).ready(function() {
$("#menu-toggle").click(function(e) {
e.preventDefault();
$("#wrapper").toggleClass("toggled");
});
$(window).on('load, resize', function mobileViewUpdate() {
var viewportWidth = $(window).width();
if (viewportWidth < 768) {
$("#wrapper").removeClass("toggled");
}else{
$("#wrapper").addClass("toggled");
}
});
$('.accordeon').click(function () {
$(this).children('span').toggleClass('plus min');
$(this).parent().siblings().children('h2').children('span').removeClass('min').addClass('plus');
$(this).next('div').slideToggle();
$(this).parent().siblings().children().next().slideUp();
return false;
});
});
/*onclick="clickChapter('item1')"*/
|
#!/usr/bin/env node
var Promptosaurus = require('../lib/promptosaurus');
var rawr = new Promptosaurus();
rawr.add('Would you like to play a game of chess (y | n)?', function(answer){
// tell promptosaurus if you wish to accept the answer.
// A value of 'false' will have Promptosaurus ask the question again
// until an accepted response is given.
// *Important* - be sure if you set the flag to false, you allow it to
// then be set true with acceptable answer, or it will continue to loop
// the same question over and over.
this.hasValidResponse = (answer === 'y' || answer === 'n');
this.setError('Yeah... that answer is not a "y" or "n". Try again');
this.log('You have responded with: ' + answer);
})
.done(function(){
// this callback will execute once all questions have been successfully answered
this.log('You were asked: ' + this.queries[0].prompt);
this.log('You responded with: ' + this.queries[0].response);
})
.ask();
|
/**
* babel plugin for common configuration
*
* This will replace any object expression with a value specified in its parameter.
*/
import * as Kit from "./kit";
export default Kit.babelPlugin(function* (si) {
const s = Kit.auto(si);
for (const i of s) {
if (i.enter && i.type === Kit.Tag.ObjectExpression) {
yield* Kit.emitConst(i.pos, s.opts.pluginOpts);
Kit.skip(s.copy(i));
} else yield i;
}
});
|
const router = require('express').Router();
const jwt = require('jsonwebtoken');
const SECRET = process.env.JWT_KEY;
router.get('/', (req, res, next) => {
jwt.verify(req.cookies.token, SECRET, (err, payload) => {
(!req.cookies.token) ? res.redirect("./login") : res.render('./dailyplan/')
});
});
module.exports = router;
|
const fs = require('fs');
const resolve = require('path').resolve;
const userIds = require('../userIds');
/**
* @param {IMessage} msg Message object
* @return {boolean} whether the message sender has access
*/
function senderIsOwner (msg) {
const sender = msg.member || msg.author;
const isAeryk = sender.id === userIds.aeryk || sender.id === userIds.eve;
return isAeryk;
}
/**
* @access private
* @param {string} path
*/
function makeGuildFolder (path) {
fs.mkdirSync(path);
fs.mkdirSync(path + '/_vid');
fs.mkdirSync(path + '/img');
}
/**
* Makes a folder for storing music, pre-converted videos and cached avatars
*
* @param {Discordie} client
*/
function ensureFoldersExist (client) {
client.Guilds.forEach(g => {
const guildFolder = resolve(__dirname, `../plugins/dl/${g.id}`);
if (!fs.existsSync(guildFolder)) {
makeGuildFolder(guildFolder);
log('Created folders for: ' + g.name);
}
});
}
function log (s) {
process.stdout.write(s + '\n');
}
/**
* Requires a dependency if it exists, otherwise null
*
* @param {string} name
* @returns any
*/
function tryRequire (name) {
try {
require.resolve(name);
return require(name);
} catch(e) { /* NO OP */ }
return null;
}
function refreshConfig (config) {
fs.writeFileSync('../config.json', JSON.stringify(config, null, 4));
}
module.exports = {
// Message utility
senderIsOwner,
// General utility
ensureFoldersExist,
log,
refreshConfig,
tryRequire
};
|
const db = require('./db');
const bookshelf = require('bookshelf')(db);
const BCrypt = require('bcryptjs');
const SALT_FACTOR = 10;
let RoleModel = require('./Role');
//console.log('orm loaded and ready');
let User = bookshelf.Model.extend({
tableName: 'user_accounts',
initialize: function() {
this.on('creating', (model, attrs, options) => {
// console.log(model);
// console.log('..');
// console.log(attrs);
});
this.on('creating', this.hashPassword, this);
},
role: () => {
return this.belongsTo(RoleModel);
},
hashPassword: (model, attrs, options) => {
return new Promise((resolve, reject) => {
let pattern = /^\S+@\S+$/;
let isValidEmail = pattern.test(model.attributes['email']);
if (!isValidEmail) reject(new Error('invalid email specified'));
BCrypt.hash(model.attributes['password_hash'], SALT_FACTOR, (err, hash) => {
if (err) reject(err);
model.set('registration_date', new Date().toISOString().slice(0, 19).replace('T', ' '));
model.set('password_hash', hash);
resolve(hash);
})
})
},
comparePasswordSync: (attemptedPassword, passwordHash) => {
return BCrypt.compareSync(attemptedPassword, passwordHash);
},
comparePassword: (attemptedPassword, passwordHash, callback) => {
BCrypt.compare(attemptedPassword, passwordHash, (err, isMatch) => {
if (err) return callback(err);
else callback(err);
})
}
});
console.log('user model defined & exporting');
module.exports = User; |
version https://git-lfs.github.com/spec/v1
oid sha256:2e55b4cdfa39ace8085f1f7ca5e9807f119de33cc5fb7b1099ebc2f22d6a62e7
size 833
|
import React from 'react';
import 'highlight.js/styles/github-gist.css';
import {getTopicDetail} from '../lib/client';
import {renderMarkdown} from '../lib/utils';
export default class TopicDetail extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
componentDidMount() {
getTopicDetail(this.props.params.id)
.then(topic => {
topic.html = renderMarkdown(topic.content);
this.setState({topic});
})
.catch(err => console.error(err));
}
render() {
const topic = this.state.topic;
if (!topic) {
return (
<div>正在加载...</div>
);
}
return (
<div>
<h2>{topic.title}</h2>
<section dangerouslySetInnerHTML={{__html: topic.html}}></section>
<ul className="list-group">
{topic.comments.map((item, i) => {
return (
<li className="list-group-item" key={i}>
{item.authorId}于{item.createAt}说:<br/>{item.content}
</li>
)
})}
</ul>
</div>
)
}
}
|
// dataViews/index.js
import * as actions from './actions';
import * as components from './components';
import * as constants from './constants';
import reducer from './reducer';
import * as selectors from './selectors';
export default { actions, components, constants, reducer, selectors };
|
var el = document.getElementById('input');
// el.addEventListener('click', function() {
// el.value = 'clicked';
// });
var msgContainer = document.getElementById('msg-container');
function sendMessage() {
var msg = el.value;
el.value = '';
var msgEl = document.createElement('p');
msgEl.innerText = msg;
var timeEl = document.createElement('span');
timeEl.innerHTML = (new Date() + '').split(' ')[4];
msgEl.appendChild(timeEl);
msgContainer.appendChild(msgEl);
}
el.addEventListener('keydown', function (e) {
if (e.keyCode === 13) {
sendMessage();
}
});
document.getElementById('send-button')
.addEventListener('click', function(e) {
sendMessage();
console.log(e.clientX, e.clientY);
console.log(e.pageX, e.pageY);
}); |
'use strict';
/**
* Drags the `from` element to the location of the `to` element.
* @param from element whose position to start drag operation at
* @param to element whose position to stop drag operation at
*/
module.exports.drag = function (from, to) {
browser.actions().
mouseMove(from).
mouseDown().
mouseMove(to).
mouseUp().
perform();
};
|
'use strict';
// Fire me up!
module.exports = {
implements: 'starSelector/initError/throwError:sub'
};
module.exports.factory = function () {
throw new Error(require('path').relative(process.cwd(), __filename));
};
|
const InvalidError = require('./errors/InvalidError');
const NegativeError = require('./errors/NegativeError');
class Range{
constructor(start, end, step = 1){
this.start = start;
this.end = end;
this.step = step;
if(this.end < this.start){
throw new InverseOrderError(start, end);
}
if(this.step < 1){
throw new NegativeError(step);
}
}
contains(number){
return number >= this.start
&& number <= this.end
&& number % this.step == this.start % this.step;
}
__isAll__(allowed){
return this.start == allowed.start &&
this.end == allowed.end &&
this.step == allowed.step;
}
__isPunctual__(){
return this.start == this.end &&
this.step == 1;
}
__isOneStepRange__(){
return this.start != this.end &&
this.step == 1;
}
__isRangeCycle__(){
return this.start != this.end &&
this.step != 1;
}
*iterator(){
let value = this.start;
while(value <= this.end){
yield value;
value += this.step;
}
}
}
module.exports = Range;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.