text
stringlengths 7
3.69M
|
|---|
export default class Powerup {
constructor(context, img){
this.img = img;
this.x = 0;
this.y = 0;
this.ctxWidth = context.canvas.width;
this.ctxHeight = context.canvas.height;
this.generateRandomStartPosition();
}
generateRandomStartPosition(){
this.x = Math.floor(Math.random() * this.ctxWidth);
this.y = Math.floor(Math.random() * this.ctxHeight);
}
draw(context){
context.beginPath();
context.translate(this.x, this.y);
context.drawImage(this.img, -20, -20, 40,40);
context.resetTransform();
}
checkClicked(touch_x, touch_y){
let vector_x = touch_x - this.x;
let vector_y = touch_y - this.y;
let vector_length = Math.sqrt((vector_x*vector_x) + (vector_y* vector_y));
//let radius_length = Math.sqrt((this.radius*this.radius) + (this.radius*this.radius));
if(vector_length < 20){
return true;
}else{
return false;
}
}
}
|
/**
* Created by KJain on 8/10/2016.
*/
var express = require('express');
var router = express.Router();
var mongo = require('../mongo');
// GET Signin page.
router.get('/', function(req, res, next) {
res.render('signin', {badCredentials: false});
});
//Check if user has enter correct username and password
function authenticateUser(username, password, callback){
var col = mongo.collection('users');
var query = { $or:
[
{username: username},
{email: username}
],
password: password
};
col.findOne(query, function(err, user){
callback(err, user);
});
}
router.post('/', function(req, res){
//Extracting username and password obtained from html form
var username = req.body.username;
var password = req.body.password;
authenticateUser(username, password, function(err, user){
if (user) {
req.session.username = user.username;
res.redirect('/documents');
}
else {
res.render('signin', {badCredentials: true});
}
});
});
module.exports = router;
|
require('rootpath')();
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var config = require('config.json');
var mongoose = require('mongoose');
mongoose.connect(config.connectionString);
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// Routes
app.use('/api/people', require('controllers/people.controller'));
app.use('/api/customers', require('controllers/customers.controller'));
app.use('/api/tasks', require('controllers/tasks.controller'));
app.use('/', require('controllers/home.controller'));
app.use('/app', express.static('app'));
var server = app.listen(3000, function(){
console.log('Server listening at port 3000');
});
|
import React, { Component } from 'react';
import styled from 'styled-components';
import ObserverGraph from './components/observerGraph/ObserverGraph';
import ObserverGraphSettings from './components/observerGraphSettings/ObserverGraphSettings';
import './App.css';
import Data from './Data';
const Wrapper = styled.div`
width: 100%;
height: 100%;
`;
const HeaderWrapper = styled.div`
height: 50px;
padding: 20px;
display: flex;
justify-content: center;
align-items: center;
`;
const Title = styled.h1`
font-size: 1.5em;
color: #222222;
`;
const Main = styled.div`
width: 100%;
height: calc(100% - 90px);
display: flex;
justify-content: space-evenly;
align-items: center;
@media(max-width: 768px) {
flex-direction: column;
}
`;
const initialData = Data.data;
const initialGains = Data.gains;
const initialOffsets = Data.offsets;
const initialMarkers = Data.markers;
const initialLineWidth = Data.lineWidth;
const initialColors = Data.colors;
class App extends Component {
constructor(props) {
super(props);
this.state = {
data: initialData,
gains: initialGains,
offsets: initialOffsets,
colors: initialColors,
lineWidth: initialLineWidth,
markers: initialMarkers,
isAddingRemark: false,
};
}
generateObserverGraphOptions = () => {
const { gains, offsets, colors, lineWidth } = this.state;
return {
lineWidth,
colors,
gains,
offsets,
};
}
getParsedValue = (value, type, fallback) => {
switch (type) {
case 'int':
return isNaN(value) ? fallback : parseInt(value, 10)
case 'float':
return isNaN(value) ? fallback : parseFloat(value)
default:
return value;
}
}
generateStateByProperty = (property, value, lineIndex, prevState, type, fallback) => {
return {
...prevState,
[property]: [
...prevState[property].slice(0, lineIndex),
this.getParsedValue(value, type, fallback),
...prevState[property].slice(lineIndex + 1)]
}
}
generateNextState = (property, value, lineIndex, prevState) => {
switch (property) {
case 'colors':
return this.generateStateByProperty(property, value, lineIndex, prevState, 'string');
case 'lineWidth':
return {
...prevState,
lineWidth: this.getParsedValue(value, 'int', initialLineWidth),
};
case 'gains':
return this.generateStateByProperty(property, value, lineIndex, prevState, 'float', 0);
case 'offsets':
return this.generateStateByProperty(property, value, lineIndex, prevState, 'int', 0);
case 'markers':
return {
...prevState,
markers: [...prevState.markers, this.getParsedValue(value, 'float')],
};
default:
return prevState;
}
}
handleFieldChanged = (type, value, lineIndex) => {
this.setState((prevState) => this.generateNextState(type, value, lineIndex, prevState));
}
handleAddingRemark = () => {
this.setState((prevState) => ({
...prevState,
isAddingRemark: true,
}));
}
render() {
const { data, gains, offsets, colors, lineWidth, markers, isAddingRemark } = this.state;
return (
<Wrapper>
<HeaderWrapper>
<Title>ObserverGraph App</Title>
</HeaderWrapper>
<Main>
<ObserverGraph
data={data}
options={this.generateObserverGraphOptions()}
markers={markers}
isAddingRemark={isAddingRemark}
onFieldChanged={(type, value, lineIndex) => this.handleFieldChanged(type, value, lineIndex)}
/>
<ObserverGraphSettings
gains={gains}
offsets={offsets}
colors={colors}
lineWidth={lineWidth}
onFieldChanged={(type, value, lineIndex) => this.handleFieldChanged(type, value, lineIndex)}
onAddRemark={this.handleAddingRemark}
onSelectMarker={(row, column) => { console.log(row, column) }}
/>
</Main>
</Wrapper>
);
}
}
export default App;
|
import React, { Fragment } from 'react';
import { Alert } from 'react-bootstrap';
import 'bootstrap/dist/css/bootstrap.min.css';
const Error = ({ error }) => {
return (
<Fragment>
<Alert variant='danger'>
{error}
</Alert>
</Fragment>
);
}
export default Error;
|
import React, { Component } from 'react';
import Loadwrap from './loadstyled'
import load from '../../assets/images/timg.gif'
class loading extends Component {
render() {
return (
<Loadwrap>
<div>
<img src={load} alt=""/>
<span>
请稍等...
</span>
</div>
</Loadwrap>
);
}
}
export default loading;
|
$(document).ready(function () {
$('.i-check').iCheck({
checkboxClass: 'icheckbox_quacol',
radioClass: 'icheckbox_quacol',
//increaseArea: '20%' // optional
});
$('.endoexpert-popup select').change(function () {
if ($(this).val() ==='0') {$(this).addClass('-empty')} else {$(this).removeClass('-empty')}
});
});
|
chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
console.log(message);
sendResponse({
content : "content.js sendResponse"
});
});
|
import axios from 'axios'
import {setUser, setUserLoginError, setUserToken} from "../reducer/userReducer";
import {url} from "../helpers/utils";
import {setProfile} from "../reducer/profileReducer";
import {setError, setErrorAction} from "../reducer/errorReducer";
export const loginUser = (password, username) => {
return async (dispatch) => {
// GRAB TOKEN
const token = await axios.post("http://127.0.0.1:8000/token/", {password, username}).then((res) => {
dispatch(setUserToken(res.data))
return res
}).catch((e) => {
dispatch(setErrorAction(e))
})
if (token) {
// GRAB USER ID
const user = await axios.get("http://127.0.0.1:8000/user/react-info/", {
headers: {
"Authorization": 'JWT ' + token.data.access,
}
}).then((res) => {
dispatch(setUser(res.data))
return res.data
}).catch((e) => dispatch(setErrorAction(e)))
// GRAB USER INFORMATION
await axios.get(`http://127.0.0.1:8000/user/${user.id}`, {
headers: {
Authorization: 'JWT ' + token.data.access,
'Content-Type': 'application/json'
}
}).then((res) => {
dispatch(setProfile(res.data))
}).catch((e) => {
dispatch(setErrorAction(e))
})
}
}
}
|
const fs = require('fs')
const path = require('path')
const util = require('util')
const glob = require('glob')
const PixelDiff = require('pixel-diff')
const IMAGE_FORMAT = 'png'
const SCREENSHOT_EXTENSION = 'png'
const makeDir = util.promisify(fs.mkdir)
const globDir = util.promisify(glob)
function resolveScreenshotPath(dir, snapshotName) {
return path.resolve(dir, snapshotName)
}
async function ensureScreenshotsDir(dir) {
try {
await makeDir(path.resolve(dir))
} catch (error) {
if (error.code === 'EEXIST') {
return
}
throw error
}
}
async function getScreenshots(dir) {
return await globDir(`*.${SCREENSHOT_EXTENSION}`, { cwd: path.resolve(dir) })
}
async function compareSnapshot(
snapshotName,
{ referenceDir, testDir, outputDir, threshold }
) {
console.log(`Comparing screenshot ${snapshotName}`)
const diff = new PixelDiff({
imageAPath: resolveScreenshotPath(referenceDir, snapshotName),
imageBPath: resolveScreenshotPath(testDir, snapshotName),
imageOutputPath: resolveScreenshotPath(
outputDir,
`${snapshotName}.${IMAGE_FORMAT}`
),
imageOutputLimit: PixelDiff.OUTPUT_SIMILAR,
thresholdType: PixelDiff.THRESHOLD_PERCENT,
threshold: threshold,
})
return diff.runWithPromise()
}
async function command({ referenceDir, testDir, outputDir, max, threshold }) {
await ensureScreenshotsDir(outputDir)
const snapshotsA = new Set(await getScreenshots(referenceDir))
const snapshotsB = new Set(await getScreenshots(testDir))
const snapshots = new Set(
[...snapshotsA].filter((snapshot) => snapshotsB.has(snapshot)).slice(0, max)
)
if (snapshots.size === 0) {
console.log(`Nothing to compare ¯\\_(ツ)_/¯`)
return
}
console.log('Starting tests...\n')
for (let snapshotName of snapshots) {
try {
await compareSnapshot(snapshotName, {
referenceDir,
testDir,
outputDir,
threshold,
})
} catch (error) {
// Errors will be printed by PixelDiff instance
}
}
}
module.exports = command
|
import styled from 'styled-components'
import Login from '../src/components/Login'
import Topbar from '../src/components/Topbar'
const StyledWrapper = styled.div`
`
const HomePage = (props) => {
return (
<StyledWrapper>
<Topbar></Topbar>
<Login></Login>
</StyledWrapper>
)
}
export default HomePage;
|
import occurenceLevelEnum from 'motifs-js/_motifs/occurence/_enums/level/occurence.level.enum.js'
import get from './get/get.js'
import namesProp from './_props/names/names.prop.js'
export default {
id: 'youtube-video',
names: namesProp,
occurences: [{
level: occurenceLevelEnum.FOLDER,
folderMatch: /\/_data\/youtube-videos\/([\w|\-]*)/,
transform: ([ path, id ]) => ({ path, id })
}],
get
}
|
const Convention = require("./convention")
const DataMapper = require("./dataMapper")
const { checker } = require('@herbsjs/suma')
const dependency = { convention: Convention }
module.exports = class Repository {
constructor(options) {
const di = Object.assign({}, dependency, options.injection)
this.convention = di.convention
this.collectionName = options.collection
this.collectionQualifiedName = `${this.collectionName}`
this.entity = options.entity
this.entityIDs = options.ids
this.mongodb = options.mongodb
this.dataMapper = new DataMapper(this.entity, this.entityIDs)
}
runner() {
return this.mongodb
}
/**
*
* Create a new entity
*
* @param {type} entityInstance Entity instance
*
* @return {type} Current entity
*/
async insert(entityInstance) {
const payload = this.dataMapper.collectionFieldsWithValue(entityInstance)
let { ops } = await this.runner().collection(this.collectionQualifiedName).insertOne(payload)
return this.dataMapper.toEntity(ops[0])
}
/**
*
* Create multiple entities
*
* @param {type} arrayEntityInstance Array of Entity instance
*
* @return {type} Current entities
*/
async insertMany(arrayEntityInstance) {
const payload = arrayEntityInstance.map((entityInstance) => this.dataMapper.collectionFieldsWithValue(entityInstance))
let { ops } = await this.runner().collection(this.collectionQualifiedName).insertMany(payload)
return ops.map((op) => this.dataMapper.toEntity(op))
}
/**
*
* Update Many entities
*
* @param {type} options object with some properties as filter definition and update definition
*
* @return {type} True when success
*/
async updateMany(options = { filter, update }) {
const ret = await this
.runner()
.collection(this.collectionQualifiedName)
.updateMany(
options.filter,
options.update,
{ upsert: true }
)
return ret.modifiedCount === 1
}
/**
*
* Update entity
*
* @param {type} entityInstance Entity instance
*
* @return {type} True when success
*/
async update(entityInstance) {
const payload = this.dataMapper.collectionFieldsWithValue(entityInstance)
delete payload._id
const ret = await this.runner().collection(this.collectionQualifiedName)
.updateOne({ _id: String(entityInstance._id)},
{ $set : payload },
{ upsert: true })
return ret.modifiedCount === 1
}
/**
*
* Find entity by ID
*
* @param {type} id Entity _id
*
* @return {type} return entity when found
*/
async findByID(id) {
let result = await this.runner().collection(this.collectionQualifiedName).findOne({ _id: String(id)})
return this.dataMapper.toEntity(result)
}
/**
*
* Find entities
*
* @param {type} object.limit Limit items to list
* @param {type} object.filter Filter items to list
* @param {type} object.skip Rows that will be skipped from the resultset
* @param {type} object.search Where query term
* @param {type} object.orderBy Order by query
*
* @return {type} List of entities
*/
async find(options = { filter, project, skip, limit, sort }) {
options.sort = options.sort || null
options.limit = options.limit || 0
options.skip = options.skip || 0
options.project = options.project || null
options.filter = options.filter || null
let query = this.runner().collection(this.collectionQualifiedName)
if (options.limit > 0) query = query.limit(options.limit)
if (options.skip > 0) query = query.skip(options.skip)
const queryOptions = {}
if (options.sort) {
if (!options.sort || typeof options.sort === "object" && !Array.isArray(options.sort) && checker.isEmpty(options.sort)) throw "sort is invalid"
queryOptions.sort({ [options.sort]: 1 })
}
if (options.filter) {
const conditionTermCollectionField = this.dataMapper.toCollectionFieldName(Object.keys(options.filter)[0])
const conditionTerm = Object.keys(options.filter)[0]
if (!conditionTerm || conditionTerm === "0") throw "condition term is invalid"
const conditionValue = Array.isArray(options.filter[conditionTerm])
? options.filter[conditionTerm]
: [options.filter[conditionTerm]]
if (!options.filter[conditionTerm] ||
(typeof options.filter[conditionTerm] === "object" && !Array.isArray(options.filter[conditionTerm])) ||
(Array.isArray(options.filter[conditionTerm]) && !options.filter[conditionTerm].length))
throw "condition value is invalid"
query = query.find({ [conditionTermCollectionField] : conditionValue[0] }, queryOptions)
}
else
{
query = query.find({ }, queryOptions)
}
const cursor = query
const entities = []
if ((await cursor.count()) === 0) {
return null
}
const ret = await cursor.toArray()
for (const row of ret) {
if (row === undefined) continue
entities.push(this.dataMapper.toEntity(row))
}
return entities
}
/**
*
* Delete entity by ID
*
* @param {type} id Entity _id
*
* @return {type} True when success
*/
async deleteByID(id) {
const ret = await this.runner().collection(this.collectionQualifiedName)
.deleteOne({ _id: String(id)})
return ret.result.ok === 1
}
/**
*
* Delete entity by ID
*
* @param {type} object.filter Filter items to list
*
* @return {type} True when success
*/
async deleteMany(options = { filter, project, skip, limit, sort }) {
options.filter = options.filter || null
let query = this.runner().collection(this.collectionQualifiedName)
if (options.filter) {
const conditionTermCollectionField = this.dataMapper.toCollectionFieldName(Object.keys(options.filter)[0]).toString()
const conditionTerm = Object.keys(options.filter)[0]
if (!conditionTerm || conditionTerm === "0") throw "condition term is invalid"
const conditionValue = Array.isArray(options.filter[conditionTerm])
? options.filter[conditionTerm]
: [options.filter[conditionTerm]]
if (!options.filter[conditionTerm] ||
(typeof options.filter[conditionTerm] === "object" && !Array.isArray(options.filter[conditionTerm])) ||
(Array.isArray(options.filter[conditionTerm]) && !options.filter[conditionTerm].length))
throw "condition value is invalid"
query = query.deleteMany({ [conditionTermCollectionField] : conditionValue[0] })
}
else
{
query = query.deleteMany({})
}
let ret = await query
return ret.result.ok === 1
}
}
|
import registerComponent from '../../core/component_registrator';
import NumberBoxMask from './number_box.mask'; // STYLE numberBox
registerComponent('dxNumberBox', NumberBoxMask);
export default NumberBoxMask;
|
import { createAction, handleActions } from 'redux-actions';
const initialState = {
};
export const wizardStart = createAction('WIZARD_START');
export const wizardReceiveGist = createAction('WIZARD_RECEIVE_GIST');
export default handleActions({
[wizardReceiveGist]: (state, { payload }) => ({
...state,
...payload,
}),
}, initialState);
|
import React, { Component } from 'react';
import Main from './Main';
import Heading from './Heading';
import CurrentForecast from './CurrentForecast';
import ComingDaysList from './ComingDaysList';
import './App.css';
class App extends Component {
constructor(props) {
super(props);
this.state = {
futureCast: [0, 1, 2],
}
}
render() {
return (
<div className='weather'>
<Heading title='Current Conditions' />
<Main>
<CurrentForecast/>
</Main>
<Heading title='Later this Week' />
<Main>
<ComingDaysList futureCast={this.state.futureCast} />
</Main>
</div>
);
}
}
export default App;
|
const fs = require("fs");
console.log("start");
let globalStart = Date.now();
function call(callback) {
fs.readFile(__filename, callback);
}
for (let i = 0; i < 20; i++) {
call(() => {
let start = Date.now();
while (Date.now() - start < 100) {}
console.log(`done:${i}`);
});
}
setTimeout(() => {
console.log("timeout:" + `${Date.now() - globalStart}ms`);
setImmediate(() => {
console.log("immediate:" + `${Date.now() - globalStart}ms`);
});
}, 10);
|
/*$Rev: 1154 $ Revision number must be in the first line of the file in exactly this format*/
/*
Copyright (C) 2009 Innectus Corporation
All rights reserved
This code is proprietary property of Innectus Corporation. Unauthorized
use, distribution or reproduction is prohibited.
$HeadURL: http://info.innectus.com.cn/innectus/trunk/loom/App/app/public/jscript_dev/uicontrollers/components/taskmonitor.js $
$Id: taskmonitor.js 1154 2010-03-17 23:58:47Z gesanto $
*/
/**
* Global flag to turn the ajax listening features of the TaskMonitors on and
* off for debugging.
* @type Boolean
*/
gTaskAjaxListenerOn = true;
/**
* All the paths for urls used throughout the script.
* @private
* @name TaskMonitor#gTaskUrls
* @type Object
*/
var gTaskUrls = {
initialize : "/secure/taskmon/initialize",
getUpdate : "/secure/taskmon/getUpdate",
cancel : "/secure/taskmon/cancel"
};
/**
*
* @class This displays the progress and status for a task.
* @param {Number}
* pbarCells the amount of cells to display for the ProgressBar.
* @param {Number}
* ajaxTime the update frequency in milliseconds
* @return A TaskMonitor Object
*/
function TaskMonitor(pbarCells, ajaxTime) {
this._pbar = new ProgressBar(pbarCells);
this._text = null;
this._time = null;
// enum of the states the taskmonitor can be in
this._enumState = {
off : 0, // the progress bar is off
on : 1, // the progress bar is on
aborted : 2 // the progress bar is off due to an abort
};
this._state = this._enumState.off;
this._isMonitorOn = false;
this._ajaxTime = ajaxTime || 3000;
if(ajaxTime == -1)
this._disableAjax = true;
else
this._disableAjax = false;
this._incProgDelay = 50;
/**
* An event for handling the finishing of a task (when either stopProgress
* or abortProgress are called).
*
* @name TaskMonitor#onFinish
* @event
* @param result
* The result of the task (For ajax, the dhtmlx loader object).
* If aborted, the abort message.
* @param {Boolean}
* abort True if the task was aborted.
* @type void
*/
this._onFinishCb = null;
/**
* An event for handling an error that was set.
*
* @name TaskMonitor#onError
* @event
* @param errorData
* Data needed to process the error.
* @type void
*/
this._onErrorCb = null;
this._serverErrorMsg = "A server side error has occured. If this persists, contact the system administrator.";
}
/**
* Set the html elements to display each TaskMonitor ui element.
*
* @public
* @param {Object|String}
* pbarDiv The html element or id to attach the progress bar ui to.
* @param {Object|String}
* textDiv The html element or id to attach the display text to.
* @param {Object|String}
* timeDiv The html element or id to attach the time remaining text
* to.
* @type void
*/
TaskMonitor.prototype.setDivs = function(pbarDiv, textDiv, timeDiv) {
this.setProgressBarDiv(pbarDiv);
this.setTextDiv(textDiv);
this.setTimeDiv(timeDiv);
};
/**
* Sets the html element to display the ProgressBar ui element.
*
* @public
* @param {Object|String}
* pbarDiv The html element or id to attach the progress bar ui to.
* @type void
*/
TaskMonitor.prototype.setProgressBarDiv = function(pbarDiv) {
if (typeof (pbarDiv) == "string")
pbarDiv = document.getElementById(pbarDiv);
this._pbar.attachToDiv(pbarDiv);
};
/**
* Sets the html element to display the text output.
*
* @public
* @param {Object|String}
* textDiv The html element or id to attach the display text to.
* @type void
*/
TaskMonitor.prototype.setTextDiv = function(textDiv) {
if (typeof (textDiv) == "string")
textDiv = document.getElementById(textDiv);
this._text = textDiv;
};
/**
* Sets the html element to display the time remaining output.
*
* @public
* @param {Object|String}
* timeDiv The html element or id to attach the time remaining text
* to.
* @type void
*/
TaskMonitor.prototype.setTimeDiv = function(timeDiv) {
if (typeof (timeDiv) == "string")
timeDiv = document.getElementById(timeDiv);
this._time = timeDiv;
};
/**
* Checks to see if the task is currently running
* @public
* @type Boolean
* @return true if the task is running.
*/
TaskMonitor.prototype.isRunning = function()
{
return this._state == this._enumState.on;
};
/**
* Starts a task or a subtask if called again without stopping a task.
*
* @public
* @param {Number}
* [maxInc=0] The maximum value to increment the progress bar up to.
* If it is 0 the progress bar will display as continuous.
* @param {Number}
* [startFill=0] The initial fill of the progress bar.
* @type void
*/
TaskMonitor.prototype.startProgress = function(maxInc, startFill) {
if (this._state != this._enumState.on) {
this._state = this._enumState.on;
this._callOnStartCb();
}
if (maxInc) {
this._pbar.start(maxInc, startFill);
this._setTime("Calculating...");
} else {
this._clearTime();
this._pbar.start();
}
};
/**
* Stops a task and checks for any errors.
*
* @public
* @param [result=null]
* The result of the task.
* @type void
*/
TaskMonitor.prototype.stopProgress = function(result) {
// check if abort has been called
if (this._state == this._enumState.aborted)
return;
this._state = this._enumState.off;
this._stopAjaxListener();
// finalize monitors.
if (this._isMonitorOn && !this._disableAjax)
this._ajaxUpdate();
// calling ajax update could have potentially called abort, check again if
// it was called.
if (this._state == this._enumState.aborted)
return;
// verify no errors have occured if this is monitoring tasks.
if (this._isMonitorOn) {
var tempResult = result;
if(result == null) {
result = this._extractLoaderFromIframe();
}
if(!this._removeAndVaildateResponseFrame() || !this._validateAjaxResponse(tempResult)) {
this.abortProgress(this._serverErrorMsg);
return;
}
}
this._setTime("Task Completed!");
this._pbar.stop();
// delay a call to the stopCb to allow for ui and current ajax returns to
// update
this._delayStopCb(result, false);
};
/**
* Aborts a task
*
* @public
* @param {String}
* [errorMsg=null] An error message about why a process was aborted.
* @type void
*/
TaskMonitor.prototype.abortProgress = function(errorMsg) {
// this checks that abort isn't being called twice.
if (this._state == this._enumState.aborted) {
INNECTUS.Dev.clientError("State is already aborted.", "TaskMonitor.abortProgress", arguments);
return;
}
this._state = this._enumState.aborted;
this._stopAjaxListener();
// cancel if this is monitoring
if (this._isMonitorOn) {
if(!this._disableAjax) {
var loader = dhtmlxAjax.getSync(gTaskUrls.cancel + "?"
+ this.getAjaxQuery());
// throw an error if the server crashed.
if (!gInspect.isValidDocument(loader.xmlDoc.responseText))
INNECTUS.Dev.serverError(gTaskUrls.cancel + "?" + this.getAjaxQuery(), "TaskMonitor.abortProgress");
}
if (!this._removeAndVaildateResponseFrame())
INNECTUS.Dev.serverError(gTaskUrls.cancel + "?" + this.getAjaxQuery(), "TaskMonitor.abortProgress");
}
this._setTime("Task Cancelled.");
this._pbar.stopError();
// delay a call to the stopCb to allow for ui and current ajax returns to
// update
this._delayStopCb(errorMsg, true);
};
/**
* Increments the progress bar.
*
* @public
* @param {Number}
* [amount=1] Increment amount.
* @type void
*/
TaskMonitor.prototype.incProgress = function(amount) {
if (this._state == this._enumState.on) {
this._pbar.increment(amount);
this._updateTime();
}
};
/**
* Fills the progress bar to a specific value.
*
* @public
* @param {Number}
* amount Fill amount.
* @type void
*/
TaskMonitor.prototype.fillProgress = function(amount) {
if (this._state == this._enumState.on) {
this._pbar.fill(amount);
this._updateTime();
}
};
/**
* Sets the display text.
*
* @public
* @param {String}
* text the text to display.
* @type void
*/
TaskMonitor.prototype.setText = function(text) {
if (this._text && text)
this._text.innerHTML = text;
};
/**
* Set an error that occured durring processing the task.
*
* @public
* @param {String}
* errorMsg A message to display.
* @param [errorData=null]
* Any data related to what caused the error.
* @type void
*/
TaskMonitor.prototype.setError = function(errorMsg, errorData) {
// for consistence of api, this function
// is just the public version of the _callOnErrorCb.
// this may change if errorMsgs are preprocessed.
this._callOnErrorCb(errorMsg, errorData);
};
/**
* This will automatically submit a form and monitor it.
*
* @public
* @param {Object}
* form The form to monitor.
* @param {Function}
* [onFinish=null] An event to call when the task finishes. Loader object will only have
* the response text availible.
* @param {Function}
* [onError=null] An event to call when the task runs into an error.
* @type void
*/
TaskMonitor.prototype.monitorFormSubmit = function(form, onFinish, onError) {
var that = this; // callback handle
if (typeof (form) == "string")
form = document.getElementById(form);
var responseFrameId = "taskMonitor" + Math.floor(Math.random() * 100000);
this._responseFrame = gDocumentHelpers.createHiddenIFrame(responseFrameId,
function() {
that.stopProgress();
});
form.target = responseFrameId;
this.startAjaxListener(onFinish, onError);
this._formPbarId = document.createElement("input");
this._formPbarId.type = "hidden";
this._formPbarId.name = this.getAjaxIdName();
this._formPbarId.id = this.getAjaxIdName();
form.appendChild(this._formPbarId);
this._formPbarId.value = this.getAjaxId();
form.submit();
};
/**
* This will automatically do an AJAX post and monitor it.
*
* @public
* @param {String}
* url The url for the AJAX call.
* @param {String}
* post The post data.
* @param {Function}
* [onFinish=null] An event to call when the task finishes.
* @param {Function}
* [onError=null] An event to call when the task runs into an error.
* @type void
*/
TaskMonitor.prototype.monitorAjaxPost = function(url, post, onFinish, onError) {
var that = this; // callback handle
this.startAjaxListener(onFinish, onError);
// add pbarId to the post!
if (!post || post == "")
post = this.getAjaxQuery();
else
post += "&" + this.getAjaxQuery();
dhtmlxAjax.post(url, post, function(result) {
that.stopProgress(result);
});
};
/**
* This will automatically do an AJAX get and monitor it.
*
* @public
* @param {String}
* url The url for the AJAX call.
* @param {Function}
* [onFinish=null] An event to call when the task finishes.
* @param {Function}
* [onError=null] An event to call when the task runs into an error.
* @type void
*/
TaskMonitor.prototype.monitorAjaxGet = function(url, onFinish, onError) {
var that = this; // callback handle
this.startAjaxListener(onFinish, onError);
// add pbarId to the get!
if (url.indexOf("?") == -1)
url += "?";
else
url += "&";
url += this.getAjaxQuery();
dhtmlxAjax.get(url, function(result) {
that.stopProgress(result);
});
this._type = "get";
};
/**
* This will start the ajax listener that will grab task updates from the
* server.
*
* @public
* @param {Function}
* [onFinish=null] An event to call when the task finishes.
* @param {Function}
* [onError=null] An event to call when the task runs into an error.
* @type void
*/
TaskMonitor.prototype.startAjaxListener = function(onFinish, onError) {
this._isMonitorOn = true;
if (onFinish)
this._onFinishCb = onFinish;
if (onError)
this._onErrorCb = onError;
var that = this; // callback handle
this.startProgress();
this._clearTime();
if(this._disableAjax) {
this._ajaxId = null;
return;
}
loader = dhtmlxAjax.getSync(gTaskUrls.initialize);
// setup start loop
if (!this._validateAjaxResponse(loader))
INNECTUS.Dev.serverError(gTaskUrls.initialize, "TaskMonitor.startAjaxListener");
else if(gTaskAjaxListenerOn)
this._intervalId = setInterval(function() {
that._ajaxUpdate();
}, this._ajaxTime);
this._ajaxId = loader.xmlDoc.responseText;
};
/**
* This gets the server variable name for the task monitor id.
*
* @type String
*/
TaskMonitor.prototype.getAjaxIdName = function() {
return "pbarId";
};
/**
* This gets the server variable value for the task monitor id.
*
* @type String
*/
TaskMonitor.prototype.getAjaxId = function() {
return this._ajaxId;
};
/**
* This gets the server variable name and value query string for the task
* monitor id.
*
* @type String
*/
TaskMonitor.prototype.getAjaxQuery = function() {
return this.getAjaxIdName() + "=" + this.getAjaxId();
};
/**
* Called when a task starts. Use with inheritence to handle ui updates.
* @private
* @type void
*/
TaskMonitor.prototype._callOnStartCb = function() {
//VOID
};
/**
* Called when a task finishes. Use with inheritence to handle ui updates.
* @private
* @param result The result (usually a dhtmlx loader object if monitoring an ajax call or an abort message)
* @param {Boolean} abort True if the task was aborted.
* @param {Boolean} noAlert True to suppress the alert message (use with overridine this function)
* @type void
*/
TaskMonitor.prototype._callOnFinishCb = function(result, abort, noAlert) {
if (this._onFinishCb) {
// set stopCb to null before the call back is called,
// incase it sets it to a new value.
var temponFinishCb = this._onFinishCb;
this._onFinishCb = null;
this._onErrorCb = null;
temponFinishCb(result, abort);
} else if (!noAlert && abort) {
if (result)
INNECTUS.alert("Task was aborted: " + result);
else
INNECTUS.alert("Task was aborted.");
}
};
TaskMonitor.prototype._extractLoaderFromIframe = function(){
if (this._responseFrame){
//mock dhtmlxLoader Object
var body = window.frames[this._responseFrame.id].document.body;
var doc;
if(body.firstChild)
doc = body.firstChild.innerHTML;
else
doc = body.innerHTML;
return {
xmlDoc:{
responseText:doc,
responseXML:null
},
doXPath:function(){return [];},
doXSLTransToString:function(){return [];}
};
}
return null;
};
/**
* Called when an error is set. Use with inheritence to handle ui updates.
* @private
* @param {string} errorMsg The error message.
* @param [errorData=null] Data relating to the error.
* @type void
*/
TaskMonitor.prototype._callOnErrorCb = function(errorMsg, errorData) {
if (this._onErrorCb)
this._onErrorCb(errorData);
};
/**
* Stops the ajax listener.
* @private
* @type void
*/
TaskMonitor.prototype._stopAjaxListener = function() {
if (this._intervalId) {
clearInterval(this._intervalId);
this._intervalId = null;
}
};
/**
* Gets an xml script that will update the state of this.
* @private
* @type void
*/
TaskMonitor.prototype._ajaxUpdate = function() {
var loader = dhtmlxAjax.getSync(gTaskUrls.getUpdate + "?"
+ this.getAjaxQuery());
// throw an error if the server crashed.
if (!gInspect.isValidDocument(loader.xmlDoc.responseText))
INNECTUS.Dev.serverError(gTaskUrls.getUpdate + "?" + this.getAjaxQuery(), "TaskMonitor._ajaxUpdate")
else {
var script = loader.xmlDoc.responseXML;
gXmlScript.run(script, this);
}
};
/**
* Updates the time remaining display with text relating to how much time is left.
* @private
* @type void
*/
TaskMonitor.prototype._updateTime = function() {
if (this._time) {
var remainingTime = this._pbar.getRemainingTime();
if(remainingTime) {
var output = "";
if (remainingTime < 5)
output = "The process should end shortly.";
else if (remainingTime < 15)
output = "Less than 15 seconds remaining.";
else if (remainingTime < 30)
output = "15 to 30 seconds remaining.";
else if (remainingTime < 60)
output = "30 to 60 seconds remaining.";
else {
var mins = Math.ceil(remainingTime / 60);
if (mins >= 60) {
var hours = floor(mins / 60);
mins -= hours * 60;
if (hours >= 24) {
var days = floor(hours / 24);
hours -= days * 24;
output += days + " day";
if (days > 1)
output += "s";
output += " and ";
}
output += hours + " hour";
if (hours > 1)
output += "s";
output += " and ";
}
output += mins + " minute";
if (mins > 1)
output += "s";
output += " remaining.";
}
this._time.innerHTML = output;
}
}
};
/**
* Clears the time remaining display.
* @private
* @type void
*/
TaskMonitor.prototype._clearTime = function() {
if (this._time)
this._time.innerHTML = "";
};
/**
* Sets the time display to a specific value (used for display a completed or aborted task).
* @private
* @param text The text to display.
* @type void
*/
TaskMonitor.prototype._setTime = function(text) {
if (this._time)
this._time.innerHTML = text;
};
/**
* Checks to see if the response from an ajax call is valid.
* @private
* @param {Object|String} result Either the dhtmlx loader object or a string containing the response.
* @return true if the result does not have any server errors.
* @type Boolean
*/
TaskMonitor.prototype._validateAjaxResponse = function(result) {
if (result) {
if (typeof (result) == "object" && result.xmlDoc
&& result.xmlDoc.responseText)
result = result.xmlDoc.responseText;
if (!gInspect.isValidDocument(result))
return false;
}
return true;
};
/**
* Removes the form response frame from the document also checks to see if errors exist in it.
* @private
* @return true if the form response frame has no server errors
* @type Boolean
*/
TaskMonitor.prototype._removeAndVaildateResponseFrame = function() {
if (this._responseFrame) {
gDocumentHelpers.delayDelete(this._responseFrame.id);
if(this._formPbarId){
this._formPbarId.parentNode.removeChild(this._formPbarId);
this._formPbarId = null;
}
var responseFrame = this._responseFrame;
this._responseFrame = null;
// verify no errors have occured.
return gInspect.isValidIframe(responseFrame);
}
return true;
};
/**
* Sets up calling the _callOnFinishCb function after a short time to ensure that the display can be updated.
* @private
* @param result The result of the task.
* @param {Boolean} abort True if the task was aborted.
* #type void
*/
TaskMonitor.prototype._delayStopCb = function(result, abort) {
var that = this; // callback handle
var thatResult = result; // callback handle
var thatAbort = abort; // callback handle
setTimeout(function() {
if ((that._state == that._enumState.aborted) && (thatAbort == false))
return;
// no longer monitoring once this point is reached.
that._isMonitorOn = false;
that._callOnFinishCb(thatResult, thatAbort);
}, this._incProgDelay);
};
|
/*
* File: app/view/RightWindow.js
*
* This file was generated by Sencha Architect version 3.2.0.
* http://www.sencha.com/products/architect/
*
* This file requires use of the Ext JS 4.2.x library, under independent license.
* License of Sencha Architect does not include license for Ext JS 4.2.x. For more
* details see http://www.sencha.com/license or contact license@sencha.com.
*
* This file will be auto-generated each and everytime you save your project.
*
* Do NOT hand edit this file.
*/
Ext.define('platform.system.view.RightWindow', {
extend: 'Ext.window.Window',
requires: [
'Ext.form.Panel',
'Ext.form.field.Hidden',
'Ext.form.RadioGroup',
'Ext.form.field.Radio',
'Ext.form.field.Number',
'Ext.toolbar.Toolbar',
'Ext.button.Button'
],
height: 226,
width: 500,
resizable: false,
title: '功能编辑',
modal: true,
initComponent: function() {
var me = this;
Ext.applyIf(me, {
items: [
{
xtype: 'form',
border: false,
height: 348,
bodyPadding: 10,
title: '',
items: [
{
xtype: 'hiddenfield',
anchor: '100%',
fieldLabel: 'Label',
name: 'id'
},
{
xtype: 'textfield',
anchor: '100%',
fieldLabel: '功能名称',
labelAlign: 'right',
name: 'text',
allowBlank: false,
emptyText: '请输入菜单名称',
maxLength: 50,
minLength: 1,
validateBlank: true
},
{
xtype: 'textfield',
anchor: '100%',
fieldLabel: '访问地址',
labelAlign: 'right',
name: 'url',
readOnly: true,
maxLength: 200
},
{
xtype: 'radiogroup',
fieldLabel: '是否需复核',
labelAlign: 'right',
items: [
{
xtype: 'radiofield',
name: 'needCheck',
boxLabel: '是',
checked: true,
inputValue: 'true'
},
{
xtype: 'radiofield',
name: 'needCheck',
boxLabel: '否',
inputValue: 'false'
}
],
listeners: {
beforerender: {
fn: me.onRadiogroupBeforeRender,
scope: me
}
}
},
{
xtype: 'radiogroup',
hidden: true,
fieldLabel: '功能状态',
labelAlign: 'right',
items: [
{
xtype: 'radiofield',
name: 'status',
boxLabel: '正常',
checked: true,
inputValue: 'Normal'
},
{
xtype: 'radiofield',
name: 'status',
boxLabel: '停用',
inputValue: 'Banned'
}
]
},
{
xtype: 'numberfield',
anchor: '100%',
fieldLabel: '排列顺序',
labelAlign: 'right',
name: 'sort',
value: 1,
maxLength: 5,
minValue: 0
},
{
xtype: 'textfield',
anchor: '100%',
fieldLabel: '菜单图标',
labelAlign: 'right',
name: 'icon',
readOnly: true,
listeners: {
focus: {
fn: me.onTextfieldFocus,
scope: me
}
}
}
],
listeners: {
afterrender: {
fn: me.onFormAfterRender,
scope: me
}
}
}
],
dockedItems: [
{
xtype: 'toolbar',
dock: 'bottom',
defaultAlign: 'right',
layout: {
type: 'hbox',
align: 'middle',
pack: 'end'
},
items: [
{
xtype: 'button',
iconCls: 'icon-ok',
text: '确 定',
listeners: {
click: {
fn: me.onBtnOkClick,
scope: me
}
}
},
{
xtype: 'button',
iconCls: 'icon-cancel',
text: '取 消',
listeners: {
click: {
fn: me.onBtnCancelClick,
scope: me
}
}
}
]
}
]
});
me.callParent(arguments);
},
onRadiogroupBeforeRender: function(component, eOpts) {
this.needCheckField = component;
},
onFormAfterRender: function(component, eOpts) {
this.form = component;
},
onTextfieldFocus: function(component, e, eOpts) {
try{
var me = this;
Common.upload({suffix:'jpg,png,gif,bmp',callback:function(result){
var data = result;
var url = Common.getDownloadURL(data.id);
component.setValue(url);
//me.iconImg.getEl().dom.src = url;
}});
}catch(error){
Common.show({title:'信息提示',html:error.toString()});
}
},
onBtnOkClick: function(button, e, eOpts) {
var me = this;
try{
Common.formSubmit({
url : ctxp+'/system/right/save',
form:me.form,
callback : function(result)
{
Ext.Msg.alert('信息提示', '保存成功!');
me.close();
}
});
}catch(error){
Common.show({title:'信息提示',html:error.toString()});
}
},
onBtnCancelClick: function(button, e, eOpts) {
this.close();
},
loadFormData: function(id) {
var me = this;
try{
Common.ajax({
component : me.form,
message : '加载信息...',
url : ctxp+'/system/right/load?id='+id,
callback : function(result)
{
try{
me.form.getForm().reset();
var rightType = result.rows.type;
if(rightType !== 'BUTTON')
{
me.needCheckField.setDisabled(true);
result.rows.needCheck = 'false';
}
var needCheck = result.rows.needCheck;
if(needCheck){
result.rows.needCheck = 'true';
}else{
result.rows.needCheck = 'false';
}
me.form.getForm().setValues(result.rows);
}catch(err){}
}
});
}
catch(error)
{
Common.show({title:'信息提示',html:error.toString()});
}
}
});
|
const DEBUG = "DEBUG";
const INFO = "INFO";
const WARN = "WARN";
const ERROR = "ERROR";
const availableLevels = {};
availableLevels[DEBUG] = 0;
availableLevels[INFO] = 1;
availableLevels[WARN] = 2;
availableLevels[ERROR] = 3;
let loggers = [
CreateLogger({
name: "default",
type: "console",
level: INFO
})
];
let formatters = [];
function CreateLogger(config) {
if (!config.logger) {
config.logger = require(`./lib/${config.type}`);
}
return {
level: config.level,
name: config.name,
logger: new config.logger(config)
};
}
function processFormatters(formatters, logObject) {
if (!formatters.length) {
return Promise.resolve(logObject);
}
const formatter = formatters.shift();
return (() =>
new Promise(resolve => formatter(logObject, () => resolve())))().then(
() => processFormatters(formatters, logObject)
);
}
function buildLogObject(level, module, message, data) {
const logObject = {
level: level,
module: module,
message: message,
data: data
};
return processFormatters([...formatters], logObject).then(() =>
Promise.resolve(logObject)
);
}
function getLoggerLevel(currentLogger, logObject) {
if (typeof currentLogger.level === "function") {
return currentLogger.level(logObject);
}
return currentLogger.level;
}
function log(level, module, message, data) {
return buildLogObject(level, module, message, data).then(logObject => {
loggers
.filter(
currentLogger =>
availableLevels[level] >=
availableLevels[getLoggerLevel(currentLogger, logObject)]
)
.forEach(currentLogger => currentLogger.logger.log(logObject));
return Promise.resolve();
});
}
function buildLogger(module) {
return Object.keys(availableLevels).reduce((allLoggers, level) => {
allLoggers[
`log${level.substring(0, 1)}${level.substring(1).toLowerCase()}`
] = log.bind(undefined, level, module);
return allLoggers;
}, {});
}
function registerLogger(config, logger) {
if (logger) {
config.logger = logger;
}
loggers.push(CreateLogger(config));
}
function setLoggerLevel(logger, level) {
const matchedLoggers = loggers.filter(
currentLogger => currentLogger.name === logger
);
if (!matchedLoggers.length) {
return;
}
matchedLoggers[0].level = level;
}
function removeAll() {
loggers.forEach(logger => logger.logger.stop());
loggers = [];
formatters = [];
}
module.exports = Object.assign(
{
registerLogger: registerLogger,
registerFormatter: handler => formatters.push(handler),
removeAll: removeAll,
setLoggerLevel: setLoggerLevel,
log: log,
forModule: buildLogger
},
buildLogger()
);
|
var Reimbursements = [];
var PendingReimbursements = [];
var acceptedReimbursements = [];
function addReimbursement() {
var reID = prompt("ReimbursmentID: ");
var amount = prompt("amount: ");
var userID = prompt("userID: ");
var reimbursement = [reID, amount, "Pending", userID];
var x = reimbursement.toString();
PendingReimbursements.push(reimbursement);
Reimbursements.push(reimbursement);
}
<!--
function allReimbursements(Reimbursements){
var x = Reimbursements.toString();
document.getElementById("demo").innerHTML = x;
}
-->
|
const MongoClient = require('mongodb').MongoClient;
let db;
let collection;
MongoClient.connect('mongodb://ec2-18-218-138-62.us-east-2.compute.amazonaws.com/', { poolSize: 10 }).then((client) => {
console.log('pass')
db = client.db('ivydatabase');
collection = db.collection('attractions');
})
const getById = function getById(id, callback) {
// collection.find().hint({ id }).limit(1).toArray()
// console.log('dataside')
// console.time('time')
console.log(id)
const a = JSON.parse(id)
collection.find({ id: a }).toArray()
.then((data) => {
// console.timeEnd('time')
console.log('data',data)
callback(null, data)
})
.catch((err) => {
callback(err, null)
})
}
exports.getById = getById;
|
import gql from 'graphql-tag'
import { graphql } from 'react-apollo'
import storiesFragment from '../fragments/stories'
export const StoriesQuery = gql`
query StoriesQuery($filter: FilterInput) {
stories(filter: $filter) {
...StoriesFragment
}
}
${storiesFragment}
`
export const queryConfig = {
options: props => {
console.log(props.router)
const { subdomain } = props.router.query
return {
variables: {
filter: {
organization: {
subdomain
},
limit: 20,
offset: 0,
order: [
{
column: 'updatedAt',
direction: 'DESC'
}
]
}
}
}
},
props: ({ ownProps, data }) => ({
...ownProps,
...data
})
}
export default graphql(StoriesQuery, queryConfig)
|
var searchData=
[
['main_5fwc_2ec',['main_wc.c',['../main__wc_8c.html',1,'']]]
];
|
let age = prompt('How old are you?');
alert(`You are ${age} years old!`);
let isBoss = confirm("Are you the boss?");
alert( isBoss );
let userName = prompt('What is your name ?');
alert(`Welcome ${userName} !`);
|
var Parser = require('expr-eval').Parser;
var value = '';
export const ButtonHandler = (e) => {
var val = e.target.value;
return value+=val;
}
export const evaluate = (expression) => {
}
|
// Tag 9 - 16.01.2020
// Queue, binär Baum und Tasterturevents
// Tasterturevents
onkeydown // Taste drücken
onkeyup // Taste loslassen
onkeypress // Tasten Bestätigung
// onkeydown und onkeypress wiederhollen sich immer wieder bis onkeyup gedrückt wird.
// KeyEvent
keyEvent.key // Was wurde gedrückt
keyEvent.getModifierState(str) // str="ALT" oder str"Control" oder str="AltGr" oder str="schift"
// Beispiel 1
onkeydown = (evt) => { console.log(evt.getModifierState("Schift"), evt.getModifierState("Control"), evt.getModifierState("Alt"), evt.getModifierState("AltGr")); };
// Beispiel 2
document.body.onkeyup = (evt) => { console.log(evt.key); };
function onkeyup()
// Beispiel für A D W S
document.body.onkeyup = (evt) => {
switch (evt.key) {
case "a":
console.log("left");
break;
case "d":
console.log("right");
break;
case "w":
console.log("up");
break;
case "s":
console.log("down");
break;
}
}
|
import {Picture} from './pictures.js';
//继承Picture类
function LinePic(parameter) {
Picture.call(this,'L',parameter);
}
LinePic.prototype = new Picture();
LinePic.prototype.constructor = LinePic;
//重写topath方法
LinePic.prototype.toPath = function(){
return this.command+this.parameter[0]+' '+this.parameter[1];
};
//重写addLocation方法
LinePic.prototype.addLocation = function (incX, incY) {
this.parameter[0] += incX;
this.parameter[1] += incY;
};
export {LinePic};
|
// function first(name){
// console.log("Hello "+name);
// }
// first("World");
var http = require('http');
var module1 = require('./module-1');
var module2 = require('./module-2');
var fs = require('fs');
var url = require('url');
function renderHTML(path,res){
fs.readFile(path,null,function(error,data){
if(error){
res.writeHead(404);
res.write("File not found");
}
else{
res.write(data);
}
res.end();
});
}
function requestHandler(req,res){
res.writeHead(200,{'Content-Type':'text/html'});
res.write(module1.Variable);
module1.myFunction();
res.write(module2.demovariable);
module2.demoFunction();
var path = url.parse(req.url).pathname;
console.log(path);
switch(path){
case '/':
renderHTML('./index.html',res);
break;
case '/login':
renderHTML('./login.html',res);
break;
default:
res.writeHead(404);
res.write("Route not defined");
res.end();
}
}
// http.createServer(requestHandler).listen(8000);
// http.createServer(function(){ //Anonymous function
// res.writeHead(200,{'Content-Type':'text/plain'});
// res.write(module1.Variable);
// module1.myFunction();
// res.write(module2.demovariable);
// module2.demoFunction();
// res.end();
// }).listen(80000);
|
const fs = require("fs");
const path = require("path");
const webpack = require("webpack");
const webpackConfig = require("./webpack.config");
const BuilderFactory = require("./src/Build/Factory");
console.log("[+] Run Webpack");
webpack(webpackConfig, (error) => {
if(error){
console.log(error);
}else{
console.log("[+] Webpack finished successfully")
}
transformArticles();
});
function transformArticles(){
console.log("[+] Transforms articles");
let articlesDistPath = path.join(__dirname, "dist/articles");
createPathIfNotExist({path: articlesDistPath});
transformArticles({articlesDistPath: articlesDistPath});
console.log("[+] Build finished successfully");
function createPathIfNotExist({path}){
if(!fs.existsSync(articlesDistPath)){
fs.mkdirSync(articlesDistPath);
}
}
function transformArticles({articlesDistPath}){
let builder = BuilderFactory.createBuilder({
articlesDistPath: articlesDistPath
});
builder.build();
}
}
|
let BCLS_toc = (function (window, document) {
let side_nav_created = false,
in_page_nav_right = true,
side_nav = document.getElementById('side_nav'),
pathname = window.location.pathname,
url = window.location.href,
in_page_nav = document.getElementById('in_page_nav'),
centered_in_page_toc = document.getElementById('centered_in_page_toc'),
right_side_nav = document.getElementById('right_side_nav'),
centered_inpage_nav = document.getElementById('centered_inpage_nav'),
article = document.querySelector('article.bcls-article'),
// product_logo = document.querySelector('.product-logo'),
// product_logo_full_path = product_logo.getAttribute('src'),
// product_logo_small_path =
// 'https://support.brightcove.com/site-assets/images/site/product-logos/b-white-on-black.svg',
h2s = document.querySelectorAll('h2[id]'),
toc_items,
toc_links,
breakpoint = 1600;
// if on an index page just remove page contents menus and leave
// if (pathname === '/' || pathname.indexOf('/index.html') > 0) {
// centered_inpage_nav.setAttribute('style', 'display: none;');
// right_side_nav.setAttribute('style', 'display: none;');
// in_page_nav_right = false;
// return;
// }
/**
* Add a class to an element
* @param {node} el the element
* @param {string} cls the class to add
*/
function addClass (el, cls) {
el.classList.add(cls);
}
/**
* Remove a class from an element
* @param {node} el the element
* @param {string} cls the class to add
*/
function removeClass (el, cls) {
el.classList.remove(cls);
}
/**
* Check to see if an element is in the viewport
* @param {node} el the element to check
*/
function isScrolledIntoView(el) {
let rect = el.getBoundingClientRect();
let elemTop = rect.top;
let elemBottom = rect.bottom;
// Only completely visible elements return true:
let isVisible = (elemTop >= 0) && (elemBottom <= window.innerHeight);
// Partially visible elements return true:
//isVisible = elemTop < window.innerHeight && elemBottom >= 0;
return isVisible;
}
/**
* Removes all child elements (eg the items in a list)
* @param {node} parent the element to remove children from
*/
function removeAllChildNodes (parent) {
if (parent) {
while (parent.firstChild) {
parent.removeChild(parent.firstChild)
}
} else {
console.log(
parent,
'Either the parent node was not passed in or does not exist'
)
}
}
/**
* Create the in-page navigation
*/
function create_inpage_nav () {
let navEl = in_page_nav,
navWrapper = right_side_nav,
h2,
li,
link,
option,
value,
i,
iMax,
frag = document.createDocumentFragment(),
parent;
// check window width to set the elements to use
if (window.innerWidth < breakpoint) {
navWrapper = centered_in_page_toc;
navEl = centered_in_page_toc;
right_side_nav.setAttribute('style', 'display: none;');
article.removeAttribute('style');
removeAllChildNodes(in_page_nav);
in_page_nav_right = false;
} else {
in_page_nav_right = true;
centered_inpage_nav.setAttribute('style', 'display: none;');
article.setAttribute('style', 'max-width:72%;');
navWrapper = right_side_nav;
navEl = in_page_nav;
}
// in case this gets run multiple times by mistake, clear existing items
if (navEl) {
removeAllChildNodes(navEl)
}
// for centered inpage nav add first option
if (navEl === centered_in_page_toc) {
option = document.createElement('option');
option.setAttribute('class', 'toc-item');
option.textContent = 'Page Contents';
option.setAttribute('value', '#');
frag.appendChild(option)
}
// add additional section items
iMax = h2s.length
console.log('navEl', navEl);
for (i = 0; i < iMax; i++) {
h2 = h2s[i]
if (in_page_nav_right) {
if (h2.id) {
li = document.createElement('li')
li.setAttribute('class', 'toc-item')
link = document.createElement('a')
link.setAttribute('href', '#' + h2.id)
link.textContent = h2.textContent
li.appendChild(link)
frag.appendChild(li)
}
} else {
if (h2.id) {
option = document.createElement('option')
option.setAttribute('class', 'toc-item')
option.setAttribute('value', '#' + h2.id)
option.textContent = h2.textContent
frag.appendChild(option)
}
}
}
if (frag.firstChild && navEl) {
navEl.appendChild(frag)
if (in_page_nav_right) {
implementHighlighting()
}
// side nav is being generated; set the flag
side_nav_created = true
} else { // no sections, remove inpage nav
if (navEl) {
parent = navEl.parentNode;
parent.setAttribute('style', 'display:none;')
}
}
// event listeners
if (in_page_nav_right) {
toc_items = document.querySelectorAll('li.toc-item');
console.log('toc_items', toc_items);
toc_links = document.querySelectorAll('li.toc-item a');
console.log('toc_links', toc_links);
iMax = toc_items.length;
for (i = 0; i < iMax; i++) {
toc_items[i].setAttribute('style', 'cursor:pointer;')
toc_items[i].addEventListener('click', function(evt) {
location.hash = this.firstElementChild.getAttribute('href');
});
}
} else {
centered_in_page_toc.addEventListener('change', function() {
let newHash = centered_in_page_toc.options[centered_in_page_toc.selectedIndex].value;
location.hash = newHash;
});
}
}
/**
* implement highlighting
* smooth scrolling for Safari
*/
function implementHighlighting () {
var navItems = document.getElementsByClassName('toc-item'),
linkEl,
j,
jMax,
linkTarget
iMax = navItems.length
for (i = 0; i < iMax; i++) {
linkEl = navItems[i]
linkTarget = linkEl.firstElementChild.getAttribute('href')
linkEl.addEventListener('click', function (e) {
document.querySelector(linkTarget).scrollIntoView({
behavior: 'smooth'
})
})
}
}
// set listener for window resize
window.addEventListener('resize', function () {
if (window.innerWidth > breakpoint) {
if (!in_page_nav_right && centered_inpage_nav) {
side_nav_created = false;
in_page_nav_right = true;
centered_inpage_nav.setAttribute('style', 'display: none;');
right_side_nav.removeAttribute('style');
removeAllChildNodes(centered_in_page_toc);
console.log('recreate right nav');
create_inpage_nav();
}
} else {
if (right_side_nav) {
if (in_page_nav_right) {
side_nav_created = false
right_side_nav.setAttribute('style', 'display:none;');
centered_inpage_nav.removeAttribute('style');
removeAllChildNodes(in_page_nav);
create_inpage_nav();
}
}
}
});
// listener for scroll events
window.addEventListener('scroll',(event) => {
let i = 0,
iMax = h2s.length;
for (i; i<iMax; i++) {
let thisID = h2s[i].getAttribute('id');
if (isScrolledIntoView(h2s[i])) {
if (toc_links) {
let i = 0,
iMax = toc_links.length;
for (i; i < iMax; i++) {
if (toc_links[i].getAttribute('href') === '#' + thisID) {
addClass(toc_items[i], 'in-view');
}
}
}
} else {
if (toc_links) {
let i = 0,
iMax = toc_links.length;
for (i; i < iMax; i++) {
if (toc_links[i].getAttribute('href') === '#' + thisID) {
removeClass(toc_items[i], 'in-view');
}
}
}
}
}
});
// if inside iframe, hide appropriate elements
// if (window.location !== window.parent.location) {
// bc_veggie_burger_wrapper.setAttribute('style', 'display:none');
// }
// hide nav by default on landing pages
// if (location.pathname.substring(location.pathname.lastIndexOf('/')) === '/index.html' || location.pathname.substring(location.pathname.lastIndexOf('/')) === '/') {
// console.log('turning off nav menu');
// toggle_nav_menu();
// }
// initial create
create_inpage_nav();
// this creates a public method, allow it to be run again (imported content for example)
return {
create_inpage_nav: create_inpage_nav,
side_nav_created: side_nav_created
}
})(window, document)
|
import store from '@/store'
import { Notification, MessageBox, Message } from 'element-ui'
import { getToken ,ERROR_CODE} from '@/libs/platformUtil'
var qs = require('qs');
function requestInterceptors(config) {
let token = getToken();
const isToken = (config.headers || {}).isToken === false ;
//给所有请求添加 携带token 请求
if(token && !isToken){
config.headers['Authorization']='Bearer ' + token ;
}
if (config.method === 'post') {
let payload = config.data.payload;
config.data = config.data.data;
if(!payload) {
config.headers['Content-Type'] = "application/json"
// config.data = qs.stringify(config.data);
}
} else if (config.method === 'get') {
if (config.url.indexOf('?') === -1) {
config.url = config.url + "?&t=" + new Date().getTime();
} else {
config.url = config.url + "&t=" + new Date().getTime();
}
}
return config;
}
function requestError(error) {
return Promise.reject(error);
}
function responseInterceptors(res) {
// 未设置状态码则默认成功状态
const code = res.data.code || 200 || 11000;
// 获取错误信息
const msg = ERROR_CODE[code] || res.data.msg || ERROR_CODE['default']
if (code === 401) {
MessageBox.confirm(msg, '系统提示', {
confirmButtonText: '重新登录',
cancelButtonText: '取消',
type: 'warning'
}
).then(() => {
store.dispatch('handleLogOut').then(() => {
location.href = '/login';
})
})
} else if (code === 500) {
Message({
message: msg,
type: 'error'
})
return Promise.reject(new Error(msg))
} else if (code !== 200 && code !== 11000) {
Notification.error({
title: msg
})
return Promise.reject(msg)
} else {
return res ;
}
}
function responseError(error) {
return Promise.reject(error);
}
function browserDetection() {
let ua = navigator.userAgent;
if (ua.match(/Chrome/i)) {
return true
} else if (ua.match(/Firefox/i)) {
return {ok:true}
} else if (ua.match(/Edge/i)) {
return {ok:true}
}else if(ua.match(/Safari/i)){
return {ok:true}
}
else if(ua.match(/MSIE/i)){
let errorInfo = "<div>您的浏览器暂不支持,建议下载 <a target='view_window' href='https://www.google.cn/chrome'>Chrome</a> 查看该网站</div>"
return {ok:false,errorInfo:errorInfo}
}else if(ua.match(/Trident/i)){
let errorInfo = "<div>您的浏览器暂不支持,建议下载 <a target='view_window' href='https://www.google.cn/chrome'>Chrome</a> 查看该网站</div>"
return {ok:false,errorInfo:errorInfo}
}
else {
let errorInfo = "<div>您的浏览器体验效果不佳,建议下载 <a target='view_window' href='https://www.google.cn/chrome/'>Chrome</a> 查看该网站</div>"
return {ok:false,errorInfo:errorInfo}
}
}
export default {
requestInterceptors: requestInterceptors,
responseInterceptors: responseInterceptors,
requestError: requestError,
responseError: responseError,
browserDetection
}
|
const fs = require('fs');
const folders = fs.existsSync('src') ?
fs.readdirSync('src', { withFileTypes: true })
.filter((dirent) => dirent.isDirectory())
.map((dirent) => dirent.name)
: undefined;
module.exports = {
extends: ['plugin:prettier/recommended'],
plugins: ['simple-import-sort'],
overrides: [
{
files: ['*.tsx', '*.ts', '*.js', '*.jsx'],
rules: {
'react/display-name': 'off',
'simple-import-sort/imports': [
'warn',
{
groups: [
// Packages. `react` related packages come first.
// Things that start with a letter (or digit or underscore), or `@` followed by a letter.
['^\\u0000', '^react$', '^prop-types$', '^@?\\w', '^redux$'],
// Absolute imports
folders ? [`^(${folders.join('|')})(/.*|$)`] : undefined,
// Relative imports.
['^\\.'],
// for scss imports.
['^[^.]'],
].filter((rule) => rule),
},
],
},
},
],
};
|
$(function() {
var that = null;
var isText = function(attr,prompt,name){
var pattern = new RegExp("[`~!@#$^&*()=|{}':;',\\[\\].<>/?~!@#¥……&*()——|{}【】‘;:”“'。,、?]"); //非法字符
var mobilereg = /^((13[0-9])|(15[^4,\D])|(17[0-9])|(18[0-9])|145|147)\d{8}$/;
var attrText = attr.val();
prompt.text('');
if(pattern.test(attrText)){
prompt.text('不能输入非法字符,如~!@#$^&*等');
attr.focus();
return false;
}else{
switch (name) {
case '登录名':
if(!attrText){
prompt.text('请输入登录名');
attr.focus();
return false;
}
break;
case '密码':
if(!attrText){
prompt.text('请输入密码');
attr.focus();
return false;
}else if(attrText.length < 6){
prompt.text('请输入至少6位以上字符');
attr.focus();
return false;
}
break;
case '真实姓名':
if(!attrText){
prompt.text('请输入真实姓名');
attr.focus();
return false;
}
break;
case '昵称':
if(!attrText){
prompt.text('请输入昵称');
attr.focus();
return false;
}
break;
case '手机号码':
if(!attrText){
prompt.text('请输入手机号码');
attr.focus();
return false;
}else if(!mobilereg.test(attrText)){
prompt.text('您输入的手机不正确');
attr.focus();
return false;
}
break;
case '星级':
if(!attrText){
prompt.text('请输入星级');
attr.focus();
return false;
}
break;
}
}
return true;
};
//失去焦点时,判断值
$('input').change(function(){
that = $(this);
var prText = that.parents('tr').find('td:first-child').text();
isText(that,that.next(),prText);
});
//提交值
$('#myForm').click(function(){
that = $('input');
var num = 0;
for(var i = that.length;i >= 0 ;i--){
var prText = $(that[i]).parents('tr').find('td:first-child').text();
if(!isText($(that[i]),$(that[i]).next(),prText)){
num++;
}
}
return;
/*alert(num);
if(num > 0){
alert(1);
}
*/
});
});
/*$(document).ready(function(e) {
$("#selProv").change(function(){
var v=$("#selProv option:selected").val();
$("#pValue").val(v);
});
$("#selStatus").change(function(){
var v=$("#selStatus option:selected").val();
$("#textstaus").val(v);
});
$("#check").click(function(){
var flag = false;//flag用于判断是否提交表单
var isMobile=/^(?:13\d|15\d|18\d)\d{5}(\d{3}|\*{3})$/; //手机号码验证规则
if($("#textno").val() == ""){
alert( "茶艺师编号不能为空!");
$("#textno").focus();
return false;
}else if($("#textname").val() == ""){
alert( "姓名不能为空!");
$("#textname").focus();
return false;
}else if($("#textstaus").val() == ""){
alert( "状态不能为空!");
$("#textstaus").focus();
return false;
}else if($("#textstatr").val() == ""){
alert( "茶艺师级别不能为空!");
$("#textstatr").focus();
return false;
}else if($("#pwd").val() == ""){
alert( "密码不能为空!");
$("#pwd").focus();
return false;
}else if($("#textphone").val()==""){
alert( "手机号不能为空!");
$("#textphone").focus();
return false;
}else if(!isMobile.test($("#textphone").val())){
alert('请输入有效的手机号码!');
$("#textphone").focus();
return false;
}else if ($('select').val() == null || $('select').val() == " ") {
alert("亲,您还为选择状态或权限!");
return false;
}else if(pattern.test($("#textno").val())||pattern.test($("#pwd").val())||pattern.test($("#textname").val())||pattern.test($("#txtnickname").val())){
alert("亲,输入项含有非法字符,如:~!@#$^&*()=|{}':;',\\[\\].<>/?~!@#¥……&*(),请重新输入!");
}else{
var messagerInfor = confirm('确定要添加吗?');
if(messagerInfor==true){
var curWwwPath=window.document.location.href;
var localhostPaht=curWwwPath.substring(0,curWwwPath.lastIndexOf('/'));
var data = localhostPaht+"/addAdmin";
$.ajax({
type: "post",
url: data,
dataType:"json",
data:$("#yourformid").serialize(),
async:false,
success: function(data){
var jsonData = data.code;
if (jsonData>0) {
alert("添加成功");
}
else if(jsonData=="nomber not empty!"){
alert("编号已存在");
}else if(jsonData=="username not empty!"){
alert("用户已存在");
}
},
error: function(XMLHttpRequest, textStatus, errorThrown){
if(XMLHttpRequest.status!=200){
alert("服务器异常!");
}
}
});
}
}
return flag;
});
});
*/
|
declare module 'stellar-sdk' {
/* stellar-base */
declare class xdrBase {
toXDR(): Buffer;
}
declare class xdr$Signature extends xdrBase {
signature(): Buffer;
}
declare class xdr$DecoratedSignature extends xdr$Signature {
constructor({hint: Buffer, signature: Buffer}): xdr$DecoratedSignature;
hint(): Buffer;
}
declare class xdr$Transaction extends xdrBase {
}
declare class xdr$TransactionEnvelope extends xdrBase {
tx: xdr$Transaction;
signatures: Array<xdr$DecoratedSignature>;
}
declare class xdr$EnvelopeType extends xdrBase {
static envelopeTypeTx(): xdr$EnvelopeType;
}
declare class xdr$Memo extends xdrBase {
}
declare class xdr$Asset extends xdrBase {
}
declare var xdr: {
DecoratedSignature: typeof xdr$DecoratedSignature,
Transaction: xdr$Transaction,
TransactionEnvelope: xdr$TransactionEnvelope,
EnvelopeType: typeof xdr$EnvelopeType
};
declare var Networks: {
PUBLIC: string,
TESTNET: string;
}
declare function hash(s: any): Buffer;
declare type BuilderOptions = {
fee?: number,
timebounds?: TimeBounds,
memo?: Memo
}
declare type TimeBounds = {
minTime?: number | string,
maxTime?: number | string
}
declare class Account {
constructor(accountId: string, sequence: string): Account;
accountId(): string;
sequenceNumber(): string;
incrementSequenceNumber(): void;
}
declare class Asset {
code: string;
issuer: string;
constructor(code: string, issuer: string): Asset;
static native(): Asset;
static fromOperation(xdr$Asset): Asset;
toXDRObject(): xdr$Asset;
getCode(): string;
getIssuer(): string;
getAssetType(): string;
isNative(): boolean;
equals(asset: Asset): boolean;
}
declare class Keypair {
static fromSecret(string): Keypair;
static fromRawEd25519Seed(Buffer): Keypair;
static master(): Keypair;
static fromPublicKey(publicKey: string): Keypair;
static random(): Keypair;
xdrAccountId(): Buffer;
xdrPublicKey(): Buffer;
rawPublicKey(): Buffer;
signatureHint(): Buffer;
publicKey(): string;
secret(): string;
rawSecretKey(): Buffer;
canSign(): boolean;
sign(Buffer): Buffer;
verify(message: Buffer, signature: Buffer): boolean;
signDecorated(Buffer): xdr$DecoratedSignature;
}
declare class Memo {
type: string;
value: null | string | Buffer;
static none(): Memo;
static text(string): Memo;
static id(string): Memo;
static hash(any): Memo;
static return(any): Memo;
toXDRObject(): xdr$Memo;
static fromXDRObject(xdr$Memo): Memo;
}
declare class Network {
_networkPassphrase: string;
constructor(networkPassphrase: string): Network;
static usePublicNetwork(): void;
static useTestNetwork(): void;
static use(Network): void;
static current(): Network;
networkPassphrase(): string;
networkId(): string;
}
declare class Operation {
source: string;
type: string;
masterWeight: number;
lowThreshold: number;
medThreshold: number;
highThreshold: number;
signer: Object;
static payment(Object): Operation;
}
declare class StrKey {
static encodeEd25519PublicKey(Buffer): string;
static decodeEd25519PublicKey(string): Buffer;
static isValidEd25519PublicKey(string): boolean;
static encodeEd25519SecretSeed(Buffer): string;
static decodeEd25519SecretSeed(string): Buffer;
static isValidEd25519SecretSeed(string): boolean;
static encodePreAuthTx(Buffer): string;
static decodePreAuthTx(string): Buffer;
static encodeSha256Hash(Buffer): string;
static decodeSha256Hash(string): Buffer;
}
declare class Transaction {
source: string;
tx: xdr$Transaction;
signatures: Array<xdr$DecoratedSignature>;
operations: Array<Operation>;
memo: Memo;
sequence: string;
fee: number | string;
timeBounds?: TimeBounds;
_memo: xdr$Memo;
constructor(envelope: string | xdr$TransactionEnvelope): Transaction;
sign(Array<Keypair>): void;
signHashX(Buffer | string): void;
hash(): Buffer;
signatureBase(): Buffer;
toEnvelope(): xdr$TransactionEnvelope;
}
declare class TransactionBuilder {
source: string;
operations: Array<Operation>;
baseFee: number;
timebounds?: TimeBounds;
memo: Memo;
constructor(sourceAccount: Account, opts: ?BuilderOptions): TransactionBuilder;
addOperation(Operation): TransactionBuilder;
addMemo(Memo): TransactionBuilder;
build(): Transaction;
}
/* stellar-sdk */
declare type SignerTypeEnum = (
'ed25519_public_key' |
'preauth_tx' |
'sha256_hash'
);
declare type Signer = {
key: string,
public_key?: string,
type: SignerTypeEnum,
weight: number
}
declare type AssetTypeEnum = (
'native' |
'credit_alphanum4' |
'credit_alphanum12'
);
declare type Trustline = {
balance: string | number,
asset_type: AssetTypeEnum,
asset_issuer?: string,
asset_code?: string,
limit?: number
}
declare type AccountFlagsEnum = (
'auth_required' |
'auth_revocable' |
'auth_immutable'
);
declare type ThresholdCategory = (
'low_threshold' |
'med_threshold' |
'high_threshold'
);
declare type AccountInfo = {
balances: Array<Trustline>,
flags: {[AccountFlagsEnum]: boolean},
id: string,
inflationDest?: string,
sequence: string,
signers: Array<Signer>,
subentryCount: number,
thresholds: {[ThresholdCategory]: number},
}
declare class Server {
constructor(url: any): Server;
accounts(): AccountCallBuilder;
}
declare class AccountCallBuilder {
accountId(id: string): AccountCallBuilder;
call(): Promise<AccountInfo>;
}
}
|
const mongoose = require('mongoose');
const uniqueValidator = require("mongoose-unique-validator");
const generalDataSchema = mongoose.Schema({
params:{type:{}}
});
generalDataSchema.plugin(uniqueValidator);
module.exports = mongoose.model('GENERAL_DATA', generalDataSchema);
|
const admin = require('firebase-admin')
module.exports = {
isAdmin: async ( req, res, next ) => {
//get the session cookie
const sessionCookie = req.cookies.__session || ""
//const sessionCookie = req.cookies.session || ""
admin
.auth()
.verifySessionCookie(sessionCookie, true /** checkRevoked */)
.then(() => {
res.locals.admin = true
next()
})
.catch((error) => {
console.log('error in authenticate ', error)
res.redirect("/admin/signin")
})
}
}
|
import React, { Component } from 'react';
import { classroomService, qualificationService } from '../../services';
import { Link, withRouter, NavLink } from 'react-router-dom';
import { withAuthConsumer } from '../../contexts/AuthStore';
class ClassroomShow extends Component {
state = {
classroom: {
name: '',
students: [],
tutor: {
name: ''
},
exams: [],
createdat: '',
updatedat: ''
},
exams: [],
isMounted: false
}
findAverage = () => {
console.log(this.state.classroom)
if (this.state.classroom.exams.length > 0) {
return this.state.classroom.exams.reduce((prev, curr) => prev + curr.grade, 0) / this.state.classroom.exams.length;
}
return 0
}
componentDidMount() {
this.state.isMounted = true;
const { match: { params } } = this.props;
classroomService.get(params.id)
.then(
(classroom) => {
this.setState({ classroom: {...classroom}}, () => {
this.fetchExams()
})
},
(error) => console.error(error)
)
}
fetchExams = () => {
qualificationService.list({ classroom: this.state.classroom.id })
.then(exams => this.setState({ exams }))
}
render() {
const { name, tutor, classroom, exams } = this.state;
return (
<div className="box mx-auto mt-5">
<div className="container">
<h3>Clase {classroom.name}</h3><br/>
<h5>Tutor: <small>{classroom.tutor.name}</small></h5><br/>
<h5>Alumnos:</h5>
<table className="table">
<thead>
<tr className="text-center align-middle">
<th scope="col">#</th>
<th scope="col"><i class="fa fa-users fa-lg"></i></th>
<th scope="col">Nombre</th>
<th scope="col">email</th>
</tr>
</thead>
<tbody>
{classroom.students.map((student, index) => (
<tr {...student} key={student.id} className="text-center align-middle">
<th scope="row">{index + 1}</th>
<td><img className="img-fluid rounded-circle" width="50" height="50" src={student.avatarURL || "http://ecuciencia.utc.edu.ec/media/foto/default-user_x5fGYax.png"}/></td>
<Link to={`/students/${student.id}`}><td>{student.name} </td></Link>
<td>{student.email}</td>
<Link className="btn btn-sm btn-primary" to={`/classrooms/${classroom.id}/qualifications/${student.id}`} role="button">Poner Nota</Link>
</tr>
))}
</tbody>
</table>
<div>
<Link className="btn btn-sm btn-primary" to={`/classrooms/${classroom.id}/edit`}>
Editar Clase
</Link>
</div>
<br/>
<h5>Exámenes:</h5>
<table className="table">
<thead>
<tr className="text-center align-middle">
<th scope="col">#</th>
<th scope="col">Alumno</th>
<th scope="col">Código de Examen</th>
<th scope="col">Fecha</th>
<th scope="col">Puntuación</th>
</tr>
</thead>
<tbody>
{exams.map((exam, index) => (
<tr key={exam.id} className="text-center align-middle" >
<th scope="row">{index+1}</th>
<td>{exam.student.name}</td>
<td>{exam.examCode}</td>
<td>{exam.date && new Date(exam.date).toLocaleDateString()}</td>
<td>{exam.grade}</td>
</tr>
))}
<tr className="text-center align-middle">
<th scope="row">Media</th>
<td></td>
<td></td>
<td></td>
<td>{this.findAverage()}</td>
</tr>
</tbody>
</table>
<a className="float-right"><i className='fa fa-reply fa-2x mt-3 text-danger' onClick={() => this.props.history.go(-1)}></i></a>
</div>
</div>
)
}
}
export default withAuthConsumer(ClassroomShow)
// export default withRouter(withAuthConsumer(ClassroomShow));
|
({
changeClient: function(component, event) {
var jsonResponseJs;
var selectedClient = component.find("inf1").get("v.value")[0];
//component.set("v.client", selectedClient);
if(!$A.util.isEmpty(selectedClient))
{
var action = component.get("c.getData");
console.log('client id: '+ selectedClient.Id);
action.setParams({
id: selectedClient.toString()
});
action.setCallback(this, function(response) {
try
{
var g = response.getReturnValue();
console.log("Future Simulation Response on change client: " + JSON.stringify(g));
var state = response.getState();
if(state==="SUCCESS" && (!($A.util.isUndefinedOrNull(g)))) {
//set loan, credit, saving, networth, goals
component.set('v.saving', g.financialAccountList['0']);
component.set('v.credit', g.financialAccountList['1']);
component.set('v.loan', g.financialAccountList['2']);
var netWorth = g.balanceList['0'] - (g.balanceList['1'] + g.balanceList['2']);
component.set('v.netWorth', netWorth);
}
else { helper.showToast(component, selectedClient.Name);}
}
catch(e){}
})
$A.enqueueAction(action);
}
},
})
|
$(function (){
function buildHTML(message) {
if (message.text && message.image) {
var html =
`<div class="message" data-message-id="${ message.id }">
<div class="user">${ message.user }</div>
<div class="time">${ message.time }</div>
<div class="text">
<p class="lower-message__text">${ message.text }</p>
<img class="lower-message__image" src="${ message.image }">
</div>
</div>`
} else if (message.text) {
var html = `<div class="message" data-message-id="${ message.id }">
<div class="user">${ message.user }</div>
<div class="time">${ message.time }</div>
<div class="text">
<p class="lower-message__text">${ message.text }</p>
</div>
</div>`
} else if (message.image) {
var html = `<div class="message" data-message-id="${ message.id }">
<div class="user">${ message.user }</div>
<div class="time">${ message.time }</div>
<img class="lower-message__image" src="${ message.image }">
</div>`
};
return html;
};
$('#new_message').on('submit', function(e){
e.preventDefault();
var $form = $(this);
formData = new FormData(this);
$.ajax({
url: './messages',
type: 'POST',
data: formData,
dataType: 'json',
processData: false,
contentType: false
})
.done(function(data){
var insertHTML = buildHTML(data);
var mainBarContent = $('.main-bar__content__messages')
mainBarContent.append(insertHTML)
mainBarContent.animate({scrollTop: mainBarContent[0].scrollHeight},'fast');
$('#new_message')[0].reset();
$('.submit-message').prop("disabled", false);
})
.fail(function(){
alert('error');
})
})
$(function(){
setInterval(updateMessage, 5000);
})
if(location.pathname.match(/\/groups\/\d+\/messages/)) {
var updateMessage = function (){
if ($('.message')[0]) {
var message_id = $('.message:last').data('message-id');
} else {
var message_id = 0
}
$.ajax({
url: location.href,
type: 'GET',
data: { id: message_id },
dataType: 'json'
})
.done(function(data){
var insertHTML = "";
data.forEach(function(message){
insertHTML += buildHTML(message);
$('.main-bar__content__messages').append(insertHTML);
});
var mainBarContent = $('.main-bar__content')
mainBarContent.animate({scrollTop: mainBarContent[0].scrollHeight},'fast');
})
.fail(function(){
alert('自動更新に失敗しました');
})
}
} else {
clearInterval(interval);
}
});
|
var searchData=
[
['securityflags',['SecurityFlags',['../ncrypt_2lib_8h.html#a2073a168ca3a64c3c30d13fa4917a05d',1,'lib.h']]],
['selectfileflags',['SelectFileFlags',['../browser_8h.html#afde6c0a2b0c99baa6b2ee3a0c855e966',1,'browser.h']]],
['sendflags',['SendFlags',['../send_8h.html#af731a62ddd44f1d907196beef8f8f19f',1,'send.h']]],
['sig_5fhandler_5ft',['sig_handler_t',['../signal2_8h.html#a60d3777917d4b61a09ecb88574a935e1',1,'signal2.h']]],
['smtpcapflags',['SmtpCapFlags',['../smtp_8c.html#a206bf9f5e94a73ce8408fd4a513b9c11',1,'smtp.c']]],
['sort_5ft',['sort_t',['../sort_8h.html#ae599403f309e9dcfdbf62e63e628a2d8',1,'sort.h']]],
['stateflags',['StateFlags',['../state_8h.html#ab47bd6fc8d3f30a89e37e9514b101391',1,'state.h']]]
];
|
import React from 'react';
import '../css/LandPage.css';
//import ReactHtmlParser from 'react-html-parser';
function LandPage(props) {
return (
<div id='LandpageWrapper'>
<button className='selectBtn' onClick={props.select}>Start</button>
</div>
);
}
export default LandPage;
|
const RippleAPI = require('ripple-lib').RippleAPI
async function run() {
// Example of setting up a 2 of 3 multisig address using ripple-lib
// Notes:
// 1. The best docs on ripple-lib are here: https://github.com/ripple/ripple-lib/blob/develop/docs/index.md
// 2. Ripple testnet explorer that shows signers of multi-sig: http://ripplerm.github.io/ripple-wallet/
// 3. From a technical perspective, there's nothing stopping you from having the
// multisignature address by a multisig of multisigs. So, if it's an issue, we
// can tell people that the existing XRP ledger can support more than 8 validators for the
// multisig.
// 4. You can set a multisign to be the only option for an address.
// 5. How the private key for the original multisign is derived is unclear.
// The most straightforward is to start with a regular XRP keypair, then setup multisign, then remove the keypair, and only accept funds to the address if it's multi-sign only. Clients could enforce this, so as long as you're running the right software and the validators are commiting their XRP address on the USDX chain, you have BFT (I think?) guarantee that you're sending funds to a multi-sig controlled by the validators of the UDSX chain.
// You could aslo do MPC ECDSA, and then I'm not sure you would even need to create the multisig with Ripple-Lib. However, I don't think you could prove that it's a multisig to clients then.
const api = new RippleAPI({
server: 'wss://s.altnet.rippletest.net:51233' // Public rippled server
})
await api.connect()
const signerAddresses = [
{
address: "rJGnjrcCmRnaecWYtXg57WuoVHUxiNkjzj",
secret: "sstZdZjm1NSSUcsmp1UtVxjjsJgyC"
},
{
address: "rNSfagh9usmvrBVWUTeqyAAW9BCP1NdWyY",
secret: "ssDEJJKNVv1GHEskCSMeTqJsXkwoN"
},
{
address: "rJpZtBRwAwpTwABapNGs5ojzT8C24d9ewx",
secret: "sa3VWXx1ZDMCUXitKGsMx2TXJUiab"
}
]
const multiSignAddress = {
address: "rs16hESfGChwAnK97oSdRJq4A18gcJbE7j",
secret: "sptZMEp27uRzAbdh7VarnWotkqC8v",
sequence: async(a) => {
const api = new RippleAPI({
server: 'wss://s.altnet.rippletest.net:51233' // Public rippled server
})
await api.connect()
const info = await api.getAccountInfo(a)
return info.sequence
}
}
const signerEntries = [
{
"SignerEntry": {
"Account": "rJGnjrcCmRnaecWYtXg57WuoVHUxiNkjzj",
"SignerWeight": 1
}
},
{
"SignerEntry": {
"Account": "rNSfagh9usmvrBVWUTeqyAAW9BCP1NdWyY",
"SignerWeight": 1
}
},
{
"SignerEntry": {
"Account": "rJpZtBRwAwpTwABapNGs5ojzT8C24d9ewx",
"SignerWeight": 1
}
}
]
const setupXrpMultisig= async (api, xrpAddress, signers, quorum) => {
const txJson = {
"Flags": 0,
"TransactionType": "SignerListSet",
"Account": xrpAddress.address,
"Sequence": await xrpAddress.sequence(xrpAddress.address),
"Fee": "12",
"SignerQuorum": quorum,
"SignerEntries": signers
}
const signedTx = await api.sign(JSON.stringify(txJson), xrpAddress.secret)
console.log(signedTx)
const receipt = await api.submit(signedTx.signedTransaction)
console.log(receipt)
return
}
// Set up two of three multisign for rs16hESfGChwAnK97oSdRJq4A18gcJbE7j
await setupXrpMultisig(api, multiSignAddress, signerEntries, 2)
}
run().then(res => process.exit(0)).catch(e => { console.log(e); process.exit(1) })
|
import React from "react";
import { Formik } from "formik";
import * as Yup from "yup";
import axios from 'axios';
import { withRouter } from 'react-router';
import SuperKlass from '../function/DefineConst';
import "../CSS/LoginFeature.css";
class ValidatedSignUpForm extends React.Component{
constructor(props) {
super(props);
this.state = {
isAgreed: false,
backSignUp:false,
name_sei:'',
name_mei:'',
name_kana_sei:'',
name_kana_mei:'',
email: '',
password: '',
password_check:''
}
this.handleToMailCheckPage = this.handleToMailCheckPage.bind(this)
}
onAgreementCheckboxChanged(newValue) {
this.setState({ isAgreed: newValue })
}
handleToMailCheckPage = (values) => {
this.props.history.push({
pathname: "/mail-check",
state: {
name_sei:values.name_sei,
name_mei: values.name_mei,
name_kana_sei: values.name_kana_sei,
name_kana_mei: values.name_kana_mei,
email: values.email,
password: values.password,
password_check: values.password_check
}
});
};
/*
componentDidMount(){
console.log(BackorFirst);
if(BackorFirst){
console.log('change');
this.setState({
name_sei: this.props.location.state.name_sei,
name_mei: this.props.location.state.name_mei,
name_kana_sei: this.props.location.state.name_kana_sei,
name_kana_mei: this.props.location.state.name_kana_mei,
email: this.props.location.state.email,
password: this.props.location.state.password,
password_check: this.props.location.state.password_check,
});
}
}
*/
render() {
return(
<Formik
initialValues={{
name_sei: this.props.location.state.name_sei,
name_mei: this.props.location.state.name_mei,
name_kana_sei: this.props.location.state.name_kana_sei,
name_kana_mei: this.props.location.state.name_kana_mei,
email: this.props.location.state.email,
password: this.props.location.state.password,
password_check: this.props.location.state.password_check,
}}
onSubmit={(values, { setSubmitting }) => {
setTimeout(() => {
setSubmitting(false);
this.handleToMailCheckPage(values);
axios
.post( SuperKlass.CONST.DOMAIN + '/user/', {
values
})
.then((res) => {
console.log("登録しました");
})
}, 500);
}}
validationSchema={Yup.object().shape({
name_sei: Yup.string()
.required("必須項目です"),
name_mei: Yup.string()
.required("必須項目です"),
name_kana_sei: Yup.string()
.required("必須項目です"),
name_kana_mei: Yup.string()
.required("必須項目です"),
email: Yup.string()
.email("有効なメールアドレスではありません")
.required("必須項目です"),
password: Yup.string()
.required("必須項目です")
.min(8, "パスワードは8文字以上です")
.matches(/[a-zA-Z0-9]+/, "パスワードは半角英数字で入力してください"),
password_check: Yup.string()
.oneOf([Yup.ref('password')], "パスワードが一致しません")
.required("必須項目です")
})}
>
{props => {
const {
values,
touched,
errors,
isSubmitting,
handleChange,
handleBlur,
handleSubmit
} = props;
return (
<form onSubmit={handleSubmit} className='input-form'>
<label htmlFor="email">姓</label>
<input
name="name_sei"
type="text"
placeholder="姓"
value={values.name_sei}
onChange={handleChange}
onBlur={handleBlur}
className={errors.name_sei && touched.name_sei && "error"}
/>
{errors.name_sei && touched.name_sei && (
<div className="input-feedback">{errors.name_sei}</div>
)}
<label htmlFor="email">名</label>
<input
name="name_mei"
type="text"
placeholder="名"
value={values.name_mei}
onChange={handleChange}
onBlur={handleBlur}
className={errors.name_mei && touched.name_mei && "error"}
/>
{errors.name_mei && touched.name_mei && (
<div className="input-feedback">{errors.name_mei}</div>
)}
<label htmlFor="email">セイ</label>
<input
name="name_kana_sei"
type="text"
placeholder="セイ"
value={values.name_kana_sei}
onChange={handleChange}
onBlur={handleBlur}
className={errors.name_kana_sei && touched.name_kana_sei && "error"}
/>
{errors.name_kana_sei && touched.name_kana_sei && (
<div className="input-feedback">{errors.name_kana_sei}</div>
)}
<label htmlFor="email">メイ</label>
<input
name="name_kana_mei"
type="text"
placeholder="メイ"
value={values.name_kana_mei}
onChange={handleChange}
onBlur={handleBlur}
className={errors.name_kana_mei && touched.name_kana_mei && "error"}
/>
{errors.name_kana_mei && touched.name_kana_mei && (
<div className="input-feedback">{errors.name_kana_mei}</div>
)}
<label htmlFor="email">メールアドレス</label>
<input
name="email"
type="text"
placeholder="メールアドレスを入力"
value={values.email}
onChange={handleChange}
onBlur={handleBlur}
className={errors.email && touched.email && "error"}
/>
{errors.email && touched.email && (
<div className="input-feedback">{errors.email}</div>
)}
<label htmlFor="email">パスワード</label>
<input
name="password"
type="password"
placeholder="パスワードを入力"
value={values.password}
onChange={handleChange}
onBlur={handleBlur}
className={errors.password && touched.password && "error"}
/>
{errors.password && touched.password && (
<div className="input-feedback">{errors.password}</div>
)}
<label htmlFor="email">パスワード(確認)</label>
<input
name="password_check"
type="password"
placeholder="再度パスワードを入力"
value={values.password_check}
onChange={handleChange}
onBlur={handleBlur}
className={errors.password_check && touched.password_check && "error"}
/>
{errors.password_check && touched.password_check && (
<div className="input-feedback">{errors.password_check}</div>
)}
<input
id="check"
type="checkbox"
name="check"
onClick={evt => {
this.onAgreementCheckboxChanged(evt.currentTarget.checked)
}}
/><label>利用規約・特定商品取引法に同意する</label>
<button
id="but"
type="submit"
disabled={isSubmitting || !this.state.isAgreed}
>
登録
</button>
</form>
);
}}
</Formik>
);
}
}
/* const FormikForm = withFormik({
mapPropsToValues({ title, body }) {
return {
title: title || '', // titleに値が入っていたらpropsで渡されたtitleを表示、または空表示
body: body || ''
}
}
})(ValidatedSignUpForm) */
export default withRouter(ValidatedSignUpForm);
|
//Models
const { Post, User } = require("../models");
// Obtiene todos los Posts de la DB
export const getPosts = async (req, res) => {
try {
const allPosts = await Post.findAll();
res.status(200).json(allPosts || []);
} catch (error) {
res.status(500).json({ status: 500, mensaje: error.message });
}
};
// Obtiene Post filtrado por id de la BD
export const getPostById = async (req, res) => {
try {
const { id } = req.params;
const foundPost = await Post.findOne({
where: { id },
include: User,
});
res.status(200).json(foundPost || {});
} catch (error) {
res.status(500).json({ status: 500, mensaje: error.message });
}
};
// Crear nuevo Post de la DB
export const createPost = async (req, res) => {
try {
await Post.create(req.body);
res.status(201).send({
status: 201,
mensaje: "Post fue creado correctamente!!",
});
} catch (error) {
res.status(500).json({ status: 500, mensaje: error.message });
}
};
// Borrar Post de la DB
export const deletePost = async (req, res) => {
try {
const { id } = req.params;
const deleted = await Post.destroy({
where: { id },
});
if (!deleted) {
return res.status(404).json({
status: 404,
mensaje: "Id de Post no encontrado!",
});
}
res.status(200).json({
status: 200,
mensaje: `Post ${id} fue borrado correctamente!!`,
});
} catch (error) {
res.status(500).json({ status: 500, mensaje: error.message });
}
};
// Actualizar Post de la BD
export const updatePost = async (req, res) => {
try {
const { id } = req.params;
const newPost = req.body;
const [updated] = await Post.update(newPost, {
where: { id },
});
if (!updated) {
return res.status(404).json({
status: 404,
mensaje: "Id de Usuario no encontrado!",
});
}
res.status(200).json({
status: 200,
mensaje: `Post ${id} fue actualizado correctamente!!`,
});
} catch (error) {
res.status(500).json({ status: 500, mensaje: error.message });
}
};
|
var searchData=
[
['city',['city',['../classdomain_1_1RuralHouse.html#a4ac1bd1de58f97487abbcb8dc27a8077',1,'domain::RuralHouse']]]
];
|
import React from "react";
const EmptyBookmark = () => {
return (
<React.Fragment>
<h1>Your bookmark is empty</h1>
</React.Fragment>
);
};
export default EmptyBookmark;
|
const clickSuche = function() {
this.expect.element('@suche').to.be.visible
return this.click('@suche')
}
export default {
elements: {
suche: {
selector: 'hs-nav li:nth-child(1) a',
},
},
commands: [
{
clickSuche,
},
],
}
|
/*
test.js - test script
The MIT License (MIT)
Copyright (c) 2016 Dale Schumacher
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";
var test = module.exports = {};
//var log = console.log;
var log = function () {};
var warn = console.log;
//var tart = require('tart-tracing');
var actor = require('../humus/hybrid.js');
test['actor model defines create and send'] = function (test) {
test.expect(2);
test.strictEqual(typeof actor.create, 'function');
test.strictEqual(typeof actor.send, 'function');
test.done();
};
var null_beh = function null_beh(msg) { // no-op actor behavior
return {
actors: [],
events: [],
behavior: undefined
};
};
test['behavior returns actors, events, and optional behavior'] = function (test) {
test.expect(4);
var m = 'Hello!';
var r = null_beh(m);
log('r:', r);
test.strictEqual(typeof r, 'object');
test.ok(Array.isArray(r.actors));
test.ok(Array.isArray(r.events));
test.ok((r.behavior === undefined) || ('function' === typeof r.behavior));
test.done();
};
test['create returns actor address'] = function (test) {
test.expect(1);
var a = actor.create(null_beh);
test.strictEqual(typeof a, 'function'); // address encoded as a function
test.done();
};
test['send returns message-event'] = function (test) {
test.expect(3);
var a = actor.create(null_beh);
var m = 'Hello!';
var e = actor.send(a, m);
test.strictEqual(typeof e, 'object');
test.strictEqual(e.target, a);
test.strictEqual(e.message, m);
test.done();
};
test['one shot actor should forward first message, then ignore everything'] = function (test) {
test.expect(4);
var null_beh = function null_beh(msg) {
log('null'+actor.self+':', msg);
test.strictEqual(++count, 2);
return {
actors: [],
events: [],
behavior: undefined
};
};
var one_shot = function one_shot(fwd) {
return function one_shot_beh(msg) {
log('one_shot'+actor.self+':', msg);
test.strictEqual(++count, 1);
return {
actors: [],
events: [
actor.send(fwd, msg)
],
behavior: null_beh
};
};
};
var done_beh = function done_beh(msg) {
log('done'+actor.self+':', msg);
test.done();
return {
actors: [],
events: [],
behavior: undefined
};
};
var count = 0;
var a = actor.create(function end_beh(msg) {
log('end'+actor.self+':', msg);
test.strictEqual(++count, 3);
var d = actor.create(done_beh);
return {
actors: [d],
events: [
actor.send(d, 'Z')
],
behavior: undefined
};
});
var b = actor.create(one_shot(a));
actor.apply({
actors: [a, b],
events: [
actor.send(b, 'X'),
actor.send(b, 'Y')
]
});
test.strictEqual(actor.self, undefined);
};
function Y(a, b) { // binary tree with left branch `a` and right branch `b`
this.a = a;
this.b = b;
}
// Y.prototype.toString = function toString() { return '<' + this.a + ', ' + this.b + '>' };
var aTree = new Y(1, new Y(new Y(2, 3), 4)); // <1, <<2, 3>, 4>>
var bTree = new Y(new Y(1, 2), new Y(3, 4)); // <<1, 2>, <3, 4>>
var cTree = new Y(new Y(new Y(1, 2), 3), new Y(5, 8)); // <<<1, 2>, 3>, <5, 8>>
test['<1, <<2, 3>, 4>> has fringe [1, 2, 3, 4]'] = function (test) {
test.expect(1);
var fringe = function fringe(tree) {
if (tree instanceof Y) {
let left = fringe(tree.a);
let right = fringe(tree.b);
return left.concat(right);
}
return [ tree ];
};
test.deepEqual(fringe(aTree), [ 1, 2, 3, 4 ]);
test.done();
};
test['fringe(<1, <<2, 3>, 4>>) = fringe(<<1, 2>, <3, 4>>)'] = function (test) {
test.expect(1);
var fringe = function fringe(tree) {
if (tree instanceof Y) {
return fringe(tree.a).concat(fringe(tree.b));
}
return [ tree ];
};
test.deepEqual(fringe(aTree), fringe(bTree));
test.done();
};
test['suspend calculations in generators'] = function (test) {
test.expect(1);
var genFringe = function* genFringe(tree) {
if (tree instanceof Y) {
yield* genFringe(tree.a);
yield* genFringe(tree.b);
} else {
yield tree;
}
};
var fringe = [];
var gen = genFringe(aTree);
var leaf = gen.next();
while (leaf.value !== undefined) {
fringe.push(leaf.value);
leaf = gen.next();
};
test.deepEqual(fringe, [ 1, 2, 3, 4 ]);
test.done();
};
test['suspend calculations in closures'] = function (test) {
test.expect(1);
var genFringe = function genFringe(tree, next) {
next = next || (() => ({})); // default next == end
if (tree instanceof Y) {
return () => {
var right = genFringe(tree.b, next);
var left = genFringe(tree.a, right);
return left();
}
} else {
return () => ({ value: tree, next: next });
}
};
var fringe = [];
var leaf = (genFringe(aTree))();
while (leaf.value !== undefined) {
fringe.push(leaf.value);
leaf = leaf.next();
};
test.deepEqual(fringe, [ 1, 2, 3, 4 ]);
test.done();
};
test['incrementally compare functional fringe'] = function (test) {
test.expect(5);
var genFringe = function genFringe(tree, next) {
next = next || (() => ({})); // default next == end
if (tree instanceof Y) {
return () => (genFringe(tree.a, genFringe(tree.b, next)))();
} else {
return () => ({ value: tree, next: next });
}
};
var r0 = (genFringe(aTree))();
var r1 = (genFringe(bTree))();
while (true) {
test.strictEqual(r0.value, r1.value); // match stream contents
if ((r0.value === undefined) || (r1.value === undefined)) {
break; // stream end
}
r0 = r0.next();
r1 = r1.next();
};
test.done();
};
test['compare functional fringe to infinite series'] = function (test) {
test.expect(6);
var genFringe = function genFringe(tree, next) {
next = next || (() => ({})); // default next == end
if (tree instanceof Y) {
return () => (genFringe(tree.a, genFringe(tree.b, next)))();
} else {
return () => ({ value: tree, next: next });
}
};
var genSeries = function genSeries(value, update) {
return () => ({ value: value, next: genSeries(update(value), update) });
};
var r0 = (genFringe(aTree))();
var r1 = (genSeries(1, n => n + 1))();
while ((r0.value !== undefined) && (r1.value !== undefined)) {
test.strictEqual(r0.value, r1.value); // match stream contents
r0 = r0.next();
r1 = r1.next();
};
test.strictEqual(r0.value, undefined); // fringe stream ended
test.strictEqual(r1.value, 5); // un-matched series value should be 5
test.done();
};
test['compare generator fringe to infinite series'] = function (test) {
test.expect(6);
var genFringe = function* genFringe(tree) {
if (tree instanceof Y) {
yield* genFringe(tree.a);
yield* genFringe(tree.b);
} else {
yield tree;
}
};
var genSeries = function* genSeries(value, update) {
while (true) {
yield value;
value = update(value);
}
};
var gen0 = genFringe(aTree);
var r0 = gen0.next();
var gen1 = genSeries(1, n => n + 1);
var r1 = gen1.next();
while ((r0.value !== undefined) && (r1.value !== undefined)) {
test.strictEqual(r0.value, r1.value); // match stream contents
r0 = gen0.next();
r1 = gen1.next();
};
test.strictEqual(r0.value, undefined); // fringe stream ended
test.strictEqual(r1.value, 5); // un-matched series value should be 5
test.done();
};
test['compare generator fringe to infinite series using for..of'] = function (test) {
test.expect(6);
var genFringe = function* genFringe(tree) {
if (tree instanceof Y) {
yield* genFringe(tree.a);
yield* genFringe(tree.b);
} else {
yield tree;
}
};
var genSeries = function* genSeries(value, update) {
while (true) {
yield value;
value = update(value);
}
};
var zip = function* zip(first, second) {
while (true) {
let f = first.next();
let s = second.next();
if (f.done || s.done) {
return;
}
yield [f.value, s.value];
}
};
let pair;
for (pair of zip(genFringe(aTree), genSeries(1, n => n + 1))) {
test.strictEqual(pair[0], pair[1]);
}
test.strictEqual(pair[0], 4); // finished at last fringe stream value
test.strictEqual(pair[1], 4); // finished at last series value
test.done();
};
test['compare generator fringe to infinite series using compare generator'] = function (test) {
test.expect(2);
var genFringe = function* genFringe(tree) {
if (tree instanceof Y) {
yield* genFringe(tree.a);
yield* genFringe(tree.b);
} else {
yield tree;
}
};
var genSeries = function* genSeries(value, update) {
while (true) {
yield value;
value = update(value);
}
};
var compare = function* compare(first, second) {
while (true) {
let f = first.next();
let s = second.next();
if (f.value === s.value) {
if (f.value === undefined) {
return yield (f.done && s.done);
} else {
yield true;
}
} else {
return yield false;
}
}
};
let match;
let matched = 0;
for (match of compare(genFringe(aTree), genSeries(1, n => n + 1))) {
match ? matched++ : matched;
}
test.strictEqual(matched, 4); // only first four match
test.strictEqual(match, false); // the fringe doesn't match the series
test.done();
};
test['compare generator fringe to generator fringe using compare generator'] = function (test) {
test.expect(1);
var genFringe = function* genFringe(tree) {
if (tree instanceof Y) {
yield* genFringe(tree.a);
yield* genFringe(tree.b);
} else {
yield tree;
}
};
var compare = function* compare(first, second) {
while (true) {
let f = first.next();
let s = second.next();
if (f.value === s.value) {
if (f.value === undefined) {
return yield (f.done && s.done);
} else {
yield true;
}
} else {
return yield false;
}
}
};
let match;
for (match of compare(genFringe(aTree), genFringe(aTree)))
;
test.strictEqual(match, true); // the fringe matches the fringe
test.done();
};
test['verify iterFringe() and sameIterable() as posted'] = function (test) {
test.expect(4);
var iterFringe = function* iterFringe(tree) {
if (tree instanceof Y) {
yield* iterFringe(tree.a);
yield* iterFringe(tree.b);
} else {
yield tree;
}
};
var sameIterable = function sameIterable(g0, g1) {
let r0 = g0.next(); // get result from first sequence
let r1 = g1.next(); // get result from second sequence
while (r0.value === r1.value) {
if (r0.value === undefined) {
return (r0.done && r1.done); // true == stream end
}
r0 = g0.next();
r1 = g1.next();
}
return false; // mismatch
};
test.strictEqual(sameIterable(iterFringe(aTree), iterFringe(bTree)), true);
test.strictEqual(sameIterable(iterFringe(bTree), iterFringe(cTree)), false);
test.strictEqual(sameIterable(iterFringe(cTree), iterFringe(aTree)), false);
test.strictEqual(sameIterable(iterFringe(cTree), iterFringe(cTree)), true);
test.done();
};
test['functional fringe comparisons'] = function (test) {
test.expect(6);
var genFringe = function genFringe(tree, next) {
next = next || (() => ({})); // default next == end
if (tree instanceof Y) {
return () => (genFringe(tree.a, genFringe(tree.b, next)))();
} else {
return () => ({ value: tree, next: next });
}
};
var sameFringe = function sameFringe(s0, s1) {
let r0 = s0(); // get result from first sequence
let r1 = s1(); // get result from second sequence
while (r0.value === r1.value) {
if (r0.value === undefined) {
return true; // stream end
}
r0 = r0.next();
r1 = r1.next();
}
return false; // mismatch
};
test.strictEqual(sameFringe(genFringe(aTree), genFringe(bTree)), true);
test.strictEqual(sameFringe(genFringe(cTree), genFringe(bTree)), false);
var genSeries = function genSeries(value, update) {
return () => {
try {
let next = genSeries(update(value), update);
return { value: value, next: next };
} catch (e) {
return { error: e };
}
};
};
test.strictEqual(sameFringe(genFringe(cTree), genSeries(1, n => n + 1)), false);
var genRange = function genRange(lo, hi) {
if (lo < hi) {
return () => ({ value: lo, next: genRange(lo + 1, hi) });
} else {
return () => ({}); // stream end
}
};
test.strictEqual(sameFringe(genRange(0, 32), genRange(0, 32)), true);
test.strictEqual(sameFringe(genRange(0, 99999), genRange(0, 99999)), true);
test.strictEqual(sameFringe(genRange(42, 123456), genSeries(42, n => n + 1)), false);
test.done();
};
var tart = (f)=>{let c=(b)=>{let a=(m)=>{setImmediate(()=>{try{x.behavior(m)}catch(e){f&&f(e)}})},x={self:a,behavior:b,sponsor:c};return a};return c};
/*
var tart = (f) => {
let c = (b) => {
let a = (m) => {
setImmediate(() => {
try {
x.behavior(m)
} catch(e) {
f && f(e)
}
})
}, x = {
self: a,
behavior: b,
sponsor: c
};
return a
};
return c
};
var tart = function(){var c=function(b){var a=function(m){setImmediate(function(){x.behavior(m)})},x={self:a,behavior:b,sponsor:c};return a};return c}
var tart = function () {
var c = function (b) {
var a = function (m) {
setImmediate(function () {
x.behavior(m)
})
}, x = {
self: a,
behavior: b,
sponsor: c
};
return a
};
return c
}
*/
test['stateless actor-based fringe stream'] = function (test) {
test.expect(1);
var sponsor = tart(warn); // actor create capability
var mkFringe = function mkFringe(tree, next) {
return function fringeBeh(cust) {
next = next || this.sponsor(function (cust) { cust({}); });
if (tree instanceof Y) {
var right = this.sponsor(mkFringe(tree.b, next));
var left = this.sponsor(mkFringe(tree.a, right));
left(cust);
} else {
cust({ value: tree, next: next });
}
};
};
var collector = function collector(fringe) {
return function collectBeh(leaf) { // leaf = { value:, next: } | {}
log('leaf:', leaf);
if (leaf.value) {
this.behavior = collector(fringe.concat([ leaf.value ]));
leaf.next(this.self);
} else {
test.deepEqual(fringe, [ 1, 2, 3, 4 ]);
test.done();
}
};
};
var stream = sponsor(mkFringe(aTree));
var reader = sponsor(collector([]));
stream(reader);
};
test['stateful actor-based fringe stream'] = function (test) {
test.expect(1);
var sponsor = tart(warn); // actor create capability
var mkFringe = function mkFringe(tree, next) {
return function fringeBeh(cust) {
next = next || this.sponsor(function (cust) { cust({}); });
if (tree instanceof Y) {
var right = this.sponsor(mkFringe(tree.b, next));
this.behavior = mkFringe(tree.a, right);
this.self(cust);
} else {
cust({ value: tree, next: next });
}
};
};
var collector = function collector(fringe) {
return function collectBeh(leaf) { // leaf = { value:, next: } | {}
log('leaf:', leaf);
if (leaf.value) {
this.behavior = collector(fringe.concat([ leaf.value ]));
leaf.next(this.self);
} else {
test.deepEqual(fringe, [ 1, 2, 3, 4 ]);
test.done();
}
};
};
var stream = sponsor(mkFringe(aTree));
var reader = sponsor(collector([]));
stream(reader);
};
test['incrementally compare actor-based streams'] = function (test) {
test.expect(5);
var sponsor = tart(warn); // actor create capability
var mkFringe = function mkFringe(tree, next) {
return function fringeBeh(cust) {
next = next || this.sponsor(function (cust) { cust({}); });
if (tree instanceof Y) {
var right = this.sponsor(mkFringe(tree.b, next));
this.behavior = mkFringe(tree.a, right);
this.self(cust);
} else {
cust({ value: tree, next: next });
}
};
};
var comparator = function comparator(cust) {
var initBeh = function compareBeh(r0) { // r0 = { value:, next: } | {}
this.behavior = function compareBeh(r1) { // r1 = { value:, next: } | {}
this.behavior = initBeh;
log('r0:', r0, 'r1:', r1);
if (r0.value === r1.value) {
if (r0.value === undefined) {
cust(true); // stream end
} else {
test.strictEqual(r0.value, r1.value); // match stream contents
r0.next(this.self);
r1.next(this.self);
}
} else {
cust(false); // mismatch
}
};
};
return initBeh;
};
var finish = sponsor(function finishBeh(matched) {
test.ok(matched);
test.done();
});
var s0 = sponsor(mkFringe(aTree));
var s1 = sponsor(mkFringe(bTree));
var compare = sponsor(comparator(finish));
s0(compare);
s1(compare);
};
test['stream comparison stops early on mismatch'] = function (test) {
test.expect(5);
var sponsor = tart(warn); // actor create capability
var mkFringe = function mkFringe(tree, next) {
return function fringeBeh(cust) {
next = next || this.sponsor(function (cust) { cust({}); });
if (tree instanceof Y) {
var right = this.sponsor(mkFringe(tree.b, next));
this.behavior = mkFringe(tree.a, right);
this.self(cust);
} else {
cust({ value: tree, next: next });
}
};
};
var comparator = function comparator(cust) {
var initBeh = function compareBeh(r0) { // r0 = { value:, next: } | {}
this.behavior = function compareBeh(r1) { // r1 = { value:, next: } | {}
this.behavior = initBeh;
log('r0:', r0, 'r1:', r1);
if (r0.value === r1.value) {
if (r0.value === undefined) {
cust(true); // stream end
} else {
test.strictEqual(r0.value, r1.value); // match stream contents
r0.next(this.self);
r1.next(this.self);
}
} else {
// cust(false); // mismatch
cust(r1); // send mismatch to finish
}
};
};
return initBeh;
};
var finish = sponsor(function finishBeh(matched) {
log('matched:', matched);
test.strictEqual('object', typeof matched);
test.strictEqual(5, matched.value);
test.done();
});
var s0 = sponsor(mkFringe(aTree));
var s1 = sponsor(mkFringe(cTree));
var compare = sponsor(comparator(finish));
s0(compare);
s1(compare);
};
test['compare actor fringe to infinite series'] = function (test) {
test.expect(6);
var sponsor = tart(warn); // actor create capability
var mkFringe = function mkFringe(tree, next) {
return function fringeBeh(cust) {
next = next || this.sponsor(function (cust) { cust({}); });
if (tree instanceof Y) {
var right = this.sponsor(mkFringe(tree.b, next));
this.behavior = mkFringe(tree.a, right);
this.self(cust);
} else {
cust({ value: tree, next: next });
}
};
};
var mkSeries = function mkSeries(value, update) {
return function seriesBeh(cust) {
var next = this.sponsor(mkSeries(update(value), update));
cust({ value: value, next: next });
}
};
var comparator = function comparator(cust) {
var initBeh = function compareBeh(r0) { // r0 = { value:, next: } | {}
this.behavior = function compareBeh(r1) { // r1 = { value:, next: } | {}
this.behavior = initBeh;
log('r0:', r0, 'r1:', r1);
if (r0.value === r1.value) {
if (r0.value === undefined) {
cust(true); // stream end
} else {
test.strictEqual(r0.value, r1.value); // match stream contents
r0.next(this.self);
r1.next(this.self);
}
} else {
// cust(false); // mismatch
cust(r0); // send mismatch to finish
}
};
};
return initBeh;
};
var finish = sponsor(function finishBeh(matched) {
log('matched:', matched);
test.strictEqual('object', typeof matched);
test.strictEqual(5, matched.value);
test.done();
});
var s0 = sponsor(mkFringe(aTree));
var s1 = sponsor(mkSeries(1, (n => n + 1)));
var compare = sponsor(comparator(finish));
s0(compare);
s1(compare);
};
|
import styled from 'styled-components';
import { Link } from '@reach/router';
export const Wrapper = styled.div`
padding: 40px;
display: flex;
justify-content: space-between;
align-items: flex-start;
`;
export const TitleContainer = styled.div`
display: flex;
justify-content: space-between;
align-items: center;
`;
export const NavContainer = styled.div`
margin: 0;
display: flex;
flex-direction: column;
align-items: flex-end;
position: relative;
`;
export const Form = styled.form`
margin: 20px 0 0;
`;
export const StyledLink = styled(Link)`
padding: 10px;
`;
export const CreateContainer = styled.div`
display: flex;
flex-direction: column;
align-items: flex-end;
padding-top: 20px;
position: absolute;
top: 100%;
width: 300px;
`;
export const CreateButton = styled.button`
border: none;
background: #000;
color: #fff;
padding: 10px 15px;
cursor: pointer;
`;
export const AddWrapper = styled.div`
margin: 20px 0 0;
border: 1px solid #000;
padding: 15px;
box-shadow: 1px 1px 10px rgba(0, 0, 0, 0.2);
`;
export const AddTitle = styled.h4`
margin: 0 0 10px;
`;
export const AddInput = styled.input`
height: 21px;
border: 1px solid #000;
margin: 0;
padding-left: 3px;
padding-right: 3px;
width: 200px;
`;
export const AddButton = styled.button`
border: 1px solid #000;
background-color: ${props =>
props.opened ? 'rgba(0,0,0,0.75)' : 'rgba(0,0,0,1)'};
color: white;
padding: 5px 9px;
cursor: pointer;
outline: none;
height: 25px;
`;
|
//variable declarations
var express = require('express'),
mongoose = require('mongoose'),
router = new express.Router(),
renderVlogs = require("../renderVlogs.js");
router.get("/", function(req, res){
//get vlogs
console.log("about to render run render vlogs function");
renderVlogs(res);
});
module.exports = router;
|
import React, {Component} from 'react';
import {withStyles} from '@material-ui/core/styles';
import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
import Typography from '@material-ui/core/Typography';
import Button from '@material-ui/core/Button';
import MenuIcon from '@material-ui/icons/Menu';
import IconButton from '@material-ui/core/IconButton';
import BookIcon from '@material-ui/icons/CollectionsBookmark';
import Menu from '@material-ui/core/Menu';
import MenuItem from '@material-ui/core/MenuItem';
import {Link} from "react-router-dom";
const styles = theme => ({
root: {
flexGrow: 1,
marginBottom: "40px"
},
flex: {
flexGrow: 1,
display: "flex"
},
icon: {
marginRight: theme.spacing.unit
},
menuButton: {
marginLeft: -12,
marginRight: 20,
},
link: {
textDecoration: "none",
color: "#fff"
},
loginButton: {
marginLeft: "auto"
}
});
class Header extends Component {
render() {
const {classes} = this.props;
return (
<div className={classes.root}>
<AppBar position="static">
<Toolbar>
<Link to="/" className={[classes.flex, classes.link].join(" ")}>
<BookIcon className={classes.icon}/>
<Typography variant="title" color="inherit" className={classes.flex}>
Dictionary - remember everything!
</Typography>
</Link>
<Link to="/login" className={classes.link}>
<Button color="inherit">Login</Button>
</Link>
</Toolbar>
</AppBar>
</div>
);
}
}
export default withStyles(styles)(Header);
|
const base = require('./base')
const native = require('./native')
const web = require('./web')
const merge = require('webpack-merge')
const { check } = require('./utils')
const configs = {
ios: native,
android: native,
base,
web
}
module.exports = () => {
try {
check()
const { platform, action } = process.env
return !platform
? [
merge(base('ios', action), native('ios', action, true)),
merge(base('android', action), native('android', action, true))
]
: [merge(base(platform, action), configs[platform](platform, action))]
} catch (error) {
throw new Error(`\x1b[31m${error}\x1b[0m`)
}
}
|
import React from "react";
// material-ui components
import withStyles from "@material-ui/core/styles/withStyles";
import Slide from "@material-ui/core/Slide";
import Dialog from "@material-ui/core/Dialog";
import DialogTitle from "@material-ui/core/DialogTitle";
import DialogContent from "@material-ui/core/DialogContent";
import IconButton from "@material-ui/core/IconButton";
// @material-ui/icons
import Close from "@material-ui/icons/Close";
import DialogActions from "@material-ui/core/DialogActions";
import CircularProgress from "@material-ui/core/CircularProgress";
import Edit from "@material-ui/icons/Edit";
import isEqual from "lodash/isEqual";
// core components
import Button from "../../components/CustomButtons/Button";
import SliderForm from "./sliderForm";
import modalStyle from "../../assets/jss/material-kit-react/modalStyle";
import { Grid, Snackbar } from "../../../node_modules/@material-ui/core";
import GridItem from "../../components/Grid/GridItem";
import Validator from "../../helpers/validator";
import BezopSnackBar from "../../assets/jss/bezop-mkr/BezopSnackBar";
import SliderUplooad from "../../bezopComponents/Images/sliderPlaceholder";
const wrapper = {
position: "relative",
};
const buttonProgress = {
position: "absolute",
top: "50%",
left: "50%",
marginTop: -12,
marginLeft: -12,
color: "#ffffff",
};
function Transition(props) {
return <Slide direction="down" {...props} />;
}
class SliderModal extends React.Component {
constructor(props) {
super(props);
const { sliderDetails, elements } = this.props;
this.state = {
modal: false,
sliderDetails,
snackBarOpen: false,
snackBarMessage: "",
loading: false,
elements: Validator.propertyExist(this.props, "elements") ? elements : {},
};
}
componentWillReceiveProps(newProps) {
const { slider, sliderDetails } = this.props;
if (Validator.propertyExist(newProps, "slider", "addSlider")
&& !isEqual(slider.addSlider, newProps.slider.addSlider)) {
if (typeof newProps.slider.addSlider === "string") {
this.setState({
snackBarOpen: true,
snackBarMessage: newProps.slider.addSlider,
loading: false,
});
return false;
}
this.setState({
sliderDetails,
loading: false,
});
this.handleClose();
}
if (Validator.propertyExist(newProps, "slider", "updateSlider")
&& !isEqual(slider.updateSlider, newProps.slider.updateSlider)) {
if (typeof newProps.slider.updateSlider === "string") {
this.setState({
snackBarOpen: true,
snackBarMessage: newProps.slider.updateSlider,
loading: false,
});
return false;
}
this.setState({
loading: false,
});
this.handleClose();
}
if (Validator.propertyExist(newProps, "slider", "updateImage")) {
if (typeof newProps.slider.updateImage === "string") {
return false;
}
this.setState({
elements: newProps.slider.updateImage.elements,
});
}
return false;
}
onCloseHandler = () => {
this.setState({ snackBarOpen: false });
}
setParentSliderDetails = (sliderDetails) => {
this.setState({
sliderDetails,
});
}
handleClose = () => {
this.setState({
modal: false,
});
}
handleClickOpen = () => {
this.setState({
modal: true,
});
}
addSliderPost = () => {
const { postSliderDetails } = this.props;
const { sliderDetails } = this.state;
this.setState({
loading: true,
});
postSliderDetails(sliderDetails);
}
updateSliderPost = () => {
const { putSliderDetails, eachData } = this.props;
const { sliderDetails } = this.state;
this.setState({
loading: true,
});
putSliderDetails(sliderDetails, eachData.id);
}
render() {
const { classes, type, slider, sliderDetails, eachData, postImage, height, width } = this.props;
const { snackBarOpen, snackBarMessage, loading, elements, modal } = this.state;
let header;
let content;
let submitButton;
switch (type) {
case "add":
header = (
<div style={wrapper}>
<Button
color="primary"
onClick={this.handleClickOpen}
>
Create New Post
</Button>
</div>
);
content = (
<SliderForm
sliderDetails={sliderDetails}
setParentSliderDetails={this.setParentSliderDetails}
slider={slider}
/>
);
submitButton = (
<div style={wrapper}>
<Button
variant="contained"
color="primary"
component="span"
disabled={loading}
style={{ width: "100%" }}
onClick={this.addSliderPost}
>
Create Slider
</Button>
{loading && <CircularProgress size={20} style={buttonProgress} />}
</div>
);
break;
case "edit":
header = (
<Edit
color="primary"
onClick={this.handleClickOpen}
/>
);
content = (
<SliderForm
sliderDetails={sliderDetails}
setParentSliderDetails={this.setParentSliderDetails}
slider={slider}
eachData={eachData}
/>
);
submitButton = (
<div>
<Button
variant="contained"
color="primary"
component="span"
style={{ width: "100%" }}
onClick={this.updateSliderPost}
disabled={loading}
>
Update Slider
</Button>
{loading && <CircularProgress size={20} style={buttonProgress} />}
</div>
);
break;
case "image":
header = (
<div style={wrapper}>
<Button
color="primary"
onClick={this.handleClickOpen}
>
Upload Images
</Button>
</div>
);
content = (
<SliderUplooad
postImage={postImage}
slider={slider}
eachData={eachData}
elements={elements}
collection="slider"
height={height}
width={width}
/>
);
submitButton = null;
break;
default:
return false;
}
return (
<div>
{header}
<Dialog
fullScreen
fullWidth
classes={{
root: classes.center,
paper: classes.modal,
}}
open={modal}
TransitionComponent={Transition}
keepMounted
onClose={this.handleClose}
aria-labelledby="modal-slide-title"
aria-describedby="modal-slide-description"
>
<DialogTitle
id="classic-modal-slide-title"
disableTypography
className={classes.modalHeader}
>
<IconButton
className={classes.modalCloseButton}
key="close"
aria-label="Close"
color="inherit"
onClick={this.handleClose}
>
<Close className={classes.modalClose} />
</IconButton>
</DialogTitle>
<DialogContent
id="modal-slide-description"
className={classes.modalBody}
>
{content}
</DialogContent>
<DialogActions>
{submitButton !== null
? (
<Grid container>
<GridItem xs={12}>
{submitButton}
</GridItem>
</Grid>) : null}
</DialogActions>
<Snackbar
anchorOrigin={{ vertical: "top", horizontal: "center" }}
open={snackBarOpen}
onClose={this.onCloseHandler}
>
<BezopSnackBar
onClose={this.onCloseHandler}
variant="error"
message={snackBarMessage}
/>
</Snackbar>
</Dialog>
</div>
);
}
}
export default withStyles(modalStyle)(SliderModal);
|
var https = require('https');
var connect = require('connect');
var log4js = require('log4js');
var fs = require('fs');
var logger = log4js.getLogger();
var Proxy = module.exports = exports = function(options, broker){
this.options = options;
this.broker = broker;
this.init();
}
Proxy.prototype.init = function(){
var self = this;
var options = {
key: fs.readFileSync(__dirname+'/certs/key.pem'),
cert: fs.readFileSync(__dirname+'/certs/cert.pem')
};
var app = connect().use(connect.favicon()).use(connect.query()).use(connect.bodyParser()).use(function(req, res){
var routingKey = new Date().getTime();
self.request(routingKey, req.query, res);
});
this.server = https.createServer(options, app);
}
Proxy.prototype.request = function(routingKey, req, res){
this.broker.collect(routingKey, req, this.response, res);
}
Proxy.prototype.response = function(res, message){
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end(JSON.stringify(message));
}
Proxy.prototype.start = function(){
var self = this;
var host = self.options.host;
var port = self.options.port;
self.server.listen(port, host,function(){
logger.info("Https Proxy started: " + host+":"+port)
});
return this;
}
|
/*
Copyright 2019 Adobe. All rights reserved.
This file is licensed to you under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under
the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
OF ANY KIND, either express or implied. See the License for the specific language
governing permissions and limitations under the License.
*/
const ora = require('ora')
const open = require('open')
const chalk = require('chalk')
const fs = require('fs-extra')
// const path = require('path')
const BaseCommand = require('../../BaseCommand')
const AppScripts = require('@adobe/aio-app-scripts')
const { flags } = require('@oclif/command')
class Deploy extends BaseCommand {
async run () {
// cli input
const { flags } = this.parse(Deploy)
// const appDir = path.resolve(args.path)
// const currDir = process.cwd()
// process.chdir(appDir)
// setup scripts, events and spinner
// todo modularize (same for all app-scripts wrappers)
const spinner = ora()
try {
const listeners = {
onStart: taskName => {
this.log(chalk.bold(`> ${taskName}`))
spinner.start(taskName)
},
onEnd: taskName => {
spinner.succeed(chalk.green(taskName))
this.log()
},
onWarning: warning => {
spinner.warn(chalk.dim(chalk.yellow(warning)))
spinner.start()
},
onProgress: info => {
if (flags.verbose) {
spinner.stopAndPersist({ text: chalk.dim(` > ${info}`) })
} else {
spinner.info(chalk.dim(info))
}
spinner.start()
}
}
const scripts = AppScripts({ listeners })
// build phase
if (!flags.deploy) {
if (!flags.static) {
if (fs.existsSync('actions/')) {
await scripts.buildActions()
} else {
this.log('no action src, skipping action build')
}
}
if (!flags.actions) {
if (fs.existsSync('web-src/')) {
await scripts.buildUI()
} else {
this.log('no web-src, skipping web-src build')
}
}
}
// deploy phase
if (!flags.build) {
if (!flags.static) {
if (fs.existsSync('actions/')) {
await scripts.deployActions()
} else {
this.log('no action src, skipping action deploy')
}
}
if (!flags.actions) {
if (fs.existsSync('web-src/')) {
const url = await scripts.deployUI()
this.log(chalk.green(chalk.bold(`url: ${url}`))) // always log the url
if (!flags.verbose) {
open(url) // do not open if verbose as the user probably wants to look at the console
}
} else {
this.log('no web-src, skipping web-src deploy')
}
}
}
// final message
if (flags.build) {
this.log(chalk.green(chalk.bold('Build success, your app is ready to be deployed 👌')))
} else if (flags.actions) {
this.log(chalk.green(chalk.bold('Well done, your actions are now online 🏄')))
} else {
this.log(chalk.green(chalk.bold('Well done, your app is now online 🏄')))
}
// process.chdir(currDir)
} catch (error) {
spinner.fail()
// process.chdir(currDir)
this.error(error)
}
}
}
Deploy.description = `Build and deploy an Adobe I/O App
`
Deploy.flags = {
...BaseCommand.flags,
build: flags.boolean({
char: 'b',
description: 'Only build, don\'t deploy',
exclusive: ['deploy']
}),
deploy: flags.boolean({
char: 'd',
description: 'Only deploy, don\'t build',
exclusive: ['build']
}),
static: flags.boolean({
char: 's',
description: 'Only build & deploy static files'
}),
actions: flags.boolean({
char: 'a',
description: 'Only build & deploy actions'
})
// todo no color/spinner/open output
// 'no-fancy': flags.boolean({ description: 'Simple output and no url open' }),
}
// for now we remove support for path arg
// until https://github.com/adobe/aio-cli-plugin-config/issues/44 is resolved
Deploy.args = [] // BaseCommand.args
module.exports = Deploy
|
self.__precacheManifest = (self.__precacheManifest || []).concat([
{
"revision": "581783e2ba79fad994deeae0c9b99c2a",
"url": "/index.html"
},
{
"revision": "eddd732c41e0f1ded3ab",
"url": "/static/css/main.efff993e.chunk.css"
},
{
"revision": "b4d8651d5fd687e38674",
"url": "/static/js/2.0e474515.chunk.js"
},
{
"revision": "c64c486544348f10a6d6c716950bc223",
"url": "/static/js/2.0e474515.chunk.js.LICENSE.txt"
},
{
"revision": "eddd732c41e0f1ded3ab",
"url": "/static/js/main.addcd3a2.chunk.js"
},
{
"revision": "1c1cad6f0c9f6d7ea233",
"url": "/static/js/runtime-main.961e63d6.js"
}
]);
|
const uuidv4 = require('uuid/v4');
// eslint-disable-next-line no-multi-assign
const UuidHook = (exports = module.exports = {});
UuidHook.uuid = async uuid => {
uuid.id = uuidv4();
};
|
import React, { useState } from "react";
import "../style/opcionesMenu.css";
import combo from "../images/combo.png";
import BotonesOpciones from "../componentes/botonesOpciones";
import Header from "../componentes/header"
function OpcionesMenu( props ) {
const [inicio, setInicio] = useState(["Tipo" ]);
let mostrarOpciones;
const click = (e) => {
props.setMostrar(false)
}
return (
<div>
<Header />
<div className="Container3">
<div className="grid">
<div className="zonaImagen">
{" "}
<img src={combo} alt="combo" />
</div>
<div className="zonaClase">
{" "}
<div
className="bot"
type="button"
onClick={() => { mostrarOpciones =
"Tipo";
setInicio(mostrarOpciones)
}}
>
{" "}
Tipo{" "}
</div>
<div
className="bot"
type="button"
onClick={() => { mostrarOpciones =
"Adición";
setInicio(mostrarOpciones)
}}
>
{" "}
Adiciones{" "}
</div>
<div
className="bot"
type="button"
onClick={() => { mostrarOpciones =
"Salsas";
setInicio(mostrarOpciones)
}}
>
{" "}
Salsas{" "}
</div>{" "}
</div>
<div className="zonaBotones">
{" "}
<BotonesOpciones tipoFiltro ={inicio} envio={props.setContadorAdiciones} intento={props.adiciones}/>
</div>
</div>
<button className='botonVolver' onClick={()=>{click()} }>Regresar</button>
</div>
</div>
);
}
export default OpcionesMenu;
|
import { useState, useCallback } from "react";
export const useAction = (listStudent) => {
const [textInput, setTextInput] = useState("");
const [result, setResult] = useState([]);
const getResult = useCallback(() => {
let temp = [];
listStudent.map((item) => {
if (item.includes(textInput)) temp.push(item);
});
setResult(temp?.toString());
}, [textInput]);
return [textInput, result, { setTextInput, getResult }];
};
|
var express = require('express');
var app = express();
var port = process.env.PORT||8000;
var multer = require('multer');
var upload = multer();
app.use(express.static('public'));
app.post('/getfilesize', upload.single('file'), function(request, response){
if(request.file){
response.json({size: request.file.size});
}else{
response.json({error: 'No file provided'});
}
});
app.listen(port);
|
if (Meteor.isServer) {
Meteor.startup(function() {
PythonCode.remove({});
for (j = 0; j < 10; j ++) {
for(i = 0; i < 40; i++) {
PythonCode.insert({prob: j, team: 'team' + i, code: '', last_wrote: ''});
}
PythonCode.insert({prob: j, team: 'nrt', code: '', last_wrote: ''});
}
Timers.remove({});
Timers.insert({prob: 0, min: 0, sec: 0});
CurrNum.remove({});
CurrNum.insert({num: 0});
Meteor.methods({
'Timers.Update': function(args) {
var timer = Timers.findOne({"prob" : 0});
Timers.update({"_id": timer['_id']}, {$set : {"min": args.mins, "sec": args.secs}});
return false;
},
'PythonCode.Update': function(args) {
var id = Meteor.user().emails[0].address;
var teamN = id.split('_')[0];
var code = PythonCode.findOne({prob: args.num, team: teamN});
PythonCode.update({"_id" : code['_id']}, {prob: args.num, team: args.teamN, code: args.newStr, last_wrote: args.id});
},
'CurrNum.Update': function() {
// Updating to the next problem
var obj = CurrNum.findOne({});
CurrNum.update({_id : obj['_id']}, {num: obj['num'] + 1});
}
});
PythonCode.deny({
insert: function() {
return true;
},
update: function() {
return true;
}
});
CurrNum.deny({
insert: function() {
return true;
},
update: function() {
return true;
}
});
Timers.deny({
insert: function () {
return true;
},
update: function() {
return true;
}
});
});
}
|
import React from "react";
import Header from "../Header/Header";
import DataDisplay from "../DataDisplay/DataDisplay";
// import Chart from "../Chart/Chart";
import Button from "../Button/Button";
import Backdrop from "../Backdrop/Backdrop";
import Modal from "../Modal/Modal";
import PropTypes from "prop-types";
import "./Diet.scss";
const diet = props => {
// console.log(props)
return (
<div className="Diet">
<Header clicked={props.handleButtonClicks} menuOpened={props.menuOpened} />
<DataDisplay
foodList={props.foodList}
// nutritionData={props.nutritionData}
nutritionsNames={props.nutritionsNames}
data={props.data}
userData={props.userData}
/>
{/* <Chart /> */}
<Button className="add-food-button" clicked={props.handleButtonClicks} textContent="+" action="toggle-modal" />
<Backdrop showBackdrop={props.modalOpened}>
<Modal modalOpened={props.modalOpened} clicked={props.handleButtonClicks} addNutrition={props.addNutrition} />
</Backdrop>
</div>
);
};
diet.propTypes = {
handleButtonClicks: PropTypes.func,
menuOpened: PropTypes.bool,
userData: PropTypes.object,
nutritionData: PropTypes.object,
addNutrition: PropTypes.func
};
export default diet;
|
/*
Write a function called productOfArray which takes in an array of numbers and
returns the product of them all
*/
function productOfArray(arr) {
// edge case: arr = []
if (!arr.length) return null;
// base case: arr.length = 1
if (arr.length === 1) return arr[0];
return arr[0] * productOfArray(arr.slice(1))
}
console.log(productOfArray([1,2,3])); // 6
console.log(productOfArray([1,2,3,10])); // 60
|
/* eslint-disable jsx-a11y/alt-text */
/* eslint-disable react-hooks/exhaustive-deps */
import React, { useEffect, useState } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { Button, Form, Grid, Card, Image, Message } from 'semantic-ui-react';
import {
getCategories,
postInfo,
singlePost,
saveCoordinate,
fetchPosts
} from '../actions';
import Map from './Map';
import Swal from 'sweetalert2';
import { DirectUpload } from 'activestorage';
const PostDetails = (props) => {
const dispatch = useDispatch();
const categories = useSelector((state) => state.categories);
const info = useSelector((state) => state.postInfo);
const user = useSelector((state) => state.user);
const coordinate = useSelector((state) => state.map);
const token = localStorage.getItem('token');
const [id, setId] = useState(0);
const [title, setTitle] = useState('');
const [description, setDescription] = useState('');
const [latitude, setLatitude] = useState(30.5103116);
const [longitude, setLongitude] = useState(-97.837184);
const [category, setCategory] = useState('');
const [image, setImage] = useState('');
useEffect(() => {
getCat();
if (props.match.params.id) {
getPostById();
}
}, []);
const getPostById = async () => {
const response = await fetch(
`https://gift-away-backend.herokuapp.com/api/v1/posts/${props.match.params.id}`,
{
method: 'GET',
headers: {
Authorization: `Bearer ${token}`
}
}
);
const data = await response.json();
dispatch(singlePost(data));
setId(data.id);
setTitle(data.title);
setDescription(data.description);
setLatitude(data.latitude);
setLongitude(data.longitude);
dispatch(saveCoordinate({ lat: data.latitude, lng: data.longitude }));
setImage(data.image.url);
setCategory(data.category.category);
dispatch(
postInfo({
category_id: data.category_id,
image: data.image
})
);
dispatch(
saveCoordinate({
lat: data.latitude,
lng: data.longitude
})
);
};
const getCat = async () => {
const response = await fetch(
'https://gift-away-backend.herokuapp.com/api/v1/categories',
{
method: 'GET',
headers: {
Authorization: `Bearer ${token}`
}
}
);
const data = await response.json();
dispatch(getCategories(data));
};
const handleSubmit = (e) => {
e.preventDefault();
const title = e.target.title.value;
const description = e.target.description.value;
if (title.length === 0 || description.length === 0) {
Swal.fire({
title: 'Oops!',
text: 'Title or description cannot be blank...',
icon: 'error',
confirmButtonText: 'Ok'
});
}
updatePost(title, description);
uploadFile(title, description);
props.history.push('/manage-my-post');
};
const updatePost = (title, description) => {
const token = localStorage.getItem('token');
let data = {
title: title,
description: description,
category_id: info.category_id,
latitude: coordinate.lat,
longitude: coordinate.lng,
image: info.image
};
fetch(
`https://gift-away-backend.herokuapp.com/api/v1/posts/${id}?info=post`,
{
method: 'PUT',
// mode: 'cors',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
Authorization: `Bearer ${token}`
},
body: JSON.stringify(data)
}
)
.then((response) => response.json())
.then((result) => {
if (result) {
uploadFile();
}
});
};
const uploadFile = (title, description) => {
const token = localStorage.getItem('token');
const upload = new DirectUpload(
info.image,
'https://gift-away-backend.herokuapp.com/rails/active_storage/direct_uploads'
);
upload.create((error, blob) => {
if (error) {
console.log(error);
} else {
console.log("there's no error");
fetch(`https://gift-away-backend.herokuapp.com/api/v1/posts/${id}`, {
method: 'PUT',
// mode: 'cors',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
Authorization: `Bearer ${token}`
},
body: JSON.stringify({ image: blob.signed_id })
})
.then((response) => response.json())
.then((result) => dispatch(fetchPosts('manage', user.id)));
}
});
};
const handleOnChange = (e) => {
if (e.target.type === 'file') {
dispatch(postInfo({ image: e.target.files[0] }));
}
};
console.log(coordinate.lat);
console.log(coordinate.lng);
return (
<div className="App">
<Grid textAlign="center" verticalAlign="middle">
<Grid.Column style={{ maxWidth: 850 }}>
<br></br>
<br></br>
<br></br>
<Form color="green" onSubmit={(event) => handleSubmit(event)}>
<Form.Field>
<label>Title</label>
<input placeholder="Title" name="title" defaultValue={title} />
</Form.Field>
<Form.Field>
<label>Description</label>
<textarea
placeholder="Tell us more"
rows="3"
name="description"
defaultValue={description}
></textarea>
</Form.Field>
<Form.Select
fluid
label="Category"
name="category"
options={categories.categories.map((cat) => {
return {
key: cat.id,
text: cat.category,
value: cat.id
};
})}
placeholder="Select a Category"
onChange={(e, { value, text }) => {
setCategory(text);
dispatch(
postInfo({
category_id: value,
category: text
})
);
}}
text={category}
/>
<label>Files</label>
<div>
<Card>
<Image src={image} wrapped ui={false} />
</Card>
<Message
attached
content="By uploading new image, old image will be overwritten."
/>
</div>
<input
type="file"
multiple
name="image_files"
onChange={(e) => handleOnChange(e)}
/>
<div style={{ margin: '100px' }}>
<label>Pick-up Location</label>
<Map
center={{
lat: parseFloat(latitude),
lng: parseFloat(longitude)
}}
height="300px"
zoom={15}
/>
</div>
<Button color="teal" fluid size="large" type="submit">
Save and Post
</Button>
</Form>
</Grid.Column>
</Grid>
</div>
);
};
export default PostDetails;
|
const {router} = require("../../config/expressconfig");
const {sql} = require("../../config/dbConfig");
const {url} = require("../../config/serverRootUrl");
const {knex} = require("../../knex/knex");
const bcrypt = require("bcrypt")
const jwt = require('jsonwebtoken')
//SIMPLE LOGIN API
let userLoginApi = router.post("/login-userSelection", async (req, res) => {
let {email, password} = req.body;
const user = await knex('user').where({email}).first()
bcrypt.compare(password, user.password, (err, result) => {
if (err) {
return res.status(401).json({
message: 'Auth failed'
})
}
if (result) {
user.password = '';
const token = jwt.sign({
email: user.email,
},
process.env.JWT_SECRET_KEY,
{}
);
return res.status(200).json({
message: 'Auth successful',
token: token,
user: user
})
}
res.status(401).json({
message: 'Auth failed'
})
})
});
//FB AND GMAIL INFO SAVE TO THE SYSTEM
let userSocialLogin = router.post("/social-login/", (req, res) => {
let {provider, uid, email, userName} = req.body;
console.log(req.body)
if (provider == "facebook.com") {
let userobj = {
fbUid: uid,
email: email,
userName
}
sql.selectByEmail('user', req.body, (result) => {
if (result && result.length != 0) {
if (!result[0].fbUid) {
sql.updateFbQuery('user', email, userobj, (result) => {
return res.json({message: "USER UID UPDATED SUCCESSFULLY", responseCode: 200, user: result})
});
} else {
return res.json({message: "USER UID ALREADY UPDATED", responseCode: 200, user: result})
}
} else {
sql.insertQuery('user', userobj, (respons) => {
console.log(respons)
sql.selectByFbId('user', userobj, (newUser) => {
return res.json({message: "USER NOT FOUND", responseCode: 404, user: newUser})
})
})
}
});
} else if (provider == "google.com") {
let userobj = {
gmailUid: uid,
email: email,
userName
}
sql.selectByEmail('user', req.body, (result) => {
// console.log(result)
if (result && result.length != 0) {
// console.log(result[0].gmailUid)
if (!result[0].gmailUid) {
sql.updateGmailQuery('user', email, userobj, (result) => {
return res.json({message: "USER UID UPDATED SUCCESSFULLY", responseCode: 200, user: result})
});
} else {
return res.json({message: "USER UID ALREADY UPDATED", responseCode: 200, user: result})
}
} else {
sql.insertQuery('user', userobj, (respons) => {
// console.log(respons)
sql.selectByGmailId('user', userobj, (newUser) => {
return res.json({message: "USER NOT FOUND", responseCode: 404, user: newUser})
})
})
}
});
} else {
return res.json({message: "USER NOT FOUND", responseCode: 404, user: "not found"})
}
});
// CHECK EMAIL IS EXISTS IN THE SYSTEM OR NOT
let validateEmailApi = router.get("/validateEmail/:email", (req, res) => {
// let { email, password } = req.params;
sql.selectByEmail('user', req.params, (result) => {
if (result && result.length != 0) {
return res.json({message: "EMAIL FOUND", responseCode: 200, user: result})
} else {
return res.json({message: "EMAIL NOT FOUND", responseCode: 404, user: result})
}
})
});
// VERIFY USER BY EMAIL
let verifyUser = router.get("/verify-userSelection/:email", (req, res) => {
let {email} = req.params;
let obj = {
isVerified: 'Verified',
email
}
sql.updateUserVerificationQuery('user', email, obj, (result) => {
if (result && result.affectedRows == 0) {
return res.send("sorry this email is not exists");
} else {
let file = url + "/staticTemplates/verifyUser.html";
return res.redirect(file);
}
});
});
module.exports = {userLoginApi, userSocialLogin, validateEmailApi, verifyUser}
|
// HTTP requests in Postman:
// GET /api/v1/employees HTTP/1.1
// Host: dummy.restapiexample.com
// GET /api/v1/employee/1 HTTP/1.1
// Host: dummy.restapiexample.com
// POST /api/v1/create HTTP/1.1
// Host: dummy.restapiexample.com
// PUT /api/v1/update/21 HTTP/1.1
// Host: dummy.restapiexample.com
// DELETE /api/v1/delete/2 HTTP/1.1
// Host: dummy.restapiexample.com
|
/*
* modals.js
* *
* *
* * Copyright (c) 2016 HEB
* * All rights reserved.
* *
* * This software is the confidential and proprietary information
* * of HEB.
* *
*/
(function () {
'use strict';
angular.module('productMaintenanceUiApp').directive('warningModal',
function (){
return{
restrict: 'E',
templateUrl: "src/utils/modals/warningModal.html"
};
});
})();
|
/* eslint-disable react/jsx-one-expression-per-line */
import React from 'react'
import { FaSkull, FaSkullCrossbones, FaExclamationCircle } from 'react-icons/fa'
import * as Story from '_story'
import ListOrdered from '../list-ordered'
import ListUnordered from '../list-unordered'
import ListItem, { LI } from '.'
const Demo = () => (
<>
<h1>ListItem</h1>
<p>
The <em>ListOrdered</em> and <em>ListUnordered</em> components apply theme
styling for the HTML <code>ol</code> and <code>ul</code> elements.
</p>
<p>
The <em>ListItem</em> component applies theme styling to the HTML{' '}
<code>li</code> element and is used with both ordered and unordered lists.
</p>
<h2>LI Alias</h2>
<p>
The <em>LI</em> component is an alias for <em>ListItem</em>.
</p>
<Story.Grid>
<Story.Box>
<ListOrdered>
<LI>item</LI>
<LI icon={<FaSkull />}>icon item</LI>
<LI>
Balaam Kali Ili e-Ol balazodareji, od aala tahilanu-osnetaabe:
daluga vaomesareji elonusa cape-mi-ali varoesa cala homila; Damballa
soba ipame luipamis: das sobolo vepe zodomeda poamal, od bogira aai
ta piape Piamoel od Vaoan! Zodacare, eca, od zodameranu! odo cicale
Qaa
</LI>
<LI icon={<FaSkull />}>
Shamad T'an-mo Dracula Balaam Micama! goho Pe-IAD! zodir com-selahe
azodien biabe os-lon-dohe. Mormo Azazel elanu saha caelazod: Sedit
Pilada noanu vaunalahe balata od-vaoan. das zodonurenusagi cab:
Mormo Do-o-i-ape mada: goholore, gohus, amiranu! Micama!
</LI>
</ListOrdered>
</Story.Box>
<Story.Box>
<ListUnordered>
<LI>item</LI>
<LI icon={<FaSkull />}>icon item</LI>
<LI>
Balaam Kali Ili e-Ol balazodareji, od aala tahilanu-osnetaabe:
daluga vaomesareji elonusa cape-mi-ali varoesa cala homila; Damballa
soba ipame luipamis: das sobolo vepe zodomeda poamal, od bogira aai
ta piape Piamoel od Vaoan! Zodacare, eca, od zodameranu! odo cicale
Qaa
</LI>
<LI icon={<FaSkull />}>
Shamad T'an-mo Dracula Balaam Micama! goho Pe-IAD! zodir com-selahe
azodien biabe os-lon-dohe. Mormo Azazel elanu saha caelazod: Sedit
Pilada noanu vaunalahe balata od-vaoan. das zodonurenusagi cab:
Mormo Do-o-i-ape mada: goholore, gohus, amiranu! Micama!
</LI>
</ListUnordered>
</Story.Box>
</Story.Grid>
<h2>Icon Prop</h2>
<p>
The <em>ListItem</em> component <em>icon</em> prop accepts a React
component to use in place of a list marker.
</p>
<Story.Grid>
<Story.Box>
<ListUnordered>
<ListItem>item</ListItem>
<ListItem>item</ListItem>
<ListUnordered>
<ListItem>item</ListItem>
<ListItem icon={<FaSkull />}>item</ListItem>
</ListUnordered>
<ListItem icon={<FaExclamationCircle />}>item</ListItem>
<ListItem icon={<FaSkullCrossbones />}>item</ListItem>
</ListUnordered>
</Story.Box>
</Story.Grid>
<h2>Color and MarkerColor Props</h2>
<Story.Grid>
<Story.Box color="dark">
<ListOrdered>
<ListItem>primary item</ListItem>
<ListItem icon={<FaSkull />}>primary icon item</ListItem>
</ListOrdered>
</Story.Box>
<Story.Box>
<ListOrdered>
<ListItem>primary item</ListItem>
<ListItem icon={<FaSkull />}>primary icon item</ListItem>
</ListOrdered>
</Story.Box>
</Story.Grid>
<p>
The <em>color</em> prop should color both the marker and the text.
</p>
<Story.Grid>
<Story.Box color="dark">
<ListOrdered color="primary">
<ListItem>primary item</ListItem>
<ListItem icon={<FaSkull />}>primary icon item</ListItem>
<ListItem color="secondary">secondary item</ListItem>
<ListItem color="secondary" icon={<FaSkull />}>
secondary icon item
</ListItem>
</ListOrdered>
</Story.Box>
<Story.Box>
<ListOrdered color="primary">
<ListItem>primary item</ListItem>
<ListItem icon={<FaSkull />}>primary icon item</ListItem>
<ListItem color="secondary">secondary item</ListItem>
<ListItem color="secondary" icon={<FaSkull />}>
secondary icon item
</ListItem>
</ListOrdered>
</Story.Box>
</Story.Grid>
<p>
The <em>markerColor</em> prop should color only the marker (only works on
native markers in Firefox and Safari >= 11.1).
</p>
<Story.Grid>
<Story.Box color="dark">
<ListOrdered markerColor="primary">
<ListItem>primary item</ListItem>
<ListItem icon={<FaSkull />}>primary icon item</ListItem>
<ListItem markerColor="secondary">secondary item</ListItem>
<ListItem markerColor="secondary" icon={<FaSkull />}>
secondary icon item
</ListItem>
</ListOrdered>
</Story.Box>
<Story.Box>
<ListOrdered markerColor="primary">
<ListItem>primary item</ListItem>
<ListItem icon={<FaSkull />}>primary icon item</ListItem>
<ListItem markerColor="secondary">secondary item</ListItem>
<ListItem markerColor="secondary" icon={<FaSkull />}>
secondary icon item
</ListItem>
</ListOrdered>
</Story.Box>
</Story.Grid>
</>
)
Demo.story = {
name: 'ListItem',
}
export default Demo
|
import React from 'react';
import ReactDOM from 'react-dom';
import './styles/css/index.css'; // Include in CSS from SASS
import {createStore} from 'redux';
import rootReducer from './redux/reducer';
import {Provider} from 'react-redux';
import Main from './components/Main';
const store = createStore(rootReducer);
ReactDOM.render(<Provider store={store}><Main /></Provider>, document.getElementById('root'));
|
'use strict';
angular.module('liztApp')
.filter('date', function () {
return function (input) {
if (!input) {
return '';
}
var date = moment(input);
return date.fromNow();
};
});
|
$(document).ready(function() {
$('#confirmButton').click(processSaving);
$('.ajaxlink').click(function() {
$.ajax({
url: this,
type: 'GET',
success: function(data) {
success(data);
}
});
});
$('.overlay-bg').hide();
$('.show-popup').click(function(event) {
event.preventDefault();
var uri = this.toString();
var id = uri.substring(uri.lastIndexOf("/") + 1);
$.ajax({
url: this,
type: 'GET',
success: function(data) {
if (uri.indexOf("describeTrainType") != -1) {
overlayTrainTypes(data, id);
}
if (uri.indexOf("describePath") != -1) {
overlayPaths(data, id);
}
if (uri.indexOf("viewPassengers") != -1) {
overlayPassengers(data, id);
}
}
});
var docHeight = $(document).height();
var scrollTop = $(window).scrollTop(); //grab the px value from the top of the page to where you're scrolling
$('.overlay-bg').show().css({'height': docHeight}); //display your popup and set height to the page height
$('.overlay-content').css({'top': scrollTop + 20 + 'px'}); //set the content 20px from the window top
});
$('.close-btn').click(function() {
$("#overlay-header").html('');
$("#overlay-table").html('');
$('.overlay-bg').hide(); // hide the overlay
});
$('.overlay-bg').click(function() {
$("#overlay-header").html('');
$("#overlay-table").html('');
$('.overlay-bg').hide();
})
$('.overlay-content').click(function() {
return false;
});
});
function success(data) {
if (data.id == null) {
$("#train-header").html("<h3>Train: new train</h3>");
} else {
$("#train-header").html("<h3>Train: " + data.id + "</h3>");
}
$("#train-id").val(data.id);
var date = new Date(data.date);
var y = date.getFullYear();
var m = date.getMonth() + 1;
var d = date.getDate;
if (m < 10)
m = "0" + m;
if (d < 10)
d = "0" + d;
var newDate = y + "-" + m + "-" + d;
$("#train-type-select").val(data.trainTypeId);
$("#path-select").val(data.pathId);
$("#date").val(newDate);
$("#free-seats-label").html("<td colspan=\"2\">Free seats: " + data.freeSeats + "</td>");
}
function overlayTrainTypes(data, id) {
var overlayHeader = "<h3>Train type: " + id + "</h3>";
var tableHeader = "<tr><th width=\"100px\">id</th>\n\
<th width=\"200px\">Type</th>\n\
<th width=\"200px\">Cost multiplier</th>\n\
<th width=\"200px\">Max seats</th>\n";
var tableBody = "<tr><td>" + data.id + "</td>\n"
+ "<td>" + data.type + "</td>\n"
+ "<td>" + data.costMultiplier + "</td>\n"
+ "<td>" + data.maxSeats + "</td></tr>";
$("#overlay-header").html(overlayHeader);
$("#overlay-table").html(tableHeader + tableBody);
}
function overlayPaths(data, id) {
var overlayHeader = "<h3>Path: " + id + "</h3>";
var tableHeader = "<tr><th width=\"10%\">Number</th>\n\
<th width=\"20%\">Station</th>\n\
<th width=\"20%\">Time</th></tr>\n";
var tableBody = ''
for (var i in data) {
var time = new Date(data[i].time);
var h = time.getHours();
var m = time.getMinutes();
var tableBody = tableBody +
"<tr><td>" + data[i].number + "</td>\n\
<td>" + data[i].stationName + "</td>\n\
<td>" + h + ":" + m + "</td></tr>";
}
$("#overlay-header").html(overlayHeader);
$("#overlay-table").html(tableHeader + tableBody);
}
function overlayPassengers(data, id) {
var overlayHeader = "<h3>Train: " + id + "</h3>";
var tableHeader = "<tr><th width=\"100px\">Ticket id</th>\n\
<th width=\"150px\">Name</th>\n\\n\
<th width=\"150px\">Second name</th>\n\\n\
<th width=\"100px\">Passport</th>\n\
</tr>\n";
var tableBody = '';
for (var i in data) {
tableBody = tableBody +
"<tr><td>" + data[i].ticketId + "</td>\n\
<td>" + data[i].name + "</td>\n\
<td>" + data[i].secondName + "</td>\n\
<td>" + data[i].passport + "</td>\n\
</tr>";
}
$("#overlay-header").html(overlayHeader);
$("#overlay-table").html(tableHeader + tableBody);
}
function processSaving() {
var trainId = $('#train-id').val();
var trainTypeId = $('#train-type-select option:selected').val();
var trainTypeType = $('#train-type-select option:selected').text();
var pathId = $('#path-select option:selected').val();
var date = $("#date").val();
$.post('/railwayWeb/trains/addTrain',
{
id: trainId,
trainTypeId: trainTypeId,
trainTypeType: trainTypeType,
pathId: pathId,
dateString: date
},
function(data) {
window.location.replace("/railwayWeb/trains")
});
}
|
import React, {Component} from 'react';
import axios from 'axios';
import {getData, GetSubRedditByHot} from './RedditApi'
class Cmp1 extends Component{
constructor(...args){
super(...args);
this.state={
users: []
}
}
// async componentDidMount(){
// try{
// let {data}=await axios.get('../data/data.json');
// this.setState({
// users: data
// });
// }catch(e){
// alert('刷新');
// }
// }
async componentDidMount(){
//let res=await fetch('../data/data.json');
// let res=await fetch('./data.json');
// let data=await res.json();
let data=await getData("canada");
data.forEach(element => {
console.log(element.title);
});
console.log('==================');
let data2=await GetSubRedditByHot("china");
data2.forEach(element => {
console.log(element.title);
});
this.setState({
users: data
});
}
render(){
return (
<ul>
{this.state.users.map((user, index)=>(
<li key={index}>{user.user}, {user.password}</li>
))}
</ul>
);
}
}
export default Cmp1;
|
// =======================================================================
// Modified Copy of TechTSP's MASTER_FILES/index.js
// =======================================================================
// global state/variables: must be set before calling qs_start_doc
// most are kept the same for all page sets
//
// CONVENTIONS:
// -----------
// IMAGES:
// img directory for images
// img/trans.gif: transparent one pixel image
// img/qsbg.jpg: height 1px, width=real wide, 2pixel in color scheme color
// img/qslogo.jpg: logo adapted to color scheme
//
// COLOR VARIABLES
// var qs_page_color: scheme's foreground color
// var qs_link_color: scheme's foreground color
// var qs_link_hover: color sufficiently diffent from foregound color
// var qs_background_color: color scheme foreground color
// var qs_background: color used for off white background in bckground image
// img/qspagecolor.jpg 1 pixel in color scheme color
//
// MENU
// the menu is build on the basis of the global qs_menu_target array variable
// the function qs_build_menu_table builds the main menu on the left of the
// web page, qs_menu_across builds the menu references at the bottom of the
// page. qs_location and qs_location_ref are helper fcts. All these functions// are specific to page sets
//
// A minimal web page with menu is build as follows:
// 1) include this file
// 2) add script section with:
// qs_path = <PATH to this file";
// qs_doc_start('Menu Item', 'Submenuitem');
// qs_body_start(true);
// html();
// 3) page contents
// 4) script section with
// qs_doc_finish("DATE");
// html();
//
// A minimal web page without menu is build as follows:
// 1) include this file
// 2) add script section with:
// qs_path = <PATH to this file";
// qs_img_doc_start('Menu Item', 'Submenuitem', 'headline');
// html();
// 3) page contents
// 4) script section with
// qs_img_doc_finish("DATE");
// html();
//
// optionally the following functions may be called:
// qs_doc_title(text) == set the title to text instead of default string
// qs_doc_headline(text) == underline headline at beginning of page contents
//
// qs_row_spacer(w, h) == add a transparent spacer row, sizes are in pixels
// maybe called just before qs_doc_finish
// qs_menu_set_bling_html(html) == insert html above menu
// ---------------------------------------------------------------------
// ---------------------------------------------------------------------
// these variables are rarely changed
var qs_trans_img = 'img/trans.gif';
var qs_page_width = 800;
var qs_body_width = 632;
var qs_spacer_dist = 12;
// qspath the path to this file relative to the including file
var qs_path = '.';
var qs_mcmTheater_jar = "jar/mcmTheater.jar";
// these vars are the same for whole sets of pages
// paths are givemn relative to this_location/qs_path
var qs_dot_img = 'img/qsdot.png';
var qs_background_img = 'img/qsbg.jpg';
var qs_background_color = '#f7f2f6';
var qs_color_img = 'img/qspagecolor.jpg';
var qs_link_hover = '#8c2633'; // concorde red
var qs_link_hover = '#ff8e05'; // orangy
var qs_page_color = '#336799';
var qs_link_color = qs_page_color;
var qs_link_visited = qs_page_color;
var qs_link_hover = '#ef791f';
var qs_code_color = "#e6e6e6";
var qs_lesson_code_padding = 8;
var qs_line_size = 14;
var qs_my_location = "UNDEFINED MY LOCATION";
var qs_my_menu = "UNDEFINED";
var qs_my_sub_menu = "UNDEFINED SUB MENU";
var qs_menu_bling_bling;
function qs_init_vars(menu_loc, sub_menu_loc, tit)
{
qs_dot_img = qs_path + '/' + qs_dot_img;
qs_background_img = qs_path + '/' + qs_background_img;
qs_color_img = qs_path + '/' + qs_color_img;
qs_trans_img = qs_path + '/' + qs_trans_img;
qs_mcmTheater_jar = qs_path + "/" + qs_mcmTheater_jar;
qs_my_location = qs_location(menu_loc, sub_menu_loc);
qs_my_menu = menu_loc;
qs_my_sub_menu = sub_menu_loc;
}
// ---------------------------------------------------------------------
// Menu definition
// is the same for a whole set of pages
// ---------------------------------------------------------------------
var qs_menu_target = new Array();
var qs_menu_image = new Array();
qs_menu_target[qs_location('MCM Theater Home', undefined)] = "index.html";
qs_menu_target[qs_location("MCM Basics", undefined)] = "basics/index.html";
qs_menu_target[qs_location("MCM Basics", 'Moving')] = "basics/move.html";
qs_menu_target[qs_location("MCM Basics", 'Movement Speed')] = "basics/moveSpeed.html";
qs_menu_target[qs_location("MCM Basics", 'Turning')] = "basics/turn.html";
qs_menu_target[qs_location("MCM Basics", 'Jumping')] = "basics/jump.html";
qs_menu_target[qs_location("MCM Basics", 'TrailColor/Width')] = "basics/colorWidth.html";
qs_menu_target[qs_location("MCM Basics", 'Shapes')] = "basics/shapes.html";
qs_menu_target[qs_location("MCM Basics", 'Time')] = "basics/time.html";
qs_menu_target[qs_location("MCM Basics", 'Multiple Actors')] = "basics/multiple.html";
qs_menu_target[qs_location("Step By Step", undefined)] = "stepByStep/index.html";
qs_menu_target[qs_location("Step By Step", 'A First Program')] = "stepByStep/sy/index.html";
qs_menu_target[qs_location("Step By Step", 'Bouncers')] = "stepByStep/bouncer/index.html";
qs_menu_target[qs_location("Step By Step", 'Triangles ...')] = "stepByStep/shapes/index.html";
qs_menu_target[qs_location("Step By Step", 'Jumpers')] = "stepByStep/jumpers/index.html";
qs_menu_target[qs_location("Step By Step", 'Generators')] = "stepByStep/generators/index.html";
qs_menu_target[qs_location("Step By Step", 'Draw Squares')] = "stepByStep/drawSquares/index.html";
qs_menu_target[qs_location("Gallery", undefined)] = "gallery/index.html";
qs_menu_target[qs_location("Gallery", 'Attraction')] = "gallery/attraction.html";
qs_menu_target[qs_location("Gallery", 'Follow The Leader')] = "gallery/follower.html";
qs_menu_target[qs_location("Gallery", 'Spirals')] = "gallery/spirals.html";
qs_menu_target[qs_location("Gallery", 'Growing Shapes')] = "gallery/growAndClone.html";
qs_menu_target[qs_location("Gallery", 'Marching Blocks')] = "gallery/marching.html";
qs_menu_target[qs_location("Gallery", 'Mona Lisa')] = "gallery/monaLisa.html";
qs_menu_target[qs_location("Gallery", 'Falling Leafs')] = "gallery/leafs.html";
qs_menu_target[qs_location("Gallery", 'Boat Collage')] = "gallery/boat.html";
qs_menu_target[qs_location("Gallery", 'Pulsing Circle')] = "gallery/jumpMove.html";
qs_menu_target[qs_location("Gallery", 'Circle Segments')] = "gallery/shootLines.html";
qs_menu_target[qs_location("Gallery", 'Exponential Growth')] = "gallery/exponential.html";
qs_menu_target[qs_location("Gallery", 'Galloway')] = "class/2006.galloway/index.html";
qs_menu_target[qs_location("Games", undefined)] = "games/index.html";
qs_menu_target[qs_location("JavaDoc", undefined)] = "javadoc/index.html";
qs_menu_target[qs_location("Downloads", undefined)] = "downloads/index.html";
qs_menu_target[qs_location("DrJava", undefined)] = "drJava/index.html";
qs_menu_target[qs_location("Contact", undefined)] = "contact/index.html";
qs_menu_image[qs_location('MCM Theater Home', undefined)] = "spiralToss";
qs_menu_image[qs_location("MCM Basics", undefined)] = "rectangles";
qs_menu_image[qs_location("MCM Basics", 'Moving')] = "followTheLeader";
qs_menu_image[qs_location("MCM Basics", 'Movement Speed')] = "wheel";
qs_menu_image[qs_location("MCM Basics", 'Turning')] = "spiralToss";
qs_menu_image[qs_location("MCM Basics", 'Jumping')] = "spiralJump";
qs_menu_image[qs_location("MCM Basics", 'TrailColor/Width')] = "widthColorSquareJump";
qs_menu_image[qs_location("MCM Basics", 'Shapes')] = "balloons";
qs_menu_image[qs_location("MCM Basics", 'Time')] = "HalfCircles17";
qs_menu_image[qs_location("MCM Basics", 'Multiple Actors')] = "MarchingLine";
qs_menu_image[qs_location("Step By Step", undefined)] = "HalfCircles5";
//qs_menu_image[qs_location("Step By Step", 'Bouncers')] = "balloons";
//qs_menu_image[qs_location("Step By Step", 'Triangles ...')] = "balloons";
//qs_menu_image[qs_location("Step By Step", 'Jumpers')] = "growSquares";
//qs_menu_image[qs_location("Step By Step", 'Generators')] = "balloons";
//qs_menu_image[qs_location("Step By Step", 'Draw Squares')] = "rectangles";
qs_menu_image[qs_location("Gallery", undefined)] = "bubbles";
qs_menu_image[qs_location("Gallery", "Attraction")] = "followTheLeader";
qs_menu_image[qs_location("Gallery", "Follow The Leader")] = "followTheLeader";
qs_menu_image[qs_location("Gallery", "Boat Collage")] = "balloons";
qs_menu_image[qs_location("Gallery", "Pulsing Circle")] = "HalfCircles10";
qs_menu_image[qs_location("Gallery", "Circle Segments")] = "cornerShooter";
qs_menu_image[qs_location("Gallery", "Spirals")] = "spiralToss";
qs_menu_image[qs_location("Gallery", "Growing Shapes")] = "growSquares";
qs_menu_image[qs_location("Gallery", "Marching Blocks")] = "bubblesSolid";
qs_menu_image[qs_location("Gallery", "Mona Lisa")] = "HalfCircles8";
qs_menu_image[qs_location("Gallery", "Falling Leafs")] = "HalfCircles17";
qs_menu_image[qs_location("Gallery", 'Exponential Growth')] = "bubbles";
qs_menu_image[qs_location("Gallery", 'Galloway')] = "rectangles";
qs_menu_image[qs_location("Games", undefined)] = "bubbles";
qs_menu_image[qs_location("Downloads", undefined)] = "widthColorSquareJump";
qs_menu_image[qs_location("DrJava", undefined)] = "widthColorSquareJump";
qs_menu_image[qs_location("Contact", undefined)] = "widthColorSquareJump";
function qs_ref_menu_item(txt, menu, sub_menu)
{
return qs_menu_ref(qs_my_location, qs_location(menu, sub_menu), txt);
}
// PRIVATE (specific to page set)
function qs_build_menu_table(menu_loc, sub_menu_loc)
{
wd(qs_table_start(0, undefined));
if (qs_menu_bling_bling != undefined) {
qs_menu_insert_bling_bling(qs_menu_bling_bling);
wd(qs_row_spacer(4));
qs_menu_separator(qs_color_img)
}
qs_menu_item(menu_loc, sub_menu_loc, 'MCM Theater Home', undefined);
qs_menu_separator(qs_color_img)
if (qs_menu_item(menu_loc, sub_menu_loc, 'MCM Basics', undefined)) {
qs_menu_item(menu_loc, sub_menu_loc, 'MCM Basics', 'Moving');
qs_menu_item(menu_loc, sub_menu_loc, 'MCM Basics', 'Movement Speed');
qs_menu_item(menu_loc, sub_menu_loc, 'MCM Basics', 'Turning');
qs_menu_item(menu_loc, sub_menu_loc, 'MCM Basics', 'Jumping');
qs_menu_item(menu_loc, sub_menu_loc, 'MCM Basics', 'TrailColor/Width');
qs_menu_item(menu_loc, sub_menu_loc, 'MCM Basics', 'Shapes');
qs_menu_item(menu_loc, sub_menu_loc, 'MCM Basics', 'Time');
qs_menu_item(menu_loc, sub_menu_loc, 'MCM Basics', 'Multiple Actors');
}
qs_menu_separator(qs_color_img)
if (qs_menu_item(menu_loc, sub_menu_loc, 'Step By Step', undefined)) {
qs_menu_item(menu_loc, sub_menu_loc, 'Step By Step', 'Bouncers');
qs_menu_item(menu_loc, sub_menu_loc, 'Step By Step', 'Draw Squares');
qs_menu_item(menu_loc, sub_menu_loc, 'Step By Step', 'Triangles ...');
qs_menu_item(menu_loc, sub_menu_loc, 'Step By Step', 'A First Program');
qs_menu_item(menu_loc, sub_menu_loc, 'Step By Step', 'Jumpers');
qs_menu_item(menu_loc, sub_menu_loc, 'Step By Step', 'Generators');
}
qs_menu_separator(qs_color_img)
if (qs_menu_item(menu_loc, sub_menu_loc, 'Gallery', undefined)) {
qs_menu_item(menu_loc, sub_menu_loc, 'Gallery', 'Falling Leafs');
qs_menu_item(menu_loc, sub_menu_loc, 'Gallery', 'Mona Lisa');
qs_menu_item(menu_loc, sub_menu_loc, 'Gallery', 'Boat Collage');
qs_menu_item(menu_loc, sub_menu_loc, 'Gallery', 'Galloway');
qs_menu_item(menu_loc, sub_menu_loc, 'Gallery', 'Pulsing Circle');
qs_menu_item(menu_loc, sub_menu_loc, 'Gallery', 'Circle Segments');
qs_menu_item(menu_loc, sub_menu_loc, 'Gallery', 'Spirals');
qs_menu_item(menu_loc, sub_menu_loc, 'Gallery', 'Growing Shapes');
qs_menu_item(menu_loc, sub_menu_loc, 'Gallery', 'Marching Blocks');
qs_menu_item(menu_loc, sub_menu_loc, 'Gallery', 'Attraction');
qs_menu_item(menu_loc, sub_menu_loc, 'Gallery', 'Follow The Leader');
qs_menu_item(menu_loc, sub_menu_loc, 'Gallery', 'Exponential Growth');
}
qs_menu_separator(qs_color_img)
qs_menu_item(menu_loc, sub_menu_loc, 'Games', undefined);
qs_menu_separator(qs_color_img)
qs_menu_item(menu_loc, sub_menu_loc, 'JavaDoc', undefined);
qs_menu_separator(qs_color_img)
qs_menu_item(menu_loc, sub_menu_loc, 'DrJava', undefined);
qs_menu_separator(qs_color_img)
qs_menu_item(menu_loc, sub_menu_loc, 'Downloads', undefined);
qs_menu_separator(qs_color_img)
qs_menu_item(menu_loc, sub_menu_loc, 'Contact', undefined);
wd(qs_table_finish());
}
// PRIVATE (specific to page set)
function qs_menu_across()
{
cur_loc = qs_location(qs_my_menu, qs_my_sub_menu);
wd(qs_menu_ref(cur_loc, qs_location('MCM Theater Home', undefined),
'MCM Theater Home'));
}
// PRIVATE (specific to page set)
function qs_dot()
{
return '<img src=' + qs_dot_img + " align=middle>";
}
function qs_location(item_text, sub_item_text )
{
loc = 'MCM Theater Home';
if (item_text != 'MCM Theater Home') {
loc += ' > ' + item_text;
}
if (sub_item_text != undefined) {
loc += ' > ' + sub_item_text;
}
return loc;
}
// PRIVATE (specific to page set)
function qs_location_ref(item_text, sub_item_text, color)
{
loc = qs_location('MCM Theater Home', undefined);
s = qs_menu_ref(qs_my_location, loc, 'MCM Theater Home', color);
if (item_text != 'MCM Theater Home') {
loc = qs_location(item_text, undefined);
s += ' > ' + qs_menu_ref(qs_my_location, loc, item_text, color);
}
if (sub_item_text != undefined) {
loc = qs_location(item_text, sub_item_text);
s += ' > ' + qs_menu_ref(qs_my_location, loc, sub_item_text, color);
}
if (color != undefined) {
s = '<font color=' + color + '>' + s + '</font>';
}
return s;
}
// =======================================================================
// =======================================================================
// =======================================================================
// from here on it's the same for all page sets
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
// always need an undefined
// -----------------------------------------------------------------------
var undefined;
// ---------------------------------------------------------------------------
// table
// ---------------------------------------------------------------------------
var number_of_open_tables = 0;
// table with colored background
function qs_colored_table_start(padding, framecolor, tableWidth, extra)
{
if (extra == undefined)
extra = " ";
if (framecolor == undefined)
framecolor = qs_page_color;
if (tableWidth == undefined) {
tableWidth = "";
} else {
tableWidth=" width=" + tableWidth;
}
number_of_open_tables = number_of_open_tables + 1;
return ('<TABLE cellpadding=' + padding + ' cellspacing=0 border=0 bgcolor=' +
framecolor + tableWidth + " " + extra + '>');
}
function qs_framed_table_start(frameWidth, framecolor, tableColor,
tableWidth, tableHeight, extra)
{
if (extra == undefined)
extra = " ";
if (tableHeight == undefined) {
tableHeight=" ";
} else {
tableHeight=" height=" + tableHeight + " " ;
}
tableSmallWidth = tableWidth;
if (tableWidth != undefined)
tableSmallWidth= tableWidth - 2;
s = qs_colored_table_start(frameWidth, framecolor,
tableWidth, tableHeight + extra) +
"<TR><TD>" +
qs_table_start(0, tableSmallWidth, 'bgcolor=' + tableColor +
' height=100%');
return s;
}
function qs_framed_table_finish()
{
return qs_table_finish() +
"</TD></TR>" +
qs_table_finish();
}
function qs_table_start(b, w, extra)
{
number_of_open_tables = number_of_open_tables + 1;
width = "";
if (w != undefined) {
width = " width=" + w ;
}
if (extra == undefined) { extra = ""; }
s = '<table cellpadding=0 cellspacing=0 vspace=0 hspace=0' +
' border=' + b + 'px ' + width + " " + extra + ">";
return s;
}
function qs_table_finish()
{
number_of_open_tables--;
return "</table>";
}
function qs_tr(html, extra)
{
if (extra == undefined) extra = "";
s = "<TR " + extra + "> " + html + "</TR>";
return s;
}
function qs_td(html, extra)
{
if (extra == undefined) extra = "";
s = "<TD " + extra + "> " + html + "</TD>";
return s;
}
function qs_row_spacer(height)
{
if (height == undefined) {
height = qs_spacer_dist;
}
return '<tr><td ' + qs_debug_color() + '>' +
qs_spacer_img(1, height, qs_trans_img) +
'</td></tr>';
}
function qs_col_spacer(w, h, colsp, extra)
{
var span = '';
if (extra == undefined) extra = "";
if (colsp != undefined && colsp != 1) span = ' colspan=' + colsp;
return('<td ' + span + ' ' + extra + ' width=' + w + 'px height=' + h + 'px>' +
qs_spacer_img(w, h, qs_trans_img) + '</td>');
}
function qs_horz_table(left_html, right_html, spacing, extra)
{
if (spacing == undefined) spacing = 24;
return (qs_table_start(0, extra)) +
(qs_tr(qs_td(left_html, 'valign=top') +
qs_col_spacer(spacing, 1) +
qs_td(right_html, 'valign=top'))) +
(qs_table_finish());
}
function qs_vert_table(top_html, bottom_html, spacing, extra)
{
if (spacing == undefined) spacing = 24;
return (qs_table_start(0, extra)) +
(qs_tr(qs_td(top_html))) +
(qs_row_spacer(spacing)) +
(qs_tr(qs_td(bottom_html))) +
(qs_table_finish());
}
// ----------------------------------------------------------------------------
// generators for <a href= ....
// ----------------------------------------------------------------------------
function qs_goto_link(location) {
try {
document.location.href=location;
} catch (e) {;}
}
function qs_reload(txt)
{
return qs_ref(txt, "JavaScript:window.location.reload()", "Reload");
}
function qs_go_back_ref(txt)
{
return "<a href=javascript:history.back();>" + txt + "</a>";
}
function qs_ref(text, target, status)
{
if (target == undefined)
return " ";
s = "<a href='" + target + "'";
if (status == undefined) {
status = target;
}
s += ' onMouseOver="window.status=\'' + status + '\'; return true;" ' +
' onMouseOut="window.status=\'' + qs_my_location + '\'; return true;"';
s += ">" + text + "</a>";
return s;
}
// ----------------------------------------------------------------------------
// utility fcts
// ----------------------------------------------------------------------------
function qs_spacer_img(w, h, img)
{
return '<img src=' + img + ' height=' + h + 'px ' +
'width=' + w + 'px>';
}
function qs_color_txt(html)
{
return qs_font_color() + html + "</font>";
}
function qs_font_color(sz)
{
if (sz != undefined) {
size = 'size=' + sz;
} else {
size = '';
}
//return '<font ' + size + '>';
return '<font ' + size + ' color=' + qs_page_color + '>';
}
function qs_indent(pix)
{
if (pix == undefined)
pix = qs_spacer_dist;
qs_body_width -= pix;
return qs_table_start(0) + "<TR>" + qs_col_spacer(pix, 1) + "<TD>";
}
function qs_unindent(pix)
{
if (pix == undefined)
pix = qs_spacer_dist;
qs_body_width += pix;
return "</TD></TR>" + qs_table_finish();
}
// ---------------------------------------------------------------------------
// support for qs_menu function
// ---------------------------------------------------------------------------
function qs_menu_ref(cur_loc, item_loc, text, color)
{
if (color == undefined) {
precolor = '';
postcolor = '';
} else {
precolor = '<font color=' + color + '>';
postcolor = '</font>';
}
var href = new String(qs_menu_target[item_loc]);
if (href.match(/^http:/)) {
target_file = href;
} else {
target_file = qs_path + "/" + qs_menu_target[item_loc];
}
s = ('<a href=' + target_file + ' ' +
'onMouseOver="window.status=\'' + item_loc + '\'; return true;" ' +
'onMouseOut="window.status=\'' + cur_loc + '\'; return true;">' +
precolor + text + postcolor + '</a>');
return s;
}
function qs_menu_item(cur_menu, cur_sub_menu, item_text, sub_item_text)
{
cur_loc = qs_location(cur_menu, cur_sub_menu);
item_loc = qs_location(item_text, sub_item_text);
target_file = qs_path + "/" + qs_menu_target[item_loc];
subitem = (sub_item_text != undefined);
istext = (item_loc == cur_loc);
color = qs_page_color;
if (subitem) {
text = sub_item_text;
} else {
text = item_text;
}
if (istext) {
ptr = '> ';
//ptr = qs_dot() + " "
} else {
ptr = ' ';
}
wd('<tr>');
wd(qs_col_spacer(8,1, 1));
wd(qs_col_spacer(8,1, 1));
wd('<td width=16px><font color=' + color + '>' + ptr + '</font></td>');
if (subitem) {
wd(qs_col_spacer(16,1, 1));
wd('<td align=left>');
} else {
wd('<td colspan=2 align=left>');
}
wd(qs_menu_ref(cur_loc, item_loc, text));
wd('</td></tr>');
return (cur_menu == item_text);
}
function qs_menu_separator(color_img)
{
wd('<tr>');
wd(qs_col_spacer(8,1, 1));
wd('<td colspan=4 height=16px>' +
'<img src=' + color_img + ' width=144px height=2px>' +
'</td>');
wd('</tr>');
}
function qs_menu_insert_bling_bling(html)
{
wd('<tr>');
wd(qs_col_spacer(8,1, 1));
wd('<td colspan=4 width=144px>');
wd(html);
wd('</td></tr>');
}
// --------------------------------------------------------------------------
// fcts used in page building
// --------------------------------------------------------------------------
var qs_do_head = true;
// EXPORTED; used in pages that request non default title
function qs_doc_title(str)
{
if (qs_do_head) {
wd('<meta content="text/html; charset=ISO-8859-1 ' +
'http-equiv="content-type">' +
'<title>' + str + '</title>' +
'</head>');
qs_do_head = false;
}
}
// EXPORTED
function qs_menu_set_bling_html(html)
{
qs_menu_bling_bling = html;
}
// EXPORTED
var qs_header_image;
function qs_set_header_image(img) {
qs_header_image = img;
}
function qs_get_header_image() {
if (qs_header_image == undefined)
qs_header_image = qs_menu_image[qs_my_location];
if (qs_header_image != undefined)
s = '<img src=' + qs_path + '/img/header/' + qs_header_image + '.png>';
else
s = '<img src=' + qs_color_img + " width=792px height=12px>";
return s;
}
function qs_doc_start(menu_loc, sub_menu_loc, dotitle, tit) {
// init vars and build top of page
qs_determine_browser();
qs_doc_setup(menu_loc, sub_menu_loc, true, dotitle, tit);
wd(qs_table_start(0, undefined));
qs_doc_row(1, qs_page_color);
wd(qs_row_spacer(6));
// setup doc line
// menu in first 2 cols on left, page content in 2 cols on right
wd('<tr>');
wd('<td valign=top ' + qs_debug_color() + 'colspan=2 rowspan=100>');
qs_build_menu_table(qs_my_menu, qs_my_sub_menu);
wd('</td>');
wd('<td rowspan=100 width=16px ' + qs_debug_color() + '>'+
'<img src=' + qs_trans_img + '></td>');
// page content in its on table
wd('<td colspan=2>' + qs_table_start(0, qs_body_width, qs_debug_color()));
html();
}
// EXPOERTED
function qs_doc_headline(left)
{
if (left != undefined) {
wd('<tr><td align=left>' + qs_font_color() + left + '</font></td></tr>');
}
html();
}
// EXPORTED
function qs_body_start(with_underline)
{
if (with_underline) {
qs_line(true);
wd('<tr><td height=8px>' +
qs_spacer_img(qs_body_width, 2, qs_trans_img) +
'</td></tr>');
}
wd('<tr><td width=100% valign=top>');
wd(qs_indent(8));
html(); // spit out HTML before <SCRIPT> section is ended
// main page content lives in one table element
}
// EXPORTED
function qs_doc_finish(date, spacing)
{
//wd('</td></tr>' + qs_table_finish()); // end of main page contents
wd(qs_unindent(8));
wd('</td></tr>');
if (spacing == undefined) {
spacing = 36;
}
if (spacing < 0) {
spacing = 36;
}
wd(qs_row_spacer( spacing));
qs_line(true);
wd('<TR><TD>');
wd(qs_table_start(0, qs_body_width));
wd('<tr><td align=left ' + qs_debug_color() + '>');
qs_menu_across();
wd('</td>');
wd('<td align=right' + qs_debug_color() + '>');
wd(qs_go_back_ref("Back"));
wd('</td>');
wd('</tr>');
if (date != undefined) {
wd(qs_row_spacer(4));
wd('<tr' + qs_debug_color() + '>' +
'<td colspan=2 align=right>' + qs_font_color(-2) +
' Last Updated: ' + date +
'</font></td></tr>');
}
wd(qs_table_finish(0));
wd('</TD></TR>');
wd(qs_row_spacer( 8));
wd(qs_table_finish());
wd(qs_table_finish());
wd('</body>');
//alert("open table=" + number_of_open_tables);
html();
}
function qs_doc_setup(menu_loc, sub_menu_loc, dobg, dohead, tit)
{
if ((dohead != undefined) && (dohead != true)) {
qs_do_head = false;
}
// alert(menu_loc + '\n' +
// sub_menu_loc + '\n' +
// 'bg=' + dobg + '\n' +
// 'head=' + dohead + '\n' +
// 'dohead=' + qs_do_head + '\n' +
// 'tit=' + tit);
qs_init_vars(menu_loc, sub_menu_loc, tit);
window.status = qs_my_location;
if (tit != undefined) {
tit = ' ' + tit ;
} else {
tit = '';
}
qs_doc_title(qs_my_location + tit);
bgimg = '';
if (dobg) {
bgimg = 'background=' + qs_background_img;
} else {
bgimg = 'bgcolor=' + qs_background_color;
}
wd('<body ' + bgimg +
' link=' + qs_link_color +
' alink=' + qs_link_hover +
' vlink=' + qs_link_visited +
' leftmargin=0 topmargin=0' +
' marginheight=0 marginwidth=0 >');
// The Page is a table: with the following row layout
// | 8 | 144 | 16 | 616=qs_body_width over 2 cols
// the logo takes up col 1,2,3 over two rows
// the color bar extends on the lower row next to the logo in col 4
// the menu takes up he first two columns
// the document body is inside a table that takes up grid entry 4,4
wd(qs_table_start(0, undefined, "width=" + qs_page_width));
qs_doc_row(6, qs_page_color);
// shows current location
wd('<tr bgcolor=' + qs_page_color + '>' );
wd(qs_col_spacer(8, 1, 1) );
wd(qs_col_spacer(144, 1, 1) );
wd(qs_col_spacer(16, 1, 1) );
wd('<td width=' + qs_body_width + 'px align=right>' +
qs_location_ref(qs_my_menu, qs_my_sub_menu, qs_background_color) +
qs_spacer_img(6, 1, qs_trans_img) +
'</td>');
wd('</tr>');
// page color row
wd('<tr>' );
wd(qs_col_spacer(1, 6, 4, 'bgcolor=' + qs_page_color) );
wd('</tr>');
// background color row
wd('<tr>' );
wd(qs_col_spacer(1, 1, 4, 'bgcolor=' + qs_background_color) );
wd('</tr>');
// page color row
wd('<tr>' );
wd(qs_col_spacer(1, 3, 4, 'bgcolor=' + qs_page_color) );
wd('</tr>');
var header_img = qs_get_header_image();
if (header_img != undefined) {
wd('<tr>' +
'<td colspan=4 bgcolor=red>' +
qs_spacer_img(3, 1, qs_color_img) +
qs_spacer_img(qs_page_width - 6, 1, qs_background_img) +
qs_spacer_img(3, 1, qs_color_img) +
'<TD>' +
'</tr>');
// the show applet image
wd('<tr><td colspan=4 bgcolor=green>');
wd(qs_table_start(0, undefined));
wd('<tr bgcolor=' + qs_page_color + '>' +
qs_col_spacer(3, 1, 1) +
qs_col_spacer(1, 1, 1, 'bgcolor=' + qs_background_color) +
'<td width=' + (qs_page_width - 8) + '>' + header_img + '</td>' +
qs_col_spacer(1, 1, 1, 'bgcolor=' + qs_background_color) +
qs_col_spacer(3, 1, 1) +
'</tr>');
wd(qs_table_finish());
wd('</td></tr>');
wd('<tr>' +
'<td colspan=4 bgcolor=red>' +
qs_spacer_img(3, 1, qs_color_img) +
qs_spacer_img(qs_page_width - 6, 1, qs_background_img) +
qs_spacer_img(3, 1, qs_color_img) +
'<TD>' +
'</tr>');
}
wd('<tr>' );
wd(qs_col_spacer(1, 3, 4, 'bgcolor=' + qs_page_color) );
wd('</tr>');
//wd(qs_row_spacer(8));
wd(qs_table_finish());
}
function qs_doc_row(height, color)
{
// page color row and table setup
wd('<tr bgcolor=' + color + '>' );
wd(qs_col_spacer(8, height, 1) );
wd(qs_col_spacer(144, height, 1) );
wd(qs_col_spacer(16, height, 1) );
wd(qs_col_spacer(qs_body_width, height, 1) );
wd('</tr>');
}
function qs_line(visible)
{
img = qs_color_img;
wd('<tr' + qs_debug_color() + '>' +
'<td height=16px><img width=' + qs_body_width + 'px height=2px src=' + img + '>' +
'</td></tr>');
}
// -----------------------------------------------------------------------
// htm text gathering fcts
// -----------------------------------------------------------------------
var html_text = '';
// EXPORTED
function wd(s) { html_text += s + '\n'; }
// EXPORTED
function html_get() {
s = html_text;
html_text = '\n';
return s;
}
// EXPORTED
function alerthtml() {
alert(html_text);
html();
}
// EXPOERTED
function html() {
document.writeln(html_text);
html_text = '\n';
}
// -----------------------------------------------------------------------
// debugging support
// -----------------------------------------------------------------------
function handle_error(msg, url)
{
file = new String(url);
if (file.length > 40) {
file = "..." + file.substring(file.length-40);
}
alert(file + ": \n" + msg);
}
window.onerror = handle_error;
var debug_color_index = 0;
var debug_color = new Array();
debug_color[0] = "red";
debug_color[1] = "green";
debug_color[2] = "blue";
debug_color[8] = "#777777";
debug_color[3] = "yellow";
debug_color[4] = "maroon";
debug_color[7] = "#555555";
debug_color[5] = "purple";
debug_color[6] = "orange";
debug_color[9] = "pink";
function qs_debug_color()
{
return ' ';
// do return s when you want to debug
debug_color_index = debug_color_index + 1;
if (debug_color_index > 9) debug_color_index = 0;
s = ' bgcolor=' + debug_color[debug_color_index] + ' ';
return s;
}
// =======================================================================
// end of general purpose code
// =======================================================================
// =======================================================================
// SPECIFICS FOR TSP HOMEPAGE
// --------------------------------------------------------------------------
// pages style sheet
//
function css_link() {
return('\n<STYLE type="text/css">\n' +
'<!--\n' +
'A { text-decoration: none }\n' +
'A:hover { color: ' + qs_link_hover + '; text-decoration: underline }\n' +
'A {font-family: Arial, Helvetica, Sans-serif; font-size: 12px;}\n' +
'body, P, td, ul, li { font-family: Arial, Helvetica, Sans-serif; font-size: 12px; color: black}\n' +
'\n' +
'.navMenu { font-family: Arial, Helvetica, Sans-serif; font-size: 12px; font-weight: bold; color=white' +
'text-decoration: none; }\n' +
'\n' +
'.postcardLink { color: white; \n' +
' font-family: Arial, Helvetica, Sans-serif; \n' +
' font-size: 12px; font-weight: bold; }\n' +
'\n' +
'a.postcardLink {text-decoration: none; }\n' +
'a.postcardLink:link { color: white; }\n' +
'a.postcardLink:visited { color: white; }\n' +
'a.postcardLink:hover { color: white; text-decoration: underline; }\n' +
'\n-->\n' +
'</STYLE>\n');
}
//----------------------------------------------------------------------------
// applets and mcm lesson building fcts
//----------------------------------------------------------------------------
var qs_applet_id = 0;
var qs_applet_color = qs_background_color;
var qs_applet_frame_color = qs_page_color;
var qs_code_padding = 12;
var qs_jar_path = ".";
function java_src_ref(javaSrc, refText)
{
if (javaSrc == undefined)
return " ";
var file = javaSrc;
file = file.replace(/\./g, "/");
file = file.replace(/\/java/g, ".java");
cur_loc = qs_location(qs_my_menu, qs_my_sub_menu);
if (refText == undefined) {
refText = "JavaSource";
}
return qs_ref(refText, file, file);
}
function qs_applet_restart(applet_name)
{
if (applet_name == undefined) return " ";
return (qs_ref("Restart",
"JavaScript:document." + applet_name + ".stop();" +
//"JavaScript:document." + applet_name + ".init();" +
"JavaScript:document." + applet_name + ".start();",
"Restart Applet"));
}
// make a 2 element table row if
// at least one of javaSr or applet_name is undefined
function qs_tr_src_restart(javaSrc, applet_name)
{
if ((javaSrc == undefined) && (applet_name == undefined))
return ""
return qs_tr(qs_td(java_src_ref(javaSrc), "align=left") +
qs_td(qs_applet_restart(applet_name), "align=right"));
}
// applet framed by a colored table
// return name
// write html with wd fct
// height refers to tabel height
// returns objcte with html and name property
function qs_applet(cls, archive, width, height, params, framecolor, wincolor)
{
var applet = new Object();
if (wincolor == undefined)
wincolor = qs_applet_color;
if (framecolor == undefined)
framecolor = qs_applet_frame_color;
if (params == undefined)
params = '';
applet.name = 'applet_' + qs_applet_id;
qs_applet_id++;
var applet = new Applet(applet_name,
"mcm.theater.Play.class",
"./krtek.jar",
qs_mcmTheater_jar + ", " + qs_jar_path + "/" + archive + ".jar",
width - 6, height - 6);
applet.addParam("ACTOR", cls);
applet.addParam("TRACENAMES", "true");
applet.addParam("BGCOLOR", wincolor);
// params
s = qs_colored_table_start(3, framecolor, width);
s += '<TR><TD>';
s += '<APPLET name=' + applet.name + ' hspace=0 vspace=0 ';
s += ' CODE=mcm.theater.Play.class ARCHIVE="' +
qs_mcmTheater_jar + ", " +
qs_jar_path + "/" + archive + ".jar" + '"\n' ;
s += ' WIDTH=' + (width - 6) + ' HEIGHT=' + (height - 6) + '\n';
s += ' ALT="If you could run this applet, ' +
'you would see some animation">\n';
s += ' <PARAM NAME=ACTOR VALUE="' + cls + '">' + '\n';
s += ' <PARAM NAME=TRACENAMES VALUE="true">' + '\n';
s += ' <PARAM NAME=BG VALUE="' + wincolor + '">' + '\n';
s += ' ' + params + '\n';
s += ' Your browser is completely ignoring the <APPLET> tag!\n';
s += '</APPLET>\n';
s += '</TD></TR>\n';
s += qs_table_finish();
applet.html = s;
return applet;
}
// write formmated code
function qs_code(code, padding, width, height, framecolor) {
wd(qs_code_html(code, padding, width, height, framecolor));
}
// return code formatted inside a framecolor table
// height refers to height of outside table
function qs_code_html(code, padding, width, height, framecolor) {
if (framecolor == undefined)
framecolor = qs_applet_frame_color;
if (padding == undefined) {
padding = qs_code_padding;
}
s = qs_framed_table_start(1, framecolor, qs_code_color, width, height) +
qs_tr(
qs_col_spacer(padding, 1) +
qs_td('<pre>' + code + '</pre>', 'valign=top') +
qs_col_spacer(padding, 1)) +
qs_framed_table_finish();
return s;
}
function qs_applet_src(applet, javaSrc, archive,
width, height, params,
restart, framecolor, wincolor)
{
applet = qs_applet(applet, archive, width, height, params,
framecolor, wincolor);
if (restart != undefined)
restart = applet.name;
applet.html =
qs_table_start(0) +
qs_tr(qs_td(applet.html, "colspan=2")) +
qs_tr_src_restart(javaSrc,restart) +
qs_table_finish();
return applet;
}
function qs_applet_vert_code(applet, javaSrc, archive,
width, height, params, code,
restart, framecolor, wincolor)
{
var applet = qs_applet_src(applet, javaSrc, archive,
width, height, params,
restart, framecolor, wincolor);
applet_code = qs_code_html(code, undefined, width);
return qs_vert_table(
applet.html, //top
applet_code, //bottom
1);
}
function qs_img_horz_code(cls, javaSrc, img,
total_width, img_width, height, code,
restart, framecolor)
{
var width;
if (total_width != undefined) {
width = total_width -img_width - qs_spacer_dist;
if (width < 0) width = undefined;
}
if (framecolor== undefined) {
framecolor = qs_page_color;
}
var imgHtml = qs_colored_table_start(3, framecolor, img_width) +
qs_tr(qs_td("<img src=" + img +
" alt='Image of " + cls + " execution'" +
" border=0px >")) +
qs_table_finish();
var html = qs_table_start(0) +
qs_tr(qs_td(imgHtml)) +
qs_tr(qs_td(java_src_ref(javaSrc))) +
qs_table_finish();
applet_code = qs_code_html(code, undefined, width, height);
return qs_horz_table(html, //top
applet_code, //bottom
qs_spacer_dist);
}
function qs_applet_horz_code(applet, javaSrc, archive,
total_width, applet_width, height, params, code,
restart, framecolor, wincolor)
{
var width;
if (total_width != undefined) {
width = total_width -applet_width - qs_spacer_dist;
if (width < 0) width = undefined;
}
var applet = qs_applet_src(applet, javaSrc, archive,
applet_width, height, params,
restart, framecolor, wincolor);
applet_code = qs_code_html(code, undefined, width, height);
return qs_horz_table(applet.html, //top
applet_code, //bottom
qs_spacer_dist);
}
function qs_applet_info()
{
return "Each actor's statements are shown next to the " +
"applet executing it. Click on the " +
"<font color=" + qs_link_color + ">Restart" + "</font> link under applets " +
"to see them execute all over again. The links labeled " +
"<font color=" + qs_link_color + ">JavaSource</font> show the complete " +
"Java source code file for the actors executing in this page's applets. ";
}
// --------------------------------------------------------------------------
// applet made easier
// --------------------------------------------------------------------------
var applet_width = qs_body_width;
var applet_height = 380;
var applet_frame_color = qs_page_color;
var applet_color = "#ffffff";
function applet_plain(pkg, cls, params, withSrcRef, restart)
{
var archive = pkg;
var applet = pkg + "." + cls ;
var javaSrc;
if (withSrcRef) {
javaSrc = pkg + "/" + cls + ".java";
}
wd(qs_applet_src(applet, javaSrc, archive,
applet_width, applet_height,
params,
restart,
applet_frame_color, applet_color).html);
}
function applet_with_code(pkg, cls, params, code, vert, noRestart)
{
var archive = pkg;
var javaSrc = pkg + "/" + cls + ".java";
var applet = pkg + "." + cls ;
if (noRestart != undefined)
restart = undefined;
else
restart = "Restart";
if (vert == undefined)
var applet = qs_applet_horz_code(
applet, javaSrc, archive,
qs_body_width, applet_width, applet_height,
params, code, restart,
applet_frame_color, applet_color);
else
var applet = qs_applet_vert_code(
applet, javaSrc, archive,
applet_width, applet_height,
params, code, restart,
applet_frame_color, applet_color);
wd(applet);
}
function applet_code(code, width, height) {
wd(qs_code_html(code, undefined, width, height));
}
function applet_replace(c1, word, c2, align)
{
if (align == undefined)
align = "";
wd(qs_table_start(0));
wd("<TR><TD>");
wd(qs_code_html(c1));
wd("</TD>" + qs_col_spacer(4, 1) + "<TD " + align + ">");
wd(word);
wd("</TD>" + qs_col_spacer(4, 1) + "<TD>");
wd(qs_code_html(c2));
wd("</TD></TR>");
wd(qs_table_finish());
}
function qs_determine_browser() {
wd('<SCRIPT LANGUAGE="JavaScript"><!--');
wd('var _info = navigator.userAgent; ');
wd('var _ns = false;');
wd('var _ie = (_info.indexOf("MSIE") > 0 && _info.indexOf("Win") > 0');
wd('&& _info.indexOf("Windows 3.1") < 0);');
wd('//--><\/SCRIPT>');
wd('<COMMENT><SCRIPT LANGUAGE="JavaScript1.1"><!--');
wd('var _ns = (navigator.appName.indexOf("Netscape") >= 0');
wd('&& ((_info.indexOf("Win") > 0 && _info.indexOf("Win16") < 0');
wd('&& java.lang.System.getProperty("os.version").indexOf("3.5") < 0)');
wd('|| _info.indexOf("Sun") > 0));');
wd('//--><\/SCRIPT></COMMENT>');
wd('<SCRIPT LANGUAGE="JavaScript">');
// wd('if (_ie != undefined) { alert("IE=" + _ie); }');
// wd('if (_ns != undefined) { alert("NETSCAPE=" + _ns); }');
wd('<\/SCRIPT>');
html();
}
// --------------------------------------------------------------------------
// Applet tgeneration
// --------------------------------------------------------------------------
function Applet(name, code, archives, width, height) {
this._name = name;
this._code = code;
this._archives = archives;
this._params = new Array();
this._htmlTags = "";
this._width = width;
this._height = height;
}
Applet.prototype._name;
Applet.prototype._code;
Applet.prototype._archives;
Applet.prototype._params ;
Applet.prototype._width;
Applet.prototype._height;
Applet.prototype.addParam = function(name, value) {
i = this._params.length;
this._params[i] = new Array(name, value);
}
Applet.prototype.getHtmlString = function() {
if (_ns) {
return this.geEmbedString();
}
if (_ie) {
return this.getObjectString();
}
return this.geAppletString();
}
Applet.prototype.geAppletString = function() {
s = "";
s += '<APPLET name=' + this._name + ' ' + this._htmlTags + ' ' ;
s += ' CODE=' + this._code + ' ';
s += ' ARCHIVE="' + this._archives + '"\n' ;
s += ' WIDTH=' + this._width + ' ' ;
s += ' HEIGHT=' + this._height + ' ' ;
s += '\n';
s += ' ALT="If you could run this applet, ' +
'you would see some animation">\n';
for (i = 0; i < this._params.length; i++) {
s += ' <PARAM name=' + this._params[i][0] + " value=" + this._params[i][1] + ">\n";
}
s += ' Your browser is completely ignoring the <APPLET> tag!\n';
s += '</APPLET>\n';
return s;
}
Applet.prototype.geEmbedString = function() {
s = "";
s += '<EMBED name="' + this._name + '" type="application/x-java-applet;version=1.3" ';
s += ' code="' + this._code + '" ';
s += ' java_archive="' + this._archives + '" ' ;
s += ' width="' + this._width + '" ' ;
s += ' height="' + this._height + '" ';
s += ' ' + this._htmlTags + '\n';
for (i = 0; i < this._params.length; i++) {
s += ' ' + this._params[i][0] + '="' + this._params[i][1] + '"\n'
}
s += ' pluginspage="http://java.sun.com">\n';
s += '<NOEMBED>\n';
s += ' No Java 2 SDK, Standard Edition v 1.3 support for APPLET!!\n';
s += '</NOEMBED>\n';
s += '</EMBED>\n';
return s;
}
Applet.prototype.getObjectString = function() {
s = '<OBJECT name="' + this._name + ' "classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"\n';
s += ' width="' + this._width + '" ' ;
s += ' height="' + this._height + '" ';
s += ' ' + this._htmlTags + '\n';
s+= ' codebase="http://java.sun.com">\n';
s += '<PARAM NAME="code" VALUE="' + applet._code + '">\n';
s += '<PARAM NAME="archive" VALUE="' + applet._archives + '">\n';
s += '<PARAM NAME="type" VALUE="application/x-java-applet;version=1.3">\n';
s += '<PARAM NAME="scriptable" VALUE="false">\n';
for (i = 0; i < this._params.length; i++) {
s += ' <PARAM name=' + this._params[i][0] + " value=" + this._params[i][1] + ">\n";
}
s += '</OBJECT>';
return s;
}
// --------------------------------------------------------------------------
// home page specific fcts
// --------------------------------------------------------------------------
wd(css_link());
wd('<body bgcolor=white' +
' link=' + qs_link_color +
' alink=' + qs_link_hover +
' vlink=' + qs_link_visited +
' leftmargin=0 topmargin=0' +
' marginheight=0 marginwidth=0 >');
html();
//alert("index.js loaded ");
|
/**
* @file demos/util.js
* @author leeight
*/
class SimpleAction {
constructor(actionContext) {
this.context = actionContext;
}
enter(actionContext) {
if (Math.random() > .8) {
return Promise.reject(new Error('RANDOM error on entering action...'));
}
const container = actionContext.container;
const containerElement = document.getElementById(container);
if (containerElement) {
const now = new Date();
const url = actionContext.url.toString();
containerElement.innerHTML = `
<h1>Simple Action Loaded!</h1>
<h2>Url: ${url}</h2>
<h3>Time: ${now}</h3>
`;
return Promise.resolve();
}
return Promise.reject(new Error('No such element, id = ' + container));
}
}
export function createAction(ms = 350) {
return {
createRuntimeAction(actionContext) {
return new Promise((resolve, reject) => {
setTimeout(() => resolve(new SimpleAction(actionContext)), ms);
});
}
};
}
|
import React from 'react';
import ReactDOM from 'react-dom';
import { shallow } from 'enzyme';
import renderer from 'react-test-renderer';
import ReviewComp from '../components/flashcard/ReviewComp';
it('renders without crashing', () => {
shallow(<ReviewComp />);
});
it('renders without crashing', () => {
const div = document.createElement('div');
ReactDOM.render(<ReviewComp />, div);
ReactDOM.unmountComponentAtNode(div);
});
test('snapshot of UI renders consistently', () => {
const tree = renderer.create(<ReviewComp />).toJSON();
expect(tree).toMatchSnapshot();
});
it('contains the container div ChooseLevelComp on shallow render', () => {
const component = shallow(<ReviewComp />);
expect(component.html()).toContain('ReviewComp');
});
|
//= require paper-kit/jquery-ui-1.12.1.custom.min
//= require paper-kit/jquery-3.2.1
//= require paper-kit/bootstrap-switch.min
//= require paper-kit/popper
//= require paper-kit/moment.min
//= require paper-kit/bootstrap-datetimepicker.min
//= require paper-kit/bootstrap.min
//= require paper-kit/paper-kit
//= require paper-kit/nouislider
|
const express = require("express");
const { route } = require("./product");
const Card = require('../Model/Card');
const router = express.Router();
router.post('/addcard', async (req, res) => {
try {
const newcard = new Card(req.body);
console.log('neee',newcard)
await newcard.save();
await res.status(201).json({ msg: 'Card added succesfuly' })
} catch (error) {
console.error('impoosible dajouter au panier ', error);
res.status(401).json({ msg: 'Card register Failed' })
}
})
router.get('/getall', async (req, res) => {
try {
const allO = await Card.find();
allO
await res.status(201).json(allO)
} catch (error) {
console.error("getting Order failed", error);
res.status(401).json({ msg: `getting Order Failed` });
}
})
module.exports = router;
|
$(document).ready(function () {
var classroomSelect = $('#ClassroomId');
$(".clear-all").click(function () {
const form = $('form[name="main-form"]');
form.find(".selectpicker").each(function () {
$(this).val('default');
$(this).selectpicker('render');
});
form.find("input, textarea").val("");
if (($('#Date').val() == "" || $('#LessonNumber').val() == null) &&
form.attr('method') == 'post')
{
classroomSelect.prop('disabled', true)
classroomSelect.selectpicker({ title: '-- Спершу вкажіть дату та номер пари --' });
classroomSelect.selectpicker('refresh');
}
if (form.attr('method') == 'get') {
form.submit();
}
});
});
|
import React from 'react';
import {StyleSheet, View, Text, TextInput} from 'react-native';
import RadioGroup from 'react-native-radio-buttons-group';
const Content = props => {
const renderQuestion = () => {
if (props.div === 'MARRY') {
return '결혼 하셨나요?';
} else if (props.div === 'AGE') {
return '나이는 몇 살인가요?';
} else if (props.div === 'ASSET') {
return '자산은 얼마나 있나요?';
}
};
const renderContent = () => {
if (props.div === 'MARRY') {
return (
<RadioGroup
radioButtons={[
{id: '1', label: '미혼', value: '1', selected: true},
{id: '2', label: '기혼', value: '2'},
]}
layout={'row'}
/>
);
} else if (props.div === 'AGE') {
return <TextInput />;
}
};
return (
<View style={styles.contentMain}>
<View style={styles.questionArea}>
<Text>{renderQuestion()}</Text>
</View>
<View style={styles.answerArea}>{renderContent()}</View>
</View>
);
};
const styles = StyleSheet.create({
contentMain: {
flex: 1,
// backgroundColor : 'green',
padding: 20,
},
answerArea: {
paddingTop: 10,
},
});
export default Content;
|
export const compareList = (arr, item) => {
let storedList = arr;
let itemId = item;
if (storedList.length > 0 && itemId) {
return storedList.some((b) => b.id === itemId);
}
};
|
Ext.define('MESTouch.view.Nav.NavReport', {
extend: 'Ext.dataview.List',
xtype: 'nav_report',
requires: [
'Ext.dataview.List'
],
initialize: function() {
this.callParent();
this.getStore().load();
},
config: {
title: 'Report',
disclosure: true,
grouped: true,
store: 'Report',
itemTpl: '<div class="report"><strong>{reportId}</strong> {desc}</div>'
}
});
|
/* Write a JavaScript program to compute the sum of an array of integers.
*/
function add(arr) {
if (arr.length == 1) return arr[0]; // base case
let sum = arr[0] + add(arr.slice(1)); // recurse
return sum;
}
let arr = [5, 10, 20, 5, 4, 6];
console.log(add(arr));
|
/* global gapi */
const fetchEmailIds = () => {
return new Promise((resolve, reject) => {
gapi.client.gmail.users.messages
.list({
userId: "me",
labelIds: "INBOX",
maxResults: 10
})
.then(response => {
resolve(response.result.messages.map(message => message.id));
})
.catch(error => {
reject(error.message);
});
});
};
export default fetchEmailIds;
|
'use strict';
var HomeKitGenericService = require('./HomeKitGenericService.js').HomeKitGenericService;
var util = require("util");
function HomeMaticHomeKitLuxMeterService(log,platform, id ,name, type ,adress,special, cfg, Service, Characteristic) {
HomeMaticHomeKitLuxMeterService.super_.apply(this, arguments);
}
util.inherits(HomeMaticHomeKitLuxMeterService, HomeKitGenericService);
HomeMaticHomeKitLuxMeterService.prototype.createDeviceService = function(Service, Characteristic) {
var that = this;
var brightness = new Service["LightSensor"](this.name);
this.services.push(brightness);
var cbright = brightness.getCharacteristic(Characteristic.CurrentAmbientLightLevel)
.on('get', function(callback) {
that.query("LUX",function(value){
if (callback) callback(null,value);
});
}.bind(this));
this.currentStateCharacteristic["LUX"] = cbright;
cbright.eventEnabled= true;
}
module.exports = HomeMaticHomeKitLuxMeterService;
|
import React from 'react';
import { withRouter } from 'react-router-dom'
import PollChart from '../blocks/PollChart';
import Dropdown from '../blocks/Dropdown';
import {observer, inject} from 'mobx-react';
@withRouter @inject("ViewStore", "ApiStore") @observer class PollView extends React.Component{
constructor(props) {
super(props);
}
componentWillMount() {
this.props.ApiStore.reset();
this.props.ApiStore.currentPoll_Id = this.props.match.params.id;
this.props.ApiStore.lastVote.set(null)
this.props.ApiStore.fetchPollsList();
//this.props.ViewStore.setPollView(this.props.match.params.id);
}
componentWillUnmount() {
this.props.ApiStore.currentPoll_Id = null;
}
componentDidUpdate(prevProps) {
this.props.ApiStore.currentPoll_Id = this.props.match.params.id;
console.log("I did update");
if (this.props.location != prevProps.location) {
console.log("raised");
this.props.ApiStore.lastVote.set(null);
this.props.ApiStore.fetchPollsList();
}
}
render() {
let storedCurrentPoll = this.props.ViewStore.getProperty('currentPoll');
let choice = this.props.ViewStore.chosenOptionIndex.get();
let newOption = this.props.ApiStore.newOption.get();
let userOption = () => {
if (newOption != "") {
return newOption
} else return (
(choice == 0 || choice) ? storedCurrentPoll.options[choice].name : "Choose an option from the list below:"
)
}
if (storedCurrentPoll) {
return(
<div className = "poll-view">
<div className = "flex-item flex-item-poll-view-header"><div className = "poll-view-header"></div>{storedCurrentPoll.name}</div>
<div className = "poll-view-sub-headers">
<div className = "left-line">
<div className = "p-1">I'll vote for ...</div>
<div className = "flex-item user-option">{userOption()}</div>
<div className = "flex-item options-container"><Dropdown options = {storedCurrentPoll.options}/></div>
{(this.props.ApiStore.lastVote.get() != null) ? <div className = "last-vote"><span className = "last-vote-span">Last Voted for</span>{' "' + storedCurrentPoll.options[this.props.ApiStore.lastVote.get()].name + '"'}</div> : null}
{buttonRender(this.props.ApiStore.vote, this.props.ApiStore.lastVote.get(), this.props.ViewStore.getProperty("currentPoll"))}
</div>
{chartRender(storedCurrentPoll, this.props.ViewStore)}
</div>
</div>
)}
else return null
}
}
let buttonRender = (vote, cond, poll) => {
if (cond || cond == 0) {
return (<div className = "flex-item poll-view-btns"> <div className = "flex-item btn btn-submit" onClick = {() => {vote()}}>Submit</div>
<button className = "flex-item btn btn-social" onClick = {() => {FB.ui(
{
method: 'share',
quote: `I've voted for "${poll.options[cond].name}" at "${poll.name}"`,
href: window.location.href,
}, function(response){});}}>
Share on
<i className="fab fa-facebook icon-fb"></i></button> </div>)
} else
return(<div className = "flex-item poll-view-btns"> <div className = "flex-item btn btn-submit" onClick = {() => {vote()}}>Submit</div></div>)
}
let chartRender = (poll, store) => {
var totalVotes = poll.options.reduce((sum, opt) => {
return sum + opt.votes;
}, 0);
if (totalVotes > 0) {
return <div className = "right-line">
<div className = "p-1">Community votes:</div>
<div className = "option-name">{renderOptionName(store.activeOptionIndex.get(), poll)} </div>
<div className = "flex-item" id = "chart-container">
<PollChart poll = {poll}/>
</div>
</div>
} else return <div className = "right-line">
<div className = "p-1">Community votes:</div>
<div class = "chart-dummy">{`Congratulations!\nYou're first to Vote!`}</div>
</div>
}
let renderOptionName = (id, poll) => {
if (id >=0 && poll) {
return poll.options[id].name
}
}
export default PollView;
|
const ForumQuestion = require('../../../models/forumQuestion');
const User = require('../../../models/user');
const { TransformObject } = require('./merge');
const { emailTemplate } = require('../../helpers/emailTemplates/answeredQuestion');
const { sendEmail } = require('../../helpers/sendEmail');
exports.addForumQuestionAnswer = async (args, req) => {
try {
if (!req.isTheUserAuthenticated) {
throw new Error('Unauthenticated!');
}
const forumQuestion = await ForumQuestion.findById(args.forumQuestionId);
const creator = await User.findById(forumQuestion.creator);
let answers = forumQuestion.answers;
const answer = {
userId: req.userId,
answer: args.answer,
date: new Date().toISOString()
};
if (!forumQuestion.answers) answers = [];
const userIndex = answers.findIndex(answer => answer.userId === req.userId);
if (userIndex === -1) {
answers.push(answer)
} else {
answers[userIndex] = answer;
}
forumQuestion.markModified('answers');
forumQuestion.answers = answers;
await forumQuestion.save();
sendEmail(creator.email, 'Someone just answered your question!', emailTemplate(creator.name, forumQuestion));
return TransformObject(forumQuestion);
} catch (e) {
throw e
}
};
|
/**
* Created by 86wh2 on 2017/7/8.
*/
import {configState} from './config';
import {personInfoState} from './personalInfo';
import {sys} from './sys';
const states=Object.assign(configState,personInfoState,sys);
export default states;
|
import React, { createContext, useEffect, useState } from 'react';
import { useFirebase, useUser } from '../hooks/firebase';
export const ShortUrlContext = createContext({
urls: [],
tinyurl: '',
addShortUrl: () => { },
readurl: () => { }
})
export const ShortUrlProvider = ({ children }) => {
const { firestore } = useFirebase();
const { user } = useUser();
const [urls, setUrls] = useState([]);
const [tinyurl, setTinyurl] = useState('');
useEffect(() => {
if (user) {
const unsubscribe = firestore.collection('users').doc(user.uid).collection('shortUrls').onSnapshot((q) => {
setUrls(q.docs.map((doc) => doc.data()))
})
return () => unsubscribe()
}
}, [user])
const makeid = (length) => {
let result = '';
let characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let charactersLength = characters.length;
for (let i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
}
const readurl = (number) => {
if (firestore !== undefined)
firestore.collection('shortUrls').doc(number).get()
.then((res) => {
window.location.href = res.data().inputUrl;
})
}
const addShortUrl = (url) => {
let url1 = makeid(5);
setTinyurl(url1);
if (user) {
firestore.collection(`users/${user.uid}/shortUrls`).doc(url1)
.set({
inputUrl: url,
outputUrl: url1
})
}
firestore.collection('shortUrls').doc(`${url1}`)
.set({
inputUrl: url,
outputUrl: url1
})
}
return (
<ShortUrlContext.Provider value={{ urls, addShortUrl, readurl, tinyurl }} >
{children}
</ShortUrlContext.Provider>
)
}
|
const { resolve: pathResolve } = require('path');
const config = {
server: {
host: 'localhost',
port: 46234
},
database: {
host: 'HOST',
port: 10000,
username: 'USERNAME',
password: 'PASSWORD',
database: 'DATABASE'
},
security: {
accessToken: {
length: 50,
lifespan: (1000 * 60) * 10 // 10 minutes
},
refreshToken: {
length: 50,
lifespan: (1000 * 60 * 60) * 24 // 24 hours
}
},
files: {
storagePath: pathResolve(__dirname, '../storage/uploads/')
}
};
exports.config = config;
|
(function() {
var NgModule = ng.core.NgModule;
var Component = ng.core.Component;
var BrowserModule = ng.platformBrowser.BrowserModule;
var platformBrowserDynamic = ng.platformBrowserDynamic.platformBrowserDynamic();
var Class = ng.core.Class;
var UpdateTimeService = Class({
constructor: function UpdateTimeService() {
},
getOnlyTime: function() {
this.time = new Date();
var time = this.time.toTimeString().split(" ")[0];
console.log(time);
return time;
},
generateCurrentTime: function(delay, callback) {
var self = this;
callback(this.getOnlyTime());
setInterval(function() {
callback(self.getOnlyTime());
}, delay);
}
});
var CurrentTimeComponent = Component({
selector: 'current-time',
template: '<p>{{ time }}</p>'
})
.Class({
constructor: [UpdateTimeService, function CurrentTimeComponent(updateTimeService) {
var self = this;
updateTimeService.generateCurrentTime(1000, function(time) {
self.time = time;
});
}]
});
var AppComponent = Component({
selector: 'my-app',
template:
'<p>The current time</p>' +
'<current-time></current-time>'
})
.Class({
constructor: function AppComponent() {}
});
var AppModule = NgModule({
imports: [BrowserModule],
declarations: [AppComponent, CurrentTimeComponent],
providers: [UpdateTimeService],
bootstrap: [AppComponent]
})
.Class({
constructor: function() {}
});
platformBrowserDynamic.bootstrapModule(AppModule);
})();
|
const axios = require('axios');
const moment = require('moment');
const turf = require('@turf/turf');
const settings = require('./appsettings.json');
async function getBirdInfo(settings) {
const limit = 500;
let offset = 0;
let availability = [];
let res = {};
const url = `${settings.BaseUrl}availability`;
do {
res = await axios.get(url, {
params: {
limit,
offset,
},
headers: settings.Headers
});
availability = availability.concat(res.data.availability);
offset += res.data.availability.length;
} while (res.data.availability.length != 0);
return availability;
}
async function getLimeInfo(settings) {
let page = 0;
let res = {};
let availability = [];
const url = `${settings.BaseUrl}availability`;
do {
res = await axios.get(url, {
params: {
page,
},
headers: settings.Headers
});
availability = availability.concat(res.data.data);
page += 1;
} while (res.data.data.length != 0);
return availability;
}
async function getSkipInfo(settings) {
let availability = [];
const url = `${settings.BaseUrl}availability.json`;
let res = await axios.get(url, {
headers: settings.Headers
});
availability = availability.concat(res.data.reduce(
(accu, curr) => {
accu.push(curr);
return accu;
}, [])
);
return availability;
}
const bird = getBirdInfo(settings.CompanySettings.Bird);
const lime = getLimeInfo(settings.CompanySettings.Lime);
const skip = getSkipInfo(settings.CompanySettings.Skip);
let totalavailability = [];
var fs = require('fs');
var fileStream = fs.createWriteStream('availability.json');
let returns = 0;
function callback() {
returns += 1;
if (returns == 3) {
fileStream.write(JSON.stringify(totalavailability));
fileStream.close();
}
}
bird.then((availability) => {
totalavailability = totalavailability.concat(availability);
console.log('Done reading Bird.');
callback();
})
.catch((err) => {
console.error(JSON.stringify(err));
});
lime.then((availability) => {
totalavailability = totalavailability.concat(availability);
console.log('Done reading Lime.');
callback();
})
.catch((err) => {
console.error(JSON.stringify(err));
});
skip.then((availability) => {
totalavailability = totalavailability.concat(availability);
console.log('Done reading Skip.');
callback();
})
.catch((err) => {
console.error(JSON.stringify(err));
});
|
var webpack = require('webpack');
var UglifyJsPlugin = webpack.optimize.UglifyJsPlugin;
var path = require('path');
var config = {
entry: __dirname + '/src/index.js',
devtool: 'source-map',
output: {
path: __dirname + '/lib',
filename: 'protractor-ngstrictdi-plugin.min.js',
library: 'protractor-ngstrictdi-plugin',
libraryTarget: 'commonjs2'
},
module: {
loaders: [
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ['es2015']
}
},
{
test: /\.js$/,
loader: 'eslint-loader',
exclude: /node_modules/
}
]
},
resolve: {
root: path.resolve('./src'),
extension: ['', '.js']
},
plugins: [
new UglifyJsPlugin({ minimize: true })
]
};
module.exports = config;
|
const express = require("express")
const app = express();
const port = 3000
app.get('/', (req, res) => res.send('วิชานาถ บุญหมั้น'))
app.get('/about', (req, res) => res.send('อิอิ about'))
app.get('/test', (req, res) =>{
res.json({message: "test"})
})
app.listen(port, () => console.log(`Example app listening on port ${port}!`))
|
import React from 'react';
import { Form, Button } from 'react-bootstrap';
import './../CSS/booking.css';
import About from './About Us';
import Footer from './Contact Us';
import {connect} from 'react-redux';
import { raiseTickets } from './../Redux/Actions/index';
import Tickets from './BookingRequests';
class Booking extends React.Component {
constructor(props) {
super(props)
this.state = {
cus_name: null,
cus_id: null,
start: null,
destiny: null,
startdate: null,
return: null,
quantity: 0
}
this.handleSubmit = this.handleSubmit.bind(this);
}
componentDidMount() {
var curruser = this.props.reducerState.userReducer.currentuser;
this.setState({
cus_id: curruser.id,
cus_name: curruser.name
})
//getting data from db
//var details = this.props.reducerState.userReducer.dealers;
//var details = await items.find({}).toArray();
//checking if the user details are present in db or not
//var ispresent = details.some(item => item.owner_id === curruser.id);
//var dealerDetails = details.filter(detail => detail.age > 20);
//console.log("Dealers :- " + dealerDetails[0]);
// if (details) {
// var names = [];
// details.forEach(function (detail) {
// if (detail.isCustomer === true) {
// names.push(detail.name);
// }
// });
// console.log("ARRAY:- " + names);
//setting the state values
//this.setState({
// dealers: names
//})
//}
}
handleSubmit = (e) => {
e.preventDefault();
this.props.raiseTickets(this.state.cus_name,this.state.cus_id, this.state.start, this.state.destiny, this.state.startdate, this.state.return, this.state.quantity);
this.setState({});
}
render() {
return (
<>
<div className="containerbooking">
<h1 className='bookinghead'>Book Your Tickets</h1>
<p className='bookingp'>Fill your starting point and your Destiny</p>
<Form onSubmit={this.handleSubmit}>
<Form.Row style={{ paddingLeft: '480px' }}>
<Form.Group controlId="formBasicStart">
<Form.Label style={{ color: 'white', fontFamily: 'Courier', fontWeight: 'bolder'}}>Start</Form.Label>
<Form.Control required type="text" onChange={e => this.setState({ start: e.target.value })} />
<Form.Text className="text-muted">
</Form.Text>
</Form.Group>
<Form.Group controlId="formBasicDestiny">
<Form.Label style={{ color: 'white', fontFamily: 'Courier', fontWeight: 'bolder' }}>Destiny</Form.Label>
<Form.Control required type="text" onChange={e => this.setState({ destiny: e.target.value })} />
<Form.Text className="text-muted">
</Form.Text>
</Form.Group>
</Form.Row>
<Form.Row style={{ paddingLeft: '485px' }}>
<Form.Group controlId="formBasicStartDate">
<Form.Label style={{ color: 'white', fontFamily: 'Courier', fontWeight: 'bolder' }}>Start Date</Form.Label>
<Form.Control required type="date" onChange={e => this.setState({ startdate: e.target.value })} />
<Form.Text className="text-muted">
</Form.Text>
</Form.Group>
<Form.Group controlId="formBasicReturnDate">
<Form.Label style={{ color: 'white', fontFamily: 'Courier', fontWeight: 'bolder' }}>Return Date</Form.Label>
<Form.Control required type="date" onChange={e => this.setState({ return: e.target.value })} />
<Form.Text className="text-muted">
</Form.Text>
</Form.Group>
</Form.Row>
<Form.Row style={{ paddingLeft: '580px' }} min={1}>
<Form.Group controlId="formBasicTickets">
<Form.Label style={{ color: 'white', fontFamily: 'Courier', fontWeight: 'bolder' }}>Number Of Tickets</Form.Label>
<Form.Control required type="number" onChange={e => this.setState({ quantity: e.target.value })} />
<Form.Text className="text-muted">
</Form.Text>
</Form.Group>
</Form.Row>
<Button variant="primary" type="submit">
Submit
</Button>
</Form>
</div>
<Tickets />
<About />
<Footer />
</>
);
}
}
const mapStateToProps = (state) => ({
reducerState: state
})
const mapDispatchToProps = {
raiseTickets
}
export default connect(mapStateToProps, mapDispatchToProps)(Booking);
|
var form = document.querySelector('form')
console.log(form.elements.pseudo.type)
|
/* eslint-disable eqeqeq */
import React from 'react'
import { StyleSheet } from 'quantum'
const styles = StyleSheet.create({
self: {
fontSize: '12px',
textDecoration: 'none',
color: '#9e9e9e',
},
decorated: {
textDecoration: 'underline',
},
})
const TransactionLink = ({ children, rowData, onClick }) => {
const commentId = rowData.get('comment_id')
const transitionId = rowData.get('transaction_id')
return (
<span
className={styles({ decorated: commentId == 1 })}
onClick={(commentId == 1 && onClick) && onClick.bind(null, transitionId)}
>
{children}
</span>
)
}
export default TransactionLink
|
const UPDATE_PERCENT = "UPDATE_PERCENT"
const UPDATE_URL = "UPDATE_URL";
const FILE_UPLOADED = "FILE_UPLOADED"
export const reducer = (state = {}, action) => {
switch(action.type){
case FILE_UPLOADED:
return {
...state,
fileUploadedStatus : action.fileUploadedStatus
}
case UPDATE_PERCENT:
return {
...state,
percent : action.percent
}
case UPDATE_URL:
return {
...state,
url :action.url
}
default:
return state;
}
}
export const updatePercent = (percent)=>{
return {
type : UPDATE_PERCENT,
percent : percent
}
}
export const updateUrl = (url)=>{
return {
type : UPDATE_URL,
url : url
}
}
export const fileUploaded = (fileUploadedStatus)=>{
return {
type : FILE_UPLOADED,
fileUploadedStatus : fileUploadedStatus
}
}
|
import * as actionTypes from './actionTypes';
import axios from '../../axios-orders';
export const getOrdersFromServerSuccess = (res) => {
const fetchedOrders = [];
for (let key in res.data) {
fetchedOrders.push({
id: key,
...res.data[key]
});
}
return {
type: actionTypes.GET_ORDERS_FROM_SERVER_SUCCESS,
orders: fetchedOrders
}
}
export const getOrdersFromServerFailed = () => {
return {
type: actionTypes.GET_ORDERS_FROM_SERVER_FAILED
}
}
export const getOrdersFromServerStart = () => {
return {
type: actionTypes.GET_ORDERS_FROM_SERVER_START
}
}
export const getOrdersFromServer = (token, userId) => {
return dispatch => {
const queryParams = '?auth=' + token + '&orderBy="userId"&equalTo="' + userId + '"';
dispatch(getOrdersFromServerStart());
axios.get('/orders.json' + queryParams)
.then(res => dispatch(getOrdersFromServerSuccess(res)))
.catch(err => dispatch(getOrdersFromServerFailed()))
}
}
// Sync
export const purchaseBurgerSuccess = (id, orderData) => {
return {
type: actionTypes.PURCHASE_BURGER_SUCCESS,
orderId: id,
orderData: orderData
}
}
// Sync
export const purchaseBurgerFail = (error) => {
return {
type: actionTypes.PURCHASE_BURGER_FAIL,
error: error
}
}
// Async
export const purchaseBurger = (orderData, token, userId) => {
return dispatch => {
dispatch(purchaseBurgerStart());
axios.post( '/orders.json?auth=' + token, orderData )
.then(res => dispatch(purchaseBurgerSuccess(res.data.name, orderData)))
.catch(err => dispatch(purchaseBurgerFail(err)))
}
}
export const purchaseBurgerStart = () => {
return {
type: actionTypes.PURCHASE_BURGER_START,
}
}
export const purchaseInit = () => {
return {
type: actionTypes.PURCHASE_INIT
}
}
|
const Employee = require('./Employee');
class Intern extends Employee {
// todo: add id, name, email
constructor(id, name, email, school) {
super(id, name, email);
this.school = school;
}
getSchool() {
return (this.school);
}
}
// const internEmployee = new Intern(data.id, data.getRole, data.getofficeNumber);
module.exports = Intern;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.