code stringlengths 2 1.05M |
|---|
const Joi = require('joi');
const _validateRequest = (schema, isValidateBody) => {
return (req, res, next) => {
let obj = isValidateBody ? req.body : req.query;
let { error, value } = Joi.validate(obj, schema);
if(error) {
let message = _formatErrorMessage(error);
return res.status(400).json({message});
}
next();
};
}
const _formatErrorMessage = (joiError) => {
return joiError.details.map(d => d.message).join(',');
}
const validateBody = (schema) => {
return _validateRequest(schema, true);
}
const validateQuery = (schema) => {
return _validateRequest(schema, false);
}
module.exports = {
validateBody,
validateQuery
}; |
module.exports = {
/*
* Global configuration.
* These values are used in 'gruntfile.js', usually for globbing
* patterns. I.e. <%= build_dir %>
*
*/
source_dir: './src/',
build_dir: './build/',
compile_dir: './application/',
/*
* Build configuration.
* The build object below loads the scripts in the provided order
* and writes <script> tags in 'index.html'
*
* Build scripts should not be minified; this will make it easier
* to debug as we'll see full exception messages in references to
* specific line numbers.
*
* The CSS files defined here will be concatenated and minified,
* together with the stylesheets present in '/assets'.
* 'vendor_css' + 'src/assets' -> build/src/assets/app.min.css
*
*/
build: {
vendor_js: [
//written in 'index.html' in this order
'./vendor/wow/dist/wow.js',
'./vendor/jquery/dist/jquery.js',
'./vendor/angular/angular.js',
'./vendor/angular-ui-router/release/angular-ui-router.js',
'./vendor/angular-mocks/angular-mocks.js',
'./vendor/angular-load/angular-load.js',
'./vendor/angular-scroll/angular-scroll.js',
'./vendor/fingerprint/fingerprint.js',
'./vendor/angular-translate/angular-translate.js',
'./vendor/angular-sanitize/angular-sanitize.js',
'./vendor/angulike/angulike.js',
'./vendor/a0-angular-storage/dist/angular-storage.js',
'./vendor/hamsterjs/hamster.js',
'./vendor/angular-mousewheel/mousewheel.js',
'./vendor/angular-animate/angular-animate.js',
'./vendor/angular-messages/angular-messages.js'
],
vendor_css: [
//concatenated with 'assets' stylesheets in 'app.min.css'
'./vendor/bootstrap-fadeit/dist/css/bootstrap.min.css',
'./vendor/font-awesome/css/font-awesome.min.css',
'./vendor/animate.css/animate.min.css'
]
},
/*
* Compile configuration.
* The compile object is similar to the build one, except it
* contains two Arrays: one for minified scripts and one for
* unminified ones.
* The reason for this is that usually (but not always), Bower
* dependencies also have a minified version of a component,
* therefore there is no reason for us to minify it again.
*
*/
compile: {
vendor_min_js: [
//won't minify again
'./vendor/wow/dist/wow.min.js',
'./vendor/jquery/dist/jquery.min.js',
'./vendor/angular/angular.min.js',
'./vendor/angular-ui-router/release/angular-ui-router.min.js',
'./vendor/angular-load/angular-load.min.js',
'./vendor/angular-scroll/angular-scroll.min.js',
'./vendor/angular-translate/angular-translate.min.js',
'./vendor/angular-sanitize/angular-sanitize.min.js',
'./vendor/a0-angular-storage/dist/angular-storage.min.js',
'./vendor/angular-animate/angular-animate.min.js',
'./vendor/angular-messages/angular-messages.min.js'
],
vendor_js: [
//doesn't have a min files, will minify
'./vendor/fingerprint/fingerprint.js',
'./vendor/angulike/angulike.js',
'./vendor/hamsterjs/hamster.js',
'./vendor/angular-mousewheel/mousewheel.js'
]
},
/*
* Common configuration.
* Common resources are vendor (third party) assets that have to
* be included in the project source and are not JavaScript or
* CSS files.
*
* The common object contains only fonts, but might as well
* contain other assets.
* (Note: if there are other types of assets, then the grunfile.
* js needs to be updated accordingly; there is no task set up
* for other common resources)
*
* Setting up a new common resource should be done by following
* the fonts implementation in the copy task:
*
* copy: {
* ............................................................
* build_resource: {
* src: ['<%= common.vendor_resource %>'],
* dest: '<%= build_dir %>src/assets/resource-type/',
* expand: true,
* flatten: true,
* filter: 'isFile'
* },
* ............................................................
* }
*
* The task should also be added in the 'build' task:
*
* grunt.registerTask('build', [
* ............................................................
* 'copy:build_resource',
* ............................................................
*
*/
common: {
vendor_fonts: [
'./vendor/bootstrap-fadeit/dist/fonts/**/*',
'./vendor/font-awesome/fonts/**/*'
]
},
/*
* The module file order Array.
* As the name suggests, this object is used to dictate a
* certain module file order.
*
* The order of AngularJS modules is important because the app
* might be easily be broken if a Controller is defined before
* the module that contains it.
*
*/
module_file_order: [
//Init files contain global configuration
'**/*.init.js',
//Config files are used to define module dependecies on the root module after application bootstrap (using the 'pushAfterBootstrap' method). The config files also contain the module config block (angular.module('name').config()) and the constant blocks (angular.module('name').constant()).
'**/*.config.js',
'**/*.translations.js',
//Run blocks are used to execute code after the injector is created and are used to kickstart the application
'**/*.run.js',
//Services represent angular services, but also can also be a factory, provider or value. The rule of thumb is to always use 'file.service.js' for any of these components.
'**/*.service.js',
'**/*.factory.js',
'**/*.provider.js',
'**/*.value.js',
//After services come controllers and finally directives and filters
'**/*.controller.js',
'**/*.directive.js',
'**/*.filter.js'
]
};
|
var Model = useModel('Model');
/**
* Privilege Model
*/
function Privilege(){
this.collection = 'privileges';
}
Privilege.prototype = new Model();
module.exports = new Privilege;
|
import React, { Component } from "react";
import { observer } from "mobx-react";
import styled from "styled-components";
import IfYesThenFirst from "../IfYesThenFirst";
import Textbox from '../../atoms/Textbox';
const RecordingContainer = styled.div`
display: flex;
justify-content: space-between;
background-color: ${props => (props.active ? "wheat" : "#f1f1f1")};
padding: 5px;
cursor: pointer;
margin-bottom: 2px;
padding-left: 15px;
margin: 5px;
color: #727e96;
min-height: 33px;
`;
const RecordingLabel = styled.span``;
const RecordingButton = styled.button`margin-left: 5px;`;
class Recording extends Component {
constructor() {
super();
this.state = {
isEdit: false
};
}
render() {
const {
currentTracker,
recording,
playRecording,
renameRecording,
removeRecording
} = this.props;
return (
<RecordingContainer>
{!this.state.isEdit && <RecordingLabel>{recording.name}</RecordingLabel>}
{this.state.isEdit && (
<Textbox
style={{ width: '400px' }}
inputRef={ele => (this.renameTextbox = ele)}
placeholder="Name"
defaultValue={recording.name}
/>
)}
<div>
{!this.state.isEdit && (
<RecordingButton
className="btn btn-sm"
onClick={() => {
playRecording(currentTracker.id, recording.recordingId);
}}
>
Play
</RecordingButton>
)}
<RecordingButton
className="btn btn-sm"
onClick={event => {
if (this.state.isEdit) {
renameRecording(
recording.recordingId,
this.renameTextbox.value
);
}
this.setState({
isEdit: !this.state.isEdit
});
}}
>
{this.state.isEdit ? "Save" : "Edit"}
</RecordingButton>
<RecordingButton
className="btn btn-sm"
onClick={() => {
currentTracker.removeRecording(recording.recordingId);
}}
>
Delete
</RecordingButton>
</div>
</RecordingContainer>
);
}
}
export default observer(Recording);
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _objectAssign = require('object-assign');
var _objectAssign2 = _interopRequireDefault(_objectAssign);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
/**
* Utility for extracting border style props from components
*/
var sides = ['', 'Top', 'Right', 'Bottom', 'Left'];
function borderStyles(props) {
props = props || {};
return _objectAssign2.default.apply(undefined, [{}].concat(_toConsumableArray(sides.map(function (side) {
var attr = 'border' + side;
var value = props[attr];
if (value === undefined) {
return {};
} else if (typeof value === 'number') {
var _ref;
return _ref = {}, _defineProperty(_ref, attr + 'Style', 'solid'), _defineProperty(_ref, attr + 'Width', value + 'px'), _ref;
} else {
return _defineProperty({}, attr + 'Style', value ? 'solid' : 'none');
}
}))));
}
exports.default = borderStyles; |
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
* @format
* @emails oncall+relay
*/
'use strict';
const DataChecker = require('./DataChecker');
const RelayCore = require('./RelayCore');
const RelayDefaultHandlerProvider = require('../handlers/RelayDefaultHandlerProvider');
const RelayInMemoryRecordSource = require('./RelayInMemoryRecordSource');
const RelayModernRecord = require('./RelayModernRecord');
const RelayObservable = require('../network/RelayObservable');
const RelayPublishQueue = require('./RelayPublishQueue');
const RelayResponseNormalizer = require('./RelayResponseNormalizer');
const invariant = require('invariant');
const normalizePayload = require('./normalizePayload');
const normalizeRelayPayload = require('./normalizeRelayPayload');
const warning = require('warning');
import type {HandlerProvider} from '../handlers/RelayDefaultHandlerProvider';
import type {
GraphQLResponse,
Network,
PayloadData,
PayloadError,
UploadableMap,
} from '../network/RelayNetworkTypes';
import type {Subscription} from '../network/RelayObservable';
import type {
Environment,
OperationLoader,
MatchFieldPayload,
MissingFieldHandler,
OperationSelector,
OptimisticUpdate,
RelayResponsePayload,
NormalizationSelector,
ReaderSelector,
FragmentOwner,
SelectorStoreUpdater,
Snapshot,
Store,
StoreUpdater,
UnstableEnvironmentCore,
} from '../store/RelayStoreTypes';
import type {NormalizationSplitOperation} from '../util/NormalizationNode';
import type {CacheConfig, Disposable} from '../util/RelayRuntimeTypes';
export type EnvironmentConfig = {|
+configName?: string,
+handlerProvider?: HandlerProvider,
+operationLoader?: OperationLoader,
+network: Network,
+store: Store,
+missingFieldHandlers?: $ReadOnlyArray<MissingFieldHandler>,
|};
class RelayModernEnvironment implements Environment {
_operationLoader: ?OperationLoader;
_network: Network;
_publishQueue: RelayPublishQueue;
_store: Store;
configName: ?string;
unstable_internal: UnstableEnvironmentCore;
_missingFieldHandlers: ?$ReadOnlyArray<MissingFieldHandler>;
constructor(config: EnvironmentConfig) {
this.configName = config.configName;
const handlerProvider = config.handlerProvider
? config.handlerProvider
: RelayDefaultHandlerProvider;
const operationLoader = config.operationLoader;
if (__DEV__) {
if (operationLoader != null) {
invariant(
typeof operationLoader === 'object' &&
typeof operationLoader.get === 'function' &&
typeof operationLoader.load === 'function',
'RelayModernEnvironment: Expected `operationLoader` to be an object ' +
'with get() and load() functions, got `%s`.',
operationLoader,
);
}
}
this._operationLoader = operationLoader;
this._network = config.network;
this._publishQueue = new RelayPublishQueue(config.store, handlerProvider);
this._store = config.store;
this.unstable_internal = RelayCore;
(this: any).__setNet = newNet => (this._network = newNet);
// Register this Relay Environment with Relay DevTools if it exists.
// Note: this must always be the last step in the constructor.
const _global =
typeof global !== 'undefined'
? global
: typeof window !== 'undefined'
? window
: undefined;
const devToolsHook = _global && _global.__RELAY_DEVTOOLS_HOOK__;
if (devToolsHook) {
devToolsHook.registerEnvironment(this);
}
if (config.missingFieldHandlers != null) {
this._missingFieldHandlers = config.missingFieldHandlers;
}
}
getStore(): Store {
return this._store;
}
getNetwork(): Network {
return this._network;
}
applyUpdate(optimisticUpdate: OptimisticUpdate): Disposable {
const dispose = () => {
this._publishQueue.revertUpdate(optimisticUpdate);
this._publishQueue.run();
};
this._publishQueue.applyUpdate(optimisticUpdate);
this._publishQueue.run();
return {dispose};
}
revertUpdate(update: OptimisticUpdate): void {
this._publishQueue.revertUpdate(update);
this._publishQueue.run();
}
replaceUpdate(update: OptimisticUpdate, newUpdate: OptimisticUpdate): void {
this._publishQueue.revertUpdate(update);
this._publishQueue.applyUpdate(newUpdate);
this._publishQueue.run();
}
applyMutation({
operation,
optimisticResponse,
optimisticUpdater,
}: {
operation: OperationSelector,
optimisticUpdater?: ?SelectorStoreUpdater,
optimisticResponse?: Object,
}): Disposable {
return this.applyUpdate({
operation,
selectorStoreUpdater: optimisticUpdater,
response: optimisticResponse || null,
});
}
check(readSelector: NormalizationSelector): boolean {
if (this._missingFieldHandlers == null) {
return this._store.check(readSelector);
}
return this._checkSelectorAndHandleMissingFields(
readSelector,
this._missingFieldHandlers,
);
}
commitPayload(
operationSelector: OperationSelector,
payload: PayloadData,
): void {
// Do not handle stripped nulls when commiting a payload
const relayPayload = normalizeRelayPayload(operationSelector.root, payload);
this._publishQueue.commitPayload(operationSelector, relayPayload);
this._publishQueue.run();
}
commitUpdate(updater: StoreUpdater): void {
this._publishQueue.commitUpdate(updater);
this._publishQueue.run();
}
lookup(readSelector: ReaderSelector, owner?: FragmentOwner): Snapshot {
return this._store.lookup(readSelector, owner);
}
subscribe(
snapshot: Snapshot,
callback: (snapshot: Snapshot) => void,
): Disposable {
return this._store.subscribe(snapshot, callback);
}
retain(selector: NormalizationSelector): Disposable {
return this._store.retain(selector);
}
_checkSelectorAndHandleMissingFields(
selector: NormalizationSelector,
handlers: $ReadOnlyArray<MissingFieldHandler>,
): boolean {
const target = new RelayInMemoryRecordSource();
const result = DataChecker.check(
this._store.getSource(),
target,
selector,
handlers,
this._operationLoader,
);
if (target.size() > 0) {
this._publishQueue.commitSource(target);
this._publishQueue.run();
}
return result;
}
/**
* Returns an Observable of GraphQLResponse resulting from executing the
* provided Query or Subscription operation, each result of which is then
* normalized and committed to the publish queue.
*
* Note: Observables are lazy, so calling this method will do nothing until
* the result is subscribed to: environment.execute({...}).subscribe({...}).
*/
execute({
operation,
cacheConfig,
updater,
}: {
operation: OperationSelector,
cacheConfig?: ?CacheConfig,
updater?: ?SelectorStoreUpdater,
}): RelayObservable<GraphQLResponse> {
return RelayObservable.create(sink => {
let optimisticResponse = null;
const subscriptions: Set<Subscription> = new Set();
function start(subscription): void {
// NOTE: store the subscription object on the observer so that it
// can be cleaned up in complete() or the dispose function.
this._subscription = subscription;
subscriptions.add(subscription);
}
function complete(): void {
subscriptions.delete(this._subscription);
if (subscriptions.size === 0) {
sink.complete();
}
}
// Convert each GraphQLResponse from the network to a RelayResponsePayload
// and process it
function next(response: GraphQLResponse): void {
const payload = normalizePayload(operation, response);
const isOptimistic = response.extensions?.isOptimistic === true;
processRelayPayload(payload, operation, updater, isOptimistic);
sink.next(response);
}
// Each RelayResponsePayload contains both data to publish to the store
// immediately, but may also contain matchPayloads that need to be
// asynchronously normalized into RelayResponsePayloads, which may
// themselves have matchPayloads: this function is recursive and relies
// on GraphQL queries *disallowing* recursion to ensure termination.
const processRelayPayload = (
payload: RelayResponsePayload,
operationSelector: OperationSelector | null = null,
payloadUpdater: SelectorStoreUpdater | null = null,
isOptimistic: boolean = false,
): void => {
const {matchPayloads} = payload;
if (matchPayloads && matchPayloads.length) {
const operationLoader = this._operationLoader;
invariant(
operationLoader,
'RelayModernEnvironment: Expected an operationLoader to be ' +
'configured when using `@match`.',
);
matchPayloads.forEach(matchPayload => {
processMatchPayload(
processRelayPayload,
operationLoader,
matchPayload,
).subscribe({
complete,
error: sink.error,
start,
});
});
}
if (isOptimistic) {
invariant(
optimisticResponse === null,
'environment.execute: only support one optimistic response per ' +
'execute.',
);
optimisticResponse = {
source: payload.source,
fieldPayloads: payload.fieldPayloads,
};
this._publishQueue.applyUpdate(optimisticResponse);
this._publishQueue.run();
} else {
if (optimisticResponse !== null) {
this._publishQueue.revertUpdate(optimisticResponse);
optimisticResponse = null;
}
if (operationSelector && payloadUpdater) {
this._publishQueue.commitPayload(
operationSelector,
payload,
payloadUpdater,
);
} else {
this._publishQueue.commitRelayPayload(payload);
}
this._publishQueue.run();
}
};
const {node} = operation;
this._network
.execute(node.params, operation.variables, cacheConfig || {})
.subscribe({
complete,
next,
error: sink.error,
start,
});
return () => {
if (subscriptions.size !== 0) {
subscriptions.forEach(sub => sub.unsubscribe());
subscriptions.clear();
}
if (optimisticResponse !== null) {
this._publishQueue.revertUpdate(optimisticResponse);
optimisticResponse = null;
this._publishQueue.run();
}
};
});
}
/**
* Returns an Observable of GraphQLResponse resulting from executing the
* provided Mutation operation, the result of which is then normalized and
* committed to the publish queue along with an optional optimistic response
* or updater.
*
* Note: Observables are lazy, so calling this method will do nothing until
* the result is subscribed to:
* environment.executeMutation({...}).subscribe({...}).
*/
executeMutation({
operation,
optimisticResponse,
optimisticUpdater,
updater,
uploadables,
}: {|
operation: OperationSelector,
optimisticUpdater?: ?SelectorStoreUpdater,
optimisticResponse?: ?Object,
updater?: ?SelectorStoreUpdater,
uploadables?: ?UploadableMap,
|}): RelayObservable<GraphQLResponse> {
let optimisticUpdate;
if (optimisticResponse || optimisticUpdater) {
optimisticUpdate = {
operation: operation,
selectorStoreUpdater: optimisticUpdater,
response: optimisticResponse || null,
};
}
const {node} = operation;
return this._network
.execute(node.params, operation.variables, {force: true}, uploadables)
.do({
start: () => {
if (optimisticUpdate) {
this._publishQueue.applyUpdate(optimisticUpdate);
this._publishQueue.run();
}
},
next: payload => {
if (optimisticUpdate) {
this._publishQueue.revertUpdate(optimisticUpdate);
optimisticUpdate = undefined;
}
this._publishQueue.commitPayload(
operation,
normalizePayload(operation, payload),
updater,
);
this._publishQueue.run();
},
error: error => {
if (optimisticUpdate) {
this._publishQueue.revertUpdate(optimisticUpdate);
optimisticUpdate = undefined;
this._publishQueue.run();
}
},
unsubscribe: () => {
if (optimisticUpdate) {
this._publishQueue.revertUpdate(optimisticUpdate);
optimisticUpdate = undefined;
this._publishQueue.run();
}
},
});
}
/**
* @deprecated Use Environment.execute().subscribe()
*/
sendQuery({
cacheConfig,
onCompleted,
onError,
onNext,
operation,
}: {
cacheConfig?: ?CacheConfig,
onCompleted?: ?() => void,
onError?: ?(error: Error) => void,
onNext?: ?(payload: GraphQLResponse) => void,
operation: OperationSelector,
}): Disposable {
warning(
false,
'environment.sendQuery() is deprecated. Update to the latest ' +
'version of react-relay, and use environment.execute().',
);
return this.execute({operation, cacheConfig}).subscribeLegacy({
onNext,
onError,
onCompleted,
});
}
/**
* @deprecated Use Environment.executeMutation().subscribe()
*/
sendMutation({
onCompleted,
onError,
operation,
optimisticResponse,
optimisticUpdater,
updater,
uploadables,
}: {
onCompleted?: ?(errors: ?Array<PayloadError>) => void,
onError?: ?(error: Error) => void,
operation: OperationSelector,
optimisticUpdater?: ?SelectorStoreUpdater,
optimisticResponse?: Object,
updater?: ?SelectorStoreUpdater,
uploadables?: UploadableMap,
}): Disposable {
warning(
false,
'environment.sendMutation() is deprecated. Update to the latest ' +
'version of react-relay, and use environment.executeMutation().',
);
return this.executeMutation({
operation,
optimisticResponse,
optimisticUpdater,
updater,
uploadables,
}).subscribeLegacy({
// NOTE: sendMutation has a non-standard use of onCompleted() by passing
// it a value. When switching to use executeMutation(), the next()
// Observer should be used to preserve behavior.
onNext: payload => {
onCompleted && onCompleted(payload.errors);
},
onError,
onCompleted,
});
}
toJSON(): mixed {
return `RelayModernEnvironment(${this.configName ?? ''})`;
}
}
/**
* Processes a MatchFieldPayload, asynchronously resolving the fragment,
* using it to normalize the field data into a RelayResponsePayload.
* Because @match fields may contain other @match fields, the result of
* normalizing `matchPayload` may contain *other* MatchFieldPayloads:
* the processRelayPayload() callback is responsible for publishing
* both the normalize payload's source as well as recursively calling
* this function for any matchPayloads it contains.
*
* @private
*/
function processMatchPayload(
processRelayPayload: RelayResponsePayload => void,
operationLoader: OperationLoader,
matchPayload: MatchFieldPayload,
): RelayObservable<void> {
return RelayObservable.from(
new Promise((resolve, reject) => {
operationLoader
.load(matchPayload.operationReference)
.then(resolve, reject);
}),
).map((operation: ?NormalizationSplitOperation) => {
if (operation == null) {
return;
}
const selector = {
dataID: matchPayload.dataID,
variables: matchPayload.variables,
node: operation,
};
const source = new RelayInMemoryRecordSource();
const matchRecord = RelayModernRecord.create(
matchPayload.dataID,
matchPayload.typeName,
);
source.set(matchPayload.dataID, matchRecord);
const normalizeResult = RelayResponseNormalizer.normalize(
source,
selector,
matchPayload.data,
);
const relayPayload = {
errors: null, // Errors are handled as part of the parent GraphQLResponse
fieldPayloads: normalizeResult.fieldPayloads,
matchPayloads: normalizeResult.matchPayloads,
source: source,
};
processRelayPayload(relayPayload);
});
}
// Add a sigil for detection by `isRelayModernEnvironment()` to avoid a
// realm-specific instanceof check, and to aid in module tree-shaking to
// avoid requiring all of RelayRuntime just to detect its environment.
(RelayModernEnvironment: any).prototype['@@RelayModernEnvironment'] = true;
module.exports = RelayModernEnvironment;
|
//////////// inspired by ionicframework modal
var ngModal = angular.module('ngModal',[]);
ngModal.factory('ModalProvider',['$rootScope', '$compile','$timeout', '$http', '$q', function($rootScope, $compile,$timeout,$http,$q){
var service = {};
var status = {};
// var modals = {};
var currentModal = null;
function fetchTemplate(url,opts) {
return $http.get(url,{cache: opts.cache})
.then(function(res){
return res.data && res.data.trim();
});
}
function compile(template,opts) {
var scope = opts.scope && opts.scope.$new() || $rootScope.$new(true);
return $compile(template)(scope);
}
function Modal(url,opts){
var self = this;
self.url = url;
self.opts = opts || {
cache: true // cache template
};
fetchTemplate(url,self.opts).then(function(template){
self.compiledTpl = compile(template,self.opts);
if(opts.pre_append){
service.setModal(self);
//$contentWrapper.append(self.compiledTpl);
}
if(self.status === Modal.STATUS.PENDING){
self.status = Modal.STATUS.RESOLVED;
self.show();
}
self.status = Modal.STATUS.RESOLVED;
});
//modals[url] = this;
}
/// status
Modal.STATUS = {
RESOLVED: 1,
PENDING: 2
};
Modal.prototype.show = function(){
if(this.status !== Modal.STATUS.RESOLVED){
this.status = Modal.STATUS.PENDING;
return;
}
if(currentModal !== this){
service.setModal(this);
}
$backdrop.addClass('active');
};
Modal.prototype.hide = function(){
$backdrop.removeClass('active');
};
var $backdrop = angular.element('<div class="fixed top ng-modal left right cover flex-row center">');
var $contentWrapper = angular.element('<div class="modal-content-wrapper">');
$backdrop.append($contentWrapper);
$backdrop.on('click',function(e){
e.stopPropagation();
$backdrop.removeClass('active');
});
$contentWrapper.on('click',function(e){
e.stopPropagation();
});
document.body.appendChild($backdrop[0]);
service.fromTemplateUrl = function(url,opts){
//return modals[url] || new Modal(url,opts);
return new Modal(url,opts);
};
service.setModal = function(modal){
currentModal = modal;
$contentWrapper.html('');
$contentWrapper.append(modal.compiledTpl);
};
///////
///for dev console inspect
// service.modals = modals;
// window.ModalProvider = service;
return service;
}]); |
import React, {Component} from 'react';
import {action, toJS} from 'mobx';
import {inject} from 'mobx-react';
import {Button} from 'react-bootstrap';
@inject('designStore')
export default class ClearAllButton extends Component {
constructor(props) {
super(props);
}
render() {
return <Button bsStyle='warning' className='pull-right' onClick={() => {
this.props.designStore.clear()
}}>Clear all</Button>
}
}
|
/**
* John Resig 的 assert 函数,做了小封装
*/
window.assert = window.assert || function () {
var output = document.getElementById('output')
return function (outcome, description) {
var li = document.createElement('li')
li.className = outcome ? 'pass' : 'fail'
li.appendChild(document.createTextNode(description))
output.appendChild(li)
}
}() |
let Victor = require('victor');
let PBody = require('../PBody.js').PBody;
let Ability = new (require('./Abilities/Abilities.js').Abilities)();
const PLAYER_STATE = {
'DEFAULT': 0,
'INVULNERABLE': 1
};
class Player{
constructor(id){
this.id = id;
this.state = PLAYER_STATE.DEFAULT;
this.color = global.randomFromArray(global.PALETTE.PLAYER) || 'white';
this.pbody = new PBody();
this.speed = 20;
this.maxSpeed = 10;
// Event/input handlers
this._onCollision = Ability.bite.bind(this);
this._onClick = Ability.dash.bind(this);
this._onRightClick = undefined;
}
get onCollision(){
if(this._onCollision) return this._onCollision;
return () => {};
}
get onClick(){
if(this._onClick) return this._onClick;
return () => {};
}
get onRightClick(){
if(this._onRightClick) return this._onRightClick;
return () => {};
}
eatParticle(p){
this.pbody.mass += p.pbody.mass;
}
moveToMouse(data){
// Camera coords in world space
let cameraLoc = new Victor(this.pbody.loc.x + data.w/2, this.pbody.loc.y + data.h/2);
// Mouse coords in world space
let mouseLoc = cameraLoc.clone().subtract(new Victor(data.x, data.y));
// Vector from player to mouse
let playerToMouse = this.pbody.loc.clone().subtract(mouseLoc);
// If the mouse is close enough to the player, hold still
/*if(playerToMouse.magnitude() < 10){
this.pbody.vel.x = this.pbody.vel.y = 1;
return;
}*/
// Vector from player to mouse
let force = playerToMouse.normalize();
force.x *= this.speed;
force.y *= this.speed;
this.pbody.applyForce(force);
}
update(){
if(this.pbody.mass <= 0){
this.pbody = new PBody();
return;
}
if(this.pbody.loc.magnitude() > 500){
let centerForce = this.pbody.loc.clone().multiply(new Victor(-1,-1));
this.pbody.applyForce(centerForce);
}
this.pbody.move(this.maxSpeed);
}
}
module.exports.Player = Player; |
/** MarkDocTheme Object
*
* The Theme object which handles retrieval of theme pieces
*
**/
var $ = require('./Utils.js'),
rsvp = require('rsvp'),
_ = require('underscore'),
path = require('path'),
marked = require('marked'),
MarkedProcessor = require('./MarkedProcessor.js');
marked.setOptions({
gfm: true,
tables: true,
renderer: MarkedProcessor,
headerPrefix: 'h'
});
function MarkDocTheme (Doc) {
// DEFAULT VALUES
this.__header = path.resolve(__dirname, '../themes/default/header.html');
this.__nav = path.resolve(__dirname, '../themes/default/nav.html');
this.__footer = path.resolve(__dirname, '../themes/default/footer.html');
MarkedProcessor.setDoc(Doc);
// Add Styles
this.addContent(Doc);
}
MarkDocTheme.prototype.addContent = function (Doc) {
Doc.addLESS(path.resolve(__dirname, '../themes/default/css/styles.less'));
Doc.addLESS(path.resolve(__dirname, '../themes/default/css/print.css'));
Doc.addJS(path.resolve(__dirname, '../themes/default/js/script.js'));
};
MarkDocTheme.prototype.renderHeader = function (opts) {
return this.__render(this.__header, opts);
};
MarkDocTheme.prototype.renderNav = function (opts) {
return this.__render(this.__nav, opts);
};
MarkDocTheme.prototype.renderContent = function (md, page) {
MarkedProcessor.setPage(page);
if(this.__content)
return this.__render(this.__content, {'Content':marked(md)});
else
return rsvp.Promise(function (res) {
var html = marked(md);
res("\t\t<article id=\"page-"+page.getID()+"\">\n\t\t\t"+html+"\n\t\t</article>");
});
};
MarkDocTheme.prototype.renderFooter = function (opts) {
return this.__render(this.__footer, opts);
};
MarkDocTheme.prototype.__render = function (file, opts) {
return rsvp.Promise(function (res, rej) {
$.PromiseReader(file).then(function (tmpl) {
try {
res( _.template(tmpl)(opts) );
} catch(e) {
rej( e.stack );
}
}, rej);
});
};
module.exports = MarkDocTheme; |
"use strict";
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;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var core_1 = require('@angular/core');
var http_1 = require('@angular/http');
var router_1 = require('@angular/router');
var ng2_toastr_1 = require('ng2-toastr/ng2-toastr');
var SupportService = (function () {
// constructor
function SupportService(router, http, toastr) {
this.router = router;
this.http = http;
this.toastr = toastr;
// global variables
this.headers = new http_1.Headers({
'Authorization': 'Bearer ' + localStorage.getItem('access_token'),
'Content-Type': 'application/json'
});
this.options = new http_1.RequestOptions({ headers: this.headers });
}
// list bcs customer
SupportService.prototype.getContuinityCustomerData = function (page) {
var customerObservableArray = new wijmo.collections.ObservableArray();
var url = "http://api.innosoft.ph/api/continuity/list/continuity/customers";
this.http.get(url, this.options).subscribe(function (response) {
var results = new wijmo.collections.ObservableArray(response.json());
if (results.length > 0) {
for (var i = 0; i <= results.length - 1; i++) {
customerObservableArray.push({
CustomerId: results[i].CustomerId,
Customer: results[i].Customer
});
}
}
document.getElementById("btn-hidden-continuity-data").click();
});
return customerObservableArray;
};
// list article by article type
SupportService.prototype.getListArticleData = function (page, articleTypeId) {
var articleObservableArray = new wijmo.collections.ObservableArray();
var url = "http://api.innosoft.ph/api/article/list/byArticleTypeId/" + articleTypeId;
this.http.get(url, this.options).subscribe(function (response) {
var results = new wijmo.collections.ObservableArray(response.json());
if (results.length > 0) {
for (var i = 0; i <= results.length - 1; i++) {
articleObservableArray.push({
Id: results[i].Id,
Article: results[i].Article
});
}
}
if (page == "supportDetail") {
if (articleTypeId == 2) {
document.getElementById("btn-hidden-product-data").click();
}
else {
if (articleTypeId == 1) {
document.getElementById("btn-hidden-encoded-by-user-data").click();
}
}
}
else {
if (articleTypeId == 2) {
document.getElementById("btn-hidden-continuity-data").click();
}
}
});
return articleObservableArray;
};
// list continuity by status
SupportService.prototype.getListContinuityData = function (page, customerId, isSelectedCustomerOnly) {
var _this = this;
var continuityObservableArray = new wijmo.collections.ObservableArray();
var url = "http://api.innosoft.ph/api/continuity/list/byCustomerId/byContinuityStatus/" + customerId;
this.http.get(url, this.options).subscribe(function (response) {
var results = new wijmo.collections.ObservableArray(response.json());
if (results.length > 0) {
for (var i = 0; i <= results.length - 1; i++) {
var myExpireDate = new Date(results[i].ExpiryDate);
var myExpireDateValue = [myExpireDate.getFullYear(), _this.pad(myExpireDate.getMonth() + 1), _this.pad(myExpireDate.getDate())].join('-');
var remarksDetail = " ";
if (results[i].Remarks != null) {
remarksDetail = " - " + results[i].Remarks;
}
continuityObservableArray.push({
Id: results[i].Id,
ContinuityNumberDetail: results[i].ContinuityNumber + " - " + results[i].Product + " (Exp: " + myExpireDateValue + ")" + remarksDetail,
ContinuityNumber: results[i].ContinuityNumber,
Customer: results[i].Customer,
ProductId: results[i].ProductId,
Product: results[i].Product,
});
}
}
if (page == "supportDetail") {
if (!isSelectedCustomerOnly) {
document.getElementById("btn-hidden-encoded-by-user-data").click();
}
}
else {
if (!isSelectedCustomerOnly) {
document.getElementById("btn-hidden-assigned-to-user-data").click();
}
else {
document.getElementById("supportContinuitySelectedValue").value = continuityObservableArray[0].Id;
document.getElementById("btn-hidden-set-continuity-selectedvalue").click();
}
}
});
return continuityObservableArray;
};
// list user
SupportService.prototype.getListUserData = function (page, userType) {
var userObservableArray = new wijmo.collections.ObservableArray();
var url = "http://api.innosoft.ph/api/user/list";
this.http.get(url, this.options).subscribe(function (response) {
var results = new wijmo.collections.ObservableArray(response.json());
if (results.length > 0) {
for (var i = 0; i <= results.length - 1; i++) {
userObservableArray.push({
Id: results[i].Id,
FullName: results[i].FullName
});
}
}
if (page == "supportDetail") {
if (userType == "encodedByUser") {
document.getElementById("btn-hidden-assigned-to-user-data").click();
}
else {
if (userType == "assignedToUser") {
document.getElementById("btn-hidden-support-data").click();
}
else {
if (userType == "activityAssignedToUser") {
document.getElementById("btn-hidden--activity-finished-load").click();
document.getElementById("btnActivitySave").innerHTML = "<i class='fa fa-save fa-fw'></i> Save";
document.getElementById("btnActivitySave").disabled = false;
document.getElementById("btnActivityClose").disabled = false;
}
}
}
}
else {
if (userType == "assignedToUser") {
document.getElementById("btn-hidden-finished-load").click();
}
}
});
return userObservableArray;
};
// pad - leading zero for date
SupportService.prototype.pad = function (n) {
return (n < 10) ? ("0" + n) : n;
};
// list support by date ranged (start date and end date)
SupportService.prototype.getListSupportData = function (supportStartDate, supportEndDate, status, supportType) {
var _this = this;
var url = "http://api.innosoft.ph/api/support/list/bySupportDateRange/" + supportStartDate.toDateString() + "/" + supportEndDate.toDateString() + "/" + status + "/" + supportType;
var supportObservableArray = new wijmo.collections.ObservableArray();
this.http.get(url, this.options).subscribe(function (response) {
var results = new wijmo.collections.ObservableArray(response.json());
if (results.length > 0) {
for (var i = 0; i <= results.length - 1; i++) {
var myDate = new Date(results[i].SupportDate);
var myDateValue = [myDate.getFullYear(), _this.pad(myDate.getMonth() + 1), _this.pad(myDate.getDate())].join('-');
supportObservableArray.push({
Id: results[i].Id,
SupportNumber: results[i].SupportNumber,
SupportDate: myDateValue,
ContinuityId: results[i].ContinuityId,
ContinuityNumber: results[i].ContinuityNumber,
IssueCategory: results[i].IssueCategory,
Issue: results[i].Issue,
CustomerId: results[i].CustomerId,
Customer: results[i].Customer,
ProductId: results[i].ProductId,
Product: results[i].Product,
SupportType: results[i].SupportType,
Severity: results[i].Severity,
Caller: results[i].Caller,
Remarks: results[i].Remarks,
ScreenShotURL: results[i].ScreenShotURL,
EncodedByUserId: results[i].EncodedByUserId,
EncodedByUser: results[i].EncodedByUser,
AssignedToUserId: results[i].AssignedToUserId,
AssignedToUser: results[i].AssignedToUser == null ? " " : results[i].AssignedToUser,
SupportStatus: results[i].SupportStatus,
});
}
}
document.getElementById("btn-hidden-complete-loading").click();
document.getElementById("btnRefresh").disabled = false;
document.getElementById("btnRefresh").innerHTML = "<i class='fa fa-refresh fa-fw'></i> Refresh";
});
return supportObservableArray;
};
// get support by id
SupportService.prototype.getSupportById = function (id) {
var _this = this;
var url = "http://api.innosoft.ph/api/support/get/byId/" + id;
this.http.get(url, this.options).subscribe(function (response) {
var results = response.json();
if (results != null) {
document.getElementById("btn-hidden-finished-load").click();
setTimeout(function () {
document.getElementById("supportNumber").value = results.SupportNumber;
document.getElementById("supportDateValue").value = results.SupportDate;
document.getElementById("supportContinuitySelectedValue").value = results.ContinuityId;
document.getElementById("supportIssueCategorySelectedValue").value = results.IssueCategory;
document.getElementById("supportIssue").value = results.Issue;
document.getElementById("supportCustomerSelectedValue").value = results.CustomerId;
document.getElementById("supportTypeSelectedValue").value = results.SupportType;
document.getElementById("supportSeveritySelectedValue").value = results.Severity;
document.getElementById("supportCaller").value = results.Caller;
document.getElementById("supportRemarks").value = results.Remarks;
document.getElementById("supportScreenShotURL").value = results.ScreenShotURL;
document.getElementById("supportEncodedBySelectedValue").value = results.EncodedByUser;
document.getElementById("supportAssignedToSelectedValue").value = results.AssignedToUserId;
document.getElementById("supportStatusSelectedValue").value = results.SupportStatus;
document.getElementById("btn-hidden-selectedValue-data").click();
document.getElementById("btn-hidden-complete-loading").click();
}, 200);
}
else {
alert("No Data");
_this.router.navigate(["/supportActivity"]);
}
});
};
// add support
SupportService.prototype.postSupportData = function (supportObject, toastr) {
var _this = this;
var url = "http://api.innosoft.ph/api/support/post";
this.http.post(url, JSON.stringify(supportObject), this.options).subscribe(function (response) {
var results = response.json();
if (results > 0) {
_this.toastr.success('', 'Save Successful');
setTimeout(function () {
document.getElementById("btn-hidden-support-detail-modal").click();
_this.router.navigate(['/supportDetail', results]);
}, 1000);
}
else {
_this.toastr.error('', 'Something`s went wrong!');
document.getElementById("btnSaveSupport").innerHTML = "<i class='fa fa-save fa-fw'></i> Save";
document.getElementById("btnSaveSupport").disabled = false;
document.getElementById("btnCloseSupport").disabled = false;
}
}, function (error) {
alert("Error");
});
};
// update support
SupportService.prototype.putSupportData = function (id, supportObject, toastr) {
var _this = this;
var url = "http://api.innosoft.ph/api/support/put/" + id;
this.http.put(url, JSON.stringify(supportObject), this.options).subscribe(function (response) {
_this.toastr.success('', 'Save Successful');
document.getElementById("btn-hidden-complete-loading").click();
document.getElementById("btnSaveSupportDetail").innerHTML = "<i class='fa fa-save fa-fw'></i> Save";
document.getElementById("btnSaveSupportDetail").disabled = false;
document.getElementById("btnCloseSupportDetail").disabled = false;
}, function (error) {
_this.toastr.error('', 'Save Unsuccessful');
// this.toastr.error(error._body.replace(/^"?(.+?)"?$/, '$1'), 'Save Failed');
document.getElementById("btnSaveSupportDetail").innerHTML = "<i class='fa fa-save fa-fw'></i> Save";
document.getElementById("btnSaveSupportDetail").disabled = false;
document.getElementById("btnCloseSupportDetail").disabled = false;
});
};
// delete support
SupportService.prototype.deleteSupportData = function (id, toastr) {
var _this = this;
var url = "http://api.innosoft.ph/api/support/delete/" + id;
this.http.delete(url, this.options).subscribe(function (response) {
_this.toastr.success('', 'Delete Successful');
document.getElementById("btn-hidden-support-delete-modal").click();
document.getElementById("btn-hidden-refresh-grid").click();
}, function (error) {
_this.toastr.error('', 'Something`s went wrong!');
document.getElementById("btnDeleteSupport").innerHTML = "<i class='fa fa-trash fa-fw'></i> Delete";
document.getElementById("btnDeleteSupport").disabled = false;
document.getElementById("btnDeleteCloseSupport").disabled = false;
});
};
// list activity by support Id
SupportService.prototype.getListActivityBySupportId = function (supportId, isLoadActivityOnly) {
var _this = this;
// let url = "http://api.innosoft.ph/api/activity/list/bySupportId/" + supportId;
var url = "http://api.innosoft.ph/api/activity/list/bySupportId/" + supportId;
var activityObservableArray = new wijmo.collections.ObservableArray();
this.http.get(url, this.options).subscribe(function (response) {
var results = new wijmo.collections.ObservableArray(response.json());
if (results.length > 0) {
for (var i = 0; i <= results.length - 1; i++) {
var myDate = new Date(results[i].ActivityDate);
var myDateValue = [myDate.getFullYear(), _this.pad(myDate.getMonth() + 1), _this.pad(myDate.getDate())].join('-');
activityObservableArray.push({
Id: results[i].Id,
ActivityNumber: results[i].ActivityNumber,
ActivityDate: myDateValue,
StaffUserId: results[i].StaffUserId,
StaffUser: results[i].StaffUser,
CustomerId: results[i].CustomerId,
Customer: results[i].Customer,
ProductId: results[i].ProductId,
Product: results[i].Product,
ParticularCategory: results[i].ParticularCategory,
Particulars: results[i].Particulars,
Location: results[i].Location,
NumberOfHours: results[i].NumberOfHours,
ActivityAmount: results[i].ActivityAmount,
ActivityStatus: results[i].ActivityStatus,
LeadId: results[i].LeadId,
QuotationId: results[i].QuotationId,
DeliveryId: results[i].DeliveryId,
SupportId: results[i].SupportId,
SoftwareDevelopmentId: results[i].SoftwareDevelopmentId
});
}
}
if (!isLoadActivityOnly) {
document.getElementById("btn-hidden-customer-data").click();
}
document.getElementById("btn-hidden-activity-staffUser").click();
});
return activityObservableArray;
};
// add activity
SupportService.prototype.postActivityData = function (activityOject, toastr) {
var _this = this;
var url = "http://api.innosoft.ph/api/activity/post";
this.http.post(url, JSON.stringify(activityOject), this.options).subscribe(function (response) {
_this.toastr.success('', 'Save Successful');
document.getElementById("btn-hidden-activity-detail-modal").click();
document.getElementById("btn-hidden-activity-data").click();
}, function (error) {
_this.toastr.error('', 'Something`s went wrong!');
document.getElementById("btnActivitySave").innerHTML = "<i class='fa fa-save fa-fw'></i> Save";
document.getElementById("btnActivitySave").disabled = false;
document.getElementById("btnActivityClose").disabled = false;
});
};
// update activity
SupportService.prototype.putActivityData = function (id, activityOject, toastr) {
var _this = this;
var url = "http://api.innosoft.ph/api/activity/put/" + id;
this.http.put(url, JSON.stringify(activityOject), this.options).subscribe(function (response) {
_this.toastr.success('', 'Save Successful');
document.getElementById("btn-hidden-activity-detail-modal").click();
document.getElementById("btn-hidden-activity-data").click();
}, function (error) {
_this.toastr.error('', 'Something`s went wrong!');
document.getElementById("btnActivitySave").innerHTML = "<i class='fa fa-save fa-fw'></i> Save";
document.getElementById("btnActivitySave").disabled = false;
document.getElementById("btnActivityClose").disabled = false;
});
};
// delete activity
SupportService.prototype.deleteActivityData = function (id, toastr) {
var _this = this;
var url = "http://api.innosoft.ph/api/activity/delete/" + id;
this.http.delete(url, this.options).subscribe(function (response) {
_this.toastr.success('', 'Delete Successful');
document.getElementById("btn-hidden-activity-delete-modal").click();
document.getElementById("btn-hidden-activity-data").click();
}, function (error) {
_this.toastr.error('', 'Something`s went wrong!');
document.getElementById("btnActivityDeleteConfirmation").innerHTML = "<i class='fa fa-save fa-fw'></i> Save";
document.getElementById("btnActivityDeleteConfirmation").disabled = false;
document.getElementById("btnActivityCloseDeleteConfirmation").disabled = false;
});
};
SupportService = __decorate([
core_1.Injectable(),
__metadata('design:paramtypes', [router_1.Router, http_1.Http, ng2_toastr_1.ToastsManager])
], SupportService);
return SupportService;
}());
exports.SupportService = SupportService;
//# sourceMappingURL=support.service.js.map |
/**
* SoftLayer Documentation Node.js Parser
*
* Copyright (c) 2013 Yani Iliev <yani@iliev.me>
* Licensed under the MIT license.
*
* @author Yani Iliev <yani@iliev.me>
* @copyright 2013 Yani Iliev
* @license
* https://github.com/yani-/blog/master/softlayer-documentation-nodejs-parser
* @version GIT: 1.0.0
* @link https://github.com/yani-/softlayer-documentation-nodejs-parser
*/
'use strict';
var http = require('http'),
Emitter = require('events').EventEmitter,
cheerio = require('cheerio'),
Service = require(__dirname + '/service'),
Method = require(__dirname + '/method'),
Parameter = require(__dirname + '/parameter'),
Header = require(__dirname + '/header');
var getContent = function (url, cb) {
http.get(url, function (res) {
var data = '';
res.setEncoding('utf8');
res.on('data', function (chunk) {
data += chunk;
});
res.on('end', function () {
cb(data);
});
}).on('error', function (e) {
throw new Error(e.message);
});
};
/**
* Application constructor
*
* @return {Object} The application object
*/
var Application = function () {
var self = this;
self.on('error', function (err) {
console.error(err);
});
};
/**
* Inherit from Emitter.prototype.
*/
Application.prototype = Emitter.prototype;
/**
* Finds all services supported by SoftLayer and assigns them to _services var
*
* @return {void}
*/
Application.prototype.retrieveServices = function () {
var self = this;
getContent(
'http://sldn.softlayer.com/reference/services/',
function (content) {
self.services = content.toString();
self.retrieveServicesMethods();
}
);
};
Application.prototype.retrieveServicesMethods = function (current) {
var self = this;
current = current || 0;
if (current !== 0) {
console.dir(self.services[current-1]);
}
if (current === self.services.length) {
// done
console.log('DONE');
self.emit('Parsing complete');
} else {
console.log('Retrieiving for ' + self.services[current].name);
self.retrieveServiceMethods(self.services[current], current + 1);
}
};
/**
* Finds all methods for a SoftLayer API service
*
* @return {void}
*/
Application.prototype.retrieveServiceMethods = function (service, next) {
var self = this;
getContent(service.href, function (content) {
service.overview = content.toString();
service.methods = content.toString();
self.retrieveMethodsProperties(0, next);
});
};
Application.prototype.retrieveMethodsProperties = function (current, next) {
var self = this;
current = current || 0;
if (current === self.services[next-1].methods.length) {
self.retrieveServicesMethods(next);
} else {
self.retrieveMethodProperties(
self.services[next-1].methods[current],
current + 1,
next
);
}
};
/**
* Finds the properties of a SoftLayer API service method
*
* @return {void}
*/
Application.prototype.retrieveMethodProperties = function (
method,
current,
next
) {
var self = this;
console.log(method);
getContent(method.href, function (content) {
method.overview = content.toString();
method.parameters = content.toString();
method.optionalHeaders = content.toString();
method.requiredHeaders = content.toString();
method.returnValue = content.toString();
self.retrieveMethodsProperties(current, next);
});
};
/**
* Define setter/getter for api services
*/
Object.defineProperty(
Application.prototype,
'services',
{
enumerable: true,
set: function (value) {
this._services = this._services || [];
var $ = cheerio.load(value),
self = this;
$('div.item-list > ul > li.views-row > div > span > a').map(
function (i, v) {
self._services.push(new Service(v));
}
);
},
get: function () {
return this._services;
}
}
);
/**
* Creates a new application object and passes variables to its constructor
*
* @return {Object} Application object
*/
var createApplication = function () {
return new Application();
};
module.exports = createApplication;
|
var uglify = require('../src/uglify');
var assert = require('chai').assert;
var compactState = "var square=x=>x*x;";
var normalState = "var square = x => x * x;";
describe('uglify module', function() {
describe('exitsed', function() {
it('should have necessary functions', function() {
assert.isOk(uglify);
assert.isFunction(uglify.compile);
});
});
});
|
"use strict";
/* tslint:disable */
var load_themed_styles_1 = require("@microsoft/load-themed-styles");
var styles = {};
load_themed_styles_1.loadStyles([{ "rawString": ".ms-FocusZoneListExample .ms-DetailsRow{display:block}" }]);
module.exports = styles;
/* tslint:enable */
//# sourceMappingURL=FocusZone.List.Example.scss.js.map
|
var path = require('path');
var express = require('express');
var config = require('./config').config;
var app = express();
var routes = require('./routes');
var userproxy = require('./proxy/userproxy');
/**
* configuration in all env
**/
app.configure(function(){
var viewsRoot = path.join(__dirname, 'views');
app.set('view engine', 'html');
app.set('views', viewsRoot);
app.engine('html', require('ejs').renderFile);
app.use(express.static(__dirname + '/public'));
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.session({
secret:'mozillapersona'
}));
app.use(function(req,res,next){
if(req.session.email){
userproxy.getUserByEmail(req.session.email,function(err,user){
if(err){
next(err);
}
res.locals.user=user;
next();
});
}else{
res.locals.user = null;
next();
}
});
});
//set routes
routes(app);
// start app
app.listen(config.port);
console.log("sinter listening on port %d in %s mode",config.port,app.settings.env);
if (process.env.NODE_ENV == 'test') {
console.log("sinter listening on port %d in %s mode",config.port,app.settings.env);
};
module.exports = app;
|
/* Problem: Given a array of numbers representing the stock prices of a company in chronological order,
write a function that calculates the maximum profit you could have made from buying and selling that stock once.
You must buy before you can sell it.
Example:
Input: [9, 11, 8, 5, 7, 10]
Output: 5
Explanation: min buy is 5 and max sell is 10 so profit is 5
Input: [7,6,4,3,1]
Output: 0
Explanation: No profit
*/
// Solution 1: Using double iteration
function maxProfit(arr) {
var maxProfit = 0;
if (arr.length === 0) {
return maxProfit;
}
var i = 0;
while (i < arr.length) {
var j = i + 1;
while (j < arr.length) {
var diff = arr[j] - arr[i];
if (diff > maxProfit) {
maxProfit = diff;
}
j++;
}
i++;
}
return maxProfit;
}
maxProfit([9, 11, 8, 5, 7, 10]); // 5
maxProfit([14, 13, 12, 11]); // 0
// Time Complexity: O(N * N - 1 / 2)
// Space Complexity: O(1)
// Solution 2: One pass
function maxProfit(arr) {
var minBuy = Infinity;
var maxProfit = 0;
var i = 0;
if (arr.length === 0) {
return profit;
}
while (i < arr.length) {
if (arr[i] < minBuy) {
minBuy = arr[i];
} else if (arr[i] - minBuy > maxProfit) {
maxProfit = arr[i] - minBuy;
}
i++;
}
return maxProfit;
}
maxProfit([9, 11, 8, 5, 7, 10]); // 5
maxProfit([14, 13, 12, 11]); // 0
// Time Complexity: O(N)
// Space Complexity: O(1)
|
import * as t from './actionTypes';
import api from 'lib/api';
import messages from 'lib/text';
import moment from 'moment';
function requestProduct() {
return {
type: t.PRODUCT_DETAIL_REQUEST
};
}
function receiveProduct(item) {
return {
type: t.PRODUCT_DETAIL_RECEIVE,
item
};
}
function receiveProductError(error) {
return {
type: t.PRODUCT_DETAIL_FAILURE,
error
};
}
function receiveImages(images) {
return {
type: t.PRODUCT_IMAGES_RECEIVE,
images
};
}
function receiveVariants(variants) {
return {
type: t.PRODUCT_VARIANTS_RECEIVE,
variants
};
}
function receiveOptions(options) {
return {
type: t.PRODUCT_OPTIONS_RECEIVE,
options
};
}
export function cancelProductEdit() {
return {
type: t.PRODUCT_DETAIL_ERASE
};
}
function requestProducts() {
return {
type: t.PRODUCTS_REQUEST
};
}
function requestMoreProducts() {
return {
type: t.PRODUCTS_MORE_REQUEST
};
}
function receiveProductsMore({ has_more, total_count, data }) {
return {
type: t.PRODUCTS_MORE_RECEIVE,
has_more,
total_count,
data
};
}
function receiveProducts({ has_more, total_count, data }) {
return {
type: t.PRODUCTS_RECEIVE,
has_more,
total_count,
data
};
}
function receiveProductsError(error) {
return {
type: t.PRODUCTS_FAILURE,
error
};
}
export function selectProduct(id) {
return {
type: t.PRODUCTS_SELECT,
productId: id
};
}
export function deselectProduct(id) {
return {
type: t.PRODUCTS_DESELECT,
productId: id
};
}
export function deselectAllProduct() {
return {
type: t.PRODUCTS_DESELECT_ALL
};
}
export function selectAllProduct() {
return {
type: t.PRODUCTS_SELECT_ALL
};
}
export function setFilter(filter) {
return {
type: t.PRODUCTS_SET_FILTER,
filter: filter
};
}
function deleteProductsSuccess() {
return {
type: t.PRODUCT_DELETE_SUCCESS
};
}
function setCategorySuccess() {
return {
type: t.PRODUCT_SET_CATEGORY_SUCCESS
};
}
function requestUpdateProduct() {
return {
type: t.PRODUCT_UPDATE_REQUEST
};
}
function receiveUpdateProduct(item) {
return {
type: t.PRODUCT_UPDATE_SUCCESS,
item
};
}
function errorUpdateProduct(error) {
return {
type: t.PRODUCT_UPDATE_FAILURE,
error
};
}
function successCreateProduct(id) {
return {
type: t.PRODUCT_CREATE_SUCCESS
};
}
function imagesUploadStart() {
return {
type: t.PRODUCT_IMAGES_UPLOAD_START
};
}
function imagesUploadEnd() {
return {
type: t.PRODUCT_IMAGES_UPLOAD_END
};
}
const getFilter = (state, offset = 0) => {
const searchTerm = state.products.filter.search;
const sortOrder = searchTerm && searchTerm.length > 0 ? 'search' : 'name';
let filter = {
limit: 50,
fields:
'id,name,category_id,category_ids,category_name,sku,images,enabled,discontinued,stock_status,stock_quantity,price,on_sale,regular_price,url',
search: searchTerm,
offset: offset,
sort: sortOrder
};
if (
state.productCategories.selectedId !== null &&
state.productCategories.selectedId !== 'all'
) {
filter.category_id = state.productCategories.selectedId;
}
if (state.products.filter.stockStatus !== null) {
filter.stock_status = state.products.filter.stockStatus;
}
if (state.products.filter.enabled !== null) {
filter.enabled = state.products.filter.enabled;
}
if (state.products.filter.discontinued !== null) {
filter.discontinued = state.products.filter.discontinued;
}
if (state.products.filter.onSale !== null) {
filter.on_sale = state.products.filter.onSale;
}
return filter;
};
export function fetchProducts() {
return (dispatch, getState) => {
const state = getState();
if (state.products.loadingItems) {
// do nothing
} else {
dispatch(requestProducts());
dispatch(deselectAllProduct());
let filter = getFilter(state);
return api.products
.list(filter)
.then(({ status, json }) => {
dispatch(receiveProducts(json));
})
.catch(error => {
dispatch(receiveProductsError(error));
});
}
};
}
export function fetchMoreProducts() {
return (dispatch, getState) => {
const state = getState();
if (!state.products.loadingItems) {
dispatch(requestMoreProducts());
const offset = state.products.items.length;
let filter = getFilter(state, offset);
return api.products
.list(filter)
.then(({ status, json }) => {
dispatch(receiveProductsMore(json));
})
.catch(error => {
dispatch(receiveProductsError(error));
});
}
};
}
export function deleteCurrentProduct() {
return (dispatch, getState) => {
const state = getState();
let product = state.products.editProduct;
if (product && product.id) {
return api.products
.delete(product.id)
.then(() => {})
.catch(err => {
console.log(err);
});
}
};
}
export function deleteProducts() {
return (dispatch, getState) => {
const state = getState();
let promises = state.products.selected.map(productId =>
api.products.delete(productId)
);
return Promise.all(promises)
.then(values => {
dispatch(deleteProductsSuccess());
dispatch(deselectAllProduct());
dispatch(fetchProducts());
})
.catch(err => {
console.log(err);
});
};
}
export function setCategory(category_id) {
return (dispatch, getState) => {
const state = getState();
let promises = state.products.selected.map(productId =>
api.products.update(productId, { category_id: category_id })
);
return Promise.all(promises)
.then(values => {
dispatch(setCategorySuccess());
dispatch(deselectAllProduct());
dispatch(fetchProducts());
})
.catch(err => {
console.log(err);
});
};
}
export function updateProduct(data) {
return (dispatch, getState) => {
dispatch(requestUpdateProduct());
return api.products
.update(data.id, data)
.then(({ status, json }) => {
const product = fixProductData(json);
dispatch(receiveUpdateProduct(product));
})
.catch(error => {
dispatch(errorUpdateProduct(error));
});
};
}
export function createProduct(history) {
return (dispatch, getState) => {
const state = getState();
const productDraft = {
enabled: false,
category_id: state.productCategories.selectedId
};
return api.products
.create(productDraft)
.then(({ status, json }) => {
dispatch(successCreateProduct(json.id));
history.push('/admin/product/' + json.id);
})
.catch(error => {});
};
}
const fixProductData = product => {
const saleFrom = moment(product.date_sale_from);
const saleTo = moment(product.date_sale_to);
const stockExpected = moment(product.date_stock_expected);
product.date_sale_from = saleFrom.isValid() ? saleFrom.toDate() : null;
product.date_sale_to = saleTo.isValid() ? saleTo.toDate() : null;
product.date_stock_expected = stockExpected.isValid()
? stockExpected.toDate()
: null;
return product;
};
export function fetchProduct(id) {
return (dispatch, getState) => {
dispatch(requestProduct());
return api.products
.retrieve(id)
.then(({ status, json }) => {
const product = fixProductData(json);
dispatch(receiveProduct(product));
})
.catch(error => {
dispatch(receiveProductError(error));
});
};
}
export function fetchImages(productId) {
return (dispatch, getState) => {
return api.products.images
.list(productId)
.then(({ status, json }) => {
dispatch(receiveImages(json));
})
.catch(error => {});
};
}
export function fetchOptions(productId) {
return (dispatch, getState) => {
return api.products.options
.list(productId)
.then(({ status, json }) => {
dispatch(receiveOptions(json));
})
.catch(error => {});
};
}
export function fetchVariants(productId) {
return (dispatch, getState) => {
return api.products.variants
.list(productId)
.then(({ status, json }) => {
dispatch(receiveVariants(json));
})
.catch(error => {});
};
}
export function createVariant(productId) {
return (dispatch, getState) => {
const state = getState();
const {
regular_price,
stock_quantity,
weight
} = state.products.editProduct;
const variant = {
price: regular_price,
stock_quantity: stock_quantity,
weight: weight
};
return api.products.variants
.create(productId, variant)
.then(({ status, json }) => {
dispatch(receiveVariants(json));
})
.catch(error => {});
};
}
export function updateVariant(productId, variantId, variant) {
return (dispatch, getState) => {
return api.products.variants
.update(productId, variantId, variant)
.then(({ status, json }) => {
dispatch(receiveVariants(json));
})
.catch(error => {});
};
}
export function setVariantOption(productId, variantId, optionId, valueId) {
return (dispatch, getState) => {
const option = { option_id: optionId, value_id: valueId };
return api.products.variants
.setOption(productId, variantId, option)
.then(({ status, json }) => {
dispatch(receiveVariants(json));
})
.catch(error => {});
};
}
export function createOptionValue(productId, optionId, valueName) {
return (dispatch, getState) => {
return api.products.options.values
.create(productId, optionId, { name: valueName })
.then(({ status, json }) => {
dispatch(fetchOptions(productId));
})
.catch(error => {});
};
}
export function createOption(productId, option) {
return (dispatch, getState) => {
return api.products.options
.create(productId, option)
.then(({ status, json }) => {
dispatch(receiveOptions(json));
})
.catch(error => {});
};
}
export function updateOptionValue(productId, optionId, valueId, valueName) {
return (dispatch, getState) => {
return api.products.options.values
.update(productId, optionId, valueId, { name: valueName })
.then(({ status, json }) => {
dispatch(fetchOptions(productId));
})
.catch(error => {});
};
}
export function updateOption(productId, optionId, option) {
return (dispatch, getState) => {
return api.products.options
.update(productId, optionId, option)
.then(({ status, json }) => {
dispatch(receiveOptions(json));
})
.catch(error => {});
};
}
export function deleteOptionValue(productId, optionId, valueId) {
return (dispatch, getState) => {
return api.products.options.values
.delete(productId, optionId, valueId)
.then(({ status, json }) => {
dispatch(fetchOptions(productId));
})
.catch(error => {});
};
}
export function deleteOption(productId, optionId) {
return (dispatch, getState) => {
return api.products.options
.delete(productId, optionId)
.then(({ status, json }) => {
dispatch(receiveOptions(json));
})
.catch(error => {});
};
}
export function deleteVariant(productId, variantId) {
return (dispatch, getState) => {
return api.products.variants
.delete(productId, variantId)
.then(({ status, json }) => {
dispatch(receiveVariants(json));
})
.catch(error => {});
};
}
export function deleteImage(productId, imageId) {
return (dispatch, getState) => {
return api.products.images
.delete(productId, imageId)
.then(({ status, json }) => {
dispatch(fetchImages(productId));
})
.catch(error => {});
};
}
export function updateImage(productId, image) {
return (dispatch, getState) => {
return api.products.images
.update(productId, image.id, image)
.then(() => {
dispatch(fetchImages(productId));
})
.catch(error => {});
};
}
export function updateImages(productId, images) {
return (dispatch, getState) => {
let promises = images.map(image =>
api.products.images.update(productId, image.id, image)
);
return Promise.all(promises)
.then(() => {
dispatch(fetchImages(productId));
})
.catch(error => {});
};
}
export function uploadImages(productId, form) {
return (dispatch, getState) => {
dispatch(imagesUploadStart());
return api.products.images
.upload(productId, form)
.then(() => {
dispatch(imagesUploadEnd());
dispatch(fetchImages(productId));
})
.catch(error => {
dispatch(imagesUploadEnd());
});
};
}
|
import _makeArrayFlattener from "../privates/_makeArrayFlattener";
/**
* Flattens the "first level" of an array.
* @example <caption>Showing the difference with <code>flatten</code>:</caption>
* const arr = [1, 2, [3, 4, [5, 6]], 7, 8];
*
* _.flatten(arr) // => [1, 2, 3, 4, 5, 6, 7, 8]
* _.shallowFlatten(arr) // => [1, 2, 3, 4, [5, 6], 7, 8]
*
* @memberof module:lamb
* @category Array
* @function
* @see {@link module:lamb.flatten|flatten}
* @since 0.9.0
* @param {Array} array
* @returns {Array}
*/
var shallowFlatten = _makeArrayFlattener(false);
export default shallowFlatten;
|
import { pluralizeWord } from 'xitomatl/helpers/pluralize-word';
import { module, test } from 'qunit';
module('Unit | Helper | pluralize word');
// Replace this with your real tests.
test('it works', function(assert) {
let result = pluralizeWord([42]);
assert.ok(result);
});
|
import React from 'react';
import Header from 'components/Header.js';
import './SetNickname.less';
export default class SetGender extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<Header headerName="设置性别" />
</div>
)
}
} |
/* @flow */
import Type from './Type';
import type Validation, {IdentifierPath} from '../Validation';
export default class MixedType extends Type {
typeName: string = 'MixedType';
collectErrors (validation: Validation<any>, path: IdentifierPath, input: any): boolean {
return false;
}
accepts (input: any): boolean {
return true;
}
toString (): string {
return 'mixed';
}
toJSON () {
return {
typeName: this.typeName
};
}
} |
var _ = require('underscore');
var Promise = require('../promise');
// interface Storage {
// readonly attribute boolean async;
// string getItem(string key);
// void setItem(string key, string value);
// void removeItem(string key);
// void clear();
// Promise getItemAsync(string key);
// Promise setItemAsync(string key, string value);
// Promise removeItemAsync(string key);
// Promise clearAsync();
// }
var Storage = {};
var apiNames = ['getItem', 'setItem', 'removeItem', 'clear'];
var localStorage = global.localStorage;
try {
var testKey = '__storejs__';
localStorage.setItem(testKey, testKey);
if (localStorage.getItem(testKey) != testKey) {
throw new Error();
}
localStorage.removeItem(testKey);
} catch (e) {
localStorage = require('localstorage-memory');
}
// in browser, `localStorage.async = false` will excute `localStorage.setItem('async', false)`
_(apiNames).each(function(apiName) {
Storage[apiName] = function() {
return localStorage[apiName].apply(localStorage, arguments);
};
});
Storage.async = false;
module.exports = Storage;
|
var Slideout = require('slideout');
if(window.location.host == "tipbox.in" && !window.location.hash) {
window.location.href = "https://tipbox.is";
}
window.setCurrentView = function(hash) {
var unsupportedBrowser = function() {
return !(window && window.crypto && window.crypto.getRandomValues && window.Uint8Array);
}
var previousView = window.currentView || "homeView";
var currentView;
if(hash.match(/^#create/)) {
currentView = 'createView';
} else if(hash.match(/^#compose/)) {
currentView = 'composeView';
if(window.ComposeViewController) window.ComposeViewController.init();
} else {
currentView = 'homeView';
}
if(currentView != "homeView" && unsupportedBrowser()) {
currentView = 'unsupportedBrowser'
}
document.querySelector('#'+previousView).classList.add('hidden');
document.querySelector('#'+currentView).classList.remove('hidden');
var activeModal = document.querySelector('.modal.active');
if(activeModal) toggleModal("#"+activeModal.id);
window.currentView = currentView;
return currentView;
}
window.setCurrentView(window.location.hash);
// In case the hash changes before page.js is loaded
// (once page.js is loaded, window.hashchange will be overridden)
window.onhashchange = function() {
window.setCurrentView(window.location.hash);
};
var openModalEls = document.querySelectorAll('.openModal');
for(var i=0;i<openModalEls.length; i++) {
var el = openModalEls[i];
el.addEventListener("click", function(e) {
e.preventDefault();
toggleModal('#'+this.dataset.modal);
return false;
});
}
var toggleModal = function(modalID) {
var modal = document.querySelector(modalID);
// Discarding currently active modal
if (modal.classList.contains('active')) {
modal.style.zIndex = 0;
return modal.classList.toggle('active');
}
var currentlyActive = document.querySelectorAll(".modal.active");
var zIndex = 15;
if(currentlyActive.length > 0)
zIndex = ( currentlyActive.length + 1 ) * 10;
modal.style.zIndex = zIndex;
modal.classList.toggle('active');
}
window.slideout = new Slideout({
'panel': document.getElementById('content'),
'menu': document.getElementById('menu'),
'side': 'right'
});
document.getElementById('open-menu').addEventListener('click', function() {
slideout.toggle();
});
|
var FileSystem = require('fs');
var WalkSync = require('walk-sync');
var path = require('path');
var glob = require('glob-fs')({ gitignore: true });
/**.
* A very simple template assembler for angular 1.
*
* @author Mwayi Dzanjalimodzi
*
* var ngTemplate = new NgTemplate(['.src/*.html']);
* ngTemplate.writeToFile(destination);
*
* @var {Array} src of files to read from.
* @var {Array} destination to write to.
*/
var NgTemplate = function(source, moduleName) {
this.addSources(source);
this.loadFiles(source);
this.buildTemplates(this.files);
this.moduleName = moduleName || 'app';
};
/**
* @var {Array} sources to look for files.
*/
NgTemplate.prototype.sources = [];
/**
* @var {Array} file bus.
*/
NgTemplate.prototype.files = {};
/**
* @var {Array} sources to look for files.
*/
NgTemplate.prototype.templates = [];
/**
* Load files from directories
*
* @param {String|Array} source(s) to read from.
* @return void
*/
NgTemplate.prototype.addSources = function(source) {
if(typeof source == 'string') {
this.sources.push(source);
}
if(Array.isArray(source)) {
this.sources = this.sources.concat(source);
}
}
/**
* Load files from directories.
*s
* @param {String|Array} source(s) to read from.
* @return void
*/
NgTemplate.prototype.loadFiles = function() {
for(var i in this.sources) {
var files = glob.readdirSync(this.sources[i]);
for(var j in files) {
this.files[files[j]] = 1;
}
}
}
/**
* Build Ng Templates from files.
*
* @param {Array} array of files to render as templates.
* @return {String} of templates.
*/
NgTemplate.prototype.buildTemplates = function(files) {
for(var file in files) {
var template = this.getSyntax(
path.parse(file).name,
this.getContents(file)
);
this.templates.push(template);
}
};
/**
* Get file contents as json.
*
* @param {fileName} The file path
* @return {String} The file contents.
*/
NgTemplate.prototype.getContents = function(filePath) {
var fileBuffer = FileSystem.readFileSync(filePath);
return fileBuffer.toString();
};
/**
* Get the template syntax.
*
* @param {String} The name of the cached template.
* @param {String} The content string which is JSON stringified.
* @return {String}
*/
NgTemplate.prototype.getSyntax = function(name, content) {
return "\n $templateCache.put('" + name + "'," + JSON.stringify(content) + ");";
};
/**
* Get module syntax.
*
* @param {String} The name of the module.
* @param {String} The content of the module.
* @return {String}
*/
NgTemplate.prototype.getModuleSyntax = function(moduleName, content) {
return "angular.module('"
+ moduleName
+ "').run(['$templateCache', function($templateCache) {"
+ content + "\n}]);";
};
/**
* Write to file.
*
* @param {String} The destination of the file to write to.
* @return void
*/
NgTemplate.prototype.writeToFile = function(destination) {
FileSystem.writeFileSync(
destination,
this.getModuleSyntax(
this.moduleName,
this.templates.join("\n")
)
);
};
module.exports = function(source, moduleName) {
return new NgTemplate(source, moduleName);
}
|
import React, { Component } from 'react'
import { bindActionCreators } from 'redux'
import TagSearchScreen from '../../components/TagSearch/TagSearch.screen'
import * as articlesActions from '../../redux/modules/Articles.redux'
import { connect } from 'react-redux'
type Props = {
articles: Array<any>,
navigation: Object,
actions: Object,
}
class TagSearchContainer extends Component {
props: Props
static navigationOptions = {
title: 'タグで検索',
}
render() {
const { articles, navigation, actions } = this.props
return (
<TagSearchScreen
navigation={navigation}
tagList={articles.tagList}
isFetching={articles.isFetching}
fetchSucceeded={articles.fetchSucceeded}
{...actions} />
)
}
}
export default connect(
state => ({
articles: state.articles,
}),
dispatch => ({
actions: {
articlesActions: bindActionCreators(articlesActions, dispatch),
},
})
)(TagSearchContainer)
|
/**f
* touch thumbs control class
* addon to strip gallery
*/
function UGTouchSliderControl(){
var g_objSlider, g_objInner, g_parent = new UGSlider();
var g_objParent, g_options, t=this;
var g_functions = new UGFunctions();
this.events = {
CLICK:"click"
};
var g_options = {
slider_transition_continuedrag_speed: 250, //the duration of continue dragging after drag end
slider_transition_continuedrag_easing: "linear", //easing function of continue dragging animation
slider_transition_return_speed: 300, //the duration of the "return to place" animation
slider_transition_return_easing: "easeInOutQuad" //easing function of the "return to place" animation
};
var g_temp = {
touch_active: false,
startMouseX: 0,
startMouseY: 0,
lastMouseX: 0,
lastMouseY: 0,
startPosx:0,
startTime:0,
isInitDataValid:false,
slides: null,
lastNumTouches:0,
isDragging: false,
storedEventID: "touchSlider",
videoStartX: 0,
isDragVideo: false,
videoObject: null
};
/**
* get diff inner object position from current item pos
*/
function getDiffPosFromCurrentItem(slides){
if(!slides)
var slides = g_parent.getSlidesReference();
var posCurrent = g_functions.getElementSize(slides.objCurrentSlide);
var inPlaceX = -posCurrent.left;
var objInnerSize = g_functions.getElementSize(g_objInner);
var diffPos = inPlaceX - objInnerSize.left;
return(diffPos);
}
/**
* check if the movement that was held is valid for slide change
*/
function isMovementValidForChange(){
var slides = g_parent.getSlidesReference();
//check position, if more then half, move
var diffPos = getDiffPosFromCurrentItem(slides);
var breakSize = Math.round(slides.objCurrentSlide.width() * 3 / 8);
if(Math.abs(diffPos) >= breakSize)
return(true);
//check gesture, if vertical mostly then not move
var diffX = Math.abs(g_temp.lastMouseX - g_temp.startMouseX);
var diffY = Math.abs(g_temp.lastMouseY - g_temp.startMouseY);
//debugLine("diffx: " + diffX, true, true);
if(diffX < 20)
return(false);
//if(diffY >= diffX)
//return(false);
//check time. Short time always move
var endTime = jQuery.now();
var diffTime = endTime - g_temp.startTime;
//debugLine("time: " + diffTime, true);
if(diffTime < 500)
return(true);
return(false);
}
/**
* check tab event occured
* invokes on touchend event on the slider object
*/
this.isTapEventOccured = function(event){
//validate one touch
var arrTouches = g_functions.getArrTouches(event);
var numTouches = arrTouches.length;
if(numTouches != 0 || g_temp.lastNumTouches != 0){
g_temp.lastNumTouches = numTouches;
return(false);
}
g_temp.lastNumTouches = numTouches;
var slides = g_parent.getSlidesReference();
//check position, if more then half, move
var diffPos = getDiffPosFromCurrentItem(slides);
//check gesture, if vertical mostly then not move
var diffX = Math.abs(g_temp.lastMouseX - g_temp.startMouseX);
var diffY = Math.abs(g_temp.lastMouseY - g_temp.startMouseY);
//check by time
var endTime = jQuery.now();
var diffTime = endTime - g_temp.startTime;
//combine move and time
if(diffX < 20 && diffY < 50 && diffTime < 500)
return(true);
return(false);
}
/**
* return the item to place
*/
function returnToPlace(slides){
if(g_parent.isInnerInPlace() == true)
return(false);
//trigger before return event
g_objParent.trigger(g_parent.events.BEFORE_RETURN);
if(!slides)
var slides = g_parent.getSlidesReference();
var posCurrent = g_functions.getElementSize(slides.objCurrentSlide);
var destX = -posCurrent.left;
//animate objects
g_objInner.animate({left:destX+"px"},{
duration: g_options.slider_transition_return_speed,
easing: g_options.slider_transition_continuedrag_easing,
queue: false,
progress: function(animation, number, remainingMS){
//check drag video
if(g_temp.isDragVideo == true){
var objSize = g_functions.getElementSize(g_objInner);
var innerX = objSize.left;
var posDiff = innerX - destX;
var videoPosX = g_temp.videoStartX + posDiff;
g_temp.videoObject.css("left", videoPosX);
}
},
complete: function(){
g_objParent.trigger(g_parent.events.AFTER_RETURN);
}
});
}
/**
*
* change the item to given direction
*/
function changeItem(direction){
g_parent.getVideoObject().hide();
g_parent.switchSlideNums(direction);
g_parent.placeNabourItems();
}
/**
* continue the dragging by changing the slides to the right place.
*/
function continueSlideDragChange(){
//get data
var slides = g_parent.getSlidesReference();
var diffPos = getDiffPosFromCurrentItem(slides);
if(diffPos == 0)
return(false);
var direction = (diffPos > 0) ? "left" : "right";
var isReturn = false;
switch(direction){
case "right": //change to prev item
if( g_parent.isSlideHasItem(slides.objPrevSlide) ){
var posPrev = g_functions.getElementSize(slides.objPrevSlide);
var destX = -posPrev.left;
}else //return current item
isReturn = true;
break;
case "left": //change to next item
if( g_parent.isSlideHasItem(slides.objNextSlide) ){
var posNext = g_functions.getElementSize(slides.objNextSlide);
var destX = -posNext.left;
}else
isReturn = true;
break;
}
if(isReturn == true){
returnToPlace(slides);
}else{
//animate objects
g_objInner.stop().animate({left:destX+"px"},{
duration: g_options.slider_transition_continuedrag_speed,
easing: g_options.slider_transition_continuedrag_easing,
queue: false,
progress: function(){
//check drag video
if(g_temp.isDragVideo == true){
var objSize = g_functions.getElementSize(g_objInner);
var innerX = objSize.left;
var posDiff = innerX - g_temp.startPosx;
var videoPosX = g_temp.videoStartX + posDiff;
g_temp.videoObject.css("left", videoPosX);
}
},
always:function(){
changeItem(direction);
g_objParent.trigger(g_parent.events.AFTER_DRAG_CHANGE);
}
});
}
}
/**
* handle slider drag on mouse drag
*/
function handleSliderDrag(event){
var diff = g_temp.lastMouseX - g_temp.startMouseX;
if(diff == 0)
return(true);
var direction = (diff < 0) ? "left":"right";
var objZoomSlider = g_parent.getObjZoom();
//don't drag if the zoom panning enabled
//store init position after image zoom pan end
if(objZoomSlider){
var isPanEnabled = objZoomSlider.isPanEnabled(event,direction);
if(isPanEnabled == true){
g_temp.isInitDataValid = false;
return(true);
}else{
if(g_temp.isInitDataValid == false){
storeInitTouchData(event);
return(true);
}
}
}
//set inner div position
var currentPosx = g_temp.startPosx + diff;
//check out of borders and slow down the motion:
if(diff > 0 && currentPosx > 0)
currentPosx = currentPosx / 3;
else if(diff < 0 ){
var innerEnd = currentPosx + g_objInner.width();
var sliderWidth = g_objSlider.width();
if( innerEnd < sliderWidth ){
currentPosx = g_temp.startPosx + diff/3;
}
}
if(g_temp.isDragging == false){
g_temp.isDragging = true;
g_objParent.trigger(g_parent.events.START_DRAG);
}
g_objInner.css("left", currentPosx+"px");
//drag video
if(g_temp.isDragVideo == true){
var posDiff = currentPosx - g_temp.startPosx;
var videoPosX = g_temp.videoStartX + posDiff;
g_temp.videoObject.css("left", videoPosX);
}
}
/**
* store init touch position
*/
function storeInitTouchData(event){
var mousePos = g_functions.getMousePosition(event);
g_temp.startMouseX = mousePos.pageX;
//debugLine("startx:" + g_temp.startMouseX, true, true);
g_temp.startMouseY = mousePos.pageY;
g_temp.lastMouseX = g_temp.startMouseX;
g_temp.lastMouseY = g_temp.startMouseY;
g_temp.startTime = jQuery.now();
var arrTouches = g_functions.getArrTouches(event);
g_temp.startArrTouches = g_functions.getArrTouchPositions(arrTouches);
var objPos = g_functions.getElementSize(g_objInner);
g_temp.startPosx = objPos.left;
g_temp.isInitDataValid = true;
//check if video object need to be dragged
g_temp.isDragVideo = false;
var objVideo = g_parent.getVideoObject();
if(objVideo.isVisible() == true){
g_temp.isDragVideo = true;
g_temp.videoObject = objVideo.getObject();
var videoSize = g_functions.getElementSize(g_temp.videoObject);
g_temp.videoStartX = videoSize.left;
}
g_functions.storeEventData(event, g_temp.storedEventID);
}
/**
* disable touch active
*/
function disableTouchActive(who){
g_temp.touch_active = false;
//debugLine("disable: " + who, true, true);
}
/**
* enable the touch active
*/
function enableTouchActive(who, event){
g_temp.touch_active = true;
storeInitTouchData(event);
//debugLine("enable: " + who, true, true);
}
/**
* on touch slide start
*
*/
function onTouchStart(event){
event.preventDefault();
g_temp.isDragging = false;
//debugLine("touchstart", true, true);
//check if the slides are changing from another event.
if(g_parent.isAnimating() == true){
g_objInner.stop(true, true);
}
//check num touches
var arrTouches = g_functions.getArrTouches(event);
if(arrTouches.length > 1){
if(g_temp.touch_active == true){
disableTouchActive("1");
}
return(true);
}
if(g_temp.touch_active == true){
return(true);
}
enableTouchActive("1", event);
}
/**
*
* on touch move event
*/
function onTouchMove(event){
if(g_temp.touch_active == false)
return(true);
//detect moving without button press
if(event.buttons == 0){
disableTouchActive("2");
continueSlideDragChange();
return(true);
}
g_functions.updateStoredEventData(event, g_temp.storedEventID);
event.preventDefault();
var mousePos = g_functions.getMousePosition(event);
g_temp.lastMouseX = mousePos.pageX;
g_temp.lastMouseY = mousePos.pageY;
//debugLine("lastX:" + g_temp.lastMouseX, true, true);
var scrollDir = null;
if(g_options.slider_vertical_scroll_ondrag == true)
scrollDir = g_functions.handleScrollTop(g_temp.storedEventID);
if(scrollDir !== "vert")
handleSliderDrag(event);
}
/**
* on touch end event
*/
function onTouchEnd(event){
//debugLine("touchend", true, true);
var arrTouches = g_functions.getArrTouches(event);
var numTouches = arrTouches.length;
var isParentInPlace = g_parent.isInnerInPlace();
if(isParentInPlace == true && g_temp.touch_active == false && numTouches == 0){
return(true);
}
if(numTouches == 0 && g_temp.touch_active == true){
//trigger click event
if(isParentInPlace == true)
jQuery(t).trigger(t.events.CLICK);
disableTouchActive("3");
var isValid = false;
var wasVerticalScroll = g_functions.wasVerticalScroll(g_temp.storedEventID);
if(wasVerticalScroll == false)
isValid = isMovementValidForChange();
if(isValid == true)
continueSlideDragChange(); //change the slide
else
returnToPlace(); //return the inner object to place (if not in place)
}else{
if(numTouches == 1 && g_temp.touch_active == false){
enableTouchActive("2",event);
}
}
}
/**
* init touch events
*/
function initEvents(){
//slider mouse down - drag start
g_objSlider.bind("mousedown touchstart",onTouchStart);
//on body move
jQuery("body").bind("mousemove touchmove",onTouchMove);
//on body mouse up - drag end
jQuery(window).add("body").bind("mouseup touchend", onTouchEnd);
}
/**
* init function for avia controls
*/
this.init = function(objSlider, customOptions){
g_parent = objSlider;
g_objParent = jQuery(g_parent);
g_objects = objSlider.getObjects();
g_objSlider = g_objects.g_objSlider;
g_objInner = g_objects.g_objInner;
g_options = jQuery.extend(g_options, customOptions);
initEvents();
}
/**
* get last mouse position
*/
this.getLastMousePos = function(){
var obj = {
pageX: g_temp.lastMouseX,
pageY: g_temp.lastMouseY
};
return(obj);
}
/**
* is touch active
*/
this.isTouchActive = function(){
return(g_temp.touch_active);
}
} |
const baseConfig = require('./webpack.config')
module.exports = Object.assign({}, baseConfig, {
entry: {
demo: ['./entries/demo/index.js']
},
output: {
path: `${__dirname}/docs/demo`,
filename: '[name].[chunkhash].js'
}
})
|
exports.make = function (Schema, mongoose) {
Story = new Schema({
summary: String,
estimate: String,
active: Boolean,
revealed: Boolean,
deskId: String
});
return mongoose.model('Story', Story);
}; |
/*
* cw_gallery
* http://clivewalkden.co.uk/code/cw_gallery/
*
* Copyright (c) 2014 Clive Walkden
* Licensed under the MIT license.
*/
(function($){
$.fn.cwGallery = function(custom) {
// Default plugin settings
var defaults = {
thumb_container : 'cw_thumbs',
img_container : 'cw_image',
active_class : 'cw_active',
animate_height : false
};
// Merge default and user settings
var settings = $.extend({}, defaults, custom);
$('.'+settings.thumb_container+' a').on({
click : function(e) {
e.preventDefault();
$('.'+settings.thumb_container+' a').removeClass(settings.active_class);
$(this).addClass(settings.active_class);
var main_img = $('.'+settings.img_container).children('img');
var origWidth = main_img.width();
var origHeight = main_img.height();
var self = this;
var largeimg = $(self).attr('href');
$('.'+settings.img_container).children('img').fadeTo(300,0.01,function(){
// Create temp image for the SOLE purpose of grabbing the image size
var img = $('<img/>')
.attr('src',largeimg)
.load(function(){
var imgHeight = this.height;
//var imgWidth = this.width;
// Check if the origHeight is different
if(imgHeight !== origHeight && settings.animate_height === true){
// Resize
$('.'+settings.img_container).children('img').animate({
'height':imgHeight,
'width' :origWidth
},700,function(){
// Fade in new image
$('.'+settings.img_container).children('img').attr({src: largeimg});
$('.'+settings.img_container).children('img').fadeTo(300,1);
});
}else{
// Fade in new image
$('.'+settings.img_container).children('img').attr({src: largeimg});
$('.'+settings.img_container).children('img').fadeTo(300,1);
}
origHeight = undefined;
});
});
}
});
};
})(jQuery);
|
var sunTexture;
var sunColorLookupTexture;
var solarflareTexture;
var sunHaloTexture;
var sunHaloColorTexture;
var sunCoronaTexture;
function loadStarSurfaceTextures(){
if( sunTexture === undefined ){
sunTexture = THREE.ImageUtils.loadTexture( "/images/sun_surface.png");
sunTexture.anisotropy = maxAniso;
sunTexture.wrapS = sunTexture.wrapT = THREE.RepeatWrapping;
}
if( sunColorLookupTexture === undefined ){
sunColorLookupTexture = THREE.ImageUtils.loadTexture( "/images/star_colorshift.png" );
}
if( solarflareTexture === undefined ){
solarflareTexture = THREE.ImageUtils.loadTexture( "/images/solarflare.png" );
}
if( sunHaloTexture === undefined ){
sunHaloTexture = THREE.ImageUtils.loadTexture( "/images/sun_halo.png" );
}
if( sunHaloColorTexture === undefined ){
sunHaloColorTexture = THREE.ImageUtils.loadTexture( "/images/halo_colorshift.png" );
}
if( sunCoronaTexture === undefined ){
sunCoronaTexture = THREE.ImageUtils.loadTexture( "/images/corona.png" );
}
}
var surfaceGeo = new THREE.SphereGeometry( 7.35144e-8, 60, 30);
function makeStarSurface( radius, uniforms ){
var sunShaderMaterial = new THREE.ShaderMaterial( {
uniforms: uniforms,
vertexShader: shaderList.starsurface.vertex,
fragmentShader: shaderList.starsurface.fragment,
});
var sunSphere = new THREE.Mesh( surfaceGeo, sunShaderMaterial);
return sunSphere;
}
var haloGeo = new THREE.PlaneGeometry( .00000022, .00000022 );
function makeStarHalo(uniforms){
var sunHaloMaterial = new THREE.ShaderMaterial(
{
uniforms: uniforms,
vertexShader: shaderList.starhalo.vertex,
fragmentShader: shaderList.starhalo.fragment,
blending: THREE.AdditiveBlending,
depthTest: false,
depthWrite: false,
color: 0xffffff,
transparent: true,
// settings that prevent z fighting
polygonOffset: true,
polygonOffsetFactor: 1,
polygonOffsetUnits: 100,
}
);
var sunHalo = new THREE.Mesh( haloGeo, sunHaloMaterial );
sunHalo.position.set( 0, 0, 0 );
return sunHalo;
}
var glowGeo = new THREE.PlaneGeometry( .0000012, .0000012 );
function makeStarGlow(uniforms){
// the bright glow surrounding everything
var sunGlowMaterial = new THREE.ShaderMaterial(
{
//map: sunCoronaTexture,
uniforms: uniforms,
blending: THREE.AdditiveBlending,
fragmentShader: shaderList.corona.fragment,
vertexShader: shaderList.corona.vertex,
color: 0xffffff,
transparent: true,
// settings that prevent z fighting
polygonOffset: true,
polygonOffsetFactor: -1,
polygonOffsetUnits: 100,
depthTest: true,
depthWrite: true,
}
);
var sunGlow = new THREE.Mesh( glowGeo, sunGlowMaterial );
sunGlow.position.set( 0, 0, 0 );
return sunGlow;
}
function makeStarLensflare(size, zextra, hueShift){
var sunLensFlare = addStarLensFlare( 0,0,zextra, size, undefined, hueShift);
sunLensFlare.customUpdateCallback = function(object){
if( object.visible == false )
return;
var f, fl = this.lensFlares.length;
var flare;
var vecX = -this.positionScreen.x * 2;
var vecY = -this.positionScreen.y * 2;
var size = object.size ? object.size : 16000;
var camDistance = camera.position.length();
for( f = 0; f < fl; f ++ ) {
flare = this.lensFlares[ f ];
flare.x = this.positionScreen.x + vecX * flare.distance;
flare.y = this.positionScreen.y + vecY * flare.distance;
flare.scale = size / Math.pow(camDistance,2.0) * 2.0;
if( camDistance < 10.0 ){
flare.opacity = Math.pow(camDistance * 2.0,2.0);
}
else{
flare.opacity = 1.0;
}
flare.rotation = 0;
//flare.rotation = this.positionScreen.x * 0.5;
//flare.rotation = 0;
}
for( f=2; f<fl; f++ ){
flare = this.lensFlares[ f ];
var dist = Math.sqrt( Math.pow(flare.x,2) + Math.pow(flare.y,2) );
flare.opacity = constrain( dist, 0.0, 1.0 );
flare.wantedRotation = flare.x * Math.PI * 0.25;
flare.rotation += ( flare.wantedRotation - flare.rotation ) * 0.25;
}
// console.log(camDistance);
};
return sunLensFlare;
}
var solarflareGeometry = new THREE.TorusGeometry( 0.00000003, 0.000000001 + 0.000000002, 60, 90, 0.15 + Math.PI );
function makeSolarflare( uniforms ){
var solarflareMaterial = new THREE.ShaderMaterial(
{
uniforms: uniforms,
vertexShader: shaderList.starflare.vertex,
fragmentShader: shaderList.starflare.fragment,
blending: THREE.AdditiveBlending,
color: 0xffffff,
transparent: true,
depthTest: true,
depthWrite: false,
polygonOffset: true,
polygonOffsetFactor: -100,
polygonOffsetUnits: 1000,
}
);
var solarflareMesh = new THREE.Object3D();
for( var i=0; i< 6; i++ ){
var solarflare = new THREE.Mesh(solarflareGeometry, solarflareMaterial );
solarflare.rotation.y = Math.PI/2;
solarflare.speed = Math.random() * 0.01 + 0.005;
solarflare.rotation.z = Math.PI * Math.random() * 2;
solarflare.rotation.x = -Math.PI + Math.PI * 2;
solarflare.update = function(){
this.rotation.z += this.speed;
}
var solarflareContainer = new THREE.Object3D();
solarflareContainer.position.x = -1 + Math.random() * 2;
solarflareContainer.position.y = -1 + Math.random() * 2;
solarflareContainer.position.z = -1 + Math.random() * 2;
solarflareContainer.position.multiplyScalar( 7.35144e-8 * 0.8 );
solarflareContainer.lookAt( new THREE.Vector3(0,0,0) );
solarflareContainer.add( solarflare );
solarflareMesh.add( solarflareContainer );
}
return solarflareMesh;
}
function makeSun( options ){
var radius = options.radius;
var spectral = options.spectral;
// console.time("load sun textures");
loadStarSurfaceTextures();
// console.timeEnd("load sun textures");
var sunUniforms = {
texturePrimary: { type: "t", value: sunTexture },
textureColor: { type: "t", value: sunColorLookupTexture },
textureSpectral: { type: "t", value: starColorGraph },
time: { type: "f", value: 0 },
spectralLookup: { type: "f", value: 0 },
};
var solarflareUniforms = {
texturePrimary: { type: "t", value: solarflareTexture },
time: { type: "f", value: 0 },
textureSpectral: { type: "t", value: starColorGraph },
spectralLookup: { type: "f", value: 0 },
};
var haloUniforms = {
texturePrimary: { type: "t", value: sunHaloTexture },
textureColor: { type: "t", value: sunHaloColorTexture },
time: { type: "f", value: 0 },
textureSpectral: { type: "t", value: starColorGraph },
spectralLookup: { type: "f", value: 0 },
};
var coronaUniforms = {
texturePrimary: { type: "t", value: sunCoronaTexture },
textureSpectral: { type: "t", value: starColorGraph },
spectralLookup: { type: "f", value: 0 },
};
// container
var sun = new THREE.Object3D();
// the actual glowy ball of fire
// console.time("make sun surface");
var starSurface = makeStarSurface( radius, sunUniforms );
sun.add( starSurface );
// console.timeEnd("make sun surface");
// console.time("make sun solarflare");
var solarflare = makeSolarflare( solarflareUniforms );
sun.solarflare = solarflare;
sun.add( solarflare );
// console.timeEnd("make sun solarflare");
// 2D overlay elements
var gyro = new THREE.Gyroscope();
sun.add( gyro );
sun.gyro = gyro;
// console.time("make sun lensflare");
var starLensflare = makeStarLensflare(1.5, 0.0001, spectral);
sun.lensflare = starLensflare;
sun.lensflare.name == 'lensflare';
gyro.add( starLensflare );
// console.timeEnd("make sun lensflare");
// the corona that lines the edge of the sun sphere
// console.time("make sun halo");
var starHalo = makeStarHalo( haloUniforms );
gyro.add( starHalo );
// console.timeEnd("make sun halo");
// console.time("make sun glow");
var starGlow = makeStarGlow( coronaUniforms );
gyro.add( starGlow );
// console.timeEnd("make sun glow");
var latticeMaterial = new THREE.MeshBasicMaterial({
map: glowSpanTexture,
blending: THREE.AdditiveBlending,
transparent: true,
depthTest: true,
depthWrite: true,
wireframe: true,
opacity: 0.8,
});
var lattice = new THREE.Mesh( new THREE.IcosahedronGeometry( radius * 1.25, 2), latticeMaterial );
lattice.update = function(){
this.rotation.y += 0.001;
this.rotation.z -= 0.0009;
this.rotation.x -= 0.0004;
}
lattice.material.map.wrapS = THREE.RepeatWrapping;
lattice.material.map.wrapT = THREE.RepeatWrapping;
lattice.material.map.needsUpdate = true;
lattice.material.map.onUpdate = function(){
this.offset.y -= 0.01;
this.needsUpdate = true;
}
sun.add(lattice);
sun.sunUniforms = sunUniforms;
sun.solarflareUniforms = solarflareUniforms;
sun.haloUniforms = haloUniforms;
sun.coronaUniforms = coronaUniforms;
// sun.rotation.z = -0.93;
// sun.rotation.y = 0.2;
sun.setSpectralIndex = function( index ){
var starColor = map( index, -0.3, 1.52, 0, 1);
starColor = constrain( starColor, 0.0, 1.0 );
this.starColor = starColor;
this.sunUniforms.spectralLookup.value = starColor;
this.solarflareUniforms.spectralLookup.value = starColor;
this.haloUniforms.spectralLookup.value = starColor;
this.coronaUniforms.spectralLookup.value = starColor;
}
sun.setScale = function( index ){
this.scale.setLength( index );
// remove old lensflare
this.gyro.remove( this.lensflare );
var lensflareSize = 4.0 + index * 0.5 + 0.1 * Math.pow(index,2);
if( lensflareSize < 1.5 )
lensflareSize = 1.5;
this.lensflare = makeStarLensflare( lensflareSize, 0.0002 * index, this.starColor );
this.lensflare.name = 'lensflare';
this.gyro.add( this.lensflare );
}
sun.randomizeSolarFlare = function(){
this.solarflare.rotation.x = Math.random() * Math.PI * 2;
this.solarflare.rotation.y = Math.random() * Math.PI * 2;
}
sun.setSpectralIndex( spectral );
sun.update = function(){
this.sunUniforms.time.value = shaderTiming;
this.haloUniforms.time.value = shaderTiming + rotateYAccumulate;
this.solarflareUniforms.time.value = shaderTiming;
// ugly.. terrible hack
// no matter what I do I can't remove the lensflare visibility at a distance
// which was causing jittering on pixels when the lensflare was too small to be visible
// is this the only way?
if( camera.position.z > 400 ){
var lensflareChild = this.gyro.getObjectByName('lensflare');
if( lensflareChild !== undefined )
this.gyro.remove( lensflareChild );
}
else{
if( this.gyro.getObjectByName('lensflare') === undefined ){
this.gyro.add( this.lensflare );
}
}
}
// test controls
var c = gui.add( sunUniforms.spectralLookup, 'value', -.25, 1.5 );
c.onChange( function(v){
sun.setSpectralIndex( v );
});
// doesn't work
// var c = gui.add( sunUniforms.texturePrimary.value.repeat, 'x', 0.2, 100.0 )
// .name( 'sun texture repeat')
// .onChange( function(v){
// sunUniforms.texturePrimary.value.repeat.y = v;
// sunUniforms.texturePrimary.value.needsUpdate = true;
// });
return sun;
}
|
import path from 'path';
import fs from 'fs-extra';
import { walkJsonDir, walkJsonDirSync } from './walkDir';
jest.mock('fs-extra');
describe('walkJsonDir', () => {
it('walks the api directory for relevant files', async () => {
const mockFileSystem = {
app: {
api: {
'2016-2017': {
'modules.json': '["test"]',
},
'2017-2018': {
'modules.json': '["test1"]',
},
},
},
};
fs.setMock(mockFileSystem);
const expected = {
'2016-2017': ['test'],
'2017-2018': ['test1'],
};
const apiPath = path.join('app', 'api');
expect(await walkJsonDir(apiPath, 'modules.json')).toEqual(expected);
});
});
describe('walkJsonDirSync', () => {
it('walks the api directory for relevant files', async () => {
const mockFileSystem = {
app: {
api: {
'2016-2017': {
'modules.json': '["test"]',
},
'2017-2018': {
'modules.json': '["test1"]',
},
},
},
};
fs.setMock(mockFileSystem);
const expected = {
'2016-2017': ['test'],
'2017-2018': ['test1'],
};
const apiPath = path.join('app', 'api');
expect(walkJsonDirSync(apiPath, 'modules.json')).toEqual(expected);
});
});
|
import React from 'react';
import { Button } from '../../../../src';
import generateCodeTemplate from './generateCodeTemplate';
import generateTableTemplate from './generateTableTemplate';
import styles from './style';
const sampleCode = `import {Button} from 'scuba';
<div>
<Button>BUTTON</Button>
<Button backgroundColor="none">BUTTON</Button>
<Button disabled>DISABLED</Button>
<Button clear>CLEAR</Button>
</div>
`;
const Buttons = () => (
<div>
<h2 id="buttons">Buttons</h2>
<div className={styles.buttons}>
<Button>BUTTON</Button>
<Button backgroundColor="none">BUTTON</Button>
<Button disabled>DISABLED</Button>
<Button clear>CLEAR</Button>
</div>
{generateCodeTemplate(sampleCode)}
<h3>Properties</h3>
<h4>Button</h4>
{generateTableTemplate([
{
name : 'className',
type : 'string',
default: ''
},
{
name : 'style',
type : 'Object',
default: ''
},
{
name : 'children',
type : 'React.Element<*>',
default: ''
},
{
name : 'width',
type : 'number | string',
default: 'auto'
},
{
name : 'backgroundColor',
type : 'none | string',
default: 'a theme\'s color'
},
{
name : 'disabled',
type : 'boolean',
default: 'false'
},
{
name : 'clear',
type : 'boolean',
default: 'false'
},
{
name : 'onClick',
type : 'Function',
default: ''
}
])}
</div>
);
export default Buttons;
|
const VoiceResponse = require('twilio').twiml.VoiceResponse;
const response = new VoiceResponse();
const dial = response.dial();
dial.number('415-123-4567');
console.log(response.toString());
|
"use strict";
const prettier = require("prettier-local");
const generateSchema = require("../../../scripts/generate-schema");
test("schema", () => {
expect(generateSchema(prettier.getSupportInfo().options)).toMatchSnapshot();
});
|
import sumArray from './'
test('should sum an array of integers', () => {
const one = sumArray([1])
expect(one).toBe(1)
const two = sumArray([1, 2, -1])
expect(two).toBe(2)
const six = sumArray([1, 2, 3])
expect(six).toBe(6)
})
test('should handle empty lists', () => {
const empty = sumArray([])
expect(empty).toEqual(0)
})
|
var fs = require('fs');
fs.readFile(process.argv[2], function (err, data) {
if (err) {
console.log(err);
} else {
var lines = data.toString('utf8').split('\n').length - 1;
console.log(lines);
}
});
|
/**
* @license
* Copyright 2018 Google Inc.
*
* 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.
*/
import * as tslib_1 from "tslib";
import { MDCComponent } from '@material/base/component';
import { applyPassive } from '@material/dom/events';
import { matches } from '@material/dom/ponyfill';
import { MDCRipple } from '@material/ripple/component';
import { MDCRippleFoundation } from '@material/ripple/foundation';
import { MDCSwitchFoundation } from './foundation';
var MDCSwitch = /** @class */ (function (_super) {
tslib_1.__extends(MDCSwitch, _super);
function MDCSwitch() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.ripple_ = _this.createRipple_();
return _this;
}
MDCSwitch.attachTo = function (root) {
return new MDCSwitch(root);
};
MDCSwitch.prototype.destroy = function () {
_super.prototype.destroy.call(this);
this.ripple_.destroy();
this.nativeControl_.removeEventListener('change', this.changeHandler_);
};
MDCSwitch.prototype.initialSyncWithDOM = function () {
var _this = this;
this.changeHandler_ = function () {
var _a;
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return (_a = _this.foundation_).handleChange.apply(_a, tslib_1.__spread(args));
};
this.nativeControl_.addEventListener('change', this.changeHandler_);
// Sometimes the checked state of the input element is saved in the history.
// The switch styling should match the checked state of the input element.
// Do an initial sync between the native control and the foundation.
this.checked = this.checked;
};
MDCSwitch.prototype.getDefaultFoundation = function () {
var _this = this;
// DO NOT INLINE this variable. For backward compatibility, foundations take a Partial<MDCFooAdapter>.
// To ensure we don't accidentally omit any methods, we need a separate, strongly typed adapter variable.
var adapter = {
addClass: function (className) { return _this.root_.classList.add(className); },
removeClass: function (className) { return _this.root_.classList.remove(className); },
setNativeControlChecked: function (checked) { return _this.nativeControl_.checked = checked; },
setNativeControlDisabled: function (disabled) { return _this.nativeControl_.disabled = disabled; },
};
return new MDCSwitchFoundation(adapter);
};
Object.defineProperty(MDCSwitch.prototype, "ripple", {
get: function () {
return this.ripple_;
},
enumerable: true,
configurable: true
});
Object.defineProperty(MDCSwitch.prototype, "checked", {
get: function () {
return this.nativeControl_.checked;
},
set: function (checked) {
this.foundation_.setChecked(checked);
},
enumerable: true,
configurable: true
});
Object.defineProperty(MDCSwitch.prototype, "disabled", {
get: function () {
return this.nativeControl_.disabled;
},
set: function (disabled) {
this.foundation_.setDisabled(disabled);
},
enumerable: true,
configurable: true
});
MDCSwitch.prototype.createRipple_ = function () {
var _this = this;
var RIPPLE_SURFACE_SELECTOR = MDCSwitchFoundation.strings.RIPPLE_SURFACE_SELECTOR;
var rippleSurface = this.root_.querySelector(RIPPLE_SURFACE_SELECTOR);
// DO NOT INLINE this variable. For backward compatibility, foundations take a Partial<MDCFooAdapter>.
// To ensure we don't accidentally omit any methods, we need a separate, strongly typed adapter variable.
var adapter = tslib_1.__assign({}, MDCRipple.createAdapter(this), { addClass: function (className) { return rippleSurface.classList.add(className); }, computeBoundingRect: function () { return rippleSurface.getBoundingClientRect(); }, deregisterInteractionHandler: function (evtType, handler) {
_this.nativeControl_.removeEventListener(evtType, handler, applyPassive());
}, isSurfaceActive: function () { return matches(_this.nativeControl_, ':active'); }, isUnbounded: function () { return true; }, registerInteractionHandler: function (evtType, handler) {
_this.nativeControl_.addEventListener(evtType, handler, applyPassive());
}, removeClass: function (className) { return rippleSurface.classList.remove(className); }, updateCssVariable: function (varName, value) {
rippleSurface.style.setProperty(varName, value);
} });
return new MDCRipple(this.root_, new MDCRippleFoundation(adapter));
};
Object.defineProperty(MDCSwitch.prototype, "nativeControl_", {
get: function () {
var NATIVE_CONTROL_SELECTOR = MDCSwitchFoundation.strings.NATIVE_CONTROL_SELECTOR;
return this.root_.querySelector(NATIVE_CONTROL_SELECTOR);
},
enumerable: true,
configurable: true
});
return MDCSwitch;
}(MDCComponent));
export { MDCSwitch };
//# sourceMappingURL=component.js.map |
!function(e){function r(t){if(o[t])return o[t].exports;var n=o[t]={exports:{},id:t,loaded:!1};return e[t].call(n.exports,n,n.exports,r),n.loaded=!0,n.exports}var o={};return r.m=e,r.c=o,r.p="/",r(0)}([function(e,r,o){e.exports=o(1)},function(e,r){"use strict";function o(){var e=new ScrollMagic.Controller;new ScrollMagic.Scene({duration:100,offset:50}).setPin(".banner-mobile").addTo(e)}Object.defineProperty(r,"__esModule",{value:!0}),r.default=o}]); |
// Download the Node helper library from twilio.com/docs/libraries/node
// These consts are your accountSid and authToken from https://www.twilio.com/console
const accountSid = 'ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
const authToken = 'your_auth_token';
const client = require('twilio')(accountSid, authToken);
const opts = {
friendlyName: 'My First Service',
statusCallback: 'http://requestb.in/1234abcd',
};
client.messaging.services
.create(opts)
.then(response => {
console.log(response);
})
.catch(error => {
console.log(error);
});
|
/*
* Copyright (c) 2015 by Rafael Angel Aznar Aparici (rafaaznar at gmail dot com)
*
* openAUSIAS: The stunning micro-library that helps you to develop easily
* AJAX web applications by using Java and jQuery
* openAUSIAS is distributed under the MIT License (MIT)
* Sources at https://github.com/rafaelaznar/
*
* 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.
*
*/
'use strict';
moduloTipotarea.controller('TipotareaPListController', ['$scope', '$routeParams', 'serverService', '$location',
function ($scope, $routeParams, serverService, $location) {
$scope.visibles={};
$scope.visibles.id = true;
$scope.visibles.id_curso = true;
$scope.visibles.ponderacion = true;
$scope.visibles.descripcion = true;
$scope.ob = "tipotarea";
$scope.op = "plist";
$scope.title = "Listado de tipotareaes";
$scope.icon = "fa-user";
$scope.neighbourhood = 2;
if (!$routeParams.page) {
$routeParams.page = 1;
}
if (!$routeParams.rpp) {
$routeParams.rpp = 10;
}
$scope.numpage = $routeParams.page;
$scope.rpp = $routeParams.rpp;
$scope.order = "";
$scope.ordervalue = "";
$scope.filter = "id";
$scope.filteroperator = "like";
$scope.filtervalue = "";
$scope.systemfilter = "";
$scope.systemfilteroperator = "";
$scope.systemfiltervalue = "";
$scope.params = "";
$scope.paramsWithoutOrder = "";
$scope.paramsWithoutFilter = "";
$scope.paramsWithoutSystemFilter = "";
if ($routeParams.order && $routeParams.ordervalue) {
$scope.order = $routeParams.order;
$scope.ordervalue = $routeParams.ordervalue;
$scope.orderParams = "&order=" + $routeParams.order + "&ordervalue=" + $routeParams.ordervalue;
$scope.paramsWithoutFilter += $scope.orderParams;
$scope.paramsWithoutSystemFilter += $scope.orderParams;
} else {
$scope.orderParams = "";
}
if ($routeParams.filter && $routeParams.filteroperator && $routeParams.filtervalue) {
$scope.filter = $routeParams.filter;
$scope.filteroperator = $routeParams.filteroperator;
$scope.filtervalue = $routeParams.filtervalue;
$scope.filterParams = "&filter=" + $routeParams.filter + "&filteroperator=" + $routeParams.filteroperator + "&filtervalue=" + $routeParams.filtervalue;
$scope.paramsWithoutOrder += $scope.filterParams;
$scope.paramsWithoutSystemFilter += $scope.filterParams;
} else {
$scope.filterParams = "";
}
if ($routeParams.systemfilter && $routeParams.systemfilteroperator && $routeParams.systemfiltervalue) {
$scope.systemFilterParams = "&systemfilter=" + $routeParams.systemfilter + "&systemfilteroperator=" + $routeParams.systemfilteroperator + "&systemfiltervalue=" + $routeParams.systemfiltervalue;
$scope.paramsWithoutOrder += $scope.systemFilterParams;
$scope.paramsWithoutFilter += $scope.systemFilterParams;
} else {
$scope.systemFilterParams = "";
}
$scope.params = ($scope.orderParams + $scope.filterParams + $scope.systemFilterParams);
$scope.params = $scope.params.replace('&', '?');
serverService.getDataFromPromise(serverService.promise_getSome($scope.ob, $scope.rpp, $scope.numpage, $scope.filterParams, $scope.orderParams, $scope.systemFilterParams)).then(function (data) {
if (data.status != 200) {
$scope.status = "Error en la recepción de datos del servidor";
} else {
$scope.pages = data.message.pages.message;
if (parseInt($scope.numpage) > parseInt($scope.pages))
$scope.numpage = $scope.pages;
$scope.page = data.message.page.message;
$scope.registers = data.message.registers.message;
$scope.status = "";
}
});
$scope.getRangeArray = function (lowEnd, highEnd) {
var rangeArray = [];
for (var i = lowEnd; i <= highEnd; i++) {
rangeArray.push(i);
}
return rangeArray;
};
$scope.evaluateMin = function (lowEnd, highEnd) {
return Math.min(lowEnd, highEnd);
};
$scope.evaluateMax = function (lowEnd, highEnd) {
return Math.max(lowEnd, highEnd);
};
$scope.dofilter = function () {
if ($scope.filter != "" && $scope.filteroperator != "" && $scope.filtervalue != "") {
if ($routeParams.order && $routeParams.ordervalue) {
if ($routeParams.systemfilter && $routeParams.systemfilteroperator) {
$location.path($scope.ob + '/' + $scope.op + '/' + $scope.numpage + '/' + $scope.rpp).search('filter', $scope.filter).search('filteroperator', $scope.filteroperator).search('filtervalue', $scope.filtervalue).search('order', $routeParams.order).search('ordervalue', $routeParams.ordervalue).search('systemfilter', $routeParams.systemfilter).search('systemfilteroperator', $routeParams.systemfilteroperator).search('systemfiltervalue', $routeParams.systemfiltervalue);
} else {
$location.path($scope.ob + '/' + $scope.op + '/' + $scope.numpage + '/' + $scope.rpp).search('filter', $scope.filter).search('filteroperator', $scope.filteroperator).search('filtervalue', $scope.filtervalue).search('order', $routeParams.order).search('ordervalue', $routeParams.ordervalue);
}
} else {
$location.path($scope.ob + '/' + $scope.op + '/' + $scope.numpage + '/' + $scope.rpp).search('filter', $scope.filter).search('filteroperator', $scope.filteroperator).search('filtervalue', $scope.filtervalue);
}
}
return false;
};
}]); |
/**********************************************************\
| |
| hprose |
| |
| Official WebSite: http://www.hprose.com/ |
| http://www.hprose.org/ |
| |
\**********************************************************/
/**********************************************************\
* *
* HarmonyMaps.js *
* *
* Harmony Maps for JavaScript. *
* *
* LastModified: Nov 18, 2016 *
* Author: Ma Bingyao <andot@hprose.com> *
* *
\**********************************************************/
(function (global) {
'use strict';
var hasWeakMap = 'WeakMap' in global;
var hasMap = 'Map' in global;
var hasForEach = true;
if (hasMap) {
hasForEach = 'forEach' in new global.Map();
}
if (hasWeakMap && hasMap && hasForEach) { return; }
var hasObject_create = 'create' in Object;
var createNPO = function () {
return hasObject_create ? Object.create(null) : {};
};
var namespaces = createNPO();
var count = 0;
var reDefineValueOf = function (obj) {
var privates = createNPO();
var baseValueOf = obj.valueOf;
var valueOf = function (namespace, n) {
if ((this === obj) &&
(n in namespaces) &&
(namespaces[n] === namespace)) {
if (!(n in privates)) { privates[n] = createNPO(); }
return privates[n];
}
else {
return baseValueOf.apply(this, arguments);
}
};
if (hasObject_create && 'defineProperty' in Object) {
Object.defineProperty(obj, 'valueOf', {
value: valueOf,
writable: true,
configurable: true,
enumerable: false
});
}
else {
obj.valueOf = valueOf;
}
};
if (!hasWeakMap) {
global.WeakMap = function WeakMap() {
var namespace = createNPO();
var n = count++;
namespaces[n] = namespace;
var map = function (key) {
if (key !== Object(key)) {
throw new Error('value is not a non-null object');
}
var privates = key.valueOf(namespace, n);
if (privates !== key.valueOf()) {
return privates;
}
reDefineValueOf(key);
return key.valueOf(namespace, n);
};
var m = this;
if (hasObject_create) {
m = Object.create(WeakMap.prototype, {
get: {
value: function (key) { return map(key).value; },
writable: false,
configurable: false,
enumerable: false
},
set: {
value: function (key, value) { map(key).value = value; },
writable: false,
configurable: false,
enumerable: false
},
has: {
value: function (key) { return 'value' in map(key); },
writable: false,
configurable: false,
enumerable: false
},
'delete': {
value: function (key) { return delete map(key).value; },
writable: false,
configurable: false,
enumerable: false
},
clear: {
value: function () {
delete namespaces[n];
n = count++;
namespaces[n] = namespace;
},
writable: false,
configurable: false,
enumerable: false
}
});
}
else {
m.get = function (key) { return map(key).value; };
m.set = function (key, value) { map(key).value = value; };
m.has = function (key) { return 'value' in map(key); };
m['delete'] = function (key) { return delete map(key).value; };
m.clear = function () {
delete namespaces[n];
n = count++;
namespaces[n] = namespace;
};
}
if (arguments.length > 0 && Array.isArray(arguments[0])) {
var iterable = arguments[0];
for (var i = 0, len = iterable.length; i < len; i++) {
m.set(iterable[i][0], iterable[i][1]);
}
}
return m;
};
}
if (!hasMap) {
var objectMap = function () {
var namespace = createNPO();
var n = count++;
var nullMap = createNPO();
namespaces[n] = namespace;
var map = function (key) {
if (key === null) { return nullMap; }
var privates = key.valueOf(namespace, n);
if (privates !== key.valueOf()) { return privates; }
reDefineValueOf(key);
return key.valueOf(namespace, n);
};
return {
get: function (key) { return map(key).value; },
set: function (key, value) { map(key).value = value; },
has: function (key) { return 'value' in map(key); },
'delete': function (key) { return delete map(key).value; },
clear: function () {
delete namespaces[n];
n = count++;
namespaces[n] = namespace;
}
};
};
var noKeyMap = function () {
var map = createNPO();
return {
get: function () { return map.value; },
set: function (_, value) { map.value = value; },
has: function () { return 'value' in map; },
'delete': function () { return delete map.value; },
clear: function () { map = createNPO(); }
};
};
var scalarMap = function () {
var map = createNPO();
return {
get: function (key) { return map[key]; },
set: function (key, value) { map[key] = value; },
has: function (key) { return key in map; },
'delete': function (key) { return delete map[key]; },
clear: function () { map = createNPO(); }
};
};
if (!hasObject_create) {
var stringMap = function () {
var map = {};
return {
get: function (key) { return map['!' + key]; },
set: function (key, value) { map['!' + key] = value; },
has: function (key) { return ('!' + key) in map; },
'delete': function (key) { return delete map['!' + key]; },
clear: function () { map = {}; }
};
};
}
global.Map = function Map() {
var map = {
'number': scalarMap(),
'string': hasObject_create ? scalarMap() : stringMap(),
'boolean': scalarMap(),
'object': objectMap(),
'function': objectMap(),
'unknown': objectMap(),
'undefined': noKeyMap(),
'null': noKeyMap()
};
var size = 0;
var keys = [];
var m = this;
if (hasObject_create) {
m = Object.create(Map.prototype, {
size: {
get : function () { return size; },
configurable: false,
enumerable: false
},
get: {
value: function (key) {
return map[typeof(key)].get(key);
},
writable: false,
configurable: false,
enumerable: false
},
set: {
value: function (key, value) {
if (!this.has(key)) {
keys.push(key);
size++;
}
map[typeof(key)].set(key, value);
},
writable: false,
configurable: false,
enumerable: false
},
has: {
value: function (key) {
return map[typeof(key)].has(key);
},
writable: false,
configurable: false,
enumerable: false
},
'delete': {
value: function (key) {
if (this.has(key)) {
size--;
keys.splice(keys.indexOf(key), 1);
return map[typeof(key)]['delete'](key);
}
return false;
},
writable: false,
configurable: false,
enumerable: false
},
clear: {
value: function () {
keys.length = 0;
for (var key in map) { map[key].clear(); }
size = 0;
},
writable: false,
configurable: false,
enumerable: false
},
forEach: {
value: function (callback, thisArg) {
for (var i = 0, n = keys.length; i < n; i++) {
callback.call(thisArg, this.get(keys[i]), keys[i], this);
}
},
writable: false,
configurable: false,
enumerable: false
}
});
}
else {
m.size = size;
m.get = function (key) {
return map[typeof(key)].get(key);
};
m.set = function (key, value) {
if (!this.has(key)) {
keys.push(key);
this.size = ++size;
}
map[typeof(key)].set(key, value);
};
m.has = function (key) {
return map[typeof(key)].has(key);
};
m['delete'] = function (key) {
if (this.has(key)) {
this.size = --size;
keys.splice(keys.indexOf(key), 1);
return map[typeof(key)]['delete'](key);
}
return false;
};
m.clear = function () {
keys.length = 0;
for (var key in map) { map[key].clear(); }
this.size = size = 0;
};
m.forEach = function (callback, thisArg) {
for (var i = 0, n = keys.length; i < n; i++) {
callback.call(thisArg, this.get(keys[i]), keys[i], this);
}
};
}
if (arguments.length > 0 && Array.isArray(arguments[0])) {
var iterable = arguments[0];
for (var i = 0, len = iterable.length; i < len; i++) {
m.set(iterable[i][0], iterable[i][1]);
}
}
return m;
};
}
if (!hasForEach) {
var OldMap = global.Map;
global.Map = function Map() {
var map = new OldMap();
var size = 0;
var keys = [];
var m = Object.create(Map.prototype, {
size: {
get : function () { return size; },
configurable: false,
enumerable: false
},
get: {
value: function (key) {
return map.get(key);
},
writable: false,
configurable: false,
enumerable: false
},
set: {
value: function (key, value) {
if (!map.has(key)) {
keys.push(key);
size++;
}
map.set(key, value);
},
writable: false,
configurable: false,
enumerable: false
},
has: {
value: function (key) {
return map.has(key);
},
writable: false,
configurable: false,
enumerable: false
},
'delete': {
value: function (key) {
if (map.has(key)) {
size--;
keys.splice(keys.indexOf(key), 1);
return map['delete'](key);
}
return false;
},
writable: false,
configurable: false,
enumerable: false
},
clear: {
value: function () {
if ('clear' in map) {
map.clear();
}
else {
for (var i = 0, n = keys.length; i < n; i++) {
map['delete'](keys[i]);
}
}
keys.length = 0;
size = 0;
},
writable: false,
configurable: false,
enumerable: false
},
forEach: {
value: function (callback, thisArg) {
for (var i = 0, n = keys.length; i < n; i++) {
callback.call(thisArg, this.get(keys[i]), keys[i], this);
}
},
writable: false,
configurable: false,
enumerable: false
}
});
if (arguments.length > 0 && Array.isArray(arguments[0])) {
var iterable = arguments[0];
for (var i = 0, len = iterable.length; i < len; i++) {
m.set(iterable[i][0], iterable[i][1]);
}
}
return m;
};
}
})(hprose.global);
|
/**
* ueditor完整配置项
* 可以在这里配置整个编辑器的特性
*/
/**************************提示********************************
* 所有被注释的配置项均为UEditor默认值。
* 修改默认配置请首先确保已经完全明确该参数的真实用途。
* 主要有两种修改方案,一种是取消此处注释,然后修改成对应参数;另一种是在实例化编辑器时传入对应参数。
* 当升级编辑器时,可直接使用旧版配置文件替换新版配置文件,不用担心旧版配置文件中因缺少新功能所需的参数而导致脚本报错。
**************************提示********************************/
(function () {
/**
* 编辑器资源文件根路径。它所表示的含义是:以编辑器实例化页面为当前路径,指向编辑器资源文件(即dialog等文件夹)的路径。
* 鉴于很多同学在使用编辑器的时候出现的种种路径问题,此处强烈建议大家使用"相对于网站根目录的相对路径"进行配置。
* "相对于网站根目录的相对路径"也就是以斜杠开头的形如"/myProject/ueditor/"这样的路径。
* 如果站点中有多个不在同一层级的页面需要实例化编辑器,且引用了同一UEditor的时候,此处的URL可能不适用于每个页面的编辑器。
* 因此,UEditor提供了针对不同页面的编辑器可单独配置的根路径,具体来说,在需要实例化编辑器的页面最顶部写上如下代码即可。当然,需要令此处的URL等于对应的配置。
* window.UEDITOR_HOME_URL = "/xxxx/xxxx/";
*/
var URL = window.UEDITOR_HOME_URL || (function(){
function PathStack() {
this.documentURL = self.document.URL || self.location.href;
this.separator = '/';
this.separatorPattern = /\\|\//g;
this.currentDir = './';
this.currentDirPattern = /^[.]\/]/;
this.path = this.documentURL;
this.stack = [];
this.push( this.documentURL );
}
PathStack.isParentPath = function( path ){
return path === '..';
};
PathStack.hasProtocol = function( path ){
return !!PathStack.getProtocol( path );
};
PathStack.getProtocol = function( path ){
var protocol = /^[^:]*:\/*/.exec( path );
return protocol ? protocol[0] : null;
};
PathStack.prototype = {
push: function( path ){
this.path = path;
update.call( this );
parse.call( this );
return this;
},
getPath: function(){
return this + "";
},
toString: function(){
return this.protocol + ( this.stack.concat( [''] ) ).join( this.separator );
}
};
function update() {
var protocol = PathStack.getProtocol( this.path || '' );
if( protocol ) {
//根协议
this.protocol = protocol;
//local
this.localSeparator = /\\|\//.exec( this.path.replace( protocol, '' ) )[0];
this.stack = [];
} else {
protocol = /\\|\//.exec( this.path );
protocol && (this.localSeparator = protocol[0]);
}
}
function parse(){
var parsedStack = this.path.replace( this.currentDirPattern, '' );
if( PathStack.hasProtocol( this.path ) ) {
parsedStack = parsedStack.replace( this.protocol , '');
}
parsedStack = parsedStack.split( this.localSeparator );
parsedStack.length = parsedStack.length - 1;
for(var i= 0,tempPath,l=parsedStack.length,root = this.stack;i<l;i++){
tempPath = parsedStack[i];
if(tempPath){
if( PathStack.isParentPath( tempPath ) ) {
root.pop();
} else {
root.push( tempPath );
}
}
}
}
var currentPath = document.getElementsByTagName('script');
currentPath = currentPath[ currentPath.length -1 ].src;
return new PathStack().push( currentPath ) + "";
})();
/**
* 配置项主体。注意,此处所有涉及到路径的配置别遗漏URL变量。
*/
window.UEDITOR_CONFIG = {
//为编辑器实例添加一个路径,这个不能被注释
UEDITOR_HOME_URL : URL
//图片上传配置区
,imageUrl:URL+"../../fwrite/upload_img" //图片上传提交地址
,imagePath:"" //图片修正地址,引用了fixedImagePath,如有特殊需求,可自行配置
//,imageFieldName:"upfile" //图片数据的key,若此处修改,需要在后台对应文件修改对应参数
//,compressSide:0 //等比压缩的基准,确定maxImageSideLength参数的参照对象。0为按照最长边,1为按照宽度,2为按照高度
//,maxImageSideLength:900 //上传图片最大允许的边长,超过会自动等比缩放,不缩放就设置一个比较大的值,更多设置在image.html中
//涂鸦图片配置区
,scrawlUrl:URL+"../../fwrite/upload_scraw" //涂鸦上传地址
,scrawlPath:"" //图片修正地址,同imagePath
//附件上传配置区
,fileUrl:URL+"../../fwrite/upload_file" //附件上传提交地址
,filePath:"" //附件修正地址,同imagePath
//,fileFieldName:"upfile" //附件提交的表单名,若此处修改,需要在后台对应文件修改对应参数
//远程抓取配置区
//,catchRemoteImageEnable:true //是否开启远程图片抓取,默认开启
,catcherUrl:URL +"../../fwrite/get_remote_image" //处理远程图片抓取的地址
,catcherPath:"" //图片修正地址,同imagePath
//,catchFieldName:"upfile" //提交到后台远程图片uri合集,若此处修改,需要在后台对应文件修改对应参数
//,separater:'ue_separate_ue' //提交至后台的远程图片地址字符串分隔符
//,localDomain:[] //本地顶级域名,当开启远程图片抓取时,除此之外的所有其它域名下的图片都将被抓取到本地,默认不抓取127.0.0.1和localhost
//图片在线管理配置区
,imageManagerUrl:URL + "../../fwrite/image_manager" //图片在线管理的处理地址
,imageManagerPath:"" //图片修正地址,同imagePath
//屏幕截图配置区
,snapscreenHost: location.hostname //屏幕截图的server端文件所在的网站地址或者ip,请不要加http://
,snapscreenServerUrl: URL +"php/imageUp.php" //屏幕截图的server端保存程序,UEditor的范例代码为“URL +"server/upload/php/snapImgUp.php"”
,snapscreenPath: URL + "php/"
,snapscreenServerPort: location.port //屏幕截图的server端端口
//,snapscreenImgAlign: '' //截图的图片默认的排版方式
//word转存配置区
,wordImageUrl:URL + "php/imageUp.php" //word转存提交地址
,wordImagePath:URL + "php/" //
//,wordImageFieldName:"upfile" //word转存表单名若此处修改,需要在后台对应文件修改对应参数
//获取视频数据的地址
,getMovieUrl:URL+"../../fwrite/get_movie" //视频数据获取地址
//工具栏上的所有的功能按钮和下拉框,可以在new编辑器的实例时选择自己需要的从新定义
, toolbars:[
['fullscreen', 'source', '|', 'undo', 'redo', '|',
'bold', 'italic', 'underline', 'fontborder', 'strikethrough', 'superscript', 'subscript', 'removeformat', 'formatmatch', 'autotypeset', 'blockquote', 'pasteplain', '|', 'forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist', 'selectall', 'cleardoc', '|',
'rowspacingtop', 'rowspacingbottom', 'lineheight', '|',
'customstyle', 'paragraph', 'fontfamily', 'fontsize', '|',
'directionalityltr', 'directionalityrtl', 'indent', '|',
'justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|', 'touppercase', 'tolowercase', '|',
'link', 'unlink', 'anchor', '|', 'imagenone', 'imageleft', 'imageright', 'imagecenter', '|',
'insertimage', 'emotion', 'scrawl', 'insertvideo', 'music', 'attachment', 'map', 'gmap', 'insertframe','insertcode', 'webapp', 'pagebreak', 'template', 'background', '|',
'horizontal', 'date', 'time', 'spechars', 'snapscreen', 'wordimage', '|',
'inserttable', 'deletetable', 'insertparagraphbeforetable', 'insertrow', 'deleterow', 'insertcol', 'deletecol', 'mergecells', 'mergeright', 'mergedown', 'splittocells', 'splittorows', 'splittocols', '|',
'print', 'preview', 'searchreplace', 'help']
]
//当鼠标放在工具栏上时显示的tooltip提示,留空支持自动多语言配置,否则以配置值为准
// ,labelMap:{
// 'anchor':'', 'undo':''
// }
//webAppKey
//百度应用的APIkey,每个站长必须首先去百度官网注册一个key后方能正常使用app功能
//,webAppKey:""
//语言配置项,默认是zh-cn。有需要的话也可以使用如下这样的方式来自动多语言切换,当然,前提条件是lang文件夹下存在对应的语言文件:
//lang值也可以通过自动获取 (navigator.language||navigator.browserLanguage ||navigator.userLanguage).toLowerCase()
//,lang:"zh-cn"
//,langPath:URL +"lang/"
//主题配置项,默认是default。有需要的话也可以使用如下这样的方式来自动多主题切换,当然,前提条件是themes文件夹下存在对应的主题文件:
//现有如下皮肤:default
//,theme:'default'
//,themePath:URL +"themes/"
//若实例化编辑器的页面手动修改的domain,此处需要设置为true
//,customDomain:false
//针对getAllHtml方法,会在对应的head标签中增加该编码设置。
//,charset:"utf-8"
//常用配置项目
//,isShow : true //默认显示编辑器
//,initialContent:'欢迎使用ueditor!' //初始化编辑器的内容,也可以通过textarea/script给值,看官网例子
//,initialFrameWidth:1000 //初始化编辑器宽度,默认1000
//,initialFrameHeight:320 //初始化编辑器高度,默认320
//,autoClearinitialContent:true //是否自动清除编辑器初始内容,注意:如果focus属性设置为true,这个也为真,那么编辑器一上来就会触发导致初始化的内容看不到了
//,iframeCssUrl: URL + '/themes/iframe.css' //给编辑器内部引入一个css文件
//,textarea:'editorValue' // 提交表单时,服务器获取编辑器提交内容的所用的参数,多实例时可以给容器name属性,会将name给定的值最为每个实例的键值,不用每次实例化的时候都设置这个值
//,focus:false //初始化时,是否让编辑器获得焦点true或false
//,autoClearEmptyNode : true //getContent时,是否删除空的inlineElement节点(包括嵌套的情况)
//,fullscreen : false //是否开启初始化时即全屏,默认关闭
//,readonly : false //编辑器初始化结束后,编辑区域是否是只读的,默认是false
//,zIndex : 900 //编辑器层级的基数,默认是900
//,imagePopup:true //图片操作的浮层开关,默认打开
//如果自定义,最好给p标签如下的行高,要不输入中文时,会有跳动感
//,initialStyle:'p{line-height:1em}'//编辑器层级的基数,可以用来改变字体等
//,autoSyncData:true //自动同步编辑器要提交的数据
//,emotionLocalization:false //是否开启表情本地化,默认关闭。若要开启请确保emotion文件夹下包含官网提供的images表情文件夹
//,pasteplain:false //是否默认为纯文本粘贴。false为不使用纯文本粘贴,true为使用纯文本粘贴
//纯文本粘贴模式下的过滤规则
// 'filterTxtRules' : function(){
// function transP(node){
// node.tagName = 'p';
// node.setStyle();
// }
// return {
// //直接删除及其字节点内容
// '-' : 'script style object iframe embed input select',
// 'p': {$:{}},
// 'br':{$:{}},
// 'div':{'$':{}},
// 'li':{'$':{}},
// 'caption':transP,
// 'th':transP,
// 'tr':transP,
// 'h1':transP,'h2':transP,'h3':transP,'h4':transP,'h5':transP,'h6':transP,
// 'td':function(node){
// //没有内容的td直接删掉
// var txt = !!node.innerText();
// if(txt){
// node.parentNode.insertAfter(UE.uNode.createText(' '),node);
// }
// node.parentNode.removeChild(node,node.innerText())
// }
// }
// }()
//,allHtmlEnabled:false //提交到后台的数据是否包含整个html字符串
//iframeUrlMap
//dialog内容的路径 ~会被替换成URL,垓属性一旦打开,将覆盖所有的dialog的默认路径
//,iframeUrlMap:{
// 'anchor':'~/dialogs/anchor/anchor.html',
// }
//insertorderedlist
//有序列表的下拉配置,值留空时支持多语言自动识别,若配置值,则以此值为准
// ,'insertorderedlist':{
// //自定的样式
// 'num':'1,2,3...',
// 'num1':'1),2),3)...',
// 'num2':'(1),(2),(3)...',
// 'cn':'一,二,三....',
// 'cn1':'一),二),三)....',
// 'cn2':'(一),(二),(三)....',
// //系统自带
// 'decimal' : '' , //'1,2,3...'
// 'lower-alpha' : '' , // 'a,b,c...'
// 'lower-roman' : '' , //'i,ii,iii...'
// 'upper-alpha' : '' , lang //'A,B,C'
// 'upper-roman' : '' //'I,II,III...'
// }
//insertunorderedlist
//无序列表的下拉配置,值留空时支持多语言自动识别,若配置值,则以此值为准
//,insertunorderedlist : {
// //自定的样式
// 'dash' :'— 破折号',
// 'dot':' 。 小圆圈'
// //系统自带
// 'circle' : '', // '○ 小圆圈'
// 'disc' : '', // '● 小圆点'
// 'square' : '' //'■ 小方块'
//}
// ,listDefaultPaddingLeft : '30'//默认的左边缩进的基数倍
// ,listiconpath : 'http://bs.baidu.com/listicon/'//自定义标号的路径
// ,maxListLevel : 3 //限制可以tab的级数-1不限制
//fontfamily
//字体设置 label留空支持多语言自动切换,若配置,则以配置值为准
// ,'fontfamily':[
// { label:'',name:'songti',val:'宋体,SimSun'},
// { label:'',name:'kaiti',val:'楷体,楷体_GB2312, SimKai'},
// { label:'',name:'yahei',val:'微软雅黑,Microsoft YaHei'},
// { label:'',name:'heiti',val:'黑体, SimHei'},
// { label:'',name:'lishu',val:'隶书, SimLi'},
// { label:'',name:'andaleMono',val:'andale mono'},
// { label:'',name:'arial',val:'arial, helvetica,sans-serif'},
// { label:'',name:'arialBlack',val:'arial black,avant garde'},
// { label:'',name:'comicSansMs',val:'comic sans ms'},
// { label:'',name:'impact',val:'impact,chicago'},
// { label:'',name:'timesNewRoman',val:'times new roman'}
// ]
//fontsize
//字号
//,'fontsize':[10, 11, 12, 14, 16, 18, 20, 24, 36]
//paragraph
//段落格式 值留空时支持多语言自动识别,若配置,则以配置值为准
//,'paragraph':{'p':'', 'h1':'', 'h2':'', 'h3':'', 'h4':'', 'h5':'', 'h6':''}
//rowspacingtop
//段间距 值和显示的名字相同
//,'rowspacingtop':['5', '10', '15', '20', '25']
//rowspacingBottom
//段间距 值和显示的名字相同
//,'rowspacingbottom':['5', '10', '15', '20', '25']
//lineheight
//行内间距 值和显示的名字相同
//,'lineheight':['1', '1.5','1.75','2', '3', '4', '5']
//customstyle
//自定义样式,不支持国际化,此处配置值即可最后显示值
//block的元素是依据设置段落的逻辑设置的,inline的元素依据BIU的逻辑设置
//尽量使用一些常用的标签
//参数说明
//tag 使用的标签名字
//label 显示的名字也是用来标识不同类型的标识符,注意这个值每个要不同,
//style 添加的样式
//每一个对象就是一个自定义的样式
//,'customstyle':[
// {tag:'h1', name:'tc', label:'', style:'border-bottom:#ccc 2px solid;padding:0 4px 0 0;text-align:center;margin:0 0 20px 0;'},
// {tag:'h1', name:'tl',label:'', style:'border-bottom:#ccc 2px solid;padding:0 4px 0 0;margin:0 0 10px 0;'},
// {tag:'span',name:'im', label:'', style:'font-style:italic;font-weight:bold'},
// {tag:'span',name:'hi', label:'', style:'font-style:italic;font-weight:bold;color:rgb(51, 153, 204)'}
// ]
//右键菜单的内容,可以参考plugins/contextmenu.js里边的默认菜单的例子,label留空支持国际化,否则以此配置为准
// ,contextMenu:[
// {
// label:'', //显示的名称
// cmdName:'selectall',//执行的command命令,当点击这个右键菜单时
// //exec可选,有了exec就会在点击时执行这个function,优先级高于cmdName
// exec:function () {
// //this是当前编辑器的实例
// //this.ui._dialogs['inserttableDialog'].open();
// }
// }
// ]
//快捷菜单
//,shortcutMenu:["fontfamily", "fontsize", "bold", "italic", "underline", "forecolor", "backcolor", "insertorderedlist", "insertunorderedlist"]
//
//wordCount
//,wordCount:true //是否开启字数统计
//,maximumWords:10000 //允许的最大字符数
//字数统计提示,{#count}代表当前字数,{#leave}代表还可以输入多少字符数,留空支持多语言自动切换,否则按此配置显示
//,wordCountMsg:'' //当前已输入 {#count} 个字符,您还可以输入{#leave} 个字符
//超出字数限制提示 留空支持多语言自动切换,否则按此配置显示
//,wordOverFlowMsg:'' //<span style="color:red;">你输入的字符个数已经超出最大允许值,服务器可能会拒绝保存!</span>
//highlightcode
// 代码高亮时需要加载的第三方插件的路径
// ,highlightJsUrl:URL + "third-party/SyntaxHighlighter/shCore.js"
// ,highlightCssUrl:URL + "third-party/SyntaxHighlighter/shCoreDefault.css"
//tab
//点击tab键时移动的距离,tabSize倍数,tabNode什么字符做为单位
//,tabSize:4
//,tabNode:' '
//elementPathEnabled
//是否启用元素路径,默认是显示
//,elementPathEnabled : true
//removeFormat
//清除格式时可以删除的标签和属性
//removeForamtTags标签
//,removeFormatTags:'b,big,code,del,dfn,em,font,i,ins,kbd,q,samp,small,span,strike,strong,sub,sup,tt,u,var'
//removeFormatAttributes属性
//,removeFormatAttributes:'class,style,lang,width,height,align,hspace,valign'
//undo
//可以最多回退的次数,默认20
//,maxUndoCount:20
//当输入的字符数超过该值时,保存一次现场
//,maxInputCount:1
//autoHeightEnabled
// 是否自动长高,默认true
//,autoHeightEnabled:true
//scaleEnabled
//是否可以拉伸长高,默认true(当开启时,自动长高失效)
//,scaleEnabled:false
//,minFrameWidth:800 //编辑器拖动时最小宽度,默认800
//,minFrameHeight:220 //编辑器拖动时最小高度,默认220
//autoFloatEnabled
//是否保持toolbar的位置不动,默认true
//,autoFloatEnabled:true
//浮动时工具栏距离浏览器顶部的高度,用于某些具有固定头部的页面
//,topOffset:30
//编辑器底部距离工具栏高度(如果参数大于等于编辑器高度,则设置无效)
//,toolbarTopOffset:400
//indentValue
//首行缩进距离,默认是2em
//,indentValue:'2em'
//pageBreakTag
//分页标识符,默认是_ueditor_page_break_tag_
//,pageBreakTag:'_ueditor_page_break_tag_'
//sourceEditor
//源码的查看方式,codemirror 是代码高亮,textarea是文本框,默认是codemirror
//注意默认codemirror只能在ie8+和非ie中使用
//,sourceEditor:"codemirror"
//如果sourceEditor是codemirror,还用配置一下两个参数
//codeMirrorJsUrl js加载的路径,默认是 URL + "third-party/codemirror/codemirror.js"
//,codeMirrorJsUrl:URL + "third-party/codemirror/codemirror.js"
//codeMirrorCssUrl css加载的路径,默认是 URL + "third-party/codemirror/codemirror.css"
//,codeMirrorCssUrl:URL + "third-party/codemirror/codemirror.css"
//编辑器初始化完成后是否进入源码模式,默认为否。
//,sourceEditorFirst:false
//autotypeset
// //自动排版参数
// ,autotypeset:{
// mergeEmptyline : true, //合并空行
// removeClass : true, //去掉冗余的class
// removeEmptyline : false, //去掉空行
// textAlign : "left" , //段落的排版方式,可以是 left,right,center,justify 去掉这个属性表示不执行排版
// imageBlockLine : 'center', //图片的浮动方式,独占一行剧中,左右浮动,默认: center,left,right,none 去掉这个属性表示不执行排版
// pasteFilter : false, //根据规则过滤没事粘贴进来的内容
// clearFontSize : false, //去掉所有的内嵌字号,使用编辑器默认的字号
// clearFontFamily : false, //去掉所有的内嵌字体,使用编辑器默认的字体
// removeEmptyNode : false , // 去掉空节点
// //可以去掉的标签
// removeTagNames : {标签名字:1},
// indent : false, // 行首缩进
// indentValue : '2em' //行首缩进的大小
// },
//填写过滤规则
//filterRules : {}
};
})();
|
module.exports = function (App) {
var Contatos = App.Controllers.Contato;
App.route('/contatos/atualizar').post(Contatos.atualizar);
App.route('/contatos/cadastrados').post(Contatos.cadastrados);
App.route('/contatos/remover').post(Contatos.remover);
App.route('/contatos/cadastrar').post(Contatos.cadastrar);
}
|
var searchData=
[
['getapi',['GetApi',['../class_oxy_engine_1_1_game_instance.html#a1f748c1d60ef1ef37362c3608819e016',1,'OxyEngine::GameInstance']]],
['getbackgroundcolor',['GetBackgroundColor',['../class_oxy_engine_1_1_graphics_1_1_graphics_manager.html#adce48eecdd0ff39dbf6e0173481f2bac',1,'OxyEngine::Graphics::GraphicsManager']]],
['getcolor',['GetColor',['../class_oxy_engine_1_1_graphics_1_1_graphics_manager.html#a153afe3cdf4abe412afa930241d54a86',1,'OxyEngine::Graphics::GraphicsManager']]],
['getcursorposition',['GetCursorPosition',['../class_oxy_engine_1_1_input_1_1_input_manager.html#ab1560bdeee5af0ffdeb651d3f59b55aa',1,'OxyEngine::Input::InputManager']]],
['getgamepadstick',['GetGamePadStick',['../class_oxy_engine_1_1_input_1_1_input_manager.html#a0460ae9c31ac412fec6db59b1dc8f500',1,'OxyEngine::Input::InputManager']]],
['getgamepadtrigger',['GetGamePadTrigger',['../class_oxy_engine_1_1_input_1_1_input_manager.html#ac49207da22a7ddadcb4e7975ceb88026',1,'OxyEngine::Input::InputManager']]],
['getlinewidth',['GetLineWidth',['../class_oxy_engine_1_1_graphics_1_1_graphics_manager.html#a435673f4e2a47f3d6542b4419e6725b0',1,'OxyEngine::Graphics::GraphicsManager']]],
['getmousewheel',['GetMouseWheel',['../class_oxy_engine_1_1_input_1_1_input_manager.html#a8835cf218ca877181ce13aa86231cd71',1,'OxyEngine::Input::InputManager']]]
];
|
define(['app', 'editFormUtility',], function(app) {
app.directive('campaign', function() {
return {
restrict: 'EAC',
templateUrl: '/app/js/directives/campaign.html',
scope: {
id: '=',
},
controller: function(editFormUtility, $scope) {
$scope.campaign = {};
editFormUtility.load($scope.id).then(function(campaign) {
// console.log('campaign: ', campaign);
$scope.campaign = campaign;
});
},
};
});
});
|
/**
* @file TagField
*/
export default from './TagField';
|
/**
* @author: az@alloyTeam Bin Wang
* @description: 高斯模糊
*
*/
;(function(Ps){
window[Ps].module("Filter.gaussBlur",function(P){
var M = {
/**
* 高斯模糊
* @param {Array} pixes pix array
* @param {Number} width 图片的宽度
* @param {Number} height 图片的高度
* @param {Number} radius 取样区域半径, 正数, 可选, 默认为 3.0
* @param {Number} sigma 标准方差, 可选, 默认取值为 radius / 3
* @return {Array}
*/
process: function(imgData,radius, sigma) {
var pixes = imgData.data;
var width = imgData.width;
var height = imgData.height;
var gaussMatrix = [],
gaussSum = 0,
x, y,
r, g, b, a,
i, j, k, len;
radius = Math.floor(radius) || 3;
sigma = sigma || radius / 3;
a = 1 / (Math.sqrt(2 * Math.PI) * sigma);
b = -1 / (2 * sigma * sigma);
//生成高斯矩阵
for (i = 0, x = -radius; x <= radius; x++, i++){
g = a * Math.exp(b * x * x);
gaussMatrix[i] = g;
gaussSum += g;
}
//归一化, 保证高斯矩阵的值在[0,1]之间
for (i = 0, len = gaussMatrix.length; i < len; i++) {
gaussMatrix[i] /= gaussSum;
}
//x 方向一维高斯运算
for (y = 0; y < height; y++) {
for (x = 0; x < width; x++) {
r = g = b = a = 0;
gaussSum = 0;
for(j = -radius; j <= radius; j++){
k = x + j;
if(k >= 0 && k < width){//确保 k 没超出 x 的范围
//r,g,b,a 四个一组
i = (y * width + k) * 4;
r += pixes[i] * gaussMatrix[j + radius];
g += pixes[i + 1] * gaussMatrix[j + radius];
b += pixes[i + 2] * gaussMatrix[j + radius];
// a += pixes[i + 3] * gaussMatrix[j];
gaussSum += gaussMatrix[j + radius];
}
}
i = (y * width + x) * 4;
// 除以 gaussSum 是为了消除处于边缘的像素, 高斯运算不足的问题
// console.log(gaussSum)
pixes[i] = r / gaussSum;
pixes[i + 1] = g / gaussSum;
pixes[i + 2] = b / gaussSum;
// pixes[i + 3] = a ;
}
}
//y 方向一维高斯运算
for (x = 0; x < width; x++) {
for (y = 0; y < height; y++) {
r = g = b = a = 0;
gaussSum = 0;
for(j = -radius; j <= radius; j++){
k = y + j;
if(k >= 0 && k < height){//确保 k 没超出 y 的范围
i = (k * width + x) * 4;
r += pixes[i] * gaussMatrix[j + radius];
g += pixes[i + 1] * gaussMatrix[j + radius];
b += pixes[i + 2] * gaussMatrix[j + radius];
// a += pixes[i + 3] * gaussMatrix[j];
gaussSum += gaussMatrix[j + radius];
}
}
i = (y * width + x) * 4;
pixes[i] = r / gaussSum;
pixes[i + 1] = g / gaussSum;
pixes[i + 2] = b / gaussSum;
// pixes[i] = r ;
// pixes[i + 1] = g ;
// pixes[i + 2] = b ;
// pixes[i + 3] = a ;
}
}
//end
imgData.data = pixes;
return imgData;
}
};
return M;
});
})("psLib");
|
var mongoose = require('mongoose'),
bcrypt = require('bcrypt-nodejs');
// define the schema for our admin model
var schema = new mongoose.Schema({
username: String,
password: String
});
// methods ======================
// generating a hash
schema.methods.generateHash = function(password) {
return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
};
// checking if password is valid
schema.methods.checkPassword = function(password) {
return bcrypt.compareSync(password, this.password);
};
module.exports = mongoose.model('Admin', schema);
|
import { takeLatest, delay } from 'redux-saga';
import { call, put, fork } from 'redux-saga/effects';
import { fixedConstants, $setPrices } from './createCryptoCurrenciesPricesReduxStoreSection';
import invokeRequest from 'daniloster-utils/lib/invokeRequest';
import axios from 'axios';
import logger from '../logger';
export const timingRefreshPrices = logger.timeEffect(call, function* onRefreshPrices({ endpoints, selectedCurrencies, setPricesConstant }) {
yield put($setPrices([], setPricesConstant));
yield call(delay, 500);
const responses = yield endpoints.map(url => call(invokeRequest, axios.request, { url, method: 'GET' }));
const prices = responses.reduce((transientPrices, { error, data, status }, index) => {
if (status === 200 && data && data.length) {
const currency = selectedCurrencies[index].toLowerCase();
return data.map((priceCrypto) => {
const {
[`price_${currency}`]: price,
[`24h_volume_${currency}`]: volume24h,
[`market_cap_${currency}`]: marketCap,
price_usd: priceUSD,
['24h_volume_usd']: volume24hUSD,
market_cap_usd: marketCapUSD,
last_updated: lastUpdated,
rank,
...otherCryptoInfo,
} = priceCrypto;
const currentPriceGroups = (transientPrices[index] || { priceGroups: [] }).priceGroups;
return {
...otherCryptoInfo,
lastUpdated: Number(lastUpdated),
rank,
priceGroups: currentPriceGroups.concat(
(transientPrices.length === 0
? [
{
currency: 'USD',
price: Number(priceUSD),
volume24h: Number(volume24hUSD),
marketCap: Number(marketCapUSD),
},
]
: []).concat([
{
currency: selectedCurrencies[index],
price: Number(price),
volume24h: Number(volume24h),
marketCap: Number(marketCap),
},
]),
),
};
});
}
return transientPrices;
}, []);
yield put($setPrices(prices, setPricesConstant));
});
export function* watcRefreshPrices() {
yield* takeLatest(fixedConstants.REFRESH_PRICES, timingRefreshPrices);
}
export default function* () {
yield fork(watcRefreshPrices);
}
|
import { connect } from 'react-redux';
import Pager from '../../components/Transaction/List/Pager';
import { changeFilterPage } from '../../actions/ui/transaction/filter';
import {
getPage,
getVisiblePages
} from '../../selectors/ui/transaction/filter';
const mapStateToProps = state => ({
page: getPage(state),
pages: getVisiblePages(state)
});
export default connect(
mapStateToProps,
{ changeFilterPage }
)(Pager);
|
const express = require('express');
const router = express.Router();
router.get('/ping', (req, res, next) => res.send('pong!'));
router.get('/', (req, res, next) => {
const renderObject = {
title: 'home',
user: req.user,
messages: req.flash('messages')
};
res.render('index', renderObject);
});
module.exports = router;
|
// var Ownable = artifacts.require("ownership/Ownable.sol");
// NOTE: Use this file to easily deploy the contracts you're writing.
// (but make sure to reset this file before committing
// with `git checkout HEAD -- migrations/2_deploy_contracts.js`)
module.exports = function (deployer) {
// deployer.deploy(Ownable);
};
|
// START HEROKU SETUP
var express = require("express");
var app = express();
app.get('/', function(req, res){ res.send('The Guild Ball Plots bot is running.'); });
app.listen(process.env.PORT || 5000);
// END HEROKU SETUP
// config
//
// Config.keys uses environment variables so sensitive info is not in the repo.
var config = {
me: 'GuildBallPlots', // The authorized account with a list to retweet
keys: {
consumer_key: process.env.TWITTER_CONSUMER_KEY,
consumer_secret: process.env.TWITTER_CONSUMER_SECRET,
access_token_key: process.env.TWITTER_ACCESS_TOKEN_KEY,
access_token_secret: process.env.TWITTER_ACCESS_TOKEN_SECRET
},
};
/**
* A hash containg the season 1 plots and a count of
* how many times each has been selected. since last
* restart
*/
var plotLog = {
'Vengeance': 0,
'Man Marking': 0,
'Make A Game Of It!': 0,
'Knee Slider!': 0,
'Miraculous Recovery': 0,
'Keep Ball': 0,
'Man Down': 0,
'Sideline Repairs': 0,
'Dont Touch The Hair!': 0,
'Second Wind': 0,
'Who Are Ya?': 0,
'Protect Your Balls': 0
};
// A hash containg the season 1 plots
var seasonOnePlots = [
'Vengeance',
'Man Marking',
'Make A Game Of It!',
'Knee Slider!',
'Miraculous Recovery',
'Keep Ball',
'Man Down',
'Sideline Repairs',
'Dont Touch The Hair!',
'Second Wind',
'Who Are Ya?',
'Protect Your Balls'
];
/**
* For each player in the players array randomly select 5 unique
* plots from the seasonOnePlots array. Then add the player and
* their plots to the returned object.
*/
function getPlots(players) {
// clone the plots array
var plotsCpy = _.clone(seasonOnePlots);
var playersPlots = {};
var idx = 0;
var i = 0;
var j = 0;
do {
var plotText = ' Plots: ';
i = 0;
do {
// get a random index for the plots array
idx = Math.floor((Math.random() * plotsCpy.length));
// add the plot to the returned string
plotText = plotText + plotsCpy[idx];
if (i < 4) {
plotText = plotText + ', ';
}
// log the selection of the plot
plotLog[plotsCpy[idx]]++;
// remove the plot we have just added
plotsCpy.splice(idx, 1);
i++;
}
while (i < 5);
playersPlots[players[j]] = plotText;
j++;
}
while (j < players.length);
return playersPlots;
}
// Print the plot log to see whats been going on
function printPlotLog() {
console.log(JSON.stringify(plotLog, null, 4));
}
/**
* Check if a second player was mentioned in the tweet.
* If so, add them to the players array and get the
* plots. Finally, send a tweet to each player in the
* players array to let them know what their plots are.
*/
function buildReply(tweet) {
// Build the array of players
var players = [tweet.user.screen_name];
_.find(tweet.entities.user_mentions, function(user) {
if (user.screen_name !== config.me) {
players.push(user.screen_name);
}
});
// Get the plots for the players.
var playerPlots = getPlots(players);
var plotKeys = Object.keys(playerPlots);
sendTweetOrDm(plotKeys[0], playerPlots, tweet);
if (plotKeys.length > 1) {
sendTweetOrDm(plotKeys[1], playerPlots, tweet);
}
}
function sendTweetOrDm(player, playerPlots, tweet) {
twitter.post('direct_messages/new', {
screen_name: player,
text: playerPlots[player]
}, function(err, data, response) {
if(err) {
console.log('DM failed, sending as tweet instead.');
twitter.post('statuses/update', {
status: '@' + player + playerPlots[player],
in_reply_to_status_id: tweet.id_str
}, onTweet);
}
else {
console.log('DM sent successfully to ' + player + '. Text: ' + playerPlots[player]);
}
});
}
// What to do after we tweet something.
function onTweet(err, tweet, response) {
if(err) {
console.error("tweet failed to send :(");
console.error(err);
}
else {
console.log("tweet sent: " + tweet.text);
}
}
// What to do when we get a tweet.
function triageTweet(tweet) {
// Reject the tweet if:
// 1. it's flagged as a retweet
if (tweet.retweeted) {
return;
}
else {
// Send a tweet to the person that requested the plots
buildReply(tweet);
printPlotLog();
}
}
// Function for listening to twitter streams for mentions.
function startStream() {
twitter.stream('statuses/filter', {
track: config.me
}, function(stream) {
console.log("listening to stream for " + config.me);
stream.on('data', triageTweet);
});
}
// An instance of underscore.
var _ = require('underscore');
// The application itself.
// Use the node-twitter (twitter) node module to get access to twitter.
var twitter = require('twitter')(config.keys);
// Run the application.
startStream();
|
point = function(game,layer){
this.game = game; //objet du jeu
this.layer = layer; //layer vu par le joueur
this.score = 0; //initialisation du score
this.scoreText = null; //initialiser de l'objet texte
points.game.add.group(); //creation du groupe de point
//fonction permettant de placer les points lors d'un nouveau niveau
this.PlacePoint = function(){
//creation des superPoint
superPoint = game.add.group(); //superpoint est une variable globale
superPoint.enableBody = true;
//creation des points
points = game.add.group();
points.enableBody = true;
var i=0;
var j=0;
var GrosPoint;
//placement de grosPoint avec repartition aléatoire sur la map
do {
GrosPoint = Math.floor((Math.random() * 25)); //nombre random entre 0 et 24
} while ((map.getTile(GrosPoint,GrosPoint,layer,true).index!=136)||(map.getTile(GrosPoint,GrosPoint,layer,true).index==1)||(map.getTile(GrosPoint,GrosPoint,layer,true).index==69));
for (i = 0; i < 31; i++) {
for (j = 0; j < 24; j++) {
if ((GrosPoint==i*25)&&(GrosPoint==j*25)) { // Placer le super point
superPoint.create(i*25,j*25,'diamond');
j++;
}
if ((i*25==player.position.x) && (j*25==player.position.y)) { //Pas d'étoiles sur le pacman
j++;
}
if (map.getTile(i,j,layer,true).index == 136) {
var point = points.create(i*25,j*25,'LittlePoint');
this.howLeft += 10;
}
}
}
this.howLeft -= 1;
}
this.reset = function(){
if (this.howLeft == 0) {
this.PlacePoint();
level++;
levelText.text = 'current level: '+ level;
}
}
this.scoring = function(){
this.Point.kill();
this.score += 10;
scoreText.text = 'score: '+ score;
this.howLeft -= 10;
}
}
|
var app = app || {};
app.TrackView = Backbone.View.extend({
tagName: 'li',
template: _.template( $('#track-template').html() ),
events: {
},
initialize: function() {
this.listenTo(this.model, 'change', this.render);
},
render: function() {
this.$el.html( this.template( this.model.toJSON() ) );
return this;
}
}); |
/**
* configure RequireJS
* prefer named modules to long paths, especially for version mgt
* or 3rd party libraries
*/
require.config({
paths: {
'angular': '../bower_components/angular/angular',
'angular-route': '../bower_components/angular-route/angular-route',
'angular-mocks': '../bower_components/angular-mocks/angular-mocks',
'angular-cookie': '../bower_components/angular-cookie/angular-cookie',
'domReady': '../bower_components/requirejs-domready/domReady',
'require': '../bower_components/requirejs/require',
'facebook': './js/facebook',
'dropzone':'../bower_components/dropzone/downloads/dropzone',
/* 'btford.socket-io': '../bower_components/btford.socket-io',*/
'textAngular':'../bower_components/textAngular/src/textAngular',
'ngSanitize':'../bower_components/textAngular/src/textAngular-sanitize',
'textAngularSetup':'../bower_components/textAngular/src/textAngularSetup',
'ngResource': '../bower_components/angular-resource/angular-resource',
'socket':'../bower_components/angular-socket-io/socket',
'socket.io':'../bower_components/socket.io-client/dist/socket.io',
'angular-bootstrap-tpls':'../bower_components/angular-bootstrap/ui-bootstrap-tpls',
'ngTouch':'../bower_components/angular-touch/angular-touch',
'ngAnimate':'../bower_components/angular-animate/angular-animate',
'd3': '../bower_components/d3/d3',
'angular-carousel':'../bower_components/angular-carousel/dist/angular-carousel',
'ngLocale':'./js/angular-locale_uk-ua',
'app.templates':'./templates/maintemplate'
},
/**
* for libs that either do not support AMD out of the box, or
* require some fine tuning to dependency mgt'
*/
shim: {
'angular': {
exports: 'angular'
},
'angular-carousel':{
deps: ['angular']
},
'socket.io': {
exports: 'io',
deps: ['angular']
},
'angular-route': {
deps: ['angular']
},
'ngSanitize': {
deps: ['angular']
},
'ngResource': {
deps: ['angular']
},
'ngTouch':{
deps: ['angular']
},
'ngAnimate':{
deps: ['angular']
},
'socket': {
deps: ['socket.io']
},
'angular-mocks': {
deps: ['angular']
},
'angular-cookie': {
deps: ['angular']
},
'textAngularSetup': {
deps: ['angular']
},
'textAngular': {
deps: ['angular']
},
'angular-bootstrap-tpls':{
deps: ['angular']
},
'facebook' : {
exports: 'FB'
},
'ngLocale':{
deps: ['angular']
},
'app.templates': {
deps: ['angular']
}
},
deps: [
// kick start application... see bootstrap.js
'./bootstrap'
]
});
|
"use strict"
Object.defineProperty(exports, "__esModule", {
value: true,
})
exports.StandaloneSearchBox = undefined
var _defineProperty2 = require("babel-runtime/helpers/defineProperty")
var _defineProperty3 = _interopRequireDefault(_defineProperty2)
var _getPrototypeOf = require("babel-runtime/core-js/object/get-prototype-of")
var _getPrototypeOf2 = _interopRequireDefault(_getPrototypeOf)
var _classCallCheck2 = require("babel-runtime/helpers/classCallCheck")
var _classCallCheck3 = _interopRequireDefault(_classCallCheck2)
var _createClass2 = require("babel-runtime/helpers/createClass")
var _createClass3 = _interopRequireDefault(_createClass2)
var _possibleConstructorReturn2 = require("babel-runtime/helpers/possibleConstructorReturn")
var _possibleConstructorReturn3 = _interopRequireDefault(
_possibleConstructorReturn2
)
var _inherits2 = require("babel-runtime/helpers/inherits")
var _inherits3 = _interopRequireDefault(_inherits2)
var _invariant = require("invariant")
var _invariant2 = _interopRequireDefault(_invariant)
var _react = require("react")
var _react2 = _interopRequireDefault(_react)
var _reactDom = require("react-dom")
var _reactDom2 = _interopRequireDefault(_reactDom)
var _propTypes = require("prop-types")
var _propTypes2 = _interopRequireDefault(_propTypes)
var _MapChildHelper = require("../../utils/MapChildHelper")
var _constants = require("../../constants")
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : { default: obj }
}
/**
* A wrapper around `google.maps.places.SearchBox` without the map
*
* @see https://developers.google.com/maps/documentation/javascript/3.exp/reference#SearchBox
*/
/*
* -----------------------------------------------------------------------------
* This file is auto-generated from the corresponding file at `src/macros/`.
* Please **DO NOT** edit this file directly when creating PRs.
* -----------------------------------------------------------------------------
*/
/* global google */
var SearchBox = (function(_React$PureComponent) {
;(0, _inherits3.default)(SearchBox, _React$PureComponent)
function SearchBox() {
var _ref
var _temp, _this, _ret
;(0, _classCallCheck3.default)(this, SearchBox)
for (
var _len = arguments.length, args = Array(_len), _key = 0;
_key < _len;
_key++
) {
args[_key] = arguments[_key]
}
return (
(_ret = ((_temp = ((_this = (0, _possibleConstructorReturn3.default)(
this,
(_ref =
SearchBox.__proto__ ||
(0, _getPrototypeOf2.default)(SearchBox)).call.apply(
_ref,
[this].concat(args)
)
)),
_this)),
(_this.state = (0, _defineProperty3.default)(
{},
_constants.SEARCH_BOX,
null
)),
_temp)),
(0, _possibleConstructorReturn3.default)(_this, _ret)
)
}
;(0, _createClass3.default)(SearchBox, [
{
key: "componentDidMount",
value: function componentDidMount() {
;(0, _invariant2.default)(
google.maps.places,
'Did you include "libraries=places" in the URL?'
)
var element = _reactDom2.default.findDOMNode(this)
/*
* @see https://developers.google.com/maps/documentation/javascript/3.exp/reference#SearchBox
*/
var searchBox = new google.maps.places.SearchBox(
element.querySelector("input") || element
)
;(0, _MapChildHelper.construct)(
SearchBox.propTypes,
updaterMap,
this.props,
searchBox
)
;(0, _MapChildHelper.componentDidMount)(this, searchBox, eventMap)
this.setState(
(0, _defineProperty3.default)({}, _constants.SEARCH_BOX, searchBox)
)
},
},
{
key: "componentDidUpdate",
value: function componentDidUpdate(prevProps) {
;(0, _MapChildHelper.componentDidUpdate)(
this,
this.state[_constants.SEARCH_BOX],
eventMap,
updaterMap,
prevProps
)
},
},
{
key: "componentWillUnmount",
value: function componentWillUnmount() {
;(0, _MapChildHelper.componentWillUnmount)(this)
},
},
{
key: "render",
value: function render() {
return _react2.default.Children.only(this.props.children)
},
/**
* Returns the bounds to which query predictions are biased.
* @type LatLngBounds
* @public
*/
},
{
key: "getBounds",
value: function getBounds() {
return this.state[_constants.SEARCH_BOX].getBounds()
},
/**
* Returns the query selected by the user, or `null` if no places have been found yet, to be used with `places_changed` event.
* @type Array<PlaceResult>nullplaces_changed
* @public
*/
},
{
key: "getPlaces",
value: function getPlaces() {
return this.state[_constants.SEARCH_BOX].getPlaces()
},
},
])
return SearchBox
})(_react2.default.PureComponent)
SearchBox.displayName = "StandaloneSearchBox"
SearchBox.propTypes = {
/**
* @type LatLngBounds|LatLngBoundsLiteral
*/
defaultBounds: _propTypes2.default.any,
/**
* @type LatLngBounds|LatLngBoundsLiteral
*/
bounds: _propTypes2.default.any,
/**
* function
*/
onPlacesChanged: _propTypes2.default.func,
}
var StandaloneSearchBox = (exports.StandaloneSearchBox = SearchBox)
exports.default = StandaloneSearchBox
var eventMap = {
onPlacesChanged: "places_changed",
}
var updaterMap = {
bounds: function bounds(instance, _bounds) {
instance.setBounds(_bounds)
},
}
|
import UserControler from 'controllers/user.controller'
let router = express.Router()
router.get('/login', UserControler.login)
module.exports = router; |
/**
* Example of a Vantage server that hooks into
* an Express server.
*
* To run, ensure you have devDependencies
* with `npm install`.
*/
/**
* Module dependencies.
*/
var Vantage = require('./../../lib/index')
, express = require('express')
, app = express()
;
/**
* Variable declarations.
*/
var vantage
, delimiter = 'svr:5000~$'
, port = 5000
, server
;
/**
* Firing up a Vantage server.
*/
server = Vantage()
.delimiter(delimiter)
.listen(app, port)
.show();
|
// We only need to import the modules necessary for initial render
import App from 'containers/App';
import { getAsyncInjectors } from 'utils/asyncInjectors';
const errorLoading = err => {
console.error('Dynamic page loading failed', err);
};
const loadModule = cb => componentModule => {
cb(null, componentModule.default);
};
export default (store) => {
const { injectReducer, injectSagas } = getAsyncInjectors(store);
return {
component : App,
childRoutes: [
{
path: '/',
name: 'home',
getComponent (nextState, cb) {
System.import('containers/HomePage')
.then(loadModule(cb))
.catch(errorLoading);
}
},
{
path: '/search',
name: 'search',
getComponent (nextState, cb) {
const importModules = Promise.all([
System.import('containers/SearchPage/reducer'),
System.import('containers/SearchPage/sagas'),
System.import('containers/SearchPage')
]);
const renderRoute = loadModule(cb);
importModules.then(([reducer, sagas, component]) => {
injectReducer('search', reducer.default);
injectSagas(sagas.default);
renderRoute(component);
});
importModules.catch(errorLoading);
}
},
{
path: '*',
name: 'notFound',
getComponent (nextState, cb) {
System.import('containers/NotFoundPage')
.then(loadModule(cb))
.catch(errorLoading);
}
}
]
};
};
|
// Opt in to strict mode of JavaScript, [ref](http://is.gd/3Bg9QR)
// Use this statement, you can stay away from several frequent mistakes
'use strict';
var $ = require("jquery");
var MultiEvent = function (fn, time, opt) {
var self = this;
this.fn = fn;
this.time = time;
opt = opt || {};
this._triggerEvent = function (e) {
e.preventDefault();
var elem = this,
type = e.type;
function funcwrap() {
return self.fn.call(elem, e);
}
clearTimeout(self.timer);
self.timer = setTimeout(function () {
funcwrap.call(elem);
}, self.time);
};
this._stopperEvent = function (e) {
clearTimeout(self.timer);
};
return this
};
MultiEvent.prototype.trigger = function (elems, type) {
elems = $(elems);
elems.on(type, this._triggerEvent);
return this;
};
MultiEvent.prototype.stopper = function (elems, type) {
elems = $(elems);
elems.on(type, this._stopperEvent);
return this;
};
MultiEvent.prototype.removeTrigger = function (elems, type) {
elems = $(elems);
elems.off(type, this._triggerEvent);
return this;
};
MultiEvent.prototype.removeStopper = function (elems, type) {
elems = $(elems);
elems.off(type, this._stopperEvent)
return this;
}
module.exports = function(fn, time, opt){
return new MultiEvent(fn, time, opt);
} |
(function() {
'use strict';
angular.module('calendar.events', []);
})(); |
/**
* window.c.userFollows component
* Shows all user follows cards
*
* Example of use:
* view: () => {
* ...
* m.component(c.userFollows, {user: user})
* ...
* }
*/
import m from 'mithril';
import postgrest from 'mithril-postgrest';
import _ from 'underscore';
import h from '../h';
import models from '../models';
import UserFollowCard from '../c/user-follow-card';
import loadMoreBtn from '../c/load-more-btn';
const userFollows = {
controller(args) {
models.userFollow.pageSize(9);
const userFriendVM = postgrest.filtersVM({user_id: 'eq'}),
user = args.user,
hash = m.prop(window.location.hash),
followsListVM = postgrest.paginationVM(models.userFollow,
'created_at.desc', {
'Prefer': 'count=exact'
});
userFriendVM.user_id(user.user_id);
if (!followsListVM.collection().length) {
followsListVM.firstPage(userFriendVM.parameters());
}
return {
followsListVM: followsListVM
};
},
view(ctrl, args) {
const followsVM = ctrl.followsListVM;
return m('.w-section.bg-gray.before-footer.section', [
m('.w-container', [
m('.w-row', [
_.map(followsVM.collection(), (friend) => {
return m.component(UserFollowCard,
{friend: _.extend({},{following: true, friend_id: friend.follow_id}, friend.source)});
}),
]),
m('.w-section.section.bg-gray', [
m('.w-container', [
m('.w-row.u-marginbottom-60', [
m('.w-col.w-col-5', [
m('.u-marginright-20')
]), m.component(loadMoreBtn, {collection: followsVM}),
m('.w-col.w-col-5')
])
])
])
])
])
;
}
};
export default userFollows;
|
var webapp = angular.module('webapp');
webapp.controller('AuthController', ['$scope', '$http', '$window', '$cookies', 'AuthService',
function ($scope, $http, $window, $cookies, AuthService) {
(function init() {
})();
$scope.user = {};
$scope.login = function() {
var username = this.username;
var password = this.password;
AuthService.requestAccessToken(username, password, function (accessToken) {
if (accessToken) {
AuthService.setCredentials(username, accessToken);
$window.location.href = "";
} else {
}
});
};
$scope.logout = function() {
console.log("LOGOUT");
AuthService.clearCredentials();
$window.location.href = $window.location.href + 'auth/login.html';
}
}
]);
|
import { default as FivetwelveRgbParam } from 'fivetwelve/lib/param/RgbParam.js'
/**
*
*/
export default class RgbParam extends FivetwelveRgbParam {
/**
* Create a new RGB-Param.
*
* @param {Array<number>} channels - The assigned DMX-channels within the
* device (1-based channel number passed as [r,g,b]).
*
* @param {RgbParam.RGB|RgbParam.CMY} format - The color-format used by the
* device.
*/
constructor(channels, format = RgbParam.RGB) {
super(channels, format)
}
setValue(device, color) {
this.color.set(color)
const colorData = this.format === RgbParam.RGB
? this.color.rgb
: this.color.cmy
for (let i = 0; i < 3; i++) {
device.setChannelValue(this.channels[i], colorData[i])
}
}
getValue(device) {
// make sure color is initialized
if (!this.color) {
this.color = new Color()
}
let channelValues = [
device.getChannelValue(this.channels[0]),
device.getChannelValue(this.channels[1]),
device.getChannelValue(this.channels[2])
]
if (this.format === RgbParam.RGB) {
this.color.rgb = channelValues
} else if (this.format === RgbParam.CMY) {
this.color.cmy = channelValues
}
return this.color
}
}
|
import React from 'react';
import DatePicker from 'react-bootstrap-date-picker';
export default class EnhanceDatePicker extends React.Component {
render() {
const dayLabels = ['CN', 'T2', 'T3', 'T4', 'T5', 'T6', 'T7'];
const monthLabels = [
'Tháng 1 /', 'Tháng 2 /', 'Tháng 3 /', 'Tháng 4 /', 'Tháng 5 /', 'Tháng 6 /',
'Tháng 7 /', 'Tháng 8 /', 'Tháng 9 /', 'Tháng 10 /', 'Tháng 11 /', 'Tháng 12 /',
];
return (
<DatePicker className="form-control input-medium"
value={this.props.value}
showClearButton={false}
dateFormat="DD/MM/YYYY"
dayLabels={dayLabels}
monthLabels={monthLabels}
weekStartsOnMonday={true}
onChange={this.props.onChange}/>
);
}
}
|
/*
Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'showblocks', 'no', {
toolbar: 'Vis blokker'
} );
|
var dns = require('dns');
/** old dns.lookup function - used to restore original function **/
var lookup;
/**
* A module that monkeypatch dns.lookup for graceful
* falling to another IP stack version.
* @module dns-graceful-stack-switch
*/
/**
* Monkeypatch function
* @param {Number} defaultVersion - version of IP stack, that will be used first
* @param {Boolean} remove - if true, removes monkeypatch
*/
module.exports = function (defaultVersion, remove) {
if (remove && dns.lookup._wrapped) {
dns.lookup = lookup;
lookup = undefined;
return;
}
/* check, that we won't wrap already wrapped function */
if (dns.lookup._wrapped)
return;
/** default version of IP stack to lookup first */
defaultVersion = defaultVersion || process.env.NODE_DNS_GRACEFUL_STACK_SWITCH_DEFAULT || 4;
/** store original function, in case removing */
lookup = dns.lookup;
/**
* Patched function wrapper
* @param domain {String} - domain to lookup for
* @param family {Number} - version of IP stack to use first
* @param callback {Function} - callback function (signature: function(err, address, family))
*/
dns.lookup = function (domain, family, callback) {
if (arguments.length === 2) {
callback = family;
family = 0;
} else if (!family) {
family = 0;
} else {
family = +family;
if (family !== 4 && family !== 6) {
throw new Error('invalid argument: `family` must be 4 or 6');
}
}
var requestedFamily = family || defaultVersion;
lookup(domain, requestedFamily, function (err, address, family) {
if (!err) {
return callback(err, address, family);
}
/* store error for full output, in case next lookup fails */
var prevError = "IPv" + requestedFamily + " " + err.message + "; ";
/* choose other family, that was not used */
var otherFamily = requestedFamily === 4 ? 6 : 4;
lookup(domain, otherFamily, function (err, address, family) {
if (err) {
/* modify error to store previous lookup error */
err.message = prevError + "IPv" + otherFamily + " " + err.message;
}
callback(err, address, family);
});
});
};
/** _wrapped - boolean flag to recognize patched functions between different versions of modules **/
dns.lookup._wrapped = true;
};
|
/**
* @fileoverview Rule to flag unnecessary double negation in Boolean contexts
* @author Brandon Mills
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const astUtils = require("./utils/ast-utils");
const eslintUtils = require("eslint-utils");
const precedence = astUtils.getPrecedence;
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
module.exports = {
meta: {
type: "suggestion",
docs: {
description: "disallow unnecessary boolean casts",
category: "Possible Errors",
recommended: true,
url: "https://eslint.org/docs/rules/no-extra-boolean-cast"
},
schema: [{
type: "object",
properties: {
enforceForLogicalOperands: {
type: "boolean",
default: false
}
},
additionalProperties: false
}],
fixable: "code",
messages: {
unexpectedCall: "Redundant Boolean call.",
unexpectedNegation: "Redundant double negation."
}
},
create(context) {
const sourceCode = context.getSourceCode();
// Node types which have a test which will coerce values to booleans.
const BOOLEAN_NODE_TYPES = [
"IfStatement",
"DoWhileStatement",
"WhileStatement",
"ConditionalExpression",
"ForStatement"
];
/**
* Check if a node is a Boolean function or constructor.
* @param {ASTNode} node the node
* @returns {boolean} If the node is Boolean function or constructor
*/
function isBooleanFunctionOrConstructorCall(node) {
// Boolean(<bool>) and new Boolean(<bool>)
return (node.type === "CallExpression" || node.type === "NewExpression") &&
node.callee.type === "Identifier" &&
node.callee.name === "Boolean";
}
/**
* Checks whether the node is a logical expression and that the option is enabled
* @param {ASTNode} node the node
* @returns {boolean} if the node is a logical expression and option is enabled
*/
function isLogicalContext(node) {
return node.type === "LogicalExpression" &&
(node.operator === "||" || node.operator === "&&") &&
(context.options.length && context.options[0].enforceForLogicalOperands === true);
}
/**
* Check if a node is in a context where its value would be coerced to a boolean at runtime.
* @param {ASTNode} node The node
* @returns {boolean} If it is in a boolean context
*/
function isInBooleanContext(node) {
return (
(isBooleanFunctionOrConstructorCall(node.parent) &&
node === node.parent.arguments[0]) ||
(BOOLEAN_NODE_TYPES.indexOf(node.parent.type) !== -1 &&
node === node.parent.test) ||
// !<bool>
(node.parent.type === "UnaryExpression" &&
node.parent.operator === "!")
);
}
/**
* Checks whether the node is a context that should report an error
* Acts recursively if it is in a logical context
* @param {ASTNode} node the node
* @returns {boolean} If the node is in one of the flagged contexts
*/
function isInFlaggedContext(node) {
return isInBooleanContext(node) ||
(isLogicalContext(node.parent) &&
// For nested logical statements
isInFlaggedContext(node.parent)
);
}
/**
* Check if a node has comments inside.
* @param {ASTNode} node The node to check.
* @returns {boolean} `true` if it has comments inside.
*/
function hasCommentsInside(node) {
return Boolean(sourceCode.getCommentsInside(node).length);
}
/**
* Checks if the given node is wrapped in grouping parentheses. Parentheses for constructs such as if() don't count.
* @param {ASTNode} node The node to check.
* @returns {boolean} `true` if the node is parenthesized.
* @private
*/
function isParenthesized(node) {
return eslintUtils.isParenthesized(1, node, sourceCode);
}
/**
* Determines whether the given node needs to be parenthesized when replacing the previous node.
* It assumes that `previousNode` is the node to be reported by this rule, so it has a limited list
* of possible parent node types. By the same assumption, the node's role in a particular parent is already known.
* For example, if the parent is `ConditionalExpression`, `previousNode` must be its `test` child.
* @param {ASTNode} previousNode Previous node.
* @param {ASTNode} node The node to check.
* @returns {boolean} `true` if the node needs to be parenthesized.
*/
function needsParens(previousNode, node) {
if (isParenthesized(previousNode)) {
// parentheses around the previous node will stay, so there is no need for an additional pair
return false;
}
// parent of the previous node will become parent of the replacement node
const parent = previousNode.parent;
switch (parent.type) {
case "CallExpression":
case "NewExpression":
return node.type === "SequenceExpression";
case "IfStatement":
case "DoWhileStatement":
case "WhileStatement":
case "ForStatement":
return false;
case "ConditionalExpression":
return precedence(node) <= precedence(parent);
case "UnaryExpression":
return precedence(node) < precedence(parent);
case "LogicalExpression":
if (previousNode === parent.left) {
return precedence(node) < precedence(parent);
}
return precedence(node) <= precedence(parent);
/* istanbul ignore next */
default:
throw new Error(`Unexpected parent type: ${parent.type}`);
}
}
return {
UnaryExpression(node) {
const parent = node.parent;
// Exit early if it's guaranteed not to match
if (node.operator !== "!" ||
parent.type !== "UnaryExpression" ||
parent.operator !== "!") {
return;
}
if (isInFlaggedContext(parent)) {
context.report({
node: parent,
messageId: "unexpectedNegation",
fix(fixer) {
if (hasCommentsInside(parent)) {
return null;
}
if (needsParens(parent, node.argument)) {
return fixer.replaceText(parent, `(${sourceCode.getText(node.argument)})`);
}
let prefix = "";
const tokenBefore = sourceCode.getTokenBefore(parent);
const firstReplacementToken = sourceCode.getFirstToken(node.argument);
if (
tokenBefore &&
tokenBefore.range[1] === parent.range[0] &&
!astUtils.canTokensBeAdjacent(tokenBefore, firstReplacementToken)
) {
prefix = " ";
}
return fixer.replaceText(parent, prefix + sourceCode.getText(node.argument));
}
});
}
},
CallExpression(node) {
if (node.callee.type !== "Identifier" || node.callee.name !== "Boolean") {
return;
}
if (isInFlaggedContext(node)) {
context.report({
node,
messageId: "unexpectedCall",
fix(fixer) {
const parent = node.parent;
if (node.arguments.length === 0) {
if (parent.type === "UnaryExpression" && parent.operator === "!") {
/*
* !Boolean() -> true
*/
if (hasCommentsInside(parent)) {
return null;
}
const replacement = "true";
let prefix = "";
const tokenBefore = sourceCode.getTokenBefore(parent);
if (
tokenBefore &&
tokenBefore.range[1] === parent.range[0] &&
!astUtils.canTokensBeAdjacent(tokenBefore, replacement)
) {
prefix = " ";
}
return fixer.replaceText(parent, prefix + replacement);
}
/*
* Boolean() -> false
*/
if (hasCommentsInside(node)) {
return null;
}
return fixer.replaceText(node, "false");
}
if (node.arguments.length === 1) {
const argument = node.arguments[0];
if (argument.type === "SpreadElement" || hasCommentsInside(node)) {
return null;
}
/*
* Boolean(expression) -> expression
*/
if (needsParens(node, argument)) {
return fixer.replaceText(node, `(${sourceCode.getText(argument)})`);
}
return fixer.replaceText(node, sourceCode.getText(argument));
}
// two or more arguments
return null;
}
});
}
}
};
}
};
|
/**
* @since 2019-09-24 02:14
* @author vivaxy
*/
import * as ET from '../enums/event-types.js';
import * as GS from '../enums/game-state.js';
import * as TS from '../enums/tetromino-state.js';
import * as DIRECTIONS from '../enums/directions.js';
import StateMachine from '../class/state-machine.js';
import Grid from '../class/grid.js';
import Score from '../class/score.js';
import Tetromino from '../class/tetromino.js';
import Speed from '../class/speed.js';
const state = new StateMachine({
default: GS.NEW_GAME,
start: [GS.NEW_GAME, GS.PLAYING],
eliminate: [GS.PLAYING, GS.ELIMINATING],
continue: [GS.ELIMINATING, GS.PLAYING],
pause: [GS.PLAYING, GS.PAUSED],
resume: [GS.PAUSED, GS.PLAYING],
over: [GS.PLAYING, GS.GAME_OVER],
reset: [GS.GAME_OVER, GS.NEW_GAME],
});
function init(ee) {
const grid = new Grid();
const score = new Score();
const tetromino = new Tetromino();
const speed = new Speed();
state.onChange(handleStateChange);
tetromino.onStateChange(handleTetrominoStateChange);
ee.on(ET.TICK, handleTick);
ee.on(ET.RENDER, handleRender);
ee.on(ET.TETROMINO_LEFT, handleTetrominoLeft);
ee.on(ET.TETROMINO_RIGHT, handleTetrominoRight);
ee.on(ET.TETROMINO_ROTATE, handleTetrominoRotate);
ee.on(ET.TETROMINO_DOWN, handleTetrominoDown);
function handleStateChange({ to }) {
switch (true) {
case to === GS.GAME_OVER:
alert('Game Over!');
state.reset();
break;
case to === GS.NEW_GAME:
grid.reset();
score.reset();
speed.reset();
setTimeout(function() {
state.start();
}, 1000);
break;
}
}
function handleTetrominoStateChange({ to }) {
switch (to) {
case TS.MOVING:
tetromino.createTetromino(grid);
grid.addTetromino(tetromino);
break;
case TS.SETTLED:
if (speed.toOriginalSpeed) {
speed.toOriginalSpeed();
}
speed.add();
if (tetromino.isOnTopBorder()) {
state.over();
} else {
score.add(1);
}
break;
case TS.DROPPING:
speed.toMaxSpeed();
break;
}
}
function handleEliminating() {
if (speed.isNextFrame()) {
const { scoreToAdd } = grid.eliminateRows();
score.add(scoreToAdd);
state.continue();
return;
}
const eliminatingRows = grid.getEliminatingRows();
if (eliminatingRows.length) {
eliminatingRows.forEach(function(rowIndex) {
grid.get()[rowIndex].forEach(function(item) {
if (item._color) {
item.color = item._color;
delete item._color;
} else {
item._color = item.color;
item.color = '#fff';
}
});
});
}
}
function handlePlaying() {
switch (tetromino.getState()) {
case TS.DROPPING:
case TS.MOVING:
if (speed.isNextFrame()) {
speed.clearTick();
if (tetromino.canMove(grid, DIRECTIONS.DOWN)) {
grid.removeTetromino(tetromino);
tetromino.move(DIRECTIONS.DOWN);
grid.addTetromino(tetromino);
} else {
tetromino.settle();
grid.computeEliminatingRows();
if (grid.getEliminatingRows().length) {
state.eliminate();
}
}
}
break;
case TS.SETTLED:
tetromino.create();
break;
}
}
function handleTick() {
if (state.getState() === GS.ELIMINATING) {
handleEliminating();
} else if (GS.PLAYING) {
handlePlaying();
}
}
function handleRender(et, { ctx, canvas }) {
grid.render(ctx, canvas);
score.render(ctx, canvas, speed.get());
}
function handleTetrominoDown() {
if (tetromino.getState() === TS.MOVING) {
tetromino.drop();
}
}
function handleTetrominoLeft() {
if (tetromino.canMove(grid, DIRECTIONS.LEFT)) {
grid.removeTetromino(tetromino);
tetromino.move(DIRECTIONS.LEFT);
grid.addTetromino(tetromino);
}
}
function handleTetrominoRight() {
if (tetromino.canMove(grid, DIRECTIONS.RIGHT)) {
grid.removeTetromino(tetromino);
tetromino.move(DIRECTIONS.RIGHT);
grid.addTetromino(tetromino);
}
}
function handleTetrominoRotate() {
grid.removeTetromino(tetromino);
tetromino.rotate(grid);
grid.addTetromino(tetromino);
}
}
export default {
init,
start() {
state.start();
},
};
|
// onionoo api baseurl
exports.BASE_URL = 'https://onionoo.torproject.org/';
// request timeout in milliseconds
exports.REQUEST_TIMEOUT = 10000;
// 1000 * 60 * 60 * 24
exports.DAY = 86400000; |
export default {
html: `
<div>
Hello World
<input />
<input />
</div>
<div>
Sapper App
<input />
<input />
</div>
`,
ssrHtml: `
<div>
Hello World
<input value="Hello"/>
<input value="World"/>
</div>
<div>
Sapper App
<input value="Sapper"/>
<input value="App"/>
</div>
`,
async test({ assert, target, window }) {
const [input1, input2, input3, input4] = target.querySelectorAll('input');
input1.value = 'Awesome';
await input1.dispatchEvent(new window.Event('input'));
assert.htmlEqual(
target.innerHTML,
`
<div>
Awesome World
<input />
<input />
</div>
<div>
Sapper App
<input />
<input />
</div>
`
);
input2.value = 'Svelte';
await input2.dispatchEvent(new window.Event('input'));
assert.htmlEqual(
target.innerHTML,
`
<div>
Awesome Svelte
<input />
<input />
</div>
<div>
Sapper App
<input />
<input />
</div>
`
);
input3.value = 'Foo';
await input3.dispatchEvent(new window.Event('input'));
assert.htmlEqual(
target.innerHTML,
`
<div>
Awesome Svelte
<input />
<input />
</div>
<div>
Foo App
<input />
<input />
</div>
`
);
input4.value = 'Bar';
await input4.dispatchEvent(new window.Event('input'));
assert.htmlEqual(
target.innerHTML,
`
<div>
Awesome Svelte
<input />
<input />
</div>
<div>
Foo Bar
<input />
<input />
</div>
`
);
}
};
|
'use strict';
// Use applicaion configuration module to register a new module
ApplicationConfiguration.registerModule('treeMenus');
|
export { default } from 'ember-models-table/components/models-table/themes/ember-paper/data-group-by-select';
|
import React, { PropTypes } from 'react';
import { Split, Wrapper, Icon } from 'bits';
import { connect } from 'utils';
import { Follow } from 'react-twitter-widgets';
import FacebookProvider, { Like } from 'react-facebook';
import styles from './styles.css';
import GoogleMap from 'google-map-react';
import hackbatMarker from './img/hackbatmarker.png';
const cn = require('classnames/bind').bind(styles);
const MARKER_SIZE = 60;
const hackbatPosition = {
position: 'absolute',
width: MARKER_SIZE,
height: MARKER_SIZE,
left: -MARKER_SIZE / 2,
top: -MARKER_SIZE / 2,
};
const Footer = ({
services: {
ui: { toggleModal },
},
}) => (
<div className={cn('Footer')}>
<Wrapper className={cn('Footer__box')}>
<div className={cn('Footer__items')}>
<div className={cn('Footer__item')}>
<Icon className={cn('Footer__item-icon')} name="map-marker" />
<div className={cn('Footer__item-content')}>
Sienkiewicza 1/1, lok. 200 <br />
Białystok, Poland
</div>
</div>
<div className={cn('Footer__item')}>
<Icon className={cn('Footer__item-icon')} name="envelope" />
<div className={cn('Footer__item-content')}>
Call us at <a href="callto:+4791908036"><b>+47 919 08 036</b></a><br />
Email at <a href="mailto:hello@hacklag.org"><b>hello@hacklag.org</b></a>
</div>
</div>
<div className={cn('Footer__item')}>
<Icon className={cn('Footer__item-icon')} name="github" />
<div className={cn('Footer__item-content')}>
Code with us at <br />
<a href="https://github.com/hacklag">github.com/<b>hacklag</b></a>
</div>
</div>
<div className={cn('Footer__item')}>
<Icon className={cn('Footer__item-icon')} name="slack" />
<div className={cn('Footer__item-content')}>
<a onClick={() => toggleModal('CommunityMemberSignup')}>
Join <b>HACKLAG</b>
</a>
<br /> community on Slack
</div>
</div>
</div>
<Split>
<div className={cn('Footer__copyrights')}>
© 2016 by Hacklag. All rights reserved.
</div>
<div className={cn('Footer__social')}>
<FacebookProvider appID="1108028089293935">
<Like href="https://www.facebook.com/HacklagHQ" action="like" size="small" showFaces={false} share={false} layout="button" colorScheme="light" />
</FacebookProvider>
<Follow
username="HacklagHQ"
options={{ showCount: false }}
/>
</div>
</Split>
</Wrapper>
<div className={cn('Footer__map')}>
<GoogleMap
bootstrapURLKeys={{
key: GOOGLE_MAPS_API_KEY,
}}
defaultCenter={{ lat: 53.1302151, lng: 23.1595374 }}
defaultZoom={17}
zoomControl={false}
>
<div
lat={53.1312518}
lng={23.1603008}
>
<img
style={hackbatPosition}
role={'presentation'}
src={hackbatMarker}
/>
</div>
</GoogleMap>
</div>
</div>
);
Footer.propTypes = {
services: PropTypes.object.isRequired,
};
export default connect(Footer);
|
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
/**
* MenuItem Schema
*/
var MenuItemSchema = new Schema({
name: {
type: String,
default: '',
required: 'Please fill MenuItem name',
trim: true
},
description: {
type: String,
default: '',
trim: true
},
course: {
id: {
type: Schema.Types.ObjectId,
ref: 'Course'
},
name: String
},
price: {
type: Number,
default: 0
},
enabled: {
type: Boolean,
default: true
},
created: {
type: Date,
default: Date.now
},
user: {
type: Schema.ObjectId,
ref: 'User'
}
});
mongoose.model('MenuItem', MenuItemSchema);
|
var map = L.map('map').setView([0, 0], 3);
var geoJsonLayer;
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
function onEachFeature(feature, layer) {
// does this feature have a property named popupContent?
var popupContent = "";
var properties = feature.properties;
if (properties) {
for (var prop in feature.properties) {
popupContent += "<b>" + prop + "</b> : " + properties[prop] + "<br>";
}
}
layer.bindPopup(popupContent)
}
function viewGeoJson(element) {
var url = document.getElementById("geojson-endpoint").value;
console.log(url);
$.get(url,
function(geoJson) {
if (geoJson) {
var geoJsonFeatures = JSON.parse(geoJson);
if (geoJsonLayer) {
map.removeLayer(geoJsonLayer)
}
geoJsonLayer = L.geoJson(geoJsonFeatures,{ onEachFeature: onEachFeature }).addTo(map);
map.fitBounds(geoJsonLayer.getBounds());
}
}
);
return false;
}
$('#url-input').submit(function () {
viewGeoJson(this);
return false;
});
L.control.locate({
position: 'topleft', // set the location of the control
layer: new L.LayerGroup(), // use your own layer for the location marker
drawCircle: true, // controls whether a circle is drawn that shows the uncertainty about the location
follow: false, // follow the user's location
setView: true, // automatically sets the map view to the user's location, enabled if `follow` is true
keepCurrentZoomLevel: false, // keep the current map zoom level when displaying the user's location. (if `false`, use maxZoom)
stopFollowingOnDrag: false, // stop following when the map is dragged if `follow` is true (deprecated, see below)
remainActive: false, // if true locate control remains active on click even if the user's location is in view.
markerClass: L.circleMarker, // L.circleMarker or L.marker
circleStyle: {}, // change the style of the circle around the user's location
markerStyle: {},
followCircleStyle: {}, // set difference for the style of the circle around the user's location while following
followMarkerStyle: {},
icon: 'fa fa-map-marker', // class for icon, fa-location-arrow or fa-map-marker
iconLoading: 'fa fa-spinner fa-spin', // class for loading icon
circlePadding: [0, 0], // padding around accuracy circle, value is passed to setBounds
metric: true, // use metric or imperial units
onLocationError: function(err) {alert(err.message)}, // define an error callback function
onLocationOutsideMapBounds: function(context) { // called when outside map boundaries
alert(context.options.strings.outsideMapBoundsMsg);
},
showPopup: true, // display a popup when the user click on the inner marker
strings: {
title: "Show me where I am", // title of the locate control
metersUnit: "meters", // string for metric units
feetUnit: "feet", // string for imperial units
popup: "You are within {distance} {unit} from this point", // text to appear if user clicks on circle
outsideMapBoundsMsg: "You seem located outside the boundaries of the map" // default message for onLocationOutsideMapBounds
},
locateOptions: {} // define location options e.g enableHighAccuracy: true or maxZoom: 10
}).addTo(map); |
define(function () {
return {
// all clickable scroll elements
$elements: null,
// bool page is stroll
active: false,
SETTINGS: {
// divide distance by this value to calculate time scroll
time: 2,
// min time scroll
minTime: 400,
// max time scroll
maxTime: 1200,
// run autoScroll when hash in URL is begin with this string
prefixAutoScroll: 'scroll-'
},
/**
* Start function
*
* @param {Object} data
* replace values in SETTINGS
*/
start(data) {
$.extend( self.SETTINGS, data );
this.autoScroll();
this.refresh();
},
/**
* Automatic scroll page to element ID
* when user visit page with hash
* begin with SETTINGS.prefixAutoScroll
*/
autoScroll() {
var
self = Main.scrollTo,
hash = window.location.hash;
// Check if page must trigger autoScroll
if( hash.startsWith( "#" + self.SETTINGS.prefixAutoScroll ) ) {
// Fix annoying jumping when user disturb scroll
Main.function.offUserScroll();
// Remove hash from url
var
cleanUrl = location.protocol + "//" + location.host + location.pathname;
window.history.replaceState({}, document.title, cleanUrl);
// Create target ID from hash
var
targetID = hash.substring(hash.indexOf('-')+1, hash.lenght);
/* test-code */
Main.debugConsole.add("scrollTo.js auto trigger function autoScroll().", 'auto');
/* end-test-code */
// Fix annoying jumping when page is still not ready
window.setTimeout(()=>{
self.on(targetID);
}, 900);
}
},
/**
* Scroll function
* @param {Event interface} event
* @param {jQuery object; String ID} target
* @param {Number} time
*/
scroll(event, target = false, time = false) {
var
self = Main.scrollTo,
targetID, $target;
// Check event and remove default action
if (event) {
event.preventDefault();
}
// Check target element
if (!target)
{
targetID = "#" + $(this).attr("data-scroll");
$target = $(targetID);
}
else
{
if (target instanceof jQuery)
{
$target = target;
targetID = "#" + $target.attr("ID");
}
else
{
targetID = "#" + target;
$target = $(targetID);
}
}
// Check if scroll animation is free to use
if (!self.active) {
// Check $target exist
if ($target.length) {
// Block other scroll triggers
self.active = true;
// Grab target top position
var
targetPositionTop = $target.offset().top;
// Calculate scrollTime
var scrollTime = Math.round(Math.abs(targetPositionTop - Main.SCROLL.top) / self.SETTINGS.time);
if (scrollTime < self.SETTINGS.minTime)
{
scrollTime = self.SETTINGS.minTime;
}
else if (scrollTime > self.SETTINGS.maxTime)
{
scrollTime = self.SETTINGS.maxTime;
}
/* test-code */
Main.debugConsole.add(`Scroll to element <strong>${targetID}</strong> with speed <strong>${scrollTime}ms</strong>`);
/* end-test-code */
// Animate scroll
Main.function.offUserScroll();
Main.ELEMENTS.$page.animate({
scrollTop: targetPositionTop,
}, scrollTime, () => {
Main.function.onUserScroll();
self.active = false;
});
return true;
}
else {
/* test-code */
Main.debugConsole.add(`scrollTo.js function scroll(). Element <strong>${targetID}</strong> don't exist`, 'error');
/* end-test-code */
return false;
}
}
/* test-code */
else
{
Main.debugConsole.add(`scrollTo.js function scroll(). Other scroll animation isn't end.`, 'warning');
}
/* end-test-code */
},
/**
* Scroll to element
* @param {jQuery object; String ID} element
* @param {Number} time
* @return {Bool}
*/
on(element, time = false) {
return this.scroll(false, element, time);
},
/**
* Refresh binded $elements
*/
refresh() {
var self = Main.scrollTo;
if (self.$elements) {
self.$elements.off("click", self.scroll);
}
self.$elements = $("[data-scroll]");
self.$elements.on("click", self.scroll);
},
};
}); |
const app = require('koa')()
const handlebars = require('koa-handlebars')
const Router = require('koa-router')
const config = require('./config')
const debug = require('debug')('jsdoc')
const providers = require('./lib/providers')
const controllers = require('./controllers')
app.env = config.env
app.name = config.name
app.keys = config.keys
// Register middleware generators
app.use(require('koa-static')(config.static.directory))
app.use(handlebars(config.handlebars))
// Configure the router
const router = new Router()
// Param validator
router.param('provider', function *(provider, next) {
var matches = providers.match(provider)
if (matches) return yield next
this.status = 400
yield this.render('error', { message: 'Unsupported provider: ' + provider })
})
// Register routes
router.get('/', controllers.main)
router.get('/about', controllers.about)
router.get('/search', controllers.search)
router.get('/:provider/:organization/:repository', controllers.documentation)
router.get('/:provider/:organization/:repository/v/:branch', controllers.documentation)
app.use(router.middleware())
// Final handler
app.use(function *() {
this.status = 404
yield this.render('error', {})
})
// Exports the server
if (require.main !== module) return module.exports = app
// Or listen if it's the main module
app.listen(+config.port || 3000, function () {
console.log('Server running on port ' + config.port || 3000)
})
|
var gulp = require('gulp'),
connect = require('gulp-connect'),
markdown = require('gulp-markdown'),
jade = require('gulp-jade'),
rimraf = require('gulp-rimraf');
gulp.task('clean', function() {
return gulp.src('index.html')
.pipe(rimraf());
})
gulp.task('markdown', function() {
return gulp.src('site/content.md')
.pipe(markdown())
.pipe(gulp.dest('site/'));
});
gulp.task('jade', ['clean'], function() {
return gulp.src('site/index.jade')
.pipe(jade({ pretty: true }))
.pipe(gulp.dest('.'))
.pipe(connect.reload());
});
gulp.task('connect', function() {
connect.server({
port: 3333,
livereload: true
});
});
gulp.task('site', ['connect'], function() {
gulp.watch('site/**/*.md', ['markdown', 'jade']);
gulp.watch('site/**/*.jade', ['markdown', 'jade']);
gulp.watch('site/**/*.css').on('change', connect.reload);
gulp.watch('site/**/*.js').on('change', connect.reload);
}); |
import { connect } from 'react-redux'
import { Layout as LayoutView } from './layout.view'
const mapStateToProps = (state) => ({})
const mapDispatchToProps = (dispatch) => ({})
const makeContainer = (component) => {
return connect(
mapStateToProps,
mapDispatchToProps
)(component)
}
export const Layout = makeContainer(LayoutView)
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
$(document).ready(function () {
var html_table = $('#example').html();
var linkExcel = $('#ToExcel').attr('href');
var linkPdf = $('#ToPdf').attr('href');
var linkPrint = $('#ToPrint').attr('href');
$('#ToExcel').attr('href', linkExcel + '/' + html_table);
$('#ToPdf').attr('href', linkPdf + '/' + html_table);
$('#ToPrint').attr('href', linkPrint + '/' + html_table);
// alert(linkExcel+ '/' + encodeURI(html_table));
// alert(linkPdf+ '/' + encodeURI(html_table));
// alert(linkPrint+ '/' + encodeURI(html_table));
// alert(html_table);
});
|
var fieldTests = require('./commonFieldTestUtils.js');
var RelationshipModelTestConfig = require('../../../modelTestConfig/RelationshipModelTestConfig');
module.exports = {
before: fieldTests.before,
after: fieldTests.after,
'Relationship field should show correctly in the initial modal': function (browser) {
browser.adminUIApp.openList({section: 'fields', list: 'Relationship'});
browser.adminUIListScreen.createFirstItem();
browser.adminUIApp.waitForInitialFormScreen();
browser.adminUIInitialFormScreen.assertFieldUIVisible({
modelTestConfig: RelationshipModelTestConfig,
fields: [{name: 'name'}, {name: 'fieldA'}]
});
browser.adminUIInitialFormScreen.cancel();
browser.adminUIApp.waitForListScreen();
},
'Relationship field can be filled via the initial modal': function(browser) {
browser.adminUIApp.openList({section: 'fields', list: 'Relationship'});
browser.adminUIListScreen.createFirstItem();
browser.adminUIApp.waitForInitialFormScreen();
browser.adminUIInitialFormScreen.fillFieldInputs({
modelTestConfig: RelationshipModelTestConfig,
fields: {
'name': {value: 'Relationship Field Test 1'},
'fieldA': {option: 'option1'},
}
});
browser.adminUIInitialFormScreen.assertFieldInputs({
modelTestConfig: RelationshipModelTestConfig,
fields: {
'name': {value: 'Relationship Field Test 1'},
'fieldA': {value: 'e2e member'},
}
});
browser.adminUIInitialFormScreen.save();
browser.adminUIApp.waitForItemScreen();
browser.adminUIItemScreen.assertFieldInputs({
modelTestConfig: RelationshipModelTestConfig,
fields: {
'name': {value: 'Relationship Field Test 1'},
'fieldA': {value: 'e2e member'},
}
})
},
'Relationship field should show correctly in the edit form': function(browser) {
browser.adminUIItemScreen.assertFieldUIVisible({
modelTestConfig: RelationshipModelTestConfig,
fields: [{name: 'fieldB'}]
});
},
'Relationship field can be filled via the edit form': function(browser) {
browser.adminUIItemScreen.fillFieldInputs({
modelTestConfig: RelationshipModelTestConfig,
fields: {
'fieldB': {option: 'option2'}
}
});
browser.adminUIItemScreen.save();
browser.adminUIApp.waitForItemScreen();
browser.adminUIItemScreen.assertFlashMessage('Your changes have been saved successfully');
browser.adminUIItemScreen.assertFieldInputs({
modelTestConfig: RelationshipModelTestConfig,
fields: {
'name': {value: 'Relationship Field Test 1'},
'fieldA': {value: 'e2e member'},
'fieldB': {value: 'e2e user'}
}
})
},
};
|
// All material copyright ESRI, All Rights Reserved, unless otherwise specified.
// See https://js.arcgis.com/4.16/esri/copyright.txt for details.
//>>built
define({root:{widgetLabel:"Zoom",zoomIn:"Zoom in",zoomOut:"Zoom out"},ar:1,bs:1,ca:1,cs:1,da:1,de:1,el:1,es:1,et:1,fi:1,fr:1,he:1,hr:1,hu:1,id:1,it:1,ja:1,ko:1,lv:1,lt:1,nl:1,nb:1,pl:1,"pt-br":1,"pt-pt":1,ro:1,ru:1,sl:1,sr:1,sv:1,th:1,tr:1,uk:1,vi:1,"zh-cn":1,"zh-hk":1,"zh-tw":1}); |
pageflow.EditChapterView = Backbone.Marionette.Layout.extend({
template: 'templates/edit_chapter',
className: 'edit_chapter',
mixins: [pageflow.failureIndicatingView],
regions: {
formContainer: '.form_container'
},
events: {
'click a.back': 'goBack',
'click a.destroy': 'destroy',
},
onRender: function() {
this.formContainer.show(new pageflow.TextInputView({
model: this.model,
propertyName: 'title'
}));
},
destroy: function() {
if (confirm("Kapitel einschließlich ALLER enthaltener Seiten wirklich löschen?\n\nDieser Schritt kann nicht rückgängig gemacht werden.")) {
this.model.destroy();
this.goBack();
}
},
goBack: function() {
editor.navigate('/', {trigger: true});
}
}); |
var pacbot = require('../../lib/pacbot');
var fss = require('../../lib/fss');
var contains = function (test, supstr, substr) {
test.ok(supstr.indexOf(substr) > -1);
};
exports.canCreateAppCacheFile = function (test) {
pacbot.config({
appdir: 'spec/cases/cache/content',
pubdir: 'spec/out/cache',
config: 'spec/cases/cache/pacbot.js',
timestamp: false
});
pacbot.build(function () {
var content = fss.readFile('spec/out/cache/cache.appcache');
var solution = fss.readFile('spec/out/cache/solution.appcache');
test.equal(content, solution);
test.done();
});
};
exports.canHonorRootAndTimestamp = function (test) {
pacbot.config({
appdir: 'spec/cases/cache/content',
pubdir: 'spec/out/cache',
config: 'spec/cases/cache/pacbot.js',
root: 'foo/bar/',
timestamp: true
});
pacbot.build(function () {
var content = fss.readFile('spec/out/cache/cache.appcache');
contains(test, content, 'CACHE MANIFEST\n# Time: ');
contains(test, content, '\nfoo/bar/img/1.png\n');
contains(test, content, '\nfoo/bar/img/a/2.png\n');
contains(test, content, '\nfoo/bar/html/cached.html\n');
contains(test, content, '\nfoo/bar/css/1.css?v=');
contains(test, content, '\nfoo/bar/js/a.js?v=');
test.done();
});
};
|
var express = require('express'),
nunjucks = require('nunjucks'),
fs = require('fs'),
util = require('util'),
_ = require('underscore'),
app = express(),
port = process.env.PORT || 1168,
config = JSON.parse(fs.readFileSync('config.json')),
a2 = require('./a2/lib/core');
var env = new nunjucks.Environment(new nunjucks.FileSystemLoader('views'));
env.express(app);
// Configure the express app
app.use(express.bodyParser());
app.use(express.static('public'));
app.use(express.logger('dev'));
// Bootstrap a2 for this specific app, using the config settings
// intended for a2 (so the rest of our config object can be
// project-specific if desired)
config.a2.extensions = [ __dirname + '/a2' ];
a2.bootstrap(app, config.a2);
app.get('/', function(req, res) {
res.render('index.html');
});
var areas = {
body: {
},
sidebar: {
}
};
app.get('/admin/area/:id', function(req, res) {
var id = req.params.id;
if (!_.has(areas, id))
{
res.status = 404;
res.send(404);
return;
}
res.send(JSON.stringify(areas[id]));
});
app.put('/admin/area/:id', function(req, res) {
var id = req.params.id;
if (!_.has(areas, id)) {
res.status = 404;
res.send(404);
}
// Data arrives as JSON, Express turns that into a nice req.body object
console.log(req.body);
a2.validateArea(req.body, {}, function(err, area) {
if (err) {
console.log('error in post');
res.send(500, err);
return;
}
areas[id] = area;
res.send(JSON.stringify(areas[id]));
});
});
app.listen(port, function() {
util.log('Listening on port ' + port);
});
|
process.env.NODE_TLS_REJECT_UNAUTHORIZED = 0;
// Necessary for this setup, because we don't have a CA signed certificate
var https = require('https'),
colors = require('colors'),
q = require('q'),
settings = require('../settings').resourceServer,
errorCodes = require('../shared/error-codes'),
operations = require('./operations'),
app = require('../shared/app')(__dirname);
// Create and start the https server using the Express app
https.createServer(settings.options, app).listen(settings.port);
/*
Routes
*/
// Default route
app.get('/', function (req, res) {
res.send(errorCodes.respondWith('invalidRequest', 'This route is a dead endpoint..'));
});
//
// Data routes
app.post(settings.routes.protected_data, function (req, res) {
// Start the access token validation
var request = app.get('urlencodedParser')(req.body);
if (!request.redirect_uri) { console.log('The client did not provide a redirect URI, stopping the process'); res.end(); return; }
else operations.validateAccessToken(request, res, app);
});
app.post(settings.routes.token_validation_response, function (req, res) {
app.get('requestOutOfBuffer')(req.params.requestToken).then(function (request) {
// Receive the token validation and respond to the requester
var response = app.get('urlencodedParser')(req.body);
operations.respond(request, response, res, app);
});
});
//
// Files buffer
var fileBuffer = {
buffer: [],
add: function (file) {
this.buffer.push(file);
},
remove: function (index) {
this.buffer.splice(index, 1);
}
};
app.set('addFileToBuffer', function (file) {
fileBuffer.add(file);
});
app.set('removeFileFromBuffer', function (index) {
fileBuffer.remove(index);
});
app.get(settings.routes.get_file, function (req, res) {
/*
If access is granted, the file can be GET through
the combination of the file URI and a created file token
*/
operations.sendFile(fileBuffer.buffer, req.params.fileToken, res, app);
});
console.log('\n----------------------'.grey);
console.log('Resource server online'.magenta);
console.log('----------------------\n'.grey); |
/* @flow */
/* eslint-disable import/no-commonjs */
if (process.env.NODE_ENV === 'production') {
module.exports = require('./configureStore.prod').default;
} else {
module.exports = require('./configureStore.dev').default;
}
|
'use strict';
let AbstractGroupModel = require('./AbstractGroupModel');
const DETAILS = {
id: 'HEL002',
manufacturer: 'Philips',
name: 'Hue Entity Pendant',
type: 'Luminaire',
};
/**
* Group model: HEL002
*/
class HEL002 extends AbstractGroupModel {
/**
* Constructor
*/
constructor() {
super(DETAILS);
}
}
module.exports = HEL002;
|
// Copyright (c) 2011-2015, HL7, Inc & The MITRE Corporation
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of HL7 nor the names of its contributors may be used to
// endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
import ApplicationSerializer from 'ember-fhir-adapter/serializers/application';
var Identifier = ApplicationSerializer.extend({
attrs: {
type : {embedded: 'always'},
system : {embedded: 'always'},
period : {embedded: 'always'},
assigner : {embedded: 'always'}
}
});
export default Identifier;
|
(function () {
'use strict';
var utils = require('./utils'),
postscribe = require('postscribe'),
mapUrl = 'https://api.map.baidu.com/api?v=2.0&ak=KUuesdf9xuLFZGGPj7j0F3jBT9QYz2vx&s=1';
function init() {
var map = new BMap.Map("map"),
circleOverlay = utils.overlayInit(),
point = {
lng: 116.301456,
lat: 40.050388
},
circleOverlayInstance = (function () {
var childDiv = [],
child,
childText,
offset = { // 当offset是一个值(即覆盖物为正方形),可以设置offset = 14; 否则,x为宽度的一半,y为高度的一半
x: 14,
y: 14
},
id = 12;
child = document.createElement('div');
child.className = 'circle-child';
childText = document.createTextNode('circle');
child.appendChild(childText);
childDiv.push(child);
return new circleOverlay(map, offset, 'main', {
id: id,
lng: point.lng,
lat: point.lat
}, point, {
childDiv: childDiv
});
})(),
tap = function () {
alert('you taped me?');
};
map.centerAndZoom(point, 10);
map.addOverlay(circleOverlayInstance);
circleOverlayInstance.tap(tap);
}
module.exports = {
init: function () {
postscribe('#mapScript', '<script src="'+mapUrl+'"><\/script>', {
done: function () {
init();
}
});
}
};
})(); |
$(function(){
$(document).ready(function(){
$.ajax({
url :'/chairsDetails',
type :'get'
}).done(function(data){
console.log("data found:",data);
$('#product-list-').html("");
$('#product-type').html("");
data[0].forEach(function(entry,index){
//console.log("data in entry 0 point ",entry);
$('#product-type').append(
"<li> "+
"<div class='li-box hvr-grow-shadow'>"+
" <a href='#' class='fliterCurtains' data_product_Type_id="+ entry.product_type_id +" data_product_Sub_Type_id="+ entry._id+" data_route="+ entry.subTypeName +">"+ entry.subTypeName +"</a>"+
"</div>"+
"</li>"
)
})
data[1].forEach(function(entry,index){
//console.log("val img src",entry);
$('#product-list').append(
"<li class='col-md-3'>" +
"<div class='product-block hvr-grow-shadow' data_product_id="+ entry._id +" data_product_Sub_Type_id="+entry.product_Sub_Type_id+ " data_product_Type_id="+entry.product_Type_id+" >" +
"<a href=/productsales?product_id="+entry._id+" data_product_Sub_Type_id="+entry.product_Sub_Type_id+ " data_product_Type_id="+entry.product_Type_id+">" +
"<img src=/static/images/productImages/"+ entry.productmgPath +" class='img-responsive center-block' data_product_Sub_Type_id="+entry.product_Sub_Type_id+ " data_product_Type_id="+entry.product_Type_id+">" +
"<div class=''> <span class='prudct-name'>"+ entry.productName +" </span> </div>" +
"<span class='product-price'> Rs " + entry.productPrice + "</span>" +
"<span> </span>" +
"</a>" +
"</div>" +
"</li>"
)
});
}).fail(function(err){
console.log("errr",err)
$('#product-list').html("<li><h1>Record Not found</h1></li>");
})
})
$(document.body).on('click','.middle-section .product-type .product-type-ul li a',function(){
//$(this).addClass('active');
var data_sub_type = $(this).attr('data_product_Sub_Type_id');
var dataRoute = $(this).attr("data_route");
//console.log("data route",dataRoute);
//console.log("data route", dataRoute);
$.ajax({
url :'/productSearch',
type:'get',
data:{
search_id : data_sub_type,
product_name : dataRoute
}
}).done(function(data){
//console.log("data has been pass", data);
$('#product-list').html("");
data.forEach(function(entry,index){
//console.log("val img src",entry);
$('#product-list').append(
"<li class='col-md-3'>" +
"<div class='product-block hvr-grow-shadow' data_product_id="+ entry._id +" data_product_Sub_Type_id="+entry.product_Sub_Type_id+ " data_product_Type_id="+entry.product_Type_id+" >" +
"<a href=/productsales?product_id="+entry._id+" data_product_Sub_Type_id="+entry.product_Sub_Type_id+ " data_product_Type_id="+entry.product_Type_id+">" +
"<img src=/static/images/productImages/"+ entry.productmgPath +" class='img-responsive center-block' data_product_Sub_Type_id="+entry.product_Sub_Type_id+ " data_product_Type_id="+entry.product_Type_id+">" +
"<div class=''> <span class='prudct-name'>"+ entry.productName +" </span> </div>" +
"<span class='product-price'> Rs " + entry.productPrice + "</span>" +
"<span> </span>" +
"</a>" +
"</div>" +
"</li>"
)
})
}).fail(function(err){
console.log("errr in the get call a tag ",err);
$('#product-list').html("<li><h1>product Not Avaliable </h1></li>");
})
})
$(document).on('click','.middle-section .product-type .product-type-ul li .li-box',function(){
//console.log("child of the class",$(this).children());
$('.middle-section .product-type .product-type-ul li .li-box').removeClass('active');
$(this).addClass('active');
})
}) |
/**
* @enum EFriendFlags
*/
module.exports = {
"None": 0,
"Blocked": 1,
"FriendshipRequested": 2,
"Immediate": 4,
"ClanMember": 8,
"OnGameServer": 16,
"RequestingFriendship": 128,
"RequestingInfo": 256,
"Ignored": 512,
"IgnoredFriend": 1024,
"Suggested": 2048,
"ChatMember": 4096,
"FlagAll": 65535,
// Value-to-name mapping for convenience
"0": "None",
"1": "Blocked",
"2": "FriendshipRequested",
"4": "Immediate",
"8": "ClanMember",
"16": "OnGameServer",
"128": "RequestingFriendship",
"256": "RequestingInfo",
"512": "Ignored",
"1024": "IgnoredFriend",
"2048": "Suggested",
"4096": "ChatMember",
"65535": "FlagAll",
};
|
import GitUtilities from "./GitUtilities";
import FileSystemUtilities from "./FileSystemUtilities";
import path from "path";
import logger from "./logger";
export default class Repository {
constructor() {
if (!GitUtilities.isInitialized()) {
logger.info("Initializing Git repository.");
GitUtilities.init();
}
this.rootPath = path.resolve(GitUtilities.getTopLevelDirectory());
this.lernaJsonLocation = path.join(this.rootPath, "lerna.json");
this.packageJsonLocation = path.join(this.rootPath, "package.json");
this.packagesLocation = path.join(this.rootPath, "packages");
// Legacy
this.versionLocation = path.join(this.rootPath, "VERSION");
if (FileSystemUtilities.existsSync(this.lernaJsonLocation)) {
this.lernaJson = JSON.parse(FileSystemUtilities.readFileSync(this.lernaJsonLocation));
}
if (FileSystemUtilities.existsSync(this.packageJsonLocation)) {
this.packageJson = JSON.parse(FileSystemUtilities.readFileSync(this.packageJsonLocation));
}
}
get lernaVersion() {
return this.lernaJson && this.lernaJson.lerna;
}
get version() {
return this.lernaJson && this.lernaJson.version;
}
get publishConfig() {
return this.lernaJson && this.lernaJson.publishConfig || {};
}
get bootstrapConfig() {
return this.lernaJson && this.lernaJson.bootstrapConfig || {};
}
isIndependent() {
return this.version === "independent";
}
}
|
const lumpit = require('@lump/it')
const task = require('@lump/task')
const remove = require('@lump/remove')
const copy = require('@lump/copy')
lumpit(async () => {
await task({
text: 'Build',
exec: async () => {
await copy({
src: 'files/*',
dest: 'new/ubication'
})
await remove('files')
}
})
})
|
var TimeLine = (function(timeline) {
timeline.Router.RoutesManager = Backbone.Router.extend({
initialize: function(args) {
Backbone.history.start( { pushState: true, root: '/' } );
//this.collection = args.collection;
//console.log("this.collection", this.collection);
},
routes: {
"hello" : "hello",
"login" : "login",
"profil" : "profil",
"create" : "create_timeline",
":id" : "timeline",
"edit" : "edit",
"*path" : "root"
},
root: function() {
console.log("root *");
$("body").removeClass().addClass("page-home");
mainView.profilView.hide();
mainView.tlView.hide();
mainView.headerView.render();
mainView.homeView.render( { show: true } );
/*
var that = this;
this.collection.all().fetch({
success: function(result) {
mainView.render(result);
}
});
*/
},
hello: function() {
$("h1").html("Hello World !!!");
},
login: function () {
console.log("root login");
},
profil: function () {
console.log("root profil");
$("body").removeClass().addClass("page-profil");
mainView.homeView.hide();
mainView.tlView.hide();
mainView.headerView.render();
mainView.profilView.render( { show: true } );
},
create_timeline : function () {
console.log("root create_timeline");
// A définir...
},
timeline: function ( id ) {
console.log("root timeline", id);
$("body").removeClass().addClass("page-timeline");
//mainView.currentpage.setCurrentpage( "timeline" );
mainView.tlView.getTimeline( id );
mainView.homeView.hide();
mainView.profilView.hide();
},
edit: function () {
$("h1").html("Edit");
}
});
return timeline;
}(TimeLine)); |
import {dbSetup, sequelizer} from './index';
import Sequelize from 'sequelize';
import {Article} from './article';
export const User = dbSetup.define(
'user',
{
firstName: { type: sequelizer.STRING },
lastName: { type: sequelizer.STRING },
username: { type: sequelizer.STRING, allowNull: false, unique: true },
password: { type: sequelizer.STRING, allowNull: false },
},
{
timestamps: false
}
);
User.hasMany(Article, {as: 'Articles'})
|
let Promise = require('bluebird');
let plugged = require('../client');
const langfile = require('../../langfile');
const config = require('../load_config');
let utils = require('../utils');
let soundCloudApi = require('../apiConnectors/soundCloud');
module.exports = {
name: 'SoundCloudGuard',
enabled: true,
check: (booth,now)=> {
return new Promise((resolve, reject) => {
if(now.media.format === 2){
if (config.soundcloudGuard.block) reject({
type: 'soundcloudguard',
preskip: langfile.soundcloudGuard.skip,
afterskip: utils.replace(langfile.soundcloudGuard.block, {username: plugged.getUserByID(booth.dj).username}),
doLockskip: config.soundcloudGuard.lockskip,
blacklist: false
});
else if (config.soundcloudGuard.enabled) {
soundCloudApi.check(now.media).spread((skip, reasons) => {
if (skip) reject({
type: 'soundcloudguard',
preskip: langfile.soundcloudGuard.skip,
afterskip: utils.replace(reasons.skip, {username: plugged.getUserByID(booth.dj).username}),
doLockskip: config.soundcloudGuard.lockskip,
blacklist: true,
blReason: reasons.blacklist
});
else resolve();
}).catch(resolve);
} else resolve();
} else resolve();
});
}
}; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.