text
stringlengths 2
6.14k
|
|---|
"use strict";
var helpers = require("../../helpers/helpers");
exports["Africa/Douala"] = {
"guess:by:offset" : helpers.makeTestGuess("Africa/Douala", { offset: true, expect: "Africa/Lagos" }),
"guess:by:abbr" : helpers.makeTestGuess("Africa/Douala", { abbr: true, expect: "Africa/Lagos" }),
"1905" : helpers.makeTestYear("Africa/Douala", [
["1905-06-30T23:46:24+00:00", "23:59:59", "LMT", -815 / 60],
["1905-06-30T23:46:25+00:00", "23:46:25", "GMT", 0]
]),
"1908" : helpers.makeTestYear("Africa/Douala", [
["1908-06-30T23:59:59+00:00", "23:59:59", "GMT", 0],
["1908-07-01T00:00:00+00:00", "00:13:35", "LMT", -815 / 60]
]),
"1913" : helpers.makeTestYear("Africa/Douala", [
["1913-12-31T23:46:24+00:00", "23:59:59", "LMT", -815 / 60],
["1913-12-31T23:46:25+00:00", "00:16:25", "+0030", -30]
]),
"1919" : helpers.makeTestYear("Africa/Douala", [
["1919-08-31T23:29:59+00:00", "23:59:59", "+0030", -30],
["1919-08-31T23:30:00+00:00", "00:30:00", "WAT", -60]
])
};
|
const path = require('path')
const BannerPlugin = require('webpack/lib/BannerPlugin')
const DedupePlugin = require('webpack/lib/optimize/DedupePlugin')
const DefinePlugin = require('webpack/lib/DefinePlugin')
const OccurrenceOrderPlugin = require(
'webpack/lib/optimize/OccurrenceOrderPlugin')
const UglifyJsPlugin = require('webpack/lib/optimize/UglifyJsPlugin')
const ProvidePlugin = require('webpack/lib/ProvidePlugin')
module.exports = function(buildTarget) {
const FILENAME = buildTarget.FILENAME
const DEV_BUILD = buildTarget.DEV_BUILD
const POLYFILL = buildTarget.POLYFILL
const SOURCEMAPS = !process.env.NO_SOURCEMAPS
return {
entry: {
horizon: POLYFILL ?
'./src/index-polyfill.js' :
'./src/index.js',
},
target: 'web',
output: {
path: path.resolve(__dirname, 'dist'),
filename: FILENAME,
library: 'Horizon', // window.Horizon if loaded by a script tag
libraryTarget: 'umd',
pathinfo: DEV_BUILD, // Add module filenames as comments in the bundle
devtoolModuleFilenameTemplate: DEV_BUILD ?
function(file) {
if (file.resourcePath.indexOf('webpack') >= 0) {
return `webpack:///${file.resourcePath}`
} else {
// Show correct paths in stack traces
return path.join('..', file.resourcePath)
.replace(/~/g, 'node_modules')
}
} :
null,
},
externals: [
function(context, request, callback) {
// Selected modules are not packaged into horizon.js. Webpack
// allows them to be required natively at runtime, either from
// filesystem (node) or window global.
if (!POLYFILL && /^rxjs\/?/.test(request)) {
callback(null, {
// If loaded via script tag, has to be at window.Rx when
// library loads
root: 'Rx',
// Otherwise imported via `require('rx')`
commonjs: 'rxjs',
commonjs2: 'rxjs',
amd: 'rxjs'
})
} else {
callback()
}
},
{ ws: 'commonjs ws' }
],
debug: DEV_BUILD,
devtool: SOURCEMAPS ? (DEV_BUILD ? 'source-map' : 'source-map') : false,
module: {
noParse: [
],
preLoaders: [],
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
query: {
cacheDirectory: true,
extends: path.resolve(__dirname, 'package.json'),
},
},
],
},
plugins: [
new BannerPlugin('__LICENSE__'),
// Possibility to replace constants such as `if (__DEV__)`
// and thus strip helpful warnings from production build:
new DefinePlugin({
'process.env.NODE_ENV': (DEV_BUILD ? 'development' : 'production'),
}),
new ProvidePlugin({
Promise: 'es6-promise',
}),
].concat(DEV_BUILD ? [] : [
new DedupePlugin(),
new OccurrenceOrderPlugin(),
new UglifyJsPlugin({
compress: {
screw_ie8: false,
warnings: false,
},
mangle: {
except: [],
},
}),
]),
node: {
// Don't include unneeded node libs in package
process: false,
fs: false,
__dirname: false,
__filename: false,
},
}
}
|
class MemorableClass {
static final ArrayList list = new ArrayList(100);
}
Calling String.intern() on lengthy String
String str=readString(); // read lengthy string any source db,textbox/jsp etc..
// This will place the string in memory pool from which you cant remove
str.intern();
(Unclosed) open streams ( file , network etc... )
try {
BufferedReader br = new BufferedReader(new FileReader(inputFile));
...
...
} catch (Exception e) {
e.printStacktrace();
}
Unclosed connections
try {
Connection conn = ConnectionFactory.getConnection();
...
...
} catch (Exception e) {
e.printStacktrace();
}
|
import React, { PropTypes as T } from 'react';
import ReactModal2 from 'react-modal2';
export default class Modal extends React.Component {
static propTypes = {
children: T.node,
onClose: T.func.isRequired,
closeOnEsc: T.bool,
closeOnBackdropClick: T.bool,
};
static defaultProps = {
closeOnEsc: true,
closeOnBackdropClick: true,
onClose: () => {
},
};
constructor(props) {
super(props);
this.handleBackdropClick = this.handleBackdropClick.bind(this);
}
handleBackdropClick() {
const { onClose, closeOnBackdropClick } = this.props;
if (closeOnBackdropClick) {
onClose();
}
}
render() {
const {
onClose,
closeOnEsc,
closeOnBackdropClick,
children,
} = this.props;
return (
<ReactModal2
onClose={onClose}
closeOnEsc={closeOnEsc}
closeOnBackdropClick={closeOnBackdropClick}
backdropClassName="Modal"
modalClassName="Modal-content"
>
<div className="Modal-close" onClick={this.handleBackdropClick}>
{children}
</div>
</ReactModal2>
);
}
}
|
Thorax.templatePathPrefix = 'templates/';
var Application = window.Application = module.exports = new Thorax.Application(module.exports);
$(document).ready(function() {
$('body').append(Application.el);
Application.start({
pushState: false,
root: '/'
});
});
|
// methods
import curry from './curry';
// utils
import coalesceToArray from './_utils/coalesceToArray';
import isObject from './_utils/isObject';
/**
* @function takeObject
*
* @description
* get the first n number of items in an object
*
* @param {number} size the number of items to get from the end of the object
* @param {Object} object the object of items to get the first n items from
* @param {Array<string>} keys the keys of the object
* @return {Object} the first n number of items
*/
function takeObject(size, object, keys) {
let index = -1,
newObject = {},
key;
while (++index < size) {
key = keys[index];
newObject[key] = object[key];
}
return newObject;
}
/**
* @function takeArray
*
* @description
* get the first n number of items in an array
*
* @param {number} size the number of items to get from the end of the array
* @param {Array<*>} array the array of items to get the first n items from
* @return {Array<*>} the first n number of items
*/
function takeArray(size, array) {
return size > 0 ? array.slice(0, size) : [];
}
/**
* @function take
*
* @description
* get the first n number of items in a collection
*
* @param {number} size the number of items to get from the end of the collection
* @param {Array<*>|Object} collection the collection of items to get the first n items from
* @return {Array<*>|Object} the first n number of items
*/
export default curry(function take(size, collection) {
return isObject(collection)
? takeObject(size, collection, Object.keys(collection))
: takeArray(size, coalesceToArray(collection));
});
|
import { all } from 'redux-saga/effects';
import { actionCreator, asyncActionCreators, createAxiosSaga } from './utils';
import { appName } from '../config';
/**
* Constants
* */
export const moduleName = 'main';
const prefix = `${appName}/${moduleName}`;
export const CONST_EXAMPLE = `${prefix}/CONST_EXAMPLE`;
/**
* Reducer
* */
export default (state = {}, action) => {
const { type } = action;
switch (type) {
default:
return state;
}
};
/**
* Selectors
* */
/**
* Action Creators
* */
export const exampleAction = actionCreator(CONST_EXAMPLE);
export const exampleAsyncAction = asyncActionCreators(CONST_EXAMPLE);
/**
* Sagas
* */
export const exampleSaga = createAxiosSaga(exampleAsyncAction);
export const saga = function*() {
yield all([exampleSaga()]);
};
|
/**
* @jest-environment jsdom
*/
/* eslint import/extensions: [0, {}] */
/* eslint import/no-unresolved: [0, {}] */
import DOMRouter from 'core/DOMRouter';
describe('DOMRouter', () => {
test('can trigger the right controller using data attributes on the <body> tag', async () => {
const testController01 = {
init: jest.fn(),
doSomething: jest.fn(),
doSomethingElse: jest.fn(),
};
const testController02 = { init: jest.fn(), doSomethingElseAgain: jest.fn() };
const controllers = { test01: () => testController01, test02: () => testController02 };
const router = new DOMRouter(controllers);
// Set up our document body
document.body.setAttribute('data-controller', 'test01');
document.body.setAttribute('data-action', 'doSomething');
await router.init();
expect(testController01.init).toHaveBeenCalled();
expect(testController01.doSomething).toHaveBeenCalled();
expect(testController01.doSomethingElse).not.toHaveBeenCalled();
expect(testController02.init).not.toHaveBeenCalled();
expect(testController02.doSomethingElseAgain).not.toHaveBeenCalled();
});
});
|
/* global chrome: true */
(function() {
if (window.onbeforeunload !== null) {
chrome.extension.sendRequest({ url: document.documentURI, type: "onbeforeunload", sessionID: "", message: "Site has redefined window.onbeforeunload with " + window.onbeforeunload.toString() }, function(response) {} );
}
}());
|
'use strict';
//使用应用名和依赖定义主模块
angular.module(ApplicationConfiguration.applicationModuleName, ApplicationConfiguration.applicationModuleVendorDependencies);
// 启动HTML location模式
angular.module(ApplicationConfiguration.applicationModuleName).config(['$locationProvider', '$httpProvider',
function ($locationProvider, $httpProvider) {
// hashPrefix(前缀): {string}
// Hashbang URLs的前缀 (在Hashbang模式中或者低级浏览器中使用)
// default: '!'
$locationProvider.html5Mode(true).hashPrefix('!');
//添加一个https请求的一个拦截器,当请求返回一定的特殊错误码的时候直接做特殊处理
$httpProvider.interceptors.push('authInterceptor');
}
]);
//run方法会在注入器初始化完成之后运行
angular.module(ApplicationConfiguration.applicationModuleName).run(function ($rootScope, $state, Authentication) {
// 在state改变前检查权限
$rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
if (toState.data && toState.data.roles && toState.data.roles.length > 0) {
var allowed = false;
toState.data.roles.forEach(function (role) {
if (Authentication.user.roles !== undefined && Authentication.user.roles.indexOf(role) !== -1) {
allowed = true;
return true;
}
});
if (!allowed) {
event.preventDefault();
if (Authentication.user !== undefined && typeof Authentication.user === 'object') {
$state.go('forbidden');
} else {
$state.go('authentication.signin').then(function () {
//保存要去的状态和参数,当登录之后可以继续
storePreviousState(toState, toParams);
});
}
}
}
});
// 监听路由改变事件来保存历史State
$rootScope.$on('$stateChangeSuccess', function (event, toState, toParams, fromState, fromParams) {
storePreviousState(fromState, fromParams);
});
// 保存历史State
function storePreviousState(state, params) {
// only store this state if it shouldn't be ignored
if (!state.data || !state.data.ignoreState) {
$state.previous = {
state: state,
params: params,
href: $state.href(state, params)
};
}
}
});
//定义启动application的初始化方法
angular.element(document).ready(function () {
//Fixing facebook bug with redirect
if (window.location.hash && window.location.hash === '#_=_') {
if (window.history && history.pushState) {
window.history.pushState('', document.title, window.location.pathname);
} else {
// Prevent scrolling by storing the page's current scroll offset
var scroll = {
top: document.body.scrollTop,
left: document.body.scrollLeft
};
window.location.hash = '';
// Restore the scroll offset, should be flicker free
document.body.scrollTop = scroll.top;
document.body.scrollLeft = scroll.left;
}
}
//Then init the app
angular.bootstrap(document, [ApplicationConfiguration.applicationModuleName]);
});
|
'use strict';
//Hostels service used to communicate Hostels REST endpoints
angular.module('hostels').factory('Hostels', ['$resource',
function($resource) {
return $resource('hostels/:hostelId', { hostelId: '@_id'
}, {
update: {
method: 'PUT'
}
});
}
]);
|
/**
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
module.exports = {
'ios' : {
parser : './src/metadata/ios_parser',
url : 'https://git-wip-us.apache.org/repos/asf?p=cordova-ios.git',
version: '3.1.0'
},
'android' : {
parser : './src/metadata/android_parser',
url : 'https://git-wip-us.apache.org/repos/asf?p=cordova-android.git',
version: '3.1.0'
},
'wp7' : {
parser : './src/metadata/wp7_parser',
url : 'https://git-wip-us.apache.org/repos/asf?p=cordova-wp8.git',
version: '3.1.0'
},
'wp8' : {
parser : './src/metadata/wp8_parser',
url : 'https://git-wip-us.apache.org/repos/asf?p=cordova-wp8.git',
version: '3.1.0'
},
'blackberry10' : {
parser : './src/metadata/blackberry10_parser',
url : 'https://git-wip-us.apache.org/repos/asf?p=cordova-blackberry.git',
version: '3.1.0'
},
'www':{
url : 'https://git-wip-us.apache.org/repos/asf?p=cordova-app-hello-world.git',
version: '3.1.0'
},
'firefoxos':{
parser: './src/metadata/firefoxos_parser',
url : 'https://git-wip-us.apache.org/repos/asf?p=cordova-firefoxos.git',
version: '3.1.0'
},
'windows8':{
parser: './src/metadata/windows8_parser',
url : 'https://git-wip-us.apache.org/repos/asf?p=cordova-windows.git',
version: '3.1.0'
}
};
var addModuleProperty = require('./src/util').addModuleProperty;
Object.keys(module.exports).forEach(function(key) {
var obj = module.exports[key];
if (obj.parser) {
addModuleProperty(module, 'parser', obj.parser, false, obj);
}
});
|
var StartLayer_root = null;
var StartLayer = cc.Layer.extend({
rootnode:null,
PushBg:null,
TextFieldName:null,
ButtonCertain:null,
PanelNickName:null,
ctor:function () {
this._super();
StartLayer_root = this;
var size = cc.winSize;
this.rootnode = ccs.load(res.StartLayer_json).node;
this.addChild(this.rootnode);
StartLayer_root.PanelNickName = ccui.helper.seekWidgetByName(StartLayer_root.rootnode, "PanelNickName");
StartLayer_root.TextFieldName = ccui.helper.seekWidgetByName(StartLayer_root.rootnode, "TextFieldName");
StartLayer_root.ButtonCertain = this.rootnode.getChildByName("ButtonCertain");
StartLayer_root.ButtonCertain.addTouchEventListener(this.onBackClick);
return true;
},
onBackClick:function(sender,type)
{
console.log("333");
var buttonName = sender.getName();
switch(type)
{
case ccui.Widget.TOUCH_ENDED:
if (buttonName == "ButtonCertain")
{
console.log("11111111111111");
UserData.NickName = StartLayer_root.TextFieldName.getString();
MainScene_root.popLayer();
}
break;
}
}
});
|
import { Random } from 'meteor/random';
import { FlowRouter } from 'meteor/kadira:flow-router';
import { BlazeLayout } from 'meteor/kadira:blaze-layout';
FlowRouter.route('/', {
name: 'home',
action() {
BlazeLayout.render('layout', { main: 'home' });
},
});
FlowRouter.route('/bailout', {
name: 'home-bailout',
action() {
BlazeLayout.render('layout', { main: 'homeBailout' });
},
});
FlowRouter.route('/ir', {
name: 'home-ir',
action() {
BlazeLayout.render('layout', { main: 'homeIr' });
},
});
FlowRouter.route('/new', {
name: 'create',
action() {
BlazeLayout.render('layout', { main: 'new' });
},
});
FlowRouter.route('/admin', {
name: 'adminActions',
action() {
BlazeLayout.render('layout', { main: 'adminActions' });
},
});
FlowRouter.route('/admin/list', {
name: 'adminList',
action() {
BlazeLayout.render('layout', { main: 'adminList' });
},
});
FlowRouter.route('/job/new', {
name: 'jobCreate',
triggersEnter: [(context, redirect) => {
redirect(`/job/${Random.id()}`);
}],
});
FlowRouter.route('/job/:_publicId', {
name: 'jobHome',
action({ _publicId }) {
Meteor.call('job:getOrCreate', { _publicId }, () => BlazeLayout.render('layout', { main: 'jobHome' }));
},
});
FlowRouter.route('/ir/new', {
name: 'irjobCreate',
triggersEnter: [(context, redirect) => {
redirect(`/ir/${Random.id()}`);
}],
});
FlowRouter.route('/irhydra', {
name: 'irhydraRedirect',
action() {
const root = process.env.ROOT_URL || 'localhost:3000';
const path = FlowRouter.current().path;
document.location.assign(`${root}/${path}`);
window.location.reload();
return;
},
});
FlowRouter.route('/ir/:_publicId', {
name: 'irjobHome',
action({ _publicId }) {
Meteor.call('irjob:getOrCreate', { _publicId }, () => BlazeLayout.render('layout', { main: 'irjobHome' }));
},
});
|
var loadDate = new Date();
console.log(loadDate);
window.setInterval(function(){
getTimeFromLoading();
}, 1000);
function getTimeFromLoading(){
var now = new Date();
var resultado = (now - loadDate);
var seconds = Math.round(resultado/1000);
document.getElementById('time').innerHTML="<strong>The time since the page load is: " +
seconds + " seconds</strong>";
}
// TODO: Look for a more efficient way to do it;
|
var example_8 = switcher.items({eventMethod: "mouseover"});
// Табы
example_8.addTabs('#tab_7 span', function () {
this.classList.add('tab_active');
}, function () {
this.classList.remove('tab_active');
});
// Блоки
example_8.addBlocks('#block_7 img', function() {
var
i=0,
that = this;
this.style.opacity = 0;
this.style.display = "block";
// Удаляем таймер от предыдущего элемента, если есть
clearInterval(example_8.varTimer);
// Таймер
example_8.varTimer = setInterval(function() {
if(i >= 1) {
clearInterval(example_8.varTimer);
}
i+=0.1;
that.style.opacity = i;
}, 50);
}, function() {
this.style.display = "none";
});
example_8.turnOn(4);
|
/* eslint-disable jsx-a11y/anchor-is-valid */
import '../src/bootstrap';
// --- Post bootstrap -----
import React from 'react';
import Button from '@material-ui/core/Button';
import Dialog from '@material-ui/core/Dialog';
import DialogTitle from '@material-ui/core/DialogTitle';
import DialogContent from '@material-ui/core/DialogContent';
import DialogContentText from '@material-ui/core/DialogContentText';
import DialogActions from '@material-ui/core/DialogActions';
import Typography from '@material-ui/core/Typography';
import { makeStyles } from '@material-ui/styles';
import Link from 'next/link';
const useStyles = makeStyles(theme => ({
root: {
textAlign: 'center',
paddingTop: theme.spacing.unit * 20,
},
}));
function Index() {
const classes = useStyles();
const [open, setState] = React.useState(false);
const handleClose = () => {
setState(false);
};
const handleClick = () => {
setState(true);
};
return (
<div className={classes.root}>
<Dialog open={open} onClose={handleClose}>
<DialogTitle>Super Secret Password</DialogTitle>
<DialogContent>
<DialogContentText>1-2-3-4-5</DialogContentText>
</DialogContent>
<DialogActions>
<Button color="primary" onClick={handleClose}>
OK
</Button>
</DialogActions>
</Dialog>
<Typography variant="h4" gutterBottom>
Material-UI
</Typography>
<Typography variant="subtitle1" gutterBottom>
example project
</Typography>
<Typography gutterBottom>
<Link href="/about">
<a>Go to the about page</a>
</Link>
</Typography>
<Button variant="contained" color="secondary" onClick={handleClick}>
Super Secret Password
</Button>
</div>
);
}
export default Index;
|
/**
* IMG
* preFlash
*
* All functions related to img files
* management.
*/
// PACKAGES
const gulp = require("gulp");
const g = {
cached: require("gulp-cached"),
favicon: require("gulp-real-favicon"),
if: require("gulp-if"),
imagemin: require("gulp-imagemin"),
plumber: require("gulp-plumber"),
rename: require("gulp-rename"),
util: require("gulp-util")
};
const cson = require("cson");
const fs = require("fs");
// !!! Run-sequence in to delete in gulp version 4 !!!
const run = require("run-sequence");
// CONFIG & HELPERS
const CONFIG = cson.requireFile("preFlash.config.cson");
const HELPERS = require("./../helpers.js");
// MAIN
gulp.task("img", function() {
g.util.log(g.util.colors.green("Images"), "running!");
return gulp.src(CONFIG.paths.sources.img)
.pipe(g.plumber({errorHandler: HELPERS.alert}))
.pipe(g.cached('img'))
.pipe(g.imagemin(
[
g.imagemin.gifsicle(CONFIG.packages.img.plugins.gifsicle),
g.imagemin.jpegtran(CONFIG.packages.img.plugins.jpegtran),
g.imagemin.optipng(CONFIG.packages.img.plugins.optipng),
g.imagemin.svgo(CONFIG.packages.img.plugins.svgo)
],
CONFIG.packages.img.options
))
.pipe(g.if(CONFIG.packages.img.rename, g.rename({suffix: '.min'})))
.pipe(gulp.dest(HELPERS.getPath() + CONFIG.packages.img.dir));
});
// WATCH
gulp.task("img.watch", (cb) => {
gulp.watch(CONFIG.paths.watch.img, ["img"]);
gulp.watch(CONFIG.packages.img.favicon.masterPicture, ["generate-favicon"]);
cb();
});
// FAVICONS
// http://realfavicongenerator.net/favicon/gulp
gulp.task("img.favicon", (cb) => {
run(
"generate-favicon",
"check-for-favicon-update",
cb
);
});
// Generate the icons. This task takes a few seconds to complete.
// You should run it at least once to create the icons. Then,
// you should run it whenever RealFaviconGenerator updates its
// package (see the check-for-favicon-update task below).
gulp.task('generate-favicon', (done) => {
g.util.log(g.util.colors.green("Favicon Generator"), "running!");
g.favicon.generateFavicon(
Object.assign(
{},
CONFIG.packages.img.favicon,
{ dest: HELPERS.getPath() }
),
() => done()
);
});
// Check for updates on RealFaviconGenerator (think: Apple has just
// released a new Touch icon along with the latest version of iOS).
// Run this task from time to time. Ideally, make it part of your
// continuous integration system.
gulp.task('check-for-favicon-update', function(done) {
g.util.log(g.util.colors.green("Favicon Generator Update"), "running!");
var currentVersion = JSON.parse(fs.readFileSync(CONFIG.packages.img.favicon.markupFile)).version;
g.favicon.checkForUpdates(currentVersion, function(err) {
if (err) {
throw err;
}
});
done();
});
|
/**
* Created by @axiat on 2017. 4. 10..
*/
// This script will keep the footer always at the bottom of the page
$(document).ready(function () {
var docHeight = $(window).height();
var footerHeight = $('#footer').height();
var footerTop = $('#footer').position().top + footerHeight;
if (footerTop < docHeight) {
$('#footer').css('margin-top', 10+ (docHeight - footerTop) + 'px');
}
});
|
import React from 'react';
import MarkdownDocs from 'docs/src/modules/components/MarkdownDocs';
import { prepareMarkdown } from 'docs/src/modules/utils/parseMarkdown';
const pageFilename = 'components/tree-view';
const requireDemo = require.context('docs/src/pages/components/tree-view', false, /\.(js|tsx)$/);
const requireRaw = require.context(
'!raw-loader!../../src/pages/components/tree-view',
false,
/\.(js|md|tsx)$/,
);
export default function Page({ demos, docs }) {
return <MarkdownDocs demos={demos} docs={docs} requireDemo={requireDemo} />;
}
Page.getInitialProps = () => {
const { demos, docs } = prepareMarkdown({ pageFilename, requireRaw });
return { demos, docs };
};
|
import React, { PropTypes } from 'react'
import { connect } from 'react-redux'
import { actions as userActions, USER_ENUM } from '../../redux/modules/UserReducer'
class AuthRequiredWrapper extends React.Component {
static propTypes = {
children: PropTypes.element.isRequired,
isAuthenticated: PropTypes.bool.isRequired,
user: PropTypes.object.isRequired,
unauthorizedRoute: PropTypes.func.isRequired
};
componentWillMount() {
const { isAuthenticated, user } = this.props
if (!(isAuthenticated && user.user &&
([USER_ENUM.ROLE_ADMIN, USER_ENUM.ROLE_OWNER].includes(user.user.role)))) {
this.props.unauthorizedRoute()
}
}
render() {
const { children } = this.props
return (
<div>
{children}
</div>
)
}
}
const mapStateToProps = (state) => ({
isAuthenticated : state.user.isAuthenticated,
user : state.user
})
export default connect(mapStateToProps, userActions)(AuthRequiredWrapper)
|
GrandCentral.Dashboard = DS.Model.extend({
title: DS.attr('string'),
published: DS.attr('boolean')
});
|
function getMemoryList() {
var memoryList = [{
round: 1,
position: undefined,
valuee: undefined
},
{
round: 2,
position: undefined,
valuee: undefined
},
{
round: 3,
position: undefined,
valuee: undefined
},
{
round: 4,
position: undefined,
valuee: undefined
},
{
round: 5,
position: undefined,
valuee: undefined
},
];
return memoryList;
}
function memory(display, round, memoryList) {
if (round==1) {
if (display ==1) {
memoryList[0].position = 2;
return("Press the button in the second position")
}
if (display ==2) {
memoryList[0].position = 2;
return("Press the button in the second position")
}
if (display ==3) {
memoryList[0].position = 3;
return("Press the button in the third position")
}
if (display ==4) {
memoryList[0].position = 4;
return("Press the button in the fourth position")
}
}
if (round==2) {
if (display ==1) {
memoryList[1].valuee = 4;
return("Press the button labeled 4")
}
if (display ==2 || display ==4) {
answer = memoryList[0].position;
memoryList[1].position = answer;
return("Press the button in the position of " + answer);
}
if (display ==3) {
memoryList[1].position = 1;
return("Press the button in the first position")
}
}
if (round==3) {
if (display ==1) {
answer = memoryList[1].valuee;
memoryList[2].valuee = answer;
return("Press the button with the label " + answer);
}
if (display ==2) {
answer = memoryList[0].valuee;
memoryList[2].valuee = answer;
return("Press the button with the label " + answer);
}
if (display ==3) {
memoryList[2].position = 3;
return("Press the button in the third position")
}
if (display ==4) {
memoryList[2].valuee = 4;
return("Press the button labeled 4")
}
}
if (round==4) {
if (display ==1) {
answer = memoryList[0].position;
memoryList[3].position = answer;
return("Press the button with the position " + answer);
}
if (display ==2) {
memoryList[3].position = 1;
return("Press the button in the first position")
}
if (display ==3 || display==4) {
//same position as stage 2
answer = memoryList[1].position;
memoryList[3].position = answer;
return("Press the button with the position " + answer)
}
}
if (round==5) {
if (display ==1) {
//same label as stage 1
answer = memoryList[0].valuee;
memoryList[4].valuee = answer;
return("Press the button with the label " + answer)
}
if (display ==2) {
answer = memoryList[1].valuee;
memoryList[4].position = answer;
return("Press the button with the label " + answer)
}
if (display ==3) {
//same label as stage 4
answer = memoryList[3].valuee;
memoryList[4].valuee = answer;
return("Press the button with the label " + answer)
}
if (display ==4) {
//same label as stage 3
answer = memoryList[2].valuee;
memoryList[4].valuee = answer;
return("Press the button with the label " + answer)
}
}
}
|
/*
The MIT License (MIT)
Copyright (c) 2015 Los Andes University
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
(function (ng) {
var mod = ng.module('tripModule');
mod.controller('tripCategoryEditCtrl', ['$scope', 'category', 'pool', 'model', '$state',
function ($scope, category, available, model, $state) {
$scope.records = category;
$scope.model = model;
$scope.available = available.plain();
$scope.actions = {
save: {
displayName: 'Save',
icon: 'save',
fn: function () {
$scope.records.customPUT().then(function () {
$state.go('tripCategoryList', null, {reload: true});
});
}
},
cancel: {
displayName: 'Cancel',
icon: 'remove',
fn: function () {
$state.go('tripCategoryList');
}
}
};
}]);
})(window.angular);
|
module.exports.parse = function (object) {
statement = "";
statement += String(object).toUpperCase() == "AND" ? " AND " : " OR ";
return statement;
};
|
/**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component, PropTypes } from 'react';
import { AppRegistry, NativeModules, StyleSheet, Text, View } from 'react-native';
import ActionExtensionScreen from './app/ActionExtensionScreen';
export default class ReactNativeExampleBrowserExtension extends Component {
static propTypes = {
isActionExtension: PropTypes.bool
};
static defaultProps = {
isActionExtension: false
};
render() {
if (this.props.isActionExtension) {
return <ActionExtensionScreen />;
} else {
return (
<View style={styles.container}>
<Text style={styles.welcome}>Welcome to ReactNativeExampleBrowserExtension!</Text>
<Text style={styles.instructions}>
This app shows how to create a browser extension using React Native
</Text>
<Text style={styles.instructions}>
You can mostly ignore this main app code, all the fun is in the extension and the
README, which contains the instructions you should follow
</Text>
</View>
);
}
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF'
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5
}
});
AppRegistry.registerComponent(
'ReactNativeExampleBrowserExtension',
() => ReactNativeExampleBrowserExtension
);
|
TextVisApp.factory('dataService', ['$http', function ($http) {
}]);
|
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { CellModule } from '../cell/cell.module';
import { Ng2SmartTableTbodyComponent } from './tbody.component';
import { TbodyCreateCancelComponent } from './cells/create-cancel.component';
import { TbodyEditDeleteComponent } from './cells/edit-delete.component';
import { TbodyCustomComponent } from './cells/custom.component';
var TBODY_COMPONENTS = [
TbodyCreateCancelComponent,
TbodyEditDeleteComponent,
TbodyCustomComponent,
Ng2SmartTableTbodyComponent
];
var TBodyModule = (function () {
function TBodyModule() {
}
return TBodyModule;
}());
TBodyModule = __decorate([
NgModule({
imports: [
CommonModule,
FormsModule,
CellModule,
],
declarations: TBODY_COMPONENTS.slice(),
exports: TBODY_COMPONENTS.slice(),
})
], TBodyModule);
export { TBodyModule };
//# sourceMappingURL=tbody.module.js.map
|
var chai = require('chai');
var chaiAsPromised = require('chai-as-promised');
chai.use(chaiAsPromised);
var expect = chai.expect;
var Promise = require('bluebird');
var messages = require('../server/messages');
var Chat = require('../server/database.js');
describe('Chat Timing', function() {
before(function(done) {
Promise.mapSeries(Array.apply(null, Array(11)), function(item, index) {
return new Chat({user: 'user', text: 'text' + index, session: '4'}).save();
}).then(() => done()).catch(done);
});
describe('#getPosts', function(done) {
it('should return 10', function(done) {
expect(messages.getPosts()).to.eventually.have.lengthOf(10)
.then((m) => done()).catch(done);
});
it('should return only the new ones when sent a date', function(done) {
var lastDate;
messages.getPosts()
.then((r) => {
lastDate = r[r.length - 1].createdOn;
expect(lastDate).to.not.be.null;
})
.then(() => messages.addPost('bill', 'new post', 'session'))
.then(() => messages.getPosts(lastDate))
.then((updated) => {
expect(updated).to.have.lengthOf(1);
})
.then(() => done()).catch(done);
});
});
after(function(done) {
Chat.remove().then(() => done()).catch(done);
done();
});
});
|
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*
* @format
*/
'use strict';var _slicedToArray = function () {function sliceIterator(arr, i) {var _arr = [];var _n = true;var _d = false;var _e = undefined;try {for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {_arr.push(_s.value);if (i && _arr.length === i) break;}} catch (err) {_d = true;_e = err;} finally {try {if (!_n && _i["return"]) _i["return"]();} finally {if (_d) throw _e;}}return _arr;}return function (arr, i) {if (Array.isArray(arr)) {return arr;} else if (Symbol.iterator in Object(arr)) {return sliceIterator(arr, i);} else {throw new TypeError("Invalid attempt to destructure non-iterable instance");}};}();
const babel = require('babel-core');
const babelGenerate = require('babel-generator').default;
const babylon = require('babylon');
const assetPropertyBlacklist = new Set(['files', 'fileSystemLocation', 'path']);
function generateAssetCodeFileAst(
assetRegistryPath,
assetDescriptor)
{
const properDescriptor = filterObject(
assetDescriptor,
assetPropertyBlacklist);
const descriptorAst = babylon.parseExpression(
JSON.stringify(properDescriptor));
const t = babel.types;
const moduleExports = t.memberExpression(
t.identifier('module'),
t.identifier('exports'));
const requireCall = t.callExpression(t.identifier('require'), [
t.stringLiteral(assetRegistryPath)]);
const registerAssetFunction = t.memberExpression(
requireCall,
t.identifier('registerAsset'));
const registerAssetCall = t.callExpression(registerAssetFunction, [
descriptorAst]);
return t.file(
t.program([
t.expressionStatement(
t.assignmentExpression('=', moduleExports, registerAssetCall))]));
}
function generateAssetTransformResult(
assetRegistryPath,
assetDescriptor)
{var _babelGenerate =
babelGenerate(
generateAssetCodeFileAst(assetRegistryPath, assetDescriptor),
{ comments: false, compact: true });const code = _babelGenerate.code;
const dependencies = [assetRegistryPath];
const dependencyOffsets = [code.indexOf(assetRegistryPath) - 1];
return { code, dependencies, dependencyOffsets };
}
// Test extension against all types supported by image-size module.
// If it's not one of these, we won't treat it as an image.
function isAssetTypeAnImage(type) {
return (
['png', 'jpg', 'jpeg', 'bmp', 'gif', 'webp', 'psd', 'svg', 'tiff'].indexOf(
type) !==
-1);
}
function filterObject(object, blacklist) {
const copied = Object.assign({}, object);
for (const key of blacklist) {
delete copied[key];
}
return copied;
}
function createRamBundleGroups(
ramGroups,
groupableModules,
subtree)
{
// build two maps that allow to lookup module data
// by path or (numeric) module id;
const byPath = new Map();
const byId = new Map();
groupableModules.forEach(m => {
byPath.set(m.sourcePath, m);
byId.set(m.id, m.sourcePath);
});
// build a map of group root IDs to an array of module IDs in the group
const result = new Map(
ramGroups.map(modulePath => {
const root = byPath.get(modulePath);
if (root == null) {
throw Error(`Group root ${modulePath} is not part of the bundle`);
}
return [
root.id,
// `subtree` yields the IDs of all transitive dependencies of a module
new Set(subtree(root, byPath))];
}));
if (ramGroups.length > 1) {
// build a map of all grouped module IDs to an array of group root IDs
const all = new ArrayMap();
for (const _ref of result) {var _ref2 = _slicedToArray(_ref, 2);const parent = _ref2[0];const children = _ref2[1];
for (const module of children) {
all.get(module).push(parent);
}
}
// find all module IDs that are part of more than one group
const doubles = filter(all, _ref3 => {var _ref4 = _slicedToArray(_ref3, 2);let parents = _ref4[1];return parents.length > 1;});
for (const _ref5 of doubles) {var _ref6 = _slicedToArray(_ref5, 2);const moduleId = _ref6[0];const parents = _ref6[1];
const parentNames = parents.map(byId.get, byId);
const lastName = parentNames.pop();
throw new Error(
`Module ${byId.get(moduleId) ||
moduleId} belongs to groups ${parentNames.join(', ')}, and ${String(
lastName)
}. Ensure that each module is only part of one group.`);
}
}
return result;
}
function* filter(iterator, predicate) {
for (const value of iterator) {
if (predicate(value)) {
yield value;
}
}
}
class ArrayMap extends Map {
get(key) {
let array = super.get(key);
if (!array) {
array = [];
this.set(key, array);
}
return array;
}}
module.exports = {
createRamBundleGroups,
generateAssetCodeFileAst,
generateAssetTransformResult,
isAssetTypeAnImage };
|
/* eslint-env node */
'use strict';
const assert = require('assert');
const fs = require('fs');
const {join} = require('path');
const ohm = require('../../packages/ohm-js');
const contents = fs.readFileSync(join(__dirname, 'csv.ohm'));
const g = ohm.grammar(contents);
const semantics = g.createSemantics().addOperation('value', {
csv(r, _, rs, eol) {
return [r.value()].concat(rs.children.map(c => c.value()));
},
row(c, _, cs) {
return [c.value()].concat(cs.children.map(c => c.value()));
},
col(_) {
return this.sourceString;
},
});
const someInput = 'foo,bar,baz\n' + 'foo,bar\n' + '\n' + 'foo,,baz\n' + ',bar,baz\n' + 'foo';
function parse(input) {
const match = g.match(input);
assert(match.succeeded());
return semantics(match).value();
}
assert.deepEqual(parse(someInput), [
['foo', 'bar', 'baz'],
['foo', 'bar'],
[''],
['foo', '', 'baz'],
['', 'bar', 'baz'],
['foo'],
]);
assert.deepEqual(parse(someInput + '\n'), [
['foo', 'bar', 'baz'],
['foo', 'bar'],
[''],
['foo', '', 'baz'],
['', 'bar', 'baz'],
['foo'],
]);
|
/*
* ______ _____ _____ _ _____________ _________________ ____________
* | ___ \ _ / __ \| | / /_ _| ___ \ ___| ___| ___| | ___ \ ___ \
* | |_/ / | | | / \/| |/ / | | | |_/ / |__ | |_ | |_ | |_/ / |_/ /
* | /| | | | | | \ | | | /| __|| _| | _| | ___ \ ___ \
* | |\ \\ \_/ / \__/\| |\ \ | | | |\ \| |___| | | | | |_/ / |_/ /
* \_| \_|\___/ \____/\_| \_/ \_/ \_| \_\____/\_| \_| \____/\____/
*
* "THE BEER-WARE LICENSE" (Revision 42):
* <rob ∂ rocktreff de> wrote this file. As long as you retain this notice you
* can do whatever you want with this stuff. If we meet some day, and you think
* this stuff is worth it, you can buy me a beer in return.
*
*/
'use strict';
var _ = require( 'lodash' )
var Promise = require( 'promise' )
function createFromSchema( schema ) {
var obj = {}
if ( !schema || !schema.properties ) return obj
var properties = schema.properties
for ( var key in properties ) {
if ( !properties.hasOwnProperty( key ) ) continue
var property = properties[ key ]
switch ( property.type.toLowerCase() ) {
case 'object':
obj[ key ] = createFromSchema( property.properties )
case 'string':
obj[ key ] = property.default || ''
case 'array':
obj[ key ] = property.default || []
case 'boolean':
obj[ key ] = property.default || false
case 'number':
obj[ key ] = property.default || 0
}
}
return obj
}
module.exports = function ( template ) {
template = createFromSchema( template )
return {
create: function ( obj ) {
return new Promise( function ( resolve ) {
resolve( _.defaults( obj, template ) )
})
},
omit: function () {
var args = Array.prototype.slice.call( arguments )
return function ( obj ) {
var foo = obj instanceof Array ?
_.map( obj, function ( o ) {
return _.omit( o, args )
})
: _.omit( obj, args )
return foo
}
},
merge: _.curry( function ( src, obj ) {
return _.merge( obj, src )
})
}
}
|
(function(){
'use strict';
/**
* jQuery UI date pciker range filter model
* @constructor
* @param {string} dataPath - DatePickerRangeFilter data-path attribute
* @param {string} dateTimeFormat
* @param {Date|string} prevDate
* @param {Date|string} nextDate
*/
jQuery.fn.jplist.ui.controls.DatePickerRangeFilterDTO = function(dataPath, dateTimeFormat, prevDate, nextDate){
var result = {
path: dataPath
,format: dateTimeFormat
,filterType: 'dateRange'
,prev_year: ''
,prev_month: ''
,prev_day: ''
,next_year: ''
,next_month: ''
,next_day: ''
};
if(prevDate){
result.prev_year = prevDate.getFullYear();
result.prev_month = prevDate.getMonth();
result.prev_day = prevDate.getDate();
}
if(nextDate){
result.next_year = nextDate.getFullYear();
result.next_month = nextDate.getMonth();
result.next_day = nextDate.getDate();
}
return result;
};
})();
|
const {PI} = Math
import SphericalMercator from './sphericalmercator'
import Transformation from './transformation'
class CRS {
constructor(opts) {
this.projection = new SphericalMercator()
this.tileSize = 256 + 256 * (opts.zoom % 1)
const earthRadius = 6378137
const scale = 0.5 / (PI * earthRadius);
this.transformation = new Transformation(scale, 0.5, -scale, 0.5)
}
// @method scale(zoom: Number): Number
// Returns the scale used when transforming projected coordinates into
// pixel coordinates for a particular zoom.
// `256 * 2^zoom` for Mercator-based CRS.
scale(zoom) {
return this.tileSize * Math.pow(2, zoom);
}
// @method zoom(scale: Number): Number
// Inverse of `scale()`, returns the zoom level corresponding to a scale
// factor of `scale`.
zoom(scale) {
return Math.log(scale / this.tileSize) / Math.LN2;
}
// @method latLngToPoint(latlng: LatLng, zoom: Number): Point
// Projects geographical coordinates into pixel coordinates for a given zoom.
latLngToPoint(latlng, zoom) {
const projectedPoint = this.projection.project(latlng)
const scale = this.scale(zoom)
return this.transformation.transform(projectedPoint, scale)
}
// @method pointToLatLng(point: Point, zoom: Number): LatLng
// The inverse of `latLngToPoint`. Projects pixel coordinates on a given
// zoom into geographical coordinates.
pointToLatLng(point, zoom) {
const scale = this.scale(zoom)
const untransformedPoint = this.transformation.untransform(point, scale);
const result = this.projection.unproject(untransformedPoint);
return result
}
}
module.exports = CRS
|
(function() {
var Walrus;
Walrus = (typeof exports !== "undefined" && exports !== null ? require('./walrus') : this).Walrus;
/**
* *:reverse*
* Reverses a string.
*
* Parameters: none
*
* Usage:
*
* {{ "hello" | :reverse }} // => "olleh"
*/
Walrus.addFilter('reverse', function(value) {
return value.split('').reverse().join('');
});
/**
* *:downcase*
* Converts a string to lowercase characters. Opposite of `:upcase`.
*
* Parameters: none
*
* Usage:
*
* {{ "HelLO!" | :downcase }} // => "hello!"
*/
Walrus.addFilter('downcase', function(value) {
return value.toLowerCase();
});
/**
* *:upcase*
* Converts a string to uppercase characters. Opposite of `:downcase`.
*
* Parameters: none
*
* Usage:
*
* {{ "HelLO!" | :upcase }} // => "HELLO!"
*/
Walrus.addFilter('upcase', function(value) {
return value.toUpperCase();
});
/**
* *:squish*
* Removes all leading and trailing whitespace, then condenses any internal whitespace
* groups to a single space each.
*
* Parameters: none
*
* Usage:
*
* {{ " foo bar \n baz" | :squish }} // => "foo bar baz"
*/
Walrus.addFilter('squish', function(string) {
return Walrus.Utils.trim(string).replace(/\s+/g, ' ');
});
/**
* *:truncate*
* Truncates a string to the specified `length`, optionally breaking at a separator
* or providing a custom string to denote an omission.
*
* Parameters:
* length (int) - the number of characters to keep, at most
* separator (string) - Optional: a specified string to break on
* omission (string) - Optional: a string to denote an omission
*
* Usage:
*
* {{ "Once upon a time in a world far far away" | :truncate( 27, ' ' ) }} // => "Once upon a time in a..."
*/
Walrus.addFilter('truncate', function(string, length, separator, omission) {
var chars, stop;
if (separator == null) separator = false;
if (omission == null) omission = '...';
chars = length - omission.length;
stop = separator ? string.lastIndexOf(separator, chars) || chars : chars;
if (string.length > length) {
return string.substr(0, stop) + omission;
} else {
return string;
}
});
/**
* *:titleize*
* Capitalizes all words within a string
*
* Parameters: none
*
* Usage:
*
* { "man from the boondocks" | :titleize } // => "Man From The Boondocks"
* { "x-men: the last stand" | :titleize } // => "X Men: The Last Stand"
* { "TheManWithoutAPast" | :titleize } // => "The Man Without A Past"
* { "raiders_of_the_lost_ark" | :titleize } // => "Raiders Of The Lost Ark"
*/
Walrus.addFilter('titleize', function(string) {
var capitalize, title, word, words;
title = string.replace(/[ \-_]+/g, ' ');
words = Walrus.Utils.trim(title.replace(/([A-Z])/g, " $&")).split(' ');
capitalize = function(word) {
return word.charAt(0).toUpperCase() + word.slice(1);
};
return ((function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = words.length; _i < _len; _i++) {
word = words[_i];
_results.push(capitalize(word));
}
return _results;
})()).join(' ');
});
}).call(this);
|
ya.$onReady(function () {
"use strict";
var view = app.view.Bar.$create({
config: {
models: [
ya.$factory({
module: 'ya',
alias: 'Model',
namespace: 'likes',
data: {
count: 0
},
methods: {
incrementCount: function () {
var me = this;
me.data('count', me.data('count') + 1);
}
}
})
],
id: 'bar',
tpl: {
id: 'tpl-bar',
tpl: [
'<div class="bar">',
'Count : {{likes.count}}',
'<button css="cursor: pointer;">+</button>',
'</div>'
]
},
renderTo: '#container'
}
});
// create main controller to
ya.Controller.$create({
config: {
name: 'Main',
events: {
'$bar button': {
click: function (view, event) {
view.getModel('likes').incrementCount();
}
}
}
}
});
view.render();
});
|
(function ($, kv) {
var $fSetToggler = $('<a href="#" class="fSetToggler">advanced</a>');
/**
*
* @param event
* @context {ExpandableSet}
*/
function handleToggleClick(event) {
event.preventDefault();
event.data.expandableSet.expandableToggle();
}
/**
*
*/
kv.FormSet.prototype.expandable = function () {
this.settings.expandable = $.extend({}, kv.FormSet.expandable.defaults, this.settings.expandable);
var $expandableSet = this.$formSet
, $toggler = $fSetToggler.clone().appendTo($('.fSetHead .fSetInner', $expandableSet))
, $nestedSet = $('> .fSetHead + .fSet', $expandableSet);
// Make sure everything is structured the way we need it
$.each({expandableSet: $expandableSet, toggler: $toggler, nestedSet: $nestedSet}, function (key, val) {
if (val.length === 0) {
throw 'missing ' + key;
}
});
this.decorate('expandable', {
$toggler: $toggler
, $nestedSet: $nestedSet
/**
* Toggles the display of the expandableSet
*/
, expandableToggle: function () {
if (this.attr('expandableState') == 'expanded') {
this.close();
} else {
this.expand();
}
}
/**
* Expands the expandableSet
*/
, expand: function () {
var self = this;
self.$nestedSet.stop().slideDown(function () {
self.$toggler.text(self.settings.expandedText);
self.attr('expandableState', 'expanded');
$(this).addClass(self.settings.expandable.openClass);
});
}
/**
* Closes the expandableSet
*/
, close: function () {
var self = this;
self.$nestedSet.stop().slideUp(function () {
self.$toggler.text(self.settings.closedText);
self.attr('expandableState', 'closed');
$(this).removeClass(self.settings.expandable.openClass);
});
}
});
if (this.settings.expandable.expandOnLoad) {
this.expand();
} else {
this.attr('expandableState', 'closed');
}
this.$toggler.click({expandableSet: this}, handleToggleClick);
};
kv.FormSet.expandable = {
defaults: {
openClass: 'open'
, expandedText: 'close'
, closedText: 'advanced'
, expandOnLoad: false
}
};
}(jQuery, kv));
|
version https://git-lfs.github.com/spec/v1
oid sha256:c06f2e9547bd4de53c941d51fe6cb23a056852096115e73799c03835b88d9b1f
size 63066
|
// fixtures/basic.fixture.html
var template = function (_swig,_ctx,_filters,_utils,_fn) {
var _ext = _swig.extensions,
_output = "";
_output += _filters["e"]((((typeof _ctx.foo !== "undefined" && _ctx.foo !== null) ? ((typeof _ctx.foo !== "undefined" && _ctx.foo !== null) ? _ctx.foo : "") : ((typeof foo !== "undefined" && foo !== null) ? foo : "")) !== null ? ((typeof _ctx.foo !== "undefined" && _ctx.foo !== null) ? ((typeof _ctx.foo !== "undefined" && _ctx.foo !== null) ? _ctx.foo : "") : ((typeof foo !== "undefined" && foo !== null) ? foo : "")) : "" ));
return _output;
};
|
'use strict';
var vkey = require('vkey');
var fromUnicode = require('./utext').fromUnicode;
// map virtual key to Unicode corresponding to trit-text, with modifiers
var _keymap = {
// vkey: normal, shifted, control, shift-control
A: ['a', 'A', '☺', ''],
B: ['b', 'B', '☻', ''],
C: ['c', 'C', '♥', ''],
D: ['d', 'D', '♦', ''],
E: ['e', 'E', '•', ''],
F: ['f', 'F', '◘', ''],
G: ['g', 'G', '○', ''],
H: ['h', 'H', '◙', ''],
I: ['i', 'I', '♂', ''],
J: ['j', 'J', '♀', ''],
K: ['k', 'K', '☼', ''],
L: ['l', 'L', '▒', ''],
M: ['m', 'M', '←', ''],
N: ['n', 'N', '→', ''],
O: ['o', 'O', '↑', ''],
P: ['p', 'P', '↓', ''],
Q: ['q', 'Q', '', ''],
R: ['r', 'R', '', ''],
S: ['s', 'S', '', ''],
T: ['t', 'T', '', ''],
U: ['u', 'U', '', ''],
V: ['v', 'V', '', ''],
W: ['w', 'W', '', ''],
X: ['x', 'X', '≈', ''],
Y: ['y', 'Y', '', ''],
Z: ['z', 'Z', '', ''],
'`': ['`', '~', '', ''],
1: ['1', '!', '', ''],
2: ['2', '@', '', '\u0000'],
3: ['3', '#', '', ''],
4: ['4', '$', '', ''],
5: ['5', '%', '', ''],
6: ['6', '^', '', ''],
7: ['7', '&', '', ''],
8: ['8', '*', '', ''],
9: ['9', '(', '', ''],
0: ['0', ')', '', ''],
'-': ['-', '_', '‾', ''],
'=': ['=', '+', '±', '∓'],
'[': ['[', '{', '', ''],
']': [']', '}', '', ''],
'\\': ['\\', '|', '', ''],
';': [';', ':', '', ''],
'\'': ['\\', '"', '', ''],
',': [',', '<', '«', ''],
'.': ['.', '>', '»', ''],
'/': ['/', '?', '', ''],
'<backspace>': ['\u0000', '\u0000', '', ''], // null for now, seems reasonable TODO: shift/control backspace?
'<escape>': ['⌂', '⌂', '', ''],
'<enter>': ['\n', '\n', '', ''],
'<space>': [' ', ' ', ' ', ' '],
};
function fromEvent(ev) {
var vkeyChar = vkey[ev.keyCode];
var flags = (ev.shiftKey ? 1 : 0) + (ev.ctrlKey ? 2 : 0); // TODO: metaKey(cmd)? altKey(opt)?
var varChars = _keymap[vkeyChar];
if (!varChars) return null;
if (varChars[flags] === '' && flags === 3) flags = 2; // no shift-control variant, try control
if (varChars[flags] === '' && flags === 2) flags = 0; // no control variant, try normal
var c = varChars[flags];
var tt = fromUnicode(c);
if (tt == null) return null;
if (ev.altKey) tt = -tt; // alt/option key inverts
return tt;
}
module.exports = fromEvent;
|
module.exports = function isPrimitive(arg) {
return arg === null ||
typeof arg === 'boolean' ||
typeof arg === 'number' ||
typeof arg === 'string' ||
typeof arg === 'symbol' || // ES6 symbol
typeof arg === 'undefined';
}
|
import React, { Component } from 'react';
import {
Text,
View
} from 'react-native';
import styles from './style';
const Favorite = () => (
<View style={styles.container}>
<Text>
This is the Favorite page, I beg to be implemented
</Text>
</View>
);
export default Favorite;
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
"use strict";
// Include required modules
var prefs = require("../../../../lib/prefs");
var tabs = require("../../../lib/tabs");
var utils = require("../../../../lib/utils");
var browser = require("../../../lib/ui/browser");
const BASE_URL = collector.addHttpResource("../../../../data/");
const TEST_DATA = BASE_URL + "geolocation/position.html";
const PREF_WIFI_LOGGING = "geo.wifi.logging.enabled";
const TIMEOUT_POSITION = 30000;
function setupModule(aModule) {
// Only geolocation test that tests 3rd party services
// Run this test only against Nightly
if (!utils.appInfo.version.contains("a1")) {
var message = "Geolocation service integration test runs only on Nightly";
testVerifyDisplayGeolocationNotification.__force_skip__ = message;
teardownModule.__force_skip__ = message;
}
aModule.browserWindow = new browser.BrowserWindow();
aModule.controller = aModule.browserWindow.controller;
aModule.locationBar = aModule.browserWindow.navBar.locationBar;
aModule.tabBrowser = new tabs.tabBrowser(aModule.controller);
prefs.setPref(PREF_WIFI_LOGGING, true);
aModule.tabBrowser.closeAllTabs();
}
function teardownModule(aModule) {
prefs.clearUserPref(PREF_WIFI_LOGGING);
aModule.tabBrowser.closeAllTabs();
}
/**
* Test displaying geolocation notification
*/
function testVerifyDisplayGeolocationNotification() {
// Wait for the notification to be opened and check its icon in the location bar
locationBar.waitForNotificationPanel(() => {
controller.open(TEST_DATA);
controller.waitForPageLoad();
}, {type: "notification"});
// Check the geolocation icon is visible in the location bar
var geolocationIcon = locationBar.getElement({type: "notificationIcon",
subtype: "geo"});
expect.ok(geolocationIcon.getNode(), "The notification icon has been found");
// Check the icon inside the popup notification exists
var icon = locationBar.getNotificationElement("geolocation-notification",
{type: "popupid", value: "geolocation"});
expect.ok(icon, "The geolocation icon appears in the notification popup");
// Check if a Share Location button is visible
var locationLabel = utils.getProperty("chrome://browser/locale/browser.properties",
"geolocation.shareLocation");
var button = locationBar.getNotificationElement("geolocation-notification",
{type: "label", value: locationLabel});
expect.ok(button, "'Share location' button appears in the notification popup");
// Wait for the notification to unload
locationBar.waitForNotificationPanel(() => {
button.click();
}, {type: "notification", open: false});
// Check if the location is displayed
// The position updates lazily so additional timeout is needed
var result = new elementslib.ID(controller.tabs.activeTab, "result");
var regExp = /\d+(\.\d*)?\.\d+/;
try {
assert.waitFor(function () {
return regExp.test(result.getNode().textContent);
}, "", TIMEOUT_POSITION);
}
catch (e) {
assert.fail("Geolocation position is: " + result.getNode().textContent);
}
}
|
this["templates"] = this["templates"] || {};
this["templates"]["Basic"] = (function() {
var frag;
function anonymous(data_0) {
var frag = document.createDocumentFragment();
var data = data_0;
var el0 = document.createTextNode("I'm a basic template, yippee!");
frag.appendChild(el0);
return frag;
}
return function template() {
if (!frag) {
frag = anonymous();
}
return frag.cloneNode(true);
};
}());
|
$('ul.dropdown-menu [data-toggle=dropdown]').on('click', function(event) {
// Avoid following the href location when clicking
event.preventDefault();
// Avoid having the menu to close when clicking
event.stopPropagation();
// Re-add .open to parent sub-menu item
$(this).parent().addClass('open');
$(this).parent().find("ul").parent().find("li.dropdown").addClass('open');
});
//making the carousel have a 10 seconds delay
$('.carousel').carousel({
interval: 10000
})
|
export let redditPost = function(state = {}, action) {
return state;
};
|
module.exports = {
publicPath: process.env.NODE_ENV === 'production'
? '/dist/'
: '/',
devServer: {
proxy: {
'/api/v1': {
target: 'http://localhost:8078',
secure: false
},
'/static/': {
target: 'http://localhost:8078',
secure: false
}
}
}
};
|
import { gql, graphql } from 'react-apollo'
import persist from '../lib/persist'
import React from 'react'
import {
Button,
} from 'react-native'
const Logout = ({ logout }) => {
return (
<Button onPress={logout} title='LogOut'></Button>
)
}
const logout = gql`
mutation logout {
logout {
loggedOutAt
}
errors {
code
message
}
}
`
Logout.propTypes = () => ({
logout: React.PropTypes.func.isRequired
})
export default graphql(logout, {
props: ({ mutate }) => ({
logout: () => mutate({
updateQueries: {
userProfile: () => {
// Clear session
persist.willRemoveSessionToken()
// Provide no user
return { user: null, errors: [] }
}
}
})
})
})(Logout)
|
import Em from 'ember';
import { test } from 'ember-qunit';
import startApp from '../helpers/start-app';
import config from 'dummy/config/environment';
var App;
module('Ember CLI Concat', {
setup: function() {
App = startApp();
},
teardown: function() {
Em.run(App, 'reset');
}
});
var checkTagExists = function(fileName) {
var isCSS = fileName.indexOf('.css') > -1;
var attribute = isCSS ? 'href' : 'src';
var element = isCSS ? 'link' : 'script';
var tagExists = $(element + '[' + attribute + '="/assets/' + fileName + '"]').length === 1;
ok(tagExists, fileName + ' ' + element + ' tag should be written to to the index.html file');
};
test('Assets added to index.html file', function() {
andThen(function() {
var env = config.environment;
var appFiles, vendorFiles, testFiles;
if (env === 'development') {
checkTagExists('dummy.css');
checkTagExists('vendor.css');
checkTagExists('dummy.js');
checkTagExists('vendor.js');
if (App.testing) {
checkTagExists('test-support.css');
checkTagExists('test-support.js');
}
} else if (env === 'production') {
/* TODO - Currently can't run tests in production environment */
checkTagExists('app.css');
checkTagExists('app.js');
} else {
expect(0);
}
});
});
|
var PeerServer = require('peer').PeerServer
var Topics = require('./public/js/Topics.js')
var Hapi = require('hapi')
var server = new Hapi.Server({})
server.connection({
port: Number(process.env.PORT) || 8000
})
server.register(require('inert'), function (err) {
if (err) {
throw err
}
server.route({
method: 'GET',
path: '/{param*}',
handler: {
directory: {
path: __dirname + '/public'
}
}
})
server.start(function (err) {
if (err) {
throw err
}
console.log('Server running at:', server.info.uri)
})
})
var io = require('socket.io').listen(server.listener)
var peerServer = new PeerServer({ port: 9000, path: '/chat' })
peerServer.on('connection', function (id) {
io.emit(Topics.USER_CONNECTED, id)
console.log('User connected with #', id)
})
peerServer.on('disconnect', function (id) {
io.emit(Topics.USER_DISCONNECTED, id)
console.log('With #', id, 'user disconnected.')
})
|
/* globals makeAuthRequest,Materialize,micromarkdown,cleanMarkdown */
/* jshint -W003 */ // ugh I'm done with rearranging
"use strict";
var drug, allDrugs, allConsumptions = [],
allExperiences;
var analyticsCount = 0;
var analyticsFinished = 0;
// just get jshint off our back. these are defined in their respective files
var vitals, experience_list, top_listings, hours_days, purchasing;
var autoStart, countdown = 5,
updateInterval;
var hasSelected = false;
function drugSelected() {
if ($('#drug').val().indexOf('dup') > -1) {
$('#drug').val($('#drug').val().split('-')[1]); // break out dups from menu
}
allDrugs.forEach(function(singleDrug) {
if (singleDrug.id === parseInt($('#drug').val())) {
if (location.search.length < 1) {
// only set if we haven't set already, otherwise the page refreshes and we infiniloop
location.search = singleDrug.id;
}
drug = singleDrug;
return;
}
});
document.title = drug.name.substr(0, 1).toUpperCase() + drug.name.substr(1) + ' | SupTracked';
$('.drugName').text(drug.name);
$('#unit').html(drug.unit);
$('#classification').html(drug.classification);
$('#family').html(drug.family);
switch (parseInt(drug.rarity)) {
case 0:
$('#rarity').html('<span class="blue white-text" style="padding: 3px; border-radius: 24px;">Very Common</span>');
break;
case 1:
$('#rarity').html('<span class="green white-text" style="padding: 3px; border-radius: 24px;">Common</span>');
break;
case 2:
$('#rarity').html('<span class="purple white-text" style="padding: 3px; border-radius: 24px;">Uncommon</span>');
break;
case 3:
$('#rarity').html('<span class="red white-text" style="padding: 3px; border-radius: 24px;">Rare</span>');
break;
default:
$('#rarity').html('<span class="grey white-text" style="padding: 3px; border-radius: 24px;">???</span>');
}
$('#notes').html(cleanMarkdown(micromarkdown.parse(drug.notes.split('$$$purchasedata$$$')[0])));
// compile all consumptions
makeAuthRequest('/consumption/search', 'POST', JSON.stringify({
drug_id: drug.id
}), 'json', function(err, data, code) {
allExperiences = data;
if (data) {
data.forEach(function(experience) {
experience.consumptions.forEach(function(consumption) {
if (consumption.drug.id === drug.id) {
consumption.title = experience.title;
consumption.exp_id = experience.id;
allConsumptions.push(consumption);
}
});
});
// sort in ascending date
allConsumptions.sort(function(a, b) {
return (a.date < b.date) ? -1 : (a.date > b.date) ? 1 : 0;
});
$('#drugEntry').attr('href', '/drugs.html?' + drug.id);
// off we go!
startAnalytics();
} else {
$('#selection').hide();
$('#none').show();
analyticsFinished = analyticsCount;
}
});
}
// set up the completion listener
updateInterval = setInterval(function updateCompletion() {
var percentage = Math.round(analyticsFinished / analyticsCount) * 100;
$('#analyticsComplete').text(percentage + '%');
$('#analyticsProgress').css('width', percentage + '%');
if (analyticsFinished === analyticsCount || window.location.hash.substring(1).indexOf('skip') > -1) {
// we're done here; display it after an aesthetic delay for the progress bar to hit 100%
setTimeout(function() {
clearInterval(updateInterval);
$('#loading').hide();
$('#analytics').show();
}, 500);
}
}, 100);
function startAnalytics() {
vitals();
experience_list();
top_listings();
hours_days();
purchasing();
}
// populate the drug dropdown
makeAuthRequest('/drug/all', 'GET', null, 'json', function(err, data, code) {
if (data.length < 1) {
$('#none').show();
return;
}
allDrugs = data.sort(function(a, b) {
a = a.name.toLowerCase();
b = b.name.toLowerCase();
return (a < b) ? -1 : (a > b) ? 1 : 0;
});
var drugsByUsage = allDrugs.slice();
drugsByUsage = drugsByUsage.sort(function(a, b) {
return b.use_count - a.use_count;
}).slice(0, 5);
$('#drug').append('<optgroup label="Common" id="common_dropdwngroup"></optgroup>');
drugsByUsage.forEach(function(drug, index, orig) {
$('#common_dropdwngroup').append('<option value="' + drug.id + '">' + drug.name + '</option>');
orig[index] = drug.id;
});
$('#drug').append('<optgroup label="All" id="all_dropdwngroup"></optgroup>');
allDrugs.forEach(function(drug) {
if (drugsByUsage.indexOf(drug.id) === -1) {
$('#all_dropdwngroup').append('<option value="' + drug.id + '">' + drug.name + '</option>');
} else {
$('#all_dropdwngroup').append('<option value="dup-' + drug.id + '">' + drug.name + '</option>');
}
});
var allIds = allDrugs.map(function(drug) {
return drug.id;
});
// we have a search
if (location.search.length > 1 && allIds.indexOf(Number(location.search.substr(1))) > -1) {
$('#drug').val(location.search.substr(1));
drugSelected();
} else {
$('#drug').val(drugsByUsage[0]);
drugSelected();
}
});
$('#drug').change(function(){
if($('#drug').val().indexOf('dup') > -1){
$('#drug').val($('#drug').val().split('dup-')[1]);
}
location.search = $('#drug').val();
});
|
import {log} from 'node-bits';
const select = (table, column) =>
`select max(${column}) from ${table}`;
const selectPostgres = (table, column) =>
`select max(${column}) from "${table}"`;
const resetPostgres = (table, column, max) =>
`alter sequence "${table}_${column}_seq" restart with ${max + 1}`;
const resetMssql = (table, column, max) =>
`DBCC CHECKIDENT ('[${table}]', RESEED, ${max + 1});`;
const resetMySQL = (sequelize, table, max) =>
`alter table ${table} AUTO_INCREMENT = ${max + 1};`;
const map = {
mysql: {select, reset: resetMySQL},
postgres: {select: selectPostgres, reset: resetPostgres},
mssql: {select, reset: resetMssql},
};
export const resetAutoIncrement = (sequelize, model) => {
const sqlGen = map[sequelize.getDialect()];
if (!sqlGen) {
return Promise.resolve();
}
const table = model.getTableName();
const column = 'id';
const select = sqlGen.select(table, column);
log(select);
return sequelize.query(select).then(result => {
const max = result[0][0].max;
const reset = sqlGen.reset(table, column, max);
log(reset);
return sequelize.query(reset);
});
};
|
'use strict';
module.exports = {
up: function (queryInterface, Sequelize) {
/*
Add altering commands here.
Return a promise to correctly handle asynchronicity.
Example:
return queryInterface.createTable('users', { id: Sequelize.INTEGER });
*/
return queryInterface.createTable(
'procedures',
{
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
rank: {
type: Sequelize.INTEGER,
defaultValue: 0,
allowNull: false
},
categoryId: {
type: Sequelize.INTEGER,
references: {
model: 'categories',
key: 'id'
}
},
createdAt: {
type: Sequelize.DATE,
defaultValue: Sequelize.NOW
},
updatedAt: {
type: Sequelize.DATE,
defaultValue: Sequelize.NOW
}
}
);
},
down: function (queryInterface, Sequelize) {
/*
Add reverting commands here.
Return a promise to correctly handle asynchronicity.
Example:
return queryInterface.dropTable('users');
*/
return queryInterface.dropTable('procedures');
}
};
|
/**
* Created by zhoujialin on 2016/5/4.
*/
const LinkedStateMixin = React.addons.LinkedStateMixin;
// 数据双向绑定
const Comp = React.createClass({
displayname: 'Comp',
mixins:[LinkedStateMixin],
getInitialState(){
return {
name:''
}
},
render(){
return <div>
{this.state.name}
<input type="text" valueLink={this.linkState('name')} />
</div>
}
});
ReactDOM.render(<Comp/>, document.body);
|
import Component from '@ember/component'
import layout from '../../templates/components/bs-table-pagination/table-row'
export default Component.extend({
layout,
tagName: 'tr'
})
|
import {ObserverLocator} from 'aurelia-binding';
import {HttpClient} from 'aurelia-fetch-client';
import breeze from 'breeze-client';
import {Q} from './promise-adapter';
import {BreezeObservationAdapter} from './observation-adapter';
import {AjaxAdapter} from './ajax-adapter'; //eslint-disable-line no-unused-vars
export function configure(frameworkConfig) {
// ensure breeze is using the modelLibrary backing store (vs Knockout or Backbone)
breeze.config.initializeAdapterInstance('modelLibrary', 'backingStore');
// make breeze use our ES6 Promise based version of Q.
breeze.config.setQ(Q);
// provide aurelia with a way to observe breeze properties.
frameworkConfig.container.get(ObserverLocator).addAdapter(new BreezeObservationAdapter());
// provide the ajax adapter with an HttpClient factory...
// the adapter lazily gets the HttpClient instance to enable scenarios where
// the aurelia-breeze plugin is installed prior to the HttpClient being
// configured in the container.
let adapter = breeze.config.initializeAdapterInstance('ajax', 'aurelia', true);
adapter.setHttpClientFactory(() => frameworkConfig.container.get(HttpClient));
}
|
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-51965342-1', 'yaggirbalochi.github.io');
ga('send', 'pageview');
|
'use strict';
angular.module('myApp.products', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/products', {
templateUrl: 'views/products/products-tpl.html',
controller: 'ProductsCtrl'
});
}])
.controller('ProductsCtrl', function($scope, apiInterfaceSrv) {
$scope.apiInterfaceSrv = apiInterfaceSrv;
apiInterfaceSrv.fetch();
$scope.paginationSettings = {
currentPage: 1,
itemsPerPage: 5,
maxSize: 5
}
}
);
|
Array.prototype.splice = function(start, num) {
var additions = $A(arguments).slice(2);
var delta = additions.length - num;
var newlen = this.length + delta;
if (delta >= 0) {
this.length += delta;
}
for (var i = start + num + delta; i < newlen + delta + 1; i++) {
this[i] = this[i - delta];
}
for (var j = start; j < start + additions.length; j++) {
this[j] = additions[j - start];
}
this.length = newlen;
return this;
};
|
const DEGREES_SYMBOL = '\u00B0';
const MINUTES_SYMBOL = "'";
function parseLatitude(latitude) {
return {
degrees: parseInt(latitude.substring(0, 2), 10),
minutes: parseInt(latitude.substring(2, 7), 10) / 1000.0,
direction: latitude[latitude.length - 1]
};
}
function parseLongitude(longitude) {
return {
degrees: parseInt(longitude.substring(0, 3), 10),
minutes: parseInt(longitude.substring(3, 8), 10) / 1000.0,
direction: longitude[longitude.length - 1]
};
}
function toDecimalDegrees(degreesAndMinutes) {
let direction = degreesAndMinutes.direction.toUpperCase();
let sign = (direction === 'N' || direction === 'E') ? 1 : -1;
return sign * (degreesAndMinutes.degrees + degreesAndMinutes.minutes / 60.0);
}
function formatDegreesMinutes(degMin) {
let deg = degMin.degrees.toFixed(0);
let min = degMin.minutes.toFixed(3);
let direction = degMin.direction;
return deg + DEGREES_SYMBOL + min + MINUTES_SYMBOL + direction;
}
export default function parseLatitudeLongitude(latLonString) {
let latitude = parseLatitude(latLonString.substring(0, 8));
let longitude = parseLongitude(latLonString.substring(8));
return {
lat: toDecimalDegrees(latitude),
lng: toDecimalDegrees(longitude),
formatted: formatDegreesMinutes(latitude) + ", " + formatDegreesMinutes(longitude)
};
}
|
version https://git-lfs.github.com/spec/v1
oid sha256:522e5fb03690b037ed9132d4318611bdd12b069343ae441a28118f819f94f2cf
size 678
|
define('blog/app', [
'jquery',
'list'
], function($, List) {
'use strict';
var timeData = [
'<li>',
'<h4><span class="open">▼</span>2014</h4>',
'<ul>',
'<li class="item"><a href="http://ianli-sc.github.io/performanceInspector/">Performance Inspector</a></li>',
'<li class="item"><a href="http://ianli-sc.github.io/jqDataTable/">jQuery data table</a></li>',
'</ul>',
'</li>'
];
List.init(timeData);
});
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _IconBase = require('./../components/IconBase/IconBase');
var _IconBase2 = _interopRequireDefault(_IconBase);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(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) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var IosCrop = function (_React$Component) {
_inherits(IosCrop, _React$Component);
function IosCrop() {
_classCallCheck(this, IosCrop);
return _possibleConstructorReturn(this, Object.getPrototypeOf(IosCrop).apply(this, arguments));
}
_createClass(IosCrop, [{
key: 'render',
value: function render() {
if (this.props.bare) {
return _react2.default.createElement(
'g',
null,
_react2.default.createElement(
'g',
null,
_react2.default.createElement('rect', { x: '128', y: '64', width: '16', height: '48' }),
_react2.default.createElement('polygon', { points: '144,368 144,160 128,160 128,384 352,384 352,368 \t' }),
_react2.default.createElement('rect', { x: '400', y: '368', width: '48', height: '16' }),
_react2.default.createElement('polygon', { points: '64,128 64,144 368,144 368,448 384,448 384,128 \t' })
)
);
}return _react2.default.createElement(
_IconBase2.default,
null,
_react2.default.createElement(
'g',
null,
_react2.default.createElement('rect', { x: '128', y: '64', width: '16', height: '48' }),
_react2.default.createElement('polygon', { points: '144,368 144,160 128,160 128,384 352,384 352,368 \t' }),
_react2.default.createElement('rect', { x: '400', y: '368', width: '48', height: '16' }),
_react2.default.createElement('polygon', { points: '64,128 64,144 368,144 368,448 384,448 384,128 \t' })
)
);
}
}]);
return IosCrop;
}(_react2.default.Component);
exports.default = IosCrop;
;IosCrop.defaultProps = { bare: false };
|
// https://github.com/ed-lea/jquery-collagePlus
//= require jquery.collageplus/v0.3.3/jquery.collageplus.js
|
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker: */
// +---------------------------------------------------------------------------
// | SWAN [ $_SWANBR_SLOGAN_$ ]
// +---------------------------------------------------------------------------
// | Copyright $_SWANBR_COPYRIGHT_$
// +---------------------------------------------------------------------------
// | Version $_SWANBR_VERSION_$
// +---------------------------------------------------------------------------
// | Licensed ( $_SWANBR_LICENSED_URL_$ )
// +---------------------------------------------------------------------------
// | $_SWANBR_WEB_DOMAIN_$
// +---------------------------------------------------------------------------
/**
+------------------------------------------------------------------------------
* madapter attribute
+------------------------------------------------------------------------------
*
* @package
* @version $_SWANBR_VERSION_$
* @copyright $_SWANBR_COPYRIGHT_$
* @author $_SWANBR_AUTHOR_$
+------------------------------------------------------------------------------
*/
function SwanmAdapterAttr() {
ModuleBase.call(this);
/*{{{members*/
var __this = this;
/*}}}*/
/*{{{functions*/
/*{{{init Attr*/
/**
* init Attr
*/
this.init = function () {
D(12312123)
}
/*}}}*/
/*{{{show attr dataTable*/
/**
* show attr dataTable
*/
this.loadIndexList = function () {
$(document).ready(function () {
var madapter_id = $('#madapterAttr_table').attr('madapter_id');
$('#madapterAttr_table').dataTable({
'processing': false,
'serverSide': true,
'ordering': false,
'ajax': {
'url': gPrefixUrl + 'mAdapterAttr_index',
'type': 'post',
'data': {'madapter_id' : madapter_id}
},
'columns': [
{data: function (obj) {
var checkHtml = '<div class="checker"><span><input type="checkbox" value="' + obj.attr_id + '" class="checkboxes" name="attr_id[]"></span></div>';
return checkHtml;
}},
{data: 'attr_name'},
{data: 'attr_display_name'},
{data: 'form_type'},
{data: 'form_data'},
{data: 'attr_default'},
{data: function (obj) {
var __html = [];
__html.push('<a class="btn mini black" href="javascript:;"><i class="icon-edit"></i> Edit</a>');
__html.push('<a class="btn mini black" href="javascript:;"><i class="icon-trash"></i> Delete</a>');
return __html.join(' ');
}}
]
});
//分页
jQuery('#madapterAttr_table_wrapper .dataTables_filter input').addClass("m-wrap small");
jQuery('#madapterAttr_table_wrapper .dataTables_length select').addClass("m-wrap small");
jQuery('#madapterAttr_table_wrapper .dataTables_length select').select2();
});
}
/*}}}*/
/*{{{validate add attr */
/**
* validate add attr
*/
this.initAdd = function () {
},
/*}}}*/
/*{{{add attr data*/
/**
* add attr data
*/
this.addData = function () {
}
/*}}}*/
/*}}}*/
}
|
import OAuth2PasswordGrant from 'ember-simple-auth/authenticators/oauth2-password-grant';
export default OAuth2PasswordGrant.extend({
serverTokenEndpoint: 'http:///localhost:80/employees/admin'
// serverTokenEndpoint: 'http://localhost:80/intranet-api/admin'
});
|
'use strict';
var React = require('react');
var SvgIcon = require('../../svg-icon');
var ImageAssistant = React.createClass({
displayName: 'ImageAssistant',
render: function render() {
return React.createElement(
SvgIcon,
this.props,
React.createElement('path', { d: "M19 2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h4l3 3 3-3h4c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-5.12 10.88L12 17l-1.88-4.12L6 11l4.12-1.88L12 5l1.88 4.12L18 11l-4.12 1.88z" })
);
}
});
module.exports = ImageAssistant;
|
import React from 'react';
import IconBase from './../components/IconBase/IconBase';
export default class IosIonicOutline extends React.Component {
render() {
if(this.props.bare) {
return <g>
<g>
<path d="M425.5,134.8c4.7-5.9,7.5-13.5,7.5-21.6c0-19.2-15.6-34.9-34.8-34.9c-8.2,0-15.7,2.8-21.6,7.5c-34-24.2-75-37.8-119.9-37.8
C141.8,48,48,140.5,48,255.6C48,370.7,141.7,464,256.6,464C371.5,464,464,370.7,464,255.6C464,210.6,449.7,168.9,425.5,134.8z
M398,91.3c12.2,0,22,9.9,22,22c0,12.2-9.9,22-22,22c-12.2,0-22-9.9-22-22C376,101.2,385.8,91.3,398,91.3z M391.8,391.7
c-17.6,17.6-38.2,31.6-61.1,41.3c-23.7,10-48.2,15.2-74.2,15.2c-25.9,0-51.7-5.1-75.4-15.2c-22.9-9.7-43.4-23.5-61.1-41.3
c-17.6-17.6-31.5-38.3-41.2-61.2c-10-23.7-15.1-48.9-15.1-74.9c0-25.9,5.1-51.2,15.1-74.9c9.7-22.9,23.5-43.5,41.2-61.2
s38.2-31.6,61.1-41.3c23.7-10,49.4-14.1,75.4-14.1c25.9,0,50.5,4,74.2,14.1c12.7,5.4,24.7,12.1,35.9,20c-2.1,4.5-3.3,9.5-3.3,14.9
c0,19.2,15.6,34.9,34.8,34.9c5.3,0,10.3-1.2,14.9-3.3c7.9,11.2,14.6,23.2,20,36c10,23.7,15.1,48.9,15.1,74.9
c0,25.9-5.1,51.2-15.1,74.9C423.3,353.4,409.5,374,391.8,391.7z"></path>
<path d="M256.5,160.1c-53,0-96,42.8-96,95.9s42.9,96.1,96,96.1c53,0,96-43,96-96.1S309.5,160.1,256.5,160.1z M256.5,335.8
c-44.1,0-79.7-35.8-79.7-79.8c0-44.1,35.6-79.6,79.7-79.6s79.7,35.6,79.7,79.6C336.2,300.1,300.5,335.8,256.5,335.8z"></path>
</g>
</g>;
} return <IconBase>
<g>
<path d="M425.5,134.8c4.7-5.9,7.5-13.5,7.5-21.6c0-19.2-15.6-34.9-34.8-34.9c-8.2,0-15.7,2.8-21.6,7.5c-34-24.2-75-37.8-119.9-37.8
C141.8,48,48,140.5,48,255.6C48,370.7,141.7,464,256.6,464C371.5,464,464,370.7,464,255.6C464,210.6,449.7,168.9,425.5,134.8z
M398,91.3c12.2,0,22,9.9,22,22c0,12.2-9.9,22-22,22c-12.2,0-22-9.9-22-22C376,101.2,385.8,91.3,398,91.3z M391.8,391.7
c-17.6,17.6-38.2,31.6-61.1,41.3c-23.7,10-48.2,15.2-74.2,15.2c-25.9,0-51.7-5.1-75.4-15.2c-22.9-9.7-43.4-23.5-61.1-41.3
c-17.6-17.6-31.5-38.3-41.2-61.2c-10-23.7-15.1-48.9-15.1-74.9c0-25.9,5.1-51.2,15.1-74.9c9.7-22.9,23.5-43.5,41.2-61.2
s38.2-31.6,61.1-41.3c23.7-10,49.4-14.1,75.4-14.1c25.9,0,50.5,4,74.2,14.1c12.7,5.4,24.7,12.1,35.9,20c-2.1,4.5-3.3,9.5-3.3,14.9
c0,19.2,15.6,34.9,34.8,34.9c5.3,0,10.3-1.2,14.9-3.3c7.9,11.2,14.6,23.2,20,36c10,23.7,15.1,48.9,15.1,74.9
c0,25.9-5.1,51.2-15.1,74.9C423.3,353.4,409.5,374,391.8,391.7z"></path>
<path d="M256.5,160.1c-53,0-96,42.8-96,95.9s42.9,96.1,96,96.1c53,0,96-43,96-96.1S309.5,160.1,256.5,160.1z M256.5,335.8
c-44.1,0-79.7-35.8-79.7-79.8c0-44.1,35.6-79.6,79.7-79.6s79.7,35.6,79.7,79.6C336.2,300.1,300.5,335.8,256.5,335.8z"></path>
</g>
</IconBase>;
}
};IosIonicOutline.defaultProps = {bare: false}
|
import { moduleFor, test } from 'ember-qunit';
moduleFor('controller:login/settings', 'Unit | Controller | login/settings', {
// Specify the other units that are required for this test.
// needs: ['controller:foo']
});
// Replace this with your real tests.
test('it exists', function(assert) {
let controller = this.subject();
assert.ok(controller);
});
|
import {
GET_USER_RECIPES,
GET_USER_RECIPES_ERROR,
DELETE_RECIPE,
DELETE_RECIPE_ERROR
} from '../../actions/actionTypes';
import getUserRecipe from '../../reducers/getUserRecipe';
describe('Test for getUserRecipe reducer should', () => {
it('set recipe when action of type GET_USER_RECIPES is called', () => {
const initialState = {
recipe: { }
};
const action = {
type: GET_USER_RECIPES,
recipes: [
{
id: 3,
name: 'recipe 3',
userId: 1,
},
{
id: 2,
name: 'recipe 2',
userId: 1,
}
]
};
const newState = getUserRecipe(initialState, action);
expect(newState.userRecipes).toEqual(action.recipes);
expect(newState.getUserRecipeError).toEqual(false);
});
it('update store correctly when action of type GET_USER_RECIPES_ERROR is called', () => {
const initialState = {
recipe: { }
};
const action = {
type: GET_USER_RECIPES_ERROR,
addRecipeErrorMessage: 'error'
};
const newState = getUserRecipe(initialState, action);
expect(newState.userRecipes).toEqual([]);
expect(newState.getUserRecipeError).toEqual(true);
});
it('update store correctly when action of type DELETE_RECIPE_ERROR is called', () => {
const initialState = {
recipe: { }
};
const action = {
type: DELETE_RECIPE_ERROR,
addRecipeErrorMessage: 'error'
};
const newState = getUserRecipe(initialState, action);
expect(newState).toBeTruthy();
});
it('set recipe when action of type DELETE_RECIPE is called', () => {
const initialState = {
recipes: { },
userRecipes: [
{
id: 3,
name: 'recipe 3',
userId: 1,
},
{
id: 2,
name: 'recipe 2',
userId: 1,
}
]
};
const action = {
type: DELETE_RECIPE,
recipeId: 3,
recipes: [
{
id: 3,
name: 'recipe 3',
userId: 1
},
{
id: 2,
name: 'recipe 2',
userId: 1,
}
]
};
const newState = getUserRecipe(initialState, action);
expect((newState.userRecipes).length).toEqual(1);
});
});
|
import { Indicator, IndicatorInput } from '../indicator/indicator';
export class CrossInput extends IndicatorInput {
constructor(lineA, lineB) {
super();
this.lineA = lineA;
this.lineB = lineB;
}
}
export class CrossUp extends Indicator {
constructor(input) {
super(input);
this.lineA = input.lineA;
this.lineB = input.lineB;
var currentLineA = [];
var currentLineB = [];
const genFn = (function* () {
var current = yield;
var result = false;
while (true) {
currentLineA.unshift(current.valueA);
currentLineB.unshift(current.valueB);
result = current.valueA > current.valueB;
var pointer = 1;
while (result === true && currentLineA[pointer] >= currentLineB[pointer]) {
if (currentLineA[pointer] > currentLineB[pointer]) {
result = false;
}
else if (currentLineA[pointer] < currentLineB[pointer]) {
result = true;
}
else if (currentLineA[pointer] === currentLineB[pointer]) {
pointer += 1;
}
}
if (result === true) {
currentLineA = [current.valueA];
currentLineB = [current.valueB];
}
current = yield result;
}
});
this.generator = genFn();
this.generator.next();
this.result = [];
this.lineA.forEach((value, index) => {
var result = this.generator.next({
valueA: this.lineA[index],
valueB: this.lineB[index]
});
if (result.value !== undefined) {
this.result.push(result.value);
}
});
}
static reverseInputs(input) {
if (input.reversedInput) {
input.lineA ? input.lineA.reverse() : undefined;
input.lineB ? input.lineB.reverse() : undefined;
}
}
nextValue(valueA, valueB) {
return this.generator.next({
valueA: valueA,
valueB: valueB
}).value;
}
;
}
CrossUp.calculate = crossUp;
export function crossUp(input) {
Indicator.reverseInputs(input);
var result = new CrossUp(input).result;
if (input.reversedInput) {
result.reverse();
}
Indicator.reverseInputs(input);
return result;
}
|
function quadraticEquation(args){
//ax^2 + bx + c = 0
let a = +args[0],
b = +args[1],
c = +args[2];
let x1,x2;
const discriminant = Math.pow(b,2) - 4 * a * c;
if(discriminant === 0){
x1 = x2 =(-b/(2 * a)).toFixed(2);
console.log('x1=x2=' + x1);
}
else if(discriminant < 0){
console.log('no real roots');
}
else if( discriminant > 0){
x1 = ((-b - Math.sqrt(discriminant))/ (2 * a)).toFixed(2);
x2 = ((-b + Math.sqrt(discriminant))/ (2 * a)).toFixed(2);
console.log('x1='+ x1 + ';'+ ' '+ 'x2='+ x2);
}
}
quadraticEquation(['0.2', '9.572', '0.2']);
|
"use strict";
/**
* Created by johan on 27/04/16.
*
* Should be in a directory 1 level up.
*/
var express = require("express");
var vhost = require("vhost");
var tls = require("tls");
var fs = require("fs");
// pass your own objects/apps or use cody.makeWebApp to generate them
// apps should be an application object or an array of, each application object
// should have
// app [express application]
// host [ string or array of strings ]
// should have at least 1 of the 2 below
// http [ portnumber for the http services ]
// https [ portnumber for the https services ]
// should have -if https port is specified-
// certificate [ filename without extention of the key-pair ]
/*
startserver({ app: testApp, https: 443, host: "localhost", certificate: "mykey" });
or
startserver([{...}, {...}]);
or
host: ["localhost", "www.mysite.com", ...]
Cody production example:
------------------------
var cody = require("cody");
cody.makeWebApp(__dirname, "mysite", function(app) {
console.log("Loaded mysite web app with config:", cody.config);
startServer(app);
});
// for multi site hosting, collect all app's in an array
// and when all set up, pass the array to startServer.
Cody development startup:
-------------------------
var cody = require("cody");
cody.makeWebApp(__dirname, "mysite", "config-devel.json", function(app) {
console.log("loaded mysite");
app.app.listen(app.http, function() {
console.log("mysite listening on " + this.address().port);
});
}
*/
// global express app, wrapping all other apps
var exp;
// global object containing for each domain the certificates
var sites;
// collected ports -> example = { 80: false, 443: true }
var ports = {};
module.exports = function( apps ) {
// make our global express app and an empty site list
exp = express();
sites = [];
if (apps instanceof Array) {
for (let app of apps) {
startApp(app);
}
} else {
startApp(apps);
}
// get at least one listener
var http = false;
var https = false;
for (let port in ports) {
if (!ports[port]) http = true;
if (ports[port]) https = true;
}
if (!http && !https) {
http = true;
ports[3000] = false;
}
console.log("==> ports:", ports);
//////////
// http //
//////////
if (http) {
var httpFactory = require('http');
var httpServer = httpFactory.createServer(exp);
// http ports are "false"
for (let port in ports)
if (! ports[port])
httpServer.listen(port, function () {
console.log("Listening for http on port: " + this.address().port);
});
}
///////////
// https //
///////////
if (https) {
var secureOpts = {
SNICallback: function (domain, cb) {
if (typeof sites[domain] === "undefined") {
cb(new Error("domain not found"), null);
console.log("Error: domain not found: " + domain);
} else {
cb(null, sites[domain]);
}
}
/* left out the default keys:
key: fs.readFileSync('....key').toString(),
cert: fs.readFileSync('....crt').toString()
*/
};
var httpsFactory = require('https');
var httpsServer = httpsFactory.createServer(secureOpts, exp);
// https ports are "true"
for (let port in ports)
if (ports[port])
httpsServer.listen(port, function () {
console.log("Listening https on port: " + this.address().port);
console.log(" with certificates: ", sites);
});
}
};
function startApp( application ) {
// collect extra portnumbers
if (application.http && (typeof ports[application.http] === "undefined")) ports[application.http] = false;
if (application.https && (typeof ports[application.https] === "undefined")) ports[application.https] = true;
var certContext;
// if the application has a certificate, create a tls credential context of it
if ((application.certificate) && (application.certificate.length > 0)) {
certContext = tls.createSecureContext({
key: fs.readFileSync(application.certificate + '.key').toString(),
cert: fs.readFileSync(application.certificate + '.crt').toString()
}).context;
}
// start the application for each (virtual) host
if (application.host instanceof Array) {
for (let host of application.host) {
startHost( host, application.app, certContext );
}
} else {
startHost( application.host, application.app, certContext );
}
}
function startHost( host, app, certContext ) {
console.log("added host " + host);
exp.use(vhost(host, app));
if (certContext) {
// if we have a credential context, add it to our hashmap
console.log("added certificates for " + host);
sites[host] = certContext;
}
}
|
'use strict';
var _ = require('lodash');
var async = require('async');
var config = require('config');
var queue = require('./services/queue-service')(config);
var workers = require('./lib/workers');
var Message = require('./lib/message');
var process = function() {
queue.receiveMessage(function(err, data) {
if (data.Messages && data.Messages.length) {
var message = new Message().ingest(data.Messages[0]);
console.log('Processing message:', message);
async.series([
function(callback) {
async.applyEachSeries(_.pluck(workers, 'process'), message, callback);
},
function(callback) {
queue.deleteMessage(message, callback);
}
], function(err, data) {
if (err) {
console.log(err, err.stack);
} else {
console.log('Done');
}
});
} else {
console.log('No messages to process at this time');
}
});
};
console.log('Worker started');
(function poll() {
process();
setTimeout(poll, 30e3);
})();
|
args = Array.prototype.slice.call(args, 1);
// [0] = type, [1] = lib.jar [2] = blockX, [3] = classX
var File = java.io.File,
FileReader = java.io.FileReader,
FileInputStream = java.io.FileInputStream,
FRAMEWORK = args[0],
out = java.lang.System.out,
err = java.lang.System.err,
Modifier = java.lang.reflect.Modifier,
clz,
ZipInputStream = java.util.zip.ZipInputStream,
zis = new ZipInputStream(new FileInputStream(args[1])),
entry = null;
var content = [
'/*********************',
'## Events Helper Module (' + FRAMEWORK + ' version)',
'The Events helper module provides a suite of functions - one for each possible event.',
'For example, the events.' + args[2] + '() function is just a wrapper function which calls events.on(' + args[3] + ', callback, priority)',
'This module is a convenience wrapper for easily adding new event handling functions in JavaScript. ',
'At the in-game or server-console prompt, players/admins can type `events.` and use TAB completion ',
'to choose from any of the approx. 160 different event types to listen to.',
'',
'### Usage',
'',
' events.' + args[2] + '( function( event ) { ',
' echo( event.player, \'You broke a block!\'); ',
' });',
'',
'The crucial difference is that the events module now has functions for each of the built-in events. The functions are accessible via TAB-completion so will help beginning programmers to explore the events at the server console window.',
'',
'***/'
];
var canary = false;
if (FRAMEWORK == 'CanaryMod') {
canary = true;
}
for (var i = 0; i < content.length; i++) {
out.println(content[i]);
}
while ((entry = zis.nextEntry) != null) {
var name = new String(entry.name);
var re1 = /org\/bukkit\/event\/.+Event\.class$/;
if (canary) {
re1 = /net\/canarymod\/hook\/.+Hook\.class$/;
}
if (re1.test(name)) {
name = name.replace(/\//g, '.').replace('.class', '');
try {
clz = java.lang.Class.forName(name);
} catch (e) {
err.println('Warning: could not Class.forName("' + name + '")');
clz = engine.eval(name);
}
var isAbstract = Modifier.isAbstract(clz.getModifiers());
if (isAbstract) {
continue;
}
var parts = name.split('.');
var shortName = null;
if (canary) {
shortName = name.replace('net.canarymod.hook.', '');
}
if (!canary) {
shortName = name.replace('org.bukkit.event.', '');
}
var fname = parts.reverse().shift().replace(/^(.)/, function (a) {
return a.toLowerCase();
});
if (!canary) {
fname = fname.replace(/Event$/, '');
}
if (canary) {
fname = fname.replace(/Hook$/, '');
}
var javaDoc = canary ? 'https://ci.visualillusionsent.net/job/CanaryLib/javadoc/net/canarymod/hook/' : 'https://hub.spigotmc.org/javadocs/spigot/org/bukkit/event/';
var comment = [
'/*********************',
'### events.' + fname + '()',
'',
'#### Parameters ',
'',
' * callback - A function which is called whenever the [' + shortName + ' event](' + javaDoc + shortName.replace('.', '/') + '.html) is fired',
'',
' * priority - optional - see events.on() for more information.',
'',
'***/'
//http://jd.bukkit.org/rb/apidocs/org/bukkit/event/player/PlayerJoinEvent.html
];
for (var i = 0; i < comment.length; i++) {
out.println(comment[i]);
}
out.println('exports.' + fname + ' = function(callback,priority){ ');
if (canary) {
out.println(' return events.on(Packages.' + name + ',callback,priority);');
} else {
out.println(' return events.on(' + name + ',callback,priority);');
}
out.println('};');
}
}
|
(function() {
'use strict';
var logger = require('../my_modules/logHelper.js');
var common = require('../my_modules/common.js');
var edModel = require('../models/edModel.js');
var express = require('express');
var router = express.Router();
router.get('/account/regist', function(req, res, next) {
var api = [
{
name: 'seed',
url: '/api/ed25519-supercop/createSeed',
type: 'get',
params: {},
results: {
seed: null
}
},
{
name: 'keyPair',
url: '/api/ed25519-supercop/createKeyPair',
type: 'get',
params: {
seed: 'seed'
},
results: {}
}
];
var attach = {
};
var resource = [
'/public/css/animate.min.css',
'/public/css/common.css',
'/public/js/lib/socket.io.min.js',
'/public/js/lib/crypto-js.js',
'/public/js/account/regist.js'
];
common.dataFactory(req, res, api, attach, function(err, data) {
res.render('./account/regist.html', data, function(err, html) {
res.send(common.addResource(html, resource));
});
});
});
router.get('/account/login', function(req, res, next) {
var api = [];
var attach = {};
var resource = [
'/public/css/animate.min.css',
'/public/css/common.css',
'/public/js/lib/crypto-js.js',
'/public/js/account/login.js'
];
if (req.query.logout) {
req.session.keyPair = null;
}
common.dataFactory(req, res, api, attach, function(err, data) {
res.render('./account/login.html', data, function(err, html) {
res.send(common.addResource(html, resource));
});
});
});
router.post('/account/login', function(req, res, next) {
var data = {};
if (edModel.isKeyPair(req.body)) {
req.session.keyPair = req.body;
data.success = true;
data.message = '密钥文件正确';
} else {
data.success = false;
data.message = '密钥文件不正确';
}
res.json(data);
});
module.exports = router;
})();
|
$("#toogle-wms").css("visibility", "visible");
//swir wms
var swirwms = L.tileLayer.betterWms("http://landsatfact-data-dev.nemac.org/lsf-cr-swir-allchange?AOI_ID=368", {
layers: 'swir-archiveMaskForForestCloud',
format: 'image/png',
transparent: true,
attribution: '<a href="http://www.landsatfact.com">Landsat FACT</a>',
maxZoom: 15,
opacity: 0.65
});
//ndvi wms
var ndviwms = L.tileLayer.betterWms("http://landsatfact-data-dev.nemac.org/lsf-cr-ndvi?AOI_ID=368", {
layers: 'ndvi-archiveMaskForForestCloud',
format: 'image/png',
transparent: true,
attribution: '<a href="http://www.landsatfact.com">Landsat FACT</a>',
maxZoom: 15,
opacity: 0.65
});
//ndmi wms
var ndmiwms = L.tileLayer.betterWms("http://landsatfact-data-dev.nemac.org/lsf-cr-ndmi?AOI_ID=368", {
layers: 'ndmi-archiveMaskForForestCloud',
format: 'image/png',
transparent: true,
attribution: '<a href="http://www.landsatfact.com">Landsat FACT</a>',
maxZoom: 15,
opacity: 0.65
});
//set overlays for map
var wmsLayers = {
"SWIR(wms)":swirwms,
"NDMI(wms)":ndmiwms,
"NDVI(wms)":ndviwms
};
overlayMaps.push(wmsLayers);
|
module.exports.init = function (db, words, callback) {
var batch = db.batch()
words.forEach(function (word) {
var key = word.length + '!' + word
batch.put(key, word)
})
batch.write(function (err) {
if (err)
callback(err)
else
callback(null)
})
}
module.exports.query = function (db, word, callback) {
var start = word.length + '!' + word.replace(/\*/g, '')
var end = word.length + '!' + word.replace(/\*/g, '~')
var results = []
var options = { start: start,
end: end,
keys: false,
values: true }
db.createReadStream(options).on('data', function (word) {
results.push(word)
}).on('error', function(err) {
if (err)
callback(err)
}).on('end', function() {
callback(null, results)
})
}
|
import { makeIconComponent } from './utils/icon-wrapper'
import { MenuNav3 } from '@clair/icons'
export const IconMenuNav3 = /*@__PURE__*/ makeIconComponent({
name: 'CIconMenuNav3',
template: MenuNav3
})
|
import prop from "./prop";
import flip from "./flip";
/**
* Returns the value at the specified property.
* The only difference from `prop` is the parameter order.
*
* @func
* @memberOf R
* @see R.prop
* @category Object
* @param {Object} obj The object to query
* @param {String} prop The property name
* @return {*} The value at obj.p
* @example
*
* prop({x: 100}, 'x'); // => 100
*/
export default flip(prop);
|
// tracknewcomments.js
// Copyright (c) 2017 Miles Bright, MIT License
// https://github.com/smilesbright/onewordeachbot
'use strict';
const snoowrap = require('snoowrap');
const jsonfile = require('jsonfile');
const requestParameters = {
client_id: process.env.CLIENTID,
client_secret: process.env.CLIENTSECRET,
username: process.env.USERNAME,
password: process.env.PASSWORD,
user_agent: process.env.USERAGENT
};
const request = new snoowrap(requestParameters);
//
// This method checks text for punctuation that ends a sentence.
//
function hasPunctuation(text) {
while (text[text.length - 1] === ' ') {
text = text.slice(0, text.length - 1);
}
var c = text[text.length - 1];
if (c == '.' || c == '?' || c == '!') {
return true;
}
else {
return false;
}
}
//
// This script requests new comments from /r/onewordeach and adds comments with
// punctuation to comments.json data storage file to be tracked.
//
jsonfile.readFile('./comments.json', function(err, obj) {
request.getNewComments('onewordeach').then(function(newComments) {
// go through the list of new comments
newComments.forEach(function(newComment) {
// if comment has a punctuation
if (hasPunctuation(newComment.body)) {
// if it's not already in comments list
var hasBeenAdded = 0;
obj.comments.forEach(function(commentListing) {
if (commentListing.id == newComment.id) {
hasBeenAdded = 1;
}
});
if (hasBeenAdded == 0) {
// and if its thread doesn't already have a comment from bot
var addNewComment = true;
for (var j=0; j < obj.comments.length; j++) {
if (obj.comments[j].thread == newComment.link_id && obj.comments[j].hasposted == 1) {
addNewComment = false;
}
//console.log(obj.comments[j].thread);
}
if (addNewComment == true) {
// add new comment to list.
var newComment = {id: newComment.id, thread: newComment.link_id,
hasposted: 0, daysOld: 0, score: newComment.score};
obj.comments.push(newComment);
jsonfile.writeFile('./comments.json', obj); // < completely rewrites entire json file.
}
}
}
});
});
});
|
'use strict';
(function(){
var camera, scene, renderer;
var projector;
setup();
function setup(){
setupCanvas();
setupScene();
requestAnimationFrame(function animate(){
renderer.render(scene, camera);
requestAnimationFrame(animate);
});
}
function setupCanvas(){
camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 10000);
camera.position.y = 10;
camera.position.z = 800;
scene = new THREE.Scene();
renderer = new THREE.WebGLRenderer({
antialias: true
});
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// Set up user click events
projector = new THREE.Projector();
renderer.domElement.addEventListener('mousedown', function(event){
var vector = new THREE.Vector3(
renderer.devicePixelRatio * (event.pageX - this.offsetLeft) / this.width * 2 - 1,
-renderer.devicePixelRatio * (event.pageY - this.offsetTop) / this.height * 2 + 1,
0
);
projector.unprojectVector(vector, camera);
var raycaster = new THREE.Raycaster(
camera.position,
vector.sub(camera.position).normalize()
);
var intersects = raycaster.intersectObjects(scene.children);
intersects[0].object.material.color.set(0xff0000);
intersects[0].object.position.y = 0;
}, false);
}
function setupScene(){
var light = new THREE.DirectionalLight(0xffffff, 1);
light.position.set(1, 1, 1).normalize();
scene.add(light);
// Cube model
var geometry = new THREE.IcosahedronGeometry(100, 2);
for (var i = 0; i < 20; i++) {
var cube = new THREE.Mesh(geometry, new THREE.MeshLambertMaterial({
color: Math.random() * 0xffffff,
wireframe: true,
wireframeLinewidth: 3
}));
cube.position.x = Math.floor(Math.random() * 200 - 100) * 4;
cube.position.y = Math.floor(Math.random() * 200 - 100) * 4;
cube.position.z = Math.floor(Math.random() * 200 - 100) * 4;
scene.add(cube);
}
}
})();
|
const shell = require('shelljs');
const path = require('path');
console.log('Patch react-devtools-core');
const rdStandalone = path.join(
__dirname,
'../dist/node_modules/react-devtools-core/dist/standalone.js'
);
// Avoid logging from react-devtools-core
// log: connected, disconnected
// error: listening error (can be seen directly in the panel)
shell.sed(
'-i',
// eslint-disable-next-line
/\(_console[0-9]* = console\).(log|warn|error).apply\(_console[0-9]*, \[ "\[React DevTools\]" \].concat\(args\)\)/,
'',
rdStandalone
);
console.log('Patch react-dev-utils/launchEditor');
shell.sed(
'-i',
/require\('chalk'\)/g,
'{red:f=>f,cyan:f=>f,green:f=>f}',
path.join(__dirname, '../node_modules/react-dev-utils/launchEditor.js')
);
|
'use strict';
describe('Controller: AboutCtrl', function () {
// load the controller's module
beforeEach(module('angularWeatherApp'));
var AboutCtrl,
scope;
// Initialize the controller and a mock scope
beforeEach(inject(function ($controller, $rootScope) {
scope = $rootScope.$new();
AboutCtrl = $controller('AboutCtrl', {
$scope: scope
});
}));
it('should attach a list of awesomeThings to the scope', function () {
expect(scope.awesomeThings.length).toBe(3);
});
});
|
var sage = require('../../../build/sage');
var Schema = sage.Schema;
var UserSchema = new Schema({
USER_ID: {
type: "number",
readonly: true
},
CREATED_AT: {
type: "timestamp",
readonly: true
},
USERNAME: {
type: "varchar"
},
POSTS: {
type: "association",
joinType: "hasMany",
joinsWith: "SAGE_TEST.POSTS",
foreignKeys: {
mine: "USER_ID",
theirs: "USER_ID"
},
model: "SAGE_TEST.POSTS"
},
PROFILE: {
type: "association",
joinType: "hasOne",
joinsWith: "SAGE_TEST.PROFILES",
foreignKeys: {
mine: "USER_ID",
theirs: "USER_ID"
},
model: "SAGE_TEST.PROFILES"
}
}, {
primaryKey: "USER_ID"
});
module.exports = sage.model("SAGE_TEST.USERS", UserSchema);
|
define(['views/attributes_view', 'views/attribute_view', 'views/topic_map_attribute_view'], function(AttributesView, AttributeView, TopicMapAttributeView){
var TopicHeaderView = AttributesView.extend({
ordinals: function(){
return this.model.constructor.headers;
},
items: function(){
var model = this.model;
return this.ordinals().map(function(attr){
var view;
if (attr === 'topic_map_id') {
var tm = model.client().db.topic_maps.get(model.topic_map_id());
view = new TopicMapAttributeView({model: tm, attribute: 'id'});
} else {
view = new AttributeView({model: model, attribute: attr});
}
return view;
});
}
});
return TopicHeaderView;
});
|
"use strict";
define(['backbone','model/DomoticModelMapper', 'config'],
function(Backbone, DomoticModelMapper, config) {
return Backbone.Collection.extend({
url: config.rest.domoticItems,
model: function (attrs, options) {
return new (DomoticModelMapper(attrs['@type']))(attrs, options);
},
//localStorage: new Backbone.LocalStorage('domotic-items'),
comparator: 'name',
startAutoRefresh: function(interval) {
var self = this;
this.autoRefreshID = setInterval(function() {
self.fetch();
}, interval);
},
stopAutoRefresh: function() {
clearInterval(this.autoRefreshID);
}
});
}
);
|
var express = require('express');
var router = express.Router();
var childProcess = require('child_process'),
jav;
router.get('/', function(req, res, next) {
var idModel = req.query.idModel,
predResult;
jav = childProcess.exec('java -jar C:\\Users\\AegisLabs\\irfan-db\\Dropbox\\THESIS\\c0d3\\TwitterPredictionWithSVR\\dist\\TwitterPredictionWithSVR.jar '+idModel+' jml_respon_pertahap timestamp', function (error, stdout, stderr) {
if (error) {
console.log(error.stack);
console.log('Error code: '+error.code);
console.log('Signal received: '+error.signal);
}
predResult = JSON.parse(stdout);
res.json(predResult);
});
jav.on('exit', function (code) {
console.log('Child process exited with exit code '+ code);
//res.send(predResult);
});
});
router.get('/listHashtag', function(req, res, next){
var idUser = req.query.idUser;
var UserHashtag = [
[{'id' : 999, 'label' : 'pilih tagar', 'id' : 0, 'label' : '#bebasLembab', 's' : '02:06:33', 'e': ' 02:56:33'}, {'id' : 3, 'label' : '#hostForInfinity', 's': '13:27:53', 'e': '14:17:53'}],
[{'id' : 999, 'label' : 'pilih tagar', 'id' : 1, 'label' : '#pestaKeluargaErtiga', 's': '16:48:25', 'e': '17:38:25'}],
[{'id' : 999, 'label' : 'pilih tagar', 'id' : 2, 'label' : '#jkw4p', 's' : '18:11:58', 'e' : '19:01:58'}],
[{'id' : 999, 'label' : 'pilih tagar', 'id' : 4, 'label' : '#happynest', 's' : '19:49:50', 'e' : '20:39:50'}]
]
res.json(UserHashtag[idUser]);
});
module.exports = router;
|
// generator: babel-node
// adapted from kangax's tests
var key1 = {};
var key2 = {};
var weakmap = new WeakMap([[key1, 123], [key2, 456]]);
console.log (weakmap.has(key1) && weakmap.get(key1) === 123 &&
weakmap.has(key2) && weakmap.get(key2) === 456);
|
define(['app'],function(UniversalDesignBootstrap) {
UniversalDesignBootstrap.module('Routers.WizardModule', function(WizardModuleRouter, UniversalDesignBootstrap, Backbone, Marionette, $, _) {
// Marionette uses an AppRouter to drop in Controllers. Basically is Controller.method, i.e. '': 'showWizard' = Controller.showWizard
WizardModuleRouter.Router = Marionette.AppRouter.extend({
before: function () {
App.startSubApp('WizardModule', {});
},
appRoutes:{
'': 'showStep',
'step/:stepNumber': 'showStep'
}
});
// Always check that WizardModule is started and do any necessary surrounding updates for general action execution in this module
var executeAction = function(action, arg) {
UniversalDesignBootstrap.startSubApp("WizardModule");
action(arg);
// UniversalDesignBootstrap.execute("set:active:header", "contacts");
};
// Public API for this Modules' routing
var API = {
// shows whatever step should be shown in url #step/:stepNumber
showStep: function(stepNumber){
require(['../apps/wizard/controllers/index'], function(WizardController) {
if (!stepNumber) {
stepNumber = 0;
}
UniversalDesignBootstrap.navigate('step/' + stepNumber);
executeAction(WizardController.showStep, stepNumber);
});
},
// add another model for the same collection
addAnother: function(stepNumber) {
require(['../apps/wizard/controllers/index'], function(WizardController) {
});
}
};
// Global events that can be triggered in this module
UniversalDesignBootstrap.on('WizardModule:step:showStep', function(stepNumber) {
UniversalDesignBootstrap.navigate('step/' + stepNumber);
API.showStep(stepNumber);
});
// Setup the Marionette controller
UniversalDesignBootstrap.addInitializer(function() {
new WizardModuleRouter.Router({
controller: API
});
});
});
return UniversalDesignBootstrap.WizardModuleRouter;
});
|
/**
* Backbone-tastypie.js 0.1
* (c) 2011 Paul Uithol
*
* Backbone-tastypie may be freely distributed under the MIT license.
* Add or override Backbone.js functionality, for compatibility with django-tastypie.
*/
(function( undefined ) {
"use strict";
// Backbone.noConflict support. Save local copy of Backbone object.
var Backbone = window.Backbone;
Backbone.Tastypie = {
doGetOnEmptyPostResponse: true,
doGetOnEmptyPutResponse: false,
apiKey: {
username: '',
key: ''
}
};
/**
* Override Backbone's sync function, to do a GET upon receiving a HTTP CREATED.
* This requires 2 requests to do a create, so you may want to use some other method in production.
* Modified from http://joshbohde.com/blog/backbonejs-and-django
*/
Backbone.oldSync = Backbone.sync;
Backbone.sync = function( method, model, options ) {
var headers = '';
if ( Backbone.Tastypie.apiKey && Backbone.Tastypie.apiKey.username.length ) {
headers = _.extend( {
'Authorization': 'ApiKey ' + Backbone.Tastypie.apiKey.username + ':' + Backbone.Tastypie.apiKey.key
}, options.headers );
options.headers = headers;
}
if ( ( method === 'create' && Backbone.Tastypie.doGetOnEmptyPostResponse ) ||
( method === 'update' && Backbone.Tastypie.doGetOnEmptyPutResponse ) ) {
var dfd = new $.Deferred();
// Set up 'success' handling
dfd.done( options.success );
options.success = function( resp, status, xhr ) {
// If create is successful but doesn't return a response, fire an extra GET.
// Otherwise, resolve the deferred (which triggers the original 'success' callbacks).
if ( !resp && ( xhr.status === 201 || xhr.status === 202 || xhr.status === 204 ) ) { // 201 CREATED, 202 ACCEPTED or 204 NO CONTENT; response null or empty.
var location = xhr.getResponseHeader( 'Location' ) || model.id;
return $.ajax( {
url: location,
headers: headers,
success: dfd.resolve,
error: dfd.reject
});
}
else {
return dfd.resolveWith( options.context || options, [ resp, status, xhr ] );
}
};
// Set up 'error' handling
dfd.fail( options.error );
options.error = function( xhr, status, resp ) {
dfd.rejectWith( options.context || options, [ xhr, status, resp ] );
};
// Make the request, make it accessibly by assigning it to the 'request' property on the deferred
dfd.request = Backbone.oldSync( method, model, options );
return dfd;
}
return Backbone.oldSync( method, model, options );
};
Backbone.Model.prototype.idAttribute = 'resource_uri';
Backbone.Model.prototype.url = function() {
// Use the id if possible
var url = this.id;
// If there's no idAttribute, use the 'urlRoot'. Fallback to try to have the collection construct a url.
// Explicitly add the 'id' attribute if the model has one.
if ( !url ) {
url = this.urlRoot;
url = url || this.collection && ( _.isFunction( this.collection.url ) ? this.collection.url() : this.collection.url );
if ( url && this.has( 'id' ) ) {
url = addSlash( url ) + this.get( 'id' );
}
}
url = url && addSlash( url );
return url || null;
};
/**
* Return the first entry in 'data.objects' if it exists and is an array, or else just plain 'data'.
*/
Backbone.Model.prototype.parse = function( data ) {
return data && data.objects && ( _.isArray( data.objects ) ? data.objects[ 0 ] : data.objects ) || data;
};
/**
* Return 'data.objects' if it exists.
* If present, the 'data.meta' object is assigned to the 'collection.meta' var.
*/
Backbone.Collection.prototype.parse = function( data ) {
if ( data && data.meta ) {
this.meta = data.meta;
}
return data && data.objects;
};
Backbone.Collection.prototype.url = function( models ) {
var url = this.urlRoot || ( models && models.length && models[0].urlRoot );
url = url && addSlash( url );
// Build a url to retrieve a set of models. This assume the last part of each model's idAttribute
// (set to 'resource_uri') contains the model's id.
if ( models && models.length ) {
var ids = _.map( models, function( model ) {
var parts = _.compact( model.id.split( '/' ) );
return parts[ parts.length - 1 ];
});
url += 'set/' + ids.join( ';' ) + '/';
}
return url || null;
};
var addSlash = function( str ) {
return str + ( ( str.length > 0 && str.charAt( str.length - 1 ) === '/' ) ? '' : '/' );
}
})();
|
'use strict';
angular.module( 'mmOrders', [] )
.provider( '$mmOrdersConfig', function() {
this.$get = function() {
return {
'itemFind': '/Shop/Parts/Search',
};
};
} )
.config( [
'$mmApiProvider',
function($mmApiProvider) {
$mmApiProvider.addRoute( 'website', 'shop', '/Shop' );
},
] )
.run( [
'$rootScope',
'mmOrders',
'dataStore',
function($rootScope, mmOrders, dataStore) {
$rootScope.$on( 'authentication:endSession', function(broadcastName, data) {
mmOrders.init();
$rootScope.$broadcast( 'mmOrders:change', null );
} );
$rootScope.$on( 'mmOrders:change', function() {
mmOrders.$save();
} );
if (angular.isObject( dataStore.get( 'mmOrders' ) )) {
mmOrders.$restore( dataStore.get( 'mmOrders' ) );
} else {
mmOrders.init();
}
},
] )
.directive( 'mmOrdersList', [
'mmOrders',
function(mmOrders) {
return {
restrict : 'EA',
transclude: true,
link : function(scope) {
scope.items = mmOrders.store.cart.items;
scope.cartTotalUniqueItems = function() {
return mmOrders.cartTotalUniqueItems();
};
},
};
},
] )
.service( 'mmOrders', [
'$mmOrdersConfig',
'$q',
'toasty',
'dataStore',
'$localStorage',
'mmProduct',
'$http',
'$rootScope',
'api',
function($mmOrdersConfig, $q, toasty, dataStore, $localStorage, mmProduct, $http, $rootScope, api) {
var self = this;
self.init = function() {
self.store = {
cart : {
items: [],
},
forms: [],
order: {},
};
};
$rootScope.$watch( function() {
return $localStorage.mmOrders;
}, function() {
if (angular.isObject( angular.fromJson( $localStorage.mmOrders ) )) {
var items = angular.fromJson( $localStorage.mmOrders ).cart.items;
self.store.cart.items.splice( 0, self.store.cart.items.length );
angular.forEach( items, function(item) {
self.store.cart.items.push( new mmProduct( item ) );
} );
}
}, true );
self.itemGet = function(item) {
var deferred = $q.defer();
api.get( 'website', 'parts', item ).then( function(response) {
deferred.resolve( new mmProduct( response.data.data.part ) );
} ).catch( function(response) {
deferred.reject( response.data.data );
} );
return deferred.promise;
};
self.itemFind = function(itemQuery) {
var deferred = $q.defer();
$http.post( $mmOrdersConfig.itemFind, {search: itemQuery} ).then( function(response) {
deferred.resolve( response.data.data.items );
} ).catch( function(response) {
deferred.reject( response.data.data.items );
} );
return deferred.promise;
};
},
] ).value( 'version', '0.0.1' );
|
Session.setDefault('showGame', 'false');
UI.body.helpers({
showGame: function (state) {
return Session.equals('showGame', state);
}
});
|
var Service, Characteristic;
var apcUps = require("./snmp.js");
var ipaddress = require("./ipaddress");
var ups = new apcUps(ipaddress);
const DEF_MIN_TEMPERATURE = -100,
DEF_MAX_TEMPERATURE = 100,
DEF_TIMEOUT = 5000;
module.exports = function(homebridge) {
Service = homebridge.hap.Service;
Characteristic = homebridge.hap.Characteristic;
homebridge.registerAccessory("homebridge-apc-snmp", "APC", APCAccessory);
}
function APCAccessory(log, config) {
this.log = log;
this.name = config["name"];
this.location = config["location"];
this.model = config["model"] || "Model not available";
this.serial = config["serial"] || "Non-defined serial";
this.minTemperature = config["min_temp"] || DEF_MIN_TEMPERATURE;
this.maxTemperature = config["max_temp"] || DEF_MAX_TEMPERATURE;
this.temperature = 0.0;
this.service = "Temperature Sensor";
}
APCAccessory.prototype = {
getState: function(callback) {
ups.getTemperature(function(error,temperature) {
console.log('The current temperature is:', temperature, 'C');
console.dir();
return(null,temperature);
}).bind(this)},
identify: function(callback) {
this.log("Identify requested!");
callback(); // success
},
getServices: function () {
var informationService = new Service.AccessoryInformation();
informationService
.setCharacteristic(Characteristic.Manufacturer, this.manufacturer)
.setCharacteristic(Characteristic.Model, this.model)
.setCharacteristic(Characteristic.SerialNumber, this.serial);
if (this.service == "Temperature Sensor") {
temperatureService = new Service.TemperatureSensor("Room Temperature");
temperatureService
.getCharacteristic(Characteristic.CurrentTemperature)
.on('get', this.getState.bind(this));
return [informationService, temperatureService];
}
}
};
|
'use strict';
System.register(['aurelia-pal', './aurelia-plugins-cookie-consent-config'], function (_export, _context) {
"use strict";
var PLATFORM, Config;
function configure(aurelia, configCallback) {
var instance = aurelia.container.get(Config);
if (configCallback !== undefined && typeof configCallback === 'function') configCallback(instance);
aurelia.globalResources([PLATFORM.moduleName('./aurelia-plugins-cookie-consent-element')]);
}
_export('configure', configure);
return {
setters: [function (_aureliaPal) {
PLATFORM = _aureliaPal.PLATFORM;
}, function (_aureliaPluginsCookieConsentConfig) {
Config = _aureliaPluginsCookieConsentConfig.Config;
}],
execute: function () {}
};
});
|
"use strict";
function render() {
return React.createElement("div", {className: 'component'}, React.createElement("div", {className: 'component__title'}, "Title"), React.createElement("div", {className: 'component__footer'}, "Title"));
}
|
let errorConstructors = {};
function generateErrorConstructor(options) {
function F(message) {
this.message = message || options.message;
this.code = options.code;
this.status = options.status;
this.name = options.name;
};
F.prototype = Error.prototype;
Object.defineProperty(F, 'name', {
value: options.name,
writable: false
});
errorConstructors[options.name] = F;
}
const definitions = [
{
name: 'LoginValidationError',
message: 'Login validation failed.',
code: 100,
status: 400
},
{
name: 'LoginNotFoundError',
message: 'A record could not be found with the credentials provided.',
code: 101,
status: 404
},
{
name: 'RegistrationValidationError',
message: 'Registration validation failed.',
code: 102,
status: 400
},
{
name: 'ForgottenPasswordValidationError',
message: 'Forgotten password validation failed.',
code: 104,
status: 400
},
{
name: 'ResetPasswordTokenValidationError',
message: 'The reset password token is invalid or has expired.',
code: 106,
status: 400
},
{
name: 'ResetPasswordValidationError',
message: 'Reset password validation failed.',
code: 107,
status: 400
},
{
name: 'EmailVerificationTokenValidationError',
message: 'The email address verification token is invalid or has expired.',
code: 109,
status: 400
},
{
name: 'UserNotFoundError',
message: 'User not found.',
code: 200,
status: 404
},
{
name: 'UserValidationError',
message: 'User validation failed.',
code: 201,
status: 400
},
{
name: 'UserPermissionError',
message: 'Permission denied to access user.',
code: 202,
status: 403
},
{
name: 'WishListNotFoundError',
message: 'Wish list not found.',
code: 300,
status: 404
},
{
name: 'WishListValidationError',
message: 'Wish list validation failed.',
code: 301,
status: 400
},
{
name: 'WishListPermissionError',
message: 'Permission denied to access wish list.',
code: 302,
status: 403
},
{
name: 'GiftNotFoundError',
message: 'Gift not found.',
code: 400,
status: 404
},
{
name: 'GiftValidationError',
message: 'Gift validation failed.',
code: 401,
status: 400
},
{
name: 'GiftPermissionError',
message: 'Permission denied to access gift.',
code: 402,
status: 403
},
{
name: 'CommentNotFoundError',
message: 'Comment not found.',
code: 500,
status: 404
},
{
name: 'CommentValidationError',
message: 'Comment validation failed.',
code: 501,
status: 400
},
{
name: 'CommentPermissionError',
message: 'Permission denied to access comment.',
code: 502,
status: 403
},
{
name: 'DibNotFoundError',
message: 'Dib not found.',
code: 600,
status: 404
},
{
name: 'DibValidationError',
message: 'Dib validation failed.',
code: 601,
status: 400
},
{
name: 'DibPermissionError',
message: 'Permission denied to access dib.',
code: 602,
status: 403
},
{
name: 'FriendshipNotFoundError',
message: 'Friendship not found.',
code: 700,
status: 404
},
{
name: 'FriendshipValidationError',
message: 'Friendship validation failed.',
code: 701,
status: 400
},
{
name: 'FriendshipPermissionError',
message: 'Permission denied to access friendship.',
code: 702,
status: 403
},
{
name: 'NotificationNotFoundError',
message: 'Notification not found.',
code: 800,
status: 404
},
{
name: 'NotificationValidationError',
message: 'Notification validation failed.',
code: 801,
status: 400
},
{
name: 'NotificationPermissionError',
message: 'Permission denied to access notification.',
code: 802,
status: 403
},
{
name: 'FeedbackValidationError',
message: 'Feedback validation failed.',
code: 901,
status: 400
}
];
definitions.forEach((definition) => {
generateErrorConstructor(definition);
});
module.exports = errorConstructors;
|
import React from 'react';
import { SubmitButton } from '../form-fields/submit-button.js';
export class CardSizeButton extends React.Component {
constructor(props) {
super(props);
this.updateSize = this.updateSize.bind(this);
};
updateCardSize(size) {
var cards = document.querySelector('.spell-card-container');
cards.setAttribute("data-card-size", size);
}
updateSize(e) {
let size = e.target.innerHTML;
let active = document.querySelector(".size-buttons .btn.active");
let buttons = document.querySelectorAll(".size-buttons");
if (e.target.className.indexOf("active") > -1) {
e.target.className = "btn";
size = "";
} else if (active) {
active.className = active.className.replace(/active/g,"");
e.target.className += " active";
} else {
e.target.className += " active";
}
this.updateCardSize(size);
}
render() {
return <div className="size-buttons">
<SubmitButton cssClass="sm" label="sm" onUpdate={this.updateSize} />
<SubmitButton cssClass="md" label="md" onUpdate={this.updateSize} />
<SubmitButton cssClass="lg" label="lg" onUpdate={this.updateSize} />
<SubmitButton cssClass="xl" label="xl" onUpdate={this.updateSize} />
</div>
}
}
|
'use strict';
var gulp = require('gulp');
var browserSync = require('browser-sync');
var runSequence = require('run-sequence');
gulp.task('reload', function() {
// runSequence('styles', 'ie8styles', 'ie7styles', 'views', 'images', 'js','scripts','copyfonts', 'watch',function(){
// });
console.log('reloading **************************************');
browserSync.reload();
});
|
// All symbols in the `Zs` category as per Unicode v9.0.0:
[
'\x20',
'\xA0',
'\u1680',
'\u2000',
'\u2001',
'\u2002',
'\u2003',
'\u2004',
'\u2005',
'\u2006',
'\u2007',
'\u2008',
'\u2009',
'\u200A',
'\u202F',
'\u205F',
'\u3000'
];
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.