text
stringlengths 7
3.69M
|
|---|
import React from 'react';
import {connect} from 'react-redux'
import { saveLocation,createLocation, changeLocation } from '../../actions/location.action';
import {loadOrganization} from '../../actions/organization.action';
import TextField from 'material-ui/TextField';
import RaisedButton from 'material-ui/RaisedButton';
import PlacesAutocomplete, { geocodeByAddress, getLatLng } from 'react-places-autocomplete'
export class LocationComponent extends React.Component{
constructor(props){
super(props);
console.log("LOCATION PROPS: ", props);
this.state = { address: this.props.location.address }
this.onChange = (address) => this.setState({address})
}
saveLocation() {
// ES6 object destructuring on props
let location = {...this.props.location, address: this.state.address, organization_id: this.props.organization._id}
console.log(location)
geocodeByAddress(this.state.address)
.then(results => getLatLng(results[0]))
.then(latLng => {
console.log('Success', latLng)
location.latLng = [latLng.lng, latLng.lat];
this.saveOrUpdateLocation(location);
})
.catch(error => {
console.error('Error', error)
this.saveOrUpdateLocation(location);
})
}
saveOrUpdateLocation(location){
if (location._id) {
this.props.dispatch(saveLocation(location))
.then(c=>{
this.props.dispatch(loadOrganization(this.props.organization._id));
});
} else {
this.props.dispatch(createLocation(location))
.then(c=>{
this.props.dispatch(loadOrganization(this.props.organization._id));
});
}
}
onChangeFunction(key, input){
this.props.dispatch(changeLocation(key,input.target.value));
}
// componentDidReceiveProps(){
// if(this.props.location.address &&
// this.state.location.address != this.props.location)
// this.setState({address: this.props.location.address });
// }
render(){
if(!this.props.location) return (<div></div>);
const inputProps = {
value: this.state.address,
onChange: this.onChange
}
return(
<div>
<form ref="form" id="locationForm">
<p>All the general info about the location</p>
<TextField
onChange={this.onChangeFunction.bind(this, "called")}
value={this.props.location.called}
floatingLabelText="Name"
/>
<PlacesAutocomplete inputProps={inputProps} />
<RaisedButton label="Save"
onTouchTap={this.saveLocation.bind(this)} />
</form>
</div>
)
}
}
let mapStateToProps = (state, props) => {
return {
location: state.locationReducer.location,
locations: state.locationReducer.locations,
organization: state.organizationReducer.organization
}
};
export default connect(mapStateToProps)(LocationComponent);
|
import React from 'react'
import { Button, Upload } from 'Components/UI-Library'
import './ProfileAvatar.Style.less'
const ProfileAvatar = () => {
return (
<div className="profile-img">
<img src="https://i.ytimg.com/vi/1Ne1hqOXKKI/maxresdefault.jpg" alt="" />
<Upload name="avatar" className="upload-image">
<Button className="file">Change Photo</Button>
</Upload>
</div>
)
}
export default ProfileAvatar
|
// Creates a menu in Google Sheets to send a test email and/or the final email
function onOpen() {
SpreadsheetApp.getUi()
.createMenu('Send Email')
.addSubMenu(SpreadsheetApp.getUi().createMenu('Project Email')
.addItem('Send Test Email', 'sendProjectToSelf')
.addItem('Send Email To List Provided', 'sendProjectToList'))
.addSeparator()
.addSubMenu(SpreadsheetApp.getUi().createMenu('Program Email')
.addItem('Send Test Email', 'sendProgramToSelf')
.addItem('Send Email To List Provided', 'sendProgramToList'))
.addToUi();
}
// Updates Program sheet when the number of projects is edited
function onEdit(e){
if (e.range.getA1Notation() === projectCountCell) {
var projectCountValue = sh.getRange(projectCountCell).getValue();
sh.getRange('A' + projectStartCell + ':B200').clear().clearNote().setDataValidation(null);
// Copies the project template range as many times as specified in projectCountValue
for (i = 0; i < projectCountValue; i++) {
projectTemplateRange.copyTo(sh.getRange('A' + projectStartCell), SpreadsheetApp.CopyPasteType.PASTE_NORMAL);
projectStartCell = projectStartCell + (projectTemplateRows + 1);
}
}
}
|
const CustomError = require('../extensions/custom-error');
const hasNestedArray = arr => arr.some(item => Array.isArray(item));
module.exports = class DepthCalculator {
calculateDepth(arr) {
let depth = 1;
if (hasNestedArray(arr)) {
const newArr = arr.reduce((acc, item) => acc.concat(item), []);
return depth + this.calculateDepth(newArr);
}
return depth;
}
};
|
import superagent from 'superagent';
import util from 'src/util/util';
import ui from 'src/util/ui';
import _ from 'lodash';
module.exports = {
search(term) {
return superagent
.get(
`https://reference.cheminfo.org/v1/search?appendMolfile=true&quick=${encodeURIComponent(
term
)}`
)
.then((result) => {
const data = result.body && result.body.data;
if (!data) {
ui.showNotification('No results in reference DB', 'warn');
return Promise.resolve([]);
}
return data;
})
.then((data) => data.map(fromChemexper))
.then((data) =>
data.sort((a, b) => {
let rn1 = Number(a.catalogID);
let rn2 = Number(b.catalogID);
return rn1 - rn2;
})
);
}
};
function fromChemexper(datum) {
return {
$content: {
general: {
molfile: datum.molfile,
description: datum.iupac && datum.iupac[0],
name: [{ value: datum.iupac[0] }],
mf: datum.mf && datum.mf.mf,
mw: datum.mf && datum.mf.mass,
em: datum.mf && datum.mf.monoisotopicMass
},
identifier: {
cas: numberToCas(datum.catalogID)
},
stock: {
catalogNumber: datum.catalogID
},
physical: {
density: datum.density,
mp: datum.mp,
bp: datum.bp
}
},
id: util.getNextUniqueId(true),
names: datum.iupac,
source: 'reference'
};
}
function numberToCas(nb) {
nb = String(nb);
return `${nb.slice(0, -3)}-${nb.slice(-3, -1)}-${nb.slice(-1)}`;
}
|
import React from 'react'
import './style.scss'
const Work = () => (
<div className="work">
<div className="slider">
</div>
<article>
<h2>Heavy Sand - Creative Photography</h2>
<p>Aenean sollicitudin, lorem quis bibendum auctor, nisi
elit consequat ipsum, nec sagittis sem nibh id elit. Duis
sed odio sit amet nibh vulputate cursus a sit amet mauris.
Morbi accumsan ipsum velit. Nam nec tellus a odio tincidunt
auctor a ornare odio. Sed non mauris vitae erat consequat
auctor eu in elit. Class aptent taciti sociosqu ad litora
This is Photoshop's version of Lorem Ipsum. Proin gravida
nibh vel velit auctor aliquet.</p>
<p>
Duis sed odio sit amet nibh vulputate cursus a sit amet
mauris. Morbi accumsan ipsum velit. Nam nec tellus a odio
tincidunt auctor a ornare odio.
</p>
</article>
<div className="related-projects">
<h2>Related Projects</h2>
<div className="project"></div>
<div className="project"></div>
<div className="project"></div>
</div>
<div className="project-info">
<h2>Project Info</h2>
<span>premium layers</span>
<span>138 likes</span>
<span>25 December, 2013</span>
<span>4 Comments</span>
</div>
<div className="tags">
<h2>Tags</h2>
<button className="tag">web design</button>
<button className="tag">photography</button>
<button className="tag">development</button>
<button className="tag">php</button>
<button className="tag">ecommerce</button>
<button className="tag">graphic</button>
</div>
<div className="project-gallery">
<h2>Project Gallery</h2>
<div className="gallery-item"></div>
<div className="gallery-item"></div>
<div className="gallery-item"></div>
<div className="gallery-item"></div>
<div className="gallery-item"></div>
<div className="gallery-item"></div>
<div className="gallery-item"></div>
<div className="gallery-item"></div>
<div className="gallery-item"></div>
<div className="gallery-item"></div>
<div className="gallery-item"></div>
</div>
<div className="project-features">
<h2>Project Features</h2>
<span>Responsive Layout</span>
<span>Font Awesome Icons</span>
<span>Clear & Commented Code</span>
<span>Pixel perfect Design</span>
<span>Highly Customizable</span>
</div>
</div>
)
export default Work
|
import React from 'react';
const descriptions = {
queEs: {
title: '¿Qué son las alertas tempranas?',
description: (
<p>
{'Los indicadores de biodiversidad son '}
<b>
medidas
</b>
{' que nos hablan sobre '}
<b>
aspectos particulares de la biodiversidad,
</b>
{' algunos la cuantifican, otros se refieren a su condición, otros dimensionan las presiones que la afectan. Una característica importante de los indicadores es '}
<b>
que se encuentren relacionados con un contexto particular
</b>
{' en el que puedan ser utilizados para apoyar la toma de decisiones ambientales. Por ejemplo, la cifra sobre riqueza de especies (número de especies presentes en un lugar y tiempo determinado) no es un indicador si no se encuentra asociado con una '}
<b>
“historia” y un objetivo particular,
</b>
{' es así como la riqueza de especies se convierte en un indicador cuando nuestro objetivo es, por ejemplo, representar en las Áreas Protegidas al menos el 80% de las especies conocidas presentes en Colombia y utilizamos la riqueza como una medida que se repite a través del tiempo para cuantificar el avance hacia el objetivo planteado.'}
</p>
),
},
porque: {
title: '¿Por qué son importantes los alertas tempranas?',
description: (
<p>
{'Los indicadores son una herramienta que '}
<b>
provee información robusta
</b>
{' sobre el estado actual de la biodiversidad y sus tendencias. Al ser información medible, cuantificable y periódica los indicadores '}
<b>
permiten evaluar cómo está nuestra biodiversidad y cómo se ve o verá afectada
</b>
{' bajo diferentes escenarios de manejo o gestión. Los indicadores proveen evidencia científica y contextualizada para entender los cambios en la biodiversidad y sus posibles consecuencias para el bienestar humano, '}
<b>
convirtiéndose en herramientas poderosas para tomar decisiones ambientales informadas.
</b>
</p>
),
},
quienProduce: {
title: '¿Quién genera las alertas tempranas?',
description: (
<p>
{'Los principales productores de este tipo de información es la '}
<b>
comunidad científica
</b>
{' vinculada tanto a Institutos de Investigación como a Instituciones Académicas. Una '}
<b>
batería mínima de Indicadores de Biodiversidad
</b>
{' a nivel nacional es acordada por el SINA bajo el liderazgo del Ministerio de Medio Ambiente y Desarrollo Sostenible y otros indicadores de biodiversidad se encuentran en el '}
<b>
Plan Estadístico Nacional
</b>
{' liderado por el DANE.'}
</p>
),
},
queEncuentras: {
title: '¿Qué encuentras en esta módulo?',
description: (
<p>
{'Esta sitio contiene un tablero de control de indicadores de Biodiversidad para Colombia. Acá podrás '}
<b>
buscar indicadores
</b>
{' de acuerdo a objetivos de conservación y desarrollo sostenible y podrás visualizar el avance logrado en cada objetivo. Puedes '}
<b>
explorar los indicadores
</b>
{' asociados a un área geográfica específica: áreas protegidas, ecosistemas o áreas administrativas y puedes relacionar o '}
<b>
interpretar varios indicadores
</b>
{' en contextos específicos bajo el marco de Presión, Estado, Respuesta y Beneficios. Para cada indicador encontrarás '}
<b>
información que facilita su interpretación y uso
</b>
{' para la gestión de la biodiversidad en Colombia.'}
</p>
),
},
};
export default descriptions;
|
db.xmen.updateMany({class:{$exists:false}},{$inc:{power:-100}})
|
import React from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { ConnectedRouter } from 'connected-react-router';
import PropTypes from 'prop-types';
import routes from 'routes';
import NavBar from 'components/NavBar';
import { library } from '@fortawesome/fontawesome-svg-core';
import { fab } from '@fortawesome/free-brands-svg-icons';
import * as appLoadActions from 'actions/appLoad';
import * as loginActions from 'actions/login';
class App extends React.Component {
constructor(props) {
super(props);
library.add(fab);
}
componentDidMount() {
this.props.appLoadActions.checkUserStatus();
}
render() {
const { history, loginState, loginActions } = this.props;
return(
<div>
<ConnectedRouter history={ history }>
<NavBar
loginState={loginState}
onClick={() => this.logout(loginActions)}
/>
{ routes }
</ConnectedRouter>
</div>
)
}
logout(loginActions) {
loginActions.logoutUser();
}
}
App.propTypes = {
history: PropTypes.object.isRequired,
appLoadActions: PropTypes.object.isRequired
}
function mapStateToProps(state) {
return {
loginState: state.loginState
};
}
function mapDispatchToProps(dispatch) {
return {
appLoadActions: bindActionCreators(appLoadActions, dispatch),
loginActions: bindActionCreators(loginActions, dispatch)
};
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(App);
|
/**
* Created by nerds on 8/18/2017.
*/
function EncapsulateWords(ebookState) {
//==================================================
// PUBLIC FUNCTIONS
//==================================================
this.encapsulateWordsIntoSpans = function() {
var textNodes = getAllTextNodes();
for (var i = 0; i < textNodes.length; i++) {
var spans = extractSingleWordSpansFromTextNode(textNodes[i]);
replaceTextNodeWithSingleWordSpans(textNodes[i], spans);
}
indexSingleWordSpans();
};
//==================================================
// PRIVATE FUNCTIONS
//==================================================
function indexSingleWordSpans() {
var spans = getEbookIFrameDocument().querySelectorAll(SINGLE_WORD_SPAN_SELECTOR());
for (var i = 0; i < spans.length; i++) {
(function (ii) {
spans[ii].dataset.wordIndex = ii;
spans[ii].addEventListener("dblclick", function () {
ebookState.playFromWordIndex(ii);
});
}(i));
}
}
function getAllTextNodes() {
var iFrameBody = getEbookIFrameDocument().body;
var textNodesOnlyFilter = NodeFilter.SHOW_TEXT;
var filterOutEmptyTextNodes = function (node) {
var onlyContainsWhitespace = new RegExp("^\\s*$");
if (onlyContainsWhitespace.test(node.data)) {
return NodeFilter.FILTER_REJECT;
}
return NodeFilter.FILTER_ACCEPT;
};
var dontDiscardSubTreeIfRejected = false;
var treeWalker = document.createTreeWalker(
iFrameBody,
textNodesOnlyFilter,
filterOutEmptyTextNodes,
dontDiscardSubTreeIfRejected
);
var node;
var textNodeArray = [];
while (node = treeWalker.nextNode()) {
textNodeArray.push(node);
}
return textNodeArray;
}
function replaceTextNodeWithSingleWordSpans(textNode, spans) {
var parent = textNode.parentNode;
var refNode = textNode;
for (var i = spans.length - 1; i >= 0; i--) {
refNode = parent.insertBefore(spans[i], refNode);
}
parent.removeChild(textNode);
}
function extractSingleWordSpansFromTextNode(textNode) {
var words = textNode.textContent.split(" ");
var singleWordSpans = [];
for (var i = 0; i < words.length; i++) {
if (words[i] !== "") {
var newSpan = createSingleWordSpan(words[i]);
singleWordSpans.push(newSpan);
}
}
return singleWordSpans;
}
function createSingleWordSpan(word) {
var span = document.createElement("span");
span.className = SINGLE_WORD_SPAN_CLASS();
var newTextNode = document.createTextNode(word);
span.appendChild(newTextNode);
return span;
}
}
|
const express = require('express');
const sms = require('../controllers/sms.controller.js');
const router = express.Router();
router.get('/', sms.smsSend);
router.post('/:id', sms.setStatus);
router.post('/:id/:id', sms.updateStatus);
module.exports = router
|
import Controller from '@ember/controller';
export default Controller.extend({
init() {
this._super(...arguments);
this.sources = [
{ src: "https://vjs.zencdn.net/v/oceans.mp4", type: "video/mp4" },
{ src: "https://vjs.zencdn.net/v/oceans.webm", type: "video/webm" }
];
},
actions: {
progress: function(e) {
console.log("progress");
},
ready: function() {
console.log("ready");
},
togglePlay: function(player) {
if (player.paused()) {
player.play();
} else {
player.pause();
}
},
}
});
|
function showbox(){
document.getElementById('box3').style.display = 'block';
document.getElementById('boxzoz').style.display ='none';
}
function show1(){
document.getElementById('box2').style.display = 'block';
document.getElementById('box1').style.display ='none';
}
function show2(){
document.getElementById('div2').style.display = 'block';
document.getElementById('div1').style.display ='none';
}
function show3(){
document.getElementById('div3').style.display = 'block';
document.getElementById('div2').style.display = 'none';
document.getElementById('div1').style.display ='none';
}
function show4(){
document.getElementById('div4').style.display = 'block';
document.getElementById('div2').style.display ='none';
document.getElementById('div3').style.display = 'none';
document.getElementById('div1').style.display ='none';
}
function show5(){
document.getElementById('div5').style.display = 'block';
document.getElementById('div4').style.display = 'none';
document.getElementById('div2').style.display ='none';
document.getElementById('div3').style.display = 'none';
document.getElementById('div1').style.display ='none';
}
function show6(){
document.getElementById('div6').style.display = 'block';
document.getElementById('div5').style.display = 'none';
document.getElementById('div4').style.display = 'none';
document.getElementById('div2').style.display ='none';
document.getElementById('div3').style.display = 'none';
document.getElementById('div1').style.display ='none';
}
function show7(){
document.getElementById('div7').style.display = 'block';
document.getElementById('div6').style.display = 'none';
document.getElementById('div5').style.display = 'none';
document.getElementById('div4').style.display = 'none';
document.getElementById('div2').style.display ='none';
document.getElementById('div3').style.display = 'none';
document.getElementById('div1').style.display ='none';
}
function show8(){
document.getElementById('div8').style.display = 'block';
document.getElementById('div7').style.display = 'none';
document.getElementById('div6').style.display = 'none';
document.getElementById('div5').style.display = 'none';
document.getElementById('div4').style.display = 'none';
document.getElementById('div2').style.display ='none';
document.getElementById('div3').style.display = 'none';
document.getElementById('div1').style.display ='none';
}
function show9(){
document.getElementById('div9').style.display = 'block';
document.getElementById('div8').style.display = 'none';
document.getElementById('div7').style.display = 'none';
document.getElementById('div6').style.display = 'none';
document.getElementById('div5').style.display = 'none';
document.getElementById('div4').style.display = 'none';
document.getElementById('div2').style.display ='none';
document.getElementById('div3').style.display = 'none';
document.getElementById('div1').style.display ='none';
}
function show10(){
document.getElementById('div10').style.display = 'block';
document.getElementById('div9').style.display = 'none';
document.getElementById('div8').style.display = 'none';
document.getElementById('div7').style.display = 'none';
document.getElementById('div6').style.display = 'none';
document.getElementById('div5').style.display = 'none';
document.getElementById('div4').style.display = 'none';
document.getElementById('div2').style.display ='none';
document.getElementById('div3').style.display = 'none';
document.getElementById('div1').style.display ='none';
}
|
import Vue from 'vue';
import Vuex from 'vuex';
import characters from '../modules/characters';
import alignments from '../modules/alignments';
import classes from '../modules/classes';
import races from '../modules/races';
import scenarios from '../modules/scenarios';
import players from '../modules/players';
Vue.use(Vuex);
export default new Vuex.Store({
modules: {
characters,
alignments,
classes,
races,
scenarios,
players,
}
})
|
import React from 'react';
import '../css/ImageCard.css';
class ImageCard extends React.Component {
constructor(props) {
super(props);
this.imageRef = React.createRef();
}
render() {
const { description, urls } = this.props.image;
const active = this.props.active;
return (
<div className={`carousel-item ${active}`}>
<div className="grey-back">
<img
ref={this.imageRef}
alt={description}
src={urls.regular}
/>
</div>
</div>
);
}
}
export default ImageCard;
|
import { storiesOf } from "@storybook/react";
import { action } from "@storybook/addon-actions";
import Button from "../components/Button";
import Loading from "../components/Loading";
import Timer from "../components/GameplayView/Timer";
import Panel from "../components/GameplayView/Panel";
import PanelList from "../components/GameplayView/PanelList";
import GameplayHeader from "../components/GameplayView/GameplayHeader";
import ActiveQuestion from "../components/GameplayView/Question";
import Home from "../components/Home";
import WaitingRoom from "../components/WaitingRoom/index";
import PlayerListItem from "../components/WaitingRoom/PlayerListItem";
import PlayerList from "../components/WaitingRoom/PlayerList";
import OptionItem from "../components/WaitingRoom/OptionsForm/OptionItem";
import OptionItemList from "../components/WaitingRoom/OptionsForm/OptionItemList";
import OptionsForm from "../components/WaitingRoom/OptionsForm/index";
import Option from "../components/WaitingRoom/OptionsForm/OptionItemList";
import DialogueBox from "../components/Modal";
import Dropdown from "../components/Dropdown";
import ScoreListItem from "../components/GameplayView/ScoreListItem";
import ScoreList from "../components/GameplayView/ScoreList";
import Scoreboard from "../components/GameplayView/Scoreboard";
import StartGame from "../components/GameplayView/StartGame";
storiesOf("Button", module).add("Submit", () => <Button>Submit</Button>);
storiesOf("Loading", module).add("Dots", () => (
<Loading type="ThreeDots" color="#e9c46a" />
));
storiesOf("Timer", module)
.add("20 second Timer - Big", () => <Timer duration={20} />)
.add("10 second Timer - Small", () => (
<Timer duration={10} size={50} strokeWidth={4} />
))
.add("5 second timer - Small", () => (
<Timer duration={5} size={50} strokeWidth={4} />
));
// ));
storiesOf("Timer", module)
.add("10 second Timer - Small", () => (
<Timer duration={10} size={50} strokeWidth={4} />
))
.add("5 second timer - Small", () => (
<Timer duration={5} size={50} strokeWidth={4} />
));
storiesOf("Panel", module).add("Panel", () => (
<Panel
info={{ answerString: "Charles Dickens" }}
setSelected={action("selected")}
/>
));
storiesOf("Panel", module).add("Panel", () => (
<Panel
info={{ answerString: "Charles Dickens" }}
setSelected={action("selected")}
/>
));
storiesOf("Panel", module)
.add("Panel", () => (
<Panel
info={{ answerString: "Charles Dickens" }}
setSelected={action("selected")}
/>
))
.add("Selected True Panel", () => (
<Panel
setSelected={action("selected")}
info={{ answerString: "Jodie Foster", selected: true, correct: true }}
/>
))
.add("Selected False Panel", () => (
<Panel
setSelected={action("selected")}
info={{ answerString: "Jodie Foster", selected: true, correct: false }}
/>
));
const answersArray = [
{ answerString: "Herman Melville", selected: false, correct: false },
{ answerString: "William Golding", selected: false, correct: false },
{ answerString: "William Shakespeare", selected: false, correct: false },
{ answerString: "J.R.R. Tolkein", selected: false, correct: true },
];
const questionArray = [{ questionString: "Is this going to work?" }];
storiesOf("PanelList", module)
.add("PanelList of answers", () => <PanelList infoArray={answersArray} />)
.add("PanelList of Question", () => <PanelList infoArray={questionArray} />);
storiesOf("GameplayHeader", module).add("Gameplay Header", () => (
<GameplayHeader questionId="3" />
));
const questionObj = {
questionIndex: 3,
question:
"Who wrote the novel "Moby-Dick"? Its a really important question because Western culture is good for getting jobs duhhhh bro",
correct_answer: "Herman Melville",
incorrect_answers: [
" It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.",
"Will",
"J. R. R. Tolkien",
],
};
storiesOf("Question View", module).add("Active Question View", () => (
<ActiveQuestion
questionObj={questionObj}
questionIndex={3}
timeLimit={30}
audioOn={true}
/>
));
storiesOf("Home View", module).add("Landing Page", () => <Home />);
const playersObj = {
players: [
{ name: "Player_1", score: 0 },
{ name: "Player_2", score: 0 },
{ name: "Player_3", score: 0 },
],
};
const gameId = "FBDEGF";
storiesOf("Dropdown", module).add("Dropdown Menu", () => <Dropdown />);
storiesOf("Waiting Room", module).add("Basic Waiting Room", () => (
<WaitingRoom players={playersObj.players} gameId={gameId} />
));
storiesOf("Waiting Room", module).add("Player List Item", () => (
<PlayerListItem name={"Sam"} playerItem />
));
storiesOf("Waiting Room", module).add("Game Id Item", () => (
<PlayerListItem name={"BEIYCD"} gameIdItem />
));
storiesOf("Waiting Room", module).add("Player List", () => (
<PlayerList players={playersObj.players} />
));
storiesOf("Options Menu", module).add("Option Item list 1", () => (
<OptionItemList
clickHandler={action("clicked!")}
optionsList={[15, 20, 35, 40]}
gameSetting="How many questions?"
/>
));
storiesOf("Options Menu", module).add("Option Item list 2", () => (
<OptionItemList
clickHandler={action("clicked!")}
optionsList={[15, 20, 35, 40]}
gameSetting="How many questions?"
/>
));
storiesOf("Options Menu", module).add("Option Item 3", () => (
<OptionItem gameSetting="Category" clickHandler={action("clicked!")}>
Horses
</OptionItem>
));
storiesOf("Options Menu", module).add("The entire option form", () => (
<OptionsForm />
));
storiesOf("ScoreBoard", module).add("Score List Item", () => <ScoreListItem />);
storiesOf("ScoreBoard", module).add("Score List", () => <ScoreList />);
storiesOf("ScoreBoard", module).add("Score Board", () => <Scoreboard />);
storiesOf("Start Game View", module).add("StartGame", () => <StartGame />);
const victoryPlayers = [
{ name: "player_1", score: 65, pointsEarned: 3, correctAnswer: true },
{ name: "player_1", score: 65, pointsEarned: 3, correctAnswer: true },
{ name: "player_6", score: 65, pointsEarned: 3, correctAnswer: false },
{ name: "player_2", score: 65, pointsEarned: -2, correctAnswer: true },
{ name: "player_3", score: 29, pointsEarned: 1, correctAnswer: false },
{ name: "player_3", score: 29, pointsEarned: 1, correctAnswer: false },
{ name: "player_3", score: 29, pointsEarned: 1, correctAnswer: false },
];
const scoresArray = [65, 45, 29];
// storiesOf("Victory Score Board", module).add("Victory", () => (
// <Scoreboard players={victoryPlayers} time={5} view={"FINISHED"} />
// ));
storiesOf("Score Board", module).add("Victory", () => (
<ScoreList orderedArray={victoryPlayers} scoresArray={scoresArray} />
));
|
import React, { useState, useEffect } from 'react';
import './Home.scss';
import axios from 'axios';
import UrlCard from '../components/UrlCard';
export default function Home() {
// const longUrlRef = useRef();
const [longUrl, setlongUrl] = useState('');
const [urlData, setUrlData] = useState({});
const [loading, setLoading] = useState(false);
const [change, setChange] = useState(false);
const postRequest = async () => {
try {
console.log('hello');
const response = await axios.post('https://ak-surl.herokuapp.com/url', {
longUrl,
});
console.log(response.data);
} catch (error) {
console.log(error);
}
return postRequest;
};
useEffect(() => {
async function fetchData() {
console.log('hello');
axios.get('https://ak-surl.herokuapp.com/url').then((response) => {
// console.log(response.data);
setUrlData(() => response.data);
});
}
fetchData();
setTimeout(() => {
setLoading(true);
}, 1500);
}, [change]);
function handleSubmit(e) {
e.preventDefault();
console.log(longUrl);
postRequest();
setlongUrl('');
setChange(true);
}
function redirect(url) {
console.log(url);
// window.location.replace(url)
window.location.href = url;
}
return (
<div className="container">
<h1 className="title">Url Shortner</h1>
<form onSubmit={handleSubmit} className="input-form">
<input
className="input"
value={longUrl}
onChange={(e) => setlongUrl(e.target.value)}
type="url"
placeholder="Enter Long Url"
/>
</form>
<div className="url-list">
{loading &&
urlData.map((urldata, index) => (
<UrlCard
handleClick={() => redirect(urldata.longUrl)}
data={urldata}
key={index}
/>
))}
</div>
{/* <UrlCard handleClick={tryClick} /> */}
</div>
);
}
|
/**
* API para manipulação Aura através.
*/
var AURA = new function() {
var showLoading = function(theStatus) {
if(theStatus) {
$('#aura-icon').attr('class', 'fa fa-circle-o-notch fa-spin');
} else {
$('#aura-icon').attr('class', 'fa fa-circle-o');
}
};
this.submitOrder = function(theClearInput, theCallback) {
showLoading(true);
$('#auraPainelResposta').html('').slideUp('fast');
$.ajax({
url: "./api/",
context: document.body,
data: $('#formAura').serialize(),
success: function(theData){
showLoading(false);
$('html,body').animate({scrollTop: $("#linhaConsoleAura").offset().top - 60}, 'fast', function() {
$('#auraPainelResposta').html(theData).slideDown('fast');
});
if(theCallback) {
theCallback(theData);
}
},
error: function() {
$('#auraPainelResposta').html("Erro ao enviar ordem. Tente de novo.");
}
});
if(theClearInput == undefined || theClearInput) {
$(':input','#formAura').val('');
}
return false;
};
/**
* Imita a interação humana com o console da aura, colocando o texto
* informado dentro do console e pressionando o botão de enviar.
*/
this.typeConsoleCommand = function(theCommand) {
$(':input','#formAura').val(theCommand);
AURA.submitOrder();
};
this.formatUsingImage = function(theMachines) {
var aImg = prompt('Qual o nome da imagem?');
if(aImg != '') {
AURA.sendCommand('Formate com a imagem "'+aImg+'" ' + theMachines);
}
};
this.runArbitraryCommand = function(theMachines) {
var aCommand = prompt('Qual o comando a ser executado?');
if(aCommand != '') {
AURA.sendCommand('Execute o comando "'+aCommand+'" ' + theMachines);
}
};
/**
* Envia um comando para a Aura, mostrando o resultado desse comando
* como um popup na tela.
*/
this.sendCommand = function(theCommand, theCallback) {
$.ajax({
url: "./api/",
context: document.body,
data: {command: theCommand},
success: function(theData){
if(theCallback) {
theCallback(theData);
} else {
alert(theData);
}
},
error: function() {
alert('Não foi possível executar a ação!');
}
});
};
this.refreshLabsDashboard = function(theIdsLabs) {
var aId = '';
for(var i = 0; i < theIdsLabs.length; i++) {
aId = theIdsLabs[i];
var aFunc = function() {
$.ajax({
url: "ajax-lab-stats.php",
context: document.body,
data: 'lab=' + aId,
success: function(data){
var aReg = /<!-- id: (.*) -->/g;
var aLabId = aReg.exec(data)[1];
$('#lab' + aLabId).fadeOut('fast', function() {
$('#lab' + aLabId).html(data);
$('#lab' + aLabId).fadeIn();
});
},
error: function() {
$('#lab' + aId).html("Erro ao obter dados. Tente recarregar a página.");
}
});
}
aFunc();
setInterval(aFunc, 60000);
}
};
/**
*
*/
this.spyglass = function(theDeviceHash, theDeviceName) {
window.open('spyglass.php?hash=' + theDeviceHash + '&name=' + encodeURIComponent(theDeviceName),'Spyglass','width=1920,height=1200,toolbar=0,menubar=0,location=0');
};
this.init = function() {
$('#formAura').submit(AURA.submitOrder);
};
};
|
import React from 'react';
import * as S from './styled';
import ProjectImage from './ProjectImage/index';
import Strapline from '../../shared/Typography/Strapline';
import Heading from '../../shared/Typography/Heading';
import Button from '../../shared/Button';
function Project({ date, slug, strapline, title, thumbnail }) {
return (
<S.Project href={`/portfolio/${slug}`}>
<S.Header>
<Strapline>{strapline}</Strapline>
<Heading color="blackPearl" type="h4">
{title}
</Heading>
</S.Header>
<S.ImageContainer>
<ProjectImage src={thumbnail} alt={title} />
</S.ImageContainer>
<S.Footer>
<S.Date>{date}</S.Date>
<Button variation="secondary" as="button" tabIndex="-1">
View project
</Button>
</S.Footer>
</S.Project>
);
}
export default Project;
|
$(document).ready(function() {
$('#letter-a a').click(function() {
$('#dictionary').load('a.html');
return false;
});
$('#letter-b a').click(function() {
$.getJSON('b.json');
return false;
});
});
|
import React from 'react'
import {connect} from 'react-redux'
import {Row, Col} from 'react-bootstrap'
import {
compose,
lifecycle,
withHandlers,
branch,
renderNothing
} from 'recompose'
import Table from './components/OrdersTable'
import {getOrdersByCompany} from '../../modules/Companies'
import {cancelOrder} from '../../modules/Orders'
const CompanyAdd = ({handleSubmit, cancelOrder, company, orders}) =>
<div>
<Row bsClass="text-center">
<h3>
My Orders - {company.name}
</h3>
</Row>
<Row>
<Col md={10} mdOffset={1}>
<Table orders={orders} cancelOrder={cancelOrder} />
</Col>
</Row>
</div>
export default compose(
connect(state => ({
company: state.company_orders.company,
orders: state.company_orders.orders
})),
lifecycle({
componentDidMount() {
this.props.dispatch(getOrdersByCompany(this.props.params.id))
}
}),
withHandlers({
cancelOrder: ({dispatch}) => id => dispatch(cancelOrder(id))
}),
branch(props => !props.company, renderNothing)
)(CompanyAdd)
|
//
//
console.log(`Bozo`);
const { body } = document;
const changeBackground = (num) => {
let previousBackground;
if (body.className) {
previousBackground = body.className;
}
body.className = '';
switch (num) {
case '1':
body.classList.add(`background-1`);
break;
case '2':
body.classList.add(`background-2`);
break;
case '3':
body.classList.add(`background-3`);
break;
default:
break;
}
};
|
$(document).ready(function(){
RefreshClick();
printDropdown();
ClearClick();
DropDownDown();
TableCall();
DeleteRow();
});
function ListenSocketNewOld(){
var socket = io(':3000');
socket.on("user-" + thisUserId, function(data){
message = JSON.parse(data);
notify = message.data.data.message;
$.toast({
heading: notify.title,
text: notify.message,
hideAfter: 20000,
icon: notify.type,
showHideTransition: 'slide',
position: { left : 'auto', right : 10, top : 'auto', bottom : 35 },
});
printDropdown();
redrawNotifys();
});
socket.emit('subscribe', "user-" + thisUserId);
}
function ListenSocket(){
var canal = 'user-'+thisUserId;
if(app_env == 'local')
var socket = io(':3000');
else
var socket = io('http://steel4web.com.br:3000');
socket.on(canal, function(data) {
var notify = data.data.data.message;
$.toast({
heading: notify.title,
text: notify.message,
hideAfter: 20000,
icon: notify.type,
showHideTransition: 'slide',
position: { left : 'auto', right : 10, top : 'auto', bottom : 35 },
});
printDropdown();
redrawNotifys();
});
}
function printDropdown(){
$('.notify_menu').find('li').remove().end();
$('.labelNotys').remove().end();
$.ajax({
url: urlbaseGeral+"/notificacoes/listNots",
type: 'GET',
dataType: 'json',
})
.done(function(response) {
$('.labelWrapper').removeClass('faa-ring animated');
if(Object.keys(response).length > 0){
var count = 0;
var len = 0;
var notifys = '';
$.each(response, function (index, el){
if(el.status == 0 || el.status == 1){
len++;
if(count <= 20){
notifys = notifys + '<li id="notx'+el.id+'" class="singleNotify"><a href="'+urlbaseGeral+'/notificacao/'+el.id+'" class="not_read_yet"><i class="fa '+notIcon(el.tipo)+'"></i>'+el.titulo+'<small class="delete_notification pull-right" title="Dispensar Notificação"><i class="fa fa-times"></i></small><small style="font-size:8px"><br>'+diffForHumans(el.created_at,'d/m/y h:i')+' - '+el.autor+'</small></a></li>'
count++;
}
}
});
$.each(response, function (index, el){
if(el.status == 2){
if(count <= 20){
notifys = notifys + '<li id="notx'+el.id+'" class="singleNotify"><a href="'+urlbaseGeral+'/notificacao/'+el.id+'"><i class="fa '+notIcon(el.tipo)+'"></i>'+el.titulo+'<small class="delete_notification pull-right" title="Dispensar Notificação"><i class="fa fa-times"></i></small><small style="font-size:8px"><br>'+diffForHumans(el.created_at,'d/m/y h:i')+' - '+el.autor+'</small></a></li>'
count++;
}
}
});
if(len>0){
$('.labelWrapper').after('<span class="labelNotys label label-info">'+len+'</span>');
$('.labelWrapper').addClass('faa-ring animated');
}
$('.notify_menu').append(notifys);
$.ajax({
url: urlbaseGeral+"/notificacoes/status",
type: 'POST',
dataType: 'html',
data: {all: true, listed: true}
})
}else{
$('.notify_menu').append('<li style="text-align:center"><a href="#">Você não tem notificações</a></li>');
}
})
}
function notIcon(type) {
switch (type) {
case 'success':
return 'fa-check text-green';
break;
case 'error':
return 'fa-exclamation-triangle text-red';
break;
case 'warning':
return 'fa-exclamation text-yellow';
break;
case 'info':
return 'fa-info-circle text-aqua';
break;
default:
return 'fa-flag';
break;
}
}
if (!Object.keys) {
Object.keys = function (obj) {
var arr = [],
key;
for (key in obj) {
if (obj.hasOwnProperty(key)) {
arr.push(key);
}
}
return arr;
};
}
function RefreshClick(){
$('#limparNotifys').off();
$(document).on('click', '#limparNotifys', function(event) {
$.ajax({
url: urlbaseGeral+"/notificacoes/clear",
type: 'POST',
dataType: 'html',
data: {clear: true},
success: function(result){
printDropdown();
redrawNotifys();
}
})
event.stopPropagation();
});
}
function ClearClick(){
$('.delete_notification').off();
$(document).on('click', '.delete_notification', function(event) {
event.preventDefault();
var ind = $(this).closest('.singleNotify').attr('id');
var ids = ind.split('x');
var id = ids[1];
$.ajax({
url: urlbaseGeral+"/notificacoes/delete",
type: 'POST',
dataType: 'html',
data: {id: id},
success: function(result){
printDropdown();
redrawNotifys();
}
})
// }).done(function() {
// $('.notify_dropdown').dropdown('toggle');
// });
// dd('evento coisou');
event.stopPropagation();
});
}
function DropDownDown(){
$('.notifications-menu').off();
$(document).on('hidden.bs.dropdown', '.notifications-menu', function(event) {
$.ajax({
url: urlbaseGeral+"/notificacoes/status",
type: 'POST',
dataType: 'html',
data: {all: true},
success: function(result){
$('.labelWrapper').removeClass('faa-ring animated');
$('.singleNotify').find('a').removeClass('not_read_yet');
$('.labelNotys').remove();
}
})
});
}
function DeleteRow(){
$(document).on('click', '.deleteListedNotify', function(event) {
event.preventDefault();
var ind = $(this).attr('id');
var ids = ind.split('R');
var id = ids[1];
$.ajax({
url: urlbaseGeral+"/notificacoes/delete",
type: 'POST',
dataType: 'html',
data: {id: id},
success: function(result){
printDropdown();
redrawNotifys();
flashSuccess('Notificação Excluida com Sucesso!');
}
})
});
}
function TableCall(){
return $('#NotifyTable').DataTable({
ajax: {
type: 'GET',
url: urlbaseGeral+"/notificacoes/getNots",
},
responsive: true,
columns: [
{ "data": "icon" },
{ "data": "title"},
{ "data": "msg" },
{ "data": "date" },
{ "data": "autor" },
{ "data": "action" },
],
"iDisplayLength": 100,
"retrieve": true,
"ordering": false
});
}
function redrawNotifys(){
var table = TableCall();
table.ajax.url(urlbaseGeral+"/notificacoes/getNots").load();
}
// $(document).ready(function() {
// Pusher.log = function(message) {
// if (window.console && window.console.log) {
// window.console.log(message);
// }
// };
// var pusher = new Pusher('a39f21ceccb5ed40d1b7', {
// encrypted: true
// });
// // Pusher.channel_auth_endpoint = '/presence_auth.php';
// console.log(thisUserId);
// var channel = pusher.subscribe("user-" + thisUserId);
// channel.bind('my_event', function(data) {
// console.log(data);
// $('.notBox').addClass(data.type);
// $('.notText').html(data.message);
// $('.notTitle').html(data.title);
// $('.notBox').fadeIn(400);
// });
// });
// this.socket.on("user-" + thisUserId + ":App\\Events\\Eventname", function(data){
// console.log(data);
// $('.notBox').addClass(data.type);
// $('.notText').html(data.message);
// $('.notTitle').html(data.title);
// $('.notBox').fadeIn(400);
// });
// var sockete = io.connect('http://localhost:8890');
// //socket.on('connect', function(data){
// // socket.emit('subscribe', {channel:'score.update'});
// //});
// sockete.on('user', function (data) {
// //Do something with data
// console.log('Score updated: ', data);
// });
|
import { useState } from "react"
import { useDispatch } from "react-redux"
import { useHistory } from "react-router"
import WorkHistoryMultiRow from './FormComponents/WorkHistoryMultiRow'
import ImageUploader from "../ImageComponents/ImageUploader";
import {Button, Select, MenuItem, Typography} from '@material-ui/core'
import { useSelector } from "react-redux";
import RegistrationStepper from './Stepper'
function WorkHistory() {
const dispatch = useDispatch();
const history = useHistory();
// boolean state for if a resume has been submitted, for form validation
const [resumeSubmitted, setResumeSubmitted] = useState(false)
// use selector for work history items, this could be used to render upon submit
const workHistoryItems = useSelector(store => store.workHistoryReducer)
// state variable for years of experience, default to -, set upon handleNext and for validated
const [yearsExperience, setYearsExperience] = useState('-');
// state array on which work history sub components are rendered,
//once a subform is submitted, this counts up by one, rendering a new subform
const [amountOfWorkHistories, setAmountOfWorkHistories] = useState([1])
// increases the amount of work history elements in the array above
function addWorkHistoryItem() {
// keyForWorkHistoryMultiRow++
setAmountOfWorkHistories(amountOfWorkHistories =>
[...amountOfWorkHistories, amountOfWorkHistories.length + 1])
}
// sets years of experience based on select
function handleChange(e) {
setYearsExperience(e.target.value)
}
// passed down as props to image uploader, to be triggered upon attach button click, see ImageUploader.jsx
function handleImageAttach(awsKey) {
setResumeSubmitted(true)
}
/**
* Passed down to stepper, upon pressing next, form validate, then send dispatches as below
* once dispatches are complete, send user to next page
* @returns
*/
async function handleNext() {
if(yearsExperience === '-') {
return alert('Please enter years of experience')
}
if (resumeSubmitted === false) {
return alert('Please attach your resume')
}
if (amountOfWorkHistories.length === 1) {
return alert('Please add at least one work history item')
}
// send dispatch with just years of experience
await dispatch({
type: 'PUT_WORK_HISTORY',
payload: {
yearsExperience: yearsExperience,
}
})
// send a dispatch to post all work histories from the reducer
await dispatch({
type: 'POST_WORK_HISTORY_ITEMS',
payload: workHistoryItems
})
// send user to next page
history.push('/missionhistory')
}
// props for imageUploader. only declaring these here for visibility
const resume = 'resume'
const dispatchText = 'POST_RESUME'
const DBdispatchText = 'POST_RESUME_TO_DB'
// props for stepper
const activeStep = 2
return (
<div>
<Typography variant="h4" className="registration-title">Work History</Typography>
<hr></hr>
<Typography variant="subtitle1" className="registration-title-subheading">Submit Your Resume</Typography>
{/* takes in props above the return, and the submitResumeFunction */}
<ImageUploader imageType={resume} dispatchText={dispatchText} DBdispatchText={DBdispatchText} imageSubmitted={resumeSubmitted} attachImageFunction={handleImageAttach}/>
<br></br>
<div className="text-field-wrapper">
<div className="text-field-wrapper">
<Typography variant="body1" htmlFor="yearsExperienceInput">Years of experience</Typography>
</div>
<Select variant="outlined" value={yearsExperience} name="yearsExperience" id="yearsExperienceInput" onChange={handleChange}>
<MenuItem value="-">-</MenuItem>
<MenuItem value="1-2">1-2</MenuItem>
<MenuItem value="2-3">2-3</MenuItem>
<MenuItem value="3-5">3-5</MenuItem>
<MenuItem value="5-10">5-10</MenuItem>
<MenuItem value="10-15">10-15</MenuItem>
<MenuItem value="15-20">15-20</MenuItem>
<MenuItem value="20+">20+</MenuItem>
</Select>
</div>
<Typography variant="h5" className="registration-title-subheading">Add Work History</Typography>
{/* maps a state array to render relevant number of work history forms */}
{amountOfWorkHistories.map((history, i )=> {
return (
<WorkHistoryMultiRow key={i} addWorkHistoryItem={addWorkHistoryItem} /> // key={keyForWorkHistoryMultiRow} https://reactjs.org/docs/lists-and-keys.html
)
})}
{/* <Button variant="contained" color="primary" disabled={!workHistorySubmitted ? true : false} onClick={handleNext}> Next </Button> */}
<div>
<RegistrationStepper activeStep={activeStep} submitFunction={handleNext} />
</div>
{/* stepper goes here with props of which page */}
</div>
)
}
export default WorkHistory
|
const mongoose = require('mongoose')
const BlogModel = require('../models/Blog')
exports.getNewId = () => {
return new Promise(async (resolve, reject) => {
await BlogModel.find({ id: { $gt: 0 } }).sort({ id: -1 }).then(([first, ...others]) => {
resolve(first ? first.id + 1 : 1)
})
})
}
exports.addBlog = (blog) => {
return new Promise((resolve, reject) => {
blog.save((err, data) => {
if (err) {
console.log('addBlog error', err)
reject(err)
} else {
console.log('addBlog success', data)
resolve(data)
}
})
})
}
exports.getAll = (page = 1, pageSize = 10) => {
return new Promise(async (resolve, reject) => {
try {
let total = await BlogModel.count({})
await BlogModel.find({})
.skip((page - 1) * pageSize)
.limit(pageSize)
.sort({ createAt: -1 })
.exec((err, data) => {
resolve({
list: data,
total: total,
page: page,
pageSize: pageSize
})
})
} catch (error) {
reject(error)
}
})
}
exports.getBolg = (obj) => {
return new Promise(async (resolve, reject) => {
try {
await BlogModel.find(obj)
.exec((err, data) => {
resolve(data)
})
} catch (error) {
reject(error)
}
})
}
|
export {
Set,
GetRect,
GetRects,
GetRecti,
Draw,
Recter,
DrawCrossline,
CanvasClick,
Drag,
StopDrag,
Del,
GetResult,
Clear,
LoadRects,
CursorStyle
}
var minwidth = 2
var minheight = 2
var rect = null
var rects = []
function LoadRects (loadrects) {
rects = loadrects
}
function Set (w, h) {
minwidth = w
minheight = h
}
function GetRect () {
return rect
}
function GetRects () {
return rects
}
function GetRecti (i) {
if (i > -1 && i < rects.length) {
return rects[i]
} else if (i < 0 && i + rects.length >= 0) {
return rects[i + rects.length]
} else {
return null
}
}
function Dis (x, y, x1, y1) {
return Math.sqrt((x - x1) * (x - x1) + (y - y1) * (y - y1))
}
function RectDrag (x, y, rect, radius) {
if (Dis(x, y, rect.x, rect.y) < radius) {
return 1
}
if (Dis(x, y, rect.x, rect.y + rect.height) < radius) {
return 3
}
if (Dis(x, y, rect.x + rect.width, rect.y) < radius) {
return 2
}
if (Dis(x, y, rect.x + rect.width, rect.y + rect.height) < radius) {
return 4
}
return 0
}
// 矩形生成
function Recter (x, y, width, height, color) {
this.x = x
this.y = y
this.width = width
this.height = height
this.color = color
}
function DrawCrossline (ctx, x, y, w, h, strokestyle) {
ctx.beginPath()
ctx.strokeStyle = strokestyle
ctx.moveTo(x, 0)
ctx.lineTo(x, h)
ctx.stroke()
ctx.moveTo(0, y)
ctx.lineTo(w, y)
ctx.stroke()
}
function Draw (ctx, rect, strokestyle, fillstyle, linewidth, radius, rate, scalei) {
if (rect === null) {
return false
}
ctx.lineWidth = linewidth
ctx.strokeStyle = strokestyle
ctx.beginPath()
ctx.fillStyle = strokestyle
ctx.arc(rect.x * scalei, rect.y * scalei, radius, 0, 2 * Math.PI)
ctx.stroke()
ctx.fill()
ctx.closePath()
ctx.beginPath()
ctx.fillStyle = strokestyle
ctx.arc(rect.x * scalei + rect.width * scalei, rect.y * scalei, radius, 0, 2 * Math.PI)
ctx.stroke()
ctx.fill()
ctx.closePath()
ctx.beginPath()
ctx.fillStyle = strokestyle
ctx.arc(rect.x * scalei + rect.width * scalei, rect.y * scalei + rect.height * scalei, radius, 0, 2 * Math.PI)
ctx.stroke()
ctx.fill()
ctx.closePath()
ctx.beginPath()
ctx.fillStyle = strokestyle
ctx.arc(rect.x * scalei, rect.y * scalei + rect.height * scalei, radius, 0, 2 * Math.PI)
ctx.stroke()
ctx.fill()
ctx.closePath()
ctx.beginPath()
ctx.fillStyle = fillstyle
ctx.rect(rect.x * scalei, rect.y * scalei, rect.width * scalei, rect.height * scalei)
ctx.stroke()
ctx.fill()
}
function IsPointInRecti (x, y, i, radius) {
if ((x > rects[i].x && x < rects[i].x + rects[i].width && y > rects[i].y && y < rects[i].y + rects[i].height) || RectDrag(x, y, rects[i], radius) > 0) {
return true
}
return false
}
function IsPointInRect (x, y, radius) {
var select = -1
var dragrect = 0
for (var i = rects.length - 1; i >= 0; i--) {
if ((x > rects[i].x && x < rects[i].x + rects[i].width && y > rects[i].y && y < rects[i].y + rects[i].height) || RectDrag(x, y, rects[i], radius) > 0) {
select = i
dragrect = RectDrag(x, y, rects[i], radius)
break
}
}
return {
select: select,
dragrect: dragrect
}
}
// 依据点击位置进入不同操作模式 1.移动矩形 2.更改矩形 3.新建矩形
function CanvasClick (x, y, radius, res) {
var dragres = IsPointInRect(x, y, radius)
var dragrect = dragres.dragrect
var i = dragres.select
if (res !== null && res.i > -1 && IsPointInRecti(x, y, res.i, radius)) {
i = res.i
dragrect = RectDrag(x, y, rects[i], radius)
}
return {
x: x,
y: y,
// 存储以便drag
x0: x,
y0: y,
dragrect: dragrect,
i: i
}
}
// 拖拽动作,从(x0,y0)到(x,y),依据点击事件选择不同动作
function Drag (x, y, color, res) {
var i = res.i
var drag = res.dragrect
// 移动矩形
if (i > -1 && drag === 0) {
rects[i].x = rects[i].x + x - res.x0
rects[i].y = rects[i].y + y - res.y0
}
// 修改矩形
if (i > -1 && drag > 0) {
if (drag === 1) {
rects[i].width = rects[i].x + rects[i].width - x
rects[i].x = x
rects[i].height = rects[i].y + rects[i].height - y
rects[i].y = y
// window.cursor.style = 'e-move'
} else if (drag === 2) {
rects[i].width = x - rects[i].x
rects[i].height = rects[i].y + rects[i].height - y
rects[i].y = y
} else if (drag === 3) {
rects[i].height = y - rects[i].y
rects[i].width = rects[i].x + rects[i].width - x
rects[i].x = x
rects[i].y = y - rects[i].height
} else if (drag === 4) {
rects[i].width = x - rects[i].x
rects[i].height = y - rects[i].y
}
}
// 新建矩形
if (i < 0) {
var rx, ry
var x0 = res.x
var y0 = res.y
rx = x > x0 ? x0 : x
ry = y > y0 ? y0 : y
if (Math.abs(x - x0) >= minwidth && Math.abs(y - y0) >= minheight) {
rect = new Recter(rx, ry, Math.abs(x - x0), Math.abs(y - y0), color)
}
}
res.x0 = x
res.y0 = y
}
function CursorStyle (x, y, angle, radius, selectres) {
var res = IsPointInRect(x, y, radius)
if (selectres && selectres.i > -1 && IsPointInRecti(x, y, selectres.i, radius)) {
res.i = selectres.i
res.dragrect = RectDrag(x, y, rects[selectres.i], radius)
}
if (res.select > -1 && res.dragrect === 0) {
return 'move'
}
if (res.dragrect === 0) {
return 'crosshair'
} else if (res.dragrect === 1) {
if (angle === 0 || angle === 2) {
return 'se-resize'
} else {
return 'sw-resize'
}
} else if (res.dragrect === 2) {
if (angle === 0 || angle === 2) {
return 'sw-resize'
} else {
return 'se-resize'
}
} else if (res.dragrect === 3) {
if (angle === 0 || angle === 2) {
return 'ne-resize'
} else {
return 'nw-resize'
}
} else if (res.dragrect === 4) {
if (angle === 0 || angle === 2) {
return 'nw-resize'
} else {
return 'ne-resize'
}
} else {
return 'auto'
}
}
function StopDrag (res) {
if (rect !== null) {
rects.push(rect)
rect = null
return true
}
if (res === null) {
// nothing
} else {
var i = res.i
if (i > -1 && rects[i].width < 0) {
rects[i].x = rects[i].x + rects[i].width
rects[i].width = Math.abs(rects[i].width)
}
if (i > -1 && rects[i].height < 0) {
rects[i].y = rects[i].y + rects[i].height
rects[i].height = Math.abs(rects[i].height)
}
}
return false
}
function Del (res) {
var i = res.i
if (i > -1) {
rects.splice(i, 1)
}
}
function GetResult (rate) {
var res = []
// var rectpoint = []
for (var i = 0; i < rects.length; i++) {
var newrect = new Recter(rects[i].x * rate, rects[i].y * rate, rects[i].width * rate, rects[i].height * rate, rects[i].color)
res.push(newrect)
// var pt1 = new Pointer(rects[i].x * rate, rects[i].y * rate)
// var pt2 = new Pointer(rects[i].x + rects[i].width, rects[i].y + rects[i].height)
// rectpoint.push(pt1)
// rectpoint.push(pt2)
// res.push(rectpoint)
}
return res
}
function Clear () {
rects = []
}
|
import { BaseEvent } from "./BaseEvent";
export class Event extends BaseEvent {
constructor(id, title, time, contentPath, contentSavePath, deletePath, imageUploadPath, privacy, fileUploadPath) {
super(title, time);
this.id = id;
this.private = privacy;
this.contentPath = contentPath;
this.contentSavePath = contentSavePath;
this.imageUploadPath = imageUploadPath;
this.fileUploadPath = fileUploadPath;
this.deletePath = deletePath;
}
static copyEvent(event) {
return new Event(
event.id,
event.title,
new Date(event.time.getTime()),
event.contentPath,
event.contentSavePath,
event.deletePath,
event.imageUploadPath,
event.private,
event.fileUploadPath
);
}
}
|
/**
* @file: loginFormInput.js
* @description: Handles all the login form using formik (a third paty library)
*/
import React from 'react';
import {View, StyleSheet, Dimensions, useColorScheme} from 'react-native';
//CONSTANTS
import {isMobileWeb} from '../../../constants/constants';
//REDUX
import {useDispatch} from 'react-redux';
import {LogInAction} from '../../../redux/actions/authAction';
//THEME
import {useTheme} from '@react-navigation/native';
//THIRD PARTY FORM MODULE
import {Formik} from 'formik';
//PARTS
import LoginUsernameInput from './loginUsernameInput/loginUsernameInput';
import LoginPasswdInput from './loginPasswdInput/loginPasswdInput';
import LoginSubmitButton from './loginSubmitButton/loginSubmitButton';
import ErrorMessage from './errorMessage/errorMessage';
const LoginFormInput = ({dimensions}) => {
//GLOBAL VARIABLES
const theme = useTheme();
const schema = useColorScheme();
//REDUX
const dispatch = useDispatch();
//ERROR HANDLER
const [error, setError] = React.useState('');
//INLINE STYLES
const inputContainerInline = {
width: dimensions.window.width / (isMobileWeb ? 1.8 : 4.4),
height: Dimensions.get('window').height / 18,
};
const textInputContainerInline = {
borderColor: schema === 'dark' ? theme.colors.notification : '#D0D0D0',
width: dimensions.window.width / (isMobileWeb ? 1.8 : 4.4),
height: Dimensions.get('window').height / 18,
};
const textInputInline = {
width: dimensions.window.width / (isMobileWeb ? 2.2 : 5.4),
color: theme.colors.background,
};
const securyEntryInline = {
width: dimensions.window.width / 20,
};
/**
* @function loginPost
* @param {String} url
* @param {Object} data
*
* @description: Calls node in order to Login, and handles the response. If the response is
* positive calls to redux in order to keep the token in async storage. If not shows an error
* message.
*
*/
const loginPost = async function postData(url, data) {
// Default options are marked with *
const response = await fetch(url, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: data.email,
passwd: data.passwd,
}),
}).then((e) => {
if (e.status === 200) {
setError('');
e.json().then((json) => {
dispatch(LogInAction(json.access_token));
});
} else if (e.status === 401) {
setError('Usuario o contraseña no válidos');
} else {
setError('Algo ha ido mal. Vuelve a intentarlo en unos minutos.');
}
});
return response;
};
return (
<Formik
initialValues={{username: '', passwd: ''}}
onSubmit={(values) => {
loginPost('http://localhost:4001/auth/login', {
email: values.username,
passwd: values.passwd,
});
}}>
{({handleChange, handleBlur, handleSubmit, values}) => (
<View style={styles.container}>
<ErrorMessage error={error} dimensions={dimensions} />
{/* USERNAME */}
<LoginUsernameInput
inputContainerInline={inputContainerInline}
textInputInline={textInputInline}
textInputContainerInline={textInputContainerInline}
handleChange={handleChange}
handleBlur={handleBlur}
value={values.username}
theme={theme}
/>
{/* PASSWD */}
<LoginPasswdInput
inputContainerInline={inputContainerInline}
textInputInline={textInputInline}
textInputContainerInline={textInputContainerInline}
handleChange={handleChange}
handleBlur={handleBlur}
value={values.passwd}
theme={theme}
securyEntryInline={securyEntryInline}
/>
{/* SUBMIT BUTTON */}
<LoginSubmitButton
handleSubmit={handleSubmit}
dimensions={dimensions}
/>
</View>
)}
</Formik>
);
};
const styles = StyleSheet.create({
container: {
flex: 0.6,
justifyContent: 'flex-start',
},
//REACT ICONS
icon: {
alignSelf: 'center',
},
});
export default LoginFormInput;
|
import Player from './player';
import Platform from './platform';
class Game {
constructor() {
this.player = null;
this.platforms = [];
this.count = 30;
}
add(object) {
if (object instanceof Player) {
this.player = object;
} else if(object instanceof Platform) {
this.platforms.push(object);
} else {
throw 'unknown type of object';
}
}
allObjects() {
return [].concat(this.player, this.platforms);
}
addPlatform() {
const platform = new Platform({ game: this });
this.add(platform);
return platform;
}
addStartingPlatforms() {
}
addPlayer() {
const player = new Player({ game: this });
this.add(player);
return player;
}
onPlatform() {
this.player.setMaxHeight(this.platforms[0]);
}
draw(ctx) {
ctx.clearRect(0, 0, Game.DIM_X, Game.DIM_Y);
ctx.fillStyle = Game.BG_COLOR;
ctx.fillRect(0, 0, Game.DIM_X, Game.DIM_Y);
this.allObjects().forEach((object) => {
object.draw(ctx);
});
}
moveObjects() {
this.allObjects().forEach((object) => {
if (object instanceof Player) {
this.onPlatform();
object.vel[1] = object.vel[1] += 1.5;
}
object.move();
});
}
step() {
this.moveObjects();
}
}
Game.BG_COLOR = "#000000";
Game.DIM_X = 1000;
Game.DIM_Y = 600;
export default Game;
|
import React, { Component } from 'react';
import './App.css';
class Preview extends Component {
render = () => {
let myFontStyle = "normal"
let myStyle = {
height: "100vh",
width: "50vh",
padding: "30px",
fontStyle: myFontStyle
}
return (
<div style={myStyle}>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla sollicitudin sem et ante luctus sodales. Vivamus mi eros, fringilla et felis vitae, efficitur efficitur justo. Praesent dolor mauris, ultrices vel justo ac, sagittis
</div>
);
}
}
export default Preview;
|
db.movies.updateOne({title:"Batman"},{$set:{imdbRating:7.7}});
|
//url for fetches
// export const BASE_URL = 'http://localhost:3000'
export const BASE_URL = 'https://basketapp-api.herokuapp.com'
|
const sass = require('gulp-sass');
module.exports = function() {
return gulp.src(atPaths.atSass[0].sassSrc)
.pipe(sass())
.pipe(gulp.dest(atPaths.atSass[0].sassDist));
};
|
const fs = require('fs').promises;
const puppeteer = require('puppeteer');
const getPageListingData = require('./scrapListing');
const writeDataToExcel = require('./writeToExcel');
async function createInstance() {
const browser = await puppeteer.launch({
// headless: false, // uncomment to see the browser in action
});
const pages = await browser.pages();
const page = pages[0];
await page.goto("https://www.city24.ee/en/", { waitUntil: "networkidle2" });
await searchTerms(page);
const searchResults = await paginateResults(page);
await writeDataToExcel(searchResults);
await browser.close();
}
/**
* reads search terms from json file and populates in page
* @param {Page} page
*/
async function searchTerms(page) {
const search = JSON.parse(await fs.readFile('./searchTerms.json'));
console.log(search);
await page.$eval('#display_text', (el, search) => el.value = search.address, search);
await page.click('#display_text');
const roomsOptions = await page.$$(".rooms-select a");
search['#rooms'].forEach(room => {
roomsOptions[room - 1].click();
});
await page.$eval('.searchButton', el => el.click());
await page.waitForNavigation({ waitUntil: 'networkidle2' });
}
/**
* Iterates over all the links in current page and scraps it
* using scrapeListing.js
* @param {Page} page the current page for dashboard
* @returns {JSON[]} Array containing details of the each post within
* value attrib
*/
async function paginateResults(page) {
let results = [];
let noNextPage;
do {
let urlArray = await page.$$eval('.new.result.regular .addressLink', (aTags) => {
return aTags.map((a) => $(a).attr('href'));
});
console.log("str len", urlArray.length);
results = [...results, await getPageListingData(urlArray)].flat();
console.log(results.length);
// change the page
noNextPage = await page.$('.next.disabled');
if (!noNextPage) {
await Promise.all([
page.waitForNavigation(), // The promise resolves after navigation has finished
page.click('.next'), // Clicking the link will indirectly cause a navigation
]);
}
} while (!noNextPage);
return results;
}
createInstance();
/**
* @typedef Page
* @type {import('puppeteer').Page}
*/
|
const models= require('../models');
const jwt = require('jsonwebtoken');
module.exports = {
isAuth : function (req, res, next) {
jwt.verify(req.headers.authentication, 'shhhhh', function (err, decoded) {
if (err) {
res.send({
'status': err
})
} else {
next()
}
})
},
isAdmin : function (req, res, next) {
jwt.verify(req.headers.authentication, 'shhhhh', function (err, decoded) {
models.User.findOne({
where: {
email: decoded.user
}
}).then(function (user) {
if (user.role === 'admin') {
next()
} else {
res.send({
status: 'bukan admin'
})
}
})
})
}
}
|
let istrue = true;
console.log(!!istrue);
let isfase = 0;
console.log(!!"")
console.log(!! NaN)
console.log(!!null)
console.log(!!(isfase = false))
|
const fs = require('fs');
const Discord = require('discord.js');
const { prefix, token } = require('./config.json');
const usernameCacheFunction = require('./update-username-cache')
const client = new Discord.Client();
client.commands = new Discord.Collection();
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
}
const cooldowns = new Discord.Collection();
client.once('ready', () => {
console.log('Ready!');
usernameCacheFunction(client)
});
// const list = client.guilds.cache.get("803429347750576138");
// console.log(list.members.cache.array());
// Go through each of the members, and console.log() their name
// list.members.fetch().then(members => console.log(members))
const cron = require('cron');
let counter = 0
let scheduledMessage = new cron.CronJob('* 0 * * * *', () => {
// This runs every day at 10:30:00, you can do anything you want
usernameCacheFunction(client)
console.log('cache updated ' + Date());
});
// When you want to start it, use:
scheduledMessage.start()
client.on(
'message', message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(' ');
const commandName = args.shift().toLowerCase();
const command = client.commands.get(commandName)
|| client.commands.find(cmd => cmd.aliases && cmd.aliases.includes(commandName));
if (!command) return;
if (command.args && !args.length) {
return message.channel.send(`You didn't provide any arguments, ${message.author}!`);
}
try {
command.execute(message, args);
} catch (error) {
console.error(error);
message.reply('there was an error trying to execute that command!');
}
});
client.login(token);
|
import React, {Component} from 'react'
import axios from 'axios'
import Product from './Product'
import ProductForm from './ProductForm'
import update from 'immutability-helper'
import '../semantic-dist/semantic.css'
class ProductsContainer extends Component{
constructor(props){
super(props)
this.state = {
products: [],
images: [],
editingProductId: null
}
}
componentDidMount(){
axios.get('https://stormy-headland-47707.herokuapp.com/api/v1/products.json').then(
response => {
console.log(response)
this.setState({products: response.data})
}).catch(error => {
console.log(error)
})
}
handleProductUpVote = (productId) =>{
const nextProducts = this.state.products.map((product) => {
if (product.id === productId) {
return Object.assign({}, product, {
votes: product.votes + 1,
});
} else {
return product;
}
});
this.setState({
products: nextProducts,
});
}
addNewProduct = () => {
axios.post(
`https://stormy-headland-47707.herokuapp.com/api/v1/products`,
{ product:
{
title: '',
description: '',
productImageUrl: '',
submitterAvatarUrl: ''
}
}
).then(response => {
console.log(response)
const products = update(this.state.products, {
$splice: [[0,0,response.data]]
})
this.setState({
products: products,
editingProductId: response.data.id
})
}).catch(error => {
console.log(error)
})
}
updateProduct = (product) => {
const productIndex = this.state.products.findIndex(x => x.id === product.id)
const products = update(this.state.products,{
[productIndex]: { $set: product }
})
this.setState({products: products})
}
reset = () => {
{this.setState({notification: ''})}
}
enableEditing = (id) => {
this.setState({editingProductId: id})
}
delete = (id) => {
axios.delete(
`https://stormy-headland-47707.herokuapp.com/api/v1/products/${id}`
).then(response => {
const productIndex = this.state.products.findIndex(x => x.id === id)
const products = update(this.state.products, {
$splice: [[productIndex, 1]]
})
this.setState({products: products})
}).catch(error => {
console.log(error)
})
}
render() {
const products = this.state.products.sort((a, b) => (
b.votes - a.votes
));
const productComponents = products.map((product) => (
<Product
key={'product-' + product.id}
id={product.id}
title={product.title}
description={product.description}
url={product.url}
votes={product.votes}
submitterAvatarUrl={product.submitterAvatarUrl}
productImageUrl={product.productImageUrl}
onClick={this.enableEditing}
onDelete={this.delete}
onVote={this.handleProductUpVote}
/>
));
return (
<div className='ui unstackable items'>
{productComponents}
<span className="notified">{this.state.notification}</span>
{this.state.products.map((product) => {
if(this.state.editingProductId === product.id){
return(<ProductForm product={product} key={product.id} updateProduct={this.updateProduct}
reset={this.reset}/>)
}
})}
</div>
);
}
}
export default ProductsContainer
|
//core
import { Button, Image, StatusBar, StyleSheet, Text, TouchableOpacity, View } from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { BottomSocial } from '../Components/BottomSocial';
import { LinearGradient } from 'expo-linear-gradient';
import React from 'react';
import style from '../Style';
//style
export default class PageInitiale extends React.Component {
constructor(props) {
super(props);
}
async componentDidMount() {
const token = await AsyncStorage.getItem("@token");
console.log('token: ', token);
if(token != null)
this.props.navigation.navigate('BottomTabs');
}
render() {
return (
<View style={style.view_top}>
<StatusBar backgroundColor='#FF8787A2' barStyle="light-content" />
<Image source={require("../assets/logo_large.png")} style={style.logo} />
<View style={style.button}>
<TouchableOpacity
style={style.sign}
onPress={() => { this.props.navigation.navigate('Connexion') }}
>
<LinearGradient
colors={['#FF8787', '#f39a9a']}
style={style.sign}
>
<Text style={[style.textSign, { color: '#fff' }]}>Connexion</Text>
</LinearGradient>
</TouchableOpacity>
</View>
<View style={style.button}>
<TouchableOpacity
style={style.sign}
onPress={() => { this.props.navigation.navigate('Inscription') }}
>
<LinearGradient
colors={['#FF8787', '#f39a9a']}
style={style.sign}
>
<Text style={[style.textSign, { color: '#fff' }]}>Inscription</Text>
</LinearGradient>
</TouchableOpacity>
</View>
<BottomSocial />
</View>
)
}
}
/*
const styles = StyleSheet.create({
button: {
alignItems: 'center',
width: "50%",
borderRadius: 10,
marginBottom: 15,
marginTop: 15
},
sign: {
width: '100%',
height: 40,
justifyContent: 'center',
alignItems: 'center',
borderRadius: 10
},
textSign: {
fontSize: 18,
fontWeight: 'bold',
width: '100%',
textAlign: 'center'
}
});
*/
|
import React from 'react';
import SideNav from '../SideNav/SideNav.js';
import './Nav.scss';
class Nav extends React.Component {
sideNavToggle() {
const sideNav = document.getElementById('side-nav');
sideNav.classList.toggle('hidden');
}
render() {
return (
<nav id='nav'>
<a href='#work-section' className='nav-links'>
.work()
</a>
<a href='#skills-section' className='nav-links'>
.skills()
</a>
<h1>
<a id='logo' href='/'>ls</a>
</h1>
<a href='#about-section' className='nav-links'>
.about()
</a>
<a href='#contact-section' className='nav-links'>
.contact()
</a>
<span className="material-icons burger-icon" onClick={this.sideNavToggle}>
menu
</span>
<SideNav />
</nav>
);
}
}
export default Nav;
|
import BsInput from 'ember-bootstrap/components/bs-form/element/control/input';
export default BsInput.extend({
didInsertElement() {
this._super(...arguments);
if (this.autofocus) {
this.element.focus();
}
},
});
|
//年度議價協議主檔json全域變數
var BPA;
//特殊合約明細json全域變數
var BPCDetail;
//特殊合約明細搜尋結果json全域變數
var BPCDetailResult;
//綠色採購選項全域變數
var GreenOption = $('<div>');
//供應商
var supplies;
$(function () {
setFieldStatus($('#P_CurrentStep').val(), $('#P_Status').val());
$(document).on(
{
mouseenter:
function () {
$(this).find('#DeleteThisDetail').show();
},
mouseleave:
function () {
$(this).find('#DeleteThisDetail').hide();
}
},
"#bpaDetail tbody"
)
//取得後端Model
BPA = getModel();
//取得綠色採購
getGreenCategory();
//若CID存在,則直接帶入資料,不重新查詢核可的供應商清單(因為特殊合約會隨著時間推移而過期,變成不核可的供應商)
supplies = BPA.FormStatus != 0 ? getExistSupplies() : getSupplies();
//Edit or Create頁面處理
loadFormData();
//聯絡人onchange事件
$('#ContactPerson').change(function () {
BPA.ContactPerson = $(this).val();
});
//聯絡人郵件地址onchange事件
$('#ContactEmail').change(function () {
BPA.ContactEmail = $(this).val();
});
//採購備註onchange事件
$('#PurchaseRemark').change(function () {
BPA.PurchaseRemark = $(this).val();
});
//供應商發票地點onchange事件
$('#invoiceAddress').change(function () {
BPA.VendorSiteId = $(this).val();
BPA.VendorSiteName = $(this).find('option:selected').text();
});
//全選特殊合約明細
$('#contractDetailAll').change(function () {
$('.contractDetail').prop('checked', $(this).prop('checked'));
});
//年度議價明細刪除
$(document).on('click', '#bpaDetail .icon-cross', function () {
if (BPA.YearlyContractDetailList.length > 1) {
var check = confirm('請確認是否刪除?');
if (check == true) {
//var tr = $(this).closest('tr');
var tr = $(this).parents('tr');
var CDID = tr.attr('id');
$.each(BPA.YearlyContractDetailList, function (index, element) {
if (element.CDetailID == CDID && !element.IsDelete) {
if (element.YCDetailID == 0) {
BPA.YearlyContractDetailList.splice(index, 1);
}
else {
element.IsDelete = true;
element.DeleteBy = BPA.FillInEmpNum;
}
return false;
}
});
BPCDetail.splice(tr.index(), 1);
tr.remove();
$('#bpaDetail').find('tr').find('td:first').each(function (index) {
$(this).text(index + 1);
});
}
}
else {
alertopen("無法再進行刪除!")
}
});
//移除特殊合約 or 供應商
$(document).on('click', '.glyphicon-remove', function () {
//var divID = $(this.closest('div .area-fix02-2')).attr('id');
var divID = $(this).parents('div .area-fix02-2').attr('id');
switch (divID) {
case 'suppliesNameLinks':
resetSuppliesInfo();
resetContratInfo();
break;
case 'contratNoLinks':
resetContratInfo();
break;
case 'invoiceLinks':
BPA.InvoiceEmpName = null;
BPA.InvoiceEmpNum = null;
resetInvoiceEmp();
break;
}
resetSubMenu();
});
//開啟供應商視窗前,出現提醒視窗
$(document).on('click', '#SuppliesOpen', function () {
if (BPA.VendorNum) {
confirmopen(
'修改此欄位會將所有資料清空,是否確認修改',
function () {
resetSuppliesInfo();
resetContratInfo();
resetSubMenu();
setTimeout(function () {
openVendorSearchBox();
}, 50);
},
function () { }
);
}
else {
openVendorSearchBox();
}
});
//開啟特殊合約明細查詢視窗前,出現提醒視窗
$(document).on('click', '#ContractOpen', function () {
if (BPA.CID != '00000000-0000-0000-0000-000000000000') {
confirmopen(
'修改此欄位會將所有特定請購資訊清空,是否確認修改',
function () {
resetContratInfo();
resetSubMenu();
setTimeout(function () {
openModalContract();
}, 50);
},
function () { }
);
}
else {
openModalContract();
}
});
//單價
$(document).on('change', '#bpaDetail input:text', function () {
//var tr = $(this).closest('tr');
var tr = $(this).parents('tr');
var CDID = tr.attr('id');
var bpaPrice = accounting.unformat($(this).val());
if (bpaPrice <= 0 || accounting.unformat(tr.find('.oriPrice').text()) < bpaPrice) {
alertopen('議價單價必須大於0,且不可超過報價單價!');
$(this).val(0);
}
else {
$(this).val(numberNoRightPaddingZeros(bpaPrice, accounting.formatNumber(bpaPrice, BPA.ExtendedPrecision, ',')));
}
bpaPrice = accounting.unformat($(this).val());
$.each(BPA.YearlyContractDetailList, function (index, element) {
if (element.CDetailID == CDID && !element.IsDelete) {
element.UnitPrice = bpaPrice;
return false;
}
});
});
//是否決行
$(document).on('change', '#bpaDetail input:radio', function () {
var check = $(this).val() == 'True' ? true : false;
//var CDID = $(this).closest('tr').attr('id');
var CDID = $(this).parents('tr').attr('id');
$.each(BPA.YearlyContractDetailList, function (index, element) {
if (element.CDetailID == CDID && !element.IsDelete) {
element.GeneralFlag = check;
return false;
}
});
});
//綠色採購
$(document).on('change', '#bpaDetail select', function () {
var option = $(this).val();
var option_text = $(this).find('option:selected').text();
//var CDID = $(this).closest('tr').attr('id');
var CDID = $(this).parents('tr').attr('id');
$.each(BPA.YearlyContractDetailList, function (index, element) {
if (element.CDetailID == CDID && !element.IsDelete) {
element.GreenCategory = option;
element.GreenCategoryName = option_text;
return false;
}
});
});
//合約起始時間
$('#StartDate').on('dp.change', function () {
BPA.ContractStartDate = $(this).find('input').val();
if (!BPA.ContractStartDate) {
$('#EndDate input').val('').trigger('dp.change');
return;
}
var date = new Date(BPA.ContractStartDate);
var value = $('#EndDate input').val();
$('#EndDate').data('DateTimePicker').minDate(date);
$('#EndDate input').val(value).trigger('dp.change');
if (BPA.ContractStartDate >= BPA.ContractEndDate) {
date.setDate(date.getDate() + 1);
$('#EndDate input').val(convertDateString(date)).trigger('dp.change');
}
});
//合約結束時間
$('#EndDate').on('dp.change', function () {
BPA.ContractEndDate = $(this).find('input').val();
});
if (BPA.ContractStartDate) {
$('#StartDate span').trigger('click');
}
if (BPA.ContractEndDate) {
$('#EndDate span').trigger('click');
}
//ApplyItem
initialApplyItem();
});
function openVendorSearchBox() {
var result = getSupplies();
openVendor(false, result);
}
//開啟特殊合約查詢
function openModalContract() {
clearSearchCondition();
$('#contractNoDrop').selectpicker();
$('#contractNoDrop').empty();
$.ajax({
async: false,
url: '/BPA/GetContractByVendor',
dataType: 'json',
type: 'POST',
data: { suppliesNum: BPA.VendorNum },
success: function (data, textStatus, jqXHR) {
$.each(data, function (index, value) {
$('#contractNoDrop').append('<option value="' + value.CID + '">' + value.BpcNum + '</option>');
});
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
$('#contractNoDrop').attr('data-live-search', $('#contractNoDrop option').length > 10 ? 'true' : 'false');
$('#contractNoDrop').selectpicker('refresh');
$('[data-remodal-id=modal-contract]').remodal().open();
var checkBox = $('#searchResult input:checkbox');
$.each(checkBox, function (index, item) {
$(item).attr('checked', false);
});
}
//清除搜尋內容
function clearSearchCondition() {
$('#contractNoDrop').val('');
$('#contractNoDrop').selectpicker('refresh');
$('#purchasePICDrop').val('');
$('#purchasePICDrop').selectpicker('refresh');
$('#contractDescribe').val('');
$('#searchResult').attr('style', 'display:none');
}
//合約明細查詢Ajax
function getCDetail(cID, itemDescription, cDetailIDList) {
$.ajax({
async: false,
url: '/BPA/GetCDetailByCID',
dataType: 'json',
type: 'POST',
data: { cID: cID, itemDescription: itemDescription, cDetailIDList: cDetailIDList },
success: function (data, textStatus, jqXHR) {
BPCDetailResult = data;
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
return BPCDetailResult;
}
//搜尋判斷
function searchBtn() {
var result = getCDetail($('#contractNoDrop').val(), $('#contractDescribe').val(), null);
if (result) {
$('#searchResult .popup-tbody ul').empty();
$.each(result, function (index, value) {
$('#searchResult .popup-tbody ul').append('<li>\
<label class="w100 label-box">\
<div class="table-box w5" id="'+ index + '">\
<input name="www" class="contractDetail" type="checkbox">\
</div>\
<div class="table-box w5">' + (index + 1) + '</div>\
<div class="table-box w25">' + value.CategoryName + '</div>\
<div class="table-box w25">' + value.ItemDescription + '</div>\
<div class="table-box w5">' + value.UomName + '</div>\
<div class="table-box w5">' + value.CurrencyName + '</div>\
<div class="table-box w10">' + value.Price + '</div>\
<div class="table-box w10">' + value.PurchaseEmpName + '(' + value.PurchaseEmpNum + ')</div>\
<div class="table-box w10">' + value.InvoiceEmpName + '(' + value.InvoiceEmpNum + ')</div>\
</label>\
</li>');
});
}
var contractNo = $('#contractNoDrop').val();
if (contractNo != '') {
$('#searchResult').attr('style', 'display:block');
}
else {
alert("申請單號為必填")
}
}
//根據CDetailID進行array排序
function compareCDetailIndex(a, b) {
if (a.CDetailID < b.CDetailID)
return -1;
if (a.CDetailID > b.CDetailID)
return 1;
return 0;
}
//清空新增的明細(YCDetailID值為0),將舊的明細IsDelete設定為true
function resetBPADetail() {
BPA.YearlyContractDetailList = $.grep(BPA.YearlyContractDetailList, function (item, index) {
return (item.YCDetailID != 0);
});
$.each(BPA.YearlyContractDetailList, function (index, item) {
item.IsDelete = true;
item.DeleteBy = BPA.FillInEmpNum;
});
}
//查詢特殊合約明細後,按下帶入之動作
function appendDetail() {
//先清空年度議價明細資訊
resetBPADetail();
$('#bpaDetail tbody').remove();
//將核選的明細帶入BPA表單中議價明細
var checkedList = $('input.contractDetail:checked').parents('li');
var a = [];
if (checkedList.length > 0) {
BPCDetail = [];
BPA.CID = $('#contractNoDrop').val();
BPA.InvoiceEmpName = BPCDetailResult[0].InvoiceEmpName;
BPA.InvoiceEmpNum = BPCDetailResult[0].InvoiceEmpNum;
$.each(checkedList, function (index, item) {
var temp = $(item).find('div');
a.push({ CategoryName: $(temp[2]).text(), ItemDescription: $(temp[3]).text(), UomName: $(temp[4]).text(), Price: $(temp[6]).text(), CDetailID: $(temp[0]).attr('id') })
BPCDetail.push(BPCDetailResult[$(temp[0]).attr('id')]);
});
a.sort(compareCDetailIndex);
BPCDetail.sort(compareCDetailIndex);
$.each(a, function (index, item) {
var detail = {
"CDetailID": BPCDetail[index].CDetailID,
"CreateBy": BPA.FillInEmpNum,
"DeleteBy": null,
"GeneralFlag": true, //預設為決行
"GreenCategory": 'OTHERS',
"GreenCategoryName": '其他',
"IsDelete": false,
"UnitPrice": 0,
"YCDetailID": 0,
"YCID": BPA.YCID
};
BPA.YearlyContractDetailList.push(detail);
})
//特殊合約編號
contractSelectChange(true);
//協議明細
createBpaDetail();
$('#bpaDetailBlock').show();
resetSubMenu();
$('div[data-remodal-id=modal-contract]').remodal().close();
}
else {
alert("至少選擇一個明細");
}
}
//建立年度議價協議明細
function createBpaDetail() {
$.each(BPCDetail, function (index, item) {
var tr = $(
'<tr id="' + item.CDetailID + '">\
<td class="text-center">' + (index + 1) + '</td>\
<td>' + item.CategoryName + '</td>\
<td>' + item.ItemDescription + '</td>\
<td>' + item.UomName + '</td>\
<td class="oriPrice">' + numberNoRightPaddingZeros(item.Price, accounting.formatNumber(item.Price, BPA.ExtendedPrecision, ',')) + '</td>\
<td><input type="text" class="input h30" placeholder="填寫單價"></td>\
<td>\
<div class="w100 text-box">\
<label><input id="' + index + '_Y" name="' + index + '" type="radio" value="True"><span class="success-text">決行</span></label>\
<label><input id="' + index + '_N" name="' + index + '" type="radio" value="False"><span class="fail-text">不決行</span></label>\
</div>\
</td>\
<td>\
<div class="row">\
<div class="col-sm-10 content-box">\
<div class="w90 text-box">\
<select id="basic" class="selectpicker show-tick form-control select-h30" data-live-search="false" title="請選擇">\
'+ GreenOption.html() + '\
</select>\
</div>\
</div>\
<div class="col-sm-2 content-box">\
<div></div>\
<div class="icon-remove-size" style="display:none" id="DeleteThisDetail" title="刪除欄位"><a class="icon-cross"></a></div>\
</div>\
</div>\
</td>\
</tr>'
);
var jsonElement = $.grep(BPA.YearlyContractDetailList, function (element, jsonIndex) {
return (element.CDetailID == item.CDetailID && !element.IsDelete);
});
if (jsonElement.length > 0) {
//議價單價
tr.find('input:text').val(numberNoRightPaddingZeros(jsonElement[0].UnitPrice, accounting.formatNumber(jsonElement[0].UnitPrice, BPA.ExtendedPrecision, ',')));
//是否決行
if (jsonElement[0].GeneralFlag) {
tr.find('#' + index + '_Y').prop('checked', true);
}
else {
tr.find('#' + index + '_N').prop('checked', true);
}
//綠色採購
var selectDOM = tr.find('select');
if ($('#P_CurrentStep').val() != '1' || $('#P_Status').val() == '4') {
$(selectDOM).append('<option value="' + jsonElement[0].GreenCategory + '">' + jsonElement[0].GreenCategoryName + '</option>')
}
$(selectDOM).selectpicker();
$(selectDOM).val(jsonElement[0].GreenCategory);
$(selectDOM).selectpicker('refresh');
if ($('#P_CurrentStep').val() != '1' || $('#P_Status').val() == '4') {
var select = $(tr).find('select');
$(tr).children().last().empty().append($('<div class="w100 text-box">').append(select));
var input = $(tr).find('input').val();
$(tr).children().eq(5).empty().text(input);
}
}
$('#bpaDetail').append($('<tbody>').append(tr));
});
if ($('#P_CurrentStep').val() != '1' || $('#P_Status').val() == '4') {
//$('#bpaDetail input:text').prop('disabled', true).addClass('input-disable');
$('#bpaDetail input:radio:not(:checked)').prop('disabled', true);
$('#bpaDetail select').prop('disabled', true).addClass('input-disable').selectpicker('refresh');
}
}
//移除or重選供應商
function resetSuppliesInfo() {
//供應商
//$('#suppliesNameLinks .no-file-text').show();
//$('#suppliesNameLinks .Links').hide();
$('#VendorName').empty().append('<span class="undone-text">請點選右方【選擇】鈕選擇供應商</span>');
$('#ApplyItem').val('供應商-');
BPA.VendorName = null;
BPA.VendorNum = null;
$('#invoiceAddress').empty().val('').selectpicker('refresh');
BPA.VendorSiteId = null;
BPA.VendorSiteName = null;
$('#ContactPerson').val('');
BPA.ContactPerson = null;
$('#ContactEmail').val('');
BPA.ContactEmail = null;
//核發資訊隱藏
$('#bpaContentBlock').hide();
}
//移除or重選發票管理人
function resetInvoiceEmp() {
if (BPA.InvoiceEmpNum) {
if ($('#P_CurrentStep').val() == '1' && $('#P_Status').val() != '4') {
$('#invoiceLinks .no-file-text').hide();
$('#invoiceLinks span').text(BPA.InvoiceEmpName + '(' + BPA.InvoiceEmpNum + ')');
$('#invoiceLinks .Links').show();
}
else {
$('#invoiceLinks').text(BPA.InvoiceEmpName + '(' + BPA.InvoiceEmpNum + ')');
}
}
else {
$('#invoiceLinks .Links').hide();
$('#invoiceLinks .no-file-text').show();
}
}
//移除or重選特殊合約編號
function resetContratInfo() {
//合約編號
//$('#contratNoLinks .no-file-text').show();
//$('#contratNoLinks .Links').hide();
$('#contratNo').empty().append('<span class="undone-text">請點選右方【選擇】鈕選擇合約</span>');
BPA.CID = '00000000-0000-0000-0000-000000000000';
//合約申請人
$('#contratApplicant').empty();
//發票管理員
BPA.InvoiceEmpName = null;
BPA.InvoiceEmpNum = null;
resetInvoiceEmp();
//幣別
$('#currency').text('');
//匯率
$('#exchangeRate').text('');
BPA.ExchangeRate = 0;
//合約起訖時間
$('#StartDate input').val('').trigger('dp.change');
$('#EndDate input').val('').trigger('dp.change');
//明細資訊
$('#bpaDetail tbody').remove();
$('#bpaDetailBlock').hide();
resetBPADetail();
}
//呼叫FIIS取得綠色採購下拉清單
function getGreenCategory() {
if ($('#P_CurrentStep').val() == '1' && $('#P_Status').val() != '4') {
$.ajax({
async: false,
url: '/BPA/GetGreenCategory',
data: { source: 'BPA' },
dataType: 'json',
type: 'POST',
success: function (data, textStatus, jqXHR) {
$.each(data, function (index, value) {
GreenOption.append('<option value="' + value.greenProcureCategory + '">' + value.description + '</option>');
});
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
}
}
//開啟查詢供應商前,搜尋核可的供應商清單
function getSupplies() {
var result;
$.ajax({
async: false,
url: '/BPA/GetSupplies',
dataType: 'json',
type: 'POST',
success: function (data, textStatus, jqXHR) {
result = data;
},
error: function (jqXHR, textStatus, errorThrown) {
result = null;
}
});
return result;
}
//供應商變更的UI操作
function suppliesUIChange() {
$('#VendorName').empty().append(BPA.VendorName + '(' + BPA.VendorNum + ')');
$('#ApplyItem').val('供應商-' + BPA.VendorName);
}
//載入特殊合約明細
function contractSelectChange(loadBySearch) {
//特殊合約單號
$('#contratNo').text(BPCDetail[0].BpcNum);
//合約申請人
var depArray = BPCDetail[0].ApplicantDepName.split(',');
$('#contratApplicant').empty();
$('#contratApplicant').append('<span class="fL">' + BPCDetail[0].ApplicantName + '(' + BPCDetail[0].ApplicantEmpNum + ')</span>\
<div class="info-note-box">\
<a class="info-bt icon-info text-blue-link "></a>\
<span class="info-note">\
<i></i>\
<ul class="info-list-text">\
<li>\
<span class="icon-account_balance"></span>\
<span>' + depArray[0] + '</span>\
</li>\
<li>\
<span class="icon-room"></span>\
<span>' + depArray[1] + '</span>\
</li>\
<li>\
<span class="icon-room"></span>\
<span>' + depArray[2] + '</span>\
</li>\
</ul>\
</span>\
</div>');
//發票管理人
resetInvoiceEmp();
//合約幣別
$('#currency').text(BPCDetail[0].CurrencyName + '(' + BPCDetail[0].CurrencyCode + ')');
//匯率
if ($('#P_CurrentStep').val() == '1' && $('#P_Status').val() != '4') {
//getExchangeRate(BPCDetail[0].CurrencyCode);
getCurrencyInfo(BPCDetail[0].CurrencyCode, BPCDetail[0].ExchangeRate);
}
$('#exchangeRate').text(BPA.ExchangeRate);
if (loadBySearch) {
//合約起訖
var myDate = new Date(BPCDetail[0].ContractStartDate);
$('#StartDate input').val(convertDateString(myDate)).trigger('dp.change');
myDate = new Date(BPCDetail[0].ContractEndDate);
$('#EndDate input').val(convertDateString(myDate)).trigger('dp.change');
}
else {
var myDate = new Date();
if (BPA.ContractStartDate) {
myDate = new Date(BPA.ContractStartDate);
$('#StartDate input').val(convertDateString(myDate)).trigger('dp.change');
}
if (BPA.ContractEndDate) {
myDate = new Date(BPA.ContractEndDate);
$('#EndDate input').val(convertDateString(myDate)).trigger('dp.change');
}
}
}
//取得幣別匯率
//不用了,改抓特殊合約存的匯率
//以防萬一user機掰又要改回來,留著
//function getExchangeRate(from) {
// if (from == 'TWD') {
// BPA.ExchangeRate = 1;
// BPA.ExtendedPrecision = 0;
// }
// else {
// $.ajax({
// async: false,
// url: '/FIIS/GetConversionRate?sourceCode=BPA&fromCurrencyCode=' + from + '&toCurrencyCode=TWD',
// dataType: 'json',
// success: function (data, textStatus, jqXHR) {
// BPA.ExchangeRate = data.conversionRate;
// BPA.ExtendedPrecision = data.extendedPrecision;
// },
// error: function (jqXHR, textStatus, errorThrown) {
// alert('取得幣別匯率失敗!\n' + errorThrown);
// BPA.ExchangeRate = 1;
// BPA.ExtendedPrecision = 0;
// }
// });
// }
//}
//取得幣別資訊
function getCurrencyInfo(from, rate) {
if (from == 'TWD') {
BPA.ExchangeRate = 1;
BPA.ExtendedPrecision = 4;
}
else {
$.ajax({
cache: false,
async: false,
type: 'POST',
url: '/BPA/GetCurrencyCode',
data: { code: from },
dataType: 'json',
success: function (data, textStatus, jqXHR) {
BPA.ExchangeRate = rate;
BPA.ExtendedPrecision = 4;
},
error: function (jqXHR, textStatus, errorThrown) {
alert('取得幣別資訊失敗!\n' + errorThrown);
BPA.ExchangeRate = rate;
BPA.ExtendedPrecision = 4;
}
});
}
}
//Get頁面取得供應商資料並顯示在UI上
function loadSupplies() {
supplies = $.grep(supplies, function (element, index) {
return element.VendorNum == BPA.VendorNum;
});
if (supplies.length > 0) {
suppliesUIChange();
$('#invoiceAddress').val(BPA.VendorSiteId);
$('#bpaContentBlock').show();
}
else {
alert('特定請購過期!');
resetSuppliesInfo();
resetContratInfo();
}
}
//Get頁面
function loadFormData() {
var today = new Date();
if (!BPA.ApplicantName) {
BPA.ApplicantEmpNum = $('input[name="ApplicantEmpNum"]').val();
BPA.ApplicantName = $('input[name="ApplicantName"]').val();
BPA.ApplicantDepName = $('input[name="ApplicantDepName"]').val();
BPA.ApplicantDepId = $('input[name="ApplicantDepId"]').val();
}
if (BPA.BpaNum) {
if (BPA.VendorNum) {
loadSupplies();
}
if (BPA.PurchaseRemark) {
$('#PurchaseRemark').val(BPA.PurchaseRemark).text(BPA.PurchaseRemark);
}
if (BPA.CID) {
var idArray = [];
$.each(BPA.YearlyContractDetailList, function (index, element) {
idArray.push(element.CDetailID);
});
var cDetailIDList = idArray.join();
BPCDetail = getCDetail(BPA.CID, null, cDetailIDList);
if (BPCDetail.length) {
contractSelectChange(false);
$('#bpaDetailBlock').show();
}
if (BPA.YearlyContractDetailList.length > 0) {
createBpaDetail();
}
}
resetSubMenu();
}
}
//若CID存在,則直接帶入資料,不重新查詢核可的供應商清單(因為特殊合約會隨著時間推移而過期,變成不核可的供應商)
function getExistSupplies() {
var result;
$.ajax({
async: false,
url: '/BPA/GetExistSupplies',
dataType: 'json',
type: 'POST',
data: { cid: BPA.CID, vendorNum: BPA.VendorNum },
success: function (data, textStatus, jqXHR) {
result = data;
},
error: function (jqXHR, textStatus, errorThrown) {
result = null;
}
});
return result;
}
function alertopen(text) {
/// <summary>偉大的UI/UX說不要用醜醜的原生alert,改用remodal</summary>
/// <param name="text" type="string or array">你想顯示給北七使用者的文字</param>
$('#alertText').empty();
if (typeof (text) != typeof ([])) {
$('#alertText').text(text);
$('[data-remodal-id=alert-modal]').remodal().open();
}
else {
if (text.length < 1) {
return;
}
$('#alertText').append(text.join("<br>"));
$('[data-remodal-id=alert-modal]').remodal().open();
}
}
function checkContractQuoteAmount() {
var deferred = $.Deferred();
$.ajax({
url: '/BPA/CheckContractQuoteAmount/',
dataType: 'json',
type: 'POST',
data: { cid: BPA.CID, quoteAmount: BPCDetail[0].QuoteAmount, bpcNum: BPCDetail[0].BpcNum, source: 'BPA' },
success: function (data, textStatus, jqXHR) {
if (!data) {
alertopen('核發總金額已大於合約報價金額合計');
deferred.reject();
}
else {
deferred.resolve();
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert('取得已核發總金額失敗!\n' + errorThrown);
deferred.reject();
}
});
return deferred.promise();
}
function checkFieldValid() {
//欄位資料檢核
$('div[class="error-text"]').hide();
var verifyDom = [];
if (!BPA.VendorNum) {
verifyDom.push('VendorNum');
}
if (!BPA.VendorSiteId) {
verifyDom.push('VendorSiteId');
}
if (BPA.ContactEmail && !validateEmail(BPA.ContactEmail)) {
verifyDom.push('ContactEmail');
}
if (BPA.CID == '00000000-0000-0000-0000-000000000000') {
verifyDom.push('CID');
}
if (!BPA.InvoiceEmpNum) {
verifyDom.push('InvoiceEmpNum');
}
if (!BPA.ContractStartDate) {
verifyDom.push('StartDate');
}
if (!BPA.ContractEndDate) {
verifyDom.push('EndDate');
}
var unSaveRow = $.grep(BPA.YearlyContractDetailList, function (item, index) {
return !item.IsDelete;
}).length;
var invalidRow = $.grep(BPA.YearlyContractDetailList, function (item, index) {
return (!item.IsDelete && (item.UnitPrice == 0 || item.GreenCategory == -1));
}).length;
if (unSaveRow == 0 || invalidRow > 0) {
verifyDom.push('YearlyContractDetailList');
}
$.each(verifyDom, function (index, item) {
$('div[RequiredField="' + item + '"][class="error-text"]').show();
});
if (verifyDom.length > 0) {
$('html, body').animate({
scrollTop: ($('div[RequiredField="' + verifyDom[0] + '"][class!="error-text"]').offset().top) - 50
}, 500);
return false;
}
else {
return true;
}
}
//前端欄位檢核卡控
function Verify() {
var deferred = $.Deferred();
if (checkFieldValid()) {
if ($('#P_Status').val() == '0') {
$.when(checkContractQuoteAmount()).done(function () {
deferred.resolve();
}).fail(function () {
deferred.reject();
});
}
else {
deferred.resolve();
}
}
else {
deferred.reject();
}
return deferred.promise();
}
function Save() {
var deferred = $.Deferred();
var _url = BPA.BpaNum ? '/BPA/Edit' : '/BPA/Create';
$.ajax({
url: _url,
dataType: 'json',
type: 'POST',
data: BPA
}).done(function (data, textStatus, jqXHR) {
console.log('save finish');
if (data.Flag) {
_formInfo.formGuid = data.FormGuid;
_formInfo.formNum = data.FormNum;
_formInfo.flag = data.Flag;
}
else {
_formInfo.flag = false;
alertopen('儲存表單失敗!');
}
}).fail(function (jqXHR, textStatus, errorThrown) {
}).always(function () {
if (_formInfo.flag && _clickButtonType == 3) {
$.when($.ajax({
url: '/BPA/FIISCreateBpa/',
dataType: 'json',
type: 'POST',
data: { yearlyContract: BPA, currencyCode: BPCDetailResult[0].CurrencyCode, referenceDocument: BPCDetailResult[0].BpcNum, contractDetailList: BPCDetailResult },
}).done(function (data, textStatus, jqXHR) {
console.log('FIISCreateBpa finish : done');
if (typeof data != 'string') {
_formInfo.flag = data;
}
else {
alertopen(data);
_formInfo.flag = false;
}
}).fail(function (jqXHR, textStatus, errorThrown) {
alertopen(jqXHR.responseText);
_formInfo.flag = false;
})).always(function () {
deferred.resolve();
});
}
else {
deferred.resolve();
}
});
return deferred.promise();
}
//暫存
function draft() {
blockPageForJBPMSend();
var deferred = $.Deferred();
var _url = BPA.BpaNum ? '/BPA/Edit' : '/BPA/Create';
return $.ajax({
cache: false,
url: _url,
dataType: 'json',
type: 'POST',
data: BPA,
success: function (data, textStatus, jqXHR) {
_formInfo.formGuid = data.FormGuid;
_formInfo.formNum = data.FormNum;
_formInfo.flag = data.Flag;
if (!data.Flag) {
blockPage('');
alertopen('儲存表單失敗!');
}
},
error: function (jqXHR, textStatus, errorThrown) {
blockPage('');
alert(jqXHR.responseText);
_formInfo.flag = false;
}
});
}
//組織樹輸出查詢結果(自行改寫區塊)
function BPAQueryTemp(datas, type, row) {
BPA.InvoiceEmpName = datas[0].user_name;
BPA.InvoiceEmpNum = datas[0].user_id;
resetInvoiceEmp();
}
//確認選擇供應商,更新供應商名稱 & 重設側邊選單
function vendorSelected(vendor) {
if (vendor) {
BPA.VendorNum = vendor.supplierNumber;
BPA.VendorID = vendor.supplierID;
BPA.VendorName = vendor.supplierName;
suppliesUIChange();
$('#invoiceAddress').empty();
$.each(vendor.supplierSite, function (index, element) {
$('#invoiceAddress').append($('<option>').val(element.supplierSiteID).text(element.supplierSiteCode));
});
$('#invoiceAddress').val('').selectpicker('refresh');
BPA.VendorSiteId = 0;
BPA.VendorSiteName = null;
$('#bpaContentBlock').show();
resetContratInfo();
resetSubMenu();
}
}
//如關卡類別為依表單欄位,各表單需實作特定關卡取得下一關人員清單
function GetPageCustomizedList(stepSequence) {
if (stepSequence == 3) {
return { SignedID: [BPA.InvoiceEmpNum], SignedName: [BPA.InvoiceEmpName] };
}
}
function OverrideOrgPickerSetting(step) {
/// <summary>提供cbp-SendSetting.js針對「傳送其他主管同仁」按鈕做最後OrgPicker更改機會</summary>
/// <param name="step" type="number">目前關卡數</param>
if (step == 1) {
return {
allowRole: ["JA18000078"]
};
}
if (step == 2) {
return {
allowRole: ["JA18000226"]
};
}
}
function convertDateString(date) {
/// <summary>將日期轉換成yyyy-MM-dd格式</summary>
/// <param name="date" type="Date">日期</param>
var dateYear = date.getFullYear();
var dateMonth = date.getMonth() + 1;
if (dateMonth.toString().length < 2) {
dateMonth = "0" + dateMonth.toString();
}
var dateDay = date.getDate();
if (date.getDate().toString().length < 2) {
dateDay = "0" + date.getDate().toString();
}
return dateYear + "-" + dateMonth + "-" + dateDay;
}
function numberNoRightPaddingZeros(num, formatNum) {
/// <summary>accounting多餘的0去掉</summary>
/// <param name="num" type="number">原始數字</param>
/// <param name="formatNum" type="string">經過account format後的字串(含0)</param>
var splitNum = num.toString().split(".");
var splitFormatNum = formatNum.toString().split(".");
var lengthNum = splitNum.length == 2 ? splitNum[1].length : 0;
var lengthFormatNum = splitFormatNum.length != 2 ? 0 :
lengthNum != 0 ? splitFormatNum[1].length : splitFormatNum[1].length + 1;
return formatNum.substring(0, formatNum.toString().length - (lengthFormatNum - lengthNum));
}
|
import { MessageBox } from 'element-ui'
let loginTipsOpen = false // 判断 弹出层存在
// 弹出消息,登录环境错误问题
export function openMessage(data) {
// 只允许同时一个弹出窗
if (loginTipsOpen) return
loginTipsOpen = true
MessageBox.confirm(`<div>
<p>没有 ${data.message} 环境的cookie,需要登录 ${data.message} 环境,
<a style="color:#409EFF;text-decoration:none" href="${data.loginLink}" target="_blank">前往登录</a></p>
<p>完成登录操作后点击确认刷新页面</p>
</div>`, '登录提醒', {
dangerouslyUseHTMLString: true,
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
loginTipsOpen = false
window.location.reload()
}).catch(() => {
loginTipsOpen = false
})
}
// 重置302登录问题
export function httpError302() {
if (window.isPreview) {
const env = window.parent.previewEnv || window.previewEnv || 'online'
const options = {
tx: {
message: '测试',
loginLink: '/login'
},
online: {
message: '正式',
loginLink: '/login'
}
}
openMessage(options[env])
}
}
|
import React from "react";
import "./SignUp.css";
import { Field, reduxForm } from "redux-form";
import { compose } from "redux";
import { connect } from "react-redux";
import { signUp } from "../../redux/actions/authActions";
import { useHistory } from "react-router-dom";
const Signup = (props) => {
const {
handleSubmit,
pristine,
reset,
submitting,
signUp,
currentAuthState,
} = props;
let history = useHistory();
const formData = async (data) => {
try {
console.log("called", data);
await signUp(data);
reset();
if (currentAuthState.errorMessage) {
history.push({
pathname: "/product",
// search: "?query=abc",
// state: { detail: currentAuthState },
});
}
} catch (error) {
console.log(error);
}
};
return (
<div>
<div className="container">
<div
className="alert alert-primary"
id="accountAlert"
role="alert"
style={{ display: "none" }}
>
account created successfully!
</div>
<div className="row d-flex justify-content-center my-5">
<div className="col-md-6 px-3 form-left">
<div className="alert alert-primary">
<h6 className="text-center">Sign up</h6>
</div>
<form onSubmit={handleSubmit(formData)}>
<div className="form-group">
{/* <label>Email</label> */}
<div>
<Field
name="email"
component="input"
type="email"
id="email"
placeholder="Email"
className="form-control"
/>
</div>
</div>
<br />
<div className="form-group">
{/* <label>Password</label> */}
<div>
<Field
name="password"
id="password"
component="input"
type="password"
placeholder="Password"
className="form-control"
/>
</div>
</div>
{/* <br />
{currentAuthState.errorMessage ? (
<div className="alert alert-danger">
{currentAuthState.errorMessage}
</div>
) : null} */}
<div className="mt-2">
<button
className="btn btn-primary me-2"
type="submit"
disabled={pristine || submitting}
>
Sign up
</button>
<button
type="button"
disabled={pristine || submitting}
onClick={reset}
className="btn btn-danger "
>
Clear Values
</button>
</div>
</form>
</div>
</div>
</div>
</div>
);
};
const mapStateToProps = (state) => {
return {
currentAuthState: state.auth,
};
};
const mapDispatchToProps = {
signUp: signUp,
};
export default compose(
connect(mapStateToProps, mapDispatchToProps),
reduxForm({ form: "signup" })
)(Signup);
|
import $ from '../../core/renderer';
import { getWindow } from '../../core/utils/window';
import eventsEngine from '../../events/core/events_engine';
import browser from '../../core/utils/browser';
import positionUtils from '../../animation/position';
import { each } from '../../core/utils/iterator';
import Class from '../../core/class';
import { Deferred } from '../../core/utils/deferred';
import Callbacks from '../../core/utils/callbacks';
import { VirtualDataLoader } from './ui.grid.core.virtual_data_loader';
var SCROLLING_MODE_INFINITE = 'infinite';
var SCROLLING_MODE_VIRTUAL = 'virtual';
var NEW_SCROLLING_MODE = 'scrolling.newMode';
var _isVirtualMode = that => that.option('scrolling.mode') === SCROLLING_MODE_VIRTUAL || that._isVirtual;
var _isAppendMode = that => that.option('scrolling.mode') === SCROLLING_MODE_INFINITE && !that._isVirtual;
export var getPixelRatio = window => window.devicePixelRatio || 1;
export function getContentHeightLimit(browser) {
if (browser.msie) {
return 4000000;
} else if (browser.mozilla) {
return 8000000;
}
return 15000000 / getPixelRatio(getWindow());
}
export function subscribeToExternalScrollers($element, scrollChangedHandler, $targetElement) {
var $scrollElement;
var scrollableArray = [];
var scrollToArray = [];
var disposeArray = [];
$targetElement = $targetElement || $element;
function getElementOffset(scrollable) {
var $scrollableElement = scrollable.element ? scrollable.$element() : scrollable;
var scrollableOffset = positionUtils.offset($scrollableElement);
if (!scrollableOffset) {
return $element.offset().top;
}
return scrollable.scrollTop() - (scrollableOffset.top - $element.offset().top);
}
function createWindowScrollHandler(scrollable) {
return function () {
var scrollTop = scrollable.scrollTop() - getElementOffset(scrollable);
scrollTop = scrollTop > 0 ? scrollTop : 0;
scrollChangedHandler(scrollTop);
};
}
var widgetScrollStrategy = {
on: function on(scrollable, eventName, handler) {
scrollable.on('scroll', handler);
},
off: function off(scrollable, eventName, handler) {
scrollable.off('scroll', handler);
}
};
function subscribeToScrollEvents($scrollElement) {
var isDocument = $scrollElement.get(0).nodeName === '#document';
var scrollable = $scrollElement.data('dxScrollable');
var eventsStrategy = widgetScrollStrategy;
if (!scrollable) {
scrollable = isDocument && $(getWindow()) || $scrollElement.css('overflowY') === 'auto' && $scrollElement;
eventsStrategy = eventsEngine;
if (!scrollable) return;
}
var handler = createWindowScrollHandler(scrollable);
eventsStrategy.on(scrollable, 'scroll', handler);
scrollToArray.push(function (pos) {
var topOffset = getElementOffset(scrollable);
var scrollMethod = scrollable.scrollTo ? 'scrollTo' : 'scrollTop';
if (pos - topOffset >= 0) {
scrollable[scrollMethod](pos + topOffset);
}
});
scrollableArray.push(scrollable);
disposeArray.push(function () {
eventsStrategy.off(scrollable, 'scroll', handler);
});
}
for ($scrollElement = $targetElement.parent(); $scrollElement.length; $scrollElement = $scrollElement.parent()) {
subscribeToScrollEvents($scrollElement);
}
return {
scrollTo: function scrollTo(pos) {
each(scrollToArray, function (_, scrollTo) {
scrollTo(pos);
});
},
dispose: function dispose() {
each(disposeArray, function (_, dispose) {
dispose();
});
}
};
}
export var VirtualScrollController = Class.inherit(function () {
var members = {
ctor: function ctor(component, dataOptions, isVirtual) {
this._dataOptions = dataOptions;
this.component = component;
this._viewportSize = 0;
this._viewportItemSize = 20;
this._viewportItemIndex = 0;
this._contentSize = 0;
this._itemSizes = {};
this._sizeRatio = 1;
this._isVirtual = isVirtual;
this.positionChanged = Callbacks();
this._dataLoader = new VirtualDataLoader(this, this._dataOptions);
},
getItemSizes: function getItemSizes() {
return this._itemSizes;
},
option: function option() {
return this.component.option.apply(this.component, arguments);
},
isVirtual: function isVirtual() {
return this._isVirtual;
},
virtualItemsCount: function virtualItemsCount() {
if (_isVirtualMode(this)) {
var totalItemsCount = this._dataOptions.totalItemsCount();
if (this.option(NEW_SCROLLING_MODE) && totalItemsCount !== -1) {
var viewportParams = this.getViewportParams();
var endItemsCount = totalItemsCount - (viewportParams.skip + viewportParams.take);
return {
begin: viewportParams.skip,
end: endItemsCount
};
}
return this._dataLoader.virtualItemsCount.apply(this._dataLoader, arguments);
}
},
setViewportPosition: function setViewportPosition(position) {
var result = new Deferred();
var scrollingTimeout = Math.min(this.option('scrolling.timeout') || 0, this._dataOptions.changingDuration());
if (scrollingTimeout < this.option('scrolling.renderingThreshold')) {
scrollingTimeout = this.option('scrolling.minTimeout') || 0;
}
clearTimeout(this._scrollTimeoutID);
if (scrollingTimeout > 0) {
this._scrollTimeoutID = setTimeout(() => {
this._setViewportPositionCore(position);
result.resolve();
}, scrollingTimeout);
} else {
this._setViewportPositionCore(position);
result.resolve();
}
return result.promise();
},
getViewportPosition: function getViewportPosition() {
return this._position || 0;
},
getItemIndexByPosition: function getItemIndexByPosition() {
var position = this._position;
var defaultItemSize = this.getItemSize();
var offset = 0;
var itemOffset = 0;
var itemOffsetsWithSize = Object.keys(this._itemSizes).concat(-1);
for (var i = 0; i < itemOffsetsWithSize.length && offset < position; i++) {
var itemOffsetWithSize = parseInt(itemOffsetsWithSize[i]);
var itemOffsetDiff = (position - offset) / defaultItemSize;
if (itemOffsetWithSize < 0 || itemOffset + itemOffsetDiff < itemOffsetWithSize) {
itemOffset += itemOffsetDiff;
break;
} else {
itemOffsetDiff = itemOffsetWithSize - itemOffset;
offset += itemOffsetDiff * defaultItemSize;
itemOffset += itemOffsetDiff;
}
var itemSize = this._itemSizes[itemOffsetWithSize];
offset += itemSize;
itemOffset += offset < position ? 1 : (position - offset + itemSize) / itemSize;
}
return Math.round(itemOffset * 50) / 50;
},
_setViewportPositionCore: function _setViewportPositionCore(position) {
this._position = position;
var itemIndex = this.getItemIndexByPosition();
var result = this.setViewportItemIndex(itemIndex);
this.positionChanged.fire();
return result;
},
setContentItemSizes: function setContentItemSizes(sizes) {
var virtualItemsCount = this.virtualItemsCount();
this._contentSize = sizes.reduce((a, b) => a + b, 0);
if (virtualItemsCount) {
sizes.forEach((size, index) => {
this._itemSizes[virtualItemsCount.begin + index] = size;
});
var virtualContentSize = (virtualItemsCount.begin + virtualItemsCount.end + this.itemsCount()) * this._viewportItemSize;
var contentHeightLimit = getContentHeightLimit(browser);
if (virtualContentSize > contentHeightLimit) {
this._sizeRatio = contentHeightLimit / virtualContentSize;
} else {
this._sizeRatio = 1;
}
}
},
getItemSize: function getItemSize() {
return this._viewportItemSize * this._sizeRatio;
},
getItemOffset: function getItemOffset(itemIndex, isEnd) {
var virtualItemsCount = this.virtualItemsCount();
var itemCount = itemIndex;
if (!virtualItemsCount) return 0;
var offset = 0;
var totalItemsCount = this._dataOptions.totalItemsCount();
Object.keys(this._itemSizes).forEach(currentItemIndex => {
if (!itemCount) return;
if (isEnd ? currentItemIndex >= totalItemsCount - itemIndex : currentItemIndex < itemIndex) {
offset += this._itemSizes[currentItemIndex];
itemCount--;
}
});
return Math.floor(offset + itemCount * this._viewportItemSize * this._sizeRatio);
},
getContentOffset: function getContentOffset(type) {
var isEnd = type === 'end';
var virtualItemsCount = this.virtualItemsCount();
if (!virtualItemsCount) return 0;
return this.getItemOffset(isEnd ? virtualItemsCount.end : virtualItemsCount.begin, isEnd);
},
getVirtualContentSize: function getVirtualContentSize() {
var virtualItemsCount = this.virtualItemsCount();
return virtualItemsCount ? this.getContentOffset('begin') + this.getContentOffset('end') + this._contentSize : 0;
},
getViewportItemIndex: function getViewportItemIndex() {
return this._viewportItemIndex;
},
setViewportItemIndex: function setViewportItemIndex(itemIndex) {
this._viewportItemIndex = itemIndex;
if (this.option(NEW_SCROLLING_MODE)) {
return;
}
return this._dataLoader.viewportItemIndexChanged.apply(this._dataLoader, arguments);
},
viewportItemSize: function viewportItemSize(size) {
if (size !== undefined) {
this._viewportItemSize = size;
}
return this._viewportItemSize;
},
viewportSize: function viewportSize(size) {
if (size !== undefined) {
this._viewportSize = size;
}
return this._viewportSize;
},
reset: function reset(isRefresh) {
this._dataLoader.reset();
if (!isRefresh) {
this._itemSizes = {};
}
},
subscribeToWindowScrollEvents: function subscribeToWindowScrollEvents($element) {
this._windowScroll = this._windowScroll || subscribeToExternalScrollers($element, scrollTop => {
if (this.viewportItemSize()) {
this.setViewportPosition(scrollTop);
}
});
},
dispose: function dispose() {
clearTimeout(this._scrollTimeoutID);
this._windowScroll && this._windowScroll.dispose();
this._windowScroll = null;
},
scrollTo: function scrollTo(pos) {
this._windowScroll && this._windowScroll.scrollTo(pos);
},
isVirtualMode: function isVirtualMode() {
return _isVirtualMode(this);
},
isAppendMode: function isAppendMode() {
return _isAppendMode(this);
},
// new mode
getViewportParams: function getViewportParams() {
var topIndex = this._viewportItemIndex;
var bottomIndex = this._viewportSize + topIndex;
var maxGap = this.pageSize();
var minGap = this.option('scrolling.minGap');
var virtualMode = this.option('scrolling.mode') === SCROLLING_MODE_VIRTUAL;
var skip = Math.floor(Math.max(0, topIndex - minGap) / maxGap) * maxGap;
var take = Math.ceil((bottomIndex + minGap) / maxGap) * maxGap - skip;
if (virtualMode) {
var remainedItems = this._dataOptions.totalItemsCount() - skip;
take = Math.min(take, remainedItems);
}
return {
skip,
take
};
}
};
['pageIndex', 'beginPageIndex', 'endPageIndex', 'pageSize', 'load', 'loadIfNeed', 'handleDataChanged', 'itemsCount', 'getDelayDeferred'].forEach(function (name) {
members[name] = function () {
return this._dataLoader[name].apply(this._dataLoader, arguments);
};
});
return members;
}());
|
import React, { Component } from 'react';
import adapters from '../adapters'
export default class AddShowForm extends Component {
state = {
genreList: [],
selected_genre: 1,
nameOfShowOrMovie: '',
cover: null,
coverURL: null
}
componentDidMount() {
adapters.getGenres()
.then(data => this.setState({ genreList: data}))
}
genreDropDown = (genres) => {
return genres.map((genre) => {
return <option key={genre.id} value={genre.id}>{genre.genre_name}</option>
})
}
handleNameInput = (e) => {
this.setState({
nameOfShowOrMovie: e.target.value
})
}
handleGenreSelection = (e) => {
this.setState({
selected_genre: e.target.value
})
}
handleFile = (e) => {
const file = e.target.files[0]
const fileReader = new FileReader()
fileReader.onloadend = () => {
this.setState({
cover: file,
coverURL: fileReader.result
})
}
if (file) {
fileReader.readAsDataURL(file)
}
}
submitForm = (e) => {
e.preventDefault()
const formData = new FormData()
formData.append('show[title]', this.state.nameOfShowOrMovie)
formData.append('show[user_id]', 3)
formData.append('show[genre_id]', this.state.selected_genre)
if (this.state.cover) {
formData.append('show[cover]', this.state.cover)
adapters.addShow(formData)
}
}
render () {
const preview = this.state.coverURL ? <img className="preview-img" alt="preview-img" src={this.state.coverURL}/> : null
return (
<div className="form-container">
<form onSubmit={this.submitForm} className="form">
<h1>Add Show or Movie</h1>
<p>Enter Show/Movie Name: <input onChange={this.handleNameInput} value={this.state.nameOfShowOrMovie}/></p>
<p>Select Genre: <select onChange={this.handleGenreSelection} value={this.state.selected_genre}>
{this.genreDropDown(this.state.genreList)}
</select>
</p>
<p>Upload Cover Art: <input onChange={this.handleFile} type="file"/></p>
{preview}
<button type="submit">Submit</button>
</form>
</div>
)
}
}
|
import React from 'react';
import Image from 'next/image';
import Link from 'next/link';
const Logo = () => {
return (
<div style={{ position: 'relative' }}>
<Link href="/" passHref>
<a>
<Image
src="/images/portfolio-logo.svg"
alt="Cian Dolphin logo"
height={16}
width={120}
/>
</a>
</Link>
</div>
);
};
export default Logo;
|
import styles from '../styles/Home.module.css'
import React,{ useEffect, useState} from 'react';
import { Container, Row, Col } from 'reactstrap';
import axios from 'axios';
import { useRouter } from 'next/router'
import Filter from '../components/Filter/filter';
import Card from '../components/Card/card';
function Home(props) {
const { launches } = props;
const router = useRouter();
const { land_success, launch_success, launch_year } = router.query;
const [filter, setFilter] = useState({year:launch_year ? launch_year:'',launch:launch_success?launch_success:'',landing:land_success?land_success:''});
const [flights, setFlights] = useState(launches);
const [loading, setLoading] = useState(false);
useEffect(() => {
const yearFilter = launch_year ? launch_year : ""
const launchFilter = launch_success ? launch_success : ""
const landingFilter = land_success ? land_success : ""
setLoading(true)
axios.get(`https://api.spacexdata.com/v3/launches?limit=100&launch_year=${yearFilter}&launch_success=${launchFilter}&land_success=${landingFilter}`)
.then(res => {
setFlights(res.data)
setLoading(false);
})
}, [land_success,launch_success,launch_year]);
const updateFilterState = (key, value) => {
console.log(key, value)
setFilter(prevState => ({
...prevState,
[key]: value
}));
const _year = (key === 'year' && value) ? value : launch_year;
const _land = (key === 'landing' && value) ? value : land_success;
const _launch = (key === 'launch' && value) ? value : launch_success;
router.push(`/?launch_success=${_launch?_launch:''}&land_success=${_land?_land:''}&launch_year=${_year?_year:''}`, undefined, { shallow: true });
}
console.log('-##############-',filter)
return (
<Container fluid={true} className={styles.App}>
<Row xl="12">
<Col><h2>Space X Launch Program</h2></Col>
</Row>
<Row xs="12" sm="12">
<Col xs="12" sm="4" md="3"><Filter
updateFilter={(key, value) => updateFilterState(key, value)}
yearProp={filter.year}
launchProp={filter.launch}
landingProp={filter.landing} /></Col>
<Col xs="12" sm="8" md="9">
<Row xs="12" sm="8">
{flights && flights.length > 0 && flights.map(f => <Col md="3" sm="6" xs="12" className={styles.padtop}>
<Card
missionName={f.mission_name}
flightNumber={f.flight_number}
imageURL={f.links.mission_patch_small}
missionIds={f.mission_id}
launchYear={f.launch_year}
launchSuccess={f.launch_success === null ? '' : f.launch_success.toString()}
launchLanding={f.rocket.first_stage.cores[0].land_success === null? '': f.rocket.first_stage.cores[0].land_success.toString()}
/>
</Col>)}
{loading && <Col><h4>Loading...........</h4></Col>}
{!loading && flights.length === 0 && <Col><h4>No Data</h4></Col>}
</Row>
</Col>
</Row>
<Row xl="12">
<Col><h2>Developed By Vignesh K B</h2></Col>
</Row>
</Container>
)
}
export default React.memo(Home);
export async function getStaticProps() {
const res = await axios.get(`https://api.spacexdata.com/v3/launches?limit=100&launch_year=""&launch_success=""&land_success=""`);
return {
props: {
launches: res.data,
},
}
}
|
/*
JavaScript Algorithms and Data Structures Masterclass
Pivot Helper
Create a function pivotHelper that accepts an array and makes the first element of that array a pivot. It should arrange the array (in place) such that the numbers to the left of the pivot are less than the pivot and so the numbers to the right of the pivot are greater than the pivot. pivotHelper returns the final index of the pivot.
*/
const pivotHelper = (arr) => {
let index = 0;
for(let i = 1; i < arr.length; i++) {
if(arr[i] < arr[0]) {
index++;
let temp = arr[i];
arr[i] = arr[index];
arr[index] = temp;
}
}
if(index > 0) {
let holder = arr[0];
arr[0] = arr[index];
arr[index] = holder;
}
console.log('here is arr: ' + arr);
return index;
}
|
//Use getters and setters to Control Access to an Object
function makeClass() {
"use strict";
/* Alter code below this line */
class Thermostat {
constructor(Farenheit){
this._temp = temp;
}
get celsius(){
return this._temp;
}
set celsius(updatedTemp) {
this._temp = updatedTemp;
}
}
/* Alter code above this line */
return Thermostat;
}
const Thermostat = makeClass();
const thermos = new Thermostat(76); // setting in Fahrenheit scale
let temp = thermos.temperature; // 24.44 in C
thermos.temperature = 26;
temp = thermos.temperature; // 26 in C
|
describe("@deprecated tag", function() {
var docSet = jasmine.getDocSetFromFile('test/fixtures/deprecatedtag.js'),
foo = docSet.getByLongname('foo')[0],
bar = docSet.getByLongname('bar')[0];
it('When a symbol has a @deprecated tag with no value, the doclet has a deprecated property set to true.', function() {
expect(foo.deprecated).toBe(true);
});
it('When a symbol has a @deprecated tag with a value, the doclet has a deprecated property set to that value.', function() {
expect(bar.deprecated).toBe('since version 2.0');
});
});
|
var router = require('express').Router()
var ServerInfo = require('../../models/server_info')
router.get('/server_info', function (req, res, next) {
console.log("server_info get 1")
ServerInfo.find()
.sort('-date')
.exec(function (err, server_list) {
if (err) { return next(err) }
res.json(server_list)
})
})
router.post('/server_info', function (req, res, next) {
console.log("server_info post 1")
// todo: get scalechain account and merge info and save
var server = new ServerInfo({servername: req.body.servername,
option: req.body.option})
server.serverid = "serverid test"
console.log("save info %s %s %s", server.servername, server.option, server.serverid)
server.save(function (err) {
if (err) { return next(err) }
res.sendStatus(201)
})
})
module.exports = router
|
//console.log(window.angular) shows that angular is an object in the root scope
var myApp = angular.module('myApp', []);
//console.log(myApp);
//the controller method creates a controller that belongs to myApp
//we pass controller an anonymous function
//$scope is the object that glues the view and controller together
//myController has access to everything inside $scope
myApp.controller('myController', function($scope){
//$scope.first = "Keith";
//$scope.last = "Moore";
$scope.cities = [
{
name: 'Atlanta',
population: 500000
},
{
name: 'Houston',
population: 2200000
},
{
name: 'Portland',
population: 610000
}
];
})
|
self.__precacheManifest = (self.__precacheManifest || []).concat([
{
"revision": "15aa246d0f39069386538f346fa61012",
"url": "/index.html"
},
{
"revision": "ccebc16b1851dfde4af4",
"url": "/static/js/2.3e72e2ad.chunk.js"
},
{
"revision": "bbe46e138f5b46e95769",
"url": "/static/js/main.973de4a5.chunk.js"
},
{
"revision": "ba78efeb6a6cf079e0e4",
"url": "/static/js/runtime-main.39352176.js"
}
]);
|
/*
所有路由配置的数组
路由组件懒加载:
1). 在打包时路由组件会被单独打包(代码分割: code split)
2). 默认不请求加载路由组件打包文件, 当请求需要路由组件时才请求加载
1. import动态引入:
import(模块路径)
结果: 被引入的模块会被单独打包(代码分割: code split)
2. 配置的路由组件是函数(返回动态加载的路由组件模块)
函数开始是不执行(开始不请求加载单独打包的路由组件模块代码)
当请求对应路径需要显示组件界面时, 去加载路由组件打包文件
作用: 减小首屏需要加载的js文件 ==> 显示更快
*/
import GoodDetail from '../components/GoodDetail/GoodDetail.vue'
import Imgs from '../components/GoodDetail/Imgs.vue'
import Parameter from '../components/GoodDetail/Parameter.vue'
import Questions from '../components/GoodDetail/Questions.vue'
import Search from '../pages/search/search.vue'
// 必买清单
import MustBuy from '../pages/mustBuy/mustBuy.vue'
import CareChoice from '../pages/mustBuy/channel/channel.vue'
import CoolMachine from '../pages/mustBuy/channel/phone.vue'
import Electrics from '../pages/mustBuy/channel/electrics.vue'
import Supermarket from '../pages/mustBuy/channel/supermarket.vue'
import Closes from '../pages/mustBuy/channel/closes.vue'
import Category from '../pages/category/category.vue'
import Detail from '../pages/mustBuy/channel/detail.vue'
import Home from '../pages/Home/Home.vue'
import Profile from '../pages/profile/profile.vue'
import Setup from '../pages/SetUp/SetUp.vue'
import ShopCart from '../pages/ShopCart/ShopCart.vue'
import Login from '../pages/Login/login.vue'
import Centre from '../pages/CouponCentre/centre.vue'
import Profit from '../pages/profit/recommend.vue'
//领券中心下级
import Persons from '../pages/CouponCentre/Persons.vue'
import CartList from '../pages/CartList/CartList.vue'
export default [
{
path:'/home',
component:Home,
meta: {
isShowFooter: true
}
},
{
path:'/home/money',
component:Profit
},
{
path:'/home/centre',
component:Centre,
},
{
path:'/home/centre/persons',
component:Persons
},
{
path:'/category',
component: Category,
meta: {
isShowFooter: false
}
},
{
path:'/mustBuy/careChoice/:id',
props:true,
component: Detail,
},
{
path:'/mustBuy',
component: MustBuy,
meta: {
isShowFooter: true
},
children:[
{
path:'careChoice',
component: CareChoice,
meta: {
isShowFooter: true
}
},
{
path:'coolMachine',
component: CoolMachine,
meta: {
isShowFooter: true
}
},
{
path:'electrics',
component: Electrics,
meta: {
isShowFooter: true
}
},
{
path:'supermarket',
component: Supermarket,
meta: {
isShowFooter: true
}
},
{
path:'closes',
component: Closes,
meta: {
isShowFooter: true
}
},
{
path:'',
redirect: 'careChoice',
meta: {
isShowFooter: true
}
}
]
},
{
path:'/shopcart',
component: ShopCart,
meta: {
isShowFooter: true
}
},
{
path:'/cartlist',
component: CartList
},
{
path:'/profile',
component: Profile,
meta: {
isShowFooter: true
}
},
{
path:'/setup',
component: Setup,
},
{
path:'',
redirect: '/home',
},
{
path:'/search',
component: Search,
},
{
path:'/login',
component: Login,
},
{
path:'/home/gooddetail/:id',
props:true,
component: GoodDetail,
children:[
{
path:'imgs',
component: Imgs,
},
{
path:'parameter',
component: Parameter,
},
{
path:'questions',
component:Questions,
},
{
path:'',
redirect: 'imgs',
}
]
},
// {
// path:'/gooddetail',
// component: GoodDetail,
// children:[
// {
// path:'imgs',
// component: Imgs,
// },
// {
// path:'parameter',
// component: Parameter,
// },
// {
// path:'questions',
// component:Questions,
// },
// {
// path:'',
// redirect: 'imgs',
// }
// ]
// }
]
// // name: 'shop',
// // path: '/shop/:id',
// // props: true, // 将所有params参数转换成标签属性传递给子路由组件
// // // props: toRoute => ({id: toRoute.params.id})
// // component: Shop,
// // // children: [
// // // {
// // // path: 'goods',
// // // component: Goods
// // // },
// ]
|
import { SET_USERS, SET_REASONS, SET_SELECTED_EMPLOYEE, SET_SELECTED_REASON } from '../constants/action-types';
import { SET_VISITOR, ADD_MESSAGE, CLAER_EXPIREDMESSAGES, CLAER_READMESSAGES } from '../constants/action-types';
export const setUsers = users => {
return {
type: SET_USERS,
users
}
}
export const setReasons = reasons => {
return {
type: SET_REASONS,
reasons
}
}
export const setSelectedEmployee = employee => {
return {
type: SET_SELECTED_EMPLOYEE,
employee
}
}
export const setSelectedReason = reason => {
return {
type: SET_SELECTED_REASON,
reason
}
}
export const setVisitor = visitor => {
return {
type: SET_VISITOR,
visitor
}
}
export const addMessage = message => {
return {
type: ADD_MESSAGE,
message
}
}
export const clearExpiredMessages = () => {
return {
type: CLAER_EXPIREDMESSAGES,
}
}
export const clearReadMessages = (user_id) => {
return {
type: CLAER_READMESSAGES,
user_id
}
}
|
import React from 'react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faBell } from '@fortawesome/free-solid-svg-icons'
import 'bootstrap/dist/css/bootstrap.css';
import {
Collapse,
Navbar,
NavbarBrand,
NavbarToggler,
Nav,
NavItem,
Button, UncontrolledPopover, PopoverHeader, Popover, PopoverBody
} from "reactstrap";
class Message extends React.Component {
constructor(props) {
super(props);
console.log("props",this.props.message)
this.state = {
message:this.props.message,
type:this.props.type
}
}
render(){
let msg=this.state.message
var style={
backgroundColor:this.state.color,
}
return(
<div >
<p className={this.props.type} style={{color:"#FFFFFF"}}>{this.props.message}</p>
</div>
)
}
}
export default Message;
|
SubComponent={(row) => {
return (
data.map((company,i)=>{
return company.brands.map((brand, i)=>{
return <div key={i}>{brand.brandName}</div>
})
})
)
}}
{
expander: true
},
row.original.brands.map((brand, i)=>{
return <div key={i}>{brand.brandName}</div>
})
expanded={{ // The nested row indexes on the current page that should appear expanded
0: false,
1: true,
}}
const filterCaseInsensitive = (filter, row) => {
const id = filter.pivotId || filter.id;
return (
row[id] !== undefined ?
String(row[id].toLowerCase()).startsWith(filter.value.toLowerCase())
:
true
);
};
import React, { Component } from 'react';
import ReactTable from 'react-table'
import CheckboxParent from './CheckboxParent.js'
export default class TurnerReactTable extends Component {
constructor(props){
super(props)
this.state = {
searchBrand: '',
searchLocation:'',
searchCategory:''
}
}
handleBrandSearch(e){
this.setState({
searchLocation: '',
searchBrand: e.target.value,
searchCategory: ''
});
}
handleLocationSearch(e){
this.setState({
searchLocation: e.target.value,
searchBrand: '',
searchCategory: ''
});
}
handleCategorySearch(e){
this.setState({
searchLocation: '',
searchBrand: '',
searchCategory: e.target.value
});
}
render() {
let data = [];
// search by name
if (this.state.searchBrand){
data = this.props.data.filter((row) => {
return row.name.toLowerCase().includes(this.state.searchBrand.toLowerCase())
})
}
// search by location
if (this.state.searchLocation){
data = this.props.data.filter((row) => {
return row.location.toLowerCase().includes(this.state.searchLocation.toLowerCase())
})
}
// search by category status
if (this.state.searchCategory){
data = this.props.data.filter((row)=>{
return row.category.includes(this.state.searchCategory)
})
}
const companyColumns = [{
expander: true,
width: 50
}, {
Header: 'Name',
accessor: 'name', // String-based value accessors!
Cell: props => <span className='number'> <input type="checkbox"/> {props.value}</span> ,
width: 500,
}, {
Header: 'Type',
accessor: 'type',
Cell: props => <span className='number'>{props.value}</span>, // Custom cell components!
filterable: false
}, {
Header: 'Location',
accessor: 'location',
Cell: props => <span className='number'>{props.value}</span>,
sortable: false // Custom cell components!
}, {
Header: 'Version',
accessor: 'version',
Cell: props => <span className='number'>{props.value}</span>, // Custom cell components!
filterable: false,
sortable: false
}, {
Header: 'Category',
accessor: 'category',
Cell: props => <span className='number'>{props.value}</span>, // Custom cell components!
filterable: false,
sortable: false
}, {
Header: 'Published',
accessor: 'published', // Custom value accessors!
},{
width: 65,
filterable: false,
sortable: false
}]
const brandColumns = [{
width: 50
}, {
accessor: 'brandName', // String-based value accessors!
Cell: props => <span style={{ paddingLeft: "20px" }} className='number'><input type="checkbox"/> {props.value}</span> ,
width: 500,
sortable: false
}, {
accessor: 'type',
Cell: props => <span className='number'>{props.value}</span>, // Custom cell components!
filterable: false,
sortable: false
}, {
accessor: 'countryName',
Cell: props => <span className='number'>{props.value}</span>,
sortable: false, // Custom cell components!
}, {
accessor: 'version',
Cell: props => <span className='number'>{props.value}</span>, // Custom cell components!
filterable: false,
sortable: false
}, {
accessor: 'category',
Cell: props => <span className='number'>{props.value}</span>, // Custom cell components!
filterable: false,
sortable: false
}, {
accessor: 'published', // Custom value accessors!
}, {
expander: true,
width: 65,
Expander: ({ isExpanded, ...rest }) =>
<div>
{isExpanded
? <span>⊙</span>
: <span>⊕</span>}
</div>,
style: {
cursor: "pointer",
fontSize: 25,
padding: "0",
textAlign: "center",
userSelect: "none"
}
}]
return (
<div>
<div>
<input value={this.state.searchBrands}
onChange={(e)=>{this.handleBrandSearch(e)}}
placeholder="Search Brands"
style={{height: "30px", width: "200px", fontSize:"1em"}}
/>
<input value={this.state.searchLocation}
onChange={(e)=>{this.handleLocationSearch(e)}}
placeholder="Search Location"
style={{height: "30px", width: "200px", fontSize:"1em"}}
/>
<select
onChange={(e)=>{this.handleCategorySearch(e)}}
>
<option value="all">Show All</option>
<option value="Company">Company</option>
<option value="Brand">Brand</option>
</select>
</div>
<ReactTable
defaultPageSize={10}
data={data}
columns={companyColumns}
SubComponent={(row) => {
return (
<ReactTable
showPaginationBottom={false}
defaultPageSize={row.original.brands.length}
data={row.original.brands}
columns={brandColumns}
SubComponent={(row) => {
console.log('row', row)
return (
<div style={{padding: "20px 20px 20px 50px", border:"solid black 1px",}}>
Run new affinio report on @{row.original.brandName}
</div>
) }}
/>
)
}}
/>
</div>
)
}
}
|
import firebase from 'firebase';
import '@firebase/firestore';
import {
FETCH_ATTR_SUCCESS,
ATTR_NAME_CHANGED,
ATTR_ADD_NEW_SUCCESS,
OPEN_ADD_ATTR_DIALOG,
CLOSE_ADD_ATTR_DIALOG,
ERROR_ADD_ATTR_CHANGED,
ADDING_NEW_ATTR,
REMOVE_ATTR
} from './types';
export const attributeFetch = () => async dispatch => {
const { currentUser } = firebase.auth();
let db = firebase.firestore();
let data = [];
db.collection('users').doc(`${currentUser.uid}`).collection('attributes').get()
.then((querySnapshot) => {
querySnapshot.forEach((doc) => {
data.push({ id: doc.id, name: doc.data().name })
});
dispatch({ type: FETCH_ATTR_SUCCESS, payload: data });
})
.catch((err) => {
console.log(err);
});
}
export const attrNameChange = (text) => {
return {
type: ATTR_NAME_CHANGED,
payload: text
};
}
export const openAddAttrModal = () => {
return {
type: OPEN_ADD_ATTR_DIALOG
}
}
export const closeAddAttrModal = () => {
return {
type: CLOSE_ADD_ATTR_DIALOG
}
}
export const addNewAttribute = (value) => (dispatch) => {
dispatch({ type: ADDING_NEW_ATTR });
const { currentUser } = firebase.auth();
let db = firebase.firestore();
let data = {
name: value
};
db.collection('users').doc(`${currentUser.uid}`).collection('attributes').add(data)
.then((docRef) => {
let data2 = { id: docRef.id, name: value }
dispatch({ type: ATTR_ADD_NEW_SUCCESS, payload: data2 });
})
.catch((err) => {
console.log(err);
})
}
export const addAttrError = (error) => {
return {
type: ERROR_ADD_ATTR_CHANGED,
payload: error
}
}
export const deleteAttr = (id, array) => (dispatch) => {
const { currentUser } = firebase.auth();
let db = firebase.firestore();
db.collection('users').doc(`${currentUser.uid}`).collection('attributes').doc(id).delete()
.then(() => {
dispatch({ type: REMOVE_ATTR, payload: array });
})
}
|
export const robots = [
{
id: 1,
name: 'Desmend Jetton',
username: 'DThug',
email: 'desmendjetton@gmail.com'
},
{
id: 2,
name: 'Jak Lak',
username: 'vames',
email: 'ruuuglleee@gmail.com'
},
{
id: 3,
name: 'Desmend Jetton',
username: 'DThug',
email: 'desmendjetton@gmail.com'
},
{
id: 4,
name: 'Desmend Jetton',
username: 'DThug',
email: 'desmendjetton@gmail.com'
},
{
id: 5,
name: 'Desmend Jetton',
username: 'DThug',
email: 'desmendjetton@gmail.com'
},
{
id: 6,
name: 'Desmend Jetton',
username: 'DThug',
email: 'desmendjetton@gmail.com'
},
{
id: 7,
name: 'Desmend Jetton',
username: 'DThug',
email: 'desmendjetton@gmail.com'
},
]
|
var GeneralScheduleView = Backbone.View.extend({
events: {
'click .close-sched-modal': function (e) {
sessionStorage.setItem('genSched', 'closed');
},
'click a#appl-form-city': 'bring_appl_form',
'click .collapsable-free-ev': function (e) {
$('.collapse').collapse('toggle');
}
},
bring_appl_form: function(event) {
event.preventDefault();
App.renderApplicationForm();
$("#applicationmodal").modal();
},
welcome: function() {
return choose_language("Schedule of all activities & classes", "ตารางสำหรับชั้นเรียนและกิจกรรมทั้งหมด");
},
description_of_free: function() {
return choose_language("Description of free activities", "คำอธิบายสำหรับกิจกรรมฟรี");
},
list_title: function() {
return choose_language("List of class sessions...", "รายการชั้นเรียน...");
},
please_click_here: function() {
return choose_language("Description of these classes", "คำอธิบายสำหรับชั้นเรียนเหล่านี้");
},
sorted_class_times: function() {
return this.collection.toJSON().sort(function(a, b) {
return a.order_no - b.order_no;
});
},
class_times: function() {
var using_thai_language = thai_language();
var class_time_list = [];
this.sorted_class_times().forEach(function(time) {
if (using_thai_language) {
class_time_list.push(time.period_thai);
} else {
class_time_list.push(time.period);
}
});
return class_time_list;
},
template: HandlebarsTemplates['front/general_schedule'],
render: function() {
this.$el.html(this.template({
thai_language: thai_language(),
welcome: this.welcome(),
description_of_free: this.description_of_free(),
list_title: this.list_title(),
please_click_here: this.please_click_here(),
class_times: this.class_times()
}));
return this;
}
});
|
//[COMMENTS]
//myVar should equal 10
//Use the -- operator on myVar
//Do not change code above the line
//[COMMENTS]
var myVar = 11;
// Only change code below this line
//Changed the initial line of myVar = myVar - 1; to the line below
myVar--;
|
const app = require('../src/app')
describe('App', () => {
it('GET / responds with 200 containing "Hey now, it works!"', () => {
return supertest(app).get('/').expect(200, 'Hey now, it works!')
})
})
|
Key.init(document);
Origami.canvas = document.getElementById("c");
Mouse.init(window, document.getElementById("c"));
var Game = {};
Game.isPaused = false;
Game.friction = 0.96;
Game.acceleration = 0.2;
Game.turnSpeed = 0.007;
Game.camDist = 60;
Game.log = "";
Game.raceTime = 0;
Game.hero = new Kart(3, 1, Origami.world.shapes[0]);
Game.opponents = [
new Kart(1, 1, Origami.world.shapes[1]),
new Kart(1, 3, Origami.world.shapes[2]),
new Kart(1, 3, Origami.world.shapes[3]),
new Kart(1, 3, Origami.world.shapes[4]),
new Kart(1, 3, Origami.world.shapes[5]),
new Kart(1, 3, Origami.world.shapes[6]),
new Kart(1, 3, Origami.world.shapes[7])
];
Game.cam = {};
Game.gui = {};
Game.state = "spiral";
Game.ai = function(kart, time){
kart.nextWaypoint = kart.nextWaypoint || 0;
var waypoint = Origami.world.mode7.track.waypoints[kart.nextWaypoint];
var dx = waypoint.x - kart.shape.x;
var dz = waypoint.y - kart.shape.z;
var dr = Math.atan2(dx, dz);
dr = kart.shape.ry - dr;
if(dr > Math.PI){
dr -= Math.PI*2;
}
var steer = Math.floor(dr/Math.PI/60);
//console.log(kart.nextWaypoint+" dr: "+kart.shape.ry + " -- " + dr + " => "+steer);
kart.step(1, steer, 0, time);
kart.move();
var prevWaypoint = Origami.world.mode7.track.waypoints[(kart.nextWaypoint || Origami.world.mode7.track.waypoints.length) - 1];
var v1 = new Vector(kart.shape.x - prevWaypoint.x, kart.shape.z - prevWaypoint.y);
var v2 = new Vector(waypoint.x - prevWaypoint.x, waypoint.y - prevWaypoint.y);
if(v1.projectOnto(v2) >= v2.length()){
kart.nextWaypoint = (kart.nextWaypoint + 1)%Origami.world.mode7.track.waypoints.length;
}
};
Game.doFrameReady = function(time){
if(Game.state == "spiral"){
Game.spiralCamera(time);
}else if(Game.state == "countdown"){
Game.countdown(time);
}else if(Game.state == "playing"){
if(Key.isPressed(13)){
Game.isPaused = !Game.isPaused;
}else if(time > 1000){
Game.isPaused = true;
}
if(Game.isPaused){
Game.pausedScreen(time);
}else{
Game.playGame(time);
}
}
Origami.render();
var w = Origami.world.images.background.image.width;
Origami.ctx.globalCompositeOperation = "destination-over";
Origami.ctx.drawImage(Origami.world.images.background.image, w/2 - w/2*(Game.cam.ry%(Math.PI*2))/Math.PI/2+240, 0, 240, 160, 0, 0, 240, 160);
Origami.ctx.globalCompositeOperation = "source-over";
Game.gui.render(Origami.ctx);
FPS.frameComplete();
}
Game.spiralCamera = function(time){
Game.cam.ry += time/1000;
if(Game.cam.ry < Game.hero.shape.ry){
Game.cam.z = Game.hero.shape.z - Math.cos(Game.cam.ry)*(1.5*(Game.hero.shape.ry - Game.cam.ry) + 1)*Game.camDist;
Game.cam.y = Game.hero.shape.y + 17 + (Game.hero.shape.ry - Game.cam.ry)*5;
Game.cam.x = Game.hero.shape.x - Math.sin(Game.cam.ry)*(1.5*(Game.hero.shape.ry - Game.cam.ry) + 1)*Game.camDist;
}else{
Game.cam.ry = Game.hero.shape.ry;
Game.cam.z = Game.hero.shape.z - Math.cos(Game.cam.ry)*Game.camDist;
Game.cam.y = 17;
Game.cam.x = Game.hero.shape.x - Math.sin(Game.cam.ry)*Game.camDist;
Game.state = "playing";
}
}
Game.countdown = function(time){
Game.countdown.timeLeft = Game.countdown.timeLeft || 3000;
Game.countdown.timeLeft -= time;
};
Game.drawTime = function(){
function twoDigits(val){
if(val < 10){
return "0"+val;
}else{
return (val+"").substr(-2);
}
}
var hundreds = Math.round(Game.raceTime/10);
var seconds = Math.round(hundreds/100);
var minutes = Math.round(seconds/60);
Game.gui.drawText(minutes+"="+twoDigits(seconds)+"<"+twoDigits(hundreds), Origami.canvas.width - 9*8, 8);
};
Game.pausedScreen = function(time){
Game.gui.drawText("hit enter to unpause", 40, 64);
}
Game.playGame = function(time){
Game.raceTime += time;
Game.drawTime( );
Game.hero.step(Key.isDown(38), Key.isDown(39) - Key.isDown(37), Key.isDown(40), time);
Game.hero.hitTestAndMove(Origami.world.mode7.track.walls, Origami.world.shapes);
Game.cam.ry = Game.hero.shape.ry;
Game.cam.z = Game.hero.shape.z - Math.cos(Game.cam.ry)*Game.camDist*(1+Game.hero.velocity/30);
Game.cam.x = Game.hero.shape.x - Math.sin(Game.cam.ry)*Game.camDist*(1+Game.hero.velocity/30);
for(var i in Game.opponents){
Game.ai(Game.opponents[i], time);
}
}
Origami.initWorld(function(){
Game.cam = Origami.cam;
Game.gui = new GUI(Origami.ctx, Origami.world.images.text.image);
Animation.start(Game.doFrameReady);
Origami.canvas.style.width = window.innerWidth + "px";
Origami.canvas.style.height = Origami.canvas.height/Origami.canvas.width*window.innerWidth + "px";
});
|
let count = 180;
let saygac=0;
let basla=0;
let san=0;
let gun=0;
let deq=0;
let saat=0;
let div = document.getElementsByTagName("div")[0];
CountDown();
let time = setInterval(CountDown,1000);
function CountDown(){
div.innerHTML = basla+" saniye ="+ gun+ " gun "+saat+" saat "+deq+" deq "+san+" san ";
if(san!=0){
san--;
}
else{
san=59;
if(deq!=0){
deq--;
}
else{
deq=59;
if(saat!=0){
saat--;
}
else{
saat=23;
if(gun!=0)
{
gun--;
}
}
}
}
saygac++;
if(saygac==(basla+2)){
clearInterval(time);
}
}
this.onload=()=>{
basla=count;
gun= Math.floor(count/86400);
count=Math.abs(count-(86400*gun));
saat= Math.floor(count/3600);
count=Math.abs(count-(3600*saat));
deq= Math.floor(count/60);
count=Math.abs(count-(60*deq));
san=count;
}
|
/* begin copyright text
*
* Copyright © 2016 PTC Inc., Its Subsidiary Companies, and /or its Partners. All Rights Reserved.
*
* end copyright text
*/
/* jshint node: true */
/* jshint strict: global */
'use strict';
var debug = require('debug')('vxs:auth.ptc');
var lodash = require('lodash');
var soap = require('soap');
var url = require('url');
var performanceMetrics = require('../routes/handlers/performanceMetrics.js');
var namespace = require("../lib/namespace");
var acctServiceConfig = {
hostname: 'apps.ptc.com',
path: '/accountServices/PtcAccountService?wsdl',
protocol: 'https',
//need this so WSDL accepts the method name without xml namespace prefix
wsdlOptions: {
ignoredNamespaces: {
namespaces: [],
override: true
}
},
cacheEntryTTL: 100
};
module.exports.authenticateUser = function(req, username, pw, done) {
soap.createClient(acctServiceConfig.url, acctServiceConfig.wsdlOptions, function(err, client){
if (err){
debug("soap client creation failed", err);
performanceMetrics.increment('ves.auth.checkPtcUser.failed', req.namespaceId);
return done(null, null);
}
client.addHttpHeader('Connection', 'keep-alive');
var credentials = {
"uid" : username,
"pw" : pw
};
//Use isPassword method of PtcAccountService WSDL
client.isPassword(credentials, function(err, result, body) {
if (err) {
debug("authentication request failed with error", err);
performanceMetrics.increment('ves.auth.checkPtcUser.failed', req.namespaceId);
return done(null, null);
} else {
debug ("Soap authentication result", result);
//result should be a json object as follows:
//{"return": true} if authentication succeeded
//{"return": false} if authentication failed
if ( result.return === true ){
namespace.authenticate(req, username, function(err) {
if (err) {
performanceMetrics.increment('ves.auth.checkPtcUser.failed', req.namespaceId);
if (req.trySelfRegistration){
return done(err);
}
return done(null, null);
}
performanceMetrics.increment('ves.auth.checkPtcUser.success', req.namespaceId);
performanceMetrics.set('ves.auth.ptcUserSet', username, req.namespaceId);
debug("PTC auth succeeded: %s", username);
done(null, username);
});
} else {
performanceMetrics.increment('ves.auth.checkPtcUser.failed', req.namespaceId);
return done(null, null);
}
}
});
});
};
module.exports.init = function(authConfig) {
acctServiceConfig = lodash.defaultsDeep({}, authConfig, acctServiceConfig);
debug("PTC Account Services configuration: %j", acctServiceConfig);
var urlObject = {protocol: acctServiceConfig.protocol, host: acctServiceConfig.hostname, port: acctServiceConfig.port};
acctServiceConfig.url = url.format(urlObject) + acctServiceConfig.path;
debug("Using PTC Account Services url: ", acctServiceConfig.url);
};
module.exports.processSession = function(auth) {
return auth;
};
module.exports.getCacheEntryTTL = function() {
return acctServiceConfig.cacheEntryTTL;
};
module.exports.useCache = function() {
return acctServiceConfig.useCache;
};
|
const program = require('commander');
const util = require('./util');
program
.description('Use your current HMAC key to generate a new HMAC Key')
.option('-n, --nickname <nickname>', '(optional) Nickname to give your new HMAC key')
.option('-p, --permissionsDocument <permissionsDocument>', '(optional) JSON permissions document to use with this new key')
.parse(process.argv);
util.wrapper(program, async client => {
const { nickname, permissionsDocument } = program;
let permissionDocumentJSON = undefined;
if (permissionsDocument) permissionDocumentJSON = JSON.parse(permissionsDocument);
const response = await client.createApiKey(util.removeUndefined({ nickname, permissionsDocument: permissionDocumentJSON }));
console.log(JSON.stringify(response, null, 2));
});
|
import React from 'react';
import { Meteor } from 'meteor/meteor';
import AppNavigation from '../containers/app-navigation';
export class App extends React.Component {
propTypes: {
children: React.PropTypes.element.isRequired,
}
render(){
return(
<div id="app">
<AppNavigation />
<div className="main-container">
{this.props.children}
</div>
</div>
);
}
}
|
var React = require("react"),
Authentication = require('./components/login/requireAuth'),
auth = require('./components/login/auth');
var Dashboard = React.createClass({displayName: "Dashboard",
mixins: [ Authentication ],
render: function () {
var token = auth.getToken();
/* jshint ignore:start */
return (
<div>
<Link to="logout"><Translate trKey="template.links.logOut" /></Link>
<h1>Dashboard</h1>
<p>You made it!</p>
</div>
);
/* jshint ignore:end */
}
});
module.exports = Dashboard;
|
/**
* Angular Settings page controller.
*
* User: Jhonny Ventiades<jhonny.ventiadesg@gmail.com>
* Date: 2014-08-01
*/
angular.module('studyaAPP')
.factory('Teachers', function ($resource) {
return $resource('/api/teachers/:id',
{}, { //parameters default
getAll: {
method: 'GET',
params: {
id:'@id'
},
isArray:true
}
});
});
angular.module('studyaAPP')
.factory('TeachersAll', function ($resource) {
return $resource('/api/teachers',
{}, { //parameters default
post: {
method: 'POST'
}
});
});
|
import { reactive } from "vue";
import { makeFilterForObjectsInsideArray } from "../../../root/functions/makeFilterForObjectsInsideArray";
import { makeFilterForStringProperty } from "../../../root/functions/makeFilterForStringProperty";
const columns = {
email: "",
emsAgenciesAdministered: "",
emsAgencyMemberships: "",
hospitalMemberships: "",
hospitalsAdministered: "",
name: "",
username: "",
};
const makeFilter = () => {
const emsAgenciesAdministeredFilter = makeFilterForObjectsInsideArray({
arrayPropertyName: "emsAgenciesAdministered",
itemPropertyName: "name",
string: filtering.columns.emsAgenciesAdministered,
});
const emsAgencyMembershipsFilter = makeFilterForObjectsInsideArray({
arrayPropertyName: "emsAgencyMemberships",
itemPropertyName: "name",
string: filtering.columns.emsAgencyMemberships,
});
const emailFilter = makeFilterForStringProperty({
string: filtering.columns.email,
});
const hospitalMembershipsFilter = makeFilterForObjectsInsideArray({
arrayPropertyName: "hospitalMemberships",
itemPropertyName: "name",
string: filtering.columns.hospitalMemberships,
});
const hospitalsAdministeredFilter = makeFilterForObjectsInsideArray({
arrayPropertyName: "hospitalsAdministered",
itemPropertyName: "name",
string: filtering.columns.hospitalsAdministered,
});
const nameFilter = makeFilterForStringProperty({
string: filtering.columns.name,
});
const usernameFilter = makeFilterForStringProperty({
string: filtering.columns.username,
});
return (user) =>
usernameFilter(user.username) &&
nameFilter(`${user.firstName} ${user.lastName}`) &&
emailFilter(user.email) &&
hospitalsAdministeredFilter(user) &&
hospitalMembershipsFilter(user) &&
emsAgenciesAdministeredFilter(user) &&
emsAgencyMembershipsFilter(user);
};
export const filtering = reactive({
columns,
makeFilter,
});
|
var amqp = require( 'amqplib' )
var AMQP2Influx = function( processMessage ) {
var amqp2influx = this
this.amqp = amqp.connect( process.env.AMQP_URL ).then( function( connection ) {
connection.createChannel().then( function( channel ) {
amqp2influx.channel = channel
var queue = channel.assertQueue( process.env.AMQP_QUEUE_NAME, { durable: true } )
queue.then( function() {
channel.consume( process.env.AMQP_QUEUE_NAME, function(envelope) {
var message = JSON.parse(envelope.content)
processMessage( message, null, function() {
channel.ack( envelope )
})
}, { noAck: false } )
})
})
})
}
module.exports = AMQP2Influx
|
import React, { Component } from "react";
import "./Input.css";
import Loading from "../common/Loading";
import { withRouter } from "react-router-dom";
import { Button, Icon } from "semantic-ui-react";
const axios = require("axios");
class Input extends Component {
constructor() {
super();
this.state = {
item: {},
employee_code: 0,
loading: false
};
this.handleInputChange = this.handleInputChange.bind(this);
this.onChangeHandler = this.onChangeHandler.bind(this);
}
handleInputChange(event) {
const na = event.target.name;
const value = event.target.value;
const { item } = { ...this.state };
const currentState = item;
currentState[na] = value;
this.setState({ item: currentState });
}
onChangeHandler = () => {
this.setState({ loading: true });
axios
.post("http://localhost:5000/add", {
//id: Id,
name: this.state.item.name,
machine_no: this.state.item.machine_no,
employee_code: this.state.item.employee_code,
per_unit_weight: this.state.item.per_unit_weight,
units_to_order: this.state.item.units_to_order
})
.then(res => {
console.log(res);
if (res.data == "No") {
alert("Employee does not exist");
this.setState({ loading: false });
} else if (res.data.name == "MongoError") {
alert("Duplicate Shelf Number");
this.setState({ loading: false });
} else {
this.props.onClose();
}
//alert("Deleted the item : " + res.data);
})
.catch(e => {
console.log("Error in adding", e);
});
//console.log(this.state.item);
};
render() {
const { item, loading } = this.state;
if (loading) {
return (
<div className="loading-container">
<Loading />
</div>
);
}
return (
<div className="Input">
<h1 className="Input-heading">ENTER NEW SHELF DETAIL</h1>
<div className="Input-container">
<form>
<div className="Input-item">
<label>
Item:{" "}
<input
className="Input-value"
name="name"
//type="text"
onChange={this.handleInputChange}
/>
</label>
</div>
<div className="Input-item">
<label>
Shelf No:{" "}
<input
className="Input-value"
name="machine_no"
//type="text"
onChange={this.handleInputChange}
/>
</label>
</div>
<div className="Input-item">
<label>
Unit Weight:{" "}
<input
className="Input-value"
name="per_unit_weight"
//type="text"
onChange={this.handleInputChange}
/>
</label>
</div>
<div className="Input-item">
<label>
Units to Order:{" "}
<input
className="Input-value"
name="units_to_order"
//type="text"
onChange={this.handleInputChange}
/>
</label>
</div>
<div className="Input-item">
<label>
Employee Code:{" "}
<input
className="Input-value"
name="employee_code"
//type="text"
onChange={this.handleInputChange}
/>
</label>
</div>
<div className="Input-button">
<Button
animated
onClick={() => {
this.onChangeHandler();
}}
>
<Button.Content visible>Submit</Button.Content>
<Button.Content hidden>
<Icon
name="edit"
onClick={() => {
this.onChangeHandler();
}}
/>
</Button.Content>
</Button>
</div>
</form>
</div>
</div>
);
}
}
export default Input;
|
/* eslint-disable react/jsx-one-expression-per-line,jsx-a11y/anchor-is-valid */
import React from 'react'
import { colors } from 'config'
import Header from '.'
const Demo = () => (
<>
<h1>Header</h1>
<p>
The <em>Header</em> component applies theming to the HTML{' '}
<code>header</code> tag. By default, <em>Header</em> components contain
their children to the content width dictated by the theme.
</p>
<Header color="primary">default header</Header>
<h2>Fluid Prop</h2>
<Header color="secondary" fluid>
This header is fluid and does not confine its children to a center content
area.
</Header>
<h2>Color Prop</h2>
{colors.map(color => (
<Header color={color}>{color} header</Header>
))}
<h2>Padding Props</h2>
<p>
<em>Header</em>s accept <em>padding</em> props, but left and right padding
can only be set if the Block is also <em>fluid</em>.
</p>
<Header color="primary" padding="medium">
padded contained header
</Header>
<Header color="secondary" padding="medium" fluid>
padded fluid header
</Header>
</>
)
Demo.story = {
name: 'Header',
}
export default Demo
|
import React from 'react';
import './statusBar.css';
import Grid from '@material-ui/core/Grid';
function StatusBar(props){
return <Grid item className="d-flex StatusBar" md={2}>
<span className="mb-auto mx-auto"> Status </span>
</Grid>;
}
export default StatusBar;
|
var Booking = artifacts.require("./Booking.sol");
module.exports = function(deployer) {
deployer.deploy(Booking);
};
|
import React, { Component } from "react";
import Dialog from "@material-ui/core/Dialog";
import AppBar from "@material-ui/core/AppBar";
import { ThemeProvider as MuiThemeProvider } from "@material-ui/core/styles";
import Button from "@material-ui/core/Button";
import School from './School';
export class StudyForm extends Component {
continue = (e) => {
e.preventDefault();
this.props.nextStep();
};
back = (e) => {
e.preventDefault();
this.props.prevStep();
};
addSchool = (e) => {
e.preventDefault();
this.props.addSchool();
};
render() {
const { values, handleChange } = this.props;
return (
<MuiThemeProvider>
<>
<Dialog open fullWidth maxWidth="sm">
<AppBar title="Enter Education experience" />
{values.schools?.map((school,idx) => {
return (
<div className="school" key={'school'+idx} >
<h3>School {idx+1}</h3>
<School values={school} idx={idx} handleChange={handleChange}/>
</div>
)
})}
<br />
<Button color="primary" variant="contained" onClick={this.addSchool}>
Add school
</Button>
<br />
<Button color="secondary" variant="contained" onClick={this.back}>
Back
</Button>
<Button color="primary" variant="contained" onClick={this.continue}>
Continue
</Button>
</Dialog>
</>
</MuiThemeProvider>
);
}
}
export default StudyForm;
|
;(function(){
// 导航区定位
$(".mao").click(function(){
var sc_top=$(".sec"+$(this).index()+"").offset().top;
$("body,html").animate({"scrollTop":sc_top},500);
})
//当前时间
var nowtime=new Date();
var nowyear=nowtime.getFullYear();
$(".nowtime").html(nowyear);
})()
|
const s = {
"data":[
{
"s_id":"01",
"s_name":"赵雷",
"s_birth":"1990-01-01",
"s_sex":"男"
},
{
"s_id":"02",
"s_name":"钱电",
"s_birth":"1990-12-21",
"s_sex":"男"
},
{
"s_id":"03",
"s_name":"孙风",
"s_birth":"1990-05-20",
"s_sex":"男"
},
{
"s_id":"04",
"s_name":"李云",
"s_birth":"1990-08-06",
"s_sex":"男"
},
{
"s_id":"05",
"s_name":"周梅",
"s_birth":"1991-12-01",
"s_sex":"女"
},
{
"s_id":"06",
"s_name":"吴兰",
"s_birth":"1992-03-01",
"s_sex":"女"
},
{
"s_id":"07",
"s_name":"郑竹",
"s_birth":"1989-07-01",
"s_sex":"女"
},
{
"s_id":"08",
"s_name":"王菊",
"s_birth":"1990-01-20",
"s_sex":"女"
},
{
"s_id":"09",
"s_name":"张全蛋",
"s_birth":"2019-08-07 09:39:20",
"s_sex":"男"
},
{
"s_id":"10",
"s_name":"童利亚",
"s_birth":"2019-08-07 14:54:27",
"s_sex":"男"
},
{
"s_id":"11",
"s_name":"岳云鹏",
"s_birth":"2019-08-07 09:41:38",
"s_sex":"男"
},
{
"s_id":"12",
"s_name":"乔碧萝",
"s_birth":"1990-9-9",
"s_sex":"女"
}
]
}
|
ravApp.controller('ConfirmationControl', function($scope, $rootScope, $q, PeristentFactory) {
$scope.config={};
$scope.confirmationPos = {};
function init() {
var defer = $q.defer();
PeristentFactory.allConfirmation().then(function(pos) {
$scope.confirmationPos = pos;
PeristentFactory.getConfig().then(function(config) {
$scope.config = angular.copy(config);
defer.resolve();
});
});
return $q.promise;
}
;
$scope.newConfirmation = function() {
currentConfirmation = {};
currentConfirmation.id = Math.random().toString().substr(2);
currentConfirmation.bewDay = new Date().getDate();
currentConfirmation.actMounth=$scope.config.actMounth;
currentConfirmation.isOpen=true;
currentConfirmation.isEmail=true;
currentConfirmation.isRav=false;
currentConfirmation.isFulltime=false;
currentConfirmation.isPersonal=false;
currentConfirmation.isPhone=false;
currentConfirmation.firmName="";
currentConfirmation.addresse="";
currentConfirmation.contact="";
currentConfirmation.phone="";
currentConfirmation.jobName="";
currentConfirmation.parttime="";
currentConfirmation.isInterview=false;
currentConfirmation.isJob=false;
currentConfirmation.isClosed=false;
currentConfirmation.ground="";
$rootScope.$broadcast('newConfirmation');
location = "#/app/confirmationNew";
};
$scope.editPos = function(pos) {
currentConfirmation=pos;
location = "#/app/confirmationEdit";
};
$scope.deletePos = function(pos){
PeristentFactory.deleteConfirmation(pos).then(function(records) {
$scope.confirmation=records;
$scope.apply;
});
};
$scope.$on('initConfirmation', function() {
init();
});
init();
});
|
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const GeomapSchema = new Schema({
});
module.exports = mongoose.model('Geomap', GeomapSchema);
|
// axios
import axios from 'axios'
import {
cacheAdapterEnhancer
} from 'axios-extensions';
import router from './router'
import store from './store/store'
const domain = process.env.MIX_API_DOMAIN;
axios.defaults.baseURL = domain;
axios.defaults.adapter = cacheAdapterEnhancer(axios.defaults.adapter, {
enabledByDefault: false,
});
axios.interceptors.response.use(function (response) {
// Do something with response data
return response;
}, function (error) {
// Do something with response error
if (router.currentRoute.name != "page-error") {
return router.push({
name: "page-error",
params: {
code: error.response.status,
message: error.response.data.message
}
});
}
});
// Add a request interceptor
axios.interceptors.request.use(
config => {
const token = store.getters['auth/token'];
if (token) {
config.headers['Authorization'] = 'Bearer ' + token;
}
return config;
},
error => {
Promise.reject(error)
});
export default axios
|
var bigimg = document.querySelector(".bigimg");
var bigpic = bigimg.querySelector(".big");
var bigtext = bigimg.querySelector(".bigtext");
var smallpic = document.querySelectorAll(".small");
for(var i = 0; i<smallpic.length; i++){
smallpic[i].addEventListener("click", changeimg);
}
function changeimg(){
var imgAttribute = this.getAttribute("src");
bigpic.setAttribute("src", imgAttribute);
var title = this.parentNode.querySelector(".text");
bigtext.innerHTML = title.innerText;
console.log(title.innerText);
}
|
const { description } = require("../package")
module.exports = {
markdown: {
lineNumbers: true,
extendMarkdown: md => {
// use more markdown-it plugins!
md.use(require("markdown-it-html5-embed"), {
html5embed: {
useImageSyntax: true, // Enables video/audio embed with ![]() syntax (default)
useLinkSyntax: true // Enables video/audio embed with []() syntax
}
})
}
},
base: "/",
title: "Speckle Docs",
description: description,
head: [
["meta", { name: "theme-color", content: "#0480FB" }],
["meta", { name: "apple-mobile-web-app-capable", content: "yes" }],
[
"meta",
{ name: "apple-mobile-web-app-status-bar-style", content: "black" }
],
[
"script",
{
src: "/scripts/scroll-to-hash.js"
}
]
],
/**
* Theme configuration, here is the default theme configuration for VuePress.
*
* ref:https://v1.vuepress.vuejs.org/theme/default-theme-config.html
*/
themeConfig: {
repo: "specklesystems/speckle-docs/",
docsBranch: "main",
editLinks: true,
editLinkText: "Edit this page",
docsDir: "",
sidebarDepth: 2,
activeHeaderLinks: false,
lastUpdated: true,
logo: "/assets/logo-docs.png",
algolia: {
apiKey: '4f23c1e333e0ff5c9e7e5cbb8a933749',
indexName: 'speckle'
},
nav: [
{
text: "User Guide",
link: "/"
},
{
text: "Developer Docs",
link: "/dev/"
},
{
text: "Speckle Website",
link: "https://speckle.systems"
},
//this button has custom style in index.styl under `.nav-item:last-child a`
{
text: "Get Started",
link: "https://speckle.systems/getstarted/"
}
],
sidebar: {
"/user/": [
{
title: "Quickstart 🏃♀️",
collapsable: false,
children: ["quickstart", "FAQs"]
},
{
title: "User Guide 🤷",
collapsable: false,
children: ["", "concepts", "concepts-advanced", "manager", "web"]
},
{
title: "Connectors 🔌",
collapsable: false,
children: [
"connectors",
"ui",
"revit",
"rhino",
"autocadcivil",
"grasshopper",
"dynamo",
"unity",
"unreal",
"blender",
"excel",
"support-tables"
]
},
{
title: "Tutorials ⚡",
collapsable: false,
children: [
"tutorials"
]
}
],
"/dev/": [
{
title: "Developer Docs 👩💻",
collapsable: false,
children: ["", "architecture"]
},
{
title: "Core Concepts",
collapsable: false,
children: ["base", "decomposition", "kits", "transports", "apps-auth"]
},
{
title: "Advanced Concepts",
collapsable: false,
children: []
},
{
title: ".NET SDK",
collapsable: false,
children: ["dotnet", "objects", "connectors-dev", "kits-dev", "transports-dev"]
},
{
title: "Python SDK",
collapsable: false,
children: ["python", "py-examples", "py-sample"]
},
{
title: "Javascript SDK",
collapsable: false,
children: ["js", "viewer", "js-app-script"]
},
{
title: "Server API & Apps",
collapsable: false,
children: ["server-api", "server-graphql-api", "server-rest-api", "server-webhooks", "server-setup", "server-manualsetup", "tokens", "apps"]
}
]
}
},
/**
* Apply plugins,ref:https://v1.vuepress.vuejs.org/zh/plugin/
*/
plugins: [
"@vuepress/plugin-back-to-top",
"@vuepress/plugin-medium-zoom",
[
"vuepress-plugin-matomo",
{
siteId: 5,
trackerUrl: "https://speckle.matomo.cloud/"
}
]
]
}
|
import React from 'react';
import './Comment.css';
const Comment = (props) => {
return(
<div className="comment user-comment">
<div className="info">
<p>{props.name}</p>
</div>
<p>{props.body}</p>
</div>
)
};
export default Comment;
|
const express = require('express');
const tourController = require('./../controllers/tourController');
const authController = require('./../controllers/authController');
const reviewController = require('./../controllers/reviewController');
const reviewRouter = require('./reviewRoutes')
const router = express.Router();
// // NESTED ROUTES
// // POST /:tourId/2541fr7/reviews
// // Get /:tourId/2541fr7/reviews
// // Get /:tourId/2541fr7/reviews/45651fg45
// router
// .route('/:tourId/reviews')
// .post(authController.protect, authController.restrictTo('user'), reviewController.createReviews)
// MergerParams
router.use('/:tourId/reviews', reviewRouter)
router
.route('/tour-stats')
.get(tourController.getTourStats);
router
.route('/montly-plan/:year')
.get(authController.protect,authController.restrictTo('admin','lead-guide','guide'),tourController.getMonthlyPlan);
router
.route('/top-5-cheap')
.get(tourController.aliasTopTours,tourController.getAllTours);
router.
route('/tours-within/:distance/center/:latlng/unit/:unit').get(tourController.getToursWithin)
router.
route('/distances/:latlng/unit/:unit').get(tourController.getDistances)
// or this /tours-distance?distance=233¢er=-40,45&unit=mi query string
// route /tours-distance/233/center/-40,45/unit/mi
router
.route('/')
.get( tourController.getAllTours)
.post(authController.protect,authController.restrictTo('admin','lead-guide'), tourController.createTour);
router
.route('/:id')
.get(tourController.getTour)
.patch(authController.protect,authController.restrictTo('admin','lead-guide'),tourController.uploadTourImage,tourController.resizeTourImage,tourController.updateTour)
.delete(authController.protect, authController.restrictTo('admin','lead-guide'), tourController.deleteTour);
module.exports = router;
|
const {unusualSpending} = require('./unusual-spending');
const {fetch} = require('./fetch');
const {categorize} = require('./categorize');
const {email} = require('./email');
jest.mock('./fetch');
jest.mock('./categorize');
jest.mock('./email');
describe('unusual spending test suite',() => {
it('canary show test infrastructure is working',() => {
expect(true).toBe(true);
});
it('orchestrates the collaboration between fetch, categorize and email',() => {
// Arrange
const userID = 'userID1';
const payments = [
{
month: { year: 2021, month: 3 },
payments: [
{ amount: 90, catagory: "golf" },
{ amount: 110, catagory: "dinner" },
{ amount: 180, catagory: "golf" },
{ amount: 140, catagory: "dinner" },
],
},
{
month: { year: 2021, month: 2 },
payments: [
{ amount: 80, catagory: "basketball" },
{ amount: 140, catagory: "bicycling" },
{ amount: 700, catagory: "basketball" },
{ amount: 150, catagory: "bicycling" },
],
},
];
const categorizedPayments = [
{
month: { year: 2020, month: 3 },
payments: [
{ amount: 270, catagory: "golf" },
{ amount: 250, catagory: "dinner" },
],
},
{
month: { year: 2020, month: 2 },
payments: [
{ amount: 780, catagory: "basketball" },
{ amount: 290, catagory: "bicycling" },
],
},
];
fetch.mockReturnValue(payments);
categorize.mockReturnValue(categorizedPayments);
// Act
unusualSpending(userID);
// Assert
expect(fetch).toHaveBeenCalledWith(userID);
expect(categorize).toHaveBeenCalledWith(payments);
expect(email).toHaveBeenCalledWith(userID, categorizedPayments);
});
});
|
import React, { useEffect, useState } from 'react';
import './style.css'
export const Song = (props)=>{
const [songs, setSongs] = useState([]);
const imageStyle = {
height:'100px',
width:'100px'
}
let singerName = props.singerName;
if(!singerName){
singerName = props.match.params.singerName;
}
console.log('Singer Name Rec is ', singerName);
useEffect(()=>{
let url = `${process.env.REACT_APP_SONG_URL}?name=${singerName}`;
const promise = fetch(url);
promise.then(response=>{
response.json().then(data=>{
console.log('Data is ', data);
setSongs(data);
}).catch(err=>{
console.log('JSON Error is ', err);
})
}).catch(err=>console.log("Error is ",err));
});
return (<>
<h3>Song of {singerName}</h3>
{songs.map(song=>{
return (<div className='song'>
<img src={song.imageurl} style={imageStyle}/>
<p>{song.name}</p>
<audio controls className='player'>
<source src={song.url} type="audio/mp4"></source>
</audio>
</div>)
})}
</>
)
}
|
module.exports = {
'GOOGLE_CLIENT_ID': '243768376855-vf41jnnki09nt8kcq4jfqlv2dt6gjl2m.apps.googleusercontent.com',
'GOOGLE_CLIENT_SECRET': 'PgtndxhHutlqG1K0O5dxn5BA',
'CALLBACK_URL': 'http://localhost:3000/auth/google/callback'
};
|
import React from "react";
import { Card } from "react-bootstrap";
const Question = ({ exam }) => {
return (
<Card>
<Card.Img
variant="bottom"
src={exam.question === undefined ? null : exam.question.imageBase64}
/>
<Card.Body>
<Card.Title>{exam.name}</Card.Title>
<Card.Text>{exam.description}</Card.Text>
</Card.Body>
</Card>
);
};
export default Question;
|
import React from 'react';
import { NavLink } from 'react-router-dom'
import PropTypes from 'prop-types';
import './Nav.css';
const Nav = ( { favorites, getCards } ) => {
const favNumber = favorites.length && favorites[0].type !== 'none'
? favorites.length
: 0
return (
<div className="button-container navbar">
<div className='button'>
<NavLink to='/people'
name="people"
className='people-btn'
onClick={() => getCards("people")}
>PEOPLE
</NavLink>
</div>
<div className='button'>
<NavLink to='/planets'
name="planets"
className='planets-btn'
onClick={() => getCards("planets")}
>PLANETS
</NavLink>
</div>
<div className='button'>
<NavLink to='/vehicles'
name="vehicles"
className='vehicles-btn'
onClick={() => getCards("vehicles")}
>VEHICLES
</NavLink>
</div>
<div className='button end'>
<NavLink to='/favorites'
name="favorites"
className='favorites-btn'
onClick={() => getCards("favorites")}
>FAVORITES
<div className='fav-cont'>
{favNumber}
</div>
</NavLink>
</div>
</div>
)
}
Nav.propTypes = {
getCards: PropTypes.func.isRequired,
favorites: PropTypes.array.isRequired
}
export default Nav;
|
const { timestampFormat } = require('./logFormat')
class LoggerCreator {
constructor(winston, logLevel, format) {
this.winston = winston;
this.logLevel = logLevel;
this.logger = null;
this.format = format;
this._init(this.winston, this.logLevel, this.format);
}
_init(winston, logLevel) {
this.logger = winston.createLogger({
logLevel,
format: this.format,
transports: [
new winston.transports.File({ filename: `${__dirname}/../../../../logs/${timestampFormat()}.log`})
]
});
}
log(message, path = "") {
if (this.logger === null) {
return;
}
if (typeof message !== "string" || message === "") {
return;
}
const timestamp = new Date().toLocaleTimeString();
const logLevel = this.logLevel;
this.logger.log({message, path, level: logLevel, timestamp});
}
}
module.exports.LoggerCreator = LoggerCreator;
|
var dialog_8c =
[
[ "dialog_find", "dialog_8c.html#ac18ab064a2131a8af6bfb93798162bfe", null ],
[ "dialog_push", "dialog_8c.html#a7c4678f81d8185d89e16e4befe94bb08", null ],
[ "dialog_pop", "dialog_8c.html#a82616808183352fb315931b2bb3518c0", null ],
[ "dialog_config_observer", "dialog_8c.html#a13d00da9aacc6d05b2444c747244597e", null ],
[ "dialog_create_simple_index", "dialog_8c.html#ab4301ef9e9e3760408861a398de176a9", null ],
[ "dialog_destroy_simple_index", "dialog_8c.html#a4f69c951431777334f8d18d38b9d643a", null ]
];
|
/**
* Created by KJain on 8/10/2016.
*/
var express = require('express');
var router = express.Router();
var mongo = require('../mongo');
/* GET Signup page. */
router.get('/', function(req, res, next) {
res.render('signup', {error: null});
});
function createUser(username, email, password, password_confirmation, callback) {
var col = mongo.collection('users');
if (password !== password_confirmation) {
var err = 'Passwords do not match';
callback(err);
}
else {
var query = { $or:
[
{username: username},
{email: email}
]};
var userObject = {
username: username,
email: email,
password: password,
notifications: []
};
// Making sure this username/email does not exist already
col.findOne(query, function(err, user){
if (user) {
if(user.username == username)
err = 'Username you entered already exists';
if(user.email == email)
err = 'Email you entered already exists';
callback(err);
} else {
// Create a new user
col.insertOne(userObject, function(err, user) {
//Indexing on the basis of username and email
col.createIndex({username: 1, email: 1});
callback(err, user.ops[0]);
});
}
});
}
}
router.post('/', function(req, res){
//Extracting user details from html form
var username = req.body.username;
var email = req.body.email;
var password = req.body.password;
var password_confirmation = req.body.password_confirmation;
createUser(username, email, password, password_confirmation, function(err, user){
if (err) {
res.render('signup', {error: err});
} else {
req.session.username = user.username;
res.redirect('/documents');
}
});
});
module.exports = router;
|
import React, { Component } from 'react';
import './main.css';
import Quaters from '../../Containers/appquaters/appquaters.js';
import Apphead from '../apphead/apphead.js';
export default class Main extends Component {
constructor(props) {
super(props);
}
componentDidMount() {
// let el = document.getElementById('main');
// var style = getComputedStyle(el);
// console.log(style.width);
}
render() {
return (
<div className='main' id = 'main'>
<Apphead text = 'MAIN PAGE APPLICATION'/>
<Quaters />
</div>
);
}
}
|
'use strict';
const eventData = require('../../data/events/portal_web');
const getEmergenciaLima = async (req, res, next) => {
try {
const eventlist = await eventData.emergenciaLima();
res.send(eventlist);
} catch (error) {
res.status(400).send(error.message);
}
}
const getQuirurgicoLima = async (req, res, next) => {
try {
const eventlist = await eventData.quirurgicoLima();
res.send(eventlist);
} catch (error) {
res.status(400).send(error.message);
}
}
const getAmbulatorioLima = async (req, res, next) => {
try {
const eventlist = await eventData.ambulatorioLima();
res.send(eventlist);
} catch (error) {
res.status(400).send(error.message);
}
}
const getEmergenciaChorrillos = async (req, res, next) => {
try {
const eventlist = await eventData.emergenciaChorrillos();
res.send(eventlist);
} catch (error) {
res.status(400).send(error.message);
}
}
const getQuirurgicoChorrillos = async (req, res, next) => {
try {
const eventlist = await eventData.quirurgicoChorrillos();
res.send(eventlist);
} catch (error) {
res.status(400).send(error.message);
}
}
const getAmbulatorioChorrillos = async (req, res, next) => {
try {
const eventlist = await eventData.ambulatorioChorrillos();
res.send(eventlist);
} catch (error) {
res.status(400).send(error.message);
}
}
const getEmergenciaSurco = async (req, res, next) => {
try {
const eventlist = await eventData.emergenciaSurco();
res.send(eventlist);
} catch (error) {
res.status(400).send(error.message);
}
}
const getQuirurgicoSurco = async (req, res, next) => {
try {
const eventlist = await eventData.quirurgicoSurco();
res.send(eventlist);
} catch (error) {
res.status(400).send(error.message);
}
}
const getAmbulatorioSurco = async (req, res, next) => {
try {
const eventlist = await eventData.ambulatorioSurco();
res.send(eventlist);
} catch (error) {
res.status(400).send(error.message);
}
}
module.exports = {
getEmergenciaLima,
getQuirurgicoLima,
getAmbulatorioLima,
getEmergenciaChorrillos,
getQuirurgicoChorrillos,
getAmbulatorioChorrillos,
getEmergenciaSurco,
getQuirurgicoSurco,
getAmbulatorioSurco
}
|
/*MONGO Connection-*/
var MongoClient = require('mongodb').MongoClient;
var Server = require('mongodb').Server;
//connection not yet established (syncronous)
var mongoclient = new MongoClient(new Server('localhost',27017,
{'native_parser':true} ));
var db = mongoclient.db('bds');
exports.index = function(req,res){
res.render('default');
console.log('ran');
}
exports.POget = function(req,res){
console.log('POed');
db.collection('PO').findOne({},
function(err, doc){
console.log(doc);
res.render('PO',doc);
});
}
var insertPO = function(db, callback) {
var collection = db.collection('documents');
collection.insert({test : 1},
function(err, result) {
assert.equal(err, null);
console.log("inserted");
callback(result);
}
);
}
/*// get the ten most recent PO's from mongo
var d;
var findDocuments = function(db, callback) {
var collection = db.collection('documents');
collection.find({}).limit(10).sort({date:1}).toArray(function(err,
docs){callback(docs);});}
moving this inside the exports.PO brokes it..
// but I don't need it for the other views
// so wth
MongoClient.connect(url,function(err,db){
console.log("connected to mongo!");
findDocuments(db,function(docs) { d = docs
db.close(); }) }
);
// documents from mongo in var d */
|
import React from 'react';
import axios from 'axios';
import utils from '../../general/components/utils';
import EditForm from '../components/EditForm';
import RedirectToProfile from '../../general/components/RedirectToProfile';
export default class Edit extends React.Component {
constructor() {
super()
this.state = {
username: '',
firstName: '',
lastName: '',
gender: '',
orientation: '',
location: '',
address: '',
bio: '',
avatar: '',
birthday: '',
photos: [],
tags: [],
updated: false
};
this.saveEdit = this.saveEdit.bind(this);
}
componentWillMount() {
const decoded = utils.decodedCookie();
if (decoded) {
axios.get(`/api/users/profile/${decoded.username}`).then(({data}) => {
if (data.success) {
this.setState({
username: data.userData.username,
firstName: data.userData.firstName,
lastName: data.userData.lastName,
gender: data.userData.gender,
orientation: data.userData.orientation,
location: data.userData.location,
birthday: data.userData.birthday,
avatar: data.userData.avatar,
bio: data.userData.bio,
photos: data.photos,
tags: data.tags
})
}
}).catch(err => console.error('Error: ', err));
}
}
saveEdit() {
// const user = Object.assign({}, this.state);
// axios.post('/api/users', user).then(({ data }) => {
// const { success, message } = data;
// if (success) {
// NotificationManager.success(message, 'Success !', 6000);
// this.setState({ updated: true });
// }
// else
// NotificationManager.error(message, 'Sorry but...', 6000);
// })
// .catch(err => console.error('Error: ', err));
}
saveState(name, value) {
this.setState({ [name]: value });
}
render() {
switch (this.state.updated) {
case true:
return <RedirectToProfile username={this.state.username} />;
default:
return (
<EditForm
user={this.state}
onSubmit={this.saveEdit}
onChange={this.saveState}
/>
);
}
}
}
|
import formatType from './formatType'
class Schema {
constructor(rule = {}, data = {}) {
Object.keys(rule).forEach((key) => {
const ruleItem = rule[key]
const dataItem = data[key]
const schemaData = this.schemaContext(ruleItem, dataItem)
const newdata = schemaData !== undefined ? schemaData : undefined
if (newdata !== undefined) {
data[key] = newdata
}
})
return data
}
// eslint-disable-next-line class-methods-use-this
ruleType(rule) {
if (typeof rule === 'string') {
return {
type: rule,
default: rule === 'string' ? '' : undefined
}
}
return rule
}
schemaContext(rule = {}, data) {
rule = this.ruleType(rule)
const type = formatType(data)
switch (rule.type) {
case 'array':
return this.schemaArray(rule, data)
case 'object':
return this.schemaObject(rule, data)
default:
return this.schemaDefault(type, rule, data)
}
}
schemaObject(rule = {}, data) {
rule = this.ruleType(rule)
if (formatType(data) === 'object') {
if (rule.children) {
Object.keys(rule.children).forEach((key) => {
const ruleItem = rule.children[key]
const dataItem = data[key]
data[key] = this.schemaContext(ruleItem, dataItem)
})
}
return data
}
return rule.default || {}
}
schemaArray(rule = {}, data) {
rule = this.ruleType(rule)
if (Array.isArray(data)) {
if (typeof rule.children === 'string') {
// eslint-disable-next-line array-callback-return
data = data.map(item => this.schemaContext(rule.children, item)).filter(item => item !== undefined)
} else if (rule.children) {
data = data.map(item => new Schema(rule.children, item))
}
return data.length > 0 ? data : data.default || []
}
return rule.default || []
}
schemaDefault(type, rule = {}, data) {
if (rule.type === 'any') return data
rule = this.ruleType(rule)
// eslint-disable-next-line valid-typeof
if (type === rule.type) {
return data
}
return rule.default
}
}
export default Schema
|
import { Spin, Space } from 'antd';
import './Loading.scss'
function Loading() {
return (
<div className='spinner-container'>
<Spin size="large" wrapperClassName='spinner' />
<h2 className='loading-title'>Please Wait . . .</h2>
</div>
)
}
export default Loading
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.