text
stringlengths 2
6.14k
|
|---|
module.exports = function(RED) {
"use strict";
var reconnect = RED.settings.ibmdbReconnectTime || 30000;
var db2 = require('ibm_db');
var Promise = require('promise');
function IbmDBNode(n) {
RED.nodes.createNode(this,n);
this.host = n.host;
this.port = n.port;
this.connected = false;
this.connecting = false;
this.dbname = n.db;
var node = this;
function doConnect(conncb) {
node.connecting = true;
node.conn = {};
node.connection = {
connect: (cb) => {
var conStr = "DRIVER={DB2};DATABASE="+node.dbname
+";HOSTNAME="+node.host
+";UID="+node.credentials.user
+";PWD="+node.credentials.password
+";PORT="+node.port+";PROTOCOL=TCPIP";
db2.open(conStr, function (err,conn) {
if (err) {
cb(err, null);
}
else {
console.log('connection to ' + node.dbname);
conn.connName = node.dbname;
cb(null, conn);
}
});
},
end: (conn) => {
conn.close(() => {
console.log('connection closed');
});
}
};
node.connection.connect(function(err, conn) {
node.connecting = false;
if (err) {
node.error(err);
console.log("connection error " + err);
} else {
node.conn = conn;
node.connected = true;
}
conncb(err);
});
}
this.connect = function() {
return new Promise((resolve, reject) => {
if (!this.connected && !this.connecting) {
doConnect((err)=>{
if(err) reject(err);
else resolve();
});
}
else{
resolve();
}
});
}
this.on('close', function (done) {
if (this.connection) {
node.connection.end(this.conn);
}
done();
});
}
RED.nodes.registerType("IbmDBdatabase", IbmDBNode, {
credentials: {
user: {type: "text"},
password: {type: "password"}
}
});
function IbmDBNodeIn(n) {
RED.nodes.createNode(this,n);
this.mydb = n.mydb;
var node = this;
node.query = function(node, db, msg){
if ( msg.payload !== null && typeof msg.payload === 'string' && msg.payload !== '') {
db.conn.query(msg.payload, function(err, rows) {
if (err) {
console.log("QUERY ERROR "+ err);
node.error(err,msg);
}
else {
rows.forEach(function(row) {
node.send({ topic: msg.topic, payload: row });
})
node.send([ null, { topic: msg.topic, control: 'end' }]);
}
});
}
else {
if (msg.payload === null) {
node.error("msg.payload : the query is not defined");
}
if (typeof msg.payload !== 'string') {
node.error("msg.payload : the query is not defined as a string");
}
if (typeof msg.payload === 'string' && msg.payload === '') {
node.error("msg.payload : the query string is empty");
}
}
}
node.on("input", (msg) => {
if ( msg.database !== null && typeof msg.database === 'string' && msg.database !== '') {
node.mydbNode = RED.nodes.getNode(n.mydb);
if (node.mydbNode) {
node.send([ null, { control: 'start', query: msg.payload, database: n.mydb } ]);
if(node.mydbNode.conn && node.mydbNode.conn.connName === msg.database){
console.log("already connected");
node.query(node, node.mydbNode, msg);
}
else{
var findNode;
RED.nodes.eachNode((node)=>{
if(node.db && node.db === msg.database){
findNode = RED.nodes.getNode(node.id);
node.mydb = node.id;
}
})
findNode.connect()
.then(()=>{
node.query(node, findNode, msg);
});
}
}
else {
this.error("database not configured");
}
}
else{
this.error("database not specified");
}
});
}
RED.nodes.registerType("ibmdb", IbmDBNodeIn);
}
|
import { linkTo } from '@storybook/addon-links';
export default {
title: 'Addon/Links',
};
export const GoToWelcome = () => ({
template: '<my-button :rounded="true" @click="click" >This buttons links to Welcome</my-button>',
methods: {
click: linkTo('Welcome'),
},
});
GoToWelcome.story = {
name: 'Go to welcome',
};
|
jQuery(document).ready(function($){
var is_firefox = navigator.userAgent.indexOf('Firefox') > -1;
//open team-member bio
$('#cd-team').find('ul a').on('click', function(event){
event.preventDefault();
var selected_member = $(this).data('type');
$('.cd-member-bio.'+selected_member+'').addClass('slide-in');
$('#mainNav').hide();
$('.cd-member-bio-close').addClass('is-visible');
// firefox transitions break when parent overflow is changed, so we need to wait for the end of the trasition to give the body an overflow hidden
if( is_firefox ) {
$('main').addClass('slide-out').one('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend', function(){
$('body').addClass('overflow-hidden');
});
} else {
$('main').addClass('slide-out');
$('body').addClass('overflow-hidden');
}
});
//close team-member bio
$(document).on('click', '.cd-overlay, .cd-member-bio-close', function(event){
event.preventDefault();
$('.cd-member-bio').removeClass('slide-in');
$('#mainNav').show();
$('.cd-member-bio-close').removeClass('is-visible');
if( is_firefox ) {
$('main').removeClass('slide-out').one('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend', function(){
$('body').removeClass('overflow-hidden');
});
} else {
$('main').removeClass('slide-out');
$('body').removeClass('overflow-hidden');
}
});
});
|
(function($) {
}) (JQuery);
|
'use strict';
describe('Service: ScreenSpySrv', function () {
// load the service's module
beforeEach(module('brandonMcgregorApp'));
// instantiate service
var ScreenSpySrv;
beforeEach(inject(function (_ScreenSpySrv_) {
ScreenSpySrv = _ScreenSpySrv_;
}));
it('should do something', function () {
expect(!!ScreenSpySrv).toBe(true);
});
});
|
'use strict';
angular.module('baka')
.controller('NavbarCtrl', function ($scope, AuthenticationService) {
$scope.logout = function () {
AuthenticationService.logout();
};
});
|
/**
* Created by Adrian on 2016-05-08.
*/
import angular from "angular";
import angularMeteor from "angular-meteor";
import uiRouter from "angular-ui-router";
import "./mobile.html";
import {Tasks} from "../../../api/tasks/index";
import {name as TaskItem} from "../taskItem/taskItem";
class TasksList {
constructor($scope, $reactive) {
'ngInject';
$reactive(this).attach($scope);
this.subscribe('tasks');
this.helpers({
tasks() {
return Tasks.find();
}
});
}
}
const template = 'mobile';
const name = 'tasksList';
export default angular.module(name, [
angularMeteor,
uiRouter,
TaskItem
]).component(name, {
templateUrl: `imports/ui/components/${name}/${template}.html`,
controllerAs: name,
controller: TasksList
});
|
// colors and line weights
var NOTHING = 0;
var EVERYTHING = 255;
var MOSTLY = 200;
var THICK_WEIGHT = 4;
var THIN_WEIGHT = 1;
// background
var CANVAS_WIDTH = 1000;
var CANVAS_HEIGHT = 750;
// touchpad
var BOX_SIZE = 50;
var X_MIN = CANVAS_WIDTH - (2 * BOX_SIZE);
var X_MAX = X_MIN + BOX_SIZE;
var Y_MIN = BOX_SIZE;
var Y_MAX = Y_MIN + BOX_SIZE;
// the circle
var DIAMETER = 20;
var EASING = 0.1;
var x_now = 0;
var y_now = 0;
var remap_cursor = function(sketch){
sketch.setup = function(){
sketch.createCanvas(CANVAS_WIDTH, CANVAS_HEIGHT);
sketch.background(NOTHING, NOTHING, EVERYTHING);
sketch.stroke(EVERYTHING);
sketch.strokeWeight(THIN_WEIGHT);
sketch.fill(NOTHING, NOTHING, EVERYTHING);
sketch.rect(X_MIN, Y_MIN, BOX_SIZE, BOX_SIZE);
}// end sketch.setup
sketch.draw = function(){
// refresh the background
sketch.background(NOTHING, NOTHING, EVERYTHING, MOSTLY);
sketch.strokeWeight(THIN_WEIGHT);
sketch.rect(X_MIN, Y_MIN, BOX_SIZE, BOX_SIZE);
// map the mouse position in the box to the larger image
mx = sketch.map(sketch.mouseX, X_MIN, X_MAX, 0, CANVAS_WIDTH);
my = sketch.map(sketch.mouseY, Y_MIN, Y_MAX, 0, CANVAS_HEIGHT);
// add easing
x_now = x_now + (mx - x_now) * EASING;
y_now = y_now + (my - y_now) * EASING;
// draw the circle
sketch.strokeWeight(THICK_WEIGHT);
sketch.ellipse(x_now, y_now,
DIAMETER, DIAMETER);
}// end sketch.draw
}// end remap_cursor
|
/**
* Takes an array of strings that represent functional dependencies and returns
* them as an array of objects containing functionaldependency objects.
*/
var parseInput = function(lines) {
lines = lines.split('\n');
var functionalDependencies = new DependencySet();
for(var i = 0; i < lines.length; ++i) {
var line = lines[i];
var arrowIndex = line.indexOf('->');
if(arrowIndex >= 0) {
var lhs = line.substring(0, arrowIndex).trim().split(',');
var rhs = line.substring(arrowIndex + 2, line.length).trim().split(',');
/* Trim all the individual attributes */
for(var j=0;j<lhs.length;++j)
lhs[j] = lhs[j].trim();
for(var k=0;k<rhs.length;++k)
rhs[k] = rhs[k].trim();
/* Make sure they're nonzero and add them to the list */
if(lhs.length > 0 && rhs.length > 0) {
var functionalDependency = new FunctionalDependency(lhs, rhs);
functionalDependencies.add(functionalDependency);
}
}
}
return functionalDependencies;
};
|
var test = require('tape');
var url = require('url');
var curli = require('../');
var testServer = require('./server.js');
var buildUAString = require('../lib/util').buildUAString;
test('Default user agent being set', function(t) {
var server = testServer.createServer();
var ua = buildUAString();
server.listen(0, function() {
var port = server.address().port;
var host = '//localhost:' + port;
var href = 'http:' + host + '/';
server.on('/', function(req, res) {
t.equal(req.headers['user-agent'], ua, 'Default user agent set to "' + ua + '"');
res.writeHead(200);
res.end();
});
curli(href, function(err, headers) {
t.ok(headers, 'Headers sent');
t.error(err, 'Shouldn\'t error');
server.close();
t.end();
});
});
});
test('Custom user agent', function(t) {
var server = testServer.createServer();
server.listen(0, function() {
var port = server.address().port;
var host = '//localhost:' + port;
var href = 'http:' + host + '/';
var options = url.parse(href);
options.headers = {
'User-Agent': 'Node'
};
var ua = options.headers['User-Agent'];
server.on('/', function(req, res) {
t.equal(req.headers['user-agent'], ua, 'Custom user agent set to "' + ua + '"');
res.writeHead(200);
res.end();
});
curli(options, function(err, headers) {
t.ok(headers, 'Headers sent');
t.error(err, 'Shouldn\'t error');
server.close();
t.end();
});
});
});
test('Custom user agent, funky header', function(t) {
var server = testServer.createServer();
server.listen(0, function() {
var port = server.address().port;
var host = '//localhost:' + port;
var href = 'http:' + host + '/';
var options = url.parse(href);
options.headers = {
'UsER-AgeNt': 'kNode'
};
var ua = options.headers['UsER-AgeNt'];
server.on('/', function(req, res) {
t.equal(req.headers['user-agent'], ua, 'Custom user agent set to "' + ua + '"');
res.writeHead(200);
res.end();
});
curli(options, function(err, headers) {
t.ok(headers, 'Headers sent');
t.error(err, 'Shouldn\'t error');
server.close();
t.end();
});
});
});
|
var path = require('path'),
config;
config = {
production: {
url: 'http://localhost:2368',
database: {
client: 'sqlite3',
connection: {
filename: path.join(__dirname, '../node_modules/ghost/content/data/ghost-dev.db')
},
debug: false
},
server: {
host: '127.0.0.1',
port: '2368'
},
paths: {
contentPath: path.join(__dirname, '../node_modules/ghost/content/')
}
}
};
// Export config
module.exports = config;
|
// All symbols in the Phoenician block as per Unicode v6.1.0:
[
'\uD802\uDD00',
'\uD802\uDD01',
'\uD802\uDD02',
'\uD802\uDD03',
'\uD802\uDD04',
'\uD802\uDD05',
'\uD802\uDD06',
'\uD802\uDD07',
'\uD802\uDD08',
'\uD802\uDD09',
'\uD802\uDD0A',
'\uD802\uDD0B',
'\uD802\uDD0C',
'\uD802\uDD0D',
'\uD802\uDD0E',
'\uD802\uDD0F',
'\uD802\uDD10',
'\uD802\uDD11',
'\uD802\uDD12',
'\uD802\uDD13',
'\uD802\uDD14',
'\uD802\uDD15',
'\uD802\uDD16',
'\uD802\uDD17',
'\uD802\uDD18',
'\uD802\uDD19',
'\uD802\uDD1A',
'\uD802\uDD1B',
'\uD802\uDD1C',
'\uD802\uDD1D',
'\uD802\uDD1E',
'\uD802\uDD1F'
];
|
import React, {PropTypes} from "react";
import {Provider} from "react-redux";
import {Router} from "react-router";
import {getRoutes} from "./routes";
export default function Root({history, store}) {
return (
<Provider store={store}>
<Router history={history} routes={getRoutes(store.getState)}/>
</Provider>
);
}
Root.propTypes = {
history: PropTypes.object.isRequired,
store: PropTypes.object.isRequired
};
|
/*********************************************************************************
* File Name : loader.js
* Created By : Jone Casper(xu.chenhui@live.com)
* Creation Date : [2014-03-25 22:14]
* Last Modified : [2014-04-06 05:17]
* Description : A loader for loading module
**********************************************************************************/
(function(root, name, factory) {
"use strict";
if (typeof define === 'function' && define.amd) {
define(function(){
return factory();
});
}else if (typeof module !== 'undefined' && module.exports && typeof require === 'function'){
module.exports = factory();
}else{
var namespaces = name.split("."),
scope = root || this;
for (var i=0; i<namespaces.length; i++) {
var p = namespaces[i],
ex = scope[p];
scope = scope[p] = (i === namespaces.length - 1) ?
factory():
(ex || {});
}
}
}(this, "backchart.base.loader",function(){
var root = this;
var exports = function(name, callback){
var args = [];
if (typeof define === 'function' && define.amd) {
require(name instanceof Array ? name : [name], callback);
}else if (typeof module !== 'undefined' && module.exports && typeof require === 'function'){
if (name instanceof Array){
for (var i=0; i<name.length ; i++){
args.push(require(name[i]));
}
callback.apply(this, args);
}else{
callback.call(this, require(name));
}
}else{
if (typeof name === "string" || name instanceof String){
name = [name];
}
for (var n=0; n<name.length; n++){
var namespaces = name[n],
scope = root;
namespaces = namespaces.replace("/",".").split(".");
for (var j=0; j<namespaces.length; j++) {
var p = namespaces[j],
ex = scope[p];
if (!ex) {
args.push(null);
break;
//callback.call(this, null);
}
if (j === namespaces.length -1){
args.push(ex);
//callback.call(this, ex);
}
scope = ex;
}
}
callback.apply(this, args);
}
};
return exports;
}));
|
/*jshint esversion: 6 */
(function () {
let locationPromise = new Promise((resolve, reject) => {
navigator.geolocation.getCurrentPosition((position) => {
resolve(position);
});
});
locationPromise
.then(displayLocation)
.catch((error) => {
// var errMessage = document.getElementById("main");
let errMessage = $("#main");
errMessage.html("Can not get location");
});
function displayLocation(position) {
let imgSrc = `http://maps.googleapis.com/maps/api/staticmap?center=${position.coords.latitude},${position.coords.longitude}&zoom=18&size=600x600&sensor=true`;
$("#locationMap").attr("src", imgSrc);
}
}());
|
"use strict";
System.register([], function (_export, _context) {
"use strict";
var ClickCounter;
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
return {
setters: [],
execute: function () {
_export("ClickCounter", ClickCounter = function () {
function ClickCounter() {
_classCallCheck(this, ClickCounter);
this.count = 0;
}
ClickCounter.prototype.increment = function increment() {
this.count++;
};
return ClickCounter;
}());
_export("ClickCounter", ClickCounter);
}
};
});
|
/**
* local_resize_img
* by hefish@gmail.com
* 2015-04-08
*/
var MAX_SIZE = 600;
var LIT_SIZE = 80;
$.fn.local_resize_img = function(obj) {
this.on('change', function() {
var file_path = this.files[0];
load_image(file_path);
});
function is_android() {
var ua = navigator.userAgent.toLowerCase();
is_android_browser = ua.indexOf("android") > -1;
return is_android_browser;
}
function is_ios() {
var ua = navigator.userAgent.toLowerCase();
is_android_browser = ua.indexOf("iphone") > -1;
return is_android_browser;
}
function load_image(file_path) {
if (! file_path.type.match(/image.*/)) {
if (window.console) {
console.log("我说哥哥,只能选图片");
}else {
window.confirm("我说哥哥,只能选图片啊");
}
return ;
}
var reader = new FileReader() ;
reader.onloadend = function(e) {
//获取到图片内容,准备渲染 (内容是base64滴,还带header)
render(e.target.result);
};
reader.readAsDataURL(file_path);
};
function render(img_data) {
var img = new Image() ;
img.src = img_data; //先把图啊,用个img对象装起来
img.onload = function () {
var this_img = this;
var w = this_img.width, lit_w, lit_h,
h = this_img.height,
scale = w/h; //宽高比
//计算缩放之后的宽高
if (Math.min(w,h) > MAX_SIZE) {
if (w > h) {
h=MAX_SIZE; w=h*scale;
lit_h = LIT_SIZE; lit_w = lit_h * scale;
}
else {
w=MAX_SIZE; h = w/scale;
lit_w = LIT_SIZE ; lit_h = w/scale;
}
}
//取exif.orientation
EXIF.getData(this);
var orientation = EXIF.getTag(this, "Orientation") || 1;
var rotate_degree = 0;
switch(orientation) {
case 1:
rotate_degree = 0; break;
case 8:
rotate_degree = -90;
break;
case 3:
rotate_degree = 180;
break;
case 6:
rotate_degree = 90;
break;
}
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
if (rotate_degree == 90 || rotate_degree == -90) {
$(canvas).attr({width: h, height: w});
}else {
$(canvas).attr({width: w, height: h});
}
//draw on big resized canvas MAX_SIZE
var canvas_width = $(canvas).attr("width");
var canvas_height = $(canvas).attr("height");
if (is_ios()) {
var mp_img = new MegaPixImage(img);
mp_img.render(canvas, {maxWidth:w, maxHeight:h, orientation:orientation});
}else {
ctx.translate(canvas_width/2, canvas_height/2);
ctx.rotate(rotate_degree * Math.PI/180);
ctx.drawImage(this_img, -w/2,-h/2, w,h);
}
var base64 = canvas.toDataURL("image/jpeg", 0.8);
if (base64.indexOf("image/jpeg") > 0) {
}
else {
var encoder = new JPEGEncoder(80);
var img_data = ctx.getImageData(0,0,canvas_width,canvas_height);
base64 = encoder.encode(img_data);
}
var result = {
base64: base64,
};
obj.success(result);
};
}
};
|
module.exports = require('identity-obj-proxy');
|
Meteor.startup(function () {
Meteor.defer(function () {
Session.setDefault("checked", $("input[type=checkbox]").is(":checked"));
});
if (Meteor.isCordova) {
window.alert = navigator.notification.alert;
}
Push.addListener('message', function(notification) {
// Called on every message
console.log(JSON.stringify(notification))
function alertDismissed() {
NotificationHistory.update({_id: notification.payload.historyId}, {
$set: {
"recievedAt": new Date()
}
});
}
alert(notification.message, alertDismissed, notification.payload.title, "Ok");
});
});
|
// dependencies
var AWS = require('aws-sdk'); //Provided by lambda (no need to install)
var async = require('async');
var gm = require('gm')
.subClass({ imageMagick: true }); // Enable ImageMagick integration.
var util = require('util');
var fs = require("fs");
var path = require("path");
// get reference to S3 client
var s3 = new AWS.S3();
exports.handler = function(event, context) {
// Load config.json
var configPath = path.resolve(__dirname, "config.json");
var config = JSON.parse(fs.readFileSync(configPath, { encoding: "utf8" }));
// Read options from the event.
console.log("Reading options from event:\n", util.inspect(event, {depth: 5}));
var srcBucket = event.Records[0].s3.bucket.name;
var srcKey = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' '));
var dstBucket = config.dstBucket; //from config.json
var dstKey = srcKey;
// Sanity check: validate that source and destination are different buckets.
if (srcBucket == dstBucket) {
console.error("Destination bucket must not match source bucket.");
return;
}
var thumbs = config.thumbs; // From config.json
var thumbs2 = thumbs; // Take a copy to iterate, but leave original alone
for (var i=0, tot=thumbs2.length; i < tot; i++) {
async.waterfall(
[
function download(next) {
// Download the image from S3 into a buffer.
s3.getObject(
{
Bucket: srcBucket,
Key: srcKey
},
next
);
},
function getFormat(response, next) {
gm(response.Body).format(function (err, format) {
// console.log('Format: '+ format);
next(null, format, response);
});
},
function transform(imageType, response, next) {
// console.log('imageType: '+ imageType);
var current_thumb = thumbs.pop();
if(current_thumb.type=='thumbnail'){
if (typeof current_thumb.geometry == 'undefined') current_thumb.geometry = '960x540';
console.log('Thumbnail '+ current_thumb.geometry);
gm(response.Body)
.autoOrient()
.noProfile()
.command('convert')
.out('-quality', 95)
.out('-gravity', 'center')
.out('-resize', current_thumb.geometry+'^')
.out('-crop', current_thumb.geometry+'+0+0')
.toBuffer(imageType, function(err, buffer) {
if (err) {
next(err);
} else {
next(null, response.ContentType, buffer, current_thumb.folder);
}
});
} else if(current_thumb.type=='resize'){
if (typeof current_thumb.width == 'undefined') current_thumb.width = null;
if (typeof current_thumb.height == 'undefined') current_thumb.height = null;
console.log('Resize '+ current_thumb.width + 'x' + current_thumb.height);
gm(response.Body)
.resize(current_thumb.width, current_thumb.height)
.toBuffer(imageType, function(err, buffer) {
if (err) {
next(err);
} else {
next(null, response.ContentType, buffer, current_thumb.folder);
}
});
}
},
function upload(contentType, data, folder, next) {
// Stream the transformed image to a different S3 bucket.
console.log('Uploading '+ folder + '/' + dstKey);
s3.putObject(
{
Bucket: dstBucket,
Key: folder + '/' + dstKey,
Body: data,
ContentType: contentType
},
next
);
}
],
function (err) {
if (err) {
console.error(
'Unable to resize ' + srcBucket + '/' + srcKey +
' and upload to ' + dstBucket + '/' + dstKey +
' due to an error: ' + err
);
} else {
console.log(
'Successfully resized ' + srcBucket + '/' + srcKey +
' and uploaded to ' + dstBucket + '/' + dstKey
);
}
//callback(null, "message");
}
);
}
};
|
import Yoga from '@react-pdf/yoga';
import setJustifyContent from '../../src/node/setJustifyContent';
describe('node setJustifyContent', () => {
const mock = jest.fn();
const node = { _yogaNode: { setJustifyContent: mock } };
beforeEach(() => {
mock.mockReset();
});
test('should return node if no yoga node available', () => {
const emptyNode = { box: { width: 10, height: 20 } };
const result = setJustifyContent(null)(emptyNode);
expect(result).toBe(emptyNode);
});
test('Should set center', () => {
const result = setJustifyContent('center')(node);
expect(mock.mock.calls).toHaveLength(1);
expect(mock.mock.calls[0][0]).toBe(Yoga.JUSTIFY_CENTER);
expect(result).toBe(node);
});
test('Should set flex-end', () => {
const result = setJustifyContent('flex-end')(node);
expect(mock.mock.calls).toHaveLength(1);
expect(mock.mock.calls[0][0]).toBe(Yoga.JUSTIFY_FLEX_END);
expect(result).toBe(node);
});
test('Should set flex-start', () => {
const result = setJustifyContent('flex-start')(node);
expect(mock.mock.calls).toHaveLength(1);
expect(mock.mock.calls[0][0]).toBe(Yoga.JUSTIFY_FLEX_START);
expect(result).toBe(node);
});
test('Should set space-between', () => {
const result = setJustifyContent('space-between')(node);
expect(mock.mock.calls).toHaveLength(1);
expect(mock.mock.calls[0][0]).toBe(Yoga.JUSTIFY_SPACE_BETWEEN);
expect(result).toBe(node);
});
test('Should set space-around', () => {
const result = setJustifyContent('space-around')(node);
expect(mock.mock.calls).toHaveLength(1);
expect(mock.mock.calls[0][0]).toBe(Yoga.JUSTIFY_SPACE_AROUND);
expect(result).toBe(node);
});
test('Should set space-evenly', () => {
const result = setJustifyContent('space-evenly')(node);
expect(mock.mock.calls).toHaveLength(1);
expect(mock.mock.calls[0][0]).toBe(Yoga.JUSTIFY_SPACE_EVENLY);
expect(result).toBe(node);
});
});
|
// Constants
export const USERS_INCREMENT = 'USERS_INCREMENT'
export const USERS_DOUBLE_ASYNC = 'USERS_DOUBLE_ASYNC'
// Actions
export function increment(value = 1) {
return {
type: USERS_INCREMENT,
payload: value
}
}
export const doubleAsync = () => {
return (dispatch, getState) => {
return new Promise((resolve) => {
setTimeout(() => {
dispatch({
type: USERS_DOUBLE_ASYNC,
payload: getState().users
})
resolve()
}, 200)
})
}
}
export const actions = {
increment,
doubleAsync
}
// Action Handlers
const ACTION_HANDLERS = {
[USERS_INCREMENT]: (state, action) => state + action.payload,
[USERS_DOUBLE_ASYNC]: (state) => state * 2
}
// Reducer
const initialState = 0
export default function usersReducer(state = initialState, action) {
const handler = ACTION_HANDLERS[action.type]
return handler ? handler(state, action) : state
}
|
import React from 'react';
import SvgExclamation from '../svg/Exclamation.js';
import styles from './InputArea.scss';
const exclamation = () =>
<div className={styles.suffix + ' ' + styles.exclamation}>
<SvgExclamation width={2} height={11}/>
</div>;
export default exclamation;
|
var TestTime = require('logux-core').TestTime
var ServerSync = require('../server-sync')
var TestPair = require('../test-pair')
var sync
function createTest () {
var test = new TestPair()
sync = new ServerSync('server', TestTime.getLog(), test.left)
test.leftSync = sync
return test.left.connect().then(function () {
return test
})
}
afterEach(function () {
sync.destroy()
})
it('sends debug messages', function () {
return createTest().then(function (test) {
test.leftSync.sendDebug('testType', 'testData')
return test.wait('right')
}).then(function (test) {
expect(test.leftSent).toEqual([['debug', 'testType', 'testData']])
})
})
it('emits a debug on debug error messages', function () {
var pair = new TestPair()
sync = new ServerSync('server', TestTime.getLog(), pair.left)
sync.authenticated = true
var debugs = []
sync.on('debug', function (type, data) {
debugs.push(type, data)
})
sync.onMessage(['debug', 'error', 'testData'])
expect(debugs).toEqual(['error', 'testData'])
})
it('checks types', function () {
var wrongs = [
['debug'],
['debug', 0],
['debug', []],
['debug', {}, 'abc'],
['debug', 'error', 0],
['debug', 'error', []],
['debug', 'error', {}]
]
return Promise.all(wrongs.map(function (command) {
return createTest().then(function (test) {
test.right.send(command)
return test.wait('right')
}).then(function (test) {
expect(test.leftSync.connected).toBeFalsy()
expect(test.leftSent).toEqual([
['error', 'wrong-format', JSON.stringify(command)]
])
})
}))
})
|
'use strict';
var util = require('util'),
Transform = require('stream').Transform,
Response = require('../response');
function ResponseStream (multiline) {
this.multiline = multiline || false;
var response;
this._transform = function (chunk, encoding, callback) {
if (undefined === response) {
response = Response.createFromString(encoding === 'buffer' ? chunk.toString() : chunk);
if (false === this.multiline) {
this.push(response);
this.end();
}
} else {
response.lines.push(chunk);
}
callback();
};
this._flush = function (callback) {
this.push(response);
callback();
};
Transform.call(this, { objectMode: true });
}
util.inherits(ResponseStream, Transform);
module.exports = ResponseStream;
|
// Regular expression that matches all symbols with the `Pattern_White_Space` property as per Unicode v6.3.0:
/[\x09-\x0D\x20\x85\u200E\u200F\u2028\u2029]/;
|
$(function() {
// When we're using HTTPS, use WSS too.
$('#all_messages').scrollTop($('#all_messages')[0].scrollHeight);
var to_focus = $("#message");
var ws_scheme = window.location.protocol == "https:" ? "wss" : "ws";
var chatsock = new ReconnectingWebSocket(ws_scheme + '://' + window.location.host + "/ws/");
chatsock.onmessage = function(message) {
if($("#no_messages").length){
$("#no_messages").remove();
}
var data = JSON.parse(message.data);
if(data.type == "presence"){
//update lurkers count
lurkers = data.payload.lurkers;
lurkers_ele = document.getElementById("lurkers-count");
lurkers_ele.innerText = lurkers;
//update logged in users list
user_list = data.payload.members;
document.getElementById("loggedin-users-count").innerText = user_list.length;
user_list_obj = document.getElementById("user-list");
user_list_obj.innerText = "";
//alert(user_list);
for(var i = 0; i < user_list.length; i++ ){
var user_ele = document.createElement('li');
user_ele.setAttribute('class', 'list-group-item');
user_ele.innerText = user_list[i];
user_list_obj.append(user_ele);
}
return;
}
var chat = $("#chat")
var ele = $('<li class="list-group-item"></li>')
ele.append(
'<strong>'+data.user+'</strong> : ')
ele.append(
data.message)
chat.append(ele)
$('#all_messages').scrollTop($('#all_messages')[0].scrollHeight);
};
$("#chatform").on("submit", function(event) {
var message = {
message: $('#message').val()
}
chatsock.send(JSON.stringify(message));
$("#message").val('').focus();
return false;
});
setInterval(function() {
chatsock.send(JSON.stringify("heartbeat"));
}, 10000);
});
|
"use strict";
/** @module router
* A module that defines a class for routing
* http requests to handler functions
*/
module.exports = {
Router: Router
};
var url = require('url');
function Router(db) {
this.db = db;
this.routeMap = {
get: [],
post: []
}
}
/** @function route
* Routes an incoming request to the proper registered
* request handler, or sends a 404 error if no match
* is found. Modifies the request object to contain a
* params associative array of tokens parsed from the
* reqeust object.
* @param {http.incomingRequest} req - the reqeust object
* @param {http.serverResponse} res - the response object
*/
Router.prototype.route = function(req, res) {
console.log("Routing!");
// The method is used to determine which routeMap
// to search for the route in
var routeMap = this.routeMap[req.method.toLowerCase()];
// The resource string from the request url will
// be matched against the routeMap regular expressions
var resource = url.parse(req.url).pathname;
// Find the correct route for the requested resource
// INVARIANT: route has not yet been found.
for(var i = 0; i < routeMap.length; i++){
var match = routeMap[i].regexp.exec(resource);
if(match) {
// Store the parameters as an object
// on the request
req.params = {}
routeMap[i].tokens.forEach(function(token, j){
// Each token corresponds to a capture group
// from the regular expression match. These are
// offset by 1, as the first entry in the match
// array is the full matching string.
req.params[token] = match[j+1];
});
// Trigger the handler and return, stopping execution
return routeMap[i].handler(req, res);
}
}
console.log("Resource Not Mapped");
// If we reach this point, the resource was not mapped
// to a route, so send a 404 error
res.statusCode = 404;
res.statusMessage = "Resource not found";
res.end("Resource not found");
}
/** @function get
* Adds a GET route with associated handler to
* the get routemap.
* @param {string} route - the route to add
* @param {function} handler - the function to
* call when a match is found
*/
Router.prototype.get = function(route, handler) {
addRoute(this.routeMap.get, route, handler);
}
/** @function post
* Adds a POST route with associated handler to
* the get routemap.
* @param {string} route - the route to add
* @param {function} handler - the function to
* call when a match is found
*/
Router.prototype.post = function(route, handler) {
addRoute(this.routeMap.post, route, handler);
}
/** @function resource
* This is a shorthand method for generating restful
* routes for a resource, i.e.:
* GET route/ -> resource.list()
* POST route/ -> resource.add()
* GET route/:id -> resource.show()
* POST route/:id -> resource.update()
* GET route/:id/edit -> resource.edit()
* POST route/:id/destroy -> resource.destroy()
* @param {string} route - the resource route
* @param {object} resource - an object implementing the
* above methods
*/
Router.prototype.resource = function(route, resource) {
var db = this.db;
console.log("Route: "+route);
if(resource.list) this.get(route, function(req, res) {resource.list(req, res, db)});
if(resource.create) this.post(route, function(req, res) {resource.create(req, res, db)});
if(resource.read) this.get(route + '/:id', function(req, res) {resource.read(req, res, db)});
if(resource.edit) this.get(route + '/:id/edit', function(req, res) {resource.read(req, res, db)});
if(resource.update) this.post(route + '/:id', function(req, res) {resource.update(req, res, db)});
if(resource.destroy) this.get(route + '/:id/destroy', function(req, res) {resource.destroy(req, res, db)});
}
/** @function addRoute
* This helper function adds a route to a routeMap
* associative array
* @param {object} routeMap - the routemap to add the route to
* @param {string} route - the route to add
* @param {function} handler - the handler to add
*/
function addRoute(routeMap, route, handler) {
var tokens = [];
// Convert the route into a regular expression
var parts = route.split('/').map(function(part) {
if(part.charAt(0) == ':') {
// This is a token, so store the token and
// add a regexp capture group to our parts array
tokens.push(part.slice(1));
return '(\\w+)';
} else {
// This is a static sequence of characters,
// so leave it as-is
return part;
}
});
var regexp = new RegExp('^' + parts.join('/') + '/?$');
// Store the route in the routemap
routeMap.push({
regexp: regexp,
tokens: tokens,
handler: handler
});
}
|
function almostPerfect() {
console.log("Hello, world!");
};
for(var i = 0; i < 10; i++)
almostPerfect();
|
'use strict';
var _ = require( 'lodash' );
/* RESPONSE DATA STRUCTURE
==========================================================================
data = [ ..., { // Day Object
stop_id: '2681',
stop_name: 'Highland Ave @ Benton Rd',
mode: [ ..., { // Mode Object
mode_name: 'Bus',
route_type: '3',
route: [ ..., { // Route Object
route_id: '88',
route_name: '88',
direction: [ ..., { // Direction Object
direction_id: '1',
direction_name: 'Inbound',
trip: [ ..., { // Trip Object
sch_arr_dt: '1434278820',
sch_dep_dt: '1434278820',
trip_id: '26616679',
trip_name: '6:40 am from Clarendon Hill Busway to Lechmere'
}]
}]
}]
}]
}]
*/
/**
* Convert from a Day Object to a flat array of data objects representing trips
* @param {Number} dayIndex A numeric index for a weekday, from 0 to 6
* @param {Object} route A route object from the API response
* @return {Array} A flat array of trip data objects
*/
function convertRouteToTripsArray( dayIndex, route ) {
/* jshint camelcase: false */
var routeId = route.route_id;
var routeName = route.route_name;
return _.map( route.direction, function( direction ) {
return _.map( direction.trip, function( trip ) {
return {
day: +dayIndex,
name: trip.trip_name,
route: routeName,
routeId: routeId,
time: +trip.sch_arr_dt,
// Trip ID is NOT UNIQUE: avoid collection issues by avoiding 'id'
tripId: +trip.trip_id
};
});
});
}
/**
* Convert the raw API responses into a flat array of trips
* @param {Array} data The API response object
* @return {Array} A flat array of object literals describing trips
*/
function parseData( data ) {
return _.chain( data )
.reduce(function( memo, day, dayIndex ) {
var trips = _.chain( day.mode )
.pluck( 'route' )
.flatten()
// Create the mapper method for the relevant day
.map( _.partial( convertRouteToTripsArray, dayIndex ) )
.flattenDeep() // Deep flatten
.value();
// Concatenate with the prior results
return memo.concat( trips );
}, [])
.sortBy(function( trip ) {
return trip.time;
})
.value();
}
module.exports = parseData;
|
'use strict';
var extend = require('../utils/extend');
var LoginTask = require('./login');
var IonicAppLib = require('ionic-app-lib');
var IonicProject = IonicAppLib.project;
var Share = IonicAppLib.share;
var log = IonicAppLib.logging.logger;
var Login = IonicAppLib.login;
var appLibUtils = IonicAppLib.utils;
var settings = {
title: 'share',
name: 'share',
summary: 'Share an app with a client, co-worker, friend, or customer',
args: {
'<EMAIL>': 'The email to share the app with'
},
isProjectTask: true
};
function run(ionic, argv) {
var project;
if (argv._.length < 2) {
return appLibUtils.fail('Invalid command', 'share');
}
try {
project = IonicProject.load();
} catch (ex) {
appLibUtils.fail(ex.message);
return;
}
if (project.get('app_id') === '') {
return appLibUtils.fail('You must first upload the app to share it');
}
var email = argv._[1];
if (email.indexOf('@') < 0) {
return appLibUtils.fail('Invalid email address', 'share');
}
log.info(['Sharing app ', project.get('name'), ' (', project.get('app_id'), ') with ', email, '.'].join('').green);
return Login.retrieveLogin()
.then(function(jar) {
if (!jar) {
log.info('No previous login existed. Attempting to log in now.');
return LoginTask.login(argv);
}
return jar;
})
.then(function(jar) {
return Share.shareApp(process.cwd(), jar, email);
})
.catch(function(ex) {
return appLibUtils.fail(ex);
});
}
module.exports = extend(settings, {
run: run
});
|
/*jshint node:true, indent:2, curly:false, eqeqeq:true, immed:true, latedef:true, newcap:true, noarg:true,
regexp:true, undef:true, strict:true, trailing:true, white:true */
/*global X:true */
(function () {
"use strict";
var _ = X._;
/**
Defines the data route.
@extends X.Route
@class
*/
X.dataRoute = X.Route.create({
handle: function (xtr) {
var path, handler, session;
path = xtr.get("requestType");
handler = this.find(path);
if (!handler) {
xtr.error("Could not handle %@".f(path));
} else {
if (handler.needsSession) session = X.Session.create(xtr.get("data"));
handler.handle(xtr, session);
}
},
find: function (path) {
var ret = X.functorMap[path];
//console.log("find(): ", Object.keys(X.functorMap));
return ret;
},
handles: "data /data".w()
});
}());
|
require([
"gaslib/Node"
], function(Node){
QUnit.test( "Node - initialize", function( assert ) {
var node = new Node();
assert.equal( node.getCaption(), "Node", "Nieprawidłowa nazwa węzła" );
});
});
|
var requireDir = require('require-dir')
requireDir('./gulp/tasks')
|
'use strict';
angular.module('myApp.setting')
.factory('SettingServices', ['$http', '$q', '$timeout',
function ($http, $q, $timeout) {
var obj = {};
obj.getMyCfg = function() {
var srvUrl;
if (location.hostname === "localhost" || location.hostname === "127.0.0.1") {
srvUrl = 'localhost:8090';
} else {
srvUrl = 'exploit.courses';
}
var cfg = {
srvurl: srvUrl,
}
return cfg;
}
obj.setMyCfg = function(config) {
localStorage.setItem('lxdcfg', JSON.stringify(config));
}
obj.getSrvUrl = function() {
return '//' + obj.getMyCfg().srvurl;
}
obj.getSrvApiUrl = function() {
return '//' + obj.getMyCfg().srvurl + '/1.0';
}
return obj;
}])
;
|
/*
* sentinel
* https://github.com/jaredhoyt/jquery-sentinel
*
* Copyright (c) 2015 Jared Hoyt
* Licensed under the MIT license.
*/
(function($) {
// Collection method.
$.fn.sentinel = function() {
return this.each(function(i) {
// Do something awesome to each selected element.
$(this).html('awesome' + i);
});
};
// Static method.
$.sentinel = function(options) {
// Override default options with passed-in options.
options = $.extend({}, $.sentinel.options, options);
// Return something awesome.
return 'awesome' + options.punctuation;
};
// Static method default options.
$.sentinel.options = {
punctuation: '.'
};
// Custom selector.
$.expr[':'].sentinel = function(elem) {
// Is this element awesome?
return $(elem).text().indexOf('awesome') !== -1;
};
}(jQuery));
|
import request from "./request";
export default function(defaultMimeType, response) {
return function(url, callback) {
var r = request(url).mimeType(defaultMimeType).response(response);
return callback ? r.get(callback) : r;
};
};
|
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './utils/registerServiceWorker';
import 'semantic-ui-css/semantic.min.css';
ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();
|
$('.registerModalButton').on("click", function () {
var courseId = $(this).data('id'),
courseName = $(this).data('name');
$("#studentModal .registerOkButton").data('courseToRegisterId', courseId);
$("#studentModal #courseNameModal").text(courseName);
});
$(".registerOkButton").on("click", function () {
var id = $("#studentModal .registerOkButton").data('courseToRegisterId'),
token = $('input[name="__RequestVerificationToken"]').val(),
data = {
'courseId': id,
'__RequestVerificationToken': token
};
$.ajax({
type: "POST",
url: "/Home/AssignToCourse",
data: data,
datatype: "html",
success: function (data) {
$('[data-groupid=' + id + ']')
.clone()
.appendTo('.registerdSection')
.find('button')
.remove();
},
error: function (data) {
$("#errorModal .modal-title").text(data.responseText);
$('#errorModal').modal();
console.log('fail to register');
}
});
});
|
import { ActionCreators } from 'redux-undo';
import * as types from './actionTypes';
export function setInitialState(options) {
return {
type: types.SET_INITIAL_STATE,
options
};
}
export function changeDimensions(gridProperty, increment) {
return {
type: types.CHANGE_DIMENSIONS,
gridProperty,
increment
};
}
export function updateGridBoundaries(gridElement) {
return {
type: types.UPDATE_GRID_BOUNDARIES,
gridElement
};
}
export function selectPaletteColor(position) {
return {
type: types.SELECT_PALETTE_COLOR,
position
};
}
export function setCustomColor(customColor) {
return {
type: types.SET_CUSTOM_COLOR,
customColor
};
}
export function cellAction({
id,
drawingTool,
color,
paletteColor,
columns,
rows
}) {
return {
type: `APPLY_${drawingTool}`,
id,
color,
paletteColor,
columns,
rows
};
}
export function moveDrawing({ xDiff, yDiff, cellWidth }) {
return {
type: 'MOVE_DRAWING',
moveDiff: { xDiff, yDiff, cellWidth }
};
}
export function setDrawing(
frames,
paletteGridData,
cellSize,
columns,
rows,
hoveredIndex
) {
return {
type: types.SET_DRAWING,
frames,
paletteGridData,
cellSize,
columns,
rows,
hoveredIndex
};
}
export function endDrag() {
return {
type: types.END_DRAG
};
}
export function switchTool(tool) {
return {
type: types.SWITCH_TOOL,
tool
};
}
export function setCellSize(cellSize) {
return {
type: types.SET_CELL_SIZE,
cellSize
};
}
export function resetGrid() {
return {
type: types.SET_RESET_GRID
};
}
export function showSpinner() {
return {
type: types.SHOW_SPINNER
};
}
export function hideSpinner() {
return {
type: types.HIDE_SPINNER
};
}
export function sendNotification(message) {
return {
type: types.SEND_NOTIFICATION,
message
};
}
export function changeActiveFrame(frameIndex) {
return {
type: types.CHANGE_ACTIVE_FRAME,
frameIndex
};
}
export function reorderFrame(selectedIndex, destinationIndex) {
return {
type: types.REORDER_FRAME,
selectedIndex,
destinationIndex
};
}
export function createNewFrame() {
return {
type: types.CREATE_NEW_FRAME
};
}
export function deleteFrame(frameId) {
return {
type: types.DELETE_FRAME,
frameId
};
}
export function duplicateFrame(frameId) {
return {
type: types.DUPLICATE_FRAME,
frameId
};
}
export function setDuration(duration) {
return {
type: types.SET_DURATION,
duration
};
}
export function changeFrameInterval(frameIndex, interval) {
return {
type: types.CHANGE_FRAME_INTERVAL,
frameIndex,
interval
};
}
export function newProject() {
return {
type: types.NEW_PROJECT
};
}
export function changeHoveredCell(cell) {
return {
type: types.CHANGE_HOVERED_CELL,
cell
};
}
export function undo() {
return ActionCreators.undo();
}
export function redo() {
return ActionCreators.redo();
}
|
/*
* Copyright (c) 2012-2016 André Bargull
* Alle Rechte vorbehalten / All Rights Reserved. Use is subject to license terms.
*
* <https://github.com/anba/es6draft>
*/
const {
assertSame
} = Assert;
// Annex E: Completion reform changes
// https://bugs.ecmascript.org/show_bug.cgi?id=4337
// If-Statement completion value
assertSame(undefined, eval(`0; if (false) ;`));
assertSame(undefined, eval(`0; if (true) ;`));
assertSame(undefined, eval(`0; if (false) ; else ;`));
assertSame(undefined, eval(`0; if (true) ; else ;`));
// Switch-Statement completion value
assertSame(1, eval(`switch (0) { case 0: 1; case 1: }`));
assertSame(1, eval(`switch (0) { case 0: 1; default: }`));
// Try-Statement completion value
assertSame(1, eval(`L: try { throw null } catch (e) { ; } finally { 1; break L; }`));
|
class upnp_upnpservice_1 {
constructor() {
}
// System.Runtime.Remoting.ObjRef CreateObjRef(type requestedType)
CreateObjRef() {
}
// bool Equals(System.Object obj)
Equals() {
}
// int GetHashCode()
GetHashCode() {
}
// System.Object GetLifetimeService()
GetLifetimeService() {
}
// type GetType()
GetType() {
}
// System.Object InitializeLifetimeService()
InitializeLifetimeService() {
}
// string ToString()
ToString() {
}
}
module.exports = upnp_upnpservice_1;
|
/* global GazelleSchema :true */
// obj2 is merged into obj1, replacing duplicate keys.
function merge (obj2, obj1) {
for (var k in obj2) {
try {
if (obj2[k].constructor === Object) {
obj1[k] = merge(obj1[k], obj2[k]);
} else {
obj1[k] = obj2[k];
}
} catch (e) {
obj1[k] = obj2[k];
}
}
return obj1;
}
var formatLabel = function (identifier, label) {
return 'The ' + (identifier ? identifier + '\'s ' : ' ') + label;
};
GazelleSchema = function (identifier) {
this.identifier = identifier;
};
GazelleSchema.prototype.formatLabel = function (label) {
return formatLabel(this.identifier, label);
};
GazelleSchema.prototype.id = function (extra) {
return merge(extra, {
type: String,
label: this.formatLabel('id'),
index: true,
unique: true,
autoValue: function () {
if (this.isInsert) {
return Random.id();
} else {
this.unset();
}
}
});
};
GazelleSchema.prototype.foreignId = function (identifier, extra) {
return merge(extra, {
type: String,
label: formatLabel(identifier, 'id'),
index: true,
unique: false,
optional: false
});
};
GazelleSchema.prototype.title = function (extra) {
return merge(extra, {
type: String,
label: this.formatLabel('title'),
index: true
});
};
GazelleSchema.prototype.name = function (extra) {
return merge(extra, this.title({
label: this.formatLabel('name')
}));
};
GazelleSchema.prototype.createdAt = function (extra) {
return merge(extra, {
type: Date,
label: this.formatLabel('created at timestamp'),
autoValue: function () {
if (this.isInsert) {
return new Date;
} else if (this.isUpsert) {
return {
$setOnInsert: new Date
};
} else {
this.unset();
}
}
});
};
GazelleSchema.prototype.updatedAt = function (extra) {
return merge(extra, {
type: Date,
label: this.formatLabel('updated at timestamp'),
autoValue: function () {
if (this.isUpdate) {
return new Date();
}
},
denyInsert: true,
optional: true
});
};
GazelleSchema.prototype.createdBy = function (extra) {
return merge(extra, {
type: String,
label: this.formatLabel('created by user id'),
autoValue: function () {
if (this.isInsert) {
return this.userId;
} else if (this.isUpsert) {
return {
$setOnInsert: this.userId
};
} else {
this.unset();
}
}
});
};
GazelleSchema.prototype.images = function (extra) {
return merge(extra, {
type: [new SimpleSchema({
title: this.images({
index: false
}),
url: {
type: String,
label: 'The url of the image'
},
createdAt: this.createdAt('image'),
createdBy: this.createdBy('image')
})],
label: 'The images',
optional: true
});
};
GazelleSchema.prototype.description = function (extra) {
return merge(extra, {
type: String,
label: this.formatLabel('description'),
optional: true
});
};
GazelleSchema.prototype.body = function (extra) {
return merge(extra, this.description({
label: this.formatLabel('body')
}));
};
GazelleSchema.prototype.tags = function (extra) {
return merge(extra, {
type: [new SimpleSchema({
id: this.id('tag'),
createdAt: this.createdAt('tag'),
createdBy: this.createdBy('tag')
})],
label: this.formatLabel('tag'),
optional: true
});
};
GazelleSchema.prototype.leechType = function (extra) {
return merge(extra, {
type: String,
label: this.formatLabel('leech type'),
defaultValue: function () {
return 'Regular';
},
allowedValues: ['Regular', 'Free Leech', 'Neutral Leech']
});
};
GazelleSchema.year = function (extra) {
return {
type: Number,
label: 'The ' + (entity ? entity + '\s ' : ' ') + 'year',
optional: false
};
};
|
/*
* File: Options.AreaChart.js
*
*/
/*
Object: Options.AreaChart
<AreaChart> options.
Other options included in the AreaChart are <Options.Canvas>, <Options.Label>, <Options.Margin>, <Options.Tips> and <Options.Events>.
Syntax:
(start code js)
Options.AreaChart = {
animate: true,
labelOffset: 3,
type: 'stacked',
selectOnHover: true,
showAggregates: true,
showLabels: true,
filterOnClick: false,
restoreOnRightClick: false
};
(end code)
Example:
(start code js)
var areaChart = new $jit.AreaChart({
animate: true,
type: 'stacked:gradient',
selectOnHover: true,
filterOnClick: true,
restoreOnRightClick: true
});
(end code)
Parameters:
animate - (boolean) Default's *true*. Whether to add animated transitions when filtering/restoring stacks.
labelOffset - (number) Default's *3*. Adds margin between the label and the default place where it should be drawn.
type - (string) Default's *'stacked'*. Stack style. Posible values are 'stacked', 'stacked:gradient' to add gradients.
selectOnHover - (boolean) Default's *true*. If true, it will add a mark to the hovered stack.
showAggregates - (boolean) Default's *true*. Display the sum of the values of the different stacks.
showLabels - (boolean) Default's *true*. Display the name of the slots.
filterOnClick - (boolean) Default's *true*. Select the clicked stack by hiding all other stacks.
restoreOnRightClick - (boolean) Default's *true*. Show all stacks by right clicking.
*/
Options.AreaChart = {
$extend: true,
animate: true,
labelOffset: 3, // label offset
type: 'stacked', // gradient
Tips: {
enable: false,
onShow: $.empty,
onHide: $.empty
},
Events: {
enable: false,
onClick: $.empty
},
selectOnHover: true,
showAggregates: true,
showLabels: true,
filterOnClick: false,
restoreOnRightClick: false
};
|
import React, { createContext, useState } from 'react';
import PropTypes from 'prop-types';
const ErrorContext = createContext({
errors: [],
});
const ErrorProvider = ({ children }) => {
const [errors, setErrors] = useState([]);
return (
<ErrorContext.Provider
value={{
errors,
setErrors,
}}
>
{children}
</ErrorContext.Provider>
);
};
ErrorProvider.propTypes = {
children: PropTypes.node,
};
export { ErrorContext, ErrorProvider };
|
module.exports = {
'ar': require('../../i18n/ar.json'),
'da': require('../../i18n/da.json'),
'de': require('../../i18n/de.json'),
'en': require('../../i18n/en.json'),
'es': require('../../i18n/es.json'),
'fr': require('../../i18n/fr-FR.json'),
'fr-FR': require('../../i18n/fr-FR.json'),
'he': require('../../i18n/he.json'),
'it': require('../../i18n/it.json'),
'ja': require('../../i18n/ja.json'),
'ko': require('../../i18n/ko.json'),
'nb-NO': require('../../i18n/nb-NO.json'),
'nl': require('../../i18n/nl-NL.json'),
'nl-NL': require('../../i18n/nl-NL.json'),
'pt': require('../../i18n/pt.json'),
'pt-BR': require('../../i18n/pt-BR.json'),
'ru': require('../../i18n/ru.json'),
'sv': require('../../i18n/sv.json'),
'tlh': require('../../i18n/tlh.json'),
'tr': require('../../i18n/tr.json'),
'zh': require('../../i18n/zh.json'),
'zh-TW': require('../../i18n/zh-TW.json')
}
|
var request = require('request');
module.exports = function(args) {
var opts = {
API_URL:'http://en.wikipedia.org/w/api.php',
RATE_LIMIT:false,
RATE_LIMIT_MIN_WAIT:false,
RATE_LIMIT_LAST_CALL:false,
USER_AGENT:'wikipedia (https://github.com/meadowstream/wikipedia.js/)'
};
for (var i in args) {
opts[i] = args[i];
}
return {
// variables
'cache':new Cache(),
// Functions
'opts':opts,
'search':search,
'set_caching':set_caching,
'suggest':suggest,
'page':page,
'geosearch':geosearch,
'languages':languages,
'set_lang':set_lang,
'set_rate_limiting':set_rate_limiting,
'random':random,
// Classes
'WikipediaPage':WikipediaPage
};
};
|
version https://git-lfs.github.com/spec/v1
oid sha256:a285e8981a5115bbdd913280943a1d1a0d498b079ace167d6e90a0cc9e2cdfba
size 93324
|
var gulp = require('gulp'),
config = require('../config.js');
require('./browserify.js');
require('./default.js');
require('./sass.js');
gulp.task('watch', ['default'], function() {
gulp.watch(config.paths.sass.src, ['sass']);
gulp.start('watch:js');
});
|
var path = require('path')
var lib = require(path.join(__dirname, '/lib'))
module.exports = lib
|
import { Factory, faker } from 'ember-cli-mirage';
export default Factory.extend({
survey_type: 'Biological Resources',
duplicator_label: 'Observation(s)',
fully_editable: true,
name() {
return faker.name.jobType();
},
status() {
return faker.list.random('draft', 'active', 'inactive')();
}
});
|
(function($) {
"use strict"; // Start of use strict
// jQuery for page scrolling feature - requires jQuery Easing plugin
$('a.page-scroll').bind('click', function(event) {
var $anchor = $(this);
$('html, body').stop().animate({
scrollTop: ($($anchor.attr('href')).offset().top - 50)
}, 1250, 'easeInOutExpo');
event.preventDefault();
});
// Highlight the top nav as scrolling occurs
$('body').scrollspy({
target: '.navbar-fixed-top',
offset: 100
});
// Closes the Responsive Menu on Menu Item Click
$('.navbar-collapse ul li a').click(function() {
$('.navbar-toggle:visible').click();
});
// Offset for Main Navigation
$('#mainNav').affix({
offset: {
top: 50
}
})
})(jQuery); // End of use strict
((window.gitter = {}).chat = {}).options = {
room: 'FMeat/Lobby'
};
|
var search = require('simple-object-query').search,
CssSelectorParser = require('css-selector-parser').CssSelectorParser,
cssParser = new CssSelectorParser();
cssParser
.registerNestingOperators('>')
.registerAttrEqualityMods('^', '$', '*', '~')
;
module.exports = cssFind;
function cssFind(root, rule) {
if (typeof rule === 'string') {
rule = cssParser.parse(rule);
}
if (rule.type === 'selectors') {
for (var i = 0, len = rule.selectors.length; i < len; i++) {
var res = cssFind(root, rule.selectors[i].rule);
if (res) return res;
}
return;
}
else if (rule.type === 'ruleSet') {
rule = rule.rule;
}
return search({
source: root,
query: {
type: 'tag'
},
include: function (item) {
if (rule.nestingOperator === '>' && item.parent && item.parent !== root) return false;
return (
item.field === 'children' ||
item.path[item.path.length - 1] === 'children'
);
},
callback: function (item) {
if (item.target === root) return;
var node = item.target;
if (isCssValid(node, rule)) {
if (!rule.rule) {
return node;
}
return cssFind(node, rule.rule);
}
}
});
}
function isCssValid(node, rule) {
var i, len;
if (rule.tagName) {
if (node.name !== rule.tagName) return false;
}
if (rule.classNames) {
var classes = (node.attr['class'] || '').split(/\s+/);
for (i = 0, len = rule.classNames.length; i < len; i++) {
if (classes.indexOf(rule.classNames[i]) === -1) return false;
}
}
if (rule.attrs) {
for (i = 0, len = rule.attrs.length; i < len; i++) {
var attr = rule.attrs[i];
if (!node.attr.hasOwnProperty(attr.name)) return false;
switch (attr.operator) {
case '=':
if (node.attr[attr.name] !== attr.value) return false;
break;
case '^=':
if (node.attr[attr.name].indexOf(attr.value) !== 0) return false;
break;
case '$=':
if (node.attr[attr.name].slice(-attr.value.length) !== attr.value) return false;
break;
case '*=':
if (node.attr[attr.name].indexOf(attr.value) === -1) return false;
break;
}
}
}
if (rule.pseudos) {
for (i = 0, len = rule.pseudos.length; i < len; i++) {
var pseudo = rule.pseudos[i];
switch (pseudo.name) {
case 'nth-child':
case 'eq':
if (getChildNodes(node.parent).indexOf(node) !== Number(pseudo.value) - 1) return false;
break;
}
}
}
return true;
}
function getChildNodes(node) {
var nodes = [];
for (var i = 0, len = node.children.length; i < len; i++) {
if (node.children[i].type === 'tag') {
nodes.push(node.children[i]);
}
}
return nodes;
}
|
var Worker = require('./worker')
/**
* Tracks worker state across runs.
*/
function WorkerManager () {
this._pollHandle = null
this.workers = {}
this.isPolling = false
this.shouldShutdown = false
}
WorkerManager.prototype.registerWorker = function registerWorker (workerData) {
if (this.workers[workerData.id]) {
this.unregisterWorker(this.workers[workerData.id])
}
var worker = new Worker(workerData)
worker.emit('status', worker.status)
this.workers[workerData.id] = worker
return worker
}
WorkerManager.prototype.unregisterWorker = function unregisterWorker (worker) {
worker.emit('delete', worker)
worker.removeAllListeners()
delete this.workers[worker.id]
return worker
}
WorkerManager.prototype.updateWorker = function updateWorker (workerData) {
var workers = this.workers
if (workers[workerData.id]) {
var worker = workers[workerData.id]
var prevStatus = worker.status
Object.keys(workerData).forEach(function (k) {
worker[k] = workerData[k]
})
if (worker.status !== prevStatus) {
worker.emit('status', worker.status)
}
}
}
WorkerManager.prototype.startPolling = function startPolling (client, pollingTimeout, callback) {
if (this.isPolling || this.shouldShutdown) {
return
}
var self = this
this.isPolling = true
client.getWorkers(function (err, updatedWorkers) {
if (err) {
self.isPolling = false
return (callback ? callback(err) : null)
}
var activeWorkers = (updatedWorkers || []).reduce(function (o, worker) {
o[worker.id] = worker
return o
}, {})
Object.keys(self.workers).forEach(function (workerId) {
if (activeWorkers[workerId]) {
// process updates
self.updateWorker(activeWorkers[workerId])
} else {
// process deletions
self.unregisterWorker(self.workers[workerId])
}
})
self._pollHandle = setTimeout(function () {
self.isPolling = false
self.startPolling(client, pollingTimeout, callback)
}, pollingTimeout)
})
}
WorkerManager.prototype.stopPolling = function stopPolling () {
if (this._pollHandle) {
clearTimeout(this._pollHandle)
this._pollHandle = null
}
this.shouldShutdown = true
}
// expose a single, shared instance of WorkerManager
module.exports = new WorkerManager()
|
/*global describe, beforeEach, it*/
'use strict';
var assert = require('assert');
describe('frontender generator', function () {
it('can be imported without blowing up', function () {
var app = require('../app');
assert(app !== undefined);
});
});
|
var indexSectionsWithContent =
{
0: "abcdefghilmnoprstuy~",
1: "abcdefghmnops",
2: "e",
3: "acdegilmnoprstu~",
4: "acefpsy",
5: "p",
6: "em"
};
var indexSectionNames =
{
0: "all",
1: "classes",
2: "namespaces",
3: "functions",
4: "variables",
5: "typedefs",
6: "enums"
};
var indexSectionLabels =
{
0: "All",
1: "Classes",
2: "Namespaces",
3: "Functions",
4: "Variables",
5: "Typedefs",
6: "Enumerations"
};
|
const assert = require('assert');
const makeConfig = require('../../../core/util/makeConfig');
describe('make config', function () {
it('should pass the filter arg correctly', function () {
const actualConfig = makeConfig('init', { filter: true });
assert.strictEqual(actualConfig.args.filter, true);
});
it('should work without an option param', function () {
const actualConfig = makeConfig('init');
assert.deepStrictEqual(actualConfig.args, {});
});
});
|
game.TeamArcher = me.Entity.extend({
init: function(x, y, settings){
this._super(me.Entity, 'init', [x, y, {
image: "archer",
width: 64,
height: 64,
spritewidth: "64",
spriteheight: "64",
getShape: function(){
return (new me.Rect(0, 0, 64, 64)).toPolygon();
}
}]);
this.health = 10;
this.alwaysUpdate = true;
this.attacking = false;
this.lastAttacking = new Date().getTime();
this.lastHit = new Date().getTime();
this.now = new Date().getTime();
this.body.setVelocity(3, 20);
this.type = "TeamArcher";
this.renderable.addAnimation("attack", [260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272], 80);
this.renderable.addAnimation("walk", [143, 144, 145, 146, 147, 148, 149, 150, 151], 80);
this.renderable.setCurrentAnimation("walk");
},
loseHealth: function(damage){
this.health = this.health - damage;
},
update: function(delta){
if(this.health <= 0){
me.game.world.removeChild(this);
}
this.now = new Date().getTime();
this.body.vel.x += this.body.accel.x * me.timer.tick;
me.collision.check(this, true, this.collideHandler.bind(this), true);
this.body.update(delta);
this._super(me.Entity, "update", [delta]);
return true;
},
collideHandler: function(response){
if(response.b.type==='EnemyBaseEntity'){
this.attacking=true;
this.lastAttacking=this.now;
this.body.vel.x = 0;
this.pos.x = this.pos.x + 1;
if((this.now-this.lastHit >=1000)){
this.lastHit = this.now;
response.b.loseHealth(game.data.teamArcherAttack);
}
}else if (response.b.type==='EnemyCreep'){
var xdif = this.pos.x - response.b.pos.x;
}else if(response.b.type==='EnemyWizard'){
var xdif = this.pos.x - response.b.pos.x;
}
this.attacking=true;
if(xdif>0){
this.pos.x = this.pos.x + 1;
this.body.vel.x = 0;
}
if((this.now-this.lastHit >=1000) && xdif>0){
this.lastHit = this.now;
response.b.loseHealth(game.data.teamArcherAttack);
}
}
}
);
|
describe('Manual namespace managment', function() {
describe('Namespace#addNamespace', function() {
it('inserts a namespace for a given key', function() {
nsr.addNamespace('users').should.eq('test:users');
});
});
describe('Namespace#removeNamespace', function() {
it('removes a namespace for a given key', function() {
nsr.removeNamespace('test:users').should.eq('users');
});
});
});
|
/* jshint node: true */
/* global require, module */
var EmberAddon = require( 'ember-cli/lib/broccoli/ember-addon' );
var packageConfig = require( './package.json' );
var replace = require( 'broccoli-string-replace' );
var env = require( './config/environment' );
var app = new EmberAddon();
var tree;
// Use `app.import` to add additional libraries to the generated
// output files.
//
// If you need to use different assets in different
// environments, specify an object as the first parameter. That
// object's keys should be the environment name and the values
// should be the asset to use in that environment.
//
// If the library that you are including contains AMD or ES6
// modules that you would like to import into your application
// please specify an object with the list of modules as keys
// along with the exports of each module as its value.
// Testing dependencies
app.import( app.bowerDirectory + '/sinonjs/sinon.js', {
type: 'test'
});
app.import( app.bowerDirectory + '/sinon-qunit/lib/sinon-qunit.js', {
type: 'test'
});
tree = replace( app.toTree(), {
files: [
'index.html',
'assets/dummy.js'
],
patterns: [
{
match: /REPLACE_META_DESCRIPTION/g,
replacement: packageConfig[ 'description' ]
}, {
match: /REPLACE_META_KEYWORDS/g,
replacement: packageConfig[ 'keywords' ].join( ', ' ) +
', ember, ember cli'
}, {
match: /REPLACE_APPLICATION_VERSION/g,
replacement: packageConfig[ 'version' ]
}
]
});
module.exports = tree;
|
function normalizeUrl(url){
// parseUri 1.2.2
// (c) Steven Levithan <stevenlevithan.com>
// MIT License
function parseUri (str) {
var o = parseUri.options,
m = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
uri = {},
i = 14;
while (i--) uri[o.key[i]] = m[i] || "";
uri[o.q.name] = {};
uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
if ($1) uri[o.q.name][$1] = $2;
});
return uri;
};
parseUri.options = {
strictMode: false,
key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
q: {
name: "queryKey",
parser: /(?:^|&)([^&=]*)=?([^&]*)/g
},
parser: {
strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
}
};
//////////////////////////////////////////////////////////////////////////
// //
//////////////////////////////////////////////////////////////////////////
// parse the url
var uri = parseUri(url);
//console.log("BEFORE uri.path", uri.path)
var paths = uri.path.split('/');
//console.log("paths", JSON.stringify(paths))
// remove empty path '//' or null path '/./'
paths = paths.filter(function(str, idx){
if( idx === 0 ) return true;
if( str === '' ) return false;
if( str === '.' ) return false;
return true;
});
//console.log("paths", JSON.stringify(paths))
// handle the parent path '..'
for(var i = 0; i < paths.length; i++ ){
//console.log(i+"th", paths[i], "paths", JSON.stringify(paths))
if( i >= 1 && paths[i+1] === '..' ){
//console.log("BEFORE", i+"th", paths[i], "paths", JSON.stringify(paths))
paths.splice(i, 2);
i -= 2;
//console.log("AFTER", i+"th", paths[i], "paths", JSON.stringify(paths))
}else if( paths[i] === '..' ){
//console.log("BEFORE", i+"th", paths[i], "paths", JSON.stringify(paths))
paths.splice(i, 1);
i -= 1;
//console.log("AFTER", i+"th", paths[i], "paths", JSON.stringify(paths))
}
}
//console.log("paths", JSON.stringify(paths))
// reassemble uri.path
uri.path = paths.join('/');
//console.log("AFTER uri.path", uri.path)
// build the newUrl
var newUrl = uri.protocol+"://"+uri.authority+uri.path
+ (uri.query ? '?'+uri.query :'')
+ (uri.anchor ? '#'+uri.anchor:'');
// return the newUrl
return newUrl;
}
// export in common js
if( typeof module !== "undefined" && ('exports' in module)){
module.exports = normalizeUrl
}
|
var User = require('../../models/user');
module.exports = function(req, res) {
var result = User.find ({})
.where('loginName').ne('root')
.select('id loginName name claims')
.exec(function(err, users) {
res.json(users);
});
};
|
import { moduleForComponent, test } from 'ember-qunit';
//import hbs from 'htmlbars-inline-precompile';
moduleForComponent('fd-uml-diagram', 'Integration | Component | fd-uml-diagram', {
integration: true
});
test('it renders', function(assert) {
// Set any properties with this.set('myProperty', 'value');
// Handle any actions with this.on('myAction', function(val) { ... });
this.set('mockLinkFunction', function() {});
//this.render(hbs`{{fd-uml-diagram
// enableEditLinks = mockLinkFunction
// enableWrapBaseLinks = mockLinkFunction
// disableEditLinks = mockLinkFunction
//}}`);
//assert.equal(this.$().text().trim(), '');
assert.equal('', '');
});
|
'use strict';
angular.module('cmaManagementApp')
.constant('storageTypes', {
VENDOR_UID: "VENDOR_UID",
VENDOR_PASS: "VENDOR_PASS",
CLIENT_UID: "CLIENT_UID",
CLIENT_PASS: "CLIENT_PASS",
MONITOR_UID: "MONITOR_UID",
MONITOR_PASS: "MONITOR_PASS",
ORCH_UID: "ORCH_UID",
ORCH_PASS: "ORCH_PASS"
});
|
/**
* No Coin - Stop coin miners in your browser
**
* @author Rafael Keramidas <ker.af>
* @license MIT
* @source https://github.com/keraf/NoCoin
*/
// Config
const defaultConfig = {
toggle: true,
whitelist: [{
domain: 'cnhv.co',
expiration: 0,
}],
};
const localConfig = JSON.parse(localStorage.getItem('config'));
let config = {
...defaultConfig,
...localConfig,
};
/**
* Functions
*/
const saveConfig = () => {
localStorage.setItem('config', JSON.stringify(config));
};
const changeToggleIcon = (isEnabled) => {
chrome.browserAction.setIcon({
path: `img/${isEnabled ? 'logo_enabled' : 'logo_disabled'}.png`,
});
};
const getDomain = (url) => {
const match = url.match(/:\/\/(.[^/]+)/);
return match ? match[1] : '';
};
const getTimestamp = () => {
return Math.floor(Date.now() / 1000);
};
const isDomainWhitelisted = (domain) => {
if (!domain) return false;
const domainInfo = config.whitelist.find(w => w.domain === domain);
if (domainInfo) {
if (domainInfo.expiration !== 0 && domainInfo.expiration <= getTimestamp()) {
removeDomainFromWhitelist(domain);
return false;
}
return true;
}
return false;
};
const addDomainToWhitelist = (domain, time) => {
if (!domain) return;
// Make sure the domain is not already whitelisted before adding it
if (!isDomainWhitelisted(domain)) {
config.whitelist = [
...config.whitelist,
{
domain: domain,
expiration: time === 0 ? 0 : getTimestamp() + (time * 60),
},
];
saveConfig();
}
};
const removeDomainFromWhitelist = (domain) => {
if (!domain) return;
config.whitelist = config.whitelist.filter(w => w.domain !== domain);
saveConfig();
};
const runBlocker = (blacklist) => {
const blacklistedUrls = blacklist.split('\n');
chrome.webRequest.onBeforeRequest.addListener(details => {
// Globally paused
if (!config.toggle) {
return { cancel: false };
}
// Is domain white listed
if (isDomainWhitelisted(domains[details.tabId])) {
return { cancel: false };
}
return { cancel: true };
}, {
urls: blacklistedUrls
}, ['blocking']);
};
const runFallbackBlocker = () => {
fetch(chrome.runtime.getURL('blacklist.txt'))
.then(resp => {
resp.text().then(text => runBlocker(text));
});
};
/**
* Main
*/
let domains = [];
// Updating domain for synchronous checking in onBeforeRequest
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
domains[tabId] = getDomain(tab.url);
});
chrome.tabs.onRemoved.addListener((tabId) => {
delete domains[tabId];
});
// Run with the right icon
if (!config.toggle) {
changeToggleIcon(false);
}
// Load the blacklist and run the blocker
const blacklist = 'https://raw.githubusercontent.com/keraf/NoCoin/master/src/blacklist.txt';
fetch(blacklist)
.then(resp => {
if (resp.status === 200) {
resp.text().then((text) => {
if (text === '') {
runFallbackBlocker();
} else {
runBlocker(text);
}
});
} else {
runFallbackBlocker();
}
})
.catch(err => {
runFallbackBlocker();
});
// Communication with the popup and content scripts
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
switch (message.type) {
case 'GET_STATE':
sendResponse({
whitelisted: isDomainWhitelisted(domains[message.tabId]),
toggle: config.toggle,
});
break;
case 'TOGGLE':
config.toggle = !config.toggle;
saveConfig();
changeToggleIcon(config.toggle);
sendResponse(config.toggle);
break;
case 'WHITELIST': {
if (message.whitelisted) {
removeDomainFromWhitelist(domains[message.tabId], message.time);
} else {
addDomainToWhitelist(domains[message.tabId], message.time);
}
sendResponse(!message.whitelisted);
break;
}
}
});
|
/**
* @author mrdoob / http://mrdoob.com/
*/
THREE.CSS2DObject = function ( element ) {
THREE.Object3D.call( this );
this.element = element;
this.element.style.position = 'absolute';
this.addEventListener( 'removed', function ( event ) {
if ( this.element.parentNode !== null ) {
this.element.parentNode.removeChild( this.element );
}
} );
};
THREE.CSS2DObject.prototype = Object.create( THREE.Object3D.prototype );
THREE.CSS2DObject.prototype.constructor = THREE.CSS2DObject;
//
THREE.CSS2DRenderer = function () {
console.log( 'THREE.CSS2DRenderer', THREE.REVISION );
var _width, _height;
var _widthHalf, _heightHalf;
var vector = new THREE.Vector3();
var viewMatrix = new THREE.Matrix4();
var viewProjectionMatrix = new THREE.Matrix4();
var domElement = document.createElement( 'div' );
domElement.style.overflow = 'hidden';
this.domElement = domElement;
this.setSize = function ( width, height ) {
_width = width;
_height = height;
_widthHalf = _width / 2;
_heightHalf = _height / 2;
domElement.style.width = width + 'px';
domElement.style.height = height + 'px';
};
var renderObject = function ( object, camera ) {
if ( object instanceof THREE.CSS2DObject ) {
vector.setFromMatrixPosition( object.matrixWorld );
vector.applyMatrix4( viewProjectionMatrix );
var element = object.element;
var style = 'translate(-50%,-50%) translate(' + ( vector.x * _widthHalf + _widthHalf ) + 'px,' + ( - vector.y * _heightHalf + _heightHalf ) + 'px)';
element.style.WebkitTransform = style;
element.style.MozTransform = style;
element.style.oTransform = style;
element.style.transform = style;
if ( element.parentNode !== domElement ) {
domElement.appendChild( element );
}
}
for ( var i = 0, l = object.children.length; i < l; i ++ ) {
renderObject( object.children[ i ], camera );
}
};
this.render = function ( scene, camera ) {
scene.updateMatrixWorld();
if ( camera.parent === null ) camera.updateMatrixWorld();
viewMatrix.copy( camera.matrixWorldInverse );
viewProjectionMatrix.multiplyMatrices( camera.projectionMatrix, viewMatrix );
renderObject( scene, camera );
};
};
|
/*************************************************************
*
* MathJax/localization/br/FontWarnings.js
*
* Copyright (c) 2009-2018 The MathJax Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
MathJax.Localization.addTranslation("br","FontWarnings",{
version: "2.7.3",
isLoaded: true,
strings: {
webFont: "MathJax a implij ar fonto\u00F9 web evit diskwel ar jedado\u00F9 war ar bajenn-ma\u00F1. Pell eo ar re-se o pellgarga\u00F1 ha diskwelet e vefe buanoc'h ma stailhfec'h fonto\u00F9 jedoniezh war-eeun e teuliad fonto\u00F9 ho reizhiad.",
noFonts: "N'hall ket MathJax lec'hia\u00F1 ur polis evit diskwel e jedado\u00F9, ha dihegerz eo ar fonto\u00F9 skeudenn. Ret eo implijout arouezenno\u00F9 Unicode neuze. Emicha\u00F1s e c'hallo ho merdeer diskwel anezho. Ne c'hallo ket arouezenno\u00F9 zo beza\u00F1 diskwelet mat, tamm ebet zoken.",
webFonts: "GAnt an darn vrasa\u00F1 eus ar merdeerio\u00F9 arnevez e c'haller pellgarga\u00F1 fonto\u00F9 adalek ar web. Hizivaat ho merdeer (pe che\u00F1ch merdeer) a c'hallfe gwellaat kalite ar jedado\u00F9 war ar bajenn-ma\u00F1.",
fonts: "Gallout a ra MathJax implijout pe ar fonto\u00F9 [STIX](%1) pe ar fonto\u00F9 [MathJax TeX](%2); Pellgargit ha stailhit unan eus fonto\u00F9-se evit gwellaat ho skiant-prenet gant MathJax.",
STIXPage: "Krouet eo bet ar bajenn-ma\u00F1 evit implijout ar fonto\u00F9 [STIX ](%1). Pellgargit ha stailhit ar fonto\u00F9-se evit gwellaat ho skiant-penet gant MathJax.",
TeXPage: "Krouet eo bet ar bajenn-ma\u00F1 evit implijout ar fonto\u00F9 [MathJax TeX](%1). Pellgargit ha stailhit ar fonto\u00F9-se evit gwellaat ho skiant-prenet gant MathJax.",
imageFonts: "Ober a ra MathJax gant skeudenno\u00F9 font kentoc'h eget gant fonto\u00F9 web pe fonto\u00F9 lec'hel. Gant se e teu an trao\u00F9 gorrekoc'h war-wel ha marteze ne vo ket ar jedado\u00F9 evit beza\u00F1 moullet diouzh pizhder kloka\u00F1 ho moullerez."
}
});
MathJax.Ajax.loadComplete("[MathJax]/localization/br/FontWarnings.js");
|
'use strict';
describe('Controller: AdvisorCtrl', function () {
// load the controller's module
beforeEach(module('advisorLinkApp'));
var AdvisorCtrl, scope;
// Initialize the controller and a mock scope
beforeEach(inject(function ($controller, $rootScope) {
scope = $rootScope.$new();
AdvisorCtrl = $controller('AdvisorCtrl', {
$scope: scope
});
}));
it('should ...', function () {
expect(1).toEqual(1);
});
});
|
var db= require('../../db');
var test = require('assert');
var create;
var createEmbeded;
var createOne;
var createOneEmbeded;
var find;
var findEmbeded;
var findOne;
var findOneEmbeded;
describe('core',function () {
before(function (done) {
db.connect(function () {
create= require('../../core/create');
createEmbeded= require('../../core/createEmbeded');
createOne= require('../../core/createOne');
createOneEmbeded= require('../../core/createOneEmbeded');
find= require('../../core/find');
findEmbeded= require('../../core/findEmbeded');
findOne= require('../../core/findOne');
findOneEmbeded= require('../../core/findOneEmbeded');
done();
});
});
describe('find',function () {
it('find',function (done) {
var payload= new Date().getTime();
create('find',[{p1:payload}])
.then(function () {
return find('find',{p1:payload}).toArray();
})
.then(function (r) {
test.equal(1, r.length);
done();
})
.catch(function (err) {
done(err);
});
});
it('findOne',function (done) {
var payload= new Date().getTime();
create('findOne',[{p1:payload}])
.then(function () {
return findOne('findOne',{p1:payload});
})
.then(function (r) {
test.equal(payload, r.p1);
done();
})
.catch(function (err) {
done(err);
});
});
it('Projection',function (done) {
var payload= new Date().getTime();
create('findOne',[{p1:payload}])
.then(function () {
return findOne('findOne',{p1:payload},{_id:0});
})
.then(function (r) {
test.equal(false, r.hasOwnProperty('_id'));
test.equal(payload, r.p1);
done();
})
.catch(function (err) {
done(err);
});
});
it('findEmbeded',function (done) {
var payload= new Date().getTime();
create('findEmbeded',[
{
a:payload,
embededProperty:[
{
b:payload,
c:1
}]
},
{
a:payload,
embededProperty:[
{
b:payload,
c:2
}]
}
])
.then(function () {
return findEmbeded('embededProperty',{b:payload},{},'findEmbeded');
})
.then(function (r) {
// console.log(r);
test.equal( r.length,2);
done();
})
.catch(function (err) {
done(err);
});
});
it('findOneEmbeded',function (done) {
var payload= new Date().getTime();
create('findOneEmbeded',[
{
a:payload,
embededProperty:[
{
b:payload
}]
},
{
a:payload,
embededProperty:[
{
b:payload
}]
}
])
.then(function () {
return findOneEmbeded('embededProperty',{b:payload},{},'findOneEmbeded');
})
.then(function (r) {
test.equal(payload, r.b);
done();
})
.catch(function (err) {
console.log(err);
done(err);
});
});
});
});
|
(function() {
'use strict';
angular
.module('noctemApp')
.config(stateConfig);
stateConfig.$inject = ['$stateProvider'];
function stateConfig($stateProvider) {
$stateProvider.state('jhi-health', {
parent: 'admin',
url: '/health',
data: {
authorities: ['ROLE_ADMIN'],
pageTitle: 'health.title'
},
views: {
'content@': {
templateUrl: 'app/admin/health/health.html',
controller: 'JhiHealthCheckController',
controllerAs: 'vm'
}
},
resolve: {
translatePartialLoader: ['$translate', '$translatePartialLoader', function ($translate, $translatePartialLoader) {
$translatePartialLoader.addPart('health');
return $translate.refresh();
}]
}
});
}
})();
|
var Reflux = require('reflux');
var Firebase = require('firebase');
var GroupActions = require('../actions/GroupActions');
var DefaultStoreActions = require('../actions/DefaultStoreActions');
var _ = require('underscore');
var firebaseRef;
function updateWithSnapshot(snapshot) {
var val = snapshot.val();
var group = {id: snapshot.key() };
group = _.extend(group, val);
GroupStore.setGroup(snapshot.key(), group);
GroupStore.StoreActions.addSuccess(snapshot.key());
}
function setupFirebase() {
firebaseRef = new Firebase("http://glaring-heat-1654.firebaseio.com/groups");
firebaseRef.on('child_added', updateWithSnapshot);
firebaseRef.on('child_changed', updateWithSnapshot);
firebaseRef.on('child_removed', snapshot => {
GroupStore.destroyGroup(snapshot.key());
});
}
var GroupStore = Reflux.createStore({
_collections : {},
listenables: GroupActions,
StoreActions: DefaultStoreActions(),
init() {
setupFirebase();
},
getGroups(userGroups) {
if (!userGroups) return this._collections;
var groups = [];
userGroups.forEach(groupId => {
groups.concat(this._collections[groupId] || []);
});
return groups;
},
setGroup(key, group) {
this._collections[key] = group;
this.trigger("setGroups", this._collections);
},
destroyGroup(key) {
delete this._collections[key];
this.trigger("setGroups", this._collections);
},
addGroup(group) {
firebaseRef.push(group);
},
updateGroup(group) {
var groupRef = firebaseRef.child(group.id);
groupRef.update(group);
},
removeGroup(group) {
firebaseRef.child(group.id).remove();
}
});
module.exports = GroupStore;
|
'use strict';
angular.module('myApp.view1')
.directive('articolo', [function(){
return{
restrict: "EAC",
scope: {
articolo: "=news",
searchKey: "=searchKey"
},
templateUrl: 'app/components/view1/view1_articolo.html'
}
}])
;
|
'use strict';
const { BasePage } = require('kakunin');
class SimpleForm extends BasePage {
constructor() {
super();
this.url = '/form/simple';
this.form = $('form');
this.nameInput = this.form.$('input[name="name"]');
this.descriptionTextarea = this.form.$('textarea[name="description"]');
this.optionCheckboxes = this.form.$$('input[type="checkbox"]');
this.optionRadios = this.form.$$('input[type="radio"]');
this.statusSelect = this.form.$('select[name="status"]');
this.submitButton = this.form.$('input[type="submit"]');
}
}
module.exports = SimpleForm;
|
var map;
$(document).ready(function(){
var a=document.getElementById('map');
map = new GMaps({el: a,
//el: '#map',
lat: 55.763585,
lng: 37.560883,
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoomControl : true,
zoomControlOpt: {
style : 'SMALL',
position: 'TOP_LEFT'
}
});
var logo=$('#logo').attr('src');
//alert(logo);
var icon = {
url: '/bundles/realty/map_icon.png', // url
scaledSize: new google.maps.Size(40, 40), // scaled size
origin: new google.maps.Point(0,0), // origin
anchor: new google.maps.Point(0, 0) // anchor
};
//var icon='/bundles/realty/map_icon.png';
var markers=$('#PagesAllGoogleMap').val();
markers= JSON.parse(markers);
var PagesAllGoogleMap_path=$('#PagesAllGoogleMap_path').val();
for (var i =0; i<markers.length;i++)
{
if (markers[i]['city'] && markers[i]['street'] ) {
var address=markers[i]['city']+', '+markers[i]['street']+', '+markers[i]['house'];
var image='';
if (markers[i]['image_path']) {
image='<img src="/'+markers[i]['image_path']+'">';
}
var price='';
if (markers[i]['price']) {
price='<p>Price: '+markers[i]['price']+' USD</p>';
}
var totalArea='';
if (markers[i]['totalArea']) {
totalArea='<p>Total Area: '+markers[i]['totalArea']+'m2</p>';
}
var floor='';
if (markers[i]['totalArea']) {
floor='<p>Floor: '+markers[i]['numberOfFloors']+'/'+markers[i]['floor']+'</p>';
}
var contentHtml='<div class="bubblewrap">' +
'<a style="display:block;text-decoration:none" href="'+PagesAllGoogleMap_path+markers[i]['path']+'">' +
'<div class="mapContainer">' +
'<div class="mapPhoto">' + image +
'</div>' +
'<div class="mapDataC">' +
'<p><i class="fa fa-map-marker" aria-hidden="true"></i>'+address+'</p>' +
'<p>'+totalArea+'</p>' +
'<p>'+floor+'</p>' +
'<p>'+price+'</p>' +
'</div>' +
'<div class="view_div"><i class="info_window_arrow fa fa-5x fa-angle-right"></i></div>' +
'</div>' +
'</a>' +
'</div>';
// ************************
// grnertae makers content theme hlml css
// ************************
mapMake(address,icon,contentHtml);
}
}
function mapMake(address, icon, contentHtml )
{
GMaps.geocode({
address: address,
callback: function(results, status, html1) {
if (status == 'OK') {
var latlng = results[0].geometry.location;
map.setCenter(latlng.lat(), latlng.lng());
map.addMarker({
lat: latlng.lat(),
lng: latlng.lng(),
// title: 'Lima',
icon: icon,
infoWindow: {
content: contentHtml
}
});
}
}
});
}
});
|
//Init
var CANVAS_WIDTH = 512;
var CANVAS_HEIGHT = 512;
var MOVABLE = "movable";
//jiglib body types in strings
var BODY_TYPES = ["SPHERE", "BOX","CAPSULE", "PLANE"];
//enums for indexing BODY_TYPES
var BodyValues = {"SPHERE":0, "BOX":1, "CAPSULE":2, "PLANE":3};
var SCORE_LOC_X = 130;
var SCORE_LOC_Y = 475;
var SCORETEXT_LOC_X = 70;
var SCORETEXT_LOC_Y = 478;
var SCORE_TEXT_CONTENT = "score:";
//Factors for the ray xyz-values. Used in initStatusScene()
var RAY_FACTOR_X = -5;
var RAY_FACTOR_Y = 5;
var RAY_FACTOR_Z = -5;
//Start and end message constants
var GAME_OVER_TEXT = "Game over!";
var START_GAME_TEXT = "Press 'enter' to start!";
var START_OFFSET_X = 0;
var START_OFFSET_Y = 0;
var START_OFFSET_Z = -5;
var END_OFFSET_X = 0;
var END_OFFSET_Y = 0;
var END_OFFSET_Z = -5;
var DEFAULT_FOG_COLOR = "#3F3F3F";
var EFFECT_FOG_COLOR = "#DCFCCC";
var SCORE_TEXT_COLOR = "#D0F0C0";
var SCORE_TEXT_SIZE = 10;
var STATE_TEXT_COLOR = "#D0F0C0";//"#ffdd00";
var STATE_TEXT_SIZE = 17;
var calculateSize = function(side1, side2){
if(side2 == side1){
return 0;
}
else if(side2 < 0.0 && side1 >= 0.0){
return(Math.abs(side2) + side1);
}
else if(side1 < 0.0 && side2 >= 0.0){
return(Math.abs(side1) + side2);
}
else if(side1 >= 0.0 && side2 >= 0.0 && side1 > side2){
return(side1-side2);
}
else if(side1 >= 0.0 && side2 >= 0.0 && side2 > side1){
return(side2-side1);
}
else if(side1 < 0.0 && side2 < 0.0 && Math.abs(side1) > Math.abs(side2)){
return(Math.abs(side1)-Math.abs(side2));
}
else if(side1 < 0.0 && side2 < 0.0 && Math.abs(side2) > Math.abs(side1)){
return(Math.abs(side2)-Math.abs(side1));
}
}
|
WAF.define('WakendoColorPicker', ['waf-core/widget', 'wakendoCore'], function(widget, $) {
'use strict';
var KendoColorPicker = widget.create('WakendoColorPicker', {
value: widget.property({
type: 'string'
}),
flat: widget.property({
type: 'boolean',
defaultValue: false
}),
init: function() {
var self = this;
self.valueChangeSubscriber = self.value.onChange(function(newValue) {
self.kendoWidget.value(newValue);
});
self.flat.onChange(self.render);
self.render();
},
render: function() {
var self = this;
$(self.node).empty();
var options = {
change: function(event) {
self.valueChangeSubscriber.pause();
self.value(event.value);
self.valueChangeSubscriber.resume();
}
};
if (self.flat()) {
var $el = $(self.node);
$el.kendoFlatColorPicker(options);
self.kendoWidget = $el.data("kendoFlatColorPicker");
} else {
var $el = $('<input />').appendTo(self.node);
$el.kendoColorPicker(options);
self.kendoWidget = $el.data("kendoColorPicker");
}
},
open: function() {
this.kendoWidget.open();
},
close: function() {
this.kendoWidget.close();
},
enable: function() {
this.kendoWidget.enable();
},
disable: function() {
this.kendoWidget.enable(false);
}
});
return KendoColorPicker;
});
|
let express = require('express');
let path = require('path');
let logger = require('morgan');
let bodyParser = require('body-parser');
let index = require('./routes/index');
let semanticui = require('./routes/semanticui');
let foundation = require('./routes/foundation');
let test = require('./routes/test-post');
let helmet = require('helmet');
let resourceMonitorMiddleware = require('express-watcher').resourceMonitorMiddleware;
let app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(resourceMonitorMiddleware);
app.use(helmet());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname + '/public')));
app.use(express.static(path.join(__dirname + '/dist')));
app.use('/', index);
app.use('/semanticui', semanticui);
app.use('/foundation', foundation);
app.post('/test', function (req, res) {
console.log('REQ.BODY: ' + req.body);
res.send('click click');
});
// catch 404 and forward to error handler
app.use(function(req, res, next) {
console.log(res.statusCode);
next(res.error);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
|
import { emit } from "../../api";
import { setActiveRoom } from "../room/roomSlice.js";
export function presentChanged(present) {
return { type: "localUser/present", present };
}
export const ping = () => () => emit("/user/current/ping");
export const changeActiveRoom = roomId => dispatch => {
dispatch(setActiveRoom(roomId));
return emit("/user/current/activity", { room: roomId });
};
export function changePresent(present) {
return dispatch => {
return emit("/user/current/present", { present }).then(() => dispatch(presentChanged(present)));
};
}
|
/*
* Returns Messages
*
* This contains all the text for the Returns component.
*/
import { defineMessages } from 'react-intl';
export default defineMessages({
header: {
id: 'app.components.Returns.header',
defaultMessage: 'returns',
},
returnPolicy: {
id: 'app.components.Returns.returnPolicy',
defaultMessage: 'Return Policy',
},
message: {
id: 'app.components.Returns.message',
defaultMessage: 'This item must be returned within 30 days of the ship date. See {policyLink} for details. Prices, promotions, styles and availability may vary by store and online.',
},
});
|
import React from 'react'
import '../../styles/gkm-item.scss';
import ProductItem from './ProductItem'
import Input from '../Common/Input'
import SearchBar from '../SearchBar';
import _ from 'lodash'
class EtsyProduct extends React.Component {
constructor(props, context) {
super(props, context);
this.editables = {
name: {
max: 20,
display: 'Name'
},
shortDescription: {
max: 100,
display: 'Short Description'
},
twitterTitle: {
max: 100,
display: 'Twitter Text'
}
};
}
onUpdateField(update) {
console.log(update)
let product = this.props.product
_.each(update, (v, k) => {
product[k] = v;
})
this.props.updateItem(product);
}
getListingById(id) {
return _.find(this.props.listings, (l) => l.id === id)
}
editableFieldsHtml() {
const { product } = this.props
return (
<div>
{_.map(this.editables, (v, fld) => (
<Input
title={v.display}
fld={fld}
value={product[fld]}
id={product.id}
onUpdate={
(i, update) => this.onUpdateField(update)
}
/>))
}
</div>
)
}
onAddtoCategory(category) {
const { product } = this.props;
addItemtoCategory(product, category)
}
render() {
const { product, listings, addListingToProduct } = this.props;
const loader = (<div>loading...</div >)
const productItems = product.populatedListings.map((listing) => (listing ? < ProductItem key={listing.id} product={listing} inProduct={true} /> : loader))
return (
<div className='gkm-etsy-product' id={product.id}>
<h5>Etsy Product</h5>
<div>
Product Name: {product.name}
<div>Categories:</div>
{_.map(product.hashtags.all(), (hashtag) => (<div>{hashtag}</div>))}
<Input title="add category" fld='category' resetOnClick={true} button={{ text: 'ADD!', action: this.onAddtoCategory }} />
{this.editableFieldsHtml()}
</div>
{productItems}
<div> Add another listing: </div>
<SearchBar products={listings}
onSelect={
(listingId) => {
addListingToProduct(product, this.getListingById(listingId))
}
} />
</div>
)
}
}
/*
Item.propTypes = {
};
*/
export default EtsyProduct
|
/**
* Main JS file for Jasper behaviours
*/
if (typeof jQuery == 'undefined') {
document.write('<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1.min.js"></' + 'script>');
}
(function ($) {
"use strict";
// Header Parallax and Fade
$(window).on('scroll', function() {
var scroll_top = $(this).scrollTop();
var top_offset = 600;
$('#site-head-content').css({
'opacity' : (1-scroll_top/top_offset),
'top' : (scroll_top*-.2)
});
/*
// Background Image Parallax
$('#site-head').css({
'background-position' : 'center ' + (scroll_top*-.07) + 'px'
});
*/
});
// Shameless self-promotion
console.log("Yo, fellow dev. Check out our homepage, and find out about our other goodies: http://www.farmsoftstudios.com")
}(jQuery));
|
describe('dev-radiolist', function() {
beforeEach(function() {
browser().navigateTo(mainUrl);
});
it('should show radio options and submit new value', function() {
var s = '[ng-controller="DevRadiolistCtrl"] ';
expect(element(s+'a.normal ').text()).toMatch('status1');
element(s+'a.normal ').click();
expect(element(s+'a.normal ').css('display')).toBe('none');
expect(element(s+'form[editable-form="$form"]').count()).toBe(1);
expect(element(s+'form input[type="radio"]:visible:enabled').count()).toBe(2);
expect(using(s+'label:eq(0)').input('$parent.$parent.$data').val()).toBe('true');
expect(using(s+'label:eq(1)').input('$parent.$parent.$data').val()).toBe('false');
// select status2
using(s+'label:eq(1)').input('$parent.$parent.$data').select('false');
element(s+'form button[type="submit"]').click();
expect(element(s+'a.normal ').css('display')).not().toBe('none');
expect(element(s+'a.normal ').text()).toMatch('status2');
expect(element(s+'form').count()).toBe(0);
});
it('should show radio options and call on-change event', function() {
var s = '[ng-controller="DevRadiolistCtrl"] ';
expect(element(s+'a.nobuttons ').text()).toMatch('status1');
element(s+'a.nobuttons ').click();
expect(element(s+'a.nobuttons ').css('display')).toBe('none');
expect(element(s+'form[editable-form="$form"]').count()).toBe(1);
expect(element(s+'form input[type="radio"]:visible:enabled').count()).toBe(2);
expect(element(s+'form input[type="radio"]').attr('ng-change')).toBeDefined();
expect(using(s+'label:eq(0)').input('$parent.$parent.$data').val()).toBe('true');
expect(using(s+'label:eq(1)').input('$parent.$parent.$data').val()).toBe('false');
// select status2
using(s+'label:eq(1)').input('$parent.$parent.$data').select('false');
element(s).click();
expect(element(s+'a.nobuttons ').css('display')).not().toBe('none');
expect(element(s+'a.nobuttons ').text()).toMatch('status1');
expect(element(s+'form').count()).toBe(0);
});
});
|
import React from 'react';
import styles from './App.less';
import withContext from '../../decorators/withContext';
import withStyles from '../../decorators/withStyles';
import Rankinglist from '../Rankinglist/Rankinglist';
@withContext
@withStyles(styles)
class App {
render() {
return (
<div id="app">
<div className="panel panel-primary">
<div className="panel-heading">
<h3 className="panel-title">Norges Tour</h3>
</div>
<div id="main-wrapper">
<nav className="sidebar-left" id="left-menu">
<ul className="nav nav-pills nav-stacked">
<li role="presentation" className="active"><a href="#">
<span className="glyphicon glyphicon-stats" aria-hidden="true"></span> Rankinglister</a>
</li>
<li role="presentation" className="disabled"><a href="#">
<span className="glyphicon glyphicon-bullhorn" aria-hidden="true"></span> Resultater</a>
</li>
<li role="presentation" className="disabled"><a href="#">
<span className="glyphicon glyphicon-align-justify" aria-hidden="true"></span> Turneringer</a>
</li>
</ul>
</nav>
<main>
<Rankinglist />
</main>
</div>
</div>
</div>
);
}
}
export default App;
|
/**
* tiny-di
* @module binding/lazy
* @copyright Dennis Saenger <tiny-di-15@mail.ds82.de>
*/
'use strict';
import { AbstractBinding } from './abstract';
export class LazyBinding extends AbstractBinding {
constructor(injector, key, path, opts) {
super(injector, key);
this.path = path;
this.opts = opts;
}
load() {
return this.injector.load(this.key, this.path, this.opts);
}
$get() {
return this.load();
}
}
|
const mtype = require('@lib/mediatype');
const model = require('@lib/model');
const fs = require('fs');
const mcdir = require('@lib/mcdir');
module.exports = function(r) {
const db = require('../db')(r);
async function addFileToDirectoryInProject(fileToUpload, directoryId, projectId, userId) {
let fileEntry = {
// Create the id for the file being uploaded as this will determine
// the location of the uploaded file in our object store.
id: await r.uuid(),
name: fileToUpload.name,
checksum: fileToUpload.hash,
mediatype: mtype.mediaTypeDescriptionsFromMime(fileToUpload.type),
size: fileToUpload.size,
path: fileToUpload.path,
owner: userId,
parentId: '',
};
let file = await getFileByNameInDirectory(fileToUpload.name, directoryId);
if (!file) {
// There is no existing file with this name in the directory.
fileEntry.usesid = await findMatchingFileIdByChecksum(fileEntry.checksum);
return await loadNewFileIntoDirectory(fileEntry, directoryId, projectId);
} else if (file.checksum !== fileEntry.checksum) {
// There is an existing file in the directory but it has a different
// checksum, so we have to do a little book keeping to make this file
// the current file, set its parent entry back to the existing, as well
// as do the usual steps for uploading a file into the object store.
fileEntry.usesid = await findMatchingFileIdByChecksum(fileEntry.checksum);
return await loadExistingFileIntoDirectory(file, fileEntry, directoryId, projectId);
} else {
// If we are here then there is a file with the same name in the directory
// and it has the same checksum. In that case there is nothing to load
// into the database as the user is attempting to upload an existing
// file (name and checksum match the existing file).
removeFile(fileEntry.path);
return file;
}
}
// getFileByNameInDirectory will return the current file in the directory
// that matches the filename. This is used to construct multiple versions
// of a file, with only one version being the current one.
async function getFileByNameInDirectory(fileName, directoryId) {
let file = await r.table('datadir2datafile').getAll(directoryId, {index: 'datadir_id'})
.eqJoin('datafile_id', r.table('datafiles')).zip()
.filter({name: fileName, current: true});
if (file) {
return file[0]; // query returns an array of 1 entry.
}
return null;
}
async function loadNewFileIntoDirectory(fileEntry, directoryId, projectId) {
await addToObjectStore(fileEntry);
return await createFile(fileEntry, directoryId, projectId);
}
async function loadExistingFileIntoDirectory(parent, fileEntry, directoryId, projectId) {
await addToObjectStore(fileEntry);
fileEntry.parentId = parent.id;
let created = await createFile(fileEntry, directoryId, projectId);
// Parent is no longer the current file
await r.table('datafiles').get(parent.id).update({current: false});
return created;
}
async function addToObjectStore(fileEntry) {
if (fileEntry.usesid === '') {
// This is a brand new file so move into the object store.
await mcdir.moveIntoStore(fileEntry.path, fileEntry.id);
} else {
// There is already a file in the store with the same checksum
// so delete uploaded file.
removeFile(fileEntry.path);
}
}
// findMatchingFileIdByChecksum will return the id of the file that
// was uploaded with the name checksum or "" if there is no match.
async function findMatchingFileIdByChecksum(checksum) {
let matching = await r.table('datafiles').getAll(checksum, {index: 'checksum'});
if (matching.length) {
// Multiple entries have been found that have the same checksum. In the database
// a file has a usesid which points to the original entry that was first uploaded
// with the matching checksum. So, we take the first entry in the list, it is
// either this original upload, or a file with a usesid that points to the original
// upload. We can determine this by checking if usesid === "". If it is return the
// id, otherwise return the usesid.
return matching[0].usesid === '' ? matching[0].id : matching[0].usesid;
}
// If we are here then there was no match found, so just return "" to signify no match.
return '';
}
function removeFile(path) {
try {
fs.unlinkSync(path);
} catch (e) {
return false;
}
}
async function createFile(fileEntry, directoryId, projectId) {
let file = new model.DataFile(fileEntry.name, fileEntry.owner);
file.mediatype = fileEntry.mediatype;
file.size = fileEntry.size;
file.uploaded = file.size;
file.checksum = fileEntry.checksum;
file.usesid = fileEntry.usesid;
file.id = fileEntry.id;
file.parent = fileEntry.parentId ? fileEntry.parentId : '';
let created = await db.insert('datafiles', file);
await addFileToDirectory(created.id, directoryId);
await addFileToProject(created.id, projectId);
return created;
}
async function addFileToDirectory(fileId, directoryId) {
const dd2df = new model.DataDir2DataFile(directoryId, fileId);
await r.table('datadir2datafile').insert(dd2df);
}
async function addFileToProject(fileId, projectId) {
let p2df = new model.Project2DataFile(projectId, fileId);
await r.table('project2datafile').insert(p2df);
}
return {
addFileToDirectoryInProject,
createFile,
};
};
|
'use strict';
import ResponseHandler from './response-handler';
import retrieve from './retrieve';
class ResultList {
constructor(search, options, onSuccess, onFailure) {
this._search = search;
this._options = options;
this._onSuccess = onSuccess;
this._onFailure = onFailure;
this._requestPromises = [];
// first call of next will increment to desired page
this._options.page -= 1;
}
next() {
const nextPage = this._options.page += 1;
if (this._requestPromises[nextPage]) {
return this._requestPromises[nextPage];
}
return this._get();
}
previous() {
if (this._options.page <= 1) {
throw new Error('There is no previous page');
}
const previousPage = this._options.page -= 1;
if (this._requestPromises[previousPage]) {
return this._requestPromises[previousPage];
}
return this._get();
}
_get() {
const page = this._options.page;
const perPage = this._options.per_page;
const promise = retrieve(this._search, this._options)
.then(this._success(page, perPage))
.catch(this._failure(page, perPage));
this._requestPromises[page] = promise;
return promise;
}
_success(page, perPage) {
return res => {
const resHndlr = new ResponseHandler(res, page, perPage, this._onSuccess);
return resHndlr.success();
};
}
_failure(page, perPage) {
return res => {
const resHndlr = new ResponseHandler(res, page, perPage, this._onFailure);
return resHndlr.failure();
};
}
}
export default ResultList;
|
// ==UserScript==
// @name GitHub Label Manager
// @namespace http://github.com/senritsu
// @version 0.1
// @description Enables importing/exporting of repository labels
// @author senritsu
// @require https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.6.15/browser-polyfill.min.js
// @require https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.6.15/browser.min.js
// @match http*://github.com/*/*/labels*
// ==/UserScript==
/* jshint ignore:start */
var inline_src = (<><![CDATA[
/* jshint ignore:end */
/* jshint esnext: true */
/* jshint asi:true */
const find = (selector, context) => (context || document).querySelector(selector)
const findAll = (selector, context) => (context || document).querySelectorAll(selector)
const newLabelButton = find('.labels-list .subnav button.js-details-target')
const importButton = document.createElement('button')
importButton.id = 'import-labels'
importButton.classList.add('btn', 'btn-default', 'right', 'select-menu-button')
importButton.textContent = 'Import '
const exportButton = document.createElement('button')
importButton.id = 'export-labels'
exportButton.classList.add('btn', 'btn-default', 'right')
exportButton.textContent = 'Export'
const author = find('span.author a').textContent
const repository = find('.repohead-details-container strong[itemprop=name] a').textContent
const exportLink = document.createElement('a')
exportLink.style.display = 'none'
exportLink.download = `${author}-${repository}-labels.json`
exportButton.appendChild(exportLink)
const newLabelForm = find('form.new-label')
const importForm = document.createElement('form')
importForm.id = 'label-import-toolbar'
importForm.classList.add('form')
importForm.style.padding = '10px'
importForm.style.marginBottom = '15px'
importForm.style.backgroundColor = '#fafafa'
importForm.style.border = '1px solid #e5e5e5'
importForm.style.display = 'none'
const importInput = document.createElement('input')
importInput.id = 'label-import-file'
importInput.classList.add('form-control', 'right')
importInput.type = 'file'
importForm.appendChild(importInput)
const clearAllDiv = document.createElement('div')
clearAllDiv.classList.add('checkbox', 'right')
clearAllDiv.style.marginTop = '9px'
clearAllDiv.style.marginRight = '15px'
importForm.appendChild(clearAllDiv)
const clearAllLabel = document.createElement('label')
clearAllDiv.appendChild(clearAllLabel)
const clearAllCheckbox = document.createElement('input')
clearAllCheckbox.id = 'clear-labels-before-import'
clearAllCheckbox.type = 'checkbox'
clearAllLabel.appendChild(clearAllCheckbox)
clearAllLabel.appendChild(document.createTextNode(' Clear all existing labels first'))
const clearfix = document.createElement('div')
clearfix.classList.add('clearfix')
importForm.appendChild(clearfix)
console.log($)
if(newLabelButton) {
setup()
}
function setup() {
const parent = newLabelButton.parentNode
parent.insertBefore(importButton, newLabelButton)
parent.insertBefore(exportButton, newLabelButton)
newLabelForm.parentNode.insertBefore(importForm, newLabelForm)
let open = false
importButton.addEventListener('click', (event) => {
open = !open
importForm.style.display = open ? 'block' : 'none'
})
importInput.addEventListener('change', (event) => {
const reader = new FileReader()
reader.onload = (event) => {
const labels = JSON.parse(reader.result)
if(clearAllCheckbox.checked) {
deleteAllLabels()
}
for(const label of labels) {
addLabel(label)
}
}
reader.readAsText(importInput.files[0])
})
exportButton.addEventListener('click', exportLabels)
}
function rgb2hex(rgb) {
const [_, r, g, b] = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/)
const hex = (x) => ("0" + parseInt(x).toString(16)).slice(-2)
return "#" + hex(r) + hex(g) + hex(b)
}
function exportLabels() {
const labels = Array.from(findAll('.labels-list-item .label-link'))
.map((label) => ({
name: find('.label-name', label).textContent,
color: rgb2hex(label.style.backgroundColor)
}))
const data = 'data:text/json;charset=utf8,' + encodeURIComponent(JSON.stringify(labels, null, 2));
exportLink.href = data
exportLink.click()
}
function findLabel(label) {
return Array.from(findAll('.labels-list-item'))
.filter((x) => find('.label-name', x).textContent === label.name)[0]
}
function updateLabel(label, element) {
find('.js-edit-label', element).click()
find('.label-edit-name', element).value = label.name
find('.color-editor-input', element).value = label.color
find('.new-label-actions .btn-primary', element).click()
}
function addLabel(label) {
find('input.label-edit-name', newLabelForm).value = label.name
find('input#edit-label-color-new', newLabelForm).value = label.color
find('button[type=submit]', newLabelForm).click()
}
function deleteLabel(element) {
find('.labels-list-actions button.js-details-target', element).click()
find('.label-delete button[type=submit]', element).click()
}
function deleteAllLabels() {
const labels = Array.from(findAll('.labels-list-item'))
for(const label of labels) {
deleteLabel(label)
}
}
/* jshint ignore:start */
]]></>).toString();
var c = babel.transform(inline_src);
eval(c.code);
/* jshint ignore:end */
|
// moment.js locale configuration
// locale : german (de)
// author : lluchs : https://github.com/lluchs
// author: Menelion Elensúle: https://github.com/Oire
(function (factory) {
if (typeof define === 'function' && define.amd) {
define(['moment'], factory); // AMD
} else if (typeof exports === 'object') {
module.exports = factory(require('../moment')); // Node
} else {
factory(window.moment); // Browser global
}
}(function (moment) {
function processRelativeTime(number, withoutSuffix, key, isFuture) {
var format = {
'm': ['eine Minute', 'einer Minute'],
'h': ['eine Stunde', 'einer Stunde'],
'd': ['ein Tag', 'einem Tag'],
'dd': [number + ' Tage', number + ' Tagen'],
'M': ['ein Monat', 'einem Monat'],
'MM': [number + ' Monate', number + ' Monaten'],
'y': ['ein Jahr', 'einem Jahr'],
'yy': [number + ' Jahre', number + ' Jahren']
};
return withoutSuffix ? format[key][0] : format[key][1];
}
return moment.defineLocale('de', {
months : 'Januar_Februar_März_April_Mai_Juni_Juli_August_September_Oktober_November_Dezember'.split('_'),
monthsShort : 'Jan._Febr._Mrz._Apr._Mai_Jun._Jul._Aug._Sept._Okt._Nov._Dez.'.split('_'),
weekdays : 'Sonntag_Montag_Dienstag_Mittwoch_Donnerstag_Freitag_Samstag'.split('_'),
weekdaysShort : 'So._Mo._Di._Mi._Do._Fr._Sa.'.split('_'),
weekdaysMin : 'So_Mo_Di_Mi_Do_Fr_Sa'.split('_'),
longDateFormat : {
LT: 'HH:mm [Uhr]',
L : 'DD.MM.YYYY',
LL : 'D. MMMM YYYY',
LLL : 'D. MMMM YYYY LT',
LLLL : 'dddd, D. MMMM YYYY LT'
},
calendar : {
sameDay: '[Heute um] LT',
sameElse: 'L',
nextDay: '[Morgen um] LT',
nextWeek: 'dddd [um] LT',
lastDay: '[Gestern um] LT',
lastWeek: '[letzten] dddd [um] LT'
},
relativeTime : {
future : 'in %s',
past : 'vor %s',
s : 'ein paar Sekunden',
m : processRelativeTime,
mm : '%d Minuten',
h : processRelativeTime,
hh : '%d Stunden',
d : processRelativeTime,
dd : processRelativeTime,
M : processRelativeTime,
MM : processRelativeTime,
y : processRelativeTime,
yy : processRelativeTime
},
ordinalParse: /\d{1,2}\./,
ordinal : '%d.',
week : {
dow : 1, // Monday is the first day of the week.
doy : 4 // The week that contains Jan 4th is the first week of the year.
}
});
}));
|
//!Defines two helper functions.
/*
* c
* https://github.com/rumpl/c
*
* Copyright (c) 2012 Djordje Lukic
* Licensed under the MIT license.
*/
"use strict";
const helpers = module.exports;
const colors = require("colors/safe"); //Despite looking unused, is not unused.
const fs = require("fs");
const SPACING = 1; //Change this value if you want more or less space between file names and comments.
const PADDING = " "; //Change this value for what character should present your padding.
/**Prints a coloured node name, padding, and it's assigned comment.
* @param {string} nodeName The name of the node.
* @param {string} nodeComment The comment for the node.
* @param {number} maxLine The length of the longest node name in the specified directory.
* @param {string} dir the relative filepath to a directory, the contents of which will be listed.
*/
function print(nodeName, nodeComment, maxLine, dir) {
nodeComment = nodeComment || "";
nodeComment = nodeComment.replace(/(\r\n|\n|\r)/gm, " "); //Removes any new lines with blank spaces.
let pad;
//The amount of spacing & the colouring changes depending on whether 'file' is a file or a directory.
if (fs.statSync(dir + "/" + nodeName).isFile()) {
pad = PADDING.repeat(maxLine - nodeName.length + 1 + SPACING);
console.log(
// @ts-ignore - TS compiler throws an unnecessary error.
colors.brightGreen(nodeName) + pad + colors.yellow(nodeComment)
);
} else {
pad = PADDING.repeat(maxLine - nodeName.length + SPACING);
console.log(
// @ts-ignore - TS compiler throws an unnecessary error.
colors.brightCyan(nodeName + "/") + pad + colors.yellow(nodeComment)
);
}
}
//TODO: refactor printFileComments & printOnlyComments into one function - they're almost identical for the most part
/**Prints all of the files and sub-directories of a specified directory, as well as their assigned comments.
* @param {Array<string>} files An array of all of the file names in the specified directory.
* @param {Array<string>} comments An array of all of the comments in the specified directory.
* @param {string} dir the relative filepath to a directory, the content of which will be listed.
*/
helpers.printFileComments = function (files, comments, dir) {
//Gets the length of the longest filename in the array - iterators through files.
const maxLine = maxLength(files);
//Prints the current file and it's comment
print(".", comments["."], maxLine, dir);
print("..", comments[".."], maxLine, dir);
//For each file run the print function.
files.forEach(function (file) {
print(file, comments[file], maxLine, dir);
});
};
/**Prints only the files and sub-directories of a specified directory which have comments, as well as their assigned comments.
* @param {Array<string>} filesNames An array of all of the file names in the specified directory.
* @param {Array<string>} comments An array of all of the comments in the specified directory.
* @param {string} relativePathToTarget the relative filepath to a directory, the content of which will be listed.
*/
helpers.printOnlyComments = function (
filesNames,
comments,
relativePathToTarget
) {
//Gets the length of the longest filename in the array - iterators through files.
const maxLine = maxLength(filesNames);
//Prints the current file and it's comment
if (comments["."]) print(".", comments["."], maxLine, relativePathToTarget);
if (comments[".."])
print("..", comments[".."], maxLine, relativePathToTarget);
//For each file with a comment, run the print function.
filesNames.forEach(function (file) {
if (comments[file])
print(file, comments[file], maxLine, relativePathToTarget);
});
};
/**Calculates the longest file name from all the returned files.
* @param {Array<string>} files an array of all the file names in the specified directory.
* @returns {number} Returns the length of the longest name in the array.
*/
function maxLength(files) {
return files.reduce((a, b) => {
return b.length > a ? b.length : a;
}, 0);
}
|
/**
* shuji (周氏)
* https://github.com/paazmaya/shuji
*
* Reverse engineering JavaScript and CSS sources from sourcemaps
*
* Copyright (c) Juga Paazmaya <paazmaya@yahoo.com> (https://paazmaya.fi)
* Licensed under the MIT license
*/
const fs = require('fs'),
path = require('path');
const MATCH_MAP = /\.map$/iu;
const MATCH_CODE = /\.(js|css)$/iu;
const FIND_SOURCE_FILE = /\/\/#\s*sourceMappingURL=([.\w]+map)/iu;
const FIND_SOURCE_BASE64 = /\/\*?\/?#\s*sourceMappingURL=([.\w\-/=;:]*)base64,([\w]+=)/iu;
const FIND_SOURCE_UENC = /\/\*?\/?#\s*sourceMappingURL=([.\w\-/=;:]+),([;:,.\-\w%]+)/iu;
/**
* Find the sourceMap and return its contents.
* In case the given filepath is already the sourceMap file, not much is done.
* In case the given filepath is a JavaScript file, then the matching sourceMap
* is being search for.
*
* @param {string} filepath
* @param {object} options Options object. If not defined, verbose=false
* @param {boolean} options.verbose Shall there be more output
*
* @returns {string|boolean} soureMap contents or false when not found
*/
const findMap = (filepath, options) => {
options = options || {
verbose: false
};
const input = fs.readFileSync(filepath, 'utf8');
if (filepath.match(MATCH_MAP)) {
return input;
}
else if (filepath.match(MATCH_CODE)) {
if (input.match(FIND_SOURCE_BASE64)) {
const sourceMappingMatch = FIND_SOURCE_BASE64.exec(input);
if (sourceMappingMatch && sourceMappingMatch.length > 2) {
if (options.verbose) {
console.log(`Input file "${filepath}" contains Base64 of ${sourceMappingMatch[2].length} length`);
}
const buf = Buffer.from(sourceMappingMatch[2], 'base64');
return buf.toString('utf8');
}
}
else if (input.match(FIND_SOURCE_UENC)) {
const sourceMappingMatch = FIND_SOURCE_UENC.exec(input);
if (sourceMappingMatch && sourceMappingMatch.length > 2) {
if (options.verbose) {
console.log(`Input file "${filepath}" contains URL encoded of ${sourceMappingMatch[2].length} length`);
}
const buf = Buffer.from(sourceMappingMatch[2], 'ascii');
return buf.toString('utf8');
}
}
else if (input.match(FIND_SOURCE_FILE)) {
const sourceMappingMatch = FIND_SOURCE_FILE.exec(input);
if (sourceMappingMatch && sourceMappingMatch.length > 1) {
if (options.verbose) {
console.log(`Input file "${filepath}" points to "${sourceMappingMatch[1]}"`);
}
}
// Since the sourceMappingURL is relative, try to find it from the same folder
const mapFile = path.join(path.dirname(filepath), sourceMappingMatch[1]);
try {
fs.accessSync(mapFile);
}
catch (error) {
console.error(`Could not access "${mapFile}"`);
console.error(error.message);
return false;
}
return fs.readFileSync(mapFile, 'utf8');
}
}
else if (options.verbose) {
console.error(`Input file "${filepath}" was not a map nor a code file`);
}
return false;
};
module.exports = findMap;
|
var Vue = require('vue')
function fixFilters() {
// 动态 filter
Vue.filter('apply', function(value, name) {
var filter = this.$options.filters[name] || Vue.options.filters[name]
var args = [value].concat(
[].slice.call(arguments, 2)
)
if (filter) return filter.apply(this, args)
return value
})
}
module.exports = fixFilters
|
/*******************************
Release Config
*******************************/
var
requireDotFile = require('require-dot-file'),
config,
npmPackage,
version
;
/*******************************
Derived Values
*******************************/
try {
config = requireDotFile('pegaMultiselect.json');
}
catch(error) {}
try {
npmPackage = require('../../../package.json');
}
catch(error) {
// generate fake package
npmPackage = {
name: 'Unknown',
version: 'x.x'
};
}
// looks for version in config or package.json (whichever is available)
version = (npmPackage && npmPackage.version !== undefined && npmPackage.name == 'Multiselect-Pega')
? npmPackage.version
: config.version
;
/*******************************
Export
*******************************/
module.exports = {
title : 'pegaMultiselect UI',
repository : 'https://github.com/ghoshArnab/multiselect',
url : 'https://github.com/ghoshArnab/multiselect',
banner: ''
+ ' /*' + '\n'
+ ' * # <%= title %> - <%= version %>' + '\n'
+ ' * <%= repository %>' + '\n'
+ ' * <%= url %>' + '\n'
+ ' *' + '\n'
+ ' * Copyright 2014 Contributors' + '\n'
+ ' * Released under the MIT license' + '\n'
+ ' * http://opensource.org/licenses/MIT' + '\n'
+ ' *' + '\n'
+ ' */' + '\n',
version : version
};
|
/**
* Placeholder test - checks that an attribute or the content of an
* element itself is not a placeholder (i.e. 'click here' for links).
*/
'use strict';
quail.components.placeholder = function (quail, test, Case, options) {
var resolve = function resolve(element, resolution) {
test.add(Case({
element: element,
status: resolution
}));
};
test.get('$scope').find(options.selector).each(function () {
var text = '';
if ($(this).css('display') === 'none' && !$(this).is('title')) {
resolve(this, 'inapplicable');
return;
}
if (typeof options.attribute !== 'undefined') {
if ((typeof $(this).attr(options.attribute) === 'undefined' || options.attribute === 'tabindex' && $(this).attr(options.attribute) <= 0) && !options.content) {
resolve(this, 'failed');
return;
} else {
if ($(this).attr(options.attribute) && $(this).attr(options.attribute) !== 'undefined') {
text += $(this).attr(options.attribute);
}
}
}
if (typeof options.attribute === 'undefined' || !options.attribute || options.content) {
text += $(this).text();
$(this).find('img[alt]').each(function () {
text += $(this).attr('alt');
});
}
if (typeof text === 'string' && text.length > 0) {
text = quail.cleanString(text);
var regex = /^([0-9]*)(k|kb|mb|k bytes|k byte)$/g;
var regexResults = regex.exec(text.toLowerCase());
if (regexResults && regexResults[0].length) {
resolve(this, 'failed');
} else if (options.empty && quail.isUnreadable(text)) {
resolve(this, 'failed');
} else if (quail.strings.placeholders.indexOf(text) > -1) {
resolve(this, 'failed');
}
// It passes.
else {
resolve(this, 'passed');
}
} else {
if (options.empty && typeof text !== 'number') {
resolve(this, 'failed');
}
}
});
};
|
Parse.initialize("AQxY526I5fcCPVkniY6ONnaBqU5qh1qDMqcOCORz", "y0cZ5QAGDU1SN1o1DtsQA8mHAKL3TKetrRvGwv3Y");
calculateSteps();
function calculateSteps(){
var count = 0;
var Trips = Parse.Object.extend("Trip");
var query = new Parse.Query(Trips);
query.greaterThan("StepsCompleted", 0);
query.find({
success: function(results) {
for (var i = 0; i < results.length; i++) {
var object = results[i];
var stepsTaken = object.get("StepsCompleted");
count += stepsTaken;
document.getElementById('stepsContainer').innerHTML = count.toLocaleString();
var dollarsSaved = (count / 2000) * 2.5;
document.getElementById('moneyContainer').innerHTML = dollarsSaved.toFixed(2);
var co2Emissions = count * 0.0128;
document.getElementById('co2EmissionsContainer').innerHTML = co2Emissions.toFixed(2);
}
},
error: function(error) {
console.log("Error: " + error.code + " " + error.message);
}
});
//var timer = setInterval(refresh, 3000);
}
var myVar = setInterval(function(){ refresh() }, 1000);
function refresh(){
calculateSteps();
}
|
'use strict'
// Module dependencies.
var request = require('request')
var querystring = require('querystring')
var userAgent = require('random-useragent')
// Root for all endpoints.
var _baseUrl = 'http://data.europa.eu/euodp/data/api/action'
// Infrastructure prevents requests from original user agent of requestee.
var headers = {
'User-Agent': userAgent.getRandom(),
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded'
}
/**
* Calls the service and return the data in a promise, but with POST.
* @function
* @private
* @name _sendRequest
* @param {object} options - The request set of options.
* @param {string} options.endpoint - Resource endpoint, without any slashes.
* @param {object} options.query - The query parameters for the request.
* @param {object} options.body - The body if POST, PUT
* @param {string} options.method - The method to be used.
* @returns {Promise} The response in a promise.
*/
function _sendRequest (options) {
return new Promise((resolve, reject) => {
var query = querystring.stringify(options.query)
var bodyData = JSON.stringify(options.body)
request({
url: _baseUrl + `/${options.endpoint}?${query}`,
headers: headers,
method: options.method,
body: bodyData
}, (error, response, body) => {
if (error) {
reject(error)
}
resolve(body)
})
})
}
/**
* Get a list of the datasets in JSON.
* @param {object} options - The request set of options.
* @param {number} options.query.limit - Limit the number of items returned.
* @param {number} options.query.offset - Acts like pagination when limited results.
*/
module.exports.getDatasets = (options) => {
return _sendRequest({
method: 'GET',
endpoint: 'package_list',
query: (options !== undefined ? options.query : '')
})
}
/**
* Return a list of the site's tags.
* @param {object} options - The request set of options.
* @param {object} options.query - The query parameters.
* @param {string} options.query.vocabulary_id - The id or name of a vocabulary.
* If given only tags that belong to this vocabulary will be returned.
* @param {boolean} options.query.all_fields - Whether to include all fields.
*/
module.exports.getTags = (options) => {
return _sendRequest({
method: 'GET',
endpoint: 'tag_list',
query: (options !== undefined ? options.query : '')
})
}
/**
* Return a list of the site's tags.
* @param {object} options - The request set of options.
* @param {object} options.query - The query parameters.
* @param {string} options.body.id - The id of the data set.
* For example: {"id": "dgt-translation-memory"}
*/
module.exports.getDataset = (options) => {
return _sendRequest({
method: 'POST',
endpoint: 'package_show',
query: (options !== undefined ? options.query : ''),
body: (options !== undefined ? options.body : {})
})
}
/**
* Searches for packages satisfying a given search criteria.
* This action accepts solr search query parameters.
* @see http://wiki.apache.org/solr/CommonQueryParameters
* @param {object} options - The request set of options.
* @param {object} options.query - The query parameters.
* @param {object} options.body - The body parameter.
* This accepts the solr tags to filter results.
*/
module.exports.datasetSearch = (options) => {
return _sendRequest({
method: 'POST',
endpoint: 'package_search',
query: (options !== undefined ? options.query : ''),
body: (options !== undefined ? options.body : {})
})
}
|
import logger from "./logger";
const middlewares = {
logger,
};
export default middlewares;
|
import React, {PropTypes} from 'react';
import Anchor from './Anchor';
import getIdFromTitle from '../util/getIdFromTitle';
const Title = ({children}) => (
<h3>
<Anchor id={getIdFromTitle(children)}>
{children}
</Anchor>
</h3>
);
Title.propTypes = {
children: PropTypes.string.isRequired,
};
export default Title;
|
import Component from '@ember/component';
export default Component.extend({
domains: null
});
|
import React from 'react';
import { Wrapper } from '../components';
const Container = () => <Wrapper>Journal Container</Wrapper>;
export default Container;
|
/**
*
* Secure Hash Algorithm (SHA1)
* http://www.webtoolkit.info/
*
**/
export function SHA1(msg) {
function rotate_left(n, s) {
var t4 = (n << s) | (n >>> (32 - s));
return t4;
};
function lsb_hex(val) {
var str = "";
var i;
var vh;
var vl;
for (i = 0; i <= 6; i += 2) {
vh = (val >>> (i * 4 + 4)) & 0x0f;
vl = (val >>> (i * 4)) & 0x0f;
str += vh.toString(16) + vl.toString(16);
}
return str;
};
function cvt_hex(val) {
var str = "";
var i;
var v;
for (i = 7; i >= 0; i--) {
v = (val >>> (i * 4)) & 0x0f;
str += v.toString(16);
}
return str;
};
function Utf8Encode(string) {
string = string.replace(/\r\n/g, "\n");
var utftext = "";
for (var n = 0; n < string.length; n++) {
var c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
} else if ((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
} else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
};
var blockstart;
var i, j;
var W = new Array(80);
var H0 = 0x67452301;
var H1 = 0xEFCDAB89;
var H2 = 0x98BADCFE;
var H3 = 0x10325476;
var H4 = 0xC3D2E1F0;
var A, B, C, D, E;
var temp;
msg = Utf8Encode(msg);
var msg_len = msg.length;
var word_array = new Array();
for (i = 0; i < msg_len - 3; i += 4) {
j = msg.charCodeAt(i) << 24 | msg.charCodeAt(i + 1) << 16 |
msg.charCodeAt(i + 2) << 8 | msg.charCodeAt(i + 3);
word_array.push(j);
}
switch (msg_len % 4) {
case 0:
i = 0x080000000;
break;
case 1:
i = msg.charCodeAt(msg_len - 1) << 24 | 0x0800000;
break;
case 2:
i = msg.charCodeAt(msg_len - 2) << 24 | msg.charCodeAt(msg_len - 1) << 16 | 0x08000;
break;
case 3:
i = msg.charCodeAt(msg_len - 3) << 24 | msg.charCodeAt(msg_len - 2) << 16 | msg.charCodeAt(msg_len - 1) << 8 | 0x80;
break;
}
word_array.push(i);
while ((word_array.length % 16) != 14) word_array.push(0);
word_array.push(msg_len >>> 29);
word_array.push((msg_len << 3) & 0x0ffffffff);
for (blockstart = 0; blockstart < word_array.length; blockstart += 16) {
for (i = 0; i < 16; i++) W[i] = word_array[blockstart + i];
for (i = 16; i <= 79; i++) W[i] = rotate_left(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1);
A = H0;
B = H1;
C = H2;
D = H3;
E = H4;
for (i = 0; i <= 19; i++) {
temp = (rotate_left(A, 5) + ((B & C) | (~B & D)) + E + W[i] + 0x5A827999) & 0x0ffffffff;
E = D;
D = C;
C = rotate_left(B, 30);
B = A;
A = temp;
}
for (i = 20; i <= 39; i++) {
temp = (rotate_left(A, 5) + (B ^ C ^ D) + E + W[i] + 0x6ED9EBA1) & 0x0ffffffff;
E = D;
D = C;
C = rotate_left(B, 30);
B = A;
A = temp;
}
for (i = 40; i <= 59; i++) {
temp = (rotate_left(A, 5) + ((B & C) | (B & D) | (C & D)) + E + W[i] + 0x8F1BBCDC) & 0x0ffffffff;
E = D;
D = C;
C = rotate_left(B, 30);
B = A;
A = temp;
}
for (i = 60; i <= 79; i++) {
temp = (rotate_left(A, 5) + (B ^ C ^ D) + E + W[i] + 0xCA62C1D6) & 0x0ffffffff;
E = D;
D = C;
C = rotate_left(B, 30);
B = A;
A = temp;
}
H0 = (H0 + A) & 0x0ffffffff;
H1 = (H1 + B) & 0x0ffffffff;
H2 = (H2 + C) & 0x0ffffffff;
H3 = (H3 + D) & 0x0ffffffff;
H4 = (H4 + E) & 0x0ffffffff;
}
var temp = cvt_hex(H0) + cvt_hex(H1) + cvt_hex(H2) + cvt_hex(H3) + cvt_hex(H4);
return temp.toLowerCase();
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.