text
stringlengths 2
6.14k
|
|---|
/**!
*
* Copyright (c) 2015-2017 Cisco Systems, Inc. See LICENSE file.
*/
/* eslint-disable */
'use strict';
var path = require('path');
module.exports = function configGrunt(grunt, p) {
grunt.registerTask('test', []);
};
|
"use strict";
const util = require("util");
const colors = require("colors");
const consoleLog = console.log;
const consoleWarn = console.warn;
const consoleError = console.error;
const EError = require("../eerror");
function padd(str, length = process.stdout.columns) {
return str + " ".repeat(length - str.length % length);
}
/**
* Terminal output formatter that makes output colorful and organized.
*/
const Formatter = module.exports = {
/**
* Adds tabs to the given text.
*
* @param {string} str
* The text to tab.
* @param {number} x
* Amount of tabs to add.
*
* @returns {string}
* Tabbed text.
*/
tab(str = "", x = 1) {
let tab = " ".repeat(x);
let cols = process.stdout.columns - tab.length;
let match = str.match(new RegExp(`.{1,${cols}}|\n`, "g"));
str = match ? match.join(tab) : str;
return tab + str;
},
/**
* Formats given text into a heading.
*
* @param {string} str
* The heading text.
* @param {string} marker
* Heading character.
* @param {string} color2
* The color of the heading.
*/
heading(str, marker = "»".blue, color2 = "cyan") {
consoleLog();
consoleLog(marker + " " + str.toUpperCase()[color2]);
consoleLog(" " + "¨".repeat(process.stdout.columns - 3)[color2]);
},
/**
* Prints given items in list format.
*
* @param {Array|Object|string} items
* The items to print.
* @param {number} inset
* The tabbing.
* @param {string} color
* Color of the item text.
*/
list(items, inset = 0, color = "green") {
const insetTab = " ".repeat(inset) + "• "[color];
if (Array.isArray(items)) {
items.forEach((item) => {
consoleLog(this.tab(item).replace(/ /, insetTab));
});
}
else if (typeof items === "object") {
for (let [key, text] of Object.entries(items)) {
consoleLog(insetTab + key[color]);
if (typeof text !== "string") {
this.list(text, (inset || 0) + 1, color);
}
else {
consoleLog(this.tab(text, inset + 2));
}
}
}
else if (typeof items === "string") {
consoleLog(insetTab + items);
}
},
/**
* Prints formatted errors.
*
* @param {Error|string} error
* The error to print.
*/
error(error) {
consoleLog();
// Handling extended errors which provided in better format error data.
if (error instanceof EError) {
consoleLog();
consoleLog("!! ERROR ".red + "& STACK".yellow);
consoleLog(" ¨¨¨¨¨¨ ".red + "¨".yellow.repeat(process.stdout.columns - " ¨¨¨¨¨¨ ".length) + "\n");
let messageNum = 0;
error.getStackedErrors().forEach((error) => {
error.messages.forEach((message, i) => {
console.log((i === 0 ? (" #" + (++messageNum)).red : " ") + " " + message)
});
error.stacks.forEach((stack) => console.log(" • ".yellow + stack.gray));
console.log();
});
return;
}
// Handling for default errors.
Formatter.heading("ERROR", "!!".red, "red");
if (!(error instanceof Error)) {
return consoleError(error);
}
let firstBreak = error.message.indexOf("\n");
if (firstBreak === -1) {
firstBreak = error.message.length;
}
let errorBody = error.message.substr(firstBreak).replace(/\n(.)/g, "\n • ".red + "$1");
consoleError(error.message.substr(0, firstBreak));
consoleError(errorBody);
Formatter.heading("STACK TRACE", ">>".yellow, "yellow");
consoleError(error.stack.substr(error.stack.indexOf(" at ")).replace(/ /g, " • ".yellow));
},
/**
* Prints formatted warning.
*
* @param {string} str
* Warning text.
*/
warn(str) {
Formatter.heading("WARNING", "!".yellow, "yellow");
consoleWarn(str);
},
/**
* Registers listeners for formatting text from recognized tags.
*/
infect() {
console.log = function(str, ...args) {
str = str || "";
if (typeof str === "string") {
if (args) {
str = util.format(str, ...args);
}
const headingMatch = str.match(/.{2}/);
if (str.length > 2 && headingMatch[0] === "--") {
Formatter.heading(str.substr(headingMatch.index + 2));
return;
}
}
consoleLog(str);
};
console.error = function(str, ...args) {
str = str || "";
if (typeof str === "string" && args) {
str = util.format(str, ...args);
}
Formatter.error(str);
// Used for exit codes. Errors can specify error codes.
if (str instanceof Error && Number.isInteger(str.code)) {
return str.code;
}
// If not an error object then default to 1.
return 1;
};
console.warn = function(str, ...args) {
str = str || "";
if (typeof str === "string" && args) {
str = util.format(str, ...args);
}
Formatter.warn(str);
};
},
};
|
// test/main.js
var Parser = require('../src/markdown-parser');
var parser = new Parser();
var parserOptions = new Parser();
var assert = require("assert");
describe('tests', function() {
describe('parsing', function() {
it('bold', function(done) {
parser.parse("**b** __b__", function(err, result) {
assert.equal(result.bolds.length, 2);
done();
});
});
it('code', function(done) {
parser.parse("```js \n var a; \n ```", function(err, result) {
assert.equal(result.codes.length, 1);
done();
});
});
it('headings', function(done) {
parser.parse("#header1 \n#header2", function(err, result) {
assert.equal(result.headings.length, 2);
done();
});
});
it('italics', function(done) {
parser.parse("*iiiii*\nother\n\n *iiiii*", function(err, result) {
assert.equal(result.italics.length, 2);
done();
});
});
it('list', function(done) {
parser.parse("- item1 \n- item2 \nother\n*item1\nitem2", function(err, result) {
assert.equal(result.lists[0].length, 2);
done();
});
});
it('headings', function(done) {
parser.parse("#header1 \n#header2", function(err, result) {
assert.equal(result.headings.length, 2);
done();
});
});
it('images full no options', function(done) {
parser.parse("[google](http://www.google.com)", function(err, result) {
assert.equal(result.references.length, 1);
done();
});
});
it('images full', function(done) {
parserOptions.parse("[google](http://www.google.com)", function(err, result) {
assert.equal(result.references.length, 1);
done();
});
});
it('images relative', function(done) {
parserOptions.options = {html_url: "https://github.com/darul75/markdown-parser"};
parserOptions.parse("[zoubida](./images/zoubida.png)", function(err, result) {
assert.equal(result.references.length, 1);
assert.equal(result.references[0].href, parserOptions.options.html_url+'/blob/master/images/zoubida.png');
parserOptions.options.html_url = "https://github.com/CMBJS/NodeBots";
var res = parserOptions.parse("", function(err, result) {
assert.equal(result.references.length, 1);
assert.equal(result.references[0].href, parserOptions.options.html_url+'/blob/master/poster.jpg');
done();
});
});
});
it('images relative not needed', function(done) {
parserOptions.options = {html_url: "https://github.com/darul75/markdown-parser"};
parserOptions.parse("[zoubida](http://www.google.com/images/zoubida.png)", function(err, result) {
assert.equal(result.references.length, 1);
assert.equal(result.references[0].href, 'http://www.google.com/images/zoubida.png');
done();
});
});
});
});
|
import React from "react";
import { connect } from "react-redux";
import { withRouter, Route } from "react-router";
import { Link } from "react-router-dom";
import { Entry } from "../../pages/entry";
class BlogCard extends React.Component {
render() {
return (
<div>
<h2>{this.props.title}</h2>
<p>{this.props.content}</p>
<Link to={`/blog/${this.props.slug}`}>Read more..</Link>
</div>
);
}
}
export default withRouter(BlogCard);
|
module.exports = {
stores: process.env.STORES ? process.env.STORES.split(',') : [
'elasticsearch',
'postgresql',
'leveldb'
],
postgresql: {
host: process.env.POSTGRESQL_HOST || 'localhost',
port: process.env.POSTGRESQL_PORT || '5432',
username: process.env.POSTGRESQL_USER || 'postgres',
password: process.env.POSTGRESQL_PASSWORD || 'postgres'
},
elasticsearch: {
hosts: [
process.env.ELASTICSEARCH_HOST || 'http://localhost:9200'
]
},
level: {
path: process.env.LEVEL_PATH || '/tmp/level'
},
queue: {
client: process.env.QUEUE_CLIENT || 'kue',
kue: {
port: process.env.QUEUE_KUE_PORT ? Number(process.env.QUEUE_KUE_PORT) : 3000
},
rabbitmq: {
connectionString: process.env.QUEUE_RABBITMQ_CONNECTIONSTRING
}
},
project: {
client: process.env.PROJECT_CLIENT || 'file',
file: {
path: process.env.PROJECT_FILE_PATH || '/tmp/dstore'
}
},
api: {
port: (process.env.API_PORT ? Number(process.env.API_PORT) : (process.env.PORT ? process.env.PORT : 2020))
}
};
|
import React from 'react';
import { createStore } from 'redux';
import { createBrowserHistory } from 'history';
import { expect } from 'chai';
import { shallow } from 'enzyme';
import rootReducer from '../../src/reducers';
import Routes from '../../src/Routes';
import App from '../../src/containers/App';
const configureStore = initialState => createStore(
rootReducer,
initialState,
);
describe('Container | App', () => {
it('renders Routes component', () => {
const wrapper = shallow(<App history={createBrowserHistory()} store={configureStore()}/>);
expect(wrapper.find(Routes)).to.have.lengthOf(1);
});
});
|
import appActions from './application'
import todosActions from './todos'
import filterActions from './filter'
import commentsActions from './comments'
import userActions from './user'
export {
appActions,
todosActions,
filterActions,
commentsActions,
userActions
}
export * from './application'
export * from './todos'
export * from './filter'
export * from './comments'
export * from './user'
|
function browserSupportsHtml5HistoryApi() {
return !! (history && history.replaceState && history.pushState);
}
$(document).ready(function() {
//_gaq.push(['_trackEvent', 'Citizen-Format-Smartanswer', 'Load']);
if(browserSupportsHtml5HistoryApi()) {
var formSelector = ".current form";
initializeHistory();
var getCurrentPosition = function () {
var slugArray = document.URL.split('/');
return slugArray.splice(3, slugArray.length).join('/');
};
// events
// get new questions on submit
$(formSelector).live('submit', function(event) {
$('input[type=submit]', this).attr('disabled', 'disabled');
var form = $(this);
var postData = form.serializeArray();
reloadQuestions(form.attr('action'), postData);
event.preventDefault();
return false;
});
// Track when a user clicks on 'Start again' link
$('.start-right').live('click', function() {
window._gaq && window._gaq.push(['_trackEvent', 'MS_smart_answer', getCurrentPosition(), 'Start again']);
reloadQuestions($(this).attr('href'));
return false;
});
// Track when a user clicks on a 'Change Answer' link
$('.link-right a').live('click', function() {
var href = $(this).attr('href');
window._gaq && window._gaq.push(['_trackEvent', 'MS_smart_answer', href, 'Change Answer']);
reloadQuestions(href);
return false;
});
// manage next/back by tracking popstate event
window.onpopstate = function (event) {
if(event.state !== null) {
updateContent(event.state['html_fragment']);
} else {
return false;
}
};
}
$('#current-error').focus();
// helper functions
function toJsonUrl(url) {
var parts = url.split('?');
var json_url = parts[0].replace(/\/$/, "") + ".json";
if (parts[1]) {
json_url += "?";
json_url += parts[1];
}
return window.location.protocol + "//" + window.location.host + json_url;
}
function fromJsonUrl(url) {
return url.replace(/\.json$/, "");
}
function redirectToNonAjax(url) {
window.location = url;
}
// replace all the questions currently in the page with whatever is returned for given url
function reloadQuestions(url, params) {
var url = toJsonUrl(url);
addLoading('<p class="next-step">Loading next step…</p>');
$.ajax(url, {
type: 'GET',
dataType:'json',
data: params,
timeout: 10000,
error: function(jqXHR, textStatus, errorStr) {
var paramStr = $.param(params);
redirectToNonAjax(url.replace('.json', '?' + paramStr).replace('??', '?'));
},
success: function(data, textStatus, jqXHR) {
addToHistory(data);
updateContent(data['html_fragment']);
}
});
}
// manage the URL
function addToHistory(data) {
history.pushState(data, data['title'], data['url']);
window._gaq && window._gaq.push(['_trackPageview', data['url']]);
}
// add an indicator of loading
function addLoading(fragment){
$('#content .step.current')
.addClass('loading')
.find('form .next-question')
.append(fragment);
$.event.trigger('smartanswerAnswer');
};
// update the content (i.e. plonk in the html fragment)
function updateContent(fragment){
$('.smart_answer #js-replaceable').html(fragment);
$.event.trigger('smartanswerAnswer');
if ($(".outcome").length !== 0) {
$.event.trigger('smartanswerOutcome');
}
}
function initializeHistory(data) {
if (! browserSupportsHtml5HistoryApi() && window.location.pathname.match(/\/.*\//) ) {
addToHistory({url: window.location.pathname});
}
data = {
html_fragment: $('.smart_answer #js-replaceable').html(),
title: "Question",
url: window.location.toString()
};
history.replaceState(data, data['title'], data['url']);
}
var contentPosition = {
latestQuestionTop : 0,
latestQuestionIsOffScreen: function($latestQuestion) {
var top_of_view = $(window).scrollTop();
this.latestQuestionTop = $latestQuestion.offset().top;
return (this.latestQuestionTop < top_of_view);
},
correctOffscreen: function() {
$latestQuestion = $('.smart_answer .done-questions li.done:last-child');
if (!$latestQuestion.length) {
$latestQuestion = $('body');
}
if(this.latestQuestionIsOffScreen($latestQuestion)) {
$(window).scrollTop(this.latestQuestionTop);
}
},
init: function() {
var self = this;
$(document).bind('smartanswerAnswer', function() {
self.correctOffscreen();
$('.meta-wrapper').show();
});
// Show feedback form in outcomes
$(document).bind('smartanswerOutcome', function() {
$('.report-a-problem-container form #url').val(window.location.href);
$('.meta-wrapper').show();
});
}
};
contentPosition.init();
});
|
Ext.define('CustomIcons.view.Main', {
extend: 'Ext.tab.Panel',
xtype: 'main',
requires: [
'Ext.TitleBar',
'Ext.Video'
],
config: {
tabBarPosition: 'bottom',
items: [
{
title: 'Welcome',
iconCls: 'headphones',
styleHtmlContent: true,
scrollable: true,
items: {
docked: 'top',
xtype: 'titlebar',
title: 'Welcome to Sencha Touch 2'
},
html: [
"You've just generated a new Sencha Touch 2 project. What you're looking at right now is the ",
"contents of <a target='_blank' href=\"app/view/Main.js\">app/view/Main.js</a> - edit that file ",
"and refresh to change what's rendered here."
].join("")
},
{
title: 'Get Started',
iconCls: 'facebook2',
items: [
{
docked: 'top',
xtype: 'titlebar',
title: 'Getting Started'
},
{
xtype: 'video',
url: 'http://av.vimeo.com/64284/137/87347327.mp4?token=1330978144_f9b698fea38cd408d52a2393240c896c',
posterUrl: 'http://b.vimeocdn.com/ts/261/062/261062119_640.jpg'
}
]
}
]
}
});
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _index = require('../../../_lib/setUTCDay/index.js');
var _index2 = _interopRequireDefault(_index);
var _index3 = require('../../../_lib/setUTCISODay/index.js');
var _index4 = _interopRequireDefault(_index3);
var _index5 = require('../../../_lib/setUTCISOWeek/index.js');
var _index6 = _interopRequireDefault(_index5);
var _index7 = require('../../../_lib/setUTCISOWeekYear/index.js');
var _index8 = _interopRequireDefault(_index7);
var _index9 = require('../../../_lib/startOfUTCISOWeek/index.js');
var _index10 = _interopRequireDefault(_index9);
var _index11 = require('../../../_lib/startOfUTCISOWeekYear/index.js');
var _index12 = _interopRequireDefault(_index11);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var MILLISECONDS_IN_MINUTE = 60000;
function setTimeOfDay(hours, timeOfDay) {
var isAM = timeOfDay === 0;
if (isAM) {
if (hours === 12) {
return 0;
}
} else {
if (hours !== 12) {
return 12 + hours;
}
}
return hours;
}
var units = {
twoDigitYear: {
priority: 10,
set: function set(dateValues, value) {
var century = Math.floor(dateValues.date.getUTCFullYear() / 100);
var year = century * 100 + value;
dateValues.date.setUTCFullYear(year, 0, 1);
dateValues.date.setUTCHours(0, 0, 0, 0);
return dateValues;
}
},
year: {
priority: 10,
set: function set(dateValues, value) {
dateValues.date.setUTCFullYear(value, 0, 1);
dateValues.date.setUTCHours(0, 0, 0, 0);
return dateValues;
}
},
isoYear: {
priority: 10,
set: function set(dateValues, value, options) {
dateValues.date = (0, _index12.default)((0, _index8.default)(dateValues.date, value, options), options);
return dateValues;
}
},
quarter: {
priority: 20,
set: function set(dateValues, value) {
dateValues.date.setUTCMonth((value - 1) * 3, 1);
dateValues.date.setUTCHours(0, 0, 0, 0);
return dateValues;
}
},
month: {
priority: 30,
set: function set(dateValues, value) {
dateValues.date.setUTCMonth(value, 1);
dateValues.date.setUTCHours(0, 0, 0, 0);
return dateValues;
}
},
isoWeek: {
priority: 40,
set: function set(dateValues, value, options) {
dateValues.date = (0, _index10.default)((0, _index6.default)(dateValues.date, value, options), options);
return dateValues;
}
},
dayOfWeek: {
priority: 50,
set: function set(dateValues, value, options) {
dateValues.date = (0, _index2.default)(dateValues.date, value, options);
dateValues.date.setUTCHours(0, 0, 0, 0);
return dateValues;
}
},
dayOfISOWeek: {
priority: 50,
set: function set(dateValues, value, options) {
dateValues.date = (0, _index4.default)(dateValues.date, value, options);
dateValues.date.setUTCHours(0, 0, 0, 0);
return dateValues;
}
},
dayOfMonth: {
priority: 50,
set: function set(dateValues, value) {
dateValues.date.setUTCDate(value);
dateValues.date.setUTCHours(0, 0, 0, 0);
return dateValues;
}
},
dayOfYear: {
priority: 50,
set: function set(dateValues, value) {
dateValues.date.setUTCMonth(0, value);
dateValues.date.setUTCHours(0, 0, 0, 0);
return dateValues;
}
},
timeOfDay: {
priority: 60,
set: function set(dateValues, value, options) {
dateValues.timeOfDay = value;
return dateValues;
}
},
hours: {
priority: 70,
set: function set(dateValues, value, options) {
dateValues.date.setUTCHours(value, 0, 0, 0);
return dateValues;
}
},
timeOfDayHours: {
priority: 70,
set: function set(dateValues, value, options) {
var timeOfDay = dateValues.timeOfDay;
if (timeOfDay != null) {
value = setTimeOfDay(value, timeOfDay);
}
dateValues.date.setUTCHours(value, 0, 0, 0);
return dateValues;
}
},
minutes: {
priority: 80,
set: function set(dateValues, value) {
dateValues.date.setUTCMinutes(value, 0, 0);
return dateValues;
}
},
seconds: {
priority: 90,
set: function set(dateValues, value) {
dateValues.date.setUTCSeconds(value, 0);
return dateValues;
}
},
milliseconds: {
priority: 100,
set: function set(dateValues, value) {
dateValues.date.setUTCMilliseconds(value);
return dateValues;
}
},
timezone: {
priority: 110,
set: function set(dateValues, value) {
dateValues.date = new Date(dateValues.date.getTime() - value * MILLISECONDS_IN_MINUTE);
return dateValues;
}
},
timestamp: {
priority: 120,
set: function set(dateValues, value) {
dateValues.date = new Date(value);
return dateValues;
}
}
};
exports.default = units;
module.exports = exports['default'];
|
// get params
function getParams()
{
var params = {
initial_amount: parseInt($('#initial_amount').val(), 10) || 0,
interest_rate_per_annum: parseFloat($('#interest_rate_per_annum').val()) / 100 || 0,
monthly_amount: parseFloat($('#monthly_amount').val()),
num_months: parseInt($('#num_months').val(), 10)
};
params.method = $('#by_monthly_amount').is(':checked')
? 'by_monthly_amount'
: 'by_num_months';
return params;
}
function updateUI()
{
var params = getParams();
var data = computeLoanData(params);
updatePaymentTable(data);
console.log(data);
}
function computeLoanData(params) {
var
total_paid = 0,
num_months = 0,
remainder = Math.floor(params.initial_amount * 100),
monthly_interest_rate = params.interest_rate_per_annum / 12,
monthly_amount,
months = [];
if (params.method == 'by_num_months') {
var pow = Math.pow(1 + monthly_interest_rate, params.num_months);
monthly_amount = remainder * monthly_interest_rate * pow / (pow - 1);
}
else {
monthly_amount = params.monthly_amount * 100;
}
monthly_amount = Math.ceil(monthly_amount);
// compute by amount first
while (remainder > 0)
{
var interest = Math.floor(remainder * monthly_interest_rate);
remainder += interest;
var to_pay = remainder > monthly_amount ? monthly_amount : remainder;
total_paid += to_pay;
remainder -= to_pay;
months.push({
interest: interest / 100,
repayment: to_pay / 100,
remainder: remainder / 100
});
}
$('#monthly_amount').val((monthly_amount / 100).toFixed(2));
$('#num_months').val(months.length);
return {
total_paid: total_paid / 100,
interest_paid: (total_paid - params.initial_amount * 100) / 100,
months: months
};
}
function updatePaymentTable(data) {
$('#total_repayment').text(data.total_paid.toFixed(2));
$('#total_interested_paid').text(data.interest_paid.toFixed(2));
var rows = $('#monthly_breakdown').empty();
for (var idx=0; idx < data.months.length; idx++) {
var month_num = idx+1;
var is_new_year = (idx % 12) === 0;
var tr = $('<tr />')
.append($('<td />').text(month_num))
.append($('<td />').text(data.months[idx].interest.toFixed(2)))
.append($('<td />').text(data.months[idx].repayment.toFixed(2)))
.append($('<td />').text(data.months[idx].remainder.toFixed(2)))
.addClass(is_new_year ? 'jan' : '')
.appendTo(rows);
}
}
// initiatilize listeners
$('#initial_amount').on('change', updateUI);
$('#interest_rate_per_annum').on('change', updateUI);
$('#monthly_amount').on('change', updateUI);
$('#num_months').on('change', updateUI);
$('#by_monthly_amount').on('change', updateUI);
$('#by_num_months').on('change', updateUI);
|
define([
"dojo/_base/declare",
"dojo/_base/fx",
"dojo/_base/lang",
"dojo/dom-style",
"dojo/mouse",
"dojo/on",
"dijit/_WidgetBase",
"dijit/_TemplatedMixin",
"dojo/text!./templates/TGPrdItem.html",
"dijit/_OnDijitClickMixin",
"dijit/_WidgetsInTemplateMixin",
"dijit/form/Button"
], function(declare, baseFx, lang, domStyle, mouse, on, _WidgetBase,
_TemplatedMixin, template,_OnDijitClickMixin,_WidgetsInTemplateMixin,Button){
return declare([_WidgetBase, _OnDijitClickMixin,_TemplatedMixin,_WidgetsInTemplateMixin], {
// Some default values for our author
// These typically map to whatever you're passing to the constructor
// 产品名称
rtzzhmc: "No Name",
// Using require.toUrl, we can get a path to our AuthorWidget's space
// and we want to have a default avatar, just in case
// 产品默认图片
rimg: require.toUrl("./images/defaultAvatar.png"),
// //起点金额
// code5:"",
// //投资风格
// code7: "",
// //收益率
// code8:"",
// //产品经理
// code3:"",
// //产品ID
// rprid:"",
// Our template - important!
templateString: template,
// A class to be applied to the root node in our template
baseClass: "TGPrdWidget",
// A reference to our background animation
mouseAnim: null,
// Colors for our background animation
baseBackgroundColor: "#fff",
// mouseBackgroundColor: "#def",
postCreate: function(){
// Get a DOM node reference for the root of our widget
var domNode = this.domNode;
// Run any parent postCreate processes - can be done at any point
this.inherited(arguments);
// Set our DOM node's background color to white -
// smoothes out the mouseenter/leave event animations
domStyle.set(domNode, "backgroundColor", this.baseBackgroundColor);
},
//设置属性
_setRimgAttr: function(imagePath) {
// We only want to set it if it's a non-empty string
if (imagePath != "") {
// Save it on our widget instance - note that
// we're using _set, to support anyone using
// our widget's Watch functionality, to watch values change
// this._set("avatar", imagePath);
// Using our avatarNode attach point, set its src value
this.imgNode.src = HTTP+imagePath;
}
}
});
});
|
const { ipcRenderer, remote } = require('electron');
const mainProcess = remote.require('./main');
const currentWindow = remote.getCurrentWindow();
const $name = $('.name-input');
const $servings = $('.servings-input');
const $time = $('.time-input');
const $ingredients = $('.ingredients-input');
const $directions = $('.directions-input');
const $notes = $('.notes-input');
const $saveButton = $('.save-recipe-button');
const $seeAllButton = $('.see-all-button');
const $homeButton = $('.home-button');
const $addRecipeButton = $('.add-button');
let pageNav = (page) => {
currentWindow.loadURL(`file://${__dirname}/${page}`);
};
$saveButton.on('click', () => {
let name = $name.val();
let servings = $servings.val();
let time = $time.val();
let ingredients = $ingredients.val();
let directions = $directions.val();
let notes = $notes.val();
let recipe = { name, servings, time, ingredients, directions, notes};
mainProcess.saveRecipe(recipe);
pageNav('full-recipe.html');
});
$seeAllButton.on('click', () => {
mainProcess.getRecipes();
pageNav('all-recipes.html');
});
$homeButton.on('click', () => {
pageNav('index.html');
});
$addRecipeButton.on('click', () => {
pageNav('add-recipe.html');
});
|
/*
* Store drawing on server
*/
function saveDrawing() {
var drawing = $('#imagePaint').wPaint('image');
var imageid = $('#imageTarget').data('imageid');
var creatormail = $('input[name=creatorMail]').val();
//Add spinning wheel
var spin = $(document.createElement('div'));
spin.addClass('spin');
$('#dialog-content').html(spin);
$.ajax({
type: 'POST',
url: 'savedrawing',
dataType: 'json',
data: {drawing: drawing, imageid: imageid, creatormail: creatormail},
success: function (resp) {
if (resp.kind == 'success')
popup("<p>Die Zeichnung wurde erfolgreich gespeichert.</p><p>Sie wird jedoch zuerst überprüft bevor sie in der Galerie zu sehen ist.</p>");
if (resp.kind == 'error')
popup("<p>Die Zeichnung konnte leider nicht gespeichert werden.</p><p>Der Fehler wird untersucht.</p>");
},
fail: function() {
popup("<p>Die Zeichnung konnte leider nicht gespeichert werden.</p><p>Der Fehler wird untersucht.</p>");
}
});
}
function saveDrawingLocal() {
var imageid = $('img#imageTarget').data('imageid');
var drawingid = $('img#drawingTarget').data('drawingid');
window.location.href = 'getfile?drawingid=' + drawingid + '&imageid=' + imageid;
}
/*
* Popup message
*/
function popup(message) {
// get the screen height and width
var maskHeight = $(document).height();
var maskWidth = $(window).width();
// calculate the values for center alignment
var dialogTop = (maskHeight/2) - ($('#dialog-box').height()/2);
var dialogLeft = (maskWidth/2) - ($('#dialog-box').width()/2);
// assign values to the overlay and dialog box
$('#dialog-overlay').css({height:maskHeight, width:maskWidth}).show();
$('#dialog-box').css({top:dialogTop, left:dialogLeft}).show();
// display the message
$('#dialog-content').html(message);
}
$(document).ready(function() {
/***********************************************
* Encrypt Email script- Please keep notice intact
* Tool URL: http://www.dynamicdrive.com/emailriddler/
* **********************************************/
var emailriddlerarray=[104,111,115,116,109,97,115,116,101,114,64,109,97,99,104,100,105,101,115,116,114,97,115,115,101,98,117,110,116,46,99,111,109]
var encryptedemail_id65='' //variable to contain encrypted email
for (var i=0; i<emailriddlerarray.length; i++)
encryptedemail_id65+=String.fromCharCode(emailriddlerarray[i])
$('#mailMaster').attr('href', 'mailto:' + encryptedemail_id65 );
var emailriddlerarray=[105,110,102,111,64,109,97,99,104,100,105,101,115,116,114,97,115,115,101,98,117,110,116,46,99,111,109]
var encryptedemail_id23='' //variable to contain encrypted email
for (var i=0; i<emailriddlerarray.length; i++)
encryptedemail_id23+=String.fromCharCode(emailriddlerarray[i])
$('#mailInfo').attr('href', 'mailto:' + encryptedemail_id23 );
/*
* Change image
*/
$(".imageSmallContainer").click(function(evt){
var imageid = $(this).data('imageid');
var drawingid = $(this).data('drawingid');
var ids = {imageid : imageid,
drawingid : drawingid};
$.get('changeimage', ids)
.done(function(data){
var imageContainer = $('#imageContainer');
//Hide all images in container
imageContainer.children('.imageRegular').hide();
//Add spinning wheel
var spin = $(document.createElement('div'));
spin.addClass('spin');
imageContainer.prepend(spin);
//Remove hidden old image
$('#imageTarget').remove();
//Create new hidden image
var imageNew = $(document.createElement('img'));
imageNew.attr('id', 'imageTarget');
imageNew.addClass('imageRegular');
imageNew.attr('data-imageid', imageid);
imageNew.data('imageid', imageid);
imageNew.attr('src', data.imagefile);
imageNew.css('display', 'none');
//Prepend new Image to container
imageContainer.prepend(imageNew);
//For Admin and Gallery also change Drawing
if (typeof drawingid != 'undefined') {
var drawing = $('#drawingTarget');
drawing.attr('src', data.drawingfile);
drawing.attr('data-drawingid', drawingid);
drawing.data('drawingid', drawingid);
drawing.attr('drawingid', drawingid);
}
// If newImage src is loaded, remove spin and fade all imgs
// Fires too early in FF
imageContainer.imagesLoaded(function() {
spin.remove();
imageContainer.children('.imageRegular').fadeIn();
});
});
});
/*
* Change the class of moderated images
*/
$('.imageSmallContainerOuter input').change(function(evt){
var container = $(this).parent();
var initial = container.data('initialstate');
var checked = $(this).prop('checked');
container.removeClass('notApproved');
container.removeClass('approved');
container.removeClass('changed');
if (checked && initial == 'approved')
container.addClass('approved');
else if ((checked && initial == 'notApproved') || (!checked && initial == 'approved'))
container.addClass('changed');
else if (!checked && initial == 'notApproved')
container.addClass('notApproved')
});
$('#dialog-box .close, #dialog-overlay').click(function () {
$('#dialog-overlay, #dialog-box').hide();
return false;
});
$('#drawingDialogBtn').click(function(evt){
popup("<p>Aus den besten eingeschickten Zeichnungen werden Freecards gedruckt.</p> \
<p>Mit dem Klick auf den Speicherbutton erklärst du dich dafür bereit, dass dein Bild vielleicht veröffentlicht wird.</p> \
<p>Wenn du deine Email-Adresse angibst können wir dich informieren falls wir deine Zeichnung ausgewählt haben.</p> \
<input type='text' name='creatorMail' placeholder='Email Adresse'> \
<a id='drawingSaveBtn' href='javascript:saveDrawing();' class='btn'>Speichern</a>");
});
});
|
'use strict'
//Globals will be the stage which is the parrent of all graphics, canvas object for resizing and the renderer which is pixi.js framebuffer.
var stage = new PIXI.Container();
var canvas = document.getElementById("game");;
var renderer = PIXI.autoDetectRenderer(1024, 570, {view:document.getElementById("game")});
var graphics = new PIXI.Graphics();
// Create or grab the application
var app = app || {};
function init(){
resize();
renderer = PIXI.autoDetectRenderer(1024, 570, {view:document.getElementById("game")} );
renderer.backgroundColor = 0x50503E;
//level();
canvas.focus();
app.Game.init(renderer, window, canvas, stage);
}
function resize(){
var gameWidth = window.innerWidth;
var gameHeight = window.innerHeight;
var scaleToFitX = gameWidth / 1000;
var scaleToFitY = gameHeight / 500;
// Scaling statement belongs to: https://www.davrous.com/2012/04/06/modernizing-your-html5-canvas-games-part-1-hardware-scaling-css3/
var optimalRatio = Math.min(scaleToFitX, scaleToFitY);
var currentScreenRatio = gameWidth / gameHeight;
if(currentScreenRatio >= 1.77 && currentScreenRatio <= 1.79) {
canvas.style.width = gameWidth + "px";
canvas.style.height = gameHeight + "px";
}else{
canvas.style.width = 1000 * optimalRatio + "px";
canvas.style.height = 500 * optimalRatio + "px";
}
}
//do not REMOVE
/*
//takes two arrays
// the w_array is an array of column width values [w1, w2, w3, ...], y_array is
//3d array setup as such [[row 1], [row 2], [row3]] and the rows are arrays
// that contain pairs of y,l values where y is the fixed corner of the
//rectangle and L is the height of the rectangle.
function level(){
// drawRect( xstart, ystart, x size side, y size side)
app.levelData = {
w_array: [102 * 2, 102 * 2, 102 * 2, 102 * 2, 102 * 2],
y_array: [
[
[0 * 2, 90 * 2],
[0 * 2, 90 * 2],
[0 * 2, 90 * 2],
[0 * 2, 90 * 2],
[0 * 2, 90 * 2],
],
[
[90 * 2, 90 * 2],
[90 * 2, 90 * 2],
[90 * 2, 90 * 2],
[90 * 2, 90 * 2],
[90 * 2, 90 * 2],
],
[
[180 * 2, 90 * 2],
[180 * 2, 90 * 2],
[180 * 2, 90 * 2],
[180 * 2, 90 * 2],
[180 * 2, 90 * 2],
],
[
[270 * 2, 90 * 2],
[270 * 2, 90 * 2],
[270 * 2, 90 * 2],
[270 * 2, 90 * 2],
[270 * 2, 90 * 2],
]
],
p_array: [
[50,50,50,50],
[50,450,50,50],
[920,50,50,50],
[920,450,50,50],
]
};
// set a fill and a line style again and draw a rectangle
graphics.lineStyle(2, 0x995702, 1);
graphics.beginFill(0x71FF33, 1);
var x = 0;
//reset the x
x = 0;
//post fence post
for(var h = 0, hlen = app.levelData.y_array.length; h < hlen; h++){
for( var i = 0, len = app.levelData.w_array.length; i < len; i++){
//setup the y value
graphics.drawRect(x, app.levelData.y_array[h][i][0], app.levelData.w_array[i], app.levelData.y_array[h][i][1]);
x += app.levelData.w_array[i];
}
//reset the x
x = 0;
}
graphics.lineStyle(2, 0x3472D8, 1);
graphics.beginFill(0x3472D8, 1);
for(var i = 0, len = app.levelData.p_array.length; i < len; i++){
graphics.drawRect(app.levelData.p_array[i][0], app.levelData.p_array[i][1], app.levelData.p_array[i][2], app.levelData.p_array[i][3]);
}
stage.addChild(graphics);
}
// Reads in a JSON object with data
function readJSONFile( filePath ){
$.getJSON( filePath, function(){} )
.done( function( data ){
console.log( "SUCCESS: File read from " + filePath );
app.levelData = data;
} )
.fail( function( ){
console.log( "FAILED: File at " + filePath );
} );
}
*/
window.addEventListener('resize', resize, false);
window.addEventListener('orientationchange', resize, false);
|
import React, {Component} from 'react';
import {connect} from 'react-redux';
class MapFull extends Component {
constructor() {
super();
this.state = {
htmlContent: null
};
}
componentDidMount() {
this.getMapHtml();
}
componentDidUpdate(prevProps, prevState) {
if (!this.props.map || this.props.map.filehash !== prevProps.map.filehash) {
this.getMapHtml();
}
}
getMapHtml() {
const path = this.props.settings.html_url + this.props.map.filehash;
fetch(path).then(response => {
return response.text();
}).then(response => {
this.setState({
htmlContent: response
});
});
}
getMarkup() {
return {__html: this.state.htmlContent}
}
render() {
return (
<div className="MapFull layoutbox">
<h3>{this.props.map.titlecache}</h3>
<div id="overDiv" style={{position: 'fixed', visibility: 'hide', zIndex: 1}}></div>
<div>
{this.state.htmlContent ? <div>
<div dangerouslySetInnerHTML={this.getMarkup()}></div>
</div> : null}
</div>
</div>
)
}
}
function mapStateToProps(state) {
return {settings: state.settings}
}
export default connect(mapStateToProps)(MapFull);
|
// Karma configuration file, see link for more information
// https://karma-runner.github.io/1.0/config/configuration-file.html
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', '@angular-devkit/build-angular'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('@angular-devkit/build-angular/plugins/karma')
],
client: {
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
reporters: ['progress', 'kjhtml'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false,
restartOnFileChange: true
});
};
|
var f = require('fs');
var _ = require('underscore');
var r = {};
var cr = require('../config.json').resources;
var k = require('../config.json').plugins;
var b = require('../config.json').APIVARS.PLUGINS;
var n = __dirname.replace('/autoform', b.DIR);
var w = ['tokens', 'settings'];
var s = ['actions', 'login', 'recover', 'register' ];
var p = './views/index/forms';
var c = function (n) {
return n.replace('.jade','');
};
var j = function (props) {
for (var p in props) {
if(props.hasOwnProperty(p)){
if(!props[p].exclude){
r[p] = props[p];
}
}
}
};
var init = function() {
for(var i in k){
if(k.hasOwnProperty(i)){
var e = k[i];
var g = '/' + e;
var a = require(n + g + b.CONFIG);
j(a.resources);
}
}
};
init();
j(r);
var generator = function (cb) {
var t;
var x;
var v;
var u = _.union(Object.keys(r), Object.keys(cr));
var m = _.difference(u, w);
for(var idx in r) {
if (r.hasOwnProperty(idx)) {
rc[idx] = r[idx];
}
}
if(f.existsSync(p)){
t = f.readdirSync(p);
t = _.map(t, c);
t = _.difference(t,s);
x = _.intersection(m,t);
v = _.difference(m,t);
}
cb({
models: m,
valid: x,
missing: v,
resources: u,
schemas: cr
});
};
module.exports = generator;
|
var AWS = require('aws-sdk');
var Policy = require("./s3post").Policy;
var helpers = require("./helpers");
var POLICY_FILE = "policy.json";
var schedule = require('node-schedule');
var Worker = function(sqsCommnad, s3Object, simpleData){
var queue = sqsCommnad;
var s3 = s3Object;
var simpleDataAuth = simpleData;
var policyData = helpers.readJSONFile(POLICY_FILE);
var policy = new Policy(policyData);
var bucket_name = policy.getConditionValueByKey("bucket");
Worker.prototype.job = function(){
var run = schedule.scheduleJob('*/4 * * * * *',
function(){
queue.recv(function(err, data){
if (err) {
console.log(err);
return;
}
console.log({Body : data.Body, MD5OfBody : data.MD5OfBody});
params = {
Bucket: bucket_name,
Key: data.Body
}
s3.getObject(params, function(err, data) {
if (err) {
console.log(err, err.stack);
}
else {
var request = require('request');
var mime = require('mime');
var gm = require('gm').subClass({ imageMagick: true });
var src = 'http://s3-us-west-2.amazonaws.com/'+params.Bucket+'/'+params.Key;
gm(request(src, params.Key))
.rotate('black', 15)
.stream(function(err, stdout, stderr) {
var buf = new Buffer('');
stdout.on('data', function(res) {
buf = Buffer.concat([buf, res]);
});
stdout.on('end', function(data) {
var atr = {
Bucket: params.Bucket,
Key: params.Key,
Body: buf,
ACL: 'public-read',
Metadata: {
"username" : "Szymon Glowacki",
"ip" : "192.168.1.10"
}
};
s3.putObject(atr, function(err, res) {
console.log("done");
});
});
});
}
});
});
});
}
}
module.exports = Worker;
|
import React, { Component } from 'react'
import { Form, Grid, Image, Transition } from 'shengnian-ui-react'
const transitions = [
'scale',
'fade', 'fade up', 'fade down', 'fade left', 'fade right',
'horizontal flip', 'vertical flip',
'drop',
'fly left', 'fly right', 'fly up', 'fly down',
'swing left', 'swing right', 'swing up', 'swing down',
'browse', 'browse right',
'slide down', 'slide up', 'slide right',
]
const options = transitions.map(name => ({ key: name, text: name, value: name }))
export default class TransitionExampleSingleExplorer extends Component {
state = { animation: transitions[0], duration: 500, visible: true }
handleChange = (e, { name, value }) => this.setState({ [name]: value })
handleVisibility = () => this.setState({ visible: !this.state.visible })
render() {
const { animation, duration, visible } = this.state
return (
<Grid columns={2}>
<Grid.Column as={Form}>
<Form.Select
label='Choose transition'
name='animation'
onChange={this.handleChange}
options={options}
value={animation}
/>
<Form.Input
label={`Duration: ${duration}ms `}
min={100}
max={2000}
name='duration'
onChange={this.handleChange}
step={100}
type='range'
value={duration}
/>
<Form.Button content={visible ? 'Unmount' : 'Mount'} onClick={this.handleVisibility} />
</Grid.Column>
<Grid.Column>
<Transition.Group animation={animation} duration={duration}>
{visible && <Image centered size='small' src='/assets/images/leaves/4.png' />}
</Transition.Group>
</Grid.Column>
</Grid>
)
}
}
|
var Game = {
map: {
width: 980,
height: 62 * 12
},
tiles: {
size: 62,
count: [100, 12]
},
sprite: {
8: 'LAND_LEFT',
2: 'LAND_MID',
10: 'LAND_RIGHT',
9: 'LAND',
5: 'WATER_TOP',
12: 'WATER',
4: 'STONE_WITH_MONEY',
11: 'STONE',
6: 'CACTUS',
13: 'GRASS',
7: 'START',
1: 'END'
}
};
Crafty.init(Game.map.width, Game.map.height, document.getElementById('game'));
Crafty.background('url(./assets/images/bg.png)');
Crafty.scene('Loading');
|
'use strict';
import _ from 'lodash';
import bluebird from 'bluebird';
import fs from 'fs';
import requireDir from 'require-dir';
import Logger from '../../logger';
bluebird.promisifyAll(fs);
function main() {
const imports = _.chain(requireDir('./importers'))
.map('default')
.map((importer) => importer.run())
.value();
return Promise.all(imports);
}
Logger.info('base.data.imports.imports: Running...');
main()
.then(() => {
Logger.info('base.data.imports.imports: Done!');
process.exit(0);
})
.catch((error) => {
Logger.error('base.data.imports.imports:', error);
process.exit(1);
});
|
Ext.define('Category.view.GenericList', {
extend: 'Ext.grid.Panel',
alias: 'widget.genericlist',
store: 'Generic',
title: Raptor.getTag('category_header'),
iconCls:'',
initComponent: function() {
this.columns = [{
header:Raptor.getTag('category_name'),
dataIndex: 'name',
flex: 1
}];
this.dockedItems = [{
dock: 'top',
xtype: 'toolbar',
items: [{
xtype: 'button',
text: Raptor.getTag('add'),
privilegeName:'insert',
action:'addAction',
iconCls:'icon-add'
},{
xtype: 'button',
text: Raptor.getTag('edit'),
disabled:true,
privilegeName:'edit/:id',
action:'editAction',
iconCls:'icon-edit'
},{
xtype: 'button',
text: Raptor.getTag('delete'),
disabled:true,
privilegeName:'delete/:id',
action:'deleteAction',
iconCls:'icon-del'
}]
}];
this.callParent();
}
});
|
const moment = require('moment')
const expect = require('chai').expect
const sinon = require('sinon')
const proxyquire = require('proxyquire')
const breadcrumbHelper = require('../../helpers/breadcrumb-helper')
const orgUnitConstant = require('../../../app/constants/organisation-unit.js')
const activeStartDate = moment('25-12-2017', 'DD-MM-YYYY').toDate() // 2017-12-25T00:00:00.000Z
const activeEndDate = moment('25-12-2018', 'DD-MM-YYYY').toDate() // 2018-12-25T00:00:00.000Z
const breadcrumbs = breadcrumbHelper.TEAM_BREADCRUMBS
const expectedReductionExport = [
{
offenderManager: 'Test_Forename Test_Surname',
reason: 'Disability',
amount: 5,
startDate: activeStartDate,
endDate: activeEndDate,
status: 'ACTIVE',
additionalNotes: 'New Test Note'
}]
let getReductionsData
let exportReductionService
let getBreadcrumbsStub
beforeEach(function () {
getReductionsData = sinon.stub()
getBreadcrumbsStub = sinon.stub().resolves(breadcrumbs)
exportReductionService =
proxyquire('../../../app/services/get-reductions-export',
{
'./data/get-reduction-notes-export': getReductionsData,
'./get-breadcrumbs': getBreadcrumbsStub
})
})
describe('services/get-reductions-export', function () {
it('should return the expected reductions exports for team level', function () {
getReductionsData.resolves(expectedReductionExport)
return exportReductionService(1, orgUnitConstant.TEAM.name)
.then(function (result) {
expect(getReductionsData.calledWith(1, orgUnitConstant.TEAM.name)).to.be.eql(true)
expect(getBreadcrumbsStub.calledWith(1, orgUnitConstant.TEAM.name)).to.be.eql(true)
expect(result.reductionNotes[0].offenderManager).to.be.eql(expectedReductionExport[0].offenderManager)
expect(result.reductionNotes[0].reason).to.be.eql(expectedReductionExport[0].reason)
expect(result.reductionNotes[0].amount).to.be.eql(expectedReductionExport[0].amount)
expect(result.reductionNotes[0].startDate).to.be.eql('25 12 2017, 00:00')
expect(result.reductionNotes[0].endDate).to.be.eql('25 12 2018, 00:00')
expect(result.reductionNotes[0].status).to.be.eql(expectedReductionExport[0].status)
expect(result.reductionNotes[0].additionalNotes).to.be.eql(expectedReductionExport[0].additionalNotes)
})
})
})
|
import axios from 'axios'
import pipelineApi from './api'
import { addMessage } from '../../../client/utils/flash-messages'
import { transformValueForAPI } from '../../../client/utils/date'
function transformValuesForApi(values, oldValues = {}) {
const data = {
name: values.name,
status: values.category,
}
function addValue(key, value) {
const existingValue = oldValues[key]
const hasExistingValue = Array.isArray(existingValue)
? !!existingValue.length
: !!existingValue
if (hasExistingValue || (Array.isArray(value) ? value.length : value)) {
data[key] = value || null
}
}
addValue('likelihood_to_win', parseInt(values.likelihood, 10))
addValue('sector', values.sector?.value)
addValue(
'contacts',
values.contacts ? values.contacts.map(({ value }) => value) : []
)
addValue('potential_value', values.export_value)
addValue('expected_win_date', transformValueForAPI(values.expected_win_date))
return data
}
export async function getPipelineByCompany({ companyId }) {
const { data } = await pipelineApi.list({ company_id: companyId })
return {
companyId,
count: data.count,
results: data.results,
}
}
export async function addCompanyToPipeline({ values, companyId }) {
const { data } = await pipelineApi.create({
company: companyId,
...transformValuesForApi(values),
})
addMessage('success', `You added ${values.name} to your pipeline`)
return data
}
export async function getPipelineItem({ pipelineItemId }) {
const { data } = await pipelineApi.get(pipelineItemId)
return data
}
export async function getCompanyContacts({ companyId, features }) {
const contactEndpointVersion = features['address-area-contact-required-field']
? 'v4'
: 'v3'
const { data } = await axios.get(
`/api-proxy/${contactEndpointVersion}/contact`,
{
params: { company_id: companyId, limit: 500 },
}
)
return data.results
}
export async function editPipelineItem({
values,
pipelineItemId,
currentPipelineItem,
}) {
const { data } = await pipelineApi.update(
pipelineItemId,
transformValuesForApi(values, currentPipelineItem)
)
addMessage('success', `You saved changes to ${values.name}`)
return data
}
export async function archivePipelineItem({
values,
pipelineItemId,
projectName,
}) {
const { data } = await pipelineApi.archive(pipelineItemId, {
reason: values.reason,
})
addMessage('success', `You archived ${projectName}`)
return data
}
export async function unarchivePipelineItem({ projectName, pipelineItemId }) {
const { data } = await pipelineApi.unarchive(pipelineItemId)
addMessage('success', `You unarchived ${projectName}`)
return data
}
export async function deletePipelineItem({ projectName, pipelineItemId }) {
const { status } = await pipelineApi.delete(pipelineItemId)
addMessage('success', `You deleted ${projectName} from your pipeline`)
return status
}
|
const multiples =
'(hundred|thousand|million|billion|trillion|quadrillion|quintillion|sextillion|septillion)'
const here = 'fraction-tagger'
// plural-ordinals like 'hundredths' are already tagged as Fraction by compromise
const tagFractions = function (doc) {
// hundred
doc.match(multiples).tag('#Multiple', here)
// half a penny
doc.match('[(half|quarter)] of? (a|an)', 0).tag('Fraction', 'millionth')
// nearly half
doc.match('#Adverb [half]', 0).tag('Fraction', 'nearly-half')
// half the
doc.match('[half] the', 0).tag('Fraction', 'half-the')
// two-halves
doc.match('#Value (halves|halfs|quarters)').tag('Fraction', 'two-halves')
// ---ordinals as fractions---
// a fifth
doc.match('a #Ordinal').tag('Fraction', 'a-quarter')
// seven fifths
doc.match('(#Fraction && /s$/)').lookBefore('#Cardinal+$').tag('Fraction')
// one third of ..
doc.match('[#Cardinal+ #Ordinal] of .', 0).tag('Fraction', 'ordinal-of')
// 100th of
doc.match('[(#NumericValue && #Ordinal)] of .', 0).tag('Fraction', 'num-ordinal-of')
// a twenty fifth
doc.match('(a|one) #Cardinal?+ #Ordinal').tag('Fraction', 'a-ordinal')
// doc.match('(a|one) [#Ordinal]', 0).tag('Fraction', 'a-ordinal')
// values.if('#Ordinal$').tag('Fraction', '4-fifths')
// seven quarters
// values.tag('Fraction', '4-quarters')
// doc.match('(#Value && !#Ordinal)+ (#Ordinal|#Fraction)').tag('Fraction', '4-fifths')
// 12 and seven fifths
// doc.match('#Value+ and #Value+ (#Ordinal|half|quarter|#Fraction)').tag('Fraction', 'val-and-ord')
// fixups
// doc.match('#Cardinal+? (second|seconds)').unTag('Fraction', '3 seconds')
// doc.match('#Ordinal (half|quarter)').unTag('Fraction', '2nd quarter')
// doc.match('#Ordinal #Ordinal+').unTag('Fraction')
// doc.match('[#Cardinal+? (second|seconds)] of (a|an)', 0).tag('Fraction', here)
// doc.match(multiples).tag('#Multiple', here)
// // '3 out of 5'
doc.match('#Cardinal+ out? of every? #Cardinal').tag('Fraction', here)
// // one and a half
// doc.match('#Cardinal and a (#Fraction && #Value)').tag('Fraction', here)
// fraction - 'a third of a slice'
// TODO:fixme
// m = doc.match(`[(#Cardinal|a) ${ordinals}] of (a|an|the)`, 0).tag('Fraction', 'ord-of')
// tag 'thirds' as a ordinal
// m.match('.$').tag('Ordinal', 'plural-ordinal')
return doc
}
module.exports = tagFractions
|
window._skel_config = {
prefix: 'css/style',
preloadStyleSheets: true,
resetCSS: true,
boxModel: 'border',
grid: { gutters: 30 },
breakpoints: {
wide: { range: '1200-', containers: 1140, grid: { gutters: 50 } },
narrow: { range: '481-1199', containers: 960 },
mobile: { range: '-480', containers: 'fluid', lockViewport: true, grid: { collapse: true } }
}
};
$(document).ready(function () {
$("#calculate").click(function () {
var opOne = $("#opOneID").val();
var opTwo = $("#opTwoID").val();
var selected = $('#mathFunction :selected').val();
if (opOne.length != 0) {
$("#resultID").val(process(selected, opOne, opTwo)); // puts the result into the correct dom element resultID on the page.
}
else if (opTwo.length != 0) {
$("#resultID").val(process(selected, opOne, opTwo)); // puts the result into the correct dom element resultID on the page.
}
});
$("#clear").click(function () {
$("#opOneID").val('');
$("#opTwoID").val('');
$("#resultID").val('');
});
$("#pnlRemove").click(function () {
/* this function remove the fron panelof the cube so you can see inside and changes the bottom image which is the manchester United chrest with the image that ]
was the front panel image] this only shows the panels being changed by using code*/
var imageName = 'img/v8liv.PNG';
var changepnl = $('#btmpnl');
var pnlID = $('#v8front');
$(pnlID).hide(); // hide the front panel
$('#btmpnl').attr('src', imageName); // change the bottom image to v8rear.PNG
});
$('#mathFunction :selected').val();
$('#mathFunction').change(function () {
/* this fucntion calls the calucate funtion with the number to be converted with the conversion type which comes from the select tag, eg pk is pounds to kilo's
this function fires when the select dropdown box changes */
var opOne = $("#opOneID").val();
var opTwo = $("#opTwoID").val();
var selected = $('#mathFunction :selected').val();
// console.log($('#conversion :selected').val()); //write it out to the console to verify what was
$("#resultID").val(process(selected, opOne,opTwo)); // puts the convertion into the correct dom element on the page.
}).change();
});
function process(selected, opOne,opTwo) {
switch (selected) {
case "+":
return Calc.AddNo(opOne,opTwo);
break;
case "-":
return Calc.SubNo(opOne, opTwo);
break;
case "/":
return Calc.DivideNo(opOne, opTwo);
break;
case "*":
return Calc.MultplyNo(opOne, opTwo);
break;
default:
return "Error ! ";
// code to be executed if n is different from case 1 and 2
}
}
|
(function(app, undefined) {
'use strict';
if(!app) throw new Error('Application "app" namespace not found.');
//----------------------------------------------------------------------------
console.log( 'hello world' );
console.log( 'Application Running...' );
//----------------------------------------------------------------------------
// @begin: renders
app.render.jquery();
app.render.vanilla();
// @end: renders
//----------------------------------------------------------------------------
// @begin: to_jquery
app.to_jquery.run();
// @end: to_jquery
//----------------------------------------------------------------------------
// @begin: mustache
app.menu.render();
app.menu.option.reset();
// @begin: mustache
//----------------------------------------------------------------------------
})(window.app);
|
import Ember from 'ember';
import CheckboxMixin from '../mixins/checkbox-mixin';
export default Ember.Component.extend(CheckboxMixin, {
type: 'checkbox',
checked: false,
onChange: function() {
this.set('checked', this.$('input').prop('checked'));
this.sendAction("action", {
checked: this.get('checked'),
value: this.get('value')
});
}
});
|
"use strict"
var express = require('express');
var app = express();
var elasticsearch = require('elasticsearch');
var client = new elasticsearch.Client({
host: 'localhost:9200',
log: 'trace'
});
var router = express.Router();
router.get('/accidents', function(req, res) {
var query = {
index: 'wildmap',
type: 'accidents',
size: 10000,
body: {
query: {
bool: {
must: [
{
match_all: {}
}
]
}
}
}
}
var animal_type = req.query.animal_type;
var day_type = req.query.day_type;
var season = req.query.season;
if(animal_type && animal_type!="all"){
query.body.query.bool.must.push({
term: {
"accidents.pin.animal_type": animal_type
}
});
}
if(day_type && day_type!="all"){
query.body.query.bool.must.push({
term: {
"accidents.pin.day_type": day_type
}
});
}
if(season && season!="all"){
query.body.query.bool.must.push({
term: {
"accidents.pin.season": season
}
});
}
console.log(query);
client.search(query).then(function (resp) {
console.log(resp.hits.hits);
var response = resp.hits.hits.map(function(e){
return e._source.pin;
})
res.send(response);
}, function (err) {
console.log(err.message);
res.status(500).end();
});
});
app.use('/api', router);
var port = process.env.PORT || 8080;
app.listen(port);
console.log("Backend is running on port " + port);
|
const S$ = require('S$');
function loadSrc(obj, src) {
throw src;
}
const cookies = S$.symbol('Cookie', '');
const world = {};
if (cookies) {
if (/iPhone/.exec(cookies)) {
loadSrc(world, '/resources/' + cookies);
}
loadSrc(world, '/resources/unknown');
} else {
loadSrc(world, '/resources/fresh');
}
|
module.exports = function (seneca, util) {
//var Joi = util.Joi
}
|
'use strict'
var test = require('tap').test
var strip = require('./')
test('stripFalsy', function(t) {
t.plan(5)
t.deepEqual(strip(null), {})
t.deepEqual(strip('test'), {})
t.deepEqual(strip(13), {})
t.deepEqual(strip(), {})
var input = {
a: false
, b: 0
, c: null
, d: undefined
, e: ''
, f: 'biscuits'
, g: '0'
}
var exp = {
f: 'biscuits'
, g: '0'
}
t.deepEqual(strip(input), exp)
})
|
$(function () {
$('.imageUploadMultiple').each(function (index, item) {
var $item = $(item);
var $group = $item.closest('.form-group');
var $innerGroup = $item.find('.form-group');
var $errors = $item.find('.errors');
var $input = $item.find('.imageValue');
var flow = new Flow({
target: $item.data('target'),
testChunks: false,
chunkSize: 1024 * 1024 * 1024,
query: {
_token: $item.data('token')
}
});
var updateValue = function () {
var values = [];
$item.find('img[data-value]').each(function () {
values.push($(this).data('value'));
});
$input.val(values.join(','));
};
flow.assignBrowse($item.find('.imageBrowse'));
flow.on('filesSubmitted', function (file) {
flow.upload();
});
flow.on('fileSuccess', function (file, message) {
flow.removeFile(file);
$errors.html('');
$group.removeClass('has-error');
var result = $.parseJSON(message);
$innerGroup.append('<div class="col-xs-6 col-md-3 imageThumbnail"><div class="thumbnail">' +
'<img data-value="' + result.value + '" src="' + result.url + '" />' +
'<a href="#" class="imageRemove">Remove</a></div></div>');
updateValue();
});
flow.on('fileError', function (file, message) {
flow.removeFile(file);
var response = $.parseJSON(message);
var errors = '';
$.each(response, function (index, error) {
errors += '<p class="help-block">' + error + '</p>'
});
$errors.html(errors);
$group.addClass('has-error');
});
$item.on('click', '.imageRemove', function (e) {
e.preventDefault();
$(this).closest('.imageThumbnail').remove();
updateValue();
});
$innerGroup.sortable({
onUpdate: function () {
updateValue();
}
});
});
});
|
// function that finds the sum of two parameters
function findSum(firstnr, secondnr){
return firstnr + secondnr;
}
//function that finds the product of two parameters
function findProduct(firstnr, secondnr){
return firstnr * secondnr;
}
/* threeOperation calls the operation parameter as a function so it's able to run and "do" different things
depending on the global function it takes as a parameter when calling it*/
function threeOperation (x, operation){
/*put console.log here so it doesn't only returns the result but also prints it in the console first:
to check if it gives the right answer when it's called*/
console.log(operation(3, x));
return operation(3, x);
}
//Call "threeOperation" with the values of "4" and "findSum"
threeOperation(4, findSum);
//Call "threeOperation" with the values of "5" and "findSum"
threeOperation(5, findSum);
//Call "threeOperation" with the values of "4" and "findProduct"
threeOperation(4, findProduct);
//Call "threeOperation" with the values of "5" and "findProduct"
threeOperation(5, findProduct);
|
// GPG4Browsers - An OpenPGP implementation in javascript
// Copyright (C) 2011 Recurity Labs GmbH
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
/**
* Public-Key Encrypted Session Key Packets (Tag 1)<br/>
* <br/>
* {@link http://tools.ietf.org/html/rfc4880#section-5.1|RFC4880 5.1}: A Public-Key Encrypted Session Key packet holds the session key
* used to encrypt a message. Zero or more Public-Key Encrypted Session Key
* packets and/or Symmetric-Key Encrypted Session Key packets may precede a
* Symmetrically Encrypted Data Packet, which holds an encrypted message. The
* message is encrypted with the session key, and the session key is itself
* encrypted and stored in the Encrypted Session Key packet(s). The
* Symmetrically Encrypted Data Packet is preceded by one Public-Key Encrypted
* Session Key packet for each OpenPGP key to which the message is encrypted.
* The recipient of the message finds a session key that is encrypted to their
* public key, decrypts the session key, and then uses the session key to
* decrypt the message.
* @requires crypto
* @requires enums
* @requires type/s2k
* @module packet/sym_encrypted_session_key
*/
var type_s2k = require('../type/s2k.js'),
enums = require('../enums.js'),
crypto = require('../crypto');
module.exports = SymEncryptedSessionKey;
/**
* @constructor
*/
function SymEncryptedSessionKey() {
this.tag = enums.packet.symEncryptedSessionKey;
this.sessionKeyEncryptionAlgorithm = null;
this.sessionKeyAlgorithm = 'aes256';
this.encrypted = null;
this.s2k = new type_s2k();
}
/**
* Parsing function for a symmetric encrypted session key packet (tag 3).
*
* @param {String} input Payload of a tag 1 packet
* @param {Integer} position Position to start reading from the input string
* @param {Integer} len
* Length of the packet or the remaining length of
* input at position
* @return {module:packet/sym_encrypted_session_key} Object representation
*/
SymEncryptedSessionKey.prototype.read = function(bytes) {
// A one-octet version number. The only currently defined version is 4.
this.version = bytes.charCodeAt(0);
// A one-octet number describing the symmetric algorithm used.
var algo = enums.read(enums.symmetric, bytes.charCodeAt(1));
// A string-to-key (S2K) specifier, length as defined above.
var s2klength = this.s2k.read(bytes.substr(2));
// Optionally, the encrypted session key itself, which is decrypted
// with the string-to-key object.
var done = s2klength + 2;
if (done < bytes.length) {
this.encrypted = bytes.substr(done);
this.sessionKeyEncryptionAlgorithm = algo;
} else
this.sessionKeyAlgorithm = algo;
};
SymEncryptedSessionKey.prototype.write = function() {
var algo = this.encrypted === null ?
this.sessionKeyAlgorithm :
this.sessionKeyEncryptionAlgorithm;
var bytes = String.fromCharCode(this.version) +
String.fromCharCode(enums.write(enums.symmetric, algo)) +
this.s2k.write();
if (this.encrypted !== null)
bytes += this.encrypted;
return bytes;
};
/**
* Decrypts the session key (only for public key encrypted session key
* packets (tag 1)
*
* @return {String} The unencrypted session key
*/
SymEncryptedSessionKey.prototype.decrypt = function(passphrase) {
var algo = this.sessionKeyEncryptionAlgorithm !== null ?
this.sessionKeyEncryptionAlgorithm :
this.sessionKeyAlgorithm;
var length = crypto.cipher[algo].keySize;
var key = this.s2k.produce_key(passphrase, length);
if (this.encrypted === null) {
this.sessionKey = key;
} else {
var decrypted = crypto.cfb.decrypt(
this.sessionKeyEncryptionAlgorithm, key, this.encrypted, true);
this.sessionKeyAlgorithm = enums.read(enums.symmetric,
decrypted[0].keyCodeAt());
this.sessionKey = decrypted.substr(1);
}
};
SymEncryptedSessionKey.prototype.encrypt = function(passphrase) {
var length = crypto.getKeyLength(this.sessionKeyEncryptionAlgorithm);
var key = this.s2k.produce_key(passphrase, length);
var private_key = String.fromCharCode(
enums.write(enums.symmetric, this.sessionKeyAlgorithm)) +
crypto.getRandomBytes(
crypto.getKeyLength(this.sessionKeyAlgorithm));
this.encrypted = crypto.cfb.encrypt(
crypto.getPrefixRandom(this.sessionKeyEncryptionAlgorithm),
this.sessionKeyEncryptionAlgorithm, key, private_key, true);
};
/**
* Fix custom types after cloning
*/
SymEncryptedSessionKey.prototype.postCloneTypeFix = function() {
this.s2k = type_s2k.fromClone(this.s2k);
};
|
export default {
FETCH_TAGS_PENDING: Symbol("FETCH_TAGS_PENDING"),
FETCH_TAGS_SUCCESS: Symbol("FETCH_TAGS_SUCCESS"),
FETCH_TAGS_FAILURE: Symbol("FETCH_TAGS_FAILURE"),
FILTER_TAGS: Symbol("FILTER_TAGS"),
ORDER_TAGS: Symbol("ORDER_TAGS")
};
|
/**
*
* @function
* @param {Array|arraylike} value
* @param {Function} cmd
* @param {any} context
* @returns {?}
*/
export default function eachValue(value, cmd, context, keepReverse) {
if (value === undefined || value === null) return undefined;
const size = (0 | value.length) - 1;
for (let index = size; index > -1; index -= 1) {
const i = keepReverse ? index : size - index;
const item = value[i];
const resolve = cmd.call(context || item, item, i, value, i);
if (resolve === undefined === false) {
return resolve;
}
}
return undefined;
}
|
const should = require('should'),
sinon = require('sinon'),
_ = require('lodash'),
settingsCache = require('../../../../server/services/settings/cache'),
common = require('../../../../server/lib/common'),
controllers = require('../../../../server/services/routing/controllers'),
TaxonomyRouter = require('../../../../server/services/routing/TaxonomyRouter'),
RESOURCE_CONFIG = require('../../../../server/services/routing/assets/resource-config'),
sandbox = sinon.sandbox.create();
describe('UNIT - services/routing/TaxonomyRouter', function () {
let req, res, next;
beforeEach(function () {
sandbox.stub(settingsCache, 'get').withArgs('permalinks').returns('/:slug/');
sandbox.stub(common.events, 'emit');
sandbox.stub(common.events, 'on');
sandbox.spy(TaxonomyRouter.prototype, 'mountRoute');
sandbox.spy(TaxonomyRouter.prototype, 'mountRouter');
req = sandbox.stub();
res = sandbox.stub();
next = sandbox.stub();
res.locals = {};
});
afterEach(function () {
sandbox.restore();
});
it('instantiate', function () {
const taxonomyRouter = new TaxonomyRouter('tag', '/tag/:slug/');
should.exist(taxonomyRouter.router);
should.exist(taxonomyRouter.rssRouter);
taxonomyRouter.taxonomyKey.should.eql('tag');
taxonomyRouter.getPermalinks().getValue().should.eql('/tag/:slug/');
common.events.emit.calledOnce.should.be.true();
common.events.emit.calledWith('router.created', taxonomyRouter).should.be.true();
taxonomyRouter.mountRouter.callCount.should.eql(1);
taxonomyRouter.mountRouter.args[0][0].should.eql('/tag/:slug/');
taxonomyRouter.mountRouter.args[0][1].should.eql(taxonomyRouter.rssRouter.router());
taxonomyRouter.mountRoute.callCount.should.eql(3);
// permalink route
taxonomyRouter.mountRoute.args[0][0].should.eql('/tag/:slug/');
taxonomyRouter.mountRoute.args[0][1].should.eql(controllers.channel);
// pagination feature
taxonomyRouter.mountRoute.args[1][0].should.eql('/tag/:slug/page/:page(\\d+)');
taxonomyRouter.mountRoute.args[1][1].should.eql(controllers.channel);
// edit feature
taxonomyRouter.mountRoute.args[2][0].should.eql('/tag/:slug/edit');
taxonomyRouter.mountRoute.args[2][1].should.eql(taxonomyRouter._redirectEditOption.bind(taxonomyRouter));
});
it('fn: _prepareContext', function () {
const taxonomyRouter = new TaxonomyRouter('tag', '/tag/:slug/');
taxonomyRouter._prepareContext(req, res, next);
next.calledOnce.should.eql(true);
res.locals.routerOptions.should.eql({
name: 'tag',
permalinks: '/tag/:slug/',
type: RESOURCE_CONFIG.QUERY.tag.resource,
data: {tag: _.omit(RESOURCE_CONFIG.QUERY.tag, 'alias')},
filter: RESOURCE_CONFIG.TAXONOMIES.tag.filter,
context: ['tag'],
slugTemplate: true,
identifier: taxonomyRouter.identifier
});
res._route.type.should.eql('channel');
});
});
|
import React from 'react';
import $ from 'jquery';
import _ from 'lodash';
import Block from './Block';
export default class BlockGrid extends React.Component {
constructor() {
super();
this.setDefaults();
this.setContainerWidth = this.setContainerWidth.bind(this);
this.handleWindowResize = this.handleWindowResize.bind(this);
this.resizeTimer = null;
// throttle call to this func whenever an image is loaded
this.throttledSetContainerWidth = _.throttle(this.setContainerWidth, 500);
}
setDefaults(){
this.blockWidth = 260; // initial desired block width
this.borderWidth = 5;
this.wrapperWidth = 0;
this.colCount = 0;
this.blocks = [];
this.blockCount = 0;
}
handleWindowResize(){
clearTimeout(this.resizeTimer);
const _this = this;
this.resizeTimer = setTimeout(function() {
$('.block-container').css('width', '100%');
_this.setDefaults();
_this.setContainerWidth();
// above code computes false height of blocks
// so as a lose patch re-position blocks after 500 ms
setTimeout(_this.setContainerWidth, 700);
}, 200);
}
componentDidMount(){
this.setContainerWidth();
/*
height of each block is measured with an error the first time so there are some
space between blocks specially the top values of the grid.
Only solution seems like re calculating positions of the block after few seconds
*/
// _.delay(this.setContainerWidth, 3000);
// reset all blocks when window resized
$(window).resize(this.handleWindowResize);
}
componentWillReceiveProps(nextProps){
// after clicking Load More there will be newProps here
// Re calculate block positions so no error occurs when there are
// all image less blocks
// _.delay(this.setContainerWidth, 2000);
}
componentDidUpdate(prevProps, prevState){
if(this.blockCount != this.props.data.length){
this.setDefaults();
this.setContainerWidth();
}
}
componentWillUnmount(){
$(window).off("resize", this.handleWindowResize);
}
setContainerWidth(){
// setContainerWidth only first time we recieve BlockList data
if(this.wrapperWidth == 0){
this.wrapperWidth = $('.block-container').outerWidth();
this.colCount = Math.round(this.wrapperWidth/this.blockWidth);
$('.block').css('width', this.blockWidth);
this.blockCount = document.getElementsByClassName('block').length;
if(this.blockCount < this.colCount){
this.wrapperWidth = (this.blockWidth*this.blockCount) - ( (this.blockCount - 1) * this.borderWidth);
this.colCount = this.blockCount;
} else {
this.wrapperWidth = (this.blockWidth*this.colCount) - ( (this.colCount - 1) * this.borderWidth);
}
$('.block-container').css('width', this.wrapperWidth);
}
// if wrapperWidth is already calculated than just reset block positions
for( var i = 0; i < this.colCount; i++ )
this.blocks[i] = 0;
this.setBlocks();
}
setBlocks() {
const component = this;
$('.block').each(function(){
var min = Math.min.apply(Math, component.blocks);
var index = $.inArray(min, component.blocks);
var left = index * (component.blockWidth - component.borderWidth) - component.borderWidth;
// for the first blocks that needs to overlap container border
if(left == 0)
left = - component.borderWidth;
// start with overlap on top container border
var top = min + 10 - component.borderWidth;
$(this).css({
'top' : top + 'px',
'left' : left + 'px'
});
component.blocks[index] = top + this.offsetHeight;
});
// set wrapper height
var wrapperHeight = Math.max.apply(Math, this.blocks);
wrapperHeight += this.borderWidth; // block borders
$(".block-container").css("height",wrapperHeight + 'px');
}
renderBlocks() {
const { data } = this.props;
return data.map((pin) => {
return <Block {...pin} key={pin._id} loadHandler={this.throttledSetContainerWidth}/>;
});
}
render() {
return(
<div class="row">
<div class="col-sm-offset-2 col-sm-8 col-xs-offset-1 col-xs-10">
<div class="block-container">
{ this.renderBlocks() }
</div>
</div>
</div>
);
}
}
|
const chalk = require('chalk');
const Sequelize = require('sequelize');
// db server constant(s)
const dbName = 'relationshipVisualizer';
// +(process.env.NODE_ENV === 'testing' ? '_test' : '');
const url = process.env.DATABASE_URL || `postgres://localhost:5432/${dbName}`;
// notify the user we're about to do it
console.log(chalk.yellow(`Opening database connection to ${url}`))
// init the db
const db = new Sequelize(url, {
define: {
freezeTableName: true // don't go changing my table names sequelize!
},
logging: false
});
module.exports = db;
|
var system = require('system');
var args = system.args;
var url = "http://"+args[1],
filename = args[2]+".png",
timeout = args[3],
savePath = args[4],
page = require('webpage').create();
//setTimeout(function(){phantom.exit();}, timeout)
page.viewportSize = { width: 1200, height: 700 };
page.clipRect = { top: 0, left: 0, width: 1200, height: 700 };
var f = false;
page.onLoadFinished = function(status) {
console.log('Status: ' + status);
setTimeout(function(){
render(page);
phantom.exit();
}, 15000)
};
page.onResourceReceived = function(response) {
if (response.url === url && !f) {
setTimeout(function(){
render(page);
phantom.exit();
}, 15000)
f = true
}
};
function render(page) {
var resPath
if (savePath == "") {
resPath = filename
} else {
resPath = savePath + "/" + filename
}
page.render(resPath)
}
console.log("start get " + url)
page.open(url, function() {
});
|
/* globals describe, before, beforeEach, after, afterEach, it */
'use strict';
const chai = require('chai');
const assert = chai.assert;
const expect = chai.expect;
chai.should();
chai.use(require('chai-things')); //http://chaijs.com/plugins/chai-things
chai.use(require('chai-arrays'));
describe('<%= pkgName %>', function () {
before('before', function () {
});
beforeEach('beforeEach', function () {
});
afterEach('afterEach', function () {
});
after('after', function () {
});
describe('Stub test', function () {
it('should have unit test', function () {
assert(false, 'Please add unit tests.');
});
});
});
|
var nums = [];
for (var i = 0; i < 100; ++i) {
nums[i] = Math.floor(Math.random() * 101);
}
insertionsort(nums);
dispArr(nums);
print();
putstr("Enter a value to count: ");
var val = parseInt(readline());
var retVal = count(nums, val);
print("Found " + retVal + " occurrences of " + val + ".");
|
import imageContainer from '../server/api/helpers/imageContainer';
const entries = [
{
html: '<img src="/img/60x30.png" alt="60x30" class="zoom" data-zoom-src="/img/60x30-original.png">',
},
{
html: `<div>
<img src="/img/20x50.jpg">
</div>
<img src="/img/40x10.svg" alt="40x10">`,
},
{
html: '<div>Hello, World!</div>',
},
];
describe('ImageContainer', () => {
const modifiedEntries = imageContainer(entries, __dirname);
it('Parses one image', () => {
expect(modifiedEntries[0].html).toContain('<div class="imageContainer" style="width: 60px;">');
expect(modifiedEntries[0].html).toContain('<div style="padding-bottom: 50%">');
});
it('Parses multiple images', () => {
expect(modifiedEntries[1].html).toContain('<div class="imageContainer" style="width: 20px;">');
expect(modifiedEntries[1].html).toContain('<div style="padding-bottom: 250%">');
expect(modifiedEntries[1].html).toContain('<div class="imageContainer" style="width: 40px;">');
expect(modifiedEntries[1].html).toContain('<div style="padding-bottom: 25%">');
});
it('Doesn’t parse things it shouldn’t', () => {
expect(modifiedEntries[2].html.length).toEqual(entries[2].html.length);
});
it('Doesn’t crash when passing in an empty array', () => {
const emptyEntries = [];
expect(emptyEntries).toEqual(imageContainer(emptyEntries));
});
});
|
// Karma configuration
// http://karma-runner.github.io/0.10/config/configuration-file.html
module.exports = function(config) {
config.set({
// base path, that will be used to resolve files and exclude
basePath: '',
// testing framework to use (jasmine/mocha/qunit/...)
frameworks: ['mocha', 'chai', 'sinon'],
// list of files / patterns to load in the browser
files: [
'app/bower_components/angular/angular.js',
'app/bower_components/angular-mocks/angular-mocks.js',
'app/scripts/*.js',
'app/scripts/**/*.js',
'test/mock/**/*.js',
'test/spec/**/*.js'
],
// list of files / patterns to exclude
exclude: [],
// web server port
port: 8080,
// level of logging
// possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: false,
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
browsers: ['Chrome'],
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun: false
});
};
|
/*
* Reading a variable.
*/
if (typeof print !== 'function') { print = console.log; }
function test() {
function outer() {
var o = 123;
return function inner() {
var i;
var t;
for (i = 0; i < 1e6; i++) {
t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o;
t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o;
t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o;
t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o;
t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o;
t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o;
t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o;
t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o;
t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o;
t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o; t = o;
}
};
}
var f = outer();
f();
}
try {
test();
} catch (e) {
print(e.stack || e);
throw e;
}
|
/*
* Globalize Culture id
*
* http://github.com/jquery/globalize
*
* Copyright Software Freedom Conservancy, Inc.
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* This file was generated by the Globalize Culture Generator
* Translation: bugs found in this file need to be fixed in the generator * Portions (c) Corporate Web Solutions Ltd.
*/
(function( window, undefined ) {
var Globalize;
if ( typeof require !== "undefined" &&
typeof exports !== "undefined" &&
typeof module !== "undefined" ) {
// Assume CommonJS
Globalize = require( "globalize" );
} else {
// Global variable
Globalize = window.Globalize;
}
Globalize.addCultureInfo( "id", "default", {
name: "id",
englishName: "Indonesian",
nativeName: "Bahasa Indonesia",
language: "id",
numberFormat: {
",": ".",
".": ",",
percent: {
",": ".",
".": ","
},
currency: {
decimals: 0,
",": ".",
".": ",",
symbol: "Rp"
}
},
calendars: {
standard: {
firstDay: 1,
days: {
names: ["Minggu","Senin","Selasa","Rabu","Kamis","Jumat","Sabtu"],
namesAbbr: ["Minggu","Sen","Sel","Rabu","Kamis","Jumat","Sabtu"],
namesShort: ["M","S","S","R","K","J","S"]
},
months: {
names: ["Januari","Februari","Maret","April","Mei","Juni","Juli","Agustus","September","Oktober","Nopember","Desember",""],
namesAbbr: ["Jan","Feb","Mar","Apr","Mei","Jun","Jul","Agust","Sep","Okt","Nop","Des",""]
},
AM: null,
PM: null,
patterns: {
d: "dd/MM/yyyy",
D: "dd MMMM yyyy",
t: "H:mm",
T: "H:mm:ss",
f: "dd MMMM yyyy H:mm",
F: "dd MMMM yyyy H:mm:ss",
M: "dd MMMM",
Y: "MMMM yyyy"
}
}
}
});
}( this ));
|
import omit from 'lodash/omit';
import get from 'lodash/get';
import isFunction from 'lodash/isFunction';
import { bunyanLevelToRollbarLevelName } from '../common/rollbar';
// Rollbar script exposes this global immediately, whether or not its already initialized
export const isGlobalRollbarConfigured = () => !!get(global, 'Rollbar');
/**
* Custom rollbar stream that transports to logentries from a browser
* Wortks with a global Rollbar instance that is already initialized.
* Note this expects rollbar to be loaded in the head, not via an npm module.
* See https://rollbar.com/docs/notifier/rollbar.js/#quick-start for details on
* integrating Rollbar in client apps
*
* @param {String} options.token
* @param {String} options.environment
* @param {String} options.codeVersion
*/
export default function ClientRollbarLogger({ token, environment, codeVersion }) {
// Rollbar may already be initialized, but thats ok
// https://rollbar.com/docs/notifier/rollbar.js/configuration/
global.Rollbar.configure({
accessToken: token,
environment,
captureUncaught: true,
captureUnhandledRejections: true,
payload: {
environment,
javascript: {
code_version: codeVersion,
source_map_enabled: true,
},
},
});
}
/**
* Transport logs to Rollbar
* @param {Object} data
* @returns {undefined}
*/
ClientRollbarLogger.prototype.write = function (data = {}) {
const rollbarLevelName = bunyanLevelToRollbarLevelName(data.level);
const scopeData = omit(data, ['err', 'level']);
const payload = Object.assign({ level: rollbarLevelName }, scopeData);
// https://rollbar.com/docs/notifier/rollbar.js/#rollbarlog
const logFn = global.Rollbar[rollbarLevelName];
if (isFunction(logFn)) {
logFn.call(global.Rollbar, data.msg, data.err, payload);
} else {
global.Rollbar.error(data.msg, data.err, payload);
}
};
|
var mongoose = require('mongoose');
var bcrypt = require('bcrypt-nodejs');
// define the schema for our user model
var authUserSchema = mongoose.Schema({
unique_ID : String,
username : String,
password : String,
role : String,
first_name : String,
last_name : String
});
// methods ======================
// generating a hash
authUserSchema.methods.generateHash = function(password) {
return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
};
// checking if password is valid
authUserSchema.methods.validPassword = function(password) {
return bcrypt.compareSync(password, this.password);
};
// create the model for users and expose it to our app
module.exports = mongoose.model('authUser', authUserSchema);
|
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
var Lib = require('../../lib');
// The contour extraction is great, except it totally fails for constraints because we
// need weird range loops and flipped contours instead of the usual format. This function
// does some weird manipulation of the extracted pathinfo data such that it magically
// draws contours correctly *as* constraints.
module.exports = function(pathinfo, operation) {
var i, pi0, pi1;
var op0 = function(arr) { return arr.reverse(); };
var op1 = function(arr) { return arr; };
switch(operation) {
case '][':
case ')[':
case '](':
case ')(':
var tmp = op0;
op0 = op1;
op1 = tmp;
// It's a nice rule, except this definitely *is* what's intended here.
/* eslint-disable: no-fallthrough */
case '[]':
case '[)':
case '(]':
case '()':
/* eslint-enable: no-fallthrough */
if(pathinfo.length !== 2) {
Lib.warn('Contour data invalid for the specified inequality range operation.');
return;
}
// In this case there should be exactly two contour levels in pathinfo. We
// simply concatenate the info into one pathinfo and flip all of the data
// in one. This will draw the contour as closed.
pi0 = pathinfo[0];
pi1 = pathinfo[1];
for(i = 0; i < pi0.edgepaths.length; i++) {
pi0.edgepaths[i] = op0(pi0.edgepaths[i]);
}
for(i = 0; i < pi0.paths.length; i++) {
pi0.paths[i] = op0(pi0.paths[i]);
}
while(pi1.edgepaths.length) {
pi0.edgepaths.push(op1(pi1.edgepaths.shift()));
}
while(pi1.paths.length) {
pi0.paths.push(op1(pi1.paths.shift()));
}
pathinfo.pop();
break;
case '>=':
case '>':
if(pathinfo.length !== 1) {
Lib.warn('Contour data invalid for the specified inequality operation.');
return;
}
// In this case there should be exactly two contour levels in pathinfo. We
// simply concatenate the info into one pathinfo and flip all of the data
// in one. This will draw the contour as closed.
pi0 = pathinfo[0];
for(i = 0; i < pi0.edgepaths.length; i++) {
pi0.edgepaths[i] = op0(pi0.edgepaths[i]);
}
for(i = 0; i < pi0.paths.length; i++) {
pi0.paths[i] = op0(pi0.paths[i]);
}
break;
}
};
|
module.exports = {
defersToPromises : function(defers) {
if(Array.isArray(defers)) {
return defers.map(function(defer) {
return defer && defer.promise ?
defer.promise :
defer;
});
}
var res = {};
Object.keys(defers).forEach(function(key) {
res[key] = defers[key] && defers[key].promise ?
defers[key].promise :
defer;
});
return res;
}
};
|
export default (sequelize, DataTypes) => {
const Product = sequelize.define('Product', {
name: DataTypes.STRING,
description: DataTypes.TEXT,
price: DataTypes.FLOAT,
releasedate: DataTypes.DATE
}, {
classMethods: {
associate: models => {
Product.belongsToMany(models.Cart, {through: 'ProductCart'});
Product.belongsToMany(models.Platform, {through: 'ProductPlatform'});
Product.belongsTo(models.SpecialEdition);
}
}
});
return Product;
};
|
import { SET_SORT_ORDER } from '../constants/actions';
export default function (state = 'ASCENDING', action) {
switch (action.type) {
case SET_SORT_ORDER:
return action.order;
default:
return state;
}
}
|
import mongoose from 'mongoose';
const ModelPortfolioSchema = new mongoose.Schema({
id: String,
name: String,
displayName: String,
email: String,
securities: [{
symbol: String,
allocation: {type: Number, min: 0, max: 100},
}]
});
ModelPortfolioSchema.add({
subGroups: [ModelPortfolioSchema],
modelPortfolios: [ModelPortfolioSchema],
});
export default mongoose.model('ModelPortfolio', ModelPortfolioSchema);
|
define('findScriptUrls', [], function () {
return function(pattern) {
var type = typeof pattern, i, tags = document.querySelectorAll("script"), matches = [], src;
for (i = 0; i < tags.length; i++) {
src = tags[i].src || "";
if (type === "string") {
if (src.indexOf(pattern) !== -1) {
matches.push(src);
}
} else if (pattern.test(src)) {
matches.push(src);
}
}
return matches;
};
});
|
// Karma configuration
// http://karma-runner.github.io/0.12/config/configuration-file.html
// Generated on 2015-05-11 using
// generator-karma 0.8.3
module.exports = function(config) {
'use strict';
config.set({
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// base path, that will be used to resolve files and exclude
basePath: '../',
// testing framework to use (jasmine/mocha/qunit/...)
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'app/scripts/**/*.js',
'test/mock/**/*.js',
'test/spec/**/*.js'
],
// list of files / patterns to exclude
exclude: [],
// web server port
port: 8080,
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
browsers: [
'PhantomJS'
],
// Which plugins to enable
plugins: [
'karma-phantomjs-launcher',
'karma-jasmine'
],
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun: false,
colors: true,
// level of logging
// possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
logLevel: config.LOG_INFO,
// Uncomment the following lines if you are using grunt's server to run the tests
// proxies: {
// '/': 'http://localhost:9000/'
// },
// URL root prevent conflicts with the site root
// urlRoot: '_karma_'
});
};
|
var indexSectionsWithContent =
{
0: "dfrsw~",
1: "drs",
2: "dfrs~",
3: "rs",
4: "w"
};
var indexSectionNames =
{
0: "all",
1: "classes",
2: "functions",
3: "variables",
4: "pages"
};
var indexSectionLabels =
{
0: "All",
1: "Classes",
2: "Functions",
3: "Variables",
4: "Pages"
};
|
var pub = {},
Q,
Knex;
module.exports = function ($inject) {
$inject = $inject || {};
Q = $inject.Q;
Knex = $inject.Knex;
return pub;
};
pub.get = function(tableName) {
var q = Q.defer();
pub.getMetadata(tableName)
.then(function(relations) {
q.resolve(relations[0]);
});
return q.promise;
};
pub.getMetadata = function(tableName) {
return Knex.knex.raw('SELECT ' +
'KCU1.CONSTRAINT_NAME AS FK_CONSTRAINT_NAME, ' +
'KCU1.COLUMN_NAME AS FK_COLUMN_NAME, ' +
'KCU2.CONSTRAINT_NAME AS REFERENCED_CONSTRAINT_NAME, ' +
'KCU2.TABLE_NAME AS REFERENCED_TABLE_NAME, ' +
'KCU2.COLUMN_NAME AS REFERENCED_COLUMN_NAME ' +
'FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS AS RC ' +
'INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KCU1 ' +
'ON KCU1.CONSTRAINT_CATALOG = RC.CONSTRAINT_CATALOG ' +
'AND KCU1.CONSTRAINT_SCHEMA = RC.CONSTRAINT_SCHEMA ' +
'AND KCU1.CONSTRAINT_NAME = RC.CONSTRAINT_NAME ' +
'AND KCU1.TABLE_NAME = RC.TABLE_NAME ' +
'INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS KCU2 ' +
'ON KCU2.CONSTRAINT_CATALOG = RC.UNIQUE_CONSTRAINT_CATALOG ' +
'AND KCU2.CONSTRAINT_SCHEMA = RC.UNIQUE_CONSTRAINT_SCHEMA ' +
'AND KCU2.CONSTRAINT_NAME = RC.UNIQUE_CONSTRAINT_NAME ' +
'AND KCU2.ORDINAL_POSITION = KCU1.ORDINAL_POSITION ' +
'AND KCU2.TABLE_NAME = RC.REFERENCED_TABLE_NAME ' +
'WHERE kcu1.table_name = ?', tableName);
};
|
export default class State {
constructor($rootScope) {
this.$rootScope = $rootScope;
this.state = [];
}
setData(data) {
console.log('state set data', data)
this.state = data;
this.$rootScope.$apply();
}
getData() {
//console.log('state get data', state)
return this.state;
}
}
|
var request = require('request');
var Client = (function () {
function Client() {
this.options = {
"url": "",
"method": "GET",
"bodyParams": {},
"gzip": true,
"json": true
};
}
Client.prototype.connect = function (parent) {
var config = parent.config;
this.configure(config);
this._connector = parent;
parent.logger.trace('Connected to google custom search');
};
Client.prototype.disconnect = function (parent) {
this.config = {};
this.url = '';
this._connector = parent;
parent.logger.trace('Disconnected from google custom search');
};
Client.prototype.configure = function (config) {
if (!config || !config.key)
throw new Error('Configuration is not set.');
this.key = config.key;
this.config = config;
if (config.cx)
this.cx = config.cx;
else if (config.cref)
this.cref = config.cref;
if (!this.cx && !this.cref)
throw new Error('You must provide either cx or cref parameter in your configuration!');
this.url = 'https://www.googleapis.com/customsearch/v1?key=' + this.key;
if (this.cx)
this.url += '&cx=' + this.cx;
else if (this.cref)
this.url += '&cref=' + this.cref;
this.baseUrl = this.url;
return true;
};
Client.prototype.setParameters = function (v) {
if (!v.where)
throw "You need to set a where clause and provide a query ('q') parameter";
if (typeof v.where === 'string' || v.where instanceof String)
v.where = JSON.parse(v.where);
if (!v.where.q) {
throw "You need to provide a query ('q') parameter in where clause.";
}
this._parseParameters(v);
this._creteQuery();
this.url = this.baseUrl + this._query;
return this;
};
Client.prototype.query = function (callback) {
this.options.url = this.url;
return request(this.options, callback);
};
Client.prototype.prepareResults = function (results, model) {
var tmp_results = [];
if (results && results.length) {
for (var i = 0; i < results.length; i++) {
var p_model = this._createIndividualModel(model, results[i]);
tmp_results.push(p_model);
}
}
return tmp_results;
};
Client.prototype._creteQuery = function () {
var params = this._params;
var i = 0;
for (var key in params) {
if (i === 0) {
this._query = '&' + key + '=' + params[key];
}
else {
this._query += '&' + key + '=' + params[key];
}
i++;
}
return this._query;
};
Client.prototype._parseParameters = function (v) {
if (!v.per_page)
v.where.num = 10;
else
v.where.num = v.per_page;
if (!v.skip)
v.where.start = 1;
else
v.where.start = v.skip;
if (v.limit)
v.where.num = v.limit - v.where.start;
if (v.page) {
v.where.start = ((v.page - 1) * v.per_page + 1);
}
if (v.order)
v.where.sort = v.order;
if (v.linkSite)
v.where.linkSite = v.linkSite;
if (v.lowRange)
v.where.lowRange = v.lowRange;
if (v.relatedSite)
v.where.relatedSite = v.relatedSite;
if (v.searchType)
v.where.searchType = v.searchType;
if (v.siteSearch)
v.where.siteSearch = v.siteSearch;
if (v.siteSearchFilter)
v.where.siteSearchFilter = v.siteSearchFilter;
this._params = v.where;
return true;
};
Client.prototype._createIndividualModel = function (Model, data) {
var model = Model.instance(data, true);
model.setPrimaryKey(data.cacheId);
return model;
};
return Client;
})();
exports.Client = Client;
//# sourceMappingURL=client.js.map
|
function* generatorFn() {
yield 'foo';
yield 'bar';
return 'baz';
}
let generatorObject1 = generatorFn();
let generatorObject2 = generatorFn();
console.log(generatorObject1.next()); // { done: false, value: 'foo' }
console.log(generatorObject2.next()); // { done: false, value: 'foo' }
console.log(generatorObject2.next()); // { done: false, value: 'bar' }
console.log(generatorObject1.next()); // { done: false, value: 'bar' }
GeneratorYieldExample03.js
|
// var isWaiting = false;
// var isRunning = false;
// var seconds = 10;
// var countdownTimer;
// var finalCountdown = false;
function GameTimer(game) {
this.seconds = game.timelimit;
this.secondPassed = function() {
if (this.seconds === 0 && !game.gameOver) {
game.endGame();
} else if (!game.gameOver) {
this.seconds--;
$("#timer_num").html(this.seconds);
}
}
var countdownTimer = setInterval('t.secondPassed()', 1000);
}
|
/* global Cervus */
const material = new Cervus.materials.PhongMaterial({
requires: [
Cervus.components.Render,
Cervus.components.Transform
],
texture: Cervus.core.image_loader('../textures/4.png'),
normal_map: Cervus.core.image_loader('../textures/normal2.jpg')
});
const phong_material = new Cervus.materials.PhongMaterial({
requires: [
Cervus.components.Render,
Cervus.components.Transform
]
});
const game = new Cervus.core.Game({
width: window.innerWidth,
height: window.innerHeight,
// clear_color: 'f0f'
// fps: 1
});
game.camera.get_component(Cervus.components.Move).keyboard_controlled = true;
// game.camera.get_component(Cervus.components.Move).mouse_controlled = true;
// By default all entities face the user.
// Rotate the camera to see the scene.
const camera_transform = game.camera.get_component(Cervus.components.Transform);
camera_transform.position = [0, 2, 5];
camera_transform.rotate_rl(Math.PI);
// game.camera.keyboard_controlled = true;
const plane = new Cervus.shapes.Plane();
const plane_transform = plane.get_component(Cervus.components.Transform);
const plane_render = plane.get_component(Cervus.components.Render);
plane_transform.scale = [100, 1, 100];
plane_render.material = phong_material;
plane_render.color = "#eeeeee";
game.add(plane);
const cube = new Cervus.shapes.Box();
const cube_transform = cube.get_component(Cervus.components.Transform);
const cube_render = cube.get_component(Cervus.components.Render);
cube_render.material = material;
cube_render.color = "#00ff00";
cube_transform.position = [0, 0.5, -1];
const group = new Cervus.core.Entity({
components: [
new Cervus.components.Transform()
]
});
game.add(group);
group.add(cube);
//
game.on('tick', () => {
// group.get_component(Cervus.components.Transform).rotate_rl(16/1000);
game.light.get_component(Cervus.components.Transform).position = game.camera.get_component(Cervus.components.Transform).position;
});
|
const SELECTOR_BOOK_IMAGE = '#default > div > div > div > div > section > div:nth-child(2) > ol > li:nth-child(1) > article > div.image_container > a > img';
const puppeteer = require('puppeteer');
let scrapeSite1 = async (browser) => {
const page = await browser.newPage();
await page.goto('http://books.toscrape.com/');
await page.waitFor(1000);
await page.click(SELECTOR_BOOK_IMAGE);
await page.waitFor(2000);
const result = await page.evaluate(() => {
let title = document.querySelector('h1').innerText;
let price = document.querySelector('.price_color').innerText;
return {
title,
price
}
});
return result;
}
let scrape = async () => {
const browser = await puppeteer.launch({ headless: false });
const result = await Promise.all([
scrapeSite1(browser),
scrapeSite1(browser),
scrapeSite1(browser),
scrapeSite1(browser),
scrapeSite1(browser)
]);
await browser.close();
return result;
};
scrape().then((value) => {
console.log(value); // Success!
});
|
var five = require("../lib/johnny-five.js");
var board = new five.Board();
board.on("ready", function() {
var gyro = new five.Gyroscope({
pins: ["I0", "I1"],
freq: 200,
extent: 4
});
gyro.on("acceleration", function(data) {
console.log(data.position);
});
});
|
version https://git-lfs.github.com/spec/v1
oid sha256:d5b913ad3304fa791ac6c6064dcecf37b157290bb0e8292e76aee05bee6dc425
size 3752
|
/**
* Filtering sensitive information
*/
const _ = require('lodash');
/**
* reset option
* @param {string|object|array} opt filter option
* @param {array} filterKeys filter keys
* @param {string|function} replaceChat replace chat or function
* @param {boolean} recursion whether recursive , true of false
*/
const setOption = (option) => {
let filterKeys = ['password', 'token', 'authorization'];
let replaceChat = '*';
let recursion = false;
if (option !== undefined) {
if (typeof option === 'string') {
filterKeys = [option];
} else if (option instanceof Array && option.length > 0) {
filterKeys = option.filter(item => typeof item === 'string');
} else if (_.isPlainObject(option)) {
const { filterKeys: fks, recursion: rcs, replaceChat: rpc } = option;
recursion = !!rcs;
if (fks instanceof Array && fks.length > 0) {
filterKeys = fks.filter(item => typeof item === 'string');
}
if (typeof rpc === 'string') {
replaceChat = rpc;
} else {
replaceChat = '*';
}
} else {
console.error(new Error(`option.filter do not support ${typeof option} type !`));
}
}
return { filterKeys, recursion, replaceChat };
};
/**
* replace by replaceChat
* @param {string} param content to replace
* @param {string|function} replaceChat replace chat or function
*/
const replace = (param, replaceChat) => {
if (typeof replaceChat === 'function') {
return replaceChat(param);
}
return param.replace(/\S/g, '*');
};
/**
* filter log message by option
* @param {*} message logger message
* @param {object} opt filter option
* @param {boolean} hit hit the fileterkeys , default false
*/
const filter = (message, opt, hit = false) => {
const result = message;
const { filterKeys, replaceChat } = opt;
if (_.isPlainObject(result)) {
Object.keys(result).forEach((key) => {
const dHit = hit || filterKeys.indexOf(key) > -1;
result[key] = filter(result[key], opt, dHit);
// if (recursion) {
// result[key] = filter(param, opt, true);
// } else {
// result[key] = replaceChat;
// // replace the value of hit key
// // eslint-disable-next-line no-return-assign
// Object.keys(param).forEach(pk => (filterKeys.indexOf(pk) !== -1 ? result[key] = replaceChat : ''));
// }
});
return result;
} else if (typeof result === 'number') {
return replace(result.toString(), replaceChat);
} else if (result instanceof Array && result.length > 0) {
return result.map(param => filter(param, opt, hit));
}
return replace(result, replaceChat);
};
/**
* filter log message by option do not recursion
* @param {*} message logger message
* @param {object} opt filter option
* @param {array} opt.filterKeys filter keys
* @param {string} opt.replaceChat replace chat or function
*/
const filterNoRecursion = (message, opt) => {
const result = message;
const { filterKeys, replaceChat } = opt;
if (_.isPlainObject(result)) {
Object.keys(result).forEach((key) => {
if (filterKeys.indexOf(key) === -1) {
result[key] = filterNoRecursion(result[key], opt);
} else {
result[key] = replaceChat;
}
});
return result;
} else if (typeof result === 'number') {
return result;
} else if (result instanceof Array && result.length > 0) {
return result;
}
return result;
};
/**
* filter sensitive information
* @param {object} message log message
* @param {*} option filter option
*/
const filteringSensitiveInfo = (message, option = false) => {
if (!option) {
return message;
}
if (typeof option === 'function') {
return option(message);
}
return filterNoRecursion(message, setOption(option));
};
module.exports = {
filteringSensitiveInfo,
setOption,
};
|
describe("The ot object has a forEach method, which allows you: ", function () {
it("To iterate over an array", function () {
var array = [1, 2, 4, 8, 16];
var sum = 0;
var sumIndex = 0;
ot.forEach(array, function (value, index) {
sum += value;
sumIndex += index;
expect(this.context).toBe(true);
}, {context: true});
expect(sum).toBe(1 + 2 + 4 + 8 + 16);
expect(sumIndex).toBe(1 + 2 + 3 + 4);
});
it("To iterate over an object's properties", function () {
var obj = {
prop1: false,
prop2: false,
prop3: false
};
ot.forEach(obj, function (value, key) {
obj[key] = !value;
expect(this.context).toBe(true);
}, {context: true});
expect(obj.prop1).toBe(true);
expect(obj.prop2).toBe(true);
expect(obj.prop3).toBe(true);
});
it("To iterate over user set function properties", function () {
var fnWithProps = function aName() {
};
fnWithProps.prop1 = false;
fnWithProps.prop2 = false;
fnWithProps.prop3 = false;
ot.forEach(fnWithProps, function (value, key) {
fnWithProps[key] = !value;
expect(this.context).toBe(true);
}, {context: true});
expect(fnWithProps.prop1).toBe(true);
expect(fnWithProps.prop2).toBe(true);
expect(fnWithProps.prop3).toBe(true);
});
it("To iterate over an object with a forEach method", function () {
var objectWithForEach = {
forEach: function (iterator, context) {
iterator.call(context, true);
}
};
ot.forEach(objectWithForEach, function(calledFromForEach) {
expect(calledFromForEach).toBe(true);
expect(this.context).toBe(true);
}, {context: true});
});
});
|
import * as types from '../actions/types';
const search = (state = [], action) => {
switch(action.type) {
case types.SEARCH_INPUT_SUCCESS:
return action.data;
case types.SEARCH_INPUT_FAILED:
return action.error.message;
default:
return state;
}
};
export default search;
|
/**
* Created by lee on 10/13/17.
*/
import React, { Component } from 'react';
export default class PlacesItem extends Component {
constructor(props) {
super(props);
this.config = this.config.bind(this);
this.rateStars = this.rateStars.bind(this);
this.startBounce = this.startBounce.bind(this);
this.endBounce = this.endBounce.bind(this);
}
config() {
return {
itemPhotoSize : {
maxWidth: 80,
maxHeight: 91
}
}
}
startBounce() {
this.props.place.marker.setAnimation(google.maps.Animation.BOUNCE);
}
endBounce() {
this.props.place.marker.setAnimation(null);
}
// build rate starts
rateStars(num) {
let stars = [];
for(let i = 0; i < num; i++) {
stars.push(
<span><img key={i} src='./assets/star.png' /></span>
)
}
return stars
}
render() {
const {place} = this.props.place;
const img = place.photos ? place.photos[0].getUrl(this.config().itemPhotoSize) : './assets/no_image.png';
return(
<div className="item-box" onMouseOver = {this.startBounce} onMouseOut={this.endBounce}>
<div className="item-text">
<strong>{place.name}</strong>
{ place.rating ?<p>{this.rateStars(place.rating)}<span> {'$'.repeat(place.price_level)}</span></p> : <p>{'$'.repeat(place.price_level)}</p>
}
<p id="item-address">{place.formatted_address}</p>
<p>{place.opening_hours && place.opening_hours.open_now ? "Open" :"Closed"}</p>
</div>
<img className='item-image' src={img} />
</div>
)
}
}
|
/* eslint import/no-extraneous-dependencies: ["error", {"devDependencies": true}] */
import path from 'path';
import webpack from 'webpack';
import CopyWebpackPlugin from 'copy-webpack-plugin';
import HtmlWebpackPlugin from 'html-webpack-plugin';
export default {
context: __dirname,
entry: './index.jsx',
output: {
path: `${__dirname}/__dev__`,
publicPath: '/',
filename: 'bundle.js',
},
module: {
loaders: [
{
test: /\.(jpe?g|png|gif|svg)$/i,
loaders: [
'file?hash=sha512&digest=hex&name=[hash].[ext]',
'image-webpack?bypassOnDebug&optimizationLevel=7&interlaced=false'
]
},
{ test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel-loader' },
{ test: /\.json$/, loader: 'json-loader' },
{ test: /\.scss$/, loaders: [
'style-loader',
'css-loader',
'sass-loader?includePaths[]=' + path.resolve(__dirname, './node_modules/compass-mixins/lib')
]},
],
},
resolve: {
extensions: ['.js', '.jsx'],
},
plugins: [
new CopyWebpackPlugin([
{ from: '404.html' },
{ from: 'img', to: 'img' },
{ from: 'fonts', to: 'fonts' }
]),
new HtmlWebpackPlugin({
template: 'index.template.ejs',
inject: 'body'
}),
],
};
|
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
info: >
Math.sqrt, recommended that implementations use the approximation
algorithms for IEEE 754 arithmetic contained in fdlibm
es5id: 15.8.2.17_A6
description: >
Checking if Math.sqrt is approximately equals to its mathematical
values on the set of 64 argument values; all the sample values is
calculated with LibC
includes:
- math_precision.js
- math_isequal.js
---*/
// CHECK#1
vnum = 64;
var x = new Array();
x[0] = 0.00000000000000000000;
x[1] = 0.25396825396825395000;
x[2] = 0.50793650793650791000;
x[3] = 0.76190476190476186000;
x[4] = 1.01587301587301580000;
x[5] = 1.26984126984126980000;
x[6] = 1.52380952380952370000;
x[7] = 1.77777777777777770000;
x[8] = 2.03174603174603160000;
x[9] = 2.28571428571428560000;
x[10] = 2.53968253968253950000;
x[11] = 2.79365079365079350000;
x[12] = 3.04761904761904740000;
x[13] = 3.30158730158730140000;
x[14] = 3.55555555555555540000;
x[15] = 3.80952380952380930000;
x[16] = 4.06349206349206330000;
x[17] = 4.31746031746031720000;
x[18] = 4.57142857142857120000;
x[19] = 4.82539682539682510000;
x[20] = 5.07936507936507910000;
x[21] = 5.33333333333333300000;
x[22] = 5.58730158730158700000;
x[23] = 5.84126984126984090000;
x[24] = 6.09523809523809490000;
x[25] = 6.34920634920634890000;
x[26] = 6.60317460317460280000;
x[27] = 6.85714285714285680000;
x[28] = 7.11111111111111070000;
x[29] = 7.36507936507936470000;
x[30] = 7.61904761904761860000;
x[31] = 7.87301587301587260000;
x[32] = 8.12698412698412650000;
x[33] = 8.38095238095238140000;
x[34] = 8.63492063492063440000;
x[35] = 8.88888888888888930000;
x[36] = 9.14285714285714230000;
x[37] = 9.39682539682539720000;
x[38] = 9.65079365079365030000;
x[39] = 9.90476190476190510000;
x[40] = 10.15873015873015800000;
x[41] = 10.41269841269841300000;
x[42] = 10.66666666666666600000;
x[43] = 10.92063492063492100000;
x[44] = 11.17460317460317400000;
x[45] = 11.42857142857142900000;
x[46] = 11.68253968253968200000;
x[47] = 11.93650793650793700000;
x[48] = 12.19047619047619000000;
x[49] = 12.44444444444444500000;
x[50] = 12.69841269841269800000;
x[51] = 12.95238095238095300000;
x[52] = 13.20634920634920600000;
x[53] = 13.46031746031746000000;
x[54] = 13.71428571428571400000;
x[55] = 13.96825396825396800000;
x[56] = 14.22222222222222100000;
x[57] = 14.47619047619047600000;
x[58] = 14.73015873015872900000;
x[59] = 14.98412698412698400000;
x[60] = 15.23809523809523700000;
x[61] = 15.49206349206349200000;
x[62] = 15.74603174603174500000;
x[63] = 16.00000000000000000000;
var y = new Array();
y[0] = 0.00000000000000000000;
y[1] = 0.50395263067896967000;
y[2] = 0.71269664509979835000;
y[3] = 0.87287156094396945000;
y[4] = 1.00790526135793930000;
y[5] = 1.12687233963802200000;
y[6] = 1.23442679969673530000;
y[7] = 1.33333333333333330000;
y[8] = 1.42539329019959670000;
y[9] = 1.51185789203690880000;
y[10] = 1.59363814577919150000;
y[11] = 1.67142178807468980000;
y[12] = 1.74574312188793890000;
y[13] = 1.81702705031799170000;
y[14] = 1.88561808316412670000;
y[15] = 1.95180014589706640000;
y[16] = 2.01581052271587870000;
y[17] = 2.07784992659727900000;
y[18] = 2.13808993529939520000;
y[19] = 2.19667858946110380000;
y[20] = 2.25374467927604400000;
y[21] = 2.30940107675850290000;
y[22] = 2.36374736114111530000;
y[23] = 2.41687191246657520000;
y[24] = 2.46885359939347060000;
y[25] = 2.51976315339484810000;
y[26] = 2.56966429775848400000;
y[27] = 2.61861468283190830000;
y[28] = 2.66666666666666650000;
y[29] = 2.71386797119523940000;
y[30] = 2.76026223736941700000;
y[31] = 2.80588949764880670000;
y[32] = 2.85078658039919340000;
y[33] = 2.89498745782298350000;
y[34] = 2.93852354676981160000;
y[35] = 2.98142396999971960000;
y[36] = 3.02371578407381760000;
y[37] = 3.06542417893925380000;
y[38] = 3.10657265339049320000;
y[39] = 3.14718316987777280000;
y[40] = 3.18727629155838300000;
y[41] = 3.22687130401855570000;
y[42] = 3.26598632371090410000;
y[43] = 3.30463839483761390000;
y[44] = 3.34284357614937950000;
y[45] = 3.38061701891406630000;
y[46] = 3.41797303712883060000;
y[47] = 3.45492517089848670000;
y[48] = 3.49148624377587780000;
y[49] = 3.52766841475278750000;
y[50] = 3.56348322549899170000;
y[51] = 3.59894164336974940000;
y[52] = 3.63405410063598340000;
y[53] = 3.66883053033489940000;
y[54] = 3.70328039909020570000;
y[55] = 3.73741273720925400000;
y[56] = 3.77123616632825340000;
y[57] = 3.80475892484536750000;
y[58] = 3.83798889135426350000;
y[59] = 3.87093360626696680000;
y[60] = 3.90360029179413280000;
y[61] = 3.93599587043272870000;
y[62] = 3.96812698209517300000;
y[63] = 4.00000000000000000000;
var val;
for (i = 0; i < vnum; i++)
{
val = Math.sqrt(x[i]);
if (!isEqual(val, y[i]))
{
$ERROR("\nx = " + x[i] + "\nlibc.sqrt(x) = " + y[i] + "\nMath.sqrt(x) = " + Math.sqrt(x[i]) + "\nMath.abs(libc.sqrt(x) - Math.sqrt(x)) > " + prec + "\n\n");
}
}
|
import http from "http";
import express from "express";
import cors from "cors";
import morgan from "morgan";
import bodyParser from "body-parser";
import initializeDb from "./db";
import middleware from "./middleware";
import api from "./api";
import config from "config"; //we load the db location from the JSON files
let app = express();
app.server = http.createServer(app);
//don't show the log when it is test
if (process.env.NODE_ENV !== "test") {
// logger
app.use(morgan("dev"));
}
// 3rd party middleware
app.use(
cors({
exposedHeaders: config.corsHeaders
})
);
app.use(
bodyParser.json({
limit: config.bodyLimit
})
);
const dbOptions = {
useMongoClient: true
};
// connect to db
initializeDb(config.dbURI, dbOptions, () => {
// internal middleware
app.use(middleware({ config }));
// api router
app.use("/api", api({ config }));
app.server.listen(process.env.PORT || config.port, () => {
console.log(`Started on port ${app.server.address().port}`);
});
});
export default app;
|
import Ember from 'ember';
import PaginatedScrollViewMixin from 'kowa/mixins/paginated-scroll-view';
var PaginatedScrollBox = Ember.View.extend(PaginatedScrollViewMixin);
export default PaginatedScrollBox;
|
import clearSuggestedActions from './actions/clearSuggestedActions';
import connect from './actions/connect';
import createStore, { withDevTools as createStoreWithDevTools } from './createStore';
import disconnect from './actions/disconnect';
import dismissNotification from './actions/dismissNotification';
import emitTypingIndicator from './actions/emitTypingIndicator';
import markActivity from './actions/markActivity';
import postActivity from './actions/postActivity';
import sendEvent from './actions/sendEvent';
import sendFiles from './actions/sendFiles';
import sendMessage from './actions/sendMessage';
import sendMessageBack from './actions/sendMessageBack';
import sendPostBack from './actions/sendPostBack';
import setDictateInterims from './actions/setDictateInterims';
import setDictateState from './actions/setDictateState';
import setLanguage from './actions/setLanguage';
import setNotification from './actions/setNotification';
import setSendBox from './actions/setSendBox';
import setSendTimeout from './actions/setSendTimeout';
import setSendTypingIndicator from './actions/setSendTypingIndicator';
import startDictate from './actions/startDictate';
import startSpeakingActivity from './actions/startSpeakingActivity';
import stopDictate from './actions/stopDictate';
import stopSpeakingActivity from './actions/stopSpeakingActivity';
import submitSendBox from './actions/submitSendBox';
import * as ActivityClientState from './constants/ActivityClientState';
import * as DictateState from './constants/DictateState';
const Constants = { ActivityClientState, DictateState };
const version = process.env.npm_package_version;
export {
clearSuggestedActions,
connect,
Constants,
createStore,
createStoreWithDevTools,
disconnect,
dismissNotification,
emitTypingIndicator,
markActivity,
postActivity,
sendEvent,
sendFiles,
sendMessage,
sendMessageBack,
sendPostBack,
setDictateInterims,
setDictateState,
setLanguage,
setNotification,
setSendBox,
setSendTimeout,
setSendTypingIndicator,
startDictate,
startSpeakingActivity,
stopDictate,
stopSpeakingActivity,
submitSendBox,
version
};
|
var assert = require('assert');
var listXf = require('./helpers/listXf');
var R = require('..');
describe('any', function() {
var odd = function(n) {return n % 2 === 1;};
var T = function() {return true;};
var intoArray = R.into([]);
it('returns true if any element satisfies the predicate', function() {
assert.strictEqual(R.any(odd, [2, 4, 6, 8, 10, 11, 12]), true);
});
it('returns false if all elements fails to satisfy the predicate', function() {
assert.strictEqual(R.any(odd, [2, 4, 6, 8, 10, 12]), false);
});
it('returns true into array if any element satisfies the predicate', function() {
assert.deepEqual(intoArray(R.any(odd), [2, 4, 6, 8, 10, 11, 12]), [true]);
});
it('returns false if all elements fails to satisfy the predicate', function() {
assert.deepEqual(intoArray(R.any(odd), [2, 4, 6, 8, 10, 12]), [false]);
});
it('works with more complex objects', function() {
var people = [{first: 'Paul', last: 'Grenier'}, {first:'Mike', last: 'Hurley'}, {first: 'Will', last: 'Klein'}];
var alliterative = function(person) {return person.first.charAt(0) === person.last.charAt(0);};
assert.strictEqual(R.any(alliterative, people), false);
people.push({first: 'Scott', last: 'Sauyet'});
assert.strictEqual(R.any(alliterative, people), true);
});
it('can use a configurable function', function() {
var teens = [{name: 'Alice', age: 14}, {name: 'Betty', age: 18}, {name: 'Cindy', age: 17}];
var atLeast = function(age) {return function(person) {return person.age >= age;};};
assert.strictEqual(R.any(atLeast(16), teens), true, 'Some can legally drive');
assert.strictEqual(R.any(atLeast(21), teens), false, 'None can legally drink');
});
it('returns false for an empty list', function() {
assert.strictEqual(R.any(T, []), false);
});
it('returns false into array for an empty list', function() {
assert.deepEqual(intoArray(R.any(T), []), [false]);
});
it('dispatches when given a transformer in list position', function() {
assert.deepEqual(R.any(odd, listXf), {
any: false,
f: odd,
xf: listXf
});
});
it('is automatically curried', function() {
var count = 0;
var test = function(n) {count++; return odd(n);};
assert(R.any(test)([2, 4, 6, 7, 8, 10]) === true);
});
});
|
"use strict";
var _slicedToArray = function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { var _arr = []; for (var _iterator = arr[Symbol.iterator](), _step; !(_step = _iterator.next()).done;) { _arr.push(_step.value); if (i && _arr.length === i) break; } return _arr; } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } };
var _createClass = (function () { function defineProperties(target, props) { for (var key in props) { var prop = props[key]; prop.configurable = true; if (prop.value) prop.writable = true; } Object.defineProperties(target, props); } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
var _get = function get(object, property, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc && desc.writable) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } };
var _inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; };
var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } };
exports.alts = alts;
exports.timeout = timeout;
exports.pipelineAsync = pipelineAsync;
// Enforces order resolution on resulting channel
// This might need to be the default behavior, though that requires more thought
exports.order = order;
Object.defineProperty(exports, "__esModule", {
value: true
});
var _channelsJs = require("./channels.js");
var Channel = _channelsJs.Channel;
var Transactor = _channelsJs.Transactor;
var AltsTransactor = (function (_Transactor) {
function AltsTransactor(offer, commitCb) {
_classCallCheck(this, AltsTransactor);
_get(Object.getPrototypeOf(AltsTransactor.prototype), "constructor", this).call(this, offer);
this.commitCb = commitCb;
}
_inherits(AltsTransactor, _Transactor);
_createClass(AltsTransactor, {
commit: {
value: function commit() {
this.commitCb();
return _get(Object.getPrototypeOf(AltsTransactor.prototype), "commit", this).call(this);
}
}
});
return AltsTransactor;
})(Transactor);
function alts(race) {
var outCh = new Channel();
var transactors = race.map(function (cmd) {
var tx = undefined;
if (Array.isArray(cmd)) {
var _cmd;
(function () {
_cmd = _slicedToArray(cmd, 2);
var ch = _cmd[0];
var val = _cmd[1];
tx = new AltsTransactor(val, function () {
transactors.forEach(function (h) {
return h.active = false;
});
});
ch.fill(val, tx).deref(function () {
outCh.fill([val, ch]).deref(function () {
return outCh.close();
});
});
})();
} else {
tx = new AltsTransactor(true, function () {
transactors.forEach(function (h) {
return h.active = false;
});
});
cmd.drain(tx).deref(function (val) {
outCh.fill([val, cmd]).deref(function () {
return outCh.close();
});
});
}
return tx;
});
return outCh;
}
function timeout(ms) {
var ch = new Channel();
setTimeout(function () {
ch.close();
}, ms);
return ch;
}
function pipelineAsync(inch, converter, outch) {
var shouldCloseDownstream = arguments[3] === undefined ? false : arguments[3];
function take(val) {
if (val !== null) {
Promise.resolve(converter(val)).then(function (converted) {
outch.put(converted).then(function (didPut) {
if (didPut) {
inch.take().then(take);
}
});
});
} else if (shouldCloseDownstream) {
outch.close();
}
}
inch.take().then(take);
}
function order(inch, sizeOrBuf) {
var outch = new Channel(sizeOrBuf);
function drain() {
inch.take().then(function (val) {
if (val === null) {
outch.close();
} else {
outch.put(val).then(drain);
}
});
}
drain();
return outch;
}
//# sourceMappingURL=utils.js.map
|
const mutations = {
SET_ACTIVE_TAB(state, tab){
state.activeTab = tab;
},
SET_DATA_ACTIVE_TAB(state, tab){
state.hubActiveTab = tab;
},
SET_PROXY_STATE(state, proxy){
state.proxy_switch = proxy;
},
SET_INIT_INFO(state, info){
_.extend(state, info);
}
};
export default mutations;
|
// home page
exports.index = function(req, res){
res.render('index', { title: 'B O X L A N D' });
};
|
'use strict';
/**
* Module dependencies.
*/
var express = require('express'),
mean = require('meanio'),
consolidate = require('consolidate'),
mongoStore = require('connect-mongo')(express),
flash = require('connect-flash'),
helpers = require('view-helpers'),
config = require('./config'),
expressValidator = require('express-validator'),
appPath = process.cwd(),
fs = require('fs'),
assetmanager = require('assetmanager');
module.exports = function(app, passport, db) {
app.set('showStackError', true);
// Prettify HTML
app.locals.pretty = true;
// cache=memory or swig dies in NODE_ENV=production
app.locals.cache = 'memory';
// Should be placed before express.static
// To ensure that all assets and data are compressed (utilize bandwidth)
app.use(express.compress({
filter: function(req, res) {
return (/json|text|javascript|css/).test(res.getHeader('Content-Type'));
},
// Levels are specified in a range of 0 to 9, where-as 0 is
// no compression and 9 is best compression, but slowest
level: 9
}));
// Only use logger for development environment
if (process.env.NODE_ENV === 'development') {
app.use(express.logger('dev'));
}
// assign the template engine to .html files
app.engine('html', consolidate[config.templateEngine]);
// set .html as the default extension
app.set('view engine', 'html');
// Set views path, template engine and default layout
app.set('views', config.root + '/server/views');
// Enable jsonp
app.enable('jsonp callback');
app.configure(function() {
// The cookieParser should be above session
app.use(express.cookieParser());
// Request body parsing middleware should be above methodOverride
app.use(express.urlencoded());
app.use(express.json());
app.use(expressValidator());
app.use(express.methodOverride());
// Import your asset file
var assets = require('./assets.json');
assetmanager.init({
js: assets.js,
css: assets.css,
debug: (process.env.NODE_ENV !== 'production'),
webroot: 'public/public'
});
// Add assets to local variables
app.use(function(req, res, next) {
res.locals({
assets: assetmanager.assets
});
next();
});
// Express/Mongo session storage
app.use(express.session({
secret: config.sessionSecret,
store: new mongoStore({
db: db.connection.db,
collection: config.sessionCollection
})
}));
// Dynamic helpers
app.use(helpers(config.app.name));
// Use passport session
app.use(passport.initialize());
app.use(passport.session());
//mean middleware from modules before routes
app.use(mean.chainware.before);
// Connect flash for flash messages
app.use(flash());
// Routes should be at the last
app.use(app.router);
// Setting the fav icon and static folder
app.use(express.favicon());
app.use('/public', express.static(config.root + '/public'));
app.get('/modules/aggregated.js', function(req, res) {
res.setHeader('content-type', 'text/javascript');
res.send(mean.aggregated.js);
});
app.get('/modules/aggregated.css', function(req, res) {
res.setHeader('content-type', 'text/css');
res.send(mean.aggregated.css);
});
mean.events.on('modulesFound', function() {
mean.modules.forEach(function(module) {
app.use('/' + module.name, express.static(config.root + '/node_modules/' + module.name + '/public'));
});
bootstrapRoutes();
//mean middlware from modules after routes
app.use(mean.chainware.after);
// Assume "not found" in the error msgs is a 404. this is somewhat
// silly, but valid, you can do whatever you like, set properties,
// use instanceof etc.
app.use(function(err, req, res, next) {
// Treat as 404
if (~err.message.indexOf('not found')) return next();
// Log it
console.error(err.stack);
// Error page
res.status(500).render('500', {
error: err.stack
});
});
// Assume 404 since no middleware responded
app.use(function(req, res) {
res.status(404).render('404', {
url: req.originalUrl,
error: 'Not found'
});
});
});
});
function bootstrapRoutes() {
var routes_path = appPath + '/server/routes';
var walk = function(path) {
fs.readdirSync(path).forEach(function(file) {
var newPath = path + '/' + file;
var stat = fs.statSync(newPath);
if (stat.isFile()) {
if (/(.*)\.(js$|coffee$)/.test(file)) {
require(newPath)(app, passport);
}
// We skip the app/routes/middlewares directory as it is meant to be
// used and shared by routes as further middlewares and is not a
// route by itself
} else if (stat.isDirectory() && file !== 'middlewares') {
walk(newPath);
}
});
};
walk(routes_path);
}
};
|
version https://git-lfs.github.com/spec/v1
oid sha256:b51623fcae1419d2bb29084e11d56fc9aafae7b0e35bd2a7fd30633a133bef40
size 24229
|
var gif_bgs = [];
var gif_center = [];
var length_bgs = 0;
var length_center = 0;
var timer;
var duration = 4000;
var loaded = 0;
var next_bg;
var next_center;
var audio = document.getElementById("sound");
var muted = false;
function next(e){
clearInterval(timer);
timer = setInterval(next, duration);
$("#background").css("background-image","url("+gif_bgs[next_bg]+")");
$("#center").css("background-image","url("+gif_center[next_center]+")");
next_bg = Math.floor( Math.random()*length_bgs );
next_center = Math.floor( Math.random()*length_center );
$("#load_bg").attr("src",gif_bgs[next_bg]);
$("#load_center").attr("src",gif_center[next_center]);
}
function toggleInfo(){
$("#info-overlay").toggleClass("show");
$("#info-btn").toggleClass("show");
}
function check(){
if (loaded > 1) {
next_bg = Math.floor( Math.random()*length_bgs );
next_center = Math.floor( Math.random()*length_center );
next();
$("#wrapper").click(next);
}
}
function toggleSound(){
if (muted) {
muted = false;
audio.muted = muted;
$("#sound-btn").removeClass('muted');
}else{
muted = true;
audio.muted = muted;
$("#sound-btn").addClass('muted');
}
}
function init() {
$("#info-btn").click(toggleInfo);
$("#sound-btn").click(toggleSound);
$.ajax({
url: "json/bg.json",
cache: false,
dataType: "json",
success: function(d){
gif_bgs = d;
length_bgs = gif_bgs.length;
loaded++;
check();
}
});
$.ajax({
url: "json/center.json",
cache: false,
dataType: "json",
success: function(d){
gif_center = d;
length_center = gif_center.length;
loaded++;
check();
}
});
}
Meteor.startup(function(){init();});
|
// -------------------------------------------------------------
// WARNING: this file is used by both the client and the server.
// Do not use any browser or node-specific API!
// -------------------------------------------------------------
/* eslint hammerhead/proto-methods: 2 */
import reEscape from '../utils/regexp-escape';
import INTERNAL_ATTRS from '../processing/dom/internal-attributes';
import { isSpecialPage } from '../utils/url';
const SOURCE_MAP_RE = /#\s*sourceMappingURL\s*=\s*[^\s]+(\s|\*\/)/i;
const CSS_URL_PROPERTY_VALUE_PATTERN = /(url\s*\(\s*)(?:(')([^\s']*)(')|(")([^\s"]*)(")|([^\s\)]*))(\s*\))|(@import\s+)(?:(')([^\s']*)(')|(")([^\s"]*)("))/g;
const STYLESHEET_PROCESSING_START_COMMENT = '/*hammerhead|stylesheet|start*/';
const STYLESHEET_PROCESSING_END_COMMENT = '/*hammerhead|stylesheet|end*/';
const HOVER_PSEUDO_CLASS_RE = /\s*:\s*hover(\W)/gi;
const PSEUDO_CLASS_RE = new RegExp(`\\[${ INTERNAL_ATTRS.hoverPseudoClass }\\](\\W)`, 'ig');
const IS_STYLE_SHEET_PROCESSED_RE = new RegExp(`^\\s*${ reEscape(STYLESHEET_PROCESSING_START_COMMENT) }`, 'gi');
const STYLESHEET_PROCESSING_COMMENTS_RE = new RegExp(`^\\s*${ reEscape(STYLESHEET_PROCESSING_START_COMMENT) }\n?|` +
`\n?${ reEscape(STYLESHEET_PROCESSING_END_COMMENT) }\\s*$`, 'gi');
class StyleProcessor {
constructor () {
this.STYLESHEET_PROCESSING_START_COMMENT = STYLESHEET_PROCESSING_START_COMMENT;
this.STYLESHEET_PROCESSING_END_COMMENT = STYLESHEET_PROCESSING_END_COMMENT;
}
process (css, urlReplacer, isStylesheetTable) {
if (!css || typeof css !== 'string' || IS_STYLE_SHEET_PROCESSED_RE.test(css))
return css;
var prefix = isStylesheetTable ? STYLESHEET_PROCESSING_START_COMMENT + '\n' : '';
var postfix = isStylesheetTable ? '\n' + STYLESHEET_PROCESSING_END_COMMENT : '';
// NOTE: Replace the :hover pseudo-class.
css = css.replace(HOVER_PSEUDO_CLASS_RE, '[' + INTERNAL_ATTRS.hoverPseudoClass + ']$1');
// NOTE: Remove the ‘source map’ directive.
css = css.replace(SOURCE_MAP_RE, '$1');
// NOTE: Replace URLs in CSS rules with proxy URLs.
return prefix + this._replaceStylsheetUrls(css, urlReplacer) + postfix;
}
cleanUp (css, parseProxyUrl) {
if (typeof css !== 'string')
return css;
css = css
.replace(PSEUDO_CLASS_RE, ':hover$1')
.replace(STYLESHEET_PROCESSING_COMMENTS_RE, '');
return this._replaceStylsheetUrls(css, url => {
var parsedProxyUrl = parseProxyUrl(url);
return parsedProxyUrl ? parsedProxyUrl.destUrl : url;
});
}
_replaceStylsheetUrls (css, processor) {
return css.replace(
CSS_URL_PROPERTY_VALUE_PATTERN,
(match, prefix1, openQuote1, url1, closeQuote1, openQuote2, url2, closeQuote2, url3, postfix,
prefix2, openQuote3, url4, closeQuote3, openQuote4, url5, closeQuote4) => {
var prefix = prefix1 || prefix2;
var openQuote = openQuote1 || openQuote2 || openQuote3 || openQuote4 || '';
var url = url1 || url2 || url3 || url4 || url5;
var closeQuote = closeQuote1 || closeQuote2 || closeQuote3 || closeQuote4 || '';
postfix = postfix || '';
var processedUrl = isSpecialPage(url) ? url : processor(url);
return url ? prefix + openQuote + processedUrl + closeQuote + postfix : match;
}
);
}
}
export default new StyleProcessor();
|
import announcements from './announcements'
import delegates from './delegates'
import fees from './fees'
import ledger from './ledger'
import market from './market'
import peer from './peer'
import wallets from './wallets'
export {
announcements,
delegates,
fees,
ledger,
market,
peer,
wallets
}
|
/**
* @flow
* @module ProductPropertyInput
* @extends React.PureComponent
*
* @author Oleg Nosov <olegnosov1@gmail.com>
* @license MIT
*
* @description
* React form for product property(options select only).
*
*/
import React, { PureComponent } from "react";
import { isObject } from "../../../helpers";
import type {
GetLocalization,
InputEvent,
ProductPropertyOption,
Prices,
} from "../../../types";
/**
* @typedef {Object.<string, number>} OptionIndex
*/
export type OptionIndex = {
[propertyName: string]: number,
};
/**
* @typedef {Object} OptionObject
*/
export type OptionObject = {|
onSelect?: (option: OptionObject) => void,
additionalCost?: Prices,
value: ProductPropertyOption,
|};
/** @ */
export type PropertyOption = ProductPropertyOption | OptionObject;
/** @ */
export type PropertyOptions = Array<PropertyOption>;
/** @ */
export type OnChange = (obj: { value: OptionIndex }) => void;
export type Props = {|
name: string,
options: PropertyOptions,
selectedOptionIndex: number,
currency: string,
onChange: OnChange,
getLocalization: GetLocalization,
|};
const defaultProps = {
selectedOptionIndex: 0,
};
export default class ProductPropertyInput extends PureComponent<Props, void> {
props: Props;
static defaultProps = defaultProps;
static displayName = "ProductPropertyInput";
/*
* If option value is an object, we need to extract primitive value
*/
static getOptionValue = (value: PropertyOption): ProductPropertyOption =>
isObject(value) ? ProductPropertyInput.getOptionValue(value.value) : value;
/*
* Generate select input options based on options values
*/
static generateOptionsSelectionList = (
options: PropertyOptions,
getLocalization: GetLocalization,
currency: string,
localizationScope: Object = {},
): Array<React$Element<*>> =>
options
.map(ProductPropertyInput.getOptionValue)
.map((optionValue, index) => (
<option key={optionValue} value={optionValue}>
{typeof optionValue === "string"
? getLocalization(optionValue, {
...localizationScope,
...(isObject(options[index])
? {
cost:
(isObject(options[index].additionalCost) &&
options[index].additionalCost[currency]) ||
0,
}
: {}),
})
: optionValue}
</option>
));
handleSelectInputValueChange = ({ currentTarget }: InputEvent) => {
const { value: optionValue } = currentTarget;
const { name, options, onChange } = this.props;
const { getOptionValue } = ProductPropertyInput;
const selectedOptionIndex = options
.map(getOptionValue)
.indexOf(optionValue);
const selectedOption = options[selectedOptionIndex];
if (
isObject(selectedOption) &&
typeof selectedOption.onSelect === "function"
)
selectedOption.onSelect(selectedOption);
onChange({
value: { [name]: selectedOptionIndex },
});
};
render() {
const {
name,
options,
selectedOptionIndex,
currency,
getLocalization,
} = this.props;
const { handleSelectInputValueChange } = this;
const {
generateOptionsSelectionList,
getOptionValue,
} = ProductPropertyInput;
const localizationScope = {
name,
currency,
get localizedName() {
return getLocalization(name, localizationScope);
},
get localizedCurrency() {
return getLocalization(currency, localizationScope);
},
};
return (
<div className="form-group row">
<label
htmlFor={name}
className="col-xs-3 col-sm-3 col-md-3 col-lg-3 col-form-label"
>
{getLocalization("propertyLabel", localizationScope)}
</label>
<div className="col-xs-9 col-sm-9 col-md-9 col-lg-9">
<select
onChange={handleSelectInputValueChange}
className="form-control"
value={getOptionValue(options[selectedOptionIndex | 0])}
>
{generateOptionsSelectionList(
options,
getLocalization,
currency,
localizationScope,
)}
</select>
</div>
</div>
);
}
}
|
import React, { Component, PropTypes } from 'react'
import { Search, Grid } from 'semantic-ui-react'
import { browserHistory } from 'react-router'
import Tag from './Tag'
import { search, setQuery, clearSearch } from '../actions/entities'
import { MIN_CHARACTERS, DONE_TYPING_INTERVAL } from '../constants/search'
const propTypes = {
dispatch: PropTypes.func.isRequired,
search: PropTypes.object.isRequired
}
const resultRenderer = ({ name, type, screenshots }) => {
return (
<Grid>
<Grid.Column floated="left" width={12}>
<Tag name={name} type={type} />
</Grid.Column>
<Grid.Column floated="right" width={4} textAlign="right">
<small className="text grey">{screenshots.length}</small>
</Grid.Column>
</Grid>
)
}
class GlobalSearch extends Component {
state = {
typingTimer: null
}
handleSearchChange = (e, value) => {
clearTimeout(this.state.typingTimer)
this.setState({
typingTimer: setTimeout(
() => this.handleDoneTyping(value.trim()),
DONE_TYPING_INTERVAL
)
})
const { dispatch } = this.props
dispatch(setQuery(value))
}
handleDoneTyping = value => {
if (value.length < MIN_CHARACTERS) return
const { dispatch } = this.props
dispatch(search({ query: value }))
}
handleResultSelect = (e, item) => {
const { dispatch } = this.props
const { name } = item
dispatch(clearSearch())
browserHistory.push(`/tag/${name}`)
}
render() {
const { search } = this.props
const { query, results } = search
return (
<Search
minCharacters={MIN_CHARACTERS}
onSearchChange={this.handleSearchChange}
onResultSelect={this.handleResultSelect}
resultRenderer={resultRenderer}
results={results}
value={query}
/>
)
}
}
GlobalSearch.propTypes = propTypes
export default GlobalSearch
|
<<<<<<< HEAD
var xmlDoc;
var xmlloaded = false;
var _finalUrl;
/*
* input: none
* output: none
* gets zipcode from the zipcode text field
*/
function createURL() {
var zip = document.getElementById("zipcode").value;
var format = "&format=xml"
var _clientId = "&client_id=API KEY";
var _url = "https://api.seatgeek.com/2/recommendations?events.id=1162104&postal_code=";
_finalUrl = _url + zip + _clientId + format;
// document.getElementById("displayURL").innerHTML = _finalUrl; // debugging
}
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
// ready states 1-4 & status 200 = okay
// 0: uninitialized
// 1: loading
// 2: loaded
// 3: interactive
// 4: complete
if (xhttp.readyState == 4 && xhttp.status == 200) {
myFunction(xhttp);
}
};
var zip = document.getElementById("zipcode").value;
var format = "&format=xml"
var _clientId = "&client_id=API KEY";
var _url = "https://api.seatgeek.com/2/recommendations?events.id=1162104&postal_code=";
_finalUrl = _url + zip + _clientId + format;
xhttp.open("GET", _finalUrl, true);
xhttp.send();
}
function myFunction(xml) {
var i, buyTickets;
var xmlDoc = xml.responseXML;
var x = xmlDoc.getElementsByTagName("recommendations");
for (i = 0; i < x.length; i++) {
buyTickets = x[i].getElementsByTagName("url")[2].childNodes[0].nodeValue;
}
document.getElementById("demo").innerHTML = window.open(buyTickets);
}
|
// Copyright 2015 LastLeaf, LICENSE: github.lastleaf.me/MIT
'use strict';
var fs = require('fs');
var fse = require('fs-extra');
var async = require('async');
var User = fw.module('/db_model').User;
var exports = module.exports = function(conn, res, args){
User.checkPermission(conn, 'admin', function(perm){
if(!perm) return res.err('noPermission');
res.next();
});
};
exports.list = function(conn, res){
// read site list
var sitesDir = conn.app.config.app.siteRoot + '/xbackup/';
fs.readdir(sitesDir, function(err, files){
if(err) return res.err('system');
var sites = files.sort();
// list available backup files
var details = [];
var local = null;
async.eachSeries(sites, function(site, cb){
var siteDir = sitesDir + site;
if(site !== 'local' && site.slice(-5) !== '.site') return cb();
fs.readdir(siteDir, function(err, files){
if(err) return cb('system');
var zips = [];
for(var i=0; i<files.length; i++) {
var match = files[i].match(/^(.*?)\.xbackup\.zip(\.enc|)$/);
if(match) {
var ft = match[1].replace(/^([0-9]+)-([0-9]+)-([0-9]+)_([0-9]+)-([0-9]+)-([0-9]+)/, function(m, m1, m2, m3, m4, m5, m6){
return m1 + '-' + m2 + '-' + m3 + ' ' + m4 + ':' + m5 + ':' + m6;
});
zips.push({
file: files[i],
timeString: ft
});
}
}
if(site === 'local') {
local = zips;
} else details.push({
domain: site.slice(0, -5),
files: zips
});
cb();
});
}, function(err){
if(err) return res.err('system');
res({
local: local,
sites: details
});
});
});
};
exports.modify = function(conn, res, args){
var addSites = String(args.add).match(/\S+/g) || [];
var removeSites = String(args.remove).match(/\S+/g) || [];
async.eachSeries(removeSites, function(site, cb){
var dir = conn.app.config.app.siteRoot + '/xbackup/' + site + '.site';
fse.remove(dir, function(){
cb();
});
}, function(){
async.eachSeries(addSites, function(site, cb){
var dir = conn.app.config.app.siteRoot + '/xbackup/' + site + '.site';
fs.mkdir(dir, function(){
cb();
});
}, function(){
res();
});
});
};
|
var axios = require("axios");
var expect = require("chai").expect;
var MockAdapter = require("../src");
describe("MockAdapter asymmetric matchers", function () {
var instance;
var mock;
beforeEach(function () {
instance = axios.create();
mock = new MockAdapter(instance);
});
it("mocks a post request with a body matching the matcher", function () {
mock
.onPost("/anyWithBody", {
asymmetricMatch: function (actual) {
return actual.params === "1";
},
})
.reply(200);
return instance
.post("/anyWithBody", { params: "1" })
.then(function (response) {
expect(response.status).to.equal(200);
});
});
it("mocks a post request with a body not matching the matcher", function () {
mock
.onPost("/anyWithBody", {
asymmetricMatch: function (actual) {
return actual.params === "1";
},
})
.reply(200);
return instance
.post("/anyWithBody", { params: "2" })
.catch(function (error) {
expect(error.message).to.eq("Request failed with status code 404");
});
});
});
|
'use strict';
var intlNameInitials = function () {
};
var pattern = '{0}{1}';
function _firstLetter(text) {
return text.charAt(0);
}
function _upperCase(letter) {
if (letter === 'ı'){
return 'I';
}
return letter.toUpperCase();
}
function _isHangul(l){
if ((l > 44032) && (l < 55203)) {
return true;
}
return false;
}
function _initials(letter) {
var l = letter.charCodeAt(0);
// Generated by regenerate and unicode-8.0.0
// Greek 117
// Latin 991
// Cyrillic 302
var alphaRegex = '[A-Za-z\xAA\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02B8\u02E0-\u02E4\u0370-\u0373\u0375-\u0377\u037A-\u037D\u037F\u0384\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03E1\u03F0-\u0484\u0487-\u052F\u1D00-\u1D25\u1D2C-\u1D5C\u1D62-\u1D65\u1D6B-\u1D77\u1D79-\u1DBE\u1E00-\u1EFE]';
var re = new RegExp(alphaRegex,'i');
if (re.test(letter)){
return letter;
}
return '';
}
function _isSupportedInitials(letter) {
var alphaRegex = '[A-Za-z\xAA\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02B8\u02E0-\u02E4\u0370-\u0373\u0375-\u0377\u037A-\u037D\u037F\u0384\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03E1\u03F0-\u0484\u0487-\u052F\u1D00-\u1D25\u1D2C-\u1D5C\u1D62-\u1D65\u1D6B-\u1D77\u1D79-\u1DBE\u1E00-\u1EFE]';
var re = new RegExp(alphaRegex,'i');
if (re.test(letter)){
return true;
}
return false;
}
function isThai(a){
var thaiRegex = '[\u0E01-\u0E3A\u0E40-\u0E5B]';
var re = new RegExp(thaiRegex,'i');
if (a.length === 1){
return true;
} else {
var letter = _firstLetter(a);
if (re.test(a)) {
return true;
}
}
return false;
}
function isCJK(a){
// HANGUL SYLLABLES
// We want to be sure the full name is Hangul
if (a.length < 3){
var i = 0;
for(var c=0;c< a.length;c++){
if (_isHangul(a.charCodeAt(c)) )
{
i++;
}
}
if (i === a.length){
return true;
}
}
return false;
}
intlNameInitials.prototype.format = function (name, options) {
var initials = '',
a = '',
b = '';
var fields = ['firstName', 'lastName'],
initialName = { firstName : '', lastName: '' };
if (name === null || typeof name !== 'object' ) {
return undefined;
}
fields.forEach(function(field){
if (name.hasOwnProperty(field)) {
if (name[field] === null || name[field].length === 0){
// Nothing to do. but keeping it as placeholder
} else {
if (_isSupportedInitials(_firstLetter(name[field]))) {
initialName[field] = _firstLetter(name[field]);
initials = initials + _upperCase(_initials(initialName[field]));
}
}
}
});
// for CJK
if (name.hasOwnProperty("lastName")){
if (name.lastName === null || name.lastName.length === 0){
} else {
if (isCJK(name.lastName)) {
initials = name.lastName;
}
}
}
if (initials.length === 0){
return undefined;
}
return initials;
};
module.exports = intlNameInitials;
|
export default [
{
radius: 6,
sizeReduction: .85,
branchProbability: 0.12,
rotation: new THREE.Vector3(0, 1, 0),
color: 'blue'
},{
radius: 6,
sizeReduction: .85,
branchProbability: 0.21,
rotation: new THREE.Vector3(0, 1, 0),
color: 'blue'
},{
radius: 3,
sizeReduction: .87,
branchProbability: 0.25,
rotation: new THREE.Vector3(0, 1, 0),
color: 'blue'
}, {
radius: 7,
sizeReduction: .82,
branchProbability: 0.22,
rotation: new THREE.Vector3(0, 1, 0),
color: 'blue'
},{
radius: 7,
sizeReduction: .82,
branchProbability: 0.22,
rotation: new THREE.Vector3(0, 1, 0),
color: 'blue'
},{
radius: 7,
sizeReduction: .82,
branchProbability: 0.27,
rotation: new THREE.Vector3(0, 1, 0),
color: 'blue'
},
{
radius: 10,
sizeReduction: .9,
branchProbability: 0.2,
rotation: new THREE.Vector3(0, 1, 0),
color: 'pink'
},{
radius: 10,
sizeReduction: .75,
branchProbability: 0.3,
rotation: new THREE.Vector3(0, 1, 0),
color: 'pink'
}
];
|
setTimeout(() => {
import(/* webpackPreload: true */ "./lazy-chunk-2.js").then((mod) =>
mod.test()
);
}, 750);
|
var Purest = require('purest');
function Facebook(opts) {
this._opts = opts || {};
this._opts.provider = 'facebook';
this._purest = new Purest(this._opts);
this._group = 'LIB:SOCIAL:FACEBOOK';
return this;
}
Facebook.prototype.user = function (cb) {
var self = this;
this._purest.query()
.get('me')
.auth(this._opts.auth.token)
.request(function (err, res, body) {
if (err) {
console.log(err);
return cb(err);
}
cb(null, body);
});
};
Facebook.prototype.post = function (endpoint, form, cb) {
// form = {message: 'post message'}
this._purest.query()
.post(endpoint || 'me/feed')
.auth(this._opts.auth.token)
.form(form)
.request(function (err, res, body) {
if (err) {
console.log(err);
return cb(err);
}
cb(null, body);
});
};
module.exports = function(app) {
return Facebook;
};
|
/* vim: set syntax=javascript ts=8 sts=8 sw=8 noet: */
/*
* Copyright 2016, Joyent, Inc.
*/
var BINDING = require('./lockfd_binding');
function
check_arg(pos, name, value, type)
{
if (typeof (value) !== type) {
throw (new Error('argument #' + pos + ' (' + name +
') must be of type ' + type));
}
}
function
lockfd(fd, callback)
{
check_arg(1, 'fd', fd, 'number');
check_arg(2, 'callback', callback, 'function');
BINDING.lock_fd(fd, 'write', false, function (ret, errmsg, errno) {
var err = null;
if (ret === -1) {
err = new Error('File Locking Error: ' + errmsg);
err.code = errno;
}
setImmediate(callback, err);
});
}
function
lockfdSync(fd)
{
var cb_fired = false;
var err;
check_arg(1, 'fd', fd, 'number');
BINDING.lock_fd(fd, 'write', true, function (ret, errno, errmsg) {
cb_fired = true;
if (ret === -1) {
err = new Error('File Locking Error: ' + errmsg);
err.__errno = errno;
return;
}
});
if (!cb_fired) {
throw (new Error('lockfdSync: CALLBACK NOT FIRED'));
} else if (err) {
throw (err);
}
return (null);
}
function
flock(fd, op, callback)
{
check_arg(1, 'fd', fd, 'number');
check_arg(2, 'op', op, 'number');
check_arg(3, 'callback', callback, 'function');
BINDING.flock(fd, op, false, function (ret, errmsg, errno) {
var err = null;
if (ret === -1) {
err = new Error('File Locking Error: ' + errmsg);
err.code = errno;
}
setImmediate(callback, err);
});
}
function
flockSync(fd, op)
{
var cb_fired = false;
var err;
check_arg(1, 'fd', fd, 'number');
check_arg(2, 'op', op, 'number');
BINDING.flock(fd, op, true, function (ret, errmsg, errno) {
cb_fired = true;
if (ret === -1) {
err = new Error('File Locking Error: ' + errmsg);
err.code = errno;
return;
}
});
if (!cb_fired) {
throw (new Error('flockSync: CALLBACK NOT FIRED'));
} else if (err) {
throw (err);
}
return (null);
}
module.exports = {
LOCK_SH: 1,
LOCK_EX: 2,
LOCK_NB: 4,
LOCK_UN: 8,
flock: flock,
flockSync: flockSync,
lockfd: lockfd,
lockfdSync: lockfdSync
};
|
Template.postSubmit.onCreated(function() {
Session.set('postSubmitErrors', {});
});
Template.postSubmit.helpers({
errorMessage: function(field) {
return Session.get('postSubmitErrors')[field];
},
errorClass: function (field) {
return !!Session.get('postSubmitErrors')[field] ? 'has-error' : '';
}
});
Template.postSubmit.onRendered(function(){
// AutoForm.hooks({
// postSubmitForm: hooksObject
// });
});
// Template.postSubmit.events({
// 'submit form': function(e) {
// e.preventDefault();
// var post = {
// url: $(e.target).find('[name=url]').val(),
// title: $(e.target).find('[name=title]').val()
// };
// var errors = validatePost(post);
// if (errors.title || errors.url)
// return Session.set('postSubmitErrors', errors);
// Meteor.call('postInsert', post, function(error, result) {
// // display the error to the user and abort
// if (error)
// return throwError(error.reason);
// // show this result but route anyway
// if (result.postExists)
// throwError('This link has already been posted');
// Router.go('postPage', {_id: result._id});
// });
// }
// });
|
version https://git-lfs.github.com/spec/v1
oid sha256:c4d5490597798effaf63d11e546f0b200f196f28e17c69d39ce236de0c6683f0
size 64139
|
(function() {
var $, expect, fruits;
$ = require('../');
expect = require('expect.js');
/*
Examples
*/
fruits = '<ul id = "fruits">\n <li class = "apple">Apple</li>\n <li class = "orange">Orange</li>\n <li class = "pear">Pear</li>\n</ul>'.replace(/(\n|\s{2})/g, '');
/*
Tests
*/
describe('$(...)', function() {
describe('.find', function() {
it('() : should return this', function() {
return expect($('ul', fruits).find()[0].name).to.equal('ul');
});
it('(single) : should find one descendant', function() {
return expect($('#fruits', fruits).find('.apple')[0].attribs["class"]).to.equal('apple');
});
it('(many) : should find all matching descendant', function() {
return expect($('#fruits', fruits).find('li')).to.have.length(3);
});
it('(many) : should merge all selected elems with matching descendants');
it('(invalid single) : should return empty if cant find', function() {
return expect($('ul', fruits).find('blah')).to.have.length(0);
});
return it('should return empty if search already empty result', function() {
return expect($('#fruits').find('li')).to.have.length(0);
});
});
describe('.children', function() {
it('() : should get all children', function() {
return expect($('ul', fruits).children()).to.have.length(3);
});
it('(selector) : should return children matching selector', function() {
return expect($('ul', fruits).children('.orange').hasClass('orange')).to.be.ok;
});
it('(invalid selector) : should return empty', function() {
return expect($('ul', fruits).children('.lulz')).to.have.length(0);
});
return it('should only match immediate children, not ancestors');
});
describe('.next', function() {
it('() : should return next element', function() {
return expect($('.orange', fruits).next().hasClass('pear')).to.be.ok;
});
return it('(no next) : should return null (?)');
});
describe('.prev', function() {
it('() : should return previous element', function() {
return expect($('.orange', fruits).prev().hasClass('apple')).to.be.ok;
});
return it('(no prev) : should return null (?)');
});
describe('.siblings', function() {
it('() : should get all the siblings', function() {
return expect($('.orange', fruits).siblings()).to.have.length(2);
});
return it('(selector) : should get all siblings that match the selector', function() {
return expect($('.orange', fruits).siblings('li')).to.have.length(2);
});
});
describe('.each', function() {
return it('( (i, elem) -> ) : should loop selected returning fn with (i, elem)', function() {
var items;
items = [];
$('li', fruits).each(function(i, elem) {
return items[i] = elem;
});
expect(items[0].attribs["class"]).to.equal('apple');
expect(items[1].attribs["class"]).to.equal('orange');
return expect(items[2].attribs["class"]).to.equal('pear');
});
});
describe('.first', function() {
it('() : should return the first item', function() {
var elem, src;
src = $("<span>foo</span><span>bar</span><span>baz</span>");
elem = src.first();
expect(elem.length).to.equal(1);
return expect(elem.html()).to.equal('foo');
});
return it('() : should return an empty object for an empty object', function() {
var first, src;
src = $();
first = src.first();
expect(first.length).to.equal(0);
return expect(first.html()).to.be(null);
});
});
describe('.last', function() {
it('() : should return the last element', function() {
var elem, src;
src = $("<span>foo</span><span>bar</span><span>baz</span>");
elem = src.last();
expect(elem.length).to.equal(1);
return expect(elem.html()).to.equal('baz');
});
return it('() : should return an empty object for an empty object', function() {
var last, src;
src = $();
last = src.last();
expect(last.length).to.equal(0);
return expect(last.html()).to.be(null);
});
});
describe('.first & .last', function() {
return it('() : should return same object if only one object', function() {
var first, last, src;
src = $("<span>bar</span>");
first = src.first();
last = src.last();
expect(first.html()).to.equal(last.html());
expect(first.length).to.equal(1);
expect(first.html()).to.equal('bar');
expect(last.length).to.equal(1);
return expect(last.html()).to.equal('bar');
});
});
return describe('.eq', function() {
return it('(i) : should return the element at the specified index', function() {
expect($('li', fruits).eq(0).text()).to.equal('Apple');
expect($('li', fruits).eq(1).text()).to.equal('Orange');
expect($('li', fruits).eq(2).text()).to.equal('Pear');
expect($('li', fruits).eq(3).text()).to.equal('');
return expect($('li', fruits).eq(-1).text()).to.equal('Pear');
});
});
});
}).call(this);
|
(function(){
'use strict';
function ListService($http){
this.getList = function(list_id){
return $http.get('/lists/' + list_id + ".json")
}
}
ListService.$inject = ['$http']
angular
.module('app')
.service('ListService', ListService)
}())
|
angular.module('movieApp')
.directive('movieResult', function () {
var directive = {
restrict: 'E',
replace: true,
scope: {
result: '=result'
},
template: [
'<div class="row">',
'<div class="col-sm-4">',
'<img ng-src="{{result.Poster}}" alt="{{result.Title}}" width="220px">',
'</div>',
'<div class="col-sm-8">',
'<h3>{{result.Title}}</h3>',
'<p>{{result.Plot}}</p>',
'<p><strong>Director:</strong> {{result.Director}}</p>',
'<p><strong>Actors:</strong> {{result.Actors}}</p>',
'<p><strong>Released:</strong> {{result.Released}} ({{result.Released | fromNow}})</p>',
'<p><strong>Genre:</strong> {{result.Genre}}</p>',
'</div>',
'</div>'
].join('')
};
return directive;
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.