text
stringlengths 7
3.69M
|
|---|
const express = require("express")
const app = express()
const port = process.env.PORT||3000
const url= "https://docs.google.com/forms/d/e/1FAIpQLSdOQ_Y1ELnqhDJpW-AW1plRUEsbuErPhL6znr4WU_aWvRZ1nA/viewform"
app.get('/' , (req,res)=> res.redirect(url ))
app.listen(port,console.log("welcome to nsutmun"));
|
import React from 'react'
import { Container } from '../Atoms/ContainerElements';
import { Gap } from '../Atoms/Gap';
import { Section } from '../Atoms/Section';
import SectionTitles from '../Atoms/SectionTitle';
import Detail from '../Molecules/Detail';
const Interest = ({titleLine, titleDetail}) => {
return (
<Container>
<Section id='interest'>
<SectionTitles sectionTitle={titleLine}></SectionTitles>
<Detail detail={titleDetail}/>
<Gap/>
</Section>
</Container>
)
}
export default Interest;
|
var fs = require('fs');
var path = require('path');
var xml2js = require('xml2js');
var templates = [];
var rootPath = path.resolve(__dirname, '../');
var readmePath = path.resolve(__dirname, '../README.md');
var writeStream = fs.createWriteStream(readmePath);
writeStream.once('open', function(fd) {
writeStream.write(fs.readFileSync(path.resolve(__dirname, './README.header.md')));
writeStream.write('\n\n');
writeStream.write('###Templates');
writeStream.write('\n\n');
fs.readdir(rootPath, function(err, files) {
if (err) throw err;
var tempFiles = [];
files.forEach(function (fileName) {
if (/^[A-Za-z0-9]*\.xml$/g.exec(fileName)) {
tempFiles.push(fileName);
}
});
tempFiles.forEach(function (fileName, index) {
var filePath = path.resolve(rootPath, fileName);
fs.readFile(filePath, function (err, data) {
if (err) throw err;
xml2js.parseString(data, function (err, result) {
if (err) throw err;
var lines = [];
lines.push('####' + result.templateSet.$.group);
lines.push('');
result.templateSet.template.forEach(function(template) {
lines.push('`' + template.$.name + '` - ' + template.$.description + '\n');
lines.push('```');
lines.push(template.$.value);
lines.push('```');
lines.push('');
});
templates.push(lines.join('\n'));
//fs.appendFile(readmePath, lines.join('\n'));
//writeStream.write(lines.join('\r\n\n'));
if (tempFiles.length == templates.length) {
writeStream.write(templates.join('\n\n'));
}
});
});
});
});
});
|
this["Perf"] && void 0 !== this["Perf"].enabled || (function (window) {
'use strict';
function a() {
return function () { }
}
function b(e) {
return function () {
return e
}
}
var c = {
DEBUG: {
name: "DEBUG",
value: 1
},
INTERNAL: {
name: "INTERNAL",
value: 2
},
PRODUCTION: {
name: "PRODUCTION",
value: 3
},
DISABLED: {
name: "DISABLED",
value: 4
}
};
window.PerfConstants = {
PAGE_START_MARK: "PageStart",
PERF_PAYLOAD_PARAM: "bulkPerf",
MARK_NAME: "mark",
MEASURE_NAME: "measure",
MARK_START_TIME: "st",
MARK_LAST_TIME: "lt",
PAGE_NAME: "pn",
ELAPSED_TIME: "et",
REFERENCE_TIME: "rt",
Perf_LOAD_DONE: "loadDone",
STATS: {
NAME: "stat",
SERVER_ELAPSED: "internal_serverelapsed",
DB_TOTAL_TIME: "internal_serverdbtotaltime",
DB_CALLS: "internal_serverdbcalls",
DB_FETCHES: "internal_serverdbfetches"
}
};
window.PerfLogLevel = c;
var d = window.Perf = {
currentLogLevel: c.DISABLED,
mark: function () {
return d
},
endMark: function () {
return d
},
updateMarkName: function () {
return d
},
measureToJson: b(""),
toJson: b(""),
setTimer: function () {
return d
},
toPostVar: b(""),
getMeasures: function () {
return []
},
getBeaconData: b(null),
setBeaconData: a(),
clearBeaconData: a(),
removeStats: a(),
stat: function () {
return d
},
getStat: b(-1),
onLoad: a(),
startTransaction: function () {
return d
},
endTransaction: function () {
return d
},
updateTransaction: function () {
return d
},
isOnLoadFired: b(!1),
util: {
setCookie: a()
},
enabled: !1
};
})(this);
|
/*
EXERCISE 17:
Write a small function called "fromOneToTen" that takes no parameters and returns and returns a random number from 1 to 10 (inclusive).
For example:
fromOneToTen() should never return 0
fromOneToTen() should return a decimal
fromOneToTen() can return 10
fromOneToTen() can return 1
*/
function fromOneToTen(){
var val = 1;
return val;
}
|
const rest = (a,...argumentos) => {
console.log(a);
console.log(argumentos);
}
// rest(1,2,3,4,5,6)
const obj = {
a:1, b: 2, c:1, d:1
}
// const { a, b, ...restobj } = obj
// console.log(a, b, restobj);
const arr = [1,2,3,4,5]
const [a,b, ...r] = arr
// console.log(a,b,r)
const useState = () => ['valor', () => {}]
const [valor, setValor] = useState()
console.log(valor, setValor);
|
const express = require('express');
const router = express.Router();
const { UserCategory } = require('../models/UserCategory');
router.post('/', async (req, res, next) => {
try {
let userCategory = UserCategory({
category: "categorycategory",
});
await userCategory.save();
return res.status(201).send('userCategory Added Successfully');
}
catch (e) {
return e;
}
});
module.exports = router;
|
import axios from 'axios'
async function getIcon(type) {
const local = 'http://localhost:8000'
const url =
process.env.NODE_ENV !== 'production'
? `${local}/static/img/weather/${type}.svg`
: `/static/img/weather/${type}.svg`
const image = await axios.get(url)
console.log(image)
}
|
import React from 'react';
import { Marker } from "react-google-maps";
import { MarkerClusterer } from "react-google-maps/lib/components/addons/MarkerClusterer";
import HomeIcon from "../../../assets/icons/home.svg";
console.log("Home Icon", HomeIcon);
const noOp = () => { };
const PropertyMarker = ({ property, onClick = noOp }) => {
const position = { lat: property.latitude, lng: property.longitude };
const icon = {
url: HomeIcon,
scaledSize: { width: 32, height: 32 }
}
return <Marker position={position} onClick={onClick} icon={icon} />
};
const PropertiesContents = ({ properties, selectProperty }) => {
const propertyMarkers = properties.map((property, i) => (
<PropertyMarker property={property} key={i} onClick={() => selectProperty(property)} />
));
return (
<MarkerClusterer>
{propertyMarkers}
</MarkerClusterer>
);
};
export default PropertiesContents;
|
import {SubmissionError} from 'redux-form'
import axios from 'axios'
import converter from 'number-to-words'
import numeral from 'numeral'
import alert, {confirmation} from '../../../../components/utils/alerts'
import {smallBox, bigBox, SmartMessageBox} from "../../../../components/utils/actions/MessageActions";
import Msg from '../../../../components/i18n/Msg'
import {isYesClicked, isNoClicked, getLangKey, getDateFrontEndFormat, getTranslation, instanceAxios} from '../../../../components/utils/functions'
import LanguageStore from '../../../../components/i18n/LanguageStore'
import Loader, {Visibility as LoaderVisibility} from '../../../../components/Loader/Loader';
import print from '../../../../components/utils/reportRendering'
const feePaymentSlipTemplate = require('html-loader!./FeePaymentSlip-1.html');
export function generateFeeCollections(values) {
console.log('in generateFeeCollections ', values, values.feeStructureId.join());
// console.log('hi ' , values.studentId==null?"null":values.studentId);
LoaderVisibility(true);
axios.get('api/GenerateFeeCollections/' + values.shiftId + '/' + values.classId + '/'
+ values.sectionId + '/' + values.batchId +'/'+values.feeStructureId.join()+ '/' + (values.studentId==null?"null":values.studentId))
.then(function (response) {
alert('s', 'data has been generated successfully');
var table = $('#FeeCollectionGrid').DataTable();
table.clear();
table.ajax.reload(null, false);
LoaderVisibility(false);
})
.catch(function (error) {
console.log(error);
alert('f', '');
LoaderVisibility(false);
});
}
export function submitFeePayment(values, dueFeeIdsForDelete) {
LoaderVisibility(true);
if (values.feeDueDetails.length > 0) {
values.feeDueDetails[0].paymentDate = values.paymentDate;
values.feeDueDetails[0].paymentComments = values.paymentComments;
values.feeDueDetails[0].paymentModeId = values.paymentModeId;
values.feeDueDetails[0].feeCollectedBy = values.feeCollectedBy;
//console.log(' not empty ..', values.feeDueDetails);
if (dueFeeIdsForDelete.length > 0) {
instanceAxios.post('/api/RemoveFeeCollectionAging/' + dueFeeIdsForDelete)
.then(function (response) {
console.log('remove done .. ');
UpdateFeeAgingApiCall(values);
})
.catch(function (error) {
console.log('error agya.. ', error);
if (error.response) {
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
alert('f', error.response.data.StatusMessage);
LoaderVisibility(false);
} else if (error.request) {
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in node.js
console.log(error.request);
} else {
// Something happened in setting up the request that triggered an Error
console.log('Error', error.message);
}
//console.log(error.config);
//alert('f', '');
LoaderVisibility(false);
});
}
else {
UpdateFeeAgingApiCall(values);
}
}
else {
LoaderVisibility(false);
alert('f', "At least one record must be entered");
}
}
function UpdateFeeAgingApiCall(values) {
instanceAxios.put('/api/UpdateFeeAging', values.feeDueDetails)
.then(function (response) {
// console.log('response submitFeePayment(values)',response);
// console.log('response response.data ',response.data);
// console.log('response response.status ',response.status);
// console.log('response response.data.StatusMessage ',response.data.StatusMessage);
alert('s', 'data has been updated.');
$('#feeCollectionPopup').modal('hide');
$('#paymentId').val(response.data);
LoaderVisibility(false);
})
.catch(function (error) {
console.log('error agya.. ', error);
if (error.response) {
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
alert('f', error.response.data.StatusMessage);
LoaderVisibility(false);
} else if (error.request) {
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in node.js
console.log(error.request);
} else {
// Something happened in setting up the request that triggered an Error
console.log('Error', error.message);
}
//console.log(error.config);
//alert('f', '');
LoaderVisibility(false);
});
}
export function printFeeSlip(langKey, feePaymentId) {
console.log('feePaymentId ==> ', feePaymentId, numeral(2324).format('0,0.00'));
if (feePaymentId) {
langKey = getLangKey ();
alert('i', 'Please wait while report data is loading ... ');
//console.log(',feePaymentSlipTemplate ==> ',feePaymentSlipTemplate)
var htmlContent = feePaymentSlipTemplate; //$("#feePaymentSlip").html(); //this.state.feePaymentSlipTemplate;
axios.get('api/FeePayments/FeePaymentByID/' + langKey + '/' + feePaymentId)
.then(res => {
var masterData = res.data[0];
//console.log('res from api/FeePayments/FeePaymentByID/ ', res, converter.toWords(masterData.TotalPaidAmount));
htmlContent = htmlContent.replace('$SchoolName$', getTranslation('Prime Stars International School'));
htmlContent = htmlContent.replace('$SchoolAddress$', getTranslation('Al Kharj Saudi Arabia'));
htmlContent = htmlContent.replace('$ReportTitle$', getTranslation('Fee Receipt'));
htmlContent = htmlContent.replace('$RollNoText$', getTranslation('RollNoText'));
htmlContent = htmlContent.replace('$NameText$', getTranslation('NameText'));
htmlContent = htmlContent.replace('$BatchText$', getTranslation('BatchText'));
htmlContent = htmlContent.replace('$ClassText$', getTranslation('ClassText'));
htmlContent = htmlContent.replace('$SectionText$', getTranslation('SectionText'));
htmlContent = htmlContent.replace('$PaymentCodeText$', getTranslation('PaymentCodeText'));
htmlContent = htmlContent.replace('$PaymentDateText$', getTranslation('PaymentDateText'));
htmlContent = htmlContent.replace('$PrintDateText$', getTranslation('PrintDateText'));
htmlContent = htmlContent.replace('$FeeTitleText$', getTranslation('FeeTypeText'));
htmlContent = htmlContent.replace('$AmountText$', getTranslation('AmountText'));
htmlContent = htmlContent.replace('$AmountInWordsText$', getTranslation('AmountInWordsText'));
htmlContent = htmlContent.replace('$TotalAmountText$', getTranslation('TotalPaidAmountText'));
htmlContent = htmlContent.replace('$PaymentModeText$', getTranslation('PaymentModeText'));
htmlContent = htmlContent.replace('$BalanceText$', getTranslation('BalanceText'));
htmlContent = htmlContent.replace('$CommentsText$', getTranslation('CommentsText'));
htmlContent = htmlContent.replace('$DiscountAmountText$', getTranslation('DiscountAmountText'));
htmlContent = htmlContent.replace('$PrintedByText$', getTranslation('PrintedByText'));
htmlContent = htmlContent.replace('$FeeCollectedByText$', getTranslation('FeeCollectedByText'));
htmlContent = htmlContent.replace('$Batch$', masterData.BatchName);
htmlContent = htmlContent.replace('$Class$', masterData.ClassName);
htmlContent = htmlContent.replace('$Section$', masterData.SectionName);
htmlContent = htmlContent.replace('$RollNo$', masterData.RollNo);
htmlContent = htmlContent.replace('$Name$', masterData.StudentFullName);
htmlContent = htmlContent.replace('$PaymentCode$', masterData.FeePaymentCode);
htmlContent = htmlContent.replace('$PaymentDate$', getDateFrontEndFormat(masterData.PaidOn));
htmlContent = htmlContent.replace('$PrintDate$', getDateFrontEndFormat(moment()));
htmlContent = htmlContent.replace('$TotalAmount$', numeral(masterData.TotalPaidAmount).format('0,0.00'));
htmlContent = htmlContent.replace('$DiscountAmount$', numeral(masterData.DiscountAmount).format('0,0.00'));
htmlContent = htmlContent.replace('$PaymentMode$', masterData.PaymentModeName);
htmlContent = htmlContent.replace('$Balance$', numeral(masterData.Balance).format('0,0.00'));
htmlContent = htmlContent.replace('$PrintedBy$', "Zeeshan");
//htmlContent = htmlContent.replace('$IssuedBy$', "Admin");
htmlContent = htmlContent.replace('$FeeCollectedBy$', masterData.FeeCollectedBy);
htmlContent = htmlContent.replace('$ComputerGeneratedDocument$', getTranslation('ComputerGeneratedDocumentText'));
htmlContent = htmlContent.replace('$AmountInWords$', converter.toWords(masterData.TotalPaidAmount));
htmlContent = htmlContent.replace('$Comments$', masterData.Comments);
var tblRow = '<tr><td>#</td><td>$title$</td><td class="text-right">$amount$</td></tr>';
var temp = '';
res.data.forEach(function(element, index){
temp += tblRow.replace('#', index+1).replace('$title$', element.FeeTypeName).replace('$amount$', numeral(element.PaidAmount).format('0,0.00'));
});
htmlContent = htmlContent.replace(tblRow, temp);
if (langKey == 'ar') {
htmlContent = htmlContent.replace('direction: ltr;', 'direction: rtl;');
htmlContent = htmlContent.replace('text-right', 'text-left');
}
//this.setState({ feePaymentSlipTemplate: htmlContent });
$("#reportContainer").html(htmlContent);
print('feePaymentSlip');
});
}
}
// function submit(values) {
// console.log(values);
// if (values.feeStructureId > 0) {
// update(values);
// }
// else {
// insert(values);
// }
// }
// function insert(values) {
// LoaderVisibility(true);
// console.log(values);
// instanceAxios.post('/api/FeeStructures', values)
// .then(function (response) {
// LoaderVisibility(false);
// alert('s', 'data has been saved successfully');
// $('#FeeCollectionPopup').modal('hide');
// })
// .catch(function (error) {
// if (error.response) {
// alert('f', error.response.data.StatusMessage);
// LoaderVisibility(false);
// //throw new SubmissionError({ _error: "That's weird. "});
// //reject('error error error');
// console.log('submission error')
// throw new SubmissionError({
// shiftId: 'record already exists',
// _error: 'You cannot proceed further!',
// });
// } else if (error.request) {
// console.log(error.request);
// } else {
// // Something happened in setting up the request that triggered an Error
// console.log('Error', error.message);
// }
// //console.log(error.config);
// //alert('f', '');
// LoaderVisibility(false);
// });
// }
// function update(values) {
// //console.log('in update');
// //console.log(values);
// LoaderVisibility(true);
// instanceAxios.put('/api/FeeStructures', values)
// .then(function (response) {
// alert('s', 'data has been updated successfully');
// $('#FeeCollectionPopup').modal('hide');
// LoaderVisibility(false);
// })
// .catch(function (error) {
// console.log(error);
// alert('f', '');
// LoaderVisibility(false);
// });
// }
export function remove(id, delCell) {
let messageText = LanguageStore.getData().phrases["DeleteConfirmationMessageText"]
|| 'Are you sure, you want to delete this record?';
confirmation(messageText, function (ButtonPressed) {
deleteRecord(ButtonPressed, id, delCell);
});
}
function deleteRecord(ButtonPressed, id, delCell) {
if (isYesClicked(ButtonPressed)) {
LoaderVisibility(true);
console.log('delete feecoll id ', id);
$.ajax({
url: '/api/RemoveFeeCollection/' + id,
type: "POST",
//data : formData,
success: function (data, textStatus, jqXHR) {
console.log('success...');
alert('s', 'data has been deleted successfully');
var table = $('#FeeCollectionGrid').DataTable();
table
.row(delCell.parents('tr'))
.remove()
.draw();
LoaderVisibility(false);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log('error = ', jqXHR, textStatus, errorThrown);
alert('f', '');
LoaderVisibility(false);
}
});
}
else if (isNoClicked(ButtonPressed)) {
// do nothing
}
}
export function removePayment(id, delCell) {
let messageText = LanguageStore.getData().phrases["DeleteConfirmationMessageText"]
|| 'Are you sure, you want to delete this record?';
confirmation(messageText, function (ButtonPressed) {
deletePaymentRecord(ButtonPressed, id, delCell);
});
}
function deletePaymentRecord(ButtonPressed, id, delCell) {
if (isYesClicked(ButtonPressed)) {
LoaderVisibility(true);
console.log('delete removePayment id ', id);
$.ajax({
url: '/api/RemoveFeePayment/' + id,
type: "POST",
//data : formData,
success: function (data, textStatus, jqXHR) {
console.log('success... feePaymentDetailsGrid ??? need to fix aging effect . ');
alert('s', 'data has been deleted successfully');
var table = $('#feePaymentDetailsGrid').DataTable();
table
.row(delCell.parents('tr'))
.remove()
.draw();
LoaderVisibility(false);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log('error = ', jqXHR, textStatus, errorThrown);
alert('f', '');
LoaderVisibility(false);
}
});
}
else if (isNoClicked(ButtonPressed)) {
// do nothing
}
}
|
/*
* REQUIRED FILES / LIBS
**/
import './modules'
var $ = require('jquery')
global.jQuery = $;
require('bootstrap-sass');
require('bootstrap-material-design');
/*
* GLOBAL VARIABLES
**/
var body = $('body');
var nav_container = $('.nav-container');
var nav1 = $('#navbar-primary');
var nav2 = $('#navbar-secondary');
var navbar_content = $('#navbarContent');
var progress = $('.progress-bar');
var window_width = $(window).width();
var nav1_height = get_outer_height(nav1, true);
var nav1_offset = $(nav1).offset().top;
var nav2_height = get_outer_height(nav2, true);
var nav_height = nav1_height + nav2_height;
/*
* INIT FUNCTIONS
**/
$.material.init();
calculate();
$(window).resize(function() {
window_width = $(window).width();
nav1_height = get_outer_height(nav1, true);
nav1_offset = $(nav1).offset().top;
nav2_height = get_outer_height(nav2, true);
nav_height = nav1_height + nav2_height;
calculate();
});
/*
* EVENTS
**/
$('body').on('activate.bs.scrollspy', function() {
var active_nav = $(nav1).find('li.active');
if (!active_nav.length) {
return;
}
var link = $(active_nav).find('a');
if (!link.length) {
return;
}
var hash = $(link).attr('href').substr(1);
var elem = $('#' + hash);
if (!elem.length) {
return;
}
elem.attr('id', '');
window.location.replace('#' + hash);
elem.attr('id', hash);
});
$(document).on('scroll', function() {
var scroll_top = $(document).scrollTop();
var ratio = (scroll_top / ($(document).height() - $(window).height())) * 100;
$(progress).css('width', ratio + '%').attr('aria-valuenow', ratio);
calculate();
});
$('#navbar-primary a').on('click', function(event) {
if (this.hash !== '') {
event.preventDefault();
var hash = this.hash;
$('html, body').animate({
scrollTop: $(hash).offset().top - nav_height
}, 300, function() {
window.location.replace('#' + hash);
});
}
if ($(navbar_content).hasClass('in')) {
$(navbar_content).collapse('hide');
}
});
/*
* FUNCTION DEFINITIONS
**/
// function calc_nav() {
// nav1_height = get_outer_height(nav1, true);
// nav1_offset = $(nav1).offset().top;
// nav2_height = get_outer_height(nav2, true);
// nav_height = nav1_height + nav2_height;
// }
//
// function pad_body() {
// $(body).attr('data-offset', nav_height);
// var scroll_top = $(document).scrollTop();
//
// if (scroll_top >= nav1_offset) {
// $(nav_container).addClass('sticky');
// $(body).css('padding-top', nav_height);
// } else {
// $(nav_container).removeClass('sticky');
// $(body).css('padding-top', '');
// }
// }
function get_outer_height(elem, withMargin) {
if (!elem || !$(elem).length) {
return undefined;
}
if (!withMargin) {
withMargin = false;
}
return $(elem).is(':visible') ? $(elem).outerHeight(withMargin) : 0;
}
function calculate() {
$(body).attr('data-offset', nav_height);
var scroll_top = $(document).scrollTop();
var is_sticky = $(nav_container).hasClass('sticky');
if (scroll_top > nav2_height || window_width <= 767) {
$(nav_container).addClass('sticky');
$(body).css('padding-top', nav_height);
} else {
$(nav_container).removeClass('sticky');
$(body).css('padding-top', '');
}
}
|
import React from "react";
const SearchField = ({ handleChange }) => {
return (
<div>
<input
placeholder="lets find a note..."
onChange={handleChange}
style={{ width: "100%" }}
/>
</div>
);
};
export default SearchField;
|
[{
"_id": "56763e4a01623f6b017c5aea",
"odCode": "160",
"uuidv1": "93379450-a6db-11e5-aa56-f16a2b6d38bf",
"odCreationDate": "1450589770261",
"odUser": {
"controlObj": {
"uuRole": "user",
"isVerified": false
},
"infoObj": {
"uuLastName": "Chai",
"uuFirstName": "Yit Sheng",
"uuGender": "male",
"uuDob": null,
"uuIcNo": "760606145507",
"uuAdd1": "B-5-8 Plaza Mont Kiara",
"uuAdd2": "Mont Kiara",
"uuPostcode": "50480",
"uuTowncity": "Kuala Lumpur",
"uuState": "Wilayah Persekutuan Kuala Lumpur",
"uuHomeTelNo": "77281035",
"uuMobileTelNo": "0122193911",
"uuShipAdd1": "53 Lorong Zaaba",
"uuShipAdd2": "Taman Tun Dr Ismail",
"uuShipPostcode": "60000",
"uuShipTowncity": "Kuala Lumpur",
"uuShipState": "Wilayah Persekutuan Kuala Lumpur"
},
"uuidv1": "6762a070-6d7b-11e5-a2e1-6ff7a2d404ac",
"uuCreationDate": "1444281248759",
"__v": 0,
"password": null,
"email": "yschai@riscmicro.com",
"_id": "55fa80a059c70f6f38399d97"
},
"odTotal": 44.55,
"odCartTotalAmount": 39.9,
"odPayObj": {
"payment": "none"
},
"__v": 0,
"odShip": {
"odShipWayBillBarcode": null,
"odShipWayBillDate": null,
"odShipOutDate": null,
"odTotalWeight": 0.4,
"odCost": 4.65,
"odWeightCode": "1a",
"odZone": "a",
"odWeightBand": 1
},
"controlObj": {
"odToken": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJzdWIiOiI1NWZhODBhMDU5YzcwZjZmMzgzOTlkOTciLCJlbWFpbCI6InlzY2hhaUByaXNjbWljcm8uY29tIiwiaXNzIjoiMjFDYXJ0IiwiaWF0IjoxNDUwNTE2NDUxNTM1LCJzY29wZSI6WyJ1c2VyIl19.ML4q422NbCtiGZoM1b_FHItURwUqs9tl-7Llh64DHeBOfOjwfuTBxmX0xCBeN7LuO3jSb8uKSp5QRpoIY7LUEw",
"odStatus": "new"
},
"odCart": [{
"id": "55ddabddebb7421a234d81bf",
"code": "28",
"name": "Chelsie Side Split Midi Dress (grey)",
"image": "55ddabddebb7421a234d81bfimage1.jpg",
"sellingprice": 39.9,
"retailprice": 60,
"qty": 1,
"check": true,
"checksubTotal": 39.9,
"weight": 0.4,
"actualWeight": 0.4,
"volumetricWeight": 0
}]
}]
|
import React from 'react';
import Typography from '@material-ui/core/Typography';
import Paper from '@material-ui/core/Paper';
import { makeStyles } from '@material-ui/core/styles';
import InfoIcon from '@material-ui/icons/Info';
const useStyles = makeStyles((theme) => ({
message: {
color: 'blue',
display: 'flex',
alignItems: 'center',
textAlign: 'left'
},
paper: {
padding: theme.spacing(3)
},
icon: {
marginRight: theme.spacing(2)
}
}));
export default function OnboardingStepChecklistAlert(props) {
const classes = useStyles();
return (
<>
<Paper className={classes.paper} elevation={3}>
<Typography variant="h6" component="h1" className={classes.message}>
<InfoIcon className={classes.icon} /> {props.children}
</Typography>
</Paper>
<br />
<br />
</>
)
}
|
import { Fragment } from "react";
import { Row } from "reactstrap";
import Leftbar from "./leftbar";
import Rightbar from "./rightbar";
const Header = () => {
return (
<Fragment>
<div className="page-header">
<Row className="header-wrapper m-0">
<Leftbar />
<Rightbar />
</Row>
</div>
</Fragment>
);
};
export default Header;
|
define(['require'], function () {
'use strict'
var ngApp = angular.module('app', [
'protect.ui.xxt',
'ngRoute',
'ui.bootstrap',
'ui.tms',
'http.ui.xxt',
'notice.ui.xxt',
'tinymce.ui.xxt',
'ui.xxt',
'member.xxt',
'service.matter',
'service.article',
'thumbnail.ui.xxt',
])
ngApp.constant('cstApp', {
innerlink: [
{
value: 'article',
title: '单图文',
url: '/rest/pl/fe/matter',
},
{
value: 'channel',
title: '频道',
url: '/rest/pl/fe/matter',
},
{
value: 'enroll',
title: '记录',
url: '/rest/pl/fe/matter',
},
{
value: 'signin',
title: '签到',
url: '/rest/pl/fe/matter',
},
],
})
ngApp.config([
'$routeProvider',
'$locationProvider',
'$controllerProvider',
'srvSiteProvider',
'srvAppProvider',
'srvTagProvider',
function (
$routeProvider,
$locationProvider,
$controllerProvider,
srvSiteProvider,
srvAppProvider,
srvTagProvider
) {
var RouteParam = function (name, baseURL) {
!baseURL && (baseURL = '/views/default/pl/fe/matter/article/')
this.templateUrl = baseURL + name + '.html?_=' + new Date() * 1
this.controller = 'ctrl' + name[0].toUpperCase() + name.substr(1)
this.reloadOnSearch = false
this.resolve = {
load: function ($q) {
var defer = $q.defer()
require([baseURL + name + '.js'], function () {
defer.resolve()
})
return defer.promise
},
}
}
ngApp.provider = {
controller: $controllerProvider.register,
}
$routeProvider
.when('/rest/pl/fe/matter/article/body', new RouteParam('body'))
.when('/rest/pl/fe/matter/article/preview', new RouteParam('preview'))
.when('/rest/pl/fe/matter/article/coin', new RouteParam('coin'))
.when('/rest/pl/fe/matter/article/user', new RouteParam('user'))
.when('/rest/pl/fe/matter/article/log', new RouteParam('log'))
.otherwise(new RouteParam('main'))
$locationProvider.html5Mode(true)
//设置服务参数
;(function () {
var ls, siteId, articleId
ls = location.search
siteId = ls.match(/[\?&]site=([^&]*)/)[1]
articleId = ls.match(/[\?&]id=([^&]*)/)[1]
//
srvSiteProvider.config(siteId)
srvTagProvider.config(siteId)
srvAppProvider.setSiteId(siteId)
srvAppProvider.setAppId(articleId)
})()
},
])
ngApp.controller('ctrlArticle', [
'$scope',
'$location',
'srvSite',
'srvApp',
'tmsThumbnail',
function ($scope, $location, srvSite, srvApp, tmsThumbnail) {
$scope.subView = ''
$scope.$on('$locationChangeSuccess', function (event, currentRoute) {
var subView = currentRoute.match(/([^\/]+?)\?/)
$scope.subView = subView[1] === 'article' ? 'main' : subView[1]
switch ($scope.subView) {
case 'main':
case 'body':
$scope.opened = 'edit'
break
case 'preview':
$scope.opened = 'publish'
break
case 'user':
case 'coin':
case 'log':
$scope.opened = 'other'
break
default:
$scope.opened = ''
}
})
$scope.switchTo = function (subView) {
var url = '/rest/pl/fe/matter/article/' + subView
$location.path(url)
}
$scope.update = function (names) {
return srvApp.update(names)
}
$scope.editMschema = function (oMschema) {
if (oMschema.matter_id) {
if (oMschema.matter_type === 'mission') {
location.href =
'/rest/pl/fe/matter/mission/mschema?id=' +
oMschema.matter_id +
'&site=' +
$scope.editing.siteid +
'#' +
oMschema.id
} else {
location.href =
'/rest/pl/fe/site/mschema?site=' +
$scope.editing.siteid +
'#' +
oMschema.id
}
} else {
location.href =
'/rest/pl/fe?view=main&scope=user&sid=' +
$scope.editing.siteid +
'&mschema=' +
oMschema.id
}
}
srvSite.get().then(function (oSite) {
$scope.site = oSite
})
srvSite.tagList().then(function (oTag) {
$scope.oTag = oTag
})
srvSite.tagList('C').then(function (oTag) {
$scope.oTagC = oTag
})
srvSite.snsList().then(function (oSns) {
$scope.sns = oSns
$scope.snsNames = oSns.names
$scope.snsCount = oSns.count
srvApp.get().then(function (editing) {
$scope.editing = editing
!editing.attachments && (editing.attachments = [])
$scope.entry = {
url: editing.entryUrl,
qrcode:
'/rest/site/fe/matter/article/qrcode?site=' +
$scope.editing.siteid +
'&url=' +
encodeURIComponent(editing.entryUrl),
}
if ($scope.editing.matter_cont_tag !== '') {
$scope.editing.matter_cont_tag.forEach(function (cTag, index) {
$scope.oTagC.forEach(function (oTag) {
if (oTag.id === cTag) {
$scope.editing.matter_cont_tag[index] = oTag
}
})
})
}
if ($scope.editing.matter_mg_tag !== '') {
$scope.editing.matter_mg_tag.forEach(function (cTag, index) {
$scope.oTag.forEach(function (oTag) {
if (oTag.id === cTag) {
$scope.editing.matter_mg_tag[index] = oTag
}
})
})
}
srvSite
.memberSchemaList($scope.editing)
.then(function (aMemberSchemas) {
$scope.memberSchemas = aMemberSchemas
$scope.mschemasById = {}
$scope.memberSchemas.forEach(function (mschema) {
$scope.mschemasById[mschema.id] = mschema
})
})
})
})
window.onbeforeunload = function (e) {
if (!$scope.editing.pic && !$scope.editing.thumbnail) {
tmsThumbnail.thumbnail($scope.editing)
}
}
},
])
/***/
require(['domReady!'], function (document) {
angular.bootstrap(document, ['app'])
})
/***/
return ngApp
})
|
(function () {
'use strict';
angular.module('AdBase').controller('loginController',loginController);
loginController.$inject = ['$scope', 'loginService','orgUnitsService'];
function loginController($scope,loginService,orgUnitsService){
var self = this ;
self.searchInput = {};
self.totalItems ;
self.itemPerPage=25;
self.currentPage = 1;
self.maxSize = 5 ;
self.logins = [];
self.searchEntity = {};
self.selectedLogin = {} ;
self.selectedIndex ;
self.handleSearchRequestEvent = handleSearchRequestEvent;
self.handlePrintRequestEvent = handlePrintRequestEvent;
self.paginate = paginate;
self.orgUnits = [];
init();
function init(){
self.searchInput = {
entity:{},
fieldNames:[],
start:0,
max:self.itemPerPage
}
findByLike(self.searchInput);
loadOrg();
}
function loadOrg(){
orgUnitsService.findActifsFromNow().then(function(entitySearchResult){
self.orgUnits = entitySearchResult;
})
}
function findByLike(searchInput){
loginService.findLogins(searchInput).then(function(entitySearchResult) {
self.logins = entitySearchResult.resultList;
self.totalItems = entitySearchResult.count ;
});
}
function processSearchInput(){
var fileName = [];
if(self.searchInput.entity.loginName){
fileName.push('loginName') ;
}
if(self.searchInput.entity.fullName){
fileName.push('fullName') ;
}
if(self.searchInput.entity.ouIdentif){
fileName.push('ouIdentif') ;
}
self.searchInput.fieldNames = fileName ;
return self.searchInput ;
};
function handleSearchRequestEvent(){
processSearchInput();
findByLike(self.searchInput);
};
function paginate(){
self.searchInput.start = ((self.currentPage - 1) * self.itemPerPage) ;
self.searchInput.max = self.itemPerPage ;
findByLike(self.searchInput);
};
function handlePrintRequestEvent(){
}
};
})();
|
const _ = require('lodash')
const async = require('async')
const vector = require('./vector')
function Physics() {
this.intersectionsChecked = {}
}
Physics.prototype.update = function (deltatime, entities, map) {
const movementFunctions = []
const onCollideFunctions = []
for(const origin in entities) {
const object = entities[origin]
if (!object.collider) continue
let directionToMove = object.velocity
if (!directionToMove || vector.length(directionToMove) === 0) continue
let nextPosition = {
x: object.position.x + directionToMove.x * deltatime,
y: object.position.y + directionToMove.y * deltatime,
}
if(!object.collider.attr.isFlying) {
let nextPositionVer = {
x: object.position.x,
y: object.position.y + directionToMove.y * deltatime,
}
let nextPositionHor = {
x: object.position.x + directionToMove.x * deltatime,
y: object.position.y,
}
const canWalk = map.isWalkable(nextPosition)
if(!canWalk) {
const canWalkVer = map.isWalkable(nextPositionVer)
if(canWalkVer) {
nextPosition = nextPositionVer
} else {
const canWalkHor = map.isWalkable(nextPositionHor)
if(canWalkHor) {
nextPosition = nextPositionHor
} else {
continue
}
}
}
}
let nextObj = Object.assign({}, object, { position: nextPosition })
for(const comp in entities) {
if (!directionToMove || vector.length(directionToMove) === 0) break
if (origin === comp) continue
const objectCmp = entities[comp]
if (!objectCmp.collider) continue
if(!this.shouldCollide(object.collider.with, objectCmp.tags)) continue
let collided = this.boxCollision( nextObj, objectCmp )
if (collided) {
const dirCollision = vector.direction(objectCmp.position, object.position)
const dirCollisionInv = vector.direction(object.position, objectCmp.position)
if (object.onCollide) onCollideFunctions.push(_ => object.onCollide(objectCmp, dirCollision, dirCollisionInv))
directionToMove = vector.multiply(vector.length(directionToMove), vector.length(directionToMove))
}
}
if (directionToMove && vector.length(directionToMove) > 0) {
movementFunctions.push(_ => {
object.position = nextObj.position
})
}
}
for (let i = 0; i < movementFunctions.length; i++) movementFunctions[i]()
for (let i = 0; i < onCollideFunctions.length; i++) onCollideFunctions[i]()
}
Physics.prototype.shouldCollide = function(withs, tags) {
const id = withs.join('') + tags.join('')
if(!_.isNil(this.intersectionsChecked[id])) return this.intersectionsChecked[id]
const coll = _.intersection(withs, tags).length !== 0
this.intersectionsChecked[id] = coll
return coll
}
Physics.prototype.circleCollision = function (obj1, obj2) {
const centerDiff = Math.pow((obj1.position.x - obj2.position.x), 2) + Math.pow((obj1.position.y - obj2.position.y), 2)
const radiusDiff = Math.pow((obj1.collider.radius + obj2.collider.radius), 2)
return radiusDiff >= centerDiff
}
Physics.prototype.boxCollision = function (obj1, obj2) {
const obj1Edges = obj1.collider.edges(obj1.position)
const obj2Edges = obj2.collider.edges(obj2.position)
if (obj1Edges.max.x <= obj2Edges.min.x) return false // a is left of b
if (obj1Edges.min.x >= obj2Edges.max.x) return false // a is right of b
if (obj1Edges.max.y <= obj2Edges.min.y) return false // a is above b
if (obj1Edges.min.y >= obj2Edges.max.y) return false // a is below b
return true // boxes overlap
}
module.exports = Physics
|
// 定义所有错误消息
const ERROR_MESSAGE = {
// 网络请求问题
SERVER_ERROR: '服务器出错, 请稍后尝试!',
TIMEOUT: '数据请求超时!',
NOT_FOUND: '请求的资源文件不存在!',
UNCOMMITTED: '未被授权,没有操作权限!',
REQUIRED_LOGIN: '需要登录!',
UNKNOWN_ERROR: '未列出的错误原因!',
ERR_REQUEST_ID: '请求的ID不正确'
};
class ErrorService {
getErrorMessage(errorCode) {
if (errorCode.serviceMsg) {
return errorCode.serviceMsg;
}
return ERROR_MESSAGE[errorCode.code] || ERROR_MESSAGE.SERVER_ERROR;
}
}
export default ErrorService;
|
import React, { Component } from "react";
import { Mutation } from "react-apollo";
import gql from "graphql-tag";
import Error from "../ErrorMessage";
import { CURRENT_USER_QUERY } from "../Accounts/User";
/* Mutation Query */
const SIGNUP_USER_MUTATION = gql`
mutation SIGNUP_USER_MUTATION(
$email: String!
$name: String!
$password: String!
) {
signUpUser(email: $email, name: $name, password: $password) {
id
email
name
}
}
`;
class SignUp extends Component {
state = {
name: "",
password: "",
email: "",
};
addToState = e => {
this.setState({ [e.target.name]: e.target.value });
};
render() {
return (
<Mutation
mutation={SIGNUP_USER_MUTATION}
variables={this.state}
refetchQueries={[{ query: CURRENT_USER_QUERY }]}
>
{(signUpUser, { error, loading }) => (
<form
className="forms"
onSubmit={async e => {
e.preventDefault();
await signUpUser();
this.setState({
name: "",
email: "",
password: "",
});
}}
method="post"
>
<h1 className="header1">Create Account</h1>
<span>or use your email for registration</span>
<Error
error={
<span>
This email has been used to create an existing account
</span>
}
/>
<input
type="text"
placeholder="First, then Last Name"
name="name"
required
autoFocus
value={this.state.name}
onChange={this.addToState}
/>
<input
type="email"
placeholder="Enter your Email"
name="email"
style={{ textTransform: "lowercase" }}
required
value={this.state.email}
onChange={this.addToState}
/>
<input
type="password"
placeholder="Enter Password"
title="Atleast 6 characters with one capital letter"
name="password"
required
value={this.state.password}
onChange={this.addToState}
/>
<button className="btn" type="submit">
Sign{loading ? "ing" : ""} Up
</button>
</form>
)}
</Mutation>
);
}
}
export default SignUp;
|
var Checker = require('../lib/checker');
var assert = require('assert');
describe('rules/require-preceding-comma', function() {
var checker;
beforeEach(function() {
checker = new Checker();
checker.registerDefaultRules();
checker.configure({ requirePrecedingComma: true });
});
it('should report succeeding comma', function() {
assert(checker.checkString(
'var x = { a : 1,\n' +
'b: 2 };'
).getErrorCount() === 1);
assert(checker.checkString(
'var x = 1,\n' +
'y = 2,\n' +
'z = 1;'
).getErrorCount() === 2);
});
it('should not report preceding comma', function() {
assert(checker.checkString('var x = { a : 1\n, b: 2 };').isEmpty());
assert(checker.checkString('var x = 1\n, y = 2').isEmpty());
});
});
|
import React from 'react';
import { withStyles } from 'material-ui/styles';
import FolderIcon from 'material-ui-icons/Folder';
import IconButton from 'material-ui/IconButton';
import FolderList from '../containers/ktpht_folders'
import Menu, { MenuItem } from 'material-ui/Menu';
import Typography from 'material-ui/Typography';
import ChevronRight from 'material-ui-icons/ChevronRight';
import Divider from 'material-ui/Divider';
const styles = theme => ({
root: {
display: 'flex',
},
poper: {
zIndex:1000,
},
popperClose: {
pointerEvents: 'none',
},
button: {
margin: theme.spacing.unit,
},
breadcrumbText: {
lineHeight: '64px',
},
breadcrumbSepa: {
height: '64px',
}
});
const ITEM_HEIGHT = 48;
class KtphtFolderMenu extends React.Component {
state = {
open: false,
lv1: null,
lv2: null,
lv3: null,
lv4: null,
};
handleUpdateBreadcrumb = (lv1, lv2, lv3, lv4) => {
this.setState({
lv1: (lv1 === undefined ? null : (lv1 === '' ? '未設定' : lv1)),
lv2: (lv2 === undefined ? null : (lv2 === '' ? '未設定' : lv2)),
lv3: (lv3 === undefined ? null : (lv3 === '' ? '未設定' : lv3)),
lv4: (lv4 === undefined ? null : (lv4 === '' ? '未設定' : lv4)),
});
}
handleClick = (event) => {
event.preventDefault(); // prevent selection quirk
this.setState({ anchorEl: event.currentTarget });
};
handleClose = () => {
this.setState({ anchorEl: null });
};
render() {
const { classes } = this.props;
const { anchorEl } = this.state;
return (
<div className={classes.root}>
<IconButton className={classes.button}
aria-owns={Boolean(anchorEl) ? 'menu-list' : null}
aria-haspopup="false"
onClick={this.handleClick}
aria-label="メニュー">
<FolderIcon />
</IconButton>
{(() => {
if (this.state.lv1 != null) {
return (
<Typography type="body1" align="right" className={classes.breadcrumbText}>
{this.state.lv1}
</Typography>
);
} else {
return (
<Typography type="body1" align="right" className={classes.breadcrumbText}>
工程写真の絞り込み
</Typography>
);
}
})()}
{ this.state.lv2 != null ? <ChevronRight className={classes.breadcrumbSepa}/> : ''}
{(() => {
if (this.state.lv2 != null) {
return (
<Typography type="body1" align="right" className={classes.breadcrumbText}>
{this.state.lv2}
</Typography>
);
}
})()}
{ this.state.lv3 != null ? <ChevronRight className={classes.breadcrumbSepa}/> : ''}
{(() => {
if (this.state.lv3 != null) {
return (
<Typography type="body1" align="right" className={classes.breadcrumbText}>
{this.state.lv3}
</Typography>
);
}
})()}
{ this.state.lv4 != null ? <ChevronRight className={classes.breadcrumbSepa}/> : ''}
{(() => {
if (this.state.lv4 != null) {
return (
<Typography type="body1" align="right" className={classes.breadcrumbText}>
{this.state.lv4}
</Typography>
);
}
})()}
<Menu
id="long-menu"
anchorEl={this.state.anchorEl}
open={Boolean(anchorEl)}
onClose={this.handleClose}
PaperProps={{
style: {
maxHeight: ITEM_HEIGHT * 10,
maxWidth: 600,
},
}}
>
<FolderList data={this.props.folders}
filterLvs={this.props.filterLvs}
onFolderSelect={(lv1,lv2,lv3,lv4) => {
this.props.onFolderSelect(lv1, lv2, lv3, lv4);
this.handleClose();
this.handleUpdateBreadcrumb(lv1, lv2, lv3, lv4);
}} />
<Divider />
<MenuItem onClick={() => {
this.props.onFolderSelect();
this.handleClose();
this.handleUpdateBreadcrumb();
}}>
<Typography type="body1" align="right">絞り込みをクリア</Typography>
</MenuItem>
</Menu>
</div>
);
}
}
export default withStyles(styles)(KtphtFolderMenu);
|
/*
* eCommerceViewDirectionsComponent.js
*
* Copyright (c) 2017 HEB
* All rights reserved.
*
* This software is the confidential and proprietary information
* of HEB.
*/
'use strict';
/**
* product details -> product -> eCommerce View -> Directions component.
*
* @author vn00602
* @since 2.14.0
*/
(function () {
angular.module('productMaintenanceUiApp').component('eCommerceViewDirection', {
scope: '=',
bindings: {
currentTab: '<',
productMaster: '<',
eCommerceViewDetails: '=',
getECommerceViewDataSource:'&',
isEditText: '='
},
// Inline template which is bind to message variable in the component controller
templateUrl: 'src/productDetails/product/eCommerceView/eCommerceViewDirections.html',
// The controller that handles our component logic
controller: DirectionController
});
DirectionController.$inject = ['$scope', 'ECommerceViewApi', '$sce', 'PermissionsService','$rootScope'];
/**
* ECommerce View Directions component's controller definition.
*
* @param $scope scope of the eCommerceView component.
* @param eCommerceViewApi the api of eCommerceView.
* @constructor
*/
function DirectionController($scope, eCommerceViewApi, $sce, permissionsService,$rootScope) {
/**
* All CRUD operation controls of choice option page goes here.
*/
var self = this;
/**
* Reload eCommerce view key.
* @type {string}
*/
self.RELOAD_ECOMMERCE_VIEW = 'reloadECommerceView';
/**
* Reset eCommerce view.
* @type {string}
*/
self.RESET_ECOMMERCE_VIEW = 'resetECommerceView';
/**
* Reload after save popup.
* @type {string}
*/
self.RELOAD_AFTER_SAVE_POPUP = 'reloadAfterSavePopup';
/**
* The default error message.
*
* @type {string}
*/
self.UNKNOWN_ERROR = "An unknown error occurred.";
/**
* Max length of textarea input.
*
* @type {number}
*/
self.MAX_LENGTH = 10000;
/**
* The direction logical attribute id.
*
* @type {number}
*/
self.DIRECTION_ATTRIBUTE_ID = 1676;
/**
* Flag for waiting response from back end.
*
* @type {boolean}
*/
self.isWaitingForResponse = false;
/**
* The product maintenance source selected when click Edit text button.
*
* @type {boolean}
*/
self.isProductMaintenanceSourceSelected = false;
/**
* The flag that check if Directions is editable or not.
*
* @type {boolean}
*/
self.isEditingDirection = false;
const EDIT_DIRECTION_PHY_ATTR_ID = 1654;
const SRC_SYS_ID_EDIT = 4;
self.hasPermission = false;
/**
* Component ngOnInit lifecycle hook. This lifecycle is executed every time the component is initialized.
*/
this.$onInit = function () {
self.isWaitingForResponse = true;
self.findDirections();
};
/**
* Component will reload the data whenever the item is changed in.
*/
this.$onChanges = function () {
self.isWaitingForResponse = true;
self.isProductMaintenanceSourceSelected = false;
self.findDirections();
};
/**
* Reload ECommerceView.
*/
$scope.$on(self.RELOAD_ECOMMERCE_VIEW, function() {
self.$onChanges();
});
/**
* Reset eCommerce view.
*/
$scope.$on(self.RESET_ECOMMERCE_VIEW, function() {
self.setEditMode();
self.isProductMaintenanceSourceSelected = false;
});
/**
* Reload after save popup.
*/
$scope.$on(self.RELOAD_AFTER_SAVE_POPUP, function(event, attributeId, status) {
if(attributeId === self.DIRECTION_ATTRIBUTE_ID){
self.isEditingDirection = false;
if(status === true){
self.$onChanges();
}else{
self.isWaitingForResponse = true;
}
}
});
/**
* Find the directions by product id or upc.
*/
self.findDirections = function () {
eCommerceViewApi.findDirections({
productId: self.productMaster.prodId,
scanCodeId: self.productMaster.productPrimaryScanCodeId
},
self.directionResponseSuccess,
self.fetchError);
};
/**
* Handle when click Edit source button, to find all the direction attribute priorities by product id or upc.
*
* @param attributeId
* @param headerTitle
*/
self.editSourceHandle = function (attributeId, headerTitle) {
self.isEditText = self.isEditingDirection;
self.getECommerceViewDataSource({
productId: self.productMaster.prodId,
scanCodeId: self.productMaster.productPrimaryScanCodeId,
attributeId: attributeId,
salesChannel: self.currentTab.saleChannel.id,
headerTitle: headerTitle,
typeSource: 'type1'});
};
/**
* Handle when click Edit text of Directions.
*/
self.editTextDirection = function () {
self.isEditingDirection = true;
self.isProductMaintenanceSourceSelected = true;
};
/**
* Load the directions data response success.
*
* @param result the results to load.
*/
self.directionResponseSuccess = function (result) {
self.isWaitingForResponse = false;
self.differentWithDefaultValue = false;
self.isEditingDirection = false;
if (!result) {
self.eCommerceViewDetails.directions = {};
self.eCommerceViewDetails.directionsOrg = {};
} else {
self.eCommerceViewDetails.directions = result;
self.eCommerceViewDetails.directionsOrg = angular.copy(self.eCommerceViewDetails.directions);
self.differentWithDefaultValue = result.differentWithDefaultValue;
self.setEditMode();
}
};
/**
* Callback for when the backend returns an error.
*
* @param error The error from the back end.
*/
self.fetchError = function (error) {
self.isWaitingForResponse = false;
self.isEditingDirection = false;
self.success = null;
self.error = self.getErrorMessage(error);
};
/**
* Returns error message.
*
* @param error
* @returns {string}
*/
self.getErrorMessage = function (error) {
if (error && error.data) {
if (error.data.message) {
return error.data.message;
} else {
return error.data.error;
}
} else {
return self.UNKNOWN_ERROR;
}
};
/**
* Check edit status or not.
*
* @returns {boolean}
*/
self.setEditMode = function(){
if (self.eCommerceViewDetails.directions != null) {
self.isEditingDirection = self.eCommerceViewDetails.directions.sourceSystemId === SRC_SYS_ID_EDIT && self.eCommerceViewDetails.directions.physicalAttributeId == EDIT_DIRECTION_PHY_ATTR_ID;
}
self.hasPermission = permissionsService.getPermissions('PD_ECOM_04', 'EDIT');
};
/**
* Check change direction.
*/
self.checkChangeDirection = function () {
$rootScope.contentChangedFlag = true;
if(angular.equals(self.eCommerceViewDetails.directions, self.eCommerceViewDetails.directionsOrg)){
$rootScope.contentChangedFlag = false;
}
}
}
})();
|
import React, { Component } from 'react';
import axios from 'axios';
import { Link } from 'react-router-dom';
import EditActivity from './EditActivity';
import AddExperience from '../experiences/AddExperience';
import ExperiencesList from '../experiences/ExperiencesList';
import './ActivityDetails.css';
class ActivityDetails extends Component {
constructor(props) {
super(props);
this.state = {
title: "",
description: "",
category: "",
status: "",
owner: "",
_id: "",
showForm: false,
experiences: []
}
}
getActivityDetails = () => {
axios.get(`${process.env.REACT_APP_API_URL}/activities/${this.props.match.params.activityId}`, { withCredentials: true })
.then((responseFromApi) => {
const selectedActivity = responseFromApi.data
this.setState(selectedActivity)
}, error => console.log(error))
}
componentDidMount() {
this.getActivityDetails()
}
toggleForm = () => {
this.state.showForm ? this.setState({ showForm: false }) : this.setState({ showForm: true })
}
render() {
return (
<div className="page-container">
<h1>Activities</h1>
{this.state.showForm ? <h3>Edit activity</h3> : <h3>Details</h3>}
<div className="activity-details-page">
<div>
{this.state.showForm ?
<div className="activity-box">
<button onClick={this.toggleForm} className="close-btn">X</button>
<EditActivity {...this.props} theActivity={this.state} toggleForm={this.toggleForm} getActivityDetails={this.getActivityDetails} />
</div>
:
<div className="activity-box">
<h4>{this.state.title}</h4>
<p>{this.state.description}</p>
<p className="category-tag">{this.state.category}</p>
<div className="activity-box-details">
<p>{this.state.experiences.length} {this.state.experiences.length == 1 ? "Experience" : "Experiences"}</p>
<button onClick={this.toggleForm} className="edit-btn">Edit Activity</button>
</div>
</div>
}
</div>
<h3>Experiences</h3>
<ExperiencesList experiences={this.state.experiences} activityId={this.state._id} getActivityDetails={this.getActivityDetails} />
</div>
</div>
)
}
}
export default ActivityDetails;
|
import React from 'react';
import './Destination.scss';
import Destination from './Destination.js'
var DestinationArr = [
{
index: 2,
image: "./img/francja.jpg",
country_name: 'Francja',
number_of_offers: 3,
more_destinations: "Wyjazdy do Francji",
},
{
index: 1,
image: './img/szwajcaria.jpg',
country_name: 'Szwajcaria',
number_of_offers: 2,
more_destinations: "Wyjazdy do Szwajcarii",
}
];
DestinationArr.sort(function(a,b){
return parseInt(a.index) - parseInt(b.index);
})
function DestinationWrapper() {
return (
<div id="destinationContainer">
<div className="content">
<div className="mainText">
<h2>Obierz swój kierunek</h2>
<p className="mainText">TAKSIDI to zorganizowane wyjazdy narciarskie i snowboardowe dla młodych i aktywnych ludzi do renomowanych alpejskich ośrodków we Francji, Włoszech, Szwajcarii i Austrii. Nasze wyjazdy to połączenie dobrej zabawy na najlepszych stokach, imprez, warsztatów i mnóstwa dodatkowych atrakcji.</p>
</div>
<div className="destinationWrapper">
{DestinationArr.map((oneCountry,index) =>
<Destination key={index} text={oneCountry.text} image={oneCountry.image} country_name={oneCountry.country_name} number={oneCountry.number_of_offers} />
)}
<div className="oneDestination">
<div className="text">
<h3>... i wiele więcej</h3>
<p>Sprawdź wszystkie dostępne destynacje w sezonie 2020/2021.</p>
<button className="destinationButton btn">Sprawdź</button>
</div>
</div>
</div>
</div>
</div>
);
}
export default DestinationWrapper
|
// # Learner State Processor
// ## learner_state.processor.js
// Imports the required dependencies.
const _ = require('lodash');
const highland = require('highland');
const log = require('../commons/logger')('Learner_State_Processor');
// `toTriplesOfLearnerState` converts a Learner State document to a collection of triples.
// A triple is a combination of a source, target and relation.
// `toTriplesOfLearnerState` inputs a message and then creates
// a collection of triples following the steps below.
// 1. Stores the `message` in `header` which is to be
// used in later stages to send Acknowledgements.
// 2. Parses the string in the message to the learnerState.
// 3. Creates a `source` using the `label` and the `identifier`.
// With `identifier` being the property used to create user Node.
// 4. Then using the `elements` of the learnState we create `target` and `relation`.
// 5. Then based on the state of the element 0, 1 or 2.
// It is mapped to a relation like `yetToStart`, `started`, `completed`.
// 6. And by this it generates a triple for each `element`.
// 7. And then returns an object containing `header` and `triples`.
const toTriplesOfLearnerState = (message) => {
log.debug('To Triples Of Learner State');
const header = message;
const percpLearnerState = JSON.parse(message.content.toString());
const source = {
properties: {
label: 'user',
identifier: percpLearnerState.student_id
},
options: {
uniqueConstraintsOn: [
'identifier'
]
}
};
const learningResources = percpLearnerState.elements.filter(element => element.elementType === 'learningresource');
const triplesOfLearnerStateAndLearningResource = learningResources.map((element) => {
const target = {
properties: {
label: 'resource',
resourceId: element.identifier
},
options: {
uniqueConstraintsOn: [
'resourceId'
]
}
};
let relationType = 'yetToStart';
if (typeof element.state !== 'undefined') {
if (element.state === 1) relationType = 'started';
if (element.state === 2) relationType = 'completed';
}
const relation = {
properties: {
relation: relationType
},
options: {
uniqueConstraintsOn: [
'relation'
]
}
};
return { source, target, relation };
});
const triplesOfLearnerStateAndCourse = [{
source,
target: {
properties: {
label: 'course',
courseId: percpLearnerState.courseId
},
options: {
uniqueConstraintsOn: [
'courseId'
]
}
},
relation: {
properties: {
relation: 'subscribedTo'
}
}
}];
const triples = _.concat(
triplesOfLearnerStateAndLearningResource,
triplesOfLearnerStateAndCourse
);
return { header, triples };
};
// The `processor` input a stream and maps it toTriplesOfLearnerState.
const processor = highland.pipeline(highland.map(toTriplesOfLearnerState));
// Exports the processor.
module.exports = processor;
|
var sc = require("soundclouder")
var client_id = '0717fd902d21b8df7ef5db79fc9d43d5'
var client_secret = '61482a2ee8c176d47c590e55b34d8a89'
var redirect_uri = ''
sc.init(client_id, client_secret, redirect_uri)
sc.auth( code, function (error, access_token) {
if (error) {
console.error(e.message)
} else {
console.log('access_token= ' + access_token)
}
})
sc.get('/tracks/' + track_id, access_token, function (error, data) {
console.log( data.title )
})
|
export function isEqual(a, b) {
let set1 = new Set(a);
let set2 = new Set(b);
return set1.size === set2.size && [...set1].every((value) => set2.has(value));
}
export const getWords = ['application', 'programming', 'interface', 'wizard'];
|
//Tutorial 24
// Plugin_Command
// Alias the plugin command function
var soul_interpreterCommand = Game_Interpreter.prototype.pluginCommand;
Game_Interpreter.prototype.pluginCommand = function(command, args) {
// to be overridden by plugins
soul_interpreterCommand.apply(this);
// printString alert "Hello World"
if (command == 'access'){
switch(args[0]) {
case 'item':
SceneManager.push(Scene_Item);
break;
case 'save':
SceneManager.push(Scene_Save);
break;
}
}
};
|
import loginService from "../../service/login.service";
import { STORAGE_KEYS } from "../../service/sessionStorage.service";
const oauthRequired = (to, from, next) => {
if (loginService.isLogin()) {
next();
} else {
sessionStorage.removeItem(STORAGE_KEYS.TOKEN_LOGGED_IN);
next.redirect('/');
}
};
export default oauthRequired;
|
const express = require('express');
const router = express.Router();
// importar express validator
//const {body}=require('express-validator/check');
//const express=require('express-validator');
//importar el controlador
const proyectoscontrolers =require
('../controlers/proyectoscontrolers');
const tareasControlers=require('/controlers/tareascontrolers');
const usuariosControlers=require('/controlers/usuariosControlers');
const authController= require('../controlers/authControlers');
module.exports = function(){
//ruta para el home
router.get('/',authControlers.usuarioAutenticado,proyectosControlers.proyectosHome);
router.get('/nuevo-proyecto',authControlers.usuarioAutenticado,proyectosController.formularioProyecto);
router.post('/nuevo-proyecto',authControlers.usuarioAutenticado,
body('nombre').not().isEmpty().trim().escape(),
proyectoscontrolers.nuevoProyecto);
/*router.get('/nosotros',(req, res)=>){
res.render('nosotros');
)};*/
// Listar Proyecto
router.get('/proyectos/:url,authControlers.usuarioAutenticado,proyectoControlers.proyectoPorUrl');
// Actulaizar el proyecto
router.get('/proyecto/editar/:id',authControlers.usuarioAutenticado,proyectoControlers.proyectoPorUrl);
router.post('/nuevo-proyecto/:id',authControlers.usuarioAutenticado,
body('nombre').not().isEmpty().trim().escape(),
proyectoscontrolers.actualizarProyecto
);
//Eliminar proyecto
router.delete('/proyectos/:url',authControlers.usuarioAutenticado, proyectosControlers.eliminarProyecto);
// Tareas
router.post('/proyectos/:url',authControlers.usuarioAutenticado,tareasControlers.agregarTarea);
//Actualizar Tarea
router.patch('/tareas/:id',authControlers.usuarioAutenticado,tareasControlers.combiarEstadoTarea);
// Eliminar tarea
router.delete('/tareas/:id',authControlers.usuarioAutenticado,tareasControlers.eliminarTarea);
router.get('/crear-cuenta',usuariosControlers.formCrearCuenta);
router.post('/crear-cuenta',usuariosControlers.crearCuenta);
router.get('/confirmar/:correo',usuariosControlers.confirmarCuenta);
router.get('/iniciar-sesion', usuariosControlers.formIniciarSesion);
router.post('/iniciar-sesion',authController.autenticarUsuario);
//cerrar sesion
router.get('/cerrar-sesion',usuariosControlers.cerrarSesion);
// Restablecer contraseña
router.get('/reestablecr',usuariosControlers.formRestablecerPassword);
router.post('/reestablecer',authControlers.enviarToken);
router.get('/reestablecer/:token',authControlers.validarToken);
router.post('/reestablecer/:token',authControlers.actualizarPassword);
return router;
}
|
const correctAnswer = ['C', 'B', 'B', 'B', 'A', 'B', 'A', 'A', 'A', 'B'];
const form = document.querySelector('.quiz-form');
const result = document.querySelector('.result')
form.addEventListener('submit', e => {
e.preventDefault();
let score = 0;
const userAnswers = [form.q1.value,
form.q2.value,
form.q3.value,
form.q4.value,
form.q5.value,
form.q6.value,
form.q7.value,
form.q8.value,
form.q9.value,
form.q10.value
];
// check answers
userAnswers.forEach((answer, index) => {
if (answer === correctAnswer[index]) {
score += 10;
}
});
//console.log(score)
//show result on page
//scrollTo() position on page
// animate quiz results using setInterval()
scrollTo(0, 0);
result.classList.remove('d-none');
let output = 0;
const timer = setInterval(() => {
result.querySelector('span').textContent = `${output}%`;
if (output === score) {
clearInterval(timer);
} else {
output++;
}
}, 15);
});
// const form =
// `<div class="my-5">
// <p class="lead font-weight-normal">${question.value}2. What is 275 divided by 25?</p>
// <div class="form-check my-2 text-white-50">
// <input type="radio" name="q2" value="A" checked>
// <label class="form-check-label">13</label>
// </div>
// <div class="form-check my-2 text-white-50">
// <input type="radio" name="q2" value="B">
// <label class="form-check-label">11</label>
// </div>
// </div>`
|
import {createSelector} from 'reselect';
const selectDirectory = (state)=>state.directory;
export const selectDirectorySelections = createSelector(
[selectDirectory],
directory=>directory.sections
)
|
import { loadProfile, getSkater, loadFinishedAdventure, loadAdventureLink, hasFinishedTasks } from '../common/utils.js';
import adventures from '../data/adventures-data.js';
loadProfile();
const skater = getSkater();
if (hasFinishedTasks(adventures, skater)) {
window.location = '../results';
}
const navigateAdventures = document.getElementById('adventures');
for (let i = 0; i < adventures.length; i++) {
const adventure = adventures[i];
let adventureDisplay = null;
if (skater.completed[adventure.id]) {
adventureDisplay = loadFinishedAdventure(adventure);
} else {
adventureDisplay = loadAdventureLink(adventure);
}
navigateAdventures.appendChild(adventureDisplay);
}
|
var express = require('express');
var router = express.Router();
var googleMapsClient = require('@google/maps');
var json2csv = require('json2csv');
// /* GET distance matrix */
// router.get('/', function(req, res, next) {
// currentClient = googleMapsClient.createClient({
// key: 'YOUR-KEY'
// });
// var originsList = ['1600 Amphitheatre Parkway, Mountain View, CA', '100 Main St, San Franciso, CA'];
// var destinationsList = ['10 Amphitheatre Parkway, Mountain View, CA', '200 Spring St, San Francisco, CA'];
// var travelMode = 'driving';
// var units = 'metric';
// var language = 'pt-BR';
// // Geocode an address.
// currentClient.distanceMatrix({
// origins: originsList,
// destinations: destinationsList,
// mode: travelMode,
// units: units,
// language: language
// }, function(err, response) {
// if (!err) {
// console.log(response.json);
// var data = response.json.rows;
// var csv = '';
// var fields = ['distance.text', 'distance.value', 'duration.text', 'duration.value', 'status', 'userOrigin', 'userDestination', 'googleOrigin', 'googleDestination', 'rowId'];
// csv += fields.join(',') + '\n';
// for (var i = 0; i < data.length; i++) {
// for (var j = 0; j < data[i].elements.length; j++) {
// var element = data[i].elements[j];
// element.userOrigin = originsList[i];
// element.userDestination = destinationsList[j];
// element.googleOrigin = response.json.origin_addresses[i];
// element.googleDestination = response.json.destination_addresses[j];
// element.rowId = i.toString() + j.toString();
// try {
// var result = json2csv({
// data: element,
// fields: fields,
// hasCSVColumnTitle: false
// });
// csv += result + '\n';
// } catch (err) {
// // Errors are thrown for bad options, or if the data is empty and no fields are provided.
// // Be sure to provide fields if it is possible that your data array will be empty.
// console.error(err);
// }
// }
// }
// console.log(csv);
// res.send(csv);
//
// }
// });
// });
router.post('/', function(request, clientResponse){
console.log(request.body); // your JSON
var requestJson = request.body;
currentClient = googleMapsClient.createClient({
key: requestJson.apiKey
});
var originsList = requestJson.originAddressList;
var originsIdList = requestJson.originIdList;
var destinationsList = requestJson.destAddressList;
var destinationsIdList = requestJson.destIdList;
var travelMode = requestJson.travelMode;
var units = requestJson.units;
var language = requestJson.language;
// Geocode an address.
currentClient.distanceMatrix({
origins: originsList,
destinations: destinationsList,
mode: travelMode,
units: units,
language: language
}, function(err, response) {
if (!err) {
console.log(response.json);
var data = response.json.rows;
var csv = '';
var fields = ['distance.text', 'distance.value', 'duration.text', 'duration.value', 'status', 'userOrigin', 'userDestination', 'googleOrigin', 'googleDestination', 'rowId', 'originId', 'destId'];
csv += fields.join(',') + '\n';
for (var i = 0; i < data.length; i++) {
for (var j = 0; j < data[i].elements.length; j++) {
var element = data[i].elements[j];
element.userOrigin = originsList[i];
element.userDestination = destinationsList[j];
element.googleOrigin = response.json.origin_addresses[i];
element.googleDestination = response.json.destination_addresses[j];
element.originId = originsIdList[i];
element.destId = destinationsIdList[j];
element.rowId = i.toString() + j.toString();
try {
var result = json2csv({
data: element,
fields: fields,
hasCSVColumnTitle: false
});
csv += result + '\n';
} catch (err) {
// Errors are thrown for bad options, or if the data is empty and no fields are provided.
// Be sure to provide fields if it is possible that your data array will be empty.
console.error(err);
}
}
}
console.log(csv);
var finalResponse = {
result: csv,
status: 200
};
clientResponse.end(JSON.stringify(finalResponse));
}
});
});
module.exports = router;
|
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var morgan = require('morgan');
var mongoose = require('mongoose');
var request = require('request');
const uuidV1 = require('uuid/v1');
var hostId = uuidV1();
var msgCount = 1;
var cookieParser = require('cookie-parser');
var https = require('https');
var jwt = require('jsonwebtoken');
var dbConfig = require('./src/myMongo');
var User = require('./src/User');
//var ChatState = require('./src/ChatState');
var GossipFacade = require('./src/GossipFacade');
var MyRestGw = require('./src/RestGateway');
var MyDao = require('./src/Dao');
var urls = {"peer0":"http://104.236.235.18:4444"};
var peers = ["peer0"];
var dao = new MyDao();
var restGw = new MyRestGw();
var port = 6666;
var gossipF = new GossipFacade(peers,urls,dao,restGw,"http://104.236.235.18:"+ port);//:=var chatState = {"rumors":[]};
mongoose.connect(dbConfig.database);
var config = require('./config');
app.use(bodyParser.json());
app.use(cookieParser());
app.set('superSecret', dbConfig.secret);
app.use(morgan('dev'));
app.get('/setup', function(req, res) {
// create a sample user
var mike = new User({
name: 'Mike',
password: '',
admin: true ,
checkins: []
});
// save the sample user
mike.save(function(err) {
if (err) throw err;
console.log('User saved successfully');
res.json({ success: true });
});
});
app.get('/api/fsredirect', function(req,res){
debugger;
var url = require('url');
var url_parts = url.parse(req.url, true);
var query = url_parts.query;
var code = query.code;
var cli_id = "1BM5TKMPHSUMBNAQHQ2NQPWQXJ1CJU2LCEVAKEYWGJ2NHZOS";
var cli_sec = "NXTH2TXJRY3Y3MBTAOWJNQ12ITTV5RHKADHNKYVV0V2CZFHG";
var fsUrl = "/oauth2/access_token?client_id="+ cli_id +"&client_secret="+cli_sec +"&grant_type=authorization_code&redirect_uri=http://104.236.235.18:3333/api/fsredirect&code="+code;
// debugger;
var options = {
host: 'foursquare.com',
port: 8080,
path: fsUrl,
method: 'GET'
};
request('https://foursquare.com' + fsUrl, function(error,fsres,body){
debugger;
console.log(body);
res.cookie('fs_at',JSON.parse(body).access_token, { maxAge: 900000, httpOnly: true});
res.redirect('/');
});
});
app.post('/authenticate', function (req, res) {
User.findOne({
name: req.body.username
}, function(err, user) {
if (err) throw err;
if (!user) {
res.json({ success: false, message: 'Authentication failed. User not found.' });
} else if (user) {
res.cookie('user',user.name,{ maxAge: 900000,httpOnly: true});
res.redirect('/index.html#/home');
}
});
});
app.get('/api/logout',function(req,res){
request.post("https://foursquare.com/logout",function(err,fres,body)
{
//Redirect
res.clearCookie('user');
res.clearCookie('fs_at');
res.redirect('/index.html#/home');
});
});
/**
* Create new user
*
*/
app.post('/api/user',function(req,res){
var user = req.body.username;
debugger;
var newbie= new User({
name: user,
password: '',
admin: true,
checkins:[]
});
// save the sample user
newbie.save(function(err) {
if (err) throw err;
res.cookie('user',newbie.name,{ maxAge: 900000,httpOnly: true});
res.clearCookie('fs_at');
console.log('User saved successfully');
res.redirect('/index.html#/home');
});
});
app.get('/api/currentUser',function(req,res){
var username = req.cookies.user;
User.findOne({
name: username
}, function(err, user) {
if (err) res.json({ success: false, "name": 'notLoggedIn.' });
if (!user) {
res.json({ success: false, "name": 'notLoggedIn.' });
} else if (user) {
res.json({"details": user, "name": username, 'cookies':req.cookies});
}
});
});
var updateList = function(req,cb){
var accessToken = req.cookies.fs_at;
var user = req.cookies.user;
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10) {
dd='0'+dd
}
if(mm<10) {
mm='0'+mm
}
today = yyyy+'' +mm+'' +dd;
debugger;
if (typeof accessToken != 'undefined' && typeof user != 'undefined')
{
request('https://api.foursquare.com/v2/checkins/recent?oauth_token='+ accessToken + "&v="+ today,function(err,fsres,body){
//Store most recent in database
User.findOne({
name: user
}, function(err, user) {
debugger;
if (err) throw err;
if (!user) {
}
else
{
user.checkins = body;
user.save(function(err){
cb();
});
}
});
});
}
}
app.get('/api/user', function(req,res){
updateList(req,function(){
User.find({}, function(err, users) {
res.send(users);
});
});
});
app.get( "/api/chatstate", function(req,res){
//Return State of Chat
res.json(gossipF.state);
// chatStat
});
app.post( "/api/consumeRumor",function(req,res)
{
debugger;
gossipF.checkRegistry(req.headers.host);
gossipF.handleRumor(req.body);
res.status(200).json({"Status":"Success"});
});
app.post( "/api/sendChat", function(req,res){
//Return State of Chat
var msg = req.body.msgId;
var name = req.body.name;
gossipF.addMessage({"MessageId":hostId +":"+msgCount++,"Originator":name,"Text":msg});
res.status(200).json({Status:true});
});
setInterval(function(){
gossipF.sendRumor(function(err){
if (err)
{
console.log(err);
}
});
},gossipF.updateInterval);
app.use(express.static('public'));
app.listen(port);
console.log("App Started on port "+ port);
|
(function () {
'use strict';
// register the route config on the application
angular
.module('printwfApp.wenyinshi', [
'ui.router',
'printwfApp.mainMenu'
])
.config(configWenyinshiRoute);
// inject configAdminRoute dependencies
configWenyinshiRoute.$inject = ['$stateProvider', 'mainMenuProvider'];
// route config function configuring the passed $stateProvider
function configWenyinshiRoute($stateProvider, mainMenuProvider) {
var wenyinshiState = {
name: 'wenyinshi',
url: '/wenyinshi',
authenticate: true,
templateUrl: 'app/wenyinshi/wenyinshi.html',
controller: 'WenyinshiMainController',
controllerAs: 'vm'
};
$stateProvider.state(wenyinshiState);
mainMenuProvider.addMenuItem({
name: '主页',
state: wenyinshiState.name,
order: 1,
role: 'wenyinshi'
});
}
})();
|
import { StaticQuery, graphql } from "gatsby";
import React from "react";
const TitleNosvaleur = () => (
<StaticQuery
query={graphql`
query {
wordpressAcfPages(wordpress_id: { eq: 18 }) {
acf {
video_valeurs {
source_url
}
title_valeurs
content_valeurs
}
}
}
`}
render={data => (
<section className="se-valeurs">
<div className="container ">
<div className="row justify-content-center">
<div className="col-sm-12 p0 col-lg-10">
<div className="se-card se_header no-bg se-v">
<h2 className="se_title">
{data.wordpressAcfPages.acf.title_valeurs}
</h2>
<div className="se-video">
<video autoPlay muted>
<source
src={
data.wordpressAcfPages.acf.video_valeurs.source_url
}
type="video/mp4"
/>
Your browser does not support HTML5 video.
</video>
</div>
<div
className="se_excerpt"
dangerouslySetInnerHTML={{
__html: data.wordpressAcfPages.acf.content_valeurs
}}
/>
</div>
</div>
</div>
</div>
</section>
)}
/>
);
export default TitleNosvaleur;
|
app.factory("SupplierReceiptService",
['$http', '$log', function ($http, $log) {
return {
findOne: function (id) {
return $http.get("/api/supplierReceipt/findOne/" + id).then(function (response) {
return response.data;
});
},
findBySupplier: function (supplierId) {
return $http.get("/api/supplierReceipt/findBySupplier/" + supplierId).then(function (response) {
return response.data;
});
},
createIn: function (supplierReceipt) {
return $http.post("/api/supplierReceipt/createIn", supplierReceipt).then(function (response) {
return response.data;
});
},
createOut: function (supplierReceipt) {
return $http.post("/api/supplierReceipt/createOut", supplierReceipt).then(function (response) {
return response.data;
});
},
remove: function (id) {
return $http.delete("/api/supplierReceipt/delete/" + id);
},
filter: function (search) {
return $http.get("/api/supplierReceipt/filter?" + search).then(function (response) {
return response.data;
});
},
findByTodayIn: function () {
return $http.get("/api/supplierReceipt/findByToday/In").then(function (response) {
return response.data;
});
},
findByWeekIn: function () {
return $http.get("/api/supplierReceipt/findByWeek/In").then(function (response) {
return response.data;
});
},
findByMonthIn: function () {
return $http.get("/api/supplierReceipt/findByMonth/In").then(function (response) {
return response.data;
});
},
findByYearIn: function () {
return $http.get("/api/supplierReceipt/findByYear/In").then(function (response) {
return response.data;
});
},
findByTodayOut: function () {
return $http.get("/api/supplierReceipt/findByToday/Out").then(function (response) {
return response.data;
});
},
findByWeekOut: function () {
return $http.get("/api/supplierReceipt/findByWeek/Out").then(function (response) {
return response.data;
});
},
findByMonthOut: function () {
return $http.get("/api/supplierReceipt/findByMonth/Out").then(function (response) {
return response.data;
});
},
findByYearOut: function () {
return $http.get("/api/supplierReceipt/findByYear/Out").then(function (response) {
return response.data;
});
}
};
}]);
|
//registration
const regForm = document.querySelector('#reg-form');
if(regForm){
regForm.addEventListener('submit', (e) => {
e.preventDefault();
//get user info
const email = regForm['email'].value;
const password = regForm['password'].value;
firebase.auth().createUserWithEmailAndPassword(email, password).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
window.alert("Error:" + errorMessage);
});
userCred();
})
}
// logout
const logout = document.querySelector('#logout');
if(logout) {
logout.addEventListener('click', (e) => {
e.preventDefault();
firebase.auth().signOut().then(()=> {
window.location = "login.html";
});
} )
}
//login
const loginForm = document.querySelector('#login-form');
if(loginForm) {
loginForm.addEventListener('submit', (e) => {
e.preventDefault();
//get user info
const email = loginForm['email'].value;
const password = loginForm['password'].value;
firebase.auth().signInWithEmailAndPassword(email, password).then(cred =>{
loginForm.reset();
firebase.auth().signInWithEmailAndPassword(email, password).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
window.alert("Error:" + errorMessage);
});
})
userCred();
});
}
//get user email when user is loged in
function userCred() {
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
var email = user.email;
window.location = "categories.html?email=" + email;
}
});
}
|
//build 配置文件
module.exports = {
root: "../",
noStore: true,
concat: {
title: "文件合并",
dir: "src",
list: [
{
src: ["Q.UI.Box.js", "Q.UI.ContextMenu.js", "Q.UI.DropdownList.js", "Q.UI.DataPager.js", "Q.UI.Tabs.js", "Q.UI.Marquee.js", "Q.UI.ColorPicker.js", "Q.UI.Progressbar.js", "Q.UI.RangeSlider.js"],
dest: "/Q.UI.js"
},
{
src: ["/lib/Q.mini.js", "adapter/jquery.js", "/Q.UI.js"],
dest: "/jquery.QUI.js"
}
],
replace: [
//移除\r字符
[/\r/g, ""],
//移除VS引用
[/\/\/\/\s*<reference path="[^"]*" \/>\n/gi, ""]
]
},
cmd: [
{
title: "压缩js",
//cmd: "java -jar D:\\tools\\compiler.jar --js=%f.fullname% --js_output_file=%f.dest%",
cmd: "uglifyjs %f.fullname% -o %f.dest% -c -m",
output: "dist",
match: ["lib/*.js", "*.js", "src/**.js"],
replace: [
//去掉文件头部压缩工具可能保留的注释
[/^\/\*([^~]|~)*?\*\//, ""]
],
//可针对单一的文件配置 before、after,def 表示默认
before: [
{
"def": "//devin87@qq.com\n",
"Q.js": "//Q.js devin87@qq.com\n//mojoQuery&mojoFx scott.cgi\n",
"Q.mini.js": "//Q.mini.js devin87@qq.com\n",
"jquery-1.11.3.js": "/*! jQuery v1.11.3 | (c) jQuery Foundation | jquery.org/license */\n",
"jquery-1.12.0.js": "/*! jQuery v1.12.0 | (c) jQuery Foundation | jquery.org/license */\n"
},
{
"def": "//build:%NOW%\n",
"jquery-1.11.3.js": "",
"jquery-1.12.0.js": ""
}
]
}
],
copy: {
title: "同步demo到jquery-demo",
dir: "demo",
match: ["**"],
output: "/jquery-demo"
},
format: {
title: "修改jquery-demo html 为jquery引用",
dir: "jquery-demo",
match: ["*.html"],
autoSkip: false,
replace: [
['<script type="text/javascript" src="../lib/Q.js"></script>',
'<script type="text/javascript" src="../lib/jquery-1.12.0.js"></script>\n ' +
'<script type="text/javascript" src="../lib/Q.mini.js"></script>\n ' +
'<script type="text/javascript" src="../src/adapter/jquery.js"></script>']
]
},
run: ["concat", "cmd", "copy", "format"]
};
|
'use strict';
angular.module('Exponencial', ["chart.js"])
.controller('ExponencialController',
function ($scope, $confirm, $uibModal, Notification) {
//Configuraciones generales de la libreria para graficar
$scope.colors = ['#E54125', '#059BFF', '#4BC0C0', '#FFCE56', '#E7E9ED'];
$scope.dataSeries = ['Numeros Aleatorios'];
$scope.onClick = function(points, evt) {
};
$scope.datasetOverride = [{
yAxisID: 'y-axis-1'
}];
$scope.options1 = {
scales: {
yAxes: [{
id: 'y-axis-1',
type: 'linear',
display: true,
position: 'left',
ticks: {
beginAtZero: true
}
}]
}
};
$scope.disabledButton = false;
//Metodo que calcula los numeros aleatorios segun una cantidad deseada
$scope.randomExponencial = function(lamda,cantidad, intervalos){
if(lamda<=0) {
Notification.error({message: 'Lamda debe ser mayor a cero', delay: 3000, replaceMessage: true});
return;
}
$scope.series = new Array()
$scope.labels = new Array();
$scope.data = new Array();
$scope.randoms = new Array();
var zetas = new Array();
var max = -Number.MAX_VALUE,
min = Number.MAX_VALUE;
//FOR para crear numeros aleatorios con la formula EXPONENCIAL
for (var i = 0; i < cantidad; i++) {
var aux1 = Math.random();
var random = (-(1/lamda)*Math.log(1-aux1));
zetas.push(random);
//Necesito el max y min de los numeros generados, para poder definir el paso de los intervalos
if (max < random) {
max = random;
}
if (min > random) {
min = random;
}
//RANDOMS es un arreglo con los numeros que se listan, por performance se limita a 5000
if($scope.randoms.length < 5000) {
$scope.randoms.push(random.toFixed(2));
}
}
//Esta forma de calcular max y min, no va mas.
// var max = Math.max(...zetas);
// var min = Math.min(...zetas);
$scope.paso = (max-min)/intervalos;
//El arreglo LABELS guarda el valor maximo LIMITE de cada intervalo
//El arreglo DATA sera un acumulador con la cantidad de numeros aleatorios presentados por intervalo
for (var i = 1; i <= intervalos; i++) {
min = min + $scope.paso;
$scope.labels.push(min);
$scope.data.push(0);
}
// FOR del arreglo con los numeros aleatorios generados
for (var i = 0; i <= zetas.length; i++) {
var labels = $scope.labels;
var random = zetas[i];
//FOR del arreglo con los limites maximos de cada intervalo, y pregunto si el numero z[i] pertenece
//al intervalo, en caso positivo lo acumulo.
for(var j = 0; j < labels.length; j++){
if(random <= labels[j]){
$scope.data[j]++;
break;
}
}
}
//El arreglo series tiene el valor medio del intervalo, para presentarlo en la grafica
for (var i = 0; i < $scope.labels.length; i++) {
$scope.series.push(($scope.labels[i]-($scope.paso/2)).toFixed(2));
}
if($scope.data.length > 0){
$scope.disabledButton = true;
}
};
//Metodo para agregar de a un solo numero aleatorio
$scope.random1 = function(lamda){
var aux1 = Math.random();
var random = (-(1/lamda)*Math.log(1-aux1));
if($scope.randoms.length < 5000) {
$scope.randoms.push(random.toFixed(2));
}
for(var j = 0; j < $scope.labels.length; j++){
if(random <= $scope.labels[j]){
$scope.data[j]++;
break;
}
}
};
//Metodo prueba chi cuadrado
$scope.pruebaChi = function(alfa, lamda,cantidad, intervalos){
if(alfa<0 || alfa >1) {
Notification.error({message: 'Alfa debe estar entre 0 y 1', delay: 3000, replaceMessage: true});
return;
}
$scope.frecuenciaEsperada = new Array();
$scope.suma = 0;
$scope.sumaFrecuenciaEsperada = 0;
$scope.arrayChi = new Array();
//Procedo a calcular la frecuencia esperada para cada intervalo
for(var i = 0; i < $scope.labels.length; i++){
//jStat es una libreria de JS que provee funciones para calcular distribuciones
var aux1 = jStat.exponential.cdf($scope.labels[i], lamda);
var aux2 = jStat.exponential.cdf($scope.labels[i]-$scope.paso, lamda);
var aux3 = (aux1-aux2)*cantidad;
$scope.frecuenciaEsperada.push(aux3);
$scope.sumaFrecuenciaEsperada = $scope.sumaFrecuenciaEsperada+aux3;
}
//[(FE-FO)^2] / FE
for(var i = 0; i < $scope.data.length; i++){
var aux = (Math.pow($scope.data[i]-$scope.frecuenciaEsperada[i], 2))/$scope.frecuenciaEsperada[i];
$scope.arrayChi.push(aux);
$scope.suma = $scope.suma+aux;
}
//Grados de Libertad
$scope.gdl = intervalos - 2 - 1;
//Calculo chi cuadrado, 1-alfa -> Nivel de confianza
//El nivel de confianza es la probabilidad de que el parámetro a estimar se encuentre
//en el intervalo de confianza. El nivel de confianza (p) se designa mediante 1 − α,
//y se suele tomar en tanto por ciento.
//Los niveles de confianza más usuales son: 90%; 95% y 99%. El nivel de significación se designa mediante α.
$scope.chi = jStat.chisquare.inv(1-alfa,$scope.gdl);
if($scope.suma<$scope.chi){
$scope.verifica = 'VERDADERO'
}
else {
$scope.verifica = "FALSO"
}
};
});
|
import { isDefined } from '../../core/utils/type';
import { extend } from '../../core/utils/extend';
function round(value) {
return Math.round(value * 1000) / 1000; // checked with browser zoom - 500%
}
function getTextLines(doc, text, font, _ref) {
var {
wordWrapEnabled,
columnWidth
} = _ref;
if (wordWrapEnabled) {
// it also splits text by '\n' automatically
return doc.splitTextToSize(text, columnWidth, {
fontSize: (font === null || font === void 0 ? void 0 : font.size) || doc.getFontSize()
});
}
return text.split('\n');
}
function calculateTextHeight(doc, text, font, _ref2) {
var {
wordWrapEnabled,
columnWidth
} = _ref2;
var height = doc.getTextDimensions(text, {
fontSize: (font === null || font === void 0 ? void 0 : font.size) || doc.getFontSize()
}).h;
var linesCount = getTextLines(doc, text, font, {
wordWrapEnabled,
columnWidth
}).length;
return height * linesCount * doc.getLineHeightFactor();
}
function calculateRowHeight(doc, cells, columnWidths) {
if (cells.length !== columnWidths.length) {
throw 'the cells count must be equal to the count of the columns';
}
var rowHeight = 0;
for (var cellIndex = 0; cellIndex < cells.length; cellIndex++) {
var cellText = cells[cellIndex].text;
var font = cells[cellIndex].font;
var wordWrapEnabled = cells[cellIndex].wordWrapEnabled;
var columnWidth = columnWidths[cellIndex];
if (isDefined(cellText)) {
var cellHeight = calculateTextHeight(doc, cellText, font, {
wordWrapEnabled,
columnWidth
});
if (rowHeight < cellHeight) {
rowHeight = cellHeight;
}
}
}
return rowHeight;
}
function drawLine(doc, startX, startY, endX, endY) {
doc.line(round(startX), round(startY), round(endX), round(endY));
}
function drawRect(doc, x, y, width, height, style) {
if (isDefined(style)) {
doc.rect(round(x), round(y), round(width), round(height), style);
} else {
doc.rect(round(x), round(y), round(width), round(height));
}
}
function drawTextInRect(doc, text, rect, wordWrapEnabled, jsPdfTextOptions) {
var textArray = getTextLines(doc, text, doc.getFont(), {
wordWrapEnabled,
columnWidth: rect.w
});
var linesCount = textArray.length;
var heightOfOneLine = calculateTextHeight(doc, textArray[0], doc.getFont(), {
wordWrapEnabled: false
}); // TODO: check lineHeightFactor - https://github.com/MrRio/jsPDF/issues/3234
var y = rect.y + rect.h / 2 - heightOfOneLine * (linesCount - 1) / 2; // align by vertical 'middle', https://github.com/MrRio/jsPDF/issues/1573
var textOptions = extend({
baseline: 'middle'
}, jsPdfTextOptions);
doc.text(textArray.join('\n'), round(rect.x), round(y), textOptions);
}
export { calculateRowHeight, drawLine, drawRect, drawTextInRect };
|
/* $Rev: 2692 $
* $HeadURL: http://source/svn/innectus/trunk/loom/App/build/js/jsheaderdev.txt
$
* $Id: innectus-dojo.profile.js 2692 2011-05-24 00:09:43Z volkmuth $
*
* Copyright (C) 2011 Innectus Corporation
* All rights reserved
* This code is proprietary property of Innectus Corporation.
* Unauthorized use, distribution or reproduction is prohibited.
*/
/*
* Profile for dojo custom build. Instructions:
* Download source release of dojo (e.g. dojo-release-1.6.0-src)
* cd dojo-release-1.6.0-src/util
* cp /path/to/this/file profiles/innectus-dojo.profile.js
* ./build.sh profile=innectus-profile action=clean,release cssOptimize=comments
* The resulting build will be in ../release/dojo. You will still have to manually
* clean up the release/dojo directory to remove extraneous js and css files, the
* dojo build tool is not smart about including only relevant files.
*/
dependencies = ({
prefixes:[
["dijit", "../dijit"],
["dojox", "../dojox"],
["innectus", "../innectus"]
],
layers:[
{
dependencies:[
"dijit.form.RadioButton",
"dojo.data.ItemFileWriteStore",
"dojox.grid.EnhancedGrid",
"dijit.form.Button",
"dijit.form.Textarea",
"dojox.grid.enhanced.plugins.IndirectSelection"
],
name:"../innectus/dojo.js",
resourceName:"innectus.dojo"
}
]
})
|
const users = [];
const addUser = ({ id, userId }) => {
const user = { id, userId };
users.push(user);
return user;
};
const removeUser = (id) => {
const userIndex = users.findIndex((user) => user.id === id);
if (userIndex !== -1) {
return users.splice(userIndex, 1)[0];
}
};
const toString = (buffer) => {
return buffer.toString("base64");
};
module.exports = {
toString,
addUser,
removeUser,
};
|
import React, {Component} from 'react'
import axios from 'axios'
import IndividualCustomerProduct from './IndividualCustomerProduct'
class FindProducts extends Component {
constructor() {
super()
this.state = {
customerEmail: '',
products: [],
loading: true,
findProduct: '',
sortBy: ''
}
this.fetchAllProducts = this.fetchAllProducts.bind(this)
this.handleChange = this.handleChange.bind(this)
this.handleQuantityChange = this.handleQuantityChange.bind(this)
this.search = this.search.bind(this)
this.buyProduct = this.buyProduct.bind(this)
}
fetchAllProducts(req) {
this.setState({
loading: true
})
axios.post('http://localhost:4000/customer/fetchAllProducts', req)
.then(res => {
this.setState({
products: res.data.message,
loading: false,
sortBy: 'Sort By'
}, () => {
console.log(this.state)
});
})
.catch(err => {
console.log(err)
this.setState({
products: [],
loading: false,
sortBy: 'Sort By'
})
})
}
componentDidMount() {
const req = {
filter: "False",
name: ""
}
this.setState({
customerEmail: this.props.customerEmail,
findProduct: ''
},() => this.fetchAllProducts(req))
}
handleChange(event) {
const {name, value, type} = event.target;
this.setState({
[name]: value
}, () => {
console.log(this.state)
if(type == 'select-one') {
if(value === 'Sort By') {
return
}
if(value === 'Price') {
let products = this.state.products
products.sort(function(a, b) {return a.price - b.price})
this.setState({
products: products
})
return
}
if(value === 'Quantity Left') {
let products = this.state.products
products.sort(function(a, b) {return a.available - b.available})
this.setState({
products: products
})
return
}
if(value === 'Rating') {
let products = this.state.products
console.log(products)
products.sort(function(a, b) {return a.vendorRating - b.vendorRating})
this.setState({
products: products
})
return
}
}
})
}
handleQuantityChange(event, id) {
console.log(id)
const {value} = event.target
this.setState({
[id]: value
}, () => {
console.log(this.state)
})
}
buyProduct(event, id, available) {
event.preventDefault()
const required = this.state[id]
const customerEmail = this.state.customerEmail
if(required == undefined) {
alert('You need to select a positive quantity of the product')
return
}
else if(required > available) {
alert('This much quantity is not available')
return
}
const req = {
id: id,
required: required,
customerEmail: customerEmail
}
axios.post('http://localhost:4000/customer/buyProduct', req)
.then(res => {
console.log(res)
this.fetchAllProducts({filter: 'False', name: ''})
})
}
search() {
const {findProduct} = this.state
const req = {
filter: "True",
name: findProduct
}
this.fetchAllProducts(req)
}
render() {
const allProducts = this.state.products.map(product => <IndividualCustomerProduct key = {product._id} item = {product} handleQuantityChange = {this.handleQuantityChange} buyProduct = {this.buyProduct}/>)
return (
<div>
{this.state.loading === true ?
<p>Loading ...</p>:
<div>
<br/>
<div className="input-group">
<input
type="text"
className="form-control"
style={{width: '200px'}}
placeholder='Search for products'
name='findProduct'
onChange = {this.handleChange}
/>
<br/>
<span className="input-group-btn">
<button
className="btn btn-default"
type="button"
onClick = {() => this.search()}
>
FIND
</button>
<button
className="btn btn-default"
type="button"
onClick = {() => this.fetchAllProducts({filter: "False", name: ""})}
>
ALL PRODUCTS
</button>
<select name = 'sortBy' value = {this.state.sortBy} className="custom-select mr-sm-2" id="inlineFormCustomSelect" style = {{width: '200px'}} onChange = {this.handleChange}>
<option selected value = 'Sort By'>Sort By</option>
<option value="Price">Price</option>
<option value="Quantity Left">Quantity Left</option>
<option value="Rating">Rating</option>
</select>
</span>
</div>
<div className = 'container-fluid fill' style = {{marginTop: '60px'}}>
<div className ="flex-container">
{allProducts}
</div>
</div>
</div>
}
</div>
)
}
}
export default FindProducts
|
let canvas = document.getElementById("only_canv"); // creating canvas
let ctx = canvas.getContext("2d");
let box = 30;
drawCanvasSize = function () {
let userWidth = document.querySelector("#widthInput").value;
let userHeight = document.querySelector("#heightInput").value;
canvas.width = userWidth || 900;
canvas.height = userHeight || 450;
}
let maxX = canvas.width / box; // calculation for apple's random coordinates;
let maxY = canvas.height / box;
let apple = {
img: document.getElementById("apple")
};
apple.x = Math.floor(Math.random() * maxX + 0) * box;
apple.y =Math.floor(Math.random() * maxY + 0) * box;
let score = 0;
let highScore = localStorage.setItem("highScore",0);
if (score > localStorage.getItem("highScore")) {
localStorage.setItem("highScore", score);
}
// let appleNum = parseInt(document.querySelectorById("apple_count").value);
// part of the whole snake;
let snake = [
{
x: canvas.width / 2,
y: 5 * box
},
{
x: canvas.width / 2 + box ,
y: 5 * box
},
{
x: canvas.width / 2 + (2 * box),
y: 5 * box
}
];
// let snakeLengthByUser = Number(document.querySelector("#snake_size").value);
// for (i = 3; i < snakeLengthByUser; i++){
// snake.push({
// x: canvas.width / 2 + (i * box),
// y: 5 * box
// })
let dir = "left"; // keydown events and linking them with snake's directions;
document.onkeydown = function (e) {
if (e.keyCode == 37 && dir != "right") {
dir = "left";
}
else if (e.keyCode == 38 && dir != "down") {
dir = "up";
}
else if (e.keyCode == 39 && dir != "left") {
dir = "right";
}
else if (e.keyCode == 40 && dir != "up") {
dir = "down";
}
}
let speedInputByUser = document.querySelector("#speed_input").value;
let gameInterval;
let game = function () {
if (document.querySelector("#novice").checked){
gameInterval = setInterval(draw, 900);
}
else if(document.querySelector("#intermediate").checked){
gameInterval = setInterval(draw, 600);
}
else if(document.querySelector("#hard").checked){
gameInterval = setInterval(draw, 300);
}
}
let snakeX = snake[0].x; // snake old head x coordinate
let snakeY = snake[0].y; // y coordinate
newHead = {
x: snakeX,
y: snakeY
};
collision = function (newHead, snake){
for(let i = 1; i < snake.length; i++){
if (newHead.x == snake[i].x && newHead.y == snake[i].y){
return true;
}
else {
return false;
}
}
}
function draw(drawCanvasSize) {
ctx.clearRect(0, 0, canvas.width, canvas.height); // we need to clear canvas and draw it again in every single moment to get dynamic picture
ctx.drawImage(apple.img, apple.x, apple.y, 30, 30);
ctx.fillStyle = "white"; // showing score on canvas
ctx.font = "30px Arial";
ctx.fillText(score, box, box);
for (i = 0; i < snake.length; i++) {
let grd = ctx.createLinearGradient(0, 0, 170, 0); // creating snake
grd.addColorStop(0, "purple");
grd.addColorStop(1, "gold");
ctx.fillStyle = grd;
ctx.fillRect(snake[i].x, snake[i].y, box, box);
}
if (dir == "left") snakeX -= box; // to make snake move
if (dir == "up") snakeY -= box;
if (dir == "right") snakeX += box;
if (dir == "down") snakeY += box;
if (snakeX == apple.x && snakeY == apple.y) {
score = score + 10;
apple = {
img: document.getElementById("apple")
};
apple.x = Math.floor(Math.random() * maxX + 0) * box;
apple.y =Math.floor(Math.random() * maxY + 0) * box;
newHead = {
x: snakeX,
y: snakeY
}
snake.unshift(newHead);
}
else {
newHead = {
x: snakeX,
y: snakeY
}
snake.unshift(newHead);
snake.pop();
}
if (snakeX < 0 || snakeX > canvas.width || snakeY < 0 || snakeY > canvas.height || collision(newHead, snake)){
clearInterval(gameInterval);
ctx.fillStyle = "red";
ctx.font = "25px Arial";
ctx.fillText(`Your score is ${score}!! `, canvas.width / 3, canvas.height / 2);
}
}
|
require('dotenv').config()
let express = require('express');
let cors = require('cors');
let bodyParser = require('body-parser');
let cookieParser = require('cookie-parser');
require('./server/database/db-conn');
// ****Initialize app**********
const app = express();
app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(cors()); // OK if you don't care about cookies
const personRoute = require('./server/routes/score.route')
app.use('/score', personRoute)
// test API
app.get('/test', (req, res) => {
res.json({test: 2});
})
app.post('/info', (req, res) => {
console.log("info called!")
console.log(req.body.fname + " " + req.body.age);
})
app.get('/*', (req, res) => {
res.sendFile('index.html', {root: '.'});
})
// PORT
const port = process.env.PORT || 4000;
const server = app.listen(port, () => {
console.log('Connected to port ' + port)
})
// 404 Error
app.use((req, res, next) => {
next(createError(404));
});
app.use(function (err, req, res, next) {
console.error(err.message);
if (!err.statusCode) err.statusCode = 500;
res.status(err.statusCode).send(err.message);
});
|
(function() {
var isMoment = function (m) {
return jasmine.isA_('Object', m) && jasmine.isA_('Date', m._d);
};
var format = function(o) {
return isMoment(o) ? o.format() : o;
};
jasmine.getEnv().addEqualityTester(function(aMoment, anotherMoment) {
if (isMoment(aMoment) && isMoment(anotherMoment)) {
return (aMoment.unix() === anotherMoment.unix());
}
});
jasmine.getEnv().beforeEach(function() {
this.addMatchers({
toBeMoment: function(expected) {
var actual = this.actual;
var notText = this.isNot ? " not" : "";
this.message = function () {
return "Expected " + format(actual) + notText + " to be moment " + format(expected);
};
return isMoment(actual) && isMoment(expected) && actual.unix() === expected.unix();
}
});
});
jasmine.setupMoment = function (date, anObject) {
spyOn(anObject, "moment");
anObject.moment.plan = function () {
var realMoment = anObject.moment.originalValue;
// set "now" to a fixed date to enable static expectations
if (!arguments.length) {
return realMoment(date);
}
return realMoment.apply(null, arguments);
};
};
})();
|
var files_dup =
[
[ "alu.h", "alu_8h.html", "alu_8h" ],
[ "functionHandles.h", "functionHandles_8h.html", "functionHandles_8h" ],
[ "functions.h", "functions_8h.html", "functions_8h" ],
[ "jacobi.h", "jacobi_8h.html", "jacobi_8h" ],
[ "ludecomp.h", "ludecomp_8h.html", "ludecomp_8h" ],
[ "main.c", "main_8c.html", "main_8c" ],
[ "prol.h", "prol_8h.html", "prol_8h" ],
[ "restr.h", "restr_8h.html", "restr_8h" ],
[ "sor.h", "sor_8h.html", "sor_8h" ],
[ "stencils.h", "stencils_8h.html", "stencils_8h" ],
[ "v_cycle.h", "v__cycle_8h.html", "v__cycle_8h" ],
[ "w_cycle.h", "w__cycle_8h.html", "w__cycle_8h" ]
];
|
var anOpen = [];
var sImageUrl = "http://qa.kleer.la/wp-content/uploads/2011/03/";
//sImageUrl = "./DataTables-1.9.1/media/images/";
var oTable;
$(document).ready(function() {
oTable = $('#cursos').dataTable( {
"bLengthChange": false,
"sAjaxSource": '/entrenamos/eventos/pais/todos',
"aoColumns": [
{ "sWidth": "5%" },
{ "sWidth": "75%" },
{ "sClass": "right", "sWidth": "20%" }
],
"aaSorting": [],
"bSort": false,
"bPaginate": false,
"oLanguage": {
"sZeroRecords": "<div class=\"alert alert-warning\">Cargando...</div>",
"sInfo": "<div class=\"alert alert-info\">Mostrando desde _START_ hasta _END_ de _TOTAL_ registros</div>",
"sInfoEmpty": "",
"sInfoFiltered": "<div class=\"alert alert-info\">(filtrado de _MAX_ registros en total)</div>",
"sInfoPostFix": "",
"sSearch": "Buscar:",
"sUrl": ""
},
"fnInitComplete": function(oSettings, json) {
oSettings.oLanguage.sZeroRecords = "<div class=\"alert alert-warning\">No tenemos cursos que cumplan con ese criterio pero nos gustaría que nos contactes a <a href=\"mailto:hola@kleer.la\">hola@kleer.la</a> con tu inquietud.</div>";
}
});
// Cuelgo los handlers de los clicks
$("ul#country-filter > li > a").on("click", function(event) {
event.preventDefault();
var newSource = $(this).attr("href");
oTable.fnReloadAjax(newSource);
var containerUl = $(this).parent().parent();
containerUl.children("li").removeClass("active");
var clickedLi = $(this).parent();
clickedLi.addClass("active");
});
});
$.fn.dataTableExt.oApi.fnReloadAjax = function ( oSettings, sNewSource, fnCallback, bStandingRedraw )
{
if ( typeof sNewSource != 'undefined' && sNewSource != null ) {
oSettings.sAjaxSource = sNewSource;
}
// Server-side processing should just call fnDraw
if ( oSettings.oFeatures.bServerSide ) {
this.fnDraw();
return;
}
this.oApi._fnProcessingDisplay( oSettings, true );
var that = this;
var iStart = oSettings._iDisplayStart;
var aData = [];
this.oApi._fnServerParams( oSettings, aData );
oSettings.fnServerData.call( oSettings.oInstance, oSettings.sAjaxSource, aData, function(json) {
/* Clear the old information from the table */
that.oApi._fnClearTable( oSettings );
/* Got the data - add it to the table */
var aData = (oSettings.sAjaxDataProp !== "") ?
that.oApi._fnGetObjectDataFn( oSettings.sAjaxDataProp )( json ) : json;
for ( var i=0 ; i<aData.length ; i++ )
{
that.oApi._fnAddData( oSettings, aData[i] );
}
oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
if ( typeof bStandingRedraw != 'undefined' && bStandingRedraw === true ) {
oSettings._iDisplayStart = iStart;
that.fnDraw( false );
}
else {
that.fnDraw();
}
that.oApi._fnProcessingDisplay( oSettings, false );
/* Callback user function - for event handlers etc */
if ( typeof fnCallback == 'function' && fnCallback != null ) {
fnCallback( oSettings );
}
}, oSettings );
};
|
(function(window) {
"use strict";
var App = window.App || {};
var $ = window.jQuery;
function FormHandler(selector) {
if (!selector) {
throw new Error("No selector provided");
}
this.$formElement = $(selector);
if (this.$formElement.length === 0) {
throw new Error("Could not find element with selector: " + selector);
}
}
FormHandler.prototype.addSubmitHandler = function(fn) {
/*eslint-disable no-console*/
console.log("Setting submit handler for form");
this.$formElement.on("submit", function(event) {
event.preventDefault();
var data = {};
$(this).serializeArray().forEach(function(item) {
data[item.name] = item.value;
console.log(item.name + " is " + item.value);
});
console.log(data);
fn(data);
this.reset();
this.elements[0].focus();
var modal = document.getElementById("myModal");
var btn = document.getElementById("myBtn");
var span = document.getElementsByClassName("close")[0];
btn.onclick = function() {
modal.style.display = "block";
};
span.onclick = function() {
modal.style.display = "none";
};
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
};
});
};
FormHandler.prototype.addInputHandler = function(fn) {
console.log("Setting input handler for form");
this.$formElement.on("input", "[name='emailAddress']", function(event) {
var emailAddress = event.target.value;
var message = "";
if (fn(emailAddress)) {
event.target.setCustomValidity("");
} else {
message = emailAddress + " is not an authorized emai address!";
event.target.setCustomValidity(message);
}
});
};
App.FormHandler = FormHandler;
window.App = App;
})(window);
|
// @flow
import {
Platform,
NativeModules,
} from 'react-native';
import TONNativeUtilityWebAssembly from './TONNativeUtilityWebAssembly';
import type { TONNativeUtility } from './TONNativeUtility';
export default function TONNativeUtilityReactNative(): Promise<TONNativeUtility> {
return Platform.OS === 'web'
? TONNativeUtilityWebAssembly()
: Promise.resolve(NativeModules.TONUtility);
}
|
'use strict';
var Menu = {
tableName: 'mds_menus',
attributes: {
mds_id: { type: 'string' },
name: { type: 'string' },
meals: { type: 'array' },
availability: { type: 'json' },
/*type: { type: String },
from_date: Date,
to_date: Date,
on_days: [String],*/
order_index: { type: 'integer' }, // todo
featured_meal: { type: 'string' },
is_active: { type: 'boolean' },
created_at: { type: 'datetime' },
last_modified: { type: 'datetime' }
}
};
module.exports = Menu;
|
const mysql=require("mysql");
const connection=mysql.createConnection({
host:"localhost", //默认链接的是本地
user:"root", //用户名
password:"123456789", //密码
database:"smsm" //链接的是哪个数据库
})
connection.connect(()=>{
console.log("数据库链接成功");
})
// 因为别人要用connection ,所以我要将它暴露出去哦
module.exports=connection;
|
import {BigNumber} from 'bignumber.js';
import moment from 'moment';
export default {
searchOfAds(ads, _this) {
var Payroll = _this.Payroll;
var web3 = _this.web3;
var PayrollInstance;
Payroll.deployed().then((instance) => {
PayrollInstance = instance;
var employeeInfo = PayrollInstance.employees.call(ads);
return employeeInfo;
}).then((result) => {
_this.loading = false;
_this.disabled = false;
let employeeAds = result[0];
// 判段地址是否是 0x0000000000000000000000000000000000000000
if (parseInt(employeeAds.slice(2), 10) === 0) {
_this.result = 0;
return;
}
// salary
let salary = web3.fromWei(new BigNumber(result[1]).toNumber());
// lastPayDay
let lastPayDay = moment(new Date(new BigNumber(result[2]).toNumber()) * 1000).format('LLLL');
let employeeInfo = {
employeeAds: {
name: '员工地址',
value: employeeAds
},
salary: {
name: '员工月薪',
value: salary
},
lastPayDay: {
name: '上次领取薪水时间',
value: lastPayDay
}
};
_this.result = employeeInfo;
});
}
};
|
import React from 'react';
const NotFound = ({statusHandler}) => {
return (
<div >
<h1>Page not found</h1>
<p>Login or go homepage</p>
<button onClick={() => statusHandler('goHomepage')}>Go homepage</button>
</div>
);
};
export default NotFound;
|
const JSONParcer = string => {
try {
return JSON.parse(string)
}
catch (err) {
return err
}
}
const obj = {
prop: 'val'
}
|
import React, { Component } from 'react';
import { css } from 'emotion';
import { lighten } from 'polished';
import { auth } from 'firebase';
import { Link, NavLink, withRouter } from 'react-router-dom';
import { connect } from 'react-redux';
import { flavours, factors } from '../constants/styleTokens';
import { mapStateToProps, mapActionCreators } from '../redux/store';
const headerStyles = {
wrapper: css(`
display: flex;
flex-direction: row;
padding: 0 4em;
margin-bottom: 2em;
height: 4.3em;
background-color: ${lighten(0.99, flavours.black)};
div {
display: flex;
}
`),
brand: css(`
width: 15em;
box-sizing: border-box;
padding: 1.5em 0.4em;
`),
breadCrumb: css(`
width: 15em;
padding: 1.5em 0.4em;
`),
navigation: css(`
flex:1;
justify-content: flex-end;
ul {
list-style: none;
margin: 0;
display: flex;
flex-direction: row;
li {
display: flex;
a {
padding: 1.5em 1em;
cursor: pointer;
margin-left: 0.1em;
box-sizing: content-box;
text-decoration: none;
color: ${flavours.black};
&:visited {
color: ${flavours.black};
}
&:focus {
outline: 2px solid ${flavours.outline};
}
&:hover, &.active {
color: ${flavours.default};
}
&.active {
background: ${lighten(factors.lightenNav, flavours.default)};
border-bottom: 0.1em solid ${flavours.default};
}
}
}
}
`),
profile: css(`
width: 10em;
justify-content: space-around;
a {
padding: 1.5em 1em;
}
`),
logout: css(`
justify-content: flex-end;
a {
padding: 1.5em 1em;
}
`)
}
class Header extends Component {
logout = async () => {
try {
await auth().signOut();
this.props.logoutUser();
this.props.history.push('/login');
} catch (e) {
console.warn('err' + e);
}
}
render() {
return (
<div className={headerStyles.wrapper}>
<div className={headerStyles.brand}>
<span>
Rotaract District Quiz
</span>
</div>
<div className={headerStyles.navigation}>
<ul>
<li>
<NavLink to={'/home/leaderboard'} activeClassName={'active'}>LeaderBoard</NavLink>
</li>
<li>
<NavLink to={'/home/quiz'} activeClassName={'active'}>Quiz</NavLink>
</li>
<li>
<NavLink to={'/home/guidelines'} activeClassName={'active'}>Guidelines</NavLink>
</li>
</ul>
</div>
<div className={headerStyles.profile}>
<a>
</a>
</div>
<div className={headerStyles.logout}>
<a onClick={this.logout}>
Logout
</a>
</div>
</div>
);
}
};
export const HeaderWidget = connect(mapStateToProps, mapActionCreators)(withRouter(Header));
|
import React, { useState, useCallback, useEffect } from 'react';
import { useSelector } from 'react-redux';
import styled from '@emotion/styled';
import { message } from 'antd';
const FieldsContainer = styled.div`
width: 100%;
height: 50%;
& .field-title {
display: flex;
width: 100%;
height: 35px;
border-top: 1px solid #c4c4c4;
border-bottom: 1px solid #c4c4c4;
padding-top: 0.3rem;
& div {
width: 50%;
height: 100%;
text-align: center;
}
}
.field-main {
width: 100%;
height: 100%;
display: flex;
& .field-middle-category {
width: 50%;
height: 100%;
display: flex;
flex-direction: column;
list-style: none;
padding-left: 1rem;
& li {
width: 90%;
height: 14%;
line-height: 45px;
text-align: center;
}
}
& .field-subclass {
width: 50%;
height: 100%;
display: flex;
flex-direction: column;
list-style: none;
padding-left: 1rem;
& li {
width: 90%;
height: 14%;
line-height: 45px;
text-align: center;
}
}
}
`;
const Fields = ({ tempFields, setTempFields }) => {
const { categories } = useSelector((state) => state.category);
const [middleCategory, setMiddleCategory] = useState('');
const [showingSubclass, setShowingSubclass] = useState(false);
const clickMiddleCategory = useCallback(
(categoryName) => () => {
setMiddleCategory(categoryName);
setShowingSubclass(true);
},
[]
);
const clickSubclass = useCallback(
(subclass) => () => {
if (tempFields.length === 3) {
return message.error('최대 3개만 입력 됩니다.');
}
const { id, name } = subclass;
const field = { id, name, middleCategory };
const hasSameField = tempFields.some((field) => field.id === id);
if (hasSameField) return;
const newfields = [...tempFields, field];
setTempFields(newfields);
},
[middleCategory, tempFields]
);
return (
<FieldsContainer>
<div className='field-title'>
<div>대분류</div>
<div>소분류</div>
</div>
<div className='field-main'>
<ul className='field-middle-category'>
{Object.keys(categories).map((categoryName) => (
<li key={categoryName} onClick={clickMiddleCategory(categoryName)}>
{categoryName}
</li>
))}
</ul>
{showingSubclass && (
<ul className='field-subclass'>
{categories[middleCategory].map((subclass) => (
<li key={subclass.name} onClick={clickSubclass(subclass)}>
{subclass.name}
</li>
))}
</ul>
)}
</div>
</FieldsContainer>
);
};
export default Fields;
|
let request = require("request-promise");
const fs = require('fs')
const cookieJar = request.jar();
request = request.defaults({jar: cookieJar, strictSSL: false});
// const root_url = 'https://www.infosubvenciones.es/bdnstrans/GE/es/index'
const root_url = 'https://www.infosubvenciones.es/bdnstrans/GE/es/index'
async function initializeHeaders() {
const result = await request.get(root_url);
// const result = await request.get({ url: root_url, strictSSL: false});
const cookieString = cookieJar.getCookieString(root_url)
// console.log(cookieString)
const splittedByScrfCookieName = cookieString.split("JSESSIONID=")
const JSESSIONID = splittedByScrfCookieName[1].split(";")[0];
// console.log(JSESSIONID)
var headers = {
'Cookie': `JSESSIONID=${JSESSIONID};`
};
return headers
}
async function scrapeRoot(headers, page) {
let data_url
if (page == null) {
data_url = `https://www.infosubvenciones.es/bdnstrans/busqueda?type=topconv&_search=false&nd=1601915599703&rows=50&page=1&sidx=4&sord=desc`
} else {
data_url = `https://www.infosubvenciones.es/bdnstrans/busqueda?type=topconv&_search=false&nd=1601915599703&rows=50&page=${page}&sidx=4&sord=desc`
}
const data_result = await request.get({headers: headers, url: data_url})
return data_result
}
async function main() {
const headers = await initializeHeaders();
console.log(headers);
const data_result = await scrapeRoot(headers)
console.log(data_result)
/*
const loginResult = await request.post("https://internshala.com/login/verify_ajax/user", {
form: {
csrf_test_name,
email: "brennan.vir@intrees.org",
password: "kwrqt6W$",
}
});
console.log("\n\n========:4::::::::::==========::::::::::\n\n");
const matches = await request.get(
"https://internshala.com/internships/matching-preferences"
);
fs.writeFileSync("./matches.html", matches);
console.log(loginResult);
*/
}
module.exports = {
main,
scrapeRoot,
initializeHeaders,
}
|
//= require jquery
//= require rails-ujs
//= require activestorage
//= require turbolinks
//= require select2
//= require semantic-ui/dropdown
//= require jquery-mask-plugin
$.jMaskGlobals.watchDataMask = true;
$.ajaxSetup({
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).on('turbolinks:load', function() {
$('.select').select2({language: "ru"});
$('.dropdown').dropdown();
$('#standard_calendar').calendar({ ampm: false });
$('#standard_calendar_1').calendar({ ampm: false });
});
|
export default function merge_sort_animations(arr){
let animations=[]
merge(arr,arr.slice(),animations,0,arr.length-1)
return animations
}
function merge(arr,auxArr,animations,startIndx,endIndx){
if (endIndx!==startIndx){
let midIndx=Math.floor((startIndx+endIndx)/2)
merge(auxArr,arr,animations,startIndx,midIndx)
merge(auxArr,arr,animations,midIndx+1,endIndx)
let i=startIndx,j=midIndx+1,k=startIndx
while(i<=midIndx && j<=endIndx){
animations.push([i,j])
if (auxArr[i]>auxArr[j]){
arr[k]=auxArr[i]
animations.push([k,auxArr[i]])
animations.push([i,j])
i++
}
else {
arr[k]=auxArr[j]
animations.push([k,auxArr[j]])
animations.push([i,j])
j++
}
k++
}
while (i<=midIndx){
arr[k]=auxArr[i]
animations.push([i,i])
animations.push([k,auxArr[i]])
animations.push([i,i])
i++
k++
}
while (j<=endIndx){
arr[k]=auxArr[j]
animations.push([j,j])
animations.push([j,auxArr[j]])
animations.push([j,j])
j++
k++
}
}
}
|
;
(function ($, window, undefined) {
$(function () {
$(".bulkActionForm").submit(function (e) {
/*check if atleast 1 item is checked*/
var selectedItems = $(".itemId:checked");
if (selectedItems.length == 0) {
alert('Please select at least one item');
e.preventDefault();
return false;
}
processBulkAction($(".bulkAction option:selected"), selectedItems, e);
/*console.log($(".bulkAction option:selected").attr('data-action'));
console.log($(".bulkAction option:selected").data('action'));*/
/*e.preventDefault();*/
});
});
function processBulkAction($action, $selectedItems, event) {
if ($action.data('itemsContainer')) {
console.log($action.data('itemsContainer'));
inflateIdsTo($($action.data('itemsContainer')), $selectedItems);
}
if ($action.data('action')) {
console.log($action.data('action'));
$($action.data('action')).modal();
event.preventDefault();
}
}
function inflateIdsTo($container, $ids){
$container.empty();
$ids.each(function(){
$container.append('<input type="hidden" name="id[]" value="'+$(this).val()+'">');
});
}
})(jQuery, window);
|
define(function (){
var rootPath = "http://m.dev.weintrade.com/";
var imgUrl = "http://img.dev.weintrade.com";
//附件
var generalUrl = rootPath + "api/general/file/";
var config = {
upload:{
uploadUrl:generalUrl + 'upload',
downloadUrl:imgUrl
},
index: {
api:{
ipinfo: rootPath + "api/international/ipinfo"
}
},
request: {
api:{
sourcingRequest: rootPath + "api/international/sourcingRequest/"
}
},
link : {
home: rootPath,
sourcingRequest : rootPath + "request/sourcing-request.html"
},
statusCode : {
SUCCESS : 2000000,
NOTPHONE : 2000309,//登录手机号码不存在
NOTPASSWORD : 2000310, //登录密码不正确
LOGININVALID : 2000312, //登录用户名或密码错误
FROEENACOUNT : 2000205, //当前用户已被冻结
SESSIONEXPIRE : 1000100,//session 失效
NOLOGIN : 2001000,//未登录
INVALIDPRODUCT : 2000800 //失效产品
}
};
return config;
});
|
// NightDate; custom field that asks for a date (year, month, day).
class NightDate extends React.Component {
constructor(props) {
super(props);
this.state = this.props.formData;
this.state[this.props.name] = this.state[this.props.name]
? this.state[this.props.name]
: moment().format('YYYY-MM-DD');
this.onChange = this.onChange.bind(this);
this.renderDateType = this.renderDateType.bind(this);
}
onChange(name) {
return event => {
this.setState(
{
[name]: event.target.value
},
() => this.props.onChange(this.state)
);
};
}
renderDateType() {
if (this.props.schema.showDateType) {
return (
<div className="form-check">
{this.props.schema.properties.dateType.options.map(item =>
<label key={'label' + item} className="row mt-1 ml-1 form-check-label">
<input
key={'input' + item}
name="dateType"
type="radio"
className="form-check-input"
value={item}
onChange={this.onChange('dateType')}
checked={this.state.dateType == item}
/>
<span className="ml-1" key={'span' + item}>
{item}
</span>
</label>
)}
</div>
);
}
}
render() {
return (
<fieldset className="pt-1 pb-2" id={this.props.name + 'field'}>
<legend>
{this.props.schema.required && <i className="fas fa-asterisk night-required-icon pb-1 mr-1" />}
{this.props.schema.title}
</legend>
<div className="form-group row">
<div className="col-5">
<input
className="form-control"
type="date"
value={this.state[this.props.name]}
onChange={this.onChange(this.props.name)}
id={this.props.name + 'input'}
/>
</div>
</div>
{this.renderDateType()}
</fieldset>
);
}
}
|
define(['angular'],function (angular) {
angular.module('AboutFactory', []).factory('AboutFactory', aboutFactory);
function aboutFactory() {
var committees = [{
name: "Allen Linatoc",
image: "public/images/members/allen.jpg",
links: [
],
quote: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris eget leo nunc, nec tempus mi? Curabitur id nisl mi, ut vulputate urna. Quisque porta facilisis tortor, vitae bibendum velit fringilla vitae! Lorem ipsum dolor sit amet, consectetur adipiscing elit. "
},
{
name: "Allan Suaco",
image: "public/images/bm.jpg",
links: [
],
quote: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris eget leo nunc, nec tempus mi? Curabitur id nisl mi, ut vulputate urna. Quisque porta facilisis tortor, vitae bibendum velit fringilla vitae! Lorem ipsum dolor sit amet, consectetur adipiscing elit. "
},
{
name: "Dexter Qua",
image: "public/images/members/dexter.jpg",
links: [
],
quote: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris eget leo nunc, nec tempus mi? Curabitur id nisl mi, ut vulputate urna. Quisque porta facilisis tortor, vitae bibendum velit fringilla vitae! Lorem ipsum dolor sit amet, consectetur adipiscing elit. "
},
{
name: "Jemlon Sagarino",
image: "public/images/members/jemlon.jpg",
links: [
],
quote: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris eget leo nunc, nec tempus mi? Curabitur id nisl mi, ut vulputate urna. Quisque porta facilisis tortor, vitae bibendum velit fringilla vitae! Lorem ipsum dolor sit amet, consectetur adipiscing elit. "
},
{
name: "Majesty Amazona",
image: "public/images/members/majesty.jpg",
links: [
],
quote: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris eget leo nunc, nec tempus mi? Curabitur id nisl mi, ut vulputate urna. Quisque porta facilisis tortor, vitae bibendum velit fringilla vitae! Lorem ipsum dolor sit amet, consectetur adipiscing elit. "
},
{
name: "Zee",
image: "public/images/members/zee.jpg",
links: [
],
quote: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris eget leo nunc, nec tempus mi? Curabitur id nisl mi, ut vulputate urna. Quisque porta facilisis tortor, vitae bibendum velit fringilla vitae! Lorem ipsum dolor sit amet, consectetur adipiscing elit. "
},
{
name: "Jason Crisostomo",
image: "public/images/members/jaeson.jpg",
links: [
],
quote: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris eget leo nunc, nec tempus mi? Curabitur id nisl mi, ut vulputate urna. Quisque porta facilisis tortor, vitae bibendum velit fringilla vitae! Lorem ipsum dolor sit amet, consectetur adipiscing elit. "
},
];
var devTeamMembers = [{
name: "Marc Remmel Abiva",
image: "public/images/members/renmel.jpg",
links: [
],
quote: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris eget leo nunc, nec tempus mi? Curabitur id nisl mi, ut vulputate urna. Quisque porta facilisis tortor, vitae bibendum velit fringilla vitae! Lorem ipsum dolor sit amet, consectetur adipiscing elit. "
},
{
name: "Raffy Apurillo",
image: "public/images/members/raffy.jpg",
links: [
],
quote: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris eget leo nunc, nec tempus mi? Curabitur id nisl mi, ut vulputate urna. Quisque porta facilisis tortor, vitae bibendum velit fringilla vitae! Lorem ipsum dolor sit amet, consectetur adipiscing elit. "
},
{
name: "Ruther Bergunia",
image: "public/images/members/ruther.jpg",
links: [
],
quote: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris eget leo nunc, nec tempus mi? Curabitur id nisl mi, ut vulputate urna. Quisque porta facilisis tortor, vitae bibendum velit fringilla vitae! Lorem ipsum dolor sit amet, consectetur adipiscing elit. "
},
{
name: "Kenneth Bolico",
image: "public/images/members/kenneth.jpg",
links: [
],
quote: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris eget leo nunc, nec tempus mi? Curabitur id nisl mi, ut vulputate urna. Quisque porta facilisis tortor, vitae bibendum velit fringilla vitae! Lorem ipsum dolor sit amet, consectetur adipiscing elit. "
},
{
name: "Billious Braga Boquila",
image: "public/images/members/billious.jpg",
links: [
],
quote: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris eget leo nunc, nec tempus mi? Curabitur id nisl mi, ut vulputate urna. Quisque porta facilisis tortor, vitae bibendum velit fringilla vitae! Lorem ipsum dolor sit amet, consectetur adipiscing elit. "
},
{
name: "Analyn Cui Cajocson",
image: "public/images/members/analyn.jpg",
links: [
],
quote: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris eget leo nunc, nec tempus mi? Curabitur id nisl mi, ut vulputate urna. Quisque porta facilisis tortor, vitae bibendum velit fringilla vitae! Lorem ipsum dolor sit amet, consectetur adipiscing elit. "
},
{
name: "Ian Concepcion",
image: "public/images/members/ian.jpg",
links: [
],
quote: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris eget leo nunc, nec tempus mi? Curabitur id nisl mi, ut vulputate urna. Quisque porta facilisis tortor, vitae bibendum velit fringilla vitae! Lorem ipsum dolor sit amet, consectetur adipiscing elit. "
},
{
name: "Regine Grace In",
image: "public/images/members/regine.jpg",
links: [
],
quote: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris eget leo nunc, nec tempus mi? Curabitur id nisl mi, ut vulputate urna. Quisque porta facilisis tortor, vitae bibendum velit fringilla vitae! Lorem ipsum dolor sit amet, consectetur adipiscing elit. "
},
{
name: "Melquidez Lazaro",
image: "public/images/members/melquidez.jpg",
links: [
],
quote: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris eget leo nunc, nec tempus mi? Curabitur id nisl mi, ut vulputate urna. Quisque porta facilisis tortor, vitae bibendum velit fringilla vitae! Lorem ipsum dolor sit amet, consectetur adipiscing elit. "
},
{
name: "Mon Cedric Reyes",
image: "public/images/members/mon.jpg",
links: [
],
quote: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris eget leo nunc, nec tempus mi? Curabitur id nisl mi, ut vulputate urna. Quisque porta facilisis tortor, vitae bibendum velit fringilla vitae! Lorem ipsum dolor sit amet, consectetur adipiscing elit. "
}
];
return {
getCommittees: function () {
return committees;
},
getDevTeamMembers: function () {
return devTeamMembers;
}
}
}
});
|
import React, { Component } from 'react';
import GamesListMake from './GamesListMake';
import axios from 'axios';
import './App.css';
import GameList from './GameList';
import EntityDisplay from './EntityDisplay.js';
class ComboViewer extends Component {
constructor(props) {
super(props);
this.state = {
games: [],
}
}
getAll = () => {
axios.get('/getAllGames').then(r => { this.setState({ games: r.data }) });
}
render() {
let games = this.state.games.map(g => <EntityDisplay gameName={g.gameName} gameID={g.gameID} />)
return (
<div className="body">
<div className="container">
<br />
<div className="row">
<div className="col-12">
<label>
<h1>COMBO VIEWER</h1>
</label>
<div>
{games}
</div>
</div>
</div>
<br />
<button onClick={this.getAll}>get all games</button>
</div>
</div>
);
}
}
export default ComboViewer;
|
import React from 'react';
export default class SubredditSearch extends React.Component{
constructor(props) {
super(props);
this.state = {
subreddit: '',
numResults: 0,
loading:null,
};
}
handleChange(e) {
this.setState({
[e.target.name]: e.target.value,
});
}
handleSubmit(e) {
e.preventDefault();
this.props.handleSearch(this.state);
}
render() {
return (
<React.Fragment>
<form onSubmit={this.props.handleSearch}>
<input
name="subreddit"
placeholder="Subreddit Name..."
value={this.state.subreddit}
onChange={e => this.handleChange(e)}/>
<input
name="numResults"
type="number"
min="1"
max="99"
value={this.state.numResults}
onChange={e => this.handleChange(e)}/>
<button onClick={e => this.handleSubmit(e)}>Search</button>
</form>
</React.Fragment>
);
}
}
|
jQuery(function() {
var root_element = '#container ';
function changeNav(e){
e.preventDefault();
jQuery(root_element + ".navItem.active").removeClass("active");
jQuery(this).addClass('active');
}
function changeAdvItem(e){
e.preventDefault();
jQuery(root_element + "#viewport div.advItem").removeClass("active");
var activeDivId = jQuery(this).data("item");
activeDivId = "#" + activeDivId;
jQuery(root_element + activeDivId).addClass('active');
}
function changeAdvThumb(e){
e.preventDefault();
var imgSrc = jQuery(this).attr("src");
jQuery(root_element + "#viewport div.advItem.active .mainImage img").attr('src',imgSrc);
}
jQuery(root_element + ".navItem").on('click', changeNav);
jQuery(root_element + ".navItem").on('click', changeAdvItem);
jQuery(root_element + "#viewport .thumb").on('click', changeAdvThumb);
jQuery("#nav li").first().click();
});
|
require('./Controller.scss');
const React = require('react');
const $ = require('jquery');
const { ajax } = $;
const AVAILABLE_PROFILES = [
{
id: 'react',
name: 'React Component',
default: true,
},
{
id: 'react-router',
name: 'React Route Handler'
}
];
const { string } = React.PropTypes;
const MirageController = React.createClass({
propTypes: {
activeModule: string,
paramsFile: string,
subjectPath: string,
},
getInitialState() {
return {
visible: !this.props.subject && !this.props.subjectPath,
fileList: null,
fileListFilter: this.props.subjectPath || '',
selectedModule: this.props.subjectPath || null,
selectedProfile: null,
paramSource: this.props.paramsFile ? 'file' : 'inline',
};
},
componentDidMount() {
this.loadAvailableFiles();
document.addEventListener('keydown', this.toggle, false);
},
componentWillReceiveProps(nextProps) {
if (nextProps.paramsFile) {
this.setState({ paramSource: 'file' });
}
},
componentDidUpdate() {
if (this.state.fileListFilter.length === 0 && this.state.selectedModule) {
this.setState({ selectedModule: null });
}
$('#application').toggleClass('mirage-application--hidden', this.isVisible());
},
componentWillUnmount() {
document.removeEventListener('keydown', this.toggle, false);
},
render() {
if (!this.isVisible()) {
return null;
}
return (
<form className="mirage-controller" onSubmit={this.activateModule}>
<h3>Runner Configuration</h3>
<fieldset>
<label>Search for a module:
{' '}
<input
type="text"
onChange={this.filterModuleList}
value={this.state.fileListFilter}
autoFocus
/>
</label>
{this.state.fileListFilter.length > 0 && this.state.fileList && (
<div>
<h4>Module List</h4>
<select size={10} onChange={this.trackCandidateModule}>
{getMatchingFiles(this.state.fileList, this.state.fileListFilter, 30).map(this.renderFile)}
</select>
</div>
)}
</fieldset>
<fieldset>
<label>Profile:{' '}
<select onChange={this.trackProfile} value={this.state.selectedProfile}>
{AVAILABLE_PROFILES.map(this.renderProfileOption)}
</select>
</label>
</fieldset>
<fieldset>
<div>
Parameters:
{' '}
<label>
<input
type="radio"
name="paramSource"
value="file"
checked={this.state.paramSource === 'file'}
onChange={this.trackParamSource}
/> From file
</label>
{' '}
<label>
<input
type="radio"
name="paramSource"
value="inline"
checked={this.state.paramSource === 'inline'}
onChange={this.trackParamSource}
/> Inline
</label>
</div>
{this.state.paramSource === 'inline' && (
<textarea ref="params" placeholder="JSON parameters go here" />
)}
{this.state.paramSource === 'file' && (
<input
ref="params"
type="text"
placeholder="path/to/js/file.js"
defaultValue={this.props.paramsFile}
/>
)}
</fieldset>
<div className="mirage-controller__actions">
<button type="submit" onClick={this.activateModule} disabled={!this.canActivateModule()}>
Activate Module
</button>
<button onClick={this.loadAvailableFiles}>
{this.state.fileList === null ?
"Load Available Modules" :
"Reload Available Modules"
}
</button>
</div>
</form>
);
},
renderFile(filePath) {
return (
<option key={filePath} value={filePath}>{filePath}</option>
);
},
renderProfileOption(profile) {
return (
<option key={profile.id} value={profile.id} default={profile.default}>{profile.name}</option>
);
},
toggle(e) {
if (!e.defaultPrevented && (e.keyCode || e.which) === 112) {
e.preventDefault();
this.setState({ visible: !this.state.visible });
}
},
isVisible() {
return (!this.props.subject && !this.props.subjectPath) || this.state.visible === true;
},
filterModuleList(e) {
this.setState({ fileListFilter: e.target.value });
},
trackCandidateModule(e) {
this.setState({ selectedModule: e.target.value });
},
trackProfile(e) {
this.setState({ selectedProfile: e.target.value });
},
trackParamSource(e) {
this.setState({ paramSource: e.target.value });
},
canActivateModule() {
const { selectedModule } = this.state;
return (
selectedModule &&
selectedModule.length > 0
);
},
activateModule(e) {
e.preventDefault();
if (!this.canActivateModule()) {
return;
}
ajax({
url: '/mirage/activate',
type: 'POST',
data: JSON.stringify({
filePath: this.state.selectedModule,
profile: this.state.selectedProfile || AVAILABLE_PROFILES.filter(x => x.default)[0].id,
params: this.state.paramSource === 'inline' ? this.refs.params.value : undefined,
paramsFile: this.state.paramSource === 'file' ? this.refs.params.value : undefined,
})
}).then(() => {
if (this.isMounted() && this.isVisible()) {
this.setState({ visible: false });
}
});
},
loadAvailableFiles() {
ajax({
url: '/mirage/ls',
type: 'GET'
}).then(fileList => {
this.setState({ fileList: fileList.sort() });
}, () => {
window.alert("Unable to load module listing!");
});
}
});
function getMatchingFiles(list, _filter, limit) {
const filter = _filter.toLowerCase();
return list.filter(x => x.toLowerCase().indexOf(filter) > -1).slice(0, limit);
}
module.exports = MirageController;
|
/* begin copyright text
*
* Copyright © 2016 PTC Inc., Its Subsidiary Companies, and /or its Partners. All Rights Reserved.
*
* end copyright text
*/
/*global module*/
/* jshint node: true */
/* jshint strict: global */
/* jshint camelcase: false */
'use strict';
var debug = require('debug')('arpublish:portalurl');
var vxshelper = require('./../vxs/vxshelper');
module.exports = function(req, res, next) {
debug('In get portalurl ...');
if (req.accepts('text/plain') && !req.accepts('html')) res.type('txt');
var appServer;
if (vxshelper.isMultiTenant(req)) {
// As of now the portal hostname is same as App hostname.
// If it changes in future then this method needs to be changed.
appServer = vxshelper.getAppServerUrl(req);
appServer = appServer.replace(/^https?:\/\//i, req.protocol + '://');
} else {
// On non multi-tenant setup assume that it is on same host as AR Publish Service
appServer = req.protocol + '://' + req.headers.host;
}
res.status(200).send(appServer + '/portal');
}
|
import React, { Component } from 'react';
import { getCommentById, updateCommentVote } from '../api';
import { Card, CardContent } from '@material-ui/core/';
import { formatDate } from '../utils'
import Vote from './Vote'
import { Link } from '@reach/router'
import AvatarDisplay from './AvatarDisplay'
import ErrorPage from './ErrorPage'
import { UserContext } from '../contexts/User'
class CommentCard extends Component {
state = {
comment: {},
hasError: false,
errorMessage: '',
isLoading: true
}
componentDidMount() {
getCommentById(this.props.comment_id).then(comment => {
this.setState({ comment, isLoading: false })
})
.catch(err => {
const { response: { status, data: { msg } }, } = err
this.setState({ hasError: true, errorMessage: `${status}! ${msg}` })
})
}
handleVote = (inc) => {
const { comment_id } = this.state.comment
this.setState((currState) => {
const { votes, ...restOfComment } = currState.comment
const newState = {
comment: { ...restOfComment, votes: votes + inc }
}
return newState
})
updateCommentVote(inc, comment_id)
.catch(err => {
const { response: { status, data: { msg } }, } = err
this.setState({ hasError: true, errorMessage: `${status}! ${msg}` })
})
}
handleDelete = () => {
const { comment_id } = this.state.comment
this.props.removeComment(comment_id)
}
render() {
const {
author,
body,
comment_id,
created_at,
votes
} = this.state.comment
if (this.state.hasError) {
return <ErrorPage errorMessage={this.state.errorMessage} />
}
else if (this.state.isLoading) {
return <p>loading ...</p>
}
else return (
<Card key={comment_id}>
<CardContent >
<div className='card-header'>
<div className="post-by">
<AvatarDisplay author={author} />
<p><Link to={`/users/${author}`} style={{ textDecoration: 'none' }} > {author}</Link> <br />{formatDate(created_at)}</p>
</div>
<Vote handleVote={this.handleVote} votes={votes} />
</div>
<p className="comment-body">{body}</p>
{(this.context.loggedInUser === author ? (
<button onClick={this.handleDelete} id="delete-comment-button">Delete Comment</button>
) : null)}
</CardContent>
</Card>
);
}
}
CommentCard.contextType = UserContext
export default CommentCard;
|
import React, { Component } from "react";
import TimePicker from "./presenter";
export default class Timer extends Component {
state = {
timeOver: false,
time: "POP"
};
static getDerivedStateFromProps(nextProps, prevState) {
if (nextProps.leftTime < prevState.time) {
const time =
100 + nextProps.leftTime - Math.floor(new Date().getTime() / 1000);
return { time };
}
return null;
}
componentDidMount() {
const timer = setInterval(() => {
const time =
100 + this.props.leftTime - Math.floor(new Date().getTime() / 1000);
this.setState({ time });
}, 1000);
this.setState({ timer });
}
componentWillUnmount() {
this._clearInterval();
}
_stopTimer = async () => {
try {
await this.props.socket.emit("timeOut");
await this.props.resetchat();
this.setState({ time: "" });
await this.props.explodeChatRoom();
} catch (err) {
console.log(err);
}
};
_clearInterval = () => {
clearInterval(this.state.timer);
};
render() {
return (
<TimePicker
time={this.state.time}
stopTimer={this._stopTimer}
clearInterval={this._clearInterval}
/>
);
}
}
|
#!/usr/bin/env node
var basedir = __dirname;
var dir = process.argv[2] ? process.argv[2] : ".";
process.title = 'Visual Studio Code Haxe Template Installer';
require(basedir + "/../index.js").install(dir);
|
var log4js = require('log4js');
var logger = log4js.getLogger();
var amqp = require('amqp');
var Broker = module.exports = exports = function(options){
this.name = "ReqBroker";
this.enableRedis = false;
this.started = false;
this.options = options;
this.waitingQueue = {};
this.init();
}
Broker.prototype.init = function(){
}
Broker.prototype.collect = function(routingKey, message, callback, res){
var routingKey = "req."+routingKey;
if(this.enableRedis){
this.redisClient.set(routingKey, JSON.stringify([callback, res]), this.redisClient.print);
}else{
this.waitingQueue[routingKey] = [callback, res];
}
this.exchange.publish(routingKey, message, {});
}
Broker.prototype.dispatch = function(message, headers, deliveryInfo){
var routingKey = deliveryInfo.routingKey;
routingKey = "req."+routingKey.substr(routingKey.indexOf(".")+1);
var call = null;
if(this.enableRedis){
this.redisClient.get(routingKey, function(err, data) {
call = JSON.parse(data);
if(call){
var callback = call[0];
console.log(typeof call[1]);
var res = call[1];
callback(res, message);
}
});
}else{
call = this.waitingQueue[routingKey];
if(call){
var callback = call[0];
var res = call[1];
callback(res, message);
}
}
}
Broker.prototype.start = function(){
var self = this;
var reqQueueName = 'requestQueue';
var resQueueName = 'responseQueue';
var exchangeName = 'default';
if(this.started){
return this;
}
self.started = true;
//Redis
var redis = require("redis");
this.redisClient = redis.createClient('6379','127.0.0.1');
this.redisClient.on("connect", function (err) {
console.log("redis connected!");
});
this.redisClient.on("error", function (err) {
console.log("Error " + err);
});
//RabbitMQ
self.connection = amqp.createConnection(self.options.server, self.options.amqp);
self.connection.on('ready', function () {
logger.info("Proxy connection to message server "+self.options.server.host+":"+self.options.server.port +' is ready!');
self.exchange = self.connection.exchange(exchangeName, {type:'topic'}, function (exchange) {
logger.info('Worker Exchange ' + exchange.name + ' is ready!');
//declare request queue
self.reqQueue = self.connection.queue(reqQueueName, function(reqQueue){
logger.info('Request Queue ' + reqQueue.name + ' is ready!');
reqQueue.bind(exchangeName, "req.*");
//declare response queue
self.resQueue = self.connection.queue(resQueueName, function(resQueue){
logger.info('Response Queue ' + resQueue.name + ' is ready!');
resQueue.bind(exchangeName, "res.*");
resQueue.subscribe(function (message, headers, deliveryInfo) {
//dispatch message
console.log("res:"+deliveryInfo.routingKey);
self.dispatch(message, headers, deliveryInfo);
});
});
});
});
});
return this;
}
|
const { verifyToken } = require('@utils/JWT');
const { update } = require('@services/user');
const publicURL = '//localhost:3000/';
module.exports = async (req, res) => {
const token = req.query.token;
try {
const { context: { userId } } = await verifyToken(token);
const user = await update({ _id: userId }, { status: 1 });
if(user) {
return res.redirect(`${publicURL}login?verification=success`);
}
return res.redirect(`${publicURL}login?verification=error`)
} catch(e) {
return res.redirect(`${publicURL}login?verification=error`)
}
}
|
const router = require("express").Router();
const User = require('../models/User');
const bcrypt=require('bcrypt');
const passport = require('passport');
const shelter='SHELTER'
const adopter='ADOPTER'
/* LOGIN USER*/
router.get("/loginUser", (req, res, next) => {
res.render("auth/loginUser");
});
router.post('/loginUser', (req, res, next) => {
passport.authenticate('local', (err, theUser, failureDetails) => {
if (err) {
// Something went wrong authenticating user
return next(err);
}
if (!theUser) {
// Unauthorized, `failureDetails` contains the error messages from our logic in "LocalStrategy" {message: '…'}.
res.render('auth/loginUser', { message: 'Ooops, wrong password or username' });
return;
}
// save user in session: req.user
req.login(theUser, err => {
if (err) {
// Session save went bad
return next(err);
}
// All good, we are now logged in and `req.user` is now set
res.redirect('/private');
});
})(req, res, next);
});
/* LOGOUT USER*/
router.get('/logout', (req, res)=>{
req.logout();
res.redirect('/')
})
/* SIGN UP USER*/
router.get("/signupUser", (req, res, next) => {
res.render("auth/signupUser");
});
router.post("/signupUser", (req, res)=>{
const {username, password, email, role} = req.body;
if(!username || !password || !email|| !role){
res.render('auth/signupUser', {message: 'All fields are mandatory'})
return
}
if(password.length<8){
res.render('auth/signupUser', {message: 'Your password must be longer than 8 characters'})
return
}
User.findOne({username: username}).then(userDB=>{
if(userDB !== null){
res.render('auth/signupUser', {message: 'This username is taken. Choose another!'})
}else{
const salt=bcrypt.genSaltSync(10);
const hash=bcrypt.hashSync(password, salt)
User.create({username: username, email: email, password: hash, role: role}).then(userDB=>{
// passport.authenticate('local', {
// successRedirect: '/private',
// failureRedirect: '/signupUser',
// session: true,
// });
req.login(userDB, err => {
if (err) {
// Session save went bad
return next(err);
}else{
if(req.user.role===shelter){
res.render('shelterViews/profileSubmit', {user: req.user})
}else{
res.redirect('/private')
}
}
// All good, we are now logged in and `req.user` is now set
// res.redirect('/private');
});
// console.log(userDB)
// res.redirect('/')
}).catch(err=>console.log('Oops!', err))
}
}).catch(err=>console.log('Something went wrong', err))
})
router.get('/logout', (req, res)=>{
req.logout();
res.redirect('/')
})
module.exports = router;
|
import React, { Component } from 'react';
import { StyleSheet, Text, View, Image, FlatList } from 'react-native';
export default class DanhSachMonAnComponent extends Component {
constructor(props) {
super(props);
}
render() {
return (
<>
<View key={this.props.item.Id} style={styles.container}>
<View style={styles.left}>
<Image
style={styles.avatarLogin}
source={{
uri: this.props.item.AnhMonAn,
}}
/>
</View>
<View style={styles.right}>
<View style={styles.rightTop}>
<Text style={{ fontSize: 18 }}>{this.props.item.TenMonAn}</Text>
<Text style={{ fontSize: 20, color: 'red' }}>
{' '}
{this.props.item.Calo}
</Text>
</View>
<View style={styles.rightBottom}>
<Text>{this.props.item.DonViTinh}</Text>
</View>
</View>
</View>
<View
style={{
height: 2,
backgroundColor: 'black',
}}
/>
</>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'row',
padding: 5,
},
avatarLogin: {
width: 80,
height: 80,
marginBottom: 3,
},
left: {
flex: 1,
},
right: {
flex: 3,
paddingLeft: 5,
},
rightTop: {
flex: 1,
flexDirection: 'row',
justifyContent: 'space-between',
marginTop: 15,
},
rightBottom: { flex: 1 },
flatListItem: {
color: 'black',
padding: 10,
fontSize: 16,
},
});
|
const Discord = require('discord.js');
exports.run = (client,message,args) => {
let embed = new Discord.RichEmbed();
embed.setTitle("Bot Source")
.setColor("#0366d6")
.setDescription("https://github.com/get-thepacket/discord-bot.git");
message.channel.send(embed);
}
exports.info = "Give source of the bot";
|
import React from 'react'
import { View } from 'react-native'
import { Text, useTheme } from '@ui-kitten/components'
import styled from 'styled-components'
const DataSourceCard = styled(View)`
display: flex;
justify-content: center;
align-items: center;
background: ${props => props.bg ? props.bg : 'blue'};
padding-top: 8px;
`
const DataSourceText = styled(Text)`
color: white;
font-size: 10px;
`
export default () => {
const theme = useTheme()
return (
<DataSourceCard bg={theme['color-primary-500']}>
<DataSourceText>Data provided by Pokéapi V2</DataSourceText>
</DataSourceCard>
)
}
|
angular.module('app')
.controller('UserEditController', function($stateParams, $location, $timeout, UserService, User) {
const vm = this;
const userId = $stateParams.userId;
if(userId)
vm.user = UserService.get(userId);
else
vm.user = new User();
const valid = response => {
vm.hasError = false;
vm.fields = response.fields;
vm.messages = response.messages;
if(vm.fields) {
vm.hasError = true;
for(var i = 0; i < vm.fields.length; i++) {
if(vm.fields[i] === 'firstName') {
vm.errFirstName = vm.fields[i];
vm.errFirstNameMsg = vm.messages[i];
} else if (vm.fields[i] === 'lastName') {
vm.errLastName = vm.fields[i];
vm.errLastNameMsg = vm.messages[i];
} else if (vm.fields[i] === 'mobilePhone') {
vm.errMobilePhone = vm.fields[i];
vm.errMobilePhoneMsg = vm.messages[i];
} else if (vm.fields[i] === 'email') {
vm.errEmail = vm.fields[i];
vm.errEmailMsg = vm.messages[i];
} else if (vm.fields[i] === 'password') {
vm.errPassword = vm.fields[i];
vm.errPasswordMsg = vm.messages[i];
} else if (vm.fields[i] === 'details') {
vm.errDetails = vm.fields[i];
vm.errDetailsMsg = vm.messages[i];
}
}
}
}
const setNull = () => {
delete vm.user.fields;
delete vm.user.messages;
vm.errFirstName = null;
vm.errFirstNameMsg = null;
vm.errLastName = null;
vm.errLastNameMsg = null;
vm.errMobilePhone = null;
vm.errMobilePhoneMsg = null;
vm.errEmail = null;
vm.errEmailMsg = null;
vm.errPassword = null;
vm.errPasswordMsg = null;
vm.errDetails = null;
vm.errDetailsMsg = null;
}
const saveCallback = response => {
valid(response);
if(!vm.hasError) {
vm.hasError = null;
$location.path(`/admin/user-edit/${vm.user.id}`);
}
};
const errorCallback = err => {
vm.msg=`${err.data.message}`;
};
vm.saveUser = () => {
setNull();
UserService.save(vm.user)
.then(saveCallback)
.catch(errorCallback);
};
const updateCallback = response => {
valid(response);
if(vm.hasError) {
vm.user = UserService.get(userId);
}
if(!vm.hasError) {
vm.hasError = null;
vm.msgSuccess = 'Changes saved';
}
}
const setUserEmail = result => {
vm.userEmail = result[0];
}
const userEmailPromise = UserService.getUserEmail();
userEmailPromise.$promise.then(setUserEmail);
const checkNonRemovableAccounts = () => {
if(vm.userEmail === "admin@example.com" || vm.userEmail === "user@example.com") {
vm.msg = 'You cannot change this user\'s (\'admin@example.com\' and \'user@example.com\''
+ ' modifications or delete are not possible)';
throw new Exception();
}
};
vm.updateUser = () => {
setNull();
checkNonRemovableAccounts();
UserService.update(vm.user)
.then(updateCallback)
.catch(errorCallback);
};
});
|
import { arrayMethods } from './array'
import Dep from './dep.js'
console.log(Dep, 2323)
import { defineProperty } from '../util'
export function observe (data) {
if(data.__ob__) return data
if(data && typeof data === 'object') {
// data必须是一个对象
return new Observer(data)
}
}
class Observer {
constructor(value) {
this.dep = new Dep();
// 使用 defineProperty 来重新定义属性
if(Array.isArray(value)) {
// 函数劫持, 重写数组的方法,再调用原方法的同时,又去做了一些响应式处理的逻辑
value.__proto__ = arrayMethods
// 观测数组的对象类型,对象变化也做一些事情
this.observeArray(value)
// 判断一个对象是否被观测过
defineProperty(value, '__ob__',this)
} else {
this.walk(value)
}
}
observeArray (value) {
value.forEach(item => {
observe(item)
})
}
walk (data) {
let keys = Object.keys(data) // 获取对象的key
keys.forEach(key => {
defineReactive(data, key, data[key])
})
}
}
function defineReactive (data,key,value) {
// 为了实现了深层对象的处理, 首先递归地执行 observe 进行判断,如果还是一个对象类型的话
// 这样会导致性能比较差
// 获取到数组对应的 dep
let childDep = observe(value)
// 每个属性都有一个 dep 属性,用于存放 watcher
// 当页面取值时候,说明这个值用来渲染了,此时将这个 属性和 watcher 对应起来
let dep = new Dep()
Object.defineProperty(data, key, {
get () {
if(Dep.target) { // 让这个属性记住这个 watcher
dep.depend()
if(typeof childDep === 'object') {
childDep.dep.depend() // 数组存起来这个渲染过程
}
}
return value
},
set (newValue) {
if(newValue === value) return
// 如果用户传进来的依旧是个对象的话,对这个对象依旧使用 observe 方法
observe(newValue)
value = newValue
dep.notify()
}
})
}
// 但是要对数组进行特殊的操作
// 确实使用 defineProperty确实可以对数组进行拦截,但是如果是个巨大的数组, 会导致性能很差
// 于是 Vue 直接重写了数组的常用方法, 在你调用这些方法时候,添加了一些实现了响应式的逻辑
// -- push , pop ,shift , unshift , splice , sort ,reserve
|
import React, { useContext, useEffect, useState } from 'react';
import { UserContext } from '../../../App';
import OrderListCard from '../OrderListCard/OrderListCard';
import Sidebar from '../Sidebar/Sidebar';
const OrderList = () => {
const { user } = useContext(UserContext);
const [loggedInUser, setLoggedInUser] = user;
const [ placedOrders, setPlacedOrders] = useState([]);
useEffect(() => {
fetch('https://mighty-ravine-85440.herokuapp.com/placeOrders', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
}
})
.then(res => res.json())
.then(data => setPlacedOrders(data));
},[])
console.log(placedOrders);
return (
<div className="d-flex col-sm-12">
<Sidebar></Sidebar>
<div className="" style={{ height: '700px', width: '100%', marginTop: '100px',background: '#F4F7FC' }}>
<div className="">
<h4 className="">Service List-Order</h4>
</div>
<div className="mt-5 p-5 container-fluid" style={{width: '100%', background: '#F4F7FC' }}>
<div className="card-deck">
<div className="row w-100">
{
placedOrders.map(placedOrder => <OrderListCard placedOrder={placedOrder} key={placedOrder._id} />)
}
</div>
</div>
</div>
</div>
</div>
);
};
export default OrderList;
|
function TrackPiece( x1, y1, x2, y2, x3, y3, x4, y4 ){
this.start = createVector( x1, y1 );
this.c1 = createVector( x2, y2 );
this.c2 = createVector( x3, y3 );
this.end = createVector( x4, y4 );
this.points = [];
this.sections = 50;
this.width = 50;
this.s = -1;
this.e = -1;
this.m = 1;
for( var i=0; i<=this.sections; i++ ){
var x = bezierPoint( this.start.x, this.c1.x, this.c2.x, this.end.x, i/this.sections );
var y = bezierPoint( this.start.y, this.c1.y, this.c2.y, this.end.y, i/this.sections );
var tx = bezierTangent( this.start.x, this.c1.x, this.c2.x, this.end.x, i/this.sections );
var ty = bezierTangent( this.start.y, this.c1.y, this.c2.y, this.end.y, i/this.sections );
var normal = atan2( ty, tx )+PI/2;
var n = i/(this.sections);
t = ( this.s*(1-n) + this.e*n );
t += (cos( n*PI*2+PI + sin(n*PI*2)/4 )+1)/2*(this.m-t);
t *= this.width/2;
this.points.push({
x:x,
y:y,
tx:cos(normal),
ty:sin(normal),
t:t,
});
}
this.draw = function(){
stroke(255);fill(255);strokeWeight(1);
ellipse( this.start.x, this.start.y, 5, 5 );
noFill();
/*
bezier(
this.start.x, this.start.y,
this.c1.x, this.c1.y,
this.c2.x, this.c2.y,
this.end.x, this.end.y
)
*/
var w = this.width/2;
var point, prev;
point = this.points[0];
line(point.x-point.tx*w, point.y-point.ty*w,point.x+point.tx*w, point.y+point.ty*w);
point = this.points[ this.points.length-1 ];
line(point.x-point.tx*w, point.y-point.ty*w,point.x+point.tx*w, point.y+point.ty*w);
for( var i=0; i<this.points.length; i++ ){
point = this.points[i];
//line(point.x-point.tx*w, point.y-point.ty*w,point.x+point.tx*w, point.y+point.ty*w);
if( i>0 ){
line(point.x-point.tx*w, point.y-point.ty*w, prev.x-prev.tx*w, prev.y-prev.ty*w );
line(point.x+point.tx*w, point.y+point.ty*w, prev.x+prev.tx*w, prev.y+prev.ty*w );
}
prev = point;
}
stroke(255,0,0);fill(255,0,0);strokeWeight(3);
for( var i=0; i<this.points.length; i++ ){
point = this.points[i];
if( i>0 )
line( prev.x+prev.tx*prev.t, prev.y+prev.ty*prev.t, point.x+point.tx*point.t, point.y+point.ty*point.t );
prev = point;
prevt = t;
}
}
}
|
// Tradition
var tradition = new Vaisseau('Tradition', 'Tradition', '5EE-classe-Pegasus', explorateur, green_pulsion, m10);
tradition.setBlindage(blindage_mk2);
tradition.setBouclier(b40);
tradition.addArme('babord', canon_laser_leger);
tradition.addArme('tribord', canon_laser_leger);
tradition.addArme('tourelle', canon_magnetique);
tradition.setEchelon(2);
tradition.compute();
var vaisseau = tradition;
|
import React from 'react';
import CommentForm from '../comment/comment_form_container';
import LikeButton from '../like/like_button_container';
import { deleteComment } from '../../actions/photo_actions.js';
import CommentList from '../comment/comment_list_container';
import {Link} from 'react-router-dom';
class PhotoModal extends React.Component{
componentDidMount(){
if (!this.props.photo){
this.props.requestPhoto(this.props.id);
}
}
commentList (photo){
return (
<ul className='photo-modal-comment-list-ul'>
{photo.comments.map(comment => {
return(
<CommentList photoId={photo.id} com={comment} photoAuthorId={photo.user_id}/>
);
})}
</ul>
);
}
deleteButton(){
if (this.props.currentUserId === this.props.photo.user_id){
return (
<button title='delete photo' className='delete-button' onClick={() => this.props.deletePhoto(this.props.photo.id)
.then(()=>this.props.getUser(this.props.currentUserId))
.then(()=>this.props.closeModal())}>
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="black" stroke="#000" strokeWidth="1" strokeLinecap="round" strokeLinejoin="round">
<circle cx="12" cy="12" r="2"/>
<circle cx="20" cy="12" r="2"/>
<circle cx="4" cy="12" r="2"/>
</svg>
</button>
);
}
}
render () {
if (!this.props.photo){
return null;
}
return (
<div onClick={(e) => e.stopPropagation()} className ='photo-modal-wrap'>
<img className ='photo-modal-image' src={this.props.photo.image_url}/>
<div className ='photo-modal-right'>
<div className='photo-modal-right-top'>
<header className='photo-modal-header'>
<div className='photo-modal-user-div'>
<Link to={`/users/${this.props.photo.user_id}`} className='photo-modal-avatar-link'> <img className='photo-modal-avatar-image' src={this.props.photo.user_avatar}/></Link>
<Link to={`/users/${this.props.photo.user_id}`} className='photo-modal-author-name'> {this.props.photo.username}</Link>
</div>
</header>
<div className='photo-modal-comment-list-div'>
{this.commentList(this.props.photo)}
</div>
</div>
<div className='photo-modal-right-bottom'>
<section className='like-comment-button-container'>
<LikeButton photoId={this.props.photo.id} liked={this.props.photo.viewer_liked} likeId={this.props.photo.viewer_like_id}/>
<button type="button" className='comment-icon-button'>
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#000" strokeWidth="1" strokeLinecap="round" strokeLinejoin="round">
<path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"/>
</svg>
</button>
</section>
<section className='num-likes-container'>
<div className='num-likes'> {this.props.photo.num_likes} likes</div>
</section>
<Link onClick={this.props.closeModal}to={`/photos/${this.props.photo.id}`} className='post-time-link' id={this.props.photo.id}>
<div className='post-time-div'>{this.props.photo.time_ago}</div>
</Link>
<div className='comment-form-delete-button'>
<CommentForm photoId={this.props.photo.id}/>
{this.deleteButton()}
</div>
</div>
</div>
</div>
);
}
}
export default PhotoModal;
|
import React, { Component } from 'react';
class Topics extends Component {
constructor(props) {
super(props);
this.state = {
topic: this.props.topic,
opinion: '',
}
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(e) {
this.setState({
[e.target.name]: e.target.value,
})
}
handleSubmit() {
fetch('/post_opinion', {
method: 'post',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(this.state),
})
.catch(err => {
console.log("Error when attempting to post_opinion", err);
})
}
render () {
const style = {
entry: {
width: '345px',
height: '100px',
backgroundColor: 'lightblue',
display: 'flex',
alignItems: 'center',
},
opinions: {
width: '800px',
height: '120px',
backgroundColor: 'lightblue',
alignItems: 'center',
overflow: 'scroll',
},
div: {
display: 'block',
clear: 'both'
},
list: {
listStyleType: 'none',
}
}
return (
<div>
<div style={{float: 'left'}}>
<div style={style.entry} className="entry" id={this.props.i}><h1>{this.props.topic}</h1></div>
<form>
<input name="opinion" placeholder="opinion" value={this.state.opinion} onChange={this.handleChange}/>
<input value="Submit" onClick={this.handleSubmit}/>
</form>
</div>
</div>
)
}
}
|
import { extend } from '../../core/utils/extend';
import errors from '../widget/ui.errors';
import { deepExtendArraySafe } from '../../core/utils/object';
import { getRecurrenceProcessor } from './recurrence';
var PROPERTY_NAMES = {
startDate: 'startDate',
endDate: 'endDate',
allDay: 'allDay',
text: 'text',
description: 'description',
startDateTimeZone: 'startDateTimeZone',
endDateTimeZone: 'endDateTimeZone',
recurrenceRule: 'recurrenceRule',
recurrenceException: 'recurrenceException',
disabled: 'disabled'
};
class AppointmentAdapter {
constructor(rawAppointment, options) {
this.rawAppointment = rawAppointment;
this.options = options;
}
get duration() {
return this.endDate ? this.endDate - this.startDate : 0;
}
get startDate() {
var result = this.getField(PROPERTY_NAMES.startDate);
return result === undefined ? result : new Date(result);
}
set startDate(value) {
this.setField(PROPERTY_NAMES.startDate, value);
}
get endDate() {
var result = this.getField(PROPERTY_NAMES.endDate);
return result === undefined ? result : new Date(result);
}
set endDate(value) {
this.setField(PROPERTY_NAMES.endDate, value);
}
get allDay() {
return this.getField(PROPERTY_NAMES.allDay);
}
set allDay(value) {
this.setField(PROPERTY_NAMES.allDay, value);
}
get text() {
return this.getField(PROPERTY_NAMES.text);
}
set text(value) {
this.setField(PROPERTY_NAMES.text, value);
}
get description() {
return this.getField(PROPERTY_NAMES.description);
}
set description(value) {
this.setField(PROPERTY_NAMES.description, value);
}
get startDateTimeZone() {
return this.getField(PROPERTY_NAMES.startDateTimeZone);
}
get endDateTimeZone() {
return this.getField(PROPERTY_NAMES.endDateTimeZone);
}
get recurrenceRule() {
return this.getField(PROPERTY_NAMES.recurrenceRule);
}
set recurrenceRule(value) {
this.setField(PROPERTY_NAMES.recurrenceRule, value);
}
get recurrenceException() {
return this.getField(PROPERTY_NAMES.recurrenceException);
}
set recurrenceException(value) {
this.setField(PROPERTY_NAMES.recurrenceException, value);
}
get disabled() {
return !!this.getField(PROPERTY_NAMES.disabled);
}
get timeZoneCalculator() {
return this.options.getTimeZoneCalculator();
}
get isRecurrent() {
return getRecurrenceProcessor().isValidRecurrenceRule(this.recurrenceRule);
}
getField(property) {
return this.options.getField(this.rawAppointment, property);
}
setField(property, value) {
return this.options.setField(this.rawAppointment, property, value);
}
calculateStartDate(pathTimeZoneConversion) {
if (!this.startDate || isNaN(this.startDate.getTime())) {
throw errors.Error('E1032', this.text);
}
return this.calculateDate(this.startDate, this.startDateTimeZone, pathTimeZoneConversion);
}
calculateEndDate(pathTimeZoneConversion) {
return this.calculateDate(this.endDate, this.endDateTimeZone, pathTimeZoneConversion);
}
calculateDate(date, appointmentTimeZone, pathTimeZoneConversion) {
if (!date) {
// TODO: E1032 should be thrown only for startDate above
return undefined;
}
return this.timeZoneCalculator.createDate(date, {
appointmentTimeZone: appointmentTimeZone,
path: pathTimeZoneConversion
});
}
clone() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : undefined;
var result = new AppointmentAdapter(deepExtendArraySafe({}, this.rawAppointment), this.options);
if (options !== null && options !== void 0 && options.pathTimeZone) {
result.startDate = result.calculateStartDate(options.pathTimeZone);
result.endDate = result.calculateEndDate(options.pathTimeZone);
}
return result;
}
source() {
var serializeDate = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
if (serializeDate) {
// TODO: hack for use dateSerializationFormat
var clonedAdapter = this.clone();
clonedAdapter.startDate = this.startDate;
clonedAdapter.endDate = this.endDate;
return clonedAdapter.source();
}
return extend({}, this.rawAppointment);
}
}
export default AppointmentAdapter;
|
import React, { Component } from 'react';
import styles from './styles.scss';
class faveImage extends Component {
render() {
const faveBg = {
backgroundImage: 'linear-gradient(to bottom, rgba(0,0,0,0) 0%,rgba(0,0,0,0) 67%,rgba(0,0,0,0.65) 100%), url('+ this.props.image + ')',
backgroundPosition: 'center',
backgroundSize: 'cover',
}
return (
<div className="faveImageContainer">
<div className="faveCard">
<div className="faveImage" style={faveBg}></div>
<div className="faveInfo">
<p className="dishName">{this.props.name}</p>
<p className="dishNumber" >{this.props.number}</p>
</div>
</div>
</div>
);
}
}
export default faveImage;
|
var readline = require('readline');
var utility = require('../Utility/utility.js');
var read = readline.createInterface({
input : process.stdin,
output : process.stdout
});
function windChill()
{
read.question("Enter the temperature in farenheit ", function(temp){
read.question("Enter the wind speed in hours ", function(speed){
utility.windChill(temp , speed);
read.close();
})
})
}
windChill();
|
/* eslint-disable react/no-danger */
import Layout from "../components/Layout";
import PropTypes from "prop-types";
import "../styles/index.css";
const App = ({ Component, pageProps }) => (
<>
<Layout>
<Component {...pageProps} />
</Layout>
</>
);
App.propTypes = {
Component: PropTypes.any,
pageProps: PropTypes.object
};
export default App;
|
/*=========================================================================================
File Name: moduleCalendarMutations.js
Description: Calendar Module Mutations
----------------------------------------------------------------------------------------
Item Name: Vuexy - Vuejs, HTML & Laravel Admin Dashboard Template
Author: Pixinvent
Author URL: http://www.themeforest.net/user/pixinvent
==========================================================================================*/
export default {
ADD_ITEM(state, item) {
state.contacts.unshift(item);
},
SET_CONTACTS(state, contacts) {
state.contacts = contacts;
},
UPDATE_CONTACT(state, contact) {
const contactIndex = state.contacts.findIndex(p => p.id === contact.id);
Object.assign(state.contacts[contactIndex], contact);
},
REMOVE_ITEM(state, itemSlug) {
const ItemIndex = state.contacts.findIndex(p => p.tag === itemSlug);
state.contacts.splice(ItemIndex, 1);
}
};
|
// browser-specific hooks and definitions
var sys = {};
sys.print = function(str) {
// var s = str.toString().replace(new RegExp('\n', 'g'), '<br />');
var span = document.createTextNode(s);
span.style["white-space"] = "pre";
document.body.appendChild(span);
};
sys.error = function(e) {
if (typeof(console) !== 'undefined' && console.log) {
if (e.stack) {
console.log(e.stack);
}
else {
console.log("Error: " + str);
}
}
else {
var s = "Error: " + e.toString() + "\n";
var span = document.createTextNode(s);
span.style["white-space"] = "pre";
document.body.appendChild(span);
}
};
sys.inspect = function(x) {
// FIXME: add more helpful inspect function that'll show
// us what's really inside. Perhaps use toString()?
return x + '';
};
var DEBUG_ON = false;
var setDebug = function(v) {
DEBUG_ON = v;
};
var debug = function(s) {
if (DEBUG_ON) {
sys.print(s);
}
};
var debugF = function(f_s) {
if (DEBUG_ON) {
sys.print(f_s());
}
};
var deepEqual = function (obj1, obj2) {
var i;
if (obj1 === obj2) {
return true;
}
for (i in obj1) {
if ( obj1.hasOwnProperty(i) ) {
if ( !(obj2.hasOwnProperty(i) && deepEqual(obj1[i], obj2[i])) ) {
return false;
}
}
}
for (i in obj2) {
if ( obj2.hasOwnProperty(i) ) {
if ( !(obj1.hasOwnProperty(i) && deepEqual(obj1[i], obj2[i])) )
return false;
}
}
return true;
};
var assert = {};
assert.equal = function(x, y) {
if (x !== y) {
alert('AssertError: ' + x + ' equal ' + y);
throw new Error('AssertError: ' + x + ' equal ' + y);
}
};
assert.deepEqual = function(x, y) {
if ( !deepEqual(x, y) ) {
alert('AssertError: ' + x + ' deepEqual ' + y);
throw new Error('AssertError: ' + x + ' deepEqual ' + y);
}
};
assert.ok = function(x) {
if (!x) {
alert('AssertError: not ok: ' + x);
throw new Error('AssertError: not ok: ' + x );
}
};
assert.throws = function(f) {
try {
f.apply(null, []);
} catch (e) {
return;
}
throw new Error('AssertError: Throw expected, none received.');
};
|
/*
* @lc app=leetcode id=120 lang=javascript
*
* [120] Triangle
*/
/**
* @param {number[][]} triangle
* @return {number}
*/
var minimumTotal = function(triangle) {
if (!triangle.length) {
return 0;
}
let count = [triangle[0][0] || 0];
for (let i = 1; i < triangle.length; i++) {
for (let j = triangle[i].length - 1; j >= 0; j--) {
const top1 = count[j] !== undefined ? count[j] : Number.MAX_VALUE;
const top2 = count[j - 1] !== undefined ? count[j - 1] : Number.MAX_VALUE;
count[j] = triangle[i][j] + Math.min(top1, top2);
}
}
let min = Number.MAX_VALUE;
for (let i of count) {
(min > i) && ( min = i );
}
return min;
};
minimumTotal([[1],[-5,-2],[3,6,1],[-1,2,4,-3]]);
|
const ids = "./ids.json";
class List {
constructor() {
this.index = 0;
this.ids = ids;
this.unavailableIndexes = [];
}
getId() {
if (this.unavailableIndexes.length >= this.ids.length) {
throw Error("No more IDs to provide!");
}
// get id at current index
const currentId = this.ids[this.index];
}
incrementId() {
// if (this.unavailableIndexes.length >= this.ids.length) {
// throw Error("No more IDs to provide!");
// }
// increment index
this.index += 1;
// if unavailableIndexes contains index, increment again.
if (this.unavailableIndexes.includes(this.index)) {
this.incrementId();
}
}
}
module.exports = List;
|
jQuery(function($) {
function toggleDrawer(e) {
$('#drawer-toggle').toggleClass('clicked');
$('#drawer').toggleClass('visible');
$('.drawer-overlay').fadeToggle();
}
// var mainHeader = $('.main-header-container');
// var mainMenu = $('#main-menu');
// var slider = $('#slider');
// var menuItems = mainMenu.find('a');
// var sections = menuItems.map(function() {
// var id = $(this).attr('href').split('#')[1];
$('#drawer-toggle, .drawer-overlay').click(toggleDrawer);
$('#search-form-toggle').click(function() {
$(this).toggleClass('clicked');
$(this).siblings('.search-form').toggleClass('visible');
// .find('input[type=search]').focus();
});
// if (id) { return $('#' + id); }
// });
// slider.slick({
// arrows: false,
// centerMode: false,
// variableWidth: false,
// responsive: [
// {
// breakpoint: 1280,
// settings: {
// centerMode: true,
// variableWidth: true
// }
// }
// ]
// });
// $(window).resize(function() {
// if ($(window).width() >= 1280)
// slider.slick('slickSetOption', 'centerMode', true, true);
// })
// $(window).scroll(function() {
// var fromTop = $(this).scrollTop();
// var section = sections.map(function() {
// if ($(this).offset().top < fromTop) {
// return this;
// }
// });
// section = section[section.length - 1];
// var id =
// });
// $('#store-tabs').tabs({
// show: { effect: 'fade', duration: 500 },
// hide: { effect: 'fade', duration: 100 }
// }).find('.store-title').click(function () {
// id = $(this).children('a').attr('href');
// marker = window.markers[id.replace(/[^-]+-/, '')];
// window.map.panTo(marker);
// });
// var openingHours = $('#otvaracia-doba');
// openingHours.find('.show-more').click(function() {
// openingHours.find('.day').animate({ height: 'toggle',
// opacity: 'toggle'});
// $(this).toggleClass('opened');
// });
// $('.mc4wp-alert').click(function() {
// $(this).fadeOut();
// });
// $('.gallery').slick({
// arrows: false,
// slidesToShow: 4,
// variableWidth: true,
// infinite: false
// });
// mainHeader.hcSticky();
// $('#sidebar').hcSticky({ top: mainHeader.height()});
});
// function initMap() {
// markers = {
// 'liptovsky-mikulas': { lat: 49.07998, lng: 19.621558 },
// 'liptovsky-hradok': { lat: 49.038086, lng: 19.717175 }};
// elem = document.getElementById('map');
// map = new google.maps.Map(elem, {
// center: markers['liptovsky-mikulas'],
// zoom: 13 });
// for (slug in markers) {
// marker = new google.maps.Marker({
// position: markers[slug],
// map: map});
// }
// window.markers = markers;
// window.map = map;
// }
|
/**
* Email List Item
*/
import React from 'react';
import IconButton from '@material-ui/core/IconButton';
import classnames from 'classnames';
import Checkbox from '@material-ui/core/Checkbox';
import Avatar from '@material-ui/core/Avatar';
// helpers functions
import { textTruncate } from 'Helpers/helpers';
const EmailListItem = ({ email, onSelectEmail, handleMarkAsStar, onReadEmail, getTaskLabelNames }) => (
<li className="d-flex justify-content-between align-items-center list-item" onClick={onReadEmail}>
<div className="d-flex align-items-center w-100">
<div className="checkbox-wrap">
<Checkbox
checked={email.selected}
onClick={onSelectEmail}
/>
</div>
<div className="icon-wrap">
<IconButton onClick={handleMarkAsStar} className="mx-10 d-none d-sm-block">
<i className={classnames('zmdi zmdi-star', { 'text-warning': email.starred })}></i>
</IconButton>
</div>
<div className="emails media w-100">
<div className="avatar-wrap w-10 align-self-center">
{email.from.avatar !== '' ?
<img src={email.from.avatar} alt="mail user" className="rounded-circle mr-15 align-self-center" width="40" height="40" />
: <Avatar className="mr-15 align-self-center">{email.from.name.charAt(0)}</Avatar>
}
</div>
<div className="media-body d-flex align-items-center w-90">
<div className="d-inline-block w-25">
<h5 className="mb-1">{email.user_name }</h5>
<span className="font-xs d-inline-block">{textTruncate(email.email_subject, 30)}</span>
</div>
<p className="font-xs text-muted w-75 d-inline-block mb-0 mx-4">{textTruncate(email.email_content, 120)}</p>
</div>
</div>
</div>
<div className="font-xs text-muted w-10 text-right">{email.received_time}</div>
</li>
);
export default EmailListItem;
|
var superUserId = "111111112222222233333333";
var date = new Date();
var time = date.getTime();
//load 10 000 profiles
//load("generatedProfiles.js")
//=================1.generate super Users
var USERS_COUNT=100; //should be more than popular index (40currently)
//var PROFILES_COUNT=100;
var occupationList = [
"Actor",
"Actress",
"Teacher",
"Manager",
"Professor",
"Administrator",
"Singer",
"Doctor",
"Sport player",
"Musician",
"Writer"
];
var skillsList = [
"Accurate",
"Ambitious",
"Artistic",
"Charismatic",
"Collaborative",
"Communicative",
"Creative",
"Confident",
"Consistent",
"Direct",
"Entertaining",
"Energetic",
"Flexible",
"Innovative",
"Leadership",
"Listening",
"Modest",
"Politeness",
"Productive",
"Reliable",
"Resourceful",
"Responsible",
"Sincere",
"Thorough"
];
//super user to generate profiles
//only run once
db.users.insert(
{"_id" : ObjectId(superUserId),
"created" : time,
"first_name" : "fbTest1First",
"last_name" : "fbTest1Last",
"email" : "reviyoutest10@gmail.com",//put your fb email here!
"is_fake_user" :true, //additional field just for our internal purposes
"login_provider" : "facebook",
"token" : "token",
"gender": "male",
//image should be in our db or on our web server
//a.png would work since it's less than 6 characters and nginx will return default image this case
//"user_profile_image" : "a.png",
"google_login_data" :
{
"expiresIn" : "1000000000",
"idToken" : "someuserid",
"refreshToken": "sometoken",
"tokenType" :"type",
"googleUserId": "gggguserId",
"image_url": "http://www.emagazin.info/img/articles/arenda-admina/super-admin.jpg",
"is_default_image" :false
}
}
);
for (var i = 1; i <= USERS_COUNT; i++) {
db.users.insert(
{ "created" : time,
"first_name" : "admin_FirstName"+i,
"last_name" : "admin_LastName"+i,
"email" : "admin" + i + "@reviyou.com",
"is_fake_user" :true, //additional field just for our internal purposes
"login_provider" : "facebook",
"token" : "token",
"gender": "male",
"fb_login_data" :
{
"expiresIn" : "1",//small number so that user does expire
"fbUserId" : "fbUserIdTestUtils"+i,
"image_url": "https://api.reviyou.com/api/1.0/image/default.pic",
"is_default_image" :false
}
}
)
}
//userId's
var userIds = [];
var userIdCursor = db.users.find({},{"is_fake_user": true})//projection by _id
while(userIdCursor.hasNext() && userIds.length<=100) {
var userId = userIdCursor.next();
userIds.push(userId._id.str);
}
//=================2.add skills and professions
//var str ="AaBbCcDdEeFfGgHhIiGgKkLlMmNnOoPpRrSsTtUuVvWwXxYyZz";
for (var i = 0; i < skillsList.length; i++) {
db.skills.insert({"skill_name" : skillsList[i] })
}
for(var i=0;i<occupationList.length;i++) {
db.professions.insert({"profession_name" : occupationList[i] })
}
//load visitors for each profile and 1 vote for general
var profileIdCursor3 = db.profiles.find({"user_id": superUserId},{"popular_index": 1})//TODO:also add a check to run only profiles created today
while(profileIdCursor3.hasNext()) {
var profileId3 = profileIdCursor3.next();
var popular = profileId3.popular_index;
//print('popular' + popular);
//for(var j=0;j<popular;j++) {
db.profileVisitors.insert({"_id": profileId3._id, "user_ids" : userIds.slice(0, popular)});
//}
//user2 General
db.votes.insert({
"created" : time,
"profile_id": profileId3._id.str,
"user_id" : superUserId,
"vote_time" : time,
"vote_value" : (popular/10)
});
}
//-1000*60*60*24*i;//minus day
var uniqueDate = new Date(time);
db.news.insert({
"title": "This is a first official release 1.0.0!",
"content": "Dear Users! We are proud to present you this application, please give it a try and let us know what you think and what you want us to add to it. You can start with an intro section to learn more about how to use this app. Hope you'll enjoy it and find it useful. We intend to continuosly work on improving it and adding more features. Love Reviyou? Drop us a rating in the App Store! Truly yours, Reviyou Team.",
"create_time": uniqueDate
})
print('end of upload script');
|
import React, {Component} from "react";
import "./style.css";
import { Form, FormGroup, Label, Input, FormText, Button } from "reactstrap";
class PetFormBasics extends Component {
continue = e => {
e.preventDefault();
this.props.nextStep();
};
render() {
const { values, handleChange } = this.props;
return (
<React.Fragment>
<FormGroup>
<Label for="petName">Pet Name: </Label>
<Input type="text" name="petName" id="petName" onChange={handleChange('petName')} defaultValue={values.petName} placeholder="Nicknames work too!" />
</FormGroup>
<FormGroup>
<Label for="petBirthday">Birthday: </Label>
<Input type="date" name="petBirthday" id="petBirthday" onChange={handleChange('petBirthday')} defaultValue={values.petBirthday} placeholder="mm/dd/yyyy" style={{height: "100%"}} />
</FormGroup>
<FormGroup>
<Label for="petType">Type: </Label>
<Input type="text" name="petType" id="petType" onChange={handleChange('petType')} defaultValue={values.petType} placeholder="Are they a Dog? Cat?" />
</FormGroup>
<FormGroup>
<Label for="breed">Breed: </Label>
<Input type="text" name="breed" id="breed" onChange={handleChange('breed')} defaultValue={values.breed} />
</FormGroup>
<Button className="formBtn" style={{marginLeft: '52%'}} onClick={this.continue}>Continue</Button>
</React.Fragment>
)
}
}
export default PetFormBasics;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.