text
stringlengths 7
3.69M
|
|---|
const express = require('express');
const router = express.Router();
const db = require('../models');
const ItemStatus = db.ItemStatus;
// fetching user routes
router.route('/')
.get((req, res) => {
return ItemStatus.findAll()
.then((statuses) => {
console.log('list of statuses returned');
return res.json(statuses);
});
});
module.exports = router;
|
function binaryAgent(str) {
let arr = str.split(' ');
let newStrArr = [];
for(let i in arr) {
newStrArr.push(String.fromCharCode(parseInt(arr[i], 2)))
}
return newStrArr.join('');
}
binaryAgent("01000001 01110010 01100101 01101110 00100111 01110100 00100000 01100010 01101111 01101110 01100110 01101001 01110010 01100101 01110011 00100000 01100110 01110101 01101110 00100001 00111111");
|
export const content={
'id': 0,
'title': '人工智能的发展历史与当今应用领域',
'author': {
'id': 0,
'username': '王永',
'role': 'AI研究员',
},
};
|
module.exports = {
options: {
outputStyle: 'nested',
sourceMap: true
},
defaults: {
cwd: '<%= paths.src %>/scss/',
src: [
'styles-veams.scss',
'styles-veams-generator.scss',
'styles-veams-methodology.scss',
'styles-veams-js.scss',
'styles-veams-components.scss',
'styles-veams-sass.scss'
],
dest: '<%= paths.dev %>/css/',
expand: true,
ext: '.css'
}
};
|
// Global variable.
let onloadPlatform, xScale, xScale2, x_axis, x_axis_el, yScale, yScale2, y_axis, y_axis_el, info, yOld, xOld,
x1, x2, transformXY, xFunc, yFunc, w, d, e, g, x, y, margin, width, height, funcTested, funC, zoomTransform,
func2, txx = 0;
|
import React, { Component } from 'react';
import {connect} from 'react-redux';
import {onUpdateA,onUpdateB,onUpdateC,onUpdateD} from '../Action/Task2action';
class Task2component extends Component{
render(){
return(
<div> your number:
<span>{this.props.numa}</span>
<button onClick={()=>this.props.onUpdateA(this.props.numc)}>UpdateA</button>
<span>{this.props.numb}</span>
<button onClick={()=>this.props.onUpdateB(this.props.numd)}>UpdateB</button>
<span>{this.props.numc}</span>
<button onClick={()=>this.props.onUpdateC(this.props.numa)}>UpdateC</button>
<span>{this.props.numd}</span>
<button onClick={()=>this.props.onUpdateD(this.props.numb)}>UpdateD</button>
</div>
);
}
}
const mapStateToProps=(state)=>{
const{numa}=state.Task2reducerA;
const{numb}=state.Task2reducerB;
const{numc}=state.Task2reducerC;
const{numd}=state.Task2reducerD;
return{numa,numb,numc,numd};
};
export default connect(mapStateToProps,{onUpdateA,onUpdateB,onUpdateC,onUpdateD})(Task2component);
|
import React, { Component } from 'react';
import axios from 'axios';
import moment from 'moment'
// Internal Imports
import HabitList from '../Habits/HabitsList';
import HabitsForm from '../Habits/HabitsForm'
import Chart from './ChartsContainer'
class HabitContainer extends Component{
state={
user: '',
Habits : [],
ajaxloaded : false,
HabitsData: ''
}
componentDidMount(){
this.fetchData();
}
editHabit = (habitId)=>{
console.log(habitId)
}
addHabit=(habit)=>{
axios.post('http://localhost:4000/api/v1/habits/create',{name: `${habit}`, id: localStorage.getItem('uid')}).then(
(res)=>{
this.setState({
Habits : [...this.state.Habits, res.data.data]
})
}
)
}
updateHabit=(habitId, habitName)=>{
axios.put(`http://localhost:4000/api/v1/habits/${habitId}/edit`,{name: habitName}).then(
this.setState({
Habits : [...this.state.Habits.map(
habit=>{
if(habit._id === habitId){
habit.name = habitName
}
return habit
}
)]
})
).catch(err=>{
console.log(err)
})
}
deleteHabit=(habitId)=>{
console.log(habitId)
axios.delete(`http://localhost:4000/api/v1/habits/${habitId}`).then(
res=>{
this.setState({
Habits : [...this.state.Habits.filter(habit=> habit._id !== habitId)]
})
}
).catch(
err=>{
console.log(err)
}
)
}
checkboxHandler =(habitId)=>{
console.log(habitId)
console.log(moment()._d)
axios.put(`http://localhost:4000/api/v1/habits/edit/${habitId}`, {"date" : moment().format("MMM Do YYYY")}).then(res=>{
this.setState({
Habits : [...this.state.Habits.map(habit=>{
if(habit._id=== habitId){
habit.daysCompleted= res.data.data.daysCompleted
}
return habit
})]
})
}).catch(err=>{
console.log(err)
})
}
render(){
return(
<div className="habits-container">
<div className="habits">
<HabitsForm addHabit={this.addHabit} />
<HabitList checkboxHandler={this.checkboxHandler} habits={this.state.Habits} deleteHabit={this.deleteHabit} editHabit={this.editHabit} updateHabit={this.updateHabit} />
</div>
<div className='chart'>
<Chart habits={this.state.Habits} />
</div>
</div>
)
}
fetchData =()=>{
axios.get(`http://localhost:4000/api/v1/users/${localStorage.getItem('uid')}`).then(
res=>{
console.log(res);
this.setState({
Habits : res.data.data.habits,
ajaxloaded: true
})
}
).catch(err=>{
console.log(err)
})
}
}
export default HabitContainer;
|
import React from "react";
import { useSelector, useDispatch } from "react-redux";
import * as balanceActions from "../actions/balanceActions";
function ReduxDeposit() {
const balance = useSelector(state => state.balanceReducer.balance);
const loading = useSelector(state => state.balanceReducer.loading);
const loan = useSelector(state => state.loanReducer.loan);
const dispatch = useDispatch();
const onDepositHandle = () => {
dispatch(balanceActions.depositAsync());
};
return (
<div>
{loading ? <h1>saving......</h1> : <h1>Balance: {balance}</h1>}
{loan ? <h1>Loan Applied</h1> : null}
<button onClick={onDepositHandle}>Deposit</button>
</div>
);
}
export default ReduxDeposit;
|
jsfac.module('application', ['dashboard', 'diagnostics'], function (register) {
register('main', ['fooWidgetViewModel', 'barWidgetViewModel', 'eventMonitorViewModel'],
function (fooWidgetViewModel, barWidgetViewModel, eventMonitorViewModel) {
return {
foo: fooWidgetViewModel,
bar: barWidgetViewModel,
monitor: eventMonitorViewModel
};
});
});
|
define(['angularAMD',
'angular-moment',
'angular-ui-select',
'angular-ui-grid',
'angular-validation',
'ng-tagsinput',
'rate',
'apps/base/base.service',
'apps/base/base.service.permission',
'apps/base/base.service.enum',
'apps/base/base.service.notification',
'apps/base/base.service.attach',
'apps/base/base.service.tag',
'apps/base/base.service.process',
'apps/base/base.service.message',
'apps/base/base.service.settings',
'apps/base/base.directive.book',
'apps/base/base.directive.editor',
'apps/base/base.directive.tagsinput',
'apps/base/base.directive.popover',
'apps/base/base.directive.panel',
'apps/base/base.directive.icheck',
'apps/base/base.directive.tree',
'apps/base/base.directive.split',
'apps/base/base.directive.drawer',
'apps/base/base.directive.wizard',
'apps/base/base.directive.permission',
'apps/base/base.directive.datepicker',
'apps/base/base.directive.plUpload',
'apps/base/base.directive.notification',
'apps/base/base.directive.process',
'apps/base/base.directive.user',
'apps/base/base.directive.charts'],
function (angularAMD) {
var controller = angular.module('base.controller', [
'base.service','angularMoment',
'ngCkeditor',
'ngAnimate',
'ui.bootstrap',
'ngSanitize',
'ngTouch',
'ngTagsInput',
'ngRateIt',
'ui.router',
'ct.ui.router.extras',
'ui.select',
'ui.grid',
'ui.grid.selection',
'ui.grid.treeView',
'ui.grid.edit',
'ui.grid.cellNav',
'ui.grid.infiniteScroll',
'ui.grid.pagination',
'ui.grid.exporter',
'ui.grid.autoResize',
'ui.grid.grouping',
'ui.grid.resizeColumns',
'ui.grid.moveColumns',
'ui.grid.pinning',
'ui.grid.cellNav',
'validation', 'validation.rule',
'ui.bootstrap.timepicker',
'ui.bootstrap.popover',
'ui.bootstrap.progressbar',
'ui.bootstrap.typeahead',
'ui.bootstrap.modal',
'ui.bootstrap.accordion',
'ui.bootstrap.tabs']);
controller.controller('base.controller.page',
function ($rootScope, $scope, $location, $state, $timeout, $uibModal, menuService,
localStorageService, notificationService, userService, chatClient,
imagePreviewUrl, userApiUrl, userApiVersion, moment,Restangular) {
moment.locale("zh-cn");
// 菜单栏最小化后的鼠标事件
$scope.initSilder = handSilderHover;
$scope.imageBaseSrc = imagePreviewUrl;
$scope.changeBusiness = function (b) {
$rootScope.currentBusiness = b;
}
$scope.$watch("currentBusiness", function (newVal, oldVal) {
if(newVal && newVal.tabs.length > 0){
var firstTab = newVal.tabs[0];
$state.go(firstTab.state, firstTab.params);
}
$rootScope.$broadcast("businessChanged", newVal);
});
$rootScope.filterUsers = function (filter) {
var result = [];
angular.forEach($rootScope.user_item, function (user) {
if (filter.length == 0 || user.Name.indexOf(filter) >= 0) {
result.push({
ID: user.ID,
Name: user.Name,
Dept: user.Dept,
PhotoImg: user.PhotoImg
});
}
})
return result;
}
var getMyGroupCount = function () {
var count = 0;
angular.forEach($scope.chatGroups, function (g) {
if (g.CreateEmpID == $scope.currentUser.Account.ID) {
count++;
}
});
return count;
}
$scope.$watch("maxGroupCount", function (newval, oldval) {
if (newval ) {
$scope.canCreateGroup = getMyGroupCount() < newval;
}
});
$scope.$watchCollection("chatGroups", function (newval, oldval) {
if (newval) {
$scope.canCreateGroup = getMyGroupCount() < $scope.maxGroupCount;
}
});
$scope.openNotifyWindow = function (notify) {
$uibModal.open({
animation: false,
templateUrl: 'apps/base/view/notification-list.html',
size: 'lg',
controller: function ($scope, $uibModal, $uibModalInstance, currentNotify) {
$scope.notifications = notificationService.getEffects(1000).$object;
$scope.setCurrentNotify = function (notify) {
$scope.currentNotify = notify;
};
$scope.$watch("currentNotify", function (newval, oldval) {
if (newval && !newval.IsRead) {
newval.IsRead = true;
// 设置提醒已读
notificationService.read(newval.ID);
}
});
$scope.viewObject = function () {
var info = {};
var objItems = $rootScope.getBaseData("Object");
var objTags = objItems.find(function (item) {
return item.Tags["name"] == $scope.currentNotify.SourceName;
});
info.controller = objTags["controller"];
info.template = objTags["template"];
info.controllerUrl = objTags["controllerUrl"];
//angular.forEach($rootScope.Object_item, function (item) {
// if (item.Tags["name"] == $scope.currentNotify.SourceName) {
// info.controller = item.Tags["controller"];
// info.template = item.Tags["template"];
// info.controllerUrl = item.Tags["controllerUrl"];
// }
//});
$uibModal.open({
animation: false,
size: 'lg',
windowTopClass: 'fade',
templateUrl: info.template,
controller: info.controller,
resolve: {
loadController: angularAMD.$load(info.controllerUrl),
objParam: function () {
return {
id: $scope.currentNotify.SourceID,
view: true
}
},
}
});
};
$scope.close = function () {
$uibModalInstance.dismiss('cancel');
}
$scope.currentNotify = currentNotify;
},
resolve: {
currentNotify: function () {
return notify;
}
}
});
};
$scope.settings = function () {
$uibModal.open({
animation: false,
templateUrl: 'apps/base/view/personal-settings.html',
size: 'lg',
controller: function ($scope, $uibModal, $uibModalInstance, userService) {
$scope.chooseImg1 = function (id) {
$scope.currentUser.Account.PhotoImg = id + ".jpg";
userService.setUserImage(id + ".jpg", id + "x.jpg");
}
$scope.chooseImg2 = function (id) {
$scope.currentUser.Account.PhotoImg = 'avatar' + id + ".png";
userService.setUserImage('avatar' + id + ".png", 'avatar' + id + "_big.png");
}
$scope.close = function () {
$uibModalInstance.dismiss('cancel');
}
}
});
}
$scope.isActive = function (viewLocation) {
return viewLocation === $location.path();
};
$scope.addToQuickLink = function(){
userService.addUserConfig({
ConfigName : 'QuickLink',
ConfigKey : $state.current.name,
ConfigValue : JSON.stringify($state.params),
ConfigText : $state.current.text,
}).then(function(result){
if(result == 3){
bootbox.alert( $state.current.text + "重复添加");
}else{
bootbox.alert( $state.current.text + "加入快速访问成功");
}
});
}
$scope.goQuick = function(item){
$state.go(item.ConfigKey,JSON.parse(item.ConfigValue))
}
// 注销
$scope.logout = function () {
localStorageService.remove('user_' + $rootScope.currentUser.Account.ID);
var allUser = localStorageService.get("all_user");
for (var i = 0; i < allUser.length; i++) {
if (allUser[i] == $rootScope.currentUser.Account.ID) {
allUser.splice(i, 1);
break;
}
}
localStorageService.set('all_user', allUser);
// 断开当前登录用户的聊天连接
chatClient.disconnect();
if (allUser.length == 0) {
$state.go("login");
} else {
$state.go("chooseuser");
}
}
// 切换用户
$scope.chooseuser = function () {
$state.go("chooseuser");
}
// 访问的历史记录
$scope.viewHistorys = [];
$scope.openMenu = function (menu) {
$scope.viewHistorys.push(menu);
}
$scope.goHis = function (m) {
$state.go(m.Href, m.Param);
}
// 聊天对象
$scope.ChatTargets = [];
// 在线用户列表
$rootScope.onLineUsers = [];
$scope.msgCount = 0;
$scope.groupMsgCount = 0;
$scope.userMsgCount = 0;
// 聊天消息到达
$scope.$on("$chat_message_receive", function (a, message) {
$timeout(function () {
if (message.MessageType == 300 ||
message.MessageType == 303) {
if (!message.isRead) {
$scope.msgCount++;
}
var user = $rootScope.user_item.find(function (uu) { return uu.ID == message.UserIdentity });
if (user) {
user.Title = message.Title;
message.UserPhotoImg = user.PhotoImg;
if (message.TargetUser > 0) {
if (!message.isRead) {
$scope.userMsgCount++;
if (user.unReadMsgCount) {
user.unReadMsgCount++;
} else {
user.unReadMsgCount = 1;
}
}
user.lastMsg = message;
} else {
var group = $scope.chatGroups.find(function (uu) { return uu.GroupID == message.TargetGroup; });
if (!message.isRead) {
$scope.groupMsgCount++;
if (group.unReadMsgCount) {
group.unReadMsgCount++;
} else {
group.unReadMsgCount = 1;
}
group.lastMsg = message;
}
}
}
}
else if (message.MessageType == 302) {
// 发送的消息服务器已接收
} else if (message.MessageType == 100) {
// 新的用户连接到聊天服务
$rootScope.onLineUsers[message.NewConnecedUserID] = message.NewConnecedUserName;
} else if (message.MessageType == 102) {
// 用户离线
$rootScope.onLineUsers[message.OutlineUserIdentity] = undefined;
} else if (message.MessageType == 103) {
$scope.msgCount += message.UnReadMessage.length;
// 用户离线消息
angular.forEach(message.UnReadMessage, function (ms) {
var user = $rootScope.user_item.find(function (uu) { return uu.ID == ms.UserIdentity });
if (user) {
ms.UserPhotoImg = user.PhotoImg;
if (ms.TargetUser > 0) {
$scope.userMsgCount++;
if (user.unReadMsgCount) {
user.unReadMsgCount++;
} else {
user.unReadMsgCount = 1;
}
user.lastMsg = ms;
}
}
});
}
else if (message.MessageType == 104) {
if (message.IsNew) {
$scope.chatGroups.push(message.Group);
} else {
// 更新组信息
//var thisGroup = $scope.chatGroups.find(function (g) { return g.GroupID == message.Group.GroupID }) ;
//thisGroup= message.Group;
for (var i = 0; i < $scope.chatGroups.length; i++) {
if ($scope.chatGroups[i].GroupID == message.Group.GroupID) {
$scope.chatGroups[i] = message.Group;
break;
}
}
}
} else if (message.MessageType == 105) {
// 删除组
$scope.chatGroups.custRemove(function (g) {
return g.GroupID == message.GroupID
});
} else if (message.MessageType == 106) {
// 退组
var thisGroup = $scope.chatGroups.find(function (g) { return g.GroupID == message.GroupID });
thisGroup.UserIDs.custRemove(function (u) {
return u.EmpID == message.UserID
});
if (thisGroup.Users) {
thisGroup.Users.custRemove(function (u) {
return u.ID == message.UserID
});
}
} else if (message.MessageType == 107) {
// 用户所在的组
$scope.chatGroups = message.Groups;
} else if (message.MessageType == 108) {
// 在线用户列表
$rootScope.onLineUsers = message.Users;
} else if (message.MessageType == 100) {
// 有新的用户登录
$rootScope.onLineUsers[message.NewConnecedUserID] = message.NewConnecedUserName;
}
});
});
// 断开聊天服务
$scope.$on("$chat_server_close", function (a, message) {
$rootScope.onLineUsers = [];
});
// 添加聊天对象到tab中
var addChatObject = function (target) {
var t = $scope.ChatTargets.find(function (t) { return t.ID == target.ID; });
if (t && !t.visiable) {
target.messages = t.messages;
$scope.ChatTargets.push(target);
$scope.ChatTargets.removeObj(t);
} else if (!t) {
$scope.ChatTargets.push(target);
}
}
// 打开聊天窗口
$rootScope.openChat = function (user, title) {
if (!user.ID) {
user = $scope.user_item.find(function (u) { return u.ID == user });
}
$scope.msgCount = $scope.msgCount - user.unReadMsgCount;
$scope.userMsgCount = $scope.userMsgCount - user.unReadMsgCount;
user.visiable = true;
user.unReadMsgCount = 0;
user.messages = chatClient.getUserMessages(user.ID);
if (title) {
user.Title = title;
}
addChatObject(user);
var modalInstance = $uibModal.open({
animation: false,
dialogClass: 'dragable',
templateUrl: 'apps/base/view/chat.html',
controller: 'base.controller.chat',
size: 'lg',
resolve: {
targets: function () {
return $scope.ChatTargets;
},
currentChatTagrget: function () {
return user;
},
msgCountSrv: function () {
return {
set: function (unReadMsgCount) {
$scope.msgCount = $scope.msgCount - unReadMsgCount;
$scope.userMsgCount = $scope.userMsgCount - unReadMsgCount;
}
};
}
}
});
modalInstance.result.then(function () {
//success
// 设置当前聊天对象
chatClient.setCurrentChatUser(0);
}, function () {
//dismissed
// 设置当前聊天对象
chatClient.setCurrentChatUser(0);
});
};
// 打开组聊天窗口
$rootScope.openGroupChat = function (group) {
$scope.msgCount = $scope.msgCount - group.unReadMsgCount;
$scope.groupMsgCount = $scope.groupMsgCount - group.unReadMsgCount;
group.ID = group.GroupID;
//group.Name = group.GroupName;
//group.PhotoImg = 'assets/global/images/avatars/' + (group.IsPublic ? 'b2x.jpg' : 'ba2x.jpg');
group.IsGroup = true;
group.visiable = true;
group.unReadMsgCount = 0;
group.messages = chatClient.getUserMessages(group.GroupID)
if (group.IsPublic) {
group.Users = $rootScope.user_item;
} else if (group.UserIDs.length > 0 && !group.Users) {
group.Users = group.UserIDs.map(function (u) {
return $rootScope.user_item.find(function (_u) {
return _u.ID == u.EmpID;
})
});
}
addChatObject(group);
var modalInstance = $uibModal.open({
animation: false,
dialogClass: 'dragable',
templateUrl: 'apps/base/view/chat.html',
controller: 'base.controller.chat',
size: 'lg',
resolve: {
targets: function () {
return $scope.ChatTargets;
},
currentChatTagrget: function () {
return group;
},
msgCountSrv: function () {
return {
set: function (unReadMsgCount) {
$scope.msgCount = $scope.msgCount - unReadMsgCount;
$scope.groupMsgCount = $scope.groupMsgCount - unReadMsgCount;
}
};
}
}
});
modalInstance.result.then(function () {
//success
// 设置当前聊天对象
chatClient.setCurrentChatUser(0);
}, function () {
//dismissed
// 设置当前聊天对象
chatClient.setCurrentChatUser(0);
});
}
// 创建聊天分组
$scope.createChatGroup = function () {
var modalInstance = $uibModal.open({
animation: true,
dialogClass: 'dragable',
templateUrl: 'apps/base/view/crate-chatgroup.html',
controller: 'base.controller.createchatgroup'
});
}
// 修改密码窗口
$scope.changePassword = function () {
$uibModal.open({
animation: true,
templateUrl: 'apps/base/view/change-password.html',
controller: 'base.controller.changePassword'
});
}
// 页面参数
$scope.lang = 'zh-cn';
$scope.pageSize = 20;
$scope.pageSizes = [20, 50, 100];
// 保存文件流
$rootScope.saveAs = function (res, fileName) {
var myFile = streamSaver.createWriteStream(fileName);
let reader = res.body.getReader()
let pump = () => {
return reader.read().then(({ value, done }) => {
if (done) {
myFile.close()
return
}
myFile.write(value)
return pump()
})
}
pump()
}
Restangular.setErrorInterceptor(function (response, deferred, responseHandler) {
if (response.status === 500) {
notificationService.showException(response.data.ExceptionMessage,response.data.ExceptionType,response.data.StackTrace);
return false; // error handled
}
return true; // error not handled
});
});
return controller;
});
|
import Vue from "vue";
import Request from './scms-requests';
let sg = {}
sg.install = function (Vue, options) {
Vue.prototype.$scms = {
Request,
showDate(id){
const date = new Date(parseInt(id.toString().substring(0, 8), 16) * 1000);
const day = date.getDate().toString().length == 1 ? "0" + date.getDate().toString():date.getDate().toString();
const month = (Number(date.getMonth()) + 1).toString().length == 1 ? "0" + (Number(date.getMonth()) + 1):(Number(date.getMonth()) + 1).toString();
const year = date.getFullYear().toString().length == 1 ? "0" + date.getFullYear().toString():date.getFullYear().toString();
return [year,month,day].join('/')
},
showTime(id){
const date = new Date(parseInt(id.toString().substring(0, 8), 16) * 1000);
return [date.getHours(),date.getMinutes(),date.getSeconds()].join(":")
},
toFullHtml(content){
const patternObj = {
code:{
reg:/\[code\](.*?)\[\/code]/g
},
br:{
reg:/(?:\r\n|\r|\n)/g,
newStr:"<br />"
},
b:{
reg:/\[b\](.*?)\[\/b\]/g,
newStr:"<b>$1</b>"
},
img:{
reg:/\[img(.*?)](.*?)\[\/img\]/g
},
url:{
reg:/\[url.*?].*?\[\/url\]/g
},
color:{
reg:/\[c='(.*?)'\](.*?)\[\/c\]/g,
newStr:"<span style='color:$1'>$2</span>"
},
size:{
reg:/\[s='(.*?)'\](.*?)\[\/s\]/g,
newStr:"<span style='font-size:$1'>$2</span>",
},
i:{
reg:/\[i\](.*?)\[\/i\]/g,
newStr:"<i>$1</i>"
},
quote:{
reg:/\[quote](.*?)\[\/quote]/g,
newStr:"<blockquote>$1</blockquote>"
},
u:{
reg:/\[u\](.*?)\[\/u\]/g,
newStr:"<u>$1</u>"
}
};
let newContent = content.replace(/\</g,"<").replace(/\>/g,">");
for (let pat in patternObj){
let tags
switch (pat){
case "code":
tags = newContent.match(patternObj[pat].reg);
if (tags !== null){
tags.forEach(code => {
let convertedTag = code.replace(patternObj[pat].reg,"$1");
convertedTag = convertedTag.replace(/\</g,"<");
convertedTag = convertedTag.replace(/\>/g,">");
newContent = newContent.replace(/\[code](.*?)\[\/code\]/, `<blockquote class='pre-scrollable'>${convertedTag}</blockquote>`);
});
}
break;
case "img":
tags = newContent.match(patternObj[pat].reg);
if (tags !== null){
tags.forEach(img =>{
const attributes = (img.match(/\[img(.*?)]/))[1];
const url = (img.match(/\](.*?)\[\//))[1];
const alt = attributes.match(/a=\'(.*?)\'/) === null ? "":` alt='${(attributes.match(/a=\'(.*?)\'/))[1]}'`; //更换alt标签
const w = attributes.match(/w=\'(.*?)\'/) === null ? "":` width='${(attributes.match(/w=\'(.*?)\'/))[1]}'`; //更换width标签
const h = attributes.match(/h=\'(.*?)\'/) === null ? "":` height='${(attributes.match(/h=\'(.*?)\'/))[1]}'`; //更换height标签
const imgTag = `<img${alt}${w}${h} src='${url}' />`;
newContent = newContent.replace(/\[img.*?].*?\[\/img\]/,imgTag);
});
}
break;
case "url":
tags = newContent.match(patternObj[pat].reg);
if (tags !== null){
tags.forEach(url => {
const attributes = (url.match(/\[url(.*?)]/))[1];
const alt = (url.match(/\](.*?)\[\//))[1] === "" ? `${(attributes.match(/a=\'(.*?)\'/))[1]}`:(url.match(/\](.*?)\[\//))[1];
const link = `href='${attributes.match(/a=\'(.*?)\'/)[1]}'`;
const urlTag = `<a ${link}>${alt}</a>`;
newContent = newContent.replace(/\[url.*?].*?\[\/url\]/,urlTag);
});
}
break;
default:
newContent = newContent.replace(patternObj[pat].reg,patternObj[pat].newStr);
}
}
return newContent
},
showShortArticle(content,id){
let endNum = 150;
const patternObj = {
code:{
reg:/\[code\](.*?)\[\/code]/g
},
b:{
reg:/\[b\](.*?)\[\/b\]/g,
newStr:"$1"
},
img:{
reg:/\[img(.*?)](.*?)\[\/img\]/g,
},
url:{
reg:/\[url.*?].*?\[\/url\]/g
},
color:{
reg:/\[c='(.*?)'\](.*?)\[\/c\]/g,
newStr:"$2"
},
size:{
reg:/\[s='(.*?)'\](.*?)\[\/s\]/g,
newStr:"$2",
},
i:{
reg:/\[i\](.*?)\[\/i\]/g,
newStr:"$1"
},
quote:{
reg:/\[quote](.*?)\[\/quote]/g,
newStr:"$1"
},
u:{
reg:/\[u\](.*?)\[\/u\]/g,
newStr:"$1"
}
};
let newContent = content.replace(/\</g,"<").replace(/\>/g,">");
let matched;
for (let pat in patternObj){
//replace html tags
switch (pat){
case "img":
matched = newContent.match(patternObj[pat].reg);
newContent = newContent.replace(patternObj[pat].reg,`<a href='/articles/${id}'>查看图片</a>`);
if (matched !== null){
endNum += (`<a href='/articles/${id}'>查看源码</a>`.length) * matched.length;
}
break;
case "code":
matched = newContent.match(patternObj[pat].reg);
newContent = newContent.replace(patternObj[pat].reg,`<a href='/articles/${id}'>查看源码</a>`);
if (matched !== null){
endNum += (`<a href='/articles/${id}'>查看源码</a>`.length) * matched.length;
}
break;
case "url":
const tags = newContent.match(patternObj[pat].reg);
if (tags !== null){
tags.forEach(url => {
const attributes = (url.match(/\[url(.*?)]/))[1];
const alt = (url.match(/\](.*?)\[\//))[1] === "" ? `${(attributes.match(/a=\'(.*?)\'/))[1]}`:(url.match(/\](.*?)\[\//))[1];
const link = `href='${attributes.match(/a=\'(.*?)\'/)[1]}'`;
const urlTag = `<a ${link}>${alt}</a>`;
endNum += urlTag.length;
newContent = newContent.replace(/\[url.*?].*?\[\/url\]/,urlTag);
});
}
break;
default:
newContent = newContent.replace(patternObj[pat].reg,patternObj[pat].newStr);
}
}
if (newContent.length < endNum){
return newContent
};
return newContent.substring(0,endNum) + ` <a href='/articles/${id}'>更多...</a>`;
},
showShortTitle(title,num){
if (title.length > num){
return title.substring(0,num) + " ...."
}
return title
},
showCommentNumber(comments){
let num = 0;
if (comments.length != 0){
comments.forEach(cm =>{
num +=1;
for (let i = 0;i < Object.keys(cm.comments).length;i ++){
num += 1;
}
});
}
return num
},
readObjectUrlAsFile:url =>{
return new Promise( (resolve, reject) =>{
const xhr = new XMLHttpRequest();
xhr.open('GET', url , true);
xhr.responseType = 'blob';
xhr.onload = e=> {
if (xhr.status == 200) {
const blobData = xhr.response;
resolve( blobData );
}else{
reject( xhr.statusText );
}
};
xhr.send();
});
}
}
}
Vue.use(sg);
|
import React, { Component } from 'react';
import { imagePath } from '../../utils/assetUtils';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import styles from './home.scss';
import {
Carousel,
CarouselItem,
CarouselIndicators
} from 'reactstrap';
// const mapStateToProps = state => ({});
// const mapDispatchToProps = dispatch => ({
// dispatch
// });
const items = [
{
src: 't1.jpg',
altText: 'Slide 1',
caption: 'Paneer Pudina Tikka and Mutton Sheesh Kabab?',
shortDescription: 'Getting the right venue for my wedding was proving to be a huge task. Knots&Vows helped me find that perfect venue at the right price. I love the fact that I could select only the specific service that I needed and not go for the entire package.',
buttonText: 'Browse caterers',
pathToRedirect: 'wishlist',
descAuthor: 'Haritha K',
}, {
src: 't2.jpg',
altText: 'Slide 1',
caption: 'Paneer Pudina Tikka and Mutton Sheesh Kabab?',
shortDescription: 'I really thought that I can plan my own wedding with help of my friends & family. After talking to Knots&Vows I realized the amount of work & stress the planning would be. Their services & price made it a no brainer for me to pick them as my wedding planner. ',
buttonText: 'Browse caterers',
pathToRedirect: 'wishlist',
descAuthor: 'Rajesh G',
}, {
src: 't3.jpg',
altText: 'Slide 1',
caption: 'Paneer Pudina Tikka and Mutton Sheesh Kabab?',
shortDescription: 'Knots&Vows really helped me turn my dreams into reality. From the decor to the food and from the photographer to the mehendi artist, everything was top-notch to say the least.',
buttonText: 'Browse caterers',
pathToRedirect: 'wishlist',
descAuthor: 'Akhila V',
}, {
src: 't4.jpg',
altText: 'Slide 1',
caption: 'Paneer Pudina Tikka and Mutton Sheesh Kabab?',
shortDescription: 'I thank my friend for recommending Knots&Vows. I was planning a simple wedding but with a lot of warmth. With the help of Knots&Vows, I achieved exactly that. ',
buttonText: 'Browse caterers',
pathToRedirect: 'wishlist',
descAuthor: 'Nishanth B',
}
];
class CarouselComponent extends Component {
constructor(props) {
super(props);
this.state = { activeIndex: 0 };
}
onExiting = () => {
this.animating = true;
}
onExited = () => {
this.animating = false;
}
next = () => {
if (this.animating) return;
const nextIndex = this.state.activeIndex === items.length - 1 ? 0 : this.state.activeIndex + 1;
this.setState({ activeIndex: nextIndex });
}
previous = () => {
if (this.animating) return;
const nextIndex = this.state.activeIndex === 0 ? items.length - 1 : this.state.activeIndex - 1;
this.setState({ activeIndex: nextIndex });
}
goToIndex = (newIndex) => {
if (this.animating) return;
this.setState({ activeIndex: newIndex });
}
render() {
const { activeIndex } = this.state;
const slides = items.map((item, index) => {
return (
<CarouselItem
onExiting={this.onExiting}
onExited={this.onExited}
key={index}>
<div className={styles.carouselItem}>
<div className={styles.carouselImage} style={{ backgroundImage: `url(${imagePath(item.src)})` }}></div>
<div className={styles.carouselContent}>
<img src={imagePath('quote.svg')} alt="quote" />
<p className={`${styles.carouselText} ${this.props.isZoom ? styles.carouselTextLarge : ''}`}>{item.shortDescription}</p>
<p className={styles.author}>{item.descAuthor}</p>
</div>
</div>
</CarouselItem>
);
});
return (
<div className={styles.carousel}>
<Carousel
activeIndex={activeIndex}
next={this.next}
previous={this.previous}>
<CarouselIndicators items={items} activeIndex={activeIndex} onClickHandler={this.goToIndex} />
{slides}
</Carousel>
</div>
);
}
}
CarouselComponent.propTypes = {
isZoom: PropTypes.bool,
};
export default connect(
)(CarouselComponent);
|
import React from 'react';
import PropTypes from 'prop-types';
import TrainingListItem from '../TrainingListItem';
const TrainingList = ({ trainings }) => {
const elements = trainings.map((item, index) => {
/* destructured id, spred operator ...propsExceptId */
return (
<TrainingListItem
key={index}
item={item}
/>
);
});
return (
<ul>
{ elements }
</ul>
);
};
TrainingList.propTypes = {
trainings: PropTypes.array
};
export default TrainingList;
|
import React from 'react';
import { AppMenu } from './component/menu';
import './App.less';
import imgAva from './imgs/avatar.png';
import { Layout, Avatar, Menu } from 'antd';
const { Header, Footer, Sider, Content } = Layout;
const MyAvatar = () => {
return <img src={imgAva} />
}
const App = () => (
<div className="App">
<Layout>
<Header>
<Avatar size={64} icon={<MyAvatar />} />
<div className='title'>
jay-app-cli
</div>
</Header>
<Layout>
<Sider>
<AppMenu />
</Sider>
<Content>Content</Content>
</Layout>
<Footer>
<div>
<div>版权所有©</div>
<div>jay-app-cli:Email:756774388@qq.com</div>
</div>
</Footer>
</Layout>
</div>
);
export default App;
|
/*
* 在 Telegram 群組中取得群組的 ID,以便於配置互聯機器人
*/
module.exports = ( pluginManager, options ) => {
let tg = pluginManager.handlers.get( 'Telegram' );
if ( tg ) {
tg.addCommand( 'thisgroupid', ( context ) => {
if ( context.isPrivate ) {
context.reply( `YourId = ${ context.from }` );
console.log( `\x1b[33m[Connect]\x1b[0m [groupid-tg.js] Msg #${ context.msgId }: YourId = ${ context.from }` );
} else {
context.reply( `GroupId = ${ context.to }` );
console.log( `\x1b[33m[Connect]\x1b[0m [groupid-tg.js] Msg #${ context.msgId }: GroupId = ${ context.to }` );
}
} );
}
};
|
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/app/App';
// You must include styles inside .jsx files because
// styles won't be aplied to the html even if you have
// extractor for css
import '../css/app.scss';
ReactDOM.render(<App />, document.getElementById('app'));
|
export const dateUnaVuelta = (inc = 1) =>{
return{
type:'INCREMENT',
howMuchToIncrement: inc
}
}
|
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { decrement, increment, incrementAsync, selectCount } from './counterSlice';
import styles from './counter.module.css';
export default () => {
const count = useSelector(selectCount);
const dispatch = useDispatch();
return (
<div>
<div className={styles.row}>
<button className={styles.button} aria-label='Increment value' onClick={() => dispatch(increment())}>
+
</button>
<span className={styles.value}>{count}</span>
<button className={styles.button} aria-label='Decrement value' onClick={() => dispatch(decrement())}>
-
</button>
</div>
<div className={styles.row}>
<button className={styles.asyncButton} onClick={() => dispatch(incrementAsync())}>
Add Async
</button>
</div>
</div>
);
};
|
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
/**
* Project Schema
*/
var ProjectSchema = new Schema({
name: {
type: String,
default: '',
required: 'Please fill Project name',
trim: true
},
description: {
type: String,
trim: true
},
created: {
type: Date,
default: Date.now
},
user: {
type: Schema.ObjectId,
ref: 'User'
},
assignedTo: {
type: Schema.ObjectId,
ref: 'User'
},
completeBy: {
type: Date,
required: false
},
dateCompleted: {
type: Date,
required: false
},
isComplete: {
type: Boolean,
required: false,
default: false
},
percentComplete: {
type: Number,
required: false,
default: 0
},
tasks: [{
type: Schema.ObjectId,
ref: 'Task'
}]
});
/**
* Statics
*/
mongoose.model('Project', ProjectSchema);
|
$(document).ready(function(){
$("#submenu2").hide();
document.getElementById('Edicion').addEventListener("mouseover", muestra_menu,false);
document.getElementById('Edicion').addEventListener("click", oculta_menu,false);
$("#submenu2").hide();
document.getElementById('Herramientas').addEventListener("mouseover", muestra_menu3,false);
document.getElementById('Herramientas').addEventListener("click", oculta_menu3,false);
});
function muestra_menu(){
$("#submenu2").show();
}
function oculta_menu(){
$("#submenu2").hide();
}
function muestra_menu3(){
$("#submenu3").show();
}
function oculta_menu3(){
$("#submenu3").hide();
}
|
'use strict';
// test cases for .join() with only simple components.
var commonTestCases = [
[[''], '.'],
[['/'], '/'],
[['.'], '.'],
[['..'], '..'],
[['foo'], 'foo'],
[['/', ''], '/'],
[['/', '/'], '/'],
[['/', '.'], '/'],
[['/', '..'], '/'],
[['/', 'foo'], '/foo'],
[['.', ''], '.'],
[['.', '/'], '/'],
[['.', '.'], '.'],
[['.', '..'], '..'],
[['.', 'foo'], 'foo'],
[['..', ''], '..'],
[['..', '/'], '/'],
[['..', '.'], '..'],
[['..', '..'], '../..'],
[['..', 'foo'], '../foo'],
[['foo', ''], 'foo/'],
[['foo', '/'], '/'],
[['foo', '.'], 'foo/'],
[['foo', '..'], 'foo/..'],
[['foo', 'x'], 'foo/x']
];
var uncTestCases = [
["\\\\server\\share", {fileName: "", prefix: "\\\\", volumeName: "\\\\server\\share"}],
["\\\\a\\b", {fileName: "", prefix: "\\\\", volumeName: "\\\\a\\b"}],
];
var joinTestCases = [
[['/.', 'a','b', '..', 'b','c.js'], '/a/b/c.js', 'a/b/../b/c.js'],
[['/foo', '../../../bar'], '/bar'],
[['.','foo', '../../../bar'], '../../bar'],
[['.','foo/', '../../../bar'], '../../bar'],
[['.','foo/x', '../../../bar'], '../bar'],
[['foo/x', './bar'], 'foo/x/bar'],
[['foo/x/', './bar'], 'foo/x/bar'],
[['foo/x/', '.', 'bar'], 'foo/x/bar'],
[['.', '.', '.'], '.'],
[['.', './', '.'], '.'],
[['', '', '/foo'], '/foo'],
[['', '', 'foo'], 'foo'],
[['/', '..', '..'], '/'],
[[' /foo'], ' /foo'],
[['/', '//foo'], '/foo'],
[['/', '', '/foo'], '/foo'],
[['', '/', 'foo'], '/foo'],
[['', '/', '/foo'], '/foo']
];
joinTestCases.push(
[['.', '/', '.'], '/'],
[['foo', '', '/bar'], '/bar'],
[['./', '..', '/foo'], '/foo'],
[['foo', '/bar'], '/bar'],
[['foo/', ''], 'foo/'],
[['./', '..', '..', '/foo'], '/foo'],
[['.', '..', '..', '/foo'], '/foo'],
[['', '.', '..', '..', '/foo'], '/foo'],
[[' ', '/'], '/'],
[['./'], '.'],
[['.', './'], '.'],
[['.', '/////./', '.'], '/']
);
var resolveTestCases = commonTestCases.slice();
resolveTestCases.push(
[['.', '/./', '.'], '/'],
[['foo', '', '/bar'], '/bar'],
[['./', '..', '/foo'], '/foo'],
[['foo', '/bar'], '/bar'],
[['foo/', ''], 'foo'],
[['./', '..', '..', '/foo'], '/foo'],
[['.', '..', '..', 'foo'], '../../foo'],
[['', '.', '..', '..', '/foo'], '/foo'],
[['', '.', '..', '..', 'foo'], '../../foo'],
[[' ', '/'], '/'],
[['./'], '.'],
[['.', './'], '.'],
[['/var/lib', '../', 'file/'], '/var/file'],
[['/var/lib', '/../', 'file/'], '/file'],
[['a/b/c/', '../../..'], '.'],
[['/some/dir', '.', '/absolute/'], '/absolute'],
[['.', '/////./', '.'], '/']
);
var io = require("./abstractIO");
var assert = require("assert");
var util = require("util");
var PosixPathStrings = io.PosixPathStrings;
var WindowsPathStrings = io.WindowsPathStrings;
var PathStrings = PosixPathStrings;
var specialPosixPathStrings = ["/", "//", "/.", "//.", ".", "./", ".//", "../", "..//", "..", "/..", "//.."];
var specialRelativeWindowsPathStrings = String.raw`\, .\, ..\, \\, .\\, ..\\, ., \., \\., .., \.., \\..`.split(", ");
var specialVolumeRelativeWindowsPathStrings = specialRelativeWindowsPathStrings.map(path => "C:" + path);
for(var test of commonTestCases) assert.ok(PosixPathStrings.isValid(test[1]));
for(var test of commonTestCases) assert.strictEqual(PosixPathStrings.join(...test[0]), test[1]);
for(var test of joinTestCases) assert.strictEqual(PosixPathStrings.normalize(PosixPathStrings.join(...test[0])), test[1]);
var invariants = [
(ps) => PathStrings.join(...PathStrings.getComponents(ps)) === PathStrings.normalize(ps),
(ps) => ps === "" || PathStrings.normalize(ps).length <= ps.length,
(ps) => PathStrings.normalize(PathStrings.normalize(ps)) === PathStrings.normalize(ps),
(ps) => PathStrings.getRoot(ps) === "" || PathStrings.getRoot(ps) === PathStrings.getPrefix(ps) + PathStrings.getVolumeName(ps) + PathStrings.SEPARATOR,
(ps) => PathStrings.getRoot(ps) === "" || PathStrings.getRoot(ps) === PathStrings.getComponents(ps)[0],
(ps) => PathStrings.getRoot(ps) === "" || PathStrings.getRoot(ps).endsWith(PathStrings.SEPARATOR),
];
function testPaths(paths) {
for(var ps of paths) for(var invariant of invariants) {
assert(invariant(ps));
}
}
testPaths(specialPosixPathStrings);
testPaths(specialRelativeWindowsPathStrings);
testPaths(specialVolumeRelativeWindowsPathStrings);
|
function simpleTimeout(consoleTimer){
console.timeEnd(consoleTimer);
}
var a = {'two':2000,'one':1000,'five':5000,'50Milli':50};
for(var idx in a){
console.time(idx);
setTimeout(simpleTimeout, a[idx], idx);
}
|
/* HTTP Host: static.ak.fbcdn.net */
/* Generated: March 25th 2009 9:41:32 AM PDT */
/* Machine: 10.16.139.101 */
/* Source: Local Cache */
/* Location: rsrc:b318tcm4:nu_ll:/html/js/lib/ui/UIPagelet.js */
/* Locale: nu_ll */
/* Path: js/lib/ui/UIPagelet.js */
function UIPagelet(element,src,context_data,data){this._element=ge(element||$N('div'));this._src=src||null;this._context_data=context_data||{};this._data=data||{};}
copy_properties(UIPagelet.prototype,{getElement:function(){return this._element;},go:function(src,data){if(arguments.length>=2||typeof src=='string'){this._src=src;this._data=data||{};}else if(arguments.length==1){this._data=src;}
this.refresh();return this;},refresh:function(){var handler=function(response){this._element.setContent(HTML(response.getPayload()));}.bind(this);new AsyncRequest().setURI(this._src).setMethod('GET').setData({data:JSON.encode(merge(this._context_data,this._data))}).setReadOnly(true).setHandler(handler).setOption('bundle',true).send();return this;}});
if (window.Bootloader) { Bootloader.done(["js\/lib\/ui\/UIPagelet.js"]); }
|
import React, {useState, useEffect} from 'react';
import {
Text,
View,
Modal,
StyleSheet,
TouchableOpacity,
Dimensions,
} from 'react-native';
import Entypo from 'react-native-vector-icons/Entypo';
import AntDesign from 'react-native-vector-icons/AntDesign';
import MaterialIcons from 'react-native-vector-icons/MaterialIcons';
import SimpleLineIcons from 'react-native-vector-icons/SimpleLineIcons';
import FontAwesome5 from 'react-native-vector-icons/FontAwesome5';
import {colors} from '../constants';
const height = Dimensions.get('window').height;
import {AuthContext} from '../../context';
import AsyncStorage from '@react-native-community/async-storage';
const MenuModal = ({exitModal, popModal, nav}) => {
const {signOut} = React.useContext(AuthContext);
const [name, setName] = useState('');
const closeModal = (item) => {
exitModal(item);
};
const logOut = () => {
signOut();
};
useEffect(() => {
async function getUser() {
let value = await AsyncStorage.getItem('@username');
setName(value);
}
getUser();
}, []);
return (
<View>
<Modal
animationType="slide"
transparent={true}
visible={popModal}
onRequestClose={() => {}}>
<View style={[styles.centeredView, {}]}>
<View style={styles.headerModal}>
<Entypo
name={'cross'}
size={28}
color={'#000'}
onPress={() => closeModal(true)}
/>
<View style={{justifyContent: 'center', alignItems: 'center'}}>
<SimpleLineIcons name={'user'} size={82} color={'#000'} />
<Text style={styles.header}>{name}</Text>
</View>
<AntDesign
name={'logout'}
size={22}
color={'#000'}
onPress={() => {
closeModal(true);
logOut();
}}
/>
</View>
<View style={styles.actions}>
<TouchableOpacity
style={styles.box}
onPress={() => {
closeModal(true);
nav.push('Profile');
}}>
<View style={styles.iconBox}>
<FontAwesome5 name={'user-circle'} size={42} color={'#000'} />
</View>
<Text style={styles.smallText}>Profile</Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.box}
onPress={() => {
closeModal(true);
nav.push('GameHistory');
}}>
<View style={styles.iconBox}>
<FontAwesome5 name={'history'} size={42} color={'#000'} />
</View>
<Text style={styles.smallText}>Game History</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.box}>
<View style={styles.iconBox}>
<FontAwesome5 name={'lock'} size={42} color={'#000'} />
</View>
<Text style={styles.smallText}>Password</Text>
</TouchableOpacity>
{/* <TouchableOpacity
style={styles.box}
onPress={() => {
closeModal(true);
nav.push('Withdraw');
}}>
<View style={styles.iconBox}>
<FontAwesome5
name={'money-bill-alt'}
size={38}
color={'#000'}
/>
</View>
<Text style={styles.smallText}>Withdraw</Text>
</TouchableOpacity> */}
<TouchableOpacity
onPress={() => {
closeModal(true);
nav.push('howtplay');
}}
style={styles.box}>
<View style={styles.iconBox}>
<FontAwesome5 name={'info-circle'} size={42} color={'#000'} />
</View>
<Text style={styles.smallText}>How to Play</Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.box}
onPress={() => {
closeModal(true);
nav.push('Agent');
}}>
<View style={styles.iconBox}>
<MaterialIcons
name={'support-agent'}
size={42}
color={'#000'}
/>
</View>
<Text style={styles.smallText}>Be an Agent</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.box}>
<View style={styles.iconBox}>
<FontAwesome5 name={'share-alt'} size={42} color={'#000'} />
</View>
<Text style={styles.smallText}>Share</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={() => {
closeModal(true);
nav.push('rate');
}} style={styles.box}>
<View style={styles.iconBox}>
<FontAwesome5 name={'th-list'} size={42} color={'#000'} />
</View>
<Text style={styles.smallText}>Rate</Text>
</TouchableOpacity>
{/* <TouchableOpacity
onPress={() => {
closeModal(true);
nav.push('chartls');
}} style={styles.box}>
<View style={styles.iconBox}>
<FontAwesome5 name={'chart-bar'} size={42} color={'#000'} />
</View>
<Text style={styles.smallText}>Chart</Text>
</TouchableOpacity> */}
</View>
</View>
</Modal>
</View>
);
};
const styles = StyleSheet.create({
centeredView: {
flex: 1,
backgroundColor: '#fff',
},
header: {
fontFamily: 'AveriaSansLibre-Regular',
fontSize: 24,
textAlign: 'center',
},
smallText: {
fontSize: 18,
color: '#000',
fontFamily: 'AveriaSansLibre-Regular',
},
submitBtn: {
alignItems: 'center',
justifyContent: 'center',
padding: 10,
backgroundColor: '#6b75c3',
margin: 20,
borderRadius: 6,
width: '40%',
},
box: {flexDirection: 'row', alignItems: 'center', margin: 20},
boxContainer: {
marginTop: height - 600,
alignSelf: 'center',
},
headerModal: {
flexDirection: 'row',
// alignItems: 'center',
justifyContent: 'space-between',
backgroundColor: colors.primary,
paddingBottom: 30,
borderBottomRightRadius: 200,
borderBottomLeftRadius: 200,
height: 200,
paddingHorizontal: 10,
paddingTop: 10,
elevation: 5,
borderBottomColor: '#c4c4c4',
borderBottomWidth: 5,
},
actions: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
flexWrap: 'wrap',
padding: 10,
},
iconBox: {
alignItems: 'center',
justifyContent: 'center',
backgroundColor: colors.primary,
padding: 5,
height: 60,
width: 60,
borderRadius: 60,
},
box: {
alignItems: 'center',
justifyContent: 'center',
margin: 20,
},
});
export default MenuModal;
|
import React from "react";
import { connect } from 'react-redux'
import ProgramTable from './ProgramTable';
import ProgramGraph from './ProgramGraph';
import ProgramCard from './ProgramCard';
import '../../style/programDashboard.css';
class ProgramDashboardRender extends React.Component {
state = {
value: '1'
}
selected = (event) => {
return this.setState({
value: event.target.value
});
}
render() {
let month = new Date().getMonth();
let year = new Date().getFullYear() - 1;
month = month == 0 ? 12 : month;
let data1 = this.props.programDashboard.filter((data) => data.year == year);
return (
// <div className="container">
<div className="col-md-12 img4">
<div className="row">
{/*<div className="col-md-3">
<h1> Dashboard</h1>
</div>*/}
<div className="col-md-8 form-group">
<label> </label>
<form>
<div className="form-group radio-name radio-style">
<label><input type="radio" name="optradio" value="1" onChange={this.selected} defaultChecked /> Last Month</label>
<label> <input type="radio" name="optradio" value="3" onChange={this.selected} /> Last 3 Months </label>
<label> <input type="radio" name="optradio" value="6" onChange={this.selected} /> Last 6 Months </label>
<label><input type="radio" name="optradio" value="9" onChange={this.selected} /> Last 9 Months </label>
<label> <input type="radio" name="optradio" value="12" onChange={this.selected} /> Last 12 Months </label>
</div>
</form>
</div>
<div className="col-md-1"></div>
</div>
<br />
<div className="row">
<ProgramCard data={data1} value={this.state.value} onSelected={this.selected} month={month} />
</div >
<div className="row">
<ProgramGraph programData={data1} value={this.state.value} month={month} />
</div><br />
<div className="row radio-name">
<h6>* Datas are shown in average</h6>
</div>
<div className="row">
<ProgramTable programData={this.props.programDashboard} />
</div><br /><br />
</div>
// </div>
)
}
}
const mapStateToProps = (state) => {
return {
programDashboard: state.programDashboard,
dashBoard: state.dashboard
}
}
export default connect(mapStateToProps)(ProgramDashboardRender);
|
/**
* Created with JetBrains PhpStorm.
* User: a.savchenko
* Date: 28.10.13
* Time: 9:45
* To change this template use File | Settings | File Templates.
*/
define(['templates', 'backbone', 'stage'], function (templates, Backbone, LiveAPI) {
var EventView = Backbone.View.extend({
className: 'event-wrapper', //THE DIV ELEMENT WITH PROVIDED CLASS
initialize: function () {
/*SUBSCRIBING TO DIFFERENT EVENTS TO PROVIDE CORRECT VIEW FOR USER*/
this.model.bind('change', this.render, this);
this.model.bind('add:to', this.render, this);
this.model.bind('remove:from', this.remove, this);
},
render: function () { //RENDER MODEL VIEW
this.$el.attr('starttime', this.model.get('event').start_time); //ADD STARTTIME ATTRIBUTE FOR SORTING
this.$el.html(this.template(this.model.attributes)); //SET TEMPLATE TO CONTAINER DIV
return this;
},
renderMarket: function (markets, size, useForaTemplate, euro) { //FOR MARKET RENDERING;
/*MARKETS IS ARRAY OF BETTYPE MARKETS,
* SIZE - HOW MANY ODDS CAN BE IN ONE RAW (AND I THEY ARE IN ONE MARKET),
* USEFORETEMPLATE - FLAG, WHERE TO RENDER OUTCOMES WITH VALUES,
* EURO - FLAG, THAT INDICATE WHERE TO USE UERO MARKET AND ODD TEMPLATES*/
var marketsTemplate = '',
self = this;
if (euro) {
_.each(markets, function (market) {
marketsTemplate += templates.euroMarketTemplate({market: market, self: self});
});
} else {
_.each(markets, function (market) {
marketsTemplate += templates.marketTemplate({market: market, self: self, size: size, useForaTemplate: useForaTemplate});
});
}
return marketsTemplate;
},
renderEmptyMarket: function () { //RETURN AN EMPTY MARKET (FOR VISUAL ESTETIC VIEW)
return templates.emptyMarket();
},
renderOdds: function (odds, size, useForaTemplate) { //RENDER ODD OF PROVIDED MARKET
/*ODD - ARRAY OF ONE MARKET,
* SIZE IS GIVEN BY THE RENDERmARKET METHOD,
* AND USEFORATEMPLATE TOO*/
var oddsTemplate = '',
self = this,
width = 'span' + 12/parseInt(size, 10),//SPAN12 HAS A WIDTH 100%, THIS IS FOR RESPONSIVE DESIGN
templateEngine = useForaTemplate ? templates.foraOddTemplate : templates.oddTemplate; //IF FORATEMPLATE - USER ANOTHER TEMPLATE
_.each(odds, function (odd) {
oddsTemplate += templateEngine({width: width, odd: odd, self: self});
});
return oddsTemplate;
},
renderEuroOdds: function (odds) { //THIS IS FOR RENDERING ODD WITHOUT OUTCOMES
var oddsTemplate = '',
self = this;
_.each(odds, function (odd) {
oddsTemplate += templates.euroOddTemplate({odd: odd, self: self});
});
return oddsTemplate;
},
remove: function () { //FOR REMOVING ENDED AND REMOVED EVENTS, FIRE WHEN MODEL ARE REMOVED FROM COLLECTION
this.$el.remove();
},
renderStoppedLayer: function (empty) { //THIS IS FOR BETSTATUS STOOPED AND NOT_STARTED EVENTS
if (empty) {
return '';
} else {
return templates.stoppedLayerTemplate();
}
}
});
return EventView;
});
|
const Sequelize = require("sequelize");
const { sequelize } = require("../Database/dbConfig");
const Detail = sequelize.define("Detail", {
title: {
type: Sequelize.STRING,
},
description: {
type: Sequelize.STRING,
},
});
// sequelize
// .sync({ force: true })
// .then(() => {
// console.log(`Database & tables created!`);
// })
// .catch((err) => {
// console.log(err);
// });
module.exports = {
Detail,
};
|
//https://projecteuler.net/problem=21
/*
* Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n).
* If d(a) = b and d(b) = a, where a ≠ b, then a and b are an amicable pair and each of a and b are called amicable
* numbers.
*
* For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The
* proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220.
*
* Evaluate the sum of all the amicable numbers under 10000.
*/
var nElements = 10000;
var amicableNumbers = {};
function sumOfProperDivisors (n) {
var result = 0;
for(var j = 1; j < n; j++) {
if(n % j === 0) {
result += j;
}
}
return result;
}
function isAmicablePair (n) {
var sumOne, sumTwo;
sumOne = sumOfProperDivisors(n);
if(sumOne !== n) {
sumTwo = sumOfProperDivisors(sumOne);
if(sumTwo === n) {
amicableNumbers[n] = n;
amicableNumbers[sumOne] = sumOne;
}
}
}
for(var i = 1; i < nElements; i++) {
isAmicablePair(i);
}
var sum = 0;
Object.keys(amicableNumbers).forEach(function(key) {
sum += +key;
});
console.log(sum);
|
import { createApp } from 'vue'
import App from './App.vue'
import routes from './shared/router/main.router';
import { createRouter, createWebHistory} from 'vue-router';
const router = createRouter({
history: createWebHistory(),
routes
});
const app = createApp(App);
app.use(router);
app.mount('#app');
|
import * as axios from 'axios';
const URL = 'api/todos'
const getTodos = async function() {
try {
const response = await axios.get(URL);
return response.data;
} catch (error) {
console.error(error);
throw new Error(error);
}
};
const addTodo = async function(todoName) {
try {
const response = await axios.post(URL, { name: todoName });
return response.data;
} catch (error) {
console.error(error);
throw new Error(error);
}
}
const removeTodo = async function(todoId) {
try {
const response = await axios.delete(`${URL}/${ todoId ? todoId : '0' }`);
return response.data;
} catch (error) {
console.error(error);
throw new Error(error);
}
}
const updateTodo = async function(todoId, key, value) {
try {
const response = await axios.put(URL, { id: todoId, key: key, value: value });
return response.data;
} catch (error) {
console.error(error);
throw new Error(error);
}
}
export const todosService = {
getTodos,
addTodo,
removeTodo,
updateTodo
};
|
/*
* LOOPS:
*
* 0. Loops perform or utter an action repeatedly.
*
* 1. They're important so we can perform an action a specific number of times.
*
* 2. There are three main kinds of loops:
* - While loops
* - For loops
* - For in loops
*
* 3. For and while loops all have startng an stopping conditions.
*
* 4. Starting conditions tell your code when to start executing.
*
* 5. Stopping conditions tell your code when to stop.
*
* 6. Make sure to properly set your stopping condition or your code may never stop running!
*/
//WHILE LOOPS
//Loops through a block of code as long as a specified condition is true.
var whileLoop = 1; // This is the starting condition.
while (whileLoop < 10) // This is the stopping condition. The loop will run until this isn't true.
{ // The iterator must be located here in order to prevent an infinite loop.
console.log(whileLoop++);
}// prints numbers 1 - 9 on separate lines
//FOR LOOPS
// Similar to while loops, but the starting condition can be in the same scope.
for (var i = 0; i < 5; i++)
//this is your initialized variable, with stopping condition and increment
{console.log("yo!")} // this is the code you want to run
//prints "yo!" five times on separate lines
//FOR IN LOOPS
// Loops through the properties of an object.
var me = {"firstName": "Nico", "lastName": "Paulino"};
for (var key in me) // This assigns a variable, usually named key.
// Then you put "in (object)".
//This is saying, for every key that is in this object, do this:
{console.log(me[key])} //This prints every value that is in the object.
// prints => "Nico" "Paulino"
// To loop through the keys of an object, you can ue the Object.keys method.
var keys = Object.keys(me); //Put the object name in the parentheses.
console.log(keys); // prints => ['firstName', 'lastName'];
//LOOPING OVER AN ARRAY
/* To loop through a string, you can use a for loop.
* - set your starting condition to the first index you want to loop through.
* - set your stopping condition to the last index you want to loop through.
* - Either increment or decrement.
*/
var myStringArray = ["Hello","World", "This", "Is", "My", "String"];
for (var i = 0; i < myStringArray.length; i++) {
console.log(myStringArray[i]) } //prints ever index of the string on a separate line
/* To loop backwards over an array is very similar, you must:
* - set your starting condition to yourArrayHere.length -1
* - set stopping condition to i >= 0
* - set incrementer to i--
*/
for (var i = myStringArray.length - 1; i >= 0; i--) {
console.log(myStringArray[i]);
} // prints every index on the string backwards on separate lines
|
// create a calculator function that accepts 3 arguements 2 numbers and 1 operator
// ex. calculator ( 2, *, 2) >> this should return 4
// hints-- you will need to use conditionals ;-)
function calculator(num1, operator, num2)
{
if (operator === "+" ) {
return num1 + num2;
} else if (operator === "-" ){
return num1 - num2;
} else if ( operator === "*" ){
return num1 * num2 ;
} else {
return "nope";
}
}
var calcAnswer = calculator(22, "*", 22)
console.log(calcAnswer);
|
import React, { Component} from 'react';
import API from '../../services/api';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faEdit, faTrash, faEye } from '@fortawesome/free-solid-svg-icons';
import { Link } from "react-router-dom";
export default class Main extends Component {
state = {
produtos: [],
}
componentDidMount() {
this.loadProdutos();
}
loadProdutos = async () => {
const response = await API.get('produto/listar');
this.setState({ produtos: response.data })
};
deletaProduto = async (id) => {
const response = await API.delete(`produto/deletar/${id}`);
this.setState({ produtos: response.data })
};
render() {
const { produtos } = this.state;
return(
<div className="container posts-page">
<br />
<div className="row">
<div className="col-md-12 img-posts">
<h1>Nexti</h1>
<p>Quantidade de produtos: {produtos.length}</p>
</div>
</div>
<br />
<div className="row">
<div className="col-md-12">
<Link to={`/produto/incluir`} className="btn btn-outline-primary btn-xs"><FontAwesomeIcon icon={faEdit} /> Incluir</Link>
</div>
</div>
<br />
<div className="row">
<div className="col-md-12 img-posts">
<table className="table">
<thead className="thead-dark">
<tr>
<th scope="col">ID</th>
<th scope="col">Nome</th>
<th scope="col">PREÇO</th>
<th scope="col">SKU</th>
<th scope="col">DESCRIÇÃO</th>
<th scope="col">QUANTIDADE</th>
<th scope="col">AÇÕES</th>
</tr>
</thead>
<tbody>
{produtos.map(produto => (
<tr key={produto.id}>
<th scope="row">{produto.id}</th>
<td>{produto.nome}</td>
<td>{produto.preco}</td>
<td>{produto.sku}</td>
<td>{produto.descricao}</td>
<td>{produto.quantidade}</td>
<td>
<Link to={`/produto/detalhes/${produto.id}`} className="btn btn-outline-success btn-sm"><FontAwesomeIcon icon={faEye} /></Link>
<Link to={`/produto/editar/${produto.id}`} className="btn btn-outline-primary btn-sm"><FontAwesomeIcon icon={faEdit} /></Link>
<button type="button" className="btn btn-outline-danger btn-sm" onClick={(e) => this.deletaCliente(produto.id)}><FontAwesomeIcon icon={faTrash} /></button>
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
</div>
);
}
}
|
import {request, request1} from "./request"
export function getCategoryGoods(page) {
return request({
url: "/home/data",
params: {
type: 'pop',
page,
}
})
}
export function getCategoryMeishi(page) {
return request1({
url: "/category/meishi/"+page,
})
}
|
import React, { Component } from 'react';
import Style from './index.module.less';
import Avatar from '@components/avatar';
import { Button } from 'antd';
class AttentionList extends Component {
render() {
const { followList} = this.props;
let avatarStyle = {
'width': '44px',
'height': '44px',
};
return (
<div className={`${Style['attention-list']}`}>
<div className={Style['title']}>推荐</div>
<ul className={Style['list']}>
{
followList.length === 0 ?
<li>天啊噜,目前居然没有可关注的人,快来成为第一个发帖人吧</li>
:
followList.map((item, index) => {
return (
<li key={index}>
<Avatar userInfo={item} avatarStyle={avatarStyle} />
{
item.hasFollow
? <Button onClick={() => { this.props.setFollowStatus(index, false) }}>已关注</Button>
: <Button type="primary" onClick={() => {this.props.setFollowStatus(index, true)}}>关注</Button>
}
</li>
)
})
}
</ul>
</div>
);
}
}
export default AttentionList;
|
var friends = require("../data/friends");
module.exports = function (app) {
// Get
app.get("/api/friends", function (req, res) {
res.json(friends);
});
//Post
app.post("/api/friends", function (req, res) {
var newFriend = req.body;
var lowest = 999;
var match;
friends.push(req.body);
console.log(newFriend);
for (var i = 0; i < friends.length-1; i++) {
var checkDiff = 0;
// Check score differences
for (var j = 0; j < friends[i].scores.length; j++) {
if(parseInt(newFriend.scores[j])!=parseInt(friends[i].scores[j])){
checkDiff++;
}
}
console.log("Difference: " + checkDiff+ " for "+friends[i].name)
// If difference is lower than lowest, store it
if(checkDiff < lowest){
lowest=checkDiff;
match = i;
}
}
res.json(friends[match]);
});
}
|
function abortInstaller()
{
installer.setDefaultPageVisible(QInstaller.Introduction, false);
installer.setDefaultPageVisible(QInstaller.TargetDirectory, false);
installer.setDefaultPageVisible(QInstaller.ComponentSelection, false);
installer.setDefaultPageVisible(QInstaller.ReadyForInstallation, false);
installer.setDefaultPageVisible(QInstaller.StartMenuSelection, false);
installer.setDefaultPageVisible(QInstaller.PerformInstallation, false);
installer.setDefaultPageVisible(QInstaller.LicenseCheck, false);
var abortText = "<font color='red' size=3>" + qsTr("Installation failed:") + "</font>";
var error_list = installer.value("component_errors").split(";;;");
abortText += "<ul>";
// ignore the first empty one
for (var i = 0; i < error_list.length; ++i) {
if (error_list[i] !== "") {
log(error_list[i]);
abortText += "<li>" + error_list[i] + "</li>"
}
}
abortText += "</ul>";
installer.setValue("FinishedText", abortText);
}
function log() {
var msg = ["QTCI: "].concat([].slice.call(arguments));
console.log(msg.join(" "));
}
function printObject(object) {
var lines = [];
for (var i in object) {
lines.push([i, object[i]].join(" "));
}
log(lines.join(","));
}
var status = {
widget: null,
finishedPageVisible: false,
installationFinished: false
}
function tryFinish() {
if (status.finishedPageVisible && status.installationFinished) {
if (status.widget.LaunchQtCreatorCheckBoxForm) {
// Disable this checkbox for minimal platform
status.widget.LaunchQtCreatorCheckBoxForm.launchQtCreatorCheckBox.setChecked(false);
}
if (status.widget.RunItCheckBox) {
// LaunchQtCreatorCheckBoxForm may not work for newer versions.
status.widget.RunItCheckBox.setChecked(false);
}
log("Press Finish Button");
gui.clickButton(buttons.FinishButton);
}
}
function Controller() {
installer.installationFinished.connect(function() {
status.installationFinished = true;
gui.clickButton(buttons.NextButton);
tryFinish();
});
installer.setMessageBoxAutomaticAnswer("OverwriteTargetDirectory", QMessageBox.Yes);
installer.setMessageBoxAutomaticAnswer("installationErrorWithRetry", QMessageBox.Ignore);
installer.setMessageBoxAutomaticAnswer("XcodeError", QMessageBox.Ok);
// Allow to cancel installation for arguments --list-packages
installer.setMessageBoxAutomaticAnswer("cancelInstallation", QMessageBox.Yes);
}
Controller.prototype.WelcomePageCallback = function() {
log("Welcome Page");
gui.clickButton(buttons.NextButton);
var widget = gui.currentPageWidget();
/*
Online installer 3.0.6
- It must disconnect the completeChanged callback after used, otherwise it will click the 'next' button on another pages
*/
var callback = function() {
gui.clickButton(buttons.NextButton);
widget.completeChanged.disconnect(callback);
}
widget.completeChanged.connect(callback);
}
Controller.prototype.CredentialsPageCallback = function() {
var login = installer.environmentVariable("QT_CI_LOGIN");
var password = installer.environmentVariable("QT_CI_PASSWORD");
if (login === "" || password === "") {
gui.clickButton(buttons.CommitButton);
}
var widget = gui.currentPageWidget();
widget.loginWidget.EmailLineEdit.setText(login);
widget.loginWidget.PasswordLineEdit.setText(password);
gui.clickButton(buttons.CommitButton);
}
Controller.prototype.ComponentSelectionPageCallback = function() {
log("ComponentSelectionPageCallback");
function list_packages() {
var components = installer.components();
log("Available components: " + components.length);
var packages = ["Packages: "];
for (var i = 0 ; i < components.length ;i++) {
packages.push(components[i].name);
}
log(packages.join(" "));
}
if (installer.environmentVariable("LIST_PACKAGES") !== "") {
list_packages();
gui.clickButton(buttons.CancelButton);
return;
}
log("Select components");
function trim(str) {
return str.replace(/^ +/,"").replace(/ *$/,"");
}
var widget = gui.currentPageWidget();
var packages = trim(installer.environmentVariable("PACKAGES")).split(",");
if (packages.length > 0 && packages[0] !== "") {
widget.deselectAll();
var components = installer.components();
var allfound = true;
for (var i in packages) {
var pkg = trim(packages[i]);
var found = false;
for (var j in components) {
if (components[j].name === pkg) {
found = true;
break;
}
}
if (!found) {
allfound = false;
log("ERROR: Package " + pkg + " not found.");
} else {
log("Select " + pkg);
widget.selectComponent(pkg);
}
}
if (!allfound) {
list_packages();
// TODO: figure out how to set non-zero exit status.
gui.clickButton(buttons.CancelButton);
return;
}
} else {
widget.selectAll();
log("Use all component list");
}
gui.clickButton(buttons.NextButton);
}
Controller.prototype.IntroductionPageCallback = function() {
log("Introduction Page");
log("Retrieving meta information from remote repository");
/*
Online installer 3.0.6
- Don't click buttons.NextButton directly. It will skip the componenet selection.
*/
if (installer.isOfflineOnly()) {
gui.clickButton(buttons.NextButton);
}
}
Controller.prototype.TargetDirectoryPageCallback = function() {
var OUTPUT = installer.environmentVariable("INSTALLDIR");
log("Set target installation page: " + OUTPUT);
var widget = gui.currentPageWidget();
if (widget != null) {
widget.TargetDirectoryLineEdit.setText(OUTPUT);
}
gui.clickButton(buttons.NextButton);
}
Controller.prototype.LicenseAgreementPageCallback = function() {
log("Accept license agreement");
var widget = gui.currentPageWidget();
if (widget != null) {
widget.AcceptLicenseRadioButton.setChecked(true);
}
gui.clickButton(buttons.NextButton);
}
Controller.prototype.ReadyForInstallationPageCallback = function() {
log("Ready to install");
// Bug? If commit button pressed too quickly finished callback might not show the checkbox to disable running qt creator
// Behaviour started around 5.10. You don't actually have to press this button at all with those versions, even though gui.isButtonEnabled() returns true.
gui.clickButton(buttons.CommitButton, 200);
}
Controller.prototype.PerformInstallationPageCallback = function() {
log("PerformInstallationPageCallback");
gui.clickButton(buttons.CommitButton);
}
Controller.prototype.FinishedPageCallback = function() {
log("FinishedPageCallback");
var widget = gui.currentPageWidget();
// Bug? Qt 5.9.5 and Qt 5.9.6 installer show finished page before the installation completed
// Don't press "finishButton" immediately
status.finishedPageVisible = true;
status.widget = widget;
tryFinish();
}
|
require("../common/vendor.js"), (global.webpackJsonp = global.webpackJsonp || []).push([ [ "pages/personal_package/material/house_purchase" ], {
"146d": function(e, n, a) {
a.d(n, "b", function() {
return t;
}), a.d(n, "c", function() {
return o;
}), a.d(n, "a", function() {});
var t = function() {
var e = this;
e.$createElement;
e._self._c;
}, o = [];
},
"18aa": function(e, n, a) {
var t = a("7be4");
a.n(t).a;
},
"7be4": function(e, n, a) {},
aea6: function(e, n, a) {
a.r(n);
var t = a("146d"), o = a("fbd5");
for (var r in o) [ "default" ].indexOf(r) < 0 && function(e) {
a.d(n, e, function() {
return o[e];
});
}(r);
a("18aa");
var u = a("f0c5"), c = Object(u.a)(o.default, t.b, t.c, !1, null, "1e28c790", null, !1, t.a, void 0);
n.default = c.exports;
},
d92e: function(e, n, a) {
(function(e) {
function n(e) {
return e && e.__esModule ? e : {
default: e
};
}
a("6cdc"), n(a("66fd")), e(n(a("aea6")).default);
}).call(this, a("543d").createPage);
},
fbd5: function(e, n, a) {
a.r(n);
var t = a("ffa9"), o = a.n(t);
for (var r in t) [ "default" ].indexOf(r) < 0 && function(e) {
a.d(n, e, function() {
return t[e];
});
}(r);
n.default = o.a;
},
ffa9: function(e, n, a) {
Object.defineProperty(n, "__esModule", {
value: !0
}), n.default = void 0;
var t = {
components: {
TopRightShare: function() {
a.e("components/views/top_right_share").then(function() {
return resolve(a("73b4"));
}.bind(null, a)).catch(a.oe);
}
},
onShareAppMessage: function() {
var e = {
title: "杭州购房全流程,摇号买房注意事项都在这里啦~",
path: "/pages/personal_package/material/house_purchase"
};
return this.getShareInfo(e);
}
};
n.default = t;
}
}, [ [ "d92e", "common/runtime", "common/vendor" ] ] ]);
|
/**
* Given a string, determine if it is a palindrome,
* considering only alphanumeric characters and ignoring cases.
Note: For the purpose of this problem, we define empty string as valid palindrome.
Example 1:
Input: "A man, a plan, a canal: Panama"
Output: true
Example 2:
Input: "race a car"
Output: false
Constraints:
s consists only of printable ASCII characters.
*/
const validPalindrome = (s) => {
const modified = s.toLowerCase().replace(/[^a-z0-9]/g, "");
if(modified.length < 1) return true;
let left = 0;
let right = modified.length - 1;
while(left < right){
if(modified[left] !== modified[right]){
return false;
} else {
left++;
right--;
}
}
return true;
}
console.log(validPalindrome("A man, a plan, a canal: Panama"));
|
import React from 'react'
import { Grid } from '@material-ui/core'
import { useHistory } from "react-router-dom";
import SingleProduct from './SingleProduct';
export default function CatalogPRoduct({products, checkedProducts, checkboxChanged, setActiveProduct, setIsOpen}) {
const history = useHistory();
const openModal = (item) => {
setActiveProduct(item);
setIsOpen(true);
history.push(`/catalog/details/${item.id}`)
};
return (
<Grid container justify="space-between">
{products.map((item) => (
<SingleProduct
key={item.id}
image={item.imageUrl}
title={item.title}
id={item.id}
price={item.price}
description={item.description}
checkboxChanged={checkboxChanged}
checkedProducts={checkedProducts}
openModal={openModal}
item={item}
/>
))}
</Grid>
)
}
|
import React, { Component, PropTypes } from 'react'
import Day from './day'
import Chart from './chart'
import { connect } from 'react-redux'
import * as actions from '../actions'
import Moment from 'moment'
class Card extends Component {
static PropTypes = {
data: PropTypes.array
}
constructor (props) {
super(props)
this.state = {
clouds: '',
temp: '',
precipitation: '',
humidity: '',
wind: '',
date: '',
icon: '',
runOnce: false,
days: ''
}
this.setSelected = this.setSelected.bind(this)
}
componentDidUpdate () {
if (!this.state.runOnce) {
let currentDay = Object.keys(this.props.data)[0]
let currentDayArr = this.props.data[currentDay]
this.setSelected(currentDayArr) // pre-select the first 3-hr
this.setState({runOnce: true})
}
}
setSelected (obj) {
this.setState({
clouds: obj[0].weather[0].description,
temp: Math.floor(obj[0].main.temp),
precipitation: obj[0].rain ? obj[0].rain[Object.keys(obj[0].rain)[0]] : 0,
humidity: obj[0].main.humidity,
wind: Math.ceil(obj[0].wind.speed),
date: Moment(obj[0].dt_txt).format('ddd, MMMM Do YYYY'),
icon: `http://openweathermap.org/img/w/${obj[0].weather[0].icon}.png`,
days: obj
})
}
render () {
if (!this.state.days) {
return <div>
Select city above...
</div>
}
let days
days = this.state.days.map((day, key) => {
let _time = day.dt_txt.split(' ')[1]
_time = _time.split(':')[0]
if (_time > 12) {
_time -= 12
_time = _time + ' PM'
}else if (_time == '00') {
_time = 12 + ' AM'
}
else if (_time == '12') {
_time = 12 + ' PM'
}else {
_time = _time.replace(0, '')
_time = _time + ' AM'
}
return (
<div className='col-md-3 deck' key={key}>
<small><strong>{_time}</strong></small>
<br />
<small className='clouds text-primary'>{day.weather[0].description}</small>
<div>
<img src={`http://openweathermap.org/img/w/${day.weather[0].icon}.png`} />
<small className='temp_small'>{day.main.temp ? Math.floor(day.main.temp) : '--'}</small> <sup>°F</sup>
</div>
<div>
<small>Precipitation: {day.rain ? day.rain[Object.keys(day.rain)[0]] : 0} MM</small>
<br />
<small>Humidity: {day.main.humidity ? day.main.humidity + '%' : '--'}</small>
<br />
<small>Wind: {day.wind ? Math.ceil(day.wind.speed) + ' mph' : '--'}</small>
</div>
</div>
)
})
return (
<div className='card'>
<div className='card-block'>
<h4 className='card-title'>{this.props.city}</h4>
<span>{this.state.date}</span>
<br />
<span className='clouds text-primary'>{this.state.clouds}</span>
<div className='card-text'>
<span><img src={this.state.icon} /> <span className='temp'>{this.state.temp ? this.state.temp : '--'}</span> <sup>°F</sup></span>
<div className='pull-sm-right'>
<span>Precipitation: {this.state.precipitation ? this.state.precipitation : 0} MM</span>
<br />
<span>Humidity: {this.state.humidity ? this.state.humidity + '%' : '--'}</span>
<br />
<span>Wind: {this.state.wind ? this.state.wind + ' mph' : '--'}</span>
</div>
</div>
<div className='row'>
<Day data={Object.keys(this.props.data)} onSelectWeather={this.setSelected} />
</div>
<div className='row'>
<Chart data={this.state.days} />
</div>
<div className='row'>
{days}
</div>
</div>
</div>
)
}
}
function mapStateToProps (state) {
return {}
}
export default connect(mapStateToProps, actions)(Card)
|
import React from 'react'
import POSItemsView from './posItemsView'
const mainView = () => {
return (
<div className='wrapper'>
<POSItemsView />
</div>
)
}
export default mainView
|
import React from 'react';
import "../../../Assets/CSS/ws_test_configuration.css";
import { Card, Col, Row, Button, message, Icon, Input, DatePicker } from "antd";
import moment from 'moment';
import { Link } from 'react-router-dom'
import CreditCardInput from 'react-credit-card-input';
const dateFormat = 'YYYY/MM/DD';
class Payment extends React.Component {
constructor(props) {
super(props);
this.state = {
name: '',
cardNumber: '',
expiry: '',
cvc: ''
};
}
handleCardNumberChange = (event) => {
this.setState({
cardNumber: event.target.value
}, () => {
console.log(this.state.cardNumber)
})
}
handleCardExpiryChange = (event) => {
this.setState({
expiry: event.target.value
}, () => {
console.log(this.state.expiry)
})
}
handleCardCVCChange = (event) => {
this.setState({
cvc: event.target.value
}, () => {
console.log(this.state.cvc)
})
}
handleNameChange = (event) => {
this.setState({
name: event.target.value
}, () => {
console.log(this.state.name)
})
}
handleNumberChange = (event) => {
this.setState({
number: event.target.value
}, () => {
console.log(this.state.number)
})
}
handleCsvChange = (event) => {
this.setState({
csv: event.target.value
}, () => {
console.log(this.state.csv)
})
}
render() {
return <React.Fragment >
<div>
<Row>
<Col span={24}>
<div style={{ background: '#ECECEC', padding: '30px' }}>
<Card title="Payment Details" bordered={false} className="ws_top_row" >
<h2><b>Insert User Details</b></h2>
<Row>
<Col span={12}><p>Input your name :</p></Col>
<Col span={12}> <Input value={this.state.name} onChange={this.handleNameChange} ></Input></Col>
</Row>
<br />
{/* <Row>
<Col span={12}>Card number :</Col>
<Col span={12}><Input placeholder="xxxx-xxxx-xxxx-xxxx" value={this.state.number} onChange={this.handleNumberChange} /> </Col>
</Row>
<br />
<Row>
<Col span={12}>Expiary date :</Col>
<Col span={12}> <DatePicker defaultValue={moment('2015/01/01', dateFormat)} format={dateFormat} /> </Col>
</Row>
<br />
<Row>
<Col span={12}>Csv :</Col>
<Col span={12}> <Input placeholder="xxx" value={this.state.csv} onChange={this.handleCsvChange} /> </Col>
</Row>
<br /><br /><br /> */}
<Card title="Credit Card Details" bordered={false} className="ws_mini" >
<Row>
<Col span={12}><p>Enter your card details :</p></Col>
<Col span={12}><CreditCardInput
cardNumberInputProps={{ value: this.state.cardNumber, onChange: this.handleCardNumberChange }}
cardExpiryInputProps={{ value: this.state.expiry, onChange: this.handleCardExpiryChange }}
cardCVCInputProps={{ value: this.state.cvc, onChange: this.handleCardCVCChange }}
fieldClassName="input"
/></Col>
</Row>
<br /><br /><br />
</Card>
<Row>
<Col span={4}></Col>
<Col span={4}></Col>
<Col span={4}></Col>
<Col span={4}></Col>
<Col span={4}></Col>
<Col span={4}><Link to="/payment"><Button type="primary" block>Proceed payment</Button></Link></Col>
</Row>
</Card>
</div>
</Col>
</Row>
</div>
</React.Fragment>;
}
}
export default Payment;
|
import React, {Component} from 'react';
import {Card } from 'reactstrap';
import {connect} from 'react-redux';
import {withRouter , Link} from 'react-router-dom';
const mapStateToProps = state => {
return{
products: state.products
}
}
const RenderSupplements = ({ product }) => {
const supplements = product.map(supplement => {
return (
<div className='m-3'>
<Link to={`/supplements/${supplement.productId}`}>
<Card className='productCard'>
<img src={supplement.src} alt={supplement.brandName} width='300' height='300' />
</Card>
</Link>
<div className='d-flex justify-content-center text-center'>
<h4>{supplement.brandName} <br /> ₦{supplement.price}</h4>
</div>
</div >
)
})
return (
supplements
)
}
class Supplements extends Component {
render() {
console.log(this.props.products);
return (
<div className='container'>
<div className='row offset-2 mt-3'>
<h2>Supplements</h2>
</div>
<hr className='offset-1'></hr>
<div className='row offset-1'>
<RenderSupplements product={this.props.products.supplements} />
</div>
</div>
)
}
}
export default withRouter(connect(mapStateToProps)(Supplements));
|
/**
* Fake background script messaging.
* This script is prepended to background script(if exist).
* Only other pages should receive messages sent from background script
*/
// shadow the global
let browser = (function () {
const runtimeOnMessage = {
addListener (listener) {
if (typeof listener !== 'function') {
throw new TypeError('Wrong argument type')
}
if (!window.msgBackgroundListeners.some(x => x === listener)) {
window.msgBackgroundListeners.push(listener)
}
},
removeListener (listener) {
if (typeof listener !== 'function') {
throw new TypeError('Wrong argument type')
}
window.msgBackgroundListeners = window.msgBackgroundListeners.filter(
x => x !== listener
)
},
hasListener (listener) {
if (typeof listener !== 'function') {
throw new TypeError('Wrong argument type')
}
return window.msgBackgroundListeners.some(x => x === listener)
}
}
function runtimeSendMessage (extensionId, message) {
return new Promise((resolve, reject) => {
if (typeof extensionId !== 'string') {
message = extensionId
}
try {
message = JSON.parse(JSON.stringify(message))
} catch (err) {
return reject(new TypeError('Wrong argument type'))
}
let isClosed = false
let isAsync = false
function sendResponse (response) {
if (isClosed) {
return reject(new Error('Attempt to response a closed channel'))
}
try {
// deep clone & check data
response = JSON.parse(JSON.stringify(response))
} catch (err) {
return reject(new TypeError('Response data not serializable'))
}
resolve(response)
}
window.msgPageListeners.forEach(listener => {
const hint = listener(message, {}, sendResponse)
// return true or Promise to send a response asynchronously
if (hint === true) {
isAsync = true
} else if (hint && typeof hint.then === 'function') {
isAsync = true
hint.then(sendResponse)
}
})
// close synchronous response
setTimeout(() => {
if (!isAsync) {
isClosed = true
}
}, 0)
})
}
// FRAGILE: Assuming all tab messages are sent to the tab that is under development
// Filter out messages here if you need to narrow down
function tabsSendMessage (tabId, message) {
if (typeof tabId !== 'string') {
return Promise.reject(new TypeError('Wrong argument type'))
}
return browser.runtime.sendMessage(tabId, message)
}
let runtime = Object.assign({}, window.browser.runtime, {
sendMessage: runtimeSendMessage,
onMessage: runtimeOnMessage
})
let tabs = Object.assign({}, window.browser.tabs, {
sendMessage: tabsSendMessage
})
return Object.assign({}, window.browser, { runtime, tabs, _identity: 'cool' })
})() // eslint-disable-line
|
"Use strict"
const services = [
{
icon: 'facebook',
title: 'interFace Design',
description: 'Continually scale resource-leveling vectors without best-of-breed schemas. Assertively initiate backward-compatible'
},
{
icon: 'twitter',
title: 'Experience Design',
description: 'Continually scale resource-leveling vectors without best-of-breed schemas. Assertively initiate backward-compatible'
},
{
icon: 'instagram',
title: 'Web Development',
description: 'Continually scale resource-leveling vectors without best-of-breed schemas. Assertively initiate backward-compatible'
},
{
icon: 'linkedin',
title: 'Mobile app',
description: 'Continually scale resource-leveling vectors without best-of-breed schemas. Assertively initiate backward-compatible'
},
{
icon: 'facebook',
title: 'Digital marketing',
description: 'Continually scale resource-leveling vectors without best-of-breed schemas. Assertively initiate backward-compatible'
},
{
icon: 'facebook',
title: 'Woocommerce',
description: 'Continually scale resource-leveling vectors without best-of-breed schemas. Assertively initiate backward-compatible'
}
];
|
'use strict'
const setLocation = (location, extra = {}) => state => [{
...state,
...extra,
location,
}, []]
const zip = (a, b) => {
const result = []
const len = Math.max(a.length, b.length)
for (let i = 0; i < len; i++) {
result.push([ a[i], b[i] ])
}
return result
}
const isParam = path => path.startsWith(':')
const trimPath = path => path.endsWith('/') && path.length > 1
? path.substring(0, path.length - 1)
: path
const canHandle = ({ location }) => ({ path }) => {
const loc_parts = trimPath(location).split('/')
const path_parts = path.split('/')
return loc_parts.length === path_parts.length && canHandlePath(loc_parts, path_parts)
}
const canHandlePath = (location, path) => {
const parts = zip(location, path)
return parts.every(([location, path]) => isParam(path) || location === path)
}
const getParams = ({ location }, { path }) => {
const parts = zip(
trimPath(location).split('/'),
path.split('/')
)
return parts.reduce(
(prev, [location, path]) =>
prev === false
? prev
: isParam(path)
? Object.assign(prev, { [path.substring(1)]: location })
: location === path
? prev
: false,
{}
)
}
export default routes => {
const initRoute = location => {
const route = routes.find(canHandle({ location }))
const params = getParams({ location }, route)
return typeof route.init === 'function'
? route.init(params)
: [{}, []]
}
const triggerLocation = location => state => [ state, [
[ fx.goTo, location ],
]]
const init = () => {
const location = window.location.pathname
const [ state, effects ] = initRoute(location)
return [{
...state,
location,
}, [
[ setupListener ],
...effects
]]
}
const setupListener = (_, dispatch) => {
window.addEventListener('popstate', ev => {
dispatch([ triggerLocation(ev.state.location) ])
})
}
const fx = {
goTo: ([ path ], dispatch) => {
window.history.pushState({ location: path }, '', path)
const [ state, effects ] = initRoute(path)
effects.forEach(([ e, ...params ]) => e(params, dispatch))
return dispatch([ setLocation(path, state) ])
},
back: (_, dispatch) => {
window.history.back()
},
}
const render = (state, dispatch) => {
const route = routes.find(canHandle(state))
const params = getParams(state, route)
return route.view(state, dispatch, params)
}
return {
init,
fx,
render,
}
}
|
var mongoose = require('mongoose');
mongoose.connect('mongodb://' + process.env.IP + '/movies_app')
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
var movieSchema = mongoose.Schema({
title: String,
year: Number,
director: [String],
actors: [String],
plot: String
});
var Movie = mongoose.model('Movie', movieSchema);
// Movie.create([{
// title: "John Wick",
// year: 2014,
// director: [
// "Chad Stahelski",
// "David Leitch"
// ],
// actors: [
// "Keanu Reeves",
// "Michael Nyqvist",
// "Alfie Allen",
// "Willem Dafoe"
// ]
// }, {
// title: "The Hobbit: An Unexpected Journey",
// year: 2012,
// director: "Peter Jackson",
// actors: [
// "Ian McKellen",
// "Martin Freeman",
// "Richard Armitage",
// "Ken Stott"
// ]
// }, {
// title: "Independence Day",
// year: 1996,
// director: "Roland Emmerich",
// actors: [
// "Will Smith",
// "Bill Pullman",
// "Jeff Goldblum",
// "Mary McDonnell"
// ]
// }, {
// title: "Home Alone",
// year: 1990,
// director: "Chris Columbus",
// actors: [
// "Macaulay Culkin",
// "Daniel Stern",
// "John Heard"
// ]
// }, {
// title: "Men in Black",
// year: 1997,
// director: "Barry Sonnenfeld:",
// actors: [
// "Will Smith",
// "Tommy Lee Jones",
// "Linda Fiorentino",
// "Vincent D'Onofrio"
// ]
// }, {
// title: "Inception",
// year: 2010,
// director: "Christopher Nolan",
// actors: [
// "Leonardo DiCaprio",
// "Joseph Gordon-Levitt",
// "Ellen Page",
// "Tom Hardy"
// ]
// }, function(err, contacts) {
// if (err) {
// return console.error(err);
// }
// console.log(contacts);
// }]);
// Movie.find({}, function(err, contacts) {
// if (err) {
// return console.error(err);
// }
// console.log(contacts);
// });
// Movie.find({"director": "Christopher Nolan"}, function(err, contacts) {
// if (err) {
// return console.error(err);
// }
// console.log(contacts);
// });
// Movie.find({
// "actors": "Will Smith"
// }, function(err, contacts) {
// if (err) {
// return console.error(err);
// }
// console.log(contacts);
// });
// Movie.find({
// $and: [{
// "year": {
// $gte: 1990
// }
// }, {
// "year": {
// $lt: 2000
// }
// }]
// }, function(err, contacts) {
// if (err) {
// return console.error(err);
// }
// console.log(contacts);
// });
// Movie.find({
// "year": {
// $gt: 2010
// }
// }, function(err, contacts) {
// if (err) {
// return console.error(err);
// }
// console.log(contacts);
// });
// Movie.update({
// "title": "Home Alone"
// }, {
// $addToSet: {
// actors: "Joe Pesci"
// }
// }, function(err, contacts) {
// if (err) {
// return console.error(err);
// }
// console.log(contacts);
// });
// Movie.find({"title": "Home Alone"}, function(err, contacts) {
// if (err) {
// return console.log(err);
// }
// console.log(contacts);
// });
// when adding a new field to a document,
// update the schema
// Movie.update({
// "title": 'Men in Black'
// }, {
// $set: {
// "plot": "A police officer joins a secret organization that polices and monitors extraterrestrial interactions on Earth."
// }
// }, {
// new: true
// },
// function(err, movies) {
// if (err) {
// return console.error(err);
// }
// console.log(movies);
// });
// Movie.find({}, function(err, movies) {
// if (err) {
// return console.error(err);
// }
// console.log(movies);
// })
});
|
import ApiBase from './ApiBase'
import ApiConfig from './ApiConfig'
class RegisterApi extends ApiBase {
verifyInformation(state) {
if (ApiConfig.UseMocks) {
return new Promise((resolve, reject) => {
resolve({
data: {
cliente: {
estadoRegistro: 'Preregistro',
idCliente: 10
},
respuesta: {
codigo: 0,
mensaje: 'Preregistro pendiente de validación'
}
}
});
});
}
else {
return super.buildPost(
ApiConfig.RegisterVerifyInformationApiMethod,
state.data,
{
headers: {
'Content-Type': 'application/json',
Authorization: 'Bearer ' + state.appToken,
usuario: 'usuarioMonte'
}
}
);
}
}
createUser(state) {
if (ApiConfig.UseMocks) {
return new Promise((resolve, reject) => {
resolve({
data: {
cliente: {
estadoRegistro: 'pendiente',
idCliente: 10
},
respuesta: {
codigo: 0,
mensaje: 'Validacion de Medio de Contacto'
}
}
});
});
}
else {
return super.buildPost(
ApiConfig.RegisterCreateUserApiMethod,
state.data,
{
headers: {
'Content-Type': 'application/json',
Authorization: 'Bearer ' + state.appToken,
usuario: 'usuarioMonte'
}
}
);
}
}
resendActivationCode(state) {
if (ApiConfig.UseMocks) {
return new Promise((resolve, reject) => {
resolve({
data: {
cliente: {
estadoRegistro: 'validacion',
idCliente: 10
},
respuesta: {
codigo: 0,
mensaje: 'Validacion de Medio de Contacto'
}
}
});
});
}
else {
return super.buildPost(
ApiConfig.RegisterResendTokenApiMethod,
state.data,
{
headers: {
'Content-Type': 'application/json',
Authorization: 'Bearer ' + state.appToken,
usuario: 'usuarioMonte'
}
}
);
}
}
}
export default new RegisterApi();
|
angular.module("app")
.controller("mainCtrl", function($scope, adminSvc) {
adminSvc.getProducts()
.then(function(products) {
$scope.products = products;
});
});
|
const empleados = [
{
id: 1,
nombre: 'Hugo'
},
{
id: 2,
nombre: 'Faby'
},
{
id: 3,
nombre: 'Sofia'
}
];
const salarios = [
{
id: 1,
salario: 191200
},
{
id: 2,
salario: 122400
}
];
const getEmpleado = (id) => {
return new Promise((resolve, reject) => {
const empleado = empleados.find(e => e.id === id)?.nombre
empleado
? resolve(empleado)
: reject(`No existe empleado con id ${id}`)
});
}
const getSalario = (id) => {
return new Promise((resolve, reject) => {
const salario = salarios.find(s => s.id === id)?.salario
salario
? resolve(salario)
: reject(`No existe salario con id ${id}`)
});
}
id = 3;
/*
getEmpleado(id)
.then(empleado => console.log(empleado))
.catch(err => console.log(err));
getSalario(id)
.then(salario => console.log(salario))
.catch(err => console.log(err));
*/
let nombre;
getEmpleado(id)
.then(empleado => {
nombre = empleado;
return getSalario(id)
})
.then(salario => console.log(`El empleado ${nombre} tiene un salario de ${salario} `))
.catch(error => console.log(error));
|
var gulp = require('gulp');
var sass = require('gulp-sass');
var sourcemaps = require('gulp-sourcemaps');
var mmq = require('gulp-merge-media-queries');
var purge = require('gulp-css-purge');
var cssmin = require('gulp-cssmin');
var rename = require('gulp-rename');
//var sync = require('browser-sync').create();
gulp.task('default',['sass'], function () {
gulp.watch('./sass/*',['sass']);
});
gulp.task('minify',function(){
return gulp.src('./public/css/*.css')
.pipe(purge())
.pipe(cssmin())
.pipe(rename({
suffix:'-min'
}))
.pipe(gulp.dest('./public/css/'));
});
gulp.task('sass',function(){
return gulp.src('./sass/*.sass')
.pipe(sass().on('error',sass.logError))
//.pipe(sass())
.pipe(purge())
.pipe(mmq({
log:true
}))
.pipe(sourcemaps.write())
.pipe(gulp.dest('./public/css'));
});
|
var searchData=
[
['commitcontroller',['CommitController',['../class_commit_controller.html',1,'']]],
['commitmodel',['CommitModel',['../class_commit_model.html',1,'']]]
];
|
import Controller from '@ember/controller';
import move from 'ember-animated/motions/move';
import { fadeIn, fadeOut } from 'ember-animated/motions/opacity';
export default Controller.extend({
rows: [],
currentId: 1,
interval: null,
init() {
this._super(...arguments);
this.startInterval();
},
*transition({ insertedSprites, keptSprites, removedSprites }) {
yield Promise.all(removedSprites.map(sprite => fadeOut(sprite, { duration: 300 })));
yield Promise.all(keptSprites.map(sprite => move(sprite, { duration: 300 })));
yield Promise.all(insertedSprites.map(sprite => fadeIn(sprite, { duration: 300 })));
},
addRow() {
this.rows.addObject({
id: this.currentId++,
random1: (Math.random() * 100).toFixed(0),
random2: (Math.random() * 1000 + 100).toFixed(0)
});
},
startInterval() {
if (!this.interval) {
let interval = setInterval(
() => { this.addRow() },
1800
);
this.set('interval', interval);
}
},
endInterval() {
clearInterval(this.interval);
this.set('interval', null);
},
actions: {
addSingle() {
this.addRow();
},
toggleTimer() {
if (this.interval) {
this.endInterval();
} else {
this.startInterval();
}
}
}
});
|
var fs = require('fs'),
path = require('path'),
async = require('async'),
EventSocket = require('/event-socket/event-socket'),
es = new EventSocket('ws://zip-socket:8080/')
;
es.bind('open', function() {
var output = fs.createWriteStream("output.zip");
es.send("pipe", {});
es.on("stream", function(data) {
console.log("OUTPUT STREAM...", data);
if(data.chunk) {
output.write(new Buffer(data.chunk, 'base64'));
// output.write(base64.decode(data.chunk));
} else {
console.log("Output Chunk missing: ", data);
}
});
es.on("stream:end", function(data) {
console.log("OUTPUT STREAM COMPLETE!");
output.end();
});
setTimeout(function() {
// Read each file in current directory and stream it to zip socket
fs.readdir(".", function(err, files) {
var appendStream = function(file, cb) {
var readstream = fs.createReadStream(file);
es.send("append", { name: path.basename(file) });
es.pipe(readstream, {
name: path.basename(file)
});
readstream.on('end', cb);
};
async.eachSeries(files, appendStream, function(err) {
if(err) {
console.error("Error Streaming Files: ", err);
}
console.log("All file streams complete, finalizing zip...");
es.send("finalize", {});
});
});
}, 3000);
});
|
const Notifications = require('notifications');
var HelperFunctions = {};
HelperFunctions.extend = function(target, source) {
for(var n in source) {
if(!source.hasOwnProperty(n)) {
continue;
}
if(target.hasOwnProperty(n)) {
continue;
}
target[n] = source[n];
}
};
HelperFunctions.garbageCollection = function() {
var counter = 0;
for(var n in Memory.creeps) {
var c = Game.creeps[n];
if(!c) {
delete Memory.creeps[n];
//Notifications.add(`The creep ${n} died.`)
counter++;
}
}
}
module.exports = HelperFunctions;
|
const express = require("express");
const session = require("express-session");
const log4js = require("log4js");
const logger = log4js.getLogger("testApp");
const passport = require("passport");
const pug = require("pug");
const WebAppStrategy = require("./../lib/appid-sdk").WebAppStrategy;
const app = express();
// Below URLs will be used for AppID OAuth flows
const LOGIN_URL = "/ibm/bluemix/appid/login";
const CALLBACK_URL = "/ibm/bluemix/appid/callback";
const LOGOUT_URL = "/ibm/bluemix/appid/logout";
// Setup express application to use express-session middleware
// Must be configured with proper session storage for production
// environments. See https://github.com/expressjs/session for
// additional documentation
app.use(session({
secret: "123456",
resave: true,
saveUninitialized: true
}));
// Configure Pug template engine
pug.basedir = "samples";
app.set("view engine", "pug");
app.set("views", "./samples/views");
// Configure express application to use passportjs
app.use(passport.initialize());
app.use(passport.session());
// Configure passportjs to use WebAppStrategy
passport.use(new WebAppStrategy({
tenantId: "bb9b7729-3a5e-4e4b-b917-5076e848bcf2",
clientId: "a8fd7d1c-2c82-4ad0-b4f8-0ded373e69a9",
secret: "NWY3MzIzYzctMzM0Ny00MWM4LWJkYmUtY2FjNTNjYzM2MWNi",
authorizationEndpoint: "https://mobileclientaccess.stage1-dev.ng.bluemix.net/oauth/v3/bb9b7729-3a5e-4e4b-b917-5076e848bcf2/authorization",
tokenEndpoint: "https://mobileclientaccess.stage1-dev.ng.bluemix.net/oauth/v3/bb9b7729-3a5e-4e4b-b917-5076e848bcf2/token",
redirectUri: "http://localhost:1234" + CALLBACK_URL
}));
// Configure passportjs with user serialization/deserialization. This is required
// for authenticated session persistence accross HTTP requests. See passportjs docs
// for additional information http://passportjs.org/docs
passport.serializeUser(function(user, cb) {
cb(null, user);
});
passport.deserializeUser(function(obj, cb) {
cb(null, obj);
});
// Main application landing page. Not protected by WebAppStrategy
app.get("/", function(req, res, next) {
var user = req.user;
var data = {};
if (user){
data = {
isAuthenticated: true,
name: user.name,
picture: user.picture
};
}
res.render("index.pug", data);
});
// userProfile page. Will return current user information. Protected by WebAppStrategy
// In case of attempt to open this page without authenticating first will redirect to login page
// Before redirecting to the login page the WebAppStrategy.ensureAuthenticated() method will
// persist original request URL to HTTP session under WebAppStrategy.ORIGINAL_URL key.
app.get("/userProfile", WebAppStrategy.ensureAuthenticated(LOGIN_URL), function(req, res){
res.json(req.user);
});
// Login page
app.get(LOGIN_URL, passport.authenticate(WebAppStrategy.STRATEGY_NAME));
// Callback to finish authorization process. Will retrieve access and identity tokens
// from AppID service and redirect to either (in below order)
// 1. successRedirect as specified in passport.authenticate(name, {successRedirect: "...."}) invocation
// 2. the original URL of the request that triggered authentication, as persisted in HTTP session under WebAppStrategy.ORIGINAL_URL key.
// 3. application root ("/")
app.get(CALLBACK_URL, passport.authenticate(WebAppStrategy.STRATEGY_NAME));
// Clears authetnication information from session
app.get(LOGOUT_URL, function(req, res){
WebAppStrategy.logout(req);
res.redirect("/");
});
var port = process.env.PORT || 1234;
app.listen(port, function(){
logger.info("Listening on http://localhost:" + port);
});
|
var User = require('../models/User');
var Profile = require('../models/profile');
const jwt = require("jsonwebtoken");
const passport = require("passport");
require("../config/passport")(passport);
module.exports = {
login: function (req, res,next) {
const username = req.body.username;
const password = req.body.password;
const query = { username}
//Check the user exists
User.findOne(query, (err, user) => {
//Error during exuting the query
if (err) {
return res.send({
success: false,
message: 'Error, please try again'
});
}
//No User match the search condition
if (!user) {
return res.send({
success: false,
message: 'Error, Account not found'
});
}
//Check if the password is correct
user.isPasswordMatch(password, user.password, (err, isMatch) => {
//Invalid password
if (!isMatch) {
return res.send({
success: false,
message: 'Error, Invalid Password'
});
}
//User is Valid
const ONE_WEEK = 604800; //Token validtity in seconds
//Generating the token
const token = jwt.sign({ user },"abirayed", { expiresIn: ONE_WEEK });
//User Is Valid
//This object is just used to remove the password from the retuned filds
let returnUser = {
username: user.username,
id: user._id
}
//Send the response back
return res.send({
success: true,
message: 'You can login now',
user: returnUser,
token
});
});
});
},
register : function (req, res, next) {
let newUser = new User({
username: req.body.username,
password: req.body.password,
});
console.log("user mongo",newUser.username);
let newProfile = new Profile({
role: req.body.role,
age: req.body.age,
user: newUser,
famille: req.body.famille,
nourriture: req.body.nourriture
});
newUser.save((err, user) => {
if (err) {
return res.send({
success: false,
message: 'Failed to save the user'
});
}
newProfile.save();
res.send({
success: true,
message: 'User Saved yes',
user,
newProfile,
});
});
}
}
|
var User = require('./model/user');
var Card = require('./model/card');
var mongoose = require('mongoose');
var bluebird = require('bluebird');
mongoose.Promise = bluebird;
var applyCard = function (mainUser ,minonUser,credit_line) {
var account = new Account({
account_id : randomstring.generate({
length: 16,
charset: '0123456789'
}),
time : dateutil.format(new Date(),'YYYY-MM-DD HH:mm:ss'),
money : 200,
merchant : '星巴克',
merchant_id : randomstring.generate({
length: 8,
charset: '0123456789'
}),
pos_id : randomstring.generate({
length: 12,
charset: '0123456789'
}),
detail : "星冰乐",
type : "餐饮酒水",
consum_card :mongoose.Types.ObjectId('5bbf284a6a967e23874202f1'),
owner_card : mongoose.Types.ObjectId('5bbf3bfe7453e50f604bdb7c')
});
account.save(function (err,result){
res.send({code:1000,msg:"成功"});
});
minonUser.save((err,res) => {
if (err) {
console.log("User Insert Error:" + error);
}
return Promise.resolve (res);
})
.then((res) => {
console.log("Inser User Res:"+ res);
var main_Id,minor_Id;
User.find ({'user_id' : mainUser.user_id}
).exec().then(function (res) {
main_Id = res[0].id;
console.log("main_Id Res:" + main_Id);
},function (error) {
console.log("Find Error:" + err);
});
});
// var mypromise = minonUser.save().exec();
// mypromise.then(function (res) {
// console.log("Inser User Res:"+ res);
// var main_Id,minor_Id;
// User.find ({'user_id' : mainUser.user_id}
// ).then(function (res) {
// main_Id = res[0].id;
// console.log("main_Id Res:" + main_Id);
// },function (error) {
// console.log("Find Error:" + err);
// });
// },function (error){
// console.log("User Insert Error:" + error);
// });
// var main_Id,minor_Id;
// User.find ({'user_id' : mainUser.user_id}, function(err, res){
// if (err) {
// console.log("Find Error:" + err);
// }
// else {
// // main_Id = res[0].id;
// console.log("main_Id Res:" + main_Id);
// }
// });
// console.log("++++++ mytest Res:" + mytest[0]);
// User.find ({'user_id' : minonUser.user_id}, function(err, res){
// if (err) {
// console.log("Find Error:" + err);
// }
// else {
// // minor_Id = res[0].id;
// console.log("minor_Id Res:" + minor_Id);
// }
// });
var card = new Card (
{
card_num : '621024344423232',
bank : '招商银行',
type : 0,
credit_line : credit_line,
main_id : mongoose.SchemaTypes.ObjectId(main_Id),
minor_id : minor_Id
}
);
card.save (function(err,res) {
if (err) {
console.log("Card Insert Error:" + err);
}
else {
console.log("Res:"+ res);
}
});
};
exports.function = applyCard;
|
import babel from 'rollup-plugin-babel';
import babelrc from 'babelrc-rollup';
const pkg = require('./package.json');
export default {
sourcemap: true,
input: 'src/index.js',
external: Object.keys(pkg.dependencies),
plugins: [
babel(
Object.assign(
{
include: ['src/**']
},
babelrc()
)
)
],
output: [
{
sourcemap: true,
name: 'StratumnAgentClient',
file: pkg.module,
format: 'es'
},
{
sourcemap: true,
name: 'StratumnAgentClient',
file: pkg.main,
format: 'cjs'
}
]
};
|
import React, { useState, useEffect } from 'react';
import {
Button,
Card,
CardBody,
CardHeader,
Col,
Collapse,
Fade,
Form,
FormGroup,
Input,
InputGroup,
Label,
Row,
} from 'reactstrap';
import axios from 'axios';
import { ToastContainer, toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.css';
import { token, API_SERVER } from '../../../helper/variable';
const CreateRekening = (props) => {
const [dataBank, setDataBank] = useState([]);
const [ownerName, setOwnerName] = useState('')
const [number, setNumber] = useState('');
const [status, setStatus] = useState('');
const [bankId, setBankId] = useState(0);
const timeout = 300;
const fadeIn = true;
const collapse = true;
const ca = token
const base64Url = ca.split('.')[1];
const decodedToken = JSON.parse(window.atob(base64Url));
let url = '';
if(decodedToken.group === 1){
url = 'bank'
}
if(decodedToken.group === 3){
url = 'bank-operational'
}
useEffect(() => {
axios.get(`${API_SERVER}/${url}`, {
headers: {
Authorization: `Bearer ${token}`
}
})
.then(res => setDataBank(res.data.values))
}, [url])
const success = () => {
toast.success("Bank berhasil ditambahkan", {
onClose: () => window.location.href="/rekening",
autoClose: 2000
})
}
const error = message => {
toast.error(`${message}`,{
onClose: () => window.location.reload(),
autoClose: 2000
})
}
const submitData = async (e) => {
e.preventDefault();
const ca = token
const base64Url = ca.split('.')[1];
const decodedToken = JSON.parse(window.atob(base64Url));
let url2 = '';
if(decodedToken.group === 1){
url2 = 'rekening-admin'
}
if(decodedToken.group === 3){
url2 = 'rekening-operational'
}
try {
const result = await axios.post(`${API_SERVER}/${url2}`, {
name: ownerName,
number: number,
bankId: bankId,
active: status
}, {
headers: {
Authorization: `Bearer ${token}`
}
})
if(result.status === 200 && result.data.status === 'OK'){
success();
} else if(result.data.message === 'Rekening has been created') {
error('Rekening has been created');
} else {
error('Terdapat kesalahan pada server')
}
} catch (error) {
console.log(error)
}
}
return (
<div>
<Row>
<ToastContainer position={toast.POSITION.TOP_CENTER}/>
<Col xs="9">
<Fade timeout={timeout} in={fadeIn}>
<Card>
<CardHeader>
<i className="fa fa-edit"></i>Create Bank
</CardHeader>
<Collapse isOpen={collapse} id="collapseExample">
<CardBody>
<Form onSubmit={submitData} className="form-horizontal">
<FormGroup>
<Label htmlFor="appendedInput">Nama Pemilik Rekening</Label>
<div className="controls">
<InputGroup>
<Input onChange={e => setOwnerName(e.target.value)} value={ownerName} size="16" type="text" required />
</InputGroup>
</div>
</FormGroup>
<FormGroup>
<Label htmlFor="appendedInput">Nomor Rekening</Label>
<div className="controls">
<InputGroup>
<Input onChange={e => setNumber(e.target.value)} value={number} size="16" type="number" required />
</InputGroup>
</div>
</FormGroup>
<FormGroup>
<Label htmlFor="exampleSelect">Bank</Label>
<div className="controls">
<Input onChange={e => setBankId(e.target.value)} type="select" name="status" id="exampleSelect">
<option disabled selected>Pilih Bank</option>
{dataBank.map((item, index) => {
return(
<>
<option key={index} value={item.id}>{item.name}</option>
</>
)
})}
</Input>
</div>
</FormGroup>
<FormGroup>
<Label for="exampleSelect">Status</Label>
<Input onChange={e => setStatus(e.target.value)} type="select" name="status" id="exampleSelect">
<option disabled selected>Status</option>
<option value="1">Active</option>
<option value="0">Non Active</option>
</Input>
</FormGroup>
<div className="form-actions">
<Button type="submit" size="sm" color="success" style={{marginRight: '10px'}}><i className="fa fa-dot-circle-o"></i>Submit</Button>
<Button onClick={() => window.location.reload()} type="reset" size="sm" color="danger"><i className="fa fa-ban"></i> Reset</Button>
</div>
</Form>
</CardBody>
</Collapse>
</Card>
</Fade>
</Col>
</Row>
</div>
)
}
export default CreateRekening;
|
import React from "react";
import CustomSlider from "./CustomSlider";
export default {
title: "form/Input/Slider",
component: CustomSlider,
};
export const CustomSliderComponent = () => <CustomSlider />;
|
/*
* Loading libraries
*/
var fs = require("fs");
/*
* Global variables
*/
var rebalancingPath0 = "../Data/201402_rebalancing_data-000.csv";
var rebalancingPath1 = "../Data/201402_rebalancing_data-001.csv";
var rentalOutputPath = "../Prediction/input/rental_data.csv";
/**
* Main Work Here :
* - Read one file, then the other
* - Compute the diff for each line to know how many bike left and entered the station
*/
fs.readFile(rebalancingPath0, 'utf8', function(err, data1) {
console.log("# First file read");
if (err)
throw err;
fs.readFile(rebalancingPath1, 'utf8', function(err, data2) {
console.log("# Second file read");
if (err)
throw err;
data1 = data1.split("\n");
data2 = data2.split("\n");
console.log('# Line splited');
var fullCSV = "";
var currentHour = new Date(Date.UTC(2013, 07, 29, 12, 0));
var nextHour = new Date(Date.UTC(2013, 07, 29, 13, 0));
var bikesIn = 0;
var bikesOut = 0;
var lastBikeCount = 0;
var idStation = 0;
fs.writeFileSync(rentalOutputPath, "station_id, bikeIn, bikeOut, date, time, day, holiday\n");
console.log("# Data consolidated");
console.time("start_loop");
function extractBikeData(data) {
/**
* Going through each log line to compute the number of bikes in and bikes out of each stations
*/
for (var i = 1; i < data.length; i++) {
/**
* Skip header lines
*/
if (data[i].match(/^station_id/))
continue;
var line = data[i].replace(/"/g, "").split(",");
station_id = parseInt(line[0], "10");
/**
* Selection of the San Fransisco Stations
*/
if ((station_id > 77 || station_id < 41) && station_id != 82)
continue;
time = new Date(line[3] + " GMT");
bikes_available = parseInt(line[1], "10");
docks_available = parseInt(line[2], "10");
/**
* Saving each 100 000 loop to free up memory
*/
if (i % 100000 == 0) {
fs.appendFileSync(rentalOutputPath, fullCSV);
console.timeEnd("start_loop");
console.time("start_loop");
fullCSV = "";
console.log("saving.. " + i);
}
/**
* When we hit another hour, we reset the count for the next hour
*/
if (time > nextHour) {
var dateStr = currentHour.toISOString().replace(/-/g, "/").split("T");
var toSave = idStation + ", " + bikesIn + ", " + bikesOut + ", " + dateStr[0] + ", " + dateStr[1].split(".")[0] + ", \"" + getDay(currentHour) + "\", " + isHoliday(currentHour);
fullCSV += toSave + "\n";
currentHour = new Date(time.getFullYear(), time.getMonth(), time.getDate(), time.getHours(), 0, 0);
nextHour = new Date(currentHour);
nextHour.setHours(nextHour.getHours() + 1);
bikesIn = bikesOut = 0;
}
var movement = bikes_available - lastBikeCount;
/**
* When hitting a new station, we reset the count
*/
if (idStation != station_id) {
idStation = station_id;
console.log("New Station: " + idStation);
movement = 0;
currentHour = new Date(Date.UTC(2013, 07, 29, 12, 0, 0));
nextHour = new Date(Date.UTC(2013, 07, 29, 13, 0, 0));
bikesIn = bikesOut = 0;
}
/**
* if the movement is positive, then the sation gained some bike, otherwise, they were rented
*/
if (movement >= 0)
bikesIn += movement;
else
bikesOut -= movement;
lastBikeCount = bikes_available;
}
fs.appendFileSync(rentalOutputPath, fullCSV);
}
extractBikeData(data1)
extractBikeData(data2)
console.timeEnd("start_loop");
});
});
/**
* Identify a date as an holiday
* @param {Date} date Date to test for holiday
* @return {Boolean}
*/
function isHoliday(date) {
var day = date.toISOString().split("T")[0];
if (day == "2013-09-02"
|| day == "2013-10-14"
|| day == "2013-11-11"
|| day == "2013-11-28"
|| day == "2013-11-29"
|| day == "2013-12-25"
|| day == "2014-01-01"
|| day == "2014-01-20"
|| day == "2014-01-31"
|| day == "2014-02-17")
return 1;
else
return 0;
}
/**
* Return the day of the week of a given date
* @param {Date} date Date to test
* @return {String} Day of the week in english
*/
function getDay(date) {
switch (date.getUTCDay()) {
case 1:
return "Monday";
case 2:
return "Tuesday";
case 3:
return "Wednesday";
case 4:
return "Thursday";
case 5:
return "Friday";
case 6:
return "Saturday";
case 0:
return "Sunday";
}
}
|
import React from 'react';
// import ReactDOM from 'react-dom';
import TodoList from './Components/todolist'
import TodoForm from './Components/todoForm'
import './App.css';
class App extends React.Component {
constructor() {
super()
this.initialState = {
todoName: '',
todoItems: [],
}
this.state = this.initialState
}
handleSubmit = (e) => {
e.preventDefault();
const { todoName, todoItems } = this.state
const newTodoItemsCopy = [...todoItems];
newTodoItemsCopy.push({
todoName: todoName
})
this.setState({
todoItems: newTodoItemsCopy
})
}
handleName = (e) => {
this.setState({
todoName: e.target.value
})
}
// Use key to delete seperate ones? Nope it just works with a simple remove of the child
removeTodo = () => {
console.log('Remove')
let element = document.getElementById('elementId');
element.parentNode.removeChild(element);
}
render() {
const { todoName, todoItems } = this.state
return (
<div className="App">
<TodoForm
todoName={todoName}
todoItems={todoItems}
handleName={this.handleName}
handleSubmit={this.handleSubmit}
/>
<TodoList
key={todoName}
todoName={todoName}
todoItems={todoItems}
removeTodo={this.removeTodo}
/>
</div>
);
}
}
export default App;
//We want the App state to hold the name and information of the todo itself
//the todo.js will keep its lifecycle methods and be called by the todolist
|
$(document).ready(function() {
$('img[src *= logo]').slideUp(3000).slideDown(3000);
}); // End of ready
|
// need to add follower's img
import React, {useState, useEffect} from 'react';
function UserFolloweeCard({followee, removeFollowee, user, currentUser}){
// followee = friendship's id
// followee.follower_id = (the person who are following you)
// follower.followee_id = (the one being followed)
const API = "http://localhost:3001/"
const [followeeUser, setFolloweeUser] = useState('')
useEffect(()=>{
fetch(`${API}users/find/${followee.followee_id}`)
.then(r => r.json())
.then(userObj=>{
setFolloweeUser(userObj)
})
}, [followee.followee_id])
function handleRemoveFollowee(id){
fetch(`${API}friendships/${id}`, {
method: "DELETE",
})
removeFollowee(id)
}
return(
<div>
<div className="search-card-div">
<div className="search-card-user-image-div">
{followeeUser.image_url
? <img
src={followeeUser.image_url}
alt={followeeUser.username}
/>
: <img
src="https://miro.medium.com/max/720/1*W35QUSvGpcLuxPo3SRTH4w.png"
alt={followeeUser.username}
/>
}
</div>
<div className="search-card-username">{followeeUser.username}</div>
{user.id === currentUser.id
? <span
onClick={() => handleRemoveFollowee(followee.id)}>
<i class="fas fa-user-slash"></i>
</span>
: null
}
</div>
</div>
)
}
export default UserFolloweeCard;
|
/* eslint-env node */
module.exports = {
bail: 1,
coverageDirectory: "coverage",
collectCoverageFrom: ["**/src/**"],
coverageReporters: ["text", "html"],
coverageThreshold: {
global: {
branches: 100,
functions: 100,
lines: 100,
statements: 100,
},
},
notify: true,
notifyMode: "always",
resetMocks: true,
}
|
/**
* @param {number[]} A
* @return {number}
*/
var maxTurbulenceSize = function(A) {
var n = A.length;
var ans = 1;
var anchor = 0;
for (var i = 1; i<n; i++) {
var diff;
if(A[i-1] === A[i]) {
diff = 0;
} else if (A[i-1] <A[i]) {
diff= -1;
} else {
diff = 1;
}
var diff2;
if(A[i] === A[i+1]) {
diff2 = 0;
} else if (A[i] <A[i+1]) {
diff2= -1;
} else {
diff2 = 1;
}
if (diff === 0) {
anchor = i; // update anchor
} else if (i === n-1 || diff * diff2 !== -1) {
ans = Math.max(ans, i- anchor +1);
anchor = i;
}
}
return ans;
};
console.log(maxTurbulenceSize([9,4,2,10,7,8,8,1,9]));
console.log(maxTurbulenceSize([4,8,12,16]));
console.log(maxTurbulenceSize([100]));
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Table } from 'semantic-ui-react';
import { findAll as findAllExploitationTypes} from '../../actions/exploitationTypes';
class RepairsTotalCostsTable extends Component {
componentDidMount = () => {
this.props.findAllExploitationTypes();
}
getRepairsTotalCostValue = (repairsCostsCollection, exploitationTypeValue) => {
if (!repairsCostsCollection || repairsCostsCollection.length <= 0)
return '-';
for (var i=0; i < repairsCostsCollection.length; i++) {
if (repairsCostsCollection[i].exploitationTypeValue === exploitationTypeValue) {
return repairsCostsCollection[i].totalCost;
}
}
return '-';
}
render() {
if (this.props.exploitationTypes
&& this.props.exploitationTypes.length > 0
) {
return (
<Table celled compact fixed definition>
<Table.Header>
<Table.Row>
<Table.HeaderCell />
<Table.HeaderCell>{this.props.exploitationTypes[0].exploitationType}</Table.HeaderCell>
<Table.HeaderCell>{this.props.exploitationTypes[1].exploitationType}</Table.HeaderCell>
<Table.HeaderCell>{this.props.exploitationTypes[2].exploitationType}</Table.HeaderCell>
</Table.Row>
</Table.Header>
<Table.Body>
<Table.Row>
<Table.Cell>Total cost</Table.Cell>
<Table.Cell>{this.getRepairsTotalCostValue(this.props.repairsTotalCosts, this.props.exploitationTypes[0].value)}</Table.Cell>
<Table.Cell>{this.getRepairsTotalCostValue(this.props.repairsTotalCosts, this.props.exploitationTypes[1].value)}</Table.Cell>
<Table.Cell>{this.getRepairsTotalCostValue(this.props.repairsTotalCosts, this.props.exploitationTypes[2].value)}</Table.Cell>
</Table.Row>
</Table.Body>
</Table>
);
} else
return (<div style = {{ display: 'none' }}></div>);
}
}
const mapStateToProps = (state) => {
return {
exploitationTypes: state.exploitationTypesReducer.exploitationTypes
}
}
export default connect(mapStateToProps, { findAllExploitationTypes }) (RepairsTotalCostsTable);
|
import React, {useState} from 'react';
import AddOneTodo from './AddOneTodo';
const TodoList = ()=> {
const [todos, setTodos] = useState([
{id: 1, todo: 'Acheter des cadeaux de noel'},
{id: 2, todo: 'Emballez les cadeaux de noel'},
{id: 3, todo: 'Offrir les cadeaux de noel'}
])
const [warning, setWarning] = useState(false)
console.log(todos);
const myTodos = todos.map((todo) => {
return (
<li key={todo.id}> {todo.todo} </li>
)
})
const addNewTodo = (newTodo) => {
if(newTodo !== '') {
setTodos([...todos, {
id: '',
todo: newTodo
}])
} else {
setWarning(true);
}
}
return (
<div>
<h2> {todos.length} To - do</h2>
<ul>
{myTodos}
</ul>
<AddOneTodo addNewTodo={addNewTodo} />
</div>
)
}
export default TodoList;
|
import React from "react";
import { Container, Row, Col, NavLink } from "reactstrap";
import { MdModeEdit } from "react-icons/md";
import EditAbout from "./editabout";
import { connect } from "react-redux";
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
const About = (props) => {
const { clinician } = props.auth;
return (
<Container>
<div className="position">
<h2 className="floater-left1 dataDesign">About</h2>
<NavLink href="/editabout" className="floater-right1">
<MdModeEdit size="25px" />
Edit
</NavLink>
</div>
<Container style={{ height: "288px" }} className="floater-left1">
<Row style={{ padding: "4px 0px 4px 0px" }}>
<Col sm={2}>Name</Col>
<Col sm={10} className="dataDesign">
{`${clinician.firstName} ${clinician.middleName} ${clinician.lastName}`}
</Col>
</Row>
<Row style={{ padding: "4px 0px 4px 0px" }}>
<Col sm={2}>Birthdate</Col>
<Col sm={10} className="dataDesign">
{`${clinician.birthMonth} ${clinician.birthDay}, ${clinician.birthYear}`}
</Col>
</Row>
<Row style={{ padding: "4px 0px 4px 0px" }}>
<Col sm={2}>Age</Col>
<Col sm={10} className="dataDesign">
{`${clinician.age} y/o`}
</Col>
</Row>
<Row style={{ padding: "4px 0px 4px 0px" }}>
<Col sm={2}>Sex</Col>
<Col sm={10} className="dataDesign">
{`${clinician.sex}`}
</Col>
</Row>
<Row style={{ padding: "4px 0px 4px 0px" }}>
<Col sm={2}>Contact No.</Col>
<Col sm={10} className="dataDesign">
{clinician.contactNumber ? clinician.contactNumber : "N/A"}
</Col>
</Row>
</Container>
<Router>
<Switch>
<Route exact path="/editabout" component={EditAbout} />
</Switch>
</Router>
</Container>
);
};
const mapStateToProps = (state) => ({
auth: state.auth
});
export default connect(mapStateToProps)(About);
|
import React from 'react';
class InputRadio extends React.Component {
constructor(props) {
super(props);
this.state = {inputs: this.props.inputs}
}
onClick(ev) {
let e = ev.target;
let $inputs = this.state.inputs;
let $index = $(e).data("index");
$inputs.map((input, i) => {
if(i == $index) {
input.isChecked = true;
} else {
input.isChecked = false;
}
return input;
})
this.setState({inputs: $inputs});
}
onChange() {
//this.setState({isChecked: !this.state.isChecked});
}
render() {
return <div>
{
this.state.inputs.map((input, index) => {
if(input.isChecked) {$("#"+this.props.ID).val(input.val)}
return <div key={input.val} styles="display: inline-block; width: 200px; height: 100px; margin: 1em;">
<input className="mdl-js-radio__button" data-index={index} type="radio" name={input.name} id={input.id} checked={input.isChecked} defaultValue={input.val} onChange={this.onChange.bind(this)} onClick={this.onClick.bind(this)} />
<label className="mdl-js-radio__label" htmlFor={input.id}>{input.show}</label>
</div>
})
}
<input id={this.props.ID} name={this.props.ID} type="hidden" defaultValue={this.props.default} />
</div>
}
}
export default InputRadio
|
let mongoose = require('mongoose');
let AccountSchema = require('../schemas/AccountSchema');
let Account = mongoose.model('account', AccountSchema);
module.exports = Account;
|
const express = require('express');
const app = express()
const mongoose = require('mongoose');
// const bodyParser = require('body-parser');
mongoose.set('useFindAndModify', false);
require('dotenv/config')
mongoose.connect(process.env.DB_CONNECTION, {useNewUrlParser: true, useUnifiedTopology: true})
const database = mongoose.connection
database.on('error', (error) => {
console.error(error);
});
database.once('open', ()=> {
console.log('Mongo Connected')
})
app.set('view engine', 'ejs');
app.use(express.urlencoded({extended:false}));
const questionRouter = require('./routes/question');
const optionsRouter = require('./routes/options');
app.use(express.json());
app.use('/questions', questionRouter);
app.use('/options', optionsRouter);
app.get('/', (req,res) => {
res.render('index')
})
app.listen(process.env.PORT || 3000, function(){
console.log("Express server listening on port %d in %s mode", this.address().port, app.settings.env);
});
// app.listen(3000, () => {
// console.log('Server Started');
// });
|
import * as Constants from '../constants/Constants';
function register(profileState, action) {
switch (action.type) {
case Constants.REGISTER(Constants.PENDING):
return {
...profileState,
register: {
saving: true
}
};
case Constants.REGISTER(Constants.FULFILLED):
return {
...profileState,
register: {
saving: false,
saved: true,
data: action.payload
}
};
case Constants.REGISTER(Constants.REJECTED):
return {
...profileState,
register: {
saving: false,
saved: false,
error: action.payload
}
};
default:
return profileState
}
}
function getProfile(profileState, action) {
switch (action.type) {
case Constants.GET_MY_PROFILE(Constants.PENDING):
return {
...profileState,
profile: {
fetching: true
}
};
case Constants.GET_MY_PROFILE(Constants.FULFILLED):
return {
...profileState,
profile: {
fetching: false,
fetched: true,
data: action.payload.data
}
};
case Constants.GET_MY_PROFILE(Constants.REJECTED):
return {
...profileState,
profile: {
fetching: false,
fetched: false,
error: action.payload
}
};
default:
return profileState
}
}
function getSingle(profileState, action) {
switch (action.type) {
case Constants.GET_SINGLE_PROFILE(Constants.PENDING):
return {
...profileState,
currentProfile: {
...profileState.currentProfile,
single: {
...profileState.currentProfile.single,
fetching: true,
fetchingId: action.meta.fetchingId
},
friends: {
fetching: false,
fetched: false,
data: null,
error: null
}
}
};
case Constants.GET_SINGLE_PROFILE(Constants.FULFILLED):
return {
...profileState,
currentProfile: {
...profileState.currentProfile,
single: {
...profileState.currentProfile.single,
fetching: false,
fetched: true,
data: action.payload.data
}
}
};
case Constants.GET_SINGLE_PROFILE(Constants.REJECTED):
return {
...profileState,
currentProfile: {
...profileState.currentProfile,
single: {
...profileState.currentProfile.single,
fetching: false,
fetched: true,
error: action.payload
}
}
};
default:
return profileState
}
}
function getFriends(profileState, action) {
switch (action.type) {
case Constants.GET_FRIENDS(Constants.PENDING):
return {
...profileState,
currentProfile: {
...profileState.currentProfile,
friends: {
fetching: true
}
}
};
case Constants.GET_FRIENDS(Constants.FULFILLED):
return {
...profileState,
currentProfile: {
...profileState.currentProfile,
friends: {
fetching: false,
fetched: true,
data: action.payload.data
}
}
};
case Constants.GET_FRIENDS(Constants.REJECTED):
return {
...profileState,
currentProfile: {
...profileState.currentProfile,
friends: {
fetching: false,
fetched: true,
data: action.payload.data
}
}
};
default:
return profileState
}
}
function getAllProfile(profileState, action) {
switch (action.type) {
case Constants.GET_ALL_PROFILE(Constants.PENDING):
return {
...profileState,
profiles: {
fetching: true
}
};
case Constants.GET_ALL_PROFILE(Constants.FULFILLED):
return {
...profileState,
profiles: {
fetching: false,
fetched: true,
data: action.payload.data
}
};
case Constants.GET_ALL_PROFILE(Constants.REJECTED):
return {
...profileState,
profiles: {
fetching: false,
fetched: false,
error: action.payload
}
};
default:
return profileState
}
}
function logout(profileState, action) {
switch (action.type) {
case Constants.FACEBOOK_LOG_OUT(Constants.FULFILLED):
return {
...profileState,
profile: {
fetching: false,
fetched: false,
data: null,
error: null
}
};
default:
return profileState
}
}
const initialProfileState = {
register: {
saving: false,
saved: false,
data: null,
error: null
},
profile: {
fetching: false,
fetched: false,
data: null,
error: null
},
profiles: {
fetching: false,
fetched: false,
data: null,
error: null
},
currentProfile: {
single: {
fetching: false,
fetchingId: null,
fetched: false,
data: null,
error: null
},
friends: {
fetching: false,
fetched: false,
data: null,
error: null
}
}
};
const ProfileReducer = (profileState = initialProfileState, action) => {
switch (action.type) {
case Constants.REGISTER(Constants.PENDING):
case Constants.REGISTER(Constants.FULFILLED):
case Constants.REGISTER(Constants.REJECTED):
return register(profileState, action);
case Constants.GET_MY_PROFILE(Constants.PENDING):
case Constants.GET_MY_PROFILE(Constants.FULFILLED):
case Constants.GET_MY_PROFILE(Constants.REJECTED):
return getProfile(profileState, action);
case Constants.GET_ALL_PROFILE(Constants.PENDING):
case Constants.GET_ALL_PROFILE(Constants.FULFILLED):
case Constants.GET_ALL_PROFILE(Constants.REJECTED):
return getAllProfile(profileState, action);
case Constants.GET_SINGLE_PROFILE(Constants.PENDING):
case Constants.GET_SINGLE_PROFILE(Constants.FULFILLED):
case Constants.GET_SINGLE_PROFILE(Constants.REJECTED):
return getSingle(profileState, action);
case Constants.GET_FRIENDS(Constants.PENDING):
case Constants.GET_FRIENDS(Constants.FULFILLED):
case Constants.GET_FRIENDS(Constants.REJECTED):
return getFriends(profileState, action);
case Constants.FACEBOOK_LOG_OUT(Constants.FULFILLED):
return logout(profileState, action);
default:
return profileState;
}
};
export default ProfileReducer;
|
import { expect } from 'chai';
import mockery from 'mockery';
import * as config from '../lib/config';
import conf from './mockdata/conf';
const cwd = process.cwd();
describe('config', () => {
beforeEach(() => {
mockery.enable({ warnOnUnregistered: false });
});
afterEach(() => {
mockery.disable();
});
describe('load', () => {
context('given a configuration file exists', () => {
beforeEach(() => {
mockery.registerMock(`${cwd}/totally`, conf);
});
afterEach(() => {
mockery.deregisterMock(`${cwd}/totally`);
});
it('should resolve the configuration', (done) => {
config.load()
.then((result) => {
expect(result).to.equal(conf);
done();
}).catch(done);
});
});
context('given a configuration file does not exist', () => {
it('should reject with an error', (done) => {
config.load()
.then((conf) => done(new Error()))
.catch((e) => {
expect(e.name).to.equal('ConfigNotFoundError');
done();
});
});
});
});
describe('validate', () => {
context('given a conf that is not an array', () => {
it('should reject with a validation error', (done) => {
config.validate({})
.then((conf) => done(new Error()))
.catch((e) => {
expect(e.name).to.equal('ConfigValidationError');
expect(e.message).to.equal('totally.js must export an array');
done();
});
});
});
context('when validating individual items', () => {
context('and an item is not an object', () => {
it('should reject with a validation error', (done) => {
config.validate(['not-an-object'])
.then((conf) => done(new Error()))
.catch((e) => {
expect(e.name).to.equal('ConfigValidationError');
expect(e.message).to.equal('an item in your configuration is not an object');
expect(e.extra.itemIndex).to.equal(0);
done();
});
});
});
context('and filePath is not defined', () => {
it('should reject with a validation error', (done) => {
config.validate([{}])
.then((conf) => done(new Error()))
.catch((e) => {
expect(e.name).to.equal('ConfigValidationError');
expect(e.message).to.equal('filePath must be defined for each item');
expect(e.extra.itemIndex).to.equal(0);
done();
});
});
});
context('and the filePath is not a string', () => {
it('should reject with a validation error', (done) => {
config.validate([{ filePath: 1 }])
.then((conf) => done(new Error()))
.catch((e) => {
expect(e.name).to.equal('ConfigValidationError');
expect(e.message).to.equal('filePath must be a string');
expect(e.extra.itemIndex).to.equal(0);
done();
});
});
});
context('and endpoint is not defined', () => {
it('should reject with a validation error', (done) => {
config.validate([{ filePath: 'test' }])
.then((conf) => done(new Error()))
.catch((e) => {
expect(e.name).to.equal('ConfigValidationError');
expect(e.message).to.equal('endpoint must be defined for each item');
expect(e.extra.itemIndex).to.equal(0);
done();
});
});
});
context('and endpoint is not a string', () => {
it('should reject with a validation error', (done) => {
config.validate([{ filePath: 'test', endpoint: 1 }])
.then((conf) => done(new Error()))
.catch((e) => {
expect(e.name).to.equal('ConfigValidationError');
expect(e.message).to.equal('endpoint must be a string');
expect(e.extra.itemIndex).to.equal(0);
done();
});
});
});
context('and excludeFromDiff is defined but not a valid type', () => {
it('should reject with a validation error', (done) => {
config.validate([{ filePath: 'test', endpoint: 'test', excludeFromDiff: {} }])
.then((conf) => done(new Error()))
.catch((e) => {
expect(e.name).to.equal('ConfigValidationError');
expect(e.message).to.equal('excludeFrom Diff must be a string or array of strings');
expect(e.extra.itemIndex).to.equal(0);
done();
});
});
});
context('and excludeFromDiff is defined but includes an item that is not a string', () => {
it('should reject with a validation error', (done) => {
config.validate([{ filePath: 'test', endpoint: 'test', excludeFromDiff: [{}] }])
.then((conf) => done(new Error()))
.catch((e) => {
expect(e.name).to.equal('ConfigValidationError');
expect(e.message).to.equal('excludeFromDiff must only contain strings');
expect(e.extra.itemIndex).to.equal(0);
done();
});
});
});
});
});
});
|
/**
* Listens to DML trigger notifications from postgres and pushes the trigger data into kafka
*/
const config = require('config')
const pg = require('pg')
const logger = require('./common/logger')
const kafkaService = require('./services/pushToDirectKafka')
const pushToDynamoDb = require('./services/pushToDynamoDb')
const pgOptions = config.get('POSTGRES')
const postMessage = require('./services/posttoslack')
const pgConnectionString = `postgresql://${pgOptions.user}:${pgOptions.password}@${pgOptions.host}:${pgOptions.port}/${pgOptions.database}`
const pgClient = new pg.Client(pgConnectionString)
const auditTrail = require('./services/auditTrail');
const paudit_dd = require('./services/producer_audit_dd')
const express = require('express')
const app = express()
const port = 3000
const isFailover = process.argv[2] != undefined ? (process.argv[2] === 'failover' ? true : false) : false
async function setupPgClient() {
var payloadcopy
try {
await pgClient.connect()
//for (const triggerFunction of pgOptions.triggerFunctions) {
for (const triggerFunction of pgOptions.triggerFunctions.split(',')) {
await pgClient.query(`LISTEN ${triggerFunction}`)
}
pgClient.on('notification', async (message) => {
try {
payloadcopy = ""
logger.debug('Entering producer 2')
logger.debug(message)
const payload = JSON.parse(message.payload)
payloadcopy = message
const validTopicAndOriginator = (pgOptions.triggerTopics.includes(payload.topic)) && (pgOptions.triggerOriginators.includes(payload.originator)) // Check if valid topic and originator
if (validTopicAndOriginator) {
if (!isFailover) {
//logger.info('trying to push on kafka topic')
await kafkaService.pushToKafka(payload)
logger.info('Push to kafka and added for audit trail')
audit(message)
} else {
logger.info('Push to dynamodb for reconciliation')
await pushToDynamoDb(payload)
logger.info('Push to producer_audit_dd for reconciliation')
await paudit_dd.pushToAuditDD(message)
}
} else {
logger.debug('Ignoring message with incorrect topic or originator')
// push to slack - alertIt("slack message")
}
} catch (error) {
logger.error('Could not parse message payload')
logger.debug(`error-sync: producer parse message : "${error.message}"`)
const errmsg1 = `postgres-ifx-processor: producer or dd : Error Parse or payload : "${error.message}" \n payload : "${payloadcopy.payload}"`
logger.logFullError(error)
audit(error)
// push to slack - alertIt("slack message"
await callposttoslack(errmsg1)
}
})
logger.info('pg-ifx-sync producer: Listening to pg-trigger channel.')
} catch (err) {
const errmsg = `postgres-ifx-processor: producer or dd : Error in setting up postgres client: "${err.message}"`
logger.error(errmsg)
logger.logFullError(err)
// push to slack - alertIt("slack message")
await callposttoslack(errmsg)
terminate()
}
}
const terminate = () => process.exit()
async function run() {
logger.debug("Initialising producer setup...")
await setupPgClient()
if (!isFailover)
{
kafkaService.init().catch((e) => {
logger.error(`Kafka producer intialization error: "${e}"`)
terminate()
})
}
}
async function callposttoslack(slackmessage) {
if (config.SLACK.SLACKNOTIFY === 'true') {
return new Promise(function (resolve, reject) {
postMessage(slackmessage, (response) => {
console.log(`respnse : ${response}`)
if (response.statusCode < 400) {
logger.debug('Message posted successfully');
//callback(null);
} else if (response.statusCode < 500) {
const errmsg1 = `Slack Error: posting message to Slack API: ${response.statusCode} - ${response.statusMessage}`
logger.debug(`error-sync: ${errmsg1}`)
}
else {
logger.debug(`Server error when processing message: ${response.statusCode} - ${response.statusMessage}`);
//callback(`Server error when processing message: ${response.statusCode} - ${response.statusMessage}`);
}
resolve("done")
});
}) //end
}
}
// execute
run()
async function audit(message) {
const pl_processid = message.processId
if (pl_processid != 'undefined') {
const payload = JSON.parse(message.payload)
const pl_seqid = payload.payload.payloadseqid
const pl_topic = payload.topic // TODO can move in config ?
const pl_table = payload.payload.table
const pl_uniquecolumn = payload.payload.Uniquecolumn
const pl_operation = payload.payload.operation
const pl_timestamp = payload.timestamp
const pl_payload = JSON.stringify(payload.payload)
const logMessage = `${pl_seqid} ${pl_processid} ${pl_table} ${pl_uniquecolumn} ${pl_operation} ${payload.timestamp}`
if (!isFailover) {
logger.debug(`producer : ${logMessage}`);
} else {
logger.debug(`Producer DynamoDb : ${logMessage}`);
}
await auditTrail([pl_seqid, pl_processid, pl_table, pl_uniquecolumn, pl_operation, "push-to-kafka", "", "", "", JSON.stringify(message), pl_timestamp, pl_topic], 'producer')
} else {
const pl_randonseq = 'err-' + (new Date()).getTime().toString(36) + Math.random().toString(36).slice(2)
if (!isFailover) {
await auditTrail([pl_randonseq, 1111, "", "", "", "error-producer", "", "", message.message, "", new Date(), ""], 'producer')
}
}
}
app.get('/health', (req, res) => {
res.send('health ok')
})
app.listen(port, () => console.log(`app listening on port ${port}!`))
|
import React from 'react';
import './style.css'
const card = (props) => {
return <div className="container" >
<img className="img" src={props.img} alt="" />
<div className="desc"><p className="head"> {props.title}</p><br />
<p> {props.description}</p></div>
</div>
}
export default card;
|
(function ($) {
"use strict";
/*global alert: true, ODSA */
$(document).ready(function () {
var initData, bh,
settings = new JSAV.utils.Settings($(".jsavsettings")),
jsav = new JSAV($('.avcontainer'), {settings: settings}),
exercise,
arr1, arr2, arr3, arr4,
input1, input2, input3,
invoutputarr,
swapIndex,
currentinvisoutput,
invoutput,
output;
jsav.recorded();
function init() {
var inputlabel1 = jsav.label("Input Runs", {left: 140, top: 200});
var outputlabel1 = jsav.label("Output Buffer", {left: 350, top: 250});
var disklabel = jsav.label("Disk", {left: 475, top: 170});
var nodeNum = 3;
currentinvisoutput = jsav.variable(0);
if(arr1)
{
arr1.clear();
}
if(arr2)
{
arr2.clear();
}
if(arr3)
{
arr3.clear();
}
if(arr4)
{
arr4.clear();
}
if(invoutputarr)
{
invoutputarr.clear();
}
invoutput = ["", "", "", "", "", "", "", "", ""];
output = ["", "", ""];
input1 = JSAV.utils.rand.numKeys(10, 100, nodeNum);
input2 = JSAV.utils.rand.numKeys(10, 100, nodeNum);
input3 = JSAV.utils.rand.numKeys(10, 100, nodeNum);
input1.sort();
input2.sort();
input3.sort();
// Create an array object under control of JSAV library
arr1 = jsav.ds.array(input1, {indexed: false, left: 135, top: 230});
arr2 = jsav.ds.array(input2, {indexed: false, left: 135, top: 280});
arr3 = jsav.ds.array(input3, {indexed: false, left: 135, top: 330});
arr4 = jsav.ds.array(output, {indexed: false, left: 350, top: 280});
invoutputarr = jsav.ds.array(invoutput, {indexed: false, left: 350, top: 200, visible: true});
// Log the initial state of the exercise
var exInitData = {};
exInitData.gen_array = input1;
ODSA.AV.logExerciseInit(exInitData);
swapIndex = jsav.variable(-1);
jsav._undo = [];
jsav.displayInit();
// click handler
arr1.click(clickHandler);
arr2.click(clickHandler);
arr3.click(clickHandler);
arr4.click(clickHandler);
return [invoutputarr, arr1, arr2, arr3, arr4, currentinvisoutput];
}
function fixState(modelState) {
var modelinvoutputarr = modelState[0];
var modelarr1 = modelState[1];
var modelarr2 = modelState[2];
var modelarr3 = modelState[3];
var modelarr4 = modelState[4];
var modelinvisoutput = modelState[5];
var invoutputsize = modelinvoutputarr.size();
var arrsize1 = arr1.size();
var arrsize2 = arr2.size();
var arrsize3 = arr3.size();
var arrsize4 = arr4.size();
// check invoutputarr
for (var i = 0; i < invoutputsize; i++)
{
invoutputarr.value(i, modelinvoutputarr.value(i));
}
// check arr1
for (var j = 0; j < arrsize1; j++)
{
arr1.value(j, modelarr1.value(j));
}
// check arr2
for (var k = 0; k < arrsize2; k++)
{
arr2.value(k, modelarr2.value(k));
}
// check arr3
for (var l = 0; l < arrsize3; l++)
{
arr3.value(l, modelarr3.value(l));
}
// check arr1
for (var m = 0; m < arrsize4; m++)
{
arr4.value(m, modelarr4.value(m));
}
// only swaps are graded so swapIndex cannot be anything else after correct step
swapIndex.value(-1);
// check invis array "size"
currentinvisoutput.value(modelinvisoutput.value());
}
function model(modeljsav) {
var setWhite = function (index, arr) {
arr.css(index, {"background-color": "#FFFFFF", "color": "black" });
};
var setYellow = function (index, arr) {
arr.css(index, {"background-color": "#FFFF00", "color": "black" });
};
var highlight_background_color = "#2B44CF";
var highlight = function (index, arr) {
arr.css(index, {"background-color": highlight_background_color, "color": "white"});
};
var modelarr1 = modeljsav.ds.array(input1, {indexed: false, left: 85, top: 30});
var modelarr2 = modeljsav.ds.array(input2, {indexed: false, left: 85, top: 80});
var modelarr3 = modeljsav.ds.array(input3, {indexed: false, left: 85, top: 130});
var modelarr4 = modeljsav.ds.array(output, {indexed: false, left: 300, top: 80});
var modelinvoutputarr = modeljsav.ds.array(invoutput, {indexed: false, left: 300, top: 0, visible: true});
var inputlabel2 = modeljsav.label("Input Runs", {left: 90, top: 0});
var outputlabel2 = modeljsav.label("Output Buffer", {left: 300, top: 50});
var disklabel2 = modeljsav.label("Disk", {left: 425, top: -25});
modeljsav.displayInit();
var currentoutput = 0;
var currentinvoutput = modeljsav.variable(0);
var currentinput1 = 0;
var currentinput2 = 0;
var currentinput3 = 0;
modeljsav._undo = [];
while (modelinvoutputarr.value(8) == "") {
modeljsav.umsg("We must look at the first value of each input run.");
setWhite(0, modelarr4);
setWhite(1, modelarr4);
setWhite(2, modelarr4);
setYellow(currentinput1, modelarr1);
setYellow(currentinput2, modelarr2);
setYellow(currentinput3, modelarr3);
modeljsav.step();
// arr1 value is smallest
if(((modelarr1.value(currentinput1) <= modelarr2.value(currentinput2)) &&
(modelarr1.value(currentinput1) <= modelarr3.value(currentinput3))) ||
//must check if other inputs are out of bounds
(currentinput2 == 3 && (modelarr1.value(currentinput1) <= modelarr3.value(currentinput3))) ||
(currentinput3 == 3 && (modelarr1.value(currentinput1) <= modelarr2.value(currentinput2))) ||
(currentinput2 == 3 && currentinput3 == 3))
{
modeljsav.umsg("The value "+modelarr1.value(currentinput1)+" is removed and sent to the output because it is the smallest value.");
modeljsav.effects.moveValue(modelarr1, currentinput1, modelarr4, currentoutput);
setYellow(currentoutput, modelarr4);
setWhite(currentinput1, modelarr1);
setWhite(currentinput2, modelarr2);
setWhite(currentinput3, modelarr3);
currentoutput += 1;
currentinput1 += 1;
modeljsav.stepOption("grade", true);
modeljsav.step();
}
// arr2 value is smallest
else if(((modelarr2.value(currentinput2) <= modelarr1.value(currentinput1)) &&
(modelarr2.value(currentinput2) <= modelarr3.value(currentinput3))) ||
//must check if other inputs are out of bounds
(currentinput1 == 3 && (modelarr2.value(currentinput2) <= modelarr3.value(currentinput3))) ||
(currentinput3 == 3 && (modelarr2.value(currentinput2) <= modelarr1.value(currentinput1))) ||
(currentinput1 == 3 && currentinput3 == 3))
{
modeljsav.umsg("The value "+modelarr2.value(currentinput2)+" is removed and sent to the output because it is the smallest value.");
modeljsav.effects.moveValue(modelarr2, currentinput2, modelarr4, currentoutput);
setYellow(currentoutput, modelarr4);
setWhite(currentinput1, modelarr1);
setWhite(currentinput2, modelarr2);
setWhite(currentinput3, modelarr3);
currentoutput += 1;
currentinput2 += 1;
modeljsav.stepOption("grade", true);
modeljsav.step();
}
// arr3 value is smallest
else if(((modelarr3.value(currentinput3) <= modelarr1.value(currentinput1)) &&
(modelarr3.value(currentinput3) <= modelarr2.value(currentinput2))) ||
//must check if other inputs are out of bounds
(currentinput1 == 3 && (modelarr3.value(currentinput3) <= modelarr2.value(currentinput2))) ||
(currentinput2 == 3 && (modelarr3.value(currentinput3) <= modelarr1.value(currentinput1))) ||
(currentinput1 == 3 && currentinput2 == 3))
{
modeljsav.umsg("The value "+modelarr3.value(currentinput3)+" is removed and sent to the output because it is the smallest value.");
modeljsav.effects.moveValue(modelarr3, currentinput3, modelarr4, currentoutput);
setYellow(currentoutput, modelarr4);
setWhite(currentinput1, modelarr1);
setWhite(currentinput2, modelarr2);
setWhite(currentinput3, modelarr3);
currentoutput += 1;
currentinput3 += 1;
modeljsav.stepOption("grade", true);
modeljsav.step();
}
//check if arr4 needs to be output
if(modelarr4.value(2) !== "")
{
modeljsav.umsg("We must write the output buffer to the disk.");
modeljsav.effects.moveValue(modelarr4, 0, modelinvoutputarr, currentinvoutput.value());
modeljsav.effects.moveValue(modelarr4, 1, modelinvoutputarr, currentinvoutput.value() + 1);
modeljsav.effects.moveValue(modelarr4, 2, modelinvoutputarr, currentinvoutput.value() + 2);
setYellow(0, modelarr4);
setYellow(1, modelarr4);
currentinvoutput.value(currentinvoutput.value() + 3);
currentoutput = 0;
modeljsav.stepOption("grade", true);
modeljsav.step();
}
}
return [modelinvoutputarr, modelarr1, modelarr2, modelarr3, modelarr4, currentinvoutput];
}
var firstSelection, secondSelection;
function clickHandler(index) {
jsav._redo = []; // clear the forward stack, should add a method for this in lib
var sIndex = swapIndex.value();
if (sIndex === -1) { // if first click
firstSelection = this;
firstSelection.css(index, {"font-size": "145%"});
swapIndex.value(index);
} else if (sIndex === index) {
secondSelection = this;
if(firstSelection === secondSelection)
{
firstSelection.css(index, {"font-size": "100%"});
swapIndex.value(-1);
firstSelection = null;
secondSelection = null;
}
// different entities were selected
else
{
firstSelection.css(sIndex, {"font-size": "100%"});
jsav.effects.moveValue(firstSelection, sIndex, secondSelection, index);
firstSelection = null;
secondSelection = null;
swapIndex.value(-1);
exercise.gradeableStep();
}
} else { // second click will swap
secondSelection = this;
if(firstSelection === secondSelection)
{
firstSelection.css([sIndex, index], {"font-size": "100%"});
firstSelection.swap(sIndex, index, {});
}
// different entities were selected
else
{
firstSelection.css(sIndex, {"font-size": "100%"});
jsav.effects.moveValue(firstSelection, sIndex, secondSelection, index);
}
firstSelection = null;
secondSelection = null;
swapIndex.value(-1);
exercise.gradeableStep();
}
}
// Process About button: Pop up a message with an Alert
function about() {
alert("Multiway Merge Proficiency Exercise\nWritten by Josh Horn\nCreated as part of the OpenDSA hypertextbook project\nFor more information, see http://opendsa.org.\nSource and development history available at\nhttps://github.com/OpenDSA/OpenDSA\nCompiled with JSAV library version " + JSAV.version());
}
exercise = jsav.exercise(model, init,
{ compare: { css: "background-color" },
controls: $('.jsavexercisecontrols'),
fix: fixState });
exercise.reset();
$("#outputbuffer").click(function () {
if(currentinvisoutput >= invoutputarr.size()) {
return;
}
jsav.effects.moveValue(arr4, 0, invoutputarr, currentinvisoutput.value());
jsav.effects.moveValue(arr4, 1, invoutputarr, currentinvisoutput.value() + 1);
jsav.effects.moveValue(arr4, 2, invoutputarr, currentinvisoutput.value() + 2);
currentinvisoutput.value(currentinvisoutput.value() + 3);
exercise.gradeableStep();
});
$("#about").click(about);});
}(jQuery));
|
const CategorySerializer = {
serialize({
id,
parent,
name,
slug,
isDeleted,
status,
image,
order,
createdBy,
updatedBy,
createdAt,
updatedAt,
children,
productCount
}) {
return {
id,
parent,
name,
slug,
isDeleted,
status,
image,
order,
createdBy,
updatedBy,
createdAt,
updatedAt,
children,
productCount
};
}
};
module.exports = CategorySerializer;
|
// let characters = null;
// let inventories = null;
// let stacks = null;
// let identificators=null;
// let characterRecipes = null;
// let cellsMap=[];
//
// let charactersUpdate = null;
// let inventoriesUpdate = null;
// let stacksUpdate = null;
// let characterRecipesUpdate = null;
//
// let charactersDelete = [];
// let inventoriesDelete = [];
// let stacksDelete = [];
let isBusy = false;
let timeLoop = 50000;
function toDataBase(sqlUtils, data){
setInterval(function(){
// sqlUtils.initDB().then(
if (!isBusy){
isBusy = true;
sqlUtils.updateById('system', null, 1);
sqlUtils.createTable('identificatorsTmp');
sqlUtils.insertAll('identificatorsTmp', data.identificators);
sqlUtils.createTable('accountsTmp');
sqlUtils.insertAll('accountsTmp',data.accounts);
sqlUtils.createTable('charactersTmp');
sqlUtils.insertAll('charactersTmp',data.characters);
sqlUtils.createTable('inventoriesTmp');
sqlUtils.insertAll('inventoriesTmp', data.inventories);
sqlUtils.createTable('stacksTmp');
sqlUtils.createTable('commonItemsTmp');
sqlUtils.createTable('weaponsRangeTmp');
sqlUtils.insertAll('stacksTmp', data.stacks);
sqlUtils.createTable('characterRecipesTmp');
sqlUtils.insertAll('characterRecipesTmp', data.characters);
//sqlUtils.updateAllById('mapCells', data.getMap());
sqlUtils.updateById('system', null, 2);
sqlUtils.pushDb().then(
result=> {
sqlUtils.drop('identificators'),
sqlUtils.drop('accounts'),
sqlUtils.drop('characters'),
sqlUtils.drop('inventories'),
sqlUtils.drop('stacks'),
sqlUtils.drop('commonItems'),
sqlUtils.drop('weaponsRange'),
sqlUtils.drop('characterRecipes'),
sqlUtils.updateById('system', null, 3),
sqlUtils.pushDb().then(
result=> {
sqlUtils.rename('identificatorsTmp', 'identificators'),
sqlUtils.rename('accountsTmp', 'accounts'),
sqlUtils.rename('charactersTmp', 'characters'),
sqlUtils.rename('inventoriesTmp', 'inventories'),
sqlUtils.rename('stacksTmp', 'stacks'),
sqlUtils.rename('commonItemsTmp', 'commonItems'),
sqlUtils.rename('weaponsRangeTmp', 'weaponsRange'),
sqlUtils.rename('characterRecipesTmp', 'characterRecipes'),
sqlUtils.updateById('system', null, 0),
sqlUtils.pushDb().then(
result=> {
isBusy = false,
console.log('backup database ')
})
})
});
}
}, timeLoop);
}
exports.toDataBase = toDataBase;
// exports.addData = addData;
// exports.addAllData = addAllData;
// exports.deleteData = deleteData;
|
const sharp = require("sharp");
const fs = require("fs");
const path = require("path");
const thumbnailSize = 500;
const inDir = "./static/projects/full";
const outDir = "./static/projects/thumb";
fs.readdir(inDir, (err, files) => {
if (err) {
console.error("Failed to load files", err);
} else {
files.forEach(file => {
console.log(`Processing ${file}...`);
sharp(path.join(inDir, file))
.resize({ width: thumbnailSize, kernel: sharp.kernel.cubic })
.toFile(path.join(outDir, file), (err, info) => {
if (err) {
console.error(`Failed to save ${file}`, err);
} else {
console.log(`Successfully saved ${file}`);
}
});
});
}
});
|
$(document).ready(function(){
/*** SLIDE OUT CARD CONTENT ON MOBILE ***/
$('.mobile-icon').on('click', function(event){
event.preventDefault();
$(this).parent().parent().find('.card-bottom').slideToggle();
console.log('hi there');
});
/*** HIDE OR SHOW CARD CONTENT ON RESPONSIVE WINDOW RESIZE ***/
$(window).resize(function() {
if ($(window).width() < 768){
$('.card-bottom').css('display','none'); //Resets card to be hidden if opened on mobile, resized on Desktop and brough back down to mobile
}else{
$('.card-bottom').css('display','block'); //Prevents the card content from being invisible if resizing on Dekstop
}
});
});
/**** icon-bar:first-of-type{
transform:rotate(45deg);
}
icon-bar:last-of-type{
transform:rotate(-45deg);
top:-10px;
margin-top:-3px;
margin-left:0px
}
.icon-bar .middle-bar{
display:none
}
****/
|
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import {API} from '../Common/config'
import _ from 'lodash';
import Popup from "reactjs-popup";
// import './Teamsdata.css';
var axios = require('axios');
export default class Teams extends Component {
constructor(props) {
super(props);
this.state = {
showLoading: false,
teamList: [],
teamName: '',
teamId: '',
oldTeamId: '',
teamLeadersso:'',
teamCreateSuccess: false,
teamCreateFailure: false,
teamUpdateSuccess: false,
teamUpdateFailure: false,
showTeamFieldsMandatoryMessage: false,
searchTeam: false,
createTeamClicked: false,
noRecordsFound: false,
showPopup: false,
onChangePopupFields: false,
userNotFound: false,
userFound: false,
deletingTeam: '',
onClickDeleteTeam: false,
};
//this.handleClick = this.handleClick.bind(this);
this.handleChange = this.handleChange.bind(this);
this.createTeam = this.createTeam.bind(this);
this.removeTeam = this.removeTeam.bind(this);
}
handleChange(event) {
const target = event.target;
const name = target.name;
const value = event.target.value;
this.setState({ onChangePopupFields: true });
if(target.name === "teamName"){
let regEx = /^[A-z0-9@#$%&*+=?:]*$/g ;
if(regEx.test(value)){
this.setState({ teamName: value });
}
}
// else if(target.name === "teamLeadersso"){
// let regEx = /^[0-9]{0,9}$/g ;
// if(regEx.test(value)){
// this.setState({ teamLeadersso: value });
// }
// }
else{
this.setState({ [name]: value });
}
this.setState({ teamCreateFailure: false });
this.setState({ teamCreateSuccess: false });
this.setState({ teamUpdateFailure: false });
this.setState({ teamUpdateSuccess: false });
this.setState({ noRecordsFound: false });
this.setState({ userNotFound: false });
this.setState({ onClickDeleteTeam: false });
this.setState({ userFound: false });
this.setState({ showTeamFieldsMandatoryMessage: false });
}
onClickTeamsSearch(){
var self = this;
self.setState({ teamList: [] });
self.setState({ showLoading: true });
self.setState({ noRecordsFound: false });
let targetUrl = `${API.appUrl}/teamList?teamName=`+this.state.teamName;
axios.get(targetUrl).then((data) => {
if(data.data.teams.length === 0){
self.setState({ noRecordsFound: true });
}
else{
self.setState({teamList: data.data.teams});
}
self.setState({ showLoading: false });
})
.catch(function (response) {
self.setState({ showLoading: false });
console.log("Error: " + response);
});
}
createTeam(event) {
event.preventDefault();
var self = this;
self.setState({ userFound: false });
self.setState({ userNotFound: false });
self.setState({ showTeamFieldsMandatoryMessage: false });
if( this.state.teamId.trim() === '') {
self.setState({ showTeamFieldsMandatoryMessage: true });
return;
}
self.setState({ showLoading: true });
var body = {
teamId: this.state.teamId,
teamLeadersso: this.state.teamLeadersso,
}
axios({
method: 'post',
url: `${API.appUrl}/addteam`,
data: body
})
.then(function (response) {
console.log(response);
if(response.data.message === 'success'){
self.setState({ teamCreateSuccess: true });
self.setState({ showLoading: false });
}
else{
self.setState({ teamCreateFailure: true });
self.setState({ showLoading: false });
}
})
.catch(function (error) {
self.setState({ teamCreateFailure: true });
self.setState({ showLoading: false });
});
}
clearCreateTeamFields(){
var self = this;
self.setState({ teamId: '' });
self.setState({ teamLeadersso: '' });
self.setState({ showTeamFieldsMandatoryMessage: false });
self.setState({ teamCreateSuccess: false });
self.setState({ userNotFound: false });
self.setState({ userFound: false });
self.setState({ teamCreateFailure: false });
}
clearSearchFields(){
var self = this;
this.clearCreateTeamFields();
self.setState({ teamName: '' });
self.setState({ teamList: [] });
self.setState({ noRecordsFound: false });
self.setState({ userNotFound: false });
this.setState({ onClickDeleteTeam: false });
self.setState({ userFound: false });
}
onClickCreateTeam(event) {
var self = this;
self.clearSearchFields(event);
self.setState({ teamList: [] });
self.setState({ createTeamClicked: true });
self.setState({ searchTeam: true });
self.setState({ teamCreateSuccess: false });
self.setState({ teamCreateFailure: false });
}
onClickCancel(event){
var self = this;
self.clearCreateTeamFields(event);
self.setState({ createTeamClicked: false });
self.setState({ searchTeam: false });
self.setState({ teamCreateSuccess: false });
self.setState({ teamCreateFailure: false });
}
onClickEditButton(TEAM, TEAM_LEADER_SSO, event){
event.preventDefault();
var self = this;
self.setState({ showPopup: true });
self.setState({ teamId:TEAM });
self.setState({ oldTeamId:TEAM });
self.setState({ teamLeadersso:TEAM_LEADER_SSO });
}
onclickSubmitForUpdateTeam(event){
var self = this;
self.setState({ showLoading: true });
self.setState({ onChangePopupFields: true });
self.setState({ showTeamFieldsMandatoryMessage: false });
if( this.state.teamId.trim() === '') {
self.setState({ showTeamFieldsMandatoryMessage: true });
return;
}
var body = {
oldTeamId: this.state.oldTeamId,
teamId: this.state.teamId,
teamLeadersso: this.state.teamLeadersso,
}
axios({
method: 'put',
url: `${API.appUrl}/editTeam`,
data: body
})
.then(function (response) {
self.setState({ teamUpdateSuccess: true });
self.setState({ showLoading: false });
})
.catch(function (error) {
self.setState({ teamUpdateFailure: true });
self.setState({ showLoading: false });
});
}
removeTeam(team){
this.setState({ deletingTeam: team });
this.setState({ onClickDeleteTeam: false });
const url = `${API.appUrl}/deleteTeam`;
axios.delete(url, { data: { team: this.state.deletingTeam }})
.then(res => {
console.log(res.data);
this.setState({ teamName : ''});
this.onClickTeamsSearch();
this.setState({ deletePopup: false });
this.setState({ onClickDeleteTeam: true });
})
.catch((err) => {
console.log(err);
})
}
onClickCancelFOrUpdateTeamInPopup(event){
this.setState({ showPopup: false });
this.setState({ onChangePopupFields: false });
this.setState({ teamUpdateSuccess: false });
this.setState({ teamUpdateFailure: false });
this.onClickTeamsSearch();
this.setState({ deletePopup: false });
}
onClickdeleteTeamToShowPopup(team){
var self = this;
console.log(team);
self.setState({ deletingTeam: team }, () => console.log(this.state.deletingTeam));
self.setState({ deletePopup: true });
}
onBlurTeamLeaderSSO(event) {
var self = this;
self.setState({ showLoading: true });
self.setState({ userNotFound: false });
self.setState({ userFound: false });
let parseString = require('xml2js').parseString;
let config = {
headers: {
'Content-Type': 'application/json',
'API_KEY': "asdas578SFG-fwmvobsknaiv60"
}
};
let url = 'https://sso-name.ext.geappl.io/IPAL/webapi/user/';
var res = url.concat (self.state.teamLeadersso);
var userId;
let getUsers =
axios.get( res,config ).then(function (response) {
parseString(response.data, function (err, result) {
console.log(result.users.user[0].georaclehrid);
userId = result.users.user[0].georaclehrid;
})
}).then(data => {
self.setState({ userFound: true });
self.setState({ showLoading: false });
})
.catch(function (error) {
self.setState({ userNotFound: true });
self.setState({ showLoading: false });
console.log('Error: '+ error);
});
}
render() {
return (
<div className="main-container">
{this.state.showLoading
?<div className="loading">
<div className="loading-icon">
<div></div>
<div></div>
<div></div>
</div>
</div>
:null
}
<main className="main">
{this.state.noRecordsFound === true
?
<h4 style={{ color:"red", textAlign:"center"}}>No results found !</h4>
:null
}
{this.state.onClickDeleteTeam === true
?
<h4 style={{ color:"red", textAlign:"center"}}>Team deleted successfully!</h4>
:null
}
{this.state.showTeamFieldsMandatoryMessage === true
?
<h4 style={{ color:"red", textAlign:"center"}}>Please enter the Team name !</h4>
:null
}
{this.state.userNotFound === true
?
<h4 style={{ color:"red", textAlign:"center"}}>Entered SSO ID is not valid.</h4>
:null
}
{this.state.teamCreateSuccess === true
?
<h4 style={{ color:"green", textAlign:"center"}}>Team created successfully !</h4>
:null
}
{this.state.teamCreateFailure
?
<h4 style={{ color:"red", textAlign:"center"}}>Team creation failed, Team name already exists in database !</h4>
:null
}
<div className="container content inner-page">
<div className="row margin-t2">
{!this.state.searchTeam
?
<div className="col-12">
<h2> Team Data Maintenance</h2>
<p style={{textAlign:"justify",fontStyle: "italic"}}> Search with team name to get team details.</p>
<div className="row margin-b1">
<div className="col-12 col-md-6 col-lg-3 margin-t1">
<label htmlFor="teamName">Team Name : </label>
<input type="text" className="input-res" name="teamName" id="teamName" onChange={this.handleChange} value={this.state.teamName}/>
</div>
</div>
<div>
<p style={{color:"#dc3545", fontSize:"14px", textAlign:"justify"}}>(Click "Search" button with empty Team name to fetch all Team(s) details)</p>
</div>
<div className="row margin-b2">
<div className="col-12 col-md-4 col-lg-2 margin-t1">
<input type="button" className="btn-brick btn" onClick={this.onClickTeamsSearch.bind(this)} value="Search" />
</div>
<div className="col-12 col-md-4 col-lg-2 margin-t1">
<input type="button" className="btn-brick btn" onClick={this.onClickCreateTeam.bind(this)} value="Create Team" />
</div>
<div className="col-12 col-md-4 col-lg-2 margin-t1">
<input type="button" className="btn-trueblue btn" onClick={this.clearSearchFields.bind(this)}value="Clear" />
</div>
</div>
</div>
:
null
}
{this.state.teamList
?
<div className="col-12" style={{paddingLeft:"0px"}}>
{this.state.teamList.length > 0
?
<div className="row margin-t2">
<div className="col-12 col-lg-6 margin-v1">
<h5>{this.state.teamList.length} Team(s) match your selections.</h5>
</div>
</div>
:
null
}
{this.state.teamList.length > 0
?
<div className="col-12" style={{paddingLeft:"0px"}}>
<table className="fdw-table scroll-table">
<thead>
<tr className="fdw-table__header sticky-header">
<th style={{ textAlign: "center" }} >Sl. No </th>
<th>Team Name </th>
<th>Team Leader SSO </th>
<th>Edit Team </th>
<th>Delete Team </th>
</tr>
</thead>
<tbody>
{_.sortBy(this.state.teamList, 'TEAM').map((team, index) => {
return (
<tr key={index} className="fdw-table__row">
<td style={{ textAlign: "center" }} >{index+1}</td>
<td>{team.TEAM}</td>
<td>{team.TEAM_LEADER_SSO}</td>
<td>
<a href="javascript:void(0)" style={{ margin:"14px"}} onClick={this.onClickEditButton.bind(this, team.TEAM, team.TEAM_LEADER_SSO)}><i style={{fontSize:"20px",verticalAlign:"middle" }} className="fas text-darkblue fa-edit"></i></a>
</td>
<td>
<a href="javascript:void(0)" style={{ margin:"14px"}} onClick={() => this.onClickdeleteTeamToShowPopup(team.TEAM)} ><i style={{fontSize:"20px",verticalAlign:"middle" }} className="far text-darkblue fa-trash-alt"></i></a>
</td>
</tr>
)}
)
}
</tbody>
</table>
</div>
:null
}
</div>
:null
}
{this.state.createTeamClicked
?
<div className="row">
<div className="col-12">
<div className="row margin-b1">
<div className="col-12">
<h3>Enter New Team Details:</h3>
</div>
<div className="col-12 col-md-6 col-lg-3 margin-t1">
<label htmlFor="teamId">Team Name : <font className="error">*</font></label>
<input type="text" className="input-res" name="teamId" id="teamId" onChange={this.handleChange} value={this.state.teamId} />
</div>
<div className="inputSearchButton col-md-6 col-lg-3" style={{ position:"relative" }}>
<label htmlFor="teamLeadersso">Team Leader SSO :</label>
<input type="text" placeholder="Search.." name="teamLeadersso" id="teamLeadersso" onChange={this.handleChange} value={this.state.teamLeadersso}/>
<button type="button" onClick={this.onBlurTeamLeaderSSO.bind(this)} style={{ height:"59%" }}><i className="fa fa-search"></i></button>
</div>
</div>
<div className="row margin-b2" style={{ paddingTop:"25px"}}>
<div className="col-12 col-md-4 col-lg-2 margin-t1">
<input type="button" className="btn-brick btn" onClick={this.createTeam.bind(this)} defaultValue="Create" />
</div>
<div className="col-12 col-md-4 col-lg-2 margin-t1">
<input type="button" className="btn-trueblue btn" onClick={this.clearCreateTeamFields.bind(this)}value="Clear" />
</div>
<div className="col-12 col-md-4 col-lg-2 margin-t1">
<input type="button" className="btn-trueblue btn" onClick={this.onClickCancel.bind(this)}defaultValue="Cancel" />
</div>
</div>
</div>
</div>
:null
}
</div>
</div>
</main>
{this.state.showPopup &&
<div className="popupHeader">
<div className="popupContent" style={{ width:"65%"}}>
<button className="popupCancelButton" onClick={this.onClickCancelFOrUpdateTeamInPopup.bind(this)}><i style={{fontSize:"30px"}} className="fas error fa-times"></i></button>
<div style={{fontSize:"25px", paddingBottom:"25px" }}> Edit the Team details </div>
<div>
{this.state.showTeamFieldsMandatoryMessage === true
?
<div>
<h4 style={{ color:"red", textAlign:"center", paddingBottom:"25px"}}>Please enter the Team name !</h4>
</div>
:null
}
{this.state.teamUpdateSuccess === true
?
<div>
<h4 style={{ color:"green", textAlign:"center", paddingBottom:"25px" }}>Team Details Updated successfully! </h4>
</div>
:
null}
{this.state.teamUpdateFailure === true
?
<div>
<h4 style={{ color:"red", textAlign:"center", paddingBottom:"25px" }}>Team Updation Failed! </h4>
</div>
:
null}
<div className="row">
<div className="col-12">
<div className="row margin-b1">
<div className="col-12 col-md-6 col-lg-3 margin-t1" style={{paddingLeft:"50px"}}>
<label htmlFor="teamId">Team Name : </label>
<input type="text" className="input-res" name="teamId" id="teamId" onChange={this.handleChange} value={this.state.teamId} />
</div>
<div className="col-12 col-md-6 col-lg-3 margin-t1" style={{paddingLeft:"50px"}}>
<label htmlFor="teamLeadersso">Team Leader SSO : </label>
<input type="text" className="input-res" name="teamLeadersso" id="teamLeadersso" onChange={this.handleChange} value={this.state.teamLeadersso} />
</div>
</div>
</div>
</div>
</div>
{this.state.onChangePopupFields
?
<div className="row margin-b1" style={{ paddingTop: "30px" }}>
<div className="col-12 col-md-6 col-lg-3 margin-t1" style={{paddingLeft:"60px"}}>
<input type="button" className="btn-brick btn" onClick={this.onclickSubmitForUpdateTeam.bind(this)} defaultValue="Submit" />
</div>
<div className="col-12 col-md-6 col-lg-3 margin-t1" style={{paddingLeft:"60px"}}>
<input type="button" className="btn-brick btn" onClick={this.onClickCancelFOrUpdateTeamInPopup.bind(this)} defaultValue="Cancel" />
</div>
</div>
:
null
}
</div>
</div>
}
{this.state.deletePopup &&
<div className="popupHeader">
<div className="popupContent" style={{ width:"45%"}}>
<button className="popupCancelButton" onClick={this.onClickCancelFOrUpdateTeamInPopup.bind(this)}><i style={{fontSize:"30px"}} className="fas error fa-times"></i></button>
<div style={{fontSize:"25px", paddingBottom:"15px", paddingTop:"15px"}}> Are you sure you want to delete this Team record ? </div>
<div className="row margin-b1" style={{ paddingTop: "30px", paddingLeft:"75px" }}>
<div className="col-12 col-md-6 col-lg-3 margin-t1" style={{paddingLeft:"50px"}}>
<input type="button" className="btn-brick btn" onClick={() => this.removeTeam(this.state.deletingTeam)} defaultValue="Yes" />
</div>
<div className="col-12 col-md-6 col-lg-3 margin-t1" style={{paddingLeft:"50px"}}>
<input type="button" className="btn-brick btn" onClick={() => this.setState({ deletePopup: false })} defaultValue="No" />
</div>
</div>
</div>
</div>
}
</div>
);
}
};
|
// export { default } from './Dashboard';
export { default as EmploymentHistory } from './EmploymentHistory';
export { default as PersonalInfo } from './PersonalInfo';
export { default as ExperienceQualifications} from './ExperienceQualifications'
export { default as Disclosures} from './Disclosures'
export { default as Review} from './Review'
|
var fs = require('fs-extra');
var uuid = require('uuid');
var path = require('path');
var Hooks = require('../../../helpers/hooks');
var Files = require('../../../helpers/files');
module.exports = (Orden) => {
Orden.beforeRemote('basePrioritario', Hooks.beforeRemoteFormData);
Orden.basePrioritario = function( operador, file, options, next) {
var ds = Orden.dataSource;
var data = {};
let valores = options && options.accessToken;
let token = valores && valores.id;
let userId = valores && valores.userId;
let desFileName = '';
Promise.resolve()
.then(function() {
return new Promise(function(resolve, reject) {
Orden.app.models.user.findById(
userId,{},
(err,data)=>{
if(err){
console.log(err);
reject();
}
else{
if(!data){
console.log("No se encontraron datos de usuario.");
reject();
}else{
desFileName="nombre x";
//next(null, {archivo:desFileName});
resolve(data);
}
}
}
)
})
})
.then((data)=>{
return new Promise(function(resolve, reject) {
//console.log("1emp_id -> "+emp_id);
let filename = file.name;// uuid.v1() + file.name.substring(file.name.lastIndexOf('.'));
desFileName = uuid.v1()+"_"+filename;
//console.log("ruta complete -> "+emp_id);
let destPath = path.join(Orden.app.get("path").prioritario.generar, desFileName);
// console.log(desFileName);
fs.copyFile(file.path, destPath, (err) => {
if (err) {
reject(err);
}else{
resolve(data);
}
});
})
})
.then((data)=>{
return new Promise(function(resolve, reject) {
let sql = "";
//sql = "select * from proceso.sp_doc_recepcionar_archivo($1,$2,$3, $4, $5);";
sql = "select * from proceso.sp_carga_base_prioritario($1, $2, $3, $4);";
let params = [desFileName, operador, data.emp_id, userId];
//console.log(params);
ds.connector.execute(sql, params, function(err, data) {
if (err){
reject(err);
}else{
if(data[0].error){
next(data[0].mensaje);
}else{
next(null, {archivo:desFileName});
}
}
});
})
})
.catch(function(err){
console.log(err);
next('Ocurrio un error, vuelva a intentar en unos minutos');
});
};
Orden.remoteMethod(
'basePrioritario',
{
http: {
path: '/basePrioritario',
verb: 'post'
},
accepts: [
{
arg: 'operador',
type: 'string',
required: true
},{
arg: 'file',
type: 'object',
required: true
},
{arg: "options", type: "object", 'http': "optionsFromRequest"}
],
returns: {
args: 'response',
type: 'object',
root: true
}
}
);
}
|
import React from "react";
import PropTypes from "prop-types";
import {
Modal,
Header,
Button,
Icon,
Segment,
} from 'semantic-ui-react'
import 'semantic-ui-css/semantic.min.css';
import styles from "./styles.module.scss";
const ConfirmModal = (props, context) => {
return (
<Modal
open={props.visible}
onClose={props.handleClose}
size={props.size}
// dimmer={'blurring'}
// closeIcon
basic
style={{textAlign:'center', color:'black'}}
>
<Segment>
<Modal.Header>
<h2>{props.title}</h2>
</Modal.Header>
<Modal.Content scrolling style={{textAlign: 'center', margin: '20px'}}>
<Modal.Description>
{_renderModalContents(props.contents)}
</Modal.Description>
</Modal.Content>
<Modal.Actions>
<Button onClick={props.handleClose}>
<Icon name='cancel' />{context.t('취소')}
</Button>
<Button color='green' onClick={props.handleConfirm}>
<Icon name='checkmark' />{context.t(`${props.buttonString}`)}
</Button>
</Modal.Actions>
</Segment>
</Modal>
)
}
const _renderModalContents = (contents) => {
return (
contents.map( (t, index) => {
return (
<div key={index} className={styles.descriptionHeader}>
{t.title !== null ? <Header>{t.title}</Header> : null}
<div>
{
t.text.map( (t, index) =>{
return ( <p key={index}>{t}</p> )
})
}
</div>
</div>
)
})
)
}
ConfirmModal.propTypes = {
title: PropTypes.string.isRequired,
contents: PropTypes.array.isRequired,
handleClose: PropTypes.func.isRequired,
handleConfirm: PropTypes.func.isRequired,
buttonString: PropTypes.string.isRequired,
}
ConfirmModal.contextTypes = {
t: PropTypes.func.isRequired
};
export default ConfirmModal;
|
/* Magic Mirror
* Node Helper: MMM-OrderManagement
*
* By
* MIT Licensed.
*/
var util = require("util"),
eyes = require('eyes'),
https = require('https'),
fs = require('fs'),
xml2js = require('xml2js'),
moment = require('moment'),
querystring = require('querystring'),
printer = require('printer');
NodeHelper = require("node_helper");
const { Curl } = require('node-libcurl');
var exec = require("child_process").exec;
parser = new xml2js.Parser(),
module.exports = NodeHelper.create({
start: function() {
this.started = false;
this.config = {};
this.orderList = {};
this.detailOrder = {};
},
socketNotificationReceived: function(notification, payload) {
var self = this;
if (notification === 'CONFIG') {
if (!this.started) {
this.config = payload;
this.started = true;
console.log("MMM-OrderManagment module has started")
this.sendSocketNotification("SHUTIT", payload);
}
}
if (notification === "GET_NEW_ORDERS") {
orderList = this.getNewOrders();
console.log("Get new Orders!");
if (orderList != null && orderList.size > 0){
this.sendSocketNotification("NEW_ORDERS_RECEIVED", orderList);
}else {
this.sendSocketNotification("ORDERS_EMPTY", "");
}
}
if (notification === "GET_ORDER_DETAIL"){
var pOrder = JSON.parse(payload);
detailOrder = this.getOrder(pOrder);
}
if (notification === "UPDATE_ORDER"){
var pOrder = JSON.parse(payload);
this.updateOrder(pOrder);
}
if (notification === "CHANGE_DELIVERY_TIME"){
this.sendSocketNotification("DELIVERY_TIME_DIALOG", payload);
}
if (notification === "PRINT_ORDER"){
console.log("Bestellung drucken ");
this.printOrder(JSON.parse(payload));
//Hier müssen wir nicht zurück
}
if (notification === "CLOSE_OR_OPEN_SHOP"){
var shopClose = JSON.parse(payload);
console.log("Shop " + (shopClose === true ? "schließen. " : "öffnen"));
this.closeOrOpenShop(shopClose);
}
if (notification === "RESTART") {
console.log("Restarting RaspberryPi!");
exec('sudo reboot now', console.log);
}
if (notification === "SHUTDOWN") {
console.log("Shutdown RaspberryPi!");
exec('sudo shutdown now', console.log);
}
},
/*Bestellung wird verändert
Entweder: Status ändern in
"Erhalten" : received
"Küche": kitchen
"Zustellung" : in_delivery
"Zugestellt" : delivered
"Storniert" : error (?)
Oder: Lieferzeit wird verändert
time : YYYY-MM-DD hh:mm:ss + 02:00
*/
updateOrder: function(pOrder){
var self = this;
var pOrderId = Array.isArray(pOrder.OrderID) ? pOrder.OrderID[0] : pOrder.OrderID;
var pTime = Array.isArray(pOrder.DeliveryTime) ? pOrder.DeliveryTime[0] : pOrder.DeliveryTime;
var pStatus = Array.isArray(pOrder.DeliveryStatus) ? pOrder.DeliveryStatus[0] : pOrder.DeliveryStatus;
var putString = JSON.stringify({
status : pStatus,
time : pTime,
close_shop : "false"});
//Erstmal in eine Datei schreiben
fs.writeFileSync("programming.txt", putString);
var curl = new Curl();
console.log("String: "+ putString);
fs.open("programming.txt", 'r+', function (err, fd) {
curl.setOpt(Curl.option.URL, self.config.magentoEndpoint +
self.config.singleOrderAccess + pOrderId + "?login="+
self.config.login+ "&password="+self.config.password);
curl.setOpt(Curl.option.HTTPHEADER, ['Content-Type: application/json']);
curl.setOpt(Curl.option.VERBOSE, false);
curl.setOpt(Curl.option.UPLOAD, true);
curl.setOpt(Curl.option.READDATA, fd);
curl.on('end', function () {
console.log("Habe Bestellung geändert auf: " +JSON.stringify(putString));
curl.close.bind(curl);
// remember to always close the file descriptor!
fs.closeSync(fd);
fs.unlinkSync("programming.txt");
self.sendSocketNotification("ORDER_UPDATE_SUCCESSFUL", "");
});
curl.on('error', function(error) {
console.log("Fehler: " +error);
curl.close.bind(curl);
self.sendSocketNotification("ERROR_ORDER_UPDATE", error);
});
curl.perform();
});
},
//TODO: Es kann nicht sein, dass diese API-Methode an einer Bestellung
//hängt. Zum Testen erstmal hard verdrahtete Bestellung
closeOrOpenShop: function(pClose){
var self = this;
var curl = new Curl();
var paramClose = pClose;
const close = curl.close.bind(curl);
fs.writeFileSync("close.txt", JSON.stringify({close_shop : paramClose}));
fs.open("close.txt", 'r+', function (err, fd) {
curl.setOpt(Curl.option.URL, self.config.magentoEndpoint +
self.config.singleOrderAccess + "999" + "?login="+
self.config.login+ "&password="+self.config.password);
curl.setOpt(Curl.option.HTTPHEADER, ['Content-Type: application/json']);
curl.setOpt(Curl.option.VERBOSE, false);
curl.setOpt(Curl.option.UPLOAD, true);
curl.setOpt(Curl.option.READDATA, fd);
curl.on('end', function () {
console.log("Shop ist nun geschlossen: " +JSON.stringify(paramClose));
curl.close.bind(curl);
fs.closeSync(fd);
fs.unlinkSync("close.txt");
self.sendSocketNotification("SHOP_OPEN_CLOSE_SUCCESSFUL", +JSON.stringify(paramClose));
});
curl.on('error', function(error) {
curl.close.bind(curl);
self.sendSocketNotification("ERROR_OPEN_CLOSE_SHOP", error);
});
curl.perform();
});
},
//Ermittelt die neuen Bestellungen
getNewOrders: function () {
var self =this;
var url = this.config.magentoEndpoint + this.config.apiMethodNewOrders + "?login="+this.config.login+ "&password="+this.config.password ;
var curl = new Curl();
curl.setOpt('URL', url);
curl.setOpt('FOLLOWLOCATION', true);
curl.on('end', function (statusCode, data, headers) {
console.info(statusCode);
console.info('---');
console.info(data.length);
parser.parseString(data, function(err, result) {
if (err) {
console.log('Got error1: ' + err.message);
} else {
var container = result.LieferKasse.OrderList;
self.orderList = container[0];
}
if (self.orderList && self.orderList.Order.length > 0) {
console.log("good");
self.sendSocketNotification("NEW_ORDERS_RECEIVED", JSON.stringify(self.orderList));
}
else {
console.log("bad");
self.sendSocketNotification("ORDERS_EMPTY", "");
}
});
});
curl.on('error', curl.close.bind(curl));
curl.perform();
},
/* Ermittelt zur übergebenen Array von Orders die Bestellung im Format
<LieferKasse>
<StatusMessage>
<OrderID>999</OrderID> # Bestellnummer
<DeliveryStatus>received</DeliveryStatus> # Status
<DeliveryTime>21:50</DeliveryTime> # Lieferzeit | kann auch nur als Text (z.B. "Sofortlieferung") übergeben werden
</StatusMessage>
</LieferKasse>
*/
getOrder: function (pOrder) {
var self =this;
var pOrderId = pOrder["OrderID"];
console.log("ORDER_ID: " + pOrderId);
var url = this.config.magentoEndpoint + this.config.singleOrderAccess + pOrderId+ "?login="+this.config.login+ "&password="+this.config.password ;
console.log(url);
var curl = new Curl();
curl.setOpt('URL', url);
curl.setOpt('FOLLOWLOCATION', true);
curl.on('end', function (statusCode, data, headers) {
console.info(statusCode);
console.info('---');
console.info(data.length);
//console.info(data);
parser.parseString(data, function(err, result) {
if (err) {
console.log('Got error: ' + err.message);
} else {
//eyes.inspect(result);
console.log('Done.' + JSON.stringify(result));
var container = result.LieferKasse.StatusMessage[0];
container.OrderPdf = pOrder["OrderPDF"];
self.sendSocketNotification("ORDER_DETAIL_RECEIVED", JSON.stringify(container));
}
});
console.info('---');
console.info(this.getInfo( 'TOTAL_TIME'));
this.close();
});
curl.on('error', curl.close.bind(curl));
curl.perform();
//self.sendSocketNotification("ORDER_DETAILS_GATHERED", order);
},
//Bestellung ausdrucken
printOrder : function (pBuffer) {
//console.log("Supported Formats are: " + util.inspect(printer.getSupportedPrintFormats(), {colors:true, depth:10}));
//console.log("Supported job commands: " + util.inspect(printer.getSupportedJobCommands(), {colors:true, depth:10}));
var buff = Buffer.from(pBuffer.toString(), 'base64');
//Erstmal in eine Datei schreiben
fs.writeFileSync("receipt.pdf", buff);
//Hier kommt der echte Druck
setTimeout(function(){printer.printFile({
filename: "receipt.pdf",
printer: "pos80",
type: "PDF",
success: function(id){
console.log ("Order printed with Jobid: " + id);
},
error: function(err){
console.log ("Error on printing " + err);
}
})}, 500);
/*printer.printDirect({
data: buff,
printer: "pos80",
type: "PDF",
success: function(id){
console.log ("Order printed with Jobid: " + id);
},
error: function(err){
console.log ("Error on printing " + err);
}
});*/
},
checkForExecError: function(error, stdout, stderr) {
if (stderr) {
console.log('stderr: "' + stderr + '"');
return 1;
}
if (error !== null) {
console.log('exec error: ' + error);
return 1;
}
return 0;
},
})
|
import AbstractView from "./AbstractView.js";
export default class extends AbstractView {
constructor(params) {
super(params);
this.setTitle("Yoga");
}
getHtml = async () => {
return `
<h1>Welcome to Omflow</h1>
<a href="/teachers" data-link>View teachers</a>
<a href="/classes" data-link>View classes</a>
`;
}
}
|
/** @format */
import React from "react";
function RatingStars() {
return (
<React.Fragment>
<div class='rating rating2'>
<a href='#5' title='Give 5 stars'>
★
</a>
<a href='#4' title='Give 4 stars'>
★
</a>
<a href='#3' title='Give 3 stars'>
★
</a>
<a href='#2' title='Give 2 stars'>
★
</a>
<a href='#1' title='Give 1 star'>
★
</a>
</div>
</React.Fragment>
);
}
export default RatingStars;
|
var searchdata________________8js________8js____8js__8js_8js =
[
[ "searchdata________8js____8js__8js_8js", "searchdata________________8js________8js____8js__8js_8js.html#a89024f7782a507e2cdca62a3e262c996", null ]
];
|
import React, { Component } from 'react';
import config from '../config';
class EditRestaurant extends Component {
state = {
the_restaurant: '',
type: '',
id: '',
index: ''
}
componentDidMount() {
const { the_restaurant, type, id } = this.props.location.state.restaurant
const { index } = this.props.location.state
this.setState({
the_restaurant,
type,
id,
index
})
}
handleChange = (e) => {
this.setState({
[e.target.name]: e.target.value
})
}
// update the selected restaurant, with the given id
handleSubmit = (e) => {
e.preventDefault()
const editedRestaurant = {
the_restaurant: this.state.the_restaurant,
type: this.state.type,
id: this.state.id
}
fetch(`${config.API_ENDPOINT}/api/restaurant/${this.state.id}`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(editedRestaurant)
})
.then(() => {
console.log('edit')
this.props.editRestaurant(editedRestaurant, this.state.index)
this.props.history.push('/home')
})
.catch(err => {
this.setState({ err })
})
}
render() {
const { the_restaurant, type } = this.state
return (
<>
{/* submit edited restaurant, with required name, and optional type */}
<div className="EditRestaurant">
<form onSubmit={this.handleSubmit}>
<input
type='text'
value={the_restaurant}
name='the_restaurant'
onChange={this.handleChange}
className="Placeholder"
required
min={3}
/>
<br />
<select
required
onChange={this.handleChange}
name='type'
className="Placeholder"
type='selected'
value={type}
>
<option value='Keto'>Keto</option>
<option value='Mediterranean'>Mediterranean</option>
<option value='Plant-based'>Plant-based</option>
</select>
<br />
<button
type='submit'
>Update</button>
</form>
</div>
</>
);
}
}
export default EditRestaurant;
|
import React,{createContext,useState} from 'react'
export const TaskContext = createContext();
export const TaskListContextProvider = ({children}) => {
const [task, settask] = useState([
])
const [ edititem, setedititem ] = useState(null);
const AddTask = (title) => {
settask([...task,{title,id:Math.floor(Math.random() * 100000000)}])
}
const RemoveTask = (id) => {
settask(task.filter(tasks=>tasks.id!==id))
}
const ClearTask = () => {
settask([])
}
const FindTask = id => {
const item = task.find(tasks => tasks.id === id);
setedititem(item);
}
const EditTask = (title, id) => {
const NewTask = task.map(tasks => tasks.id === id ? {title, id} : tasks);
settask(NewTask);
console.log(NewTask);
setedititem(null);
}
return (
<TaskContext.Provider value={{
task,
AddTask,
RemoveTask,
ClearTask,
FindTask,
edititem,
EditTask
}}>
{children}
</TaskContext.Provider>
)
}
|
const { config } = require('../../framework/index.js');
Page({
data: {
isMore: false,
sliderBox: {
height: 0,
initHeight: 280,
minHeight: 100,
},
},
onReady() {
this.caculateBoxHeight();
},
onShareAppMessage() {
return config.shareData;
},
caculateBoxHeight() {
const that = this;
const query = wx.createSelectorQuery();
query.select('.slider_box').boundingClientRect((rect) => {
const clientHeight = rect.height;
const clientWidth = rect.width;
const ratio = 750 / clientWidth;
const height = clientHeight * ratio;
that.setData({
'sliderBox.height': Math.floor(height / 2),
});
}).exec();
},
});
|
'use strict';
const { Suite } = require('benchmark');
const { mm, pm } = require('./load-time');
const { cyan, red, green } = require('ansi-colors');
const argv = require('minimist')(process.argv.slice(2));
const longList = require('./fixtures/long-list');
/**
* Setup
*/
const cycle = (e, newline) => {
process.stdout.write('\u001b[G');
process.stdout.write(` ${e.target}${newline ? `\n` : ''}`);
};
function bench(name, options) {
const config = { name, ...options };
const suite = new Suite(config);
const add = suite.add.bind(suite);
suite.on('error', console.error);
if (argv.run && !new RegExp(argv.run).test(name)) {
suite.add = () => suite;
return suite;
}
console.log(`\n# ${config.name}`);
suite.add = (key, fn, opts) => {
if (typeof fn !== 'function') opts = fn;
add(key, {
onCycle: e => cycle(e),
onComplete: e => cycle(e, true),
fn,
...opts
});
return suite;
};
return suite;
}
/**
* Caching enabled
*/
bench(red('.makeRe') + ' - star')
.add('minimatch', () => mm.makeRe('*'))
.add('picomatch', () => pm.makeRe('*'))
.run();
bench(cyan('.isMatch') + ' - star')
.add('minimatch', () => mm('abc.txt', '*'))
.add('picomatch', () => pm('abc.txt')('*', true, true))
.run();
bench(red('.makeRe') + ' - with star')
.add('minimatch', () => mm.makeRe('c*3.txt'))
.add('picomatch', () => pm.makeRe('c*3.txt'))
.run();
bench(cyan('.isMatch') + ' - with star')
.add('minimatch', () => mm('abc.txt', 'c*3.txt'))
.add('picomatch', () => pm('abc.txt')('c*3.txt', true, true))
.run();
bench(red('.makeRe') + ' - negated')
.add('minimatch', () => mm.makeRe('!c*3.txt'))
.add('picomatch', () => pm.makeRe('!c*3.txt'))
.run();
bench(cyan('.isMatch') + ' - negated')
.add('minimatch', () => mm('abc.txt', '!c*3.txt'))
.add('picomatch', () => pm('abc.txt')('!c*3.txt', true, true))
.run();
bench(red('.makeRe') + ' - globstar')
.add('minimatch', () => mm.makeRe('foo/bar/**/bar.txt'))
.add('picomatch', () => pm.makeRe('foo/bar/**/bar.txt'))
.run();
bench(cyan('.isMatch') + ' - globstar')
.add('minimatch', () => mm('foo/bar.txt', '**/bar.txt'))
.add('picomatch', () => pm('foo/bar.txt')('**/bar.txt', true, true))
.run();
bench(red('.makeRe') + ' - globstar_negated')
.add('minimatch', () => mm.makeRe('!**/bar.txt'))
.add('picomatch', () => pm.makeRe('!**/bar.txt'))
.run();
bench(cyan('.isMatch') + ' - globstar_negated')
.add('minimatch', () => mm('foo/bar.txt', '!**/bar.txt'))
.add('picomatch', () => pm('foo/bar.txt')('!**/bar.txt', true, true))
.run();
bench(red('.makeRe') + ' - braces')
.add('minimatch', () => mm.makeRe('{a,b,c}*.txt'))
.add('picomatch', () => pm.makeRe('{a,b,c}*.txt'))
.run();
bench(cyan('.isMatch') + ' - braces')
.add('minimatch', () => mm('abc.txt', '{a,b,c}*.txt'))
.add('picomatch', () => pm('abc.txt')('{a,b,c}*.txt', true, true))
.run();
bench(red('.makeRe') + ' - multiple stars')
.add('minimatch', () => mm.makeRe('**/*c09.*'))
.add('picomatch', () => pm.makeRe('**/*c09.*'))
.run();
bench(cyan('.isMatch') + ' - multiple stars')
.add('minimatch', () => mm('foo/bar/ac09b.txt', '**/*c09.*'))
.add('picomatch', () => pm('foo/bar/ac09b.txt')('**/*c09.*', true, true))
.run();
bench(red('.makeRe') + ' - no-glob')
.add('minimatch', () => mm.makeRe('abc.txt'))
.add('picomatch', () => pm.makeRe('abc.txt'))
.run();
bench(cyan('.isMatch') + ' - no-glob')
.add('minimatch', () => mm('abc.txt', 'abc.txt'))
.add('picomatch', () => pm('abc.txt')('abc.txt', true, true))
.run();
/**
* Caching disabled
*/
let opts = { nocache: true, normalize: false, unixify: false, strictSlashes: true };
bench(red('.makeRe') + ' star (caching disabled)')
.add('minimatch', () => mm.makeRe('*'))
.add('picomatch', () => pm.makeRe('*', opts))
.run();
bench(cyan('match') + ' star (caching disabled)')
.add('minimatch', () => mm('abc.txt', '*'))
.add('picomatch', () => pm('*', opts)('abc.txt', true, true))
.run();
bench(red('.makeRe') + ' with star (caching disabled)')
.add('minimatch', () => mm.makeRe('c*3.txt'))
.add('picomatch', () => pm.makeRe('c*3.txt', opts))
.run();
bench(cyan('match') + ' with star (caching disabled)')
.add('minimatch', () => mm('abc.txt', 'c*3.txt'))
.add('picomatch', () => pm('c*3.txt', opts)('abc.txt', true, true))
.run();
bench(red('.makeRe') + ' - negated (caching disabled)')
.add('minimatch', () => mm.makeRe('!c*3.txt'))
.add('picomatch', () => pm.makeRe('!c*3.txt', opts))
.run();
bench(cyan('match') + ' - negated (caching disabled)')
.add('minimatch', () => mm('abc.txt', '!c*3.txt'))
.add('picomatch', () => pm('!c*3.txt', opts)('abc.txt', true, true))
.run();
bench(red('.makeRe') + ' - globstar (caching disabled)')
.add('minimatch', () => mm.makeRe('foo/bar/**/bar.txt'))
.add('picomatch', () => pm.makeRe('foo/bar/**/bar.txt', opts))
.run();
bench(cyan('match') + ' - globstar (caching disabled)')
.add('minimatch', () => mm('foo/bar.txt', '**/bar.txt'))
.add('picomatch', () => pm('**/bar.txt', opts)('foo/bar.txt', true, true))
.run();
bench(red('.makeRe') + ' - globstar_negated (caching disabled)')
.add('minimatch', () => mm.makeRe('!**/bar.txt'))
.add('picomatch', () => pm.makeRe('!**/bar.txt', opts))
.run();
bench(cyan('match') + ' - globstar_negated (caching disabled)')
.add('minimatch', () => mm('foo/bar.txt', '!**/bar.txt'))
.add('picomatch', () => pm('!**/bar.txt', opts)('foo/bar.txt', true, true))
.run();
bench(red('.makeRe') + ' - braces (caching disabled)')
.add('minimatch', () => mm.makeRe('{a,b,c}*.txt'))
.add('picomatch', () => pm.makeRe('{a,b,c}*.txt', opts))
.run();
bench(cyan('match') + ' - braces (caching disabled)')
.add('minimatch', () => mm('abc.txt', '{a,b,c}*.txt'))
.add('picomatch', () => pm('{a,b,c}*.txt', opts)('abc.txt', true, true))
.run();
bench(red('.makeRe') + ' - multiple stars (caching disabled)')
.add('minimatch', () => mm.makeRe('**/*c09.*'))
.add('picomatch', () => pm.makeRe('**/*c09.*', opts))
.run();
bench(cyan('match') + ' - multiple stars (caching disabled)')
.add('minimatch', () => mm('foo/bar/ac09b.txt', '**/*c09.*'))
.add('picomatch', () => pm('**/*c09.*', opts)('foo/bar/ac09b.txt', true, true))
.run();
bench(red('.makeRe') + ' - no-glob (caching disabled)')
.add('minimatch', () => mm.makeRe('abc.txt'))
.add('picomatch', () => pm.makeRe('abc.txt', opts))
.run();
bench(cyan('match') + ' - no-glob (caching disabled)')
.add('minimatch', () => mm('abc.txt', 'abc.txt'))
.add('picomatch', () => pm('abc.txt', opts)('abc.txt', true, true))
.run();
|
import React, { Component } from 'react';
import { Modal, Button } from 'react-bootstrap'
class MovieModal extends Component {
state = {
show: false,
}
render() {
// console.log(this.props)
const { title, genres, revenue, release_date, production_companies, imdb_id } = this.props;
const month = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
//revenueC
let revenueValue = revenue
if (revenueValue >= 1000000000) {
revenueValue = (revenueValue / 1000000000).toFixed(2) + " billion"
} else if (revenueValue >= 1000000) {
revenueValue = (revenueValue / 1000000).toFixed(2) + " million"
}
else if (revenueValue >= 1000) {
revenueValue = (revenueValue / 1000).toFixed(2) + " thousand";
}
let rel_date = "";
let companies = "";
let Moviegenres = ""
if (title) {
//date
var parts = release_date.split("-"),
date = new Date(parts[0], parts[1] - 1, +parts[2]);
rel_date = `${date.getDate()} ${month[date.getMonth()]} ${date.getFullYear()}`
//production companies
production_companies.forEach((element) => {
companies = companies + element.name + ", "
});
//genres
genres.forEach((element) => {
Moviegenres = Moviegenres + element.name + ", "
});
}
return (
<>
<Button variant="primary" onClick={() => this.setState({ show: true })}>
More Details
</Button>
<Modal
show={this.state.show}
onHide={() => this.setState({ show: false })}
dialogClassName="modal-90w"
aria-labelledby="example-custom-modal-styling-title"
>
<Modal.Header closeButton>
<Modal.Title id="example-custom-modal-styling-title">
{title}
</Modal.Title>
</Modal.Header>
<Modal.Body>
<p><strong>Release date: </strong>{rel_date}</p>
<p><strong>Revenue: </strong>${revenueValue}</p>
<p><strong>Genres: </strong>{Moviegenres}</p>
<p><strong>Production Companies: </strong>{companies}</p>
<p><span className="link" onClick={() => window.open(`https://www.imdb.com/title/${imdb_id}`, '_blank')}>IMDB Link</span></p>
</Modal.Body>
</Modal>
</>
);
}
}
export default MovieModal;
|
function switchVideo(s) {
let target = document.querySelector("#aVideo");
target.src = "../video/" + s.id + ".mp4";
target.poster = "../video/" + s.id + ".png";
// if(document.getElementsByName="two"){
// document.getElementById("wenzi").innerHTML = "Hello World";
// }
}
var bianzi = document.getElementById("wenzi");
var bian = document.getElementById("our-list").getElementsByTagName("li")
for(i = 0; i < bian.length; i++){
bian[i].addEventListener("click",activateItem);
}
function activateItem() {
bianzi.innerHTML = this.innerHTML;
}
|
'use strict';
var SCREEN_WIDTH = 505,
SCREEN_HEIGHT = 606,
TILE_WIDTH = 101,
TILE_HEIGHT = 81,
PLAYER_SIDE_MOVE = 101,
PLAYER_VERTICAL_MOVE = 83,
PLAYER_HEIGHT = 50,
PLAYER_WIDTH = 40,
PLAYER_TOP_SPACE = 80,
PLAYER_SIDE_SPACE = 40,
ENEMY_HEIGHT = 66,
ENEMY_WIDTH = 97,
ENEMY_TOP_SPACE = 78,
ENEMY_SIDE_SPACE = 2,
GEM_HEIGHT = 35,
GEM_WIDTH = 30,
GEM_TOP_SPACE = 2,
GEM_SIDE_SPACE = 2,
HEART_HEIGHT = 34,
HEART_WIDTH = 34,
HEART_TOP_SPACE = 1,
HEART_SIDE_SPACE = 1,
LEVEL_ONE_GEMS = 5,
LEVEL_TWO_GEMS = 10,
LEVEL_THREE_GEMS = 15,
SAFE = 81,
score = 0;
/**
* Create the enemy object.
* @constructor
* @param {!number} x X cordinates for enemy starting position
* @param {!number} y Y cordinates for the enemy starting position
* @param {!number} h Height of the enemy image
* @param {!number} w Width of the enemy image
* @param {!number} emptyTop Empty space between the top of the actual image and the picture of the enemy
* @param {!number} emptySide Empty space between the side of the actual image and the picture of the enemy
* @param {string} image The image to be used for the enemy
*/
var Enemy = function(x, y, h, w, emptyTop, emptySide, image) {
this.sprite = image;
this.x = x;
this.y = y;
this.h = h;
this.w = w;
this.side = emptySide;
this.top = emptyTop;
this.speed = randomIntFromInterval();
};
/**
* Update the enemy's position using random speeds for movement across screen
* @param {number} dt a time delta between ticks
*/
Enemy.prototype.update = function(dt) {
if(this.x < SCREEN_WIDTH){
this.x += this.speed*dt;
player.collideEnemy();
}else{
this.x = -100;
if(level.level === 1){
this.y = Math.floor(Math.random()*(250-60+1)+60);
}else{
this.y = Math.floor(Math.random()*(320-60+1)+60);
}
this.speed = randomIntFromInterval();
this.x += this.speed*dt;
player.collideEnemy();
}
};
/**
* Draw the enemy on the screen, required method for game
*/
Enemy.prototype.render = function() {
if(Resources.get(this.sprite)){
ctx.drawImage(Resources.get(this.sprite), this.x, this.y);
}
};
/**
* Create the player object
* @constructor
* @param {!number} x X cordinates for player starting position
* @param {!number} y Y cordinates for the player starting position
* @param {!number} h Height of the player image
* @param {!number} w Width of the player image
* @param {!number} emptyTop Empty space between the top of the actual image and the picture of the player
* @param {!number} emptySide Empty space between the side of the actual image and the picture of the player
* @param {string} image The image to be used for the player
*/
var Player = function(x, y, h, w, emptyTop, emptySide, image) {
this.player = image;
this.dead = false;
this.collision = false;
this.x = x;
this.y = y;
this.h = h;
this.w = w;
this.side = emptySide;
this.top = emptyTop;
this.lives = 5;
};
/**
* Draw the player on the screen
*/
Player.prototype.render = function(){
if(Resources.get(this.player)){
ctx.drawImage(Resources.get(this.player), this.x, this.y);
}
};
/**
* Reset the player to starting position after a collision or once the player reaches the water
* Dependin on if collision or not will deduct one life
*/
Player.prototype.reset = function(){
if(this.y + PLAYER_TOP_SPACE > PLAYER_VERTICAL_MOVE){
this.lives --;
heart.update();
}
this.x = TILE_WIDTH * 2;
this.y = TILE_HEIGHT * 5;
this.dead = false;
};
/**
* Find a collision between player and enemy
*/
Player.prototype.collideEnemy = function(){
if(this.dead === false){
for(var i=0; i<allEnemies.length; i++){
if(isCollisionWith(this, allEnemies[i])){
this.dead = true;
setTimeout(this.reset.bind(this), 200);
}
}
}
};
/**
* Find a collision between player and gem
* updates the score then checks to see if more gems should be created based on score
*/
Player.prototype.collideGem = function(){
if(isCollisionWith(this, gem) && gem.allGems === false){
score.update();
if(level.level === 1 && score.gems < LEVEL_ONE_GEMS){
gem.gemUpdate();
}else if(level.level === 2 && score.gems < LEVEL_TWO_GEMS){
gem.gemUpdate();
}else if(level.level === 3 && score.gems < LEVEL_THREE_GEMS){
gem.gemUpdate();
}else{
delete gem.image;
gem.allGems = true;
}
}
};
/**
* Find a collision between player and heart
*/
Player.prototype.collideHeart = function(){
if(safeHeart.oneChance === true){
if(isCollisionWith(this, safeHeart)){
safeHeart.newLife();
}
}
};
/**
* Moves player around the screen
* @param {!number} key Number representing key press to determine player movement
*/
Player.prototype.handleInput = function(key){
switch (key){
case 'left':
if(this.x > TILE_WIDTH - 1){
this.x = this.x - PLAYER_SIDE_MOVE;
}
this.collideGem();
this.collideHeart();
break;
case 'up':
if(this.y + PLAYER_TOP_SPACE > PLAYER_VERTICAL_MOVE){
this.y = this.y - PLAYER_VERTICAL_MOVE;
if(this.y + PLAYER_TOP_SPACE < PLAYER_VERTICAL_MOVE){
score.check();
}
}
this.collideGem();
this.collideHeart();
break;
case 'right':
if(this.x < SCREEN_WIDTH - TILE_WIDTH){
this.x = this.x + PLAYER_SIDE_MOVE;
}
this.collideGem();
this.collideHeart();
break;
case 'down':
if(this.y + PLAYER_TOP_SPACE < SCREEN_HEIGHT - TILE_HEIGHT * 2){
this.y = this.y + PLAYER_VERTICAL_MOVE;
}
this.collideGem();
this.collideHeart();
}
};
/**
* Create Gem and safeHeart objects
* @constructor
* @param {!number} h Height of the object image
* @param {!number} w Width of the object image
* @param {!number} top Empty space between the top of the actual image and the picture of the object
* @param {!number} side Empty space between the side of the actual image and the picture of the object
* @param {string} image The image to be used for the object
* @param {object} shouldRenderFunc A function that decides if object should render
*/
var CollectableObject = function(h, w, top, side, image, shouldRenderFunc){
this.image = image;
this.x = this.xCordinates();
this.y = this.yCordinates();
this.w = w;
this.h = h;
this.top = top;
this.side = side;
this.allGems = false;
this.oneChance = true;
this.shouldRenderFunc = shouldRenderFunc;
};
/**
* Get random x cordinates
*/
CollectableObject.prototype.xCordinates = function(){
var objectX = [25, 126, 227, 328, 429];
var randomX = objectX[Math.floor(Math.random() * objectX.length)];
return randomX;
};
/**
* Get random y cordinates
*/
CollectableObject.prototype.yCordinates = function(){
var objectY = [];
if(level.level === 1){
objectY = [146, 222, 318];
}else{
objectY = [146, 222, 318, 394];
}
var randomY = objectY[Math.floor(Math.random() * objectY.length)];
return randomY;
};
/**
* Render the gem or heart
*/
CollectableObject.prototype.render = function(){
if(this.shouldRenderFunc()){
if(Resources.get(this.image)){
ctx.drawImage(Resources.get(this.image), this.x, this.y);
}
}
};
/**
* Add a new life to player on collision with safeHeart
*/
CollectableObject.prototype.newLife = function(){
if(player.lives <= 1){
player.lives++;
heart.count = player.lives + ' x ';
delete this;
this.oneChance = false;
}
};
/**
* Update gem position ensuring gem does not appear in same space twice
*/
CollectableObject.prototype.gemUpdate = function(){
var oldGemX = this.x;
var oldGemY = this.y;
var match = true;
while(match){
this.x = this.xCordinates();
this.y = this.yCordinates();
if(this.x === oldGemX && this.y === oldGemY){
continue;
}else{
match = false;
}
}
};
/**
* Provides life score for game by creating a heart object and a life score counter
* @constructor
* @param {!number} x X cordinates for heart
* @param {!number} y Y cordinates for heart
* @param {string} image Image to be used for heart
*/
var Heart = function(x, y, image){
this.x = x;
this.y = y;
this.heart = image;
this.count = player.lives + ' x ';
};
/**
* Draw the life count and heart on screen
*/
Heart.prototype.render = function(){
ctx.font = '30px Arial';
ctx.fillStyle = 'white';
if(Resources.get(this.heart)){
ctx.drawImage(Resources.get(this.heart), this.x + 45, this.y - 27);
}
ctx.fillText(this.count, this.x, this.y);
ctx.strokeText(this.count, this.x, this.y);
};
/**
* Update the life count on collision with enemy
*/
Heart.prototype.update = function (){
if(player.lives < 0){
Alert.render('Sorry, you lose');
}else{
this.count = player.lives + ' x ';
}
};
/**
* Tracks the number of gems collected and displays on screen
* @constructor
* @param {!number} x X cordinates for score
* @param {!number} y Y cordinates for score
*/
var Score = function(x, y){
this.x = x;
this.y = y;
this.gems = 0;
this.display = 'Gems: ' + this.gems;
};
/**
* Draw score on screen
*/
Score.prototype.render = function(){
ctx.font = '30px Arial';
ctx.fillStyle = 'white';
ctx.fillText(this.display, this.x, this.y);
ctx.strokeText(this.display, this.x, this.y);
};
/**
* Updates the score on collision with gems
*/
Score.prototype.update = function(){
this.gems ++;
this.display = 'Gems: ' + this.gems;
};
/**
* Checks to see if player has enough gems to win level once in the water
*/
Score.prototype.check = function(){
if(level.level === 1){
level.score(LEVEL_ONE_GEMS);
}else if(level.level === 2){
level.score(LEVEL_TWO_GEMS);
}else{
level.score(LEVEL_THREE_GEMS);
}
};
/**
* Creates Levels for game
* @constructor
* @param {!number} x X cordinates for level indicator on screen
* @param {!number} y Y cordinates for level indicator on screen
*/
var Level = function(x, y){
this.x = x;
this.y = y;
this.level = 1;
this.display = 'Level ' + this.level;
};
/**
* Draw the level number on screen
*/
Level.prototype.render = function(){
ctx.font = '30px Arial';
ctx.fillStyle = 'white';
ctx.fillText(this.display, this.x, this.y);
ctx.strokeText(this.display, this.x, this.y);
};
/**
* Update the level when enough gems are collected and turns safeHeart object back on
*/
Level.prototype.update = function(){
this.level++;
this.display = 'Level ' + this.level;
safeHeart.oneChance = true;
this.render();
};
/**
* Indicates if player has won the level or the game based on score/number of gems collected & if the player has reached the water
* @param {!number} points Number of gems needed to win each level
*/
Level.prototype.score = function(points){
if(score.gems === points && player.y + PLAYER_TOP_SPACE < SAFE){
if(points === LEVEL_THREE_GEMS){
Alert.render('Yay, you won the game!');
}else{
var self = this;
setTimeout(function() {
Alert.render('Yay, you won this level!');
self.update();
score.gems = 0;
score.display = 'Gems: ' + score.gems;
player.reset();
self.enemies();
gem = new CollectableObject (GEM_HEIGHT,
GEM_WIDTH,
GEM_TOP_SPACE,
GEM_SIDE_SPACE,
'images/Gem Blue Small.png',
function() {
return true;
});
gem.render();
}, 500);
}
}else{
setTimeout(player.reset.bind(player), 1000);
}
};
/**
* Adds an extra enemy to screen on level 2
*/
Level.prototype.enemies = function(){
if(this.level === 2){
allEnemies.push(enemyFactory(101, 301));
allEnemies[2].render();
}
};
/**
* Custom alerts were created using code from https://www.developphp.com/video/JavaScript/Custom-Alert-Box-Programming-Tutorial, although it has been modified by me for use in this project
* Creates custom alert boxes
* @constructor
*/
var CustomAlert = function (){
this.winH = window.innerHeight;
this.winW = window.innerWidth;
this.dialogoverlay = document.getElementById('dialogoverlay');
this.startBox = document.getElementById('startingBox');
this.dialogbox = document.getElementById('dialogbox');
};
/**
* Game instructions and start game button
*/
CustomAlert.prototype.instructions = function (){
this.dialogoverlay.style.height = this.winH + 'px';
this.startBox.style.top = 60 + 'px';
this.startBox.style.left = (this.winW / 2) - (450 * 0.5) + 'px';
document.getElementById('instructions').innerHTML = instructions;
document.getElementById('startGame').innerHTML = '<button onclick="start.start()">Start Game!</button>';
};
/**
* Start Game button
*/
CustomAlert.prototype.start = function(){
this.dialogoverlay.style.display = 'none';
this.startBox.style.display = 'none';
};
/**
* Level, game win and lose alerts
* @param {string} dialog What to display in the alert based on if level or game win
*/
CustomAlert.prototype.render = function(dialog){
this.dialogoverlay.style.display = 'block';
this.dialogoverlay.style.height = this.winH + 'px';
this.dialogbox.style.display = 'block';
this.dialogbox.style.top = 200 + 'px';
this.dialogbox.style.left = (this.winW / 2) - (450 * 0.5) + 'px';
document.getElementById('dialogboxbody').innerHTML = dialog;
document.getElementById('dialogboxfoot').innerHTML = '<button onclick="Alert.ok()">OK</button>';
};
/**
* OK button on alerts
*/
CustomAlert.prototype.ok = function(){
this.dialogbox.style.display = 'none';
this.dialogoverlay.style.display = 'none';
if(player.lives < 0 || score.gems === LEVEL_THREE_GEMS){
reload();
}
};
/**
* Instatiate objects
*/
var instructions = 'Collect all the gems and get to the water!<br>Level 1 - collect 5 gems'+
'<br>Level 2 - collect 10 gems'+
'<br>Level 3 - collect 15 gems'+
'<br>Complete all 3 levels to win game!'+
'<br><br>Water and grass are safe but entering the water without all the gems will reset your player.'+
'<br><br>Have fun and good luck!<br><br>Pssst...keep an eye out for the extra lives.';
var allEnemies = [];
var level = new Level(205, 100);
var gem = new CollectableObject(GEM_HEIGHT,
GEM_WIDTH,
GEM_TOP_SPACE,
GEM_SIDE_SPACE,
'images/Gem Blue Small.png',
function() {
return true;
});
var player = new Player(TILE_WIDTH * 2,
TILE_HEIGHT * 5,
PLAYER_HEIGHT,
PLAYER_WIDTH,
PLAYER_TOP_SPACE,
PLAYER_SIDE_SPACE,
'images/char-boy.png');
var heart = new Heart(417, 100, 'images/Heart Small.png');
var score = new Score(10, 100);
var safeHeart = new CollectableObject(HEART_HEIGHT,
HEART_WIDTH,
HEART_TOP_SPACE,
HEART_SIDE_SPACE,
'images/Heart Small Safe.png',
function() {
return player.lives <=1 && this.oneChance === true;
});
var start = new CustomAlert();
var Alert = new CustomAlert();
function initialEnemies(){
allEnemies.push(enemyFactory(1, 60));
allEnemies.push(enemyFactory(202, 140));
for(var i = 0; i < allEnemies.length; i++){
allEnemies[i].render();
}
}
/**
* render objects
*/
start.instructions();
level.render();
gem.render();
initialEnemies();
player.render();
heart.render();
score.render();
/*
* function to handle collision detection for all objects
* @param {object} player The player object
* @param {object} thing The object the player is colliding with
*/
function isCollisionWith(player, thing) {
var playerAdjustedX = player.x + player.side;
var playerAdjustedY = player.y + player.top;
var thingAdjustedX = thing.x + thing.side;
var thingAdjustedY = thing.y + thing.top;
if( playerAdjustedX < thingAdjustedX+ thing.w &&
playerAdjustedX + player.w > thingAdjustedX &&
playerAdjustedY < thingAdjustedY + thing.h &&
playerAdjustedY + player.h > thingAdjustedY) {
return true;
}
}
/**
* Creates the enemies
* @param {!number} x X cordinates for starting position
* @param {!number} y Y cordinates for starting position
*/
function enemyFactory(x, y){
return new Enemy(x,
y,
ENEMY_HEIGHT,
ENEMY_WIDTH,
ENEMY_TOP_SPACE,
ENEMY_SIDE_SPACE,
'images/enemy-bug.png');
}
/**
* function to generate random numbers
*/
function randomIntFromInterval(){
if(level.level === 1){
return Math.floor(Math.random() * (300 - 100 + 1) + 100);
}else if(level.level === 2){
return Math.floor(Math.random()*(400 - 200 + 1) + 200);
}else{
return Math.floor(Math.random()*(500 - 200 + 1) + 200);
}
}
/**
* Reloads page after game loss or win
*/
function reload(){
location.reload();
}
/**
* This listens for key presses and sends the keys to Player.handleInput() method.
*/
document.addEventListener('keyup', function(e) {
var allowedKeys = {
37: 'left',
38: 'up',
39: 'right',
40: 'down'
};
player.handleInput(allowedKeys[e.keyCode]);
});
|
/** When your routing table is too long, you can split it into small modules */
const authRouter = [
{
path: '/signin',
alias: '/login',
component: () => import('@/views/auth/SignIn.vue'),
hidden: true
},
{
path: '/signup',
alias: '/registration',
component: () => import('@/views/auth/SignUp.vue'),
hidden: true
}
];
export default authRouter;
|
//const fs = require('fs')
var path = require('path');
const ObjectsToCsv = require('objects-to-csv')
const xlsxFile = require('read-excel-file/node')
var glob = require("glob")
const folder1 = 'D:/Dropbox/0_isep/TDMEI/tdmei/other/slither_modified/'
const folder2 = 'D:/Dropbox/0_isep/TDMEI/tdmei/other/mythril_modified/'
let names = []
/*fs.readdir(path, function(err, items) {for (var i=0; i<items.length; i++) {console.log(items[i])}});*/
const getPatterns = (folder) => {
//glob("**/*.js", options, function (er, files) { // options is optional
glob(folder+'*', function (er, files) {
console.log('Total files:' +files.length)
for (let i=0; i<files.length; i++) {
//let fileName = path.basename(files[i],'.sol')
let fileName = path.basename(files[i])
fileName = fileName.split('.').slice(0, -1).join('.') // remover extensao
names.push(fileName)
//console.log(fileName)
}
})
}
getPatterns(folder1)
getPatterns(folder2)
function onlyUnique(value, index, self){ //devolve valores unicos
return self.indexOf(value) === index;
}
function foo(arr) { //conta repeticoes de cada item em um array
var a = [], b = [], prev;
arr.sort();
for ( var i = 0; i < arr.length; i++ ) {
if ( arr[i] !== prev ) {
a.push(arr[i]);
b.push(1);
} else {
b[b.length-1]++;
}
prev = arr[i];
}
return [a, b];
}
setTimeout(() => {
//var unique = names.filter(onlyUnique);
var unique = foo(names)
//console.log(unique.length)
//console.log(unique[0][0])
//console.log(unique[1][0])
for (let i=0; i<unique[0].length; i++) {
if (unique[1][i] < 2){
console.log(unique[0][i])
}
}
},1000)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.