text
stringlengths 7
3.69M
|
|---|
/* global kakao */
import React, { useState, useEffect } from 'react'
import Header from '../header/header';
import Footer from '../footer/footer';
import { Link } from 'react-router-dom';
import '../components/common/Button.css';
import '../components/css/map.css';
import * as App from '../App';
const APP_KEY = 'dfa21c11ffd9592aa4e83b78260f76ae'
const KakaoMap = () => {
const [map, setMap] = useState(false)
const imgSrc = "https://t1.daumcdn.net/localimg/localimages/07/mapapidoc/markerStar.png";
let position = App.getPosition();
let data = App.getData();
console.log(data);
console.log(position);
console.log(map);
//지도 생성
const createMap = () => {
const script1 = document.createElement('script')
script1.async = true
script1.src = `https://dapi.kakao.com/v2/maps/sdk.js?appkey=${APP_KEY}&autoload=false`
document.head.appendChild(script1)
script1.onload = () => {
const { kakao } = window
kakao.maps.load(() => {
let container = document.getElementById('listMap')
let options = {
center: new kakao.maps.LatLng(position['lat'], position['lng']),
level: 5,
}
const createdMap = new kakao.maps.Map(container, options)
let imgSize = new kakao.maps.Size(24,35);
let img = new kakao.maps.MarkerImage(imgSrc,imgSize);
setMap(createdMap)
displayMarker({'name':'내 위치', 'lat':position['lat'],'lng':position['lng']},img);
})
}
const script2 = document.createElement('script')
script2.async = true
script2.src = `//dapi.kakao.com/v2/maps/sdk.js?appkey=${APP_KEY}&libraries=services,clusterer,drawing&autoload=false`
document.head.appendChild(script2)
}
//장소 검색 객체 생성
const renewal=()=>{
data = App.getData();
dataDisplay()
}
//맛집위치에 마커 표시
function displayMarker(data, img){
const { kakao } = window
// 마커를 생성하고 지도에 표시합니다
const marker = new kakao.maps.Marker({
map : map,
position: new kakao.maps.LatLng(data['lat'],data['lng']),
title:data['name'],
image: img,
clickable : true
});
var infowindow = new kakao.maps.InfoWindow({zIndex:1});
// 마커에 클릭이벤트를 등록합니다
kakao.maps.event.addListener(marker, 'click', function() {
// 마커를 클릭하면 장소명이 인포윈도우에 표출됩니다
infowindow.setContent('<div style="padding:5px;font-size:12px; justify-content: center">' + data['name']+'</div>');
infowindow.open(map, marker);
});
}
function dataDisplay()
{
console.log(data);
for(let i in data){
displayMarker(data[i]);
}
}
if(!map)
{
console.log(App.getPosition());
createMap();
//dataDisplay()
}
return (
<div className="App">
<Link to="/roulette">
<button class="previous_step">이전단계로 돌아가기</button>
</Link>
<h2>맛집 추천 지도</h2>
<button class="right" onClick={renewal}>갱신</button>
<div className='container'>
<div className ='area'>
<div id="listMap" style={{ width: '70vw', height: '60vh' }}></div>
</div>
</div>
</div>
)
}
export default KakaoMap
|
var gulp = require('gulp');
var gutil = require('gulp-util');
var source = require('vinyl-source-stream');
var browserify = require('browserify');
var watchify = require('watchify');
var reactify = require('reactify');
var templatify = require('react-templatify');
var sass = require('gulp-sass');
var jade = require('gulp-jade');
var rt = require('gulp-react-templates');
var spritesmith = require('gulp.spritesmith');
var sourcemaps = require('gulp-sourcemaps');
// React js
function build(file){
if (file) {
gutil.log("Recompiling: "+file);
}
return bundler
.bundle()
.on('error', gutil.log.bind(gutil,'Browserify Error'))
.pipe(source('main.js'))
.pipe(gulp.dest('./dist/assets/js'));
}
var bundler = watchify(browserify({
entries:['./src/jsx/app.jsx'],
// transform: [reactify],
// transform: [templatify],
extensions:['.jsx'],
debug:true,
cache:{},
packageCache:{},
fullPaths:true
}));
bundler.on('update',build);
gulp.task('jsx', function(){
build();
})
gulp.task('rt', function() {
gulp.src('./src/rt/**/*.rt')
.pipe(rt({modules: 'commonjs'}))
.pipe(gulp.dest('./src/jsx/templates'));
});
// Css libs
gulp.task('csslibs', function () {
gulp.src('./src/sass/libs.scss')
.pipe(sourcemaps.init())
.pipe(sass().on('error', sass.logError))
.pipe(sourcemaps.write('./maps'))
.pipe(gulp.dest('./dist/assets/css/'));
});
// Sass
gulp.task('sass', function () {
gulp.src('./src/sass/main.scss')
.pipe(sourcemaps.init())
.pipe(sass().on('error', sass.logError))
.pipe(sourcemaps.write('./maps'))
.pipe(gulp.dest('./dist/assets/css/'));
});
// Jade
gulp.task('jade', function() {
gulp.src(['./src/jade/*.jade','!./src/jade/_*.jade'])
.pipe(jade({
pretty: true
}))
.pipe(gulp.dest('./dist/'))
});
// Sprite
// gulp.task('sprite', function() {
// gulp.src('./src/images/*.png')
// .pipe(spritesmith({
// destImg: './dist/images/sprite.png',
// destCSS: './src/sass/atoms/_sprite.scss'
// }));
// });
gulp.task('sprite', function () {
var spriteData = gulp.src('./src/images/*.png')
.pipe(spritesmith({
imgName: 'sprite.png',
cssName: '_sprite.scss'
}));
// var cssStream = spriteData.css
// // .pipe(csso())
// .pipe(gulp.dest('./src/sass/atoms/'));
// return spriteData.pipe(gulp.dest('./dist/assets/images'));
// return merge(imgStream, cssStream);
spriteData.img.pipe(gulp.dest('./dist/assets/images'))
spriteData.css.pipe(gulp.dest('./src/sass/atoms/'));
});
// gulp.task('sprite', function () {
// var spriteData = gulp.src('images/*.png')
// .pipe(spritesmith({
// imgName: 'sprite.png',
// cssName: 'sprite.css'
// }));
// return spriteData.pipe(gulp.dest('path/to/output/'));
// });
// Watch
gulp.task('watch', function () {
gulp.watch('./src/sass/**/*.scss',['sass']);
gulp.watch('./src/jade/**/*.jade',['jade']);
});
//
gulp.task('default', ['sass', 'jade', 'jsx', 'watch']);
|
import { GET_USER_NOW } from "./type";
export const getUserNow = (userNow) => (dispatch) => {
dispatch({
type: GET_USER_NOW,
payload: userNow,
});
};
export default getUserNow;
|
const Event = require('../../../models/event'),
{ transformEvent } = require('../common'),
log = require('../../../helpers/logger/log')(module.filename),
HttpError = require('../../../error/HttpError');
const editEvent = async (args, { req, res }) => {
try {
if (!req.isAuth) {
throw new HttpError(401);
}
const editEvent = args.editEventInput;
const event = await Event.findById(editEvent.id);
if (!event) {
throw new HttpError(404, "Can't update nonexistent Event");
}
if (editEvent.title !== event.title) {
event.title = editEvent.title;
}
if (editEvent.price !== event.price) {
event.price = editEvent.price;
}
if (editEvent.date !== event.date) {
event.date = editEvent.date;
}
if (editEvent.description !== event.description) {
event.description = editEvent.description;
}
const rezultOfEventSave = await event.save();
return transformEvent(rezultOfEventSave);
} catch (error) {
log.error(error);
res.handleGraphqlError(error);
}
};
module.exports = editEvent;
|
/*
FlashCanvas, 2012-11-01T22:38 commit ID 34a50cbe6aeb11e050c7d41e8e2cf266a345aeed
Copyright 2012 Willow Systems Corp
Copyright (c) 2009 Tim Cameron Ryan
Copyright (c) 2009-2011 FlashCanvas Project
Released under the MIT/X License
*/
window.ActiveXObject && !window.CanvasRenderingContext2D && function () {
function D(a) {
return ((a[C + "Options"] || {}).swfPath || K) + "flashcanvas.swf"
}
function s(a) {
return ("" + a)
.replace(/&/g, "&")
.replace(/</g, "<")
}
function i(a) {
throw new E(a);
}
function F(a) {
var b = parseInt(a.width, 10),
c = parseInt(a.height, 10);
if (isNaN(b) || 0 > b)
b = 300;
if (isNaN(c) || 0 > c)
c = 150;
a.width = b;
a.height = c
}
var G = this.document,
t = "canvas",
C = "FlashCanvas",
H = "onreadystatechange",
n;
a : {
n = this
.document
.getElementsByTagName("script");
var I = "",
u = n.length;
if (u)
for (I = n[u - 1].src || ""; u;) {
script = n[u - 1];
if (script.src && script.src.match("flashcanvas")) {
n = 8 <= G.documentMode
? script.src
: script.getAttribute("src", 4);
break a
}
u--
}
n = I
}
var K = n.replace(/[^\/]+$/, ""),
e = new function (a) {
for (var b = 0, c = a.length; b < c; b++)
this[a[b]] = b
}(("toDataURL save restore scale rotate translate transform setTransform globalAlph" +
"a globalCompositeOperation strokeStyle fillStyle createLinearGradient createRadi" +
"alGradient createPattern lineWidth lineCap lineJoin miterLimit shadowOffsetX sha" +
"dowOffsetY shadowBlur shadowColor clearRect fillRect strokeRect beginPath closeP" +
"ath moveTo lineTo quadraticCurveTo bezierCurveTo arcTo rect arc fill stroke clip" +
" isPointInPath font textAlign textBaseline fillText strokeText measureText drawI" +
"mage createImageData getImageData putImageData addColorStop direction resize").split(" ")),
v = {},
p = {},
q = {},
x = {},
y = {},
w = function (a, b) {
this.canvas = a;
this._swf = b;
this._canvasId = b
.id
.slice(8);
this._initialize();
this._gradientPatternId = 0;
this._font = this._direction = "";
var c = this;
this._executeCommandIntervalID = setInterval(function () {
for (var a = c.canvas, b = !1, a = a.parentNode; a && !b;)
b = a.body,
a = a.parentNode;
b
? 0 === q[c._canvasId] && c._executeCommand()
: clearInterval(c._executeCommandIntervalID)
}, 30)
};
w.prototype = {
save: function () {
this._setCompositing();
this._setShadows();
this._setStrokeStyle();
this._setFillStyle();
this._setLineStyles();
this._setFontStyles();
this
._stateStack
.push([
this._globalAlpha,
this._globalCompositeOperation,
this._strokeStyle,
this._fillStyle,
this._lineWidth,
this._lineCap,
this._lineJoin,
this._miterLimit,
this._shadowOffsetX,
this._shadowOffsetY,
this._shadowBlur,
this._shadowColor,
this._font,
this._textAlign,
this._textBaseline
]);
this
._queue
.push(e.save)
},
restore: function () {
var a = this._stateStack;
a.length && (a = a.pop(), this.globalAlpha = a[0], this.globalCompositeOperation = a[1], this.strokeStyle = a[2], this.fillStyle = a[3], this.lineWidth = a[4], this.lineCap = a[5], this.lineJoin = a[6], this.miterLimit = a[7], this.shadowOffsetX = a[8], this.shadowOffsetY = a[9], this.shadowBlur = a[10], this.shadowColor = a[11], this.font = a[12], this.textAlign = a[13], this.textBaseline = a[14]);
this
._queue
.push(e.restore)
},
scale: function (a, b) {
this
._queue
.push(e.scale, a, b)
},
rotate: function (a) {
this
._queue
.push(e.rotate, a)
},
translate: function (a, b) {
this
._queue
.push(e.translate, a, b)
},
transform: function (a, b, c, d, f, g) {
this
._queue
.push(e.transform, a, b, c, d, f, g)
},
setTransform: function (a, b, c, d, f, g) {
this
._queue
.push(e.setTransform, a, b, c, d, f, g)
},
_setCompositing: function () {
var a = this._queue;
this._globalAlpha !== this.globalAlpha && (this._globalAlpha = this.globalAlpha, a.push(e.globalAlpha, this._globalAlpha));
this._globalCompositeOperation !== this.globalCompositeOperation && (this._globalCompositeOperation = this.globalCompositeOperation, a.push(e.globalCompositeOperation, this._globalCompositeOperation))
},
_setStrokeStyle: function () {
if (this._strokeStyle !== this.strokeStyle) {
var a = this._strokeStyle = this.strokeStyle;
if ("string" !== typeof a)
if (a instanceof r || a instanceof z)
a = a.id;
else
return;
this
._queue
.push(e.strokeStyle, a)
}
},
_setFillStyle: function () {
if (this._fillStyle !== this.fillStyle) {
var a = this._fillStyle = this.fillStyle;
if ("string" !== typeof a)
if (a instanceof r || a instanceof z)
a = a.id;
else
return;
this
._queue
.push(e.fillStyle, a)
}
},
createLinearGradient: function (a, b, c, d) {
(!isFinite(a) || !isFinite(b) || !isFinite(c) || !isFinite(d)) && i(9);
this
._queue
.push(e.createLinearGradient, a, b, c, d);
return new r(this)
},
createRadialGradient: function (a, b, c, d, f, g) {
(!isFinite(a) || !isFinite(b) || !isFinite(c) || !isFinite(d) || !isFinite(f) || !isFinite(g)) && i(9);
(0 > c || 0 > g) && i(1);
this
._queue
.push(e.createRadialGradient, a, b, c, d, f, g);
return new r(this)
},
createPattern: function (a, b) {
a || i(17);
var c = a.tagName,
d,
f = this._canvasId;
if (c)
if (c = c.toLowerCase(), "img" === c)
d = a.getAttribute("src", 2);
else {
if (c === t || "video" === c)
return;
i(17)
} else
a.src
? d = a.src
: i(17);
"repeat" === b || ("no-repeat" === b || "repeat-x" === b || "repeat-y" === b || "" === b || null === b) || i(12);
this
._queue
.push(e.createPattern, s(d), b);
!p[f][d] && v[f] && (this._executeCommand(), ++q[f], p[f][d] = !0);
return new z(this)
},
_setLineStyles: function () {
var a = this._queue;
this._lineWidth !== this.lineWidth && (this._lineWidth = this.lineWidth, a.push(e.lineWidth, this._lineWidth));
this._lineCap !== this.lineCap && (this._lineCap = this.lineCap, a.push(e.lineCap, this._lineCap));
this._lineJoin !== this.lineJoin && (this._lineJoin = this.lineJoin, a.push(e.lineJoin, this._lineJoin));
this._miterLimit !== this.miterLimit && (this._miterLimit = this.miterLimit, a.push(e.miterLimit, this._miterLimit))
},
_setShadows: function () {
var a = this._queue;
this._shadowOffsetX !== this.shadowOffsetX && (this._shadowOffsetX = this.shadowOffsetX, a.push(e.shadowOffsetX, this._shadowOffsetX));
this._shadowOffsetY !== this.shadowOffsetY && (this._shadowOffsetY = this.shadowOffsetY, a.push(e.shadowOffsetY, this._shadowOffsetY));
this._shadowBlur !== this.shadowBlur && (this._shadowBlur = this.shadowBlur, a.push(e.shadowBlur, this._shadowBlur));
this._shadowColor !== this.shadowColor && (this._shadowColor = this.shadowColor, a.push(e.shadowColor, this._shadowColor))
},
clearRect: function (a, b, c, d) {
this
._queue
.push(e.clearRect, a, b, c, d)
},
fillRect: function (a, b, c, d) {
this._setCompositing();
this._setShadows();
this._setFillStyle();
this
._queue
.push(e.fillRect, a, b, c, d)
},
strokeRect: function (a, b, c, d) {
this._setCompositing();
this._setShadows();
this._setStrokeStyle();
this._setLineStyles();
this
._queue
.push(e.strokeRect, a, b, c, d)
},
beginPath: function () {
this
._queue
.push(e.beginPath)
},
closePath: function () {
this
._queue
.push(e.closePath)
},
moveTo: function (a, b) {
this
._queue
.push(e.moveTo, a, b)
},
lineTo: function (a, b) {
this
._queue
.push(e.lineTo, a, b)
},
quadraticCurveTo: function (a, b, c, d) {
this
._queue
.push(e.quadraticCurveTo, a, b, c, d)
},
bezierCurveTo: function (a, b, c, d, f, g) {
this
._queue
.push(e.bezierCurveTo, a, b, c, d, f, g)
},
arcTo: function (a, b, c, d, f) {
0 > f && isFinite(f) && i(1);
this
._queue
.push(e.arcTo, a, b, c, d, f)
},
rect: function (a, b, c, d) {
this
._queue
.push(e.rect, a, b, c, d)
},
arc: function (a, b, c, d, f, g) {
0 > c && isFinite(c) && i(1);
this
._queue
.push(e.arc, a, b, c, d, f, g
? 1
: 0)
},
fill: function () {
this._setCompositing();
this._setShadows();
this._setFillStyle();
this
._queue
.push(e.fill)
},
stroke: function () {
this._setCompositing();
this._setShadows();
this._setStrokeStyle();
this._setLineStyles();
this
._queue
.push(e.stroke)
},
clip: function () {
this
._queue
.push(e.clip)
},
isPointInPath: function () {},
_setFontStyles: function () {
var a = this._queue;
if (this._font !== this.font)
try {
var b = y[this._canvasId];
b.style.font = this._font = this.font;
var c = b.currentStyle,
d = [c.fontStyle, c.fontWeight, b.offsetHeight, c.fontFamily].join(" ");
a.push(e.font, d)
} catch (f) {}
this._textAlign !== this.textAlign && (this._textAlign = this.textAlign, a.push(e.textAlign, this._textAlign));
this._textBaseline !== this.textBaseline && (this._textBaseline = this.textBaseline, a.push(e.textBaseline, this._textBaseline));
this._direction !== this.canvas.currentStyle.direction && (this._direction = this.canvas.currentStyle.direction, a.push(e.direction, this._direction))
},
fillText: function (a, b, c, d) {
this._setCompositing();
this._setFillStyle();
this._setShadows();
this._setFontStyles();
this
._queue
.push(e.fillText, s(a), b, c, void 0 === d
? Infinity
: d)
},
strokeText: function (a, b, c, d) {
this._setCompositing();
this._setStrokeStyle();
this._setShadows();
this._setFontStyles();
this
._queue
.push(e.strokeText, s(a), b, c, void 0 === d
? Infinity
: d)
},
measureText: function (a) {
var b = y[this._canvasId];
try {
b.style.font = this.font
} catch (c) {}
b.innerText = a.replace(/[ \n\f\r]/g, "\t");
return new L(b.offsetWidth)
},
drawImage: function (a, b, c, d, f, g, j, M, N) {
a || i(17);
var h = a.tagName,
k,
l = arguments.length,
A = this._canvasId;
if (h)
if (h = h.toLowerCase(), "img" === h)
k = a.getAttribute("src", 2);
else {
if (h === t || "video" === h)
return;
i(17)
} else
a.src
? k = a.src
: i(17);
this._setCompositing();
this._setShadows();
k = s(k);
if (3 === l)
this._queue.push(e.drawImage, l, k, b, c);
else if (5 === l)
this._queue.push(e.drawImage, l, k, b, c, d, f);
else if (9 === l)
(0 === d || 0 === f) && i(1),
this._queue.push(e.drawImage, l, k, b, c, d, f, g, j, M, N);
else
return;
!p[A][k] && v[A] && (this._executeCommand(), ++q[A], p[A][k] = !0)
},
createImageData: function () {},
getImageData: function () {},
putImageData: function () {},
loadImage: function (a, b, c) {
var d = a.tagName,
f,
g = this._canvasId;
d
? "img" === d.toLowerCase() && (f = a.getAttribute("src", 2))
: a.src && (f = a.src);
if (f && !p[g][f]) {
if (b || c)
x[g][f] = [a, b, c];
this
._queue
.push(e.drawImage, 1, s(f));
v[g] && (this._executeCommand(), ++q[g], p[g][f] = !0)
}
},
_initialize: function () {
this.globalAlpha = this._globalAlpha = 1;
this.globalCompositeOperation = this._globalCompositeOperation = "source-over";
this.fillStyle = this._fillStyle = this.strokeStyle = this._strokeStyle = "#000000";
this.lineWidth = this._lineWidth = 1;
this.lineCap = this._lineCap = "butt";
this.lineJoin = this._lineJoin = "miter";
this.miterLimit = this._miterLimit = 10;
this.shadowBlur = this._shadowBlur = this.shadowOffsetY = this._shadowOffsetY = this.shadowOffsetX = this._shadowOffsetX = 0;
this.shadowColor = this._shadowColor = "rgba(0, 0, 0, 0.0)";
this.font = this._font = "10px sans-serif";
this.textAlign = this._textAlign = "start";
this.textBaseline = this._textBaseline = "alphabetic";
this._queue = [];
this._stateStack = []
},
_flush: function () {
var a = this._queue;
this._queue = [];
return a
},
_executeCommand: function () {
var a = this._flush();
if (0 < a.length)
try {
return eval(this._swf.CallFunction('<invoke name="executeCommand" returntype="javascript"><arguments><string>' + a.join("�") + "</string></arguments></invoke>"))
} catch (b) {}
},
_resize: function (a, b) {
this._executeCommand();
this._initialize();
0 < a && (this._swf.width = a);
0 < b && (this._swf.height = b);
this
._queue
.push(e.resize, a, b)
}
};
var r = function (a) {
this._ctx = a;
this.id = a._gradientPatternId++
};
r.prototype = {
addColorStop: function (a, b) {
(isNaN(a) || 0 > a || 1 < a) && i(1);
this
._ctx
._queue
.push(e.addColorStop, this.id, a, b)
}
};
var z = function (a) {
this.id = a._gradientPatternId++
},
L = function (a) {
this.width = a
},
E = function (a) {
this.code = a;
this.message = {
1: "INDEX_SIZE_ERR",
9: "NOT_SUPPORTED_ERR",
11: "INVALID_STATE_ERR",
12: "SYNTAX_ERR",
17: "TYPE_MISMATCH_ERR",
18: "SECURITY_ERR"
}[a]
};
E.prototype = Error();
var J = "initElement",
m = {
registeredEvents: {},
canvases: {},
initWindow: function (a) {
function b() {
if ("complete" === a.document.readyState) {
a
.document
.detachEvent(H, b);
for (var c = a.document.getElementsByTagName(t), d = 0, e = c.length; d < e; ++d)
m[J](c[d])
}
}
var c = a.document;
c.createElement(t);
c
.createStyleSheet()
.cssText = t + "{display:inline-block;overflow:hidden;width:300px;height:150px}";
var d = this.canvases,
e = this.registeredEvents,
g = function () {
a.detachEvent("onunload", g);
var b,
c,
h,
k,
l,
j,
B;
for (B in d)
if (b = d[B], c = b.firstChild, k = b.ownerDocument.defaultView
? b.ownerDocument.defaultView
: b.ownerDocument.parentWindow, a === k) {
for (h in c)
"function" === typeof c[h] && (c[h] = null);
for (h in b)
"function" === typeof b[h] && (b[h] = null);
k = 0;
for (l = e[B].length; k !== l; k++)
j = e[B][k],
c.detachEvent(j[0], j[1]),
b.detachEvent(j[0], j[1])
}
a.CanvasRenderingContext2D = null;
a.CanvasGradient = null;
a.CanvasPattern = null;
a[C] = null
};
a.attachEvent("onunload", g);
a.CanvasRenderingContext2D = w;
a.CanvasGradient = r;
a.CanvasPattern = z;
a[C] = m;
var j = D(a);
0 === j.indexOf(a.location.protocol + "//" + a.location.host + "/") && a.setTimeout(function () {
var a = new ActiveXObject("Microsoft.XMLHTTP");
a.open("GET", j, !1);
a.send(null)
}, 0);
"complete" === a.document.readyState
? b()
: a
.document
.attachEvent(H, b)
}
};
m[J] = function (a) {
if (a.getContext)
return a;
var b = a.ownerDocument,
c = b.defaultView
? b.defaultView
: b.parentWindow;
c.CanvasRenderingContext2D || this.initWindow(c);
var d = Math
.random()
.toString(36)
.slice(2) || "0",
f = "external" + d;
v[d] = !1;
p[d] = {};
q[d] = 1;
x[d] = {};
this.registeredEvents[d] = [];
F(a);
var g = D(c);
a.innerHTML = '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="' + ("https:" === c.location.protocol
? "https:"
: "http:") + '//fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0' +
'" width="100%" height="100%" id="' + f + '"><param name="allowScriptAccess" value="always"><param name="flashvars" value="' +
'id=' + f + '"><param name="wmode" value="transparent"></object><span style="margin:0;padding' +
':0;border:0;display:inline-block;position:static;height:1em;overflow:visible;whi' +
'te-space:nowrap"></span>';
this.canvases[d] = a;
var j = a.firstChild;
y[d] = a.lastChild;
var i = b.body.contains;
if (i(a))
j.movie = g;
else
var m = c.setInterval(function () {
i(a) && (c.clearInterval(m), j.movie = g)
}, 2);
if ("BackCompat" === b.compatMode || !c.XMLHttpRequest)
y[d].style.overflow = "hidden";
var h = new w(a, j);
a.getContext = function (a) {
return "2d" === a
? h
: null
};
a.toDataURL = function (a, b) {
"image/jpeg" === ("" + a).toLowerCase()
? h
._queue
.push(e.toDataURL, a, "number" === typeof b
? b
: "")
: h
._queue
.push(e.toDataURL, a);
return h._executeCommand()
};
b = function (a) {
var a = a
? a.srcElement
: c.event.srcElement,
b = a.parentNode;
a.blur();
b.focus()
};
this
.registeredEvents[d]
.push(["onfocus", b]);
j.attachEvent("onfocus", b);
return a
};
m.saveImage = function (a) {
a
.firstChild
.saveImage()
};
m.setOptions = function () {};
m.trigger = function (a, b) {
this
.canvases[a]
.fireEvent("on" + b)
};
m.unlock = function (a, b, c) {
try {
var d,
e,
g,
j,
i,
m,
h,
k,
l;
if (void 0 === b)
d = this.canvases[a],
e = d.firstChild,
k = d.ownerDocument,
l = k.defaultView
? k.defaultView
: k.parentWindow,
F(d),
g = d.width,
j = d.height,
d.style.width = g + "px",
d.style.height = j + "px",
0 < g && (e.width = g),
0 < j && (e.height = j),
e.resize(g, j),
b = function (a) {
var a = a
? a
: l.event,
b = a.propertyName;
if ("width" === b || "height" === b) {
var a = a.srcElement,
c = a[b],
d = parseInt(c, 10);
if (isNaN(d) || 0 > d)
d = "width" === b
? 300
: 150;
c === d
? (a.style[b] = d + "px", a.getContext("2d")._resize(a.width, a.height))
: a[b] = d
}
}
,
this
.registeredEvents[a]
.push(["onpropertychange", b]),
d.attachEvent("onpropertychange", b),
v[a] = !0,
"function" === typeof d.onload && l.setTimeout(function () {
d.onload()
}, 0);
else if (i = x[a][b])
m = i[0],
h = i[1 + c],
delete x[a][b],
"function" === typeof h && h.call(m);
q[a] && --q[a]
} catch (n) {
throw console.log("Call to FlashCanvas.unlock had thrown an error: ", n.message),
n;
}
};
m.initWindow(this, G);
keep = [w.measureText, w.loadImage]
}.call(window);
|
import count from './count';
import newsList from './news-list';
// export ...brightUiReducers from 'components/reducers';
import toast from './toast';
import loading from './loading';
export { count, newsList, toast, loading };
|
//YouTube Video ID
let playList = [
"Yd_nsFJAXV4",
"R-fQPTwma9o",
"EH3zcuRQXNo",
"EO0abB6gJEw",
"x0Wa6ix51i0",
"_eu7EZIdLMM",
"U5tLGYIPGdQ",
"XzwVReweL_o",
"b5QXpUlEOyk",
"niElcLtli_Q",
"SGJIFBSCXgM"
];
//播放起訖秒數
let playTime = [
[100, 103],
[110, 112],
[111, 114],
[32, 34],
[84, 89],
[47, 50],
[59, 61],
[59, 61],
[32, 35],
[49, 50],
[38, 40]
];
|
module.exports = {
footerText: 'Copyright Quancy Ltd. © 2019',
// Date formats from
// https://www.ibm.com/support/knowledgecenter/en/SSS28S_8.1.0/XFDL/i_xfdl_r_formats_en_SG.html
singaporeDateFormat: {
short: 'M/d/yy',
medium: 'dd-MMM-yyyy',
long: 'MMMM d, yyyy',
full: 'EEEE, MMMM d, yyyy'
},
singaporeDateTimeFormat: {
short: `M/d/yy h:mm a`,
medium: `dd-MMM-yyyy a hh:mm:ss`
}
};
|
import React from "react";
import images from "../../../utils/ImageHelper";
import OffersRate from "../OffersRate";
import CheckoutForm from "./CheckoutForm";
const OffersPayment = ({sendToUser, sendByUser, isOffer, makePayment, isPaid, projectId, companyId}) => {
return (
<div className="chat-main-box">
<div className="accepted-box-bg greeb-box m-b-0">
<div className="accepted-box-body offer_conform">
<div className="right-img">
<img src={sendToUser.ProfileImage || images.avatarImg} alt="user"/>
<h5>{sendToUser.FullName}</h5>
</div>
<div className="green-bg-line">
<a >${isOffer.offerAmount}</a>
</div>
<div className="right-img">
<img src={sendByUser.ProfileImage || images.avatarImg} alt="user"/>
<h5>{sendByUser.FullName}</h5>
</div>
</div>
<div className="bottom-two-btn green-bottom-box">
<a className="bottom-two-box" >Accepted <i className="fa fa-check" aria-hidden="true"/></a>
<a className="bottom-two-box" >Confirmed <i className="fa fa-check" aria-hidden="true"/></a>
</div>
<div className="congrats-msg congrats-green-msg">
<div className="congrats-msg-box">
<div className="check-icon">
<img src={images.congratsiconwhite} alt="img"/>
</div>
<div className="congrats-msg-script">
<p>You’ve Confirmed, Work is finished! <br/> Now make a payment and then rate the worker.</p>
</div>
</div>
</div>
</div>
{
isPaid ? <OffersRate projectId={projectId} companyId={companyId}/> :
<div className="reveiw-box-wrapper m-b-0">
<CheckoutForm sendToUser={sendToUser} sendByUser={sendByUser} isOffer={isOffer} makePayment={makePayment} isPaid={isPaid} projectId={projectId} companyId={companyId}/>
</div>
}
</div>
);
}
export default OffersPayment;
|
(function () {
angular.module('app').controller('homeController', homeController);
function homeController($scope, Message, FileUploader, NumerosSortiados, $http, $location, $state) {
$scope.list=[];
$scope.list_testSet=[];
$scope.xlm = false;
$scope.showTestset = function(){
NumerosSortiados.find({"filter":{"order":"numero ASC"}}).$promise.then(function (results) {
$scope.list_testSet=results;
});
var query = {
"date_begin": $scope.form.data.date_begin,
"date_end": $scope.form.data.date_end,
"clusterId": $scope.form.clusterId,
"status": $scope.form.status,
};
Transation.generateOrderReportDateNow(query)
.$promise
.then(function (data) {
if (data.report.response === 200) {
//sucesso
$scope.download_report = true;
console.log(data);
document.getElementById('download').setAttribute("href", data.report.url);
document.getElementById('download').click();
$scope.download_report = false;
} else if (data.report.response === 404) {
Message.CUSTOM('Não há dados para serem gerados dessa consulta', 'error');
} else {
Message.CUSTOM('Erro ao gerar o relatório', 'error');
}
});
}
$(document).on('change', ':file', function () {
var input = $(this),
numFiles = input.get(0).files ? input.get(0).files.length : 1,
label = input.val().replace(/\\/g, '/').replace(/.*\//, '');
var input = $(this).parents('.input-group').find(':text'),
name = numFiles > 1 ? numFiles + ' files selected' : label;
input.val(name);
});
//Conf upload
var uploader = $scope.uploader = new FileUploader({
url: '/api/containers/lotofacil/upload'
});
// ADDING FILTERS
uploader.filters.push({
name: 'filterName',
fn: function (item, options) {
if (item.size > 1000000) {
Message.CUSTOM('Tamanho máximo : 1 MB', 'error');
return false;
} else
return true;
// second user filter
uploader.clearQueue();
}
});
// ERRO FILE
uploader.onErrorItem = function (item, response, status, headers) {
Message.CUSTOM('Erro no arquivo', 'error');
};
$scope.saveButton = true;
$scope.submit = function (form) {
$scope.saveButton = false;
//Upload file
uploader.uploadAll();
uploader.onSuccessItem = function (item, response, status, headers) {
var retrievedObject = localStorage.currentUser;
var currentUser = JSON.parse(retrievedObject);
var nameFile = {
file: response.result.files.file[0],
loginId: currentUser.credentials.loginId,
typeNumerosSortiadosId:1
}
NumerosSortiados.saveFile(nameFile, function (_return) {
$scope.saveButton = true;
$scope.xlm=true;
if (_return.response.message !== "Arquivo incorreto") {
if (_return.response.list > 0) {
$scope.showTestset();
Message.SAVETRUEPARAM("Numeros gerado com sucesso");
$http.delete('/api/containers/lotofacil/files/' + encodeURIComponent(nameFile.file.name));
} else {
Message.INVALID("Erro ao salvar o arquivo");
$http.delete('/api/containers/lotofacil/files/' + encodeURIComponent(nameFile.file.name));
}
} else {
Message.INVALID(_return.response.message);
$http.delete('/api/containers/lotofacil/files/' + encodeURIComponent(nameFile.file.name));
}
});
};
};
}
})();
|
import React from 'react'
export default function Header({ contents, styles }) {
return (
<div style={styles}>
<h1>{contents.value}</h1>
</div>
);
}
|
import React, { Component } from "react";
import "./index.css";
import "antd/dist/antd.css";
import { Row, Col, Menu } from "antd";
import {Redirect,Route} from "react-router-dom"
const navigation = {
backgroundColor: "#79bcdc",
};
const navigation1 = {
fontFamily: "lisu",
fontSize: 28,
color: "#3061A1",
};
export default class index extends Component {
render() {
return (
<Row style={navigation}>
<Col span={1}></Col>
<Col span={2} style={navigation1}>
<Row align="middle" justify="center" style={{ height: 0.1*window.screen.height }}>
校园招聘
</Row>
</Col>
</Row>
);
}
}
|
// var temperatureInFahr = prompt("Please enter a temperature in Fahrenheit: ");
// var temperatureInCelcius = (temperatureInFahr - 32) * 5 / 9;
// console.log("Temperature in Fahrenheit : ", temperatureInFahr);
// console.log("Temperature in Celcius : ", temperatureInCelcius);
var temperature = prompt("Please enter a temperature: ");
var temperatureUnit = prompt("Please enter a temperature unit: ");
var temperatureInCelcius = 0;
var temperatureInFahr = 0;
var temperatureInKelvin = 0;
temperature = parseInt(temperature);
if (temperatureUnit === "Fahrenheit") {
temperatureInFahr = (temperature).toFixed(2);
temperatureInCelcius = ((temperature - 32) * 5 / 9).toFixed(2);
temperatureInKelvin = (temperatureInCelcius + 273.15).toFixed(2);
} else if (temperatureUnit === "Celcius") {
temperatureInFahr = ((temperature * 9 / 5) + 32).toFixed(2);
temperatureInCelcius = (temperature).toFixed(2);
temperatureInKelvin = (temperatureInCelcius - 273.15).toFixed(2);
} else { // Temperature unit is Kelvin
temperatureInFahr = ((temperature + 459.67) * 5/9).toFixed(2);
temperatureInCelcius = (temperature + 273.15).toFixed(2);
temperatureInKelvin = (temperature).toFixed(2);
}
console.log("Temperature in Fahrenheit : ", temperatureInFahr);
console.log("Temperature in Celcius : ", temperatureInCelcius);
console.log("Temperature in Kelvin : ", temperatureInKelvin);
|
var module = angular.module('ucms.app.permission');
module.controller("permissionCtrl", function ($scope, $xhttp, $filter, $uibModal, $modal, $folder, $content) {
$scope.fullPath = [];
$scope.permissionChanged = false;
$scope.object = {
id: '',
type: '',
parentId: '',
data: {},
permission: {}
}
$scope.profiles = [];
$scope.users = [];
// load all users and profiles from system, then combine them into a list
function loadAllPrincipals() {
$xhttp.get(WEBAPI_ENDPOINT + '/api/profile/getall').then(function (response) {
$scope.profiles = response.data;
});
$xhttp.get(WEBAPI_ENDPOINT + '/api/user/getall?username=&status=Active&pageIndex=1&pageSize=500&sortBy=user_name&sortDirection=asc').then(function (response) {
$scope.users = response.data.Items;
});
}
function getObject() {
if ($scope.object.type === "Folder") {
$folder.getById($scope.object.id).then(function (response) {
$scope.object.data = response.data;
$scope.object.parentId = response.data.ParentId;
$scope.fullPath = response.data.Path;
});
}
else if ($scope.object.type === "Content") {
$content.getById($scope.object.id).then(function (response) {
$scope.object.data = response.data;
$scope.object.parentId = response.data.Folder.Id;
$scope.fullPath = response.data.Folder.Path;
});
}
}
function getObjectPermission() {
$xhttp.get(WEBAPI_ENDPOINT + '/api/permission/object/getpermissions?objectId=' + $scope.object.id).then(function (response) {
$scope.object.permission = response.data;
_.each($scope.object.permission.ProfilePermissions,
function (item) {
checkPermissionFlag(item);
});
_.each($scope.object.permission.UserPermissions,
function (item) {
checkPermissionFlag(item);
if (item.User.Id === $scope.object.data.Owner.Id) {
item.isOwner = true;
} else {
item.isOwner = false;
}
});
});
}
function checkPermissionFlag(item) {
item.canRead = item.Permission.indexOf('Read') > -1;
item.canEdit = item.Permission.indexOf('Edit') > -1;
item.canCreate = item.Permission.indexOf('Create') > -1;
item.canDelete = item.Permission.indexOf('Delete') > -1;
item.fullControl = item.canRead && item.canCreate && item.canEdit && item.canDelete;
}
$scope.onPermissionChanged = function (item, changeType) {
$scope.permissionChanged = true;
switch (changeType) {
case 'Read':
if (!item.canRead) {
item.canCreate = item.canEdit = item.canDelete = item.fullControl = false;
} else {
item.fullControl = item.canRead && item.canCreate && item.canEdit && item.canDelete;
}
break;
case 'Create':
if (item.canCreate) {
item.canRead = true;
item.fullControl = item.canRead && item.canCreate && item.canEdit && item.canDelete;
} else {
item.fullControl = false;
}
break;
case 'Edit':
if (item.canEdit) {
item.canRead = true;
item.fullControl = item.canRead && item.canCreate && item.canEdit && item.canDelete;
} else {
item.fullControl = false;
}
break;
case 'Delete':
if (item.canDelete) {
item.canRead = true;
item.fullControl = item.canRead && item.canCreate && item.canEdit && item.canDelete;
} else {
item.fullControl = false;
}
break;
case 'Full':
if (!item.fullControl) {
item.fullControl = item.canRead && item.canCreate && item.canEdit && item.canDelete;
} else {
item.canRead = item.canCreate = item.canEdit = item.canDelete = true;
}
break;
}
var permissions = [];
if (item.canRead) permissions.push('Read');
if (item.canCreate) permissions.push('Create');
if (item.canEdit) permissions.push('Edit');
if (item.canDelete) permissions.push('Delete');
item.Permission = permissions.join();
}
$scope.init = function () {
$scope.object.id = Utils.getParameterByName("objectid");
$scope.object.type = Utils.getParameterByName("type");
$scope.getPermissions().then(function () {
if ($scope.hasPermission('None', $scope.object.type)) {
window.location = PAGE_403;
}
});
getObject();
loadAllPrincipals();
getObjectPermission();
}
$scope.addPrincipal = function () {
var grantedProfiles = _.map($scope.object.permission.ProfilePermissions, 'Profile');
var notSelectedProfiles = _.differenceBy($scope.profiles, grantedProfiles, 'Id');
var grantedUsers = _.map($scope.object.permission.UserPermissions, 'User');
var notSelectedUsers = _.differenceBy($scope.users, grantedUsers, 'Id');
var principals = [];
_.each(notSelectedProfiles,
function (item) {
principals.push({
data: item,
type: 'Profile',
checked: false
});
});
_.each(notSelectedUsers,
function (item) {
principals.push({
data: item,
type: 'User',
checked: false
});
});
var modal = $uibModal.open({
templateUrl: 'permissionAddEdit.html',
controller: 'permissionAddEditCtrl',
resolve: {
principals: function () { return principals; },
}
});
modal.result.then(function (selectedPrincipals) {
_.each(selectedPrincipals,
function (item) {
var permissionItem;
if (item.type === 'Profile') {
permissionItem = {
Profile: item.data,
Type: $scope.object.type,
ObjectId: $scope.object.id,
Permission: 'Read'
};
checkPermissionFlag(permissionItem);
$scope.object.permission.ProfilePermissions.push(permissionItem);
} else {
permissionItem = {
User: item.data,
Type: $scope.object.type,
ObjectId: $scope.object.id,
Permission: 'Read'
};
checkPermissionFlag(permissionItem);
$scope.object.permission.UserPermissions.push(permissionItem);
}
});
});
}
$scope.cleanup = function () {
$scope.permissionChanged = true;
$scope.object.permission.ProfilePermissions = [];
_.remove($scope.object.permission.UserPermissions,
function (item) {
return item.User.Id !== $scope.object.data.Owner.Id;
});
}
$scope.inherit = function () {
$scope.permissionChanged = true;
$xhttp.get(WEBAPI_ENDPOINT + '/api/permission/object/getpermissions?objectId=' + $scope.object.parentId).then(
function (response) {
var parentPermission = response.data;
$scope.object.permission.ProfilePermissions = parentPermission.ProfilePermissions;
_.each($scope.object.permission.ProfilePermissions,
function (item) {
checkPermissionFlag(item);
});
_.remove($scope.object.permission.UserPermissions,
function (item) {
return item.User.Id !== $scope.object.data.Owner.Id;
});
_.each(parentPermission.UserPermissions,
function (item) {
if (item.User.Id !== $scope.object.data.Owner.Id) {
checkPermissionFlag(item);
$scope.object.permissions.UserPermissions.push(item);
}
});
});
}
$scope.savPermission = function () {
$scope.object.permission.Type = $scope.object.type;
$xhttp.post(WEBAPI_ENDPOINT + '/api/permission/object/setpermissions', $scope.object.permission).then(function (response) {
$scope.alertSvc.addSuccess('Update permissions successfully');
$scope.init();
});
}
});
module.controller('permissionAddEditCtrl', function ($scope, $uibModalInstance, principals) {
$scope.principals = [];
$scope.init = function () {
$scope.principals = principals;
}
$scope.init();
$scope.ok = function () {
var selected = _.filter($scope.principals, 'checked');
$uibModalInstance.close(selected);
}
$scope.cancel = function () {
$uibModalInstance.dismiss('cancel');
}
});
|
const path = require('path');
const gulp = require('gulp');
const postcss = require('gulp-postcss');
const sourcemaps = require('gulp-sourcemaps');
const sass = require('gulp-dart-sass');
const cssnano = require('cssnano');
const autoprefixer = require('autoprefixer');
const r = path.resolve.bind(null, __dirname);
// Pull in our settings.
const { karmabunny } = require('./package.json');
karmabunny.src = karmabunny.src.map(path => r(path));
karmabunny.target = r(karmabunny.target);
let watched = [];
// A lovely little hack to 'discover' all the watched files.
const _render = sass.compiler.renderSync;
sass.compiler.renderSync = (function(opts) {
const result = _render(opts);
watched = result.stats.includedFiles.slice(0);
return result;
});
function build(cb) {
gulp.src(karmabunny.src)
.pipe(sourcemaps.init())
.pipe(
sass.sync({
sourceMap: true,
})
.on('error', cb)
)
.pipe(
postcss([
autoprefixer(),
cssnano({
preset: 'default',
}),
])
)
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest(karmabunny.target))
.on('end', cb);
}
function watch() {
return gulp.watch(watched, {
ignoreInitial: true,
events: 'all',
delay: 300,
}, build);
}
function notify() {
const notifier = require('node-notifier');
function onError(error) {
if (!error) return;
notifier.notify({
title: 'Gulp error',
message: error.message,
})
}
return gulp.watch(watched, {
ignoreInitial: true,
events: 'all',
delay: 300,
}, () => build(onError));
}
exports.default = build;
exports.build = build;
exports.watch = gulp.series(build, watch);
exports.notify = gulp.series(build, notify);
|
goog.provide('olcs.VectorSynchronizer');
goog.require('goog.events');
goog.require('ol.layer.Vector');
goog.require('olcs.AbstractSynchronizer');
goog.require('olcs.core');
goog.require('olcs.core.OlLayerPrimitive');
/**
* Unidirectionally synchronize OpenLayers vector layers to Cesium.
* @param {!ol.Map} map
* @param {!Cesium.Scene} scene
* @constructor
* @extends {olcs.AbstractSynchronizer.<olcs.core.OlLayerPrimitive>}
* @api
*/
olcs.VectorSynchronizer = function(map, scene) {
/**
* @type {!Cesium.PrimitiveCollection}
* @private
*/
this.csAllPrimitives_ = new Cesium.PrimitiveCollection();
scene.primitives.add(this.csAllPrimitives_);
this.csAllPrimitives_.destroyPrimitives = false;
// Initialize core library
olcs.core.glAliasedLineWidthRange = scene.maximumAliasedLineWidth;
goog.base(this, map, scene);
};
goog.inherits(olcs.VectorSynchronizer, olcs.AbstractSynchronizer);
/**
* @inheritDoc
*/
olcs.VectorSynchronizer.prototype.addCesiumObject = function(object) {
goog.asserts.assert(!goog.isNull(object));
this.csAllPrimitives_.add(object);
};
/**
* @inheritDoc
*/
olcs.VectorSynchronizer.prototype.destroyCesiumObject = function(object) {
object.destroy();
};
/**
* @inheritDoc
*/
olcs.VectorSynchronizer.prototype.removeAllCesiumObjects = function(destroy) {
this.csAllPrimitives_.destroyPrimitives = destroy;
this.csAllPrimitives_.removeAll();
this.csAllPrimitives_.destroyPrimitives = false;
};
/**
* @inheritDoc
*/
olcs.VectorSynchronizer.prototype.createSingleCounterpart = function(olLayer) {
if (!(olLayer instanceof ol.layer.Vector)) {
return null;
}
goog.asserts.assertInstanceof(olLayer, ol.layer.Vector);
goog.asserts.assert(!goog.isNull(this.view));
var view = this.view;
var source = olLayer.getSource();
var featurePrimitiveMap = {};
var csPrimitives = olcs.core.olVectorLayerToCesium(olLayer, view,
featurePrimitiveMap);
olLayer.on('change:visible', function(e) {
csPrimitives.show = olLayer.getVisible();
});
var onAddFeature = function(feature) {
goog.asserts.assertInstanceof(olLayer, ol.layer.Vector);
var prim = csPrimitives.convert(olLayer, view, feature);
if (prim) {
featurePrimitiveMap[goog.getUid(feature)] = prim;
csPrimitives.add(prim);
}
};
var onRemoveFeature = function(feature) {
var geometry = feature.getGeometry();
var id = goog.getUid(feature);
if (goog.isDefAndNotNull(geometry) && geometry.getType() == 'Point') {
var context = csPrimitives.context;
var bbs = context.billboards;
var bb = context.featureToCesiumMap[id];
delete context.featureToCesiumMap[id];
if (goog.isDefAndNotNull(bb)) {
goog.asserts.assertInstanceof(bb, Cesium.Billboard);
bbs.remove(bb);
}
}
var csPrimitive = featurePrimitiveMap[id];
delete featurePrimitiveMap[id];
if (goog.isDefAndNotNull(csPrimitive)) {
csPrimitives.remove(csPrimitive);
}
};
source.on('addfeature', function(e) {
goog.asserts.assert(goog.isDefAndNotNull(e.feature));
onAddFeature(e.feature);
}, this);
source.on('removefeature', function(e) {
goog.asserts.assert(goog.isDefAndNotNull(e.feature));
onRemoveFeature(e.feature);
}, this);
source.on('changefeature', function(e) {
var feature = e.feature;
goog.asserts.assert(goog.isDefAndNotNull(feature));
onRemoveFeature(feature);
onAddFeature(feature);
}, this);
return csPrimitives;
};
|
import { faFileImage, faMicrophone, faPaperPlane, faPlus } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import React, { useRef, useState } from "react";
import { getImageTags } from "../../async/getImageTags";
import { addMessage } from "../../dispatches/addMessage";
import { addOptions } from "../../dispatches/addOptions";
import { setLoading } from "../../dispatches/setIsLoading";
function Input() {
const read = (event) => {
return URL.createObjectURL(event.target.files[0]);
};
const add = () => {
if (!input) return;
addMessage({
isSender: true,
content: input,
});
setinput("");
};
const [input, setinput] = useState("");
const [expand, setexpand] = useState(false)
const ref = useRef();
return (
<div className="flex justify-around z-20 bottom-0 w-full items-center p-3 border-t-2">
<div className="flex py-1 overflow-hidden" style={{maxWidth: !expand ? 25 : 75, transition:".3s ease all"}}>
{/* PLUS */}
<div className="mr-2" style={{transform: expand ? "rotate(45deg)" : undefined, transition: ".3s ease all"}} onClick={()=>setexpand(!expand)}>
<FontAwesomeIcon
icon={faPlus}
className="text-2xl cursor-pointer text-blue-600"
/>
</div>
{/* FILE */}
<div className="mr-3">
<FontAwesomeIcon
icon={faFileImage}
className="text-2xl cursor-pointer text-blue-600"
onClick={() => ref.current.click()}
/>
<input
ref={ref}
onChange={async (e) => {
setLoading({ value: true });
addOptions({
options: await getImageTags({ image: e.target.files[0] }),
});
addMessage({
isSender: true,
image: read(e),
});
setLoading({ value: false });
}}
type="file"
style={{ display: "none" }}
/>
</div>
{/* VOCAL */}
<div>
<FontAwesomeIcon
icon={faMicrophone}
className="text-2xl cursor-pointer text-blue-600"
/>
</div>
</div>
<input
type="text"
placeholder="Your message..."
className="border-0 focus:outline-none text-sm"
value={input}
onChange={(e) => setinput(e.target.value)}
></input>
<button
onClick={() => {
add();
if (window.nextInputSubmit) {
window.nextInputSubmit(input);
window.nextInputSubmit = undefined;
}
}}
type="submit"
className="cursor-pointer text-sm font-semibold"
>
<div className="p-1">
<FontAwesomeIcon
icon={faPaperPlane}
className="text-lg text-blue-600"
/>
</div>
</button>
</div>
);
}
export default Input;
|
import React from 'react'
import { css } from 'theme-ui'
import { Link } from 'theme-ui'
import { FaLink } from 'react-icons/fa'
const styles = {
heading: {
a: {
visibility: `hidden`
},
':hover a': {
visibility: `visible`
},
pointerEvents: `painted`
},
link: {
fontSize: 2,
ml: -3,
mr: -1,
pr: 1
}
}
const heading = Tag => props => (
<Tag {...props} css={css(styles.heading)}>
<Link href={`#${props.id}`} variant='normal' sx={styles.link}>
<FaLink />
</Link>
{props.children}
</Tag>
)
export default {
h1: heading(`h1`),
h2: heading(`h2`),
h3: heading(`h3`),
h4: heading(`h4`),
h5: heading(`h5`),
h6: heading(`h6`)
}
|
app.view.show.show(sorceData.state);
app.scrollAdd($("#index_page .warp"));
|
var searchData=
[
['moderegister',['ModeRegister',['../_h_m_c5883_l_8h.html#a588e30fd18c31816cde04b8e3b3adf15',1,'HMC5883L.h']]]
];
|
import React, { useState } from 'react';
import styled from '@emotion/styled';
import ReactMapGL, { Marker } from 'react-map-gl';
import { FaMapMarkerAlt } from 'react-icons/fa';
import { CustomH2 } from '../home/HomeStyling';
const Icon = styled(FaMapMarkerAlt)`
color: ${props => props.theme.colors.primary};
font-size: 3rem;
cursor: pointer;
&:hover {
font-size: 4rem;
}
`;
const Map1 = ({
latitude,
longitude,
title,
mapStyle,
height,
width,
location,
zoom,
}) => {
const [viewport, setViewport] = useState({
latitude,
longitude,
width: width,
height: height,
zoom,
});
return (
<div>
{title && (
<>
<CustomH2>{title}</CustomH2>
</>
)}
<ReactMapGL
{...viewport}
mapboxApiAccessToken={process.env.GATSBY_MAPBOX_API_TOKEN}
mapStyle={mapStyle}
scrollZoom={false}
onViewportChange={viewport => {
setViewport(viewport);
}}
>
<Marker
key={location.title}
latitude={location.primaryLocation.lat}
longitude={location.primaryLocation.lon}
>
<Icon />
</Marker>
</ReactMapGL>
</div>
);
};
export default Map1;
|
const bodyParser = require('body-parser')
var urlencodedParser = bodyParser.urlencoded({ extended: false })
const Product = require('../model/Products.js');
const Task=require("../model/Task.js");
const User = require('../model/User.js');
const Role = require('../model/User_Role');
exports.print= (req, res) => {
res.render('order_worker')
}
exports.load_product=async (req, res) => {
const { id_product } = req.body
console.log("@@@@@@@@^"+id_product)
//const user_role1= await User_Role.create({id_role:1,id_user:2})
//user_role1.addTask(task1, { through: { selfGranted: false } });
const role1=await Role.create({id_role:2,id_user:2})
//const role2=await Role.create({id_role:1,id_user:1})
const task1= await Task.create({id_product:1,name:"Clear window",finish:true})
const task2= await Task.create({id_product:1,name:"paint with a primer",finish:false})
await role1.addTask(task1);
await role1.addTask(task2);
Role.findAll({where:{id_role:2}, include: Task}).then(data=>{
console.log("3333"+JSON.stringify(data))
})
Product.findOne({ where: { id_product: id_product }}).then(data=>{
res.render('order_worker',{title:"product",id_product:data.id_product,model:data.model,id_order:data.id_order})
})
}
|
// JavaScript - Node v8.1.3
any = (arr, fun) => arr.some(fun);
|
import React from "react"
import '../styles/global.css'
export default() => (
<footer>
<div class="container">
<div class="col-3">
<p>Amanda Chesin Photography</p>
</div>
<div class="col-1">
<ul class="unstyled-list">
<li><strong>Instagram</strong></li>
</ul>
</div>
<div class="col-1">
<ul class="unstyled-list">
<li><strong>Drop a Line</strong></li>
</ul>
</div>
</div>
</footer>
)
|
import React, { useState, useEffect } from "react";
import Loading from "./Loading";
import Products from "./Products";
// ATTENTION!!!!!!!!!!
// I SWITCHED TO PERMANENT DOMAIN
const url =
"https://my-json-server.typicode.com/keerthana-karthik/ecommerce/salwars";
function App() {
const [loading, setLoading] = useState(false);
const [products, setProducts] = useState([]);
const removeProduct = (id) => {
setProducts((products) => {
const filteredProducts = products.filter((product) => {
return id !== product.id;
});
return filteredProducts;
});
};
const fetchProducts = async () => {
setLoading(true);
try {
const response = await fetch(url);
const productsResponse = await response.json();
console.log(productsResponse);
setProducts((products) => {
return productsResponse;
});
setLoading(false);
} catch (error) {
setLoading(false);
console.log(error);
}
};
useEffect(() => {
fetchProducts();
}, []);
if (loading) {
return (
<main>
<Loading />
</main>
);
}
return (
<main>
<Products removeProduct={removeProduct} products={products} />
<button className="btn" onClick={() => fetchProducts()}>
refresh
</button>
</main>
);
}
export default App;
|
var unirest = require('unirest');
var changeCase = require('change-case')
const today = require('../tokens/today.json');
exports.run = function(client, message, args) {
var date = new Date();
var month = date.getMonth();
var fix = 1;
var monthfix = month + 1;
var day = date.getDay();
unirest.get("https://numbersapi.p.mashape.com/" + month + "/" + day + "/date?fragment=true&json=true")
.header("X-Mashape-Key", today.token)
.header("Accept", "text/plain")
.end(function(result) {
// For debug Only
//console.log(result.status, result.headers, result.body);
console.log("Running command for Today | Params: Day: " + day + " " + "Month: " + monthfix);
var text = changeCase.upperCaseFirst(result.body["text"])
message.channel.send(text + "." + "\n\nDate: " + monthfix + "/" + day + "/" + result.body["year"]);
});
}
|
// Initialize Firebase
const firebaseConfig = {
apiKey: "AIzaSyDqfQKweo_zzigcPmpAnNSigI2k4vXBB8o",
authDomain: "train-scheduler-ff3ee.firebaseapp.com",
databaseURL: "https://train-scheduler-ff3ee.firebaseio.com",
projectId: "train-scheduler-ff3ee",
storageBucket: "",
messagingSenderId: "464761733629",
appId: "1:464761733629:web:ad60a212bcd0d6e2"
};
firebase.initializeApp(firebaseConfig);
const database = firebase.database();
function calculateMinutesAway(trainFreq, trainStart) {
// Current Time
let currentTime = moment();
let trainStartTime = moment(trainStart, "HH:mm");
if (currentTime.isBefore(trainStartTime)){
return trainStartTime.diff(currentTime, "minutes");
}
// First Time (pushed back 1 year to make sure it comes before current time)
let startTimeConverted = trainStartTime.subtract(1, "years");
// Difference between the times
let diffTime = currentTime.diff(startTimeConverted, "minutes");
// Time apart (remainder)
let tRemainder = diffTime % trainFreq;
// Minute Until Train
let tMinutesTillTrain = trainFreq - tRemainder;
return tMinutesTillTrain;
}
// Button for adding train
$("#add-train-btn").on("click", function (event) {
event.preventDefault();
// Grabs user input
const trainName = $("#train-name-input").val().trim();
const trainDest = $("#destination-input").val().trim();
const trainStart = moment($("#start-input").val().trim(), "HH:mm").format("HH:mm");
const trainFreq = $("#frequency-input").val().trim();
// Creates local "temporary" object for holding train data
const newTrain = {
name: trainName,
destination: trainDest,
start: trainStart,
frequency: trainFreq
};
// Uploads train data to the database
database.ref().push(newTrain);
alert("Train successfully added");
// Clears all of the text-boxes
$("#train-name-input").val("");
$("#destination-input").val("");
$("#start-input").val("");
$("#frequency-input").val("");
});
database.ref().on("child_added", function (childSnapshot) {
// Store everything into a variable.
const trainName = childSnapshot.val().name;
const trainDest = childSnapshot.val().destination;
const trainStart = childSnapshot.val().start;
const trainFreq = childSnapshot.val().frequency;
// Create the new row
let newRow = $("<tr>").append(
$("<td>").text(trainName),
$("<td>").text(trainDest),
$("<td>").text(trainStart),
$("<td>").text(trainFreq),
$("<td>").text(calculateMinutesAway(trainFreq, trainStart))
);
// Append the new row to the table
$("#train-table > tbody").append(newRow);
});
|
import React from "react";
import "./Form.css";
const Form = props =>
<div className="container" id="form">
<div className="card">
<div className="card-header text-center">
<h5>Search</h5>
</div>
<div className="card-body">
<form>
<div className="form-group">
<label>Topic</label>
<input
type="text"
className="form-control"
name="topic"
onChange ={props.handleInputChange}
required
/>
</div>
<div className="form-group">
<label>Start Year</label>
<input
type="number"
value={props.startYear}
className="form-control"
name="startYear"
onChange={props.handleInputChange}
/>
</div>
<div className="form-group">
<label>End Year</label>
<input
className="form-control"
type="number"
name="endYear"
value={props.startYear}
onChange={props.handleInputChange}
/>
</div>
<input
className="btn btn-primary"
id="submit-btn"
type="submit"
value="Search"
onClick={props.handleFormSubmit}
/>
</form>
<br/>
</div>
</div>
</div>
export default Form;
|
const fs = require('fs');
let pkgJSON = require('./package.json');
let [argv1] = process.argv.slice(2);
let pkgVersion = pkgJSON.version.split('.');
if (argv1 === '--l') {
++pkgVersion[0]
}
else if (argv1 === '--m') {
++pkgVersion[1];
}
else {
++pkgVersion[2];
}
pkgJSON.version = pkgVersion.join('.');
fs.writeFileSync('./package.json', JSON.stringify(pkgJSON, null, 2));
|
import { SNComponent } from "@socialNetwork";
class HeaderComponent extends SNComponent {
constructor(config) {
super(config);
}
}
export const header = new HeaderComponent({
selector: "app-header",
template: ``
});
|
/**
*
* Sticky Box
*
* @author Predrag Krstic
* @version 1.0
* @requires jQuery.dimensions plugin (jQuery.dimensions is part of jQuery core
* since 1.2.3 version)
*
* Parameters:
* @param heightElement -
* (selector) dom element that wraps details
* @param options.marginTop -
* (optional) sticky element distance from window top
*
* sticky element must be wraped with something like: <div style="height:100%;
* position:relative;">
*
* @example of usage:
*
* HTML <div id="content"> <div class="column1">...</div> <div class="column2">
* <div id="stickyBox" data-stickyboxbounds="#content"> STICKY BOX CONTENT
* </div> </div> </div>
*
* CALL $('#stickyBox').stickyBox({bounds: '#content', marginTop: 10 });
*
*/
(function($) {
$.fn.stickyBox = function(options) {
var defaults = {
bounds : '.stickyBoxBounds',
marginTop : 0
};
return this.each(function() {
var sticky = this;
var stickyHeight = $(sticky).height();
var o = $.extend(defaults, options);
o.bounds = $(sticky).data('stickyboxbounds') || o.bounds;
o.marginTop = $(sticky).data('stickyboxmargintop') || o.marginTop;
var bounds = $(sticky).parents(o.bounds).first();
$(sticky).parent().css({
position : 'relative',
height : '100%'
});
$(sticky).css({
position : 'absolute'
});
var stickyFormPos = function() {
var boundsW = $(bounds).width();
var top = $(bounds).offset().top;
var bottom = $(bounds).height() + top;
var left = $(sticky).parent().offset().left;
var stickyCurrH = $(sticky).height();
var stickyCurrHTemp = stickyCurrH;
var posTop = $(window).scrollTop();
var posLeft = $(window).scrollLeft();
var winW = $(window).width();
var winH = $(window).height();
if (stickyCurrH > stickyHeight) {
stickyCurrH = stickyHeight;
}
if (top - o.marginTop > posTop || stickyCurrH + o.marginTop > winH) {
$(sticky).css({
"position" : "static",
"left" : null,
"top" : null
});
} else {
var stickyBottom = posTop + stickyCurrH + o.marginTop;
if (stickyCurrHTemp > stickyHeight) {
stickyBottom = stickyBottom + (stickyCurrHTemp - stickyHeight);
}
var d = o.marginTop;
if (stickyBottom > bottom) {
d = o.marginTop + (bottom - stickyBottom);
}
var l = 'auto';
if (boundsW > winW) {
l = left - posLeft;
}
$(sticky).css({
"position" : "fixed",
"top" : d + "px",
"left" : l
});
}
};
$(window).on('scroll resize', stickyFormPos);
});
};
})(jQuery);
|
/*
There is an array of strings.
All strings contains similar letters except one.
Try to find it!
findUniq([ 'Aa', 'aaa', 'aaaaa', 'BbBb', 'Aaaa', 'AaAaAa', 'a' ]) === 'BbBb'
findUniq([ 'abc', 'acb', 'bac', 'foo', 'bca', 'cab', 'cba' ]) === 'foo'
Strings may contain spaces.
Spaces is not significant, only non-spaces symbols matters.
E.g. string that contains only spaces is like empty string.
It’s guaranteed that array contains more than 3 strings.
*/
function findUniq(arr) {
let obj = {};
let letters = arr.join('');
for (let i = 0; i < letters.length; i++) {
let letter = letters[i].toLowerCase();
obj[letter] = obj[letter] + 1 || 1;
}
let minAmount = Infinity;
let targetLetter;
for (let key in obj) {
if (obj[key] < minAmount) {
minAmount = obj[key];
targetLetter = key;
}
}
return arr.find(str => str.includes(targetLetter) || str.includes(targetLetter.toUpperCase()));
}
|
import React from 'react';
import { styled } from 'styletron-react';
const Container = styled('div', {
padding: '100px',
});
const App = ({ children }) => (
<Container>
{children}
</Container>
);
export default App;
|
"use strict";
const methods_host = "https://api.vk.com/method/";
|
import { Bar } from 'vue-chartjs'
import chartBuilder from './chartBuilder'
export default chartBuilder(Bar)
|
var apexTimeLineControllers = angular.module('apexTimelineControllers', []);
apexTimeLineControllers.controller('ApexTimeLineController',
['$scope','$window','$http','ForceAuthService',
function ($scope,$window,$http,ForceAuthService) {
$scope.init = function(){
$scope.$apply($scope.initializeData);
}
$scope.initializeData = function () {
$scope.authorized=true;
$scope.sessionToken = ForceAuthService.getSessionToken();
$scope.minTimeToRun=100;
$http({ method: 'POST',
url:'/logs',
data:{
'sessionId':$scope.sessionToken.access_token,
'instanceUrl':$scope.sessionToken.instance_url
},
headers:{
'Accept':'application/json'
}
}).success(function(data, status) {
if(data.records){
$scope.logRecords=data.records;
$http({ method: 'POST',
url:'/userinfo',
data:{
'sessionId':$scope.sessionToken.access_token,
'idUrl':$scope.sessionToken.id
},
headers:{
'Accept':'application/json'
}
}).success(function(data, status) {
$scope.userInfo=data;
}).error(function(data, status) {
});
}else{
$scope.authorized=false;
ForceAuthService.resetSessionToken();
return;
}
}).error(function(data, status) {
$scope.authorized=false;
ForceAuthService.resetSessionToken();
});
}
$scope.initiateOAuth = function (){
ForceAuthService.ready($scope.config);
}
$scope.oauthCallback=function(popupWindow,tokenHash){
popupWindow.close();
ForceAuthService.oauthCallback(tokenHash);
$scope.init();
}
//Register the Oauth callback as a function on the main window
$window.oauthCallback=$scope.oauthCallback;
$scope.config= CONFIG ;
try{
$scope.sessionToken = ForceAuthService.getSessionToken();
$scope.authorized=true;
$scope.initializeData();
}catch(err){
$scope.authorized=false;
}
}
]);
|
function hello(name){
if (name){
return "Hello, " + name.substring(0,1).toUpperCase() + name.substring(1).toLowerCase() + '!';
} else {
return "Hello, World!";
}
}
refactored
const hello = name => name ? "Hello, " + name.substring(0,1).toUpperCase() + name.substring(1).toLowerCase() + '!' : "Hello, World!";
|
import React, { Component } from 'react';
import d3 from 'd3';
const width = 420,
height = 420,
radius = width/2;
const data = [
{label: "Dogs trust", value:45, class: 'spin_1'},
{label: "CASJ", value:45, class: 'spin_2'},
{label: "SOS", value:45, class: 'spin_3'},
{label: "RSCPA", value:45, class: 'spin_4'},
{label: "Hope for paws", value:45, class: 'spin_5'},
{label: "ASPCA", value:45, class: 'spin_6'},
{label: "Mercy for Animals", value:45, class: 'spin_7'},
{label: "PETA", value:45, class: 'spin_8'}
];
let colors = [
'#FFE773',
'#FFBD7B',
'#FFCED6',
'#F6849C',
'#9AECE0',
'#ADB5F7',
'#D6E75A',
'#6ee527'
];
let pie = d3.layout.pie().value(function(d){return d.value;});
let arc = d3.svg.arc().outerRadius(radius);
export default class Wheel extends Component {
constructor(props){
super(props)
}
shouldComponentUpdate() {
return false;
}
componentDidMount(){
this.drawSvgContainer();
this.spin = false;
}
render() {
return (
<div className="wheel-wrapper" id="wheel-wrapper" ref="wheel"/>
);
}
spinWheel = () => {
if(!this.spin){
this.spin = true;
let draw = Math.floor(Math.random() * 8);
this.result = data[draw];
d3.select('#wheel-wrapper').attr('class', 'wheel-wrapper ' + this.result.class);
}
setTimeout(() => {
this.props.onSpinEnd(this.result.label);
}, 4000)
};
drawSvgContainer = () => {
this.svg = d3.select('#wheel-wrapper')
.append("svg")
.data([data])
.attr("width", width)
.attr("height", height)
.append("g")
.attr("class", "wheel-group")
.attr("transform", "translate(210,210)")
.on('click', this.spinWheel);
this.arcs = this.svg.selectAll("g.slice").data(pie)
.enter()
.append("g")
.attr("class", "slice");
this.arcs.append("path")
.attr("fill", function(d, i){return colors[i];})
.attr("d", function (d) {return arc(d);});
this.arcs.append("text")
.attr("transform", function(d){
d.innerRadius = 20;
d.outerRadius = radius;
return "translate(" + arc.centroid(d) + ")";}
)
.attr("text-anchor", "middle")
.style({
"font-size": "12px",
"fill": "white"
})
.text( function(d, i) {return data[i].label;});
this.arcs.append("circle")
.attr("transform", function(d, i){
d.innerRadius = 200;
d.outerRadius = radius;
return "translate(" + arc.centroid(d) + ")";}
)
.attr("r", "20")
.attr("fill", function(d, i){return colors[i]});
this.arcs.append("circle")
.attr("transform", function(d, i){
d.innerRadius = 202;
d.outerRadius = radius;
return "translate(" + arc.centroid(d) + ")";}
)
.attr("r", "15")
.attr("fill", "#FFFFFF");
}
}
|
// U3.W9:JQuery
// I worked on this challenge [by myself, with: ].
// This challenge took me [#] hours.
$(document).ready(function(){
//RELEASE 0:
//link the image
//RELEASE 1:
//Link this script and the jQuery library to the jQuery_example.html file and analyze what this code does.
$('body').css({'background-color': 'pink'});
//RELEASE 2:
//Add code here to select elements of the DOM
bodyElement = $('body');
title = $('title');
h1 = $('h1:first');
mascot = $('.mascot');
fade = $('#fade')
menuHover = $("#menu-hover")
secretMenu = $("#secret-menu")
//mascotHone = mascot.first("h1");
//RELEASE 3:
// Add code here to modify the css and html of DOM elements
title.html("J QUERY FTW")
h1.css({"fontSize": "3em"});
h1.css({"border": "5px dotted plum"});
//h1.css({"visibility": "hidden"})
fade.css({"padding": "50px" })
fade.css({"border": "5px solid aqua"})
fade.css({"background-color": "plum"})
mascot.css({"margin-left": "200px"});
mascot.html("<h1>Firey Skippers</h1> <img src='./dbc_logo.png'>");
secretMenu.css({"display": "none"})
secretMenu.css({"background-color": "yellow"})
secretMenu.css({"padding": "200px"})
//RELEASE 4: Event Listener
// Add the code for the event listener here
$('img').on('mouseover', function(e){
e.preventDefault()
$(this).attr('src', 'http://www.jeffpippen.com/butterflies/fieryskipper081004-6948brunswick.coz.jpg')
})
$('img').on('mouseleave', function(leave){
$(this).attr('src', './dbc_logo.png')
})
//RELEASE 5: Experiment on your own
h1.on('mouseover', function(e){
$(this).animate({height: "110px"});
})
h1.on('mouseleave', function(leave){
$(this).animate({height: "75px"});
})
fade.on('mouseover', function(){
$(this).fadeOut("slow");
})
menuHover.click(function(){
secretMenu.slideDown("slow")
})
}) // end of the document.ready function: do not remove or write DOM manipulation below this.
// REFLECTION
/*
What is jQuery?
it is a JS library built with vanilla javascript, meant to make it easier for developers to implement JS features
into HTML documents. It adds convenience and readability. It helps implement rich JS features into HTML
ocuments without having to write the complex JS.
What does jQuery do for you?
it provides easy "shortcuts" to common JS tasks such as grabbing onto various elements in the DOM
tree and implementing effects.
What did you learn about the DOM while working on this challenge?
jquery gives all sorts of options like first, last, nth of etc. that make it easy to
traverse the DOM without having to create JS loops.
|
import store from "../../store";
class TableOfCheckboxes {
constructor(question) {
this.id = question.id;
this.type = "tableOfCheckboxes";
if (!question.horizontalValues) {
this.horizontalValues = [];
} else {
this.horizontalValues = question.horizontalValues;
}
if (!question.verticalValues) {
this.verticalValues = [];
} else {
this.verticalValues = question.verticalValues;
}
// if (!question.items) {
// this.items = [];
// } else {
// this.items = question.items;
// }
if (!question.page) {
this.page = 0;
} else {
this.page = question.page;
}
if (!question.title) {
this.title = null;
} else {
this.title = question.title;
}
if (!question.description) {
this.description = null;
} else {
this.description = question.description;
}
if (!question.error) {
this.error = false;
} else {
this.error = question.error;
}
if (!question.optional) {
this.optional = false;
} else {
this.optional = question.optional;
}
if (!question.editing) {
this.editing = true;
} else {
this.editing = question.editing;
}
if (!question.pageBreak) {
this.pageBreak = false;
} else {
this.pageBreak = question.pageBreak;
}
if (!question.style) {
this.style = {
titleFontSize: null
};
} else {
this.style = question.style;
}
}
set addHorizontalValue(v) {
this.horizontalValues.push(v);
this.createItems();
}
set removeHorizontalValue(v) {
this.horizontalValues.remove(v);
this.createItems();
}
set addVerticalValue(v) {
this.verticalValues.push(v);
this.createItems();
}
set removeVerticalValue(v) {
this.verticalValues.remove(v);
this.createItems();
}
get horizontal() {
return this.horizontalValues;
}
get vertical() {
return this.verticalValues;
}
// get items() {
// return this.items;
// }
// set items(i) {
// this.items = [];
// }
createItems() {
const items = [];
if (this.horizontalValues && this.verticalValues) {
this.verticalValues.forEach(vv => {
const answers = [];
this.horizontalValues.forEach(hv => {
answers.push({
id: `${hv.id}_${vv.id}`,
text: hv.text,
selected: hv.selected
});
});
items.push({ id: vv.id, title: vv.title, answers });
});
}
// console.log(items);
this.items = items;
// return items;
}
}
class PageHandler {
constructor(q) {
this.questionnaire = q;
this.totalPages = 0;
this.pagesQueue = null;
this.questionsQueue = null;
this.currentPage = 0;
this.deactivatedPages = [];
this.deactivatedQuestions = [];
this.showSubmit = false;
this.showNext = true;
this.showPrevious = false;
this.init();
}
labels() {
return `${this.currentPage + 1} / ${Object.keys(this.pagesQueue).length -
this.deactivatedPages.length}`;
}
init() {
this.findTotalPages();
this.toggleSections();
this.toggleQuestions();
}
set page(v) {
this.currentPage = v;
}
get page() {
return this.currentPage;
}
get buttons() {
const buttons = {
next: this.showNext,
previous: this.showPrevious,
submit: this.showSubmit
};
return buttons;
}
findTotalPages() {
let pageCount = 0;
this.questionnaire.questions.forEach(q => {
if (q.page >= pageCount) {
pageCount = q.page;
}
});
this.totalPages = pageCount - this.deactivatedPages.length;
if (this.totalPages === 0) {
this.showNext = false;
this.showSubmit = true;
}
}
pageVisibility(v) {
// console.log('page visibility for :: ', v);
return this.pagesQueue[v].visibility;
}
goToPreviousPage() {
// console.log('going to previous page');
for (let i = this.currentPage - 1; i >= 0; i -= 1) {
// console.log('checking page:: ', i, this.pagesQueue[i]);
if (i === 0) {
// console.log('i = first page');
this.showSubmit = false;
this.showNext = true;
this.showPrevious = false;
}
if (i > 0 && i < Object.keys(this.pagesQueue).length - 1) {
// console.log('i smaller than last page');
this.showSubmit = false;
this.showNext = true;
this.showPrevious = true;
}
if (this.pagesQueue[i].visibility) {
this.currentPage = i;
break;
}
}
}
goToNextPage() {
for (
let i = this.currentPage + 1;
i < Object.keys(this.pagesQueue).length;
i += 1
) {
if (i === Object.keys(this.pagesQueue).length - 1) {
this.showSubmit = true;
this.showNext = false;
}
if (i < Object.keys(this.pagesQueue).length - 1) {
this.showNext = true;
}
if (i > 0 && i <= Object.keys(this.pagesQueue).length) {
this.showPrevious = true;
}
// console.log(i);
if (this.pagesQueue[i].visibility) {
this.currentPage = i;
break;
}
}
}
toggleQuestions() {
// console.log('toggling questions');
const questionsToAdd = [];
const questionsToRemove = [];
this.deactivatedQuestions = [];
this.questionnaire.questions.forEach(question => {
// for each question check if has value
if (
question.type === "combobox" &&
(question.value || question.optional === true)
) {
// console.log('found combobox with value or optional:: ', question);
question.items.forEach(item => {
if (
item.activateQuestions &&
item.activateQuestions[0] !== "-" &&
question.value === item.value
) {
// console.log('found item active to remove page from deactivated');
item.activateQuestions.forEach(i => {
questionsToRemove.push(i.id);
});
}
if (
item.activateQuestions &&
item.activateQuestions[0] !== "-" &&
question.value !== item.value
) {
// console.log('found item active to add page to deactivated');
item.activateQuestions.forEach(i => {
questionsToAdd.push(i.id);
});
}
});
}
if (question.type === "combobox" && !question.value) {
question.items.forEach(item => {
if (item.activateQuestions && item.activateQuestions[0] !== "-") {
// console.log('found combobox without value:: ', question);
item.activateQuestions.forEach(i => {
questionsToAdd.push(i.id);
});
}
});
}
if (question.type === "repeatable") {
// console.log('REPEATABLE :: do not show these questions');
question.repeatQuestions.forEach(repeated => {
questionsToAdd.push(repeated.id);
// console.log('repeatable id to remove::', repeated.id);
});
console.log("removed repeatable questions");
question.questions.forEach(r => {
console.log("print questions in repeatable:: ", r);
if (r.questions) {
console.log(r.questions);
r.questions.forEach(rq => {
console.log("rq::", rq.type);
if (
rq.type === "combobox" &&
(rq.value || rq.optional === true)
) {
console.log("found combobox with value or optional:: ", rq);
rq.items.forEach(item => {
console.log(
"found this with questions::",
item.activateQuestions
);
// if (
// item.activateQuestions &&
// item.activateQuestions[0] !== '-' &&
// rq.value === item.value
// ) {
// console.log('found item active to remove question from deactivated');
// item.activateQuestions.forEach((i) => {
// // questionsToRemove.push(i.id);
// questionsToAdd.push(i.id);
// });
// }
if (
item.activateQuestions &&
item.activateQuestions[0] !== "-" &&
rq.value !== item.value
) {
item.activateQuestions.forEach(i => {
questionsToAdd.push(i.id);
});
}
});
}
if (rq.type === "combobox" && !rq.value) {
rq.items.forEach(item => {
if (
item.activateQuestions &&
item.activateQuestions[0] !== "-"
) {
// console.log('found combobox without value:: ', question);
item.activateQuestions.forEach(i => {
questionsToAdd.push(i.id);
});
}
});
}
});
}
});
}
});
// console.log('to add and to remove :: ', questionsToAdd, questionsToRemove);
const unique = questionsToAdd.filter(p => !questionsToRemove.includes(p));
// console.log('unique var:: ', unique, JSON.stringify(unique));
unique.forEach(u => {
this.deactivatedQuestions.push(u);
});
console.log("deactivated questions:: ", this.deactivatedQuestions);
store.commit("setDeactivatedQuestions", this.deactivatedQuestions);
// const questionsQueue = {};
// for (let index = 0; index <= this.totalPages; index += 1) {
// // console.log('deactivated questions:: ', this.deactivatedQuestions);
// if (this.deactivatedQuestions.includes(index)) {
// // console.log('false');
// questionsQueue[`${index}`] = { visibility: false };
// } else {
// // console.log('true');
// questionsQueue[`${index}`] = { visibility: true };
// }
// }
// this.questionsQueue = questionsQueue;
}
toggleSections() {
// console.log('toggling sections');
const pagesToAdd = [];
const pagesToRemove = [];
// console.log(selected);
this.deactivatedPages = [];
this.questionnaire.questions.forEach(question => {
// for each question check if has value
if (
question.type === "combobox" &&
(question.value || question.optional === true)
) {
// console.log('found combobox with value or optional:: ', question);
question.items.forEach(item => {
if (
item.activatePages &&
item.activatePages[0] !== "-" &&
question.value === item.value
) {
// console.log('found item active to remove page from deactivated');
item.activatePages.forEach(i => {
pagesToRemove.push(i);
});
}
if (
item.activatePages &&
item.activatePages[0] !== "-" &&
question.value !== item.value
) {
// console.log('found item active to add page to deactivated');
item.activatePages.forEach(i => {
pagesToAdd.push(i);
});
}
});
}
if (question.type === "combobox" && !question.value) {
question.items.forEach(item => {
if (item.activatePages && item.activatePages[0] !== "-") {
// console.log('found combobox without value:: ', question);
item.activatePages.forEach(i => {
pagesToAdd.push(i);
});
}
});
}
});
// console.log(pagesToAdd, pagesToRemove);
this.deactivatedPages = pagesToAdd.filter(p => !pagesToRemove.includes(p));
const pagesQueue = {};
for (let index = 0; index <= this.totalPages; index += 1) {
// console.log(this.deactivatedPages);
if (this.deactivatedPages.includes(index)) {
// console.log('false');
pagesQueue[`${index}`] = { visibility: false };
} else {
// console.log('true');
pagesQueue[`${index}`] = { visibility: true };
}
}
this.pagesQueue = pagesQueue;
}
}
class Questionnaire {
constructor(questionnaire) {
// console.log(questionnaire);
this.questions = questionnaire.questions;
this.properties = questionnaire.properties;
this.loaded = false;
this.init();
}
// get questions() {
// return this.questions;
// }
// set questions(qs) {
// this.questions = qs;
// }
// get properties() {
// return this.properties;
// }
init() {
this.loaded = true;
this.questions.forEach((q, index) => {
if (q.type === "tableOfCheckboxes") {
// console.log('found table and loading');
this.questions[index] = new TableOfCheckboxes(q);
// console.log(this.questions[index]);
}
});
}
}
export { TableOfCheckboxes, PageHandler, Questionnaire };
|
'use strict'
const mongoose = require('mongoose')
const Schema = mongoose.Schema
// const email_match = [/^\w+([\.-]?\w+)*@\w+([\.-]?\w)*(\.\w{2,3})+$/, 'Email Not validate']
/* const password_validation = {
validator: function (p) {
return this.password_confirmation === p
},
message: 'Las Contraseñas no son iguales'
}
*/
const CompanySchema = new Schema({
name: String, // nombre o razon social de la compañia
nit: {type: String, unique: true},
place_fundation: String,
email: { type: 'String', unique: true, lowercase: true, required: 'Email is obligatory' }, // correo con el usuario se registro total mente obligario y tiene que ser unico
tel: {type: Number, unique: true, required: 'Number Celphone is obligatory'}, // telefono obligatorio de la compañia
username: {type: 'String', maxlength: [50, 'Your username is extensive'], minlength: [3, 'Your username is short']}, // nombre de usuario con el que el se registrar
nickname: {type: 'String', maxlength: [20, 'Your username is extensive'], minlength: [3, 'Your username is short']},
password: {type: 'String', minlength: [7, 'Password must be greater than 7 characters']}, // contraseña con la cual el usuario se registrara
fundation: Date,
typeOfCompany: {type: String, enum: ['inmobiliaria', 'otros']}, // tipo de compañia
residence: String,
class_company: {type: String, enum: ['sede principal', 'sucursal']},
profile_img: {type: String, default: null}, // imagen de perfíl
banner: {type: String, default: null}, //imagen de portada
tel_home: Number, // telefono opcional
permision_level: {type: Number, default: 1}, // Crea un nivel de permiso al usuario para saber asi cuanto es el poder que tiene este en la app
singUpDate: {type: Date, default: Date.now()} // el dia que se unio al sistema
})
module.exports = mongoose.model('Company', CompanySchema)// crea un export para el modelo company y la base de datos
|
require('heatshrink').decompress(
atob(
'mEwxH+AClhCyoAYsIwuF4IwtF4Qxqw2GF4mG1YsqAAeF1eyAAIteFhAvHGLZbKR4guEGDItGwooBAweH6/X6wwGGKpVHE4PXGgWsAwQACGDIuFFoYvCw3WFwpjIFyuG2QkFRYQAJFwerwwvTwwmLGBeHDYQuoNwQcDFxlbCIWFRgwAJlb0HJohePdQoAKq0AlYJG1YfDRr+sgEAL4wABwxgNLy1WBZBgDF5uFLzYABwqQMBgWHdiBeKSByODJZReHBxaQMF4eyLznX2QvPLqBeM6/WcQYvZldbrYvN64jDF7rRNF7qPDGBqPPd54xDGBTvQPpowQ1YvLGAeHF54wDlYMIwwvPwovQGAIuJ6+FdxSQF1YwRABKONF4mGF7aONMEBeDRxQvFsOyFy+yP4gvL/1bSLXWRp7CdFwgvUCgKSS2QuUGAz0RdQguSGA+G1gtMLgguUeYoACwuH1aWE2QsBwpDGFyhiIAB2GFzAwUFrQxRLbYzOworBFkgA/AH4AuA=='
)
);
|
import React, {useState} from 'react';
const AddCommentsSection = ({articleName, setArticleInfo}) => {
const [userName, setUserName] = useState('');
const [commentText, setcommentText] = useState('');
const submitComments = async () =>{
setArticleInfo({ UserName:userName, Comments:commentText, articleName:articleName });
setUserName('');
setcommentText('');
}
return (
<div id="add-comment-form">
<label> Name: <input type="text" value={userName} placeholder="Your Name" onChange={(event)=> setUserName(event.target.value)} /> </label>
<label> Comments: <textarea rows="4" cols="50" placeholder="Your Comments Here!" value={commentText} onChange={(event)=> setcommentText(event.target.value)}></textarea> </label>
<button onClick={() => submitComments()}> Add Comment </button>
</div>);
};
export default AddCommentsSection;
|
/**
* Mail Services
*/
const nodemailer = require('nodemailer');
// create reusable transporter object using the default SMTP transport
const transporter = nodemailer.createTransport({
service: 'Zoho',
auth: {
user: process.env.USERNAME,
pass: process.env.PASSWORD
}
});
module.exports = {
/**
* Send Mail
* @param {Object} options Parameters to send the mail
* @param {String} html The HTML String to send via mail
* @returns {Function} callback
*/
SendMail: function (options, html, callback) {
// setup email data with unicode symbols
let mailOptions = {
from: '"Ashwin P Chandran" <' + process.env.USERNAME + '>', // sender address
to: options.to, // list of receivers
bcc: '"Ashwin P Chandran" <' + process.env.USERNAME + '>', // sender address
subject: options.subject, // Subject line
// text: 'Hello world ?', // plain text body
html: html // html body
};
// send mail with defined transport object
transporter.sendMail(mailOptions, (err, info) => {
if (err) {
return callback(err, null);
}
callback(null,info);
});
}
}
|
// Ajax functions
$(document).on("click", ".load-btn:not(.loading)", function (e) {
let loadBtn = $(this);
let page = loadBtn.data("page");
let newPage = page + 1;
let sort = loadBtn.data("sort");
let ajaxUrl = loadBtn.data("url");
let meta_key = loadBtn.data("meta");
loadBtn.addClass("loading");
loadBtn.html("Loading...");
$.ajax({
type: "post",
url: ajaxUrl,
data: {
page: page,
sort: sort,
meta_key: meta_key,
action: "load_more_users",
},
error: function (res) {
console.log(res);
},
success: function (res) {
loadBtn.data("page", newPage);
loadBtn.removeClass("loading");
loadBtn.html("Load More");
$("#load-users").append(res);
},
});
e.preventDefault();
});
|
class Response {
constructor (io, socketId) {
this.io = io;
this.socketId = socketId;
}
reply (event, data, error) {
let con = this.getConnection();
if (con) con.emit(event, error, data);
}
broadcast (event, data, error) {
return this.io.sockets.emit(event, error, data);
}
getConnection () {
return this.io.sockets.connected[this.socketId];
}
}
export default class Socket {
constructor (io, socket, session) {
this.socket = socket;
this.session = session;
this.response = new Response(io, this.socket.id);
}
handle (route) {
let events = Object.getPrototypeOf(route).routes || [];
route.setSession(this.session);
for (let event of events) {
this.socket.on(event, async (data) => {
try {
if (data) await route[event](this.response, data);
else await route[event](this.response);
} catch (error) {
this.response.reply(event, null, error);
console.log(error.stack || error);
}
});
}
}
}
|
import styled from "styled-components";
import tokens from "@paprika/tokens";
export const TimePicker = styled.div`
position: relative;
.timeinput-picker {
position: absolute;
}
input[type="text"][disabled] {
background: ${tokens.color.blackLighten70};
cursor: not-allowed;
}
`;
|
// Copyright 2017 Joseph W. May. All Rights Reserved.
//
// 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.
/**
* Base class for testing the Mastery Data class.
*/
var MasteryDataTests = function() {
Tests.call(this);
};
inherit_(MasteryDataTests, Tests);
/**
* Test to confirm that the learning goal numbers are retrieved.
*/
MasteryDataTests.prototype.testGetLearningGoalNumbers = function() {
var actualLgNums = [];
for (var i = 1; i < 21; i++) {
actualLgNums.push(i);
}
var masteryData = new MasteryData();
var testLgNums = masteryData.getLearningGoalNumbers();
assertEqualsArray_(actualLgNums, testLgNums);
};
|
export const changeThemeOptions = [
'background-image-one',
'background-image-two',
'background-image-three',
'background-image-four',
'background-image-five',
'background-image-six',
'background-image-seven',
'background-image-eight',
];
|
import React from 'react';
import { Transition } from 'react-transition-group';
import _ from 'lodash';
import Nav from './Nav';
class RouterNav extends React.Component {
state = {
in: true
};
componentWillReceiveProps() {
this.setState({ in: false }, () => this.setState({ in: true }));
}
render() {
const {
linkCollection,
match: {
params: { name }
}
} = this.props;
const tab = _.find(linkCollection, ['name', name]);
if (!tab) return null;
return (
<Transition in={this.state.in} timeout={300} unmountOnExit>
{state => {
console.log(state);
return (
<Nav
state={state}
links={tab.subLinks.map(link => ({
href: `${name}/${link.name}`,
text: link.name
}))}
/>
);
}}
</Transition>
);
}
}
export default RouterNav;
|
import React from 'react';
import { connect } from 'react-redux';
import {
Container, Row, Col, Input, FormGroup,
Button, Alert,
} from 'reactstrap';
import Link from 'next/link';
import PropTypes from 'prop-types';
import { connectWebSocket as connectWebSocketAction } from '../store/actions';
import '../css/home.css';
class Home extends React.Component {
constructor(props) {
super(props);
this.state = { apiKey: '', alertOn: false };
}
componentDidMount() {
// Loading the key after mounting due to SSR
const apiKey = localStorage.getItem('apiKey');
if (apiKey) {
this.setState({ apiKey });
}
// Input autofocus
this.apiKeyInput.focus();
}
changeValue(event, name) {
this.setState({ [name]: event.target.value });
}
connectToBattleNet() {
const { connectWebSocket } = this.props;
const { apiKey } = this.state;
connectWebSocket(apiKey);
localStorage.setItem('apiKey', apiKey);
}
render() {
const { alertOn, apiKey } = this.state;
return ([
<Container className="index__content" key="0">
<Row>
<Col>
<div className="index__title__center__wrapper">
<img src="/static/reforged.png" alt="Warcraft III Reforged" />
</div>
</Col>
</Row>
<Row className="index__title__row">
<Col>
<div className="index__title__center__wrapper">
<div className="index__title__wrapper">
<h1 className="index__title__title">
Classic Bot
</h1>
<small className="index__title__subtitle">
v1.0.1
</small>
</div>
</div>
</Col>
</Row>
<Row>
<Col>
<div className="index__title__center__wrapper">
<FormGroup>
<Input
type="password"
name="apiKey"
id="apiKey"
value={apiKey}
onChange={(event) => { this.changeValue(event, 'apiKey'); }}
placeholder="Enter your API key..."
autoFocus
ref={input => { this.apiKeyInput = input; }}
/>
</FormGroup>
</div>
</Col>
</Row>
{ alertOn && (
<Row>
<Col>
<div className="index__title__center__wrapper">
<Alert color="danger" className="index__alert">
This is a danger alert — check it out!
</Alert>
</div>
</Col>
</Row>
)}
<Row className="index__button__row">
<Col>
<div className="index__title__center__wrapper">
<Button color="primary" onClick={() => { this.connectToBattleNet(); }}>Connect</Button>
</div>
</Col>
</Row>
<Row className="index__faq__row">
<Col>
<div className="index__title__center__wrapper">
<Link prefetch href="/about">
<a>What is Classic Bot?</a>
</Link>
</div>
</Col>
</Row>
{/* Sticky footer: https://css-tricks.com/couple-takes-sticky-footer/ */}
<div className="push" />
</Container>,
<footer className="index__footer" key="1">
<small>
Warcraft® III: Reforged™ |
©2018 Blizzard Entertainment, Inc.. All rights reserved.
This is not an official product.
</small>
</footer>,
]);
}
}
const mapDispatchToProps = dispatch => ({
connectWebSocket: (apiKey) => dispatch(connectWebSocketAction(undefined, apiKey)),
});
Home.propTypes = {
connectWebSocket: PropTypes.func.isRequired,
};
export default connect(undefined, mapDispatchToProps)(Home);
|
import {Remote, Wallet} from 'ripple-lib'
import Config from './Config'
import logger from './Logger'
import BB from 'bluebird'
if (!Config.get('RIPPLED_SERVER_WEBSOCKET')) {
throw new Error('Must supply RIPPLED_SERVER_WEBSOCKET environment variable');
} else if (!Config.get('RIPPLE_ADDRESS') || !Config.get('RIPPLE_SECRET')) {
throw new Error('Must supply RIPPLE_ADDRESS and RIPPLE_SECRET environment variables');
}
export function fundNewAccount() {
var remote = new Remote({
trusted: true,
local_signing: true,
local_fee: true,
fee_cushion: 1.5,
servers: [ Config.get('RIPPLED_SERVER_WEBSOCKET') ]
});
remote.setSecret(Config.get('RIPPLE_ADDRESS'), Config.get('RIPPLE_SECRET'));
return new Promise(function(resolve, reject) {
logger.info('Generating new Ripple account');
// Generate new wallet
var wallet = Wallet.generate();
logger.info('Generated new account:', wallet.address);
var remoteConnect = BB.promisify(remote.connect, remote);
return remoteConnect().then(function() {
// Send XRP to new wallet
var transaction = remote.createTransaction('Payment', {
account: Config.get('RIPPLE_ADDRESS'),
destination: wallet.address,
// Convert to drops
amount: Config.get('XRP_AMOUNT') * 1000000
})
logger.info('Submitting tx')
var txSubmit = BB.promisify(transaction.submit, transaction)
return txSubmit().then(function(res) {
logger.info('Funded '+wallet.address+' with '+XRP_AMOUNT+' XRP');
resolve(wallet)
remote.disconnect()
})
}).catch(function(err) {
logger.info('ERROR', err)
reject(err)
remote.disconnect()
})
})
}
|
// ================================================================================
//
// Copyright: M.Nelson - technische Informatik
// Die Software darf unter den Bedingungen
// der APGL ( Affero Gnu Public Licence ) genutzt werden
//
// weblet: personnal/time/detail
// ================================================================================
{
var i;
var str = "";
var ivalues =
{
schema : 'mne_personnal',
query : 'time',
table : 'time',
querymax : 'timemax',
slotstartschema : 'mne_personnal',
slotstarttable : 'timemanagement_param',
persondataschema : 'mne_personnal',
persondataquery : 'personowndatapublic',
funcschema : 'mne_personnal',
okfunction : "time_mod",
delfunction : "time_del",
orderschema : 'mne_crm',
orderquery : 'order_detail',
orderproducttimeschema : 'mne_personnal',
orderproducttimequery : 'orderproducttime_skill',
orderproducttimecheckquery : 'orderproducttime'
};
weblet.initDefaults(ivalues);
weblet.loadview();
weblet.obj.mkbuttons.push( { id : 'okadd', value : weblet.txtGetText("#mne_lang#Ok/Hinzufügen"), before : 'ok' });
weblet.obj.mkbuttons.push( { id : 'next', value : weblet.txtGetText("#mne_lang#Neuer Schritt#") });
var attr =
{
hinput : false,
useridInput : { notclear : true },
orderproducttimeidInput : { notclear : true, checktype : weblet.inChecktype.notempty, inputcheckobject : "stepdescription" },
orderidInput : { notclear : true },
ordernumberInput : { notclear : true, checktype : weblet.inChecktype.notempty, onkeyup : function(evt) { try { this.weblet.onkeyup(this,evt) } catch(e) { this.weblet.exception("Ordernumber", e) } } },
nameOutput : { notclear : true },
refnameOutput : { notclear : true },
productnameOutput : { notclear : true },
productnumberInput : { notclear : true, onkeyup : function(evt) { try { this.weblet.onkeyup(this, evt) } catch(e) { this.weblet.exception("Produktnumber", e) } } },
stepdescriptionOutput : { notclear : true },
orderdescriptionOutput : { notclear : true },
dateInput : { inputtyp : 'date', notclear : true, checktype : weblet.inChecktype.notempty },
clocktimeInput : { inputtyp : 'time', onkeydown : function() { this.weblet.obj.inputs.clocktimeend.value = '' }},
clocktimeendInput : { inputtyp : 'time', onkeydown : function() { this.weblet.obj.inputs.duration.value = '' } },
durationInput : { inputtyp : 'time', onkeydown : function() { this.weblet.obj.inputs.clocktimeend.value = '' }},
commentInput : { spellcheck : false },
daytextOutput : { outputtyp : 'day', notclear : true }
}
weblet.findIO(attr);
weblet.showLabel();
weblet.showids = new Array("timeid");
weblet.titleString.add = weblet.txtGetText("#mne_lang#Zeiteintrag hinzufügen");
weblet.titleString.mod = weblet.txtGetText("#mne_lang#Zeiteintrag bearbeiten");
weblet.obj.ajaxread = new MneAjaxData(weblet.win);
weblet.obj.slotstart = 0;
var param =
{
"schema" : weblet.initpar.slotstartschema,
"table" : weblet.initpar.slotstarttable,
"cols" : "slotstart",
"sqlend" : 1
};
weblet.obj.ajaxread.read("/db/utils/table/data.xml", param)
if ( weblet.obj.ajaxread.values.length > 0 )
weblet.obj.slotstart = weblet.obj.ajaxread.values[0][0];
param =
{
"schema" : weblet.initpar.persondataschema,
"query" : weblet.initpar.persondataquery,
"cols" : "personid,fullname,loginname",
"loginnameInput.old" : "session_user",
"sqlend" : 1
};
weblet.obj.ajaxread.read("/db/utils/query/data.xml", param)
if ( weblet.obj.ajaxread.values.length > 0 )
{
weblet.showInput(weblet.obj.inputs.userid, weblet.obj.ajaxread.values[0][0]);
weblet.showOutput(weblet.obj.outputs.name, weblet.obj.ajaxread.values[0][1])
weblet.showInput(weblet.obj.inputs.loginname, weblet.obj.ajaxread.values[0][2]);
weblet.act_values.loginname = weblet.obj.ajaxread.values[0][2];
}
weblet.showValue = function(weblet)
{
this.obj.inputs.clocktimeend.disabled = false;
if ( weblet == null || typeof weblet.act_values.timeid == 'undefined' || weblet.act_values.timeid == '################')
{
this.add();
if ( weblet != null )
{
if ( typeof weblet.act_values.orderproducttimeid != 'undefined' )
{
this.showInput(this.obj.inputs.orderproducttimeid, weblet.act_values.orderproducttimeid);
this.showInput(this.obj.inputs.ordernumber, weblet.act_values.ordernumber);
this.showInput(this.obj.inputs.productnumber, weblet.act_values.productnumber);
this.showOutput(this.obj.outputs.orderdescription, weblet.act_values.orderdescription);
this.showOutput(this.obj.outputs.stepdescription, weblet.act_values.stepdescription);
this.showOutput(this.obj.outputs.productname, weblet.act_values.productname);
this.showOutput(this.obj.outputs.refname, weblet.act_values.refname);
}
}
}
else
{
MneAjaxWeblet.prototype.showValue.call(this,weblet);
this.obj.act_timeid = weblet.act_values.timeid;
if ( this.act_values.duration > 86400 ) this.obj.inputs.clocktimeend.disabled = true;
if ( weblet.win.mne_config.timeauto.substr(0,1) != "t" )
{
this.showOutput(this.obj.labels.interval, "");
this.showOutput(this.obj.outputs.interval, "");
}
}
if ( typeof this.act_values.ordernumber == 'undefined' )
this.act_values.ordernumber = '';
if ( typeof this.obj.timeoutid != 'undefined')
{
window.clearTimeout(this.obj.timeoutid);
this.showOutput(this.obj.labels.interval, "noauto");
delete this.obj.timeoutid;
}
var param =
{
"schema" : this.initpar.schema,
"query" : this.initpar.querymax,
"cols" : "start,startday,starttime,userid",
"loginnameInput.old" : this.act_values.loginname,
"sqlend" : 1
};
this.obj.ajaxread.read("/db/utils/query/data.xml", param)
if ( this.obj.ajaxread.values.length > 0 )
this.act_values.lasttime = Number(this.obj.ajaxread.values[0][0]) - 200000;
else
this.act_values.lasttime = 0;
if ( weblet == null && this.win.mne_config.timeauto.substr(0,1) == "t" )
{
if ( this.obj.ajaxread.values.length > 0 )
{
var day = this.obj.ajaxread.values[0][1];
var start = this.obj.ajaxread.values[0][2];
var param =
{
"schema" : this.initpar.schema,
"query" : this.initpar.query,
"cols" : "timeid",
"useridInput.old" : this.obj.ajaxread.values[0][3],
"startInput.old" : this.obj.ajaxread.values[0][0],
"sqlend" : 1
};
this.obj.ajaxread.read( "/db/utils/query/data.xml", param)
if ( this.obj.ajaxread.values.length > 0 )
{
this.act_values.timeid = this.obj.ajaxread.values[0][0];
MneAjaxWeblet.prototype.showValue.call(this,this);
if ( this.act_values.duration > 86400 ) this.obj.inputs.clocktimeend.disabled = true;
if ( this.act_values.interval < 43300 )
{
var self = this;
var timeout = function() { try { self.obj.timeout.call(self) } catch(e) {}; };
var d = new Date();
if ( typeof this.obj.timeoutid == 'undefined')
{
this.obj.timeoutid = window.setTimeout(timeout, 1100 - ( d.getTime() % 1000 ));
this.showOutput(this.obj.labels.interval, "auto");
}
}
else
{
var interval = this.act_values.interval;
this.showOutput(this.obj.outputs.interval, interval, "interval", true);
this.showOutput(this.obj.labels.interval, "noauto");
}
}
}
}
}
weblet.checkmodified = function()
{
return false;
}
weblet.add = function(setdepend)
{
var param =
{
"schema" : this.initpar.schema,
"query" : this.initpar.querymax,
"cols" : "start,startday,starttime,daytext,userid,duration",
"loginnameInput.old" : "session_user",
"sqlend" : 1
};
this.obj.ajaxread.read("/db/utils/query/data.xml", param)
if ( this.obj.ajaxread.values.length > 0 )
this.act_values.lasttime = Number(this.obj.ajaxread.values[0][0]) - 200000;
this.obj.inputs.clocktimeend.disabled = false;
MneAjaxWeblet.prototype.add.call(this,false);
if ( this.obj.intimeout != true )
this.obj.act_timeid = this.act_values.timeid;
this.obj.intimeout = false;
if ( typeof this.obj.timeoutid != 'undefined')
{
window.clearTimeout(this.obj.timeoutid);
this.showOutput(this.obj.labels.interval, "noauto");
delete this.obj.timeoutid;
}
var d = new Date();
var nexttime = Number(this.obj.inputs.clocktime.mne_timevalue) + Number(this.obj.inputs.duration.mne_timevalue);
var actdate = ( d.getTime() / 1000 ) - (( d.getTime() / 1000 ) % 86400) + ( d.getTimezoneOffset() * 60);
if ( this.obj.inputs.date.value == '' )
{
if ( this.obj.ajaxread.values.length > 0 )
{
this.showInput(this.obj.inputs.date, Number(this.obj.ajaxread.values[0][1]), '1001', true);
this.showInput(this.obj.inputs.clocktime, Number(this.obj.ajaxread.values[0][2]) + Number(this.obj.ajaxread.values[0][5]), 'interval', true);
this.showInput(this.obj.inputs.clocktimeend, Number(this.obj.ajaxread.values[0][2]) + Number(this.obj.ajaxread.values[0][5]), 'interval', true);
this.showInput(this.obj.inputs.duration, 0, 'interval', true);
this.showOutput(this.obj.outputs.daytext, this.obj.ajaxread.values[0][3], 'day', true);
}
else
{
this.showInput(this.obj.inputs.date, actdate, '1001', true);
this.showInput(this.obj.inputs.clocktime, this.obj.slotstart, 'interval', true);
this.showInput(this.obj.inputs.clocktimeend, this.obj.slotstart, 'interval', true);
this.showInput(this.obj.inputs.duration, 0, 'interval', true);
this.showOutput(this.obj.outputs.daytext, d.getDay() + 1, 'day', true);
}
}
else
{
if ( this.obj.ajaxread.values.length > 0 && Number(this.obj.ajaxread.values[0][1] ) == this.obj.inputs.date.mne_timevalue )
nexttime = Number(this.obj.ajaxread.values[0][2] ) + Number(this.obj.ajaxread.values[0][5] )
this.obj.inputs.date.onkeyup();
this.showInput(this.obj.inputs.clocktime, nexttime, 'interval', true);
this.showInput(this.obj.inputs.clocktimeend, nexttime, 'interval', true);
this.showInput(this.obj.inputs.duration, 0, 'interval', true);
var param =
{
"schema" : weblet.initpar.schema,
"query" : weblet.initpar.query,
"cols" : "start",
wcol : "loginname,start,start",
wval : "session_user," + ( Number(this.obj.inputs.date.mne_timevalue) + nexttime) + "," + ( Number(this.obj.inputs.date.mne_timevalue) + 86400 ),
wop : "=,>=,<=",
scols : "start",
"sqlend" : 1
};
weblet.obj.ajaxread.read("/db/utils/query/data.xml", param)
if ( weblet.obj.ajaxread.values.length > 0 )
{
this.showInput(this.obj.inputs.clocktimeend, Number(weblet.obj.ajaxread.values[0][0]) - Number(this.obj.inputs.date.mne_timevalue), 'interval', true);
this.showInput(this.obj.inputs.duration, Number(weblet.obj.ajaxread.values[0][0]) - Number(this.obj.inputs.date.mne_timevalue) - Number(this.obj.inputs.clocktime.mne_timevalue), 'interval', true);
}
}
this.setDepends('add');
return false;
}
weblet.cancel = function()
{
this.act_values.timeid = this.obj.act_timeid;
this.showValue(this);
if ( this.okaction == "add" )
{
this.obj.timeoutid_productnumber = "add";
this.obj.timeout_productnumber.call(this,true);
if ( this.obj.inputs.productnumber.className.indexOf('modifywrong') >= 0 )
{
this.obj.timeoutid_ordernumber = "add";
this.obj.timeout_ordernumber.call(this,true);
}
}
return false;
}
weblet.write = function()
{
this.obj.inputs.start.value = Number(this.obj.inputs.date.mne_timevalue) + Number(this.obj.inputs.clocktime.mne_timevalue);
if ( this.obj.inputs.start.value == "NaN")
{
this.error("#mne_lang#Bitte die Zeiteingaben überprüfen");
return true;
}
if ( this.obj.inputs.clocktimeend.disable != true && this.obj.inputs.clocktimeend.value != '' )
{
var duration = Number(this.obj.inputs.clocktimeend.mne_timevalue) - Number(this.obj.inputs.clocktime.mne_timevalue);
if ( duration < 0 ) duration = duration + 86400;
this.showInput(this.obj.inputs.duration, duration, 'interval', true);
}
var p =
{
schema : this.initpar.funcschema,
name : this.initpar.okfunction,
typ0 : "text",
typ1 : "text",
typ2 : "text",
typ3 : "long",
typ4 : "long",
typ5 : "text",
sqlend : 1
}
p = this.addParam(p, "par0", this.obj.inputs.timeid);
p = this.addParam(p, "par1", this.obj.inputs.orderproducttimeid);
p = this.addParam(p, "par2", this.obj.inputs.userid);
p = this.addParam(p, "par3", this.obj.inputs.start);
p = this.addParam(p, "par4", this.obj.inputs.duration);
p = this.addParam(p, "par5", this.obj.inputs.comment);
return MneAjaxWeblet.prototype.write.call(this,'/db/utils/connect/func/execute.xml', p);
}
weblet.ok = function()
{
if ( this.write() == 'ok' )
{
this.act_values.timeid = this.act_values.result;
this.showValue(this);
this.setDepends("showValue");
return false;
}
return true;
}
weblet.okadd = function()
{
if ( this.write() == 'ok' )
{
this.add();
return false;
}
return true;
}
weblet.del = function()
{
var p =
{
schema : this.initpar.funcschema,
name : this.initpar.delfunction,
typ0 : "text",
sqlend : 1
}
p = this.addParam(p, "par0", this.act_values.timeid);
if ( this.confirm(this.txtSprintf(this.txtGetText("#mne_lang#Eintrag <$1> wirklich löschen"), this.obj.inputs.date.value + " - " + this.obj.inputs.clocktime.value + " / " + this.obj.inputs.duration.value)) != true )
return false;
if ( MneAjaxWeblet.prototype.write.call(this,'/db/utils/connect/func/execute.xml', p) == 'ok')
{
this.showValue(null);
this.setDepends("del");
return false;
}
return true;
}
weblet.next = function()
{
this.add();
var nexttime = Number(this.obj.inputs.clocktime.mne_timevalue) + Number(this.obj.inputs.duration.mne_timevalue);
this.showInput(this.obj.inputs.clocktime, nexttime, 'interval', true);
var interval = Number((new Date).getTime() / 1000) - Number(this.obj.inputs.date.mne_timevalue) - Number(this.obj.inputs.clocktime.mne_timevalue);
this.showInput(this.obj.inputs.duration, Number(interval / 3600, 10) * 3600, "interval", true);
}
weblet.actday = function()
{
var d = new Date();
var actdate = ( d.getTime() / 1000 ) - (( d.getTime() / 1000 ) % 86400) + ( d.getTimezoneOffset() * 60);
this.showInput(this.obj.inputs.date, actdate, 'date', true);
this.showInput(this.obj.inputs.clocktime, this.obj.slotstart, 'interval', true);
this.showInput(this.obj.inputs.clocktimeend, this.obj.slotstart, 'interval', true);
this.showInput(this.obj.inputs.duration, 0, 'interval', true);
this.showOutput(this.obj.outputs.daytext, d.getDay() + 1, 'day', true);
return this.add();
}
weblet.onbtnclick = function(id, button)
{
if ( button.weblet.oid == 'selectday' )
{
if ( ( this.obj.inputs.clocktime.className.indexOf("modifyok") == -1 ||
this.obj.inputs.date.mne_timevalue != this.act_values.date ) &&
this.okaction == 'add')
{
this.showInput(this.obj.inputs.clocktime, this.obj.slotstart, 'interval', true);
this.showInput(this.obj.inputs.clocktimeend, this.obj.slotstart, 'interval', true);
this.showInput(this.obj.inputs.duration, 0, 'interval', true);
}
this.setDepends('selectday');
}
else if ( button.weblet.oid == this.oid + 'inputlistordernumber' )
{
this.obj.timeoutid_ordernumber = "onbtnclick";
this.obj.timeout_ordernumber.call(this,true);
}
else if ( button.weblet.oid == this.oid + 'inputlistproductnumber' )
{
this.obj.timeoutid_productnumber = "onbtnclick";
this.obj.timeout_productnumber.call(this,true);
}
else if ( button.weblet.oid == this.oid + 'inputliststepdescription' )
{
this.setModify(this.obj.labels.stepdescription,"modifyno");
}
}
weblet.onkeyup = function(obj, evt)
{
if ( typeof evt == 'undefined' || evt == null )
{
MneMisc.prototype.inOnmodify.call(obj);
return;
}
if ( obj.id == 'ordernumberInput' )
{
var self = this;
var timeout = function() { try { self.obj.timeout_ordernumber.call(self) } catch(e) {}; };
if ( this.obj.timeoutid_ordernumber != 'undefined' )
window.clearTimeout(this.obj.timeoutid_ordernumber);
this.obj.timeoutid_ordernumber = window.setTimeout(timeout, 500 );
}
else if ( obj.id == 'productnumberInput' )
{
var self = this;
var timeout = function() { try { self.obj.timeout_productnumber.call(self) } catch(e) {}; };
if ( this.obj.timeoutid_productnumber != 'undefined' )
window.clearTimeout(this.obj.timeoutid_productnumber);
this.obj.timeoutid_productnumber = window.setTimeout(timeout, 500 );
}
}
weblet.obj.timeout = function()
{
var d = new Date();
var interval = Number(d.getTime() / 1000) - Number(this.obj.inputs.date.mne_timevalue) - Number(this.obj.inputs.clocktime.mne_timevalue);
this.showOutput(this.obj.outputs.interval, interval - Number(this.act_values.duration,10), "interval", true);
if ( interval > Number(this.act_values.duration,10) + 3600 )
{
if ( this.confirm("#mne_lang#Soll die Zeit auf den aktuellen Projektschritt erfasst werden ?"))
{
this.showInput(this.obj.inputs.duration, Number(interval / 3600, 10) * 3600, "interval", true);
this.obj.inputs.clocktimeend.value = '';
var timeid = this.act_values.timeid;
this.ok(false);
this.act_values.timeid = this.act_values.result;
this.showValue(this);
}
}
{
var self = this;
var timeout = function() { try { self.obj.timeout.call(self) } catch(e) {}; };
this.obj.timeoutid = window.setTimeout(timeout, 601000 - ( (new Date()).getTime() % 600000 ));
this.showOutput(this.obj.labels.interval, "auto");
}
}
weblet.obj.timeout_ordernumber = function(noadd)
{
var w = new MneAjaxData(this.win);
var param =
{
"schema" : this.initpar.orderschema,
"query" : this.initpar.orderquery,
"cols" : "orderid,refname,description",
"ordernumberInput.old" : this.obj.inputs.ordernumber.value,
"closedInput.old" : "false",
"openInput.old" : "true",
"sqlend" : 1
};
if ( typeof this.obj.timeoutid_ordernumber == 'undefined' )
return;
delete this.obj.timeoutid_ordernumber;
this.obj.intimeout = true;
if ( noadd != true )
this.add();
this.obj.intimeout = false;
w.read("/db/utils/query/data.xml", param);
if ( w.values.length > 0 )
{
this.showInput(this.obj.inputs.orderid, w.values[0][0], null, true);
this.showOutput(this.obj.outputs.refname, w.values[0][1]);
this.showOutput(this.obj.outputs.orderdescription, w.values[0][2]);
this.act_values.ordernumber = this.obj.inputs.ordernumber.value;
this.setModify(this.obj.inputs.ordernumber,"modifyok");
}
else
{
this.showOutput(this.obj.outputs.refname, "");
this.showOutput(this.obj.outputs.orderdescription, "");
this.setModify(this.obj.inputs.ordernumber,"modifywrong");
}
this.showInput(this.obj.inputs.orderproducttimeid, "", null, true);
this.showInput(this.obj.inputs.productnumber, "", null, true);
this.showOutput(this.obj.outputs.productname, "");
this.showOutput(this.obj.outputs.stepdescription, "");
}
weblet.obj.timeout_productnumber = function(noadd)
{
var w = new MneAjaxData(this.win);
var param =
{
"schema" : this.initpar.orderproducttimeschema,
"query" : this.initpar.orderproducttimequery,
"cols" : "productname,orderproducttimeid,stepdescription",
"orderidInput.old" : this.obj.inputs.orderid.value,
"productnumberInput.old" : this.obj.inputs.productnumber.value,
"loginInput.old" : "session_user",
"sqlend" : 1
};
if ( typeof this.obj.timeoutid_productnumber == 'undefined' )
return;
delete this.obj.timeoutid_productnumber;
if ( this.obj.inputs.productnumber.value == '' )
return;
this.obj.intimeout = true;
if ( noadd != true )
this.add();
this.obj.intimeout = false;
w.read("/db/utils/query/data.xml", param);
if ( w.values.length > 0 )
{
this.showOutput(this.obj.outputs.productname, w.values[0][0]);
this.showOutput(this.obj.outputs.stepdescription, "");
this.showInput(this.obj.inputs.orderproducttimeid, "", null, true);
this.setModify(this.obj.inputs.productnumber,"modifyok");
if ( w.values.length == 1 )
{
this.showInput(this.obj.inputs.orderproducttimeid, w.values[0][1], null, true);
this.showOutput(this.obj.outputs.stepdescription, w.values[0][2]);
}
else
{
this.showInput(this.obj.inputs.orderproducttimeid, '', null, true);
this.showOutput(this.obj.outputs.stepdescription, '');
}
}
else
{
param =
{
"schema" : this.initpar.orderproducttimeschema,
"query" : this.initpar.orderproducttimecheckquery,
"cols" : "productnumber,productname",
"orderidInput.old" : this.obj.inputs.orderid.value,
"productnumberInput.old" : this.obj.inputs.productnumber.value,
"sqlend" : 1
};
w.read("/db/utils/query/data.xml", param);
if ( w.values.length == 0 )
{
this.setModify(this.obj.inputs.productnumber,"modifywrong");
}
else
{
this.showOutput(this.obj.outputs.productname, w.values[0][1]);
this.showOutput(this.obj.outputs.stepdescription, "");
this.showInput(this.obj.inputs.orderproducttimeid, "", null, true);
this.setModify(this.obj.inputs.productnumber,"modifyok");
}
}
}
}
|
export default {
en: {
field: "field",
institution: "institution"
}
}
|
import React, { PropTypes } from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles'
import s from './SuperTree.less';
import {Tree} from 'antd';
const TreeNode = Tree.TreeNode;
const TreeType = {
root: PropTypes.string
// 如下均为key-value对,value取值为{key: <string>, title: <string>, parent: <string>, children: <string array>}
};
/**
* 参数说明:
* tree:对象,用于存储一颗树的数据,其root属性表示根节点的key
* select:表示选中条目的key
* expand:对象,key-value对,key表示条目的key,value为true表示展开,为false表示折叠
* onExpand:展开/折叠时触发,原型为function(key, expand),expand为true表示展开
* onSelect:条目选中时触发,原型为function(key),key标识所选条目
*/
class SuperTree extends React.Component {
static propTypes = {
tree: PropTypes.shape(TreeType).isRequired,
select: PropTypes.string,
expand: PropTypes.object,
checked: PropTypes.object,
onExpand: PropTypes.func,
onSelect: PropTypes.func,
onCheck: PropTypes.func,
};
onSelect = (keys) => {
const {onSelect} = this.props;
if (onSelect && keys.length !== 0) {
onSelect(keys[0]);
}
};
onExpand = (expandedKeys, {expanded, node}) => {
const {onExpand} = this.props;
if (onExpand) {
onExpand(node.props.eventKey, expanded);
}
};
onCheck = (checkedKeys, {checked, node}) => {
const {onCheck} = this.props;
if (onCheck) {
onCheck(node.props.eventKey, checked);
}
};
toNodes = (tree, keys) => {
return keys.map(key => {
const {title, children} = tree[key];
return (
<TreeNode key={key} title={title}>
{children ? this.toNodes(tree, children) : null}
</TreeNode>
);
});
};
toTree = () => {
const {tree} = this.props;
if (tree.root) {
return this.toNodes(tree, tree[tree.root].children);
} else {
return null;
}
};
render() {
const {select, expand={}, checked={}} = this.props;
const props = {
checkable: true,
selectedKeys: [select],
expandedKeys: Object.keys(expand).filter(key => expand[key]),
checkedKeys: Object.keys(checked).filter(key => checked[key]),
autoExpandParent: false,
onSelect: this.onSelect,
onExpand: this.onExpand,
onCheck: this.onCheck,
};
return <div className={s.root}><Tree {...props}>{this.toTree()}</Tree></div>;
}
}
export default withStyles(s)(SuperTree);
|
"use strict";
angular.module("mushroom",["ngRoute"])
.config($routeProvider => {
$routeProvider
.when("/",{
templateUrl:"partials/partials.html",
controller:"MushroomController"
})
.otherwise("/")
});
|
import React from "react";
import styles from "./css/topBar.module.css";
export default function TopBar() {
return (
<div className={styles.topBar}>
<h1 className={styles.right}>
مستجدات فيروس كورونا بالمغرب <span className={styles.circle}> </span>
</h1>
</div>
);
}
|
function newPassword() {
var newPass = document.getElementById("newPass");
var reply = document.getElementById("replyPass");
var token = document.getElementById("token");
var message = document.getElementById("errorCurrentPass");
if ( reply.value == newPass.value ) {
var data = {
token: token.textContent,
newPassword: newPass.value
};
$("#errorCurrentPass").load("/profile/newPassword", data,function() {
if (message.textContent == 'Пароль изменен') {
window.setTimeout(function () {
window.location.replace("/login");
},3000);
}
});
} else {
message.innerHTML = "Пароли не совпадают"
}
}
|
const button = document.getElementById('button');
button.addEventListener('change', () => {
document.body.classList.toggle('dark');
});
|
import React from "react";
import "./aboutStyles.css";
const AboutMe = () => {
return (
<div id="aboutMe" className="aboutMe fullHeight d-flex">
<div className="aboutContent mobile-column d-flex">
<div className="photo d-flex" />
<div className="paragraf d-flex">
<div className="paragraf_content">
<p>
My name is Karolina and I am 22 years old. I am from Częstochowa,
but I live in Warsaw. I graduated in Microbiology from the
University of Wroclaw. I am cat mama of 8 months old Maine Coon -
Ginger.
</p>
<hr />
<p>
I started programming because, it was always fascinating for me
how apps work and I wanted to build something by myself. Now I know
that programming is what I would like to do in my life and I am
ready to work.
</p>
<hr />
<p>
In my free time I like playing with my cat, learning new things
and meeting with friends.
</p>
</div>
</div>
</div>
</div>
);
};
export default AboutMe;
|
const mongoose = require('mongoose');
const mongoosePaginate = require('mongoose-paginate');
const CardSchema = new mongoose.Schema({
name: {
type: String,
require: true
},
price: {
type: Number,
require: true
},
description : {
type: String,
require: true
},
createdAt: {
type: Date,
default: Date.now
}
});
CardSchema.plugin(mongoosePaginate);
module.exports = mongoose.model('Card', CardSchema)
//mongoose.model("Card", CardSchema)
|
import React, {Component} from 'react';
import { withStyles } from "@material-ui/core/styles";
import Paper from '@material-ui/core/Paper';
import Typography from '@material-ui/core/Typography';
import Button from '@material-ui/core/Button';
import TextField from '@material-ui/core/TextField';
import MenuItem from '@material-ui/core/MenuItem';
import {
MIN_LOGIN_LENGTH, MAX_LOGIN_LENGTH,
MIN_NAME_LENGTH, MAX_NAME_LENGTH,
MAX_EMAIL_LENGTH,
MIN_PASSWORD_LENGTH, MAX_PASSWORD_LENGTH
} from "../../constants";
const styles = {
registrationForm: {
marginTop: '35px',
padding: '20px',
minWidth:'350px',
display: 'flex',
flexDirection: 'column',
flexWrap: 'nowrap',
justifyContent: 'flex-start',
alignItems: 'stretch',
alignContent: 'space-around',
},
submitButton: {
marginTop: '10px',
marginBottom: '5px',
},
formHeader: {
marginBottom: '10px'
},
};
class RegistrationForm extends Component{
constructor(props){
super(props);
this.state = {
login:{
value:''
},
firstName:{
value:''
},
lastName:{
value:''
},
companyName:{
value:''
},
companyCountry: 'Другая',
companyCity:{
value:''
},
email:{
value:''
},
password:{
value:''
}
};
this.handleInputChange = this.handleInputChange.bind(this);
this.onClickSubmitButton = this.onClickSubmitButton.bind(this);
}
onClickSubmitButton = () => {
let fields = this.state;
let account = {
login: fields.login.value,
password: fields.password.value,
profile: {
email: fields.email.value,
firstName: fields.firstName.value,
lastName: fields.lastName.value
},
employee: {
company: {
name: fields.companyName.value,
city: fields.companyCity.value,
country:{
name: fields.companyCountry
}
}
}
};
this.props.handleSubmitButton(account);
};
handleInputChange = (event, validateFunction) => {
const target = event.target;
const inputName = target.name;
const inputValue = target.value;
const validation = validateFunction(inputValue);
this.setState({
[inputName]:{
value: inputValue,
err: validation.err
}
});
};
handleChange = name => event => {
this.setState({
[name]: event.target.value,
});
};
isNotValidForm = () => {
let fields = this.state;
let isNotValidLogin = fields.login.err || fields.login.err === undefined;
let isNotValidFirstName = fields.firstName.err || fields.firstName.err === undefined;
let isNotValidLastName = fields.lastName.err || fields.lastName.err === undefined;
let isNotValidCompanyName = fields.companyName.err || fields.companyName.err === undefined;
let isNotValidCompanyCity = fields.companyCity.err || fields.companyCity.err === undefined;
let isNotValidEmail = fields.email.err || fields.email.err === undefined;
let isNotValidPassword = fields.password.err || fields.password.err === undefined;
let isNotValidCountry = !fields.companyCountry || fields.companyCountry === undefined;
return (isNotValidLogin ||
isNotValidFirstName ||
isNotValidLastName ||
isNotValidCompanyName ||
isNotValidCompanyCity ||
isNotValidEmail ||
isNotValidPassword ||
isNotValidCountry
);
};
render(){
const { classes } = this.props;
const fields = this.state;
return (
<div>
<Paper className={classes.registrationForm} elevation={0}>
<Typography className={classes.formHeader} variant="h5" component="h3">
Sign up
</Typography>
<TextField
id="login-textfield"
label="Login"
name="login"
placeholder="Your login"
error={fields.login.err}
onChange={(event) => {this.handleInputChange(event, this.validateLogin)}}
margin="dense"
variant="outlined"
/>
<TextField
id="firstname-textfield"
label="First Name"
name="firstName"
placeholder="Your first name"
error={fields.firstName.err}
onChange={(event) => {this.handleInputChange(event, this.validateName)}}
margin="dense"
variant="outlined"
/>
<TextField
id="lastname-textfield"
label="Last Name"
name="lastName"
placeholder="Your last name"
error={fields.lastName.err}
onChange={(event) => {this.handleInputChange(event, this.validateName)}}
margin="dense"
variant="outlined"
/>
<TextField
id="lastname-textfield"
label="Company Name"
name="companyName"
placeholder="Your last name"
error={fields.companyName.err}
onChange={(event) => {this.handleInputChange(event, this.validateName)}}
margin="dense"
variant="outlined"
/>
<TextField
select
margin="dense"
variant="outlined"
label="Country"
name="companyCountry"
value={this.state.companyCountry}
onChange={this.handleChange('companyCountry')}
>
{this.props.countries.map(country => (
<MenuItem key={country.id} value={country.name}>
{country.name}
</MenuItem>
))}
</TextField>
<TextField
id="lastname-textfield"
label="City"
name="companyCity"
placeholder="Your last name"
error={fields.companyCity.err}
onChange={(event) => {this.handleInputChange(event, this.validateName)}}
margin="dense"
variant="outlined"
/>
<TextField
id="email-textfield"
label="Email"
name="email"
placeholder="Your email"
error={fields.email.err}
onChange={(event) => {this.handleInputChange(event, this.validateEmail)}}
margin="dense"
variant="outlined"
/>
<TextField
id="password-textfield"
label="Password"
name="password"
placeholder="Your password"
type="password"
error={fields.password.err}
onChange={(event) => {this.handleInputChange(event, this.validatePassword)}}
margin="dense"
variant="outlined"
/>
<Button onClick={this.onClickSubmitButton} disabled={this.isNotValidForm()} className={classes.submitButton} variant="contained" color="primary">
Register
</Button>
<Typography variant="caption" gutterBottom>
Already registered? <a href="/signin">Login now!</a>
</Typography>
</Paper>
</div>
)
};
validateLogin = (login) => {
const LOGIN_REGEX = RegExp('^[a-zA-Z1-9]+$');
if(!LOGIN_REGEX.test(login)){
return {
err: true,
errorMessage: 'Login contains invalid characters.'
}
}
if(login.length < MIN_LOGIN_LENGTH){
return {
err: true,
errorMessage: `Minimum login length is ${MIN_LOGIN_LENGTH}.`
}
}
if(login.length > MAX_LOGIN_LENGTH){
return {
err: true,
errorMessage: `Maximum login length is ${MAX_LOGIN_LENGTH}.`
}
}
return {
err: false,
errorMessage: null
}
};
validateName = (name) => {
const NAME_REGEX = RegExp('^[a-zA-ZА-яа-я]+$');
if(!NAME_REGEX.test(name)){
return {
err: true,
errorMessage: 'Name contains invalid characters'
}
}
if(name.length < MIN_NAME_LENGTH){
return {
err: true,
errorMessage: `Minimum name length is ${MIN_NAME_LENGTH}.`
}
}
if(name.length > MAX_NAME_LENGTH){
return {
err: true,
errorMessage: `Maximum name length is ${MAX_NAME_LENGTH}.`
}
}
return {
err: false,
errorMessage: null
}
};
validateEmail = (email) => {
if(!email){
return {
err: true,
errorMessage: 'Email can\'t be empty.'
}
}
const EMAIL_REGEX = RegExp('[^@ ]+@[^@ ]+\\.[^@ ]+');
if(!EMAIL_REGEX.test(email)) {
return {
err: true,
errorMessage: 'Email not valid.'
}
}
if(email.length > MAX_EMAIL_LENGTH){
return {
err: true,
errorMessage: 'Email address length cannot be more than 254 symbols.'
}
}
return {
err: false,
errorMessage: null
}
};
validatePassword = (password) => {
if(password.length < MIN_PASSWORD_LENGTH){
return {
err: true,
errorMessage: `Password length cannot be less than ${MIN_PASSWORD_LENGTH} symbols.`
}
}
if(password.length > MAX_PASSWORD_LENGTH){
return {
err: true,
errorMessage: `Password length cannot be more than ${MAX_PASSWORD_LENGTH} symbols.`
}
}
return {
err: false,
errorMessage: null
}
}
}
export default withStyles(styles)(RegistrationForm);
|
import React from "react";
import "./style.css";
import { Link } from "react-router-dom";
function MobileNav() {
return (
<div id="menu-canvas" uk-offcanvas="overlay: true">
<div className="uk-offcanvas-bar">
<button className="uk-offcanvas-close" type="button" uk-close="true"></button>
<ul className="uk-list">
<li><Link to="/about" className="nav-item mobile-nav-item">About</Link></li>
<li><Link to="/portfolio" className="nav-item mobile-nav-item">Portfolio</Link></li>
<li><Link to="/skills" className="nav-item mobile-nav-item">Skills</Link></li>
<li><a uk-toggle="target: #contact-canvas" className="nav-item mobile-nav-item">Contact</a></li>
</ul>
</div>
</div>
)
};
export default MobileNav;
|
var pg = require('pg'); //require postgres?
var path = require('path');
var connectionString = process.env.DATABASE_URL; //this is the string that leads us to our server on 5432
var conString = require(path.join(__dirname, '../', '../', 'config'));
var client = new pg.Client(conString); //makes a new client connect to port 5432
client.connect(); //connect the client to the db
var query = client.query('CREATE TABLE registered(id SERIAL PRIMARY KEY, email VARCHAR (255) not null, password VARCHAR (255) not null, firstName VARCHAR(255) not null, lastName VARCHAR(255) not null, licensePlate VARCHAR (6) not null, state VARCHAR (2) not null, phoneNumber VARCHAR (10))'); //make a table
query.on('end', function() { client.end(); });
|
// Our input frames will come from here.
const videoElement =
document.getElementsByClassName('input_video')[0];
const canvasElement =
document.getElementsByClassName('output_canvas')[0];
const controlsElement =
document.getElementsByClassName('control-panel')[0];
const canvasCtx = canvasElement.getContext('2d');
// We'll add this to our control panel later, but we'll save it here so we can
// call tick() each time the graph runs.
const fpsControl = new FPS();
// Optimization: Turn off animated spinner after its hiding animation is done.
const spinner = document.querySelector('.loading');
spinner.ontransitionend = () => {
spinner.style.display = 'none';
};
function removeElements(landmarks, elements) {
for (const element of elements) {
delete landmarks[element];
}
}
function removeLandmarks(results) {
if (results.poseLandmarks) {
removeElements(
results.poseLandmarks,
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 16, 17, 18, 19, 20, 21, 22]);
}
}
function connect(ctx, connectors) {
const canvas = ctx.canvas;
for (const connector of connectors) {
const from = connector[0];
const to = connector[1];
if (from && to) {
if (from.visibility && to.visibility &&
(from.visibility < 0.1 || to.visibility < 0.1)) {
continue;
}
ctx.beginPath();
ctx.moveTo(from.x * canvas.width, from.y * canvas.height);
ctx.lineTo(to.x * canvas.width, to.y * canvas.height);
ctx.stroke();
}
}
}
function onResults(results) {
// console.log(results);
// Hide the spinner.
document.body.classList.add('loaded');
// Remove landmarks we don't want to draw.
removeLandmarks(results);
// Update the frame rate.
fpsControl.tick();
// Draw the overlays.
canvasCtx.save();
canvasCtx.clearRect(0, 0, canvasElement.width, canvasElement.height);
canvasCtx.drawImage(
results.image, 0, 0, canvasElement.width, canvasElement.height);
// Connect elbows to hands. Do this first so that the other graphics will draw
// on top of these marks.
canvasCtx.lineWidth = 5;
if (results.poseLandmarks) {
if (results.rightHandLandmarks) {
canvasCtx.strokeStyle = 'white';
connect(canvasCtx, [[
results.poseLandmarks[POSE_LANDMARKS.RIGHT_ELBOW],
results.rightHandLandmarks[0]
]]);
}
if (results.leftHandLandmarks) {
canvasCtx.strokeStyle = 'white';
connect(canvasCtx, [[
results.poseLandmarks[POSE_LANDMARKS.LEFT_ELBOW],
results.leftHandLandmarks[0]
]]);
}
}
// Pose...
drawConnectors(
canvasCtx, results.poseLandmarks, POSE_CONNECTIONS,
{ color: 'white' });
drawLandmarks(
canvasCtx,
Object.values(POSE_LANDMARKS_LEFT)
.map(index => results.poseLandmarks[index]),
{ visibilityMin: 0.65, color: 'white', fillColor: 'rgb(255,138,0)' });
drawLandmarks(
canvasCtx,
Object.values(POSE_LANDMARKS_RIGHT)
.map(index => results.poseLandmarks[index]),
{ visibilityMin: 0.65, color: 'white', fillColor: 'rgb(0,217,231)' });
// Hands...
drawConnectors(
canvasCtx, results.rightHandLandmarks, HAND_CONNECTIONS,
{ color: 'white' });
drawLandmarks(
canvasCtx, results.rightHandLandmarks, {
color: 'white',
fillColor: 'rgb(0,217,231)',
lineWidth: 2,
radius: (data) => {
return lerp(data.from.z, -0.15, .1, 10, 1);
}
});
drawConnectors(
canvasCtx, results.leftHandLandmarks, HAND_CONNECTIONS,
{ color: 'white' });
drawLandmarks(
canvasCtx, results.leftHandLandmarks, {
color: 'white',
fillColor: 'rgb(255,138,0)',
lineWidth: 2,
radius: (data) => {
return lerp(data.from.z, -0.15, .1, 10, 1);
}
});
// Face...
drawConnectors(
canvasCtx, results.faceLandmarks, FACEMESH_TESSELATION,
{ color: '#C0C0C070', lineWidth: 1 });
drawConnectors(
canvasCtx, results.faceLandmarks, FACEMESH_RIGHT_EYE,
{ color: 'rgb(0,217,231)' });
drawConnectors(
canvasCtx, results.faceLandmarks, FACEMESH_RIGHT_EYEBROW,
{ color: 'rgb(0,217,231)' });
drawConnectors(
canvasCtx, results.faceLandmarks, FACEMESH_LEFT_EYE,
{ color: 'rgb(255,138,0)' });
drawConnectors(
canvasCtx, results.faceLandmarks, FACEMESH_LEFT_EYEBROW,
{ color: 'rgb(255,138,0)' });
drawConnectors(
canvasCtx, results.faceLandmarks, FACEMESH_FACE_OVAL,
{ color: '#E0E0E0' });
drawConnectors(
canvasCtx, results.faceLandmarks, FACEMESH_LIPS,
{ color: '#E0E0E0' });
canvasCtx.restore();
}
const holistic = new Holistic({
locateFile: (file) => {
return `https://cdn.jsdelivr.net/npm/@mediapipe/holistic@0.3.1620694839/${file}`;
}
});
holistic.onResults(onResults);
/**
* Instantiate a camera. We'll feed each frame we receive into the solution.
*/
const camera = new Camera(videoElement, {
onFrame: async () => {
await holistic.send({ image: videoElement });
},
width: 1280,
height: 720
});
camera.start();
// Present a control panel through which the user can manipulate the solution
// options.
new ControlPanel(controlsElement, {
selfieMode: true,
modelComplexity: 1,
smoothLandmarks: true,
minDetectionConfidence: 0.5,
minTrackingConfidence: 0.5
})
.add([
new StaticText({ title: 'MediaPipe Holistic' }),
fpsControl,
new Toggle({ title: 'Selfie Mode', field: 'selfieMode' }),
new Slider({
title: 'Model Complexity',
field: 'modelComplexity',
discrete: ['Lite', 'Full', 'Heavy'],
}),
new Toggle(
{ title: 'Smooth Landmarks', field: 'smoothLandmarks' }),
new Slider({
title: 'Min Detection Confidence',
field: 'minDetectionConfidence',
range: [0, 1],
step: 0.01
}),
new Slider({
title: 'Min Tracking Confidence',
field: 'minTrackingConfidence',
range: [0, 1],
step: 0.01
}),
])
.on(options => {
videoElement.classList.toggle('selfie', options.selfieMode);
holistic.setOptions(options);
});
|
import VueFetch, { $fetch } from '../../plugins/fetch'
export function getProfile(username) {
return $fetch(`users/${username}/profile/`)
.then(res => res)
.catch(err => {
console.log(err);
throw err;
});
}
export function editProfile(userUsername, dateOfBirth, profileBio) {
return $fetch(`users/${userUsername}/profile/`, {
method: 'put',
body: JSON.stringify({
date_of_birth: dateOfBirth,
bio: profileBio
})
})
.then(res => res)
.catch(err => console.log(err));
}
export function editPhoto(userUsername, profilePhoto) {
return $fetch(`users/${userUsername}/profile/`, {
method: 'put',
body: JSON.stringify({
photo: profilePhoto
})
})
.then(res => res)
.catch(err => console.log(err));
}
export function editUserEmail(userId, userEmail) {
return $fetch(`users/${userId}/`, {
method: 'put',
body: JSON.stringify({
email: userEmail
})
})
.then(res => res)
.catch(err => {
console.log(err);
throw err;
});
}
export function changePassword(oldPassword, newPassword) {
return $fetch(`change-password/`, {
method: 'put',
body: JSON.stringify({
old_password: oldPassword,
new_password: newPassword
})
})
.then(res => res.json())
.catch(err => {
console.log(err);
throw err;
});
}
export function createSocialAccount(profileId, network, nichandle, userId) {
return $fetch(`users/social-account/`, {
method: 'post',
body: JSON.stringify({
account: profileId,
network: network,
nichandle: nichandle,
user: userId
})
})
.then(res => res)
.catch(err => {
console.log(err);
throw err;
});
}
export function deleteSocialAccount(socialAccountId) {
return $fetch(`users/social-account/${socialAccountId}/delete/`, {
method: 'delete',
body: JSON.stringify({
id: socialAccountId
})
})
.then(res => res.json())
.catch(err => console.log(err));
}
export function deletePhoto(profileId) {
return $fetch(`remove-photo/${profileId}/`, {
method: 'put',
body: JSON.stringify({
id: profileId
})
})
.then(res => res.json())
.catch(err => console.log(err));
}
|
/* eslint-env mocha */
const bfs = require('../../../src').algorithms.search.bfs;
const assert = require('assert');
describe('BFS', () => {
it('should perform bfs on a tree', () => {
const tree = {
root: {
name: 'root',
children: [{
name: 'child_1',
children: [{
name: 'child_4',
children: []
}, {
name: 'child_5',
children: []
}]
}, {
name: 'child_2',
children: [{
name: 'child_6',
children: []
}]
}, {
name: 'child_3',
children: [{
name: 'child_7',
children: []
}]
}]
}
};
const children = [];
bfs(tree.root, 'children', node => children.push(node.name));
assert.deepStrictEqual(
children, [
'root',
'child_1',
'child_2',
'child_3',
'child_4',
'child_5',
'child_6',
'child_7'
]
);
});
});
|
$(document).ready(function(){
$('#lg_login').on('click', function() {
var conn = null;
conn = new Easemob.im.Connection();
$('body').on('click', '#lg_login', function() {
var username = $("#lg_username").val();
var pass = $("#lg_password").val();
conn.open({
user : username,
pwd : pass,
appKey : 'kuaiju#xiaojianproperty'
});
});
conn.init({
onOpened : function() {
conn.setPresence();
addCookie("my_conn", conn, 1);
window.location.href="jsp/home.jsp";
}
});
});
});
function addCookie(name,value,expiresHours){
var cookieString=name+"="+escape(value);
//判断是否设置过期时间
if(expiresHours>0){
var date=new Date();
date.setTime(date.getTime+expiresHours*3600*1000);
cookieString=cookieString+"; expires="+date.toGMTString();
}
document.cookie=cookieString;
}
|
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import PropTypes from 'prop-types';
import s from './ShortList';
export default class ShortList extends Component {
render() {
let listItems = [];
listItems = this.props.data.map(item => (
<li key={item.id} className={s.shortListItem}>
<div className={s.itemDetails}>
<p className={s.itemName}>{item.title}</p>
<Link to={item.item} className={s.itemSubDetails}><span>{item.item.name}</span></Link>
</div>
</li>
));
return (
<div>
<h4 className={s.shortListTitle}>{this.props.title}</h4>
<ul className={s.list}>
{ listItems }
</ul>
<Link to={this.props.showMoreLink} className={s.viewAll}><span>{this.props.showMore}</span></Link>
</div>
);
}
}
ShortList.defaultProps = {
data: [],
title: null,
showMoreLink: null,
showMore: 'View All',
};
ShortList.propTypes = {
data: PropTypes.array,
title: PropTypes.string,
showMoreLink: PropTypes.string,
showMore: PropTypes.string,
};
|
// @flow
import * as React from 'react';
import { findDOMNode } from 'react-dom';
import classNames from 'classnames';
import _ from 'lodash';
import { addStyle, getWidth } from 'dom-lib';
import { defaultProps } from '../utils';
import bindElementResize, { unbind as unbindElementResize } from 'element-resize-event';
const omitProps = [
'placement',
'shouldUpdatePosition',
'arrowOffsetLeft',
'arrowOffsetTop',
'positionLeft',
'positionTop',
'getPositionInstance',
'getToggleInstance',
'autoWidth'
];
const resizePlacement = [
'topLeft',
'topRight',
'leftBottom',
'rightBottom',
'auto',
'autoVerticalLeft',
'autoVerticalRight',
'autoHorizontalBottom'
];
type Props = {
classPrefix?: string,
className?: string,
getPositionInstance?: () => any,
getToggleInstance?: () => any,
placement?: string,
autoWidth?: boolean
};
class MenuWrapper extends React.Component<Props> {
menuElement = null;
bindMenuRef = ref => {
this.menuElement = ref;
};
componentDidMount() {
const { autoWidth } = this.props;
if (resizePlacement.includes(this.props.placement)) {
bindElementResize(this.menuElement, this.handleResize);
}
if (autoWidth) {
this.updateMenuStyle();
}
}
componentWillUnmount() {
if (this.menuElement) {
unbindElementResize(this.menuElement);
}
}
updateMenuStyle() {
const { getToggleInstance } = this.props;
if (this.menuElement && getToggleInstance) {
const instance = getToggleInstance();
if (instance && instance.toggle) {
const width = getWidth(findDOMNode(instance.toggle));
addStyle(this.menuElement, 'min-width', `${width}px`);
}
}
}
handleResize = () => {
const { getPositionInstance } = this.props;
const instance = getPositionInstance ? getPositionInstance() : null;
if (instance) {
instance.updatePosition(true);
}
};
render() {
const { className, classPrefix, ...rest } = this.props;
return (
<div
{..._.omit(rest, omitProps)}
ref={this.bindMenuRef}
className={classNames(classPrefix, className)}
/>
);
}
}
const enhance = defaultProps({
classPrefix: 'picker-menu'
});
export default enhance(MenuWrapper);
|
Component({
properties: {
name: {
type: String,
value: ""
},
//弹窗类型:modal:模态框 slot:自定义弹窗
type: {
type: String,
value: ""
},
//默认关闭蒙版关闭弹窗
hidden: {
type: Boolean,
value: true
},
//弹窗标题
title: {
type: String,
value: '提示'
},
//弹窗内容信息
content: {
type: String,
value: ''
},
//默认显示取消按钮
showCancel: {
type: Boolean,
value: true
},
//取消按钮文字
cancelTxt: {
type: String,
value: '取消'
},
//取消按钮字体颜色
cancelColor: {
type: String,
value: ''
},
//默认展示确定按钮
showConfirm: {
type: Boolean,
value: true
},
//确定按钮文字
confirmTxt: {
type: String,
value: '确定'
},
//确定按钮字体颜色
confirmColor: {
type: String,
value: ''
}
},
data: {
text: "text",
},
methods: {
// 点击蒙版关闭弹窗
hideModal: function () {
this.setData({
hidden: true,
})
},
// 确定按钮单击事件监听
confirm: function () {
this.hideModal()
var myEventDetail = {} // detail对象,提供给事件监听函数
var myEventOption = {} // 触发事件的选项
this.triggerEvent('confirm', myEventDetail, myEventOption)
},
// 取消按钮单击事件监听
cancel: function () {
var myEventDetail = {} // detail对象,提供给事件监听函数
var myEventOption = {} // 触发事件的选项
this.triggerEvent('cancel', myEventDetail, myEventOption)
}
}
})
|
//add by mingwei0727w 2015/07017
PRODUCT_NON_SPEC = "無規格";
CURRICULUM_SETTING = "課程設定";
POINT_OUT = "提示";
THIS_CURRICULUM_IS_SELL_CANT_DELETE_MESSAGE = "該課程已經售出,不可以刪除!";
PRODUCT_DETAIL = "商品細項";
CURRICULUM_DETAIL = "課程細項";
PEOPLE_COUNT = "人數";
NEW_ONE_ITEM = "新增";
SAVE_COMPLETE = "保存成功";
SAVE_FAIL = "保存失敗";
|
'use strict';
const passport = require('passport');
const Strategy = require('passport-http-bearer').Strategy;
const userModel = require('../models').users;
const jwt = require('jsonwebtoken');
var passportHandle = passport.use(new Strategy(
function(token, cb, user) {
jwt.verify(token, 'shhhhh', function (err, decoded) {
if (!decoded) {
return cb(null, false);
}
userModel.findById(decoded.id).then(function(user) {
//if (err) { return cb(err); }
if (!user) { return cb(null, false); }
return cb(null, user);
});
})
}));
module.exports = passportHandle;
|
/*global console, alert*/
/*
start whit letters, underscore, $
var = JvaScript Variable Keyword
myprice = Variable Name
( = ) = Assignment Operator
100 = Variable Value
*/
var myOldPrice = 2000,
myNewPrivce = 900,
myDiscount = myOldPrice - myNewPrivce + 500;
document.getElementById("price").innerHTML = myDiscount;
|
import request from '@/utils/request'
export function publish(article) {
return request({
url: '/publish',
method: 'post',
data: article
})
}
export function getArticleById(id) {
return request({
url: `/article/${id}`,
method: 'get'
})
}
export function getTags() {
return request({
url: '/tag/list',
method: 'get'
})
}
export function getTypes() {
return request({
url: '/type/list',
method: 'get'
})
}
|
import React from "react";
import { connect } from "react-redux";
import { addTask } from "../../actions/";
import setNewTask from "../../hoc/setNewTask";
class Form extends React.Component {
render() {
const {
text,
handleOption,
handleChange,
isValidField,
getClassName
} = this.props;
return (
<form
onSubmit={this.handleSubmit}
className="add-card-form add-card-form-true"
>
<div className="add-card-form__header">
<div onClick={handleOption} className="form__low-pr">
<input
className="form__checkbox"
type="radio"
name="priority"
value="card-color-low"
alt="Low Priority"
/>
<label className="form__label" htmlFor="Low Priority">
Low Priority
</label>
</div>
<div onClick={handleOption} className="form__med-pr">
<input
className="form__checkbox"
type="radio"
name="priority"
value="card-color-med"
alt="Med Priority"
/>
<label className="form__label" htmlFor="Med Priority">
Med Priority
</label>
</div>
<div onClick={handleOption} className="form__high-pr">
<input
className="form__checkbox"
type="radio"
name="priority"
value="card-color-high"
alt="High Priority"
/>
<label className="form__label" htmlFor="High Priority">
High Priority
</label>
</div>
</div>
<textarea
className={getClassName()}
type="text"
placeholder="Write your task"
value={text}
onChange={handleChange}
/>
<div className="add-card-form__footer">
<div className="form__footer">
<div className="form__footer-av">
<img src={require("../../assets/img/thompson.jpg")} />
</div>
<div className="attach-ico">
<i className="material-icons">attach_file</i>
</div>
</div>
<input
className="form-add-btn"
type="submit"
value="Add"
disabled={!isValidField()}
/>
</div>
</form>
);
}
handleSubmit = ev => {
const { addTask } = this.props;
ev.preventDefault();
addTask(this.props);
};
}
export default connect(
null,
{ addTask }
)(setNewTask(Form));
|
var searchData=
[
['error',['error',['../class_sndfile_handle.html#a3918868973e847faad5427697a2ed610',1,'SndfileHandle']]]
];
|
//delete for bonus #1
// var victimCount = prompt("How many victims do you wish to enter?")
// var names = []
// var phoneNumbers = []
// var streets = []
// for (i = 0; i < victimCount; i++) {
// names.push(prompt("What is their name?"))
// phoneNumbers.push(prompt("What is their phone number?"))
// streets.push(prompt("What is their street?"))
// }
// Bonus #1 code
// while (cont) {
// names.push(prompt("What is their name?"))
// phoneNumbers.push(prompt("What is their phone number?"))
// streets.push(prompt("What is their street?"))
// cont = confirm("Add another?")
// }
// var volunteerCount = prompt("How many volunteers are needed?")
// var volunteers = []
// var volunteerNames = []
// var volunteerPhones = []
// var volunteerStreets = []
// for(i = 0; i < volunteerCount; i++) {
// var volunteerInfo = {
// volName: "",
// volPhone: "",
// volStreet: ""
// }
// volunteerInfo.volName= prompt("What is their name?")
// volunteerInfo.volPhone = prompt("What is their phone number?")
// volunteerInfo.volStreet = prompt("What is their street?")
// volunteers.push(volunteerInfo)
// }
// console.log(volunteers)
// for (i = 0; i < volunteerCount; i++) {
// volunteerNames.push(prompt("What is their name?"))
// volunteerPhones.push(prompt("What is their phone number?"))
// volunteerStreets.push(prompt("What is their street?"))
// }
// alert("# of persons in need: " + victimCount + "\n# of volunteers: " + volunteerCount + "\nVictims: " + names + "\nVolunteers: " + volunteerNames)
// Bonus #2 code
// var personInNeed = prompt("Who is in need?")
// var streetInNeed = ""
// for (i = 0; i < names.length; i++) {
// if (personInNeed === names[i]) {
// streetInNeed = streets[i]
// }
// }
// for (n = 0; n < streets.length; n++) {
// if (streetInNeed === volunteerStreets[n]) {
// alert("The closest volunteer is " + volunteerNames[n])
// }
// }
angular.module('modSquad', [])
angular.module('modSquad')
.controller('squadRoller', ['$scope', function($scope) {
$scope.firstName = "First Name"
$scope.phoneNumber = "xxx-xxx-xxxx"
$scope.street = "Your Street"
$scope.victims = []
$scope.subVic = function(event) {
$scope.vicInfo = {
firstName: "",
phone: "",
street: ""
}
$scope.vicInfo.firstName = $scope.firstName
$scope.vicInfo.phone = $scope.phoneNumber
$scope.vicInfo.street = $scope.street
$scope.victims.push(vicInfo)
}
console.log($scope.victims)
}])
|
import { combineReducers } from "redux";
import authReducer from "./auth";
import hireReducer from "./hires";
import jobReducer from "./jobs";
import posterReducer from "./posters";
import profileReducer from "./profile";
import notifReducer from "./notifications";
const rootReducer = {
auth: authReducer,
hire: hireReducer,
job: jobReducer,
poster: posterReducer,
profile: profileReducer,
notif: notifReducer
};
export default combineReducers(rootReducer);
|
var basePath = window.document.location.href;
basePath = basePath.substring(0,basePath.lastIndexOf('/'))+"/";
function all_read(obj){
var c = document.getElementsByClassName("col-md-1 glyphicon glyphicon-envelope");
for(var i = 0 ; i < c.length; i++){
if(c[i].style.color == "darkkhaki"){
$(c[i]).parent().siblings("input").prop("checked", true);
//console.log($(c[i]).siblings("input"));
//$(c[i]).siblings("input").get()[0].checked = true;
//c[i].previousSibling.checked = true;
}else{
$(c[i]).parent().siblings("input").prop("checked", false);
}
}
}
//-------------------------------转发------------------------------------------------
function transpond(obj){
var id = document.getElementById("sendMailId").innerText;
var time = document.getElementById("time").innerText;
window.location.href = basePath+"transpond.do?time="+time+"&"+"id="+id;
}
//--------------------------单个未读--------------------------------------------
function noread(obj){
var id = document.getElementById("sendMailId").innerText;
var time = document.getElementById("time").innerText;
$.ajax({
type:"post",
url:basePath+"noReadFun.do",
data:"time="+time+"&"+"id="+id,
success:function(data){
document.getElementById("noread_mail").innerText = data[0];
if(data == time){
//v.parent();
}
}
});
}
//---------------------点击星标按钮改变星标状态-------------------------------------------------
function change_star1(obj){
var id = document.getElementById("sendMailId").innerText;
var time = document.getElementById("time").innerText;
$.ajax({
type:"post",
url:basePath+"starColor.do",
data:"color="+color+"&"+"id="+s22+"&"+"time="+s33,
success:function(data){
}
});
}
//----------------------------取消星标-------------------------------------------------------
function nochange_star1(obj){
var id = document.getElementById("sendMailId").innerText;
var time = document.getElementById("time").innerText;
$.ajax({
type:"post",
url:basePath+"starColor.do",
data:"color="+"black"+"&"+"id="+s22+"&"+"time="+s33,
success:function(data){
}
});
}
//-------------加入已发送----------------------------
function asend(obj){
var id = document.getElementById("sendMailId").innerText;
var time = document.getElementById("time").innerText;
$.ajax({
type:"post",
url:basePath+"asend.do",
data:"time="+time+"&"+"id="+id,
success:function(data){
}
});
}
//-------------------全部标记为已读---------------------------------------------
function asend_box(){
var id = document.getElementById("sendMailId").innerText;
var time = document.getElementById("time").innerText;
$.ajax({
type:"post",
url:basePath+"inbox1.do",
data:"time="+time+"&"+"id="+id,
success:function(data){
}
});
}
//-------------------单个已读---------------------------------------------------
function read(obj){
var id = document.getElementById("sendMailId").innerText;
var time = document.getElementById("time").innerText;
$.ajax({
type:"post",
url:basePath+"allReadFun.do",
data:"time="+time+"&"+"id="+id,
success:function(data){
document.getElementById("noread_mail").innerText = data[0];
if(data == time){
//v.parent();
}
}
});
}
//-------------------------------举报------------------------------------------------
function report(obj){
var id = document.getElementById("sendMailId").innerText;
var time = document.getElementById("time").innerText;
alert(id);
$.ajax({
type:"post",
url:basePath+"report.do",
data:"time="+time+"&"+"id="+id,
success:function(data){
}
});
}
function deleteTrue(obj){ //彻底删除
var id = document.getElementById("sendMailId").innerText;
var time = document.getElementById("time").innerText;
alert(id);
$.ajax({
type:"post",
url:basePath+"deleteTrue.do",
data:"time="+time+"&"+"id="+id,
success:function(data){
}
});
/*var a = document.getElementById("page_num").value-1;
window.location.href = basePath+"readAll_Inbox.do?pageNum="+a;*/
}
//---------------------------------删除-----------------------------------------------
function delete1(obj){ //加入删除状态
var id = document.getElementById("sendMailId").innerText;
var time = document.getElementById("mail_id").innerText;
alert(time+"1");
$.ajax({
type:"post",
url:basePath+"delete1.do",
data:"time="+time+"&"+"id="+id,
success:function(data){
alert("111");
}
});
/*for(var i = 1 ; i < c.length; i++){
var b = c[i].checked;
if(b == true){
var v = $(c[i]);
var id = v.siblings()[1].children[0].innerText;
var time = v.siblings()[3].children[0].innerText;
v.parent()[0].style.display = "none";
//var num = v.parent().parent().siblings()[4].children[0].children[0].children[1].innerText;
//num = num - 1;
//v.parent().parent().siblings()[4].children[0].children[0].children[1].innerText = num;
//console.log(v.parent().parent().siblings()[4].children[0].children[0].children[1].innerText);
}
}*/
/*var a = document.getElementById("page_num").value-1;
window.location.href = basePath+"readAll_Inbox.do?pageNum="+a;*/
}
function all_noread(obj){
var c = document.getElementsByClassName("col-md-1 glyphicon glyphicon-envelope");
for(var i = 0 ; i < c.length; i++){
if(c[i].style.color == "darkkhaki"){
console.log($(c[i]).parent().siblings("input"));
$(c[i]).parent().siblings("input").prop("checked", false);
//console.log($(c[i]).siblings("input"));
//$(c[i]).siblings("input").get()[0].checked = true;
//c[i].previousSibling.checked = true;
}else{
console.log($(c[i]).parent().siblings("input"));
$(c[i]).parent().siblings("input").prop("checked", true);
}
}
}
function all_no(obj){
var c = document.getElementsByClassName("col-md-1");
for(var i = 0 ; i < c.length; i++){
c[i].checked = false;
}
}
function all_check(obj){
var c = document.getElementsByClassName("col-md-1");
for(var i = 0 ; i < c.length; i++){
c[i].checked = true;
}
}
function change_mail(obj){
$(obj).children().css("color","darkkhaki");
}
var i = 1;
function change_star(obj){
if(i == 0){
$(obj).css("color","slategray");
i = 1;
}else{
$(obj).css("color","#FAD04D");
i = 0;
}
}
function change_color(obj){
var s1 = $(obj).parent();
var s2 = $(obj).is(":checked");
if(s2 == true){
s1.css("background-color","#528BCB");
}else{
s1.css("background-color","white");
}
}
function yc(){
$("#yc_div_1").css("display","inline");
}
function yc_l(){
$("#yc_div_1").css("display","none");
}
function on_back(obj){
$(obj).css("display","none");
$(obj).next().css("display","inline");
}
|
class Form
{
constructor(formSelector, fields) {
this.formSelector = formSelector;
this.fieldSet = fields;
this.validator = new Validator(this);
}
fieldSetValidate() {
this.fieldSet.forEach(function (field) {
field.validate();
});
}
}
class Field
{
constructor(type, selector) {
this.type = type;
this.selector = selector;
this.validator = new Validator(this);
this.validateSet = [this.checkEmpty];
}
checkEmpty(context) {
let domElement = document.querySelector(context.selector);
if(!domElement.value) {
context.validator.generateError('Can not be empty!');
}
}
validate() {
let self = this;
this.validateSet.forEach(function (validateMethod) {
validateMethod(self);
})
}
}
class TextField extends Field
{
constructor(type, selector) {
super(type, selector);
this.validateSet.push(this.textValidate);
}
textValidate(context)
{
let domElement = document.querySelector(context.selector);
if(domElement.value.match(/"/i) || domElement.value.match(/'/i)) {
context.validator.generateError('Contains \" \' symbol(s)');
}
if(domElement.value.length > 0 && domElement.value.length < 3) {
context.validator.generateError('Text should has more than 2 charts');
}
}
}
class PassField extends Field
{
constructor(type, selector, passwordConfirmation) {
super(type, selector);
this.passwordConfirmation = passwordConfirmation;
this.validateSet.push(this.passwordValidate);
}
passwordValidate(context)
{
let domElement = document.querySelector(context.selector);
let conf = document.querySelector(context.passwordConfirmation.selector);
if(domElement.value !== conf.value) {
context.validator.generateError('Password does not match!');
}
}
}
class EmailField extends Field
{
constructor(type, selector) {
super(type, selector);
this.validateSet.push(this.emailValidate);
}
emailValidate(context)
{
let domElement = document.querySelector(context.selector);
let regExp = "([a-z0-9_-]+\.)*[a-z0-9_-]+@[a-z0-9_-]+(\.[a-z0-9_-]+)*\.[a-z]{2,6}$";
if(!domElement.value.match(regExp)) {
context.validator.generateError('E-mail does not correct! E-mail should contains @');
}
}
}
class ErrorGenerator
{
constructor() {
this.errorContainer = document.createElement('div');
console.log(this.errorContainer);
}
generate(errorText) {
this.errorContainer.className = 'error';
this.errorContainer.style.color = 'red';
this.errorContainer.innerHTML = errorText;
return this;
}
getError()
{
return this.errorContainer;
}
}
class Validator
{
constructor(element) {
this.element = element;
this.errorGenerator = new ErrorGenerator();
}
generateError(text) {
let error = this.errorGenerator.generate(text).getError();
let domElement = document.querySelector(this.element.selector);
domElement.parentElement.insertBefore(error, domElement);
domElement.style.borderColor = 'red';
domElement.focus();
}
removeErrorStyles() {
const errors = document.querySelectorAll('.error');
if (errors.length) {
errors.forEach(function (error) {
error.nextSibling.style.borderColor = 'green';
error.remove();
});
}
}
}
class Submit
{
constructor(form, selector) {
this.form = form;
this.selector = selector;
}
init() {
let self = this;
let formElement = document.querySelector('#form');
formElement.addEventListener('submit', function (event) {
event.preventDefault();
self.form.validator.removeErrorStyles();
self.form.fieldSetValidate();
if(formElement.querySelectorAll('.error').length <= 0) {
document.querySelector('.modal').style.display = 'block';
}
})
}
}
const passConfirmField = new Field('passwordConfirmation', '.passwordConfirmation');
const fields = [
new TextField('fname', '.firstName'),
new TextField('lname', '.lastName'),
new TextField('birthday', '.birthday'),
new TextField('country', '.country'),
new TextField('address', '.address'),
passConfirmField,
new PassField('password', '.password', passConfirmField),
new EmailField('email', '.email'),
new TextField('note', '.note'),
];
const form = new Form('.form', fields);
const submit = new Submit(form);
submit.init();
|
import React, {Component} from 'react';
import {ToastAndroid,Button, StyleSheet, Text, TextInput, Picker, View,
Switch, CheckBox, Slider} from 'react-native';
export default class AppBanco extends Component {
constructor(props) {
super(props);
this.state = {
mail:false,
cuit:0,
moneda:1,
capitalInicial:0,
capitalFinal:0,
dias:1,
monto:0,
swtichValue: false
};
this.hacerPlazoFijo = this.hacerPlazoFijo.bind(this);
this.buscarInteres = this.buscarInteres.bind(this);
}
hacerPlazoFijo(){
if(this.state.mail == '' && this.state.cuit <= 0 || this.state.cuit == '' && this.state.monto === 0 || this.state.monto == ''){
ToastAndroid.show('Faltan datos',
ToastAndroid.LONG);
}else{
var interes = this.state.monto * (Math.pow(1+this.buscarInteres()/100,this.state.dias/360)-1);
this.setState({capitalFinal:this.state.monto+interes});
ToastAndroid.show('Plazo fijo realizado',
ToastAndroid.LONG);
}
}
buscarInteres(){
if(this.state.monto>0 && this.state.monto<=5000)
{
if(this.state.dias < 30){
return 25;
}else{
return 27.5;
}
}else{
if(this.state.monto>5000 && this.state.monto<=99999){
if(this.state.dias < 30){
return 30;
}else{
return 32.3;
}
}else{
if(this.state.monto>99999){
if(this.state.dias < 30){
return 35;
}else{
return 38.5;
}
}
}
}
}
render() {
return (
<View style={styles.container}>
<Text>
Correo Electronico
</Text>
<TextInput
onChangeText={(text) => this.setState({ mail: text})}
value4 = {this.state.mail}
keyboardType='email-address'>
</TextInput>
<Text>
CUIT
</Text>
<TextInput
onChangeText={(text) => this.setState({ cuit: text})}
value5 = {this.state.cuit}
keyboardType='numeric'>
</TextInput>
<Text>
Moneda
</Text>
<Picker
style={{width: 200}}
selectedValue={this.state.moneda}
onValueChange={(valor) => this.setState({moneda:valor})}>
<Picker.Item label="Dolar" value="1" />
<Picker.Item label="Pesos ARS" value="2" />
</Picker>
<Text>
Monto
</Text>
<TextInput
keyboardType='numeric'
onChangeText={(text) => this.setState({ monto: text})}
value1 = {this.state.monto}>
</TextInput>
<Text>
Dias
</Text>
<Slider
minimumValue={1}
maximumValue={30}
style={{ width: 300 }}
step={1}
value2 ={this.state.dias}
onSlidingComplete={val => this.setState({ dias: val })}>
</Slider>
<Text>
{this.state.dias} dias
</Text>
<Text>
Avisar por mail
</Text>
<Switch
value={this.state.swtichValue}
onValueChange={(value) => this.setState({swtichValue : value})}>
</Switch>
<View style={{ flexDirection: 'row' }}>
<CheckBox
value3 ={this.state.checked}
onValueChange={() => this.setState({ checked: !this.state.checked })}
/>
<Text style={{marginTop: 5}}>
Acepto términos y condiciones
</Text>
</View>
<Button title="Hacer Plazo Fijo"
color="#FF0000"
onPress={this.hacerPlazoFijo}>
</Button>
<Text>
El plazo fijo con un monto de ${this.state.monto} por el plazo de {this.state.dias} días se realizó exitosamente.
</Text>
<Text>
El monto final será de ${this.state.capitalFinal}.
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'column',
justifyContent: 'flex-start',
alignItems: 'flex-start',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
|
(function () {
"use strict";
function getToDestination(age, isInsured, hasCar){
var isLicensed = age >= 16;
var isLegalDriver = isLicensed && isInsured;
if (isLegalDriver && hasCar){
console.log("Let's get in and go!");
} else if(!isLegalDriver && rideShareAvailable()){
console.log("Let's call a rideshare!");
} else{
console.log("I think my friend can give us a lift!");
}
}
function rideShareAvailable( ) {
let location = confirm ( "Is this a big city?" );
let cost = confirm ( "Do you have more than 20.00?" );
let timeOfDay = confirm ( "Is it before 1am?" );
let age = confirm ( "Are you over the age of 16?" );
if (location && cost && timeOfDay && age) {
console.log ( "An uber is availiable for you to book!" );
return true;
} else {
console.log ( "You will not be able to book an Uber!" );
}
return false;
}
getToDestination(17, true, true);
}
)()
|
import React, { createContext, useState, useEffect } from 'react';
import { ActivityIndicator, Image } from 'react-native';
import Styled from 'styled-components/native';
import AsyncStorage from '@react-native-community/async-storage';
const Loading = Styled.View`
flex: 1;
background-color: #FEFFFF;
align-items: center;
justify-content: center;
`;
const RandomUserDataContext = createContext({
getMyFeed: number => {
return [];
},
});
const RandomUserDataProvider = ({ cache, children }) => {
const [ userList, setUserList ] = useState([]);
const [ descriptionList, setDescriptionList ] = useState([]);
const [ imageList, setImageList ] = useState([]);
const getCacheData = async (key) => {
const cachedData = await AsyncStorage.getItem(key);
if (cache === false || cachedData === null) {
return undefined;
}
const cacheList = JSON.parse(cachedData);
if(cacheList.length !== 25) {
return undefined;
}
return cacheList;
};
const setCacheData = (key, data) => {
AsyncStorage.setItem(key, JSON.stringify(data));
};
const setUsers = async() => {
const cachedData = await getCacheData('UserList');
if(cachedData) {
setUserList(cachedData);
return;
}
try {
const response = await fetch('https://uinames.com/api/?amount=25&ext');
const data = await response.json();
setUserList(data);
setCacheData('UserList', data);
} catch(error) {
console.log(error);
}
};
const setDescriptions = async () => {
const cachedData = await getCacheData('DescriptionList');
if (cachedData) {
setDescriptionList(cachedData);
return;
}
try {
const response = await fetch('https://opinionated-quotes-api.gigalixirapp.com/v1/quotes?rand=t&n=25');
const data = await response.json();
let text = [];
for(const index in data.quotes) {
text.push(data.quotes[index].quote);
}
setDescriptionList(text);
setCacheData('DescriptionList', text);
} catch(error) {
console.log(error);
}
};
const setImages = async () => {
const cachedData = await getCacheData('ImageList');
if (cachedData) {
if (Image.queryCache) {
Image.queryCache(cachedData);
cachedData.map(data => {
Image.prefetch(data);
});
}
setImageList(cachedData);
return;
}
setTimeout(async () => {
try {
const response = await fetch('https://source.unsplash.com/random/');
const data = response.url;
if(imageList.indexOf(data) >= 0) {
setImages();
return;
}
setImageList([ ...imageList, data ]);
} catch(error) {
console.log(error);
}
}, 400);
};
useEffect(() => {
setUsers();
setDescriptions();
}, []);
useEffect(() => {
if (imageList.length !== 25) {
setImages();
} else {
setCacheData('ImageList', imageList);
}
}, [imageList]);
const getImages = () => {
let images = [];
const count = Math.floor(Math.random() * 4);
for (let i=0; i<=count; ++i) {
images.push(imageList[Math.floor(Math.random() * 24)]);
}
return images;
}
const getMyFeed = (number = 10) => {
let feeds = [];
for(let i=0; i<number; ++i) {
const user = userList[Math.floor(Math.random() * 24)];
feeds.push({
name: user.name,
photo: user.photo,
description: descriptionList[Math.floor(Math.random() * 24)],
images: getImages(),
});
}
return feeds;
}
console.log(`${userList.length} / ${descriptionList.length} / ${imageList.length}`);
return (
<RandomUserDataContext.Provider
value={{
getMyFeed,
}}>
{userList.length === 25 &&
descriptionList.length === 25 &&
imageList.length === 25 ? (
children
) : (
<Loading>
<ActivityIndicator color="#D3D3D3" size="large" />
</Loading>
)}
</RandomUserDataContext.Provider>
);
};
export { RandomUserDataProvider, RandomUserDataContext };
|
//login scripts
$(document).ready(function(){
Path.map('#/login').to(function() {
loginUserModal();
});
Path.map('#/login-email').to(function() {
emailLoginModal();
});
Path.map('#/forgot').to(function() {
forgotPassword();
});
Path.root("#/login");
Path.listen(true);
});
var loginContent = '<div class="loginOptions"><h3 class="gateWayTitle">Enter Orobind Pro</h3><div class="loginCard"><button class="loginCta fb">Facebook</button><p class="label">Connect via Facebook</p><div class="divider"><span class="dividerText">or</span></div><button class="loginCta gp">Google</button><p class="label">Connect via Google+</p><div class="divider"><span class="dividerText">or</span></div><button class="loginCta em">Email</button><p class="label">Login with your email</p></div><a href="#" class="existing">New User?</a></div>';
var loginEmailContent = '<div class="loginEmail"><h3 class="gateWayTitle">Login with Email</h3><button class="back"><i class="fa fa-long-arrow-left"></i> Back</button><div class="loginCard"><input type="text" class="loginField" name="email" placeholder="Email"><input type="password" class="loginField" name="password" placeholder="••••••••"><button class="loginCta em">Login</button></div><a href="#/forgot" class="existing">Forgot your password?</a></div>';
var forgotPwContent = '<div class="forgotPw"><h3 class="gateWayTitle">Forgot Password?</h3><p class="success">An email has been sent to you with a link to reset the password.</p><p class="error">Invalid email address. Please try again with the correct email.</p><button class="back"><i class="fa fa-long-arrow-left"></i> Back</button><div class="forgotCard"><input type="text" class="loginField" name="email" placeholder="Email"><button class="loginCta em">Reset Password</button></div></div>';
function loginUserModal(){
showModalMessage({
"class":"gateWayModal",
"closable":"0",
"content":loginContent,
"nobutton":true,
"timed":"0",
"size":"small"
});
}
function emailLoginModal(){
showModalMessage({
"class":"gateWayModal",
"closable":"0",
"content":loginEmailContent,
"nobutton":true,
"timed":"0",
"size":"small"
});
}
function forgotPassword(){
showModalMessage({
"class":"gateWayModal",
"closable":"0",
"content":forgotPwContent,
"nobutton":true,
"timed":"0",
"size":"small"
});
}
function closeModals(){
$(".messageModal").fadeOut(150);
}
$(document).on("click",".loginCta.em",function(){
window.location.hash = "#/login-email";
});
$(document).on("click",".forgotPw .back",function(){
window.location.hash = "#/login-email";
});
$(document).on("click",".loginEmail .back",function(){
window.location.hash = "#/login";
});
|
export {default as calendarSvg} from './calendar.svg';
export {default as clockSvg} from './clock.svg';
export {default as commitSvg} from './commit.svg';
export {default as configureSvg} from './configure.svg';
export {default as doneSvg} from './done.svg';
export {default as failSvg} from './fail.svg';
export {default as playSvg} from './play.svg';
export {default as rebuildSvg} from './rebuild.svg';
export {default as settingsSvg} from './settings.svg';
export {default as stopwatchSvg} from './stopwatch.svg';
export {default as userSvg} from './user.svg';
export {default as clearInputSvg} from './clear-input.svg';
export {default as emptySvg} from './empty.svg';
|
import {StyleSheet} from 'react-native';
export default StyleSheet.create({
titleText: {
fontSize: 20,
fontWeight: '600',
color: '#333',
},
boldText: {
marginLeft: 5,
marginRight: 5,
fontSize: 15,
fontWeight: '600',
color: '#333',
},
link: {
color: '#2199d8',
},
itemContainer: {
height: 50,
width: '100%',
paddingHorizontal: 15,
justifyContent: 'center',
alignItems: 'center',
borderBottomWidth: 1,
borderBottomColor: '#333',
},
itemText: {
width: '100%',
fontFamily: 'SFUIText-Medium',
fontSize: 14,
color: '#222',
},
textInputContainer: {
width: '100%',
height: 100,
paddingHorizontal: 15,
justifyContent: 'center',
alignItems: 'center',
// backgroundColor: "#189"
},
textInputStyle: {
width: '100%',
borderBottomColor: '#414244',
borderBottomWidth: 1,
fontFamily: 'SFUIText-Medium',
fontSize: 14,
color: '#222',
},
});
|
import React, { Component } from 'react';
import { Modal, Input } from 'antd';
import '../../static/css/shortcut.css';
class ChatMessageShortcut extends Component{
constructor(){
super();
this.state={
isSetShow: false
};
}
setShortcut = () => {
this.toggleSet(true);
};
shortcutFetch = () => {
let _self = this;
let shortKey = this.refs.shortKey.input.value;
let shortValue = this.refs.shortValue.textAreaRef.value;
let bodyData = 'csid='+(localStorage.getItem('uuchat.csid') || '')+'&shortcut='+shortKey+'&msg='+shortValue;
if (shortKey.replace(/^\s$/g, '') === '') {
_self.toggleSet(false);
return false;
}
fetch('/shortcuts', {
credentials: 'include',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: bodyData
}).then(d=>d.json()).then(data=>{
localStorage.setItem('newShortcut', '{"shortcut": "'+shortKey+'","msg": "'+shortValue+'", "action":"INSERT"}');
_self.toggleSet(false);
}).catch((e)=>{});
};
shortcutCancel = () => {
this.toggleSet(false);
};
toggleSet = (flag) => {
this.setState({
isSetShow: flag
});
};
render(){
let { content } = this.props;
content = content.replace(/ /g, ' ').replace(/(^\s*)/g, '').replace(/>/g, '>').replace(/</g, '<');
return (
<div className="short-item-setting" onClick={this.setShortcut}>
<Modal
title="Add a Personal Shortcut"
visible={this.state.isSetShow}
cancelText="Cancel"
okText="Save"
onCancel={this.shortcutCancel}
onOk={this.shortcutFetch}
>
<div>
<div className="set-item">
Add a personal shortcut for the text you want to expand then type <i>;</i> in chat to search for the shortcut.
</div>
<div className="set-item">
<p className="set-item-label">Shortcut</p>
<Input defaultValue="" addonBefore=";" ref="shortKey" />
<p className="set-item-label">Expanded Message</p>
<Input.TextArea defaultValue={content} ref="shortValue" />
</div>
</div>
</Modal>
</div>
);
}
}
export default ChatMessageShortcut;
|
// pages/profile/child-components/profile-list-footer/profile-list-footer.js
Component({
/**
* 组件的属性列表
*/
properties: {
},
/**
* 组件的初始数据
*/
data: {
},
/**
* 组件的方法列表
*/
methods: {
loginout() {
this.triggerEvent('loginout', {}, {})
}
}
})
|
import React, { Component } from 'react';
import './App.css';
import TabContainer from "./tabContainer";
import ContactInfo from "./contactInfo";
import AboutMe from "./aboutMe";
import Resume from "./resume";
import Projects from "./projects";
class StateController extends Component {
constructor() {
super();
this.state = {
tabArray: [],
selectedIndex: 0
};
}
componentWillMount() {
let tabArray = this._generateTabList();
this.setState({
tabArray: tabArray
});
}
_generateTabList = () => {
let appTab = {
title: 'About Me',
content: (
<div key={0}>
<AboutMe containerClass='paragraph' />
</div>
)
};
let aboutTab = {
title: 'Resume',
content: (
<div key={1}>
<Resume />
</div>
)
};
let projectsTab = {
title: 'Projects',
content: (
<div key={1}>
<Projects containerClass='projects' />
</div>
)
};
return [appTab, aboutTab, projectsTab];
};
_switchToTab = (index) => {
this.setState({
selectedIndex: index
});
};
render() {
return (
<div className='background'>
<ContactInfo containerClass='container' />
<TabContainer containerClass='tab-container'
contentContainerClass='content-container'
tabRowClass='tab-row-class'
headerClass='tab-header'
selectedHeaderClass='tab-header-selected'
titleClass='tab-title'
emptySpaceRight={(<div className='empty-tab' />)}
headerClickHandler={this._switchToTab}
selectedIndex={this.state.selectedIndex}
tabArray={this.state.tabArray} />
</div>
);
}
}
export default StateController;
|
import React,{ Component } from 'react';
import { Jumbotron, Button,Container,Row,Col,InputGroup,InputGroupAddon,Input } from 'reactstrap';
import "./ArtBoard.css";
export class ArtBoard extends Component {
render() {
return (
<div>
<Jumbotron>
<center>
<div id="jumbotron-container">
<h1 className="display-3">Upload in-house as well as out-house projects</h1>
<div>
<p className="lead mx-auto">
<Button color="primary" className="rnd-btn" size="lg">In House</Button>
<Button color="primary" className="rnd-btn1" size="lg">Out House</Button>
</p>
</div>
</div>
</center>
</Jumbotron>
<div>
<Container>
<Row>
<Col>
<div className="click">
<input className="Add-content" type="text" placeholder="Click to add files" style={{height:65,width:300}}></input>
<button type="submit" className="add-button" ><i class="fas fa-plus plus-logo fa-2x" aria-hidden="true" style={{height:65,width:65}}></i></button>
</div>
</Col>
</Row>
</Container>
Name of the project:<br></br>
<input type="text" name="Name of the project"></input>
<br></br>
Contributers name:<br></br>
<input type="text" name="Contributers name">
</input>
</div>
</div>
);
}
}
export default ArtBoard;
|
(function(app) {
'use strict';
app.populateHomeView = function() {
var el = document.getElementById('welcomeMsg');
var user = app.getUserName();
el.innerHTML = 'Welcome' + (user ? ' ' + user : '') + '!';
el = document.getElementById('activeBudgetPeriod');
var period = app.getActiveBudgetPeriod();
if (period) {
el.innerHTML = 'Period: ' +
(period.startDate ? app.formatDate(period.startDate) : '-') + ' until ' +
(period.endDate ? app.formatDate(period.endDate) : '-');
} else {
el.innerHTML = 'Period: - until -';
}
app.getTargetBudget(function(err, targetBudget) {
var el = document.getElementById('targetBudgetMsg');
if (err) {
el.innerHTML = err;
} else {
el.innerHTML = 'Your target is ' + targetBudget.toFixed(2);
app.getActualDailyBudget(function(err, dailyBudget) {
var el = document.getElementById('budgetOrb');
if (err) {
el.innerHTML = err;
} else {
var backgroundColor;
var warningMsg;
if (dailyBudget >= targetBudget) {
backgroundColor = '#05550D';
warningMsg = 'Congratulations, you are on target!';
} else {
backgroundColor = '#FF7308';
warningMsg = 'Be careful, you are overspending!';
}
var html = '<p class="dailyBudgetMsg">Daily budget</p>';
html += '<p class="dailyBudgetAmt">' + dailyBudget.toFixed(2) + '</p>'
el.innerHTML = html;
el.style.backgroundColor = backgroundColor;
el = document.getElementById('warningMsg');
el.innerHTML = warningMsg;
}
});
}
});
app.getIncomeAlerts(3, function(err, incomeAlerts) {
var el = document.getElementById('homeScreenAlerts');
if (err) {
el.innerHTML = err;
} else {
app.getExpensesAlerts(3, function(err, expensesAlerts) {
if (err) {
el.innerHTML = err;
} else {
var alerts = incomeAlerts.concat(expensesAlerts);
if (alerts.length > 0) {
var html = '<p>Alerts</p>';
html += '<ul>';
alerts.forEach(function(msg) {
html += '<li>' + msg + '</li>';
});
html += '</ul>';
el.innerHTML = html;
} else {
el.innerHTML = 'No alerts';
}
}
});
}
});
var el = document.getElementById('enterIncomeBtn');
el.addEventListener('click', function() {
app.route('actualIncomesForm', -1);
});
el = document.getElementById('enterExpenseBtn');
el.addEventListener('click', function() {
app.route('actualExpensesForm', -1);
});
el = document.getElementById('planIncomeBtn');
el.addEventListener('click', function() {
app.route('plannedIncomesTable');
});
el = document.getElementById('planExpensesBtn');
el.addEventListener('click', function() {
app.route('plannedExpensesTable');
});
el = document.getElementById('budgetReportBtn');
el.addEventListener('click', function() {
app.route('budgetReport');
});
}
app.showHomeView = function() {
app.getViewHtml('./views/home/home.html', function(err, response) {
var target = document.getElementById('appView');
if (err) {
target.innerHTML = err;
} else {
target.innerHTML = response;
app.populateHomeView();
}
});
};
})(frugalisApp);
|
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const assetSchema = new Schema(
{
japanese: {
type: String,
required: true
},
english: {
type: String,
required: true
},
creator: {
type: Schema.Types.ObjectId,
ref: 'User',
required: true
}
},
{ timestamps: true }
);
module.exports = mongoose.model('Asset', assetSchema);
|
var port = 3000;
var http=require('http');
var express=require('express');
var app = express();
var server = http.createServer(app).listen(3000, function() {
console.log('Server On puerto 3000');
});
var io = require('socket.io').listen(server);
app.get('/',function(req,res){
res.sendfile('index.html');
})
//Modulo
var Twit = require('twit');
//Keys para acceder a la api de Twitter
var T = new Twit({
consumer_key: 'T6nFO3fHOv0AH8xKkfOvAY68p',
consumer_secret: 'K3mDWeGsOuQncZ9ez5wd8S6UH4qrJ8nZP5Dc5ly2t2JqhPaXOY',
access_token: '158932605-Pw4VJXLsYk8TvQotHGQ1QTIDLmLWRbfnTYxQomNc',
access_token_secret: 'mKFL68qw3ZvwSj5VX1IfcOW9NUnaeHE9VEmdhL2HOYUNY'
});
//Filtro para los Tweets
var stream = T.stream('statuses/filter', { track: 'Messi' })
io.sockets.on('connection', function (socket) {
stream.on('tweet', function(data) {
io.sockets.emit('tweet',{
image:data.user.profile_image_url_https,
twet:data.text
});
});
});
|
import { makeStyles } from '@material-ui/core/styles';
export default makeStyles(({
iconButton: {
margin: -20,
},
icon: {
'&:hover': {
transform: 'scale(1.2)',
},
},
dialog: {
borderRadius: 30,
},
dialogTitle: {
fontSize: 20,
textAlign: 'center',
},
dialogAction: {
marginTop: -10,
marginBottom: 10,
margin: 'auto',
},
actionButton: {
margin: '0 30px',
borderRadius: 30,
width: 80,
fontWeight: '600',
},
}));
|
import {createStore, compse} from 'redux';
import {syncHistoryWithStore} from 'react-router-redux';
import {browserHistory} from 'react-router';
//import root reducer
import rootReducer from '../reducers/index';
//import default data
import comments from '../data/comments';
import posts from '../data/posts';
//create an object for default data
const defaultState = {
posts,
comments
}
//creating of store
const store = createStore(rootReducer, defaultState); //принимает корневой редюсер и дефолтное состояние
export const history = syncHistoryWithStore(browserHistory, store);
export default store;
|
//Входныой массив данных, деструктуризация
const sponsors = {
cash: [40000, 5000, 30400, 12000],
eu: ['SRL', 'PLO', 'J&K'],
rus: ['RusAuto', 'SBO']
};
const {cash, eu, rus} = sponsors;
const ownMoney = 0;
class Money {
constructor(ownMoney = 0, cash) {
this.ownMoney = ownMoney;
this.cash = cash;
}
calcCash(){
return total = this.cash.reduce((total = this.ownMoney, curr) => total += curr);
}
}
const money = new Money(ownMoney, cash);
export {eu,rus};
export default money.calcCash();
|
import React from 'react';
import ReactDOM from 'react-dom';
// import createReactClass from 'create-react-class';
import NameList from './components/NameList';
class App extends React.Component {
render() {
return (
<div>
<NameList number="1" />
<NameList number="2" />
</div>
)
}
}
ReactDOM.render(
<App />,
document.getElementById('app')
);
|
import React, { Component, PropTypes } from 'react'
import ReactDOM from 'react-dom';
import CreateOutfitItemsListItem from './CreateOutfitItemsListItem';
import CreateOutfitInfos from './CreateOutfitInfos';
import habit_img from '../src/img/habit_test.png'
import chaussure_img from '../src/img/chaussure_test.png'
import { DragDropContext } from 'react-dnd';
import HTML5Backend from 'react-dnd-html5-backend';
import CollageOutfit from './CollageOutfit';
import ItemsFilters from "../components/ItemsFilters"
import { config } from '../config.js'
const API_URL = config.API_URL;
import { Link } from "react-router";
class CreateOutfitItemsList extends Component {
constructor(props) {
super(props);
this.state = {
list: {},
validate:false,
}
}
componentDidMount() {
this.props.fetchItems();
this.props.fetchCategories();
this.props.fetchCategoriesByUser();
this.props.onRemoveAllItems();
}
hideCategory(e) {
var toHide = e.target.nextSibling;
var icnToggle = e.target.firstChild;
if (!e.target.classList.contains('visible')){
TweenLite.set(toHide, {
height: "auto"
});
TweenLite.from(toHide, 1.5, {height: 0, ease:Expo.easeOut});
icnToggle.classList.add('more');
e.target.classList.add("visible");
} else {
TweenLite.to(toHide, 1, {height: 0, ease:Expo.easeOut});
icnToggle.classList.remove("more");
e.target.classList.remove("visible");
}
}
onClickItemToList(e){
var element = e.target;
var id = element.getAttribute("data-id");
var src = element.getAttribute("data-src");
if (element.parentElement.classList.contains('selected')){
element.parentElement.classList.remove("selected");
this.props.onDeleteItem(this.props.listItems, id);
this.setState({
list: this.props.listItems
});
} else {
var img = new Image();
img.src = src;
img.onload = function(){
var height = img.naturalHeight;
var width = img.naturalWidth;
this.props.onClickItem(this.props.listItems, id, {top: 100, left: 100, width:width, height:height, zIndex:0, img:src});
this.setState({
list: this.props.listItems
});
element.parentElement.className+=" selected";
}.bind(this)
}
}
removeAll(){
var tabItem = document.getElementsByClassName("create-outfit-list-item-link");
for (var i = 0; i < tabItem.length; i++) {
tabItem[i].classList.remove("selected");
}
this.props.onRemoveAllItems();
}
render() {
const {fetchItems, dataItems, dataCategories, dataCategoriesUser, fetchCategories, fetchCategoriesByUser, onClickItem, listItems, hideSourceOnDrag, onRemoveAllItems, onUpdateItem, onDeleteItem, onClickCreateOutfitImage, onClickCreateOutfitInfos} = this.props
if (Object.keys(listItems).length!==0){
var isListItem = true;
} else {
var isListItem = false;
}
return (
<div>
<div className="app-create-outfit-collage">
<div className="app-add-item-top app-top-tools">
<Link className="btn-back-to" to="app/outfits">
<span className="btn-back-to-arrow"></span>Retour à la liste
</Link>
<div className="app-top-tools-right">
{!this.state.validate && isListItem &&
<div className="btn1 app-top-tools-right-btn" onClick={this.removeAll.bind(this)}>
Tout supprimer
</div>
}
{this.state.validate &&
<div className="btn1 app-top-tools-right-btn" onClick={(e) => this.setState({validate:false})}>
Modifier
</div>
}
</div>
</div>
<CollageOutfit
hideSourceOnDrag={true}
listItems={listItems}
onClickItem={onClickItem}
onUpdateItem={onUpdateItem}
/>
</div>
<div className="app-create-outfit-items">
{!this.state.validate &&
<div className="items-list">
{dataItems && dataCategoriesUser &&
<div>
<div className="app-item-detail-top app-top-tools">
<div className="app-top-tools-right">
{isListItem &&
<div className="btn1 app-top-tools-right-btn" onClick={()=>this.setState({validate:true})} >Valider cette tenue</div>
}
</div>
</div>
{dataCategoriesUser.map(function(category){
var jsxItems = dataItems.filter(e => e.category === category.id).map(item => <div key={item.id} className="create-outfit-list-item" data-id={item.id} onClick={this.onClickItemToList.bind(this)} ><CreateOutfitItemsListItem id={item.id} key={item.id} imgBase={API_URL+item.img} onClickItem={onClickItem} listItems={listItems} photo={API_URL+item.img190}/></div>);
return <div key={category.id} className="items-list-block app-block">
<div className="items-list-block-category visible" onClick={this.hideCategory.bind(this)} ><span className="items-list-block-category-see-more more"></span>{category.name}</div>
<div className="items-list-block-category-items">
<div className="items-list-block-category-items-inner">
{jsxItems}
<div className="items-list-item-add items-list-item">
<Link className="items-list-item-add-inner" to="/app/items/add-item">+</Link>
</div>
</div>
</div>
</div>
}.bind(this))}
</div>
}
</div>
}
{this.state.validate &&
<CreateOutfitInfos
onClickCreateOutfitImage={onClickCreateOutfitImage}
onClickCreateOutfitInfos={onClickCreateOutfitInfos}
listItems={listItems}
/>
}
</div>
</div>
)
}
}
export default DragDropContext(HTML5Backend)(CreateOutfitItemsList)
|
var WebTorrent = require('webtorrent');
var inherits = require('inherits');
var DEFAULT_MAX_TORRENTS = 1;
inherits(WebTorrentFifo, WebTorrent);
function WebTorrentFifo(opts) {
if (!(this instanceof WebTorrentFifo)) return new WebTorrentFifo(opts)
WebTorrent.call(this, opts);
if (!opts) opts = {};
this.maxConcurrentTorrents = opts.maxConcurrentTorrents || DEFAULT_MAX_TORRENTS;
}
WebTorrentFifo.prototype.add = function(torrentId, opts, ontorrent) {
// If torrent is new, check list for room.
if (this.get(torrentId) === null) {
if (this.torrents.length >= this.maxConcurrentTorrents) {
console.log("Reached maximum torrents, removing oldest torrent " + this.torrents[0].magnetURI);
this.remove(this.torrents[0].magnetURI);
}
}
return WebTorrentFifo.super_.prototype.add.call(this, torrentId, opts, ontorrent);
}
module.exports = WebTorrentFifo;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.