text stringlengths 7 3.69M |
|---|
function validar() {
var nombre, apellidos, correo, usuario, clave, telefono, expresion;
nombre = document.getElementById("nombre").value;
apellidos = document.getElementById("apellidos").value;
correo = document.getElementById("correo").value;
usuario = document.getElementById("usuario").value;
clave = document.getElementById("clave").value;
telefono = document.getElementById("telefono").value;
expresion = /\w+@\w+\.+[a-z]/;
if (nombre === "" || apellidos === "" || correo === "" || usuario === "" || clave === "" || telefono === "") {
alert("Todos los campos deben estar llenos");
return false;
} else if (nombre.length > 30) {
alert("El nombre es muy largo");
return false;
} else if (apellidos.length > 80) {
alert("Los apellidos son muy largos");
return false;
} else if (correo.length > 100) {
alert("El correo es muy largo");
return false;
} else if (!expresion.test(correo)) {
alert("El correo no es valido");
return false;
} else if (usuario.length > 20) {
alert("El usuario solo debe tener 20 caracteres como maximo");
return false;
} else if (clave.length > 20) {
alert("La clave solo debe tener 20 caracteres como maximo");
return false;
} else if (telefono.length > 10) {
alert("El telefono es muy largo");
return false;
} else if (isNaN(telefono)) {
alert("El telefono ingresado no es un numero");
return false;
}
} |
require("crafter"); |
/**
* This npawify function analyzes an adapter and returns an object containing its findings.
*
* @param {String} file Contents of the file.
* @returns {Object}
*/
module.exports = function (file) {
var allgetters = ['getPlayhead', 'getPlayrate', 'getFramesPerSecond', 'getDroppedFrames',
'getDuration', 'getBitrate', 'getThroughput', 'getRendition', 'getTitle', 'getTitle2',
'getIsLive', 'getResource', 'getPosition']
var getters = []
for (var i = 0; i < allgetters.length; i++) {
var element = allgetters[i]
if (file.indexOf(element) !== -1) {
getters.push(element)
}
}
return {
buffer: file.indexOf('fireBufferBegin') !== -1 ? 'native' : 'monitor',
seek: file.indexOf('fireSeekBegin') !== -1 ? 'native' : 'monitor',
getters: getters
}
}
|
import React from 'react';
import CardDeck from 'react-bootstrap/CardDeck';
import Card from 'react-bootstrap/Card';
import ReactTooltip from "react-tooltip";
function WorldSummary({latest}) {
const lastUpdated = new Date(parseInt(latest.updated)).toString();
return (
<div>
<h5
data-tip={'Data last updated: ' + lastUpdated}
style={{textAlign:'center'}}
>
World Summary
</h5>
<ReactTooltip />
<br />
<CardDeck>
<Card
bg={'primary'}
text={'white'}
className='text-center'
style={{margin: '10px'}}
>
<Card.Body>
<Card.Title>Total Cases</Card.Title>
<Card.Text style={{fontSize: '30px'}}>
{latest.cases}
</Card.Text>
</Card.Body>
<Card.Footer>
<small>Last updated {lastUpdated}</small>
</Card.Footer>
</Card>
<Card
bg={'success'}
text={'white'}
className='text-center'
style={{margin: '10px'}}
>
<Card.Body>
<Card.Title>Recovered</Card.Title>
<Card.Text style={{fontSize: '30px'}}>
{latest.recovered}
</Card.Text>
</Card.Body>
<Card.Footer>
<small>Last updated {lastUpdated}</small>
</Card.Footer>
</Card>
<Card
bg={'danger'}
text={'white'}
className='text-center'
style={{margin: '10px'}}
>
<Card.Body>
<Card.Title>Dead</Card.Title>
<Card.Text style={{fontSize: '30px'}}>
{latest.deaths}
</Card.Text>
</Card.Body>
<Card.Footer>
<small>Last updated {lastUpdated}</small>
</Card.Footer>
</Card>
</CardDeck>
</div>
);
}
export default WorldSummary;
|
function updateClock() {
var clock = document.getElementById("clock");
var time_vals = clock.innerHTML.split(':');
if(time_vals.length == 2){ time_vals.unshift('0');}
var total_seconds = time_vals[0]*3600+time_vals[1]*60+time_vals[2]*1;
function tick() {
total_seconds--;
var time = total_seconds;
var hours = Math.floor(time / 3600);
time = time - hours * 3600;
var minutes = Math.floor(time / 60);
var seconds = time - minutes * 60;
var hours_str = (hours > 0 ? String(hours)+":":"")
clock.innerHTML = hours_str + String(minutes) + ":" + (seconds < 10 ? "0" + String(seconds):String(seconds));
}
tick();
if(total_seconds==0){
clearInterval(timeinterval);
setTimeout(function(){window.location.href = '/not-available/';}, 1000);
}
}
var timeinterval = setInterval(updateClock,1000);
|
let obj = {
newObj: {
obj2: {
obj5: {
one: 1,
},
},
},
obj3: {
obj4: { two: 2 },
},
};
// { 'newObj.obj2.obj5.one': 1, 'obj3.obj4.two': 2 }
let flatObject = {};
function flattenObject(obj , flatObject , keyTillNow){
for(key in obj){
if( typeof obj[key] == "object"){
keyTillNow = keyTillNow + key +"."
flattenObject( obj[key] , flatObject , keyTillNow);
}
else{
keyTillNow = keyTillNow + key;
flatObject[keyTillNow] = obj[key];
}
}
}
flattenObject(obj , flatObject , "");
console.log(flatObject);
|
// Required NPM libraries
require('dotenv').config();
const axios = require('axios');
const Express = require('express');
// require and set view engine using ejs
const ejsLayouts = require('express-ejs-layouts')
//require all middleware for ap/authentication
// helmet, morgan, passport, and custom middleware, express-session, sequelize session, flash
const helmet = require('helmet');
const session = require('express-session');
const flash = require('flash');
const passport = require('./config/ppConfig');
const db = require('./models');
// want to add alink to our customer middleware for isLoggedIn
const isLoggedIn = require('./middleware/isLoggedIn');
const SequelizeStore = require('connect-session-sequelize')(session.Store)
const methodOverride = require('method-override');
// App setup
const app = Express();
app.use(Express.urlencoded({ extended: false}));
app.use(Express.static(__dirname + "/public"));
app.set('view engine', 'ejs');
app.use(ejsLayouts);
app.use(require('morgan')('dev'));
app.use(helmet());
app.use(methodOverride('_method'));
// create new instance of class Sequelize Store
const sessionStore = new SequelizeStore({
db: db.sequelize,
expiration: 1000 * 60 * 30
})
app.use(session({
secret: process.env.SESSION_SECRET,
store: sessionStore,
resave: false,
saveUninitialized: true
}))
// Need next bit to run the previous bit
sessionStore.sync();
// Initialize flash message, passport and session info
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
app.use(function(req,res, next) {
res.locals.alerts = req.flash();
res.locals.currentUser = req.user;
next();
})
// ROUTES
app.get('/', function(req, res) {
res.render("index");
});
// app.get('/profile', isLoggedIn, function(req, res) {
// var mealUrl = "https://www.themealdb.com/api/json/v1/1/categories.php";
// axios.get(mealUrl).then(function(apiResponse) {
// console.log(apiResponse);
// var category = apiResponse.data.results;
// res.render('profile/index', { category: category})
// }).catch(errorHandler)
// })
// include auth controllers
app.use('/profile', require('./controllers/profile'));
app.use('/auth', require('./controllers/auth'));
app.use('/categories', require('./controllers/categories'));
// initialize
app.listen(process.env.PORT || 3000, function() {
console.log(`Rootin n Tootin on port ${process.env.PORT}`)
}); |
#pragma strict
var PowerupPrefab:Rigidbody;
var numPowerup:int;
function generatePowerup(maxpower:int){
var counter:int;
for(counter=0;counter<maxpower;counter++)
{
var xcoord:float;
var ycoord:float;
xcoord = Random.Range(BorderController.leftmost,BorderController.rightmost);
ycoord = Random.Range(BorderController.bottommost,BorderController.topmost);
Instantiate(PowerupPrefab,Vector3(xcoord,ycoord,3),Quaternion.identity);
yield WaitForSeconds(5);
}
}
function Start () {
generatePowerup(numPowerup);
}
function Update () {
}
|
import * as actionType from './actionType.js';
import axios from 'axios';
import { fromJS } from 'immutable';
const setDetail=(data)=>{
return {
type: actionType.SET_DETAIL,
detailList: fromJS(data)
}
}
export const getDetail = (id) =>{
return ((dispatch)=>{
axios.get('/api/detail.json?id='+id)
.then((res)=>{
const data = res.data;
if(data.success){
dispatch(setDetail(data.data));
}
})
})
}
export const isPageDetail = (status) =>{
return{
type: actionType.IS_PAGE_DETAIL,
status:status
}
}
export const changeHeader = (status) =>{
return{
type: actionType.CHANGE_HEADER,
status:status
}
} |
/**
* @file DataUtil
* @author Miracle He
* @version v1.0.0
* @description 基于业务数据处理工具类(字典,时间等)
* @createDate 2019-01-20
*/
import moment from 'moment';
import { DataType } from '../data';
import { DATA_SEPARATOR, DATE_FORMATTER, TABLE_COLUMN_WIDTH } from '../constants';
export class DataUtil {
/**
* @method 获取指定类型的字典中所有的项目
* @param {Array} dict 当前字典数据源(一般为字典数组集合)
* @param {String} type 字典类型
* @param {Object} args 扩展配置参数(可配置字段名称)
* @desc 如当前的字典数据源不存在或未找到指定的字典类型,则都返回空数组
* @returns {Array} 返回对应字典类型的[{key,value}]
*/
static getDictItems(dict, type, { typeName = 'type', itemsName = 'items' } = {}) {
if (!dict || !type) return [];
const dictType = dict.find(item => item[typeName] === type);
return dictType && dictType[itemsName] ? dictType[itemsName] : [];
}
/**
* @method 获取指定类型的字典中对应key的值
* @param {Array} dict 当前字典数据源(一般为字典数组集合)
* @param {String} type 字典类型
* @param {String} key 指定的key值(一般为服务器下发))
* @param {Object} args 扩展配置参数(可配置字段名称)
* @desc 如当前的字典数据源不存在或未找到指定的字典类型或未找到字典中指定的key,则都返回当前key值
* @returns {String} 返回字典key对应的value值
*/
static getDictValue(dict, type, key, {
separator = DATA_SEPARATOR.comma,
typeName = 'type',
itemsName = 'items',
keyName = 'key',
valueName = 'value'
} = {}) {
if (!dict || !type || (!key && key !== '0' && key !== false)) return key;
const dictType = dict.find(item => item[typeName] === type);
if (!dictType) return key;
if (DataType.isArray(key)) {
const dictItem = dictType[itemsName].filter(item => key.indexOf(item[keyName]) > -1);
return dictItem.map(item => item[valueName]).join(separator);
} else {
if (DataType.isBoolean(key)) {
key = key ? '1' : '0';
}
const dictItem = dictType[itemsName].find(item => item[keyName] === key);
return dictItem ? dictItem[valueName] : key;
}
}
/**
* @method 扩展(拷贝)已有的数据类型(数组或对象)
* @param {Array|Object} target 拷贝的目标(对象或数组,依赖于拷贝来源)
* @param {Array|Object} source 拷贝的来源(对象或数组)
* @param {Boolean} deep 是否进行深拷贝(默认:true)
* @desc 只能对数组或对象进行深拷贝,其他数据类型都只能完成浅拷贝
* @returns {Array|Object} 返回扩展(拷贝)之后的类型
*/
static extend(target, source, deep = true) {
// 如为浅拷贝(只支持对象或者数组的的拷贝),则直接返回本身
if (!deep || (!DataType.isPlainObject(source) && !DataType.isArray(source))) return source;
for (const prop in source) {
const isPlainObjectForSourceProp = DataType.isPlainObject(source[prop]);
const isPlainObjectForTargetProp = DataType.isPlainObject(target[prop]);
const isArrayForSourceProp = DataType.isArray(source[prop]);
const isArrayForTargetProp = DataType.isArray(target[prop]);
if (deep && (isPlainObjectForSourceProp || isArrayForSourceProp)) {
if (isPlainObjectForSourceProp && !isPlainObjectForTargetProp) {
target[prop] = {};
}
if (isArrayForSourceProp && !isArrayForTargetProp) {
target[prop] = [];
}
this.extend(target[prop], source[prop], deep);
} else if (source[prop] !== undefined) {
target[prop] = source[prop];
}
}
return target;
}
/**
* @method 对指定的数据类型(数组或对象)进行拷贝
* @param {Array|Object} item 拷贝的来源(对象或数组)
* @param {Object} { deep } 是否进行深拷贝(默认:true)
* @param {Boolean} { asArray } 拷贝之后是否转化为数组(仅仅只针对对象拷贝,默认:false)
* @returns {Array|Object} 返回拷贝之后的类型
*/
static clone(item, { deep, asArray } = { deep: true, asArray: false }) {
if (DataType.isArray(item)) {
const target = this.extend([], item, deep);
return target;
} else if (DataType.isObject(item)) {
const target = this.extend({}, item, deep);
return asArray ? [target] : target;
}
return asArray ? [item] : item;
}
/**
* @method 获取指定长度的随机字符串
* @param {Number} len 指定长度(默认:32)
* @returns {String} 返回对应的随机字符串
*/
static randomString(len = 32) {
/****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
const $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
const maxPos = $chars.length;
let result = '';
for (let i = 0; i < len; i++) {
result += $chars.charAt(Math.floor(Math.random() * maxPos));
}
return result.toLowerCase();
}
/**
* @method 使用moment格式化指定日期(不带时分秒)
* @param {Number} date 需要格式化的日期, 如日期未传入则获取当前日期
* @param {Number} format 格式化字符串(默认:YYYY-MM-DD)
* @returns {String} 返回格式化之后的日期
*/
static formatDate(date, format = DATE_FORMATTER.date) {
date = DataType.defaultVal(date, new Date());
return moment(date).format(format);
}
/**
* @method 使用moment格式化指定完整日期
* @param {Number} date 需要格式化的日期, 如日期未传入则获取当前日期
* @param {Object} { short } 是否格式化为不带秒的日期(默认:true,如2019-01-20 12:30)
* @param {Object} { format } 指定格式化字符串(将忽略short配置)
* @returns {String} 返回格式化之后的日期
*/
static formatDateTime(date, {
short = true,
format
} = {}) {
if (format) {
return DataUtil.formatDate(date, format);
}
return DataUtil.formatDate(date, short ? DATE_FORMATTER.datetime_short : DATE_FORMATTER.datetime);
}
/**
* @method 使用moment格式化指定时间
* @param {Number} date 需要格式化的日期, 如日期未传入则获取当前日期
* @param {Object} { short } 是否格式化为不带秒的日期(默认:true,如12:30)
* @param {Object} { format } 指定格式化字符串(将忽略short配置)
* @returns {String} 返回格式化之后的时间
*/
static formatTime(date, {
short = true,
format
} = {}) {
if (format) {
return DataUtil.formatDate(date, format);
}
return DataUtil.formatDate(date, short ? DATE_FORMATTER.time_short : DATE_FORMATTER.time);
}
/**
* @method 获取表格固定列
* @param {Array} columns 表格列配置数组
* @param {Object} {leftCols} 左侧固定列(必须)
* @param {Object} {rightCols} 右侧固定列(非必须)
* @returns {Object} 返回配置完毕后的列(自动计算宽度)
*/
static getFixColumns(columns, { leftCols = [], rightCols = [] } = {}) {
const result = { columns: [], width: 0, check: true };
if (!DataType.isArray(columns) || DataType.isEmptyArray(columns)) {
console.warn('当前需要固定列为空,固定列效果可能失效。');
result.columns = columns;
result.check = false;
return result;
}
if (DataType.isEmptyArray(leftCols)) {
console.warn('当前未配置左侧固定列,固定列效果可能失效。');
result.columns = columns;
result.check = false;
}
if (!DataType.isEmptyArray(rightCols)) {
if (rightCols.some(item => leftCols.indexOf(item) > -1)) {
console.warn('左侧固定列和右侧固定列中不能包含同名的列,固定列效果可能失效。');
result.columns = columns;
result.check = false;
}
}
columns.forEach(item => {
item.width = DataType.defaultVal(item.width, this.getColumnWidth());
if (result.check) {
const columnName = item.dataIndex;
if (leftCols.indexOf(columnName) > -1) {
result.columns.push({...item, fixed: 'left'});
} else if (rightCols.indexOf(columnName) > -1) {
result.columns.push({...item, fixed: 'right'});
} else {
result.columns.push({...item});
}
}
if (!item.width) {
console.warn(`当前列${item.dataIndex}未配置宽度,固定列效果可能失效。`);
}
result.width += item.width;
})
delete result.check;
return result;
}
/**
* @method 获取表格列宽
* @param {String} width 列宽(默认:'md', 还可配置'xs','sm','md','lg','xl')
* @returns {Number} 返回指定的列宽
*/
static getColumnWidth(width = 'md') {
if (Object.keys(TABLE_COLUMN_WIDTH).indexOf(width) > -1) {
return TABLE_COLUMN_WIDTH[width];
}
const $width = parseInt(width);
return isNaN($width) || $width === 0 ? TABLE_COLUMN_WIDTH['md'] : $width;
}
/**
* @method 为表格配置操作列
* @param {Array} columns 表格列配置数组
* @param {Function} render 配置渲染函数(可通过item参数获取当前行的数据
* @param {Object} options 额外配置项
* @returns {Array} 返回带有操作列的表格
*/
static addActionColumn(columns, render = () => {}, options = {}) {
// 首先去除之前action列
const result = columns.filter(item => item.dataIndex !== 'action')
options = {
title: '操作',
dataIndex: 'action',
width: DataUtil.getColumnWidth('lg'),
key: DataUtil.randomString(10),
...options
};
result.push({
...options,
render
});
return result
}
} |
import React from "react";
import { addDecorator, storiesOf } from "@storybook/react";
import { withKnobs } from "@storybook/addon-knobs";
import Navigation from ".";
const stories = storiesOf("02 - Molecule/Navigation", module);
addDecorator(withKnobs);
stories.add("Default", () => {
return <Navigation />;
});
|
import { connect } from 'react-redux'
import { vote } from '../actions'
import * as Detail from '../components/Detail/index'
const connector = connect(
state => ({
news: state.news.getIn(['detail', 'news']).toJS(),
vote: state.news.getIn(['detail', 'vote']).toJS(),
}),
dispatch => ({
onVote: () => {
dispatch(vote('p'))
},
onUnvote: () => {
dispatch(vote('n'))
},
})
)
export const Desktop = connector(Detail.Desktop)
export const Tablet = connector(Detail.Tablet)
export const Mobile = connector(Detail.Mobile)
|
export default {
getCookie(name) {
let cookieValue = null;
if (document.cookie && document.cookie !== '') {
const cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i++) { //eslint-disable-line
const cookie = cookies[i].trim();
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (`${name}=`)) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
},
setCookie(name, value, expire) {
const d = new Date();
d.setTime(d.getTime() + expire);
const expires = `expires=${d.toUTCString()}`;
document.cookie = `${name}=${value};${expires}`;
},
deleteCookie(name) {
this.setCookie(name, '', -1);
}
};
|
import Joi from 'joi';
export default {
// POST /api/users
createCurriculum: {
body: {
name: Joi.string().required(),
//skills: Joi.array().required(),
organization: Joi.string().required()
}
},
};
|
import React, { Component } from 'react';
import { Media, Button, Label } from 'reactstrap';
import { Control, LocalForm } from 'react-redux-form';
class TaskInfo extends Component {
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(values) {
this.props.putTask(this.props.id, values.description, values.type, values.status);
}
render() {
if (this.props.id) {
return (
<div className="container">
<div className="row-content">
<div className="col-12">
<h3>Edit Task : {this.props.id} </h3>
<hr />
</div>
</div>
<div className="row-content">
<Media>
<LocalForm onSubmit={values => this.handleSubmit(values)}>
<div className="form-group">
<Label htmlFor="description">Description</Label>
<Control.textarea model=".description" id="description" name="description"
rows="1"
className="form-control"
/>
</div>
<div className="form-group">
<Label htmlFor="type">Type</Label>
<Control.textarea model=".type" id="type" name="type"
rows="1"
className="form-control"
/>
</div>
<div className="form-group">
<Label htmlFor="status">Status</Label>
<Control.textarea model=".status" id="status" name="status"
rows="1"
className="form-control"
/>
</div>
<Button type="submit" color="primary">
Update Task
</Button>
<Button onClick={() => this.props.deleteTask(this.props.id)}>
Delete Task
</Button>
</LocalForm>
</Media>
</div>
</div>
)
} else {
return (
<div>
d
</div>
);
}
}
}
export default TaskInfo; |
import React from 'react';
const InputValidator = (props) => {
let ret = props.counter < 5 ?
<p>Text too short</p> :
<p>Text too long</p>;
return ret;
};
export default InputValidator; |
export const removeUser = () => ({
type: 'REMOVEUSER',
})
export const saveUser = () => ({
type: 'SAVEUSER',
}) |
import React, { Component } from "react";
import { Icon } from "react-materialize";
class ProjectTable extends Component {
getCountryStateName = state => {
switch (state) {
case 1:
return "New South Wales";
case 2:
return "Queensland";
case 3:
return "South Australia";
case 4:
return "Tasmania";
case 5:
return "Victoria";
case 6:
return "Western Australia";
default:
return "";
}
};
editHandler = (e, id) => {
e.stopPropagation();
this.props.editProject(id);
};
rowClickHandler = project => {
const { budgetPage, selectProjectHandler } = this.props;
selectProjectHandler(project);
budgetPage(project.id);
};
getStatus = status => {
switch (status) {
case 1:
return "active";
case 2:
return "inactive";
case 3:
return "completed";
}
};
render() {
const {
props: { projectData, projectPermission },
editHandler,
getCountryStateName,
rowClickHandler,
getStatus
} = this;
return (
<div className="control-pane">
<div className="control-section">
<div className="varicon-table mr-0">
<table className="table">
<colgroup>
<col span="4" className="description-col"></col>
</colgroup>
<thead>
<tr>
<th>Id</th>
<th>Project Name</th>
<th>Type</th>
<th>Status</th>
<th>Start Date</th>
<th>Completion Date</th>
<th>State</th>
{projectPermission && projectPermission.change_project && (
<th>Actions</th>
)}
</tr>
</thead>
<tbody>
{projectData.length > 0 ? (
projectData.map(project => (
<tr
className=""
key={project.id}
onClick={() => rowClickHandler(project)}
style={{ cursor: "pointer" }}
>
<td>{project.code}</td>
<td>{project.name}</td>
<td>{project.type == 0 ? "Civil" : "Demolition"}</td>
<td>
<span
className={`status varicon-${getStatus(
project.status
)}`}
style={{ textTransform: "capitalize" }}
>
{getStatus(project.status)}
</span>
</td>
<td>
{project.start_date &&
new Date(project.start_date).toDateString()}
</td>
<td>
{project.end_date &&
new Date(project.end_date).toDateString()}
</td>
<td> {getCountryStateName(project.state)}</td>
{projectPermission && projectPermission.change_project && (
<td>
<div className="action">
<span
className="action-icon edit-icon varicon-active"
onClick={e => editHandler(e, project.id)}
>
<Icon>edit</Icon>
</span>
</div>
</td>
)}
</tr>
))
) : (
<tr>
<td
colSpan={
projectPermission && projectPermission.change_project
? "8"
: "7"
}
>
No record available.
</td>
</tr>
)}
</tbody>
</table>
</div>
</div>
</div>
);
}
}
export default ProjectTable;
|
function pageLoad() {
// Main page div element
const mainContainer = document.getElementById("content");
function makeElement(id, type, parentEle) {
let tempEle = document.createElement(type);
tempEle.id = id;
parentEle.appendChild(tempEle)
}
function makeElementText(id, type, parentEle, text) {
let tempTextEle = document.createElement(type);
tempTextEle.id = id;
tempTextEle.innerHTML = text;
parentEle.appendChild(tempTextEle);
}
// Header element
makeElement("pageHeader", "header", mainContainer);
let pageHeader = document.getElementById("pageHeader")
// Information section element.
makeElement("infoSection", "section", mainContainer);
// Footer element.
makeElement("pageFooter", "footer", mainContainer);
let pageFooter = document.getElementById("pageFooter");
// Restaurant name element for header.
makeElementText("name", "h1", pageHeader, "The Last Stop");
// Hours title element for footer
makeElementText("hoursTitle", "h3", pageFooter, "Hours");
// Hours Text
makeElementText("hoursText", "p", pageFooter,
`Tues - Sat: 11:30 am - 10:00 pm </br>
Sunday: 3:00 pm - 9:30 pm</br>
Monday: Closed`);
// Contact title for footer
makeElementText("contactTitle", "h3", pageFooter, "Contact");
// Contact text
makeElementText("contactText", "p", pageFooter,
`914-555-5555</br>
info@thelaststop.com</br>
724 Cambridge Place, Derry, PA`)
// Nav bar
makeElement("navTabs", "nav", pageHeader);
const navBar = document.getElementById("navTabs");
// Nav bar buttons list
const navList = document.createElement("ul");
navList.id = "navList";
navBar.appendChild(navList);
// Home button
makeElementText("homeButton", "li", navList, "<a>Home</a>");
const homeButton = document.getElementById("homeButton");
homeButton.className = "navBtn";
homeButton.style.textDecoration = "underline";
// Menu button
makeElementText("menuButton", "li", navList, "<a>Menu</a>");
const menuButton = document.getElementById("menuButton");
menuButton.className = "navBtn";
// About button
makeElementText("aboutButton", "li", navList, "<a>About</a>");
const aboutButton = document.getElementById("aboutButton");
aboutButton.className = "navBtn";
}
// Function to highlight button depending on which page is viewed.
function highlightSelected(selected, non1, non2) {
selected.style.textDecoration = "underline";
non1.style.textDecoration = "none";
non2.style.textDecoration = "none";
}
export { pageLoad, highlightSelected } |
$(function(){
//header里的微信二维码
$("#header .header .left .weixin").hover(
function(){
$(this).find("img").show();
},
function(){
$(this).find("img").hide();
}
);
$.ajax({
type: "post",
url: "../getGoodsJson.php",
success: function(data){
var arr = eval("("+data+")");
console.log(arr);
for(var i=0;i<arr.length;i++){
var str = '<dl><dt><a href="details'+arr[i].goodsId+'.html"><img src="../'
+arr[i].goodsImg+'" /></a></dt><dd><a>'+arr[i].goodsName+
'</a><a>'+arr[i].goodsDesc+'</a><a>'+
arr[i].goodsPrice+'</a></dd></dl>';
$(".goodsDl").append(str);
}
}
});
//图片放大
$(".goodsDl").on("mouseenter","dl",function(){
$(this).find("img").stop(true,true).animate({"width":"100%","height":"100%"},200);
});
$(".goodsDl").on("mouseleave","dl",function(){
$(this).find("img").stop(true,true).animate({"width":"80%","height":"80%"},200);
});
});
|
var express = require("express");
var router = express.Router();
var restaurantService = require("../services/restaurantService");
router.get("/restaurants", function(req, res){
restaurantService.getRestaurants()
.then(restaurants => res.json(restaurants));
});
router.get("/restaurants/:id", function(req, res){
var id = req.params.id;
restaurantService.getRestaurant(id)
.then(restaurant => res.json(restaurant));
});
module.exports = router; |
/*
* @lc app=leetcode id=268 lang=javascript
*
* [268] Missing Number
*/
/**
* @param {number[]} nums
* @return {number}
*/
var missingNumber = function(nums) {
const n = nums.length;
return (1 + n) * n / 2 - nums.reduce((count, i) => count + i);
};
|
// to create an instance of ProductsController Class
const productsControl = new ProductsController();
function loadData() {
//add items to the ProductsController Class - items currently are hard coded into the class
productsControl.addItem("31263", "Rugged Backpack", ["black", "red", "blue", "white"], "$69.90", "Lorem ipsum dolor sit, amet consectetur adipisicing elit.", "images/featured-bag3.jpg", "men");
productsControl.addItem("12312", "Stylish Backpack", ["black", "white", "pink"], "$59.90", "Lorem ipsum dolor sit, amet consectetur adipisicing elit.", "images/bag1.jpg", "ladies");
productsControl.addItem("54567", "Playful Backpack", ["black", "pink"], "$25.90", "Lorem ipsum dolor sit, amet consectetur adipisicing elit.", "images/bag2.jpg", "kids");
productsControl.addItem("21314", "Social Backpack", ["black", "blue", "brown", "white"], "$59.90", "Lorem ipsum dolor sit, amet consectetur adipisicing elit.", "images/bag2.jpg", "ladies");
productsControl.addItem("65743", "After-work Backpack", ["black"], "$59.90", "Lorem ipsum dolor sit, amet consectetur adipisicing elit.", "images/featured-bag2.jpg", "men");
productsControl.addItem("54587", "Fun Backpack", ["black", "pink"], "$25.90", "Lorem ipsum dolor sit, amet consectetur adipisicing elit.", "images/bag3.jpg", "kids");
productsControl.addItem("21314", "Fashionable Backpack", ["black", "blue", "brown", "white"], "$59.90", "Lorem ipsum dolor sit, amet consectetur adipisicing elit.", "images/bag3.jpg", "ladies");
productsControl.addItem("65743", "Outdoor Backpack", ["black"], "$59.90", "Lorem ipsum dolor sit, amet consectetur adipisicing elit.", "images/bag1.jpg", "men");
productsControl.addItem("54587", "School Backpack", ["black", "pink"], "$25.90", "Lorem ipsum dolor sit, amet consectetur adipisicing elit.", "images/featured-bag3.jpg", "kids");
productsControl.addItem("21314", "Gym Backpack", ["black", "blue", "brown", "white"], "$59.90", "Lorem ipsum dolor sit, amet consectetur adipisicing elit.", "images/featured-bag1.jpg", "ladies");
productsControl.addItem("65743", "Ball games Backpack", ["black", "blue"], "$59.90", "Lorem ipsum dolor sit, amet consectetur adipisicing elit.", "images/bag3.jpg", "men");
productsControl.addItem("54587", "Sports day Backpack", ["black", "pink", "red"], "$25.90", "Lorem ipsum dolor sit, amet consectetur adipisicing elit.", "images/bag1.jpg", "kids");
productsControl.addItem("31263", "Hiking Backpack", ["black", "red", "blue", "white"], "$69.90", "Lorem ipsum dolor sit, amet consectetur adipisicing elit.", "images/featured-bag3.jpg", "men");
productsControl.addItem("12312", "Meet-up Backpack", ["black", "white", "pink"], "$59.90", "Lorem ipsum dolor sit, amet consectetur adipisicing elit.", "images/bag1.jpg", "ladies");
productsControl.addItem("54567", "Friends Backpack", ["black", "pink"], "$25.90", "Lorem ipsum dolor sit, amet consectetur adipisicing elit.", "images/bag2.jpg", "kids");
productsControl.displayItem();
}
loadData(); |
// Copyright 2010 William Malone (www.williammalone.com)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
var buf=0;
var canvas;
var context;
var canvasWidth = 200;
var canvasHeight = 200;
var padding = 25;
var lineWidth = 8;
var colorPurple = "#cb3594";
var colorGreen = "#659b41";
var colorYellow = "#ffcf33";
var colorBrown = "#986928";
var backgroundImage = new Image();
var clickX = new Array();
var clickY = new Array();
var new_clickX = new Array();
var new_clickY = new Array();
var clickColor = new Array();
var clickTool = new Array();
var clickSize = new Array();
var clickDrag = new Array();
var paint = false;
var curColor = colorPurple;
var curTool = "marker";
var curSize = "normal";
var drawingAreaX = 0;
var drawingAreaY = 0;
var drawingAreaWidth = 200;
var drawingAreaHeight = 200;
var sizeHotspotWidthObject = new Object();
sizeHotspotWidthObject.huge = 39;
sizeHotspotWidthObject.large = 25;
sizeHotspotWidthObject.normal = 18;
sizeHotspotWidthObject.small = 16;
var totalLoadResources = 1;
var curLoadResNum = 0;
var a=0,b=0,c=0,d=0;
/**
* Calls the redraw function after all neccessary resources are loaded.
*/
function resourceLoaded()
{
if(++curLoadResNum >= totalLoadResources){ //document.getElementById('canvas').getContext("2d").drawImage(backgroundImage, 0,0,canvasWidth, canvasHeight);
context.translate(Math.min(canvasHeight,canvasWidth)/2, Math.min(canvasHeight,canvasWidth)/2);
//alert(backgroundImage.height+" : "+backgroundImage.width);
//context.translate(160,160);
context.rotate(90*Math.PI/180);
context.translate(-Math.min(canvasHeight,canvasWidth)/2, -Math.min(canvasHeight,canvasWidth)/2);
//context.translate(-160,-160);
context.drawImage(backgroundImage,0,0,canvasWidth,canvasHeight);
/*
context.translate(Math.min(canvasHeight,canvasWidth)/2, Math.min(canvasHeight,canvasWidth)/2);
//alert(backgroundImage.height+" : "+backgroundImage.width);
context.rotate(-90*Math.PI/180);
context.translate(-Math.min(canvasHeight,canvasWidth)/2, -Math.min(canvasHeight,canvasWidth)/2);
*/
redraw();
}
}
/**
* Creates a canvas element, loads images, adds events, and draws the canvas for the first time.
*/
function prepareCanvas(imgs)
{
/*
var canvasDiv = document.getElementById('canvasDiv');
canvas = document.createElement('canvas');
canvas.setAttribute('width', 600);
canvas.setAttribute('height', 400);
canvas.setAttribute('id', 'canvas');
canvas.setAttribute('style','border: 5px solid black');
canvasDiv.appendChild(canvas);
context = canvas.getContext("2d");
//context.rotate(90*Math.PI/180);
var img=document.getElementById("aaa");
context.drawImage(img, 0,0);
alert("a");
//alert(Math.min(img.height,img.width)/2 + ":" + Math.min(img.height,img.width)/2);
canvas.setAttribute('width', 400);
canvas.setAttribute('height', 600);
context.translate(Math.min(img.height,img.width)/2, Math.min(img.height,img.width)/2);
context.rotate(90*Math.PI/180);
//alert("a");
context.translate(-Math.min(img.height,img.width)/2, -Math.min(img.height,img.width)/2);
//context.drawImage(img, -Math.min(400,600)/2,-Math.min(400,600)/2);
context.drawImage(img, 0,0);
//alert("b");
return true;
*/
//initialize again
clickX = new Array();
clickY = new Array();
new_clickX = new Array();
new_clickY = new Array();
clickColor = new Array();
clickTool = new Array();
clickSize = new Array();
clickDrag = new Array();
paint = false;
sizeHotspotWidthObject = new Object();
totalLoadResources = 1;
curLoadResNum = 0;
a=0;b=0;c=0;d=0;
if(context)
clearCanvas();
var canvasDiv = document.getElementById('canvasDiv');
if(!canvas){
alert("you canvas");
canvas = document.createElement('canvas');
var w=window.screen.width;
var h=window.screen.height;
//var w=544;
//var h=320;
canvas.setAttribute('width', canvasWidth);
canvas.setAttribute('height', canvasHeight);
canvas.setAttribute('id', 'canvas');
canvas.setAttribute('style','border: 5px solid black');
canvasDiv.appendChild(canvas);
context = canvas.getContext("2d");
//update height & width
canvasHeight= w-2*20;
canvasWidth = canvasHeight*4/3;
drawingAreaHeight = canvasHeight;
drawingAreaWidth = canvasWidth;
canvas.setAttribute('width', canvasHeight);
canvas.setAttribute('height', canvasWidth);
// Load images
backgroundImage.onload = function(){
if(buf==0)
resourceLoaded();
else{
context.drawImage(backgroundImage,0,0,canvasWidth,canvasHeight);
redraw();
}
}
backgroundImage.src=imgs;
}
else{
buf=1;
backgroundImage.src=imgs;
++curLoadResNum;
}
//rotate picture
//alert("a");
// Add mouse events
// ----------------
$("#canvas").on("vmousedown",function(e)
{
//a++;
//$("#mousedown").text(a);
// Mouse down location
// Mouse down location
var mouseX = e.pageX - this.offsetLeft;
var mouseY = e.pageY - this.offsetTop;
$("#mousedown").text(mouseX + " : " +mouseY);
//alert(mouseX + " : " + mouseY);
paint = true;
addClick(mouseX, mouseY, false);
redraw();
});
$("#canvas").on("vmousemove",function(e){
var mouseX = e.pageX - this.offsetLeft;
var mouseY = e.pageY - this.offsetTop;
$("#mousemove").text(mouseX + " : " +mouseY);
if(paint==true){
//alert("a");
addClick(e.pageX - this.offsetLeft, e.pageY - this.offsetTop, true);
redraw();
}
});
$("#canvas").on("vmouseup",function(e){
paint = false;
redraw();
});
$("#canvas").on("vmouseout",function(e){
paint = false;
});
//alert("prepare done");
}
/**
* Adds a point to the drawing array.
* @param x
* @param y
* @param dragging
*/
function addClick(x, y, dragging)
{
if(x>0&&y>0&&x<canvasHeight&&y<canvasWidth){
clickX.push(x);
clickY.push(y);
new_clickX.push(y);
new_clickY.push(canvasHeight-x);
clickTool.push(curTool);
clickColor.push(curColor);
clickSize.push(curSize);
clickDrag.push(dragging);
}
}
/**
* Clears the canvas.
*/
function clearCanvas()
{
context.clearRect(0, 0, canvasWidth, canvasHeight);
}
/**
* Redraws the canvas.
*/
function redraw()
{
// Make sure required resources are loaded before redrawing
if(curLoadResNum < totalLoadResources){ return; }
clearCanvas();
//context.drawImage(backgroundImage, 0, -canvasHeight);
context.drawImage(backgroundImage, 0,0,canvasWidth,canvasHeight);
// Keep the drawing in the drawing area
context.save();
context.beginPath();
context.rect(drawingAreaX, drawingAreaY, drawingAreaWidth, drawingAreaHeight);
context.clip();
var radius;
var i = 0;
for(; i < clickX.length; i++)
{
context.beginPath();
if(clickDrag[i] && i){
//context.moveTo(clickX[i-1], clickY[i-1]);
context.moveTo(clickY[i-1],canvasHeight-clickX[i-1]);
}else{
//context.moveTo(clickX[i], clickY[i]);
context.moveTo(clickY[i],canvasHeight-clickX[i]);
}
//context.lineTo(clickX[i], clickY[i]);
context.lineTo(clickY[i],canvasHeight-clickX[i]);
context.closePath();
/*
if(clickTool[i] == "eraser"){
//context.globalCompositeOperation = "destination-out"; // To erase instead of draw over with white
context.strokeStyle = 'white';
}else{
//context.globalCompositeOperation = "source-over"; // To erase instead of draw over with white
context.strokeStyle = clickColor[i];
}*/
context.strokeStyle = clickColor[i];
context.lineJoin = "round";
context.lineWidth = radius;
context.stroke();
}
//context.globalCompositeOperation = "source-over";// To erase instead of draw over with white
context.restore();
context.globalAlpha = 1; // No IE support
}
|
/*
Class isimleri ile seçilen nesnelere tıkladığında
nesnenin içindeki değeri ekrana yazdırma
*/
$(function () {
$(".kutu h1").on("click", function () {
// div içindeki değerleri okumak için html() metodu kullanılır.
//$(this) aktif olan nesneyi ifade eder.
//$(this) ile tıkladığımız nesneyi seçeriz
let deger = $(this).html();
$("#yaz").html(deger);
});
});
|
const randomNumber = function randomNumber(length = 4) {
let result = '';
let characters = '0123456789';
let charactersLength = characters.length;
for (var i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
}
module.exports.randomNumber = randomNumber
module.exports = randomNumber |
import * as firebase from 'firebase';
//firebase connection
export const base = firebase.initializeApp({
apiKey: process.env.REACT_APP_FIREBASE_KEY,
authDomain: process.env.REACT_APP_FIREBASE_DOMAIN,
databaseURL: process.env.REACT_APP_FIREBASE_DATABASE,
projectId: process.env.REACT_APP_FIREBASE_PROJECT_ID,
storageBucket: process.env.REACT_APP_FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.REACT_APP_FIREBASE_SENDER_ID
});
export const goalRef = firebase.database().ref('goals');
export const completeGoalRef = firebase.database().ref('completeGoals');
// "auth != null" |
var mongoose = require("mongoose")
module.exports = mongoose.model("ability", {
data: {type: [String], default: []},
name: {type: String, default: ''},
cooldown: {type: String, default: ''},
mana: {type: String, default: ''},
description: {type: String, default: ''},
icon: {type: String, default: ''},
liveIcon: {type: String, default: ''},
lore: {type: String, default: ''},
heroID: {type: Number, default: 0},
id: {type: Number, default: 0}
})
|
import fecth from '../utils/fecth';
export default {
articleList(data){
return fecth.get('/articleList', data);
},
tagList(data){
return fecth.get('/tagList', data);
},
postTest(data){
return fecth.post('/postTest', data);
},
userInfo(data){
return fecth.get('/userInfo', data);
}
}
|
import Vue from 'vue'
import Router from 'vue-router'
import App from '@/App'
import Home from '@/components/Home'
import Find from '@/components/Find'
import My from '@/components/My'
import Order from '@/components/Order'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'app',
component: App
},
{
path: '/home',
name: 'home',
component: Home
},
{
path: '/find',
name: 'find',
component: Find
},
{
path: '/my',
name: 'my',
component: My
},
{
path: '/order',
name: 'order',
component: Order
}
]
})
|
import React from "react"
import { connect } from "react-redux";
import ShortNumber from "short-number"
import axios from "../../axios-orders"
import Translate from "../../components/Translate/Index"
class Index extends React.Component {
constructor(props) {
super(props)
this.state = {
item: props.item
}
}
static getDerivedStateFromProps(nextProps, prevState) {
if(typeof window == "undefined" || nextProps.i18n.language != $("html").attr("lang")){
return null;
}
if(nextProps.item.like_dislike != prevState.item.like_dislike){
return {item:nextProps.item}
} else{
return null
}
}
onChange = () => {
if(this.props.disabled){
return
}
if (this.props.pageInfoData && !this.props.pageInfoData.loggedInUserDetails) {
document.getElementById('loginFormPopup').click();
} else {
const formData = new FormData()
formData.append('id', this.props.id)
formData.append('type', this.props.type + "s")
formData.append('action', 'like')
let url = '/likes'
axios.post(url, formData)
.then(response => {
}).catch(err => {
//this.setState({submitting:false,error:err});
});
}
}
render() {
if (this.props.type != "channel_post" && this.props.pageInfoData.appSettings[`${(this.props.parentType ? this.props.parentType + "_" : "") + this.props.type + "_like"}`] != 1) {
return null
}
return (
this.props.pageInfoData.loggedInUserDetails && this.state.item.like_dislike == "like" ?
<span onClick={this.onChange} className="active" title={Translate(this.props,'Like')}><span className="material-icons-outlined md-18" data-icon="thumb_up"></span>{" " + `${ShortNumber(this.props.like_count ? this.props.like_count : 0)}`}</span>
:
<span onClick={this.onChange} className="icon" title={Translate(this.props,'Like')}><span className="material-icons-outlined md-18" data-icon="thumb_up"></span>{" " + `${ShortNumber(this.props.like_count ? this.props.like_count : 0)}`}</span>
)
}
}
const mapStateToProps = state => {
return {
pageInfoData: state.general.pageInfoData
};
};
export default connect(mapStateToProps, null)(Index)
|
var serveur=null;
var ConnecterServeur = function()
{
var classeServeur = "smartfox"/*node smartfox*/;
this.initialiserServeur = function(nom)
{
if(classeServeur=="node")
{
serveur = new CommuniquerServeurNode();
}
if(classeServeur=="smartfox")
{
serveur = new CommuniquerServeurSmartfox();
}
if(serveur!=null)
serveur.initialiserServeur(nom);
}
this.quitterSeveur = function()
{
serveur.quitterSeveur();
}
this.getNomJoueur = function()
{
return serveur.getNomJoueur();
}
this.getNomAdversaire = function()
{
return serveur.getNomAdversaire();
}
this.getPositionAutreJoueur = function()
{
return serveur.getPositionAutreJoueur();
}
this.getEtat = function()
{
return serveur.getEtat();
}
this.getDeplacementBalle = function()
{
return serveur.getDeplacementBalle();
}
this.getNumeroJoueur = function()
{
return serveur.getNumeroJoueur();
}
this.getPositionBalle = function()
{
return serveur.getPositionBalle();
}
}
function changerVariablesServeur(noms, valeurs)
{
if(serveur!=null)
serveur.changerVariablesServeur(noms, valeurs);
}
function tracer(message, alerte)
{
console.log(message);
if(!(alerte!=true)) alert(message);
} |
ajax={
getJSON:function(url, callback)
{
var xhr=new XMLHttpRequest();
xhr.addEventListener("load", function(e){
console.log(url);
console.log(this.response);
response=JSON.parse(this.response);
(callback)(response);
});
xhr.open("GET", url);
xhr.send();
},
getSearchResults:function(name, sku, callback)
{
ajax.getJSON("api/search?name="+encodeURIComponent(name)+"&sku="+encodeURIComponent(sku), callback);
},
getProduct:function(id, callback)
{
ajax.getJSON("api/getproduct?id="+encodeURIComponent(id), callback);
},
getProducts:function(ids, callback)
{
ajax.getProduct(encodeURIComponent(ids.join(",")), callback);
}
}
function formPost(path, params)
{
var form=document.createElement("form");
console.log(form);
form.method="POST";
form.action=path;
form.style.display="none";
for(var name in params) {
if(params.hasOwnProperty(name)) {
var input=form.appendChild(document.createElement("input"));
input.type="hidden";
input.name=name;
input.value=params[name];
}
}
document.body.appendChild(form);
form.submit();
}
|
var highlighterCode = function() {
// var doc = '';
// var id = '';
var newEl = null;
window.actOnElement = function(el, pos) {
var active = getVariable('active');
// var tmp = getVariable('tmp');
if (active === 'stop') {
// setVariable('tmp', '');
// doc = '';
// id = '';
newEl = null;
return;
}
if (!el) {
if (newEl === null) {
return;
}
// if (!tmp) {
// return;
// }
// var [doc, id] = tmp.split(' ');
// var elDoc = parent.document
// .getElementById('object-' + doc).contentWindow.document;
// var newEl = elDoc.getElementById(id);
var elDoc = newEl.ownerDocument;
var selection = elDoc.getSelection();
if (!selection || selection.type !== 'Range') {
return;
}
newEl.setAttribute('contenteditable', true);
elDoc.execCommand('styleWithCSS', true, null);
elDoc.execCommand(
'backColor',
false,
$('#sample').css('background-color')
);
newEl.setAttribute('contenteditable', false);
return;
} else {
// doc = el.ownerDocument.body.id;
// id = el.id;
newEl = el;
// setVariable('tmp', el.ownerDocument.body.id + ' ' + el.id);
}
};
instrumentCode();
};
var searchCode = function() {
var docId = '';
if (isInEditor(this)) {
$('.sub-instrument#search').on(touch ? 'tap' : 'click', function(e) {
// var docId = getVariable('tmp');
var text = $('#text').text();
if (!docId) {
$.ajax('/api/search?query=' + text).done(function(response) {
var resultsContainer = $('#resultsContainer');
resultsContainer.html('');
var ids = response.ids;
ids.splice(10);
ids.forEach(function(id) {
var el = document.createElement('div');
el.setAttribute('id', id.id);
$(el).html(id.id);
resultsContainer.append(el);
var snippets = document.createElement('div');
snippets.setAttribute('id', 'snippet-' + id.id);
id.positions.forEach(function(position) {
var snippet = document.createElement('p');
$(snippet).html(position);
$(snippets).append(snippet);
});
resultsContainer.append(snippets);
resultsContainer.append(document.createElement('hr'));
$(document.body).highlight(text);
});
});
return;
}
var targetEl = $(parent.document).find('#object-' + docId)[0];
if (!targetEl) {
return;
}
var targetDoc = targetEl.contentDocument;
$(targetDoc.body).removeHighlight();
$(targetDoc.body).highlight(text);
});
$('#stop').on(touch ? 'tap' : 'click', function(e) {
// var docId = getVariable('tmp');
if (!docId) {
return;
}
var targetDoc = $(parent.document).find('#object-' + docId)[0].contentDocument;
$(targetDoc.body).removeHighlight();
// setVariable('tmp', '');
docId = '';
removeOthers('search');
});
}
window.actOnElement = function(el, pos) {
// if ($(el).attr('id') === 'pairing-button') {
// console.log('bla');
// }
if (!el) {
return;
}
// setVariable('tmp', el.ownerDocument.body.getAttribute('id'));
docId = el.ownerDocument.body.getAttribute('id');
};
instrumentCode();
};
var createObjectById = function(id) {
var iframe = document.createElement('iframe');
iframe.setAttribute(
'src',
'new?prototype=objectBase&id=' + id.replace('.txt', '')
);
$(document.body).append(iframe);
$(iframe).on('transcluded', function(e) {
var iframeDoc = this.contentDocument;
var textContainer = iframeDoc.createElement('div');
iframeDoc.body.setAttribute('id', name.replace('.txt', ''));
$(iframeDoc.body).append(textContainer);
$.ajax('/file?id=' + id).done(function(response) {
$(textContainer).html(response.text);
// $(this).remove();
}.bind(iframe));
}.bind(iframe));
return iframe;
};
var textObjectCreatorCode = function() {
$('.sub-instrument#create').on(touch ? 'tap' : 'click', function(e) {
$.ajax('/fileNames').done(function(response) {
response.names.forEach(function(name, i) {
if (!name.endsWith('.txt') || i <= -1 || i > 100) {
return;
}
createObjectById(name);
});
});
});
};
// var historyCode = function() {
// window.actOnElement = function(el, pos) {
// if (!el || isInDocument(el, document)) {
// return;
// }
// var state = getVariable('active');
// if (state === 'redo') {
// return;
// }
// var tmp = $('#tmp');
// var iframe = document.createElement('iframe');
// // iframe.setAttribute('src', el.ownerDocument.body.id);
// iframe.setAttribute('src', el.ownerDocument.body.id + '?v=-1');
// tmp.html(iframe);
// // iframe.addEventListener('transcluded', function(e) {
// // debugger;
// // });
// };
//
// instrumentCode();
// };
var textInserterCode = function() {
var selected = new Set();
var newEl = null;
window.actOnElement = function(el, pos) {
if (!el && newEl) {
el = newEl;
newEl = null;
selected.add(el.ownerDocument.body.id + ' ' + el.id);
$(el).find('svg').css('display', 'none');
el.setAttribute('contenteditable', true);
el.ownerDocument.execCommand('styleWithCSS', true, null);
var sample = $('#sample').find('span')[0];
// console.log($(sample).css('text-decoration'));
if ($(sample).css('font-weight') === 'bold') {
el.ownerDocument.execCommand('bold');
}
if ($(sample).css('font-style') === 'italic') {
el.ownerDocument.execCommand('italic');
}
if ($(sample).css('text-decoration') === 'underline') {
el.ownerDocument.execCommand('underline');
}
// console.log($(sample).css('color'));
el.ownerDocument.execCommand('foreColor', false, $(sample).css('color'));
// console.log($(sample).css('font-weight'));
// console.log($(sample).css('font-style'));
// console.log($(sample).css('font-size'));
return;
}
if (el && !newEl) {
newEl = el;
}
var state = getVariable('active');
if (state === 'stop') {
return;
}
};
var clearContentEditable = function(docIds) {
// var selected = getVariable('tmp');
var keep = new Set();
var remove = [];
selected.forEach(function(selEl) {
var parts = selEl.split(' ');
var doc = parts[0];
var id = parts[1];
// var [doc, id] = selEl.split(' ');
// if (docIds.indexOf(doc) >= 0) {
remove.push(selEl);
// } else {
// keep.push(selEl);
// }
});
remove.forEach(function(selEl) {
var parts = selEl.split(' ');
var doc = parts[0];
var id = parts[1];
// var [doc, id] = selEl.split(' ');
if (isInEditor(this)) {
var el = parent.document
.getElementById('object-' + doc).contentWindow.document
.getElementById(id);
if (el) {
$(el).attr('contenteditable', false);
$(el).find('svg').css('display', 'block');
}
}
});
// setVariable('tmp', keep);
selected = keep;
};
// window.turnOn = function(doc) {
// defaultOnMove(doc, false);
// };
window.turnOff = function(doc) {
var docId = doc.body.id;
clearContentEditable([docId]);
};
$('#stop').on(touch ? 'tap' : 'click', function(e) {
// var selected = getVariable('tmp');
var docIds = [];
selected.forEach(function(selEl) {
var parts = selEl.split(' ');
var doc = parts[0];
var id = parts[1];
// var [doc, id] = selEl.split(' ');
docIds.push(doc);
});
clearContentEditable(docIds);
});
instrumentCode();
};
var textStylerCode = function() {
var newEl = null;
var elDoc = null;
window.actOnElement = function(el, pos) {
// var tmp = getVariable('tmp');
if (!el || isInDocument(el, document)) {
// if (!isEmpty(tmp)) {
if (newEl && elDoc) {
// var [doc, id] = tmp.split(' ');
var state = $('.selected').attr('id');
if (!state) {
return;
}
// if (parent && doc && id) {
// var elDoc = parent.document
// .getElementById('object-' + doc).contentWindow.document;
var selection = elDoc.getSelection();
// el = elDoc.getElementById(id);
el = newEl;
el.setAttribute('contenteditable', true);
el.ownerDocument.execCommand('styleWithCSS', true, null);
if (state === 'bold') {
el.ownerDocument.execCommand('bold');
} else if (state === 'italic') {
el.ownerDocument.execCommand('italic');
} else if (state === 'underline') {
el.ownerDocument.execCommand('underline');
} else if (state === 'no-format') {
el.ownerDocument.execCommand('removeFormat');
} else if (state === 'verdana') {
el.ownerDocument.execCommand('fontName', false, 'verdana');
} else if (state === 'georgia') {
el.ownerDocument.execCommand('fontName', false, 'georgia');
}
el.setAttribute('contenteditable', false);
// setVariable('tmp', '');
newEl = null;
elDoc = null;
return;
// }
}
} else {
newEl = el;
elDoc = el.ownerDocument;
// setVariable('tmp', el.ownerDocument.body.id + ' ' + el.id);
}
};
instrumentCode();
};
var openerCode = function() {
var instrumentNames = new Set([
'resizer',
'mover',
'draw',
'clipboard',
'shapes',
'textStyler',
'textInserter',
'opener',
'search',
'colorPicker',
'highlighter'
]);
var reservedDocuments = new Set([
'frontpage',
'editorBase',
'newObject',
'new_instrument',
'sessionBase',
'objectBase',
'textObjectCreator',
'start',
'instrument_editor',
'newDocument'
]);
var objectNames = new Set();
if (!isInEditor(parent)) {
$('.shortcuts').remove();
$.ajax('/api/names').done(function(response) {
var shortcuts = document.createElement('div');
shortcuts.setAttribute('class', 'row shortcuts');
document.body.appendChild(shortcuts);
var instrumentShortcuts = document.createElement('div');
instrumentShortcuts.setAttribute('class', 'col s6');
instrumentShortcuts.setAttribute('id', 'instrument-shortcuts');
shortcuts.appendChild(instrumentShortcuts);
var instrumentTitle = document.createElement('h5');
instrumentTitle.innerText = 'Instruments:';
instrumentShortcuts.appendChild(instrumentTitle);
instrumentNames.forEach(function(name) {
var instrumentNode = document.createElement('div');
instrumentNode.setAttribute('id', name);
instrumentNode.setAttribute('class', 'name');
instrumentNode.innerText = name;
instrumentShortcuts.appendChild(instrumentNode);
if (document.body.id === 'new') {
$(instrumentNode).on(touch ? 'tap' : 'click', function() {
$('.selected').removeClass('selected');
$(this).addClass('selected');
});
} else if (document.body.id === 'opener') {
$(instrumentNode).on(touch ? 'tap' : 'click', function() {
openObjectByName($(this).attr('id'));
});
}
});
var otherShortcuts = document.createElement('div');
otherShortcuts.setAttribute('class', 'col s6');
otherShortcuts.setAttribute('id', 'instrument-shortcuts');
shortcuts.appendChild(otherShortcuts);
var othersTitle = document.createElement('h5');
othersTitle.innerText = 'Documents:';
otherShortcuts.setAttribute('id', 'other-shortcuts');
otherShortcuts.appendChild(othersTitle);
objectNames = new Set(response.ids);
response.ids.forEach(function(id) {
if (instrumentNames.has(id) || reservedDocuments.has(id)) {
return;
}
var node = document.createElement('div');
node.setAttribute('id', id);
node.setAttribute('class', 'name');
node.innerText = id;
if (document.body.id === 'new') {
$(node).on(touch ? 'tap' : 'click', function() {
$('.selected').removeClass('selected');
$(this).addClass('selected');
});
} else if (document.body.id === 'opener') {
$(node).on(touch ? 'tap' : 'click', function() {
openObjectByName($(this).attr('id'));
});
}
otherShortcuts.appendChild(node);
});
});
}
var openObjectByName = function(text, basedOn) {
if (parent.document !== document) {
if (!isInEditor(this)) {
$(parent).bind('beforeunload', function(e) {
$(parent.document.body).find('.opener-iframe').remove();
});
parent.location.href = '/' + text;
return;
}
var params = getParams(parent.location.search);
var name = normalizeName(text);
if (params.active && params.active.indexOf(name) === -1) {
if (!Array.isArray(params.active)) {
params.active = [params.active];
}
params.active.push('object-' + name);
}
parent.history.pushState(
'',
'Webstrates',
parent.location.origin + parent.location.pathname + stringFromParams(params)
);
if ($(parent.document.body).find('[object=object-' + normalizeName(text) + ']').length) {
parent.document.styleSheets[0].insertRule(
'.editor-container[object=object-' + name + '] {display: block !important;}', 0
);
return;
}
// setVariable('tmp', text);
var elContainer = parent.document.createElement('div');
elContainer.setAttribute('class', 'editor-container');
elContainer.setAttribute('object', 'object-' + normalizeName(text));
var iframe = parent.document.createElement('iframe');
if (objectNames.has(text)) {
iframe.setAttribute('src', normalizeName(text));
} else {
if (basedOn) {
iframe.setAttribute(
'src',
'new?prototype=' + basedOn + '&id=' + text
);
$(document.body).append(iframe);
} else {
iframe = createObjectById(text);
}
}
iframe.setAttribute('id', 'object-' + normalizeName(text));
iframe.style.width = '200px';
// iframe.style.display = 'none';
$(elContainer).prepend(iframe);
var shortcut = parent.document.createElement('div');
shortcut.setAttribute('class', 'shortcut');
shortcut.setAttribute('object', 'object-' + normalizeName(text));
$(shortcut).text(normalizeName(text));
$(elContainer).prepend(shortcut);
$(parent.document.body).prepend(elContainer);
$(iframe).on('transcluded', function(e) {
var iFrameDoc = $(this.contentDocument);
if (!iFrameDoc.find('#info').length) {
var objectHelpers = $(document)
.find('#info')[0]
.cloneNode(true);
iFrameDoc[0].body.appendChild(objectHelpers);
}
iFrameDoc[0].body.setAttribute('id', normalizeName(text));
parent.window.editorCode(this);
});
}
};
// getObjectNames();
// $('.update').on('click', function(e) {
// getObjectNames();
// });
var editorClicking = function() {
$('#editors').find('div').each(function(el) {
$(this).on('click', function() {
if (parent.document !== document) {
parent.location.href = $(this).text();
} else {
window.location.href = $(this).text();
}
});
});
};
var normalizeName = function(text) {
return text.replace('.txt', '').replace('.', '-');
};
editorClicking();
$('#open').on('click', function() {
var basedOnElements = $('.name.selected');
var basedOn;
if (basedOnElements.length) {
basedOn = $(basedOnElements[0]).text();
}
openObjectByName($('#name').text(), basedOn);
});
window.actOnElement = function(el, pos) {
if (!el || isInDocument(el, document)) {
return;
}
};
instrumentCode();
};
|
'use strict'
const User = use('App/Models/User')
const Hash = use ('Hash')
class UserController {
async login({auth,request , response })
{
const {email, password} = request.body
try
{
await auth.attempt(email,password)
return response.redirect('/panel')
}
catch(error)
{
return response.redirect('back')
}
}
async signUp({request,response,view})
{
const {email,password,name} = request.body
const user = new User()
user.email = email
user.username = name
user.password = password
await user.save()
return view.render('login')
}
async logout({auth,response})
{
await auth.logout()
return response.redirect('/login')
}
}
module.exports = UserController
|
import 'phoenix_html';
// import { Socket } from 'phoenix';
import SimpleMDE from 'simplemde';
import hljs from 'highlight.js';
// SimpleMDE setup
const mdEnabled = document.getElementById('js-markdown-enabled');
if(mdEnabled) {
let simplemde = new SimpleMDE({
element: mdEnabled,
autoDownloadFontAwesome: false
});
}
// Highlight.js setup
hljs.initHighlightingOnLoad();
// External links open in a new tab
(function() {
const docLinksArray = Array.from(document.links);
docLinksArray.filter(function(link) {
return link.hostname && link.hostname !== location.hostname;
}).map(function(a) {
a.setAttribute('target', '_blank');
a.setAttribute('rel', 'nofollow');
});
})();
|
import * as PropTypes from 'prop-types';
import * as React from 'react';
import Label from '../label/label';
import { uuid4 } from '../../../utils/utils';
/* eslint-disable */
const selected = function() {
const todayDate = new Date();
var mm = todayDate.getMonth() + 1;
var dd = todayDate.getDate();
return [(mm>9 ? '' : '0') + mm,
(dd>9 ? '' : '0') + dd,
todayDate.getFullYear()
].join('/').toString();
};
/**
* @uxpincomponent
*/
export default class DatePicker extends React.Component {
componentDidMount() {
setTimeout(() => {
const datePicker = document.getElementById('chi-datepicker-control');
const self = this;
if (datePicker) {
const input = datePicker.querySelector('input');
input.addEventListener('focus', () => {
self.props.focus();
});
input.addEventListener('blur', () => {
self.props.focusLost();
});
input.addEventListener('input', () => {
self.props.input();
});
input.addEventListener('change', () => {
self.props.valueChange();
});
}
}, 1000);
}
render() {
const dpId = `dp-${uuid4()}`;
const label = this.props.label
? (
<Label
htmlFor={`${dpId}-control`}
className="chi-label"
required={this.props.required}
label={this.props.label}>
</Label>
)
: null;
const excludedDays = `
${!this.props.su ? '0,' : ''}
${!this.props.mo ? '1,' : ''}
${!this.props.tu ? '2,' : ''}
${!this.props.we ? '3,' : ''}
${!this.props.th ? '4,' : ''}
${!this.props.fr ? '5,' : ''}
${!this.props.sa ? '6' : ''}
`;
return (
<div className="chi-form__item" style={{ width: '14rem' }}>
{label}
<chi-date-picker
id={dpId}
disabled={this.props.disabled}
excluded-weekdays={excludedDays}
excluded-dates={this.props.dates}
min={this.props.min}
max={this.props.max}
value={this.props.selected}
onClick={this.props.click}
mode={this.props.mode}
onMouseEnter={this.props.mouseOver}
onMouseLeave={this.props.mouseLeave}
onMouseDown={this.props.mouseDown}
onMouseUp={this.props.mouseUp}>
</chi-date-picker>
</div>
);
}
}
DatePicker.propTypes = {
disabled: PropTypes.bool,
label: PropTypes.string,
required: PropTypes.oneOf(['none', 'required', 'optional']),
mode: PropTypes.oneOf(['date', 'datetime']),
min: PropTypes.string,
max: PropTypes.string,
selected: PropTypes.string,
mo: PropTypes.bool,
tu: PropTypes.bool,
we: PropTypes.bool,
th: PropTypes.bool,
fr: PropTypes.bool,
sa: PropTypes.bool,
su: PropTypes.bool,
dates: PropTypes.string,
click: PropTypes.func,
focus: PropTypes.func,
focusLost: PropTypes.func,
input: PropTypes.func,
mouseDown: PropTypes.func,
mouseLeave: PropTypes.func,
mouseOver: PropTypes.func,
mouseUp: PropTypes.func,
valueChange: PropTypes.func,
};
/* eslint-enable */
DatePicker.defaultProps = {
disabled: false,
label: 'Label',
required: 'none',
mode: 'date',
selected: selected(),
mo: true,
tu: true,
we: true,
th: true,
fr: true,
sa: true,
su: true,
};
|
'use strict'
module.exports = {
NODE_ENV: '"production"',
APT_HOST: '"http://172.16.46.241:8081/yxxtcs"' // 生产环境下的地址
}
|
const Commando = require('discord.js-commando');
const winston = require('winston');
const path = require('path');
const client = new Commando.Client({
owner: process.env.OWNER,
commandPrefix: process.env.PREFIX
});
client.logger = winston.createLogger({
format: winston.format.combine(
winston.format.timestamp({
format: 'DD.MM.YYYY HH:mm:ss'
}),
winston.format.printf(info => `[${info.timestamp}] ${info.level}: ${info.message}`)
),
transports: [
new winston.transports.Console(),
new winston.transports.File({ filename: 'wokkibot.log' })
]
});
client
.on('ready', () => {
client.logger.info(`Logged in as ${client.user.tag}`);
client.user.setActivity('you', { type: 'WATCHING'} );
})
.on('warn', client.logger.error)
.on('error', client.logger.warn)
.on('commandRun', (cmd, promise, msg, args) => client.logger.info(`${msg.author.tag} (${msg.author.id}) ran command ${cmd.groupID}:${cmd.memberName}`))
.on('commandError', (cmd, err) => client.logger.error(`Error occurred when running command ${cmd.groupID}:${cmd.memberName}`, err));
client.registry
.registerGroups([
['music', 'Music commands'],
['general', 'General commands'],
['mod', 'Moderation commands']
])
.registerDefaultTypes()
.registerDefaultGroups()
.registerDefaultCommands({
unknownCommand: false
})
.registerCommandsIn(path.join(__dirname, 'commands'));
client.login(process.env.TOKEN); |
import {hp, vent} from '../../helper';
export let LoaderV = Backbone.View.extend({
id: 'scoreBord',
className: 'scoreBord',
template: hp.tmpl('tmplScoreBoard'),
initialize: function (options) {
this.parentV = options.pageV;
this.render();
this.timer = new TimerV(options);
this.loaderSlipV = new LoaderSlipV(options);
this.listenTo(vent, 'removeGame', this.remove);
},
render: function () {
this.parentV.$el.append(this.$el.append(this.template));
},
show: function () {
this.timer.render();
this.loaderSlipV.render();
this.$el.addClass('show');
},
hide: function () {
this.$el.removeClass('show');
}
});
let LoaderSlipV = Backbone.View.extend({
initialize: function (options) {
this.setElement('#loaderSlip');
vent.game.on('changeDestroyed', this.shift, this);
this.listenTo(vent, 'removeGame', this.remove);
},
render: function () {
this.$el.css({left: 0 });
},
shift: function () {
let percent = this.model.get('destroyed') / (this.model.get('NUMBER_GOALS') / 100)
,left = (this.$el.width() / 100) * percent
;
//console.log(this.model.get('destroyed'), this.model.get('NUMBER_GOALS'), left, this.$el.width(), percent);
this.$el.css({left: -left });
}
});
let TimerV = Backbone.View.extend({
initialize: function (options) {
this.setElement('#timer');
this.model = options.model;
this.listenTo(vent.game, 'firstShot', this.start, this);
this.listenTo(vent, 'removeGame', this.remove);
},
render: function () {
this.$el.text(this.model.get('PERIOD') - this.model.get('timeSpend'));
},
start: function () {
let id = setInterval(() => {
//console.log('isGameFinished',this.model.isGameFinished());
vent.game.trigger('changeTimeSpend');
this.render();
if (this.model.isGameFinished()) {
//console.log('clear timer');
clearTimeout(id);
}
}, 1000);
}
}); |
const reload = document.getElementById("reload");
const clock = document.getElementById("clock");
const todolist = document.getElementById("todolist");
const task = document.getElementById("task-input");
//clasess of icons
const CHECK = "fa-check-square";
const UNCHECK = "fa-square";
const CROSSLINE = "lineThrough";
//Variables
let list,id;
//localstorage
let data = localStorage.getItem("TODO");
if(data){
list = JSON.parse(data);
id = list.length;
loadList(list);
} else {
list = [];
id = 0;
}
function loadList (array){
array.forEach(function(element) {
addTask(element.name,element.id,element.done,element.trash);
});
}
reload.addEventListener("click",function(){
localStorage.clear();
location.reload();
});
// date and clock
const format = {
weekday: "long",
month: "short",
day: "numeric"
};
const date = new Date();
clock.innerHTML = date.toLocaleDateString("en-US",format);
function odliczanie()
{
var dzisiaj = new Date();
var godzina = dzisiaj.getHours();
if (godzina<10) godzina = "0"+godzina;
var minuta = dzisiaj.getMinutes();
if (minuta<10) minuta = "0"+minuta;
var sekunda = dzisiaj.getSeconds();
if (sekunda<10) sekunda = "0"+sekunda;
document.getElementById("zegar").innerHTML = godzina+":"+minuta+":"+sekunda;
setTimeout("odliczanie()",1000);
}
//add task function
function addTask(task,id,done, trash){
if(trash){return;}
const DONE = done? CHECK : UNCHECK;
const LINE = done? CROSSLINE : "";
const item = `<li class="task">
<i class="far ${DONE} co" job="complete" id =${id}></i>
<p class ="text ${LINE}">${task}</p>
<i class="fas fa-trash-alt de" job="delete" id = ${id}></i>
</li>`;
const position = "beforeend";
todolist.insertAdjacentHTML(position,item);
};
//add new task when user press enter
document.addEventListener("keyup", function(event){
if(event.keyCode == 13){
const todo = task.value;
if(todo){
addTask(todo,id,false,false);
list.push({
name: todo,
id: id,
done: false,
trash: false
});
localStorage.setItem("TODO", JSON.stringify(list));
id++;
}
task.value = "";
}
});
function completedTask(el) {
el.classList.toggle('fa-check-square');
el.classList.toggle('fa-square');
el.parentNode.querySelector(".text").classList.toggle(CROSSLINE);
list[el.id].done = !list[el.id].done;
}
function removeTask (el){
el.parentNode.parentNode.removeChild(el.parentNode);
list[el.id].trash = true;
}
todolist.addEventListener("click", function(event){
const element = event.target;
const elemJob = element.attributes.job.value;
if(elemJob == "complete"){
completedTask(element);
} else if( elemJob == "delete"){
removeTask(element);
}
localStorage.setItem("TODO", JSON.stringify(list));
}); |
var app = app || {};
(function () {
'use strict';
var Pages = Backbone.Collection.extend({
url: '/search',
model: app.Page,
parse: function(response, xhr){
return response.items;
}
});
// var colls = [
// {
// "author": "Johnson",
// "content": "This is a test document",
// "date": "2013-10-25",
// "title": "Test"
// },
// {
// "author": "Wife",
// "content": "This is a test document",
// "date": "2013-10-25",
// "title": "What the"
// }
// ];
app.pages = new Pages();
})();
|
var requirejs = require('requirejs');
var ModuleController = require('../controllers/module');
var TabController = requirejs('common/modules/tab');
var TabView = require('../views/modules/tab');
var parent = ModuleController.extend(TabController);
var TabModule = parent.extend({
visualisationClass: TabView,
initialize: function () {
this.tabs = _.map(this.model.get('tabs'), function (tab) {
tab.controller = TabModule.map[tab['module-type']];
tab.slug = this.model.get('slug') + '-' + tab.slug;
if (!tab.info) {
tab.info = this.model.get('info');
}
return tab;
}, this);
parent.prototype.initialize.apply(this, arguments);
},
render: function () {
this.tabModules = this.renderModules(
this.tabs,
this.model.get('parent'),
function (model) {
return {
url: this.url + '/' + model.get('slug')
};
}.bind(this),
{},
function () {
this.model.set('tabs', _.map(this.tabModules, function (module) {
return _.extend(module.model.toJSON(), { html: module.html });
}));
parent.prototype.render.apply(this);
}.bind(this)
);
}
});
module.exports = TabModule;
|
// with map function
let arr =[20,40,38,56];
function square(x){
return x*x;
}
let newarr = arr.map(square);
console.log(newarr);
//``````````````````````````````````````//
//without Map function Inner Working
function myarray(arr,cb){
let newarr=[];
for(let i=0;i<arr.length;i++){
let ans=cb(arr[i]);
newarr.push(ans);
}
return newarr;
}
console.log(myarray(arr,square)); |
#!/usr/bin/env node
/*
Copyright 2017 Linux Academy
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
const app = require('../app');
const debug = require('debug')('web-client:server');
const http = require('http');
const assertDynamoTable = require('../assertDynamoTable');
// Normalize a port into a number, string, or false.
const normalizePort = (val) => {
const tmpPort = parseInt(val, 10);
if (isNaN(tmpPort)) {
// named pipe
return val;
}
if (tmpPort >= 0) {
// port number
return tmpPort;
}
return false;
};
const port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
const server = http.createServer(app);
server.on('error', (error) => {
if (error.syscall !== 'listen') {
throw error;
}
const bind = typeof port === 'string' ? `Pipe ${port}` : `Port ${port}`;
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(`${bind} requires elevated privileges`);
process.exit(1);
break;
case 'EADDRINUSE':
console.error(`${bind} is already in use`);
process.exit(1);
break;
default:
throw error;
}
});
server.on('listening', () => {
// create dynamo table on startup to allow time for creation
assertDynamoTable(app.locals.dynamodb, app.locals.table);
const addr = server.address();
const bind = typeof addr === 'string' ? `pipe ${addr}` : `port ${addr.port}`;
console.log(`Listening on ${bind}`);
});
server.listen(port);
|
import React from 'react'
const RemoveChecked = ({ deleteAll }) => {
return (
<div className="remove">
<button className="remove-btn" onClick={() => deleteAll()}>Remove Checked</button>
</div>
)}
export default RemoveChecked |
'use strict';
window.showCard = (function () {
return function () {
// Переменные для диалогового окна
var dialog = document.querySelector('.dialog'); // Модальное окно
var dialogClose = document.querySelector('.dialog__close'); /* Кнопка закрыть модальное окно */
// Константы для keyCode
var ENTER_KEY_CODE = 13;
var ESCAPE_KEY_CODE = 27;
// Функции для проверки соответствия keyCode
var deactivatingEvent = function (e) {
return e.keyCode && e.keyCode === ESCAPE_KEY_CODE;
};
var activatingEvent = function (e) {
return e.keyCode && e.keyCode === ENTER_KEY_CODE;
};
/* функция, определяющая скрыто диалоговое окно, или показано
задаёт соответствующий статус aria-hidden */
var toggleAriaHidden = function () {
if (dialog.classList.contains('invisible')) {
dialog.setAttribute('aria-hidden', true);
} else {
dialog.setAttribute('aria-hidden', false);
}
};
// функция для управления отображением диалогового окна (показать - 'add', скрыть - 'remove')
var setDialogClassInvisible = function (action) {
dialog.classList[action]('invisible');
};
// закрытие диалогового окна и переключение статуса aria-hidden
var deactivateDialogAndPin = function (callback) {
setDialogClassInvisible('add');
// динамически изменяем статус aria-hidden диалогового окна
toggleAriaHidden();
var activePin = document.querySelector('.pin--active');
if (activePin) {
activePin.classList.remove('pin--active');
activePin.setAttribute('aria-pressed', false);
}
// если переданный параметр callback является функцией, запускаем его.
if (typeof callback === 'function') {
callback();
}
};
/* АЛГОРИТМ работы функции */
// Вызываем функцию, которая определит, скрыто диалоговое окно, или показано
toggleAriaHidden();
// !!!
document.addEventListener('keydown', function (e) {
if (deactivatingEvent(e)) {
deactivateDialogAndPin(window.callbackKeydownPin);// Вызов функции и коллбека
}
});
// закрытие диалогового окна и переключение статуса aria-hidden по клику
dialogClose.addEventListener('click', function () {
deactivateDialogAndPin(window.callbackKeydownPin);// Вызов функции и коллбека
});
// закрытие диалогового окна и переключение статуса aria-hidden по нажатию escape
dialogClose.addEventListener('keydown', function (e) {
if (activatingEvent(e)) {
deactivateDialogAndPin(window.callbackKeydownPin);// Вызов функции и коллбека
}
});
};
})();
|
const embeds = require('../util/embeds.js');
exports.help = {
syntax: 'kick <@USER|USER_ID> <REASON>',
required: 'KICK_MEMBERS',
description: 'Kick a user.'
};
exports.run = (client, message, args) => {
if (!args[0] || !args[1])
return embeds.errorSyntax(message.channel, client[message.guild.id].prefix + this.help.syntax);
const user = message.guild.member(message.mentions.users.first()) || message.guild.members.get(args[0]);
const reason = args.slice(1).join(' ');
if (!user) return embeds.error(message.channel, `User "${args[0]}" not found.`, 'ERROR');
if (message.member.highestRole.calculatedPosition <= user.highestRole.calculatedPosition)
return embeds.errorAuthorized(message.channel, "You can't kick a user with the same or higher permissions.");
if (user.id === client.user.id) return embeds.error(message.channel, "I can't kick myself.", 'ERROR');
user
.kick(`Kicked by: ${message.author.username}#${message.author.discriminator}, Reason: ${reason}`)
.then(embeds.feedbackReason(message.channel, `${message.author} kicked ${user}`, 'KICK', reason))
.catch(err => {
if (err) console.error(err);
});
};
|
const mongoose = require('mongoose');
const schema = mongoose.Schema;
const rewardPointsSchema = new schema({
rewardAmount: String,
rewardStatus: String,
createdDate: {
type: Date,
default: Date.now
},
})
const reward= module.exports = mongoose.model('Reward',rewardPointsSchema); |
export { default } from './ShopItemFunc';
|
const router = require("express").Router();
const { User, Transaction } = require("../db/models");
// const isLoggedIn = require("./middleware/isLoggedIn");
// const isAdminUser = require("./middleware/isAdminUser");
module.exports = router;
//GET USER TRANSACTION HISTORY
//is it necessary to send the user id?
router.get("/:id", async (req, res, next) => {
try {
const transactions = await Transaction.findAll({
where: {
userId: req.params.id,
},
});
res.send(transactions);
} catch (err) {
console.error(err);
next(err); // <-- do we need that
}
});
//NEW TRANSACTION
router.post("/", async (req, res, next) => {
try {
const newTransaction = await Transaction.create(req.body);
res.send(newTransaction);
} catch (err) {
console.error(err);
}
});
|
import React from 'react';
import {Alert} from 'react-bootstrap';
import {bindActionCreators} from 'redux'
import {connect} from 'react-redux'
import {removeError} from '../actions/app-actions'
export default class MyAlert extends React.Component {
constructor(props) {
super(props);
this.state = {visible: false};
}
handleAlertDismiss = () => {
const {removeError} = this.props.appActions;
removeError(this.props.num);
};
componentWillReceiveProps = (nextProps) => {
this.setState({visible: nextProps.error});
};
render() {
if (this.state.visible) {
return (
<Alert bsStyle="danger" onDismiss={this.handleAlertDismiss}>
<h4>Oh snap! You got an error!</h4>
<p>{this.props.error.message}</p>
</Alert>
);
}
return null;
}
}
function mapDispatchToProps(dispatch) {
return {
appActions: bindActionCreators({removeError}, dispatch)
}
}
export default connect(null, mapDispatchToProps)(MyAlert) |
import React from 'react';
import {
InputGroup, InputGroupText, InputGroupAddon, Input,
Button, Form, FormGroup, Label,
Modal, ModalBody, ModalFooter, ModalHeader
} from 'reactstrap';
const AddItemtoBudget = props => {
return (
<div style={{ display: "inline-block" }}>
{/* <Button size="sm" color="danger" style={{ display: "inline-block" }} onClick={this.toggle}>+</Button> */}
<Modal isOpen={props.open} toggle={props.toggle}>
<ModalHeader toggle={props.toggle}>Cotizar Item</ModalHeader>
<ModalBody>
<Form>
<div className="row">
<div className="col-md-6">
<FormGroup>
<Label for="price">Precio Unitario</Label>
<InputGroup>
<InputGroupAddon addonType="append">$</InputGroupAddon>
<Input type="number" min="0" value={props.price} name="price" total="totalprice" id="price" onChange={props.inputHandler}></Input>
</InputGroup>
</FormGroup>
</div>
<div className="col-md-6">
<FormGroup>
<Label for="totalprice">Precio Total</Label>
<InputGroup>
<InputGroupAddon addonType="append">$</InputGroupAddon>
<Input disabled name="totalprice" id="totalprice" value={props.price*props.quantity} ></Input>
</InputGroup>
</FormGroup>
</div>
</div>
<div className="row">
<div className="col-md-6">
<FormGroup>
<Label for="weight">Peso Unitario</Label>
<InputGroup>
<Input type="number" value={props.weight} min="0" name="weight" id="weight" onChange={props.inputHandler}></Input>
<Input type="select" value={props.measure} name="measure" onChange={props.inputHandler}>
<option value="g">g</option>
<option value="m">m</option>
<option value="m2">m²</option>
<option value="m3">m³</option>
<option value="lt">lt</option>
</Input>
</InputGroup>
</FormGroup>
</div>
<div className="col-md-6">
<FormGroup>
<Label for="totalweight">Peso Total</Label>
<InputGroup>
<Input disabled min='0' value={props.weight*props.quantity} name="totalweight" id="totalweight" ></Input>
<InputGroupAddon addonType="append">{props.measure}</InputGroupAddon>
</InputGroup>
</FormGroup>
</div>
</div>
<br />
<div className="row">
<div className="col-md-12">
<InputGroup size="md">
<InputGroupAddon addonType="prepend">
<InputGroupText>Proveedor</InputGroupText>
</InputGroupAddon>
<Input name="provider" id="provider" value={props.provider} onChange={props.inputHandler}></Input>
</InputGroup>
</div>
</div>
<br />
<div className="row">
<div className="col-md-12">
<FormGroup>
<Label for="estado">Estado</Label>
<Input value={props.estado} onChange={props.inputHandler} type="select" name="estado" id="estado" >
{props.estados.map((estado,i)=>(
<option key={i} value={i}>{estado.name}</option>
))}
{/* <option value="Cotizado con Comentarios">Cotizado con comentarios</option>
<option value="Pendiente de entrega">Pendiente de entrega</option>
*/}
</Input>
</FormGroup>
</div>
</div>
<div className="row">
<div className="col-md-12">
<InputGroup size="">
<InputGroupAddon addonType="prepend">
<InputGroupText>Comentarios</InputGroupText>
</InputGroupAddon>
<Input type="textarea" name="comments" id="comments" onChange={props.inputHandler}></Input>
</InputGroup>
</div>
</div>
</Form>
</ModalBody>
<ModalFooter>
<Button color="primary" onClick={props.submitHandler}>Agregar</Button>{' '}
<Button color="secondary" onClick={props.toggle}>Volver</Button>
</ModalFooter>
</Modal>
</div>
);
};
export default AddItemtoBudget; |
const Discord = require('discord.js')
const fs = require('fs');
const escapeRegex = str => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
module.exports = {
name: 'message',
async execute(message, client) {
client.commands = new Discord.Collection();
const commandFolders = fs.readdirSync('./commands');
for (const folder of commandFolders) {
const commandFiles = fs.readdirSync(`./commands/${folder}`).filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`../commands/${folder}/${file}`);
client.commands.set(command.name, command);
}
}
delete require.cache[require.resolve('../config.json')];
const config = require('../config.json');
const prefixRegex = new RegExp(`^(<@!?${client.user.id}>|${escapeRegex(config.discord.prefix)})\\s*`);
if ((!prefixRegex.test(message.content)) || message.author.bot) return;
const [, matchedPrefix] = message.content.match(prefixRegex);
const args = message.content.slice(matchedPrefix.length).trim().split(/ +/);
const commandName = args.shift().toLowerCase();
const command = client.commands.get(commandName) || client.commands.find(cmd => cmd.aliases && cmd.aliases.includes(commandName));
if (!command) return;
if (message.channel.type === 'dm') return;
if ((message.author.id != config.discord.ownerId) && command.ownerOnly) return message.channel.send(
new Discord.MessageEmbed()
.setDescription(`Sorry, you don't have permission to do this`)
.setColor('DC143C')
);
try {
command.execute(message, args);
} catch (error) {
console.error(error);
return message.channel.send(
new Discord.MessageEmbed()
.setDescription(`Something went wrong, please try again in a few minutes`)
.setColor('DC143C')
);
}
},
}; |
import path from 'path';
import webpack from 'webpack';
import autoprefixer from 'autoprefixer';
import precss from 'precss';
import LiveReloadPlugin from 'webpack-livereload-plugin';
import webpackCombineLoaders from 'webpack-combine-loaders';
import serverConfig from './server.config';
export default {
devtool: 'sourcemap',
watch: true,
entry: {
base: [
'babel-polyfill',
'./src/index.js'
]
},
output: {
path: path.join(__dirname, 'dist'),
publicPath: '/dist/',
filename: 'bundle.js'
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new LiveReloadPlugin({
hostname: serverConfig.url,
appendScriptTag: true
})
],
resolve: {
modules: [
path.join(__dirname, 'src'),
path.join(__dirname, 'node_modules')
],
extensions: ['.js', '.jsx', '.css', '.scss']
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
use: ['babel-loader']
},
{
test: /\.css$/,
loader: webpackCombineLoaders([
{
loader: 'css-loader',
query: {
modules: true,
camelCase: true,
localIdentName: '[path][name]---[local]---[hash:base64:5]',
},
},
{
loader: 'postcss-loader',
},
]),
},
{
test: /\.s[ac]ss$/,
loader: webpackCombineLoaders([
{
loader: 'style-loader',
},
{
loader: 'css-loader',
query: {
modules: true,
camelCase: true,
localIdentName: '[local]',
},
},
{
loader: 'postcss-loader',
},
{
loader: 'sass-loader',
query: {
sourceMaps: 'true',
},
},
]),
}
]
}
}
|
var mkdirp = require('mkdirp');
var fs = require('fs');
var path = require('path');
var readline = require('readline');
var package = require('./package');
/**
* mkdir -p
*
* @param {String} pathName
* @param {Function} callback
*/
function mkdirP(pathName) {
return new Promise(function (resolve, reject) {
mkdirp(pathName, 0755, function (error) {
if (error) reject(error);
console.log(' [√] created: ' + pathName);
resolve();
});
});
}
/**
* read and load a file content from /templates
*
* @param {String} fileName
* @returns {*}
*/
function loadFile(filePath) {
return fs.readFileSync(path.join(__dirname, filePath), 'utf-8');
}
/**
* receive string data and write to a file
*
* @param {String} path
* @param {String} data
* @param {Number} mode
*/
function writeToFile(pathName, data, mode) {
return new Promise(function (resolve, reject) {
fs.writeFileSync(pathName, data, {
mode: mode || 0666
});
console.log(' [√] created: ' + pathName);
resolve();
});
}
/**
* determine if the dir is empty and pass a boolean to the callback function
*
* @param {String} path
* @param {Function} callback
*/
function isEmptyDir(path, callback) {
fs.readdir(path, function (error, files) {
if (error && 'ENOENT' != error.code) throw new Error(error);
callback(!files || !files.length);
});
}
/**
* determine if launched from cmd and return a boolean
*
* @returns {boolean}
*/
function isCmd() {
return process.platform === 'win32' && process.env._ === undefined;
}
/**
* make a prompt to STDIN or STDOUT
*
* @param message
* @param callback
*/
function mkPrompt(message, callback) {
var newPrompt = readline.createInterface({
input: process.stdin,
output: process.stdout
});
newPrompt.question(message, function (answer) {
newPrompt.close();
callback(/^y|yes|ok|true$/i.test(answer));
});
}
function finished(appName, typescript) {
var prompt = isCmd() ? '>' : '$';
console.log('\n');
console.log('\x1b[32m%s\x1b[0m', ' Successfully generated a new Koa2 RESTFul project - ' + appName + '!\n');
if (typescript) {
console.log('\x1b[36m%s\x1b[0m', ' [+] Run the project in DEV mode: ');
console.log(' %s npm start\n', prompt);
console.log('\x1b[36m%s\x1b[0m', ' [+] Run the project in PRODUCTION mode: ');
console.log(' %s npm run serve (requires pm2 global installation)\n', prompt);
console.log('\x1b[36m%s\x1b[0m', ' [+] Build the project: ');
console.log(' %s npm run build\n', prompt);
console.log('\x1b[36m%s\x1b[0m', ' [+] Clean the project: ');
console.log(' %s npm run clean\n', prompt);
console.log('\x1b[36m%s\x1b[0m', ' [+] Lint the project: ');
console.log(' %s npm run lint\n', prompt);
console.log(' The project is written in TypeScript.\n To read TypeScript documentation, please leave for https://www.typescriptlang.org/docs/home.html\n');
} else {
console.log('\x1b[36m%s\x1b[0m', ' [+] Run the project in DEV mode: ');
console.log(' %s npm run dev\n', prompt);
console.log('\x1b[36m%s\x1b[0m', ' [+] Run the project in PRODUCTION mode: ');
console.log(' %s npm run prod (requires pm2 global installation)\n', prompt);
}
console.log(' For more information, please leave for ' + package.homepage);
console.log(' For bugs or issues, please leave for ' + package.bugs.url);
}
module.exports = {
mkdirP,
loadFile,
writeToFile,
isEmptyDir,
mkPrompt,
finished
}
|
import React from "react";
import PropTypes from "prop-types";
class Appnotifier extends React.Component {
render() {
return (
<React.Fragment>
<h3>{this.props.message}</h3>
</React.Fragment>
);
}
}
export default Appnotifier;
|
/**
* 汉字简繁转换
*
* @auth superbiger(superbiger@qq.com)
*/
import { PinyinResource } from "./PinyinResource.js"
var CHINESE_REGEX = /^[\u4e00-\u9fa5]+$/;
var CHINESE_MAP = PinyinResource.getChineseResource();
export class ChineseHelper {
/**
* 将单个繁体字转换为简体字
* @param {string/char} c
*/
static _convertCharToSimplifiedChinese(c) {
var simplifiedChinese = CHINESE_MAP[c];
if(typeof(simplifiedChinese) == "undefined") {
return c;
}
return simplifiedChinese;
}
/**
* 将单个简体字转换为繁体字
* @param {string/char} c
*/
static _convertCharToTraditionalChinese(c) {
for(var key in CHINESE_MAP) {
if(CHINESE_MAP[key] == c) {
return key;
}
}
return c;
}
/**
* 将繁体转化为简体
* @param {string} str
*/
static convertToSimplifiedChinese(str) {
var result = '';
for(var i=0; i < str.length; i++) {
var c = str.charAt(i);
result += this._convertCharToSimplifiedChinese(c);
}
return result;
}
/**
* 将简体转化为繁体
* @param {string} str
*/
static convertToTraditionalChinese(str) {
var result = '';
for(var i=0; i < str.length; i++) {
var c = str.charAt(i);
result += this._convertCharToTraditionalChinese(c);
}
return result;
}
/**
* 判断是否为繁体字
* @param {string/char} c
*/
static isTraditionalChinese(c) {
var val = CHINESE_MAP[c];
return typeof(val) != 'undefined'
}
/**
* 判断是否为汉字
* @param {string/char} c
*/
static isChinese(c) {
return '〇' == c || CHINESE_REGEX.test(c)
}
/**
* 是否包含汉字
* @param {string} str
*/
static containsChinese(str) {
for(var i=0; i < str.length; i++) {
if(this.isChinese(str.charAt(i))){
return true;
}
}
return false;
}
static addChineseDictResource(res) {
CHINESE_MAP = Object.assign(res, CHINESE_MAP);
}
} |
import React from 'react';
import PropTypes from 'prop-types';
const Index = (props) => {
const { loading=false, text } = props
return loading?(
<div className="bxs-loading">
<div className="bxs-loading-snake"></div>
<div className="bxs-loading-text">{text}</div>
</div>
):null
}
Index.propTypes = {
loading: PropTypes.bool,
text: PropTypes.string
}
export default Index; |
/* global describe, it, expect */
import React from 'react'
import { render } from 'setup-test'
import Toggle from '.'
describe('Toggle', () => {
it('should render as a checkbox', () => {
const { container } = render(
<Toggle type="checkbox" id="example" name="example" />
)
expect(container).toMatchSnapshot()
})
it('should render as a radio', () => {
const { container } = render(
<Toggle type="radio" id="example" name="example" />
)
expect(container).toMatchSnapshot()
})
})
|
// https://github.com/airbnb/babel-preset-airbnb
// TODO: eslint-config-airbnb requires babel-preset-airbnb
module.exports = {
presets: [
// https://babel.dev/docs/en/babel-preset-env
'@babel/preset-env',
// https://babel.dev/docs/en/babel-preset-react
['@babel/preset-react', { runtime: 'automatic' }],
// https://babel.dev/docs/en/babel-preset-typescript
'@babel/preset-typescript',
],
};
|
const loopy = "Loopy";
const lighthouse = "Lighthouse";
for (let i = 100; i <= 200; i++){
if (i % 3 === 0 && i % 4 === 0){
console.log(loopy + lighthouse);
} else if (i % 3 === 0){
console.log(loopy);
} else if (i % 4 === 0){
console.log(lighthouse);
} else {
console.log(i);
}
} |
module.exports = {
port: process.env.PORT,
app: {
url: process.env.APP_URL
},
assets: {
url: process.env.ASSETS_URL
},
authentication: {
secret: process.env.AUTHENTICATION_SECRET,
remote: {
google: {
clientID: 'TODO',
clientSecret: 'TODO'
},
facebook: {
clientID: 'TODO',
clientSecret: 'TODO'
},
github: {
clientID: 'TODO',
clientSecret: 'TODO'
}
}
}
}
|
class Parent {
constructor(name, age) {
this.name = name
this.age = age
}
sayName() {
// NOTE TEMPLATE
return `Hi, I am ${this.name}`
}
increaseAge(num) {
this.age += num;
}
getAge() {
return this.age;
}
}
const parent = new Parent('Billy', 43)
class Kid extends Parent {
constructor(name, age, parent) {
super(name, age);
this.parent = parent;
}
getParentName() {
if (this.parent) {
return this.parent.sayName();
}
return 'I don\'t have a parent'
}
}
const kid = new Kid('Suzie', 12, parent);
// console.log(kid.getParentName())
// console.log(kid.sayName())
// console.log(parent.getParentName())
|
/** =================================================== */
/**
* 全局数据
*/
/** =================================================== */
const Service_Phone = "0793-322132153"; // 客服电话
const Version_Name = "Beta 1.1.25"; // 版本名称
const Version_Code = 1; // 版本编号
/** =================================================== */
/**
* 网络请求
*/
/** =================================================== */
// const URL_Service = "http://192.168.3.111:5050"; // 路径
const URL_Service = "http://192.168.3.187:8080"; // 路径
const URL_Login = "/member/oauth"; // 登陆
const URL_Register = "/member/reg"; // 注册
const URL_SendSMS = "/member/SMS"; // 发送短信验证码
const URL_Query_User = "/member/bind"; // 查询用户
const URL_Binding = "/member/bind"; // 绑定用户
const URL_Coupon_Customer = "/coupon/info"; // 用户优惠券
const URL_Coupon_Recive = "/coupon/info"; // 领取用户券
const URL_Coupon_List = "/couponType/info"; // 优惠券列表
const URL_Deposit_Get = "/deposit/info"; // 获取寄存商品
/** =================================================== */
/**
* Enum
*/
/** =================================================== */
const Res_Code_Success = 10000; // 成功
const Res_Code_LoginTimeOut = 20001; // 登陆超时
const Res_Code_LoginFailure = 20002; // 账号密码不正确
const Res_Code_UserNotExist = 20003; // 用户不存在
const Res_Code_UnRegister = 20004; // 未注册
const Res_Code_BindFailed = 20005; // 账户绑定失败
const Res_Code_UnBind = 20006; // 用户未绑定
const Res_Code_GetMemberError = 30001; // 获取用户信息失败
const Res_Code_OverridePreNum = 40001; // 券类型超过预发数量
const Res_Code_OverrideGetNumTotal = 40002; // 超过总领取数量
const Res_Code_OverrideGetNumDay = 40003; // 超过每日领取数量限制
const Res_Code_VerifyCodeError = 70001; // 短信验证码错误
const Res_Code_PhoneError = 70002; // 输入手机号错误
const Res_Code_SendMessageFailed = 70003; // 发送短信验证码失败
const Res_Code_SMSEmpty = 70004; // 短信验证码未空
const Res_Code_OverrideEffectiveDate = 80001; // 未在兑换积分商品时间内
const Res_Code_OverrideBeyondCount = 80002; // 积分商品库存数量不足
const Res_Code_OverrideNotEnoughScore = 80003; // 兑换积分不足
const Res_Code_OverrideExceptionState = 80004; // 商品停售
const Res_Code_OverrideBeyondLimiteExchange = 80005; // 超出可兑换数量限制
const Res_Code_OverrideBeyondLimiteExchangeDay = 80006; // 超出单日可兑换数量限制
const Res_Code_Unkown = 90001; // 未知异常
const Res_Code_DataException = 90002; // 数据异常
const QRCode_Type_Coupon = 0; // 二维码类型 优惠券
const Coupon_Type_Unuse = 0; // 优惠券 未使用
const Coupon_Type_Used = 1; // 优惠券 已使用
const Coupon_Type_Expire = 2; // 优惠券 已过期
const Deposit_Type_Current = 0; // 寄存商品 当前寄存
const Deposit_Type_TakeBack = 1; // 寄存商品 已取回
/** =================================================== */
/**
* Key
*/
/** =================================================== */
const Key_UserInfo = "UserInfo"; // 用户信息缓存
const Key_IsLogin = "IsLogin"; // 是否已经登录
/** =================================================== */
/**
* value
*/
/** =================================================== */
/** =================================================== */
/**
* pages
*/
/** =================================================== */
const Page_Home = "/pages/home/index"; // 首页
const Page_Register_Index = "/pages/register/index"; // 注册首页
const Page_Register_BindVip = "/pages/register/bindVip/bindVip"; // 绑定会员卡
const Page_Register_BindSelector = "/pages/register/bindVip/bindSelector"; // 选择要绑定的会员
const Page_Register_RegisterSelector = "/pages/register/register/registerSelector"; // 注册类型选择
const Page_Register_RegisterNew = "/pages/register/register/register"; // 注册新会员
const Page_Personal_Setting = "/pages/personal/setting/index"; // 设置
const Page_Personal_EditPersonal = "/pages/personal/editPersonal/index"; // 编辑个人信息
const Page_Personal_QRCode = "/pages/personal/qrCode/index"; // 二维码
const Page_Coupon_CouponList = "/pages/coupon/couponList/index"; // 优惠券列表
const Page_Coupon_ReceiveCoupon = "/pages/coupon/receiveCoupon/index"; // 领券中心
const Page_Balance_BalanceRecharge = "/pages/balance/balanceRecharge/index"; // 余额充值
const Page_Balance_BalanceDetail = "/pages/balance/balanceDetail/index"; // 余额明细
const Page_Project_ProjectIndex = "/pages/project/index"; // 项目储值首页
const Page_Project_ProjectRecharge = "/pages/project/projectRecharge/index"; // 项目储值充值
const Page_Project_ProjectDetail = "/pages/project/projectDetail/index"; // 项目储值明细
const Page_Project_ProjectOrder = "/pages/project/projectOrder/index"; // 项目预约
const Page_DepositGoods_DepositGoodsDetail = "/pages/depositGoods/depositGoodsDetail/index"; // 寄存商品详情
const Page_Point_PointDetail = "/pages/point/pointDetail/index"; // 积分明细
const Page_Point_PointExchange = "/pages/point/pointExchange/index"; // 积分兑换
const Page_QRCode_Index = '/pages/qrCode/index'; // 二维码
module.exports = {
Service_Phone, // 客服电话
Version_Name, // 版本名称
Version_Code, // 版本编号
URL_Service, // 请求路径
URL_Register, // 注册
URL_SendSMS, // 发送短信验证码
URL_Login, // 登陆
URL_Query_User, // 查询用户
URL_Binding, // 绑定用户
URL_Coupon_Customer, // 用户优惠券
URL_Coupon_Recive, // 领取用户券
URL_Coupon_List, // 优惠券列表
URL_Deposit_Get, // 获取寄存商品
Res_Code_Success, // 成功
Res_Code_LoginTimeOut, // 登陆超时
Res_Code_LoginFailure, // 账号密码不正确
Res_Code_UserNotExist, // 用户不存在
Res_Code_UnRegister, // 未注册
Res_Code_BindFailed, // 账户绑定失败
Res_Code_UnBind, // 用户未绑定
Res_Code_GetMemberError, // 获取用户信息失败
Res_Code_OverridePreNum, // 券类型超过预发数量
Res_Code_OverrideGetNumTotal, // 超过总领取数量
Res_Code_OverrideGetNumDay, // 超过每日领取数量限制
Res_Code_VerifyCodeError, // 短信验证码错误
Res_Code_PhoneError, // 输入手机号错误
Res_Code_SendMessageFailed, // 发送短信验证码失败
Res_Code_SMSEmpty, // 短信验证码未空
Res_Code_OverrideEffectiveDate, // 未在兑换积分商品时间内
Res_Code_OverrideBeyondCount, // 积分商品库存数量不足
Res_Code_OverrideNotEnoughScore, // 兑换积分不足
Res_Code_OverrideExceptionState, // 商品停售
Res_Code_OverrideBeyondLimiteExchange, // 超出可兑换数量限制
Res_Code_OverrideBeyondLimiteExchangeDay, // 超出单日可兑换数量限制
Res_Code_Unkown, // 未知异常
Res_Code_DataException, // 数据异常
QRCode_Type_Coupon, // 二维码类型 优惠券
Coupon_Type_Unuse, // 优惠券 未使用
Coupon_Type_Used, // 优惠券 已使用
Coupon_Type_Expire, // 优惠券 已过期
Deposit_Type_Current, // 寄存商品 当前寄存
Deposit_Type_TakeBack, // 寄存商品 已取回
Key_UserInfo, // 用户信息缓存
Key_IsLogin, // 是否已经登录
Page_Home, // 首页
Page_Register_Index, // 注册首页
Page_Register_BindVip, // 绑定会员卡
Page_Register_BindSelector, // 选择绑定账号
Page_Register_RegisterSelector, // 注册类型选择
Page_Register_RegisterNew, // 注册新会员
Page_Personal_Setting, // 设置
Page_Personal_EditPersonal, // 编辑个人信息
Page_Personal_QRCode, // 二维码
Page_Coupon_CouponList, // 优惠券列表
Page_Coupon_ReceiveCoupon, // 领券中心
Page_Balance_BalanceRecharge, // 余额充值
Page_Balance_BalanceDetail, // 余额明细
Page_Project_ProjectIndex, // 项目储值首页
Page_Project_ProjectRecharge, // 项目储值充值
Page_Project_ProjectDetail, // 项目储值明细
Page_Project_ProjectOrder, // 项目预约
Page_DepositGoods_DepositGoodsDetail, // 寄存商品详情
Page_Point_PointDetail, // 积分明细
Page_Point_PointExchange, // 积分兑换
Page_QRCode_Index, // 二维码
}
|
import AbstractComponent from "./abstract-component";
export default class BoardFilter extends AbstractComponent {
getTemplate() {
return `<div class="board__filter-list"></div>`;
}
}
|
/**
* Created by lusiwei on 16/9/5.
*/
'use strict';
import { createStore, applyMiddleware } from 'redux'
import thunkMiddleware from 'redux-thunk'
import rootReducer from '../reducers/index'
let createStoreWithMiddleware = applyMiddleware(thunkMiddleware)(createStore);
export const store = createStoreWithMiddleware(rootReducer);
|
import React,{Component} from 'react'
import {
StyleSheet,
ToastAndroid,
} from 'react-native'
import SimpleTabNavigator from './SimpleTabNavigator';
export default class Footer extends Component{
constructor(props) {
super(props);
}
componentWillMount() {
// if (Platform.OS === 'android') {
// BackAndroid.addEventListener('hardwareBackPress', this.onBackAndroid);
//
// // BackAndroid.addEventListener('hardwareBackPress', this.onBackAndroid);
// }
}
componentWillUnmount() {
// if (Platform.OS === 'android') {
// BackAndroid.addEventListener('hardwareBackPress', function() {
// this.onBackAndroid;
// return true;
// });
// }
}
onBackAndroid = () => {
ToastAndroid.show('This is a toast with short duration', ToastAndroid.SHORT);
this.webView.goBack();
true;
};
render() {
return (
<SimpleTabNavigator
style={styles.container}
>
</SimpleTabNavigator>
);
}
}
const styles = StyleSheet.create({
center:{
flex:1
},
});
|
import React from 'react';
import {View} from 'react-native';
import { QRCode } from 'react-native-custom-qr-codes';
import {connect} from 'react-redux';
import { sha256 } from 'react-native-sha256';
const UserQRCode= ({navigation,qrValue}) => {
const [value, HashVaule] = React.useState(null)
React.useEffect(() => {
sha256(qrValue).then(async hash => { HashVaule(hash)})
}
)
return (
<View style={{flex:1, paddingTop:80, alignItems:'center', backgroundColor:'white'}}>
<QRCode
value={value}
/>
</View>
);
};
const mapStateToProps = (state, props) => ({
qrValue: state.auth.userToken.id_licence,
navigation: props.navigation
})
export default connect(mapStateToProps)(UserQRCode) |
var searchData=
[
['readinput',['readInput',['../class_abstract_menu.html#abac536874705a679492b0a6d5d91ab6d',1,'AbstractMenu::readInput()'],['../class_load_game_menu.html#a45dc14cac9b117c6f564d621ca9ec10c',1,'LoadGameMenu::readInput()'],['../class_local_player.html#a4ed9641e781fa37d8690ce2bce120fcd',1,'LocalPlayer::readInput()']]]
];
|
import React from 'react'
import { shallow } from 'enzyme'
import { Contact } from '../../contact'
describe('<Contact />', () => {
let contact
beforeEach(() => {
contact = shallow(<Contact />)
})
it('should render correctly', () => {
expect(contact).toBeDefined()
expect(contact.exists()).toBeTruthy()
expect(contact.is('.contact')).toBeTruthy()
})
}) |
import React, {Component} from 'react'
import DataSource from './DateSource'
import HigherOrderComponent from './Hoc'
class BlogList extends Component {
render(){
return(
<div>
<ul>
{ this.props.info.map((item)=> <li key = {item.id}>{item.title}</li> )}
</ul>
</div>
)
}
}
export default HigherOrderComponent(BlogList,DataSource.getBlogs.bind(DataSource)) |
$(document).ready(function() {
addFilters($('#filter'));
$('.modal').modal();
// Se filtra por tipo de comida y se crea un container que tiene las imagenes correspondiente de cada restaurante
$('#filter').change(function() {
$('#restaurants-container').children().remove();
var selection = $('select').val();
for (var i = 0; i < restaurants.length; i++) {
for (var cantidad = 0; cantidad < restaurants[i].filters.length; cantidad++) {
if (restaurants[i].filters[cantidad] === selection) {
var image = restaurants[i].photo;
$('#restaurants-container').append('<div class=\'col s12 l6 xl6\'><div class=\'container-img-p\'><p class=\'overlay-text\'>' + restaurants[i].name + '</p>' + image + '</div></div>');
}
}
};
// mouseover
$('.container-img-p').mouseover(function() {
$(':nth-child(1)', this).css({'opacity': '1'});
});
// La informacion que ira en el modal
$('.container-img-p').click(function() {
var place = $(this).children('img').attr('alt');
for (var i = 0; i < restaurants.length; i++) {
if (place === restaurants[i].name) {
$('#title-modal').empty();
$('#modal-data').empty();
$('#title-modal').html(restaurants[i].name);
$('#modal-map').empty();
var newName = restaurants[i].name.replace(/ /g, '+');
for (var cantidad = 0; cantidad < restaurants[i].address.length; cantidad++) {
var newAddress = restaurants[i].address[cantidad].replace(/ /g, '+');
var addressGoogle = newAddress.replace(/,/g, '');
$('#modal-data').append('<p>' + restaurants[i].address[cantidad] + '</p>');
}
$('#modal-data').append('<p><a href=\'' + restaurants[i].website + '\'>' + restaurants[i].website + '</a></p>');
}
}
// Para que aparezca el modal
$('#modal').modal('open');
});
});
});
// Recorre el array creado (data.js), y se filtra por tipo de comida
var addFilters = (function(element) {
var filtersArr = [];
for (var i = 0; i < restaurants.length; i++) {
for (var cantidad = 0; cantidad < restaurants[i].filters.length; cantidad++) {
filtersArr.push(restaurants[i].filters[cantidad]);
}
}
var uniqueFilters = [...new Set(filtersArr)];
var filtersFinal = uniqueFilters.sort();
for (var cantidadDos = 0; cantidadDos < filtersFinal.length; cantidadDos++) {
element.append('<option value=\'' + filtersFinal[cantidadDos] + '\'>' + filtersFinal[cantidadDos] + '');
};
return filtersFinal;
});
|
/* @flow weak */
import React from "react";
import { View } from "react-native";
import { Text } from "native-base";
import styled from "styled-components/native";
import { formattedTime } from "../utils/time";
const Info = ({ song: { name }, position, duration }) => (
<Container>
<Text
style={{ textAlign: "center", paddingHorizontal: 10 }}
ellipsizeMode={"tail"}
numberOfLines={1}
>
{name}
</Text>
<Text note>
{formattedTime(position)}
{" "}
/
{" "}
{formattedTime(duration)}
</Text>
</Container>
);
const Container = styled.View`
align-items: center;
justify-content: center;
padding-bottom: 2;
`;
export default Info;
|
//= require ./internal_links/grid_page_type
//= require ./internal_links/list_page_type |
$(document).ready(function (){
CKEDITOR.replace("noiDung");
$("#selectImg").click(function () {
var finder = new CKFinder();
finder.selectActionFunction = function (fileUrl) {
$("#txtImage").val(fileUrl);
};
finder.popup();
});
}); |
var searchData=
[
['memmap',['memMap',['../struct_engine___desc.html#ae7e1fe76e49e00c3a8a7b1b97c87c07a',1,'Engine_Desc']]],
['memtype',['memType',['../struct_engine___alg_desc.html#a09d66c692b6c4aa9c99ad166c3b9a43f',1,'Engine_AlgDesc']]]
];
|
import { saveAs } from 'file-saver';
import { ACTIONS, STATUS } from '../../common/constants';
import RecordRTC from 'recordrtc';
class BackgroundPage {
constructor() {
chrome.runtime.onMessage.addListener(this.onMessage.bind(this));
this.saveImage = this.saveImage.bind(this);
this.onStartRecord = this.onStartRecord.bind(this);
this.onStopRecord = this.onStopRecord.bind(this);
this.handleStream = this.handleStream.bind(this);
this.recorder = null;
this.stream = null;
this.recording = null;
this.initSettings();
}
initSettings() {
const settings = {
imageFormat: 'png',
videoFormat: 'webm',
gifFormat: 'gif',
};
let settingsToSave = {};
chrome.storage.sync.get(Object.keys(settings), (settingsStored) => {
Object.keys(settings).forEach((s) => {
if (!settingsStored[s]) settingsToSave = Object.assign(settingsToSave, {[s]: settings[s]});
});
if (Object.keys(settingsToSave).length) {
chrome.storage.sync.set(settingsToSave);
}
});
}
// From http://stackoverflow.com/questions/14967647/
fixBinary(bin) {
const length = bin.length;
const buf = new ArrayBuffer(length);
const arr = new Uint8Array(buf);
for (let i = 0; i < length; i++) {
arr[i] = bin.charCodeAt(i);
}
return buf;
}
getFilename(ext) {
return `page2gif-${new Date()}.${ext}`;
}
saveImage(data, ext) {
const binary = this.fixBinary(atob(data.split(',')[1]));
const file = new File(
[binary],
this.getFilename(ext),
{type: `image/${ext}`}
);
saveAs(file);
}
handleStream({stream, type, ext}) {
this.stream = stream;
const mime = type === 'gif' ? 'image' : 'video';
var options = {
type,
frameRate: 200,
quality: 10,
ignoreMutedMedia: false,
mimeType: `${mime}/${ext}`,
showMousePointer: true,
};
this.recorder = new RecordRTC(this.stream, options);
this.recorder.startRecording();
}
onStartRecord(type, ext) {
chrome.storage.sync.set({ page2gifStatus: STATUS.record });
const options = {
audio: false,
video: true,
videoConstraints: {
mandatory: {
chromeMediaSource: 'tab'
}
}
};
chrome.tabCapture.capture(options, (stream) => this.handleStream({stream, type, ext}));
}
onStopRecord(ext) {
chrome.storage.sync.set({ page2gifStatus: STATUS.default });
this.stream && this.stream.stop();
this.stream && this.stream.getTracks().forEach(s => s.stop());
if (!this.recorder) {
return;
}
const fileName = this.getFilename(ext);
this.recorder.stopRecording(() => this.recorder.save(fileName));
}
onMessage({ action, type }) {
const typeFormat = `${type}Format`;
chrome.storage.sync.get(typeFormat, (opt) => {
const ext = opt[typeFormat];
switch (action) {
case ACTIONS.takePicture:
chrome.tabs.captureVisibleTab(null, {format: ext}, (data) => this.saveImage(data, ext));
break;
case ACTIONS.start:
this.onStartRecord(type, ext);
this.recording = {ext, type};
break;
case ACTIONS.stop:
this.recording && this.onStopRecord(this.recording.ext);
this.recording = null;
break;
}
});
}
}
new BackgroundPage();
|
//返回顶部
window.onload = imgFade;
window.onscroll = imgFade;
$(".return-top").click(function () {
$("html,body").animate({ scrollTop: 0 }, 500);
})
function imgFade() {
var eleTop = $('.concert-show').offset().top;
var isFirst = true;
// window.onscroll = function(){
if ($(document.documentElement).scrollTop() > 2150) {
$(".return-top").show();
} else {
$(".return-top").hide();
}
var cliHeight = $(window).height();
var scroll = $(document.documentElement).scrollTop() + cliHeight;
if (scroll > eleTop && isFirst == true) {
for(var i=0;i<$('.concert-show ul li').length;i++){
if(i%2==0){
$('.concert-show ul li').eq(i).addClass('fadeLeft')
}else {
$('.concert-show ul li').eq(i).addClass('fadeRight')
}
}
isFirst = false;
}
}
|
/*
Al presionar el botón pedir números
hasta que el usuario quiera, mostrar:
1-Suma de los negativos.
2-Suma de los positivos.
3-Cantidad de positivos.
4-Cantidad de negativos.
5-Cantidad de ceros.
6-Cantidad de números pares.
7-Promedio de positivos.
8-Promedios de negativos.
9-Diferencia entre positivos y negativos, (positvos-negativos). */
function mostrar() {
var sumaDePositivos=0;
var sumaNegativos=0;
var respuesta;
var numeroIngresado;
var contadorPositivos=0;
var contadorNegativos=0;
var cantidad0=0;
var contadorpares=0;
var promediopositivo;
var promedionegativo;
var difAmbos;
respuesta =true;
while (respuesta){
numeroIngresado = prompt ("ingrese un numero");
numeroIngresado = parseInt(numeroIngresado);
while (isNaN(numeroIngresado)) {
numeroIngresado = prompt ("ingrese unicamente numero");
numeroIngresado = parseInt(numeroIngresado);
}
if(numeroIngresado > 0){
sumaDePositivos = sumaDePositivos + numeroIngresado;
//sumaDePositivos = parseInt(sumaDePositivos); no hace falta
contadorPositivos++;
}else {
if (numeroIngresado < 0){
sumaNegativos = sumaNegativos + numeroIngresado;
//sumaNegativos =parseInt(sumaNegativos); no hace falta
contadorNegativos++
}else {
cantidad0++;
}
}
if (numeroIngresado % 2 == 0) {
contadorpares++;
}
respuesta = confirm ("Desea continuar?");
}
if (contadorPositivos > 0){
promediopositivo = sumaDePositivos / contadorPositivos;}
if(contadorPositivos > 0){
promedionegativo = sumaNegativos / contadorNegativos;}
difAmbos = sumaDePositivos - sumaNegativos;
document.write("suma de positivos es = " + sumaDePositivos + "<br>");
document.write("suma de negativos es = " + sumaNegativos + "<br>");
document.write("la cantidad de positivos = "+contadorPositivos + "<br>");
document.write("la cantidad de negativos = "+contadorNegativos + "<br>");
document.write("La cantidad de ceros es de = "+cantidad0 + "<br>");
document.write("La cantida de pares es de = "+contadorpares + "<br>");
document.write("El promedio de numeros positivos es = "+promediopositivo + "<br>");
document.write("el promedio de numero negativos es = "+promedionegativo + "<br>");
document.write("La diferencia entre porsit y negat es = "+difAmbos + "<br>");
} |
// Calcola la somma e la media dei numeri da 1 a 10.
// calcolo la somma dei numeri da 1 a 10
var somma = 0;
// scorro tutti i numeri da 1 a 10 compreso
for (var i = 1; i <= 10; i++) {
// accumulo la somma dei numeri visti finora
somma += i; // equivalente a: somma = somma + i;
}
// alla fine del ciclo ho la somma di tutti i numeri da 1 a 10
console.log('somma = ' + somma);
// calcolo la media dei numeri da 1 a 10
var media = somma / 10;
console.log('media = ' + media);
|
import connectDb from "../../../../utils/connectDb";
import Post from "../../../../models/Post";
import User from "../../../../models/User";
import authenticate from "../../../../middleware/auth";
connectDb();
const handler = async (req, res) => {
switch (req.method) {
case "PATCH":
await handlePatchRequest(req, res);
break;
default:
res.status(405).send(`Method ${req.method} not allowed`);
break;
}
};
// @route PATCH api/posts/hidepost/[id]
// @desc toggle hide / show post
// @res
// @access Protected
async function handlePatchRequest(req, res) {
const {
query: { id },
} = req;
try {
//get post
let postData = await Post.findById(id);
if (!post) res.status(404).send("Post Not Found");
//compare post author id to user id
if (postData.user.toString() === req.user.id.toString()) {
//toggle post.isVisible
postData.isVisible = !postData.isVisible;
await postData.save();
res.status(200).send(postData);
} else {
res.status(403).send("Invalid permissions");
}
} catch (err) {
res.status(500).send("Server Error");
}
}
export default authenticate(handler);
|
/** ********************** Require node modules ************************ */
const bcrypt = require('bcrypt-nodejs');
/** @function encryptPassword
* @desc This function is used to encrypt password of a user
* @param {String} password consist of user input password
* @return {String} hash of the password
*/
function encryptPassword(password) {
return bcrypt.hashSync(password, null);
}
/** @function comparePassword
* @desc This function is used to compare password of a user
* @param {String} password consist of user input password
* @param {JSON object} user includes user's password
* @return {Boolean} true if password is matched
*/
function comparePassword(password, user) {
return bcrypt.compareSync(password, user.password);
}
module.exports = {
encryptPassword,
comparePassword,
};
|
import React from "react";
export default function Filter(props) {
const dataList = props.infoOption;
const elementList = dataList.map((data, index) => (
<option key={index} value={data.value}>
{data.text}
</option>
));
return (
<div key={props.id}>
<select
className="filter-select"
onChange={props.change}
value={props.value}
>
{elementList}
</select>
</div>
);
}
|
var mongo = require( "mongodb" )
var mongoClient = mongo.MongoClient
var dbLocation = "mongodb://localhost/egDB"
var dbColl = "egColl"
var validate = require( './Validation.js' )
var ut = require( './UtilityFunctions.js')
var HTTP = ut.http_codes()
var db = require( './DatabaseActions.js' )
module.exports = {
/**
* Change the default Database Functions to another file implementing the same functions.
* @param { STRING } db_connetion - Functions file address.
*/
toggleDBActions: function ( db_connetion ) {
db = require( db_connetion )
},
/**
* Stepping stone function designed to make use of these functions easier to understand.
* @param { STRING } key - The Key value of an existing formula entry.
* @param { FUNCTION ( http_code, output ) } callback - A call back function to be executed when
* computation finishes, takes a status code and the evaluated value as its arguments.
*/
evaluateExpression: function ( key, callback ){
module.exports.resolveExpression( '', key, [], [], callback )
},
/**
* Recursive resolve function that builds a final expression as it progresses through the initial expression replacing
* keys with their expressions or values. Computation stops when there are no more keys to be replaces and the expressions
* is mathematically correct.
* @param { STRING } completed - Parts of the expression that contain no keys, left hand side of any key values or
* unproccessed sections.
* @param { STRING } expressionKey - The Key value of an existing formula entry.
* @param { STRING ARRAY } unproccessed - Array of unprocessed snippets of the expression, acting like a stack.
* @param { STRING ARRAY } callstack - Array of expression keys keeping track of previously visited keys that have yet to
* have a set value. Used to detect circular difinitions.
* @param { FUNCTION ( http_code, output ) } callback - A call back function to be executed when
* computation finishes, takes a status code and the evaluated value as its arguments.
*/
resolveExpression: function ( completed , expressionKey, unprocessed, callstack, callback ){
// Check to see if expression key is valid
if( expressionKey != null ){
// Check to see that there isn't a circular expression by checking callstack/
if ( callstack.indexOf( expressionKey ) != -1 ){
callback( HTTP.BAD_REQUEST, "ERROR: Circular definition found, unable to evaluate.")
} else {
// Record key in call stack and then read in value from database.
callstack.push( expressionKey )
db.read( expressionKey, function ( expStatus, row ){
if( expStatus == HTTP.OK) {
// Expression was found, continue to refactor taking all info along.
module.exports.refactor( completed, row.value.substring(1), unprocessed, callstack, callback)
} else {
// Expressions not found therefore no circular reasoning for this key, remove it from callstack
callstack.pop()
// Create alternate key to look for value entry
alternateKey = expressionKey.substring( 0, expressionKey.length - 8 ) + '_value'
db.read( alternateKey, function ( valStatus, row ) {
if( valStatus == HTTP.OK ){
// raw value can be appended to completed
var lhs = completed + row.value
if( unprocessed.length != 0 ){
// Things still left to check, extract from unprcessed and continue to refactor.
var current = unprocessed.pop()
module.exports.refactor( lhs, current , unprocessed, callstack, callback )
} else {
// Nothing left to process, evaluate the completed string and return its value.
try{
callback( HTTP.OK, eval( lhs ))
} catch (e) {
// Condition should never be meet, fires when completed string is malformed.
// All expressions are validated when created or updated.
callback( HTTP.BAD_REQUEST, 'ERROR: Expression is invalid.')
}
}
} else {
// No value found, therefore expressions points to cells that do not exist
// Return undefined and stop computation.
callback( HTTP.BAD_REQUEST, 'ERROR: Cell has undefined properties.')
}
})
}
})
}
} else {
// No key given
if( unprocessed.length != 0) {
// Still things to evaluate, pop and continue to refactor
var current = unprocessed.pop()
module.exports.refactor( completed, current, unprocessed, callstack, callback )
} else {
// Everything has been processed.
try{
callback( HTTP.OK, eval( completed ))
} catch (e) {
// Condition should never be meet, fires when completed string is malformed.
// All expressions are validated when created or updated.
callback( HTTP.BAD_REQUEST, 'ERROR: Expression is invalid.')
}
}
}
},
/**
* Examines a raw expression and seperates it into three parts: Left hand side of the first key found that does not need to
* be evaluated, Key reference that needs to be evaluated, and the unprocessed right hand side of the expression key.
* @param { STRING } lhs - Parts of the expression that contain no keys, left hand side of any key values or
* unproccessed sections.
* @param { STRING } raw_expression - Mathematical statement potentially containing expression keys.
* @param { STRING ARRAY } unproccessed - Array of unprocessed snippets of the expression/previous expressions, acting like a stack.
* @param { STRING ARRAY } callstack - Array of expression keys keeping track of previously visited keys that have yet to
* have a set value. Used to detect circular difinitions.
* @param { FUNCTION ( http_code, output ) } callback - A call back function to be executed when
* computation finishes, takes a status code and the evaluated value as its arguments.
*/
refactor: function ( lhs, raw_expression, unprocessed, callstack, callback ) {
// Remove any redundant blank space from the expression
var expression = raw_expression.replace( " ", "")
if ( expression.search( /[A-Z]/ ) != -1 ){
// A key value exists within the expression, find index of first and last character of key.
var bIndex = expression.search( /[A-Z]/ )
var escapedEnd = expression.substring( bIndex ) + '+'
var eIndex = bIndex + escapedEnd.search( /[-^*()+{}\[\]\/]/ )
// Concatinate everything left of key into the lhs, extract expression key, push into unprocessed right hand side.
lhs = lhs + expression.substring(0, bIndex) + '('
var subExpressionKey = expression.substring( bIndex, eIndex ) + '_formula'
unprocessed.push( ')'+expression.substring(eIndex) )
// return to resolveExpression to replace key with expression or value.
module.exports.resolveExpression( lhs, subExpressionKey, unprocessed, callstack, callback)
} else {
// No key found therefore pop from callstack as previous key evaluates to value.
callstack.pop()
lhs = lhs + expression
// return to resolve expressions to work on unprocessed or to evaluate and return to user.
module.exports.resolveExpression( lhs, null, unprocessed, callstack, callback )
}
}
} |
//Main-content
let headerArea = document.createElement('div');
headerArea.classList.add('Main-content__header');
mainContent.appendChild(headerArea);
let headerAreaBox = document.createElement('div');
headerArea.appendChild(headerAreaBox);
let headerCover = document.createElement('div');
headerCover.classList.add('Main-content__header__cover');
headerAreaBox.appendChild(headerCover);
let headerImg = document.createElement('img');
headerImg.setAttribute('src', 'assets/pics/nature_cover.jpg')
headerImg.classList.add('Main-content__header__cover__img');
headerCover.appendChild(headerImg);
let headerAreaButtons = document.createElement('div');
headerArea.appendChild(headerAreaButtons);
let headerButtonsBox = document.createElement('div');
headerButtonsBox.classList.add('Main-content__header__buttonBox');
headerAreaBox.appendChild(headerButtonsBox);
let headerbtns = document.createElement('div');
headerbtns.classList.add('Main-content__header__buttonBox__btns');
headerButtonsBox.appendChild(headerbtns);
let leftBtns = document.createElement('div');
leftBtns.classList.add('Main-content__header__buttonBox__btns__left');
headerbtns.appendChild(leftBtns);
let leftBtnsItems = document.createElement('div');
leftBtns.appendChild(leftBtnsItems);
let leftBtnsBox = document.createElement('div');
leftBtnsBox.classList.add('Main-content__header__buttonBox__btns__left__items');
leftBtnsItems.appendChild(leftBtnsBox);
let leftBtnItemsLike = document.createElement('div');
leftBtnsBox.appendChild(leftBtnItemsLike);
let leftBtnLike = document.createElement('button');
leftBtnLike.classList.add('Main-content__header__buttonBox__btns__left__items__like');
leftBtnItemsLike.appendChild(leftBtnLike);
let likeIcon = document.createElement('i');
likeIcon.setAttribute('class', 'fas fa-thumbs-up');
likeIcon.setAttribute('style', 'color: gray')
leftBtnLike.appendChild(likeIcon);
let likeText = document.createTextNode(' Like');
leftBtnLike.appendChild(likeText);
let leftBtnItemsFlw = document.createElement('div');
leftBtnsBox.appendChild(leftBtnItemsFlw);
let leftBtnFollow = document.createElement('button');
leftBtnFollow.classList.add('Main-content__header__buttonBox__btns__left__items__follow');
leftBtnItemsFlw.appendChild(leftBtnFollow);
let followIcon = document.createElement('i');
followIcon.setAttribute('class', 'fas fa-wifi');
followIcon.setAttribute('style', 'color: gray')
leftBtnFollow.appendChild(followIcon);
let followText = document.createTextNode(' Follow');
leftBtnFollow.appendChild(followText);
let leftBtnItemsShare = document.createElement('div');
leftBtnsBox.appendChild(leftBtnItemsShare);
let leftBtnShare = document.createElement('button');
leftBtnShare.classList.add('Main-content__header__buttonBox__btns__left__items__share');
leftBtnItemsShare.appendChild(leftBtnShare);
let shareIcon = document.createElement('i');
shareIcon.setAttribute('class', 'fas fa-share');
shareIcon.setAttribute('style', 'color: gray')
leftBtnShare.appendChild(shareIcon);
let shareText = document.createTextNode(' Share');
leftBtnShare.appendChild(shareText);
let leftBtnItemsMore = document.createElement('div');
leftBtnsBox.appendChild(leftBtnItemsMore);
let leftBtnMore = document.createElement('button');
leftBtnMore.classList.add('Main-content__header__buttonBox__btns__left__items__more');
leftBtnItemsMore.appendChild(leftBtnMore);
let moreText = document.createTextNode('...');
leftBtnMore.appendChild(moreText);
let rightBtn = document.createElement('div');
rightBtn.classList.add('Main-content__header__buttonBox__btns__right');
headerbtns.appendChild(rightBtn);
let rightBtnsItems = document.createElement('div');
rightBtn.appendChild(rightBtnsItems);
let rightBtnBox = document.createElement('div');
rightBtnBox.classList.add('Main-content__header__buttonBox__btns__right__items');
rightBtn.appendChild(rightBtnBox);
let rightBtnItem = document.createElement('div');
rightBtnBox.appendChild(rightBtnItem);
let rightBtnMore = document.createElement('span');
rightBtnMore.classList.add('Main-content__header__buttonBox__btns__right__items__learn-more');
rightBtnItem.appendChild(rightBtnMore);
let buttonMore = document.createElement('button');
buttonMore.classList.add('Main-content__header__buttonBox__btns__right__items__learn-more__button');
rightBtnMore.appendChild(buttonMore);
let lMoretext = document.createTextNode('Learn More ');
buttonMore.appendChild(lMoretext);
let penIcon = document.createElement('i');
penIcon.setAttribute('class', 'fas fa-pencil-alt');
penIcon.setAttribute('style', 'color: white')
buttonMore.appendChild(penIcon);
let contentArea = document.createElement('div');
contentArea.classList.add('Main-content__content-container');
mainContent.appendChild(contentArea);
let contRight = document.createElement('div');
contRight.classList.add('Main-content__content-container__right');
contentArea.appendChild(contRight);
let contRightBox = document.createElement('div');
contRightBox.classList.add('Main-content__content-container__right__box');
contRight.appendChild(contRightBox);
let contRightBoxCol = document.createElement('div');
contRightBoxCol.classList.add('Main-content__content-container__right__box__col');
contRightBox.appendChild(contRightBoxCol);
let rating = document.createElement('div');
rating.classList.add('Main-content__content-container__right__box__col__rating');
contRightBoxCol.appendChild(rating);
let ratingCont = document.createElement('div');
ratingCont.classList.add('Main-content__content-container__right__box__col__rating__cont');
rating.appendChild(ratingCont);
let ratingContIcon = document.createElement('div');
ratingContIcon.classList.add('Main-content__content-container__right__box__col__rating__cont__icon');
rating.appendChild(ratingContIcon);
// let ratingIcon = document.createElement('i');
// ratingIcon.setAttribute('class', 'fas fa-comment-alt');
// ratingContIcon.appendChild(ratingIcon);
let ratingContText = document.createElement('div');
ratingContText.classList.add('Main-content__content-container__right__box__col__rating__cont__text');
rating.appendChild(ratingContText);
let ratingtext = document.createTextNode('No Rating Yet');
ratingContText.appendChild(ratingtext);
let story = document.createElement('div');
story.classList.add('Main-content__content-container__right__box__col__story');
contRightBoxCol.appendChild(story);
let storyBox = document.createElement('div');
storyBox.classList.add('Main-content__content-container__right__box__col__story__box');
story.appendChild(storyBox);
let storyBoxPic = document.createElement('div');
storyBoxPic.classList.add('Main-content__content-container__right__box__col__story__box__pic');
storyBox.appendChild(storyBoxPic);
let storyBoxHead = document.createElement('div');
storyBoxHead.classList.add('Main-content__content-container__right__box__col__story__box__head');
storyBox.appendChild(storyBoxHead);
let storyBoxTitle1 = document.createElement('div');
storyBoxTitle1.classList.add('Main-content__content-container__right__box__col__story__box__head__title');
storyBoxHead.appendChild(storyBoxTitle1);
let storyText1 = document.createTextNode('Our Story');
storyBoxTitle1.appendChild(storyText1);
let storyBoxTitle2 = document.createElement('div');
storyBoxTitle2.classList.add('Main-content__content-container__right__box__col__story__box__head__subtitle');
storyBoxHead.appendChild(storyBoxTitle2);
let storyText2 = document.createTextNode('+Tell people about your business');
storyBoxTitle2.appendChild(storyText2)
let community = document.createElement('div');
community.classList.add('Main-content__content-container__right__box__col__community');
contRightBoxCol.appendChild(community);
let communityHead = document.createElement('div');
communityHead.classList.add('Main-content__content-container__right__box__col__community__header');
community.appendChild(communityHead);
let communityHeadBold = document.createElement('span');
communityHeadBold.classList.add('Main-content__content-container__right__box__col__community__header__titleBold');
communityHead.appendChild(communityHeadBold);
let comBoldText = document.createTextNode('Community');
communityHeadBold.appendChild(comBoldText);
let communityHeadReg = document.createElement('span');
communityHeadReg.classList.add('Main-content__content-container__right__box__col__community__header__tilteReg');
communityHead.appendChild(communityHeadReg);
let comRegText = document.createTextNode('See All');
communityHeadReg.appendChild(comRegText);
let communityLike = document.createElement('div');
communityLike.classList.add('Main-content__content-container__right__box__col__community__likes');
community.appendChild(communityLike);
let communityLikeBox = document.createElement('div');
communityLikeBox.classList.add('Main-content__content-container__right__box__col__community__likes__box');
communityLike.appendChild(communityLikeBox);
let likeBoxIcon = document.createElement('div');
likeBoxIcon.classList.add('Main-content__content-container__right__box__col__community__likes__box__icon');
communityLike.appendChild(likeBoxIcon);
let comLikeIcon = document.createElement('i');
comLikeIcon.setAttribute('class', 'fas fa-thumbs-up');
comLikeIcon.setAttribute('style', 'color: gray')
likeBoxIcon.appendChild(comLikeIcon);
let likeBoxText = document.createElement('div');
likeBoxText.classList.add('Main-content__content-container__right__box__col__community__likes__box__text');
communityLike.appendChild(likeBoxText);
let comLikeText = document.createElement('span');
comLikeText.classList.add('Main-content__content-container__right__box__col__community__likes__box__text__cont');
likeBoxText.appendChild(comLikeText);
let comLikeTextCont = document.createTextNode('150 people like this');
comLikeText.appendChild(comLikeTextCont);
let communityFollow = document.createElement('div');
communityFollow.classList.add('Main-content__content-container__right__box__col__community__follows');
community.appendChild(communityFollow);
let communityFollowBox = document.createElement('div');
communityFollowBox.classList.add('Main-content__content-container__right__box__col__community__follows__box');
communityFollow.appendChild(communityFollowBox);
let followBoxIcon = document.createElement('div');
followBoxIcon.classList.add('Main-content__content-container__right__box__col__community__follows__box__icon');
communityFollow.appendChild(followBoxIcon);
let comFollowIcon = document.createElement('i');
comFollowIcon.setAttribute('class', 'fas fa-wifi');
comFollowIcon.setAttribute('style', 'color: gray')
followBoxIcon.appendChild(comFollowIcon);
let followBoxText = document.createElement('div');
followBoxText.classList.add('Main-content__content-container__right__box__col__community__follows__box__text');
communityFollow.appendChild(followBoxText);
let comFollowtext = document.createElement('span');
comFollowtext.classList.add('Main-content__content-container__right__box__col__community__follows__box__text__cont');
followBoxText.appendChild(comFollowtext);
let comFollowTextCont = document.createTextNode('150 people follow this');
comFollowtext.appendChild(comFollowTextCont);
let contLeft = document.createElement('div');
contLeft.setAttribute('id', 'allPosts')
contLeft.classList.add('Main-content__content-container__left');
contentArea.appendChild(contLeft);
let contLeftFeed = document.createElement('div');
contLeftFeed.classList.add('Main-content__content-container__left__feed');
contLeft.appendChild(contLeftFeed);
let feedPostin = document.createElement('div');
feedPostin.classList.add('Main-content__content-container__left__feed__postin');
contLeftFeed.appendChild(feedPostin);
let postinSec = document.createElement('section');
postinSec.classList.add('Main-content__content-container__left__feed__postin__sect');
feedPostin.appendChild(postinSec);
let postinHead = document.createElement('ul');
postinHead.classList.add('Main-content__content-container__left__feed__postin__sect__list');
postinSec.appendChild(postinHead);
let postinLi1 = document.createElement('li');
postinLi1.classList.add('Main-content__content-container__left__feed__postin__sect__list__item');
postinHead.appendChild(postinLi1);
let li1Icon = document.createElement('i');
li1Icon.setAttribute('class', 'fas fa-pen');
postinLi1.appendChild(li1Icon);
let li1Text = document.createElement('a');
li1Text.setAttribute('href', '#')
li1Text.setAttribute('class', 'Main-content__content-container__left__feed__postin__sect__list__item__text');
postinLi1.appendChild(li1Text);
let li1TextItem = document.createTextNode('Create Post');
li1Text.appendChild(li1TextItem);
// let li2Icon = document.createElement('i');
// li2Icon.setAttribute('style', 'float: right');
// li2Icon.setAttribute('class', 'fas fa-user-circle');
// postinLi1.appendChild(li2Icon);
let postinInp = document.createElement('div');
postinInp.classList.add('Main-content__content-container__left__feed__postin__sect__inpSec');
postinSec.appendChild(postinInp);
let postinInpPic = document.createElement('div');
postinInpPic.classList.add('Main-content__content-container__left__feed__postin__sect__inpSec__pic');
postinInp.appendChild(postinInpPic);
let inpTextField = document.createElement('div');
inpTextField.classList.add('Main-content__content-container__left__feed__postin__sect__inpSec__textArea');
postinInp.appendChild(inpTextField);
let textFieldInput = document.createElement('input');
textFieldInput.setAttribute('id', 'postInput');
textFieldInput.setAttribute('type', 'text');
textFieldInput.setAttribute('placeholder', 'Write a post...');
textFieldInput.classList.add('Main-content__content-container__left__feed__postin__sect__inpSec__textArea__input');
inpTextField.appendChild(textFieldInput);
let postinBtns = document.createElement('div');
postinBtns.classList.add('Main-content__content-container__left__feed__postin__sect__btnSec');
postinSec.appendChild(postinBtns);
let postinBtnsBox = document.createElement('div');
postinBtnsBox.classList.add('Main-content__content-container__left__feed__postin__sect__btnSec__listBox');
postinBtns.appendChild(postinBtnsBox);
let btnsBoxItem1 = document.createElement('div');
btnsBoxItem1.classList.add('Main-content__content-container__left__feed__postin__sect__btnSec__listBox__Btn');
postinBtnsBox.appendChild(btnsBoxItem1);
let btnsBoxItemIcon1 = document.createElement('div');
btnsBoxItemIcon1.classList.add('Main-content__content-container__left__feed__postin__sect__btnSec__listBox__Btn__icon');
btnsBoxItem1.appendChild(btnsBoxItemIcon1);
let btnsBoxItemText1 = document.createElement('span');
btnsBoxItemText1.classList.add('Main-content__content-container__left__feed__postin__sect__btnSec__listBox__Btn__text');
btnsBoxItem1.appendChild(btnsBoxItemText1);
let btnsBoxItemTextCont1 = document.createTextNode('Photo/Video');
btnsBoxItemText1.appendChild(btnsBoxItemTextCont1);
let btnsBoxItem2 = document.createElement('div');
btnsBoxItem2.classList.add('Main-content__content-container__left__feed__postin__sect__btnSec__listBox__Btn');
postinBtnsBox.appendChild(btnsBoxItem2);
let btnsBoxItemIcon2 = document.createElement('div');
btnsBoxItemIcon2.classList.add('Main-content__content-container__left__feed__postin__sect__btnSec__listBox__Btn__icon');
btnsBoxItem2.appendChild(btnsBoxItemIcon2);
let btnsBoxItemText2 = document.createElement('span');
btnsBoxItemText2.classList.add('Main-content__content-container__left__feed__postin__sect__btnSec__listBox__Btn__text');
btnsBoxItem2.appendChild(btnsBoxItemText2);
let btnsBoxItemTextCont2 = document.createTextNode('Tag Friends');
btnsBoxItemText2.appendChild(btnsBoxItemTextCont2);
let btnsBoxItem3 = document.createElement('div');
btnsBoxItem3.classList.add('Main-content__content-container__left__feed__postin__sect__btnSec__listBox__Btn');
postinBtnsBox.appendChild(btnsBoxItem3);
let btnsBoxItemIcon3 = document.createElement('div');
btnsBoxItemIcon3.classList.add('Main-content__content-container__left__feed__postin__sect__btnSec__listBox__Btn__icon');
btnsBoxItem3.appendChild(btnsBoxItemIcon3);
let btnsBoxItemText3 = document.createElement('span');
btnsBoxItemText3.classList.add('Main-content__content-container__left__feed__postin__sect__btnSec__listBox__Btn__text');
btnsBoxItem3.appendChild(btnsBoxItemText3);
let btnsBoxItemTextCont3 = document.createTextNode('Check in');
btnsBoxItemText3.appendChild(btnsBoxItemTextCont3);
let btnsBoxItem4 = document.createElement('button');
btnsBoxItem4.classList.add('Main-content__content-container__left__feed__postin__sect__btnSec__listBox__Btn');
// btnsBoxItem4.addEventListener("click", addPosts());
btnsBoxItem4.setAttribute('id', 'postBtn');
postinBtnsBox.appendChild(btnsBoxItem4);
let btnsBoxItemIcon4 = document.createElement('div');
btnsBoxItemIcon4.classList.add('Main-content__content-container__left__feed__postin__sect__btnSec__listBox__Btn__icon');
btnsBoxItem4.appendChild(btnsBoxItemIcon4);
let btnsBoxItemText4 = document.createElement('span');
btnsBoxItemText4.classList.add('Main-content__content-container__left__feed__postin__sect__btnSec__listBox__Btn__text');
btnsBoxItem4.appendChild(btnsBoxItemText4);
let btnsBoxItemTextCont4 = document.createTextNode('post');
btnsBoxItemText4.appendChild(btnsBoxItemTextCont4);
let feedPosts = document.createElement('div');
feedPosts.classList.add('Main-content__content-container__left__feed__posts');
contLeftFeed.appendChild(feedPosts);
let feedPostsContent = document.createElement('div');
feedPostsContent.classList.add('Main-content__content-container__left__feed__posts__content');
feedPosts.appendChild(feedPostsContent);
let postUser = document.createElement('div');
postUser.classList.add('Main-content__content-container__left__feed__posts__content__user');
feedPostsContent.appendChild(postUser);
let userPicture = document.createElement('div');
userPicture.classList.add('Main-content__content-container__left__feed__posts__content__user__pic');
postUser.appendChild(userPicture);
let userTextInfo = document.createElement('div');
userTextInfo.classList.add('Main-content__content-container__left__feed__posts__content__user__postInfo');
postUser.appendChild(userTextInfo);
let userName = document.createElement('p');
userName.classList.add('Main-content__content-container__left__feed__posts__content__user__postInfo__name');
userTextInfo.appendChild(userName);
let userNametext = document.createTextNode('TecHub');
userName.appendChild(userNametext);
let userDate = document.createElement('span');
userDate.classList.add('Main-content__content-container__left__feed__posts__content__user__postInfo__date');
userTextInfo.appendChild(userDate);
let userDateText = document.createTextNode('January 20 at 08:15 AM .');
userDate.appendChild(userDateText);
let userGlobe = document.createElement('i');
userGlobe.setAttribute('class', 'fas fa-globe-europe');
userDate.appendChild(userGlobe);
let postText = document.createElement('p');
postText.classList.add('Main-content__content-container__left__feed__posts__content__text');
feedPostsContent.appendChild(postText);
let postTextCont = document.createTextNode('Photo description photo description photo description photo description photo description photo description photo description')
postText.appendChild(postTextCont);
let postPhoto = document.createElement('div');
postPhoto.classList.add('Main-content__content-container__left__feed__posts__content__postPhoto');
feedPostsContent.appendChild(postPhoto);
let postReactions = document.createElement('div');
postReactions.classList.add('Main-content__content-container__left__feed__posts__content__postReactions');
feedPostsContent.appendChild(postReactions);
let reactionsList = document.createElement('ul');
reactionsList.classList.add('Main-content__content-container__left__feed__posts__content__postReactions__list');
postReactions.appendChild(reactionsList);
let reactItem1 = document.createElement('li');
reactItem1.classList.add('Main-content__content-container__left__feed__posts__content__postReactions__list__item');
reactionsList.appendChild(reactItem1);
let reactLike1 = document.createElement('i');
reactLike1.setAttribute('class', 'far fa-thumbs-up');
reactItem1.appendChild(reactLike1);
let reactLiketext1 = document.createElement('span');
reactLiketext1.classList.add('Main-content__content-container__left__feed__posts__content__postReactions__list__item__reacttext');
reactItem1.appendChild(reactLiketext1);
let reactLiketextCont1 = document.createTextNode(' Like');
reactLiketext1.appendChild(reactLiketextCont1);
let reactItem2 = document.createElement('li');
reactItem2.classList.add('Main-content__content-container__left__feed__posts__content__postReactions__list__item');
reactionsList.appendChild(reactItem2);
let reactLike2 = document.createElement('i');
reactLike2.setAttribute('class', 'far fa-comment');
reactItem2.appendChild(reactLike2);
let reactLiketext2 = document.createElement('span');
reactLiketext2.classList.add('Main-content__content-container__left__feed__posts__content__postReactions__list__item__reacttext');
reactItem2.appendChild(reactLiketext2);
let reactLiketextCont2 = document.createTextNode(' Comment');
reactLiketext2.appendChild(reactLiketextCont2);
let reactItem3 = document.createElement('li');
reactItem3.classList.add('Main-content__content-container__left__feed__posts__content__postReactions__list__item');
reactionsList.appendChild(reactItem3);
let reactLike3 = document.createElement('i');
reactLike3.setAttribute('class', 'far fa-trash-alt');
reactItem3.appendChild(reactLike3);
let reactLiketext3 = document.createElement('span');
reactLiketext3.classList.add('Main-content__content-container__left__feed__posts__content__postReactions__list__item__reacttext');
reactItem3.appendChild(reactLiketext3);
let reactLiketextCont3 = document.createTextNode(' Delete');
reactLiketext3.appendChild(reactLiketextCont3);
|
import React from 'react';
import '../css/RewardDetails.css';
import { useState } from "react";
const RewardDetails = ({ reward, redeemReward, redeemed }) => {
const [message, setMessage] = useState(null);
function handleSetMessage(message) {
setMessage(message.message);
}
function displayRedeem() {
if (redeemed)
return <div>REDEEMED</div>;
return (
<button onClick={() => redeemReward(reward, handleSetMessage)}>
Redeem This Reward
</button>
);
}
return (
<div className="reward-detail">
<h1>{reward.title}</h1>
<h3>Brand: {reward.company}</h3>
<p>Description: {reward.description}</p>
<p>Points: {reward.points}</p>
<p>Expiry Date: {new Date(reward.expiryDate).toDateString()}</p>
<p>Reward Category: {reward.category}</p>
{displayRedeem()}
{message && <p>{message}</p>}
</div>
);
};
export default RewardDetails;
|
import React from 'react';
import './styleSheets/styling.css';
class App extends React.Component {
constructor(props) {
super(props);
this.state= {
currentTodo: "",
todoItems: []
}
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(field) {
return (e) => {
this.setState({ [field]: e.target.value});
}
}
handleSubmit(e) {
if (e.key === "Enter") {
e.preventDefault();
this.state.todoItems.push(this.state.currentTodo);
this.setState({currentTodo: ""});
}
}
render() {
return (
<div>
<div className="header">Task Lister</div>
<div className="task-add-and-task-ul">
<h2>Add Task:</h2>
<form className="task-input-form">
<input
type="text"
placeholder="whaddya gotta do?"
className="add-task-input"
value={this.state.currentTodo}
onChange={this.handleChange('currentTodo')}
onKeyPress={this.handleSubmit}>
</input>
</form>
<h1>All Tasks:</h1>
<ul>
{this.state.todoItems.map((item, idx) => {
return <li key={idx}>{item}</li>
})}
</ul>
</div>
</div>
);
}
}
export default App; |
module.exports.inMap = {
};
module.exports.outMap = {
"Token": "Token",
"Type": "Type",
"UserId": "UserId",
"createdAt": "createdAt",
"updatedAt": "updatedAt"
};
|
import React from 'react';
import './RankDeath.css'
import numeral from 'numeral';
function RankDeath( {lists} ) {
return (
<div className="rankdeath">
<div className="titleWrap">
<h1>Deaths</h1>
{/* <h2>Top 20</h2> */}
</div>
<div className="scope">
{lists != null ? lists.sort((a,b)=>(a.deaths < b.deaths ? 1 : -1))
.map((item, i)=>(<div key={i} className="deathItem">
<h4>{item.country}</h4>
<h5 className="deathDigit">{numeral(item.deaths).format('0,0')}
<span style={{color: 'gray'}}> deaths</span>
</h5></div>)): <h1>null</h1>}
</div>
</div>
// {lists != null ? lists.sort().map((item)=>(<h4>{item.country}</h4>)): <h1>null</h1>}
)
}
export default RankDeath
|
const log4js = require('log4js');
log4js.configure({
appenders: {
everything: {
type: 'file',
filename: './logs/all-the-logs.log',
maxLogSize: 2048,
backups: 3,
compress: true
},
out: {
type: 'stdout'
}
},
categories: {
default: {
appenders: ['everything', 'out'],
level: 'all'
}
}
});
const log4jser = log4js.getLogger('default');
module.exports = {
log4jser
} |
var mn = mn || {};
mn.services = mn.services || {};
mn.services.MnSession = (function (Rx) {
"use strict";
MnSessionService.annotations = [
new ng.core.Injectable()
];
MnSessionService.parameters = [
ng.common.http.HttpClient,
mn.services.MnAuth,
mn.services.MnAdmin,
ngb.NgbModal
];
MnSessionService.prototype.createTimer = createTimer;
MnSessionService.prototype.activate = activate;
MnSessionService.prototype.getUiSessionTimeout = getUiSessionTimeout;
MnSessionService.prototype.getDialogTimeout = getDialogTimeout;
MnSessionService.prototype.removeDialog = removeDialog;
MnSessionService.prototype.dismissDialog = dismissDialog;
MnSessionService.prototype.isDialogOpened = isDialogOpened;
MnSessionService.prototype.openDialog = openDialog;
MnSessionService.prototype.setTimeout = setTimeout;
MnSessionService.prototype.logout = logout;
MnSessionService.prototype.isUiSessionTimeoutEvent = isUiSessionTimeoutEvent;
MnSessionService.prototype.minToSeconds = minToSeconds;
MnSessionService.prototype.resetAndSyncTimeout = resetAndSyncTimeout;
return MnSessionService;
function MnSessionService(http, mnAuthService, mnAdminService, modalService) {
this.http = http;
this.modalService = modalService;
this.postUILogout = mnAuthService.stream.postUILogout;
this.stream = {};
this.stream.storage = Rx.fromEvent(window, 'storage');
this.stream.mousemove = Rx.fromEvent(window, 'mousemove');
this.stream.keydown = Rx.fromEvent(window, 'keydown');
this.stream.touchstart = Rx.fromEvent(window, 'touchstart');
this.stream.userEvents = Rx.merge(
this.stream.mousemove,
this.stream.keydown,
this.stream.touchstart
).pipe(Rx.operators.throttleTime(300));
this.stream.poolsSessionTimeout =
mnAdminService.stream.uiSessionTimeout;
this.stream.storageResetSessionTimeout =
this.stream.storage
.pipe(Rx.operators.filter(this.isUiSessionTimeoutEvent.bind(this)));
this.stream.resetSessionTimeout =
Rx.merge(
this.stream.storageResetSessionTimeout,
this.stream.poolsSessionTimeout,
this.stream.userEvents)
.pipe(
Rx.operators.map(this.isDialogOpened.bind(this)),
Rx.operators.filter(mn.helper.invert),
Rx.operators.map(this.getUiSessionTimeout.bind(this)),
mn.core.rxOperatorsShareReplay(1)
);
}
function activate(mnOnDestroy) {
this.stream.poolsSessionTimeout
.pipe(Rx.operators.map(this.minToSeconds.bind(this)),
Rx.operators.takeUntil(mnOnDestroy))
.subscribe(this.setTimeout.bind(this));
this.stream.userEvents
.pipe(Rx.operators.map(this.isDialogOpened.bind(this)),
Rx.operators.filter(mn.helper.invert),
Rx.operators.takeUntil(mnOnDestroy))
.subscribe(this.resetAndSyncTimeout.bind(this));
this.stream.storageResetSessionTimeout
.pipe(Rx.operators.filter(this.isDialogOpened.bind(this)),
Rx.operators.takeUntil(mnOnDestroy))
.subscribe(this.dismissDialog.bind(this));
this.stream.resetSessionTimeout
.pipe(Rx.operators.map(this.getDialogTimeout.bind(this)),
Rx.operators.switchMap(this.createTimer.bind(this)),
Rx.operators.takeUntil(mnOnDestroy))
.subscribe(this.openDialog.bind(this));
this.stream.resetSessionTimeout
.pipe(Rx.operators.switchMap(this.createTimer.bind(this)),
Rx.operators.takeUntil(mnOnDestroy))
.subscribe(this.logout.bind(this));
}
function setTimeout(uiSessionTimeout) {
localStorage.setItem("uiSessionTimeout", Number(uiSessionTimeout));
}
function resetAndSyncTimeout() {
//localStorage triggers event "storage" only when storage value has been changed
localStorage.setItem("uiSessionTimeoutReset",
(Number(localStorage.getItem("uiSessionTimeoutReset")) + 1) || 0);
}
function getUiSessionTimeout() {
return Number(localStorage.getItem("uiSessionTimeout")) || 0;
}
function isUiSessionTimeoutEvent(e) {
return e.key === "uiSessionTimeoutReset";
}
function openDialog() {
this.dialogRef = this.modalService.open(mn.components.MnSessionTimeoutDialog);
this.dialogRef.result.then(this.removeDialog.bind(this), this.removeDialog.bind(this));
}
function removeDialog() {
this.dialogRef = null;
}
function dismissDialog() {
this.dialogRef.dismiss();
}
function isDialogOpened() {
return !!this.dialogRef;
}
function getDialogTimeout(t) {
return t - 30000;
}
function minToSeconds(t) {
return t * 1000;
}
function createTimer(t) {
return t && t > 0 ? Rx.timer(t) : Rx.NEVER;
}
function logout() {
this.postUILogout.post();
}
})(window.rxjs);
|
import React from 'react';
import { Text, TouchableOpacity, View, StyleSheet, FlatList } from 'react-native';
import { colors, fonts, globalStyles } from '../styles/gobalStyles'
// accepts a single stat category that contains a name, average and max
function Stat({ category } ) {
return(
<TouchableOpacity style={styles.column}>
<Text style={styles.headerText}>{category.name}</Text>
<Text style={styles.dataText}>{category.average}</Text>
<Text style={styles.text}>avg</Text>
<Text style={styles.dataText}>{category.max}</Text>
<Text style={styles.text}>max</Text>
</TouchableOpacity>
)
}
// accepts an array of stat categories that contain name, average and max
export function StatsWidget( { climber } ) {
const activeClimber = climber;
if(activeClimber){
return (
<View style={globalStyles.widget}>
<Text style={globalStyles.h2}>Stats</Text>
<View style={styles.table}>
{activeClimber.dashStats.map(item => <Stat key={item.key} category={item} />)}
</View>
</View>
);
}else{
return(
<View style={globalStyles.widget}>
<Text style={globalStyles.h2}>No Stats</Text>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
},
headerText:{
color: colors.white,
fontFamily: fonts.bodyFont,
fontWeight: 'bold',
fontSize: 20,
},
dataText:{
color: colors.white,
fontFamily: fonts.bodyFont,
fontSize: 20,
},
text:{
color: colors.muted,
fontFamily: fonts.bodyFont
},
table:{
flexDirection: 'row',
justifyContent: 'space-evenly'
},
column: {
justifyContent: 'space-evenly',
alignItems: 'center',
}
}); |
import React, { Component } from 'react';
import JobList from "./jobListContainer";
import Banner from "../banner";
class SearchList extends Component {
render() {
console.log('this.props.list====>', this.props.list);
return (
<main className="content-area">
<Banner />
<JobList listing={this.props.list} {...this.props} />
</main>
);
}
}
export default SearchList;
|
import { fork, call, take } from 'redux-saga/effects';
export default function takeFirst(pattern, saga, ...args) {
return fork(function*() {
while (true) {
const action = yield take(pattern);
yield call(saga, ...args.concat(action));
}
});
}
|
import {Typography, Grid, TextField } from '@material-ui/core';
const Input = ( name, label, autoFocus, handleChange, type) => {
return (
<Grid item xs={12} sm={12} >
<TextField name={name} label={label} type={type} variant="outlined" fullWidth required onChange={handleChange} autoFocus={autoFocus}/>
</Grid>
)
}
export default Input
|
import { Nav, Navbar } from "react-bootstrap";
import NavbarBlack from "./NavbarBlack";
import NavbarWhite from "./NavbarWhite";
import React, { Component } from "react";
import { Route } from "react-router";
export class Header extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div className="header">
<NavbarBlack
openWebPage={this.props.openMe}
isLoggedIn={this.props.isLoggedIn}
email={this.props.email}
logout={this.props.logout}
showNotifications={this.props.showNotifications}
notifications={this.props.notifications}
></NavbarBlack>
<Route
path=""
render={(props) => (
<NavbarWhite
{...props}
isLoggedIn={this.props.isLoggedIn}
email={this.props.email}
token={this.props.token}
/>
)}
/>
</div>
);
}
}
export default Header;
|
const Users = require('../helpers/dbModel');
const bcrypt = require('bcryptjs');
module.exports = {
validateUser: function (req, res, next) {
if (Object.keys(req.body).length !== 0 && req.body.constructor === Object) {
if (req.body.username && req.body.password) {
next();
} else {
res.status(400).json({ message: 'Nahhhhh! You missed the required username and/or password fields' })
}
} else {
res.status(400).json({ message: 'You must be kidding! Where is the user data?' })
};
},
validateLogin: function (req, res, next) {
let { username, password } = req.body
Users.getBy({ username })
.first()
.then(user => {
if (user && bcrypt.compareSync(password, user.password)) {
req.session.user = user; // sets the session for the user
req.user = user;
next();
} else {
res.status(401).json({ message: 'Oops! Invalid Credentials' });
}
})
.catch(() => {
res.status(401).json({ message: 'Oops! Invalid Credentials' });
});
},
restrict: function (req, res, next) {
if (req.session && req.session.user) {
next();
} else {
res.status(400).json({ message: 'Oops! No Credentials' });
}
}
} |
import EthereumjsWallet from 'ethereumjs-wallet'
import EthereumjsTx from 'ethereumjs-tx'
import { isString, isObject, isUndefined } from 'lodash'
import config from 'Config'
import { stripHexPrefix, parseJson } from 'Utilities/helpers'
import { toChecksumAddress } from 'Utilities/convert'
import EthereumWallet from './EthereumWallet'
export default class EthereumWalletKeystore extends EthereumWallet {
static type = 'EthereumWalletKeystore';
constructor(keystore) {
super()
if (keystore instanceof EthereumjsWallet) {
this._isEncrypted = false
} else {
if (!keystore) {
throw new Error(`Invalid keystore "${keystore}"`)
}
// Convert keystore to lower case to avoid ethereumjs-wallet parsing issues
if (isString(keystore)) {
keystore = parseJson(keystore.toLowerCase())
} else if (isObject(keystore)) {
keystore = Object.entries(keystore).reduce((lowerCased, [key, value]) => ({
...lowerCased,
[key.toLowerCase()]: value
}), {})
} else {
throw new Error(`Keystore has invalid type ${typeof keystore}`)
}
let version = keystore.version
if (typeof version === 'undefined') {
throw new Error('Keystore version information missing')
}
if (version !== 3) {
throw new Error(`Keystore version ${keystore.version} unsupported`)
}
if (!keystore.crypto) {
throw new Error('Keystore crypto information missing')
}
if (!keystore.address) {
throw new Error('Keystore address missing')
}
this._isEncrypted = true
}
this.keystore = keystore
}
static generate() {
return new EthereumWalletKeystore(EthereumjsWallet.generate())
}
static fromPrivateKey(privateKey) {
const pk = Buffer.from(stripHexPrefix(privateKey.trim()), 'hex')
return new EthereumWalletKeystore(EthereumjsWallet.fromPrivateKey(pk))
}
static fromJson(jsonKeystore) {
return new EthereumWalletKeystore(jsonKeystore)
}
getType() { return EthereumWalletKeystore.type }
getTypeLabel() { return 'Keystore file' }
getAddress() { return toChecksumAddress(this.keystore.address || this.keystore.getAddressString()) }
isPersistAllowed() { return this._isEncrypted && this._persistAllowed }
isPasswordProtected() { return this._isEncrypted }
checkPasswordCorrect(password) {
if (!isString(password)) {
return false
}
try {
this.decrypt(password)
return true
} catch(e) {
return false
}
}
encrypt(password = '') {
if (this._isEncrypted) {
return this
}
return new EthereumWalletKeystore(this.keystore.toV3(password, config.encrOpts))
}
decrypt(password) {
if (!this._isEncrypted) {
return this
}
if (isUndefined(password)) {
password = window.prompt(`Enter password for Ethereum account ${this.getId()}`)
}
if (!isString(password)) {
throw new Error(`Invalid password of type ${typeof password}`)
}
return new EthereumWalletKeystore(EthereumjsWallet.fromV3(this.keystore, password, true))
}
_signTx(tx, { password }) {
return Promise.resolve().then(() => {
let keystore = this.keystore
if (this._isEncrypted) {
keystore = this.decrypt(password).keystore
}
const signedTx = new EthereumjsTx({ ...tx.txData, chainId: 1 })
signedTx.sign(keystore.getPrivateKey())
return {
signedTxData: this._signedEthJsTxToObject(signedTx)
}
})
}
getFileName(password) {
return Promise.resolve(this.decrypt(password).keystore.getV3Filename())
}
getPrivateKeyString(password, mock) {
if (mock) return Promise.resolve('mock_pk_123')
return Promise.resolve(this.decrypt(password).keystore.getPrivateKeyString())
}
}
|
const mongoose = require('mongoose')
const Response = require('../lib/generateResponseLib')
const logger = require('../lib/loggerLib')
const util = require('../lib/utilityLib')
const socketLib = require('../lib/socketLib')
const TodoLists = mongoose.model('TodosList');
const Todo = mongoose.model('Todo');
/* Save User Lists of TODOS */
let saveList = (req, res) => {
if (req.body.userId && req.body.lists) {
let lists = JSON.parse(req.body.lists);
TodoLists.findOne({ userId: req.body.userId }, (error, result) => {
if (error) {
console.log(error)
logger.error('Error occurred while retrieval from database.', 'todoListController: saveList()', 10);
let apiResponse = Response.generate(true, 'Failed to save User Todo List!! Some internal error occurred.', 500, null);
res.send(apiResponse);
}
else {
console.log("-- findOne result--")
console.log(result)
let newTodoLists = new TodoLists({
userId: req.body.userId,
listNames: lists,
lastModified: new Date(),
createdOn: new Date()
});
let upsertData = newTodoLists.toObject();
delete upsertData._id; // mandatory so as to upsert
console.log("--Upsert Data--", upsertData)
TodoLists.updateOne({ userId: req.body.userId }, upsertData, { upsert: true },
(err, rawMessage) => {
if (error) {
console.log(err)
logger.error('Error occurred while saving at database.', 'todoListController: saveList()', 10);
let apiResponse = Response.generate(true, 'Failed to save User Todo List!! Some internal error occurred.', 500, null);
res.send(apiResponse);
}
else {
console.log(rawMessage)
logger.info('TODO List saved!!', 'todoListController: saveList()', 10)
if (req.body.friendAccess === 'true')
socketLib.notificationsSystem(req, {}, 'SAVE_LIST')
let apiResponse = Response.generate(false, 'TODO List created!!', 200, newTodoLists);
res.send(apiResponse);
}
}) //saved TODO List in database
}
})
}
} // END saveList()
/* Get names of all TODO Lists */
let getAllLists = (req, res) => {
if (req.query.userId) {
TodoLists.findOne({ userId: req.query.userId }, {},
{ sort: { 'createdOn': -1 } }, (err, result) => {
if (err) {
console.log(err)
logger.error('Error occurred while retrieving from database.', 'todoListController: getAllLists()', 10);
let apiResponse = Response.generate(true, 'Failed to retrieve!! Some internal error occurred', 500, null);
res.send(apiResponse);
}
else if (util.isEmpty(result)) {
let apiResponse = Response.generate(true, 'Retrieval Failed!! Invalid UserId or No List yet', 404, null);
res.send(apiResponse);
}
else {
console.log(result.listNames)
let apiResponse = Response.generate(false, 'Retrieval Successful', 200, result.listNames);
res.send(apiResponse);
}
})
}
else {
let apiResponse = Response.generate(true, 'UserId field empty', 400, null);
res.send(apiResponse);
}
} // END getAllLists()
/* Save TODO List */
let saveTodo = (req, res) => {
if (util.isObjectEmpty(req.body)) {
let apiResponse = Response.generate(true, 'Save Failed !! One or More Parameters are Missing.', 400, null);
res.send(apiResponse);
}
else {
let data = JSON.parse(req.body.TodoList);
let newTodo = new Todo({
listName: req.body.listName,
userId: req.body.userId,
TodoList: data,
createdOn: new Date()
});
let upsertData = newTodo.toObject();
delete upsertData._id; // mandatory so as to upsert
Todo.updateOne({ userId: req.body.userId, listName: req.body.listName }, upsertData,
{ upsert: true }, (error, rawMessage) => {
if (error) {
console.log(error)
logger.error('Error occurred while saving at database.', 'todoListController: saveTodo()', 10);
let apiResponse = Response.generate(true, 'Failed to save User Todo List!! Some internal error occurred.', 500, null);
res.send(apiResponse);
}
else {
console.log("-- updateOne result--", rawMessage)
logger.info('TODO List saved!!', 'todoListController: saveTodo()', 10)
if (req.body.friendAccess === 'true')
socketLib.notificationsSystem(req, {}, 'SAVE_TODO')
let apiResponse = Response.generate(false, 'TODO List saved!!', 200, upsertData);
res.send(apiResponse);
}
}) //saved TODO List in database
}
} // END saveTodo()
/* Get a particular TODO List */
let getTodo = (req, res) => {
if (req.query.userId && req.query.listname) {
Todo.findOne({ userId: req.query.userId, listName: req.query.listname }, (err, result) => {
if (err) {
console.log(err)
logger.error('Error occurred while retrieving from database.', 'todoListController: getTodo()', 10);
let apiResponse = Response.generate(true, 'Failed to retrieve!! Some internal error occurred', 500, null);
res.send(apiResponse);
}
else if (util.isEmpty(result)) {
let apiResponse = Response.generate(true, 'Retrieval Failed!! Invalid UserId or List is empty', 404, null);
res.send(apiResponse);
}
else {
console.log(result.TodoList)
let apiResponse = Response.generate(false, 'Retrieval Successful', 200, result.TodoList);
res.send(apiResponse);
}
})
}
else {
let apiResponse = Response.generate(true, 'One or More Parameters are Missing.', 400, null);
res.send(apiResponse);
}
} //END getTodo()
let deleteList = (req, res) => {
if (!req.body.userId || !req.body.listName) {
let apiResponse = Response.generate(true, 'One or More Parameters are Missing.', 400, null);
res.send(apiResponse);
return;
}
TodoLists.findOne({ userId: req.body.userId }, (err, result) => {
if (err) {
console.log(err)
logger.error('Error occurred while querying to database.', 'todoListController: deleteList()', 10);
}
else if (util.isEmpty(result)) {
let apiResponse = Response.generate(true, 'No User Found!! Invalid UserId or No Lists Yet', 404, null);
console.log(apiResponse);
}
else {
console.log('Lists: ', result.listNames)
/* Delete the list from listNames*/
util.spliceWithKey(result.listNames, req.body.listName);
// Save the changes to the document
result.save((error, doc) => {
if (error) {
console.log(error);
logger.error("Failed to save", "todoListController: deleteList()", 10);
}
else {
logger.info('List removed from User Lists !!', "todoListController: deleteList()", 10);
}
}); // Changes Saved for User
}
})
Todo.findOneAndDelete({ userId: req.body.userId, listName: req.body.listName }, (err, result) => {
if (err) {
console.log(err)
logger.error('Error occurred while querying to database.', 'todoListController: deleteList()', 10);
let apiResponse = Response.generate(true, 'Failed to delete!! Some internal error occurred', 500, null);
res.send(apiResponse);
}
else if (util.isEmpty(result)) {
let apiResponse = Response.generate(true, 'No such List Found!! List may be Empty or Invalid User', 404, null);
res.send(apiResponse);
}
else {
console.log('List content: ', result)
let apiResponse = Response.generate(false, 'List Deleted Successfully', 200, result);
res.send(apiResponse);
}
})
} // END deleteList()
module.exports = {
saveList: saveList,
saveTodo: saveTodo,
getTodo: getTodo,
getAllLists: getAllLists,
deleteList: deleteList
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.