text
stringlengths 7
3.69M
|
|---|
import React, { Component } from "react";
import axios from "axios";
import "./Posts.css";
import Post from "./Post/Post";
import FullPost from "./FullPost/FullPost";
class Posts extends Component {
constructor(props) {
super(props);
this.state = {
posts: [],
selectedPostId: null,
};
}
componentDidMount() {
axios
.get("https://jsonplaceholder.typicode.com/posts")
.then((response) => {
this.setState({
posts: response.data.slice(0, 12),
});
})
.catch((err) => console.log(err));
}
postClickedHandler = (id) => {
this.setState({ selectedPostId: id });
};
deletePostHandler = (id) => {
let newPosts = this.state.posts.filter((item) => item.id !== id);
this.setState({ posts: newPosts });
};
render() {
const posts = this.state.posts.map((post) => {
return (
<Post
key={post.id}
title={post.title}
author={post.userId}
body={post.body}
clicked={() => this.postClickedHandler(post.id)}
/>
);
});
return (
<div className="Posts-Container">
<section className="Posts-All">{posts}</section>
<section className="Posts-FullPost">
<FullPost
id={this.state.selectedPostId}
delete={this.deletePostHandler}
/>
</section>
</div>
);
}
}
export default Posts;
|
class Timer {
constructor(durationInput, startButton, pauseButton, callbacks){
this.durationInput = durationInput;
this.startButton = startButton;
this.pauseButton = pauseButton;
this.ongoing = false;
if (callbacks) {
this.onStart = callbacks.onStart;
this.onTick = callbacks.onTick;
this.onComplete = callbacks.onComplete;
}
this.startButton.addEventListener('click', this.start)
this.pauseButton.addEventListener('click', this.stop)
this.durationInput.addEventListener('input', this.onDurationChange )
}
start = () => {
if (this.ongoing === true) {
return;
}else{
if (this.onStart) {
this.onStart(this.timeRemaining);
}
durationInput.setAttribute("value", `${durationInput.value}`);
this.clocky = setInterval(this.tick, 50);
this.ongoing = true
}
}
tick = () => {
if (durationInput.value> 0) {
this.timeRemaining = this.timeRemaining - 0.05;
if (this.onTick) {
this.onTick(this.timeRemaining);
}
}else{
clearInterval(this.clocky);
this.ongoing = false;
}
}
get timeRemaining(){
return parseFloat(this.durationInput.value);
}
set timeRemaining(time){
this.durationInput.value = time.toFixed(2);
durationInput.setAttribute("value", `${durationInput.value}`);
}
stop = () => {
clearInterval(this.clocky);
this.ongoing = false;
}
onDurationChange= () => {
clearInterval(this.clocky)
this.ongoing = false;
}
}
|
/**
* Created by msavur on 2/15/17.
*/
var app = angular.module("App", ['ui.router']);
app.config(function ($stateProvider, $urlRouterProvider) {
$stateProvider.state('sirket',{
url:"/sirket",
templateUrl:"views/sirket.html",
controller: "AppController"
});
$stateProvider.state('vergi',{
url:"/vergi",
templateUrl:"views/vergi.html",
controller: "VergiController"
});
});
app.controller("VergiController",function () {
});
app.controller("AppController", function ($scope, $http) {
$scope.pageSirkets=[];
$scope.kelimeAra="";
$scope.pageSayac = 0;
$scope.size=5;
$scope.pages = [];
$scope.kelimeAraFunc = function () {
$http.get("listsSirket?kelimeAra="
+$scope.kelimeAra+"&page="
+$scope.pageSayac+"&size="
+$scope.size)
.then(function(response) {
$scope.pageSirkets = response.data;
$scope.pages = new Array(response.data.totalPages);
});
$scope.kelimeAra = "";
}
$scope.gotoPage=function (page) {
$scope.pageSayac = page;
$scope.kelimeAraFunc();
}
});
|
/* eslint-disable import/prefer-default-export */
import axios from 'axios';
import { toastr } from 'react-redux-toastr';
import { decreaseBalance } from './wallet';
import config from '../config';
import C from '../constants/actions';
export const withdrawSubmit = transaction => (dispatch, getState) => {
// TODO: connect it to server
// const tokenId = getState().tokens.find(
// token => token.name === transaction.tokenName,
// ).id;
const walletId = getState().userInfo.wallets.find(
wallet => wallet.tokenId === transaction.tokenId,
).id;
axios({
data: {
transaction: JSON.stringify({ ...transaction, walletId }),
},
method: 'post',
url: `${config.api.serverUrl}/v1/transaction`,
headers: {
authorization: getState().userInfo.authToken,
[config.apiKeyHeader]: config.apiKey,
},
})
.then(res => {
if (res.status === 200) {
dispatch(decreaseBalance(transaction.tokenId, transaction.amount));
toastr.success(res.data.message.title, res.data.message.description);
}
dispatch({ type: C.TOGGLE_WITHDRAWING });
})
.catch(err => {
if (err.response && err.response.data.error) {
toastr.error(
err.response.data.error.title,
err.response.data.error.description,
);
}
dispatch({ type: C.TOGGLE_WITHDRAWING });
});
};
export const fetchTransactions = () => (dispatch, getState) => {
axios({
method: 'get',
url: `${config.api.serverUrl}/v1/transaction`,
headers: {
authorization: getState().userInfo.authToken,
[config.apiKeyHeader]: config.apiKey,
},
})
.then(res => {
if (res.status === 200) {
dispatch({
type: C.SET_USER_TRANSACTION_HISTORY,
payload: res.data,
});
}
})
.catch(err => {
if (err.response && err.response.data.error) {
toastr.error(
err.response.data.error.title,
err.response.data.error.description,
);
}
});
};
|
Redoc.init('openapi.yaml', {
theme: { colors: { primary: { main: '#db3d44' } } },
hideHostname: true,
lazyRendering: true,
nativeScrollbars: true,
suppressWarnings: true,
untrustedSpec: true,
noAutoAuth: true,
}, document.getElementById('redoc-container'))
|
export function lockScroll() {
document.body.style.overflowY = "hidden";
document.body.style.height = "100vh";
}
export function unlockScroll() {
document.body.style.overflowY = "initial";
document.body.style.height = "auto";
}
|
const myServer = require('http');
const fs = require('fs');
const url = require('url');
const path = require('path');
const process = require('child_process');
myServer.createServer((request, response) => {
var myParsedUrl = url.parse(request.url, true);
const myUrl = myParsedUrl.path;
console.log(myUrl);
console.log(path.join(__dirname, myUrl));
if (myUrl != '/favicon.ico') {
const myFileReaderProcess = process.fork('./day4/exercise1/readFile');
myFileReaderProcess.send(path.join(__dirname, myUrl));
myFileReaderProcess.on('message', (chunks) => response.end(chunks))
} else {
response.end();
}
}).listen(8000, () => console.log('listining on 8000 for processing file by streams'))
|
const getDataFromAPI = (name) =>
(window.location.href = `https://www.twitchdatabase.com/following/${name}`);
|
import React, { useState } from 'react';
import PropTypes from 'prop-types';
import styled from '@emotion/styled';
import Heading from 'components/Heading';
import Text from 'components/Text';
import ProjectBox from 'components/ProjectBox';
import Followers from 'components/Followers';
import CardButton from 'components/CardButton';
const ProfileCardContainer = styled.div`
width: 270px;
background-color: ${({ backgroundColor, theme }) => theme.colors[backgroundColor] ?? theme.colors.white};
display: flex;
flex-direction: column;
align-items: center;
border-radius: ${({ theme }) => theme.radius.main};
box-shadow: ${({ theme }) => theme.shadows.main};
position: relative;
`;
const Header = styled.div`
height: 50px;
width: 100%;
background-color: ${({ withoutBackground, theme }) => withoutBackground ? '' : theme.colors.primary};
margin-bottom: 40px;
position: relative;
`;
const HeaderBackgroundImage = styled.img`
background-color: blue;
height: 50px;
width: 100%;
position: absolute;
object-fit: cover;
opacity: 0.2;
`;
const BackgroundImage = styled.div`
background-image: url(${({ avatar }) => avatar});
background-position: center center;
background-size: cover;
width: 100%;
height: 100%;
position: absolute;
opacity: 0.2;
`;
const Avatar = styled.img`
position: absolute;
height: 56px;
width: 56px;
margin-top: 26px;
left: 50%;
margin-left: -28px;
border-radius: 50%;
`;
const Content = styled.div`
display: flex;
flex-direction: column;
align-items: center;
margin-top: 12px;
margin-left: ${({ theme }) => theme.spacing.medium};
margin-right: ${({ theme }) => theme.spacing.medium};
margin-bottom: ${({ theme }) => theme.spacing.medium};
width: calc(100% - 48px);
& > h2, & > span {
margin-bottom: ${({ theme }) => theme.spacing.tiny};
}
z-index: 1;
`;
const Seperator = styled.div`
width: 100%;
background-color: ${({ theme }) => theme.colors.gray};
height: 1px;
margin: ${({ theme }) => theme.spacing.small} 0;
`;
const StyledProjectBox = styled(ProjectBox)`
width: 100%;
`;
const StyledCardButton = styled(CardButton)`
margin-top: 20px;
z-index: 1;
`;
const ProfileCard = ({ name, email, followers, avatar, url, project }) => {
const [isHovered, setIsHovered] = useState(false);
const renderPersonalInfo = () => {
return (
<>
<Heading as="h2" weight="bold" color={isHovered ? 'white' : 'primary'}>{name}</Heading>
<Text as="span" color={isHovered ? 'white' : 'primary'}>{email ? email : `-`}</Text>
{followers >= 0 && <Followers count={followers} color={isHovered ? 'white' : 'primary'}/>}
</>
);
}
const renderProfileCard = () => {
if (isHovered) {
return (
<>
<BackgroundImage avatar={avatar}/>
<Header withoutBackground>
<Avatar src={avatar}/>
</Header>
<Content>
{renderPersonalInfo()}
</Content>
<StyledCardButton href={url} target="_blank" rel="noopener noreferrer">Open Profile</StyledCardButton>
</>
);
}
return (
<>
<Header>
{avatar && <HeaderBackgroundImage src={avatar}/>}
{avatar && <Avatar src={avatar}/>}
</Header>
<Content>
{renderPersonalInfo()}
<Seperator/>
{project && <StyledProjectBox {...project} />}
</Content>
</>
);
}
return (<ProfileCardContainer
backgroundColor={isHovered && 'primary'}
onMouseEnter={() => setIsHovered(true)}
onMouseLeave={() => setIsHovered(false)}
>
{renderProfileCard()}
</ProfileCardContainer>);
};
ProfileCard.propTypes = {
name: PropTypes.string,
email: PropTypes.string,
followers: PropTypes.number,
avatar: PropTypes.string,
url: PropTypes.string,
};
ProfileCard.defaultProps = {
name: '',
email: '',
followers: null,
avatar: null,
url: null,
};
export default ProfileCard;
|
module.exports = (app) => {
const express = require("express");
const router = express.Router();
const authJwt = require("../middlewares/auth-token");
const services = require("../controllers/services-controller");
// upadate the services
router.patch("/services/:id", authJwt.verifyToken, services.updateServices);
// get all the services with user details
router.get(
"/user/services/:id",
authJwt.verifyToken,
services.getAllUsersAndServices
);
app.use("/api", router);
};
|
({
doInit: function(component, event, helper) {
helper.getGroupinfo(component); //fetch group information for the first sub group created
helper.getaddress(component); //fetch group address
helper.getratingregion(component); //fetch rating region;
},
handleNavigateAction: function(component, event, helper) {
var SubGroup = component.get("v.subgroup");
var cmpEvt = component.getEvent("navCompFlow");
cmpEvt.setParams({
"Objatt": {
SubGroup
}
});
cmpEvt.fire();
},
/**
* aura method to be invoked from Master Flow
*
* @param {Component}
* component
* @param {Event}
* event
* @param {Helper}
* helper
* @return parameters to be sent to master component - Sub Group Information
*/
getAttributeMethod: function(component, event, helper) {
var params = event.getParam('arguments');
var subGrouplst = [];
// alert(component.get("v.subgroup.Address").length);
if (component.get("v.subgroup.Number") !== '000') {
if ($A.util.isEmpty(component.get("v.subgroup.Name")) || component.get("v.subgroup.Address").length === 0||component.get("v.subgroup.Address")==null) {
if (component.get("v.subgroup.Address").length === 0) {
component.find('addr-id').set("v.error", true);
}
params.navigate = false;
} else {
params.navigate = true;
subGrouplst = component.get("v.subgrouplst");
subGrouplst.push(component.get("v.subgroup"));
component.set("v.subgrouplst", subGrouplst);
params.subgrouplst = component.get("v.subgrouplst");
params.subgroup = component.get("v.subgroup");
console.log('************' + JSON.stringify(params));
params.navigate = true; //no validation in child components. Can move to next component
alert('In sub Group Form' + JSON.stringify(params));
}
} else {
params.navigate = true;
}
return params; //returns to master component
}
})
|
import {
isNumber,
} from 'lodash';
import * as selectors from '../selectors';
function createMessage(utils, { name, state, expected, actual, pass }) {
return pass
? () => `${this.utils.matcherHint(`.not.${name}`)}
Expected
${utils.printExpected(expected)}
Reveived
${utils.printReceived(actual)}
With state
${utils.printReceived(state)}`
: () => `${utils.matcherHint(`.${name}`)}
Expected
${utils.printExpected(expected)}
Reveived
${utils.printReceived(actual)}
With state
${utils.printReceived(state)}`;
}
expect.extend({
toBeNextSceneStartAngle(state, nextStartAngle) {
const actual = selectors.nextSceneStartAngle({ scene: state });
const pass = actual === nextStartAngle;
const message = createMessage(this.utils, {
expected: nextStartAngle,
name: 'toBeNextSceneStartAngle',
actual,
pass,
state,
});
return { actual: state, message, pass };
},
toHaveCurrentScenes(state, stuff) {
const actual = selectors.currentScenesData({ scene: state });
let pass;
if (isNumber(stuff)) {
pass = actual.count() === stuff;
} else {
pass = this.equals(actual.toJS(), stuff);
}
const message = createMessage(this.utils, {
name: 'toHaveCurrentScenes',
expected: stuff,
actual: isNumber(stuff) ? actual.count() : actual,
pass,
state,
});
return { actual, message, pass };
},
toHaveLoadingScenes(state, stuff) {
const actual = selectors.loadingScenes({ scene: state });
let pass;
if (isNumber(stuff)) {
pass = actual.count() === stuff;
} else {
pass = this.equals(actual, stuff);
}
const message = createMessage(this.utils, {
name: 'toHaveLoadingScenes',
expected: stuff,
actual: isNumber(stuff) ? actual.count() : actual,
pass,
state,
});
return { actual: state, message, pass };
},
toHaveLoadedScenes(state, stuff) {
const actual = selectors.loadedScenes({ scene: state });
let pass;
if (isNumber(stuff)) {
pass = actual.count() === stuff;
} else {
pass = this.equals(actual, stuff);
}
const message = createMessage(this.utils, {
name: 'toHaveLoadedScenes',
expected: stuff,
actual: isNumber(stuff) ? actual.count() : actual,
pass,
state,
});
return { actual: state, message, pass };
},
toHaveActiveScenes(state, stuff) {
const actual = selectors.currentScenesData({ scene: state });
let pass;
if (isNumber(stuff)) {
pass = actual && actual.count() === stuff;
} else {
pass = this.equals(actual, stuff);
}
const message = createMessage(this.utils, {
name: 'toHaveActiveScenes',
expected: stuff,
actual: isNumber(stuff) ? actual.count() : actual,
pass,
state,
});
return { actual: state, message, pass };
},
toHaveCurrentScene(state, stuff) {
const actual = selectors.currentSceneData({ scene: state });
let pass;
if (isNumber(stuff)) {
pass = actual && actual.sceneId === stuff;
} else {
pass = this.equals(actual, stuff);
}
const message = createMessage(this.utils, {
name: 'toHaveCurrentScene',
expected: stuff,
actual: isNumber(stuff) ? actual.sceneId : actual,
pass,
state,
});
return { actual: state, message, pass };
},
toHaveBackgroundScene(state, stuff) {
const actual = selectors.backgroundSceneData({ scene: state });
let pass;
if (isNumber(stuff)) {
pass = actual && actual.sceneId === stuff;
} else {
pass = this.equals(actual, stuff);
}
const message = createMessage(this.utils, {
name: 'toHaveBackgroundScene',
expected: stuff,
actual: isNumber(stuff) ? actual.sceneId : actual,
pass,
state,
});
return { actual: state, message, pass };
},
toHavePreviousScene(state, stuff) {
const actual = selectors.previousSceneData({ scene: state });
let pass;
if (isNumber(stuff)) {
pass = actual && actual.sceneId === stuff;
} else {
pass = this.equals(actual, stuff);
}
const message = createMessage(this.utils, {
name: 'toHavePreviousScene',
expected: stuff,
actual: isNumber(stuff) ? actual.sceneId : actual,
pass,
state,
});
return { actual: state, message, pass };
},
toHaveDissolve(state, bool) {
const actual = selectors.dissolve({ scene: state });
const pass = this.equals(actual, bool);
const message = createMessage(this.utils, {
name: 'toHaveDissolve',
expected: bool,
actual,
pass,
state,
});
return { actual: state, message, pass };
},
toBeLive(state) {
const actual = selectors.isLive({ scene: state });
const pass = this.equals(actual, true);
const message = createMessage(this.utils, {
name: 'toBeLive',
expected: true,
actual,
pass,
state,
});
return { actual: state, message, pass };
},
});
|
import React from 'react';
import './styles/FoodTable.css';
import Spinner from './Spinner';
const FoodTable = (props) => {
if (props.data.foodNutrients) {
return (
<div className="tableContainer">
<h1>{props.data.description}</h1>
<table className="table table-hover">
<thead>
<tr>
<th scope="col">Nutrient</th>
<th scope="col">Value</th>
<th scope="col">Units</th>
</tr>
</thead>
<tbody>
{props.data.foodNutrients.map((nutrient) => {
if (nutrient.amount || nutrient.amount === 0) {
return (
<tr>
<th scope="row">{nutrient.nutrient.name}</th>
<td>{nutrient.amount}</td>
<td>{nutrient.nutrient.unitName}</td>
</tr>
);
}
return (
// <tr className="table-info">
// <th scope="row">{nutrient.nutrient.name}</th>
// <td>{nutrient.amount}</td>
// <td>-</td>
// </tr>
<>
</>
);
})
}
</tbody>
</table>
</div>
);
}
return (<Spinner />);
};
export default FoodTable;
|
const express = require('express');
const userRouter = require("./users/userRouter");
const postRouter = require("./posts/postRouter");
//require other middleware here
const logger = require("./middleware/logger");
const validateUser = require("./middleware/validateUser");
const server = express();
server.use(express.json());
//Put use of other middleware here
//Logger is first on purpose I think
server.use(logger);
// server.use(validateUser);
server.use("/users", userRouter);
// server.use(postRouter);
server.get('/', (req, res) => {
res.send(`<h2>Let's write some middleware!</h2>`);
});
//custom middleware
// function logger(req, res, next) {}
//Remember this
module.exports = server;
|
import React from 'react'
import Nav from './Nav'
const signup = () => (
<div className="signup-container">
<Nav/>
<div className="three fields">
<label>First name</label>
<input type="text" placeholder="First Name">
</input>
<label>Middle name</label>
<input type="text" placeholder="Middle Name">
</input>
<label>Last name</label>
<input type="text" placeholder="Last Name">
</input>
<label>Username</label>
<input type="text" placeholder="Username">
</input>
<label>Password</label>
<input type="password">
</input>
</div>
<div className="inline fields">
<label for="fruit">Select your favorite fruit:</label>
<div className="ui radio checkbox">
<input type="radio" name="fruit" checked="" tabindex="0" class="hidden">
<label>Apples</label>
</input>
<input type="radio" name="fruit" tabindex="0" class="hidden">
<label>Oranges</label>
</input>
<input type="radio" name="fruit" tabindex="0" class="hidden">
<label>Pears</label>
</input>
</div>
</div>
</div>
)
export default signup
|
import React, { Component } from "react";
import Loader from "./Components/Loader";
import Error from "./Components/Error";
import ModelsView from "./modelDetails/modelsView";
import WebglView from "./webGL/mapView";
import { inject, observer } from "mobx-react";
import Materialize from "materialize-css";
class App extends Component {
componentDidUpdate() {
var sidenav = document.querySelectorAll(".sidenav");
Materialize.Sidenav.init(sidenav, null);
}
async componentDidMount() {
try {
this.props.store.initiateMap();
} catch (error) {
console.log(error);
}
}
withDataState = (renderer) => {
return (
<div>
<button
style={{border: "none", backgroundColor: "transparent" }}
data-target="slide-out"
className="sidenav-trigger mobileMenu"
>
<i className="material-icons black-text menu-icon">menu</i>
</button>
<ul id="slide-out" className="sidenav sidenav-fixed grey lighten-3">
{renderer}
</ul>
<WebglView />
</div>
);
};
loadingState = () => <Loader />;
errorState = () => <Error />;
loadedState = () => <ModelsView />;
render() {
const { assetsLoadingState, errorState } = this.props.store;
if (errorState === false) {
if (assetsLoadingState === false) {
return this.withDataState(this.loadedState());
} else {
return this.withDataState(this.loadingState());
}
} else {
return this.withDataState(this.errorState());
}
}
}
export default inject("store")(observer(App));
|
import React, {PropTypes} from 'react';
import {Link} from 'react-router';
const CalActionButtons = ({actions}) => {
return <div className="col-lg-6">
<button type="button" className="btn btn-default" onClick={actions.prevMonth}><i className="glyphicon glyphicon-arrow-left"></i>
</button>
<button type="button" className="btn btn-default" onClick={actions.nextMonth}><i className="glyphicon glyphicon-arrow-right"></i>
</button>
<button type="button" className="btn btn-default" onClick={actions.today}>Today</button>
<button type="button" className="btn btn-primary"><Link style={{color: 'white'}} to={`/create-event`}>Create event</Link></button>
</div>
};
CalActionButtons.propTypes = {
actions: PropTypes.object
};
export default CalActionButtons;
|
import React from 'react';
import { SafeAreaView, Text, StyleSheet } from 'react-native';
export default ({ valor }) => {
return (
<SafeAreaView style={style.container}>
<Text style={style.texto}>{valor}</Text>
</SafeAreaView>
)
}
const style = StyleSheet.create({
container: {
height: 100,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#010010'
},
texto: {
textAlign: "center",
fontSize: 32,
color: '#fff'
}
});
|
import { gql } from "apollo-server-express";
export default gql`
type Mutation {
createCoffeeShop(
name: String!
latitude: String
longitude: String
categoryName: String
photo: Upload
): MutationResponse!
}
`;
|
window.onload = function () {
/* 获取json数据(图片的地址) */
$.getJSON("./js/data.json", function (data) {
if (!data.length) {
return
}
var swiperWrapper = document.getElementById("swiper-wrapper");
data.forEach(function (ele) {
var itemScreen = document.createElement("div");
if (itemScreen.setAttribute) {
itemScreen.setAttribute("class", "swiper-slide");
itemScreen.style.background = "url("+ele.valueUrl+") center center no-repeat";
itemScreen.style.backgroundSize="100%";
}
swiperWrapper.appendChild(itemScreen);
})
var mySwiper = new MySwiper();
})
// 实例化swiper
function MySwiper() {
var mySwiper = new Swiper('.swiper-container', {
direction: 'vertical',
})
return mySwiper;
}
}
|
import { verticalScale, scale, colors, alignment } from '../../utils'
import { StyleSheet } from 'react-native'
const styles = StyleSheet.create({
flex: {
flex: 1
},
safeAreaStyle: {
backgroundColor: colors.headerbackground
},
container: {
flex: 1,
alignItems: 'center'
},
body: {
// adjust body height in order to accomodate footer
height: '85%',
width: '100%',
alignItems: 'center',
backgroundColor: colors.backgroudGray
},
backImg: {
width: '15%',
justifyContent: 'center',
alignItems: 'center'
},
// header
header: {
height: '8%',
width: '100%',
backgroundColor: colors.whiteColor,
borderBottomWidth: verticalScale(1),
borderColor: colors.grayLinesColor,
alignItems: 'center'
},
headerRow: {
height: '100%',
width: '100%',
flexDirection: 'row',
alignItems: 'center'
},
headerText: {
width: '60%'
},
headerBtn: {
width: '30%',
height: '80%',
justifyContent: 'center',
alignItems: 'flex-start'
},
// main
main: {
height: '100%',
width: '95%',
paddingTop: verticalScale(10)
},
mainScroll: {
height: '100%',
width: '100%'
},
// Empty View
emptyContainer: {
width: '100%',
backgroundColor: colors.container,
borderRadius: scale(5),
alignItems: 'center',
...alignment.MBmedium,
...alignment.PTmedium,
...alignment.PBmedium
},
address: {
...alignment.MTmedium,
...alignment.MBsmall,
...alignment.PLxSmall,
width: '90%',
justifyContent: 'center'
},
btnContainer: {
width: '90%',
justifyContent: 'flex-start'
},
unselectedButton: {
height: scale(40),
width: '100%',
backgroundColor: colors.brownColor,
justifyContent: 'center',
alignItems: 'center',
borderRadius: scale(3)
}
})
export default styles
|
const knex = require("knex");
const knexConfig = require("../knexfile");
const Students = require("../students/students-model");
const cohortsRouter = require("express").Router();
const Cohorts = require("./cohorts-model");
cohortsRouter.get("/", (req, res) => {
Cohorts.find()
.then(cohorts => {
res.status(200).json(cohorts);
})
.catch(error => {
res.status(500).json(error);
});
});
cohortsRouter.get("/:id", (req, res) => {
Cohorts.findById(req.params.id)
.then(cohort => {
if (cohort) {
res.status(200).json(cohort);
} else {
res.status(404).json({ message: "Cohort not found" });
}
})
.catch(error => {
res.status(500).json(error);
});
});
cohortsRouter.get("/:id/students", (req, res) => {
Students.find()
.select()
.where({ cohort_id: req.params.id })
.then(cstudent => {
res.status(200).json(cstudent);
})
.catch(error => {
res.status(500).json(error);
});
});
cohortsRouter.post("/", (req, res) => {
Cohorts.find()
.insert(req.body, "id")
.then(ids => {
res.status(201).json(ids);
})
.catch(error => {
res.status(500).json(error);
});
});
cohortsRouter.put("/:id", (req, res) => {
const changes = req.body;
Cohorts.find()
.where({ id: req.params.id })
.update(changes)
.then(count => {
if (count > 0) {
res.status(200).json({ message: `${count} records updated` });
} else {
res.status(404).json({ message: "Cohort not found" });
}
})
.catch(error => {
res.status(500).json(error);
});
});
cohortsRouter.delete("/:id", (req, res) => {
Cohorts.find()
.where({ id: req.params.id })
.del()
.then(count => {
if (count > 0) {
const unit = count > 1 ? "records" : "record";
res.status(200).json({ message: `${count} ${unit} deleted` });
} else {
res.status(404).json({ message: "Cohort not found" });
}
})
.catch(error => {
res.status(500).json(error);
});
});
module.exports = cohortsRouter;
|
'use strict';
(function () {
var forms = document.querySelectorAll('form');
var INVALID_MESSAGE = 'Данные не верны';
var onSubmitForm = function (i) {
return function () {
var success = document.querySelector('#success').content.querySelector('.success').cloneNode(true);
var formSuccess = forms[i].appendChild(success);
formSuccess.querySelector('button').addEventListener('click', function () {
forms[i].removeChild(formSuccess);
});
};
};
for (var i = 0; i < forms.length; i++) {
forms[i].addEventListener('submit', onSubmitForm(i));
}
for (var j = 0; j < forms.length; j++) {
forms[j].addEventListener('submit', function (evt) {
evt.preventDefault();
});
}
var onInputChange = function (e) {
var input = e.target;
if (!input.checkValidity()) {
input.classList.add('form__error-input');
} else {
input.classList.remove('form__error-input');
}
}
var inputs = document.querySelectorAll('input');
inputs.forEach(function (input) {
input.insertAdjacentHTML('afterend', '<p class="form__error-message">' + INVALID_MESSAGE + '</p>');
input.addEventListener('input', onInputChange);
});
})();
|
//exports.parse = parse; // for testing with nodejs
function assert(iffalse, throwthis) {
if (! iffalse ) throw throwthis || "Assertion failed";
}
function isEmpty(obj) {
for(var prop in obj) {
if(obj.hasOwnProperty(prop))
return false;
}
return JSON.stringify(obj) === JSON.stringify({});
}
function validate(config) {
/* TODO
must hold:
forall els:
questiontext, type, points must exist
assumptions.length >= 3
foreach assumption:
text, type, points must exist
assert type in [needed, notneeded, complicatedfactor]
any assumptions that are != needed:
reasons.length >= 2
foreach reason:
text, type, points must exist
assert type in [true, false]
if any of the above is violated, throw an error
*/
assert(config.length > 0, "config file contained no questions");
for (var i = 0 ; i < config.length ; i++) {
for (var kw in {'questiontitle': 1, 'realworldmodelpath': 1, 'idealizedmodelpath': 1, 'assumptions': 1}) {
assert(kw in config[i], kw + " field is missing from one of the questions");
}
assert(config[i].assumptions.length >= 3,
"question must have at least 3 assumptions: " +
config[i].assumptions.length);
var atypes = {};
for (var k = 0 ; k < config[i].assumptions.length ; k++) {
atypes[config[i].assumptions[k].assumption_type] = 1;
if (!(config[i].assumptions[k].assumption_type in {'needed': 1, 'unneeded': 1, 'complicatingfactor': 1}))
throw "assumption_type is invalid: " + config[i].assumptions[k].assumption_type;
}
assert ('needed' in atypes, "assumptions must have at least one NEEDED type");
}
return config;
}
var parser = function(text, check) {
"use strict";
var self = this;
this.raw = text;
this.check = (check !== null) ? check : true; // should we validate the text?
var config = []; // at the end, this is an an array of JSON objects
var assumptions = [];
var reasons = [];
var Q = {};
var A = {};
var R = {};
this.parse_questiontitle = function(kw, x) {
if (!isEmpty(Q)) {
if (!isEmpty(R)) reasons.push(R);
if (reasons.length > 0) A.reasons = reasons;
reasons = [];
R = {};
if (!isEmpty(A)) assumptions.push(A);
A = {};
Q.assumptions = assumptions;
config.push(Q);
}
Q = {};
assumptions = [];
Q.questiontitle = x.replace(kw, "");
return Q.questiontitle;
};
this.parse_realworldmodelpath = function(kw, x) {
if (isEmpty(Q)) throw "invalid file format: no questiontitle";
Q.realworldmodelpath = x.replace(kw, "");
return Q.realworldmodelpath;
};
this.parse_idealizedmodelpath = function(kw, x) {
if (isEmpty(Q)) throw "invalid file format: no questiontitle";
Q.idealizedmodelpath = x.replace(kw, "");
return Q.idealizedmodelpath;
};
this.parse_assumption_text = function(kw, x) {
if (isEmpty(Q)) throw "invalid file format: no questiontitle";
if (!isEmpty(A)) {
if (!isEmpty(R)) reasons.push(R);
if (reasons.length > 0) A.reasons = reasons;
reasons = [];
R = {};
assumptions.push(A);
}
A = {};
A.assumption_text = x.replace(kw, "");
return A.assumption_text;
};
this.parse_assumption_type = function(kw, x) {
if (isEmpty(Q)) throw "invalid file format: no questiontitle";
if (isEmpty(A)) throw "invalid file format: no assumption_text";
A.assumption_type = x.replace(kw, "");
return A.assumption_type;
};
this.parse_assumption_points = function(kw, x) {
if (isEmpty(Q)) throw "invalid file format: no questiontitle";
if (isEmpty(A)) throw "invalid file format: no assumption_text";
A.assumption_points = parseInt(x.replace(kw, ""));
return A.assumption_points;
};
this.parse_reason_text = function(kw, x) {
if (isEmpty(Q)) throw "invalid file format: no questiontitle";
if (assumptions.length === 0) throw "invalid file format: reasons before assumptions";
if (!isEmpty(R)) {
reasons.push(R);
}
R = {};
R.reason_text = x.replace(kw, "");
return R.reason_text;
};
this.parse_reason_type = function(kw, x) {
if (isEmpty(Q)) throw "invalid file format: no questiontitle";
if (assumptions.length === 0) throw "invalid file format: reasons before assumptions";
R.reason_type = x.replace(kw, "");
return R.reason_type;
};
this.parse_reason_points = function(kw, x) {
if (isEmpty(Q)) throw "invalid file format: no questiontitle";
if (assumptions.length === 0) throw "invalid file format: reasons before assumptions";
R.reason_points = parseInt(x.replace(kw, ""));
return R.reason_points;
};
this.parse = function() {
var lines = this.raw.split('\n');
for (var linenum = 0 ; linenum < lines.length ; linenum++) {
var line = lines[linenum];
for (var i = 0; i < self.parser_map.length; i++) {
var kws = self.parser_map[i];
if (kws.kw.test(line)) {
kws.func(kws.kw, line);
}
}
}
if (!isEmpty(Q)) {
if (!isEmpty(R)) reasons.push(R);
if (reasons.length > 0) A.reasons = reasons;
reasons = [];
R = {};
if (!isEmpty(A)) {
assumptions.push(A);
}
Q.assumptions = assumptions;
config.push(Q);
}
if (self.check)
return validate(config);
return config;
};
this.parser_map = [
{ kw: /^questiontitle:\s*/, func: self.parse_questiontitle },
{ kw: /^realworldmodelpath:\s*/, func: self.parse_realworldmodelpath },
{ kw: /^idealizedmodelpath:\s*/, func: self.parse_idealizedmodelpath },
{ kw: /^assumption_text:\s*/, func: self.parse_assumption_text },
{ kw: /^assumption_type:\s*/, func: self.parse_assumption_type },
{ kw: /^assumption_points:\s*/, func: self.parse_assumption_points },
{ kw: /^\s*reason_text:\s*/, func: self.parse_reason_text },
{ kw: /^\s*reason_points:\s*/, func: self.parse_reason_points },
{ kw: /^\s*reason_type:\s*/, func: self.parse_reason_type },
];
};
/* for testing using nodejs... */
/*
var Ptest = `questiontitle: xxxx
realworldmodelpath: relative/path/no/absolutes.png
idealizedmodelpath: relative/path/no/absolutes.png
assumption_text: xxx1 assumption1 must be on a single line
assumption_type: needed
assumption_points: 1
assumption_text: xxx2 assumption2 can contain: "special characters" & html
assumption_type: unneeded
assumption_points: -1
reason_text: xxx2 this reason relates to the most recently parsed assumption-text
reason_type: true
reason_points: +1
reason_text: xxx2 another1 invariant is #reasons given >= 2
reason_type: false
reason_points: -1
assumption_text: xxx3 assumption1 must be on a single line
assumption_type: needed
assumption_points: 1
`;
*/
var Ptest2 = `
questiontitle:Hip Joint Force Analysis
realworldmodelpath:RealWorld1.png
idealizedmodelpath:IdealizedModel1.png
assumption_text:Hip acts as a pivot point (no lifting off the bed)
assumption_type:needed
assumption_points:1
assumption_text:Forces are reasonably approximated using static analysis
assumption_type:needed
assumption_points:1
assumption_text:Patient does not slide on the bed
assumption_type:needed
assumption_points:1
assumption_text:Lower leg remains approximately perpendicular to upper leg
assumption_type:needed
assumption_points:1
assumption_text:Incorrect Assumption #1.1
assumption_type:unneeded
assumption_points:-1
reason_text:Valid Reason #1.1.1
reason_type:true
reason_points:1
reason_text:Invalid Reason #1.1.2
reason_type:false
reason_points:-1
reason_text:Invalid Reason #1.1.3
reason_type:false
reason_points:-1
assumption_text:Incorrect Assumption #1.2
assumption_type:unneeded
assumption_points:-1
reason_text:Invalid Reason #x.y.z
reason_type:false
reason_points:-1
reason_text:Invalid Reason #hashtag
reason_type:false
reason_points:-1
reason_text:Invalid Reason #HertzRules!
reason_type:false
reason_points:-1
reason_text:Valid
reason_type:true
reason_points:1
assumption_text:Complicating Assumption #Who Cares I Am Making All This Up?
assumption_type:unneeded
assumption_points:-1
assumption_text:Incorrect Assumption that includes a lot of text to make certain you can handle it #1.3
assumption_type:unneeded
assumption_points:-1
reason_text:Valid Reason #ExamplesAreHard
reason_type:true
reason_points:1
questiontitle:Second Example
realworldmodelpath:RealWorld2.png
idealizedmodelpath:IdealizedModel2.png
assumption_text:Forces are reasonably approximated using static analysis
assumption_type:needed
assumption_points:1
assumption_text:Lower leg remains approximately perpendicular to upper leg
assumption_type:needed
assumption_points:1
assumption_text:Hip acts as a pivot point (no lifting off the bed)
assumption_type:needed
assumption_points:1
assumption_text:Patient does not slide on the bed
assumption_type:needed
assumption_points:1
`;
// var P = new parser(Ptest2);
// var XX = P.parse();
// console.log(JSON.stringify(XX, null, " "));
|
var http = require('http'),
xml2js = require('xml2js'),
url = require('url'),
numeral = require('numeral'),
qs = require('querystring'),
// accountSid = 'AC6cb41d2c4476f7ec6f73caa3f8f890a8',
// authToken = '05698ff30e915eb04dda72ca33a264a6',
// destinationNumber = '+15103328835',
twilio = require('twilio'), //(accountSid, authToken),
currencyFormat = function(val) {
return numeral(Number(val[0])).format('$0,0.00');
},
numberFormat = function(val) {
return numeral(Number(val[0])).format('0,0');
};
var server = http.createServer(function(req, res) {
});
server.listen(3000);
server.on('request', function(req, res) {
var reqBody = '';
req.setEncoding('utf8');
req.on('data', function(data) {
reqBody += data;
});
//process the twilio request
req.on('end', function() {
var reqData = qs.parse(reqBody),
jsonString = JSON.stringify(reqData),
jsonDataObject = JSON.parse(jsonString),
tickerStr = jsonDataObject.Body,
tickerArr = tickerStr.replace(/\s+/g,'').split(','),
expandedIndex = tickerArr.indexOf('expanded');
//process ticker string
var expandedInfo = expandedIndex !== -1;
if (expandedInfo)
tickerArr.splice(expandedIndex, 1);
var ticker = tickerArr.join(','),
quoteWsUrl = 'http://ws.cdyne.com/delayedstockquote/delayedstockquote.asmx/GetQuoteDataSet?StockSymbols=' + ticker + '&LicenseKey=0';
//console.log('==> tickerStr: ' + tickerStr + '--- tickerArr: ' + tickerArr + '--- ticker: ' + ticker);
//fetch stock quote from web service
http.get(quoteWsUrl, function(response) {
var msg = '';
if (response.statusCode === 200) {
response.setEncoding('utf8');
response.on('data', function(chunk) {
msg += chunk;
});
response.on('end', function() {
xml2js.parseString('' + msg, function (err, result) {
res.statusCode = 200;
//console.log('result: ==== ' + JSON.stringify(result));
var tickerResultArr = result.DataSet['diffgr:diffgram'][0].QuoteData[0].Quotes,
textBody = [];
//console.log('tickerResultArr: ==== ' + JSON.stringify(tickerResultArr));
for (var idx = 0; idx < tickerResultArr.length; idx++) {
var tickerResultObj = tickerResultArr[idx];
textBody.push('Stock quote for ' + tickerResultObj.CompanyName + ' (' + tickerResultObj.StockSymbol + '): ' + currencyFormat(tickerResultObj.LastTradeAmount));
if (expandedInfo) {
textBody.push('\n\n');
textBody.push('Open: ' + currencyFormat(tickerResultObj.OpenAmount));
textBody.push('\n');
textBody.push('Days\'s Range: ' + currencyFormat(tickerResultObj.DayLow) + ' - ' + currencyFormat(tickerResultObj.DayHigh));
textBody.push('\n');
textBody.push('Previous Close: ' + currencyFormat(tickerResultObj.PrevCls));
textBody.push('\n');
textBody.push('Volume: ' + numberFormat(tickerResultObj.StockVolume));
}
textBody.push('\n');
textBody.push('------------------------\n');
}
//console.log('=>' + textBody.join(''));
//send text
// twilio.messages.create({
// to: destinationNumber,
// from: '+16506662343', //my twilio number/account
// body: textBody.join('')
// }, function(error, message) {
// if (error) {
// console.log(error.message);
// }
// });
var tResp = new twilio.TwimlResponse();
tResp.message(textBody.join(''));
//show on browser data being sent
res.writeHead(200, {'Content-Type': 'text/xml'});
res.end(tResp.toString());
});
});
}
}).on('error', function(err) {
console.log('error: ' + err);
});
});
});
|
'use strict';
module.exports = {
up: async (queryInterface, Sequelize) => {
return queryInterface.bulkInsert('profiles',
[
{
name: "admin",
last_name:"admin",
email:"dramirez@suavit.cl",
user_id:1,
address:"iquique",
phone:"+569-84766696"
},
], {});
},
down: async (queryInterface, Sequelize) => {
return queryInterface.bulkDelete('profiles', null, {});
}
};
|
/**
* Render HTML in the content element according to parsed events (character input, etc).
*
* @param content element that contains rendered content
* @param eventParser interface for handling parsed events
* @param parse a function that defines how to parse a character into html
* @param ch a character
* @return string of html
*/
module.exports = function(content, eventParser, parse) {
var obj = {};
function el(html) {
// prevents against some injection possibilities
return $('<span/>').html(html);
}
// list-like management of the editor
obj.add = function(ch) {
content.append(el(parse(ch)));
};
obj.addAt = function(index, ch) {
var chEl = el(parse(ch));
chEl.insertBefore(content[index]);
};
eventParser.parseCharacter(function() {
});
// pass up properties
var content = cursorBlinker.content, cursor = cursorBlinker.cursor;
function addEl(el) {
el.insertBefore(cursor);
}
function removeEl(el) {
el.detach();
}
content.click(function(e) {
var target = $(e.target);
if(target.tabindex == content.tabindex) { // not on a child
// later re positioning code if click outside text
}
else {
var next = target.next();
if(next.length==0) {
a
}
var test = (e.x < next.position().left);
if(test) {
cursor.insertBefore(target);
}
else {
cursor.insertAfter(target);
}
}
});
// user defined
function parseChar(c) {
// trivial default
switch(c) {
case '\n': return '<br>';
case '\t': return ' ';
case ' ': return ' ';
default: return c;
}
}
this.setParseFunc = function(parseFunc) {
parseChar = parseFunc;
};
function formCharFromCode(code) {
return (code !== 13) ? String.fromCharCode(code) : '\n';
}
content.keypress(function(e) {
var c = formCharFromCode(e.which);
var el = $('<span>'+parseChar(c)+'</span>');
addEl(el);
});
// enable tab
content.keydown(function(e) {
if(e.which === 9) {
e.preventDefault();
var el = $('<span>'+parseChar('\t')+'</span>');
addEl(el);
}
});
// special case backspace
content.keydown(function(e) {
if(e.which === 8) { // backspace
e.preventDefault();
var prevEl = cursor.prev();
if(prevEl.length != 0) { // prev exists
removeEl(prevEl);
}
}
});
}
|
// simple interest formula = (P*r*t)/100
function simpleInterest(principle,rate,time){
let interest = (principle * rate * time) / 100;
return interest;
}
let principle = 50000;
let rate = 5;//5% interest deoya hobe.
let time = 3;
let yearlyInterest = simpleInterest(principle,rate,time);
console.log('Interset is :',yearlyInterest);
|
$(document).ready( function() {
var lock = navigator.requestWakeLock("cpu");
$('li i').each(function() {
var id = $(this).parent()[0].id;
switch(id) {
case 'li0':
$(this).bind('mousedown', function(e){ tamaControls.HungerMeter();});
break;
case 'li1':
$(this).bind('mousedown', function(e){ tamaControls.FeedingTime();});
break;
case 'li2':
$(this).bind('mousedown', function(e){ tamaControls.Toilet();});
break;
case 'li3':
$(this).bind('mousedown', function(e){ tamaControls.GamingTime();});
break;
case 'li4':
$(this).bind('mousedown', function(e){ tamaControls.Discipline();});
break;
case 'li5':
$(this).bind('mousedown', function(e){ tamaControls.Health();});
break;
case 'li6':
$(this).bind('mousedown', function(e){ tamaControls.Lights();});
break;
case 'li7':
$(this).bind('mousedown', function(e){ tama.help();});
break;
}
});
tama.init();
$('#snack').bind('mouseup', function() { tamaControls.FeedingTime('snack'); });
$('#food').bind('mouseup', function() { tamaControls.FeedingTime('food'); });
$('#praise').bind('mouseup', function() { tamaControls.Discipline('praise'); });
$('#punish').bind('mouseup', function() { tamaControls.Disciplines('punish'); });
});
$(function() {
$( "#load" ).click(function() {
var tamaLoad = localStorage.getItem("tamaVars");
tamaVars = JSON.parse(tamaLoad); //var test is now re-loaded!
if(tamaVars.theme == 'firefoxos'){
var cssLink = $("<link rel='stylesheet' type='text/css' href='css/firefoxos.css'>");
$("head").append(cssLink);
}
else{
$('link[rel=stylesheet][href~="css/firefoxos.css"]').remove();
}
});
});
$(function() {
$( "#save" ).click(function() {
localStorage.setItem('tamaVars', JSON.stringify(tamaVars));
});
});
$(function() {
$( "#help" ).on('mousedown', function() {
$("#li8-content").toggle();
$("#li0-content").toggle();
});
$( "#exit-help" ).on('mousedown', function() {
$("#li7-content").toggle();
});
});
$(function(){
$("#firefoxos").on('mousedown', function(){
var cssLink = $("<link rel='stylesheet' type='text/css' href='css/firefoxos.css'>");
$("head").append(cssLink);
tamaVars.theme = 'firefoxos';
});
$("#themedefault").on('mousedown', function(){
$('link[rel=stylesheet][href~="css/firefoxos.css"]').remove();
tamaVars.theme = 'default';
});
});
|
////////////////////////////////////////////////////////////////////////////
function dataValidation() {
var x, text;
// Get the value of input field with id="numb"
x = document.getElementById("oneToTen").value;
// If x is Not a Number or less than one or greater than 10
if (isNaN(x) || x < 1 || x > 10) {
text = "Input not valid";
} else {
text = "Input OKKK";
}
document.getElementById("validationResult").innerHTML = text;
}
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
function getSite(sel) {
var SelectedSite = sel.value;
document.getElementById(PDFdisplay).style.display = 'block';
//<a href="./database/Oct-2016(25-Sep-2016_24-Oct-2016).PDF" target="iframe_PDF"></a><br/>
}
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
|
/**
* Created by mooshroom on 2016/1/24.
*/
define('MDEditor', [
'avalon',
'jquery',
'text!../../lib/MDEditor/MDEditor.html',
'css!../../lib/MDEditor/MDEditor.css',
'../../lib/uploader/uploader',
"../../lib/MDEditor/markdown",
"../../lib/MDEditor/prettify",
'css!../../src/css/font-awesome.min.css'
], function (avalon, $, html, css, uploader, markdown, prettify) {
avalon.component("tsy:mdeditor", {
$template: html,
id: "",
now: "1",
md: '',
html: "",
loadLocaDoc: true,
$opt: {},
//图片上传组件配置
$uploader:{
},
callback: function (md) {
},
file:'',
initType: 1,//0为初始纯净模式;1为初始双屏模式;2为初始阅读模式
//本地缓存
isHTML5: false,
getLoaclDoc: function () {
},
//文档编译
trs: function () {
},
toWrite: function () {
},
toBoth: function () {
},
toRead: function () {
},
height: "auto",
autoHeight: function () {
},
doubleScroll: function () {
},
insert: function () {
},
//粗体
bold: function () {
},
//斜体
italic: function () {
},
//插入连接
link: "",
links: function () {
},
//表格
table: function () {
},
//段落引用
quote: function () {
},
//插入代码
code: function () {
},
//插入图片
imgUrl: "",
img: function () {
},
//插入有序列表
ol: function () {
},
//插入无序列表
ul: function () {
},
//插入标题h1
h1: function () {
},
//插入标题h2
h2: function () {
},
//插入标题h3
h3: function () {
},
//插入标题h4
h4: function () {
},
//插入标题h5
h5: function () {
},
//插入分割线
divider: function () {
},
//分段落
paragraph: function () {
},
//打开文件
open: function (e) {
},
// //保存文件
Base64: {
},
save: function () {
},
saveFile: function () {
},
//下拉菜单
dh: false,//插入标题下拉菜单
dl: false,//插入列表下拉菜单
dropdown: function (i) {
},
//各个模态框的显示
showModal:0,
toggleModal: function (i) {
},
$init: function (vm, elem) {
if(vm.id!=""){
window[vm.id]=vm
}
marked.setOptions({
renderer: new marked.Renderer(),
gfm: true,
tables: true,
breaks: false,
pedantic: false,
sanitize: true,
smartLists: true,
smartypants: false
});
console.log("【markdown编辑器模块加载完成!】");
//本地缓存
vm.getLoaclDoc = function () {
if (vm.loadLocaDoc) {
//检测是否支持html5web存储
if (typeof(Storage) !== "undefined") {
vm.isHTML5 = true;
//查找存储中的lastMD,判断是否为第一次使用
var isFirst = true;
for (var i = 0; i < window.localStorage.length; i++) {
if (window.localStorage.key(i) == "lastMD") {
isFirst = false;
break
}
}
//加载上一次的文档
if (isFirst) {
//avalon.ajax({
// url: "./README.md",
// type: "get",
// success: function (data) {
// vm.md = data;
// vm.trs();
// }
//
//})
}
else {
vm.md = window.localStorage.getItem("lastMD");
if (vm.md !== "") {
vm.trs();
tip.on("成功加载上一次的文档!", 1, 3000)
}
}
}
else {
tip.on("您老的浏览器老得不行了,无法为您开启文档保护", 0, 6000)// Sorry! No web storage support..
vm.isHTML5 = false;
}
}
}
//执行编译
vm.trs = function () {
vm.html = marked(vm.md) + '<br/><br/><br/><br/><br/><br/>'
//执行本地缓存
if (vm.isHTML5 === true) {
window.localStorage.setItem("lastMD", vm.md)
}
prettyPrint();
//回掉给其他东西
vm.callback(vm.md)
}
//编辑窗口动作
vm.toWrite = function () {
$("#doc-show-tool").show();
$(".doc-layout").removeClass("col-sm-6").addClass("col-sm-12"); //.doc-layout class变为col-sm-12
$("#doc-show-layout").fadeOut();
$("#doc-main-layout").fadeIn();
//变形完成
$("#doc-show").show();
$("#read-only").hide();
vm.autoHeight();
vm.now = 0
}
vm.toBoth = function () {
$("#read-only").hide();
$("#doc-show").show();
$("#nav-read").fadeOut(); //#nav-both class添加 hidden
$("#nav-write").fadeOut();
$(".doc-layout").removeClass("col-sm-6 col-sm-12").addClass("col-sm-6"); //.doc-layout class变为col-sm-12
$("#doc-main-layout").fadeIn();
$("#doc-show-layout").fadeIn(); //#doc-show-layout class添加hidden
$("#nav-both").fadeIn(); //#nav-write class 去除hidden
$("#doc-main-tool").find(".to-write").show();
$("#doc-show-tool").find(".to-read").show();
//变形完成
vm.autoHeight();
vm.now = 1
}
vm.toRead = function () {
$(".doc-layout").removeClass("col-sm-6 col-sm-12").addClass("col-sm-12"); //.doc-layout class变为col-sm-12
$("#doc-main-layout").fadeOut();
$("#doc-show-layout").fadeIn();
$("#doc-show").hide();
$("#doc-show-tool").hide();
$("#read-only").show();
$('.doc-layout').css('height', 'auto');
//变形完成
vm.now = 2
}
vm.autoHeight = function () {
if (vm.height == "auto") {
var adaptHeight = function () {
var x = $(window).height();
$('.doc-layout').css('height', (x - 90) + 'px');
};
adaptHeight();
$(window).resize(function () {
adaptHeight();
});
}
else {
$('.doc-layout').css('height', (vm.height - 90) + 'px');
}
}
//跟随滚动:
vm.doubleScroll = function () {
$(".live-sroll").hover(function () {
$(this).on("scroll", function () {
//得到要跟随滚动的ID值
//元素获取
var thisId = $(this).attr('id');
var otherId = thisId == "doc-show" ? "doc-main" : "doc-show";
//参数获取
var sh1 = document.getElementById(thisId).scrollHeight;
var st1 = $("#" + thisId).scrollTop();
var sh2 = document.getElementById(otherId).scrollHeight;
var h1 = $("#" + thisId).height();
var h2 = $("#" + otherId).height();
//跟随滚动公式
// 实际运动高度
//var l1 = (sh1 - h1);
//var l2 = (sh2 - h2);
//文本运动高度之比与实际运动高度之比相等
var st2 = st1 / (sh1 - h1) * (sh2 - h2);
//动作执行
$("#" + otherId).scrollTop(st2);
});
}, function () {
$(this).off("scroll");
});
}
//插入内容模块
vm.insert = function (f1, f2, n1, n2) {
//保存当前滚动高度
var sh = $("#doc-main").scrollTop();
var textarea = document.getElementById("doc-main");
var start = textarea.selectionStart;//获取光标所在位置对应的文本节点
var end = textarea.selectionEnd;
var l = vm.md.length;//获取整个文本总长度
//插入指定的东西
var t1 = vm.md.slice(0, start);
var t = vm.md.slice(start, end);
var t2 = vm.md.slice(end, l);
var afterMd = t1 + f1 + t + f2 + t2;
vm.md = afterMd;
//文本域获取焦点并且选中制定的文本
textarea.focus();
textarea.setSelectionRange(start + n1, end + n1 + n2);
//滚回原来的高度
$("#doc-main").scrollTop(sh);
//执行编译
vm.trs();
console.log()
}
//粗体
vm.bold = function () {
var textarea = document.getElementById("doc-main");
if (textarea.selectionStart == textarea.selectionEnd) {
vm.insert("**加粗的文字", "**", 2, 5)
}
else {
vm.insert("**", "**", 2, 0)
}
}
//斜体
vm.italic = function () {
var textarea = document.getElementById("doc-main");
if (textarea.selectionStart == textarea.selectionEnd) {
vm.insert("*倾斜的文字", "*", 1, 5)
}
else {
vm.insert("*", "*", 1, 0)
}
}
//插入连接
vm.links = function () {
vm.toggleModal(0)
if (vm.link == "") {
vm.link = "输入连接地址";
}
var textarea = document.getElementById("doc-main");
if (textarea.selectionStart == textarea.selectionEnd) {
vm.insert("[输入连接描述", "](" + vm.link + ")", 1, 6)
}
else {
vm.insert("[", "](" + vm.link + ")", 1, 0)
}
vm.link = "";
}
//表格
vm.table = function () {
vm.insert("\r\n", "表头一|表头二|表头三\r\n----|----|----\r\n行一列一|行一列二|行一列三\r\n行二列一|行二列二|行二列三\r\n行三列一|行三列二|行三列三", 1, 0)
}
//段落引用
vm.quote = function () {
vm.insert("\r\n> ", "", 3, 0)
}
//插入代码
vm.code = function () {
var textarea = document.getElementById("doc-main");
if (textarea.selectionStart == textarea.selectionEnd) {
vm.insert("```输入代码语言\r\n输入代码", "\r\n ```", 3, 6)
}
else {
vm.insert("```输入代码语言\r\n", "\r\n ```", 3, 6)
}
}
//插入图片
vm.img = function () {
function imgIn() {
//要插入
vm.toggleModal(0)
if (vm.imgUrl == "") {
vm.imgUrl = "输入图片URL地址";
}
var textarea = document.getElementById("doc-main");
if (textarea.selectionStart == textarea.selectionEnd) {
vm.insert("", 2, 6)
}
else {
vm.insert("", 2, 0)
}
vm.imgUrl = "";
}
if (vm.imgUrl == "") {
//没有 图片地址
var a = confirm("您还没有输入或上传图片,确定插入么?")
if (a) {
imgIn()
}
else {
//不要插入
}
} else {
//已有图片地址
imgIn()
}
}
//插入有序列表
vm.ol = function () {
vm.insert("\r\n1. ", "", 5, 0)
}
//插入无序列表
vm.ul = function () {
vm.insert("\r\n* ", "", 5, 0)
}
//插入标题h1
vm.h1 = function () {
var textarea = document.getElementById("doc-main");
if (textarea.selectionStart == textarea.selectionEnd) {
vm.insert("\r\n# 标题1", "\r\n", 3, 3)
}
else {
vm.insert("\r\n# ", "\r\n", 3, 0)
}
}
//插入标题h2
vm.h2 = function () {
var textarea = document.getElementById("doc-main");
if (textarea.selectionStart == textarea.selectionEnd) {
vm.insert("\r\n## 标题2", "\r\n", 4, 3)
}
else {
vm.insert("\r\n## ", "\r\n", 4, 0)
}
}
//插入标题h3
vm.h3 = function () {
var textarea = document.getElementById("doc-main");
if (textarea.selectionStart == textarea.selectionEnd) {
vm.insert("\r\n### 标题3", "\r\n", 5, 3)
}
else {
vm.insert("\r\n### ", "\r\n", 6, 0)
}
}
//插入标题h4
vm.h4 = function () {
var textarea = document.getElementById("doc-main");
if (textarea.selectionStart == textarea.selectionEnd) {
vm.insert("\r\n#### 标题4", "\r\n", 6, 3)
}
else {
vm.insert("\r\n#### ", "\r\n", 6, 0)
}
}
//插入标题h5
vm.h5 = function () {
var textarea = document.getElementById("doc-main");
if (textarea.selectionStart == textarea.selectionEnd) {
vm.insert("\r\n##### 标题5", "\r\n", 7, 3)
}
else {
vm.insert("\r\n##### ", "\r\n", 7, 0)
}
}
//插入分割线
vm.divider = function () {
vm.insert("", "\r\n---\r\n", 7, 0)
}
//分段落
vm.paragraph = function () {
vm.insert("\r\n\r\n", "", 2, 0)
}
//打开文件
vm.open = function (e) {
if (typeof FileReader == "undified") {
alert("您老的浏览器不行了!");
}
var resultFile = document.getElementById("file").files[0];
if (resultFile) {
var reader = new FileReader();
reader.readAsText(resultFile, 'UTF-8');
reader.onload = function (e) {
vm.md = this.result;
vm.toggleModal(0)
vm.trs();
};
tip.on("成功载入!最后更新日期:" + resultFile.lastModifiedDate, 1, 5000)
}
}
// //保存文件
vm.Base64 = {
_keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
encode: function (input) {
var output = "";
var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
var i = 0;
input = vm.Base64._utf8_encode(input);
while (i < input.length) {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output = output +
vm.Base64._keyStr.charAt(enc1) + vm.Base64._keyStr.charAt(enc2) +
vm.Base64._keyStr.charAt(enc3) + vm.Base64._keyStr.charAt(enc4);
}
return output;
},
decode: function (input) {
var output = "";
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0;
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
while (i < input.length) {
enc1 = vm.Base64._keyStr.indexOf(input.charAt(i++));
enc2 = vm.Base64._keyStr.indexOf(input.charAt(i++));
enc3 = vm.Base64._keyStr.indexOf(input.charAt(i++));
enc4 = vm.Base64._keyStr.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
output = output + String.fromCharCode(chr1);
if (enc3 != 64) {
output = output + String.fromCharCode(chr2);
}
if (enc4 != 64) {
output = output + String.fromCharCode(chr3);
}
}
output = vm.Base64._utf8_decode(output);
return output;
},
_utf8_encode: function (string) {
string = string.replace(/\r\n/g, "\n");
var utftext = "";
for (var n = 0; n < string.length; n++) {
var c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
}
else if ((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
}
else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
},
_utf8_decode: function (utftext) {
var string = "";
var i = 0;
var c = c1 = c2 = 0;
while (i < utftext.length) {
c = utftext.charCodeAt(i);
if (c < 128) {
string += String.fromCharCode(c);
i++;
}
else if ((c > 191) && (c < 224)) {
c2 = utftext.charCodeAt(i + 1);
string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
i += 2;
}
else {
c2 = utftext.charCodeAt(i + 1);
c3 = utftext.charCodeAt(i + 2);
string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
i += 3;
}
}
return string;
}
}
vm.save = function (ele) {
if (/msie/i.test(navigator.userAgent)) {
}
else {
var content = vm.md;
vm.file="data:application/octet-stream;base64,"+ vm.Base64.encode(content);
}
}
vm.saveFile = function () {
if (/msie/i.test(navigator.userAgent)) {
var path = prompt("输入保存路径和文件名", "D:\\" + "新建markdown文件.md");
var content = vm.md;
content = content.replace(/\n/g, "\r\n");
var fso = new ActiveXObject("Scripting.FileSystemObject");
var s = fso.CreateTextFile(path, true);
s.WriteLine(content);
s.Close();
}
else {
}
}
//下拉菜单
vm.dropdown = function (i) {
if (vm[i]) {
vm[i] = false
} else {
vm.dh = false
vm.dl = false
vm[i] = true
}
}
//模态框控制
vm.toggleModal= function (i) {
vm.showModal=i
}
},
$ready: function (vm, elem) {
switch (vm.initType) {
case 0:
vm.toWrite();//切换为专注书写模式
break;
case 1:
vm.toBoth();//切换为实时预览模式
break;
case 2:
vm.toRead();//切换为纯净阅读模式
break;
}
vm.autoHeight();//自适应高度
vm.doubleScroll();//实时预览双滚动
setTimeout(function () {
vm.getLoaclDoc()
}, 300)
}
})
})
|
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { AppStore } from "./redux/store";
import Routes from './Routes';
import 'antd/dist/antd.css';
import './index.css';
import { Layout, Menu, Breadcrumb } from 'antd';
const { Header, Content, Footer } = Layout;
const rootElement = document.getElementById("root");
ReactDOM.render(
<Provider store={AppStore}>
<Header>
<div className="logo" />
<Menu theme="dark" mode="horizontal" >
Previsão do Tempo
</Menu>
</Header>
<Routes />
</Provider>,
rootElement
);
|
import Cookies from 'js-cookie';
const SessionKey = 'ILDWotAuthLoginInfo';
const SessionIdKey = 'ILDWotAuthSession';
export function getSession() {
return Cookies.get(SessionKey);
}
export function setSession(sessionContent) {
return Cookies.set(SessionKey, sessionContent);
}
export function removeSession() {
return Cookies.remove(SessionKey);
}
export function getSessionId() {
return Cookies.get(SessionIdKey);
}
export function setSessionId(sessionContent) {
return Cookies.set(SessionIdKey, sessionContent);
}
export function removeSessionId() {
return Cookies.remove(SessionIdKey);
}
|
import Ember from 'ember';
// import config from '../config/environment';
// import Factory from 'ember-cli-pagination/factory';
// import pagedArray from 'ember-cli-pagination/computed/paged-array';
export default Ember.ArrayController.extend({
// pagedContent: pagedArray("content"),
// actions: {
// save: function() {
// this.forEach(function(t) {
// t.save();
// });
// }
// }
});
|
import React from 'react'
import * as Rebass from 'rebass'
import { Markdown } from '../src'
const md = `
# Hello
- This...
- is a list
- with list items
\`\`\`jsx
console.log('hi')
\`\`\`
\`\`\`.jsx
<h1>Hello, world!</h1>
\`\`\`
`
export default () => (
<div>
<Markdown
scope={Rebass}
src={md}
/>
</div>
)
|
import React from 'react';
import './App.css';
import { Switch, Route } from 'react-router-dom';
import NavBar from "./components/NavBar/NavBar";
import Home from "./components/Home/Home";
import ItemDetailContainer from "./components/ItemDetailContainer/ItemDetailContainer";
import CategoryContainer from "./components/CategoryContainer/CategoryContainer";
import CategoriesContainer from "./components/CategoriesContainer/CategoriesContainer";
import About from "./components/About/About";
import Contact from "./components/Contact/Contact";
import Cart from "./components/Cart/Cart";
import CartContextProvider from "./context/CartContext";
function App() {
return (
<CartContextProvider>
<div className="App">
<NavBar/>
<Switch>
<Route path="/item/:id" component={ItemDetailContainer}/>
<Route path="/about" component={About}/>
<Route path="/contact" component={Contact}/>
<Route exact path="/category/:id" component={CategoryContainer}/>
<Route path="/categories" component={CategoriesContainer}/>
<Route path="/cart" component={Cart}/>
<Route path="/" component={Home} />
</Switch>
{/*<Link to={'/list'}>Return to Home</Link>
<Link to={'/'}>Return to Home</Link>*/}
</div>
</CartContextProvider>
);
}
export default App;
|
import React, {useEffect} from 'react';
import './App.scss';
import {Route, Switch} from "react-router-dom";
import Auth from "../Auth/Auth";
import FlightsList from "../FlightsList/FlightsList";
import {useDispatch, useSelector} from "react-redux";
import {Redirect} from "react-router";
import {clearFavorite, flightDayClear} from "../../store/actions";
const App = () => {
const authorized = useSelector(state => state.auth.login);
const favorites = useSelector(state => state.favorites);
const dispatch = useDispatch();
useEffect(() => {
if (!authorized) {
dispatch(clearFavorite());
dispatch(flightDayClear());
}
}, [authorized])
return (
<div className={"App"}>
<Switch>
<Route exact path={'/'} component={Auth}/>
<Route path={'/flights-list'} component={FlightsList}/>
</Switch>
{authorized ? <Redirect to={'/flights-list'}/> : <Redirect to={'/'}/>}
</div>
)
}
export default App;
|
/*
FONCTIONS - PRÉPA 3 : Une première calculatrice
1. Déclarez la fonction calculer()
pour qu'elle gère les 4 opérations mathématiques de base :
addition, soustraction, multiplication et division.
Conseil : utilisez un switch pour basculer entre les différentes opérations.
2. Utilisez ensuite votre fonction pour calculer
- 4 + 6 (qui doit évidemment donner 10)
- 4 - 6 (qui doit évidemment donner -2)
- 2 * 0 (qui doit évidemment donner 0)
- 12 / 0 (qui doit donner Infinity)
Aide : votre fonction s'exécute avec le pattern suivant : calculer(nb1, "+", nb2)
*/
function calculer(nb1,signe,nb2){
switch (signe) {
case `+`:
calcul = nb1 + nb2;
break;
case `-`:
calcul = nb1 - nb2;
break;
case `*`:
calcul = nb1 * nb2;
break;
default:
calcul = nb1 / nb2;
}
return calcul;
}
console.log(calculer(parseInt(prompt(`entrer un nombre`)),prompt(`entrer + - * ou /`),parseInt(prompt(`entrer un nombre`))));
|
var Game = function() {
this.fps = 60;
var canvas = document.getElementById('world');
// the getContext method gives you a way to manipulate the canvas. It's like a portal to the canvas
this.context = canvas.getContext('2d');
this.WIDTH = canvas.width;
this.HEIGHT = canvas.height;
this.player = new Player(this);
// assigning this to a variable so that we don't have to invoke'this' everytime from the DOM
var game = this;
// setInterval performs the function in its first argument every x time where x is the second argument
var gameloop = setInterval(function(){
game.updateAll();
game.drawAll();
}, 1000 / this.fps);
}
Game.prototype.updateAll = function(){
// nothing here yet
this.player.update();
}
Game.prototype.drawAll = function(){
// nothing here yet
var obj = this;
obj.drawRectangle('#fff',0,0,this.WIDTH,this.HEIGHT);
obj.player.draw();
}
Game.prototype.drawRectangle = function(color,x,y,width,height){
var obj = this;
obj.context.fillStyle = color;
obj.context.fillRect(x,y,width,height);
}
|
/*
using:
circular positioning code:
http://stackoverflow.com/a/10152437/1644202
point at:
http://pointat.idenations.com/api
depends on:
jquery
https://github.com/thomas-dotworx/jqrotate (pointat)
*/
function createFields() {
$('.field').remove();
var container = $('#container');
for(var i = 0; i < +$('input:text').val(); i++) {
$('<div/>', {
'class': 'field',
'text': i + 1,
}).appendTo(container);
}
// console.log("create run");
}
function distributeFields(deg) {
deg = deg || 0;
var radius = 250;
var fields = $('.field:not([deleting])'), container = $('#container'),
width = container.width(), height = container.height(),
angle = deg || Math.PI*3.5, step = (2*Math.PI) / fields.length;
fields.each(function() {
var x = Math.round(width/2 + radius * Math.cos(angle) - $(this).width()/2);
var y = Math.round(height/2 + radius * Math.sin(angle) - $(this).height()/2);
if(window.console) {
// console.log($(this).text(), x, y);
}
$(this).css({
left: x + 'px',
top: y + 'px'
});
angle += step;
});
}
$('input').change(function() {
createFields();
distributeFields();
initPointAt();
});
var timer = null,
timer2 = null;
$('#addone').click(function() {
addOne();
});
function addOne(playerName){
// do not append to current, otherwise you see it moving through the container
$('.field').addClass('moveAni');
$('<div/>', {
'class': 'field',
'text': playerName
})
.css({
left: $('#container').width()/2-25 + 'px',
top: $('#container').height()/2-25 + 'px'})
.addClass('moveAni')
.appendTo('#container')
.pointat({
target: "#center",
defaultDirection: "down"
});
distributeFields();
// without css:
//$('.field').pointat("updateRotation");
// with css: for css move animation
clearInterval(timer); clearTimeout(timer2);
timer = setInterval(function() {
$('.field').pointat({
target: "#center",
defaultDirection: "down"
}); // does not seem to update correctly: .pointat("updateRotation")
}, 20);
timer2 = setTimeout(function() {
clearInterval(timer);
}, 420); // css animation timeout, interval +1 extra to update after the ani
// update input field
$('input:text').val($('.field').length);
}
$('#delone').click(function() {
$('#container .field:not([deleting]):last')
.attr('deleting', 'true')
.css({
left: $('#container').width()/2-25 + 'px',
top: $('#container').height()/2-25 + 'px'
})
.fadeOut(400, function() {
$(this).remove();
});
// do distribiution as if the currently out-animating fields are gone allready
distributeFields();
clearInterval(timer); clearTimeout(timer2);
timer = setInterval(function() {
$('.field').pointat({
target: "#center",
defaultDirection: "down"
}); // does not seem to update correctly: .pointat("updateRotation")
}, 20);
timer2 = setTimeout(function() {
clearInterval(timer);
}, 420); // css animation timeout, interval +1 extra to update after the ani
// update input field
$('input:text').val($('.field:not([deleting])').length); // update yet
});
createFields();
distributeFields();
initPointAt();
function initPointAt() {
$('.field').pointat({
target: "#center",
defaultDirection: "down",
xCorrection: -20,
yCorrection: -20
});
}
|
import Bold from './bold';
class Sub extends Bold {}
Sub.blotName = 'sub';
Sub.tagName = ['SUB'];
export default Sub;
|
import React from "react"
import styled from "styled-components"
import { useStaticQuery, graphql } from "gatsby"
import Image from "gatsby-image"
import {
ImageHeaderGrid,
BackgroundImageWrapper,
} from "../../../styles/Containers"
import useRenderBackgroundImage from "../../../hooks/useRenderBackgroundImage"
import useIsBackgroundReady from "../../../hooks/useIsBackgroundReady"
import BackgroundImageLoader from "../../Shared/BackgroundImageLoader"
import Headline3 from "../../Headlines/Headline3"
import KindalOneCopy from "./Copy/KindalOneCopy"
import Certifications from "./Certifications"
import { above } from "../../../styles/Theme"
const KindalSectionOne = () => {
const query = graphql`
query {
mobileKindal: file(
sourceInstanceName: { eq: "AboutImages" }
name: { eq: "about-kindal-600x1300" }
) {
childImageSharp {
fluid(maxWidth: 600, maxHeight: 1300, quality: 90) {
...GatsbyImageSharpFluid
}
}
}
tabletKindal: file(
sourceInstanceName: { eq: "AboutImages" }
name: { eq: "about-kindal-834x1112" }
) {
childImageSharp {
fluid(maxWidth: 834, maxHeight: 1112, quality: 90) {
...GatsbyImageSharpFluid
}
}
}
ipadProKindal: file(
sourceInstanceName: { eq: "AboutImages" }
name: { eq: "about-kindal-1024x1366" }
) {
childImageSharp {
fluid(maxWidth: 1024, maxHeight: 1366, quality: 90) {
...GatsbyImageSharpFluid
}
}
}
laptopKindal: file(
sourceInstanceName: { eq: "AboutImages" }
name: { eq: "about-kindal-1440x900" }
) {
childImageSharp {
fluid(maxWidth: 1440, maxHeight: 900, quality: 90) {
...GatsbyImageSharpFluid
}
}
}
}
`
const images = useStaticQuery(query)
const mobile = images.mobileKindal
const tablet = images.tabletKindal
const ipadPro = images.ipadProKindal
const laptop = images.laptopKindal
const background = useRenderBackgroundImage(mobile, tablet, ipadPro, laptop)
const backgroundReady = useIsBackgroundReady(background)
return (
<ExtendImageHeaderGrid>
<BackgroundImageWrapper>
{backgroundReady ? (
<Image fluid={background} />
) : (
<BackgroundImageLoader />
)}
</BackgroundImageWrapper>
<ContentWrapper>
<Headline3>Hi, I'm Kindal!</Headline3>
<KindalOneCopy />
<Certifications />
</ContentWrapper>
</ExtendImageHeaderGrid>
)
}
export default KindalSectionOne
const ExtendImageHeaderGrid = styled(ImageHeaderGrid)`
z-index: -1;
${above.ipadPro`
margin: 0;
`}
`
const ContentWrapper = styled.div`
margin: 80px 0 0 0;
padding: 0 0 0 16px;
grid-column: 1 / -1;
grid-row: 1 / -1;
justify-self: start;
display: flex;
flex-direction: column;
align-items: flex-start;
width: 60%;
z-index: 1;
${above.mobile`
margin: 100px 0 0 0;
padding: 0 0 0 40px;
width: 66%;
`}
${above.tablet`
margin: 240px 0 0 0;
`}
${above.ipadPro`
padding: 0 0 0 100px;
width: 60%;
`}
`
|
// console.log(values);
function ValidURL(str) {
var regex = /(http|https):\/\/(\w+:{0,1}\w*)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%!\-\/]))?/;
if (!regex.test(str)) {
// alert("Please enter valid URL.");
return false;
} else {
return true;
}
}
let arr = document.querySelectorAll(".input")
//---------caching the data entered by the user-----------
//getting data form cache
for (let i = 0; i < 4; i++) {
x = localStorage.getItem(`input${i}`);
if (x) {
arr[i].value = x;
}
}
//storing data in cache
for (let i = 0; i < 4; i++) {
arr[i].addEventListener("change", () => {
localStorage.setItem(`input${i}`, arr[i].value);
})
}
//updating the drop downs
updatelist();
function updatelist() {
let obj = localStorage.getItem("data");
if (obj != null) {
obj = JSON.parse(obj);
}
else {
obj = [];
}
var teachers = document.getElementById("teachers");
let html = ``;
let html2 = ``;
obj.forEach(function (element) {
let x = `<option value="${element.teacher}">${element.teacher}</option>`
html += x;
let y = `<option value="${element.class}">${element.class}</option>`
html2 += y;
})
teachers.innerHTML = html;
classes.innerHTML = html2;
}
//---------------linking both dropdowns-----------
document.getElementById("teachers").addEventListener("change", () => {
let index = document.getElementById("teachers").options.selectedIndex;
document.getElementById("classes").value = document.getElementById("classes").options[index].value;
});
document.getElementById("classes").addEventListener("change", () => {
let index = document.getElementById("classes").options.selectedIndex;
document.getElementById("teachers").value = document.getElementById("teachers").options[index].value;
});
var addbtn = document.getElementById("addbtn");
addbtn.addEventListener("click", () => {
let obj = {
"teacher": document.getElementById("inputteacher").value,
"class": document.getElementById("inputclass").value,
"meet": document.getElementById("inputmeet").value,
"gcr": document.getElementById("inputgcr").value
}
if (ValidURL(obj.meet) && ValidURL(obj.gcr) == true) {
if (obj.teacher && obj.class && obj.meet && obj.gcr != "") {
console.log("values updated", obj);
let data = JSON.parse(localStorage.getItem("data"));
if (data == null) { data = []; }
data.push(obj);
localStorage.setItem("data", JSON.stringify(data));
updatelist();
for (let i = 0; i < 4; i++) {
localStorage.removeItem(`input${i}`);
}
document.getElementById("inputteacher").value = "";
document.getElementById("inputclass").value = "";
document.getElementById("inputmeet").value = "";
document.getElementById("inputgcr").value = "";
}
}
if(obj.teacher==false){
document.querySelector("#inputteacher").style.border = "2px solid red";
setTimeout(() => {
document.querySelector("#inputteacher").style.border = "2px solid black";
}, 2000);
}
if(obj.class==false){
document.querySelector("#inputclass").style.border = "2px solid red";
setTimeout(() => {
document.querySelector("#inputclass").style.border = "2px solid black";
}, 2000);
}
if(ValidURL(obj.meet)==false){
document.querySelector("#inputmeet").style.border = "2px solid red";
setTimeout(() => {
document.querySelector("#inputmeet").style.border = "2px solid black";
}, 2000);
}
if(ValidURL(obj.gcr)==false){
document.querySelector("#inputgcr").style.border = "2px solid red";
setTimeout(() => {
document.querySelector("#inputgcr").style.border = "2px solid black";
}, 2000);
}
});
document.getElementById("meetbtn").addEventListener("click", () => {
let index = (document.getElementById("classes").options.selectedIndex);
let data = localStorage.getItem("data");
if (data != null) {
data = JSON.parse(data);
}
else {
data = [];
}
console.log(data[index].meet);
chrome.tabs.query({ currentWindow: true, active: true }, function (tabs) {
var activeTab = tabs[0];
chrome.tabs.sendMessage(activeTab.id, { "message": "btnclicked", "link": data[index].meet });
});
// console.log(document.getElementById("teachers").options.selectedIndex);
//link of the meet or obj is values[index]
});
document.getElementById("gcrbtn").addEventListener("click", () => {
let index = (document.getElementById("classes").options.selectedIndex);
let data = localStorage.getItem("data");
if (data != null) {
data = JSON.parse(data);
}
else {
data = [];
}
console.log(data[index].gcr); //link of the meet or obj is values[index]
chrome.tabs.query({ currentWindow: true, active: true }, function (tabs) {
var activeTab = tabs[0];
chrome.tabs.sendMessage(activeTab.id, { "message": "btnclicked", "link": data[index].gcr });
});
});
document.getElementById("delbtn").addEventListener("click", () => {
let index = (document.getElementById("classes").options.selectedIndex);
// console.log(values[index].gcr); //link of the meet or obj is values[index]
let data = localStorage.getItem("data");
if (data != null) {
data = JSON.parse(data);
}
else {
data = [];
}
data.splice(index, 1);
localStorage.setItem("data", JSON.stringify(data));
updatelist();
});
|
import Vue from 'vue'
import moment from 'moment'
import VueResource from 'vue-resource'
import Constants from '../bean/Constants'
import {authService} from '../components/auth/auth-service'
import {RendezVousBean} from '../bean/RendezVousBean'
Vue.use(VueResource)
export class RendezVousResource {
// Recherche des rendez-vous pour une date précise
findRendezVous (result, date) {
return Vue.http.get(Constants.back.hostname + '/rdvs?date=' + date,
{
headers: {
'uid': authService.getAuthInfo().uid,
'email': authService.getAuthInfo().email
}
}).then(response => {
result(null, response.data)
}, response => {
result(response, null)
})
}
// Recherche des rendez-vous pour une date précise
findClientRendezVous (dayRange, result) {
return Vue.http.get(Constants.back.hostname + '/rdvs?dayRange=' + dayRange + '&clientRequired=true',
{
headers: {
'uid': authService.getAuthInfo().uid,
'email': authService.getAuthInfo().email
}
}).then(response => {
result(null, response.data)
}, response => {
result(response, null)
})
}
// Rectourne la timeline, contenant également les infos de distance, pour une journée donnée
getTimeline (result, date) {
return Vue.http.get(Constants.back.hostname + '/rdv/timeline?date=' + date,
{
headers: {
'uid': authService.getAuthInfo().uid,
'email': authService.getAuthInfo().email
}
}).then(response => {
result(null, response.data)
}, response => {
result(response, null)
})
}
// Recherche des dates possédant des rdvs existants pour une adresse donnée
findPropositionRendezVous (days, distance, placeId, adresseId, result) {
return Vue.http.get(Constants.back.hostname + '/rdv/search?dayRange=' + days + '&distanceRange=' + distance + '&placeId=' + placeId + '&adresseId=' + adresseId,
{
headers: {
'uid': authService.getAuthInfo().uid,
'email': authService.getAuthInfo().email
}
}).then(response => {
result(null, response.data)
}, response => {
result(response, null)
})
}
// Recherche des dates disponibles pour le mois sélectionné
findFreeDays (month, year, result) {
let startDate = moment([year, month]).format(Constants.rdv.dateFormat)
let endDate = moment(startDate).endOf('month').format(Constants.rdv.dateFormat)
return Vue.http.get(Constants.back.hostname + '/rdv/free?startDate=' + startDate + '&endDate=' + endDate,
{
headers: {
'uid': authService.getAuthInfo().uid,
'email': authService.getAuthInfo().email
}
}).then(response => {
result(null, response.data)
}, response => {
result(response, null)
})
}
createRendezVous (rdvForm, client, result) {
let rdv = this.map(rdvForm, client)
return Vue.http.post(Constants.back.hostname + '/rdv', rdv,
{
headers: {
'uid': authService.getAuthInfo().uid,
'email': authService.getAuthInfo().email
}
}).then(response => {
result(null)
}, response => {
result(response)
})
}
map (rdvForm, client) {
let rdv = new RendezVousBean()
rdv.placeId = rdvForm.placeId
rdv.client = client.id
rdv.adresseId = client.adresse.id
rdv.appareils = rdvForm.appareils
rdv.event.id = rdvForm.event.id
rdv.event.date = moment(rdvForm.event.date).format(Constants.rdv.dateFormat)
rdv.event.startTime = rdvForm.event.startTime
rdv.event.endTime = rdvForm.event.endTime
rdv.event.summary = rdvForm.event.summary
rdv.event.description = rdvForm.event.description
rdv.event.location = rdvForm.event.location
rdv.event.status = rdvForm.event.status
return rdv
}
}
|
import React, { Component } from 'react';
import users from '../files/users.json';
class Tableau extends Component {
// const names = props.names;
// const listNames = names.map(())
render() {
const monTableau = [
{
name: "NOM",
email: "e@mail",
age: "AGE",
city: "city"
}
]
const projects = monTableau.map( project =>
<tr className="Project">
<td>{project.name}</td>
<td>{project.email}</td>
<td>{project.age}</td>
<td>{project.city}</td>
</tr>
)
return (
<div>
<h1>TITRE LOREM IPSUM</h1>
<p>Le Lorem Ipsum est simplement du faux texte employé dans la composition et la mise en page avant impression.</p>
{projects}
</div>
);
}
}
export default Tableau;
|
'use strict'
/** @type {typeof import('@adonisjs/lucid/src/Lucid/Model')} */
const driver = require('bigchaindb-driver')
const Env = use('Env')
class Bigchain {
Bigchain() {
this.Bigchain_URL = Config.get('BIGCHAIN_URL')
this.Connection = new driver.Connection(this.Bigchain_URL);
}
store(data, metaData, publicKey, privateKey) {
}
getFiles(publicKey) {
var con = new driver.Connection('http://localhost:9984/api/v1/');
try {
return con.searchAssets(publicKey);
} catch(error) {
return error;
}
}
}
module.exports = Bigchain
|
var header = require('../header.js');
/*
============================================
; Title: Program Header
; Author: Professor Krasso
; Date: 09 January 2018
; Modified By: Heather Peterson
; Description: Exercise 5.3 - Object Collections
;===========================================
/*
Expected output:
FirstName LastName
Exercise 5.3
Today's Date
-- COMPOSERS --
Last Name: Beethoven, Genre: Classical, Rating: 8
Last Name: Mozart, Genre: Classical, Rating: 10
Last Name: Bach, Genre: Classical, Rating: 9
Last Name: Haydn, Genre: Classical, Rating: 6
Last Name: Schubert, Genre: Classical, Rating: 5
*/
// start program
var famousComposers = [ // Array-Like Object of 5 famous composers
{
firstName: 'Ludwig',
lastName: 'Beethoven',
genre:'Classical',
rating: '8'
},
{
firstName: 'Johannes',
lastName: 'Mozart',
genre: 'Classical',
rating: '10'
},
{
firstName: 'Johann',
lastName: 'Bach',
genre:'Classical',
rating: '6'
},
{
firstName:'Franz',
lastName:'Haydn',
genre: 'Classical',
rating: '6'
},
{
firstName: 'Franz',
lastName:'Schubert',
genre: 'Classical',
rating: '5'
},
];
console.log("-- COMPOSERS --"); // display text of Composers
famousComposers.forEach(function(composer){ // iteration through the forEach() method
console.log("Last Name: " + composer.lastName + ", " + "Genre: " + composer.genre + ", " + "Rating: " + composer.rating)
}); //output of composers last names, genres, and ratings
// end program
|
import React, { Component } from 'react';
import moment from 'moment';
import "moment/locale/ja";
import { AutoComplete, Row, Col, Spin } from 'antd';
import RouteCard from './RouteCard';
import './App.css';
const API_HOST = "https://fth.babu.ml";
class App extends Component {
constructor(props) {
super(props);
this.resultTimer = null;
this.state = {
dataSourceDeparture: [],
dataSourceArrival: [],
departure: "",
arrival: "",
loading: false,
routes: [],
};
}
componentDidMount() {
const { params } = this.props.match;
if (Object.keys(params).length === 2) {
this._fetchResult(params.departure, params.arrival);
this.setState({departure: params.departure});
this.setState({arrival: params.arrival});
this.resultTimer = window.setInterval(this._fetchResult, 30000, params.departure, params.arrival);
}
}
_setSource = (way, stops) => {
if (way === "departure") this.setState({dataSourceDeparture: stops});
else this.setState({dataSourceArrival: stops});
}
handleSearch = (way, value) => {
window.clearInterval(this.resultTimer);
if (value === "") {
this._setSource(way, []);
}
fetch(`${API_HOST}/search/${value}`)
.then(res => res.json())
.then(json => {
let stops = [];
stops = json.map(j => j.stopName);
this._setSource(way, stops);
});
}
_setStop = (way, value) => {
if (way === "departure") this.setState({departure: value});
else this.setState({arrival: value});
}
_fetchResult = (departure, arrival) => {
this.setState({loading: true});
fetch(`${API_HOST}/result/${departure}/${arrival}`)
.then(res => res.json())
.then(json => {
json = json.map(j => {
const departure = j.predicted_time_departure.split(":");
const departure_time = moment().hour(departure[0]).minute(departure[1]);
j["remaining"] = departure_time.fromNow();
return j;
}).sort((a, b) => {
const departure_time = [a, b].map(d => {
const departure = d.predicted_time_departure.split(":");
return moment().hour(departure[0]).minute(departure[1]);
});
return departure_time[0] > departure_time[1];
});
this.setState({routes: json})
})
.then(() => this.setState({loading: false}));
}
handleSelect = async(value, prop) => {
const way = prop._owner.memoizedProps.id;
await this._setStop(way, value);
if (this.state.departure && this.state.arrival) {
this._fetchResult(this.state.departure, this.state.arrival);
window.history.pushState(null, null, `/fuck-the-h4k0bu5-v2/${this.state.departure}/${this.state.arrival}`);
window.clearInterval(this.resultTimer);
this.resultTimer = window.setInterval(this._fetchResult, 30000, this.state.departure, this.state.arrival);
}
}
render() {
const { departure, arrival } = this.props.match.params;
let searchTimerDeparture, searchTimerArrival;
const searcherDeparture = value => {
window.clearTimeout(searchTimerDeparture);
searchTimerDeparture = window.setTimeout(this.handleSearch, 1000, "departure", value);
}
const searcherArrival = value => {
window.clearTimeout(searchTimerArrival);
searchTimerArrival = window.setTimeout(this.handleSearch, 1000, "arrival", value);
}
return (
<div>
<Row>
<Col key={1} sm={24} md={12}>
<AutoComplete id="departure"
defaultValue={departure}
dataSource={this.state.dataSourceDeparture}
style={{ width: 200 }}
onSearch={searcherDeparture}
onSelect={this.handleSelect}
placeholder="出発地"
/>
</Col>
<Col key={2} sm={24} md={12}>
<AutoComplete id="arrival"
defaultValue={arrival}
dataSource={this.state.dataSourceArrival}
style={{ width: 200 }}
onSearch={searcherArrival}
onSelect={this.handleSelect}
placeholder="到着地"
/>
</Col>
</Row>
<Row type="flex" justify="center">
<Spin spinning={this.state.loading} />
</Row>
<Row id="routes">
{this.state.routes.map((route, key) => (
<Col key={key} sm={24} md={12}>
<RouteCard route={route} />
</Col>
))}
</Row>
</div>
);
}
}
export default App;
|
import React from "react";
import { Search, Form, SearchIcon } from "../style";
export function SearchComponent(props) {
const search = require("../../icons/search.png");
return (
<>
<Form>
<SearchIcon src={search} alt="Search"></SearchIcon>
<Search type="search" placeholder="Search or start new chat" />
</Form>
</>
);
}
|
/* 🤖 this file was generated by svg-to-ts*/
export const EOSIconsEco = {
name: 'eco',
data: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M6.05 8.05a7.001 7.001 0 00-.02 9.88c1.47-3.4 4.09-6.24 7.36-7.93A15.952 15.952 0 008 19.32c2.6 1.23 5.8.78 7.95-1.37C19.43 14.47 20 4 20 4S9.53 4.57 6.05 8.05z"/></svg>`
};
|
const request = require('supertest');
const redis = require('redis-mock');
const app = require('../src/app');
let mockRedis = {
addEventToList: jest.fn(() => Promise.resolve()),
getData: jest.fn(() => Promise.resolve()),
};
require('../src/routes')(app, mockRedis);
afterEach(() => {
mockRedis.addEventToList.mockClear();
mockRedis.getData.mockClear();
});
describe('Test the /logs path', () => {
test('It should response the GET method with content type JSON', (done) => {
request(app).get('/logs').expect('Content-Type', /json/).then((response) => {
expect(response.statusCode).toBe(200);
expect(mockRedis.getData).toHaveBeenCalledTimes(1);
done();
});
});
});
describe('Test the /data path', () => {
test('It should response the GET method with content type JSON', (done) => {
request(app).get('/data').expect('Content-Type', /json/).then((response) => {
expect(response.statusCode).toBe(200);
expect(mockRedis.getData).toHaveBeenCalledTimes(1);
done();
});
});
});
describe('Test the /addData path', () => {
test('It should response with status 400 and messege field when "name" not present in request', (done) => {
request(app).post('/addData')
.send({
text: 'text'
})
.expect('Content-Type', /json/).then((response) => {
expect(response.statusCode).toBe(400);
expect(response.body).toHaveProperty('message', 'Error: payload does not have field "name".');
expect(mockRedis.addEventToList).toHaveBeenCalledTimes(0);
done();
});
});
test('It should response with status 400 and messege field when "text" not present in request', (done) => {
request(app).post('/addData')
.send({
name: 'name'
})
.expect('Content-Type', /json/).then((response) => {
expect(response.statusCode).toBe(400);
expect(response.body).toHaveProperty('message', 'Error: payload does not have field "text".');
expect(mockRedis.addEventToList).toHaveBeenCalledTimes(0);
done();
});
});
test('It should response with status 201 and {message: "success"}', (done) => {
request(app).post('/addData')
.send({
name: 'name',
text: 'text'
})
.expect('Content-Type', /json/).then((response) => {
expect(response.statusCode).toBe(201);
expect(response.body).toHaveProperty('message', 'success');
expect(mockRedis.addEventToList).toHaveBeenCalledTimes(2); // twice, because we add two events in different redis lists
done();
});
});
});
|
import { renderString } from '../../src/index';
describe(`Apply Python string formatting to an object.`, () => {
it(`%s can be replaced with other variables or values`, () => {
const html = renderString(`{{ "Hi %s %s"|format(contact.firstname, contact.lastname) }} `);
});
});
|
import React, { Component } from 'react'
import { Link, NavLink } from 'react-router-dom'
/**
The main top menu
**/
class MainMenu extends Component {
render() {
return (
<nav id="main-menu" className="navbar navbar-expand-lg fixed-top">
<button className="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span className="navbar-toggler-icon"></span>
</button>
<Link className="navbar-brand" to="/">Giveth</Link>
<div className="collapse navbar-collapse" id="navbarSupportedContent">
<ul className="navbar-nav mr-auto">
<li className="nav-item">
<NavLink className="nav-link" to="/dacs" activeClassName="active">DACs</NavLink>
</li>
<li className="nav-item">
<NavLink className="nav-link" to="/campaigns" activeClassName="active">Campaigns</NavLink>
</li>
{this.props.authenticated &&
<li className="nav-item">
<NavLink className="nav-link" to="/dashboard" activeClassName="active">Dashboard</NavLink>
</li>
}
{this.props.authenticated &&
<li className="nav-item">
<NavLink className="nav-link" to="/profile" activeClassName="active">Profile</NavLink>
</li>
}
</ul>
<ul className="navbar-nav ml-auto mr-sm-2">
{ !this.props.authenticated &&
<li className="nav-item">
<Link className="btn btn-outline-secondary" to="/signin">Sign In</Link>
</li>
}
</ul>
<form id="search-form" className="form-inline my-2 my-lg-0">
<input className="form-control mr-sm-2" type="text" placeholder="E.g. save the whales"/>
<button className="btn btn-outline-success my-2 my-sm-0" type="submit">Find</button>
</form>
</div>
</nav>
)
}
}
export default MainMenu
|
import React from 'react';
import { QueryTable } from 'sula';
import { remoteDataSource } from './config';
import access from '@/components/access';
// form表单项基础配置
export const basicFields = [
{
name: 'name',
label: '姓名',
field: {
type: 'input',
props: {
placeholder: '请输入',
},
},
rules: [{ required: true, message: '请输入姓名' }],
},
{
name: 'ages',
label: '年龄',
field: {
type: 'inputnumber',
props: {
placeholder: '请输入',
min: 1,
max: 100,
style: {
width: '100%',
},
},
},
rules: [{ required: true, message: '请输入年龄' }],
},
{
name: 'address',
label: '地址',
field: {
type: 'textarea',
props: {
placeholder: '请输入',
},
},
},
];
export const initialValuesForm = {
name: 'sula',
ages: 12,
address: '杭州市西湖区支付宝大楼',
};
const Normatble = (props) => {
const [formType, setFormType] = React.useState('modalForm');
const format = props.formatMessage;
const config = {
remoteDataSource,
tableProps: {
size: 'small',
},
itemLayout: {
cols: 4,
labelCol: { // label标签布局;可设置 span、offset
span: 6
},
wrapperCol: { // value布局, 方式同labelCol(horizontal状态下配置)
span: 18,
}
},
layout: 'horizontal',
rowSelection: {
onChange: () => {
},
},
actionsRender: [
{
type: 'button',
visible: ctx => {
const selectedRowKeys = ctx.table.getSelectedRowKeys() || [];
return selectedRowKeys.length;
},
props: {
children: '批量删除',
type: 'primary',
},
action: [
ctx => {
console.log(ctx.table.getSelectedRowKeys(), '批量删除');
},
],
},
{
type: 'button',
props: {
children: '创建',
type: 'primary',
},
action: [
{
type: formType,
title: '创建',
fields: basicFields,
submit: {
url: 'https://www.mocky.io/v2/5ed7a8b63200001ad9274ab5',
method: 'POST',
},
},
'refreshtable',
],
},
{
type: 'button',
props: {
children: '刷新',
type: 'primary',
},
action: ['refreshTable'],
},
],
fields: [
{
name: 'name',
label: '文本框',
field: {
type: 'input',
props: {
allowClear: true,
placeholder: '请输入内容',
}
},
},
{
name: 'name1',
label: '单选下拉框',
initialSource: [
{
text: '水果',
value: 'fruit',
},
{
text: '蔬菜',
value: 'vegetables',
},
],
field: {
type: 'select',
props: {
allowClear: true,
placeholder: '请选择',
},
},
},
{
name: 'remote',
label: '下拉框接口',
field: {
type: 'select',
props: {
allowClear: true,
placeholder: '请选择',
},
},
remoteSource: {
url: 'https://mocks.alibaba-inc.com/mock/sula_doc/demo/select.json',
method: 'get',
},
},
{
name: 'backFormat',
label: '日期格式',
field: {
type: 'datepicker',
props: {
placeholder: '请输入',
valueFormat: true,
},
},
},
{
name: 'basic',
label: '级联',
initialSource: [
{
value: 'zhejiang',
text: '浙江',
children: [
{
value: 'hangzhou',
text: '杭州',
children: [
{
value: 'xihuqu',
text: '西湖区',
},
],
},
{
value: 'ningbo',
text: '宁波',
},
],
},
{
value: 'shanghai',
text: '上海',
},
],
field: {
type: 'cascader',
props: {
placeholder: '请输入',
},
},
},
{
name: 'name5',
label: format({ id: 'event.name' }),
field: 'input',
},
{
name: 'name6',
label: format({ id: 'event.name' }),
field: 'input',
},
{
name: 'name7',
label: format({ id: 'event.name' }),
field: 'input',
},
],
columns: [
{
key: 'name',
title: '规则名称',
},
{
key: 'desc',
title: '描述',
},
{
key: 'callNo',
title: '服务调用次数',
renrenderderText: (val) => `${val} 万`,
},
{
key: 'gender',
title: '性别',
render: ({ text }) => {
return text === 'male' ? '男' : '女';
},
},
{
key: 'operator',
title: "操作",
width: 260,
render: [
{
type: 'link',
props: {
children: '详情',
},
disabled: '#{record.running}',
action: ['refreshtable'],
},
{
type: 'link',
props: {
children: '编辑',
},
action: [
{
type: 'route',
path: '/query-table/normal-table/create?name=#{record.name}',
},
],
},
]
},
],
rowKey: 'key',
};
return (
<div>
<QueryTable {...config} />
</div>
);
};
export default access(Normatble);
|
(function (state) {
var threads = Object.keys(state.threads || {}).map(renderThread);
function renderThread (id) { return _.thread(state.threads[id]) }
return $.h(".app",
[ _.status(state)
, $.h(".content", [_.form()].concat(threads.reverse())) ]);
})
|
Discourse.KbDataType = Discourse.Model.extend({
// fields:
// name - the longer hyphenated name for the type, e.g. glycemic-problems
// shortName - a one-word name for the type, e.g. glyprobs, triggers
// abbrv - a two letter abbreviation
title: function() {
return I18n.t('diaedu.' + this.get('shortName') + '.title.other');
}.property('shortName'),
singularTitle: function() {
return I18n.t('diaedu.' + this.get('shortName') + '.title.one');
}.property('shortName'),
singularShortName: function() {
return this.get('shortName').slice(0,-1);
}.property('shortName'),
modelClass: function() {
return Discourse['Kb' + this.get('singularShortName').capitalize()];
}.property('shortName'),
backendPath: function() {
return '/kb/' + this.get('name');
}.property('name'),
iconPath: function() {
return '/assets/diaedu/' + this.get('shortName') + '-active.png';
}.property('shortName'),
smallerIconPath: function() {
return '/assets/diaedu/' + this.get('shortName') + '-smaller.png';
}.property('shortName'),
});
Discourse.KbDataType.reopenClass({
byName: null,
get: function(which) { var self = this;
// if which is an integer, just return that one
if (typeof(which) == 'number')
return this.instances[which];
else {
// build the hash if not built already
if (!this.byName) {
this.byName = {};
this.instances.forEach(function(dt){ self.byName[dt.name] = dt; });
}
return this.byName[which];
}
},
findByAbbrv: function(abbrv) { var self = this;
return self.instances.filter(function(dt){ return dt.get('abbrv') == abbrv; })[0];
},
// total number of instances
count: 4,
instances: [
Discourse.KbDataType.create({
name: 'glycemic-problems',
shortName: 'glyprobs',
abbrv: 'gp'
}),
Discourse.KbDataType.create({
name: 'triggers',
shortName: 'triggers',
abbrv: 'tr'
}),
Discourse.KbDataType.create({
name: 'barriers',
shortName: 'barriers',
abbrv: 'br'
}),
Discourse.KbDataType.create({
name: 'goals',
shortName: 'goals',
abbrv: 'gl'
})
]
});
|
import React, { Component, createRef } from "react";
import ReactGA from "react-ga";
import { viewports } from "./viewports";
import "./responsiveTest.css";
export default class ResponsiveTest extends Component {
state = {
url: "",
setUrlToIframe: null,
selectedViewport: "1280x800",
};
iframeRef = createRef(null);
handleChange = (event) => {
event.preventDefault();
const { value } = event.target;
this.setState({ url: value });
};
handleSubmit = (event) => {
event.preventDefault();
this.setState({ setUrlToIframe: this.state.url });
ReactGA.event({
category: "click",
action: "Inspect Clicked",
});
};
handleViewportChange = (event) => {
const { value } = event.target;
this.setState({ selectedViewport: value });
};
render() {
const { setUrlToIframe, selectedViewport } = this.state;
const viewportValue = viewports.find(
(item) => item.selector === selectedViewport
);
return (
<div className="responsive-test-container">
<div className="row">
<form className="col-sm-8">
<label htmlFor="url">Enter URL</label>
<div className="input-group shadow-sm">
<input
id="url"
type="text"
placeholder="https://..."
className="form-control rounded-0"
onChange={this.handleChange}
/>
<div className="input-group-append">
<button
className="btn btn-outline-secondary rounded-0"
type="button"
id="button-addon2"
onClick={this.handleSubmit}
>
Inspect
</button>
</div>
</div>
<span className="font-weight-light font-italic font-smaller">
Please enter full URL e.g: https://google.com
</span>
</form>
<div className="col-sm-4">
<label htmlFor="url">Select Viewport</label>
<select
className="form-control rounded-0 shadow-sm"
value={selectedViewport}
onChange={this.handleViewportChange}
>
{viewports.map((item, index) => (
<option key={index} value={item.selector}>
{item.name}
</option>
))}
</select>
</div>
</div>
<div className={`frame ${setUrlToIframe ? "loader" : ""}`}>
<iframe
title="frame"
ref={this.iframeRef}
id="web-frame"
src={setUrlToIframe}
frameBorder="0"
width={viewportValue && viewportValue.width}
height={viewportValue && viewportValue.height}
></iframe>
</div>
</div>
);
}
}
|
'use strict'
angular.module('tutorialize')
.component('admin', {
templateUrl: './views/admin/admin.html',
controller: Admin
})
function Admin($resource, $scope) {
let request = $resource('/tuto/all');
request.get().$promise.then((data) => { // REQUETE DES TUTORIELS
let tutorials = data.tuto;
tutorials.map((e) => { // On parcours les tutos pour savoir si il est possible de remplacer le txt techno par une image
/* let technos = [];
for (let i = 0; i < e.techno.length; i++) {
let obj = {
name: e.techno[i],
hasImg: availableTechnosIcons.indexOf(e.techno[i].toLowerCase()) > -1
}
technos.push(obj);
}
e.techno = technos;*/
// On convertis la date en format lisible
e.datePost = new Date(e.datePost).toLocaleDateString();
e.dateCreate = new Date(e.dateCreate).toLocaleDateString();
return e;
});
this.tutos = tutorials;
this.tutosCopy = [].concat(tutorials);
$scope.predicates = ['lang', 'title', 'language', 'dateTuto', 'datePost', 'link', 'price', 'flags', 'valid'];
$scope.selectedPredicate = $scope.predicates[8];
});
this.valid = function (id) {
console.log("ID: ", id);
let request = $resource('/tuto/valid/' + id);
request.save().$promise.then((data) => {
let index = this.tutos.findIndex((e) => {
return e._id == id;
});
console.log(index);
let item = this.tutos.splice(index, 1)[0];
item.isValid = data.valid;
this.tutos.push(item);
console.log('Validey', this.tutos);
});
}
this.edit = function (id) {
}
// Function that resets flags to 0
this.clearFlags = function (id) {
}
this.delete = function (id) {
let request = $resource('/tuto/' + id);
request.delete().$promise.then((data) => {
this.tutos.splice(this.tutos.findIndex((e) => e._id = id), 1);
});
}
}
|
import React, { Component } from 'react';
import PageSwitch from 'pageswitch';
import Slide1 from './components/Slide1/Slide1';
import Slide2 from './components/Slide2/Slide2';
import Slide3 from './components/Slide3/Slide3';
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
activeIndex: null
}
this.pw = null;
this.colors = [
'linear-gradient(to top, #4e54c8, #8f94fb)',
'linear-gradient(to bottom, #59c173, #a17fe0, #5d26c1)',
'linear-gradient(to bottom, #00c6ff, #0072ff)',
'linear-gradient(to top, #396afc, #2948ff)',
];
}
componentDidMount() {
this.pw = new PageSwitch('switcher',{
duration:600,
direction:0,
start:0,
loop:false,
ease:'ease',
transition:'flip3d',
freeze:false,
mouse:true,
mousewheel:true,
arrowkey:true,
autoplay:false,
});
this.pw.on('before', (index, prev) => {
});
this.pw.on('after', index => {
this.setState({ activeIndex: index });
});
setTimeout(() => {
this.setState({ activeIndex: 0 });
}, 1000);
}
shouldComponentUpdate(nextProps, { activeIndex }) {
return activeIndex !== this.state.activeIndex;
}
render() {
const { activeIndex } = this.state;
return (
<div className="App" style={{height: window.innerHeight}}>
<div id='switcher'>
<Slide2
color={this.colors[1]}
activeIndex={activeIndex}
index={0} />
<Slide1
text1='Happy'
text2="Fathers's Day!"
color={this.colors[0]}
activeIndex={activeIndex}
index={1}
classes={activeIndex === 1 ? 'slide1 slide1-show' : 'slide1'} />
<Slide3
color={this.colors[3]}
activeIndex={activeIndex}
index={2}
classes={activeIndex === 2 ? 'slide3 slide3-show' : 'slide3'} />
<Slide1
text1='Alex'
text2=''
color={this.colors[2]}
activeIndex={activeIndex}
index={3}
classes={activeIndex === 3 ? 'slide1 slide-end slide1-show' : 'slide1 slide-end'} />
</div>
</div>
);
}
}
|
'use strict';
var logger = require('yocto-logger');
var _ = require('lodash');
var Q = require('q');
var Schema = require('mongoose').Schema;
/**
*
* Manage Crud function for adding model
*
* @date : 25/09/2015
* @author : Mathieu ROBERT <mathieu@yocto.re>
* @copyright : Yocto SAS, All right reserved
*
* @class Crud
*/
function Crud (logger) {
/**
* Logger instance
*
* @property logger
*/
this.logger = logger;
/**
* Alias object for exclusion process
*
* @property alias
*/
this.alias = {
'create' : [ 'insert' ],
'get' : [ 'read' ],
'getOne' : [ 'readOne' ],
'delete' : [ 'destroy' ],
'update' : [ 'modify' ]
};
}
/**
* Alias method for create method
*
* @return {Promise} promise object to use for handling
*/
Crud.prototype.insert = function () {
// default instance
return this.create.apply(this, arguments);
};
/**
* Alias method for get method
*
* @return {Promise} promise object to use for handling
*/
Crud.prototype.read = function () {
// default instance
return this.get.apply(this, arguments);
};
/**
* Alias method for getOne method
*
* @return {Promise} promise object to use for handling
*/
Crud.prototype.readOne = function () {
// default instance
return this.getOne.apply(this, arguments);
};
/**
* Alias method for update method
*
* @return {Promise} promise object to use for handling
*/
Crud.prototype.modify = function () {
// default instance
return this.update.apply(this, arguments);
};
/**
* Alias method for delete method
*
* @return {Promise} promise object to use for handling
*/
Crud.prototype.destroy = function () {
// default instance
return this.delete.apply(this, arguments);
};
/**
* Get One item from given rules
*
* @param {String|Object} conditions conditions to use for search
* @param {String|Object} filter filter to use to process filter
* @return {Promise} promise object to use for handling
*/
Crud.prototype.getOne = function (conditions, filter) {
// call main get function
return this.get(conditions, filter, 'findOne');
};
/**
* Get data from a model
*
* @param {Object|String} conditions query rules to add in find
* @param {Object} filter object property to process filter action
* @param {String} method id a method name is ginve force method name usage
* @return {Promise} promise object to use for handleling
*/
Crud.prototype.get = function (conditions, filter, method) {
// process redis usage
var redis = this[ method === 'findOne' ? 'getOneRedis' : 'getRedis' ];
// defined default method name to use
method = _.isString(method) && !_.isEmpty(method) ? method : 'find';
// is string ? so if for findById request. change method name
method = _.isString(conditions) ? 'findById' : method;
// Create our deferred object, which we will use in our promise chain
var deferred = Q.defer();
// normalize filter object
filter = _.isString(filter) && !_.isEmpty(filter) ? filter : '';
// save context for possible strict violation
var context = this;
/**
* Default method to retreive data
*
* @param {Object|String} conditions query rules to add in find
* @param {Object} filter object property to process filter action
*/
function defaultFind (conditions, filter, store) {
// normal process
context[method](conditions, filter, function (error, data) {
// has error ?
if (error) {
// reject
deferred.reject(error);
} else {
// in case of no data
if (_.isObject(store)) {
// store data on db
redis.instance.add(store.key, data, store.expire);
// do not process promise catch here beacause this process must not stop normal process
// in any case
}
// valid
deferred.resolve(data);
}
});
}
// has redis ?
if (redis) {
// normalize redisKey
var redisKey = _.merge(_.isString(conditions) ?
_.set([ this.modelName, conditions ].join('-'), conditions) : conditions || {}, filter || {});
// get key
redis.instance.get(redisKey).then(function (success) {
// success resolve
deferred.resolve(success);
}).catch(function (error) {
// normal stuff
defaultFind.call(this, conditions, filter, _.isNull(error) ? {
key : redisKey,
expire : redis.expire
} : error);
}.bind(this));
} else {
// normal process
defaultFind.call(this, conditions, filter);
}
// return deferred promise
return deferred.promise;
};
/**
* Find and Remove a specific model
*
* @param {String} id query rules to add in find
* @return {Promise} promise object to use for handling
*/
Crud.prototype.delete = function (id) {
// Create our deferred object, which we will use in our promise chain
var deferred = Q.defer();
// is valid type ?
if (_.isString(id) && !_.isEmpty(id)) {
// try to find
this.findByIdAndRemove(id, function (error, data) {
// has error ?
if (error) {
// reject
deferred.reject(error);
} else {
// valid
deferred.resolve(data);
}
});
} else {
// reject
deferred.reject([ 'Given id is not a string',
_.isString(id) && _.isEmpty(id) ? ' and is empty' : '' ].join(' '));
}
// return deferred promise
return deferred.promise;
};
/**
* Find a model and update it
*
* @param {Object|String} conditions query rules to add in find
* @param {String} update data to use for update
* @param {Boolean} multi set to true to process to un multi update action
* @return {Promise} promise object to use for handling
*/
Crud.prototype.update = function (conditions, update, multi) {
// is string ? so if for findByIdAndUpdate request. change method name
var method = _.isString(conditions) ? 'findByIdAndUpdate' : 'findOneAndUpdate';
// Create our deferred object, which we will use in our promise chain
var deferred = Q.defer();
// is multi request ??
if (_.isBoolean(multi) && multi) {
// process specific where
this.where().setOptions({ multi : true }).update(conditions, update, function (error, data) {
// has error ?
if (error) {
// reject
deferred.reject(error);
} else {
// valid
deferred.resolve(data);
}
});
} else {
// try to find
this[method](conditions, update, { new : true }, function (error, data) {
// has error ?
if (error) {
// reject
deferred.reject(error);
} else {
// valid
deferred.resolve(data);
}
});
}
// return deferred promise
return deferred.promise;
};
/**
* Insert new data in bdd for current model
*
* @param {Object} value value to use for create action
* @return {Promise} promise object to use for handling
*/
Crud.prototype.create = function (value) {
// Create our deferred object, which we will use in our promise chain
var deferred = Q.defer();
// create default instance model
var model = !_.isFunction(this.save) ? new this() : this;
// default status
var status = true;
var errors = [];
// has a validate function ?
if (_.isFunction(this.validate)) {
// so try to validate
status = this.validate(value);
// save error
errors = status.error;
// change value here if validate is was call
value = _.has(status, 'value') ? status.value : value;
// get status
status = _.isNull(status.error);
}
// is valid ?
if (status) {
// model is a valid instance ?
if (model instanceof this) {
// extend data before save
_.extend(model, value);
// try to find
model.save(function (error, data) {
// has error ?
if (error) {
// reject
deferred.reject(error);
} else {
// elastic is enable on schema ?
if (this.schema.elastic) {
// add this a listener to log indexes action
model.on('es-indexed', function (err) {
// log succes message
if (err) {
// reject with error message
deferred.reject([ '[ Crud.create ] - Indexes creation failed :', err ].join(' '));
} else {
// resolve default statement
deferred.resolve(data);
}
});
} else {
// valid
deferred.resolve(data);
}
}
}.bind(this));
} else {
// reject invalid instance model
deferred.reject('[ Crud.create ] - Cannot save. invalid instance model');
}
} else {
// reject schema validation error
deferred.reject([ '[ Crud.create ] - Cannot save new schema.',
errors ].join(' '));
}
// return deferred promise
return deferred.promise;
};
/**
* An utility method to use for search request to elastic search instances
*
* @param {Object} query query to use on elastic search request
* @param {Object} options Optional options, eg. : hydrate, from, size
* @return {Promise} promise object to use for handling
*/
Crud.prototype.esearch = function (query, options) {
// Create our deferred object, which we will use in our promise chain
var deferred = Q.defer();
// elastic is enabled ?
if (!_.isUndefined(this.search) && _.isFunction(this.search)) {
// try to find
this.search(query || {}, options || {}, function (error, data) {
// has error ?
if (error) {
// reject
deferred.reject(error);
} else {
// valid
deferred.resolve(data);
}
});
} else {
// reject with error message
deferred.reject('Elastic search is not enabled. Cannot process a search request');
}
// return deferred promise
return deferred.promise;
};
/**
* Add a crud method to statics givent schema
*
* @param {Object} schema default schema to use
* @param {Array} exclude array of method to exclude
* @param {Object} redisIncludes default redis include config retreive form model definition
* @param {Object} redis current redis instance to use on current crud method
* @return {Object|Boolean} modified schema with new requested method
*/
Crud.prototype.add = function (schema, exclude, redisIncludes, redis) {
// valid data ?
if ((!_.isObject(schema) && !(schema instanceof Schema)) || !_.isArray(exclude)) {
this.logger.warning('[ Crud.add ] - Schema or exclude item given is invalid');
// invalid statement
return false;
}
// default difference
var difference = [ 'add' ];
// elastic is disable ?
if (!schema.elastic) {
// add search method to diff to remove default crud method
difference.push('elasticsearch');
}
// keep only correct method
var existing = _.difference(Object.keys(Crud.prototype), difference);
// normalize data
exclude = _.isArray(exclude) ? exclude : [];
// try to add alias on exclude array
if (!_.isEmpty(exclude) && _.isArray(exclude)) {
// build excluded alias
var excludeAlias = _.intersection(Object.keys(this.alias), exclude);
// parse alias to add item
_.each(excludeAlias, function (ex) {
// push it
exclude.push(this.alias[ex]);
}.bind(this));
// flatten array to have unique level
exclude = _.flatten(exclude);
}
// keep only needed methods
var saved = _.difference(existing, exclude);
// parse all
_.each(saved, function (s) {
// is a valid func ?
if (_.isFunction(this[s])) {
// has redis config define ?
if (redisIncludes) {
// current method is include on redis config ?
if (_.includes(redisIncludes.value || [], s)) {
// assign method via static method and bind of redis on it
schema.static([ s, 'Redis' ].join(''), {
instance : redis,
expire : redisIncludes.expire || 0
});
}
}
// assign method via static method
schema.static(s, this[s]);
}
}.bind(this));
// default statement
return schema;
};
// Default export
module.exports = function (l) {
// is a valid logger ?
if (_.isUndefined(l) || _.isNull(l)) {
logger.warning('[ Crud.constructor ] - Invalid logger given. Use internal logger');
// assign
l = logger;
}
// default statement
return new (Crud)(l);
};
|
import React from 'react';
export default function Contact() {
// const [name, setName] = React.useState('');
// const [email, setEmail] = React.useState('');
// const [message, setMessage] = React.useState('');
function encode(data) {
return Object.keys(data).map((key) => encodeURIComponent(key) + '=' + encodeURIComponent(data[key])).join('&');
}
// function handleSubmit(e) {
// e.preventDefault();
// fetch('/', {
// method: 'POST',
// headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
// body: encode({ 'form-name': 'contact', name, email, message })
// }).then(() => alert('Message sent!')).catch((error) => alert(error));
// }
return (
<section id="contact" >
<div className="container px-5 py-10 mx-auto flex sm:flex-nowrap flex-wrap">
{/* <div className="lg:w-2/3 md:w-1/2 bg-gray-900 rounded-lg overflow-hidden sm:mr-10 p-10 flex items-end justify-start relative">
<iframe
width="100%"
height="100%"
title="map"
className="absolute inset-0"
frameBorder={0}
marginHeight={0}
marginWidth={0}
style={{ filter: "opacity(0.7)" }}
src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d2794.3040456467647!2d-122.62750258443985!3d45.54420887910194!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x5495a72aad4f4549%3A0xbed4dbb063837473!2s2933%20NE%2037th%20Ave%2C%20Portland%2C%20OR%2097212!5e0!3m2!1sen!2sus!4v1629916330564!5m2!1sen!2sus"
/> */}
{/* <div className="bg-gray-900 relative flex flex-wrap py-6 rounded shadow-md">
<div className="lg:w-1 px-6">
<h2 className="title-font font-semibold text-white tracking-widest text-xs">
ADDRESS
</h2>
<p className="mt-1">
2933 NE 37th Ave <br />
Portland, OR 97212
</p>
</div>
<div className="lg:w-7/12 px-6 mt-4 lg:mt-0">
<h2 className="title-font font-semibold text-white tracking-widest text-xs">
EMAIL
</h2>
<a className="text-indigo-400 leading-relaxed">
mrjacobdevries@gmail.com
</a>
<h2 className="title-font font-semibold text-white tracking-widest text-xs mt-4">
PHONE
</h2>
<p className="leading-relaxed">(541) 539-1828</p>
</div>
</div> */}
{/* </div> */}
<form
netlify
name="contact"
className="lg:w-8/10 md:w-8/10 flex flex-col md:ml-auto w-full md:py-8 mt-8 md:mt-0 text-center mb-20">
<h2 className="sm:text-4xl text-3xl font-medium title-font text-white mb-4">
Contact Me
</h2>
<p className="text-base leading-relaxed xl:w-2/4 lg:w-3/4 mx-auto">
I would love to talk with you about any opportunities or any of my projects displayed above. Please reach out however is most convenient for you. I look forward to talking with you. Thank you!
</p>
<br></br>
<div className="relative mb-4">
<label htmlFor="email" className="leading-9 text-sm text-white">
Email
</label>
<h1 className='leading-7 text-sm text-gray-400'>
mrjacobdevries@gmail.com
</h1>
{/* <input
type="text"
id="name"
name="name"
className="w-full bg-gray-800 rounded border border-gray-700 focus:border-indigo-500 focus:ring-2 focus:ring-indigo-900 text-base outline-none text-gray-100 py-1 px-3 leading-8 transition-colors duration-200 ease-in-out"
/> */}
</div>
<div className="relative mb-4">
<label htmlFor="phone" className="leading-9 text-sm text-white">
Phone Number
</label>
<h1 className='leading-7 text-sm text-gray-400'>
(541) 539-1828
</h1>
{/* <input
type="email"
id="email"
name="email"
className="w-full bg-gray-800 rounded border border-gray-700 focus:border-indigo-500 focus:ring-2 focus:ring-indigo-900 text-base outline-none text-gray-100 py-1 px-3 leading-8 transition-colors duration-200 ease-in-out"
/> */}
</div>
<div className="relative mb-4">
<label
htmlFor="linkedin"
className="leading-9 text-sm text-white">
LinkedIn
</label>
<h1 className='leading-7 text-sm text-gray-400'><a>
https://www.linkedin.com/in/jacobdv/
</a></h1>
{/* <textarea
id="message"
name="message"
className="w-full bg-gray-800 rounded border border-gray-700 focus:border-indigo-500 focus:ring-2 focus:ring-indigo-900 h-32 text-base outline-none text-gray-100 py-1 px-3 resize-none leading-6 transition-colors duration-200 ease-in-out"
/> */}
</div>
<div className="relative mb-4">
<label
htmlFor="github"
className="leading-9 text-sm text-white">
GitHub
</label>
<h1 className='leading-7 text-sm text-gray-400'><a>
https://github.com/jacobdv
</a></h1>
{/* <textarea
id="message"
name="message"
className="w-full bg-gray-800 rounded border border-gray-700 focus:border-indigo-500 focus:ring-2 focus:ring-indigo-900 h-32 text-base outline-none text-gray-100 py-1 px-3 resize-none leading-6 transition-colors duration-200 ease-in-out"
/> */}
</div>
{/* <button
onclick='handleSubmit(e);'
type="submit"
className="text-white bg-indigo-500 border-0 py-2 px-6 focus:outline-none hover:bg-indigo-600 rounded text-lg">
Submit
</button> */}
</form>
</div>
</section>
)
}
|
const router = require("express").Router();
const Wallet = require('./../models/Wallet.model')
const LaundryService = require('./../models/LaundryService.model')
const MenuPurchase = require('./../models/MenuPurchase.model')
const { checkLoggedUser } = require('./../middleware')
//wallet details
router.get('/', checkLoggedUser, (req, res) => {
const user_id = req.session.currentUser._id
const walletPromise = Wallet.findOne({ user: user_id })
const menuPromise = MenuPurchase.find({ user: user_id }).populate('dish')
const laundryPromise = LaundryService.find({ user: user_id })
Promise.all([menuPromise, walletPromise, laundryPromise])
.then(response => res.json(response))
.catch(err => res.json({ message: 'Ha ocurrido un error ', err }))
})
//wallet edit
router.put('/topUp', checkLoggedUser, (req, res) => {
const user_id = req.session.currentUser._id
const { balance } = req.body
Wallet
.findOne({ user: user_id })
.select('balance')
.then(response => {
let addTokens = Number(balance) + response.balance
return Wallet.findOneAndUpdate({ user: user_id }, { balance: addTokens }, { new: true })
})
.then(response => res.json(response))
.catch(err => res.json({ message: 'Ha ocurrido un error ', err }))
})
module.exports = router
|
const jwt = require('jsonwebtoken');
require('dotenv').config()
exports.checkToken = (req, res, next) => {
try {
const token = req.headers.authorization.split(' ')[1];
const decodedToken = jwt.verify(token, process.env.JWT);
const userId = decodedToken.userId;
const userRole = decodedToken.userRole;
if(userId){
req.userId = userId;
req.userRole = userRole;
next();
}else{
throw 'Not authenticated'
}
} catch {
res.status(401).json({
error: new Error('Invalid request!')
});
}
}
exports.checkSpecialAuthorization = (req, res, next) => {
try {
const token = req.headers.authorization.split(' ')[1];
const decodedToken = jwt.verify(token, process.env.JWT);
const userId = decodedToken.userId;
const userRole = decodedToken.userRole;
if ((req.body.userId && req.body.userId == userId) || userRole === 1 ) {
next();
} else {
throw 'Forbidden request'
}
} catch(error) {
res.status(403).json({ error: error.message });
}
}
|
angular.module('ngApp.home').controller('HomeTempController', function (AppSpinner, localStorage, OauthService, CurrentUserService, $scope, $location, $translate, $state, $log, LogonService, SessionService, toaster) {
$scope.submit = function (isValid, credentials) {
if (isValid) {
if (!CurrentUserService.profile.token) {
OauthService.oauthToken(credentials.UserName, credentials.Password).then(
function (response) {
// store token in local storage
if (response && response && response.data.access_token) {
CurrentUserService.setProfile($scope.credentials.UserName, response.data.access_token);
$scope.getuserTabs();
}
else {
toaster.pop({
type: 'warning',
title: 'User Access Error',
body: 'User does not exist. Please verify that the User Name and Password entered are correct.',
showCloseButton: true
});
}
}, function (error) {
toaster.pop({
type: 'error',
title: $scope.TitleFrayteValidation,
body: $scope.TextErrorWhileLogin,
showCloseButton: true
});
});
} else {
$scope.getuserTabs();
}
}
else {
toaster.pop({
type: 'warning',
title: $scope.TitleFrayteValidation,
body: $scope.TextPleaseEnterValidUserPass,
showCloseButton: true
});
}
};
function init() {
}
init();
});
|
import React from "react"
import {colors} from "../utils/styles"
import {dragElement} from "../utils/dragable"
const titleBarStyle = {
display: 'flex',
justifyContent: 'space-between',
position: 'relative',
height: 78,
minHeight: 78,
backgroundColor: colors.blue,
color: colors.white,
paddingLeft: 20
}
const flexMiddle = {
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
fontSize: 20,
width: '96%'
}
const backButtonStyle = {
display: 'flex',
cursor: 'pointer',
paddingLeft: 4,
paddingRight: 24
}
const buttonStyle = {
cursor: 'pointer',
marginRight: '20px'
}
const exitStyle = {
cursor: 'pointer',
fontSize: 15,
fontWeight: 'bold',
color: colors.white,
marginRight: '20px'
}
const headerLeft = {
alignItems: 'center',
marginTop: -2
}
const headerSubtitle = {
paddingLeft: 7,
marginTop: 3,
fontSize: '20px',
fontWeight: 600
}
const finePrint = {
marginTop: 1,
color: colors.white
}
export class TitleBar extends React.Component {
handleClose() {
if (this.props.closeFn)
this.props.closeFn()
}
componentDidMount(){
if (this.props.drag) {
let anchor = document.getElementsByClassName("titleBar")
if (anchor.length > 0){
// assume last title bar in the list is the "active" one
anchor = anchor[anchor.length-1]
}
let container = document.getElementsByClassName(this.props.drag)[0]
if (!container) {
return
}
if (container.style.marginLeft.substr(0,1) === "-"){
console.error("cannot use drag with negative margin")
return
}
dragElement(container, anchor)
}
}
getButtons() {
const {showCloseButton} = this.props
let showClose = false
showClose = showCloseButton !== undefined ? showCloseButton : showClose
return (
<span className='titlebar-buttons' style={{display: 'flex', alignItems: 'center', paddingLeft: '10px'}}>
{showClose && <span id="close" style={exitStyle} onClick={this.handleClose.bind(this)} data-tip={"Close"}>✕</span>}
</span>
)
}
render() {
let {title, subtitles, fineprint, rightDetails, embedded, showBackButton, delimiter} = this.props
let backButton=false
let delimiterToUse = delimiter ? delimiter : '|'
const getSubtitles = subtitles && subtitles.map((s, i) => (
<span key={i} style={headerSubtitle} className="h2">| {s}</span>))
const cc = '%%%%'
const getFineprints = fineprint && fineprint.filter( e => e != null).join(cc + ' '+delimiterToUse+' ' + cc).split(cc)
.map((s, i) => (<span key={i}>{s}</span>))
const getRightDetails = rightDetails && rightDetails.map((s, i) => (
<span key={i} style={{paddingRight: 6}}>{s}</span>))
if (!embedded){
backButton=true
}
backButton = showBackButton !== undefined ? showBackButton : backButton
return (
<div className="titleBar" style={titleBarStyle}>
<span style={flexMiddle}>
<div style={headerLeft}>
<div>
<span className="h1">{title}</span>
{getSubtitles}
</div>
{fineprint &&
<div style={finePrint} className="h4">
{getFineprints}
</div>}
</div>
<div className="h2" style={{display: 'flex', alignItems: 'center'}}>
{getRightDetails}
</div>
{this.getButtons()}
</span>
</div>
)
}
}
|
$(function() {
var h2 = $('#nav h2');
var navbox = $('#nav .navbox');
var nav = $('#nav');
var str=1;
/*用一个按钮控制要用if else判断,不能写两个if*/
h2.click(function(){
if(str==1){
nav.css({'height':'415px'});
navbox.show();
str=2;
}else if(str==2){
nav.css({'height':'58px'});
navbox.hide();
str=1;
}
})
})
|
//柯里化得演示
{
function checkAge(age) {
let min = 18;
return age > 18
}
}
// 这个函数有硬编码,可以柯里化,也可以转成普通纯函数
// 纯函数
{
function checkAge(age, min) {
return age > min
}
console.log(checkAge(20, 30)); // false
}
// 函数柯里化,其实就是闭包
{
function checkAge(min) {
return function (age) {
return age > min
}
}
const checkAge18 = checkAge(18)
console.log(checkAge18(20)); // true
console.log(checkAge18(20)); // true
console.log(checkAge18(10)); // false
}
// es6
{
// 箭头函数中 return 得函数用括号包一下
let checkAge = min => (age => age > min)
}
|
function generateWinningNumber() {
return Math.floor(Math.random() * 100) + 1;
}
function shuffle(arr) {
var length = arr.length;
var original;
var swap;
while(length) {
swap = Math.floor(Math.random() * length);
length--;
original = arr[length];
arr[length] = arr[swap];
arr[swap] = original;
}
return arr;
}
function Game() {
this.playersGuess = null;
this.pastGuesses = [];
this.winningNumber = generateWinningNumber();
}
Game.prototype.difference = function() {
return Math.abs(this.winningNumber - this.playersGuess);
}
Game.prototype.isLower = function() {
if (this.playersGuess < this.winningNumber) {
return true;
} else {
return false;
}
}
Game.prototype.playersGuessSubmission = function (guess) {
if (guess < 1 || guess > 100 || isNaN(guess)) {
throw "That is an invalid guess.";
} else {
this.playersGuess = guess;
}
return this.checkGuess();
}
Game.prototype.checkGuess = function() {
if (this.playersGuess === this.winningNumber) {
disableButtons();
return `You Win!`;
} else if (this.pastGuesses.indexOf(this.playersGuess) > -1) {
$("#play").text("Guess again");
return `You have already guessed that number.`;
} else if (this.pastGuesses.indexOf(this.playersGuess) < 0) {
this.pastGuesses.push(this.playersGuess);
$(".guesses li:nth-child(" + this.pastGuesses.length + ")").text(this.playersGuess);
if (this.pastGuesses.length === 5) {
disableButtons();
$("guess").text("Press the reset button to play again.");
return `You Lose.`;
} else if (this.difference() < 10) {
return `You're burning up!`
} else if (this.difference() < 25) {
return `You're lukewarm.`
} else if (this.difference() < 50) {
return `You're a bit chilly.`
} else if (this.difference() < 100) {
return `You're ice cold!`
}
}
}
function newGame() {
var result = new Game();
$("#play").text("Play the Guessing Game!");
$("#guess").text("Guess a number between 1 - 100!");
$("#player-input").val("");
$(".guess").text("-");
enableButtons();
return result;
}
function disableButtons() {
$("#submit-player-input").prop("disabled", true);
$("#hint").prop("disabled", true);
}
function enableButtons() {
$("#submit-player-input").prop("disabled", false);
$("#hint").prop("disabled", false);
}
Game.prototype.provideHint = function() {
var hint = [];
hint.push(this.winningNumber);
hint.push(generateWinningNumber());
hint.push(generateWinningNumber());
return shuffle(hint).join(", ");
}
function getGuess(currentGame) {
var guess = +($("#player-input").val());
$("#player-input").val("");
var result = currentGame.playersGuessSubmission(guess);
console.log(result);
$("#guess").text(result);
}
$(document).ready(function() {
var game = newGame();
$("#submit-player-input").on("click", function() {
getGuess(game);
});
$("#player-input").keypress(function(key) {
if(key.keyCode === 13) {
getGuess(game);
}
});
$("#reset").on("click", function() {
game = newGame();
});
$("#hint").on("click", function() {
$("#play").text("Here's a hint. One of these three is the number!");
$("#guess").text(game.provideHint());
});
});
|
// Written by Yijing Wu and Cliff Shaffer
$(document).ready(function(){
"use strict";
var av_name = "SATProofFS";
var av = new JSAV(av_name);
var Frames = PIFRAMES.init(av_name);
// Frame 1
av.umsg("Recall that to prove a problem NP-complete, we must prove that it is in NP, and that it is NP-hard. To prove that it is in NP, we usually provide a NP algorithm. This is typically easy: Check in polynomial time that a guessed answer is correct. To prove that the problem is NP-hard, our normal process is to find some known NP-hard problem and reduce it to our problem.<br/><br/>Thus, to start the process of being able to prove problems are NP-complete, we need to know that some problem <b>H</b> is NP-complete. After that, every problem proven NP-complete gives us another problem available to use in future proofs of other problems.");
av.displayInit();
// Frame 2
av.umsg(Frames.addQuestion("direction"));
av.step();
// Frame 3
av.umsg(Frames.addQuestion("hard"));
av.step();
// Frame 4
av.umsg("So a crucial first step to getting this whole theory off the ground is finding one problem that is NP-hard. The first proof that a problem is NP-hard (and because it is in NP, therefore NP-complete) was done by Stephen Cook. <br/><br/>For this feat, Cook won the first Turing award, which is the closest Computer Science equivalent to the Nobel Prize. The <q>grand-daddy</q> NP-complete problem that Cook used is called SATISFIABILITY (or SAT for short).");
av.step();
// Frame 5
av.umsg("A <b>Boolean expression</b> is comprised of Boolean variables combined using the operators AND (⋅), OR (+), and NOT (to negate Boolean variable $x$ we write $\\bar{x}$). A <b>literal</b> is a Boolean variable or its negation. A <b>clause</b> is one or more literals OR'ed together.");
av.step();
// Frame 6
av.umsg("Let <b>E</b> be a Boolean expression over variables <b>x<sub>1</sub>,x<sub>2</sub>,...,x<sub>n</sub></b>. Then we define Conjunctive Normal Form (CNF) to be a Boolean expression written as a series of clauses that are AND'ed together. For example, <br><br><br><b>E = (x<sub>5</sub> + x<sub>7</sub> + <i class = 'over'>x</i><sub>8</sub> + x<sub>10</sub>)⋅(<i class = 'over'>x</i><sub>2</sub> + x<sub>3</sub>)⋅(x<sub>1</sub> + <i class = 'over'>x</i><sub>3</sub> + x<sub>6</sub>)</b> <br><br><br>is in CNF, and has three clauses. Now we can define the problem SAT.");
av.step();
// Frame 7
av.umsg("<b>Problem</b><br><br>SATISFIABILITY (SAT)<br><br><b>Input: </b>A Boolean expression <b>E</b> over variables x<sub>1</sub>,x<sub>2</sub>,... in Conjunctive Normal Form. <br><br> <b>Output: </b>YES if there is an assignment to the variables that makes <b>E</b> true, NO otherwise.");
av.step();
// Frame 8
av.umsg(Frames.addQuestion("decision"));
av.step();
// Frame 9
av.umsg(Frames.addQuestion("TM"));
av.step();
// Frame 10
av.umsg("Cook used Turing machines in his proof because they are simple enough that he could develop this transformation of Turing machines to Boolean expressions, and rich enough to be able to compute any function that a regular computer can compute.<br/><br/>The significance of this transformation is that any decision problem that is performable by the Turing machine is transformable to SAT. Thus, SAT is NP-hard.");
av.step();
// Frame 11
av.umsg(Frames.addQuestion("q7"));
av.step();
// Frame 12
av.umsg("Here are several known NP-complete problems. They are linked to show the most typical reductions used to prove the problem NP-complete.");
var x=200;
var y=20;
var l=180;
var w=30;
var r= 10;
av.g.rect(x,y+0,l,w,r,{"fill":"Silver"});
av.label("<b>Circuit-SAT</b>",{top:y-10,left:x+l/4});
av.g.line(x+l/2,y+w,x+l/2,y+75);
y+=75;
av.g.rect(x,y+0,l,w,r,{"fill":"Silver"});
av.label("<b>SAT</b>",{top:y-10,left:x+2*l/5});
av.g.line(x+l/2,y+w,x+l/2,y+75);
y+=75;
av.g.rect(x,y+0,l,w,r,{"fill":"Silver"});
av.label("<b>3-SAT</b>",{top:y-10,left:x+4*l/11});
var x2=x-150;
y+=100;
var x1 = x+150;
av.g.rect(x2,y+0,l,w,r,{"fill":"Silver"});
av.label("<b>Clique</b>",{top:y-10,left:x2+l/3});
av.g.line(x+l/4,y-100+w,x2+l/2,y);
av.g.line(x+3*l/4,y-100+w,x1+l/2,y);
av.g.rect(x1,y+0,l,w,r,{"fill":"Silver"});
av.label("<b>Hamiltonian Cycle</b>",{top:y-10,left:x1+l/12});
av.g.line(x2+l/2,y+w,x2+l/2,y+75);
av.g.line(x1+l/2,y+w,x1+l/2,y+75);
y+=75;
av.g.rect(x2,y+0,l,w,r,{"fill":"Silver"});
av.label("<b>Independent Set</b>",{top:y-10,left:x2+l/8});
av.g.rect(x1,y+0,l,w,r,{"fill":"Silver"});
av.label("<b>Traveling Salesman</b>",{top:y-10,left:x1+l/16});
av.g.line(x2+l/2,y+w,x2+l/2,y+75);
y+=75;
av.g.rect(x2,y+0,l,w,r,{"fill":"Silver"});
av.label("<b>Vertex Cover</b>",{top:y-10,left:x2+l/5});
av.step();
// Frame 13
av.umsg("Congratulations! Frameset completed.");
av.recorded();
});
|
// source: chat.proto
/**
* @fileoverview
* @enhanceable
* @suppress {messageConventions} JS Compiler reports an error if a variable or
* field starts with 'MSG_' and isn't a translatable message.
* @public
*/
// GENERATED CODE -- DO NOT EDIT!
var jspb = require('google-protobuf');
var goog = jspb;
var global = Function('return this')();
var users_pb = require('./users_pb.js');
goog.object.extend(proto, users_pb);
var api_pb = require('./api_pb.js');
goog.object.extend(proto, api_pb);
goog.exportSymbol('proto.chat.Channel', null, global);
goog.exportSymbol('proto.chat.ChatStreamResponse', null, global);
goog.exportSymbol('proto.chat.ConnectRequest', null, global);
goog.exportSymbol('proto.chat.ConnectionsResponse', null, global);
goog.exportSymbol('proto.chat.ConnectionsStreamResponse', null, global);
goog.exportSymbol('proto.chat.Message', null, global);
/**
* Generated by JsPbCodeGenerator.
* @param {Array=} opt_data Optional initial data array, typically from a
* server response, or constructed directly in Javascript. The array is used
* in place and becomes part of the constructed object. It is not cloned.
* If no data is provided, the constructed object will be empty, but still
* valid.
* @extends {jspb.Message}
* @constructor
*/
proto.chat.ConnectRequest = function(opt_data) {
jspb.Message.initialize(this, opt_data, 0, -1, null, null);
};
goog.inherits(proto.chat.ConnectRequest, jspb.Message);
if (goog.DEBUG && !COMPILED) {
/**
* @public
* @override
*/
proto.chat.ConnectRequest.displayName = 'proto.chat.ConnectRequest';
}
/**
* Generated by JsPbCodeGenerator.
* @param {Array=} opt_data Optional initial data array, typically from a
* server response, or constructed directly in Javascript. The array is used
* in place and becomes part of the constructed object. It is not cloned.
* If no data is provided, the constructed object will be empty, but still
* valid.
* @extends {jspb.Message}
* @constructor
*/
proto.chat.ConnectionsStreamResponse = function(opt_data) {
jspb.Message.initialize(this, opt_data, 0, -1, proto.chat.ConnectionsStreamResponse.repeatedFields_, null);
};
goog.inherits(proto.chat.ConnectionsStreamResponse, jspb.Message);
if (goog.DEBUG && !COMPILED) {
/**
* @public
* @override
*/
proto.chat.ConnectionsStreamResponse.displayName = 'proto.chat.ConnectionsStreamResponse';
}
/**
* Generated by JsPbCodeGenerator.
* @param {Array=} opt_data Optional initial data array, typically from a
* server response, or constructed directly in Javascript. The array is used
* in place and becomes part of the constructed object. It is not cloned.
* If no data is provided, the constructed object will be empty, but still
* valid.
* @extends {jspb.Message}
* @constructor
*/
proto.chat.ConnectionsResponse = function(opt_data) {
jspb.Message.initialize(this, opt_data, 0, -1, proto.chat.ConnectionsResponse.repeatedFields_, null);
};
goog.inherits(proto.chat.ConnectionsResponse, jspb.Message);
if (goog.DEBUG && !COMPILED) {
/**
* @public
* @override
*/
proto.chat.ConnectionsResponse.displayName = 'proto.chat.ConnectionsResponse';
}
/**
* Generated by JsPbCodeGenerator.
* @param {Array=} opt_data Optional initial data array, typically from a
* server response, or constructed directly in Javascript. The array is used
* in place and becomes part of the constructed object. It is not cloned.
* If no data is provided, the constructed object will be empty, but still
* valid.
* @extends {jspb.Message}
* @constructor
*/
proto.chat.ChatStreamResponse = function(opt_data) {
jspb.Message.initialize(this, opt_data, 0, -1, proto.chat.ChatStreamResponse.repeatedFields_, null);
};
goog.inherits(proto.chat.ChatStreamResponse, jspb.Message);
if (goog.DEBUG && !COMPILED) {
/**
* @public
* @override
*/
proto.chat.ChatStreamResponse.displayName = 'proto.chat.ChatStreamResponse';
}
/**
* Generated by JsPbCodeGenerator.
* @param {Array=} opt_data Optional initial data array, typically from a
* server response, or constructed directly in Javascript. The array is used
* in place and becomes part of the constructed object. It is not cloned.
* If no data is provided, the constructed object will be empty, but still
* valid.
* @extends {jspb.Message}
* @constructor
*/
proto.chat.Channel = function(opt_data) {
jspb.Message.initialize(this, opt_data, 0, -1, null, null);
};
goog.inherits(proto.chat.Channel, jspb.Message);
if (goog.DEBUG && !COMPILED) {
/**
* @public
* @override
*/
proto.chat.Channel.displayName = 'proto.chat.Channel';
}
/**
* Generated by JsPbCodeGenerator.
* @param {Array=} opt_data Optional initial data array, typically from a
* server response, or constructed directly in Javascript. The array is used
* in place and becomes part of the constructed object. It is not cloned.
* If no data is provided, the constructed object will be empty, but still
* valid.
* @extends {jspb.Message}
* @constructor
*/
proto.chat.Message = function(opt_data) {
jspb.Message.initialize(this, opt_data, 0, -1, null, null);
};
goog.inherits(proto.chat.Message, jspb.Message);
if (goog.DEBUG && !COMPILED) {
/**
* @public
* @override
*/
proto.chat.Message.displayName = 'proto.chat.Message';
}
if (jspb.Message.GENERATE_TO_OBJECT) {
/**
* Creates an object representation of this proto.
* Field names that are reserved in JavaScript and will be renamed to pb_name.
* Optional fields that are not set will be set to undefined.
* To access a reserved field use, foo.pb_<name>, eg, foo.pb_default.
* For the list of reserved names please see:
* net/proto2/compiler/js/internal/generator.cc#kKeyword.
* @param {boolean=} opt_includeInstance Deprecated. whether to include the
* JSPB instance for transitional soy proto support:
* http://goto/soy-param-migration
* @return {!Object}
*/
proto.chat.ConnectRequest.prototype.toObject = function(opt_includeInstance) {
return proto.chat.ConnectRequest.toObject(opt_includeInstance, this);
};
/**
* Static version of the {@see toObject} method.
* @param {boolean|undefined} includeInstance Deprecated. Whether to include
* the JSPB instance for transitional soy proto support:
* http://goto/soy-param-migration
* @param {!proto.chat.ConnectRequest} msg The msg instance to transform.
* @return {!Object}
* @suppress {unusedLocalVariables} f is only used for nested messages
*/
proto.chat.ConnectRequest.toObject = function(includeInstance, msg) {
var f, obj = {
userId: jspb.Message.getFieldWithDefault(msg, 1, 0),
active: jspb.Message.getBooleanFieldWithDefault(msg, 2, false)
};
if (includeInstance) {
obj.$jspbMessageInstance = msg;
}
return obj;
};
}
/**
* Deserializes binary data (in protobuf wire format).
* @param {jspb.ByteSource} bytes The bytes to deserialize.
* @return {!proto.chat.ConnectRequest}
*/
proto.chat.ConnectRequest.deserializeBinary = function(bytes) {
var reader = new jspb.BinaryReader(bytes);
var msg = new proto.chat.ConnectRequest;
return proto.chat.ConnectRequest.deserializeBinaryFromReader(msg, reader);
};
/**
* Deserializes binary data (in protobuf wire format) from the
* given reader into the given message object.
* @param {!proto.chat.ConnectRequest} msg The message object to deserialize into.
* @param {!jspb.BinaryReader} reader The BinaryReader to use.
* @return {!proto.chat.ConnectRequest}
*/
proto.chat.ConnectRequest.deserializeBinaryFromReader = function(msg, reader) {
while (reader.nextField()) {
if (reader.isEndGroup()) {
break;
}
var field = reader.getFieldNumber();
switch (field) {
case 1:
var value = /** @type {number} */ (reader.readInt32());
msg.setUserId(value);
break;
case 2:
var value = /** @type {boolean} */ (reader.readBool());
msg.setActive(value);
break;
default:
reader.skipField();
break;
}
}
return msg;
};
/**
* Serializes the message to binary data (in protobuf wire format).
* @return {!Uint8Array}
*/
proto.chat.ConnectRequest.prototype.serializeBinary = function() {
var writer = new jspb.BinaryWriter();
proto.chat.ConnectRequest.serializeBinaryToWriter(this, writer);
return writer.getResultBuffer();
};
/**
* Serializes the given message to binary data (in protobuf wire
* format), writing to the given BinaryWriter.
* @param {!proto.chat.ConnectRequest} message
* @param {!jspb.BinaryWriter} writer
* @suppress {unusedLocalVariables} f is only used for nested messages
*/
proto.chat.ConnectRequest.serializeBinaryToWriter = function(message, writer) {
var f = undefined;
f = message.getUserId();
if (f !== 0) {
writer.writeInt32(
1,
f
);
}
f = message.getActive();
if (f) {
writer.writeBool(
2,
f
);
}
};
/**
* optional int32 user_id = 1;
* @return {number}
*/
proto.chat.ConnectRequest.prototype.getUserId = function() {
return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 1, 0));
};
/**
* @param {number} value
* @return {!proto.chat.ConnectRequest} returns this
*/
proto.chat.ConnectRequest.prototype.setUserId = function(value) {
return jspb.Message.setProto3IntField(this, 1, value);
};
/**
* optional bool active = 2;
* @return {boolean}
*/
proto.chat.ConnectRequest.prototype.getActive = function() {
return /** @type {boolean} */ (jspb.Message.getBooleanFieldWithDefault(this, 2, false));
};
/**
* @param {boolean} value
* @return {!proto.chat.ConnectRequest} returns this
*/
proto.chat.ConnectRequest.prototype.setActive = function(value) {
return jspb.Message.setProto3BooleanField(this, 2, value);
};
/**
* List of repeated fields within this message type.
* @private {!Array<number>}
* @const
*/
proto.chat.ConnectionsStreamResponse.repeatedFields_ = [1];
if (jspb.Message.GENERATE_TO_OBJECT) {
/**
* Creates an object representation of this proto.
* Field names that are reserved in JavaScript and will be renamed to pb_name.
* Optional fields that are not set will be set to undefined.
* To access a reserved field use, foo.pb_<name>, eg, foo.pb_default.
* For the list of reserved names please see:
* net/proto2/compiler/js/internal/generator.cc#kKeyword.
* @param {boolean=} opt_includeInstance Deprecated. whether to include the
* JSPB instance for transitional soy proto support:
* http://goto/soy-param-migration
* @return {!Object}
*/
proto.chat.ConnectionsStreamResponse.prototype.toObject = function(opt_includeInstance) {
return proto.chat.ConnectionsStreamResponse.toObject(opt_includeInstance, this);
};
/**
* Static version of the {@see toObject} method.
* @param {boolean|undefined} includeInstance Deprecated. Whether to include
* the JSPB instance for transitional soy proto support:
* http://goto/soy-param-migration
* @param {!proto.chat.ConnectionsStreamResponse} msg The msg instance to transform.
* @return {!Object}
* @suppress {unusedLocalVariables} f is only used for nested messages
*/
proto.chat.ConnectionsStreamResponse.toObject = function(includeInstance, msg) {
var f, obj = {
usersList: jspb.Message.toObjectList(msg.getUsersList(),
users_pb.User.toObject, includeInstance)
};
if (includeInstance) {
obj.$jspbMessageInstance = msg;
}
return obj;
};
}
/**
* Deserializes binary data (in protobuf wire format).
* @param {jspb.ByteSource} bytes The bytes to deserialize.
* @return {!proto.chat.ConnectionsStreamResponse}
*/
proto.chat.ConnectionsStreamResponse.deserializeBinary = function(bytes) {
var reader = new jspb.BinaryReader(bytes);
var msg = new proto.chat.ConnectionsStreamResponse;
return proto.chat.ConnectionsStreamResponse.deserializeBinaryFromReader(msg, reader);
};
/**
* Deserializes binary data (in protobuf wire format) from the
* given reader into the given message object.
* @param {!proto.chat.ConnectionsStreamResponse} msg The message object to deserialize into.
* @param {!jspb.BinaryReader} reader The BinaryReader to use.
* @return {!proto.chat.ConnectionsStreamResponse}
*/
proto.chat.ConnectionsStreamResponse.deserializeBinaryFromReader = function(msg, reader) {
while (reader.nextField()) {
if (reader.isEndGroup()) {
break;
}
var field = reader.getFieldNumber();
switch (field) {
case 1:
var value = new users_pb.User;
reader.readMessage(value,users_pb.User.deserializeBinaryFromReader);
msg.addUsers(value);
break;
default:
reader.skipField();
break;
}
}
return msg;
};
/**
* Serializes the message to binary data (in protobuf wire format).
* @return {!Uint8Array}
*/
proto.chat.ConnectionsStreamResponse.prototype.serializeBinary = function() {
var writer = new jspb.BinaryWriter();
proto.chat.ConnectionsStreamResponse.serializeBinaryToWriter(this, writer);
return writer.getResultBuffer();
};
/**
* Serializes the given message to binary data (in protobuf wire
* format), writing to the given BinaryWriter.
* @param {!proto.chat.ConnectionsStreamResponse} message
* @param {!jspb.BinaryWriter} writer
* @suppress {unusedLocalVariables} f is only used for nested messages
*/
proto.chat.ConnectionsStreamResponse.serializeBinaryToWriter = function(message, writer) {
var f = undefined;
f = message.getUsersList();
if (f.length > 0) {
writer.writeRepeatedMessage(
1,
f,
users_pb.User.serializeBinaryToWriter
);
}
};
/**
* repeated users.User users = 1;
* @return {!Array<!proto.users.User>}
*/
proto.chat.ConnectionsStreamResponse.prototype.getUsersList = function() {
return /** @type{!Array<!proto.users.User>} */ (
jspb.Message.getRepeatedWrapperField(this, users_pb.User, 1));
};
/**
* @param {!Array<!proto.users.User>} value
* @return {!proto.chat.ConnectionsStreamResponse} returns this
*/
proto.chat.ConnectionsStreamResponse.prototype.setUsersList = function(value) {
return jspb.Message.setRepeatedWrapperField(this, 1, value);
};
/**
* @param {!proto.users.User=} opt_value
* @param {number=} opt_index
* @return {!proto.users.User}
*/
proto.chat.ConnectionsStreamResponse.prototype.addUsers = function(opt_value, opt_index) {
return jspb.Message.addToRepeatedWrapperField(this, 1, opt_value, proto.users.User, opt_index);
};
/**
* Clears the list making it empty but non-null.
* @return {!proto.chat.ConnectionsStreamResponse} returns this
*/
proto.chat.ConnectionsStreamResponse.prototype.clearUsersList = function() {
return this.setUsersList([]);
};
/**
* List of repeated fields within this message type.
* @private {!Array<number>}
* @const
*/
proto.chat.ConnectionsResponse.repeatedFields_ = [1];
if (jspb.Message.GENERATE_TO_OBJECT) {
/**
* Creates an object representation of this proto.
* Field names that are reserved in JavaScript and will be renamed to pb_name.
* Optional fields that are not set will be set to undefined.
* To access a reserved field use, foo.pb_<name>, eg, foo.pb_default.
* For the list of reserved names please see:
* net/proto2/compiler/js/internal/generator.cc#kKeyword.
* @param {boolean=} opt_includeInstance Deprecated. whether to include the
* JSPB instance for transitional soy proto support:
* http://goto/soy-param-migration
* @return {!Object}
*/
proto.chat.ConnectionsResponse.prototype.toObject = function(opt_includeInstance) {
return proto.chat.ConnectionsResponse.toObject(opt_includeInstance, this);
};
/**
* Static version of the {@see toObject} method.
* @param {boolean|undefined} includeInstance Deprecated. Whether to include
* the JSPB instance for transitional soy proto support:
* http://goto/soy-param-migration
* @param {!proto.chat.ConnectionsResponse} msg The msg instance to transform.
* @return {!Object}
* @suppress {unusedLocalVariables} f is only used for nested messages
*/
proto.chat.ConnectionsResponse.toObject = function(includeInstance, msg) {
var f, obj = {
usersList: jspb.Message.toObjectList(msg.getUsersList(),
users_pb.User.toObject, includeInstance)
};
if (includeInstance) {
obj.$jspbMessageInstance = msg;
}
return obj;
};
}
/**
* Deserializes binary data (in protobuf wire format).
* @param {jspb.ByteSource} bytes The bytes to deserialize.
* @return {!proto.chat.ConnectionsResponse}
*/
proto.chat.ConnectionsResponse.deserializeBinary = function(bytes) {
var reader = new jspb.BinaryReader(bytes);
var msg = new proto.chat.ConnectionsResponse;
return proto.chat.ConnectionsResponse.deserializeBinaryFromReader(msg, reader);
};
/**
* Deserializes binary data (in protobuf wire format) from the
* given reader into the given message object.
* @param {!proto.chat.ConnectionsResponse} msg The message object to deserialize into.
* @param {!jspb.BinaryReader} reader The BinaryReader to use.
* @return {!proto.chat.ConnectionsResponse}
*/
proto.chat.ConnectionsResponse.deserializeBinaryFromReader = function(msg, reader) {
while (reader.nextField()) {
if (reader.isEndGroup()) {
break;
}
var field = reader.getFieldNumber();
switch (field) {
case 1:
var value = new users_pb.User;
reader.readMessage(value,users_pb.User.deserializeBinaryFromReader);
msg.addUsers(value);
break;
default:
reader.skipField();
break;
}
}
return msg;
};
/**
* Serializes the message to binary data (in protobuf wire format).
* @return {!Uint8Array}
*/
proto.chat.ConnectionsResponse.prototype.serializeBinary = function() {
var writer = new jspb.BinaryWriter();
proto.chat.ConnectionsResponse.serializeBinaryToWriter(this, writer);
return writer.getResultBuffer();
};
/**
* Serializes the given message to binary data (in protobuf wire
* format), writing to the given BinaryWriter.
* @param {!proto.chat.ConnectionsResponse} message
* @param {!jspb.BinaryWriter} writer
* @suppress {unusedLocalVariables} f is only used for nested messages
*/
proto.chat.ConnectionsResponse.serializeBinaryToWriter = function(message, writer) {
var f = undefined;
f = message.getUsersList();
if (f.length > 0) {
writer.writeRepeatedMessage(
1,
f,
users_pb.User.serializeBinaryToWriter
);
}
};
/**
* repeated users.User users = 1;
* @return {!Array<!proto.users.User>}
*/
proto.chat.ConnectionsResponse.prototype.getUsersList = function() {
return /** @type{!Array<!proto.users.User>} */ (
jspb.Message.getRepeatedWrapperField(this, users_pb.User, 1));
};
/**
* @param {!Array<!proto.users.User>} value
* @return {!proto.chat.ConnectionsResponse} returns this
*/
proto.chat.ConnectionsResponse.prototype.setUsersList = function(value) {
return jspb.Message.setRepeatedWrapperField(this, 1, value);
};
/**
* @param {!proto.users.User=} opt_value
* @param {number=} opt_index
* @return {!proto.users.User}
*/
proto.chat.ConnectionsResponse.prototype.addUsers = function(opt_value, opt_index) {
return jspb.Message.addToRepeatedWrapperField(this, 1, opt_value, proto.users.User, opt_index);
};
/**
* Clears the list making it empty but non-null.
* @return {!proto.chat.ConnectionsResponse} returns this
*/
proto.chat.ConnectionsResponse.prototype.clearUsersList = function() {
return this.setUsersList([]);
};
/**
* List of repeated fields within this message type.
* @private {!Array<number>}
* @const
*/
proto.chat.ChatStreamResponse.repeatedFields_ = [1];
if (jspb.Message.GENERATE_TO_OBJECT) {
/**
* Creates an object representation of this proto.
* Field names that are reserved in JavaScript and will be renamed to pb_name.
* Optional fields that are not set will be set to undefined.
* To access a reserved field use, foo.pb_<name>, eg, foo.pb_default.
* For the list of reserved names please see:
* net/proto2/compiler/js/internal/generator.cc#kKeyword.
* @param {boolean=} opt_includeInstance Deprecated. whether to include the
* JSPB instance for transitional soy proto support:
* http://goto/soy-param-migration
* @return {!Object}
*/
proto.chat.ChatStreamResponse.prototype.toObject = function(opt_includeInstance) {
return proto.chat.ChatStreamResponse.toObject(opt_includeInstance, this);
};
/**
* Static version of the {@see toObject} method.
* @param {boolean|undefined} includeInstance Deprecated. Whether to include
* the JSPB instance for transitional soy proto support:
* http://goto/soy-param-migration
* @param {!proto.chat.ChatStreamResponse} msg The msg instance to transform.
* @return {!Object}
* @suppress {unusedLocalVariables} f is only used for nested messages
*/
proto.chat.ChatStreamResponse.toObject = function(includeInstance, msg) {
var f, obj = {
messagesList: jspb.Message.toObjectList(msg.getMessagesList(),
proto.chat.Message.toObject, includeInstance)
};
if (includeInstance) {
obj.$jspbMessageInstance = msg;
}
return obj;
};
}
/**
* Deserializes binary data (in protobuf wire format).
* @param {jspb.ByteSource} bytes The bytes to deserialize.
* @return {!proto.chat.ChatStreamResponse}
*/
proto.chat.ChatStreamResponse.deserializeBinary = function(bytes) {
var reader = new jspb.BinaryReader(bytes);
var msg = new proto.chat.ChatStreamResponse;
return proto.chat.ChatStreamResponse.deserializeBinaryFromReader(msg, reader);
};
/**
* Deserializes binary data (in protobuf wire format) from the
* given reader into the given message object.
* @param {!proto.chat.ChatStreamResponse} msg The message object to deserialize into.
* @param {!jspb.BinaryReader} reader The BinaryReader to use.
* @return {!proto.chat.ChatStreamResponse}
*/
proto.chat.ChatStreamResponse.deserializeBinaryFromReader = function(msg, reader) {
while (reader.nextField()) {
if (reader.isEndGroup()) {
break;
}
var field = reader.getFieldNumber();
switch (field) {
case 1:
var value = new proto.chat.Message;
reader.readMessage(value,proto.chat.Message.deserializeBinaryFromReader);
msg.addMessages(value);
break;
default:
reader.skipField();
break;
}
}
return msg;
};
/**
* Serializes the message to binary data (in protobuf wire format).
* @return {!Uint8Array}
*/
proto.chat.ChatStreamResponse.prototype.serializeBinary = function() {
var writer = new jspb.BinaryWriter();
proto.chat.ChatStreamResponse.serializeBinaryToWriter(this, writer);
return writer.getResultBuffer();
};
/**
* Serializes the given message to binary data (in protobuf wire
* format), writing to the given BinaryWriter.
* @param {!proto.chat.ChatStreamResponse} message
* @param {!jspb.BinaryWriter} writer
* @suppress {unusedLocalVariables} f is only used for nested messages
*/
proto.chat.ChatStreamResponse.serializeBinaryToWriter = function(message, writer) {
var f = undefined;
f = message.getMessagesList();
if (f.length > 0) {
writer.writeRepeatedMessage(
1,
f,
proto.chat.Message.serializeBinaryToWriter
);
}
};
/**
* repeated Message messages = 1;
* @return {!Array<!proto.chat.Message>}
*/
proto.chat.ChatStreamResponse.prototype.getMessagesList = function() {
return /** @type{!Array<!proto.chat.Message>} */ (
jspb.Message.getRepeatedWrapperField(this, proto.chat.Message, 1));
};
/**
* @param {!Array<!proto.chat.Message>} value
* @return {!proto.chat.ChatStreamResponse} returns this
*/
proto.chat.ChatStreamResponse.prototype.setMessagesList = function(value) {
return jspb.Message.setRepeatedWrapperField(this, 1, value);
};
/**
* @param {!proto.chat.Message=} opt_value
* @param {number=} opt_index
* @return {!proto.chat.Message}
*/
proto.chat.ChatStreamResponse.prototype.addMessages = function(opt_value, opt_index) {
return jspb.Message.addToRepeatedWrapperField(this, 1, opt_value, proto.chat.Message, opt_index);
};
/**
* Clears the list making it empty but non-null.
* @return {!proto.chat.ChatStreamResponse} returns this
*/
proto.chat.ChatStreamResponse.prototype.clearMessagesList = function() {
return this.setMessagesList([]);
};
if (jspb.Message.GENERATE_TO_OBJECT) {
/**
* Creates an object representation of this proto.
* Field names that are reserved in JavaScript and will be renamed to pb_name.
* Optional fields that are not set will be set to undefined.
* To access a reserved field use, foo.pb_<name>, eg, foo.pb_default.
* For the list of reserved names please see:
* net/proto2/compiler/js/internal/generator.cc#kKeyword.
* @param {boolean=} opt_includeInstance Deprecated. whether to include the
* JSPB instance for transitional soy proto support:
* http://goto/soy-param-migration
* @return {!Object}
*/
proto.chat.Channel.prototype.toObject = function(opt_includeInstance) {
return proto.chat.Channel.toObject(opt_includeInstance, this);
};
/**
* Static version of the {@see toObject} method.
* @param {boolean|undefined} includeInstance Deprecated. Whether to include
* the JSPB instance for transitional soy proto support:
* http://goto/soy-param-migration
* @param {!proto.chat.Channel} msg The msg instance to transform.
* @return {!Object}
* @suppress {unusedLocalVariables} f is only used for nested messages
*/
proto.chat.Channel.toObject = function(includeInstance, msg) {
var f, obj = {
id: jspb.Message.getFieldWithDefault(msg, 1, 0),
name: jspb.Message.getFieldWithDefault(msg, 2, "")
};
if (includeInstance) {
obj.$jspbMessageInstance = msg;
}
return obj;
};
}
/**
* Deserializes binary data (in protobuf wire format).
* @param {jspb.ByteSource} bytes The bytes to deserialize.
* @return {!proto.chat.Channel}
*/
proto.chat.Channel.deserializeBinary = function(bytes) {
var reader = new jspb.BinaryReader(bytes);
var msg = new proto.chat.Channel;
return proto.chat.Channel.deserializeBinaryFromReader(msg, reader);
};
/**
* Deserializes binary data (in protobuf wire format) from the
* given reader into the given message object.
* @param {!proto.chat.Channel} msg The message object to deserialize into.
* @param {!jspb.BinaryReader} reader The BinaryReader to use.
* @return {!proto.chat.Channel}
*/
proto.chat.Channel.deserializeBinaryFromReader = function(msg, reader) {
while (reader.nextField()) {
if (reader.isEndGroup()) {
break;
}
var field = reader.getFieldNumber();
switch (field) {
case 1:
var value = /** @type {number} */ (reader.readInt32());
msg.setId(value);
break;
case 2:
var value = /** @type {string} */ (reader.readString());
msg.setName(value);
break;
default:
reader.skipField();
break;
}
}
return msg;
};
/**
* Serializes the message to binary data (in protobuf wire format).
* @return {!Uint8Array}
*/
proto.chat.Channel.prototype.serializeBinary = function() {
var writer = new jspb.BinaryWriter();
proto.chat.Channel.serializeBinaryToWriter(this, writer);
return writer.getResultBuffer();
};
/**
* Serializes the given message to binary data (in protobuf wire
* format), writing to the given BinaryWriter.
* @param {!proto.chat.Channel} message
* @param {!jspb.BinaryWriter} writer
* @suppress {unusedLocalVariables} f is only used for nested messages
*/
proto.chat.Channel.serializeBinaryToWriter = function(message, writer) {
var f = undefined;
f = message.getId();
if (f !== 0) {
writer.writeInt32(
1,
f
);
}
f = message.getName();
if (f.length > 0) {
writer.writeString(
2,
f
);
}
};
/**
* optional int32 id = 1;
* @return {number}
*/
proto.chat.Channel.prototype.getId = function() {
return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 1, 0));
};
/**
* @param {number} value
* @return {!proto.chat.Channel} returns this
*/
proto.chat.Channel.prototype.setId = function(value) {
return jspb.Message.setProto3IntField(this, 1, value);
};
/**
* optional string name = 2;
* @return {string}
*/
proto.chat.Channel.prototype.getName = function() {
return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, ""));
};
/**
* @param {string} value
* @return {!proto.chat.Channel} returns this
*/
proto.chat.Channel.prototype.setName = function(value) {
return jspb.Message.setProto3StringField(this, 2, value);
};
if (jspb.Message.GENERATE_TO_OBJECT) {
/**
* Creates an object representation of this proto.
* Field names that are reserved in JavaScript and will be renamed to pb_name.
* Optional fields that are not set will be set to undefined.
* To access a reserved field use, foo.pb_<name>, eg, foo.pb_default.
* For the list of reserved names please see:
* net/proto2/compiler/js/internal/generator.cc#kKeyword.
* @param {boolean=} opt_includeInstance Deprecated. whether to include the
* JSPB instance for transitional soy proto support:
* http://goto/soy-param-migration
* @return {!Object}
*/
proto.chat.Message.prototype.toObject = function(opt_includeInstance) {
return proto.chat.Message.toObject(opt_includeInstance, this);
};
/**
* Static version of the {@see toObject} method.
* @param {boolean|undefined} includeInstance Deprecated. Whether to include
* the JSPB instance for transitional soy proto support:
* http://goto/soy-param-migration
* @param {!proto.chat.Message} msg The msg instance to transform.
* @return {!Object}
* @suppress {unusedLocalVariables} f is only used for nested messages
*/
proto.chat.Message.toObject = function(includeInstance, msg) {
var f, obj = {
id: jspb.Message.getFieldWithDefault(msg, 1, 0),
content: jspb.Message.getFieldWithDefault(msg, 2, ""),
timestamp: jspb.Message.getFieldWithDefault(msg, 3, ""),
userId: jspb.Message.getFieldWithDefault(msg, 4, 0)
};
if (includeInstance) {
obj.$jspbMessageInstance = msg;
}
return obj;
};
}
/**
* Deserializes binary data (in protobuf wire format).
* @param {jspb.ByteSource} bytes The bytes to deserialize.
* @return {!proto.chat.Message}
*/
proto.chat.Message.deserializeBinary = function(bytes) {
var reader = new jspb.BinaryReader(bytes);
var msg = new proto.chat.Message;
return proto.chat.Message.deserializeBinaryFromReader(msg, reader);
};
/**
* Deserializes binary data (in protobuf wire format) from the
* given reader into the given message object.
* @param {!proto.chat.Message} msg The message object to deserialize into.
* @param {!jspb.BinaryReader} reader The BinaryReader to use.
* @return {!proto.chat.Message}
*/
proto.chat.Message.deserializeBinaryFromReader = function(msg, reader) {
while (reader.nextField()) {
if (reader.isEndGroup()) {
break;
}
var field = reader.getFieldNumber();
switch (field) {
case 1:
var value = /** @type {number} */ (reader.readInt32());
msg.setId(value);
break;
case 2:
var value = /** @type {string} */ (reader.readString());
msg.setContent(value);
break;
case 3:
var value = /** @type {string} */ (reader.readString());
msg.setTimestamp(value);
break;
case 4:
var value = /** @type {number} */ (reader.readInt32());
msg.setUserId(value);
break;
default:
reader.skipField();
break;
}
}
return msg;
};
/**
* Serializes the message to binary data (in protobuf wire format).
* @return {!Uint8Array}
*/
proto.chat.Message.prototype.serializeBinary = function() {
var writer = new jspb.BinaryWriter();
proto.chat.Message.serializeBinaryToWriter(this, writer);
return writer.getResultBuffer();
};
/**
* Serializes the given message to binary data (in protobuf wire
* format), writing to the given BinaryWriter.
* @param {!proto.chat.Message} message
* @param {!jspb.BinaryWriter} writer
* @suppress {unusedLocalVariables} f is only used for nested messages
*/
proto.chat.Message.serializeBinaryToWriter = function(message, writer) {
var f = undefined;
f = message.getId();
if (f !== 0) {
writer.writeInt32(
1,
f
);
}
f = message.getContent();
if (f.length > 0) {
writer.writeString(
2,
f
);
}
f = message.getTimestamp();
if (f.length > 0) {
writer.writeString(
3,
f
);
}
f = message.getUserId();
if (f !== 0) {
writer.writeInt32(
4,
f
);
}
};
/**
* optional int32 id = 1;
* @return {number}
*/
proto.chat.Message.prototype.getId = function() {
return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 1, 0));
};
/**
* @param {number} value
* @return {!proto.chat.Message} returns this
*/
proto.chat.Message.prototype.setId = function(value) {
return jspb.Message.setProto3IntField(this, 1, value);
};
/**
* optional string content = 2;
* @return {string}
*/
proto.chat.Message.prototype.getContent = function() {
return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, ""));
};
/**
* @param {string} value
* @return {!proto.chat.Message} returns this
*/
proto.chat.Message.prototype.setContent = function(value) {
return jspb.Message.setProto3StringField(this, 2, value);
};
/**
* optional string timestamp = 3;
* @return {string}
*/
proto.chat.Message.prototype.getTimestamp = function() {
return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 3, ""));
};
/**
* @param {string} value
* @return {!proto.chat.Message} returns this
*/
proto.chat.Message.prototype.setTimestamp = function(value) {
return jspb.Message.setProto3StringField(this, 3, value);
};
/**
* optional int32 user_id = 4;
* @return {number}
*/
proto.chat.Message.prototype.getUserId = function() {
return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 4, 0));
};
/**
* @param {number} value
* @return {!proto.chat.Message} returns this
*/
proto.chat.Message.prototype.setUserId = function(value) {
return jspb.Message.setProto3IntField(this, 4, value);
};
goog.object.extend(exports, proto.chat);
|
const parens = require('../../8_Recursion_and_Dinamic_Programming/9_Parens');
test('1 pair of parens is ()', () => {
expect(parens(1).join(',')).toBe('()');
})
test('2 pairs of parens are ()() (()) ', () => {
expect(parens(2).join(',')).toBe('(()),()()');
})
|
import React from 'react';
import { MapExplorer } from '@stratumn/react-mapexplorer';
import { shallow } from 'enzyme';
import { expect } from 'chai';
import sinon from 'sinon';
import * as statusTypes from '../constants/status';
import {
TestAgentBuilder,
TestProcessBuilder,
TestStateBuilder
} from '../test/builders/state';
import { MapPage, mapStateToProps } from './mapPage';
describe('<MapPage />', () => {
const validProps = {
agent: {
name: 'myAgent',
url: 'http://localhost:42'
},
process: {
name: 'proc42'
},
mapId: '42',
notifications: [],
selectSegment: () => {},
removeSegmentNotifications: () => {}
};
it('should render a MapExplorer component', () => {
const mapPage = shallow(<MapPage {...validProps} />);
expect(mapPage.find(MapExplorer)).to.have.length(1);
});
it('should display an error if agent url is missing', () => {
const mapPage = shallow(
<MapPage {...validProps} agent={{ name: 'missing-url' }} />
);
expect(mapPage.find(MapExplorer)).to.have.length(0);
expect(mapPage.find('.error')).to.have.length(1);
});
it('should extract agent, process and map information', () => {
const process = new TestProcessBuilder('p1').build();
const agent = new TestAgentBuilder()
.withUrl('http://localhost:4242')
.withProcess(process)
.build();
const state = new TestStateBuilder()
.withAgent('agent', agent)
.withAppendedSegment()
.withNotifications([
{ key: 'foo', mapId: '42' },
{ key: 'bar', mapId: '53' }
])
.build();
const routeProps = {
match: { params: { agent: 'agent', process: 'p1', id: '42' } }
};
const props = mapStateToProps(state, routeProps);
expect(props).to.deep.equal({
agent: {
name: 'agent',
url: 'http://localhost:4242'
},
process: {
name: 'p1'
},
mapId: '42',
notifications: [{ key: 'foo', mapId: '42' }]
});
});
it('should not fail props if agent or process is missing', () => {
const agent = new TestAgentBuilder().withStatus(statusTypes.FAILED).build();
const state = new TestStateBuilder().withAgent('a', agent).build();
const routeProps = {
match: { params: { agent: 'a', process: 'cannotFindMe', id: '42' } }
};
const props = mapStateToProps(state, routeProps);
expect(props).to.deep.equal({
agent: {
name: 'a'
},
process: {
name: 'cannotFindMe'
},
notifications: [],
mapId: '42'
});
});
it('should remove notification after render', () => {
const removeNotifySpy = sinon.spy();
const thisProps = {
...validProps,
removeSegmentNotifications: removeNotifySpy,
mapId: 'bar'
};
const mapPage = shallow(<MapPage {...thisProps} />);
mapPage.setProps({
...thisProps,
notifications: [{ key: 'foo', mapId: 'bar' }]
});
expect(removeNotifySpy.callCount).to.equal(1);
expect(removeNotifySpy.getCall(0).args[0]).to.deep.equal(['foo']);
});
});
|
import { Template } from 'meteor/templating';
import { ReactiveVar } from 'meteor/reactive-var';
import { HTTP } from 'meteor/http';
import { Meteor } from 'meteor/meteor';
import './register.html';
Template.register.onCreated(function helloOnCreated() {
// counter starts at 0
// alert('hello world');
this.counter = new ReactiveVar(0);
document.body.style.backgroundColor = '#fff';
});
Template.register.helpers({
destroy: function() {
this.dom.remove();
},
isUserLogin: function(){
var user = Meteor.user();
if (user) {
Router.go('/home');
}
}
});
// Template.foo.helpers({
// destroy: function() {
// this.dom.remove();
// }
// });
Template.register.events({
'submit form.close' : function(e, t) {
e.preventDefault();
t.__component__.dom.remove();
return false;
},
// 'click button'(event, instance) {
// // increment the counter when button is clicked
// instance.counter.set(instance.counter.get() + 1);
// },
'submit .regsiter': function(event){
event.preventDefault();
//alert('')
var username = event.target.username.value,
emailVar = event.target.email.value,
passwordVar = event.target.pwd.value,
fName = event.target.fname.value,
lName = event.target.lname.value,
number = event.target.number.value,
cPassword = event.target.cpassword.value,
cEmail = event.target.cEmail.value;
if(emailVar !== ""){
if(emailVar == cEmail){
if(fName !== ""){
if(lName !== ""){
if(username !== ""){
if(passwordVar.length > 5){
if(passwordVar == cPassword){
var response = Meteor.call('createUsers',username, emailVar, passwordVar, fName, lName, number, false, function(err,result) {
console.log(result);
if(typeof result.error !== 'undefined'){
//alert(result.error)
sweetAlert("Error!",result.error);
return;
}else{
Meteor.call('sendVerificationLink',function(err, res){
if(err)
{
console.log(err);
}
else
{
sweetAlert("Message!","Please check your email to verify your account.");
console.log('Verify done');
console.log(res);
Router.go('/');
}
});
//alert('Signup successfully.')
// Meteor.loginWithPassword(emailVar, passwordVar);
// sweetAlert("Success!","You have successfully Signup.");
}
});
}else{
sweetAlert("Warning!","Password not matching.");
}
}else{
sweetAlert("Warning!","Password not 6 chkt long.");
}
}else{
sweetAlert("Warning!","Please enter username first.");
}
}else{
sweetAlert("Warning!","Please enter last name first.");
}
}else{
sweetAlert("Warning!","Plesae enter first name.");
}
}else{
sweetAlert("Warning!","Confirm email address wrong.");
}
}else{
sweetAlert("Warning!","Please enter email address.");
}
},
'click .btn': function(event){
event.preventDefault();
//alert('');
Router.go('/userLogin');
}
// 'click .loginBtn': function(){
// console.log("You clicked an li element");
// }
});
Template.adminRegister.onCreated(function helloOnCreated() {
// counter starts at 0
// alert('hello world');
this.counter = new ReactiveVar(0);
document.body.style.backgroundColor = '#fff';
});
Template.adminRegister.helpers({
destroy: function() {
this.dom.remove();
}
});
// Template.foo.helpers({
// destroy: function() {
// this.dom.remove();
// }
// });
Template.adminRegister.events({
'submit form.close' : function(e, t) {
e.preventDefault();
t.__component__.dom.remove();
return false;
},
'submit .regsiter': function(event){
event.preventDefault();
//alert('')
var username = event.target.username.value,
emailVar = event.target.email.value,
passwordVar = event.target.pwd.value,
fName = event.target.fname.value,
lName = event.target.lname.value,
number = event.target.number.value,
cPassword = event.target.cpassword.value,
cEmail = event.target.cEmail.value;
if(emailVar !== ""){
if(emailVar == cEmail){
if(fName !== ""){
if(lName !== ""){
if(username !== ""){
if(passwordVar.length > 5){
if(passwordVar == cPassword){
var response = Meteor.call('createUsers',username, emailVar, passwordVar, fName, lName, number, true, function(err,result) {
console.log(result);
if(typeof result.error !== 'undefined'){
//alert(result.error)
sweetAlert("Error!",result.error);
return;
}else{
//alert('Signup successfully.')
Meteor.loginWithPassword(emailVar, passwordVar);
sweetAlert("Success!","You have successfully Signup.");
Router.go('/dashboard');
}
});
}else{
sweetAlert("Warning!","Password not matching.");
}
}else{
sweetAlert("Warning!","Password not 6 chkt long.");
}
}else{
sweetAlert("Warning!","Please enter username first.");
}
}else{
sweetAlert("Warning!","Please enter last name first.");
}
}else{
sweetAlert("Warning!","Plesae enter first name.");
}
}else{
sweetAlert("Warning!","Confirm email address wrong.");
}
}else{
sweetAlert("Warning!","Please enter email address.");
}
},
'click .btn': function(event){
event.preventDefault();
//alert('');
Router.go('/userLogin');
}
// 'click .loginBtn': function(){
// console.log("You clicked an li element");
// }
});
|
var idRegistro='';
var idEliminar='';
jQuery(document).ready(iniciar);
function iniciar()
{
console.log( 'cargo la pagina' );
window.tabla_BD = jQuery('#tabla-registros').DataTable(
{
"oLanguage": {
"sLengthMenu": "Mostrando _MENU_ filas",
"sSearch": "",
"sProcessing": "Procesando...",
"sLengthMenu": "Mostrar _MENU_ registros",
"sZeroRecords": "No se encontraron resultados",
"sEmptyTable": "Ningún dato disponible en esta tabla",
"sInfo": "Mostrando registros del _START_ al _END_ de un total de _TOTAL_ registros",
"sInfoEmpty": "Mostrando registros del 0 al 0 de un total de 0 registros",
"sInfoFiltered": "(filtrado de un total de _MAX_ registros)",
"sInfoPostFix": "",
"sSearch": "Buscar:",
"sUrl": "",
"sInfoThousands": ",",
"sLoadingRecords": "Cargando...",
"oPaginate": {
"sFirst": "Primero",
"sLast": "Último",
"sNext": "Siguiente",
"sPrevious": "Anterior"
}
}
});
BD_Cargar();
jQuery("#loader").fadeOut();
}
function BD_Cargar()
{//console.log('BD Cargada Exitosamente');
window.tabla_BD.clear();
//window.tabla_BD.draw();
jQuery.ajax(
{
url:'ws/travel/cuentas',
type:'GET',
dataType: 'json'
})
.done(function( data ){
Informacion=data.records;
jQuery.each(data.records, function (index, valor) {
Col1='<center>'+(index+1)+'</center>';
Col2=valor.nombre;
Col3='<td>'+
'<a data-placement="top" title="Añadir o eliminar rubros" class="btn-ver btn btn-info btn-xs toltip" href="#modal-ver" data-toggle="modal" data-idregistro="'+valor.id+'"><i class="glyphicon glyphicon-list"></i></a> '+
'<a data-placement="top" title="Editar cuenta y rubros" style="margin-left: 5px;" class="btn-editar btn btn-primary btn-xs toltip" href="#modal-editar" data-toggle="modal" data-idregistro="'+valor.id+'"><i class="fa fa-pencil"></i></a>'+
'<a data-placement="top" title="Eliminar cuenta con sus rubros" style="margin-left: 5px;" class="btn btn-danger btn-xs btn-eliminar toltip" href="#modal-eliminar" data-toggle="modal" data-idregistro="'+valor.id+'"><i class="fa fa-trash-o "></i></a>'+
'</td>';
window.tabla_BD.row.add([Col1,Col2,Col3]).draw();
//'<div class="tooltip-example"><button data-placement="top" data-toggle="tooltip" class="btn-editar fa btn-sm fa-pencil btn-warning tooltips" data-id="'+valor.id+'" data-index="'+index+'"></button> <button data-placement="top" data-toggle="tooltip" class="btn-eliminar fa btn-sm fa-minus btn-danger tooltips" data-id="'+valor.id+'" data-index="'+index+'"></button></div>';
});
})
.fail(function(error){console.log('error: ');console.log(error);})
}
///////////////////////////////////////////////////////ABC/////////////////////////////////////////////////////////////////
jQuery('#crear').on('click',function(){
jQuery('#form-crear')[0].reset();
jQuery('#descripcion_nuevo').remove();
jQuery('#detalles_nuevo').append("<div id='descripcion_nuevo'></div>");
});
var contar1=0;
jQuery('#masmen').on('click',function(e){
e.preventDefault();
jQuery('#descripcion_ver').append('<div class="div_ver_'+contar1+' divs_ver"><div class="form-group col-md-11"><input type="text" class="form-control descripcion_class_ver" required value="" /></div><div class="form-group col-md-1"><button class="btn btn-danger btn" data-id="'+contar1+'" id="elim-ver" ref="#modal-confirmar" data-toggle="modal">x</button></div></div><p></p>');
contar1=contar1+1;
});
jQuery('#descripcion_ver').on('click','#elim-ver',function(e){
e.preventDefault();
idEliminar=jQuery(e.target).data('id');
jQuery('#modal-confirmar').modal('show');
jQuery('#modal-ver').modal('hide');
});
jQuery('#btn-eliminar-confirmar').on('click', function( e ){
var coneli=0;
jQuery('.descripcion_class_ver').each(function()
{
coneli=coneli+1;
//console.log('contar: '+coneli);
});
if(coneli>1)
{
jQuery('.div_ver_'+idEliminar).remove();
}
else
{
toastr['warning']('Se necesita 1 descripcion como minimo', 'Espere');
}
jQuery('#modal-confirmar').modal('hide');
jQuery('#modal-ver').modal('show');
});
jQuery('#btn-eliminar-negar').on('click', function( e ){
e.preventDefault();
jQuery('#modal-confirmar').modal('hide');
jQuery('#modal-ver').modal('show');
});
jQuery('#detalles_nuevo').delegate('.elim_nuevo','click', eliminar_nuevo);
var contar=1;
jQuery('#mas').on('click',function(e){
e.preventDefault();
jQuery('#descripcion_nuevo').append('<div class="div_'+contar+'">'+
'<div class="form-group col-md-11">'+
'<input type="text" class="form-control descripcion_class" value="" />'+
'</div>'+
'<div class="form-group col-md-1">'+
'<button class="elim_nuevo btn btn-danger btn" data-id="'+contar+'">'+
'<i class="glyphicon glyphicon-remove"></i>'+
'</button>'+
'</div><p></p>'+
'</div>');
contar=contar+1;
});
function eliminar_nuevo( e )
{
e.preventDefault();
var eliminar = jQuery(this).data('id');
jQuery('.div_'+eliminar).remove();
}
jQuery('#btn-guardar').on('click',function(){
var error=0;
var descripciones = [];
jQuery('.descripcion_class_ver').each(function()
{
var contenido='';
var objeto={};
if(jQuery(this).text()) { contenido=jQuery(this).text(); }
else { contenido=jQuery(this).val(); }
if(contenido)
{
var objeto = {descripcion : contenido};
descripciones.push(objeto);
}
else
{
error=1;
}
});
var detalles = JSON.stringify(descripciones);
if(error==0)
{
// console.log( 'detalles='+detalles+'&eliminar=Si: '+ idRegistro);
jQuery.ajax(
{
url:'ws/travel/cuentas/'+idRegistro,
type:'PUT',
dataType: 'json',
data: 'detalles='+detalles+'&eliminar=si',
})
.done(function( data ){
//console.log(data);
if(data.result)
{
toastr['success'](data.message, 'Éxito');
jQuery('#modal-ver').modal('hide');
setTimeout( function(){ BD_Cargar(); }, 500);
}
else
{
//console.log(data);
toastr['warning'](data.message, 'Espere');
}
})
.fail(function(error){
console.log(error);
toastr['warning'](error.message, 'Espere');
})
}
else
{
toastr['warning']('no pueden haber descripciones vacias', 'Espere')
}
});
var contar2=1;
jQuery('#mas_editar').on('click',function(e)
{
e.preventDefault();
jQuery('#descripcion_editar').append('<div id="div_'+contar2+'"><input id="descripcioneditar_'+contar2+'"type="text" class="form-control descripcion_editar" required name="descripcion"><button class="btn btn-danger btn" data-id="'+contar2+'" id="elim-des-editar"><i class="glyphicon glyphicon-remove"></i></button></div><p></p>')
contar2=contar2+1;
});
jQuery('#descripcion_editar').on('click','#elim-des-editar',function(e)
{
//console.log("eliminar")
e.preventDefault();
var eliminar2= jQuery(e.target).data('id');
jQuery('#div_'+eliminar2).remove();
});
jQuery('#btn-crear').on('click',function(){
var error=0;
if(jQuery('#nombre').val())
{
var descripciones = [];
jQuery('.descripcion_class').each(function()
{
if(jQuery(this).val().length)
{
var objeto =
{
descripcion : jQuery(this).val()
}
descripciones.push(objeto);
}
else
{
//console.log('::'+jQuery(this).val());
error=1;
}
});
var detalle_desc = JSON.stringify(descripciones);
if(error==0)
{
//console.log(detalle_desc);
// console.log(jQuery('#nombre').val());
jQuery.ajax(
{
url: 'ws/travel/cuentas',
type: 'POST',
dataType: 'json',
data: 'detalles='+detalle_desc+'&nombre='+jQuery('#nombre').val(),
})
.done(function( data ){
//console.log(data);
if(data.result)
{
toastr['success'](data.message, 'Éxito');
jQuery('#modal-crear').modal('hide');
setTimeout( function(){ BD_Cargar(); }, 500);
jQuery('#descripcion').remove();
jQuery('#detalles').append("<div id='descripcion'></div>");
}
else
{
toastr['warning'](data.message, 'Espere');
}
})
.fail(function(error){
toastr['warning'](error.message, 'Espere');
})
jQuery('#form-crear').each (function(){
this.reset();
});
}
else
{
toastr['warning']('Una de las descripciones esta vacia', 'Espere');
}
}
else
{
toastr['warning']('El nombre esta vacio', 'Espere');
}
});
jQuery('#tabla-registros').on('click','a.btn-ver',function(e){
e.preventDefault();
idRegistro = jQuery(this).data('idregistro');
jQuery('.divs_ver').remove();
//console.log(idRegistro);
jQuery.ajax(
{
url:'ws/travel/cuentas/'+idRegistro,
type:'GET',
dataType: 'json'
})
.done(function( data ){
//console.log(data.records);
jQuery('#desc-nomb').text(data.records.nombre);
idRegistro=data.records.id;
// jQuery('#edit_descripcion').val(data.records.descripcion);
jQuery.ajax(
{
url:'ws/travel/cuentas/detalles/'+idRegistro,
type:'GET',
dataType: 'json'
})
.done(function( data ){
//console.log(data.records);
contar1=0;
jQuery.each(data.records, function (index,datos) {
jQuery('#descripcion_ver').append('<div class="div_ver_'+contar1+' divs_ver"><div class="form-group col-md-11"><label type="text" class="form-control descripcion_class_ver" required >'+datos.nombre+'</label></div><div class="form-group col-md-1"><button class="btn btn-danger btn" data-id="'+contar1+'" data-ide="'+datos.id+'" id="elim-ver">x</button></div></div><p></p>');
//console.log(datos.nombre);
contar1=contar1+1;
});
})
.fail(function(error){
toastr['warning'](error.message, 'Espere');
})
})
.fail(function(error){
toastr['warning'](error.message, 'Espere');
})
});
jQuery('#tabla-registros').on('click','a.btn-editar',function(e){
e.preventDefault();
idRegistro = jQuery(this).data('idregistro');
jQuery('.div_edit').remove();
//console.log(idRegistro);
jQuery.ajax(
{
url:'ws/travel/cuentas/'+idRegistro,
type:'GET',
dataType: 'json'
})
.done(function( data ){
//console.log(data.records);
jQuery('#edit_nombre').val(data.records.nombre);
// jQuery('#edit_descripcion').val(data.records.descripcion);
jQuery.ajax(
{
url:'ws/travel/cuentas/detalles/'+idRegistro,
type:'GET',
dataType: 'json'
})
.done(function( data ){
//console.log(data.records);
jQuery.each(data.records, function (index,datos) {
jQuery('#descripcion_edit').append('<div class="div_edit"><input type="text" class="form-control descripcion_class_edit" required value="'+datos.nombre+'"><br></div>');
//console.log(datos.nombre);
});
})
.fail(function(error){
toastr['warning'](error.message, 'Espere');
})
})
.fail(function(error){
toastr['warning'](error.message, 'Espere');
})
});
jQuery('#btn-actualizar').on('click',function(){
var descripciones = [];
var error=0;
jQuery('.descripcion_class_edit').each(function()
{
if(jQuery(this).val().length)
{
var objeto =
{
descripcion : jQuery(this).val()
}
descripciones.push(objeto);
}
else
{
//console.log('::'+jQuery(this).val());
error=1;
}
});
var detalle_desc = JSON.stringify(descripciones);
if(jQuery('#edit_nombre').val())
{
if(error==0)
{
jQuery.ajax(
{
url:'ws/travel/cuentas/'+idRegistro,
type:'PUT',
dataType: 'json',
data: 'nombre='+jQuery('#edit_nombre').val()+'&detalles='+detalle_desc,
})
.done(function( data ){
//console.log(data.records);
if(data.result)
{
toastr['success'](data.message, 'Éxito');
jQuery('#modal-editar').modal('hide');
setTimeout( function(){ BD_Cargar(); }, 500);
}
else
{
console.log(data);
toastr['warning'](data.message, 'Espere');
}
})
.fail(function(error){
console.log(error);
toastr['warning']("No se permite campo vacio", 'Espere');
})
}
else
{
toastr['warning']("Ninguna descripcion debe de ir vacia", 'Espere');
}
}
else
{
toastr['warning']("El nombre esta vacio", 'Espere');
}
});
jQuery('#tabla-registros').on('click', 'a.btn-eliminar', function( e )
{
e.preventDefault();
idEliminar = jQuery(this).data('idregistro');
});
jQuery('#btn-eliminar').on('click', function(){
//console.log(idEliminar);
jQuery.ajax(
{
url:'ws/travel/cuentas/'+idEliminar,
type:'DELETE',
dataType: 'json',
})
.done(function( data ){
toastr['success'](data.message, 'Éxito');
BD_Cargar();
jQuery('#modal-eliminar').modal('hide');
})
.fail(function(error){
toastr['warning'](error.message, 'Espere');
})
});
|
import axios from 'axios';
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import './index.css';
class Home extends Component{
constructor(props){
super(props)
this.state={
filmes:[]
}
this.loadFilmes = this.loadFilmes.bind(this);
}
componentDidMount(){
this.loadFilmes();
}
// Load filmes
async loadFilmes(){
let url = 'https://sujeitoprogramador.com/r-api/?api=filmes'
await axios.get(url).then(res=>{
const arrayData = res.data
this.setState({filmes:arrayData});
})
}
render(){
return(
<div>
<h5>Pagina Home</h5>
<div className="container">
{
this.state.filmes.map((filme)=>{
return(
<div key={filme.id} className="ListaFilmes">
<article >
<strong>{filme.nome}</strong>
<img src={filme.foto} alt={filme.nome }/>
<Link to={`/filme/${filme.id}`}>Acessar</Link>
</article>
</div>
)
})
}
</div>
</div>
)
}
}
export default Home;
|
import React, { Component } from 'react';
import css from './styles.scss';
import {string} from 'prop-types';
import tonneauImg from 'assets/img/tonneau.jpg';
import mountainImg from 'assets/img/moutain.jpg';
import coupleImg from 'assets/img/couple.jpg';
import ScrollAnim from 'rc-scroll-anim';
const Parallax = ScrollAnim.Parallax;
class Citaion extends Component {
static propTypes = {
title: string,
img: string
}
constructor(props) {
super();
let isMobile = false;
document.body.clientWidth < 764 && (isMobile = true);
this.state = {
isMobile: isMobile
}
}
componentDidMount() {
window.addEventListener('resize', () => {
this.setState({
isMobile: document.body.clientWidth < 764
});
});
}
get settingsStartAnimation () {
if (!this.state.isMobile) {
return (
{transform: 'translateY(100px)'} )
} else {
return (
{ transform: 'translateY(50px)', playScale: [-1, 1] }
)
}
}
/**
* Get Background Image of the instance of the card
* @return {string} [description]
*/
get img() {
let img;
this.props.img === 'mountain'
&& (img = mountainImg);
this.props.img === 'tonneau'
&& (img = tonneauImg);
this.props.img === 'couple'
&& (img = coupleImg);
return img;
}
/**
* Get all Classes of the block
* @return {string}
*/
get class () {
return (
this.props.withMargin
? [css.component, 'withMargin'].join(' ')
: css.component
)
}
render() {
return (
<div className={this.class} style={{backgroundImage: `url(${this.img})`}} >
<Parallax animation={{ y: 0}} key="1" style={this.settingsStartAnimation}>
<div className='' dangerouslySetInnerHTML={{__html: this.props.title}}/>
</Parallax>
</div>
);
}
}
export default Citaion
|
import React, { Component } from 'react'
import { formHeaderData } from '../../../../staticData'
import ImageHandler from './ImageHandler/index'
import { connect } from 'react-redux'
import { updateBirthday } from '../../../../store/Birthday/BirthdayActions'
import Input from '../../../Input/index'
import {
FormGroup,
Label
} from 'reactstrap'
import ToolTip from '../../../ToolTip'
class Form_header extends Component {
constructor() {
super()
this.state = {
invalidInput: false
}
}
/**
* An advanced simple action
*/
simpleAction = (event) => {
this.props.updateBday(event.target.value)
}
/**
* Rendering my input fields here, so all three are shows
* I am doing this using Object.keys and map
*/
renderInputs = () =>
this.props.birthdayEvent
? Object.keys(this.props.birthdayEvent).sort().map(this.renderInput)
: null
renderInput = key => (
<FormGroup key={key} >
<Label className="birthday-label">
{formHeaderData[key].text} {formHeaderData[key].tooltip ? <ToolTip text={formHeaderData[key].tooltip} /> : '' }
</Label>
<Input
id={formHeaderData[key].id}
className={formHeaderData[key].className}
keyVal={key}
val={this.props.birthdayEvent[key]}
callback={this.callback}
placeholder={formHeaderData[key].defaultValue}
/>
</FormGroup>
)
/**
* My callback function
*/
callback = (value, key) => {
this.props.updateBday({ [key]: value })
if (value.length > 2 && key === 'aTitle') {
let id = key
let element = document.getElementById(id)
element.classList.remove("invalid")
} else if (value.length <= 2 && key === 'aTitle') {
let id = key
let element = document.getElementById(id)
element.classList.add("invalid")
}
if (!/\s/.test(value) && value.length > 25 && key === 'aTitle') {
let id = key
let element = document.getElementById(id)
element.classList.add("invalid")
}
if (value.length > 1 && key === 'bName') {
let id = key
let element = document.getElementById(id)
element.classList.remove("invalid")
} else if (value.length < 2 && key === 'bName') {
let id = key
let element = document.getElementById(id)
element.classList.add("invalid")
}
if (/^\d*$/.test(value) && (value === "" || parseInt(value) <= 20) && key === 'cAge') {
let id = key
let element = document.getElementById(id)
element.classList.remove("invalid")
} else if (key === 'cAge') {
let id = 'cAge'
let element = document.getElementById(id)
element.classList.add("invalid")
}
}
render() {
return (
<div className="form-header-container">
<h1 className="form-headline headline-size">Skapa Kalas</h1>
<div className="box-container padding-fix" style={{ zIndex: '30' }}>
<div className="box text-left">
<div>
{this.renderInputs()}
</div>
</div>
<div className="box force-top">
<ImageHandler />
</div>
</div>
</div>
)
}
}
const mapStateToProps = state => {
return {
birthdayEvent: state.birthday.birthdayEvent
}
}
const mapDispatchToProps = dispatch => ({
updateBday: (data) => dispatch(updateBirthday(data))
})
export default connect(mapStateToProps, mapDispatchToProps)(Form_header)
|
import React from 'react'
import { shallow } from 'enzyme'
import Tr from '../src/tr'
const data = ['foo', 'bar']
test('is not instance of <Tr />', () => {
const wrapper = shallow(<Tr rowData={data} />)
const inst = wrapper.instance()
expect(inst).not.toBeInstanceOf(Tr)
})
test('constains two table cell <Td /> React component', () => {
const wrapper = shallow(<Tr rowData={data} />)
const children = wrapper.children()
expect(children.length).toBe(2)
data.map((_, idx) => {
expect(children.at(idx).text()).toBe('<Td />')
})
})
test('should pass the corresponding data to each table cell', () => {
const wrapper = shallow(<Tr rowData={data} />)
const children = wrapper.children()
data.map((item, idx) => {
expect(children.at(idx).props().cellData).toBe(item)
})
})
test('constains one table row header <Th /> React component', () => {
const wrapper = shallow(<Tr rowData={data} scope={'row'} />)
const children = wrapper.children()
expect(children.length).toBe(2)
expect(children.at(0).text()).toBe('<Th />')
expect(children.at(1).text()).toBe('<Td />')
})
|
/**
* Sample React Native App
* https://github.com/facebook/react-native
*
* @format
* @flow
*/
import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View, ScrollView} from 'react-native';
import ActionButton from 'react-native-action-button';
import Icon from 'react-native-vector-icons/Ionicons';
import { Toolbar } from 'react-native-material-ui';
const schoolName = 'Santa Teresa'
type Props = {};
export default class App extends Component<Props> {
render() {
return (
<View style={styles.container}>
<ScrollView stickyHeaderIndices={[0]} showsVerticalScrollIndicator={false} style={{ width: "100%" }} >
<Toolbar
style={styles.toolbar}
leftElement="menu"
centerElement=schoolName
/>
<Text style={styles.welcome}>Welcome to React Native!</Text>
<Text style={styles.welcome}>Welcome to React Native!</Text>
<Text style={styles.welcome}>Welcome to React Native!</Text>
<Text style={styles.welcome}>Welcome to React Native!</Text>
<Text style={styles.welcome}>Welcome to React Native!</Text>
<Text style={styles.welcome}>Welcome to React Native!</Text>
<Text style={styles.welcome}>Welcome to React Native!</Text>
<Text style={styles.welcome}>Welcome to React Native!</Text>
<Text style={styles.welcome}>Welcome to React Native!</Text>
<Text style={styles.welcome}>Welcome to React Native!</Text>
<Text style={styles.welcome}>Welcome to React Native!</Text>
<Text style={styles.welcome}>Welcome to React Native!</Text>
<Text style={styles.welcome}>Welcome to React Native!</Text>
</ScrollView>
<ActionButton buttonColor="rgba(231,76,60,1)">
<ActionButton.Item buttonColor='#9b59b6' title="New Task" onPress={() => console.log("notes tapped!")}>
<Icon name="md-create" style={styles.actionButtonIcon} />
</ActionButton.Item>
<ActionButton.Item buttonColor='#3498db' title="Notifications" onPress={() => {}}>
<Icon name="md-notifications-off" style={styles.actionButtonIcon} />
</ActionButton.Item>
<ActionButton.Item buttonColor='#1abc9c' title="All Tasks" onPress={() => {}}>
<Icon name="md-done-all" style={styles.actionButtonIcon} />
</ActionButton.Item>
</ActionButton>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
}
});
|
import React from "react";
import styled from "styled-components";
import classNames from "classnames";
import { ChevronRight } from "../../../common/icons";
import { Link } from "react-router-dom";
import moment from "moment";
import step1 from "../../../../assets/images/step-student.svg";
import step2 from "../../../../assets/images/book-lesson.svg";
import step3 from "../../../../assets/images/confirmed.svg";
const StyledSteps = styled.section`
margin-bottom: 5%;
.mystudent__inner__text {
display: flex;
align-items: center;
font-size: 16px;
padding: 25px 10px;
margin-bottom: 2%;
.text-color {
color: #6254e8;
font-weight: 500;
}
.arrow {
margin: 0 15px;
font-size: 12px;
svg {
font-size: 12px;
}
}
a {
color: #082487;
:hover {
color: #6254e8;
}
}
p {
margin: 0;
}
}
.inner {
display: flex;
max-width: 570px;
margin: 0 auto 40px;
position: relative;
justify-content: space-between;
}
.step__item {
color: #b4bff1;
position: relative;
&__icon {
background: #ced7ff;
border: 2px solid #b4bff1;
width: 40px;
height: 40px;
border-radius: 100%;
display: flex;
justify-content: center;
align-items: center;
cursor: pointer;
}
p {
position: absolute;
font-size: 14px;
width: 150px;
left: -55px;
font-weight: 500;
cursor: pointer;
padding-top: 6px;
}
.--date-time {
width: 200px;
left: -78px;
}
}
.active {
.step__item__icon {
background: #f6732f;
border: 2px solid #db5f1e;
}
p {
color: #f6732f;
}
}
.completed {
.step__item__icon {
background: #c3e4ca;
border: 2px solid #80ce82;
}
p {
color: #80ce82;
text-transform: capitalize;
}
}
.borderCompleted {
background: #80ce82;
}
span {
width: calc(50% - 75px);
height: 2px;
background: #b4bff1;
position: absolute;
top: 35px;
}
.border1 {
left: 55px;
}
.border2 {
right: 55px;
}
@media only screen and (max-width: 660px) {
.step__item p {
font-size: 12px;
width: 100px;
left: -35px;
}
.step__item:first-of-type p {
left: -20px;
}
}
@media only screen and (max-width: 420px) {
.step__item .--date-time {
width: 115px;
left: -40px;
}
}
`;
function Steps({
step,
handleStep1,
handleStep2,
handleStep3,
student,
storeBookLesson,
}) {
return (
<StyledSteps>
<div className="container">
<div className="mystudent__inner__text">
<Link to="/dashboard/teacher">Home</Link>
<p className="arrow">
<ChevronRight />
</p>
<p className="text-color">New lesson</p>
</div>
<div className="inner">
<div
className={classNames("step__item", {
active: step === 1,
completed: step > 1,
})}
onClick={handleStep1}
>
<div className="step__item__icon">
<img src={step1} alt="step1" />
</div>
<p>{student.label || "Select a student"}</p>
</div>
<span
className={classNames("border1", {
borderCompleted: step > 1,
})}
></span>
<div
className={classNames("step__item", {
active: step === 2,
completed: step > 2,
})}
onClick={handleStep2}
>
<div className="step__item__icon">
<img src={step2} alt="step2" />
</div>
<p className="--date-time">
{storeBookLesson.date && storeBookLesson.time
? moment(storeBookLesson.date).format("MMM Do YYYY") +
", " +
moment(storeBookLesson.time).format("h:mma")
: "Pick a date and time"}
</p>
</div>
<span
className={classNames("border2", {
borderCompleted: step > 2,
})}
></span>
<div
className={classNames("step__item", {
active: step === 3,
})}
onClick={handleStep3}
>
<div className="step__item__icon">
<img src={step3} alt="step3" />
</div>
<p>Confirm</p>
</div>
</div>
</div>
</StyledSteps>
);
}
export default Steps;
|
import React from 'react';
import Grid from "@material-ui/core/Grid";
import LocationOnIcon from '@material-ui/icons/LocationOn';
import MailOutlineIcon from '@material-ui/icons/MailOutline';
import PhoneIcon from '@material-ui/icons/Phone';
import './styles/footer.scss';
export const Footer = props => {
return (
<Grid container spacing={0}>
<footer className='footer black-background'>
<div className='contact'>
<span className='contact-item'>
<LocationOnIcon />
384 Hoàng Diệu, Phường 6, Quận 4, Hồ Chí Minh
</span>
<span className='contact-item'>
|
<PhoneIcon />
028 3826 8160
</span>
<span className='contact-item'>
|
<MailOutlineIcon />
phuong@fossil.com
</span>
</div>
<div className='name-company'>
<span>
© Công Ty TNHH Fossil Việt Nam
</span>
</div>
</footer>
</Grid>
)
}
|
/********************************************/
/* GenerateFreqLoss.js */
/* */
/* Holds the generation functions */
/* for hearing loss configuration */
/* (low-/high-frequency). */
/* */
/* @author: Kyra Taylor */
/* @date: 05/17/2021 */
/********************************************/
/*************************************/
/* IMPORTS */
/*************************************/
const { NORMAL_MIN, NORMAL_MAX } = require('../HearingDegrees');
const { generateCont: GC } = require('./GenerateContainer');
const { generateOneEar } = require('./GenerateOneEar');
/**************************************/
/* CONFIG GENERATION FUNCTIONS */
/**************************************/
/**
* @returns {Object}
*/
function getBC() {
if (GC.type === 'Conductive') {
return generateOneEar(NORMAL_MIN, NORMAL_MAX);
}
return generateOneEar(GC.getNextDb(), GC.getNextDb(), GC.freq);
}
/**
* Generates Unilateral, Low-Frequency,
* or High-Frequency hearing loss.
*
* @returns {Object}
*/
function generateFreqLoss() {
return {
'AC': generateOneEar(GC.getNextDb(), GC.getNextDb(), GC.freq),
'BC': getBC()
};
}
/********************************************/
module.exports = { generateFreqLoss };
|
import React from "react";
import "../styles/output.css";
import { START, RULES, ACTIONLIST } from '../constants';
const Menu = (props) => {
const { setDisplayContent, gameStatus, handleStopGame } = props;
console.log("MENU:", props)
return (
<div className="bg-gray-700 p-3 rounded-lg w-full grid grid-cols-3 gap-2">
hi
{!gameStatus && (<div className="col-span-1 sm:col-span-full">
<button className=" p-4 w-full bg-purple-600 rounded-lg font-bold text-white md:mb-4 hover:bg-purple-700 flex justify-center items-center" onClick={() => setDisplayContent(ACTIONLIST)}>
Actions
</button>
</div>)}
{!gameStatus && (<div className="col-span-1 sm:col-span-full">
<button className="p-4 w-full bg-purple-600 rounded-lg font-bold text-white md:mb-4 hover:bg-purple-700" onClick={() => setDisplayContent(RULES)}>
Rules
</button>
</div>)}
{!gameStatus && (<div className="col-span-1 sm:col-span-full">
<button className="p-4 w-full bg-green-400 rounded-lg font-bold text-white hover:bg-green-600" onClick={() => setDisplayContent(START)}>
Game
</button>
</div>)}
{gameStatus && (<div className="col-span-3 sm:col-span-full">
<button className="p-4 w-full bg-red-600 rounded-lg font-bold text-white hover:bg-red-700" onClick={handleStopGame}>
Stop Game
</button>
</div>)}
</div>
);
}
export default Menu;
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var ValidationRule = (function () {
function ValidationRule(rule, htmlInputElement) {
this.rule = rule;
this.htmlInputElement = htmlInputElement;
}
ValidationRule.prototype.execute = function (appendResponseCallback) {
this.rule.validate.call(this.htmlInputElement, appendResponseCallback);
return this;
};
return ValidationRule;
}());
exports.ValidationRule = ValidationRule;
|
$(function() {
var recipients = [];
function removeRecipient() {
var $li = $(this).parent();
var id = $li.data('id');
recipients = _.filter(recipients, function(v) {
// Type-insensitive check
return v != id;
});
$('#recipients').val(recipients.join('|'));
$li.remove();
return false;
}
$('#group_selector').change(function() {
var data = $(this).find('option:selected').data();
if ((data.id === -1) || (_.indexOf(recipients, data.id) != -1)) {
return;
}
recipients.push(data.id);
$(this).prop('selectedIndex', 0);
$('#recipients').val(recipients.join('|'));
$('<li />')
.text(data.name)
.data('id', data.id)
.addClass('mtop-5')
.append($('<button>')
.addClass('close')
.attr('aria-label', 'Close')
.html('<span aria-hidden="true">x</span>')
.click(removeRecipient)
)
.appendTo($('#recipient-list'));
});
$('#recipient-list button').click(removeRecipient);
var val = $('#recipients').val();
if (val && val.length) {
recipients = val.split('|');
}
var receiver = [];
$('#receiver-list button').click(removeRecipient);
var val = $('#receiver').val();
if (val && val.length) {
receiver = val.split('|');
}
$('#user_selector').change(function() {
var data = $(this).find('option:selected').data();
if ((data.id === -1) || (_.indexOf(receiver, data.id) != -1)) {
return;
}
receiver.push(data.id);
$(this).prop('selectedIndex', 0);
$('#receiver').val(receiver.join('|'));
$('<li />')
.text(data.name+' added as receiver')
.data('id', data.id)
.addClass('mtop-5')
.append($('<button>')
.addClass('close')
.attr('aria-label', 'Close')
.html('<span aria-hidden="true">x</span>')
.click(removeRecipient)
)
.appendTo($('#receiver-list'));
});
});
|
import hotels01 from '../assets/images/hotels-01.png';
import hotels02 from '../assets/images/hotels-02.png';
import hotels03 from '../assets/images/hotels-03.png';
import hotels04 from '../assets/images/hotels-04.png';
import hotels05 from '../assets/images/hotels-05.png';
import hotels06 from '../assets/images/hotels-06.png';
import hotelss01 from '../assets/images/hotels-01.jpg';
import hotelss02 from '../assets/images/hotels-02.jpg';
import hotelss03 from '../assets/images/hotels-03.jpg';
import hotelss04 from '../assets/images/hotels-04.jpg';
import hotelss05 from '../assets/images/hotels-05.jpg';
import hotelss06 from '../assets/images/hotels-06.jpg';
import banner from '../assets/images/banner-02.jpg';
export class experienceNearby extends HTMLElement {
constructor() {
super();
this.template();
this.hotelsData = this.querySelector(".hotels");
this.experiencesData = this.querySelector(".experiences");
}
set nearByHotels(data) {
this._experiences = data;
if (data) {
this.hotelsData.innerHTML = data.map(nearby => `
<div class="list-hotels">
<div class="box-hotels">
<div class="detail-hotels">
<div class="ways">
1.5 km away
</div>
<div class="img-hotels" style="background-image: url('${nearby.thumbnailUrl}')"></div>
<div class="name-hotels">
<button class="btn-book">
Book Now
</button>
<p class="name">${nearby.title}</p>
<p class="lating">
<svg xmlns="http://www.w3.org/2000/svg" width="15" height="12.975" viewBox="0 0 15 12.975">
<path id="Path_374" data-name="Path 374" d="M507.975,287.94c.338-.342.647-.668.97-.98a3.866,3.866,0,1,1,5.4,5.528q-2.745,2.752-5.5,5.5c-.27.271-.539.543-.82.826-.062-.057-.115-.1-.165-.153-1.742-1.742-3.49-3.479-5.222-5.231a13.311,13.311,0,0,1-1.376-1.549,3.77,3.77,0,0,1,2.2-5.916,3.73,3.73,0,0,1,3.513.975C507.327,287.251,507.638,287.6,507.975,287.94Z" transform="translate(-500.538 -285.837)" fill="#bebebe"/>
</svg>
210
</p>
</div>
</div>
</div>
</div>
`).join('');
}
}
set nearByExperiences(data) {
this._nearby = data;
if (data) {
this.experiencesData.innerHTML = data.map(nearby => `
<div class="list-hotels">
<div class="box-hotels">
<div class="detail-hotels">
<div class="ways">
1.5 km away
</div>
<div class="img-hotels" style="background-image: url('${nearby.thumbnailUrl}')"></div>
<div class="name-hotels">
<button class="btn-book">
Book Now
</button>
<p class="name">${nearby.title}</p>
<p class="lating">
<svg xmlns="http://www.w3.org/2000/svg" width="15" height="12.975" viewBox="0 0 15 12.975">
<path id="Path_374" data-name="Path 374" d="M507.975,287.94c.338-.342.647-.668.97-.98a3.866,3.866,0,1,1,5.4,5.528q-2.745,2.752-5.5,5.5c-.27.271-.539.543-.82.826-.062-.057-.115-.1-.165-.153-1.742-1.742-3.49-3.479-5.222-5.231a13.311,13.311,0,0,1-1.376-1.549,3.77,3.77,0,0,1,2.2-5.916,3.73,3.73,0,0,1,3.513.975C507.327,287.251,507.638,287.6,507.975,287.94Z" transform="translate(-500.538 -285.837)" fill="#bebebe"/>
</svg>
210
</p>
</div>
</div>
</div>
</div>
`).join('');
}
}
template() {
this.innerHTML = `
<div class="exp-nearby">
<div class="container">
<p class="title">
<svg xmlns="http://www.w3.org/2000/svg" width="66.116" height="33.637" viewBox="0 0 66.116 33.637">
<g id="Group_25" data-name="Group 25" transform="translate(-441.935 -225.506)">
<path id="Path_12" data-name="Path 12" d="M451.637,228.294a9.7,9.7,0,1,0,9.7,9.7A9.713,9.713,0,0,0,451.637,228.294Zm0,17.8A8.094,8.094,0,1,1,459.73,238,8.1,8.1,0,0,1,451.637,246.089Z" transform="translate(0 1.355)" fill="#89c966"/>
<path id="Path_13" data-name="Path 13" d="M450.269,246.69a.252.252,0,0,1-.447,0l-2.363-4.554a6.606,6.606,0,0,1-2.247-.838l4.357,8.394a.536.536,0,0,0,.952,0l4.357-8.394a6.623,6.623,0,0,1-2.247.838Z" transform="translate(1.592 7.674)" fill="#89c966"/>
<path id="Path_14" data-name="Path 14" d="M483.074,228.294a9.7,9.7,0,1,0,9.7,9.7A9.713,9.713,0,0,0,483.074,228.294Zm0,17.8A8.094,8.094,0,1,1,491.167,238,8.1,8.1,0,0,1,483.074,246.089Z" transform="translate(15.276 1.355)" fill="#89c966"/>
<path id="Path_15" data-name="Path 15" d="M481.706,246.69a.252.252,0,0,1-.447,0l-2.363-4.554a6.606,6.606,0,0,1-2.247-.838l4.357,8.394a.536.536,0,0,0,.952,0l4.357-8.394a6.623,6.623,0,0,1-2.247.838Z" transform="translate(16.868 7.674)" fill="#89c966"/>
<path id="Path_16" data-name="Path 16" d="M467.994,225.506a11.652,11.652,0,1,0,11.651,11.653A11.666,11.666,0,0,0,467.994,225.506Zm0,21.373a9.722,9.722,0,1,1,9.721-9.721A9.733,9.733,0,0,1,467.994,246.879Z" transform="translate(7)" fill="#89c966"/>
<path id="Path_17" data-name="Path 17" d="M466.35,247.6a.3.3,0,0,1-.538,0l-2.838-5.468a7.958,7.958,0,0,1-2.7-1.007l5.232,10.082a.644.644,0,0,0,1.144,0l5.232-10.082a7.976,7.976,0,0,1-2.7,1.007Z" transform="translate(8.913 7.589)" fill="#89c966"/>
<path id="Path_18" data-name="Path 18" d="M461.375,240.561h2.945v-3.244h2.453v3.244h2.945V229.69h-8.343Zm4.513-9.47h2.9v.886h-2.9Zm0,1.834h2.9v.886h-2.9Zm0,1.834h2.9v.886h-2.9Zm-3.584-3.667h2.9v.886h-2.9Zm0,1.834h2.9v.886h-2.9Zm0,1.834h2.9v.886h-2.9Z" transform="translate(9.446 2.033)" fill="#89c966"/>
<path id="Path_19" data-name="Path 19" d="M446.035,241.065h2.548v-2.807h2.122v2.807h2.548v-9.407h-7.219Zm3.9-8.195h2.513v.767h-2.513Zm0,1.587h2.513v.767h-2.513Zm0,1.587h2.513v.767h-2.513Zm-3.1-3.174h2.513v.767h-2.513Zm0,1.587h2.513v.767h-2.513Zm0,1.587h2.513v.767h-2.513Z" transform="translate(1.992 2.989)" fill="#89c966"/>
<path id="Path_20" data-name="Path 20" d="M477.472,241.065h2.548v-2.807h2.122v2.807h2.548v-9.407h-7.219Zm3.9-8.195h2.513v.767h-2.513Zm0,1.587h2.513v.767h-2.513Zm0,1.587h2.513v.767h-2.513Zm-3.1-3.174h2.513v.767h-2.513Zm0,1.587h2.513v.767h-2.513Zm0,1.587h2.513v.767h-2.513Z" transform="translate(17.268 2.989)" fill="#89c966"/>
</g>
</svg>
Nearby Hotels
</p>
<div class="nearby-hotels">
<div class="row-hotels hotels">
</div>
</div>
<exp-banner banner="${banner}" hide="hide"></exp-banner>
<p class="title">
<svg xmlns="http://www.w3.org/2000/svg" width="66.116" height="33.637" viewBox="0 0 66.116 33.637">
<g id="Group_25" data-name="Group 25" transform="translate(-441.935 -225.506)">
<path id="Path_12" data-name="Path 12" d="M451.637,228.294a9.7,9.7,0,1,0,9.7,9.7A9.713,9.713,0,0,0,451.637,228.294Zm0,17.8A8.094,8.094,0,1,1,459.73,238,8.1,8.1,0,0,1,451.637,246.089Z" transform="translate(0 1.355)" fill="#89c966"/>
<path id="Path_13" data-name="Path 13" d="M450.269,246.69a.252.252,0,0,1-.447,0l-2.363-4.554a6.606,6.606,0,0,1-2.247-.838l4.357,8.394a.536.536,0,0,0,.952,0l4.357-8.394a6.623,6.623,0,0,1-2.247.838Z" transform="translate(1.592 7.674)" fill="#89c966"/>
<path id="Path_14" data-name="Path 14" d="M483.074,228.294a9.7,9.7,0,1,0,9.7,9.7A9.713,9.713,0,0,0,483.074,228.294Zm0,17.8A8.094,8.094,0,1,1,491.167,238,8.1,8.1,0,0,1,483.074,246.089Z" transform="translate(15.276 1.355)" fill="#89c966"/>
<path id="Path_15" data-name="Path 15" d="M481.706,246.69a.252.252,0,0,1-.447,0l-2.363-4.554a6.606,6.606,0,0,1-2.247-.838l4.357,8.394a.536.536,0,0,0,.952,0l4.357-8.394a6.623,6.623,0,0,1-2.247.838Z" transform="translate(16.868 7.674)" fill="#89c966"/>
<path id="Path_16" data-name="Path 16" d="M467.994,225.506a11.652,11.652,0,1,0,11.651,11.653A11.666,11.666,0,0,0,467.994,225.506Zm0,21.373a9.722,9.722,0,1,1,9.721-9.721A9.733,9.733,0,0,1,467.994,246.879Z" transform="translate(7)" fill="#89c966"/>
<path id="Path_17" data-name="Path 17" d="M466.35,247.6a.3.3,0,0,1-.538,0l-2.838-5.468a7.958,7.958,0,0,1-2.7-1.007l5.232,10.082a.644.644,0,0,0,1.144,0l5.232-10.082a7.976,7.976,0,0,1-2.7,1.007Z" transform="translate(8.913 7.589)" fill="#89c966"/>
<path id="Path_18" data-name="Path 18" d="M461.375,240.561h2.945v-3.244h2.453v3.244h2.945V229.69h-8.343Zm4.513-9.47h2.9v.886h-2.9Zm0,1.834h2.9v.886h-2.9Zm0,1.834h2.9v.886h-2.9Zm-3.584-3.667h2.9v.886h-2.9Zm0,1.834h2.9v.886h-2.9Zm0,1.834h2.9v.886h-2.9Z" transform="translate(9.446 2.033)" fill="#89c966"/>
<path id="Path_19" data-name="Path 19" d="M446.035,241.065h2.548v-2.807h2.122v2.807h2.548v-9.407h-7.219Zm3.9-8.195h2.513v.767h-2.513Zm0,1.587h2.513v.767h-2.513Zm0,1.587h2.513v.767h-2.513Zm-3.1-3.174h2.513v.767h-2.513Zm0,1.587h2.513v.767h-2.513Zm0,1.587h2.513v.767h-2.513Z" transform="translate(1.992 2.989)" fill="#89c966"/>
<path id="Path_20" data-name="Path 20" d="M477.472,241.065h2.548v-2.807h2.122v2.807h2.548v-9.407h-7.219Zm3.9-8.195h2.513v.767h-2.513Zm0,1.587h2.513v.767h-2.513Zm0,1.587h2.513v.767h-2.513Zm-3.1-3.174h2.513v.767h-2.513Zm0,1.587h2.513v.767h-2.513Zm0,1.587h2.513v.767h-2.513Z" transform="translate(17.268 2.989)" fill="#89c966"/>
</g>
</svg>
Nearby Experiences
</p>
<div class="nearby-hotels">
<div class="row-hotels experiences"></div>
</div>
</div>
</div>
`;
}
}
|
export const IWouldLike = {
template: `<div id="IWouldLike" class="IWouldLike-Override">
<i class="i-part">I</i><i class="would-part">Would</i><i class="like-part">Like</i>
</div>`
};
|
StudentCentre.panel.AssignmentsHome = function(config) {
config = config || {};
Ext.apply(config,{
border: false
,baseCls: 'modx-formpanel'
,cls: 'container'
,items: [{
html: '<h2>'+_('studentcentre.ass')+'</h2>'
,border: false
,cls: 'modx-page-header'
},{
xtype: 'modx-tabs'
,defaults: { border: false ,autoHeight: true }
,border: true
,items: [{
title: _('studentcentre.ass_active')
,defaults: { autoHeight: true }
,items: [{
html: '<p>'+_('studentcentre.ass_active_desc')+'</p>'
,border: false
,bodyCssClass: 'panel-desc'
},{
xtype: 'studentcentre-grid-student-assignments'
,cls: 'main-wrapper'
,preventRender: true
}]
},{
title: _('studentcentre.ass_enrollment')
,defaults: { autoHeight: true }
,items: [{
html: '<p>'+_('studentcentre.ass_enrollment_desc')+'</p>'
,border: false
,bodyCssClass: 'panel-desc'
},{
xtype: 'studentcentre-grid-student-enrollment'
,cls: 'main-wrapper'
,preventRender: true
}]
},{
title: _('studentcentre.ass_programs')
,defaults: { autoHeight: true }
,items: [{
html: '<p>'+_('studentcentre.ass_program_desc')+'</p>'
,border: false
,bodyCssClass: 'panel-desc'
},{
xtype: 'studentcentre-grid-assignment-programs'
,cls: 'main-wrapper'
,preventRender: true
}]
},{
title: _('studentcentre.ass_levels')
,defaults: { autoHeight: true }
,items: [{
html: '<p>'+_('studentcentre.ass_level_desc')+'</p>'
,border: false
,bodyCssClass: 'panel-desc'
},{
xtype: 'studentcentre-grid-assignment-levels'
,cls: 'main-wrapper'
,preventRender: true
}]
},{
title: _('studentcentre.ass_assignments')
,defaults: { autoHeight: true }
,items: [{
html: '<p>'+_('studentcentre.ass_assignments_desc')+'</p>'
,border: false
,bodyCssClass: 'panel-desc'
},{
xtype: 'studentcentre-grid-assignments'
,cls: 'main-wrapper'
,preventRender: true
}]
}]
// only to redo the grid layout after the content is rendered
// to fix overflow components' panels, especially when scroll bar is shown up
,listeners: {
'afterrender': function(tabPanel) {
tabPanel.doLayout();
}
}
}]
});
StudentCentre.panel.AssignmentsHome.superclass.constructor.call(this,config);
};
Ext.extend(StudentCentre.panel.AssignmentsHome,MODx.Panel);
Ext.reg('studentcentre-panel-home',StudentCentre.panel.AssignmentsHome);
|
import React, { useContext, useState, useEffect, useRef } from "react";
import "antd/dist/antd.css";
import "./App.css";
import { Table, Input, Button, Form } from "antd";
import Map from "./MyMap"
const EditableContext = React.createContext(null);
const EditableRow = ({ index, ...props }) => {
const [form] = Form.useForm();
return (
<Form form={form} component={false}>
<EditableContext.Provider value={form}>
<tr {...props} />
</EditableContext.Provider>
</Form>
);
};
const EditableCell = ({
title,
editable,
children,
dataIndex,
record,
handleSave,
...restProps
}) => {
const [editing, setEditing] = useState(false);
const inputRef = useRef(null);
const form = useContext(EditableContext);
useEffect(() => {
if (editing) {
inputRef.current.focus();
}
}, [editing]);
const toggleEdit = () => {
setEditing(!editing);
form.setFieldsValue({
[dataIndex]: record[dataIndex],
});
};
const save = async () => {
try {
const values = await form.validateFields();
toggleEdit();
handleSave({ ...record, ...values });
} catch (errInfo) {
console.log("Save failed:", errInfo);
}
};
let childNode = children;
if (editable) {
let required = true;
if (dataIndex === "lat" || dataIndex === "lon") required = false;
childNode = editing ? (
<Form.Item
style={{
margin: 0,
}}
name={dataIndex}
rules={[
{
required: required,
message: `${title} is required.`,
},
]}
>
<Input ref={inputRef} onPressEnter={save} onBlur={save} />
</Form.Item>
) : (
<div
className="editable-cell-value-wrap"
style={{
paddingRight: 24,
}}
onClick={toggleEdit}
>
{children}
</div>
);
}
return <td {...restProps}>{childNode}</td>;
};
class App extends React.Component {
constructor(props) {
super(props);
this.columns = [
{
dataIndex: "operationDelete",
render: (_, record) =>
this.state.dataSource.length >= 1 ? (
<div>
<img src="/delete-32.png" alt="delete" onClick={() => this.handleDelete(record.key)}></img>
</div>
) : null,
},
{
title: "Идентификатор заказа",
dataIndex: "number",
editable: true,
align: "center",
width: "10%",
},
{
title: "Широта (необязательно)",
dataIndex: "lat",
editable: true,
align: "center",
width: "7%",
},
{
title: "Долгота (необязательно)",
dataIndex: "lon",
editable: true,
align: "center",
width: "7%",
},
{
title: "Наименование получателя",
dataIndex: "recName",
editable: true,
align: "center",
},
{
title: "Адрес получателя",
dataIndex: "recAdr",
editable: true,
align: "center",
},
{
title: "Окно",
dataIndex: "window",
editable: true,
align: "center",
},
{
title: "Жесткое окно, Да/Нет",
dataIndex: "harshWindow",
editable: true,
align: "center",
width: "6%",
},
{
title: "Время обслуживания на адрес, сек",
dataIndex: "timeAdr",
editable: true,
align: "center",
width: "7%",
},
{
title: "Время обслуживания на заказ, сек",
dataIndex: "timeDel",
editable: true,
align: "center",
width: "7%",
},
{
title: "Вес, кг",
dataIndex: "weight",
editable: true,
align: "center",
},
];
this.state = {
dataSource: [
{
key: "1",
number: "Текстовый заказ 1",
lat: "55.730847",
lon: "37.576789",
recName: "Перекресток",
recAdr: "Усачева ул.,2, стр.1",
window: "09:00-10:00",
harshWindow: "true",
timeAdr: "600",
timeDel: "120",
weight: "42.4",
},
],
count: 2,
};
}
handleDelete = (key) => {
const { count, dataSource } = this.state;
this.setState({
dataSource: dataSource.filter((item) => item.key !== key),
count: count - 1,
});
};
handleAdd = () => {
const { count, dataSource } = this.state;
const newData = {
key: count,
number: `Текстовый заказ ${count}`,
lat: "",
lon: "",
recName: "Перекресток",
recAdr: "Усачева ул.,2, стр.1",
window: "09:00-10:00",
harshWindow: "true",
timeAdr: "600",
timeDel: "120",
weight: "42.4",
};
this.setState({
dataSource: [...dataSource, newData],
count: count + 1,
});
};
handleSave = (row) => {
const newData = [...this.state.dataSource];
const index = newData.findIndex((item) => row.key === item.key);
const item = newData[index];
newData.splice(index, 1, { ...item, ...row });
this.setState({
dataSource: newData,
});
};
render() {
const { dataSource } = this.state;
const components = {
body: {
row: EditableRow,
cell: EditableCell,
},
};
const columns = this.columns.map((col) => {
if (!col.editable) {
return col;
}
return {
...col,
onCell: (record) => ({
record,
editable: col.editable,
dataIndex: col.dataIndex,
title: col.title,
handleSave: this.handleSave,
}),
};
});
return (
<div>
<Map/>
<Button
onClick={this.handleAdd}
type="primary"
style={{
marginBottom: 16,
}}
>
Добавить строку
</Button>
<Table
components={components}
rowClassName={() => "editable-row"}
bordered
dataSource={dataSource}
columns={columns}
/>
</div>
);
}
}
export default App;
|
/*****
CHEYENNE WALLACE: ANGULAR UPLOAD WITH PRESIGNED URL
http://www.cheynewallace.com/uploading-to-s3-with-angularjs-and-pre-signed-urls/
RUBY: UPLOAD WITH PRESIGNED URL
http://docs.aws.amazon.com/AmazonS3/latest/dev/UploadObjectPreSignedURLRubySDK.html#UploadObjectPreSignedURLRubySDKV2
*****/
module.exports = function($scope, $q, $http, $location, $state, UserService, envService, ImageSearchService, SearchService) {
// var deferred = $q.defer();
$scope.formData = { 'title': '', 'source': '', attach: false}
$scope.cancel = function() {
console.log('CANCEL')
$state.go('images')
}
$scope.upload = function (file) {
$scope.filename = file.name
var options = { headers: { "accesstoken": UserService.accessToken() }}
var query = {
filename: file.name,
title: $scope.formData.title,
source: $scope.formData.source,
attach: $scope.formData.attach,
type: file.type,
owner: UserService.username()
};
// 1. Get presigned URL
var url = envService.read('apiUrl') + '/presigned'
$http.post(url, query).success(function(response) {
console.log('_IMAGE: success, presigned token received', JSON.stringify(response))
var req = {
method: 'PUT',
url: response.url,
headers: { 'Content-Type': file.type },
data: file
}
// 2. Upload file to S3
$http(req)
.success(function(response) {
console.log('_IMAGE: success, image uploaded to S3', JSON.stringify(response))
console.log("IMAGE QUERY: " + JSON.stringify(query))
// 3. Add image to API database
var title = $scope.filename.split('.')[0].replace('_', ' ')
query['title'] = title
$http.post(envService.read('apiUrl') + '/images', query, options )
.success(function(response){
console.log('_IMAGE: success,create image database record, id = ' + response['id'])
console.log('_IMAGE: success,create image database record, response = ' + JSON.stringify(response))
if ($scope.formData.attach == true ) {
console.log('_IMAGE: FORK A, parent document = ' + response['parent_document'])
SearchService.query('id=' + response['parent_document'])
}
else {
ImageSearchService.query('id='+response['id'], $state)
console.log('_IMAGE: FORK B')
}
})
})
.error(function(response) {
console.log("_IMAGE: Error:" + JSON.stringify(response));
});
})
};
}
|
/*
* 总 SDK
*
*
*/
function epgs (spec){
this.epgMedia = epgMedia.init(spec.host,spec.epgId);
this.epgAd = epgAd.init(spec.host,spec.epgId);
this.epgArea = epgArea.init(spec.host);
this.epgCategory = epgCategory.init(spec.host, spec.epgId);
this.epgChannel = epgChannel.init(spec.host);
this.epgColumn = epgColumn.init(spec.host, spec.epgId);
this.epgLanguage = epgLanguage.init(spec.host);
this.epgProvider = epgProvider.init(spec.host);
this.epgRcmb = epgRcmb.init(spec.host, spec.epgId);
this.epgSync = epgSync.init(spec.host, spec.epgId);
}
epgs.init = function (host, epgId) {
return new epgs({
epgId: epgId,
host: host
});
};
//----------------------------------- media 请求部分
function epgMedia (spec) {
this.id = spec.epgId;
this.host = spec.host;
this.url = 'http://' + spec.host + '/epgs/' + spec.epgId + '/media/'
this.send = function (url, body, callback) { // callback (err, resp)
var epgId = this.id;
var host = this.host;
if(!epgId || !host) {
if (typeof callback === 'function') callback(401, 'epgId and host are required!!');
return;
}
var url = this.url + url;
var req = new XMLHttpRequest();
req.onreadystatechange = function () {
if (req.readyState == '4') {
switch (req.status) {
case 100:
case 200:
case 201:
case 202:
case 203:
case 204:
case 205:
if (typeof callback === 'function') callback(null, req.responseText);
break;
default:
if (typeof callback === 'function') callback(req.status, req.responseText);
}
}
};
req.open('GET', url, true);
if (body) {
req.setRequestHeader('Content-Type', 'application/json');
req.send(JSON.stringify(body));
} else {
req.send();
}
};
}
epgMedia.init = function (host, epgId) {
return new epgMedia({
epgId: epgId,
host: host
});
};
epgMedia.prototype.get = function (columnid, token, obj, callback) {
var url = 'get?columnid=' + columnid + '&token=' + token;
if (obj != null) {
if (obj.pagesize != null)
url += ('&pagesize=' + obj.pagesize);
if (obj.pageindex != null)
url += ('&pageindex=' + obj.pageindex);
if (obj.meta != null)
url += ('&meta=' + obj.meta);
if (obj.category != null)
url += ('&category' + obj.category);
if (obj.area != null)
url += ('&area' + obj.area);
if (obj.tag != null)
url += ('&tag=' + obj.tag);
if (obj.year != null)
url += ('&year=' + obj.year);
if (obj.title != null)
url += ('&title=' + obj.title);
if (obj.pinyin != null)
url += ('&pinyin=' + obj.pinyin);
if (obj.actor != null)
url += ('&actor=' + obj.actor);
if (obj.sort != null)
url += ('&sort=' + obj.sort);
if (obj.lang != null)
url += ('&lang=' + obj.lang);
}
this.send(url, null,callback);
};
epgMedia.prototype.detail = function (columnid, token, obj, callback){
var url = 'detail?columnid=' + columnid + '&token=' + token;
if (obj != null) {
if (obj.id != null)
url += ('&id=' + obj.id);
if (obj.provider != null)
url += ('&provider=' + obj.provider);
if (obj.pageindex != null)
url += ('&pageindex=' + obj.pageindex);
if (obj.lang != null)
url += ('&lang=' + obj.lang);
if (obj.pagesize != null)
url += ('&pagesize=' + obj.pagesize);
}
this.send(url, null,callback);
}
epgMedia.prototype.relate = function (columnid, token, obj, callback){
var url = 'relate?columnid=' + columnid + '&token=' + token;
if (obj != null) {
if (obj.id != null)
url += ('&id=' + obj.id);
if (obj.lang != null)
url += ('&lang=' + obj.lang);
if (obj.size != null)
url += ('&size=' + obj.size);
}
this.send(url, null,callback);
}
//---------------------------- END Media
//---------------------------- Ad 请求部分
function epgAd (spec) {
this.id = spec.epgId;
this.host = spec.host;
this.url = 'http://' + spec.host + '/epgs/' + spec.epgId + '/ad/'
this.send = function (url, body, callback) { // callback (err, resp)
var epgId = this.id;
var host = this.host;
if(!epgId || !host) {
if (typeof callback === 'function') callback(401, 'epgId and host are required!!');
return;
}
var url = this.url + url;
var req = new XMLHttpRequest();
req.onreadystatechange = function () {
if (req.readyState == '4') {
switch (req.status) {
case 100:
case 200:
case 201:
case 202:
case 203:
case 204:
case 205:
if (typeof callback === 'function') callback(null, req.responseText);
break;
default:
if (typeof callback === 'function') callback(req.status, req.responseText);
}
}
};
req.open('GET', url, true);
if (body) {
req.setRequestHeader('Content-Type', 'application/json');
req.send(JSON.stringify(body));
} else {
req.send();
}
};
}
epgAd.init = function (host, epgId) {
return new epgAd({
epgId: epgId,
host: host
});
};
epgAd.prototype.get = function (columnid, token, obj, callback) {
var url = 'get?columnid=' + columnid + '&token=' + token;
if (obj != null) {
if (obj.meta != null)
url += ('&meta=' + obj.meta);
if (obj.title != null)
url += ('&title=' + obj.title);
if (obj.type != null)
url += ('&type=' + obj.type);
}
this.send(url, null, callback);
};
epgAd.prototype.map = function (token, callback){
var url = 'map?token=' + token;
this.send(url, null,callback);
}
//----------------- END Ad
//----------------- Area 部分
function epgArea (spec) {
this.host = spec.host;
this.url = 'http://' + spec.host + '/epgs/area/'
this.send = function (url, body, callback) { // callback (err, resp)
var epgId = this.id;
var host = this.host;
if(!host) {
if (typeof callback === 'function') callback(401, 'host are required!!');
return;
}
var url = this.url + url;
var req = new XMLHttpRequest();
req.onreadystatechange = function () {
if (req.readyState == '4') {
switch (req.status) {
case 100:
case 200:
case 201:
case 202:
case 203:
case 204:
case 205:
if (typeof callback === 'function') callback(null, req.responseText);
break;
default:
if (typeof callback === 'function') callback(req.status, req.responseText);
}
}
};
req.open('GET', url, true);
if (body) {
req.setRequestHeader('Content-Type', 'application/json');
req.send(JSON.stringify(body));
} else {
req.send();
}
};
}
epgArea.init = function (host) {
return new epgArea({
host: host
});
};
epgArea.prototype.get = function (token, obj, callback) {
var url = 'get?token=' + token;
if (obj != null) {
if (obj.lang != null)
url += ('&lang=' + obj.lang);
}
this.send(url, null,callback);
};
//---------------------- END Area
//---------------------- Category 部分
function epgCategory (spec) {
this.id = spec.epgId;
this.host = spec.host;
this.url = 'http://' + spec.host + '/epgs/' + spec.epgId + '/category/'
this.send = function (url, body, callback) { // callback (err, resp)
var epgId = this.id;
var host = this.host;
if(!epgId || !host) {
if (typeof callback === 'function') callback(401, 'epgId and host are required!!');
return;
}
var url = this.url + url;
var req = new XMLHttpRequest();
req.onreadystatechange = function () {
if (req.readyState == '4') {
switch (req.status) {
case 100:
case 200:
case 201:
case 202:
case 203:
case 204:
case 205:
if (typeof callback === 'function') callback(null, req.responseText);
break;
default:
if (typeof callback === 'function') callback(req.status, req.responseText);
}
}
};
req.open('GET', url, true);
if (body) {
req.setRequestHeader('Content-Type', 'application/json');
req.send(JSON.stringify(body));
} else {
req.send();
}
};
}
epgCategory.init = function (host, epgId) {
return new epgCategory({
epgId: epgId,
host: host
});
};
epgCategory.prototype.get = function (columnid, token, obj, callback) {
var url = 'get?columnid=' + columnid + '&token=' + token;
if (obj != null) {
if (obj.lang != null)
url += ('&lang=' + obj.lang);
}
this.send(url, null,callback);
};
//------------------- END Category
//------------------- Channel 部分
function epgChannel (spec) {
this.host = spec.host;
this.url = 'http://' + spec.host + '/epgs/channel/epg/'
this.send = function (url, body, callback) { // callback (err, resp)
var epgId = this.id;
var host = this.host;
if(!host) {
if (typeof callback === 'function') callback(401, 'host are required!!');
return;
}
var url = this.url + url;
var req = new XMLHttpRequest();
req.onreadystatechange = function () {
if (req.readyState == '4') {
switch (req.status) {
case 100:
case 200:
case 201:
case 202:
case 203:
case 204:
case 205:
if (typeof callback === 'function') callback(null, req.responseText);
break;
default:
if (typeof callback === 'function') callback(req.status, req.responseText);
}
}
};
req.open('GET', url, true);
if (body) {
req.setRequestHeader('Content-Type', 'application/json');
req.send(JSON.stringify(body));
} else {
req.send();
}
};
}
epgChannel.init = function (host, epgId) {
return new epgChannel({
host: host
});
};
epgChannel.prototype.get = function (id, token, obj, callback) {
var url = 'get?id=' + id + '&token=' + token;
if (obj != null) {
if (obj.date != null)
url += ('&date=' + obj.date);
if (obj.timezone != null)
url += ('&timezone=' + obj.timezone);
if (obj.days != null)
url += ('&days=' + obj.days);
if (obj.lang != null)
url += ('&lang=' + obj.lang);
if (obj.utc != null)
url += ('&utc=' + obj.utc);
if (obj.endutc != null)
url += ('&endutc=' + obj.endutc);
}
this.send(url, null, callback);
};
epgChannel.prototype.sync = function (token, callback){
var url = 'sync?token=' + token;
this.send(url, null,callback);
}
//--------------------- END Channel
//--------------------- Column 部分
function epgColumn (spec) {
this.id = spec.epgId;
this.host = spec.host;
this.url = 'http://' + spec.host + '/epgs/' + spec.epgId + '/column/'
this.send = function (url, body, callback) { // callback (err, resp)
var epgId = this.id;
var host = this.host;
if(!epgId || !host) {
if (typeof callback === 'function') callback(401, 'epgId and host are required!!');
return;
}
var url = this.url + url;
var req = new XMLHttpRequest();
req.onreadystatechange = function () {
if (req.readyState == '4') {
switch (req.status) {
case 100:
case 200:
case 201:
case 202:
case 203:
case 204:
case 205:
if (typeof callback === 'function') callback(null, req.responseText);
break;
default:
if (typeof callback === 'function') callback(req.status, req.responseText);
}
}
};
req.open('GET', url, true);
if (body) {
req.setRequestHeader('Content-Type', 'application/json');
req.send(JSON.stringify(body));
} else {
req.send();
}
};
}
epgColumn.init = function (host, epgId) {
return new epgColumn({
epgId: epgId,
host: host
});
};
epgColumn.prototype.get = function (pid, token, obj, callback) {
var url = 'get?pid=' + pid + '&token=' + token;
if (obj != null) {
if (obj.lang != null)
url += ('&lang=' + obj.lang);
}
this.send(url, null, callback);
};
epgColumn.prototype.list = function (token, obj, callback){
var url = 'list?token=' + token;
if (obj != null) {
if (obj.lang != null)
url += ('&lang=' + obj.lang);
}
this.send(url, null,callback);
}
epgColumn.prototype.map = function (token, obj, callback){
var url = 'map?token=' + token;
if (obj != null) {
if (obj.lang != null)
url += ('&lang=' + obj.lang);
}
this.send(url, null,callback);
}
epgColumn.prototype.info = function (token, id, callback){
var url = 'info?token=' + token + '&id=' + id;
this.send(url, null,callback);
}
//---------------------- END Column
//---------------------- Language 部分
function epgLanguage (spec) {
this.host = spec.host;
this.url = 'http://' + spec.host + '/epgs/language'
this.send = function (url, body, callback) { // callback (err, resp)
var epgId = this.id;
var host = this.host;
if(!host) {
if (typeof callback === 'function') callback(401, 'host are required!!');
return;
}
var url = this.url + url;
var req = new XMLHttpRequest();
req.onreadystatechange = function () {
if (req.readyState == '4') {
switch (req.status) {
case 100:
case 200:
case 201:
case 202:
case 203:
case 204:
case 205:
if (typeof callback === 'function') callback(null, req.responseText);
break;
default:
if (typeof callback === 'function') callback(req.status, req.responseText);
}
}
};
req.open('GET', url, true);
if (body) {
req.setRequestHeader('Content-Type', 'application/json');
req.send(JSON.stringify(body));
} else {
req.send();
}
};
}
epgLanguage.init = function (host) {
return new epgLanguage({
host: host
});
};
epgLanguage.prototype.get = function (token, callback) {
var url = '?token=' + token;
this.send(url, null,callback);
};
//--------------------- END Language
//--------------------- Provider 部分
function epgProvider (spec) {
this.host = spec.host;
this.url = 'http://' + spec.host + '/epgs/provider/'
this.send = function (url, body, callback) { // callback (err, resp)
var epgId = this.id;
var host = this.host;
if(!host) {
if (typeof callback === 'function') callback(401, 'host are required!!');
return;
}
var url = this.url + url;
var req = new XMLHttpRequest();
req.onreadystatechange = function () {
if (req.readyState == '4') {
switch (req.status) {
case 100:
case 200:
case 201:
case 202:
case 203:
case 204:
case 205:
if (typeof callback === 'function') callback(null, req.responseText);
break;
default:
if (typeof callback === 'function') callback(req.status, req.responseText);
}
}
};
req.open('GET', url, true);
if (body) {
req.setRequestHeader('Content-Type', 'application/json');
req.send(JSON.stringify(body));
} else {
req.send();
}
};
}
epgProvider.init = function (host) {
return new epgProvider({
host: host
});
};
epgProvider.prototype.get = function (token, obj, callback) {
var url = 'get?token=' + token;
if (obj != null) {
if (obj.lang != null)
url += ('&lang=' + obj.lang);
}
this.send(url, null,callback);
};
//------------------ END Provider
//----------------- Rcmb 部分
function epgRcmb (spec) {
this.id = spec.epgId;
this.host = spec.host;
this.url = 'http://' + spec.host + '/epgs/' + spec.epgId + '/rcmb/'
this.send = function (url, body, callback) { // callback (err, resp)
var epgId = this.id;
var host = this.host;
if(!epgId || !host) {
if (typeof callback === 'function') callback(401, 'epgId and host are required!!');
return;
}
var url = this.url + url;
var req = new XMLHttpRequest();
req.onreadystatechange = function () {
if (req.readyState == '4') {
switch (req.status) {
case 100:
case 200:
case 201:
case 202:
case 203:
case 204:
case 205:
if (typeof callback === 'function') callback(null, req.responseText);
break;
default:
if (typeof callback === 'function') callback(req.status, req.responseText);
}
}
};
req.open('GET', url, true);
if (body) {
req.setRequestHeader('Content-Type', 'application/json');
req.send(JSON.stringify(body));
} else {
req.send();
}
};
}
epgRcmb.init = function (host, epgId) {
return new epgRcmb({
epgId: epgId,
host: host
});
};
epgRcmb.prototype.get = function (columnid, token, obj, callback) {
var url = 'get?columnid=' + columnid + '&token=' + token;
if (obj != null) {
if (obj.meta != null)
url += ('&meta=' + obj.meta);
if (obj.title != null)
url += ('&title=' + obj.title);
if (obj.type != null)
url += ('&type=' + obj.type);
}
this.send(url, null, callback);
};
epgRcmb.prototype.map = function (token, callback){
var url = 'map?token=' + token;
this.send(url, null,callback);
}
//---------------------------- END Rcmb
//---------------------------- Sync 部分
function epgSync (spec) {
this.id = spec.epgId;
this.host = spec.host;
this.url = 'http://' + spec.host + '/epgs/' + spec.epgId + '/sync/';
this.send = function (url, body, callback) { // callback (err, resp)
var epgId = this.id;
var host = this.host;
if(!epgId || !host) {
if (typeof callback === 'function') callback(401, 'epgId and host are required!!');
return;
}
var url = this.url + url;
var req = new XMLHttpRequest();
req.onreadystatechange = function () {
if (req.readyState == '4') {
switch (req.status) {
case 100:
case 200:
case 201:
case 202:
case 203:
case 204:
case 205:
if (typeof callback === 'function') callback(null, req.responseText);
break;
default:
if (typeof callback === 'function') callback(req.status, req.responseText);
}
}
};
req.open('GET', url, true);
if (body) {
req.setRequestHeader('Content-Type', 'application/json');
req.send(JSON.stringify(body));
} else {
req.send();
}
};
}
epgSync.init = function (host, epgId) {
return new epgSync({
epgId: epgId,
host: host
});
};
epgSync.prototype.get = function (columnid, token, callback) {
columnid = (columnid == null) ? '' : columnid;
var url = 'get?columnid=' + columnid + '&token=' + token;
this.send(url, null, callback);
};
epgSync.prototype.map = function (token, callback){
var url = 'map?token=' + token;
this.send(url, null,callback);
}
//----------------------- END Sync
|
import styled from "styled-components/macro"
import MyWorkContainer from "../containers/MyWorkContainer"
import { SidebarContainer } from "../containers/SidebarContainer"
export default function MyWork() {
const Wrapper = styled.div`
display: flex;
`
return (
<Wrapper>
<SidebarContainer />
<MyWorkContainer />
</Wrapper>
)
}
|
const parser = require('freestyle-parser');
exports.eventGroup = 'onMessage';
exports.description = 'Spammer';
exports.command = 'spam';
exports.parameters = [
{
input: true,
description: 'num'
},
{
input: true,
description: 'phrase'
}
];
exports.script = function(cmd, msg){
msg.delete({timeout:0});
let maxSpams = 10;
let num = Math.min(parseInt(parser.getArg(msg.content, 0)), maxSpams);
let content = parser.getFreestyle(msg.content, 1);
for(let i = 0; i < num; i++) msg.channel.send(content);
}
|
import "./completedtest.css";
import Swal from 'sweetalert2';
import { DataGrid } from "@material-ui/data-grid";
import { Link } from "react-router-dom";
import { useEffect, useState } from 'react';
import TestDataService from "../../../services/tests.service";
import DeleteIcon from "@material-ui/icons/Delete";
import Button from '@material-ui/core/Button';
export default function SubbmittedTests() {
const columns = [
{ field: 'specimenid', headerName: 'Specimen ID', width: 140 },
{
field: 'starteddate',
headerName: 'Date Started',
width: 200,
type: 'date',
editable: true,
},
{
field: 'completeddate',
headerName: 'Date Finished',
width: 200,
type: 'date',
editable: true,
},
{
field: 'testtype',
headerName: 'Specimen Type',
type: 'text',
width: 130,
editable: true,
},
{
field: 'status',
headerName: 'Status',
type: 'text',
width: 130,
editable: true,
},
{
field: "action",
headerName: "Action",
width: 275,
renderCell: (params) => {
return (
<>
<Link to={"/staff/labassistant/downloadform/" + params.row.id}>
<button className="userListEdit2">Report Download</button>
</Link>
<Button
variant="contained"
color="secondary"
value={params.row.id}
onClick={deleteTest}
>
<DeleteIcon />
</Button>
</>
);
},
}
];
const deleteTest = event => {
Swal.fire({
icon: 'success',
title: 'Test has been Deleted',
showConfirmButton: false,
timer: 1500
})
TestDataService.remove(event.currentTarget.value)
.then(response => {
window.location.reload();
})
.catch(error => {
console.log(error);
})
}
const [tests, setTests] = useState([]);
useEffect(() => {
retrieveCompletedTests();
}, []);
const retrieveCompletedTests = () => {
TestDataService.getAllCompleted()
.then(response => {
setTests(response.data)
})
.catch(err => {
console.log("Error while getting data from database" + err);
}
)
};
let rows = [];
for (const test of tests) {
rows.push(
{
id: test._id,
specimenid: test.specimenid,
starteddate: test.starteddate,
completeddate: test.completeddate,
testtype: test.testtype,
patientsname: test.patientsname,
status: test.status
}
)
}
return (
<div style={{ height: 550, width: '100%' }} className="userList">
<DataGrid
rows={rows}
disableSelectionOnClick
columns={columns}
pageSize={8}
checkboxSelection
/>
</div>
);
}
|
import { API } from "../config";
import queryString from 'query-string';
//==== Return Product by sold/arrival ====//
export const getProducts = (sortBy) => {
return fetch(`${API}/products?sortBy=${sortBy}&order=desc&limit=6`, {
method: "GET",
})
.then((response) => {
return response.json();
})
.catch((err) => console.log(err));
};
//========================================//
//==== Get all categories ====//
// Retrieves all categories from
// the backend
export const getCategories = () => {
return fetch(`${API}/categories`, {
method: "GET",
})
.then((response) => {
return response.json();
})
.catch((err) => console.log(err));
};
//=========================================//
//===== Get filtered products ====/
export const getFilteredProducts = (skip, limit, filters = {}) => {
const data = {
limit,
skip,
filters
};
return fetch(`${API}/products/by/search`, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify(data)
})
.then(response => {
return response.json();
})
.catch(err => {
console.log(err);
});
};
//=================================/
//==== Get all products based on query parameter ====//
// Used in returning products based on search
// to be displayed on the homepage after search
export const list = (params) => {
const query = queryString.stringify(params);
return fetch(`${API}/products/search?${query}`, {
method: "GET",
})
.then((response) => {
return response.json();
})
.catch((err) => console.log(err));
};
//===================================================//
//==== Get single product ====//
// Used to fetch single product
// to be displayed on the product (detail) page
export const read = productId => {
return fetch(`${API}/product/${productId}`, {
method: "GET"
})
.then(response => {
return response.json();
})
.catch(err => console.log(err));
};
//============================//
//==== Get all related products ====//
// Used to fetch all the related products
// based on the category of a selected
// product by the user
export const listRelated = productId => {
return fetch(`${API}/products/related/${productId}`, {
method: "GET"
})
.then(response => {
return response.json();
})
.catch(err => console.log(err));
};
//=================================//
//==== Get braintree client-side token ====//
export const getBraintreeClientToken = (userId, token)=> {
return fetch(`${API}/braintree/getToken/${userId}`, {
method: "GET",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
Authorization : `Bearer ${token}`
},
})
.then(response => {
return response.json();
})
.catch(err => console.log(err));
};
//==========================================//
//==== Process payment ====//
export const processPayment = (userId, token, paymentData) => {
return fetch(`${API}/braintree/payment/${userId}`, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
Authorization: `Bearer ${token}`
},
body: JSON.stringify(paymentData)
})
.then(response => {
return response.json();
})
.catch(err => console.log(err));
};
//=========================//
//==== Create order ====//
export const createOrder = (userId, token, createOrderData) => {
return fetch(`${API}/order/create/${userId}`, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
Authorization: `Bearer ${token}`
},
body: JSON.stringify({ order: createOrderData })
})
.then(response => {
return response.json();
})
.catch(err => console.log(err));
};
//=======================//
|
import React from 'react'
import { Route } from 'react-router-dom'
import * as BooksAPI from './utils/BooksAPI'
import ListBooks from './components/ListBooks'
import SearchBooks from './components/SearchBooks'
import './App.css'
class BooksApp extends React.Component {
state = {
books: []
}
componentDidMount() {
this.fetchAllBooks()
}
fetchAllBooks() {
BooksAPI.getAll().then((books) => this.setState({ books }))
}
changeShelf = (updatedBook, shelf) => {
BooksAPI.update(updatedBook, shelf).then(() => {
this.setState(state => {
let currentBooks = []
const alreadyOnShelf = state.books.find(book => book.id === updatedBook.id)
if (alreadyOnShelf) {
currentBooks = state.books.map(book => {
if (book.id === updatedBook.id) {
book.shelf = shelf
}
return book
})
} else {
updatedBook.shelf = shelf
currentBooks = state.books.concat([updatedBook])
}
return {books: currentBooks}
})
})
}
handler = (books) => {
this.setState({books})
}
render() {
const {books} = this.state
return (
<div className="app">
<Route exact path='/' render={() => (
<ListBooks
books={books}
onShelfChange={this.changeShelf}
/>
)}/>
<Route path='/search' render={({ history }) => (
<SearchBooks
currentBooks={books}
handler={this.handler}
onShelfChange={this.changeShelf}
/>
)}/>
</div>
)
}
}
export default BooksApp
|
import path from 'path'
import pify from 'pify'
import { GitCommit, GitTree } from '../models'
import { GitRefManager, GitObjectManager, GitIndexManager } from '../managers'
import { rm, write, fs } from '../utils'
async function writeTreeToDisk ({ gitdir, workdir, index, prefix, tree }) {
for (let entry of tree) {
let { type, object } = await GitObjectManager.read({
gitdir,
oid: entry.oid
})
let entrypath = prefix === '' ? entry.path : `${prefix}/${entry.path}`
let filepath = path.join(workdir, prefix, entry.path)
switch (type) {
case 'blob':
await write(filepath, object)
let stats = await pify(fs().lstat)(filepath)
index.insert({
filepath: entrypath,
stats,
oid: entry.oid
})
break
case 'tree':
let tree = GitTree.from(object)
await writeTreeToDisk({
gitdir,
workdir,
index,
prefix: entrypath,
tree
})
break
default:
throw new Error(
`Unexpected object type ${type} found in tree for '${entrypath}'`
)
}
}
}
export async function checkout ({ workdir, gitdir, remote, ref }) {
// Get tree oid
let oid
if (remote) {
let remoteRef
if (ref === undefined) {
remoteRef = await GitRefManager.resolve({
gitdir,
ref: `${remote}/HEAD`,
depth: 2
})
ref = path.basename(remoteRef)
} else {
remoteRef = `${remote}/${ref}`
}
oid = await GitRefManager.resolve({ gitdir, ref: remoteRef })
// Make the remote ref our own!
await write(`${gitdir}/refs/heads/${ref}`, oid + '\n')
} else {
if (ref === undefined) {
throw new Error('Cannot checkout ref "undefined"')
}
oid = await GitRefManager.resolve({ gitdir, ref })
}
let commit = await GitObjectManager.read({ gitdir, oid })
if (commit.type !== 'commit') {
throw new Error(`Unexpected type: ${commit.type}`)
}
let comm = GitCommit.from(commit.object.toString('utf8'))
let sha = comm.headers().tree
// Get top-level tree
let { type, object } = await GitObjectManager.read({ gitdir, oid: sha })
if (type !== 'tree') throw new Error(`Unexpected type: ${type}`)
let tree = GitTree.from(object)
// Acquire a lock on the index
await GitIndexManager.acquire(`${gitdir}/index`, async function (index) {
// TODO: Big optimization possible here.
// Instead of deleting and rewriting everything, only delete files
// that are not present in the new branch, and only write files that
// are not in the index or are in the index but have the wrong SHA.
for (let entry of index) {
try {
await rm(path.join(workdir, entry.path))
} catch (err) {}
}
index.clear()
// Write files. TODO: Write them atomically
await writeTreeToDisk({ gitdir, workdir, index, prefix: '', tree })
// Update HEAD TODO: Handle non-branch cases
write(`${gitdir}/HEAD`, `ref: refs/heads/${ref}`)
})
}
|
function openOver() {
document.getElementById("overlayUp").style.height = "750px";
}
function closeOver() {
document.getElementById("overlayUp").style.height = "0";
}
function closeIn() {
document.getElementById("overlayUp").style.height = "0";
}
function openReg() {
document.getElementById("overlayUp2").style.height = "750px";
}
|
import React from 'react';
import './style/post.css'
export default ({urltoimg,description,id,title}) => {
const body = (
<div className="post">
<p className="post_title"> {title} </p>
<img src={urltoimg} alt="imeges" />
<p className="post_description"> {description} </p>
</div>
)
return(
<div>
{body}
</div>
);
}
|
/*
* Copyright (C) 2009-2013 SAP AG or an SAP affiliate company. All rights reserved
*/
jQuery.sap.declare("sap.ca.ui.quickoverview.Quickoverview");
jQuery.sap.require("sap.ui.base.Object");
jQuery.sap.require("sap.ca.ui.utils.resourcebundle");
sap.ca.ui.quickoverview.QuickviewUtils = (function() {
var _INIT = "initstuff";
return ({
getAttrValue : function(sValue, oModel) {
// take over the value or read the value-'path' from model in case
// model is provided
//deep attributes: oModel.getData()["deeptest"]["deepattr1"]
if (!sValue) {
return "";
}
var iBrStart = sValue.indexOf('{');
var iBrEnd = sValue.indexOf('}')
if (iBrStart > -1 && oModel) {
// read modelattribute
var sPath = sValue;
sPath = sPath.substring(iBrStart + 1);
sPath = sPath.substring(0, iBrEnd - 1);
sPath = sPath.replace(/\//g, ".")
// remove the first '.'
var sFirstChar = sPath.substring(0, 1)
if (sFirstChar === ".") {
sPath = sPath.substring(1)
}
var sPathValue = oModel.getData()[sPath];
return sPathValue;
} else {
return sValue;
}
}
});
}());
sap.ca.ui.quickoverview.QuickviewBase = (function() {
var _QVPOPOVERID = "qvPopover";
var _QVVIEWNAME = "qvView";
var _QVBACKBUTTON = "qvBackBtn";
var _QVTITLE = "qvTitle";
var _QVNAVCNT = "qvNavCnt";
var _QVINITPAGE = jQuery.sap.uid()+"-p1"; // IDs always needs to be unique
var _DEFAULTHEIGHT = "38rem";
var _oApp = null;
// todo: replace 'byId() statements - rather use the following variable
// var _oQvControls = {};
// _oQvControls.oPopover = null;
var getViewName = function() {
return "sap.ca.ui.quickoverview.Quickview";
};
var showHideBackButton = function(){
//compare current displayed page with initial page
var oBackButton = sap.ui.getCore().byId(_QVBACKBUTTON);
var oNav = sap.ui.getCore().byId(_QVNAVCNT);
oBackButton.setVisible((oNav.getCurrentPage().sId !== oNav.getInitialPage()));
};
var configureQvView = function(oQvView, oConfig, oQvPage, oQuickoverview) {
//hosting view: set model for application attributes
oQvView.setModel(oConfig.oModel);
//hosting controller: set additional properties
var oController = oQvView.getController();
configController(oController, oConfig, oQuickoverview);
//configure quickoverview...embed subview etc.
var oQvViewSetup = oController.configureView();
//popover Title and popoverheight
configPopover( oConfig.title, oQvPage, oConfig.popoverHeight);
//call application 'exit'
var sCallback = oConfig.afterQvConfigured;
if ( typeof(sCallback) == "function"){
sCallback(oQvViewSetup.oQvView, oQvViewSetup.oSubView);
}
};
var configPopover = function(sTitle, oPage, sHeight) {
if (!sTitle) {
sTitle = sap.ca.ui.utils.resourcebundle
.getText("Quickoverview.popovertitle")
}
var oTitle = sap.ui.getCore().byId(_QVTITLE);
oTitle.setText(sTitle);
//set title also for page: ( during 'backnavigation'
//this page title will be taken for the popover title )
oPage.setTitle(sTitle);
var sThisHeight = sHeight;
if (!sThisHeight)
{
sThisHeight = _DEFAULTHEIGHT;
}
var oPopover = sap.ui.getCore().byId(_QVPOPOVERID);
oPopover.setContentHeight(sThisHeight);
oPage.qvHeight = sThisHeight; //hack to buffer popoverheight !
};
var setPopoverTitleFromPage = function(oPage){
var oTitle = sap.ui.getCore().byId(_QVTITLE);
oTitle.setText(oPage.getTitle());
};
var setPopoverHeightFromPage = function(oPage){
var oPopover = sap.ui.getCore().byId(_QVPOPOVERID);
oPopover.setContentHeight(oPage.qvHeight);
};
var configController = function(oController, oConfig, oQuickoverview) {
//QUICKOVERVIEW HOSTVIEW controller: add configuration properties
var sEmpty = "";
oController.viewConfig = {};
oController.viewConfig.headerNoIcon = (oConfig.headerNoIcon) ? oConfig.headerNoIcon
: false;
oController.viewConfig.headerTitle = (oConfig.headerTitle) ? oConfig.headerTitle
: sEmpty;
oController.viewConfig.headerSubTitle = (oConfig.headerSubTitle) ? oConfig.headerSubTitle
: sEmpty;
oController.viewConfig.headerImgURL = (oConfig.headerImgURL) ? oConfig.headerImgURL : sEmpty;
oController.viewConfig.subViewName = (oConfig.subViewName) ? oConfig.subViewName : sEmpty;
oController.viewConfig.quickOverview = oQuickoverview;
oController.viewConfig.beforeExtNav = (oConfig.beforeExtNav) ? oConfig.beforeExtNav : sEmpty;
oController.viewConfig.beforeExtNavSubHdr = (oConfig.beforeExtNavSubHdr) ? oConfig.beforeExtNavSubHdr : sEmpty;
};
// create initial popover and page and view
var createQVPopover = function() {
var popoverId = _QVPOPOVERID;
var oPopover = sap.ui.getCore().byId(popoverId);
if (!oPopover) {
// add nav container + page + view
var oNavContainer = new sap.m.NavContainer(_QVNAVCNT, {
initialPage : _QVINITPAGE,
height : "100%",
pages : [ new sap.m.Page(_QVINITPAGE, {
showHeader : false,
enableScrolling : true,
content : [ new sap.ui.view({
id : "qvView",
viewName : "sap.ca.ui.quickoverview.Quickview",
type : sap.ui.core.mvc.ViewType.XML
})
]
}) ]
});
var fAfterNavigate = function(oData) {
var sPageId;
if (oData.mParameters.isBack) {
// destroy and remove previous page
sPageId = oData.mParameters.fromId;
var oPrevPage = this.getPage(sPageId);
if ( oPrevPage ) {
oPrevPage.destroy();
this.removePage(sPageId);
}
//update popover title
setPopoverTitleFromPage(this.getPage(oData.mParameters.toId));
setPopoverHeightFromPage(this.getPage(oData.mParameters.toId));
} else if (oData.mParameters.isBackToTop) {
// destroy and remove previous page stack
var count = this.getPages().length;
for ( var i = count - 1; i > -1; i--) {
sPageId = this.getPages()[i].sId;
if (sPageId !== this.getInitialPage()) {
this.getPage(sPageId).destroy();
this.removePage(sPageId);
}
}
}
showHideBackButton();
}
oNavContainer.attachAfterNavigate(fAfterNavigate);
//prepare header
var oBackButton = new sap.m.Button({
id : _QVBACKBUTTON,
icon : "sap-icon://nav-back",
visible : false,
tap : function() {
var nav = sap.ui.getCore().byId(_QVNAVCNT);
nav.back();
}
});
var oTitle = new sap.m.Label({
id : _QVTITLE,
visible : true
});
var oCustHeader = new sap.m.Bar({
translucent : false,
contentLeft : oBackButton,
contentMiddle : oTitle
});
oPopover = new sap.m.ResponsivePopover(popoverId, {
customHeader : oCustHeader,
//modal : true, //required for analyzing
showHeader : true,
placement : sap.m.PlacementType.Right,
verticalScrolling : false,
contentWidth : "20em", // "320px", // width of an IPhone
contentHeight : _DEFAULTHEIGHT,
content : oNavContainer
});
var fnPopoverClose = function() {
var nav = sap.ui.getCore().byId(_QVNAVCNT);
nav.backToTop();
showHideBackButton();
};
oPopover.attachAfterClose(fnPopoverClose);
//load stylesheet for object header icon coloring
//"sap/ca/ui/themes/base/QuickOverview.css"
var sPath = jQuery.sap.getModulePath("sap/ca/ui") + "/themes/base/QuickOverview.css";
jQuery.sap.includeStyleSheet(sPath);
}
return oPopover;
};
return ({
initQVPopover : function(oParentCard) {
var oPopover = createQVPopover();
},
openQVPopover : function(oSourceControl, oConfig, oLocation,
oQuickoverview) {
// set additional attributes to the viewcontroller
var oView = sap.ui.getCore().byId(_QVVIEWNAME);
var oPage = sap.ui.getCore().byId(_QVINITPAGE);
//set up content of popover
configureQvView(oView, oConfig, oPage, oQuickoverview);
//open popover ...with placement!
try {
// jQuery.sap.history.addVirtualHistory();
// fix: dynamic calculation of placement type
var oPopover = sap.ui.getCore().byId(_QVPOPOVERID);
if (!oLocation) {
var $link = oSourceControl.$ ? oSourceControl.$()
: jQuery(oSourceControl);
var iScreenWidth = jQuery(window).width();
var iOffsetLeft = $link.offset().left;
var sPlacement = sap.m.PlacementType.Left;
if (iOffsetLeft < iScreenWidth / 2) {
sPlacement = sap.m.PlacementType.Right;
var iControlWidth = $link.width();
oPopover.setOffsetX(-iControlWidth + 50);
} else {
oPopover.setOffsetX(0);
}
oPopover.setOffsetY(0);
oPopover.setPlacement(sPlacement);
}
else {
oPopover.setOffsetX(oLocation.offsetX);
oPopover.setOffsetY(oLocation.offsetY);
oPopover.setPlacement(oLocation.placement);
}
oPopover.openBy(oSourceControl);
} catch (err) {
// jQuery.sap.log.error(sap.ca.common.uilib.dialogResourceBundle.getText("YMSG_BC_ERROR",
// [err.message]));
}
},
navQVPopover : function(oConfig, oQuickoverview) {
//create target (Quickview ) view
var oView = new sap.ui.view({
viewName : "sap.ca.ui.quickoverview.Quickview",
type : sap.ui.core.mvc.ViewType.XML
});
//create target page
var oPage = new sap.m.Page({
showHeader : false,
enableScrolling : true,
content : [ oView ]
});
//set up content of popover
configureQvView(oView, oConfig, oPage, oQuickoverview);
var nav = sap.ui.getCore().byId(_QVNAVCNT);
nav.addPage(oPage);
nav.to(oPage.getId(), "show");
},
});
}());
// ///////////////////////////////////////////////
// Public Interface: sap.ca.ui.quickoverview...
// ///////////////////////////////////////////////
sap.ui.base.Object.extend("sap.ca.ui.quickoverview.Quickoverview", {
iControlType : 0, // popover
oConfig : {}, // QV Configuration
oParentCard : undefined,
oSourceControl : undefined,
// Public interface: constructor
constructor : function(oConfig, oApp, oParentCard) {
if (!oConfig)
return;
//SIL - TODO - filter/verify the incoming parameters!
this.oInitialConfig = oConfig;
// init
sap.ca.ui.quickoverview.QuickviewBase.initQVPopover(this.oParentCard);
},
// Public interface: openBy - initially called when opening the popover
openBy : function(oSourceControl, oLocation) {
if (!this.oInitialConfig)
return;
this.oSourceControl = oSourceControl;
// use ResponsivePopover
sap.ca.ui.quickoverview.QuickviewBase.openQVPopover(oSourceControl,
this.oInitialConfig, oLocation, this);
return;
},
navigateTo : function(oConfig) {
sap.ca.ui.quickoverview.QuickviewBase.navQVPopover(oConfig, this);
},
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.