text
stringlengths 7
3.69M
|
|---|
import React, {Component} from 'react';
import {connect} from 'react-redux';
import * as actions from './../Demo-Redux/Actions/Actions';
class TaskForm extends Component{
constructor(props){
super(props);
this.state={}
}
UNSAFE_componentWillMount(){
if(this.props.itemEditting){
this.setState({
id : this.props.itemEditting.id,
name : this.props.itemEditting.name,
status : this.props.itemEditting.status
});
}
}
UNSAFE_componentWillReceiveProps(nextProps){
if(nextProps && nextProps.itemEditting){
this.setState({
id : nextProps.itemEditting.id,
name : nextProps.itemEditting.name,
status : nextProps.itemEditting.status
});
}else if(!nextProps.itemEditting){
this.setState({
id:'',
name : '',
status : true
});
}
}
onChange = (event) => {
var target = event.target;
var name = target.name;
var value = target.value;
if(name === 'status'){
value = target.value === 'true' ? true : false;
}
this.setState({
[name] : value
})
}
onSubmit = (event) => {
event.preventDefault();
this.props.onAddTask(this.state);
this.onClear();
this.onExitForm();
}
onExitForm = () => {
this.props.onCLoseFormm();
}
onClear = () => {
this.setState({
name : '',
status : false
});
}
render(){
var {displayform} = this.props;
var {id} = this.state;
if(!displayform) return null;
return (
<div>
<div className="card">
<div className="card-body">
<form onSubmit = {this.onSubmit}>
<div className="form-row">
<div className="form-group col-md-12">
<h5>{ id !== '' ? 'Cập nhật công việc' : 'Thêm công việc'}
<span className="fas fa-times-circle text-right" onClick = {this.onExitForm}></span>
</h5>
<label>Tên công việc</label>
<input type="text"
className="form-control"
name = "name"
value = {this.state.name}
onChange = {this.onChange}/><br/>
<label>Trạng thái</label>
<select className="custom-select custom-select-sm"
name = "status"
value = {this.state.status}
onChange = {this.onChange}>
<option defaultValue>Trạng thái</option>
<option value={false}>Kích hoạt</option>
<option value={true}>Ẩn</option>
</select><hr/>
<div className="text-center">
<button type="submit" className="btn btn-warning btn-sm">
<span className="fas fa-plus"></span> Lưu lại
</button>
<button type="button" className="btn btn-danger btn-sm" onClick={this.onClear}>
<span className="fas fa-window-close" ></span> Hủy Bỏ
</button>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
);
}
}
const mapStatetoProps = (state) => {
return {
tasks : state.tasks,
displayform : state.displayform,
itemEditting : state.settingstask
}
}
const mapDispatchtoProps = (dispatch, props) => {
return {
onAddTask : (task) => {
dispatch(actions.addtask(task));
},
onCLoseFormm : () => {
dispatch(actions.closeform());
}
}
};
export default connect(mapStatetoProps, mapDispatchtoProps)(TaskForm);
|
Ext.ns("App");
Ext.ns("Ext.app");
App.init = function() {
Ext.QuickTips.init();// 这句为表单验证必需的代码
Ext.BLANK_IMAGE_URL = __ctxPath + '/commons/scripts/ext/resources/images/default/s.gif';
var frameContent = null;
var cookies = Ext.util.Cookies;
var pWidth = cookies.get('pWidth');
var pHeight = cookies.get('pHeight');
var certainSize = /[0-9_]/i.test(pWidth) && /[0-9_]/i.test(pHeight);
var pWidth = certainSize ? pWidth : (Ext.lib.Dom.getViewWidth(true)<980?980:Ext.lib.Dom.getViewWidth(true));
var pHeight = certainSize ? pHeight : (Ext.lib.Dom.getViewHeight(true)<600?600:Ext.lib.Dom.getViewHeight(true));
var flagW = document.body.clientWidth>980;
var flagH = document.body.clientHeight>600;
if(flagW && flagH){
document.body.style.overflowX = 'hidden';
document.body.style.overflowY = 'hidden';
}
var viewW = pWidth;
var treePanelW = 180;
var frmPanelW = viewW - treePanelW-7;
var frmContentW = viewW - treePanelW-8;
var panW = pWidth - treePanelW;
Ext.get("content").setWidth(viewW);
var viewH = pHeight;
var frmPanelH = viewH - 62;
var frmContentH = viewH - 62;
var treePanelH = viewH - 62;
Ext.get("content").setHeight(viewH);
var frmPanel = new Ext.Panel({
id : 'frmPanel',
margin : 0,
split : true,
region : 'center',
border : false,
frame : false,
autoScroll: false,
html : String.format('<img width="{0}px" height="{1}px" src="' + __ctxPath
+ '/commons/images/welcome.jpg"></img>',
frmContentW, frmContentH)
});
// var pos = '当前位置:';
// var treeLoader = new Ext.tree.TreeLoader({
// dataUrl : 'treeJson.json',
// listeners:{
// load:function(){
// treeRootNode.eachChild(function(node){
// if(node.hasChildNodes()){
// node.getUI().getIconEl().src=__ctxPath + '/commons/images/parentNode.png';
// node.eachChild(function(leafNode){
// if(leafNode.isLeaf()){
// leafNode.getUI().getIconEl().src=__ctxPath + '/common/images/leafNode.png';
// }
//
// },this);
//
// }
// },this);
// }
// }
// });
// var treeRootNode = new Ext.tree.AsyncTreeNode({
//
// });
// var treePanel = new Ext.tree.TreePanel({
// id : 'treepanel',
// baseCls : 'mainLeftTree',
// region : 'west',
// bodyStyle:'padding-top:20px;',
// width : treePanelW,
// height : treePanelH,
// header : false,
//// useArrows : true,
// autoScroll : true,
// monitorResize : true,
// lines : false,
// border : false,
// rootVisible : false,
// trackMouseOver : true,
// loader : treeLoader,
// root : treeRootNode,
// listeners : {
// 'click' : function(node, event, root) {
// if (node.leaf) {
// frmPanel.load({
// url : node.attributes.value,
// callback : function() {
// },
// scripts : true
// })
// var temp = node.text;
// while (node.parentNode.text) {
// temp = node.parentNode.text + ' > ' + temp;
// node = node.parentNode;
// }
// pos += temp;
// Ext.getCmp('userpos').setText(pos);
// pos = '当前位置:';
// } else if (!node.leaf) {
// node.parentNode.collapseChildNodes();
// node.expand();
// }
// }
// }
//
// });
// treePanel.expandAll();
// var treePanel = new Ext.Panel( {
// id : 'treepanel',
// baseCls : 'mainLeftTree',
// header : false,
// autoScroll : true,
// html : '<ul class="container"></ul>',
// region : 'west',
// layout : 'accordion',
// split : true,
// width : treePanelW,
// height : treePanelH,
// minSize : 180,
// maxSize : 200,
// margins : '0 0 0 2'
// });
// var bannerPanel = new Ext.Panel({
// width : pWidth,
// height : 68,
// renderTo : 'banner',
// id : 'bannerPanel',
// margin : 0,
// region : 'north',
// layout : 'fit',
// border : false,
// frame : false,
// defaults : {
// autoScroll : true
// },
// html : String.format('<img align="center" width="{0}px" height="{1}px" src="' + __ctxPath
// + '/common/images/banner.png"></img>',
// viewW, 68)
//
// });
new Ext.Panel({
renderTo : 'content',
width : viewW,
height : viewH,
margins : 0,
layout : 'border',
//autoScroll : false,
//bodyStyle : 'overflow-x:auto; overflow-y:auto',
items : [
{
region : 'north',
border : false,
html : '<div id="banner">' +
'<span style="float:left; margin:13px 0 0 40px;">' +
' <a style="font-size:32px; font-family:微软雅黑; color:#FFF;">河南跨境贸易服务系统</a>' +
'</span>' +
'<span style="position:absolute; bottom:6px; right:25px; font-family:微软雅黑; color:#FFF; font-size:15px;">' +
' <a id="username" style="font-size:15px; float:left;">您好,'+ userName +'</a>' +
' <a id="change" style="float:left; cursor:pointer; margin-left:20px; height:20px;" ' +
' onMouseOver="this.style.color=\'yellow\'" onMouseOut="this.style.color=\'white\'"' +
' onClick="if(ukey.checkSCAClient()){if(ukey.checkUkey()){App.ChangePasswordDialog.show();}else{alert(\'请使用ukey登陆!\')}}">' +
' <img src="commons/images/mima.png" style="float:left; margin-right:5px;">修改key密码</a>' +
' <a id="logout" style=":active:(background:#00aa00); float:left; cursor:pointer; margin-left:20px;" ' +
' onMouseOver="this.style.color=\'yellow\'" onMouseOut="this.style.color=\'white\'"' +
' onClick="if (confirm(\'是否确定退出系统?\')) { window.location = \'quit.jsp\' }">' +
//' onClick="Ext.MessageBox.confirm(\'提示\', \'是否确定退出系统?\', function(btn){if(btn==\'yes\')window.location=\'quit.jsp\'});">' +
' <img src="commons/images/tuichu.png" style="float:left; margin-right:5px;">退出系统</a>' +
'</span>' +
'</div>'
},
// treePanel,
//frmPanel,
{
id:'frmPanel',
region : 'center',
xtype:'uploadPanel',
border : false,
fileSize : 1024*10,//限制文件大小
uploadUrl : 'upload/excel',
flashUrl : 'swfupload.swf',
filePostName : 'file', //后台接收参数
fileTypes : '*.xls;*.xlsx',//可上传文件类型
postParams : {savePath:'upload\\'} //上传文件存放目录
}
]
});
function changeSize(sender) {
var expires = new Date('1/10/2999 03:05:01 PM GMT-0600');
cookies.set("pWidth", sender.pWidth, expires);
cookies.set("pHeight", sender.pHeight, expires);
cookies.set("pWidth", sender.pWidth, expires);
cookies.set("pHeight", sender.pHeight, expires);
window.location = __ctxPath + '/main.jsp';
}
function getFrameContent() {
if (frameContent == null) {
frameContent = Ext
.get(Ext.DomQuery.selectNode("iframe#frmContent"));
}
return frameContent;
}
function logout() {
if (confirm('是否确定退出系统?')) {
location.href = __ctxPath+"/security/logout";
}
}
function showUserInfo() {
userInfoForm.getForm().load({
url : 'security/loadUserInfo',
success : function(form, action) {
Ext.getCmp('customsCodeCombo')
.setValue(action.result.data.customsCode);
},
failure : function(form, action) {
Ext.Msg.alert('系统异常', "载入用户信息失败。");
}
});
userInfoWin.show();
}
window.onresize = function(){
var flagW = document.body.clientWidth>pWidth;
var flagH = document.body.clientHeight>pHeight;
if(flagW){
document.body.style.overflowX = 'hidden';
}else{
document.body.style.overflowX = 'auto';
}
if(flagH){
document.body.style.overflowY = 'hidden';
}else{
document.body.style.overflowY = 'auto';
}
}
};
|
import { getNewDeck } from '../../utility/getNewDeck';
const User = require('../../emun/user');
const Score = require('../../emun/score');
const { CardDeck } = require('../../emun/cards');
const getInitialGame = async params => {
const { name } = params;
let response = {
success: false,
code: 400,
result: {}
};
try {
// get new shuffled card deck.
const deck = getNewDeck();
const coins = 1000;
const { _id: userId, name: userName, createdTime } = await User.create({ name, coins, deck });
const { _id } = await Score.create({ userId, point: 0, user: userId });
response = {
success: true,
code: 200,
result: { userName, userId, coins, score: 0, createdTime, _id }
};
return response;
} catch (error) {
// eslint-disable-next-line no-console
console.log('getInitialGame error : ', error);
return response;
}
};
const callNewRound = async params => {
const { userId, bets } = params;
let response = {
success: false,
code: 400,
result: {}
};
try {
let { deck, coins } = await User.findById(userId);
// If card total is less than 52 dealer will shuffling new card deck.
deck = deck.length <= 52 ? getNewDeck() : deck;
coins = coins - bets;
// calling will start with 2 cards always and dealer will get 2 cards as well.
const { cards: cardList, deck: newDeck } = drawCardFromDeck(deck, 4);
const cards = getCardInfo(cardList);
const playerCards = [cards[0], cards[1]];
const dealerCards = [cards[2], cards[3]];
const { point: playerPoint } = calCardPoint(playerCards);
await User.findByIdAndUpdate(userId, { deck: newDeck, coins, dealerCards, playerCards });
response = {
success: true,
code: 200,
result: { coins, playerPoint, playerCards, dealerCards: [dealerCards[1]], totalCard: newDeck.length }
};
return response;
} catch (error) {
// eslint-disable-next-line no-console
console.log('callNewRound error : ', error);
return response;
}
};
const callHitCard = async params => {
const { userId } = params;
let response = {
success: false,
code: 400,
result: {}
};
try {
let { deck, playerCards } = await User.findById(userId);
const { cards: cardList, deck: newDeck } = drawCardFromDeck(deck, 1);
const cards = getCardInfo(cardList);
playerCards = playerCards.concat(cards);
await User.findByIdAndUpdate(userId, { deck: newDeck, playerCards });
const { point: playerPoint } = calCardPoint(playerCards);
response = {
success: true,
code: 200,
result: { cards, playerPoint, playerCards, totalCard: newDeck.length }
};
return response;
} catch (error) {
// eslint-disable-next-line no-console
console.log('callHitCard error : ', error);
return response;
}
};
const standCard = async params => {
const { userId, bets } = params;
let response = {
success: false,
code: 400,
result: {}
};
try {
let { deck, coins, dealerCards, playerCards } = await User.findById(userId);
const { winner, dealerPoint, playerPoint, currentDeck, isBlackjack, dealerCards: allDealerCards } = dealerTurn(deck, dealerCards, playerCards);
let { point: userScore } = await Score.findOne({ userId });
if (winner === 'player') {
coins += bets * 2;
userScore += bets;
await Score.findOneAndUpdate({ userId }, { point: userScore });
} else if (winner === 'push') {
coins += bets;
}
await User.findByIdAndUpdate(userId, { coins, deck: currentDeck, dealerCards: [], playerCards: [] });
response = {
success: true,
code: 200,
result: { winner, coins, score: userScore, dealerPoint, playerPoint, isBlackjack, dealerCards: allDealerCards }
};
return response;
} catch (error) {
// eslint-disable-next-line no-console
console.log('standCard error : ', error);
return response;
}
};
const getScoreTable = async () => {
let response = {
success: false,
code: 400,
result: {}
};
try {
const query = await Score.find().sort({ point: -1 }).limit(10).populate('user', 'name createdTime');
let result = [];
for (let i = 0; i < query.length; i++) {
const data = {
point: query[i].point,
name: query[i].user.name,
createdTime: query[i].user.createdTime
};
result.push(data);
}
response = {
success: true,
code: 200,
result
};
return response;
} catch (error) {
// eslint-disable-next-line no-console
console.log('getScoreTable error : ', error);
return response;
}
};
const drawCardFromDeck = (deck, amount = 1) => {
let cards = [];
let totalCard = deck.length;
for (let i = 0; i < amount; i++) {
const cardNumber = Math.floor(Math.random() * totalCard);
const card = deck[cardNumber];
deck.splice(cardNumber, 1);
totalCard = deck.length;
cards.push(card);
}
return { cards, deck };
};
const getCardInfo = cardList => {
let cards = [];
const totalCard = cardList.length;
for (let i = 0; i < totalCard; i++) {
const cardNumber = cardList[i];
const card = CardDeck[cardNumber % 52];
cards.push(card);
}
return cards;
};
const dealerTurn = (deck, dealerCards, playerCards) => {
let currentDeck = deck;
let isEndRound = false;
let isBlackjack = false;
let winner = '';
let { point: dealerPoint, isBlackjack: dealerIsBlackjack } = calCardPoint(dealerCards);
let { point: playerPoint, isBlackjack: playerIsBlackjack } = calCardPoint(playerCards);
if (playerPoint === 21 && playerIsBlackjack) {
isEndRound = true;
isBlackjack = true;
winner = 'player';
} else if (dealerPoint === 21 && dealerIsBlackjack) {
isEndRound = true;
isBlackjack = true;
winner = 'dealer';
} else if (playerPoint === 21 && dealerPoint === 21) {
isEndRound = true;
winner = 'push';
} else if (playerPoint === 21) {
isEndRound = true;
winner = 'player';
} else if (playerPoint > 21) {
isEndRound = true;
winner = 'dealer';
}
if (!isEndRound) {
while (dealerPoint < playerPoint) {
const { cards: cardList, deck: newDeck } = drawCardFromDeck(currentDeck, 1);
currentDeck = newDeck;
const cards = getCardInfo(cardList);
dealerCards = dealerCards.concat(cards);
({ point: dealerPoint } = calCardPoint(dealerCards));
}
if (dealerPoint === 21) {
isEndRound = true;
winner = 'dealer';
} else if (dealerPoint > 21) {
isEndRound = true;
winner = 'player';
} else if (dealerPoint === playerPoint) {
isEndRound = true;
winner = 'push';
} else if (dealerPoint > playerPoint) {
isEndRound = true;
winner = 'dealer';
} else if (dealerPoint > playerPoint) {
isEndRound = true;
winner = 'dealer';
}
}
return { winner, isBlackjack, dealerPoint, playerPoint, currentDeck, dealerCards };
};
const calCardPoint = cardList => {
let A_card = 0;
let point = 0;
let isBlackjack = false;
for (let i = 0; i < cardList.length; i++) {
const card = cardList[i];
if (card.name !== 'A') {
point += card.point;
} else {
A_card++;
}
}
for (let i = 0; i < A_card; i++) {
if (point + 11 > 21) {
point += 1;
} else {
point += 11;
}
}
if (cardList.length === 2 && point === 21) {
isBlackjack = true;
}
return { point, isBlackjack };
};
export default { getInitialGame, callNewRound, callHitCard, standCard, getScoreTable };
|
Package.describe({
summary: 'Use Coffee React to compile CJSX.',
version: '5.0.0',
name: 'literalsands:coffee-react',
git: 'https://github.com/literalsands/meteor-coffee-react'
});
Package.registerBuildPlugin({
name: 'compileCJSX',
use: [
'caching-compiler@1.0.4',
'ecmascript@0.4.3'
],
sources: ['compile-cjsx.js'],
npmDependencies: {
"source-map": "0.5.3",
"coffee-react": "5.0.0"
}
});
Package.onUse(function (api) {
api.use('isobuild:compiler-plugin@1.0.0');
});
|
import React from 'react';
import ListsIndexContainer from '../lists/lists_index_container';
class Sidebar extends React.Component {
constructor(props) {
super(props);
}
render () {
let { title } = this.props;
return (
<div className="sidebar">
<ListsIndexContainer />
</div>
);
}
}
export default Sidebar;
|
// getUserMedia only works over https in Chrome 47+, so we redirect to https. Also notify user if running from file.
if (window.location.protocol == "file:") {
alert("You seem to be running this example directly from a file. Note that these examples only work when served from a server or localhost due to canvas cross-domain restrictions.");
} else if (window.location.hostname !== "localhost" && window.location.protocol !== "https:"){
window.location.protocol = "https";
}
|
export default {
'set_new_minor_value': (state, value) => {
state.value -= value
},
'set_new_higher_value': (state, value) => {
state.value += value
},
}
|
import AppSection from '../molecules/AppSection';
const AppSignature = () => (
<AppSection decoration={false}>
<div className="text-center">
<p className="text-gray text-xs md:text-sm">
warm greetings from class X MIPA 5
</p>
<p className="text-gray-100">
web dev by :
</p>
<h3 className="font-signature text-xl md:text-3xl inline-block py-1 mt-3 md:mt-6 border-b border-orange">
IlhamShofa
</h3>
</div>
</AppSection>
);
export default AppSignature;
|
AngularApp.service('userService', ['$http', '$q', 'errorService', function ($http, $q, errorService) {
var errors = errorService;
var result = null;
//URL'S
var urlFetch = "users/service/getList.json";
var urlUserSave = "users/service/save";
var urlUserSearch = "users/service/search/";
var urlUserDelById = "users/service/delete/";
var urlUserDelAll = "users/service/deleteAll";
var usersListLoaded = false;
var loadingStatus = false;
var savingStatus = false;
var deletionStatus = false;
this.fetchUserList = function () {
setLoadingStatus(true);
setUsersListLoaded(false);
result = $q.defer();
$http.get(urlFetch).then(function (response) {
result.resolve(response.data);
setLoadingStatus(false);
setUsersListLoaded(true);
}, function (errorMessages) {
result.reject(errorMessages);
errors.setErrors('Could not load users list.', errorMessages.data.errors);
setLoadingStatus(false);
setUsersListLoaded(false);
});
return result.promise;
};
this.saveUser = function (user) {
setSavingStatus(true);
user = validatedUser(user);
result = $q.defer();
$http.post(urlUserSave, user).then(function (response) {
result.resolve(response.data);
setSavingStatus(false);
}, function (errorMessages) {
result.reject(errorMessages);
errors.setErrors('Could not save user.', errorMessages.data.errors);
setSavingStatus(false);
});
return result.promise;
};
this.searchUsers = function (criteria) {
setLoadingStatus(true);
setUsersListLoaded(false);
result = $q.defer();
$http.get(urlUserSearch + criteria).then(function (response) {
result.resolve(response.data);
setLoadingStatus(false);
setUsersListLoaded(true);
}, function (errorMessages) {
result.reject(errorMessages);
errors.setErrors('Could not find user with given criteria', errorMessages.data.errors);
setLoadingStatus(false);
setUsersListLoaded(false);
});
return result.promise;
};
this.deleteById = function (id) {
setDeletionStatus(true);
result = $q.defer();
$http.delete(urlUserDelById + id).then(function (response) {
result.resolve(response.data);
setDeletionStatus(false);
}, function (errorMessages) {
result.reject(errorMessages);
errors.setErrors('Could not delete user.', errorMessages.data.errors);
setDeletionStatus(false);
});
return result.promise;
};
this.deleteAll = function () {
setDeletionStatus(true);
result = $q.defer();
$http.delete(urlUserDelAll).then(function (response) {
result.resolve(response.data);
setDeletionStatus(false);
}, function (errorMessages) {
result.reject(errorMessages);
errors.setErrors('Could not delete users.', errorMessages.data.errors);
setDeletionStatus(false);
});
return result.promise;
};
var validatedUser = function (user) {
if (user.id <= 0) user.id = null;
user.firstName = user.firstName.trim();
user.lastName = user.lastName.trim();
return user;
};
this.getUsersListLoadedStatus = function () {
return usersListLoaded;
};
this.getLoadingStatus = function () {
return loadingStatus;
};
this.getSavingStatus = function () {
return savingStatus;
};
this.getDeletionStatus = function () {
return deletionStatus;
};
var setUsersListLoaded = function (value) {
usersListLoaded = value;
};
var setLoadingStatus = function (value) {
loadingStatus = value;
};
var setSavingStatus = function (value) {
savingStatus = value;
};
var setDeletionStatus = function (value) {
deletionStatus = value;
};
}]);
|
(function() {
var shown = [];
// Show tags
function updateHash() {
for(var i = 0; i < shown.length; ++i) {
shown[i].style.display = "none";
}
shown = document.getElementsByClassName("tag-" + location.hash.substr(1));
for(var i = 0; i < shown.length; ++i) {
shown[i].style.display = "";
}
}
updateHash();
addEventListener("hashchange", updateHash);
}());
|
require("dotenv").config();
const fs = require("fs")
const path = process.env.USERFILEPATH;
const filesServices = {
readFile(){
try{
let data = fs.readFileSync(path, "utf-8")
let jsonObj = JSON.parse(data.toString());
console.log(jsonObj);
return jsonObj;
}
catch(error){
console.log(error)
console.log("Error while reading file")
}
},
writeFile( data){
let updData = JSON.stringify(data);
try {
fs.writeFileSync(path, updData);
console.log("JSON obj written");
} catch (error) {
console.error(err);
}
}
}
module.exports = filesServices;
|
/* eslint-disable */
import Vue from 'vue';
import Vuex from 'vuex';
import { ROOT_API } from '../config';
Vue.use(Vuex);
const store = new Vuex.Store({
state: {
issues: [],
header: {
text: '',
disabled: false,
},
currentLink: {
target: { name: 'Index' },
disabled: true,
},
nextLink: {
target: { name: 'Index' },
disabled: true,
},
flatPages: [],
sidebar: false
},
mutations: {
SET_CURRENT_LINK(state, obj) {
state.currentLink.target = obj;
state.currentLink.disabled = false;
},
SET_NEXT_LINK(state, obj) {
state.nextLink.target = obj;
state.nextLink.disabled = false;
},
SET_ISSUES(state, arr) {
state.issues = arr;
},
SET_SITE_HEADER(state, headerStr) {
state.header.disabled = headerStr === undefined;
state.header.text = headerStr;
},
SET_FLATPAGES(state, flatPagesArray = []) {
state.flatPages = flatPagesArray;
},
OPEN_SIDEBAR(state) {
state.sidebar = true
},
CLOSE_SIDEBAR(state) {
state.sidebar = false
}
},
actions: {
setSiteHeader(context, headerStr) {
context.commit('SET_SITE_HEADER', headerStr);
},
fetchSiteStuff({ commit }) {
// todo przy wchodzeniu na dodatkowe strony wysyła dwa requesty
return new Promise((resolve) => {
const p = Vue.http.get('site', {
before() {
// abort previous request, if exists
if (this.previousRequest) {
this.request.abort();
}
// set previous request on Vue instance
// this.previousRequest = request
},
}, )
.then(response => {
return response.data},
rejected => {
console.log('Uuuuuuuuuuuu')
console.log(rejected)
})
.then((data) => {
commit('SET_FLATPAGES', data.flatpages);
commit('SET_CURRENT_LINK', data.issues.current);
commit('SET_NEXT_LINK', data.issues.next);
return data;
});
resolve(p);
});
},
getIssueById: ({ state }, issueId) => {
// eslint-disable-next-line
for (const x of state.issues) {
if (x.id === issueId) return x;
}
return null;
},
fetchCategories() {
return Vue.http.get('categories').then(response => response.data);
},
fetchIssues({ state, commit }) {
if (state.issues.length > 0) {
return new Promise(((resolve) => {
resolve(state.issues);
}));
}
return Vue.http.get('issues')
.then((response) => {
commit('SET_ISSUES', response.data);
return response;
})
.then(response => response.data.map((x) => {
x.coverUrl = ROOT_API + x.cover_url;
x.alternativeLink = x.alternative_link;
x.shortDescription = x.short_description;
x.articles.forEach((article) => {
article.belongTo = article.belong_to;
});
return x;
}));
},
fetchArticle({}, { slug, id }) {
return Vue.http.get(`articles/${slug}`)
.then(res => {
res.data.belongTo = res.data.belong_to;
return res.data
});
},
fetchAuthors() {
return Vue.http.get('authors')
.then(res => res.data)
.then(items => items.map((x) => {
x.avatar = ROOT_API + x.avatar_url;
x.shortDescription = x.short_description;
x.fullName = x.full_name;
return x;
}));
}
,
fetchEditors() {
return Vue.http.get('editors').then(res => res.data)
.then(items => items.map((x) => {
x.avatar = ROOT_API + x.avatar_url;
x.shortDescription = x.short_description;
x.fullName = x.full_name;
x.role = x.function;
return x;
}));
},
fetchColleagues() {
return Vue.http.get('colleagues').then(res => res.data)
.then(items => items.map((x) => {
x.avatar = ROOT_API + x.avatar_url;
x.shortDescription = x.short_description;
x.fullName = x.full_name;
return x;
}));
},
fetchAuthor({}, authorId) {
return Vue.http.get(`authors/${authorId}`).then((res) => {
res.data.avatar = ROOT_API + res.data.avatar_url;
return res.data;
});
},
fetchEditor({}, editorId) {
return Vue.http.get(`editors/${editorId}`).then(res => res.data);
},
fetchColleague({}, colleagueId) {
return Vue.http.get(`colleagues/${colleagueId}`).then(res => res.data);
},
async fetchArticleFilterStuff({ dispatch }) {
return {
// todo wywalic async/await
authors: await dispatch('fetchAuthors'),
issues: await dispatch('fetchIssues'),
categories: await dispatch('fetchCategories'),
};
},
fetchArticles() {
return Vue.http.get('articles')
.then(res => res.data)
.then(items => items.map((article) => {
article.belongTo = article.belong_to;
article.authors.forEach((author) => {
author.fullName = author.full_name;
});
return article
}));
},
fetchNews({}, { categorySlug, page } = { page: 1 }) {
const s = categorySlug ? { category: categorySlug, page } : { page };
if (s.page.length === 0) {
console.log('s.page. === 0', s.page)
s.page = 1;
}
return Vue.http.get(
'news', { params: s },
{
// use before callback
before() {
// abort previous request, if exists
if (this.previousRequest) {
this.request.abort();
}
// set previous request on Vue instance
// this.previousRequest = request
},
},
)
.then(res => ({
items: res.data.results,
next: res.data.next == null ? null : +page + 1,
}));
},
fetchHomePage() {
return Vue.http.get('index')
.then(res => res.data)
.then((data) => {
data.issues.current.coverUrl = ROOT_API + data.issues.current.cover_url;
data.issues.next.coverUrl = ROOT_API + data.issues.next.cover_url;
return data;
});
},
getFlatPage({ }, { pageLink }) {
return new Promise(((resolve) => {
// const el = state.flatPages.find(function (o) {
// return o.link == pageLink
// })
resolve(Vue.http.get(`flatpages/${pageLink}`)
.then(response => response.data));
}));
},
setSidebar({ commit }, value) {
value ?
commit('OPEN_SIDEBAR'):
commit('CLOSE_SIDEBAR')
},
openSidebar({ dispatch }) {
dispatch('setSidebar', true)
},
closeSidebar({ dispatch }) {
dispatch('setSidebar', false)
},
toggleSidebar({ dispatch, state }) {
state.sidebar ?
dispatch('openSidebar') :
dispatch('closeSidebar')
},
},
getters: {
currentLinkExists: state => !state.currentLink.disabled,
nextLinkExists: state => !state.nextLink.disabled,
getCurrentLink: (state) => {
if (state.currentLink.target.alternative_link) {
return { path: state.currentLink.target.alternative_link };
}
return { name: 'IssueList', params: { date: state.currentLink.target.date } };
},
getNextLink: (state) => {
if (state.nextLink.target.alternative_link) {
return { path: state.nextLink.target.alternative_link };
}
return { name: 'IssueList', params: { date: state.nextLink.target.date } };
},
getFlatPages: state => state.flatPages,
displayHeader: state => !state.header.disabled,
headerText: state => state.header.text,
showSidebar: state => state.sidebar
},
modules: {
},
});
export default store;
|
import React from 'react';
import LikeItem from './LikeItem/LikeItem';
import classes from './LikePanel.module.css';
import * as loveList from '../../../../utils/loveList';
import { connect } from 'react-redux';
import { get_loved_recipe } from '../../../../store/actions/loveListActions';
class LikePanel extends React.Component {
render() {
const classList = [];
classList.push(classes.LikePanel);
if(this.props.show)
classList.push(classes.Show);
let ListItems = loveList.size() === 0 ? [] : loveList.getAll();
ListItems = ListItems.map(recipe => {
return (<LikeItem
recipe={recipe}
key={recipe.uri}
clicked={() => this.props.clickLoveHandler(recipe.uri)}
></LikeItem>);
})
return (
<div
className={classList.join(' ')}
onMouseEnter={this.props.enter}
onMouseLeave={this.props.leave}
>
<ul className={classes.LikeList}>
{ListItems}
</ul>
</div>
);
}
}
const mapStateToProps = state => {
return {
clickedRecipe: state.loveList.lovedRecipe
};
}
const mapDispatchToProps = dispatch => {
return {
clickLoveHandler: (uri) => dispatch(get_loved_recipe(uri))
}
}
export default connect(mapStateToProps, mapDispatchToProps)(LikePanel);
|
function solve(input)
{
return input.filter((a, i)=>i%2==1)
.map(x=>x*2)
.reverse()
.join(' ');
}
solve([10, 15, 20, 25])
|
var express = require('express');
var router = express.Router();
//Require mongoose model
var Entry = require('../models/entry').Entry;
/* GET main blog page */
router.get('/', function(req, res) {
Entry.find(function(err, data) {
res.render('blog', {
title: 'Blog',
activeId: 'blog',
blogList: data
});
});
});
// GET new entry page
router.get('/newentry', function(req, res) {
res.render('newentry', {title: "New Entry"});
});
// POST new entry to database
router.post('/addentry', function(req, res) {
var today = new Date();
var post = req.body.post;
var headline = req.body.headline;
var blurb = req.body.blurb;
var tags = req.body.tags.split(" ");
var data = {
'post': post,
'headline': headline,
'blurb': blurb,
'date': {
'year': String(today.getFullYear()),
'month': String(today.getMonth() + 1),
'day': String(today.getDay()) },
'tags': tags,
'comments': []
};
var toAdd = new Entry(data);
toAdd.save(function(err) {
res.location("/blog");
res.redirect("/blog");
});
});
// GET complete post
router.get('/viewentry', function(req, res) {
var id = req.query.id;
Entry.findOne({_id: id}, function(err, data) {
res.render('viewblog', {entry: data});
});
});
//DELETE post
router.delete('/deleteentry', function(req, res) {
var id = req.body.id;
Entry.remove({_id: id}, function(err) {
res.status(200).send("Deletion successful!");
});
});
module.exports = router;
|
const { Axios, getUrl } = require("./backEndApiCall");
export const login = async (id, password) => {
const response = await Axios.post(getUrl(`/login`), {
id,
password,
});
if (response.data.code !== 200) throw new Error(response.data.message);
};
export const logout = ()=>{
return Axios.get(getUrl(`/logout`));
}
export const getNurseSchedule = async () => {
const response = await Axios.get(getUrl(`/nurse/schedule`));
return response.data;
};
export const updateStatus = async (treatmentId, status) => {
const response = await Axios.post(getUrl(`/treatment`), {
treatmentId,
status,
});
};
export const getNurseData = async () => {
const response = await Axios.get(getUrl(`/nurse`));
return response.data;
};
export const getTreatmentData = async (id) => {
const response = await Axios.get(getUrl(`/treatment/${id}`));
return response.data;
};
|
import axios from "axios";
export const getProductsAPI = (keywordSearch, price, time, category, page) => {
return axios.get(
`${process.env.REACT_APP_API_URL}/products/search?name=${keywordSearch}&price=${price}&time=${time}&limit=15&page=${page}&category=${category}`
);
};
export const addProductsAPI = (body) => {
return axios.post(`${process.env.REACT_APP_API_URL}/products/add`, body, {
headers: {
"content-type": "multipart/form-data",
"x-access-token": `bearer ${localStorage.getItem("token")}`,
},
});
};
export const deleteProductsAPI = (id,body) => {
return axios.delete(`${process.env.REACT_APP_API_URL}/products/delete/${id}`, {
headers: {
"x-access-token": `bearer ${localStorage.getItem("token")}`,
},
data:body
},
);
};
export const updateProductsAPI = (id, body) => {
return axios.patch(`${process.env.REACT_APP_API_URL}/products/update/${id}`, body, {
headers: {
"content-type": "multipart/form-data",
"x-access-token": `bearer ${localStorage.getItem("token")}`,
},
});
};
|
var serverQueue;
const constants = require('./constants.js');
module.exports =
{
name: '~stop',
description: 'stop!',
execute(msg, queue) {
serverQueue = queue.get(msg.guild.id);
if (!msg.member.voiceChannel)
return msg.channel.send(
"You have to be in a voice channel to stop the music!"
);
constants.End = true;
serverQueue.connection.dispatcher.pause();
},
};
|
import React from 'react';
import BoardSquare from './BoardSquare';
class Board extends React.Component {
constructor() {
super();
this.renderSquare = this.renderSquare.bind(this);
this._getSquareProps = this._getSquareProps.bind(this);
}
renderSquare(i) {
return (
<BoardSquare key={i} {...this._getSquareProps(i)} />
);
}
_getSquareProps(i) {
const height = Math.sqrt(this.props.grid.length);
const x = i % height;
const y = Math.floor(i / height);
const alive = this.props.grid[i];
const handleClick= (x, y) => { this.props.handleSquareClick(x, y); };
return {
height,
x,
y,
alive,
handleClick
};
}
render() {
const squares = [];
for(let i = 0; i < this.props.grid.length; i++) {
squares.push(this.renderSquare(i));
}
return (
<div className="board">
{squares}
</div>
);
}
}
Board.propTypes = {
grid: React.PropTypes.array.isRequired,
handleSquareClick: React.PropTypes.func.isRequired
};
export default Board;
|
function main(){
alert("Hello World!");
}
main();
|
/**
* @file Tab機能
*/
const tabTriggers = [];
const tabContents = [];
/**
* Tab切替
* @param {*} event イベント
* @param {*} group TabのGroup
* @param {*} name 連動するTabの名称
*/
const changeTab = (event, group, name) => {
console.log('changeTab');
event.preventDefault();
// タブの選択中トリガーを切り替える
for (const trigger of tabTriggers) {
// 同一group以外は無視する
if (trigger.group !== group) {
continue;
}
// 選択中のタブを切替
if (trigger.name === name) {
trigger.element.classList.add('is-current');
} else {
trigger.element.classList.remove('is-current');
}
}
// タブの選択中コンテンツを切り替える
for (const content of tabContents) {
// 同一group以外は無視する
if (content.group !== group) {
continue;
}
// 選択中のタブを切替
if (content.name === name) {
// 表示
content.element.style.display = '';
content.element.classList.add('is-current');
} else {
// 非表示
content.element.style.display = 'none';
content.element.classList.remove('is-current');
}
}
};
export const generateTab = (wrapper) => {
const triggers = [...wrapper.getElementsByClassName('js-tab-trigger')];
const contents = [...wrapper.getElementsByClassName('js-tab-content')];
// Tabトリガー設定
for (const trigger of triggers) {
// data属性のlistとinfoを取得する
const triggerGroup= trigger.getAttribute('data-tab-group');
const triggerName = trigger.getAttribute('data-tab-name');
// data属性のlistとinfoは設定必須なのでチェック
if (!triggerGroup || !triggerName) {
continue;
}
// Tabのトリガーを設定
tabTriggers.push({
element: trigger,
group: triggerGroup,
name: triggerName,
});
// トリガーのクリックイベントを設定
trigger.addEventListener('click', () => changeTab(event, triggerGroup, triggerName));
}
// Tabコンテンツ設定
for (const content of contents) {
// data属性のlistとinfoを取得する
const contentGroup = content.getAttribute('data-tab-group');
const contentName = content.getAttribute('data-tab-name');
// data属性のlistとinfoは設定必須なのでチェック
if (!contentGroup || !contentName) {
continue;
}
// Tabのコンテンツを設定
tabContents.push({
element: content,
group: contentGroup,
name: contentName,
});
}
}
|
exports.myFunction = function(params, callback) {
var num = params.num;
if(num > 10){
return callback({err: 'Num too large'}, {result: num});
}
callback(null, {result: num});
};
exports.redFunction = function(params, callback) {
callback({err: 'Red Error'});
};
exports.greenFunction = function(params, callback) {
callback(null, {result: "Green Sucess"});
};
|
export const filterMethods = (methods) => Object.keys(methods)
.filter(m => !m.startsWith('0x'))
.reduce((a, m) => ({ ...a, [m]: methods[m] }), {})
|
import React from 'react';
import { SidebarContainer, SideBtnWrap, SidebarLink, SidebarMenu, Icon, CloseIcon, SidebarRoute } from './SidebarElements';
function index({isOpen, toggle}) {
return (
<SidebarContainer isOpen={isOpen} onClick={toggle}>
<Icon onClick={toggle}>
<CloseIcon />
</Icon>
<SidebarMenu>
<SidebarLink to="/">Menu</SidebarLink>
<SidebarLink to="/">Feature</SidebarLink>
<SidebarLink to="/">Recipe</SidebarLink>
<SidebarLink to="/">About Us</SidebarLink>
</SidebarMenu>
<SideBtnWrap>
<SidebarRoute to="/" >Order Now</SidebarRoute>
</SideBtnWrap>
</SidebarContainer>
)
}
export default index
|
require.config({
baseUrl: ".",
paths: {
d3: "node_modules/d3/d3",
"dat.GUI": "libs/dat-gui/src/dat/gui/GUI",
"dat": "libs/dat-gui/src/dat",
"text": "libs/text",
"colorbrewer": "libs/colorbrewer"
},
shim: {
d3: {
exports: "d3"
},
colorbrewer: {
exports: "colorbrewer"
}
},
deps: ["src/main"]
});
|
/**######################################################
* paths for images loading
* ######################################################*/
var localhost = {
public_folder : 'C:/Users/Arnas/webProject/appBackend_v2/public',
images_location : 'http://localhost:3000/',
ipAddress: null,
};
var realServer = {
public_folder : '/home/arnas/appBackend_v2/public',
images_location : 'http://139.59.134.47:3000/',
ipAddress: null
}
var myLaptoop ={
ipAddress: '192.168.1.67',
images_location : 'http://192.168.1.67:3000/',
public_folder : 'C:/Users/Arnas/webProject/appBackend_v2/public',
}
module.exports = realServer;
|
import { BrowserRouter, Route, Switch, Redirect } from "react-router-dom";
import React from "react";
import LoginPage from "../src/pages/login_page/LoginPage";
import Admin from "./pages/admin/index_admin";
import Dashboard from "../src/pages/dash_page/dash_page";
import SendForgotPassword from "../src/pages/send_forgot_password/SendForgotPassword";
import ForgotPassword from "../src/pages/forgot_password/ForgotPassword";
import { isAuthenticated } from "./service/auth";
export default function Routes() {
const PrivateRoute = ({ component: Component, ...rest }) => (
<Route
{...rest}
render={(props) =>
isAuthenticated() ? (
<Component {...props} />
) : (
<Redirect to={{ pathname: "/", state: { from: props.location } }} />
)
}
/>
);
return (
<BrowserRouter>
<Switch>
<Route path="/" exact component={LoginPage} />
<Route path="/sendemail" component={SendForgotPassword} />
<Route path="/forgotpassword" component={ForgotPassword} />
<PrivateRoute path="/admin" component={Admin} />
<PrivateRoute path="/dash" component={Dashboard} />
</Switch>
</BrowserRouter>
);
}
|
import React from 'react';
const Slide = (props) => {
return (
<li className={(props.index === props.activeSlide) ? 'slideContent slideContent--active': 'slideContent'}>
<img src={props.image.image} alt="First Slide" className="slideImage"/>
<p className='slideDescription'>{props.image.description}</p>
</li>
)
};
export default Slide;
|
export const addReadme = data => ({
type: 'ADD_README',
text: data
})
|
/*global $:false*/
(function () {
'use strict';
angular
.module('musicalisimo')
.directive('player', function (utils, player, $window, $interval) {
return {
restrict: 'A',
scope: {},
templateUrl: '/musicalisimo/player/player.html',
controller: function ($scope) {
var isTracking = false,
halfOfCursorWidth = 8;
$scope.isPlaying = false;
$scope.getLink = player.getCurrentVideoLink;
$scope.play = function () {
player.playVideo();
$scope.isPlaying = true;
};
$scope.stop = function () {
player.pauseVideo();
$scope.isPlaying = false;
};
$interval(function () {
if (player.isReady) {
updateProgress(isTracking);
updateTime();
}
}, 500);
angular.element($window)
.bind('resize', updateProgress);
$('#progressTrack').mousedown(function (event) {
isTracking = true;
$('#progressCursor').css('left', event.pageX - halfOfCursorWidth + 'px');
});
$(document).mouseup(function (event) {
if (isTracking) {
player.seekTo(event.pageX / getWindowWidth() * player.getDuration(), true);
isTracking = false;
}
});
$(document).mousemove(function (event) {
if (isTracking) {
$('#progressCursor').css('left', event.pageX - halfOfCursorWidth + 'px');
}
});
function updateProgress(isTracking) {
var per = player.getCurrentTime() ? player.getCurrentTime() / player.getDuration() : 0;
$("#progressBar").css('width', per * 100 + '%');
if (!isTracking)
$('#progressCursor').css('left', per * $(window).width() - halfOfCursorWidth + 'px');
}
function updateTime() {
$('#leftTime').html(utils.formatTime(player.getCurrentTime()));
$('#title').html(player.getTitle());
$('#rightTime').html(utils.formatTime(player.getDuration()));
}
//Utils
function getWindowWidth() {
return $(window).width();
}
}
};
});
})();
|
/**
*
* @author Maurício Generoso
*/
(() => {
'use strict';
describe('Test Service: ConvertPolarCartesiaConvertPolarCartesianServicenService', () => {
beforeEach(angular.mock.module('radarApp'));
var _ConvertPolarCartesianService;
beforeEach(inject(ConvertPolarCartesianService => {
_ConvertPolarCartesianService = ConvertPolarCartesianService;
}));
it('Test if ConvertPolarCartesianService is defined', () => {
expect(_ConvertPolarCartesianService).toBeDefined();
expect(_ConvertPolarCartesianService.convertCartesianToPolar).toBeDefined();
expect(_ConvertPolarCartesianService.convertPolarToCartesian).toBeDefined();
});
it('Should throw when object not have axis x in function convertCartesianToPolar', () => {
var object = { axisY: 45 };
expect(() => _ConvertPolarCartesianService.convertCartesianToPolar(object)).toThrow();
});
it('Should throw when object not have axis y in function convertCartesianToPolar', () => {
var object = { axisX: 45 };
expect(() => _ConvertPolarCartesianService.convertCartesianToPolar(object)).toThrow();
});
it('Test function convertCartesianToPolar', () => {
var object = {
axisX: 4,
axisY: 2
};
object = _ConvertPolarCartesianService.convertCartesianToPolar(object);
expect(object.radius).toEqual('4.47');
expect(object.angle).toEqual('26.57');
});
it('Should throw when object not have radius in function convertPolarToCartesian', () => {
var object = { angle: 45 };
expect(() => _ConvertPolarCartesianService.convertPolarToCartesian(object)).toThrow();
});
it('Should throw when object not have angle in function convertPolarToCartesian', () => {
var object = { radius: 45 };
expect(() => _ConvertPolarCartesianService.convertPolarToCartesian(object)).toThrow();
});
it('Test function convertPolarToCartesian', () => {
var object = {
radius: 2,
angle: 30
};
var object = _ConvertPolarCartesianService.convertPolarToCartesian(object);
expect(object.axisX).toEqual('1.73');
expect(object.axisY).toEqual('1.00');
});
});
})();
|
const ADD_TODO = 'ADD_TODO'
const TOGGLE_TODO = 'TOGGLE_TODO'
const DELETE_TODO = 'DELETE_TODO'
const UPDATE_TODO = 'UPDATE_TODO'
export default{
ADD_TODO,
TOGGLE_TODO,
DELETE_TODO,
UPDATE_TODO
}
|
// Exercise 16
//
// Write a JavaScript program that returns an array of ALL the numbers
// between two provided values, num1 and num2, that meet the following criteria.
//
// The sum of the cube of the digits of a number is equal to the number.
//
// e.g.
// 371 --> 3^3 + 7^3 + 1^3 = 371.
// Edit only the code between the lines (below)
// -----------------------------------------------------------------
function findNumbers(num1, num2) {
// num1 and num2 are Numbers
//some cheking
let list = []; // list to put all numbers in
for(let n = num1; n<=num2; n++){ // assume num2 inclusive
//check if n=0
if(n===0){
list.push(n);
continue; // go to next loop
}else{ // when n is larger than 0
// get each digits
let n_cur = n;
let dig = 0; // find the digits and cube it and store here :D
let base = 10; // base 10 calculation
while(n_cur!==0){ // loop until n_cur drops to 0
let d = n_cur%base; // e.g. 5142 % 10 = 2
dig += d**3; // => and cube it
n_cur =(n_cur - d)/base; // => and remove the digit from number. If drop to n_cur = 5, 5 - 5 / 10 = 0.
}
if(dig===n){
list.push(n);
}
}
}
return list;
}
// -----------------------------------------------------------------
// Edit only the code between the lines (above)
console.log(findNumbers(0, 1000));
// Create more test cases.
console.log(findNumbers(0, 5000));
console.log(findNumbers(0, 100000));
// This is needed for automated testing (more on that later)
module.exports = findNumbers;
|
Polymer({
is: "iron-icon",
properties: {
icon: {
type: String
},
theme: {
type: String
},
src: {
type: String
},
_meta: {
value: Polymer.Base.create("iron-meta", {
type: "iconset"
})
}
},
observers: ["_updateIcon(_meta, isAttached)", "_updateIcon(theme, isAttached)", "_srcChanged(src, isAttached)", "_iconChanged(icon, isAttached)"],
_DEFAULT_ICONSET: "icons",
_iconChanged: function(t) {
var i = (t || "").split(":");
this._iconName = i.pop(), this._iconsetName = i.pop() || this._DEFAULT_ICONSET, this._updateIcon()
},
_srcChanged: function(t) {
this._updateIcon()
},
_usesIconset: function() {
return this.icon || !this.src
},
_updateIcon: function() {
this._usesIconset() ? (this._img && this._img.parentNode && Polymer.dom(this.root).removeChild(this._img), "" === this._iconName ? this._iconset && this._iconset.removeIcon(this) : this._iconsetName && this._meta && (this._iconset = this._meta.byKey(this._iconsetName), this._iconset ? (this._iconset.applyIcon(this, this._iconName, this.theme), this.unlisten(window, "iron-iconset-added", "_updateIcon")) : this.listen(window, "iron-iconset-added", "_updateIcon"))) : (this._iconset && this._iconset.removeIcon(this), this._img || (this._img = document.createElement("img"), this._img.style.width = "100%", this._img.style.height = "100%", this._img.draggable = !1), this._img.src = this.src, Polymer.dom(this.root).appendChild(this._img))
}
});
|
var environment_variables= {
prod:{
port: process.env.PORT,
db: process.env.MONGOLAB_URI || "mongodb://localhost/api_db",
secret: process.env.SECRET || '9raOHbNfeDu43eifySLGww'
},
dev:{
port: process.env.PORT || 3500,
db: process.env.MONGOLAB_URI || "mongodb://localhost/api_testdb",
secret: process.env.SECRET || '9raOHbNfeDu43eifySLGww'
},
test:{
port: process.env.PORT || 3500,
db: process.env.MONGOLAB_URI || "mongodb://localhost/api_testdb",
secret: process.env.SECRET || '9raOHbNfeDu43eifySLGww'
}
}
module.exports=environment_variables[process.env.NODE_ENV||'dev']
|
const express = require("express");
const {listarTodos, novoJogo, listarPorId, atualizarJogo,excluirJogo} = require("../controller/jogos")
const router = express();
router.get("/jogos", listarTodos);
router.get("/jogos/:id", listarPorId)
router.post("/jogos", novoJogo);
router.put("/jogos/:id", atualizarJogo);
router.delete("/jogos/:id",excluirJogo);
module.exports = router
|
define([
'page_config'
],
function (PageConfig) {
describe('PageConfig', function () {
var req;
beforeEach(function () {
var get = jasmine.createSpy();
get.plan = function (prop) {
return {
assetPath: '/path/to/assets/',
}[prop];
};
var headers = jasmine.createSpy();
headers.plan = function(prop) {
return {
'Request-Id': 'a-uuid',
'GOVUK-Request-Id': '1231234123'
}[prop];
};
req = {
app: {
get: get
},
get: headers,
protocol: 'http',
originalUrl: '/performance/foo'
};
});
describe('getGovUkUrl', function () {
beforeEach(function () {
process.env.GOVUK_WEBSITE_ROOT = 'https://www.gov.uk';
});
it('returns the equivalent page location on GOV.UK', function () {
expect(PageConfig.getGovUkUrl(req)).toEqual('https://www.gov.uk/performance/foo');
});
});
describe('commonConfig', function () {
it('contains assetPath property', function () {
var commonConfig = PageConfig.commonConfig(req);
expect(commonConfig.assetPath).toEqual('/path/to/assets/');
});
it('contains assetPath property', function () {
var commonConfig = PageConfig.commonConfig(req);
expect(commonConfig.url).toEqual('/performance/foo');
});
it('contains requestId property', function() {
var commonConfig = PageConfig.commonConfig(req);
expect(commonConfig.requestId).toEqual('a-uuid');
});
});
});
});
|
import React from 'react';
import { connect } from 'react-redux';
import { Grid, Row, Col } from 'react-bootstrap';
import { Button } from 'reactstrap';
import styled from 'styled-components';
import { Link, Redirect } from 'react-router-dom';
import { loginUser } from '../actions/userActions';
import isAuthorized from '../helpers/isAuthorized';
const SignUpContiner = styled.div``;
export default class SignUp extends React.Component {
state = {
screenHeight: 0
};
componentDidMount = () => {
this.calculations();
window.addEventListener('resize', this.calculations);
};
componentWillUnmount = () => {
window.removeEventListener('resize', this.calculations);
};
calculations = () => {
const screenHeight = window.innerHeight;
this.setState({ screenHeight });
};
signUp = () => {
};
render = () => {
const authorized = isAuthorized();
if (authorized) {
return (<Redirect to="/"/>);
}
return (
<SignUpContiner className="sign-up-wrapper">
<Grid>
<Row>
<Col md={12} className="sign-up-container" style={{ height: this.state.screenHeight }}>
<div className="sign-up-card">
<form className="register-form">
<input id="register-email" type="email" className="form-control" placeholder="Email address" required/>
<input id="register-password" type="password" className="form-control" placeholder="Password" required/>
<input id="register-re-password" type="password" className="form-control" placeholder="Repeat password" required/>
<Button
type="submit"
className="cms-button"
onClick={() => this.signUp()}
>
Sign up
</Button>
<hr/>
<div className="sign-in">
<Link to="/login">
<Button className="cms-button">
Sign in
</Button>
</Link>
</div>
</form>
</div>
</Col>
</Row>
</Grid>
</SignUpContiner>
);
}
}
|
var searchData=
[
['navigation',['Navigation',['../classca_1_1mcgill_1_1ecse211_1_1project_1_1_navigation.html',1,'ca::mcgill::ecse211::project']]]
];
|
import React from 'react';
import logo from './logo.svg';
import './App.css';
import Navbar from './components/Navbar/Navbar'
import TourList from './components/Tourlist';
import "@fortawesome/fontawesome-free/css/all.min.css";
function App() {
return (
<React.Fragment>
<Navbar />
<TourList />
</React.Fragment>
);
}
export default App;
|
export const UPDATE_PAGE = 'UPDATE_PAGE';
export const RECEIVE_LAZY_RESOURCES = 'RECEIVE_LAZY_RESOURCES';
export const UPDATE_OFFLINE = 'UPDATE_OFFLINE';
export const UPDATE_WIDE_LAYOUT = 'UPDATE_WIDE_LAYOUT';
export const UPDATE_DRAWER_STATE = 'UPDATE_DRAWER_STATE';
export const OPEN_SNACKBAR = 'OPEN_SNACKBAR';
export const CLOSE_SNACKBAR = 'CLOSE_SNACKBAR';
export const UPDATE_SUBTITLE = 'UPDATE_SUBTITLE';
export const navigate = (location) => (dispatch) => {
// Extract the page name from path.
// Any other info you might want to extract from the path (like page type),
// you can do here.
const pathname = location.pathname;
const parts = pathname.slice(1).split('/');
const page = parts[0] || 'home';
// item id is in the path: /detail/{itemId}
const itemId = parts[1];
// query is extracted from the search string: /explore?q={query}
const match = RegExp('[?&]q=([^&]*)').exec(location.search);
const query = match && decodeURIComponent(match[1].replace(/\+/g, ' '))
dispatch(loadPage(page, query, itemId));
};
const loadPage = (page, query, itemId) => async (dispatch, getState) => {
let module;
switch (page) {
case 'home':
await import('../components/home-page.js');
// Put code here that you want it to run every time when
// navigate to view1 page and home-page.js is loaded
break;
case 'about':
await import('../components/about-page.js');
// Put code here that you want it to run every time when
// navigate to view1 page and home-page.js is loaded
break;
case 'search':
module = await import('../components/item-search.js');
// Put code here that you want it to run every time when
// navigate to explore page and item-search.js is loaded.
//
// In this case, we want to dispatch searchItems action.
// In item-search.js module it exports searchItems so we can call the function here.
dispatch(module.searchItems(query));
break;
case 'detail':
module = await import('../components/item-detail.js');
// Fetch the item info for the given item id.
await dispatch(module.fetchItem(itemId));
// Wait for to check if the item id is valid.
if (isFetchItemFailed(getState().item)) {
page = '404';
}
break;
default:
// Nothing matches, set page to '404'.
page = '404';
}
if (page === '404') {
import('../components/not-found-page.js');
}
dispatch(updatePage(page));
const lazyLoadComplete = getState().app.lazyResourcesLoaded;
// load lazy resources after render and set `lazyLoadComplete` when done.
if (!lazyLoadComplete) {
requestAnimationFrame(async () => {
await import('../components/lazy-resources.js');
dispatch({
type: RECEIVE_LAZY_RESOURCES
});
});
}
}
export const refreshPage = () => (dispatch, getState) => {
const state = getState();
// load page using the current state
dispatch(loadPage(state.app.page, state.item && state.item.query, state.item && state.item.id));
}
const updatePage = (page) => {
return {
type: UPDATE_PAGE,
page
};
}
const isFetchItemFailed = (item) => {
return !item.isFetching && item.failure;
}
let snackbarTimer;
export const showSnackbar = () => (dispatch) => {
dispatch({
type: OPEN_SNACKBAR
});
clearTimeout(snackbarTimer);
snackbarTimer = setTimeout(() =>
dispatch({type: CLOSE_SNACKBAR}), 3000);
};
export const updateOffline = (offline) => (dispatch, getState) => {
const prev = getState().app.offline;
dispatch({
type: UPDATE_OFFLINE,
offline
});
if (prev !== undefined) {
dispatch(showSnackbar());
}
// automatically refresh when you come back online (offline was true and now is false)
if (prev === true && offline === false) {
dispatch(refreshPage());
}
};
export const updateLayout = (wide) => (dispatch, getState) => {
dispatch({
type: UPDATE_WIDE_LAYOUT,
wide
});
if (getState().app.drawerOpened) {
dispatch(updateDrawerState(false));
}
}
export const updateDrawerState = (opened) => (dispatch, getState) => {
if (getState().app.drawerOpened !== opened) {
dispatch({
type: UPDATE_DRAWER_STATE,
opened
});
}
}
export const updateSubTitle = (subTitle) => {
return {
type: UPDATE_SUBTITLE,
subTitle
}
}
export const updateLocationURL = (url) => (dispatch) => {
window.history.pushState({}, '', url);
dispatch(navigate(window.location));
}
|
$('#toregister').click(function() {
console.log("togglelogs clicked");
$('.bg-modal').toggleClass('hidden');
});
document.getElementById('toregister').addEventListener('click', function() {
document.querySelector('.bg-modal').toggleClass('hidden');
});
|
var num,a;
flag = 0;
function openpara(val)
{
document.getElementById("display").value+=val;
flag+=1;
}
function closepara(val)
{
document.getElementById("display").value+=val;
flag-=1;
}
function displayNum(num)
{
document.getElementById("display").value += num;
}
function rub(num)
{
document.getElementById("display").value = num;
}
function backspace()
{
var a = document.getElementById("display").value;
document.getElementById("display").value = a.substr(0, a.length - 1);
}
function solve()
{
try
{
rub(eval(document.getElementById("display").value));
}
catch(evaluate)
{
rub('Error');
}
}
/*
function squareRoot(num)
{
document.getElementById("display").value += num;
rub(Math.sqrt(document.getElementById("display").value));
}
function piValue()
{
document.getElementById("display").value = Math.PI;
}
function sin(form)
{
document.getElementById("display").value = Math.sin(document.getElementById("display").value );
}
function cos(form)
{
document.getElementById("display").value = Math.cos(document.getElementById("display").value );
}
function tan(form)
{
document.getElementById("display").value = Math.tan(document.getElementById("display").value );
}
*/
|
var random = require("random-js")();
var random_str = require('random-string');
var _ = require('underscore');
require('date-utils');
var app_id_2_app = {
"1": require('./aie/box'),
"2": require('./aie/dropbox'),
"3": {
"appname": "GoogleDrive",
"hostname": "www.gdrive.com",
"category": ["storage"],
"activity_path": {
"login": ['-100000'],
"upload": ["-100000", "-100001"],
"preview": ["-100000", "-100004"],
"delete": ["-100000", "-100003"],
"upload_preview_download": ["-100000", "-100001", "-100004", "-100002"],
"download": ["-100000", "-100004", "-100002"]
},
"activities": require('./aie/common_activity.js')('user_token')
},
"4": {
"appname": "ShareFile",
"hostname": "www.sharefile.com",
"category": ["storage"],
"activity_path": {
"login": ['-100000'],
"upload": ["-100000", "-100001"],
"preview": ["-100000", "-100004"],
"delete": ["-100000", "-100003"],
"upload_preview_download": ["-100000", "-100001", "-100004", "-100002"],
"download": ["-100000", "-100004", "-100002"]
},
"activities": require('./aie/common_activity.js')('user_token')
},
"5": {
"appname": "SugarSync",
"hostname": "www.sugarsync.com",
"category": ["storage"],
"activity_path": {
"login": ['-100000'],
"upload": ["-100000", "-100001"],
"preview": ["-100000", "-100004"],
"delete": ["-100000", "-100003"],
"upload_preview_download": ["-100000", "-100001", "-100004", "-100002"],
"download": ["-100000", "-100004", "-100002"]
},
"activities": require('./aie/common_activity.js')('user_token')
},
"6": {
"appname": "DropSend",
"hostname": "www.dropsend.com",
"category": ["storage"],
"activity_path": {
"login": ['-100000'],
"upload": ["-100000", "-100001"],
"preview": ["-100000", "-100004"],
"delete": ["-100000", "-100003"],
"upload_preview_download": ["-100000", "-100001", "-100004", "-100002"],
"download": ["-100000", "-100004", "-100002"]
},
"activities": require('./aie/common_activity.js')('user_token')
},
"7": {
"appname": "PhotoBucket",
"hostname": "www.photobucket.com",
"category": ["storage"],
"activity_path": {
"login": ['-100000'],
"upload": ["-100000", "-100001"],
"preview": ["-100000", "-100004"],
"delete": ["-100000", "-100003"],
"upload_preview_download": ["-100000", "-100001", "-100004", "-100002"],
"download": ["-100000", "-100004", "-100002"]
},
"activities": require('./aie/common_activity.js')('user_token')
},
"8": {
"appname": "SkyPath",
"hostname": "www.skypath.com",
"category": ["storage"],
"activity_path": {
"login": ['-100000'],
"upload": ["-100000", "-100001"],
"preview": ["-100000", "-100004"],
"delete": ["-100000", "-100003"],
"upload_preview_download": ["-100000", "-100001", "-100004", "-100002"],
"download": ["-100000", "-100004", "-100002"]
},
"activities": require('./aie/common_activity.js')('user_token')
},
"9": {
"appname": "Mozy",
"hostname": "www.mozy.com",
"category": ["storage"],
"activity_path": {
"login": ['-100000'],
"upload": ["-100000", "-100001"],
"preview": ["-100000", "-100004"],
"delete": ["-100000", "-100003"],
"upload_preview_download": ["-100000", "-100001", "-100004", "-100002"],
"download": ["-100000", "-100004", "-100002"]
},
"activities": require('./aie/common_activity.js')('user_token')
},
"10": {
"appname": "SyncPlicity",
"hostname": "www.syncplicity.com",
"category": ["storage"],
"activity_path": {
"login": ['-100000'],
"upload": ["-100000", "-100001"],
"preview": ["-100000", "-100004"],
"delete": ["-100000", "-100003"],
"upload_preview_download": ["-100000", "-100001", "-100004", "-100002"],
"download": ["-100000", "-100004", "-100002"]
},
"activities": require('./aie/common_activity.js')('user_token')
},
"11": {
"appname": "Hightail",
"hostname": "www.hightail.com",
"category": ["storage"],
"activity_path": {
"login": ['-100000'],
"upload": ["-100000", "-100001"],
"preview": ["-100000", "-100004"],
"delete": ["-100000", "-100003"],
"upload_preview_download": ["-100000", "-100001", "-100004", "-100002"],
"download": ["-100000", "-100004", "-100002"]
},
"activities": require('./aie/common_activity.js')('user_token')
},
"12": {
"appname": "icloud",
"hostname": "www.icloud.com",
"category": ["storage"],
"activity_path": {
"login": ['-100000'],
"upload": ["-100000", "-100001"],
"preview": ["-100000", "-100004"],
"delete": ["-100000", "-100003"],
"upload_preview_download": ["-100000", "-100001", "-100004", "-100002"],
"download": ["-100000", "-100004", "-100002"]
},
"activities": require('./aie/common_activity.js')('user_token')
},
"13": {
"appname": "MicrosoftSkyDrive",
"hostname": "www.msskydrive.com",
"category": ["storage"],
"activity_path": {
"login": ['-100000'],
"upload": ["-100000", "-100001"],
"preview": ["-100000", "-100004"],
"delete": ["-100000", "-100003"],
"upload_preview_download": ["-100000", "-100001", "-100004", "-100002"],
"download": ["-100000", "-100004", "-100002"]
},
"activities": require('./aie/common_activity.js')('user_token')
},
"15": {
"appname": "Wuala",
"hostname": "www.wuala.com",
"category": ["storage"],
"activity_path": {
"login": ['-100000'],
"upload": ["-100000", "-100001"],
"preview": ["-100000", "-100004"],
"delete": ["-100000", "-100003"],
"upload_preview_download": ["-100000", "-100001", "-100004", "-100002"],
"download": ["-100000", "-100004", "-100002"]
},
"activities": require('./aie/common_activity.js')('user_token')
},
"16": {
"appname": "Egnyte",
"hostname": "www.ngnyte.com",
"category": ["storage"],
"activity_path": {
"login": ['-100000'],
"upload": ["-100000", "-100001"],
"preview": ["-100000", "-100004"],
"delete": ["-100000", "-100003"],
"upload_preview_download": ["-100000", "-100001", "-100004", "-100002"],
"download": ["-100000", "-100004", "-100002"]
},
"activities": require('./aie/common_activity.js')('user_token')
},
"17": {
"appname": "WeTransfer",
"hostname": "www.wetransfer.com",
"category": ["storage"],
"activity_path": {
"login": ['-100000'],
"upload": ["-100000", "-100001"],
"preview": ["-100000", "-100004"],
"delete": ["-100000", "-100003"],
"upload_preview_download": ["-100000", "-100001", "-100004", "-100002"],
"download": ["-100000", "-100004", "-100002"]
},
"activities": require('./aie/common_activity.js')('user_token')
},
"18": {
"appname": "Accelion",
"hostname": "www.accelion.com",
"category": ["storage"],
"activity_path": {
"login": ['-100000'],
"upload": ["-100000", "-100001"],
"preview": ["-100000", "-100004"],
"delete": ["-100000", "-100003"],
"upload_preview_download": ["-100000", "-100001", "-100004", "-100002"],
"download": ["-100000", "-100004", "-100002"]
},
"activities": require('./aie/common_activity.js')('user_token')
},
"19": {
"appname": "LiveDrive",
"hostname": "www.livedrive.com",
"category": ["storage"],
"activity_path": {
"login": ['-100000'],
"upload": ["-100000", "-100001"],
"preview": ["-100000", "-100004"],
"delete": ["-100000", "-100003"],
"upload_preview_download": ["-100000", "-100001", "-100004", "-100002"],
"download": ["-100000", "-100004", "-100002"]
},
"activities": require('./aie/common_activity.js')('user_token')
},
"20": {
"appname": "JungleDisk",
"hostname": "www.jungledisk.com",
"category": ["storage"],
"activity_path": {
"login": ['-100000'],
"upload": ["-100000", "-100001"],
"preview": ["-100000", "-100004"],
"delete": ["-100000", "-100003"],
"upload_preview_download": ["-100000", "-100001", "-100004", "-100002"],
"download": ["-100000", "-100004", "-100002"]
},
"activities": require('./aie/common_activity.js')('user_token')
},
"21": {
"appname": "OneDrive",
"hostname": "www.onedrive.com",
"category": ["storage"],
"activity_path": {
"login": ['-100000'],
"upload": ["-100000", "-100001"],
"preview": ["-100000", "-100004"],
"delete": ["-100000", "-100003"],
"upload_preview_download": ["-100000", "-100001", "-100004", "-100002"],
"download": ["-100000", "-100004", "-100002"]
},
"activities": require('./aie/common_activity.js')('user_token')
},
'22': {
"appname": 'Squareup',
"hostname": 'www.squareup.com',
"category": ["sales"],
"activity_path": {
"login": ["-100000"],
"get": ["-100000", "-100001"],
"put": ["-100000", "-100002"],
"post": ["-100000", "-100003"],
"delete": ["-100000", "-100004"]
},
"activities": require('./aie/l2_common_activity.js')('user_token')
},
'23': {
"appname": 'Expensify',
"hostname": 'www.expensify.com',
"category": ["finace"],
"activity_path": {
"login": ["-100000"],
"get": ["-100000", "-100001"],
"put": ["-100000", "-100002"],
"post": ["-100000", "-100003"],
"delete": ["-100000", "-100004"]
},
"activities": require('./aie/l2_common_activity.js')('user_token')
},
'24': {
"appname": 'Constcontacts',
"hostname": 'www.constcontacts.com',
"category": ["sales"],
"activity_path": {
"login": ["-100000"],
"get": ["-100000", "-100001"],
"put": ["-100000", "-100002"],
"post": ["-100000", "-100003"],
"delete": ["-100000", "-100004"]
},
"activities": require('./aie/l2_common_activity.js')('user_token')
},
'25': {
"appname": 'Concursolutions',
"hostname": 'www.concursolutions.com',
"category": ["finace"],
"activity_path": {
"login": ["-100000"],
"get": ["-100000", "-100001"],
"put": ["-100000", "-100002"],
"post": ["-100000", "-100003"],
"delete": ["-100000", "-100004"]
},
"activities": require('./aie/l2_common_activity.js')('user_token')
},
'26': {
"appname": 's3',
"hostname": 'www.s3.com',
"category": ["storage"],
"activity_path": {
"login": ['-100000'],
"upload": ["-100000", "-100001"],
"preview": ["-100000", "-100004"],
"delete": ["-100000", "-100003"],
"upload_preview_download": ["-100000", "-100001", "-100004", "-100002"],
"download": ["-100000", "-100004", "-100002"]
},
"activities": require('./aie/common_activity.js')('user_token')
},
'27': {
"appname": 'AWS Glacier',
"hostname": 'www.glacier.com',
"category": ["finace"],
"activity_path": {
"login": ['-100000'],
"upload": ["-100000", "-100001"],
"preview": ["-100000", "-100004"],
"delete": ["-100000", "-100003"],
"upload_preview_download": ["-100000", "-100001", "-100004", "-100002"],
"download": ["-100000", "-100004", "-100002"]
},
"activities": require('./aie/common_activity.js')('user_token')
},
// add more for GW
"10001": {
"appname": "gmail",
"hostname": "www.gmail.com",
"category": ["mail"],
"activity_path": {
"login": ["-100000"]
},
"activities": require('./aie/l2_common_activity.js')('user_token')
},
"10002": {
"appname": "hotmail",
"hostname": "www.hotmail.com",
"category": ["mail"],
"activity_path": {
"login": ["-100000"]
},
"activities": require('./aie/l2_common_activity.js')('user_token')
},
'10004': {
"appname": "yahoo-mail",
"hostname": "www.yahoo-mail.com",
"category": ["mail"],
"activity_path": {
"login": ["-100000"]
},
"activities": require('./aie/l2_common_activity.js')('user_token')
},
'20001': {
"appname": "skype",
"hostname": "www.skype.com",
"category": ["im"],
"activity_path": {
"login": ["-100000"]
},
"activities": require('./aie/l2_common_activity.js')('user_token')
},
'20002': {
"appname": "gtalk",
"hostname": "www.gtalk.com",
"category": ["im"],
"activity_path": {
"login": ["-100000"]
},
"activities": require('./aie/l2_common_activity.js')('user_token')
},
'30001': {
"appname": "facebook",
"hostname": "www.facebook.com",
"category": ["social"],
"activity_path": {
"login": ["-100000"]
},
"activities": require('./aie/l2_common_activity.js')('user_token')
},
'30002': {
"appname": "twitter",
"hostname": "www.twitter.com",
"category": ["social"],
"activity_path": {
"login": ["-100000"]
},
"activities": require('./aie/l2_common_activity.js')('user_token')
},
'30003': {
"appname": "youtube",
"hostname": "www.youtube.com",
"category": ["social"],
"activity_path": {
"login": ["-100000"]
},
"activities": require('./aie/l2_common_activity.js')('user_token')
}
}
var user_info = {
"jackson@gmail.com": {
"unsub_emails": ['jackson@yahoo.com', 'jackson@hotmail.com'],
"devices": [{
"mac": 'ja:ck:so:n0:00:00'
},
{
"mac": 'ja:ck:so:n1:00:00'
},
{
"mac": 'ja:ck:so:n2:00:00'
}
]
},
"aiden@gmail.com": {
"unsub_emails": ['aiden@yahoo.com', 'aiden@abc.com'],
"devices": [{
"mac": 'ai:de:n0:00:00:00'
},
{
"mac": 'ai:de:n1:00:00:00'
}
]
},
"liam@gmail.com": {
"unsub_emails": ['liam@yahoo.com', 'liam@sina.com'],
"devices": [{
"mac": 'li:am:00:00:00:00'
},
{
"mac": 'li:am:01:00:00:00'
}
]
},
"lucas@gmail.com": {
"unsub_emails": ['lucas@hotmail.com', 'lucas@abc.com'],
"devices": [{
"mac": 'lu:ca:s0:00:00:00'
},
{
"mac": 'lu:ca:s1:00:00:00'
}
]
},
"justin@gmail.com": {
"unsub_emails": ['justin@yahoo.com', 'justin@abc.com'],
"devices": [{
"mac": 'ju:st:in:00:00:00'
},
{
"mac": 'ju:st:in:01:00:00'
}
]
},
"eric@gmail.com": {
"unsub_emails": ['eric@hotmail.com', 'eric@abc.com'],
"devices": [{
"mac": 'er:ic:00:00:00:00'
},
{
"mac": 'er:ic:01:00:00:00'
}
]
},
"david@gmail.com": {
"unsub_emails": ['david@yahoo.com', 'david@uvw.com'],
"devices": [{
"mac": 'da:vi:d0:00:00:00'
},
{
"mac": 'da:vi:d1:01:00:00'
}
]
},
"emma@gmail.com": {
"unsub_emails": ['emma@yahoo.com', 'emma@xyz.com'],
"devices": [{
"mac": 'em:ma:00:00:00:00'
},
{
"mac": 'em:ma:01:00:00:00'
}
]
},
"mary@gmail.com": {
"unsub_emails": ['mary@yahoo.com', 'mary@mnt.com'],
"devices": [{
"mac": 'ma:ry:00:00:00:00'
},
{
"mac": 'ma:ry:01:00:00:00'
}
]
},
"susan@gmail.com": {
"unsub_emails": ['susan@yahoo.com', 'susan@rst.com'],
"devices": [{
"mac": 'su:sa:n0:00:00:00'
},
{
"mac": 'su:sa:n1:00:00:00'
}
]
},
"jacob@gmail.com": {
"unsub_emails": ['jacob@yahoo.com', 'jacob@efg.com'],
"devices": [{
"mac": 'ja:co:b0:00:00:00'
},
{
"mac": 'ja:co:b1:00:00:00'
}
]
},
"ryan@gmail.com": {
"unsub_emails": ['ryan@yahoo.com', 'ryan@hij.com'],
"devices": [{
"mac": 'ry:an:00:00:00:00'
},
{
"mac": 'ry:an:01:00:00:00'
}
]
},
"alexander@gmail.com": {
"unsub_emails": ['alexander@yahoo.com', 'alexander@ij.com'],
"devices": [{
"mac": 'al:ex:an:de:r0:00'
},
{
"mac": 'al:ex:an:de:r1:00'
}
]
},
"james@gmail.com": {
"unsub_emails": ['james@yahoo.com', 'james@mn.com'],
"devices": [{
"mac": 'ja:me:s0:00:00:00'
},
{
"mac": 'ja:me:s1:00:00:00'
}
]
},
"robert@gmail.com": {
"unsub_emails": ['robert@yahoo.com', 'robert@ppt.com'],
"devices": [{
"mac": 'ro:be:rt:00:00:00'
},
{
"mac": 'ro:be:rt:01:00:00'
}
]
},
"william@gmail.com": {
"unsub_emails": ['william@yahoo.com', 'william@doc.com'],
"devices": [{
"mac": 'wi:ll:ia:m0:00:00'
},
{
"mac": 'wi:ll:ia:m1:00:00'
}
]
},
"jack@gmail.com": {
"unsub_emails": ['jack@abc.com', 'jack@xls.com'],
"devices": [{
"mac": 'ja:ck:00:00:00:00'
},
{
"mac": 'ja:ck:01:00:00:00'
}
]
},
"simon@gmail.com": {
"unsub_emails": ['simon@yahoo.com', 'simon@pdf.com'],
"devices": [{
"mac": 'si:mo:n0:00:00:00'
},
{
"mac": 'si:mo:n1:00:00:00'
}
]
},
"alex@gmail.com": {
"unsub_emails": ['alex@yahoo.com', 'alex@abc.com'],
"devices": [{
"mac": 'al:ex:00:00:00:00'
},
{
"mac": 'al:ex:01:00:00:00'
}
]
},
"olivia@gmail.com": {
"unsub_emails": ['olivia@yahoo.com', 'olivia@rst.com'],
"devices": [{
"mac": 'ol:iv:ia:00:00:00'
},
{
"mac": 'ol:iv:ia:01:00:00'
}
]
},
"john@gmail.com": {
"unsub_emails": ['john@yahoo.com', 'john@req.com'],
"devices": [{
"mac": 'jo:hn:00:00:00:00'
},
{
"mac": 'jo:hn:01:00:00:00'
}
]
},
"daniel@gmail.com": {
"unsub_emails": ['daniel@yahoo.com', 'daniel@rsp.com', "daniel@inbox.com"],
"devices": [{
"mac": 'da:ni:el:00:00:00'
},
{
"mac": 'da:ni:el:01:00:00'
}
]
},
"moshe@gmail.com": {
"unsub_emails": ['moshe@yahoo.com', 'moshe@abc.com'],
"devices": [{
"mac": 'mo:sh:e0:00:00:00'
},
{
"mac": 'mo:sh:e1:01:00:00'
}
]
},
"julia@gmail.com": {
"unsub_emails": ['julia@yahoo.com', 'julia@abc.com', "julia@yeah.net"],
"devices": [{
"mac": 'ju:li:a0:00:00:00'
},
{
"mac": 'ju:li:a1:00:00:00'
},
{
"mac": 'ju:li:a2:00:00:00'
}
]
}
}
var type_2_value = {
"boolean": function() {
return random_boolean();
},
"string": function() {
return random_string();
},
"int": function(min, max) {
return random_int(min, max);
},
"date": function(format, defval) {
return random_date_data(format, defval);
},
"ip": function(format, defval) {
if ('ipv6' == format) {
return "fe80::5ef9:38ff:fe8d:b764";
}
return random.integer(1, 255) + "." + random.integer(1, 255) + "." + random.integer(1, 255) + "." + random.integer(1, 255);
},
"url": function(format, defval) {
var keys = [];
for (key in app_id_2_app) {
keys.push(key);
}
return app_id_2_app[random_array_data(keys)]['hostname']
},
"user_agent": function() {
return random_user_agent();
},
"rsp_code": function() {
return random_rsp_code();
},
"http_method": function() {
return random_http_method();
},
"person_name": function() {
return random_person_name();
},
"email": function() {
return random_email();
},
"file_name": function() {
return random_file_name();
},
"file_size": function() {
return random_file_size(2, 8);
},
"mac": function() {
return random_mac();
}
}
function random_array_data(arr) {
if (!arr) {
throw "Empty array: " + arr;
}
return arr[random.integer(0, arr.length - 1)];
}
function get_date_str(val, format) {
return val.toFormat(format);
}
function random_date_data(format, defval) {
defval = defval || new Date();
return get_date_str(defval, format);
}
function random_public_ip() {
return random_array_data([
"205.251.245.123",
"221.176.24.154",
"54.84.19.197",
"63.218.211.37",
"54.84.177.105",
"74.125.239.115"
]);
}
function random_user_agent() {
return random_array_data([
"BlackBerry9700/5.0.0.862 Profile/MIDP-2.1 Configuration/CLDC-1.1 VendorID/331 UNTRUSTED/1.0 3gpp-gba",
"Mozilla/5.0 (Linux; U; Android 4.0.4; en-gb; GT-I9300 Build/IMM76D) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30",
"Mozilla/5.0(iPad; U; CPU iPhone OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B314 Safari/531.21.10",
"Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_3; en-us; Silk/1.1.0-80) AppleWebKit/533.16 (KHTML, like Gecko) Version/5.0 Safari/533.16 Silk-Accelerated=true",
"Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0; Touch)",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.131 Safari/537.36",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:29.0) Gecko/20100101 Firefox/29.0",
"Windows NT 5.1; SV1) ; Maxthon; InfoPath.1; .NET CLR 3.5.30729; .NET CLR 3.0.30618)",
"Mozilla/5.0 (Macintosh; U; PPC Mac OS X; nl-nl) AppleWebKit/416.12 (KHTML, like Gecko) Safari/416.13",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:2.0b11) Gecko/20110209 Firefox/ SeaMonkey/2.1b2",
"Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.0.9) Gecko/2009042410 Firefox/3.0.9 Wyzo/3.0.3",
"Mozilla/5.0 (compatible; MSIE 10.6; Windows NT 6.1; Trident/5.0; InfoPath.2; SLCC1; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; .NET CLR 2.0.50727) 3gpp-gba UNTRUSTED/1.0",
"Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)",
"Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; GTB7.4; InfoPath.2; SV1; .NET CLR 3.3.69573; WOW64; en-US)",
"Mozilla/5.0 (Windows; U; MSIE 7.0; Windows NT 6.0; en-US)",
"Mozilla/5.0 (iPhone; CPU iPhone OS 6_1_3 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10B329 Safari/8536.25",
"Mozilla/5.0 (iPhone; CPU iPhone OS 6_1_4 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10B350 Safari/8536.25",
"Mozilla/5.0 (BlackBerry; U; BlackBerry 9900; en) AppleWebKit/534.11+ (KHTML, like Gecko) Version/7.1.0.346 Mobile Safari/534.11+",
"Mozilla/5.0 (Linux; U; Android 4.0.3; ko-kr; LG-L160L Build/IML74K) AppleWebkit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30",
"Mozilla/5.0(iPad; U; CPU iPhone OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B314 Safari/531.21.10",
"Mozilla/5.0 (Linux; <Android Version>; <Build Tag etc.>) AppleWebKit/<WebKit Rev>(KHTML, like Gecko) Chrome/<Chrome Rev> Safari/<WebKit Rev>",
"unknown"
]);
}
function random_string() {
return random_str();
}
function random_int(min, max) {
return random.integer(min || 0, max || 65536);
}
function random_rsp_code() {
return random_array_data([100, 200, 201, 202, 203, 304, 400, 500]);
}
function random_http_method() {
return random_array_data(['GET', 'POST']);
}
function random_person_name() {
return random_array_data(['Jackson', 'Aiden', "Liam", "Lucas", "Justin", "Eric", "David", "Emma", "Mary", "Susan", "Jacob", "Ryan", "Alexander", "James", 'Robert', 'William', 'Jack', 'Simon', 'Alex', 'Olivia', 'John', 'Daniel', 'Moshe', 'Julia']);
}
function random_email(user_name, domain) {
user_name = user_name || random_person_name();
domain = domain || random_array_data(["abc.com", "yahoo.com"]);
return user_name.toLowerCase() + "@" + domain;
}
function random_mac() {
return random_array_data(['5c:f9:38:8d:b7:64', "22:00:0a:41:86:a0"]);
}
function random_file_name(file_name) {
file_name = file_name || random_array_data(['cms_fs.docx', 'overview.doc', "linux.pdf", "jquery.txt", "mootools.xls", "angular.pdf", "emberjs.doc", "jetty.pdf", "spring.doc", "hibernate.pdf", "stratus.xml", "iteye.ppt", "csdn.txt", "netty.pptx", "mina.doc", 'hadoop.xlsx']);
return file_name;
}
function random_file_size(start, end) {
start = start || 2;
end = end || 8
return random_int(start, end) * 1024;
}
function random_boolean() {
return random_array_data([true, false]);
}
function random_app(id) {
var keys = get_all_app_ids();
if (id) {
if (_.isArray(id)) {
keys = id;
} else {
keys = [id];
}
}
return app_id_2_app[random_array_data(keys)];
}
function get_all_app_ids() {
var keys = [];
for (key in app_id_2_app) {
// just for have signature definition apps
if(parseInt(key) < 10000) {
keys.push(key);
}
}
return keys;
}
function random_app_activity_path(app, activity_path_key) {
if (!app || !app.activity_path) {
throw "The app(" + app.hostname + ") does not has activity path";
}
var keys = [];
for (key in app.activity_path) {
keys.push(key)
}
if (activity_path_key) {
if (_.isArray(activity_path_key)) {
keys = activity_path_key;
} else {
keys = [activity_path_key];
}
}
return app.activity_path[random_array_data(keys)];
}
function random_user_info(id) {
var keys = get_all_user_info_keys();
if (id) {
if (_.isArray(id)) {
keys = id;
} else {
keys = [id];
}
}
var key = random_array_data(keys);
var user = user_info[key];
user.sub_email = key;
return user;
}
function get_all_user_info_keys() {
var keys = [];
for (key in user_info) {
keys.push(key);
}
return keys;
}
function random_data(type, format) {
var method = type_2_value[type];
if (!method) {
throw "Can not get random data method with type: " + type + " With format: " + JSON.stringify(format);
}
return method(format);
}
exports.app_id_2_app = app_id_2_app;
exports.random_data = random_data;
exports.random_array_data = random_array_data;
exports.random_public_ip = random_public_ip;
exports.random_user_agent = random_user_agent;
exports.random_string = random_string;
exports.random_int = random_int;
exports.random_rsp_code = random_rsp_code;
exports.random_http_method = random_http_method;
exports.random_person_name = random_person_name;
exports.random_email = random_email;
exports.random_file_name = random_file_name;
exports.random_mac = random_mac;
exports.random_app = random_app;
exports.get_all_app_ids = get_all_app_ids;
exports.random_app_activity_path = random_app_activity_path;
exports.random_user_info = random_user_info;
exports.get_all_user_info_keys = get_all_user_info_keys;
|
// 04-dates/05-get-spooky-fridays/script.js - 4.5: calcul des vendredi 13
(() => {
// your code here
document.getElementById("run").addEventListener("click", () => {
const year = document.getElementById("year").value;
const months = [];
for (let month=0; month<12; month++) {
// Vérifier si le 13eme jour est un vendredi
// si oui, incrémenter de 1
// si non, nothing
let d = new Date(year,month,13);
// Dans la fonction getDay, on commence par le dimanche = 0 => Vendredi = 5
if(d.getDay() == 5){
// On introduit les données obtenues dans le tableau months
months.push(d.toLocaleString('default', { month: 'long' }));
}
}
alert(months);
})
})();
|
(function () {
'use strict';
angular.module('agenda.routes')
.config(['$stateProvider', RouteApp]);
function RouteApp ($stateProvider) {
$stateProvider.state('app', {
url: '/app',
authorize : true,
templateUrl: 'views/menu.html'
});
}
})();
|
import React from 'react'
import { Route } from 'react-router-dom'
import {
App,
Todo,
About,
Topic
} from 'containers'
import { fetchTodos } from './actions/todo'
import './global/global-style.css'
export const routesCollection = [
{
path: '/',
exact: true,
component: Todo,
action: fetchTodos()
},
{
path: '/about',
component: About
},
{
path: '/topic',
component: Topic
}
]
export default () => (
<div>
<App>
{routesCollection.map((route, index) => <Route key={index} {...route} />)}
</App>
</div>
)
|
const express = require("express");
let blogRouter = express.Router();
const Blog = require('../models/blogData')
const Comment = require('../models/commentData')
const methodOverride = require("method-override");
const { ensureAdmin} = require('../config/admin');
const { ensureAuthenticated } = require("../config/auth");
blogRouter.use(methodOverride("_method"));
blogRouter.use(express.urlencoded({ extended: true }));
blogRouter.route("/")
.get(async(req, res) => {
const data = await Blog.find({});
res.render("blog/index",{data})
});
blogRouter.use("/new",ensureAuthenticated,ensureAdmin)
blogRouter.route("/new")
.get((req, res) => {
res.render("blog/new",{});
})
.post(async(req,res)=>{
const blog = req.body;
try{
await Blog.create(blog);
}
catch(err){
console.log( err);
}
res.redirect("/blog")
});
blogRouter.route("/:id")
.get( (req, res) => {
const { id } = req.params;
Blog.findOne({ _id: id }, async function (err, docs) {
if (err) {
console.log(err);
} else {
const comments = await Comment.find({blogID: req.params.id})
// const today = new Date();
// for (const c in comments){
// console.log(c)
// // let storedSecond = c.date.getSeconds()
// // let storedMinutes = c.date.getMinutes()
// // let storedHours = c.date.getHours()
// }
// console.log(comments)
// console.log(storedSecond)
// console.log(storedMinutes)
// console.log(storedHours)
// let nowSecond = today.getSeconds()
// let nowMinutes = today.getMinutes()
// let nowHours = today.getHours()
// console.log(nowSecond)
// console.log(nowMinutes)
// console.log(nowHours)
res.render("blog/show", {comment: comments, data: docs,});
}
});
})
.delete( (req, res) => {
const { id } = req.params;
console.log(id);
Blog.findByIdAndDelete(id, function (err) {
if (err) {
console.log(err);
} else {
res.redirect("/blog");
}
});
})
.patch( (req, res) => {
const { id } = req.params;
const upDatedBlog = req.body;
Blog.findByIdAndUpdate(
id,
{
title: upDatedBlog.title,
image: upDatedBlog.image,
author: upDatedBlog.author,
content: upDatedBlog.content,
},
function (err, docs) {
if (err) {
console.log(err);
} else {
console.log("Updated User : ", docs);
res.redirect("/blog");
}
}
);
})
.put(async(req,res)=>{
const blogID = req.params.id
const userID = req.user._id
const username = req.user.name
const email = req.user.email
const body = req.body.comment;
try{
await Comment.create({
blogID: blogID,
userID: userID,
username: username,
email: email,
body: body,
});
}
catch(err){
console.log( err);
}
res.redirect("/blog"+"/"+ req.params.id)
});
blogRouter.use("/:id/edit",ensureAuthenticated, ensureAdmin)
blogRouter.get("/:id/edit", (req, res) => {
const { id } = req.params;
Blog.findById(id, function (err, docs) {
if (err) {
console.log("error");
} else {
console.log("yo");
res.render("blog/edit", { data: docs });
}
});
});
blogRouter.delete("/comment/:id/",(req,res)=>{
console.log("worked")
const commID = req.body.commID;
console.log(commID)
Comment.findByIdAndDelete(commID , function (err) {
if (err) {
console.log(err);
} else {
res.redirect("/blog/"+ req.params.id);
}
});
})
module.exports = blogRouter;
|
// eslint-disable-next-line no-unused-vars
// function myDeleteFunction() {
//
// // eslint-disable-next-line no-undef
// swal({
// title: 'Are you sure?',
// text: 'You will not be able to recover your account!',
// type: 'warning',
// showCancelButton: true,
// confirmButtonClass: 'btn-danger',
// confirmButtonText: 'Yes, delete!',
// cancelButtonText: 'No, cancel!',
// closeOnConfirm: false,
// closeOnCancel: false
// },
// function (isConfirm) {
// if (isConfirm) {
// // eslint-disable-next-line no-undef
// swal('Deleted!', 'Your account has been deleted.', 'success')
// const endpoint = '/profileEmployer'
// fetch(endpoint, {
// method: 'DELETE',
// })
// .then(response => response.json())
// .then(data => window.location.href = data.redirect)
// .catch(err => console.log(err))
// } else {
// // eslint-disable-next-line no-undef
// swal('Cancelled', 'Your account is safe :)', 'error')
// }
// })
// }
const form = document.querySelector('form')
const emailError = document.querySelector('.email.error')
const passwordError = document.querySelector('.password.error')
const succUpdate = document.querySelector('.update.succ')
const failUpdate = document.querySelector('.update.fail')
var email = ''
var password = ''
var firstName = ''
var lastName = ''
var phoneNumber = ''
var city = ''
var street = ''
var houseNumber = ''
var changePassword = 0//false = no change
function get(e,p,fn,ls,phone,c,s,h) {
email = e
password = p
firstName = fn
lastName = ls
phoneNumber = phone
city = c
street = s
houseNumber = h
}
form.addEventListener('submit', async (e) => {
e.preventDefault()
console.log(email +password+ firstName + lastName + phoneNumber + city + street + houseNumber+ ' !!!!!!!!!!!!!!!')
var myInput1 = document.getElementById('email')
if (myInput1 && myInput1.value) email = form.email.value
//var myInput = document.getElementById('password')
var myInput12 = document.getElementById('confirmationPassword')
if (myInput12 && myInput12.value) {
password = form.password.value
const confirmationPassword = form.confirmationPassword.value
if (password !== confirmationPassword) {
passwordError.textContent = 'Passwords Does not Match'
return
}
else{
changePassword = 1 // true = change
}
}
var myInput2 = document.getElementById('firstName')
if (myInput2 && myInput2.value) firstName = form.firstName.value
var myInput3 = document.getElementById('lastName')
if (myInput3 && myInput3.value) lastName = form.lastName.value
var myInput4 = document.getElementById('phoneNumber')
if (myInput4 && myInput4.value) phoneNumber = form.phoneNumber.value
var myInput5 = document.getElementById('city')
if (myInput5 && myInput5.value) {
city = form.city.value
}
var myInput6 = document.getElementById('street')
if (myInput6 && myInput6.value) {
street = form.street.value
}
var myInput7 = document.getElementById('houseNumber')
if (myInput7 && myInput7.value) {
houseNumber = form.houseNumber.value
}
console.log(email +password+ firstName + lastName + phoneNumber + city + street + houseNumber+ ' !!!!!!!!!!!!!!!')
try {
const res = await fetch('/profileEmployer', {
method: 'POST',
body: JSON.stringify({email, password, firstName, lastName, phoneNumber, city, street, houseNumber,changePassword}),
headers: {'Content-Type': 'application/json'}
})
const data = await res.json()
if (data.errors) {
emailError.textContent = data.errors.email
failUpdate.textContent = 'There was a problem updating the data..Please try again'
}
if (data.user) { //successful
succUpdate.textContent = 'Everything is saved successfully!'
location.assign('/profileEmployer')
}
} catch (err) {
console.log(err)
}
})
|
class Line{
constructor(x1,y1,x2,y2,ratio){
this.ratio = ratio;
this.textX1 = x1*1;
this.textY1 = -y1;
this.textX2 = x2*1;
this.textY2 = -y2;
this.x1 = parseFloat(x1)*this.ratio;
this.y1 = parseFloat(y1)*this.ratio;
this.x2 = parseFloat(x2)*this.ratio;
this.y2 = parseFloat(y2)*this.ratio;
}
drawLine(name){
var x1 = this.x1;
var y1 = this.y1;
var x2 = this.x2;
var y2 = this.y2;
strokeWeight(2);
line(x1,y1,x2,y2);
strokeWeight(10);
point(this.x1, this.y1);
point(this.x2, this.y2);
push();
noStroke();
text(name + ": ("+this.textX1+","+this.textY1+")",this.x1+10 ,this.y1);
text(name + ": ("+this.textX2+","+this.textY2+")",this.x2+10 ,this.y2);
pop();
}
}
class LineCollection{
constructor(ratio){
this.list = new Array();
this.ratio = ratio;
}
addLine(x1,y1,x2,y2){
this.list.push(new Line(x1,y1,x2,y2,this.ratio));
}
remLine(x1,y1,x2,y2){
this.list.pop();
}
updateLine(x1,y1,x2,y2,i){
this.list[i] = new Line(x1,y1,x2,y2,this.ratio);
}
}
class LineController{
constructor(ratio){
this.ratio = ratio
this.lineCol = new LineCollection(this.ratio);
this.totalLine = 0;
}
addLine() {
this.totalLine +=1
var parent = select('#controller-container');
var temp = createDiv(
'<h4> LINE '+ this.totalLine + '</h4>'+
'<input id="line-x1-' + this.totalLine + '" type="number" name="" value="" placeholder="Coordinate x1">' +
'<input id="line-y1-' + this.totalLine + '" type="number" name="" value="" placeholder="Coordinate y1">' +
'<input id="line-x2-' + this.totalLine + '" type="number" name="" value="" placeholder="Coordinate x2">' +
'<input id="line-y2-' + this.totalLine + '" type="number" name="" value="" placeholder="Coordinate y2">'
);
temp.id('vector-card');
parent.child(temp);
this.currX1 = select('#line-x1-'+this.totalLine).value();
this.currY1 = select('#line-y1-'+this.totalLine).value();
this.currX2 = select('#line-x2-'+this.totalLine).value();
this.currY2 = select('#line-y2-'+this.totalLine).value();
this.lineCol.addLine(this.currX1,this.currY1,this.currX2,this.currY2);
}
drawResult(){
if(this.totalLine == 0){
return;
}
else{
for(var i = 0; i < this.totalLine; i++){
this.currX1 = select('#line-x1-'+(i+1)).value();
this.currY1 = select('#line-y1-'+(i+1)).value();
this.currX2 = select('#line-x2-'+(i+1)).value();
this.currY2 = select('#line-y2-'+(i+1)).value();
this.currX1 = this.currX1;
this.currY1 = -this.currY1;
this.currX2 = this.currX2;
this.currY2 = -this.currY2;
this.lineCol.updateLine(this.currX1,this.currY1,this.currX2,this.currY2,i);
fill(255);
this.lineCol.list[i].drawLine("L" + parseInt(i+1));
}
}
}
}
|
// Generated by CoffeeScript 1.8.0
(function() {
var BaseController;
BaseController = (function() {
function BaseController() {
var func, name;
for (name in this) {
func = this[name];
if ((name !== "constructor" && name !== "action") && name.indexOf("__") !== 0) {
if (this.__before__) {
this[name] = this.__wrap__(name, this.__before__, this[name]);
}
if (this.__after__) {
this[name] = this.__wrap__(name, this[name], this.__after__);
}
}
}
}
BaseController.prototype.__wrap__ = function(name, func_a, func_b) {
return function(req, res, next) {
func_a(req, res, next);
return func_b(req, res, next);
};
};
return BaseController;
})();
exports.BaseController = BaseController;
}).call(this);
|
$(function () {
// set the scene size
var WIDTH = 1024,
HEIGHT = 768;
// set some camera attributes
var VIEW_ANGLE = 45,
ASPECT = WIDTH / HEIGHT,
NEAR = 0.1,
FAR = 10000;
// get the DOM element to attach to
// - assume we've got jQuery to hand
var $container = $('#container');
// create a WebGL renderer, camera
// and a scene
var renderer = new THREE.WebGLRenderer();
var camera = new THREE.PerspectiveCamera(VIEW_ANGLE, ASPECT, NEAR, FAR);
var clock = new THREE.Clock();
var scene = new THREE.Scene();
scene.add(camera);
camera.position.y = 50;
camera.position.z = 300;
renderer.setSize(WIDTH, HEIGHT);
$container.append(renderer.domElement);
// create an ambient light
var ambientLight = new THREE.AmbientLight(0x404040);
// set its position
ambientLight.position.x = 0;
ambientLight.position.y = 500;
ambientLight.position.z = 130;
// add to the scene
scene.add(ambientLight);
// create a plane
var width = 500,
height = 500,
widthSegments = width - 1,
heightSegments = height - 1;
var planeGeometry = new THREE.PlaneGeometry(7500, 7500, widthSegments,
heightSegments);
console.log(plane);
var depth = height;
var data = generateHeight( width, depth);
camera.position.y = data[ (width/2) + (depth/2) * width ] + 500;
planeGeometry.applyMatrix( new THREE.Matrix4().makeRotationX( - Math.PI / 2 ) );
for ( var i = 0, l = planeGeometry.vertices.length; i < l; i ++ ) {
planeGeometry.vertices[ i ].y = data[ i ] * 10;
}
var texture = new THREE.Texture( generateTexture( data, width, depth ), new THREE.UVMapping(), THREE.ClampToEdgeWrapping, THREE.ClampToEdgeWrapping );
texture.needsUpdate = true;
var planeMaterial = new THREE.MeshBasicMaterial({ map: texture });
var plane = new THREE.Mesh(planeGeometry, planeMaterial);
console.log(plane);
scene.add(plane);
var controls = new THREE.FirstPersonControls( camera );
controls.movementSpeed = 1000;
controls.lookSpeed = 0.1;
// draw!
renderer.render(scene, camera);
(function animate() {
requestAnimationFrame(animate);
controls.update( clock.getDelta() );
renderer.render(scene, camera);
})();
function generateHeight( width, height ) {
var size = width * height,
data = new Float32Array(size),
perlin = new ImprovedNoise(),
quality = 1,
z = Math.random() * 100;
for ( var i = 0; i < size; i ++ ) {
data[ i ] = 0
}
for ( var j = 0; j < 4; j ++ ) {
for ( var i = 0; i < size; i ++ ) {
var x = i % width, y = ~~ ( i / width );
data[ i ] += Math.abs( perlin.noise( x / quality, y / quality, z ) * quality * 1.75 );
}
quality *= 5;
}
return data;
}
function generateTexture( data, width, height ) {
var canvas, canvasScaled, context, image, imageData,
level, diff, vector3, sun, shade;
vector3 = new THREE.Vector3( 0, 0, 0 );
sun = new THREE.Vector3( 1, 1, 1 );
sun.normalize();
canvas = document.createElement( 'canvas' );
canvas.width = width;
canvas.height = height;
context = canvas.getContext( '2d' );
context.fillStyle = '#000';
context.fillRect( 0, 0, width, height );
image = context.getImageData( 0, 0, canvas.width, canvas.height );
imageData = image.data;
for ( var i = 0, j = 0, l = imageData.length; i < l; i += 4, j ++ ) {
vector3.x = data[ j - 2 ] - data[ j + 2 ];
vector3.y = 2;
vector3.z = data[ j - width * 2 ] - data[ j + width * 2 ];
vector3.normalize();
shade = vector3.dot( sun );
imageData[ i ] = ( 96 + shade * 128 ) * ( 0.5 + data[ j ] * 0.007 );
imageData[ i + 1 ] = ( 32 + shade * 96 ) * ( 0.5 + data[ j ] * 0.007 );
imageData[ i + 2 ] = ( shade * 96 ) * ( 0.5 + data[ j ] * 0.007 );
}
context.putImageData( image, 0, 0 );
// Scaled 4x
canvasScaled = document.createElement( 'canvas' );
canvasScaled.width = width * 4;
canvasScaled.height = height * 4;
context = canvasScaled.getContext( '2d' );
context.scale( 4, 4 );
context.drawImage( canvas, 0, 0 );
image = context.getImageData( 0, 0, canvasScaled.width, canvasScaled.height );
imageData = image.data;
for ( var i = 0, l = imageData.length; i < l; i += 4 ) {
var v = ~~ ( Math.random() * 5 );
imageData[ i ] += v;
imageData[ i + 1 ] += v;
imageData[ i + 2 ] += v;
}
context.putImageData( image, 0, 0 );
return canvasScaled;
}
function ImprovedNoise() {
var p = [151,160,137,91,90,15,131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,
23,190,6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33,88,237,149,56,87,
174,20,125,136,171,168,68,175,74,165,71,134,139,48,27,166,77,146,158,231,83,111,229,122,60,211,
133,230,220,105,92,41,55,46,245,40,244,102,143,54,65,25,63,161,1,216,80,73,209,76,132,187,208,
89,18,169,200,196,135,130,116,188,159,86,164,100,109,198,173,186,3,64,52,217,226,250,124,123,5,
202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42,223,183,170,213,119,
248,152,2,44,154,163,70,221,153,101,155,167,43,172,9,129,22,39,253,19,98,108,110,79,113,224,232,
178,185,112,104,218,246,97,228,251,34,242,193,238,210,144,12,191,179,162,241,81,51,145,235,249,
14,239,107,49,192,214,31,181,199,106,157,184,84,204,176,115,121,50,45,127,4,150,254,138,236,205,
93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180];
for (var i=0; i < 256 ; i++) {
p[256+i] = p[i];
}
function fade(t) {
return t * t * t * (t * (t * 6 - 15) + 10);
}
function lerp(t, a, b) {
return a + t * (b - a);
}
function grad(hash, x, y, z) {
var h = hash & 15;
var u = h < 8 ? x : y, v = h < 4 ? y : h == 12 || h == 14 ? x : z;
return ((h&1) == 0 ? u : -u) + ((h&2) == 0 ? v : -v);
}
return {
noise: function (x, y, z) {
var floorX = ~~x, floorY = ~~y, floorZ = ~~z;
var X = floorX & 255, Y = floorY & 255, Z = floorZ & 255;
x -= floorX;
y -= floorY;
z -= floorZ;
var xMinus1 = x -1, yMinus1 = y - 1, zMinus1 = z - 1;
var u = fade(x), v = fade(y), w = fade(z);
var A = p[X]+Y, AA = p[A]+Z, AB = p[A+1]+Z, B = p[X+1]+Y, BA = p[B]+Z, BB = p[B+1]+Z;
return lerp(w, lerp(v, lerp(u, grad(p[AA], x, y, z),
grad(p[BA], xMinus1, y, z)),
lerp(u, grad(p[AB], x, yMinus1, z),
grad(p[BB], xMinus1, yMinus1, z))),
lerp(v, lerp(u, grad(p[AA+1], x, y, zMinus1),
grad(p[BA+1], xMinus1, y, z-1)),
lerp(u, grad(p[AB+1], x, yMinus1, zMinus1),
grad(p[BB+1], xMinus1, yMinus1, zMinus1))));
}
}
}
});
|
function main(){
video_1 = document.getElementById('video_1');
video_1.volume = 0.0;
video_2 = document.getElementById('video_2');
video_2.volume = 0.0;
video_3 = document.getElementById('video_3');
video_3.volume = 0.0;
display = document.getElementById("display")
// Tamaño de los video_s
video_1.width = 300;
video_1.height = 200;
video_2.width = 300;
video_2.height = 200;
video_3.width = 300;
video_3.height = 200;
display.width = 250;
display.height = 200;
//Audio onmouse video_ 1
video_1.onmouseover = () => {
console.log('Audio ON!')
video_1.muted = false;
video_1.style.backgroundColor = "lightgray"
}
video_1.onmouseout = () => {
console.log('Audio OFF')
video_1.muted =true;
video_1.style.backgroundColor = ""
}
plano1 = document.getElementById('plano1');
plano1.onclick = () => {
display.src ="https://gsyc.urjc.es/jmplaza/csaai/realizador-fuente1.mp4";
}
// Audio onmouse video_ 2
video_2.onmouseover = () => {
console.log('Audio ON!')
video_2.muted = false;
video_2.style.backgroundColor = "lightgray"
}
video_2.onmouseout = () => {
console.log('Audio OFF')
video_2.muted =true;
video_2.style.backgroundColor = ""
}
plano2 = document.getElementById('plano2');
plano2.onclick = () => {
display.src ="https://gsyc.urjc.es/jmplaza/csaai/realizador-fuente2.mp4";
}
// Audio onmouse video_ 3
video_3.onmouseover = () => {
console.log('Audio ON!')
video_3.muted = false;
video_3.style.backgroundColor = "lightgray"
}
video_3.onmouseout = () => {
console.log('Audio OFF')
video_3.muted =true;
video_3.style.backgroundColor = ""
}
plano3 = document.getElementById('plano3');
plano3.onclick = () => {
display.src ="https://gsyc.urjc.es/jmplaza/csaai/realizador-fuente3.mp4";
}
}
|
/* global isWeChatMiniProgram */
const props = [{
name: 'nodes',
get(domNode) {
return domNode.getAttribute('nodes') || [];
},
}];
if (isWeChatMiniProgram) {
props.push({
name: 'space',
get(domNode) {
return domNode.getAttribute('space') || '';
},
});
}
export default {
name: 'rich-text',
props,
handles: {},
};
|
/// <reference path="D:\Shop\Git\Shop.Web\Assets/admin/libs/angular/angular.js" />
(function () {
angular.module('shop.application_roles', ['shop.common']).config(config);
function config($stateProvider, $urlRouterProvider) {
$stateProvider
.state('application_roles', {
url: '/application_roles',
parent: 'base',
templateUrl: '/app/components/application_roles/applicationRolesListView.html',
controller: 'applicationRolesListController'
})
.state('add_application_roles', {
url: '/add_application_roles',
parent: 'base',
templateUrl: '/app/components/application_roles/applicationRolesAddView.html',
controller: 'applicationRolesAddController'
})
.state('edit_application_roles', {
url: '/edit_application_roles/:id',
parent: 'base',
templateUrl: '/app/components/application_roles/applicationRolesEditView.html',
controller: 'applicationRolesEditController'
});
}
})();
|
//Se importan los types
import {
SAVE_RANDOM_CUSTOMER_ID,
SAVE_RANDOM_CUSTOMER_ID_EXIT
} from '../types';
/**cada reducer tiene su propio state */
/*el state siempre es un objeto, pensar que propiedades
debe tener el state de customer
*/
const initialState={
id:null,
error: null
}
/*El reducer siempre es una función, el state si no se pasa va a ser el stata inicial
el store pasa el store y la acción a ejecutar (action), en el action siempre se pasa un type
el reducer debe ser una función pura, no debe realizar side effects
No debe mutar los argumentos
No debe llamar a funciones no puras (Date.now(), Math.random(), etc)
*/
export default function (state=initialState, action){
switch(action.type){
/*Aquí van todos los case que van a describir lo que va a pasar en la app
y van a ir cambiando el state, de acuerdo a algo llamado el payload
siempre hay que retornar uno por default;
*/
case SAVE_RANDOM_CUSTOMER_ID:
return {
...state,
error:action.payload
}
case SAVE_RANDOM_CUSTOMER_ID_EXIT:
return {
...state,
id:action.payload,
error: false
}
default:
return state;
}
}
|
angular.module('zingClient')
.directive('zingChartList', function() {
return {
restrict: 'E',
templateUrl: '/app/charts/views/list.html',
controller: 'ChartListCtrl'
};
})
.directive('zingchart', function() {
return {
restrict: 'A',
scope: {
options: '=zcData'
},
link: function($scope, $elem, attrs) {
var options = $.extend( {id: attrs.id}, $scope.options);
zingchart.render( options );
}
}
});
|
import React, { PureComponent } from 'react'
import {
View,
Modal,
Text,
StyleSheet,
Dimensions,
Button,
TouchableOpacity,
Clipboard,
Linking,
Share,
Alert
} from 'react-native'
import { isUri } from 'valid-url'
import { MaterialCommunityIcons } from '@expo/vector-icons'
import colors from '../constants/colors'
import { openURL } from '../utils'
class ResultModal extends PureComponent {
render () {
const { onDone, show, data, type } = this.props
return (
<Modal
animationType='slide'
transparent
visible={show}
onRequestClose={onDone}
>
<View style={[StyleSheet.absoluteFill, styles.overlay]}>
<View style={styles.resultContainer}>
<Text style={styles.title}>Code Found!</Text>
<Text selectable style={styles.result}>
{data}
</Text>
<View style={styles.actionContainer}>
<TouchableOpacity
style={styles.action}
onPress={() => this.handleCopyToClipboard(data)}
>
<MaterialCommunityIcons
size={40}
name={'content-copy'}
color={colors.primary}
/>
</TouchableOpacity>
<TouchableOpacity
style={styles.action}
onPress={() => this.handleShare(data)}
>
<MaterialCommunityIcons
size={40}
name={'share'}
color={colors.primary}
/>
</TouchableOpacity>
{isUri(data) && (
<TouchableOpacity
style={styles.action}
onPress={() => this.handleOpenLink(data)}
>
<MaterialCommunityIcons
size={40}
name={'link'}
color={colors.primary}
/>
</TouchableOpacity>
)}
</View>
<Button title='DONE' onPress={onDone} color={colors.secondary} />
</View>
</View>
</Modal>
)
}
handleCopyToClipboard = str => {
Clipboard.setString(str)
Alert.alert('Done!', 'Copied to clipboard')
}
handleOpenLink = async url => {
try {
await openURL(url)
} catch (error) {
Alert.alert('Oops!', "We can't open the url")
}
}
handleShare = message => {
Share.share({
title: 'Scanned with Swifty QR',
message
})
}
}
const styles = StyleSheet.create({
overlay: {
backgroundColor: colors.overlay,
alignItems: 'center',
justifyContent: 'center'
},
resultContainer: {
marginTop: 30,
width: '70%',
height: '60%',
backgroundColor: colors.white,
borderRadius: 2,
alignItems: 'center',
padding: 15
},
actionContainer: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-around'
},
action: { padding: 5, margin: 10 },
title: { color: colors.black, fontSize: 18, fontWeight: '500' },
result: { flex: 1, textAlign: 'center', overflow: 'hidden', marginTop: 20 },
})
export default ResultModal
|
/**
* 网站发布管理
*
* @class DynamicStaticPairManagePanel
* @extends Disco.Ext.CrudPanel
*/
DynamicStaticPairManagePanel = Ext.extend(Disco.Ext.CrudPanel, {
id: "dynamicStaticPairPanel",
// title:"网站发布管理",
baseUrl: "publish.java",
pageSize: 20,
viewWin: {
width: 600,
height: 185,
title: "详情查看"
},
createForm: function() {
console.log(ConfigConst.BASE)
var formPanel = new Ext.form.FormPanel({
frame: true,
labelWidth: 60,
labelAlign: 'right',
defaults: {
width: 400,
xtype: "textfield"
},
items: [{
xtype: "hidden",
name: "id"
}, Disco.Ext.Util.columnPanelBuild({
columnWidth: .60,
items: [{
name: "title",
anchor: '98%',
fieldLabel: "页面名称"
}]
}, {
columnWidth: .40,
items: [Ext.applyIf({
anchor: '94%'
}, ConfigConst.BASE.getDictionaryCombo("intervals", "自动周期", "pageRelease", "value"))]
}), {
fieldLabel: "动态地址",
name: "url"
}, {
fieldLabel: "静态地址",
name: "path"
}]
});
return formPanel;
},
createWin: function() {
return this.initWin(500, 160, "页面静态化配置......");
},
storeMapping: ["id", "url", "path", "title", "intervals", "status", "vdate"],
initComponent: function() {
this.cm = new Ext.grid.ColumnModel([{
header: "名称",
sortable: true,
width: 200,
dataIndex: "title"
}, {
header: "动态地址",
sortable: true,
width: 350,
dataIndex: "url"
}, {
header: "静态地址",
sortable: true,
width: 180,
dataIndex: "path"
}, {
header: "发布周期",
sortable: true,
width: 70,
dataIndex: "intervals"
}, {
header: "上次发布时间",
sortable: true,
width: 120,
dataIndex: "vdate",
renderer: this.dateRender()
}]);
this.gridButtons = [new Ext.Toolbar.Separator(), {
text: "静态生成",
iconCls: 'changeState',
// pressed : true,
handler: this.executeMulitCmd("generator"),
scope: this
}];
DynamicStaticPairManagePanel.superclass.initComponent.call(this);
}
});
|
import React, { Component } from 'react';
import './App.css';
import { BrowserRouter as Router, Route } from 'react-router-dom';
import About from './components/About';
import Music from './components/Music';
import Video from './components/Video';
import Signup from './components/Signup';
import Navbar from './components/CustomNavbar';
class App extends Component {
render() {
return (
<Router>
<div>
<Navbar />
<Route exact path="/" component={About} />
<Route path="/music" component={Music} />
<Route path="/video" component={Video} />
<Route path="/sign-up" component={Signup} />
</div>
</Router>
);
}
}
export default App;
|
/* global G7 */
$(function() {
'use strict';
(function($, window, undefined) {
/**
* @name Contact
* @memberof G7.Pages
* @description Holds the developer defined Contact Behavior Methods.
*/
G7.Pages.Contact = (function() {
/**
* @scope G7.Pages.Contact
* @description Exposed methods from the G7.Pages.Contact Module.
*/
return {
/**
* @name init
* @description G7.Pages.Contact Module Constructor.
*/
init: (function() {
})()
};
}());
})(jQuery, window);
});
|
// function that read the images dir and return an arr of the files`
var fs = require('fs');
function GetImage() {
return fs.readdirSync('/tmp/resources'); // Img folder here.
}
module.exports={
GetImage:GetImage
}
|
// Nahian Alam
// alam.nahian18@gmail.com
//https://nahian-alam.nahian18.workers.dev/
addEventListener("fetch", (event) => {
event.respondWith(handleRequest(event.request));
});
/**
* Respond with hello worker text
* @param {Request} request
*/
let links = []; // Array used to store the links that is received from the fetch request
// Function used to fetch data from the given link
async function setUrlData() {
let dataD = await fetch(
"https://cfw-takehome.developers.workers.dev/api/variants"
);
await Promise.resolve(dataD.json()).then(function (val) {
links = val.variants; // URL links received from the fetch request is being stored in the links array
});
}
// Function to test if load is evenly distributed
// This function is not used to determine the output
// It is only a way of showing that one of the two links
// have approximately 50% chance of getting picked
async function testChoicePercentage() {
let choice1 = 0;
let choice2 = 0;
for (i = 0; i < 10000; i++) {
var randomSelectedLink = links[~~(Math.random() * links.length)];
if (randomSelectedLink == links[0]) {
choice1 += 1;
} else {
choice2 += 1;
}
}
console.log(choice1 / 10000); // Roughly 0.50
console.log(choice2 / 10000); // Roughly 0.50
}
async function getRandomResponse() {
var randomSelectedLink = links[~~(Math.random() * links.length)]; // Index 0 or 1 is selected at random with a 50% chance
let recievedResponse = await fetch(randomSelectedLink); // A fetch request is sent using the url and response saved
return recievedResponse; // response is returned
}
async function handleRequest(request) {
await setUrlData(); // Function called to fetch url data
let response1 = await getRandomResponse(); // Random response received
return response1; // Variant 1 or 2 is returned on random
}
|
import React from 'react'
import {render} from 'react-dom';
console.log('hi')
let title="don't lose hopa!"
render(<div>{title}</div>,document.getElementById('app'))
// module.hot.accept();
|
import React, {Component} from 'react';
import {StyleSheet, Text, View, TouchableOpacity, StatusBar} from 'react-native';
import Modal from "react-native-modal";
import Icon from '../icons';
import { Input } from 'react-native-elements';
export default class DisplayModal extends Component {
constructor(props){
super(props);
this.state = {
input: '',
text: ''
};
}
// WHEN LONG PRESS LISTS ITEM - SHOW THIS MODAL - DELETE MODAL
renderDeleteModal = () => (
<View style={styles.modalContent}>
<View style={{ position: 'absolute', top: 10 ,right: 10, padding: 0, marginTop:0 }}>
<TouchableOpacity onPress={ () => this.props.function()} >
<Icon.Foundation color='#666666' name="x" size={30} />
</TouchableOpacity>
</View>
<Text style={styles.text}>Delete List</Text>
<View style={{ marginTop: 8 }}>
<Text style={{ fontSize: 22 }}>{this.props.listName}</Text>
</View>
<View style={{ marginTop: 25 ,width: "60%"}}>
<TouchableOpacity style={[styles.button, { backgroundColor: '#f44336' }]} onPress={() => this.props.deleteFunction()}>
<Text style={{ fontSize: 18, color: '#fff' }}>Delete</Text>
</TouchableOpacity>
</View>
</View>
);
// WHEN PRESS ADD BUTTON ON LISTS - SHOW THIS MODAL - ADD MODAL
renderModalContent = () => (
<View style={styles.modalContent}>
<View style={{ position: 'absolute', top: 10 ,right: 10, padding: 0, marginTop:0 }}>
<TouchableOpacity onPress={ () => this.props.function()} >
<Icon.Foundation color='#666666' name="x" size={30} />
</TouchableOpacity>
</View>
<Text style={styles.text}>New List</Text>
<Input
containerStyle={{ marginTop: 12 }}
placeholder='Type here'
inputContainerStyle={{ borderBottomWidth: 2, borderRadius: 10 }}
onChangeText={(text) => this.setState({text})}
leftIcon={
<Icon.MaterialCommunityIcons
name='pencil'
size={24}
color='black'
/>
}
/>
<View style={{ marginTop: 25 ,width: "60%"}}>
<TouchableOpacity style={styles.button} onPress={() => this.props.input(this.state.text)}>
<Text style={{ fontSize: 18, color: '#fff' }}>Add</Text>
</TouchableOpacity>
</View>
</View>
);
render(){
return(
<Modal
isVisible={this.props.display === true}
animationIn='bounceIn'
onBackdropPress={() => this.props.function()}
useNativeDriver={ true }
>
<View>
<StatusBar backgroundColor="rgba(0,0,0,0.7)" barStyle="light-content"/>
</View>
{this.props.whichModal ? this.renderModalContent() : this.renderDeleteModal()}
</Modal>
)}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "center",
alignItems: "center"
},
button: {
backgroundColor: "#1b9af7",
marginLeft: 10,
marginRight: 10,
padding: 8,
justifyContent: "center",
alignItems: "center",
borderRadius: 8,
borderColor: "rgba(0, 0, 0, 0.1)"
},
modalContent: {
backgroundColor: "white",
margin: 0,
paddingLeft: 20,
paddingRight: 20,
paddingTop: 0,
paddingBottom: 25,
justifyContent: "center",
alignItems: "center",
borderRadius: 8,
borderColor: "rgba(0, 0, 0, 0.1)"
},
text: {
fontSize: 35,
marginTop: 20
}
});
|
import React from 'react';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
import MainContainer from 'containers/main';
import estGestionnaire, { estAssistance } from 'utils/roles';
import './app.css';
import VersionComponent from '../version/version';
export default function App({ roles }) {
const isGestionnaire = estGestionnaire(roles);
const isAssistance = estAssistance(roles);
return (
<>
{(isAssistance || isGestionnaire) && (
<BrowserRouter>
<Switch>
<Route path="/:id" render={routeProps => <MainContainer {...routeProps} />} />
<Route exact path="/" render={routeProps => <MainContainer {...routeProps} />} />
</Switch>
</BrowserRouter>
)}
{!isAssistance && !isGestionnaire && (
<>
<h1>{`Vous n'êtes pas autorisé à accéder à cette application`}</h1>
<VersionComponent />
</>
)}
</>
);
}
|
const _ = require('lodash')
const requireNoCache = require('../src/helpers/require-no-cache.js')
const getFTLProductList = () => {
const ftlProductList = requireNoCache('../mock-data/product-list.json')
return _.cloneDeep(ftlProductList)
}
module.exports = getFTLProductList
|
module.exports = {
title: 'JavaScript入門1',
subtitle: 'データの出力',
language: 'javascript',
defaultValue: `function hello() {
// 文字列"Hello World!"を出力してみよう
}
hello()
`,
answer: `function hello() {
// 文字列"Hello World!"を出力してみよう
console.log("Hello World!")
}
hello()
`,
correctOutput: 'Hello World!',
isNextQuestion: true,
nextLessonId: "001"
}
|
const expect = require('expect.js');
const int = require('./int');
const part2 = require('./part2');
describe('Day 05: Part 1', () => {
it('Should support parameter modes of instructions', () => {
expect(int([1002, 4, 3, 4, 33], [])).to.eql([]);
});
it('Should support reading input and printing output', () => {
expect(int([3, 0, 4, 0, 99], [123])).to.eql([123]);
});
});
describe('Day 05: Part 2', () => {
it('Should support equal oppcode with position mode', () => {
expect(int([3, 9, 8, 9, 10, 9, 4, 9, 99, -1, 8], [8])).to.eql([1]);
expect(int([3, 9, 8, 9, 10, 9, 4, 9, 99, -1, 8], [7])).to.eql([0]);
});
it('Should support less than oppcode with position mode', () => {
expect(int([3, 9, 7, 9, 10, 9, 4, 9, 99, -1, 8], [7])).to.eql([1]);
expect(int([3, 9, 7, 9, 10, 9, 4, 9, 99, -1, 8], [9])).to.eql([0]);
});
it('Should support equal oppcode with immediate mode', () => {
expect(int([3, 3, 1108, -1, 8, 3, 4, 3, 99], [8])).to.eql([1]);
expect(int([3, 3, 1108, -1, 8, 3, 4, 3, 99], [7])).to.eql([0]);
});
it('Should support less than oppcode with immediate mode', () => {
expect(int([3, 3, 1107, -1, 8, 3, 4, 3, 99], [7])).to.eql([1]);
expect(int([3, 3, 1107, -1, 8, 3, 4, 3, 99], [9])).to.eql([0]);
});
it('Should support jump oppcode with position mode', () => {
expect(int([3, 12, 6, 12, 15, 1, 13, 14, 13, 4, 13, 99, -1, 0, 1, 9], [1])).to.eql([1]);
expect(int([3, 12, 6, 12, 15, 1, 13, 14, 13, 4, 13, 99, -1, 0, 1, 9], [0])).to.eql([0]);
});
it('Should support jump oppcode with immediate mode', () => {
expect(int([3, 3, 1105, -1, 9, 1101, 0, 0, 12, 4, 12, 99, 1], [1])).to.eql([1]);
expect(int([3, 3, 1105, -1, 9, 1101, 0, 0, 12, 4, 12, 99, 1], [0])).to.eql([0]);
});
});
|
import React, {Component} from 'react';
import './App.css';
import ValidationComponent from "./ValidationComponent";
import CharComponent from "./CharComponent";
class App extends Component {
constructor(properties) {
super(properties)
this.state = {"inputLength": 0, "inputText": ""}
}
changeInput = (event, index) => {
const valueToSet = event.target.value;
this.setState(
(oldState, setStateMethod) => {
return {"inputLength": valueToSet.length, "inputText": valueToSet}
}
);
}
removeChar = (index) => {
const indexForRemoving = index;
this.setState((oldState) => {
if (oldState.inputText) {
var textInArray = oldState.inputText.split('');
textInArray.splice(indexForRemoving, 1);
const returnText = textInArray.join('')
return {"inputText": returnText, "inputLength": returnText.length}
}else{
return {}
}
})
}
render() {
const inputTextElements = this.state.inputText ? this.state.inputText.split('') : [];
return (
<div className="App">
<ol>
<input onChange={this.changeInput} value={this.state.inputText} />
<p>{this.state.inputLength}</p>
<ValidationComponent textLength={this.state.inputLength}></ValidationComponent>
{inputTextElements.map((eachChar, position) => <CharComponent key={position} keyValue={position} highlightSelected="white" charIndex={position} removeChar={this.removeChar} letter={eachChar}/>)}
<br/>
<br/>
<li>Create an input field (in App component) with a change listener which outputs the length of the
entered text below it (e.g. in a paragraph).
</li>
<li>Create a new component (=> ValidationComponent) which receives the text length as a prop</li>
<li>Inside the ValidationComponent, either output "Text too short" or "Text long enough" depending
on the text length (e.g. take 5 as a minimum length)
</li>
<li>Create another component (=> CharComponent) and style it as an inline box (=> display:
inline-block, padding: 16px, text-align: center, margin: 16px, border: 1px solid black).
</li>
<li>Render a list of CharComponents where each CharComponent receives a different letter of the
entered text (in the initial input field) as a prop.
</li>
<li>When you click a CharComponent, it should be removed from the entered text.</li>
</ol>
<p>Hint: Keep in mind that JavaScript strings are basically arrays!</p>
</div>
);
}
}
export default App;
|
test('arr06', () => {
const myArray = bool => [
bool,
'YES'
]
console.log(myArray(true))
});
|
import Vue from 'vue';
import VueI18n from 'vue-i18n';
import lvLV from '../locales/lv_LV.yml';
import ruLV from '../locales/ru_LV.yml';
// Use i18n
Vue.use(VueI18n);
export default new VueI18n({
locale: process.env.VUE_APP_LOCALE,
messages: {
lv_LV: lvLV,
ru_LV: ruLV,
},
});
|
'use strict';
var React = require('react');
var Card = require('../../card');
var Field = require('../../field');
var skill = require('../../../sw2/skill');
var ProtectionEvasion = React.createClass({
render: function () {
var data = this.props.data;
var readOnly = this.props.readOnly;
var onChange = this.props.onChange;
var rowStyle = {
display: 'flex',
};
var evasion_skill = (data.skills || []).map(function (skill) {
return skill.name;
}).filter(skill.isEvasionSkill)
.map(function (name) {
return {
text: name,
payload: name
};
});
return (
<div>
<div style={rowStyle}>
<Card className="armor">
<div style={rowStyle}>
<Field path="armor.name" label="鎧" data={data} readOnly={readOnly} onChange={onChange} />
</div>
<div style={rowStyle}>
<Field path="armor.str_req" label="必筋" type="number"
data={data} readOnly={readOnly} onChange={onChange} />
</div>
<div style={rowStyle}>
<Field path="armor.protection" label="防護点" type="number"
data={data} readOnly={readOnly} onChange={onChange} />
</div>
<div style={rowStyle}>
<Field path="armor.evasion" label="回避" type="number"
data={data} readOnly={readOnly} onChange={onChange} />
</div>
<div style={rowStyle}>
<Field path="armor.memo" label="メモ"
multiline={true} data={data} readOnly={readOnly} onChange={onChange} />
</div>
</Card>
<Card className="shield">
<div style={rowStyle}>
<Field path="shield.name" label="盾" data={data} readOnly={readOnly} onChange={onChange} />
</div>
<div style={rowStyle}>
<Field path="shield.str_req" label="必筋" type="number"
data={data} readOnly={readOnly} onChange={onChange} />
</div>
<div style={rowStyle}>
<Field path="shield.protection" label="防護点" type="number"
data={data} readOnly={readOnly} onChange={onChange} />
</div>
<div style={rowStyle}>
<Field path="shield.evasion" label="回避" type="number"
data={data} readOnly={readOnly} onChange={onChange} />
</div>
<div style={rowStyle}>
<Field path="shield.memo" label="メモ"
multiline={true} data={data} readOnly={readOnly} onChange={onChange} />
</div>
</Card>
</div>
<Card key="2" className="evasion">
<div style={rowStyle}>
<Field path="evasion_skill" label="回避技能" type="select"
options={evasion_skill} data={data} readOnly={readOnly} onChange={onChange} />
</div>
<div style={rowStyle}>
<Field path="protection" label="防護点" type="number"
multiline={true} data={data} readOnly={true} />
<Field path="evasion" label="回避力" type="number"
multiline={true} data={data} readOnly={true} />
</div>
</Card>
</div>
);
}
});
module.exports = ProtectionEvasion;
|
import PropTypes from 'prop-types';
import { Helmet } from 'react-helmet';
import React, { useState } from 'react';
import { Link } from 'gatsby';
import {
Grid, Header, Image,
} from 'semantic-ui-react';
import Layout from './Layout';
function ProductImage({ id, imagenPrincipal, palabraClave }) {
// eslint-disable-next-line no-unused-vars
const [loading, setLoading] = useState(true);
return (
<Grid.Column
key={id}
computer="2"
tablet="5"
mobile="7"
textAlign="center"
verticalAlign="bottom"
>
<Image
as={Link}
className="zoom"
to={`/producto/${id}`}
src={imagenPrincipal}
onLoad={() => setLoading(false)}
fluid
/>
<Header size="small" style={{ marginBottom: '1em' }}>
{palabraClave}
</Header>
</Grid.Column>
);
}
ProductImage.propTypes = {
id: PropTypes.number.isRequired,
imagenPrincipal: PropTypes.string.isRequired,
palabraClave: PropTypes.string.isRequired,
};
function Products({ pageContext }) {
const { productos } = pageContext;
return (
<Layout>
<Helmet>
{/* General tags */}
<title>EXMEX - Productos</title>
<meta
name="description"
content={[
'EXTRACTOR PARA JUGO DE ZANAHORIA Y LEGUMBRES EN ACERO INOXIDABLE', 'EXTRACTOR PARA JUGO DE ZANAHORIA Y LEGUMBRES EN ALUMINIO',
'EXTRACTOR PARA JUGO DE ZANAHORIA Y LEGUMBRES AUTOMÁTICO DE EXPULSIÓN AUTOMÁTICA DE BAGAZO',
'EXPRIMIDOR DE JUGOS PARA CÍTRICOS EN ACERO INOXIDABLE',
'EXPRIMIDOR DE JUGOS PARA CÍTRICOS EN ALUMINIO',
'LICUADORA EN ACERO INOXIDABLE 3L',
'LICUADORA EN ACERO INOXIDABLE 5L',
'TRITURADOR PARA HIELO D-6',
].join('\n')}
/>
{/* <meta name="image" content={image} /> */}
</Helmet>
<Grid padded>
<Grid.Row centered>
<Grid.Column
computer="14"
tablet="15"
mobile="15"
>
<Header size="huge">
NUESTROS PRODUCTOS
</Header>
</Grid.Column>
</Grid.Row>
<Grid.Row centered>
{
productos.map(({ id, imagenPrincipal, palabraClave }) => (
<ProductImage id={id} imagenPrincipal={imagenPrincipal} palabraClave={palabraClave} />
))
}
</Grid.Row>
</Grid>
</Layout>
);
}
Products.propTypes = {
pageContext: PropTypes.shape({
productos: PropTypes.arrayOf(PropTypes.object),
}).isRequired,
};
export default Products;
|
// An avid hiker keeps meticulous records of their hikes. During the last hike that took exactly steps, for every step it was noted if it was an uphill, , or a downhill, step. Hikes always start and end at sea level, and each step up or down represents a unit change in altitude. We define the following terms:
// A mountain is a sequence of consecutive steps above sea level, starting with a step up from sea level and ending with a step down to sea level.
// A valley is a sequence of consecutive steps below sea level, starting with a step down from sea level and ending with a step up to sea level.
// Given the sequence of up and down steps during a hike, find and print the number of valleys walked through.
// Example
// The hiker first enters a valley units deep. Then they climb out and up onto a mountain units high. Finally, the hiker returns to sea level and ends the hike.
// Function Description
// Complete the countingValleys function in the editor below.
// countingValleys has the following parameter(s):
// int steps: the number of steps on the hike
// string path: a string describing the path
// Returns
// int: the number of valleys traversed
// Input Format
// The first line contains an integer , the number of steps in the hike.
// The second line contains a single string , of characters that describe the path.
// Constraints
// Sample Input
// 8
// UDDDUDUU
// Sample Output
// 1
// Explanation
// If we represent _ as sea level, a step up as /, and a step down as \, the hike can be drawn as:
// _/\ _
// \ /
// \/\/
// The hiker enters and leaves one valley.
// logic:
// Turn string into an array with -1 for D and 1 for U
// set a variable to record if sea level is reached and a variable to count valleys
// run a loop to chek if sea level was reached and if the last added value was a positive
// if condition passes the hicker came from a valey
function countingValleys(steps, path) {
const array = path.split('').map(el => {if (el==='U') { return 1} else {return -1}});
let valleys = 0
let actions = array[0];
for (let i=1; i<steps; i++) {
actions+=array[i];
if (actions === 0 && array[i]>0) {
valleys++;
}
}
return valleys;
}
console.log(countingValleys(8, 'DDUUUUDD'))
|
import request from '@/utils/request';
// 获取商品列表
export const getProductList = params => {
return request({
url: '/product/list',
params
})
}
//获取商品列表,用于级联选择
export const getProductListWithChildren = () => {
return request({
url: '/productCategory/list/withChildren'
})
}
//获取品牌列表
export const getBrandList = params => {
return request({
url: '/brand/list',
params
})
}
//根据id删除某品牌
export const deleteBrandById = id => {
return request({
url: '/brand/delete/'+id
})
}
//删除某商品
export const updateDeleteStatus = params => {
return request({
url: '/product/update/deleteStatus',
method: 'post',
params
})
}
//更新品牌的显示状态
export const updateBrandShowStatus = data => {
return request({
url: '/brand/update/showStatus',
method: 'post',
data
})
}
//根据商品id获取产品信息
export const getProductInfo = id => {
return request({
url: '/product/updateInfo/'+id
})
}
//获取商品属性列表
export const getproductAttributeList = params => {
return request({
url: '/productAttribute/category/list',
params
})
}
//根据商品Cid获取相关产品属性列表
export const getProductAttributeById = (cid, params) => {
return request({
url: '/productAttribute/list/' + cid,
params
})
}
//更新商品上架/下架状态
export const updatePublishStatus = params => {
return request({
url: '/product/update/publishStatus',
methods: 'post',
params
})
}
//获取商品分类
export const getProductCateList = (parentId, params) => {
return request({
url: '/productCategory/list/' + parentId,
params
})
}
//更新导航栏状态
export const updateNavStatus = data => {
return request({
url: '/productCategory/update/navStatus',
method: 'post',
data
})
}
//更新显示状态
export const updateShowStatus = data => {
return request({
url: '/productCategory/update/showStatus',
method: 'post',
data
})
}
//删除商品分类
export const deleteProductCate = id => {
return request({
url: '/productCategory/delete/' + id,
method: 'post'
})
}
//获取商品关联专题列表
export const getSubjectRelationList = () => {
return request({
url: '/subject/listAll'
})
}
//获取商品优选关联的列表
export const getPrefrenceAreaList = () => {
return request({
url: '/prefrenceArea/listAll'
})
}
|
import Navigations from './Navigations';
export {Navigations};
|
import airbnbPic from './projectPictures/airbnb.png';
import feedbackPick from './projectPictures/feedback.png';
import jamsearch from './projectPictures/break.png';
import crypto from './projectPictures/crypto.png';
import shell from './projectPictures/shell.png';
import finder from './projectPictures/finder.png';
import game from './projectPictures/game.png';
import printf from './projectPictures/printf.png';
import portfolio from './projectPictures/portfolio.png';
import desktop from './projectPictures/desktop.jpg';
// Array of objects for project content and information.
export default [
{
title: "Feedbacker",
summary: "Application which allows a startup founder to " +
"send out email feedback from users. \n --React/Redux, Node, Mongodb",
pic: feedbackPick,
link: 'https://github.com/kedpak/Feedback_survey'
},
{
title: "AirBnb Clone",
summary: "Clone of the popular AirBnb platform. Divided into four sections " +
"console, database, api, and frontend. \n --Python, Flask, SqlAlchemy, Mysql, " +
"html/css, Javascript",
pic: airbnbPic
},
{
title: "Jam Search",
summary: "Allows users to find breakdancing events within a radius of the " +
"search parameter. \n --React, Mongodb, Node.js, Express",
pic: jamsearch,
link: 'https://github.com/kedpak/jam-search_break_events_app'
},
{
title: "Crypto-Exchange",
summary: "A simple cryptocurrency price watcher. Can filter results based on "
+ "several categories. --React, Bittrex API",
pic: crypto,
link: 'https://github.com/kedpak/cryptocurrency_exchange'
},
{
title: "Simple Shell",
summary: "Simple shell project is a shell command line interface built with " +
"the C programming language. Utilizes basic cl commands such as ls, pwd, and more. " +
"\n --C",
pic: shell,
link: 'https://github.com/kedpak/simple_shell'
},
{
title: "Restaurant Finder",
summary: "User can search for a restaurant by inputting city or country " +
"inside of search bar. Results within 50 mile radius will be found. \n --React/Redux",
pic: finder,
link: 'https://github.com/kedpak/Finder_app'
},
{
title: "Platform Game",
summary: "Browser based platform game made with pure javascript. Game is a " +
"Frogger clone where the player must reach the other side of map without being " +
"touched. \n --Javascript",
pic: game,
link: 'https://github.com/kedpak/arcadeGame'
},
{
title: "Custom prinf",
summary: "A custom built version of the prinf function in the C programming " +
"language. \n --C",
pic: printf,
link: 'https://github.com/kedpak/printf'
},
{
title: "Portfolio Site",
summary: "The app you are looking at this very moment! \n --React",
pic: portfolio,
link: 'https://github.com/kedpak/portfolio_kpak'
},
{
title: "Devops & Systems Eng.",
summary: "Website deployment, bash scripts, and more!",
pic: desktop,
link: 'https://github.com/kedpak/holberton-system_engineering-devops'
}
]
|
var scene,camera,renderer,sphere;
window.onload = function(){
init();
addLight();
addPlane();
addModels();
drawWordSphere();
animate();
}
function addPlane () {
var url = 'asset/grass.jpg';
var loader = new THREE.TextureLoader();
loader.load(url, function (texture) {
texture.wrapS = texture.wrapT = THREE.RepeatWrapping;
texture.repeat.set(10, 10)
var cubeGeo = new THREE.PlaneGeometry( 100, 100 );
var cubeMat = new THREE.MeshLambertMaterial({
color: 0x004400,
map: texture
});
var cube = new THREE.Mesh(cubeGeo, cubeMat);
cube.rotation.x = -Math.PI / 2;
scene.add(cube);
})
}
function addModels(){
var manager = new THREE.LoadingManager();
var textureLoader = new THREE.MTLLoader( manager );
textureLoader.load( 'asset/GermanShephardLowPoly.mtl', function (materials) {
var loader = new THREE.OBJLoader( manager );
loader.setMaterials(materials);
loader.load( 'asset/GermanShephardLowPoly.obj', function ( object ) {
addDogs(object);
}, onProgress, onError );
} );
var onProgress = function ( xhr ) {
if ( xhr.lengthComputable ) {
var percentComplete = xhr.loaded / xhr.total * 100;
console.log( Math.round(percentComplete, 2) + '% downloaded' );
}
};
var onError = function ( xhr ) {
console.log(xhr);
};
}
function addDogs (object) {
var group = new THREE.Group();
scene.add(group);
var list = getTxtPixs("江");
for(var i = 0; i < list.length; i += 2){
var temp = list[i];
for(var j = 0; j < temp.length; j += 2){
if(temp[j] === 1){
var n = Math.random() * 0.6 + 0.4;
var dog = object.clone();
group.add( dog );
dog.scale.set(n, n, n);
var box = new THREE.Box3().setFromObject(dog);
dog.position.x = j * 3 + (0.5 - Math.random()) * 2;
dog.position.z = i * 3 + (0.5 - Math.random()) * 2;
dog.position.y = 0 - box.min.y;
}
}
}
var box = new THREE.Box3().setFromObject(group);
group.position.x = (box.min.x - box.max.x) / 2;
group.position.z = (box.min.z - box.max.z) / 2;
}
function init(){
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
camera.position.set(-16, 6, 36);
renderer = new THREE.WebGLRenderer();
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.setSize( window.innerWidth, window.innerHeight );
renderer.setClearColor(0x000000, 1.0);
renderer.clear();
controls = new THREE.OrbitControls( camera, renderer.domElement );
document.body.appendChild( renderer.domElement );
}
function addLight () {
var light = new THREE.DirectionalLight( 0xffffff, 4, 1000 );
light.position.set( 100, 100, 100 );
scene.add( light );
scene.add( new THREE.AmbientLight( 0x666666 ) );
}
function animate() {
camera.position.x += 0.03;
camera.position.z -= 0.01;
if(sphere){
sphere.rotation.y -= 0.01;
}
camera.lookAt(new THREE.Vector3(0, 0, 0));
requestAnimationFrame( animate );
renderer.render( scene, camera );
}
function drawWordSphere() {
drawCore(function (obj) {
sphere = new THREE.Group();
sphere.add(obj);
var sphere1 = drawTxt("江");
var sphere2 = drawTxt("先");
var sphere3 = drawTxt("生");
sphere1.rotation.y = Math.PI / 180 * 0;
sphere2.rotation.y = Math.PI / 180 * 8;
sphere3.rotation.y = Math.PI / 180 * 16;
sphere.add(sphere1);
sphere.add(sphere2);
sphere.add(sphere3);
sphere.position.y = 18;
scene.add(sphere);
});
}
function drawCore(callback) {
var cubeGeo = new THREE.SphereGeometry( 3, 12, 12 );
var cubeMat = new THREE.MeshNormalMaterial();
var obj = new THREE.Mesh(cubeGeo, cubeMat);
callback(obj);
}
function drawTxt (txt) {
var geometry = new THREE.SphereGeometry( 8, 16, 24 );
geometry.mergeVertices();
var vertices = geometry.vertices;
var pointeGeometry = new THREE.Geometry();
pointeGeometry.vertices = vertices;
var pointeMaterial = new THREE.PointsMaterial( {
size: 1,
map: createCanvasMaterial("#12b4fd", 256, txt),
transparent: true,
depthWrite: true
} )
var points = new THREE.Points( pointeGeometry, pointeMaterial );
return points;
}
function createCanvasMaterial(color, size, txt) {
var matCanvas = document.createElement('canvas');
var matContext = matCanvas.getContext('2d');
var texture = new THREE.Texture(matCanvas);
var center = size / 2;
matCanvas.width = matCanvas.height = size;
matContext.lineWidth = size / 10;
matContext.font = size + "px Arial";
matContext.textAlign = "center";
matContext.strokeStyle = '#056bbd';
matContext.fillStyle = color;
matContext.strokeText(txt, size / 2, size * 0.9);
matContext.fillText(txt, size / 2, size * 0.9);
texture.needsUpdate = true;
return texture;
}
function getTxtPixs (txt) {
var size = 24;
var canvas = document.createElement('canvas');
canvas.width = canvas.height = size;
var context = canvas.getContext('2d');
context.fillStyle = '#fff';
context.font = size + "px Arial";
context.textAlign = "center";
context.fillText(txt, size / 2, size * 0.9);
var list = [];
for(var i = 0; i < size; i++){
var temp = [];
for(var j = 0; j < size; j++){
imageData = context.getImageData(j,i,1,1).data;
if(imageData[0] > 90){
temp.push(1);
}
else{
temp.push(0);
}
}
list.push(temp);
}
return list;
}
|
export default {
label: 'Poems',
id: 'reading',
img: 'reading',
list: [
{
id: '100',
type: 'passage',
label: 'আতা গাছে তোতা পাখি',
data: {
title: 'আতা গাছে তোতা পাখি',
type: 'poem',
text: `আতা গাছে তোতা পাখি
ডালিম গাছে মৌ,
এতো ডাকি তবুও কেন
কওনা কথা বউ ?`
}
},
{
id: '200',
type: 'passage',
label: 'চাঁদ উঠেছে ফুল ফুটেছে',
data: {
title: 'চাঁদ উঠেছে ফুল ফুটেছে',
type: 'poem',
text: `চাঁদ উঠেছে ফুল ফুটেছে
কদম তলায় কে?
হাতি নাচছে ঘোড়া নাচছে
সোনামুনির বে.`
}
},
{
id: '300',
type: 'passage',
label: 'শিল পড়া',
data: {
title: 'শিল পড়া',
type: 'poem',
text: `শিল পড়ে টুপটাপ
খোকা খুকু চুপচাপ ,
শিল পড়া থামল ,
আঙিনায় নামল ,
হুটোপুটি, ছুটোছুটি,
সারাবেলা দুপদাপ।`
}
},
{
id: '400',
type: 'passage',
label: 'খোকন খোকন',
data: {
title: 'খোকন খোকন',
type: 'poem',
text: `খোকন খোকন করে মায়,
খোকন গেছে কাদের নাই ,
সাতরা কাকে দাঁড় বাই ,
খোকনরে তুই ঘরে আই।`
}
},
{
id: '500',
type: 'passage',
label: 'কাঠবেড়ালি',
data: {
title: 'কাঠবেড়ালি',
type: 'poem',
text: `কাঠবেড়ালি, কাঠবেড়ালি
কাপড় কেচে দে ,
তোর বিয়েতে নাচতে যাব
ঝুমকো কিনে দে।`
}
},
{
id: '600',
type: 'passage',
label: 'বাক বাকুম পায়রা',
data: {
title: 'বাক বাকুম পায়রা',
type: 'poem',
text: `বাক বাকুম পায়রা
মাথায় দিয়ে টায়রা।
বৌ সাজাবে কাল কি
চড়বে সোনার পালকি।`
}
},
{
id: '700',
type: 'passage',
label: 'তাঁতীর বাড়ি',
data: {
title: 'তাঁতীর বাড়ি',
type: 'poem',
text: `তাঁতীর বাড়ি
ব্যাঙের বাসা ,
কোলা ব্যাঙের ছা
খায় - দায় গান গায় ,
তাই রে নাই রে না।`
}
},
{
id: '800',
type: 'passage',
label: 'রামধনু',
data: {
title: 'রামধনু',
type: 'poem',
text: `আকাশের গায়ে কি বা রামধনু খেলে,
দেখে চেয়ে কত লোকে সব কাজ ফেলে,
তাই দেখে খুঁতধরা বুড়ো কয় চটে,
দেখছ কি, এই রঙ পাকা নয় মোটে ॥`
}
},
{
id: '900',
type: 'passage',
label: 'নোটন নোটন পায়রাগুলি',
data: {
title: 'নোটন নোটন পায়রাগুলি',
type: 'poem',
text: `নোটন নোটন পায়রাগুলি ঝোঁটন বেঁধেছে
ওপারেতে ছেলেমেয়ে নাইতে নেমেছে।
দুই পারে দুই রুই কাতলা ভেসে উঠেছে,
কে দেখেছে? কে দেখেছে? দাদা দেখেছে।
দাদার হাতে কলম ছিল ছুঁড়ে মেরেছে
উঃ দাদা! বড্ড লেগেছে।।`
}
},
{
id: '1000',
type: 'passage',
label: 'হাট্টিমাটিমটিম',
data: {
title: 'হাট্টিমাটিমটিম',
type: 'poem',
text: `হাট্টিমা টিম টিম
তারা মাঠে পাড়ে ডিম
তাদের খাড়া দুটো শিং
তারা হাট্টিমা টিম টিম।।`
}
},
{
id: '1100',
type: 'passage',
label: 'খোকার প্রশ্',
data: {
title: 'খোকার প্রশ্',
type: 'poem',
text: `আচ্ছা মাগো, বলো দেখি
রাত্রি কেন কালো ?
সুয্যিমামা কোথা থেকে
পেলেন এমন আলো ?
ফুলগুলো সব নানান রঙের
কেমন করে হয় ?
পাতাগুলো সবুজ কেন
ফুলের মতো নয় ?`
}
}
]
};
|
var ux = require('../lib'),
fs = require('fs')
var cnn = fs.readFileSync('./data/www.cnn.com.html','utf8')
var ret = ux.check(cnn, '<img alt=".*">')
console.log(ret)
// ==> true or false
var cu = fs.readFileSync('./data/www.colorado.edu.html','utf8')
var ret = ux.check(cu, '<img alt=".*">')
// ==> true or false
|
const fs = require("fs");
const path = require("path");
const { exec } = require("child_process");
const addFunctionalComponent = (name) => {
let compText = require(path.join(__dirname,"../components/functional.js"))(name);
exec(`mkdir ${name}`,()=>{
exec("touch index.js",{cwd:`./${name}`})
exec("touch style.css",{cwd:`./${name}`})
fs.writeFile(`./${name}/index.js`,compText,function(){
console.log("done!");
});
});
};
const addStatefulComponent = (name) => {
let compText = require(path.join(__dirname,"../components/stateful.js"))(name);
exec(`mkdir ${name}`,()=>{
exec("touch index.js",{cwd:`./${name}`})
exec("touch style.css",{cwd:`./${name}`})
fs.writeFile(`./${name}/index.js`,compText,function(){
console.log("done!");
});
});
};
module.exports = {
addFunctionalComponent,
addStatefulComponent
};
|
import React, { useEffect, useState } from 'react'
import {
ScrollView,
StyleSheet,
View,
Image,
FlatList,
TouchableOpacity,
Text, useWindowDimensions
} from 'react-native'
import PropTypes from 'prop-types'
import { H2, H3 } from 'native-base'
import api from '../../services/theMovieApi'
import CustomCarousel from '../../components/carousel/carousel'
import Divider from '../../components/divider/divider'
import Loading from '../../components/loading/loading'
import Error from '../../components/error/error'
import config from '../../config/config'
const tag = 'Home'
const debug = require('debug')(tag)
const Home = ({ navigation }) => {
const [latestReleaseMovies, setLatestReleaseMovies] = useState([])
const [popularMovies, setPopularMovies] = useState([])
const [nowPlayingMovies, setNowPlayingMovies] = useState([])
const [upcomingMovies, setUpcomingMovies] = useState([])
const [loading, setLoading] = useState(true)
const [error, setError] = useState(false)
const { width: deviceWidth } = useWindowDimensions()
useEffect(() => {
const getData = async () => {
try {
const endpoints = ["top_rated", "popular", "now_playing", "upcoming"]
const response = await Promise.all(endpoints.map((endpoint) => api.get(`/movie/${endpoint}`)))
const [latest, popular, nowPlaying, upcoming] = response
setLatestReleaseMovies(latest.results)
setPopularMovies(popular.results)
setNowPlayingMovies(nowPlaying.results)
setUpcomingMovies(upcoming.results)
} catch (err) {
debug('getData', err)
setError(true)
}
setLoading(false)
}
getData()
}, [])
const handleMovieSelection = (id) => {
debug(handleMovieSelection)
navigation.navigate('Movie', { id })
}
/* Dimension Helpers */
const smallImageWidth = { width: (deviceWidth / 3) - 28 }
const bigImageWidth = { width: 172 }
if (loading) return (<Loading />)
if (error) return (<Error />)
const { imagePath } = config
return (
<ScrollView
contentInsetAdjustmentBehavior="automatic"
style={styles.bgBlack} >
{latestReleaseMovies.length ?
<CustomCarousel
data={latestReleaseMovies.slice(0, 5)}
handleMovieSelection={handleMovieSelection}
width={deviceWidth}
/>
: (null)}
<View style={styles.bgBlack}>
<H2 style={styles.title}>Popular</H2>
<ScrollView
horizontal
contentContainerStyle={{ width: 200 * popularMovies.length }}
showsHorizontalScrollIndicator={false}
decelerationRate="fast"
pagingEnabled
>
{popularMovies && popularMovies.map(popularMovie => (
<TouchableOpacity
onPress={() => handleMovieSelection(popularMovie.id)}
style={styles.marginHorizontal}
key={popularMovie.id}
>
<Image style={styles.bigImage} source={{ uri: imagePath + popularMovie.poster_path }} />
<H2 style={[styles.whiteText, bigImageWidth]}>{popularMovie.title}</H2>
<Text style={styles.grayText}>PG13 / {popularMovie.release_date.substring(0, 4)}</Text>
</TouchableOpacity>
))}
</ScrollView>
</View>
<Divider />
<View>
<H2 style={styles.title}>Popular</H2>
{nowPlayingMovies.length ? (
<FlatList data={nowPlayingMovies} numColumns={3} renderItem={({ item }) => (
<TouchableOpacity
onPress={() => handleMovieSelection(item.id)}
style={styles.marginHorizontal}
key={`nowPlayingMovies-${item.id}`}
>
<Image
style={[styles.smallImage, smallImageWidth]}
source={{ uri: imagePath + item.poster_path }} />
<H3 style={[styles.whiteText, smallImageWidth]}>{item.title}</H3>
<Text style={styles.grayText}>PG13 / {item.release_date.substring(0, 4)}</Text>
</TouchableOpacity>
)} />
) : (null)}
</View>
<Divider />
<View>
<H2 style={styles.title}>Upcoming</H2>
{upcomingMovies.length ? (
<FlatList data={upcomingMovies} numColumns={3} renderItem={({ item }) => (
<TouchableOpacity
onPress={() => handleMovieSelection(item.id)}
style={styles.marginHorizontal}
key={`upcomingMovies-${item.id}`}
>
<Image
style={[styles.smallImage, smallImageWidth]}
source={{ uri: imagePath + item.poster_path }} />
<H3 style={[styles.whiteText, smallImageWidth]}>{item.title}</H3>
<Text style={styles.grayText}>PG13 / {item.release_date.substring(0, 4)}</Text>
</TouchableOpacity>
)} />
) : (null)}
</View>
</ScrollView>
)
}
const styles = StyleSheet.create({
sectionContainer: {
marginTop: 32,
paddingHorizontal: 24
},
sectionTitle: {
fontSize: 24,
fontWeight: '600'
},
sectionDescription: {
marginTop: 8,
fontSize: 18,
fontWeight: '400'
},
highlight: {
fontWeight: '700'
},
whiteText: {
color: 'white'
},
grayText: { color: '#888888', fontSize: 16 },
title: {
color: 'white',
margin: 14
},
bigImage: { height: 250, width: 172, borderRadius: 10, marginVertical: 14 },
smallImage: {
height: 180,
borderRadius: 10,
marginVertical: 14
},
marginHorizontal: { marginHorizontal: 14 },
bgBlack: { backgroundColor: 'black' }
})
Home.propTypes = {
navigation: PropTypes.shape({ navigate: PropTypes.func, goBack: PropTypes.func }).isRequired
}
export default Home
|
// alert("Hello");
var gamepattern=[];
var zero=1;
var bool=true;
var sequence=0;
function nextSequence(){
//change title
bool=false;
var count=0;
document.querySelector("#level-title").innerText="Level "+zero++;
colorArray=["red","green","yellow","blue"];
// random number generator
randomNumber=Math.floor(Math.random()*colorArray.length);
// random color picker
randomColor=colorArray[randomNumber];
// random color pusher
gamepattern.push(randomColor);
// random color animation
$("#"+randomColor).fadeOut(100).fadeIn(100);
// play sound
playSound(randomColor);
//getting the id of the button clicked
var userClickedPattern = [];
$(".btn").click(function(){
count++;
var userClickedColor=$(this).attr("id");
playSound(userClickedColor);
animatePress(userClickedColor);
userClickedPattern.push(userClickedColor);
//sequence generar
setTimeout(function(){if(count===gamepattern.length){
console.log(gamepattern+" "+userClickedPattern);
if(JSON.stringify(userClickedPattern)==JSON.stringify(gamepattern))
{
nextSequence();
count++;
}
else
{
wrong();
}
}
},400);
});
}
function playSound(name){
var audio = new Audio("sounds/"+name+".mp3");
audio.play();
}
function animatePress(currentColor){
$("#"+currentColor).addClass("pressed")
setTimeout(function() {
$("#"+currentColor).removeClass("pressed");
}, 100);
}
//changed clicked
$(document).click(function(){
if(bool==true)
nextSequence();
});
function wrong()
{
playSound("wrong");
$("body").addClass("game-over");
$("h1").html("GAME-OVER<br> Press any key to restart");
setTimeout(function(){
$("body").removeClass("game-over");
},1000);
startover();
}
function startover()
{
zero=1;
bool=true;
gamepattern=[]
}
|
import { Link } from 'react-router-dom';
import classes from './HeaderIcon.module.css';
const HeaderIcon = (props) => {
return (
<Link t0={`/${props.label}`} className={classes.HeaderIcon}>
{props.children}
<h5>{props.label}</h5>
</Link>
);
};
export default HeaderIcon;
|
import React from 'react';
import PropTypes from 'prop-types';
import AppBar from '@mui/material/AppBar';
import Tabs from '@mui/material/Tabs';
import Tab from '@mui/material/Tab';
import Typography from '@mui/material/Typography';
class TabContainer extends React.Component {
constructor(props) {
const { initialSelectedIndex } = props;
super(props);
this.state = {
value: initialSelectedIndex,
};
}
/**
* Function to change visible content on tabs click
*/
changeTab = (event, value) => {
this.setState({ value });
};
render() {
const {
children, titles, tabClasses,
} = this.props;
const { value } = this.state;
return (
<div>
<AppBar position="static" color="default">
<Tabs
value={value}
onChange={this.changeTab}
className="DrawerTab"
centered
>
{titles.map(({
label, icon, disabled, selected,
}, i) => (
<Tab
className={`tabs ${tabClasses}`}
label={label}
icon={icon}
key={i}
disabled={disabled}
selected={selected}
/>
))}
</Tabs>
</AppBar>
{children.map((child, i) => (
value === i && (
<Typography key={i} component="div" style={{ padding: 4 * 3 }}>
{child}
</Typography>
)
))}
</div>
);
}
}
TabContainer.propTypes = {
children: PropTypes.node.isRequired,
initialSelectedIndex: PropTypes.number,
titles: PropTypes.array.isRequired,
tabClasses: PropTypes.string,
};
TabContainer.defaultProps = {
tabClasses: '',
initialSelectedIndex: 1,
};
export default TabContainer;
|
var SvgPathDraw = function($path){
var _this = this;
var path,length,dashOffset,dashArray;
this._progress = -1;
function setup(){
path = $path;
length = $path[0].getTotalLength();
dashOffset = length;
dashArray = length;
this.update(this._progress);
};
this.update = function(progress){
this._progress = progress;
TweenLite.set(path,{
strokeDashoffset:dashOffset.toFixed(3)*this._progress+'px',
strokeDasharray:dashArray.toFixed(3)+'px ' + dashArray.toFixed(3)+'px'
});
}
this.fromTo = function(from,to,dur,delay,ease,complete){
var _this = this,
_ease = ease == 'undefined'?Quart.easeInOut:ease;
return TweenLite.to(this,dur,{delay:delay,_progress:to,ease:_ease,
onStart:function(){
_this._progress = from;
},
onUpdate:function(){
_this.update(_this._progress);
},
onComplete:function(){
if(complete)complete();
}
});
}
this.to = function(to,dur,delay,ease,complete){
var _ease = ease == 'undefined'?Quart.easeInOut:ease;
return TweenLite.to(this,dur,{delay:delay,_progress:to,ease:_ease,
onStart:function(){},
onUpdate:function(){
_this.update(_this._progress);
},
onComplete:function(){
if(complete)complete();
}
});
}
setup.call(this);
return this;
}
SvgPathDraw.prototype.constructor = SvgPathDraw;
module.exports = SvgPathDraw;
|
import { defineConfig } from "vite";
import path from "path";
import reactRefresh from "@vitejs/plugin-react-refresh";
import vitePluginImp from "vite-plugin-imp";
import config from "./config";
const env = process.argv[process.argv.length - 1];
const base = config[env];
// https://vitejs.dev/config/
export default defineConfig({
base: base.cdn,
plugins: [
reactRefresh(),
vitePluginImp({
libList: [
{
// libName: "antd",
// style: (name) => `antd/lib/${name}/style/index.less`
},
],
}),
],
resolve: {
alias: {
"@": path.resolve(__dirname, "src"),
"~": path.resolve(__dirname, "./"),
},
},
server: {
port: 3000,
proxy: {
// axios proxy configuration
// '/api': {
// target: 'http://example:port/api/v1',
// changeOrigin: true,
// rewrite: path => path.replace(/^\/api/, ''),
// }
},
},
css: {
preprocessorOptions: {
less: {
javascriptEnabled: true,
},
},
},
});
|
const btn = document.querySelector("button");
const section = document.querySelector("section");
const digits = 10;
const codes = 500;
const chars = "1234567890";
btn.addEventListener("click", () => {
section.textContent = ""
for (let i = 0; i < codes; i++) {
let code = ""
for (let i = 0; i < digits; i++) {
code += chars[Math.floor(Math.random() * chars.length)]
}
const div = document.createElement("div");
section.appendChild(div);
div.textContent = code;
}
})
|
'use strict'
const conf = Object.assign({}, require('../../eslint/eslint-config.js'))
conf.overrides= [
{
"files": ["*.hbs"],
"parserOptions": {
"sourceType": "module"
}
}
]
module.exports = conf
|
window.onload = function(){
var areaClock = document.getElementById('clock');
function calcTime(){
var objDate = new Date();
var year = objDate.getFullYear();
var date = objDate.getDate(); // 20일
var hours = objDate.getHours(); // 0~23시
var setHours = objDate.getHours() % 12; // 0~23시 %12
var minutes = objDate.getMinutes(); // 0~59분
var seconds = objDate.getSeconds(); // 0~59초
var meridiem = (hours >= 12) ? "PM" : "AM";
var dayArr = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var dayName = dayArr[objDate.getDay()];
function addZero(data){
data += '';
if(data.length < 2){ data = '0' + data; }
return data;
}
var currentTime = meridiem + " " + addZero(hours) + " : " + addZero(minutes) + " : " + addZero(seconds);
areaClock.innerText = currentTime;
}
setInterval(calcTime, 1000)
}
|
import React from 'react';
import { BrowserRouter, Switch, Route, HashRouter } from 'react-router-dom'
import CreateUser from './components/createUser';
import UserList from './components/userList';
const routes =
<BrowserRouter>
<HashRouter>
<Switch>
<Route exact path='/'><UserList/></Route>
<Route path='/create-user'><CreateUser/></Route>
</Switch>
</HashRouter>
</BrowserRouter>
function App() {
return (
routes
);
}
export default App;
|
import App, { Container } from "next/app";
import StyledWrapper from "../components/StyledWrapper/StyledWrapper";
import { ApolloProvider } from "react-apollo";
import withApollo from "../lib/withApollo";
class MyApp extends App {
// Exposes page numbers.
// Will run before render function and passed to props if you return
static async getInitialProps({ Component, ctx }) {
let pageProps = {};
if (Component.getInitialProps) {
pageProps = await Component.getInitialProps(ctx);
}
pageProps.query = ctx.query;
return { pageProps };
}
render() {
const { Component, apollo, pageProps } = this.props;
return (
<Container>
{/* Expose Apollo client to React
by wrapping the App in the Apollo Provider from the HOC*/}
<ApolloProvider client={apollo}>
<StyledWrapper>
<Component {...pageProps} />
</StyledWrapper>
</ApolloProvider>
</Container>
);
}
}
export default withApollo(MyApp);
|
import axios from 'axios';
import apiKeys from '../apiKeys.json';
const baseUrl = apiKeys.firebaseKeys.databaseURL;
const getSouvenirData = () => new Promise((resolve, reject) => {
axios.get(`${baseUrl}/souvenirs.json`)
.then((response) => {
const theSouvenirs = response.data;
const souvenirs = [];
Object.keys(theSouvenirs).forEach((fbId) => {
theSouvenirs[fbId].id = fbId;
souvenirs.push(theSouvenirs[fbId]);
});
resolve(souvenirs);
})
.catch((error) => reject(error));
});
const getSouvenirById = (souvenirId) => axios.get(`${baseUrl}/souvenirs/${souvenirId}.json`);
const addNewSouvenir = (newSouvenir) => axios.post(`${baseUrl}/souvenirs.json`, newSouvenir);
const deleteSouvenir = (singleSouvenir) => axios.delete(`${baseUrl}/souvenirs/${singleSouvenir}.json`);
const updateSouvenir = (souvenirId, updatedSouvenir) => axios.put(`${baseUrl}/souvenirs/${souvenirId}.json`, updatedSouvenir);
export default {
getSouvenirData,
addNewSouvenir,
deleteSouvenir,
getSouvenirById,
updateSouvenir,
};
|
const globalModel = require("./globalModel");
module.exports = {
insert: function(req,data){
return new Promise(function(resolve, reject) {
req.getConnection(function(err,connection){
let owner_id = 0
let column = "video_id"
if(data.type == "channels"){
column = "channel_id"
}else if(data.type == "blogs"){
column = "blog_id"
}else if(data.type == "members" || data.type == "users"){
column = "user_id"
}else if(data.type == "artists"){
column = "artist_id"
}else if(data.type == "playlists"){
column = "playlist_id"
}else if(data.type == "movies"){
column = "movie_id"
}else if(data.type == "cast_crew_member"){
column = "cast_crew_member_id"
}
if(req.user && req.user.user_id){
owner_id = req.user.user_id
}
let type = "view_count"
if(typeof req.query.needSubscription == "undefined" && parseInt(owner_id) != parseInt(data.owner_id)){
var ip = req.headers['x-forwarded-for'] ||
req.connection.remoteAddress ||
req.socket.remoteAddress ||
(req.connection.socket ? req.connection.socket.remoteAddress : null);
let sql = "SELECT owner_id from recently_viewed WHERE type = ? AND id = ? "
let condition = []
condition.push(data.type)
condition.push(data.id)
if(req.user){
condition.push(owner_id)
sql += " AND owner_id = ?"
}else if(ip){
condition.push(ip)
sql += " AND ip = ?"
}else{
resolve(false)
return
}
globalModel.custom(req,sql,condition).then( result => {
if (result) {
let results = JSON.parse(JSON.stringify(result));
if(results.length == 0){
connection.query("UPDATE "+ (data.type == "members" ? "userdetails" : data.type) + " SET "+type+" = "+type+" + 1 WHERE "+column+" = "+data.id,function(err,results,fields)
{
});
}
}
});
}
if(owner_id == 0){
// resolve(false)
// return
}
if(parseInt(owner_id) == parseInt(data.owner_id)){
resolve(false)
return
}
connection.query('INSERT INTO recently_viewed SET ? ON DUPLICATE KEY UPDATE creation_date = ?',[{owner_id:owner_id,id:data.id,type:data.type,creation_date:data.creation_date,ip:ip},data.creation_date],function(err,results,fields)
{
if(err)
resolve(false)
if(results){
resolve(true)
}else{
resolve(false);
}
})
})
});
}
}
|
import passport from 'passport';
import { Router } from 'express';
import getBars from './services/find';
import getBar from './services/findOne';
import createBar from './services/create';
import updateBar from './services/update';
import deleteBar from './services/delete';
const router = Router();
// Bars
router.get('/', passport.authenticate('jwt'), getBars);
// Bar
router.get('/:id', passport.authenticate('jwt'), getBar);
router.post('/', passport.authenticate('jwt'), createBar);
router.put('/:id', passport.authenticate('jwt'), updateBar);
router.delete('/:id', passport.authenticate('jwt'), deleteBar);
export default router;
|
/* general javascript librarys.
*
* includes jQuery, Backbone and friends, underscore
*/
(function() {
/* what do i depend on */
var dependencies = [
'backbone-relational',
'backbone-tastypie'
];
/* module defination */
return define(dependencies, function() {
/* what do i provide */
var make_module = function() {
/* to make sure csrf is sent when posting.
source: django.com, 2011 Feb */
var regex1 = /^http:.*/;
var regex2 = /^https:.*/;
var csrf_token = (function() {
var cookies = document.cookie.split('; ');
for (var i = 0; i < cookies.length; ++i) {
var kv = cookies[i].split('=');
if (kv.length == 2 && kv[0] == 'csrftoken')
return kv[1];
}
})();
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!(regex1.test(settings.url) || regex2.test(settings.url)))
/* Only send the token to relative URLs i.e. locally. */
xhr.setRequestHeader("X-CSRFToken", csrf_token);
}
});
return {
$: jQuery,
_: _,
Backbone: Backbone
};
};
return make_module();
}); /* \define */
})();
|
import React from "react";
import { Button, Col, Container, Input, Row } from "reactstrap";
import Comment from '../../assets/comment.png';
import Answer from '../../assets/answer.png';
import Agree from '../../assets/agree.png';
import deleteIcon from '../../assets/delete.png';
import edit from '../../assets/edit.png';
import sent from '../../assets/sent.webp';
import {AiOutlinePaperClip} from 'react-icons/ai';
import './chat.css';
const Student = () => {
const [width] = React.useState (window.innerWidth);
const studentImage = "https://bit.ly/315GQPy";
const teacherImage = "https://bit.ly/370mw65";
return (
<React.Fragment>
{width < 500 ? <span className={"mobile-input-container"}>
<Input type={"textarea"} />
<div style={{marginLeft:"0px",padding:"5px"}}>
<AiOutlinePaperClip size={"25px"} color={"grey"} />
<hr />
<img src={sent} alt={''} style={{width:"35px",height:"35px"}} className={"sentIcon"} />
</div>
</span> : null}
<Container>
<Row style={ width < 500?{ position:"fixed",width:"100%",height:"100px",verticalAlign:"baseline",padding: "20px",zIndex:"10",background:"#ffffff"}:{ position:"fixed",width:"60%",height:"180px",verticalAlign:"baseline",padding: "20px",zIndex:"10",background:"#ffffff"}}>
<Col lg={12} style={{position:"relative",top:"10%", textAlign: "center",bottom:"20px" }}>
<h4>XII - B - Physics</h4>
<p>Interactions</p>
</Col>
{ width < 500? null :
<Col lg={12} style={{position:"relative",top:"10%", textAlign: "center", width:"100%",display:"inline-flex",marginBottom:"50px" }}>
<Input type={"textarea"} style={{borderRadius:"0px",borderRight:"none"}} />
<Button style={{borderRadius:"0px",background:"#f7f7f7",border:"none",borderTop:"1px solid #ced4da",borderBottom:"1px solid #ced4da"}}>
<AiOutlinePaperClip color={"grey"} size={"25px"} />
</Button>
<Button style={{borderRadius:"0px",background:"#f7f7f7",border:"none",borderTop:"1px solid #ced4da",borderBottom:"1px solid #ced4da",borderRight:"1px solid #ced4da"}}>
{/* <FaPaperPlane color={"grey"} size={"20px"} /> */}
<img src={sent} alt={''} style={{width:"30px",height:"30px"}} className={"sentIcon"} />
</Button>
</Col>}
</Row>
<br />
<Row style={width < 500 ? { marginTop: "100px", padding: "0px" } :{ marginTop: "180px", padding: "0px" }}>
<Container
className={"clarify-outer-container"}
>
{/* first-clarify */}
<Row>
<Col lg={12}>
<Row
className={"clarify-inner-container"}
>
<Col
lg={12}
style={{
display: "inline-flex",
}}
>
<img
src={studentImage}
alt={""}
style={{
width: "30px",
height: "30px",
borderRadius: "50px",
}}
/>
<div style={{ paddingLeft: "20px" }}>
<p>
<span style={{ fontSize: "15px", fontWeight: "bold" }}>
Vanitha
</span>{" "}
<br />
<span style={{ fontSize: "12px" }}>
Request for clarification -{" "}
<span style={{ fontSize: "10px" }}>
11/15/2019 3:32:45 PM
</span>
</span>
</p>
</div>
</Col>
<Col lg={12}>
<div style={{ paddingLeft: "50px" }}>
What is meant by Electromaganetic force?
</div>
{/* <br /> */}
<span style={{float:"right"}}>
{width < 500 ?
<React.Fragment>
{/* <a href={"/"}><img style={{width:'15px',height:'15px', marginLeft: '20px'}} src={Clarify} alt={'clarify'}/></a> */}
<a href={"/"}><img style={{width:'15px',height:'15px', marginLeft: '20px',marginRight: '10px'}} src={Answer} alt={'answer'}/></a>
<a href={"/"}><img style={{width:'15px',height:'15px', marginLeft: '20px'}} src={Comment} alt={'comment'}/></a>
<a href={"/"}><img style={{width:'15px',height:'15px', marginLeft: '20px'}} src={deleteIcon} alt={'comment'}/></a>
</React.Fragment>:
<React.Fragment>
<a style={{width:'15px',height:'15px', marginLeft: '20px',fontSize:'13px'}} href={"/"}>Answer</a>
<a style={{width:'15px',height:'15px', marginLeft: '20px',fontSize:'13px'}} href={"/"}>Comment</a>
<a style={{width:'15px',height:'15px', marginLeft: '20px',fontSize:'13px'}} href={"/"}>Delete</a>
</React.Fragment>
}
</span>
</Col>
</Row>
</Col>
</Row>
{/* first-end */}
<Row style={{ marginTop: "20px" }}>
<Col lg={12}>
<Row>
<Col lg={12} style={{ display: "inline-flex" }}>
<img
src={teacherImage}
alt={""}
style={{
width: "30px",
height: "30px",
borderRadius: "50px",
}}
/>
<div style={{ paddingLeft: "20px" }}>
<p>
<span style={{ fontSize: "15px", fontWeight: "bold" }}>
Teacher - Abinaya Sekar
</span>{" "}
<br />
<span style={{ fontSize: "12px", color: "green" }}>
Answer for clarification -{" "}
<span style={{ fontSize: "10px", color: "black" }}>
11/15/2019 3:32:45 PM
</span>
</span>
</p>
</div>
</Col>
<Col lg={12}>
<Row>
<Col
md={1}
xs={2}
style={{ borderRight: "5px solid green" }}
></Col>
<Col md={11} xs={10}>
<div style={{ fontWeight: "600", padding: "10px" }}>
The fundamental force associated with electric and
magnetic fields. The electromagnetic force is carried
by the photon and is responsible for atomic structure,
chemical reactions, the attractive and repulsive
forces associated with electrical charge and
magnetism, and all other electromagnetic phenomena.
</div>
</Col>
</Row>
<span style={{float:"right"}}>
{width < 500 ?
<React.Fragment>
{/* <a href={"/"}><img style={{width:'15px',height:'15px', marginLeft: '20px'}} src={Clarify} alt={'clarify'}/></a> */}
<a href={"/"}><img style={{width:'20px',height:'20px', marginLeft: '20px',marginRight: '10px'}} src={edit} alt={'answer'}/></a>
{/* <a href={"/"}><img style={{width:'15px',height:'15px', marginLeft: '20px'}} src={Comment} alt={'comment'}/></a> */}
<a href={"/"}><img style={{width:'15px',height:'15px', marginLeft: '20px'}} src={deleteIcon} alt={'comment'}/></a>
</React.Fragment>:
<React.Fragment>
<a style={{width:'15px',height:'15px', marginLeft: '20px',fontSize:'13px'}} href={"/"}>Answer</a>
<a style={{width:'15px',height:'15px', marginLeft: '20px',fontSize:'13px'}} href={"/"}>Comment</a>
<a style={{width:'15px',height:'15px', marginLeft: '20px',fontSize:'13px'}} href={"/"}>Delete</a>
</React.Fragment>
}
</span>
</Col>
</Row>
</Col>
</Row>
</Container>
<Container className={"clarify-outer-container"}>
<Row style={{ marginTop: "0px",padding: "0px" }}>
<Col lg={12}>
<Row
style={{
paddingTop: "10px",
paddingBottom: "10px",
background: "#ffffff",
// border: "1px solid #d8d8d8",
borderLeft: "5px solid #ee82ee",
}}
>
<Col lg={12} style={{ display: "inline-flex" }}>
<img
src={studentImage}
alt={""}
style={{
width: "30px",
height: "30px",
borderRadius: "50px",
}}
/>
<div style={{ paddingLeft: "20px" }}>
<p>
<span style={{ fontSize: "15px", fontWeight: "bold" }}>
Jeeva
</span>{" "}
<br />
<span style={{ fontSize: "12px", color: 'brown' }}>
Request for clarification -{" "}
<span style={{ fontSize: "10px", color: 'black' }}>
11/16/2019 2:45:37 PM
</span>
</span>
</p>
</div>
</Col>
<Col lg={12}>
<div style={{ paddingLeft: "50px" }}>
Give some examples of electromagnetic force?
</div>
<span style={{float:"right"}}>
{width < 500 ?
<React.Fragment>
<a href={"/"}><img style={{width:'15px',height:'15px', marginLeft: '20px'}} src={Answer} alt={'clarify'}/></a>
<a href={"/"}><img style={{width:'15px',height:'15px', marginLeft: '20px'}} src={Comment} alt={'comment'}/></a>
<a href={"/"}><img style={{width:'15px',height:'15px', marginLeft: '20px',marginRight: '10px'}} src={deleteIcon} alt={'answer'}/></a>
</React.Fragment>:
<React.Fragment>
<a style={{width:'15px',height:'15px', marginLeft: '20px',fontSize:'13px'}} href={"/"}>Answer</a>
<a style={{width:'15px',height:'15px', marginLeft: '20px',fontSize:'13px'}} href={"/"}>Comment</a>
<a style={{width:'15px',height:'15px', marginLeft: '20px',fontSize:'13px'}} href={"/"}>Delete</a>
</React.Fragment>
}
</span>
</Col>
</Row>
</Col>
</Row>
<Row style={{ marginTop: "20px" }}>
<Col lg={12}>
<Row>
<Col lg={12} style={{ display: "inline-flex" }}>
<img
src={studentImage}
alt={""}
style={{
width: "30px",
height: "30px",
borderRadius: "50px",
}}
/>
<div style={{ paddingLeft: "20px" }}>
<p>
<span style={{ fontSize: "15px", fontWeight: "bold" }}>
Kowsalya Vijay
</span>{" "}
<br />
<span style={{ fontSize: "12px" }}>
Commented On -{" "}
<span style={{ fontSize: "10px" }}>
11/16/2019 2:45:37 PM
</span>
</span>
</p>
</div>
</Col>
<Col lg={12}>
<div style={{ paddingLeft: "50px" }}>light.</div>
<span style={{float:"right"}}>
{width < 500 ?
<React.Fragment>
<a href={"/"}><img style={{width:'15px',height:'15px', marginLeft: '20px'}} src={Agree} alt={'clarify'}/></a>
<a href={"/"}><img style={{width:'15px',height:'15px', marginLeft: '20px'}} src={Comment} alt={'comment'}/></a>
<a href={"/"}><img style={{width:'15px',height:'15px', marginLeft: '20px',marginRight: '10px'}} src={deleteIcon} alt={'answer'}/></a>
</React.Fragment>:
<React.Fragment>
<a style={{width:'15px',height:'15px', marginLeft: '20px',fontSize:'13px'}} href={"/"}>Agree</a>
<a style={{width:'15px',height:'15px', marginLeft: '20px',fontSize:'13px'}} href={"/"}>Comment</a>
<a style={{width:'15px',height:'15px', marginLeft: '20px',fontSize:'13px'}} href={"/"}>Delete</a>
</React.Fragment>
}
</span>
</Col>
</Row>
</Col>
</Row>
<Row style={width < 500 ? { marginTop: "20px",marginLeft:"0px" }:{ marginTop: "20px",marginLeft:"20px" }}>
<Col lg={12}>
<Row>
<Col lg={12} style={{ display: "inline-flex" }}>
<img
src={studentImage}
alt={""}
style={{
width: "30px",
height: "30px",
borderRadius: "50px",
}}
/>
<div style={{ paddingLeft: "20px" }}>
<p>
<span style={{ fontSize: "15px", fontWeight: "bold" }}>
Renukadevi{" "}
</span>{" "}
<br />
<span style={{ fontSize: "12px" }}>
Commented On -{" "}
<span style={{ fontSize: "10px" }}>
11/16/2019 2:45:37 PM
</span>
</span>
</p>
</div>
</Col>
<Col lg={12}>
<div style={{ paddingLeft: "50px" }}>Generators.</div>
<span style={{float:"right"}}>
{width < 500 ?
<React.Fragment>
<a href={"/"}><img style={{width:'15px',height:'15px', marginLeft: '20px'}} src={Agree} alt={'clarify'}/></a>
<a href={"/"}><img style={{width:'15px',height:'15px', marginLeft: '20px'}} src={Comment} alt={'comment'}/></a>
<a href={"/"}><img style={{width:'15px',height:'15px', marginLeft: '20px',marginRight: '10px'}} src={deleteIcon} alt={'answer'}/></a>
</React.Fragment>:
<React.Fragment>
<a style={{width:'15px',height:'15px', marginLeft: '20px',fontSize:'13px'}} href={"/"}>Agree</a>
<a style={{width:'15px',height:'15px', marginLeft: '20px',fontSize:'13px'}} href={"/"}>Comment</a>
<a style={{width:'15px',height:'15px', marginLeft: '20px',fontSize:'13px'}} href={"/"}>Delete</a>
</React.Fragment>
}
</span>
</Col>
</Row>
</Col>
</Row>
<Row style={width < 500 ? { marginTop: "20px",marginLeft:"10px" }:{ marginTop: "20px",marginLeft:"20px" }}>
<Col lg={12}>
<Row>
<Col lg={12} style={{ display: "inline-flex" }}>
<img
src={studentImage}
alt={""}
style={{
width: "30px",
height: "30px",
borderRadius: "50px",
}}
/>
<div style={{ paddingLeft: "20px" }}>
<p>
<span style={{ fontSize: "15px", fontWeight: "bold" }}>
Vanitha
</span>{" "}
<br />
<span style={{ fontSize: "12px" }}>
Agree with the Comment -{" "}
<span style={{ fontSize: "10px" }}>
11/16/2019 2:45:37 PM
</span>
</span>
</p>
</div>
</Col>
<Col lg={12}>
{/* <div style={{ paddingLeft: "50px" }}>light.</div> */}
<span style={{float:"right"}}>
{width < 500 ?
<React.Fragment>
<a href={"/"}><img style={{width:'15px',height:'15px', marginLeft: '20px'}} src={Answer} alt={'clarify'}/></a>
<a href={"/"}><img style={{width:'15px',height:'15px', marginLeft: '20px'}} src={Comment} alt={'comment'}/></a>
<a href={"/"}><img style={{width:'15px',height:'15px', marginLeft: '20px',marginRight: '10px'}} src={deleteIcon} alt={'answer'}/></a>
</React.Fragment>:
<React.Fragment>
<a style={{width:'15px',height:'15px', marginLeft: '20px',fontSize:'13px'}} href={"/"}>Answer</a>
<a style={{width:'15px',height:'15px', marginLeft: '20px',fontSize:'13px'}} href={"/"}>Comment</a>
<a style={{width:'15px',height:'15px', marginLeft: '20px',fontSize:'13px'}} href={"/"}>Delete</a>
</React.Fragment>
}
</span>
</Col>
</Row>
</Col>
</Row>
<Row style={{ marginTop: "20px" }}>
<Col lg={12}>
<Row>
<Col lg={12} style={{ display: "inline-flex" }}>
<img
src={teacherImage}
alt={""}
style={{
width: "30px",
height: "30px",
borderRadius: "50px",
}}
/>
<div style={{ paddingLeft: "20px" }}>
<p>
<span style={{ fontSize: "15px", fontWeight: "bold" }}>
Teacher - Abinaya Sekar
</span>{" "}
<br />
<span style={{ fontSize: "12px", color: "green" }}>
Answer for clarification -{" "}
<span style={{ fontSize: "10px", color: "black" }}>
11/15/2019 3:32:45 PM
</span>
</span>
</p>
</div>
</Col>
<Col lg={12}>
<Row>
<Col
md={1}
xs={2}
style={{ borderRight: "5px solid green" }}
></Col>
<Col md={11} xs={10}>
<div style={{ fontWeight: "600", padding: "10px" }}>
Both are correct. I explain you in a detailed manner.
Light is an electromagnetic wave, where an oscillating
electric field generates a changing magnetic field,
which in turn creates an electric field, and so on.
Electrical generators work by a spinning magnetic
field creating a current in a nearby wire. Other
example like Electromagnetism is also responsible for
the electricity powering your screen and the device
you're reading on, with the flow of electrons
propelled
energy.
</div>
<span style={{float:"right"}}>
{width < 500 ?
<React.Fragment>
<a href={"/"}><img style={{width:'20px',height:'20px', marginLeft: '20px'}} src={edit} alt={'clarify'}/></a>
{/* <a href={"/"}><img style={{width:'15px',height:'15px', marginLeft: '20px'}} src={Comm} alt={'comment'}/></a> */}
<a href={"/"}><img style={{width:'15px',height:'15px', marginLeft: '20px',marginRight: '10px'}} src={deleteIcon} alt={'answer'}/></a>
</React.Fragment>:
<React.Fragment>
<a style={{width:'15px',height:'15px', marginLeft: '20px',fontSize:'13px'}} href={"/"}>Edit</a>
{/* <a style={{width:'15px',height:'15px', marginLeft: '20px',fontSize:'13px'}} href={"/"}>Comment</a> */}
<a style={{width:'15px',height:'15px', marginLeft: '20px',fontSize:'13px'}} href={"/"}>Delete</a>
</React.Fragment>
}
</span>
</Col>
</Row>
</Col>
</Row>
</Col>
</Row>
<Row style={{ marginTop: "20px",padding: "0px 0px 0px 15px" }}>
<Col lg={12}>
<Row
style={{
paddingTop: "10px",
paddingBottom: "10px",
background: "#ffffff",
// border: "1px solid #d8d8d8",
borderLeft: "5px solid brown",
}}
>
<Col lg={12} style={{ display: "inline-flex" }}>
<img
src={studentImage}
alt={""}
style={{
width: "30px",
height: "30px",
borderRadius: "50px",
}}
/>
<div style={{ paddingLeft: "20px" }}>
<p>
<span style={{ fontSize: "15px", fontWeight: "bold" }}>
Jansirani
</span>{" "}
<br />
<span style={{ fontSize: "12px", color: 'brown' }}>
Request for clarification -{" "}
<span style={{ fontSize: "10px", color: 'black' }}>
11/16/2019 2:45:37 PM
</span>
</span>
</p>
</div>
</Col>
<Col lg={12}>
<div style={{ paddingLeft: "50px" }}>
Is there any difference between electromagnetic force & electromagnetism
</div>
<span style={{float:"right"}}>
{width < 500 ?
<React.Fragment>
{/* <a href={"/"}><img style={{width:'15px',height:'15px', marginLeft: '20px'}} src={Clarify} alt={'clarify'}/></a> */}
<a href={"/"}><img style={{width:'15px',height:'15px', marginLeft: '20px',marginRight: '10px'}} src={Answer} alt={'answer'}/></a>
<a href={"/"}><img style={{width:'15px',height:'15px', marginLeft: '20px'}} src={Comment} alt={'comment'}/></a>
<a href={"/"}><img style={{width:'15px',height:'15px', marginLeft: '20px'}} src={deleteIcon} alt={'comment'}/></a>
</React.Fragment>:
<React.Fragment>
<a style={{width:'15px',height:'15px', marginLeft: '20px',fontSize:'13px'}} href={"/"}>Answer</a>
<a style={{width:'15px',height:'15px', marginLeft: '20px',fontSize:'13px'}} href={"/"}>Comment</a>
<a style={{width:'15px',height:'15px', marginLeft: '20px',fontSize:'13px'}} href={"/"}>Delete</a>
</React.Fragment>
}
</span>
</Col>
</Row>
</Col>
</Row>
<Row style={width < 500 ?{ marginTop: "20px" } :{ marginTop: "20px", marginLeft:"30px" }}>
<Col lg={12}>
<Row>
<Col lg={12} style={{ display: "inline-flex" }}>
<img
src={studentImage}
alt={""}
style={{
width: "30px",
height: "30px",
borderRadius: "50px",
}}
/>
<div style={{ paddingLeft: "20px" }}>
<p>
<span style={{ fontSize: "15px", fontWeight: "bold" }}>
Vanitha
</span>{" "}
<br />
<span style={{ fontSize: "12px" }}>
Commented On -{" "}
<span style={{ fontSize: "10px" }}>
11/16/2019 2:45:37 PM
</span>
</span>
</p>
</div>
</Col>
<Col lg={12}>
<div style={{ paddingLeft: "50px" }}>
There is no difference between them.
</div>
<span style={{float:"right"}}>
{width < 500 ?
<React.Fragment>
{/* <a href={"/"}><img style={{width:'15px',height:'15px', marginLeft: '20px'}} src={Clarify} alt={'clarify'}/></a> */}
<a href={"/"}><img style={{width:'15px',height:'15px', marginLeft: '20px',marginRight: '10px'}} src={Agree} alt={'answer'}/></a>
<a href={"/"}><img style={{width:'15px',height:'15px', marginLeft: '20px'}} src={Comment} alt={'comment'}/></a>
<a href={"/"}><img style={{width:'15px',height:'15px', marginLeft: '20px'}} src={deleteIcon} alt={'comment'}/></a>
</React.Fragment>:
<React.Fragment>
<a style={{width:'15px',height:'15px', marginLeft: '20px',fontSize:'13px'}} href={"/"}>Agree</a>
<a style={{width:'15px',height:'15px', marginLeft: '20px',fontSize:'13px'}} href={"/"}>Comment</a>
<a style={{width:'15px',height:'15px', marginLeft: '20px',fontSize:'13px'}} href={"/"}>Delete</a>
</React.Fragment>
}
</span>
</Col>
</Row>
</Col>
</Row>
<Row style={ width < 500 ?{ marginTop: "20px" } :{ marginTop: "20px", marginLeft:"30px" }}>
<Col lg={12}>
<Row>
<Col lg={12} style={{ display: "inline-flex" }}>
<img
src={teacherImage}
alt={""}
style={{
width: "30px",
height: "30px",
borderRadius: "50px",
}}
/>
<div style={{ paddingLeft: "20px" }}>
<p>
<span style={{ fontSize: "15px", fontWeight: "bold" }}>
Teacher - Abinaya Sekar
</span>{" "}
<br />
<span style={{ fontSize: "12px", color: "green" }}>
Answer for clarification -{" "}
<span style={{ fontSize: "10px", color: "black" }}>
11/15/2019 3:32:45 PM
</span>
</span>
</p>
</div>
</Col>
<Col lg={12}>
<Row>
<Col
md={1}
xs={2}
style={{ borderRight: "5px solid green" }}
></Col>
<Col md={11} xs={10}>
<div style={{ fontWeight: "600", padding: "10px" }}>
Jansirani answer is wrong.
Electromagnetism is a branch of physics that involvesthe study of electromagnetic force.
It is a type of interaction that occurs between electrically charged particles.
</div>
<span style={{float:"right"}}>
{width < 500 ?
<React.Fragment>
<a href={"/"}><img style={{width:'20px',height:'20px', marginLeft: '20px'}} src={edit} alt={'clarify'}/></a>
<a href={"/"}><img style={{width:'15px',height:'15px', marginLeft: '20px'}} src={deleteIcon} alt={'comment'}/></a>
{/* <a href={"/"}><img style={{width:'15px',height:'15px', marginLeft: '20px',marginRight: '10px'}} src={Answer} alt={'answer'}/></a> */}
</React.Fragment>:
<React.Fragment>
<a style={{width:'15px',height:'15px', marginLeft: '20px',fontSize:'13px'}} href={"/"}>Edit</a>
{/* <a style={{width:'15px',height:'15px', marginLeft: '20px',fontSize:'13px'}} href={"/"}>Comment</a> */}
<a style={{width:'15px',height:'15px', marginLeft: '20px',fontSize:'13px'}} href={"/"}>Delete</a>
</React.Fragment>
}
</span>
</Col>
</Row>
</Col>
</Row>
</Col>
</Row>
</Container>
</Row>
</Container>
</React.Fragment>
);
};
export default Student;
|
var Gearbox = require('gearbox'),
expect = require('chai').expect;
var box, blueprint;
describe ('Setup for implicit blueprint tests', function() {
this.timeout(50000);
it('should get a new Gearbox instance for awkward blueprint tests', function () {
box = new Gearbox();
});
it('should explicitly add dir containing blueprint gear', function () {
box.registerGearPath('blueprint', __dirname, './../gear');
});
it('should append dir containing test gears', function () {
box.appendToPath('./gears', __dirname);
});
it ('should get a blueprint gear for awkward tests', function(done) {
box.get('blueprint', {}, function(err, gear) {
expect(err).to.equal(null);
blueprint = gear;
done();
});
});
});
describe ('Implicit tests', function() {
it ('should register implicit blueprint', function() {
blueprint.registerBlueprintDir('implicit', __dirname, './blueprints/implicit-blueprint');
});
it ('Should get implicit blueprint', function(done) {
blueprint.get(
'implicit',
function (err, bp) {
expect(err).to.equal(null);
var widget;
widget = bp.findGearByPath('canvas.explicitContainer.explicitRow1.explicitColumn1.givenName');
expect(widget._id).to.equal('givenName');
widget = bp.findGearByPath('canvas.explicitContainer.explicitRow2.column1.familyName');
expect(widget._id).to.equal('familyName');
widget = bp.findGearByPath('canvas.container1.row2.column3.email');
expect(widget._id).to.equal('email');
done();
}
);
});
});
|
const express = require('express')
const app = express()
const bodyParser = require('body-parser')
const routerNavigation = require('./src')
const morgan = require('morgan')
const cors = require('cors')
app.listen(3001, "127.0.0.1",()=> {
console.log("listening on 127.0.0.1:3001");
})
app.use(cors())
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}))
app.use(morgan("dev"))
app.use('/', routerNavigation)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.