text
stringlengths 7
3.69M
|
|---|
const soap = require('soap');
const wsdlUrl = 'https://api.demo.ezidebit.com.au/v3-5/nonpci?singleWsdl';
const custUrl = 'https://api.demo.ezidebit.com.au/v3-5/pci?singleWsdl';
const Payments = require('../models/Payment.js');
const paymentAPI = async function (req, res, next) {
try {
// let Payments = [];
// let CustomerList= [];
// let ScheduledPayments = [];
soap.createClient(wsdlUrl, function (err, soapClient) {
soapClient.GetCustomerList({
DigitalKey: '4E6ACAE2-E4A9-4186-ECDD-E0B9F06785B2',
CustomerStatus: 'ALL',
PageNumber: '1'
}, function (err, result) {
// console.log("GetCustomerList.....", result.GetCustomerListResult.Data.Customer);
CustomerList = result;
});
soapClient.GetScheduledPayments({
DigitalKey: '4E6ACAE2-E4A9-4186-ECDD-E0B9F06785B2'
}, function (err, result) {
// console.log("GetScheduledPayments.....", result.GetScheduledPaymentsResult.Data.ScheduledPayment);
// ScheduledPayments = result;
});
soapClient.GetPayments({
DigitalKey: '4E6ACAE2-E4A9-4186-ECDD-E0B9F06785B2',
PaymentType: 'ALL',
PaymentMethod: 'ALL',
PaymentSource: 'ALL'
}, function (err, result) {
const payments = result.GetPaymentsResult.Data.Payment;
// console.log("GetPayments.....", result.GetPaymentsResult.Data.Payment.length);
(payments.length > 0 ? payments : []).map((data, index) => {
const newPayments = new Payments(data).addPayments();
});
});
// we now have a soapClient - we also need to make sure there's no `err` here.
});
// console.log('Payments',Payments);
// console.log('CustomerList',CustomerList);
// console.log('ScheduledPayments',ScheduledPayments);
} catch (err) {
next(err);
}
};
module.exports = { paymentAPI: paymentAPI };
//Data Format which Received by API CALL
// GetCustomerList[
// {
// AddressLine1: 'Unit 104 28 Warwick Avenue',
// AddressLine2: '',
// AddressPostCode: '3171',
// AddressState: '',
// AddressSuburb: 'SPRINGVALE',
// ContractStartDate: 2019-11-17T18:30:00.000Z,
// CustomerFirstName: 'Nihal',
// CustomerName: 'Ankam',
// Email: 'nihal.ankam@gmail.com',
// EzidebitCustomerID: '1911837',
// MobilePhone: '0410317778',
// PaymentMethod: 'CR',
// PaymentPeriod: 'M',
// PaymentPeriodDayOfMonth: '',
// PaymentPeriodDayOfWeek: '',
// SmsExpiredCard: 'NO',
// SmsFailedNotification: 'YES',
// SmsPaymentReminder: 'NO',
// StatusCode: 'A',
// StatusDescription: '',
// TotalPaymentsFailed: 0,
// TotalPaymentsFailedAmount: 0,
// TotalPaymentsSuccessful: 2,
// TotalPaymentsSuccessfulAmount: 150,
// YourGeneralReference: '',
// YourSystemReference: 'INV0001',
// Country: 'NZ',
// MobileCountryCode: '61',
// PgnRowNo: 1
// },
// ]
// GetScheduledPayments [
// {
// EzidebitCustomerID: '1911837',
// ManuallyAddedPayment: false,
// PaymentAmount: 50,
// PaymentDate: 2019-12-17T18:30:00.000Z,
// YourSystemReference: 'INV0001'
// }
// ]
// GetPayments[
// {
// BankFailedReason: '',
// BankReceiptID: '',
// BankReturnCode: '0',
// CustomerName: 'Ashutoshh Vyass',
// DebitDate: 2019-11-17T21:30:00.000Z,
// EzidebitCustomerID: '1911838',
// InvoiceID: '0',
// PaymentAmount: 100,
// PaymentID: 'SCHEDULED25376510',
// PaymentMethod: 'DR',
// PaymentReference: '',
// PaymentSource: 'SCHEDULED',
// PaymentStatus: 'P',
// ScheduledAmount: 100,
// TransactionFeeClient: 3.3,
// TransactionFeeCustomer: 0,
// YourGeneralReference: '',
// YourSystemReference: 'INV0005'
// },
// ]
|
// Load config
const { database } = require('../config.json')
console.log('Loaded config')
// Setup PG pool
const { Pool } = require('pg')
const db = new Pool(database)
console.log('Created database connection')
// Setup express app
const express = require('express')
const cors = require('cors')
const app = express()
app.use(cors())
// Mount API routes on /api/*
const api = require('./api')(db)
app.use('/api', api)
// Use port depending on environment
const port = process.env.NODE_ENV === 'production' ? process.env.PORT : 8081
// Finally, start app
app.listen(port, () => console.log(`Listening on port ${port}`))
|
import React from 'react';
import './footer.scss';
import classNames from 'classnames';
import {string, bool} from 'prop-types';
import {Link} from '../link/Link';
export class Footer extends React.Component {
static propTypes = {
className: string,
portfolioMode: bool
};
render() {
const {className, portfolioMode} = this.props;
return (
<div className={classNames('footer', portfolioMode ? 'footer_portfolio-mode' : '', className)}>
<div className="footer__container">
<div className="footer__contacts-block">
<div className="footer__title">
Контакты
</div>
<div>
<Link className="footer__link">
+7(915) 682-19-55
</Link>
</div>
<div>
<Link className="footer__link">
furnasteam@gmail.com
</Link>
</div>
</div>
<div className="footer__links-block">
<div className="footer__title">
Ссылки
</div>
<div>
<Link href="https://visa.furnas.ru/"
className="footer__link">
visa.furnas.ru
</Link>
</div>
<Link href="/policy"
className="footer__link">
Политика конфиденциальности
</Link>
</div>
<div className="footer__social-block">
{/*<div className="footer__title">*/}
{/*Social*/}
{/*</div>*/}
</div>
</div>
</div>
);
}
}
|
import React, {Component} from 'react';
import {Link} from 'react-router-dom';
class Exam extends Component {
render() {
return (
<div>
<h1>Exam title</h1>
<p>
Exam description. This should give the user some context about the exam.
Things like how many questions there are in the exam, what is the avarage score of the users,
how long does it take to finish, and so on.
</p>
<ol>
<li>Question 1</li>
<li>Question 2</li>
<li>Question 3</li>
<li>Question 4</li>
<li>Question 5</li>
<li>Question 6</li>
<li>Question 7</li>
<li>Question 8</li>
</ol>
<p>
<Link to="/">Wanna go home?</Link>
</p>
</div>
);
}
}
export default Exam;
|
/*
* Actions describe changes of state in your application
*/
// We import constants to name our Actions' type
import axios from 'axios'
import localStorage from 'localStorage'
import {AUTH_BASE_URL} from '../Config/Constants'
import {axiosInstance} from '../Config/AxiosInstance'
import {FETCH_GROUP_REPOS, FETCH_GROUP_REPOS_FULFILLED, REPO_OPERATION_REJECTED} from './ActionTypes'
/**
* Fetch all repos
*/
export function fetchGroupRepos(payload) {
return function(dispatch) {
dispatch({type: FETCH_GROUP_REPOS});
axios.post(AUTH_BASE_URL + "repos/list", payload, {
withCredentials: true,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': localStorage.getItem('token'),
}
},).then((response) => {
dispatch({type: FETCH_GROUP_REPOS_FULFILLED, payload: response.data,})
}).catch((err) => {
dispatch({type: REPO_OPERATION_REJECTED, payload: err})
})
}
}
|
import React, { useState, useEffect } from "react";
import DeleteSweepIcon from "@material-ui/icons/DeleteSweep";
import Axios from "axios";
const FriendslistAdmin = () => {
const [friends, setFriendsList] = useState([]);
const [messageToDisplay, setMessageToDisplay] = useState();
let pseudonymeUserToDelete;
useEffect(() => {
const fetchData = async () => {
const result = await Axios.get("/friends/friendslist");
setFriendsList(result.data);
};
fetchData();
}, [messageToDisplay]);
const handleClick = (event, pseudonyme) => {
event.preventDefault();
pseudonymeUserToDelete = pseudonyme;
Axios.delete(`/users/delete/${pseudonymeUserToDelete}`)
.then((response) => {
setMessageToDisplay(response.data.message);
})
.catch((err) => {
console.log(err);
});
};
return (
<div>
{friends &&
friends.map((element) => (
<div
style={{
width: "fit-content",
fontSize:'0.7em',
border: "2px black solid",
margin: 30,
backgroundColor: "yellow",
}}
key={element.id}
>
<span> PSEUDONYME : {element.pseudonyme} </span>
<span> PASSWORD : {element.password} </span>
<button
id={element.pseudonyme}
onClick={(event) => {
handleClick(event, element.pseudonyme);
}}
>
<DeleteSweepIcon />
</button>
</div>
))}
{messageToDisplay && <div> {messageToDisplay}</div>}
</div>
);
};
export default FriendslistAdmin;
|
module.exports = {
monthString :monthString,
getDateTimeFromMySql: getDateTimeFromMySql,
getNiceMonth : getNiceMonth,
getNiceday : getNiceday,
dayReportSql : dayReportSql,
formDayStr : formDayStr,
arrToTableRow : arrToTableRow
}
//==============================================================================
function monthString(month){
const monthNames = ["Января", "Февраля", "Марта", "Апреля", "Мая", "Июня",
"Июля", "Августа", "Сентября", "Октября", "Ноября", "Декабря"
];
return monthNames[month - 1];
}
//==============================================================================
function getDateTimeFromMySql (dt) {
//return dt.toISOString().slice(0, 19).replace('T', ' ');
return (new Date ((new Date((new Date(new Date(dt))).toISOString() )).getTime() - ((new Date()).getTimezoneOffset()*60000))).toISOString().slice(0, 19).replace('T', ' ');
}
//==============================================================================
function getNiceMonth(month) {
return month > 9 ? "" + month : "0" + month;
}
//==============================================================================
function getNiceday(day) {
return day > 9 ? "" + day : "0" + day;
}
//==============================================================================
function dayReportSql(day, month , year) {
const startDay = formDayStr(day, month , year);
return `SELECT dt, w_38, q_39, T_41, T_42, P_19, P_18, T_10, P_36 FROM eco2.hr3 where dt between '${startDay}' and DATE_ADD('${startDay}', INTERVAL 23 hour)`;
}
//========================================================================================
function formDayStr(day = 20, month = 1, fullyear = 2019) {
return `${fullyear}-${getNiceMonth(month)}-${getNiceday(day)} 08:00:00`;
}
//==============================================================================
function arrToTableRow(arr) {
const row = arr.map( record => {
return "<tr>" + record.map(el => "<td>" + el + "</td>").join('') + "</tr>";
});
return row.join('');
}
//==============================================================================
|
define(['angular'], function (angular) {
'use strict';
/**
* @ngdoc function
* @name kvmApp.controller:ModalInstanceCtrlCtrl
* @description
* # ModalInstanceCtrlCtrl
* Controller of the kubernetesApp
*/
angular.module('kvmApp.controllers.ModalInstanceCtrl', [])
.controller('ModalInstanceCtrl', function ($scope, $uibModalInstance, item, title) {
this.awesomeThings = [
'HTML5 Boilerplate',
'AngularJS',
'Karma'
];
$scope.item = item;
$scope.title = title;
$scope.Save = function () {
$uibModalInstance.save($scope.item);
};
$scope.Update = function () {
$uibModalInstance.Update($scope.item);
};
$scope.Updateapp = function () {
$uibModalInstance.Updateapp($scope.item);
};
$scope.Delete = function () {
$uibModalInstance.Delete($scope.item);
};
$scope.Start = function () {
$uibModalInstance.Start($scope.item);
};
$scope.Stop = function () {
$uibModalInstance.Stop($scope.item);
};
$scope.Restart = function () {
$uibModalInstance.Restart($scope.item);
};
$scope.CreateSnapshot = function () {
$uibModalInstance.CreateSnapshot($scope.item);
};
$scope.mount = function () {
$uibModalInstance.mount($scope.item);
};
$scope.umount = function () {
$uibModalInstance.umount($scope.item);
};
$scope.createdisksnap = function () {
$uibModalInstance.createdisksnap($scope.item);
};
$scope.savemember = function () {
$uibModalInstance.savemember($scope.item);
};
$scope.showmember = function () {
$uibModalInstance.showmember($scope.item);
};
$scope.cancel = function () {
$uibModalInstance.dismiss('cancel');
};
});
});
|
var APP = this.APP || {};
(function (A, $) {
var data,
sandbox;
var matchStr = function (str, q) {
var words = q.split(' ');
for (var i = 0; i < q.split.length; i += 1) {
if (str && words[i]) {
if ( str.toLowerCase().indexOf(words[i].toLowerCase()) !== -1) {
return true;
}
}
}
return false;
};
var matchPkg = function (pckg, q) {
return matchStr(pckg.name, q);
};
var matchObj = function (func, q) {
for (var i in func) {
if ( typeof func[i] === 'string') {
if (matchStr(func[i], q)) {
return true;
}
}
if ( typeof func[i] === 'object') {
if (matchObj(func[i], q)) {
return true;
}
}
}
return false;
};
var removeUnmatching = function(pckg, q) {
var methods = [];
if (pckg.methods) {
for (var i = 0; i < pckg.methods.length; i += 1) {
if (matchObj(pckg.methods[i], q)) {
methods.push(pckg.methods[i]);
}
}
}
pckg.methods = methods;
return methods.length !== 0;
};
var run = function (q) {
var dataCpy = $.extend(true, [], data);
var pcks = [];
for(var i = 0; i < dataCpy.length; i += 1) {
if (matchStr(dataCpy[i].name, q)) {
pcks.push(dataCpy[i]);
} else {
if (removeUnmatching(dataCpy[i], q)) {
pcks.push(dataCpy[i]);
}
}
}
return pcks;
};
var isArray = function(v) {
return v ? v.constructor.prototype === Array.prototype : false;
};
var isString = function(v) {
return typeof v === 'string';
};
var isObject = function(v) {
return typeof v === 'object';
};
var searchString = function(str, q) {
var i, list;
if (!q) {
return str;
}
list = q.split(' ');
for (i in list) {
if (str.indexOf(list[i]) !== -1) {
return str;
}
}
return false;
};
var searchObject = function(obj, q) {
var i, v,
rs,
match = false,
r = {};
for (i in obj) {
v = obj[i];
if (obj.hasOwnProperty(i)) {
if (isString(v)) {
if (searchString(v, q)) {
return obj;
} else {
r[i] = v;
}
} else if (isArray(v)) {
rs = searchArray(v, q);
} else if (isObject(v)) {
rs = searchObject(v, q);
}
if (rs) {
match = true;
r[i] = rs;
rs = null;
}
}
}
if (match) {
return r;
} else {
return false;
}
};
var searchArray = function(array, q) {
var i, v, r = [];
for (i in array) {
v = search(array[i], q);
if (v) {
r.push(v);
}
}
return r;
};
var search = function search(n, q) {
var r;
if (isArray(n)) {
r = searchArray(n,q);
} else if (isString(n)) {
r = searchString(n,q);
} else if (isObject(n)) {
r = searchObject(n,q);
}
return r;
};
var index = function createIndex(n) {
var i, index = [],
split,
add = function (el) {
if (index.indexOf(el) === -1) {
index.push(el);
}
};
if (isString(n)) {
split = n.split(/\W+/g);
for (i in split) {
add(split[i]);
}
} else {
for (i in n) {
createIndex(n[i]).map(add);
}
}
return index;
};
A.search = {
create: function (dt, sndbx) {
data = dt;
sandbox = sndbx;
return Object.create(this, {});
},
init: function () {
sandbox.hub.subscribe('autocomplete-focus',
function(d) {
var pcks = run(d.query);
sandbox.hub.publish('new-data', { data: pcks });
},
function (error) {
console.log(error);
}
);
sandbox.hub.subscribe('clear-search', function () {
sandbox.hub.publish('new-data', { data: data });
});
},
search: search,
index: index
};
}(APP, jQuery));
|
'use strict'
const express = require('express');
const app = express();
const path = require('path');
//Middleware to define folder for static files
app.use(express.static('public'));
app.get('/', (req,res) => {
res.render(index.html);
});
app.listen('3000', () => {
console.log('server is listen on port 3000');
});
|
export default {
'.black': { color: '#2b2b2b' },
'.white': { color: 'white' },
'.critical': { color: 'red' },
'.positive': { color: 'green' },
'.secondary': { color: '#777' },
'.formAccent': { color: 'navy' },
'.neutral': { composes: 'black' }
};
|
/**
* Created by wen on 2016/8/19.
*/
import React, { PropTypes,Component } from 'react';
import s from './Radio.css';
import ClassName from 'classnames';
class Radio extends Component {
constructor(props) {
super(props);
this.state = {};
}
static contextTypes = {
insertCss: PropTypes.func.isRequired,
};
static propTypes = {
isActivate: PropTypes.string.isRequired,//是否被激活
underLine: PropTypes.string.isRequired,//是否有下划线
clickRadio: PropTypes.func.isRequired,//点击事件
};
componentWillMount() {
const { insertCss } = this.context;
this.removeCss = insertCss(s);
}
componentWillUnmount() {
this.removeCss();
}
handlerClick (){
this.props.clickRadio()
}
render() {
return (
<div onClick={(e) => this.handlerClick(e)} className={ this.props.underLine === 'on' ? ClassName([s.radio,s.flex,s.flexrow,s.borderBottom]) : ClassName([s.radio,s.flex,s.flexrow])}>
<div className={ClassName([s.itemLeft])}><span className={this.props.isActivate == 'on' ? ClassName([s.checkBox,s.selected]) : ClassName([s.checkBox])}> </span></div>
<div className={ClassName([s.flex1,s.itemRight])}>{this.props.children}</div>
</div>
);
}
}
export default Radio;
|
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
// Connection URL
const url = 'mongodb://localhost:27017';
// Database Name
const dbName = '3a';
const client = new MongoClient(url, { useNewUrlParser: true });
// Use connect method to connect to the Server
client.connect(function(err) {
assert.equal(null, err);
console.log("Connected successfully to server");
const db = client.db(dbName);
insertDocuments(db, function() {
client.close();
});
removeDocument(db, function(){
client.close();
})
});
const insertDocuments = async function(db, callback) {
// Get the documents collection
const collection = db.collection('documents');
// Insert some documents
await collection.insertMany([
{a : 1}, {a : 2}, {a : 3}
], function(err, result) {
assert.equal(err, null);
assert.equal(3, result.result.n);
assert.equal(3, result.ops.length);
console.log("Inserted 3 documents into the collection");
callback(result);
});
}
const removeDocument = async function(db, callback) {
// Get the documents collection
const collection = db.collection('documents');
// Delete document where a is 3
await collection.deleteOne({ a : 3 }, function(err, result) {
assert.equal(err, null);
assert.equal(1, result.result.n);
console.log("Removed the document with the field a equal to 3");
callback(result);
});
}
|
// function globalFunction(x) {
// return function outerFunction(y) {
// return function innerFunction(z) {
// return x + y + z;
// };
// };
// }
// let instance1 = globalFunction(2);
// var instance2 = instance1(3);
// console.log(instance2());
// let count = 0;
// let interval = setInterval(function () {
// console.log(count);
// count++;
// }, 100);
// setTimeout(function () {
// clearInterval(interval);
// interval = setInterval(function () {
// console.log(count);
// count--;
// if (count < 0) clearInterval(interval);
// });
// }, 500);
// function mySetInterval(callback, time) {
// let interval = { working: true };
// function setter() {
// callback();
// if (interval.working) setTimeout(setter, time);
// }
// setTimeout(setter, time);
// return interval
// }
// let i = mySetInterval(function () {
// console.log("Hi");
// }, 100);
// // to clear interval
// setTimeout(function () {
// i.working = false;
// },500)
let a = ["a", "b"]
a[2] = a
function f(a) {
a = a[2]
console.log(a);
let n = Array("a", "b")
console.log(a[2] = n);
console.log(a);
console.log(n);
a = n;
console.log(a);
}
console.log(a);
f(a)
console.log(a);
|
define(['frame'], function (ngApp) {
'use strict'
ngApp.provider.controller('ctrlDoc', [
'$scope',
'$location',
'http2',
'facListFilter',
'CstNaming',
function ($scope, $location, http2, facListFilter, CstNaming) {
var _oMission, _oCriteria, hash
if ((hash = $location.hash())) {
$scope.matterType = hash
} else {
$scope.matterType = ''
}
var aUnionMatterTypes
aUnionMatterTypes = []
CstNaming.matter.docOrder.forEach(function (name) {
aUnionMatterTypes.push({
name: name,
label: CstNaming.matter.doc[name],
})
})
$scope.unionMatterTypes = aUnionMatterTypes
$scope.unionType = ''
$scope.criteria = _oCriteria = {
pid: 'ALL',
filter: {},
}
$scope.filter = facListFilter.init(function () {
$scope.list()
}, _oCriteria.filter)
$scope.addArticle = function () {
var url = '/rest/pl/fe/matter/article/create?mission=' + _oMission.id,
config = {
proto: {
title: _oMission.title + '-单图文',
},
}
http2.post(url, config).then(function (rsp) {
location.href =
'/rest/pl/fe/matter/article?id=' +
rsp.data.id +
'&site=' +
_oMission.siteid
})
}
$scope.addLink = function () {
var url = '/rest/pl/fe/matter/link/create?mission=' + _oMission.id
url += '&title=' + _oMission.title + '-链接'
http2.get(url).then(function (rsp) {
location.href =
'/rest/pl/fe/matter/link?id=' +
rsp.data.id +
'&site=' +
_oMission.siteid
})
}
$scope.addChannel = function () {
var url = '/rest/pl/fe/matter/channel/create?mission=' + _oMission.id
url += '&title=' + _oMission.title + '-频道'
http2.get(url).then(function (rsp) {
location.href =
'/rest/pl/fe/matter/channel?id=' +
rsp.data.id +
'&site=' +
_oMission.siteid
})
}
$scope.addMatter = function (matterType) {
$scope['add' + matterType[0].toUpperCase() + matterType.substr(1)]()
}
$scope.openMatter = function (matter, subView) {
var url = '/rest/pl/fe/matter/',
type = matter.type || $scope.matterType,
id = matter.id
url += type
if (subView) {
url += '/' + subView
}
switch (type) {
case 'article':
case 'link':
case 'channel':
location.href = url + '?id=' + id + '&site=' + _oMission.siteid
break
}
}
$scope.removeMatter = function (evt, matter) {
var type = matter.type || $scope.matterType,
id = matter.id,
title = matter.title,
url = '/rest/pl/fe/matter/'
evt.stopPropagation()
if (window.confirm('确定删除:' + title + '?')) {
switch (type) {
case 'link':
case 'article':
case 'channel':
url += type + '/remove?id=' + id + '&site=' + _oMission.siteid
break
}
http2.get(url).then(function (rsp) {
$scope.matters.splice($scope.matters.indexOf(matter), 1)
})
}
}
$scope.copyMatter = function (evt, matter) {
var type = matter.type || $scope.matterType,
id = matter.id,
url = '/rest/pl/fe/matter/'
evt.stopPropagation()
switch (type) {
case 'article':
url +=
type +
'/copy?id=' +
id +
'&site=' +
_oMission.siteid +
'&mission=' +
_oMission.id
break
case 'link':
alert('正在建设中……')
return
break
}
http2.get(url).then(function (rsp) {
location.href =
'/rest/pl/fe/matter/' +
type +
'?site=' +
_oMission.siteid +
'&id=' +
rsp.data.id
})
}
$scope.togglePublic = function (oMatter) {
var isPublic, url
if (oMatter.is_public) {
isPublic = oMatter.is_public === 'Y' ? 'N' : 'Y'
}
url =
'/rest/pl/fe/matter/mission/matter/update?site=' +
_oMission.siteid +
'&id=' +
_oMission.id +
'&matterType=' +
oMatter.type +
'&matterId=' +
oMatter.id
http2.post(url, { is_public: isPublic }).then(function (rsp) {
oMatter.is_public = isPublic
})
}
$scope.list = function () {
var url, data, matterType
data = {}
if (_oCriteria.filter.by === 'title') {
data.byTitle = _oCriteria.filter.keyword
}
matterType = $scope.matterType
url = '/rest/pl/fe/matter/mission/matter/list?id=' + _oMission.id
if (matterType === '') {
url += '&matterType=doc'
} else {
url += '&matterType=' + matterType
}
http2.post(url, data).then(function (rsp) {
rsp.data.forEach(function (matter) {
matter._operator = matter.modifier_name || matter.creater_name
matter._operateAt = matter.modifiy_at || matter.create_at
})
$scope.matters = rsp.data
})
}
$scope.$watch('mission', function (nv) {
if (!nv) return
_oMission = nv
$scope.$watch('unionType', function (nv) {
var aUnionType
if (nv !== undefined) {
$scope.matterType = nv
$scope.list()
}
})
})
},
])
})
|
var combineReducers = Redux.combineReducers;
var rootReducer = combineReducers({
todos: todos
});
|
var express = require('express');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var sixlbrRoutes = require('./getSixlbrRoutes');
var request = require('request');
var flatten = require('flat');
var routes = { };
var routesNodeID = {};
var wigwagnodes = {};
var nwStats = {};
var prev_nwStats = {};
var baseline = {};
setInterval(function() {
sixlbrRoutes.getRoutes().then(function(a) {
var temp = a.SixlbrMonitor1.response.result;
if(Object.keys(routes).length != Object.keys(temp).length) {
ddb.get('wigwagdevice:node').then(function(nodes) {
sixlbrRoutes.updateWigwagNodes(nodes);
// console.log('NODES: ', wigwagnodes);
});
routes = {};
routesNodeID = {};
console.log("salkdjfalksjdflkajsdlkfjalksdjflkajds");
}
if(wigwagnodes != {}) {
routes = temp;
console.log('****************************************************');
Object.keys(routes).forEach(function(node) {
// console.log('node: ', node);
// console.log('wigwagnodes: ', wigwagnodes);
sixlbrRoutes.getNodeIdFromIP(node.substring(6)).then(function(childId) {
// console.log('node: ', childId + ' rank: ', routes[node].rank);
routesNodeID[childId] = { 'parentId': '', 'ipaddr': '', 'data': ''};
sixlbrRoutes.getNodeIdFromIP(routes[node]['nexthop'].substring(6)).then(function(parentId) {
routesNodeID[childId].parentId = parentId;
routesNodeID[childId].ipaddr = node;
routesNodeID[childId].data = routes[node];
// console.log(routesNodeID);
});
});
});
}
});
}, 1000);
var it = 0;
setInterval(function() {
// routes = { };
// routesNodeID = {};
it++;
sixlbrRoutes.getNetworkStats().then(function(stats) {
if(Object.keys(baseline).length == 0) {
baseline = stats.SixlbrMonitor1.response.result;
console.log('baseline: ', baseline)
console.log('nwStats: ', nwStats);
} else {
Object.keys(stats.SixlbrMonitor1.response.result).forEach(function(key) {
if(typeof nwStats[key] == 'undefined') {
nwStats[key] = 0;
prev_nwStats[key] = 0;
}
nwStats[key] = ( (stats.SixlbrMonitor1.response.result[key] - baseline[key]) - prev_nwStats[key]) ;
prev_nwStats[key] = (stats.SixlbrMonitor1.response.result[key] - baseline[key]);
})
}
});
}, 1000);
var app = express();
// app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname)));
app.get('/routes', function(req, res) {
// console.log('routes: ', routesNodeID);
res.status(200).send(routesNodeID);
})
app.get('/sixlbrConfig', function(req, res) {
var opts;
sixlbrRoutes.getSixlbrConfig().then(function(a) {
opts = a.SixlbrMonitor1.response.result;
console.log(opts);
res.status(200).send(opts);
})
})
app.get('/networkStats', function(req, res) {
res.status(200).send(nwStats);
})
app.post('/updateSixlbrConfig', function(req, res) {
console.log('got updated values: ', req.body);
sixlbrRoutes.setSixlbrConfig(req.body).then(function() {
console.log('setSixlbrConfig successful');
res.status(200).send();
});
})
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
sixlbrRoutes.start().then(function() {
app.listen(6060);
})
module.exports = app;
|
const express = require('express');
const indexController = {
showHome: (req, res) => {
res.render('home');
},
showAgenda: (req, res) => {
res.render('agenda-mentor');
},
showMentores: (req, res) => {
res.render('mentores');
},
};
module.exports = indexController;
|
import React, {PropTypes} from 'react';
import BuildContainer from '../components/build/BuildContainer.jsx';
const Project = ({params}) => (
<div>
<BuildContainer params={params} />
</div>
);
Project.propTypes = {
params: PropTypes.object.isRequired
};
export default Project;
|
//lets require/import the mongodb native drivers.
var mongodb = require('mongodb');
var assert = require("assert");
//We need to work with "MongoClient" interface in order to connect to a mongodb server.
var MongoClient = mongodb.MongoClient;
// Connection URL. This is where your mongodb server is running.
var url = 'mongodb://localhost:27017/inmobi';
var AdTags = function(db, callback) {
var cursor =db.collection('addstore').find();
cursor.each(function(err, doc) {
assert.equal(err, null);
if (doc != null) {
console.dir(doc);
} else {
callback();
}
});
};
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
AdTags(db, function() {
db.close();
});
});
|
const { MessageEmbed } = require("discord.js");
const Color = {
info: "#2F3136",
warn: "YELLOW",
error: "RED",
};
const CreateEmbed = (color, message) => {
const embed = new MessageEmbed().setColor(Color[color]);
if (message) embed.setDescription(message);
return embed;
};
module.exports = { CreateEmbed };
|
export const INITIAL_STATE = {
username: '',
password: ''
}
export const CHANGE_USERNAME = 'CHANGE_USERNAME'
export const CHANGE_PASSWORD = 'CHANGE_PASSWORD'
export const changeUsername = username => ({
type: CHANGE_USERNAME,
username
})
export const changePassword = password => ({
type: CHANGE_PASSWORD,
password
})
const reducer = (state, action) => {
const { type, username, password } = action
switch(type) {
case CHANGE_USERNAME:
return {
...state,
username
}
case CHANGE_PASSWORD:
return {
...state,
password
}
default:
return state
}
}
export default reducer
|
'use strict';
const multimatch = require('multimatch');
const unique = require('uniq');
const path = require('path');
module.exports = function(opts) {
opts = normalize(opts);
const keys = Object.keys(opts);
const match = matcher(opts);
return (files, metalsmith, done) => {
const metadata = metalsmith.metadata();
const textContents = metadata.textContents || (metadata.textContents = {});
/**
* Find the files in each collection.
*/
Object.keys(files).forEach((file) => {
const data = files[file];
data.path = file;
match(file, data).forEach((key) => {
if (key && keys.indexOf(key) < 0) {
opts[key] = {};
keys.push(key);
}
let text = data.contents.toString().trim();
if (path.extname(file) === '.js') {
while (text.indexOf('/*') === 0) {
text = text.substr(text.indexOf('*/') + 2).trim();
}
}
textContents[key] = textContents[key] || {};
textContents[key][file.replace(/\\/g, '/')] = text;
delete files[file];
});
});
/**
* Ensure that a default empty collection exists.
*/
keys.forEach((key) => {
textContents[key] = textContents[key] || {};
});
done();
};
};
function normalize(options) {
options = options || {};
for (const key in options) {
const val = options[key];
if (typeof val === 'string') { options[key] = {pattern: val}; }
if (val instanceof Array) { options[key] = {pattern: val}; }
}
return options;
}
function matcher(cols) {
const keys = Object.keys(cols);
const matchers = {};
keys.forEach((key) => {
const opts = cols[key];
if (!opts.pattern) {
return;
}
matchers[key] = {
match(file) {
return multimatch(file, opts.pattern);
}
};
});
return function(file, data) {
const matches = [];
for (const key in matchers) {
const m = matchers[key];
if (m.match(file).length) {
matches.push(key);
}
}
return unique(matches);
};
}
|
function trazi_jedan() {
var req = new XMLHttpRequest();
req.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
{
document.getElementById('rezultati').innerHTML = this.responseText;
}
}
var ime = document.getElementById('trazi_ime1').value;
var username = document.getElementById('trazi_username1').value;
req.open("GET","trazi_ime_i_username.php?ime_p=" + ime + "&username_p=" + username, true);
req.send();
}
function trazi_sve()
{
var req = new XMLHttpRequest();
req.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
{
document.getElementById('rezultati').innerHTML = this.responseText;
}
}
var ime = document.getElementById('trazi_ime1').value;
var username = document.getElementById('trazi_username1').value;
req.open("GET","trazi_ime_i_username.php?trazi=1&ime_p=" + ime + "&username_p=" + username, true);
req.send();
}
|
module.exports = function(settings) {
if(settings) {
return $.lib.concat(settings.options.path)
} else {
return $.lib.through2.obj()
}
}
|
var MAX = 10;
$(document).ready(function() {
initMainContentTabs();
//On Click Event
$("#mainContentTabs li").click(changeMainContentTab);
// Now define one more function which is used to fadeout the
// fade layer and popup window as soon as we click on fade layer
$('#fade').click(close);
$('#cancel').click(close);
$("#create_new").click(createNew);
});
function changePage() {
if($(this).attr("class").indexOf("active") !== -1)
return;
parentId = $(this).parent().get(0).id;
$("#" + parentId+" a").removeClass("active"); //Remove any "active" class
$(this).addClass("active"); //Add "active" class to selected tab
getData(parentId.substring(0, parentId.length - "PageList".length), ($(this).html() - 1)*MAX);
}
function changeMainContentTab() {
if($(this).attr("class").indexOf("active") !== -1)
return;
$("#mainContnentTabs.tabs li").removeClass("active"); //Remove any "active" class
$(this).addClass("active"); //Add "active" class to selected tab
$(".tab_content").hide(); //Hide all tab content
var activeHref = $(this).find("a").attr("href"); //Find the href attribute value to identify the active tab + content
$(activeHref).fadeIn(); //Fade in the active ID content
getData(activeHref.substring(1, activeHref.length), 0);
$("#create_new").data("current-table", activeHref);
return false;
}
function initMainContentTabs() {
//When page loads...
$(".tab_content").hide(); //Hide all content
active = $("#mainContentTabs li:first"); //Activate first tab
active.addClass("active").show();
activeHref = $(active).find("a").attr("href");
$("#create_new").data("current-table", activeHref);
$(".tab_content:first").show(); //Show first tab content
tableName = activeHref.substring(1, activeHref.length);
getDataCount(tableName);
getData(tableName, 0);
}
function getData(tableName, from) {
$.ajax({
url : "./get"+tableName,
type : "POST",
data : {from : from, max : MAX},
success: function(data){
tableContent[tableName] = data;
initTable(tableName);
}
});
}
function getDataCount(tableName) {
$.ajax({
url : "./get"+tableName+"Num",
type : "POST",
success: function(num){
pageNum = num/MAX + (num%MAX == 0 ? 0 : 1);
initPages(tableName, pageNum);
$("#" +tableName+"PageList a").click(changePage);
}
});
}
function initPages(tableName, num) {
result = " <a class=\"button active\">1</a>";
for(var i = 2; i <= num; i++) {
result += " <a class=\"button\">"+i+"</a>";
}
$("#"+tableName+"PageList").html(result);
}
function createNew() {
showPopup($("#create_new").data("current-table")+ "Creator");
}
function close(){
// Add markup ids of all custom popup box here
$('#fade ,' + $("#create_new").data("current-table")+ "Creator").fadeOut();
return false;
}
function showPopup(popupid) {
// Now we need to popup the marked which belongs to the rel attribute
// Suppose the rel attribute of click link is popuprel then here in below code
// #popuprel will fadein
$(popupid).fadeIn();
// append div with id fade into the bottom of body tag
// and we allready styled it in our step 2 : CSS
$('#fade').css({'filter' : 'alpha(opacity=80)'}).fadeIn();
// Now here we need to have our popup box in center of
// webpage when its fadein. so we add 10px to height and width
var popuptopmargin = ($(popupid).height() + 10) / 2;
var popupleftmargin = ($(popupid).width() + 10) / 2;
// Then using .css function style our popup box for center allignment
$(popupid).css({
'margin-top' : -popuptopmargin,
'margin-left' : -popupleftmargin
});
}
function initTable(elementName) {
result = "";
for (var i = 0; i < tableContent[elementName].length; i++) {
result += "<tr>";
for (var j = 0; j < tableContent[elementName][i].length; j++)
result += "<td>" + tableContent[elementName][i][j] + "</td>";
result += "<td><a class=\"action\">Edit</a>/<a class=\"action\">Remove</a></td>";
result += "</tr>";
}
result += "</tr>";
$("#" + elementName + "> div > table > tbody").html(result);
}
|
import { eq, pick } from 'lodash';
import * as EDITOR from '../actions/editor';
import * as MODE from '../constants/Mode';
import * as SHAPE from '../constants/Shape';
import { StateStorage } from './state-storage';
const storage = new StateStorage(
'nekoboard/editor',
{
mode: MODE.DEFAULT,
shape: SHAPE.DEFAULT,
fill: false,
fillColor: '#ffffff',
fontSize: 16,
stroke: true,
strokeColor: '#000000',
strokeWidth: 1,
styleHistory: [],
edit: null,
snap: true,
ox: 0,
oy: 0,
},
[
'mode',
'shape',
'fill',
'fillColor',
'fontSize',
'stroke',
'strokeColor',
'strokeWidth',
'styleHistory',
'snap',
]
);
const StyleKeys = [
'fill',
'fillColor',
'fontSize',
'stroke',
'strokeColor',
'strokeWidth',
];
export const editor = storage.apply((state, action) => {
// eslint-disable-next-line default-case
switch (action.type) {
case EDITOR.SET_MODE:
return {
...state,
mode: action.mode,
};
case EDITOR.SET_SHAPE:
return {
...state,
shape: action.shape,
};
case EDITOR.PUSH_HISTORY:
if (
state.styleHistory.length > 0 &&
eq(pick(state, StyleKeys), state.styleHistory[0])
) return state;
return {
...state,
styleHistory: [
pick(state, StyleKeys),
...state.styleHistory,
].slice(0, 10),
};
case EDITOR.SET_STYLE:
return {
...state,
...pick(action, StyleKeys),
};
case EDITOR.SET_SNAP:
return {
...state,
snap: action.snap,
};
case EDITOR.BEGIN_EDIT:
if (state.mode === MODE.EDIT) {
// eslint-disable-next-line default-case
switch (state.shape) {
case SHAPE.TEXT:
case SHAPE.PIECE:
return state;
}
} else if (state.mode === MODE.ERASE || !action.id) {
return state;
}
return {
...state,
edit: action.id,
...pick(action, ['ox', 'oy']),
};
case EDITOR.END_EDIT:
case EDITOR.CANCEL_EDIT:
return {
...state,
edit: null,
};
}
return state;
});
|
var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var passport = require('passport');
var FacebookStrategy = require('passport-facebook').Strategy;
var expressSession = require('express-session');
mongoose.Promise = global.Promise;
// For development purposes, uncomment this line:
// mongoose.connect('mongodb://localhost/beers');
// For deployment purposes uncomment this line:
mongoose.connect(process.env.MONGOLAB_PUCE_URI ||'mongodb://localhost/beers');
var Beer = require("./models/BeerModel");
var Review= require('./models/ReviewModel');
var app = express();
// for fb authenticate
app.use(expressSession({ secret: 'mySecretKey' }));
app.use(passport.initialize());
app.use(passport.session());
app.use(bodyParser.json()); // This is the type of body we're interested in
app.use(bodyParser.urlencoded({extended: false}));
app.use(express.static('public'));
app.use(express.static('node_modules'));
// Change the callbackURL you see below
// every time that youre developing locally
// vs deploying to heroku domain
passport.use(new FacebookStrategy({
clientID: '1886152074941466',
clientSecret: '1d9904d87a3e1b3a0b46692cadcc26ef',
// For development
// callbackURL: "http://localhost:8000/auth/facebook/callback",
// For Deployment
callbackURL: "https://letsamp.herokuapp.com/auth/facebook/callback",
profileFields: ['id', 'displayName', 'photos', 'email']
},
function(accessToken, refreshToken, profile, done) {
console.log("accessToken:");
console.log(accessToken);
console.log("refreshToken:");
console.log(refreshToken);
console.log("profile:");
console.log(profile);
return done(null, profile);
}
));
// used to serialize the user for the session
passport.serializeUser(function(user, done) {
done(null, user);
});
// used to deserialize the user
passport.deserializeUser(function(user, done) {
done(null, user);
});
// To see just the JSON that facebook returns back,
// simply uncomment this line
// route for showing the profile page
app.get('/profile', function(req, res) {
console.log(req.user);
res.render('profile.ejs', {
user: req.user // get the user out of session and pass to template
});
});
app.get('/auth/facebook/callback',
passport.authenticate('facebook', {
successRedirect : '/profile',
failureRedirect : '/facebookCanceled'
}));
app.get('/profile', function(req, res) {
res.json(req.user);
});
app.get('/facebookCanceled', function(req, res) {
res.send("fail!");
});
// app.use('/userPage', facebookAuthenticate(req, res, next));
// app.get('/userPage', fucntion(req, res){
// res.send('userPage.html')
// })
app.get('/', function (req, res) {
res.send("You are inside the fullstack project")
});
app.get('/beers', function (req, res) {
Beer.find(function (error, beers) {
res.send(beers);
});
});
app.post('/beers', function (req, res, next) {
console.log(req.body);
var beer = new Beer(req.body);
beer.save(function(err, beer) {
if (err) { return next(err); }
res.json(beer);
});
});
app.delete('/beers/:id', function (req, res) {
res.send('DELETE request to homepage');
Beer.findByIdAndRemove(req.params.id, function(err) {
if (err) throw err;
// we have deleted the person
console.log('Person deleted!');
});
});
app.post('/beers/:id/reviews/', function(req, res, next) {
// req === {
// date: '1/12/16',
// body: {name: "Daniel", text: "gross"},
// params: {id: 123}
// }
// req.params.id === 123
// req.body === {name: "Daniel", text: "gross"}
// db.beers.findById() cousins with Beer.findById
// Beer is the name of the schema, same way we search through a collection
Beer.findById(req.params.id, function(err, foundBeer) {
//foundBeer is the success funct of the beer we found in the database
// we create a function within the function because once we
// find the beer, we want to create and push a review object
if (err) { return next(err); }
var review = new Review(req.body);
foundBeer.reviews.push(review);
foundBeer.save(function (err, review) {
if (err) { return next(err); }
res.json(review);
});
});
});
// fb auth
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
app.get('/auth/facebook', passport.authenticate('facebook'));
// // For development, uncomment this line
// app.listen(8000);
app.listen(process.env.PORT || '8000');
|
PayHistory = React.createClass({
mixins: [ReactMeteorData],
getMeteorData: function() {
var username = Meteor.user().username;
var thisID = StateVars.findOne({user: username}).editID;
return {
sessionID: StateVars.findOne({user: username})._id,
thisClient: Clients.findOne({_id: thisID}),
};
},
enterEditMode: function() {
StateVars.update(this.data.sessionID, {$set:{mode: "editPayHistory", editID: this.data.thisClient._id}});
},
exit: function() {
StateVars.update(this.data.sessionID, {$set:{mode: "manageClients"}});
},
render: function() {
var client = this.data.thisClient;
return <div>
<h2>{client.parents}</h2>
<ul>
{client.payHistory.map(function(check) {
return <li>Date: {check.date}, Number: {check.checkNum}, Amount: ${check.amount}</li>
})}
</ul>
<button className="btn btn-raised btn-default" onClick={this.enterEditMode}>Edit</button>
<button className="btn btn-raised btn-default" onClick={this.exit}>Done</button>
</div>;
}
});
|
import { createAsyncThunk } from "@reduxjs/toolkit"
import axios from "axios"
// Get All Categories
export const getCategories = createAsyncThunk("getCategories", (async (_, thunkAPI) => {
const { data } = await axios.get("http://localhost:4000/category/")
if (data.status === "success") {
return data.payload
} else {
return thunkAPI.rejectWithValue(data)
}
}))
// Add Category
export const addCategory = createAsyncThunk("addCategory", (async (category, thunkAPI) => {
const token = localStorage.getItem("token")
const { data } = await axios.post("http://localhost:4000/category/addCategory", category, {
headers: {
Authorization: `Bearer ${token}`
}
})
if (data.status === "success") {
return thunkAPI.fulfillWithValue(category)
} else {
return thunkAPI.rejectWithValue(data)
}
}))
// Delete Category
export const deleteCategory = createAsyncThunk("deleteCategory", (async ({ category, index }, thunkAPI) => {
const token = localStorage.getItem("token")
const { data } = await axios.post("http://localhost:4000/category/deleteCategory", category, {
headers: {
Authorization: `Bearer ${token}`
}
})
if (data.status === "success") {
return thunkAPI.fulfillWithValue(index)
} else {
return thunkAPI.rejectWithValue(data)
}
}))
// Update Category
export const updateCategory = createAsyncThunk("updateCategory", (async ({ category, index }, thunkAPI) => {
const token = localStorage.getItem("token")
const { data } = await axios.post("http://localhost:4000/category/updateCategory", category, {
headers: {
Authorization: `Bearer ${token}`
}
})
if (data.status === "success") {
return thunkAPI.fulfillWithValue({ category, index })
} else {
return thunkAPI.rejectWithValue(data)
}
}))
|
let config = require('./config.js');
let http = require('http');
let chalk = require('chalk');
let path = require('path');
let url = require('url');
let {inspect,promisify} = require('util');
let fs = require('fs');
let stat = promisify(fs.stat);
let readdir = promisify(fs.readdir);
let mime = require('mime');
let zlib = require('zlib');
let handlebars = require('handlebars');
//编译模板,得到一个渲染的方法,然后传入实际数据就可以得到渲染后的HTML
function list(){ //因为只在系统启动使用一次,使用同步异步无所谓
let tmpl = fs.readFileSync(path.resolve(__dirname,'template','list.html'),'utf8');
return handlebars.compile(tmpl);
}
let debug = require('debug')('static:app');
//这是一个在控制台输出的模块,引入时返回一个函数
//这个函数执行后又会返回一个函数
//是否在控制台打印取决于环境变量中DEBUG的值是否等于static:app
//设置的环境变量有特点,约定第一部分是项目名,第二部分是模块名
class Server {
constructor(argv){
this.list = list();
this.config = Object.assign({},config,argv);
}
start(){
let server = http.createServer();
server.on('request',this.request.bind(this));
server.listen(this.config.port,()=>{
let url = `${this.config.host}:${this.config.port}`;
debug(`server started at ${chalk.green(url)}`);
});
}
async request(req,res){
//先取到客户端向访问的文件或文件夹路径
let{pathname} = url.parse(req.url);
if(pathname === '/favicon.ico') return res.end(); //网站图标
let filepath = path.join(this.config.root,pathname);
try{
let statObj = await stat(filepath);
if(statObj.isDirectory()){ //如果是目录,应该显示目录下的文件列表
let files = await readdir(filepath); //返回的是文件名组成的数组(不带路径)
files = files.map(file=>({
name:file,
url:path.join(pathname,file) // /images,/index.css,/index.html
}));
let html = this.list({
title:pathname,
files
});
res.setHeader('Content-Type','text/html');
res.end(html);
}else{
this.sendFile(req,res,filepath,statObj);
}
}catch(e){
debug(inspect(e)); //inspect把一个toString后的对象仍然能展开显示
this.sendError(req,res);
}
}
sendFile(req,res,filepath,statObj){
if(this.handleCache(req,res,filepath,statObj))return; //如果走缓存,则直接返回
res.setHeader('Content-type',mime.getType(filepath)+';charset=utf-8');
let encoding = this.getEncoding(req,res);
let rs = this.getStream(req,res,filepath,statObj);
if(encoding){
rs.pipe(encoding).pipe(res); //先交给转换流(encoding)处理,再分发给res
}else{
rs.pipe(res);
}
}
getStream(req,res,filepath,statObj){
let start = 0;
// let end = statObj.size - 1;
let end = statObj.size;
let range = req.headers['range'];
if(range){
let result = range.match(/bytes=(\d*)-(\d*)/); //不可能有小数,网络传输的最小单位为一个字节
if(result){
start = isNaN(result[1])?0:parseInt(result[1]);
// end = isNaN(result[2])?end:parseInt(result[2]) - 1;
end = isNaN(result[2])?end:parseInt(result[2]);
}
res.setHeader('Accept-Range','bytes');
res.setHeader('Content-Range',`bytes ${start}-${end}/${statObj.size}`)
res.statusCode = 206; //返回整个数据的一块
}
return fs.createReadStream(filepath,{
start:start-1,end:end-1
});
}
sendError(req,res){
res.statusCode = 500;
res.end(`there is something wrong in the server! please try later!`);
}
getEncoding(req,res){
let acceptEncoding = req.headers['accept-encoding'];
if(/\bgzip\b/.test(acceptEncoding)){
res.setHeader('Content-Encoding','gzip');
return zlib.createGzip();
}else if(/\bdeflate\b/.test(acceptEncoding)){
res.setHeader('Content-Encoding','deflate');
return zlib.createDeflate();
}else{
return null;
}
}
handleCache(req,res,filepath,statObj){
let ifModifiedSince = req.headers['if-modified-since'];
let isNoneMatch = req.headers['is-none-match'];
res.setHeader('Cache-Control','private,max-age=30');
res.setHeader('Expires',new Date(Date.now()+30*1000).toGMTString()); //这个expires的强制缓存的时间格式不能随便写
let etag = statObj.size; //new Date(statObj.ctime.toGMTString()).getTime()+'-'+statObj.size
let lastModified = statObj.ctime.toGMTString();
res.setHeader('ETag',etag);
res.setHeader('Last-Modified',lastModified);
if(isNoneMatch && isNoneMatch != etag)return false; //存在且相等就放行
if(ifModifiedSince && ifModifiedSince != lastModified)return false;
if(isNoneMatch || ifModifiedSince){
res.writeHead(304);
res.end();
return true;
}else{
return false;
}
// if(ifNoneMatch !==etag ){
// return false;
// }
// if(ifModifiedSince!=since){
// return false;
// }
// res.statusCode = 304;
// res.end();
// return true;
}
}
module.exports = Server;
|
const debug = require('debug')('help')
const help = async (message) => {
try {
const embed = {
title: 'Coin bot commands:',
description:
'- !help (All commands)\n- !coins (All coins)\n- !github (Coin bot repository)\n- !donate (We are collecting for hosting)\n**Now in coins embeds you can find charts!**',
color: 0x4c4cff,
footer: {
icon_url:
'https://cdn.discordapp.com/avatars/395240399750299658/1e9edd0c9edf5a6edb9fd36fcd693a9f.png',
text: 'Coin bot by fosscord',
},
author: {
name: 'Coin bot',
url: 'https://github.com/quritto/coin_bot',
icon_url:
'https://cdn.discordapp.com/avatars/395240399750299658/1e9edd0c9edf5a6edb9fd36fcd693a9f.png',
},
fields: [
{
name: 'Legend:',
value:
':clock1: - 1 hour\n:calendar: - 24 hours\n:calendar_spiral: - 7 days',
},
],
}
await message.channel.send({ embed })
} catch (err) {
debug(err)
}
}
module.exports = help
|
let app_url = `${process.env.PUBLIC_URL}/api/`;
let app_server = `${process.env.PUBLIC_URL}`;
if(typeof window != "undefined"){
app_url = window.location.protocol+"//"+window.location.host+"/api/"
app_server = window.location.protocol+"//"+window.location.host;
}
export default {app_url,app_server}
|
// ---------------Required Modules--------------------------
const inquirer = require('inquirer');
const fs = require('fs');
// --------------License Logo link Variables-----------------
const mit = '';
const apache = '';
const gnu2 = '';
const gnu3 = '';
const none = '';
// ---------------------Questions Array----------------------
const questions = [
{
type: 'input',
name: 'Author',
message: 'What is the Authors name?',
default: 'Brett Treweek',
},
{
type: 'input',
name: 'Username',
message: 'What is your Github username?',
default: 'brett-treweek',
},
{
type: 'input',
name: 'Title',
message: 'What is the title of this project?',
default: 'CLI Readme Generator',
validate: (answer) => {
if(answer=== ''){
return 'Please enter a valid title'
}
return true
}
},
{
type: 'editor',
name: 'Description',
message: 'Provide a short description of this project.',
validate: (answer) => {
if(answer=== ''){
return 'Please enter a valid Description'
}
return true
}
},
{
type: 'input',
name: 'Installation',
message: 'What are the steps required to install this project?',
default: 'install node.js\ninstall npm\ninstall inquirer\n',
validate: (answer) => {
if(answer=== ''){
return 'Please enter valid Instructions'
}
return true
}
},
{
type: 'editor',
name: 'Usage',
message: 'Provide Instructions and examples for use.',
validate: (answer) => {
if(answer=== ''){
return 'Please enter valid Instructions'
}
return true
}
},
{
type: 'input',
name: 'Screenshot',
message: 'Provide file name of screenshot',
default: 'screenshot.PNG',
validate: (answer) => {
if(answer=== ''){
return 'Please enter valid screenshot'
}
return true
}
},
{
type: 'list',
name: 'License',
message: 'Please choose a License.',
choices: ['MIT','GNU 2.0', 'Apache 2.0','GNU 3.0','None'],
default: 'MIT',
},
{
type: 'input',
name: 'Contributing',
message: 'Please add Contributing Instructions.',
default: 'Contributing to this project is welcome.',
validate: (answer) => {
if(answer=== ''){
return 'Please enter valid Instructions'
}
return true
}
},
{
type: 'input',
name: 'Tests',
message: 'Please add Tests Instructions.',
default: 'There are no tests at present.'
},
{
type: 'input',
name: 'Support',
message: 'Please add Support email address',
default: 'bretttrew@gmail.com',
validate: (answer) => {
if(answer=== ''){
return 'Please enter valid email address'
}
return true
}
}
]
console.log('------------------Readme Generator--------------------')
inquirer
.prompt(questions)
.then(answers => {
// -----------------License Logo If Statement-------------------------
if(answers.License === 'MIT'){
licenseLogo = mit
}else if (answers.License === 'GNU 2.0'){
licenseLogo = gnu2
}else if(answers.License === 'GNU 3.0'){
licenseLogo = gnu3
}else if(answers.License === 'Apache 2.0'){
licenseLogo = apache
}else{
licenseLogo = none
}
// --------------------Markdown Template-----------------------------
const readmeFramework =
`# ${answers.Title}\n
${licenseLogo}\n
## Description\n
${answers.Description}\n
---
## Table of Contents\n
- [Installation](#installation)
- [Usage](#usage)
- [License](#license)
- [Contributing](#contributing)
- [Tests](#tests)
- [Questions](#questions)\n
---
## Installation\n
Please follow these steps to install the project and any dependancies.\n
\`\`\`bash
${answers.Installation}\n
\`\`\`\n
---
## Usage\n
${answers.Usage}\n
\n
---
## License\n
This project is licensed under ${licenseLogo}\n
---
## Contributing\n
${answers.Contributing}\n
You can contribute to this project at [GitHub](https://github.com/${answers.Username}/CLI-README-Generator)\n
---
## Tests\n
Please use these commands to perform tests.\n
\`\`\`bash\n
${answers.Tests}\n
\`\`\`\n
---
## Questions\n
For any questions and support please contact ${answers.Author} at ${answers.Support} or message me through [GitHub](https://github.com/${answers.Username}).`
// -----------------Function to create Readme and catch errors--------------------
fs.writeFile('proREADME.md', readmeFramework, (err) =>
err ? console.error(err) : console.log('Success!')
);
console.log(answers)
console.log(answers.Title)
})
.catch(error => {
if(error.isTtyError) {
console.log('Prompt couldnt be rendered in the current environment')
} else {
console.log('Something else went wrong')
}
});
|
var React = require("react");
var css = require("./CourseSelectList.css");
import CourseCardBundle from "../CourseCard/CourseCard.jsx"
import Popover from 'material-ui/Popover'
import Menu from 'material-ui/Menu';
import MenuItem from 'material-ui/MenuItem';
import {List, ListItem} from 'material-ui/List';
import Paper from 'material-ui/Paper';
import ContentInbox from 'material-ui/svg-icons/content/inbox';
import ContentSend from 'material-ui/svg-icons/content/send';
import DeleteIcon from 'material-ui/svg-icons/action/delete';
import FlatButton from 'material-ui/FlatButton';
import Dialog from 'material-ui/Dialog';
require('es6-promise').polyfill();
require('isomorphic-fetch');
let avatar_blank = require('./static/avatar_blank.png');
var CourseCard = CourseCardBundle.CourseCard;
const CourseCardImgSource = CourseCardBundle.CourseCardImgSource;
var AssignmentSelection = []
const customDialogContentStyle = {
width: '100%',
maxWidth: 'none',
};
class Entry extends React.Component
{
constructor(props)
{
super(props);
let assignmentSelect = localStorage.assignmentSelect;
let courseTime = localStorage.courseTime;
this.state = {
data: [],
assignmentSelect: (assignmentSelect) ? (JSON.parse(assignmentSelect)): [],
underReviewCourse: [],
courseTime: courseTime ? (JSON.parse(courseTime)) : [],
dialogOpen: false,
dialogMsg: ""
}
this.selectAssignment = this.selectAssignment.bind(this);
this.cancelSelection = this.cancelSelection.bind(this);
this.submitSelection = this.submitSelection.bind(this);
this.handleDialogClose = this.handleDialogClose.bind(this);
}
handleDialogClose = () => {
this.setState({dialogOpen: false});
}
cancelSelection = (courseId) => {
var dic = this.state.assignmentSelect;
dic[courseId] = null;
this.setState({assignmentSelect: dic});
};
selectAssignment = (courseId, assignmentId, selectAssignmentTime, selectTeacherName, avatar, courseTime) => {
var course_t = this.state.courseTime;
var underReviewCourse = this.state.underReviewCourse;
console.log(underReviewCourse);
var err = false;
var errmsg = "";
courseTime.forEach(function (value, key) {
if (!err)
{
for (var i = 0; i != value.duration; i++)
{
if (underReviewCourse[value.day][value.start_time + i])
{
errmsg = "该时间段有课程待筛选中: " + underReviewCourse[value.day][value.start_time + i].title + " " + underReviewCourse[value.day][value.start_time + i].subtitle;
err = true;
break;
}
if (course_t[value.day][value.start_time + i])
{
errmsg = "上课时间冲突:" + course_t[value.day][value.start_time + i].title;
err = true;
break;
}
}
}
});
if (!err)
{
for (var i = 0; i != 7; i++)
{
for (var j = 1; j != 13; j++)
{
if (course_t[i][j])
{
if (course_t[i][j].courseId == courseId)
{
errmsg = "课程重复, 您已经选上了" + course_t[i][j].title;
err = true;
break;
}
}
}
if (err)
{
break;
}
};
}
if (err)
{
this.setState({dialogOpen: true, dialogMsg: errmsg});
return;
}
else
{
var dic = this.state.assignmentSelect;
dic[courseId] = {
assignmentId: assignmentId,
subtitle: selectTeacherName + " " + selectAssignmentTime,
avatar: avatar
}
this.setState({assignmentSelect: dic});
}
};
saveCourseSelectionLocal = () => {
localStorage.assignmentSelect = JSON.stringify(this.state.assignmentSelect);
};
submitSelection = () => {
var data = new FormData();
this.state.assignmentSelect.forEach(function (value, key) {
if (value)
{
data.append("list", value.assignmentId);
}
});
return fetch(localStorage.root_url + 'api/Enrollment/EnrollCourses', {
method: 'POST',
headers: {
'Authorization': localStorage.token,
},
body: data
})
.then((response) => response.json())
.then((json) => {});
}
deleteLocal = () => {
localStorage.removeItem("assignmentSelect");
this.setState({assignmentSelect: []});
}
componentDidMount()
{
fetch(localStorage.root_url + 'api/Enrollment/MyUnderReview',
{
method: 'GET',
mode: "cors",
headers: {
'Authorization': localStorage.token
}
})
.then((response) => response.json())
.then((cb) => {
switch (cb.errorCode)
{
case 200:
var underReviewCourse = [[], [], [], [], [], [], []];
cb.data.forEach((value, key) => {
value.courseTime.forEach((value_t, key) => {
for (var i = 0; i != value_t.duration; i++)
{
underReviewCourse[value_t.day][value_t.startTime + i] = {
title: value.avatarTitle,
subtitle: value.instructorName,
courseId: value.courseID
}
}
})
});
this.setState({underReviewCourse: underReviewCourse});
break;
default:
console.error("获取未筛选课程失败")
}
});
return fetch(localStorage.root_url + 'api/Course/Enrollable',
{
method: 'GET',
mode: "cors",
headers: {
'Authorization': localStorage.token
}
})
.then((response) => response.json())
.then((cb) => {
switch (cb.errorCode)
{
case 200:
var data = new Array();
cb.data.forEach(function(value, key) {
var facultyList = [];
value.assignments.forEach(function(avalue, aid) {
var course_t = [];
for (var i in avalue.courseTimes)
{
var item = avalue.courseTimes[i];
course_t.push({
day: item.day,
start_time: item.startTime,
duration: item.duration
})
}
facultyList.push({
assignmentId: avalue.assignmentID,
name: avalue.instructorName,
avatar: localStorage.root_url + avalue.instructorAvatar,
course_time: course_t,
course_time_str: avalue.courseTimeStr
})
});
data.push({
avatar_title: value.courseName,
avatar_subtitle: "",
avatar_img: localStorage.root_url + "api/File/MakeCharAvatar?ch=" + value.courseName[0],
course_img: localStorage.root_url + value.courseBanner,
course_id: value.courseID,
course_title: value.courseName,
course_info: value.courseInfo,
facultyList: facultyList
})
});
this.setState({data: data});
break;
default:
console.error("课程选择列表初始化失败");
break;
}
});
}
render()
{
const actions = [
<FlatButton
label="我知道了"
primary={true}
onTouchTap={this.handleDialogClose}
/>];
return (
<div>
<div className={css.cardContainer}>
{
this.state.data.map((item, id) => {
return (this.state.assignmentSelect == null || this.state.assignmentSelect[item.course_id] == null) ? (
<div className={css.card}>
<CourseSelectCard
avatar_title={item.avatar_title}
avatar_subtitle={item.avatar_subtitle}
avatar_img={item.avatar_img}
course_img={item.course_img}
course_id={item.course_id}
course_title={item.course_title}
course_info={item.course_info}
facultyList={item.facultyList}
selectClick={this.selectAssignment}
cancelClick={this.cancelSelection}
key={id}
/>
</div>
) : (
<div className={css.card}>
<CourseSelectCard
avatar_title={item.avatar_title}
avatar_subtitle={this.state.assignmentSelect[item.course_id].subtitle}
avatar_img={this.state.assignmentSelect[item.course_id].avatar}
course_img={item.course_img}
course_id={item.course_id}
course_title={item.course_title}
course_info={item.course_info}
facultyList={item.facultyList}
selectClick={this.selectAssignment}
cancelClick={this.cancelSelection}
key={id}
/>
</div>
);
})
}
</div>
<div className={css.toolBar}>
<Paper>
<List>
<ListItem primaryText="本地保存" leftIcon={<ContentInbox />} onClick={this.saveCourseSelectionLocal}/>
<ListItem primaryText="提交申请" leftIcon={<ContentSend />} onClick={this.submitSelection}/>
<ListItem primaryText="清空本地记录" leftIcon={<DeleteIcon />} onClick={this.deleteLocal}/>
</List>
</Paper>
</div>
<div className="student-dialog">
<Dialog
title="选课失败"
actions={actions}
modal={true}
contentStyle={customDialogContentStyle}
open={this.state.dialogOpen}
>
{this.state.dialogMsg}
</Dialog>
</div>
</div>
)
}
}
class CourseSelectCard extends React.Component {
constructor(props) {
super(props);
this.state = {
open: false,
selectTeacherName: ""
};
this.handleTouchTap = this.handleTouchTap.bind(this);
this.handleSelect = this.handleSelect.bind(this);
this.handleClose = this.handleClose.bind(this);
this.handleCancel = this.handleCancel.bind(this);
}
handleTouchTap = (event) => {
// This prevents ghost click.
event.preventDefault();
this.setState({
open: true,
anchorEl: event.currentTarget,
});
};
handleClose = () => {
this.setState({
open: false,
});
}
handleSelect = (courseId, assignmentId, selectAssignmentTime, selectTeacherName, avatar, courseTime) => {
this.props.selectClick(courseId, assignmentId, selectAssignmentTime, selectTeacherName, avatar, courseTime);
this.setState({
open: false,
});
};
handleCancel = (courseId) => {
this.props.cancelClick(this.props.course_id);
this.setState({
open: false,
});
}
render() {
return (
<div>
<CourseCard className={css.card}
avatar_title={this.props.avatar_title}
avatar_subtitle={this.props.avatar_subtitle}
avatar_img={this.props.avatar_img}
course_img={this.props.course_img}
course_title={this.props.course_title}
course_info={this.props.course_info}
buttons={[{label: '专业必修', onClick: this.handleTouchTap, labelColor: '#EB2A29', backgroundColor: '#D8D8D8'}]}
/>
<Popover
open={this.state.open}
anchorEl={this.state.anchorEl}
anchorOrigin={{horizontal: 'left', vertical: 'bottom'}}
targetOrigin={{horizontal: 'left', vertical: 'top'}}
onRequestClose={this.handleClose}
>
<Menu>
{
(this.props.facultyList.map((item, id) => {
return (
<MenuItem primaryText={item.name + " (" + item.course_time_str + ")"} key={id} onClick={
(courseId, assignmentId, selectAssignmentTime, selectTeacherName, avatar, courseTime) =>
this.handleSelect(this.props.course_id, item.assignmentId, item.course_time_str, item.name, item.avatar, item.course_time)
}/>
)
}))
}
<MenuItem primaryText="取消" onClick={(courseId) => this.handleCancel(this.props.course_id)}/>
</Menu>
</Popover>
</div>
);
}
}
module.exports=Entry;
|
import { StyleSheet } from 'react-native';
import metrics from './config/metrics';
export default StyleSheet.create({
container: {
flexDirection: 'row',
},
content: {
backgroundColor: 'rgba(0,0,0,0.3)',
height: metrics.TIME_BAR_HEIGHT,
borderColor: 'black',
borderWidth: 1,
},
});
|
import React from 'react';
import ReactDOM from 'react-dom';
import ReactTestUtils from 'react-dom/test-utils';
import Player from './../../src/components/Player';
import Button from './../../src/components/Button';
import { ButtonValues } from './../../src/components/Button'
describe("Player", function() {
it('renders without crashing', () => {
const div = document.createElement('div');
ReactDOM.render(<Player />, div);
ReactDOM.unmountComponentAtNode(div);
});
describe("Content", function() {
let handleClick = (event) => {};
beforeEach(() => {
this.instance = ReactTestUtils.renderIntoDocument(<Player onButtonClick={handleClick} className="testClass" name="Player X" />);
});
it('contains a Button for each values', () => {
let buttons = ReactTestUtils.scryRenderedComponentsWithType(this.instance, Button);
expect(buttons.length).toBe(Object.values(ButtonValues).length);
for (let i = 0; i < Object.values(ButtonValues).length; i++) {
let button = buttons[i];
expect(button._reactInternalFiber.key).toBe('' + i);
expect(button.props.onButtonClick).toBe(handleClick);
expect(button.props.value).toBe(Object.values(ButtonValues)[i].toLowerCase());
}
});
it('contains a div for the buttonList', () => {
let div = ReactTestUtils.findRenderedDOMComponentWithClass(this.instance, "buttonList");
expect(div).toBeDefined();
expect(div.children.length).toBe(Object.values(ButtonValues).length);
});
it('has a name', () => {
expect(this.instance.props.name).toBe("Player X");
let h2 = ReactTestUtils.findRenderedDOMComponentWithTag(this.instance, "h2");
expect(h2).toBeDefined();
expect(h2.textContent).toBe("Player X");
});
it('has a class', () => {
expect(this.instance.props.className).toBe("testClass");
let div = ReactTestUtils.findRenderedDOMComponentWithClass(this.instance, "testClass");
expect(div).toBeDefined();
});
it('has an onButtonClick props', () => {
expect(this.instance.props.onButtonClick).toBe(handleClick);
});
})
});
|
const lookupChar=require('../Char-lookup')
const assert=require('chai').assert;
describe('Returns correct char', ()=>{
it('Returns correct index',()=>{
let index=2;
let arg="Abkhazia";
let expected='k';
assert.strictEqual(expected, lookupChar(arg, index));
});
it('Returns final char', ()=>{
let index=3;
let arg="Call";
let expected="l";
assert.strictEqual(expected, lookupChar(arg, index));
});
it('Returns first char', ()=>{
let index=0;
let arg="Varna";
let expected="V";
assert.strictEqual(expected, lookupChar(arg, index));
});
});
describe('Index out of range', ()=>{
it('negative', ()=>{
assert.strictEqual("Incorrect index", lookupChar("Summon", -1));
})
it('index too big', ()=> {
let index=100;
let arg="Matti from Finland";
let expected="Incorrect index";
assert.strictEqual(expected, lookupChar(arg,index));
});
it('index is equal to string length', ()=>{
let arg="Panaiot";
let index=arg.length;
let expected="Incorrect index";
assert.strictEqual(expected, lookupChar(arg, index));
});
});
describe('false argument type tests', ()=>{
it('string', ()=>{
let index=0;
let arg=12;
let expected=undefined;
assert.strictEqual(expected, lookupChar(arg, index));
});
it('number', ()=>{
let index= "Sega e momenta za apartamenta";
let arg="Koga?";
let expected=undefined;
assert.strictEqual(expected, lookupChar(arg,index));
});
it('double', ()=>{
let index= 1.2;
let arg="Koga?";
let expected=undefined;
assert.strictEqual(expected, lookupChar(arg, index));
});
});
|
import React from 'react'
import { connect } from 'react-redux'
import { Link } from 'react-router'
const NavItem = ({ to, visible = true, children }) =>
<li><Link to={to}>{children}</Link></li>
export default connect((state) => state.app)(({ session: { signedIn }}) => (
<nav id="navbar">
<ul>
<NavItem to="/">Home</NavItem>
<NavItem to="/info">Info</NavItem>
{ signedIn ? <NavItem to="/tickets">Tickets</NavItem> : null }
<NavItem to="/shop">Shop</NavItem>
{ !signedIn ? <NavItem to="/register">Register</NavItem> : null }
{ !signedIn ? <NavItem to="/login">Login</NavItem> : null }
{ signedIn ? <li>Logout</li> : null }
</ul>
</nav>
))
|
module.exports = {
scriptVersion: '0.1.0',
dirName: 'apiVersionnedTuto',
linkedRepos: [ 'chooz-it-app' ],
install: function() {
console.log(process.cwd());
}
};
|
import axios from 'axios';
import { ROOT_URL } from './constants';
export default {
fetchRaces() {
return axios.get(`${ROOT_URL}/races`)
},
}
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _secureDfu = require("./secure-dfu");
Object.defineProperty(exports, "SecureDFU", {
enumerable: true,
get: function get() {
return _secureDfu.SecureDFU;
}
});
|
//very similar to tutorial
angular.
module('myApp').
config(['$locationProvider', '$routeProvider',
function config($locationProvider, $routeProvider) {
$locationProvider.hashPrefix('!');
$routeProvider.
when('/login', {
templateUrl: '<login-view></login-view>'
}).
when('/list-active', {
template: '<list-view-active></list-view-active>'
}).
when('/list-archive', {
template: '<list-view-archive></list-view-archive>'
}).
when('/vote', {
template: '<vote-view></vote-view>'
}).
when('/my-org', {
template: '<my-org-view></my-org-view>'
}).
when('/sign-in', {
template: '<sign-in-view></sign-in-view>'
}).
when('/new-sign-in', {
template: '<new-sign-in-view></new-sign-in-view>'
}).
when('/new-list', {
template: '<new-list-view></new-list-view>'
}).
when('/new-vote', {
template: '<new-vote-view></new-vote-view>'
}).
when('/new-batch-vote', {
template: '<new-batch-vote-view></new-batch-vote-view>'
}).
otherwise('/login');
}
]);
|
/**\
*
* (연계형 문제 - 88번을 먼저 풀고 오셔야 합니다!)
제코베의 도움을 받아 성공적으로 지도를 만들어낸 지식이는 캐릭터의 움직임을 구현했습니다.
하지만 지도 위의 캐릭터 위치를 나타내는데 문제가 발생했습니다.
지식이는 지도 위에서 캐릭터의 위치를 나타내기 위해 다시 한번 제코베에 도움을 요청합니다.
지도 위에서 캐릭터의 위치를 나타내주세요
1. 지도는 88번 문제의 해답을 사용해 주세요
2. 입력값은 지도, 캐릭터의 움직임입니다.
3. 캐릭터의 움직임은 { 상:1, 하:2, 좌:3, 우:4 }로 정수로 이루어진 배열이 들어갑니다.
4. 벽과 장애물은 통과할 수 없습니다.
5. 마지막 캐릭터의 위치를 반영한 지도를 보여주고 위치를 반환하는 함수를 작성해 주세요.
* **데이터**
가로 = 4
세로 = 5
캐릭터위치 = [0, 0]
장애물 = [[0,1],[1,1],[2,3],[1,3]]
console.log('캐릭터 이동 전 지도')
지도 = make_map(가로, 세로, 캐릭터위치, 장애물)
움직임 = [2,2,2,4,4,4]
console.log('캐릭터 이동 후 지도')
캐릭터 위치 = move(지도, 움직임)
**출력**
캐릭터 이동 전 지도
[2, 2, 2, 2, 2, 2]
[2, 1, 2, 0, 0, 2]
[2, 0, 2, 0, 2, 2]
[2, 0, 0, 0, 2, 2]
[2, 0, 0, 0, 0, 2]
[2, 0, 0, 0, 0, 2]
[2, 2, 2, 2, 2, 2]
캐릭터 이동 후 지도
[2, 2, 2, 2, 2, 2]
[2, 0, 2, 0, 0, 2]
[2, 0, 2, 0, 2, 2]
[2, 0, 0, 0, 2, 2]
[2, 0, 0, 0, 1, 2]
[2, 0, 0, 0, 0, 2]
[2, 2, 2, 2, 2, 2]
캐릭터위치 : [4, 4]
*/
function make_map(n,m,char,obj){
//지도 초기화하기
//각 지도 가로/세로 두칸 외벽을 포함한 크기만큼 추가하기(각 끝 한칸씩)
let world_map = [];
for(let i=0; i<m+2; i++){
world_map.push(Array(n+2).fill(0));
}
//지도 외벽 그리기
for(let i in world_map){
for(let j in world_map[0]){
if (i==0 || j==world_map[0].length-1 || j==0 || i==world_map.length-1) {
world_map[i][j] = 2;
}
}
}
//지도에 캐릭터 추가하기/ 외벽으로 인해 좌표에 +1을 해줍니다.
world_map[char[0]+1][char[1]+1] = 1;
//지도에 장애물 추가하기
for (let i of obj){
if (world_map[i[0]+1][i[1]+1] != 1){
world_map[i[0]+1][i[1]+1] = 2;
} else {
world_map[i[0]+1][i[1]+1] = 1;
}
}
//장애물을 추가하려는 자리에 캐릭터가 있을 시 캐릭터는 그대로둔다
//마찬가지 외벽으로 인한 좌표 조정을 해준다.
for(let i of world_map) {
console.log(i);
}
return world_map;
}
function move(world_map, moving){
let x = 0;
let y = 0;
for(let i of world_map){
if(i.includes(1)){
x = world_map.indexOf(i);
y = i.indexOf(1);
}
}
world_map[y][x] = 0;
for(let i of moving){
if (i == 1 && world_map[y-1][x]!=2){
y -= 1;
} else if (i==2 && world_map[y+1][x]!=2){
y += 1;
} else if (i==3 && world_map[y][x-1]!=2){
x -= 1;
} else if (i==4 && world_map[y][x+1]!=2){
x += 1;
}
}
world_map[y][x] = 1;
for (let i of world_map){
console.log(i);
}
return [x,y];
}
console.log('캐릭터 이동 전 지도');
const world_map = make_map(4, 5, [0, 0], [[0,1],[1,1],[2,3],[1,3]]);
const moving = [2,2,2,4,4,4];
console.log('캐릭터 이동 후 지도');
console.log('캐릭터위치 :',move(world_map, moving));
|
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var jsonParser = bodyParser.json();
var request = require('request');
// request.debug = true;
// require("request-debug")(request);
var Recipe = require('./models/recipe.js');
var mongoose = require('mongoose');
var MongoURI = process.env.MONGO_URI || 'mongodb://localhost/recipes';
mongoose.connect(MongoURI, function(err, res) {
if (err) {
console.log('ERROR connecting to: ' + MongoURI + '. ' + err);
} else {
console.log('MongoDB connected successfully to ' + MongoURI);
}
});
app.use(bodyParser.json());
app.use(jsonParser);
var NutritionixClient = require('nutritionix');
var nutritionix = new NutritionixClient({
appId: '1e6399d7', //'a120429b',
appKey: '4088d6a1aca0376052356e4872c24b68' //'3e1551bafdb518dba63b0555ac4f1482'
});
var calculateValues = function() {
Recipe.find({
//_id: "55bb96c8b608931f120783ac",
// source_url: source_Url
calculated: false
}, function(err, recipes) {
if (recipes) {
// console.log("1 " + recipes);
recipes.forEach(function(recipe) {
var recipeFindId = recipe.id
var ingredientsArray = recipe.ingredients;
if (ingredientsArray.length !== 0) {
// console.log("4 " + ingredientsArray);
var proteinVal = 0;
var carbVal = 0;
var fatVal = 0;
var monoUnSatVal = 0;
var polyUnSatVal = 0;
var satVal = 0;
var vitCVal = 0;
var vitAVal = 0;
var vitB6Val = 0;
var vitB12Val = 0;
ingredientsArray.forEach(function(ingredient) {
// console.log(ingredient.protein.value);
console.log('values: ' + ingredient.protein.value);
console.log('values: ' + ingredient.carbohydrates.value);
if (ingredient.protein) {
proteinVal += ingredient.protein.value || 0;
}
if (ingredient.carbohydrates) {
carbVal += ingredient.carbohydrates.value || 0;
}
if (ingredient.fat) {
fatVal += ingredient.fat.value || 0;
}
// console.log('cals: ' + proteinVal);
// console.log('cals: ' + carbVal);
// console.log('cals: ' + fatVal)
if (ingredient.saturatedFat) {
satVal += ingredient.saturatedFat.value || 0;
}
if (ingredient.polyUnsaturatedFat) {
polyUnSatVal += ingredient.polyUnsaturatedFat.value || 0;
}
if (ingredient.monoUnsaturatedFat) {
monoUnSatVal += ingredient.monoUnsaturatedFat.value || 0;
}
// satVal += ingredient.saturatedFat.value;
if (ingredient.vitaminC) {
vitCVal += ingredient.vitaminC.value || 0;
}
if (ingredient.vitaminA) {
vitAVal += ingredient.vitaminA.value || 0;
}
if (ingredient.vitaminB6) {
vitB6Val += ingredient.vitaminB6.value || 0;
}
if (ingredient.vitaminB12) {
console.log("came here");
console.log(ingredient.vitaminB12);
vitB12Val += ingredient.vitaminB12.value || 0;
}
// console.log(fatVal);
});
var totalCal = (4 * proteinVal) + (4 * carbVal) + (9 * fatVal);
var totalProtPerc = (((proteinVal * 4) / totalCal)) * 100;
var totalCarbPerc = (((carbVal * 4) / totalCal)) * 100;
var totalFatPerc = (((fatVal * 9) / totalCal)) * 100;
console.log("Here are the values:");
console.log(totalCal);
console.log(proteinVal);
console.log(carbVal);
console.log(fatVal);
// console.log('cals: ' + totalCal);
Recipe.update({
_id: recipeFindId
}, {
$set: {
totalCalories: totalCal,
percentProtein: totalProtPerc,
percentCarbohydrates: totalCarbPerc,
percentFat: totalFatPerc,
monoUnsaturatedFat: monoUnSatVal,
polyUnsaturatedFat: polyUnSatVal,
saturatedFat: satVal,
vitaminC: vitCVal,
vitaminA: vitAVal,
vitaminB6: vitB6Val,
vitaminB12: vitB12Val,
calculated: true
}
}, {
upsert: true,
multi: true
}, function(err, ingredients) {
if (err) {
console.error(err);
console.log("Recipe id is");
console.log(recipeFindId);
} else {
console.log("ingredient updated!");
}
});
}
})
}
})
}
function processNutrientsHandler(ingredient, sourceUrl, ingBody) {
var nutrient = ingredient.nutrients;
console.log("nutrient length is: " + nutrient.length);
if (nutrient.length > 0) {
//define variable and assign them values in the for -loop below
var proteinValue;
var proteinUnit;
var carbohydratesValue;
var carbohydratesUnit;
var lipidValue;
var lipidUnit;
var polyUnsatValue;
var polyUnsatUnit;
var monoUnsatValue;
var monoUnsatUnit;
var satValue;
var satUnit;
var cholesterolValue;
var cholesterolUnit;
var ironValue;
var ironUnit;
var vitaminCValue;
var vitaminCUnit;
var vitaminAValue;
var vitaminAUnit;
var vitaminB6Value;
var vitaminB6Unit;
var vitaminB12Value;
var vitaminB12Unit;
//go through each nutrient in the array and look for the nutrients- carbs,lipids,etc
for (var j = 0; j < nutrient.length; j++) {
if (nutrient[j].name === "Protein") {
proteinValue = nutrient[j].value;
proteinUnit = nutrient[j].unit;
//console.log("this is nutrient info for protein: %j%j ", proteinValue, proteinUnit);
} else if (nutrient[j].name === "Carbohydrate, by difference") {
carbohydratesValue = nutrient[j].value;
carbohydratesUnit = nutrient[j].unit;
} else if (nutrient[j].name === "Total lipid (fat)") {
lipidValue = nutrient[j].value;
} else if (nutrient[j].name === "Fatty acids, total polyunsaturated") {
polyUnsatValue = nutrient[j].value;
polyUnsatUnit = nutrient[j].unit;
} else if (nutrient[j].name === "Fatty acids, total monounsaturated") {
monoUnsatValue = nutrient[j].value;
monoUnsatUnit = nutrient[j].unit;
} else if (nutrient[j].name === "Fatty acids, total saturated") {
satValue = nutrient[j].value;
satUnit = nutrient[j].unit;
//console.log("this is nutrient info for satValue: %j%j ", monoUnsatValue, monoUnsatUnit);
} else if (nutrient[j].name === "Iron,FE") {
ironValue = nutrient[j].value;
ironUnit = nutrient[j].unit;
} else if (nutrient[j].name === "Vitamin C, total ascorbic acid") {
vitaminCValue = nutrient[j].value;
vitaminCUnit = nutrient[j].unit;
} else if (nutrient[j].name === "Vitamin B-6") {
vitaminB6Value = nutrient[j].value;
vitaminB6Unit = nutrient[j].unit;
} else if (nutrient[j].name === "Vitamin B-12") {
vitaminB12Value = nutrient[j].value;
vitaminB12Unit = nutrient[j].unit;
} else if (nutrient[j].name === "Vitamin A, RAE") {
vitaminAValue = nutrient[j].value;
vitaminAUnit = nutrient[j].unit;
}
}
var ingredientsInsert = {
name: ingBody,
protein: {
value: proteinValue,
unit: proteinUnit
},
carbohydrates: {
value: carbohydratesValue,
unit: carbohydratesUnit
},
fat: {
value: lipidValue,
unit: lipidUnit
},
monoUnsaturatedFat: {
value: monoUnsatValue,
unit: monoUnsatUnit
},
polyUnsaturatedFat: {
value: polyUnsatValue,
unit: polyUnsatUnit
},
saturatedFat: {
value: satValue,
unit: satUnit
},
// cholesterol: {
// value: cholesterolValue,
// unit: cholesterolUnit
// },
// iron: {
// value: ironValue,
// unit: ironUnit
// },
vitaminC: {
value: vitaminCValue,
unit: vitaminCUnit
},
vitaminA: {
value: vitaminAValue,
unit: vitaminAUnit
},
vitaminB6: {
value: vitaminB6Value,
unit: vitaminB6Unit
},
vitaminB12: {
value: vitaminB12Value,
unit: vitaminB12Unit
}
}
// var ingredientInsert = {
// name: ingBody,
// }
var recipeUpdate = Recipe.update({
source_url: sourceUrl
}, {
$push: {
ingredients: ingredientsInsert
}
}, function(err, ingredients) {
if (err) {
console.error(err);
} else {
console.log("success!");
}
});
}
}
function getIngredientNutrients(joinedIng, sourceUrl, finalCallback) {
joinedIng.forEach(function(ing) {
var ingBody = ing;
// var ingBody = joinedIng.join("\n");
console.log("joined ingredient sent for query are %j", ingBody)
var getNutrientInfoRequest = {
method: 'POST',
headers: {
'Content-Type': 'text/plain',
'X-APP-ID': '1e6399d7', //'a120429b',
'X-APP-KEY': '4088d6a1aca0376052356e4872c24b68' //'3e1551bafdb518dba63b0555ac4f1482'
},
uri: {
protocol: 'https:',
slashes: true,
auth: null,
host: 'api.nutritionix.com',
port: 443,
hostname: 'api.nutritionix.com',
hash: null,
search: null,
query: null,
pathname: '/v2/natural',
path: '/v2/natural',
href: 'https://api.nutritionix.com/v2/natural'
},
body: ingBody
};
request(getNutrientInfoRequest, function(error, response, body) {
if (error) {
console.log(" ERROR = " + error);
finalCallback(e);
} else {
///response is an object with results as a key and value as nutrition details
console.log("1: nutrition status = " + response.statusCode);
// console.log("nutrition: body = " + response.body);
var res = response.body;
res = JSON.parse(res);
var result = res.results;
//if ingredient format is not correct
if (response.statusCode === 400) {
console.log("Bad request code " + response.statusCode);
var badReqIngredient = ingBody;
badReqIngredient = badReqIngredient.replace(/boneless|skinless|halves|cooked|uncooked|shredded|peeled|sliced|pounded|diced|pitted|melted|powdered|flavoured|flavoring|cleaned|keep|refrigerated|chilled|cold|whole|new|and|grated|room|temperature|thawed|frozen|coarsely|chopped|confectioners'|white|softened|mashed|beaten|canned|drained|lightly|uncooked|peeled|ripe|mashed|cut|into|2|inch|piece|white|divided|prepared|ground|cubed|warmed|drained|fresh|beaten|pieces|prepared|minced|to|taste|boiling|and|or|fillet|fillets|s|,/ig, function replacer(match) {
return "";
});
console.log("2: %j", badReqIngredient)
badReqIngredient = badReqIngredient.replace(/pound|pounds/ig, function replaceValues(match) {
return "lb"
});
console.log("3: %j", badReqIngredient)
badReqIngredient = badReqIngredient.replace(/ounce|ounces/ig, function replaceValues(match) {
return "oz"
})
badReqIngredient = badReqIngredient.replace(/ *\([^)]*\) */g, "");
request({
// jar: null,
method: 'POST',
headers: {
'Content-Type': 'text/plain',
'X-APP-ID': '1e6399d7', //'a120429b',
'X-APP-KEY': '4088d6a1aca0376052356e4872c24b68' //'3e1551bafdb518dba63b0555ac4f1482'
},
uri: {
protocol: 'https:',
slashes: true,
auth: null,
host: 'api.nutritionix.com',
port: 443,
hostname: 'api.nutritionix.com',
hash: null,
search: null,
query: null,
pathname: '/v2/natural',
path: '/v2/natural',
href: 'https://api.nutritionix.com/v2/natural'
},
body: badReqIngredient
}, function(error, resp, body) {
if (error) {
console.log(" ERROR = " + error);
finalCallback(error);
} else {
///response is an object with results as a key and value as nutrition details
var res = resp.body;
res = JSON.parse(res);
var result = res.results;
if (resp.statusCode === 200) {
console.log("4 nutrition status = " + resp.statusCode);
console.log("5b badReqIngredient %j", ingBody)
result.forEach(function(ingredient) {
processNutrientsHandler(ingredient, sourceUrl, ingBody)
})
finalCallback(null, result);
} else {
console.log("6: ingBody %j", ingBody)
var ingredientsInsert = {
name: ingBody
}
var recipeUpdate = Recipe.update({
source_url: sourceUrl
}, {
$push: {
ingredients: ingredientsInsert
}
}, function(err, ingredients) {
if (err) {
console.error(err);
} else {
console.log(" bad ing success!");
}
})
}
}
})
} else if (response.statusCode === 200) {
result.forEach(function(ingredient) {
processNutrientsHandler(ingredient, sourceUrl, ingBody)
})
finalCallback(null, result);
}
}
});
});
}
//callback function from individual recipes.THIS IS THE RESPONSE WITH INDIVIDUAL RECIPE. From the response, it gets an array of ingredients which will be used to make an http request.
function processRemoteRecipe(error, response, body) {
if (error) {
console.log("processRemoteRecipes: ERROR = " + error);
} else {
var body = JSON.parse(response.body);
var recipe = body.recipe;
var recipePublisher = recipe.publisher;
var recipeIngredients = recipe.ingredients;
//filtering recipes according to publishes so that it will easy to scrape methods from the same site.
if (recipePublisher === "All Recipes") {
var source_url = recipe.source_url;
var rec = Recipe.create({
title: recipe.title,
// ingredients: recipe.ingredients,
source_url: recipe.source_url,
image_url: recipe.image_url,
recipe_id: recipe.recipe_id
});
console.log("create recipe: %j", rec);
// calls getIngredientNutrients to make a http request to get nutrition details
// getIngredientNutrients(recipeIngredients, source_url, function(r) {
// return;
// });
(new Promise(function(resolve, reject) {
getIngredientNutrients(recipeIngredients, source_url, function(e, r) {
if (e) {
return reject(e);
}
resolve(r);
});
})).then(function() {
calculateValues();
}).catch(function(err) {
});
}
}
}
//make http request to api to get individual revipe details
function getRemoteRecipe(recipe) {
console.log("getRemoteRecipe:")
//stores the recipe id for each recipe and then uses it to make individual http calls
var recipeId = recipe.recipe_id;
var recipeUrl = "http://food2fork.com/api/get?key=ef82898c8dec1bd923cf8abcec885398&rId=";
recipeUrl += recipeId;
request({
url: recipeUrl,
method: 'GET'
}, processRemoteRecipe)
}
//call back function after list of recipes. Use the recipe id for each recipe in the list to make individual http requests to get recipe details.
function handleListRecipes(error, response, body) {
if (error) {
} else {
var body = JSON.parse(response.body);
var count = body.count;
var recipes = body.recipes;
recipes.forEach(getRemoteRecipe);
}
};
//Gets a list of recipes from api which will give recipe id and some other info for each recipe.
function listRecipes() {
request_params = {
url: 'http://food2fork.com/api/search?key=ef82898c8dec1bd923cf8abcec885398&page=5',
method: 'GET'
};
//make request to api to get list of recipes. handleListRecipes is the callback function
request(request_params, handleListRecipes);
};
//invokes listRecipes
listRecipes();
// calculateValues();
var server = app.listen(3000, function() {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
|
import React from 'react';
import axios from 'axios'
import Header from './components/ui/header'
import Search from './components/ui/search'
import CharacterGrid from './components/characters/characterGrid'
import './App.css';
function App() {
const [items, setItems] = React.useState([])
const [isLoading, setIsLoading] = React.useState(true)
const [query, setQuery] = React.useState('')
React.useEffect(function(){
const fetchItems = async function(){
const result = await axios(`https://www.breakingbadapi.com/api/characters?name=${query}`)
setItems(result.data)
setIsLoading(false)
}
fetchItems()
}, [query])
return (
<div className="container">
< Header />
< Search getQuery={function(q){setQuery(q)}}/>
< CharacterGrid isLoading = {isLoading} items = {items} />
</div>
);
}
export default App;
|
const QueryType = require('./QueryType')
const MutationType = require('./MutationType')
const { GraphQLSchema } = require('graphql');
module.exports = new GraphQLSchema({ query: QueryType, mutation: MutationType });
|
import Light from './light'
class RbgLight extends Light {
constructor(identity,name,realm,defaultState = 'on',attributes,data){
super(identity,name,realm,defaultState,attributes,data);
this.type = 'light';
this.supports = [Light.RBG_COLOR, Light.DIMMERABLE];
}
}
export default RbgLight;
|
// node myFile.js
const pendingTimers = [] // setTimeout, timer stuff
const pendingOSTasks = [] // networking stuff
const pendingOperations = [] // filesystem stuff
// New timers, tasks, operations are recorded from myFile running
myFile.runContents()
function shouldContinue() {
// Check one : Any pending setTimeout, setInterval, setImmediate?
// Check two : Any pending OS tasks? (Like server listening to port)
// Check three: Any pending long running operations? (Like fs module)
return (
pendingTimers.length ||
pendingOSTasks.length ||
pendingOperations.length
)
}
// Entire body executes in one 'tick' (tick -> one loop execution)
while (shouldContinue()) {
/*
1) Node looks at pendingTimers and sees if any functions are ready to be called. setTimeout, setInterval
a) runs expired timers callbacks
2) Node looks at pendingOSTasks and pendingOperations and calls relevant callbacks
a) pendingOSTasks -> some request comes into some ports at which a server is listening on
b) pendingOperations -> some file is successfully retrieve from our harddrive
during this stage node will detect that those things have been completed and will call
the relevant callbacks like callback to handle incomming request
3) Pause execution(temporarily). Continue when...(whenever some number of events occur)
a) a new pendingOSTask is done
b) a new pendingOperation is done
c) a timer is about to complete
(gives time to finish callback functions or wait for timer)
4) Look at pendingTimers. Call any setImmediate
5) Handle any 'close' events
a) readStream.on('close', () => {
console.log('Cleanup code.');
})
b) terminate any open file
c) terminates any running server
*/
}
// exit back to terminal
/* *********************************************************************************************************************************** */
/*
Node Event Loop ---------------------> Single Threaded
Some of Node Framework/Std Lib ---------------------> Not Single Threaded
Like pbkdf2 function available in crypto module does not run in single thread. It uses multithreading of
Node's C++ side (libuv) i.e. Thread Pool (by default there are four threads inside thread pool). We can
manupluate number of threads to use for any core node function that uses multithreading by
process.env.UV_THREADPOOL_SIZE = <number-of-threads>
e.g. process.env.UV_THREADPOOL_SIZE = 6
Here lets us take process.env.UV_THREADPOOL_SIZE = 4, then
Javascript Code We Write
|
|
pbkdf2 -------> Node's crypto Module
|
|
*V8*
|
|
Nodo's C++ Side
|
|
________________________
| libuv |
| ____________ |
| thread | #1 | #2 | |
| pool |_____|______| |
| | #3 | #4 | |
| |_____|______| |
|________________________|
Here if we run some heavy hashing 2 times then it will not wait for first to finish but it will be assigned
to other thread which is ready to work. Hence for 4 pbkdf2 function calls they will run concurrently in 4 threads,
but if 5 heavy pbkdf2 function is called when 4 threads is available then 4 functions call are called using 4 threads
and last call will have to wait for a thread (any one of 4 threads) to be ready.
but here performance will not be as good as when we run one functional call with one thread because one core might be
handling two threads hence it has to do more work to finish it.
__________________Questions_____________________________________________Answers_____________________________
| || |
| Can we use the threadpool for Javascript || We can write custom JS that uses the thread pool |
| code or can only nodeJS functions use it. || |
| || |
| What functionss in node std library || All 'fs' modules functions. Some crypto stuff. Depends |
| use the threadpool? || on OS (windows vs unix based) |
| || |
| How does this threadpool stuff fit || Tasks running in the threadpool are the 'pendingOperations' |
| into event loop || in our code example. |
|____________________________________________||______________________________________________________________|
Useful articles
https://medium.com/@pkostohrys/nodejs-worker-threads-24155706765
https://blog.logrocket.com/a-complete-guide-to-threads-in-node-js-4fa3898fe74f/
Cluster vs Worker Threads
There are two ways of optimizing the performance of our nodejs application
1) Cluster
-> e.g. By default nodejs app runs on single thread even if you have 4,8 core processor. Let's say you have 4 core CPU
If we want to increase handle more traffic we can run 4 instances of our app in 4 cores of our CPU and hence
we can handle 4 times the traffic before.
i) Each process has it's own memory with it's own Node(v8) instance.
ii) One process is launched on each CPU
It can be done by using `cluster` module from node
and calling cluster.fork() each time will run a new instance of nodejs app in different core
cluster.js
const cluster = require('cluster')
if(cluster.isMaster){
const cpuCount = require('os').cpus().length
create worker for each CPU
for(let i=0;i< cpuCount; i++){
cluster.fork()
}
Listen to dying worker and create a new worker again
cluster.on('exit', function(){
cluster.fork()
})
}
cluster.fork() when run it will run main index.js on new instance
so isMasetr will be falsed for other previous instance where index.js
might be running
2) Worker Thread
-> Previously worker threads was not available in nodejs but after version 10 it is available. It allows us to use
threadpool. Internally threadpool is mainly used by modules such as fs (I/0-heavy) or crypto (CPU-heavy). Worker
pool is implemented in libuv, which results in a slight delay whenever Node needs to communicate internally]
between Javascript and C++, but this is hardly noticeable
It can be done by using `worker_threads` module from node
we can communicate with running threads via onmessage and postMessage
**index.js**
const express = require('express')
const { Worker, isMainThread } = require('worker_threads')
const app = express()
app.get('/', (req, res) => {
if (isMainThread) {
const worker = new Worker('./worker.js')
worker.on('message', message => {
console.log(message)
res.json(message)
})
}
})
app.listen(3000)
**worker.js**
const { workerData, parentPort } = require('worker_threads')
function count() {
let counter = 0
while (counter < 1e9) {
counter++
}
return counter
}
parentPort.postMessage(count())
Santosh Subedi
FullStack Developer At Burgeon
*/
|
var route = require('express').Router();
var tasks = require('./tasks');
var knex = require('../db/knex');
var methods = require('../methods');
module.exports = route;
route.use('/:id', function(request, response, next) {
request.routeChain = request.routeChain || {};
request.routeChain.planitId = request.params.id;
next();
});
route.use('/:id/tasks', tasks);
// C
route.post('/', function(request, response, next) {
if (request.user) {
request.body.member_id = request.user.id;
knex('planits').returning('*').insert(request.body).then(function(planits) {
response.json({ success: true, planits: planits });
}).catch(next);
} else {
next('You must be logged in to perform this action');
}
});
// R
route.get('/:id', function(request, response, next) {
var where = {
'planits.id': request.params.id
};
if (request.routeChain && request.routeChain.memberId) {
where.member_id = request.routeChain.memberId;
}
route.readOne(where).then(function(data) {
response.json(data);
}).catch(next);
});
// U
route.put('/:id', function(request, response, next) {
methods.getPermission(request.user.id).then(function(permission) {
return knex('planits').where('id', request.params.id).then(function(planits) {
var planit = planits[0];
if (request.user.id == planit.member_id || request.user.role_name == 'admin') {
return knex('planits').where('id', request.params.id).update(request.body).then(function() {
response.json({ success: true });
});
} else {
next('You do not have permission to perform this action');
}
});
}).catch(next);
});
// D
route.delete('/:id', function(request, response, next) {
methods.getPermission(request.user.id).then(function(permission) {
return knex('planits').where('id', request.params.id).then(function(planits) {
var planit = planits[0];
if (request.user.id == planit.member_id || request.user.role_name == 'admin') {
return knex('planits').where('id', request.params.id).del().then(function() {
response.json({ success: true });
});
} else {
next('You do not have permission to perform this action');
}
});
}).catch(next);
});
// L
route.get('/', function(request, response, next) {
var where = {};
if (request.routeChain && request.routeChain.memberId) {
where.member_id = request.routeChain.memberId;
}
route.readAll(where).then(function(data) {
response.json(data);
}).catch(next);
});
route.readOne = function(where) {
return Promise.all([
knex('planits').select('planits.*', 'planit_types.name as planit_type_name')
.innerJoin('planit_types', 'planits.planit_type_id', 'planit_types.id')
.where(where)
.orderBy('start_date', 'asc'),
tasks.readAll({ planit_id: where['planits.id'] })
]).then(function(data) {
var planits = data[0];
var tasks = data[1].tasks;
return knex('planits').sum('tasks.budget as allocated')
.innerJoin('tasks', 'tasks.planit_id', 'planits.id')
.where(where).then(function(allocated) {
planits[0].allocated = allocated[0].allocated || 0;
planits[0].budget_remaining = planits[0].budget - planits[0].allocated;
return Promise.resolve({ planits: planits, tasks: tasks });
});
});
};
route.readAll = function(where) {
return knex('planits').select('planits.*', 'planit_types.name as planit_type_name')
.innerJoin('members', 'planits.member_id', 'members.id')
.innerJoin('planit_types', 'planits.planit_type_id', 'planit_types.id')
.where(where).where('end_date', '>=', new Date(Date.now())).whereNot('is_banned', true)
.orderBy('start_date', 'asc')
.then(function(planits) {
return Promise.resolve({ planits: planits });
});
};
|
import React from 'react';
import { Meteor } from 'meteor/meteor';
import { Accounts } from 'meteor/accounts-base';
import { Link } from 'react-router';
import { browserHistory } from 'react-router';
import { renderErrorsFor } from '../../modules/utils';
import {addFolder} from '../../api/folders/methods';
export class Signup extends React.Component {
constructor(props) {
super(props);
this.state = {
errors: {}
};
this._handleSubmit = this._handleSubmit.bind(this);
}
_handleSubmit(event) {
event.preventDefault();
const inputData = {
email: this.refs.email.value,
password: this.refs.password.value,
passwordConfirmation: this.refs.passwordConfirmation.value,
};
if(this._validateInputData(inputData)){
Accounts.createUser({
email: inputData.email,
password: inputData.password
}, function(error) {
if (error) {
Bert.alert(error.reason, 'danger');
} else {
addFolder.call({ name: 'Home', description: null, isPrivate: true }, null);
browserHistory.push('/');
Bert.alert('Welcome!', 'success');
}
// Meteor.setTimeout(function(){ FlowRouter.go('folders'); }, 10);
// const { location } = component.props;
// if (location.state && location.state.nextPathname) {
// browserHistory.push(location.state.nextPathname);
// } else {
// browserHistory.push('/');
// }
});
}
}
_validateInputData(inputData) {
let errors = {};
if (! inputData.email) {
errors.email = 'Email required';
}
if (! inputData.password) {
errors.password = 'Password required';
}
else if (inputData.password.length < 6) {
errors.password = 'Password must be at least 6 characters.';
}
if (inputData.passwordConfirmation !== inputData.password) {
errors.passwordConfirmation = 'Passwords do not match';
}
this.setState({errors: errors});
return (Object.keys(errors).length === 0);
}
render() {
const errors = this.state.errors;
return (
<div className='view-container sessions new'>
<main>
<header>
<div className="logo" />
</header>
<form ref="signup" id="sign_up_form" onSubmit={this._handleSubmit}>
<div className="field">
<input ref="email" id="email" type="email" placeholder="Email" required={true} />
{renderErrorsFor(errors, 'email')}
</div>
<div className="field">
<input ref="password" id="password" type="password" placeholder="Password" required={true} />
{renderErrorsFor(errors, 'password')}
</div>
<div className="field">
<input ref="passwordConfirmation" id="passwordConfirmation" type="password" placeholder="Confirm password" required={true} />
{renderErrorsFor(errors, 'passwordConfirmation')}
</div>
<button type="submit">Sign Up</button>
</form>
<Link to="/login">Have account? Log In</Link>
</main>
</div>
);
}
}
|
import React, { useState } from "react";
import { Filter } from "./Filter";
import AddMovie from "./AddMovie";
import { Navbar, Form, Nav, Image, Button, FormControl } from "react-bootstrap";
const NavBar = ({ handleAdd, handleinput, searchinit, handlerate }) => {
const [modalShow, setModalShow] = React.useState(false);
const [text, setText] = useState("");
return (
<div>
<Navbar bg="dark" variant="dark">
<Image
src="http://www.cuevasandalucia.es/es/images/logos/netflix-logo.png"
style={{ height: 30 }}
/>
<Navbar.Brand href="#home"></Navbar.Brand>
<Nav className="mr-auto">
{" "}
<Button variant="outline-info" onClick={() => setModalShow(true)}>
Add Movie
</Button>
<AddMovie
handleAdd={handleAdd}
setModalShow={setModalShow}
show={modalShow}
onHide={() => setModalShow(false)}
/>
<Filter handlerate={handlerate} />
</Nav>
<Form inline>
<FormControl
type="text"
placeholder="Search"
className="mr-sm-2"
onChange={(e) => {
setText(e.target.value);
}}
value={text}
/>
<Button
variant="outline-info"
onClick={() => {
handleinput(text);
}}
>
Search
</Button>
<Button
variant="outline-info"
onClick={() => {
searchinit();
}}
>
Reset
</Button>
</Form>
</Navbar>
</div>
);
};
export default NavBar;
|
var mongoose = require('mongoose');
var Notificacion = require('../models/notificacion');
var UserML = require('../models/userML');
var Accion = require('../models/accion');
var meli = require('mercadolibre');
var client = require('../config/mlClient');
var meliObject = new meli.Meli(client.id, client.secret);
var needle = require('needle');
module.exports.escuchoNotificaciones = function (req, res ) {
//guardarNotificacion(req, res)
procesarAccion(req, res)
res.json({success: true});
}
function procesarAccion(req, res) {
UserML.findOne({
id_ml: req.body.user_id
}, (err, user) => {
if (user) {
meliObject.get( req.body.resource, { access_token: user.token}, (request, datos ) => {
//guardarDatosAccion(datos)
ejecutarAccion(datos, user.id_cuenta)
})
}
})
}
function ejecutarAccion(datos, cuenta_id) {
//agregar pregunta al csv
console.log(datos)
}
|
/**
* Formulaire du billetage
* Remplissage automatique des champs
* @author: Delrodie AMOIKON
* @date: 23/06/2017
* @version: v1.0
*/
//Formatage de la monnaie
function format(number) {
var numberStr = parseFloat(number).toFixed(2).toString();
var numFormatDec = numberStr.slice(-2); /*decimal 00*/
numberStr = numberStr.substring(0, numberStr.length - 3); /*cut last 3 strings*/
var numFormat = new Array;
while (numberStr.length > 3) {
numFormat.unshift(numberStr.slice(-3));
numberStr = numberStr.substring(0, numberStr.length - 3);
}
numFormat.unshift(numberStr);
return numFormat.join('.'); /*+','+numFormatDec format 000.000.000,00 */
}
/**
* Test de l'existence de la valeur
* Si valeur supérieure a 0 alors garder valeur
* Sinon affecter a valeur 0
*
* @author Delrodie AMOIKON
* @date 02/05/2017
*/
function existance(number) {
if (number > 0) {
return number;
} else {
return 0;
}
}
/**
* Calcul du montant total d'ouverture de caisse
*
* @author: Delrodie AMOIKON
* @date 23/06/2017
*/
function caisseMat()
{
var dixmilleMat = parseFloat(document.getElementById("billetageForm").elements["appbundle_arrete_dixmilleMat"].value);
var cinqmilleMat = parseFloat(document.getElementById("billetageForm").elements["appbundle_arrete_cinqmilleMat"].value);
var deuxmilleMat = parseFloat(document.getElementById("billetageForm").elements["appbundle_arrete_deuxmilleMat"].value);
var milleMat = parseFloat(document.getElementById("billetageForm").elements["appbundle_arrete_milleMat"].value);
var cinqcentMat = parseFloat(document.getElementById("billetageForm").elements["appbundle_arrete_cinqcentMat"].value);
var deuxcentMat = parseFloat(document.getElementById("billetageForm").elements["appbundle_arrete_deuxcentMat"].value);
var centMat = parseFloat(document.getElementById("billetageForm").elements["appbundle_arrete_centMat"].value);
var cinquanteMat = parseFloat(document.getElementById("billetageForm").elements["appbundle_arrete_cinquanteMat"].value);
var vingtcinqMat = parseFloat(document.getElementById("billetageForm").elements["appbundle_arrete_vingtcinqMat"].value);
var dixMat = parseFloat(document.getElementById("billetageForm").elements["appbundle_arrete_dixMat"].value);
var cinqMat = parseFloat(document.getElementById("billetageForm").elements["appbundle_arrete_cinqMat"].value);
var totMat = parseFloat(document.getElementById("billetageForm").elements["appbundle_arrete_totMat"].value);
// Calcul de la somme totale
dixMille = 10000 * existance(dixmilleMat);
cinqMille = 5000 * existance(cinqmilleMat);
deuxMille = 2000 * existance(deuxmilleMat);
mille = 1000 * existance(milleMat);
cinqCent = 500 * existance(cinqcentMat);
deuxCent = 200 * existance(deuxcentMat);
cent = 100 * existance(centMat);
cinquante = 50 * existance(cinquanteMat);
vingtcinq = 25 * existance(vingtcinqMat);
dix = 10 * existance(dixMat);
cinq = 5 * existance(cinqMat);
// Calcul de la monnaie
var total = dixMille + cinqMille + deuxMille + mille + cinqCent + deuxCent + cent + cinquante + vingtcinq + dix + cinq;
return existance(total);
}
/**
* Traitement du formulaire du billetage selon 10.000
*
* @author: Delrodie AMOIKON
* @date: 23/06/2017
*/
function dixmilleMat()
{
var dixmilleMat = parseFloat(document.getElementById("billetageForm").elements["appbundle_arrete_dixmilleMat"].value);
if (!isNaN(dixmilleMat)) {
document.getElementById("billetageForm").elements["appbundle_arrete_totMat"].value = caisseMat();
} else {
document.getElementById("billetageForm").elements["appbundle_arrete_dixmilleMat"].value = 0;
document.getElementById("billetageForm").elements["appbundle_arrete_totMat"].value = caisseMat();
}
}
/**
* Traitement du formulaire du billetage selon 5.000
*
* @author: Delrodie AMOIKON
* @date: 23/06/2017
*/
function cinqmilleMat()
{
var cinqmilleMat = parseFloat(document.getElementById("billetageForm").elements["appbundle_arrete_cinqmilleMat"].value);
if (!isNaN(cinqmilleMat)) {
document.getElementById("billetageForm").elements["appbundle_arrete_totMat"].value = caisseMat();
} else {
document.getElementById("billetageForm").elements["appbundle_arrete_cinqmilleMat"].value = 0;
document.getElementById("billetageForm").elements["appbundle_arrete_totMat"].value = caisseMat();
}
}
/**
* Traitement du formulaire du billetage selon 2.000
*
* @author: Delrodie AMOIKON
* @date: 23/06/2017
*/
function deuxmilleMat()
{
var deuxmilleMat = parseFloat(document.getElementById("billetageForm").elements["appbundle_arrete_deuxmilleMat"].value);
if (!isNaN(deuxmilleMat)) {
document.getElementById("billetageForm").elements["appbundle_arrete_totMat"].value = caisseMat();
} else {
document.getElementById("billetageForm").elements["appbundle_arrete_deuxmilleMat"].value = 0;
document.getElementById("billetageForm").elements["appbundle_arrete_totMat"].value = caisseMat();
}
}
/**
* Traitement du formulaire du billetage selon 1.000
*
* @author: Delrodie AMOIKON
* @date: 23/06/2017
*/
function milleMat()
{
var milleMat = parseFloat(document.getElementById("billetageForm").elements["appbundle_arrete_milleMat"].value);
if (!isNaN(milleMat)) {
document.getElementById("billetageForm").elements["appbundle_arrete_totMat"].value = caisseMat();
} else {
document.getElementById("billetageForm").elements["appbundle_arrete_milleMat"].value = 0;
document.getElementById("billetageForm").elements["appbundle_arrete_totMat"].value = caisseMat();
}
}
/**
* Traitement du formulaire du billetage selon 500
*
* @author: Delrodie AMOIKON
* @date: 23/06/2017
*/
function cinqcentMat()
{
var cinqcentMat = parseFloat(document.getElementById("billetageForm").elements["appbundle_arrete_cinqcentMat"].value);
if (!isNaN(cinqcentMat)) {
document.getElementById("billetageForm").elements["appbundle_arrete_totMat"].value = caisseMat();
} else {
document.getElementById("billetageForm").elements["appbundle_arrete_cinqcentMat"].value = 0;
document.getElementById("billetageForm").elements["appbundle_arrete_totMat"].value = caisseMat();
}
}
/**
* Traitement du formulaire du billetage selon 200
*
* @author: Delrodie AMOIKON
* @date: 23/06/2017
*/
function deuxcentMat()
{
var deuxcentMat = parseFloat(document.getElementById("billetageForm").elements["appbundle_arrete_deuxcentMat"].value);
if (!isNaN(deuxcentMat)) {
document.getElementById("billetageForm").elements["appbundle_arrete_totMat"].value = caisseMat();
} else {
document.getElementById("billetageForm").elements["appbundle_arrete_deuxcentMat"].value = 0;
document.getElementById("billetageForm").elements["appbundle_arrete_totMat"].value = caisseMat();
}
}
/**
* Traitement du formulaire du billetage selon 100
*
* @author: Delrodie AMOIKON
* @date: 23/06/2017
*/
function centMat()
{
var centMat = parseFloat(document.getElementById("billetageForm").elements["appbundle_arrete_centMat"].value);
if (!isNaN(centMat)) {
document.getElementById("billetageForm").elements["appbundle_arrete_totMat"].value = caisseMat();
} else {
document.getElementById("billetageForm").elements["appbundle_arrete_centMat"].value = 0;
document.getElementById("billetageForm").elements["appbundle_arrete_totMat"].value = caisseMat();
}
}
/**
* Traitement du formulaire du billetage selon 50
*
* @author: Delrodie AMOIKON
* @date: 23/06/2017
*/
function cinquanteMat()
{
var cinquanteMat = parseFloat(document.getElementById("billetageForm").elements["appbundle_arrete_cinquanteMat"].value);
if (!isNaN(cinquanteMat)) {
document.getElementById("billetageForm").elements["appbundle_arrete_totMat"].value = caisseMat();
} else {
document.getElementById("billetageForm").elements["appbundle_arrete_cinquanteMat"].value = 0;
document.getElementById("billetageForm").elements["appbundle_arrete_totMat"].value = caisseMat();
}
}
/**
* Traitement du formulaire du billetage selon 25
*
* @author: Delrodie AMOIKON
* @date: 23/06/2017
*/
function vingtcinqMat()
{
var vingtcinqMat = parseFloat(document.getElementById("billetageForm").elements["appbundle_arrete_vingtcinqMat"].value);
if (!isNaN(vingtcinqMat)) {
document.getElementById("billetageForm").elements["appbundle_arrete_totMat"].value = caisseMat();
} else {
document.getElementById("billetageForm").elements["appbundle_arrete_vingtcinqMat"].value = 0;
document.getElementById("billetageForm").elements["appbundle_arrete_totMat"].value = caisseMat();
}
}
/**
* Traitement du formulaire du billetage selon 10
*
* @author: Delrodie AMOIKON
* @date: 23/06/2017
*/
function dixMat()
{
var dixMat = parseFloat(document.getElementById("billetageForm").elements["appbundle_arrete_dixMat"].value);
if (!isNaN(dixMat)) {
document.getElementById("billetageForm").elements["appbundle_arrete_totMat"].value = caisseMat();
} else {
document.getElementById("billetageForm").elements["appbundle_arrete_dixMat"].value = 0;
document.getElementById("billetageForm").elements["appbundle_arrete_totMat"].value = caisseMat();
}
}
/**
* Traitement du formulaire du billetage selon 5
*
* @author: Delrodie AMOIKON
* @date: 23/06/2017
*/
function cinqMat()
{
var cinqMat = parseFloat(document.getElementById("billetageForm").elements["appbundle_arrete_cinqMat"].value);
if (!isNaN(cinqMat)) {
document.getElementById("billetageForm").elements["appbundle_arrete_totMat"].value = caisseMat();
} else {
document.getElementById("billetageForm").elements["appbundle_arrete_cinqMat"].value = 0;
document.getElementById("billetageForm").elements["appbundle_arrete_totMat"].value = caisseMat();
}
}
/*
=======================================================================
================== SOIR ============================
======================================================================= */
/**
* Calcul du montant total de cloture
*
* @author: Delrodie AMOIKON
* @date 27/06/2017
*/
function caisseSoir()
{
var dixmilleMat = parseFloat(document.getElementById("billetageForm").elements["appbundle_arrete_dixmilleMat"].value);
var cinqmilleMat = parseFloat(document.getElementById("billetageForm").elements["appbundle_arrete_cinqmilleMat"].value);
var deuxmilleMat = parseFloat(document.getElementById("billetageForm").elements["appbundle_arrete_deuxmilleMat"].value);
var milleMat = parseFloat(document.getElementById("billetageForm").elements["appbundle_arrete_milleMat"].value);
var cinqcentMat = parseFloat(document.getElementById("billetageForm").elements["appbundle_arrete_cinqcentMat"].value);
var deuxcentMat = parseFloat(document.getElementById("billetageForm").elements["appbundle_arrete_deuxcentMat"].value);
var centMat = parseFloat(document.getElementById("billetageForm").elements["appbundle_arrete_centMat"].value);
var cinquanteMat = parseFloat(document.getElementById("billetageForm").elements["appbundle_arrete_cinquanteMat"].value);
var vingtcinqMat = parseFloat(document.getElementById("billetageForm").elements["appbundle_arrete_vingtcinqMat"].value);
var dixMat = parseFloat(document.getElementById("billetageForm").elements["appbundle_arrete_dixMat"].value);
var cinqMat = parseFloat(document.getElementById("billetageForm").elements["appbundle_arrete_cinqMat"].value);
var totMat = parseFloat(document.getElementById("billetageForm").elements["appbundle_arrete_totMat"].value);
var dixmilleSoir = parseFloat(document.getElementById("billetageForm").elements["appbundle_arrete_dixmilleSoir"].value);
var cinqmilleSoir = parseFloat(document.getElementById("billetageForm").elements["appbundle_arrete_cinqmilleSoir"].value);
var deuxmilleSoir = parseFloat(document.getElementById("billetageForm").elements["appbundle_arrete_deuxmilleSoir"].value);
var milleSoir = parseFloat(document.getElementById("billetageForm").elements["appbundle_arrete_milleSoir"].value);
var cinqcentSoir = parseFloat(document.getElementById("billetageForm").elements["appbundle_arrete_cinqcentSoir"].value);
var deuxcentSoir = parseFloat(document.getElementById("billetageForm").elements["appbundle_arrete_deuxcentSoir"].value);
var centSoir = parseFloat(document.getElementById("billetageForm").elements["appbundle_arrete_centSoir"].value);
var cinquanteSoir = parseFloat(document.getElementById("billetageForm").elements["appbundle_arrete_cinquanteSoir"].value);
var vingtcinqSoir = parseFloat(document.getElementById("billetageForm").elements["appbundle_arrete_vingtcinqSoir"].value);
var dixSoir = parseFloat(document.getElementById("billetageForm").elements["appbundle_arrete_dixSoir"].value);
var cinqSoir = parseFloat(document.getElementById("billetageForm").elements["appbundle_arrete_cinqSoir"].value);
var totSoir = parseFloat(document.getElementById("billetageForm").elements["appbundle_arrete_totSoir"].value);
// Calcul de la somme totale
dixMille = 10000 * existance(dixmilleSoir);
cinqMille = 5000 * existance(cinqmilleSoir);
deuxMille = 2000 * existance(deuxmilleSoir);
mille = 1000 * existance(milleSoir);
cinqCent = 500 * existance(cinqcentSoir);
deuxCent = 200 * existance(deuxcentSoir);
cent = 100 * existance(centSoir);
cinquante = 50 * existance(cinquanteSoir);
vingtcinq = 25 * existance(vingtcinqSoir);
dix = 10 * existance(dixSoir);
cinq = 5 * existance(cinqSoir);
// Calcul de la monnaie
var total = dixMille + cinqMille + deuxMille + mille + cinqCent + deuxCent + cent + cinquante + vingtcinq + dix + cinq;
return existance(total);
}
/**
* Traitement du formulaire du billetage selon 10.000
*
* @author: Delrodie AMOIKON
* @date: 27/06/2017
*/
function dixmilleSoir()
{
var dixmilleSoir = parseFloat(document.getElementById("billetageForm").elements["appbundle_arrete_dixmilleSoir"].value);
if (!isNaN(dixmilleSoir)) {
document.getElementById("billetageForm").elements["appbundle_arrete_totSoir"].value = caisseSoir();
} else {
document.getElementById("billetageForm").elements["appbundle_arrete_dixmilleSoir"].value = 0;
document.getElementById("billetageForm").elements["appbundle_arrete_totSoir"].value = caisseSoir();
}
}
/**
* Traitement du formulaire du billetage selon 5.000
*
* @author: Delrodie AMOIKON
* @date: 23/06/2017
*/
function cinqmilleSoir()
{
var cinqmilleSoir = parseFloat(document.getElementById("billetageForm").elements["appbundle_arrete_cinqmilleSoir"].value);
if (!isNaN(cinqmilleSoir)) {
document.getElementById("billetageForm").elements["appbundle_arrete_totSoir"].value = caisseSoir();
} else {
document.getElementById("billetageForm").elements["appbundle_arrete_cinqmilleSoir"].value = 0;
document.getElementById("billetageForm").elements["appbundle_arrete_totSoir"].value = caisseSoir();
}
}
/**
* Traitement du formulaire du billetage selon 2.000
*
* @author: Delrodie AMOIKON
* @date: 23/06/2017
*/
function deuxmilleSoir()
{
var deuxmilleSoir = parseFloat(document.getElementById("billetageForm").elements["appbundle_arrete_deuxmilleSoir"].value);
if (!isNaN(deuxmilleSoir)) {
document.getElementById("billetageForm").elements["appbundle_arrete_totSoir"].value = caisseSoir();
} else {
document.getElementById("billetageForm").elements["appbundle_arrete_deuxmilleSoir"].value = 0;
document.getElementById("billetageForm").elements["appbundle_arrete_totSoir"].value = caisseSoir();
}
}
/**
* Traitement du formulaire du billetage selon 1.000
*
* @author: Delrodie AMOIKON
* @date: 23/06/2017
*/
function milleSoir()
{
var milleSoir = parseFloat(document.getElementById("billetageForm").elements["appbundle_arrete_milleSoir"].value);
if (!isNaN(milleSoir)) {
document.getElementById("billetageForm").elements["appbundle_arrete_totSoir"].value = caisseSoir();
} else {
document.getElementById("billetageForm").elements["appbundle_arrete_milleSoir"].value = 0;
document.getElementById("billetageForm").elements["appbundle_arrete_totSoir"].value = caisseSoir();
}
}
/**
* Traitement du formulaire du billetage selon 500
*
* @author: Delrodie AMOIKON
* @date: 23/06/2017
*/
function cinqcentSoir()
{
var cinqcentSoir = parseFloat(document.getElementById("billetageForm").elements["appbundle_arrete_cinqcentSoir"].value);
if (!isNaN(cinqcentSoir)) {
document.getElementById("billetageForm").elements["appbundle_arrete_totSoir"].value = caisseSoir();
} else {
document.getElementById("billetageForm").elements["appbundle_arrete_cinqcentSoir"].value = 0;
document.getElementById("billetageForm").elements["appbundle_arrete_totSoir"].value = caisseSoir();
}
}
/**
* Traitement du formulaire du billetage selon 200
*
* @author: Delrodie AMOIKON
* @date: 23/06/2017
*/
function deuxcentSoir()
{
var deuxcentSoir = parseFloat(document.getElementById("billetageForm").elements["appbundle_arrete_deuxcentSoir"].value);
if (!isNaN(deuxcentSoir)) {
document.getElementById("billetageForm").elements["appbundle_arrete_totSoir"].value = caisseSoir();
} else {
document.getElementById("billetageForm").elements["appbundle_arrete_deuxcentSoir"].value = 0;
document.getElementById("billetageForm").elements["appbundle_arrete_totSoir"].value = caisseSoir();
}
}
/**
* Traitement du formulaire du billetage selon 100
*
* @author: Delrodie AMOIKON
* @date: 23/06/2017
*/
function centSoir()
{
var centSoir = parseFloat(document.getElementById("billetageForm").elements["appbundle_arrete_centSoir"].value);
if (!isNaN(centSoir)) {
document.getElementById("billetageForm").elements["appbundle_arrete_totSoir"].value = caisseSoir();
} else {
document.getElementById("billetageForm").elements["appbundle_arrete_centSoir"].value = 0;
document.getElementById("billetageForm").elements["appbundle_arrete_totSoir"].value = caisseSoir();
}
}
/**
* Traitement du formulaire du billetage selon 50
*
* @author: Delrodie AMOIKON
* @date: 23/06/2017
*/
function cinquanteSoir()
{
var cinquanteSoir = parseFloat(document.getElementById("billetageForm").elements["appbundle_arrete_cinquanteSoir"].value);
if (!isNaN(cinquanteSoir)) {
document.getElementById("billetageForm").elements["appbundle_arrete_totSoir"].value = caisseSoir();
} else {
document.getElementById("billetageForm").elements["appbundle_arrete_cinquanteSoir"].value = 0;
document.getElementById("billetageForm").elements["appbundle_arrete_totSoir"].value = caisseSoir();
}
}
/**
* Traitement du formulaire du billetage selon 25
*
* @author: Delrodie AMOIKON
* @date: 23/06/2017
*/
function vingtcinqSoir()
{
var vingtcinqSoir = parseFloat(document.getElementById("billetageForm").elements["appbundle_arrete_vingtcinqSoir"].value);
if (!isNaN(vingtcinqSoir)) {
document.getElementById("billetageForm").elements["appbundle_arrete_totSoir"].value = caisseSoir();
} else {
document.getElementById("billetageForm").elements["appbundle_arrete_vingtcinqSoir"].value = 0;
document.getElementById("billetageForm").elements["appbundle_arrete_totSoir"].value = caisseSoir();
}
}
/**
* Traitement du formulaire du billetage selon 10
*
* @author: Delrodie AMOIKON
* @date: 23/06/2017
*/
function dixSoir()
{
var dixSoir = parseFloat(document.getElementById("billetageForm").elements["appbundle_arrete_dixSoir"].value);
if (!isNaN(dixSoir)) {
document.getElementById("billetageForm").elements["appbundle_arrete_totSoir"].value = caisseSoir();
} else {
document.getElementById("billetageForm").elements["appbundle_arrete_dixSoir"].value = 0;
document.getElementById("billetageForm").elements["appbundle_arrete_totSoir"].value = caisseSoir();
}
}
/**
* Traitement du formulaire du billetage selon 5
*
* @author: Delrodie AMOIKON
* @date: 23/06/2017
*/
function cinqSoir()
{
var cinqSoir = parseFloat(document.getElementById("billetageForm").elements["appbundle_arrete_cinqSoir"].value);
if (!isNaN(cinqSoir)) {
document.getElementById("billetageForm").elements["appbundle_arrete_totSoir"].value = caisseSoir();
} else {
document.getElementById("billetageForm").elements["appbundle_arrete_cinqSoir"].value = 0;
document.getElementById("billetageForm").elements["appbundle_arrete_totSoir"].value = caisseSoir();
}
}
|
var timeSlot = $('.time');
var greetSlot = $('.greeting');
var greetList = ['Hello, ', 'Hi, ', 'Greetings, ', 'Salve, ', 'Sveiki, ', 'Guten tag, ', 'Dia dhuit, ', 'Kamusta, ', 'Aloha, ', 'Hola, ']
var randomGreet = Math.floor(Math.random() * greetList.length);
timeSlot.text(moment().format('LT'));
firebase.auth().onAuthStateChanged(function(user) {
if(user) {
greetSlot.text(greetList[randomGreet] + user.displayName.split(" ")[0]);
};
});
setInterval(function() {
timeSlot.text(moment().format('LT'));
}, 5000);
|
var searchData=
[
['cabeza',['cabeza',['../structt__cola.html#aa60b2d7a3752db97b7f9d9163fb48afa',1,'t_cola']]],
['cola',['cola',['../structt__cola.html#ae6eec6efa2dd9d70da13b2a435c3de27',1,'t_cola']]],
['coladebug',['colaDebug',['../group___debug___external___variables.html#ga314fd637d927bd6a2551e119de623aa5',1,'colaDebug(): KNX_Ph.c'],['../group___k_n_x___p_h___sup___private___variables.html#ga314fd637d927bd6a2551e119de623aa5',1,'colaDebug(): KNX_Ph.c']]],
['currenttick',['currentTick',['../group___k_n_x___p_h___sup___private___variables.html#gae5c3d180a41e0a10e05863aa365a5596',1,'KNX_Ph.c']]]
];
|
var vt = vt || {};
vt.SyncManager = cc.Class.extend({
m_dict: null,
m_timeOut: 10000, // 10秒超时
m_isSyncIcon: false, // 是否正在显示超时同步图标
m_curSyncUuid: null,
ctor: function () {
//
this.m_dict = {};
var scheduler = cc.Director._getInstance().getScheduler();
scheduler.scheduleUpdateForTarget(this, 0, false);
},
/**
* 添加一个消息超时监控
* @param uuid
* @param callback
*/
add: function (uuid, callback) {
var time = new Date().getTime();
this.m_dict[uuid] = {"timeStamp": time, "callback": callback};
},
/**
* 删除一个消息超时监控
* @param uuid
*/
remove: function (uuid) {
this.m_dict[uuid] = null;
delete this.m_dict[uuid];
},
/**
* 检查指定消息超时状态
* @param uuid
* @returns {number} 0 已超时 1 未超时
*/
getValidStatus: function (uuid) {
if (!this.m_dict[uuid]){
return 0;
}
return 1;
},
/**
* 开始同步等待转圈
* @param uuid
* @param isSync [是否同步界面超时]
* @param callback
*/
addSync: function (uuid, isSync, callback) {
this.add(uuid, callback);
if (isSync) {
this.showSyncIcon(uuid);
}
},
/**
* 获取当前是否正在显示同步超时图标
* @returns {boolean}
*/
isSyncIcon: function () {
return this.m_isSyncIcon;
},
/**
* 开始显示同步超时图标
*/
showSyncIcon: function (uuid) {
//var curScene = vt.SceneManager.getInstance().getCurrScene();
if (this.m_isSyncIcon) {
return;
}
//var syncIcon = curScene.getChildByTag("syncIcon");
//if (syncIcon) {
// syncIcon.setVisible(true);
// syncIcon.runAction(cc.RepeatForever.create(cc.RotateBy.create(1, 360)));
//}
this.m_isSyncIcon = true;
this.m_curSyncUuid = uuid;
},
/**
* 停止显示同步超时图标
*/
stopSyncIcon: function () {
//var curScene = vt.SceneManager.getInstance().getCurrScene();
if (!this.m_isSyncIcon) {
return;
}
//var syncIcon = curScene.getChildByTag("syncIcon");
//if (syncIcon) {
// syncIcon.setVisible(false);
// syncIcon.stopAllActions();
//}
this.m_isSyncIcon = false;
this.m_curSyncUuid = null;
},
/**
* 停止等待超时转圈,执行用户回调
* @param uuid
* @param isTimeOut
*/
stopWaitAndDoCallback: function (uuid, isTimeOut) {
if (!this.m_dict[uuid]){
return;
}
//isTimeOut = !!isTimeOut;
var data = this.m_dict[uuid];
if (data["callback"]){
data["callback"](isTimeOut);
}
this.remove(uuid);
this.stopSyncIcon();
},
checkOut:function(uuid){
// var nowTime = new Date().getTime();
// var data = this.m_dict[uuid];
// var xx = (nowTime - data.timeStamp)/1000;
// vt.Log("checkOut ++++++++++ Time"+ xx);
// if (nowTime - data.timeStamp >= this.m_timeOut){
// }
},
/**
* 检查消息列表,发现超时的消息就清理掉
*/
update: function(){
var nowTime = new Date().getTime();
for (var uuid in this.m_dict){
var data = this.m_dict[uuid];
var _time = nowTime - data.timeStamp;
if (_time >= this.m_timeOut){
if (this.m_isSyncIcon && uuid == this.m_curSyncUuid){
var isOut = {};
isOut.isTimeOut = _time;
isOut.uuid = uuid;
this.stopWaitAndDoCallback(uuid, isOut);
}else {
this.remove(uuid);
}
}
}
}
});
vt.SyncManager.getInstance = function () {
if (!vt.s_pSyncManager) {
vt.s_pSyncManager = new vt.SyncManager();
}
return vt.s_pSyncManager;
};
|
var express = require('express');
var router = express.Router();
var wrap = require('co-express');
var mongoose = require('mongoose');
var Contact = mongoose.model('Contact');
var Category = mongoose.model('Category');
//Allowing Cross origin access
router.all('/*', wrap(function*(request, response, next) {
response.header('Access-Control-Allow-Origin', request.headers.origin);
response.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
response.header('Access-Control-Allow-Headers', 'X-Requested-With');
response.header('Access-Control-Allow-Headers', 'Content-Type');
response.header('Access-Control-Allow-Credentials', 'true');
next();
}));
router.get('/', wrap(function*(request, response, next) {
var contacts = yield Contact.find({}).exec();
var categories = yield Category.find({}).exec();
response.send({
contacts: contacts,
categories: categories
});
}));
router.post('/contact', wrap(function*(request, response, next) {
var form = request.body.form;
var contact = null;
if (form._id)
contact = yield Contact.findOne({ _id: form._id }).exec();
if (contact == null)
contact = new Contact();
contact.name = form.name;
contact.email = form.email;
contact.tel = form.tel;
console.log(form.categories);
contact.categories = form.categories;
contact.markModified('categories');
yield contact.save();
var contacts = yield Contact.find({}).exec();
response.send({
contacts: contacts
});
console.log(contact);
}));
router.delete('/contact/:id', wrap(function*(request, response, next) {
var _id = request.params.id;
yield Contact.remove({ _id: _id}).exec();
var contacts = yield Contact.find({}).exec();
response.send({
contacts: contacts
});
}));
router.post('/category', wrap(function*(request, response, next) {
var form = request.body.form;
var category = null;
if (form._id)
category = yield Category.findOne({ _id: form._id }).exec();
if (category == null)
category = new Category();
category.name = form.name;
yield category.save();
var contacts = yield Contact.find({}).exec();
var categories = yield Category.find({}).exec();
response.send({
contacts: contacts,
categories: categories
});
}));
router.delete('/category/:id', wrap(function*(request, response, next) {
var _id = request.params.id;
var removedCategory = yield Category.findOne({ _id: _id }).exec();
if (removedCategory != null) {
var contacts = yield Contact.find({ categories: removedCategory._id }).exec();
for (var i = 0; i < contacts.length; i++) {
contacts[i].categories.remove(removedCategory);
yield contacts[i].save();
}
yield Category.remove({ _id: _id}).exec();
}
var contacts = yield Contact.find({}).exec();
var categories = yield Category.find({}).exec();
response.send({
contacts: contacts,
categories: categories
});
}));
module.exports = router;
|
(function (doc, win) {
var docEl = doc.documentElement,
resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',
recalc = function () {
var clientWidth = docEl.clientWidth;
if (!clientWidth) return;
docEl.style.fontSize = 100 * (clientWidth / 750) + 'px';
};
if (!doc.addEventListener) return;
win.addEventListener(resizeEvt, recalc, false);
doc.addEventListener('DOMContentLoaded', recalc, false);
})(document, window);
$(function () {
var B = 0.75;
var canvasW = window.innerWidth;
var canvasH = canvasW / B;
if (canvasH > window.innerHeight) canvasH = window.innerHeight;
var canvasObj = $('#canvas');
canvasObj.attr('width', canvasW);
canvasObj.attr('height', canvasH);
var ca = document.getElementById("canvas");
var ctx = ca.getContext("2d");
var bj1 = new Image();
var player = new Image();
var tu = new Array();
var playerWidth = 140 * B;
var playerHeight = 170 * B;
var h = 20;
var gk = 1;
var sudu = 10;
var zl = 100;
var chi = 0;
var shi = 0;
var fs = 0;
var sm = 1;
var bj = bj1;
var flag = false;
function MyObject() {
this.x = 0;
this.y = 0;
this.l = 11;
this.image = new Image();
}
var sprite = new MyObject();
sprite.x = 0;
sprite.y = canvasH - playerHeight - 25;
sprite.image = player;
addListener(ca, "touchmove", m);
var gameTime = 64;
var remainTime;
function checkTime() {
if(flag){
var beginTime = new Date();
}
var nowTime = new Date();
remainTime = gameTime - parseInt((nowTime.getTime() - beginTime.getTime()) / 1000);
document.getElementById('m').innerHTML = remainTime;
}
var range = canvasW - 70 * B;
function chansheng() {
if (shi % h == 0) {
for (var j = 2 * chi; j < 2 * (chi + 1); j++) {
tu[j] = new MyObject();
var i = Math.round(Math.random() * range);
if (j == 2 * chi + 1) {
while (Math.abs(i - tu[2 * chi].x) < 30) {
i = Math.round(Math.random() * range);
}
}
var k = Math.round(Math.random() * zl);
if (k < 60) {
tu[j].image.src = "images/yb_20.png";
tu[j].q = 1;
} else if (k < 80) {
tu[j].image.src = "images/yb_16.png";
tu[j].q = 2;
} else {
tu[j].image.src = "images/yb_18.png";
tu[j].q = 3;
}
tu[j].x = i;
tu[j].y = -Math.round(Math.random() * 300);
}
chi++;
if (chi == 10) chi = 0;
}
shi++;
}
function sudukongzhi() {
if (remainTime > 50) {
h = 20;
sudu = 10;
} else if (remainTime > 40) {
h = 19;
sudu = 20;
} else if (remainTime > 30) {
h = 8;
sudu = 30;
} else if (remainTime > 20) {
h = 7;
sudu = 40;
} else if (remainTime > 10) {
h = 6;
sudu = 50;
} else {
h = 5;
sudu = 60;
}
}
function draw() {
sudukongzhi();
chansheng();
for (var i = 0; i < tu.length; i++) {
if (jiance(sprite, tu[i])) {
if (tu[i].q == 1) {
fs += 8;
} else if (tu[i].q == 2) {
fs += 10;
} else {
fs += -9;
}
tu[i].y += 250;
} else if (!jiance(sprite, tu[i])) {
tu[i].y += sudu;
}
ctx.drawImage(tu[i].image, tu[i].x, tu[i].y, 70 * B, 70 * B);
}
}
function jiance(a, b) {
var c = a.x - b.x;
var d = a.y - b.y;
if (c < b.image.width * B - 30 && c > -a.image.width * B + 60 && d < b.image.height * B && d > -a.image.height * B) {
return true;
} else {
return false;
}
}
function addListener(element, e, fn) {
if (element.addEventListener) {
element.addEventListener(e, fn, false);
} else {
element.attachEvent("on" + e, fn);
}
}
function m(event) {
var touch = event.touches[0];
var x = Number(touch.pageX);
sprite.x = x - playerWidth / 2;
if (sprite.x + playerWidth >= canvasW) sprite.x = canvasW - playerWidth;
else if (sprite.x <= playerWidth / 2 - 50) sprite.x = 0;
}
function stop() {
//clearInterval(interval);
gameStart = null;
if(fs>=800){
$('.success').show();
showMask();
}else{
$('.fail').show();
showMask();
}
}
/* interval = setInterval(function () {
ctx.clearRect(0, 0, canvasW, canvasH);
ctx.drawImage(bj, 0, 0, canvasW, canvasH);
ctx.drawImage(sprite.image, sprite.x, sprite.y, playerWidth, playerHeight);
draw();
document.getElementById("f").innerHTML = fs;
checkTime();
if (remainTime == 0) { stop() }
}, 100); */
//设定倒数秒数
var t = 4;
//显示倒数秒数
function showTime(){
t -= 1;
document.getElementById('second').innerHTML= t;
if(t<0){
$('.countDown').hide();
hideMask();
showTime = null;
flag = true;
gameStart();
}
timer = setTimeout(showTime,1000);
}
function gameStart(){
ctx.clearRect(0, 0, canvasW, canvasH);
ctx.drawImage(bj, 0, 0, canvasW, canvasH);
ctx.drawImage(sprite.image, sprite.x, sprite.y, playerWidth, playerHeight);
draw();
document.getElementById("f").innerHTML = fs;
if(fs<100){
player.src = "images/girl_1.png";
}else if(fs<300&&fs>100){
player.src = "images/girl_2.png";
}else if(fs<600&&fs>300){
player.src = "images/girl_3.png";
}else if(fs>600){
player.src = "images/girl_4.png";
}
checkTime();
if (remainTime == 0) { stop() }
timer_go = setTimeout(gameStart,100);
}
//引导弹窗开始游戏按钮
$('#go').on('click',function(){
$(this).parent().hide();
$('.countDown').show();
showTime();
});
showMask();
//活动规则按钮
$('#ruleBtn').on('click',function(){
$('.rule').show();
showMask();
});
//关闭弹窗
$('.close').on('click',function(){
$(this).parent().hide();
hideMask();
});
//显示遮罩层
function showMask(){
$("#mask").css("height",$(document).height());
$("#mask").css("width",$(document).width());
$("#mask").show();
$('body').css('position','fixed');
}
//隐藏遮罩层
function hideMask(){
$("#mask").hide();
$('body').css('position','unset');
}
});
|
import React,{Component, useDebugValue} from 'react';
import {AppRegistry,FlatList,Image,Text,View,StyleSheet, Switch, Alert, TouchableHighlight, Dimensions,TextInput} from 'react-native';
import Modal from 'react-native-modalbox';
import Button from 'react-native-button';
import flatListData from '../data/FlatListData';
var screen = Dimensions.get('window');
export default class AddModal extends Component{
constructor(props){
super(props);
this.myModal=React.createRef();
this.state={
hours:'',
minutes:'',
note:'',
}
}
showAddModal =()=>{
this.myModal.current.open();
}
render(){
return (
<Modal
ref={this.myModal}
style ={{
justifyContent:'center',
alignItems:'center',
borderRadius: Platform.OS ==='ios'? 30:0,
shadowRadius:10,
padding:10,
width :screen.width-80,
height:280,
}}
position='center'
backdrop ={true}
onClosed={()=>{
}}
>
<View style={{flex:1,flexDirection:'column',backgroundColor:'blue',alignContent:'center'}}>
<Text style={{fontSize:24,fontWeight:'bold',textAlign:'center'}}>Add Alarm </Text>
<View style={styles.row}>
<Text style={styles.text}>Time:</Text>
<View style={{flex:1,flexDirection:'row',backgroundColor:'orange',alignItems:'center'}}>
<TextInput keyboardType={'numeric'} style={styles.timer}
onChangeText={(text)=>{this.setState({hours:text})}}
value={this.state.hours}
></TextInput>
<Text>:</Text>
<TextInput keyboardType={'numeric'} style={styles.timer}
onChangeText={(text)=>{this.setState({minutes:text})}}
value={this.state.minutes}
></TextInput>
</View>
</View>
<View style={styles.row}>
<Text style={[styles.text]}>Note:</Text>
<TextInput style={[styles.note]}
placeholder={'Enter the note'}
onChangeText={(text)=>{this.setState({note:text})}}
value={this.state.note}
>
</TextInput>
</View>
<Button style={{fontSize:18,color:'white'}}
containerStyle={{
padding:8,
marginHorizontal:70,
height:40,
borderRadius:6,
backgroundColor:'mediumseagreen'
}}
onPress={()=>{
if(this.state.hours.length==0||this.state.minutes.length==0||this.state.note.length==0){
alert('You must fill all infomation');
return;
}
const newAlarm={
key:flatListData.length+1,
time:this.state.hours+':'+this.state.minutes,
note:this.state.note
}
flatListData.push(newAlarm);
// flatListData= [...flatListData,newAlarm];
// this.props.refreshFlatList(newAlarm.key);
// alert(newAlarm.key)
this.myModal.current.close();
}}
>
Save
</Button>
</View>
</Modal>
)
}
};
const styles= StyleSheet.create({
btnSave:{
},
row:{
flex:1,
flexDirection:'row',
justifyContent:'flex-start',
alignItems:'center',
backgroundColor:'red'
},
text:{
fontSize:20,
fontWeight:'500',
marginRight:10,
},
timer:{
width:32,
fontSize:24,
borderColor:'#312e35',
borderWidth:1,
borderRadius:5,
height:30,
marginHorizontal:5,
color:'#0D0D0D'
},
note:{
width:180,
height: 24,
fontSize:20,
borderBottomColor:'grey',
marginHorizontal:10,
marginBottom:10,
borderBottomWidth:1,
textAlign:'center',
}
})
|
import Taro from '@tarojs/taro'
import React from 'react'
import { View, Text, ScrollView } from '@tarojs/components'
import { Loading } from '@components'
import { connect } from 'react-redux'
import { getWindowHeight } from '@utils/style'
import Recommend from './recommend'
import './home.scss'
@connect(({ recommendList }) => ({
recommendList,
}))
class Home extends React.Component {
componentDidMount() {
this.loadRecommend();
}
loadRecommend = () => {
const { dispatch } = this.props;
dispatch({
type: 'recommendList/fetch',
});
}
handlePrevent = () => {
// XXX 时间关系,首页只实现底部推荐商品的点击
Taro.showToast({
title: '目前只可点击底部推荐商品',
icon: 'none'
})
}
render () {
const { recommend } = this.props
const {
recommendList: { recommendList },
} = this.props;
const { list=[] } = recommendList;
return (
<View className='home'>
<ScrollView
scrollY
className='home__wrap'
onScrollToLower={this.loadRecommend}
style={{ height: getWindowHeight() }}
>
{/* 为你推荐 */}
<Recommend list={list} />
</ScrollView>
</View>
)
}
}
export default Home
|
function changeModalColor(color)
{
var modals = document.getElementsByClassName("modal");
for(i=0; i<modals.length; i++) {
modals[i].style.backgroundColor = color;
}
}
|
import { h, Component } from 'preact';
import SectionUser from '@/components/LeftBlocks/SectionUser';
import SectionAccounts from '@/components/LeftBlocks/SectionAccounts';
import SectionDocument from '@/components/LeftBlocks/SectionDocuments';
import SectionScopes from '@/components/LeftBlocks/SectionScopes';
import SectionBad from '@/components/LeftBlocks/SectionBad';
export default class LeftMenu extends Component {
render() {
return (
<div className={this.props.className}>
<SectionUser/>
---
<SectionAccounts/>
---
<SectionDocument/>
---
<SectionScopes/>
---
<SectionBad/>
</div>
);
}
}
|
// a declaração desta variável ocorreu devido ao deploy no GCP onde a plataforma aponta a rota de forma difente.
var PORT = process.env.PORT || 3000;
module.exports = function (app) {
app.post('/chat', function (req, res) {
if (PORT === 3000) { // local
app.app.controllers.chat.iniciaChat(app, req, res);
} else {
// GCP
app.controllers.chat.iniciaChat(app, req, res);
}
});
app.get('/chat', function (req, res) {
if (PORT === 3000) { // local
app.app.controllers.chat.iniciaChat(app, req, res);
} else {
// GCP
app.controllers.chat.iniciaChat(app, req, res);
}
});
};
|
// sumZero(sortedArray)
// accept: sorted array
// return: return the first pair that sums up zero
// sumZero([-2,-1,0,1,2,3,4]) // [-2,2]
// sumZero([-3,-2,-1,0,1,2,3,4]) // [-3,3]
// zero if not such value
// sumZero([0,1,2,3,4]) // 0
// sumZero([]) // 0
function sumZero(arr) {
if (arr[0] >= 0) {
return 0
}
for (const v1 of arr) {
for (const v2 of arr) {
if (v1 + v2 == 0) {
return [v1, v2]
}
}
}
return 0
}
// time O(n^2)
// space O(1)
/**
* --------------------------------------
* --------------------------------------
* --------------------------------------
* -------------BEST SOLUTION------------
* --------------------------------------
* --------------------------------------
* --------------------------------------
*
*/
console.log(isZero([-2, -1, 0, 1, 2, 3, 4]))
// double pointer pattern
function isZero(arr) {
if (arr[0] >= 0) {
return 0
}
let l = 0
let r = arr.length - 1
while (l < r) {
let sum = arr[l] + arr[r]
if (sum == 0) {
return [arr[l], arr[r]]
} else if (sum > 0) {
r--
} else if (sum < 0) l++
}
return 0
}
// time O(n)
// space O(1)
|
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const schema = new Schema({
productName: { type: String, required: true },
productBrand: { type: String, required: true },
productCategory: { type: String, required: true },
productBarcode: { type: String, required: true },
stockQuantity: { type: Number, required: true },
stockStatus: { type: String, default: "Inactive" },
sellingPrice: { type: Number, required: true },
productPrice: { type: Number, required: true },
marginPercent: { type: Number, default: 5 },
createdDate: { type: Date, default: Date.now }
})
schema.set('toJSON', { virtuals: true });
module.exports = mongoose.model('Stock', schema);
|
var roleDropHarvester = {
/** @param {Creep} creep **/
run: function(creep, village) {
if (BASE_CREEP.run(creep, village) == -1){
return;
}
village.debugMessage.append(`\t\t\t${creep.name} is running role DropHarvester`);
// if my location isn't equal to my drop location
// move there
// else harvest
// TODO: doesn't run base class, is a mindless worker
//creep.
let mySource = village.getSource(creep.name);
//console.log(creep.name + " | SOURCE " + mySource)
let dropLocation = village.getDropHarvestLocation(creep.name);
if(!dropLocation) {
return; // TODO: do something graceful
}
let dropContainer = Game.getObjectById(dropLocation);
if (!creep.pos.isEqualTo(dropContainer.pos)) {
creep.emote('dropHarvester', CREEP_SPEECH.MOVE);
creep.moveTo(dropContainer);
} else {
creep.emote('dropHarvester', CREEP_SPEECH.HARVEST);
creep.harvest(mySource); // TEST: is this the right mem addr?
}
}
};
module.exports = roleDropHarvester;
|
/*!
* inspideez
* dropdown
*/
$(function () {
$('.dropdown-toggle').on("click", function (event) {
event.stopPropagation();
//closing all other dropdown's and adding .closing for animating
$('.dropdown.open').not($(this).parent('.dropdown')).removeClass('open').addClass('closing');
//removing .closing after timeout
setTimeout(function () {
$('.dropdown').removeClass('closing');
}, 250);
//toggle .open and .closing
$(this).parent('.dropdown').toggleClass('open');
if ($(this).parent('.dropdown').hasClass('open')) {
} else {
$(this).parent('.dropdown').addClass('closing');
setTimeout(function () {
$('.dropdown').removeClass('closing');
}, 250);
}
});
//outside click closing all dropdown's
$('html,body').on("click", function () {
$('.dropdown.open').addClass('closing');
setTimeout(function () {
$('.dropdown').removeClass('closing');
}, 250);
$('.dropdown').removeClass('open')
});
});
|
import * as React from "react";
import Button from "@material-ui/core/Button";
import { makeStyles } from "@material-ui/core/styles";
import EmojiPeopleIcon from "@material-ui/icons/EmojiPeople";
import MonetizationOnIcon from "@material-ui/icons/MonetizationOn";
const useStyles = makeStyles((theme) => ({
button: {
margin: theme.spacing(1),
},
}));
export default function IconLabelButtons() {
const classes = useStyles();
return (
<div>
<Button
variant="contained"
color="secondary"
size="large"
href="/signup-form"
className={classes.button}
startIcon={<EmojiPeopleIcon />}
>
Volunteer
</Button>
<Button
variant="contained"
color="secondary"
size="large"
href="/donate"
className={classes.button}
startIcon={<MonetizationOnIcon />}
>
Donate
</Button>
</div>
);
}
|
/*
* 각 함수들의 정의가 끝난 후, 여기서 실제의 처리를 시작
*/
Main.init(() => {
Preloader.loads([
'beat.mp3',
]);
// 시스템에서 저장된 키-벨류 값을 가져옴
UserDefault.loadValueToSystemKey();
// 타이틀 화면 생성
Window.setSize(800, 600);
Director.replaceScene(new SceneTitle());
});
|
/**
* Created by Administrator on 2016/5/5.
*/
$(function(){
$('#dg').datagrid({
onLoadSuccess: function(data){
if (data.total == 0 && data.ERROR == 'No Login!') {
var user_id = localStorage.getItem('user_id');
var user_pwd = localStorage.getItem('user_pwd');
if(user_id==''||!user_id||user_pwd==''||!user_pwd){
$.messager.alert('信息提示', '登录超时,请重新登录!', 'error');
relogin();
}
else{
$.post('loginAction!login1.zk',{user_id:user_id,user_pwd:user_pwd},function(data){
if(data.STATUS){
$('#dg').datagrid('reload');
}
},'json').complete(function(){
$('#dg').datagrid('reload');
});
}
}
$("a.popImage").fancybox({
openEffect : 'elastic',
closeEffect: 'elastic'
});
},
onLoadError : function() {
alert('出错啦');
}
});
$('#searchState').combobox({
onChange: function (n,o) {
searchUser();
}
});
});
//删除比赛
function del(){
var row = $('#dg').datagrid('getSelected');
if(!row){
showError('请先选择比赛!');
return;
}
$.messager.confirm(' 确认', "确定删除?", function(r) {
if (r) {
$.getJSON('FatburnGameAction!delete.zk',{id:row.id},function(data){
if(data.STATUS){
$('#dg').datagrid('reload');
showTip("删除成功!");
}else {
showTip("删除失败!");
}
});
}
});
}
var url;
function newGame(){
$('#fm').form('clear');
openDialog('dlg', '请编辑比赛信息');
var games=[];
var gameSel;
$.post('FatburnGameAction!listTemps.zk', {}, function(data) {
if (data.STATUS) {
var rows = data.gameTemps;
alert(rows);
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
var game = {
"id": i,
"code": row.code,
"info": row.info,
"name": row.name,
"type": row.type
};
games.push(game);
}
$('#code').combobox({
valueField: 'id',
textField: 'name',
data: games,
onSelect: function(rec) {
gameSel = games[rec.id].code;
$('#gameInfo').val(games[rec.id].info);
var equips = [];
for (var i = games[rec.id].type.length - 1; i >= 0; i--) {
var equip = games[rec.id].type[i];
var name;
switch (equip) {
case 'bike':
name = '健身车';
break;
case 'stepper':
name = '踏步机';
break;
case 'treadmill':
name = '跑步机';
break;
default:
name = '';
break;
}
var type = {
'id': equip,
'name': name
}
equips.push(type);
}
$('#gameEquip').combobox({
valueField: 'id',
textField: 'name',
data: equips,
onSelect: function(rec) {
gameSel = games[rec.id].code;
$('#gameInfo').val(games[rec.id].info);
$('#gameEquip').val(games[rec.id].type);
}
});
}
});
}
}, 'json');
url = 'FatburnGameAction!add.zk';
}
//编辑比赛信息
function editGame(){
var row = $('#dg').datagrid('getSelected');
if (!row){
showError('请先选择要编辑的比赛!');
return;
}
gymID = row.id;
openDialog('dlg', '编辑比赛信息');
//#("#code").combobox(setValue,row.code);
//#("#equip").combobox(setValue,row.equip);
$('#fm').form('load',row);
url = 'FatburnGameAction!update.zk?id='+row.id;
}
//检查表单
function checkForm(){
var code =$("#code").combobox("getValue");
if(code==''){
$.messager.alert('警告','比赛代号不能为空!');
$("#code").focus();
return false;
}
var equip =$("#gameEquip").combobox("getValue");
if(equip==''){
$.messager.alert('警告','比赛设备不能为空!');
$("#gameEquip").focus();
return false;
}
var seconds = $("#seconds").textbox("getValue")
if(seconds==''){
$.messager.alert('警告','比赛时长不能为空!');
$("#seconds").focus();
return false;
}
return true;
}
//提示信息
function showTip(msg) {
$.messager.show({
title : "消息",
timeout:2000,
msg : msg
});
}
function saveGame() {
if (checkForm()) {
$('#fm').form('submit',{
url:'FatburnGameAction!add.zk',
onSubmit: function(){
return checkForm();
},
success: function (result) {
var result = $.parseJSON(result);
if (result.STATUS) {
$('#dlg').dialog('close');
$('#dg').datagrid('reload');
} else {
showError(result.INFO);
}
}
});
}
}
function vet(){
var row = $('#dg').datagrid('getSelected');
if(!row){
showError('先选择比赛');
return ;
}
id=$('#checkGymId').val(row.id);
$('#checkName').text(row.name ? row.name : '' );
$('#checkOrganizersName').text(row.organizersName ? row.organizersName :'');
$('#checkGameSportType').text(row.gameSportType ? row.gameSportType : '');
$('#checkJoinTotle').text(row.joinTotle ? row.joinTotle : '');
$('#checkGmtStart').text(row.gmtStart ?formatDate(row.gmtStart) : '');
$('#checkGmtEnd').text(row.gmtEnd ?formatDate(row.gmtEnd) : '');
$('#checkInfo').text(row.info ? row.info : '');
$('#checkGameType').text(row.gameType ? row.gameType : '');
if(row.isAudited== '2'){
$('#checkresult').text('审核失败!' );
}else if(row.isAudited == '1'){
$('#checkresult').text('已通过审核!');
}else if(row.isAudited == '0'){
$('#checkresult').text('未审核');
}
openDialog('gymCheckdlg','审核比赛活动信息');
}
function saveCheck(s){
var row = $('#dg').datagrid('getSelected');
if(s==1){
$.post('FatburnGameAction!audited.zk',{id:row.id,pass:"y"},function(data){
if(data.STATUS){
closeDialog('gymCheckdlg');
$('#dg').datagrid('reload');
}else{
showError(data.INFO);
}
},'json');
}else{
$.post('FatburnGameAction!audited.zk',{id:row.id,pass:"n"},function(data){
if(data.STATUS){
closeDialog('gymCheckdlg');
$('#dg').datagrid('reload');
}else{
showError(data.INFO);
}
},'json');
}
}
function searchUser(){
var searchKey = $('#searchKey').textbox('getValue');
var searchState = $('#searchState').combobox('getValue');
$("#dg").datagrid('load',{name:searchKey,isAudited:searchState});
}
function formatState1(s){
if(s==0){
return "未审核";
}else if(s==1){
return "已审核";
}else{
return "审核失败";
}
}
|
/* jshint indent: 2 */
module.exports = function (sequelize, DataTypes) {
return sequelize.define(
'likes',
{
like_id: {
type: DataTypes.INTEGER(11),
allowNull: false,
primaryKey: true,
autoIncrement: true,
},
like_post_id: {
type: DataTypes.INTEGER(11),
allowNull: false,
references: {
model: 'posts',
key: 'post_id',
},
},
like_user_id: {
type: DataTypes.INTEGER(11),
allowNull: false,
references: {
model: 'users',
key: 'user_id',
},
},
},
{
tableName: 'likes',
timestamps: false,
},
);
};
|
import commonModule from '../_common';
import appLayoutRouter from './layout.router';
import {headerModule} from './header';
import {footerModule} from './footer';
import {sidebarModule} from './sidebar';
export default angular.module('app.layout', [
commonModule.name,
headerModule.name,
footerModule.name,
sidebarModule.name
]).run(appLayoutRouter);
|
import { Voices } from '../oscillators/voices';
import { VolumeEnv } from '../envelopes/volumeEnvelope';
import { Filtenv } from '../envelopes/filterEnvelope';
import { Recorder } from '../record/recorder.js';
export const SwarmEngine = audioContext => {
const _swarmEngine = {
audioContext,
recorderNode: audioContext.createGain(),
voices: new Voices(audioContext).createVoices(),
envNode: audioContext.createGain(),
filter: audioContext.createBiquadFilter(),
swOverdrive: audioContext.createWaveShaper(),
swarmVol: audioContext.createGain(),
}
_swarmEngine.recorder = Recorder(_swarmEngine.recorderNode);
_swarmEngine.volumeEnv = VolumeEnv(audioContext, _swarmEngine.envNode, _swarmEngine.linearEnv);
_swarmEngine.filtenv = new Filtenv(audioContext, _swarmEngine.filter, _swarmEngine.volumeEnv.envSettings, _swarmEngine.linearEnv);
_swarmEngine.envNode.gain.value = 0;
_swarmEngine.voices.voiceMerger.connect(_swarmEngine.envNode);
_swarmEngine.envNode.connect(_swarmEngine.filter);
_swarmEngine.filter.connect(_swarmEngine.swOverdrive);
_swarmEngine.swOverdrive.connect(_swarmEngine.swarmVol);
_swarmEngine.swarmVol.connect(_swarmEngine.recorderNode);
_swarmEngine.swarmVol.connect(_swarmEngine.audioContext.destination);
return _swarmEngine;
}
|
const data = [
{
"title": "React Class",
"content": "Today I learnt React"
},
{
"title": "Angular Class",
"content": "Today I learnt Angular from server"
}
]
module.exports = data;
|
module.exports = function(grunt) {
'use strict';
var config = require('../grunt.conf');
grunt.config('browserSync', {
dev: config.sync
});
grunt.config('watch', config.watch);
grunt.loadNpmTasks('grunt-browser-sync');
grunt.loadNpmTasks('grunt-contrib-watch');
};
|
const webpack = require('webpack');
module.exports = {
mode: "development",
devtool: 'inline-source-map',
performance: {
hints: false
},
resolve: {
extensions: [ '.ts', '.js' ]
},
module: {
rules: [
{
test: /\.ts$/,
use: [
'ts-loader',
'angular-router-loader',
'angular2-template-loader'
]
},
{
test: /\.html$/,
loader: 'html-loader'
},
{
test: /\.(png|svg|jpe?g|gif|woff|woff2|eot|ttf|ico)$/,
loader: 'url-loader',
options: {
name: 'asset/[name].[ext]',
limit: 8192
}
},
{
test: /\.(css|less)$/,
use: [
'to-string-loader',
'css-loader',
'postcss-loader',
'less-loader'
]
},
{
test: /[\/\\]@angular[\/\\]core[\/\\].+\.js$/,
parser: { system: true },
}
]
},
plugins: [
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery'
})
]
};
|
import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import Article from '../../components/ArticleCard';
import { articles } from '../../services/fakeArticleService';
import { ThemeContext } from '../../themContext';
const Articles = () => {
const { t } = useTranslation();
const { theme } = React.useContext(ThemeContext);
const [articlesCollection, setArticles] = useState(articles);
const [search, setSearch] = useState('');
const getArticles = () => {
return articlesCollection.length !== 0 ? (
<div className="flex flex-wrap mt-10 -mb-4">
{articlesCollection.map((article) => {
return (
<div className="min-w-0 lg:w-1/3 md:w-1/2" key={article.id}>
<Article
id={article.id}
title={article.title}
img={article.articleImg}
paragraph={article.text.substring(1, 100)}
time={article.date}
articleLink={article.articleLink.replace('///g', '$')}
/>
</div>
);
})}
</div>
) : null;
};
const geHeadArticle = () => {
const headArt = search === '' ? articlesCollection[0] : null;
return headArt ? (
<Article
id={headArt.id}
title={headArt.title}
img={headArt.articleImg}
paragraph={headArt.text.substring(1, 100)}
time={headArt.date}
articleLink={headArt.articleLink.replace('///g', '$')}
/>
) : (
<div />
);
};
const filterArticle = (ser) => {
let feltered = articlesCollection;
if (ser !== '') {
feltered = articlesCollection.filter((m) =>
m.title.toString().toUpperCase().startsWith(ser.toString().toUpperCase())
);
setArticles(feltered);
} else setArticles(articles);
};
const handleSearch = (ser) => {
setSearch(ser.value);
filterArticle(ser.value);
};
return (
<div className=" bg-background-primary">
<div className="Header flex-grow w-full h-64 top-0 py-64 bg-background-pinck">
<svg
className="absolute buttom-0 h-64 w-full "
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 100 100"
preserveAspectRatio="none"
>
<polygon
fill={theme === 'dark' ? '#0d2438' : 'white'}
points="0,100 100,0 100,100"
/>
</svg>
</div>
<div className="pt-56 pb-12 text-center absolute top-0 right-0 left-0">
<h1 className="text-4xl font-semibold text-blue-700">
{t('Mental Health Articles & Advices')}
</h1>
<div className="box-content flex justify-center mt-4 mb-8 text-lg leading-relaxed text-gray-600">
<p className="w-2/4 ">{t('Articles paragraph')}</p>
</div>
<div className="box-content flex justify-center m-5">
<div className="box-content flex justify-center w-4/5 md:w-3/5 bg-white rounded-full">
<input
type="text"
name="search"
placeholder={t('Search')}
className="w-full px-3 py-1 text-base leading-8 text-gray-700 transition-colors duration-200 ease-in-out bg-gray-100 border border-gray-300 rounded outline-none focus:border-indigo-500"
onChange={(e) => handleSearch(e.target)}
/>
</div>
</div>
</div>
<div className="flex flex-col px-2 md:px-12 lg:px-32 justify-center w-full ">
<div className="flex-grow mt-64 md:mt-20 w-full wx-auto justify-center">
{geHeadArticle()}
</div>
<div className="flex w-full justify-center " />
{getArticles()}
</div>
</div>
);
};
export default Articles;
|
import './App.css';
import {HashRouter, Route} from "react-router-dom";
import Table from './components/Table';
import Writer from './components/Writer';
import Modify from './components/Modify';
import Header from './components/Header';
import Nav from './components/Nav';
import Footer from './components/Footer';
import NavBar from "./components/NavBar";
import Location from "./components/Location";
import Quiz from "./components/Quiz";
function App() {
return (
<HashRouter>
<Header/>
<NavBar/>
<Route path="/" exact={true} component={Table}/>
<Route path="/writer" component={Writer}/>
<Route path="/modify" component={Modify}/>
<Route path="/loc" component={Location}/>
<Route path="/quiz" component={Quiz}/>
{/*<Nav/>*/}
<Footer/>
</HashRouter>
)
;
}
export default App;
|
import React, { Component } from 'react'
import PageTitle from '../PageTitle';
import GooMaps from './GooMaps';
import { Container, Row, Col } from 'react-bootstrap';
import ContactForm from './ContactForm';
class Contact extends Component {
render() {
return (
<div className="contact">
<PageTitle title="GOT A QUESTION OR INQUIRY?" />
<div className="map-google"><GooMaps /></div>
<Container>
<Row>
<Col md={7} className="contact-form-text">
<h3>CONTAC FORM</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Pellentesque eu eratiuy lacus, vel congue mauris. Fusce velitaria justo, faucibus eu.</p>
<ContactForm />
</Col>
<Col md={{span: 4, offset: 1}} className="contact-info-text"><div className="wrapper"></div>
<h3>CONTACT INFO</h3>
<div className="wrapper">
<p>Lorem ipsum dolor sit amet, <br />consectetur adipiscing elit.</p>
</div>
<div className="wrapper">
<p><strong>email:</strong> <span className="green"><a href="mailto:info@dispaly.com">info@dispaly.com</a></span></p>
<p><strong>phone:</strong> 1.306.222.4545</p>
</div>
<div className="wrapper">
<p>222 2nd Ave South</p>
<p>Saskabush, SK S7M 1T</p>
</div>
<h3>STORE HOURS</h3>
<table>
<tbody>
<tr>
<td>Monday - Thursday </td>
<td>8 am - 5 pm</td>
</tr>
<tr>
<td>Friday</td>
<td>8 am - 6 pm</td>
</tr>
<tr>
<td>Saturday</td>
<td>9 am - 5 pm</td>
</tr>
<tr>
<td>Sunday & Holidays</td>
<td>Closed</td>
</tr>
</tbody>
</table>
</Col>
</Row>
</Container>
</div>
)
}
}
export default Contact;
|
import React, {Component} from 'react'
class StudentsGrades extends Component{
render(){
const students = this.props.student.map((student, key)=>{
return student.score > 50 ? (
<tr key ={key}>
<td>Name: {student.name}</td>
<td>Score: {student.score}PASSED</td>
</tr>
): (
<tr key ={key}>
<td>Name: {student.name}</td>
<td>Score: {student.score}FAILED</td>
</tr>
)
})
return(
<div>
<h1>Grades</h1>
<table>
<tbody>
{students}
</tbody>
</table>
</div>
)
}
}
export default StudentsGrades
|
angular
.module('blocJams')
.controller('AlbumCtrl', function($scope, Fixtures, SongPlayer) {
$scope.currentAlbum = angular.copy(Fixtures.getAlbum()),
$scope.songPlayer = SongPlayer;
// .controller('AlbumCtrl', function(Fixtures) {
// this.albumData = angular.copy(albumPicasso);
// }
});
|
import _ from "/ui/web_modules/lodash.js";
export default mnDocumentsListController;
function mnDocumentsListController($rootScope, mnDocumentsListService, $state, $uibModal, removeEmptyValueFilter, jQueryLikeParamSerializerFilter) {
var vm = this;
vm.lookupSubmit = lookupSubmit;
vm.showCreateDialog = showCreateDialog;
vm.deleteDocument = deleteDocument;
vm.onFilterClose = onFilterClose;
vm.onFilterReset = onFilterReset;
vm.getDocumentsURI = getDocumentsURI;
vm.getFilterParamsAsString = getFilterParamsAsString;
var filterConfig = {};
try {
filterConfig.params = JSON.parse($state.params.documentsFilter);
} catch (e) {
filterConfig.params = {};
}
filterConfig.items = {
inclusiveEnd: true,
endkey: true,
startkey: true
};
vm.filterConfig = filterConfig;
activate();
function getDocumentsURI() {
return mnDocumentsListService.getDocumentsURI($state.params) + getFilterParamsAsString($state.params);
}
function getFilterParamsAsString(params) {
return "?" + jQueryLikeParamSerializerFilter(removeEmptyValueFilter(mnDocumentsListService.getDocumentsParams($state.params)));
}
function onFilterReset() {
vm.filterConfig.params = {};
}
function lookupSubmit() {
vm.lookupId && $state.go('^.^.editing', {
documentId: vm.lookupId
});
}
function deleteDocument(documentId) {
return $uibModal.open({
controller: 'mnDocumentsDeleteDialogController as documentsDeleteDialogCtl',
templateUrl: 'app/mn_admin/mn_documents_delete_dialog.html',
resolve: {
documentId: function () {
return documentId;
}
}
});
}
function showCreateDialog() {
return $uibModal.open({
controller: 'mnDocumentsCreateDialogController as documentsCreateDialogCtl',
templateUrl: 'app/mn_admin/mn_documents_create_dialog.html',
resolve: {
doc: function () {
return false;
}
}
});
}
function onFilterClose() {
var params = filterConfig.params;
params = removeEmptyValueFilter(params);
params && $state.go('^.list', {
documentsFilter: _.isEmpty(params) ? null : JSON.stringify(params)
});
}
function activate() {
$rootScope.$broadcast("reloadDocumentsPoller");
}
}
|
import React from "react"
import Img from "gatsby-image"
import RightAngle from "../../images/right-angle.svg"
const makePersonBlock = person => (
<li
key={person.id}
className="flex w-full flex-wrap mb-20 pl-0"
>
<div className="w-full md:w-1/3 md:pr-14">
{person.headshot ?
<div
className="rounded-full overflow-hidden mb-6 md:mb-0 mx-auto shadow"
style={{
maxWidth: '400px'
}}
>
<Img
className="block w-full"
alt={person.name}
fluid={person.headshot.fluid}
/>
</div>
:
<div className="w-full h-32 bg-blue-500 opacity-50 mb-3 md:mb-0"></div>
}
</div>
<div className="w-full md:w-2/3 flex justify-center flex-col text-center md:text-left">
<h3 className="mb-3">{person.name}</h3>
<div className="text-blue-500 text-sm mb-3">{person.title}</div>
{person.boardOrOfficers !== 'board' &&
<p className="text-left" style={{ marginBottom: 0 }}>{person.biographySummary}</p>
}
</div>
</li>
)
export default class LeadershipListing extends React.Component {
constructor (props) {
super(props)
this.state = {
boardExpanded: false,
officersExpanded: true
}
this.toggleSlot = this.toggleSlot.bind(this)
}
toggleSlot (key) {
this.setState({ [key]: !this.state[key] })
}
render () {
return (
<div className="bg-white">
<div className="container">
<div className="w-full py-4 border-b border-gray-400">
<div
className="flex items-center justify-between w-full cursor-pointer"
onClick={() => this.toggleSlot('boardExpanded')}
>
<div className={`text-3xl`}>Board of Directors</div>
<div
style={{
transition: `transform 250ms ease`,
transform: `rotate(${this.state.boardExpanded ? '90' : '0'}deg)`
}}
>
<RightAngle />
</div>
</div>
<ul className={`list-none mb-0 pl-0 pt-8 xl:px-20 ${this.state.boardExpanded ? 'block' : 'hidden'}`}>
{this.props.data.people.filter(p => p.boardOrOfficers === 'board').map(makePersonBlock)}
</ul>
</div>
<div className="w-full py-4 border-b border-gray-400 mb-16">
<div
className="flex items-center justify-between w-full cursor-pointer"
onClick={() => this.toggleSlot('officersExpanded')}
>
<div className={`text-3xl cursor-pointer`}>Officers</div>
<div
style={{
transition: `transform 250ms ease`,
transform: `rotate(${this.state.officersExpanded ? '90' : '0'}deg)`
}}
>
<RightAngle />
</div>
</div>
<ul className={`list-none mb-0 pt-8 pl-0 xl:px-20 ${this.state.officersExpanded ? 'block' : 'hidden'}`}>
{this.props.data.people.filter(p => p.boardOrOfficers === 'officers').map(makePersonBlock)}
</ul>
</div>
</div>
</div>
)
}
}
|
function solve(n){
let value = '';1
console.log('<div class="chessboard">')
for(let i = 0; i < n; i++){
console.log(' <div>')
for(let j = i; j < i + n; j++){
if(j % 2 == 0){
value = 'black';
}else{
value = 'white';
}
console.log(` <span class="${value}"></span>`)
}
console.log(' </div>');
}
console.log('</div>');
}
solve(3);
|
module.exports = {
baseUrl: 'http://timage.xbniao.com',
listPage:'/port/list',
addPage:'/port/add',
updatePage:'/port/update'
};
|
import { expect, request, sinon } from '../../test-helper'
import app from '../../../app'
import GetArticlesMeta from '../../../src/use_cases/get-articles-meta'
import { dummyArticleMeta } from '../../dummies/dummyArticle'
describe('Integration | Routes | articles-meta route', () => {
const articlesMeta = [dummyArticleMeta()]
beforeEach(() => {
sinon.stub(GetArticlesMeta, 'getAll').resolves(articlesMeta)
})
afterEach(() => {
GetArticlesMeta.getAll.restore()
})
it('should be 200 with /articles-meta and handle query params', done => {
request(app)
.get('/api/articles-meta')
.end((err, response) => {
expect(GetArticlesMeta.getAll).to.have.been.calledWith()
expect(response.body).to.deep.equal(articlesMeta)
expect(response.status).to.equal(200)
if (err) {
done(err)
}
done()
})
})
})
|
'use strict';
const Client = use('App/Models/Client');
class ClientController {
async index() {
const allClients = await Client.all();
return allClients;
}
async show({ request }) {
const Client = use('App/Models/Client');
return await Client.findOrFail(request.params.id);
}
async store({ request, response }) {
try {
const client = new Client();
client.company_name = request.input('company_name');
client.first_name = request.input('first_name');
client.last_name = request.input('last_name');
client.postalcode = request.input('postalcode');
client.street = request.input('street');
client.city = request.input('city');
await client.save();
return response.json({
status: 'success',
data: client
});
} catch (error) {
response.status(400).json({
status: 'error',
message: error
});
}
}
}
module.exports = ClientController;
|
var interface_c1_connector_register_device_options =
[
[ "getDictionaryWithProperties", "interface_c1_connector_register_device_options.html#a865bd09b452b612dcc2750e5a644674d", null ],
[ "appID", "interface_c1_connector_register_device_options.html#ab465abf43db41a20084544a7470b2b57", null ],
[ "campaignID", "interface_c1_connector_register_device_options.html#af95c54f926d92a5d5ab71069bc8de853", null ]
];
|
module.exports = function(grunt) {
//module to load all grunt tasks at once instead of individually calling loadNpmTasks on each.
require('load-grunt-tasks')(grunt);
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
jest: {
options: {
coverage: true,
testPathPattern: /.*-test.js/
}
},
awsebtdeploy: {
options: {
applicationName: 'walkingtours',
environmentCNAME: 'thesisserver-env.elasticbeanstalk.com',
region: 'us-east-1',
sourceBundle: 'sourcebundle/bundle.zip'
}
},
compress: {
main: {
options: {
archive: './sourcebundle/bundle.zip',
mode: 'zip'
},
files: [
{ expand: true,
cwd: 'server/',
src: ['**/*', '!tests', '!schema.sql', '!node_modules', '!test_images', '!seeds']},
]
}
},
clean: ["sourcebundle/*"],
jshint: {
files: [ 'Gruntfile.js', 'server/**/*.js', 'server/*.js', 'mobile/*.js', 'mobile/components/*.js'],
options: {
force: 'true',
jshintrc: '.jshintrc',
ignores: [
'server/node_modules/**'
]
}
},
jsdoc: {
dist : {
src: ['server/*.js', 'server/**/*.js', '!server/node_modules/**', '!server/config/*.js', 'mobile/*.js', 'mobile/components/*.js', 'README.md'],
options: {
destination: 'server/out/'
}
}
},
mochaTest: {
test: {
options: {
reporter: 'spec'
},
src: ['server/tests/*.js']
}
}
});
////////////////////////////////////////////////////
// Main grunt tasks
////////////////////////////////////////////////////
//grunt.registerTask('testFront', ['jshint', 'jest']);
grunt.registerTask('testBack', ['jshint', 'mochaTest']);
grunt.registerTask('zip', ['clean', 'compress']);
grunt.registerTask('travis', ['testFront', 'testBack']);
grunt.registerTask('build', ['jshint', 'travis', 'jsdoc', 'zip']);
grunt.registerTask('deploy', ['build', 'awsebtdeploy']);
};
|
const express = require("express");
module.exports = {
funtest : async(req,res)=>{
//console.log("hii");
try{
await getsum();
}catch(error){
console.log(error)
}
res.send("hii");
},
}
|
import styled from 'styled-components/native';
import { View } from 'react-native';
import { Card } from 'react-native-paper';
export const EventCard = styled(Card)`
border-radius: 0px;
margin-top: 17px;
margin-bottom: 17px;
padding-top: ${(props) => props.theme.space[5]};
box-shadow: 0px 4px 4px #E9E9E9;
`
export const EventCover = styled(Card.Cover)`
height: 85px;
min-width: 100%;
`
export const InfoWrapper = styled(View)`
margin-top: ${(props) => props.theme.space[4]};
padding-left: ${(props) => props.theme.space[4]};
padding-right: ${(props) => props.theme.space[4]};
padding-bottom: ${(props) => props.theme.space[2]};
`
export const Row = styled(View)`
flex-direction: row;
justify-content: flex-start;
margin-bottom: ${(props) => props.theme.space[4]};
`
|
const express = require("express");
const router = express.Router();
const RoleController = require('./roles_controllers');
router.post('/post/addrole', RoleController.addrole);
router.patch('/patch/role', RoleController.patchrole);
router.get('/get/list', RoleController.listrole);
router.get('/get/list/keyvalue', RoleController.listrolekeyvalue);
router.get('/get/roledetails/:id', RoleController.roledetails);
router.delete('/delete/role', RoleController.deleterole);
module.exports = router;
|
/*
* Footer page object
*
* @package: Blueacorn Footer.js
* @version: 1.0
* @Author: Luke Fitzgerald
* @Copyright: Copyright 2015-07-24 10:28:51 Blue Acorn, Inc.
*/
'use strict';
//enables the use of xpath to find selectors
var x = require('casper').selectXPath;
//set screen for better screen shots
casper.options.viewportSize = {width: 1940, height: 1080};
function FooterPage() {
//declare variable
var URL = 'http://nativesite.dev';
var newsletterRegistrationPath = 'input#newsletter';
var sessionMsgPath = 'input#newsletter';
var pathToLogo = x('//*[@id="header"]/div/a/img[1]');
var validationPath = 'div#advice-required-entry-newsletter';
//get methods
this.getURL = function(){
return URL;
};
this.getSessionMsgPath = function(){
return sessionMsgPath;
};
this.getValidationPath = function(){
return validationPath;
};
//enter email in newsletter subscription field
this.fillOutNewsLetterEmail = function(email){
casper.then(function(){
this.sendKeys(newsletterRegistrationPath, email);
});
};
//click subscribe button
this.subscribe = function() {
casper.then(function() {
//this.click('button.button');
this.clickLabel('Subscribe');
});
};
};
|
import * as counter from './counter';
import * as formula1 from './formula1';
export {counter, formula1,};
|
//EXAMPLES OF FASTER DOM TRAVERSAL BY FINDING ELEMENTS DIRECTLY
//ALWAYS USING QUERYSELECTOR IS SLOWER
const ul = document.querySelector('ul');
//a way to obtain individual child elements of the ul in the html
ul.children[1]
//gives an array of the items in the ul
ul.childNodes
//quicker to get first or last child elements than using querySelector and last-of-type
ul.firstChild
ul.firstElementChild
ul.lastChild
ul.lastElementChild
const liFirst = document.querySelector('li');
//can't have more than one parent
liFirst.parentNode
//to reach out to an ancestor, as long as it indirectly wraps the element
liFirst.closest('body')
const ulFam = li.parentElement;
//gives previous sibling node
ulFam.previousSibling
//gives nearest sibling element
ulFam.previousElementSibling
//gives the next sibling
ulFam.nextElementSibling
//adds item before last element in a list
list.lastElementChild.before();
//adds items after last element in a list
list.lastElementChild.after();
//replace first item in a list
list.firstElementChild.replaceWIth();
//before() and after() don't work on Safari
//works on all platforms, have to use 'beforebegin', 'afterbegin', 'beforeend', 'afterend'
//as first argument, then the second argument is what you're entering
list.insertAdjacentElement();
|
import React from "react";
import Hero from "../src/Pages/Hero";
import Passion from "../src/Pages/Passion";
import Summary from "../src/Pages/Summary";
import Expertise from "../src/Pages/Expertise";
import Portfolio from "../src/Pages/Portfolio";
import OpenSource from "../src/Pages/OpenSource";
import Subscribe from "../src/Pages/Subscribe";
import Testimonial from "../src/Pages/Testimonial";
import Contact from "../src/Pages/Contact";
import Footer from "../src/Pages/Footer";
import Logo from "../src/Pages/Logo";
//Router
import { BrowserRouter as Router, Route } from "react-router-dom";
///
import "./App.css";
function App() {
return (
<Router>
<div className="App">
<Logo />
<Hero />
<Summary />
<Passion />
<Expertise />
<Portfolio />
<OpenSource />
<Subscribe />
<Testimonial />
<Route />
<Contact />
<Footer />
</div>
</Router>
);
}
export default App;
|
import React, { Component } from 'react'
import ErrorComponent from './ErrorComponent'
import LoadingComponent from './LoadingComponent'
import './style/index.less'
export default function asyncComponent(importComponent) {
class AsyncComponent extends Component {
constructor(props) {
super(props)
this.state = {
component: LoadingComponent
}
}
async componentDidMount() {
try {
const { default: component } = await importComponent()
this.setState({
component: component
})
} catch (e) {
this.setState({
component: ErrorComponent
})
}
}
render() {
const C = this.state.component
return C ? <C {...this.props} /> : null
}
}
return AsyncComponent
}
|
// learn foreach from mdn
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
/* Questions to understand: */
/* 1. What does it do? make sure to explain all the parameters. If it has a function as a parameter, make sure to explain all of the parameters for that function. */
"you pass in a function and this method executes the function on each array element in ascending order. The range of execution is determined at the start, so you can't append stuff and have it keep running on that stuff."
/* 2. Does it edit the current array? */
"the forEach function itself does nothing, but the callback function you define can modify the current array."
/* 3. What does it return? */
"Return value is 'undefined'"
/* 4. How can I use this? Come up (not one off the internet) with a small real world example and explain it. */
"you can run functions on each member of the array without changing the array."
/* 5. Build your real world example. */
var a1 = [0, 1, 2, 3, 4, 5];
a1.forEach(e => console.log(e**e));
console.log(a1);
|
import React from 'react'
import { getUserData } from '../../store/auth/selectors'
import { useDispatch, useSelector } from 'react-redux'
import { logoutUser } from '../../store/auth/auth.thunks'
import Link from 'next/link'
import { useTranslation } from 'next-i18next'
const UserImage = () => {
const { t } = useTranslation('header')
const user = useSelector(getUserData)
const dispatch = useDispatch()
const noUserPhoto = '/no-avatar.png'
const onLogout = () => {
dispatch(logoutUser())
}
return (
<div>
<div className="dropdown">
<img
className="avatar-img"
style={{ width: '24px', height: '24px' }}
src={user?.avatar?.url ? user.avatar.url : noUserPhoto}
alt="avatar"/>
<ul /* style={{ opacity: isMenuOpen ? '1' : '0' }}*/>
<div>
<div className="d-flex accDropBlock">
<img
className="avatar-img" style={{ width: '40px', height: '40px' }}
src={user.avatar?.url ? user.avatar.url : noUserPhoto}
alt="avatar"/>
<div className="ml-3 lh-1">
<p className="mb-1 accDropTitle">
{user?.name}
</p>
<p className="mb-0 accDropMail">
{user?.email}
</p>
</div>
</div>
<div className="dropdown-divider"/>
</div>
<li>
<Link href={`/profile`}>
<a>
<i className="fab fa-flipboard" style={{ marginRight: '10px' }}/>
{t('dashboard')}
</a>
</Link>
</li>
<li>
<Link href={`/teaching`}>
<a>
<i className="fas fa-book" style={{ marginRight: '10px' }}/>
{t('teaching')}
</a>
</Link>
</li>
<li>
<Link href={`/settings`}>
<a>
<i className="fas fa-cog" style={{ marginRight: '10px' }}/>
{t('settings')}
</a>
</Link>
</li>
<div className="dropdown-divider"/>
<li>
<Link href={'/'}>
<a onClick={onLogout} style={{ cursor: 'pointer' }}>
<i className="fas fa-power-off" style={{ marginRight: '10px' }}/>
{t('exit')}</a>
</Link>
</li>
</ul>
</div>
</div>
)
}
export default UserImage
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.