text
stringlengths 7
3.69M
|
|---|
const mongoCollections = require("../database-utils/mongoCollections");
const users = mongoCollections.users;
async function usernameExists(username){
username = username.toLowerCase();
const loginCollection = await users();
return await loginCollection.findOne({username: username}) !== null;
}
module.exports = {usernameExists};
|
import React from "react";
import { Container } from "reactstrap";
import { Router, Route } from "react-router-dom";
import "./App.css";
import Topbar from "./components/Topbar";
import WrapExplore from "./containers/WrapExplore";
import history from "./components/browserHistory";
import { Provider } from "react-redux";
import PropTypes from "prop-types";
import WrapTags from "./containers/WrapTags";
import WrapPhoto from "./containers/WrapPhoto";
const App = ({ store }) => (
<Provider store={store}>
<Router history={history}>
<Container>
<Topbar />
<Route exact path="/my-flickr" component={WrapExplore} />
<Route path="/my-flickr/tags/:tag" component={WrapTags} />
<Route path="/my-flickr/photos/:photo_id" component={WrapPhoto} />
</Container>
</Router>
</Provider>
);
App.propTypes = {
store: PropTypes.object.isRequired,
history: PropTypes.object.isRequired
};
export default App;
|
const styles = {
body: {
backgroundColor: '#444444',
backgroundImage: 'url("/static/images/webpage-background.jpg")',
fontFamily: '"Trebuchet MS", Roboto, sans-serif',
color: '#dbbfff',
backgroundSize: 'cover',
},
h1: {
fontSize: '55px'
},
container: {
textAlign: 'center',
},
gameWindow: {
padding: '5px',
border: '1px solid #eeeeee',
},
}
export default styles;
|
import * as ACTIONS from '../actions'
const ACTION_HANDLERS = {
//loading
[ACTIONS.DICTIONARY_LOADING_STATE]: (state, action) => (
Object.assign({}, state, {
fetching: action.result
})
),
//列表
[ACTIONS.DICTIONARY_LIST_SET]: (state, action) => (
Object.assign({}, state, {
setList: action.result
})
),//新增或修改
[ACTIONS.DICTIONARY_LIST_UPDATE_SET]: (state, action) => (
Object.assign({}, state, {
operationResult: action.result
})
),//删除
[ACTIONS.DICTIONARY_LIST_DELETE_SET]: (state, action) => (
Object.assign({}, state, {
delLoading: action.result
})
),//类型数据获取
[ACTIONS.DICTIONARY_TYPE_LIST_SET]: (state, action) => (
Object.assign({}, state, {
typeList: action.result
})
),
}
const initialState = {
fetching: false,
setList: {data:[]},
operationResult:{},
typeList:{},
delLoading:false
}
export function Reducer(state = initialState, action) {
const handler = ACTION_HANDLERS[action.type]
return handler ? handler(state, action) : state
}
export default Reducer
|
import React from 'react';
import Token from '../tokens/Token';
import { meta } from '@sparkpost/design-tokens';
import _ from 'lodash';
import color from 'color';
import { Box, Text } from '@sparkpost/matchbox';
function ColorDescription(props) {
const c = React.useMemo(() => _.find(meta, ['name', props.name]), [
props.name
]);
const isWhite = React.useMemo(() => props.name === 'color-white', [
props.name
]);
return (
<Box mb="400">
<Box
mb="300"
height="150px"
p="300"
bg={c.value}
border={isWhite ? '400' : 'none'}
borderRadius="200"
display="flex"
justifyContent="flex-start"
alignItems="flex-end"
>
<Box
fontSize="100"
lineHeight="100"
color={color(c.value).isDark() ? 'white' : 'gray.1000'}
>
{color(c.value)
.rgb()
.string()}
, {c.value}
</Box>
</Box>
{props.title ? (
<Text
fontSize="300"
lineHeight="300"
m="0"
fontWeight="medium"
color="gray.900"
>
<span>
{props.title}
<Box as="span" display="inline-block" fontSize="200" ml="200">
<Token name={c.name} />
</Box>
</span>
</Text>
) : null}
{!props.title ? <Token name={c.name} /> : null}
{props.children && (
<Box mt="100" fontSize="200" lineHeight="200" color="gray.700">
{props.children}
</Box>
)}
</Box>
);
}
export default ColorDescription;
|
angular.module('mkaApp')
.controller('userController', function($http){
/**
* variables
*/
/**
* le contrôleur
* @type {angular.controller}
*/
var _this = this;
/**
* spécifie si le contrôleur a été initié
* @type {Boolean}
*/
this.initiated = false;
/**
* objet contenant les données de l'utilisateur
* @type {Object}
*/
this.user = {};
/**
* un tableau de données utilisateurs
* @type {Array}
*/
this.users = [];
//user
this.createUser = function(){
};
this.readUser = function(user_id){
};
this.updateUser = function(user_id){
};
this.deleteUser = function(user_id){
};
this.addUsers = function(){
};
//users
this.createUsers = function(users){
};
this.readUsers = function(criteria){
};
this.updateUsers = function(users){
};
this.deleteUsers = function(users){
};
/**
* initialise le contrôleur
*/
this.init = function(){
if(!_this.initiated){
_this.initiated = true;
}
};
this.reload = function(){
_this.initiated = false;
_this.init();
}
this.init();
});
|
$(document).ready(function() {
$('#submitSignin').click(function() {
var userID = $('#IDSignin').val();
var userPwd = $('#pwdSignin').val();
var userName = $('#nameSignin').val();
var userPwd_confirm = $('#pwd_confirmSignin').val();
if (((userID == "") || (userPwd == "")) || (userName == "")) {
alert("Insert All Information!!!");
} else {
if (userPwd == userPwd_confirm) {
var json = {};
json["email"] = userID;
json["password"] = userPwd;
json["userName"] = userName;
$.ajax({
type : 'post',
url : '/signin',
data : json,
success : function(result) {
if (result.status == "FAIL") {
alert('This id already used');
} else if (result.status == "SUCCESS") {
alert('sign in success');
}
}
});
} else {
alert('confirm password not match');
}
}
});
$('#submitLogin').click(function() {
var userID = $('#IDLogin').val();
var userPwd = $('#pwdLogin').val();
if ((userID == "") || (userPwd == "")) {
alert("Insert Your Information!");
} else {
var json = {};
json["email"] = userID;
json["password"] = userPwd;
console.log("submit");
$.ajax({
type : 'post',
url : '/login',
data : json,
success : function(result) {
if (result.status == "FAIL") {
alert('nononononono ㅗ');
} else {
$(location).attr('href', '/mypage');
//move page
}
}
});
}
});
});
|
self.addEventListener('install', function(e) {
e.waitUntil(
caches.open('pomodoroClock').then(function(cache) {
return cache.addAll([
'/',
'/index.html',
'/assets/img/144.png',
'/assets/img/favicon.ico',
'/assets/DIGITALDREAM.ttf',
'/assets/beep.mp3',
'/mainfest.json',
]);
})
);
});
self.addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request)
.then(response => response || fetch(event.request))
);
});
|
function renderDrawingArea(img) {
var totalMismatch = [100];
// Look ma, no jQuery!
//Clearing html make sure that there is no interferences
document.getElementsByClassName('literally')[0].innerHTML = "";
var lc = LC.init(
document.getElementsByClassName('literally')[0],
{imageURLPrefix: './img'}
);
var context = lc.ctx;
var myImage = new Image();
myImage.src = img;
lc.setImageSize(myImage.naturalWidth, myImage.naturalHeight);
function drawImage() {
context.globalAlpha = 0.5;
context.drawImage(myImage, 0, 0);
context.globalAlpha = 1.0;
}
function updateMatch() {
var diff = resemble(lc.getImage().toDataURL())
.compareTo(myImage.src)
.onComplete(function(data){
totalMismatch.push(data.misMatchPercentage);
document.getElementById("mismatch").innerHTML =
data.misMatchPercentage + "%";
});
diff.ignoreAntialiasing();
}
document.getElementById("check").onclick = updateMatch;
document.getElementById("dl").onclick = function() {
window.open(lc.getImage().toDataURL());
};
myImage.onload = drawImage;
var unsubscribe = lc.on('drawingChange', drawImage);
var unsubscribe = lc.on('shapeSave', drawImage);
var unsubscribe = lc.on('clear', drawImage);
var unsubscribe = lc.on('undo', drawImage);
var unsubscribe = lc.on('redo', drawImage);
var unsubscribe = lc.on('primaryColorChange', drawImage);
var unsubscribe = lc.on('secondaryColorChange', drawImage);
var unsubscribe = lc.on('backgroundColorChange', drawImage);
}
var photo1 = "./paintings/ross1.jpg";
var photo2 = "./paintings/ross2.jpg";
var photo3 = "./paintings/ross3.jpg";
renderDrawingArea(photo1)
document.getElementById("photo1").addEventListener('click', function() {
renderDrawingArea(photo1);
})
document.getElementById("photo2").addEventListener('click', function() {
renderDrawingArea(photo2);
})
document.getElementById("photo3").addEventListener('click', function() {
renderDrawingArea(photo3);
})
|
$(document).ready(function () {
// Affiche les figures 5 par 5
$(".trick").slice(0, 15).show();
$("#loadMore").on("click", function (
e
) {
e.preventDefault();
$(".trick:hidden").slice(0, 5).slideDown();
if ($(".trick:hidden").length === 0) {
$("#loadMore").text("Ajouter de nouvelles figures").addClass("noContent");
}
});
});
|
baidu.frontia.social = baidu.frontia.social || {};
(function(namespace_) {
var Error = namespace_.error;
var SOCIAL_AUTH_URL_PREFIX = namespace_.DomainManager.getSocialDomain() + '/social/oauth/2.0/authorize';
var SOCAIL_GET_INFO_URL_PREFIX = namespace_.DomainManager.getSocialDomain() + '/social/api/2.0/user/info';
var PBLOGUriPrefixs = namespace_.DomainManager.getPBLogDomain() + '/pushlog';
var USERUriPrefixs = namespace_.DomainManager.getFrontiaDomain() + '/user';
/**
* Indicates the way of grant
*
* @constant
*/
var RESPONSE_TYPE = {
/* Implicit grant */
TOKEN: 'token',
/* Authorization code */
CODE: 'code'
};
/**
* Encode URL
*/
function urlencode (str) {
return encodeURIComponent(str + '');
}
/**
* URL generator
*/
function buildURL(ak, res_type, media_type, redirect_uri, state, display, client_type, scope) {
var url = SOCIAL_AUTH_URL_PREFIX + '?' +
'response_type=' + res_type + '&' +
'client_id=' + ak + '&' +
'media_type=' + media_type + '&' +
'redirect_uri=' + urlencode(redirect_uri);
if (state) {
url += '&state=' + state;
}
if (display) {
url += '&display=' + display;
}
if (client_type) {
url += '&client_type=' + client_type;
}
if (scope) {
url +='&scope=' + scope;
}
return url + '&secure=1';
}
/**
* Build Auth URL: Authorization code
*/
function getAuthURL(option) {
var apiKey = namespace_.getApiKey();
var url = buildURL(apiKey, option.response_type, option.media_type,
option.redirect_uri, option.state, option.display, option.client_type, option.scope);
return url;
}
function getAccessTokenFromHash () {
var lochash = location.hash;
function getAuthRetParams() {
var paramsObj = {};
if (lochash) {
var startIndex = lochash.indexOf('#');
if (startIndex !== -1) {
var subStr = lochash.slice(startIndex + 1);
if (subStr) {
var params = subStr.split('&');
params.forEach(function(elem) {
var elems = elem.split('=');
paramsObj[elems[0]] = elems[1];
})
}
}
}
return paramsObj;
}
var retObj = getAuthRetParams();
return {
'access_token': retObj['access_token'],
'expires_in': retObj['expires_in'],
'media_type': retObj['media_type']
}
}
/** @namespace baidu.frontia.social*/
var social = /** @lends baidu.frontia.social*/{
/**
* 设置社会化登录后的回调函数, 登录后会自动将当前用户设置为social登录帐户
* @param {Object} options
* @param {function(result)} [options.success] 登录成功后callback, result为User对象
* @param {function(error, xhr)} [options.error] 登录失败后callback
*/
setLoginCallback: function (options) {
var retAuthObj = getAccessTokenFromHash();
if (!(namespace_.getCurrentAccount()) && retAuthObj['access_token'] && options) {
var frontia_action = {};
frontia_action['action_name'] = 'social.login';
frontia_action['timestamp'] = _getTimestamp();
options.success || (options.success = function(){});
options.error || (options.error = function(){});
namespace_.jsonp.get(SOCAIL_GET_INFO_URL_PREFIX, { access_token: retAuthObj['access_token'] }, function(data){
if (data.error_code) {
var error = new Error(data);
options.error(error);
frontia_action.err_code = error.code;
frontia_action.err_msg = error.message;
} else {
var user = new namespace_.User({
socialId: data['social_uid'],
name: data['username'],
accessToken: retAuthObj['access_token'],
expiresIn: retAuthObj['expires_in'],
mediaType: retAuthObj['media_type']
});
namespace_.setCurrentAccount(user);
var body = _attachAccount({method: 'register'});
var ajaxOpt = {
header: {
authorization: _generateAuth(namespace_.getApiKey())
},
contentType: 'application/json'
}
var ajax = namespace_.ajax;
ajax.post(USERUriPrefixs, JSON.stringify(body), 'json', ajaxOpt);
options.success(user);
frontia_action.err_code = 0;
}
frontia_action.restimestamp = _getTimestamp();
_sendPBLog(frontia_action);
}, function(ex){
});
}
},
/**
* social登录函数
*
* @param {Object} options
* @param {string} options.response_type 目前只支持token
* @param {string} options.media_type 媒体类型,支持baidu/sinaweibo/qqweibo/qqdenglu/kaixin
* @param {string(url)} options.redirect_uri 登录成功后的重定向网址
* @param {string} [options.client_type] 登录端类型,支持web
*/
login: function(options) {
namespace_.logOutCurrentAccount();
if (!options) {
throw new baidu.frontia.error(baidu.frontia.ERR_MSG.INVALID_PARAMS);
}
options.error = options.error || function () {};
if (!options.response_type) {
throw new baidu.frontia.error(baidu.frontia.ERR_MSG.INVALID_PARAMS);
}
if (!options.media_type) {
throw new baidu.frontia.error(baidu.frontia.ERR_MSG.INVALID_PARAMS);
}
if (options.response_type != RESPONSE_TYPE.TOKEN) {
throw new baidu.frontia.error(baidu.frontia.ERR_MSG.INVALID_PARAMS);
} else {
var url = getAuthURL(options);
location.href = url;
}
}
}
function _attachAccount(body) {
var self = this;
var account = null;
if (namespace_.currentAccount && namespace_.currentAccount instanceof namespace_.Role && namespace_.currentAccount.getId()) {
account = 'requester';
body[account] = namespace_.currentAccount.getType() + ':' + namespace_.currentAccount.getId();
} else if (namespace_.currentAccount && namespace_.currentAccount instanceof namespace_.User && namespace_.currentAccount.getAccessToken()) {
account = 'requester';
body[account] = namespace_.currentAccount.getType() + ':' + namespace_.currentAccount.getAccessToken();
}
return body;
}
function _generateAuth(ak) {
var base64_ak = namespace_.util.toBase64('Application:' + ak);
return 'Basic' + ' ' + base64_ak;
}
function _sendPBLog(action) {
var frontiaClient = {
application_info: [{
app_frontia_version: namespace_.version,
app_appid: namespace_.getApiKey(),
user_id: namespace_.getCurrentAccount().getId() || '',
frontia_action: [{
action_name: '',
timestamp: null,
restimestamp: null,
err_code: '',
err_msg: ''
}]
}]
}
frontiaClient['application_info'][0]['frontia_action'][0] = action;
var body = {};
var deflate = new Zlib.Gzip(new Uint8Array(JSON.stringify(frontiaClient).split("").map(function(c) {
return c.charCodeAt(0); })));
var deflate_str = deflate.compress();
body['stats'] = btoa(String.fromCharCode.apply(null, deflate_str));
var ajax = namespace_.ajax;
ajax.post(PBLOGUriPrefixs, JSON.stringify(body), 'json', { contentType: 'application/json'});
}
function _getTimestamp() {
var timestamp = Math.floor(new Date().getTime() / 1000);
return timestamp;
}
namespace_.social = social;
})(baidu.frontia);
|
var startGamebackground
var gameState
var startGamebutton, textbutton
var currentObjects = []
function preload(){
startGamebackground = loadImage("images/startgameback.png", 1000, 1000)
startGamebimg = loadAnimation("images/start.png","images/start.png", "images/blank.png","images/blank.png", "images/blank.png" )
choosebimg = loadAnimation("images/start.png","images/start.png", "images/blank.png","images/blank.png", "images/blank.png" )
starttextimg = loadImage("images/startext.png", 1000, 1000)
}
function setup(){
canvas = createCanvas(1000, 1000);
gameState = "start"
startflag = 0
textflag = 0
//startGamebutton.scale = 2
}
function draw(){
if(gameState === "start" ){
background(startGamebackground);
if(startflag === 0){
startDisplay();
}
drawSprites();
if(mousePressedOver(startGamebutton)){
clear();
gameState = "starttext"
startGamebutton = null;
}
}
if(gameState === "starttext"){
background(starttextimg);
if(textflag === 0){
textDisplay();
}
drawSprites();
if(mousePressedOver(textbutton)){
clear();
gameState = "firstchoose"
textbutton = null;
}
}
if(gameState === "firstchoose"){
console.log("works")
}
}
//function startDisplay(){
// if(gameState === "start" && startflag === 0 ){
// startGamebutton = createSprite(500,600,1,1);
// startGamebutton.addAnimation("startbutton", startGamebimg)
// startflag = 1
// }
// else if(gameState !== "start"){
// startGamebutton = null
// }
//}
//function textDisplay(){
// if(gameState === "text" && textflag === 0){
// textbutton = createSprite(500,600,1,1);
// textbutton.addAnimation("textbutton", choosebimg)
// textflag = 1
// }
// else if{
// textbutton = null
// }
//}
function startDisplay(){
startGamebutton = createSprite(500,600,1,1);
startGamebutton.addAnimation("startbutton", startGamebimg)
startflag = 1
}
function textDisplay(){
textbutton = createSprite(500,600,1,1);
textbutton.addAnimation("textbutton", startGamebimg)
textflag = 1
}
|
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({extended: true}));
app.set("view engine","ejs");
var friends = ["A", "B", "C", "D"];
app.get("/",function(req,res){
res.render("home");
});
app.get("/friends",function(req,res){
res.render("friends",{friends:friends});
});
app.post("/addFriend",function(req,res){
var newf = req.body.newf;
friends.push(newf);
res.redirect("/friends");
});
app.listen(4500,function(){
console.log("Server for PostDemo started at localhost:4500 !!");
});
|
$(function () {
$("nav a").smoothScroll();
});
|
import React, { useEffect, useState } from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';
import { Button } from 'reactstrap';
import ProjectCard from '../Components/Cards/ProjectCards';
import { getProjects } from '../helpers/data/projectData';
import ProjectForm from '../Components/Forms/ProjectForm';
const ProjectContainer = styled.div`
display: flex;
flex-flow: wrap;
justify-content: center;
margin-top: 5%;
margin-bottom: 0;
`;
const CreateButton = styled.div`
display: flex;
justify-content: center;
margin-top: 5%;
`;
export default function ProjectsView({ admin }) {
const [projects, setProjects] = useState([]);
const [showButton, setShowButton] = useState(false);
const handleClick = () => {
setShowButton((prevState) => !prevState);
};
useEffect(() => {
getProjects().then((resp) => setProjects(resp));
}, []);
return (
<div>
<h1 className="justify-content-center text-center mt-3 mb-3">My work</h1>
<hr className="mt-3 w-50"/>
{admin
&& <CreateButton className="header mt-2">
{ !showButton
? <Button className="m-2 btn-lg justify-content-center" color='danger' onClick={handleClick}>Add Project</Button>
: <div>
<Button className="m-2 btn-lg" color='secondary' onClick={handleClick}>Close</Button>
<ProjectForm className="justify-content-center mt-3" setProjects={setProjects} admin={admin}/>
</div>
}
</CreateButton>
}
<ProjectContainer className='projectsContainer mt-2 p-1'>
{projects.map((project) => (
<ProjectCard
key={project.firebaseKey}
setProjects={setProjects}
admin={admin}
{...project}
/>
))}
</ProjectContainer>
</div>
);
}
ProjectsView.propTypes = {
projects: PropTypes.array,
admin: PropTypes.any,
setProjects: PropTypes.func
};
|
import SignIn from '@components/SignIn'
import { connect } from 'react-redux'
import { AsyncStorage } from 'react-native'
import { graphql, compose } from 'react-apollo'
import gql from 'graphql-tag'
import { writeTokenToStorage, setFormValue } from '@actions/login'
import { getLogin, getPassword } from '@selectors/login'
const mapStateToProps = state => ({
login: getLogin(state),
password: getPassword(state)
})
const mapDispatchToProps = dispatch => ({
writeTokenToStorage(token) {
dispatch(writeTokenToStorage(token))
},
setFormValue(key, value) {
dispatch(setFormValue(key, value))
}
})
const createTechnology = gql`
mutation createTechnology($input:CreateTechnologyInput!) {
createTechnology(input:$input) {
changedTechnology {
name
techId
status
}
}
}
`
const loginWithPassword = gql`
mutation LoginUser($input:LoginUserInput!) {
loginUser(input:$input) {
token
}
}
`
const loginWithFacebook = gql`
mutation LoginWithFacebook($input: LoginUserWithAuth0SocialInput!) {
loginUserWithAuth0Social(input:$input) {
token
}
}
`
export default compose(
graphql(createTechnology, {name: 'createTechnology'}),
graphql(loginWithPassword, {name: 'loginWithPassword'}),
graphql(loginWithFacebook, { name: 'loginWithFacebook'}),
connect(mapStateToProps, mapDispatchToProps)
)(SignIn)
|
const Util = require('../util');
/**
* A command in the bot.
*/
class Command {
/**
* @param {TrelloBot} client
*/
constructor(client) {
this.client = client;
this.subCommands = {};
}
/**
* @private
*/
_preload() {
if (!this.preload() && this.client.config.debug)
this.client.cmds.logger.info('Preloading command', this.name);
}
/**
* The function executed while loading the command into the command handler.
*/
preload() {
return true;
}
/**
* @private
* @param {Message} message
* @param {Object} opts
*/
async _exec(message, opts) {
// Check minimum arguments
if (this.options.minimumArgs > 0 && opts.args.length < this.options.minimumArgs)
return message.channel.createMessage(
`${opts._(this.options.minimumArgsMessage)}\n${
opts._('words.usage')}: ${opts.prefixUsed.raw}${this.name}${
opts._.valid(`commands.${this.name}.usage`) ?
` \`${opts._(`commands.${this.name}.usage`)}\`` : ''}`);
// Check commmand permissions
if (this.options.permissions.length)
for (const i in this.options.permissions) {
const perm = this.options.permissions[i];
if (!Util.CommandPermissions[perm])
throw new Error(`Invalid command permission "${perm}"`);
if (!Util.CommandPermissions[perm](this.client, message, opts))
return message.channel.createMessage(opts._(`command_permissions.${perm}`));
}
// Process cooldown
if (!this.cooldownAbs || await this.client.cmds.processCooldown(message, this)) {
await this.exec(message, opts);
} else {
const cd = await this.client.db.hget(`cooldowns:${message.author.id}`, this.name);
return message.channel.createMessage(
`:watch: ${opts._('cooldown_msg', { seconds: Math.ceil(this.cooldownAbs - (Date.now() - cd))})}`);
}
}
// eslint-disable-next-line no-empty-function, no-unused-vars
exec(Message, opts) { }
/**
* The options for the command
* @type {Object}
*/
get options() {
const options = {
aliases: [],
cooldown: 2,
listed: true,
minimumArgs: 0,
permissions: [],
minimumArgsMessage: 'bad_args',
};
Object.assign(options, this._options);
return options;
}
/**
* @private
*/
_options() { return {}; }
/**
* The cooldown in milliseconnds
* @returns {number}
*/
get cooldownAbs() { return this.options.cooldown * 1000; }
/**
* The metadata for the command
* @return {Object}
*/
get metadata() {
return {
category: 'categories.misc',
};
}
}
module.exports = Command;
|
const requestBody = {
query: `
query {
events {
_id
title
description
price
date
creator {
_id
firstName
lastName
email
}
}
}
`
};
const mutationBody = ({ title, description, date, price }) => {
return {
query: `
mutation {
createEvent(eventInput: {title: "${title}", description: "${description}", date: "${date}", price: ${price}}) {
_id
title
description
price
date
creator {
_id
firstName
lastName
email
}
}
}
`
};
};
export class EventsService {
constructor(token) {
this.token = token;
}
getEvents = () => (
this.request('getEvents', requestBody)
.then(res => res.data.events)
)
createEvent = ({ title, description, date, price }) => (
this.request('createEvent', mutationBody({ title, description, date, price }), this.token)
.then(res => res.data.createEvent)
)
request = (func, body, token) => {
const headers = {
'Content-Type': 'application/json'
};
if (token) {
headers['Authorization'] = `Bearer ${token}`;
}
return fetch('http://localhost:3000/graphql-api', {
method: 'POST',
body: JSON.stringify(body),
headers
})
.then(res => {
if (res.status !== 200 && res.status !== 201) {
throw new Error(`${func} request failed!`);
}
return res.json();
})
.then(res => {
if (res.errors && res.errors.length) {
throw new Error(`${func} request failed!`);
}
return res;
})
.catch(err => console.error('EventsService request error', err));
}
}
|
/**
* Manager for user notifications.
*/
const mailerManager = require('./mailer-manager');
class NotificationsManager {
constructor(){
this.NotificationTypes = {
GENERAL: 0,
NEW_MATCH: 1,
MESSAGE: 2
};
}
init(){
return new Promise((resolve, reject) =>{
resolve();
});
}
/**
* Checks notification preferences and generates a notification email and sends it to a user
* @param template - Receives a nodemailer template function
* @param userTo - User object who is receiving the notification
* @param params - Specifics of the user for personalized emails
* @param type - Type of notification for preference checking
* @returns Promise <void>
*/
sendNotification(template, userTo, params, type) {
return new Promise((resolve, reject) => {
if (template == null || template == undefined) {
throw "Template Undefined";
}
let sendNotification = false;
switch (type) {
case this.NotificationTypes.GENERAL:
sendNotification = userTo.ReceiveGeneralNotifications;
break;
case this.NotificationTypes.NEW_MATCH:
sendNotification = userTo.ReceiveNewMatchNotifications;
break;
case this.NotificationTypes.MESSAGE:
sendNotification = userTo.ReceiveMessageNotifications;
break;
default:
throw "No type specified";
break;
}
if (sendNotification) {
template({to: userTo.Email}, params, (error)=>{
if(error)
reject(error);
else
resolve();
});
}
});
}
}
module.exports = new NotificationsManager();
|
import React from "react";
import { withRouter } from "react-router";
import { Helmet } from "react-helmet";
import Expand from "react-expand-animated";
import styled from "styled-components";
import Colors from "../../../global/styles/colors";
import { Text, SubText, Button } from "../../../global/styles/styles";
import { formatInt, airTimeString } from "../../../global/utils/utils";
import { ArrowSVG } from "../../../components/SVGIcons";
import Creator from "../../../components/Creator";
import ErrorPopup from "../../../components/ErrorPopup";
import Copy from "../../../global/locales/en_us";
import { isUserLoggedIn } from "../../../global/utils/auth";
import { connectToUser } from "../../../global/api/endpoints";
const Container = styled.div`
width: 100%;
display: grid;
position: relative;
padding: 8px;
box-shadow: 0px 0 4px 0 rgba(155, 155, 155, 0.5);
`;
const SubscribedContainer = styled.div`
position: absolute;
right: 8px;
top: 10px;
`;
const SubscribeButton = styled(Button)`
background-color: ${Colors.subscribeButton};
padding: 0px !important;
height: 28px;
width: 84px;
font-weight: 700;
letter-spacing: 0.5;
text-transform: uppercase;
text-align: center;
background-position: center;
font-size: 14px;
cursor: pointer;
`;
const SubscribedText = styled(Text)`
font-size: 14px;
text-transform: uppercase;
font-weight: 700;
padding-top: 6px;
color: ${Colors.subscribedText};
`;
const Title = styled(Text)`
font-size: 16px;
line-height: 20px;
min-height: 22px;
max-width: 75%;
font-weight: 600;
padding-top: 6px;
`;
const Viewers = styled.div`
display: flex;
align-items: center;
padding-top: 4px;
padding-bottom: 6px;
`;
const ViewerCount = styled(Text)`
font-size: 14px;
font-weight: 400;
letter-spacing: 0.5px;
`;
const ViewerLabel = styled(ViewerCount)`
font-size: 13px;
`;
const ArrowButtonContainer = styled.div`
position: absolute;
right: 8px;
bottom: 4px;
transform: ${props => (props.showDetails === true ? "rotate(180deg)" : "rotate(0deg)")};
transition: 300ms ease-in-out;
cursor: pointer;
`;
const AirTime = styled(SubText)`
font-size: 12px;
line-height: 15px;
`;
const Description = styled(Text)`
font-size: 14px;
line-height: 20px;
padding-top: 12px;
padding-bottom: 22px;
white-space: pre-line;
`;
class VideoDescriptor extends React.Component {
constructor(props) {
super(props);
this.state = {
showDetails: false,
followed: false,
followError: false
};
}
componentDidMount() {}
toggleShowDetails = () => {
this.setState({
showDetails: !this.state.showDetails
});
};
subscribeClicked = () => {
const isLoggedIn = isUserLoggedIn();
if (!isLoggedIn) {
gtag("event", "connect_clicked_unauthenticated", "watch");
this.props.history.push("/register");
return;
}
const { broadcaster } = this.props;
const { id } = broadcaster;
connectToUser(id).then(res => {
if (!res.status.error) {
gtag("event", "connect_clicked", "watch");
this.setState({ followed: true });
} else {
gtag("event", "connect_error", "watch");
this.setState({ followError: true });
}
});
};
render() {
const { title, live = false, viewerCount, airtime, description, broadcaster, runtime } = this.props;
const { showDetails, followed, followError } = this.state;
return (
<Container>
<Helmet>
<title>{`Scrim TV: ${broadcaster.displayName} presents ${title}`}</title>
<meta
name="description"
content={`${broadcaster.displayName} presents ${title},
Views: ${viewerCount},
Runtime: ${runtime} seconds,
Published ${airtime}`}
/>
</Helmet>
<SubscribedContainer>
{broadcaster.hasConnected || followed ? (
<SubscribedText>{Copy.following}</SubscribedText>
) : (
<SubscribeButton onClick={this.subscribeClicked}>{Copy.connect}</SubscribeButton>
)}
{followError && <ErrorPopup message={Copy.followError} />}
</SubscribedContainer>
<Creator type="Broadcast" {...broadcaster} />
<Title>{title}</Title>
<Viewers>
{/* <Maybe test={live}>
<RedDot />
</Maybe> */}
<ViewerCount>{formatInt(viewerCount, showDetails)}</ViewerCount>
<ViewerLabel>
{live ? Copy.viewers : Copy.views}
</ViewerLabel>
</Viewers>
<ArrowButtonContainer onClick={this.toggleShowDetails} showDetails={showDetails}>
<ArrowSVG />
</ArrowButtonContainer>
<Expand open={showDetails} duration={300}>
<AirTime>{`${airTimeString(live)} ${airtime}`}</AirTime>
<Description>{description}</Description>
</Expand>
</Container>
);
}
}
export default withRouter(VideoDescriptor);
|
var FreelancerProfile = {
init: function () {
this.cacheElements();
this.bindEvents();
this.addWidgets();
},
cacheElements: function () {
this.$rating = $('select#rating');
this.$form = $('form#project-notification-form');
this.$industries = this.$form.find('select#industries');
this.$professions = this.$form.find('select#professions');
this.$skills = this.$form.find('select#skills');
this.$skillRelation = this.$form.find('select#skill-relation');
this.$saveProjectNotification = this.$form.find('button#save-project-notification');
this.$loading = $('span.loading');
this.$initialRating = $('input#initial-rating');
this.$rateButton = $('button#rate');
this.$yourRatingPoint = $('span#your-rating-point');
this.$ratingInstruction = $('p.rating-instruction');
this.$ratingAvgPoint = $('span#rating-avg-point');
this.$ratersCount = $('span#raters-count');
this.$canRate = $('input#can-rate');
},
bindEvents: function () {
this.$rateButton.click(FreelancerProfile.rateClick);
this.$saveProjectNotification.click(FreelancerProfile.saveProjectNotificationClick);
},
addWidgets: function () {
FreelancerProfile.$rating.barrating({
theme: 'fontawesome-stars',
initialRating: FreelancerProfile.$initialRating.val(),
readonly: (FreelancerProfile.$canRate.val() == '0')
});
this.$industries.select2({
theme: "bootstrap"
});
this.$skillRelation.select2({
theme: "bootstrap"
});
var professionUrl = ROOT + 'project/ajax/professionAutocomplete';
var professionObj = Default.getSelect2Object(professionUrl);
var skillUrl = ROOT + 'project/ajax/skillAutocomplete';
var skillObj = Default.getSelect2Object(skillUrl);
this.$professions.select2(professionObj);
this.$skills.select2(skillObj);
},
/**
* Projekt ertesito mentes
*/
saveProjectNotificationClick: function () {
var $this = $(this);
$this.prop('disabled', true);
FreelancerProfile.$loading.isLoading({
text: "Folyamatban...",
//position: 'overlay'
});
FreelancerProfile.$loading.removeClass("alert-success");
var ajax = new AjaxBuilder();
var success = function(data) {
setTimeout(function() {
FreelancerProfile.$loading.isLoading('hide');
}, 500);
if (data.error) {
setTimeout(function () {
FreelancerProfile.$loading.html('Sajnos, valami hiba történt...').addClass('alert-danger');
FreelancerProfile.$loading.show();
}, 500);
setTimeout(function () {
FreelancerProfile.$loading.hide();
}, 2000);
} else {
setTimeout(function () {
FreelancerProfile.$loading.html('Sikeres mentés').addClass('alert-success');
FreelancerProfile.$loading.show();
}, 500);
setTimeout(function () {
FreelancerProfile.$loading.hide();
}, 1000);
}
setTimeout(function() {
$this.prop('disabled', false);
}, 500);
};
ajax.data(FreelancerProfile.$form.serialize()).url(FreelancerProfile.$form.attr('action')).success(success).send();
return false;
},
/**
* Ertekeles
*/
rateClick: function () {
var $this = $(this);
$this.prop('disabled', true);
var ratingValue = FreelancerProfile.$rating.val();
$.confirm({
icon: 'fa fa-question-circle',
title: 'Megerősítés',
content: 'Biztosan <strong>' + ratingValue + '</strong> ponttal értékeled a felhasználót?',
confirm: function () {
FreelancerProfile.sendRateAjax($this, ratingValue);
},
cancel: function () {
$this.prop('disabled', false);
},
confirmButton: 'IGEN',
cancelButton: 'NEM'
});
},
sendRateAjax: function ($button, ratingValue, userId) {
var userId = $button.data('user_id');
var ajax = new AjaxBuilder();
var success = function (data) {
if (data.error) {
$button.prop('disabled', false);
} else {
FreelancerProfile.$yourRatingPoint.text(data.rating);
FreelancerProfile.$ratingAvgPoint.text(data.avg);
FreelancerProfile.$ratersCount.text(data.raters_count);
FreelancerProfile.$ratingInstruction.fadeOut(function () {
FreelancerProfile.$ratingInstruction.hide();
});
FreelancerProfile.$rateButton.fadeOut(function () {
FreelancerProfile.$rateButton.hide();
$('div.bottom-container').addClass('pt20');
});
FreelancerProfile.$rating.barrating('set', parseInt(data.avg));
FreelancerProfile.$rating.barrating('readonly', true);
}
};
ajax.data({rating: ratingValue, user_id: userId}).url(ROOT + 'user/ajax/rate').success(success).send();
}
};
$(document).ready(function () {
FreelancerProfile.init();
});
|
var express = require('express');
var app = express();
var orm = require('orm');
var paging = require('orm-paging');
var server = require('http').createServer(app);
app.use(express.bodyParser({}));
app.use(orm.express("mysql://root:123456@localhost/microwin", {
define: function (db, models) {
db.use(paging);
models.provinces = db.define("provinces", {
id :Number,
provName :String,
provEname :String,
isValid :Boolean
}); //end of provinces
models.users = db.define("users", {
id :Number,
name :String,
password :String,
isValid :Boolean,
provID :Number,
detail :String
},{cache : false, autoSave : true}); //end of users
models.tasks = db.define("tasks", {
id :Number,
provID :Number,
postSTR :String,
partNumber :String,
nrPkg :String,
phoneModel :String,
city :String,
url :String,
isRandom :Boolean,
beginTime :Date,
endTime :Date,
isUpdate :Boolean,
content :String,
isDelete :Boolean
}); //end of tasks
models.logs = db.define("logs", {
id :Number,
userName :String,
dateTime :Date,
log :String
}); //end of logs
}//End of define:function...
}));//End of app.use.....................
app.get('/microWin.js',function(req,res){
res.send("??@@@###@?");
}); //写在use之前 防止读取静态文件
app.use('/', express.static(__dirname + '/'));
server.listen(12345);
var itemsPerPage = 2;
//=================================================主界面tasks.html的接口================================================
//监听来自抓取平台提交的内容,插入数据库
app.post("/insertTask", function(req, res){
var task = req.body.task; console.log(task);
req.models.tasks.create([
{ //id 1个
// id :task.id,
provID :task.provID,
postSTR :task.postSTR,
partNumber :task.partNumber,
nrPkg :task.nrPkg,
phoneModel :task.phoneModel,
city :task.city,
url :task.url,
isRandom :task.isRandom,
beginTime :task.beginTime,
endTime :task.endTime,
isUpdate :task.isUpdate,
content :task.content,
isDelete :task.isDelete
}
], function(err, items){
// res.header("Access-Control-Allow-Origin", "*");
// res.header("Access-Control-Allow-Headers", "X-Requested_with");
if(!err){
res.send(items[0]);
}else{
res.send(err);
}
})
});
//获取总页数
app.post("/pages", function(req, res){
var provID = req.body.provID;
console.log('pages--->provID');
console.log(provID);
if(provID == 666){
provID = [];
for(var i=1; i<35; i++){
provID.push(i);
}
}
//根据provID找到相应task
req.models.tasks.find({'provID' : provID}, function(err, tasks){
if(err){
res.send(err);
}else{
if(tasks.length > 0){
console.log("tasks's length="+tasks.length);
var pagesToTasks = Math.ceil(tasks.length/itemsPerPage);
console.log('pagesToTasks='+pagesToTasks);
res.send(JSON.stringify(pagesToTasks));
}else{
res.send(JSON.stringify(0));
} //end of tasks.length > 0
} //end of no err
}); //end of tasks find
});
app.get("/paging", function(req, res){
var p = req.param('p');
var provID = req.param('provID');
console.log('Pring P and provID');
console.log(p);console.log(provID);
req.models.tasks.settings.set("pagination.perpage", itemsPerPage); // default is 20
req.models.tasks.pages(function(err, pages){
if(err){
res.send(err);
}else{
if(!p){
p=1;
} //load the 1st page as default
if(provID == 666){
provID = [];
for(var i=1; i<35; i++){
provID.push(i);
}
}
console.log(provID);
req.models.tasks.page(p).find({'provID':provID}).order('id', "Z").run(function(err, tasks){
if(err){
res.send(err);
}else{
res.send(JSON.stringify(tasks));
}
});
}
});
});//End of get pages...
//Todo:Update的接口
app.post("/updateTask", function(req, res){
var task=req.body.task;
console.log(task);
req.models.tasks.get(task.id, function(err, resTask){
resTask.provID =task.provID;
resTask.postSTR =task.postSTR;
resTask.partNumber =task.partNumber;
resTask.nrPkg =task.nrPkg;
resTask.phoneModel =task.phoneModel;
resTask.city =task.city;
resTask.url =task.url;
resTask.isRandom =task.isRandom;
resTask.beginTime =task.beginTime;
resTask.endTime =task.endTime;
resTask.isUpdate =task.isUpdate;
resTask.content =task.content;
resTask.isDelete =task.isDelete;
resTask.save(function(err){
if(err){
console.log(err);
res.send(JSON.stringify({'err':err}));
}else{
console.log(resTask);
res.send(resTask);
}
}); //End of Save
}); //End of Get
}); //End of Update Get Request
app.get("/getTaskById", function(req, res){
var id=req.param('id');
req.models.tasks.get(id, function(err, task){
res.send(task);
}); //End of Get
}); //End of Update Get Request
app.post("/markAsDelete", function(req, res){
var id=req.body.id;
req.models.tasks.get(id, function(err, resTask){
resTask.isDelete = true;
resTask.save(function(err){
if(err){
res.send(JSON.stringify({'err':err}));
}else{
res.send(resTask);
}
});//End of Save
});
});//End of Get
//=================================================另一个页面modifyUsers.html的接口================================================
app.get("/users", function(req, res){
req.models.users.find({},function(err, users) {
console.log(users);
res.send(JSON.stringify(users));
});//End of get users
});//End of get pages...
//Todo:修改用户的激活属性
app.post("/updateUserValidation", function(req, res){
var id=req.body.id;
var isValid=req.body.isValid;
console.log("isValid===="+isValid);
req.models.users.get(id, function(err, resUser){
console.log(typeof isValid);
resUser.isValid=isValid;
resUser.save(function(err){
if(err){console.log(err);
res.send(JSON.stringify({'err':err}));
}else{
console.log(resUser);
res.send(resUser);
}
}); //End of Save
}); //End of Get
}); //End of Update Get Request
//============================================index.html(Login)接口===============================
//Todo: 需要检查isValid字段是否为true,
app.post("/login", function(req, res){
var na=req.body.name;
var password=req.body.password;
console.log("姓名="+na+",密码="+password);
req.models.users.find({name:na}, function (err, users){ console.log(users);
if(err){
res.send(JSON.stringify({error:err}));
}else{
if(users.length>0){//如果根据name找不到user
if(users[0].password==password){
if(users[0].isValid==1){
var o = {};
o.name = users[0].name;
o.provID = users[0].provID;
o.isValid = users[0].isValid;
o.detail = users[0].detail;
console.log(o);
res.send(JSON.stringify(o));
}else{
res.send("User Invalid...");
} //End of Valid
}else{
res.send("Password Error!!!");
} //End of Password
}else{
res.send("No User Found ~~~");
} //End of User Found
}
}); //End of find
}); //End of login get
//=============================================logs.html接口======================================
//获取总页数
app.get("/pages", function(req, res){
req.models.logs.settings.set("pagination.perpage", itemsPerPage); // default is 20
req.models.logs.pages(function (err, pages) {
res.send(JSON.stringify(pages));
});
});
app.get("/paging", function(req, res){
var p=req.param('p');
req.models.logs.settings.set("pagination.perpage", itemsPerPage); // default is 20
req.models.logs.pages(function (err, pages) {
if(p){
req.models.logs.page(p).order('id',"Z").run(function (err, logs) {
res.send(JSON.stringify(logs));
});//End of get logs
}else{
req.models.logs.page(1).order('id',"Z").run(function (err, logs) {
res.send(JSON.stringify(logs));
});//End of get logs
}
});//End of get pages
});//End of get pages...
//=================================================modifyProvinces.html的接口================================================
app.get("/provinces", function(req, res){
req.models.provinces.find({},function(err, provinces) {
res.send(JSON.stringify(provinces));
});//End of get provinces
});//End of get pages...
//Todo:修改省市的属性
app.post("/updateProvinceValidation", function(req, res){
var id = req.body.id;
var isValid = req.body.isValid;
req.models.provinces.get(id, function(err, resProv){
resProv.isValid = isValid;
resProv.save(function(err){
if(err){console.log(err);
res.send(JSON.stringify({'err':err}));
}else{
console.log(resProv);
res.send(resProv);
}
}); //End of Save
}); //End of Get
}); //End of Update Get Request
|
import React, { Component } from 'react';
import { FlatList, Text, View, StyleSheet, Image } from 'react-native';
import backgroundRound from '../../images/backgroudRound/round.png';
class Avatar extends Component {
constructor(props) {
super(props);
}
render() {
return (
<View style={styles.container}>
<Image
source={backgroundRound}
style={styles.backgroundImage}/>
<Text style={styles.text}>{this.props.text}</Text>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
justifyContent: 'center',
alignItems: 'center',
},
backgroundImage: {
flexShrink: 1,
aspectRatio: 1,
},
text: {
position: 'absolute',
backgroundColor: 'transparent',
color: '#fff',
},
});
export default Avatar;
|
const initialState = {
isPop: false,
popIndex: -1,
};
const search = (state = initialState, action) => {
switch (action.type) {
case "TOGGLE_POPUP_BOX":
return { isPop: !state.isPop, popIndex: action.dataIndex };
default:
return state;
}
};
export default search;
|
const mainColor = "#159793";
const lightestColor ="#FFF";
const darkestGray = "#3C4043"
export {
mainColor,
lightestColor,
darkestGray
}
|
import React, { Component } from 'react';
import {
StyleSheet,
View
} from 'react-native';
import Navigation from './src/view/navigation/Navigation';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import reducers from './src/redux/reducers';
import ReduxThunk from 'redux-thunk';
export default class App extends React.Component {
render() {
const store = createStore(reducers, {}, applyMiddleware(ReduxThunk));
return (
<Provider store={store}>
<Navigation />
</Provider>
);
}
}
|
import React, { useState, useEffect } from "react";
import { Form, Button, Card } from "react-bootstrap";
import { useParams, useHistory, withRouter } from "react-router-dom";
import ChallangeService from "../services/ChallangeService";
import moment from "moment";
import queryString from "query-string";
function EditChallange(props) {
let history = useHistory();
const params = useParams();
console.log("Props: ", params.id, props);
const query = queryString.parse(props.location.search);
console.log("query: ", query);
// const data = props.location.state.data;
// const SD = moment(data.startDate).format("YYYY-MM-DD");
// const ED = moment(data.expiryDate).format("YYYY-MM-DD");
const [challangeTitle, setChallangeTitle] = useState("");
const [companyName, setCompanyName] = useState(query.company);
const [startDate, setStartDate] = useState("");
const [expiryDate, setExpiryDate] = useState("");
const [formValues, setFormValues] = useState([
{ habbitTitle: "", habbitDescription: "" },
]);
useEffect(() => {
ChallangeService.getSingleChallange(params.id).then((res) => {
console.log("RES:", res);
setChallangeTitle(res.challangeTitle);
const SD = moment(res.startDate).format("YYYY-MM-DD");
const ED = moment(res.expiryDate).format("YYYY-MM-DD");
setStartDate(SD);
setExpiryDate(ED);
setFormValues(res.habbits);
});
}, []);
let handleChange = (i, e) => {
let newFormValues = [...formValues];
newFormValues[i][e.target.name] = e.target.value;
setFormValues(newFormValues);
};
let addFormFields = () => {
setFormValues([...formValues, { habbitTitle: "", habbitDescription: "" }]);
};
let removeFormFields = (i) => {
let newFormValues = [...formValues];
newFormValues.splice(i, 1);
setFormValues(newFormValues);
};
const handleSubmit = async (e) => {
e.preventDefault();
try {
const res = await ChallangeService.updateChallange(params.id, {
challangeTitle,
companyName,
startDate,
expiryDate,
habbits: formValues,
});
console.log("REs", res);
props.history.push("/challanges");
} catch (error) {
console.log("Error", error);
}
};
return (
<>
<Card className="card card-custom gutter-b example example-compact">
<Card.Header>
<Card.Title>
<h3 className="card-label">Edit Challange</h3>
</Card.Title>
</Card.Header>
<Card.Body>
<Form>
<div className="row">
<div className="col-md-5">
<Form.Group controlId="formBasicEmail">
<Form.Label>Challange Title</Form.Label>
<Form.Control
value={challangeTitle}
onChange={(e) => setChallangeTitle(e.target.value)}
type="text"
placeholder="Enter Challange Title"
/>
{/* <Form.Text className="text-muted">
We'll never share your email with anyone else.
</Form.Text> */}
</Form.Group>
</div>
<div className="col-md-5">
<Form.Group controlId="formBasicPassword">
<Form.Label>Company Name</Form.Label>
<Form.Control
value={companyName}
placeholder="Company for which challange creating..."
onChange={(e) => setCompanyName(e.target.value)}
type="text"
/>
</Form.Group>
</div>
</div>
<div className="row">
<div className="col-md-5">
<Form.Group controlId="formBasicPassword">
<Form.Label>Start Date</Form.Label>
<Form.Control
name="date"
placeholder="date placeholder"
value={startDate}
onChange={(e) => setStartDate(e.target.value)}
type="date"
/>
</Form.Group>
</div>
<div className="col-md-5">
<Form.Group controlId="formBasicPassword">
<Form.Label>Expiry Date</Form.Label>
<Form.Control
name="date"
placeholder="date placeholder"
value={expiryDate}
onChange={(e) => {
setExpiryDate(e.target.value);
}}
type="date"
/>
</Form.Group>
</div>
</div>
{/* <div className="col-md-12"> */}
{formValues.map((element, index) => (
<div key={index}>
<hr className="my-3" />
<div className="row">
<div className="col-md-5">
<Form.Group controlId="formBasicPassword">
<Form.Label>Habbit Title({index + 1})</Form.Label>
<Form.Control
name="habbitTitle"
placeholder="Habbit Title"
value={element.habbitTitle || ""}
onChange={(e) => handleChange(index, e)}
type="text"
/>
</Form.Group>
</div>
<div className="col-md-5">
<Form.Group controlId="formBasicPassword">
<Form.Label> Habbit Description({index + 1})</Form.Label>
<Form.Control
placeholder="Write a description text here ..."
rows="1"
type="textarea"
name="habbitDescription"
value={element.habbitDescription || ""}
onChange={(e) => handleChange(index, e)}
/>
</Form.Group>
</div>
<div className="col-md-2">
{index ? (
<Button
variant="danger"
onClick={() => removeFormFields(index)}
style={{ marginTop: "1.8rem" }}
>
Remove
</Button>
) : null}
</div>
</div>
</div>
))}
<div className="col-md-10">
<Button
variant="success"
size="lg"
block
onClick={() => addFormFields()}
style={{ marginBottom: "2rem" }}
>
Add Habbit
</Button>
</div>
{/* </div> */}
<div className="col-md-10">
<Button
variant="primary"
size="lg"
block
type="submit"
onClick={handleSubmit}
>
Submit
</Button>
</div>
</Form>
</Card.Body>
</Card>
</>
);
}
export default withRouter(EditChallange);
|
var Accordion = function (rootElement) {
this.rootElement = rootElement;
this.buttonItemClickOne = this.rootElement.querySelector('.accordion-click-one');
this.buttonItemClickTwo = this.rootElement.querySelector('.accordion-click-two');
this.buttonItemClickTree = this.rootElement.querySelector('.accordion-click-three');
this.buttonItem = this.rootElement.getElementsByClassName('accordion-button');
this.buttonItems = [].slice.call(this.buttonItem);
this.contentAcc = this.rootElement.getElementsByClassName('accordion-content');
this.contentAccItems = [].slice.call(this.contentAcc);
this.currentTabId = 0;
this.active = 'isActive';
this.toggleAccordion = this.toggleAccordion.bind(this);
this.handleClickAccordion = this.handleClickAccordion.bind(this);
};
Accordion.prototype.handleClickAccordion = function (event) {
this.currentTabId = this.buttonItems.indexOf(event.target);
this.setActive(this.buttonItems);
this.setActive(this.contentAccItems);
};
Accordion.prototype.toggleAccordion = function(){
this.buttonItems[this.currentTabId].classList.add(this.active);
this.contentAccItems[this.currentTabId].classList.add(this.active);
};
Object.defineProperty(Accordion.prototype, 'currentTabId', {
get: function () {
return this._currentTabId;
},
set: function (value) {
this._currentTabId = (value <= 0)? 0 : Math.min(value, this.buttonItems.length - 1);
this.toggleAccordion();
}
});
Accordion.prototype.setActive = function (itemsCollection) {
itemsCollection.forEach(function (item, index) {
if (index === this.currentTabId) {
item.classList.add(this.active);
} else {
item.classList.remove(this.active);
}
}.bind(this));
};
Accordion.prototype.delegateEvents = function () {
this.buttonItemClickOne.addEventListener('click', this.handleClickAccordion);
this.buttonItemClickTwo.addEventListener('click', this.handleClickAccordion);
this.buttonItemClickTree.addEventListener('click', this.handleClickAccordion);
return this;
};
Accordion.prototype.render = function () {
this.delegateEvents();
return this;
};
|
class VigenereCipheringMachine {
constructor(isDirect=true) {
this.isDirect = isDirect;
}
encrypt(message, key) {
if (arguments.length < 2) {
throw new Error('Wrong arguments!');
} else {
const encryptedChars = [];
for (let i = 0, omissions = 0; i < message.length; i++) {
if (/^[^A-Z]$/i.test(message[i])) {
omissions++;
encryptedChars.push(message[i]);
} else {
encryptedChars.push(
String.fromCharCode(
((message.toUpperCase().charCodeAt(i) - 65) +
(key.toUpperCase().charCodeAt((i - omissions) % key.length) - 65)) %
26 + 65)
);
}
}
return this.isDirect ? encryptedChars.join('') : encryptedChars.reverse().join('');
}
}
decrypt(encryptedMessage, key) {
if (arguments.length < 2) {
throw new Error('Wrong arguments!');
} else {
const decryptedChars = [];
for (let i = 0, omissions = 0; i < encryptedMessage.length; i++) {
if (/^[^A-Z]$/.test(encryptedMessage[i])) {
omissions++;
decryptedChars.push(encryptedMessage[i]);
} else {
decryptedChars.push(
String.fromCharCode((26 +
((encryptedMessage.charCodeAt(i) - 65) -
(key.toUpperCase().charCodeAt((i - omissions) % key.length) - 65))) %
26 + 65));
}
}
return this.isDirect ? decryptedChars.join('') : decryptedChars.reverse().join('');
}
}
}
module.exports = VigenereCipheringMachine;
|
/*
DYNAMICALLY CREATE CLICK EVENTS LISTENERS
https://toddmotto.com/attaching-event-handlers-to-dynamically-created-javascript-elements/
POPULATE BUTTONS FROM JSON RECEIVED FROM SERVER
-resources-
http://stackoverflow.com/questions/21747878/how-to-populate-a-dropdown-list-with-json-data-dynamically-section-wise-into-th
http://www.encodedna.com/2013/07/dynamically-add-remove-textbox-control-using-jquery.htm
*/
window.mySocket;//setup global var for the websocket
window.TheOrder;//setup global var for the order
var AllMyItems;//setup global var for all items that can be ordered
var orderData = {'orderData' : {}};
var orderTotal = 0.00;
var ElementId_Spacer = "-"; //space char in element name attr to denote location in buttonBuilder json
var PageIsReady = false;//used to test when all html is built
/*-------These Function are used to build buttons on the screen--------
ButtonBuilder():
IN: obj - json data
parentKey - root key for the obj
id - location of element in main buttonBuilder json, used as html id for element created
PURPOSE: iterate a branch of json, recursively iterate sub branches
OUT: pass data to HTMLgenerator() to create html view from the json
PageIsReady >True when finished, click handlers are then assigned for generated content.
*/
function ButtonBuilder(obj,parentKey,id) {
if (!PageIsReady) {PageIsReady = 2;}
else {PageIsReady += 1;};
var parentKey = parentKey;
var id = id || "";
var childKey = Object.keys(obj[parentKey]);
//to break the recursive calling of this function when obj finally becomes an actual property
//since properties of an object: price, modification, etc are NOT Object.
if (obj instanceof Object) {
for (var i=0;i<childKey.length;i++) {
var jsonID = id+ElementId_Spacer+[childKey[i]];
//if id has '.' as first character, skip over it so a letter is first
if (jsonID.charAt(0)==ElementId_Spacer) {jsonID = jsonID.substring(1);};
if (obj[parentKey][childKey[i]].price){
HTMLgenerator(jsonID,id,obj[parentKey][childKey[i]].price)}
else {
HTMLgenerator(jsonID,id);
ButtonBuilder(obj[parentKey],[childKey[i]],jsonID);};
};
}else{return;};
PageIsReady -= 1;
if(PageIsReady===1){PageIsReady===true;}
};
/*
HTMLgenerator():
IN: id - name of an item in the format of location of in main json, example- root.parent.child.item
parentDiv - what div the new div created for ID should be nested under
price - if price, means input is an actual item send to createItem()
PURPOSE: create HTML div for id, nest under parent category. actual items pass through this function
this is used for menu and submenu drop downs and organizing the html view
OUT: nothing, however html div is created in view
*/
function HTMLgenerator(id,parentDiv,price) {
var price = price || false;//menu buttons have no price, only items do
if (parentDiv==="") {parentDiv='terminal';};
if (price) {createItem(id,parentDiv,price)}
else {
//isolate just the name of the item
var nm = id.substring(id.lastIndexOf(ElementId_Spacer)+1);
var newDiv = document.createElement("div");
document.getElementById(parentDiv).appendChild(newDiv);
newDiv.setAttribute('id',id);
newDiv.setAttribute('name',nm);
document.getElementById(id).innerHTML = nm.toUpperCase();
if (parentDiv==='terminal') {newDiv.setAttribute('class','button'); }
else {newDiv.setAttribute('class','subbutton'); }
}
};
/*
createItem(id,parentDiv,price):
IN: id - name of an item in the format of location of in main json, example- root.parent.child.item
parentDiv - what div the new element created for ID should be nested under
price - price of the item
PURPOSE: create HTML button nested under parent category for a specific menu item, when item is clicked
it is added to the order.
OUT: nothing, however html element with class item is created in view for the item
*/
function createItem(id,parentDiv,price){
var nm = id.substring(id.lastIndexOf(ElementId_Spacer)+1);
var newItem = document.createElement("p");
newItem.setAttribute('class','item');
newItem.setAttribute('id',id);
newItem.setAttribute('value',price);
newItem.setAttribute('name',nm);
document.getElementById(parentDiv).appendChild(newItem);
document.getElementById(id).innerHTML = nm.toUpperCase();
};
/*
addItemToOrder(Name,count,price):
IN: Name - name of menu item
count - used for tracking multiples of same item, example - burger: 2
price - price of the item
PURPOSE: add the clicked menu item to the order. create an html element for the item
under orderArea.
OUT: nothing, however html item element is created in view
*/
function addItemToOrder(Name,count,price){
orderTotal += parseFloat(price);
var itemName = Name+'-'+count || Name;//legacy, don't really need ||
var newItem = document.createElement("p");
newItem.setAttribute('id',itemName);
document.getElementById('orderArea').appendChild(newItem);
$('#'+itemName).html(Name.toUpperCase() +' $'+price);
$('#orderTotal').html('Total: $'+orderTotal.toFixed(2));//force two decimal spots
};
/*
display_CategoryView(parentDiv):
IN: parentDiv - the element was clicked $(this)
PURPOSE: If there is content in 'categoryView' div, remove
it and return to it's correct parent. Then take the nested content
of the 'terminal' element clicked.
which is some category of items. Display the content in
'categoryView' which is the far middle column in view
OUT: nothing, however html is shuffled and displayed
*/
function display_CategoryView(parentDiv) {
$('.button').removeClass("ActiveCategory");//remove 'active' class on previous parent
var newParent = $('#categoryView');
if (newParent.children()[0].id !== 'itemView') {
var parentCategory = newParent.children()[0].id;
var end = parentCategory.indexOf("-");
parentCategory = parentCategory.substring(0,end);
newParent.find('*').css('display','none');
newParent.find('*').not('#itemView').clone(true).appendTo($('#'+parentCategory));
};
newParent.find('*').not('#itemView').remove();
//clone(true) takes all attached handlers too, see docs
parentDiv.children().clone(true).prependTo(newParent);
parentDiv.children().remove();
if(newParent.children('.subbutton').css('display') ==='none'){
newParent.children('.subbutton').toggle();};
parentDiv.addClass("ActiveCategory");
};
function display_ItemModifiers(mods) {
var id = mods.context.id;
var xtest = document.getElementById(id).childNodes;
console.log(xtest);
mods.children().css('width','50%');
mods.children().toggle();
var newItem = document.createElement("div");
console.log(xtest[1].id);
document.getElementById(xtest[1].id).appendChild(newItem);
};
function display_ItemView(parentDiv) {
console.log(parentDiv);
$('.subbutton').removeClass("ActiveItem");
var newParent = $('#itemView');
newParent.empty();
parentDiv.children().not("[name='mods']").clone(true).prependTo(newParent);
parentDiv.children("[name='mods']").clone(true).appendTo(newParent);
newParent.children().css('display','block');
parentDiv.addClass("ActiveItem");
};
$(document).ready(function(){
mySocket = io.connect();//create new websocket,
/* ON LOAD sending a json with key term 'buttonBuilder'
which will cause server to respond with a master json used to
build the buttons on the page*/
mySocket.send(JSON.stringify({'buttonBuilder':1}));
document.getElementById('sendOrder').onclick = function (){
mySocket.send(JSON.stringify(orderData));
};
/* FUNCTION TO READ INBOUND DATA*/
mySocket.on('message', function(msg) {
var JSONdata = JSON.parse(msg);
console.log(JSONdata);
/* ALL JSON data coming from server will have one parent key in the tree.
This is used to route the JSON to appropriate place through series of IF's*/
if (Object.keys(JSONdata)[0] === 'buttonBuilder'){
ButtonBuilder(JSONdata,'buttonBuilder');
//PageIsReady is 1 when all buttons are built
};
if(PageIsReady){
//ONLY ASSIGN CLICK HANDLERS WHEN ALL ELEMENTS ARE BUILT IN HTML
/*---- ITEMS Class Click Event-----*/
$('.item').click (function (event) {
var nm = $(this).attr('name');
console.log(nm);
var price = $(this).attr('value');
if (!orderData["orderData"][nm]) {
orderData["orderData"][nm] = 1;}
else {orderData["orderData"][nm] += 1;}
addItemToOrder(nm,orderData["orderData"][nm],price);
event.stopPropagation();});
/*---- SUBBUTTON Class Click Event-----*/
$('.subbutton').not("[name='mods']").click (function (event) {
display_ItemView($(this));
event.stopPropagation();
//return false; //should also work, but sometimes is failing
});
/*--special-- SUBBUTTON Class Name='mods' Click Event-----*/
$("[name='mods']").click (function (event) {
display_ItemModifiers($(this));
event.stopPropagation();
//return false; //should also work, but sometimes is failing
});
/*---- BUTTON Class Click Event-----*/
$('.button').click (function () {
display_CategoryView($(this));
});
};
});
});
|
/// <reference types="Cypress" />
describe("Login", () => {
context("when not logged in", () => {
it("redirects to the login page with a message", () => {
cy.visit('/');
// shows the login form
cy.contains("Log In");
cy.url().should('include', 'login');
// shows an error message
cy.contains("Not logged in");
});
it("can login successfully", () => {
cy.visit('/#/login');
cy.get('[placeholder=Email]')
.type('test@gmail.com');
cy.get('[placeholder=Password]')
.type('password');
cy.get('button.login')
.click();
cy.contains("Welcome to EveryCent")
.should('exist');
});
it("shows an error message if login fails", () => {
cy.visit('/#/login');
cy.get('[placeholder=Email]')
.type('wrong@gmail.com');
cy.get('[placeholder=Password]')
.type('password');
cy.get('button.login')
.click();
cy.contains("Invalid login credentials")
cy.url().should('include', '/login');
});
});
it("can login in the background", () => {
cy.login();
cy.visit('/#/account-balances')
cy.contains('Account Balances')
.should('exist');
});
});
|
angular.module('starter.controllers', [])
.controller('DashCtrl', function($scope) {})
.controller('ChatsCtrl', function($scope, Chats) {
// With the new view caching in Ionic, Controllers are only called
// when they are recreated or on app start, instead of every page change.
// To listen for when this page is active (for example, to refresh data),
// listen for the $ionicView.enter event:
//
//$scope.$on('$ionicView.enter', function(e) {
//});
$scope.chats = Chats.all();
$scope.remove = function(chat) {
Chats.remove(chat);
};
})
.controller('ChatDetailCtrl', function($scope, $stateParams, Chats) {
$scope.chat = Chats.get($stateParams.chatId);
})
.controller('BookCtrl', function($scope, $stateParams, $cordovaGeolocation) {
var options = {timeout: 10000, enableHighAccuracy: true};
$cordovaGeolocation.getCurrentPosition(options).then(function(position){
var latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var mapOptions = {
center: latLng,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
$scope.map = new google.maps.Map(document.getElementById("map"), mapOptions);
google.maps.event.addListenerOnce($scope.map, 'idle', function(){
var marker = new google.maps.Marker({
map: $scope.map,
animation: google.maps.Animation.DROP,
position: latLng
});
});
}, function(error){
console.log("Could not get location");
});
})
.controller('AccountCtrl', function($scope) {
$scope.settings = {
enableFriends: true
};
});
|
import React from 'react'
import moment from 'moment';
const ArticleIndividual = (props) => {
console.log('ai render', props);
let date = new Date(props.data.date);
let formattedDate = moment(date).format("DD/MM/YYYY HH:mm");
return (
<div className="article-individual">
{/* <div className="article-individual-date"><p>{formattedDate}</p></div> */}
<h3><p>{props.data.title}</p></h3>
<img src={props.data.image} alt={props.data.name} width="650px"></img>
<p>{props.data.text}</p>
</div>
)
}
export default ArticleIndividual;
|
import {Form, Input, Button, Radio, Select, DatePicker, Col, Row} from 'antd';
import React from 'react'
import ruleUtils from '../rules/ruleUtils';
const FormItem = Form.Item;
const checkPhone = (rule, value, callback) => {
if (value!='') {
callback();
//console.log(`11111`)
return;
}
//console.log(222)
callback('');
}
const checkEmail = (rule, value, callback) => {
if (ruleUtils.testEmail(value)) {
callback();
//console.log(`11111`)
return;
}
//console.log(222)
callback('');
}
export const FormItemPhone = (props) => {
return (
<FormItem style={{margin: 'auto'}} label={'手机号码·'}>
{
props.fieldDecorator('mobile', {
rules: [{validator: checkPhone}],
})(
<Input placeholder="输入手机号"/>
)}
</FormItem>
)
}
export const FormItemEmail = (props) => {
return (
<FormItem style={{margin: 'auto'}} label={'邮箱'}>
{props.fieldDecorator(`email`, {
// rules: [{validator: checkEmail}]
})(
<Input placeholder="输入邮箱"/>
)}
</FormItem>
)
}
|
const ArgumentInterpreter = require('./structures/ArgumentInterpreter');
const Trello = require('./structures/Trello');
const Util = require('./util');
const prisma = require('./prisma');
module.exports = class Events {
constructor(client) {
this.client = client;
client.on('messageCreate', this.onMessage.bind(this));
client.on('messageReactionAdd', this.onReaction.bind(this));
client.on('interactionCreate', this.onInteractionCreate.bind(this));
client.on('guildDelete', this.onGuildLeave.bind(this));
}
async onMessage(message) {
this.client.stats.messagesRecieved++;
if (message.author.bot || message.author.system) return;
// Don't respond to interaction responses
if (message.type === 20) return;
// Check to see if bot can send messages
if (message.channel.permissionsOf &&
!message.channel.permissionsOf(this.client.user.id).has('sendMessages')) return;
// Don't parse if Taco is in the guild and not using a mention prefix
if (this.client.config.sudoID &&
this.client.user.id !== this.client.config.sudoID &&
message.guildID &&
!new RegExp(`^<@!?${this.client.user.id}>`).test(message.content)) {
const sudoBot = message.channel.guild.members.has(this.client.config.sudoID);
if (sudoBot) return;
}
// Message awaiter
if (this.client.messageAwaiter.processHalt(message)) return;
// Postgres Data
const userData = await prisma.user.findUnique({
where: { userID: message.author.id }
});
if (userData && userData.bannedFromUse) return;
const serverData = message.guildID ?
await prisma.server.findUnique({ where: { serverID: message.guildID } }) : null;
if (serverData && serverData.bannedFromUse) return;
// Prefixes
const userPrefixes = userData ? userData.prefixes : [];
const serverPrefix = serverData && serverData.prefix ? [serverData.prefix] : [this.client.config.prefix];
const prefixes = [...userPrefixes, ...serverPrefix];
// Command parsing
const argInterpretor = new ArgumentInterpreter(Util.Prefix.strip(message, this.client, prefixes));
const args = argInterpretor.parseAsStrings();
const commandName = args.splice(0, 1)[0];
const command = this.client.cmds.get(commandName, message);
if (!message.content.match(Util.Prefix.regex(this.client, prefixes)) || !command) return;
const prefixUsed = message.content.match(Util.Prefix.regex(this.client, prefixes))[1];
const cleanPrefixUsed = message.content.match(new RegExp(`^<@!?${this.client.user.id}>`)) ?
`@${this.client.user.username}#${this.client.user.discriminator} ` : prefixUsed;
const locale = userData && userData.locale ? userData.locale : (serverData ? serverData.locale : null);
const _ = this.client.locale.createModule(locale, { raw: prefixUsed, clean: cleanPrefixUsed });
const trello = new Trello(this.client, userData ? userData.trelloToken : null);
try {
this.client.stats.onCommandRun(message.author.id, command.name);
await command._exec(message, {
args, _, trello,
userData, serverData,
prefixUsed: { raw: prefixUsed, clean: cleanPrefixUsed }
});
} catch (e) {
if (this.client.airbrake) {
await this.client.airbrake.notify({
error: e,
params: {
command: command.name,
user: {
id: message.author.id,
username: message.author.username,
discriminator: message.author.discriminator
},
message: {
id: message.id,
content: message.content,
type: message.type
},
guild: message.guildID ? {
id: message.guildID,
name: message.channel.guild.name
} : undefined,
channel: {
id: message.channel.id,
type: message.channel.type,
name: message.channel.name
}
}
});
}
if (!this.client.airbrake || this.client.config.debug) {
console.error(`The '${command.name}' command failed.`);
console.log(e);
}
message.channel.createMessage(`:fire: ${_('error')}`);
this.client.stopTyping(message.channel);
}
}
onReaction(message, emoji, member) {
const id = `${message.id}:${member.id}`;
if (this.client.messageAwaiter.reactionCollectors.has(id)) {
const collector = this.client.messageAwaiter.reactionCollectors.get(id);
collector._onReaction(emoji, member.id);
}
}
onInteractionCreate(interaction) {
if (interaction.type === 1) return interaction.pong();
if (interaction.type !== 3) return;
const id = `${interaction.message.id}:${
interaction.member ? interaction.member.id : interaction.user.id
}`;
if (this.client.messageAwaiter.componentCollectors.has(id)) {
const collector = this.client.messageAwaiter.componentCollectors.get(id);
collector._onInteract(interaction);
} else interaction.editParent({ components: [
{
type: 1,
components: [
{
type: 2,
style: 2,
label: 'Prompt expired.',
custom_id: 'null',
disabled: true
}
]
}
] });
}
onGuildLeave(guild) {
// deactivate guild webhooks
prisma.webhook.updateMany({
where: { guildID: guild.id },
data: { active: false }
});
}
};
|
const express = require ('express')
// generate a router object from the express library
// A router is sort of an empty 'app' that only has route logic
const router = express.Router()
// a route that says yay
router.get('/new', (reg, res) => {
res.send('Yay new user')
})
// a route that oretends to have deleted a user
router.get('/delete', (reg, res) => {
res.send('Deleted user')
})
// exports the router so the require()
// in the main app knows what to touch
module.exports = router
|
import React from 'react'
import './css/home.css'
import connect from 'redux-connect-decorator';
import { fetchUsers } from '../actions/blogAction'
@connect((store) => {
return {
users: store.blog.users
}
})
export default class Home extends React.Component {
constructor(props) {
super(props);
this.state = {
users: []
}
}
componentDidMount() {
this.props.dispatch(fetchUsers())
}
componentWillReceiveProps(nextProps) {
if (this.props.users !== nextProps.users) {
this.setState({
users: nextProps.users
})
}
}
route(id) {
var url = "/allposts/" + id
this.props.history.push({
pathname: url
})
}
render() {
return (
<div className='container-fluid'>
<div className='container'>
<div className='row'>
{
this.state.users.map((v, i) => {
return (
<div key={'ind_' + i} className='col-4 users-container'
onClick={this.route.bind(this, v.id)}>
<div className='p-4 my-3 users-wrapper'>
<h2 className='post-heading'>{v.name}</h2>
<h5 className='post-body'>{v.email}</h5>
<h4 className='comment-name'>http://{v.website}</h4>
</div>
</div>
)
})
}
</div>
</div>
</div>
)
}
}
|
const videoShowCase = document.getElementsByTagName("video")[0];
videoShowCase.muted = true;
console.log(videoShowCase);
document.querySelector("#icon-search-menu").addEventListener("click", () => {
document.querySelector(".search-box").classList.toggle("active");
});
document.querySelector(".notifications").addEventListener("mouseover", () => {
document.querySelector(".notifications-box").style.display = "block";
});
document.querySelector(".notifications").addEventListener("mouseout", () => {
document.querySelector(".notifications-box").style.display = "none";
});
document.querySelector(".volume-up-principal").addEventListener("click", () => {
console.log(videoShowCase);
$(".fa-volume-up").toggle();
$(".fa-volume-mute").toggle();
videoShowCase.muted = true;
// videoShowCase.play();
});
document
.querySelector(".volume-mute-principal")
.addEventListener("click", () => {
console.log(videoShowCase);
$(".fa-volume-up").toggle();
$(".fa-volume-mute").toggle();
// videoShowCase.pause();
videoShowCase.muted = false;
});
$(".fa-volume-up").on("click", () => {
$(".fa-volume-up").toggle();
$(".fa-volume-mute").toggle();
$("#volume").val(0);
$(media).prop("volume", 0);
// media.play();
currentTime = true;
});
$(".fa-volume-mute").on("click", () => {
$(".fa-volume-up").toggle();
$(".fa-volume-mute").toggle();
$("#volume").val(110);
$(media).prop("volume", 1);
// media.play();
currentTime = true;
});
|
const express = require('express');
const app = express();
const {v4: uuidv4} = require("uuid");
const router = express.Router()
app.use(express.json()) // Permite utilizar json em mais de uma rota.
const pets = [];
/**
* Query params - vamos utilizar para buscar informações especifícas ou toda a informação.
* Route params - Utilizamos para identificar um recurso da nossa rota.
* Request body - Serve para buscar o corpo da requisição que deve ser criada ou alterada.
*/
router.get('/pet', (req, res) =>{
return res.json(pets);
});
router.post('/pet', (req, res) =>{
const {nome, idade, raca, peso, vacina, castracao,
microChip, porte, is_adopted, url_imagem, nomeDono} = req.body; // traz o corpo da requisição.
const pet = {
id: uuidv4(),
nome,
idade,
raca,
peso,
vacina,
castracao,
microChip,
porte,
is_adopted,
url_imagem,
nomeDono
}
pets.push(pet);
return res.json(pet); // sempre retornar o pet criado e não o vetor completo.
})
router.put('/pet/:id', (req, res) =>{
const {id} = req.params;
const {nome, idade, raca, peso, vacina, castracao,
microChip, porte, is_adopted, url_imagem, nomeDono} = req.body;
const petIndex = pets.findIndex(pet => pet.id === id)
if(petIndex < 0){
return res.status(400).json({error: "Pet Não encontrado"})
}
const pet = {
id,
nome,
idade,
raca,
peso,
vacina,
castracao,
microChip,
porte,
is_adopted,
url_imagem,
nomeDono
}
pets[petIndex] = pet;
return res.json(pet);
})
router.delete('/pet/:id', (req, res) =>{
const {id} = req.params;
const petIndex = pets.findIndex(pet => pet.id === id)
if(petIndex < 0){
return res.status(400).json({error: "Pet Não encontrado"})
}
pets.splice(petIndex, 1);
return res.json({msg: "Pet deletado com sucesso"}).status(204)
})
module.exports = router
// app.listen(port, _ => console.log(`Running at port: ${port}`));
|
const path = require('path');
const express = require('express');
const rootDir = require('../util/path');
const router = express.Router();
router.get('/protected-section-1', (req, res, next)=>{
res.render('protected', {content: 'Protected Section'});
});
router.post('/protected-section-1', (req, res, next)=>{
console.log(req.body);
res.redirect('/')
});
module.exports=router;
|
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var toDoSchema = new Schema({
title: { type: String, reqiured: true },
comment: String,
deadline: { type: Date, default: undefined},
done: { type: Boolean, default: false },
});
var toDo = mongoose.model('toDo', toDoSchema);
module.exports = toDo;
|
var a;
(function() {a=50})();
|
import constants from '../constants.js'
export { handleMissingInput }
const handleMissingInput = (inputToCheck, notificationElement) => {
const inputValue = inputToCheck.value
if(inputValue === '') {
inputToCheck.classList.add('missing-input')
notificationElement.textContent = constants.MELDUNG_BITTE_ERGAENZEN
} else {
inputToCheck.classList.remove('missing-input')
}
}
|
import types from './model/actionTypes'
import * as http from './http.fake'
export default Object.freeze({
[types.getNumber]: async ({ id = 'blah', a, b, cached } = {}) =>
http.get(`/numbers/${id}`, {a, b}, cached),
[types.setNumber]: async ({ id = 'blah', number } = {}) =>
http.set('POST', `/numbers/${id}`, number),
[types.addNumber]: async ({ id = 'blah', number } = {}) =>
http.set('PUT', `/numbers/${id}`, number),
})
|
import React from 'react';
import Button from './Button.jsx';
// https://www.npmjs.com/package/crontrans
class CronList extends React.Component {
constructor() {
super();
}
render() {
if (this.props.data.length > 0) {
let cronNodes = this.props.data.map((cron, i) => {
if (cron) {
let boundClick = this.props.onDeleteCronHandler.bind(this, cron.comment);
return (
<li key={i} ref={'cron' + i} title={cron.comment}>
<p><span className="label label-default">{cron.expression}</span></p>
<p><small><em>{cron.comment}</em></small></p>
<Button onClick={boundClick}>
Delete
</Button>
</li>
);
}
});
if (cronNodes.length > 0) {
return (
<ul className="cron-list">
{cronNodes}
</ul>
);
} else {
return (
<p>No crons found</p>
);
}
} else {
return (
<p>No crons found</p>
);
}
}
}
export default CronList;
|
// \x00\x01...\xAB
var data = "<DATA>";
var url = "<URL>";
xhr = new XMLHttpRequest():
xhr.open("POST", url, true);
var boundary = "---------------------------";
boundary += Math.floor(Math.random()*32768);
boundary += Math.floor(Math.random()*32768);
boundary += Math.floor(Math.random()*32768);
xhr.setRequestHeader("Content-Type", "multipart/form-data; boundary=" + boundary);
var body = "";
body += "--";
body += boundary;
body += "\r\n";
body += 'Content-Disposition: form-data; name="fileField"; filename="test.ext"';
body += "\r\n";
// e.g. application/gzip image/png
body += "Content-Type: <CONTENT_TYPE>";
body += "\r\n";
body += "\r\n";
body += data;
body += "\r\n";
body += "--";
body += boundary;
body += "--";
body += "\r\n";
var aBody = new Uint8Array(body.length);
for (var i = 0; i < aBody.length; i++)
aBody[i] = body.charCodeAt(i);
xhr.send(new Blob([aBody]));
|
import React from 'react';
import withStore from '~/hocs/withStore';
import styles from './about.scoped.css';
class About extends React.Component {
constructor(props) {
super(props);
this.TEXT = this.props.stores.textsStore;
this.versions = this.props.stores.versions;
}
render() {
let versionsRows = this.versions.versions.map((ver, i) => {
let changes = ver.changes.map((change, index) => <li key={index}>- {change}</li>);
let verTitle = () => {
if (ver.current) {
return <td> {ver.ver} <br/> {this.TEXT.versions_current}</td>
}
return <td>{ver.ver}</td>
}
return (
<tr key={i}>
{verTitle()}
<td>
<ul>
{changes}
</ul>
</td>
</tr>
);
});
return (
<div className="container">
<h1>{this.TEXT.about_title}</h1>
<div className={styles.content+' content'}>
<p>{this.TEXT.about_row1}</p>
<p>{this.TEXT.about_authorTitle} <span>{this.TEXT.author}</span>.</p>
<p>{this.TEXT.about_versionTitle} <span>{this.TEXT.version}</span>.</p>
<div className="history">
<h3>{this.TEXT.about_historyTitle}</h3>
<table className={styles.table+' table table-light1 table-striped'}>
<thead>
<tr className="table-success fw-bold">
<th>{this.TEXT.versions_title}</th>
<th>{this.TEXT.versions_changes}</th>
</tr>
</thead>
<tbody>
{versionsRows}
</tbody>
</table>
</div>
</div>
</div>
)
}
}
export default withStore(About);
|
'use strict';
var gulp = require('gulp');
var webpack = require('gulp-webpack');
var run = require('run-sequence');
var BrowserSyncPlugin = require('browser-sync-webpack-plugin');
/**
* Creates a default development instance and watches for app changes
* and rebuilds while developing your application.
*/
gulp.task('default', [ 'build:dev' ], function () {
gulp
.src('./app.jsx')
.pipe(webpack({
watch: true,
output : {
filename : 'app.js'
},
module : {
loaders : [
{ test: /\.jsx?$/, loaders: [ 'react-hot', 'babel?stage=1' ], exclude: /node_modules/ },
{ test: /\.scss$/, loaders: [ 'style', 'css', 'sass' ] },
{ test: /\.(?:jpe?g|png|gif|svg)$/, loader: 'url?limit=10000&name=[name].[sha512:hash:base64:7].[ext]' }
]
},
plugins: [
new BrowserSyncPlugin({
host : 'localhost',
port : 3081,
server : { baseDir: [ 'build' ] }
})
]
}))
.pipe(gulp.dest('./build'))
;
gulp.watch('./config/**/*', [ 'reach:config' ]);
gulp.watch('./assets/**/*', [ 'copy:assets' ]);
gulp.watch('./index.html', [ 'copy:index' ]);
});
/**
* Build Development
*/
gulp.task('build:dev', function (done) {
run(
'reach:config',
// 'lint',
'copy:assets',
'copy:index',
done
);
});
|
// require('dotenv').config({ path: '.env' });
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const socketIO = require('socket.io');
const http = require('http');
const app = express();
const server = http.createServer(app);
const io = socketIO(server);
app.use(cors())
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.post('/update-editor', (req, res) => {
io.sockets.emit('text-update', {
...req.body,
});
res.status(200).send('OK');
});
app.set('port', process.env.PORT || 5000);
server.listen(app.get('port'), () => {
console.log(`Express running → PORT ${server.address().port}`);
});
|
const fs = require("fs");
const fsp = fs.promises;
/**
* Try to unlink a file, silently failing if the file doesn't exist.
* @param {string | Buffer | URL} path
*/
module.exports = async function unlinkOptional(path) {
try {
await fsp.unlink(path);
} catch (e) {
if (e.code === "ENOENT") return;
else throw e;
}
};
|
/**
* @project iii-for-vk
* @author Valentin Popov <info@valentineus.link>
* @license See LICENSE.md file included in this distribution.
*/
import urlParseLax from 'url-parse-lax';
import queryString from 'querystring';
import iiiClient from 'iii-client';
import EventEmitter from 'events';
import inherits from 'inherits';
import https from 'https';
import SDK from 'vksdk';
inherits(Bot, EventEmitter);
module.exports = Bot;
/**
* Class representing a Bot.
* @class
*/
function Bot(opts) {
opts = opts || {};
var self = this;
self.uuid = opts.uuid;
self.token = opts.token;
self.appID = opts.appID;
self.appSecret = opts.appSecret;
}
/**
* Initial initialization of all systems and services.
* @param {requestCallback} callback - The callback that handles the response.
*/
Bot.prototype.init = function(callback) {
var self = this;
// Initialize the connection to the social network
self._vk = new SDK({
appId: self.appID,
appSecret: self.appSecret,
https: true,
secure: true
});
// Setting the user's token
self._vk.setToken(self.token);
// Starting services
self._eventLoop();
// Connecting filters
self._filterMessages();
// Connecting to the bot server
iiiClient.connect(self.uuid, (raw) => callback(raw.cuid));
};
/**
* Receive a message by its ID.
* @param {Number} id - The message ID.
* @param {requestCallback} callback - The callback that handles the response.
*/
Bot.prototype.getMessageByID = function(id, callback) {
id = id || false;
var self = this;
self._vk.request('messages.getById', {
message_ids: id,
preview_length: 0
}, (raw) => {
if (raw.error) throw new Error(raw.error.error_msg);
callback(raw.response.items.shift());
});
};
/**
* Simplifies the sending of a message to the user.
* The social network API is used.
* More information: https://vk.com/dev/messages.send
* @param {Object} options - Object with parameters.
* @param {Object} options.user_id - User ID.
* @param {Object} options.message - Message text.
* @param {requestCallback} callback - The callback that handles the response.
*/
Bot.prototype.sendMessageToVK = function(options) {
options = options || {};
var self = this;
self._vk.request('messages.send', options, () => {});
};
/**
* Simplifies sending a message to the bot.
* @param {Object} options - Object with parameters.
* @param {Object} options.cuid - Session identifier.
* @param {Object} options.text - Message text.
* @param {requestCallback} callback - The callback that handles the response.
*/
Bot.prototype.sendMessageToBot = function(options, callback) {
options = options || {};
iiiClient.send(options, (answer) => callback(answer));
};
/**
* The event startup service.
*/
Bot.prototype._eventLoop = function() {
var self = this;
self._getEvents();
self.on('events', (data) => {
self._getEvents(data.ts);
});
};
/**
* Filter events for incoming messages.
* @fires: Bot#messages
*/
Bot.prototype._filterMessages = function() {
var self = this;
self.on('events', function(data) {
data.updates.filter(function(item) {
if (item[0] == 4) self.emit('messages', item);
});
});
};
/**
* Obtaining the Long Poll server address.
* @param {requestCallback} callback - The callback that handles the response.
*/
Bot.prototype._getLongPollServer = function(callback) {
var self = this;
self._vk.request('messages.getLongPollServer', {
need_pts: false
}, (raw) => {
if (raw.error) throw new Error(raw.error.error_msg);
callback(raw.response);
});
};
/**
* Waiting and returning the event.
* @fires: Bot#events
* @param {String=} [ts] - The ID of the last event.
*/
Bot.prototype._getEvents = function(ts) {
var self = this;
// Server address request
self._getLongPollServer(function(raw) {
ts = ts || raw.ts;
// Analysis of the connection address
var url = urlParseLax(raw.server);
// Details: https://vk.com/dev/using_longpoll
var options = queryString.stringify({
act: 'a_check',
key: raw.key,
ts: ts,
wait: 25,
mode: 2,
version: 1
});
// Configuring the connection
var query = {
hostname: url.hostname,
path: url.pathname + '?' + options
};
https.get(query, function(response) {
var answer = {};
response.setEncoding('utf8');
response.on('data', (data) => answer = data);
response.on('end', () => {
answer = JSON.parse(answer);
self.emit('events', answer);
});
}).on('error', (error) => Error(error));
});
};
|
import { Button } from '@material-ui/core';
import { useContext } from 'react';
import { getAlbumList } from '../../../apis/albumActions';
import { DatabaseContext } from '../../../DatabaseContext';
import AlbumList from './album-list/AlbumList';
import './AlbumPage.css';
function AlbumPage() {
const data = useContext(DatabaseContext);
data.setPageTitle("Browse albums");
if (data.albumList.length === 0) {
reloadAlbums(data);
}
return (
<div className="AlbumPage">
<div className="PageTop">
<Button
variant="outlined"
color="primary"
onClick={ () => reloadAlbums(data) }>
Refresh
</Button>
</div>
<div className="PageBottom">
<AlbumList albums={ data.albumList } />
</div>
</div>
);
}
export default AlbumPage;
function reloadAlbums(data) {
getAlbumList(data);
}
|
import { Route } from "react-router-dom";
import "./App.css";
import Home from "./components/Home";
import NavBar from "./components/NavBar";
import About from "./components/About";
import Contact from "./components/Contact";
import WishList from "./components/WishList";
import Login from "./components/Login";
import Signup from "./components/Signup";
import RequestBook from "./components/RequestBook";
import Logout from "./components/Logout";
import Library from "./main_components/Library";
import BookDetails from "./main_components/BookDetails";
import Profile from "./components/Profile";
import Todo from "./components/Todo";
function App() {
return (
<>
<NavBar />
<Route exact path="/">
<Home />
</Route>
<Route exact path="/about">
<About />
</Route>
<Route exact path="/contact">
<Contact />
</Route>
<Route exact path="/login">
<Login />
</Route>
<Route exact path="/signup">
<Signup />
</Route>
<Route exact path="/wishlist/:id">
<WishList />
</Route>
<Route exact path="/logout">
<Logout />
</Route>
<Route exact path="/request">
<RequestBook />
</Route>
<Route exact path="/profile/:id">
<Profile />
</Route>
<Route exact path="/library/:id">
<Library />
</Route>
<Route exact path="/bookdetails/:id/:uid">
<BookDetails />
</Route>
</>
);
}
export default App;
|
export const config = {
username: 'test',
password: 'test',
secret: 'WhiskeyWhiskeyWhiskey',
};
|
"use strict";
/*
Copyright [2014] [Diagramo]
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.
*/
/**
* Used to undo actions when the canvas changes his color
* @this {CanvasChangeColorCommand}
* @constructor
* @param {String} newColor - the new Color of canvas
* @author Alex, Artyom
*/
function CanvasChangeColorCommand(newColor){
this.previousColor = canvasProps.fillColor;
this.color = newColor;
this.oType = "CanvasChangeColorCommand";
}
CanvasChangeColorCommand.prototype = {
constructor : CanvasChangeColorCommand,
/**This method got called every time the Command must execute*/
execute : function(){
//Attention: canvasProps is a global variable
canvasProps.setFillColor(this.color);
},
/**This method should be called every time the Command should be undone*/
undo : function(){
//Attention: canvasProps is a global variable
canvasProps.setFillColor(this.previousColor);
setUpEditPanel(canvasProps);
}
};
|
loginCheck("orders");
function _getDate() {
var month_names = new Array("Января", "Февраля", "Марта", "Апреля", "Мая", "Июня", "Июля", "Августа", "Сентября", "Октоября", "Ноября", "Декабря");
var d = new Date();
var current_date = d.getDate();
var current_month = d.getMonth();
var current_year = d.getFullYear();
var date_now = "Сегодня: <b>"+current_date + " " + month_names[current_month] + " " + current_year + " г.</b>";
document.getElementById("currentDate").innerHTML=date_now;
//alert(date_now);
}
function setCurrentWeek(){
var xmlhttp=ajaxConnect();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState===4 && xmlhttp.status===200)
{
var fromPHPs=xmlhttp.responseText;
//alert("setCurrntWeek.fromPHPs="+fromPHPs);
try{
//var fromPHPobj=JSON.parse(fromPHPs);
var fromPHPobj=!(/[^,:{}[]0-9.-+Eaeflnr-u nrt]/.test(fromPHPs.replace(/"(.|[^"])*"/g, ''))) && eval("(" + fromPHPs + ")");
var cd=new Date();
//alert(cd);
var Year=cd.getFullYear();//alert(Year);
var objSelW = document.getElementById("selWeek");
for(var i=0;i<53;i++){
objSelW.options[i] = new Option(i+1,i+1);
}
objSelW.selectedIndex = fromPHPobj["week"]-1; // устанавливаем текущий номер недели
//////////////////////
var obj=document.getElementById("selMonth");
obj.options.length=0;
var n="0";
for(var j=1;j<=12;j++){
if(j<10){
n="0"+j;
}else{n=j;}
var option = document.createElement("option");
option.text=n;
option.value=n;
obj.add(option,null);
}
document.getElementById("selMonth").value = fromPHPobj["month"];
var obj=document.getElementById("selYear");
obj.options.length=0;
for(var j=Year-2;j<=Year+1;j++){
var option = document.createElement("option");
option.text=j;
option.value=j;
obj.add(option,null);
}
document.getElementById("selYear").value = fromPHPobj["year"];
document.getElementById("divCalendar").innerHTML = fromPHPobj["calendar"];
loadOrders();
}catch(e){
alert("Что то не то с ответом setCurrentWeek: "+e);
}
}
};
xmlhttp.open("POST","scr_orders.php?timeStamp="+new Date().getTime()+"&f=11",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send();
//alert("Посылаем запрос в "+new Date());
document.getElementById("abtnChange").disabled=true;
document.getElementById("abtnDeleteOrder").disabled=true;
document.getElementById("abtnCanselChange").disabled=true;
}
//Проверяем номер
function onliNumer(num){
//alert("Blur");
num = num.toString().replace(/\,/g, '.');//замена запятой на точку
if (isNaN(num)) num = "0";// определяем переменную
return Math.floor(num);
}
//создание объекта XMLHttpRequest
function ajaxConnect() {
var xmlhttp;
if ( window.XMLHttpRequest ) {
// Для современных браузеров IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// Для старых браузеров IE6, IE5
xmlhttp = new ActiveXObject ( "Microsoft.XMLHTTP" );
}
return xmlhttp;
}
//////////////////////////////////////////////////////////
//Показать кнопку Вставить
function showPlusMinus(){
document.getElementById("countInputs").style.display="block";
document.getElementById("plus").style.display="block";
document.getElementById("minus").style.display="block";
document.getElementById("abtnAdd").disabled=false;
document.getElementById("abtnChange").disabled=true;
document.getElementById("abtnDeleteOrder").disabled=true;
document.getElementById("abtnCanselChange").disabled=true;
}
///////////////////////////////////////////////////////
//Скрыть кнопку Вставить
function hiddenPlusMinus(){
document.getElementById("countInputs").style.display="none";
document.getElementById("plus").style.display="none";
document.getElementById("minus").style.display="none";
if(document.getElementById("check").checked){
document.getElementById("abtnAdd").disabled=true;
document.getElementById("abtnChange").disabled=true;
document.getElementById("abtnDeleteOrder").disabled=true;
document.getElementById("abtnCanselChange").disabled=true;
}else{
document.getElementById("abtnAdd").disabled=false;
document.getElementById("abtnChange").disabled=false;
document.getElementById("abtnDeleteOrder").disabled=false;
document.getElementById("abtnCanselChange").disabled=false;
}
}
function logout(){
var xmlhttp=ajaxConnect();
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState===4 && xmlhttp.status===200){
var fromPHPs=xmlhttp.responseText;
//alert("logout.fromPHPs="+fromPHPs);
try{
loginCheck();
}catch(e){
alert("logout: "+e);
}
}
};
xmlhttp.open("POST","scr_orders.php?timeStamp="+new Date().getTime()+"&f=10",false);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send();
}
var setIntervalID=0;
var delay=5;
function display(){
if(delay>1){
delay--;
document.getElementById("sec").innerHTML=delay;
}else{
delay=5;
document.getElementById("login").value="";
document.getElementById("pass").value="";
document.getElementById("btnLogin").disabled=false;
document.getElementById("delay_txt").innerHTML="<h3>Пожалуйста, введите логин и пароль!</h3>";
document.getElementById("login").focus();
clearInterval(setIntervalID);
}
}
//function loginCheck(){
//var xmlhttp=ajaxConnect();
// xmlhttp.onreadystatechange=function(){
// if (xmlhttp.readyState===4 && xmlhttp.status===200){
// var fromPHPs=xmlhttp.responseText;
// //alert("loginCheck.fromPHPs="+fromPHPs);
// try{
// var fromPHPobj=!(/[^,:{}[]0-9.-+Eaeflnr-u nrt]/.test(fromPHPs.replace(/"(.|[^"])*"/g, ''))) && eval("(" + fromPHPs + ")");
// if(!fromPHPobj["loginCheck"]){
// showLoginWindow(fromPHPobj["count"]);
// }else{
// if(fromPHPobj["levelM"]===-2)document.getElementById("nextPage").style.display="none";
// setCurrentWeek();
// document.getElementById("check").checked=false;
// // Отключаем окно
// $('#account').hide();
// // Выключаем задник
// if((document.getElementById("bgOverlay").style.display="block"))
// $('#bgOverlay').empty();
// second=0;
// clearInterval(setIntervalID);
//
// }
// }catch(e){
// alert("loginCheck: "+e);
// }
//
// }
// };
// xmlhttp.open("POST","scr_orders.php?timeStamp="+new Date().getTime()+"&f=0",false);
// xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
// xmlhttp.send();
//}
//function showLoginWindow($count){
// // Отображаем и центрируем окно
// var loginWindow = $('#account');
// loginWindow.css(
// {
// position: 'absolute',
// left: ( $(document).width() - loginWindow.outerWidth() ) / 2,
// top: 300,
// 'z-index': '100'
// });
// loginWindow.show();
// document.getElementById("login").focus();
// // включаем задник
// document.getElementById("bgOverlay").innerHTML= '<div id="TB_overlay"></div>';
// document.getElementById("delay_txt").innerHTML="<h3>Пожалуйста, введите логин и пароль!</h3>";
// if($count>0){
// document.getElementById("btnLogin").disabled=true;
// document.getElementById("delay_txt").innerHTML='<H3><font color="red">У Вас нет прав на вход!</font><br>Начать авторизацию можно через <span id="sec">'+delay+'</span> секунд.</H3>';
// clearInterval(setIntervalID);
// setIntervalID=setInterval('display()',1000);
// }else document.getElementById("btnLogin").disabled=false;
//}
//// Закрытие окна
//function closeLoginWindow(){
// // Отключаем окно
// $('#account').hide();
// // Выключаем задник
// if((document.getElementById("bgOverlay").style.display="block"))
// $('#bgOverlay').empty();
// clearInterval(setIntervalID);
//}
//function clickLoginButton(){
//var xmlhttp=ajaxConnect();
// xmlhttp.onreadystatechange=function(){
// if (xmlhttp.readyState===4 && xmlhttp.status===200){
// var fromPHPs=xmlhttp.responseText;
// //alert("clickLoginButton.fromPHPs="+fromPHPs);
// try{
// var fromPHPobj=!(/[^,:{}[]0-9.-+Eaeflnr-u nrt]/.test(fromPHPs.replace(/"(.|[^"])*"/g, ''))) && eval("(" + fromPHPs + ")");
// if(!fromPHPobj["loginCheck"]){
// loginCheck();
// document.getElementById("delay_txt").innerHTML='<h3><font color="red">У Вас нет прав на вход!</font><br>Начать авторизацию можно через <span id="sec">'+delay+'</span> секунд.</h3>';
// second=1;
// clearInterval(setIntervalID);
// setIntervalID=setInterval('display()',1000);
// }else{
// if(fromPHPobj["levelM"]===-2)document.getElementById("nextPage").style.display="none";
// closeLoginWindow();
// setCurrentWeek();
// }
// }catch(e){
// alert("clickLoginButton: "+e);
// }
// }
// };
// data={};
// data.login=document.getElementById("login").value;
// data.pass=document.getElementById("pass").value;
// if(data.login!=='' && data.pass!==''){
// document.getElementById("btnLogin").disabled=true;
// xmlhttp.open("POST","scr_orders.php?timeStamp="+new Date().getTime()+"&f=0",false);
// xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
// xmlhttp.send("data="+JSON.stringify(data));
// }
//}
function addInput(){
var xmlhttp=ajaxConnect();
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState===4 && xmlhttp.status===200){
var fromPHPs=xmlhttp.responseText;
//alert("addInput.fromPHPs="+fromPHPs);
try{
var fromPHPobj=!(/[^,:{}[]0-9.-+Eaeflnr-u nrt]/.test(fromPHPs.replace(/"(.|[^"])*"/g, ''))) && eval("(" + fromPHPs + ")");
var parentDiv=document.getElementById("models");
var newDiv=document.createElement('div');
var k=parentDiv.getElementsByTagName('div').length;
k++;
if(k<11){
newDiv.id="line"+k;
newDiv.innerHTML='<span id="span_m_id'+k+'"><input type="hidden" id="m_id'+k+'"></span>';
var sel='<span id="span_m'+k+'"><select id="aModel'+k+'">';
var opt='';
if(fromPHPobj["status"]===1){
for(var i in fromPHPobj["models"]){
opt+='<option value="'+fromPHPobj["models"][i]+'">'+fromPHPobj["models"][i]+'</option>';
}
}
sel+=opt;
sel+='</select></span>';
newDiv.innerHTML+=sel;
newDiv.innerHTML+='<span id="span_c'+k+'"><input type="text" id="aCount'+k+'" onBlur="this.value=onliNumer(this.value)"></span>';
parentDiv.appendChild(newDiv);
document.getElementById("aModel"+k).selectedIndex=-1;
}
document.getElementById("countInputs").selectedIndex=parentDiv.getElementsByTagName('div').length-1;
}catch(e){
alert("addInput: "+e);
}
}
};
var data={};
data.check=false;
xmlhttp.open("POST","scr_orders.php?timeStamp="+new Date().getTime()+"&f=7",false);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("data="+JSON.stringify(data));
}
function addInputCheck(){
var xmlhttp=ajaxConnect();
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState===4 && xmlhttp.status===200){
var fromPHPs=xmlhttp.responseText;
//alert("addInputCheck.fromPHPs="+fromPHPs);
try{
var fromPHPobj=!(/[^,:{}[]0-9.-+Eaeflnr-u nrt]/.test(fromPHPs.replace(/"(.|[^"])*"/g, ''))) && eval("(" + fromPHPs + ")");
if(fromPHPobj["status"]===1){
var parentDiv=document.getElementById("models");
//parentDiv=innerHTML='';
var newDiv=document.createElement('div');
var k=parentDiv.getElementsByTagName('div').length;
k++;
if(k<11){
newDiv.id="line"+k;
newDiv.innerHTML='<input type="hidden" id="m_id'+k+'">';
newDiv.innerHTML='<input type="text" id="sel'+k+'">';
sel='<select id="section'+k+'" onChange="checkOrder(this.value,document.getElementById(\'sel'+k+'\').value)">';
var opt='';
var j=0;
for( j in fromPHPobj["sections"]){
opt+='<option value="'+fromPHPobj["sl_id"][j]+'">'+fromPHPobj["sections"][j]+'</option>';
}
sel+=opt;
sel+='</select>';
newDiv.innerHTML+=sel;
//alert(newDiv.innerHTML);
parentDiv.appendChild(newDiv);
//document.getElementById("sel"+k).selectedIndex=-1;
document.getElementById("section"+k).selectedIndex=-1;
}
document.getElementById("countInputs").selectedIndex=parentDiv.getElementsByTagName('div').length-1;
}
}catch(e){
alert("addInputCheck: "+e);
}
}
};
var data={};
data.check=true;
xmlhttp.open("POST","scr_orders.php?timeStamp="+new Date().getTime()+"&f=7",false);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("data="+JSON.stringify(data));
}
function removeInput(){
var parentDiv=document.getElementById("models");
var q=parentDiv.getElementsByTagName('div');
if(q.length>1){
q[q.length - 1].parentNode.removeChild(q[q.length - 1]);
}
document.getElementById("countInputs").selectedIndex=q.length-1;
}
//количество редакторов для модели и количества изделий
function countInputs(n){
var parentDiv=document.getElementById("models");
if(parentDiv.getElementsByTagName('div')===undefined)
var k=0;
else
var k=parentDiv.getElementsByTagName('div').length;
if(n===undefined){
if (k===0){n=1;
for(var i=0;i<n;i++){
addInput();
}
}
}else{
if(k>n){
for(var i=n;i<k;i++)
removeInput();
}
if(k<n){
for(var i=k;i<n;i++)
addInput();
}
}
}
////////////////////////////////////////////////////
//вывод таблицы со списком ордеров для указанной недели
function loadOrders(){
//alert("loadWeek is runing");
var xmlhttp=ajaxConnect();
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState===4 && xmlhttp.status===200){
fromPHPs=xmlhttp.responseText;
//alert("loadOrders.fromPHPs="+fromPHPs);
try{
var fromPHPobj=!(/[^,:{}[]0-9.-+Eaeflnr-u nrt]/.test(fromPHPs.replace(/"(.|[^"])*"/g, ''))) && eval("(" + fromPHPs + ")");
if(fromPHPobj["status"]){
var aList='<table id="tblList" cellpadding="0">';
aList+='<tr id="trList"><th id="thNo">No</th><th id="thOrder">СПИСОК ОРДЕРОВ</th></tr>';
var n=1;
for(var i=0;i<fromPHPobj["data"].length;i++){
aList += '<tr class="trList">';
aList += '<td class="tdId">'+n+'.</td>';
aList += '<td class="tdOrder" onclick="selectOrder('+fromPHPobj["data"][i]["a_id"]+');">';
aList += '<a href="#">'+fromPHPobj["data"][i]["order"]+'</a></td></tr>';
n++;
}
aList += '<tr class="trList"><td> </td><td> </td></tr></table>';
document.getElementById("table_div").innerHTML=aList;
document.getElementById("note").innerHTML="";
}else{
document.getElementById("table_div").innerHTML='';
document.getElementById("note").innerHTML="Ордеров нет";
}
}catch(e){
document.getElementById("note").innerHTML="Ордеров нет";
}
}
};
if(!document.getElementById("check").checked)
countInputs(1); //прорисовываем поля модели-количества
//alert("check="+document.getElementById("check").checked);
var data=new Object();
data.aWeek=document.getElementById("selWeek").value;
data.month=document.getElementById("selMonth").value;
data.aYear=document.getElementById("selYear").value;
xmlhttp.open("POST","scr_orders.php?timeStamp="+new Date().getTime()+"&f=1",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("data="+JSON.stringify(data));
//alert("value="+JSON.stringify(data));
}
//////////////////////////////////////////////////////
var selWeek=0;
var selMonth=0;
var selYear=0;
function updateVisible(){
selWeek=document.getElementById("selWeek").value;
selMonth=document.getElementById("selMonth").value;
selYear=document.getElementById("selYear").value;
document.getElementById("weekMonthYear").style.display="none";
document.getElementById("abtnAdd").style.display="none";
document.getElementById("UweekMonthYear").style.display="block";
document.getElementById("txtUpdateDate").style.display="block";
document.getElementById("abtnDubl").style.display="block";
/*document.getElementById("selWeek").style.display="none";
document.getElementById("selMonth").style.display="none";
document.getElementById("selYear").style.display="none";
document.getElementById("UselWeek").style.display="blok";
document.getElementById("UselMonth").style.display="blok";
document.getElementById("UselYear").style.display="blok";
*/
}
function check(){
if(document.getElementById("check").checked){
aCanselClick();
hiddenPlusMinus();
loadOrders();
document.getElementById("abtnAdd").desabled=true;
document.getElementById("models").innerHTML="";
document.getElementById("textCheck").style.color='#FF3300';
document.getElementById("txtModel").innerHTML="МОДЕЛЬ - РАЗДЕЛ";
}
if(!document.getElementById("check").checked){
document.getElementById("models").innerHTML="";
loadOrders();
aCanselClick();
document.getElementById("textCheck").style.color='#000';
document.getElementById("raport").style.display="none";
document.getElementById("right").style.display="block";
document.getElementById("txtModel").innerHTML="МОДЕЛЬ - КОЛИЧЕСТВО";
}
}
function checkOrder(sl_id,mName){
var xmlhttp=ajaxConnect();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState===4 && xmlhttp.status===200)
{
var fromPHPs=xmlhttp.responseText;
//alert("checkOrder.fromPHPs: "+fromPHPs);
try{
fromPHPobj=!(/[^,:{}[]0-9.-+Eaeflnr-u nrt]/.test(fromPHPs.replace(/"(.|[^"])*"/g, ''))) && eval("(" + fromPHPs + ")");
if(fromPHPobj["login"]){
var str='<div id="OrderModel">Ордер: "<span id="tblROrder">'+data.order+'</span>"<br>Model: "<span id="tblRModel">'+data.mName+'</span>"</div>';
str+='<table id="tblR">';
str+='<tbody id="tblRBody">';
str+='<tr>';
str+='<th id="tblRBodyF">Фамилия, Имя</th>';
str+='<th id="tblRBodyS">№</th>';
str+='<th id="tblRBodyC">Количе-<br>ство</th>';
str+='</tr>';
for(var i in fromPHPobj["List"]){
str+='<tr>';
str+='<td class="tdRF">'+fromPHPobj["List"][i]["family"]+' '+fromPHPobj["List"][i]["name"]+'</td>';
str+='<td class="tdRS">'+fromPHPobj["List"][i]["serial"]+'</td>';
str+='<td class="tdRС">'+fromPHPobj["List"][i]["countDid"]+'</td>';
str+='</tr>';
}
str+='</tbody>';
str+='</table>';
//alert("str="+str);
document.getElementById("raport").innerHTML=str;
document.getElementById("raport").style.display="block";
document.getElementById("right").style.display="none";
}
}catch(e){
alert("Что то не то с ответом checkOrder "+e);
}
}
};
//alert("data="+data);
data={};
data.order=document.getElementById("aOrder").value;
data.sl_id=sl_id;
data.mName=mName;
data.week=document.getElementById("selWeek").value;
data.month=document.getElementById("selMonth").value;
data.year=document.getElementById("selYear").value;
xmlhttp.open("POST","scr_orders.php?timeStamp="+new Date().getTime()+"&f=9",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("data="+JSON.stringify(data));
//alert("data="+JSON.stringify(data));
}
//выбор строки из списка ордеров
function selectOrder(a_id){
document.getElementById("valueSelectOrderId").value=a_id;
//document.getElementById("valueSelectOrder").value=order;
var xmlhttp=ajaxConnect();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState===4 && xmlhttp.status===200)
{
var fromPHPs=xmlhttp.responseText;
//alert("selectOrder.fromPHPs: "+fromPHPs);
try{
fromPHPobj=!(/[^,:{}[]0-9.-+Eaeflnr-u nrt]/.test(fromPHPs.replace(/"(.|[^"])*"/g, ''))) && eval("(" + fromPHPs + ")");
if(document.getElementById("check").checked){
hiddenPlusMinus();
document.getElementById("aOrder").value=fromPHPobj["order"];
var parentDiv=document.getElementById("models");
var n=parentDiv.getElementsByTagName('div').length;
if(fromPHPobj["n"]>n){
for(var i=n;i<fromPHPobj["n"];i++){
addInputCheck();
}
}else if(fromPHPobj["n"]<n){
for(var i=fromPHPobj["n"];i<n;i++){
removeInput();
}
}
var k=1;
for(var i=0;i<fromPHPobj["n"];i++){
document.getElementById("sel"+k).value=fromPHPobj["models"][i]["model"];
// for(var i in fromPHPobj["models"]){
// document.getElementById("m_id"+k).value=fromPHPobj["models"][i]["m_id"];
// for(var j=0;j<document.getElementById("sel"+k).options.length;j++){
// if(fromPHPobj["models"][i]["model"]===document.getElementById("sel"+k).options[j].text){
// document.getElementById("sel"+k).selectedIndex=j;
// }
// }
k++;
}
}else{
updateVisible();
var objSelW = document.getElementById("UselWeek");
for(var i=0;i<53;i++){
objSelW.options[i] = new Option(i+1,i+1);
}
//alert(fromPHPobj["aWeek"]);
objSelW.selectedIndex = fromPHPobj["aWeek"]-1; // устанавливаем текущий номер недели
var obj=document.getElementById("UselMonth");
obj.options.length=0;
var n="0";
for(var j=1;j<=12;j++){
if(j<10){
n="0"+j;
}else{n=j;}
var option = document.createElement("option");
option.text=n;
option.value=n;
obj.add(option,null);
}
var m=fromPHPobj["month"];
if(m<10)m="0"+m;
document.getElementById("UselMonth").value=m;
var cd=new Date();
var Year=cd.getFullYear();//alert(Year);
var obj=document.getElementById("UselYear");
obj.options.length=0;
for(var j=Year-2;j<=Year+1;j++){
var option = document.createElement("option");
option.text=j;
option.value=j;
obj.add(option,null);
}
document.getElementById("UselYear").value = fromPHPobj["aYear"];
hiddenPlusMinus();
document.getElementById("aOrder").value=fromPHPobj["order"];
var parentDiv=document.getElementById("models");
var n=parentDiv.getElementsByTagName('div').length;
if(fromPHPobj["n"]>n){
for(var i=n;i<fromPHPobj["n"];i++){
addInput();
}
}else if(fromPHPobj["n"]<n){
for(var i=fromPHPobj["n"];i<n;i++){
removeInput();
}
}
if(fromPHPobj["n"]===0){
document.getElementById("aModel1").selectedIndex=-1;
document.getElementById("aCount1").value='';
}else{
var k=1;
for(var i in fromPHPobj["models"]){
document.getElementById("m_id"+k).value=fromPHPobj["models"][i]["m_id"];
for(var j=0;j<document.getElementById("aModel"+k).options.length;j++){
//alert(fromPHPobj["models"][i]["model"]+"==="+document.getElementById("aModel"+k).options[j].text);
if(fromPHPobj["models"][i]["model"]===document.getElementById("aModel"+k).options[j].text){
document.getElementById("aModel"+k).selectedIndex=j;
//alert("selectedIndex="+document.getElementById("aModel"+k).selectedIndex);
}
}
document.getElementById("aCount"+k).value=fromPHPobj["models"][i]["count"];
k++;
}
}
}
}catch(e){
alert("Что то не то с ответом selectOrder "+e);
}
}
};
//alert("data="+data);
data={};
data.check=document.getElementById("check").checked;
data.a_id=a_id;
xmlhttp.open("POST","scr_orders.php?timeStamp="+new Date().getTime()+"&f=2",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("data="+JSON.stringify(data));
}
///////////////////////////////////////////////////
//Нажатие на кнопку ДОбавить
function aAddClick(){
//hiddenInsert()
var xmlhttp=ajaxConnect();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState===4 && xmlhttp.status===200)
{
var fromPHPs=xmlhttp.responseText;
//alert("aAddClick.fromPHPs="+fromPHPs);
//var fromPHPobj=!(/[^,:{}[]0-9.-+Eaeflnr-u nrt]/.test(fromPHPs.replace(/"(.|[^"])*"/g, ''))) && eval("(" + fromPHPs + ")");
//alert("fromPHPs="+fromPHPs);
//alert(fromPHPobj.text+" : "+fromPHPobj.aList);
//document.getElementById("note").innerHTML='<div id="note">'+fromPHPobj.text+'</div>';
//document.getElementById("aList").innerHTML=fromPHPobj.aList;
//updateHide();
countInputs(1);
document.getElementById("aModel1").selectedIndex=-1;
document.getElementById("aCount1").value="";
document.getElementById("aOrder").value="";
loadOrders();
}
};
var data=new Object();
data.aWeek=document.getElementById("selWeek").value;
data.month=document.getElementById("selMonth").value;
data.aYear=document.getElementById("selYear").value;
data.aOrder=document.getElementById("aOrder").value;//название ордера
var n=document.getElementById("countInputs").value;
var model=[];
var count=[];
for(var i=1;i<=n;i++){
if(document.getElementById("aModel"+i).value !== undefined){
model[i-1]=document.getElementById("aModel"+i).value;
count[i-1]=document.getElementById("aCount"+i).value;
//alert("array.model="+model[i-1]+"<br>array.count="+count[i-1]);
}
}
if(data.aOrder===""){
alert("Вы не заполнили поле \"Ордер\"");
}else{
xmlhttp.open("POST","scr_orders.php?timeStamp="+new Date().getTime()+"&f=3",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("order="+JSON.stringify(data)+"&model="+JSON.stringify(model)+"&count="+JSON.stringify(count));
//alert("order="+JSON.stringify(data)+"&model="+JSON.stringify(model)+"&count="+JSON.stringify(count) );
}
}
///////////////////////////////////////////////////
//Нажатие на кнопку Дубль
function aDublClick(){
//hiddenInsert()
var xmlhttp=ajaxConnect();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState===4 && xmlhttp.status===200)
{
var fromPHPs=xmlhttp.responseText;
//alert("aDublClick.fromPHPs="+fromPHPs);
var fromPHPobj=!(/[^,:{}[]0-9.-+Eaeflnr-u nrt]/.test(fromPHPs.replace(/"(.|[^"])*"/g, ''))) && eval("(" + fromPHPs + ")");
if(fromPHPobj['status']){
document.getElementById("note").innerHTML='<div id="note">Дубль ордера добавлен</div>';
aCanselClick();
}else
alert("aDublClick: ");
}
};
var data=new Object();
data.a_id=document.getElementById("valueSelectOrderId").value;
data.week=document.getElementById("UselWeek").value;
data.month=document.getElementById("UselMonth").value;
data.year=document.getElementById("UselYear").value;
if(data.a_id===""){
alert("Вы не выбрали ордер?");
}else{
xmlhttp.open("POST","scr_orders.php?timeStamp="+new Date().getTime()+"&f=8",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("data="+JSON.stringify(data));
//alert("order="+JSON.stringify(data));
}
}
function aCanselClick(){
updateHide();
document.getElementById("valueSelectOrderId").value='';
document.getElementById("aOrder").value='';
for(var i=1;i<=document.getElementById("countInputs").value;i++){
document.getElementById("aModel"+i).value='';
document.getElementById("aCount"+i).value='';
}
showPlusMinus();
countInputs(1);
}
////////////////////////////////////////////////////////
function updateHide(){
selWeek=0;
selMonth=0;
selYear=0;
document.getElementById("weekMonthYear").style.display="block";
document.getElementById("UweekMonthYear").style.display="none";
document.getElementById("txtUpdateDate").style.display="none";
document.getElementById("abtnDubl").style.display="none";
document.getElementById("abtnAdd").style.display="block";
}
//Нажатие на кнопку Вставить
function aUpdateClick(){
//hiddenInsert()
var xmlhttp=ajaxConnect();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState===4 && xmlhttp.status===200)
{
var fromPHPs=xmlhttp.responseText;
//alert("aUpdateClick.fromPHPs="+fromPHPs);
var fromPHPobj=!(/[^,:{}[]0-9.-+Eaeflnr-u nrt]/.test(fromPHPs.replace(/"(.|[^"])*"/g, ''))) && eval("(" + fromPHPs + ")");
if (fromPHPobj["status"]===1)document.getElementById("note").innerHTML="Данные изменены!";
if (fromPHPobj["status"]===0)document.getElementById("note").innerHTML="Данные изменить не удалось!";
//document.getElementById("aList").innerHTML=fromPHPobj.aList;
updateHide();
loadOrders();
showPlusMinus();
countInputs(1);
document.getElementById("aModel1").selectedIndex=-1;
document.getElementById("aCount1").value="";
document.getElementById("aOrder").value="";
}
};
var data ={};
data.a_id=document.getElementById("valueSelectOrderId").value;
data.week=document.getElementById("UselWeek").value;
data.month=document.getElementById("UselMonth").value;
data.year=document.getElementById("UselYear").value;
data.order=document.getElementById("aOrder").value;
data.m_id=[];
data.model=[];
data.count_=[];
var n=document.getElementById("countInputs").value;
for(var i=1;i<=n;i++){
if(document.getElementById("aModel"+i).value !== undefined){
data.m_id[i-1]=document.getElementById("m_id"+i).value;
data.model[i-1]=document.getElementById("aModel"+i).value;
data.count_[i-1]=document.getElementById("aCount"+i).value;
//alert("array.model="+model[i-1]);
}
}
if(data.a_id===""){alert("Вы не выбрали строку для изменения!");}
else{
xmlhttp.open("POST","scr_orders.php?timeStamp="+new Date().getTime()+"&f=4",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("data="+JSON.stringify(data));
//alert("data="+JSON.stringify(data));
}
}
///////////////////////////////////////////////////
//Нажатие на кнопку Удалить
function aDeleteClick(){
var xmlhttp=ajaxConnect();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState===4 && xmlhttp.status===200)
{
var fromPHPs=xmlhttp.responseText;
//alert("aDeleteClick.fromPHPs="+fromPHPs);
try{
var fromPHPobj=!(/[^,:{}[]0-9.-+Eaeflnr-u nrt]/.test(fromPHPs.replace(/"(.|[^"])*"/g, ''))) && eval("(" + fromPHPs + ")");
updateHide();
loadOrders();
showPlusMinus();
if(fromPHPobj["status"])
document.getElementById("note").innerHTML='<span>Ордер удален!</span>';
else
document.getElementById("note").innerHTML='<span>Ордер удалить не удалось!</span>';
}catch(e){
alert("DeleteClick "+e);
}
}
};
var data=new Object();
data.a_id=document.getElementById("valueSelectOrderId").value;
if(document.getElementById("UselWeek").value===selWeek && document.getElementById("UselMonth").value===selMonth && document.getElementById("UselYear").value===selYear){
if(data.a_id===""){
alert("Вы не выбрали строку для удаления!");
}else {xmlhttp.open("POST","scr_orders.php?timeStamp="+new Date().getTime()+"&f=5",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("data="+JSON.stringify(data));
}
}else{
aDeleteDublClick();
} //alert("Посылаем запрос в "+new Date());
}
//Нажатие на кнопку Удалить Dubl
function aDeleteDublClick(){
var xmlhttp=ajaxConnect();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState===4 && xmlhttp.status===200)
{
var fromPHPs=xmlhttp.responseText;
// alert("aDeleteClick.fromPHPs="+fromPHPs);
try{
var fromPHPobj=!(/[^,:{}[]0-9.-+Eaeflnr-u nrt]/.test(fromPHPs.replace(/"(.|[^"])*"/g, ''))) && eval("(" + fromPHPs + ")");
if(fromPHPobj["login"]){
updateHide();
loadOrders();
showPlusMinus();
if(fromPHPobj["status"])
document.getElementById("note").innerHTML='<span>Дубль ордера удален!</span>';
else
document.getElementById("note").innerHTML='<span>Дубль ордера удалить не удалось!</span>';
}else{
logout();
}
}catch(e){
alert("DeleteDublClick "+e);
}
}
};
var data=new Object();
data.a_id=document.getElementById("valueSelectOrderId").value;
data.week=selWeek;
data.month=selMonth;
data.year=selYear;
if(data.a_id===""){
alert("Вы не выбрали ордер?");
}else{
xmlhttp.open("POST","scr_orders.php?timeStamp="+new Date().getTime()+"&f=12",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("data="+JSON.stringify(data));
}
//alert("Посылаем запрос в "+new Date());
}
///////////////////////////////////////////////
//////////////////////////////////////////////
// очистка полей ордера, моделей и количества
function clearInput(){
document.getElementById("aOrder").value="";
for(var i=0;i<5;i++){
document.getElementById("aModel[i]").value='';
document.getElementById("aCount[i]").value='';
}
}
|
const multer = require('multer');
const path = require('path');
const fs = require("fs")
, aws = require('aws-sdk');
var makeDirectory = function(dirPath, mode, callback) {
//Call the standard fs.mkdir
fs.mkdir(dirPath, mode, function(error) {
//When it fail in this way, do the custom steps
if (error && error.errno === 34) {
//Create all the parents recursively
fs.mkdirParent(path.dirname(dirPath), mode, callback);
//And then the directory
fs.mkdirParent(dirPath, mode, callback);
}
//Manually run the callback since we used our own callback to do all these
callback && callback(error);
});
};
var upload = function(filename,destination,req,type = "image") {
const upload_system = req.appSettings.upload_system
var storageEngine;
if(upload_system == "s3" && !req.uploadDirect){
aws.config.update({
secretAccessKey: req.appSettings.s3_secret_access_key,
accessKeyId: req.appSettings.s3_access_key,
region: req.appSettings.s3_region
});
const s3 = new aws.S3()
const storageObject = {
Key: (req, file, cb) => {
let originalS3ImageName = Date.now() + '_' + file.originalname.replace(/(?:\.(?![^.]+$)|[^\w.])+/g, "-");
req.originalS3ImageName = originalS3ImageName
if(file.fieldname){
if(!req.fieldImageName)
req.fieldImageName = {}
req.fieldImageName[file.fieldname] = originalS3ImageName
}
cb(null, destination+originalS3ImageName)
},
s3,
Bucket: req.appSettings.s3_bucket,
multiple: req.imageResize && req.imageResize.length > 1 ? true : false,
}
if(req.imageResize && !req.fromadmin)
storageObject['resize'] = req.imageResize;
let s3Storage = require('multer-sharp-s3')
storageEngine = s3Storage(storageObject)
}else if(upload_system == "wisabi" && !req.uploadDirect){
const accessKeyId = req.appSettings.s3_access_key;
const secretAccessKey = req.appSettings.s3_secret_access_key;
const wasabiEndpoint = new aws.Endpoint(`s3.${req.appSettings.s3_region}.wasabisys.com`);
let wisabiStorage = {
endpoint: wasabiEndpoint,
region: req.appSettings.s3_region,
accessKeyId,
secretAccessKey
};
const s3 = new aws.S3(wisabiStorage)
const storageObject = {
Key: (req, file, cb) => {
let originalS3ImageName = Date.now() + '_' + file.originalname.replace(/(?:\.(?![^.]+$)|[^\w.])+/g, "-");
req.originalS3ImageName = originalS3ImageName
if(file.fieldname){
if(!req.fieldImageName)
req.fieldImageName = {}
req.fieldImageName[file.fieldname] = originalS3ImageName
}
cb(null, destination+originalS3ImageName)
},
s3,
Bucket: req.appSettings.s3_bucket,
multiple: req.imageResize && req.imageResize.length > 1 ? true : false,
}
if(req.imageResize && !req.fromadmin)
storageObject['resize'] = req.imageResize;
let s3Storage = require('multer-sharp-s3')
storageEngine = s3Storage(storageObject)
}else{
if(!fs.existsSync('./server/public/'+destination)){
makeDirectory('./server/public/'+destination,'0777');
}
storageEngine = multer.diskStorage({
destination: './server/public/'+destination,
filename: function (req, file, cb) {
return cb(null, Date.now() + '_' + file.originalname.replace(/(?:\.(?![^.]+$)|[^\w.])+/g, "-"))
}
})
}
let size = 50
if(type == "fromadmin"){
size = 1000000
}else if(type == "image"){
size = parseInt(req.appSettings['image_upload_limit']) == 0 ? 100000 : parseInt(req.appSettings['image_upload_limit'])
}else if(type == "video"){
size = parseInt(req.appSettings['video_upload_limit']) == 0 ? 100000 : parseInt(req.appSettings['video_upload_limit'])
}else if(type == "audio"){
size = 100
}else{
size = parseInt(req.appSettings['advertisement_upload_limit']) == 0 ? 100000 : parseInt(req.appSettings['advertisement_upload_limit'])
}
//init
const multerObj = multer({
storage: storageEngine,
limits: { fileSize: size * 1024 * 1024 },//30mb
fileFilter: function (req, file, callback) {
validateFile(file, callback,req);
}
})
if(filename){
return multerObj.single(filename)
}else{
return multerObj.fields(req.uploadFields)
}
}
//file validation
var validateFile = function (file, cb,req) {
let allowedFileTypes = ""
if(req.allowedFileTypes){
allowedFileTypes = req.allowedFileTypes
}else{
allowedFileTypes = /jpeg|jpg|png|gif/
}
if(req.fromadmin){
return cb(null, true)
}
const extension = allowedFileTypes.test(path.extname(file.originalname).toLowerCase())
//const mimeType = allowedFileTypes.test(file.mimetype)
if(extension) {
return cb(null, true)
}else{
cb("Invalid file type. Only JPEG, PNG and GIF file are allowed.", false)
}
}
function bytesToSize(bytes) {
var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
if (bytes == 0) return '0 Byte';
var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
return `${Math.round(bytes / Math.pow(1024, i), 2)}${sizes[i]}`;
};
var uploadtoS3 = async (req,uploadFile,uploadPath) => {
return new Promise(async (resolve, reject) => {
let wisabiStorage = {}
if(req.appSettings.upload_system == "s3"){
aws.config.update({
secretAccessKey: req.appSettings.s3_secret_access_key,
accessKeyId: req.appSettings.s3_access_key,
region: req.appSettings.s3_region
});
}else{
const accessKeyId = req.appSettings.s3_access_key;
const secretAccessKey = req.appSettings.s3_secret_access_key;
const wasabiEndpoint = new aws.Endpoint(`s3.${req.appSettings.s3_region}.wasabisys.com`);
wisabiStorage = {
endpoint: wasabiEndpoint,
region: req.appSettings.s3_region,
accessKeyId,
secretAccessKey
};
}
var s3 = new aws.S3(wisabiStorage);
fs.readFile(uploadFile,async function read(err, data) {
let uploadMainPath = uploadPath
if (uploadPath.charAt(0) == "/") uploadMainPath = uploadPath.substr(1);
if (err) { resolve(false) }
const mimeType = require("./mimeTypes")
const type = await mimeType.ext.getExt(uploadMainPath);
const ContentType = await mimeType.ext.getContentType(type);
let params = {Bucket: req.appSettings.s3_bucket, Key: uploadMainPath, Body: data,ContentType:ContentType };
s3.putObject(params, function(err, _data) {
if (err) {
resolve(false)
} else {
resolve(true)
}
});
})
});
}
var readS3Image = async (req,image,newimage) => {
return new Promise(async function (resolve,reject) {
let wisabiStorage = {}
if(req.appSettings.upload_system == "s3"){
aws.config.update({
secretAccessKey: req.appSettings.s3_secret_access_key,
accessKeyId: req.appSettings.s3_access_key,
region: req.appSettings.s3_region
});
}else{
const accessKeyId = req.appSettings.s3_access_key;
const secretAccessKey = req.appSettings.s3_secret_access_key;
const wasabiEndpoint = new aws.Endpoint(`s3.${req.appSettings.s3_region}.wasabisys.com`);
wisabiStorage = {
endpoint: wasabiEndpoint,
region: req.appSettings.s3_region,
accessKeyId,
secretAccessKey
};
}
let trimImage = image
if (image.charAt(0) == "/") trimImage = image.substr(1);
var s3 = new aws.S3(wisabiStorage);
s3.getObject(
{ Bucket: req.appSettings.s3_bucket, Key: trimImage },
function(err, data) {
if (!err) {
const fs = require("fs")
fs.writeFile(newimage, data.Body, function(err){
if(err)
reject(false)
else
return resolve(newimage)
});
}else{
reject(false)
}
}
);
});
}
module.exports = { upload, bytesToSize, uploadtoS3,readS3Image };
|
const Input = {
UP : Symbol('UP'),
DOWN : Symbol('DOWN'),
LEFT : Symbol('LEFT'),
RIGHT : Symbol('RIGHT'),
ATTACK : Symbol('ATTACK'),
NONE : Symbol('NONE')
};
class KeyboardInput {
constructor() {
this.leftKey = new Key(KeyCode.LEFT).listen();
this.rightKey = new Key(KeyCode.RIGHT).listen();
this.upKey = new Key(KeyCode.UP).listen();
this.downKey = new Key(KeyCode.DOWN).listen();
this.attKey = new Key(KeyCode.SPACE).listen();
}
getInput() {
let down = 0;
let action = Input.NONE;
if (this.leftKey.isDown) {
down++;
action = Input.LEFT;
}
if (this.rightKey.isDown) {
down++;
action = Input.RIGHT;
}
if (this.upKey.isDown) {
down++;
action = Input.UP;
}
if (this.downKey.isDown) {
down++;
action = Input.DOWN;
}
if (down > 1) {
// too many inputs
action = Input.NONE;
}
if (this.attKey.isDown) {
// attack action overrides, because I say so
return Input.ATTACK;
} else {
return action;
}
}
}
class TwitchChatInput {
constructor() {
// TODO: connect to twitch chat, and start recording
}
getInput() {
// TODO: return an input command
}
}
|
import rp from 'request-promise'
import _ from 'lodash'
import { GOUV_API_URL, GOUV_ENDPOINT } from '../../constants'
export default (text) => {
return new Promise((resolve, reject) => {
const CP = text.match(/\b\d{5}\b/g);
let param = '';
if (CP && !_.isEmpty(CP)) {
param = `codePostal=${_.first(CP)}`;
} else {
param = `nom=${text}`;
}
const options = {
uri: `${GOUV_API_URL}${GOUV_ENDPOINT}${param}`
};
rp(options)
.then(res => {
if (!res) {
return resolve();
}
const cities = JSON.parse(res);
if (!_.isEmpty(cities) && cities.length > 1) {
const city = _.find(cities, o => text.toLowerCase() === o.nom.toLowerCase());
if (city) {
return resolve([city]);
}
}
return resolve(cities);
})
.catch(err => {
console.log(err);
return err;
});
})
}
|
(function(){
'use strict';
var app = angular.module('eissonApp', [
'ngRoute',
'ngAnimate',
'angular-loading-bar',
'ui.materialize',
'angularMoment',
'ui.validate',
'Controllers']);
app.config(['$routeProvider', 'cfpLoadingBarProvider',function($routeProvider, cfpLoadingBarProvider){
cfpLoadingBarProvider.includeSpinner = true;
cfpLoadingBarProvider.latencyThreshold = 1;
$routeProvider.
/* when('/', {
templateUrl: 'views/consultar.html',
caseInsensitiveMatch: true,
controller: 'ConsultarController',
activetab: 'consultar'
}).*/
when('/vacunar-nino', {
templateUrl: 'views/vacunar-nino.html',
caseInsensitiveMatch: true,
controller: 'VacunarNinoController',
activetab: 'vacunar'
}).
when('/nueva_contrasena', {
templateUrl: 'views/nueva_contrasena.html',
caseInsensitiveMatch: true,
controller: 'nueva_contrasenaController'
}).
when('/adicional/:id', {
templateUrl: 'views/info-adicional.html',
caseInsensitiveMatch: true,
controller: 'InfoAdicionalController',
activetab: 'vacunar'
}).
otherwise({
redirectTo: '/vacunar-nino'
});
}]);
})();
|
import {createStore} from "redux";
import {imageProcessorReducer} from "./reducer";
export const store = createStore(imageProcessorReducer);
|
import React, { Component } from 'react';
import { View, Text, StyleSheet, TouchableOpacity, TouchableWithoutFeedback, Keyboard, Button, Alert, ScrollView} from 'react-native';
import { CreditCardInput } from 'react-native-credit-card-input';
import GradientButton from 'react-native-gradient-buttons';
import Colors from '../constants/Colors';
import { MaterialCommunityIcons, Octicons, MaterialIcons } from '@expo/vector-icons';
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view';
class CreditCardScreen extends Component {
constructor(props) {
super(props);
this.state = {
};
this.setCardInputValues = this.setCardInputValues.bind(this);
this.addedAlert = this.addedAlert.bind(this);
}
componentDidMount() {
this.setCardInputValues();
this.props.navigation.setOptions({
title: 'Card Details',
headerRight: () => (
<Octicons
name="check"
size={35}
color={Colors.green03}
style={{marginRight: 10}}
onPress={(this.addedAlert)}
/>
),
headerLeft: () => (
<MaterialIcons
name={'keyboard-arrow-left'}
size={45}
color={Colors.blue}
onPress={() => this.props.navigation.navigate('Menu')}
/>
),
});
}
addedAlert() {
Alert.alert(
'Congrats!',
'Card added successfuly',
[
{
text: 'OK',
onPress: () => this.props.navigation.navigate('Menu')
}
]
)
}
setCardInputValues(){
const { card_number, full_name, card_type, valid_date } = this.props.route.params.cardDetails;
const values = {
number: card_number,
expiry: valid_date,
cvc: "CVC",
type: card_type,
name: full_name,
};
// const values = {
// number: "2222 2222 2222 2222",
// expiry: "06/19",
// cvc: "222",
// type: "visa",
// name: "Miki",
// };
console.log("values = " + JSON.stringify(values));
this.cardInput.setValues(values);
}
_onChange = (formData) => console.log(JSON.stringify(formData, null, " "));
_onFocus = (field) => console.log("focusing", field);
render() {
return (
<KeyboardAwareScrollView extraHeight={100} style={{backgroundColor: 'white'}}>
<View style={{flex: 1, paddingTop: 50, backgroundColor: 'white'}}>
<CreditCardInput
autoFocus={false}
requiresName
requiresCVC
labelStyle={s.label}
inputStyle={s.input}
validColor={"black"}
invalidColor={"red"}
placeholderColor={"darkgray"}
allowScroll={true}
ref={cardInput => this.cardInput = cardInput}
labelStyle={{fontSize: 12, fontWeight: '600', color: Colors.gray03}}
inputStyle={{fontSize: 16, fontWeight: '700', color: Colors.black}}
placeholderColor={Colors.gray02}
/>
</View>
</KeyboardAwareScrollView>
);
}
}
export default CreditCardScreen;
const s = StyleSheet.create({
switch: {
alignSelf: "center",
marginTop: 20,
marginBottom: 20,
},
container: {
backgroundColor: "#F5F5F5",
marginTop: 60,
},
label: {
color: "black",
fontSize: 12,
},
input: {
fontSize: 16,
color: "black",
},
});
|
queue()
.defer(d3.json, "/premierleague/team/LIVERPOOL")
.await(makeGraphs);
function makeGraphs(error, premierleagueData) {
if (error) {
console.error("makeGraphs error on receiving dataset:", error.statusText);
throw error;
}
var ndx = crossfilter(premierleagueData);
var yearDim = ndx.dimension(function (d) {
return new Date(d["year"], 0, 1);
});
var positionDimLiverpool = ndx.dimension(function (d) {
if (d["team"] == "LIVERPOOL") {
return d["position"];
} else {
return false;
}
});
var positionGroupLiverpool = positionDimLiverpool.group().reduceCount();
var yAxis = d3.svg.axis()
.scale(d3.scale.linear())
.orient("left")
.ticks(20);
//DATE VALUES USED IN CHARTS
var minYear = new Date(yearDim.bottom(1)[0]["year"], 0,1);
var maxYear = new Date(yearDim.top(1)[0]["year"], 0,1);
var minYearBoundary = new Date(yearDim.bottom(1)[0]["year"]-1, 0,1);
var maxYearBoundary = new Date(yearDim.top(1)[0]["year"]+1, 0,1);
// GROUPS
var liverpoolPointsByYear = createGroup(yearDim, "LIVERPOOL", "points");
var liverpoolGoalsByYear = createGroup(yearDim, "LIVERPOOL", "goals_for");
var liverpoolGoalsConcByYear = createGroup(yearDim, "LIVERPOOL", "goals_against");
var liverpoolGoalDifference = createGroup(yearDim, "LIVERPOOL", "goal_difference");
var liverpoolWins = createGroup(yearDim, "LIVERPOOL", "won");
var liverpoolDrawn = createGroup(yearDim, "LIVERPOOL", "drawn");
var liverpoolLosses = createGroup(yearDim, "LIVERPOOL", "lost");
// CHARTS
var positionSelectorLiverpool = dc.pieChart("#positionSelectorLiverpool");
var yearSelectorLiverpool = dc.barChart("#yearSelectorLiverpool");
var goalsChartLiverpool = dc.barChart("#goalsChartLiverpool");
var goalsConcChartLiverpool = dc.barChart("#goalsConcChartLiverpool");
var goalDifferenceChartLiverpool = dc.barChart("#goalDifferenceChartLiverpool");
var formGuideLiverpool = dc.lineChart("#formGuideLiverpool");
// CHART PROPERTIES
positionSelectorLiverpool
.dimension(positionDimLiverpool)
.group(positionGroupLiverpool)
.width(250)
.height(250)
.legend(dc.legend().x(10)
.y(235)
.itemHeight(15)
.gap(0)
.horizontal(true)
.itemWidth(30))
.minAngleForLabel(2)
.title(function(d) {
return 'Position ' + d.key + ': ' + d.value;
})
.radius(90)
.innerRadius(40);
yearSelectorLiverpool
.dimension(yearDim)
.group(liverpoolPointsByYear)
.width($(this).parent().width())
.height(250)
.margins({top: 50, right: 35, bottom: 50, left: 35})
.xUnits(function(){return 19;}) // SET BAR WIDTH
.centerBar(true)
.barPadding(0.25) // SET PADDING BETWEEN BARS
.xAxisLabel("Year")
.yAxisLabel("Points")
.x(d3.time.scale().domain([minYearBoundary, maxYearBoundary]))
.y(d3.scale.linear().domain([45, 90]));
formGuideLiverpool
.dimension(yearDim)
.width($(this).parent().width())
.height(300)
.margins({top: 50, right: 60, bottom: 50, left: 35})
.group(liverpoolWins, "Wins")
.stack(liverpoolDrawn, "Draws")
.stack(liverpoolLosses, "Losses")
.brushOn(false)
.renderArea(true)
.rangeChart(yearSelectorLiverpool)
.x(d3.time.scale().domain([minYear, maxYearBoundary]))
.y(d3.scale.linear().domain([0, 40]))
.legend(dc.legend().x($('#formGuideLiverpool').width()-65)
.y(58)
.itemHeight(13)
.gap(5))
.title(function(d) {
return d.key.getFullYear() + ': ' + d.value;
})
.xAxisLabel("Year")
.yAxisLabel("Total");
goalsChartLiverpool
.dimension(yearDim)
.group(liverpoolGoalsByYear)
.width($(this).parent().width())
.height(250)
.margins({top: 25, right: 35, bottom: 50, left: 35})
.brushOn(false)
.xUnits(function(){return 19;}) // SET BAR WIDTH
.centerBar(true)
.barPadding(0.25) // SET PADDING BETWEEN BARS
.rangeChart(formGuideLiverpool)
.x(d3.time.scale().domain([minYearBoundary, maxYearBoundary]))
.y(d3.scale.linear().domain([40, 110]))
.title(function(d) {
return d.key.getFullYear() + ': ' + d.value;
})
.yAxisLabel("Scored")
.xAxisLabel("Year");
goalsConcChartLiverpool
.dimension(yearDim)
.group(liverpoolGoalsConcByYear)
.width($(this).parent().width())
.height(250)
.margins({top: 25, right: 35, bottom: 50, left: 35})
.brushOn(false)
.xUnits(function(){return 19;}) // SET BAR WIDTH
.centerBar(true)
.barPadding(0.25) // SET PADDING BETWEEN BARS
.rangeChart(goalsChartLiverpool)
.x(d3.time.scale().domain([minYearBoundary, maxYearBoundary]))
.y(d3.scale.linear().domain([20, 55]))
.title(function(d) {
return d.key.getFullYear() + ': ' + d.value;
})
.yAxisLabel("Conceded")
.xAxisLabel("Year");
goalDifferenceChartLiverpool
.dimension(yearDim)
.group(liverpoolGoalDifference)
.width($(this).parent().width())
.height(250)
.margins({top: 25, right: 35, bottom: 50, left: 35})
.brushOn(false)
.xUnits(function(){return 19;}) // SET BAR WIDTH
.centerBar(true)
.barPadding(0.25) // SET PADDING BETWEEN BARS
.rangeChart(goalsConcChartLiverpool)
.x(d3.time.scale().domain([minYearBoundary, maxYearBoundary]))
.y(d3.scale.linear().domain([0, 55]))
.title(function(d) {
return d.key.getFullYear() + ': ' + d.value;
})
.yAxisLabel("Goal Difference")
.xAxisLabel("Year");
dc.renderAll();
$(window).resize(function() {
yearSelectorLiverpool
.width($(this).parent().width());
formGuideLiverpool
.legend(dc.legend().x($('#formGuideLiverpool').width()-65)
.y(58)
.itemHeight(13)
.gap(5));
dc.renderAll();
});
}
|
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const express_1 = require("express");
const config_1 = require("../config/config");
const bcrypt_1 = __importDefault(require("bcrypt"));
const jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
// Models
const usuarioModel_1 = require("../models/usuarioModel");
const maestrosModel_1 = require("../models/maestrosModel");
const loginRouter = express_1.Router();
// =================================================================
//-- Login con el metodo normal
// =================================================================
loginRouter.post('/', (req, resp) => {
var body = req.body;
usuarioModel_1.usuarioModel.findOne({ correo: body.correo }, (error, usuarioDB) => {
if (error) {
return resp.status(400).json({
ok: false,
mensaje: 'Error al logearse'
});
}
if (!usuarioDB) {
return resp.status(400).json({
ok: false,
message: `No contamos con un usuario registrado con el correo: ${body.correo}`,
});
}
if (!bcrypt_1.default.compareSync(body.password, usuarioDB.password)) {
return resp.status(400).json({
ok: false,
mensaje: 'Credenciales incorrectas',
errors: error
});
}
// Crear un token
usuarioDB.password = 'encryptpassword';
var token = jsonwebtoken_1.default.sign({ usuario: usuarioDB }, config_1.SEED, { expiresIn: 36000 });
resp.status(200).json({
ok: true,
token: token,
usuario: usuarioDB,
});
});
});
loginRouter.post('/maestros', (req, resp) => {
var body = req.body;
maestrosModel_1.maestroModel.findOne({ correo: body.correo }, (error, maestroDB) => {
if (error) {
return resp.status(400).json({
ok: false,
mensaje: 'Error al logearse'
});
}
if (!maestroDB) {
return resp.status(400).json({
ok: false,
message: `No contamos con un maestro registrado con el correo: ${body.correo}`,
});
}
if (!bcrypt_1.default.compareSync(body.password, maestroDB.password)) {
return resp.status(400).json({
ok: false,
mensaje: 'Credenciales incorrectas',
errors: error
});
}
// Crear un token
maestroDB.password = 'encryptpassword';
var token = jsonwebtoken_1.default.sign({ usuario: maestroDB }, config_1.SEED, { expiresIn: 36000 });
resp.status(200).json({
ok: true,
token: token,
maestro: maestroDB,
});
});
});
exports.default = loginRouter;
|
import React from "react";
import { Link } from "react-router-dom";
function Header({ authUser, location, signOut }) {
return (
<header>
<div className="container container--header">
<div className="brand">
<nav>
<Link to="/">
<strong>PlainChat</strong>
</Link>
</nav>
</div>
{!authUser &&
(location.pathname === "/" || location.pathname === "/signup") && (
<div className="navbar">
<nav>
<Link to="/signin">Sign in</Link>
</nav>
</div>
)}
{!authUser && location.pathname === "/signin" && (
<div className="navbar">
<nav>
<Link to="/signup">Sign up</Link>
</nav>
</div>
)}
{authUser && (
<div className="navbar">
<nav>
Welcome{" "}
<Link to="/settings">
{authUser.fullName && authUser.fullName.indexOf("undefined") < 0
? authUser.fullName
: authUser.username || authUser.email}
</Link>
</nav>
<nav onClick={signOut}>Sign out</nav>
</div>
)}
</div>
</header>
);
}
export default Header;
|
var SnapCount = 0;
function Increment(id){
Image = document.getElementById("Button");
Image.src = "../Images/ButtonB.png";
setTimeout("Reset()",100);
console.log(id);
SnapCount = SnapCount + 1;
console.log(SnapCount);
Num = document.getElementById("SnapNum");
Num.innerHTML = SnapCount;
}
function Reset(){
Image = document.getElementById("Button");
Image.src = "../Images/ButtonA.png";
}
|
import React, { Component } from 'react';
import Row from './MerchantDealRow';
export class Main extends Component {
render() {
let merchantDeals = this.props.deals;
const datamerchantDeals = merchantDeals.map( deal => <Row deleteDeal={this.props.deleteDeal} updateDeal={this.props.updateDeal} key={deal.id} deal={deal} /> );
return (
<main className="main-page" style={{margin: "auto", width: "85%"}}>
<a className="waves-effect waves-light btn" href="/newdeal">Create New Deal</a>
<h3 style={{textAlign:'center',transform:'translateY(-40px)'}}>Your Deals</h3>
<table>
<thead>
<tr>
<th>Image</th>
<th>Product</th>
<th>Quantity </th>
<th>Price</th>
<th>Expiry Date</th>
<th></th>
<th></th>
</tr>
</thead>
{datamerchantDeals}
</table>
</main>
);
}
}
export default Main;
|
$(function(){
'use strict';
var isMobile = false;
var backgroundImg = 'img/laptop-cover-bw.jpg';
var image = new Image();
var $grid = $('.grid');
var $header = $('.header');
var $year = $('.js-year');
$year.html( new Date().getFullYear() );
skrole
.scroll(function( direction ){
var top = parseInt( $header.css( 'top' ) );
if ( direction === 'down' && top === 0 ) {
$header.css( 'top', '-50px' );
} else if ( direction === 'up' && top === -50 ) {
$header.css( 'top', 0 );
}
})
.onScrollTimeout(2000, function(){
var headerPos = parseInt( $header.css( 'top' ) );
if ( headerPos === 0 ) {
$header.css( 'top', '-50px' );
}
});
image.onload = function() {
$('.loading').hide();
$('.cover')
.css( 'background', 'url(' + image.src + ') no-repeat center center' );
$('.fade-in').css( 'opacity', 1 );
};
image.src = backgroundImg;
$grid.imagesLoaded( function(){
$grid.masonry({
itemSelector : '.grid__item',
isFitWidth: true
});
});
$('.writings__row').click(function(){
var location = $(this).data( 'post' );
window.open( location );
});
var adjustCover = function() {
var wHeight = $(window).height();
var height = Math.floor( wHeight * 0.95 );
};
adjustCover();
$(window).resize( adjustCover );
$('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//,'') === this.pathname.replace(/^\//,'') && location.hostname === this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top
}, 1000);
return false;
}
}
});
var adaptOpts = {
selector: '[data-adaptive-background="1"]',
parent: '#swagg-player',
exclude: [ 'rgb(0,0,0)', 'rgba(255,255,255)' ],
normalizeTextColor: false,
normalizedTextColors: {
light: '#fff',
dark: '#000'
},
lumaClasses: {
light: 'ab-light',
dark: 'ab-dark'
}
};
var player = SwaggPlayer().init({
url: '/swf',
el: document.querySelector( '#swagg-player' ),
songs: [
{
url: 'http://audio.johnnyray.me/clothing-style.mp3',
artist: 'Cornel West',
title: 'Style',
art: 'img/cornel-west.jpg'
}
],
onResume: function( songData ) {
playButton( 'pause' );
artOnScreen();
},
onPlay: function( songData ) {
changeMeta( songData );
playButton( 'pause' );
artOnScreen();
setTimeout(function(){
$.adaptiveBackground.run( adaptOpts );
}, 700);
},
onPause: function( songData ) {
playButton( 'play' );
artOffScreen();
},
onFinish: function() {
playButton( 'play' );
artOffScreen();
}
})
.onChange(function(item, changes) {
if ( changes.art.indexOf( 'mobile' ) > -1 ) {
$( '.swagg-player__art .img' )
.css('background-image', 'url(img/cornel-west-mobile.jpg)');
} else {
$( '.swagg-player__art .img' )
.css('background-image', 'url(img/cornel-west.jpg)');
}
})
.onReady(function(){
var track = this.cursor( 0 );
// update the UI
changeMeta( track );
$.adaptiveBackground.run( adaptOpts );
$('.img').on('ab-color-found', function(ev,payload){
});
});
enquire.register('(max-width: 37.5em)', {
match: function() {
player.setData( 0, 'art', 'img/cornel-west-mobile.jpg' );
isMobile = true;
},
unmatch: function(){
player.setData( 0, 'art', 'img/cornel-west.jpg' );
isMobile = false;
}
});
// ------------------------------- helpers
function playButton( type ) {
var el = document.querySelectorAll('.play-pause-toggle')[0];
el.className = 'icon-' + type + ' play-pause-toggle swagg-player-controls__button';
}
function changeMeta( data ) {
document.querySelectorAll('.song-info__artist')[ 0 ].innerHTML = data.artist;
document.querySelectorAll('.song-info__title')[ 0 ].innerHTML = data.title;
changeCover( data.art );
}
function changeCover( url ) {
document.querySelectorAll('.img')[ 0 ].style.backgroundImage = 'url(' + url +')';
document.querySelectorAll('.img')[ 0 ].style.backgroundSize = 'cover';
}
function artOnScreen() {
$('.img').css( 'left', 0 );
}
function artOffScreen() {
$('.img').css( 'left', '-110%' );
}
// ------------------------------- click events
document
.querySelectorAll( '.icon-play' )[ 0 ]
.addEventListener('click', function(e){
e.preventDefault();
player.play();
});
});
|
/**
* Authors: Diego Ceresuela, Luis Jesús Pellicer, Raúl Piracés.
* Date: 16-05-2016
* Name file: OAuth.js
* Description: Provides callback after Twitter authentication.
*/
(function () {
var OAuth = require('oauth').OAuth;
/**
* Init OAuth object with the twitter application consumer key and secret.
* It establishes a callback URL to receive Twitter response.
* @param callback is the callback object, containing the OAuth object initialized.
*/
function initTwitterOauth(callback) {
var oa = new OAuth(
"https://twitter.com/oauth/request_token"
, "https://twitter.com/oauth/access_token"
, process.env.TWITTER_CONSUMER_KEY
, process.env.TWITTER_CONSUMER_SECRET
, "1.0A"
, process.env.CURRENT_DOMAIN + "/auth/twitter/callback"
, "HMAC-SHA1"
);
callback(oa);
}
exports.initTwitterOauth = initTwitterOauth;
})();
|
// @flow
// a package.json file
export type Package = {
// core properties
name: string,
version: string,
// For some bizare reason flow thinks that dependencies is
// at some point merged with publishConfig, release, and repository
// so throws a hissy fit when you try to give dependencies
// a more concrete definition
dependencies: Object,
repository: {
url: string,
},
private: boolean,
// semantic-release properties
publishConfig?: {
access?: string,
repository: string,
tag: string,
},
release?: {
branch?: string,
githubToken?: string,
githubUrl?: string,
tag?: string,
registry?: string,
analyzeCommits: string | Object,
generateNotes: string | Object,
},
// mono-semantic properties
scope: string,
physicalLocation: string,
releaseType?: string,
changelog?: string,
};
// npm's internal configuration settings
export type NpmConfig = {
registry: string,
loglevel?: string,
tag?: string,
};
// npm configuration for the current package
export type Npm = {
registry: string,
loglevel: string,
tag: string,
};
// environment variables
export type Env = {
CI: ?string,
};
// options passed into the cli
export type UserConfig = {
pathToPackages: string,
registry: ?string,
loglevel: ?string,
branch: ?string,
debug: ?boolean,
githubToken: ?string,
githubUrl: ?string,
githubApiPathPrefix: ?string,
};
|
/**
* LINKURIOUS CONFIDENTIAL
* Copyright Linkurious SAS 2012 - 2018
*
* - Created on 2015-06-19.
*/
'use strict';
const _ = require('lodash');
/**
* Actions that can be set to a custom group.
*/
const PUBLIC_ACTIONS = [
{
key: 'admin.connect',
description: 'Connect the data-source and read the configuration'
},
{
key: 'admin.index',
description: 'Index the data-source and read the configuration'
},
{
key: 'admin.users',
description: 'Manage the users in the data-source'
},
{
key: 'admin.alerts',
description: 'Manage the alerts in the data-source'
},
{
key: 'admin.report',
description: 'Generate analytics report'
},
{
key: 'rawReadQuery',
description: 'Send cypher queries to the graph (read)'
},
{
key: 'rawWriteQuery',
description: 'Send cypher queries to the graph (write)'
}
];
/**
* Actions that can't be set to a custom group.
*/
const PRIVATE_ACTIONS = [
{
key: 'admin.app',
description: 'Manage applications'
},
{
key: 'admin.users.delete',
description: 'Delete users'
},
{
key: 'admin.config',
description: 'Set the configuration'
},
{
key: 'admin.resetDefaults',
description: 'Reset design and captions of all sandboxes of the given data-source'
}
];
const Actions = {};
/**
* All action keys for a custom group.
*
* @type {string[]}
*/
Actions.PUBLIC_ACTIONS = _.map(PUBLIC_ACTIONS, 'key');
const PUBLIC_MAP = _.keyBy(PUBLIC_ACTIONS, 'key');
const PRIVATE_MAP = _.keyBy(PRIVATE_ACTIONS, 'key');
/**
* Return true if this action key exists.
*
* @param {string} key The action key
* @returns {boolean}
*/
Actions.exists = function(key) { return !!PUBLIC_MAP[key] || !!PRIVATE_MAP[key]; };
module.exports = Actions;
|
import limitWordNumTextarea from './limit-word-num-textarea.vue'
export default limitWordNumTextarea
|
const hamburger = document.querySelector('.hamburger'),
menu = document.querySelector('.menu'),
closeElem = document.querySelector('.menu__close');
hamburger.addEventListener('click', () => {
menu.classList.add('active');
});
closeElem.addEventListener('click', () => {
menu.classList.remove('active')
});
const counters = document.querySelectorAll('.skills__percent'),
lines = document.querySelectorAll('.skills__progras');
counters.forEach((item, i) => {
lines[i].style.width = item.innerHTML;
});
//form
$('form').submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "mailer/smart.php",
data: $(this).serialize()
}).done(function() {
$(this).find("input").val("");
$('#consultation, #order').fadeOut();
$('.overlay, #thanks').fadeIn('fast');
$('form').trigger('reset');
});
return false;
});
// scroll up
$(window).scroll(function() {
if($(this).scrollTop()>1600) {
$('.pageup').fadeIn();
} else {
$('.pageup').fadeOut();
}
})
$("body").on('click', '[href*=#up]', function(e){
var fixed_offset = 100;
$('html,body').stop().animate({ scrollTop: $(this.hash).offset().top - fixed_offset }, 1000);
e.preventDefault();
});
|
const Style = {
color:'#666666',
fontFamily: 'Poppins',
fontSize: '1rem'
};
const BlogDate = props => (
<div>
<div style={Style}>
{props.children}
</div>
</div>
);
export default BlogDate;
|
//REQUIREMENTS
const User = require("../models/user");
//REGISTER FORM
module.exports.renderRegister = (req, res)=>{
res.render("users/register")
}
//REGISTER POST
module.exports.register = async(req,res)=>{
try{
const {email, username, password} = req.body;
const user = new User({email, username});
const registeredUser = await User.register(user, password);
req.login(registeredUser, err =>{ //NEEDED TO LOG YOU IN IMMEDIATELY AFTER REGISTERING
if(err){
return next(err);
}
req.flash("success", `Welcome to CampReview, ${user.username}!`);
res.redirect("/campgrounds")
});
} catch(e){
req.flash("error", e.message);
res.redirect("/register")
}
}
//LOGIN FORM
module.exports.renderLogin = async(req,res)=>{
res.render("users/login");
}
//LOGIN POST REQUEST
module.exports.loginUser = async(req,res)=>{
req.flash("success", "Welcome back!");
const redirectUrl = req.session.returnTo || "/campgrounds";
delete req.session.returnTo;
res.redirect(redirectUrl);
}
//LOGOUT PAGE
module.exports.logoutUser = (req,res)=>{
req.logout();
req.flash("success", "You've been logged out.")
res.redirect("/campgrounds")
}
|
import React, { useState } from "react";
import NewMessageForm from "./NewMessageForm";
import MessageList from "./MessageList";
function App() {
const [messages, updateMessage] = useState([]);
const sendHandler = message =>
updateMessage(messages => [...messages, message]);
return (
<div>
<NewMessageForm onSend={sendHandler} />
<MessageList data={messages} />
</div>
);
}
export default App;
|
console.log('okkkkkkkkkk');
|
/**
* Date Author Des
*----------------------------------------------
* 2018/8/10 gongtiexin 通用搜索表格组件
* */
import React, { Component } from 'react';
import { observer } from 'mobx-react';
import { withRouter } from 'react-router-dom';
import { upObject } from 'up-utils';
import PropTypes from 'prop-types';
import { Button, Col, Form, Input, Row, Table, Select, Cascader, DatePicker, Icon } from 'antd';
import Pagination from '../Pagination';
import './index.less';
const { Item: FormItem, create } = Form;
const { Option: SelectOption } = Select;
const { RangePicker } = DatePicker;
const formItemLatest = 3;
const RefAndWithRouterAndForm = Wrapped => {
const EnhancedForm = Form.create()(Wrapped);
const WithRouter = withRouter(({ forwardRef, ...otherProps }) => (
<EnhancedForm wrappedComponentRef={forwardRef} {...otherProps} />
));
const WithRouterAndRef = React.forwardRef((props, ref) => (
<WithRouter {...props} forwardRef={ref} />
));
const name = Wrapped.displayName || Wrapped.name;
WithRouterAndRef.displayName = `withRouterAndRef(${name})`;
return WithRouterAndRef;
};
@RefAndWithRouterAndForm
@observer
export default class SearchTable extends Component {
static propTypes = {
fields: PropTypes.array,
tableProps: PropTypes.object.isRequired,
paginationProps: PropTypes.object.isRequired,
callback: PropTypes.func,
expandChildren: PropTypes.element,
form: PropTypes.object,
history: PropTypes.object,
firstFetch: PropTypes.bool,
};
static defaultProps = {
fields: [],
callback: () => new Promise(resolve => setTimeout(resolve, 1000)),
expandChildren: null,
form: {},
history: {},
firstFetch: true,
};
state = {
loading: false,
};
componentDidMount() {
this.props.firstFetch && this.fetchData();
}
componentWillUnmount() {}
handleSearch = e => {
e.preventDefault();
const {
paginationProps: { size },
} = this.props;
this.props.form.validateFields(() => {
this.fetchData({ page: 1, size });
});
};
handleReset = () => this.props.form.resetFields();
fetchData = (params = {}) => {
this.setState({ loading: true });
const {
paginationProps: { size, page },
} = this.props;
const formValues = this.props.form.getFieldsValue();
const newParams = upObject.filterNull({
// 分页参数
page,
size,
// 搜索条件
...formValues,
// 其它参数
...params,
});
return Promise.resolve(this.props.callback(newParams))
.then(data => {
const {
tableProps: { dataSource: nextDataSource },
paginationProps: { page: nextPage },
} = this.props;
// 当前页没有数据又有上一页,自动翻到上一页
if (nextDataSource.length === 0 && nextPage > 1) {
newParams.currentPage = nextPage - 1;
this.fetchData(newParams);
return;
}
this.props.history.replace({ ...this.props.history.location, state: newParams });
return data;
})
.finally(() => this.setState({ loading: false }));
};
getFormItemByType = ({ type, key, label, items = [], options, props }) => {
const {
form: { getFieldDecorator },
} = this.props;
switch (type) {
case 'input': {
return (
<FormItem label={label}>{getFieldDecorator(key, options)(<Input {...props} />)}</FormItem>
);
}
case 'select': {
return (
<FormItem label={label}>
{getFieldDecorator(
key,
options,
)(
<Select {...props}>
{items.map(item => (
<SelectOption key={item.key || item.value} value={item.value}>
{item.label}
</SelectOption>
))}
</Select>,
)}
</FormItem>
);
}
case 'datePicker': {
return (
<FormItem>
{getFieldDecorator(
key,
options,
)(<DatePicker style={{ width: '100%' }} allowClear placeholder={label} {...props} />)}
</FormItem>
);
}
case 'rangePicker': {
return <FormItem>{getFieldDecorator(key, options)(<RangePicker />)}</FormItem>;
}
case 'cascader': {
return (
<FormItem>
{getFieldDecorator(key, options)(<Cascader placeholder={label} {...props} />)}
</FormItem>
);
}
default:
return null;
}
};
renderFormItems = () => {
const { fields } = this.props;
const count = this.state.expand ? fields.length : formItemLatest;
return fields.map((field, i) => (
<Col span={8} key={field.key} style={{ display: i < count ? 'block' : 'none' }}>
{this.getFormItemByType(field)}
</Col>
));
};
toggle = () => {
const { expand } = this.state;
this.setState({ expand: !expand });
};
render() {
const { fields = [], tableProps, paginationProps, expandChildren } = this.props;
const { loading } = this.state;
return (
<div className="search-table">
{fields.length > 0 && (
<Form className="ant-advanced-search-form" onSubmit={this.handleSearch}>
<Row gutter={24}>{this.renderFormItems()}</Row>
<Row>
<Col span={24} style={{ textAlign: 'right' }}>
<Button type="primary" htmlType="submit">
搜索
</Button>
<Button style={{ marginLeft: 8 }} onClick={this.handleReset}>
重置
</Button>
{fields.length > formItemLatest && (
<a style={{ marginLeft: 8, fontSize: 12 }} onClick={this.toggle}>
展开 <Icon type={this.state.expand ? 'up' : 'down'} />
</a>
)}
</Col>
</Row>
</Form>
)}
{expandChildren && <div className="search-expand">{expandChildren}</div>}
<Table size="middle" bordered loading={loading} pagination={false} {...tableProps} />
<Pagination handleChange={this.fetchData} {...paginationProps} />
</div>
);
}
}
|
({
generateSearchToken: function(component, event, helper) {
//console.log('>>>>>> generateSearchToken');
try {
var deferred = event.getParam('deferred');
var action = component.get('c.getEmptyFilterToken');
action.setParams({
searchHub: component.get('v.searchHub')
});
action.setCallback(this, function (response) {
if (response.getState() == 'SUCCESS') {
deferred.resolve({
searchToken: response.getReturnValue()
})
}
});
$A.enqueueAction(action);
} catch (e) {
helper.sendGAExceptionEvent('XeroCommunitySearch', 'generateSearchToken: ' + e.message);
}
},
handleRegionalisationEvent : function(cmp, event, helper) {
var searchI = Coveo.$$(document).find("#search");
//helper.updateSortRegion();
// Log search event
var customSearchEvent = {name: 'searchFromLink', type: 'interface'};
Coveo.logSearchEvent(searchI, customSearchEvent, {});
// Trigger search
Coveo.executeQuery(searchI);
// Scroll to top of results
searchI.scrollIntoView();
},
executeComponentInitilization: function(cmp, event, helper) {
//console.log('>>>>>> executeComponentInitilization');
try {
helper.getSiteURL(cmp, event, helper);
helper.getUserContext(cmp, event, helper);
} catch (e) {
helper.sendGAExceptionEvent('XeroCommunitySearch', 'executeComponentInit: ' + e.message);
}
},
onInterfaceContentLoaded: function(cmp, event, helper) {
try {
var searchInterface = Coveo.$$(document.querySelector('#search'));
if (siteUrl === "") {
helper.getSiteURL(cmp, event, helper);
}
var siteUrl = cmp.get('v.siteUrl');
// Check if we filter on all live events
var allLiveEventsFilter = helper.getUrlParameter('all_live');
searchInterface.on("deferredQuerySuccess", function(e) {
var simpleFilterElement = Coveo.$$(document).find('.CoveoSimpleFilter');
var simpleFilterInstance = Coveo.get(simpleFilterElement);
if (allLiveEventsFilter) {
// trigger search after last value was selected only
simpleFilterInstance.selectValue('Live webinar', false);
simpleFilterInstance.selectValue('Live classroom', true);
// reset filter
allLiveEventsFilter = undefined;
}
});
// Make whole result template clickable
searchInterface.on("newResultDisplayed", function(e, args) {
Coveo.$$(args.item).on('click', function(event) {
// Allow Coveo debug console to open on alt+dblclick
if (!event.altKey) {
var resultLinkElement = Coveo.$$(args.item).find('.CoveoResultLink');
var resultLinkInstance = Coveo.get(resultLinkElement);
resultLinkInstance.openLink();
}
});
});
// Region Filter (XVK-535)
searchInterface.on('buildingQuery', function (e, args) {
var region = helper.getRegionFromAbbreviationSingle();
// Build region expressions
var noRegionExpressionBuilder = new Coveo.ExpressionBuilder();
var regionExpressionBuilder = new Coveo.ExpressionBuilder();
var allRegionExpressionBuilder = new Coveo.ExpressionBuilder();
var advancedExpression = '';
noRegionExpressionBuilder.add("(NOT @sfregionc)");
advancedExpression += noRegionExpressionBuilder.build();
if (region) {
regionExpressionBuilder.addFieldExpression("@sfregionc", "=", [region]);
advancedExpression += " OR " + regionExpressionBuilder.build();
}
allRegionExpressionBuilder.addFieldExpression("@sfregionc", "==", ["All"]);
advancedExpression += " OR " + allRegionExpressionBuilder.build();
// Apply expression on query
args.queryBuilder.advancedExpression.add(advancedExpression);
});
// Add User Context
searchInterface.on('buildingQuery', function (e, args) {
args.queryBuilder.addContext(cmp.get('v.userContext'));
// Add region filter
args.queryBuilder.context["userRegion"] = helper.getCurrentUserRegion();
});
searchInterface.on('changeAnalyticsCustomData', function(e, args) {
var userContext = cmp.get('v.userContext');
for (var prop in userContext) {
args.metaObject[prop] = userContext[prop];
}
// Add region filter
args.metaObject["userRegion"] = helper.getCurrentUserRegion();
});
// Normalize clickable URIs
searchInterface.on(['preprocessResults', 'preprocessMoreResults'], function (e, args) {
if (args.results.results.length > 0) {
Coveo._.each(args.results.results, function (result) {
if (result.raw.sfredwingtrainingplancid) {
result.clickUri = siteUrl + '/s/course?courseId=' + result.raw.sfredwingtrainingplancid;
} else if (result.raw.objecttype == "redwing__Training_Plan_Section_Item__c" && result.parentResult) {
result.parentResult.clickUri = siteUrl + '/s/course?courseId=' + result.parentResult.raw.sfredwingtrainingplancid;
} else if (result.raw.sfredwingtrainingtrackcid) {
result.clickUri = siteUrl + '/s/programme?programmeId=' + result.raw.sfredwingtrainingtrackcid;
}
});
// Flag first result as expandable
if (args.results.results[0].index === 0) {
args.results.results[0].raw.expandable = true;
}
}
});
// Construct lessons footer field
searchInterface.on('preprocessResults', function (e, args) {
Coveo._.each(args.results.results, function (result) {
if (result.raw && (result.raw.objecttype == "redwing__Training_Plan__c" || result.raw.objecttype == "redwing__Training_Plan_Section_Item__c")) {
var children = (result.raw.objecttype == "redwing__Training_Plan_Section_Item__c" ? [result] : []);
if (result.childResults && result.childResults.length > 0) {
children = children.concat(result.childResults);
}
var raw;
if (result.raw.objecttype == "redwing__Training_Plan_Section_Item__c" && result.parentResult) {
raw = result.parentResult.raw;
} else if (result.raw.objecttype == "redwing__Training_Plan__c") {
raw = result.raw;
}
if (raw && children.length > 0) {
var names = helper.getConcatLessons(children);
raw.childConcatString = names.length + " lesson" + (names.length > 1 ? 's' : '') + ": " + names.join(", ");
}
}
});
});
// Only include Lessons available in user's region
searchInterface.on('doneBuildingQuery', function (e, args) {
args.queryBuilder.advancedExpression.add('(NOT @sfredwingtrainingplansectionitemcid OR @sfredwinglearningrregionc=(' + helper.getRegionFromAbbreviation() + '))');
});
searchInterface.on('querySuccess', function (e, args) {
var searchSuggestions = Coveo.$$(document.querySelector('.CustomCoveoQuerySuggest'));
var resultTitle = Coveo.$$(document.querySelector('.CustomCoveoResultTitle'));
if (args.results.totalCount > 0) {
if (args.query.q != undefined) {
// Display result title
resultTitle.el.innerText = 'Results for "' + args.query.q + '"';
resultTitle.el.classList.remove('u-hidden');
}
} // Display search suggestions on no-result
else if (args.results.queryCorrections.length === 0) {
var token = Coveo.SearchEndpoint.endpoints[cmp.get('v.name')].options.accessToken;
var topSearchesData = [];
Coveo.$.ajax({
url: 'https://platform.cloud.coveo.com/rest/search/v2/querySuggest',
type: 'GET',
headers: {
'Authorization': 'Bearer ' + token,
'Accept': 'application/json'
},
data: {
'count': '6',
'searchHub': cmp.get('v.searchHub')
},
success: function (data, textStatus) {
topSearchesData = data.completions;
},
async: false
});
var topSearchesLinks = Coveo.$$('ul', { 'class': 'coveo-card-layout', 'style': 'list-style-type:none; column-count:3;' });
Coveo._.each(topSearchesData, function (d) {
var l = Coveo.$$('li', { 'class': 'icon-text' });
//l.append(Coveo.$$('span', { 'class': 'icon icon--m icon-search--fill-grey' }).el);
//l.append(Coveo.$$('a', { 'class': 'recommended-query', 'href': '#q=' + d['expression'].toString() + '&sort=relevancy' }, d['expression'].toString()).el);
l.append(Coveo.$$('a', { 'class': 'recommended-query', 'href': '#q=' + d['expression'].toString() }, d['expression'].toString()).el);
topSearchesLinks.append(l.el);
});
let strippedResult = Coveo.state(searchInterface.el, "q");
//Stripping out html content from search keyword
strippedResult = strippedResult.replace(/(<([^>]+)>)/ig,"");
var noResultTitle = Coveo.$$('h1', { 'class': 'CustomCoveoNoResult u-text-color-primary' }, 'No results for "' + strippedResult + '"');
var topSearchesTitle = Coveo.$$('p', { 'class': 'error__text' }, 'Here are terms that other people searched for that might help');
var topSearchesList = Coveo.$$('div', { 'class': 'inset-block bg-illustrated' }, topSearchesLinks);
var topSearches = Coveo.$$('div', { 'class': 'top-searches' }, noResultTitle, topSearchesTitle, topSearchesList);
if (topSearchesData.length == 0) {
topSearchesTitle.hide();
topSearchesList.hide();
}
searchSuggestions.append(topSearches.el);
searchSuggestions.el.classList.remove('u-hidden');
}
});
// Hide search suggestions on new query
searchInterface.on('newQuery', function (e, args) {
var searchSuggestions = Coveo.$$(document.querySelector('.CustomCoveoQuerySuggest'));
var resultTitle = Coveo.$$(document.querySelector('.CustomCoveoResultTitle'));
searchSuggestions.el.innerText = '';
searchSuggestions.el.classList.add('u-hidden');
resultTitle.el.classList.add('u-hidden');
});
/*
var searchI = Coveo.$$(document).find("#search");
var resultTitle = Coveo.$$(document.querySelector('.CustomCoveoResultTitle'));
var noResult = Coveo.$$(document.querySelector('.CustomCoveoNoResult'));
var resultSuggestion = Coveo.$$(document.querySelector('.CustomCoveoResultSuggestion'));
var coveoPager = Coveo.$$(document.querySelector('.CoveoPager'));
var coveoSimpleFilter = Coveo.$$(document.querySelector('.CoveoSimpleFilter'));
var resultList = Coveo.$$(document.querySelector('.CoveoResultList[data-layout="list"]'));
var resultCard = Coveo.$$(document.querySelector('.CoveoResultList[data-layout="card"]'));
// Define sessionStorage getter and setter to store query state
function setQueryState(key, value) {
window.sessionStorage.setItem(key, value);
}
function getQueryState(key) {
return window.sessionStorage.getItem(key);
}
// Clean up custom components
searchInterface.on('newQuery', function (e, args) {
resultTitle.el.classList.add('u-hidden');
noResult.el.classList.add('u-hidden');
resultSuggestion.el.classList.add('u-hidden');
});
searchInterface.on('querySuccess', function (e, args) {
if (args.results.totalCount > 0) {
// Display appropriate result layout based on query state
if (getQueryState('eq__c') === 'true') {
resultList.el.classList.add('u-hidden');
resultCard.el.classList.remove('u-hidden');
coveoPager.el.classList.add('u-hidden');
coveoSimpleFilter.el.classList.add('u-hidden');
} else {
resultList.el.classList.remove('u-hidden');
resultCard.el.classList.add('u-hidden');
coveoPager.el.classList.remove('u-hidden');
coveoSimpleFilter.el.classList.remove('u-hidden');
}
// If query is not empty
if (args.query.q != undefined) {
// Display result title
resultTitle.el.innerText = 'Results for "' + args.query.q + '"';
resultTitle.el.classList.remove('u-hidden');
}
// If redirecting with an empty query
if (getQueryState('eq__c') === 'true') {
setQueryState('eq__c', 'false');
noResult.el.innerText = 'No results for "' + Coveo.state(searchI, "oq__c") + '"';
noResult.el.classList.remove('u-hidden');
resultSuggestion.el.innerText = 'Here are terms that other people searched for that might help';
resultSuggestion.el.classList.remove('u-hidden');
resultSuggestion.el.classList.add('error__text');
}
// If presenting query correction
if (getQueryState('cq__c') === 'true') {
setQueryState('cq__c', 'false');
var searchTitle = Coveo.$$('span', {
className: 'coveo-search-title'
}, 'Search instead for');
var searchTerms = Coveo.$$('span', {
className: 'coveo-search-terms'
}, Coveo.state(searchI, "oq__c"));
searchTitle.append(searchTerms.el);
searchTerms.on('click', onSelection.bind({newQuery: Coveo.state(searchI, "oq__c")}));
function onSelection() {
// Indicate that we're bypassing query correction
setQueryState('bq__c', true);
var customSearchEvent = {name: 'searchFromLink', type: 'interface'};
Coveo.logSearchEvent(searchI, customSearchEvent, {});
setQueryState('oq__c', Coveo.state(searchI, "q"));
Coveo.state(searchI, "q", this.newQuery);
Coveo.executeQuery(searchI);
}
resultSuggestion.el.innerText = '';
resultSuggestion.el.appendChild(searchTitle.el);
resultSuggestion.el.classList.remove('u-hidden');
resultSuggestion.el.classList.remove('error__text');
}
} else {
noResult.el.innerText = 'No results for "' + Coveo.state(searchI, "q") + '"';
noResult.el.classList.remove('u-hidden');
}
});
searchInterface.on('noResults', function (e, args) {
if (Coveo.state(searchI, "q") !== getQueryState('oq__c')) {
// Check that query correction is available and user didn't choose to bypass it
if (args.results.queryCorrections.length > 0 && getQueryState('bq__c') !== 'true') {
// Trigger corrected query
setQueryState('cq__c', true);
var originalQuery = Coveo.state(searchI, "q");
Coveo.state(searchI, "oq__c", originalQuery);
setQueryState('oq__c', originalQuery);
Coveo.state(searchI, "q", args.results.queryCorrections[0].correctedQuery);
} else {
setQueryState('bq__c', 'false');
// Trigger empty query
setQueryState('eq__c', 'true');
var originalQuery = Coveo.state(searchI, "q");
Coveo.state(searchI, "oq__c", originalQuery);
setQueryState('oq__c', originalQuery);
Coveo.state(searchI, "q", "");
}
setTimeout(function () {
Coveo.executeQuery(searchI);
}, 0);
} else {
setQueryState('oq__c', Coveo.state(searchI, "q"));
}
});
searchInterface.on('buildingQuery', function (e, args) {
args.queryBuilder.enableDidYouMean = true;
});
searchInterface.on('doneBuildingQuery', function (e, args) {
if (getQueryState('eq__c') === 'true') {
args.queryBuilder.numberOfResults = 6;
}
});
searchInterface.on('deferredQuerySuccess', function (e, args) {
// Handle suggested results click event
Coveo.$(".recommended-query").click(function () {
var customSearchEvent = {name: 'searchFromLink', type: 'interface'};
Coveo.logSearchEvent(searchI, customSearchEvent, {});
Coveo.state(searchI, "q", this.innerText);
Coveo.executeQuery(searchI);
});
});
*/
// Add a nextclass field on Courses based on user region
searchInterface.on('preprocessResults', function (e, args) {
var nextclassField = helper.getNextclassField();
Coveo._.each(args.results.results, function (result) {
if (result.raw.objecttype === 'redwing__Training_Plan__c') {
result.raw.__nextclass = result.raw[nextclassField];
}
});
});
// Configure the date Sort component based on user region
//searchInterface.on('afterComponentsInitialization', function (e, args) {
// helper.updateSortRegion();
//});
// Filter out classes with a past date
searchInterface.on('doneBuildingQuery', function (e, args) {
var nextclassField = helper.getNextclassField();
args.queryBuilder.advancedExpression.add('NOT @' + nextclassField + ' OR @' + nextclassField + '>now');
});
// Add Coveo Searchbox Referrer to UA event
searchInterface.on('changeAnalyticsCustomData', function(e, args) {
args.metaObject["searchboxReferrerPath"] = document.coveoSearchboxReferrer;
args.metaObject["omniboxAnalytics"] = document.coveoOmniboxAnalytics;
// Reset the coveoOmniboxAnalytics flag
document.coveoOmniboxAnalytics = undefined;
});
} catch (e) {
helper.sendGAExceptionEvent('XeroCommunitySearch', 'onInterfaceContentLoaded: ' + e.message);
}
}
})
|
import React, { Component } from 'react'
import { connect } from 'react-redux'
import {
fetchContents,
intoLoading,
exitLoading,
} from './actions.js'
import FlatButton from 'material-ui/FlatButton';
import PageSteps from './PageSteps.js'
import Users from './Users.js'
import Chart from '../components/Chart.js'
import ExperimentSetting from './ExperimentSetting.js'
import EditQuestion from './EditQuestion.js'
import DownloadButton from './DownloadButton'
import throttle from 'react-throttle-render'
import { changePage } from './actions'
import { ReadJSON, InsertVariable } from '../util/ReadJSON'
const ThrottledChart = throttle(Chart, 100)
const mapStateToProps = ({ dispatch, dictator_results, participants, pairs, page }) => ({
dispatch, dictator_results, participants, pairs, page
})
class App extends Component {
constructor(props, context) {
super(props, context)
this.state = {}
}
componentDidMount() {
const { dispatch } = this.props
dispatch(intoLoading())
dispatch(fetchContents())
dispatch(exitLoading())
}
componentWillReceiveProps({ pairs, page }) {
if(page == "experiment") {
for(var key in pairs) {
if(pairs[key].state != "finished") return
}
const { dispatch } = this.props
dispatch(changePage("result"))
}
}
render() {
const { dictator_results, participants, pairs, page } = this.props
return (
<div>
<PageSteps />
<Users />
<ThrottledChart />
<ExperimentSetting />
<EditQuestion style={{ marginLeft: "2%" }} disabled={page != "waiting"} />
<DownloadButton
fileName={"dictator_game.csv"}
list={[
[ReadJSON().static_text["title"]],
[ReadJSON().static_text["file"][0], new Date()],
[ReadJSON().static_text["file"][1], Object.keys(participants).length],
[ReadJSON().static_text["file"][2], Object.keys(pairs).length],
[ReadJSON().static_text["file"][3], ReadJSON().static_text["file"][4]],
].concat(
Object.keys(participants).map(id => [id, participants[id].point])
).concat(
[[ReadJSON().static_text["file"][4]].concat(Object.keys(dictator_results).map(key => InsertVariable(ReadJSON().static_text["round_"], { round: key })))]
).concat(
[0, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000].map(n => [n].concat(
Object.keys(dictator_results).map(key => {
const tmp = Object.keys(dictator_results[key]).map(i => dictator_results[key][i].value)
let cnt = 0
for(var j in tmp) cnt += (0 + (tmp[j] == n))
return cnt
})
))
)}
style={{marginLeft: '2%'}}
disabled={page != "result"}
/>
</div>
)
}
}
export default connect(mapStateToProps)(App)
|
#pragma strict
// Class for the Ai
class GomokuAi {
// Variables
public var isWhite : boolean;
public var aiLevel : int;
private var recursionDepth : int;
private var ownColor : Occupation;
private var enemyColor : Occupation;
private var scanList = {};
private var outList = {};
// Contructors
public function GomokuAi (){
aiLevel = 1;
isWhite = true;
}
public function GomokuAi (_GomokuAi : GomokuAi){
aiLevel = _GomokuAi.aiLevel;
isWhite = _GomokuAi.isWhite;
}
public function GomokuAi (_aiLevel : int, _isWhite : boolean){
aiLevel = _aiLevel;
isWhite = _isWhite;
}
// Manual Setup Funcitons
public function setGomokuAi (_aiLevel : int, _isWhite : boolean){
aiLevel = _aiLevel;
isWhite = _isWhite;
}
public function setLevel (_aiLevel : int) {
aiLevel = _aiLevel;
if (aiLevel >= 3) {
recursionDepth = 1;
aiLevel = 3;
}
else if (aiLevel < 3) {
aiLevel = 1;
recursionDepth = 1;
}
}
public function setColor (_isWhite : boolean) {
if (_isWhite == true){
ownColor = Occupation.white;
enemyColor = Occupation.black;
}
else {
ownColor = Occupation.black;
enemyColor = Occupation.white;
}
}
// Setup funciton needed for the Ai' decsions in finding a move to make
// tell the ai what level it is and how hard it should try
private function initializeAi (theBoard : GomokuBoard, whitesTurn : boolean, level : int) {
setColor (whitesTurn);
setLevel (level);
}
// Ai makes a decision for it's next move
// Choose to block or build its own plan
public function chooseMove (theBoard : GomokuBoard, whitesTurn : boolean, level : int) {
var bestMove : Coordinate = new Coordinate ();
initializeAi (theBoard, whitesTurn, level);
updateLists (theBoard.lastMoveMade, theBoard, scanList, outList);
var score : double = -Mathf.Infinity;
if (ownColor == Occupation.black) score = Mathf.Infinity;
var newScore : double;
for(var nextNode in scanList){
var location = new Coordinate (nextNode.Value);
if (ownColor == Occupation.white){
theBoard.coordinates [location.x, location.y].setPiece (ownColor);
var newList = new Boo.Lang.Hash (scanList);
newList.Remove(generateKey(location));
newScore = findBestScore (newList, outList, theBoard, location, recursionDepth-1, -Mathf.Infinity, Mathf.Infinity, ownColor);
if (newScore >= score) {
score = newScore;
bestMove.setCoordinates (location);
}
theBoard.coordinates [location.x, location.y].clearSpot();
}
else {
theBoard.coordinates [location.x, location.y].setPiece (ownColor);
var newList2 = new Boo.Lang.Hash (scanList);
newScore = findBestScore (newList2, outList, theBoard, location, recursionDepth-1, -Mathf.Infinity, Mathf.Infinity, ownColor);
if (newScore <= score) {
score = newScore;
bestMove.setCoordinates (location);
}
theBoard.coordinates [location.x, location.y].clearSpot();
}
}
if (aiLevel < 3){
var rand = Random.value*100;
if (rand < (3-aiLevel)*15) {
while (true){
var spare = new Coordinate ((Random.value*100)%19, (Random.value*100)%19);
if (scanList.ContainsKey(generateKey (spare))){
bestMove.setCoordinates (spare);
break;
}
}
}
}
updateLists (bestMove, theBoard, scanList, outList);
return bestMove;
}
function findBestScore (_scanningList : Boo.Lang.Hash, _outtedList : Boo.Lang.Hash, _theBoard : GomokuBoard, _location : Coordinate, depth : int, a : double, b : double, playerColor : Occupation) : double {
var scanningList = new Boo.Lang.Hash (_scanningList);
var outtedList = new Boo.Lang.Hash (_outtedList);
var theBoard = new GomokuBoard (_theBoard);
var theLocation = new Coordinate (_location);
var scoreCount = new Array ();
scoreCount.push (findChain(theLocation ,theBoard, 1, 0));
scoreCount.push (findChain(theLocation ,theBoard, 0, 1));
scoreCount.push (findChain(theLocation ,theBoard, 1, 1));
scoreCount.push (findChain(theLocation ,theBoard, -1, 1));
var scoreSelf : double = calculateScore (scoreCount);
var scoreOpponent : double = findEnemyPotenialScore (theLocation, theBoard);
if (aiLevel > 2) scoreOpponent *= 0.9;
var currentScore : double = scoreSelf - (scoreOpponent*0.9);
//Debug.Log ("put a " + playerColor + " piece at " + theLocation.x + ", " + theLocation.y + " depth of " + depth);
if (depth == 0 || currentScore >= 1000000000 || currentScore <= -1000000000) {
//Debug.Log ("at a terminal end with score: " + currentScore + ". " + scoreSelf + "/" + scoreOpponent);
return currentScore;
}
else {
var score : double;
var newScore : double;
if (ownColor == Occupation.white){
score = -Mathf.Infinity;
for(var nextNode in scanningList){
var location = new Coordinate (nextNode.Value);
theBoard.coordinates [location.x, location.y].setPiece (ownColor);
var newList = new Boo.Lang.Hash (scanningList);
newList.Remove(generateKey(location));
updateLists(location, theBoard, newList, outtedList);
newScore = findBestScore (newList, outtedList, theBoard, location, depth-1, -Mathf.Infinity, Mathf.Infinity, enemyColor);
score = max (score, newScore);
a = max (a, score);
if (b <= a) break;
theBoard.coordinates [location.x, location.y].clearSpot();
}
}
else {
score = Mathf.Infinity;
for(var nextNode2 in scanningList){
var location2 = new Coordinate (nextNode2.Value);
theBoard.coordinates [location2.x, location2.y].setPiece (ownColor);
var newList2 = new Boo.Lang.Hash (scanningList);
newList2.Remove(generateKey(location));
updateLists(location, theBoard, newList2, outtedList);
newScore = findBestScore (newList2, outtedList, theBoard, location2, depth-1, -Mathf.Infinity, Mathf.Infinity, enemyColor);
score = min(score, newScore);
b = min (b, score);
if (b <= a) break;
theBoard.coordinates [location2.x, location2.y].clearSpot();
}
}
return score;
}
}
public function findEnemyPotenialScore (_current : Coordinate, _theBoard : GomokuBoard) {
var theBoard : GomokuBoard = new GomokuBoard (_theBoard);
var current : Coordinate = new Coordinate (_current);
var pebbleChain = new Array ();
var playerColor : Occupation = theBoard.coordinates[current.x, current.y].getState();
var opponentColor : Occupation = Occupation.black;
if (playerColor == Occupation.black) opponentColor = Occupation.white;
theBoard.coordinates[current.x, current.y].clearSpot();
theBoard.coordinates[current.x, current.y].setPiece(opponentColor);
pebbleChain.push (findChain(current ,theBoard, 1, 0));
pebbleChain.push (findChain(current ,theBoard, 0, 1));
pebbleChain.push (findChain(current ,theBoard, 1, 1));
pebbleChain.push (findChain(current ,theBoard, -1, 1));
return calculateScore (pebbleChain);;
}
public function calculateScore (pebbleChain : Array){
var totalScore : double = 0;
var blockedFour : int = 0;
var unblockedThree : int = 0;
var color : Occupation;
for (var i = 0; i < pebbleChain.length; i++){
var theChain : PieceChain = new PieceChain (pebbleChain[i]);
theChain.determineChainType ();
var curScore : double = 0;
if (i == 0) color = theChain.ownColor;
if (theChain.length > 4){
curScore += 1000000000;
}
else if (theChain.length == 4){
if (theChain.state == ChainState.unblocked) curScore += 100000000;
if (theChain.state == ChainState.blocked) {
curScore += 500000;
blockedFour++;
}
}
else if (theChain.length == 3){
if (theChain.state == ChainState.unblocked) {
curScore += 400000;
unblockedThree ++;
}
else if (theChain.state == ChainState.blocked) {
curScore += 1500;
}
}
else if (theChain.length == 2){
if ((theChain.state == ChainState.unblocked)) curScore += 1200;
else if (theChain.state == ChainState.blocked) curScore += 100;
}
else if (theChain.length == 1) {
if ((theChain.state == ChainState.unblocked)) curScore += 2;
else if (theChain.state == ChainState.blocked) curScore += 1;
}
if (aiLevel > 1){
if (theChain.detached) curScore *= 3/4;
}
totalScore += curScore;
}
if (blockedFour > 1){
totalScore = totalScore - (2*500000) + 100000000;
}
else if (blockedFour > 0 && unblockedThree > 0){
totalScore = totalScore - 400000 - 500000 + 10000000;
}
else if (unblockedThree > 1){
totalScore = totalScore - (2*400000) + 1000000;
}
if (color == Occupation.black) totalScore *= -1;
return totalScore;
}
private function findChain (current : Coordinate, _theBoard : GomokuBoard, xI : int, yI : int){
var theBoard : GomokuBoard = new GomokuBoard (_theBoard);
var cur_Coord : Coordinate = new Coordinate (current);
var playerColor : Occupation = theBoard.coordinates [cur_Coord.x, cur_Coord.y].getState ();
var opponnentColor : Occupation = Occupation.black;
if (playerColor == Occupation.black) opponnentColor = Occupation.white;
var pieceChain : PieceChain = new PieceChain ();
pieceChain.ownColor = playerColor;
pieceChain.enemyColor = opponnentColor;
pieceChain.length = 0;
if (theBoard.coordinates[cur_Coord.x, cur_Coord.y].getState() != playerColor) return pieceChain;
for (var i = 0; i < 2; i++){
cur_Coord.setCoordinates (current);
if (i == 1){
xI *= -1;
yI *= -1;
pieceChain.length--;
}
while (true) {
if ((cur_Coord.x < 0 || cur_Coord.y < 0 || cur_Coord.x > 18 || cur_Coord.y > 18) ||
theBoard.coordinates[cur_Coord.x, cur_Coord.y].getState() == opponnentColor){
if (i == 0) pieceChain.positiveCap.setCap (cur_Coord, opponnentColor);
else pieceChain.negativeCap.setCap (cur_Coord, opponnentColor);
break;
}
else if (theBoard.coordinates [cur_Coord.x, cur_Coord.y].getState () == Occupation.none){
if ((cur_Coord.x+xI >= 0 && cur_Coord.y+yI >= 0 && cur_Coord.x+xI <= 18 && cur_Coord.y+yI <= 18) &&
theBoard.coordinates [cur_Coord.x+xI, cur_Coord.y+yI].getState () == playerColor && !pieceChain.detached) {
pieceChain.neutralCap.setCap (cur_Coord, Occupation.none);
cur_Coord.increment (xI, yI);
pieceChain.detached = true;
}
else {
if (i == 0) pieceChain.positiveCap.setCap (cur_Coord, Occupation.none);
else pieceChain.negativeCap.setCap (cur_Coord, Occupation.none);
break;
}
}
else {
pieceChain.length++;
cur_Coord.increment (xI, yI);
}
}
}
return pieceChain;
}
public function updateLists (_currentLocation : Coordinate, _theBoard : GomokuBoard, theScanList : Boo.Lang.Hash, theOutList : Boo.Lang.Hash){
var currentLocation = new Coordinate (_currentLocation);
var theBoard = new GomokuBoard (_theBoard);
var northBorder = new Coordinate ();
var southBorder = new Coordinate ();
var fieldSize : int = 1;
if (theScanList.ContainsKey(generateKey(currentLocation))){
theScanList.Remove(generateKey(currentLocation));
}
if (!theOutList.ContainsKey(generateKey(currentLocation))){
theOutList.Add(generateKey(currentLocation), currentLocation);
}
for (var i = fieldSize; i >= 0; i--) {
if (currentLocation.x + i < theBoard.size) {
northBorder.x = currentLocation.x + i;
break;
}
}
for (i = fieldSize; i >= 0; i--) {
if (currentLocation.y + i < theBoard.size) {
northBorder.y = currentLocation.y + i;
break;
}
}
for (i = fieldSize; i >= 0; i--) {
if (currentLocation.x - i >= 0) {
southBorder.x = currentLocation.x - i;
break;
}
}
for (i = fieldSize; i >= 0; i--) {
if (currentLocation.y - i >= 0) {
southBorder.y = currentLocation.y - i;
break;
}
}
for (var y = southBorder.y; y <= northBorder.y; y++) {
for (var x = southBorder.x; x <= northBorder.x; x++) {
var location = new Coordinate (x,y);
if (theBoard.coordinates [x,y].getState() == Occupation.none) {
if (!theOutList.ContainsKey(generateKey(location))) {
theScanList.Add(generateKey(location), location);
theOutList.Add(generateKey(location), location);
}
}
else {
if (!theOutList.ContainsKey(generateKey(location))) {
theOutList.Add(generateKey(location), location);
}
}
}
}
}
function generateKey (location : Coordinate) {
return location.y*19 + location.x;
}
function max (a : double, b : double){
if (b >= a) return b;
else return a;
}
function min (a : double, b : double){
if (b <= a) return b;
else return a;
}
}
|
import React, {useEffect, useState} from 'react';
import {StyleSheet, View, InteractionManager} from 'react-native';
import Screen from '../Screen';
import {Colors, Layout, Styles, Fonts, SCREEN_KEYS} from '@app/constants';
import {Button} from 'native-base';
import {Circle, Flex, MapMarker, StyledText} from '@app/components';
import MapStyle from '@app/config/MapStyle.json';
import MapView, {Marker, PROVIDER_GOOGLE} from 'react-native-maps';
import {useSafeAreaInsets} from 'react-native-safe-area-context';
import LocationArrowIcon from '../../assets/icons/LocationArrowIcon';
const ASPECT_RATIO = Layout.window.width / Layout.window.height;
const LATITUDE_DELTA = 0.09;
const LONGITUDE_DELTA = LATITUDE_DELTA * ASPECT_RATIO;
export default function TripDetailsScreen(props) {
const {bottom} = useSafeAreaInsets();
const {trip} = props.route?.params ?? {};
const {id, latitude, longitude} = trip;
const [isMapVisible, setIsMapVisible] = useState(false);
useEffect(() => {
props.navigation.setOptions({title: '#' + id});
InteractionManager.runAfterInteractions(() => setIsMapVisible(true));
}, []);
const onMyWayPress = () => {
console.log('---here---');
props.navigation.navigate(SCREEN_KEYS.MAIN_STACK, {
screen: SCREEN_KEYS.HOME,
});
};
return (
<Screen style={[styles.container, {paddingBottom: bottom}]}>
<View
style={{
padding: Layout.padding.normal,
flexDirection: 'row',
}}>
<Flex>
<View style={{flexDirection: 'row', alignItems: 'center'}}>
<Circle size={18} />
<StyledText
style={{paddingHorizontal: Layout.padding.large}}
children={trip.address}
color={Colors.white}
/>
</View>
</Flex>
<View style={{justifyContent: 'space-between', alignItems: 'center'}}>
<View style={styles.locationArrowContainer}>
<LocationArrowIcon height={24} />
</View>
<StyledText color={Colors.white} children={'Cash'} />
</View>
</View>
<View style={{flex: 1}}>
<If condition={isMapVisible}>
<MapView
style={{flex: 1}}
provider={PROVIDER_GOOGLE}
customMapStyle={MapStyle}
initialRegion={{
latitude,
longitude,
latitudeDelta: LATITUDE_DELTA,
longitudeDelta: LONGITUDE_DELTA,
}}>
<MapMarker
withBubble
title={'0.5 km - 5 mins'}
description={'Coleman Park'}
coordinate={{latitude, longitude}}
/>
</MapView>
</If>
</View>
<View style={{padding: Layout.padding.large}}>
<Button block success onPress={onMyWayPress}>
<StyledText color={Colors.white} children={'On my way'} />
</Button>
</View>
</Screen>
);
}
const styles = StyleSheet.create({
container: {},
locationArrowContainer: {
width: 50,
height: 50,
borderRadius: 25,
backgroundColor: Colors.lightColor,
justifyContent: 'center',
alignItems: 'center',
marginBottom: Layout.margin.large,
},
});
|
test('subject_text');
function test(id)
{
document.getElementById(id).innerHTML="STANDARD MESSAGE";
}
|
import React from 'react'
import PropTypes from 'prop-types'
import Menu from '@material-ui/core/Menu'
import MenuItem from '@material-ui/core/MenuItem'
import { More as MoreIcon } from '../../icons'
import './more-menu.scss'
function MoreMenu({ options, onClick }) {
const [anchorEl, setAnchorEl] = React.useState(null)
const open = Boolean(anchorEl)
const handleClick = (event) => {
setAnchorEl(event.currentTarget)
}
const handleClose = (option) => {
setAnchorEl(null)
onClick(option)
}
return (
<div className="more-menu-container">
<span className="more-menu-button" onClick={handleClick}>
<MoreIcon size={12} />
</span>
<Menu
id="long-menu"
anchorEl={anchorEl}
keepMounted
open={open}
onClose={handleClose}
>
{options.map((option) => (
<MenuItem key={option} onClick={() => handleClose(option)}>
{option}
</MenuItem>
))}
</Menu>
</div>
)
}
MoreMenu.propTypes = {
options: PropTypes.arrayOf(PropTypes.string),
onClick: PropTypes.func,
}
MoreMenu.defaultProps = {
options: [],
onClick: () => {},
}
export default MoreMenu
|
import React from 'react';
import styles from './footer.module.css';
export default function Footer() {
return (
<footer className={styles.footer}>
Thomas Maxwell Smith Portfolio, made with React. View on <a href="https://github.com/atomcorp/react-portfolio">Github</a>
</footer>
);
}
|
import React, { Component } from 'react';
import './App.css';
import Navigation from './components/Navigation/Navigation.js'
import Logo from './components/Logo/Logo.js'
import Particles from 'react-particles-js';
import {particleOptions} from './particle.js'
import ImageLinkForm from './components/ImageLinkForm/ImageLinkForm.js'
import Rank from './components/Rank/Rank.js'
import FaceRecognition from './components/FaceRecognition/FaceRecognition.js'
import SignIn from './components/SignIn/SignIn.js'
import Register from './components/Register/Register.js'
const initialState =
{
input: '',
imageUrl: '',
boxes:[],
route: 'signin',
isSignedIn: false,
user:
{
id:'',
name:'',
email:'',
password:'',
entries: 0 ,
joined: ''
}
}
class App extends Component {
constructor(){
super()
this.state = initialState;
}
loadUser = (data) => {
this.setState({user: {
id: data.id,
name: data.name,
email: data.email,
password: data.password,
entries: data.entries ,
joined: data.joined
}})
}
onRouteChange = (place) => {
(place === 'signin' || place === 'register')?
this.setState(initialState):
this.setState({isSignedIn: true});
this.setState({route:place});
}
checkImage = (src) => {
const checks = {};
const img = new Image();
img.src = src;
let status;
return new Promise((resolve, reject) => {
img.onerror = () => {
checks[src] = false;
status=false;
resolve(status);
};
img.onload = () => {
checks[src] = true;
status=true;
resolve(status);
}
})
}
calculatePointsInImage = (actualFace,width,height) => {
const points = {};
points.leftCol = actualFace.left_col*width;
points.topRow = actualFace.top_row*height;
points.rightCol = width*(1.0-actualFace.right_col);
points.bottomRow = height*(1.0-actualFace.bottom_row);
return points;
}
calculateFaceLocation = (data) => {
let arrayOfFacePoints = [];
const faceLocationCoordinates = data.outputs[0].data.regions;
const image = document.getElementById('inputImage');
const width = Number(image.width);
const height = Number(image.height);
for(let actualFace of faceLocationCoordinates){
actualFace = actualFace.region_info.bounding_box;
arrayOfFacePoints.push(this.calculatePointsInImage(actualFace,width,height));
}
return arrayOfFacePoints;
}
boxesOutlineFace = (boxes_points) => {
this.setState({boxes: boxes_points})
}
onInputChange = (event) => {
this.setState({input: event.target.value})
}
detectFace = () => {
this.setState({imageUrl: this.state.input})
fetch('http://localhost:3000/imageurl',{
method:'post',
headers: {'Content-type': 'application/json'},
body: JSON.stringify({
input:this.state.input
})
})
.then(response => response.json())
.catch(err => console.log('ERROR!',err))
.then(response => {
if(response){
fetch('http://localhost:3000/image',{
method:'put',
headers: {'Content-type': 'application/json'},
body: JSON.stringify({
id:this.state.user.id
})
})
.then(response => response.json())
.then(count => {
this.setState(Object.assign(this.state.user,{entries:count})) //setState END
}) //count END
.catch(err => console.log(err));
} //if response END
this.boxesOutlineFace(this.calculateFaceLocation(response)) //calculate the points of box
})
.catch(err => console.log(err)); //if has a error then cath
this.setState({input: ''});
}
onButtonSubmit = () => {
if( this.state.input == null || !this.state.input) {return}
this.checkImage(this.state.input)
.then(res => {return res} )
.catch(err => console.log(err,'Erro ao carregar URL'))
.then(this.detectFace())
}
render(){
const { isSignedIn,imageUrl,boxes,route,input,user } = this.state;
return (
<div className="App">
<Particles
className = 'particles'
params={particleOptions}
/>
<Navigation onRouteChange={this.onRouteChange} isSignedIn={isSignedIn}/>
{ (route === 'signin')?
<SignIn onRouteChange={this.onRouteChange} loadUser={this.loadUser} />
:(route === 'home'?
<div>
<Logo />
<Rank name={user.name} entries={user.entries} />
<ImageLinkForm
onInputChange={this.onInputChange}
onButtonSubmit={this.onButtonSubmit}
valueField={input}
/>
<FaceRecognition boxesOutlineFace={boxes} imageUrl={imageUrl} />
</div> :
<Register onRouteChange={this.onRouteChange} loadUser={this.loadUser}/>
)
}
</div>
)
}
}
export default App;
|
function createDiv2(){
//creare il testo
let txt2 = document.createTextNode("DIVE E P creati dal secondo js caricato");
//console.log(txt2);
//creare p tag e append textnode nel tag
let parag2 = document.createElement("p");
parag2.setAttribute("class", "pagf2");
parag2.appendChild(txt2);
//creare div tag e append p nel div tag
let div2 = document.createElement("div");
div2.setAttribute("class", "container2")
div2.appendChild(parag2);
//console.log(div2);
let main2 = document.querySelector(".element-container");
main2.append(div2);
//style of div con class = "container"
let contain2 = document.querySelector('.container2');
//console.log(contain2);
contain2.style.color = "gray";
contain2.style.margin = "2rem";
contain2.style.padding = "2rem";
contain2.style.boxShadow = "0 0.4rem 0.5rem rgba(0, 0, 0, 0.3)"
};
export {createDiv2};
|
function Racers (name , fuel , tire , pominati ) { // konstruktor
this.name = name ;
this.fuel = fuel;
this.tire = tire ;
this.pominati = pominati;
this.getFuel = function () {
return this.fuel; // geter na fuel
}
this.setFuel = function (fuel) {
this.fuel = fuel; // seter na fuel
}
this.getTire = function () {
return this.tire;
}
this.setTire = function (tire) {
this.tire = tire;
}
this.getName = function () {
return this.name ;
}
this.getPominati= function () {
return this.pominati
}
this.setPominati = function (pominati) {
this.pominati = pominati;
}
}
function Yugo (name , fuel , tire , pominati ) {
Racers.call (this, name , fuel , tire , pominati ); // povikuvanje na konstruktorot od racers
}
Yugo.prototype = new Racers () ; // nov objekt od racers i naslednik na site negovi parametri kje bide yugo
function Pegla (name , fuel , tire , pominati ) {
Racers.call(this ,name , fuel , tire , pominati );
}
Yugo.prototype = new Racers () ;
function Buggati ( name , fuel , tire , pominati ) {
Racers.call(this, name , fuel , tire , pominati) ;
}
Buggati.prototype = new Racers () ;
|
import glob from 'glob';
import Promise from 'bluebird';
import initDebug from 'debug';
import path from 'path';
const debug = initDebug('happy:slack:utils:skillDictionary');
export default () => (
new Promise((resolve) => {
glob(path.join(__dirname, '../skills/**/config.js'), {}, (err, files) => {
let skills = [];
debug('getting library', files);
files.forEach((Skill) => {
// eslint-disable-next-line
const { listenTo } = require(Skill);
skills = [
...skills,
...listenTo,
];
});
resolve(skills);
});
})
);
|
console.log("first task");
console.time();
for (let i = 0; i < 10000; i++) {
const h3 = document.querySelector("h3");
h3.textContent = "Hey, everyone is waiting for me";
}
console.timeEnd();
console.log("Next task");
console.log("-----------------------");
console.log("firs task");
setTimeout(() => {
console.log("second task");
}, 0);
console.log("next task");
|
export default {
// "some.translation.key": "Text for some.translation.key",
//
// "a": {
// "nested": {
// "key": "Text for a.nested.key"
// }
// },
//
// "key.with.interpolation": "Text with {{anInterpolation}}"
"name-app":"SupperMarket App",
"menu":{
"home":"Home",
"products":"Products",
"about":"About",
"categories":"Categories",
"admin":"Admin",
"sign-up":"Sign up",
"login":"Login"
},
"admin": {
"category": {
"add-new": {
"title":"Create a new category (i18)",
"save":"Save category (i18)"
},
"category-name-placeholder":"The name of category",
"category-description-placeholder":"The description of category",
"save":"Save"
}
},
"category":{
"list-category":{
"list-all-products":"List all products",
"list-all-products-of":"List all products of {{name-category}}",
"index":"No",
"product-id":"Product ID",
"product-name":"Product name",
"category":"Category",
"unit":"Unit",
"price":"Price"
}
}
/* Nesting Translations
"test":{
"case-1":{
"parent-name":"Parent name",
"child-1":"This is child-1 of {{parent-name}}",
"child-2":"This is child-2 of {{parent-name}}",
"child-3":"this is child-3 of {{t 'parent'}}" //this way should not be used as the translation files shouldn't have handlebars logic
}
}
<p>{{t "test.case-1.parent-name"}}</p>
<p>{{t "test.case-1.child-1" parent-name=(t 'parent-name')}}</p>
<p>{{t "test.case-1.child-2" parent-name="parent modified"}}</p>
*/
};
|
pm_domain_url = null;
sender_guid = "";
popup_onload = false;
object_cnt = null;
// 2015.04.03 hwjang start websock_areaID[index]와 AreaID 관련성 확인
//AreaID = null;
socketIndex_AreaID = null;
// 2015.04.03 hwjang end websock_areaID[index]와 AreaID 관련성 확인
Guid2 = null;
function Bems_postmessage(domain, popup_name, popup_width, popup_height){
this.domain_url = domain;
this.window_popup = null;
this.popup_name = popup_name;
this.popup_width = popup_width;
this.popup_height = popup_height;
this.send_message = null;
this.receive_message = null;
}
function receiveMessage(event)
{
console.log('received response: ',event.data);
var strEvent = event.data;
if(strEvent.indexOf("|onload|true")!=-1){ // 제어 창을 띄울 때 수행
popup_onload = true;
bems_pm_obj.sender_send_msg(Bems_element_list[object_cnt].guid + "|" + Bems_element_list[object_cnt].animation_enable);
bems_pm_obj.sender_send_msg("Name|" + Bems_element_list[object_cnt].name);
// 2014.11.20 hwjang start description 표시 항목 변경
bems_pm_obj.sender_send_msg("Description|" + Bems_element_list[object_cnt].description);
// 2014.11.20 hwjang end description 표시 항목 변경
bems_pm_obj.sender_send_msg("Guid|" + Bems_element_list[object_cnt].guid);
bems_pm_obj.sender_send_msg("Guid2|" + Bems_element_list[object_cnt].guid2);
guidNumber = Bems_element_list[object_cnt].guid;
bems_pm_obj.sender_send_msg("PresentValue|" + Bems_element_list[object_cnt].bems_object.present_value);
// 2014.11.20 hwjang start BinaryStatic ==> BinaryObject전체로 변경
// 2016.01.18 hwjang start BinaryStateText객체 추가
if (Bems_element_list[object_cnt].base_type == "BinaryStatic" || Bems_element_list[object_cnt].base_type == "NewBinaryStatic" ||
Bems_element_list[object_cnt].base_type == "BinaryDynamic" || Bems_element_list[object_cnt].base_type == "NewBinaryDynamic" ||
Bems_element_list[object_cnt].base_type == "BinaryStateText") {
// 2016.01.18 hwjang end BinaryStateText객체 추가
if (Bems_element_list[object_cnt].bems_object.in_active_text != null && Bems_element_list[object_cnt].bems_object.in_active_text != "")
bems_pm_obj.sender_send_msg("InActiveText|" + Bems_element_list[object_cnt].bems_object.in_active_text);
if (Bems_element_list[object_cnt].bems_object.active_text != null && Bems_element_list[object_cnt].bems_object.active_text != "")
bems_pm_obj.sender_send_msg("ActiveText|"+Bems_element_list[object_cnt].bems_object.active_text);
}
// 2014.11.20 hwjang start max_value, min_value, unit추가
// 2015.03.19 hwjang start "General" Type 정보 추가
if (Bems_element_list[object_cnt].base_type == "AnalogStatic" || Bems_element_list[object_cnt].base_type == "ValueStatic" ||
Bems_element_list[object_cnt].base_type == "NewAnalogStatic" || Bems_element_list[object_cnt].base_type == "General") {
bems_pm_obj.sender_send_msg("MaxValue|" + Bems_element_list[object_cnt].bems_object.max_value);
bems_pm_obj.sender_send_msg("MinValue|" + Bems_element_list[object_cnt].bems_object.min_value);
bems_pm_obj.sender_send_msg("Unit|" + Bems_element_list[object_cnt].bems_object.unit);
}
// 2015.03.19 hwjang end "General" Type 정보 추가
// 2014.11.20 hwjang end max_value, min_value, unit추가
// 2014.12.10 hwjang start stateText, NumberOfStates, StateNo 추가
if (Bems_element_list[object_cnt].base_type == "MultiStateText") {
bems_pm_obj.sender_send_msg("StateText|" + Bems_element_list[object_cnt].bems_object.StateText);
bems_pm_obj.sender_send_msg("NumberOfStates|" + Bems_element_list[object_cnt].bems_object.NumberOfStates);
bems_pm_obj.sender_send_msg("StateNo|" + Bems_element_list[object_cnt].bems_object.present_value);
}
// 2014.12.10 hwjang end stateText, NumberOfStates, StateNo 추가
return;
}
// popup_analog/popup_binary/popup_multistate화면에서 확인_적용 버튼 선택시 수행
// 2014.12.22 hwjang start AreaID추가
// 2014.12.30 hwjang start 주소체계 변경 (WebCCMS와 통일)
var strDevicePos = n_indexOf(event.data, ".", 2);
// 2014.12.30 hwjang endt 주소체계 변경 (WebCCMS와 통일)
// 2014.12.22 hwjang end AreaID추가
// 2014.12.17 hwjang start AreaID 추가
// 2015.04.03 hwjang start websock_areaID[index]와 AreaID 관련성 확인
if (socketFlag[socketIndex_AreaID] == true && socket[socketIndex_AreaID].readyState == WebSocket.OPEN) {
// 2015.12.04 hwjang start 로그인정보 추가
socket[socketIndex_AreaID].send("3publish|" + event.data.substr(strDevicePos + 1) + "|" + userId);
// 2015.12.04 hwjang end 로그인정보 추가
console.log("send: ", "AreaID:" + setting.server.websock_areaID[socketIndex_AreaID] + " , " + event.data.substr(strDevicePos + 1) + ",userId="+userId);
}
// 2015.04.03 hwjang end websock_areaID[index]와 AreaID 관련성 확인
// 2014.12.17 hwjang end AreaID 추가
// 2014.12.05 hwjang start // 처리함.
//bems_operation(msg_data[0], msg_data[1]);
// 2014.12.05 hwjang end // 처리함.
}
Bems_postmessage.prototype = {
// 메시지 송신 후처리
// 2014.12.22 hwjang start 메시지에 guid2 추가
set_sender_postmessage: function(i, areaID, guid2){
// 2014.12.22 hwjang end 메시지에 guid2 추가
pm_domain_url = this.domain_url;
object_cnt = i;
// 2014.12.17 hwjang start AreaID 추가
// 2015.04.03 hwjang start websock_areaID[index]와 AreaID 관련성 확인
socketIndex_AreaID = -1;
for (var j = 0; j < setting.server.websock_server.length; j++) {
if (areaID == setting.server.websock_areaID[j]) {
socketIndex_AreaID = j;
break;
}
}
// 2015.04.03 hwjang end websock_areaID[index]와 AreaID 관련성 확인
// 2014.12.17 hwjang end AreaID 추가
// 2014.12.22 hwjang start 메시지에 guid2 추가
Guid2 = guid2;
// 2014.12.22 hwjang end 메시지에 guid2 추가
window.addEventListener('message',receiveMessage,false);
},
// 메시지수신 후처리(1. 화면 로드시에 화면정보 갱신용으로 수행)
set_receiver_postmessage: function(){
pm_domain_url = this.domain_url;
window.addEventListener('message',function(event) {
console.log('message received: ', event.data);
var msg_data = event.data.split('|');
if(msg_data[0] == "Name")
$("#name").html(msg_data[1]);
else if(msg_data[0] == "Description")
$("#description").html(msg_data[1]);
else if (msg_data[0] == "Guid") {
// 2014.12.10 hwjang start guid => Address로 이름 변경
//$("#guid").html("Guid : " + msg_data[1]);
$("#guid").html(msg_data[1]);
// 2014.12.10 hwjang end guid => Address로 이름 변경
set_guid(msg_data[1]);
}
else if (msg_data[0] == "Guid2") {
$("#guid2").html(msg_data[1]);
set_guid2(msg_data[1]);
}
else if (msg_data[0] == "PresentValue") {
set_present_value(msg_data[1]);
}
else if (msg_data[0] == "ActiveText") {
$("#notify1").text(msg_data[1]);
}
else if (msg_data[0] == "InActiveText") {
$("#notify2").text(msg_data[1]);
}
// 2014.11.20 hwjang start max_value, min_value, unit추가
else if (msg_data[0] == "MaxValue") {
$("#max_value").html(msg_data[1]);
set_max_value(msg_data[1]);
}
else if (msg_data[0] == "MinValue") {
$("#min_value").html( msg_data[1]);
set_min_value(msg_data[1]);
}
else if (msg_data[0] == "Unit") {
if (msg_data[1] == "no unit")
$("#unit").html("");
else
$("#unit").html(msg_data[1]);
set_unit(msg_data[1]);
}
// 2014.11.20 hwjang start max_value, min_value, unit추가
// 2014.12.10 hwjang start stateText, NumberOfStates, StateNo 추가
else if (msg_data[0] == "StateText") {
//alert(msg_data[1]);
var strArray = msg_data[1].split(",");
//alert(strArray.length);
var strText = "";
for (var i = 0; i < strArray.length; i++) {
strText += "<option>" + strArray[i] + "</option>";
}
$("#stateText").html(strText);
set_state_text(msg_data[1]);
}
else if (msg_data[0] == "NumberOfStates") {
$("#NumberOfStates").val(msg_data[1]);
set_number_of_states(msg_data[1]);
}
else if (msg_data[0] == "StateNo") {
$("#StateNo").val(msg_data[1]);
set_state_no(msg_data[1]);
}
// 2014.12.10 hwjang end stateText, NumberOfStates, StateNo 추가
else
sender_guid = msg_data[0];
},false);
},
// 송신측 메시지 송신(개별속성 송신)
sender_send_msg: function (message) {
this.window_popup.postMessage(message, this.domain_url);
},
// 수신측 메시지 송신 (2. 화면 load시, 확인/적용시)
receiver_send_msg: function(message){
console.log('receiver_send_msg ', message);
// 2014.12.05 hwjang start Guid 변경 (Device ID 제외)
//// 2014.12.22 hwjang strat GUID에서 AreaID,Network ID 제외
//window.opener.postMessage(Guid2 + "|" + message, this.domain_url);
//var strDevicePos = n_indexOf(sender_guid, ":", 2);
//window.opener.postMessage(sender_guid.substr(strDevicePos + 1) + "|" + message, this.domain_url);
//var strDevicePos = sender_guid.indexOf(":");
//console.log("receive_send_msg", strDevicePos + ":" + sender_guid.substr(strDevicePos + 1));
window.opener.postMessage(sender_guid + "|" + message, this.domain_url);
//window.opener.postMessage(sender_guid.substr(strDevicePos + 1) + "|" + message, this.domain_url);
//// 2014.12.22 hwjang end GUID에서 AreaID,Network ID 제외
// 2014.12.05 hwjang end Guid 변경 (Device ID 제외)
},
// 2016.07.12 hwjang start Browser 크기 속성 추가
create_popup: function (obj_type, url, popX2, popY2, obj_guid) {
obj_guid = typeof obj_guid !== 'undefined' ? obj_guid : "";
var popX = (1920 / document.body.clientWidth) * 390;
var popY = (1080 / document.body.clientHeight) * 200;
popX = 410;
popY = 280; //popY = 220;
// 2016.01.04 hwjang start 제어창 시작위치을 중간으로 변경 설정
LeftPosition = (screen.width - popX) / 2;
TopPosition = (screen.height - popY) / 2;
// 2016.01.04 hwjang end 제어창 시작위치을 중간으로 변경 설정
//alert(popX);
//alert(popY);
// 2016.01.18 hwjang start BinaryStateText객체 추가
if (obj_type == "BinaryStatic" || obj_type == "BinaryAnalog" || obj_type == "BinaryDynamic" || obj_type == "NewBinaryDynamic" || obj_type == "NewBinaryStatic" || obj_type == "BinaryStateText")
// 2016.01.18 hwjang end BinaryStateText객체 추가
// 2014.12.24 hwjang start 웹브라우저 주소를 자체적으로 읽어들이기
this.window_popup = window.open(this.domain_url + "/popup_binary.html", obj_guid, "width=" + popX + ",height=" + popY + ", resizable=yes,location=no,titlebar=no" + ",left=" + LeftPosition + ", top=" + TopPosition);
// 2014.12.24 hwjang end 웹브라우저 주소를 자체적으로 읽어들이기
// 2015.03.19 hwjang start "General" Type 정보 추가
else if (obj_type == "AnalogStatic" || obj_type == "ValueStatic" || obj_type == "NewAnalogStatic")
// 2015.03.19 hwjang end "General" Type 정보 추가
// 2014.12.24 hwjang start 웹브라우저 주소를 자체적으로 읽어들이기
this.window_popup = window.open(this.domain_url + "/popup_analog.html", obj_guid, "width=" + popX + ",height=" + popY + ", resizable=yes,location=no,titlebar=no" + ",left=" + LeftPosition + ", top=" + TopPosition);
// 2014.12.24 hwjang end 웹브라우저 주소를 자체적으로 읽어들이기
else if (obj_type == "MultiStateText")
// 2014.12.24 hwjang start 웹브라우저 주소를 자체적으로 읽어들이기
this.window_popup = window.open(this.domain_url + "/popup_multistate.html", obj_guid, "width=" + popX + ",height=" + popY + ", resizable=yes,location=no,titlebar=no" + ",left=" + LeftPosition + ", top=" + TopPosition);
// 2014.12.24 hwjang end 웹브라우저 주소를 자체적으로 읽어들이기
else if (obj_type == "General")
// 2014.12.24 hwjang start 웹브라우저 주소를 자체적으로 읽어들이기
this.window_popup = window.open(this.domain_url + "/popup_general.html", obj_guid, "width=" + popX + ",height=" + popY + ", resizable=yes,location=no,titlebar=no" + ",left=" + LeftPosition + ", top=" + TopPosition);
// 2014.12.24 hwjang end 웹브라우저 주소를 자체적으로 읽어들이기
else if (obj_type == "LabelLink") {
docWidth = $(window).width();
docHeight = $(window).height();
LeftPosition = screenX + ((docWidth - popX2) / 2);
TopPosition = screenY + ((docHeight - popY2) / 2);
// 2016.01.12 hwjang start LabelLink관련 로그인정보 포함 - 2018.05.09 djkim: 살려서 테스트
var popupName = url;
url += "?GUID=" + strGUID + "&GraphicControl=" + GraphicControl + "&GraphicAuth=" + GraphicAuth + "&userId=" + userId;
// 2016.01.12 hwjang end LabelLink관련 로그인정보 포함
this.window_popup = window.open(url, popupName, "width=" + popX2 + ",height=" + popY2 + ", resizable=yes,location=no,titlebar=no" + ",left=" + LeftPosition + ", top=" + TopPosition);
}
//this.window_popup.focus();
},
// 2016.07.12 hwjang end Browser 크기 속성 추가
// 2017.08.07 djkim: PopupTemplate 처리 추가
create_popup_new: function (obj_type, url, popX2, popY2, jsonRecipe, popup_title) { // 2017.10.18 djkim: 팝업창 Title 설정 추가
docWidth = $(window).width();
docHeight = $(window).height();
var LeftPosition = screenX + ((docWidth - popX2) / 2);
var TopPosition = screenY + ((docHeight - popY2) / 2);
//jsonRecipe['Title'] = popup_title; // 2017.10.18 djkim: 팝업창 Title 설정 추가
jsonRecipe.Title = popup_title; // 2017.10.18 djkim: 팝업창 Title 설정 추가
var jsonString = JSON.stringify(jsonRecipe);
// 2018.05.11 djkim: 팝업창에서 제어가 가능하도록 여러 개의 Popup 띄우기 - URL 이름으로 Popup을 구분 (Overwrite 현상 방지)
var popupName = url;
url += "?GUID=" + strGUID + "&GraphicControl=" + GraphicControl + "&GraphicAuth=" + GraphicAuth + "&userId=" + userId;
this.window_popup = window.open(url, popupName, "width=" + popX2 + ",height=" + popY2 + ", resizable=yes,location=no,titlebar=no" + ",left=" + LeftPosition + ", top=" + TopPosition);
this.window_popup.focus();
this.window_popup.addEventListener('message',jsonReceive,false);
this.window_popup.postMessage(jsonString, this.domain_url);
//this.window_popup.postMessage(jsonString, this.domain_url + "/" + this.popup_name + ".html");
//this.window_popup.onload = function () {
// this.addEventListener('message',jsonReceive,false);
// this.postMessage(jsonString, this.domain_url);
// jsonStr = jsonString;
// jsonData = JSON.parse(jsonString);
//}
}
};
function jsonReceive(event)
{
//if(event.origin !== pm_domain_url) return;
console.log('received json: ',event.data);
var strEvent = event.data;
if (strEvent.indexOf("{") != -1 && strEvent.indexOf("}") != -1) {
var eventObject = JSON.parse(strEvent);
//var strDevicePos = n_indexOf(event.data, ".", 2);
jsonData = eventObject;
jsonStr = strEvent;
console.log(jsonStr);
console.log(jsonData);
}
window.removeEventListener("message", jsonReceive, false);
}
|
/* eslint-env node,browser,amd */
//
// SaltThePass - DomainNameRule
//
// Copyright 2013 Nic Jansma
// http://nicj.net
//
// https://github.com/nicjansma/saltthepass.js
//
// Licensed under the MIT license
//
(function(root, factory) {
"use strict";
if (typeof define === "function" && define.amd) {
// AMD. Register as an anonymous module.
define(["./utils"], factory);
} else if (typeof exports === "object") {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like enviroments that support module.exports,
// like Node.
module.exports = factory(require("./utils"));
} else {
// Browser globals (root is window)
root.DomainNameRule = factory(root.SaltThePassUtils);
}
}(this, function(utils) {
"use strict";
//
// Constructor
//
/**
* Creates a new DomainNameRule
*
* @param {object} data Parameters
*/
function DomainNameRule(data) {
if (typeof (data) === "undefined") {
return;
}
//
// matches
//
this.domain = data.domain;
if (data.aliases instanceof Array) {
this.aliases = data.aliases.slice();
} else {
this.aliases = [];
}
// description (versions)
this.description = data.description;
//
// rules
//
this.min = (typeof data.min !== "undefined") ? (parseInt(data.min, 10) || 0) : 0;
this.max = (typeof data.max !== "undefined") ? (parseInt(data.max, 10) || Number.MAX_VALUE) : Number.MAX_VALUE;
this.invalid = (typeof data.invalid !== "undefined") ? data.invalid : "";
this.required = (typeof data.required !== "undefined") ? data.required : "";
this.regex = data.regex;
this.validregex = data.validregex;
}
/**
* Determines if the domain has a minimum number of characters
*
* @returns {boolean} True if there is a minimum number of characters
*/
DomainNameRule.prototype.hasMin = function() {
return this.min !== 0;
};
/**
* Determines if the domain has a maximum number of characters
*
* @returns {boolean} True if the domain has a maximum number of characters
*/
DomainNameRule.prototype.hasMax = function() {
return this.max !== Number.MAX_VALUE;
};
/**
* Determines if the domain has specific required characters
*
* @returns {boolean} True if the domain has specific required characters
*/
DomainNameRule.prototype.hasRequired = function() {
return this.required.length !== 0;
};
/**
* Determines if the domain has a list of invalid characters
*
* @returns {boolean} True if the domain has a list of invalid characters
*/
DomainNameRule.prototype.hasInvalid = function() {
return this.invalid.length !== 0;
};
/**
* Determines if the domain has a regular expression that must match
*
* @returns {boolean} True if the domain has a regular expression that must match
*/
DomainNameRule.prototype.hasRegex = function() {
return typeof this.regex !== "undefined";
};
/**
* Determines if the domain has a regular expression of valid characters
*
* @returns {boolean} True if the domain has a regular expression of valid characters
*/
DomainNameRule.prototype.hasValidRegex = function() {
return typeof this.validregex !== "undefined";
};
/**
* Determines if the specified domain matches this rule's domain
* or one of its aliases.
*
* @param {string} domain Domain to check
*
* @returns {boolean} True if the domain matches
*/
DomainNameRule.prototype.matches = function(domain) {
// standardize first
var dom = utils.standardizeDomain(domain);
// check primary domain
if (dom === this.domain) {
return true;
}
// check aliases
for (var i = 0; i < this.aliases.length; i++) {
var alias = this.aliases[i];
if (alias === dom) {
return true;
}
}
return false;
};
/**
* Determines if the password matches the domain's
* rules.
*
* @param {string} password Password
*
* @returns {boolean} True if the password matches the domain's rules
*/
DomainNameRule.prototype.isValid = function(password) {
if (!this.isValidMin(password)) {
return false;
}
if (!this.isValidMax(password)) {
return false;
}
if (!this.isValidRequired(password)) {
return false;
}
if (!this.isValidInvalid(password)) {
return false;
}
if (!this.isValidRegex(password)) {
return false;
}
if (!this.isValidValidRegex(password)) {
return false;
}
return true;
};
/**
* Determines if the password passes this rule's minimum number of characters
*
* @param {string} password Password
*
* @returns {boolean} True if the password passes this rule's minimum number of characters
*/
DomainNameRule.prototype.isValidMin = function(password) {
return (password.length >= this.min);
};
/**
* Determines if the password passes this rule's maximum number of characters
*
* @param {string} password Password
*
* @returns {boolean} True if the password passes this rule's maximum number of characters
*/
DomainNameRule.prototype.isValidMax = function(password) {
return (password.length <= this.max);
};
/**
* Determines if the password passes this rule's required characters
*
* @param {string} password Password
*
* @returns {boolean} True if the password passes this rule's required characters
*/
DomainNameRule.prototype.isValidRequired = function(password) {
if (this.required.length === 0) {
return true;
}
var foundMatch = false;
for (var i = 0; i < this.required.length; i++) {
if (password.indexOf(this.required[i]) !== -1) {
foundMatch = true;
break;
}
}
if (this.required.length > 0 && !foundMatch) {
return false;
}
return true;
};
/**
* Determines if the password passes this rule's invalid characters list
*
* @param {string} password Password
*
* @returns {boolean} True if the password passes this rule's invalid characters list
*/
DomainNameRule.prototype.isValidInvalid = function(password) {
if (this.invalid.length === 0) {
return true;
}
for (var i = 0; i < this.invalid.length; i++) {
if (password.indexOf(this.invalid[i]) !== -1) {
return false;
}
}
return true;
};
/**
* Determines if the password passes this rule's regular expression
*
* @param {string} password Password
*
* @returns {boolean} True if the password passes this rule's regular expression
*/
DomainNameRule.prototype.isValidRegex = function(password) {
if (this.regex) {
var reg = this.getRegEx();
if (!reg.test(password)) {
return false;
}
}
return true;
};
/**
* Determines if the password passes this rule's valid characters regular expression
*
* @param {string} password Password
*
* @returns {boolean} True if the password passes this rule's valid characters regular expression
*/
DomainNameRule.prototype.isValidValidRegex = function(password) {
if (this.validregex) {
var reg = this.getValidRegEx();
if (!reg.test(password)) {
return false;
}
}
return true;
};
/**
* Gets this rule's regular expression
*
* @returns {RegExp} Regular expression
*/
DomainNameRule.prototype.getRegEx = function() {
if (!this.regex) {
return;
}
return new RegExp(this.regex);
};
/**
* Gets this rule's regular expression
*
* @param {boolean} reverse If set, return an inverse of the regular expression
*
* @returns {RegExp} Regular expression
*/
DomainNameRule.prototype.getValidRegEx = function(reverse) {
if (!this.validregex) {
return;
}
if (reverse) {
return new RegExp("[^" + this.validregex + "]", "g");
}
return new RegExp("^[" + this.validregex + "]+$");
};
/**
* Attemps to rewrite the password to match this domain's rules.
*
* @param {string} password Input password
*
* @returns {string|undefined} Rewritten password (if possible), or undefined it it could not be
*/
DomainNameRule.prototype.rewrite = function(password) {
// if it's already valid, return it
if (this.isValid(password)) {
return password;
}
var newPass = password;
// remove invalid characters
for (var i = 0; i < this.invalid.length; i++) {
var index = -1;
var invalidChar = this.invalid[i];
while ((index = newPass.indexOf(invalidChar)) !== -1) {
newPass = newPass.substr(0, index) + newPass.substr(index + 1);
}
}
// if we have a valid characters regex, remove invalid characters from it
if (this.validregex) {
var reg = this.getValidRegEx();
if (!reg.test(newPass)) {
var nonRegEx = this.getValidRegEx(true);
newPass = newPass.replace(nonRegEx, "");
}
}
// trims, adds a required character if needed, then trims again.
newPass = this.trimToMax(newPass);
newPass = this.addRequiredChar(newPass);
newPass = this.trimToMax(newPass);
// make sure we're still valid
if (!this.isValid(newPass)) {
return;
}
return newPass;
};
/**
* Trims a password to its maximum length for this rule
*
* @param {string} password Password
*
* @returns {string} Trimmed password
*/
DomainNameRule.prototype.trimToMax = function(password) {
var newPass = password;
// trim to max
if (newPass.length > this.max) {
newPass = newPass.substr(0, this.max);
}
return newPass;
};
/**
* Adds a required character to a password if needed.
*
* @param {string} password Password
*
* @returns {string} Password with at least one required character
*/
DomainNameRule.prototype.addRequiredChar = function(password) {
var newPass = password;
if (this.required.length === 0) {
return newPass;
}
// ensure there's at least one required character
var foundMatch = false;
for (var i = 0; i < this.required.length; i++) {
if (newPass.indexOf(this.required[i]) !== -1) {
foundMatch = true;
break;
}
}
if (this.required.length > 0 && !foundMatch) {
// add the first required character
var reqChar = this.required[0];
// to the beginning of the string (since we trim the end)
newPass = reqChar + newPass;
}
return newPass;
};
// export
return DomainNameRule;
}));
|
import users from "./User/routes";
import posts from "./Post/routes";
import express from "express";
import bodyParser from "body-parser";
import { createJWToken } from "./libs/auth";
import allowCrossDomain from "./middleware/node-express-cors-middleware";
import MyLogger from "./middleWare/myLogger";
import axios from "axios";
const routes = express.Router();
routes.use(MyLogger);
routes.use(allowCrossDomain);
routes.use(bodyParser.json());
routes.use(bodyParser.urlencoded({ extended: true }));
routes.post("/api/v1/login", (req, res) => {
let { email, password } = req.body;
if (email === "toto" && password === "toto") {
res.status(200).json({
success: true,
token: createJWToken({
sessionData: { name: "toto", age: 15 },
maxAge: 3600
})
});
} else {
res.status(401).json({
message: "Login ou mot de passe incorrecte."
});
}
});
routes.get("/api/v1/test-nock", (req, res) => {
axios.get("https://api.github.com/repos/atom/atom/license").then(
t => {
res.send({ license: t.data.license });
},
err => res.send(t)
);
});
routes.use("/api/v1", posts);
routes.use("/api/v1", users);
routes.get("/", (req, res) => {
res.status(200).json({ message: "Connected!" });
});
module.exports = routes;
|
import React from 'react';
// 引入路由
import { NavLink } from 'react-router-dom';
// 引入icon-font
import '../../style/iconfont/iconfont.css';
// 引入样式
import './style.scss';
const tabData = [
{ id: 0, title: 'goods', icon: 'iconfont icon-good', path: '/good' },
{ id: 1, title: 'home', icon: 'iconfont icon-home', path: '/home' },
{ id: 2, title: 'mine', icon: 'iconfont icon-account', path: '/mine' },
];
export default function Tab() {
return (
<nav className='tabs'>
{tabData.map((item) => {
return (
<NavLink className='tab' key={item.id} to={item.path}>
<span className={item.icon}></span>
<span className='text'> {item.title} </span>
</NavLink>
);
})}
</nav>
);
}
|
const express = require('express');
const router = express.Router();
const items_controller = require('../controllers/items.controller');
// get items
router.get('/', items_controller.items_all);
// find item by id
router.get('/:id', items_controller.item_details);
module.exports = router;
|
import { exists, window } from "browser-monads"
import { navigate } from "gatsby"
import React from "react"
import { getCurrentUser, isLoggedIn } from "../../utils/auth"
export default ({ component: Component, ...rest }) => {
if (exists(window) && !isLoggedIn()) {
navigate(`/auth`)
}
const user = getCurrentUser()
if (!user.roles.includes("admin")) {
navigate(`/user/profile`)
}
return isLoggedIn() && user.roles.includes("admin") ? (
<Component {...rest} />
) : null
}
|
"use strict";
var ugly = require('uglify-js');
var path = require('path');
var content = require('../lib/content');
var relativePaths = require('./js.files.json');
var pub = path.join(__dirname, '..', 'public', 'js');
var scriptsDir = path.join(__dirname, 'js');
module.exports.getDevSripts = function getDevScripts() {
var scripts = [];
relativePaths.forEach(function (relativePath) {
scripts.push({ relative: '/js/' + relativePath, absolute: path.join(scriptsDir, relativePath) });
});
return scripts;
};
module.exports.getProductionScript = function getProductionScript() {
var scripts = [];
var absFiles = [];
var outputFile = path.join('site-' + Date.now() + '-.js');
var outputFileAbs = path.join(pub, outputFile);
//Get absolute path to files
relativePaths.forEach(function (relativePath) {
absFiles.push(path.join(scriptsDir, relativePath));
});
//Create bundle
var bundle = ugly.minify(absFiles);
var code = bundle.code.toString();
//Save plain & gzip
content.save(outputFileAbs, code);
content.gzipSaveString(outputFileAbs, code);
scripts.push({ relative: '/js/' + outputFile, absolute: outputFileAbs });
return scripts;
};
|
import React from "react";
import { BrowserRouter, Switch, Route, Link } from "react-router-dom";
import axios from "axios";
import "./App.css";
import { makeStyles } from '@material-ui/core/styles';
import Button from '@material-ui/core/Button';
import { AdminAuthContextProvider } from "./AdminComponents/AdminAuthContext";
import { UserAuthContextProvider } from "./UserComponents/UserAuthContext"
import AdminRouter from "./AdminComponents/AdminRouter.js";
import UserRouter from "./UserComponents/UserRouter.js";
axios.defaults.withCredentials = true;
const useStyles = makeStyles((theme) => ({
margin: {
margin: theme.spacing(1),
},
extendedIcon: {
marginRight: theme.spacing(1),
},
}));
export default function App() {
const classes = useStyles();
return (
<BrowserRouter>
<Switch>
<Route exact path="/">
<div class="flex">
<Button variant="outlined" size="large" color="primary" className={classes.margin} component={Link} to="/user">
User Portal
</Button>
<Button variant="outlined" size="large" color="primary" className={classes.margin} component={Link} to="/admin">
Admin Portal
</Button>
</div>
</Route>
<Route path="/user">
<UserAuthContextProvider>
<UserRouter />
</UserAuthContextProvider>
</Route>
<Route path="/admin">
<AdminAuthContextProvider>
<AdminRouter />
</AdminAuthContextProvider>
</Route>
</Switch>
</BrowserRouter>
);
}
|
import React from "react";
// core components
import Paper from "@material-ui/core/Paper";
import InputAdornment from "@material-ui/core/InputAdornment";
import Email from "@material-ui/icons/Email";
import Button from "../../../components/CustomButtons/Button";
import CustomInput from "../../../components/CustomInput/CustomInput";
class SubscribeCard extends React.Component {
state = {};
render() {
const { classes } = this.props;
return (
<Paper className={classes.paper} elevation={4}>
<h4 style={{ textAlign: "center" }}>
Subscribe To Newsletter
</h4>
<Paper className={classes.innerPaper} square={false} elevation={0}>
<CustomInput
labelText="Email Address"
id="subscribe"
formControlProps={{
fullWidth: true,
}}
inputProps={{
endAdornment: (<InputAdornment position="start">
<Email />
</InputAdornment>),
}}
/>
<Button round color="primary" style={{ margin: "20px auto", display: "block" }}>
Subscribe
</Button>
</Paper>
</Paper>
);
}
}
export default (SubscribeCard);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.