branch_name
stringclasses 149
values | text
stringlengths 23
89.3M
| directory_id
stringlengths 40
40
| languages
listlengths 1
19
| num_files
int64 1
11.8k
| repo_language
stringclasses 38
values | repo_name
stringlengths 6
114
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
|
|---|---|---|---|---|---|---|---|---|
refs/heads/master
|
<file_sep># homework-0
Test for making my first repository
<file_sep>##This is just to see how it looks in the Git tab
|
9032dc8136808d80a0a429d79a2bf9033a9f4d45
|
[
"Markdown",
"R"
] | 2
|
Markdown
|
nkinachtchouk/homework-0
|
28f4fca0d1f68bb349468bf446713ef688a1674d
|
19b84a2593e0d76d637880b8a188207603e7784c
|
refs/heads/master
|
<file_sep>import { useEffect, useState } from "react";
const Title = () => {
let text = "Find your streaming family.";
const [animatedText, setAnimatedText] = useState("");
text = Array.from(text);
useEffect(() => {
const timeouts =[]
setAnimatedText("");
text.forEach((element, index) => {
const timeoutIndex = setTimeout(() => {
setAnimatedText((prev) => (prev += element));
}, 100 * index);
timeouts.push(timeoutIndex)
});
return ()=>{
timeouts.forEach((timeout)=>{
clearTimeout(timeout)
})
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return <div className="title">{animatedText}</div>;
};
export default Title;
<file_sep>import React, { useContext, useEffect, useRef, useState } from "react";
import Login from "./Login/Login";
import { Link } from "react-router-dom";
import Button from "./SignUp/Button";
import { DataContext } from "../App";
import "./LoginPage.css";
const LoginPage = () => {
const { socket, setIsSuccess, setIsError, setSuccessMessage } = useContext(
DataContext
);
const forgotPasswordCompRef = useRef();
const [forgotPasswordComp, setForgotPasswordComp] = useState(false);
const [email, setEmail] = useState("");
const handleCloseForgotPasswordComp = (e) => {
if (forgotPasswordCompRef.current) {
if (!forgotPasswordCompRef.current.contains(e.target)) {
setForgotPasswordComp(false);
}
}
};
const handleSendForgotPasswordEmail = () => {
if (email.includes("@")) {
socket.emit("forgotPasswordCode", { email });
setEmail("");
setForgotPasswordComp(false);
} else {
setIsError(true);
// setErrorMessage('')
}
};
useEffect(()=>{
socket.on("forgotPasswordCodeAnswer", ({ message, success }) => {
if (success) {
setIsSuccess(true);
setSuccessMessage(message);
} else {
setIsError(true);
}
});
return ()=>{
socket.removeAllListeners('forgotPasswordCodeAnswer')
}
},[setIsError, setIsSuccess, setSuccessMessage, socket])
return (
<div
onClick={(e) => {
handleCloseForgotPasswordComp(e);
}}
className="firstComp"
>
<div className="welcomeText">
<h1 className="streamingFamily">Streaming Family</h1>
<p>First website where you can find people to share your accounts!</p>
</div>
<div className="loginContainerFirst">
<Login turnOffBack="true" />
<div className="createAccount">
<h2>Don't have account?</h2>
<Link to="/signup">
<p>Register now for free!</p>
</Link>
<hr />
<p
className="forgotPasswordParagraph"
onClick={() => setForgotPasswordComp(true)}
>
Forgot password?
</p>
</div>
</div>
{/* ENTER EMAIL COMPONENT TO FORGOT PASSWORD */}
{forgotPasswordComp && (
<div ref={forgotPasswordCompRef} className="forgotPasswordComp">
<form autoComplete="off" className="forms">
<h2>Enter your account email</h2>
<input
autoComplete="off"
type="text"
name="email"
onChange={(e) => setEmail(e.target.value)}
value={email}
placeholder="Enter your email"
/>
<button
onClick={(e) => {
e.preventDefault();
handleSendForgotPasswordEmail();
}}
style={{ display: "none" }}
type="submit"
></button>
<div style={{ width: "fit-content" }}>
<Button
onClick={() => {
handleSendForgotPasswordEmail();
}}
style={{ color: "black", borderColor: "black" }}
text="Send Code"
/>
</div>
</form>
</div>
)}
{/* END OF FORGOT COMPONENT */}
</div>
);
};
export default LoginPage;
<file_sep>import "./Login.css";
import { useEffect, useState, useRef } from "react";
import Button2 from "@material-ui/core/Button";
import { Link, useHistory } from "react-router-dom";
import anime from "animejs/lib/anime.es.js";
import Button from "../SignUp/Button";
import Cookies from "js-cookie";
import { DataContext } from "../../App";
import { useContext } from "react";
import LinearProgress from "../Loadings/LinearProgress";
const Login = ({ turnOffBack }) => {
const {
socket,
setUserID,
setNickname,
setIsSuccess,
setSuccessMessage,
setIsError,
setErrorMessage,
setIsLoginPage,
} = useContext(DataContext);
const loginContainer = useRef();
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const history = useHistory();
const [isHover, setIsHover] = useState(false);
const [isLoading, setIsLoading] = useState(false);
const buttonStyleCreateAccount = {
marginTop: "5px",
color: "black",
borderColor: "black",
width: "fit-content",
alignSelf: "center",
};
const buttonStyleHoverCreateAccount = {
marginTop: "5px",
borderColor: "#4361ee",
width: "fit-content",
alignSelf: "center",
backgroundColor: "#4361ee",
};
const handleCookies = (ID) => {
Cookies.set("userID", ID, { expires: 3 });
};
useEffect(() => {
anime({
targets: ".loginContainer",
scale: [0, 1],
duration: 2000,
});
}, []);
useEffect(() => {
socket.on("LoginAnswer", (answer) => {
if (answer.success) {
setNickname(username);
setUsername("");
setPassword("");
setIsSuccess(true);
setSuccessMessage(answer.message);
handleCookies(answer.userID);
setUserID(answer.userID);
setTimeout(() => {
history.push("/");
}, 1);
setIsLoading(false);
setIsLoginPage(false); // TO TURN ON LOGIN UI
} else {
setErrorMessage(answer.message);
setIsError(true);
setIsLoading(false);
setPassword("");
// RED BOX SHADOW IF LOGIN DATA ARE WRONG
if (loginContainer.current) {
loginContainer.current.style.transition = "0.3s";
loginContainer.current.style.boxShadow = "0px 0px 20px red";
setTimeout(() => {
loginContainer.current.style.boxShadow = "0px 0px 20px black";
}, 1000);
}
}
});
return ()=>{
socket.removeAllListeners('LoginAnswer')
}
}, [socket, history, setErrorMessage, setNickname, username, setIsSuccess, setSuccessMessage, setUserID, setIsLoginPage, setIsError]);
const handleLogin = () => {
if (username && password) {
socket.emit("Login", {
username,
password,
});
setIsLoading(true);
} else {
setErrorMessage("Check your details again");
setIsError(true);
}
};
return (
<>
{!turnOffBack && (
<div className="header">
<Link to="/">
<Button variant="outlined" text={"Back"} />
</Link>
</div>
)}
<div className="loginContent">
<div style={{ display: "flex", flexDirection: "column" }}>
<div ref={loginContainer} className="loginContainer">
<h1>Log in to your account</h1>
<div className="login">
<form autoComplete="off" className="forms">
<input
type="text"
name="username"
value={username}
onChange={(e) => setUsername(e.target.value)}
placeholder="Username"
/>
<input
autoComplete="off"
type="<PASSWORD>"
name="password"
onChange={(e) => setPassword(e.target.value)}
value={password}
placeholder="<PASSWORD>"
/>
<button
onClick={(e) => {
e.preventDefault();
handleLogin();
}}
style={{ display: "none" }}
type="submit"
></button>
<Button2
onMouseOver={() => setIsHover(true)}
onMouseOut={() => {
setIsHover(false);
}}
variant="outlined"
style={
isHover
? buttonStyleHoverCreateAccount
: buttonStyleCreateAccount
}
onClick={handleLogin}
>
Login
</Button2>
</form>
</div>
</div>
{/* LOGIN LOADING */}
{/* MADE TO TAKE 4 PX OF HEIGHT (WITHOUT IT IS ANNOYING) */}
{isLoading ? (
<LinearProgress />
) : (
<div style={{ height: "4px" }}></div>
)}
</div>
</div>
</>
);
};
export default Login;
<file_sep>import StreamingOffer from "./StreamingOffer";
import Title from "./Title";
import { Link } from "react-router-dom";
import Button from "./SignUp/Button";
import Cookies from "js-cookie";
import {DataContext} from '../App';
import { useContext, useEffect, useState } from "react";
import ExitToAppIcon from '@material-ui/icons/ExitToApp';
import AccountBoxIcon from '@material-ui/icons/AccountBox';
import LibraryBooksIcon from '@material-ui/icons/LibraryBooks';
import { IconButton } from '@material-ui/core';
const Homepage = () => {
const {nickname, setUserID, setUserData, setNickname, socket, userID} = useContext(DataContext)
const [phoneVersion, setPhoneVersion] = useState(false)
useEffect(()=>{
socket.emit("CheckUserID", userID);
if(window.innerWidth < 520){
setPhoneVersion(true)
}
window.addEventListener('resize', ()=>{
if(window.innerWidth < 520){
setPhoneVersion(true)
}else{
setPhoneVersion(false)
}
})
// eslint-disable-next-line react-hooks/exhaustive-deps
},[])
const handleLogOut = () => {
setNickname(null);
setUserID(null);
Cookies.remove("userID");
setUserData(null)
};
return (
<>
{phoneVersion ? // PHONE VERSION
<>
<div className="header">
{!nickname ? (
<Link to="/login">
<Button text={"Login"} />
</Link>
) : (
<>
<Link to="/account">
<IconButton>
<AccountBoxIcon style={{color:'white'}}/>
</IconButton>
</Link>
<Link to="/myparties">
{/* <Button text={'My Parties'}/> */}
<IconButton>
<LibraryBooksIcon style={{color:'white'}}/>
</IconButton>
</Link>
</>
)}
{!nickname ? (
<Link to="/signup">
<Button text={"Sign Up"} />
</Link>
) : (
<IconButton>
<ExitToAppIcon style={{color:'white'}} onClick={handleLogOut}/>
</IconButton>
)}
</div>
</>
:
// DESKTOP VERSION
<div className="header">
{!nickname ? (
<Link to="/login">
<Button text={"Login"} />
</Link>
) : (
<>
<Link to="/account">
<Button text={nickname} />
</Link>
<Link to="/myparties">
<Button text={'My Parties'}/>
</Link>
</>
)}
{!nickname ? (
<Link to="/signup">
<Button text={"Sign Up"} />
</Link>
) : (
<Button text={"LogOut"} onClick={handleLogOut} />
)}
</div>
}
<div className="content">
<div className="homepage">
<Title />
<div className="streamingOffers">
<StreamingOffer name="Netflix" color="#e50914" />
<StreamingOffer name="Spotify" color="#1DB954" />
<StreamingOffer name="HBOGO" color="white" />
<StreamingOffer name="Disney+" color="#113CCF" />
</div>
</div>
</div>
</>
);
};
export default Homepage;
<file_sep>import "./Account.css"
import {Link} from 'react-router-dom';
import Button from '../SignUp/Button';
import {DataContext} from '../../App';
import { useContext, useState } from "react";
import AccountInfo from './AccountInfo';
import ChangePassword from './ChangePassword';
import ChangeEmail from './ChangeEmail';
const Profile = () => {
const {userData} = useContext(DataContext)
const {name} = userData;
const [whichContent, setWhichContent] = useState('Account')
const handleSetRightPanel = (e)=> {
// console.log(e.target);
if(e.target.className === "leftPanelItem"){
setWhichContent(e.target.textContent)
}
}
return (
<>
<div className="header">
<Link to="/">
<Button variant="outlined" text={"Back"} />
</Link>
</div>
<div className="accountContent">
<h1>Hello, {name}</h1>
<div className="account">
<div onClick={(e)=>{handleSetRightPanel(e)}} className="leftPanel">
<p className="leftPanelItem">Account</p>
<p className="leftPanelItem">Change Password</p>
<p className="leftPanelItem">Change Email</p>
</div>
<div className="rightPanel">
{whichContent === "Account" && <AccountInfo/>}
{whichContent === "Change Password" && <ChangePassword/>}
{whichContent === "Change Email" && <ChangeEmail/>}
</div>
</div>
</div>
</>
);
}
export default Profile;
<file_sep>import IconButton from "@material-ui/core/IconButton";
import AddIcon from "@material-ui/icons/Add";
import { useRef, useState, useContext } from "react";
import {DataContext} from "../App"
import "./Party.css";
const Party = ({ name, users, maxUsers, color,dateCreated,creator,partyID, text, join }) => {
const [isHovered, setIsHovered] = useState();
const {userID, socket, setIsError, setErrorMessage} = useContext(DataContext)
const hoverStyle = {
boxShadow: `0px 0px 20px ${color}`,
borderColor: color,
};
const style = {};
const joinButton = useRef()
const joinParty = () =>{
const partyID = joinButton.current.dataset.id
if(userID && partyID){
socket.emit('joinParty', {userID, partyID})
}else{
setIsError(true)
setErrorMessage('Please login!')
}
}
return (
<div
className="party"
style={isHovered ? hoverStyle : style}
onMouseOver={() => setIsHovered(true)}
onMouseLeave={() => setIsHovered(false)}
>
<h1>{name}</h1>
{/* MADE FOR MYPARTIES WITH OUT + BUTTON */}
{join && <div
style={{display:'flex', flexDirection:'column', width:'fit-content', alignSelf:'center'}}
>
<IconButton
onClick={joinParty}
data-id={partyID}
ref={joinButton}
style={{ color: "white" }}>
<AddIcon style={{ color: "white", fontSize: "50px" }} />
</IconButton>
JOIN
</div>}
<h2>
{text}
</h2>
<span>Users: {users.length}/{maxUsers}</span>
<span>Created: {dateCreated}</span>
<span>Created by: {creator}</span>
</div>
);
};
export default Party;
<file_sep>import { useEffect, useState } from "react";
import Button from "../SignUp/Button";
import "./ChangePassword.css";
import { DataContext } from "../../App";
import { useContext } from "react";
const ChangePassowrd = () => {
const {
socket,
userID,
setIsSuccess,
setSuccessMessage,
setIsError,
setErrorMessage,
} = useContext(DataContext);
const [oldPassword, setOldPassword] = useState("");
const [newPassword, setNewPassword] = useState("");
const [code, setCode] = useState("");
const [changePasswordClicked, setChangePasswordClicked] = useState(false)
const handleChangePassword = (e) => {
e.preventDefault();
if (userID && oldPassword && newPassword && code) {
socket.emit("changePassword", { userID, oldPassword, newPassword, code });
} else {
setIsError(true);
setErrorMessage("Check it one more time");
}
};
// REQUEST TO GENERATE CODE TO CHANGE PASSWORD
const changePasswordCode = () =>{
socket.emit('changePasswordCode', {userID})
setChangePasswordClicked(true)
}
useEffect(()=>{
socket.on('changePasswordCodeAnswer', ({message, success})=>{
if(success){
setIsSuccess(success)
setSuccessMessage(message)
}
})
socket.on("changePasswordAnswer", ({ message, success }) => {
if (success) {
setIsSuccess(success);
setSuccessMessage(message);
setOldPassword("");
setNewPassword("");
setCode('')
} else {
setIsError(true);
setErrorMessage(message);
}
});
return ()=>{
socket.removeAllListeners('changePasswordAnswer')
socket.removeAllListeners('changePasswordCodeAnswer')
}
},[setErrorMessage, setIsError, setIsSuccess, setSuccessMessage, socket])
const divStyle = { width: "fit-content", height:'fit-content', alignSelf:'center', padding:'15px 20px',backgroundColor:'transparent' }
return (
<>
<div className="changePassword">
<h2>CHANGE PASSWORD</h2>
{changePasswordClicked ?
<form>
<input
type="password"
value={oldPassword}
onChange={(e) => {
setOldPassword(e.target.value);
}}
placeholder="Old password"
/>
<input
type="password"
value={newPassword}
onChange={(e) => {
setNewPassword(e.target.value);
}}
placeholder="New password"
/>
<input
type="text"
value={code}
onChange={(e) => {
setCode(e.target.value);
}}
placeholder="Code from email"
/>
<div style={{ width: "fit-content"}}>
<Button
onClick={handleChangePassword}
style={{width:'100%'}}
text='Change password'/>
<button
style={{ display: "none" }}
onClick={handleChangePassword}
type="submit"
></button>
</div>
</form>
:
<div style={divStyle}>
<Button text={'Send code to email!'} onClick={changePasswordCode}/>
</div>
}
</div>
</>
);
};
export default ChangePassowrd;
<file_sep>import { useEffect, useState } from "react";
import Button from "../SignUp/Button";
import "./ChangeEmail.css";
import { DataContext } from "../../App";
import { useContext } from "react";
const ChangePassowrd = () => {
const {
socket,
userID,
setIsSuccess,
setSuccessMessage,
setIsError,
setErrorMessage,
} = useContext(DataContext);
const [newEmail, setNewEmail] = useState("");
const [code, setCode] = useState("");
const [changeEmailClicked, setChangeEmailClicked] = useState(false)
const handleChangeEmail = (e) => {
e.preventDefault();
if (userID && newEmail && code) {
if(newEmail.includes('@')){
socket.emit("changeEmail", { userID, newEmail, code });
} else{
setIsError(true)
setErrorMessage('Check your new email!')
}
} else {
setIsError(true);
setErrorMessage("Check it one more time");
}
};
// REQUEST TO GENERATE CODE TO CHANGE EMAIL
const changeEmailCode = () =>{
socket.emit('changeEmailCode', {userID})
setChangeEmailClicked(true)
}
useEffect(()=>{
socket.on('changeEmailCodeAnswer', ({message, success})=>{
if(success){
setIsSuccess(success)
setSuccessMessage(message)
}
})
socket.on("changeEmailAnswer", ({ message, success }) => {
if (success) {
setIsSuccess(success);
setSuccessMessage(message);
setNewEmail("");
setCode('')
} else {
setIsError(true);
setErrorMessage(message);
}
});
return ()=>{
socket.removeAllListeners('changeEmailCodeAnswer')
socket.removeAllListeners('changeEmailAnswer')
}
},[setErrorMessage, setIsError, setIsSuccess, setSuccessMessage, socket])
const divStyle = { width: "fit-content", height:'fit-content', alignSelf:'center', padding:'15px 20px',backgroundColor:'transparent' }
return (
<>
<div className="changeEmail">
<h2>CHANGE EMAIL</h2>
{changeEmailClicked ?
<form>
<input
type="text"
value={newEmail}
onChange={(e) => {
setNewEmail(e.target.value);
}}
placeholder="New email"
/>
<input
type="text"
value={code}
onChange={(e) => {
setCode(e.target.value);
}}
placeholder="Code from email"
/>
<div style={{ width: "fit-content" }}>
<Button
onClick={handleChangeEmail}
style={{width:'100%'}}
text='Change password'/>
<button
style={{ display: "none" }}
onClick={handleChangeEmail}
type="submit"
></button>
</div>
</form>
:
<div style={divStyle}>
<Button text={'Send code to email!'} onClick={changeEmailCode}/>
</div>
}
</div>
</>
);
};
export default ChangePassowrd;
<file_sep>import "./App.css";
import io from "socket.io-client";
import Cookies from "js-cookie";
import Homepage from "./comp/Homepage";
import { Switch, Route } from "react-router-dom";
import Error from "./comp/SignUp/ErrorSnackbar";
import React, { useEffect, useState } from "react";
import SignUp from "./comp/SignUp/SignUp";
import Login from "./comp/Login/Login";
import Account from "./comp/Account/Account";
import MyParties from "./comp/MyParties/MyParties";
import ConfirmAccount from "./comp/SignUp/ConfirmAccount";
import Success from "./comp/SignUp/SuccessSnackbar";
import StreamingPlatformComp from "./comp/StreamingPlatformComp";
import PartyInfo from "./comp/MyParties/PartyInfo";
import LoginPage from "./comp/LoginPage";
import RemindPassword from "./comp/Account/RemindPassword";
const dbURL = "https://stormy-refuge-26952.herokuapp.com/";
// const socket = io("localhost:3001/");
const socket = io(dbURL);
export const DataContext = React.createContext();
function App() {
const [userID, setUserID] = useState();
const [nickname, setNickname] = useState();
const [userData, setUserData] = useState();
const [isSuccess, setIsSuccess] = useState(false);
const [successMessage, setSuccessMessage] = useState("");
const [isError, setIsError] = useState(false);
const [errorMessage, setErrorMessage] = useState("Try again!");
const [isLoginPage, setIsLoginPage] = useState(false);
useEffect(() => {
socket.on("CheckUserIDAnswer", (data) => {
setUserData(data);
setNickname(data.username);
});
return () => {
socket.removeAllListeners("CheckUserIDAnswer");
};
}, []);
useEffect(() => {
if (Cookies.get("userID")) {
setUserID(Cookies.get("userID"));
setTimeout(() => {
socket.emit("CheckUserID", userID);
}, 1);
} else {
setIsLoginPage(true);
}
}, [userID]);
const handleCreateParty = (
userID,
partyName,
text,
maxUsers,
streamingPlatform
) => {
if (userID && partyName && text && maxUsers < 6 && streamingPlatform) {
socket.emit("createParty", {
userID,
partyName,
text,
maxUsers,
streamingPlatform,
});
} else if (!userID) {
setIsError(true);
setErrorMessage("You need to login!");
} else if (maxUsers > 5) {
setIsError(true);
setErrorMessage("Party can have max 5 users");
} else {
setIsError(true);
setErrorMessage("Check it one more time");
}
};
return (
<>
<DataContext.Provider
value={{
userID,
setUserID,
nickname,
setNickname,
userData,
setUserData,
socket,
isSuccess,
setIsSuccess,
successMessage,
setSuccessMessage,
isError,
setIsError,
errorMessage,
setErrorMessage,
handleCreateParty,
setIsLoginPage,
}}
>
<div className="app">
{isLoginPage ? ( // FOR NEW USERS (LOGGED OUT)
<>
<Route path="/" exact>
<LoginPage />
</Route>
<Route path="/signup" exact>
<SignUp />
</Route>
<Route path="/remindpassword/:code">
<RemindPassword />
</Route>
</>
) : (
<Switch>
<Route path="/" exact>
<Homepage />
</Route>
<Route path="/login">
<Login />
</Route>
<Route path="/LoginPage">
<LoginPage />
</Route>
<Route path="/account">{userData && <Account />}</Route>
<Route path="/activate">
<ConfirmAccount />
</Route>
<Route path="/myparties">{userData && <MyParties />}</Route>
<Route path="/Netflix">
<StreamingPlatformComp
color="#e50914"
streamingPlatform="Netflix"
/>
</Route>
<Route path="/Spotify">
<StreamingPlatformComp
color="#1DB954"
streamingPlatform="Spotify"
/>
</Route>
<Route path="/HBOGO">
<StreamingPlatformComp
color="white"
streamingPlatform="HBOGO"
/>
</Route>
<Route path="/Disney+">
<StreamingPlatformComp
color="#113CCF"
streamingPlatform="Disney+"
/>
</Route>
<Route path="/party/:partyID" component={PartyInfo} />
</Switch>
)}
</div>
<Success />
<Error />
</DataContext.Provider>
</>
);
}
export default App;
<file_sep>import React from "react";
import PropTypes from "prop-types";
import { makeStyles } from "@material-ui/core/styles";
import Button from "../SignUp/Button";
import Avatar from "@material-ui/core/Avatar";
import List from "@material-ui/core/List";
import ListItem from "@material-ui/core/ListItem";
import ListItemAvatar from "@material-ui/core/ListItemAvatar";
import ListItemText from "@material-ui/core/ListItemText";
import DialogTitle from "@material-ui/core/DialogTitle";
import Dialog from "@material-ui/core/Dialog";
import PersonIcon from "@material-ui/icons/Person";
import { blue } from "@material-ui/core/colors";
let usersCopy;
const emails = ["<EMAIL>", "<EMAIL>"];
const useStyles = makeStyles({
avatar: {
backgroundColor: blue[100],
color: blue[600],
},
});
function SimpleDialog(props) {
const classes = useStyles();
const { onClose, selectedValue, open } = props;
const handleClose = () => {
onClose(selectedValue);
};
const handleListItemClick = (value) => {
onClose(value);
};
return (
<Dialog
className={classes.root}
style={{ color: "red" }}
onClose={handleClose}
aria-labelledby="simple-dialog-title"
open={open}
>
<DialogTitle id="simple-dialog-title">Users in the party</DialogTitle>
<List>
{usersCopy.map((user) => (
<ListItem button onClick={() => handleListItemClick(user)} key={user}>
<ListItemAvatar>
<Avatar className={classes.avatar}>
<PersonIcon />
</Avatar>
</ListItemAvatar>
<ListItemText primary={user} />
</ListItem>
))}
</List>
</Dialog>
);
}
SimpleDialog.propTypes = {
onClose: PropTypes.func.isRequired,
open: PropTypes.bool.isRequired,
selectedValue: PropTypes.string.isRequired,
};
export default function SimpleDialogDemo({ users, admin }) {
const [open, setOpen] = React.useState(false);
const [selectedValue, setSelectedValue] = React.useState(emails[1]);
usersCopy = users;
const handleClickOpen = () => {
setOpen(true);
};
const handleClose = (value) => {
setOpen(false);
setSelectedValue(value);
};
return (
<div>
{/* <Typography variant="subtitle1">Selected: {selectedValue}</Typography> */}
<Button
text="USERS"
variant="outlined"
color="primary"
onClick={handleClickOpen}
></Button>
<SimpleDialog
selectedValue={selectedValue}
open={open}
onClose={handleClose}
/>
</div>
);
}
<file_sep>import "./SignUp.css";
import { useState, useEffect } from "react";
import Button2 from "@material-ui/core/Button";
import { Link } from "react-router-dom";
import Checkbox from "./Checkbox";
import anime from "animejs/lib/anime.es.js";
import Button from "./Button";
import { useHistory } from "react-router-dom";
import {DataContext} from '../../App';
import { useContext } from "react";
import Cookies from 'js-cookie';
const SignUp = () => {
const {socket, setIsSuccess, setSuccessMessage, setUserID, setIsError, setErrorMessage} = useContext(DataContext)
const [name, setName] = useState('');
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [checkPassword, setCheckPassword] = useState('')
const [email, setEmail] = useState('');
const [checked, setChecked] = useState(false);
const history = useHistory();
const [isHover, setIsHover] = useState(false);
const buttonStyleCreateAccount = {
marginTop: "5px",
color: "black",
borderColor: "black",
width: "fit-content",
alignSelf: "center",
};
const buttonStyleHoverCreateAccount = {
marginTop: "5px",
borderColor: "#4361ee",
width: "fit-content",
alignSelf: "center",
backgroundColor: "#4361ee",
};
useEffect(() => {
anime({
targets: ".signInContainer",
scale: [0, 1],
duration: 2000,
});
}, []);
const handleSignUp = () => {
if (name && username && password && email && checkPassword) {
if (!email.includes("@")) {
setErrorMessage("Check your email");
return setIsError(true);
} else if (!checked) {
setErrorMessage("Accept everything");
return setIsError(true);
} else if (password.length < 6) {
setErrorMessage("Password is to short");
return setIsError(true);
} else if(password !== checkPassword){
setErrorMessage("Passwords are not the same");
return setIsError(true);
}
socket.emit("SignUpData", {
name,
username,
password,
email,
});
} else {
setIsError(true);
}
};
useEffect(()=>{
socket.on("SignUpAnswer", (answer) => {
if (answer.success) {
setIsSuccess(true);
setName("");
setUsername("");
setPassword("");
setEmail("");
setSuccessMessage(answer.message);
Cookies.set('userID', answer.userID, {expires: 3})
setUserID(answer.userID)
setTimeout(() => {
history.push("/");
}, 1);
} else {
setErrorMessage(answer.message);
setIsError(true);
}
});
socket.on('sendValidationCodeAnswer', ({message, success})=>{
if(success){
setSuccessMessage(message)
}else{
setErrorMessage(message)
setIsError(true)
}
})
return ()=>{
socket.removeAllListeners('SignUpAnswer')
socket.removeAllListeners('sendValidationCodeAnswer')
}
},[history, setErrorMessage, setIsError, setIsSuccess, setSuccessMessage, setUserID, socket])
return (
<>
<div className="header">
<Link to="/">
<Button variant="outlined" text={"Back"} />
</Link>
</div>
<div className="content">
<div style={{ display: "flex", flexDirection: "column" }}>
<div className="signInContainer">
<h1>Create free account</h1>
<div className="signUp">
<form autoComplete="off" className="forms">
<input
autoComplete="nope"
type="text"
name="name"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="Name"
/>
<input
type="text"
name="username"
value={username}
onChange={(e) => setUsername(e.target.value)}
placeholder="Username"
/>
<input
autoComplete="off"
type="<PASSWORD>"
name="password"
onChange={(e) => setPassword(e.target.value)}
value={password}
placeholder="<PASSWORD>"
/>
<input
autoComplete="off"
type="password"
name="checkPassword"
onChange={(e) => setCheckPassword(e.target.value)}
value={checkPassword}
placeholder="Repeat password"
/>
<input
autoComplete="off"
type="email"
name="email"
onChange={(e) => setEmail(e.target.value)}
value={email}
placeholder="Email"
/>
<Checkbox checked={checked} setChecked={setChecked} />
<button
onClick={(e) => {
e.preventDefault();
handleSignUp();
}}
style={{ display: "none" }}
type="submit"
></button>
<Button2
onMouseOver={() => setIsHover(true)}
onMouseOut={() => {
setIsHover(false);
}}
variant="outlined"
disabled={!checked}
style={
isHover
? buttonStyleHoverCreateAccount
: buttonStyleCreateAccount
}
onClick={handleSignUp}
>
Create Account
</Button2>
</form>
</div>
</div>
</div>
</div>
</>
);
};
export default SignUp;
<file_sep>import {DataContext} from '../../App';
import { useContext } from "react";
import {Link} from 'react-router-dom';
const AccountInfo = () => {
const {userData} = useContext(DataContext)
const {name, username, email, accountCreated, isVerified} = userData;
return (
<div className="accountInfo">
<div>Name: {name}</div>
<div>Username: {username}</div>
<div>Password: ******</div>
<div>Email: {email}</div>
<div>Account created: {accountCreated}</div>
{isVerified ?
<div style={{color :'#90be6d'}}>Your account is verifed
</div>
:
<Link to="/activate">
<div style={{color:'#f94144'}}>Click here to verify your account. And check your email!</div>
</Link>
}
</div>
);
}
export default AccountInfo;<file_sep>const Message = ({time, nickname, message, myMessage}) => {
return (
<>
{myMessage ?
<div title={time} style={{alignSelf:'flex-end'}}>
<p style={{borderRadius:'20px 20px 0px 20px'}}>{message}</p>
</div>
:
<>
{/* MADE FOR USER LEFT PARTY */}
{nickname === "" ?
<div title={time}>
<p style={{color:'grey',borderColor:'grey'}}>{message}</p>
</div>
:
<div title={time}>
<p><span>{nickname} : </span> {' '}{message}</p>
</div>
}
</>
}
</>
);
}
export default Message;<file_sep>import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import Button from "@material-ui/core/Button";
const useStyles = makeStyles((theme) => ({
root: {
"& > *": {
borderColor: "white",
color: "white",
transtion: "1s",
margin: '5px',
width:'fit-content'
},
"& > *:hover": {
borderColor: "white",
boxShadow: "0px 0px 10px white",
backgroundColor: 'white',
color:'black',
width:'fit-content'
},
},
}));
export default function OutlinedButtons({ text, onClick, style }) {
const classes = useStyles();
return (
<div className={classes.root}>
<Button style={style? style:{}} variant="outlined" onClick={onClick}>
{text}
</Button>
</div>
);
}
// style={style ? style : {}}<file_sep>import "./MyParties.css"
import { Link } from "react-router-dom";
import Button from "../SignUp/Button"
import {DataContext} from "../../App"
import { useContext, useEffect, useState } from "react";
import Party from "../Party"
import MyPartiesSchema from './MyPartiesSchema';
import Loading from '../Loadings/Loading';
const MyParties = () => {
const {userData,socket} = useContext(DataContext)
const [myPartiesData, setMyPartiesData] = useState([])
useEffect(()=>{
socket.emit('getMyParties', userData.myParties)
return ()=>{
setMyPartiesData([])
}
// eslint-disable-next-line react-hooks/exhaustive-deps
},[])
useEffect(()=>{
socket.on('getMyPartiesAnswer', (partiesAnswer)=>{
setMyPartiesData(partiesAnswer)
})
return ()=>{
socket.removeAllListeners('getMyPartiesAnswer')
}
},[socket])
// sorting Parties
let netflixParties = [], spotifyParties=[], hbogoParties=[], disneyParties=[];
myPartiesData.forEach((party)=>{
switch (party.streamingPlatform) {
case 'Netflix':
netflixParties.push(party)
break;
case 'Spotify':
spotifyParties.push(party)
break;
case 'HBOGO':
hbogoParties.push(party)
break;
case 'Disney+':
disneyParties.push(party)
break;
default:
console.log('streaming Party Error');
break;
}
})
netflixParties = netflixParties.map((party) => {
let color
// CHOOSE RIGTH COLOR FOR ALL PLATFORMS
switch (party.streamingPlatform) {
case 'Netflix':
color = "#e50914"
break;
case 'Spotify':
color = '#1DB954'
break;
case 'HBO GO':
color= 'white'
break ;
case 'Disney +':
color= '#113CCF'
break;
default:
color="white"
break;
}
return (
<Link to={`/party/${party._id}`}>
<Party
join={false}
key={party._id}
partyID={party._id}
name={party.partyName}
text={party.textContent}
users={party.users}
maxUsers={party.maxUsers}
creator={party.creatorUsername}
dateCreated={party.dateCreated}
color={color}
/>
</Link>
)});
spotifyParties = spotifyParties.map((party) => {
let color
// CHOOSE RIGTH COLOR FOR ALL PLATFORMS
switch (party.streamingPlatform) {
case 'Netflix':
color = "#e50914"
break;
case 'Spotify':
color = '#1DB954'
break;
case 'HBO GO':
color= 'white'
break ;
case 'Disney +':
color= '#113CCF'
break;
default:
color="white"
break;
}
return (
<Link to={`/party/${party._id}`}>
<Party
join={false}
key={party._id}
partyID={party._id}
name={party.partyName}
text={party.textContent}
users={party.users}
maxUsers={party.maxUsers}
creator={party.creatorUsername}
dateCreated={party.dateCreated}
color={color}
/>
</Link>
)});
hbogoParties = hbogoParties.map((party) => {
let color
// CHOOSE RIGTH COLOR FOR ALL PLATFORMS
switch (party.streamingPlatform) {
case 'Netflix':
color = "#e50914"
break;
case 'Spotify':
color = '#1DB954'
break;
case 'HBO GO':
color= 'white'
break ;
case 'Disney +':
color= '#113CCF'
break;
default:
color="white"
break;
}
return (
<Link to={`/party/${party._id}`}>
<Party
join={false}
key={party._id}
partyID={party._id}
name={party.partyName}
text={party.textContent}
users={party.users}
maxUsers={party.maxUsers}
creator={party.creatorUsername}
dateCreated={party.dateCreated}
color={color}
/>
</Link>
)});
disneyParties = disneyParties.map((party) => {
let color
// CHOOSE RIGTH COLOR FOR ALL PLATFORMS
switch (party.streamingPlatform) {
case 'Netflix':
color = "#e50914"
break;
case 'Spotify':
color = '#1DB954'
break;
case 'HBO GO':
color= 'white'
break ;
case 'Disney+':
color= '#113CCF'
break;
default:
color="white"
break;
}
return (
<Link to={`/party/${party._id}`}>
<Party
join={false}
key={party._id}
partyID={party._id}
name={party.partyName}
text={party.textContent}
users={party.users}
maxUsers={party.maxUsers}
creator={party.creatorUsername}
dateCreated={party.dateCreated}
color={color}
/>
</Link>
)});
return (
<>
<div className="header">
<Link to="/">
<Button variant="outlined" text={"Back"} />
</Link>
</div>
{myPartiesData ?
<div className="myPartiesContent">
<h1>My Parties</h1>
<div className="myParties">
<MyPartiesSchema parties={netflixParties} streamingPlatform={'Netflix'}/>
<MyPartiesSchema parties={spotifyParties} streamingPlatform={'Spotify'}/>
<MyPartiesSchema parties={hbogoParties} streamingPlatform={'HBO GO'}/>
<MyPartiesSchema parties={disneyParties} streamingPlatform={'Disney+'}/>
</div>
</div>
:
<div className="myPartiesLoading">
<Loading/>
</div>
}
</>
);
}
export default MyParties;<file_sep>import Party from "./Party";
import { Link } from "react-router-dom";
import Button from "./SignUp/Button";
import { DataContext } from "../App";
import { useContext, useEffect, useRef, useState } from "react";
import Progress from "./Progress";
import "./StreamingPlatformComp.css";
const StreamingPlatformComp = ({color, streamingPlatform}) => {
const [isCreatePartyContainer, setIsCreatePartyContainer] = useState(false);
const [text, setText] = useState('');
const [maxUsers, setMaxUsers] = useState('');
const [partiesData, setPartiesData] = useState([]);
const {
handleCreateParty,
userID,
socket,
setIsSuccess,
setIsError,
setSuccessMessage,
setErrorMessage,
nickname,
} = useContext(DataContext);
const [partyName, setPartyName] = useState(`${nickname}'s party`);
const createPartyContainer = useRef();
const handleCloseContainer = (e) => {
if (isCreatePartyContainer) {
if (!createPartyContainer.current.contains(e.target)) {
setIsCreatePartyContainer(false);
}
}
};
useEffect(() => {
socket.emit("getPartiesData", streamingPlatform);
return ()=>{
setPartiesData([])
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
useEffect(()=>{
socket.on("getParitesDataAnswer", (docs) => {
setPartiesData(docs);
});
// WHEN SOMEONE WILL ADD NEW PARTY
socket.on("newPartyAddedAnswer", ({ addedParty }) => {
if (addedParty.streamingPlatform === streamingPlatform) {
setPartiesData([...partiesData, addedParty]);
}
});
socket.on("joinPartyAnswer", ({ message, success }) => {
if (success) {
setIsSuccess(true);
setSuccessMessage(message);
} else {
setIsError(true);
setErrorMessage(message);
}
});
socket.on('updateParty', ({partyChanged})=>{
let deletedIndex;
const oldPartiesData = partiesData.filter((party, index)=>{
if(party._id === partyChanged._id){
deletedIndex = index
}
return party._id !== partyChanged._id
});
oldPartiesData.splice(deletedIndex, 0, partyChanged)
setPartiesData(oldPartiesData)
})
socket.on("createPartyAnswer", ({ message, success }) => {
if (success) {
setIsSuccess(true);
setSuccessMessage(message);
setPartyName("");
setText("");
setMaxUsers("");
setIsCreatePartyContainer(false);
} else {
setIsError(true);
setErrorMessage(message);
}
});
return ()=>{
socket.removeAllListeners('createPartyAnswer')
socket.removeAllListeners('updateParty')
socket.removeAllListeners('joinPartyAnswer')
socket.removeAllListeners('newPartyAddedAnswer')
socket.removeAllListeners('getParitesDataAnswer')
}
},[partiesData, setErrorMessage, setIsError, setIsSuccess, setSuccessMessage, socket, streamingPlatform])
const list = partiesData.map((party) => (
<Party
join={true}
key={party._id}
partyID={party._id}
name={party.partyName}
text={party.textContent}
users={party.users}
maxUsers={party.maxUsers}
creator={party.creatorUsername}
dateCreated={party.dateCreated}
color={color}
/>
));
return (
<>
<div onClick={handleCloseContainer} style={{ height: "100%" }}>
<div className="header">
<Link to="/">
<Button variant="outlined" text={"Back"} />
</Link>
</div>
<div className="streamingContent">
<div className="partiesContainer">
<h1>{streamingPlatform} Families</h1>
<Button
text={"Create own party"}
onClick={() => {
setIsCreatePartyContainer((prev) => !prev);
}}
/>
{list ? <div className="Parties">{list}</div> : <Progress />}
</div>
</div>
{isCreatePartyContainer && (
<div className="createPartyContainer" ref={createPartyContainer}>
<form>
<input
ref={createPartyContainer}
type="text"
placeholder="Party name"
onChange={(e) => setPartyName(e.target.value)}
value={partyName}
/>
<input
ref={createPartyContainer}
type="text"
placeholder="Text"
onChange={(e) => setText(e.target.value)}
value={text}
/>
<input
type="number"
style={{ width: "263px" }}
max={5}
min={1}
placeholder="How <NAME>"
onChange={(e) => setMaxUsers(e.target.value)}
value={maxUsers}
/>
<button onClick={(e)=>{
e.preventDefault()
handleCreateParty(userID, partyName, text, maxUsers,streamingPlatform)
}} style={{display:'none'}} type="submit"></button>
<Button
text="Create"
onClick={() =>
handleCreateParty(
userID,
partyName,
text,
maxUsers,
streamingPlatform
)
}
/>
</form>
</div>
)}
</div>
</>
);
};
export default StreamingPlatformComp;
<file_sep>import "./PartyInfo.css";
import { DataContext } from "../../App";
import { useParams } from "react-router-dom";
import { useContext, useEffect, useState } from "react";
import Button from "../SignUp/Button";
import { Link } from "react-router-dom";
import Loading from "../Loadings/Loading";
// import Avatar from '@material-ui/core/Avatar';
import Chat from "./Chat";
import { useHistory } from "react-router-dom";
import Dialog from "./Dialog";
const PartyInfo = (props) => {
const { partyID } = useParams();
const {
socket,
nickname,
setIsError,
setErrorMessage,
userID,
setIsSuccess,
setSuccessMessage,
} = useContext(DataContext);
const history = useHistory();
const [partyData, setPartyData] = useState();
const [message, setMessage] = useState("");
useEffect(() => {
if (partyID && nickname) {
socket.emit("getParty", { partyID, nickname });
}
}, [nickname, partyID, socket]);
useEffect(()=>{
socket.on("getPartyAnswer", ({ docs, success, message }) => {
if (success) {
setPartyData(docs);
} else {
setIsError(true);
setErrorMessage(message);
}
});
socket.on(`messageAnswer${partyID}`, (docs) => {
setPartyData(docs);
});
return ()=>{
socket.removeAllListeners('getPartyAnswer')
socket.removeAllListeners(`messageAnswer${partyID}`)
}
},[partyID, setErrorMessage, setIsError, socket])
const handleSendMessage = (e) => {
if (e) {
e.preventDefault();
}
if (message && partyID && nickname) {
socket.emit("messageSend", { message, partyID, nickname });
}
setMessage("");
};
const handleLeaveParty = () => {
socket.emit("leaveParty", { nickname, partyID, userID });
};
socket.on("leavePartyAnswer", ({ message, success }) => {
if (success) {
setIsSuccess(true);
setSuccessMessage(message);
history.push("/");
} else {
setIsError(true);
setErrorMessage("Error");
}
});
// let createUsersAvatars;
// if(partyData){
// createUsersAvatars = partyData.users.map((user, index) =>{
// return(
// <Avatar key={index} style={{color:'black', border: '1px solid white'}} title={user}>{user[0].toUpperCase()}</Avatar>
// )})
// }
return (
<>
<div className="header">
<Link to="/myParties">
<Button variant="outlined" text={"Back"} />
</Link>
</div>
{partyData ? (
<div className="partyInfoContainer">
<div className="partyInfo">
<div className="partyName">
<div className="info">
<h1>{partyData.partyName}</h1>
<span className="partyName__createdBy">
Created by: {partyData.creatorUsername} |{" "}
{partyData.dateCreated}
</span>
</div>
<div className="partyInfoButtons">
{/* <Button text={'USERS'}/> */}
<Dialog users={partyData.users} admin={partyData.admin} />
<Button onClick={handleLeaveParty} text={"LEAVE PARTY"} />
</div>
</div>
<div className="partyUsers"></div>
<div className="chatAndUsersContainer">
<div className="chatContainer">
<Chat chat={partyData.chat} />
<form>
<input
type="text"
value={message}
onChange={(e) => setMessage(e.target.value)}
placeholder="Send a message"
/>
<button
onClick={(e) => handleSendMessage(e)}
type="submit"
style={{ display: "none" }}
></button>
</form>
</div>
{/* <div className="userListContainer">
{createUsersAvatars}
</div> */}
</div>
</div>
</div>
) : (
<div className="partyInfoLoading">
<Loading />
</div>
)}
</>
);
};
export default PartyInfo;
|
7087ad0e544ff5c0809041c66c49f0c8b3a98b03
|
[
"JavaScript"
] | 17
|
JavaScript
|
Victorowsky/StreamingFamily
|
c5c9be6160ec60f0e329d0abea0a387b6198a267
|
de6d998a5d902735184cb56a63d838c7ce74cc10
|
refs/heads/master
|
<repo_name>lemonadezZ/Utopia<file_sep>/requirements.txt
backports.ssl-match-hostname==3.4.0.2
chardet==2.2.1
click==6.6
configobj==4.7.2
decorator==3.4.0
Flask==0.11.1
iniparse==0.4
IPy==0.75
itsdangerous==0.24
Jinja2==2.8
kitchen==1.1.1
langtable==0.0.31
MarkupSafe==0.23
perf==0.1
policycoreutils-default-encoding==0.1
pycurl==7.19.0
pygobject==3.14.0
pygpgme==0.3
pyliblzma==0.5.3
python-augeas==0.5.0
python-dmidecode==3.10.13
pyudev==0.15
pyxattr==0.5.1
seobject==0.1
sepolicy==1.1
six==1.9.0
slip==0.4.0
slip.dbus==0.4.0
urlgrabber==3.10
Werkzeug==0.11.11
yum-langpacks==0.4.2
yum-metadata-parser==1.1.4
<file_sep>/bin/start.sh
#!/usr/bin/bash
export FLASK_APP=run.py
python -m flask run --host=0.0.0.0
<file_sep>/README.md
### run
```
docker pull lemondezz/utopia
docker run -d -p 80:5000 lemondezz/utopia
```
<file_sep>/bin/install.sh
#!/usr/bin/bash
echo "下载wget\n";
yum install -y wget
yum install -y readline-devel pcre-devel openssl-devel gcc
wget https://openresty.org/download/openresty-1.11.2.1.tar.gz
tar -zxvf openresty-1.11.2.1.tar.gz
cd openresty-1.11.2.1
./configure
make && make install
echo "修改nginx文件\n"
#/usr/local/openresty/nginx/sbin/nginx -c /var/www/project/Utopia/nginx
wget https://bootstrap.pypa.io/get-pip.py
python get-pip.py
pip install -r requirements.txt
#
#pip install flask
<file_sep>/Dockerfile
FROM centos
MAINTAINER utopia
ENV workspace /var/www/project/Utopia
WORKDIR ${workspace}
RUN yum -y install git
RUN git clone https://github.com/lemonadezZ/Utopia.git .
RUN $workspace/bin/install.sh
EXPOSE 80 443 5000
ENTRYPOINT ["/var/www/project/Utopia/bin/start.sh" ]
<file_sep>/gulpfile.js
var gulp=require('gulp');
var coffee = require('gulp-coffee');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var imagemin = require('gulp-imagemin');
var sourcemaps = require('gulp-sourcemaps');
var del = require('del');
// 默认处理
//
gulp.task('default',function(){
gulp.run('img', 'css', 'lint', 'js', 'html');
});
gulp.task('js',function(){
});
gulp.task('css',function(){
});
gulp.task('html',function(){
});
gulp.task('img',function(){
});
gulp.task('lint',function(){
});
|
180eab977af6c6e5ac972a2b36c450cf05aff2cc
|
[
"Markdown",
"JavaScript",
"Text",
"Dockerfile",
"Shell"
] | 6
|
Text
|
lemonadezZ/Utopia
|
3a894c16d518025724e6612e1f6be6fb1a7b3389
|
ec699f8e8e1b7019443401cf36b1227b6eb829c2
|
refs/heads/main
|
<repo_name>armandosneto/DB_Master<file_sep>/index.php
<?php
require_once("config.php");
//Load an user by ID
//$user = new User();
//$user->loadById("Armando", "123456");
//echo $user;
//Load a user list
//$list = User::getList();
//echo json_encode($list);
//Load an user searching by login
//echo json_encode(User::search("teste"));
//Load a user by login and senha
//$user = new User();
//$user->login("Pedro", "567890");
//echo $user;
//Insert a user from the database
//$user = new User("Breno", "12131415");
//$user->insert();
//echo $user;
//Update a user from the database
//$user = new user();
//$user->loadById(10);
//$user->update("Armandinho", "test");
//Delete a user from the database
$user = new user();
$user->loadById(12);
$user->Delete();
echo $user->getDeslogin();
<file_sep>/Class/DB_Master.php
<?php
class DB_Master{
private $type;
private $dbname;
private $host;
private $username;
private $password;
private $conn;
public function __construct($type, $dbname, $username, $password, $host = "localhost", $transaction = false){
$this->type = $type;
$this->dbname = $dbname;
$this->host = $host;
$this->username = $username;
$this->password = $<PASSWORD>;
$this->conn = $this->connection();
if ($transaction) {
$this->conn->beginTransaction();
}
}
private function connection(){
//acessing PDO according to the correct DB type
switch ($this->type) {
case "pgsql":
$dsn = $this->type . ":host=" . $this->host . ";dbname=" . $this->dbname . ";user=" . $this->username . ";password=" . $<PASSWORD>;
return new PDO($dsn);
break;
case "mysql":
$dsn = $this->type . ":host=" . $this->host . ";dbname=" . $this->dbname;
return new PDO($dsn, $this->username, $this->password);
break;
default:
throw new Exception("DB Master doesn't works with this Database");
break;
}
}
public function action($query, array $values = array()){
$stmt = $this->conn->prepare($query);
$queryL = strtoupper($query);
foreach ($values as $key => $value) {
$this->setParam($stmt,$key, $value);
}
$stmt->execute();
//select resquests treatment
if (str_starts_with($queryL, 'SELECT') || str_starts_with($queryL, 'CALL')) {
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $results;
}
}
private function setParam($statement, $key, $value){
$statement->bindParam($key, $value);
}
public function rollback(){
$this->conn->rollback();
}
public function commit(){
$this->conn->commit();
}
}<file_sep>/example.php
<?php
require_once('config.php');
$conn = new DB_Master("mysql","dbphp8","root","","localhost", true);
//insert example
$conn->action("insert into tb_usuarios (deslogin, dessenha) values(:LOGIN, :PASSWORD)",array(
":LOGIN"=> "Teste",
":PASSWORD"=>"<PASSWORD>"
));
//rollback in this action
$conn->rollback();
//update exemple
$conn->action("update tb_usuarios set dessenha = :PASSWORD where deslogin = :LOGIN", array(
":PASSWORD"=>"<PASSWORD>",
":LOGIN"=> "Suely"
));
//commiting on DB
$conn->commit();
//select example
echo json_encode($conn->action("select * from tb_usuarios order by idusuario"));
|
537908c278c224e1f56a00867641175562c14324
|
[
"PHP"
] | 3
|
PHP
|
armandosneto/DB_Master
|
3c0f02e58deaebb5c3d3bef48083ba1273cd1060
|
cb78329e7d3634bc02496d0591622a50cb70f864
|
refs/heads/master
|
<repo_name>REinitiate/CybosTraderAutoRun<file_sep>/README.md
CybosTraderAutoRun
==================
주제 : 윈도우 매크로 동작 프로그램
기능 : 대신 사이보스 트레이더 프로그램을 자동적으로 실행 및 로그인
개발배경 :
대한민국에 대부분의 오피스 PC에 윈도우가 설치되어 있는 한, 업무상 윈도우 내의 여러가지 요소를 Algorithmic 하게 조작하는 것의 필요는 사라질리 없다. 이때 쉽게 선택할 수 있는 카드중의 하나로 AutoIt(http://www.autoitscript.com/site/) 이라는 시중의 프로그램을 사용하는 것이다. AutoIt은 아주 쉬운 언어로 작성된 스크립트를 프로그램이 읽어서 작동하는데 꽤 괜찮은 성능을 보여주었다. 그러나 1) 이유를 알 수 없는 오류가 가끔 존재하였고 2) 아주 세부적인 동작은 불가능 했으며 3) 비록 쉽지만 새로운 스크립트 언어를 배워야 하는 비용이 존재하였기 때문에 그냥 손수 매크로를 개발하기로 하였다.
목표는 매크로 동작을 기능단위로 세분화 하여 모듈을 작성하는 것이었는데, 생각보다 필요로 하는 동작의 개수는 많지 않다. 아래 기능 정도는 모두 모듈화 시켰으며, 앞으로 필요한 매크로가 존재할 때마다 기능들을 조립하여 쉽게 프로그램을 개발 할 수 있을 것이라고 생각한다.
- 프로세스 실행/종료
- 윈도우 체크(떠있는지)
- 윈도우 활성화
- 윈도우에 메시지 전달(버튼 클릭, 텍스트 입력)
- Modal Dialog Check
- 대기(동작 후 반응 체크) 기능
- 윈도우 컴포넌트의 상황 체크(라디오 버튼 체크)
- 차일드 윈도우 체크
- 마우스 이동 및 클릭
- 화면 내 픽셀 정보 체크
본인은 시스템 트레이딩 때문에 매일 아침 대신증권 사이보스 트레이더를 매번 실행시키고 로그인해야 했는데, 위의 모듈을 사용하여 자동화 처리를 쉽게 하였다. 이제 더 많은 노가다를 지울 수 있게 되었다.
Update
2014.07.03
ini 설정파일로 로그인정보를 가져오도록 변경
<file_sep>/Module.cs
using System;
using System.Drawing;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace CybosAutoLogin
{
class Automation
{
IntPtr mainWndHandler;
public void Action()
{
string id = Setting.ReadIniValueByKey(@"C:\settings\cybos.ini", "id");
string password = Setting.ReadIniValueByKey(@"C:\settings\cybos.ini", "password");
Module.KillProcess();
Module.Pause(2000);
System.Diagnostics.Process.Start(@"C:\DAISHIN\STARTER\ncStarter.exe", "/prj:cp");
Module.Pause(3000);
if (Module.CheckWindowIsExist("대신증권 CYBOS FAMILY"))
{
// 대신증권 CYBOS FAMILY 화면 존재
// 보안프로그램이 사용하지 않음으로 선택되어 있습니다.
Module.ButtonClick(Module.FindWindowByName("대신증권 CYBOS FAMILY"), 6);
};
Module.Pause(2000);
IntPtr windowHandler = Module.FindWindowByName("CYBOS Starter");
mainWndHandler = windowHandler; // 메인 윈도우 핸들러 등록 (WinEventProc에서 사용해야되기 때문)
Ut.Log("메인핸들러 : " + mainWndHandler.ToString("X8"));
if (Module.CheckVirtualBtnClicked())
{
// 모의투자 버튼 눌러져 있음.
}
else
{
// 모의투자 버튼 눌러져 있지 않음. 눌러야함.
Module.ButtonClick(mainWndHandler, 327);
}
Module.mainWndHander = mainWndHandler;
Ut.Log("메인핸들러 : " + mainWndHandler.ToString("X8"));
//IntPtr hhook = Win32.SetWinEventHook(Win32.EVENT_SYSTEM_FOREGROUND, Win32.EVENT_SYSTEM_FOREGROUND,
// IntPtr.Zero, new Win32.WinEventDelegate(Module.WinEventProc), 0, 0, Win32.WINEVENT_OUTOFCONTEXT);
Module.Pause(2000);
Module.SetTextInEdit(windowHandler, 156, id);
Module.Pause(500);
Module.SetTextInEdit(windowHandler, 157, password);
Module.Pause(500);
Module.ButtonClick(windowHandler, 203);
Module.Pause(20000);
Win32.Rect rec = Module.WindowPosisionByName(mainWndHandler);
rec.Top = rec.Top + 128 + 10;
rec.Left = rec.Left + 492 + 10;
Win32.POINT p = new Win32.POINT();
p.x = rec.Left;
p.y = rec.Top;
Win32.SetCursorPos(p.x, p.y);
Win32.SetCursorPos(p.x, p.y);
Module.Click(rec);
Module.Click(rec);
Module.Click(rec);
Ut.Log(System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle.ToString("X8"));
}
}
class Module
{
public static IntPtr mainWndHander;
bool isExecuting = false;
// FindWindow 사용을 위한 코드
// 프로세스가 실행되고 있는지 판단하는 프로그램.
public static bool CheckProcessIsRunning(string pcName)
{
bool result = false;
Process[] processes = Process.GetProcesses();
foreach (Process proc in processes)
{
if (proc.ProcessName.Equals(pcName))
{
Console.WriteLine(proc.ProcessName + " 실행중");
result = true;
}
}
return result;
}
// 윈도우가 실행되고 있는지를 판단.
public static bool CheckWindowIsExist(string windowName)
{
IntPtr intPtr = Module.FindWindowByName(windowName);
if (intPtr.Equals(IntPtr.Zero))
return false;
else
return true;
}
// 윈도우 앞으로
public static void ShowWindow(IntPtr wdwHandler)
{
Win32.ShowWindow(wdwHandler, Win32.SW_SHOWNORMAL);
}
// 버튼 클릭 하는 동작
public static void ButtonClick(IntPtr wdwHandler, int btnId)
{
IntPtr boxHwnd = Win32.GetDlgItem(wdwHandler, btnId);
HandleRef hrefHWndTarget = new HandleRef(null, boxHwnd);
Win32.SendMessage(boxHwnd, Win32.BM_CLICK, IntPtr.Zero, IntPtr.Zero);
Ut.Log(wdwHandler.ToString() + " " + btnId + " " + "클릭");
}
// 에디트 다이얼로그에 문자열 세팅하는 동작
public static void SetTextInEdit(IntPtr wdwHandler, int editId, string text)
{
IntPtr boxHwnd = Win32.GetDlgItem(wdwHandler, editId);
HandleRef hrefHWndTarget = new HandleRef(null, boxHwnd);
Win32.SendMessage(hrefHWndTarget, Win32.WM_SETTEXT, IntPtr.Zero, text);
Ut.Log(wdwHandler.ToString() + " " + editId + " " + text);
}
// 윈도우 핸들 반환하는 함수
public static IntPtr FindWindowByName(string windowName)
{
IntPtr procHandler = Win32.FindWindow(null, windowName);
if (procHandler != null && procHandler != IntPtr.Zero)
{
Ut.Log(windowName + "(" + procHandler.ToString() + ")" + " 윈도우를 찾았습니다.");
}
else
{
Ut.Log("윈도우가 실행되지 않았습니다.");
}
return procHandler;
}
// 인풋 시간만큼 대기(milliseonds)
public static void Pause(int milliseconds)
{
Ut.Log((milliseconds/1000).ToString() + "초 동안 대기");
System.Threading.Thread.Sleep(milliseconds);
return;
}
// 프로그램 킬
public static void KillProcess()
{
Process[] processList = Process.GetProcesses();
foreach (var process in processList)
{
//Ut.Log(process.ProcessName);
if (process.ProcessName.CompareTo("CpStart") == 0)
{
process.Kill();
Ut.Log("CpStart Process killed.");
}
if (process.ProcessName.CompareTo("ncStarter") == 0)
{
process.Kill();
Ut.Log("ncStarter Process killed.");
}
}
return;
}
// 윈도우 좌표를 가져온다.
public static Win32.Rect WindowPosisionByName(IntPtr wdwHandler)
{
Win32.Rect rect = new Win32.Rect();
Win32.GetWindowRect(wdwHandler, ref rect);
return rect;
}
// 모의투자 버튼이 눌려있는지를 판단.
public static bool CheckVirtualBtnClicked()
{
IntPtr windowHandler = Module.FindWindowByName("CYBOS Starter");
Win32.Rect rect = Module.WindowPosisionByName(windowHandler);
//Ut.Log("top:" + rect.Top + " left:" + rect.Left + " bottom:" + rect.Bottom + " right:" + rect.Right);
// 685, 715
// 6, 15
double argb = 0;
int counter = 0;
for (int i = 6; i < 16; i++)
{
for (int j = 685; j < 716; j++)
{
int x = rect.Left + j;
int y = rect.Top + i;
argb = argb + Win32.GetPixelColor(x, y).ToArgb();
counter++;
}
}
double avgPxl = argb / Convert.ToDouble(counter);
if (avgPxl < -9000000)
{
// avgPxl : -10287651 --> 모의투자버튼 눌러져 있음.
return true;
}
else
{
// avgPxl : -8949047 --> 모의투자버튼 눌러져 있지 않음
return false;
}
}
// 해당 좌표에 클릭 버튼
public static bool Click(Win32.Rect location)
{
Ut.Log("X : " + location.Left + " Y : " + location.Top + " 에 클릭");
Win32.mouse_event(Win32.MOUSEEVENTF_LEFTDOWN, (uint)location.Left, (uint)location.Top, 0, new IntPtr());
Win32.mouse_event(Win32.MOUSEEVENTF_LEFTUP, (uint)location.Left, (uint)location.Top, 0, new IntPtr());
return true;
}
public static void WinEventProc(IntPtr hWinEventHook, uint eventType,
IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime)
{
IntPtr foregroundWinHandle = Win32.GetForegroundWindow();
//Do something (f.e check if that is the needed window)
if (hwnd == mainWndHander)
{
Module.ButtonClick(Win32.GetForegroundWindow(), 1);
}
Ut.Log(hwnd.ToString("X8") + "\t" + Win32.GetForegroundWindow().ToString("X8") + "\t" + hWinEventHook.ToString("X8"));
}
}
public class Win32
{
// DC 관련 ***************************************************
[DllImport("user32.dll")]
public static extern IntPtr GetDC(IntPtr hwnd);
[DllImport("user32.dll")]
public static extern Int32 ReleaseDC(IntPtr hwnd, IntPtr hdc);
[DllImport("gdi32.dll")]
public static extern uint GetPixel(IntPtr hdc, int nXPos, int nYPos);
// 윈도우 좌표관련
[DllImport("user32.dll")]
public static extern bool GetWindowRect(IntPtr hwnd, ref Rect rectangle);
public struct Rect
{
public int Left { get; set; }
public int Top { get; set; }
public int Right { get; set; }
public int Bottom { get; set; }
}
// 윈도우 관련 ***********************************************
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern IntPtr FindWindow(string strClassName, string StrWindowName);
[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr FindWindowEx(IntPtr parentHandle, IntPtr childAfter, string className, string windowTitle);
[DllImport("user32.dll")]
public static extern IntPtr SetActiveWindow(IntPtr hWnd);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern void SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
public const int SW_SHOWNORMAL = 1;
[DllImport("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, int msg, int Param, string s);
[DllImport("user32.dll", SetLastError = false)]
public static extern IntPtr GetDlgItem(IntPtr hDlg, int nIDDlgItem);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
public static extern IntPtr SendMessage(HandleRef hWnd, uint Msg, IntPtr wParam, string lParam);
public const uint WM_SETTEXT = 0x000C;
// 버튼 클릭 관련 ********************************************
[DllImport("user32.dll")]
public static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);
public const int BM_CLICK = 0x00F5;
static public System.Drawing.Color GetPixelColor(int x, int y)
{
IntPtr hdc = GetDC(IntPtr.Zero);
uint pixel = GetPixel(hdc, x, y);
ReleaseDC(IntPtr.Zero, hdc);
Color color = Color.FromArgb((int)(pixel & 0x000000FF),
(int)(pixel & 0x0000FF00) >> 8,
(int)(pixel & 0x00FF0000) >> 16);
return color;
}
// 차일드 윈도우 관련 ****************************************
public delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
public static extern int GetWindowText(IntPtr hWnd, StringBuilder strText, int maxCount);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
public static extern int GetWindowTextLength(IntPtr hWnd);
[DllImport("user32.dll")]
public static extern bool EnumWindows(EnumWindowsProc enumProc, IntPtr lParam);
[DllImport("user32.dll")]
public static extern bool IsWindowVisible(IntPtr hWnd);
public static string GetWindowText(IntPtr hWnd)
{
int size = GetWindowTextLength(hWnd);
if (size++ > 0)
{
var builder = new StringBuilder(size);
GetWindowText(hWnd, builder, builder.Capacity);
return builder.ToString();
}
return String.Empty;
}
[DllImport("user32")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool EnumChildWindows(IntPtr window, EnumWindowProc callback, IntPtr i);
/// <summary>
/// Returns a list of child windows
/// </summary>
/// <param name="parent">Parent of the windows to return</param>
/// <returns>List of child windows</returns>
public static List<IntPtr> GetChildWindows(IntPtr parent)
{
List<IntPtr> result = new List<IntPtr>();
GCHandle listHandle = GCHandle.Alloc(result);
try
{
EnumWindowProc childProc = new EnumWindowProc(EnumWindow);
EnumChildWindows(parent, childProc, GCHandle.ToIntPtr(listHandle));
}
finally
{
if (listHandle.IsAllocated)
listHandle.Free();
}
return result;
}
/// <summary>
/// Callback method to be used when enumerating windows.
/// </summary>
/// <param name="handle">Handle of the next window</param>
/// <param name="pointer">Pointer to a GCHandle that holds a reference to the list to fill</param>
/// <returns>True to continue the enumeration, false to bail</returns>
private static bool EnumWindow(IntPtr handle, IntPtr pointer)
{
GCHandle gch = GCHandle.FromIntPtr(pointer);
List<IntPtr> list = gch.Target as List<IntPtr>;
if (list == null)
{
throw new InvalidCastException("GCHandle Target could not be cast as List<IntPtr>");
}
list.Add(handle);
// You can modify this to check to see if you want to cancel the operation, then return a null here
return true;
}
/// <summary>
/// Delegate for the EnumChildWindows method
/// </summary>
/// <param name="hWnd">Window handle</param>
/// <param name="parameter">Caller-defined variable; we use it for a pointer to our list</param>
/// <returns>True to continue enumerating, false to bail.</returns>
public delegate bool EnumWindowProc(IntPtr hWnd, IntPtr parameter);
public delegate void WinEventDelegate(IntPtr hWinEventHook, uint eventType, IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime);
[DllImport("user32.dll")]
public static extern IntPtr SetWinEventHook(uint eventMin, uint eventMax, IntPtr
hmodWinEventProc, WinEventDelegate lpfnWinEventProc, uint idProcess,
uint idThread, uint dwFlags);
[DllImport("user32.dll")]
public static extern bool UnhookWinEvent(IntPtr hWinEventHook);
// Constants from winuser.h
public const uint EVENT_SYSTEM_FOREGROUND = 3;
public const uint WINEVENT_OUTOFCONTEXT = 0;
//The GetForegroundWindow function returns a handle to the foreground window.
[DllImport("user32.dll")]
public static extern IntPtr GetForegroundWindow();
// 마우스 관련 ****************************************************
public const UInt32 MOUSEEVENTF_LEFTDOWN = 0x0002;
public const UInt32 MOUSEEVENTF_LEFTUP = 0x0004;
[DllImport("User32.Dll")]
public static extern long SetCursorPos(int x, int y);
[DllImport("User32.Dll")]
public static extern bool ClientToScreen(IntPtr hWnd, ref POINT point);
[StructLayout(LayoutKind.Sequential)]
public struct POINT
{
public int x;
public int y;
}
[DllImport("user32.dll")]
public static extern void mouse_event(UInt32 dwFlags, UInt32 dx, UInt32 dy, UInt32 dwData, IntPtr dwExtraInfo);
}
}<file_sep>/Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace CybosAutoLogin
{
/*
* 로그인 ID : 156
* 비밀번호 : 157
* 로그인 버튼 : 203
*/
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Automation auto = new Automation();
auto.Action();
Application.Exit();
}
private void buttonGetColor_Click(object sender, EventArgs e)
{
IntPtr windowHandler = Module.FindWindowByName("CYBOS Starter");
Win32.Rect rect = Module.WindowPosisionByName(windowHandler);
//Ut.Log("top:" + rect.Top + " left:" + rect.Left + " bottom:" + rect.Bottom + " right:" + rect.Right);
// 685, 715
// 6, 15
double argb = 0;
int counter = 0;
for(int i=6; i<16; i++)
{
for (int j = 685; j < 716; j++)
{
int x = rect.Left + j;
int y = rect.Top + i;
argb = argb + Win32.GetPixelColor(x, y).ToArgb();
counter++;
}
}
Ut.Log((argb / Convert.ToDouble(counter)).ToString());
return;
}
private void buttonBtnClick_Click(object sender, EventArgs e)
{
IntPtr windowHandler = Module.FindWindowByName("CYBOS Starter");
try
{
Convert.ToInt32(textBoxItemClick.Text);
}
catch
{
Ut.Log("아이템 번호가 이상합니다.");
}
if(textBoxItemClick.Text != "")
Module.ButtonClick(windowHandler, Convert.ToInt32(textBoxItemClick.Text));
}
private void button1_Click(object sender, EventArgs e)
{
IntPtr windowHandler = Module.FindWindowByName("CYBOS Starter");
try
{
Convert.ToInt32(textBoxItemClick.Text);
}
catch
{
Ut.Log("아이템 번호가 이상합니다.");
}
if (textBoxItemClick.Text != "")
Module.SetTextInEdit(windowHandler, Convert.ToInt32(textBoxItemClick.Text), textBox2.Text);
}
private void button2_Click(object sender, EventArgs e)
{
// 매크로 동작
//CpStart
//ncStarter
Automation automation = new Automation();
automation.Action();
}
}
}
<file_sep>/Ut.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.IO;
namespace CybosAutoLogin
{
class Ut
{
public static void Log(string text)
{
Console.Write(DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") + "\t" + text + "\n");
}
}
class Setting
{
public static Hashtable ReadIniFile(string path)
{
Hashtable result = new Hashtable();
return result;
}
public static string ReadIniValueByKey(string path, string key)
{
string result = null;
StreamReader sr = new StreamReader(path);
string line = "";
while ((line = sr.ReadLine()) != null)
{
if (line.Contains("="))
{
string[] words = line.Split('=');
if(words[0].CompareTo(key) == 0)
result = words[1];
}
}
sr.Close();
if (result == null)
{
Ut.Log(key + " 설정 정보가 없습니다!");
throw new Exception();
}
else
{
Ut.Log("ini loading " + key + " : " + result);
}
return result;
}
}
}
|
949d79c82f3ac32b9a65ce22c785f83cb2b480ac
|
[
"Markdown",
"C#"
] | 4
|
Markdown
|
REinitiate/CybosTraderAutoRun
|
b6283bd32228a756d9fb7e747d8704a44e2fa8b3
|
a63eb8fcb1d3d80276944db46d7fa3613c08b22c
|
refs/heads/master
|
<file_sep>const http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write('Hello World!');
res.end();
}).listen(process.env.NODE_PORT);
console.log(`Listening on Port: ${process.env.NODE_PORT}`)<file_sep>version: "3"
networks:
main-net:
volumes:
dbdata:
services:
traefik-proxy:
image: traefik
container_name: "traefik-proxy"
command: --api --docker # Enables the web UI and tells Træfik to listen to docker
environment:
- "DO_AUTH_TOKEN=${<PASSWORD>}"
ports:
- "80:80"
- "443:443"
networks:
- main-net
restart: always
volumes:
- "/var/run/docker.sock:/var/run/docker.sock"
- "./traefik/traefik.toml:/traefik.toml"
- "./traefik/acme.json:/acme.json"
labels:
- traefik.backend=traefik-proxy
- traefik.frontend.rule=Host:traefik.${COREDOMAIN}
- traefik.port=8080
- traefik.frontend.priority=100
nginx-main:
image: nginx:latest
container_name: "nginx-main"
networks:
- main-net
depends_on:
- traefik-proxy
restart: always
volumes:
- "./nginx/content:/usr/share/nginx/html"
- "./nginx/config/default.conf:/etc/nginx/conf.d/default.conf"
- "./nginx/logs/:/var/log/nginx/"
- "/etc/letsencrypt/:/etc/letsencrypt/"
labels:
- traefik.backend=nginx-main
## Pick one of the following
## All unclaimed traffic routed here
# - traefik.frontend.rule=HostRegexp:{alldomains:.*}
## Root domain and all unclaimed subdomains of root routed here
# - traefik.frontend.rule=HostRegexp:${COREDOMAIN}, {subdomain:[a-z0-9]+}.${COREDOMAIN}
- traefik.port=80
- traefik.frontend.priority=1
nodejs1:
image: node:latest
container_name: "nodejs1"
restart: always
command: ["npm", "run", "dostart"]
environment:
NODE_ENV: dev
NODE_PORT: ${NODE_PORT}
IS_PROD: "false"
# PGHOST: 'db-main'
# PGDATABASE: 'nodejs1'
# PGUSER: 'postgres'
# PGPASSWORD: '${<PASSWORD>}'
working_dir: /home/app
networks:
- main-net
depends_on:
- traefik-proxy
# - db-main
volumes:
- "./nodejs1:/home/app"
labels:
- traefik.backend=nodejs1
- traefik.frontend.rule=Host:node1.${COREDOMAIN}
- traefik.port=${NODE_PORT}
- traefik.frontend.priority=100
# POSTGRES DB
# db-main:
# image: postgres:latest
# container_name: "db-main"
# restart: always
# networks:
# - main-net
# environment:
# POSTGRES_PASSWORD: '${<PASSWORD>}'
# volumes:
# - "dbdata:/var/lib/postgresql/data"
# labels:
# - traefik.backend=db-main
# MONGO DB
# WIP NOT READY
# db-main:
# image: mongo
# container_name: "db-main"
# restart: always
# networks:
# - main-net
# environment:
# MONGO_INITDB_ROOT_USERNAME: root
# MONGO_INITDB_ROOT_PASSWORD: example
# volumes:
# - "dbdata:/var/lib/postgresql/data"
# labels:
# - traefik.backend=db-main
<file_sep>#!/bin/sh
cd /_prod
git pull
docker-compose restart<file_sep># DevOps Traefik Boilerplate
## Why?
This project came out of my desire to understand how to correctly use Traefik as my reverse proxy. I had tried to do the same first with nginx, but it felt like nginx really wasnt built with that use in mind. Once I decoded the Traefik syntax, everything became a breeze.
So here we are, a basic setup showing configuration options I used to get up and running. When in doubt, reference [the docs](https://docs.traefik.io).
## How?
The ideal process to start using and experimenting with this boilerplate is to clone it!
```git clone https://github.com/karnthis/dev-op-boilerplate.git```
Once you have a local copy, you will need to update the placeholders:
- `MYDOMAIN` and `SUB` in the nginx config
- `MYDOMAIN` in the traefik.toml
Additionally, you will need to copy `sample.env` to `.env` and populate it with your values. This boilerplate uses Digitial Ocean, but many others are supported. To use Digital Ocean, you can create a free account and move your DNS configuration to them. It should be a similar process for [other providers](https://docs.traefik.io/configuration/acme/#provider) as well.
|
7f4c907149053dc06cc61916d37c4f6a74c2961c
|
[
"JavaScript",
"YAML",
"Markdown",
"Shell"
] | 4
|
JavaScript
|
karnthis/dev-op-boilerplate
|
dbacb182014caae1454753ea4f3cd3e01ac8de57
|
4b7c35bc87266d07225a30d919c799c13538d7da
|
refs/heads/master
|
<file_sep>package com.automatedtest.sample.smartbearpom;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import io.cucumber.java.en.And;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
public class SmartBearpomPageSteps {
public SmartBearpomPage smartBearpomPage;
public SmartBearpomPageSteps() {
this.smartBearpomPage = new SmartBearpomPage();
}
@Given("^I navigate to smartbearpom homepage$")
public void iNavigateTo() {
this.smartBearpomPage.goToHomePage();
}
@Then("^SmartBearpom logo is displayed$")
public void SmartBearpomLogoIsDisplayed() {
this.smartBearpomPage.checkLogoDisplay();
}
@Then("^I scroll to radio button demo$")
public void iScrollToRadioButtonDemo() {
this.smartBearpomPage.scrollToRadioButtonDemo();
}
@And("^I select \"([^\"]*)\" option by value from radio button group having name$")
public void iSelectOptionByValueFromRadioButtonGroupHavingName(String name) {
this.smartBearpomPage.selectMale(name);
}
}<file_sep>package com.automatedtest.sample;
import io.cucumber.junit.CucumberOptions;
import io.cucumber.junit.Cucumber;
import org.junit.runner.RunWith;
@RunWith(Cucumber.class)
@CucumberOptions(features = {"src/test/resources/com/automatedtest/sample/citiform.feature"},
strict = false, plugin = {"pretty",
"json:target/cucumber_json_reports/CitiForm-page.json",
"html:target/CitiForm-page-html",
"junit:target/CitiForm-page-html/CitiForm-page.xml"},
glue = {"com.automatedtest.sample.infrastructure.driver",
"com.automatedtest.sample.citiform"})
public class CitiFormPageTest {
}
<file_sep>package com.automatedtest.sample.smartbearpom;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.Select;
import com.automatedtest.sample.basepage.BasePage;
public class SmartBearpomPage extends BasePage {
private static final String HOME_PAGE_URL = "https://www.seleniumeasy.com/test/basic-radiobutton-demo.html";
@FindBy(className = "cbt")
private WebElement logo;
@FindBy(xpath = "//*[@id='easycont']/div/div[2]/div[1]/div[1]")
private WebElement radioButtonDemo;
@FindBy(xpath = "//input[@name='optradio' and @value='Female']")
private WebElement male;
SmartBearpomPage() {
PageFactory.initElements(driver, this);
}
void checkLogoDisplay() {
wait.forElementToBeDisplayed(5, this.logo, "Logo");
}
public void goToHomePage() {
driver.get(HOME_PAGE_URL);
wait.forLoading(5);
}
void scrollToRadioButtonDemo() {
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].scrollIntoView();", radioButtonDemo);
}
void selectMale(String name) {
this.wait.forElementToBeDisplayed(5, this.male, "Male");
this.male.click();
this.wait.forElementToBeDisplayed(5, this.male, "Male");
}
}<file_sep>package com.automatedtest.sample.radio;
import com.automatedtest.sample.scb.ScbPage;
import io.cucumber.java.en.And;
import io.cucumber.java.en.Given;
public class RadioPageSteps {
public RadioPage radioPage;
public RadioPageSteps() {
this.radioPage = new RadioPage();
}
@Given("^I navigate to guru homepage$")
public void iNavigateTo() {
this.radioPage.goToHomePage();
}
@And("^I click option1$")
public void iForcefullyClickOption1 (){
this.radioPage.clickOption1();
}
}
<file_sep>package com.automatedtest.sample;
import io.cucumber.junit.CucumberOptions;
import io.cucumber.junit.Cucumber;
import org.junit.runner.RunWith;
@RunWith(Cucumber.class)
@CucumberOptions(features = {"src/test/resources/com/automatedtest/sample/guruflight.feature"},
strict = false, plugin = {"pretty",
"json:target/cucumber_json_reports/guruflight-page.json",
"html:target/guruflight-page-html",
"junit:target/guruflight-page-html/guruflight-page.xml"},
glue = {"com.automatedtest.sample.infrastructure.driver",
"com.automatedtest.sample.guruflight"})
public class GuruFlightPageTest {
}
<file_sep>package com.automatedtest.sample.radio;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import com.automatedtest.sample.basepage.BasePage;
public class RadioPage extends BasePage {
private static final String HOME_PAGE_URL = "http://demo.guru99.com/test/radio.html";
@FindBy(id = "vfb-7-1")
private WebElement option1;
RadioPage() {
PageFactory.initElements(driver, this);
}
public void goToHomePage() {
driver.get(HOME_PAGE_URL);
wait.forLoading(5);
}
void clickOption1() {
this.wait.forElementToBeDisplayed(5, this.option1, "option1");
this.option1.click();
}
}
<file_sep>package com.automatedtest.sample;
import io.cucumber.junit.CucumberOptions;
import io.cucumber.junit.Cucumber;
import org.junit.runner.RunWith;
@RunWith(Cucumber.class)
@CucumberOptions(features = {"src/test/resources/com/automatedtest/sample/smartbearpom.feature"},
strict = false, plugin = {"pretty",
"json:target/cucumber_json_reports/smartbearpom-page.json",
"html:target/smartbearpom-page-html",
"junit:target/smartbearpom-page-html/smartbearpom-page.xml"},
glue = {"com.automatedtest.sample.infrastructure.driver",
"com.automatedtest.sample.smartbearpom"})
public class SmartBearpomPageTest {
}
<file_sep>package com.automatedtest.sample.gurutelecom;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.Select;
import com.automatedtest.sample.basepage.BasePage;
public class GuruTelecomPage extends BasePage {
private static final String HOME_PAGE_URL = "http://demo.guru99.com/telecom/addcustomer.php";
@FindBy(className = "logo")
private WebElement logo;
@FindBy(xpath = "//label[contains(.,'Done')]")
private WebElement done;
@FindBy(id = "fname")
private WebElement firstName;
@FindBy(id = "lname")
private WebElement lastName;
@FindBy(name = "emailid")
private WebElement email;
@FindBy(xpath = "//textarea[@id='message']")
private WebElement address;
@FindBy(xpath = "//input[@id='telephoneno']")
private WebElement number;
@FindBy(xpath = "//input[@name='submit']")
private WebElement submit;
GuruTelecomPage() {
PageFactory.initElements(driver, this);
}
public void goToHomePage() {
driver.get(HOME_PAGE_URL);
wait.forLoading(5);
}
void checkLogoDisplay() {
wait.forElementToBeDisplayed(5, this.logo, "Logo");
}
void clickDone() {
this.wait.forElementToBeDisplayed(5, this.done, "Done");
this.done.click();
}
void enterFirstName(String name) {
this.wait.forElementToBeDisplayed(5, this.firstName, "Name");
this.firstName.sendKeys(name);
}
void enterLastName(String name) {
this.wait.forElementToBeDisplayed(5, this.lastName, "Name");
this.lastName.sendKeys(name);
}
void enterEmail(String email) {
this.wait.forElementToBeDisplayed(5, this.email, "Email");
this.email.sendKeys(email);
}
void enterAddress(String address) {
this.wait.forElementToBeDisplayed(5, this.address, "Address");
this.address.sendKeys(address);
}
void enterNumber(String number) {
this.wait.forElementToBeDisplayed(5, this.number, "Number");
this.number.sendKeys(number);
}
void clickSubmit() {
this.wait.forElementToBeDisplayed(5, this.submit, "Submit");
this.submit.click();
}
}
<file_sep>package com.automatedtest.sample.yahoo;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.ExpectedConditions;
import com.automatedtest.sample.basepage.BasePage;
public class YahooPage extends BasePage {
private static final String HOME_PAGE_URL = "https://sg.yahoo.com/";
@FindBy(xpath = "//*[@id=\"ybar-logo\"]/img[1]")
private WebElement logo;
@FindBy(id = "ybar-sbq")
private WebElement searchInput;
YahooPage() {
PageFactory.initElements(driver, this);
}
void checkLogoDisplay() {
wait.forElementToBeDisplayed(5, this.logo, "Logo");
}
void checkSearchBarDisplay() {
wait.forElementToBeDisplayed(10, this.searchInput, "Search Bracket");
}
public void goToHomePage() {
driver.get(HOME_PAGE_URL);
wait.forLoading(5);
}
void searchFor(String searchValue) {
this.searchInput.sendKeys(searchValue);
this.searchInput.sendKeys(Keys.ENTER);
}
}
<file_sep>package com.automatedtest.sample;
import io.cucumber.junit.CucumberOptions;
import io.cucumber.junit.Cucumber;
import org.junit.runner.RunWith;
@RunWith(Cucumber.class)
@CucumberOptions(features = {"src/test/resources/com/automatedtest/sample/gurutelecom.feature"},
strict = false, plugin = {"pretty",
"json:target/cucumber_json_reports/guruTelecom-page.json",
"html:target/guruTelecom-page-html",
"junit:target/guruTelecom-page-html/guruTelecom-page.xml"},
glue = {"com.automatedtest.sample.infrastructure.driver",
"com.automatedtest.sample.gurutelecom"})
public class guruTelecomPageTest {
}
<file_sep>package com.automatedtest.sample.yahoo;
import io.cucumber.java.en.And;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
public class YahooPageSteps {
public YahooPage yahooPage;
public YahooPageSteps() {
this.yahooPage = new YahooPage();
}
@Given("^A user navigates to yahoo page$")
public void aUserNavigatesToYahooPage() {
this.yahooPage.goToHomePage();
}
@Then("^Yahoo logo is displayed$")
public void yahooLogoIsDisplayed() {
this.yahooPage.checkLogoDisplay();
}
@And("^yahoo search bar is displayed$")
public void yahooSearchBarIsDisplayed() {
this.yahooPage.checkSearchBarDisplay();
}
@When("^a user searches for \"([^\"]*)\"$")
public void aUserSearchesFor(String searchValue) {
this.yahooPage.searchFor(searchValue);
}
}
|
4a0bfc51841a2152c002a6a6c6969c19fc268b13
|
[
"Java"
] | 11
|
Java
|
rohitsitani/cucumber-java-selenium-webdriver-example
|
f8d1477b24683aa87a68066b4e5021949c6b8b3b
|
744e0e13af71cb57906b12d9936cc69799d54248
|
refs/heads/master
|
<repo_name>galmax1984/angular-counter<file_sep>/src/app/counter/counter.component.ts
import { Component, OnInit } from '@angular/core';
import { GameSettingsService } from '../service/game-settings.service';
import { GameSettings } from '../models/game-settings';
import {StateMachine, StateEvent} from 'angular2-state-machine/core';
export enum By {Left = 0, Right = 1}
@Component({
selector: 'app-counter',
templateUrl: './counter.component.html',
styleUrls: ['./counter.component.css'],
providers: [GameSettingsService]
})
export class CounterComponent implements OnInit {
public gameSettings: GameSettings = new GameSettings();
public CurrentServe: By = By.Left;
public leftPlayerPoints = 0;
public rightPlayerPoints = 0;
public leftPlayerSets = 0;
public rightPlayerSets = 0;
private setWonFlag = false;
constructor(private gameSettingsService: GameSettingsService) {
gameSettingsService.getSettings('TableTennisDefault')
.subscribe(x => {
console.log(x);
if (x) {
this.gameSettings = x;
}
});
console.log(this.gameSettings);
}
ngOnInit() {
}
pointWon(player: By) {
if (this.setWonFlag) {
this.resetCounters();
return;
}
switch (player) {
case By.Left: {
this.leftPlayerPoints ++;
break;
}
default: {
this.rightPlayerPoints ++;
}
}
if (!this.canScore(player)) {
this.setWon(player);
}
}
setWon(player: By) {
this.setWonFlag = true;
switch (player) {
case By.Left: {
this.leftPlayerSets ++;
break;
}
default: {
this.rightPlayerSets ++;
}
}
this.isMatchWon(player);
}
resetCounters() {
this.setWonFlag = false;
this.leftPlayerPoints = 0;
this.rightPlayerPoints = 0;
}
canScore(player: By): boolean {
return (((this.getScore(player) < this.gameSettings.NumberOfPointsPerSet)
&& (this.getScore(player) <= this.gameSettings.DeuceStartingPoint)) ||
(Math.abs(this.getScore(By.Left) - this.getScore(By.Right)) <= 1
&& (this.getScore(player) > this.gameSettings.DeuceStartingPoint)));
}
isMatchWon(player: By): boolean {
const quotient = Math.floor(this.gameSettings.NumberOfSetsPerMatch / 2);
console.log(quotient);
return this.getSetsScore(player) > quotient;
}
getSetsScore(player: By): number {
switch (player) {
case By.Left: {
return this.leftPlayerSets;
}
default: {
return this.rightPlayerSets;
}
}
}
getScore(player: By): number {
switch (player) {
case By.Left: {
return this.leftPlayerPoints;
}
default: {
return this.rightPlayerPoints;
}
}
}
}
<file_sep>/src/app/counter/counter.component.html
<section class="container">
<div class="left-half" (click)="pointWon(0)">
<article>
<h1>{{this.leftPlayerPoints}}</h1>
</article>
</div>
<div class="right-half" (click)="pointWon(1)">
<article>
<h1>{{this.rightPlayerPoints}}</h1>
</article>
<!-- <div class="alert">
<i class="material-icons">control_point</i><p>SET POINT</p>
</div> -->
</div>
<div class="set-counter">
<h2>{{this.leftPlayerSets}}</h2>
</div>
<div class="set-counter right">
<h2>{{this.rightPlayerSets}}</h2>
</div>
</section>
<file_sep>/src/app/models/game-settings.ts
export class GameSettings {
public Name = 'TableTennisDefault';
public NumberOfPointsPerSet = 11;
public NumberOfSetsPerMatch = 5;
public DeuceStartingPoint = 10;
public NumberOfServesInARow = 2;
}
<file_sep>/src/app/service/game-settings.service.ts
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { ApiService } from './api.service';
import { GameSettings } from '../models/game-settings';
import { map, filter, catchError, mergeMap } from 'rxjs/operators';
@Injectable()
export class GameSettingsService {
constructor(private api: ApiService) { }
getSettings(settingsName: string): Observable<GameSettings> {
let result = this.api
.getGameSettings()
.pipe(
map(x => {
result = x.filter(s => s.Name === settingsName)[0];
console.log(result);
return result;
}));
return result;
}
}
<file_sep>/src/app/service/api.service.ts
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { GameSettings } from '../models/game-settings';
import { Observable } from 'rxjs';
import { map, filter, catchError, mergeMap } from 'rxjs/operators';
import 'rxjs/add/operator/map';
@Injectable()
export class ApiService {
private rootApi = 'http://5b1e84764d4fc00014b07de3.mockapi.io/api/';
constructor(private http: Http) { }
getGameSettings(): Observable<GameSettings[]> {
return this.get<GameSettings[]>('gamesettings');
}
private get<T>(url: string, parameters?: any): Observable<T> {
const search = new URLSearchParams();
return this.http
.get(this.rootApi + url, {params: search})
.pipe(map(response => response.json() as T));
}
}
|
04b252eca591d0517e73eb43b7f94b7f484511d3
|
[
"TypeScript",
"HTML"
] | 5
|
TypeScript
|
galmax1984/angular-counter
|
160174a44e8a0707fe3f8b6c1fe9651ddf678347
|
2427814926cab83838e88601a9f9d70af9a86c91
|
refs/heads/master
|
<file_sep>package main
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
//"io"
"io/ioutil"
"log"
"net/http"
"os"
"strings"
"time"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
dockerclient "github.com/docker/docker/client"
)
var environment = os.Getenv("ENVIRONMENT_NAME")
var baseUrl = os.Getenv("BASE_URL")
var baseimagename = "frikky/shuffle"
var sleepTime = 2
type Condition struct {
AppName string `json:"app_name"`
AppVersion string `json:"app_version"`
Conditional string `json:"conditional"`
Errors []string `json:"errors"`
ID string `json:"id"`
IsValid bool `json:"is_valid"`
Label string `json:"label"`
Name string `json:"name"`
Position struct {
X float64 `json:"x"`
Y float64 `json:"y"`
} `json:"position"`
}
type User struct {
Username string `datastore:"Username"`
Password string `datastore:"password,noindex"`
Session string `datastore:"session,noindex"`
Verified bool `datastore:"verified,noindex"`
ApiKey string `datastore:"apikey,noindex"`
Id string `datastore:"id" json:"id"`
Orgs string `datastore:"orgs" json:"orgs"`
}
type Org struct {
Name string `json:"name"`
Org string `json:"org"`
Users []User `json:"users"`
Id string `json:"id"`
}
// FIXME: Generate a callback authentication ID?
type WorkflowExecution struct {
Type string `json:"type"`
Status string `json:"status"`
ExecutionId string `json:"execution_id"`
ExecutionArgument string `json:"execution_argument"`
WorkflowId string `json:"workflow_id"`
LastNode string `json:"last_node"`
Authorization string `json:"authorization"`
Result string `json:"result"`
StartedAt int64 `json:"started_at"`
CompletedAt int64 `json:"completed_at"`
ProjectId string `json:"project_id"`
Locations []string `json:"locations"`
Workflow Workflow `json:"workflow"`
Results []ActionResult `json:"results"`
}
// Added environment for location to execute
type Action struct {
AppName string `json:"app_name" datastore:"app_name"`
AppVersion string `json:"app_version" datastore:"app_version"`
Errors []string `json:"errors" datastore:"errors"`
ID string `json:"id" datastore:"id"`
IsValid bool `json:"is_valid" datastore:"is_valid"`
IsStartNode bool `json:"isStartNode" datastore:"isStartNode"`
Label string `json:"label" datastore:"label"`
Environment string `json:"environment" datastore:"environment"`
Name string `json:"name" datastore:"name"`
Parameters []WorkflowAppActionParameter `json:"parameters" datastore: "parameters"`
Position struct {
X float64 `json:"x" datastore:"x"`
Y float64 `json:"y" datastore:"y"`
} `json:"position"`
Priority int `json:"priority" datastore:"priority"`
}
type Branch struct {
DestinationID string `json:"destination_id" datastore:"destination_id"`
ID string `json:"id" datastore:"id"`
SourceID string `json:"source_id" datastore:"source_id"`
HasError bool `json:"has_errors" datastore: "has_errors"`
}
type Schedule struct {
Name string `json:"name" datastore:"name"`
Frequency string `json:"frequency" datastore:"frequency"`
ExecutionArgument string `json:"execution_argument" datastore:"execution_argument"`
Id string `json:"id" datastore:"id"`
}
type Trigger struct {
AppName string `json:"app_name" datastore:"app_name"`
Status string `json:"status" datastore:"status"`
AppVersion string `json:"app_version" datastore:"app_version"`
Errors []string `json:"errors" datastore:"errors"`
ID string `json:"id" datastore:"id"`
IsValid bool `json:"is_valid" datastore:"is_valid"`
IsStartNode bool `json:"isStartNode" datastore:"isStartNode"`
Label string `json:"label" datastore:"label"`
SmallImage string `json:"small_image" datastore:"small_image,noindex" required:false yaml:"small_image"`
LargeImage string `json:"large_image" datastore:"large_image,noindex" yaml:"large_image" required:false`
Environment string `json:"environment" datastore:"environment"`
TriggerType string `json:"trigger_type" datastore:"trigger_type"`
Name string `json:"name" datastore:"name"`
Parameters []WorkflowAppActionParameter `json:"parameters" datastore: "parameters"`
Position struct {
X float64 `json:"x" datastore:"x"`
Y float64 `json:"y" datastore:"y"`
} `json:"position"`
Priority int `json:"priority" datastore:"priority"`
}
type Workflow struct {
Actions []Action `json:"actions" datastore:"actions"`
Branches []Branch `json:"branches" datastore:"branches"`
Triggers []Trigger `json:"triggers" datastore:"triggers"`
Schedules []Schedule `json:"schedules" datastore:"schedules"`
Errors []string `json:"errors,omitempty" datastore:"errors"`
Tags []string `json:"tags,omitempty" datastore:"tags"`
ID string `json:"id" datastore:"id"`
IsValid bool `json:"is_valid" datastore:"is_valid"`
Name string `json:"name" datastore:"name"`
Description string `json:"description" datastore:"description"`
Start string `json:"start" datastore:"start"`
Owner string `json:"owner" datastore:"owner"`
Sharing string `json:"sharing" datastore:"sharing"`
Org []Org `json:"org,omitempty" datastore:"org"`
ExecutingOrg Org `json:"execution_org,omitempty" datastore:"execution_org"`
WorkflowVariables []struct {
Description string `json:"description" datastore:"description"`
ID string `json:"id" datastore:"id"`
Name string `json:"name" datastore:"name"`
Value string `json:"value" datastore:"value"`
} `json:"workflow_variables" datastore:"workflow_variables"`
}
type ActionResult struct {
Action Action `json:"action" datastore:"action"`
ExecutionId string `json:"execution_id" datastore:"execution_id"`
Authorization string `json:"authorization" datastore:"authorization"`
Result string `json:"result" datastore:"result"`
StartedAt int64 `json:"started_at" datastore:"started_at"`
CompletedAt int64 `json:"completed_at" datastore:"completed_at"`
Status string `json:"status" datastore:"status"`
}
type WorkflowApp struct {
Name string `json:"name" yaml:"name" required:true datastore:"name"`
IsValid bool `json:"is_valid" yaml:"is_valid" required:true datastore:"is_valid"`
ID string `json:"id" yaml:"id" required:false datastore:"id"`
Link string `json:"link" yaml:"link" required:false datastore:"link"`
AppVersion string `json:"app_version" yaml:"app_version" required:true datastore:"app_version"`
Description string `json:"description" datastore:"description" required:false yaml:"description"`
Environment string `json:"environment" datastore:"environment" required:true yaml:"environment"`
ContactInfo struct {
Name string `json:"name" datastore:"name" yaml:"name"`
Url string `json:"url" datastore:"url" yaml:"url"`
} `json:"contact_info" datastore:"contact_info" yaml:"contact_info" required:false`
Actions []WorkflowAppAction `json:"actions" yaml:"actions" required:true datastore:"actions"`
}
// Name = current field
// action_field is the field that it's set to
// value, if Variant = ACTION_RESULT = the second field thingy, which will be
type WorkflowAppActionParameter struct {
Description string `json:"description" datastore:"description"`
ID string `json:"id" datastore:"id"`
Name string `json:"name" datastore:"name"`
Value string `json:"value" datastore:"value"`
ActionField string `json:"action_field" datastore:"action_field"`
Variant string `json:"variant", datastore:"variant"`
Required bool `json:"required" datastore:"required"`
Schema struct {
Type string `json:"type" datastore:"type"`
} `json:"schema"`
}
type WorkflowAppAction struct {
Description string `json:"description" datastore:"description"`
ID string `json:"id" datastore:"id"`
Name string `json:"name" datastore:"name"`
NodeType string `json:"node_type" datastore:"node_type"`
Environment string `json:"environment" datastore:"environment"`
Parameters []WorkflowAppActionParameter `json:"parameters" datastore: "parameters"`
Returns struct {
Description string `json:"description" datastore:"returns"`
ID string `json:"id" datastore:"id"`
Schema struct {
Type string `json:"type" datastore:"type"`
} `json:"schema" datastore:"schema"`
} `json:"returns" datastore:"returns"`
}
// removes every container except itself (worker)
func shutdown(executionId, workflowId string) {
dockercli, err := dockerclient.NewEnvClient()
if err != nil {
log.Printf("Unable to create docker client: %s", err)
os.Exit(3)
}
containerOptions := types.ContainerListOptions{
All: true,
}
containers, err := dockercli.ContainerList(context.Background(), containerOptions)
if err != nil {
panic(err)
}
_ = containers
for _, container := range containers {
for _, name := range container.Names {
if strings.Contains(name, executionId) {
// FIXME - reinstate - not here for debugging
//err = removeContainer(container.ID)
//if err != nil {
// log.Printf("Failed removing %s before shutdown.", name)
//}
break
}
}
}
// FIXME: Add an API call to the backend
// fmt.Sprintf("AUTHORIZATION=%s", workflowExecution.Authorization),
fullUrl := fmt.Sprintf("%s/api/v1/workflows/%s/executions/%s/abort", baseUrl, workflowId, executionId)
req, err := http.NewRequest(
"GET",
fullUrl,
nil,
)
if err != nil {
log.Println("Failed building request: %s", err)
}
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Authorization", authorization)
client := &http.Client{}
_, err = client.Do(req)
if err != nil {
log.Printf("Failed abort request: %s", err)
}
log.Printf("Finished shutdown.")
os.Exit(3)
}
// Deploys the internal worker whenever something happens
func deployApp(cli *dockerclient.Client, image string, identifier string, env []string) error {
hostConfig := &container.HostConfig{
LogConfig: container.LogConfig{
Type: "json-file",
Config: map[string]string{},
},
}
config := &container.Config{
Image: image,
Env: env,
}
cont, err := cli.ContainerCreate(
context.Background(),
config,
hostConfig,
nil,
identifier,
)
if err != nil {
log.Println(err)
return err
}
cli.ContainerStart(context.Background(), cont.ID, types.ContainerStartOptions{})
fmt.Printf("\n")
log.Printf("Container %s is created", cont.ID)
return nil
}
func removeContainer(containername string) error {
ctx := context.Background()
cli, err := dockerclient.NewEnvClient()
if err != nil {
log.Printf("Unable to create docker client: %s", err)
return err
}
// FIXME - ucnomment
// containers, err := cli.ContainerList(ctx, types.ContainerListOptions{
// All: true,
// })
_ = ctx
_ = cli
//if err := cli.ContainerStop(ctx, containername, nil); err != nil {
// log.Printf("Unable to stop container %s - running removal anyway, just in case: %s", containername, err)
//}
removeOptions := types.ContainerRemoveOptions{
RemoveVolumes: true,
Force: true,
}
// FIXME - remove comments etc
_ = removeOptions
//if err := cli.ContainerRemove(ctx, containername, removeOptions); err != nil {
// log.Printf("Unable to remove container: %s", err)
//}
return nil
}
func handleExecution(client *http.Client, req *http.Request, workflowExecution WorkflowExecution) error {
// if no onprem runs (shouldn't happen, but extra check), exit
// if there are some, load the images ASAP for the app
dockercli, err := dockerclient.NewEnvClient()
if err != nil {
log.Printf("Unable to create docker client: %s", err)
shutdown(workflowExecution.ExecutionId, workflowExecution.Workflow.ID)
}
onpremApps := []string{}
startAction := workflowExecution.Workflow.Start
toExecuteOnprem := []string{}
parents := map[string][]string{}
children := map[string][]string{}
// source = parent, dest = child
// parent can have more children, child can have more parents
for _, branch := range workflowExecution.Workflow.Branches {
parents[branch.DestinationID] = append(parents[branch.DestinationID], branch.SourceID)
children[branch.SourceID] = append(children[branch.SourceID], branch.DestinationID)
}
for _, action := range workflowExecution.Workflow.Actions {
if action.Environment != environment {
continue
}
toExecuteOnprem = append(toExecuteOnprem, action.ID)
actionName := fmt.Sprintf("%s:%s_%s", baseimagename, action.AppName, action.AppVersion)
found := false
for _, app := range onpremApps {
if actionName == app {
found = true
}
}
if !found {
onpremApps = append(onpremApps, actionName)
}
}
if len(onpremApps) == 0 {
return errors.New("No apps to handle onprem")
}
pullOptions := types.ImagePullOptions{}
for _, image := range onpremApps {
log.Printf("Image: %s", image)
if strings.Contains(image, " ") {
image = strings.ReplaceAll(image, " ", "-")
}
reader, err := dockercli.ImagePull(context.Background(), image, pullOptions)
if err != nil {
log.Printf("Failed getting %s. The app is missing or some other issue", image)
//shutdown(workflowExecution.ExecutionId)
}
//io.Copy(os.Stdout, reader)
_ = reader
log.Printf("Successfully downloaded and built %s", image)
}
// Process the parents etc. How?
// while queue:
// while len(self.in_process) > 0 or len(self.parallel_in_process) > 0:
// check if its their own turn to continue
// visited = {self.start_action}
visited := []string{}
nextActions := []string{}
queueNodes := []string{}
for {
//if len(queueNodes) > 0 {
// log.Println(queueNodes)
// nextActions = queueNodes
//} else {
// nextActions := []string{}
//}
// FIXME - this might actually work, but probably not
//queueNodes = []string{}
if len(workflowExecution.Results) == 0 {
nextActions = []string{startAction}
} else {
for _, item := range workflowExecution.Results {
visited = append(visited, item.Action.ID)
nextActions = children[item.Action.ID]
// FIXME: check if nextActions items are finished?
}
}
if len(nextActions) == 0 {
log.Println("No next action. Finished?")
//shutdown(workflowExecution.ExecutionId)
}
for _, node := range nextActions {
nodeChildren := children[node]
for _, child := range nodeChildren {
if !arrayContains(queueNodes, child) {
queueNodes = append(queueNodes, child)
}
}
}
//log.Println(queueNodes)
// IF NOT VISITED && IN toExecuteOnPrem
// SKIP if it's not onprem
// FIXME: Find next node(s)
//for _, result := range workflowExecution.Results {
// log.Println(result.Status)
//}
for _, nextAction := range nextActions {
action := getAction(workflowExecution, nextAction)
// FIXME - remove this. Should always need to be valid.
//if action.IsValid == false {
// log.Printf("%#v", action)
// log.Printf("Action %s (%s) isn't valid. Exiting, BUT SHOULD CALLBACK TO SET FAILURE.", action.ID, action.Name)
// os.Exit(3)
//}
// check visited and onprem
if arrayContains(visited, nextAction) {
log.Printf("ALREADY VISITIED: %s", nextAction)
continue
}
// Not really sure how this edgecase happens.
// FIXME
// Execute, as we don't really care if env is not set? IDK
if action.Environment != environment { //&& action.Environment != "" {
log.Printf("Bad environment: %s", action.Environment)
continue
}
// check whether the parent is finished executing
//log.Printf("%s has %d parents", nextAction, len(parents[nextAction]))
continueOuter := true
if action.IsStartNode {
continueOuter = false
} else if len(parents[nextAction]) > 0 {
// FIXME - wait for parents to finishe executing
fixed := 0
for _, parent := range parents[nextAction] {
parentResult := getResult(workflowExecution, parent)
if parentResult.Status == "FINISHED" || parentResult.Status == "SUCCESS" {
fixed += 1
}
}
if fixed == len(parents[nextAction]) {
continueOuter = false
}
} else {
continueOuter = false
}
if continueOuter {
log.Printf("Parents of %s aren't finished: %s", nextAction, strings.Join(parents[nextAction], ", "))
continue
}
// get action status
actionResult := getResult(workflowExecution, nextAction)
if actionResult.Action.ID == action.ID {
log.Printf("%s already has status %s.", action.ID, actionResult.Status)
continue
} else {
log.Printf("%s:%s has no status result yet. Should execute.", action.Name, action.ID)
}
appname := action.AppName
appversion := action.AppVersion
appname = strings.Replace(appname, ".", "-", -1)
appversion = strings.Replace(appversion, ".", "-", -1)
image := fmt.Sprintf("%s:%s_%s", baseimagename, action.AppName, action.AppVersion)
if strings.Contains(image, " ") {
image = strings.ReplaceAll(image, " ", "-")
}
identifier := fmt.Sprintf("%s_%s_%s_%s", appname, appversion, action.ID, workflowExecution.ExecutionId)
if strings.Contains(identifier, " ") {
identifier = strings.ReplaceAll(identifier, " ", "-")
}
// FIXME - check whether it's running locally yet too
stats, err := dockercli.ContainerInspect(context.Background(), identifier)
if err != nil || stats.ContainerJSONBase.State.Status != "running" {
// REMOVE
if err == nil {
log.Printf("Status: %s, should kill: %s", stats.ContainerJSONBase.State.Status, identifier)
err = removeContainer(identifier)
if err != nil {
log.Printf("Error killing container: %s", err)
}
} else {
//log.Printf("WHAT TO DO HERE?: %s", err)
}
} else if stats.ContainerJSONBase.State.Status == "running" {
continue
}
if len(action.Parameters) == 0 {
action.Parameters = []WorkflowAppActionParameter{}
}
if len(action.Errors) == 0 {
action.Errors = []string{}
}
// marshal action and put it in there rofl
log.Printf("Time to execute %s with app %s:%s, function %s, env %s with %d parameters.", action.ID, action.AppName, action.AppVersion, action.Name, action.Environment, len(action.Parameters))
actionData, err := json.Marshal(action)
if err != nil {
log.Printf("Failed unmarshalling action: %s", err)
continue
}
//log.Println(string(actionData))
// FIXME - add proper FUNCTION_APIKEY from user definition
env := []string{
fmt.Sprintf("ACTION=%s", string(actionData)),
fmt.Sprintf("EXECUTIONID=%s", workflowExecution.ExecutionId),
fmt.Sprintf("FUNCTION_APIKEY=%s", "asdasd"),
fmt.Sprintf("AUTHORIZATION=%s", workflowExecution.Authorization),
fmt.Sprintf("CALLBACK_URL=%s", baseUrl),
}
err = deployApp(dockercli, image, identifier, env)
if err != nil {
log.Printf("Failed deploying %s from image %s: %s", identifier, image, err)
log.Printf("Should send status and exit the entire thing?")
//shutdown(workflowExecution.ExecutionId)
}
visited = append(visited, action.ID)
//log.Printf("%#v", action)
}
//log.Println(nextAction)
//log.Println(startAction, children[startAction])
// FIXME - new request here
// FIXME - clean up stopped (remove) containers with this execution id
newresp, err := client.Do(req)
if err != nil {
log.Printf("Failed making request: %s", err)
time.Sleep(time.Duration(sleepTime) * time.Second)
continue
}
body, err := ioutil.ReadAll(newresp.Body)
if err != nil {
log.Printf("Failed reading body: %s", err)
time.Sleep(time.Duration(sleepTime) * time.Second)
continue
}
if newresp.StatusCode != 200 {
log.Printf("Err: %s\nStatusCode: %d", string(body), newresp.StatusCode)
time.Sleep(time.Duration(sleepTime) * time.Second)
continue
}
err = json.Unmarshal(body, &workflowExecution)
if err != nil {
log.Printf("Failed workflowExecution unmarshal: %s", err)
time.Sleep(time.Duration(sleepTime) * time.Second)
continue
}
if workflowExecution.Status == "FINISHED" || workflowExecution.Status == "SUCCESS" {
log.Printf("Workflow %s is finished. Exiting worker.", workflowExecution.ExecutionId)
shutdown(workflowExecution.ExecutionId, workflowExecution.Workflow.ID)
}
log.Printf("Status: %s, Results: %d, actions: %d", workflowExecution.Status, len(workflowExecution.Results), len(workflowExecution.Workflow.Actions))
if workflowExecution.Status != "EXECUTING" {
log.Printf("Exiting as worker execution has status %s!", workflowExecution.Status)
shutdown(workflowExecution.ExecutionId, workflowExecution.Workflow.ID)
}
if len(workflowExecution.Results) == len(workflowExecution.Workflow.Actions) {
shutdownCheck := true
ctx := context.Background()
for _, result := range workflowExecution.Results {
if result.Status == "EXECUTING" {
// Cleaning up executing stuff
shutdownCheck = false
// Check status
containers, err := dockercli.ContainerList(ctx, types.ContainerListOptions{
All: true,
})
if err != nil {
log.Printf("Failed listing containers: %s", err)
continue
}
stopContainers := []string{}
removeContainers := []string{}
for _, container := range containers {
for _, name := range container.Names {
if !strings.Contains(name, result.Action.ID) {
continue
}
if container.State != "running" {
removeContainers = append(removeContainers, container.ID)
stopContainers = append(stopContainers, container.ID)
}
}
}
// FIXME - add killing of apps with same execution ID too
// FIXME - stahp
//for _, containername := range stopContainers {
// if err := dockercli.ContainerStop(ctx, containername, nil); err != nil {
// log.Printf("Unable to stop container: %s", err)
// } else {
// log.Printf("Stopped container %s", containername)
// }
//}
removeOptions := types.ContainerRemoveOptions{
RemoveVolumes: true,
Force: true,
}
_ = removeOptions
// FIXME - this
//for _, containername := range removeContainers {
// if err := dockercli.ContainerRemove(ctx, containername, removeOptions); err != nil {
// log.Printf("Unable to remove container: %s", err)
// } else {
// log.Printf("Removed container %s", containername)
// }
//}
// FIXME - send POST request to kill the container
log.Printf("Should remove (POST request) stopped containers")
//ret = requests.post("%s%s" % (self.url, stream_path), headers=headers, json=action_result)
}
}
if shutdownCheck {
log.Println("BREAKING BECAUSE RESULTS IS SAME LENGTH AS ACTIONS. SHOULD CHECK ALL RESULTS FOR WHETHER THEY'RE DONE")
shutdown(workflowExecution.ExecutionId, workflowExecution.Workflow.ID)
}
}
time.Sleep(time.Duration(sleepTime) * time.Second)
}
return nil
}
func arrayContains(visited []string, id string) bool {
found := false
for _, item := range visited {
if item == id {
found = true
}
}
return found
}
func getResult(workflowExecution WorkflowExecution, id string) ActionResult {
for _, actionResult := range workflowExecution.Results {
if actionResult.Action.ID == id {
return actionResult
}
}
return ActionResult{}
}
func getAction(workflowExecution WorkflowExecution, id string) Action {
for _, action := range workflowExecution.Workflow.Actions {
if action.ID == id {
return action
}
}
return Action{}
}
// Initial loop etc
func main() {
log.Printf("Setting up worker environment")
sleepTime := 5
client := &http.Client{}
authorization := os.Getenv("AUTHORIZATION")
executionId := os.Getenv("EXECUTIONID")
if len(authorization) == 0 {
log.Println("No AUTHORIZATION key set in env")
shutdown(executionId, "")
}
if len(executionId) == 0 {
log.Println("No EXECUTIONID key set in env")
shutdown(executionId, "")
}
// FIXME - tmp
data := fmt.Sprintf(`{"execution_id": "%s", "authorization": "%s"}`, executionId, authorization)
fullUrl := fmt.Sprintf("%s/api/v1/streams/results", baseUrl)
req, err := http.NewRequest(
"POST",
fullUrl,
bytes.NewBuffer([]byte(data)),
)
if err != nil {
log.Println("Failed making request builder")
shutdown(executionId, "")
}
for {
newresp, err := client.Do(req)
if err != nil {
log.Printf("Failed request: %s", err)
time.Sleep(time.Duration(sleepTime) * time.Second)
continue
}
body, err := ioutil.ReadAll(newresp.Body)
if err != nil {
log.Printf("Failed reading body: %s", err)
time.Sleep(time.Duration(sleepTime) * time.Second)
continue
}
if newresp.StatusCode != 200 {
log.Printf("Err: %s\nStatusCode: %d", string(body), newresp.StatusCode)
time.Sleep(time.Duration(sleepTime) * time.Second)
continue
}
var workflowExecution WorkflowExecution
err = json.Unmarshal(body, &workflowExecution)
if err != nil {
log.Printf("Failed workflowExecution unmarshal: %s", err)
time.Sleep(time.Duration(sleepTime) * time.Second)
continue
}
if workflowExecution.Status == "FINISHED" || workflowExecution.Status == "SUCCESS" {
log.Printf("Workflow %s is finished. Exiting worker.", workflowExecution.ExecutionId)
shutdown(executionId, workflowExecution.Workflow.ID)
}
if workflowExecution.Status == "EXECUTING" || workflowExecution.Status == "RUNNING" {
//log.Printf("Status: %s", workflowExecution.Status)
err = handleExecution(client, req, workflowExecution)
if err != nil {
log.Printf("Workflow %s is finished: %s", workflowExecution.ExecutionId, err)
shutdown(executionId, workflowExecution.Workflow.ID)
}
} else {
log.Printf("Workflow %s has status %s. Exiting worker.", workflowExecution.ExecutionId, workflowExecution.Status)
shutdown(executionId, workflowExecution.Workflow.ID)
}
//log.Println(string(body))
time.Sleep(time.Duration(sleepTime) * time.Second)
}
}
<file_sep># Installation guide
Installation of Shuffle is currently only available in docker.
There are four parts to the infrastructure:
* Frontend - GUI, React
* Backend - Go
* Database - Google Datastore
* Orborus - Go, controls the workers to deploy. Can be used to connect to others' setup
* Worker - Controls each workflow execution
* App_sdk - Used
## Docker
The Docker setup is done with docker-compose and is a single command to get set up.
1. Make sure you have Docker and [docker-compose](https://docs.docker.com/compose/install/) installed.
2. Run docker-compose.
```
git clone https://github.com/frikky/shuffle
cd shuffle
docker-compose up -d
```
3. Useful info:
* The server is available on http://localhost:3001 (or your servername)
* Further configuration in docker-compose.yml and .env.
* Default database location is /etc/shuffle
<file_sep>package main
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"strconv"
"strings"
"time"
"cloud.google.com/go/datastore"
"cloud.google.com/go/scheduler/apiv1"
gyaml "github.com/ghodss/yaml"
"github.com/h2non/filetype"
"github.com/satori/go.uuid"
"google.golang.org/api/cloudfunctions/v1"
schedulerpb "google.golang.org/genproto/googleapis/cloud/scheduler/v1"
"github.com/go-git/go-billy/v5"
"github.com/go-git/go-billy/v5/memfs"
"github.com/go-git/go-git/v5"
newscheduler "github.com/carlescere/scheduler"
"github.com/go-git/go-git/v5/storage/memory"
//"github.com/gorilla/websocket"
//"google.golang.org/appengine"
//"google.golang.org/appengine/memcache"
//"cloud.google.com/go/firestore"
// "google.golang.org/api/option"
)
var localBase = "http://localhost:5001"
var baseEnvironment = "onprem"
var cloudname = "cloud"
var defaultLocation = "europe-west2"
var scheduledJobs = map[string]*newscheduler.Job{}
// To test out firestore before potential merge
var shuffleTestProject = "shuffle-test-258209"
var shuffleTestPath = "./shuffle-test-258209-5a2e8d7e508a.json"
//var upgrader = websocket.Upgrader{
// ReadBufferSize: 1024,
// WriteBufferSize: 1024,
// CheckOrigin: func(r *http.Request) bool {
// return true
// },
//}
type ExecutionRequest struct {
ExecutionId string `json:"execution_id"`
ExecutionArgument string `json:"execution_argument"`
WorkflowId string `json:"workflow_id"`
Environments []string `json:"environments"`
Authorization string `json:"authorization"`
Status string `json:"status"`
Start string `json:"start"`
Type string `json:"type"`
}
type Org struct {
Name string `json:"name"`
Org string `json:"org"`
Users []User `json:"users"`
Id string `json:"id"`
}
type WorkflowApp struct {
Name string `json:"name" yaml:"name" required:true datastore:"name"`
IsValid bool `json:"is_valid" yaml:"is_valid" required:true datastore:"is_valid"`
ID string `json:"id" yaml:"id,omitempty" required:false datastore:"id"`
Link string `json:"link" yaml:"link" required:false datastore:"link,noindex"`
AppVersion string `json:"app_version" yaml:"app_version" required:true datastore:"app_version"`
Generated bool `json:"generated" yaml:"generated" required:false datastore:"generated"`
Downloaded bool `json:"downloaded" yaml:"downloaded" required:false datastore:"downloaded"`
Sharing bool `json:"sharing" yaml:"sharing" required:false datastore:"sharing"`
Verified bool `json:"verified" yaml:"verified" required:false datastore:"verified"`
Tested bool `json:"tested" yaml:"tested" required:false datastore:"tested"`
Owner string `json:"owner" datastore:"owner" yaml:"owner"`
PrivateID string `json:"private_id" yaml:"private_id" required:false datastore:"private_id"`
Description string `json:"description" datastore:"description" required:false yaml:"description"`
Environment string `json:"environment" datastore:"environment" required:true yaml:"environment"`
SmallImage string `json:"small_image" datastore:"small_image,noindex" required:false yaml:"small_image"`
LargeImage string `json:"large_image" datastore:"large_image,noindex" yaml:"large_image" required:false`
ContactInfo struct {
Name string `json:"name" datastore:"name" yaml:"name"`
Url string `json:"url" datastore:"url" yaml:"url"`
} `json:"contact_info" datastore:"contact_info" yaml:"contact_info" required:false`
Actions []WorkflowAppAction `json:"actions" yaml:"actions" required:true datastore:"actions"`
Authentication Authentication `json:"authentication" yaml:"authentication" required:false datastore:"authentication"`
}
type WorkflowAppActionParameter struct {
Description string `json:"description" datastore:"description" yaml:"description"`
ID string `json:"id" datastore:"id" yaml:"id,omitempty"`
Name string `json:"name" datastore:"name" yaml:"name"`
Example string `json:"example" datastore:"example" yaml:"example"`
Value string `json:"value" datastore:"value" yaml:"value,omitempty"`
Multiline bool `json:"multiline" datastore:"multiline" yaml:"multiline"`
ActionField string `json:"action_field" datastore:"action_field" yaml:"actionfield,omitempty"`
Variant string `json:"variant" datastore:"variant" yaml:"variant,omitempty"`
Required bool `json:"required" datastore:"required" yaml:"required"`
Schema SchemaDefinition `json:"schema" datastore:"schema" yaml:"schema"`
}
type SchemaDefinition struct {
Type string `json:"type" datastore:"type"`
}
type WorkflowAppAction struct {
Description string `json:"description" datastore:"description"`
ID string `json:"id" datastore:"id" yaml:"id,omitempty"`
Name string `json:"name" datastore:"name"`
Label string `json:"label" datastore:"label"`
NodeType string `json:"node_type" datastore:"node_type"`
Environment string `json:"environment" datastore:"environment"`
Sharing bool `json:"sharing" datastore:"sharing"`
PrivateID string `json:"private_id" datastore:"private_id"`
AppID string `json:"app_id" datastore:"app_id"`
Authentication []AuthenticationStore `json:"authentication" datastore:"authentication" yaml:"authentication,omitempty"`
Tested bool `json:"tested" datastore:"tested" yaml:"tested"`
Parameters []WorkflowAppActionParameter `json:"parameters" datastore: "parameters"`
Returns struct {
Description string `json:"description" datastore:"returns" yaml:"description,omitempty"`
ID string `json:"id" datastore:"id" yaml:"id,omitempty"`
Schema SchemaDefinition `json:"schema" datastore:"schema" yaml:"schema"`
} `json:"returns" datastore:"returns"`
}
// FIXME: Generate a callback authentication ID?
type WorkflowExecution struct {
Type string `json:"type" datastore:"type"`
Status string `json:"status" datastore:"status"`
Start string `json:"start" datastore:"start"`
ExecutionArgument string `json:"execution_argument" datastore:"execution_argument"`
ExecutionId string `json:"execution_id" datastore:"execution_id"`
WorkflowId string `json:"workflow_id" datastore:"workflow_id"`
LastNode string `json:"last_node" datastore:"last_node"`
Authorization string `json:"authorization" datastore:"authorization"`
Result string `json:"result" datastore:"result,noindex"`
StartedAt int64 `json:"started_at" datastore:"started_at"`
CompletedAt int64 `json:"completed_at" datastore:"completed_at"`
ProjectId string `json:"project_id" datastore:"project_id"`
Locations []string `json:"locations" datastore:"locations"`
Workflow Workflow `json:"workflow" datastore:"workflow,noindex"`
Results []ActionResult `json:"results" datastore:"results,noindex"`
}
// Added environment for location to execute
type Action struct {
AppName string `json:"app_name" datastore:"app_name"`
AppVersion string `json:"app_version" datastore:"app_version"`
AppID string `json:"app_id" datastore:"app_id"`
Errors []string `json:"errors" datastore:"errors"`
ID string `json:"id" datastore:"id"`
IsValid bool `json:"is_valid" datastore:"is_valid"`
IsStartNode bool `json:"isStartNode" datastore:"isStartNode"`
Sharing bool `json:"sharing" datastore:"sharing"`
PrivateID string `json:"private_id" datastore:"private_id"`
Label string `json:"label" datastore:"label"`
SmallImage string `json:"small_image" datastore:"small_image,noindex" required:false yaml:"small_image"`
LargeImage string `json:"large_image" datastore:"large_image,noindex" yaml:"large_image" required:false`
Environment string `json:"environment" datastore:"environment"`
Name string `json:"name" datastore:"name"`
Parameters []WorkflowAppActionParameter `json:"parameters" datastore: "parameters,noindex"`
Position struct {
X float64 `json:"x" datastore:"x"`
Y float64 `json:"y" datastore:"y"`
} `json:"position"`
Priority int `json:"priority" datastore:"priority"`
}
// Added environment for location to execute
type Trigger struct {
AppName string `json:"app_name" datastore:"app_name"`
Description string `json:"description" datastore:"description"`
LongDescription string `json:"long_description" datastore:"long_description"`
Status string `json:"status" datastore:"status"`
AppVersion string `json:"app_version" datastore:"app_version"`
Errors []string `json:"errors" datastore:"errors"`
ID string `json:"id" datastore:"id"`
IsValid bool `json:"is_valid" datastore:"is_valid"`
IsStartNode bool `json:"isStartNode" datastore:"isStartNode"`
Label string `json:"label" datastore:"label"`
SmallImage string `json:"small_image" datastore:"small_image,noindex" required:false yaml:"small_image"`
LargeImage string `json:"large_image" datastore:"large_image,noindex" yaml:"large_image" required:false`
Environment string `json:"environment" datastore:"environment"`
TriggerType string `json:"trigger_type" datastore:"trigger_type"`
Name string `json:"name" datastore:"name"`
Parameters []WorkflowAppActionParameter `json:"parameters" datastore: "parameters,noindex"`
Position struct {
X float64 `json:"x" datastore:"x"`
Y float64 `json:"y" datastore:"y"`
} `json:"position"`
Priority int `json:"priority" datastore:"priority"`
}
type Branch struct {
DestinationID string `json:"destination_id" datastore:"destination_id"`
ID string `json:"id" datastore:"id"`
SourceID string `json:"source_id" datastore:"source_id"`
Label string `json:"label" datastore:"label"`
HasError bool `json:"has_errors" datastore: "has_errors"`
Conditions []Condition `json:"conditions" datastore: "conditions"`
}
// Same format for a lot of stuff
type Condition struct {
Condition WorkflowAppActionParameter `json:"condition" datastore:"condition"`
Source WorkflowAppActionParameter `json:"source" datastore:"source"`
Destination WorkflowAppActionParameter `json:"destination" datastore:"destination"`
}
type Schedule struct {
Name string `json:"name" datastore:"name"`
Frequency string `json:"frequency" datastore:"frequency"`
ExecutionArgument string `json:"execution_argument" datastore:"execution_argument"`
Id string `json:"id" datastore:"id"`
}
type Workflow struct {
Actions []Action `json:"actions" datastore:"actions,noindex"`
Branches []Branch `json:"branches" datastore:"branches,noindex"`
Triggers []Trigger `json:"triggers" datastore:"triggers,noindex"`
Schedules []Schedule `json:"schedules" datastore:"schedules,noindex"`
Errors []string `json:"errors,omitempty" datastore:"errors"`
Tags []string `json:"tags,omitempty" datastore:"tags"`
ID string `json:"id" datastore:"id"`
IsValid bool `json:"is_valid" datastore:"is_valid"`
Name string `json:"name" datastore:"name"`
Description string `json:"description" datastore:"description"`
Start string `json:"start" datastore:"start"`
Owner string `json:"owner" datastore:"owner"`
Sharing string `json:"sharing" datastore:"sharing"`
Org []Org `json:"org,omitempty" datastore:"org"`
ExecutingOrg Org `json:"execution_org,omitempty" datastore:"execution_org"`
WorkflowVariables []struct {
Description string `json:"description" datastore:"description"`
ID string `json:"id" datastore:"id"`
Name string `json:"name" datastore:"name"`
Value string `json:"value" datastore:"value"`
} `json:"workflow_variables" datastore:"workflow_variables"`
}
type ActionResult struct {
Action Action `json:"action" datastore:"action"`
ExecutionId string `json:"execution_id" datastore:"execution_id"`
Authorization string `json:"authorization" datastore:"authorization"`
Result string `json:"result" datastore:"result,noindex"`
StartedAt int64 `json:"started_at" datastore:"started_at"`
CompletedAt int64 `json:"completed_at" datastore:"completed_at"`
Status string `json:"status" datastore:"status"`
}
type Authentication struct {
Required bool `json:"required" datastore:"required" yaml:"required" `
Parameters []AuthenticationParams `json:"parameters" datastore:"parameters" yaml:"parameters"`
}
type AuthenticationParams struct {
Description string `json:"description" datastore:"description" yaml:"description"`
ID string `json:"id" datastore:"id" yaml:"id"`
Name string `json:"name" datastore:"name" yaml:"name"`
Example string `json:"example" datastore:"example" yaml:"example"`
Value string `json:"value,omitempty" datastore:"value" yaml:"value"`
Multiline bool `json:"multiline" datastore:"multiline" yaml:"multiline"`
Required bool `json:"required" datastore:"required" yaml:"required"`
In string `json:"in" datastore:"in" yaml:"in"`
Scheme string `json:"scheme" datastore:"scheme" yaml:"scheme"`
}
type AuthenticationStore struct {
Key string `json:"key" datastore:"key"`
Value string `json:"value" datastore:"value"`
}
type ExecutionRequestWrapper struct {
Data []ExecutionRequest `json:"data"`
}
// This might be... a bit off, but that's fine :)
// This might also be stupid, as we want timelines and such
// Anyway, these are super basic stupid stats.
func increaseStatisticsField(ctx context.Context, fieldname, id string, amount int64) error {
// 1. Get current stats
// 2. Increase field(s)
// 3. Put new stats
statisticsId := "global_statistics"
nameKey := fieldname
key := datastore.NameKey(statisticsId, nameKey, nil)
statisticsItem := StatisticsItem{}
newData := StatisticsData{
Timestamp: int64(time.Now().Unix()),
Amount: amount,
Id: id,
}
if err := dbclient.Get(ctx, key, &statisticsItem); err != nil {
// Should init
if strings.Contains(fmt.Sprintf("%s", err), "entity") {
statisticsItem = StatisticsItem{
Total: amount,
Fieldname: fieldname,
Data: []StatisticsData{
newData,
},
}
if _, err := dbclient.Put(ctx, key, &statisticsItem); err != nil {
log.Printf("Error setting base stats: %s", err)
return err
}
return nil
}
//log.Printf("STATSERR: %s", err)
return err
}
statisticsItem.Total += amount
statisticsItem.Data = append(statisticsItem.Data, newData)
// New struct, to not add body, author etc
if _, err := dbclient.Put(ctx, key, &statisticsItem); err != nil {
log.Printf("Error stats to %s: %s", fieldname, err)
return err
}
//log.Printf("Stats: %#v", statisticsItem)
return nil
}
func setWorkflowQueue(ctx context.Context, executionRequests ExecutionRequestWrapper, id string) error {
key := datastore.NameKey("workflowqueue", id, nil)
// New struct, to not add body, author etc
if _, err := dbclient.Put(ctx, key, &executionRequests); err != nil {
log.Printf("Error adding workflow queue: %s", err)
return err
}
return nil
}
func getWorkflowQueue(ctx context.Context, id string) (ExecutionRequestWrapper, error) {
key := datastore.NameKey("workflowqueue", id, nil)
workflows := ExecutionRequestWrapper{}
if err := dbclient.Get(ctx, key, &workflows); err != nil {
return ExecutionRequestWrapper{}, err
}
return workflows, nil
}
//func setWorkflowqueuetest(id string) {
// data := ExecutionRequestWrapper{
// Data: []ExecutionRequest{
// ExecutionRequest{
// ExecutionId: "2349bf96-51ad-68d2-5ca6-75ef8f7ee814",
// WorkflowId: "8e344a2e-db51-448f-804c-eb959a32c139",
// Authorization: "wut",
// },
// },
// }
//
// err := setWorkflowQueue(data, id)
// if err != nil {
// log.Printf("Fail: %s", err)
// }
//}
// Frequency = cronjob OR minutes between execution
func createSchedule(ctx context.Context, scheduleId, workflowId, name, frequency string, body []byte) error {
var err error
testSplit := strings.Split(frequency, "*")
cronJob := ""
newfrequency := 0
if len(testSplit) > 5 {
cronJob = frequency
} else {
newfrequency, err = strconv.Atoi(frequency)
if err != nil {
log.Printf("Failed to parse time: %s", err)
return err
}
//if int(newfrequency) < 60 {
// cronJob = fmt.Sprintf("*/%s * * * *")
//} else if int(newfrequency) <
}
// Reverse. Can't handle CRON, only numbers
if len(cronJob) > 0 {
return errors.New("cronJob isn't formatted correctly")
}
if newfrequency < 1 {
return errors.New("Frequency has to be more than 0")
}
//log.Printf("CRON: %s, body: %s", cronJob, string(body))
// FIXME:
// This may run multiple places if multiple servers,
// but that's a future problem
job := func() {
request := &http.Request{
Method: "POST",
Body: ioutil.NopCloser(strings.NewReader(string(body))),
}
_, _, err := handleExecution(workflowId, Workflow{}, request)
if err != nil {
log.Printf("Failed to execute: %s", err)
}
}
log.Printf("Starting frequency: %d", newfrequency)
jobret, err := newscheduler.Every(newfrequency).Seconds().NotImmediately().Run(job)
if err != nil {
log.Printf("Failed to schedule workflow: %s", err)
return err
}
//scheduledJobs = append(scheduledJobs, jobret)
scheduledJobs[scheduleId] = jobret
// Doesn't need running/not running. If stopped, we just delete it.
timeNow := int64(time.Now().Unix())
schedule := ScheduleOld{
Id: scheduleId,
WorkflowId: workflowId,
Argument: string(body),
Seconds: newfrequency,
CreationTime: timeNow,
LastModificationtime: timeNow,
LastRuntime: timeNow,
}
err = setSchedule(ctx, schedule)
if err != nil {
log.Printf("Failed to set schedule: %s", err)
return err
}
// FIXME - Create a real schedule based on cron:
// 1. Parse the cron in a function to match this schedule
// 2. Make main init check for schedules that aren't running
return nil
}
func handleGetWorkflowqueueConfirm(resp http.ResponseWriter, request *http.Request) {
cors := handleCors(resp, request)
if cors {
return
}
id := request.Header.Get("Org-Id")
if len(id) == 0 {
log.Printf("No Org-Id header set - confirm")
resp.WriteHeader(401)
resp.Write([]byte(fmt.Sprintf(`{"success": false, "reason": "Specify the org-id header."}`)))
return
}
//setWorkflowqueuetest(id)
ctx := context.Background()
executionRequests, err := getWorkflowQueue(ctx, id)
if err != nil {
log.Printf("(1) Failed reading body for workflowqueue: %s", err)
resp.WriteHeader(401)
resp.Write([]byte(fmt.Sprintf(`{"success": false, "reason": "Entity parsing error - confirm"}`)))
return
}
if len(executionRequests.Data) == 0 {
log.Printf("No requests to fix. Why did this request occur?")
resp.WriteHeader(401)
resp.Write([]byte(fmt.Sprintf(`{"success": false, "reason": "Some error"}`)))
return
}
body, err := ioutil.ReadAll(request.Body)
if err != nil {
log.Println("Failed reading body for stream result queue")
resp.WriteHeader(401)
resp.Write([]byte(fmt.Sprintf(`{"success": false, "reason": "%s"}`, err)))
return
}
// Getting from the request
//log.Println(string(body))
var removeExecutionRequests ExecutionRequestWrapper
err = json.Unmarshal(body, &removeExecutionRequests)
if err != nil {
log.Printf("Failed executionrequest in queue unmarshaling: %s", err)
resp.WriteHeader(401)
resp.Write([]byte(fmt.Sprintf(`{"success": false, "reason": "%s"}`, err)))
return
}
if len(removeExecutionRequests.Data) == 0 {
log.Printf("No requests to fix remove")
resp.WriteHeader(401)
resp.Write([]byte(fmt.Sprintf(`{"success": false, "reason": "Some removal error"}`)))
return
}
// remove items from DB
var newExecutionRequests ExecutionRequestWrapper
for _, execution := range executionRequests.Data {
found := false
for _, removeExecution := range removeExecutionRequests.Data {
if removeExecution.ExecutionId == execution.ExecutionId && removeExecution.WorkflowId == execution.WorkflowId {
found = true
break
}
}
if !found {
newExecutionRequests.Data = append(newExecutionRequests.Data, execution)
}
}
// Push only the remaining to the DB (remove)
if len(executionRequests.Data) != len(newExecutionRequests.Data) {
err := setWorkflowQueue(ctx, newExecutionRequests, id)
if err != nil {
log.Printf("Fail: %s", err)
}
}
//newjson, err := json.Marshal(removeExecutionRequests)
//if err != nil {
// resp.WriteHeader(401)
// resp.Write([]byte(fmt.Sprintf(`{"success": false, "reason": "Failed unpacking workflow execution"}`)))
// return
//}
resp.WriteHeader(200)
resp.Write([]byte("OK"))
}
func handleGetWorkflowqueue(resp http.ResponseWriter, request *http.Request) {
cors := handleCors(resp, request)
if cors {
return
}
id := request.Header.Get("Org-Id")
if len(id) == 0 {
log.Printf("No org-id header set")
resp.WriteHeader(401)
resp.Write([]byte(fmt.Sprintf(`{"success": false, "reason": "Specify the org-id header."}`)))
return
}
ctx := context.Background()
executionRequests, err := getWorkflowQueue(ctx, id)
if err != nil {
// Skipping as this comes up over and over
//log.Printf("(2) Failed reading body for workflowqueue: %s", err)
resp.WriteHeader(401)
resp.Write([]byte(fmt.Sprintf(`{"success": false, "reason": "%s"}`, err)))
return
}
if len(executionRequests.Data) == 0 {
executionRequests.Data = []ExecutionRequest{}
}
newjson, err := json.Marshal(executionRequests)
if err != nil {
resp.WriteHeader(401)
resp.Write([]byte(fmt.Sprintf(`{"success": false, "reason": "Failed unpacking workflow execution"}`)))
return
}
resp.WriteHeader(200)
resp.Write(newjson)
}
func handleGetStreamResults(resp http.ResponseWriter, request *http.Request) {
cors := handleCors(resp, request)
if cors {
return
}
body, err := ioutil.ReadAll(request.Body)
if err != nil {
log.Println("Failed reading body for stream result queue")
resp.WriteHeader(401)
resp.Write([]byte(fmt.Sprintf(`{"success": false, "reason": "%s"}`, err)))
return
}
var actionResult ActionResult
err = json.Unmarshal(body, &actionResult)
if err != nil {
log.Printf("Failed ActionResult unmarshaling: %s", err)
resp.WriteHeader(401)
resp.Write([]byte(fmt.Sprintf(`{"success": false, "reason": "%s"}`, err)))
return
}
ctx := context.Background()
workflowExecution, err := getWorkflowExecution(ctx, actionResult.ExecutionId)
if err != nil {
log.Printf("Failed getting execution (streamresult) %s: %s", actionResult.ExecutionId, err)
resp.WriteHeader(401)
resp.Write([]byte(fmt.Sprintf(`{"success": false, "reason": "Bad authorization key or execution_id might not exist."}`)))
return
}
// Authorization is done here
if workflowExecution.Authorization != actionResult.Authorization {
log.Printf("Bad authorization key when getting stream results %s.", actionResult.ExecutionId)
resp.WriteHeader(401)
resp.Write([]byte(fmt.Sprintf(`{"success": false, "reason": "Bad authorization key or execution_id might not exist."}`)))
return
}
//for _, action := range workflowExecution.Workflow.Actions {
// log.Printf("Name: %s, Env: %s", action.Name, action.Environment)
//}
newjson, err := json.Marshal(workflowExecution)
if err != nil {
resp.WriteHeader(401)
resp.Write([]byte(fmt.Sprintf(`{"success": false, "reason": "Failed unpacking workflow execution"}`)))
return
}
resp.WriteHeader(200)
resp.Write(newjson)
}
func handleWorkflowQueue(resp http.ResponseWriter, request *http.Request) {
cors := handleCors(resp, request)
if cors {
return
}
body, err := ioutil.ReadAll(request.Body)
if err != nil {
log.Println("(3) Failed reading body for workflowqueue")
resp.WriteHeader(401)
resp.Write([]byte(fmt.Sprintf(`{"success": false, "reason": "%s"}`, err)))
return
}
var actionResult ActionResult
err = json.Unmarshal(body, &actionResult)
if err != nil {
log.Printf("Failed ActionResult unmarshaling: %s", err)
resp.WriteHeader(401)
resp.Write([]byte(fmt.Sprintf(`{"success": false, "reason": "%s"}`, err)))
return
}
// 1. Get the WorkflowExecution(ExecutionId) from the database
// 2. if ActionResult.Authentication != WorkflowExecution.Authentication -> exit
// 3. Add to and update actionResult in workflowExecution
// 4. Push to db
// IF FAIL: Set executionstatus: abort or cancel
ctx := context.Background()
workflowExecution, err := getWorkflowExecution(ctx, actionResult.ExecutionId)
if err != nil {
log.Printf("Failed getting execution (workflowqueue) %s: %s", actionResult.ExecutionId, err)
resp.WriteHeader(401)
resp.Write([]byte(fmt.Sprintf(`{"success": false, "reason": "Failed getting execution ID %s because it doesn't exist."}`, actionResult.ExecutionId)))
return
}
if workflowExecution.Authorization != actionResult.Authorization {
log.Printf("Bad authorization key when updating node (workflowQueue) %s. Want: %s, Have: %s", actionResult.ExecutionId, workflowExecution.Authorization, actionResult.Authorization)
resp.WriteHeader(401)
resp.Write([]byte(fmt.Sprintf(`{"success": false, "reason": "Bad authorization key"}`)))
return
}
if workflowExecution.Status == "FINISHED" {
log.Printf("Workflowexecution is already FINISHED. No further action can be taken")
resp.WriteHeader(401)
resp.Write([]byte(fmt.Sprintf(`{"success": false, "reason": "Workflowexecution is already finished because of %s with status %s"}`, workflowExecution.LastNode, workflowExecution.Status)))
return
}
// Not sure what's up here
// FIXME - remove comment
if workflowExecution.Status == "ABORTED" || workflowExecution.Status == "FAILURE" {
log.Printf("Workflowexecution is already aborted. No further action can be taken")
resp.WriteHeader(401)
resp.Write([]byte(fmt.Sprintf(`{"success": false, "reason": "Workflowexecution is aborted because of %s with result %s and status %s"}`, workflowExecution.LastNode, workflowExecution.Result, workflowExecution.Status)))
return
}
if actionResult.Status == "ABORTED" || actionResult.Status == "FAILURE" {
log.Printf("Actionresult is %s. Should set workflowExecution and exit all running functions", actionResult.Status)
workflowExecution.Status = actionResult.Status
workflowExecution.LastNode = actionResult.Action.ID
// Cleans up aborted, and always gives a result
lastResult := ""
newResults := []ActionResult{}
// type ActionResult struct {
for _, result := range workflowExecution.Results {
if result.Status == "EXECUTING" {
result.Status = actionResult.Status
result.Result = "Aborted because of an unknown error"
}
if len(result.Result) > 0 {
lastResult = result.Result
}
newResults = append(newResults, result)
}
workflowExecution.Result = lastResult
workflowExecution.Results = newResults
if workflowExecution.Status == "ABORTED" {
err = increaseStatisticsField(ctx, "workflow_executions_aborted", workflowExecution.Workflow.ID, 1)
if err != nil {
log.Printf("Failed to increase aborted execution stats: %s", err)
}
} else if workflowExecution.Status == "FAILURE" {
err = increaseStatisticsField(ctx, "workflow_executions_failure", workflowExecution.Workflow.ID, 1)
if err != nil {
log.Printf("Failed to increase failure execution stats: %s", err)
}
}
}
// This means it should continue I think :)
if actionResult.Status == "SKIPPED" {
// How the fuck do I do this tho
// Parse _all_ children of the skipped and add them to "finished"
//
log.Printf("Find out how to handle skipped items, as there might be more branches to continue anyway")
// FIXME - simulate that every subnode is skipped
// Check worker, as it contains this code
// Children of children of children...
// Recurse, woo
//for _, item := range children {
//}
}
// FIXME rebuild to be like this or something
// workflowExecution/ExecutionId/Nodes/NodeId
// Find the appropriate action
if len(workflowExecution.Results) > 0 {
// FIXME
found := false
outerindex := 0
for index, item := range workflowExecution.Results {
if item.Action.ID == actionResult.Action.ID {
found = true
outerindex = index
break
}
}
if found {
// FIXME - this is broken, but why
//if workflowExecution.Results[outerindex].Status == actionResult.Status {
// log.Printf("Status of %s is already %s", actionResult.Action.ID, actionResult.Status)
// resp.WriteHeader(401)
// resp.Write([]byte(fmt.Sprintf(`{"success": false, "reason": "Status of %s is already %s"}`, actionResult.Action.ID, actionResult.Status)))
// return
//}
log.Printf("Updating %s in %s from %s to %s", actionResult.Action.ID, workflowExecution.ExecutionId, workflowExecution.Results[outerindex].Status, actionResult.Status)
workflowExecution.Results[outerindex] = actionResult
} else {
log.Printf("Setting value of %s in %s to %s", actionResult.Action.ID, workflowExecution.ExecutionId, actionResult.Status)
workflowExecution.Results = append(workflowExecution.Results, actionResult)
}
} else {
log.Printf("Setting value of %s in %s to %s", actionResult.Action.ID, workflowExecution.ExecutionId, actionResult.Status)
workflowExecution.Results = append(workflowExecution.Results, actionResult)
}
extraInputs := 0
for _, result := range workflowExecution.Results {
if result.Action.Name == "User Input" && result.Action.AppName == "User Input" {
extraInputs += 1
}
}
//log.Printf("Checking results %d vs %d", len(workflowExecution.Results), len(workflowExecution.Workflow.Actions)+extraInputs)
if len(workflowExecution.Results) == len(workflowExecution.Workflow.Actions)+extraInputs {
finished := true
lastResult := ""
for _, result := range workflowExecution.Results {
if result.Status != "SUCCESS" && result.Status != "FINISHED" {
finished = false
break
}
lastResult = result.Result
}
if finished {
log.Printf("Execution of %s finished.", workflowExecution.ExecutionId)
//log.Println("Might be finished based on length of results and everything being SUCCESS or FINISHED - VERIFY THIS. Setting status to finished.")
workflowExecution.Result = lastResult
workflowExecution.Status = "FINISHED"
workflowExecution.CompletedAt = int64(time.Now().Unix())
if workflowExecution.LastNode == "" {
workflowExecution.LastNode = actionResult.Action.ID
}
err = increaseStatisticsField(ctx, "workflow_executions_success", workflowExecution.Workflow.ID, 1)
if err != nil {
log.Printf("Failed to increase success execution stats: %s", err)
}
}
}
// FIXME - why isn't this how it works otherwise, wtf?
//workflow, err := getWorkflow(workflowExecution.Workflow.ID)
//newActions := []Action{}
//for _, action := range workflowExecution.Workflow.Actions {
// log.Printf("Name: %s, Env: %s", action.Name, action.Environment)
//}
err = setWorkflowExecution(ctx, *workflowExecution)
if err != nil {
log.Printf("Error saving workflow execution actionresult setting: %s", err)
resp.WriteHeader(401)
resp.Write([]byte(fmt.Sprintf(`{"success": false, "reason": "Failed setting workflowexecution actionresult: %s"}`, err)))
return
}
resp.WriteHeader(200)
resp.Write([]byte(fmt.Sprintf(`{"success": true}`)))
}
func getWorkflows(resp http.ResponseWriter, request *http.Request) {
cors := handleCors(resp, request)
if cors {
return
}
user, err := handleApiAuthentication(resp, request)
if err != nil {
log.Printf("Api authentication failed in getworkflows: %s", err)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
//memcacheName := fmt.Sprintf("%s_workflows", user.Username)
ctx := context.Background()
//if item, err := memcache.Get(ctx, memcacheName); err == memcache.ErrCacheMiss {
// // Not in cache
// //log.Printf("Workflows not in cache.")
//} else if err != nil {
// log.Printf("Error getting item: %v", err)
//} else {
// // FIXME - verify if value is ok? Can unmarshal etc.
// resp.WriteHeader(200)
// resp.Write(item.Value)
// return
//}
// With user, do a search for workflows with user or user's org attached
q := datastore.NewQuery("workflow").Filter("owner =", user.Id)
var workflows []Workflow
_, err = dbclient.GetAll(ctx, q, &workflows)
if err != nil {
log.Printf("Failed getting workflows for user %s: %s", user.Username, err)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
if len(workflows) == 0 {
resp.WriteHeader(200)
resp.Write([]byte("[]"))
return
}
newjson, err := json.Marshal(workflows)
if err != nil {
resp.WriteHeader(401)
resp.Write([]byte(fmt.Sprintf(`{"success": false, "reason": "Failed unpacking workflows"}`)))
return
}
//item := &memcache.Item{
// Key: memcacheName,
// Value: newjson,
// Expiration: time.Minute * 10,
//}
//if err := memcache.Add(ctx, item); err == memcache.ErrNotStored {
// if err := memcache.Set(ctx, item); err != nil {
// log.Printf("Error setting item: %v", err)
// }
//} else if err != nil {
// log.Printf("Error adding item: %v", err)
//} else {
// //log.Printf("Set cache for %s", item.Key)
//}
resp.WriteHeader(200)
resp.Write(newjson)
}
// FIXME - add to actual database etc
func setNewWorkflow(resp http.ResponseWriter, request *http.Request) {
cors := handleCors(resp, request)
if cors {
return
}
user, err := handleApiAuthentication(resp, request)
if err != nil {
log.Printf("Api authentication failed in set new workflowhandler: %s", err)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
body, err := ioutil.ReadAll(request.Body)
if err != nil {
log.Printf("Error with body read: %s", err)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
var workflow Workflow
err = json.Unmarshal(body, &workflow)
if err != nil {
log.Printf("Failed unmarshaling: %s", err)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
workflow.ID = uuid.NewV4().String()
workflow.Owner = user.Id
workflow.Sharing = "private"
ctx := context.Background()
err = setWorkflow(ctx, workflow, workflow.ID)
if err != nil {
log.Printf("Failed setting workflow: %s", err)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
log.Printf("Saved new workflow %s with name %s", workflow.ID, workflow.Name)
err = increaseStatisticsField(ctx, "total_workflows", workflow.ID, 1)
if err != nil {
log.Printf("Failed to increase total workflows: %s", err)
}
if len(workflow.Actions) == 0 {
workflow.Actions = []Action{}
}
if len(workflow.Branches) == 0 {
workflow.Branches = []Branch{}
}
if len(workflow.Triggers) == 0 {
workflow.Triggers = []Trigger{}
}
if len(workflow.Errors) == 0 {
workflow.Errors = []string{}
}
newActions := []Action{}
for _, action := range workflow.Actions {
if action.Environment == "" {
//action.Environment = baseEnvironment
action.IsValid = true
}
newActions = append(newActions, action)
}
workflow.Actions = newActions
workflow.IsValid = true
workflowjson, err := json.Marshal(workflow)
if err != nil {
log.Printf("Failed workflow json setting marshalling: %s", err)
resp.WriteHeader(http.StatusInternalServerError)
resp.Write([]byte(`{"success": false}`))
return
}
//memcacheName := fmt.Sprintf("%s_workflows", user.Username)
//memcache.Delete(ctx, memcacheName)
resp.WriteHeader(200)
//log.Println(string(workflowjson))
resp.Write(workflowjson)
}
func deleteWorkflow(resp http.ResponseWriter, request *http.Request) {
cors := handleCors(resp, request)
if cors {
return
}
user, err := handleApiAuthentication(resp, request)
if err != nil {
log.Printf("Api authentication failed in deleting workflow: %s", err)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
location := strings.Split(request.URL.String(), "/")
var fileId string
if location[1] == "api" {
if len(location) <= 4 {
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
fileId = location[4]
}
if len(fileId) != 36 {
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false, "reason": "Workflow ID to delete is not valid"}`))
return
}
ctx := context.Background()
workflow, err := getWorkflow(ctx, fileId)
if err != nil {
log.Printf("Failed getting the workflow locally: %s", err)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
// FIXME - have a check for org etc too..
if user.Id != workflow.Owner && user.Role != "admin" {
log.Printf("Wrong user (%s) for workflow %s", user.Username, workflow.ID)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
// Clean up triggers and executions
for _, item := range workflow.Triggers {
if item.TriggerType == "SCHEDULE" {
err = deleteSchedule(ctx, item.ID)
if err != nil {
log.Printf("Failed to delete schedule: %s", err)
}
} else if item.TriggerType == "WEBHOOK" {
err = removeWebhookFunction(ctx, item.ID)
if err != nil {
log.Printf("Failed to delete webhook: %s", err)
}
} else if item.TriggerType == "EMAIL" {
err = handleOutlookSubRemoval(ctx, workflow.ID, item.ID)
if err != nil {
log.Printf("Failed to delete email sub: %s", err)
}
}
err = increaseStatisticsField(ctx, "total_workflow_triggers", workflow.ID, -1)
if err != nil {
log.Printf("Failed to increase total workflows: %s", err)
}
}
// FIXME - maybe delete workflow executions
log.Printf("Should delete workflow %s", fileId)
err = DeleteKey(ctx, "workflow", fileId)
if err != nil {
log.Printf("Failed deleting key %s", fileId)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false, "reason": "Failed deleting key"}`))
return
}
err = increaseStatisticsField(ctx, "total_workflows", fileId, -1)
if err != nil {
log.Printf("Failed to increase total workflows: %s", err)
}
//memcacheName := fmt.Sprintf("%s_%s", user.Username, fileId)
//memcache.Delete(ctx, memcacheName)
//memcacheName = fmt.Sprintf("%s_workflows", user.Username)
//memcache.Delete(ctx, memcacheName)
resp.WriteHeader(200)
resp.Write([]byte(`{"success": true}`))
}
// FIXME - check whether all nodes has a branch, otherwise go back
func saveWorkflow(resp http.ResponseWriter, request *http.Request) {
cors := handleCors(resp, request)
if cors {
return
}
log.Println("Start")
user, userErr := handleApiAuthentication(resp, request)
if userErr != nil {
log.Printf("Api authentication failed in edit workflow: %s", userErr)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
log.Println("PostUser")
location := strings.Split(request.URL.String(), "/")
var fileId string
if location[1] == "api" {
if len(location) <= 4 {
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
fileId = location[4]
}
if len(fileId) != 36 {
log.Printf(`ID %s is not valid`, fileId)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false, "reason": "Workflow ID to save is not valid"}`))
return
}
// Here to check access rights
ctx := context.Background()
log.Println("GetWorkflow start")
tmpworkflow, err := getWorkflow(ctx, fileId)
if err != nil {
log.Printf("Failed getting the workflow locally: %s", err)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
log.Println("GetWorkflow end")
// FIXME - have a check for org etc too..
if user.Id != tmpworkflow.Owner && user.Role != "admin" {
log.Printf("Wrong user (%s) for workflow %s (save)", user.Username, tmpworkflow.ID)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
//Actions []Action `json:"actions" datastore:"actions,noindex"`
log.Printf("Hello")
body, err := ioutil.ReadAll(request.Body)
if err != nil {
log.Printf("Failed hook unmarshaling: %s", err)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
log.Printf("Hello2")
var workflow Workflow
err = json.Unmarshal([]byte(body), &workflow)
//log.Printf(string(body))
if err != nil {
log.Printf("Failed workflow unmarshaling: %s", err)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
// FIXME - auth and check if they should have access
if fileId != workflow.ID {
log.Printf("Path and request ID are not matching: %s:%s.", fileId, workflow.ID)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
// FIXME - this shouldn't be necessary with proper API checks
newActions := []Action{}
allNodes := []string{}
log.Println("Pre")
for _, action := range workflow.Actions {
allNodes = append(allNodes, action.ID)
if action.Environment == "" {
resp.WriteHeader(401)
resp.Write([]byte(fmt.Sprintf(`{"success": false, "reason": "An environment for %s is required"}`, action.Label)))
return
action.IsValid = true
}
newActions = append(newActions, action)
}
workflow.Actions = newActions
for _, trigger := range workflow.Triggers {
log.Println("TRIGGERS")
allNodes = append(allNodes, trigger.ID)
}
if len(workflow.Actions) == 0 {
workflow.Actions = []Action{}
}
if len(workflow.Branches) == 0 {
workflow.Branches = []Branch{}
}
if len(workflow.Triggers) == 0 {
workflow.Triggers = []Trigger{}
}
if len(workflow.Errors) == 0 {
workflow.Errors = []string{}
}
// FIXME - do actual checks ROFL
// FIXME - minor issues with e.g. hello world and self.console_logger
// Nodechecks
foundNodes := []string{}
for _, node := range allNodes {
for _, branch := range workflow.Branches {
log.Println("branch")
//log.Println(node)
//log.Println(branch.DestinationID)
if node == branch.DestinationID || node == branch.SourceID {
foundNodes = append(foundNodes, node)
break
}
}
}
// FIXME - append all nodes (actions, triggers etc) to one single array here
if len(foundNodes) != len(allNodes) || len(workflow.Actions) <= 0 {
// This shit takes a few seconds lol
if !workflow.IsValid {
oldworkflow, err := getWorkflow(ctx, fileId)
if err != nil {
log.Printf("Workflow %s doesn't exist - oldworkflow.", fileId)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false, "reason": "Item already exists."}`))
return
}
oldworkflow.IsValid = false
err = setWorkflow(ctx, *oldworkflow, fileId)
if err != nil {
log.Printf("Failed saving workflow to database: %s", err)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
}
// FIXME - more checks here - force reload of data or something
//if len(allNodes) == 0 {
// resp.WriteHeader(401)
// resp.Write([]byte(`{"success": false, "reason": "Please insert a node"}`))
// return
//}
// Allowed with only a start node
//if len(allNodes) != 1 {
// resp.WriteHeader(401)
// resp.Write([]byte(`{"success": false, "reason": "There are nodes with no branches"}`))
// return
//}
}
// FIXME - might be a sploit to run someone elses app if getAllWorkflowApps
// doesn't check sharing=true
// Have to do it like this to add the user's apps
log.Println("Apps set starting")
workflowApps := []WorkflowApp{}
//memcacheName = "all_apps"
//if item, err := memcache.Get(ctx, memcacheName); err == memcache.ErrCacheMiss {
// // Not in cache
// log.Printf("Apps not in cache.")
workflowApps, err = getAllWorkflowApps(ctx)
if err != nil {
log.Printf("Failed getting all workflow apps from database: %s", err)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
//} else if err != nil {
// log.Printf("Error getting item: %v", err)
//} else {
// // FIXME - verify if value is ok? Can unmarshal etc.
// err = json.Unmarshal(item.Value, &workflowApps)
// if err != nil {
// log.Printf("Failed unmarshaling allworkflowapps from memcache: %s", err)
// resp.WriteHeader(401)
// resp.Write([]byte(`{"success": false}`))
// return
// }
// if userErr == nil && len(user.PrivateApps) > 0 {
// workflowApps = append(workflowApps, user.PrivateApps...)
// }
//}
// Started getting the single apps, but if it's weird, this is faster
log.Println("Apps set done")
// Check every app action and param to see whether they exist
newActions = []Action{}
for _, action := range workflow.Actions {
curapp := WorkflowApp{}
// FIXME - can this work with ONLY AppID?
for _, app := range workflowApps {
if app.ID == action.AppID {
curapp = app
break
}
if app.Name == action.AppName && app.AppVersion == action.AppVersion {
curapp = app
break
}
}
// Check to see if the whole app is valid
if curapp.Name != action.AppName {
log.Printf("App %s doesn't exist.", action.AppName)
resp.WriteHeader(401)
resp.Write([]byte(fmt.Sprintf(`{"success": false, "reason": "App %s doesn't exist"}`, action.AppName)))
return
}
// Check tosee if the appaction is valid
curappaction := WorkflowAppAction{}
for _, curAction := range curapp.Actions {
if action.Name == curAction.Name {
curappaction = curAction
break
}
log.Println(action.Name, curAction.Name)
}
// Check to see if the action is valid
if curappaction.Name != action.Name {
log.Printf("Appaction %s doesn't exist.", action.Name)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
// FIXME - check all parameters to see if they're valid
// Includes checking required fields
newParams := []WorkflowAppActionParameter{}
for _, param := range curappaction.Parameters {
found := false
// Handles check for parameter exists + value not empty in used fields
for _, actionParam := range action.Parameters {
if actionParam.Name == param.Name {
found = true
if actionParam.Value == "" && actionParam.Variant == "STATIC_VALUE" && actionParam.Required == true {
log.Printf("Appaction %s with required param '%s' is empty.", action.Name, param.Name)
resp.WriteHeader(401)
resp.Write([]byte(fmt.Sprintf(`{"success": false, "reason": "Appaction %s with required param '%s' is empty."}`, action.Name, param.Name)))
return
}
if actionParam.Variant == "" {
actionParam.Variant = "STATIC_VALUE"
}
newParams = append(newParams, actionParam)
}
}
// Handles check for required params
if !found && param.Required {
log.Printf("Appaction %s with required param %s doesn't exist.", action.Name, param.Name)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
}
action.Parameters = newParams
newActions = append(newActions, action)
}
workflow.Actions = newActions
workflow.IsValid = true
err = setWorkflow(ctx, workflow, fileId)
if err != nil {
log.Printf("Failed saving workflow to database: %s", err)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
totalOldActions := len(tmpworkflow.Actions)
totalNewActions := len(workflow.Actions)
err = increaseStatisticsField(ctx, "total_workflow_actions", workflow.ID, int64(totalNewActions-totalOldActions))
if err != nil {
log.Printf("Failed to change total actions data: %s", err)
}
log.Printf("Saved new version of workflow %s", fileId)
resp.WriteHeader(200)
resp.Write([]byte(`{"success": true}`))
}
func getWorkflowLocal(fileId string, request *http.Request) ([]byte, error) {
fullUrl := fmt.Sprintf("%s/api/v1/workflows/%s", localBase, fileId)
client := &http.Client{}
req, err := http.NewRequest(
"GET",
fullUrl,
nil,
)
if err != nil {
return []byte{}, err
}
for key, value := range request.Header {
req.Header.Add(key, strings.Join(value, ";"))
}
newresp, err := client.Do(req)
if err != nil {
return []byte{}, err
}
body, err := ioutil.ReadAll(newresp.Body)
if err != nil {
return []byte{}, err
}
// Temporary solution
if strings.Contains(string(body), "reason") && strings.Contains(string(body), "false") {
return []byte{}, errors.New(fmt.Sprintf("Failed getting workflow %s with message %s", fileId, string(body)))
}
return body, nil
}
func abortExecution(resp http.ResponseWriter, request *http.Request) {
cors := handleCors(resp, request)
if cors {
return
}
user, err := handleApiAuthentication(resp, request)
if err != nil {
log.Printf("Api authentication failed in abort workflow: %s", err)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
location := strings.Split(request.URL.String(), "/")
var fileId string
if location[1] == "api" {
if len(location) <= 4 {
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
fileId = location[4]
}
if len(fileId) != 36 {
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false, "reason": "Workflow ID to abort is not valid"}`))
return
}
executionId := location[6]
if len(executionId) != 36 {
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false, "reason": "ExecutionID not valid"}`))
return
}
ctx := context.Background()
workflowExecution, err := getWorkflowExecution(ctx, executionId)
if err != nil {
log.Printf("Failed getting execution (abort) %s: %s", executionId, err)
resp.WriteHeader(401)
resp.Write([]byte(fmt.Sprintf(`{"success": false, "reason": "Failed getting execution ID %s because it doesn't exist (abort)."}`, executionId)))
return
}
// FIXME - have a check for org etc too..
if user.Id != workflowExecution.Workflow.Owner && user.Role != "admin" {
log.Printf("Wrong user (%s) for workflowexecution workflow %s", user.Username, workflowExecution.Workflow.ID)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
if workflowExecution.Status == "ABORTED" || workflowExecution.Status == "FAILURE" || workflowExecution.Status == "FINISHED" {
log.Printf("Stopped execution of %s with status %s", executionId, workflowExecution.Status)
resp.WriteHeader(401)
resp.Write([]byte(fmt.Sprintf(`{"success": false, "reason": "Status for %s is %s, which can't be aborted."}`, executionId, workflowExecution.Status)))
return
}
topic := "workflowexecution"
workflowExecution.CompletedAt = int64(time.Now().Unix())
workflowExecution.Status = "ABORTED"
lastResult := ""
newResults := []ActionResult{}
// type ActionResult struct {
for _, result := range workflowExecution.Results {
if result.Status == "EXECUTING" {
result.Status = "ABORTED"
result.Result = "Aborted because of an unknown error"
}
if len(result.Result) > 0 {
lastResult = result.Result
}
newResults = append(newResults, result)
}
workflowExecution.Results = newResults
if len(workflowExecution.Result) == 0 {
workflowExecution.Result = lastResult
}
err = setWorkflowExecution(ctx, *workflowExecution)
if err != nil {
log.Printf("Error saving workflow execution for updates when aborting %s: %s", topic, err)
resp.WriteHeader(401)
resp.Write([]byte(fmt.Sprintf(`{"success": false, "reason": "Failed setting workflowexecution status to abort"}`)))
return
}
err = increaseStatisticsField(ctx, "workflow_executions_aborted", workflowExecution.Workflow.ID, 1)
if err != nil {
log.Printf("Failed to increase aborted execution stats: %s", err)
}
// FIXME - allowed to edit it? idk
resp.WriteHeader(200)
resp.Write([]byte(fmt.Sprintf(`{"success": true}`)))
// Not sure what's up here
//if workflowExecution.Status == "ABORTED" || workflowExecution.Status == "FAILURE" {
// log.Printf("Workflowexecution is already aborted. No further action can be taken")
// resp.WriteHeader(401)
// resp.Write([]byte(fmt.Sprintf(`{"success": false, "reason": "Workflowexecution is aborted because of %s with result %s and status %s"}`, workflowExecution.LastNode, workflowExecution.Result, workflowExecution.Status)))
// return
//}
}
//// New execution with firestore
func cleanupExecutions(resp http.ResponseWriter, request *http.Request) {
cors := handleCors(resp, request)
if cors {
return
}
user, err := handleApiAuthentication(resp, request)
if err != nil {
log.Printf("Api authentication failed in execute workflow: %s", err)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false, "message": "Not authenticated"}`))
return
}
//if user.Role != "admin" {
// resp.WriteHeader(401)
// resp.Write([]byte(`{"success": false, "message": "Insufficient permissions"}`))
// return
//}
log.Printf("CLEANUP!")
log.Printf("%#v", user)
ctx := context.Background()
// Removes three months from today
timestamp := int64(time.Now().AddDate(0, -2, 0).Unix())
log.Println(timestamp)
q := datastore.NewQuery("workflowexecution").Filter("started_at <", timestamp)
var workflowExecutions []WorkflowExecution
_, err = dbclient.GetAll(ctx, q, &workflowExecutions)
if err != nil {
log.Printf("Error getting workflowexec: %s", err)
resp.WriteHeader(401)
resp.Write([]byte(fmt.Sprintf(`{"success": false, "reason": "Failed getting all workflowexecutions"}`)))
return
}
log.Println(len(workflowExecutions))
resp.WriteHeader(200)
resp.Write([]byte("OK"))
}
func handleExecution(id string, workflow Workflow, request *http.Request) (WorkflowExecution, string, error) {
ctx := context.Background()
if workflow.ID == "" || workflow.ID != id {
tmpworkflow, err := getWorkflow(ctx, id)
if err != nil {
log.Printf("Failed getting the workflow locally: %s", err)
return WorkflowExecution{}, "Failed getting workflow", err
}
workflow = *tmpworkflow
}
if len(workflow.Actions) == 0 {
workflow.Actions = []Action{}
}
if len(workflow.Branches) == 0 {
workflow.Branches = []Branch{}
}
if len(workflow.Triggers) == 0 {
workflow.Triggers = []Trigger{}
}
if len(workflow.Errors) == 0 {
workflow.Errors = []string{}
}
if !workflow.IsValid {
log.Printf("Stopped execution as workflow %s is not valid.", workflow.ID)
return WorkflowExecution{}, fmt.Sprintf(`workflow %s is invalid`, workflow.ID), errors.New("Failed getting workflow")
}
workflowBytes, err := json.Marshal(workflow)
if err != nil {
log.Printf("Failed workflow unmarshal in execution: %s", err)
return WorkflowExecution{}, "", err
}
//log.Println(workflow)
var workflowExecution WorkflowExecution
err = json.Unmarshal(workflowBytes, &workflowExecution.Workflow)
if err != nil {
log.Printf("Failed execution unmarshaling: %s", err)
return WorkflowExecution{}, "Failed unmarshal during execution", err
}
makeNew := true
if request.Method == "POST" {
body, err := ioutil.ReadAll(request.Body)
if err != nil {
log.Printf("Failed request POST read: %s", err)
return WorkflowExecution{}, "Failed getting body", err
}
// This one doesn't really matter.
var execution ExecutionRequest
err = json.Unmarshal(body, &execution)
if err != nil {
//log.Printf("Failed execution POST unmarshaling - still continue: %s", err)
//return WorkflowExecution{}, "", err
}
if execution.Start == "" && len(body) > 0 {
execution.ExecutionArgument = string(body)
}
// FIXME - this should have "execution_argument" from executeWorkflow frontend
if len(execution.ExecutionArgument) > 0 {
workflowExecution.ExecutionArgument = execution.ExecutionArgument
}
//log.Printf("Execution data: %#v", execution)
if len(execution.Start) == 36 {
log.Printf("SHOULD START ON NODE %s", execution.Start)
workflow.Start = execution.Start
}
if len(execution.ExecutionId) == 36 {
workflowExecution.ExecutionId = execution.ExecutionId
} else {
sessionToken := <KEY>()
workflowExecution.ExecutionId = sessionToken.String()
}
} else {
// Check for parameters of start and ExecutionId
start, startok := request.URL.Query()["start"]
answer, answerok := request.URL.Query()["answer"]
referenceId, referenceok := request.URL.Query()["reference_execution"]
if answerok && referenceok {
// If answer is false, reference execution with result
log.Printf("Answer is OK AND reference is OK!")
if answer[0] == "false" {
log.Printf("Should update reference and return, no need for further execution!")
// Get the reference execution
oldExecution, err := getWorkflowExecution(ctx, referenceId[0])
if err != nil {
log.Printf("Failed getting execution (execution) %s: %s", referenceId[0], err)
return WorkflowExecution{}, fmt.Sprintf("Failed getting execution ID %s because it doesn't exist.", referenceId[0]), err
}
if oldExecution.Workflow.ID != id {
log.Println("Wrong workflowid!")
return WorkflowExecution{}, fmt.Sprintf("Bad ID %s", referenceId), errors.New("Bad ID")
}
newResults := []ActionResult{}
//log.Printf("%#v", oldExecution.Results)
for _, result := range oldExecution.Results {
log.Printf("%s - %s", result.Action.ID, start[0])
if result.Action.ID == start[0] {
note, noteok := request.URL.Query()["note"]
if noteok {
result.Result = fmt.Sprintf("User note: %s", note[0])
} else {
result.Result = fmt.Sprintf("User clicked %s", answer[0])
}
// Stopping the whole thing
result.CompletedAt = int64(time.Now().Unix())
result.Status = "ABORTED"
oldExecution.Status = result.Status
oldExecution.Result = result.Result
oldExecution.LastNode = result.Action.ID
}
newResults = append(newResults, result)
}
oldExecution.Results = newResults
err = setWorkflowExecution(ctx, *oldExecution)
if err != nil {
log.Printf("Error saving workflow execution actionresult setting: %s", err)
return WorkflowExecution{}, fmt.Sprintf("Failed setting workflowexecution actionresult in execution: %s", err), err
}
return WorkflowExecution{}, "", nil
}
}
if referenceok {
log.Printf("Handling an old execution continuation!")
// Will use the old name, but still continue with NEW ID
oldExecution, err := getWorkflowExecution(ctx, referenceId[0])
if err != nil {
log.Printf("Failed getting execution (execution) %s: %s", referenceId[0], err)
return WorkflowExecution{}, fmt.Sprintf("Failed getting execution ID %s because it doesn't exist.", referenceId[0]), err
}
workflowExecution = *oldExecution
}
if len(workflowExecution.ExecutionId) == 0 {
sessionToken := uuid.NewV4()
workflowExecution.ExecutionId = sessionToken.String()
} else {
log.Printf("Using the same executionId as before: %s", workflowExecution.ExecutionId)
makeNew = false
}
if startok {
log.Printf("Setting start to %s based on query!", start[0])
workflowExecution.Workflow.Start = start[0]
workflowExecution.Start = start[0]
}
}
// FIXME - regex uuid, and check if already exists?
if len(workflowExecution.ExecutionId) != 36 {
log.Printf("Invalid uuid: %s", workflowExecution.ExecutionId)
return WorkflowExecution{}, "Invalid uuid", err
}
// FIXME - find owner of workflow
// FIXME - get the actual workflow itself and build the request
// MAYBE: Don't send the workflow within the pubsub, as this requires more data to be sent
// Check if a worker already exists for company, else run one with:
// locations, project IDs and subscription names
// When app is executed:
// Should update with status execution (somewhere), which will trigger the next node
// IF action.type == internal, we need the internal watcher to be running and executing
// This essentially means the WORKER has to be the responsible party for new actions in the INTERNAL landscape
// Results are ALWAYS posted back to cloud@execution_id?
if makeNew {
workflowExecution.Type = "workflow"
//workflowExecution.Stream = "tmp"
//workflowExecution.WorkflowQueue = "tmp"
//workflowExecution.SubscriptionNameNodestream = "testcompany-nodestream"
workflowExecution.ProjectId = gceProject
workflowExecution.Locations = []string{"europe-west2"}
workflowExecution.WorkflowId = workflow.ID
workflowExecution.StartedAt = int64(time.Now().Unix())
workflowExecution.CompletedAt = 0
workflowExecution.Authorization = uuid.NewV4().String()
// Status for the entire workflow.
workflowExecution.Status = "EXECUTING"
}
// Local authorization for this single workflow used in workers.
// FIXME: Used for cloud
//mappedData, err := json.Marshal(workflowExecution)
//if err != nil {
// log.Printf("Failed workflowexecution marshalling: %s", err)
// resp.WriteHeader(http.StatusInternalServerError)
// resp.Write([]byte(`{"success": false}`))
// return
//}
//log.Println(string(mappedData))
topic := "workflows"
// FIXME - remove this?
newActions := []Action{}
for _, action := range workflowExecution.Workflow.Actions {
action.LargeImage = ""
//log.Println(action.Environment)
if action.Environment == "" {
return WorkflowExecution{}, fmt.Sprintf("Environment is not defined for %s", action.Name), errors.New("Environment not defined!")
}
newActions = append(newActions, action)
}
workflowExecution.Workflow.Actions = newActions
//log.Printf("%#v", workflowExecution.Workflow.Actions)
// Verification for execution environments
onpremExecution := false
environments := []string{}
for _, action := range workflowExecution.Workflow.Actions {
if action.Environment != cloudname {
found := false
for _, env := range environments {
if env == action.Environment {
found = true
break
}
}
if !found {
environments = append(environments, action.Environment)
}
onpremExecution = true
}
}
err = setWorkflowExecution(ctx, workflowExecution)
if err != nil {
log.Printf("Error saving workflow execution for updates %s: %s", topic, err)
return WorkflowExecution{}, "Failed getting workflowexecution", err
}
// Adds queue for onprem execution
// FIXME - add specifics to executionRequest, e.g. specific environment (can run multi onprem)
if onpremExecution {
// FIXME - tmp name based on future companyname-companyId
for _, environment := range environments {
log.Printf("EXECUTION: %s should execute onprem with execution environment \"%s\"", workflowExecution.ExecutionId, environment)
executionRequest := ExecutionRequest{
ExecutionId: workflowExecution.ExecutionId,
WorkflowId: workflowExecution.Workflow.ID,
Authorization: workflowExecution.Authorization,
Environments: environments,
}
executionRequestWrapper, err := getWorkflowQueue(ctx, environment)
if err != nil {
executionRequestWrapper = ExecutionRequestWrapper{
Data: []ExecutionRequest{executionRequest},
}
} else {
executionRequestWrapper.Data = append(executionRequestWrapper.Data, executionRequest)
}
//log.Printf("Execution request: %#v", executionRequest)
err = setWorkflowQueue(ctx, executionRequestWrapper, environment)
if err != nil {
log.Printf("Failed adding to db: %s", err)
}
}
}
err = increaseStatisticsField(ctx, "workflow_executions", workflow.ID, 1)
if err != nil {
log.Printf("Failed to increase stats execution stats: %s", err)
}
return workflowExecution, "", nil
}
func executeWorkflow(resp http.ResponseWriter, request *http.Request) {
cors := handleCors(resp, request)
if cors {
return
}
user, err := handleApiAuthentication(resp, request)
if err != nil {
log.Printf("Api authentication failed in execute workflow: %s", err)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
location := strings.Split(request.URL.String(), "/")
var fileId string
if location[1] == "api" {
if len(location) <= 4 {
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
fileId = location[4]
}
if len(fileId) != 36 {
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false, "reason": "Workflow ID to execute is not valid"}`))
return
}
//memcacheName := fmt.Sprintf("%s_%s", user.Username, fileId)
ctx := context.Background()
workflow, err := getWorkflow(ctx, fileId)
if err != nil {
log.Printf("Failed getting the workflow locally: %s", err)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
// FIXME - have a check for org etc too..
// FIXME - admin check like this? idk
if user.Id != workflow.Owner && user.Role != "admin" && user.Role != "scheduler" && user.Role != fmt.Sprintf("workflow_%s", fileId) {
log.Printf("Wrong user (%s) for workflow %s (execute)", user.Username, workflow.ID)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
workflowExecution, executionResp, err := handleExecution(fileId, *workflow, request)
if err == nil {
resp.WriteHeader(200)
resp.Write([]byte(fmt.Sprintf(`{"success": true, "execution_id": "%s", "authorization": "%s"}`, workflowExecution.ExecutionId, workflowExecution.Authorization)))
return
}
resp.WriteHeader(500)
resp.Write([]byte(fmt.Sprintf(`{"success": false, "reason": "%s"}`, executionResp)))
}
func stopSchedule(resp http.ResponseWriter, request *http.Request) {
cors := handleCors(resp, request)
if cors {
return
}
user, err := handleApiAuthentication(resp, request)
if err != nil {
log.Printf("Api authentication failed in schedule workflow: %s", err)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
location := strings.Split(request.URL.String(), "/")
var fileId string
var scheduleId string
if location[1] == "api" {
if len(location) <= 6 {
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
fileId = location[4]
scheduleId = location[6]
}
if len(fileId) != 36 {
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false, "reason": "Workflow ID to stop schedule is not valid"}`))
return
}
if len(scheduleId) != 36 {
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false, "reason": "Schedule ID not valid"}`))
return
}
ctx := context.Background()
workflow, err := getWorkflow(ctx, fileId)
if err != nil {
log.Printf("Failed getting the workflow locally: %s", err)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
// FIXME - have a check for org etc too..
// FIXME - admin check like this? idk
if user.Id != workflow.Owner && user.Role != "admin" && user.Role != "scheduler" {
log.Printf("Wrong user (%s) for workflow %s (stop schedule)", user.Username, workflow.ID)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
if len(workflow.Actions) == 0 {
workflow.Actions = []Action{}
}
if len(workflow.Branches) == 0 {
workflow.Branches = []Branch{}
}
if len(workflow.Triggers) == 0 {
workflow.Triggers = []Trigger{}
}
if len(workflow.Errors) == 0 {
workflow.Errors = []string{}
}
err = deleteSchedule(ctx, scheduleId)
if err != nil {
if strings.Contains(err.Error(), "Job not found") {
resp.WriteHeader(200)
resp.Write([]byte(fmt.Sprintf(`{"success": true}`)))
} else {
resp.WriteHeader(401)
resp.Write([]byte(fmt.Sprintf(`{"success": false, "reason": "Failed stopping schedule"}`)))
}
return
}
resp.WriteHeader(200)
resp.Write([]byte(fmt.Sprintf(`{"success": true}`)))
return
}
func stopScheduleGCP(resp http.ResponseWriter, request *http.Request) {
cors := handleCors(resp, request)
if cors {
return
}
user, err := handleApiAuthentication(resp, request)
if err != nil {
log.Printf("Api authentication failed in schedule workflow: %s", err)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
location := strings.Split(request.URL.String(), "/")
var fileId string
var scheduleId string
if location[1] == "api" {
if len(location) <= 6 {
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
fileId = location[4]
scheduleId = location[6]
}
if len(fileId) != 36 {
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false, "reason": "Workflow ID to stop schedule is not valid"}`))
return
}
if len(scheduleId) != 36 {
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false, "reason": "Schedule ID not valid"}`))
return
}
ctx := context.Background()
workflow, err := getWorkflow(ctx, fileId)
if err != nil {
log.Printf("Failed getting the workflow locally: %s", err)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
// FIXME - have a check for org etc too..
// FIXME - admin check like this? idk
if user.Id != workflow.Owner && user.Role != "admin" && user.Role != "scheduler" {
log.Printf("Wrong user (%s) for workflow %s (stop schedule)", user.Username, workflow.ID)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
if len(workflow.Actions) == 0 {
workflow.Actions = []Action{}
}
if len(workflow.Branches) == 0 {
workflow.Branches = []Branch{}
}
if len(workflow.Triggers) == 0 {
workflow.Triggers = []Trigger{}
}
if len(workflow.Errors) == 0 {
workflow.Errors = []string{}
}
err = deleteSchedule(ctx, scheduleId)
if err != nil {
if strings.Contains(err.Error(), "Job not found") {
resp.WriteHeader(200)
resp.Write([]byte(fmt.Sprintf(`{"success": true}`)))
} else {
resp.WriteHeader(401)
resp.Write([]byte(fmt.Sprintf(`{"success": false, "reason": "Failed stopping schedule"}`)))
}
return
}
resp.WriteHeader(200)
resp.Write([]byte(fmt.Sprintf(`{"success": true}`)))
return
}
func deleteSchedule(ctx context.Context, id string) error {
log.Printf("Should stop schedule %s!", id)
//newscheduler "github.com/carlescere/scheduler"
log.Printf("Schedules: %#v", scheduledJobs)
if value, exists := scheduledJobs[id]; exists {
log.Printf("STOP THIS ONE: %s", value)
// Looks like this does the trick? Hurr
value.Lock()
err := DeleteKey(ctx, "schedules", id)
if err != nil {
log.Printf("Failed to delete schedule: %s", err)
return err
}
} else {
// FIXME - allow it to kind of stop anyway?
return errors.New("Can't find the schedule.")
}
return nil
}
func deleteScheduleGCP(ctx context.Context, id string) error {
c, err := scheduler.NewCloudSchedulerClient(ctx)
if err != nil {
log.Printf("%s", err)
return err
}
req := &schedulerpb.DeleteJobRequest{
Name: fmt.Sprintf("projects/%s/locations/europe-west2/jobs/schedule_%s", gceProject, id),
}
err = c.DeleteJob(ctx, req)
if err != nil {
log.Printf("%s", err)
return err
}
return nil
}
func scheduleWorkflow(resp http.ResponseWriter, request *http.Request) {
cors := handleCors(resp, request)
if cors {
return
}
user, err := handleApiAuthentication(resp, request)
if err != nil {
log.Printf("Api authentication failed in schedule workflow: %s", err)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
location := strings.Split(request.URL.String(), "/")
var fileId string
if location[1] == "api" {
if len(location) <= 4 {
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
fileId = location[4]
}
if len(fileId) != 36 {
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false, "reason": "Workflow ID to start schedule is not valid"}`))
return
}
ctx := context.Background()
workflow, err := getWorkflow(ctx, fileId)
if err != nil {
log.Printf("Failed getting the workflow locally: %s", err)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
// FIXME - have a check for org etc too..
// FIXME - admin check like this? idk
if user.Id != workflow.Owner && user.Role != "admin" && user.Role != "scheduler" {
log.Printf("Wrong user (%s) for workflow %s", user.Username, workflow.ID)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
if len(workflow.Actions) == 0 {
workflow.Actions = []Action{}
}
if len(workflow.Branches) == 0 {
workflow.Branches = []Branch{}
}
if len(workflow.Triggers) == 0 {
workflow.Triggers = []Trigger{}
}
if len(workflow.Errors) == 0 {
workflow.Errors = []string{}
}
body, err := ioutil.ReadAll(request.Body)
if err != nil {
log.Printf("Failed hook unmarshaling: %s", err)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
var schedule Schedule
err = json.Unmarshal(body, &schedule)
if err != nil {
log.Printf("Failed schedule POST unmarshaling: %s", err)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
if len(schedule.Id) != 36 {
log.Printf("ID length is not 36 for schedule: %s", err)
resp.WriteHeader(http.StatusInternalServerError)
resp.Write([]byte(`{"success": false, "reason": "Invalid data"}`))
return
}
if len(schedule.Name) == 0 {
log.Printf("Empty name.")
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false, "reason": "Schedule name can't be empty"}`))
return
}
if len(schedule.Frequency) == 0 {
log.Printf("Empty frequency.")
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false, "reason": "Frequency can't be empty"}`))
return
}
scheduleArg, err := json.Marshal(schedule.ExecutionArgument)
if err != nil {
log.Printf("Failed scheduleArg marshal: %s", err)
resp.WriteHeader(http.StatusInternalServerError)
resp.Write([]byte(`{"success": false}`))
return
}
log.Printf("Schedulearg: %s", string(scheduleArg))
err = createSchedule(
ctx,
schedule.Id,
workflow.ID,
schedule.Name,
schedule.Frequency,
scheduleArg,
)
// FIXME - real error message lol
if err != nil {
log.Printf("Failed creating schedule: %s", err)
resp.WriteHeader(401)
resp.Write([]byte(fmt.Sprintf(`{"success": false, "reason": "Invalid argument. Try cron */15 * * * *"}`)))
return
}
workflow.Schedules = append(workflow.Schedules, schedule)
err = setWorkflow(ctx, *workflow, workflow.ID)
if err != nil {
log.Printf("Failed setting workflow for schedule: %s", err)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
resp.WriteHeader(200)
resp.Write([]byte(fmt.Sprintf(`{"success": true}`)))
return
}
// FIXME - add to actual database etc
func getSpecificWorkflow(resp http.ResponseWriter, request *http.Request) {
cors := handleCors(resp, request)
if cors {
return
}
user, err := handleApiAuthentication(resp, request)
if err != nil {
log.Printf("Api authentication failed in getting specific workflow: %s", err)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
location := strings.Split(request.URL.String(), "/")
var fileId string
if location[1] == "api" {
if len(location) <= 4 {
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
fileId = location[4]
}
if strings.Contains(fileId, "?") {
fileId = strings.Split(fileId, "?")[0]
}
if len(fileId) != 36 {
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false, "reason": "Workflow ID when getting workflow is not valid"}`))
return
}
ctx := context.Background()
//memcacheName := fmt.Sprintf("%s_%s", user.Username, fileId)
//if item, err := memcache.Get(ctx, memcacheName); err == memcache.ErrCacheMiss {
// // Not in cache
// log.Printf("User %s not in cache.", memcacheName)
//} else if err != nil {
// log.Printf("Error getting item: %v", err)
//} else {
// log.Printf("Got workflow %s from cache", fileId)
// // FIXME - verify if value is ok? Can unmarshal etc.
// resp.WriteHeader(200)
// resp.Write(item.Value)
// return
//}
workflow, err := getWorkflow(ctx, fileId)
if err != nil {
log.Printf("Workflow %s doesn't exist.", fileId)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false, "reason": "Item already exists."}`))
return
}
// CHECK orgs of user, or if user is owner
// FIXME - add org check too, and not just owner
// Check workflow.Sharing == private / public / org too
if user.Id != workflow.Owner && user.Role != "admin" {
log.Printf("Wrong user (%s) for workflow %s (get workflow)", user.Username, workflow.ID)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
if len(workflow.Actions) == 0 {
workflow.Actions = []Action{}
}
if len(workflow.Branches) == 0 {
workflow.Branches = []Branch{}
}
if len(workflow.Triggers) == 0 {
workflow.Triggers = []Trigger{}
}
if len(workflow.Errors) == 0 {
workflow.Errors = []string{}
}
// Only required for individuals I think
//newactions := []Action{}
//for _, item := range workflow.Actions {
// item.LargeImage = ""
// item.SmallImage = ""
// newactions = append(newactions, item)
//}
//workflow.Actions = newactions
//newtriggers := []Trigger{}
//for _, item := range workflow.Triggers {
// item.LargeImage = ""
// newtriggers = append(newtriggers, item)
//}
//workflow.Triggers = newtriggers
body, err := json.Marshal(workflow)
if err != nil {
log.Printf("Failed workflow GET marshalling: %s", err)
resp.WriteHeader(http.StatusInternalServerError)
resp.Write([]byte(`{"success": false}`))
return
}
//item := &memcache.Item{
// Key: memcacheName,
// Value: body,
// Expiration: time.Minute * 60,
//}
//if err := memcache.Add(ctx, item); err == memcache.ErrNotStored {
// if err := memcache.Set(ctx, item); err != nil {
// log.Printf("Error setting item: %v", err)
// }
//} else if err != nil {
// log.Printf("error adding item: %v", err)
//} else {
// //log.Printf("Set cache for %s", item.Key)
//}
resp.WriteHeader(200)
resp.Write(body)
}
//func setWorkflowExecutionFS(ctx context.Context, reference string, workflowExecution WorkflowExecution) error {
// if len(workflowExecution.ExecutionId) == 0 {
// log.Printf("Workflowexeciton executionId can't be empty.")
// return errors.New("ExecutionId can't be empty.")
// }
//
// firestoreClient, err := firestore.NewClient(ctx, shuffleTestProject, option.WithCredentialsFile(shuffleTestPath))
// if err != nil {
// return err
// }
//
// executionRef := firestoreClient.Doc(reference)
// _, err = executionRef.Set(ctx, workflowExecution)
// if err != nil {
// return err
// }
//
// return nil
//}
func setWorkflowExecution(ctx context.Context, workflowExecution WorkflowExecution) error {
if len(workflowExecution.ExecutionId) == 0 {
log.Printf("Workflowexeciton executionId can't be empty.")
return errors.New("ExecutionId can't be empty.")
}
key := datastore.NameKey("workflowexecution", workflowExecution.ExecutionId, nil)
// New struct, to not add body, author etc
if _, err := dbclient.Put(ctx, key, &workflowExecution); err != nil {
log.Printf("Error adding workflow_execution: %s", err)
return err
}
return nil
}
func getWorkflowExecution(ctx context.Context, id string) (*WorkflowExecution, error) {
key := datastore.NameKey("workflowexecution", strings.ToLower(id), nil)
workflowExecution := &WorkflowExecution{}
if err := dbclient.Get(ctx, key, workflowExecution); err != nil {
return &WorkflowExecution{}, err
}
return workflowExecution, nil
}
func getApp(ctx context.Context, id string) (*WorkflowApp, error) {
key := datastore.NameKey("workflowapp", strings.ToLower(id), nil)
workflowApp := &WorkflowApp{}
if err := dbclient.Get(ctx, key, workflowApp); err != nil {
return &WorkflowApp{}, err
}
return workflowApp, nil
}
func getWorkflow(ctx context.Context, id string) (*Workflow, error) {
key := datastore.NameKey("workflow", strings.ToLower(id), nil)
workflow := &Workflow{}
if err := dbclient.Get(ctx, key, workflow); err != nil {
return &Workflow{}, err
}
return workflow, nil
}
func getAllWorkflows(ctx context.Context) ([]Workflow, error) {
var allworkflows []Workflow
q := datastore.NewQuery("workflow")
_, err := dbclient.GetAll(ctx, q, &allworkflows)
if err != nil {
return []Workflow{}, err
}
return allworkflows, nil
}
// Hmm, so I guess this should use uuid :(
// Consistency PLX
func setWorkflow(ctx context.Context, workflow Workflow, id string) error {
key := datastore.NameKey("workflow", id, nil)
// New struct, to not add body, author etc
if _, err := dbclient.Put(ctx, key, &workflow); err != nil {
log.Printf("Error adding workflow: %s", err)
return err
}
return nil
}
func deleteWorkflowApp(resp http.ResponseWriter, request *http.Request) {
cors := handleCors(resp, request)
if cors {
return
}
user, userErr := handleApiAuthentication(resp, request)
if userErr != nil {
log.Printf("Api authentication failed in edit workflow: %s", userErr)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
location := strings.Split(request.URL.String(), "/")
log.Printf("%#v", location)
var fileId string
if location[1] == "api" {
if len(location) <= 4 {
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
fileId = location[4]
}
ctx := context.Background()
log.Printf("ID: %s", fileId)
app, err := getApp(ctx, fileId)
if err != nil {
log.Printf("Error getting app %s: %s", app.Name, err)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
// FIXME - check whether it's in use and maybe restrict again for later?
// FIXME - actually delete other than private apps too..
private := false
if app.Downloaded {
log.Printf("Deleting downloaded app (authenticated users can do this)")
} else if user.Id != app.Owner && user.Role != "admin" {
log.Printf("Wrong user (%s) for app %s (delete)", user.Username, app.Name)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
} else {
private = true
}
// Not really deleting it, just removing from user cache
if private {
log.Printf("Deleting private app")
var privateApps []WorkflowApp
for _, item := range user.PrivateApps {
log.Println(item.ID, fileId)
if item.ID == fileId {
continue
}
privateApps = append(privateApps, item)
}
user.PrivateApps = privateApps
err = setUser(ctx, &user)
if err != nil {
log.Printf("Failed removing %s app for user %s: %s", app.Name, user.Username, err)
resp.WriteHeader(401)
resp.Write([]byte(fmt.Sprintf(`{"success": true"}`)))
return
}
} else {
log.Printf("Deleting public app")
err = DeleteKey(ctx, "workflowapp", fileId)
if err != nil {
log.Printf("Failed deleting workflowapp")
resp.WriteHeader(401)
resp.Write([]byte(fmt.Sprintf(`{"success": false, "reason": "Failed deleting workflow app"}`)))
return
}
}
err = increaseStatisticsField(ctx, "total_apps_deleted", fileId, 1)
if err != nil {
log.Printf("Failed to increase total apps loaded stats: %s", err)
}
//err = memcache.Delete(request.Context(), sessionToken)
resp.WriteHeader(200)
resp.Write([]byte(`{"success": true}`))
}
func getWorkflowAppConfig(resp http.ResponseWriter, request *http.Request) {
cors := handleCors(resp, request)
if cors {
return
}
user, userErr := handleApiAuthentication(resp, request)
if userErr != nil {
log.Printf("Api authentication failed in edit workflow: %s", userErr)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
location := strings.Split(request.URL.String(), "/")
log.Printf("%#v", location)
var fileId string
if location[1] == "api" {
if len(location) <= 4 {
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
fileId = location[4]
}
ctx := context.Background()
app, err := getApp(ctx, fileId)
if err != nil {
log.Printf("Error getting app: %s", app.Name)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
if user.Id != app.Owner && user.Role != "admin" {
log.Printf("Wrong user (%s) for app %s", user.Username, app.Name)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
parsedApi, err := getOpenApiDatastore(ctx, fileId)
if err != nil {
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
parsedApi.Success = true
data, err := json.Marshal(parsedApi)
if err != nil {
resp.WriteHeader(422)
resp.Write([]byte(fmt.Sprintf(`{"success": false, "reason": "Failed marshalling new parsed swagger: %s"}`, err)))
return
}
resp.WriteHeader(200)
resp.Write(data)
}
func getWorkflowApps(resp http.ResponseWriter, request *http.Request) {
cors := handleCors(resp, request)
if cors {
return
}
// FIXME - set this to be per user IF logged in, as there might exist private and public
//memcacheName := "all_apps"
ctx := context.Background()
// Just need to be logged in
// FIXME - need to be logged in?
user, userErr := handleApiAuthentication(resp, request)
if userErr != nil {
log.Printf("Api authentication failed in get all apps: %s", userErr)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
//if item, err := memcache.Get(ctx, memcacheName); err == memcache.ErrCacheMiss {
// // Not in cache
// log.Printf("Apps not in cache.")
//} else if err != nil {
// log.Printf("Error getting item: %v", err)
//} else {
// // FIXME - verify if value is ok? Can unmarshal etc.
// allApps := item.Value
// if userErr == nil && len(user.PrivateApps) > 0 {
// var parsedApps []WorkflowApp
// err = json.Unmarshal(allApps, &parsedApps)
// if err == nil {
// log.Printf("Shouldve added %d apps", len(user.PrivateApps))
// user.PrivateApps = append(user.PrivateApps, parsedApps...)
// tmpApps, err := json.Marshal(user.PrivateApps)
// if err == nil {
// allApps = tmpApps
// }
// }
// }
// resp.WriteHeader(200)
// resp.Write(allApps)
// return
//}
workflowapps, err := getAllWorkflowApps(ctx)
if err != nil {
log.Printf("Failed getting apps: %s", err)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
//log.Printf("Length: %d", len(workflowapps))
// FIXME - this is really garbage, but is here to protect again null values etc.
newapps := []WorkflowApp{}
baseApps := []WorkflowApp{}
if len(user.PrivateApps) > 0 {
newapps = append(newapps, user.PrivateApps...)
}
for _, workflowapp := range workflowapps {
if !workflowapp.Sharing {
continue
}
//workflowapp.Environment = "cloud"
newactions := []WorkflowAppAction{}
for _, action := range workflowapp.Actions {
//action.Environment = workflowapp.Environment
if len(action.Parameters) == 0 {
action.Parameters = []WorkflowAppActionParameter{}
}
newactions = append(newactions, action)
}
workflowapp.Actions = newactions
newapps = append(newapps, workflowapp)
baseApps = append(baseApps, workflowapp)
}
// Double unmarshal because of user apps
newbody, err := json.Marshal(newapps)
//newbody, err := json.Marshal(workflowapps)
if err != nil {
log.Printf("Failed unmarshalling all newapps: %s", err)
resp.WriteHeader(401)
resp.Write([]byte(fmt.Sprintf(`{"success": false, "reason": "Failed unpacking workflow apps"}`)))
return
}
//basebody, err := json.Marshal(baseApps)
////newbody, err := json.Marshal(workflowapps)
//if err != nil {
// log.Printf("Failed unmarshalling all baseapps: %s", err)
// resp.WriteHeader(401)
// resp.Write([]byte(fmt.Sprintf(`{"success": false, "reason": "Failed unpacking workflow apps"}`)))
// return
//}
// Refreshed every hour
//item := &memcache.Item{
// Key: memcacheName,
// Value: basebody,
// Expiration: time.Minute * 60,
//}
//if err := memcache.Add(ctx, item); err == memcache.ErrNotStored {
// if err := memcache.Set(ctx, item); err != nil {
// log.Printf("Error setting item: %v", err)
// }
//} else if err != nil {
// log.Printf("error adding item: %v", err)
//} else {
// log.Printf("Set cache for %s", item.Key)
//}
//log.Println(string(body))
//log.Println(string(newbody))
resp.WriteHeader(200)
resp.Write(newbody)
}
// Bad check for workflowapps :)
// FIXME - use tags and struct reflection
func checkWorkflowApp(workflowApp WorkflowApp) error {
// Validate fields
if workflowApp.Name == "" {
return errors.New("App field name doesn't exist")
}
if workflowApp.Description == "" {
return errors.New("App field description doesn't exist")
}
if workflowApp.AppVersion == "" {
return errors.New("App field app_version doesn't exist")
}
if workflowApp.ContactInfo.Name == "" {
return errors.New("App field contact_info.name doesn't exist")
}
return nil
}
func handleGetfile(resp http.ResponseWriter, request *http.Request) ([]byte, error) {
// Upload file here first
request.ParseMultipartForm(32 << 20)
file, _, err := request.FormFile("file")
if err != nil {
log.Printf("Error parsing: %s", err)
return []byte{}, err
}
defer file.Close()
buf := bytes.NewBuffer(nil)
if _, err := io.Copy(buf, file); err != nil {
return []byte{}, err
}
return buf.Bytes(), nil
}
func validateAppInput(resp http.ResponseWriter, request *http.Request) {
cors := handleCors(resp, request)
if cors {
return
}
// Just need to be logged in
// FIXME - should have some permissions?
_, err := handleApiAuthentication(resp, request)
if err != nil {
log.Printf("Api authentication failed in set new app: %s", err)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
filebytes, err := handleGetfile(resp, request)
if err != nil {
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
kind, err := filetype.Match(filebytes)
if err != nil {
log.Printf("Failed parsing filetype")
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
//fmt.Printf("File type: %s. MIME: %s\n", kind.Extension, kind.MIME.Value)
if kind == filetype.Unknown {
fmt.Println("Unknown file type")
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
if kind.MIME.Value != "application/zip" {
fmt.Println("Not zip, can't unzip")
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
// FIXME - validate folderstructure, Dockerfile, python scripts, api.yaml, requirements.txt, src/
resp.WriteHeader(200)
resp.Write([]byte(fmt.Sprintf(`{"success": true}`)))
}
// Deploy to google cloud function :)
func deployCloudFunctionPython(ctx context.Context, name, localization, applocation string, environmentVariables map[string]string) error {
service, err := cloudfunctions.NewService(ctx)
if err != nil {
return err
}
// ProjectsLocationsListCall
projectsLocationsFunctionsService := cloudfunctions.NewProjectsLocationsFunctionsService(service)
location := fmt.Sprintf("projects/%s/locations/%s", gceProject, localization)
functionName := fmt.Sprintf("%s/functions/%s", location, name)
cloudFunction := &cloudfunctions.CloudFunction{
AvailableMemoryMb: 128,
EntryPoint: "authorization",
EnvironmentVariables: environmentVariables,
HttpsTrigger: &cloudfunctions.HttpsTrigger{},
MaxInstances: 0,
Name: functionName,
Runtime: "python37",
SourceArchiveUrl: applocation,
}
//getCall := projectsLocationsFunctionsService.Get(fmt.Sprintf("%s/functions/function-5", location))
//resp, err := getCall.Do()
createCall := projectsLocationsFunctionsService.Create(location, cloudFunction)
_, err = createCall.Do()
if err != nil {
log.Printf("Failed creating new function. SKIPPING patch, as it probably already exists: %s", err)
// FIXME - have patching code or nah?
createCall := projectsLocationsFunctionsService.Patch(fmt.Sprintf("%s/functions/%s", location, name), cloudFunction)
_, err = createCall.Do()
if err != nil {
log.Println("Failed patching function")
return err
}
log.Printf("Successfully patched %s to %s", name, localization)
} else {
log.Printf("Successfully deployed %s to %s", name, localization)
}
// FIXME - use response to define the HTTPS entrypoint. It's default to an easy one tho
return nil
}
// Deploy to google cloud function :)
func deployCloudFunctionGo(ctx context.Context, name, localization, applocation string, environmentVariables map[string]string) error {
service, err := cloudfunctions.NewService(ctx)
if err != nil {
return err
}
// ProjectsLocationsListCall
projectsLocationsFunctionsService := cloudfunctions.NewProjectsLocationsFunctionsService(service)
location := fmt.Sprintf("projects/%s/locations/%s", gceProject, localization)
functionName := fmt.Sprintf("%s/functions/%s", location, name)
cloudFunction := &cloudfunctions.CloudFunction{
AvailableMemoryMb: 128,
EntryPoint: "Authorization",
EnvironmentVariables: environmentVariables,
HttpsTrigger: &cloudfunctions.HttpsTrigger{},
MaxInstances: 1,
Name: functionName,
Runtime: "go111",
SourceArchiveUrl: applocation,
}
//getCall := projectsLocationsFunctionsService.Get(fmt.Sprintf("%s/functions/function-5", location))
//resp, err := getCall.Do()
createCall := projectsLocationsFunctionsService.Create(location, cloudFunction)
_, err = createCall.Do()
if err != nil {
log.Println("Failed creating new function. Attempting patch, as it might exist already")
createCall := projectsLocationsFunctionsService.Patch(fmt.Sprintf("%s/functions/%s", location, name), cloudFunction)
_, err = createCall.Do()
if err != nil {
log.Println("Failed patching function")
return err
}
log.Printf("Successfully patched %s to %s", name, localization)
} else {
log.Printf("Successfully deployed %s to %s", name, localization)
}
// FIXME - use response to define the HTTPS entrypoint. It's default to an easy one tho
return nil
}
// Deploy to google cloud function :)
func deployWebhookFunction(ctx context.Context, name, localization, applocation string, environmentVariables map[string]string) error {
service, err := cloudfunctions.NewService(ctx)
if err != nil {
return err
}
// ProjectsLocationsListCall
projectsLocationsFunctionsService := cloudfunctions.NewProjectsLocationsFunctionsService(service)
location := fmt.Sprintf("projects/%s/locations/%s", gceProject, localization)
functionName := fmt.Sprintf("%s/functions/%s", location, name)
cloudFunction := &cloudfunctions.CloudFunction{
AvailableMemoryMb: 128,
EntryPoint: "Authorization",
EnvironmentVariables: environmentVariables,
HttpsTrigger: &cloudfunctions.HttpsTrigger{},
MaxInstances: 1,
Name: functionName,
Runtime: "go111",
SourceArchiveUrl: applocation,
}
//getCall := projectsLocationsFunctionsService.Get(fmt.Sprintf("%s/functions/function-5", location))
//resp, err := getCall.Do()
createCall := projectsLocationsFunctionsService.Create(location, cloudFunction)
_, err = createCall.Do()
if err != nil {
log.Println("Failed creating new function. Attempting patch, as it might exist already")
createCall := projectsLocationsFunctionsService.Patch(fmt.Sprintf("%s/functions/%s", location, name), cloudFunction)
_, err = createCall.Do()
if err != nil {
log.Println("Failed patching function")
return err
}
log.Printf("Successfully patched %s to %s", name, localization)
} else {
log.Printf("Successfully deployed %s to %s", name, localization)
}
// FIXME - use response to define the HTTPS entrypoint. It's default to an easy one tho
return nil
}
func loadExistingApps(resp http.ResponseWriter, request *http.Request) {
cors := handleCors(resp, request)
if cors {
return
}
// Just need to be logged in
// FIXME - should have some permissions?
_, err := handleApiAuthentication(resp, request)
if err != nil {
log.Printf("Api authentication failed in load apps: %s", err)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
fs := memfs.New()
storer := memory.NewStorage()
r, err := git.Clone(storer, fs, &git.CloneOptions{
URL: "https://github.com/frikky/shuffle-apps",
})
if err != nil {
log.Printf("Failed loading repo into memory: %s", err)
}
dir, err := fs.ReadDir("/")
if err != nil {
log.Printf("FAiled reading folder: %s", err)
}
_ = r
iterateAppGithubFolders(fs, dir, "", "")
resp.WriteHeader(200)
resp.Write([]byte(fmt.Sprintf(`{"success": true}`)))
}
// Onlyname is used to
func iterateAppGithubFolders(fs billy.Filesystem, dir []os.FileInfo, extra string, onlyname string) error {
var err error
runUpload := false
for _, file := range dir {
if len(onlyname) > 0 && file.Name() != onlyname {
continue
}
// Folder?
switch mode := file.Mode(); {
case mode.IsDir():
tmpExtra := fmt.Sprintf("%s%s/", extra, file.Name())
dir, err := fs.ReadDir(tmpExtra)
if err != nil {
log.Printf("Failed to read dir: %s", err)
break
}
// Go routine? Hmm, this can be super quick I guess
err = iterateAppGithubFolders(fs, dir, tmpExtra, "")
if err != nil {
break
}
case mode.IsRegular():
// Check the file
filename := file.Name()
if filename == "Dockerfile" {
log.Printf("Handle Dockerfile in location %s", extra)
extraSplit := strings.Split(extra, "/")
tags := []string{}
if len(extraSplit) > 1 {
tags = []string{
fmt.Sprintf("%s:%s_%s", baseDockerName, strings.ReplaceAll(extraSplit[0], " ", "-"), extraSplit[1]),
// Version = folder of last part of extra
// Name = first folder of extra
}
} else {
// Skip
runUpload = false
log.Printf("Skipping folder %s because the extra variable is empty~", extra)
break
//return nil
}
/// Only upload if successful and no errors
err := buildImageMemory(fs, tags, extra)
if err != nil {
log.Printf("Failed image build memory: %s", err)
runUpload = false
} else {
runUpload = true
}
}
}
}
// Done sequentailly to prevent bad uploads
if runUpload && err == nil {
for _, file := range dir {
if file.Name() == "api.yaml" || file.Name() == "api.yaml" {
log.Printf("Run update of %sapi.yaml in backend if it doesn't exist!!", extra)
fullPath := fmt.Sprintf("%s%s", extra, file.Name())
fileReader, err := fs.Open(fullPath)
if err != nil {
return err
}
readFile, err := ioutil.ReadAll(fileReader)
if err != nil {
log.Printf("Filereader error: %s", err)
return err
}
var workflowapp WorkflowApp
err = gyaml.Unmarshal(readFile, &workflowapp)
if err != nil {
log.Printf("Failed api.yaml unmarshal: %s", err)
return err
}
log.Printf("APIName: %s", workflowapp.Name)
extraSplit := strings.Split(extra, "/")
appName := fmt.Sprintf("%s_%s", strings.ReplaceAll(extraSplit[0], " ", "-"), extraSplit[1])
ctx := context.Background()
allapps, err := getAllWorkflowApps(ctx)
if err != nil {
log.Printf("Failed getting apps to verify: %s", err)
return err
}
log.Printf("APPS: %d", len(allapps))
for _, app := range allapps {
if app.Name == workflowapp.Name && app.AppVersion == workflowapp.AppVersion {
log.Printf("App upload for %s:%s already exists.", app.Name, app.AppVersion)
return errors.New(fmt.Sprintf("App %s already exists. ", appName))
}
}
err = checkWorkflowApp(workflowapp)
if err != nil {
log.Printf("%s for app %s:%s", err, workflowapp.Name, workflowapp.AppVersion)
return err
}
//if workflowapp.Environment == "" {
// workflowapp.Environment = baseEnvironment
//}
workflowapp.ID = uuid.NewV4().String()
workflowapp.IsValid = true
workflowapp.Verified = true
workflowapp.Sharing = true
workflowapp.Downloaded = true
err = setWorkflowAppDatastore(ctx, workflowapp, workflowapp.ID)
if err != nil {
log.Printf("Failed setting workflowapp: %s", err)
return err
}
err = increaseStatisticsField(ctx, "total_apps_created", workflowapp.ID, 1)
if err != nil {
log.Printf("Failed to increase total apps created stats: %s", err)
}
err = increaseStatisticsField(ctx, "total_apps_loaded", workflowapp.ID, 1)
if err != nil {
log.Printf("Failed to increase total apps loaded stats: %s", err)
}
log.Printf("Added %s:%s to the database", workflowapp.Name, workflowapp.AppVersion)
//memcache.Delete(ctx, "all_apps")
//os.Exit(3)
}
}
}
return err
}
func setNewWorkflowApp(resp http.ResponseWriter, request *http.Request) {
cors := handleCors(resp, request)
if cors {
return
}
// Just need to be logged in
// FIXME - should have some permissions?
_, err := handleApiAuthentication(resp, request)
if err != nil {
log.Printf("Api authentication failed in set new app: %s", err)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
body, err := ioutil.ReadAll(request.Body)
if err != nil {
log.Printf("Error with body read: %s", err)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
var workflowapp WorkflowApp
err = json.Unmarshal(body, &workflowapp)
if err != nil {
log.Printf("Failed unmarshaling: %s", err)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
ctx := context.Background()
allapps, err := getAllWorkflowApps(ctx)
if err != nil {
log.Printf("Failed getting apps to verify: %s", err)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
appfound := false
for _, app := range allapps {
if app.Name == workflowapp.Name && app.AppVersion == workflowapp.AppVersion {
log.Printf("App upload for %s:%s already exists.", app.Name, app.AppVersion)
appfound = true
break
}
}
if appfound {
log.Printf("App %s:%s already exists. Bump the version.", workflowapp.Name, workflowapp.AppVersion)
resp.WriteHeader(409)
resp.Write([]byte(fmt.Sprintf(`{"success": false, "reason": "App %s:%s already exists."}`, workflowapp.Name, workflowapp.AppVersion)))
return
}
err = checkWorkflowApp(workflowapp)
if err != nil {
log.Printf("%s for app %s:%s", err, workflowapp.Name, workflowapp.AppVersion)
resp.WriteHeader(401)
resp.Write([]byte(fmt.Sprintf(`{"success": false, "reason": "%s for app %s:%s"}`, err, workflowapp.Name, workflowapp.AppVersion)))
return
}
//if workflowapp.Environment == "" {
// workflowapp.Environment = baseEnvironment
//}
workflowapp.ID = uuid.NewV4().String()
workflowapp.IsValid = true
workflowapp.Generated = false
err = setWorkflowAppDatastore(ctx, workflowapp, workflowapp.ID)
if err != nil {
log.Printf("Failed setting workflowapp: %s", err)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
} else {
log.Printf("Added %s:%s to the database", workflowapp.Name, workflowapp.AppVersion)
}
//memcache.Delete(ctx, "all_apps")
resp.WriteHeader(200)
resp.Write([]byte(fmt.Sprintf(`{"success": true}`)))
}
func getWorkflowExecutions(resp http.ResponseWriter, request *http.Request) {
cors := handleCors(resp, request)
if cors {
return
}
user, err := handleApiAuthentication(resp, request)
if err != nil {
log.Printf("Api authentication failed in getting specific workflow: %s", err)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
location := strings.Split(request.URL.String(), "/")
var fileId string
if location[1] == "api" {
if len(location) <= 4 {
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
fileId = location[4]
}
if len(fileId) != 36 {
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false, "reason": "Workflow ID when getting workflow executions is not valid"}`))
return
}
ctx := context.Background()
workflow, err := getWorkflow(ctx, fileId)
if err != nil {
log.Printf("Failed getting the workflow locally: %s", err)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
// FIXME - have a check for org etc too..
if user.Id != workflow.Owner && user.Role != "admin" {
log.Printf("Wrong user (%s) for workflow %s (get execution)", user.Username, workflow.ID)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
// Query for the specifci workflowId
q := datastore.NewQuery("workflowexecution").Filter("workflow_id =", fileId).Limit(50)
var workflowExecutions []WorkflowExecution
_, err = dbclient.GetAll(ctx, q, &workflowExecutions)
if err != nil {
log.Printf("Error getting workflowexec: %s", err)
resp.WriteHeader(401)
resp.Write([]byte(fmt.Sprintf(`{"success": false, "reason": "Failed getting all workflowexecutions for %s"}`, fileId)))
return
}
if len(workflowExecutions) == 0 {
resp.Write([]byte("[]"))
resp.WriteHeader(200)
return
}
newjson, err := json.Marshal(workflowExecutions)
if err != nil {
resp.WriteHeader(401)
resp.Write([]byte(fmt.Sprintf(`{"success": false, "reason": "Failed unpacking workflow executions"}`)))
return
}
resp.WriteHeader(200)
resp.Write(newjson)
}
func getAllSchedules(ctx context.Context) ([]ScheduleOld, error) {
var schedules []ScheduleOld
q := datastore.NewQuery("schedules")
_, err := dbclient.GetAll(ctx, q, &schedules)
if err != nil {
return []ScheduleOld{}, err
}
return schedules, nil
}
func getAllWorkflowApps(ctx context.Context) ([]WorkflowApp, error) {
var allworkflowapps []WorkflowApp
q := datastore.NewQuery("workflowapp")
_, err := dbclient.GetAll(ctx, q, &allworkflowapps)
if err != nil {
return []WorkflowApp{}, err
}
return allworkflowapps, nil
}
// Hmm, so I guess this should use uuid :(
// Consistency PLX
func setWorkflowAppDatastore(ctx context.Context, workflowapp WorkflowApp, id string) error {
key := datastore.NameKey("workflowapp", id, nil)
// New struct, to not add body, author etc
if _, err := dbclient.Put(ctx, key, &workflowapp); err != nil {
log.Printf("Error adding workflow app: %s", err)
return err
}
return nil
}
// Starts a new webhook
func handleStopHook(resp http.ResponseWriter, request *http.Request) {
cors := handleCors(resp, request)
if cors {
return
}
user, err := handleApiAuthentication(resp, request)
if err != nil {
log.Printf("Api authentication failed in set new workflowhandler: %s", err)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
location := strings.Split(request.URL.String(), "/")
var fileId string
if location[1] == "api" {
if len(location) <= 4 {
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
fileId = location[4]
}
if len(fileId) != 32 {
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false, "reason": "Workflow ID when stopping hook is not valid"}`))
return
}
ctx := context.Background()
hook, err := getHook(ctx, fileId)
if err != nil {
log.Printf("Failed getting hook: %s", err)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
if user.Id != hook.Owner && user.Role != "admin" {
log.Printf("Wrong user (%s) for workflow %s", user.Username, hook.Id)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
log.Printf("Status: %s", hook.Status)
log.Printf("Running: %t", hook.Running)
if !hook.Running {
message := fmt.Sprintf("Error: %s isn't running", hook.Id)
log.Println(message)
resp.WriteHeader(401)
resp.Write([]byte(fmt.Sprintf(`{"success": false, "reason": "%s"}`, message)))
return
}
hook.Status = "stopped"
hook.Running = false
hook.Actions = []HookAction{}
err = setHook(ctx, *hook)
if err != nil {
log.Printf("Failed setting hook: %s", err)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
image := "webhook"
// This is here to force stop and remove the old webhook
// FIXME
err = removeWebhookFunction(ctx, fileId)
if err != nil {
log.Printf("Container stop issue for %s-%s: %s", image, fileId, err)
}
resp.WriteHeader(200)
resp.Write([]byte(`{"success": true, "reason": "Stopped webhook"}`))
}
func handleDeleteHook(resp http.ResponseWriter, request *http.Request) {
cors := handleCors(resp, request)
if cors {
return
}
user, err := handleApiAuthentication(resp, request)
if err != nil {
log.Printf("Api authentication failed in set new workflowhandler: %s", err)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
location := strings.Split(request.URL.String(), "/")
var fileId string
if location[1] == "api" {
if len(location) <= 4 {
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
fileId = location[4]
}
if len(fileId) != 36 {
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false, "reason": "Workflow ID when deleting hook is not valid"}`))
return
}
ctx := context.Background()
hook, err := getHook(ctx, fileId)
if err != nil {
log.Printf("Failed getting hook: %s", err)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
if user.Id != hook.Owner && user.Role != "admin" {
log.Printf("Wrong user (%s) for workflow %s", user.Username, hook.Id)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
if len(hook.Workflows) > 0 {
err = increaseStatisticsField(ctx, "total_workflow_triggers", hook.Workflows[0], -1)
if err != nil {
log.Printf("Failed to increase total workflows: %s", err)
}
}
hook.Status = "stopped"
err = setHook(ctx, *hook)
if err != nil {
log.Printf("Failed setting hook: %s", err)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
// This is here to force stop and remove the old webhook
//image := "webhook"
//err = removeWebhookFunction(ctx, fileId)
//if err != nil {
// log.Printf("Function removal issue for %s-%s: %s", image, fileId, err)
// if strings.Contains(err.Error(), "does not exist") {
// resp.WriteHeader(200)
// resp.Write([]byte(`{"success": true, "reason": "Stopped webhook"}`))
// } else {
// resp.WriteHeader(401)
// resp.Write([]byte(`{"success": false, "reason": "Couldn't stop webhook, please try again later"}`))
// }
// return
//}
log.Printf("Successfully deleted webhook %s", fileId)
resp.WriteHeader(200)
resp.Write([]byte(`{"success": true, "reason": "Stopped webhook"}`))
}
func removeWebhookFunction(ctx context.Context, hookid string) error {
service, err := cloudfunctions.NewService(ctx)
if err != nil {
return err
}
// ProjectsLocationsListCall
projectsLocationsFunctionsService := cloudfunctions.NewProjectsLocationsFunctionsService(service)
location := fmt.Sprintf("projects/%s/locations/%s", gceProject, defaultLocation)
functionName := fmt.Sprintf("%s/functions/webhook_%s", location, hookid)
deleteCall := projectsLocationsFunctionsService.Delete(functionName)
resp, err := deleteCall.Do()
if err != nil {
log.Printf("Failed to delete %s from %s: %s", hookid, defaultLocation, err)
return err
} else {
log.Printf("Successfully deleted %s from %s", hookid, defaultLocation)
}
_ = resp
return nil
}
func handleStartHook(resp http.ResponseWriter, request *http.Request) {
cors := handleCors(resp, request)
if cors {
return
}
user, err := handleApiAuthentication(resp, request)
if err != nil {
log.Printf("Api authentication failed in set new workflowhandler: %s", err)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
location := strings.Split(request.URL.String(), "/")
var fileId string
if location[1] == "api" {
if len(location) <= 4 {
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
fileId = location[4]
}
if len(fileId) != 36 {
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false, "reason": "Workflow ID when starting hook is not valid"}`))
return
}
ctx := context.Background()
hook, err := getHook(ctx, fileId)
if err != nil {
log.Printf("Failed getting hook: %s", err)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
if user.Id != hook.Owner && user.Role != "admin" {
log.Printf("Wrong user (%s) for workflow %s", user.Username, hook.Id)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
log.Printf("Status: %s", hook.Status)
log.Printf("Running: %t", hook.Running)
if hook.Running || hook.Status == "Running" {
message := fmt.Sprintf("Error: %s is already running", hook.Id)
log.Println(message)
resp.WriteHeader(401)
resp.Write([]byte(fmt.Sprintf(`{"success": false, "reason": "%s"}`, message)))
return
}
environmentVariables := map[string]string{
"FUNCTION_APIKEY": user.ApiKey,
"CALLBACKURL": "https://shuffler.io",
"HOOKID": fileId,
}
applocation := fmt.Sprintf("gs://%s/triggers/webhook.zip", bucketName)
hookname := fmt.Sprintf("webhook_%s", fileId)
err = deployWebhookFunction(ctx, hookname, "europe-west2", applocation, environmentVariables)
if err != nil {
resp.WriteHeader(401)
resp.Write([]byte(fmt.Sprintf(`{"success": false, "reason": "%s"}`, err)))
return
}
hook.Status = "running"
hook.Running = true
err = setHook(ctx, *hook)
if err != nil {
log.Printf("Failed setting hook: %s", err)
resp.WriteHeader(401)
resp.Write([]byte(`{"success": false}`))
return
}
log.Printf("Starting function %s?", fileId)
resp.WriteHeader(200)
resp.Write([]byte(`{"success": true, "reason": "Started webhook"}`))
return
}
func removeOutlookTriggerFunction(ctx context.Context, triggerId string) error {
service, err := cloudfunctions.NewService(ctx)
if err != nil {
return err
}
// ProjectsLocationsListCall
projectsLocationsFunctionsService := cloudfunctions.NewProjectsLocationsFunctionsService(service)
location := fmt.Sprintf("projects/%s/locations/%s", gceProject, defaultLocation)
functionName := fmt.Sprintf("%s/functions/outlooktrigger_%s", location, triggerId)
deleteCall := projectsLocationsFunctionsService.Delete(functionName)
resp, err := deleteCall.Do()
if err != nil {
log.Printf("Failed to delete %s from %s: %s", triggerId, defaultLocation, err)
return err
} else {
log.Printf("Successfully deleted %s from %s", triggerId, defaultLocation)
}
_ = resp
return nil
}
<file_sep># This is a script to test a function by itself
import requests
import json
def invoke(url, headers, message):
# Used for testing
try:
ret = requests.post(url, headers=headers, json=message, timeout=5)
print(ret.text)
print(ret.status_code)
except requests.exceptions.ConnectionError as e:
print(f"Requesterror: {e}")
def invoke_multi(url, headers, message):
cnt = 0
maxcnt = 100
print("Running %d requests towards %s." % (maxcnt, url))
while(1):
try:
ret = requests.post(url, headers=headers, json=message, timeout=1)
print(ret.status_code)
except requests.exceptions.ConnectionError as e:
print(f"Connectionerror: {e}")
except requests.exceptions.ReadTimeout as e:
print(f"Readtimeout: {e}")
cnt += 1
if cnt == maxcnt:
break
print("Done :)")
if __name__ == "__main__":
# Specific thingies for hello_world
message = {
"parameters": [{
"id_": "asd",
"name": "call",
"value": "REPEAT THIS DATA PLEASE THANKS",
"variant": "STATIC_VALUE",
}],
"name": "repeat_back_to_me",
"execution_id": "asd",
"label": "",
"position": "",
"app_name": "hello_world",
"app_version": "1.0.0",
"label": "lul",
"priority": "1",
"id_": "test",
"id": "test",
"authorization": "hey",
}
apikey = "<KEY>"
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {apikey}"
}
location = "europe-west2"
functionname = "hello-world-1-0-6"
project = "shuffler"
url = f"https://{location}-{project}.cloudfunctions.net/{functionname}"
print(url)
invoke(url, headers, message)
#invoke_multi(url, headers, message)
<file_sep>import React, { useEffect} from 'react';
import { useInterval } from 'react-powerhooks';
import Grid from '@material-ui/core/Grid';
import Paper from '@material-ui/core/Paper';
import Divider from '@material-ui/core/Divider';
import ButtonBase from '@material-ui/core/ButtonBase';
import Button from '@material-ui/core/Button';
import TextField from '@material-ui/core/TextField';
import FormControl from '@material-ui/core/FormControl';
import Tooltip from '@material-ui/core/Tooltip';
import YAML from 'yaml'
import {Link} from 'react-router-dom';
import CloudDownload from '@material-ui/icons/CloudDownload';
import { useAlert } from "react-alert";
import Dialog from '@material-ui/core/Dialog';
import DialogTitle from '@material-ui/core/DialogTitle';
import DialogActions from '@material-ui/core/DialogActions';
import DialogContent from '@material-ui/core/DialogContent';
import CircularProgress from '@material-ui/core/CircularProgress';
const surfaceColor = "#27292D"
const inputColor = "#383B40"
const Apps = (props) => {
const { globalUrl, isLoggedIn, isLoaded } = props;
//const [workflows, setWorkflows] = React.useState([]);
const alert = useAlert()
const [selectedApp, setSelectedApp] = React.useState({});
const [firstrequest, setFirstrequest] = React.useState(true)
const [apps, setApps] = React.useState([])
const [filteredApps, setFilteredApps] = React.useState([])
const [validation, setValidation] = React.useState(false)
const [isLoading, setIsLoading] = React.useState(false)
const [openApi, setOpenApi] = React.useState("")
const [openApiData, setOpenApiData] = React.useState("")
const [appValidation, setAppValidation] = React.useState("")
const [openApiModal, setOpenApiModal] = React.useState(false);
const [openApiModalType, setOpenApiModalType] = React.useState("");
const [openApiError, setOpenApiError] = React.useState("")
const { start, stop } = useInterval({
duration: 5000,
startImmediate: false,
callback: () => {
getApps()
}
});
useEffect(() => {
if (apps.length <= 0 && firstrequest) {
document.title = "Shuffle - Apps"
setFirstrequest(false)
getApps()
}
})
const appViewStyle = {
color: "#ffffff",
width: "100%",
display: "flex",
}
const paperAppStyle = {
minHeight: 130,
maxHeight: 130,
minWidth: "100%",
maxWidth: "100%",
color: "white",
backgroundColor: surfaceColor,
cursor: "pointer",
display: "flex",
}
const getApps = () => {
fetch(globalUrl+"/api/v1/workflows/apps", {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
credentials: "include",
})
.then((response) => {
if (response.status !== 200) {
console.log("Status not 200 for apps :O!")
}
return response.json()
})
.then((responseJson) => {
setApps(responseJson)
setFilteredApps(responseJson)
if (responseJson.length > 0) {
setSelectedApp(responseJson[0])
}
})
.catch(error => {
alert.error(error.toString())
});
}
const downloadApp = (inputdata) => {
const id = inputdata.id
alert.info("Preparing download.")
fetch(globalUrl+"/api/v1/apps/"+id+"/config", {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
credentials: "include",
})
.then((response) => {
if (response.status !== 200) {
window.location.pathname = "/apps"
}
return response.json()
})
.then((responseJson) => {
if (!responseJson.success) {
alert.error("Failed to download file")
} else {
const data = YAML.stringify(YAML.parse(responseJson.body))
var name = inputdata.name
name = name.replace(/ /g, "_", -1)
name = name.toLowerCase()
var blob = new Blob( [ data ], {
type: 'application/octet-stream'
})
var url = URL.createObjectURL( blob )
var link = document.createElement( 'a' )
link.setAttribute( 'href', url )
link.setAttribute( 'download', `${name}.yaml` )
var event = document.createEvent( 'MouseEvents' )
event.initMouseEvent( 'click', true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, null)
link.dispatchEvent( event )
//link.parentNode.removeChild(link)
}
})
.catch(error => {
console.log(error)
alert.error(error.toString())
});
}
// dropdown with copy etc I guess
const appPaper = (data) => {
var boxWidth = "2px"
if (selectedApp.id === data.id) {
boxWidth = "4px"
}
var boxColor = "orange"
if (data.is_valid) {
boxColor = "green"
}
var imageline = data.large_image.length === 0 ?
<img alt="Image missing" style={{width: 100, height: 100}} />
:
<img alt={data.title} src={data.large_image} style={{width: 100, height: 100, maxWidth: "100%"}} />
// FIXME - add label to apps, as this might be slow with A LOT of apps
var newAppname = data.name
newAppname = newAppname.replace("_", " ")
newAppname = newAppname.charAt(0).toUpperCase()+newAppname.substring(1)
var sharing = "public"
if (!data.sharing) {
sharing = "private"
}
var valid = "true"
if (!data.valid) {
valid = "false"
}
if (data.actions === null || data.actions.length === 0) {
valid = "false"
}
var description = data.description
const maxDescLen = 60
if (description.length > maxDescLen) {
description = data.description.slice(0, maxDescLen)+"..."
}
return (
<Paper square style={paperAppStyle} onClick={() => {
if (selectedApp.id !== data.id) {
setSelectedApp(data)
}
}}>
<Grid container style={{margin: 10, flex: "10"}}>
<ButtonBase>
{imageline}
</ButtonBase>
<div style={{marginLeft: "10px", marginTop: "5px", marginBottom: "5px", width: boxWidth, backgroundColor: boxColor}}>
</div>
<Grid container style={{margin: "0px 10px 10px 10px", flex: "1"}}>
<Grid style={{display: "flex", flexDirection: "column", width: "100%"}}>
<Grid item style={{flex: "1"}}>
<h3 style={{marginBottom: "0px"}}>{newAppname}</h3>
</Grid>
<div style={{display: "flex", flex: "1"}}>
<Grid item style={{flex: "1", justifyContent: "center", overflow: "hidden"}}>
{description}
</Grid>
</div>
<Grid item style={{flex: "1", justifyContent: "center"}}>
Sharing: {sharing}
, Valid: {valid}
</Grid>
</Grid>
</Grid>
</Grid>
<Grid container style={{margin: "10px 10px 10px 10px", flex: "1"}} onClick={() => {downloadApp(data)}}>
<Tooltip title={"Download"} style={{marginTop: "28px", width: "100%"}} aria-label={data.name}>
<CloudDownload />
</Tooltip>
</Grid>
</Paper>
)
}
const dividerColor = "rgb(225, 228, 232)"
const uploadViewPaperStyle = {
minWidth: "100%",
maxWidth: "100%",
color: "white",
backgroundColor: surfaceColor,
display: "flex",
marginBottom: 10,
}
//const handleFile = (event) =>{
// const formData = new FormData();
// formData.append('file', event.target.files[0]);
// fetch(globalUrl+"/api/v1/workflows/apps/validate", {
// method: 'POST',
// headers: {
// 'Accept': 'application/json',
// },
// body: formData,
// credentials: "include",
// })
// .then((response) => {
// if (response.status !== 200) {
// console.log("Status not 200 for apps :O!")
// return
// }
// return response.json()
// })
// .then((responseJson) => {
// console.log(responseJson)
// })
// .catch(error => {
// alert.error(error.toString())
// });
//}
const UploadView = () => {
//var imageline = selectedApp.large_image === undefined || selectedApp.large_image.length === 0 ?
// <img alt="" style={{width: "80px"}} />
// :
// <img alt="PICTURE" src={selectedApp.large_image} style={{width: "80px", height: "80px"}} />
// FIXME - add label to apps, as this might be slow with A LOT of apps
var newAppname = selectedApp.name
if (newAppname !== undefined && newAppname.length > 0) {
newAppname = newAppname.replace("_", " ")
newAppname = newAppname.charAt(0).toUpperCase()+newAppname.substring(1)
} else {
newAppname = ""
}
var description = selectedApp.description
const url = "/apps/edit/"+selectedApp.id
var editButton = selectedApp.private_id !== undefined && selectedApp.private_id.length > 0 && selectedApp.generated ?
<Link to={url} style={{textDecoration: "none"}}>
<Button
variant="outlined"
component="label"
color="primary"
style={{marginTop: "10px"}}
>
Edit app
</Button></Link> : null
var deleteButton = (selectedApp.private_id !== undefined && selectedApp.private_id.length > 0 && selectedApp.generated) || (selectedApp.downloaded != undefined && selectedApp.downloaded == true) ?
<Button
variant="outlined"
component="label"
color="primary"
style={{marginLeft: 5, marginTop: 10}}
onClick={() => {
deleteApp(selectedApp.id)
}}
>
Delete app
</Button> : null
//fetch(globalUrl+"/api/v1/get_openapi/"+urlParams.get("id"), {
var baseInfo = newAppname.length > 0 ?
<div>
<h2>{newAppname}</h2>
<p>{description}</p>
<Divider style={{marginBottom: "10px", marginTop: "10px", backgroundColor: dividerColor}}/>
<p>URL: {selectedApp.link}</p>
<p>ID: {selectedApp.id}</p>
<p>PrivateID: {selectedApp.privateId}</p>
{editButton}
{deleteButton}
</div>
:
null
return(
<div>
<Paper square style={uploadViewPaperStyle}>
<div style={{width: "100%", margin: 25}}>
<h2>App creation</h2>
<Link to="/docs/apps" style={{textDecoration: "none", color: "#f85a3e"}}>What are apps?</Link>
- <a href="https://swagger.io/specification/" style={{textDecoration: "none", color: "#f85a3e"}}>OpenAPI specification</a>
<div/>
Apps are how you interact with workflows, and are used to execute workflows. They are created with the app creator, using OpenAPI specification or manually in python.
<div/>
<div style={{marginTop: 20}}>
<Button
variant="outlined"
component="label"
color="primary"
style={{marginRight: 10, }}
onClick={() => {
setOpenApiModal(true)
}}
>
Create from OpenAPI
</Button>
<Link to="/apps/new" style={{textDecoration: "none", color: "#f85a3e"}}>
<Button
variant="outlined"
component="label"
color="primary"
style={{}}
>
Create from scratch
</Button>
</Link>
</div>
</div>
</Paper>
<Paper square style={uploadViewPaperStyle}>
<div style={{width: "100%", margin: 25}}>
{baseInfo}
</div>
</Paper>
</div>
)
}
const handleSearchChange = (event) => {
const searchfield = event.target.value.toLowerCase()
const newapps = apps.filter(data => data.name.toLowerCase().includes(searchfield) || data.description.toLowerCase().includes(searchfield))
setFilteredApps(newapps)
}
const appView = isLoggedIn ?
<div style={{width: 1366, margin: "auto"}}>
<div style={appViewStyle}>
<div style={{flex: "1", marginLeft: "10px", marginRight: "10px"}}>
<h2>Upload</h2>
<div style={{marginTop: 20}}/>
<UploadView />
</div>
<Divider style={{marginBottom: "10px", marginTop: "10px", height: "100%", width: "1px", backgroundColor: dividerColor}}/>
<div style={{flex: 1, marginLeft: "10px", marginRight: "10px"}}>
<div style={{display: "flex"}}>
<div style={{flex: 10}}>
<h2>Available integrations</h2>
</div>
{isLoading ? <CircularProgress style={{marginTop: 13, marginRight: 15}} /> : null}
<Button
variant="contained"
component="label"
color="primary"
style={{maxHeight: 50, marginTop: 10}}
onClick={() => {
getExistingApps()
}}
>
Load existing apps
</Button>
</div>
<TextField
style={{backgroundColor: inputColor}}
InputProps={{
style:{
color: "white",
minHeight: "50px",
marginLeft: "5px",
maxWidth: "95%",
fontSize: "1em",
},
}}
fullWidth
color="primary"
placeholder={"Search apps"}
onChange={(event) => {
handleSearchChange(event)
}}
/>
<div style={{marginTop: 15}}>
{apps.length > 0 ?
filteredApps.length > 0 ?
<div style={{maxHeight: "80vh", overflowY: "scroll"}}>
{filteredApps.map(app => {
return (
appPaper(app)
)
})}
</div>
:
<Paper square style={uploadViewPaperStyle}>
<h4>
Try a broader search term. E.g. "http" or "TheHive"
</h4>
</Paper>
:
<Paper square style={uploadViewPaperStyle}>
<h4>
No apps have been created, uploaded or downloaded yet. Click "Load existing apps" above to get the baseline. This may take a while as its building docker images.
</h4>
</Paper>
}
</div>
</div>
</div>
</div>
:
<div style={{width: "600px", margin: "auto", color: "white", paddingBottom: "50px"}}>
<h2>Available integrations</h2>
<Divider style={{marginBottom: "10px", height: "1px", width: "100%", backgroundColor: dividerColor}}/>
{apps.map(data => {
return (
appPaper(data)
)
})}
</div>
// Gets the URL itself (hopefully this works in most cases?
// Will then forward the data to an internal endpoint to validate the api
const getExistingApps = () => {
setValidation(true)
setIsLoading(true)
start()
alert.success("Downloading and building apps. Feel free to move around meanwhile.")
var cors = "cors"
fetch(globalUrl+"/api/v1/apps/get_existing", {
method: "GET",
mode: "cors",
headers: {
'Accept': 'application/json',
},
credentials: "include",
})
.then((response) => {
if (response.status !== 200) {
alert.success("Failed loading.")
} else {
response.text().then(function (text) {
console.log("RETURN: ", text)
alert.success("Loaded existing apps!")
})
}
setIsLoading(false)
stop()
})
.catch(error => {
alert.error(error.toString())
})
}
// Gets the URL itself (hopefully this works in most cases?
// Will then forward the data to an internal endpoint to validate the api
const validateUrl = () => {
setValidation(true)
var cors = "cors"
if (openApi.includes("localhost")) {
cors = "no-cors"
}
fetch(openApi, {
method: "GET",
mode: "cors",
})
.then((response) => {
response.text().then(function (text) {
validateOpenApi(text)
})
})
.catch(error => {
alert.error(error.toString())
});
}
const deleteApp = (appId) => {
alert.info("Attempting to delete app")
fetch(globalUrl+"/api/v1/apps/"+appId, {
method: 'DELETE',
headers: {
'Accept': 'application/json',
},
credentials: "include",
})
.then((response) => {
if (response.status === 200) {
alert.success("Successfully deleted app")
getApps()
} else {
alert.error("Failed deleting app")
}
})
.catch(error => {
alert.error(error.toString())
});
}
const validateRemote = () => {
setValidation(true)
fetch(globalUrl+"/api/v1/get_openapi_uri", {
method: 'POST',
headers: {
'Accept': 'application/json',
},
body: JSON.stringify(openApi),
credentials: "include",
})
.then((response) => {
return response.text()
})
.then((responseText) => {
validateOpenApi(responseText)
setValidation(false)
})
.catch(error => {
alert.error(error.toString())
});
}
const escapeApiData = (apidata) => {
console.log(apidata)
try {
return JSON.stringify(JSON.parse(apidata))
} catch(error) {
console.log("JSON DECODE ERROR - TRY YAML")
}
try {
return JSON.stringify(YAML.parse(apidata))
} catch(error) {
console.log("YAML DECODE ERROR - TRY SOMETHING ELSE?: "+error)
setOpenApiError(error)
}
return ""
}
// Sends the data to backend, which should return a version 3 of the same API
// If 200 - continue, otherwise, there's some issue somewhere
const validateOpenApi = (openApidata) => {
const newApidata = escapeApiData(openApidata)
if (newApidata === "") {
return
}
fetch(globalUrl+"/api/v1/validate_openapi", {
method: 'POST',
headers: {
'Accept': 'application/json',
},
body: newApidata,
credentials: "include",
})
.then((response) => {
return response.json()
})
.then((responseJson) => {
setValidation(false)
if (responseJson.success) {
setAppValidation(responseJson.id)
} else {
if (responseJson.reason !== undefined) {
setOpenApiError(responseJson.reason)
}
alert.error("An error occurred in the response")
}
})
.catch(error => {
alert.error(error.toString())
});
}
const redirectOpenApi = () => {
window.location.href = "/apps/new?id="+appValidation
}
const errorText = openApiError.length > 0 ? <div>Error: {openApiError}</div> : null
const circularLoader = validation ? <CircularProgress color="primary" /> : null
const modalView = openApiModal ?
<Dialog modal
open={openApiModal}
onClose={() => {setOpenApiModal(false)}}
PaperProps={{
style: {
backgroundColor: surfaceColor,
color: "white",
minWidth: "800px",
minHeight: "320px",
},
}}
>
<FormControl>
<DialogTitle><div style={{color: "rgba(255,255,255,0.9)"}}>Create a new integration</div></DialogTitle>
<DialogContent style={{color: "rgba(255,255,255,0.65)"}}>
Paste in the URI for the OpenAPI
<TextField
style={{backgroundColor: inputColor}}
variant="outlined"
margin="normal"
InputProps={{
style:{
color: "white",
height: "50px",
fontSize: "1em",
},
endAdornment: <Button style={{borderRadius: "0px", marginTop: "0px", height: "50px"}} variant="contained" disabled={openApi.length === 0} color="primary" onClick={() => {
setOpenApiError("")
validateRemote()
}}>Validate</Button>
}}
onChange={e => setOpenApi(e.target.value)}
helperText={<div style={{color:"white", marginBottom: "2px",}}>Must point to a version 2 or 3 specification.</div>}
placeholder="OpenAPI URI"
fullWidth
/>
<div style={{marginTop: "15px"}}/>
Example:
<div />
https://raw.githubusercontent.com/OAI/OpenAPI-Specification/master/examples/v2.0/json/uber.json
<h4>or paste the yaml/JSON directly below</h4>
<TextField
style={{backgroundColor: inputColor}}
variant="outlined"
multiline
rows={6}
margin="normal"
InputProps={{
style:{
color: "white",
fontSize: "1em",
},
endAdornment: <Button style={{marginLeft: 10, borderRadius: "0px", marginTop: "0px"}} variant="contained" disabled={openApiData.length === 0} color="primary" onClick={() => {
setOpenApiError("")
validateOpenApi(openApiData)
}}>Validate data</Button>
}}
onChange={e => setOpenApiData(e.target.value)}
helperText={<div style={{color:"white", marginBottom: "2px",}}>Must point to a version 2 or 3 specification.</div>}
placeholder="OpenAPI text"
fullWidth
/>
{errorText}
</DialogContent>
<DialogActions>
{circularLoader}
<Button style={{borderRadius: "0px"}} onClick={() => setOpenApiModal(false)} color="primary">
Cancel
</Button>
<Button style={{borderRadius: "0px"}} disabled={appValidation.length === 0} onClick={() => {
redirectOpenApi()
}} color="primary">
Submit
</Button>
</DialogActions>
</FormControl>
</Dialog>
: null
const loadedCheck = isLoaded && !firstrequest ?
<div>
{appView}
{modalView}
</div>
:
<div>
</div>
// Maybe use gridview or something, idk
return (
<div>
{loadedCheck}
</div>
)
}
export default Apps
<file_sep>import React, {useState, useEffect} from 'react';
import {Route} from 'react-router';
import {BrowserRouter} from 'react-router-dom';
import { CookiesProvider } from 'react-cookie';
import { useCookies } from 'react-cookie';
import EditSchedule from "./EditSchedule";
import Schedules from "./Schedules";
import Webhooks from "./Webhooks";
import Workflows from "./Workflows";
import EditWebhook from "./EditWebhook";
import AngularWorkflow from "./AngularWorkflow";
import ForgotPassword from "./ForgotPassword";
import ForgotPasswordLink from "./ForgotPasswordLink";
import Header from './Header';
import Apps from './Apps';
import AppCreator from './AppCreator';
import Contact from './Contact';
import Oauth2 from './Oauth2';
import About from "./About";
import Post from "./Post";
import Dashboard from "./Dashboard";
import AdminSetup from "./AdminSetup";
import Admin from "./Admin";
import Docs from "./Docs";
import RegisterLink from "./RegisterLink";
import LandingPage from "./Landingpage";
import LandingPageNew from "./LandingpageNew";
import LoginPage from "./LoginPage";
import SettingsPage from "./SettingsPage";
import MuiThemeProvider from '@material-ui/core/styles/MuiThemeProvider';
import { createMuiTheme } from '@material-ui/core/styles';
import AlertTemplate from "react-alert-template-basic";
import { positions, Provider } from "react-alert";
// Testing - localhost
//const globalUrl = "http://192.168.3.6:5001"
//console.log("HOST: ", process.env)
// Production - backend proxy forwarding in nginx
const globalUrl = window.location.origin
const surfaceColor = "#27292D"
const inputColor = "#383B40"
const theme = createMuiTheme({
palette: {
primary: {
main: "#f85a3e"
},
secondary: {
main: '#e8eaf6',
},
},
typography: {
useNextVariants: true
}
});
// FIXME - set client side cookies
const App = (message, props) => {
const [userdata, setUserData] = useState({});
//const [homePage, ] = useState(true);
const [cookies, setCookie, removeCookie] = useCookies([]);
const [isLoggedIn, setIsLoggedIn] = useState(false);
const [dataset, setDataset] = useState(false);
const [isLoaded, setIsLoaded] = useState(false);
useEffect(() => {
if (dataset === false) {
checkLogin()
setDataset(true)
}})
if (isLoaded && !isLoggedIn && (!window.location.pathname.startsWith("/login") && (!window.location.pathname.startsWith("/docs") && (!window.location.pathname.startsWith("/adminsetup"))))) {
window.location = "login"
}
const checkLogin = () => {
var baseurl = globalUrl
fetch(baseurl+"/api/v1/getinfo", {
credentials: "include",
headers: {
'Content-Type': 'application/json',
},
})
.then(response => response.json())
.then(responseJson => {
if (responseJson.success === true) {
setUserData(responseJson)
setIsLoggedIn(true)
// Updating cookie every request
for (var key in responseJson["cookies"]) {
setCookie(responseJson["cookies"][key].key, responseJson["cookies"][key].value, {path: "/"})
}
}
setIsLoaded(true)
})
.catch(error => {
setIsLoaded(true)
});
}
// Dumb for content load (per now), but good for making the site not suddenly reload parts (ajax thingies)
const options = {
timeout: 5000,
position: positions.BOTTOM_CENTER
};
const includedData = window.location.pathname === "/home" || window.location.pathname === "/features" ?
<div>
<Route exact path="/home" render={props => <LandingPageNew isLoaded={isLoaded} {...props} /> } />
</div> :
<div style={{backgroundColor: "#1F2023", color: "rgba(255, 255, 255, 0.65)", minHeight: "100vh"}}>
<Header removeCookie={removeCookie} isLoaded={isLoaded} globalUrl={globalUrl} setIsLoggedIn={setIsLoggedIn} isLoggedIn={isLoggedIn} surfaceColor={surfaceColor} inputColor={inputColor}{...props} />
<Route exact path="/oauth2" render={props => <Oauth2 isLoaded={isLoaded} globalUrl={globalUrl} surfaceColor={surfaceColor} inputColor={inputColor}{...props} /> } />
<Route exact path="/contact" render={props => <Contact isLoaded={isLoaded} globalUrl={globalUrl} surfaceColor={surfaceColor} inputColor={inputColor} {...props} /> } />
<Route exact path="/login" render={props => <LoginPage isLoggedIn={isLoggedIn} setIsLoggedIn={setIsLoggedIn} register={true} isLoaded={isLoaded} globalUrl={globalUrl} setCookie={setCookie} cookies={cookies} surfaceColor={surfaceColor} inputColor={inputColor} {...props} /> } />
<Route exact path="/admin" render={props => <Admin isLoggedIn={isLoggedIn} setIsLoggedIn={setIsLoggedIn} register={true} isLoaded={isLoaded} globalUrl={globalUrl} setCookie={setCookie} cookies={cookies} surfaceColor={surfaceColor} inputColor={inputColor} {...props} /> } />
<Route exact path="/settings" render={props => <SettingsPage isLoaded={isLoaded} userdata={userdata} globalUrl={globalUrl} surfaceColor={surfaceColor} inputColor={inputColor} {...props} /> } />
<Route exact path="/AdminSetup" render={props => <AdminSetup isLoaded={isLoaded} userdata={userdata} globalUrl={globalUrl} surfaceColor={surfaceColor} inputColor={inputColor} {...props} /> } />
<Route exact path="/webhooks" render={props => <Webhooks isLoaded={isLoaded} globalUrl={globalUrl} {...props} /> } />
<Route exact path="/webhooks/:key" render={props => <EditWebhook isLoaded={isLoaded} globalUrl={globalUrl} surfaceColor={surfaceColor} inputColor={inputColor} {...props} /> } />
<Route exact path="/schedules" render={props => <Schedules globalUrl={globalUrl} surfaceColor={surfaceColor} inputColor={inputColor} {...props} /> } />
<Route exact path="/dashboard" render={props => <Dashboard isLoaded={isLoaded} isLoggedIn={isLoggedIn} globalUrl={globalUrl} surfaceColor={surfaceColor} inputColor={inputColor} {...props} /> } />
<Route exact path="/apps" render={props => <Apps isLoaded={isLoaded} isLoggedIn={isLoggedIn} globalUrl={globalUrl} surfaceColor={surfaceColor} inputColor={inputColor} {...props} /> } />
<Route exact path="/apps/new" render={props => <AppCreator isLoaded={isLoaded} isLoggedIn={isLoggedIn} globalUrl={globalUrl} surfaceColor={surfaceColor} inputColor={inputColor} {...props} /> } />
<Route exact path="/apps/edit/:appid" render={props => <AppCreator isLoaded={isLoaded} isLoggedIn={isLoggedIn} globalUrl={globalUrl} surfaceColor={surfaceColor} inputColor={inputColor} {...props} /> } />
<Route exact path="/schedules/:key" render={props => <EditSchedule globalUrl={globalUrl} surfaceColor={surfaceColor} inputColor={inputColor} {...props} /> } />
<Route exact path="/workflows" render={props => <Workflows isLoaded={isLoaded} isLoggedIn={isLoggedIn} globalUrl={globalUrl} cookies={cookies} surfaceColor={surfaceColor} inputColor={inputColor}{...props} /> } />
<Route exact path="/workflows/:key" render={props => <AngularWorkflow globalUrl={globalUrl} isLoaded={isLoaded} isLoggedIn={isLoggedIn} surfaceColor={surfaceColor} inputColor={inputColor}{...props} /> } />
<Route exact path="/docs/:key" render={props => <Docs isLoaded={isLoaded} globalUrl={globalUrl} surfaceColor={surfaceColor} inputColor={inputColor}{...props} /> } />
<Route exact path="/docs" render={props => {window.location.pathname = "/docs/about"}} />
<Route exact path="/" render={props => {window.location.pathname = "/login"}} />
</div>
// <div style={{backgroundColor: "rgba(21, 32, 43, 1)", color: "#fffff", minHeight: "100vh"}}>
// backgroundColor: "#213243",
// This is a mess hahahah
return (
<MuiThemeProvider theme={theme}>
<CookiesProvider>
<BrowserRouter>
<Provider template={AlertTemplate} {...options}>
{includedData}
</Provider>
</BrowserRouter>
</CookiesProvider>
</MuiThemeProvider>
);
};
export default App;
<file_sep>import os
import sys
import re
import time
import json
import logging
import requests
class AppBase:
""" The base class for Python-based apps in Shuffle, handles logging and callbacks configurations"""
__version__ = None
app_name = None
def __init__(self, redis=None, logger=None, console_logger=None):#, docker_client=None):
self.logger = logger if logger is not None else logging.getLogger("AppBaseLogger")
self.redis=redis
self.console_logger = logger if logger is not None else logging.getLogger("AppBaseLogger")
# apikey is for the user / org
# authorization is for the specific workflow
self.url = os.getenv("CALLBACK_URL", "https://shuffler.io")
self.action = os.getenv("ACTION", "")
self.apikey = os.getenv("FUNCTION_APIKEY", "")
self.authorization = os.getenv("AUTHORIZATION", "")
self.current_execution_id = os.getenv("EXECUTIONID", "")
if len(self.action) == 0:
print("ACTION env not defined")
sys.exit(0)
if len(self.apikey) == 0:
print("FUNCTION_APIKEY env not defined")
sys.exit(0)
if len(self.authorization) == 0:
print("AUTHORIZATION env not defined")
sys.exit(0)
if len(self.current_execution_id) == 0:
print("EXECUTIONID env not defined")
sys.exit(0)
if isinstance(self.action, str):
self.action = json.loads(self.action)
async def execute_action(self, action):
# FIXME - add request for the function STARTING here. Use "results stream" or something
# PAUSED, AWAITING_DATA, PENDING, COMPLETED, ABORTED, EXECUTING, SUCCESS, FAILURE
# !!! Let this line stay - its used for some horrible codegeneration / stitching !!! #
#STARTCOPY
stream_path = "/api/v1/streams"
action_result = {
"action": action,
"authorization": self.authorization,
"execution_id": self.current_execution_id,
"result": "",
"started_at": int(time.time()),
"status": "EXECUTING"
}
self.logger.info("ACTION RESULT: %s", action_result)
headers = {
"Content-Type": "application/json",
"Authorization": "Bearer %s" % self.apikey
}
# Add async logger
# self.console_logger.handlers[0].stream.set_execution_id()
#self.logger.info("Before initial stream result")
try:
ret = requests.post("%s%s" % (self.url, stream_path), headers=headers, json=action_result)
self.logger.info("Workflow: %d" % ret.status_code)
if ret.status_code != 200:
self.logger.info(ret.text)
except requests.exceptions.ConnectionError as e:
print("Connectionerror: %s" % e)
return
#self.logger.info("AFTER initial stream result")
self.logger.info("THIS IS THE NEW UPDATE")
# Verify whether there are any parameters with ACTION_RESULT required
# If found, we get the full results list from backend
fullexecution = {}
try:
tmpdata = {
"authorization": self.authorization,
"execution_id": self.current_execution_id
}
self.logger.info("Auth: %s", tmpdata)
self.logger.info("Before FULLEXEC stream result")
ret = requests.post(
"%s/api/v1/streams/results" % (self.url),
headers=headers,
json=tmpdata
)
if ret.status_code == 200:
fullexecution = ret.json()
else:
self.logger.info("Error: Data: ", ret.json())
self.logger.info("Error with status code for results. Crashing because ACTION_RESULTS or WORKFLOW_VARIABLE can't be handled. Status: %d" % ret.status_code)
return
except requests.exceptions.ConnectionError as e:
self.logger.info("Connectionerror: %s" % e)
return
self.logger.info("AFTER FULLEXEC stream result")
# Takes a workflow execution as argument
# Returns a string if the result is single, or a list if it's a list
# Not implemented: lists
def get_json_value(execution_data, input_data):
parsersplit = input_data.split(".")
actionname = parsersplit[0][1:]
print(f"Actionname: {actionname}")
# 1. Find the action
baseresult = ""
try:
if actionname.lower() == "exec":
baseresult = execution_data["execution_argument"]
else:
for result in execution_data["results"]:
if result["action"]["label"].lower() == actionname.lower():
baseresult = result["result"]
break
except KeyError as error:
print(f"Error: {error}")
print(f"After first trycatch")
# 2. Find the JSON data
if len(baseresult) == 0:
return ""
if len(parsersplit) == 1:
return baseresult
baseresult = baseresult.replace("\'", "\"")
basejson = {}
try:
basejson = json.loads(baseresult)
except json.decoder.JSONDecodeError as e:
return baseresult
try:
for value in parsersplit[1:]:
if value == "#":
print("HANDLE RECURSIVE LOOP")
pass
else:
print("BASE: ", basejson)
if isinstance(basejson[value], str):
print(f"LOADING STRING '%s' AS JSON" % basejson[value])
try:
basejson = json.loads(basejson[value])
except json.decoder.JSONDecodeError as e:
print("RETURNING BECAUSE '%s' IS A NORMAL STRING" % basejson[value])
return basejson[value]
else:
basejson = basejson[value]
except KeyError as e:
print(f"Keyerror: {e}")
return basejson
except IndexError as e:
print(f"Indexerror: {e}")
return basejson
return basejson
def parse_params(action, fullexecution, parameter):
jsonparsevalue = "$."
# Regex to find all the things
if parameter["variant"] == "STATIC_VALUE":
data = parameter["value"]
self.logger.debug(f"\n\nHandle static data with JSON: {data}\n\n")
match = ".*([$]{1}(\w+\.?){1,})"
actualitem = re.findall(match, data, re.MULTILINE)
self.logger.info("PARSED: %s" % actualitem)
if len(actualitem) > 0:
for replace in actualitem:
try:
to_be_replaced = replace[0]
except IndexError:
continue
value = get_json_value(fullexecution, to_be_replaced)
if isinstance(value, str):
parameter["value"] = parameter["value"].replace(to_be_replaced, value)
elif isinstance(value, dict):
parameter["value"] = parameter["value"].replace(to_be_replaced, json.dumps(value))
# Check if json inside string
#self.logger.info(f"CONVERT DATA FROM {parameter['value']} to {data}")
#parameter["value"] = data
if parameter["variant"] == "WORKFLOW_VARIABLE":
for item in fullexecution["workflow"]["workflow_variables"]:
if parameter["action_field"] == item["name"]:
parameter["value"] = item["value"]
break
elif parameter["variant"] == "ACTION_RESULT":
# FIXME - calculate value based on action_field and $if prominent
# FIND THE RIGHT LABEL
# GET THE LABEL'S RESULT
tmpvalue = ""
print(parameter["action_field"])
if parameter["action_field"] == "Execution Argument":
tmpvalue = fullexecution["execution_argument"]
else:
self.logger.info("WORKFLOW EXEC BELOW")
self.logger.info(fullexecution)
self.logger.info(fullexecution["results"])
self.logger.info(fullexecution["workflow"]["actions"])
self.logger.info("ACTIONS ABOVE")
# redundancy..
tmpid = ""
for item in fullexecution["workflow"]["actions"]:
if item["label"] == parameter["action_field"]:
tmpid = item["id"]
if not tmpid:
self.logger.error("Value not found for that id: %s. Exiting" % parameter["action_field"])
raise Exception("Value for %s was not found in workflow actions" % parameter["action_field"])
for subresult in fullexecution["results"]:
if subresult["action"]["id"] == tmpid:
tmpvalue = subresult["result"]
break
if not tmpvalue:
self.logger.error("Value not found for label %s. Exiting" % parameter["action_field"])
raise Exception("Value for %s was not found" % parameter["action_field"])
# Override locally with JSON data
if parameter["value"].startswith(jsonparsevalue):
parsersplit = parameter["value"].split(".")
# Convert to json here
self.logger.info("JSON HANDLING: %s" % tmpvalue)
tmpvalue = tmpvalue.replace("\'", "\"")
try:
if isinstance(tmpvalue, str):
newtmp = json.loads(tmpvalue)
except json.decoder.JSONDecodeError as e:
raise Exception("JSON error: %s" % e)
try:
#previousvalue = parsersplit[1]
for value in parsersplit[1:]:
# Might need to be recursive here, because it can go
# multiple layers ($.result.#.test.users.#.name)
# That would give executions of:
# 1 + result.length + users.length
# This is also just for one param
#if parsersplit[1:][count] == "#":
if value == "#":
# This means we already have an array
# for item in newtmp:
self.logger.info("THERE SHOULD BE A LOOP HERE")
# This works, but it needs to be split into multiples hurr
# Whenever there is a loop, there is a need to
# check whether there are more loops, then do
# recursion to all the bottom leaves
#paramnamevalue.append(newtmp
newtmp = newtmp[0]
# Choose numero uno which will then be handled by the next again
# params[parameter["name"]].append(value.nextitem)
else:
newtmp = newtmp[value]
except KeyError as e:
return "KeyError: %s" % e, ""
except IndexError as e:
return "IndexError: %s" % e, ""
parameter["value"] = str(newtmp)
else:
parameter["value"] = tmpvalue
return "", parameter["value"]
def run_validation(sourcevalue, check, destinationvalue):
self.logger.info("Checking %s %s %s" % (sourcevalue, check, destinationvalue))
if check == "=" or check.lower() == "equals":
if sourcevalue.lower() == destinationvalue.lower():
return True
elif check == "!=" or check.lower() == "does not equal":
if sourcevalue.lower() != destinationvalue.lower():
return True
elif check.lower() == "startswith":
if sourcevalue.lower().startswith(destinationvalue.lower()):
return True
elif check.lower() == "endswith":
if sourcevalue.lower().endswith(destinationvalue.lower()):
return True
elif check.lower() == "contains":
if destinationvalue.lower() in sourcevalue.lower():
return True
else:
self.logger.info("Condition: can't handle %s yet. Setting to true" % check)
return False
def check_branch_conditions(action, fullexecution):
# relevantbranches = workflow.branches where destination = action
try:
if fullexecution["workflow"]["branches"] == None or len(fullexecution["workflow"]["branches"]) == 0:
return True, ""
except KeyError:
return True, ""
relevantbranches = []
for branch in fullexecution["workflow"]["branches"]:
if branch["destination_id"] != action["id"]:
continue
self.logger.info("Relevant branch: %s" % branch)
# Remove anything without a condition
try:
if (branch["conditions"]) == 0 or branch["conditions"] == None:
continue
except KeyError:
continue
self.logger.info("Relevant conditions: %s" % branch["conditions"])
successful_conditions = []
failed_conditions = []
for condition in branch["conditions"]:
self.logger.info("Getting condition value of %s" % condition)
# Parse all values first here
sourcevalue = condition["source"]["value"]
if condition["source"]["variant"] == "" or condition["source"]["variant"]== "STATIC_VALUE":
condition["source"]["variant"]= "STATIC_VALUE"
else:
check, sourcevalue = parse_params(action, fullexecution, condition["source"])
if check:
return False, "Failed condition: %s %s %s because %s" % (sourcevalue, condition["condition"]["value"], destinationvalue, check)
print(sourcevalue)
destinationvalue = condition["destination"]["value"]
if condition["destination"]["variant"]== "" or condition["destination"]["variant"]== "STATIC_VALUE":
condition["destination"]["variant"] = "STATIC_VALUE"
else:
check, destinationvalue = parse_params(action, fullexecution, condition["destination"])
if check:
return False, "Failed condition: %s %s %s because %s" % (sourcevalue, condition["condition"]["value"], destinationvalue, check)
available_checks = [
"=",
"equals",
"!=",
"does not equal",
">",
"larger than",
"<",
"less than",
">=",
"<=",
"startswith",
"endswith",
"contains",
"re",
"matches regex",
]
# FIXME - what should I do here?
if not condition["condition"]["value"] in available_checks:
self.logger.info("Skipping %s %s %s because %s is invalid." % (sourcevalue, condition["condition"]["value"], destinationvalue, condition["condition"]["value"]))
continue
#print(destinationvalue)
if not run_validation(sourcevalue, condition["condition"]["value"], destinationvalue):
self.logger.info("Failed condition check for %s %s %s." % (sourcevalue, condition["condition"]["value"], destinationvalue))
return False, "Failed condition: %s %s %s" % (sourcevalue, condition["condition"]["value"], destinationvalue)
# Make a general parser here, at least to get param["name"] = param["value"] in maparameter[string]string
#for condition in branch.conditons:
return True, ""
# Checks whether conditions are met, otherwise set
branchcheck, tmpresult = check_branch_conditions(action, fullexecution)
if not branchcheck:
self.logger.info("Failed one or more branch conditions.")
action_result["result"] = tmpresult
action_result["status"] = "SKIPPED"
try:
ret = requests.post("%s%s" % (self.url, stream_path), headers=headers, json=action_result)
self.logger.info("Result: %d" % ret.status_code)
if ret.status_code != 200:
self.logger.info(ret.text)
except requests.exceptions.ConnectionError as e:
self.logger.exception(e)
return
# Replace name cus there might be issues
# Not doing lower() as there might be user-made functions
actionname = action["name"]
if " " in actionname:
actionname.replace(" ", "_", -1)
#if action.generated:
# actionname = actionname.lower()
# Runs the actual functions
try:
func = getattr(self, actionname, None)
if func == None:
self.logger.debug("Failed executing %s because func is None." % actionname)
action_result["status"] = "FAILURE"
action_result["result"] = "Function %s doesn't exist." % actionname
elif callable(func):
try:
if len(action["parameters"]) < 1:
result = await func()
else:
# Potentially parse JSON here
# FIXME - add potential authentication as first parameter(s) here
# params[parameter["name"]] = parameter["value"]
#print(fullexecution["authentication"]
# What variables are necessary here tho hmm
params = {}
try:
for item in action["authentication"]:
print("AUTH: ", key, value)
params[item["key"]] = item["value"]
except KeyError:
print("No authentication specified!")
pass
#action["authentication"]
# calltimes is used to handle forloops in the app itself.
# 2 kinds of loop - one in gui with one app each, and one like this,
# which is super fast, but has a bad overview (potentially good tho)
calltimes = 1
result = ""
paramiter = []
for parameter in action["parameters"]:
#self.logger.info(parameter)
#print(fullexecution)
check, value = parse_params(action, fullexecution, parameter)
if check:
raise Exception(check)
params[parameter["name"]] = value
# p["value"]
# FIXME - this is horrible, but works for now
#for i in range(calltimes):
result += await func(**params)
action_result["status"] = "SUCCESS"
action_result["result"] = str(result)
if action_result["result"] == "":
action_result["result"] = result
self.logger.debug(f"Executed {action['label']}-{action['id']} with result: {result}")
self.logger.debug(f"Data: %s" % action_result)
except TypeError as e:
action_result["status"] = "FAILURE"
action_result["result"] = "TypeError: %s" % str(e)
else:
print("Not callable?")
self.logger.error(f"App {self.__class__.__name__}.{action['name']} is not callable")
action_result["status"] = "FAILURE"
action_result["result"] = "Function %s is not callable." % actionname
except Exception as e:
print(f"Failed to execute: {e}")
self.logger.exception(f"Failed to execute {e}-{action['id']}")
action_result["status"] = "FAILURE"
action_result["result"] = "Exception: %s" % e
action_result["completed_at"] = int(time.time())
# I wonder if this actually works
#self.logger.info("Before last stream result")
try:
ret = requests.post("%s%s" % (self.url, stream_path), headers=headers, json=action_result)
self.logger.info("Result: %d" % ret.status_code)
if ret.status_code != 200:
self.logger.info(ret.text)
except requests.exceptions.ConnectionError as e:
self.logger.exception(e)
return
except TypeError as e:
self.logger.exception(e)
action_result["status"] = "FAILURE"
action_result["result"] = "POST error: %s" % e
self.logger.info("Before typeerror stream result")
ret = requests.post("%s%s" % (self.url, stream_path), headers=headers, json=action_result)
self.logger.info("Result: %d" % ret.status_code)
if ret.status_code != 200:
self.logger.info(ret.text)
return
#STOPCOPY
# !!! Let the above line stay - its used for some horrible codegeneration / stitching !!! #
@classmethod
async def run(cls):
""" Connect to Redis and HTTP session, await actions """
logging.basicConfig(format="{asctime} - {name} - {levelname}:{message}", style='{')
logger = logging.getLogger(f"{cls.__name__}")
logger.setLevel(logging.DEBUG)
app = cls(redis=None, logger=logger, console_logger=logger)
# Authorization for the app/function to control the workflow
# Function will crash if its wrong, which it probably should.
await app.execute_action(app.action)
|
8362a9cad0780b9bcd84d67d51cbec479ec95cc1
|
[
"Markdown",
"Python",
"Go",
"JavaScript"
] | 7
|
Go
|
Blue-infosec/Shuffle
|
5d092ddd41457760f69fc8d49f7319e20eba7724
|
1f7f7d5a109bd0d37c1586a91a6a5b3b0185d5c9
|
refs/heads/master
|
<repo_name>ChrisGuzman/Unit-Instrumentation-Android-Tests<file_sep>/app/src/test/java/com/audhil/medium/gweatherapp/basic_mockk_samples/AppRepositoryInjectTest.kt
package com.audhil.medium.gweatherapp.basic_mockk_samples
import com.audhil.medium.gweatherapp.GDelegate
import com.audhil.medium.gweatherapp.data.model.api.response.APIResponse
import com.audhil.medium.gweatherapp.data.remote.AppAPIs
import com.audhil.medium.gweatherapp.di.components.DaggerTestAppComponent
import com.audhil.medium.gweatherapp.di.modules.TestApplicationModule
import com.audhil.medium.gweatherapp.di.modules.TestRepositoryModule
import io.mockk.every
import io.reactivex.Flowable
import org.junit.Assert.assertNotNull
import org.junit.Before
import org.junit.Test
import javax.inject.Inject
class AppRepositoryInjectTest {
@Inject
lateinit var appAPIs: AppAPIs
// @field:[Inject]
// lateinit var appAPIs: AppAPIs
@Before
fun setUp() {
val component = DaggerTestAppComponent.builder()
.applicationModule(TestApplicationModule(GDelegate()))
.repositoryModule(TestRepositoryModule())
.build()
component.into(this)
}
@Test
fun `my test`() {
assertNotNull(appAPIs)
every { appAPIs.getForecastTempWithUrl("r") } returns Flowable.just(APIResponse())
val result = appAPIs.getForecastTempWithUrl("r")
result
.test()
.assertValue(APIResponse())
}
}<file_sep>/app/src/androidTest/java/com/audhil/medium/gweatherapp/tests/MainActivityTest.kt
package com.audhil.medium.gweatherapp.tests
import android.content.Intent
import androidx.test.espresso.Espresso
import androidx.test.espresso.assertion.ViewAssertions
import androidx.test.espresso.matcher.ViewMatchers
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.rule.ActivityTestRule
import com.audhil.medium.gweatherapp.R
import com.audhil.medium.gweatherapp.dispatcher.MockServerDispatcher
import com.audhil.medium.gweatherapp.ui.main.MainActivity
import com.audhil.medium.gweatherapp.util.ConstantsUtil
import okhttp3.mockwebserver.MockWebServer
import org.hamcrest.Matchers.not
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class MainActivityTest {
private lateinit var mockServer: MockWebServer
@Rule
@JvmField
val rule = ActivityTestRule(MainActivity::class.java, false, false)
@Before
fun setUp() {
mockServer = MockWebServer()
mockServer.start(8080)
}
@After
fun tearDown() = mockServer.shutdown()
@Test
fun happyCase() {
mockServer.dispatcher = MockServerDispatcher.ResponseDispatcher()
val intent = Intent(InstrumentationRegistry.getInstrumentation().targetContext, MainActivity::class.java)
intent.putExtra(
ConstantsUtil.MOCK_URL,
mockServer.url("/v1/forecast.json?key=41c23902be8e47c0a1d171804190206&q=13.0827,80.2707&days=5").toString()
)
rule.launchActivity(intent)
// degree text view - visible on success response
Espresso.onView(ViewMatchers.withId(R.id.current_temp_txt_view))
.check(ViewAssertions.matches(ViewMatchers.isDisplayed()))
// city text view - visible on success response
Espresso.onView(ViewMatchers.withId(R.id.city_txt_view))
.check(ViewAssertions.matches(ViewMatchers.isDisplayed()))
// loading view - not visible on success response
Espresso.onView(ViewMatchers.withId(R.id.loading_layout))
.check(ViewAssertions.matches(not(ViewMatchers.isDisplayed())))
// error view - not visible on success response
Espresso.onView(ViewMatchers.withId(R.id.failure_layout))
.check(ViewAssertions.matches(not(ViewMatchers.isDisplayed())))
}
@Test
fun unHappyCase() {
mockServer.dispatcher = MockServerDispatcher.ErrorDispatcher()
val intent = Intent(InstrumentationRegistry.getInstrumentation().targetContext, MainActivity::class.java)
intent.putExtra(
ConstantsUtil.MOCK_URL,
mockServer.url("I'm a mock URL").toString()
)
rule.launchActivity(intent)
// failure layout visible
Espresso.onView(ViewMatchers.withId(R.id.failure_layout))
.check(ViewAssertions.matches(ViewMatchers.isDisplayed()))
}
}<file_sep>/app/src/test/java/com/audhil/medium/gweatherapp/di/modules/TestApplicationModule.kt
package com.audhil.medium.gweatherapp.di.modules
import com.audhil.medium.gweatherapp.GDelegate
import com.audhil.medium.gweatherapp.data.remote.AppAPIs
import com.audhil.medium.gweatherapp.repository.AppRepository
import io.mockk.mockk
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
class TestApplicationModule(delegate: GDelegate) : ApplicationModule(delegate) {
override fun giveAppAPIs(): AppAPIs = mockk()
override fun giveRetrofitService(okHttpClient: OkHttpClient): AppAPIs = mockk()
override fun giveOkHttpClient(loggingInterceptor: HttpLoggingInterceptor): OkHttpClient = mockk()
override fun giveLoggingInterceptor(): HttpLoggingInterceptor = mockk()
}
class TestRepositoryModule : RepositoryModule() {
override fun giveGPRepo(): AppRepository = mockk()
}<file_sep>/app/src/androidTest/java/com/audhil/medium/gweatherapp/UiGDelegate.kt
package com.audhil.medium.gweatherapp
import com.audhil.medium.gweatherapp.di.TestApplicationModule
import com.audhil.medium.gweatherapp.di.components.ApplicationComponent
import com.audhil.medium.gweatherapp.di.components.DaggerApplicationComponent
open class UiGDelegate : GDelegate() {
override fun getApplicationComponent(): ApplicationComponent {
return DaggerApplicationComponent.builder()
.applicationModule(TestApplicationModule(this))
.build()
}
}<file_sep>/app/src/main/java/com/audhil/medium/gweatherapp/repository/AppRepository.kt
package com.audhil.medium.gweatherapp.repository
import com.audhil.medium.gweatherapp.data.model.api.response.APIResponse
import com.audhil.medium.gweatherapp.rx.makeFlowableRxConnection
import com.audhil.medium.gweatherapp.util.CallBack
import com.audhil.medium.gweatherapp.util.ConstantsUtil
import io.reactivex.disposables.Disposable
class AppRepository : BaseRepository() {
var apiCallBack: CallBack<APIResponse>? = null
fun fetchFromServer(url: String) {
appAPIs.getForecastTempWithUrl(url)
.makeFlowableRxConnection(this, ConstantsUtil.TESTING)
}
fun fetchFromServer(latitude: String, longitude: String): Disposable =
appAPIs.getForecastTemp(latlng = latitude + ConstantsUtil.COMMA + longitude)
.makeFlowableRxConnection(this, ConstantsUtil.FORECAST_TEMP_API)
override fun onSuccess(obj: Any?, tag: String) {
when (tag) {
ConstantsUtil.TESTING,
ConstantsUtil.FORECAST_TEMP_API ->
(obj as? APIResponse)?.let {
apiCallBack?.invoke(it)
}
else ->
Unit
}
}
// chain network calls
fun fetchFromServerByCity(cityName: String): Disposable =
appAPIs.getForecastTempByCity(city = cityName)
.makeFlowableRxConnection(this, ConstantsUtil.FORECAST_TEMP_API)
}<file_sep>/app/src/test/java/com/audhil/medium/gweatherapp/basic_mockito_samples/SomeClass.kt
package com.audhil.medium.gweatherapp.basic_mockito_samples
class SomeClass {
fun multiply(x: Int, y: Int): Int {
if (x > 100)
throw IllegalArgumentException("Number should be less or equal to 100")
return x * y
}
}<file_sep>/app/build.gradle
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'
android {
compileSdkVersion rootProject.compileSdkVersion
defaultConfig {
applicationId "com.audhil.medium.gweatherapp"
minSdkVersion rootProject.minSdkVersion
targetSdkVersion rootProject.targetSdkVersion
versionCode 1
versionName "1.0"
testInstrumentationRunner "com.audhil.medium.gweatherapp.runner.UiRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
dataBinding {
enabled = true
}
// for testing
compileOptions {
sourceCompatibility 1.8
targetCompatibility 1.8
}
// for android specific class testing
testOptions {
unitTests.returnDefaultValues = true
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version",
'androidx.appcompat:appcompat:' + rootProject.appCompatVersion,
'androidx.core:core-ktx:' + rootProject.ktxVersion,
'androidx.constraintlayout:constraintlayout:' + rootProject.constraintLayoutVersion,
'com.google.android.material:material:' + rootProject.materialLibVersion,
// rxjava 2
'io.reactivex.rxjava2:rxjava:' + rootProject.rxJava2Version,
'io.reactivex.rxjava2:rxandroid:' + rootProject.rxAndroidVersion,
// retrofit 2
'com.squareup.retrofit2:retrofit:' + rootProject.retrofit2Version,
'com.squareup.retrofit2:converter-gson:' + rootProject.retrofit2Version,
'com.squareup.retrofit2:adapter-rxjava2:' + rootProject.retrofit2Version,
'com.squareup.okhttp3:logging-interceptor:' + rootProject.retrofit2LoggingVersion,
// arch components
'android.arch.lifecycle:extensions:' + rootProject.archComponentsVersion,
// dagger 2
'com.google.dagger:dagger:' + rootProject.dagger2Version,
// stetho for debugging
'com.facebook.stetho:stetho:' + rootProject.stethoVersion,
// play services
'com.google.android.gms:play-services-location:' + rootProject.playServicesLocationVersion
// room lib
kapt 'android.arch.persistence.room:compiler:' + rootProject.archComponentsVersion,
// dagger 2
'com.google.dagger:dagger-compiler:' + rootProject.dagger2Version
kaptTest 'com.google.dagger:dagger-compiler:' + rootProject.dagger2Version
testImplementation 'junit:junit:' + rootProject.jUnitVersion,
'android.arch.core:core-testing:' + rootProject.archCoreVersion
androidTestImplementation 'androidx.test.ext:junit:' + rootProject.extTestRunnerVersion,
'androidx.test:rules:' + rootProject.testRunnerVersion,
'androidx.test.espresso:espresso-core:' + rootProject.espressoVersion
androidTestImplementation('com.squareup.okhttp3:mockwebserver:' + rootProject.mockWebServerVersion) {
exclude group: "com.squareup.okhttp3"
}
// mockito
testImplementation 'org.mockito:mockito-core:2.19.0'
// mockk
testImplementation "io.mockk:mockk:1.9.3"
}<file_sep>/app/src/test/java/com/audhil/medium/gweatherapp/basic_mockito_samples/twitterapitests/TwitterClient.kt
package com.audhil.medium.gweatherapp.basic_mockito_samples.twitterapitests
open class TwitterClient {
fun sendTweet(iTweet: ITweet): String {
val tweet = iTweet.getTweet()
// do the sending logic
return tweet
}
}<file_sep>/app/src/main/java/com/audhil/medium/gweatherapp/di/components/ApplicationComponent.kt
package com.audhil.medium.gweatherapp.di.components
import com.audhil.medium.gweatherapp.GDelegate
import com.audhil.medium.gweatherapp.di.modules.ApplicationModule
import com.audhil.medium.gweatherapp.di.modules.RepositoryModule
import com.audhil.medium.gweatherapp.repository.BaseRepository
import com.audhil.medium.gweatherapp.ui.base.BaseViewModel
import dagger.Component
import javax.inject.Singleton
@Singleton
@Component(
modules = [
(ApplicationModule::class),
(RepositoryModule::class)
]
)
interface ApplicationComponent {
fun inject(into: GDelegate)
fun inject(into: BaseRepository)
fun inject(into: BaseViewModel)
}<file_sep>/app/src/test/java/com/audhil/medium/gweatherapp/basic_mockito_samples/mocksample/ArgumentCaptureSample.kt
package com.audhil.medium.gweatherapp.basic_mockito_samples.mocksample
import com.audhil.medium.gweatherapp.util.capture
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.core.IsCollectionContaining.hasItem
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.ArgumentCaptor
import org.mockito.Captor
import org.mockito.Mockito.verify
import org.mockito.Spy
import org.mockito.junit.MockitoJUnitRunner
@RunWith(MockitoJUnitRunner::class)
class ArgumentCaptureSample {
@Captor
lateinit var captor: ArgumentCaptor<MutableList<String>>
@Spy
var mockList: MutableList<String> = mutableListOf()
@Test
fun `test Argument Capture`() {
val normalList = mutableListOf("first", "second", "third", "fourth")
// val mockList: MutableList<String> = reifiedMock()
mockList.addAll(normalList)
println("sizeOfList is : ${mockList.size}") // 0 when reifiedMock(), 4 when @Spy
verify(mockList).addAll(capture(captor))
val capturedArgs = captor.value
assertThat(capturedArgs, hasItem("third"))
}
}<file_sep>/app/src/main/java/com/audhil/medium/gweatherapp/data/remote/AppAPIs.kt
package com.audhil.medium.gweatherapp.data.remote
import com.audhil.medium.gweatherapp.data.model.api.response.APIResponse
import com.audhil.medium.gweatherapp.util.ConstantsUtil
import io.reactivex.Flowable
import retrofit2.http.GET
import retrofit2.http.Path
import retrofit2.http.Query
import retrofit2.http.Url
interface AppAPIs {
@GET(
"{apiVersion}" + ConstantsUtil.FORWARD_SLASH + ConstantsUtil.FORECAST_TEMP_API + ConstantsUtil.FORWARD_SLASH
)
fun getForecastTemp(
@Path(value = "apiVersion", encoded = true)
apiVersion: String = ConstantsUtil.API_VERSION,
@Query(ConstantsUtil.KEY_PARAM)
apiKey: String = ConstantsUtil.API_KEY,
@Query(ConstantsUtil.QUERY_PARAM)
latlng: String? = null,
@Query(ConstantsUtil.DAYS_PARAM)
days: String = ConstantsUtil.FOUR
): Flowable<APIResponse>
@GET(
"{apiVersion}" + ConstantsUtil.FORWARD_SLASH + ConstantsUtil.FORECAST_TEMP_API + ConstantsUtil.FORWARD_SLASH
)
fun getForecastTempByCity(
@Path(value = "apiVersion", encoded = true)
apiVersion: String = ConstantsUtil.API_VERSION,
@Query(ConstantsUtil.KEY_PARAM)
apiKey: String = ConstantsUtil.API_KEY,
@Query(ConstantsUtil.QUERY_PARAM)
city: String? = null,
@Query(ConstantsUtil.DAYS_PARAM)
days: String = ConstantsUtil.FOUR
): Flowable<APIResponse>
// for testing purpose
@GET
fun getForecastTempWithUrl(
@Url
url: String
): Flowable<APIResponse>
}<file_sep>/app/src/test/java/com/audhil/medium/gweatherapp/basic_mockito_samples/twitterapitests/ITweet.kt
package com.audhil.medium.gweatherapp.basic_mockito_samples.twitterapitests
interface ITweet {
fun getTweet(): String
}<file_sep>/app/src/test/java/com/audhil/medium/gweatherapp/basic_mockk_samples/BaseTest.kt
package com.audhil.medium.gweatherapp.basic_mockk_samples
import com.audhil.medium.gweatherapp.GDelegate
import com.audhil.medium.gweatherapp.data.remote.AppAPIs
import com.audhil.medium.gweatherapp.di.components.DaggerTestAppComponent
import com.audhil.medium.gweatherapp.di.modules.TestApplicationModule
import com.audhil.medium.gweatherapp.di.modules.TestRepositoryModule
import javax.inject.Inject
open class BaseTest {
@Inject
lateinit var appAPIs: AppAPIs
fun setUp() {
val component = DaggerTestAppComponent.builder()
.applicationModule(TestApplicationModule(GDelegate()))
.repositoryModule(TestRepositoryModule())
.build()
component.into(this)
}
}<file_sep>/app/src/test/java/com/audhil/medium/gweatherapp/basic_mockito_samples/SomeClassTest.kt
package com.audhil.medium.gweatherapp.basic_mockito_samples
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import java.lang.Exception
class SomeClassTest {
private var someClass: SomeClass? = null
@Before
fun setUp() {
someClass = SomeClass()
}
@Test(expected = Exception::class)
fun testExceptionIsThrown() {
someClass?.multiply(101, 3)
}
@Test
fun testMultiply() {
val result = someClass?.multiply(3, 4)
assertEquals("3 x 4 = 12", 12, result)
}
}<file_sep>/app/src/test/java/com/audhil/medium/gweatherapp/basic_mockito_samples/mocksample/InjectMockSample.kt
package com.audhil.medium.gweatherapp.basic_mockito_samples.mocksample
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.InjectMocks
import org.mockito.Mock
import org.mockito.Mockito.times
import org.mockito.Mockito.verify
import org.mockito.junit.MockitoJUnitRunner
// https://howtodoinjava.com/mockito/mockito-mock-injectmocks/
@RunWith(MockitoJUnitRunner::class)
class InjectMockSample {
@InjectMocks
var mainClass: MainClass? = null
@Mock
var dependentClassOne: DatabaseDAO? = null
@Mock
var dependentClassTwo: NetworkDAO? = null
@Test
fun validateTest() {
val saved = mainClass?.save("temp.txt")
assertEquals(true, saved)
// just verification
verify(dependentClassOne, times(1))?.save("temp.txt")
verify(dependentClassTwo, times(1))?.save("temp.txt")
}
}
open class NetworkDAO {
open fun save(fileName: String) {
println("Saved in network location")
}
}
open class DatabaseDAO {
open fun save(fileName: String) {
println("Saved in database")
}
}
open class MainClass {
var database: DatabaseDAO? = null
var network: NetworkDAO? = null
//Setters and getters
fun save(fileName: String): Boolean {
database!!.save(fileName)
println("Saved in database in Main class")
network!!.save(fileName)
println("Saved in network in Main class")
return true
}
}<file_sep>/app/src/test/java/com/audhil/medium/gweatherapp/util/UtilFuncs.kt
package com.audhil.medium.gweatherapp.util
import org.mockito.ArgumentCaptor
import org.mockito.Mockito.mock
/*
* Util funcs for Mockito framework
* */
inline fun <reified T : Any> reifiedMock(): T = mock(T::class.java)
// Returns ArgumentCaptor.capture() as nullable type to avoid java.lang.IllegalStateException when null is returned
// from: https://github.com/googlesamples/android-architecture-components/blob/master/BasicRxJavaSampleKotlin/app/src/test/java/com/example/android/observability/MockitoKotlinHelpers.kt
fun <T> capture(argumentCaptor: ArgumentCaptor<T>): T = argumentCaptor.capture()<file_sep>/app/src/main/java/com/audhil/medium/gweatherapp/ui/base/BaseViewModel.kt
package com.audhil.medium.gweatherapp.ui.base
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import com.audhil.medium.gweatherapp.GDelegate
import com.audhil.medium.gweatherapp.repository.AppRepository
import io.reactivex.disposables.CompositeDisposable
import javax.inject.Inject
abstract class BaseViewModel(application: Application) : AndroidViewModel(application) {
@Inject
lateinit var appRepository: AppRepository
init {
GDelegate.INSTANCE.appComponent.inject(this)
}
var compositeDisposable: CompositeDisposable = CompositeDisposable()
override fun onCleared() {
super.onCleared()
compositeDisposable.clear()
}
}<file_sep>/app/src/test/java/com/audhil/medium/gweatherapp/basic_mockito_samples/mocksample/MyClassTest.kt
package com.audhil.medium.gweatherapp.basic_mockito_samples.mocksample
import com.audhil.medium.gweatherapp.util.reifiedMock
import org.junit.Assert.assertEquals
import org.junit.Test
import org.mockito.Mockito.*
import java.lang.IllegalArgumentException
// based on https://www.vogella.com/tutorials/Mockito/article.html
class MyClassTest {
// sample 1 with static mock function
@Test
fun testSample1() {
val classMock = mock(MyClass::class.java)
`when`(classMock.getUniqueId()).thenReturn(43)
assertEquals(classMock.getUniqueId(), 43)
}
// sample 2 return multiple values
@Test
fun testSample2() {
val iterator = mock(Iterator::class.java)
`when`(iterator.next()).thenReturn("Jack").thenReturn("and").thenReturn("jill")
val result = iterator.next() as String + " " + iterator.next() as String + " " + iterator.next() as String
assertEquals("Jack and jill", result)
}
// sample 3 return values based on input
@Test
fun testSample3() {
val comparable: Comparable<String> = reifiedMock()
`when`(comparable.compareTo("Mockito")).thenReturn(1)
`when`(comparable.compareTo("Jack and jill")).thenReturn(2)
assertEquals(1, comparable.compareTo("Mockito"))
assertEquals(2, comparable.compareTo("Jack and jill"))
}
// sample 4 return values independent of the input value
@Test
fun testSample4() {
val comparable: Comparable<Int> = reifiedMock()
`when`(comparable.compareTo(anyInt())).thenReturn(-1)
assertEquals(-1, comparable.compareTo(4))
}
// sample 5 return values based on type of provider parameter - NOT WORKING CHECK IT LATER - says "must not be null"
// @Test
// fun testSample5() {
// val comparable: Comparable<MyClass> = reifiedMock()
// `when`(comparable.compareTo(isA(MyClass::class.java))).thenReturn(0)
// assertEquals(0, comparable.compareTo(MyClass()))
// }
// sample 6
@Test
fun testSample6() {
val someClass = mock(MyClass::class.java)
`when`(someClass.getSomeRecord("Andrroid")).thenThrow(IllegalArgumentException("jack and jill, IllegalArgumentException"))
try {
someClass.getSomeRecord("Andrroid")
// fail("Andrroid is misspellled") // fails the test case
} catch (e: IllegalArgumentException) {
println("outch it got exception")
}
}
}<file_sep>/app/src/test/java/com/audhil/medium/gweatherapp/di/components/TestAppComponent.kt
package com.audhil.medium.gweatherapp.di.components
import com.audhil.medium.gweatherapp.di.modules.ApplicationModule
import com.audhil.medium.gweatherapp.di.modules.RepositoryModule
import com.audhil.medium.gweatherapp.basic_mockk_samples.AppRepositoryInjectNamedTest
import com.audhil.medium.gweatherapp.basic_mockk_samples.AppRepositoryInjectTest
import com.audhil.medium.gweatherapp.basic_mockk_samples.BaseTest
import dagger.Component
import javax.inject.Singleton
@Singleton
@Component(
modules = [
(ApplicationModule::class),
(RepositoryModule::class)
]
)
interface TestAppComponent : ApplicationComponent {
fun into(appRepositoryTest: AppRepositoryInjectNamedTest)
fun into(appRepositoryTest: AppRepositoryInjectTest)
fun into(baseTest: BaseTest)
}<file_sep>/app/src/main/java/com/audhil/medium/gweatherapp/ui/main/MainViewModel.kt
package com.audhil.medium.gweatherapp.ui.main
import android.app.Application
import androidx.databinding.ObservableField
import androidx.lifecycle.MediatorLiveData
import androidx.lifecycle.MutableLiveData
import com.audhil.medium.gweatherapp.data.model.api.NetworkError
import com.audhil.medium.gweatherapp.data.model.api.response.APIResponse
import com.audhil.medium.gweatherapp.ui.base.BaseViewModel
open class MainViewModel(application: Application) : BaseViewModel(application) {
var failureLayoutVisibility = ObservableField<Boolean>(false)
var loadingLayoutVisibility = ObservableField<Boolean>(false)
// error live data
var errorLiveData =
MediatorLiveData<NetworkError>().apply {
addSource(appRepository.errorLiveData) {
value = it
}
}
// data
val foreCastLiveData = MutableLiveData<APIResponse?>().apply {
appRepository.apiCallBack = {
value = it
}
}
// api call
open fun loadForecasts(latitude: String, longitude: String) = compositeDisposable.add(
appRepository.fetchFromServer(latitude, longitude)
)
}<file_sep>/README.md
# Unit-Instrumentation-Android-Tests
This is a demo app with Kotlin, RxJava2, Retrofit2, android arch components, dagger2, junit, espresso, mockwebserver, mockito, mockk & MVVM.
# For Instrumentation TestCase(using MockWebServer, dagger2, RxJava2) Refer: [here](https://android.jlelse.eu/instrumentation-testing-with-dagger2-retrofit2-mockwebserver-android-4cca7cb7373c)
<file_sep>/app/src/test/java/com/audhil/medium/gweatherapp/basic_mockito_samples/mocksample/DoAnswerSample.kt
package com.audhil.medium.gweatherapp.basic_mockito_samples.mocksample
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.ArgumentMatchers.anyString
import org.mockito.Mock
import org.mockito.Mockito.*
import org.mockito.Spy
import org.mockito.junit.MockitoJUnitRunner
import org.mockito.Mockito.`when`
import org.mockito.Mockito.doAnswer
@RunWith(MockitoJUnitRunner::class)
class DoAnswerSample {
// based on sample: https://stackoverflow.com/questions/36615330/mockito-doanswer-vs-thenreturn/36627077
// normal - given, when, then
@Mock
lateinit var dummy: Dummy
@Spy
val list = mutableListOf<String>()
@Test
fun `normal testing`() {
`when`(dummy.stringLength(anyString())).thenReturn(5) // preferred way for mocked objects
val length = dummy.stringLength("get it break it")
assertEquals("it is equal: good to go: ", 5, length)
// or
doReturn(5).`when`(dummy).stringLength(anyString()) // preferred way for spy objects
val length2 = dummy.stringLength("get it break it")
assertEquals("it is equal 2nd time: good to go: ", 5, length2)
}
@Test
fun `using doAnswer`() {
doAnswer { invocation ->
(invocation.getArgument(0) as String).length * 2
}.`when`(dummy).stringLength("get")
assertEquals("it is equal 2nd time: good to go: ", 6, dummy.stringLength("get"))
}
// based on sample: https://www.vogella.com/tutorials/Mockito/article.html#mockito_answers
// @Test
// fun answerTest() {
// // with doAnswer():
// doAnswer(returnsFirstArg<String>()).`when`(list).add(anyString())
// // with thenAnswer():
// `when`(list.add(anyString())).thenAnswer(returnsFirstArg<String>())
// // with then() alias:
// `when`(list.add(anyString())).then(returnsFirstArg<String>())
// }
/*
* @Test
public final void callbackTest() {
ApiService service = mock(ApiService.class);
when(service.login(any(Callback.class))).thenAnswer(i -> {
Callback callback = i.getArgument(0);
callback.notify("Success");
return null;
});
}
*/
/*
* List<User> userMap = new ArrayList<>();
UserDao dao = mock(UserDao.class);
when(dao.save(any(User.class))).thenAnswer(i -> {
User user = i.getArgument(0);
userMap.add(user.getId(), user);
return null;
});
when(dao.find(any(Integer.class))).thenAnswer(i -> {
int id = i.getArgument(0);
return userMap.get(id);
});
*/
}
open class Dummy {
open fun stringLength(string: String): Int = string.length
}<file_sep>/app/src/main/java/com/audhil/medium/gweatherapp/GDelegate.kt
package com.audhil.medium.gweatherapp
import android.app.Application
import com.audhil.medium.gweatherapp.di.components.ApplicationComponent
import com.audhil.medium.gweatherapp.di.components.DaggerApplicationComponent
import com.audhil.medium.gweatherapp.di.modules.ApplicationModule
import com.facebook.stetho.Stetho
open class GDelegate : Application() {
open lateinit var appComponent: ApplicationComponent
companion object {
lateinit var INSTANCE: GDelegate
}
override fun onCreate() {
super.onCreate()
INSTANCE = this
appComponent = getApplicationComponent()
appComponent.inject(this)
Stetho.initializeWithDefaults(this)
}
open fun getApplicationComponent(): ApplicationComponent =
DaggerApplicationComponent
.builder()
.applicationModule(ApplicationModule(this))
.build()
}<file_sep>/app/src/test/java/com/audhil/medium/gweatherapp/basic_mockito_samples/mocksample/MyClass.kt
package com.audhil.medium.gweatherapp.basic_mockito_samples.mocksample
open class MyClass {
open fun getUniqueId(): Int = 45
open fun getSomeRecord(value: String) {}
open fun testing(arg: Int) {
}
}<file_sep>/app/src/test/java/com/audhil/medium/gweatherapp/basic_mockito_samples/mocksample/MockVerifySamples.kt
package com.audhil.medium.gweatherapp.basic_mockito_samples.mocksample
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.ArgumentMatchers
import org.mockito.Mock
import org.mockito.Mockito.*
import org.mockito.junit.MockitoJUnitRunner
// based on https://www.vogella.com/tutorials/Mockito/article.html
// option 3 - to init mocks
@RunWith(MockitoJUnitRunner::class)
class MockVerifySamples {
@Mock
lateinit var myClass: MyClass
// option 1 - to init mocks
// @Rule
// @JvmField
// var rule: MockitoRule = MockitoJUnit.rule()
// option 2 - to init mocks
// @Before
// fun setUp() {
// MockitoAnnotations.initMocks(this)
// }
@Test
fun `test Mock verify`() {
`when`(myClass.getUniqueId()).thenReturn(88)
myClass.getUniqueId()
myClass.getUniqueId()
// was the method called twice
verify(myClass, times(2)).getUniqueId()
verify(myClass, never()).testing(ArgumentMatchers.anyInt())
// now check if method testing was called with the parameter "pimpi" or anyString()
myClass.getSomeRecord("pimpi")
verify(myClass).getSomeRecord(ArgumentMatchers.anyString())
// now check if method testing was called with the parameter 3" or anyInt()
myClass.testing(3)
verify(myClass).testing(ArgumentMatchers.anyInt())
verify(myClass, atLeastOnce()).testing(ArgumentMatchers.anyInt())
myClass.getSomeRecord("pimpi")
verify(myClass, atLeast(2)).getSomeRecord(ArgumentMatchers.anyString())
myClass.getSomeRecord("pimpi")
verify(myClass, atLeast(3)).getSomeRecord(ArgumentMatchers.anyString())
myClass.getSomeRecord("pimpi")
// uncomment below line to check - atMost usage
// myClass.getSomeRecord("pimpi")
verify(myClass, atMost(4)).getSomeRecord(ArgumentMatchers.anyString())
// uncomment below line - still atMost will work
// myClass.getSomeRecord("pimpi")
// This let's you check that no other methods where called on this object.
// You call it after you have verified the expected method calls.
verifyNoMoreInteractions(myClass)
}
// for meaningful message during test failures
// @After
// fun validate() {
// validateMockitoUsage()
// }
}<file_sep>/app/src/test/java/com/audhil/medium/gweatherapp/basic_mockito_samples/mocksample/StrictStubRulesSample.kt
package com.audhil.medium.gweatherapp.basic_mockito_samples.mocksample
import org.junit.Assert.assertEquals
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.Mockito.*
import org.mockito.junit.MockitoJUnit
import org.mockito.junit.MockitoJUnitRunner
import org.mockito.quality.Strictness
@RunWith(MockitoJUnitRunner::class)
class StrictStubRulesSample {
// without strict stub rules
@Mock
lateinit var deepThoughtClass: DeepThoughtClass
// this is normal test case - it'll fail for any mis-use of stubbing
@Test
fun `without strict stubs test`() {
`when`(deepThoughtClass.getAnswerFor("jack and jill")).thenReturn("yup!")
assertEquals("yup!", deepThoughtClass.getAnswerFor("jack and jill"))
verify(deepThoughtClass, times(1)).getAnswerFor("jack and jill")
}
@Rule
@JvmField
val rule = MockitoJUnit.rule().strictness(Strictness.STRICT_STUBS)
@Test
fun `with strict stub test`() {
`when`(deepThoughtClass.getAnswerFor("jack and jill")).thenReturn("yup!")
// this fails now with an UnnecessaryStubbingException since it is never called in the test
// `when`(deepThoughtClass.otherMethod("I'm other method")).thenReturn(null)
// this will now throw a PotentialStubbingProblem Exception since
// we usually don't want to call methods on mocks without configured behavior
// deepThoughtClass.someMethod()
assertEquals("yup!", deepThoughtClass.getAnswerFor("jack and jill"))
// verifyNoMoreInteractions now automatically verifies that all stubbed methods have been called as well
verifyNoMoreInteractions(deepThoughtClass)
}
}
// some class
open class DeepThoughtClass {
open fun getAnswerFor(thought: String): String {
return thought
}
open fun otherMethod(thought: String): String {
return thought
}
open fun someMethod() {
}
}<file_sep>/app/src/main/java/com/audhil/medium/gweatherapp/di/modules/ApplicationModule.kt
package com.audhil.medium.gweatherapp.di.modules
import android.content.Context
import android.content.pm.PackageManager
import com.audhil.medium.gweatherapp.GDelegate
import com.audhil.medium.gweatherapp.data.remote.AppAPIs
import com.audhil.medium.gweatherapp.repository.AppRepository
import com.audhil.medium.gweatherapp.util.ConstantsUtil
import com.audhil.medium.gweatherapp.util.GLog
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import dagger.Module
import dagger.Provides
import okhttp3.*
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit
import javax.inject.Named
import javax.inject.Singleton
@Module
open class ApplicationModule(private val application: GDelegate) {
@Provides
@Singleton
fun giveContext(): Context = this.application
@Provides
@Singleton
fun givePackageManager(): PackageManager = application.packageManager
@Provides
@Singleton
open fun giveLoggingInterceptor(): HttpLoggingInterceptor {
val interceptor = HttpLoggingInterceptor(HttpLoggingInterceptor.Logger { message ->
GLog.v("APP LOGG", message)
})
interceptor.level = if (GLog.DEBUG_BOOL)
HttpLoggingInterceptor.Level.BODY
else
HttpLoggingInterceptor.Level.NONE
return interceptor
}
// okHttpClient
@Provides
open fun giveOkHttpClient(
loggingInterceptor: HttpLoggingInterceptor
): OkHttpClient {
val httpClient = OkHttpClient.Builder()
.addInterceptor(loggingInterceptor)
// for testing
// .addInterceptor { chain ->
// Response.Builder()
// .code(400)
// .message("{}")
// .request(chain.request())
// .protocol(Protocol.HTTP_1_0)
// .body(ResponseBody.create(MediaType.parse("application/json"), "{}".toByteArray()))
// .build()
// }
// increasing time outs
.connectTimeout(1, TimeUnit.MINUTES)
.readTimeout(30, TimeUnit.SECONDS)
.writeTimeout(15, TimeUnit.SECONDS)
return httpClient.build()
}
@Provides
fun giveRetrofitBuilder(): Retrofit.Builder =
Retrofit.Builder()
.baseUrl(ConstantsUtil.API_ENDPOINT)
.addConverterFactory(GsonConverterFactory.create(GsonBuilder().create()))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
@Provides
open fun giveRetrofitService(okHttpClient: OkHttpClient): AppAPIs =
Retrofit.Builder()
.baseUrl(ConstantsUtil.API_ENDPOINT)
.addConverterFactory(GsonConverterFactory.create(GsonBuilder().create()))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.client(okHttpClient)
.build()
.create(AppAPIs::class.java)
@Provides
@Named("test")
open fun giveAppAPIs(): AppAPIs =
Retrofit.Builder().build().create(AppAPIs::class.java)
@Provides
@Singleton
fun giveGSONInstance(): Gson = Gson()
}
@Module
open class RepositoryModule {
@Provides
open fun giveGPRepo(): AppRepository = AppRepository()
}<file_sep>/app/src/test/java/com/audhil/medium/gweatherapp/basic_mockito_samples/twitterapitests/TwitterTest.kt
package com.audhil.medium.gweatherapp.basic_mockito_samples.twitterapitests
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.Mockito.*
import org.mockito.junit.MockitoJUnitRunner
@RunWith(MockitoJUnitRunner::class)
class TwitterTest {
@Mock
lateinit var iTweet: ITweet
@Mock
lateinit var twitterClient: TwitterClient
@Test
fun `test sending tweet`() {
`when`(iTweet.getTweet()).thenReturn("<NAME>")
val value = twitterClient.sendTweet(iTweet)
verify(iTweet, atLeastOnce()).getTweet()
assertEquals("here's the result", "<NAME>", value)
}
}<file_sep>/app/src/test/java/com/audhil/medium/gweatherapp/basic_mockito_samples/mocksample/MockVsSpy.kt
package com.audhil.medium.gweatherapp.basic_mockito_samples.mocksample
import junit.framework.TestCase.assertNull
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.Mockito
import org.mockito.Mockito.`when`
import org.mockito.Mockito.doReturn
import org.mockito.Spy
import org.mockito.junit.MockitoJUnitRunner
// based on https://stackoverflow.com/questions/28295625/mockito-spy-vs-mock
@RunWith(MockitoJUnitRunner::class)
class MockVsSpy {
@Mock
lateinit var mockList: MutableList<String>
@Spy
var spyList = mutableListOf<String>()
@Test
fun testMockList() {
mockList.add("0th item") // doesn't call `add()` func of mutableList
Mockito.verify(mockList).add("0th item")
assertEquals(0, mockList.size)
assertNull(mockList[0])
}
@Test
fun testSpyList() {
spyList.add("0th item") // calls `add()` func of mutableList
Mockito.verify(spyList).add("0th item")
assertEquals(1, spyList.size)
assertNotNull(spyList[0])
}
// with stubs
@Test
fun testMockListWithStub() {
`when`(mockList[1999]).thenReturn("I'm the value @ 1999") // stubbing
assertEquals("I'm the value @ 1999", mockList[1999])
}
@Test
fun testSpyListWithStub() {
// stubbing a spy method will result the same as the mock object
// doReturn("9").`when`(spyList).get(9) // take note of using doReturn instead of when - special for spy objects
doReturn("9").`when`(spyList)[9] // take note of using doReturn instead of when - special for spy objects
assertEquals("9", spyList[9])
}
}<file_sep>/app/src/test/java/com/audhil/medium/gweatherapp/basic_mockito_samples/instrumentedunittests/DummyTest.kt
package com.audhil.medium.gweatherapp.basic_mockito_samples.instrumentedunittests
import android.content.Context
import android.content.Intent
import com.audhil.medium.gweatherapp.ui.listing.ListingActivity
import org.junit.Assert.*
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.InjectMocks
import org.mockito.Mock
import org.mockito.junit.MockitoJUnitRunner
// hints: http://tools.android.com/tech-docs/unit-testing-support#TOC-Method-...-not-mocked.-
@RunWith(MockitoJUnitRunner::class)
class DummyTest {
@Mock
lateinit var context: Context
// @Mock
// lateinit var intent: Intent
// @Rule
// @JvmField
// val rule = InstantTaskExecutorRule()
@InjectMocks
lateinit var util: Util
@Test
fun `check correct extras`() {
val intent = util.createQuery(context, "jack", "jill")
assertNotNull(intent)
val bundle = intent.extras
assertNull(bundle)
//
// assertEquals("first check", "jack", bundle?.getString("query"))
// assertEquals("second check", "jill",intent.extras?.getString("value"))
}
}
open class Util {
fun createQuery(context: Context, query: String, value: String): Intent {
val intent = Intent(context, ListingActivity::class.java)
intent.putExtra("query", query)
intent.putExtra("value", value)
return intent
}
}
|
8f75eda05ac0c61b235daa78ad7b9e4bd99fe2d3
|
[
"Markdown",
"Kotlin",
"Gradle"
] | 30
|
Kotlin
|
ChrisGuzman/Unit-Instrumentation-Android-Tests
|
f0cadd23a5665ea4de93c448cc34afc134a6a76d
|
5318a29c838291b1eb56cac6cf68b1ce2688a173
|
refs/heads/master
|
<repo_name>JademyRo/CollectionExamples<file_sep>/src/ro/jademy/collections/SetTester.java
package ro.jademy.collections;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.TreeSet;
public class SetTester {
public static void main(String[] args) {
// the Set interface contains only methods inherited from Collection
// the Set interface has three implementations: HashSet, TreeSet and LinkedHashSet
// usually, the HashSet is the fastest
Set<Integer> intHashSet = new HashSet<>();
Set<Integer> intTreeSet = new TreeSet<>();
Set<Integer> intLinkedHashSet = new LinkedHashSet<>();
long startHash = System.currentTimeMillis();
for (int i = 0; i < 100000; i++) {
intHashSet.add(i);
}
long endHash = System.currentTimeMillis();
long startTree = System.currentTimeMillis();
for (int i = 0; i < 100000; i++) {
intTreeSet.add(i);
}
long endTree = System.currentTimeMillis();
long startLinked = System.currentTimeMillis();
for (int i = 0; i < 100000; i++) {
intLinkedHashSet.add(i);
}
long endLinked = System.currentTimeMillis();
System.out.println("HashSet duration: " + (endHash - startHash));
System.out.println("TeeSet duration: " + (endTree - startTree));
System.out.println("LinkedHashSet duration: " + (endLinked - startLinked));
System.out.println();
// the Set interface adds a stronger contract on the behavior of equals and hashcode so that different
// set implementations are equal if they have the same elements
System.out.println("Is the HashSet equal to the TreeSet: " + intHashSet.equals(intTreeSet));
System.out.println("Is the HashSet equal to the LinkedHashSet: " + intHashSet.equals(intLinkedHashSet));
System.out.println("Is the TreeSet equal to the LinkedHashSet: " + intTreeSet.equals(intLinkedHashSet));
}
}
<file_sep>/README.md
# CollectionExamples
Example project that demonstrates various Java Collection Framework APIs
|
5575dd51e1c94a30efebc23191cd5c7140a9b6c3
|
[
"Markdown",
"Java"
] | 2
|
Java
|
JademyRo/CollectionExamples
|
33b1b313ba6de0f5a9a03250056f11333d76618d
|
b0b44703b7ccb6a5fd9428b2ba4aa0d6c4634d57
|
refs/heads/master
|
<repo_name>lindat18/ffta<file_sep>/ffta/pixel_utils/parab.py
"""parab.py: Parabola fit around three points to find a true vertex."""
import numpy as np
def fit_peak(f, x):
'''
Uses solution to parabola to fit peak and two surrounding points
This assumes there is a peak (i.e. parabola second deriv is negative)
Parameters
----------
f : array f(x)
x : array x with the indices corresponding to f
If interested, this is educational to see with sympy
import sympy
y1, y2, y3 = sympy.symbols('y1 y2 y3')
A = sympy.Matrix([[(-1)**2, -1, 1],[0**2, 0, 1],[(1)**2,1,1]])
C = sympy.Matrix([[y1],[y2],[y3]])
D = A.inv().multiply(C)
D contains the values of a, b, c in ax**2 + bx + c
Peak position is at x = -D[1]/(2D[0])
'''
pk = np.argmax(f)
y1 = f[pk - 1]
y2 = f[pk]
y3 = f[pk + 1]
a = 0.5 * y1 - y2 + 0.5 * y3
b = -0.5 * y1 + 0.5 * y3
c = y2
xindex = -b / (2 * a)
findex = xindex * (x[1] - x[0]) + x[1]
yindex = a * xindex ** 2 + b * xindex + c
return findex, yindex, xindex
def ridge_finder(spectrogram, freq_bin):
'''
Uses parabolda to fit peak and two surrounding points
This takes a spectrogram and the frequency bin spacing and wraps parab.fit_2d
Parameters
----------
spectrogram : ndarray
Returned by scipy.signal.spectrogram or stft or cwt
Arranged in (frequencies, times) shape
freq_bin : ndarray
arrays corresponding the frequencies in the spectrogram
Returns
-------
xindex : ndarray
1D array of the frequency bins returned by parabolic approximation
yindex : ndarray
1D array of the peak values at the xindices supplied
'''
_argmax = np.argmax(np.abs(spectrogram), axis=0)
cols = spectrogram.shape[1]
# generate a (3, cols) matrix of the spectrogram values
maxspec = np.array([spectrogram[(_argmax - 1, range(cols))],
spectrogram[(_argmax, range(cols))],
spectrogram[(_argmax + 1, range(cols))]])
return fit_2d(maxspec, _argmax, freq_bin)
def fit_2d(f, p, dx):
'''
Uses solution to parabola to fit peak and two surrounding points
This assumes there is a peak (i.e. parabola second deriv is negative).
This is a broadcast version for speed purposes
Parameters
----------
f : 2-d array f(x) of size (3 , samples)
p : 1-d array with the peak positions for f
dx : 1-d array with the frequency (x values) of f
'''
if f.shape[0] != 3:
raise ValueError('Must be exactly 3 rows')
a = 0.5 * f[0, :] - f[1, :] + 0.5 * f[2, :]
b = -0.5 * f[0, :] + 0.5 * f[2, :]
c = f[1, :]
xindex = -b / (2 * a)
findex = xindex * (dx[1] - dx[0]) + dx[p]
yindex = a * (xindex ** 2) + b * xindex + c
return findex, yindex, xindex
def fit_peak_old(f, x):
"""
f = array
x = index of peak, typically just argmax
Uses parabola equation to fit to the peak and two surrounding points
"""
x1 = x - 1
x2 = x
x3 = x + 1
y1 = f[x - 1]
y2 = f[x]
y3 = f[x + 1]
d = (x1 - x3) * (x1 - x2) * (x2 - x3)
A = (x1 * (y3 - y2) + x2 * (y1 - y3) + x3 * (y2 - y1)) / d
B = (x1 ** 2.0 * (y2 - y3) +
x2 ** 2.0 * (y3 - y1) +
x3 ** 2.0 * (y1 - y2)) / d
C = (x2 * x3 * (x2 - x3) * y1 +
x3 * x1 * (x3 - x1) * y2 +
x1 * x2 * (x1 - x2) * y3) / d
xindex = -B / (2.0 * A)
yindex = C - B ** 2.0 / (4.0 * A)
return xindex, yindex
<file_sep>/XOP/trEFMAnalysisPackage.r
#include "XOPStandardHeaders.r"
resource 'vers' (1) { /* XOP version info */
0x01, 0x00, final, 0x00, 0, /* version bytes and country integer */
"1.00",
"1.00, Copyright 1993-2010 WaveMetrics, Inc., all rights reserved."
};
resource 'vers' (2) { /* Igor version info */
0x06, 0x00, release, 0x00, 0, /* version bytes and country integer */
"6.00",
"(for Igor 6.00 or later)"
};
resource 'STR#' (1100) { /* custom error messages */
{
/* [1] */
"trEFMAnalysisPackage requires Igor Pro 6.0 or later.",
/* [2] */
"Wave does not exist.",
/* [3] */
"This function requires a 3D wave.",
}
};
/* no menu item */
resource 'XOPI' (1100) {
XOP_VERSION, // XOP protocol version.
DEV_SYS_CODE, // Development system information.
0, // Obsolete - set to zero.
0, // Obsolete - set to zero.
XOP_TOOLKIT_VERSION, // XOP Toolkit version.
};
resource 'XOPF' (1100) {
{
"WAGetWaveInfo", /* function name */
F_WAVE | F_EXTERNAL, /* function category */
HSTRING_TYPE, /* return value type */
{
WAVE_TYPE, /* parameter types */
},
"WAFill3DWaveDirectMethod", /* function name */
F_WAVE | F_EXTERNAL, /* function category */
NT_FP64, /* return value type */
{
WAVE_TYPE, /* parameter types */
},
"WAFill3DWavePointMethod", /* function name */
F_WAVE | F_EXTERNAL, /* function category */
NT_FP64, /* return value type */
{
WAVE_TYPE, /* parameter types */
},
"WAFill3DWaveStorageMethod", /* function name */
F_WAVE | F_EXTERNAL, /* function category */
NT_FP64, /* return value type */
{
WAVE_TYPE, /* parameter types */
},
"WAModifyTextWave", /* function name */
F_WAVE | F_EXTERNAL, /* function category */
NT_FP64, /* return value type */
{
WAVE_TYPE, /* parameter types */
HSTRING_TYPE,
HSTRING_TYPE,
},
}
};
<file_sep>/XOP/DataFromIgor.cpp
#include <FPGAHeader.h>
#include <NiFpga.h>
#include <XOPStandardHeaders.h> // Include ANSI headers, Mac headers, IgorXOP.h, XOP.h and XOPSupport.h
#include "trEFMAnalysisPackage.h"
static int gCallSpinProcess = 1;
double** ImportDataFromIgor(waveHndl data_wave,int* rows,int*columns)
{
/*
Gets data from an igor wave for use in our analysis.
*/
waveHndl wavH;
double *dp0, *dcp, *dp;
double** data;
int numDimensions;
CountInt dimensionSizes[MAX_DIMENSIONS + 1];
CountInt numRows, numColumns, numLayers;
CountInt column;
IndexInt row;
BCInt numBytes;
double* dPtr;
int result, result2;
char noticeStr[50];
wavH = data_wave;
MDGetWaveDimensions(wavH, &numDimensions, dimensionSizes);
numRows = dimensionSizes[0];
numColumns = dimensionSizes[1];
numLayers = 0; // 2d waves
// let the caller know what these dimensions are.
(*rows) = numRows;
(*columns) = numColumns;
// Create the 2 dimensional data array.
const int nrow = (int)numRows, ncol = (int)numColumns, nelem = nrow*ncol;
data = new double*[nrow];
data[0] = new double[nelem];
for (int i = 1; i < nrow; i++)
{
data[i] = data[i - 1] + ncol;
}
numBytes = WavePoints(wavH) * sizeof(double); // Bytes needed for copy
dPtr = (double*)NewPtr(numBytes);
MDGetDPDataFromNumericWave(wavH, dPtr); // Get a copy of the wave data.
dp0 = dPtr;
for (column = 0; column < numColumns; column++) {
if (gCallSpinProcess && SpinProcess()) { // Spins cursor and allows background processing.
result = -1; // User aborted.
break;
}
dcp = dp0 + column*numRows; // Pointer to start of data for this column.
for (row = 0; row < numRows; row++) {
dp = dcp + row;
(double)data[row][column] = (*dp);
}
}
DisposePtr((Ptr)dPtr);
return data;
}<file_sep>/ffta/simulation/cantilever.py
"""simulate.py: Contains Cantilever class."""
# pylint: disable=E1101,R0902,C0103
__author__ = "<NAME>"
__copyright__ = "Copyright 2020, Ginger Lab"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
__status__ = "Production"
import numpy as np
from scipy.integrate import odeint
import ffta
# Set constant 2 * pi.
PI2 = 2 * float(np.pi)
class Cantilever:
"""Damped Driven Harmonic Oscillator Simulator for AFM Cantilevers.
Simulates a DDHO with given parameters.
This class contains the functions needed to simulate. To create a class that
simulates a subset, it needs to overload the following functions:
force(self, t)
omega(self, t)
dZdt(self, t) if the given ODE form will not work
Parameters
----------
can_params : dict
Parameters for cantilever properties. The dictionary contains:
amp_invols = float (in m/V)
def_invols = float (in m/V)
soft_amp = float (in V)
drive_freq = float (in Hz)
res_freq = float (in Hz)
k = float (in N/m)
q_factor = float
force_params : dict
Parameters for forces. The dictionary contains:
es_force = float (in N)
delta_freq = float (in Hz)
tau = float (in seconds)
v_dc = float (in Volts)
v_ac = float (in Volts)
v_cpd = float (in Volts)
dCdz = float (in F/m)
sim_params : dict
Parameters for simulation. The dictionary contains:
trigger = float (in seconds)
total_time = float (in seconds)
sampling_rate = int (in Hz)
Attributes
----------
amp : float
Amplitude of the cantilever in meters.
beta : float
Damping factor of the cantilever in rad/s.
delta : float
Initial phase of the cantilever in radians.
delta_freq : float
Frequency shift of the cantilever under excitation.
mass : float
Mass of the cantilever in kilograms.
Z : ndarray
ODE integration result, sampled at sampling_rate. Default integration
is at 100 MHz.
t_Z : ndarray
Time axis based on the provided total time and sampling rate
f_Z : ndarray
Frequency axis based on the provided sampling rate
Method
------
simulate(trigger_phase=180)
Simulates the cantilever motion with excitation happening
at the given phase.
See Also
--------
pixel: Pixel processing for FF-trEFM data.
Examples
--------
>>> from ffta.simulation import cantilever, load
>>>
>>> params_file = '../examples/sim_params.cfg'
>>> params = load.simulation_configuration(params_file)
>>>
>>> c = cantilever.Cantilever(*params)
>>> Z, infodict = c.simulate()
>>> c.analyze()
>>> c.analyze(roi=0.004) # can change the parameters as desired
"""
def __init__(self, can_params, force_params, sim_params):
# Initialize cantilever parameters and calculate some others.
for key, value in can_params.items():
setattr(self, key, value)
self.w0 = PI2 * self.res_freq # Radial resonance frequency.
self.wd = PI2 * self.drive_freq # Radial drive frequency.
if not np.allclose(self.w0, self.wd):
print('Resonance and Drive not equal. Make sure simulation is long enough!')
self.beta = self.w0 / (2 * self.q_factor) # Damping factor.
self.mass = self.k / (self.w0 ** 2) # Mass of the cantilever in kg.
self.amp = self.soft_amp * self.amp_invols # Amplitude in meters.
# Calculate reduced driving force and phase in equilibrium.
np.seterr(divide='ignore') # suprress divide-by-0 warning in arctan
self.f0 = self.amp * np.sqrt((self.w0 ** 2 - self.wd ** 2) ** 2 +
4 * self.beta ** 2 * self.wd ** 2)
self.delta = np.abs(np.arctan(np.divide(2 * self.wd * self.beta,
self.w0 ** 2 - self.wd ** 2)))
# Initialize force parameters and calculate some others.
for key, value in force_params.items():
setattr(self, key, value)
self.delta_w = PI2 * self.delta_freq # Frequency shift in radians.
self.fe = self.es_force / self.mass # Reduced electrostatic force.
# Initialize simulation parameters.
for key, value in sim_params.items():
setattr(self, key, value)
# Calculate time axis for simulated tip motion without extra cycles
num_pts = int(self.total_time * self.sampling_rate)
self.t_Z = np.linspace(0, self.total_time, num=num_pts)
# Calculate frequency axis for simulated tip_motion without extra cycles.
self.freq_Z = np.linspace(0, int(self.sampling_rate / 2), num=int(num_pts / 2 + 1))
# Create a Pixel class-compatible params file
self.fit_params = {}
self.parameters = force_params
self.parameters.update(**sim_params)
self.can_params = can_params
self.create_parameters(self.parameters, self.can_params)
return
def set_conditions(self, trigger_phase=180):
"""
Sets initial conditions and other simulation parameters.
Parameters
----------
trigger_phase: float, optional
Trigger phase is in degrees and wrt cosine. Default value is 180.
"""
self.trigger_phase = np.mod(np.pi * trigger_phase / 180, PI2)
self.n_points = int(self.total_time * self.sampling_rate)
# Add extra cycles to the simulation to find correct phase at trigger.
cycle_points = int(2 * self.sampling_rate / self.res_freq)
self.n_points_sim = cycle_points + self.n_points
# Create time vector and find the trigger wrt phase.
self.t = np.arange(self.n_points_sim) / self.sampling_rate
# Current phase at trigger.
current_phase = np.mod(self.wd * self.trigger - self.delta, PI2)
phase_diff = np.mod(self.trigger_phase - current_phase, PI2)
self.t0 = self.trigger + phase_diff / self.wd # modified trigger point
# Set the initial conditions at t=0.
z0 = self.amp * np.sin(-self.delta)
v0 = self.amp * self.wd * np.cos(-self.delta)
self.Z0 = np.array([z0, v0])
return
def force(self, t, t0=0, tau=0):
"""
Force on the cantilever at a given time.
Parameters
----------
t : float
Time in seconds.
Returns
-------
f : float
Force on the cantilever at a given time, in N/kg.
"""
driving_force = self.f0 * np.sin(self.wd * t)
return driving_force
def omega(self, t, t0=0, tau=0):
"""
Resonance frequency behavior
Parameters
----------
t : float
Time in seconds.
Returns
-------
w : float
Resonance frequency of the cantilever at a given time, in rad/s.
"""
return self.w0
def dZ_dt(self, Z, t=0):
"""
Takes the derivative of the given Z with respect to time.
Parameters
----------
Z : (2, ) array_like
Z[0] is the cantilever position, and Z[1] is the cantilever
velocity.
t : float
Time.
Returns
-------
Zdot : (2, ) array_like
Zdot[0] is the cantilever velocity, and Zdot[1] is the cantilever
acceleration.
"""
t0 = self.t0
tau = self.tau
v = Z[1]
vdot = (self.force(t, t0, tau) -
self.omega(t, t0, tau) * Z[1] / self.q_factor -
self.omega(t, t0, tau) ** 2 * Z[0])
return np.array([v, vdot])
def simulate(self, trigger_phase=180, Z0=None):
"""
Simulates the cantilever motion.
Parameters
----------
trigger_phase: float, optional
Trigger phase is in degrees and wrt cosine. Default value is 180.
Z0 : list, optional
Z0 = [z0, v0], the initial position and velocity
If not specified, is calculated from the analytical solution to DDHO
(using "set_conditions")
Returns
-------
Z : (n_points, 1) array_like
Cantilever position in Volts.
infodict : dict
Information about the ODE solver.
"""
if Z0:
if not isinstance(Z0, (np.ndarray, list)):
raise TypeError('Must be 2-size array or list')
if len(Z0) != 2:
raise ValueError('Must specify exactly [z0, v0]')
self.n_points = int(self.total_time * self.sampling_rate)
self.t = np.arange(self.n_points) / self.sampling_rate
self.t0 = self.trigger
self.Z0 = Z0
else:
self.set_conditions(trigger_phase)
Z, infodict = odeint(self.dZ_dt, self.Z0, self.t, full_output=True)
t0_idx = int(self.t0 * self.sampling_rate)
tidx = int(self.trigger * self.sampling_rate)
Z_cut = Z[(t0_idx - tidx):(t0_idx + self.n_points - tidx), 0]
self.infodict = infodict
self.Z = Z_cut
return self.Z, self.infodict
def downsample(self, target_rate=1e7):
'''
Downsamples the cantilever output. Used primarily to match experiments
or for lower computational load
This will overwrite the existing output with the downsampled verison
target_rate : int
The sampling rate for the signal to be converted to. 1e7 = 10 MHz
'''
if target_rate > self.sampling_rate:
raise ValueError('Target should be less than the initial sampling rate')
step = int(self.sampling_rate / target_rate)
n_points = int(self.total_time * target_rate)
self.Z = self.Z[0::step].reshape(n_points, 1) / self.def_invols
return
def create_parameters(self, params={}, can_params={}, fit_params={}):
'''
Creates a Pixel class-compatible parameters and cantilever parameters Dict
Parameters
----------
params : dict, optional
Contains analysis parameters for the Pixel cass
can_params : dict, optional
Contains cantilever parameters for the Pixel class. These data are
optional for the analysis.
fit_params : dict, optional
Contains various parameters for fitting and analysis. See Pixel class.
'''
# default seeding of parameters
_parameters = {'bandpass_filter': 1.0,
'drive_freq': 277261,
'filter_bandwidth': 10000.0,
'n_taps': 799,
'roi': 0.0003,
'sampling_rate': 1e7,
'total_time': 0.002,
'trigger': 0.0005,
'window': 'blackman',
'wavelet_analysis': 0}
_can_params = {'amp_invols': 5.52e-08,
'def_invols': 5.06e-08,
'k': 26.2,
'q_factor': 432}
_fit_params = {'filter_amplitude': True,
'method': 'hilbert',
'fit': True,
'fit_form': 'product'}
for key, val in _parameters.items():
if key not in params:
if hasattr(self, key):
params[key] = self.__dict__[key]
else:
params[key] = val
for key, val in _can_params.items():
if key not in can_params:
if hasattr(self, key):
can_params[key] = self.__dict__[key]
else:
can_params[key] = val
for key, val in _fit_params.items():
if key not in fit_params:
if hasattr(self, key):
fit_params[key] = self.__dict__[key]
else:
fit_params[key] = val
# then write to the Class
self.parameters.update(**params)
self.can_params.update(**can_params)
self.fit_params.update(**fit_params)
return
def analyze(self, plot=True, **kwargs):
'''
Converts output to a Pixel class and analyzes
Parameters
----------
plot : bool, optional
If True, calls Pixel.plot() to display the results
Returns
-------
pix : Pixel object
'''
param_keys = ['bandpass_filter', 'drive_freq', 'filter_bandwidth', 'n_taps',
'roi', 'sampling_rate', 'total_time', 'trigger', 'window', 'wavelet_analysis']
can_param_keys = ['amp_invols', 'def_invols', 'k', 'q_factor']
fit_param_keys = ['filter_amplitude', 'method', 'fit', 'fit_form']
params = {}
can_params = {}
fit_params = {}
for k, v in kwargs.items():
if k in param_keys:
params[k] = v
elif k in can_param_keys:
can_params[k] = v
elif k in fit_param_keys:
fit_params[k] = v
self.create_parameters(params, can_params, fit_params)
pix = ffta.pixel.Pixel(self.Z, self.parameters, self.can_params, **self.fit_params)
pix.analyze()
if plot:
pix.plot()
return pix
<file_sep>/ffta/load/load_ringdown.py
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 31 11:16:36 2020
@author: Raj
"""
import numpy as np
import h5py
from scipy.optimize import minimize
import os
import pyUSID as usid
from pycroscopy.io.write_utils import build_ind_val_dsets, Dimension
from ffta.load.load_hdf import load_folder
from ffta.load import gl_ibw
from ffta.pixel_utils import badpixels
from igor.binarywave import load as loadibw
from matplotlib import pyplot as plt
'''
Loads Ringdown data from raw .ibw and with the associated *.ibw Image file.
Usage:
>> h5_rd = load_ringdown.wrapper() # will prompt for folders
or
>> h5_rd = load_ringdown.wrapper(ibw_file_path='ringdown.ibw', rd_folder='ringdown_folder_path')
>> ffta.hdf_utils.load_ringdown.test_fitting(h5_rd, pixel=0, fit_time=[1.1, 5]) # tests fitting
>> h5_Q = ffta.hdf_utils.load_ringdown.reprocess_ringdown(h5_rd, fit_time=[1.1, 5]) #reprocesses the data
>> ffta.hdf_utils.load_ringdown.plot_ringdown(h5_rd.file, h5_path=h5_rd.parent.name) # plots
>> ffta.hdf_utils.load_ringdown.save_CSV_from_file(h5_rd.file, h5_path=h5_rd.parent.name) # saves CSV
By default, this will average the ringdown data together per-pixel and mirror to match the topography
'''
def wrapper(ibw_file_path='', rd_folder='', verbose=False, subfolder='/',
loadverbose=True, mirror=True, average=True, AMPINVOLS=100e-9):
"""
Wrapper function for processing a .ibw file and associated ringdown data
Average just uses the pixel-wise averaged data
Raw_Avg processes the raw deflection data, then averages those together
Loads .ibw single file an HDF5 format. Then appends the FF data to that HDF5
Parameters
----------
ibw_file_path : string, optional
Path to signal file IBW with images to add.
rd_folder : string, optional
Path to folder containing the Ringdown files and config file. If empty prompts dialogue
verbose : Boolean (Optional)
Whether or not to show print statements for debugging. Passed to Pycroscopy functions
loadverbose : Boolean (optional)
Whether to print any simple "loading Line X" statements for feedback
subfolder : str, optional
Specifies folder under root (/) to save data in. Default is standard pycroscopy format
average : bool, optional
Whether to automatically call the load_pixel_averaged_FF function to average data at each pixel
mirror : bool, optional
Whether to reverse the data on each line read (since data are usually saved during a RETRACE scan)
AMPINVOLS : float
inverted optical level sensitivity (scaling factor for amplitude).
if not provided, it will search for one in the attributes of h5_rd or use default
Returns
-------
h5_rd: USID Dataset
USIDataset of ringdown
"""
if not any(ibw_file_path):
ibw_file_path = usid.io_utils.file_dialog(caption='Select IBW Image ',
file_filter='IBW Files (*.ibw)')
if not any(rd_folder):
rd_folder = usid.io_utils.file_dialog(caption='Select Ringdown config in folder',
file_filter='Config File (*.cfg)')
rd_folder = '/'.join(rd_folder.split('/')[:-1])
tran = gl_ibw.GLIBWTranslator()
h5_path = tran.translate(ibw_file_path, ftype='ringdown',
verbose=verbose, subfolder=subfolder)
h5_path, data_files, parm_dict = load_folder(folder_path=rd_folder,
verbose=verbose,
file_name=h5_path)
if 'AMPINVOLS' not in parm_dict:
parm_dict.update({'AMPINVOLS': AMPINVOLS})
h5_rd = load_ringdown(data_files, parm_dict, h5_path,
verbose=verbose, loadverbose=loadverbose,
average=average, mirror=mirror)
return h5_rd
def load_ringdown(data_files, parm_dict, h5_path,
verbose=False, loadverbose=True, average=True, mirror=False):
"""
Generates the HDF5 file given path to files_list and parameters dictionary
Creates a Datagroup FFtrEFM_Group with a single dataset in chunks
Parameters
----------
data_files : list
List of the \*.ibw files to be invidually scanned
parm_dict : dict
Scan parameters to be saved as attributes
h5_path : string
Path to H5 file on disk
verbose : bool, optional
Display outputs of each function or not
loadverbose : Boolean (optional)
Whether to print any simple "loading Line X" statements for feedback
mirror : bool, optional
Flips the ibw signal if acquired during a retrace, so data match the topography pixel-to-pixel
Returns
-------
h5_path: str
The filename path to the H5 file created
"""
# e.g. if a 16000 point signal with 2000 averages and 10 pixels
# (10MHz sampling of a 1.6 ms long signal=16000, 200 averages per pixel)
# parm_dict['pnts_per_pixel'] = 200 (# signals at each pixel)
# ['pnts_per_avg'] = 16000 (# pnts per signal, called an "average")
# ['pnts_per_line'] = 2000 (# signals in each line)
num_rows = parm_dict['num_rows']
num_cols = parm_dict['num_cols']
# The signals are hard-coded in the AFM software as 800 points long
# Therefore, we can calculate pnts_per_pixel etc from the first file
signal = loadibw(data_files[0])['wave']['wData'] # Load data.
parm_dict['pnts_per_pixel'] = int(signal.shape[0] / (800 * num_cols))
parm_dict['pnts_per_avg'] = 800 # hard-coded in our AFM software
parm_dict['total_time'] = 16e-3 # hard-coded in our AFM software
if 'AMPINVOLS' not in parm_dict:
parm_dict.update({'AMPINVOLS': 100e-9})
pnts_per_avg = parm_dict['pnts_per_avg']
orig_pnts_per_pixel = parm_dict['pnts_per_pixel']
if average:
parm_dict['pnts_per_pixel'] = 1
parm_dict['pnts_per_line'] = num_cols
pnts_per_pixel = parm_dict['pnts_per_pixel']
pnts_per_line = parm_dict['pnts_per_line']
hdf = h5py.File(h5_path)
try:
rd_group = hdf.file.create_group('RD_Group')
except:
rd_group = usid.hdf_utils.create_indexed_group(hdf.file['/'], 'RD_Group')
pos_desc = [Dimension('X', 'm', np.linspace(0, parm_dict['FastScanSize'], num_cols * pnts_per_pixel)),
Dimension('Y', 'm', np.linspace(0, parm_dict['SlowScanSize'], num_rows))]
ds_pos_ind, ds_pos_val = build_ind_val_dsets(pos_desc, is_spectral=False, verbose=verbose)
spec_desc = [Dimension('Time', 's', np.linspace(0, parm_dict['total_time'], pnts_per_avg))]
ds_spec_inds, ds_spec_vals = build_ind_val_dsets(spec_desc, is_spectral=True)
for p in parm_dict:
rd_group.attrs[p] = parm_dict[p]
rd_group.attrs['pnts_per_line'] = num_cols # to change number of pnts in a line
h5_rd = usid.hdf_utils.write_main_dataset(rd_group, # parent HDF5 group
(num_rows * num_cols * pnts_per_pixel, pnts_per_avg),
# shape of Main dataset
'Ringdown', # Name of main dataset
'Amplitude', # Physical quantity contained in Main dataset
'nm', # Units for the physical quantity
pos_desc, # Position dimensions
spec_desc, # Spectroscopic dimensions
dtype=np.float32, # data type / precision
compression='gzip',
main_dset_attrs=parm_dict)
# Cycles through the remaining files. This takes a while (~few minutes)
for k, num in zip(data_files, np.arange(0, len(data_files))):
if loadverbose:
fname = k.replace('/', '\\')
print('####', fname.split('\\')[-1], '####')
fname = str(num).rjust(4, '0')
signal = loadibw(k)['wave']['wData']
signal = np.reshape(signal.T, [num_cols * orig_pnts_per_pixel, pnts_per_avg])
if average:
pixels = np.split(signal, num_cols, axis=0)
signal = np.vstack([np.mean(p, axis=0) for p in pixels])
signal *= parm_dict['AMPINVOLS']
if mirror:
h5_rd[num_cols * pnts_per_pixel * num: num_cols * pnts_per_pixel * (num + 1), :] = np.flipud(signal[:, :])
else:
h5_rd[num_cols * pnts_per_pixel * num: num_cols * pnts_per_pixel * (num + 1), :] = signal[:, :]
if verbose == True:
usid.hdf_utils.print_tree(hdf.file, rel_paths=True)
return h5_rd
def reprocess_ringdown(h5_rd, fit_time=[1, 5]):
'''
Reprocess ringdown data using an exponential fit around the timescales indicated.
Parameters
----------
h5_rd : USIDataset
Ringdown dataset
fit_time : list
The times (in milliseconds) to fit between. This function uses a single exponential fit
'''
h5_gp = h5_rd.parent
drive_freq = h5_rd.attrs['drive_freq']
Q = np.zeros([h5_rd[()].shape[0]])
A = np.zeros([h5_rd[()].shape[0]])
tx = np.arange(0, h5_rd.attrs['total_time'], h5_rd.attrs['total_time'] / h5_rd.attrs['pnts_per_avg'])
[start, stop] = [np.searchsorted(tx, fit_time[0] * 1e-3), np.searchsorted(tx, fit_time[1] * 1e-3)]
for n, pxl in enumerate(h5_rd[()]):
popt = fit_exp(tx[start:stop], pxl[start:stop] * 1e9)
popt[0] *= 1e-9
popt[1] *= 1e-9
Q[n] = popt[2] * np.pi * drive_freq
A[n] = popt[1]
Q = np.reshape(Q, [h5_rd.attrs['num_rows'], h5_rd.attrs['num_cols']])
A = np.reshape(A, [h5_rd.attrs['num_rows'], h5_rd.attrs['num_cols']])
h5_Q_gp = usid.hdf_utils.create_indexed_group(h5_gp, 'Reprocess') # creates a new group
h5_Q = h5_Q_gp.create_dataset('Q', data=Q, dtype=np.float32)
h5_A = h5_Q_gp.create_dataset('Amplitude', data=A, dtype=np.float32)
h5_Q_gp.attrs['fit_times'] = [a * 1e-3 for a in fit_time]
return h5_Q
def test_fitting(h5_rd, pixel=0, fit_time=[1, 5], plot=True):
'''
Tests curve fitting on a particular pixel, then plots the result
Parameters
----------
h5_rd : USIDataset
Ringdown dataset
pixel : int
Which pixel to fit to.
fit_time : list
The times (in milliseconds) to fit between. This function uses a single exponential fit
'''
drive_freq = h5_rd.attrs['drive_freq']
tx = np.arange(0, h5_rd.attrs['total_time'], h5_rd.attrs['total_time'] / h5_rd.attrs['pnts_per_avg'])
[start, stop] = [np.searchsorted(tx, fit_time[0] * 1e-3), np.searchsorted(tx, fit_time[1] * 1e-3)]
cut = h5_rd[()][pixel]
popt = fit_exp(tx[start:stop], cut[start:stop] * 1e9) # 1e9 for amplitude for better curve-fitting
popt[0] *= 1e-9
popt[1] *= 1e-9
if plot:
print('Fit params:', popt, ' and Q=', popt[2] * drive_freq * np.pi)
fig, a = plt.subplots()
a.plot(tx, cut, 'k')
a.plot(tx[start:stop], exp(tx[start:stop] - tx[start], *popt), 'g--')
a.set_xlabel('Time (s)')
a.set_ylabel('Amplitude (nm)')
return popt
def save_CSV_from_file(h5_file, h5_path='/', append='', mirror=False):
"""
Saves the Q, Amp, as CSV files
Parameters
----------
h5_file : H5Py file
Reminder you can always type: h5_svd.file or h5_avg.file for this
h5_path : str, optional
specific folder path to search for the tfp data. Usually not needed.
append : str, optional
text to append to file name (e.g. RD01 or something related to the file)
"""
Q = usid.hdf_utils.find_dataset(h5_file[h5_path], 'Q')[-1][()]
A = usid.hdf_utils.find_dataset(h5_file[h5_path], 'Amplitude')[-1][()]
Q_fixed, _ = badpixels.fix_array(Q, threshold=2)
print(usid.hdf_utils.find_dataset(h5_file[h5_path], 'Q')[-1].parent.name)
path = h5_file.file.filename.replace('\\', '/')
path = '/'.join(path.split('/')[:-1]) + '/'
os.chdir(path)
if mirror:
np.savetxt('Q-' + append + '.csv', np.fliplr(Q).T, delimiter=',')
np.savetxt('Qfixed-' + append + '.csv', np.fliplr(Q_fixed).T, delimiter=',')
np.savetxt('Amp-' + append + '.csv', np.fliplr(A).T, delimiter=',')
else:
np.savetxt('Q' + append + '.csv', Q.T, delimiter=',')
np.savetxt('Qfixed-' + append + '.csv', Q_fixed.T, delimiter=',')
np.savetxt('Amp-' + append + '.csv', A.T, delimiter=',')
return
def exp(t, A1, y0, tau):
'''Uses a single exponential for the case of no drive'''
return y0 + A1 * np.exp(-t / tau)
def fit_exp(t, cut):
# Cost function to minimize. Faster than normal scipy optimize or lmfit
cost = lambda p: np.sum((exp(t - t[0], *p) - cut) ** 2)
pinit = [cut.max() - cut.min(), cut.min(), 1e-4]
bounds = [(0, 5 * (cut.max() - cut.min())), (0, cut.min()), (1e-8, 1)]
popt = minimize(cost, pinit, method='TNC', bounds=bounds)
return popt.x
def plot_ringdown(h5_file, h5_path='/', append='', savefig=True, stdevs=2):
"""
Plots the relevant tfp, inst_freq, and shift values as separate image files
Parameters
----------
h5_file : h5Py File
h5_path : str, optional
Location of the relevant datasets to be saved/plotted. e.g. h5_rb.name
append : str, optional
A string to include in the saved figure filename
savefig : bool, optional
Whether or not to save the image
stdevs : int, optional
Number of standard deviations to display
"""
# h5_rd = usid.hdf_utils.find_dataset(h5_file[h5_path], 'Ringdown')[0]
if 'Dataset' in str(type(h5_file[h5_path])):
h5_path = h5_file[h5_path].parent.name
Q = usid.hdf_utils.find_dataset(h5_file[h5_path], 'Q')[0][()]
A = usid.hdf_utils.find_dataset(h5_file[h5_path], 'Amplitude')[0][()]
Q_fixed, _ = badpixels.fix_array(Q, threshold=2)
A_fixed, _ = badpixels.fix_array(A, threshold=2)
parm_dict = usid.hdf_utils.get_attributes(h5_file[h5_path])
if 'FastScanSize' not in parm_dict:
parm_dict = usid.hdf_utils.get_attributes(h5_file[h5_path].parent)
xs = parm_dict['FastScanSize']
ys = parm_dict['SlowScanSize']
asp = ys / xs
if asp != 1:
asp = asp * 2
fig, a = plt.subplots(nrows=2, figsize=(8, 9))
_, cbar_t = usid.viz.plot_utils.plot_map(a[0], Q_fixed, x_vec=xs * 1e6, y_vec=ys * 1e6,
aspect=asp, cmap='inferno', stdevs=stdevs)
_, cbar_s = usid.viz.plot_utils.plot_map(a[1], A_fixed * 1e9, x_vec=xs * 1e6, y_vec=ys * 1e6,
aspect=asp, cmap='inferno', stdevs=stdevs)
cbar_t.set_label('Q (a.u.)', rotation=270, labelpad=16)
a[0].set_title('Q', fontsize=12)
cbar_s.set_label('Amplitude (nm)', rotation=270, labelpad=16)
a[1].set_title('Amplitude', fontsize=12)
fig.tight_layout()
if savefig:
path = h5_file.file.filename.replace('\\', '/')
path = '/'.join(path.split('/')[:-1]) + '/'
os.chdir(path)
fig.savefig('Q_Amp_' + append + '_.tif', format='tiff')
return fig, a
<file_sep>/XOP/Analyze.cpp
#include "XOPStandardHeaders.h"
#include "Python.h"
#include "C:\Python27\Lib\site-packages\numpy\core\include\numpy\arrayobject.h"
#include <chrono>
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION // we aren't using enough numpy API to worry about this.
int AnalyzePixel(double *tfp, double* shift, double trigger, double total_time, double sampling_rate, double drive_freq, int window, int bandpass_filter, double filter_bandwidth, double** signal_array, int n_points, int n_signals)
{
PyObject *pName, *pModule, *pDict, *pClass, *pInstance, *pValue, *classArgs, *mat, *pyTfp, *pyShift, *pValue2, *pFunc;
PyObject *pyTrigger, *pyTotal_Time, *pySampling_Rate, *pyDrive_Freq, *pyWindow, *pyBandpass_Filter, *pyFilter_Bandwidth;
char noticeStr[50]; // string for XOP messaging
Py_Initialize();
//Every Numpy C API needs this call.
import_array1(-1);
//name of the python script to interface with.
pName = PyString_FromString("pixel");
// Import the analysis code.
pModule = PyImport_Import(pName);
if (pModule == NULL){
PyErr_Print();
}
// Get the callable objects.
pDict = PyModule_GetDict(pModule);
// Define values for parameter dictionary.
pyTrigger = PyFloat_FromDouble(trigger);
pyTotal_Time = PyFloat_FromDouble(total_time);
pySampling_Rate = PyFloat_FromDouble(sampling_rate);
pyDrive_Freq = PyFloat_FromDouble(drive_freq);
pyWindow = PyBool_FromLong(window);
pyBandpass_Filter = PyBool_FromLong(bandpass_filter);
pyFilter_Bandwidth = PyFloat_FromDouble(filter_bandwidth);
// Place some key:values into our parameter dictionary.
classArgs = PyDict_New();
PyDict_SetItemString(classArgs, "trigger", pyTrigger);
PyDict_SetItemString(classArgs, "total_time", pyTotal_Time);
PyDict_SetItemString(classArgs, "sampling_rate", pySampling_Rate);
PyDict_SetItemString(classArgs, "drive_freq", pyDrive_Freq);
PyDict_SetItemString(classArgs, "window", pyWindow);
PyDict_SetItemString(classArgs, "bandpass_filter", pyBandpass_Filter);
PyDict_SetItemString(classArgs, "filter_bandwidth", pyFilter_Bandwidth);
// Build the name of a callable class .
pClass = PyDict_GetItemString(pDict, "Pixel");
// dimension of the signal_array.
int mdim[] = { n_points, n_signals };
// Send our data into a numpy ndarray.
mat = PyArray_SimpleNewFromData(2, mdim, PyArray_DOUBLE, signal_array[0]);
// Create tuple of arguments used to initialize the class.
PyObject* args = PyTuple_New(2);
PyTuple_SetItem(args, 0, mat);
PyTuple_SetItem(args, 1, classArgs);
// Initialize the class into pInstance.
pInstance = PyObject_CallObject(pClass, args);
//if (pInstance == NULL){
//}
// Call a method of the class with no parameters
pValue = PyObject_CallMethod(pInstance, "get_tfp", NULL);
Py_XDECREF(pInstance);
Py_XDECREF(mat);
Py_XDECREF(classArgs);
if (pValue == NULL){
}
if (pValue != NULL)
{
pyTfp = PyTuple_GetItem(pValue, 0);
pyShift = PyTuple_GetItem(pValue, 1);
(*tfp) = PyFloat_AsDouble(pyTfp);
(*shift) = PyFloat_AsDouble(pyShift);
Py_XDECREF(pValue);
}
else
{
PyErr_Print();
}
// Clean up
Py_XDECREF(pModule);
Py_XDECREF(pName);
//
//Py_Finalize();
return 0;
}
<file_sep>/ffta/pixel_utils/__init__.py
__all__ = ['load', 'noise']
from . import load<file_sep>/ffta/pixel_utils/load.py
"""load.py: Includes routines for loading data and configuration files."""
__author__ = "<NAME>"
__copyright__ = "Copyright 2018, Ginger Lab"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
__status__ = "Development"
import configparser
import sys
from igor.binarywave import load as loadibw
from numpy.lib.npyio import loadtxt
from os.path import splitext
import numpy as np
import pandas as pd
def signal(path, skiprows=0):
"""
Loads .ibw or ASCII files and return it as a numpy.ndarray.
Parameters
----------
path : string
Path to signal file.
Returns
-------
signal_array : (n_points, n_signals) array_like
2D real-valued signal array loaded from given .ibw file.
"""
# Get the path and check what the extension is.
ext = splitext(path)[1]
if ext.lower() == '.ibw':
signal_array = loadibw(path)['wave']['wData'] # Load data.
elif ext.lower() == '.txt':
signal_array = loadtxt(path, skiprows=skiprows)
else:
print("Unrecognized file type!")
sys.exit(0)
try:
signal_array.flags.writeable = True # Make array writable.
except:
pass
return signal_array
def configuration(path):
"""
Reads an ASCII file with relevant parameters for processing.
Parameters
----------
path : string
Path to ASCII file.
Returns
-------
n_pixels: int
Number of pixels in the image.
parameters : dict
The list of parameters is:
trigger = float (in seconds)
total_time = float (in seconds)
sampling_rate = int (in Hz)
drive_freq = float (in Hz)
Q = float (default: 500)
roi = float (in seconds)
window = string (see documentation of scipy.signal.get_window)
bandpass_filter = int (0: no filtering, 1: FIR filter, 2: IIR filter)
filter_bandwidth = float (in Hz)
n_taps = integer (default: 999)
wavelet_analysis = bool (0: Hilbert method, 1: Wavelet Method)
wavelet_parameter = int (default: 5)
recombination = bool (0: FF-trEFMm, 1: Recombination)
phase_fitting = bool (0: frequency fitting, 1: phase fitting)
EMD_analysis = bool (0: Hilbert method, 1: Hilbert-Huang fitting)
fit_form = string (EXP, PRODUCT, SUM for type of fit function)
"""
# Create a parser for configuration file and parse it.
config = configparser.RawConfigParser()
config.read(path)
parameters = {}
# These are the keys for parameters.
paraf_keys = ['trigger', 'total_time', 'drive_freq',
'sampling_rate', 'Q']
parai_keys = ['n_pixels', 'pts_per_pixel', 'lines_per_image']
procs_keys = ['window', 'fit_form']
procf_keys = ['roi', 'FastScanSize', 'SlowScanSize', 'liftheight']
proci_keys = ['n_taps', 'filter_bandwidth', 'bandpass_filter',
'wavelet_analysis', 'wavelet_parameter', 'recombination',
'phase_fitting', 'EMD_analysis']
# Check if the configuration file has n_pixel,
# if not assume single pixel.
if config.has_option('Parameters', 'n_pixels'):
n_pixels = config.getint('Parameters', 'n_pixels')
else:
n_pixels = int(1)
# Loop through the parameters and assign them.
for key in paraf_keys:
if config.has_option('Parameters', key):
parameters[key] = config.getfloat('Parameters', key)
for key in parai_keys:
if config.has_option('Parameters', key):
parameters[key] = config.getint('Parameters', key)
for key in procf_keys:
if config.has_option('Processing', key):
parameters[key] = config.getfloat('Processing', key)
for key in procs_keys:
if config.has_option('Processing', key):
parameters[key] = config.get('Processing', key)
for key in proci_keys:
if config.has_option('Processing', key):
parameters[key] = config.getint('Processing', key)
return n_pixels, parameters
def cantilever_params(path, asDataFrame=False):
'''
Reads an experimental Parameters file describing the cantilever.
Cantilever parameters should contain an Initial, Final, and Differential\
column for describing an excited cantilever
Parameters
----------
path: str
Path to the parameters file
asDataFrame : bool
Returns Pandas dataframe instead of a dictionary
returns:
-------
can_params : dict
'''
try:
df = pd.read_csv(path, sep='\t', skiprows=1, index_col='Unnamed: 0')
except:
df = pd.read_csv(path, sep=',', skiprows=1, index_col=r'x/y')
for c in df.columns:
df[c][df[c] != 'NAN'] = pd.to_numeric(df[c][df[c] != 'NAN'])
df[c][df[c] == 'NAN'] = np.NaN
if asDataFrame:
return df
return df.to_dict()
<file_sep>/ffta/analysis/svd.py
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 7 22:04:39 2018
@author: Raj
"""
import pycroscopy as px
import pyUSID as usid
import numpy as np
from pycroscopy.processing.svd_utils import SVD
from matplotlib import pyplot as plt
from ffta.hdf_utils import hdf_utils
from ffta.load import get_utils
import h5py
"""
Wrapper to SVD functions, specific to ffta Class.
Typical usage:
>> h5_svd = svd.test_svd(h5_avg)
>> clean = [0,1,2,3] # to filter to only first 4 components
>> h5_rb = svd.svd_filter(h5_avg, clean_components=clean)
"""
def test_svd(h5_main, num_components=128, show_plots=True, override=True, verbose=True):
"""
Parameters
----------
h5_main : h5Py Dataset
Main dataset to filter
num_components : int, optional
Number of SVD components. Increasing this lenghtens computation
show_plots : bool, optional
If True displays skree, abundance_maps, and data loops
override : bool, optional
Force SVD.Compute to reprocess data no matter what
verbose : bool, optional
Print out component ratio values
Returns
-------
h5_svd_group : h5Py Group
Group containing the h5_svd data
"""
if not (isinstance(h5_main, usid.USIDataset)):
h5_main = usid.USIDataset(h5_main)
h5_svd = SVD(h5_main, num_components=num_components)
[num_rows, num_cols] = h5_main.pos_dim_sizes
# performs SVD
h5_svd_group = h5_svd.compute(override=override)
h5_S = h5_svd_group['S']
if verbose:
skree_sum = np.zeros(h5_S.shape)
for i in range(h5_S.shape[0]):
skree_sum[i] = np.sum(h5_S[:i]) / np.sum(h5_S)
print('Need', skree_sum[skree_sum < 0.8].shape[0], 'components for 80%')
print('Need', skree_sum[skree_sum < 0.9].shape[0], 'components for 90%')
print('Need', skree_sum[skree_sum < 0.95].shape[0], 'components for 95%')
print('Need', skree_sum[skree_sum < 0.99].shape[0], 'components for 99%')
if show_plots:
plot_svd(h5_svd_group)
return h5_svd_group
def svd_filter(h5_main, clean_components=None):
"""
Filters data given the array clean_components
Clean_components has 2 components will filter from start to finish
Clean_components has 3+ components will use those individual components
Parameters
----------
h5_main : h5Py
Dataset to be filtered and reconstructed.
This must be the same as where SVD was performed
"""
if not (isinstance(h5_main, usid.USIDataset)):
h5_main = usid.USIDataset(h5_main)
h5_rb = px.processing.svd_utils.rebuild_svd(h5_main, components=clean_components)
parameters = get_utils.get_params(h5_main)
for key in parameters:
if key not in h5_rb.attrs:
h5_rb.attrs[key] = parameters[key]
return h5_rb
def plot_svd(h5_main, savefig=False, num_plots=16, **kwargs):
'''
Replots the SVD showing the skree, abundance maps, and eigenvectors.
If h5_main is the results group, then it will plot the values for that group.
If h5_main is a Dataset, it will default to the most recent SVD group.
Parameters
----------
h5_main : USIDataset or h5py Dataset or h5py Group
savefig : bool, optional
Saves the figures to disk
num_plots : int
Default number of eigenvectors and abundance plots to show
kwargs : dict, optional
keyword arguments for svd filtering
Returns
-------
None
'''
if isinstance(h5_main, h5py.Group):
_U = usid.hdf_utils.find_dataset(h5_main, 'U')[-1]
_V = usid.hdf_utils.find_dataset(h5_main, 'V')[-1]
units = 'arbitrary (a.u.)'
h5_spec_vals = np.arange(_V.shape[1])
h5_svd_group = _U.parent
else:
h5_svd_group = usid.hdf_utils.find_results_groups(h5_main, 'SVD')[-1]
units = h5_main.attrs['quantity']
h5_spec_vals = h5_main.get_spec_values('Time')
h5_U = h5_svd_group['U']
h5_V = h5_svd_group['V']
h5_S = h5_svd_group['S']
_U = usid.USIDataset(h5_U)
[num_rows, num_cols] = _U.pos_dim_sizes
abun_maps = np.reshape(h5_U[:, :16], (num_rows, num_cols, -1))
eigen_vecs = h5_V[:16, :]
skree_sum = np.zeros(h5_S.shape)
for i in range(h5_S.shape[0]):
skree_sum[i] = np.sum(h5_S[:i]) / np.sum(h5_S)
plt.figure()
plt.plot(skree_sum, 'bo')
plt.title('Cumulative Variance')
plt.xlabel('Total Components')
plt.ylabel('Total variance ratio (a.u.)')
if savefig:
plt.savefig('Cumulative_variance_plot.png')
fig_skree, axes = usid.viz.plot_utils.plot_scree(h5_S, title='Scree plot')
fig_skree.tight_layout()
if savefig:
plt.savefig('Scree_plot.png')
fig_abun, axes = usid.viz.plot_utils.plot_map_stack(abun_maps, num_comps=num_plots, title='SVD Abundance Maps',
color_bar_mode='single', cmap='inferno', reverse_dims=True,
fig_mult=(3.5, 3.5), facecolor='white', **kwargs)
fig_abun.tight_layout()
if savefig:
plt.savefig('Abundance_maps.png')
fig_eigvec, axes = usid.viz.plot_utils.plot_curves(h5_spec_vals * 1e3, eigen_vecs, use_rainbow_plots=False,
x_label='Time (ms)', y_label=units,
num_plots=num_plots, subtitle_prefix='Component',
title='SVD Eigenvectors', evenly_spaced=False,
**kwargs)
fig_eigvec.tight_layout()
if savefig:
plt.savefig('Eigenvectors.png')
return
<file_sep>/ffta/load/load_commands.py
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 30 15:53:47 2020
@author: Raj
"""
from __future__ import division, print_function, absolute_import, unicode_literals
__author__ = "<NAME>"
__copyright__ = "Copyright 2018, Ginger Lab"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
__status__ = "Development"
import h5py
import pyUSID as usid
from ffta.load import get_utils
def hdf_commands(h5_path, ds='FF_Raw'):
"""
Creates a bunch of typical workspace HDF5 variables for scripting use
Parameters
----------
h5_path : str
String path to H5PY file
ds : str, optional
The dataset to search for and set as h5_main.
This prints the valid commands to the workspace. Then just highlight and
copy-paste to execute
h5_path : str
Path to hdf5 file on disk
"""
commands = ['***Copy-paste all commands below this line, then hit ENTER***',
'import h5py']
if not isinstance(h5_path, str):
raise TypeError('Pass a file path (string), not an H5 file')
try:
hdf = h5py.File(h5_path, 'r+')
commands.append("hdf = h5py.File(h5_path, 'r+')")
except:
pass
try:
h5_file = hdf.file
commands.append("h5_file = hdf.file")
except:
pass
try:
h5_main = usid.hdf_utils.find_dataset(hdf.file, ds)[0]
commands.append("h5_main = usid.hdf_utils.find_dataset(hdf.file, '" + ds + "')[0]")
except:
pass
try:
h5_if = usid.hdf_utils.find_dataset(hdf.file, 'inst_freq')[-1]
commands.append("h5_if = usid.hdf_utils.find_dataset(hdf.file, 'inst_freq')[-1]")
except:
pass
try:
h5_if = usid.hdf_utils.find_dataset(hdf.file, 'Inst_Freq')[-1]
commands.append("h5_if = usid.hdf_utils.find_dataset(hdf.file, 'Inst_Freq')[-1]")
except:
pass
try:
h5_tfp = usid.hdf_utils.find_dataset(hdf.file, 'tfp')[-1]
commands.append("h5_tfp= usid.hdf_utils.find_dataset(hdf.file, 'tfp')[-1]")
except:
pass
try:
h5_shift = usid.hdf_utils.find_dataset(hdf.file, 'shift')[-1]
commands.append("h5_shift= usid.hdf_utils.find_dataset(hdf.file, 'shift')[-1]")
except:
pass
try:
h5_avg = usid.hdf_utils.find_dataset(hdf.file, 'FF_Avg')[-1]
commands.append("h5_avg = usid.hdf_utils.find_dataset(hdf.file, 'FF_Avg')[-1]")
except:
pass
try:
h5_filt = usid.hdf_utils.find_dataset(hdf.file, 'Filtered_Data')[-1]
commands.append("h5_filt = usid.hdf_utils.find_dataset(hdf.file, 'Filtered_Data')[-1]")
except:
pass
try:
h5_rb = usid.hdf_utils.find_dataset(hdf.file, 'Rebuilt_Data')[-1]
commands.append("h5_rb = usid.hdf_utils.find_dataset(hdf.file, 'Rebuilt_Data')[-1]")
except:
pass
try:
parameters = usid.hdf_utils.get_attributes(h5_avg)
commands.append("parameters = usid.hdf_utils.get_attributes(h5_avg)")
except:
pass
try:
h5_ll = get_utils.get_line(h5_if, line_num=0)
commands.append("h5_ll = ffta.load.get_utils.get_line(h5_if, line_num=0)")
except:
pass
try:
h5_px = get_utils.get_pixel(h5_if, rc=[0, 0])
commands.append("h5_px = ffta.load.get_utils.get_pixel(h5_if, rc=[0,0])")
except:
pass
try:
h5_svd = usid.hdf_utils.find_dataset(hdf.file, 'U')[-1]
commands.append("h5_svd = usid.hdf_utils.find_dataset(hdf.file, 'U')[-1].parent")
except:
pass
try:
h5_cpd = usid.hdf_utils.find_dataset(hdf.file, 'cpd')[-1]
commands.append("h5_cpd = usid.hdf_utils.find_dataset(hdf.file, 'cpd')[-1]")
except:
pass
try:
h5_ytime = usid.hdf_utils.find_dataset(hdf.file, 'y_time')[-1]
commands.append("h5_ytime = usid.hdf_utils.find_dataset(hdf.file, 'y_time')[-1]")
except:
pass
try:
h5_Y = usid.hdf_utils.find_dataset(hdf.file, 'Y')[-1]
commands.append("h5_Y = usid.hdf_utils.find_dataset(hdf.file, 'Y')[-1]")
except:
pass
for i in commands:
print(i)
return
<file_sep>/ffta/analysis/dist_cluster.py
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 22 21:19:26 2018
@author: Raj
"""
import numpy as np
import sklearn as sk
import pycroscopy as px
from pycroscopy.processing.cluster import Cluster
import pyUSID as usid
from pyUSID.processing.process import Process
from pyUSID.io.write_utils import build_ind_val_matrices, Dimension
from matplotlib import pyplot as plt
import matplotlib.animation as animation
from ffta.analysis import mask_utils
from ffta.hdf_utils import hdf_utils
from ffta.load import get_utils
from ffta import pixel
"""
Creates a Class with various data grouped based on distance to masked edges
Typical usage:
>> mymask = mask_utils.load_mask_txt('Path_mask.txt')
>> tfp_clust = dist_cluster.dist_cluster(h5_main, mask=mymask, data_avg='tfp')
>> tfp_clust.analyze()
>> tfp_clust.plot_img()
>> tfp_clust.kmeans()
>> tfp_clust.plot_kmeans()
To do:
Implement dist_cluster as implementation of pycroscopy Cluster class
"""
class dist_cluster:
def __init__(self, h5_main, data_avg, mask, results=None, isCPD=False, parms_dict=None):
"""
Parameters
----------
h5_main : h5Py dataset or str
File type to be processed.
mask : ndarray
mask file to be loaded, is expected to be of 1 (transparent) and 0 (opaque)
loaded e.g. mask = mask_utils.loadmask('E:/ORNL/20191221_BAPI/nice_masks/Mask_BAPI20_0008.txt')
parms_dict : dict
Parameters file used for the image. Must contain at minimum:
num_rows, num_cols, sampling_rate, FastScanSize, SlowScanSize, total_time
data_avg : str
The file to use as the "averaged" data upon which to apply the mask and do calculations
e.g. 'tfp' searches within the h5_main parent folder for 'tfp'
results : clustering results
If you want to pass some previously-calculated results..
isCPD : bool, optional,
toggle between GMode and FFtrEFM data, this is just for plotting
"""
self.h5_main = h5_main
if isinstance(data_avg, str):
self.data_avg = usid.hdf_utils.find_dataset(h5_main.parent, data_avg)[0].value
elif isinstance(data_avg, np.ndarray):
self.data_avg = usid.hdf_utils.find_dataset(h5_main.parent, 'tfp')[0].value
else:
raise ValueError('Wrong format for data_avg')
if results:
self.results = results
self.isCPD = isCPD
# Set up datasets data
self.data = self.h5_main[()]
self.parms_dict = parms_dict
if parms_dict == None:
print('get params')
self.parms_dict = get_utils.get_params(h5_main)
self._params()
# Create mask for grain boundaries
if not mask.any():
mask = np.ones([self.num_rows, self.num_cols])
self.mask = mask
self.mask_nan, self.mask_on_1D, self.mask_off_1D = mask_utils.load_masks(self.mask)
self._idx_1D = np.copy(self.mask_off_1D)
return
def _params(self):
""" creates CPD averaged data and extracts parameters """
parms_dict = self.parms_dict
self.num_rows = parms_dict['num_rows']
self.num_cols = parms_dict['num_cols']
self.sampling_rate = parms_dict['sampling_rate']
self.FastScanSize = parms_dict['FastScanSize']
self.SlowScanSize = parms_dict['SlowScanSize']
self.xvec = np.linspace(0, self.FastScanSize, self.num_cols)
self.yvec = np.linspace(0, self.SlowScanSize, self.num_rows)
# IO_rate = parms_dict['IO_rate_[Hz]'] #sampling_rate
self.pxl_time = parms_dict['total_time'] # seconds per pixel
self.dt = self.pxl_time / self.data.shape[1]
self.aspect = self.num_rows / self.num_cols
return
def analyze(self):
"""
Creates 1D arrays of data and masks
Then, calculates the distances and saves those.
This also creates data_scatter within the distances function
"""
# Create 1D arrays
self._data_1D_values(self.mask)
self._make_distance_arrays()
self.data_dist, _ = self._distances(self.data_1D_pos, self.mask_on_1D_pos)
return
def _data_1D_values(self, mask):
"""
Uses 1D Mask file (with NaN and 0) and generates data of non-grain boundary regions
Parameters
----------
mask : ndarray, 2D
Unmasked locations (indices) as 1D location
data_1D_vals : data as a 1D array with data points (num_rows*num_cols X pnts_per_data)
data_avg_1D_vals : Average data (CPD_on_avg/tfP_fixed, say) that is 1D
"""
ones = np.where(mask == 1)
self.data_avg_1D_vals = np.zeros(ones[0].shape[0])
self.data_1D_vals = np.zeros([ones[0].shape[0], self.data.shape[1]])
for r, c, x in zip(ones[0], ones[1], np.arange(self.data_avg_1D_vals.shape[0])):
self.data_avg_1D_vals[x] = self.data_avg[r][c]
self.data_1D_vals[x, :] = self.data[self.num_cols * r + c, :]
return
def plot_img(self):
if self.data_avg is not None:
fig, ax = plt.subplots(nrows=1, figsize=(12, 6))
_, cbar = usid.plot_utils.plot_map(ax, self.data_avg * 1e6,
x_vec=self.xvec * 1e6, y_vec=self.yvec * 1e6,
cmap='inferno', aspect=self.aspect)
cbar.set_label('tFP (us)', rotation=270, labelpad=16)
ax.imshow(self.mask_nan)
return fig, ax
def _make_distance_arrays(self):
"""
Generates 1D arrays where the coordinates are scaled to image dimensions
Generates
-------
mask_on_1D_pos : ndarray Nx2
Where mask is applied (e.g. grain boundaries)
mask_off_1D_pos : ndarray Nx2
Where mask isn't applied (e.g. grains)
data_1D_pos : ndarray Nx2
Identical to mask_off_1D_scaled, this exists just for easier bookkeeping
without fear of overwriting one or the other
"""
csz = self.FastScanSize / self.num_cols
rsz = self.SlowScanSize / self.num_rows
mask_on_1D_pos = np.zeros([self.mask_on_1D.shape[0], 2])
mask_off_1D_pos = np.zeros([self.mask_off_1D.shape[0], 2])
for x, y in zip(self.mask_on_1D, np.arange(mask_on_1D_pos.shape[0])):
mask_on_1D_pos[y, 0] = x[0] * rsz
mask_on_1D_pos[y, 1] = x[1] * csz
for x, y in zip(self.mask_off_1D, np.arange(mask_off_1D_pos.shape[0])):
mask_off_1D_pos[y, 0] = x[0] * rsz
mask_off_1D_pos[y, 1] = x[1] * csz
self.data_1D_pos = np.copy(mask_off_1D_pos) # to keep straight, but these are the same
self.mask_on_1D_pos = mask_on_1D_pos
self.mask_off_1D_pos = mask_off_1D_pos
return
def _distances(self, data_1D_pos, mask_on_1D_pos):
"""
Calculates pairwise distance between CPD array and the mask on array.
For each pixel, this generates a minimum distance that defines the "closeness" to
a grain boundary in the mask
Returns to Class
----------------
data_scatter : distances x data_points (full data at each distance)
data_avg_scatter : distances x 1 (data_average at each distance)
data_dist : minimum pairwise distances to mask
data_avg_dist : mean of pairwise distances to maks
"""
self.data_dist = np.zeros(data_1D_pos.shape[0])
self.data_avg_dist = np.zeros(data_1D_pos.shape[0])
# finds distance to nearest mask pixel
for i, x in zip(data_1D_pos, np.arange(self.data_dist.shape[0])):
d = sk.metrics.pairwise_distances([i], mask_on_1D_pos)
self.data_dist[x] = np.min(d)
self.data_avg_dist[x] = np.mean(d)
# create single [x,y] dataset
self.data_avg_scatter = np.zeros([self.data_dist.shape[0], 2])
for x, y, z in zip(self.data_dist, self.data_avg_1D_vals, np.arange(self.data_dist.shape[0])):
self.data_avg_scatter[z] = [x, y]
self.data_scatter = np.copy(self.data_1D_vals)
self.data_scatter = np.insert(self.data_scatter, 0, self.data_dist, axis=1)
return self.data_dist, self.data_avg_dist
def write_results(self, verbose=False, name='inst_freq_masked'):
''' Writes a new main data set'''
h5_dist_clust_group = px.hdf_utils.create_indexed_group(self.h5_main.parent, 'dist-cluster')
# Create dimensions
pos_desc = [Dimension('Grain Distance', 'm', self.data_dist)]
ds_pos_ind, ds_pos_val = build_ind_val_dsets(pos_desc, is_spectral=False, verbose=verbose)
spec_desc = [Dimension('Time', 's', np.linspace(0, self.pxl_time, self.parms_dict['pnts_per_avg']))]
ds_spec_inds, ds_spec_vals = build_ind_val_dsets(spec_desc, is_spectral=True, verbose=verbose)
# Writes main dataset
h5_clust = px.hdf_utils.write_main_dataset(h5_dist_clust_group,
self.data_scatter[:, 1:],
name, # Name of main dataset
'Frequency', # Physical quantity contained in Main dataset
'Hz', # Units for the physical quantity
pos_desc, # Position dimensions
spec_desc, # Spectroscopic dimensions
dtype=np.float32, # data type / precision
main_dset_attrs=self.parms_dict)
# Adds mask and grain min distances and mean distances
grp = px.io.VirtualGroup(h5_dist_clust_group.name)
mask = px.io.VirtualDataset('mask', self.mask, parent=self.h5_main.parent)
dist_min = px.io.VirtualDataset('dist_min', self.data_dist, parent=self.h5_main.parent)
dist_mean = px.io.VirtualDataset('dist_mean', self.data_avg_dist, parent=self.h5_main.parent)
data_pos = px.io.VirtualDataset('coordinates', self.mask_off_1D_pos, parent=self.h5_main.parent)
data_avg = px.io.VirtualDataset('data_avg', self.data_avg_1D_vals, parent=self.h5_main.parent)
grp.add_children([mask])
grp.add_children([dist_min])
grp.add_children([dist_mean])
grp.add_children([data_pos])
grp.add_children([data_avg])
# Find folder, write to it
hdf = px.io.HDFwriter(self.h5_main.file)
h5_refs = hdf.write(grp, print_log=verbose)
return h5_clust
def kmeans(self, clusters=3, show_results=False, plot_mid=[]):
""""
Simple k-means
Data typically is self.CPD_scatter
Parameters
----------
plot_pts : list
Index of where to plot (i.e. when light is on). Defaults to p_on:p_off
Returns
-------
self.results : KMeans type
self.segments : dict, Nclusters
Contains the segmented arrays for displaying
"""
data = self.data_scatter[:, 1:]
# create single [x,y] dataset
estimators = sk.cluster.KMeans(clusters)
self.results = estimators.fit(data)
if show_results:
ax, fig = self.plot_kmeans(plot_mid=plot_mid)
return self.results, ax, fig
return self.results
def plot_kmeans(self, plot_mid=[]):
labels = self.results.labels_
cluster_centers = self.results.cluster_centers_
labels_unique = np.unique(labels)
self.segments = {}
self.clust_tfp = []
if not any(plot_mid):
plot_mid = [0, int(self.data_scatter.shape[1] / 2)]
# color defaults are blue, orange, green, red, purple...
colors = ['#1f77b4', '#ff7f0e', '#2ca02c',
'#d62728', '#9467bd', '#8c564b',
'#e377c2', '#7f7f7f', '#bcbd22',
'#17becf']
fig, ax = plt.subplots(nrows=1, figsize=(8, 4))
ax.tick_params(labelsize=15)
for i in labels_unique:
if not self.isCPD:
# FFtrEFM data
ax.plot(self.data_dist[labels == i] * 1e6,
self.data_avg_scatter[labels == i, 1] * 1e6,
c=colors[i], linestyle='None', marker='.')
# pix = pixel.Pixel(cluster_centers[i],self.parms_dict)
# pix.inst_freq = cluster_centers[i]
# pix.fit_freq_product()
# self.clust_tfp.append(pix.tfp)
pix_tfp = np.mean(self.data_avg_scatter[labels == i, 1])
ax.plot(np.mean(self.data_dist[labels == i] * 1e6),
pix_tfp * 1e6,
marker='o', markerfacecolor=colors[i], markersize=8,
markeredgecolor='k')
ax.set_xlabel('Distance to Nearest Boundary (um)', fontsize=16)
ax.set_ylabel('tfp (us)', fontsize=16)
elif self.isCPD:
# CPD data
ax.plot(self.data_dist[labels == labels_unique[i]] * 1e6,
self.data_avg_scatter[labels == labels_unique[i], 1] * 1e3,
c=colors[i], linestyle='None', marker='.')
xp_0 = int(
(self.parms_dict['light_on_time'][0] * 1e-3 / self.parms_dict['total_time']) * self.data_avg.shape[
1])
xp_1 = int(
(self.parms_dict['light_on_time'][1] * 1e-3 / self.parms_dict['total_time']) * self.data_avg.shape[
1])
pix = cluster_centers[i][xp_0:xp_1]
ax.plot(np.mean(self.data_dist[labels == labels_unique[i]] * 1e6),
np.mean(pix) * 1e3,
marker='o', markerfacecolor=colors[i], markersize=8,
markeredgecolor='k')
ax.set_xlabel('Distance to Nearest Boundary (um)', fontsize=16)
ax.set_ylabel('CPD (mV)', fontsize=16)
return fig, ax
def plot_centers(self):
fig, ax = plt.subplots(nrows=1, figsize=(6, 4))
for i in self.results.cluster_centers_:
ax.plot(np.linspace(0, self.parms_dict['total_time'], i.shape[0]), i)
return fig, ax
def elbow_plot(self, data=None, clusters=10):
""""
Simple k-means elbow plot, over 10 clusters. Note that this can take
a long time for big data sets.
Data defaults to self.data_scatter
Returns
-------
score : KMeans type
"""
data = self.data_scatter if data is None else data
Nc = range(1, clusters)
km = [sk.cluster.KMeans(n_clusters=i) for i in Nc]
score = [km[i].fit(data).score(data) for i in range(len(km))]
fig, ax = plt.subplots(nrows=1, figsize=(6, 4))
ax.plot(Nc, score, 's', markersize=8)
ax.set_xlabel('Clusters')
ax.set_ylabel('Score')
fig.tight_layout()
return score
def segment_maps(self, results=None):
"""
This creates 2D maps of the segments to overlay on an image
Returns to Class:
segments is in actual length
segments_idx is in index coordinates
segments_data is the full CPD trace (i.e. vs time)
segments_data_avg is for the average CPD value trace (not vs time)
To display, make sure to do [:,1], [:,0] given row, column ordering
Also, segments_idx is to display since pyplot uses the index on the axis
"""
if not results:
results = self.results
labels = results.labels_
cluster_centers = results.cluster_centers_
labels_unique = np.unique(labels)
self.segments = {}
self.segments_idx = {}
self.segments_data = {}
self.segments_data_avg = {}
for i in range(len(labels_unique)):
self.segments[i] = self.data_1D_pos[labels == labels_unique[i], :]
self.segments_idx[i] = self._idx_1D[labels == labels_unique[i], :]
self.segments_data[i] = self.data_1D_vals[labels == labels_unique[i], :]
self.segments_data_avg[i] = self.data_avg_1D_vals[labels == labels_unique[i]]
# the average value in that segment
self.data_time_avg = {}
for i in range(len(labels_unique)):
self.data_time_avg[i] = np.mean(self.segments_data[i], axis=0)
return
def plot_segment_maps(self, ax, newImage=False):
""" Plots the segments using a color map on given axis ax"""
colors = ['#1f77b4', '#ff7f0e', '#2ca02c',
'#d62728', '#9467bd', '#8c564b',
'#e377c2', '#7f7f7f', '#bcbd22',
'#17becf']
if newImage:
fig, ax = plt.subplots(nrows=1, figsize=(8, 6))
im0, _ = usid.plot_utils.plot_map(ax, self.data_on_avg, x_vec=self.FastScanSize,
y_vec=self.SlowScanSize, show_cbar=False,
cmap='inferno')
for i in self.segments_idx:
im1, = ax.plot(self.segments_idx[i][:, 1], self.segments_idx[i][:, 0],
color=colors[i], marker='s', linestyle='None', label=i)
ax.legend(fontsize=14, loc=[-0.18, 0.3])
if newImage:
return im0, im1
return im1
def heat_map(self, bins=50):
"""
Plots a heat map using CPD_avg_scatter data
"""
heatmap, _, _ = np.histogram2d(self.data_avg_scatter[:, 1], self.data_avg_scatter[:, 0], bins)
fig, ax = plt.subplots(nrows=1, figsize=(8, 4))
ax.set_xlabel('Distance to Nearest Boundary (um)')
if not self.isCPD:
ax.set_ylabel('tfp (us)')
xr = [np.min(self.data_avg_scatter[:, 0]) * 1e6, np.max(self.data_avg_scatter[:, 0]) * 1e6]
yr = [np.min(self.data_avg_scatter[:, 1]) * 1e6, np.max(self.data_avg_scatter[:, 1]) * 1e6]
aspect = ((xr[1] - xr[0]) / (yr[1] - yr[0]))
ax.imshow(heatmap, origin='lower', extent=[xr[0], xr[1], yr[0], yr[1]],
cmap='viridis', aspect=aspect)
fig.tight_layout()
else:
ax.set_ylabel('CPD (mV))')
xr = [np.min(self.data_avg_scatter[:, 0]) * 1e6, np.max(self.data_avg_scatter[:, 0]) * 1e6]
yr = [np.min(self.data_avg_scatter[:, 1]) * 1e3, np.max(self.data_avg_scatter[:, 1]) * 1e3]
aspect = ((xr[1] - xr[0]) / (yr[1] - yr[0]))
ax.imshow(heatmap, origin='lower', extent=[xr[0], xr[1], yr[0], yr[1]],
cmap='viridis', aspect=aspect)
fig.tight_layout()
return fig, ax
def animated_clusters(self, clusters=3, one_color=False):
plt.rcParams[
'animation.ffmpeg_path'] = r'C:\Users\Raj\Downloads\ffmpeg-20180124-1948b76-win64-static\bin\ffmpeg.exe'
fig, a = plt.subplots(nrows=1, figsize=(13, 6))
time = np.arange(0, self.pxl_time, 2 * self.dtCPD)
idx = np.arange(1, self.CPD.shape[1], 2) # in 2-slice increments
colors = ['#1f77b4', '#ff7f0e', '#2ca02c',
'#d62728', '#9467bd', '#8c564b',
'#e377c2', '#7f7f7f', '#bcbd22',
'#17becf']
if one_color:
colors = ['#1f77b4', '#1f77b4', '#1f77b4',
'#1f77b4', '#1f77b4', '#1f77b4',
'#1f77b4', '#1f77b4', '#1f77b4']
a.set_xlabel('Distance to Nearest Boundary (um)')
a.set_ylabel('CPD (V)')
labels = self.results.labels_
cluster_centers = self.results.cluster_centers_
labels_unique = np.unique(labels)
ims = []
for t in idx:
data = np.zeros([self.CPD_scatter.shape[0], 3])
data[:, 0] = self.CPD_scatter[:, 0]
data[:, 1:3] = self.CPD_scatter[:, t:t + 2]
_results = self.kmeans(data, clusters=clusters)
labels = _results.labels_
cluster_centers = _results.cluster_centers_
labels_unique = np.unique(labels)
km_ims = []
for i in range(len(labels_unique)):
tl0, = a.plot(data[labels == labels_unique[i], 0] * 1e6, data[labels == labels_unique[i], 1],
c=colors[i], linestyle='None', marker='.')
tl1, = a.plot(cluster_centers[i][0] * 1e6, cluster_centers[i][1],
marker='o', markerfacecolor=colors[i], markersize=8,
markeredgecolor='k')
ims.append([tl0, tl1])
km_ims = [i for j in km_ims for i in j] # flattens
ims.append(km_ims)
ani = animation.ArtistAnimation(fig, ims, interval=120, repeat_delay=10)
ani.save('kmeans_graph_.mp4')
return
def animated_image_clusters(self, clusters=5):
"""
Takes an image and animates the clusters over time on the overlay
As of 4/3/2018 this code is just a placeholder
"""
plt.rcParams[
'animation.ffmpeg_path'] = r'C:\Users\Raj\Downloads\ffmpeg-20180124-1948b76-win64-static\bin\ffmpeg.exe'
fig, ax = plt.subplots(nrows=1, figsize=(13, 6))
im0 = px.plot_utils.plot_map(ax, self.CPD_on_avg, x_size=self.FastScanSize,
y_size=self.SlowScanSize, show_cbar=False,
cmap='inferno')
time = np.arange(0, self.pxl_time, 2 * self.dtCPD)
idx = np.arange(1, self.CPD.shape[1], 2) # in 2-slice increments
ims = []
for t in idx:
data = np.zeros([self.CPD_scatter.shape[0], 3])
data[:, 0] = self.CPD_scatter[:, 0]
data[:, 1:3] = self.CPD_scatter[:, t:t + 2]
_results = self.kmeans(data, clusters=clusters)
self.segment_maps(results=_results)
im1 = self.plot_segment_maps(ax)
ims.append([im1])
ani = animation.ArtistAnimation(fig, ims, interval=120, repeat_delay=10)
ani.save('img_clusters_.mp4')
return
def plot_clust(h5_main, labels, mean_resp, x_pts, data_avg=None, tidx_off=0):
try:
_labels = np.array(labels.value).T[0]
except:
_labels = np.array(labels)
labels_unique = np.unique(_labels)
parms_dict = hdf_utils.get_params(h5_main)
clust_tfp = []
# color defaults are blue, orange, green, red, purple...
colors = ['#1f77b4', '#ff7f0e', '#2ca02c',
'#d62728', '#9467bd', '#8c564b',
'#e377c2', '#7f7f7f', '#bcbd22',
'#17becf']
fig, ax = plt.subplots(nrows=1, figsize=(12, 6))
ax.set_xlabel('Distance to Nearest Boundary (um)')
ax.set_ylabel('tfp (us)')
for i in labels_unique:
labels_tfp = []
if not data_avg.any():
for sig in h5_main[_labels == labels_unique[i], :]:
pix = pixel.Pixel(sig, parms_dict)
pix.inst_freq = sig
pix.fit_freq_product()
labels_tfp.append(pix.tfp)
labels_tfp = np.array(labels_tfp)
else:
labels_tfp = data_avg[_labels == labels_unique[i]]
ax.plot(x_pts[_labels == labels_unique[i]] * 1e6, labels_tfp * 1e6,
c=colors[i], linestyle='None', marker='.')
parms_dict['trigger'] += tidx_off / parms_dict['sampling_rate']
pix = pixel.Pixel(mean_resp[i], parms_dict)
pix.inst_freq = mean_resp[i]
pix.fit_freq_product()
clust_tfp.append(pix.tfp)
parms_dict['trigger'] -= tidx_off / parms_dict['sampling_rate']
ax.plot(np.mean(x_pts[_labels == labels_unique[i]] * 1e6), pix.tfp * 1e6,
marker='o', markerfacecolor=colors[i], markersize=8,
markeredgecolor='k')
print('tfp of clusters: ', clust_tfp)
return ax, fig
<file_sep>/ffta/pixel_utils/badpixels.py
# -*- coding: utf-8 -*-
"""
Created on Fri May 22 15:00:13 2015
@author: Raj
"""
"""
For finding the point scans and tfps of various points in an image.
In Igor/MFP code, the locations are actually as column, row when
here you want row, column (load the row .ibw, find column pixel)
"""
import numpy as np
from scipy import ndimage
import sys
from os.path import splitext
def load_csv(path):
# Get the path and check what the extension is.
ext = splitext(path)[1]
if ext.lower() == '.csv':
signal_array = np.genfromtxt(path, delimiter=',')
else:
print("Unrecognized file type!")
sys.exit(0)
return signal_array
def find_bad_pixels(signal_array, threshold=2, iterations=1):
""" Uses Median filter to find 'hot' pixels """
fixed_array = np.copy(signal_array)
for i in range(iterations):
filtered_array = ndimage.median_filter(fixed_array, size=3)
diff = np.abs(fixed_array - filtered_array)
limit = threshold * np.std(fixed_array)
bad_pixel_list = np.nonzero(diff > limit)
if i == 0:
bad_pixels_total = np.vstack((bad_pixel_list[0], bad_pixel_list[1]))
else:
bad_pixels_total = np.hstack((bad_pixels_total, bad_pixel_list))
fixed_array = remove_bad_pixels(fixed_array, filtered_array, bad_pixel_list)
return fixed_array, bad_pixels_total
def remove_bad_pixels(signal_array, filtered_array, bad_pixel_list):
""" Removes bad pixels from the array"""
fixed_array = np.copy(signal_array)
for y,x in zip(bad_pixel_list[0], bad_pixel_list[1]):
fixed_array[y, x] = filtered_array[y,x]
return fixed_array
def fix_array(path, threshold = 10, israte = False):
""" Wrapper function to find and remove 'hot' pixels.
This version uses a path to specify a file
"""
if type(path) is str:
signal_array = load_csv(path)
else:
signal_array = path
if not israte:
signal_array = 1/signal_array
filtered_array, bad_pixel_list = find_bad_pixels(signal_array, threshold)
fixed_array = remove_bad_pixels(signal_array, filtered_array, bad_pixel_list)
if not israte:
fixed_array = 1/fixed_array
return fixed_array, bad_pixel_list<file_sep>/ffta/load/get_utils.py
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 24 13:40:54 2018
@author: Raj
"""
import pycroscopy as px
import pyUSID as usid
from ffta.line import Line
from ffta.pixel import Pixel
import numpy as np
'''
Functions for extracting certain segments from an HDF FFtrEFM file
'''
def get_params(h5_path, key='', verbose=False, del_indices=True):
"""
Gets dict of parameters from the FF-file
Returns a specific key-value if requested
Parameters
----------
h5_path : str or h5py
Can pass either an h5_path to a file or a file already in use
key : str, optional
Returns specific key in the parameters dictionary
verbose : bool, optional
Prints all parameters to console
del_indices : bool, optional
Deletes relative links within the H5Py and any quantity/units
"""
if isinstance(h5_path, str):
h5_path = px.io.HDFwriter(h5_path).file
parameters = usid.hdf_utils.get_attributes(h5_path)
# if this dataset does not have complete FFtrEFM parameters
if 'trigger' not in parameters:
parameters = usid.hdf_utils.get_attributes(h5_path.parent)
# still not there? hard-select the main dataset
if 'trigger' not in parameters:
try:
h5_file = px.io.HDFwriter(h5_path).file
parameters = usid.hdf_utils.get_attributes(h5_file['FF_Group'])
except:
raise TypeError('No proper parameters file found.')
# STILL not there? Find the FF AVg
if 'trigger' not in parameters:
try:
h5_file = px.io.HDFwriter(h5_path).file
parameters = usid.hdf_utils.get_attributes(h5_file['FF_Group/FF_Avg'])
except:
raise TypeError('No proper parameters file found.')
if any(key):
return parameters[key]
if verbose:
print(parameters)
del_keys = ['Position_Indices', 'Position_Values', 'Spectroscopic_Indices',
'Spectroscopic_Values', 'quantity', 'units']
for key in del_keys:
if key in parameters:
del parameters[key]
return parameters
def change_params(h5_path, new_vals={}, verbose=False):
"""
Changes a parameter to a new value
This is equivalent to h5_main.parent.attrs[key] = new_value
Parameters
----------
h5_path : str or h5py
Can pass either an h5_path to a file or a file already in use
key : dict, optional
Returns specific keys in the parameters dictionary
value : str, int, float
The new value for the key. There is no error checking for this
verbose : bool
Prints all parameters to console
"""
parameters = usid.hdf_utils.get_attributes(h5_path)
if verbose:
print('Old parameters:')
for key in new_vals:
print(key, ':', parameters[key])
for key in new_vals:
h5_path.attrs[key] = new_vals[key]
if verbose:
print('\nNew parameters:')
for key in new_vals:
print(key, ':', parameters[key])
return parameters
def get_line(h5_path, line_num, params={},
array_form=False, avg=False, transpose=False):
"""
Gets a line of data.
If h5_path is a dataset it processes based on user-defined pnts_avg
If h5_path is a group/file/string_path then it can be a Line class or array
Parameters
----------
h5_path : str or h5py or Dataset
Can pass either an h5_path to a file or a file already in use or a specific Dataset
line_num : int
Returns specific line in the dataset
params: dict
If explicitly changing parameters (to test a feature), you can pass any subset and this will overwrite it
e.g. parameters = {'drive_freq': 10} will extract the Line, then change Line.drive_freq = 10
array_form : bool, optional
Returns the raw array contents rather than Line class
avg : bool, optional
Averages the pixels of the entire line
This will force output to be an array
transpose : bool, optional
For legacy FFtrEFM code, pixel is required in (n_points, n_signals) format
Returns
-------
signal_line : numpy 2D array, iff array_form == True
ndarray containing the line
line_inst : Line, iff array_form == False
Line class containing the signal_array object and parameters
"""
# If not a dataset, then find the associated Group
if 'Dataset' not in str(type(h5_path)):
parameters = get_params(h5_path)
h5_file = px.io.HDFwriter(h5_path).file
d = usid.hdf_utils.find_dataset(h5_file, 'FF_Raw')[0]
c = parameters['num_cols']
pnts = parameters['pnts_per_line']
else: # if a Dataset, extract parameters from the shape.
d = h5_path[()]
parameters = get_params(h5_path)
c = parameters['num_cols']
pnts = parameters['pnts_per_line']
signal_line = d[line_num * pnts:(line_num + 1) * pnts, :]
if avg == True:
signal_line = (signal_line.transpose() - signal_line.mean(axis=1)).transpose()
signal_line = signal_line.mean(axis=0)
if transpose == True:
signal_line = signal_line.transpose()
if array_form == True or avg == True:
return signal_line
if any(params):
for key, val in params.items():
parameters[key] = val
line_inst = Line(signal_line, parameters, c, pycroscopy=True)
return line_inst
def get_pixel(h5_path, rc, params={}, pixel_params={},
array_form=False, avg=False, transpose=False):
"""
Gets a pixel of data, returns all the averages within that pixel
Returns a specific key if requested
Supplying a direct link to a Dataset is MUCH faster than just the file
Note that you should supply the deflection data, not instantaneous_frequency
Parameters
----------
h5_path : str or h5py or Dataset
Can pass either an h5_path to a file or a file already in use or specific Dataset
Again, should pass the deflection data (Rebuilt_Data, or FF_Avg)
rc : list [r, c]
Pixel location in terms of ROW, COLUMN
params: dict
If explicitly changing parameters (to test a feature), you can pass any subset and this will overwrite it
e.g. parameters = {'drive_freq': 10} will extract the Pixel, then change Pixel.drive_freq = 10
pixel_params : dict, optional
Parameters 'fit', 'pycroscopy', 'method', 'fit_form'
See ffta.pixel for details. 'pycroscopy' is set to True in this function
array_form : bool, optional
Returns the raw array contents rather than Pixel class
avg : bool, optional
Averages the pixels of n_pnts_per_pixel and then creates Pixel of that
transpose : bool, optional
For legacy FFtrEFM code, pixel is required in (n_points, n_signals) format
Returns
-------
signal_pixel : 1D numpy array, iff array_form == True
Ndarray of the (n_points) in specific pixel
pixel_inst : Pixel, iff array_form == False
Line class containing the signal_array object and parameters
"""
# If not a dataset, then find the associated Group
if 'Dataset' not in str(type(h5_path)):
p = get_params(h5_path)
h5_file = px.io.HDFwriter(h5_path).file
d = usid.hdf_utils.find_dataset(h5_file, 'FF_Raw')[0]
c = p['num_cols']
pnts = int(p['pnts_per_pixel'])
parameters = usid.hdf_utils.get_attributes(d.parent)
else:
d = h5_path[()]
parameters = get_params(h5_path)
c = parameters['num_cols']
pnts = parameters['pnts_per_pixel']
signal_pixel = d[rc[0] * c + rc[1]:rc[0] * c + rc[1] + pnts, :]
if avg == True:
signal_pixel = signal_pixel.mean(axis=0)
if transpose == True: # this does nothing is avg==True
signal_pixel = signal_pixel.transpose()
if array_form == True:
return signal_pixel
if signal_pixel.shape[0] == 1:
signal_pixel = np.reshape(signal_pixel, [signal_pixel.shape[1]])
if any(params):
for key, val in params.items():
parameters[key] = val
pixel_params.update({'pycroscopy': True}) # must be True in this specific case
# pixel_inst = Pixel(signal_pixel, parameters, pycroscopy=True)
pixel_inst = Pixel(signal_pixel, parameters, **pixel_params)
return pixel_inst
<file_sep>/XOP/include/trEFMAnalysisPackage.h
/*
trEFMAnalysisPackage.h -- equates for trEFMAnalysisPackage XOP
*/
/* trEFMAnalysisPackage custom error codes */
#define OLD_IGOR 1 + FIRST_XOP_ERR
#define NON_EXISTENT_WAVE 2 + FIRST_XOP_ERR
#define NEEDS_3D_WAVE 3 + FIRST_XOP_ERR
/* Prototypes */
HOST_IMPORT int main(IORecHandle ioRecHandle);
<file_sep>/XOP/include/FPGAHeader.h
#ifndef A_H
#define A_H
#include "NiFpga.h"
#include "XOPStandardHeaders.h"
double** FPGAAcquireData(uint32_t, uint32_t, uint32_t);
int AnalyzePixel(double*, double*, double, double, double, double, int, int, double, double**, int, int);
double** ImportDataFromIgor(waveHndl, int*, int* );
#endif<file_sep>/ffta/simulation/broadband_drive.py
"""simulate.py: Contains Cantilever class."""
# pylint: disable=E1101,R0902,C0103
__author__ = "<NAME>"
__copyright__ = "Copyright 2020, Ginger Lab"
__email__ = "<EMAIL>"
__status__ = "Production"
import numpy as np
from scipy.integrate import odeint
from scipy.signal import chirp
from .cantilever import Cantilever
# Set constant 2 * pi.
PI2 = 2 * np.pi
class BroadbandPulse(Cantilever):
"""Damped Driven Harmonic Oscillator Simulator for AFM Cantilevers
Uses a broadband pulse to excite the cantilever
Parameters
----------
can_params : dict
Parameters for cantilever properties. See Cantilever
force_params : dict
Parameters for forces. Beyond Cantilever, the dictionary contains:
es_force = float (in N)
delta_freq = float (in Hz)
tau = float (in seconds)
sim_params : dict
Parameters for simulation. The dictionary contains:
trigger = float (in seconds)
total_time = float (in seconds)
sampling_rate = int (in Hz)
chirp_lo, chirp_hi : float
Control the lower and upper frequencies for defining the chirp applied
Attributes
----------
Z : ndarray
ODE integration of the DDHO response
Method
------
simulate(trigger_phase=180)
Simulates the cantilever motion with excitation happening
at the given phase.
See Also
--------
pixel: Pixel processing for FF-trEFM data.
Cantilever: base class
Examples
--------
>>> from ffta.simulation import mechanical_dirve, load
>>>
>>> params_file = '../examples/sim_params.cfg'
>>> params = load.simulation_configuration(params_file)
>>>
>>> c = mechanical_dirve.MechanicalDrive(*params)
>>> Z, infodict = c.simulate()
>>> c.analyze()
>>> c.analyze(roi=0.004) # can change the parameters as desired
"""
def __init__(self, can_params, force_params, sim_params, chirp_lo=10, chirp_hi=1e6):
parms = [can_params, force_params, sim_params]
super(BroadbandPulse, self).__init__(*parms)
t_Z = self.t_Z
self.chirp = chirp(t_Z, chirp_lo, t_Z[-1], chirp_hi)
self.delta_w = 0 # no trigger event
return
def force(self, t, t0=0, tau=0):
"""
Force on the cantilever at a given time.
Parameters
----------
t : float
Time in seconds.
Returns
-------
f : float
Force on the cantilever at a given time, in N/kg.
"""
p = int(t * self.sampling_rate)
n_points = int(self.total_time * self.sampling_rate)
_ch = self.chirp[p] if p < n_points else self.chirp[-1]
driving_force = self.f0 * _ch
return driving_force
<file_sep>/ffta/hdf_utils/hdf_utils.py
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 22 14:28:28 2018
@author: Raj
"""
import pycroscopy as px
import pyUSID as usid
import warnings
import numpy as np
from ffta.load import get_utils
from pycroscopy.io.write_utils import build_ind_val_dsets, build_ind_val_matrices, Dimension
"""
Common HDF interfacing functions
_which_h5_group : Returns a group corresponding to main FFtrEFM file
get_params : Returns the common parameters list from config file
change_params : Changes specific parameters (replicates normal command line function)
get_line : Gets a specific line, returns as either array or Line class
get_pixel : Gets a specific pixel, returns as either array or Pixel class
h5_list : Gets list of files corresponding to a key, for creating unique folders/Datasets
hdf_commands : Creates workspace-compatible commands for common HDF variable standards
add_standard_sets : Adds the standard data sets needed for much processing
"""
def _which_h5_group(h5_path):
"""
Used internally in get_ functions to indentify type of H5_path parameter.
H5_path can be passed as string (to h5 location), or as an existing
variable in the workspace.
This tries
If this is a Dataset, it will try and return the parent as that is
by default where all relevant attributs are
Parameters
----------
h5_path : str, HDF group, HDF file
Returns
-------
h5Py Group
h5Py group corresponding to "FF_Group" typically at hdf.file['/FF_Group']
"""
ftype = str(type(h5_path))
# h5_path is a file path
if 'str' in ftype:
hdf = px.io.HDFwriter(h5_path)
p = usid.hdf_utils.find_dataset(hdf.file, 'FF_Raw')[0]
return p.parent
# h5_path is an HDF Group
if 'Group' in ftype:
p = h5_path
# h5_path is an HDF File
elif 'File' in ftype:
p = usid.hdf_utils.find_dataset(h5_path, 'FF_Raw')[0]
p = p.parent
elif 'Dataset' in ftype:
p = h5_path.parent
return p
def h5_list(h5_file, key):
'''
Returns list of names matching a key in the h5 group passed.
This is useful for creating unique keys in datasets
This ONLY works on the specific group and is not for searching the HDF5 file folder
e.g. this checks for -processed folder, increments the suffix
>> names = hdf_utils.h5_list(hdf.file['/FF_Group'], 'processed')
>> try:
>> suffix = names[-1][-4:]
>> suffix = str(int(suffix)+1).zfill(4)
Parameters
----------
h5_file : h5py File
hdf.file['/Measurement_000/Channel_000'] or similar
key : str
string to search for, e.g. 'processing'
'''
names = []
for i in h5_file:
if key in i:
names.append(i)
return names
def add_standard_sets(h5_path, group, fast_x=32e-6, slow_y=8e-6,
parm_dict={}, ds='FF_Raw', verbose=False):
"""
Adds Position_Indices and Position_Value datasets to a folder within the h5_file
Uses the values of fast_x and fast_y to determine the values
Parameters
----------
h5_path : h5 File or str
Points to a path to process
group : str or H5PY group
Location to process data to, either as str or H5PY
parms_dict : dict, optional
Parameters to be passed. By default this should be at the command line for FFtrEFM data
ds : str, optional
Dataset name to search for within this group and set as h5_main
verbose : bool, optional
Whether to write to the command line
"""
hdf = px.io.HDFwriter(h5_path)
if not any(parm_dict):
parm_dict = get_utils.get_params(h5_path)
if 'FastScanSize' in parm_dict:
fast_x = parm_dict['FastScanSize']
if 'SlowScanSize' in parm_dict:
slow_y = parm_dict['SlowScanSize']
try:
num_rows = parm_dict['num_rows']
num_cols = parm_dict['num_cols']
pnts_per_avg = parm_dict['pnts_per_avg']
dt = 1 / parm_dict['sampling_rate']
except: # some defaults
warnings.warn('Improper parameters specified.')
num_rows = 64
num_cols = 128
pnts_per_avg = 1
dt = 1
try:
grp = px.io.VirtualGroup(group)
except:
grp = px.io.VirtualGroup(group.name)
pos_desc = [Dimension('X', 'm', np.linspace(0, parm_dict['FastScanSize'], num_cols)),
Dimension('Y', 'm', np.linspace(0, parm_dict['SlowScanSize'], num_rows))]
ds_pos_ind, ds_pos_val = build_ind_val_dsets(pos_desc, is_spectral=False, verbose=verbose)
spec_desc = [Dimension('Time', 's', np.linspace(0, pnts_per_avg, dt))]
ds_spec_inds, ds_spec_vals = build_ind_val_matrices(spec_desc, is_spectral=True, verbose=verbose)
aux_ds_names = ['Position_Indices', 'Position_Values',
'Spectroscopic_Indices', 'Spectroscopic_Values']
grp.add_children([ds_pos_ind, ds_pos_val, ds_spec_inds, ds_spec_vals])
h5_refs = hdf.write(grp, print_log=verbose)
h5_main = hdf.file[grp.name]
if any(ds):
h5_main = usid.hdf_utils.find_dataset(hdf.file[grp.name], ds)[0]
try:
usid.hdf_utils.link_h5_objects_as_attrs(h5_main, usid.hdf_utils.get_h5_obj_refs(aux_ds_names, h5_refs))
except:
usid.hdf_utils.link_h5_objects_as_attrs(h5_main, usid.hdf_utils.get_h5_obj_refs(aux_ds_names, h5_refs))
hdf.flush()
return h5_main
def add_single_dataset(h5_path, group, dset, dset_name, verbose=False):
'''
Adds a single dataset (dset) to group h5_grp in h5_main
Parameters
----------
h5_path : h5 File or str
Points to a path to process
group : str or H5PY group
Location to process data to, either as str or H5PY
dset : ndarray
Dataset name to search for within this group and set as h5_main
dset_name : str
Dataset name for the h5 folder
'''
hdf = px.io.HDFwriter(h5_path)
h5_file = hdf.file
if isinstance(group, str):
grp_tr = px.io.VirtualGroup(group)
grp_name = group
else:
grp_tr = px.io.VirtualGroup(group.name)
grp_name = group.name
grp_ds = px.io.VirtualDataset(dset_name, dset, parent=h5_file[grp_name])
grp_tr.add_children([grp_ds])
if verbose:
hdf.write(grp_tr, print_log=True)
usid.hdf_utils.print_tree(h5_file, rel_paths=True)
else:
hdf.write(grp_tr, print_log=False)
hdf.flush()
return hdf.file
<file_sep>/ffta/line.py
"""line.py: Contains line class."""
# pylint: disable=E1101,R0902,C0103
__author__ = "<NAME>"
__copyright__ = "Copyright 2014, Ginger Lab"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
__status__ = "Development"
import numpy as np
from ffta import pixel
class Line:
"""
Signal Processing to Extract Time-to-First-Peak.
This class is a container for pixels in a line. Since the AFM scans are in
lines, tha data taken is grouped in lines. This class takes the line data
and passes it along to pixels.
Parameters
----------
signal_array : (n_signals, n_points) array_like
2D real-valued signal array, corresponds to a line
params : dict
Includes parameters for processing. The list of parameters is:
trigger = float (in seconds)
total_time = float (in seconds)
sampling_rate = int (in Hz)
drive_freq = float (in Hz)
roi = float (in seconds)
window = string (see documentation of scipy.signal.get_window)
bandpass_filter = int (0: no filtering, 1: FIR filter, 2: IIR filter)
filter_bandwidth = float (in Hz)
n_taps = integer (default: 999)
wavelet_analysis = bool (0: Hilbert method, 1: Wavelet Method)
wavelet_parameter = int (default: 5)
recombination = bool (0: FF-trEFM, 1: Recombination)
n_pixels : int
Number of pixels in a line.
pycroscopy : bool, optional
Pycroscopy requires different orientation, so this corrects for this effect.
Attributes
----------
n_points : int
Number of points in a signal.
n_signals : int
Number of signals in a line.
inst_freq : (n_points, n_pixels) array_like
Instantenous frequencies of the line.
tfp : (n_pixels,) array_like
Time from trigger to first-peak, in seconds.
shift : (n_pixels,) array_like
Frequency shift from trigger to first-peak, in Hz.
See Also
--------
pixel: Pixel processing for FF-trEFM data.
simulate: Simulation for synthetic FF-trEFM data.
scipy.signal.get_window: Windows for signal processing.
Examples
--------
>>> from ffta import line, utils
>>>
>>> signal_file = '../data/SW_0000.ibw'
>>> params_file = '../data/parameters.cfg'
>>>
>>> signal_array = utils.load.signal(signal_file)
>>> n_pixels, params = utils.load.configuration(params_file)
>>>
>>> l = line.Line(signal_array, params, n_pixels)
>>> tfp, shift, inst_freq = l.analyze()
"""
def __init__(self, signal_array, params, n_pixels, pycroscopy=False):
# Pass inputs to the object.
self.signal_array = signal_array
if pycroscopy:
self.signal_array = signal_array.T
self.n_pixels = int(n_pixels)
self.params = params
# Initialize tFP and shift arrays.
self.tfp = np.empty(self.n_pixels)
self.shift = np.empty(self.n_pixels)
self.inst_freq = np.empty((self.signal_array.shape[0], self.n_pixels))
self.avgs_per_pixel = int(self.signal_array.shape[1]/self.n_pixels)
self.n_signals = self.signal_array.shape[0]
return
def analyze(self):
"""
Analyzes the line with the given method.
Returns
-------
tfp : (n_pixels,) array_like
Time from trigger to first-peak, in seconds.
shift : (n_pixels,) array_like
Frequency shift from trigger to first-peak, in Hz.
inst_freq : (n_points, n_pixels) array_like
Instantaneous frequencies of the line.
"""
# Split the signal array into pixels.
pixel_signals = np.split(self.signal_array, self.n_pixels, axis=1)
# Iterate over pixels and return tFP and shift arrays.
for i, pixel_signal in enumerate(pixel_signals):
p = pixel.Pixel(pixel_signal, self.params)
(self.tfp[i], self.shift[i], self.inst_freq[:, i]) = p.analyze()
return (self.tfp, self.shift, self.inst_freq)
def pixel_wise_avg(self):
"""
Averages the line per pixel and saves the result as signal_avg_array
This functionality is primarily used in Pycroscopy-loading functions
Returns
-------
signal_avg_array : (n_points, n_pixels) numpy array
Returns signal_averaged time-domain signal at each pixel
"""
self.signal_avg_array = np.empty((self.signal_array.shape[0], self.n_pixels))
for i in range(self.n_pixels):
avg = self.signal_array[:, i*self.avgs_per_pixel:(i+1)*self.avgs_per_pixel]
self.signal_avg_array[:, i] = avg.mean(axis=1)
return self.signal_avg_array
def clear_filter_flags(self):
"""Removes flags from parameters for setting filters"""
#self.params['window'] = 0
self.params['bandpass_filter'] = 0
return<file_sep>/docs/source/ffta.rst
ffta package
============
Subpackages
-----------
.. toctree::
:maxdepth: 4
ffta.acquisition
ffta.analysis
ffta.gkpfm
ffta.hdf_utils
ffta.load
ffta.pixel_utils
ffta.simulation
Submodules
----------
ffta.acquisition module
-----------------------
.. automodule:: ffta.acquisition
:members:
:undoc-members:
:show-inheritance:
:noindex:
ffta.analyze module
-------------------
.. automodule:: ffta.analyze
:members:
:undoc-members:
:show-inheritance:
ffta.analyze\_pixel module
--------------------------
.. automodule:: ffta.analyze_pixel
:members:
:undoc-members:
:show-inheritance:
ffta.line module
----------------
.. automodule:: ffta.line
:members:
:undoc-members:
:show-inheritance:
ffta.pixel module
-----------------
.. automodule:: ffta.pixel
:members:
:undoc-members:
:show-inheritance:
:noindex:
Module contents
---------------
.. automodule:: ffta
:members:
:undoc-members:
:show-inheritance:
<file_sep>/ffta/load/load_hdf.py
"""loadHDF5.py: Includes routines for loading into HDF5 files."""
from __future__ import division, print_function, absolute_import, unicode_literals
__author__ = "<NAME>"
__copyright__ = "Copyright 2018, Ginger Lab"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
__status__ = "Development"
import numpy as np
import os
import h5py
import pycroscopy as px
import pyUSID as usid
from pycroscopy.io.write_utils import build_ind_val_dsets, Dimension
from ffta.pixel_utils import load
from ffta.load import gl_ibw
from ffta.hdf_utils import hdf_utils
from ffta.load import get_utils
from ffta import line
import warnings
"""
Common HDF Loading functions
load_wrapper: Loads a specific ibw and FFtrEFM folder into a new H5 file
load_folder : Takes a folder of IBW files and creates an H5 file
load_FF : Creates FF_Raw which is the raw (r*c*averages, pnts_per_signal) Dataset
load_pixel_averaged_FF : Creates FF_Avg where each pixel's signal is averaged together (r*c, pnts_per_signal) Dataset
load_pixel_averaged_from_raw : Creates FF_Avg where each pixel's signal is averaged together using the Raw data file
createHDF5_file : Creates a single H5 file for one IBW file.
Example usage:
If you want to load an IBW (image) + associated data
>>from ffta.hdf_utils import load_hdf
>>h5_path, parameters, h5_avg = load_hdf.load_wrapper(ibw_file_path='E:/Data/FF_image_file.ibw',
ff_file_path=r'E:\Data\FF_Folder')
If you have data and just want to load (no associated image file)
>> file_name = 'name_you_want.h5'
>> h5_path, data_files, parm_dict = loadHDF5_folder(folder_path=ff_file_path, verbose=True, file_name=file_name)
>> h5_avg = load_pixel_averaged_FF(data_files, parm_dict, h5_path, mirror=True)
"""
def load_wrapper(ibw_file_path='', ff_file_path='', ftype='FF', verbose=False,
subfolder='/', loadverbose=True, average=True, mirror=True):
"""
Wrapper function for processing a .ibw file and associated FF data
Average just uses the pixel-wise averaged data
Raw_Avg processes the raw deflection data, then averages those together
Loads .ibw single file an HDF5 format. Then appends the FF data to that HDF5
Parameters
----------
ibw_file_path : string, optional
Path to signal file IBW with images to add.
ff_file_path : string, optional
Path to folder containing the FF-trEFM files and config file. If empty prompts dialogue
ftype : str, optional
Delineates Ginger Lab imaging file type to be imported (not case-sensitive)
'FF' : FF-trEFM
'SKPM' : FM-SKPM
'ringdown' : Ringdown
'trEFM' : normal trEFM
verbose : Boolean (Optional)
Whether or not to show print statements for debugging. Passed to Pycroscopy functions
loadverbose : Boolean (optional)
Whether to print any simple "loading Line X" statements for feedback
subfolder : str, optional
Specifies folder under root (/) to save data in. Default is standard pycroscopy format
average : bool, optional
Whether to automatically call the load_pixel_averaged_FF function to average data at each pixel
mirror : bool, optional
Whether to reverse the data on each line read (since data are usually saved during a RETRACE scan)
Returns
-------
h5_path: str
The filename path to the H5 file created
parm_dict: dict
Dictionary of relevant scan parameters
"""
if not any(ibw_file_path):
ibw_file_path = usid.io_utils.file_dialog(caption='Select IBW Image ',
file_filter='IBW Files (*.ibw)')
if not any(ff_file_path):
ff_file_path = usid.io_utils.file_dialog(caption='Select FF config in folder',
file_filter='Config File (*.cfg)')
ff_file_path = '/'.join(ff_file_path.split('/')[:-1])
# Igor image file translation into an H5 file
tran = gl_ibw.GLIBWTranslator()
h5_path = tran.translate(ibw_file_path, ftype=ftype,
verbose=verbose, subfolder=subfolder)
# Set up FF data
h5_path, data_files, parm_dict = load_folder(folder_path=ff_file_path, verbose=verbose,
file_name=h5_path)
# Processes the data
h5_ff = load_FF(data_files, parm_dict, h5_path, average=average,
verbose=verbose, loadverbose=loadverbose, mirror=mirror)
if loadverbose:
print('*** Copy-Paste below code ***')
print('import h5py')
print('h5_file = h5py.File("',h5_path,'")')
return h5_path, parm_dict, h5_ff
def load_folder(folder_path='', xy_scansize=[0, 0], file_name='FF_H5',
textload=False, verbose=False):
"""
Sets up loading the HDF5 files. Parses the data file list and creates the .H5 file path
Parameters
----------
folder_path : string
Path to folder you want to process
xy_sscansize : 2-float array
Width by Height in meters (e.g. [8e-6, 4e-6]), if not in parameters file
file_name : str
Desired file name, otherwise is auto-generated
textload : bool, optional
If you have a folder of .txt instead of .ibw (older files, some synthetic data)
verbose : bool, optional
Whether to output the datasets being processed
Returns
-------
h5_path: str
The filename path to the H5 file created
data_files: list
List of \*.ibw files in the folder to be processed
parm_dict: dict
Dictionary of relevant scan parameters
"""
if any(xy_scansize) and len(xy_scansize) != 2:
raise Exception('XY Scan Size must be either empty (in .cfg) or length-2')
if not any(folder_path):
folder_path = px.io_utils.file_dialog(caption='Select Config File in FF-trEFM folder',
file_filter='Config Files (*.cfg)')
folder_path = '/'.join(folder_path.split('/')[:-1])
print(folder_path, 'folder path')
filelist = os.listdir(folder_path)
if textload == False:
data_files = [os.path.join(folder_path, name)
for name in filelist if name[-3:] == 'ibw']
else:
data_files = [os.path.join(folder_path, name)
for name in filelist if name[-3:] == 'txt']
if not data_files:
raise OSError('No data files found! Are these text files?')
config_file = [os.path.join(folder_path, name)
for name in filelist if name[-3:] == 'cfg'][0]
n_pixels, parm_dict = load.configuration(config_file)
parm_dict['num_rows'] = len(data_files)
parm_dict['num_cols'] = n_pixels
# Add dimensions if not in the config file
if 'FastScanSize' not in parm_dict.keys():
if not any(xy_scansize):
raise Exception('Need XY Scan Size! Save "Width" and "Height" in Config or pass xy_scansize')
[width, height] = xy_scansize
if width > 1e-3: # if entering as microns
width = width * 1e-6
height = height * 1e-6
parm_dict['FastScanSize'] = width
parm_dict['SlowScanSize'] = height
# sometimes use width/height in config files
if 'width' in parm_dict.keys():
parm_dict['FastScanSize'] = width
parm_dict['SlowScanSize'] = height
# Check ratio is correct
ratio = np.round(parm_dict['FastScanSize'] * 1e6, 1) / np.round(parm_dict['SlowScanSize'] * 1e6, 1)
if n_pixels / len(data_files) != ratio:
print(ratio)
print(parm_dict['FastScanSize'], parm_dict['SlowScanSize'], n_pixels / len(data_files), len(data_files))
raise Exception('X-Y Dimensions do not match filelist. Add manually to config file. Check n-pixels.')
# add associated dimension info
#
# e.g. if a 16000 point signal with 2000 averages and 10 pixels
# (10MHz sampling of a 1.6 ms long signal=16000, 200 averages per pixel)
# parm_dict['pnts_per_pixel'] = 200 (# signals at each pixel)
# ['pnts_per_avg'] = 16000 (# pnts per signal, called an "average")
# ['pnts_per_line'] = 2000 (# signals in each line)
if 'pnts_per_pixel' not in parm_dict.keys():
print('Loading first signal')
# Uses first data set to determine parameters
line_file = load.signal(data_files[0])
parm_dict['pnts_per_avg'] = int(line_file.shape[0])
try:
# for 1 average per pixel, this will fail
parm_dict['pnts_per_pixel'] = int(line_file.shape[1] / parm_dict['num_cols'])
parm_dict['pnts_per_line'] = int(line_file.shape[1])
except:
parm_dict['pnts_per_pixel'] = 1
parm_dict['pnts_per_line'] = 1
folder_path = folder_path.replace('/', '\\')
if os.path.exists(file_name) == False:
h5_path = os.path.join(folder_path, file_name) + '.h5'
else:
h5_path = file_name
return h5_path, data_files, parm_dict
def load_FF(data_files, parm_dict, h5_path, verbose=False, loadverbose=True,
average=True, mirror=False):
"""
Generates the HDF5 file given path to data_files and parameters dictionary
Creates a Datagroup FFtrEFM_Group with a single dataset in chunks
Parameters
----------
data_files : list
List of the \*.ibw files to be invidually scanned. This is generated
by load_folder above
parm_dict : dict
Scan parameters to be saved as attributes. This is generated
by load_folder above, or you can pass this explicitly.
h5_path : string
Path to H5 file on disk
verbose : bool, optional
Display outputs of each function or not
loadverbose : Boolean (optional)
Whether to print any simple "loading Line X" statements for feedback
average: bool, optional
Whether to average each pixel before saving to H5. This saves both time and space
mirror : bool, optional
Mirrors the data when saving. This parameter is to match the FFtrEFM data
with the associate topography as FFtrEFM is acquired during a retrace while
topo is saved during a forward trace
Returns
-------
h5_path: str
The filename path to the H5 file created
"""
# Prepare data for writing to HDF
num_rows = parm_dict['num_rows']
num_cols = parm_dict['num_cols']
pnts_per_avg = parm_dict['pnts_per_avg']
name = 'FF_Raw'
if average:
parm_dict['pnts_per_pixel'] = 1
parm_dict['pnts_per_line'] = num_cols
name = 'FF_Avg'
pnts_per_pixel = parm_dict['pnts_per_pixel']
pnts_per_line = parm_dict['pnts_per_line']
dt = 1 / parm_dict['sampling_rate']
def_vec = np.arange(0, parm_dict['total_time'], dt)
if def_vec.shape[0] != parm_dict['pnts_per_avg']:
def_vec = def_vec[:-1]
# warnings.warn('Time-per-point calculation error')
# To do: Fix the labels/atrtibutes on the relevant data sets
hdf = px.io.HDFwriter(h5_path)
try:
ff_group = hdf.file.create_group('FF_Group')
except:
ff_group = usid.hdf_utils.create_indexed_group(hdf.file['/'], 'FF_Group')
# Set up the position vectors for the data
pos_desc = [Dimension('X', 'm', np.linspace(0, parm_dict['FastScanSize'], num_cols * pnts_per_pixel)),
Dimension('Y', 'm', np.linspace(0, parm_dict['SlowScanSize'], num_rows))]
ds_pos_ind, ds_pos_val = build_ind_val_dsets(pos_desc, is_spectral=False, verbose=verbose)
spec_desc = [Dimension('Time', 's', np.linspace(0, parm_dict['total_time'], pnts_per_avg))]
ds_spec_inds, ds_spec_vals = build_ind_val_dsets(spec_desc, is_spectral=True)
for p in parm_dict:
ff_group.attrs[p] = parm_dict[p]
ff_group.attrs['pnts_per_line'] = num_cols # to change number of pnts in a line
# ff_group.attrs['pnts_per_pixel'] = 1 # to change number of pnts in a pixel
h5_ff = usid.hdf_utils.write_main_dataset(ff_group, # parent HDF5 group
(num_rows * num_cols * pnts_per_pixel, pnts_per_avg),
# shape of Main dataset
name, # Name of main dataset
'Deflection', # Physical quantity contained in Main dataset
'V', # Units for the physical quantity
pos_desc, # Position dimensions
spec_desc, # Spectroscopic dimensions
dtype=np.float32, # data type / precision
compression='gzip',
main_dset_attrs=parm_dict)
pnts_per_line = parm_dict['pnts_per_line']
# Cycles through the remaining files. This takes a while (~few minutes)
for k, num in zip(data_files, np.arange(0, len(data_files))):
if loadverbose:
fname = k.replace('/', '\\')
print('####', fname.split('\\')[-1], '####')
fname = str(num).rjust(4, '0')
line_file = load.signal(k)
if average:
_ll = line.Line(line_file, parm_dict, n_pixels=num_cols, pycroscopy=False)
_ll = _ll.pixel_wise_avg().T
else:
_ll = line_file.transpose()
f = hdf.file[h5_ff.name]
if mirror:
f[pnts_per_line * num:pnts_per_line * (num + 1), :] = np.flipud(_ll[:, :])
else:
f[pnts_per_line * num:pnts_per_line * (num + 1), :] = _ll[:, :]
if verbose == True:
usid.hdf_utils.print_tree(hdf.file, rel_paths=True)
hdf.flush()
return h5_ff
def load_pixel_averaged_from_raw(h5_file, verbose=True, loadverbose=True):
"""
Creates a new group FF_Avg where the FF_raw file is averaged together.
This is more useful as pixel-wise averages are more relevant in FF-processing
This Dataset is (n_pixels*n_rows, n_pnts_per_avg)
Parameters
----------
h5_file : h5py File
H5 File to be examined. File typically set as h5_file = hdf.file
hdf = px.ioHDF5(h5_path), h5_path = path to disk
verbose : bool, optional
Display outputs of each function or not
loadverbose : Boolean (optional)
Whether to print any simple "loading Line X" statements for feedback
Returns
-------
h5_avg : Dataset
The new averaged Dataset
"""
hdf = px.io.HDFwriter(h5_file)
h5_main = usid.hdf_utils.find_dataset(hdf.file, 'FF_Raw')[0]
try:
ff_avg_group = h5_main.parent.create_group('FF_Avg')
except:
ff_avg_group = usid.hdf_utils.create_indexed_group(h5_main.parent, 'FF_Avg')
parm_dict = usid.hdf_utils.get_attributes(h5_main.parent)
num_rows = parm_dict['num_rows']
num_cols = parm_dict['num_cols']
pnts_per_avg = parm_dict['pnts_per_avg']
pnts_per_line = parm_dict['pnts_per_line']
pnts_per_pixel = parm_dict['pnts_per_pixel']
parm_dict['pnts_per_pixel'] = 1 # only 1 average per pixel now
parm_dict['pnts_per_line'] = num_cols # equivalent now with averaged data
n_pix = int(pnts_per_line / pnts_per_pixel)
dt = 1 / parm_dict['sampling_rate']
# Set up the position vectors for the data
pos_desc = [Dimension('X', 'm', np.linspace(0, parm_dict['FastScanSize'], num_cols)),
Dimension('Y', 'm', np.linspace(0, parm_dict['SlowScanSize'], num_rows))]
ds_pos_ind, ds_pos_val = build_ind_val_dsets(pos_desc, is_spectral=False)
spec_desc = [Dimension('Time', 's', np.linspace(0, parm_dict['total_time'], pnts_per_avg))]
ds_spec_inds, ds_spec_vals = build_ind_val_dsets(spec_desc, is_spectral=True)
for p in parm_dict:
ff_avg_group.attrs[p] = parm_dict[p]
ff_avg_group.attrs['pnts_per_line'] = num_cols # to change number of pnts in a line
ff_avg_group.attrs['pnts_per_pixel'] = 1 # to change number of pnts in a pixel
h5_avg = usid.hdf_utils.write_main_dataset(ff_avg_group, # parent HDF5 group
(num_rows * num_cols, pnts_per_avg), # shape of Main dataset
'FF_Avg', # Name of main dataset
'Deflection', # Physical quantity contained in Main dataset
'V', # Units for the physical quantity
pos_desc, # Position dimensions
spec_desc, # Spectroscopic dimensions
dtype=np.float32, # data type / precision
compression='gzip',
main_dset_attrs=parm_dict)
# Uses get_line to extract line. Averages and returns to the Dataset FF_Avg
# We can operate on the dataset array directly, get_line is used for future_proofing if
# we want to add additional operation (such as create an Image class)
for i in range(num_rows):
if loadverbose == True:
print('#### Row:', i, '####')
_ll = get_utils.get_line(h5_main, pnts=pnts_per_line, line_num=i, array_form=False, avg=False)
_ll = _ll.pixel_wise_avg()
h5_avg[i * num_cols:(i + 1) * num_cols, :] = _ll[:, :]
if verbose == True:
usid.hdf_utils.print_tree(hdf.file, rel_paths=True)
h5_avg = usid.hdf_utils.find_dataset(hdf.file, 'FF_Avg')[0]
print('H5_avg of size:', h5_avg.shape)
hdf.flush()
return h5_avg
def load_pixel_averaged_FF(data_files, parm_dict, h5_path,
verbose=False, loadverbose=True, mirror=False):
"""
Creates a new group FF_Avg where the raw FF files are averaged together
This function does not process the Raw data and is more useful when the resulting
Raw data matrix is very large (causing memory errors)
This is more useful as pixel-wise averages are more relevant in FF-processing
This Dataset is (n_pixels*n_rows, n_pnts_per_avg)
Parameters
----------
h5_file : h5py File
H5 File to be examined. File typically set as h5_file = hdf.file
hdf = px.ioHDF5(h5_path), h5_path = path to disk
verbose : bool, optional
Display outputs of each function or not
loadverbose : Boolean (optional)
Whether to print any simple "loading Line X" statements for feedback
Returns
-------
h5_avg : Dataset
The new averaged Dataset
"""
hdf = px.io.HDFwriter(h5_path)
try:
ff_avg_group = hdf.file.create_group('FF_Group')
except:
ff_avg_group = usid.hdf_utils.create_indexed_group(hdf.file['/'], 'FF_Group')
try:
ff_avg_group = hdf.file[ff_avg_group.name].create_group('FF_Avg')
except:
ff_avg_group = usid.hdf_utils.create_indexed_group(ff_avg_group, 'FF_Avg')
num_rows = parm_dict['num_rows']
num_cols = parm_dict['num_cols']
pnts_per_avg = parm_dict['pnts_per_avg']
pnts_per_line = parm_dict['pnts_per_line']
pnts_per_pixel = parm_dict['pnts_per_pixel']
parm_dict['pnts_per_pixel'] = 1 # only 1 average per pixel now
parm_dict['pnts_per_line'] = num_cols # equivalent now with averaged data
n_pix = int(pnts_per_line / pnts_per_pixel)
dt = 1 / parm_dict['sampling_rate']
# Set up the position vectors for the data
pos_desc = [Dimension('X', 'm', np.linspace(0, parm_dict['FastScanSize'], num_cols)),
Dimension('Y', 'm', np.linspace(0, parm_dict['SlowScanSize'], num_rows))]
ds_pos_ind, ds_pos_val = build_ind_val_dsets(pos_desc, is_spectral=False)
spec_desc = [Dimension('Time', 's', np.linspace(0, parm_dict['total_time'], pnts_per_avg))]
ds_spec_inds, ds_spec_vals = build_ind_val_dsets(spec_desc, is_spectral=True)
for p in parm_dict:
ff_avg_group.attrs[p] = parm_dict[p]
ff_avg_group.attrs['pnts_per_line'] = num_cols # to change number of pnts in a line
ff_avg_group.attrs['pnts_per_pixel'] = 1 # to change number of pnts in a pixel
h5_avg = usid.hdf_utils.write_main_dataset(ff_avg_group, # parent HDF5 group
(num_rows * num_cols, pnts_per_avg), # shape of Main dataset
'FF_Avg', # Name of main dataset
'Deflection', # Physical quantity contained in Main dataset
'V', # Units for the physical quantity
pos_desc, # Position dimensions
spec_desc, # Spectroscopic dimensions
dtype=np.float32, # data type / precision
compression='gzip',
main_dset_attrs=parm_dict)
# Generates a line from each data file, averages, then saves the data
for k, n in zip(data_files, np.arange(0, len(data_files))):
if loadverbose:
fname = k.replace('/', '\\')
print('####', fname.split('\\')[-1], '####')
fname = str(n).rjust(4, '0')
line_file = load.signal(k)
_ll = line.Line(line_file, parm_dict, n_pixels=n_pix, pycroscopy=False)
_ll = _ll.pixel_wise_avg().T
if mirror:
h5_avg[n * num_cols:(n + 1) * num_cols, :] = np.flipud(_ll[:, :])
else:
h5_avg[n * num_cols:(n + 1) * num_cols, :] = _ll[:, :]
if verbose == True:
usid.hdf_utils.print_tree(hdf.file, rel_paths=True)
h5_avg = usid.hdf_utils.find_dataset(hdf.file, 'FF_Avg')[0]
print('H5_avg of size:', h5_avg.shape)
hdf.flush()
return h5_avg
def createHDF5_file(signal, parm_dict, h5_path='', ds_name='FF_Raw'):
"""
Generates the HDF5 file given path to a specific file and a parameters dictionary
Parameters
----------
h5_path : string
Path to desired h5 file.
signal : str, ndarray
Path to the data file to be converted or a workspace array
parm_dict : dict
Scan parameters
Returns
-------
h5_path: str
The filename path to the H5 file create
"""
sg = signal
if 'str' in str(type(signal)):
sg = load.signal(signal)
if not any(h5_path): # if not passed, auto-generate name
fname = signal.replace('/', '\\')
h5_path = fname[:-4] + '.h5'
else:
fname = h5_path
hdf = px.ioHDF5(h5_path)
usid.hdf_utils.print_tree(hdf.file)
ff_group = px.MicroDataGroup('FF_Group', parent='/')
root_group = px.MicroDataGroup('/')
# fname = fname.split('\\')[-1][:-4]
sg = px.MicroDataset(ds_name, data=sg, dtype=np.float32, parent=ff_group)
if 'pnts_per_pixel' not in parm_dict.keys():
parm_dict['pnts_per_avg'] = signal.shape[1]
parm_dict['pnts_per_pixel'] = 1
parm_dict['pnts_per_line'] = parm_dict['num_cols']
ff_group.addChildren([sg])
ff_group.attrs = parm_dict
# Get reference for writing the data
h5_refs = hdf.writeData(ff_group, print_log=True)
hdf.flush()
<file_sep>/docs/source/ffta.acquisition.rst
ffta.acquisition package
========================
Submodules
----------
ffta.acquisition.generate\_chirp module
---------------------------------------
.. automodule:: ffta.acquisition.generate_chirp
:members:
:undoc-members:
:show-inheritance:
ffta.acquisition.polling module
-------------------------------
.. automodule:: ffta.acquisition.polling
:members:
:undoc-members:
:show-inheritance:
Module contents
---------------
.. automodule:: ffta.acquisition
:members:
:undoc-members:
:show-inheritance:
<file_sep>/ffta/analyze.py
"""analyze.py: Runs the FF-trEFM Analysis for a set of given files."""
__author__ = "<NAME>"
__copyright__ = "Copyright 2019, Ginger Lab"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
__status__ = "Development"
import os
import sys
import time
import multiprocessing
import logging
import argparse as ap
import numpy as np
import ffta.line as line
from ffta.pixel_utils import load
import badpixels
# Plotting imports
import matplotlib as mpl
#mpl.use('WxAgg')
from matplotlib import pyplot as plt
from matplotlib import gridspec as gs
def process_line(args):
"""Wrapper function for line class, used in parallel processing."""
signal_file, params, n_pixels = args
signal_array = load.signal(signal_file)
line_inst = line.Line(signal_array, params, n_pixels)
tfp, shift, _ = line_inst.analyze()
return tfp, shift
def main(argv=None):
"""Main function of the executable file."""
logging.basicConfig(filename='error.log', level=logging.INFO)
# Get the CPU count to display in help.
cpu_count = multiprocessing.cpu_count()
if argv is None:
argv = sys.argv[1:]
# Parse arguments from the command line, and print out help.
parser = ap.ArgumentParser(description='Analysis software for FF-trEFM')
parser.add_argument('path', nargs='?', default=os.getcwd(),
help='path to directory')
parser.add_argument('-p', help='parallel computing option should be'
'followed by the number of CPUs.', type=int,
choices=range(2, cpu_count + 1))
parser.add_argument('-v', action='version',
version='FFtr-EFM 2.0 Release Candidate')
args = parser.parse_args(argv)
# Scan the path for .ibw and .cfg files.
path = args.path
filelist = os.listdir(path)
data_files = [os.path.join(path, name)
for name in filelist if name[-3:] == 'ibw']
config_file = [os.path.join(path, name)
for name in filelist if name[-3:] == 'cfg'][0]
# Load parameters from .cfg file.
n_pixels, parameters = load.configuration(config_file)
print('Recombination: ', parameters['recombination'])
if 'phase_fitting' in parameters:
print('Phase fitting: ', parameters['phase_fitting'])
print( 'ROI: ', parameters['roi'])
if not args.p:
# Initialize arrays.
tfp = np.zeros((len(data_files), n_pixels))
shift = np.zeros((len(data_files), n_pixels))
# Initialize plotting.
plt.ion()
fig = plt.figure(figsize=(12, 6), tight_layout=True)
grid = gs.GridSpec(1, 2)
tfp_ax = plt.subplot(grid[0, 0])
shift_ax = plt.subplot(grid[0, 1])
plt.setp(tfp_ax.get_xticklabels(), visible=False)
plt.setp(tfp_ax.get_yticklabels(), visible=False)
plt.setp(shift_ax.get_xticklabels(), visible=False)
plt.setp(shift_ax.get_yticklabels(), visible=False)
tfp_ax.set_title('tFP Image')
shift_ax.set_title('Shift Image')
kwargs = {'origin': 'lower', 'aspect': 'equal'}
tfp_image = tfp_ax.imshow(tfp * 1e6, cmap='afmhot', **kwargs)
shift_image = shift_ax.imshow(shift, cmap='cubehelix', **kwargs)
text = plt.figtext(0.4, 0.1, '')
plt.show()
# Load every file in the file list one by one.
for i, data_file in enumerate(data_files):
signal_array = load.signal(data_file)
line_inst = line.Line(signal_array, parameters, n_pixels)
tfp[i, :], shift[i, :], _ = line_inst.analyze()
# line_inst = line.Line(signal_array, parameters, n_pixels,fitphase=True)
# tfpphase[i, :], _, _ = line_inst.analyze()
tfp_image = tfp_ax.imshow(tfp * 1e6, cmap='inferno', **kwargs)
shift_image = shift_ax.imshow(shift, cmap='cubehelix', **kwargs)
tfp_sc = tfp[tfp.nonzero()] * 1e6
tfp_image.set_clim(vmin=tfp_sc.min(), vmax=tfp_sc.max())
shift_sc = shift[shift.nonzero()]
shift_image.set_clim(vmin=shift_sc.min(), vmax=shift_sc.max())
tfpmean = 1e6 * tfp[i, :].mean()
tfpstd = 1e6 * tfp[i, :].std()
string = ("Line {0:.0f}, average tFP (us) ="
" {1:.2f} +/- {2:.2f}".format(i + 1, tfpmean, tfpstd))
text.remove()
text = plt.figtext(0.35, 0.1, string)
plt.draw()
plt.pause(0.0001)
del line_inst # Delete the instance to open up memory.
elif args.p:
print('Starting parallel processing, using {0:1d} \
CPUs.'.format(args.p))
start_time = time.time() # Keep when it's started.
# Create a pool of workers.
pool = multiprocessing.Pool(processes=args.p)
# Create the iterable and map onto the function.
n_files = len(data_files)
iterable = zip(data_files, [parameters] * n_files,
[n_pixels] * n_files)
result = pool.map(process_line, iterable)
# Do not forget to close spawned processes.
pool.close()
pool.join()
# Unzip the result.
tfp_list, shift_list = zip(*result)
# Initialize arrays.
tfp = np.zeros((n_files, n_pixels))
shift = np.zeros((n_files, n_pixels))
# Convert list of arrays to 2D array.
for i in range(n_files):
tfp[i, :] = tfp_list[i]
shift[i, :] = shift_list[i]
elapsed_time = time.time() - start_time
print ('It took {0:.1f} seconds.'.format(elapsed_time))
# Filter bad pixels
tfp_fixed, _ = badpixels.fix_array(tfp, threshold=2)
tfp_fixed = np.array(tfp_fixed)
# Save csv files.
os.chdir(path)
np.savetxt('tfp.csv', np.fliplr(tfp).T, delimiter=',')
np.savetxt('shift.csv', np.fliplr(shift).T, delimiter=',')
np.savetxt('tfp_fixed.csv', np.fliplr(tfp_fixed).T, delimiter=',')
return
if __name__ == '__main__':
sys.exit(main(sys.argv[1:]))
<file_sep>/docs/source/ffta.gkpfm.rst
ffta.gkpfm package
==================
Submodules
----------
ffta.gkpfm.gkline module
------------------------
.. automodule:: ffta.gkpfm.gkline
:members:
:undoc-members:
:show-inheritance:
ffta.gkpfm.gkpixel module
-------------------------
.. automodule:: ffta.gkpfm.gkpixel
:members:
:undoc-members:
:show-inheritance:
ffta.gkpfm.gkprocess module
---------------------------
.. automodule:: ffta.gkpfm.gkprocess
:members:
:undoc-members:
:show-inheritance:
ffta.gkpfm.load\_excitation module
----------------------------------
.. automodule:: ffta.gkpfm.load_excitation
:members:
:undoc-members:
:show-inheritance:
ffta.gkpfm.transfer\_func module
--------------------------------
.. automodule:: ffta.gkpfm.transfer_func
:members:
:undoc-members:
:show-inheritance:
Module contents
---------------
.. automodule:: ffta.gkpfm
:members:
:undoc-members:
:show-inheritance:
<file_sep>/ffta/pixel_utils/dwavelet.py
"""dwavelet.py: contains functions used in DWT calculations."""
import pywt
import numpy as np
def dwt_denoise(signal, fLow, fHigh, sampling_rate):
""" Uses Discrete Wavelet Transform to denoise signal
around a desired frequency band.
Parameters
----------
fLow: float
frequency below which DWT coefficients zeroed
fHigh: float
frequency above which DWT coefficients zeroed
sampling_rate: float
Sample rate of signal in Hz
"""
coeffs = pywt.wavedec(signal, 'db1')
frequencies = np.zeros(len(coeffs))
# The upper frequency at each DWT level
for i in xrange(len(coeffs)):
frequencies[-1-i] = sampling_rate / (2 ** (i+1))
# Levels corresponding to fLow and fHigh
fLow_idx = np.searchsorted(frequencies, fLow)
fHigh_idx = np.searchsorted(frequencies, fHigh)
# Correct issues with the index searching
if frequencies[fLow_idx] > fLow:
fLow_idx -= 1
if frequencies[fHigh_idx] < fHigh:
fHigh_idx = np.min([fHigh_idx+1, xrange(len(coeffs))])
# Set coefficients to 0
for i in xrange(fLow_idx):
coeffs[i][:] = coeffs[i][:] * 0
# for i in xrange(len(coeffs) - fHigh_idx):
# coeffs[i+fHigh_idx][:] = coeffs[i+fHigh_idx][:] * 0
denoised = pywt.waverec(coeffs, 'db1')
return denoised, coeffs, frequencies
def dwt_scalogram(coeffs):
maxsize = len(coeffs[-1])
scalogram = np.zeros(maxsize)
xpts = np.arange(maxsize)
# interpolates each row over [0...maxsize]
for i in xrange(len(coeffs)):
rptx = np.linspace(0, maxsize, len(coeffs[i]))
samplerow = np.interp(xpts, rptx, coeffs[i])
scalogram = np.vstack((scalogram, samplerow) )
# delete dummy first row that's needed for vstack to work
scalogram = np.delete(scalogram, (0), axis=0)
return scalogram
<file_sep>/ffta/analysis/__init__.py
from . import dist_cluster
from . import svd
from . import gmode_simple
from . import mask_utils
from . import test_pixel
from . import create_movie
from . import filtering
__all__ = ['svd', 'dist_cluster', 'gmode_simple']
<file_sep>/ffta/pixel_utils/fitting.py
"""fitting.py: Routines for fitting cantilever data to extract tFP/shift"""
import numpy as np
from scipy.optimize import minimize
'''
Fit Equations
'''
def ddho_freq_product(t, A, tau1, tau2):
'''Uses a product of exponentials as the functional form'''
decay = np.exp(-t / tau1) - 1
relaxation = -1 * np.exp(-t / tau2)
return A * decay * relaxation
def ddho_freq_sum(t, A1, A2, tau1, tau2):
'''Uses a sum of exponentials as the functional form'''
decay = np.exp(-t / tau1) - 1
relaxation = -1 * np.exp(-t / tau2)
return A1 * decay + A2 * relaxation
def cut_exp(t, A, y0, tau):
'''Uses a single exponential for the case of no drive'''
return y0 + A * np.exp(-t / tau)
def ddho_phase(t, A, tau1, tau2):
prefactor = tau2 / (tau1 + tau2)
return A * tau1 * np.exp(-t / tau1) * (-1 + prefactor * np.exp(-t / tau2)) + A * tau1 * (1 - prefactor)
'''
Fit functions
Product: product of two exponential functions (default)
Sum: sum of two exponential functions
Exp: Single exponential decay
Ringdown: Same as Exp but with different bounds
Phase: integrated product of two exponential functions
'''
def fit_product(Q, drive_freq, t, inst_freq):
# Initial guess for relaxation constant.
inv_beta = Q / (np.pi * drive_freq)
# Cost function to minimize.
cost = lambda p: np.sum((ddho_freq_product(t, *p) - inst_freq) ** 2)
# bounded optimization using scipy.minimize
pinit = [inst_freq.min(), 1e-4, inv_beta]
popt = minimize(cost, pinit, method='TNC', options={'disp': False},
bounds=[(-10000, -1.0),
(5e-7, 0.1),
(1e-5, 0.1)])
return popt.x
def fit_sum(Q, drive_freq, t, inst_freq):
# Initial guess for relaxation constant.
inv_beta = Q / (np.pi * drive_freq)
# Cost function to minimize.
cost = lambda p: np.sum((ddho_freq_sum(t, *p) - inst_freq) ** 2)
# bounded optimization using scipy.minimize
pinit = [inst_freq.min(), inst_freq.min(), 1e-4, inv_beta]
popt = minimize(cost, pinit, method='TNC', options={'disp': False},
bounds=[(-10000, -1.0),
(-10000, -1.0),
(5e-7, 0.1),
(1e-5, 0.1)])
return popt.x
def fit_exp(t, inst_freq):
# Cost function to minimize.
cost = lambda p: np.sum((cut_exp(t, *p) - inst_freq) ** 2)
pinit = [inst_freq.max() - inst_freq.min(), inst_freq.min(), 1e-4]
popt = minimize(cost, pinit, method='TNC', options={'disp': False},
bounds=[(1e-5, 1000),
(np.abs(inst_freq.min()) * -2, np.abs(inst_freq.max()) * 2),
(1e-6, 0.1)])
return popt.x
def fit_ringdown(t, cut):
# Cost function to minimize. Faster than normal scipy optimize or lmfit
cost = lambda p: np.sum((cut_exp(t, *p) - cut) ** 2)
pinit = [cut.max() - cut.min(), cut.min(), 1e-4]
popt = minimize(cost, pinit, method='TNC', options={'disp': False},
bounds=[(0, 5 * (cut.max() - cut.min())),
(0, cut.min()),
(1e-8, 1)])
return popt.x
def fit_phase(Q, drive_freq, t, phase):
# Initial guess for relaxation constant.
inv_beta = Q / (np.pi * drive_freq)
# Cost function to minimize.
cost = lambda p: np.sum((ddho_phase(t, *p) - phase) ** 2)
# bounded optimization using scipy.minimize
pinit = [phase.max() - phase.min(), 1e-4, inv_beta]
maxamp = phase[-1] / (1e-4 * (1 - inv_beta / (inv_beta + 1e-4)))
popt = minimize(cost, pinit, method='TNC', options={'disp': False},
bounds=[(0, 5 * maxamp),
(5e-7, 0.1),
(1e-5, 0.1)])
return popt.x
<file_sep>/ffta/__init__.py
from . import acquisition
from . import hdf_utils
from . import pixel_utils
from . import analysis
from . import gkpfm
from . import simulation
from . import load
from . import pixel
from . import line
__all__ = ['line', 'pixel']
__all__ += acquisition.__all__
__all__ += hdf_utils.__all__
__all__ += pixel_utils.__all__
__all__ += analysis.__all__
__all__ += gkpfm.__all__<file_sep>/docs/source/ffta.simulation.rst
ffta.simulation package
=======================
Submodules
----------
ffta.simulation.broadband\_drive module
---------------------------------------
.. automodule:: ffta.simulation.broadband_drive
:members:
:undoc-members:
:show-inheritance:
ffta.simulation.cantilever module
---------------------------------
.. automodule:: ffta.simulation.cantilever
:members:
:undoc-members:
:show-inheritance:
:noindex:
ffta.simulation.electric\_drive module
--------------------------------------
.. automodule:: ffta.simulation.electric_drive
:members:
:undoc-members:
:show-inheritance:
ffta.simulation.excitation module
---------------------------------
.. automodule:: ffta.simulation.excitation
:members:
:undoc-members:
:show-inheritance:
ffta.simulation.load module
---------------------------
.. automodule:: ffta.simulation.load
:members:
:undoc-members:
:show-inheritance:
ffta.simulation.mechanical\_drive module
----------------------------------------
.. automodule:: ffta.simulation.mechanical_drive
:members:
:undoc-members:
:show-inheritance:
Module contents
---------------
.. automodule:: ffta.simulation
:members:
:undoc-members:
:show-inheritance:
<file_sep>/ffta/simulation/excitation.py
'''
Contains excitation functions used in simulations.
These functions all assume an output scaled from 0 to 1. In MechanicalDrive,
these would all be passed to omega0 and to to Fe to change with these time-dependent
conditions, where t is passed relative to the trigger Cantilever.trigger
'''
import numpy as np
def single_exp(t, tau):
'''
Resonance frequency exhibits single exponential decay to a new offset
Parameters
----------
t : float or ndarray
Time axis
tau : float
Time constant for decay
'''
return -np.expm1(-t / tau)
def bi_exp(t, tau1, tau2):
'''
Resonance frequency exhibits bi-exponential decay to a new offset
'''
A = np.exp(-t / tau1)
B = np.exp(-t / tau2)
return -0.5 * (A + B - 2)
def str_exp(t, tau, beta):
'''
Resonance frequency exhibits stretched exponential decay to a new offset
'''
return - (np.exp(-t / tau) ** beta - 1)
def step(t):
'''
Heaviside function
'''
return np.heaviside(t, 0)
<file_sep>/docs/source/ffta.pixel_utils.rst
ffta.pixel\_utils package
=========================
Submodules
----------
ffta.pixel\_utils.badpixels module
----------------------------------
.. automodule:: ffta.pixel_utils.badpixels
:members:
:undoc-members:
:show-inheritance:
ffta.pixel\_utils.dwavelet module
---------------------------------
.. automodule:: ffta.pixel_utils.dwavelet
:members:
:undoc-members:
:show-inheritance:
ffta.pixel\_utils.fitting module
--------------------------------
.. automodule:: ffta.pixel_utils.fitting
:members:
:undoc-members:
:show-inheritance:
ffta.pixel\_utils.load module
-----------------------------
.. automodule:: ffta.pixel_utils.load
:members:
:undoc-members:
:show-inheritance:
ffta.pixel\_utils.noise module
------------------------------
.. automodule:: ffta.pixel_utils.noise
:members:
:undoc-members:
:show-inheritance:
ffta.pixel\_utils.parab module
------------------------------
.. automodule:: ffta.pixel_utils.parab
:members:
:undoc-members:
:show-inheritance:
ffta.pixel\_utils.peakdetect module
-----------------------------------
.. automodule:: ffta.pixel_utils.peakdetect
:members:
:undoc-members:
:show-inheritance:
ffta.pixel\_utils.tfp\_calc module
----------------------------------
.. automodule:: ffta.pixel_utils.tfp_calc
:members:
:undoc-members:
:show-inheritance:
Module contents
---------------
.. automodule:: ffta.pixel_utils
:members:
:undoc-members:
:show-inheritance:
<file_sep>/ffta/acquisition/generate_chirp.py
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 23 16:23:12 2020
@author: Raj
"""
import scipy.signal as sps
import numpy as np
import argparse
def GenChirp(f_center, f_width=100e3, length=1e-2, sampling_rate=1e8, name='chirp'):
'''
Generates a single broad-frequency signal using scipy chirp, writes to name.dat
Important usage regarding the sampling rate:
The sampling rate here must match that of the wave generator when you load
this signal. There is a limit of 250 MHz on the 33200 Agilent wave generator,
but obviously that varies.
Parameters
----------
f_center : float
Central frequency for the signal
f_width : float
The single-sided width of the chirp. Generates signal from f_center - f_width
to f_center + f_width
length : float
the timescale of the signal. Keep this length in mind for data acquisition;
if your chirp is longer than your data acquisition, you will miss many of
the frequencies
sampling_rate : int
Sampling rate of the chirp, based on length/sampling_rate number of steps
This rate must be consistent on the wave generator or the frequencies will
be off
name : str
Filename for writing the chirp to disk
'''
tx = np.arange(0, length, 1 / sampling_rate) # fixed 100 MHz sampling rate for 10 ms
f_hi = f_center + f_width
f_lo = np.max([f_center - f_width, 1]) # to ensure a positive number
chirp = sps.chirp(tx, f_lo, tx[-1], f_hi)
if '.dat' not in name:
name = name + '.dat'
np.savetxt(name, chirp, delimiter='\n', fmt='%.10f')
return chirp
def GenManyChirps(f_center, f_width=100e3, length=1e-2, sampling_rate=1e8):
'''
Based on the Agilent manual, the max-frequency is 250 MHz/number_of_points
The minimum number of points is 8, maximum is 1e6
This creates 3 chirp signals around the first three mechanical resonances
'''
name = "chirp_w.dat"
GenChirp(f_center, f_width, length, sampling_rate, name)
name = "chirp_2w.dat" # second electrical resonance
GenChirp(2 * f_center, f_width, length, sampling_rate, name)
name = "chirp_3w.dat" # third electrical resonance
GenChirp(3 * f_center, f_width, length, sampling_rate, name)
name = "chirp_w2.dat" # second mechanical resonance
GenChirp(6.25 * f_center, f_width, length, sampling_rate, name)
return
if __name__ == '__main__':
'''
From command line, usage:
>> python generate_chirp.py 350000 100000
Generates a 350 kHz +/- 100 kHz chirp. This would be ~14 MB on disk
Defaults to 100 MHz, 10 ms length
'''
parser = argparse.ArgumentParser()
parser.add_argument('freq_center', help='Resonance Frequency (Hz)')
parser.add_argument('freq_width', help='Frequency width (Hz)')
f_center = float(parser.parse_args().freq_center)
f_width = float(parser.parse_args().freq_width)
chirp = GenChirp(f_center, f_width)
# Old wavegenerator code
def GeneratePulse(pulse_time, voltage, total_time):
sample_rate = 1.0e7
total_samples = sample_rate * total_time
pulse_samples = sample_rate * pulse_time
data = np.zeros(total_samples)
data[:pulse_samples] = voltage
fo = open("Pulse.dat", "wb")
for i in range(int(total_samples)):
fo.write(str(data[i]) + "\r")
fo.close()
def GenerateTaus(tau, beta, sfx=''):
sample_rate = 1.0e8 # sampling rate used in Wavegenerator code
total_samples = 800000
pulse_samples = 700000
data = np.arange(total_samples) / sample_rate
data[:pulse_samples] = np.exp(-data[:pulse_samples] / tau) ** beta - 1
data[pulse_samples:] = 0
name = "taub" + sfx + ".dat"
np.savetxt(name, data, delimiter='\n', fmt='%.10f')
<file_sep>/docs/source/ffta.hdf_utils.rst
ffta.hdf\_utils package
=======================
Submodules
----------
ffta.hdf\_utils.analyze\_h5 module
----------------------------------
.. automodule:: ffta.hdf_utils.analyze_h5
:members:
:undoc-members:
:show-inheritance:
ffta.hdf\_utils.hdf\_utils module
---------------------------------
.. automodule:: ffta.hdf_utils.hdf_utils
:members:
:undoc-members:
:show-inheritance:
ffta.hdf\_utils.plot\_tfp module
--------------------------------
.. automodule:: ffta.hdf_utils.plot_tfp
:members:
:undoc-members:
:show-inheritance:
ffta.hdf\_utils.process module
------------------------------
.. automodule:: ffta.hdf_utils.process
:members:
:undoc-members:
:show-inheritance:
Module contents
---------------
.. automodule:: ffta.hdf_utils
:members:
:undoc-members:
:show-inheritance:
<file_sep>/ffta/simulation/__init__.py
from . import cantilever
from . import load
from . import mechanical_drive
from . import electric_drive
__all__ = ['cantilever',
'mechanical_drive',
'electric_drive']<file_sep>/ffta/pixel_utils/tfp_calc.py
# -*- coding: utf-8 -*-
"""tfp.py: Routines for fitting the frequency/phase/amplitude to extract tFP/shift """
from . import fitting
import numpy as np
from scipy import interpolate as spi
from scipy import optimize as spo
def find_minimum(pix, cut):
"""
Finds when the minimum of instantaneous frequency happens using spline fitting
Parameters
----------
pix : ffta.pixel.Pixel object
pixel object to analyze
cut : ndarray
The slice of frequency data to fit against
Returns
-------
pix.tfp : float
tFP value
pix.shift : float
frequency shift value at time t=tfp
pix.best_fit : ndarray
Best-fit line calculated from spline function
"""
# Cut the signal into region of interest.
# ridx = int(pix.roi * pix.sampling_rate)
# cut = pix.inst_freq[pix.tidx:(pix.tidx + ridx)]
# Define a spline to be used in finding minimum.
ridx = len(cut)
x = np.arange(ridx)
y = cut
_spline_sz = 2 * pix.sampling_rate / pix.drive_freq
func = spi.UnivariateSpline(x, y, k=4, ext=3, s=_spline_sz)
# Find the minimum of the spline using TNC method.
res = spo.minimize(func, cut.argmin(),
method='TNC', bounds=((0, ridx),))
idx = res.x[0]
pix.best_fit = func(np.arange(ridx))
# Do index to time conversion and find shift.
pix.tfp = idx / pix.sampling_rate
pix.shift = func(0) - func(idx)
return
def fit_freq_product(pix, cut, t):
'''
Fits the frequency shift to an approximate functional form using
an analytical fit with bounded values.
Parameters
----------
pix : ffta.pixel.Pixel object
pixel object to analyze
cut : ndarray
The slice of frequency data to fit against
t : ndarray
The time-array (x-axis) for fitting
Returns
-------
pix.tfp : float
tFP value
pix.shift : float
frequency shift value at time t=tfp
pix.rms : float
fitting error
pix.popt : ndarray
The fit parameters for the function fitting.fit_product
pix.best_fit : ndarray
Best-fit line calculated from popt and fit function
'''
# Fit the cut to the model.
popt = fitting.fit_product(pix.Q, pix.drive_freq, t, cut)
A, tau1, tau2 = popt
# Analytical minimum of the fit.
# self.tfp = tau2 * np.log((tau1 + tau2) / tau2)
# self.shift = -A * np.exp(-self.tfp / tau1) * np.expm1(-self.tfp / tau2)
# For diagnostic purposes.
pix.popt = popt
pix.best_fit = -A * (np.exp(-t / tau1) - 1) * np.exp(-t / tau2)
pix.tfp = np.argmin(pix.best_fit) / pix.sampling_rate
pix.shift = np.min(pix.best_fit)
pix.rms = np.sqrt(np.mean(np.square(pix.best_fit - cut)))
return
def fit_freq_sum(pix, ridx, cut, t):
'''
Fits the frequency shift to an approximate functional form using
an analytical fit with bounded values.
Parameters
----------
pix : ffta.pixel.Pixel object
pixel object to analyze
cut : ndarray
The slice of frequency data to fit against
t : ndarray
The time-array (x-axis) for fitting
Returns
-------
pix.tfp : float
tFP value
pix.shift : float
frequency shift value at time t=tfp
pix.rms : float
fitting error
pix.popt : ndarray
The fit parameters for the function fitting.fit_sum
pix.best_fit : ndarray
Best-fit line calculated from popt and fit function
'''
# Fit the cut to the model.
popt = fitting.fit_sum(pix.Q, pix.drive_freq, t, cut)
A1, A2, tau1, tau2 = popt
# For diagnostic purposes.
pix.popt = popt
pix.best_fit = A1 * (np.exp(-t / tau1) - 1) - A2 * np.exp(-t / tau2)
pix.tfp = np.argmin(pix.best_fit) / pix.sampling_rate
pix.shift = np.min(pix.best_fit)
return
def fit_freq_exp(pix, ridx, cut, t):
'''
Fits the frequency shift to a single exponential in the case where
there is no return to 0 Hz offset (if drive is cut).
Parameters
----------
pix : ffta.pixel.Pixel object
pixel object to analyze
cut : ndarray
The slice of frequency data to fit against
t : ndarray
The time-array (x-axis) for fitting
Returns
-------
pix.tfp : float
tFP value
pix.shift : float
frequency shift value at time t=tfp
pix.popt : ndarray
The fit parameters for the function fitting.fit_exp
pix.best_fit : ndarray
Best-fit line calculated from popt and fit function
'''
# Fit the cut to the model.
popt = fitting.fit_exp(t, cut)
# For diagnostics
A, y0, tau = popt
pix.popt = popt
pix.best_fit = A * (np.exp(-t / tau)) + y0
pix.shift = A
pix.tfp = tau
return
def fit_ringdown(pix, ridx, cut, t):
'''
Fits the amplitude to determine Q from single exponential fit.
Parameters
----------
pix : ffta.pixel.Pixel object
pixel object to analyze
cut : ndarray
The slice of amplitude data to fit against
t : ndarray
The time-array (x-axis) for fitting
Returns
-------
pix.tfp : float
Q calculated from ringdown equation
pix.ringdown_Q : float
Same as tFP. This is the actual variable, tFP is there for code simplicity
pix.shift : float
amplitude of the single exponential decay
pix.popt : ndarray
The fit parameters for the function fitting.fit_ringdown
pix.best_fit : ndarray
Best-fit line calculated from popt and fit function
'''
# Fit the cut to the model.
popt = fitting.fit_ringdown(t, cut * 1e9)
popt[0] *= 1e-9
popt[1] *= 1e-9
# For diagnostics
A, y0, tau = popt
pix.popt = popt
pix.best_fit = A * (np.exp(-t / tau)) + y0
pix.shift = A
pix.tfp = np.pi * pix.drive_freq * tau # same as ringdown_Q to help with pycroscopy bugs that call tfp
pix.ringdown_Q = np.pi * pix.drive_freq * tau
return
def fit_phase(pix, ridx, cut, t):
'''
Fits the phase to an approximate functional form using an
analytical fit with bounded values.
Parameters
----------
pix : ffta.pixel.Pixel object
pixel object to analyze
cut : ndarray
The slice of frequency data to fit against
t : ndarray
The time-array (x-axis) for fitting
Returns
-------
pix.tfp : float
tFP value
pix.shift : float
frequency shift value at time t=tfp
pix.popt : ndarray
The fit parameters for the function fitting.fit_phase
pix.best_fit : ndarray
Best-fit line calculated from popt and fit function for the frequency data
pix.best_phase : ndarray
Best-fit line calculated from popt and fit function for the phase data
'''
# Fit the cut to the model.
popt = fitting.fit_phase(pix.Q, pix.drive_freq, t, cut)
A, tau1, tau2 = popt
# Analytical minimum of the fit.
pix.tfp = tau2 * np.log((tau1 + tau2) / tau2)
pix.shift = A * np.exp(-pix.tfp / tau1) * np.expm1(-pix.tfp / tau2)
# For diagnostic purposes.
postfactor = (tau2 / (tau1 + tau2)) * np.exp(-t / tau2) - 1
pix.popt = popt
pix.best_fit = -A * np.exp(-t / tau1) * np.expm1(-t / tau2)
pix.best_phase = A * tau1 * np.exp(-t / tau1) * postfactor + A * tau1 * (1 - tau2 / (tau1 + tau2))
return
<file_sep>/XOP/FPGACollection.cpp
#include "NiFpga.h"
#include "NiFpga_125MSAcquire.h"
#include "XOPStandardHeaders.h"
#include <math.h>
static int gCallSpinProcess = 1;
double** FPGAAcquireData(uint32_t numRecords, uint32_t recordLength, uint32_t preTriggerSamples)
{
NiFpga_Session session;
NiFpga_Status status;
NiFpga_Bool edgeDetected;
double** data;
uint32_t recordsTransfered;
int16_t* signal;
char noticeString[50];
int result;
double scaleFactor = pow(2.0, 15.0);
// initialize storage pointer
const int nrow = (int) recordLength, ncol = (int)numRecords, nelem = nrow*ncol;
data = new double*[nrow];
data[0] = new double[nelem];
for (int i = 1; i < nrow; i++)
{
data[i] = data[i - 1] + ncol;
}
int16_t *s = new int16_t[recordLength];
status = NiFpga_Initialize();
// Open the Bitfile located in the IGOR Extensions Folder, where this XOP will be placed
if (NiFpga_IsNotError(status))
{
NiFpga_MergeStatus(&status, NiFpga_Open("C:\\Program Files (x86)\\WaveMetrics\\Igor Pro Folder\\Igor Extensions\\"NiFpga_125MSAcquire_Bitfile,
NiFpga_125MSAcquire_Signature,
"RIO0",
0,
&session));
sprintf(noticeString, "Error in opening bitfile:%i\r", status);
XOPNotice(noticeString);
}
if (NiFpga_IsNotError(status))
{
// Write all the requested parameters to the FPGA Acquisition System.
NiFpga_MergeStatus(&status,
NiFpga_WriteU32(session,
NiFpga_125MSAcquire_ControlU32_NumRecords, // Averages
numRecords));
NiFpga_MergeStatus(&status,
NiFpga_WriteU32(session,
NiFpga_125MSAcquire_ControlU32_RecordLength, // Points per Average
recordLength));
NiFpga_MergeStatus(&status,
NiFpga_WriteU32(session,
NiFpga_125MSAcquire_ControlU32_PreTriggerSamples, // Number of pretrigger samples
preTriggerSamples));
NiFpga_MergeStatus(&status,
NiFpga_WriteBool(session,
NiFpga_125MSAcquire_ControlBool_ExternalTrigger, // Tells the FPGA to use an external trigger instead of the built-in software trigger
1));
// Start the Acquisiton
NiFpga_MergeStatus(&status,
NiFpga_WriteBool(session,
NiFpga_125MSAcquire_ControlBool_StartAcq,
1));
}
if (NiFpga_IsNotError(status))
{
NiFpga_MergeStatus(&status,
NiFpga_ReadU32(session,
NiFpga_125MSAcquire_IndicatorU32_RecordsTransfered,
&recordsTransfered));
// Keep recording until we have reached the desired amount of triggers
while (recordsTransfered < numRecords - 1)
{
if (gCallSpinProcess && SpinProcess()) { // Spins cursor and allows background processing.
result = -1; // User aborted.
break;
}
NiFpga_MergeStatus(&status,
NiFpga_ReadU32(session,
NiFpga_125MSAcquire_IndicatorU32_RecordsTransfered,
&recordsTransfered));
// Wait until we trigger.
NiFpga_MergeStatus(&status,
NiFpga_ReadBool(session,
NiFpga_125MSAcquire_IndicatorBool_edgedetected,
&edgeDetected));
while (edgeDetected == 0)
{
NiFpga_MergeStatus(&status,
NiFpga_ReadBool(session,
NiFpga_125MSAcquire_IndicatorBool_edgedetected,
&edgeDetected));
}
// Transfer data from the FPGA FIFO to a temporary storage buffer
NiFpga_MergeStatus(&status,
NiFpga_ReadFifoI16(session,
NiFpga_125MSAcquire_TargetToHostFifoI16_ToHost,
s,
recordLength,
NiFpga_InfiniteTimeout,
NULL));
// Write from the temp buffer into the data transfer buffer
for (int i = 0; i < recordLength; i++)
{
data[i][recordsTransfered] = (double)s[i]/scaleFactor;
}
}
/* Reset the FPGA back to the "Wait for Start Trigger" State*/
NiFpga_MergeStatus(&status,
NiFpga_WriteBool(session,
NiFpga_125MSAcquire_ControlBool_StartAcq,
0));
NiFpga_MergeStatus(&status,
NiFpga_WriteBool(session,
NiFpga_125MSAcquire_ControlBool_Reset,
1));
NiFpga_MergeStatus(&status,
NiFpga_WriteBool(session,
NiFpga_125MSAcquire_ControlBool_Reset,
0));
NiFpga_MergeStatus(&status, NiFpga_Close(session, 0));
}
NiFpga_MergeStatus(&status, NiFpga_Finalize());
delete[] s;
return data;
}<file_sep>/ffta/pixel.py
"""pixel.py: Contains pixel class."""
# pylint: disable=E1101,R0902,C0103
__author__ = "<NAME>"
__copyright__ = "Copyright 2020"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
__status__ = "Development"
import logging
import numpy as np
from scipy import signal as sps
from scipy import optimize as spo
from scipy import interpolate as spi
from scipy import integrate as spg
from ffta.pixel_utils import noise
from ffta.pixel_utils import parab
from ffta.pixel_utils import fitting
from ffta.pixel_utils import dwavelet
from ffta.pixel_utils import tfp_calc
from matplotlib import pyplot as plt
import pywt
import time
class Pixel:
"""
Signal Processing to Extract Time-to-First-Peak.
Extracts Time-to-First-Peak (tFP) from digitized Fast-Free Time-Resolved
Electrostatic Force Microscopy (FF-trEFM) signals [1-2]. It includes a few
types of frequency analysis:
a) Hilbert Transform
b) Wavelet Transform
c) Hilbert-Huang Transform (EMD)
signal_array : (n_points, n_signals) array_like
2D real-valued signal array, corresponds to a pixel.
params : dict
Includes parameters for processing. The list of parameters is:
trigger = float (in seconds)
total_time = float (in seconds)
sampling_rate = int (in Hz)
drive_freq = float (in Hz)
roi = float (in seconds)
window = string (see documentation of scipy.signal.get_window)
bandpass_filter = int (0: no filtering, 1: FIR filter, 2: IIR filter)
filter_bandwidth = float (default: 5kHz)
n_taps = integer (default: 1799)
wavelet_analysis = bool (0: Hilbert method, 1: Wavelet Method)
wavelet_parameter = int (default: 5)
recombination = bool (0: Data are for Charging up, 1: Recombination)
fit_phase = bool (0: fit to frequency, 1: fit to phase)
can_params : dict, optional
Contains the cantilever parameters (e.g. AMPINVOLS).
see ffta.pixel_utils.load.cantilever_params
fit : bool, optional
Find tFP by just raw minimum (False) or fitting product of 2 exponentials (True)
pycroscopy : bool, optional
Pycroscopy requires different orientation, so this corrects for this effect.
fit_form : str, optional
Functional form used when fitting.
One of
product: product of two exponentials (default)
sum: sum of two exponentials
exp: single expential decay
ringdown: single exponential decay of amplitude, not frequency, scaled to return Q
method : str, optional
Method for generating instantaneous frequency, amplitude, and phase response
One of
hilbert: Hilbert transform method (default)
wavelet: Morlet CWT approach
stft: short time Fourier transform (sliding FFT)
filter_amplitude : bool, optional
The Hilbert Transform amplitude can sometimes have drive frequency artifact.
filter_frequency : bool, optional
Filters the instantaneous frequency to remove noise peaks
Attributes
----------
n_points : int
Number of points in a signal.
n_signals : int
Number of signals to be averaged in a pixel.
signal_array : (n_signals, n_points) array_like
Array that contains original signals.
signal : (n_points,) array_like
Signal after phase-locking and averaging.
tidx : int
Index of trigger in time-domain.
phase : (n_points,) array_like
Phase of the signal, only calculated with Hilbert Transform method.
cwt_matrix : (n_widths, n_points) array_like
Wavelet matrix for continuous wavelet transform.
inst_freq : (n_points,) array_like
Instantenous frequency of the signal.
tfp : float
Time from trigger to first-peak, in seconds.
shift : float
Frequency shift from trigger to first-peak, in Hz.
Methods
-------
analyze()
Analyzes signals and returns tfp, shift and inst_freq.
Notes
-----
Frequency shift from wavelet analysis is not in Hertz. It should be used
with caution.
analyze() does not raise an exception if there is one, however it logs the
exception if logging is turned on. This is implemented this way to avoid
crashing in the case of exception when this method is called from C API.
References
----------
.. \[1\] <NAME>, <NAME>, <NAME>, et al. Submicrosecond time
resolution atomic force microscopy for probing nanoscale dynamics.
Nano Lett. 2012;12(2):893-8.
\[2\] <NAME>, <NAME>, et al. Fast time-resolved electrostatic
force microscopy: Achieving sub-cycle time resolution. Rev Sci Inst.
2016;87(5):053702
Examples
--------
>>> from ffta import pixel, pixel_utils
>>>
>>> signal_file = '../data/SW_0000.ibw'
>>> params_file = '../data/parameters.cfg'
>>>
>>> signal_array = pixel_utils.load.signal(signal_file)
>>> n_pixels, params = pixel_utils.load.configuration(params_file)
>>>
>>> p = pixel.Pixel(signal_array, params)
>>> tfp, shift, inst_freq = p.analyze()
>>>
>>> p.plot()
"""
def __init__(self, signal_array, params, can_params=None,
fit=True, pycroscopy=False,
method='hilbert', fit_form='product', filter_amplitude=False,
filter_frequency=False):
# Create parameter attributes for optional parameters.
# These defaults are overwritten by values in 'params'
# FIR (Hilbert) filtering parameters
if can_params is None:
can_params = {}
self.n_taps = 1499
self.filter_bandwidth = 5000
self.filter_frequency = filter_frequency
# Wavelet parameters
self.wavelet_analysis = False
self.wavelet = 'cmor1-1' # default complex Morlet wavelet
self.scales = np.arange(100, 2, -1)
self.wavelet_params = {} # currently just optimize flag is supported
# Short Time Fourier Transform
self.fft_analysis = False
self.fft_cycles = 2
self.fft_params = {} # for STFT
self.recombination = False
self.phase_fitting = False
self.check_drive = True
# Assign the fit parameter.
self.fit = fit
self.fit_form = fit_form
self.method = method
self.filter_amplitude = filter_amplitude
# Default Cantilever parameters, plugging in some reasonable defaults
self.AMPINVOLS = 122e-9
self.SpringConstant = 23.2
self.k = self.SpringConstant
self.DriveAmplitude = 1.7e-9
self.Mass = 4.55e-12
self.Beta = 3114
self.Q = 360
# Read parameter attributes from parameters dictionary.
for key, value in params.items():
setattr(self, key, value)
for key, value in can_params.items():
setattr(self, key, float(value))
if self.filter_frequency:
self.bandpass_filter = 0 # turns off FIR
# Assign values from inputs.
self.signal_array = signal_array
self.signal_orig = None # used in amplitude calc to undo any Windowing beforehand
if pycroscopy:
self.signal_array = signal_array.T
self.tidx = int(self.trigger * self.sampling_rate)
# Set dimensions correctly
# Three cases: 1) 2D (has many averages) 2) 1D (but set as 1xN) and 3) True 1D
if len(signal_array.shape) == 2 and 1 not in signal_array.shape:
self.n_points, self.n_signals = self.signal_array.shape
self._n_points_orig = self.signal_array.shape[0]
else:
self.n_signals = 1
self.signal_array = self.signal_array.flatten()
self.n_points = self.signal_array.shape[0]
self._n_points_orig = self.signal_array.shape[0]
# Keep the original values for restoring the signal properties.
self._tidx_orig = self.tidx
self.tidx_orig = self.tidx
# Initialize attributes that are going to be assigned later.
self.signal = None
self.phase = None
self.inst_freq = None
self.tfp = None
self.shift = None
self.cwt_matrix = None
self.verbose = False # for console feedback
# For accidental passing ancillary datasets from Pycroscopy, this will fail
# when pickling
if hasattr(self, 'Position_Indices'):
del self.Position_Indices
if hasattr(self, 'Position_Values'):
del self.Position_Values
if hasattr(self, 'Spectroscopic_Indices'):
del self.Spectroscopic_Indices
if hasattr(self, 'Spectroscopic_Values'):
del self.Spectroscopic_Values
return
def clear_filter_flags(self):
"""Removes flags from parameters for setting filters"""
self.bandpass_filter = 0
return
def remove_dc(self):
"""Removes DC components from signals."""
if self.n_signals != 1:
for i in range(self.n_signals):
self.signal_array[:, i] -= np.mean(self.signal_array[:, i])
return
def phase_lock(self):
"""Phase-locks signals in the signal array. This also cuts signals."""
# Phase-lock signals.
self.signal_array, self.tidx = noise.phase_lock(self.signal_array, self.tidx,
np.ceil(self.sampling_rate / self.drive_freq))
# Update number of points after phase-locking.
self.n_points = self.signal_array.shape[0]
return
def average(self):
"""Averages signals."""
if self.n_signals != 1: # if not multi-signal, don't average
self.signal = self.signal_array.mean(axis=1)
else:
self.signal = np.copy(self.signal_array)
return
def check_drive_freq(self):
"""Calculates drive frequency of averaged signals, and check against
the given drive frequency."""
n_fft = 2 ** int(np.log2(self.tidx)) # For FFT, power of 2.
dfreq = self.sampling_rate / n_fft # Frequency separation.
# Calculate drive frequency from maximum power of the FFT spectrum.
signal = self.signal[:n_fft]
fft_amplitude = np.abs(np.fft.rfft(signal))
drive_freq = fft_amplitude.argmax() * dfreq
# Difference between given and calculated drive frequencies.
difference = np.abs(drive_freq - self.drive_freq)
# If difference is too big, reassign. Otherwise, continue. != 0 for accidental DC errors
if difference >= dfreq and drive_freq != 0:
self.drive_freq = drive_freq
return
def apply_window(self):
"""Applies the window given in parameters."""
self.signal *= sps.get_window(self.window, self.n_points)
return
def dwt_denoise(self):
"""Uses DWT to denoise the signal prior to processing."""
rate = self.sampling_rate
lpf = self.drive_freq * 0.1
self.signal, _, _ = dwavelet.dwt_denoise(self.signal, lpf, rate / 2, rate)
return
def fir_filter(self):
"""Filters signal with a FIR bandpass filter."""
# Calculate bandpass region from given parameters.
nyq_rate = 0.5 * self.sampling_rate
bw_half = self.filter_bandwidth / 2
freq_low = (self.drive_freq - bw_half) / nyq_rate
freq_high = (self.drive_freq + bw_half) / nyq_rate
band = [freq_low, freq_high]
# Create taps using window method.
try:
taps = sps.firwin(int(self.n_taps), band, pass_zero=False,
window='blackman')
except:
print('band=', band)
print('nyq=', nyq_rate)
print('drive=', self.drive_freq)
self.signal = sps.fftconvolve(self.signal, taps, mode='same')
# Shifts trigger due to causal nature of FIR filter
self.tidx -= (self.n_taps - 1) / 2
return
def iir_filter(self):
"""Filters signal with two Butterworth filters (one lowpass,
one highpass) using filtfilt. This method has linear phase and no
time delay."""
# Calculate bandpass region from given parameters.
nyq_rate = 0.5 * self.sampling_rate
bw_half = self.filter_bandwidth / 2
freq_low = (self.drive_freq - bw_half) / nyq_rate
freq_high = (self.drive_freq + bw_half) / nyq_rate
# Do a high-pass filtfilt operation.
b, a = sps.butter(9, freq_low, btype='high')
self.signal = sps.filtfilt(b, a, self.signal)
# Do a low-pass filtfilt operation.
b, a = sps.butter(9, freq_high, btype='low')
self.signal = sps.filtfilt(b, a, self.signal)
return
def amplitude_filter(self):
'''
Filters the drive signal out of the amplitude response
'''
AMP = np.fft.fftshift(np.fft.fft(self.amplitude))
DRIVE = self.drive_freq / (self.sampling_rate / self.n_points) # drive location in frequency space
center = int(len(AMP) / 2)
# crude boxcar
AMP[:center - int(DRIVE / 2) + 1] = 0
AMP[center + int(DRIVE / 2) - 1:] = 0
self.amplitude = np.abs(np.fft.ifft(np.fft.ifftshift(AMP)))
return
def frequency_filter(self):
'''
Filters the instantaneous frequency around DC peak to remove noise
Uses self.filter_bandwidth for the frequency filter
'''
FREQ = np.fft.fftshift(np.fft.fft(self.inst_freq))
center = int(len(FREQ) / 2)
df = self.sampling_rate / self.n_points
drive_bin = int(np.ceil(self.drive_freq / df))
bin_width = int(self.filter_bandwidth / df)
if bin_width > drive_bin:
print('width exceeds first resonance')
bin_width = drive_bin - 1
FREQ[:center - bin_width] = 0
FREQ[center + bin_width:] = 0
self.inst_freq = np.real(np.fft.ifft(np.fft.ifftshift(FREQ)))
return
def frequency_harmonic_filter(self, width=5):
'''
Filters the instantaneous frequency to remove noise
Defaults to DC and then every multiple harmonic up to sampling
Parameters
----------
width : int, optional
Size of the boxcar around the various peaks
'''
FREQ = np.fft.fftshift(np.fft.fft(self.inst_freq))
center = int(len(FREQ) / 2)
# Find drive_bin
df = self.sampling_rate / self.n_points
drive_bin = int(np.ceil(self.drive_freq / df))
bins = np.arange(len(FREQ) / 2)[::drive_bin]
bins = np.append(center - bins, center + bins)
FREQ_filt = np.zeros(len(FREQ), dtype='complex128')
for b in bins:
FREQ_filt[int(b) - width:int(b) + width] = FREQ[int(b) - width:int(b) + width]
self.inst_freq = np.real(np.fft.ifft(np.fft.ifftshift(FREQ)))
return
def hilbert(self):
"""Analytical signal and calculate phase/frequency via Hilbert transform"""
self.hilbert_transform()
self.calculate_amplitude()
self.calculate_phase()
self.calculate_inst_freq()
return
def hilbert_transform(self):
"""Gets the analytical signal doing a Hilbert transform."""
self.signal = sps.hilbert(self.signal)
return
def calculate_amplitude(self):
"""Calculates the amplitude of the analytic signal. Uses pre-filter
signal to do this."""
#
if self.n_signals != 1:
signal_orig = self.signal_array.mean(axis=1)
else:
signal_orig = self.signal_array
self.amplitude = np.abs(sps.hilbert(signal_orig))
if not np.isnan(self.AMPINVOLS):
self.amplitude *= self.AMPINVOLS
return
def calculate_power_dissipation(self):
"""Calculates the power dissipation using amplitude, phase, and frequency
and the Cleveland eqn (see DOI:10.1063/1.121434)"""
phase = self.phase # + np.pi/2 #offsets the phase to be pi/2 at resonance
# check for incorrect values (some off by 1e9 in our code)
A = self.k / self.Q * self.amplitude ** 2 * (self.inst_freq + self.drive_freq)
B = self.Q * self.DriveAmplitude * np.sin(phase) / self.amplitude
C = self.inst_freq / self.drive_freq
self.power_dissipated = A * (B - C)
return
def calculate_phase(self, correct_slope=True):
"""Gets the phase of the signal and correct the slope by removing
the drive phase."""
# Unwrap the phase.
self.phase = np.unwrap(np.angle(self.signal))
if correct_slope:
# Remove the drive from phase.
# self.phase -= (2 * np.pi * self.drive_freq *
# np.arange(self.n_points) / self.sampling_rate)
# A curve fit on the initial part to make sure that it worked.
start = int(0.3 * self.tidx)
end = int(0.7 * self.tidx)
fit = self.phase[start:end]
xfit = np.polyfit(np.arange(start, end), fit, 1)
# Remove the fit from phase.
self.phase -= (xfit[0] * np.arange(self.n_points)) + xfit[1]
self.phase = -self.phase # need to correct for negative in DDHO solution
self.phase += np.pi / 2 # corrects to be at resonance pre-trigger
return
def calculate_inst_freq(self):
"""Calculates the first derivative of the phase using Savitzky-Golay
filter."""
dtime = 1 / self.sampling_rate # Time step.
# Do a Savitzky-Golay smoothing derivative
# using 5 point 1st order polynomial.
# -self.phase to correct for sign in DDHO solution
self.inst_freq_raw = sps.savgol_filter(-self.phase, 5, 1, deriv=1,
delta=dtime)
# Bring trigger to zero.
self.tidx = int(self.tidx)
self.inst_freq = self.inst_freq_raw - self.inst_freq_raw[self.tidx]
return
def find_tfp(self):
"""Calculate tfp and shift based self.fit_form and self.fit selection"""
ridx = int(self.roi * self.sampling_rate)
cut = self.inst_freq[self.tidx:(self.tidx + ridx)]
cut -= self.inst_freq[self.tidx]
self.cut = cut
t = np.arange(cut.shape[0]) / self.sampling_rate
if not self.fit:
tfp_calc.find_minimum(self, cut)
elif self.fit_form == 'sum':
tfp_calc.fit_freq_sum(self, cut, t)
elif self.fit_form == 'exp':
tfp_calc.fit_freq_exp(self, cut, t)
elif self.fit_form == 'ringdown':
cut = self.amplitude[self.tidx:(self.tidx + ridx)]
tfp_calc.fit_ringdown(self, ridx, cut, t)
elif self.fit_form == 'product':
tfp_calc.fit_freq_product(self, cut, t)
elif self.fit_form == 'phase':
cut = -1 * (self.phase[self.tidx:(self.tidx + ridx)] - self.phase[self.tidx])
tfp_calc.fit_phase(self, cut, t)
return
def restore_signal(self):
"""Restores the signal length and position of trigger to original
values."""
# Difference between current and original values.
d_trig = int(self._tidx_orig - self.tidx)
d_points = int(self._n_points_orig - self.n_points)
# Check if the signal length can accomodate the shift or not.
if d_trig >= d_points:
# Pad from left and set the original length.
self.inst_freq = np.pad(self.inst_freq, (d_trig, 0), 'edge')
self.inst_freq = self.inst_freq[:self._n_points_orig]
self.phase = np.pad(self.phase, (d_trig, 0), 'edge')
self.phase = self.phase[:self._n_points_orig]
self.amplitude = np.pad(self.amplitude, (d_trig, 0), 'edge')
self.amplitude = self.amplitude[:self._n_points_orig]
else:
# Calculate how many points is needed for padding from right.
pad_right = d_points - d_trig
self.inst_freq = np.pad(self.inst_freq, (d_trig, pad_right),
'edge')
self.phase = np.pad(self.phase, (d_trig, pad_right),
'edge')
self.amplitude = np.pad(self.amplitude, (d_trig, pad_right),
'edge')
# Set the public variables back to original values.
self.tidx = self._tidx_orig
self.n_points = self._n_points_orig
return
def calculate_cwt(self, f_center=None, verbose=False, optimize=False, fit=False):
'''
Calculate instantaneous frequency using continuous wavelet transfer
wavelet specified in self.wavelet. See PyWavelets CWT documentation
Parameters
----------
Optimize : bool, optionals
Currently placeholder for iteratively determining wavelet scales
'''
# wavlist = pywt.wavelist(kind='continuous')
# w0, wavelet_increment, cwt_scale = self.__get_cwt__()
# determine if scales will capture the relevant frequency
if not f_center:
f_center = self.drive_freq
dt = 1 / self.sampling_rate
sc = pywt.scale2frequency(self.wavelet, self.scales) / dt
if self.verbose:
print('Wavelet scale from', np.min(sc), 'to', np.max(sc))
if f_center < np.min(sc) or f_center > np.max(sc):
raise ValueError('Choose a scale that captures frequency of interest')
if optimize:
print('!')
drive_bin = self.scales[np.searchsorted(sc, f_center)]
hi = int(1.2 * drive_bin)
lo = int(0.8 * drive_bin)
self.scales = np.arange(hi, lo, -0.1)
spectrogram, freq = pywt.cwt(self.signal, self.scales, self.wavelet, sampling_period=dt)
if not fit:
inst_freq, amplitude, _ = parab.ridge_finder(np.abs(spectrogram), np.arange(len(freq)))
# slow serial curve fitting
else:
inst_freq = np.zeros(self.n_points)
amplitude = np.zeros(self.n_points)
for c in range(spectrogram.shape[1]):
SIG = spectrogram[:, c]
if fit:
pk = np.argmax(np.abs(SIG))
popt = np.polyfit(np.arange(20),
np.abs(SIG[pk - 10:pk + 10]), 2)
inst_freq[c] = -0.5 * popt[1] / popt[0]
amplitude[c] = np.abs(SIG)[pk]
# rescale to correct frequency
inst_freq = pywt.scale2frequency(self.wavelet, inst_freq + self.scales[0]) / dt
phase = spg.cumtrapz(inst_freq)
phase = np.append(phase, phase[-1])
tidx = int(self.tidx * len(inst_freq) / self.n_points)
self.amplitude = amplitude
self.inst_freq_raw = inst_freq
self.inst_freq = -1 * (inst_freq - inst_freq[tidx]) # -1 due to way scales are ordered
self.spectrogram = np.abs(spectrogram)
self.wavelet_freq = freq # the wavelet frequencies
# subtract the w*t line (drive frequency line) from phase
start = int(0.3 * tidx)
end = int(0.7 * tidx)
xfit = np.polyfit(np.arange(start, end), phase[start:end], 1)
phase -= (xfit[0] * np.arange(len(inst_freq))) + xfit[1]
self.phase = phase
return
def calculate_stft(self, time_res=20e-6, nfft=200):
'''
Sliding FFT approach
Parameters
----------
time_res : float, optional
What timescale to evaluate each FFT over
fit : bool, optional
Fits a parabola to the frequency peak to get the actual frequency
Otherwise defaults to parabolic interpolation (see parab.fit)
nfft : int
Length of FFT calculated in the spectrogram. More points gets much slower
but the longer the FFT the finer the frequency bin spacing
'''
pts_per_ncycle = int(time_res * self.sampling_rate)
if nfft < pts_per_ncycle:
print('Error with nfft setting')
nfft = pts_per_ncycle
# drivebin = int(self.drive_freq / (self.sampling_rate / nfft ))
freq, times, spectrogram = sps.spectrogram(self.signal,
self.sampling_rate,
nperseg=pts_per_ncycle,
noverlap=pts_per_ncycle - 1,
nfft=nfft,
window=self.window,
mode='magnitude')
# Parabolic ridge finder
inst_freq, amplitude, _ = parab.ridge_finder(spectrogram, freq)
# Correctly pad the signals
_pts = self.n_points - len(inst_freq)
_pre = int(np.floor(_pts / 2))
_post = int(np.ceil(_pts / 2))
inst_freq = np.pad(inst_freq, (_pre, _post))
amplitude = np.pad(amplitude, (_pre, _post))
phase = spg.cumtrapz(inst_freq)
phase = np.append(phase, phase[-1])
tidx = int(self.tidx * len(inst_freq) / self.n_points)
self.amplitude = amplitude
self.inst_freq_raw = inst_freq
self.inst_freq = inst_freq - inst_freq[tidx]
self.spectrogram = spectrogram
self.stft_freq = freq
self.stft_times = times
# subtract the w*t line (drive frequency line) from phase
start = int(0.3 * tidx)
end = int(0.7 * tidx)
xfit = np.polyfit(np.arange(start, end), phase[start:end], 1)
phase -= (xfit[0] * np.arange(len(inst_freq))) + xfit[1]
self.phase = phase
return
def plot(self, newplot=True, raw=False):
"""
Quick visualization of best_fit and cut.
Parameters
----------
newplot : bool, optional
generates a new plot (True) or plots on existing plot figure (False)
raw : bool, optional
"""
if newplot:
fig, a = plt.subplots(nrows=3, figsize=(6, 9), facecolor='white')
dt = 1 / self.sampling_rate
ridx = int(self.roi * self.sampling_rate)
fidx = int(self.tidx)
cut = self.amplitude[fidx:(fidx + ridx)]
cut = [fidx, (fidx + ridx)]
tx = np.arange(cut[0], cut[1]) * dt
a[0].plot(tx * 1e3, self.inst_freq[cut[0]:cut[1]], 'r-')
if self.fit_form == 'ringdown':
a[1].plot(tx * 1e3, self.best_fit, 'g--')
else:
a[0].plot(tx * 1e3, self.best_fit, 'g--')
a[1].plot(tx * 1e3, self.amplitude[cut[0]:cut[1]], 'b')
a[2].plot(tx * 1e3, self.phase[cut[0]:cut[1]] * 180 / np.pi, 'm')
a[0].set_title('Instantaneous Frequency')
a[0].set_ylabel('Frequency Shift (Hz)')
a[1].set_ylabel('Amplitude (nm)')
a[2].set_ylabel('Phase (deg)')
a[2].set_xlabel('Time (ms)')
plt.tight_layout()
return
def generate_inst_freq(self, timing=False):
"""
Generates the instantaneous frequency
Parameters
----------
timing : bool, optional
prints the time to execute (for debugging)
Returns
-------
inst_freq : (n_points,) array_like
Instantaneous frequency of the signal.
"""
if timing:
t1 = time.time()
# Remove DC component, first.
# self.remove_dc()
# Phase-lock signals.
# self.phase_lock()
# Average signals.
self.average()
# Remove DC component again, introduced by phase-locking.
# self.remove_dc()
# Check the drive frequency.
if self.check_drive:
self.check_drive_freq()
# DWT Denoise
# self.dwt_denoise()
if self.method == 'wavelet':
# Calculate instantenous frequency using wavelet transform.
self.calculate_cwt(**self.wavelet_params)
elif self.method == 'stft':
# Calculate instantenous frequency using sliding FFT
self.calculate_stft(**self.fft_params)
elif self.method == 'hilbert':
# Hilbert transform method
# Apply window.
if self.window != 0:
self.apply_window()
# Filter the signal with a filter, if wanted.
if self.bandpass_filter == 1:
self.fir_filter()
elif self.bandpass_filter == 2:
self.iir_filter()
# Get the analytical signal doing a Hilbert transform.
self.hilbert()
# Filter out oscillatory noise from amplitude
if self.filter_amplitude:
self.amplitude_filter()
else:
raise ValueError('Invalid analysis method! Valid options: hilbert, wavelet, fft')
if timing:
print('Time:', time.time() - t1, 's')
# Filter out oscillatory noise from instantaneous frequency
if self.filter_frequency:
self.frequency_filter()
return self.inst_freq, self.amplitude, self.phase
def analyze(self):
"""
Analyzes the pixel with the given method.
Returns
-------
tfp : float
Time from trigger to first-peak, in seconds.
shift : float
Frequency shift from trigger to first-peak, in Hz.
inst_freq : (n_points,) array_like
Instantenous frequency of the signal.
"""
self.inst_freq, self.amplitude, self.phase = self.generate_inst_freq()
# If it's a recombination image invert it to find minimum.
if self.recombination:
self.inst_freq = self.inst_freq * -1
# Find where the minimum is.
self.find_tfp()
# Restore the length due to FIR filter being causal
if self.method == 'hilbert':
self.restore_signal()
# If it's a recombination image invert it to find minimum.
if self.recombination:
self.inst_freq = self.inst_freq * -1
self.best_fit = self.best_fit * -1
self.cut = self.cut * -1
if self.phase_fitting:
return self.tfp, self.shift, self.phase
else:
return self.tfp, self.shift, self.inst_freq
<file_sep>/ffta/gkpfm/transfer_func.py
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 19 12:10:38 2019
@author: Raj
"""
import pyUSID as usid
from pyUSID.io.write_utils import Dimension
from igor import binarywave as bw
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from scipy import signal as sg
import ffta
import time
from pycroscopy.processing.fft import get_noise_floor
def transfer_function(h5_file, tf_file='', params_file='',
psd_freq=1e6, offset=0.0016, sample_freq=10e6,
plot=False):
'''
Reads in the transfer function .ibw, then creates two datasets within
a parent folder 'Transfer_Function'
This will destructively overwrite an existing Transfer Function in there
1) TF (transfer function)
2) Freq (frequency axis for computing Fourier Transforms)
Parameters
----------
tf_file : ibw
Transfer Function .ibw File
params_file : string
The filepath in string format for the parameters file containing
Q, AMPINVOLS, etc.
psd_freq : float
The maximum range of the Power Spectral Density.
For Asylum Thermal Tunes, this is often 1 MHz on MFPs and 2 MHz on Cyphers
offset : float
To avoid divide-by-zero effects since we will divide by the transfer function
when generating GKPFM data
sample_freq : float
The desired output sampling. This should match your data.
Returns
-------
h5_file['Transfer_Function'] : the Transfer Function group
'''
if not any(tf_file):
tf_file = usid.io_utils.file_dialog(caption='Select Transfer Function file ',
file_filter='IBW Files (*.ibw)')
data = bw.load(tf_file)
tf = data.get('wave').get('wData')
if 'Transfer_Function' in h5_file:
del h5_file['/Transfer_Function']
h5_file.create_group('Transfer_Function')
h5_file['Transfer_Function'].create_dataset('TF', data=tf)
freq = np.linspace(0, psd_freq, len(tf))
h5_file['Transfer_Function'].create_dataset('Freq', data=freq)
parms = params_list(params_file, psd_freq=psd_freq)
for k in parms:
h5_file['Transfer_Function'].attrs[k] = float(parms[k])
tfnorm = float(parms['Q']) * (tf - np.min(tf)) / (np.max(tf) - np.min(tf))
tfnorm += offset
h5_file['Transfer_Function'].create_dataset('TFnorm', data=tfnorm)
TFN_RS, FQ_RS = resample_tf(h5_file, psd_freq=psd_freq, sample_freq=sample_freq)
TFN_RS = float(parms['Q']) * (TFN_RS - np.min(TFN_RS)) / (np.max(TFN_RS) - np.min(TFN_RS))
TFN_RS += offset
h5_file['Transfer_Function'].create_dataset('TFnorm_resampled', data=TFN_RS)
h5_file['Transfer_Function'].create_dataset('Freq_resampled', data=FQ_RS)
if plot:
plt.figure()
plt.plot(freq, tfnorm, 'b')
plt.plot(FQ_RS, TFN_RS, 'r')
plt.xlabel('Frequency (Hz)')
plt.ylabel('Amplitude (m)')
plt.yscale('log')
plt.title('Transfer Function')
return h5_file['Transfer_Function']
def resample_tf(h5_file, psd_freq=1e6, sample_freq=10e6):
'''
Resamples the Transfer Function based on the desired target frequency
This is important for dividing the transfer function elements together
Parameters
----------
psd_freq : float
The maximum range of the Power Spectral Density.
For Asylum Thermal Tunes, this is often 1 MHz on MFPs and 2 MHz on Cyphers
sample_freq : float
The desired output sampling. This should match your data.
'''
TFN = h5_file['Transfer_Function/TFnorm'][()]
# FQ = h5_file['Transfer_Function/Freq'][()]
# Generate the iFFT from the thermal tune data
tfn = np.fft.ifft(TFN)
# tq = np.linspace(0, 1/np.abs(FQ[1] - FQ[0]), len(tfn))
# Resample
scale = int(sample_freq / psd_freq)
print('Rescaling by', scale, 'X')
tfn_rs = sg.resample(tfn, len(tfn) * scale) # from 1 MHz to 10 MHz
TFN_RS = np.fft.fft(tfn_rs)
FQ_RS = np.linspace(0, sample_freq, len(tfn_rs))
return TFN_RS, FQ_RS
def params_list(path='', psd_freq=1e6, lift=50):
'''
Reads in a Parameters file as saved in Igor as a dictionary
For use in creating attributes of transfer Function
'''
if not any(path):
path = usid.io.io_utils.file_dialog(caption='Select Parameters Files ',
file_filter='Text (*.txt)')
df = pd.read_csv(path, sep='\t', header=1)
df = df.set_index(df['Unnamed: 0'])
df = df.drop(columns='Unnamed: 0')
parm_dict = df.to_dict()['Initial']
parm_dict['PSDFreq'] = psd_freq
parm_dict['Lift'] = lift
return parm_dict
def test_Ycalc(h5_main, pixel_ind=[0, 0], transfer_func=None, resampled=True, ratios=None,
verbose=True, noise_floor=1e-3, phase=-np.pi, plot=False, scaling=1):
'''
Divides the response by the transfer function
Parameters
----------
h5_main : h5py dataset of USIDataset
tf : transfer function, optional
This can be the resampled or normal transfer function
For best results, use the "normalized" transfer function
"None" will default to /Transfer_Function folder
resampled : bool, optional
Whether to use the upsampled Transfer Function or the original
verbose: bool, optional
Gives user feedback during processing
noise_floor : float, optional
For calculating what values to filter as the noise floor of the data
0 or None circumvents this
phase : float, optional
Practically any value between -pi and +pi works
scaling : int, optional
scales the transfer function by this number if, for example, the TF was
acquired on a line and you're dividing by a point (or vice versa)'
'''
t0 = time.time()
parm_dict = usid.hdf_utils.get_attributes(h5_main)
drive_freq = parm_dict['drive_freq']
response = ffta.hdf_utils.get_utils.get_pixel(h5_main, pixel_ind, array_form=True, transpose=False).flatten()
response -= np.mean(response)
RESP = np.fft.fft(response)
Yout = np.zeros(len(RESP), dtype=complex)
# Create frequency axis for the pixel
samp = parm_dict['sampling_rate']
fq_y = np.linspace(0, samp, len(Yout))
noise_limit = np.ceil(get_noise_floor(RESP, noise_floor)[0])
# Get the transfer function and transfer function frequency values
fq_tf = h5_main.file['Transfer_Function/Freq'][()]
if not transfer_func:
if resampled:
transfer_func = h5_main.file['Transfer_Function/TFnorm_resampled'][()]
fq_tf = h5_main.file['Transfer_Function/Freq_resampled'][()]
else:
transfer_func = h5_main.file['Transfer_Function/TFnorm'][()]
if verbose:
t1 = time.time()
print('Time for pixels:', t1 - t0)
Yout_divided = np.zeros(len(RESP), dtype=bool)
TFratios = np.ones(len(RESP))
# Calculate the TF scaled to the sample size of response function
for x, f in zip(transfer_func, fq_tf):
if np.abs(x) > noise_floor:
xx = np.searchsorted(fq_y, f)
if not Yout_divided[xx]:
TFratios[xx] = x
TFratios[-xx] = x
Yout_divided[xx] = True
signal_bins = np.arange(len(TFratios))
signal_kill = np.where(np.abs(RESP) < noise_limit)
pass_frequencies = np.delete(signal_bins, signal_kill)
drive_bin = (np.abs(fq_y - drive_freq)).argmin()
RESP_ph = (RESP) * np.exp(-1j * fq_y / (fq_y[drive_bin]) * phase)
# Step 3C) iFFT the response above a user defined noise floor to recover Force in time domain.
Yout[pass_frequencies] = RESP_ph[pass_frequencies]
Yout = Yout / (TFratios * scaling)
yout = np.real(np.fft.ifft(np.fft.ifftshift(Yout)))
if verbose:
t2 = time.time()
print('Time for pixels:', t2 - t1)
if plot:
fig, ax = plt.subplots(figsize=(12, 7))
ax.semilogy(fq_y, np.abs(Yout), 'b', label='F3R')
ax.semilogy(fq_y[signal_bins], np.abs(Yout[signal_bins]), 'og', label='F3R')
ax.semilogy(fq_y[signal_bins], np.abs(RESP[signal_bins]), '.r', label='Response')
ax.set_xlabel('Frequency (kHz)', fontsize=16)
ax.set_ylabel('Amplitude (a.u.)', fontsize=16)
ax.legend(fontsize=14)
ax.set_yscale('log')
ax.set_xlim(0, 3 * drive_freq)
ax.set_title('Noise Spectrum', fontsize=16)
return TFratios, Yout, yout
def Y_calc(h5_main, transfer_func=None, resampled=True, ratios=None, verbose=False,
noise_floor=1e-3, phase=-np.pi, plot=False, scaling=1):
'''
Divides the response by the transfer function
Parameters
----------
h5_main : h5py dataset of USIDataset
tf : transfer function, optional
This can be supplied or use the calculated version
For best results, use the "normalized" transfer function
"None" will default to /Transfer_Function folder
resampled : bool, optional
Whether to use the upsampled Transfer Function or the original
verbose: bool, optional
Gives user feedback during processing
ratios : array, optional
Array of the size of h5_main (1-D) with the transfer function data
If not given, it's found via the test_Y_calc function
noise_floor : float, optional
For calculating what values to filter as the noise floor of the data
0 or None circumvents this
phase : float, optional
Practically any value between -pi and +pi works
scaling : int, optional
scales the transfer function by this number if, for example, the TF was
acquired on a line and you're dividing by a point (or vice versa)'
'''
parm_dict = usid.hdf_utils.get_attributes(h5_main)
drive_freq = parm_dict['drive_freq']
ds = h5_main[()]
Yout = np.zeros(ds.shape, dtype=complex)
yout = np.zeros(ds.shape)
# Create frequency axis for the pixel
samp = parm_dict['sampling_rate']
fq_y = np.linspace(0, samp, Yout.shape[1])
response = ds[0, :]
response -= np.mean(response)
RESP = np.fft.fft(response)
noise_limit = np.ceil(get_noise_floor(RESP, noise_floor)[0])
# Get the transfer function and transfer function frequency values
# Use test calc to scale the transfer function to the correct size
if not transfer_func:
if resampled:
transfer_func, _, _ = test_Ycalc(h5_main, resampled=True,
verbose=verbose, noise_floor=noise_floor)
else:
transfer_func, _, _ = test_Ycalc(h5_main, resampled=False,
verbose=verbose, noise_floor=noise_floor)
import time
t0 = time.time()
signal_bins = np.arange(len(transfer_func))
for c in np.arange(h5_main.shape[0]):
if verbose:
if c % 100 == 0:
print('Pixel:', c)
response = ds[c, :]
response -= np.mean(response)
RESP = np.fft.fft(response)
signal_kill = np.where(np.abs(RESP) < noise_limit)
pass_frequencies = np.delete(signal_bins, signal_kill)
drive_bin = (np.abs(fq_y - drive_freq)).argmin()
RESP_ph = (RESP) * np.exp(-1j * fq_y / (fq_y[drive_bin]) * phase)
Yout[c, pass_frequencies] = RESP_ph[pass_frequencies]
Yout[c, :] = Yout[c, :] / (transfer_func * scaling)
yout[c, :] = np.real(np.fft.ifft(Yout[c, :]))
t1 = time.time()
print('Time for pixels:', t1 - t0)
return Yout, yout
def check_phase(h5_main, transfer_func, phase_list=[-np.pi, -np.pi / 2, 0],
plot=True, noise_tolerance=1e-6, samp_rate=10e6):
'''
Uses the list of phases in phase_list to plot the various phase offsets
relative to the driving excitation
'''
ph = -3.492 # phase from cable delays between excitation and response
row_ind = 0
test_row = np.fft.fftshift(np.fft.fft(h5_main[row_ind]))
noise_floor = get_noise_floor(test_row, noise_tolerance)[0]
print('Noise floor = ', noise_floor)
Noiselimit = np.ceil(noise_floor)
parm_dict = usid.hdf_utils.get_attributes(h5_main)
drive_freq = parm_dict['drive_freq']
freq = np.arange(-samp_rate / 2, samp_rate / 2, samp_rate / len(test_row))
tx = np.arange(0, parm_dict['total_time'], parm_dict['total_time'] / len(freq))
exc_params = {'ac': 1, 'dc': 0, 'phase': 0, 'frequency': drive_freq}
exc_params['ac']
excitation = (exc_params['ac'] * np.sin(tx * 2 * np.pi * exc_params['frequency'] \
+ exc_params['phase']) + exc_params['dc'])
for ph in phase_list:
# Try Force Conversion on Filtered data of single line (row_ind above)
G_line = np.zeros(freq.size, dtype=complex) # G = raw
G_wPhase_line = np.zeros(freq.size, dtype=complex) # G_wphase = phase-shifted
signal_ind_vec = np.arange(freq.size)
ind_drive = (np.abs(freq - drive_freq)).argmin()
# filt_line is from filtered data above
test_line = test_row - np.mean(test_row)
test_line = np.fft.fftshift(np.fft.fft(test_line))
signal_kill = np.where(np.abs(test_line) < Noiselimit)
signal_ind_vec = np.delete(signal_ind_vec, signal_kill)
# Original/raw data; TF_norm is from the Tune file transfer function
G_line[signal_ind_vec] = test_line[signal_ind_vec]
G_line = (G_line / transfer_func)
G_time_line = np.real(np.fft.ifft(np.fft.ifftshift(G_line))) # time-domain
# Phase-shifted data
test_shifted = (test_line) * np.exp(-1j * freq / (freq[ind_drive]) * ph)
G_wPhase_line[signal_ind_vec] = test_shifted[signal_ind_vec]
G_wPhase_line = (G_wPhase_line / transfer_func)
G_wPhase_time_line = np.real(np.fft.ifft(np.fft.ifftshift(G_wPhase_line)))
phaseshifted = np.reshape(G_wPhase_time_line, (parm_dict['num_cols'], parm_dict['num_rows']))
fig, axes = usid.plot_utils.plot_curves(excitation, phaseshifted, use_rainbow_plots=True,
x_label='Voltage (Vac)', title='Phase Shifted',
num_plots=4, y_label='Deflection (a.u.)')
axes[0][0].set_title('Phase ' + str(ph))
return
def save_Yout(h5_main, Yout, yout):
'''
Writes the results to teh HDF5 file
'''
parm_dict = usid.hdf_utils.get_attributes(h5_main)
# Get relevant parameters
num_rows = parm_dict['num_rows']
num_cols = parm_dict['num_cols']
pnts_per_avg = parm_dict['pnts_per_avg']
h5_gp = h5_main.parent
h5_meas_group = usid.hdf_utils.create_indexed_group(h5_gp, 'GKPFM_Frequency')
# Create dimensions
pos_desc = [Dimension('X', 'm', np.linspace(0, parm_dict['FastScanSize'], num_cols)),
Dimension('Y', 'm', np.linspace(0, parm_dict['SlowScanSize'], num_rows))]
# ds_pos_ind, ds_pos_val = build_ind_val_matrices(pos_desc, is_spectral=False)
spec_desc = [Dimension('Frequency', 'Hz', np.linspace(0, parm_dict['sampling_rate'], pnts_per_avg))]
# ds_spec_inds, ds_spec_vals = build_ind_val_matrices(spec_desc, is_spectral=True)
# Writes main dataset
h5_y = usid.hdf_utils.write_main_dataset(h5_meas_group,
Yout,
'Y', # Name of main dataset
'Deflection', # Physical quantity contained in Main dataset
'V', # Units for the physical quantity
pos_desc, # Position dimensions
spec_desc, # Spectroscopic dimensions
dtype=np.cdouble, # data type / precision
main_dset_attrs=parm_dict)
usid.hdf_utils.copy_attributes(h5_y, h5_gp)
h5_meas_group = usid.hdf_utils.create_indexed_group(h5_gp, 'GKPFM_Time')
spec_desc = [Dimension('Time', 's', np.linspace(0, parm_dict['total_time'], pnts_per_avg))]
h5_y = usid.hdf_utils.write_main_dataset(h5_meas_group,
yout,
'y_time', # Name of main dataset
'Deflection', # Physical quantity contained in Main dataset
'V', # Units for the physical quantity
pos_desc, # Position dimensions
spec_desc, # Spectroscopic dimensions
dtype=np.float32, # data type / precision
main_dset_attrs=parm_dict)
usid.hdf_utils.copy_attributes(h5_y, h5_gp)
h5_y.file.flush()
return
def check_response(h5_main, pixel=0, ph=0):
parm_dict = usid.hdf_utils.get_attributes(h5_main)
freq = parm_dict['drive_freq']
txl = np.linspace(0, parm_dict['total_time'], h5_main[pixel, :].shape[0])
resp_wfm = np.sin(txl * 2 * np.pi * freq + ph)
plt.figure()
plt.plot(resp_wfm, h5_main[()][pixel, :])
return
<file_sep>/ffta/hdf_utils/process.py
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 11 18:07:06 2020
@author: Raj
"""
import pyUSID as usid
import ffta
from ffta.pixel import Pixel
from ffta.pixel_utils import badpixels
import os
import numpy as np
from ffta.load import get_utils
from pyUSID.processing.comp_utils import parallel_compute
from pyUSID.io.write_utils import Dimension
import h5py
from matplotlib import pyplot as plt
class FFtrEFM(usid.Process):
"""
Implements the pixel-by-pixel processing using ffta.pixel routines
Abstracted using the Process class for parallel processing
Example usage:
>> from ffta.hdf_utils import process
>> data = process.FFtrEFM(h5_main)
>> data.test([1,2]) # tests on pixel 1,2 in row, column
>> data.compute()
>> data.reshape() # reshapes the tFP, shift data
>> process.save_CSV_from_file(data.h5_main.file, data.h5_results_grp.name)
>> process.plot_tfp(data)
To reload old data:
>> data = FFtrEFM()
>> data._get_existing_datasets()
"""
def __init__(self, h5_main, parm_dict={}, can_params={},
pixel_params={}, if_only=False, override=False, process_name='Fast_Free',
**kwargs):
"""
Parameters
----------
h5_main : h5py.Dataset object
Dataset to process
if_only : bool, optional
If True, only calculates the instantaneous frequency and not tfp/shift
parm_dict : dict, optional
Additional updates to the parameters dictionary. e.g. changing the trigger.
You can also explicitly update self.parm_dict.update({'key': value})
can_params : dict, optional
Cantilever parameters describing the behavior
Can be loaded from ffta.pixel_utils.load.cantilever_params
pixel_params : dict, optional
Pixel class accepts the following:
fit: bool, (default: True)
Whether to fit the frequency data or use derivative.
pycroscopy: bool (default: False)
Usually does not need to change. This parameter is because of
how Pycroscopy stores a matrix compared to original numpy ffta approach
method: str (default: 'hilbert')
Method for generating instantaneous frequency, amplitude, and phase response
One of
hilbert: Hilbert transform method (default)
wavelet: Morlet CWT approach
emd: Hilbert-Huang decomposition
fft: sliding FFT approach
fit_form: str (default: 'product')
filter_amp : bool (default: False)
Whether to filter the amplitude signal around DC (to remove drive sine artifact)
override : bool, optional
If True, forces creation of new results group. Use in _get_existing_datasets
kwargs : dictionary or variable
Keyword pairs to pass to Process constructor
"""
self.parm_dict = parm_dict
self.parm_dict['if_only'] = if_only
if not any(parm_dict):
self.parm_dict = usid.hdf_utils.get_attributes(h5_main)
self.parm_dict.update({'if_only': if_only})
for key, val in parm_dict.items():
self.parm_dict.update({key: val})
if any(can_params):
if 'Initial' in can_params: # only care about the initial conditions
for key, val in can_params['Initial'].items():
self.parm_dict.update({key: val})
else:
for key, val in can_params.items():
self.parm_dict.update({key: val})
self.pixel_params = pixel_params
self.override = override
super(FFtrEFM, self).__init__(h5_main, process_name, parms_dict=self.parm_dict, **kwargs)
# For accidental passing ancillary datasets from Pycroscopy, this will fail
# when pickling
if hasattr(self, 'Position_Indices'):
del self.Position_Indices
if hasattr(self, 'Position_Values'):
del self.Position_Values
if hasattr(self, 'Spectroscopic_Indices'):
del self.Spectroscopic_Indices
if hasattr(self, 'Spectroscopic_Values'):
del self.Spectroscopic_Values
if 'Position_Indices' in self.parm_dict:
del self.parm_dict['Position_Indices']
if 'Position_Values' in self.parm_dict:
del self.parm_dict['Position_Values']
if 'Spectroscopic_Indices' in self.parm_dict:
del self.parm_dict['Spectroscopic_Indices']
if 'Spectroscopic_Values' in self.parm_dict:
del self.parm_dict['Spectroscopic_Values']
return
def update_parm(self, **kwargs):
"""
Update the parameters, see ffta.pixel.Pixel for details on what to update
e.g. to switch from default Hilbert to Wavelets, for example
"""
self.parm_dict.update(kwargs)
return
def test(self, pixel_ind=[0, 0]):
"""
Test the Pixel analysis of a single pixel
Parameters
----------
pixel_ind : uint or list
Index of the pixel in the dataset that the process needs to be tested on.
If a list it is read as [row, column]
Returns
-------
[inst_freq, tfp, shift] : List
inst_freq : array
the instantaneous frequency array for that pixel
tfp : float
the time to first peak
shift : float
the frequency shift at time t=tfp (i.e. maximum frequency shift)
"""
# First read the HDF5 dataset to get the deflection for this pixel
if type(pixel_ind) is not list:
col = int(pixel_ind % self.parm_dict['num_rows'])
row = int(np.floor(pixel_ind % self.parm_dict['num_rows']))
pixel_ind = [row, col]
# as an array, not an ffta.Pixel
defl = get_utils.get_pixel(self.h5_main, pixel_ind, array_form=True)
pix = Pixel(defl, self.parm_dict, **self.pixel_params)
tfp, shift, inst_freq = pix.analyze()
pix.plot()
return self._map_function(defl, self.parm_dict, self.pixel_params)
def _create_results_datasets(self):
'''
Creates the datasets an Groups necessary to store the results.
Parameters
----------
h5_if : 'Inst_Freq' h5 Dataset
Contains the Instantaneous Frequencies
tfp : 'tfp' h5 Dataset
Contains the time-to-first-peak data as a 1D matrix
shift : 'shift' h5 Dataset
Contains the frequency shift data as a 1D matrix
'''
print('Creating results datasets')
# Get relevant parameters
num_rows = self.parm_dict['num_rows']
num_cols = self.parm_dict['num_cols']
pnts_per_avg = self.parm_dict['pnts_per_avg']
ds_shape = [num_rows * num_cols, pnts_per_avg]
self.h5_results_grp = usid.hdf_utils.create_results_group(self.h5_main, self.process_name)
# h5_meas_group = usid.hdf_utils.create_indexed_group(self.h5_main.parent, self.process_name)
usid.hdf_utils.copy_attributes(self.h5_main.parent, self.h5_results_grp)
# Create dimensions
pos_desc = [Dimension('X', 'm', np.linspace(0, self.parm_dict['FastScanSize'], num_cols)),
Dimension('Y', 'm', np.linspace(0, self.parm_dict['SlowScanSize'], num_rows))]
# ds_pos_ind, ds_pos_val = build_ind_val_matrices(pos_desc, is_spectral=False)
spec_desc = [Dimension('Time', 's', np.linspace(0, self.parm_dict['total_time'], pnts_per_avg))]
# ds_spec_inds, ds_spec_vals = build_ind_val_matrices(spec_desc, is_spectral=True)
# Writes main dataset
self.h5_if = usid.hdf_utils.write_main_dataset(self.h5_results_grp,
ds_shape,
'Inst_Freq', # Name of main dataset
'Frequency', # Physical quantity contained in Main dataset
'Hz', # Units for the physical quantity
pos_desc, # Position dimensions
spec_desc, # Spectroscopic dimensions
dtype=np.float32, # data type / precision
main_dset_attrs=self.parm_dict)
self.h5_amp = usid.hdf_utils.write_main_dataset(self.h5_results_grp,
ds_shape,
'Amplitude', # Name of main dataset
'Amplitude', # Physical quantity contained in Main dataset
'nm', # Units for the physical quantity
None, # Position dimensions
None, # Spectroscopic dimensions
h5_pos_inds=self.h5_main.h5_pos_inds, # Copy Pos Dimensions
h5_pos_vals=self.h5_main.h5_pos_vals,
h5_spec_inds=self.h5_main.h5_spec_inds,
# Copy Spectroscopy Dimensions
h5_spec_vals=self.h5_main.h5_spec_vals,
dtype=np.float32, # data type / precision
main_dset_attrs=self.parm_dict)
self.h5_phase = usid.hdf_utils.write_main_dataset(self.h5_results_grp,
ds_shape,
'Phase', # Name of main dataset
'Phase', # Physical quantity contained in Main dataset
'degrees', # Units for the physical quantity
None, # Position dimensions
None, # Spectroscopic dimensions
h5_pos_inds=self.h5_main.h5_pos_inds, # Copy Pos Dimensions
h5_pos_vals=self.h5_main.h5_pos_vals,
h5_spec_inds=self.h5_main.h5_spec_inds,
# Copy Spectroscopy Dimensions
h5_spec_vals=self.h5_main.h5_spec_vals,
dtype=np.float32, # data type / precision
main_dset_attrs=self.parm_dict)
self.h5_pwrdis = usid.hdf_utils.write_main_dataset(self.h5_results_grp,
ds_shape,
'PowerDissipation', # Name of main dataset
'Power', # Physical quantity contained in Main dataset
'W', # Units for the physical quantity
None, # Position dimensions
None, # Spectroscopic dimensions
h5_pos_inds=self.h5_main.h5_pos_inds, # Copy Pos Dimensions
h5_pos_vals=self.h5_main.h5_pos_vals,
h5_spec_inds=self.h5_main.h5_spec_inds,
# Copy Spectroscopy Dimensions
h5_spec_vals=self.h5_main.h5_spec_vals,
dtype=np.float32, # data type / precision
main_dset_attrs=self.parm_dict)
_arr = np.zeros([num_rows * num_cols, 1])
self.h5_tfp = self.h5_results_grp.create_dataset('tfp', data=_arr, dtype=np.float32)
self.h5_shift = self.h5_results_grp.create_dataset('shift', data=_arr, dtype=np.float32)
self.h5_if.file.flush()
return
def reshape(self):
'''
Reshapes the tFP and shift data to be a matrix, then saves that dataset instead of the 1D
'''
h5_tfp = self.h5_tfp[()]
h5_shift = self.h5_shift[()]
num_rows = self.parm_dict['num_rows']
num_cols = self.parm_dict['num_cols']
h5_tfp = np.reshape(h5_tfp, [num_rows, num_cols])
h5_shift = np.reshape(h5_shift, [num_rows, num_cols])
del self.h5_tfp.file[self.h5_tfp.name]
del self.h5_tfp.file[self.h5_shift.name]
self.h5_tfp = self.h5_results_grp.create_dataset('tfp', data=h5_tfp, dtype=np.float32)
self.h5_shift = self.h5_results_grp.create_dataset('shift', data=h5_shift, dtype=np.float32)
return
def _write_results_chunk(self):
'''
Write the computed results back to the H5
In this case, there isn't any more additional post-processing required
'''
# Find out the positions to write to:
pos_in_batch = self._get_pixels_in_current_batch()
# unflatten the list of results, which are [inst_freq array, amp, phase, tfp, shift]
_results = np.array([j for i in self._results for j in i[:1]])
_amp = np.array([j for i in self._results for j in i[1:2]])
_phase = np.array([j for i in self._results for j in i[2:3]])
_tfp = np.array([j for i in self._results for j in i[3:4]])
_shift = np.array([j for i in self._results for j in i[4:5]])
_pwr = np.array([j for i in self._results for j in i[5:]])
# write the results to the file
self.h5_if[pos_in_batch, :] = _results
self.h5_amp[pos_in_batch, :] = _amp
self.h5_pwrdis[pos_in_batch, :] = _pwr
self.h5_phase[pos_in_batch, :] = _phase
self.h5_tfp[pos_in_batch, 0] = _tfp
self.h5_shift[pos_in_batch, 0] = _shift
return
def _get_existing_datasets(self, index=-1):
"""
Extracts references to the existing datasets that hold the results
index = which existing dataset to get
"""
if not self.override:
self.h5_results_grp = usid.hdf_utils.find_dataset(self.h5_main.parent, 'Inst_Freq')[index].parent
self.h5_new_spec_vals = self.h5_results_grp['Spectroscopic_Values']
self.h5_tfp = self.h5_results_grp['tfp']
self.h5_shift = self.h5_results_grp['shift']
self.h5_if = self.h5_results_grp['Inst_Freq']
self.h5_amp = self.h5_results_grp['Amplitude']
self.h5_phase = self.h5_results_grp['Phase']
try:
self.h5_pwrdis = self.h5_results_grp['PowerDissipation']
except:
pass
return
def _unit_computation(self, *args, **kwargs):
"""
The unit computation that is performed per data chunk. This allows room for any data pre / post-processing
as well as multiple calls to parallel_compute if necessary
"""
# TODO: Try to use the functools.partials to preconfigure the map function
# cores = number of processes / rank here
args = [self.parm_dict, self.pixel_params]
if self.verbose and self.mpi_rank == 0:
print("Rank {} at Process class' default _unit_computation() that "
"will call parallel_compute()".format(self.mpi_rank))
self._results = parallel_compute(self.data, self._map_function, cores=self._cores,
lengthy_computation=False,
func_args=args, func_kwargs=kwargs,
verbose=self.verbose)
@staticmethod
def _map_function(defl, *args, **kwargs):
parm_dict = args[0]
pixel_params = args[1]
pix = Pixel(defl, parm_dict, **pixel_params)
if parm_dict['if_only']:
inst_freq, _, _ = pix.generate_inst_freq()
tfp = 0
shift = 0
amplitude = 0
phase = 0
pwr_diss = 0
else:
tfp, shift, inst_freq = pix.analyze()
pix.calculate_power_dissipation()
amplitude = pix.amplitude
phase = pix.phase
pwr_diss = pix.power_dissipated
return [inst_freq, amplitude, phase, tfp, shift, pwr_diss]
def save_CSV_from_file(h5_file, h5_path='/', append='', mirror=False):
"""
Saves the tfp, shift, and fixed_tfp as CSV files
Parameters
----------
h5_file : H5Py file of FFtrEFM class
Reminder you can always type: h5_svd.file or h5_avg.file for this
h5_path : str, optional
specific folder path to search for the tfp data. Usually not needed.
append : str, optional
text to append to file name
"""
h5_ff = h5_file
if isinstance(h5_file, ffta.hdf_utils.process.FFtrEFM):
print('Saving from FFtrEFM Class')
h5_ff = h5_file.h5_main.file
h5_path = h5_file.h5_results_grp.name
elif not isinstance(h5_file, h5py.File):
print('Saving from pyUSID object')
h5_ff = h5_file.file
tfp = usid.hdf_utils.find_dataset(h5_ff[h5_path], 'tfp')[0][()]
# tfp_fixed = usid.hdf_utils.find_dataset(h5_file[h5_path], 'tfp_fixed')[0][()]
shift = usid.hdf_utils.find_dataset(h5_ff[h5_path], 'shift')[0][()]
tfp_fixed, _ = badpixels.fix_array(tfp, threshold=2)
tfp_fixed = np.array(tfp_fixed)
print(usid.hdf_utils.find_dataset(h5_ff[h5_path], 'shift')[0].parent.name)
path = h5_ff.file.filename.replace('\\', '/')
path = '/'.join(path.split('/')[:-1]) + '/'
os.chdir(path)
if mirror:
np.savetxt('tfp-' + append + '.csv', np.fliplr(tfp).T, delimiter=',')
np.savetxt('shift-' + append + '.csv', np.fliplr(shift).T, delimiter=',')
np.savetxt('tfp_fixed-' + append + '.csv', np.fliplr(tfp_fixed).T, delimiter=',')
else:
np.savetxt('tfp-' + append + '.csv', tfp.T, delimiter=',')
np.savetxt('shift-' + append + '.csv', shift.T, delimiter=',')
np.savetxt('tfp_fixed-' + append + '.csv', tfp_fixed.T, delimiter=',')
return
def plot_tfp(ffprocess, scale_tfp=1e6, scale_shift=1, threshold=2, **kwargs):
'''
Quickly plots the tfp and shift data. If there's a height image in the h5_file associated
with ffprocess, will plot that as well
Parameters
----------
ffprocess : FFtrEFM class object (inherits Process)
Returns
-------
fig, a : figure and axes objects
'''
fig, a = plt.subplots(nrows=2, ncols=2, figsize=(13, 6))
tfp_ax = a[0][1]
shift_ax = a[1][1]
img_length = ffprocess.parm_dict['FastScanSize']
img_height = ffprocess.parm_dict['SlowScanSize']
kwarg = {'origin': 'lower', 'x_vec': img_length * 1e6,
'y_vec': img_height * 1e6, 'num_ticks': 5, 'stdevs': 3, 'show_cbar': True}
for k, v in kwarg.items():
if k not in kwargs:
kwargs.update({k: v})
num_cols = ffprocess.parm_dict['num_cols']
num_rows = ffprocess.parm_dict['num_rows']
try:
ht = ffprocess.h5_main.file['/height/Raw_Data'][:, 0]
ht = np.reshape(ht, [num_cols, num_rows]).transpose()
ht_ax = a[0][0]
ht_image, cbar = usid.viz.plot_utils.plot_map(ht_ax, ht * 1e9, cmap='gray', **kwarg)
cbar.set_label('Height (nm)', rotation=270, labelpad=16)
except:
pass
tfp_ax.set_title('tFP Image')
shift_ax.set_title('Shift Image')
tfp_fixed, _ = badpixels.fix_array(ffprocess.h5_tfp[()], threshold=threshold)
tfp_image, cbar_tfp = usid.viz.plot_utils.plot_map(tfp_ax, tfp_fixed * scale_tfp,
cmap='inferno', **kwargs)
shift_image, cbar_sh = usid.viz.plot_utils.plot_map(shift_ax, ffprocess.h5_shift[()] * scale_shift,
cmap='inferno', **kwargs)
cbar_tfp.set_label('Time (us)', rotation=270, labelpad=16)
cbar_sh.set_label('Frequency Shift (Hz)', rotation=270, labelpad=16)
text = tfp_ax.text(num_cols / 2, num_rows + 3, '')
return fig, a
<file_sep>/ffta/simulation/load.py
# -*- coding: utf-8 -*-
"""
Created on Tue May 12 11:23:17 2020
@author: Raj
"""
import configparser
def simulation_configuration(path):
"""
Reads an ASCII file with relevant parameters for simulation.
Parameters
----------
path : string
Path to ASCII file.
Returns
-------
can_params : dict
Parameters for cantilever properties. The dictionary contains:
amp_invols = float (in m/V)
def_invols = float (in m/V)
soft_amp = float (in V)
drive_freq = float (in Hz)
res_freq = float (in Hz)
k = float (in N/m)
q_factor = float
force_params : dict
Parameters for forces. The dictionary contains:
es_force = float (in N)
delta_freq = float (in Hz)
tau = float (in seconds)
v_dc = float (in V)
v_ac = float (in V)
v_cpd = float (in V)
dcdz = float (in F/m)
sim_params : dict
Parameters for simulation. The dictionary contains:
trigger = float (in seconds)
total_time = float (in seconds)
sampling_rate = int (in Hz)
"""
# Create a parser for configuration file and parse it.
config = configparser.RawConfigParser()
config.read(path)
sim_params = {}
can_params = {}
force_params = {}
can_keys = ['amp_invols', 'def_invols', 'soft_amp', 'drive_freq',
'res_freq', 'k', 'q_factor']
force_keys = ['es_force', 'ac_force', 'dc_force', 'delta_freq', 'tau',
'v_dc', 'v_ac', 'v_cpd', 'dCdz', 'v_step']
sim_keys = ['trigger', 'total_time', 'sampling_rate']
for key in can_keys:
if config.has_option('Cantilever Parameters', key):
_str = config.get('Cantilever Parameters', key).split(';')
can_params[key] = float(_str[0])
for key in force_keys:
if config.has_option('Force Parameters', key):
_str = config.get('Force Parameters', key).split(';')
force_params[key] = float(_str[0])
for key in sim_keys:
if config.has_option('Simulation Parameters', key):
_str = config.get('Simulation Parameters', key).split(';')
sim_params[key] = float(_str[0])
return can_params, force_params, sim_params
<file_sep>/ffta/load/gl_ibw.py
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 21 10:06:12 2018
@author: <NAME>
"""
from __future__ import division, print_function, absolute_import, unicode_literals
from os import path # File Path formatting
import numpy as np # For array operations
from igor import binarywave as bw
# from .translator import Translator # Because this class extends the abstract Translator class
# from .utils import generate_dummy_main_parms, build_ind_val_dsets
# from ..hdf_utils import getH5DsetRefs, linkRefs
# from ..io_hdf5 import ioHDF5 # Now the translator is responsible for writing the data.
# from ..microdata import MicroDataGroup, \
# MicroDataset # The building blocks for defining hierarchical storage in the H5 file
from pyUSID.io.translator import Translator # , generate_dummy_main_parms
from pycroscopy.io.write_utils import Dimension
from pyUSID.io.hdf_utils import write_ind_val_dsets
from pyUSID.io.hdf_utils import write_main_dataset, create_indexed_group
import h5py
class GLIBWTranslator(Translator):
"""
Translates Ginger Lab Igor Binary Wave (.ibw) files containing images or force curves to .h5
"""
def translate(self, file_path, verbose=False, parm_encoding='utf-8', ftype='FF',
subfolder='Measurement_000', h5_path='', channel_label_name=True):
"""
Translates the provided file to .h5
Adapted heavily from pycroscopy IBW file, modified to work with Ginger format
Parameters
----------
file_path : String / unicode
Absolute path of the .ibw file
verbose : Boolean (Optional)
Whether or not to show print statements for debugging
parm_encoding : str, optional
Codec to be used to decode the bytestrings into Python strings if needed.
Default 'utf-8'
ftype : str, optional
Delineates Ginger Lab imaging file type to be imported (not case-sensitive)
'FF' : FF-trEFM
'SKPM' : FM-SKPM
'ringdown' : Ringdown
'trEFM' : normal trEFM
subfolder : str, optional
Specifies folder under root (/) to save data in. Default is standard pycroscopy format
h5_path : str, optional
Existing H5 file to append to
channel_label_name : bool, optional
If True, uses the Channel as the subfolder name (e.g. Height, Phase, Amplitude, Charging)
Returns
-------
h5_path : String / unicode
Absolute path of the .h5 file
"""
# Prepare the .h5 file:
if not any(h5_path):
folder_path, base_name = path.split(file_path)
base_name = base_name[:-4]
h5_path = path.join(folder_path, base_name + '.h5')
# hard-coded exception, rarely occurs but can be useful
if path.exists(h5_path):
h5_path = path.join(folder_path, base_name + '_00.h5')
h5_file = h5py.File(h5_path, 'w')
# If subfolder improperly formatted
if subfolder == '':
subfolder = '/'
# Load the ibw file first
ibw_obj = bw.load(file_path)
ibw_wave = ibw_obj.get('wave')
parm_dict = self._read_parms(ibw_wave, parm_encoding)
chan_labels, chan_units = self._get_chan_labels(ibw_wave, parm_encoding)
if verbose:
print('Channels and units found:')
print(chan_labels)
print(chan_units)
# Get the data to figure out if this is an image or a force curve
images = ibw_wave.get('wData')
if images.shape[2] != len(chan_labels):
chan_labels = chan_labels[1:] # for weird null set errors in older AR software
# Check if a Ginger Lab format ibw (has 'UserIn' in channel labels)
_is_gl_type = any(['UserIn0' in str(s) for s in chan_labels])
if _is_gl_type == True:
chan_labels = self._get_image_type(chan_labels, ftype)
if verbose:
print('Processing image type', ftype, 'with channels', chan_labels)
type_suffix = 'Image'
num_rows = ibw_wave['wave_header']['nDim'][1] # lines
num_cols = ibw_wave['wave_header']['nDim'][0] # points
num_imgs = ibw_wave['wave_header']['nDim'][2] # layers
unit_scale = self._get_unit_factor(''.join([str(s)[-2] for s in ibw_wave['wave_header']['dimUnits'][0][0:2]]))
data_scale = self._get_unit_factor(str(ibw_wave['wave_header']['dataUnits'][0])[-2])
parm_dict['FastScanSize'] = unit_scale * num_cols * ibw_wave['wave_header']['sfA'][0]
parm_dict['SlowScanSize'] = unit_scale * num_rows * ibw_wave['wave_header']['sfA'][1]
images = images.transpose(2, 0, 1) # now ordered as [chan, Y, X] image
images = np.reshape(images, (images.shape[0], -1, 1)) # 3D [chan, Y*X points,1]
pos_desc = [Dimension('X', 'm', np.linspace(0, parm_dict['FastScanSize'], num_cols)),
Dimension('Y', 'm', np.linspace(0, parm_dict['SlowScanSize'], num_rows))]
spec_desc = Dimension('arb', 'a.u.', [1])
# Create Position and spectroscopic datasets
h5_pos_inds, h5_pos_vals = write_ind_val_dsets(h5_file['/'], pos_desc, is_spectral=False)
h5_spec_inds, h5_spec_vals = write_ind_val_dsets(h5_file['/'], spec_desc, is_spectral=True)
# Prepare the list of raw_data datasets
for chan_data, chan_name, chan_unit in zip(images, chan_labels, chan_units):
chan_grp = create_indexed_group(h5_file['/'], chan_name)
write_main_dataset(chan_grp, np.atleast_2d(chan_data), 'Raw_Data',
chan_name, chan_unit,
pos_desc, spec_desc,
dtype=np.float32)
if verbose:
print('Finished writing all channels')
h5_file.close()
return h5_path
@staticmethod
def _read_parms(ibw_wave, codec='utf-8'):
"""
Parses the parameters in the provided dictionary
Parameters
----------
ibw_wave : dictionary
Wave entry in the dictionary obtained from loading the ibw file
codec : str, optional
Codec to be used to decode the bytestrings into Python strings if needed.
Default 'utf-8'
Returns
-------
parm_dict : dictionary
Dictionary containing parameters
"""
parm_string = ibw_wave.get('note')
if type(parm_string) == bytes:
try:
parm_string = parm_string.decode(codec)
except:
parm_string = parm_string.decode('ISO-8859-1')
parm_string = parm_string.rstrip('\r')
parm_list = parm_string.split('\r')
parm_dict = dict()
for pair_string in parm_list:
temp = pair_string.split(':')
if len(temp) == 2:
temp = [item.strip() for item in temp]
try:
num = float(temp[1])
parm_dict[temp[0]] = num
try:
if num == int(num):
parm_dict[temp[0]] = int(num)
except OverflowError:
pass
except ValueError:
parm_dict[temp[0]] = temp[1]
# Grab the creation and modification times:
other_parms = ibw_wave.get('wave_header')
for key in ['creationDate', 'modDate', 'bname']:
try:
parm_dict[key] = other_parms[key]
except KeyError:
pass
return parm_dict
@staticmethod
def _get_chan_labels(ibw_wave, codec='utf-8'):
"""
Retrieves the names of the data channels and default units
Parameters
----------
ibw_wave : dictionary
Wave entry in the dictionary obtained from loading the ibw file
codec : str, optional
Codec to be used to decode the bytestrings into Python strings if needed.
Default 'utf-8'
Returns
-------
labels : list of strings
List of the names of the data channels
default_units : list of strings
List of units for the measurement in each channel
"""
temp = ibw_wave.get('labels')
labels = []
for item in temp:
if len(item) > 0:
labels += item
for item in labels:
if item == '':
labels.remove(item)
default_units = list()
for chan_ind, chan in enumerate(labels):
# clean up channel names
if type(chan) == bytes:
chan = chan.decode(codec)
if chan.lower().rfind('trace') > 0:
labels[chan_ind] = chan[:chan.lower().rfind('trace') + 5]
# Figure out (default) units
if chan.startswith('Phase'):
default_units.append('deg')
elif chan.startswith('Current'):
default_units.append('A')
else:
default_units.append('m')
return labels, default_units
def _parse_file_path(self, input_path):
pass
def _read_data(self):
pass
def _get_image_type(self, ibw_wave, ftype):
"""
Generates correct channel labels based on the passed filetype
"""
if ftype.lower() == 'ff':
del ibw_wave[0:3]
ibw_wave = ['height', 'charging', 'shift'] + ibw_wave
elif ftype.lower() == 'trefm':
del ibw_wave[0:4]
ibw_wave = ['height', 'charging', 'shift', 'error'] + ibw_wave
elif ftype.lower() == 'skpm':
del ibw_wave[0:2]
ibw_wave = ['height', 'CPD'] + ibw_wave
elif ftype.lower() == 'ringdown':
del ibw_wave[0:4]
ibw_wave = ['height', 'Q', 'shift', 'error'] + ibw_wave
elif ftype.lower() == 'pl':
del ibw_wave[0:2]
ibw_wave = ['PL_volts', 'PL_current'] + ibw_wave
else:
raise Exception('Improper File Type')
return ibw_wave
def _get_unit_factor(self, unit):
"""
Returns numerical conversion of unit label
Unit : str
"""
fc = {'um': 1e-6,
'nm': 1e-9,
'pm': 1e-12,
'fm': 1e-15,
'mm': 1e-3,
'm': 1}
if unit.lower() in fc.keys():
return fc[unit]
elif unit[0] in fc.keys():
return fc[unit[0]]
<file_sep>/ffta/analysis/mask_utils.py
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 22 18:43:21 2018
@author: Raj
"""
import numpy as np
def load_mask_txt(path, rows=64, flip=False):
"""
Loads mask from text
Parameters
----------
path : str
Filepath to disk location of the mask
rows : int, optional
Sets a hard limit on the rows of the mask, due to Igor images being larger (rowwise)
than the typical G-Mode/FF-trEFM Mask size
flip : bool, optional
Whether to flip the mask left-to-right to match CPD
Returns
-------
mask : the mask itself
"""
mask = np.loadtxt(path)
if mask.shape[1] < mask.shape[0]: # we know it's fewer rows than columns
mask = mask.transpose()
if flip:
mask = np.fliplr(mask)
mask = mask[:rows, :]
return mask
def load_masks(mask):
"""
Outputs several useful mask versions
For reference:
NaNs = 1s in the mask = transparent in display
0s = 0s in the mask = opaque in display (i.e., are exluded/masked)
Parameters
----------
mask : ndarray 2D (rows, columns)
The mask to process into various new masks
Returns
-------
maskNaN : ndarray, 2D (rows, columns)
all 1s are NaNs, primarily for image display.
mask_on_1D : ndarray, 1D (rows*columns)
non-NaN pixels as a 1D list for distance calculation
mask_off_1D : ndarray, 1D (rows*columns)
NaN pixels as a 1D list for CPD masking
"""
mask_nan = np.copy(mask)
# tuple of coordinates
zeros = np.where(mask_nan == 0)
nans = np.where(mask_nan == 1)
mask_on_1D = np.array([(x, y) for x, y in zip(zeros[0], zeros[1])])
mask_off_1D = np.array([(x, y) for x, y in zip(nans[0], nans[1])])
mask_nan[mask_nan == 1] = np.nan
return mask_nan, mask_on_1D, mask_off_1D
def averagemask(CPDarr, mask, rows=128, nan_flag=1, avg_flag=0):
'''
Returns an averaged CPD trace given the Igor mask
Parameters
----------
mask : ndarray 2D (rows, columns)
The mask to process into various new masks
CPDarr
the CPD of n-by-samples, typically 8192 x 128 (8192 pixels, 128 CPD points)
Rows = 128 is default of 128x64 images
nan_flag
what value in the mask to set to NaN. These are IGNORED
1 is "transparent" in Igor mask
0 is "opaque/masked off" in Igor mask
avg_flag
what values in mask to average.
Returns
-------
CPDpixels
the averaged CPD of those pixels
'''
mask1D = mask.flatten()
CPDpixels = np.array([])
index = [i for i in np.where(mask1D == avg_flag)[0]]
for i in index:
CPDpixels = np.append(CPDpixels, CPDarr[i, :])
CPDpixels = np.reshape(CPDpixels, [len(index), CPDarr.shape[1]])
CPDpixels = np.mean(CPDpixels, axis=0)
return CPDpixels
<file_sep>/ffta/hdf_utils/plot_tfp.py
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 27 14:05:42 2020
@author: Raj
"""
from matplotlib import pyplot as plt
# from ffta.hdf_utils import get_utils
from ffta.load import get_utils
from ffta.pixel_utils import badpixels
import pyUSID as usid
import numpy as np
import os
def plot_tfps(h5_file, h5_path='/', append='', savefig=True, stdevs=2):
"""
Plots the relevant tfp, inst_freq, and shift values as separate image files
Parameters
----------
h5_file : h5Py File
h5_path : str, optional
Location of the relevant datasets to be saved/plotted. e.g. h5_rb.name
append : str, optional
A string to include in the saved figure filename
savefig : bool, optional
Whether or not to save the image
stdevs : int, optional
Number of standard deviations to display
"""
try:
h5_if = usid.hdf_utils.find_dataset(h5_file[h5_path], 'Inst_Freq')[0]
except:
h5_if = usid.hdf_utils.find_dataset(h5_file[h5_path], 'inst_freq')[0]
parm_dict = get_utils.get_params(h5_if)
# parm_dict = usid.hdf_utils.get_attributes(h5_file[h5_path])
if 'Dataset' in str(type(h5_file[h5_path])):
h5_path = h5_file[h5_path].parent.name
tfp = usid.hdf_utils.find_dataset(h5_file[h5_path], 'tfp')[0][()]
shift = usid.hdf_utils.find_dataset(h5_file[h5_path], 'shift')[0][()]
if tfp.shape[1] == 1:
# Forgot to reconvert and/or needs to be converted
[ysz, xsz] = h5_if.pos_dim_sizes
tfp = np.reshape(tfp, [ysz, xsz])
shift = np.reshape(shift, [ysz, xsz])
try:
tfp_fixed = usid.hdf_utils.find_dataset(h5_file[h5_path], 'tfp_fixed')[0][()]
except:
tfp_fixed, _ = badpixels.fix_array(tfp, threshold=2)
tfp_fixed = np.array(tfp_fixed)
xs = parm_dict['FastScanSize']
ys = parm_dict['SlowScanSize']
asp = ys / xs
if asp != 1:
asp = asp * 2
fig, a = plt.subplots(nrows=3, figsize=(8, 9))
[vmint, vmaxt] = np.mean(tfp) - 2 * np.std(tfp), np.mean(tfp) - 2 * np.std(tfp)
[vmins, vmaxs] = np.mean(shift) - 2 * np.std(shift), np.mean(shift) - 2 * np.std(shift)
_, cbar_t = usid.viz.plot_utils.plot_map(a[0], tfp_fixed * 1e6, x_vec=xs * 1e6, y_vec=ys * 1e6,
aspect=asp, cmap='inferno', stdevs=stdevs)
_, cbar_r = usid.viz.plot_utils.plot_map(a[1], 1 / (1e3 * tfp_fixed), x_vec=xs * 1e6, y_vec=ys * 1e6,
aspect=asp, cmap='inferno', stdevs=stdevs)
_, cbar_s = usid.viz.plot_utils.plot_map(a[2], shift, x_vec=xs * 1e6, y_vec=ys * 1e6,
aspect=asp, cmap='inferno', stdevs=stdevs)
cbar_t.set_label('tfp (us)', rotation=270, labelpad=16)
a[0].set_title('tfp', fontsize=12)
cbar_r.set_label('Rate (kHz)', rotation=270, labelpad=16)
a[1].set_title('1/tfp', fontsize=12)
cbar_s.set_label('shift (Hz)', rotation=270, labelpad=16)
a[2].set_title('shift', fontsize=12)
fig.tight_layout()
if savefig:
path = h5_file.file.filename.replace('\\', '/')
path = '/'.join(path.split('/')[:-1]) + '/'
os.chdir(path)
fig.savefig('tfp_shift_' + append + '_.tif', format='tiff')
return fig, a
<file_sep>/ffta/analysis/test_pixel.py
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 8 13:17:12 2018
@author: Raj
"""
from ffta.hdf_utils import hdf_utils
from matplotlib import pyplot as plt
def test_pixel(h5_file, param_changes={}, pxls = 1, showplots = True,
verbose=True, clear_filter = False):
"""
Takes a random pixel and does standard processing.
Parameters
----------
This is to tune parameters prior to processing an entire image
h5_file : h5Py File, path, Dataset
H5 file to process
pxls : int, optional
Number of random pixels to survey
showplots : bool, optional
Whether to create a new plot or not.
verbose : bool , optional
To print to command line. Currently for future-proofing
clear_filter : bool, optional
Whether to do filtering (FIR) or not
"""
# get_pixel can work on Datasets or the H5_File
if any(param_changes):
hdf_utils.change_params(h5_file, new_vals=param_changes)
parameters = hdf_utils.get_params(h5_file)
cols = parameters['num_cols']
rows = parameters['num_rows']
# Creates random pixels to sample
pixels = []
if pxls == 1:
pixels.append([0,0])
if pxls > 1:
from numpy.random import randint
for i in range(pxls):
pixels.append([randint(0,rows), randint(0,cols)])
# Analyzes all pixels
for rc in pixels:
h5_px = hdf_utils.get_pixel(h5_file, rc=rc)
if clear_filter:
h5_px.clear_filter_flags()
h5_px.analyze()
print(rc, h5_px.tfp)
if showplots == True:
plt.plot(h5_px.best_fit, 'r--')
plt.plot(h5_px.cut, 'g-')
return <file_sep>/docs/source/ffta.analysis.rst
ffta.analysis package
=====================
Submodules
----------
ffta.analysis.create\_movie module
----------------------------------
.. automodule:: ffta.analysis.create_movie
:members:
:undoc-members:
:show-inheritance:
ffta.analysis.dist\_cluster module
----------------------------------
.. automodule:: ffta.analysis.dist_cluster
:members:
:undoc-members:
:show-inheritance:
ffta.analysis.filtering module
------------------------------
.. automodule:: ffta.analysis.filtering
:members:
:undoc-members:
:show-inheritance:
ffta.analysis.gmode\_simple module
----------------------------------
.. automodule:: ffta.analysis.gmode_simple
:members:
:undoc-members:
:show-inheritance:
ffta.analysis.mask\_utils module
--------------------------------
.. automodule:: ffta.analysis.mask_utils
:members:
:undoc-members:
:show-inheritance:
ffta.analysis.svd module
------------------------
.. automodule:: ffta.analysis.svd
:members:
:undoc-members:
:show-inheritance:
ffta.analysis.test\_pixel module
--------------------------------
.. automodule:: ffta.analysis.test_pixel
:members:
:undoc-members:
:show-inheritance:
Module contents
---------------
.. automodule:: ffta.analysis
:members:
:undoc-members:
:show-inheritance:
<file_sep>/ffta/analysis/create_movie.py
import matplotlib.animation as animation
from matplotlib import pyplot as plt
import pyUSID as usid
from scipy import signal as sps
import numpy as np
'''
Note: A 'str is not callable' bug is often due to not running set_mpeg
'''
def set_mpeg(path=None):
if not any(path):
plt.rcParams[
'animation.ffmpeg_path'] = r'C:/Users/Raj/Downloads/ffmpeg/ffmpeg/bin/ffmpeg.exe'
else:
plt.rcParams['animation.ffmpeg_path'] = path
return
def setup_movie(h5_ds, size=(10, 6), vscale=[None, None], cmap='inferno'):
fig, ax = plt.subplots(nrows=1, figsize=size, facecolor='white')
if 'USID' not in str(type(h5_ds)):
h5_ds = usid.USIDataset(h5_ds)
params = usid.hdf_utils.get_attributes(h5_ds)
if 'trigger' not in params:
params = usid.hdf_utils.get_attributes(h5_ds.parent)
ds = h5_ds.get_n_dim_form()[:, :, 0]
# set scale based on the first line, pre-trigger to post-trigger
tdx = params['trigger'] * params['sampling_rate'] / params['pnts_per_avg']
tdx = int(tdx * len(h5_ds[0, :]))
if any(vscale):
[vmin, vmax] = vscale
else:
vmin = np.min(h5_ds[0][int(tdx * 0.7): int(tdx * 1.3)])
vmax = np.max(h5_ds[0][int(tdx * 0.7): int(tdx * 1.3)])
length = h5_ds.get_pos_values('X')
height = h5_ds.get_pos_values('Y')
im0 = ax.imshow(ds, cmap=cmap, origin='lower',
extent=[0, length[-1] * 1e6, 0, height[-1] * 1e6],
vmin=vmin, vmax=vmax)
cbar = plt.colorbar(im0, ax=ax, orientation='vertical',
fraction=0.023, pad=0.03, use_gridspec=True)
return fig, ax, cbar, vmin, vmax
def create_freq_movie(h5_ds, filename='inst_freq', time_step=50,
idx_start=500, idx_stop=100, smooth=None, size=(10, 6),
vscale=[None, None], cmap='inferno', interval=60, repeat_delay=100, crop=None):
'''
Creates an animation that goes through all the instantaneous frequency data.
Parameters
----------
h5_ds : USID Dataset
The instantaneous frequency data. NOT deflection, this is for post-processed data
rotate : bool, optional
The data are saved in ndim_form in pycroscopy rotated 90 degrees
time_step : int, optional
10 @ 10 MHz = 1 us
50 @ 10 MHz = 5 us
idx_start : int
What index to start at. Typically to avoid the Hilbert Transform edge artifacts, you start a little ahead
idx_stop : int
Same as the above,in terms of how many points BEFORE the end to stop
smooth : int, optional
Whether to apply a simple boxcar smoothing kernel to the data
size : tuple, optional
Figure size
vscale : list [float, float], optional
To hard-code the color scale, otherwise these are automatically generated
crop : int
Crops the image to a certain line, in case part of the scan is bad
'''
if not isinstance(h5_ds, usid.USIDataset):
h5_ds = usid.USIDataset(h5_ds)
if any(vscale):
fig, ax, cbar, _, _ = setup_movie(h5_ds, size, vscale, cmap=cmap)
[vmin, vmax] = vscale
else:
fig, ax, cbar, vmin, vmax = setup_movie(h5_ds, size, cmap=cmap)
_orig = np.copy(h5_ds[()])
length = h5_ds.get_pos_values('X')
height = h5_ds.get_pos_values('Y')
if isinstance(crop, int):
height = height * crop / h5_ds.get_n_dim_form()[:, :, 0].shape[0]
params = usid.hdf_utils.get_attributes(h5_ds)
if 'trigger' not in params:
params = usid.hdf_utils.get_attributes(h5_ds.parent)
if isinstance(smooth, int):
kernel = np.ones(smooth) / smooth
for i in np.arange(h5_ds.shape[0]):
h5_ds[i, :] = sps.fftconvolve(h5_ds[i, :], kernel, mode='same')
cbar.set_label('Frequency (Hz)', rotation=270, labelpad=20, fontsize=16)
tx = h5_ds.get_spec_values('Time')
# Loop through time segments
ims = []
for k, t in zip(np.arange(idx_start, len(tx) - idx_stop, time_step),
tx[idx_start:-idx_stop:time_step]):
_if = h5_ds.get_n_dim_form()[:, :, k]
if isinstance(crop, int):
if crop < 0:
_if = _if[crop:, :]
else:
_if = _if[:crop, :]
htitle = 'at ' + '{0:.4f}'.format(t * 1e3) + ' ms'
im0 = ax.imshow(_if, cmap=cmap, origin='lower', animated=True,
extent=[0, length[-1] * 1e6, 0, height[-1] * 1e6],
vmin=vmin, vmax=vmax)
if t > params['trigger']:
tl0 = ax.text(length[-1] * 1e6 / 2 - .35, height[-1] * 1e6 + .01,
htitle + ' ms, TRIGGER', color='blue', weight='bold', fontsize=16)
else:
tl0 = ax.text(length[-1] * 1e6 / 2 - .35, height[-1] * 1e6 + .01,
htitle + ' ms, PRE-TRIGGER', color='black', weight='regular', fontsize=14)
ims.append([im0, tl0])
ani = animation.ArtistAnimation(fig, ims, interval=interval, repeat_delay=repeat_delay)
try:
ani.save(filename + '.mp4')
except TypeError as e:
print(e)
print('A "str is not callable" message is often due to not running set_mpeg function')
# restore data
for i in np.arange(h5_ds.shape[0]):
h5_ds[i, :] = _orig[i, :]
return
def create_cpd_movie(h5_ds, filename='cpd', size=(10, 6),
vscale=[None, None], cmap='inferno', smooth=None, interval=60, repeat_delay=100):
'''
:param h5_ds:
:param rotate:
:param filename:
:param size:
:param vscale:
:param interval:
:param repeat_delay:
:return:
'''
if not isinstance(h5_ds, usid.USIDataset):
h5_ds = usid.USIDataset(h5_ds)
if any(vscale):
fig, ax, cbar, _, _ = setup_movie(h5_ds, size, vscale, cmap=cmap)
[vmin, vmax] = vscale
else:
fig, ax, cbar, vmin, vmax = setup_movie(h5_ds, size, cmap=cmap)
cbar.set_label('Potential (V)', rotation=270, labelpad=20, fontsize=16)
_orig = np.copy(h5_ds[()])
length = h5_ds.get_pos_values('X')
height = h5_ds.get_pos_values('Y')
params = usid.hdf_utils.get_attributes(h5_ds)
if 'trigger' not in params:
params = usid.hdf_utils.get_attributes(h5_ds.parent)
if isinstance(smooth, int):
kernel = np.ones(smooth) / smooth
for i in np.arange(h5_ds.shape[0]):
h5_ds[i, :] = sps.fftconvolve(h5_ds[i, :], kernel, mode='same')
tx = h5_ds.get_spec_values('Time')
# Loop through time segments
ims = []
for k, t in enumerate(tx):
_if = h5_ds.get_n_dim_form()[:, :, k]
htitle = 'at ' + '{0:.4f}'.format(t * 1e3) + ' ms'
im0 = ax.imshow(_if, cmap=cmap, origin='lower', animated=True,
extent=[0, length[-1] * 1e6, 0, height[-1] * 1e6],
vmin=vmin, vmax=vmax)
if t > params['trigger']:
tl0 = ax.text(length[-1] * 1e6 / 2 - .35, height[-1] * 1e6 + .01,
htitle + ' ms, TRIGGER', color='blue', weight='bold', fontsize=16)
else:
tl0 = ax.text(length[-1] * 1e6 / 2 - .35, height[-1] * 1e6 + .01,
htitle + ' ms, PRE-TRIGGER', color='black', weight='regular', fontsize=14)
ims.append([im0, tl0])
ani = animation.ArtistAnimation(fig, ims, interval=interval, repeat_delay=repeat_delay)
try:
ani.save(filename + '.mp4')
except TypeError:
print('A "str is not callable" message is often due to not running set_mpeg function')
# restore data
for i in np.arange(h5_ds.shape[0]):
h5_ds[i, :] = _orig[i, :]
return
<file_sep>/ffta/pixel_utils/peakdetect.py
import numpy as np
from scipy.signal import argrelextrema
def get_peaks(x):
maxpeaks = argrelextrema(x, np.greater, order=2)
minpeaks = argrelextrema(x, np.less, order=2)
return maxpeaks[0], minpeaks[0]<file_sep>/ffta/gkpfm/gkline.py
import numpy as np
from scipy import optimize as spo
from scipy import signal as sps
import warnings
import ffta
import time
import pyUSID as usid
from pyUSID.io.write_utils import Dimension
def cpd_total(ds, params, verbose=False, ncycles = 4, smooth=3):
'''
:param ds:
:param params:
:param verbose:
:param ncycles:
:param smooth:
:return:
'''
t0 = time.time()
gk = ffta.gkpfm.gkpixel.GKPixel(ds[0, :], params)
cpd_mat = np.zeros([ds.shape[0], gk.num_ncycles])
cpd_mat_sm = np.zeros([ds.shape[0], gk.num_ncycles])
cpd, _, _ = gk.analyze(fast=True)
cpd_mat[0, :] = cpd
kernel = np.ones(smooth)/smooth
cpd_mat_sm[0, :] = sps.fftconvolve(cpd, kernel, mode='same')
for i in np.arange(1, cpd_mat.shape[0]):
if verbose:
if i % 100 == 0:
print('Line ', i)
gk = ffta.gkpfm.gkpixel.GKPixel(ds[i, :], params, ncycles=ncycles)
cpd, _, _ = gk.analyze(fast=True)
cpd_mat[i, :] = cpd
cpd_mat_sm[i, :] = sps.fftconvolve(cpd, kernel, mode='same')
t1 = time.time()
print('Time:', t1 - t0)
return cpd_mat, cpd_mat_sm
def save_cpd(h5_main, cpd_mat, cpd_sm):
'''
:param h5_main:
:param cpd_mat:
:param cpd_mat_sm:
:return:
'''
parm_dict = usid.hdf_utils.get_attributes(h5_main)
# Get relevant parameters
num_rows = parm_dict['num_rows']
num_cols = parm_dict['num_cols']
h5_gp = h5_main.parent
h5_meas_group = usid.hdf_utils.create_indexed_group(h5_gp, 'CPD')
# Create dimensions
pos_desc = [Dimension('X', 'm', np.linspace(0, parm_dict['FastScanSize'], num_cols)),
Dimension('Y', 'm', np.linspace(0, parm_dict['SlowScanSize'], num_rows))]
# ds_pos_ind, ds_pos_val = build_ind_val_matrices(pos_desc, is_spectral=False)
spec_desc = [Dimension('Time', 's', np.linspace(0, parm_dict['total_time'], cpd_mat.shape[1]))]
# ds_spec_inds, ds_spec_vals = build_ind_val_matrices(spec_desc, is_spectral=True)
# Writes main dataset
h5_cpd = usid.hdf_utils.write_main_dataset(h5_meas_group,
cpd_mat,
'cpd', # Name of main dataset
'Contact Potential', # Physical quantity contained in Main dataset
'V', # Units for the physical quantity
pos_desc, # Position dimensions
spec_desc, # Spectroscopic dimensions
dtype=np.float32, # data type / precision
)
# add smoothed dataset
h5_meas_group.create_dataset('cpd_sm', data=cpd_sm, dtype=np.float32)
usid.hdf_utils.copy_attributes(h5_main, h5_gp)
return h5_cpd
def cpd_single(ds, params):
gk = ffta.gkpfm.gkpixel.GKPixel(ds, params)
cpd, _, _ = gk.analyze(fft=True)
return cpd
<file_sep>/ffta/pixel_utils/noise.py
"""noise.py: Includes functions for reducing noise in a pixel."""
# pylint: disable=E1101,R0902
__author__ = "<NAME>"
__copyright__ = "Copyright 2013, Ginger Lab"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
__status__ = "Production"
import numpy as np
import scipy.linalg as spl
import scipy.spatial.distance as spsd
def phase_lock(signal_array, tidx, cidx):
"""
Aligns signals of a pixel on the rising edge of first zeros, if they are
not aligned due to phase jitter of analog-to-digital converter.
Parameters
----------
signal_array : (n_points, n_signals), array_like
2D real-valued signal array.
tidx: int
Time to trigger from the start of signals as index.
cidx: int
Period of the signal as number of points,
i.e. drive_freq/sampling_rate
Returns
-------
signal_array : (n_points, n_signals), array_like
Phase-locked signal array
tidx : int
Index of trigger after phase-locking.
"""
# Initialize variables.
n_points, n_signals = signal_array.shape
above = signal_array[:cidx, :] > 0
below = np.logical_not(above)
left_shifted_above = above[1:, :]
idxs = (left_shifted_above[:, :] & below[0:-1, :]).argmax(axis=0)
# Have all signals same length by cutting them from both ends.
total_cut = int(idxs.max() + idxs.min() + 1)
new_signal_array = np.empty((n_points - total_cut, n_signals))
tidx -= int(idxs.mean()) # Shift trigger index by average amount.
# Cut signals.
for i, idx in enumerate(idxs):
new_signal_array[:, i] = signal_array[idx:-(total_cut - idx), i]
return new_signal_array, tidx
def pca_discard(signal_array, k):
"""
Discards noisy signals using Principal Component Analysis and Mahalonobis
distance.
Parameters
----------
signal_array : (n_points, n_signals), array_like
2D real-valued signal array.
k : int
Number of eigenvectors to use, can't be bigger than n_signals.
Returns
-------
idx : array
Return the indices of noisy signals.
"""
# Get the size of signals.
n_points, n_signals = signal_array.shape
# Remove the mean from all signals.
mean_signal = signal_array.mean(axis=1).reshape(n_points, 1)
signal_array = signal_array - mean_signal
# Calculate the biggest eigenvector of covariance matrix.
_, eigvec = spl.eigh(np.dot(signal_array.T, signal_array),
eigvals=(n_signals - k, n_signals - 1))
eigsig = np.dot(signal_array, eigvec) # Convert it to eigensignal.
weights = np.dot(eigsig.T, signal_array) / spl.norm(eigsig)
mean = weights.mean(axis=1).reshape(1, k)
idx = np.where(spsd.cdist(weights.T, mean, 'mahalanobis') > 2)
return idx
<file_sep>/ffta/hdf_utils/__init__.py
from . import analyze_h5
from . import hdf_utils
from . import process
__all__ = ['hdf_utils', 'analyze_h5', 'process']<file_sep>/docs/requirements.txt
sphinx==2.3.1<file_sep>/ffta/gkpfm/load_excitation.py
"""loadHDF5.py: Includes routines for loading into HDF5 files."""
from __future__ import division, print_function, absolute_import, unicode_literals
__author__ = "<NAME>"
__copyright__ = "Copyright 2018, Ginger Lab"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
__status__ = "Development"
import numpy as np
import os
import h5py
import pyUSID as usid
from igor.binarywave import load as loadibw
def load_exc(ibw_folder='', pixels=64, scale=1, offset=1, verbose=False):
"""
Loads excitation files into a single .h5 file
Parameters
----------
ibw_folder : string, optional
The folder containing the excitation files to load
pixels : int, optional
How many pixels per line to divide the excitation ibw
scale : float, optional
The AC signal scaling, assuming the input excitation is wrong
offset : float, optional
The DC offset for the excitation
"""
if not any(ibw_folder):
exc_file_path = usid.io_utils.file_dialog(caption='Select any file in destination folder',
file_filter='IBW Files (*.ibw)')
exc_file_path = '/'.join(exc_file_path.split('/')[:-1])
filelist = os.listdir(exc_file_path)
data_files = [os.path.join(exc_file_path, name)
for name in filelist if name[-3:] == 'ibw']
h5_path = os.path.join(exc_file_path, 'excitation') + '.h5'
h5_file = h5py.File(h5_path, 'w')
_line0 = loadibw(data_files[0])['wave']['wData']
_pix0 = np.split(_line0, pixels, axis=1)[0].mean(axis=1)
_pix0 = scale * ((_pix0 - np.min(_pix0)) / (np.max(_line0) - np.min(_line0)) - 0.5) + offset
data = h5_file.create_dataset('excitation',
shape=(len(data_files), pixels, len(_pix0)),
compression='gzip')
for n, d in enumerate(data_files):
if verbose:
print('### Loading', d.split('/')[-1], '###')
_line = loadibw(d)['wave']['wData']
for m, l in enumerate(np.split(_line, pixels, axis=1)):
_pix = np.mean(l, axis=1)
data[n, m, :] = _pix
# self.h5_tfp = self.h5_results_grp.create_dataset('tfp', data=_arr, dtype=np.float32)
return h5_path
<file_sep>/ffta/analyze_pixel.py
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 22 12:35:38 2020
@author: Raj
"""
#Script that loads, analyzes, and plots fast free point scan with fit
from ffta.pixel import Pixel
from ffta.pixel_utils.load import signal
from ffta.pixel_utils.load import configuration
import matplotlib.pyplot as plt
def analyze_pixel(ibw_file, param_file):
'''
Analyzes a single pixel
Parameters
----------
ibw_file : str
path to \*.ibw file
param_file : str
path to parameters.cfg file
Returns
-------
pixel : Pixel
The pixel object read and analyzed
'''
signal_array = signal(ibw_file)
n_pixels, params = configuration(param_file)
pixel = Pixel(signal_array, params=params)
pixel.analyze()
pixel.plot()
plt.xlabel('Time Step')
plt.ylabel('Freq Shift (Hz)')
print('tFP is', pixel.tfp, 's')
return pixel.tfp
<file_sep>/ffta/simulation/mechanical_drive.py
"""simulate.py: Contains Cantilever class."""
# pylint: disable=E1101,R0902,C0103
__author__ = "<NAME>"
__copyright__ = "Copyright 2020, Ginger Lab"
__email__ = "<EMAIL>"
__status__ = "Production"
import numpy as np
from scipy.integrate import odeint
from .cantilever import Cantilever
from . import excitation
# Set constant 2 * pi.
PI2 = 2 * np.pi
class MechanicalDrive(Cantilever):
"""Damped Driven Harmonic Oscillator Simulator for AFM Cantilevers under
Mechanial drive (i.e. conventional DDHO)
Simulates a DDHO under excitation with given parameters and a change to resonance
and electrostatic force
Time-dependent change can be specified in two ways:
1) explicitly defining v_array, a scale from 0 to 1 of the same length as
the desired integration
2) using a defined function and parameter, passed to parameter "func"
This approach will call self.func(t, \*self.func_args)
By default, this will call excitation.single_exp, a single exponential
decay.
For this approach to work, you must supply or set self.func_args = []
Parameters
----------
can_params : dict
Parameters for cantilever properties. See Cantilever
force_params : dict
Parameters for forces. Beyond Cantilever, the dictionary contains:
es_force = float (in N)
delta_freq = float (in Hz)
tau = float (in seconds)
sim_params : dict
Parameters for simulation. The dictionary contains:
trigger = float (in seconds)
total_time = float (in seconds)
sampling_rate = int (in Hz)
v_array : ndarray, optional
If supplied, v_array is the time-dependent excitation to the resonance
frequency and the electrostatic force, scaled from 0 to 1.
v_array must be the exact length and sampling of the desired signal
func : function, optional
Attributes
----------
Z : ndarray
ODE integration of the DDHO response
Method
------
simulate(trigger_phase=180)
Simulates the cantilever motion with excitation happening
at the given phase.
See Also
--------
pixel: Pixel processing for FF-trEFM data.
Cantilever: base class
Examples
--------
>>> from ffta.simulation import mechanical_dirve, load
>>>
>>> params_file = '../examples/sim_params.cfg'
>>> params = load.simulation_configuration(params_file)
>>>
>>> c = mechanical_dirve.MechanicalDrive(*params)
>>> Z, infodict = c.simulate()
>>> c.analyze()
>>> c.analyze(roi=0.004) # can change the parameters as desired
>>>
>>> # To supply an arbitary v_array
>>> n_points = int(params[2]['total_time'] * params[2]['sampling_rate'])
>>> v_array = np.ones(n_points) # create just a flat excitation
>>> c = mechanical_dirve.MechanicalDrive(*params, v_array = v_array)
>>> Z, _ = c.simulate()
>>> c.analyze()
>>>
>>> # To use a function instead of artbitary array, say stretch exponential
>>> c = mechanical_dirve.MechanicalDrive(*params, func=excitation.str_exp, func_args=[1e-3, 0.8])
>>> Z, _ = c.simulate()
>>> c.analyze()
>>> c.func_args = [1e-3, 0.7] # change beta value in stretched exponential
>>> Z, _ = c.simulate()
>>> c.analyze()
"""
def __init__(self, can_params, force_params, sim_params,
v_array=[], func=excitation.single_exp, func_args=[]):
parms = [can_params, force_params, sim_params]
super(MechanicalDrive, self).__init__(*parms)
# Did user supply a voltage pulse themselves (Electrical drive only)
self.use_varray = False
if any(v_array):
if len(v_array) != int(self.total_time * self.sampling_rate):
raise ValueError('v_array must match sampling rate/length of parameters')
if np.min(v_array) != 0 or np.max(v_array) != 1:
raise ValueError('v_array must scale from 0 to 1')
else:
self.use_varray = True
self.v_array = v_array
self.func = func
self.func_args = func_args
# default case set a single tau for a single exponential function
if not np.any(func_args):
self.func_args = [self.tau]
try:
_ = self.func(0, *self.func_args)
except:
print('Be sure to correctly set func_args=[params]')
return
def __gamma__(self, t):
"""
Controls how the cantilever behaves after a trigger.
Default operation is an exponential decay to omega0 - delta_freq with
time constant tau.
If supplying an explicit v_array, then this function will call the values
in that array
Parameters
----------
t : float
Time in seconds.
Returns
-------
value : float
Value of the function at the given time.
"""
p = int(t * self.sampling_rate)
n_points = int(self.total_time * self.sampling_rate)
t0 = self.t0
if t >= t0:
if not self.use_varray:
return self.func(t - t0, *self.func_args)
else:
_g = self.v_array[p] if p < n_points else self.v_array[-1]
return _g
else:
return 0
def omega(self, t, t0, tau):
"""
Exponentially decaying resonance frequency.
Parameters
----------
t : float
Time in seconds.
t0: float
Event time in seconds.
tau : float
Decay constant in the exponential function, in seconds.
Returns
-------
w : float
Resonance frequency of the cantilever at a given time, in rad/s.
"""
# return self.w0 + self.delta_w * self.__gamma__(t, t0, tau)
return self.w0 + self.delta_w * self.__gamma__(t)
def force(self, t, t0, tau):
"""
Force on the cantilever at a given time. It contains driving force and
electrostatic force.
Parameters
----------
t : float
Time in seconds.
t0: float
Event time in seconds.
tau : float
Decay constant in the exponential function, in seconds.
Returns
-------
f : float
Force on the cantilever at a given time, in N/kg.
"""
driving_force = self.f0 * np.sin(self.wd * t)
# electro_force = self.fe * self.__gamma__(t, t0, tau)
electro_force = self.fe * self.__gamma__(t)
return driving_force - electro_force
<file_sep>/docs/conf.py
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
import os
import sys
import sphinx_rtd_theme
sys.path.insert(0, os.path.abspath('..'))
sys.path.insert(0, os.path.abspath('../ffta'))
sys.path.insert(0, os.path.abspath('../ffta/acquisition'))
sys.path.insert(0, os.path.abspath('../ffta/analysis'))
sys.path.insert(0, os.path.abspath('../ffta/gkpfm'))
sys.path.insert(0, os.path.abspath('../ffta/hdf_utils'))
sys.path.insert(0, os.path.abspath('../ffta/load'))
sys.path.insert(0, os.path.abspath('../ffta/pixel_utils'))
sys.path.insert(0, os.path.abspath('../ffta/simulation'))
autodoc_mock_imports = ['scipy', 'numpy', 'watchdog', 'igor', 'pandas', 'pywt',
'matplotlib', 'pyUSID', 'numexpr', 'pycroscopy', 'pywavelets',
'h5py', 'sklearn']
# -- Project information -----------------------------------------------------
project = 'FFTA'
copyright = '2020, <NAME>'
author = '<NAME>'
# -- General configuration ---------------------------------------------------
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.coverage', 'sphinx.ext.napoleon']
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# -- Options for HTML output -------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = 'sphinx_rtd_theme'
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']<file_sep>/ffta/acquisition/__init__.py
from . import generate_chirp
from . import polling
__all__ = ['generate_chirp', 'polling']<file_sep>/ffta/hdf_utils/analyze_h5.py
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 22 13:16:05 2018
@author: Raj
"""
import os
import numpy as np
import h5py
from matplotlib import pyplot as plt
from ffta.load import get_utils
from ffta.hdf_utils import hdf_utils
from ffta.pixel_utils import badpixels
import pycroscopy as px
import pyUSID as usid
from pyUSID.io.io_utils import get_time_stamp
from pyUSID.io.write_utils import build_ind_val_matrices, Dimension
"""
Analyzes an HDF_5 format trEFM data set and writes the result into that file
"""
def process(h5_file, ds='FF_Raw', ref='', clear_filter=False,
verbose=True, liveplots=True, **kwargs):
"""
Processes FF_Raw dataset in the HDF5 file
This then saves within the h5 file in FF_Group-processed
This uses the dataset in this priority:
\*A relative path specific by ref, e.g. '/FF_Group/FF_Avg/FF_Avg'
\*A dataset specified by ds, returning the last found, e.g. 'FF_Raw'
\*FF_Group/FF_Raw found via searching from hdf_utils folder
Typical usage:
>> import pycroscopy as px
>> h5_file = px.io.HDFwriter('path_to_h5_file.h5').file
>> from ffta import analyze_h5
>> tfp, shift, inst_freq = analyze_h5.process(h5_file, ref = '/FF_Group/FF_Avg/FF_Avg')
Parameters
----------
h5_file : h5Py file or str
Path to a specific h5 file on the disk or an hdf.file
ds : str, optional
The Dataset to search for in the file
ref : str, optional
A path to a specific dataset in the file.
e.g. h5_file['/FF_Group/FF_Avg/FF_Avg']
clear_filter : bool, optional
For data already filtered, calls Line's clear_filter function to
skip FIR/windowing steps
verbose : bool, optional,
Whether to write data to the command line
liveplots : bool
Displaying can sometimes cause the window to pop in front of other active windows
in Matplotlib. This disables it, with an obvious drawback of no feedback.
Returns
-------
tfp : ndarray
time-to-first-peak image array
shift : ndarray
frequency shift image array
inst_freq : ndarray (2D)
instantaneous frequency array, an N x p array of N=rows\*cols points
and where p = points_per_signal (e.g. 16000 for 1.6 ms @10 MHz sampling)
h5_if : USIDataset of h5_if (instantaneous frequency)
"""
# logging.basicConfig(filename='error.log', level=logging.INFO)
ftype = str(type(h5_file))
if ('str' in ftype) or ('File' in ftype) or ('Dataset' in ftype):
h5_file = px.io.HDFwriter(h5_file).file
else:
raise TypeError('Must be string path, e.g. E:\Test.h5')
# Looks for a ref first before searching for ds, h5_ds is group to process
if any(ref):
h5_ds = h5_file[ref]
parameters = get_utils.get_params(h5_ds)
elif ds != 'FF_Raw':
h5_ds = usid.hdf_utils.find_dataset(h5_file, ds)[-1]
parameters = get_utils.get_params(h5_ds)
else:
h5_ds, parameters = find_FF(h5_file)
if isinstance(h5_ds, h5py.Dataset):
h5_gp = h5_ds.parent
# Initialize file and read parameters
num_cols = parameters['num_cols']
num_rows = parameters['num_rows']
pnts_per_pixel = parameters['pnts_per_pixel']
pnts_per_avg = parameters['pnts_per_avg']
for key, value in kwargs.items():
_temp = parameters[key]
parameters[key] = value
if verbose:
print('Changing', key, 'from', _temp, 'to', value)
if verbose:
print('Recombination: ', parameters['recombination'])
print('ROI: ', parameters['roi'])
# Initialize arrays.
tfp = np.zeros([num_rows, num_cols])
shift = np.zeros([num_rows, num_cols])
inst_freq = np.zeros([num_rows * num_cols, pnts_per_avg])
# Initialize plotting.
plt.ion()
fig, a = plt.subplots(nrows=2, ncols=2, figsize=(13, 6))
tfp_ax = a[0][1]
shift_ax = a[1][1]
img_length = parameters['FastScanSize']
img_height = parameters['SlowScanSize']
kwargs = {'origin': 'lower', 'x_vec': img_length * 1e6,
'y_vec': img_height * 1e6, 'num_ticks': 5, 'stdevs': 3}
try:
ht = h5_file['/height/Raw_Data'][:, 0]
ht = np.reshape(ht, [num_cols, num_rows]).transpose()
ht_ax = a[0][0]
ht_image, cbar = usid.viz.plot_utils.plot_map(ht_ax, ht * 1e9, cmap='gray', **kwargs)
cbar.set_label('Height (nm)', rotation=270, labelpad=16)
except:
pass
tfp_ax.set_title('tFP Image')
shift_ax.set_title('Shift Image')
tfp_image, cbar_tfp = usid.viz.plot_utils.plot_map(tfp_ax, tfp * 1e6,
cmap='inferno', show_cbar=False, **kwargs)
shift_image, cbar_sh = usid.viz.plot_utils.plot_map(shift_ax, shift,
cmap='inferno', show_cbar=False, **kwargs)
text = tfp_ax.text(num_cols / 2, num_rows + 3, '')
plt.show()
print('Analyzing with roi of', parameters['roi'])
# Load every file in the file list one by one.
for i in range(num_rows):
line_inst = get_utils.get_line(h5_ds, i, params=parameters)
if clear_filter:
line_inst.clear_filter_flags()
_tfp, _shf, _if = line_inst.analyze()
tfp[i, :] = _tfp.T
shift[i, :] = _shf.T
inst_freq[i * num_cols:(i + 1) * num_cols, :] = _if.T
if liveplots:
tfp_image, _ = usid.viz.plot_utils.plot_map(tfp_ax, tfp * 1e6,
cmap='inferno', show_cbar=False, **kwargs)
shift_image, _ = usid.viz.plot_utils.plot_map(shift_ax, shift,
cmap='inferno', show_cbar=False, **kwargs)
tfp_sc = tfp[tfp.nonzero()] * 1e6
tfp_image.set_clim(vmin=tfp_sc.min(), vmax=tfp_sc.max())
shift_sc = shift[shift.nonzero()]
shift_image.set_clim(vmin=shift_sc.min(), vmax=shift_sc.max())
tfpmean = 1e6 * tfp[i, :].mean()
tfpstd = 1e6 * tfp[i, :].std()
if verbose:
string = ("Line {0:.0f}, average tFP (us) ="
" {1:.2f} +/- {2:.2f}".format(i + 1, tfpmean, tfpstd))
print(string)
text.remove()
text = tfp_ax.text((num_cols - len(string)) / 2, num_rows + 4, string)
# plt.draw()
plt.pause(0.0001)
del line_inst # Delete the instance to open up memory.
tfp_image, cbar_tfp = usid.viz.plot_utils.plot_map(tfp_ax, tfp * 1e6, cmap='inferno', **kwargs)
cbar_tfp.set_label('Time (us)', rotation=270, labelpad=16)
shift_image, cbar_sh = usid.viz.plot_utils.plot_map(shift_ax, shift, cmap='inferno', **kwargs)
cbar_sh.set_label('Frequency Shift (Hz)', rotation=270, labelpad=16)
text = tfp_ax.text(num_cols / 2, num_rows + 3, '')
plt.show()
h5_if = save_IF(h5_ds.parent, inst_freq, parameters)
_, _, tfp_fixed = save_ht_outs(h5_if.parent, tfp, shift)
# save_CSV(h5_path, tfp, shift, tfp_fixed, append=ds)
if verbose:
print('Please remember to close the H5 file explicitly when you are done to retain these data',
'e.g.:',
'h5_if.file.close()',
'...and then reopen the file as needed.')
return tfp, shift, inst_freq, h5_if
def save_IF(h5_gp, inst_freq, parm_dict):
""" Adds Instantaneous Frequency as a main dataset """
# Error check
if isinstance(h5_gp, h5py.Dataset):
raise ValueError('Must pass an h5Py group')
# Get relevant parameters
num_rows = parm_dict['num_rows']
num_cols = parm_dict['num_cols']
pnts_per_avg = parm_dict['pnts_per_avg']
h5_meas_group = usid.hdf_utils.create_indexed_group(h5_gp, 'processed')
# Create dimensions
pos_desc = [Dimension('X', 'm', np.linspace(0, parm_dict['FastScanSize'], num_cols)),
Dimension('Y', 'm', np.linspace(0, parm_dict['SlowScanSize'], num_rows))]
# ds_pos_ind, ds_pos_val = build_ind_val_matrices(pos_desc, is_spectral=False)
spec_desc = [Dimension('Time', 's', np.linspace(0, parm_dict['total_time'], pnts_per_avg))]
# ds_spec_inds, ds_spec_vals = build_ind_val_matrices(spec_desc, is_spectral=True)
# Writes main dataset
h5_if = usid.hdf_utils.write_main_dataset(h5_meas_group,
inst_freq,
'inst_freq', # Name of main dataset
'Frequency', # Physical quantity contained in Main dataset
'Hz', # Units for the physical quantity
pos_desc, # Position dimensions
spec_desc, # Spectroscopic dimensions
dtype=np.float32, # data type / precision
main_dset_attrs=parm_dict)
usid.hdf_utils.copy_attributes(h5_if, h5_gp)
h5_if.file.flush()
return h5_if
def save_ht_outs(h5_gp, tfp, shift):
""" Save processed Hilbert Transform outputs"""
# Error check
if isinstance(h5_gp, h5py.Dataset):
raise ValueError('Must pass an h5Py group')
# Filter bad pixels
tfp_fixed, _ = badpixels.fix_array(tfp, threshold=2)
tfp_fixed = np.array(tfp_fixed)
# write data; note that this is all actually deprecated and should be fixed
# grp_name = h5_gp.name
# grp_tr = px.io.VirtualGroup(grp_name)
# tfp_px = px.io.VirtualDataset('tfp', tfp, parent = h5_gp)
# shift_px = px.io.VirtualDataset('shift', shift, parent = h5_gp)
# tfp_fixed_px = px.io.VirtualDataset('tfp_fixed', tfp_fixed, parent = h5_gp)
#
# grp_tr.attrs['timestamp'] = get_time_stamp()
# grp_tr.add_children([tfp_px])
# grp_tr.add_children([shift_px])
# grp_tr.add_children([tfp_fixed_px])
# write data using current pyUSID implementations
# grp_tr = h5_file.create_group(h5_gp.name)
tfp_px = h5_gp.create_dataset('tfp', data=tfp, dtype=np.float32)
shift_px = h5_gp.create_dataset('shift', data=shift, dtype=np.float32)
tfp_fixed_px = h5_gp.create_dataset('tfp_fixed', data=tfp_fixed, dtype=np.float32)
h5_gp.attrs['timestamp'] = get_time_stamp()
return tfp_px, shift_px, tfp_fixed_px
def save_CSV_from_file(h5_file, h5_path='/', append='', mirror=False):
"""
Saves the tfp, shift, and fixed_tfp as CSV files
Parameters
----------
h5_file : H5Py file
Reminder you can always type: h5_svd.file or h5_avg.file for this
h5_path : str, optional
specific folder path to search for the tfp data. Usually not needed.
append : str, optional
text to append to file name
"""
tfp = usid.hdf_utils.find_dataset(h5_file[h5_path], 'tfp')[0][()]
tfp_fixed = usid.hdf_utils.find_dataset(h5_file[h5_path], 'tfp_fixed')[0][()]
shift = usid.hdf_utils.find_dataset(h5_file[h5_path], 'shift')[0][()]
print(usid.hdf_utils.find_dataset(h5_file[h5_path], 'shift')[0].parent.name)
path = h5_file.file.filename.replace('\\', '/')
path = '/'.join(path.split('/')[:-1]) + '/'
os.chdir(path)
if mirror:
np.savetxt('tfp-' + append + '.csv', np.fliplr(tfp).T, delimiter=',')
np.savetxt('shift-' + append + '.csv', np.fliplr(shift).T, delimiter=',')
np.savetxt('tfp_fixed-' + append + '.csv', np.fliplr(tfp_fixed).T, delimiter=',')
else:
np.savetxt('tfp-' + append + '.csv', tfp.T, delimiter=',')
np.savetxt('shift-' + append + '.csv', shift.T, delimiter=',')
np.savetxt('tfp_fixed-' + append + '.csv', tfp_fixed.T, delimiter=',')
return
def plot_tfps(h5_file, h5_path='/', append='', savefig=True, stdevs=2):
"""
Plots the relevant tfp, inst_freq, and shift values as separate image files
Parameters
----------
h5_file : h5Py File
h5_path : str, optional
Location of the relevant datasets to be saved/plotted. e.g. h5_rb.name
append : str, optional
A string to include in the saved figure filename
savefig : bool, optional
Whether or not to save the image
stdevs : int, optional
Number of standard deviations to display
"""
h5_file = px.io.HDFwriter(h5_file).file
try:
h5_if = usid.hdf_utils.find_dataset(h5_file[h5_path], 'Inst_Freq')[0]
except:
h5_if = usid.hdf_utils.find_dataset(h5_file[h5_path], 'inst_freq')[0]
parm_dict = get_utils.get_params(h5_if)
# parm_dict = usid.hdf_utils.get_attributes(h5_file[h5_path])
if 'Dataset' in str(type(h5_file[h5_path])):
h5_path = h5_file[h5_path].parent.name
tfp = usid.hdf_utils.find_dataset(h5_file[h5_path], 'tfp')[0][()]
shift = usid.hdf_utils.find_dataset(h5_file[h5_path], 'shift')[0][()]
if tfp.shape[1] == 1:
# Forgot to reconvert and/or needs to be converted
[ysz, xsz] = h5_if.pos_dim_sizes
tfp = np.reshape(tfp, [ysz, xsz])
shift = np.reshape(shift, [ysz, xsz])
try:
tfp_fixed = usid.hdf_utils.find_dataset(h5_file[h5_path], 'tfp_fixed')[0][()]
except:
tfp_fixed, _ = badpixels.fix_array(tfp, threshold=2)
tfp_fixed = np.array(tfp_fixed)
xs = parm_dict['FastScanSize']
ys = parm_dict['SlowScanSize']
asp = ys / xs
if asp != 1:
asp = asp * 2
fig, a = plt.subplots(nrows=3, figsize=(8, 9))
[vmint, vmaxt] = np.mean(tfp) - 2 * np.std(tfp), np.mean(tfp) - 2 * np.std(tfp)
[vmins, vmaxs] = np.mean(shift) - 2 * np.std(shift), np.mean(shift) - 2 * np.std(shift)
_, cbar_t = usid.viz.plot_utils.plot_map(a[0], tfp_fixed * 1e6, x_vec=xs * 1e6, y_vec=ys * 1e6,
aspect=asp, cmap='inferno', stdevs=stdevs)
_, cbar_r = usid.viz.plot_utils.plot_map(a[1], 1 / (1e3 * tfp_fixed), x_vec=xs * 1e6, y_vec=ys * 1e6,
aspect=asp, cmap='inferno', stdevs=stdevs)
_, cbar_s = usid.viz.plot_utils.plot_map(a[2], shift, x_vec=xs * 1e6, y_vec=ys * 1e6,
aspect=asp, cmap='inferno', stdevs=stdevs)
cbar_t.set_label('tfp (us)', rotation=270, labelpad=16)
a[0].set_title('tfp', fontsize=12)
cbar_r.set_label('Rate (kHz)', rotation=270, labelpad=16)
a[1].set_title('1/tfp', fontsize=12)
cbar_s.set_label('shift (Hz)', rotation=270, labelpad=16)
a[2].set_title('shift', fontsize=12)
fig.tight_layout()
if savefig:
path = h5_file.file.filename.replace('\\', '/')
path = '/'.join(path.split('/')[:-1]) + '/'
os.chdir(path)
fig.savefig('tfp_shift_' + append + '_.tif', format='tiff')
return
def find_FF(h5_path):
parameters = get_utils.get_params(h5_path)
h5_gp = hdf_utils._which_h5_group(h5_path)
return h5_gp, parameters
<file_sep>/ffta/analysis/gmode_simple.py
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 25 17:07:34 2018
@author: Raj
"""
import numpy as np
import ffta
from scipy import signal as sig
class F3R(object):
"""
Simple G-Mode analyzer for F3R. This does not take into account transfer
function of the tip at all.
7/25/2018 : hard coded for only single pixel work
"""
def __init__(self, signal_array, params, n_pixels=1):
for key, value in params.items():
setattr(self, key, value)
self.N_points = n_pixels
self.N_points_per_pixel = self.sampling_rate * self.total_time
self.time_per_osc = 1/self.drive_freq
self.pnts_per_period = self.sampling_rate * self.time_per_osc
self.pxl_time = self.N_points_per_pixel/self.sampling_rate
self.num_periods = int(self.pxl_time/self.time_per_osc)
xpts = np.arange(0,self.total_time, 1/self.sampling_rate)[:-1]
self.pixel_ex_wfm = np.sin(xpts * self.drive_freq*2*np.pi)
self.signal = signal_array
if len(self.signal.shape) != 1: # needs to be averaged
self.signal = self.signal.mean(axis=0)
self.signal -= np.mean(self.signal) #DC offset
return
def t_div(self):
'''
Simple divide by the transfer function to get Force. Doesn't really work
'''
h = self.pixel_ex_wfm
y = self.signal
H = np.fft.fftshift(np.fft.fft(h))
Y = np.fft.fftshift(np.fft.fft(y))
F = np.divide(H,Y)
self.signal = np.real(np.fft.ifft(np.fft.ifftshift(F)))
return
def lia(self, tc=2):
'''
Simple lockin integration
time constant tc = number of points
Does not auto calculate for you based on time.
'''
xpts = np.arange(0,self.total_time, 1/self.sampling_rate)[:-1]
sini = np.sin(2*np.pi*self.drive_freq*xpts)
cosi = np.cos(2*np.pi*self.drive_freq*xpts)
UoutX = self.signal * sini
UoutY = self.signal * cosi
X = np.array([])
Y = np.array([])
for i in np.arange(0,int(self.N_points_per_pixel), tc):
t = xpts[i:i+tc]
Uout = np.trapz(UoutX[i:i+tc], t)
X = np.append(X,Uout)
Uout = np.trapz(UoutY[i:i+tc], t)
Y = np.append(Y,Uout)
self.X = X
self.Y = Y
self.amp = np.sqrt(X**2 + Y**2)
self.phase = np.arctan(Y/X)
return
def analyze(self, periods=4):
complete_periods = True
num_periods_per_sample = int(np.floor(self.num_periods / periods))
pnts_per_sample = int(np.floor(self.pnts_per_period * periods))
if complete_periods == False:
# new approach since it's base-2 samples and can curve-fit to less than full cycle
decimation = 2**int(np.floor(np.log2(pnts_per_sample)))
self.pnts_per_CPDpix = int(self.N_points_per_pixel/decimation)
remainder = 0
else:
# old approach, but add section for missing period at the end
decimation = int(np.floor(pnts_per_sample))
self.pnts_per_CPDpix = int(self.N_points_per_pixel/decimation)
remainder = self.N_points_per_pixel - self.pnts_per_CPDpix*decimation
# second degree polynomial fitting
deg = 2
# deg = 1
# Holds all the fit parameters
self.wHfit3 = np.zeros((1, self.pnts_per_CPDpix, deg+1))
for p in range(self.pnts_per_CPDpix-min(1,remainder)):
resp = np.float32(self.signal[decimation*p:decimation*(p+1)])
resp = resp-np.mean(resp)
V_per_osc = self.pixel_ex_wfm[decimation*p:decimation*(p+1)]
popt, _ = np.polynomial.polynomial.polyfit(V_per_osc, resp, deg, full=True)
self.wHfit3[0,p,:] = popt
if remainder > 0:
resp = np.float32(self.signal[(self.pnts_per_CPDpix-1)*decimation:])
resp = (resp-np.mean(resp))
V_per_osc = self.pixel_ex_wfm[(self.pnts_per_CPDpix-1)*decimation:]
popt, _ = np.polynomial.polynomial.polyfit(V_per_osc, resp, deg, full=True)
self.wHfit3[0,-1,:] = popt
self.CPD = -0.5*np.divide(self.wHfit3[:,:,1],self.wHfit3[:,:,2])[0,:]
# self.CPD = self.wHfit3[:,:,1][0,:]
return
def smooth(self, kernel):
self.CPD_filt = np.convolve(self.CPD, kernel, mode='valid')
return
<file_sep>/setup.py
from setuptools import setup, find_packages
from os import path
this_directory = path.abspath(path.dirname(__file__))
with open(path.join(this_directory, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='FFTA',
version='0.3.0',
description='Fast Free Transient Analysis',
long_description=long_description,
long_description_content_type='text/markdown',
author='<NAME>',
author_email='<EMAIL>',
license='MIT',
url='https://github.com/rajgiriUW/ffta/',
packages=find_packages(exclude=['xop', 'docs', 'data', 'notebooks']),
install_requires=['numpy>=1.18.1',
'scipy>=1.4.1',
'igor>=0.3',
'numexpr>=2.7.1',
'watchdog>=0.10.2',
'pyUSID>=0.0.8',
'pycroscopy>=0.60',
'pywavelets>=1.1.1'],
# entry_points={
# 'console_scripts': [
# 'ffta-analyze = ffta.analyze:main',
# ],
# },
)
<file_sep>/ffta/simulation/electric_drive.py
"""simulate.py: Contains Cantilever class."""
# pylint: disable=E1101,R0902,C0103
__author__ = "<NAME>"
__copyright__ = "Copyright 2020, Ginger Lab"
__email__ = "<EMAIL>"
__status__ = "Production"
import numpy as np
from scipy.integrate import odeint
from .cantilever import Cantilever
from . import excitation
# Set constant 2 * pi.
PI2 = 2 * np.pi
class ElectricDrive(Cantilever):
"""Damped Driven Harmonic Oscillator Simulator for AFM Cantilevers under Electric drive
Simulates a DDHO under excitation with given parameters.
Parameters
----------
can_params : dict
Parameters for cantilever properties. See Cantilever
force_params : dict
Parameters for forces. The dictionary contains:
es_force = float (in N)
delta_freq = float (in Hz)
tau = float (in seconds)
v_dc = float (in Volts)
v_ac = float (in Volts)
v_cpd = float (in Volts)
dCdz = float (in F/m)
sim_params : dict
Parameters for simulation. The dictionary contains:
trigger = float (in seconds)
total_time = float (in seconds)
sampling_rate = int (in Hz)
v_array : ndarray, optional
If provided, supplies the time-dependent voltage to v_cpd
v_array must be the exact length and sampling of the desired signal
v_array only functionally does anything after the trigger.
v_step : float, optional
If v_array not supplied, then a voltage of v_step is applied at the trigger
Attributes
----------
amp : float
Amplitude of the cantilever in meters.
beta : float
Damping factor of the cantilever in rad/s.
delta : float
Initial phase of the cantilever in radians.
delta_freq : float
Frequency shift of the cantilever under excitation.
mass : float
Mass of the cantilever in kilograms.
Method
------
simulate(trigger_phase=180)
Simulates the cantilever motion with excitation happening
at the given phase.
See Also
--------
pixel: Pixel processing for FF-trEFM data.
Cantilever: base class
Examples
--------
>>> from ffta.simulation import electric_drive, load
>>>
>>> params_file = '../examples/sim_params.cfg'
>>> params = load.simulation_configuration(params_file)
>>>
>>> c = electric_drive.ElectricDrive(*params)
>>> Z, infodict = c.simulate()
>>> c.analyze()
>>> c.analyze(roi=0.004) # can change the parameters as desired
>>>
>>> # To supply an arbitary v_array
>>> n_points = int(params[2]['total_time'] * params[2]['sampling_rate'])
>>> v_array = np.ones(n_points) # create just a flat excitation
>>> c = mechanical_dirve.MechanicalDrive(*params, v_array = v_array)
>>> Z, _ = c.simulate()
>>> c.analyze()
>>>
>>> # To supply an arbitary voltage step
>>> step = -7 #-7 Volt step
>>> c = mechanical_dirve.MechanicalDrive(*params, v_step = step)
>>> Z, _ = c.simulate()
>>> c.analyze()
"""
def __init__(self, can_params, force_params, sim_params, v_array=[], v_step=np.nan,
func=excitation.single_exp, func_args=[]):
parms = [can_params, force_params, sim_params]
super(ElectricDrive, self).__init__(*parms)
# Did user supply a voltage pulse themselves (Electrical drive only)
self.use_varray = False
self.use_vstep = False
if any(v_array):
if len(v_array) != int(self.total_time * self.sampling_rate):
raise ValueError('v_array must match sampling rate/length of parameters')
else:
self.use_varray = True
self.v_array = v_array
self.scale = [np.max(v_array) - np.min(v_array), np.min(v_array)]
if not np.isnan(v_step):
self.v_step = v_step # if applying a single DC step
self.use_vstep = True
self.func = func
self.func_args = func_args
# default case set a single tau for a single exponential function
if not np.any(func_args):
self.func_args = [self.tau]
try:
_ = self.func(0, *self.func_args)
except:
print('Be sure to correctly set func_args=[params]')
return
return
def __gamma__(self, t):
"""
Controls how the cantilever behaves after a trigger.
Default operation is an exponential decay to omega0 - delta_freq with
time constant tau.
If supplying an explicit v_array, then this function will call the values
in that array
Parameters
----------
t : float
Time in seconds.
Returns
-------
value : float
Value of the function at the given time.
"""
p = int(t * self.sampling_rate)
n_points = int(self.total_time * self.sampling_rate)
t0 = self.t0
if t >= t0:
if not self.use_varray:
return self.func(t - t0, *self.func_args)
else:
_g = self.v_array[p] if p < n_points else self.v_array[-1]
_g = (_g - self.scale[1]) / self.scale[0]
return _g
else:
return 0
def omega(self, t, t0, tau):
"""
Exponentially decaying resonance frequency.
Parameters
----------
t : float
Time in seconds.
t0: float
Event time in seconds.
tau : float
Decay constant in the exponential function, in seconds.
Returns
-------
w : float
Resonance frequency of the cantilever at a given time, in rad/s.
"""
return self.w0 + self.delta_w * self.__gamma__(t)
def dc_step(self, t, t0):
"""
Adds a DC step at the trigger point for electrical drive simulation
Parameters
----------
t : float
Time in seconds.
t0: float
Event time in seconds.
"""
if t > t0:
return self.v_step
else:
return self.v_dc
def force(self, t, t0, tau):
"""
Force on the cantilever at a given time. It contains driving force and
electrostatic force.
Parameters
----------
t : float
Time in seconds.
t0: float
Event time in seconds.
tau : float
Decay constant in the exponential function, in seconds.
Returns
-------
f : float
Force on the cantilever at a given time, in N/kg.
"""
# explicitly define voltage at each time step
if self.use_varray:
p = int(t * self.sampling_rate)
n_points = int(self.total_time * self.sampling_rate)
_g = self.v_array[p] if p < n_points else self.v_array[-1]
driving_force = 0.5 * self.dCdz / self.mass * ((_g - self.v_cpd) \
+ self.v_ac * np.sin(self.wd * t)) ** 2
else: # single voltage step
driving_force = 0.5 * self.dCdz / self.mass * ((self.dc_step(t, t0) - self.v_cpd) \
+ self.v_ac * np.sin(self.wd * t)) ** 2
return driving_force
def set_conditions(self, trigger_phase=180):
"""
Sets initial conditions and other simulation parameters. Using 2w given
the squared term in electric driving
Parameters
----------
trigger_phase: float, optional
Trigger phase is in degrees and wrt cosine. Default value is 180.
"""
self.delta = np.abs(np.arctan(np.divide(2 * (2 * self.wd) * self.beta,
self.w0 ** 2 - (2 * self.wd) ** 2)))
self.trigger_phase = np.mod(np.pi * trigger_phase / 180, PI2)
self.n_points = int(self.total_time * self.sampling_rate)
# Add extra cycles to the simulation to find correct phase at trigger.
cycle_points = int(2 * self.sampling_rate / self.res_freq)
self.n_points_sim = cycle_points + self.n_points
# Create time vector and find the trigger wrt phase.
self.t = np.arange(self.n_points_sim) / self.sampling_rate
# Current phase at trigger.
current_phase = np.mod(self.wd * self.trigger - self.delta, PI2)
phase_diff = np.mod(self.trigger_phase - current_phase, PI2)
self.t0 = self.trigger + phase_diff / self.wd # modified trigger point
# Set the initial conditions at t=0.
z0 = self.amp * np.sin(-self.delta)
v0 = self.amp * self.wd * np.cos(-self.delta)
self.Z0 = np.array([z0, v0])
return
<file_sep>/XOP/trEFMAnalysisPackage.cpp
#include <FPGAHeader.h>
#include <NiFpga.h>
#include <XOPStandardHeaders.h> // Include ANSI headers, Mac headers, IgorXOP.h, XOP.h and XOPSupport.h
#include "trEFMAnalysisPackage.h"
#include <NiFpga_125MSAcquire.h>
#include <chrono>
#include "Python.h"
// Global Variables
static int gCallSpinProcess = 1; // Set to 1 to all user abort (cmd dot) and background processing.
//////// HELPER FUNCTIONS TO BE USED BY THE XOP FUNCTIONS \\\\\\\\\\
////////////////////////////////////////////////////////////////////
/*
Transfer the data from a 2d array represented by a pointer-to-pointer type to a wave already existing
in IGOR. The size of data MUST match the size of wave or you will be in trouble, mister.
*/
void TransferToIgor(waveHndl wave, double** data)
{
int result,result2;
int waveType;
double *dp0, *dcp, *dp;
CountInt numRows, numColumns, numLayers;
int numDimensions;
CountInt dimensionSizes[MAX_DIMENSIONS + 1];
BCInt numBytes;
double* dPtr;
MDGetWaveDimensions(wave, &numDimensions, dimensionSizes);
numRows = dimensionSizes[0];
numColumns = dimensionSizes[1];
numLayers = 0;
numBytes = WavePoints(wave) * sizeof(double); // Bytes needed for copy
dPtr = (double*)NewPtr(numBytes);
MDGetDPDataFromNumericWave(wave, dPtr); // Get a copy of the wave data.
result = 0;
dp0 = dPtr;
// Pointer to start of data for this layer.
for (int column = 0; column < 1; column++) {
if (gCallSpinProcess && SpinProcess()) { // Spins cursor and allows background processing.
result = -1; // User aborted.
break;
}
dcp = dp0 + column*numRows; // Pointer to start of data for this column.
for (int row = 0; row < numRows; row++) {
dp = dcp + row;
*dp = (double)data[row][column];
}
}
MDStoreDPDataInNumericWave(wave, dPtr); // Store copy in the wave.
DisposePtr((Ptr)dPtr);
WaveHandleModified(wave);
}
//////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////
#pragma pack(2) // All structures passed to Igor are two-byte aligned
struct AnalysisConfigParams {
double result;
};
typedef struct AnalysisConfigParams AnalysisConfigParams;
#pragma pack() // Reset structure alignment to default.
extern "C" int
AnalysisConfig(AnalysisConfigParams* p)
{
char noticeStr[50];
waveHndl ConfigHandlePtr; // Place to put waveHndl for new wave
char* AcquisitionWaveName = "PIXELCONFIG\0"; // C string containing name of Igor wave
int SetCurrentDataFolder(DataFolderHandle dataFolderH);
long refNum = 0;
int result = 0;
DataFolderHandle rootDataFolderHPtr;
DataFolderHandle packageDataFolderH;
DataFolderHandle currentFolderH;
char* newDataFolderName;
DataFolderHandle newDataFolderHPtr;
waveHndl AcquisitionHandlePtr; // Place to put waveHndl for new wave
int FolderID;
int WaveType = NT_I32;
GetCurrentDataFolder(¤tFolderH);
newDataFolderName = "Analysis Config\0";
if (result = GetRootDataFolder(0, &rootDataFolderHPtr))
{
return result;
}
if (result = GetNamedDataFolder(rootDataFolderHPtr, ":packages:", &packageDataFolderH))
{
result = NewDataFolder(rootDataFolderHPtr, newDataFolderName, &newDataFolderHPtr);
}
else {
result = NewDataFolder(packageDataFolderH, newDataFolderName, &newDataFolderHPtr);
}
GetDataFolderIDNumber(newDataFolderHPtr, &FolderID);
SetCurrentDataFolder(newDataFolderHPtr);
if (result = MakeWave(&AcquisitionHandlePtr, AcquisitionWaveName, 7, NT_FP64, 0))
{
return result;
}
BCInt numBytes;
double* dPtr;
numBytes = WavePoints(AcquisitionHandlePtr) * sizeof(double); // Bytes needed for copy
dPtr = (double*)NewPtr(numBytes);
dPtr[0] = 5e-4;
dPtr[1] = 1e-3;
dPtr[2] = 10e6;
dPtr[3] = 300e3;
dPtr[4] = 1;
dPtr[5] = 1;
dPtr[6] = 10e3;
MDStoreDPDataInNumericWave(AcquisitionHandlePtr, dPtr); // Store copy in the wave.
DisposePtr((Ptr)dPtr);
MDSetDimensionLabel(AcquisitionHandlePtr, 0, 0, "trigger\0");
MDSetDimensionLabel(AcquisitionHandlePtr, 0, 1, "total_time\0");
MDSetDimensionLabel(AcquisitionHandlePtr, 0, 2, "sampling_rate\0");
MDSetDimensionLabel(AcquisitionHandlePtr, 0, 3, "drive_freq\0");
MDSetDimensionLabel(AcquisitionHandlePtr, 0, 4, "window\0");
MDSetDimensionLabel(AcquisitionHandlePtr, 0, 5, "bandpass_filter\0");
MDSetDimensionLabel(AcquisitionHandlePtr, 0, 6, "filter_bandwidth\0");
SetCurrentDataFolder(currentFolderH);
return result;
}
#pragma pack(2) // All structures passed to Igor are two-byte aligned
struct AnalyzeLineParams {
waveHndl data_wave; // data collected goes here
double recordLength;
double preTriggerSamples;
double numRecords;
double numOfPixels;
waveHndl tfp_wave;
waveHndl shift_wave;
waveHndl config_wave;
double result;
};
typedef struct AnalyzeLineParams AnalyzeLineParams;
#pragma pack() // Reset structure alignment to default.
extern "C" int
AnalyzeLine(AnalyzeLineParams* p)
{
int averages = 15;
int result = 0;
int numOfPixels = (int)p->numOfPixels;
char noticeStr[50];
waveHndl wavH = p->data_wave;
waveHndl tfp_wave = p->tfp_wave;
waveHndl shift_wave = p->shift_wave;
waveHndl config_wave = p->config_wave;
double trigger;
double total_time;
double sampling_rate;
double drive_freq;
double window;
double bandpass_filter;
double filter_bandwidth;
uint32_t numRecords = (uint32_t)p->numRecords;
uint32_t recordLength = (uint32_t)p->recordLength;
int32_t preTriggerSamples = (int32_t)p->preTriggerSamples;
double* configPtr;
// Get Analysis settings from configuration wave.
BCInt numBytes;
configPtr = (double*)NewPtr(numBytes);
MDGetDPDataFromNumericWave(config_wave, configPtr);
trigger = configPtr[0];
total_time = configPtr[1];
sampling_rate = configPtr[2];
drive_freq = configPtr[3];
window = configPtr[4];
bandpass_filter = configPtr[5];
filter_bandwidth = configPtr[6];
/*
#
# HERE WE DO EVERYTHING WE NEED TO DO IN ORDER TO FILL A WAVE WITH TFP DATA.
#
*/
double tfp, shift;
tfp = 0.0;
shift = 0.0;
// Acquire deflection data using NI 5762 FPGA digitizer
double** data = FPGAAcquireData(numRecords, recordLength, preTriggerSamples);
// set up tfp data
double** tfp_data;
double** shift_data;
const int nrow = (int)numOfPixels, ncol = 1, nelem = nrow*ncol;
tfp_data = new double*[nrow];
shift_data = new double*[nrow];
tfp_data[0] = new double[nelem];
shift_data[0] = new double[nelem];
for (int i = 1; i < nrow; i++)
{
tfp_data[i] = tfp_data[i - 1] + ncol;
shift_data[i] = shift_data[i - 1] + ncol;
}
// Temp storage for data in one pixel.
double** temp_data;
const int temp_nrow = (int)recordLength, temp_ncol = averages, temp_nelem = temp_nrow*temp_ncol;
temp_data = new double*[temp_nrow];
temp_data[0] = new double[temp_nelem];
for (int i = 1; i < temp_nrow; i++)
{
temp_data[i] = temp_data[i - 1] + temp_ncol;
}
// Analyze each pixel in the line and get the tfp data
for (int pixel = 0; pixel < numOfPixels; pixel++)
{
int temp_column = 0;
for (int column = pixel*averages; column < (pixel*averages + averages) ; column++)
{
int temp_row = 0;
for (int row = 0; row < recordLength; row++)
{
temp_data[temp_row][temp_column] = data[row][column];
temp_row++;
}
temp_column++;
}
AnalyzePixel(&tfp, &shift, trigger, total_time, sampling_rate, drive_freq, window, bandpass_filter, filter_bandwidth, temp_data, recordLength, averages);
tfp_data[pixel][0] = tfp;
shift_data[pixel][0] = shift;
}
DisposePtr((Ptr)configPtr);
/* BEGIN TRANSFER OF DATA TO IGOR HERE.*/
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TransferToIgor(tfp_wave, tfp_data);
TransferToIgor(shift_wave, shift_data);
TransferToIgor(wavH, data);
delete[] data[0];
delete[] data;
delete[] tfp_data[0];
delete[] tfp_data;
delete[] shift_data[0];
delete[] shift_data;
delete[] temp_data;
return result;
}
#pragma pack(2) // All structures passed to Igor are two-byte aligned
struct AnalyzeLineOfflineParams {
waveHndl w; // handle to igor wave containing data.
waveHndl tfpWave;
waveHndl shiftWave;
double averages;
waveHndl config_wave;
double result;
};
typedef struct AnalyzeLineParams AnalyzeLineParams;
#pragma pack() // Reset structure alignment to default.
extern "C" int
AnalyzeLineOffline(AnalyzeLineOfflineParams* p)
{
int averages = (int)p->averages;
char noticeStr[50];
waveHndl wavH = p->w;
waveHndl tfpWave = p->tfpWave;
waveHndl shiftWave = p->shiftWave;
waveHndl config_wave = p->config_wave;
double trigger;
double total_time;
double sampling_rate;
double drive_freq;
double window;
double bandpass_filter;
double filter_bandwidth;
double* configPtr;
int numRows, numColumns;
int result;
// Get Analysis settings from configuration wave.
BCInt numBytes;
configPtr = (double*)NewPtr(numBytes);
MDGetDPDataFromNumericWave(config_wave, configPtr);
trigger = configPtr[0];
total_time = configPtr[1];
sampling_rate = configPtr[2];
drive_freq = configPtr[3];
window = configPtr[4];
bandpass_filter = configPtr[5];
filter_bandwidth = configPtr[6];
double tfp, shift;
tfp = 0.0;
shift = 0.0;
// Acquire data from Igor
double** data = ImportDataFromIgor(wavH,&numRows,&numColumns);
int numOfPixels = (int)(numColumns / averages);
// set up tfp and shift data pointers
double** tfp_data;
double** shift_data;
const int nrow = (int)(numColumns / averages), ncol = 1, nelem = nrow*ncol;
tfp_data = new double*[nrow];
tfp_data[0] = new double[nelem];
shift_data = new double*[nrow];
shift_data[0] = new double[nelem];
for (int i = 1; i < nrow; i++)
{
tfp_data[i] = tfp_data[i - 1] + ncol;
shift_data[i] = shift_data[i - 1] + ncol;
}
// For each pixel, create an array npoints X nAverages to store the data for a single pixel.
// This data is then analyzed by calling the Python package, and a TFP value is stored and transfered
// to igor.
double** temp_data;
const int temp_nrow = (int)numRows, temp_ncol = averages, temp_nelem = temp_nrow*temp_ncol;
temp_data = new double*[temp_nrow];
temp_data[0] = new double[temp_nelem];
for (int i = 1; i < temp_nrow; i++)
{
temp_data[i] = temp_data[i - 1] + temp_ncol;
}
for (int pixel = 0; pixel < numOfPixels; pixel++)
{
int temp_column = 0;
for (int column = pixel*averages; column < (pixel*averages + averages); column++)
{
int temp_row = 0;
for (int row = 0; row < numRows; row++)
{
temp_data[temp_row][temp_column] = data[row][column];
temp_row++;
}
temp_column++;
}
AnalyzePixel(&tfp, &shift, trigger, total_time, sampling_rate, drive_freq, window, bandpass_filter, filter_bandwidth, temp_data, numRows, averages);
tfp_data[pixel][0] = tfp;
shift_data[pixel][0] = shift;
}
DisposePtr((Ptr)configPtr);
delete[] temp_data[0];
delete[] temp_data;
delete[] data[0];
delete[] data;
/* BEGIN TRANSFER OF DATA TO IGOR HERE.*/
TransferToIgor(tfpWave, tfp_data);
TransferToIgor(shiftWave, shift_data);
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
delete[] tfp_data[0];
delete[] tfp_data;
delete[] shift_data[0];
delete[] shift_data;
return 0;
}
/* RegisterFunction()
Igor calls this at startup time to find the address of the
XFUNCs added by this XOP. See XOP manual regarding "Direct XFUNCs".
*/
static XOPIORecResult
RegisterFunction()
{
int funcIndex;
funcIndex = (int)GetXOPItem(0); // Which function is Igor asking about?
switch (funcIndex) {
case 0: // WAGetWaveInfo(wave)
return (XOPIORecResult)AnalysisConfig;
break;
case 1: // WAGetWaveInfo(wave)
return (XOPIORecResult)AnalyzeLine;
break;
case 2:
return (XOPIORecResult)AnalyzeLineOffline;
break;
}
return 0;
}
/* DoFunction()
Igor calls this when the user invokes one if the XOP's XFUNCs
if we returned NIL for the XFUNC from RegisterFunction. In this
XOP, we always use the direct XFUNC method, so Igor will never call
this function. See XOP manual regarding "Direct XFUNCs".
*/
static int
DoFunction()
{
int funcIndex;
void *p; // Pointer to structure containing function parameters and result.
int err;
funcIndex = (int)GetXOPItem(0); // Which function is being invoked ?
p = (void*)GetXOPItem(1); // Get pointer to params/result.
switch (funcIndex) {
case 0:
err = AnalysisConfig((AnalysisConfigParams*)p);
break;
case 1: // WAGetWaveInfo(wave)
err = AnalyzeLine((AnalyzeLineParams*)p);
break;
case 2: // WAGetWaveInfo(wave)
err = AnalyzeLineOffline((AnalyzeLineOfflineParams*)p);
break;
}
return(err);
}
/* XOPEntry()
This is the entry point from the host application to the XOP for all messages after the
INIT message.
*/
extern "C" void
XOPEntry(void)
{
XOPIORecResult result = 0;
switch (GetXOPMessage()) {
case FUNCTION: // Our external function being invoked ?
result = DoFunction();
break;
case FUNCADDRS:
result = RegisterFunction();
break;
}
SetXOPResult(result);
}
/* main(ioRecHandle)
This is the initial entry point at which the host application calls XOP.
The message sent by the host must be INIT.
main() does any necessary initialization and then sets the XOPEntry field of the
ioRecHandle to the address to be called for future messages.
*/
HOST_IMPORT int
main(IORecHandle ioRecHandle)
{
XOPInit(ioRecHandle); // Do standard XOP initialization.
SetXOPEntry(XOPEntry); // Set entry point for future calls.
if (igorVersion < 600) { // Requires Igor Pro 6.00 or later.
SetXOPResult(OLD_IGOR); // OLD_IGOR is defined in trEFMAnalysisInterface.h and there are corresponding error strings in trEFMAnalysisInterface.r and trEFMAnalysisInterfaceWinCustom.rc.
return EXIT_FAILURE;
}
SetXOPResult(0L);
return EXIT_SUCCESS;
}
<file_sep>/ffta/acquisition/polling.py
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 22 12:45:01 2020
@author: Raj
"""
'''
Script to constantly poll a folder of data and generate an image from that
USAGE:
Open Anaconda prompt
Navigate to folder where this file is located
python polling.py "FOLDER WHERE DATA ARE BEING SAVED"
'''
import time
import numpy as np
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
from ffta import line, pixel_utils
from matplotlib import pyplot as plt
import argparse
import pyUSID as usid
class MyHandler(FileSystemEventHandler):
'''
Event Handler for polling the FFtrEFM directory for new files
Every time a new file is created, this processes that .ibw as a Line
Parameters
----------
parameters : dict
Dictionary of the processing parameters. Found in parameters.cfg
lines : int
how many lines are expected in this image
n_pixels : int
how many pixels are in each line
wait_per_line : int
The number of seconds to wait after a new file event (avoids OS errors)
'''
def __init__(self, parameters, wait_per_line=5):
'''
Increments lines_loaded every time a new file is corrected
This method provides a (crude) flag for checking when to stop
'''
self.lines_loaded = 0
self.loaded = False
self.parameters = parameters
self.lines = parameters['lines_per_image']
self.n_pixels = parameters['n_pixels']
self.wait_per_line = int(wait_per_line)
# initialize the FFtrEFM line data
self.tfp = np.empty(n_pixels)
self.shift = np.empty(n_pixels)
def on_created(self, event):
'''
When it detects a new file is there, processes the line then saves
the tfp and shift data. The processes instananeous frequency are not
saved as this is a live imaging method
'''
if not event.is_directory:
self.loaded = True
time.sleep(self.wait_per_line)
path = event.src_path.split('\\')
signal = pixel_utils.load.signal(event.src_path)
this_line = line.Line(signal, self.parameters, self.n_pixels)
self.tfp, self.shift, _ = this_line.analyze()
print('Analyzed', path[-1], 'tFP avg =', np.mean(self.tfp),
' s; shift =', np.mean(self.shift), 'Hz')
self.loaded = False
self.lines_loaded += 1
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('path', help='Path where data are being saved')
path_to_watch = parser.parse_args().path
print('Loading data from ', path_to_watch)
params_file = path_to_watch + r'\parameters.cfg'
n_pixels, parameters = pixel_utils.load.configuration(params_file)
lines = parameters['lines_per_image']
print('Pixels = ', n_pixels)
print('Lines = ', lines)
# tfp = np.random.randn(lines, n_pixels)
# shift = np.random.randn(lines, n_pixels)
tfp = np.zeros([lines, n_pixels])
shift = np.zeros([lines, n_pixels])
# initialize event handler
my_observer = Observer()
my_event_handler = MyHandler(parameters)
my_observer.schedule(my_event_handler, path_to_watch, recursive=False)
my_observer.start()
# initialize plotting
plt.ion()
fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(12, 6), tight_layout=True, facecolor='white')
tfp_ax = ax[0]
shift_ax = ax[1]
plt.setp(tfp_ax.get_xticklabels(), visible=False)
plt.setp(tfp_ax.get_yticklabels(), visible=False)
plt.setp(shift_ax.get_xticklabels(), visible=False)
plt.setp(shift_ax.get_yticklabels(), visible=False)
tfp_ax.set_title('tFP Image!')
shift_ax.set_title('Shift Image')
kwargs = {'origin': 'lower', 'x_vec': parameters['FastScanSize'] * 1e6,
'y_vec': parameters['SlowScanSize'] * 1e6, 'num_ticks': 5, 'stdevs': 3}
tfp_image, cbar_tfp = usid.viz.plot_utils.plot_map(tfp_ax, tfp,
cmap='inferno', show_cbar=False, **kwargs)
shift_image, cbar_sh = usid.viz.plot_utils.plot_map(shift_ax, shift,
cmap='inferno', show_cbar=False, **kwargs)
# kwargs = {'origin': 'lower', 'aspect': 'equal'}
#
# tfp_image = tfp_ax.imshow(tfp * 1e6, cmap='afmhot', **kwargs)
# shift_image = shift_ax.imshow(shift, cmap='inferno', **kwargs)
#
# tfp_sc = tfp[tfp.nonzero()] * 1e6
# tfp_image.set_clim(vmin=tfp_sc.min(), vmax=tfp_sc.max())
#
# shift_sc = shift[shift.nonzero()]
# shift_image.set_clim(vmin=shift_sc.min(), vmax=shift_sc.max())
text = plt.figtext(0.4, 0.1, '')
text = tfp_ax.text(n_pixels / 2, lines + 3, '')
plt.show()
# event handling loop
try:
while my_event_handler.lines_loaded < lines:
time.sleep(1)
if my_event_handler.loaded:
tfp[my_event_handler.lines_loaded, :] = my_event_handler.tfp[:]
shift[my_event_handler.lines_loaded, :] = my_event_handler.shift[:]
# tfp_image = tfp_ax.imshow(tfp * 1e6, cmap='afmhot', **kwargs)
# shift_image = shift_ax.imshow(shift, cmap='inferno', **kwargs)
tfp_image, _ = usid.viz.plot_utils.plot_map(tfp_ax, tfp,
cmap='inferno', show_cbar=False, **kwargs)
shift_image, _ = usid.viz.plot_utils.plot_map(shift_ax, shift,
cmap='inferno', show_cbar=False, **kwargs)
# tfp_sc = tfp[tfp.nonzero()]
# tfp_image.set_clim(vmin=tfp_sc.min(), vmax=tfp_sc.max())
#
# shift_sc = shift[shift.nonzero()]
# shift_image.set_clim(vmin=shift_sc.min(), vmax=shift_sc.max())
# plt.draw()
fig.canvas.draw_idle()
plt.pause(0.0001)
except KeyboardInterrupt:
my_observer.stop()
my_observer.join()
print('Lines loaded = ', my_event_handler.lines_loaded)
plotname = path_to_watch + r'\tfp_image.png'
plt.savefig(plotname)
my_observer.stop()
my_observer.join()
<file_sep>/ffta/load/__init__.py
from . import get_utils
from . import gl_ibw
from . import load_hdf
from . import load_ringdown
from . import load_commands
__all__ = ['get_utils']<file_sep>/ffta/analysis/filtering.py
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 26 17:15:36 2018
@author: Raj
"""
import pycroscopy as px
from pycroscopy.processing.fft import FrequencyFilter
import pyUSID as usid
import numpy as np
from scipy import signal as sps
from ffta.load import get_utils
from ffta import pixel
from matplotlib import pyplot as plt
import warnings
'''
For filtering data using the pycroscopy filter command
To set up a filter, you can choose any of the following:
Harmonic Filter: pick a frequency and bandpass filters that + 2w + 3e etc
Bandpass Filter: pick a specific frequency and pass that
Lowpass Filter: pick a frequency and pass all below that
Noise Filter: pick frequencies to selectively remove (like electrical noise, etc)
# a harmonic filter center of 2000 points long at 100kHz and 2*100 kHz, with a 5000 Hz wide window, at 1 MHz sampling
>>> hbf = px.processing.fft.HarmonicPassFilter(2000, 10e6, 100e3, 5000, 2)
>>> ffta.hdf_utils.filtering.test_filter(h5_main, hbf) #will display the result before applying to the whole dataset
>>> ffta.hdf_utils.filtering.fft_filter(h5_main, hbf)
'''
def test_filter(hdf_file, freq_filts, parameters={}, pixelnum=[0, 0], noise_tolerance=5e-7,
show_plots=True, check_filter=True):
"""
Applies FFT Filter to the file at a specific line and displays the result
Parameters
----------
hdf_file : h5Py file or Nx1 NumPy array (preferred is NumPy array)
hdf_file to work on, e.g. hdf.file['/FF-raw'] if that's a Dataset
if ndarray, uses passed or default parameters
Use ndarray.flatten() to ensure correct dimensions
freq_filts : list of FrequencyFilter class objects
Contains the filters to apply to the test signal
parameters : dict, optional
Contains parameters in FF-raw file for constructing filters. Automatic if a Dataset/File
Must contain num_pts and samp_rate to be functional
pixelnum : int, optional
For extracting a specific pixel to do FFT Filtering on
show_plots : bool, optional
Turns on FFT plots from Pycroscopy
noise_tolerance : float 0 to 1
Amount of noise below which signal is set to 0
Returns
-------
filt_line : numpy.ndarray
Filtered signal of hdf_file
freq_filts : list
The filter parameters to be passed to SignalFilter
fig_filt, axes_filt: matplotlib controls
Only functional if show_plots is on
"""
reshape = False
ftype = str(type(hdf_file))
if ('h5py' in ftype) or ('Dataset' in ftype): # hdf file
parameters = get_utils.get_params(hdf_file)
hdf_file = get_utils.get_pixel(hdf_file, [pixelnum[0], pixelnum[1]], array_form=True, transpose=False)
hdf_file = hdf_file.flatten()
if len(hdf_file.shape) == 2:
reshape = True
hdf_file = hdf_file.flatten()
sh = hdf_file.shape
# Test filter on a single line:
filt_line, fig_filt, axes_filt = px.processing.gmode_utils.test_filter(hdf_file,
frequency_filters=freq_filts,
noise_threshold=noise_tolerance,
show_plots=show_plots)
# If need to reshape
if reshape:
filt_line = np.reshape(filt_line, sh)
# Test filter out in Pixel
if check_filter:
plt.figure()
plt.plot(hdf_file, 'b')
plt.plot(filt_line, 'k')
h5_px_filt = pixel.Pixel(filt_line, parameters)
h5_px_filt.clear_filter_flags()
h5_px_filt.analyze()
h5_px_filt.plot(newplot=True)
h5_px_raw = pixel.Pixel(hdf_file, parameters)
h5_px_raw.analyze()
h5_px_raw.plot(newplot=True)
# h5_px_raw_unfilt = pixel.Pixel(hdf_file, parameters)
# h5_px_raw_unfilt.clear_filter_flags()
# h5_px_raw_unfilt.analyze()
# h5_px_raw_unfilt.plot(newplot=False,c1='y', c2='c')
return filt_line, freq_filts, fig_filt, axes_filt
def fft_filter(h5_main, freq_filts, noise_tolerance=5e-7, make_new=False, verbose=False):
"""
Stub for applying filter above to the entire FF image set
Parameters
----------
h5_main : h5py.Dataset object
Dataset to work on, e.g. h5_main = px.hdf_utils.getDataSet(hdf.file, 'FF_raw')[0]
freq_filts : list
List of frequency filters usually generated in test_line above
noise_tolerance : float, optional
Level below which data are set to 0. Higher values = more noise (more tolerant)
make_new : bool, optional
Allows for re-filtering the data by creating a new folder
Returns
-------
h5_filt : Dataset
Filtered dataset within latest -FFT_Filtering Group
"""
h5_filt_grp = usid.hdf_utils.check_for_old(h5_main, 'FFT_Filtering')
if make_new == True or not any(h5_filt_grp):
sig_filt = px.processing.SignalFilter(h5_main, frequency_filters=freq_filts,
noise_threshold=noise_tolerance,
write_filtered=True, write_condensed=False,
num_pix=1, verbose=verbose, cores=2, max_mem_mb=512)
h5_filt_grp = sig_filt.compute()
else:
print('Taking previously computed results')
h5_filt = h5_filt_grp[0]['Filtered_Data']
h5_filt = h5_filt_grp['Filtered_Data']
usid.hdf_utils.copy_attributes(h5_main.parent, h5_filt)
usid.hdf_utils.copy_attributes(h5_main.parent, h5_filt.parent)
return h5_filt
def lowpass(hdf_file, parameters={}, pixelnum=[0, 0], f_cutoff=None):
'''
Interfaces to px.pycroscopy.fft.LowPassFilter
:param hdf_file:
:param parameters:
:param pixelnum:
See test_filter below
:param f_cutoff: int
frequency to cut off. Defaults to 2*drive frequency rounded to nearest 100 kHz
'''
hdf_file, num_pts, drive, samp_rate = _get_pixel_for_filtering(hdf_file, parameters, pixelnum)
if not f_cutoff:
lpf_cutoff = np.round(drive / 1e5, decimals=0) * 2 * 1e5 # 2times the drive frequency, round up
lpf = px.processing.fft.LowPassFilter(num_pts, samp_rate, lpf_cutoff)
return lpf
def bandpass(hdf_file, parameters={}, pixelnum=[0, 0], f_center=None, f_width=10e3, harmonic=None, fir=False):
'''
Interfaces to pycroscopy.processing.fft.BandPassFilter
Note that this is effectively a Harmonic Filter of number_harmonics 1, but with finite impulse response option
:param hdf_file:
:param parameters:
:param pixelnum:
See test_filter below
:param f_center: int
center frequency for the specific band to pass
:param f_width: int
width of frequency to pass
:param harmonic: int
if specified, sets the band to this specific multiple of the drive frequency
:param fir: bool
uses an Finite Impulse Response filter instead of a normal boxcar
'''
hdf_file, num_pts, drive, samp_rate = _get_pixel_for_filtering(hdf_file, parameters, pixelnum)
# default is the 2*w signal (second harmonic for KPFM)
if not f_center:
if not harmonic:
f_center = drive * 2
else:
f_center = int(drive * harmonic)
bpf = px.processing.fft.BandPassFilter(num_pts, samp_rate, f_center, f_width, fir=fir)
return bpf
def harmonic(hdf_file, parameters={}, pixelnum=[0, 0], first_harm=1, bandwidth=None, num_harmonics=5):
'''
Interfaces with px.processing.fft.HarmonicFilter
Parameters
----------
hdf_file, parameters, pixelnum : see comments in test_filter below
first_harm : int
The first harmonic based on the drive frequency to use
For G-KPFM this should be explicitly set to 2
bandwidth : int
bandwidth for filtering. For computational purposes this is hard-set to 2500 (2.5 kHz)
num_harmonics : int
The number of harmonics to use (omega, 2*omega, 3*omega, etc)
'''
hdf_file, num_pts, drive, samp_rate = _get_pixel_for_filtering(hdf_file, parameters, pixelnum)
if not bandwidth:
bandwidth = 2500
elif bandwidth > 2500:
warnings.warn('Bandwidth of that level might cause errors')
bandwidth = 2500
first_harm = drive * first_harm
hbf = px.processing.fft.HarmonicPassFilter(num_pts, samp_rate, first_harm, bandwidth, num_harmonics)
return hbf
def noise_filter(hdf_file, parameters={}, pixelnum=[0, 0],
centers=[10E3, 50E3, 100E3, 150E3, 200E3],
widths=[20E3, 1E3, 1E3, 1E3, 1E3]):
'''
Interfaces with pycroscopy.processing.fft.NoiseBandFilter
:param hdf_file:
:param parameters:
:param pixelnum:
See test_filter
:param centers: list
List of Frequencies to filter out
:param widths:
List of frequency widths for each filter. e,g. in default case (10 kHz center, 20 kHz width) is from 0 to 20 kHz
'''
hdf_file, num_pts, drive, samp_rate = _get_pixel_for_filtering(hdf_file, parameters, pixelnum)
nf = px.processing.fft.NoiseBandFilter(num_pts, samp_rate, centers, widths)
return nf
def _get_pixel_for_filtering(hdf_file, parameters={}, pixelnum=[0, 0]):
ftype = str(type(hdf_file))
if ('h5py' in ftype) or ('Dataset' in ftype): # hdf file
parameters = usid.hdf_utils.get_attributes(hdf_file)
hdf_file = get_utils.get_pixel(hdf_file, [pixelnum[0], pixelnum[1]], array_form=True, transpose=False)
hdf_file = hdf_file.flatten()
if len(hdf_file.shape) == 2:
hdf_file = hdf_file.flatten()
num_pts = hdf_file.shape[0]
drive = parameters['drive_freq']
samp_rate = parameters['sampling_rate']
return hdf_file, num_pts, drive, samp_rate
# placeholder until accepted in pull request
class BandPassFilter(FrequencyFilter):
def __init__(self, signal_length, samp_rate, f_center, f_width,
fir=False, fir_taps=1999):
"""
Builds a bandpass filter
Parameters
----------
signal_length : unsigned int
Points in the FFT. Assuming Signal in frequency space (ie - after FFT shifting)
samp_rate : unsigned integer
Sampling rate
f_center : unsigned integer
Center frequency for filter
f_width : unsigned integer
Frequency width of the pass band
fir : bool, optional
True uses a finite impulse response (FIR) response instead of a standard boxcar. FIR is causal
fir_taps : int
Number of taps (length of filter) for finite impulse response filter
Returns
-------
bpf : 1D numpy array describing the bandpass filter
"""
if f_center >= 0.5 * samp_rate:
raise ValueError('Filter cutoff exceeds Nyquist rate')
self.f_center = f_center
self.f_width = f_width
super(BandPassFilter, self).__init__(signal_length, samp_rate)
cent = int(round(0.5 * signal_length))
# very simple boxcar
ind = int(round(signal_length * (f_center / samp_rate)))
sz = int(round(cent * f_width / samp_rate))
bpf = np.zeros(signal_length, dtype=np.float32)
# Finite Impulse Response or Boxcar
if not fir:
bpf[cent - ind - sz:cent - ind + sz + 1] = 1
bpf[cent + ind - sz:cent + ind + sz + 1] = 1
else:
freq_low = (f_center - f_width) / (0.5 * samp_rate)
freq_high = (f_center + f_width) / (0.5 * samp_rate)
band = [freq_low, freq_high]
taps = sps.firwin(int(fir_taps), band, pass_zero=False,
window='blackman')
bpf = np.abs(np.fft.fftshift(np.fft.fft(taps, n=signal_length)))
self.value = bpf
def get_parms(self):
basic_parms = super(BandPassFilter, self).get_parms()
prefix = 'band_pass_'
this_parms = {prefix + 'start_freq': self.f_center, prefix + 'band_width': self.f_width}
this_parms.update(basic_parms)
return this_parms
<file_sep>/docs/source/ffta.load.rst
ffta.load package
=================
Submodules
----------
ffta.load.get\_utils module
---------------------------
.. automodule:: ffta.load.get_utils
:members:
:undoc-members:
:show-inheritance:
ffta.load.gl\_ibw module
------------------------
.. automodule:: ffta.load.gl_ibw
:members:
:undoc-members:
:show-inheritance:
ffta.load.load\_commands module
-------------------------------
.. automodule:: ffta.load.load_commands
:members:
:undoc-members:
:show-inheritance:
ffta.load.load\_hdf module
--------------------------
.. automodule:: ffta.load.load_hdf
:members:
:undoc-members:
:show-inheritance:
ffta.load.load\_ringdown module
-------------------------------
.. automodule:: ffta.load.load_ringdown
:members:
:undoc-members:
:show-inheritance:
Module contents
---------------
.. automodule:: ffta.load
:members:
:undoc-members:
:show-inheritance:
<file_sep>/ffta/gkpfm/__init__.py
from . import gkline
from . import gkpixel
from . import transfer_func
from . import gkprocess
__all__ = ['gkline', 'gkpixel', 'transfer_func', 'gkprocess']<file_sep>/XOP/include/NiFpga_125MSAcquire.h
/*
* Generated with the FPGA Interface C API Generator 13.0.0
* for NI-RIO 13.0.0 or later.
*/
#ifndef __NiFpga_125MSAcquire_h__
#define __NiFpga_125MSAcquire_h__
#ifndef NiFpga_Version
#define NiFpga_Version 1300
#endif
#include "NiFpga.h"
/**
* The filename of the FPGA bitfile.
*
* This is a #define to allow for string literal concatenation. For example:
*
* static const char* const Bitfile = "C:\\" NiFpga_125MSAcquire_Bitfile;
*/
#define NiFpga_125MSAcquire_Bitfile "NiFpga_125MSAcquire.lvbitx"
/**
* The signature of the FPGA bitfile.
*/
static const char* const NiFpga_125MSAcquire_Signature = "989E376BA1809075A27597F5FAD08118";
typedef enum
{
NiFpga_125MSAcquire_IndicatorBool_edgedetected = 0x8000000E,
} NiFpga_125MSAcquire_IndicatorBool;
typedef enum
{
NiFpga_125MSAcquire_IndicatorU16_AcquisitionState = 0x8000002E,
} NiFpga_125MSAcquire_IndicatorU16;
typedef enum
{
NiFpga_125MSAcquire_IndicatorU32_RecordsTransfered = 0x80000014,
} NiFpga_125MSAcquire_IndicatorU32;
typedef enum
{
NiFpga_125MSAcquire_ControlBool_ExternalTrigger = 0x80000012,
NiFpga_125MSAcquire_ControlBool_Reset = 0x8000000A,
NiFpga_125MSAcquire_ControlBool_StartAcq = 0x80000002,
} NiFpga_125MSAcquire_ControlBool;
typedef enum
{
NiFpga_125MSAcquire_ControlU8_TriggerType = 0x80000026,
} NiFpga_125MSAcquire_ControlU8;
typedef enum
{
NiFpga_125MSAcquire_ControlI16_TriggerHysteresis = 0x80000022,
NiFpga_125MSAcquire_ControlI16_TriggerThreshold = 0x8000001E,
} NiFpga_125MSAcquire_ControlI16;
typedef enum
{
NiFpga_125MSAcquire_ControlU32_NumRecords = 0x80000028,
NiFpga_125MSAcquire_ControlU32_PreTriggerSamples = 0x80000018,
NiFpga_125MSAcquire_ControlU32_RecordLength = 0x80000004,
} NiFpga_125MSAcquire_ControlU32;
typedef enum
{
NiFpga_125MSAcquire_TargetToHostFifoI16_ToHost = 0,
} NiFpga_125MSAcquire_TargetToHostFifoI16;
#endif
|
6e698619b1ab7f1ffbb2f5a2fe2d58c52c748a93
|
[
"reStructuredText",
"Python",
"Text",
"C",
"R",
"C++"
] | 66
|
Python
|
lindat18/ffta
|
f510a2068b7626e2984e54afc1a577450e560e97
|
662bdc92b9bf2150fb281b03cc83eb9fdab709c3
|
refs/heads/master
|
<repo_name>linqueta/rails-uuid-postgres<file_sep>/app/models/book_uuid.rb
# frozen_string_literal: true
class BookUuid < ApplicationRecord
belongs_to :author_uuid
end
<file_sep>/app/models/author_uuid.rb
# frozen_string_literal: true
class AuthorUuid < ApplicationRecord
end
<file_sep>/app/models/author_sequencial_id.rb
# frozen_string_literal: true
class AuthorSequencialId < ApplicationRecord
end
<file_sep>/performance.rb
# frozen_string_literal: true
Benchmark.ips do |x|
x.report('UUID') { AuthorUuid.create(name: '<NAME>') }
x.report('Sequencial ID') { AuthorSequencialId.create(name: '<NAME>') }
x.compare!
end
# Warming up --------------------------------------
# UUID 40.000 i/100ms
# Sequencial ID 26.000 i/100ms
# Calculating -------------------------------------
# UUID 315.518 (±28.2%) i/s - 1.520k in 5.156348s
# Sequencial ID 304.672 (±35.1%) i/s - 1.404k in 5.053431s
# Comparison:
# UUID: 315.5 i/s
# Sequencial ID: 304.7 i/s - same-ish: difference falls within error
Benchmark.ips do |x|
x.report('UUID') { AuthorUuid.find('fffc7ac3-d43b-4c66-8210-512267968f80') }
x.report('Sequencial ID') { AuthorSequencialId.find(8608) }
x.compare!
end
# Warming up --------------------------------------
# UUID 599.000 i/100ms
# Sequencial ID 741.000 i/100ms
# Calculating -------------------------------------
# UUID 7.273k (± 6.5%) i/s - 36.539k in 5.046010s
# Sequencial ID 7.410k (± 4.5%) i/s - 37.050k in 5.010742s
# Comparison:
# Sequencial ID: 7409.9 i/s
# UUID: 7272.7 i/s - same-ish: difference falls within error
<file_sep>/README.md
# Rails-UUID-app<file_sep>/app/models/author.rb
# frozen_string_literal: true
class Author < ApplicationRecord
default_scope { order(:created_at) }
end
<file_sep>/db/migrate/20190524013106_create_book_uuids.rb
class CreateBookUuids < ActiveRecord::Migration[5.2]
def change
create_table :book_uuids, id: :uuid do |t|
t.string :title
t.references :author_uuid, foreign_key: true, index: true, type: :uuid
t.timestamps
end
end
end
|
0abf3d76e853f5542297c354c869805e45a2ecc3
|
[
"Markdown",
"Ruby"
] | 7
|
Ruby
|
linqueta/rails-uuid-postgres
|
817096f4bba295998d667e9fc007bd8acd60760a
|
4fabf5a5f91bf9446375c22f9bc49f0f792eba78
|
refs/heads/master
|
<repo_name>bootcampitp/bdd-cucumber-gherkin<file_sep>/src/test/java/steps/MyStepdefs.java
package steps;
import io.cucumber.java.After;
import io.cucumber.java.AfterStep;
import io.cucumber.java.Before;
import io.cucumber.java.BeforeStep;
import io.cucumber.java.en.And;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import org.junit.Assert;
public class MyStepdefs {
@Before
public void doSomethingBefore() {
System.out.println("This is the @Before hook");
}
@After
public void doSomethingAfter(){
System.out.println("This is the @After hook");
}
@BeforeStep
public void doSomethingBeforeStep(){
System.out.println("This is running BEFORE every step");
}
@AfterStep
public void doSomethingAfterStep(){
System.out.println("This is running AFTER every step");
}
@Given("I am on the registration page {string}")
public void iAmOnTheRegistrationPage(String url) {
System.out.println("You are on the registration page: " + url);
}
@When("I type first name {string} to firstname field")
public void iTypeFirstNameToFirstnameField(String firstname) {
System.out.println("You filled in firstname field with: " + firstname);
}
@Then("I should see {string} message")
public void iShouldSeeMessage(String expectedMessage) {
String actualMessage = "Welcome";
//System.out.println("Your expectedMessage is " + expectedMessage);
Assert.assertEquals("Actual message does not match expected message", expectedMessage, actualMessage);
Assert.assertEquals(expectedMessage, actualMessage);
}
@And("my score should be {int}")
public void myScoreShouldBe(int expectedScore) {
int actualScore = 0;
Assert.assertEquals("Actual score does not match expected score", expectedScore, actualScore);
}
}
|
db474d5028b503633fb487e2500d9ef73ca4d1a5
|
[
"Java"
] | 1
|
Java
|
bootcampitp/bdd-cucumber-gherkin
|
b442dde975c9761021d276dc809edb151859be5d
|
f2da8c094a04c6c0c3c15fde7b2a286339b84fee
|
refs/heads/master
|
<repo_name>azbyluthfan/scraper<file_sep>/kissmanga_scraper.py
import time
import re
import requests
from multiprocessing.pool import ThreadPool as Pool
from bs4 import BeautifulSoup
class KissmangaScraper:
def get_soup(self, url):
"""Scrape content from url and parse it using BeautifulSoup.
"""
response = requests.get(url)
html = response.content
soup = BeautifulSoup(html, "html.parser")
return soup
def get_manga_list(self):
"""Get manga list from Kissmanga.
"""
result = []
next_link = 'http://kissmanga.com/MangaList'
while next_link is not '':
soup = self.get_soup(next_link)
mangas = soup.find('table', class_='listing').find_all('tr')
for manga in mangas:
link = manga.find('a')
if link is not None :
link = str(link['href'].encode('utf-8'))
link = 'http://kissmanga.com' + link[2:-1]
result[len(result):] = [link]
pagers = soup.find(class_='pagination').find_all('a')
next_link = ''
for pager in pagers:
if re.search('Next', str(pager.get_text().encode('utf-8'))):
next_link = str(pager['href'].encode('utf-8'))
next_link = 'http://kissmanga.com' + next_link[2:-1]
return result
def get_chapter_list(self, url):
"""Get chapter list of a manga.
"""
result = []
if url is '':
return result
soup = self.get_soup(url)
chapters = soup.find('table', class_='listing').find_all('a')
for link in chapters:
if link is not None :
link = str(link['href'].encode('utf-8'))
link = 'http://kissmanga.com' + link[2:-1]
result[len(result):] = [link]
return result
def get_images(self, url):
"""Get images from a chapter.
"""
result = []
if url is '':
return result
soup = self.get_soup(url)
scripts = soup.find_all('script')
for script in scripts:
if re.search('lstImages.push', script.get_text()):
p = re.compile('lstImages.push\("(.*)"\)')
pages = p.findall(script.get_text())
result = pages
break
return result
# get_manga_list()
# get_chapter_list('http://kissmanga.com/Manga/Onepunch-Man-ONE')
# get_images('http://kissmanga.com/Manga/Ayeshah-s-Secret/Vol-001-Ch-001-Read-Online?id=241934')
if __name__ == '__main__':
print('Started')
start = time.time()
scraper = KissmangaScraper()
urls = scraper.get_chapter_list('http://kissmanga.com/Manga/Onepunch-Man-ONE')
print(str(len(urls)) + ' chapters found')
img_count = 0
results = []
# With parallel processing
# pool = Pool(8)
# results = pool.map(scraper.get_images, urls)
# Without parallel processing
for url in urls:
results[len(results):] = [scraper.get_images(url)]
for img in results:
img_count += len(img)
print(str(img_count) + ' images found')
end = time.time()
elapsed = end - start
print('Finished in ' + str(elapsed) + ' seconds')<file_sep>/google_scraper.py
"""
Failed. Unused
"""
# import requests
# from bs4 import BeautifulSoup
# print("Specify amount")
# amount = input()
# print("Specify currency to convert from")
# cur1 = input()
# print("Specify currency to convert to")
# cur2 = input()
# url = 'https://google.com?q=' + amount + '+' + cur1 + '+to+' + cur2
# response = requests.get(url)
# html = response.content
# soup = BeautifulSoup(html, "html.parser")
# # logo = soup.find(id='hplogo')
# answer = soup.find(class_='vk_ans')
# # print(logo.prettify().encode('utf-8'))
# # print(html.prettify().encode('utf-8'))
# print(html)
|
66e4b266ae8a31cccedc7af2fffe0be42e44051a
|
[
"Python"
] | 2
|
Python
|
azbyluthfan/scraper
|
a0c1ecfdbf76817dee09ce5949037b5cd9ef1bde
|
a839579001d3594f6c8a198e15430c5410c0e805
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
namespace Kevin_spicy_GAME
{
class EnemySpawn
{
static Random random = new Random();
static List<Enemy> enemies = new List<Enemy>();
public static List<Enemy> SpawnedEnemies
{
get { return enemies; }
}
public static void SpawnEnemy(GameWindow Window)
{
float randomY = random.Next(80, Window.ClientBounds.Height - 240);
enemies.Add(new Enemy(Game1.LoadedTextures["EnemyShip"], new Vector2 (1900, randomY), 5, Vector2.One));
}
public static void Draw(SpriteBatch spriteBatch)
{
foreach(Enemy enemy in enemies)
{
spriteBatch.Draw(Game1.LoadedTextures["EnemyShip"], enemy.EnemyRectangle, Color.White);
}
}
}
}
<file_sep>using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace Kevin_spicy_GAME
{
/// <summary>
/// This is the main type for your game.
/// </summary>
public class Game1 : Game
{
float enemySpawnTimer = 0;
float enemySpawnSpeed = 1f;
public static float Health { get; set; } = 100.0f;
public static int Points { get; set; } = 0;
public static int Ammo { get; set; } = 30;
Vector2 bgPosition = new Vector2(0, 0);
static Dictionary<string, SpriteFont> loadedFonts = new Dictionary<string, SpriteFont>();
static Dictionary<string, Texture2D> loadedTextures = new Dictionary<string, Texture2D>();
public static Dictionary<string, Texture2D> LoadedTextures
{
get { return loadedTextures; }
}
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
public static Player player;
//Game World
// List<Enemies> enemies = new List<Enemies>();
Random random = new Random();
public static List<Bullet> bullets = new List<Bullet>();
//Pause
public Game1()
{
graphics = new GraphicsDeviceManager(this);
graphics.IsFullScreen = false;
graphics.PreferredBackBufferHeight = 1080;
graphics.PreferredBackBufferWidth = 1920;
Content.RootDirectory = "Content";
}
/// <summary>
/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.
/// </summary>
protected override void Initialize()
{
// TODO: Add your initialization logic here
base.Initialize();
player = new Player();
IsMouseVisible = false;
}
/// <summary>
/// LoadContent will be called once per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
// Create a new SpriteBatch, which can be used to draw textures.
spriteBatch = new SpriteBatch(GraphicsDevice);
loadedTextures["SpaceWallpaper"] = Content.Load<Texture2D>("SpaceWallpaper");
loadedTextures["EnemyShip"] = Content.Load<Texture2D>("EnemyShip");
loadedTextures["Ship"] = Content.Load<Texture2D>("KEvins Ship");
loadedTextures["Bullet"] = Content.Load<Texture2D>("bullet");
loadedTextures["Crosshair"] = Content.Load<Texture2D>("crosshair");
loadedTextures["BulletGreen"] = Content.Load<Texture2D>("BulletGreen");
loadedTextures["HUD"] = Content.Load<Texture2D>("HUD");
loadedFonts["Betong"] = Content.Load<SpriteFont>("Betong");
//pointTexture = Content.Load<Texture2D>("point");
// TODO: use this.Content to load your game content here
}
/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// game-specific content.
/// </summary>
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}
/// <summary>
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input, and playing audio.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
enemySpawnTimer -= (float)gameTime.ElapsedGameTime.TotalSeconds;
if (bgPosition.X > -11515)
{
bgPosition += new Vector2(-25, 0);
}
else
{
bgPosition = new Vector2(0, 0);
}
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
Exit();
player?.Update(gameTime, Window);
for(int i = 0; i < bullets.Count; i++)
{
bullets[i].Update(gameTime, player);
}
foreach(Enemy e in EnemySpawn.SpawnedEnemies)
{
e.Update(gameTime);
}
if (enemySpawnTimer <= 0)
{
enemySpawnTimer = enemySpawnSpeed;
SpawnEnemeies();
}
base.Update(gameTime);
}
public void SpawnEnemeies()
{
EnemySpawn.SpawnEnemy(Window);
}
/// <summary>
/// This is called when the game should draw itself.5
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
// TODO: Add your drawing code here
spriteBatch.Begin();
spriteBatch.Draw(LoadedTextures["SpaceWallpaper"], bgPosition, Color.White);
EnemySpawn.Draw(spriteBatch);
player?.Draw(spriteBatch);
foreach (Bullet bullet in bullets)
{
bullet.Draw(spriteBatch);
}
spriteBatch.DrawString(loadedFonts["Betong"], Health.ToString(), new Vector2(200, 825), Color.Blue);
spriteBatch.DrawString(loadedFonts["Betong"], Points.ToString(), new Vector2(900, 900), Color.Blue);
spriteBatch.DrawString(loadedFonts["Betong"], Ammo.ToString(), new Vector2(1630, 815), Color.Blue);
spriteBatch.End();
base.Draw(gameTime);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
namespace Kevin_spicy_GAME
{
class Button
{
Texture2D texture;
Rectangle rectangle;
Vector2 position;
Vector2 scale;
Vector2 offset;
Vector2 textOffset;
SpriteFont font;
Vector2 textScale;
Color color;
string text;
public Button(Texture2D buttonTexture, Vector2 startPosition, string buttonText, Vector2 buttonScale, Vector2 buttonTextScale, SpriteFont textFont)
{
font = textFont;
texture = buttonTexture;
text = buttonText;
position = startPosition;
scale = buttonScale;
textScale = buttonTextScale;
offset = buttonTexture.Bounds.Size.ToVector2() * 0.5f;
rectangle = new Rectangle((position - offset).ToPoint(), (buttonTexture.Bounds.Size.ToVector2() * scale).ToPoint());
}
public bool Update(MouseState mouseState)
{
bool containsMouse = false;
color = Color.White;
if (rectangle.Contains(mouseState.Position))
{
color = Color.Green;
containsMouse = true;
}
return containsMouse;
}
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(texture, position, null, color, 0, offset, scale, SpriteEffects.None, 0);
spriteBatch.DrawString(font, text, position, Color.White, 0, textOffset, textScale, SpriteEffects.None, 0);
}
public string GetButtonText()
{
return text;
}
public void Place(Vector2 newPosition)
{
position = newPosition;
rectangle.Location = (position - offset).ToPoint();
}
}
}
<file_sep>using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Kevin_spicy_GAME
{
public class Bullet
{
float bulletSpeed;
float damage;
Vector2 position;
Vector2 direction;
Texture2D redBullet;
Rectangle collisionBoxBullet;
Vector2 bulletOffset;
Vector2 bulletScale;
private Type shooterType;
public Bullet(Vector2 pos, Texture2D texture, float speed, Vector2 scale, Vector2 playerScale, Vector2 direction, float damage, Type shooterType)
{
position = pos + playerScale * 0.2555f;
redBullet = texture;
bulletSpeed = speed * 1.5f;
bulletScale = scale;
collisionBoxBullet = new Rectangle(position.ToPoint(), bulletScale.ToPoint());
bulletOffset = (texture.Bounds.Size.ToVector2() * 2f) * scale;
this.direction = direction;
this.damage = damage;
this.shooterType = shooterType;
}
public void Update(GameTime gameTime, Player player)
{
position += direction * bulletSpeed;
collisionBoxBullet.Location = position.ToPoint();
if (shooterType == typeof(Player))
{
IEnumerable<Enemy> hitEnemies = CheckEnemyCollision();
foreach (Enemy enemy in hitEnemies)
{
enemy.TakeDamage(damage);
Game1.bullets.Remove(this);
}
}
else if (shooterType == typeof(Enemy) && player != null)
{
bool hitPlayer = player.spaceshipRectangle.Intersects(collisionBoxBullet);
if (hitPlayer)
{
player.TakeDamage(damage);
Game1.bullets.Remove(this);
}
}
}
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(redBullet, position, null, Color.White, 0, bulletOffset, bulletScale , SpriteEffects.None, 0);
}
public IEnumerable<Enemy> CheckEnemyCollision()
{
for(int i = 0; i < EnemySpawn.SpawnedEnemies.Count; i++)
{
if (collisionBoxBullet.Intersects(EnemySpawn.SpawnedEnemies[i].EnemyRectangle))
{
yield return EnemySpawn.SpawnedEnemies[i];
}
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
namespace Kevin_spicy_GAME
{
public class Enemy
{
Texture2D bulletGreenTexture;
float attackTimer = 0;
float attackSpeed = 2;
private float health;
public Texture2D _texure { get; set; }
Vector2 position;
Vector2 scale;
Vector2 offset;
Rectangle rectangle;
private float enemyDamage;
public Rectangle EnemyRectangle
{
get { return rectangle; }
}
float speed;
Color color;
public Enemy(Texture2D texture, Vector2 startPosition, float enemySpeed, Vector2 enemyScale)
{
position = startPosition;
offset = Game1.LoadedTextures["EnemyShip"].Bounds.Size.ToVector2() * 0.5f;
scale = enemyScale;
rectangle = new Rectangle((startPosition - offset).ToPoint(), (Game1.LoadedTextures["EnemyShip"].Bounds.Size.ToVector2() * scale).ToPoint());
rectangle.Size = new Point(100);
enemyDamage = 5.0f;
health = 50.0f;
color = Color.White;
speed = enemySpeed;
bulletGreenTexture = Game1.LoadedTextures["BulletGreen"];
}
public void Update(GameTime gameTime)
{
attackTimer -= (float)gameTime.ElapsedGameTime.TotalSeconds;
if(attackTimer <= 0)
{
Shoot();
attackTimer = attackSpeed;
}
position += new Vector2(-1, 0) * speed;
rectangle.Location = position.ToPoint();
}
public void Shoot()
{
Game1.bullets.Add(new Bullet(position, bulletGreenTexture, 20, Vector2.One * 0.025f, rectangle.Size.ToVector2(), -Vector2.UnitX, enemyDamage, typeof(Enemy)));
}
public void TakeDamage(float amount)
{
health -= amount;
if (health <= 0)
{
Game1.Points+=100;
EnemySpawn.SpawnedEnemies.Remove(this);
}
}
}
}
<file_sep>//using System;
//using System.Collections.Generic;
//using System.Linq;
//using System.Text;
//using System.Threading.Tasks;
//using Microsoft.Xna.Framework;
//using Microsoft.Xna.Framework.Graphics;
//using Microsoft.Xna.Framework.Content;
//using Microsoft.Xna.Framework.Input;
//namespace Kevin_spicy_GAME
//{
// static class UserInterface
// {
// static bool pause;
// static SpriteFont font;
// static KeyboardState prevKeyboardState = Keyboard.GetState();
// static List<Button> buttons = new List<Button>();
// static MouseState prevMouseState;
// public static void AddButton(Texture2D texture, string text, Vector2 scale, Vector2 textScale, Vector2 screenSize)
// {
// buttons.Add(new Button(texture, Vector2.Zero, text, scale, textScale, font));
// PlaceButtons(screenSize);
// }
// public static void LoadSpriteFont(ContentManager content, string fontName)
// {
// font = content.Load<SpriteFont>(fontName);
// }
// public static bool Update(KeyboardState keyboardState, MouseState mouseState)
// {
// bool exit = false;
// if (keyboardState.IsKeyDown(Keys.Escape) && prevKeyboardState.IsKeyUp(Keys.Escape))
// {
// }
// }
// }
//}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Kevin_spicy_GAME
{
class Background
{
// spriteBatch = new SpriteBatch(GraphicsDevice);
// loadedTextures["SpaceWallpaper"] = Content.Load<Texture2D>("SpaceWallpaper");
}
}<file_sep>using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
namespace Kevin_spicy_GAME
{
public class Player
{
Texture2D kevinSpaceshipTexture;
public Rectangle spaceshipRectangle;
Vector2 position;
Vector2 crosshairpos;
Vector2 scale;
Vector2 offset;
Vector2 hudpos;
Vector2 hudScale;
Color spaceshipColor;
Texture2D hudTexture;
float health;
float playerDamage;
float speed;
float attackInterval;
float attackSpeed;
float rotation;
Texture2D bulletGreenTexture;
Texture2D crosshairTexture;
private Texture2D texture2D;
private Vector2 vector21;
private int v1;
private Vector2 vector22;
private int v2;
private Color white;
public Player()
{
kevinSpaceshipTexture = Game1.LoadedTextures["Ship"];
position = new Vector2(0, 450);
crosshairpos = new Vector2(1750, 437);
hudpos = new Vector2 (50, 25);
hudScale = new Vector2(1f, 1.2f);
speed = 300;
health = 100.0f;
attackInterval = 0.2f;
rotation = 0;
scale = new Vector2(0.3f, 0.3f);
playerDamage = 50.0f;
attackSpeed = 100;
spaceshipColor = Color.White;
offset = (kevinSpaceshipTexture.Bounds.Size.ToVector2() * 0.5f) * scale;
spaceshipRectangle = new Rectangle((position - offset).ToPoint(), (kevinSpaceshipTexture.Bounds.Size.ToVector2() * scale).ToPoint());
hudTexture = Game1.LoadedTextures["HUD"];
bulletGreenTexture = Game1.LoadedTextures["Bullet"];
crosshairTexture = Game1.LoadedTextures["Crosshair"];
}
public Player(Texture2D texture2D, Vector2 vector21, int v1, Vector2 vector22, int v2, Color white)
{
this.texture2D = texture2D;
this.vector21 = vector21;
this.v1 = v1;
this.vector22 = vector22;
this.v2 = v2;
this.white = white;
}
public void Update(GameTime gameTime, GameWindow window)
{
float deltaTime = (float)gameTime.ElapsedGameTime.TotalSeconds;
attackSpeed += deltaTime;
KeyboardState keyboardState = Keyboard.GetState();
if (keyboardState.IsKeyDown(Keys.D))
{
position += (Vector2.UnitX * speed * deltaTime);
}
if (keyboardState.IsKeyDown(Keys.LeftShift))
{
position += (Vector2.UnitX * speed * deltaTime * 3);
}
if (keyboardState.IsKeyDown(Keys.A))
{
position += (-Vector2.UnitX * speed * deltaTime * 2);
}
if (keyboardState.IsKeyDown(Keys.S))
{
position += (Vector2.UnitY * speed * deltaTime * 3);
}
if (keyboardState.IsKeyDown(Keys.W))
{
position += (-Vector2.UnitY * speed * deltaTime * 3);
}
//bounds
// crosshair
crosshairpos = Vector2.Lerp(crosshairpos, new Vector2(1600, position.Y), 0.07f);
//player
if (position.X <= 40)
{
position.X = 40;
}
if (position.X >= (window.ClientBounds.Width - (kevinSpaceshipTexture.Width * scale.X)))
{
position.X = (window.ClientBounds.Width - kevinSpaceshipTexture.Width * scale.X);
}
if (position.Y <= 75)
{
position.Y = 75;
}
if (position.Y >= (window.ClientBounds.Height - kevinSpaceshipTexture.Height * scale.Y - 145))
{
position.Y = (window.ClientBounds.Height - kevinSpaceshipTexture.Height * scale.Y - 145);
}
spaceshipRectangle.Location = (position - offset * scale).ToPoint();
if (keyboardState.IsKeyDown(Keys.Space) && attackSpeed >= attackInterval)
{
attackSpeed = 0;
Shoot();
}
}
public void Draw(SpriteBatch spriteBatch)
{
spriteBatch.Draw(kevinSpaceshipTexture, position, null, spaceshipColor, rotation, offset, scale, SpriteEffects.None, 0);
spriteBatch.Draw(crosshairTexture, crosshairpos, null, spaceshipColor, rotation, offset, scale, SpriteEffects.None, 0);
spriteBatch.Draw(hudTexture, hudpos, null, spaceshipColor, rotation, offset, hudScale, SpriteEffects.None, 0);
}
public void Shoot()
{
if (Game1.Ammo >= 1)
{
Game1.Ammo--;
Game1.bullets.Add(new Bullet(position, bulletGreenTexture, 20, Vector2.One * 0.025f, spaceshipRectangle.Size.ToVector2(), Vector2.UnitX, playerDamage, typeof(Player)));
}
else
{
Game1.Ammo = 0;
}
}
public void TakeDamage(float amount)
{
health -= amount;
Game1.Health-=5.0f;
if (health <= 0)
{
Game1.player = null;
}
}
}
}
|
1ba1e21af017cdfa549f29a7b015ce55424a2e3b
|
[
"C#"
] | 8
|
C#
|
ElliotSeger/Kevin-Spicy-DIGDIG
|
7bb366bd671772c33dbe844d762a8ceef26f7e81
|
257a2f9478ffaeebf22955b2efe88a3c011474b2
|
refs/heads/main
|
<file_sep><?php
class Post{
private $userObj;
private $con;
public function __construct($con,$user){
$this->con=$con;
$this->userObj=new User($con,$user);
}
public function submitPost($body,$userTo){
$body=strip_tags($body);//Remove html tags
$body=mysqli_real_escape_string($this->con,$body);
$checkEmpty=preg_replace('/\s+/','', $body);//Deletes all spaces
if($checkEmpty !=""){
$dateAdded=date("Y-m-d H:i:s");//Date and time
//Get username
$addedBy=$this->userObj->getUsername();
//If posting on own profile
//Insert post
$query=mysqli_query($this->con,"INSERT INTO posts VALUES('','$body','$addedBy','$userTo','$dateAdded','no','no','0')");
$returnedId=mysqli_insert_id($this->con);
//Insert notification
}
}
//-----------------PostsFriends----------------------------------
public function loadPostsFriends($data,$limit){
$page=$data['page'];
$userLoggedIn=$this->userObj->getUsername();
if($page==1){
$start=0;
}
else{
$start=($page-1)*$limit;
}
$str="";//Return this string
$dataQuery=mysqli_query($this->con,"SELECT * FROM posts WHERE deleted='no' ORDER BY id DESC");
if(mysqli_num_rows($dataQuery)>0){
$numIterations=0;//Num of results checked
$count=1;
while($row=mysqli_fetch_array($dataQuery)){
$id=$row['id'];
$body=$row['body'];
$addedBy=$row['addedBy'];
$dateTime=$row['dateAdded'];
//Prepare userTo string so it can be included even if not posted to a user
if($row['userTo']=='none'){
$userTo="";
}else{
$userToObj=new User($this->con,$row['userTo']);
$userToName=$userToObj->getFirstAndLastName();
$userTo="to <a href=' " .$row['userTo']."'> ".$userToName."</a";
}
$userLoggedObj=new User($this->con,$userLoggedIn);
if($userLoggedObj->isFriend($addedBy)){
if($numIterations++ < $start)
continue;
//Once 10 posts loaded, stop
if($count>$limit){
break;
}else{
$count++;
}
if($userLoggedIn==$addedBy)
$deleteButton="<button class='delete_button btn-danger' id='post$id'>delete</button>";
else
$deleteButton="";
//User who posted
$userDetailsQuery=mysqli_query($this->con,"SELECT firstName , lastName ,profilePic FROM users WHERE userName='$addedBy' ");
$userRow=mysqli_fetch_array($userDetailsQuery);
$firstName=$userRow['firstName'];
$lastName=$userRow['lastName'];
$profilePic=$userRow['profilePic'];
?>
<script>
function toggle<?php echo $id; ?>(e) {
if( !e ) e = window.event;
var target = $(e.target);
if (!target.is("a")) {
var element = document.getElementById("toggleComment<?php echo $id; ?>");
if(element.style.display == "block")
element.style.display = "none";
else
element.style.display = "block";
}
}
</script>
<?php
$commentsCheck=mysqli_query($this->con,"SELECT * FROM comments WHERE postId='$id'");
$commentsCheckNum=mysqli_num_rows($commentsCheck);
//Time
$dateTimeNow=date("Y-m-d H:i:s");
$startDate=new DateTime($dateTime);//Post time
$endDate=new DateTime($dateTimeNow);//Now time
$interval=$startDate->diff($endDate);//Diff
if($interval->y>=1){
$timeMessage=$interval->y." year(s) ago";
}else if($interval->m>=1){
if($interval->d==0){$days="ago";}
else if($interval->d==1){$days=$interval->d." days ago";}
else{$days=$interval->d." days ago";}
if($interval->m==1){
$timeMessage=$interval->m." month".$days;
}
else{$timeMessage=$interval->m." months".$days;}
}
else if($interval->d>=1){
if($interval->d==1){
$timeMessage="Yesterday";
}
else{$timeMessage=$interval->d."days ago";}
}
else if($interval->h>=1){
if($interval->h==1){
$timeMessage=$interval->h."hour ago";
}
else{$timeMessage=$interval->h."hours ago";}
}
else if($interval->i>=1){
$timeMessage=$interval->i."minutes ago";
}
else if($interval->i<1){
$timeMessage="Just now";
}
$str.="<div class='status_post' onClick='javascript:toggle$id(event)'>
<div class='post_profile_pic'>
<img src='$profilePic' width='50'
</div>
<div class='posted_by' style='color:#ACACAC;'>
<a href='$addedBy'>$firstName $lastName </a> $userTo <br> $timeMessage <br>
$deleteButton
</div>
<div id='post_body'>
$body
</div>
</div>
<div class='newsfeed_post_options'>
Comments($commentsCheckNum)  
<iframe src='Fly.php?postId=$id' scrolling='no'> </iframe>
</div>
</div>
<div class='post_comment' id='toggleComment$id'style='display:none;'>
<iframe src='Comment_frame.php?postId=$id' id='comment_iframe' width=100%;></iframe>
</div>
<hr>";
}
?>
<script >
$(document).ready(function() {
$('#post<?php echo $id; ?>').on('click', function() {
bootbox.confirm("Are you sure you want to delete this post?", function(result) {
$.post("Includes/Delete_post.php?post_id=<?php echo $id; ?>", {result:result});
if(result)
location.reload();
});
});
});
</script>
<?php
}
if($count > $limit)
$str .= "<input type='hidden' class='nextPage' value='" . ($page + 1) . "'><input type='hidden' class='noMorePosts' value='false'>";
else
$str .= "<input type='hidden' class='noMorePosts' value='true'><p style='text-align:center;' class='noMorePostsText'> No more posts to show! </p>";
}
echo $str;
}
//--------------------------------ProfilePosts------------------------
public function loadProfilePosts($data,$limit){
$page=$data['page'];
$profileUser=$data['profileUsername'];
$userLoggedIn=$this->userObj->getUsername();
if($page==1){
$start=0;
}
else{
$start=($page-1)*$limit;
}
$str="";//Return this string
$dataQuery=mysqli_query($this->con,"SELECT * FROM posts WHERE deleted='no' AND ((
addedBy='$profileUser' AND userTo='none')OR userTo='$profileUser') ORDER BY id DESC");
if(mysqli_num_rows($dataQuery)>0){
$numIterations=0;//Num of results checked
$count=1;
while($row=mysqli_fetch_array($dataQuery)){
$id=$row['id'];
$body=$row['body'];
$addedBy=$row['addedBy'];
$dateTime=$row['dateAdded'];
//Prepare userTo string so it can be included even if not posted to a user
if($row['userTo']=='none'){
$userTo="";
}else{
$userToObj=new User($this->con,$row['userTo']);
$userToName=$userToObj->getFirstAndLastName();
$userTo="to <a href=' " .$row['userTo']."'> ".$userToName."</a";
}
$userLoggedObj=new User($this->con,$userLoggedIn);
if($userLoggedObj->isFriend($addedBy)){
if($numIterations++ < $start)
continue;
//Once 10 posts loaded, stop
if($count>$limit){
break;
}else{
$count++;
}
if($userLoggedIn==$addedBy)
$deleteButton="<button class='delete_button btn-danger' id='post$id'>delete</button>";
else
$deleteButton="";
//User who posted
$userDetailsQuery=mysqli_query($this->con,"SELECT firstName , lastName ,profilePic FROM users WHERE userName='$addedBy' ");
$userRow=mysqli_fetch_array($userDetailsQuery);
$firstName=$userRow['firstName'];
$lastName=$userRow['lastName'];
$profilePic=$userRow['profilePic'];
?>
<script>
function toggle<?php echo $id; ?>(e) {
if( !e ) e = window.event;
var target = $(e.target);
if (!target.is("a")) {
var element = document.getElementById("toggleComment<?php echo $id; ?>");
if(element.style.display == "block")
element.style.display = "none";
else
element.style.display = "block";
}
}
</script>
<?php
$commentsCheck=mysqli_query($this->con,"SELECT * FROM comments WHERE postId='$id'");
$commentsCheckNum=mysqli_num_rows($commentsCheck);
//Time
$dateTimeNow=date("Y-m-d H:i:s");
$startDate=new DateTime($dateTime);//Post time
$endDate=new DateTime($dateTimeNow);//Now time
$interval=$startDate->diff($endDate);//Diff
if($interval->y>=1){
$timeMessage=$interval->y." year(s) ago";
}else if($interval->m>=1){
if($interval->d==0){$days="ago";}
else if($interval->d==1){$days=$interval->d." days ago";}
else{$days=$interval->d." days ago";}
if($interval->m==1){
$timeMessage=$interval->m." month".$days;
}
else{$timeMessage=$interval->m." months".$days;}
}
else if($interval->d>=1){
if($interval->d==1){
$timeMessage="Yesterday";
}
else{$timeMessage=$interval->d."days ago";}
}
else if($interval->h>=1){
if($interval->h==1){
$timeMessage=$interval->h."hour ago";
}
else{$timeMessage=$interval->h."hours ago";}
}
else if($interval->i>=1){
$timeMessage=$interval->i."minutes ago";
}
else if($interval->i<1){
$timeMessage="Just now";
}
$str.="<div class='status_post' onClick='javascript:toggle$id(event)'>
<div class='post_profile_pic'>
<img src='$profilePic' width='50'
</div>
<div class='posted_by' style='color:#ACACAC;'>
<a href='$addedBy'>$firstName $lastName </a> $timeMessage
$deleteButton
</div>
<div id='post_body'>
$body
</div>
</div>
<div class='newsfeed_post_options'>
Comments($commentsCheckNum)  
<iframe src='Fly.php?postId=$id' scrolling='no'> </iframe>
</div>
</div>
<div class='post_comment' id='toggleComment$id'style='display:none;'>
<iframe src='Comment_frame.php?postId=$id' id='comment_iframe' width=100%;></iframe>
</div>
<hr>";
}
?>
<script >
$(document).ready(function() {
$('#post<?php echo $id; ?>').on('click', function() {
bootbox.confirm("Are you sure you want to delete this post?", function(result) {
$.post("Includes/Delete_post.php?post_id=<?php echo $id; ?>", {result:result});
if(result)
location.reload();
});
});
});
</script>
<?php
}
if($count > $limit)
$str .= "<input type='hidden' class='nextPage' value='" . ($page + 1) . "'><input type='hidden' class='noMorePosts' value='false'>";
else
$str .= "<input type='hidden' class='noMorePosts' value='true'><p style='text-align:center;' class='noMorePostsText'> No more posts to show! </p>";
}
echo $str;
}
}
?><file_sep><?php
class User{
private $user;
private $con;
public function __construct($con,$user){
$this->con=$con;
$userDetailsQuery=mysqli_query($this->con,"SELECT * FROM users WHERE userName='$user'");
$this->user=mysqli_fetch_array($userDetailsQuery);
}
public function getFirstAndLastName(){
$username=$this->user['userName'];
$query=mysqli_query($this->con,"SELECT firstName , lastName FROM users WHERE userName='$username'");
$row=mysqli_fetch_array($query);
return $row['firstName']." ".$row['lastName'];
}
public function getUsername(){
return $this->user['userName'];
}
public function isFriend($usernameToCheck){
$addComma=",".$usernameToCheck.",";
if((strstr($this->user['friendArray'],$addComma)||$usernameToCheck==$this->user['userName'])){
return true;
}else{return false;}
}
public function getProfilePic(){
$username=$this->user['userName'];
$query=mysqli_query($this->con,"SELECT profilePic FROM users WHERE userName='$username'");
$row=mysqli_fetch_array($query);
return $row['profilePic'];
}
public function getFriendArray(){
$username=$this->user['userName'];
$query=mysqli_query($this->con,"SELECT friendArray FROM users WHERE userName='$username'");
$row=mysqli_fetch_array($query);
return $row['friendArray'];
}
public function didReciveRequest($userFrom){
$userTo=$this->user['userName'];
$checkRequestQuery=mysqli_query($this->con,"SELECT * FROM friendrequests WHERE userTo='$userTo' AND userFrom='$userFrom'");
if(mysqli_num_rows($checkRequestQuery)>0){
return true;
}
else {
return false;
}
}
public function didSendRequest($userTo){
$userFrom=$this->user['userName'];
$checkRequestQuery=mysqli_query($this->con,"SELECT * FROM friendrequests WHERE userTo='$userTo' AND userFrom='$userFrom'");
if(mysqli_num_rows($checkRequestQuery)>0){
return true;
}else{return false;}
}
public function removeFriend($userToRemove){
$loggedInUser=$this->user['userName'];
$query=mysqli_query($this->con,"SELECT friendArray FROM users WHERE userName='$userToRemove'");
$row=mysqli_fetch_array($query);
$friendArrayUsername=$row['friendArray'];
//Remove from logged in user
$newFriendArray=str_replace($userToRemove.",","",$this->user['friendArray']);
$removeFriend=mysqli_query($this->con,"UPDATE users SET friendArray='$newFriendArray'WHERE userName='$loggedInUser'");
//Remove from the no longer friend
$newFriendArray=str_replace($this->user['userName'].",","",$friendArrayUsername);
$removeFriend=mysqli_query($this->con,"UPDATE users SET friendArray='$newFriendArray'WHERE userName='$userToRemove'");
}
public function sendRequest($userTo){
$userFrom=$this->user['userName'];
$query=mysqli_query($this->con,"INSERT INTO friendrequests VALUES ('','$userTo','$userFrom')");
}
public function getMutualFriends($userToCheck){
$mutualFriends=0;
$userArray=$this->user['friendArray'];
$userArrayExplode=explode(',',$userArray);
$query=mysqli_query($this->con,"SELECT friendArray FROM users WHERE userName='$userToCheck' ");
$row=mysqli_fetch_array($query);
$userToCheckArray=$row['friendArray'];
$userToCheckArrayExplode=explode(",",$userToCheckArray);
foreach ($userArrayExplode as $i) {
foreach ($userToCheckArrayExplode as $j) {
if($i==$j && $i!=""){
$mutualFriends++;
}
}
}
return $mutualFriends;
}
}
?><file_sep><?php
//include("Includes/Classes/User.php");
//include("Includes/Classes/Post.php");
//include("Includes/Classes/Message.php");
if(is_readable('Config/Config.php')){
require 'Config/Config.php';}
else{
ob_start();
session_start();
$timezone=date_default_timezone_set("Europe/Bucharest");
$con=mysqli_connect("localhost","root","","euroavia-s");//Conn
if(mysqli_connect_error()){
echo mysqli_connect_error();}
}
if(isset($_SESSION['log_username'])){
$userLoggedIn=$_SESSION['log_username'];
$userDetailsQuery=mysqli_query($con,"SELECT * FROM users WHERE userName='$userLoggedIn'");
$user=mysqli_fetch_array($userDetailsQuery);
}else{header("Location: Register.php");}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
<!--Javascript-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="Js/bootstrap.js"></script>
<script src="Js/Euroavia.js"></script>
<script src="Js/bootbox.min.js"></script>
<!--Css-->
<link rel="stylesheet" type="text/css" href="Css/bootstrap.css">
<link rel="stylesheet" type="text/css" href="Css/Header.css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.1/css/all.css" integrity="<KEY>" crossorigin="anonymous">
</head>
<body>
<div class="top_bar">
<div class="logo">
<a href="EuroAvia.php">EuroAvia-Bucuresti</a>
</div>
<!---------------Navigation bar------->
<nav>
<?php
//$messages=new Message($con,$userLoggedIn);
//$numMessages=$messages->getUnreadNumber();
?>
<a href="<?php echo $userLoggedIn; ?>">
<?php echo $user['firstName']; ?>
</a>
<a href="EuroAvia.php">
<i class="fa fa-home fa-lg"></i>
</a>
<a href="javascript:void(0);"onclick="getDropdownData('<?php echo $userLoggedIn;?>','message')">
<i class="fa fa-envelope fa-lg"></i>
<?php
/*if($numMessages>0){
echo "<span class='notification_badge' id='unread_message'>".$numMessages."</span>
</a>";}*/
?>
<a href="#">
<i class="fa fa-bell fa-lg"></i>
</a>
<a href="Requests.php">
<i class="fa fa-users fa-lg"></i>
</a>
<a href="#">
<i class="fa fa-cog fa-lg"></i>
</a>
</nav>
<div class="dropdown_data_window" style="height:0px; border:none;margin-top:38px;position:absolute;right:10px;background-color: #446cb3;border-radius:0px 0px 8px 8px;"></div>
<input type="hidden" id="dropdown_data_type" value="">
</div>
<file_sep><?php
include("includes/Header.php");
include("Includes/Classes/User.php");
include("includes/Classes/Post.php");
?>
<div class="main_column2 " id="main_column">
<h4>Friend Requests</h4>
<?php
$query=mysqli_query($con,"SELECT * FROM friendRequests WHERE userTo='$userLoggedIn' ");
if(mysqli_num_rows($query)==0){
echo "You have no friend requests for now !";}
else{
while($row=mysqli_fetch_array($query)){
$userFrom=$row['userFrom'];
$userFromObj=new User($con,$userFrom);
echo $userFromObj->getFirstAndLastName()." sent you a friend request!"."<br>";
$userFromFriendArray=$userFromObj->getFriendArray();
if(isset($_POST['accept_request'.$userFrom])){
$addFriendQuery=mysqli_query($con,"UPDATE users SET friendArray=CONCAT(friendArray, '$userFrom,') WHERE userName='$userLoggedIn'");
$addFriendQuery2=mysqli_query($con,"UPDATE users SET friendArray=CONCAT(friendArray, '$userLoggedIn,') WHERE userName='$userFrom'");
$deleteQuery=mysqli_query($con,"DELETE FROM friendRequests WHERE userTo='$userLoggedIn'AND userFrom='$userFrom' ");
echo "You are now friends !";
header("Location: Requests.php");
}
if(isset($_POST['ignore_request'.$userFrom])){
$deleteQuery=mysqli_query($con,"DELETE FROM friendRequests WHERE userTo='$userLoggedIn'AND userFrom='$userFrom' ");
echo "You have ignored the request !";
header("Location: Requests.php");
}
?>
<form action="Requests.php" method="POST">
<input type="submit" name="accept_request<?php echo $userFrom; ?>" id="accept_button" value="Accept">
<input type="submit" name="ignore_request<?php echo $userFrom; ?>" id="ignore_button" value="Ignore">
</form>
<?php
}
}
?>
</div><file_sep><?php
include("Header.php");
include("Classes/User.php");
include("Classes/Post.php");
if(isset($_POST['post_body'])){
$post=new Post($con,$_POST['user_from']);
$post->submitPost($_POST['post_body'],$_POST['user_to']);
}
?><file_sep><?php
class Message{
private $userObj;
private $con;
public function __construct($con,$user){
$this->con=$con;
$this->userObj=new User($con,$user);
}
public function getMostRecentUser(){
$userLoggedIn=$this->userObj->getUsername();
$query=mysqli_query($this->con,"SELECT userTo , userFrom FROM messages WHERE userTo='$userLoggedIn' OR userFrom='$userLoggedIn' ORDER BY id DESC LIMIT 1");
if(mysqli_num_rows($query)==0)
return false;
$row=mysqli_fetch_array($query);
$userTo=$row['userTo'];
$userFrom=$row['userFrom'];
if($userTo!=$userLoggedIn){
return $userTo;
}
else{
return $userFrom;
}
}
public function sendMessage($userTo,$body,$date){
if($body!=""){
$userLoggedIn=$this->userObj->getUsername();
$query=mysqli_query($this->con,"INSERT INTO messages VALUES('','$userTo','$userLoggedIn','$body','$date','no','no','no')");
}
}
public function getMessages($otherUser){
$userLoggedIn=$this->userObj->getUsername();
$data="";
$query=mysqli_query($this->con,"UPDATE messages SET opened='yes' WHERE userTo='$userLoggedIn' AND userFrom='$otherUser'");
$getMessagesQuery=mysqli_query($this->con,"SELECT*FROM messages WHERE (userTo='$userLoggedIn' AND userFrom='$otherUser')OR (userTo='$otherUser' AND userFrom='$userLoggedIn')");
while($row=mysqli_fetch_array($getMessagesQuery)){
$userTo=$row['userTo'];
$userFrom=$row['userFrom'];
$body=$row['body'];
$divTop=($userTo==$userLoggedIn) ? "<div class='message'id='green'>":"<div class='message' id='blue'>";
$data=$data.$divTop.$body."</div><br><br>";
}
return $data;
}
public function getLatestMessage($userLoggedIn,$user2){
$detailsArray=array();
$query=mysqli_query($this->con,"SELECT body,userTo,date FROM messages WHERE (userTo='$userLoggedIn' AND userFrom='$user2')OR(userTo='$user2' AND userFrom='$userLoggedIn') ORDER BY id DESC LIMIT 1");
$row=mysqli_fetch_array($query);
$sentBy=($row['userTo']==$userLoggedIn) ? "They said :" : "You said: ";
//Time
$dateTimeNow=date("Y-m-d H:i:s");
$startDate=new DateTime($row['date']);//Post time
$endDate=new DateTime($dateTimeNow);//Now time
$interval=$startDate->diff($endDate);//Diff
if($interval->y>=1){
$timeMessage=$interval->y." year(s) ago";
}else if($interval->m>=1){
if($interval->d==0){$days="ago";}
else if($interval->d==1){$days=$interval->d." days ago";}
else{$days=$interval->d." days ago";}
if($interval->m==1){
$timeMessage=$interval->m." month".$days;
}
else{$timeMessage=$interval->m." months".$days;}
}
else if($interval->d>=1){
if($interval->d==1){
$timeMessage="Yesterday";
}
else{$timeMessage=$interval->d."days ago";}
}
else if($interval->h>=1){
if($interval->h==1){
$timeMessage=$interval->h."hour ago";
}
else{$timeMessage=$interval->h."hours ago";}
}
else if($interval->i>=1){
$timeMessage=$interval->i."minutes ago";
}
else if($interval->i<1){
$timeMessage="Just now";
}
array_push($detailsArray,$sentBy);
array_push($detailsArray,$row['body']);
array_push($detailsArray,$timeMessage);
return $detailsArray;
}
public function getConvos(){
$userLoggedIn=$this->userObj->getUsername();
$returnString="";
$convos=array();
$query=mysqli_query($this->con,"SELECT userTo , userFrom FROM messages WHERE userTo='$userLoggedIn'OR userFrom='$userLoggedIn' ORDER BY id DESC ");
while($row=mysqli_fetch_array($query)){
$userToPush=($row['userTo']!=$userLoggedIn) ? $row['userTo'] : $row['userFrom'];
if(!in_array($userToPush,$convos)){
array_push($convos,$userToPush);
}
}
foreach($convos as $userName){
$userFoundObj=new User($this->con,$userName);
$latestMessageDetails=$this->getLatestMessage($userLoggedIn,$userName);
$dots=(strlen($latestMessageDetails[1])>=12) ? "..." : "";
$split=str_split($latestMessageDetails[1],12);
$split=$split[0].$dots;
$returnString.="<a href='messages.php?u=$userName'> <div class='user_found_messages'> <img src='".$userFoundObj->getProfilePic()."' style='border-radius:5px;margin-right:5px;'>".$userFoundObj->getFirstAndLastName()."<span class='timestamp_smaller' id='grey'>".$latestMessageDetails[2]."</span> <p id='grey' style='margin:0';> ".$latestMessageDetails[0].$split."</p>
</div>
</a>";
}
return $returnString;
}
public function getConvosDropdown($data,$limit){
$page=$data['page'];
$userLoggedIn=$this->userObj->getUsername();
$returnString="";
$convos=array();
if($page==1){
$start=0;
}else{
$start=($page-1)*$limit;
}
$setViewedQuery=mysqli_query($this->con,"UPDATE messages SET viewed='yes' WHERE userTo='$userLoggedIn'");
$query=mysqli_query($this->con,"SELECT userTo , userFrom FROM messages WHERE userTo='$userLoggedIn'OR userFrom='$userLoggedIn' ORDER BY id DESC ");
while($row=mysqli_fetch_array($query)){
$userToPush=($row['userTo']!=$userLoggedIn) ? $row['userTo'] : $row['userFrom'];
if(!in_array($userToPush,$convos)){
array_push($convos,$userToPush);
}
}
$numIterations=0;
$count=1;
foreach($convos as $userName){
if($numIterations++ <$start)
continue;
if($count>$limit)
break;
else
$count++;
$isUnreadQuery=mysqli_query($this->con,"SELECT opened FROM messages WHERE userTo='$userLoggedIn'AND userFrom='$userName'ORDER BY id DESC");
$row=mysqli_fetch_array($isUnreadQuery);
$style=($row['opened']=='no')?"background-color:#DDEDFF;":"";
$userFoundObj=new User($this->con,$userName);
$latestMessageDetails=$this->getLatestMessage($userLoggedIn,$userName);
$dots=(strlen($latestMessageDetails[1])>=12) ? "..." : "";
$split=str_split($latestMessageDetails[1],12);
$split=$split[0].$dots;
$returnString.="<a href='messages.php?u=$userName'> <div class='user_found_messages' style='".$style."'> <img src='".$userFoundObj->getProfilePic()."' style='border-radius:5px;margin-right:5px;'>".$userFoundObj->getFirstAndLastName()."<span class='timestamp_smaller' id='grey'>".$latestMessageDetails[2]."</span> <p id='grey' style='margin:0';> ".$latestMessageDetails[0].$split."</p>
</div>
</a>";
}
if($count>$limit)
$returnString.="<input type='hidden'class='nextPageDropdownData' value='".($page+1)."'><input type='hidden' class='noMoreDropdownData' value='false'>";
else
$returnString.="<input type='hidden' class='noMoreDropdownData' value='true'><p style='text-align:center;'>No more messages to load</p>";
return $returnString;
}
public function getUnreadNumber(){
$userLoggedIn=$this->userObj->getUsername();
$query=mysqli_query($this->con,"SELECT * FROM messages WHERE viewed='no' AND userTo='$userLoggedIn'");
return mysqli_num_rows($query);
}
}
?>
<file_sep><?php
//Variables taken out of form
//-------------------------------
$fname="";//firstName
$lname="";//lastName
$username="";//userName
$em="";//mail
$em2="";//mail confirm
$pw="";//password
$pw2="";//password confirm
$date="";//signDate
$error=array();//Error array
if(isset($_POST['reg_button'])){
//Input variables
//-------------------------
//First name
$fname=strip_tags($_POST['reg_fname']);//Resolve html tags
$fname=str_replace(' ','-',$fname);//Remove unwanted space
$fname=ucfirst($fname);//First letter uppercase
$_SESSION['reg_fname']=$fname;
//Last name
$lname=strip_tags($_POST['reg_lname']);//Resolve html tags
$lname=str_replace(' ','-',$lname);//Remove unwanted space
$lname=ucfirst($lname);//First letter uppercase
$_SESSION['reg_lname']=$lname;
//Username
$username=strip_tags($_POST['reg_username']);//Resolve html tags
$username=str_replace(' ','',$username);//Remove unwanted space
$_SESSION['reg_username']=$username;
//email
$em=strip_tags($_POST['reg_email']);//Resolve html tags
$em=str_replace(' ','',$em);//Remove unwanted space
$em=ucfirst($em);//First letter uppercase
$_SESSION['reg_email']=$em;
//email2
$em2=strip_tags($_POST['reg_email2']);//Resolve html tags
$em2=str_replace(' ','',$em2);//Remove unwanted space
$em2=ucfirst($em2);//First letter uppercase
$_SESSION['reg_email2']=$em2;
//password
$pw=strip_tags($_POST['reg_password']);//Resolve html tags
//password2
$pw2=strip_tags($_POST['reg_password2']);//Resolve html tags
//Date
$date=date("Y-m-d");//Reg date
//------------------------------------------------------------
//Mail confirmation
if($em==$em2){
if(filter_var($em,FILTER_VALIDATE_EMAIL)){
$em=filter_var($em,FILTER_VALIDATE_EMAIL);
//Check if mail exists
$emCheck=mysqli_query($con,"SELECT mail FROM users WHERE mail='$em' ");
$emNoumber=mysqli_num_rows($emCheck);
if($emNoumber>0){
array_push($error,"This email has been used already ");
}
}
else{array_push($error,"Invalid format");}
}
else{array_push($error,"E-mails don't match");}
//----------------------------------------------------------
//Password check
if($pw!=$pw2){
array_push($error,"The passwords don't match each other");
}
if(strlen($pw)>20||strlen($pw)<6){
array_push($error,"The password must contain at least 6 letters , maximum 20");
}
//----------------------------------------------------------
//Username check
if(preg_match('[^A-za-z0-9]',$username)){
array_push($error,"The username can contain only letters and noumbers");
}
if(strlen($username)>20||strlen($username)<2){
array_push($error,"The username must contain at least 2 letters , maximum 20");
}
$usernameCheck=mysqli_query($con,"SELECT mail FROM users WHERE username='$username'" );
$usernameNoumber=mysqli_num_rows($usernameCheck);
if($usernameNoumber>0){
array_push($error,"This usernamer has been already taken");
}
//---------------------------------------------------------
//Lname and fname
if(strlen($fname)>25||strlen($lname)>25||strlen($fname)<2||strlen($lname)<2){
array_push($error,"First name and last name can contain at least 2 letters and maximim 25 letters");
}
//--------------------------------------------------------
//Introducing variables in db
if(empty($error)){
$pw=md5($pw);//Encrypt password
$profilePic="Css/Images/sigla.png";//User picture
$insert=mysqli_query($con,"INSERT INTO users VALUES('','$fname','$lname','$username','$em','$pw','$date','$profilePic','0','none','')");
//Clearin session variables
$_SESSION['reg_fname']="";
$_SESSION['reg_lname']="";
$_SESSION['reg_username']="";
$_SESSION['reg_email']="";
$_SESSION['reg_email2']="";
}
//-------------------------------------------------------
//Last acolada-------down-------
}
?><file_sep># PHP_CRUD_mini_social_site
Mini social media site.
The purpose of this project was to learn PHP.
I have stopped working on this in 2018, because I have discovered MVC pattern and because this project served its purpose(to learn vanilla php, html/cs/js and how to do CRUD operations).
<file_sep>$(document).ready(function(){
//on click sign up , hide sign in button and show resitration form
$("#signup").click(function(){
$("#first").slideUp("slow",function(){
$("#second").slideDown("slow");
});
});
// on click sign up , hide registration and show loh in form
$("#signin").click(function(){
$("#second").slideUp("slow",function(){
$("#first").slideDown("slow");
});
});
});<file_sep><?php
include("../Config/Config.php");
include("Classes/User.php");
include("Classes/Post.php");
$limit=5;//Number of posts when load
$posts=new Post($con,$_REQUEST['userLoggedIn']);
$posts->loadPostsFriends($_REQUEST,$limit);
?><file_sep><?php
require 'Config/Config.php';
require 'Includes/Register_handler.php';
require 'Includes/Login_handler.php';
?>
<!DOCTYPE html>
<html>
<div class="wrapper">
<head>
<title>Welcome to EuroAvia-Bucuresti</title>
<link rel="stylesheet" type="text/css" href="Css/Register_style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="Js/Register_js.js"></script>
</head>
<body>
<?php //Showing register page after pressing register page
if(isset($_POST['reg_button'])){
echo '
<script>
$(document).ready(function(){
$("#first").hide();
$("#second").show();
});
</script>
';
}
?>
<div class="login_box">
<h1>Welcome!</h1>
<div id="first">
<h2>Login</h2>
<form action="Register.php" method="POST">
<input type="text" name="log_username" placeholder="username">
<br>
<input type="<PASSWORD>" name="log_password" placeholder="<PASSWORD>">
<br>
<input type="submit" name="login_button" value="Login">
<br>
<?php if(in_array("Username and password are incorrect",$error)){
echo "Username and password are incorrect";} ?>
<br>
<a href="#" id="signup" class="signup">Need an account? Register here !</a>
</form>
</div>
<div id="second">
<h2>Register</h2>
<form function="Register.php" method="POST">
<input type="text" name="reg_fname" placeholder="First Name" value="<?php if(isset($_SESSION['reg_fname']))
echo $_SESSION['reg_fname'] ?>" required>
<?php if(in_array("First name and last name can contain at least 2 letters and maximim 25 letters",$error)){
echo "<br>First name and last name can contain at least 2 letters and maximim 25 letters";} ?>
<br>
<input type="text" name="reg_lname" placeholder="Last Name"
value="<?php if(isset($_SESSION['reg_lname']))
echo $_SESSION['reg_lname'] ?>" required>
<br>
<input type="text" name="reg_username" placeholder="Username" value="<?php if(isset($_SESSION['reg_username']))
echo $_SESSION['reg_username'] ?>" required>
<?php if(in_array("The username must contain at least 2 letters , maximum 20",$error)){
echo "<br>The username must contain at least 2 letters , maximum 20";}
if(in_array("This usernamer has been already taken",$error)){
echo "<br>This usernamer has been already taken";} ?>
<br>
<input type="email" name="reg_email" placeholder="E-mail" value="<?php if(isset($_SESSION['reg_email']))
echo $_SESSION['reg_email'] ?>" required>
<?php if(in_array("This email has been used already ",$error))
echo "<br>This email has been used already ";
if(in_array("Invalid format",$error))
echo "<br>Invalid format";
if(in_array("E-mails don't match",$error))
echo "<br>E-mails don't match"; ?>
<br>
<input type="email" name="reg_email2" placeholder="E-mail confirm" value="<?php if(isset($_SESSION['reg_email2']))
echo $_SESSION['reg_email2'] ?>" required>
<br>
<input type="<PASSWORD>" name="reg_password" placeholder="<PASSWORD>" required>
<?php if(in_array("The passwords don't match each other",$error))
echo "<br>The passwords don't match each other";
if(in_array("The password must contain at least 6 letters , maximum 20",$error))
echo "<br>The password must contain at least 6 letters , maximum 20";?>
<br>
<input type="password" name="reg_password2" placeholder="<PASSWORD>" required>
<br>
<input type="submit" name="reg_button" value="Register">
<?php if(isset($_POST['reg_button']))
if(empty($error))
echo "You have succesfully registered" ?>
<a href="#" id="signin" class="sigin">Already have an account?Sign in here !</a>
</form>
</div>
</div>
</div>
</body>
</html><file_sep><!DOCTYPE html>
<?php
require 'Config/Config.php';
include("Includes/Classes/User.php");
include("Includes/Classes/Post.php");
if(isset($_SESSION['log_username'])){
$userLoggedIn=$_SESSION['log_username'];
$userDetailsQuery=mysqli_query($con,"SELECT * FROM users WHERE userName='$userLoggedIn'");
$user=mysqli_fetch_array($userDetailsQuery);
}else{header("Location: Register.php");}
?>
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="Css/Header.css">
</head>
<body>
<style type="text/css">
*{
font-size:12px;
font-family: Arial,Helvetica,Sans-serif;
}
</style>
<script>
function toggle(){
var element=document.getElementById("commentSection");
if(element.style.display=="block")
element.style.display="none";
else
element.style.display="block";
}
</script>
<?php
if(isset($_GET['postId'])){
$postId=$_GET['postId'];
}
$userQuery=mysqli_query($con,"SELECT addedBy,userTo FROM posts WHERE id='postId'");
$row=mysqli_fetch_array($userQuery);
$postedTo=$row['addedBy'];
if(isset($_POST['postComment'.$postId])){
$postBody=$_POST['post_body'];
$postBody=mysqli_escape_string($con,$postBody);
$dateTimeNow=date("Y-m-d H:i:s");
$insertPost=mysqli_query($con,"INSERT INTO comments VALUES('','$postBody','$userLoggedIn','$postedTo','$dateTimeNow','no',$postId ) ");
echo "<p>Comment Posted !</p>";
}
?>
<form action="Comment_frame.php?postId=<?php echo $postId; ?>" id="comment_form" method="POST" name="postComment<?php echo $postId; ?>">
<textarea name="post_body"></textarea>
<input type="submit" name="postComment<?php echo $postId; ?>"value="Post">
</form>
<?php
$getComments=mysqli_query($con,"SELECT * FROM comments WHERE postId='$postId' ORDER BY id ASC");
$count=mysqli_num_rows($getComments);
if($count!=0){
while($comment=mysqli_fetch_array($getComments)){
$commentBody=$comment['postBody'];
$postedTo=$comment['postedTo'];
$postedBy=$comment['postedBy'];
$dateAdded=$comment['dateAdded'];
$removed=$comment['removed'];
//Time
$dateTimeNow=date("Y-m-d H:i:s");
$startDate=new DateTime($dateAdded);//Post time
$endDate=new DateTime($dateTimeNow);//Now time
$interval=$startDate->diff($endDate);//Diff
if($interval->y>=1){
$timeMessage=$interval->y." year(s) ago";
}else if($interval->m>=1){
if($interval->d==0){$days="ago";}
else if($interval->d==1){$days=$interval->d." days ago";}
else{$days=$interval->d." days ago";}
if($interval->m==1){
$timeMessage=$interval->m." month".$days;
}
else{$timeMessage=$interval->m." months".$days;}
}
else if($interval->d>=1){
if($interval->d==1){
$timeMessage="Yesterday";
}
else{$timeMessage=$interval->d."days ago";}
}
else if($interval->h>=1){
if($interval->h==1){
$timeMessage=$interval->h."hour ago";
}
else{$timeMessage=$interval->h."hours ago";}
}
else if($interval->i>=1){
$timeMessage=$interval->i."minutes ago";
}
else if($interval->i<1){
$timeMessage="Just now";
}
$userObj=new User($con,$postedBy);
?>
<div class="comment_section">
<a href="<?php echo $postedBy; ?>" target="_parent">
<img src="<?php echo $userObj->getProfilePic(); ?> "title="<?php echo $postedBy; ?>" style="float:left;"height=30 >
<?php echo $userObj->getFirstAndLastName(); ?>
</a>
<?php echo $timeMessage."<br>".$commentBody; ?>
<hr>
</div>
<?php
}
}
else{
echo "<center>No comments to show</center>";
}
?>
</body>
</html><file_sep><?php
ob_start();
session_start();
$timezone=date_default_timezone_set("Europe/Bucharest");
$con=mysqli_connect("localhost","root","","euroavia-s");//Conn
if(mysqli_connect_error()){
echo mysqli_connect_error();
}
?><file_sep><?php
if(isset($_POST['login_button'])){
$username=$_POST['log_username'];//insert username
$_SESSION['log_username']=$_POST['log_username'];
$pw=strip_tags($_POST['log_password']);
$pw=md5($pw);//insert password
//Check user and pw
//---------------------------------------------------
$checkQuery=mysqli_query($con,"SELECT * FROM users WHERE userName='$username' AND password='$pw' ");
$queryCheck=mysqli_num_rows($checkQuery);
echo $queryCheck;
echo $_SESSION['log_username'];
if($queryCheck==1){
$row=mysqli_fetch_array($checkQuery);
$username=$row['userName'];
$_SESSION['username']=$username;
header("Location: EuroAvia.php");
exit();
}else{array_push($error,"Username and password are incorrect");}
//---------------------------------------------------
}
?><file_sep><?php
include ("includes/header.php");
include("includes/Classes/Message.php");
include("includes/Classes/User.php");
include("includes/Classes/Post.php");
$messageObj=new Message($con,$userLoggedIn);
if(isset($_GET['u']))
$userTo=$_GET['u'];
else{
$userTo=$messageObj->getMostRecentUser();
if($userTo==false)
$userTo='new';
}
if($userTo!="new")
$userToObj=new User($con,$userTo);
if(isset($_POST['post_message'])){
if(isset($_POST['message_body'])){
$body=mysqli_real_escape_string($con,$_POST['message_body']);
$date=date("Y-m-d H:i:s");
$messageObj->sendMessage($userTo,$body,$date);
header("Location:Messages.php?u=$userTo");
}
}
?>
<div class="user_details column" id="profile_messages">
<a href="<?php echo $userLoggedIn; ?>">
<img src="<?php echo $user['profilePic']; ?>">
</a>
<div class="user_details_left_right">
<a href="<?php echo $userLoggedIn; ?>">
<?php
echo "<br>".$user['firstName']." ".$user['lastName']."<br>";?>
</a>
<?php
echo "Events :".$user['events']."<br>";
echo " Departament :".$user['department'];
?>
</div>
</div>
<div class="main_column column" id="main_cloumn">
<?php
if($userTo !="new"){
echo "<h4>You and <a href='$userTo'>".$userToObj->getFirstAndLastName()."</a></h4><br><br>";
echo "<div class='loaded_messages' id='scroll_messages'>";
echo $messageObj->getMessages($userTo);
echo"</div>";
}
?>
<div class="message_post">
<form action="" method="POST">
<?php
if($userTo=="new"){
echo"Select the friend you would like to message <br><br>";
?>
To: <input type='text' onkeyup='getUsers(this.value,"<?php echo $userLoggedIn;?>")' name='q' placeholder='Name' autocomplete='off' id='search_text_input'>
<?php
echo"<div class='results'></div>";
}
else{
echo"<textarea name='message_body' id='message_textarea' placeholder='Write your message'> </textarea> ";
echo"<input type='submit' name='post_message' class='info' id='message_submit' value='Send'>";
}
?>
</form>
</div>
</div>
<script >
var div=document.getElementById("scroll_messages");
div.scrollTop=div.scrollHeight;
</script>
<div class="user_details column" id="conversations">
<h4>Conversations</h4>
<div class="loaded_conversations">
<?php echo $messageObj->getConvos(); ?>
</div>
<br>
<a href="Messages.php?u=new">New Message</a>
</div><file_sep><!DOCTYPE html>
<?php
require 'Config/Config.php';
include("Includes/Classes/User.php");
include("Includes/Classes/Post.php");
if(isset($_SESSION['log_username'])){
$userLoggedIn=$_SESSION['log_username'];
$userDetailsQuery=mysqli_query($con,"SELECT * FROM users WHERE userName='$userLoggedIn'");
$user=mysqli_fetch_array($userDetailsQuery);
}else{header("Location: Register.php");}
?>
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="Css/Header.css">
</head>
<body>
<style type="text/css">
*{
font-family: Arial,Helvetica,sans-serif;
}
body{
background-color: #fff;
}
form{
top:21px;
position: absolute;
}
</style>
<?php
if(isset($_GET['postId'])){
$postId=$_GET['postId'];
}
$getFlies=mysqli_query($con,"SELECT addedBy , flies FROM posts WHERE id='$postId'");
$row=mysqli_fetch_array($getFlies);
$totalFlies=$row['flies'];
$userFlying=$row['addedBy'];
$userDetailsQuery=mysqli_query($con,"SELECT * FROM users WHERE userName='$userFlying'");
$row=mysqli_fetch_array($userDetailsQuery);
$totalUserFlies=$row['events'];
//Like button
if(isset($_POST['fly_button'])){
$totalFlies++;
$totalUserFlies++;
$query=mysqli_query($con,"UPDATE posts SET flies='$totalFlies' WHERE id='$postId'");
$userFlies=mysqli_query($con,"UPDATE users SET events='$totalUserFlies' WHERE userName='$userFlying'");
$insertUser=mysqli_query($con,"INSERT INTO fly VALUES('','$userLoggedIn','$postId') ");
//Insert not
}
//Unlike button
if(isset($_POST['unfly_button'])){
$totalFlies--;
$totalUserFlies--;
$query=mysqli_query($con,"UPDATE posts SET flies='$totalFlies' WHERE id='$postId'");
$userFlies=mysqli_query($con,"UPDATE users SET events='$totalUserFlies' WHERE userName='$userFlying'");
$insertUser=mysqli_query($con,"DELETE FROM fly WHERE userName='$userLoggedIn' AND postId='$postId' ");
}
//Check for previous likes
$checkQuery=mysqli_query($con,"SELECT * FROM fly WHERE userName='$userLoggedIn' AND postId='$postId'");
$numRows=mysqli_num_rows($checkQuery);
if($numRows>0){
echo '<form action="Fly.php?postId='.$postId.'" method="POST" >
<input type="submit" class="comment_fly" name="unfly_button" value="Unfly">
<div class="fly_value">
('.$totalFlies.' Flying)
</div>
</form>';
}
else{
echo '<form action="Fly.php?postId='.$postId.'" method="POST" >
<input type="submit" class="comment_fly" name="fly_button" value="Fly">
<div class="fly_value">
('.$totalFlies.' Flying)
</div>
</form>';
}
?>
</body>
</html><file_sep><?php
include("../config/config.php");
include("Classes/User.php");
include("Classes/Message.php");
$userLoggedIn=$_SESSION['log_username'];
$limit=7;//Number of messages
$message=new Message($con,$userLoggedIn);
echo $message->getConvosDropdown($_REQUEST,$limit);
?>
|
eb81d522a8c0d335f468ed9c1f6dca32400bed97
|
[
"Markdown",
"JavaScript",
"PHP"
] | 17
|
PHP
|
Ionii0/PHP_CRUD_mini_social_site
|
cb83a1a3f1fe8e158cb39e3370649658a2b26959
|
5e563aefec80bf854536036d0a9913c91e89fe0f
|
refs/heads/master
|
<file_sep><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<link href="../style.css" rel="stylesheet" type="text/css"/>
<link href="https://fonts.googleapis.com/css?family=Acme" rel="stylesheet">
<title>Exercice 4 </title>
</head>
<body>
<header>
<a href="/exercice1/index.php" class="btn-success">Exercice 1</a>
<a href="/exercice2/index.php" class="btn-primary">Exercice 2</a>
<a href="/exercice3/index.php" class="btn-success">Exercice 3</a>
<a href="/exercice4/index.php" class="btn-primary">Exercice 4</a>
<a href="/exercice5/index.php" class="btn-success">Exercice 5</a>
<a href="/exercice6/index.php" class="btn-primary">Exercice 6</a>
<a href="/exercice7/index.php" class="btn-success">Exercice 7</a>
<a href="/exercice8/index.php" class="btn-primary">Exercice 8</a>
</header>
<!-- Créer une variable et l'initialiser à 1.
Tant que cette variable n'atteint pas 10, il faut :
l'afficher
l'incrementer de la moitié de sa valeur -->
<div id="style">
<?php
//Délcaration de ma variable
$third = 1;
//Déclaration de ma condtion tant que ma variables n'est pas inférieur à 10
while ($third < 10) {
//Affiche valeur de la variable
echo $third;
?>
<br/>
<?php
//Affiche la valeur de la variable incrémenter de la moitié de sa valeur
//$third = $third + $third / 2;
$third += $third / 2;
}
?>
</div>
</body>
</html><file_sep><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<link href="../style.css" rel="stylesheet" type="text/css"/>
<link href="https://fonts.googleapis.com/css?family=Acme" rel="stylesheet">
<title>Exercice 3 </title>
</head>
<body>
<header>
<a href="/exercice1/index.php" class="btn-success">Exercice 1</a>
<a href="/exercice2/index.php" class="btn-primary">Exercice 2</a>
<a href="/exercice3/index.php" class="btn-success">Exercice 3</a>
<a href="/exercice4/index.php" class="btn-primary">Exercice 4</a>
<a href="/exercice5/index.php" class="btn-success">Exercice 5</a>
<a href="/exercice6/index.php" class="btn-primary">Exercice 6</a>
<a href="/exercice7/index.php" class="btn-success">Exercice 7</a>
<a href="/exercice8/index.php" class="btn-primary">Exercice 8</a>
</header>
<!-- Créer deux variables. Initialiser la première à 100 et la deuxième avec un nombre compris en 1 et 100.
Tant que la première variable n'est pas inférieur ou égale à 10 :
multiplier la première variable avec la deuxième
afficher le résultat
décrémenter la première variable -->
<div id="style">
<?php
$first = 100;
$second = 35;
while ($first >= 10) {
echo $first * $second;
?>
<br/>
<?php
$first--;
}
?>
</div>
</body>
</html>
<file_sep><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<link href="../style.css" rel="stylesheet" type="text/css"/>
<link href="https://fonts.googleapis.com/css?family=Acme" rel="stylesheet">
<title>Exercice 5 </title>
</head>
<body>
<header>
<a href="/exercice1/index.php" class="btn-success">Exercice 1</a>
<a href="/exercice2/index.php" class="btn-primary">Exercice 2</a>
<a href="/exercice3/index.php" class="btn-success">Exercice 3</a>
<a href="/exercice4/index.php" class="btn-primary">Exercice 4</a>
<a href="/exercice5/index.php" class="btn-success">Exercice 5</a>
<a href="/exercice6/index.php" class="btn-primary">Exercice 6</a>
<a href="/exercice7/index.php" class="btn-success">Exercice 7</a>
<a href="/exercice8/index.php" class="btn-primary">Exercice 8</a>
</header>
<!-- En allant de 1 à 15 avec un pas de 1, afficher le message On y arrive presque. -->
<div id="style">
<?php
//Le for ne m'oblige pas à déclarer la variable séparément
//( délcaration variable; conditon; incrémentation)
for ($foot = 1; $foot <= 15; $foot++) {
?>
<br/>
<?php
//Ecriture avec ma variable juste pour vérifier le nombres de lignes
//echo $foot . ' On y arrive presque.';
//Affichage de ma valeur et d'une petite phrase
echo ' On y arrive presque.';
}
?>
</div>
</body>
</html><file_sep><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<link href="https://fonts.googleapis.com/css?family=Acme" rel="stylesheet">
<link href="../style.css" rel="stylesheet" type="text/css"/>
<title>Exercice 2 </title>
</head>
<body>
<header>
<a href="/exercice1/index.php" class="btn-success">Exercice 1</a>
<a href="/exercice2/index.php" class="btn-primary">Exercice 2</a>
<a href="/exercice3/index.php" class="btn-success">Exercice 3</a>
<a href="/exercice4/index.php" class="btn-primary">Exercice 4</a>
<a href="/exercice5/index.php" class="btn-success">Exercice 5</a>
<a href="/exercice6/index.php" class="btn-primary">Exercice 6</a>
<a href="/exercice7/index.php" class="btn-success">Exercice 7</a>
<a href="/exercice8/index.php" class="btn-primary">Exercice 8</a>
</header>
<!-- Créer deux variables. Initialiser la première à 0 et la deuxième avec un nombre compris en 1 et 100.
Tant que la première variable n'est pas supérieur à 20 : multiplier la première variable avec la deuxième
afficher le résultat, incrementer la première variable -->
<div id="style">
<?php
//Déclaration de mes 2 variables
$departure = 0;
$centaines = 49;
//Déclaration de ma condition tant que c'est inférieur à 21
while ($departure <= 20) {
//Affichage du resultat de la multiplication de ma variable 1 * variable 2
echo $departure * $centaines;
?>
<br/>
<?php
//Ajout d'une ligne à chaque fois tant que la boucles'éxécute
$departure++;
}
?>
</div>
</body>
</html>
<file_sep><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<link href="https://fonts.googleapis.com/css?family=Acme" rel="stylesheet">
<link href="../style.css" rel="stylesheet" type="text/css"/>
<title>Exercice 1</title>
</head>
<body>
<header>
<a href="/exercice1/index.php" class="btn-success">Exercice 1</a>
<a href="/exercice2/index.php" class="btn-primary">Exercice 2</a>
<a href="/exercice3/index.php" class="btn-success">Exercice 3</a>
<a href="/exercice4/index.php" class="btn-primary">Exercice 4</a>
<a href="/exercice5/index.php" class="btn-success">Exercice 5</a>
<a href="/exercice6/index.php" class="btn-primary">Exercice 6</a>
<a href="/exercice7/index.php" class="btn-success">Exercice 7</a>
<a href="/exercice8/index.php" class="btn-primary">Exercice 8</a>
</header>
<!-- Créer une variable et l'initialiser à 0. Tant que cette variable n'atteint pas 10, il faut :
l'afficher l'incrementer-->
<div id="style">
<?php
//variable initialisée à zéro
$number = 0;
//boucle qui va répéter l'action moins de 10 fois
while ($number < 10) {
// affiche la phrase avec un saut de ligne
echo 'Je pars en vacances ' . $number . ' fois par an';
?>
<br />
<?php
//incrémentation de 1 en 1 jusqu'à la limite donnée de inf 10
$number++;
}
?>
</div>
</body>
</html>
|
e48c61b3a3e578e5bf9efa8e2f86107015d66182
|
[
"PHP"
] | 5
|
PHP
|
AudreyLesterlin/PHP-Part3-Exo1-8
|
fda4b24f80578c870cae82f79ccc41b199570baf
|
7ff8ebb27e1fc6667fd741317237f5ff632f3117
|
refs/heads/master
|
<repo_name>nutan-priya/SMC3_VolumeProject_Selenium<file_sep>/src/tests/ItemAddDeleteFunctionalityTests.java
package tests;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import pages.ItemDetails;
import pages.Login;
import utilities.CommonFunctions;
import utilities.ExceptionalHandlingFunctions;
import utilities.PropertyFileUtility;
public class ItemAddDeleteFunctionalityTests {
WebDriver driver;
Login loginToApplication;
ItemDetails itemDetails;
PropertyFileUtility propertyValue = new PropertyFileUtility("./Files/"+"/DataFile.properties");
CommonFunctions utilityfunctions = new CommonFunctions(driver);
@BeforeMethod
public void start()
{
System.setProperty("webdriver.chrome.driver", "./ExternalFiles/"+"/chromedriver.exe");
driver=new ChromeDriver();
driver.manage().window().maximize();
driver.navigate().to(propertyValue.getValue("TestingURL"));
loginToApplication=new Login(driver);
loginToApplication.LoginToApplication(propertyValue.getValue("loginUserName"),propertyValue.getValue("loginPassword"));
}
//Test to verify Add item button is present and Delete Item is Not present for One Item
@Test(priority=1)
public void verifyAddItemBtn() throws Exception
{
try {
Thread.sleep(3000);
itemDetails=new ItemDetails(driver);
utilityfunctions.isElementDisplayed(driver.findElement(itemDetails.AddItemBtn));
Assert.assertFalse(driver.findElement(By.xpath("//input[@id='deleteItem' and @style='display: none;']")).isDisplayed());
System.out.println("Verified Add Button and on single item, there is no Delete Button.");
} catch (Exception e) {
System.out.println(e.getMessage());
Assert.fail();
ExceptionalHandlingFunctions.captureScreenShot(driver, Thread.currentThread().getStackTrace()[1].getMethodName());
ExceptionalHandlingFunctions.writeTOLog(e.getMessage(),Thread.currentThread().getStackTrace()[1].getMethodName());
}
}
//Test to verify clicking on Add Item, Adds 2nd Item and Delete button added to both the item section.
@Test(priority=2)
public void clickAddItemOnce() throws Exception
{
try {
Thread.sleep(3000);
itemDetails=new ItemDetails(driver);
itemDetails.clickAdditemBtn();
Thread.sleep(2000);
utilityfunctions.isElementDisplayed(driver.findElement(itemDetails.ItemNo1Header));
utilityfunctions.isElementDisplayed(driver.findElement(itemDetails.ItemNo2Header));
utilityfunctions.isElementDisplayed(driver.findElement(itemDetails.DeleteItemBtn1));
utilityfunctions.isElementDisplayed(driver.findElement(itemDetails.DeleteItemBtn2));
utilityfunctions.isElementDisplayed(driver.findElement(itemDetails.AddItemBtn));
//Assert.assertTrue(driver.findElement(By.xpath("//input[@id='addItemBtn' and @style='display: block;']")).isDisplayed());---why cannot use this
System.out.println("Verified clicking on Add Item, Adds 2nd Item and Delete button added to both the item section.");
}catch (Exception e) {
System.out.println(e.getMessage());
Assert.fail();
ExceptionalHandlingFunctions.captureScreenShot(driver, Thread.currentThread().getStackTrace()[1].getMethodName());
ExceptionalHandlingFunctions.writeTOLog(e.getMessage(),Thread.currentThread().getStackTrace()[1].getMethodName());
}
}
//Test to verify clicking on Add Item 5 times, Adds 5 Item and Delete button gets added to all the item section. Add button gets removed.
@Test(priority=3)
public void clickAdd5times() throws Exception
{
try {
Thread.sleep(3000);
itemDetails=new ItemDetails(driver);
itemDetails.clickAdditemBtn();
Thread.sleep(2000);
itemDetails.clickAdditemBtn();
Thread.sleep(2000);
itemDetails.clickAdditemBtn();
Thread.sleep(2000);
itemDetails.clickAdditemBtn();
Thread.sleep(2000);
CommonFunctions utilityfunctions = new CommonFunctions(driver);
utilityfunctions.isDisplayedBy(itemDetails.ItemNo1Header, true);
utilityfunctions.isDisplayedBy(itemDetails.ItemNo2Header, true);
utilityfunctions.isDisplayedBy(itemDetails.ItemNo3Header, true);
utilityfunctions.isDisplayedBy(itemDetails.ItemNo4Header, true);
utilityfunctions.isDisplayedBy(itemDetails.ItemNo5Header, true);
utilityfunctions.isDisplayedBy(itemDetails.DeleteItemBtn1, true);
utilityfunctions.isDisplayedBy(itemDetails.DeleteItemBtn2, true);
utilityfunctions.isDisplayedBy(itemDetails.DeleteItemBtn3, true);
utilityfunctions.isDisplayedBy(itemDetails.DeleteItemBtn4, true);
utilityfunctions.isDisplayedBy(itemDetails.DeleteItemBtn5, true);
Assert.assertFalse(driver.findElement(By.xpath("//input[@id='addItemBtn' and @style='display: none;']")).isDisplayed());
System.out.println("Verified clicking on Add Item 5 times, Adds 5 Item and Delete button added to all the item section. Add button gets removed.");
} catch (Exception e) {
System.out.println(e.getMessage());
Assert.fail();
ExceptionalHandlingFunctions.captureScreenShot(driver, Thread.currentThread().getStackTrace()[1].getMethodName());
ExceptionalHandlingFunctions.writeTOLog(e.getMessage(),Thread.currentThread().getStackTrace()[1].getMethodName());
}
}
@Test(priority=4)
public void deleteItemFunctionality() throws Exception
{
try {
Thread.sleep(3000);
itemDetails=new ItemDetails(driver);
// Filling up the details in Item no1 section.
itemDetails.setQuantity(propertyValue.getValue("validQuantity1"));
Thread.sleep(3000);
String QuantityItem1= itemDetails.getQuantity();
String PackagingItem1=itemDetails.setPackagingTypeBasket();
String ClassItem1=itemDetails.setClass85();
String StackableItem1=itemDetails.setStackableYes();
itemDetails.setLength(propertyValue.getValue("validLength1"));
String lengthItem1= itemDetails.getLength();
itemDetails.setWidth(propertyValue.getValue("validWidth1"));
String WidthItem1= itemDetails.getWidth();
itemDetails.setHeight(propertyValue.getValue("validHeight1"));
String heightItem1= itemDetails.getHeight();
itemDetails.setWeight(propertyValue.getValue("validWeight1"));
String weightItem1= itemDetails.getWeight();
itemDetails.setCommodity(propertyValue.getValue("validCommodity4char"));
String commodityItem1= itemDetails.getCommodity();
//Adding 4 more Item section and keeping it blank
itemDetails=new ItemDetails(driver);
itemDetails.clickAdditemBtn();
Thread.sleep(2000);
itemDetails.clickAdditemBtn();
Thread.sleep(2000);
itemDetails.clickAdditemBtn();
Thread.sleep(2000);
itemDetails.clickAdditemBtn();
Thread.sleep(2000);
//Verifying the details entered in the Item No1. section after adding 4 more item section.
utilityfunctions.validationEquals(propertyValue.getValue("validQuantity1"), QuantityItem1);
utilityfunctions.validationEquals(propertyValue.getValue("validLength1"), lengthItem1);
utilityfunctions.validationEquals(propertyValue.getValue("validWidth1"), WidthItem1);
utilityfunctions.validationEquals(propertyValue.getValue("validHeight1"), heightItem1);
utilityfunctions.validationEquals(propertyValue.getValue("validWeight1"), weightItem1);
utilityfunctions.validationEquals(propertyValue.getValue("validCommodity4char"), commodityItem1);
utilityfunctions.validationEquals(PackagingItem1, "Basket");
utilityfunctions.validationEquals(ClassItem1, "85");
utilityfunctions.validationEquals(StackableItem1, "Yes");
//Filling all details in Item no.5
itemDetails.setQuantity5(propertyValue.getValue("quantity5"));
Thread.sleep(3000);
String QuantityItem5= itemDetails.getQuantity5();
String PackagingItem5=itemDetails.setPackagingTypeBox();
String ClassItem5=itemDetails.setClass92();
String StackableItem5=itemDetails.setItem5StackableNo();
itemDetails.setLength5(propertyValue.getValue("length5"));
String lengthItem5= itemDetails.getLength5();
itemDetails.setWidth5(propertyValue.getValue("width5"));
String WidthItem5= itemDetails.getWidth5();
itemDetails.setHeight5(propertyValue.getValue("height5"));
String heightItem5= itemDetails.getHeight5();
itemDetails.setWeight5(propertyValue.getValue("weight5"));
String weightItem5= itemDetails.getWeight5();
itemDetails.setCommodity5(propertyValue.getValue("CommodityDesc5"));
String commodityItem5= itemDetails.getCommodity5();
//Verifying Add item button has got removed.
Assert.assertFalse(driver.findElement(By.xpath("//input[@id='addItemBtn' and @style='display: none;']")).isDisplayed());
//Deleting Item No.4
itemDetails.clickDeleteItem4();
//Verifying 4 items section header and 4 delete button.
CommonFunctions utilityfunctions = new CommonFunctions(driver);
utilityfunctions.isDisplayedBy(itemDetails.ItemNo1Header, true);
utilityfunctions.isDisplayedBy(itemDetails.ItemNo2Header, true);
utilityfunctions.isDisplayedBy(itemDetails.ItemNo3Header, true);
utilityfunctions.isDisplayedBy(itemDetails.ItemNo4Header, true);
utilityfunctions.isDisplayedBy(itemDetails.DeleteItemBtn1, true);
utilityfunctions.isDisplayedBy(itemDetails.DeleteItemBtn2, true);
utilityfunctions.isDisplayedBy(itemDetails.DeleteItemBtn3, true);
utilityfunctions.isDisplayedBy(itemDetails.DeleteItemBtn5, true);
//Verified Add Item Button has got added.
utilityfunctions.isElementDisplayed(driver.findElement(itemDetails.AddItemBtn));
//Verifying that the Item no. 5 details are changed to Item no 4 after deleting Item no.4
utilityfunctions.validationEquals(driver.findElement(itemDetails.Quantity4).getAttribute("value"), QuantityItem5 );
utilityfunctions.validationEquals(itemDetails.getPackagingTypeBox(), PackagingItem5);
utilityfunctions.validationEquals(itemDetails.getClass92(), ClassItem5);
utilityfunctions.validationEquals(itemDetails.getItem4StackableNo(), StackableItem5);
utilityfunctions.validationEquals(driver.findElement(itemDetails.Length4).getAttribute("value"), lengthItem5 );
utilityfunctions.validationEquals(driver.findElement(itemDetails.Width4).getAttribute("value"), WidthItem5 );
utilityfunctions.validationEquals(driver.findElement(itemDetails.Height4).getAttribute("value"), heightItem5 );
utilityfunctions.validationEquals(driver.findElement(itemDetails.Weight4).getAttribute("value"), weightItem5 );
utilityfunctions.validationEquals(driver.findElement(itemDetails.CommodityDesc4).getAttribute("value"), commodityItem5 );
System.out.println("Validated: After deleting 4th item, 5th item details comes to 4th item.");
}catch (Exception e) {
System.out.println(e.getMessage());
Assert.fail();
ExceptionalHandlingFunctions.captureScreenShot(driver, Thread.currentThread().getStackTrace()[1].getMethodName());
ExceptionalHandlingFunctions.writeTOLog(e.getMessage(),Thread.currentThread().getStackTrace()[1].getMethodName());
}
}
@AfterMethod
public void close()
{
driver.close();
}
}
<file_sep>/src/tests/ShipmentDetailsTests.java
package tests;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import pages.Login;
import pages.ShipmentDetails;
import utilities.CommonFunctions;
import utilities.ExceptionalHandlingFunctions;
import utilities.PropertyFileUtility;
public class ShipmentDetailsTests {
WebDriver driver;
Login loginToApplication;
ShipmentDetails shipmentDetails;
PropertyFileUtility propertyValue = new PropertyFileUtility("./Files/"+"/DataFile.properties");
CommonFunctions utilityfunctions = new CommonFunctions(driver);
@BeforeMethod
public void start()
{
System.setProperty("webdriver.chrome.driver", "./ExternalFiles/"+"/chromedriver.exe");
driver=new ChromeDriver();
driver.manage().window().maximize();
driver.navigate().to(propertyValue.getValue("TestingURL"));
loginToApplication=new Login(driver);
loginToApplication.LoginToApplication(propertyValue.getValue("loginUserName"),propertyValue.getValue("loginPassword"));
}
@Test(priority=1)
public void payerFieldValidation() throws Exception
{
try {
Thread.sleep(3000);
shipmentDetails = new ShipmentDetails(driver);
String payerConsignee=shipmentDetails.setPayerConsignee();
utilityfunctions.validationEquals(payerConsignee , "Consignee");
System.out.println("Payer selected as Consignee.");
String payerShipper=shipmentDetails.setPayerShipper();
utilityfunctions.validationEquals(payerShipper , "Shipper");
System.out.println("Payer selected as Shipper.");
String payerThirdParty=shipmentDetails.setPayerThirdParty();
utilityfunctions.validationEquals(payerThirdParty , "Third Party");
System.out.println("Payer selected as Third Party.");
}catch (Exception e) {
System.out.println(e.getMessage());
Assert.fail();
ExceptionalHandlingFunctions.captureScreenShot(driver, Thread.currentThread().getStackTrace()[1].getMethodName());
ExceptionalHandlingFunctions.writeTOLog(e.getMessage(),Thread.currentThread().getStackTrace()[1].getMethodName());
}
}
@Test(priority=2)
public void paymentTermsFieldValidation() throws Exception
{
try {
Thread.sleep(3000);
shipmentDetails = new ShipmentDetails(driver);
String paymentPrepaid=shipmentDetails.setPaymentTermsPrepaid();
utilityfunctions.validationEquals(paymentPrepaid , "Prepaid");
System.out.println("Payment Terms selected as Prepaid.");
String paymentCollect=shipmentDetails.setPaymentTermsCollect();
utilityfunctions.validationEquals(paymentCollect , "Collect");
System.out.println("Payment Terms selected as Collect.");
String paymentThirdParty=shipmentDetails.setPaymentTermsThirdParty();
utilityfunctions.validationEquals(paymentThirdParty , "Third Party");
System.out.println("Payment Terms selected as Third Party.");
String paymentOther=shipmentDetails.setPaymentTermsOther();
utilityfunctions.validationEquals(paymentOther , "Other");
System.out.println("Payment Terms selected as Other");
}catch (Exception e) {
System.out.println(e.getMessage());
Assert.fail();
ExceptionalHandlingFunctions.captureScreenShot(driver, Thread.currentThread().getStackTrace()[1].getMethodName());
ExceptionalHandlingFunctions.writeTOLog(e.getMessage(),Thread.currentThread().getStackTrace()[1].getMethodName());
}
}
@Test(priority=3)
public void validLinearFeetValidation() throws Exception
{
try {
shipmentDetails = new ShipmentDetails(driver);
shipmentDetails.setTotalLinearFeet(propertyValue.getValue("validLinearFt1"));
Thread.sleep(2000);
//utilityfunctions.validationIsEmpty(shipmentDetails.getNoMessageforValidInput());---positive assertion
shipmentDetails.clearMethodByName("vltl_totallinearfeet");
shipmentDetails.setTotalLinearFeet(propertyValue.getValue("validLinearFt2"));
Thread.sleep(2000);
shipmentDetails.clearMethodByName("vltl_totallinearfeet");
shipmentDetails.setTotalLinearFeet(propertyValue.getValue("validLinearFt3"));
Thread.sleep(2000);
shipmentDetails.clearMethodByName("vltl_totallinearfeet");
shipmentDetails.setTotalLinearFeet(propertyValue.getValue("validLinearFt4"));
Thread.sleep(2000);
System.out.println("Validated Linear feet field with valid values ");
}catch (Exception e) {
System.out.println(e.getMessage());
Assert.fail();
ExceptionalHandlingFunctions.captureScreenShot(driver, Thread.currentThread().getStackTrace()[1].getMethodName());
ExceptionalHandlingFunctions.writeTOLog(e.getMessage(),Thread.currentThread().getStackTrace()[1].getMethodName());
}
}
@Test(priority=4)
public void invalidLinearFeetValidation() throws Exception
{
try {
Thread.sleep(3000);
shipmentDetails = new ShipmentDetails(driver);
shipmentDetails.setTotalLinearFeet(propertyValue.getValue("invalidLinearFt1"));
Thread.sleep(2000);
utilityfunctions.isElementDisplayed(shipmentDetails.getLengthLinearFtErrorMessage());
shipmentDetails.clearMethodByName("vltl_totallinearfeet");
shipmentDetails.setTotalLinearFeet(propertyValue.getValue("invalidLinearFt2"));
Thread.sleep(2000);
utilityfunctions.isElementDisplayed(shipmentDetails.getLengthLinearFtErrorMessage());
shipmentDetails.clearMethodByName("vltl_totallinearfeet");
shipmentDetails.setTotalLinearFeet(propertyValue.getValue("invalidLinearFt3"));
Thread.sleep(2000);
utilityfunctions.validationEquals("", shipmentDetails.getTotalLinearFeet());
System.out.println("Validated Linear feet field with invalid values");
}catch (Exception e) {
System.out.println(e.getMessage());
Assert.fail();
ExceptionalHandlingFunctions.captureScreenShot(driver, Thread.currentThread().getStackTrace()[1].getMethodName());
ExceptionalHandlingFunctions.writeTOLog(e.getMessage(),Thread.currentThread().getStackTrace()[1].getMethodName());
}
}
@AfterMethod
public void close()
{
driver.close();
}
}
<file_sep>/src/tests/AccessorialsTest.java
package tests;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import pages.Accessorials;
import pages.Login;
import utilities.CommonFunctions;
import utilities.ExceptionalHandlingFunctions;
import utilities.PropertyFileUtility;
public class AccessorialsTest {
WebDriver driver;
Login loginToApplication;
Accessorials accessorialDetails;
PropertyFileUtility propertyValue = new PropertyFileUtility("./Files/"+"/DataFile.properties");
CommonFunctions utilityfunctions = new CommonFunctions(driver);
@BeforeMethod
public void start()
{
System.setProperty("webdriver.chrome.driver", "./ExternalFiles/"+"/chromedriver.exe");
driver=new ChromeDriver();
driver.manage().window().maximize();
driver.navigate().to(propertyValue.getValue("TestingURL"));
loginToApplication=new Login(driver);
loginToApplication.LoginToApplication(propertyValue.getValue("loginUserName"),propertyValue.getValue("loginPassword"));
}
@Test
public void accessorialsCheckBoxValidation() throws Exception
{
try {
Thread.sleep(4000);
accessorialDetails = new Accessorials(driver);
//Test to verify the accessorial check boxes when Checked
accessorialDetails.setAccessorials();
Assert.assertTrue(driver.findElement(By.xpath("//label[contains(text(),'Notify Before Delivery')]/preceding::input[@type='checkbox'][1]")).isSelected());
Assert.assertTrue(driver.findElement(By.xpath("//label[contains(text(),'Construction Site Pickup')]/preceding::input[@type='checkbox'][1]")).isSelected());
Assert.assertTrue(driver.findElement(By.xpath("//label[contains(text(),'Construction Site Delivery')]/preceding::input[@type='checkbox'][1]")).isSelected());
Assert.assertTrue(driver.findElement(By.xpath("//label[contains(text(),'Lift Gate Service Pickup')]/preceding::input[@type='checkbox'][1]")).isSelected());
Assert.assertTrue(driver.findElement(By.xpath("//label[contains(text(),'Lift Gate Service Delivery')]/preceding::input[@type='checkbox'][1]")).isSelected());
Assert.assertTrue(driver.findElement(By.xpath("//label[contains(text(),'Limited Access Pickup')]/preceding::input[@type='checkbox'][1]")).isSelected());
Assert.assertTrue(driver.findElement(By.xpath("//label[contains(text(),'Limited Access Delivery')]/preceding::input[@type='checkbox'][1]")).isSelected());
Assert.assertTrue(driver.findElement(By.xpath("//label[contains(text(),'Residential Pickup')]/preceding::input[@type='checkbox'][1]")).isSelected());
Assert.assertTrue(driver.findElement(By.xpath("//label[contains(text(),'Residential Delivery')]/preceding::input[@type='checkbox'][1]")).isSelected());
Assert.assertTrue(driver.findElement(By.xpath("//label[contains(text(),'Hazardous Material')]/preceding::input[@type='checkbox'][1]")).isSelected());
// Assert.assertTrue(driver.findElement(By.xpath("//label[contains(text(),'Insurance')]/preceding::input[@type='checkbox'][1]")).isSelected());
System.out.println("Validated for all the accessorial items checkbox; gets selected when checked by the user. ");
//Test to verify the accessorial check boxes when Unchecked
accessorialDetails.setAccessorials();
Assert.assertFalse(driver.findElement(By.xpath("//label[contains(text(),'Notify Before Delivery')]/preceding::input[@type='checkbox'][1]")).isSelected());
Assert.assertFalse(driver.findElement(By.xpath("//label[contains(text(),'Construction Site Pickup')]/preceding::input[@type='checkbox'][1]")).isSelected());
Assert.assertFalse(driver.findElement(By.xpath("//label[contains(text(),'Construction Site Delivery')]/preceding::input[@type='checkbox'][1]")).isSelected());
Assert.assertFalse(driver.findElement(By.xpath("//label[contains(text(),'Lift Gate Service Pickup')]/preceding::input[@type='checkbox'][1]")).isSelected());
Assert.assertFalse(driver.findElement(By.xpath("//label[contains(text(),'Lift Gate Service Delivery')]/preceding::input[@type='checkbox'][1]")).isSelected());
Assert.assertFalse(driver.findElement(By.xpath("//label[contains(text(),'Limited Access Pickup')]/preceding::input[@type='checkbox'][1]")).isSelected());
Assert.assertFalse(driver.findElement(By.xpath("//label[contains(text(),'Limited Access Delivery')]/preceding::input[@type='checkbox'][1]")).isSelected());
Assert.assertFalse(driver.findElement(By.xpath("//label[contains(text(),'Residential Pickup')]/preceding::input[@type='checkbox'][1]")).isSelected());
Assert.assertFalse(driver.findElement(By.xpath("//label[contains(text(),'Residential Delivery')]/preceding::input[@type='checkbox'][1]")).isSelected());
Assert.assertFalse(driver.findElement(By.xpath("//label[contains(text(),'Hazardous Material')]/preceding::input[@type='checkbox'][1]")).isSelected());
//Assert.assertFalse(driver.findElement(By.xpath("//label[contains(text(),'Insurance')]/preceding::input[@type='checkbox'][1]")).isSelected());
System.out.println("Validated for all the accessorial items checkbox; gets unselected when unchecked by the user.");
}
catch (Exception e) {
System.out.println(e);
Assert.fail();
ExceptionalHandlingFunctions.captureScreenShot(driver, Thread.currentThread().getStackTrace()[1].getMethodName());
ExceptionalHandlingFunctions.writeTOLog(e.getMessage(),Thread.currentThread().getStackTrace()[1].getMethodName());
}
}
@AfterMethod
public void close()
{
driver.close();
}
}
<file_sep>/src/tests/OriginDetailsValidationTests.java
package tests;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import pages.OriginDetails;
import pages.Login;
import utilities.CommonFunctions;
import utilities.ExceptionalHandlingFunctions;
import utilities.PropertyFileUtility;
public class OriginDetailsValidationTests {
WebDriver driver;
Login loginToApplication;
OriginDetails originDetails;
PropertyFileUtility propertyValue = new PropertyFileUtility("./Files/"+"/DataFile.properties");
CommonFunctions utilityfunctions = new CommonFunctions(driver);
String cityNamesList;
String originState;
String originCountry;
@BeforeMethod
public void start()
{
System.setProperty("webdriver.chrome.driver", "./ExternalFiles/"+"/chromedriver.exe");
driver=new ChromeDriver();
driver.manage().window().maximize();
driver.navigate().to(propertyValue.getValue("TestingURL"));
loginToApplication=new Login(driver);
loginToApplication.LoginToApplication(propertyValue.getValue("loginUserName"),propertyValue.getValue("loginPassword"));
}
@Test(priority=1)
public void originZipValidation() throws Exception
{
try {
Thread.sleep(3000);
originDetails=new OriginDetails(driver);
//Test to validate US zipcode having 5 characters and error message to select one city.
originDetails.setOriginZip(propertyValue.getValue("OrizinZip"));
Thread.sleep(2000);
cityNamesList = originDetails.getOriginCity();
originState = originDetails.getOriginState();
originCountry = originDetails.getOriginCountry();
utilityfunctions.validationEquals(cityNamesList, propertyValue.getValue("OriginCityNames"));
utilityfunctions.validationEquals(originState, propertyValue.getValue("OriginState"));
utilityfunctions.validationEquals(originCountry, propertyValue.getValue("OriginCountry"));
System.out.println("Populated cities are: " + cityNamesList);
System.out.println("Populated State is: " + originState);
System.out.println("Populated Country is: " + originCountry);
utilityfunctions.validationEquals("Multiple cities found, please edit to one", originDetails.selectOneCityMessage());
System.out.println("Validated for valid US Zip Code");
originDetails.clearMethodById("originZip");
//Test to validate Alphanumeric Canada Zipcode
originDetails.setOriginZip(propertyValue.getValue("canadaOriginZip"));
Thread.sleep(2000);
String CAcityNamesList = originDetails.getOriginCity();
String CAoriginState = originDetails.getOriginState();
String CAoriginCountry = originDetails.getOriginCountry();
utilityfunctions.validationEquals(CAcityNamesList, propertyValue.getValue("canadaOriginCity"));
utilityfunctions.validationEquals(CAoriginState, propertyValue.getValue("canadaOriginState"));
utilityfunctions.validationEquals(CAoriginCountry, propertyValue.getValue("canadaOriginCountry"));
System.out.println("Populated cities are: " + CAcityNamesList);
System.out.println("Populated State is: " + CAoriginState);
System.out.println("Populated Country is: " + CAoriginCountry);
utilityfunctions.validationEquals("Multiple cities found, please edit to one", originDetails.selectOneCityMessage());
System.out.println("Validated for valid alphanumeric Canadian Zip Code");
//Test to validate Origin Zip by passing 7 digit Zipcode
originDetails.clearMethodById("originZip");
originDetails.setOriginZip(propertyValue.getValue("7digitOriginZip"));
utilityfunctions.validationEquals(originDetails.getOriginZip(), propertyValue.getValue("6digitTrimmedOriginZip"));
System.out.println("Validated for 6 characters in Origin Zip code.");
}catch (Exception e) {
System.out.println(e.getMessage());
Assert.fail();
ExceptionalHandlingFunctions.captureScreenShot(driver, Thread.currentThread().getStackTrace()[1].getMethodName());
ExceptionalHandlingFunctions.writeTOLog(e.getMessage(),Thread.currentThread().getStackTrace()[1].getMethodName());
}
}
@Test(priority=2)
public void originCityValidation() throws Exception
{
try {
originDetails=new OriginDetails(driver);
originDetails.setOriginZip(propertyValue.getValue("OrizinZip"));
cityNamesList = originDetails.getOriginCity();
String selectOneCity=utilityfunctions.splitFunction(cityNamesList, 1);
originDetails.setOriginCity(selectOneCity);
// originDetails.setOriginCity(
// utilityfunctions.splitFunction(cityNamesList, 1) ---or directly can be written in this way
// );
String citySelected = originDetails.getOriginCity();
utilityfunctions.validationEquals(citySelected, selectOneCity);
System.out.println("User is able to edit City field and select one from multiple cities populated: "+citySelected );
//Test to validate multiple
originDetails.clearMethodById("originCity");
originDetails.setOriginCity(propertyValue.getValue("63charCity"));
utilityfunctions.validationEquals(originDetails.getOriginCity(), propertyValue.getValue("Trimmed_60charCity"));
System.out.println("Validated 60 char length on Origin City field");
}
catch (Exception e) {
System.out.println(e.getMessage());
Assert.fail();
ExceptionalHandlingFunctions.captureScreenShot(driver, Thread.currentThread().getStackTrace()[1].getMethodName());
ExceptionalHandlingFunctions.writeTOLog(e.getMessage(),Thread.currentThread().getStackTrace()[1].getMethodName());
}
}
@Test(priority=3)
public void originStateCountryValidation() throws Exception
{
try {
//Test to verify Origin State field is editable
originDetails=new OriginDetails(driver);
originDetails.setOriginZip(propertyValue.getValue("OrizinZip"));
originDetails.setOriginState();
utilityfunctions.validationEquals(originDetails.getOriginState(), propertyValue.getValue("OriginStateNameDropdownIndex1") );
System.out.println("User is able to edit Origin State field :" + propertyValue.getValue("OriginStateNameDropdownIndex1"));
//Test to verify Origin Country field is editable
originDetails.setOriginCountry();
utilityfunctions.validationEquals(originDetails.getOriginCountry(), propertyValue.getValue("OriginCountryNameDropdownByVisibility") );
System.out.println("User is able to edit Origin State field :" + propertyValue.getValue("OriginCountryNameDropdownByVisibility"));
}catch (Exception e) {
System.out.println(e.getMessage());
Assert.fail();
ExceptionalHandlingFunctions.captureScreenShot(driver, Thread.currentThread().getStackTrace()[1].getMethodName());
ExceptionalHandlingFunctions.writeTOLog(e.getMessage(),Thread.currentThread().getStackTrace()[1].getMethodName());
}
}
@Test(priority=4)
public void verifyCurrentDate() throws Exception
{
try {
Thread.sleep(3000);
originDetails=new OriginDetails(driver);
String systemCurrentDate = utilityfunctions.dateFunction();
Thread.sleep(3000);
String applicationPickupDate = originDetails.getPickUpDate();
Assert.assertEquals(applicationPickupDate, systemCurrentDate);
System.out.println("Current Date is autopopulated in PickUp Date field while logging into application.");
}catch (Exception e) {
System.out.println(e.getMessage());
Assert.fail();
ExceptionalHandlingFunctions.captureScreenShot(driver, Thread.currentThread().getStackTrace()[1].getMethodName());
ExceptionalHandlingFunctions.writeTOLog(e.getMessage(),Thread.currentThread().getStackTrace()[1].getMethodName());
}
}
/*
@Test(priority=5)
public void verifyNextDateIsEnabled() throws Exception
{
try {
Thread.sleep(3000);
originDetails=new OriginDetails(driver);
String systemNextDay = utilityfunctions.nextDay();
Thread.sleep(3000);
originDetails.clickPickUpDate();
Thread.sleep(2000);
Assert.assertTrue(driver.findElement(By.xpath("//a[contains(text(),'"+systemNextDay+"')]")).isDisplayed());
driver.findElement(By.xpath("//a[contains(text(),'"+systemNextDay+"')]")).click();
Thread.sleep(2000);
String pickUpNextDate=originDetails.getPickUpDate();
Assert.assertTrue(pickUpNextDate.contains(systemNextDay));
System.out.println("Next Pickup day Date is selected as: " + pickUpNextDate);
}catch (Exception e) {
System.out.println(e.getMessage());
Assert.fail();
ExceptionalHandlingFunctions.captureScreenShot(driver, Thread.currentThread().getStackTrace()[1].getMethodName());
ExceptionalHandlingFunctions.writeTOLog(e.getMessage(),Thread.currentThread().getStackTrace()[1].getMethodName());
}
}
@Test(priority=6)
public void verifyPreviousDateIsDisabled() throws Exception
{
try {
Thread.sleep(3000);
originDetails=new OriginDetails(driver);
String systemPreviousDay = utilityfunctions.previousDay();
String systemCurrentDate = utilityfunctions.dateFunction();
Thread.sleep(3000);
originDetails.clickPickUpDate();
Thread.sleep(2000);
Assert.assertTrue(driver.findElement(By.xpath("//span[contains(text(),'"+systemPreviousDay+"')]")).isDisplayed());
System.out.println("Previous day from system current date: " + systemPreviousDay);
driver.findElement(By.xpath("//span[contains(text(),'"+systemPreviousDay+"')]")).click();
// Assert.assertTrue(driver.findElement(By.xpath("//span[contains(text(),'"+systemPreviousDay+"')]")).isEnabled());---doubt
Thread.sleep(2000);
String pickUpDate=originDetails.getPickUpDate();
Assert.assertEquals(pickUpDate,systemCurrentDate);
System.out.println("Previous dates are disabled.");
}catch (Exception e) {
System.out.println(e.getMessage());
Assert.fail();
ExceptionalHandlingFunctions.captureScreenShot(driver, Thread.currentThread().getStackTrace()[1].getMethodName());
ExceptionalHandlingFunctions.writeTOLog(e.getMessage(),Thread.currentThread().getStackTrace()[1].getMethodName());
}
}*/
@AfterMethod
public void close()
{
driver.close();
}
}<file_sep>/src/tests/TotalWeightPackagingUnitsFunctionalTests.java
package tests;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import pages.ItemDetails;
import pages.Login;
import utilities.CommonFunctions;
import utilities.ExceptionalHandlingFunctions;
import utilities.PropertyFileUtility;
public class TotalWeightPackagingUnitsFunctionalTests {
WebDriver driver;
Login loginToApplication;
ItemDetails itemDetails;
PropertyFileUtility propertyValue = new PropertyFileUtility("./Files/"+"/DataFile.properties");
CommonFunctions utilityfunctions = new CommonFunctions(driver);
@BeforeMethod
public void start()
{
System.setProperty("webdriver.chrome.driver", "./ExternalFiles/"+"/chromedriver.exe");
driver=new ChromeDriver();
driver.manage().window().maximize();
driver.navigate().to(propertyValue.getValue("TestingURL"));
loginToApplication=new Login(driver);
loginToApplication.LoginToApplication(propertyValue.getValue("loginUserName"),propertyValue.getValue("loginPassword"));
}
@Test(priority=1)
public void totalPackagingUnitValidation() throws Exception
{
try {
Thread.sleep(3000);
itemDetails=new ItemDetails(driver);
utilityfunctions.validationEquals("0", itemDetails.getTotalPackagingUnit());
System.out.println("Validated that, while launching the application, initially Total Packaging Units is 0.");
itemDetails.setQuantity1(propertyValue.getValue("quantity1"));
utilityfunctions.validationEquals(propertyValue.getValue("quantity1"), itemDetails.getTotalPackagingUnit());
int item1Quantity= Integer.parseInt(propertyValue.getValue("quantity1"));
itemDetails.clickAdditemBtn();
itemDetails.setQuantity2(propertyValue.getValue("quantity2"));
int item2Quantity=Integer.parseInt(propertyValue.getValue("quantity2"));
int packagingUnit= utilityfunctions.add(item1Quantity, item2Quantity);
String totalPackagingUnit = Integer.toString(packagingUnit);
utilityfunctions.validationEquals(totalPackagingUnit, itemDetails.getTotalPackagingUnit());
itemDetails.clickAdditemBtn();
itemDetails.setQuantity3(propertyValue.getValue("quantity3"));
int item3Quantity=Integer.parseInt(propertyValue.getValue("quantity3"));
packagingUnit = (utilityfunctions.add(packagingUnit, item3Quantity));
totalPackagingUnit = Integer.toString(packagingUnit);
utilityfunctions.validationEquals(totalPackagingUnit, itemDetails.getTotalPackagingUnit());
itemDetails.clickAdditemBtn();
itemDetails.setQuantity4(propertyValue.getValue("quantity4"));
int item4Quantity=Integer.parseInt(propertyValue.getValue("quantity4"));
packagingUnit = (utilityfunctions.add(packagingUnit, item4Quantity));
totalPackagingUnit = Integer.toString(packagingUnit);
utilityfunctions.validationEquals(totalPackagingUnit, itemDetails.getTotalPackagingUnit());
itemDetails.clickAdditemBtn();
itemDetails.setQuantity5(propertyValue.getValue("quantity5"));
int item5Quantity=Integer.parseInt(propertyValue.getValue("quantity5"));
packagingUnit = (utilityfunctions.add(packagingUnit, item5Quantity));
totalPackagingUnit = Integer.toString(packagingUnit);
utilityfunctions.validationEquals(totalPackagingUnit, itemDetails.getTotalPackagingUnit());
System.out.println("Total Packaging Unit: " + itemDetails.getTotalPackagingUnit());
}catch (Exception e) {
System.out.println(e.getMessage());
Assert.fail();
ExceptionalHandlingFunctions.captureScreenShot(driver, Thread.currentThread().getStackTrace()[1].getMethodName());
ExceptionalHandlingFunctions.writeTOLog(e.getMessage(),Thread.currentThread().getStackTrace()[1].getMethodName());
}
}
@Test(priority=2)
public void totalShipmentWeightValidation() throws Exception
{
try {
Thread.sleep(3000);
itemDetails=new ItemDetails(driver);
utilityfunctions.validationEquals("0", itemDetails.getTotalShipmentWeight());
System.out.println("Validated that, while launching the application, initially Total shipment weight is 0.");
itemDetails.setWeight1(propertyValue.getValue("weight1"));
utilityfunctions.validationEquals(propertyValue.getValue("weight1"), itemDetails.getTotalShipmentWeight());
int item1Weight= Integer.parseInt(propertyValue.getValue("weight1"));
itemDetails.clickAdditemBtn();
itemDetails.setWeight2(propertyValue.getValue("weight2"));
int item2Weight=Integer.parseInt(propertyValue.getValue("weight2"));
int shipmentWeight= utilityfunctions.add(item1Weight, item2Weight);
String totalShipmentWeight = Integer.toString(shipmentWeight);
utilityfunctions.validationEquals(totalShipmentWeight, itemDetails.getTotalShipmentWeight());
itemDetails.clickAdditemBtn();
itemDetails.setWeight3(propertyValue.getValue("weight3"));
int item3Weight=Integer.parseInt(propertyValue.getValue("weight3"));
shipmentWeight = (utilityfunctions.add(shipmentWeight, item3Weight));
totalShipmentWeight = Integer.toString(shipmentWeight);
utilityfunctions.validationEquals(totalShipmentWeight, itemDetails.getTotalShipmentWeight());
itemDetails.clickAdditemBtn();
itemDetails.setWeight4(propertyValue.getValue("weight4"));
int item4Weight=Integer.parseInt(propertyValue.getValue("weight4"));
shipmentWeight = (utilityfunctions.add(shipmentWeight, item4Weight));
totalShipmentWeight = Integer.toString(shipmentWeight);
utilityfunctions.validationEquals(totalShipmentWeight, itemDetails.getTotalShipmentWeight());
itemDetails.clickAdditemBtn();
itemDetails.setWeight5(propertyValue.getValue("weight5"));
int item5Weight=Integer.parseInt(propertyValue.getValue("weight5"));
shipmentWeight = (utilityfunctions.add(shipmentWeight, item5Weight));
totalShipmentWeight = Integer.toString(shipmentWeight);
utilityfunctions.validationEquals(totalShipmentWeight, itemDetails.getTotalShipmentWeight());
System.out.println("Total Shipment Weight: " + itemDetails.getTotalShipmentWeight());
}catch (Exception e) {
System.out.println(e.getMessage());
Assert.fail();
ExceptionalHandlingFunctions.captureScreenShot(driver, Thread.currentThread().getStackTrace()[1].getMethodName());
ExceptionalHandlingFunctions.writeTOLog(e.getMessage(),Thread.currentThread().getStackTrace()[1].getMethodName());
}
}
@AfterMethod
public void close()
{
driver.close();
}
}
|
ebd947bfabef94b9d82fa0de4cc92f2e1e707f1f
|
[
"Java"
] | 5
|
Java
|
nutan-priya/SMC3_VolumeProject_Selenium
|
1f4010e34161201a5d10a14fab3b9667fc9ec3ec
|
0f22ba0add243d2bb4bd4ee3ce1eb1b8dc67ea46
|
refs/heads/master
|
<repo_name>Joseph-Visconti/CanadianRecallNotifier<file_sep>/app/src/main/java/com/example/visconti/canadianrecall/RecentRecallsActivity.java
package com.example.visconti.canadianrecall;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
public class RecentRecallsActivity extends ActionBarActivity {
private static final String TAG_JSON_RESULTS = "results";
private static final String TAG_CATEGORY_ALL = "ALL";
private static final String TAG_CATEGORY_FOOD = "FOOD";
private static final String TAG_CATEGORY_VEHICLES = "VEHICLE";
private static final String TAG_CATEGORY_HEALTH = "HEALTH";
private static final String TAG_CATEGORY_CPS = "CPS";
private static final String TAG_RECALL_ID = "recallId";
private static final String TAG_TITLE = "title";
private static final String TAG_CATEGORY_TYPE = "category";
private static final String TAG_DATE_PUBLISHED = "date_published";
private static final String TAG_URL = "url";
private static final String TAG_DEPARTMENT = "department";
private String url = "http://healthycanadians.gc.ca/recall-alert-rappel-avis/api/recent/en";
private String selectedCategory = TAG_CATEGORY_ALL;
private ProgressDialog pDialog;
JSONArray recalls = null;
ArrayList<HashMap<String, String>> recallList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recent_recalls);
ImageButton btnFood = (ImageButton) findViewById(R.id.btnFood);
btnFood.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
setSelected(TAG_CATEGORY_FOOD);
new GetRecallList().execute();
}
});
ImageButton btnVechicle = (ImageButton) findViewById(R.id.btnVechicle);
btnVechicle.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
setSelected(TAG_CATEGORY_VEHICLES);
new GetRecallList().execute();
}
});
ImageButton btnHealth = (ImageButton) findViewById(R.id.btnHealth);
btnHealth.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
setSelected(TAG_CATEGORY_HEALTH);
new GetRecallList().execute();
}
});
ImageButton btnConsumerProducts = (ImageButton) findViewById(R.id.btnConsumerProducts);
btnConsumerProducts.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
setSelected(TAG_CATEGORY_CPS);
new GetRecallList().execute();
}
});
ListView lstRecalls = (ListView)findViewById(R.id.lstRecalls);
lstRecalls.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
String recallID = ((TextView) view.findViewById(R.id.recallID))
.getText().toString();
Intent in = new Intent(getApplicationContext(), RecallDetailsActivity.class);
in.putExtra(TAG_RECALL_ID, recallID);
startActivity(in);
}
});
new GetRecallList().execute();
}
private void setSelected(String selected)
{
ImageButton btnFood = (ImageButton) findViewById(R.id.btnFood);
ImageButton btnVehicle = (ImageButton) findViewById(R.id.btnVechicle);
ImageButton btnHealth = (ImageButton) findViewById(R.id.btnHealth);
ImageButton btnConsumerProducts = (ImageButton) findViewById(R.id.btnConsumerProducts);
if(selected.equals(selectedCategory))
{
selectedCategory = TAG_CATEGORY_ALL;
btnFood.setSelected(false);
btnVehicle.setSelected(false);
btnHealth.setSelected(false);
btnConsumerProducts.setSelected(false);
}
else if(selected.equals(TAG_CATEGORY_FOOD))
{
selectedCategory = selected;
btnFood.setSelected(true);
btnVehicle.setSelected(false);
btnHealth.setSelected(false);
btnConsumerProducts.setSelected(false);
}
else if(selected.equals(TAG_CATEGORY_VEHICLES))
{
selectedCategory = selected;
btnFood.setSelected(false);
btnVehicle.setSelected(true);
btnHealth.setSelected(false);
btnConsumerProducts.setSelected(false);
}
else if(selected.equals(TAG_CATEGORY_HEALTH))
{
selectedCategory = selected;
btnFood.setSelected(false);
btnVehicle.setSelected(false);
btnHealth.setSelected(true);
btnConsumerProducts.setSelected(false);
}
else if(selected.equals(TAG_CATEGORY_CPS))
{
selectedCategory = selected;
btnFood.setSelected(false);
btnVehicle.setSelected(false);
btnHealth.setSelected(false);
btnConsumerProducts.setSelected(true);
}
}
private class GetRecallList extends AsyncTask<Void, Void, Void>
{
@Override
protected void onPreExecute()
{
super.onPreExecute();
pDialog = new ProgressDialog(RecentRecallsActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
recallList = new ArrayList<HashMap<String, String>>();
}
@Override
protected Void doInBackground(Void... arg0)
{
JSONHandler jh = new JSONHandler();
String jsonStr = jh.makeJSONCall(url, JSONHandler.GET);
if (jsonStr != null)
{
try
{
JSONObject jsonObj = new JSONObject(jsonStr);
recalls = jsonObj.getJSONObject(TAG_JSON_RESULTS)
.getJSONArray(selectedCategory);
for (int i = 0; i < recalls.length(); i++)
{
JSONObject r = recalls.getJSONObject(i);
String id = r.getString(TAG_RECALL_ID);
String title = r.getString(TAG_TITLE);
String categoryType = r.getString(TAG_CATEGORY_TYPE);
String recallURL = r.getString(TAG_URL);
String datePublished = r.getString(TAG_DATE_PUBLISHED);
categoryType = categoryType.equals("[\"1\"]") ? "Food"
: categoryType.equals("[\"2\"]") ? "Vehicle"
: categoryType.equals("[\"3\"]") ? "Health"
: categoryType.equals("[\"4\"]") ? "Consumer Products"
: "";
datePublished = new SimpleDateFormat("MMM dd, yyyy").format(new Date(Long.valueOf(datePublished)*1000));
HashMap<String, String> recall = new HashMap<String, String>();
recall.put(TAG_RECALL_ID, id);
recall.put(TAG_TITLE, title);
recall.put(TAG_DEPARTMENT, "");
recall.put(TAG_CATEGORY_TYPE, categoryType);
recall.put(TAG_DATE_PUBLISHED, datePublished);
recall.put(TAG_URL, recallURL);
recallList.add(recall);
}
} catch (JSONException e)
{
e.printStackTrace();
}
} else
{
Log.e("JSONHandler", "Couldn't get any data from the url");
}
return null;
}
@Override
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
ListView lv = (ListView)findViewById(R.id.lstRecalls);
lv.setAdapter(new SimpleAdapter(
RecentRecallsActivity.this,
recallList,
R.layout.list_item_recall,
new String[]{TAG_RECALL_ID, TAG_TITLE, TAG_DATE_PUBLISHED, TAG_CATEGORY_TYPE},
new int[]{R.id.recallID, R.id.title, R.id.datePublished, R.id.category}
));
}
}
}
|
b5f66cf8e6d37299746d624e73e4c6261b71f670
|
[
"Java"
] | 1
|
Java
|
Joseph-Visconti/CanadianRecallNotifier
|
43188daadf7b48c6e37abf66d59f6dfb2c40d5da
|
8512906d32c216e4d3982a201d1ee7864f839f2d
|
refs/heads/master
|
<repo_name>BenHZW/OCUIDemo<file_sep>/人脸识别/Podfile
pod 'OpenCV', '~> 2.4'
end
<file_sep>/HZWHistory/Podfile
platform :ios,'7.0'
pod 'Masonry'
pod 'Mantle','~>1.0'
pod 'AFNetworking','~>2.6.0'
pod 'SDWebImage','~>3.7.2'
pod 'MJRefresh','~>1.4.4'<file_sep>/README.md
# OCUIDemo
There are some UI Demo creating by OC
|
c9b8397f8ffb5dbe329667e53146a731a11fc1bb
|
[
"Markdown",
"Ruby"
] | 3
|
Ruby
|
BenHZW/OCUIDemo
|
5b391ff5bed71bfe16c7aa96d25829e3a5853068
|
ed53e4bfe8bd49f96a7495847d80cc68e602234b
|
refs/heads/master
|
<repo_name>medalLi/crawler<file_sep>/com-crawler-first/src/main/java/com/medal/crawler/httpTest/HttpClientPoolTest.java
package com.medal.crawler.httpTest;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
/**
* @author medal
* @create 2019-10-05 15:34
**/
public class HttpClientPoolTest {
public static void main(String[] args) {
// 创建连接池管理器
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
// 设置最大连接数
cm.setMaxTotal(100);
// 设置每个主机的最大连接数
cm.setDefaultMaxPerRoute(10);
// 使用连接池管理器发起请求
doGet(cm);
}
private static void doGet(PoolingHttpClientConnectionManager cm){
// 不是每次创建新的HttpClient,而是从连接池中获取HttpClient对象
CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build();
// 后面和其它的是一样的
}
}
<file_sep>/com-crawler-first/src/main/java/com/medal/crawler/httpTest/CrawlerFirst.java
package com.medal.crawler.httpTest;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
/**
* @author medal
* @create 2019-10-05 14:45
**/
public class CrawlerFirst {
public static void main(String[] args) throws Exception {
// 1. 打开浏览器,创建一个HttpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
// 2.输入网址
HttpGet httpGet = new HttpGet("http://www.itcast.cn");
RequestConfig config = RequestConfig.custom().setConnectTimeout(1000) //创建连接的最长时间,单位毫秒
.setConnectionRequestTimeout(500) // 设置获取连接的最长时间,单位毫秒
.setSocketTimeout(10 * 1000) // 设置数据传输的最长时间,单位毫秒
.build();
httpGet.setConfig(config);
// 3. 按回车,发起请求,返回响应,使用httpClient对象发起请求
CloseableHttpResponse response = httpClient.execute(httpGet);
// 4.解析数据
if(response.getStatusLine().getStatusCode() == 200){
HttpEntity httpEntity = response.getEntity();
String content = EntityUtils.toString(httpEntity,"utf8");
System.out.println(content);
}
}
}
<file_sep>/com-crawler-first/src/main/java/com/medal/crawler/httpTest/HttpPostParamTest.java
package com.medal.crawler.httpTest;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.util.ArrayList;
import java.util.List;
/**
* @author medal
* @create 2019-10-05 14:45
**/
public class HttpPostParamTest {
public static void main(String[] args) throws Exception {
// 打开浏览器,创建一个HttpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建HttpPost对象,设置Url访问地址
HttpPost httpPost = new HttpPost("http://yun.itheima.com/search");
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("keys","java"));
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(pairs,"utf8");
httpPost.setEntity(formEntity);
// 按回车,发起请求,返回响应,使用httpClient对象发起请求
CloseableHttpResponse response = httpClient.execute(httpPost);
// 解析数据
if(response.getStatusLine().getStatusCode() == 200){
HttpEntity httpEntity = response.getEntity();
String content = EntityUtils.toString(httpEntity,"utf8");
System.out.println(content);
}
}
}
|
39360621451f8998f65f8ac8be1132b371f88547
|
[
"Java"
] | 3
|
Java
|
medalLi/crawler
|
f4b3c8cfa4f5e3b426695689dc71bccffe917526
|
5a3311824d49bbe425bd77c5264ebd7a9083dfd1
|
refs/heads/master
|
<repo_name>jdt/CalBender<file_sep>/Source/src/AppBundle/Repository/IEventRepository.php
<?php
namespace AppBundle\Repository;
use AppBundle\Entity\Value\Date;
interface IEventRepository
{
function selectEvents(Date $from, Date $to);
}<file_sep>/Source/src/AppBundle/Util/ICalendar.php
<?php
namespace AppBundle\Util;
interface ICalendar
{
function monthStart();
function nextMonthStart();
}<file_sep>/Source/src/AppBundle/Controller/IResponseBuilder.php
<?php
namespace AppBundle\Controller;
interface IResponseBuilder
{
public function asJson(array $data);
}<file_sep>/Source/tests/Unit/ResponseBuilderTest.php
<?php
namespace Tests\Unit\Controller;
use AppBundle\Controller\ResponseBuilder;
class ResponseBuilderTest extends \PHPUnit_Framework_TestCase
{
private $builder;
public function setUp()
{
$this->builder = new ResponseBuilder();
}
public function testAsJsonShouldReturnJsonRequest()
{
$data = array("test1" => "value1", "test2" => "value2");
$result = $this->builder->asJson($data);
$this->assertTrue($result->headers->contains("Content-Type", "application/json"));
$this->assertEquals('{"test1":"value1","test2":"value2"}', $result->getContent());
}
}
<file_sep>/Source/README.md
calbender
=========
A Symfony project created on February 29, 2016, 6:58 pm.
<file_sep>/Source/src/AppBundle/Repository/ICalDavServer.php
<?php
namespace AppBundle\Repository;
use \DateTime;
interface ICalDavServer
{
function selectEvents(DateTime $from, DateTime $to);
}<file_sep>/Source/src/AppBundle/Controller/Api/EventController.php
<?php
namespace AppBundle\Controller\Api;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
class EventController
{
public function indexAction(Request $request)
{
return new Response('<html><body>Hello!</body></html>');
}
}
<file_sep>/Build/BuildTestData.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require_once('../Source/vendor/autoload.php');
use Sabre\VObject\Component\VCalendar;
function getClient()
{
$client = new SimpleCalDAVClient();
$client->connect("http://localhost:8008/calendars/users/test/calendar/", "test", "test");
$arrayOfCalendars = $client->findCalendars();
$client->setCalendar($arrayOfCalendars["calendar"]);
return $client;
}
$events = getClient()->getEvents("19000101T000000Z", "20991231T235959Z");
while(count($events) > 0)
{
getClient()->delete($events[0]->getHref(), $events[0]->getEtag());
$events = getClient()->getEvents("19000101T000000Z", "20991231T235959Z");
}
$test1 = new VCalendar([
'VEVENT' => [
'SUMMARY' => 'Test 1',
'DTSTART' => new \DateTime('2016-03-07 10:00:00'),
'DTEND' => new \DateTime('2016-03-07 12:00:00')
]
]);
$test2 = new VCalendar([
'VEVENT' => [
'SUMMARY' => 'Test 2',
'DTSTART' => new \DateTime('2016-03-07 12:00:00'),
'DTEND' => new \DateTime('2016-03-07 14:00:00')
]
]);
$test3 = new VCalendar([
'VEVENT' => [
'SUMMARY' => 'Test 3',
'DTSTART' => new \DateTime('2016-03-07 12:00:00'),
'DTEND' => new \DateTime('2016-03-07 15:00:00')
]
]);
$test4 = new VCalendar([
'VEVENT' => [
'SUMMARY' => 'Test 4',
'DTSTART' => new \DateTime('2016-03-07 16:00:00'),
'DTEND' => new \DateTime('2016-03-07 18:00:00')
]
]);
getClient()->create($test1->serialize());
getClient()->create($test2->serialize());
getClient()->create($test3->serialize());
getClient()->create($test4->serialize());<file_sep>/Source/src/AppBundle/Controller/ResponseBuilder.php
<?php
namespace AppBundle\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
class ResponseBuilder implements IResponseBuilder
{
public function asJson(array $data)
{
$response = new Response(json_encode($data));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
}<file_sep>/README.md
# CalBender
A simple webbased, CalDav-backed calendar application
## Adding modules
Add modules to the Puppet directory with
puppet module install <module name> --target-dir /vagrant/Build/Puppet/dev/modules
### Modules used
example42-apache
willdurand-composer<file_sep>/Source/src/AppBundle/Entity/Value/Date.php
<?php
namespace AppBundle\Entity\Value;
class Date
{
private $year;
private $month;
private $day;
public function __construct($year, $month, $day)
{
$this->year = $year;
$this->month = $month;
$this->day = $day;
}
}
|
8ca86a2b8d755604dfece8d9bc15054af1c1ee56
|
[
"Markdown",
"PHP"
] | 11
|
PHP
|
jdt/CalBender
|
4127eaf6b9973a017556e72584b63341c3e9a454
|
17301e20b523b5fb3169f592e0432fa360ca9a5b
|
refs/heads/master
|
<repo_name>rgrigore/Get_next_line<file_sep>/get_next_line.c
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* get_next_line.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: rgrigore <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2018/01/11 11:07:23 by rgrigore #+# #+# */
/* Updated: 2018/01/11 11:07:25 by rgrigore ### ########.fr */
/* */
/* ************************************************************************** */
#include "get_next_line.h"
#define CONTENT tmp->content
/*
** function for selecting the right element from the list
*/
static t_list *get_file(t_list **list, int fd)
{
t_list *tmp;
tmp = *list;
while (tmp)
{
if ((int)tmp->content_size == fd)
return (tmp);
tmp = tmp->next;
}
tmp = ft_lstnew("\0", fd);
ft_lstadd(list, tmp);
return (*list);
}
/*
** return function that also frees the memory
*/
static int finish(char *tmp, int code)
{
free(tmp);
return (code);
}
/*
** the main function
*/
int get_next_line(int fd, char **line)
{
char *buf;
static t_list *list;
t_list *tmp;
int ct;
if (!(buf = ft_memalloc(BUFF_SIZE + 1)))
return (-1);
if (fd < 0 || !line || read(fd, buf, 0) < 0)
return (finish(buf, -1));
tmp = get_file(&list, fd);
if (!(*line = ft_strnew(1)))
return (finish(buf, -1));
while (!ft_strchr(buf, '\n') && (ct = read(fd, buf, BUFF_SIZE)))
{
buf[ct] = '\0';
if (!(CONTENT = ft_strjoin(CONTENT, buf)))
return (finish(buf, -1));
}
if (ct < BUFF_SIZE && !ft_strlen(CONTENT))
return (finish(buf, 0));
((ct = ft_strchrcpy(line, CONTENT, '\n')) < (int)ft_strlen(CONTENT)) ?
CONTENT += (ct + 1)
: ft_strclr(CONTENT);
return (finish(buf, 1));
}
|
1dbd73a258200105ca270e0d07c9d4abed882594
|
[
"C"
] | 1
|
C
|
rgrigore/Get_next_line
|
a5d812840048ab52fad6c217677f956f30adc09c
|
f2821d6669bcadf69417e08c8b5d70998498f070
|
refs/heads/master
|
<repo_name>MeMartijn/FakeNewsDetection<file_sep>/README.md
# Fake news: approaching automated lie detection using pre-trained word embeddings
In this repository, the following research question is explored: what is the performance of combinations of pre-trained embedding techniques with machine learning algorithms when classifying fake news?
This research will be focussed on applying transfer learning on [earlier research by Wang (2017)](https://arxiv.org/abs/1705.00648). Results of Wang will be used as a benchmark for performance.
## Table of contents
1. [Requirements](#requirements)
2. [Research questions](#rq)
3. [Results](#results)
<a name="requirements"/>
## Requirements
To run the code in the `code` folder, the following packages must be installed:
- `flair`
- `allennlp`
- `tensorflow`
- `tensorflow_hub`
- `pytorch`
- `spacy`
- `hypopt`
- `gensim`
You can install these packages by running `pip install -r /code/requirements.txt`.
<a name="rq"/>
## Research questions
#### Which way of pooling vectors to a fixed length works best for classifying fake news?
#### At what padding sequence length do neural networks hold the highest accuracy when classifying fake news?
#### How well do neural network classification architectures classify fake news compared to non-neural classification algorithms?
<a name="results">
## Results

With a combination of BERT embeddings and a logistic regression, an accuracy of 52.96% on 3 labels can be achieved, which is an increase of almost 4% compared to [previous research in which only traditional linguistic methods were used](https://esc.fnwi.uva.nl/thesis/centraal/files/f1840275767.pdf).
On the original 6 labels, this combination achieves an accuracy of 27.51%, which is 0.51% better than the [original research by Wang (2017)](https://arxiv.org/abs/1705.00648).
<file_sep>/code/data_loader.py
import os
import pandas as pd
import numpy as np
import re
import nltk
from tqdm.auto import tqdm
# Bag of Words imports
from nltk.tokenize import word_tokenize
from nltk.stem.porter import PorterStemmer
import string
from sklearn.feature_extraction.text import CountVectorizer
# InferSent imports
import torch
from models import InferSent
# Flair embedding imports
from flair.data import Sentence
from flair.embeddings import ELMoEmbeddings, BertEmbeddings, TransformerXLEmbeddings, OpenAIGPTEmbeddings, WordEmbeddings, FlairEmbeddings, StackedEmbeddings, XLMEmbeddings, XLNetEmbeddings, OpenAIGPT2Embeddings
import os
from nltk import tokenize
# doc2vec
import gensim
class FlairEncoder:
'''An interface for interacting with Zalando's Flair library'''
def __init__(self, embedding, data_dir, data):
# Prepare tqdm loops
tqdm.pandas()
# Save variables to class
self.embedding = embedding
self.data_dir = data_dir
self.dfs = data
def get_embedded_dataset(self, save = True):
'''Return the embedding representation of the dataset'''
def get_embedding_dir(embedding):
'''Turn the name of the embedding technique into a specific folder'''
if embedding[-1:] == ')':
# The embedding technique is part of a function
return re.search(r'"(.+)"', embedding).group(1)
elif embedding[-10:] == 'Embeddings':
# The embedding technique is part of the Flair library
return embedding.split('Embeddings')[0].lower()
else:
raise ValueError('The requested embedding type is not supported by the data loader.')
def create_embedding(statement, embedding):
'''Create a single embedding from a piece of text'''
try:
# Split all sentences
sentences = tokenize.sent_tokenize(statement)
# Create an array for storing the embeddings
vector = []
# Loop over all sentences and apply embedding
for sentence in sentences:
# Create a Sentence object for each sentence in the statement
sentence = Sentence(sentence, use_tokenizer = True)
# Embed words in sentence
embedding.embed(sentence)
vector.append([token.embedding.numpy() for token in sentence])
return vector
except:
print(statement)
def encode_datasets(embedding_dir, data_dir, dfs, embedding):
'''Return all datasets with embeddings instead of texts'''
# Check whether there already is a file containing the embeddings
if embedding_dir in os.listdir(data_dir):
if embedding_dir == 'flair':
# Flair's training set is divided into two pickle files
return {
dataset: (pd.read_pickle(os.path.join(data_dir, embedding_dir, dataset + '.pkl'))
if dataset != 'train' else
pd.concat([
pd.read_pickle(os.path.join(data_dir, embedding_dir, dataset + '_subset1.pkl')),
pd.read_pickle(os.path.join(data_dir, embedding_dir, dataset + '_subset2.pkl'))
]
))
for dataset in dfs.keys()
}
else:
# Return the previously made embeddings
return {
dataset: pd.read_pickle(os.path.join(
data_dir, embedding_dir, dataset + '.pkl'
)) for dataset in dfs.keys()
}
else:
print('Creating representations and saving them as files...')
# Reformat dataframes to only contain the label and statement
dfs = {
dataset: dfs[dataset][['statement', 'label']]
for dataset in dfs.keys()
}
# Activate embedding
if embedding_dir == 'flair':
# Flair's recommended usage is different from other embedding techniques
embedding = StackedEmbeddings([
WordEmbeddings('glove'),
FlairEmbeddings('news-forward'),
FlairEmbeddings('news-backward'),
])
elif embedding[-1:] == ')':
# This embedding has parameters
embedding = eval(embedding)
else:
embedding = eval(embedding + '()')
# Apply embedding
for dataset in dfs:
# Apply transformation
dfs[dataset]['statement'] = dfs[dataset]['statement'].progress_map(
lambda text: create_embedding(text, embedding)
)
if embedding_dir == 'flair' and dataset == 'train' and save:
# Flair produces files too large: we need to split them before being able to save as files
total_length = len(dfs[dataset])
split = round(total_length / 2)
flair_subset1 = dfs[dataset].iloc[0:split]
flair_subset2 = dfs[dataset].iloc[split:]
# Save both as files
flair_subset1.to_pickle(os.path.join(data_dir, embedding_dir, dataset + '_subset1.pkl'))
flair_subset2.to_pickle(os.path.join(data_dir, embedding_dir, dataset + '_subset2.pkl'))
print('Because of the file size, the training set has been split and saved in two seperate files.')
elif save:
if embedding_dir not in os.listdir(data_dir):
# Create a location to save the datasets as pickle files
os.mkdir(os.path.join(data_dir, embedding_dir))
if dataset == 'train':
# Some tokenizers fail on these two statements
dfs[dataset].loc['3561.json', 'statement'] = create_embedding('Says <NAME> side had a 3-to-1 money advantage in the Wisconsin Supreme Court campaign.', embedding)
dfs[dataset].loc['4675.json', 'statement'] = create_embedding('Since <NAME> OBrien took office Sayreville has issued 22081 building permits! Now OBrien is holding secret meetings with big developers.', embedding)
# Save the dataset as pickle file
file_path = os.path.join(data_dir, embedding_dir, dataset + '.pkl')
dfs[dataset].to_pickle(file_path)
print('Saved ' + dataset + '.pkl at ' + file_path)
return dfs
# Directory name for saving the datasets
embedding_dir = get_embedding_dir(self.embedding)
return encode_datasets(embedding_dir, self.data_dir, self.dfs, self.embedding)
class DataLoader:
'''A class which holds functionality to load and interact with the data from the research article'''
def __init__(self):
# Prepare tqdm loops
tqdm.pandas()
# Location of the data directory
self.data_dir = 'data'
# Paths of the main dataset files
self.data_link = self.get_data_loc()
# Dataframes of the train, test and validation datasets
self.df = self.get_dfs()
# All the statements, used for training models
self.all_statements = pd.concat([self.df[dataset] for dataset in self.df.keys()])['statement']
# Set embedding functions
self.set_embeddings()
def get_data_loc(self):
'''Returns the file path for the data'''
dir_name = 'liar_dataset'
def ensemble_path(file):
'''Short function to ensemble the paths of data files'''
return self.data_dir + '/' + dir_name + '/' + file
if dir_name in os.listdir(self.data_dir):
return {
'train': ensemble_path('/train.tsv'),
'test': ensemble_path('/test.tsv'),
'validation': ensemble_path('/valid.tsv')
}
raise ValueError('Please unpack the ' + dir_name + '.zip file to continue')
def get_dfs(self):
'''Returns a dictionary with pandas dataframes for all data in the data_link dictionary'''
dfs = {
dataset: pd.read_csv(self.data_link[dataset], sep='\t', header=None, index_col=0, names=['id', 'label', 'statement', 'subjects', 'speaker', 'speaker_job', 'state', 'party', 'barely_true_count', 'false_count', 'half_true_count', 'mostly_true_count', 'pants_on_fire_count', 'context'])
for dataset in self.data_link.keys()
}
# Data cleaning as described in the Data Explorations notebook
for dataset in dfs.keys():
dfs[dataset]['mistake_filter'] = dfs[dataset].statement.apply(lambda x: len(re.findall(r'\.json%%(mostly-true|true|half-true|false|barely-true|pants-fire)', re.sub(r'\t', '%%', x))))
dfs[dataset] = dfs[dataset][dfs[dataset]['mistake_filter'] == 0]
dfs[dataset].drop(columns='mistake_filter', inplace = True)
return dfs
def set_embeddings(self):
'''Set all interfaces for embedding techniques using custom functions or Flair encoders'''
def get_bow(save = False):
'''Returns bag of words representation of the dataset'''
# Directory name for saving the datasets
bow_dir = 'bag-of-words'
def tokenize(statement):
'''Tokenize function for CountVectorizer'''
# Tokenize, lowercase
statement = word_tokenize(statement.lower())
# Remove punctuation
table = str.maketrans('', '', string.punctuation)
statement = [word.translate(table) for word in statement]
# Remove empty strings
statement = [word for word in statement if len(word) > 0]
# Apply stemming
porter = PorterStemmer()
statement = [porter.stem(word) for word in statement]
return statement
def create_dataframe(df, vectorizer, features):
'''Create a Bag of Words dataframe from another dataframe'''
# Create a dataframe from the transformed statements
new_df = pd.DataFrame(vectorizer.transform(
df.statement).toarray(), columns=features)
# Add referencing columns
new_df['label'] = list(df.label)
new_df['id'] = list(df.index)
new_df.set_index('id', inplace=True)
return new_df
def init():
'''Initialize all logic from the main function'''
# Check whether there is a file containing the BoW data already present
if bow_dir in os.listdir(self.data_dir):
return {
dataset: pd.read_pickle(os.path.join(
self.data_dir, bow_dir, dataset + '.pkl'))
for dataset in self.df.keys()
}
else:
print('Creating Bag of Words representation and saving them as files...')
os.mkdir(self.data_dir + '/' + bow_dir)
# Create tokenizer
bow = CountVectorizer(
strip_accents='ascii',
analyzer='word',
tokenizer=tokenize,
stop_words='english',
lowercase=True,
)
bow.fit(self.all_statements)
# Get column names
features = bow.get_feature_names()
dfs = {
dataset: create_dataframe(self.df[dataset], bow, features)
for dataset in self.df.keys()
}
# Save the datasets as pickle files
if save:
for dataset in dfs.keys():
dfs[dataset].to_pickle(os.path.join(
self.data_dir, bow_dir, dataset + '.pkl'))
print('Saved the datasets at ' + bow_dir)
return dfs
return init()
def get_infersent(save = False):
'''Returns InferSent representation of the dataset'''
# Directory name for saving the datasets
infersent_dir = 'infersent'
fasttext_dir = 'fast-text'
encoder_dir = 'encoder'
def check_requirements():
'''For training InferSent embeddings, a few data files must be present. This function checks these requirements. Returns either nothing or errors.'''
# Make sure this is up to date
nltk.download('punkt')
if not fasttext_dir in os.listdir(self.data_dir):
print('Please refer to the InferSent installation instructions over here: https://github.com/facebookresearch/InferSent')
raise ValueError('Please download the fasttext vector file from https://dl.fbaipublicfiles.com/fasttext/vectors-english/crawl-300d-2M-subword.zip before continuing, and place the vector file (crawl-300d-2M.vec) in data/fast-text/.')
if not encoder_dir in os.listdir():
print('Please refer to the InferSent installation instructions over here: https://github.com/facebookresearch/InferSent')
raise ValueError(
'Please run the following command and rerun this function: !curl -Lo encoder/infersent2.pickle https://dl.fbaipublicfiles.com/senteval/infersent/infersent2.pkl')
def create_embedding(statement, encoder):
'''Create an InferSent embedding from text'''
sentences = tokenize.sent_tokenize(statement)
return [encoder.encode(sentence, tokenize=True) for sentence in sentences]
def create_dataframe(df, encoder):
'''Create an InferSent dataframe from another dataframe'''
new_df = df[['label', 'statement']]
# Create a dataframe with the transformed statements
new_df['statement'] = new_df['statement'].progress_map(
lambda statement: create_embedding(statement, encoder))
return new_df
def init():
'''Initialize all logic from the main function'''
# Check whether there is a file containing the InferSent data already present
if infersent_dir in os.listdir(self.data_dir):
return {
dataset: pd.read_pickle(os.path.join(
self.data_dir, infersent_dir, dataset + '.pkl'))
for dataset in self.df.keys()
}
else:
print('Creating InferSent representation and saving them as files...')
# Check whether model requirements are met
check_requirements()
# Load pre-trained model
model_version = 2
MODEL_PATH = "encoder/infersent%s.pkl" % model_version
params_model = {'bsize': 64, 'word_emb_dim': 300, 'enc_lstm_dim': 2048,
'pool_type': 'max', 'dpout_model': 0.0, 'version': model_version}
model = InferSent(params_model)
model.load_state_dict(torch.load(MODEL_PATH))
# Keep it on CPU or put it on GPU
use_cuda = False
model = model.cuda() if use_cuda else model
# Set word vectors
W2V_PATH = os.path.join(
self.data_dir, fasttext_dir, 'crawl-300d-2M.vec')
model.set_w2v_path(W2V_PATH)
# Build vocabulary
model.build_vocab(self.all_statements, tokenize=True)
dfs = {
dataset: create_dataframe(self.df[dataset], model)
for dataset in self.df.keys()
}
try:
if save:
# Create a storage directory
os.mkdir(self.data_dir + '/' + infersent_dir)
# Save the datasets as pickle files
for dataset in dfs.keys():
dfs[dataset].to_pickle(os.path.join(
self.data_dir, infersent_dir, dataset + '.pkl'))
print('Saved the datasets at ' + infersent_dir)
return dfs
except:
return dfs
return init()
def get_flair_embedding(embedding, data_dir, dfs):
encoder = FlairEncoder(embedding, self.data_dir, self.df)
return encoder.get_embedded_dataset
def get_doc2vec():
'''Returns doc2vec representation of the dataset'''
# Directory name for saving the datasets
dataset_dir = 'doc2vec'
def create_embeddings(df):
'''Create doc2vec embeddings from dataframe'''
# Create a training corpus
train_corpus = [gensim.models.doc2vec.TaggedDocument(row.statement, [index]) for index, row in df['train'].iterrows()]
# Set model parameters
model = gensim.models.doc2vec.Doc2Vec(vector_size = 4600, min_count = 2, epochs = 40)
# Build the vocabulary
model.build_vocab(train_corpus)
# Train the model
model.train(train_corpus, total_examples = model.corpus_count, epochs = model.epochs)
# Apply model to all statements
embedded_df = df.copy()
for dataset in df:
embedded_df[dataset]['statement'] = df[dataset]['statement'].apply(lambda statement: model.infer_vector(statement))
return embedded_df
def create_dataframe(df):
'''Create an doc2vec dataframe from another dataframe'''
doc2vec = {}
for dataset in self.df.keys():
# Reduce columns
doc2vec[dataset] = self.df[dataset][['label', 'statement']]
# Preprocess statements
doc2vec[dataset]['statement'] = doc2vec[dataset]['statement'].map(lambda statement: gensim.utils.simple_preprocess(statement))
return doc2vec
def save_dataframes(dfs, target_dir):
'''Save dataframes at the specified location'''
# Create a storage directory
os.mkdir(os.path.join(self.data_dir, target_dir))
# Save the datasets as pickle files
for dataset in dfs.keys():
dfs[dataset].to_pickle(os.path.join(
self.data_dir, target_dir, dataset + '.pkl'))
print('Saved the datasets at ' + target_dir)
def init():
'''Initialize all logic from the main function'''
# Check whether there is a file containing the doc2vec data already present
if dataset_dir in os.listdir(self.data_dir):
return {
dataset: pd.read_pickle(os.path.join(
self.data_dir, dataset_dir, dataset + '.pkl'))
for dataset in self.df.keys()
}
else:
print('Creating doc2vec representation and saving them as files...')
# Apply transformations to dataframe
doc2vec = create_dataframe(self.df)
doc2vec = create_embeddings(doc2vec)
# Save the dataframes as pickle files for later use
save_dataframes(doc2vec, dataset_dir)
return doc2vec
return init()
# Attach all function references
self.get_bow = get_bow
self.get_infersent = get_infersent
self.get_bert = get_flair_embedding('BertEmbeddings', self.data_dir, self.df)
self.get_elmo = get_flair_embedding('ELMoEmbeddings', self.data_dir, self.df)
self.get_transformerxl = get_flair_embedding('TransformerXLEmbeddings', self.data_dir, self.df)
self.get_gpt = get_flair_embedding('OpenAIGPTEmbeddings', self.data_dir, self.df)
self.get_flair = get_flair_embedding('FlairEmbeddings', self.data_dir, self.df)
self.get_fasttext = get_flair_embedding('WordEmbeddings("en-crawl")', self.data_dir, self.df)
self.get_doc2vec = get_doc2vec
self.get_gpt2 = get_flair_embedding('OpenAIGPT2Embeddings', self.data_dir, self.df)
self.get_xlm = get_flair_embedding('XLMEmbeddings', self.data_dir, self.df)
self.get_xlnet = get_flair_embedding('XLNetEmbeddings', self.data_dir, self.df)
@staticmethod
def apply_pooling(technique, df):
'''Functionality to apply a pooling technique to a dataframe'''
def pooling(vector):
if technique == 'max':
# Max pooling
if len(vector) > 1:
return [row.max() for row in np.transpose([[token_row.max() for token_row in np.transpose(np.array(sentence))] for sentence in vector])]
else:
return [token_row.max() for token_row in np.transpose(vector[0])]
elif technique == 'min':
# Min pooling
if len(vector) > 1:
return [row.min() for row in np.transpose([[token_row.min() for token_row in np.transpose(np.array(sentence))] for sentence in vector])]
else:
return [token_row.min() for token_row in np.transpose(vector[0])]
elif technique == 'average':
# Average pooling
if len(vector) > 1:
return [np.average(row) for row in np.transpose([[np.average(token_row) for token_row in np.transpose(np.array(sentence))] for sentence in vector])]
else:
return [np.average(token_row) for token_row in np.transpose(vector[0])]
else:
raise ValueError('This pooling technique has not been implemented. Please only use \'min\', \'max\' or \'average\' as keywords.')
def init():
'''Execute all logic'''
print('Applying ' + technique + ' pooling to the dataset...')
return {
dataset: list(
df[dataset].statement.progress_apply(
lambda statement: pooling(statement)
).values
)
for dataset in df.keys()
}
return init()
<file_sep>/code/requirements.txt
flair>=0.4.3
allennlp
tensorflow
tensorflow_hub
torch
torchvision
pytorch_pretrained_bert
spacy
hypopt
keras
gensim<file_sep>/code/classifiers.py
import pandas as pd
import numpy as np
import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout, Embedding, LSTM, Bidirectional, Reshape, Conv1D, Flatten
from keras.utils import np_utils
from sklearn.linear_model import LogisticRegression
from sklearn.svm import LinearSVC
from sklearn.ensemble import GradientBoostingClassifier
from hypopt import GridSearch
class Classifiers:
'''Interface for using pre-defined classifiers'''
@staticmethod
def get_bilstm_score(X_train, X_test, X_validation, y_train, y_test, y_validation, reshape = False):
# Rearrange data types
params = locals().copy()
inputs = {
dataset: np.array(params[dataset])
for dataset in params.keys()
}
# Create mappings
num_classes = len(y_train.unique())
if num_classes == 6:
mapping = {
'true': 0,
'mostly-true': 1,
'half-true': 2,
'barely-true': 3,
'false': 4,
'pants-fire': 5
}
elif num_classes == 3:
mapping = {
'true': 0,
'half-true': 1,
'false': 2
}
else:
mapping = {
'true': 0,
'false': 1
}
for dataset in inputs.keys():
if dataset[0:1] == 'X' and reshape:
# Reshape datasets from 2D to 3D
inputs[dataset] = np.reshape(inputs[dataset], (inputs[dataset].shape[0], inputs[dataset].shape[1], 1))
elif dataset[0:1] == 'y':
inputs[dataset] = np_utils.to_categorical(list(map(lambda label: mapping[label], np.array(inputs[dataset]))), num_classes)
# Set model parameters
epochs = 5
batch_size = 32
input_shape = inputs['X_train'].shape
# Create the model
model = Sequential()
model.add(Bidirectional(LSTM(64, input_shape=input_shape)))
model.add(Dropout(0.8))
model.add(Dense(num_classes, activation='softmax'))
model.compile('sgd', 'categorical_crossentropy', metrics=['accuracy'])
# Fit the training set over the model and correct on the validation set
model.fit(inputs['X_train'], inputs['y_train'],
batch_size=batch_size,
epochs=epochs,
validation_data=(inputs['X_validation'], inputs['y_validation']))
# Get score over the test set
score, acc = model.evaluate(inputs['X_test'], inputs['y_test'])
print(acc)
return acc
@staticmethod
def get_cnn_score(X_train, X_test, X_validation, y_train, y_test, y_validation, reshape = False):
# Rearrange data types
params = locals().copy()
inputs = {
dataset: np.array(params[dataset])
for dataset in params.keys()
}
# Create mappings
num_classes = len(y_train.unique())
if num_classes == 6:
mapping = {
'true': 0,
'mostly-true': 1,
'half-true': 2,
'barely-true': 3,
'false': 4,
'pants-fire': 5
}
elif num_classes == 3:
mapping = {
'true': 0,
'half-true': 1,
'false': 2
}
else:
mapping = {
'true': 0,
'false': 1
}
# Reshape datasets
for dataset in inputs.keys():
if dataset[0:1] == 'X':
if reshape:
inputs[dataset] = np.reshape(inputs[dataset], (inputs[dataset].shape[0], inputs[dataset].shape[1], 1))
elif dataset[0:1] == 'y':
inputs[dataset] = np_utils.to_categorical(list(map(lambda label: mapping[label], np.array(inputs[dataset]))), num_classes)
# Set model parameters
epochs = 5
batch_size = 32
input_shape = inputs['X_train'].shape
# Create the model
model = Sequential()
model.add(Conv1D(128, kernel_size=2, activation='relu', input_shape=(
input_shape[1], input_shape[2]), data_format='channels_first'))
model.add(Conv1D(128, kernel_size=3, activation='relu'))
model.add(Conv1D(128, kernel_size=4, activation='relu'))
model.add(Dropout(0.8))
model.add(Flatten())
model.add(Dense(num_classes, activation='softmax'))
model.compile('sgd', 'categorical_crossentropy', metrics=['accuracy'])
# Fit the training set over the model and correct on the validation set
model.fit(inputs['X_train'], inputs['y_train'],
batch_size=batch_size,
epochs=epochs,
validation_data=(inputs['X_validation'], inputs['y_validation']))
# Get score over the test set
score, acc = model.evaluate(inputs['X_test'], inputs['y_test'])
print(acc)
return acc
@staticmethod
def get_svm_score(X_train, X_test, X_validation, y_train, y_test, y_validation, penalty = 'l2'):
param_grid = {'C': [0.001, 0.01, 0.1, 1, 10]}
gs = GridSearch(model = LinearSVC(penalty = penalty), param_grid = param_grid)
gs.fit(X_train, y_train, X_validation, y_validation)
return gs.score(X_test, y_test)
@staticmethod
def get_logres_score(X_train, X_test, X_validation, y_train, y_test, y_validation, penalty = 'l2'):
param_grid = {'C': [0.001, 0.01, 0.1, 1, 10]}
gs = GridSearch(model = LogisticRegression(penalty = penalty), param_grid = param_grid)
gs.fit(X_train, y_train, X_validation, y_validation)
return gs.score(X_test, y_test)
@staticmethod
def get_gradientboosting_score(X_train, X_test, X_validation, y_train, y_test, y_validation):
param_grid = {'learning_rate': [0.1, 0.05, 0.02, 0.01]}
gs = GridSearch(model = GradientBoostingClassifier(), param_grid = param_grid)
gs.fit(X_train, y_train, X_validation, y_validation)
return gs.score(X_test, y_test)
<file_sep>/code/run_experiments.py
import pandas as pd
import numpy as np
from tqdm.auto import tqdm
from copy import deepcopy
import json
from keras.preprocessing import sequence
from data_loader import DataLoader
from classifiers import Classifiers
import nltk
nltk.download('punkt')
# Create class objects for interaction with data
data = DataLoader()
clfs = Classifiers()
# Load general data
liar = data.get_dfs()
liar = {
fold: liar[fold][['label', 'statement']]
for fold in liar.keys()
}
embedding_techniques = ['elmo', 'gpt', 'flair', 'bert', 'transformerxl']
clf_names = ['bilstm', 'cnn', 'svm', 'logres', 'gradientboosting']
# Create object to save results
results = {
embedding: {
label_count: {
clf: {}
for clf in clf_names
}
for label_count in [6, 3, 2]
}
for embedding in embedding_techniques
}
# Begin classifications
for embedding in tqdm(embedding_techniques):
# Get the proper data
df = eval('data.get_' + embedding + '()')
general = deepcopy(liar)
# Loop through each target variable count
for label_count in [6, 3, 2]:
if label_count == 3:
# Recode labels from 6 to 3
def recode(label):
if label == 'false' or label == 'pants-fire' or label == 'barely-true':
return 'false'
elif label == 'true' or label == 'mostly-true':
return 'true'
elif label == 'half-true':
return 'half-true'
for dataset in general.keys():
general[dataset]['label'] = general[dataset]['label'].apply(lambda label: recode(label))
elif label_count == 2:
# Recode labels from 3 to 2
def recode(label):
if label == 'true' or label == 'half-true':
return 'true'
elif label == 'false':
return 'false'
for dataset in general.keys():
general[dataset]['label'] = general[dataset]['label'].apply(lambda label: recode(label))
# Test whether the amount of labels is correct
assert (len(general['train']['label'].unique()) == label_count), 'The amount of labels is incorrect'
# ------- START NEURAL CLASSIFICATIONS ------- #
padding_variance = list(range(2, 37))
results[embedding][label_count]['bilstm'] = {
max_len: [] for max_len in padding_variance
}
results[embedding][label_count]['cnn'] = {
max_len: [] for max_len in padding_variance
}
# Concatenate dataset
concatenated_df = {
fold: [np.concatenate(np.array(statement)) for statement in df[fold]['statement']]
for fold in df.keys()
}
for max_len in padding_variance:
# Apply padding
padded_df = {
fold: sequence.pad_sequences(concatenated_df[fold], maxlen = max_len, dtype = float)
for fold in concatenated_df.keys()
}
# Get scores for neural classifiers
for neural_net in ['bilstm', 'cnn']:
for i in range(5):
test_score = eval("clfs.get_" + neural_net + "_score(padded_df['train'], padded_df['test'], padded_df['validation'], general['train']['label'], general['test']['label'], general['validation']['label'])")
results[embedding][label_count][neural_net][max_len].append(test_score)
del padded_df
# Clear up memory
del concatenated_df
# Update .json file
with open('results.json', 'w') as fp:
json.dump(results, fp)
# ------- START LINEAR CLASSIFICATIONS ------- #
linear_clfs = ['svm', 'logres', 'gradientboosting']
pooling_techniques = ['max', 'min', 'average']
regularizations = ['l1', 'l2']
for linear_clf in linear_clfs:
if linear_clf == 'gradientboosting':
results[embedding][label_count][linear_clf] = {
technique: 0 for technique in pooling_techniques
}
else:
# There needs to be both a L1 version and a L2 version
results[embedding][label_count][linear_clf] = {
reg: {
technique: 0 for technique in pooling_techniques
} for reg in regularizations
}
for pooling_technique in pooling_techniques:
# Apply pooling
pooled_df = data.apply_pooling(pooling_technique, df)
for linear_clf in linear_clfs:
if linear_clf == 'gradientboosting':
test_score = eval("clfs.get_" + linear_clf + "_score(pooled_df['train'], pooled_df['test'], pooled_df['validation'], general['train']['label'], general['test']['label'], general['validation']['label'])")
results[embedding][label_count][linear_clf][pooling_technique] = test_score
else:
for reg in regularizations:
test_score = eval("clfs.get_" + linear_clf + "_score(pooled_df['train'], pooled_df['test'], pooled_df['validation'], general['train']['label'], general['test']['label'], general['validation']['label'], penalty = '" + reg + "')")
results[embedding][label_count][linear_clf][reg][pooling_technique] = test_score
del pooled_df
# Update .json file
with open('results.json', 'w') as fp:
json.dump(results, fp)
|
7d2622dfa70f5edd4a841e77b9ffd58502668c68
|
[
"Markdown",
"Python",
"Text"
] | 5
|
Markdown
|
MeMartijn/FakeNewsDetection
|
b6891aeae8d18649c15d82b23374566a3efbc882
|
ede5302ef46c9ef472e34a1f52c3749f642ceba5
|
refs/heads/master
|
<file_sep>// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "Hazard.h"
#include "Spike.generated.h"
DECLARE_DELEGATE(FHitSignature)
/**
* 8 x 8 spike.
*/
UCLASS()
class RAGELITE_API ASpike : public AHazard
{
GENERATED_BODY()
public:
ASpike();
FHitSignature OnRlCharacterHit;
private:
UFUNCTION()
void OnHit(UPrimitiveComponent* HitComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, FVector NormalImpulse, const FHitResult& Hit);
};
<file_sep>// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "UObject/NoExportTypes.h"
#include "TimerManager.h"
#include "InputTutorial.generated.h"
class APaperTileMapActor;
class UPaperTileMap;
class ULevelManager;
class ARlCharacter;
class UWorld;
class URlGameInstance;
/**
*
*/
UCLASS()
class RAGELITE_API UInputTutorial : public UObject
{
GENERATED_BODY()
public:
UInputTutorial();
~UInputTutorial();
void Init(APaperTileMapActor* InTileMapActor, TArray<UPaperTileMap*> InTileMaps, URlGameInstance* InRlGameInstance);
virtual UWorld* GetWorld() const override;
void Update(int32 CurrentLevelIndex, bool bIsUsingGamepad);
private:
bool bInit;
APaperTileMapActor* TileMapActor;
TArray<UPaperTileMap*> TileMaps;
void HideLayer(int32 Layer);
void ShowLayer(int32 Layer);
void SetLayerColor(int32 Layer, FLinearColor Color);
void SetLayerVisibility(int32 Layer, bool bVisible);
bool GetLayerVisibility(int32 Layer);
void ToggleLayers(int32 FirstLayer, int32 SecondLayer);
void ShowLayers(int32 KeyboardLayer, int32 GamepadLayer);
void ShowOnlyLayers(int32 KeyboardLayer, int32 GamepadLayer);
UPaperTileMap* LastTileMap;
int32 LastLevel;
bool bWasUsingGamepad;
// Animations
FTimerHandle MainAnimationHandle;
FTimerHandle SecondaryAnimationHandle;
void LevelOneOne();
void LevelOneTwo();
void LevelOneThree();
void LevelOneStairs();
bool bLevelOneRight;
void LevelTwoOne();
void LevelTwoTwo();
void LevelTwoThree();
//void LevelThreeOne();
//void LevelThreeTwo();
void LevelThreeOne();
void LevelThreeTwo();
void LevelThreeThree();
void LevelThreeFour();
void LevelFourOne();
void LevelFourTwo();
private:
URlGameInstance* RlGameInstance;
};
<file_sep>// Fill out your copyright notice in the Description page of Project Settings.
#include "RlSpriteHUD.h"
#include "SpriteTextActor.h"
#include "RlGameInstance.h"
#include "Engine/World.h"
#include "TimerManager.h"
#include "RlGameMode.h"
void ARlSpriteHUD::IncreaseLevel()
{
if (URlGameInstance* RlGI = Cast<URlGameInstance>(GetGameInstance()))
{
if (LevelText)
{
LevelText->SetText(FString::FromInt(++RlGI->Level));
}
}
}
void ARlSpriteHUD::IncreaseScore()
{
if (URlGameInstance* RlGI = Cast<URlGameInstance>(GetGameInstance()))
{
if (ScoreText)
{
ScoreText->SetText(FString::FromInt(++RlGI->Score));
}
}
}
void ARlSpriteHUD::IncreaseTime()
{
if (URlGameInstance* RlGI = Cast<URlGameInstance>(GetGameInstance()))
{
if (TimeText)
{
int32 TempTime = ++RlGI->Time;
const int32 Seconds = TempTime % 60;
TempTime /= 60;
const int32 Minutes = TempTime % 60;
const int32 Hours = TempTime /= 60;
if (Hours)
{
TimeText->SetText(FString::Printf(TEXT("%02d:%02d:%02d"), Hours, Minutes, Seconds));
}
else
{
TimeText->SetText(FString::Printf(TEXT("%02d:%02d"), Minutes, Seconds));
}
}
}
}
void ARlSpriteHUD::IncreaseDeaths()
{
if (URlGameInstance* RlGI = Cast<URlGameInstance>(GetGameInstance()))
{
if (DeathsText)
{
DeathsText->SetText(FString::FromInt(++RlGI->Deaths));
}
}
}
void ARlSpriteHUD::ResetHUD()
{
if (URlGameInstance* RlGI = Cast<URlGameInstance>(GetGameInstance()))
{
RlGI->Level = 1;
RlGI->Score = 0;
RlGI->Time = 0;
RlGI->Deaths = 0;
if (ScoreText && TimeText && DeathsText)
{
LevelText->SetText(FString::FromInt(1));
ScoreText->SetText(FString::FromInt(0));
TimeText->SetText(FString("00:00"));
DeathsText->SetText(FString::FromInt(0));
}
}
}
void ARlSpriteHUD::PostInitializeComponents()
{
Super::PostInitializeComponents();
if (URlGameInstance* RlGI = Cast<URlGameInstance>(GetGameInstance()))
{
RlGI->RlSpriteHUD = this;
}
}
void ARlSpriteHUD::BeginPlay()
{
Super::BeginPlay();
ResetHUD();
GetWorld()->GetTimerManager().ClearTimer(TimeHandle);
GetWorld()->GetTimerManager().SetTimer(TimeHandle, this, &ARlSpriteHUD::TimeTick, 1.f, false);
}
void ARlSpriteHUD::TimeTick()
{
if (ARlGameMode* GameMode = Cast<ARlGameMode>(GetWorld()->GetAuthGameMode()))
{
if (GameMode->bGameStarted)
{
IncreaseTime();
}
}
GetWorld()->GetTimerManager().SetTimer(TimeHandle, this, &ARlSpriteHUD::TimeTick, 1.f, false);
}<file_sep>// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/PlayerController.h"
#include "RlPlayerController.generated.h"
/**
*
*/
UCLASS()
class RAGELITE_API ARlPlayerController : public APlayerController
{
GENERATED_BODY()
protected:
/** Allows the PlayerController to set up custom input bindings. */
virtual void SetupInputComponent() override;
public:
void FadeInBack(float Seconds);
void FadeOutBack(float Seconds);
private:
void Exit();
bool bMouseToggle = false;
public:
virtual bool InputKey(FKey Key, EInputEvent EventType, float AmountDepressed, bool bGamepad) override;
};
<file_sep>// Fill out your copyright notice in the Description page of Project Settings.
#include "WidgetManager.h"
#include "Intro.h"
#include "Kismet/GameplayStatics.h"
#include "RlGameInstance.h"
#include "RlGameMode.h"
#include "AudioManager.h"
#include "Components/AudioComponent.h"
#include "RlCharacter.h"
#include "PaperFlipbookComponent.h"
#include "HearRateModule.h"
#include "DeviceSelection.h"
DEFINE_LOG_CATEGORY_STATIC(LogStatus, Log, All);
void UWidgetManager::Init(URlGameInstance* InRlGI)
{
RlGI = InRlGI;
}
void UWidgetManager::StartIntro()
{
if (IntroClass)
{
Intro = CreateWidget<UIntro>(RlGI->GetWorld(), IntroClass);
Intro->AddToViewport();
Intro->MehStart();
auto PC = UGameplayStatics::GetPlayerController(RlGI->GetWorld(), 0);
PC->SetInputMode(FInputModeGameOnly());
UGameplayStatics::GetPlayerPawn(RlGI->GetWorld(), 0)->DisableInput(PC);
}
}
void UWidgetManager::EndIntro()
{
if (Intro)
{
Intro->RemoveFromParent();
}
auto PC = UGameplayStatics::GetPlayerController(RlGI->GetWorld(), 0);
UGameplayStatics::GetPlayerPawn(RlGI->GetWorld(), 0)->EnableInput(PC);
UE_LOG(LogStatus, Log, TEXT("Game Started"));
if (RlGI->AudioManager)
{
RlGI->AudioManager->SetMusic();
RlGI->AudioManager->Play();
}
}
void UWidgetManager::EndGame()
{
Cast<ARlGameMode>(RlGI->GetWorld()->GetAuthGameMode())->HeartRateModule->bEnabled = false;
if (IntroClass)
{
Intro = CreateWidget<UIntro>(RlGI->GetWorld(), IntroClass);
Intro->AddToViewport();
Intro->MehStart2();
auto PC = UGameplayStatics::GetPlayerController(RlGI->GetWorld(), 0);
PC->SetInputMode(FInputModeGameOnly());
UGameplayStatics::GetPlayerPawn(RlGI->GetWorld(), 0)->DisableInput(PC);
Cast<ARlCharacter>(UGameplayStatics::GetPlayerPawn(RlGI->GetWorld(), 0))->GetSprite()->ToggleVisibility();
UE_LOG(LogStatus, Log, TEXT("Game Ended"));
if (RlGI->AudioManager)
{
RlGI->AudioManager->SetWin();
RlGI->AudioManager->Play();
}
}
}
<file_sep>// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "Paper2D/Classes/PaperSpriteActor.h"
#include "Stairs.generated.h"
class UBoxComponent;
class UPrimitiveComponent;
UCLASS()
class RAGELITE_API AStairs : public APaperSpriteActor
{
GENERATED_BODY()
public:
AStairs();
UBoxComponent* GetTriggerComponent();
bool bCanEnter;
private:
UPROPERTY(Category = Trigger, VisibleAnywhere, meta = (AllowPrivateAccess = "true"))
UBoxComponent* TriggerComponent;
UFUNCTION()
void OnOverlapBegin(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult);
UFUNCTION()
void OnOverlapEnd(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex);
};
<file_sep>// Fill out your copyright notice in the Description page of Project Settings.
#include "Projectile.h"
#include "DefaultMovementComponent.h"
//#include "GameFramework/ProjectileMovementComponent.h"
#include "Paper2D/Classes/PaperSpriteComponent.h"
#include "RlCharacter.h"
#include "TimerManager.h"
#include "Engine/World.h"
AProjectile::AProjectile()
{
MovementComponent = CreateDefaultSubobject<UDefaultMovementComponent>("Movement Component");
//MovementComponent = CreateDefaultSubobject<UProjectileMovementComponent>("Movement Component");
UPaperSpriteComponent* InRenderComponent = GetRenderComponent();
InRenderComponent->SetMobility(EComponentMobility::Movable);
InRenderComponent->SetCollisionProfileName(FName("Projectile"));
InRenderComponent->SetGenerateOverlapEvents(false);
InRenderComponent->OnComponentHit.AddDynamic(this, &AProjectile::OnHit);
InitialSpeed = 100.f;
PrimaryActorTick.bCanEverTick = true;
}
void AProjectile::Tick(float DeltaSeconds)
{
if (GetWorld()->GetTimerManager().IsTimerActive(DestroyHandle))
{
return;
}
const FVector Delta = GetActorUpVector() * InitialSpeed * DeltaSeconds;
FHitResult Hit(1.f);
MovementComponent->SafeMoveUpdatedComponent(Delta, RootComponent->GetComponentQuat(), true, Hit);
//float LastMoveTimeSlice = DeltaSeconds;
//
if (Hit.bBlockingHit)
{
MovementComponent->Velocity = FVector::ZeroVector;
GetRenderComponent()->SetCollisionEnabled(ECollisionEnabled::NoCollision);
GetWorld()->GetTimerManager().SetTimer(DestroyHandle, this, &AProjectile::DestroyWrapper, 1.f, false);
}
//
//if (Hit.bStartPenetrating)
//{
// // Allow this hit to be used as an impact we can deflect off, otherwise we do nothing the rest of the update and appear to hitch.
// SlideAlongSurface(Delta, 1.f, Hit.Normal, Hit, true);
//
// if (Hit.bStartPenetrating)
// {
// OnCharacterStuckInGeometry(&Hit);
// }
//}
}
void AProjectile::OnHit(UPrimitiveComponent* HitComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, FVector NormalImpulse, const FHitResult& Hit)
{
if (ARlCharacter* RlCharacter = Cast<ARlCharacter>(OtherActor))
{
if (!RlCharacter->bDeath && !RlCharacter->bInvincible)
{
RlCharacter->Death();
}
OnRlCharacterHit.ExecuteIfBound();
Destroy();
}
}
void AProjectile::DestroyWrapper()
{
Destroy();
}
<file_sep>// Fill out your copyright notice in the Description page of Project Settings.
#include "RlButton.h"
#include "Components/Button.h"
#include "Components/TextBlock.h"
//#include "Styling/SlateTypes.h"
URlButton::URlButton(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer)
{
auto a = 3;
}
void URlButton::NativeConstruct()
{
Super::NativeConstruct();
//if (IsValid())
//{
// ButtonStyle = Button->WidgetStyle;
// TextBlock->TextDelegate.BindDynamic(this, &URlButton::Meh);
//}
//TextBlock->Text = Text;
////bIsFocusable = true;
}
void URlButton::NativeOnAddedToFocusPath(const FFocusEvent& InFocusEvent)
{
Super::NativeOnAddedToFocusPath(InFocusEvent);
//if (IsValid())
//{
// Button->WidgetStyle.Normal = ButtonStyle.Hovered;
//}
}
void URlButton::NativeOnRemovedFromFocusPath(const FFocusEvent& InFocusEvent)
{
Super::NativeOnRemovedFromFocusPath(InFocusEvent);
//if (IsValid())
//{
// Button->WidgetStyle.Normal = ButtonStyle.Normal;
//}
}
void URlButton::NativeOnMouseEnter(const FGeometry& InGeometry, const FPointerEvent& InMouseEvent)
{
Super::NativeOnMouseEnter(InGeometry, InMouseEvent);
//SetKeyboardFocus();
}
bool URlButton::Initialize()
{
bool da = Super::Initialize();
//auto a = 5;
return da;
}
FText URlButton::Meh()
{
return Text;
}
bool URlButton::IsValid()
{
return false;
//return Button && TextBlock;
}
void URlButton::SetIsEnabled(bool bInIsEnabled)
{
Super::SetIsEnabled(bInIsEnabled);
//if (IsValid())
//{
// Button->SetIsEnabled(bInIsEnabled);
//}
}
#if WITH_EDITOR
void URlButton::PostEditChangeProperty(FPropertyChangedEvent& PropertyChangedEvent)
{
Super::PostEditChangeProperty(PropertyChangedEvent);
//FName PropertyName = (PropertyChangedEvent.MemberProperty != nullptr) ? PropertyChangedEvent.MemberProperty->GetFName() : NAME_None;
//if (PropertyName == GET_MEMBER_NAME_CHECKED(URlButton, Text))
//{
// if (IsValid())
// {
// TextBlock->Text = Text;
// }
//}
}
#endif<file_sep>// Fill out your copyright notice in the Description page of Project Settings.
#include "Intro.h"
#include "Animation/WidgetAnimation.h"
#include "RlGameInstance.h"
#include "WidgetManager.h"
#include "LevelManager.h"
void UIntro::NativeConstruct()
{
}
void UIntro::MehStart()
{
PlayAnimation(Meh);
//GetWorld()->GetTimerManager().SetTimer(MehHandle, this, &UIntro::MehEnd, 1.f);
GetWorld()->GetTimerManager().SetTimer(MehHandle, this, &UIntro::MehEnd, 68.f);
}
void UIntro::MehStart2()
{
PlayAnimation(Meh2);
}
void UIntro::MehEnd()
{
UWidgetManager* WM = Cast<URlGameInstance>(GetGameInstance())->WidgetManager;
WM->EndIntro();
ULevelManager* LM = Cast<URlGameInstance>(GetGameInstance())->LevelManager;
LM->SetLevel(ELevelState::Start);
}
<file_sep>// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "Engine/GameInstance.h"
#include "RlGameInstance.generated.h"
DECLARE_DELEGATE(FShutdownSignature)
class ULevelManager;
class UWidgetManager;
class AAudioManager;
class ASpriteTextActor;
class ARlSpriteHUD;
/**
*
*/
UCLASS(Blueprintable)
class RAGELITE_API URlGameInstance : public UGameInstance
{
GENERATED_BODY()
URlGameInstance(const FObjectInitializer& ObjectInitializer);
public:
virtual void Init() override;
virtual void Shutdown() override;
FShutdownSignature OnShutdown;
// HUD variables
int32 Level;
int32 Score;
int32 Time;
int32 Deaths;
ARlSpriteHUD* RlSpriteHUD;
bool bUseDevice;
bool bDynamicDifficulty;
bool bIntro;
public:
ULevelManager* LevelManager;
UWidgetManager* WidgetManager;
UPROPERTY()
AAudioManager* AudioManager;
private:
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Levels", meta = (AllowPrivateAccess = "true"))
TSubclassOf<ULevelManager> LevelManagerPtr;
UPROPERTY(EditDefaultsOnly, Category = "Widgets", meta = (AllowPrivateAccess = "true"))
TSubclassOf<UWidgetManager> WidgetManagerClass;
public:
UPROPERTY(EditDefaultsOnly, Category = "Audio", meta = (AllowPrivateAccess = "true"))
TSubclassOf<AAudioManager> AudioManagerClass;
};
<file_sep>// Fill out your copyright notice in the Description page of Project Settings.
#include "FocusButton.h"
#include "SFocusButton.h"
#include "Components/ButtonSlot.h"
UFocusButton::UFocusButton(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer)
{
OnClicked.AddDynamic(this, &UFocusButton::OnClick);
OnHovered.AddDynamic(this, &UFocusButton::SetFocus);
//OnUnhovered.AddDynamic(this, &UFocusButton::OnUnfocused);
ButtonStyle = WidgetStyle;
}
void UFocusButton::OnClick()
{
OnClickDelegate.Broadcast(this);
}
TSharedRef<SWidget> UFocusButton::RebuildWidget()
{
MyButton = SNew(SFocusButton)
.OnClicked(BIND_UOBJECT_DELEGATE(FOnClicked, SlateHandleClicked))
.OnPressed(BIND_UOBJECT_DELEGATE(FSimpleDelegate, SlateHandlePressed))
.OnReleased(BIND_UOBJECT_DELEGATE(FSimpleDelegate, SlateHandleReleased))
.OnHovered_UObject(this, &ThisClass::SlateHandleHovered)
.OnUnhovered_UObject(this, &ThisClass::SlateHandleUnhovered)
.ButtonStyle(&WidgetStyle)
.ClickMethod(ClickMethod)
.TouchMethod(TouchMethod)
.PressMethod(PressMethod)
.IsFocusable(IsFocusable)
;
if (GetChildrenCount() > 0)
{
Cast<UButtonSlot>(GetContentSlot())->BuildSlot(MyButton.ToSharedRef());
}
SFocusButton* FocusButton = static_cast<SFocusButton*>(MyButton.Get());
FocusButton->OnFocused.BindUObject(this, &UFocusButton::OnFocused);
FocusButton->OnUnfocused.BindUObject(this, &UFocusButton::OnUnfocused);
return MyButton.ToSharedRef();
}
//void UFocusButton::NativeConstruct()
//{
// Super::NativeConstruct();
//
// ButtonStyle = WidgetStyle;
//}
void UFocusButton::Test()
{
auto a = 5;
}
void UFocusButton::OnFocused()
{
WidgetStyle.Normal = ButtonStyle.Hovered;
// TODO: Remove focus to other focus buttons
}
void UFocusButton::OnUnfocused()
{
WidgetStyle.Normal = ButtonStyle.Normal;
}
void UFocusButton::SetFocus()
{
SetKeyboardFocus();
}
<file_sep>// Fill out your copyright notice in the Description page of Project Settings.
#include "Spike.h"
#include "RlCharacter.h"
#include "Components/BoxComponent.h"
#include "Paper2D/Classes/PaperSpriteComponent.h"
ASpike::ASpike()
{
UPaperSpriteComponent* InRenderComponent = GetRenderComponent();
InRenderComponent->SetCollisionProfileName(FName("BlockAllDynamic"));
InRenderComponent->OnComponentHit.AddDynamic(this, &ASpike::OnHit);
}
void ASpike::OnHit(UPrimitiveComponent* HitComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, FVector NormalImpulse, const FHitResult& Hit)
{
if (ARlCharacter* RlCharacter = Cast<ARlCharacter>(OtherActor))
{
if (!RlCharacter->bDeath && !RlCharacter->bInvincible)
{
RlCharacter->Death();
}
OnRlCharacterHit.ExecuteIfBound();
}
}<file_sep>// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "RLTypes.h"
#include "HazardPool.generated.h"
class AHazard;
class ASpike;
class ADart;
class AStone;
UCLASS()
class RAGELITE_API AHazardPool : public AActor
{
GENERATED_BODY()
public:
AHazardPool();
UPROPERTY(EditAnywhere, Category = Spikes)
int32 InitialSpikes;
TArray<ASpike*> Spikes;
UPROPERTY(EditAnywhere, Category = Darts)
int32 InitialDarts;
TArray<ADart*> Darts;
UPROPERTY(EditAnywhere, Category = Darts)
int32 InitialStones;
TArray<AStone*> Stones;
public:
void AddSpikes(int32 SpikesNum);
void AddSpikesUntil(int32 SpikesNum);
void AddDarts(int32 DartsNum);
void AddDartsUntil(int32 DartsNum);
void AddStones(int32 StonesNum);
void AddStonesUntil(int32 StonesNum);
void ResetHazards(TArray<FHazardsData> HazardsData);
virtual void PostInitializeComponents() override;
virtual void EndPlay(const EEndPlayReason::Type EndPlayReason) override;
};
<file_sep>// Fill out your copyright notice in the Description page of Project Settings.
#include "SpriteTextActor.h"
#include "ConstructorHelpers.h"
#include "PaperSpriteComponent.h"
#include "PaperSprite.h"
#include "Materials/Material.h"
#include "Kismet/KismetSystemLibrary.h"
ASpriteTextActor::ASpriteTextActor(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
{
SceneComponent = CreateDefaultSubobject<USceneComponent>(TEXT("SceneComponent"));
RootComponent = SceneComponent;
STSceneComponent = CreateDefaultSubobject<USceneComponent>(TEXT("TextSceneComponent"));
STSceneComponent->SetupAttachment(RootComponent);
static ConstructorHelpers::FObjectFinder<UMaterialInterface> MaterialRef(TEXT("/Paper2D/MaskedUnlitSpriteMaterial"));
if (MaterialRef.Object)
{
Material = MaterialRef.Object;
}
Text = FString::FromInt(0);
TileWidth = 8;
TileHeight = 16;
TextLenght = 1;
//for (TCHAR i = 48; i < 91; ++i)
//{
// CharacterMap.Add(FString(1, &i), nullptr);
//}
}
void ASpriteTextActor::SetText(FString InText)
{
Text = InText;
UpdateHorizontal();
UpdateSprites();
UpdateAlignment();
}
void ASpriteTextActor::UpdateMaterial()
{
for (UPaperSpriteComponent* PaperSpriteComponent : SpriteTextComponents)
{
PaperSpriteComponent->SetMaterial(0, Material);
}
}
void ASpriteTextActor::UpdateSprites()
{
for (int i = 0; i < SpriteTextComponents.Num(); ++i)
{
UPaperSpriteComponent* PaperSpriteComponent = SpriteTextComponents[i];
FString Key = FString::Chr(Text[i]);
PaperSpriteComponent->SetSprite(CharacterMap.Contains(Key) ? CharacterMap[Key] : nullptr);
}
}
void ASpriteTextActor::UpdateLocationHorizontal()
{
for (int i = 0; i < SpriteTextComponents.Num(); ++i)
{
SpriteTextComponents[i]->SetRelativeLocation(FVector(TileWidth * i, 0.f, 0.f));
}
}
void ASpriteTextActor::UpdateHorizontal()
{
while (SpriteTextComponents.Num() < Text.Len())
{
UPaperSpriteComponent* PaperSpriteComponent = NewObject<UPaperSpriteComponent>(this);
PaperSpriteComponent->SetMaterial(0, Material);
FString Key = FString::Chr(Text[SpriteTextComponents.Num()]);
if (CharacterMap.Contains(Key) && CharacterMap[Key])
{
PaperSpriteComponent->SetSprite(CharacterMap[Key]);
}
PaperSpriteComponent->SetRelativeLocation(FVector(TileWidth * SpriteTextComponents.Num(), 0.f, 0.f));
PaperSpriteComponent->SetupAttachment(STSceneComponent);
PaperSpriteComponent->RegisterComponent();
SpriteTextComponents.Add(PaperSpriteComponent);
}
while (SpriteTextComponents.Num() > Text.Len())
{
UPaperSpriteComponent* PaperSpriteComponent = SpriteTextComponents.Pop();
PaperSpriteComponent->DestroyComponent();
}
TextLenght = Text.Len();
UpdateLocationHorizontal();
}
void ASpriteTextActor::UpdateAlignment()
{
FVector Location(0.f);
switch (HorizontalAlignment)
{
default:
case EHorizontalSpriteTextAligment::Left:
break;
case EHorizontalSpriteTextAligment::Center:
Location.X -= (TileWidth * TextLenght + 1) / 2;
break;
case EHorizontalSpriteTextAligment::Right:
Location.X -= TileWidth * TextLenght;
break;
}
switch (VerticalAlignment)
{
default:
case EVerticalSpriteTextAligment::Top:
break;
case EVerticalSpriteTextAligment::Center:
Location.Z += (TileHeight + 1) / 2;
break;
case EVerticalSpriteTextAligment::Bottom:
Location.Z += TileHeight;
break;
}
STSceneComponent->SetRelativeLocation(Location);
}
void ASpriteTextActor::PostLoad()
{
Super::PostLoad();
UpdateHorizontal();
UpdateMaterial();
UpdateSprites();
UpdateLocationHorizontal();
UpdateAlignment();
}
#if WITH_EDITOR
void ASpriteTextActor::PostEditChangeProperty(FPropertyChangedEvent& PropertyChangedEvent)
{
Super::PostEditChangeProperty(PropertyChangedEvent);
FName PropertyName = (PropertyChangedEvent.MemberProperty != nullptr) ? PropertyChangedEvent.MemberProperty->GetFName() : NAME_None;
if (PropertyName == GET_MEMBER_NAME_CHECKED(ASpriteTextActor, Text))
{
UpdateHorizontal();
UpdateSprites();
UpdateAlignment();
}
if (PropertyName == GET_MEMBER_NAME_CHECKED(ASpriteTextActor, Material))
{
UpdateMaterial();
}
if (PropertyName == GET_MEMBER_NAME_CHECKED(ASpriteTextActor, TileWidth)
|| PropertyName == GET_MEMBER_NAME_CHECKED(ASpriteTextActor, TileHeight))
{
UpdateLocationHorizontal();
UpdateAlignment();
}
if (PropertyName == GET_MEMBER_NAME_CHECKED(ASpriteTextActor, CharacterMap))
{
UpdateSprites();
UpdateLocationHorizontal();
}
if (PropertyName == GET_MEMBER_NAME_CHECKED(ASpriteTextActor, HorizontalAlignment)
|| PropertyName == GET_MEMBER_NAME_CHECKED(ASpriteTextActor, VerticalAlignment))
{
UpdateAlignment();
}
}
#endif<file_sep>// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "UObject/NoExportTypes.h"
#include "HearRateModule.generated.h"
class ARlGameMode;
/**
*
*/
UCLASS()
class RAGELITE_API UHearRateModule : public UObject
{
GENERATED_BODY()
public:
UHearRateModule();
TArray<uint8> HeartRates;
// Estimation of heart rate peaks
float ScopePercentage;
// Used to adjust Min and Max
float DeadZoneFactor;
float HeartRateMin;
float HeartRateMax;
float HeartRateMedian;
//uint64 HeartRateSum;
void AddHeartRate(uint8 HearRate);
void AddHeartRate(FString HearRate);
void StartCalibration();
void EndCalibration();
bool bCalibration;
// For debug
UPROPERTY()
ARlGameMode* GameMode;
//private:
bool bEnabled;
};
<file_sep>// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Pawn.h"
#include "RlCharacterMovementComponent.h"
#include "TimerManager.h"
#include "RlCharacter.generated.h"
class UPaperFlipbookComponent;
class URlCharacterMovementComponent;
class UBoxComponent;
class UArrowComponent;
class FDebugDisplayInfo;
class UPaperFlipbook;
class UParticleSystem;
class UParticleSystemComponent;
class FSocket;
DECLARE_DYNAMIC_MULTICAST_DELEGATE(FRlCharacterReachedApexSignature);
DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FRlLandedSignature, const FHitResult&, Hit);
//DECLARE_LOG_CATEGORY_EXTERN(LogHeartRate, Log, All);
//DECLARE_LOG_CATEGORY_EXTERN(LogDevice, Log, All);
enum class ERlAnimationState : int8
{
Idle,
ToIdle,
ToIdleR,
Running,
ToJumping,
Jumping,
ToFalling,
Falling,
Landing
};
struct FRlTransition
{
bool(*Predicate)(ARlCharacter*); // Give this as an argument.
ERlAnimationState NextState;
FRlTransition() {};
FRlTransition(bool(*InPredicate)(ARlCharacter*), ERlAnimationState InNextState)
{
Predicate = InPredicate;
NextState = InNextState;
}
};
struct FRlAnimation
{
//UPaperFlipbook* Animation;
UPaperFlipbook* (*Animation)(ARlCharacter*); // Give this as an argument.
//float AnimationSpeed; // maybe convert to a lambda?
bool bLoop;
bool bReverse;
int Start; // -1 to play from start
int End; // -1 to play from end
bool bKeepFrame; // True to play from current frame
TArray<FRlTransition> Transitions; // First transitions have priority
FRlAnimation() {};
FRlAnimation(UPaperFlipbook* (*InAnimation)(ARlCharacter*), bool bInLoop, bool bInReverse, bool bInKeepFrame = false, int InStart = -1, int InEnd = -1)
{
Animation = InAnimation;
bLoop = bInLoop;
bReverse = bInReverse;
Start = InStart;
End = InEnd;
bKeepFrame = bInKeepFrame;
}
};
/** RlMovementBaseUtility provides utilities for working with movement bases, for which we may need relative positioning info. */
namespace RlMovementBaseUtility
{
/** Determine whether MovementBase can possibly move. */
RAGELITE_API bool IsDynamicBase(const UPrimitiveComponent* MovementBase);
/** Determine if we should use relative positioning when based on a component (because it may move). */
FORCEINLINE bool UseRelativeLocation(const UPrimitiveComponent* MovementBase)
{
return IsDynamicBase(MovementBase);
}
/** Ensure that BasedObjectTick ticks after NewBase */
RAGELITE_API void AddTickDependency(FTickFunction& BasedObjectTick, UPrimitiveComponent* NewBase);
/** Remove tick dependency of BasedObjectTick on OldBase */
RAGELITE_API void RemoveTickDependency(FTickFunction& BasedObjectTick, UPrimitiveComponent* OldBase);
/** Get the velocity of the given component, first checking the ComponentVelocity and falling back to the physics velocity if necessary. */
RAGELITE_API FVector GetMovementBaseVelocity(const UPrimitiveComponent* MovementBase, const FName BoneName);
/** Get the tangential velocity at WorldLocation for the given component. */
RAGELITE_API FVector GetMovementBaseTangentialVelocity(const UPrimitiveComponent* MovementBase, const FName BoneName, const FVector& WorldLocation);
/** Get the transforms for the given MovementBase, optionally at the location of a bone. Returns false if MovementBase is nullptr, or if BoneName is not a valid bone. */
RAGELITE_API bool GetMovementBaseTransform(const UPrimitiveComponent* MovementBase, const FName BoneName, FVector& OutLocation, FQuat& OutQuat);
}
/** Struct to hold information about the "base" object the character is standing on. */
USTRUCT()
struct FRlBasedMovementInfo
{
GENERATED_USTRUCT_BODY()
/** Component we are based on */
UPROPERTY()
UPrimitiveComponent* MovementBase;
/** Bone name on component, for skeletal meshes. NAME_None if not a skeletal mesh or if bone is invalid. */
UPROPERTY()
FName BoneName;
/** Location relative to MovementBase. Only valid if HasRelativeLocation() is true. */
UPROPERTY()
FVector_NetQuantize100 Location;
/** Rotation: relative to MovementBase if HasRelativeRotation() is true, absolute otherwise. */
UPROPERTY()
FRotator Rotation;
/** Whether the server says that there is a base. On clients, the component may not have resolved yet. */
UPROPERTY()
bool bServerHasBaseComponent;
/** Whether rotation is relative to the base or absolute. It can only be relative if location is also relative. */
UPROPERTY()
bool bRelativeRotation;
/** Whether there is a velocity on the server. Used for forcing replication when velocity goes to zero. */
UPROPERTY()
bool bServerHasVelocity;
/** Is location relative? */
FORCEINLINE bool HasRelativeLocation() const
{
return RlMovementBaseUtility::UseRelativeLocation(MovementBase);
}
/** Is rotation relative or absolute? It can only be relative if location is also relative. */
FORCEINLINE bool HasRelativeRotation() const
{
return bRelativeRotation && HasRelativeLocation();
}
/** Return true if the client should have MovementBase, but it hasn't replicated (possibly component has not streamed in). */
FORCEINLINE bool IsBaseUnresolved() const
{
return (MovementBase == nullptr) && bServerHasBaseComponent;
}
};
/**
*
*/
//UCLASS()
UCLASS(config=Game, BlueprintType, meta=(ShortTooltip="A character is a type of Pawn that includes the ability to walk around."))
class RAGELITE_API ARlCharacter : public APawn
{
GENERATED_BODY()
public:
/** Default UObject constructor. */
ARlCharacter(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get());
private:
/** The main skeletal mesh associated with this Character (optional sub-object). */
UPROPERTY(Category = Character, VisibleAnywhere, meta = (AllowPrivateAccess = "true"))
UPaperFlipbookComponent* Sprite;
public:
/** Movement component used for movement logic in various movement modes (walking, falling, etc), containing relevant settings and functions to control movement. */
UPROPERTY(Category = Character, VisibleAnywhere, meta = (AllowPrivateAccess = "true"))
URlCharacterMovementComponent* RlCharacterMovement;
///** Movement component used for movement logic in various movement modes (walking, falling, etc), containing relevant settings and functions to control movement. */
//UPROPERTY(Category = Character, VisibleAnywhere, BlueprintReadOnly, meta = (AllowPrivateAccess = "true"))
//URlCharacterMovementComponent* CharacterMovement;
/** The CapsuleComponent being used for movement collision (by CharacterMovement). Always treated as being vertically aligned in simple collision check functions. */
UPROPERTY(Category = Character, VisibleAnywhere, meta = (AllowPrivateAccess = "true"))
UBoxComponent* BoxComponent;
UPROPERTY(Category = Character, VisibleAnywhere, meta = (AllowPrivateAccess = "true"))
UParticleSystemComponent* DustComponent;
#if WITH_EDITORONLY_DATA
/** Component shown in the editor only to indicate character facing */
UPROPERTY()
UArrowComponent* ArrowComponent;
#endif
public:
/** Returns Mesh subobject **/
FORCEINLINE UPaperFlipbookComponent* GetSprite() const { return Sprite; }
/** Name of the SpriteComponent. Use this name if you want to prevent creation of the component (with ObjectInitializer.DoNotCreateDefaultSubobject). */
static FName SpriteComponentName;
/** Returns RlCharacterMovement subobject **/
FORCEINLINE URlCharacterMovementComponent* GetRlCharacterMovement() const { return RlCharacterMovement; }
/** Name of the CharacterMovement component. Use this name if you want to use a different class (with ObjectInitializer.SetDefaultSubobjectClass). */
static FName RlCharacterMovementComponentName;
/** Returns BoxComponent subobject **/
FORCEINLINE UBoxComponent* GetBoxComponent() const { return BoxComponent; }
/** Name of the CapsuleComponent. */
static FName BoxComponentName;
#if WITH_EDITORONLY_DATA
/** Returns ArrowComponent subobject **/
class UArrowComponent* GetArrowComponent() const { return ArrowComponent; }
#endif
protected:
// The animation to play while running around
UPROPERTY(EditAnywhere, Category = Animations)
UPaperFlipbook* RunningRightAnimation;
// The animation to play while idle (standing still)
UPROPERTY(EditAnywhere, Category = Animations)
UPaperFlipbook* ToIdleRightAnimation;
// The animation to play while idle (standing still)
UPROPERTY(EditAnywhere, Category = Animations)
UPaperFlipbook* IdleRightAnimation;
// The animation to play while idle (standing still)
UPROPERTY(EditAnywhere, Category = Animations)
UPaperFlipbook* IdleRightAnimationExtras;
// The animation to play while idle (standing still)
UPROPERTY(EditAnywhere, Category = Animations)
UPaperFlipbook* JumpRightAnimation;
UPROPERTY(EditAnywhere, Category = Animations)
UPaperFlipbook* WallWalkRightAnimation;
UPROPERTY(EditAnywhere, Category = Animations)
UPaperFlipbook* RunningLeftAnimation;
// The animation to play while idle (standing still)
UPROPERTY(EditAnywhere, Category = Animations)
UPaperFlipbook* ToIdleLeftAnimation;
// The animation to play while idle (standing still)
UPROPERTY(EditAnywhere, Category = Animations)
UPaperFlipbook* IdleLeftAnimation;
// The animation to play while idle (standing still)
UPROPERTY(EditAnywhere, Category = Animations)
UPaperFlipbook* IdleLeftAnimationExtras;
// The animation to play while idle (standing still)
UPROPERTY(EditAnywhere, Category = Animations)
UPaperFlipbook* JumpLeftAnimation;
UPROPERTY(EditAnywhere, Category = Animations)
UPaperFlipbook* WallWalkLeftAnimation;
// The animation to play while idle (standing still)
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = Animations)
UParticleSystem* DeathAnimation;
UParticleSystem* DustRight;
UParticleSystem* DustLeft;
/** Called for side to side input */
void MoveRight(float Value);
/** Called to choose the correct animation to play based on the character's movement state */
void UpdateAnimation();
void Up();
///** Handle touch inputs. */
//void TouchStarted(const ETouchIndex::Type FingerIndex, const FVector Location);
///** Handle touch stop event. */
//void TouchStopped(const ETouchIndex::Type FingerIndex, const FVector Location);
/** Called for side to side input */
void Level();
FTimerHandle IgnoreTimerHandle;
FTimerHandle DeathHandle;
void Skip();
void Reset();
void DifficultyDebug(float Value);
void DifficultyAddDebug(float Value);
bool bCanDA = false;
private:
ERlAnimationState CurrentState;
void SetCurrentState(ERlAnimationState State);
//UPROPERTY()
TMap<ERlAnimationState, FRlAnimation> AnimationLibrary;
int GetFlipbookLengthInFrames(UPaperFlipbook* (*Animation)(ARlCharacter*));
float NextAnimationPostion();
bool AboveFrame(int32 Frame);
bool BelowFrame(int32 Frame);
public:
bool bDeath;
bool bInvincible;
void Death();
bool bDust;
// Animation
bool bIsLastDirectionRight;
float WalkSpeed;
float CurrentDeltaTime;
bool bIsChangingDirection;
float PreviousVelocityX;
bool bIsReversing;
bool bIsUsingGamepad;
void Vibrate();
void Vibrate(uint16 Milliseconds);
void WriteMessage(uint8* Message, uint32 MessageSize);
void HearRate(bool bStart);
void AdvertisementWatcher(bool bStart);
void Connect(FString Device);
bool bDeviceConnected;
class FTcpListener* TcpListener;
FSocket* ConnectionSocket;
bool OnConnection(FSocket* Socket, const struct FIPv4Endpoint& IPv4Endpoint);
bool bConnectionAccepted;
void CheckServer();
FTimerHandle DeviceConnectionHandle;
void CloseConnection();
// For Test Only
UPROPERTY(EditAnywhere)
float Difficulty;
#if WITH_EDITOR
virtual void PostEditChangeProperty(FPropertyChangedEvent& PropertyChangedEvent) override;
#endif
public:
// Called every frame
virtual void Tick(float DeltaTime) override;
/** Sets the component the Character is walking on, used by CharacterMovement walking movement to be able to follow dynamic objects. */
virtual void SetBase(UPrimitiveComponent* NewBase, const FName BoneName = NAME_None, bool bNotifyActor=true);
protected:
/** Info about our current movement base (object we are standing on). */
UPROPERTY()
struct FRlBasedMovementInfo BasedMovement;
protected:
/** Saved translation offset of mesh. */
UPROPERTY()
FVector BaseTranslationOffset;
/** Saved rotation offset of mesh. */
UPROPERTY()
FQuat BaseRotationOffset;
/** Event called after actor's base changes (if SetBase was requested to notify us with bNotifyPawn). */
virtual void BaseChange();
public:
/** Accessor for BasedMovement */
FORCEINLINE const FRlBasedMovementInfo& GetBasedMovement() const { return BasedMovement; }
/** Save a new relative location in BasedMovement and a new rotation with is either relative or absolute. */
void SaveRelativeBasedMovement(const FVector& NewRelativeLocation, const FRotator& NewRotation, bool bRelativeRotation);
/** Get the saved translation offset of mesh. This is how much extra offset is applied from the center of the capsule. */
UFUNCTION(BlueprintCallable, Category=Character)
FVector GetBaseTranslationOffset() const { return BaseTranslationOffset; }
/** Get the saved rotation offset of mesh. This is how much extra rotation is applied from the capsule rotation. */
virtual FQuat GetBaseRotationOffset() const { return BaseRotationOffset; }
/** Get the saved rotation offset of mesh. This is how much extra rotation is applied from the capsule rotation. */
UFUNCTION(BlueprintCallable, Category=Character, meta=(DisplayName="GetBaseRotationOffset", ScriptName="GetBaseRotationOffset"))
FRotator GetBaseRotationOffsetRotator() const { return GetBaseRotationOffset().Rotator(); }
/** When true, player wants to jump */
uint32 bWantJump:1;
uint32 bIsPressingJump:1;
uint32 bStoredJump : 1;
uint32 bWantWallWalk : 1;
uint32 bWallWalkToggle : 1;
UPROPERTY(EditAnywhere, Category = Character)
uint32 bRunEnabled : 1;
UPROPERTY(EditAnywhere, Category = Character)
uint32 bJumpEnabled : 1;
UPROPERTY(EditAnywhere, Category = Character)
uint32 bLongJumpEnabled : 1;
UPROPERTY(EditAnywhere, Category = Character)
uint32 bWallWalkEnabled : 1;
/** Disable simulated gravity (set when character encroaches geometry on client, to keep him from falling through floors) */
UPROPERTY()
uint32 bSimGravityDisabled:1;
/** Tracks whether or not the character was already jumping last frame. */
UPROPERTY(VisibleInstanceOnly, Category=Character)
uint32 bWasJumping : 1;
uint32 bWasWallWalking : 1;
uint32 bIsSprinting : 1;
/**
* Jump key Held Time.
* This is the time that the player has held the jump key, in seconds.
*/
UPROPERTY(VisibleInstanceOnly, Category=Character)
float JumpKeyHoldTime;
/** Amount of jump force time remaining, if JumpMaxHoldTime > 0. */
UPROPERTY(VisibleInstanceOnly, Category=Character)
float JumpForceTimeRemaining;
/**
* The max time the jump key can be held.
* Note that if StopJumping() is not called before the max jump hold time is reached,
* then the character will carry on receiving vertical velocity. Therefore it is usually
* best to call StopJumping() when jump input has ceased (such as a button up event).
*/
UPROPERTY(EditAnywhere, Category=Character, Meta=(ClampMin=0.0, UIMin=0.0))
float JumpMaxHoldTime;
UPROPERTY(EditAnywhere, Category=Character, Meta=(ClampMin=0.0, UIMin=0.0))
float JumpHoldForceFactor;
/**
* The max number of jumps the character can perform.
* Note that if JumpMaxHoldTime is non zero and StopJumping is not called, the player
* may be able to perform and unlimited number of jumps. Therefore it is usually
* best to call StopJumping() when jump input has ceased (such as a button up event).
*/
UPROPERTY(EditAnywhere, Category=Character)
int32 JumpMaxCount;
/**
* Tracks the current number of jumps performed.
* This is incremented in CheckJumpInput, used in CanJump_Implementation, and reset in OnMovementModeChanged.
* When providing overrides for these methods, it's recommended to either manually
* increment / reset this value, or call the Super:: method.
*/
UPROPERTY(VisibleInstanceOnly, BlueprintReadOnly, Category=Character)
int32 JumpCurrentCount;
float WallWalkHoldTime;
UPROPERTY(EditAnywhere, Category = Character, Meta = (ClampMin = 0.0, UIMin = 0.0))
float WallWalkMaxHoldTime;
/** Incremented every time there is an Actor overlap event (start or stop) on this actor. */
uint32 NumActorOverlapEventsCounter;
//~ Begin AActor Interface.
virtual void BeginPlay() override;
virtual void EndPlay(const EEndPlayReason::Type EndPlayReason) override;
virtual void ClearCrossLevelReferences() override;
//virtual void PreNetReceive() override;
//virtual void PostNetReceive() override;
//virtual void OnRep_ReplicatedMovement() override;
//virtual void PostNetReceiveLocationAndRotation() override;
//virtual void GetSimpleCollisionCylinder(float& CollisionRadius, float& CollisionHalfHeight) const override;
//virtual UActorComponent* FindComponentByClass(const TSubclassOf<UActorComponent> ComponentClass) const override;
//virtual void TornOff() override;
virtual void NotifyActorBeginOverlap(AActor* OtherActor);
virtual void NotifyActorEndOverlap(AActor* OtherActor);
//~ End AActor Interface
//~ Begin INavAgentInterface Interface
//virtual FVector GetNavAgentLocation() const override;
//~ End INavAgentInterface Interface
//~ Begin APawn Interface.
virtual void PostInitializeComponents() override;
virtual UPawnMovementComponent* GetMovementComponent() const override;
virtual UPrimitiveComponent* GetMovementBase() const override final { return BasedMovement.MovementBase; }
virtual float GetDefaultHalfHeight() const override;
virtual void TurnOff() override;
virtual void Restart() override;
virtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override;
virtual void DisplayDebug(class UCanvas* Canvas, const FDebugDisplayInfo& DebugDisplay, float& YL, float& YPos) override;
//~ End APawn Interface
/** Apply momentum caused by damage. */
virtual void ApplyDamageMomentum(float DamageTaken, FDamageEvent const& DamageEvent, APawn* PawnInstigator, AActor* DamageCauser);
// This only adds vertical velocity
/**
* Make the character jump on the next update.
* If you want your character to jump according to the time that the jump key is held,
* then you can set JumpKeyHoldTime to some non-zero value. Make sure in this case to
* call StopJumping() when you want the jump's z-velocity to stop being applied (such
* as on a button up event), otherwise the character will carry on receiving the
* velocity until JumpKeyHoldTime is reached.
*/
virtual void Jump(FKey Key);
/**
* Stop the character from jumping on the next update.
* Call this from an input event (such as a button 'up' event) to cease applying
* jump Z-velocity. If this is not called, then jump z-velocity will be applied
* until JumpMaxHoldTime is reached.
*/
virtual void StopJumping();
/**
* Check if the character can jump in the current state.
*
* The default implementation may be overridden or extended by implementing the custom CanJump event in Blueprints.
*
* @Return Whether the character can jump in the current state.
*/
bool CanJump() const;
bool CanWallWalk() const;
public:
/** Marks character as not trying to jump */
virtual void ResetJumpState();
/**
* True if jump is actively providing a force, such as when the jump key is held and the time it has been held is less than JumpMaxHoldTime.
* @see CharacterMovement->IsFalling
*/
UFUNCTION(BlueprintCallable, Category=Character)
virtual bool IsJumpProvidingForce() const;
/**
* Set a pending launch velocity on the Character. This velocity will be processed on the next CharacterMovementComponent tick,
* and will set it to the "falling" state. Triggers the OnLaunched event.
* @PARAM LaunchVelocity is the velocity to impart to the Character
* @PARAM bXYOverride if true replace the XY part of the Character's velocity instead of adding to it.
* @PARAM bZOverride if true replace the Z component of the Character's velocity instead of adding to it.
*/
virtual void LaunchCharacter(FVector LaunchVelocity, bool bXYOverride, bool bZOverride);
/**
* Called when pawn's movement is blocked
* @param Impact describes the blocking hit.
*/
virtual void MoveBlockedBy(const FHitResult& Impact) {};
/** Trigger jump if jump button has been pressed. */
virtual void CheckJumpInput(float DeltaTime);
/** Update jump input state after having checked input. */
virtual void ClearJumpInput(float DeltaTime);
/**
* Get the maximum jump time for the character.
* Note that if StopJumping() is not called before the max jump hold time is reached,
* then the character will carry on receiving vertical velocity. Therefore it is usually
* best to call StopJumping() when jump input has ceased (such as a button up event).
*
* @return Maximum jump time for the character
*/
virtual float GetJumpMaxHoldTime() const;
};
<file_sep>// Fill out your copyright notice in the Description page of Project Settings.
#include "RlLevelScriptActor.h"
#include "Engine/World.h"
#include "Camera/CameraActor.h"
#include "Camera/CameraComponent.h"
#include "Kismet/GameplayStatics.h"
#include "Kismet/KismetSystemLibrary.h"
#include "Engine/GameViewportClient.h"
#include "Engine.h"
#include "Paper2D/Classes/PaperTileMapActor.h"
#include "Paper2D/Classes/PaperTileMapComponent.h"
#include "Paper2D/Classes/PaperTileMap.h"
#include "Materials/MaterialInterface.h"
#include "Kismet/KismetMathLibrary.h"
ARlLevelScriptActor::ARlLevelScriptActor()
{
PrimaryActorTick.bCanEverTick = true;
}
void ARlLevelScriptActor::BeginPlay()
{
Super::BeginPlay();
FActorSpawnParameters ActorSpawnParameters;
MainCamera = GetWorld()->SpawnActor<ACameraActor>(FVector(0.f), FRotator(0.f, 270.f, 0.f), ActorSpawnParameters);
MainCamera->GetCameraComponent()->ProjectionMode = ECameraProjectionMode::Orthographic;
MainCamera->GetCameraComponent()->OrthoWidth = 480;
MainCamera->GetCameraComponent()->OrthoNearClipPlane = -100;
MainCamera->GetCameraComponent()->bConstrainAspectRatio = false;
if (APlayerController* PlayerController = UGameplayStatics::GetPlayerController(GetWorld(), 0))
{
PlayerController->SetViewTargetWithBlend(MainCamera);
}
}<file_sep>// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "Components/Button.h"
#include "FocusButton.generated.h"
DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FOnClickDelegate, UFocusButton*, Button);
/**
*
*/
UCLASS()
class RAGELITE_API UFocusButton : public UButton
{
GENERATED_BODY()
public:
UFocusButton(const FObjectInitializer& ObjectInitializer);
UPROPERTY()
FOnClickDelegate OnClickDelegate;
private:
UFUNCTION()
void OnClick();
protected:
virtual TSharedRef<SWidget> RebuildWidget() override;
//virtual void NativeConstruct() override;
private:
FButtonStyle ButtonStyle;
UFUNCTION()
void Test();
UFUNCTION()
void OnFocused();
UFUNCTION()
void OnUnfocused();
UFUNCTION()
void SetFocus();
};
<file_sep>// Fill out your copyright notice in the Description page of Project Settings.
#include "RLTypes.h"
FHazardsData::FHazardsData()
{
Coords = FVector2D(0.f, 0.f);
DifficultyFactor = 0.f;
HazardsLocations = 0;
HazardsType = EHazardType::Spikes;
DartsDelay = 0.f;
DartsCooldown = 1.f;
DartsSpeed = 100.f;
bSpawnsFrom = true;
}
int32 FHazardsData::Num() const
{
int32 Count = 0;
for (int32 Number = HazardsLocations; Number; ++Count)
{
Number = Number & (Number - 1);
}
return Count;
}<file_sep>// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "RlSpriteHUD.generated.h"
class ASpriteTextActor;
UCLASS()
class RAGELITE_API ARlSpriteHUD : public AActor
{
GENERATED_BODY()
public:
void IncreaseScore();
void IncreaseLevel();
void IncreaseTime();
void IncreaseDeaths();
void ResetHUD();
void PostInitializeComponents() override;
protected:
virtual void BeginPlay() override;
private:
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "HUD", meta = (AllowPrivateAccess = "true"))
ASpriteTextActor* LevelText;
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "HUD", meta = (AllowPrivateAccess = "true"))
ASpriteTextActor* ScoreText;
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "HUD", meta = (AllowPrivateAccess = "true"))
ASpriteTextActor* TimeText;
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "HUD", meta = (AllowPrivateAccess = "true"))
ASpriteTextActor* DeathsText;
UPROPERTY(EditDefaultsOnly, Category = "HUD", meta = (AllowPrivateAccess = "true"))
AActor* Test;
private:
FTimerHandle TimeHandle;
void TimeTick();
};
<file_sep>// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/PawnMovementComponent.h"
//#include "GameFramework/CharacterMovementComponent.h" // FRlFindFloorResult
#include "RlCharacterMovementComponent.generated.h"
class ARlCharacter;
class USceneComponent;
/** Movement modes for RlCharacters. */
UENUM(BlueprintType)
enum class ERlMovementMode : uint8
{
/** None (movement is disabled). */
None UMETA(DisplayName = "None"),
/** Walking on a surface. */
Walking UMETA(DisplayName = "Walking"),
/** Falling under the effects of gravity, such as after jumping or walking off the edge of a surface. */
Falling UMETA(DisplayName = "Falling"),
/** Walking across the background wall. */
WallWalking UMETA(DisplayName = "WallWalking"),
MAX UMETA(Hidden),
};
/** Data about the floor for walking movement, used by CharacterMovementComponent. */
USTRUCT(BlueprintType)
struct RAGELITE_API FRlFindFloorResult
{
GENERATED_USTRUCT_BODY()
/**
* True if there was a blocking hit in the floor test that was NOT in initial penetration.
* The HitResult can give more info about other circumstances.
*/
UPROPERTY(VisibleInstanceOnly, BlueprintReadOnly, Category=CharacterFloor)
uint32 bBlockingHit:1;
/** True if the hit found a valid walkable floor. */
UPROPERTY(VisibleInstanceOnly, BlueprintReadOnly, Category=CharacterFloor)
uint32 bWalkableFloor:1;
/** True if the hit found a valid walkable floor using a line trace (rather than a sweep test, which happens when the sweep test fails to yield a walkable surface). */
UPROPERTY(VisibleInstanceOnly, BlueprintReadOnly, Category=CharacterFloor)
uint32 bLineTrace:1;
/** The distance to the floor, computed from the swept box trace. */
UPROPERTY(VisibleInstanceOnly, BlueprintReadOnly, Category=CharacterFloor)
float FloorDist;
/** The distance to the floor, computed from the trace. Only valid if bLineTrace is true. */
UPROPERTY(VisibleInstanceOnly, BlueprintReadOnly, Category=CharacterFloor)
float LineDist;
/** Hit result of the test that found a floor. Includes more specific data about the point of impact and surface normal at that point. */
UPROPERTY(VisibleInstanceOnly, BlueprintReadOnly, Category=CharacterFloor)
FHitResult HitResult;
public:
FRlFindFloorResult()
: bBlockingHit(false)
, bWalkableFloor(false)
, bLineTrace(false)
, FloorDist(0.f)
, LineDist(0.f)
, HitResult(1.f)
{
}
/** Returns true if the floor result hit a walkable surface. */
bool IsWalkableFloor() const
{
return bBlockingHit && bWalkableFloor;
}
void Clear()
{
bBlockingHit = false;
bWalkableFloor = false;
bLineTrace = false;
FloorDist = 0.f;
LineDist = 0.f;
HitResult.Reset(1.f, false);
}
/** Gets the distance to floor, either LineDist or FloorDist. */
float GetDistanceToFloor() const
{
// When the floor distance is set using SetFromSweep, the LineDist value will be reset.
// However, when SetLineFromTrace is used, there's no guarantee that FloorDist is set.
return bLineTrace ? LineDist : FloorDist;
}
void SetFromSweep(const FHitResult& InHit, const float InSweepFloorDist, const bool bIsWalkableFloor);
void SetFromLineTrace(const FHitResult& InHit, const float InSweepFloorDist, const float InLineDist, const bool bIsWalkableFloor);
};
/**
*
*/
UCLASS()
class RAGELITE_API URlCharacterMovementComponent : public UPawnMovementComponent
{
GENERATED_UCLASS_BODY()
protected:
/** Character movement component belongs to */
UPROPERTY()
ARlCharacter* CharacterOwner;
public:
/** Get the Character that owns UpdatedComponent. */
ARlCharacter* GetCharacterOwner() const;
/**
* Actor's current movement mode (walking, falling, etc).
* - walking: Walking on a surface, under the effects of friction, and able to "step up" barriers. Vertical velocity is zero.
* - falling: Falling under the effects of gravity, after jumping or walking off the edge of a surface.
* -
*/
UPROPERTY(Category = "Character Movement: MovementMode", VisibleAnywhere)
ERlMovementMode MovementMode;
/**
* Change movement mode.
*
* @param NewMovementMode The new movement mode
*/
virtual void SetMovementMode(ERlMovementMode NewMovementMode);
// Character Movement: General Settings
/** Max Acceleration (rate of change of velocity) */
UPROPERTY(Category = "Character Movement: General Settings", EditAnywhere, meta = (ClampMin = "0", UIMin = "0"))
float MaxAcceleration;
/**
* Factor used to multiply actual value of friction used when braking.
* This applies to any friction value that is currently used, which may depend on bUseSeparateBrakingFriction.
* @note This is 2 by default for historical reasons, a value of 1 gives the true drag equation.
* @see bUseSeparateBrakingFriction, GroundFriction, BrakingFriction
*/
UPROPERTY(Category="Character Movement: General Settings", EditAnywhere, meta=(ClampMin="0", UIMin="0"))
float BrakingFrictionFactor;
/**
* Friction (drag) coefficient applied when braking (whenever Acceleration = 0, or if character is exceeding max speed); actual value used is this multiplied by BrakingFrictionFactor.
* When braking, this property allows you to control how much friction is applied when moving across the ground, applying an opposing force that scales with current velocity.
* Braking is composed of friction (velocity-dependent drag) and constant deceleration.
* This is the current value, used in all movement modes; if this is not desired, override it or bUseSeparateBrakingFriction when movement mode changes.
* @note Only used if bUseSeparateBrakingFriction setting is true, otherwise current friction such as GroundFriction is used.
* @see bUseSeparateBrakingFriction, BrakingFrictionFactor, GroundFriction, BrakingDecelerationWalking
*/
UPROPERTY(Category="Character Movement: General Settings", EditAnywhere, meta=(ClampMin="0", UIMin="0", EditCondition="bUseSeparateBrakingFriction"))
float BrakingFriction;
/**
* Time substepping when applying braking friction. Smaller time steps increase accuracy at the slight cost of performance, especially if there are large frame times.
*/
UPROPERTY(Category="Character Movement: General Settings", EditAnywhere, AdvancedDisplay, meta=(ClampMin="0.0166", ClampMax="0.05", UIMin="0.0166", UIMax="0.05"))
float BrakingSubStepTime;
/**
* If true, high-level movement updates will be wrapped in a movement scope that accumulates updates and defers a bulk of the work until the end.
* When enabled, touch and hit events will not be triggered until the end of multiple moves within an update, which can improve performance.
*
* @see FScopedMovementUpdate
*/
UPROPERTY(Category="Character Movement: General Settings", EditAnywhere, AdvancedDisplay)
uint8 bEnableScopedMovementUpdates:1;
/**
* If true, movement will be performed even if there is no Controller for the Character owner.
* Normally without a Controller, movement will be aborted and velocity and acceleration are zeroed if the character is walking.
* Characters that are spawned without a Controller but with this flag enabled will initialize the movement mode to DefaultLandMovementMode or DefaultWaterMovementMode appropriately.
* @see DefaultLandMovementMode, DefaultWaterMovementMode
*/
UPROPERTY(Category="Character Movement: General Settings", EditAnywhere, AdvancedDisplay)
uint8 bRunPhysicsWithNoController:1;
/**
* If true, BrakingFriction will be used to slow the character to a stop (when there is no Acceleration).
* If false, braking uses the same friction passed to CalcVelocity() (ie GroundFriction when walking), multiplied by BrakingFrictionFactor.
* This setting applies to all movement modes; if only desired in certain modes, consider toggling it when movement modes change.
* @see BrakingFriction
*/
UPROPERTY(Category="Character Movement: General Settings", EditAnywhere)
uint8 bUseSeparateBrakingFriction:1;
/** Mass of pawn (for when momentum is imparted to it). */
UPROPERTY(Category="Character Movement: General Settings", EditAnywhere, BlueprintReadWrite, meta=(ClampMin="0", UIMin="0"))
float Mass;
/**
* Default movement mode when not in water. Used at player startup or when teleported.
* @see DefaultWaterMovementMode
* @see bRunPhysicsWithNoController
*/
UPROPERTY(Category="Character Movement: General Settings", EditAnywhere)
ERlMovementMode DefaultLandMovementMode;
private:
/**
* Ground movement mode to switch to after falling and resuming ground movement.
* Only allowed values are: MOVE_Walking, MOVE_NavWalking.
* @see SetGroundMovementMode(), GetGroundMovementMode()
*/
UPROPERTY()
ERlMovementMode GroundMovementMode;
public:
/**
* Get current GroundMovementMode value.
* @return current GroundMovementMode
* @see GroundMovementMode, SetGroundMovementMode()
*/
ERlMovementMode GetGroundMovementMode() const { return GroundMovementMode; }
/** Used by movement code to determine if a change in position is based on normal movement or a teleport. If not a teleport, velocity can be recomputed based on the change in position. */
UPROPERTY(Category="Character Movement: General Settings", Transient, VisibleInstanceOnly, BlueprintReadWrite)
uint8 bJustTeleported:1;
/**
* Whether the character ignores changes in rotation of the base it is standing on.
* If true, the character maintains current world rotation.
* If false, the character rotates with the moving base.
*/
UPROPERTY(Category="Character Movement: Walking", EditAnywhere, BlueprintReadWrite)
uint8 bIgnoreBaseRotation:1;
// Character Movement: Walking
/**
* Setting that affects movement control. Higher values allow faster changes in direction.
* If bUseSeparateBrakingFriction is false, also affects the ability to stop more quickly when braking (whenever Acceleration is zero), where it is multiplied by BrakingFrictionFactor.
* When braking, this property allows you to control how much friction is applied when moving across the ground, applying an opposing force that scales with current velocity.
* This can be used to simulate slippery surfaces such as ice or oil by changing the value (possibly based on the material pawn is standing on).
* @see BrakingDecelerationWalking, BrakingFriction, bUseSeparateBrakingFriction, BrakingFrictionFactor
*/
UPROPERTY(Category = "Character Movement: Walking", EditAnywhere, meta = (ClampMin = "0", UIMin = "0"))
float GroundFriction;
/** Saved location of object we are standing on, for UpdateBasedMovement() to determine if base moved in the last frame, and therefore pawn needs an update. */
FQuat OldBaseQuat;
/** Saved location of object we are standing on, for UpdateBasedMovement() to determine if base moved in the last frame, and therefore pawn needs an update. */
FVector OldBaseLocation;
/** The maximum ground speed when walking. Also determines maximum lateral speed when falling. */
UPROPERTY(Category="Character Movement: Walking", EditAnywhere, meta=(ClampMin="0", UIMin="0"))
float MaxWalkSpeed;
/** The ground speed that we should accelerate up to when walking at minimum analog stick tilt */
UPROPERTY(Category = "Character Movement: Walking", EditAnywhere, meta = (ClampMin = "0", UIMin = "0"))
float MinAnalogWalkSpeed;
/**
* Deceleration when walking and not applying acceleration. This is a constant opposing force that directly lowers velocity by a constant value.
* @see GroundFriction, MaxAcceleration
*/
UPROPERTY(Category="Character Movement: Walking", EditAnywhere, meta=(ClampMin="0", UIMin="0"))
float BrakingDecelerationWalking;
/**
* Whether or not the character should sweep for collision geometry while walking.
* @see USceneComponent::MoveComponent.
*/
UPROPERTY(Category="Character Movement: Walking", EditAnywhere)
uint8 bSweepWhileNavWalking:1;
/**
* Force the Character in MOVE_Walking to do a check for a valid floor even if he hasn't moved. Cleared after next floor check.
* Normally if bAlwaysCheckFloor is false we try to avoid the floor check unless some conditions are met, but this can be used to force the next check to always run.
*/
UPROPERTY(Category="Character Movement: Walking", VisibleInstanceOnly, AdvancedDisplay)
uint8 bForceNextFloorCheck:1;
UPROPERTY(Category = "Character Movement: Walking", EditAnywhere)
float NormalMaxAcceleration;
UPROPERTY(Category = "Character Movement: Walking", EditAnywhere)
float NormalMaxWalkSpeed;
UPROPERTY(Category = "Character Movement: Walking", EditAnywhere)
float SprintMaxAcceleration;
UPROPERTY(Category = "Character Movement: Walking", EditAnywhere)
float SprintMaxWalkSpeed;
void SprintStart();
void SprintStop();
bool bSprintStop;
float LastSpeed;
// Floor
/** Information about the floor the Character is standing on (updated only during walking movement). */
UPROPERTY(Category="Character Movement: Walking", VisibleInstanceOnly, BlueprintReadOnly)
FRlFindFloorResult CurrentFloor;
bool CheckSpikes();
// Character Movement: Jumping / Falling
/** Custom gravity scale. Gravity is multiplied by this amount for the character. */
UPROPERTY(Category="Character Movement: Jumping / Falling", EditAnywhere)
float GravityScale;
/** Initial velocity (instantaneous vertical acceleration) when jumping. */
UPROPERTY(Category="Character Movement: Jumping / Falling", EditAnywhere, meta=(ClampMin="0", UIMin="0"))
float JumpZVelocity;
/** Fraction of JumpZVelocity to use when automatically "jumping off" of a base actor that's not allowed to be a base for a character. (For example, if you're not allowed to stand on other players.) */
UPROPERTY(Category="Character Movement: Jumping / Falling", EditAnywhere, AdvancedDisplay, meta=(ClampMin="0", UIMin="0"))
float JumpOffJumpZFactor;
/**
* Lateral deceleration when falling and not applying acceleration.
* @see MaxAcceleration
*/
UPROPERTY(Category="Character Movement: Jumping / Falling", EditAnywhere, meta=(ClampMin="0", UIMin="0"))
float BrakingDecelerationFalling;
/**
* Friction to apply to lateral air movement when falling.
* If bUseSeparateBrakingFriction is false, also affects the ability to stop more quickly when braking (whenever Acceleration is zero).
* @see BrakingFriction, bUseSeparateBrakingFriction
*/
UPROPERTY(Category="Character Movement: Jumping / Falling", EditAnywhere, meta=(ClampMin="0", UIMin="0"))
float FallingLateralFriction;
/** If true, impart the base actor's X velocity when falling off it (which includes jumping) */
UPROPERTY(Category="Character Movement: Jumping / Falling", EditAnywhere)
uint8 bImpartBaseVelocityX:1;
/** If true, impart the base actor's Y velocity when falling off it (which includes jumping) */
UPROPERTY(Category="Character Movement: Jumping / Falling", EditAnywhere)
uint8 bImpartBaseVelocityY:1;
/** If true, impart the base actor's Z velocity when falling off it (which includes jumping) */
UPROPERTY(Category="Character Movement: Jumping / Falling", EditAnywhere)
uint8 bImpartBaseVelocityZ:1;
/**
* If true, impart the base component's tangential components of angular velocity when jumping or falling off it.
* Only those components of the velocity allowed by the separate component settings (bImpartBaseVelocityX etc) will be applied.
* @see bImpartBaseVelocityX, bImpartBaseVelocityY, bImpartBaseVelocityZ
*/
UPROPERTY(Category="Character Movement: Jumping / Falling", EditAnywhere)
uint8 bImpartBaseAngularVelocity:1;
UPROPERTY(Category = "Character Movement: Jumping / Falling", EditAnywhere)
float TerminalVelocity;
UPROPERTY(Category = "Character Movement: Jumping / Falling", EditAnywhere)
bool bCustomTerminalVelocity;
protected:
/**
* True during movement update.
* Used internally so that attempts to change CharacterOwner and UpdatedComponent are deferred until after an update.
* @see IsMovementInProgress()
*/
UPROPERTY()
uint8 bMovementInProgress:1;
public:
/** Ignores size of acceleration component, and forces max acceleration to drive character at full velocity. */
UPROPERTY()
uint8 bForceMaxAccel:1;
public:
/** What to update CharacterOwner and UpdatedComponent after movement ends */
UPROPERTY()
USceneComponent* DeferredUpdatedMoveComponent;
protected:
/**
* Current acceleration vector (with magnitude).
* This is calculated each update based on the input vector and the constraints of MaxAcceleration and the current movement mode.
*/
UPROPERTY()
FVector Acceleration;
/**
* Rotation after last PerformMovement or SimulateMovement update.
*/
UPROPERTY()
FQuat LastUpdateRotation;
/**
* Location after last PerformMovement or SimulateMovement update. Used internally to detect changes in position from outside character movement to try to validate the current floor.
*/
UPROPERTY()
FVector LastUpdateLocation;
/**
* Velocity after last PerformMovement or SimulateMovement update. Used internally to detect changes in velocity from external sources.
*/
UPROPERTY()
FVector LastUpdateVelocity;
/** Accumulated impulse to be added next tick. */
UPROPERTY()
FVector PendingImpulseToApply;
/** Accumulated force to be added next tick. */
UPROPERTY()
FVector PendingForceToApply;
/**
* Modifier to applied to values such as acceleration and max speed due to analog input.
*/
UPROPERTY()
float AnalogInputModifier;
/** Computes the analog input modifier based on current input vector and/or acceleration. */
virtual float ComputeAnalogInputModifier() const;
public:
/** Returns the location at the end of the last tick. */
FVector GetLastUpdateLocation() const { return LastUpdateLocation; }
/** Returns the rotation at the end of the last tick. */
FRotator GetLastUpdateRotation() const { return LastUpdateRotation.Rotator(); }
/** Returns the rotation Quat at the end of the last tick. */
FQuat GetLastUpdateQuat() const { return LastUpdateRotation; }
/** Returns the velocity at the end of the last tick. */
FVector GetLastUpdateVelocity() const { return LastUpdateVelocity; }
/**
* Compute remaining time step given remaining time and current iterations.
* The last iteration (limited by MaxSimulationIterations) always returns the remaining time, which may violate MaxSimulationTimeStep.
*
* @param RemainingTime Remaining time in the tick.
* @param Iterations Current iteration of the tick (starting at 1).
* @return The remaining time step to use for the next sub-step of iteration.
* @see MaxSimulationTimeStep, MaxSimulationIterations
*/
float GetSimulationTimeStep(float RemainingTime, int32 Iterations) const;
/**
* Max time delta for each discrete simulation step.
* Used primarily in the the more advanced movement modes that break up larger time steps (usually those applying gravity such as falling and walking).
* Lowering this value can address issues with fast-moving objects or complex collision scenarios, at the cost of performance.
*
* WARNING: if (MaxSimulationTimeStep * MaxSimulationIterations) is too low for the min framerate, the last simulation step may exceed MaxSimulationTimeStep to complete the simulation.
* @see MaxSimulationIterations
*/
UPROPERTY(Category="Character Movement: General Settings", EditAnywhere, BlueprintReadWrite, AdvancedDisplay, meta=(ClampMin="0.0166", ClampMax="0.50", UIMin="0.0166", UIMax="0.50"))
float MaxSimulationTimeStep;
/**
* Max number of iterations used for each discrete simulation step.
* Used primarily in the the more advanced movement modes that break up larger time steps (usually those applying gravity such as falling and walking).
* Increasing this value can address issues with fast-moving objects or complex collision scenarios, at the cost of performance.
*
* WARNING: if (MaxSimulationTimeStep * MaxSimulationIterations) is too low for the min framerate, the last simulation step may exceed MaxSimulationTimeStep to complete the simulation.
* @see MaxSimulationTimeStep
*/
UPROPERTY(Category="Character Movement: General Settings", EditAnywhere, BlueprintReadWrite, AdvancedDisplay, meta=(ClampMin="1", ClampMax="25", UIMin="1", UIMax="25"))
int32 MaxSimulationIterations;
/**
* Max distance we allow simulated proxies to depenetrate when moving out of anything but Pawns.
* This is generally more tolerant than with Pawns, because other geometry is either not moving, or is moving predictably with a bit of delay compared to on the server.
* @see MaxDepenetrationWithGeometryAsProxy, MaxDepenetrationWithPawn, MaxDepenetrationWithPawnAsProxy
*/
UPROPERTY(Category="Character Movement: General Settings", EditAnywhere, BlueprintReadWrite, AdvancedDisplay, meta=(ClampMin="0", UIMin="0"))
float MaxDepenetrationWithGeometry;
/**
* Max distance we are allowed to depenetrate when moving out of other Pawns.
* @see MaxDepenetrationWithGeometry, MaxDepenetrationWithGeometryAsProxy, MaxDepenetrationWithPawnAsProxy
*/
UPROPERTY(Category="Character Movement: General Settings", EditAnywhere, BlueprintReadWrite, AdvancedDisplay, meta=(ClampMin="0", UIMin="0"))
float MaxDepenetrationWithPawn;
public:
UPROPERTY(Category="Character Movement: Physics Interaction", EditAnywhere)
uint8 bEnablePhysicsInteraction:1;
/**
* Set this to true if riding on a moving base that you know is clear from non-moving world obstructions.
* Optimization to avoid sweeps during based movement, use with care.
*/
UPROPERTY()
uint8 bFastAttachedMove:1;
/**
* Whether we always force floor checks for stationary Characters while walking.
* Normally floor checks are avoided if possible when not moving, but this can be used to force them if there are use-cases where they are being skipped erroneously
* (such as objects moving up into the character from below).
*/
UPROPERTY(Category="Character Movement: Walking", EditAnywhere, BlueprintReadWrite, AdvancedDisplay)
uint8 bAlwaysCheckFloor:1;
///**
// * Performs floor checks as if the character is using a shape with a flat base.
// * This avoids the situation where characters slowly lower off the side of a ledge (as their capsule 'balances' on the edge).
// */
//UPROPERTY(Category="Character Movement: Walking", EditAnywhere, BlueprintReadWrite, AdvancedDisplay)
//uint8 bUseFlatBaseForFloorChecks:1;
/** Used to prevent reentry of JumpOff() */
UPROPERTY()
uint8 bPerformingJumpOff:1;
/** Temporarily holds launch velocity when pawn is to be launched so it happens at end of movement. */
UPROPERTY()
FVector PendingLaunchVelocity;
protected:
/** Called after MovementMode has changed. Base implementation does special handling for starting certain modes, then notifies the CharacterOwner. */
virtual void OnMovementModeChanged(ERlMovementMode PreviousMovementMode);
public:
//Begin UActorComponent Interface
virtual void TickComponent(float DeltaTime, enum ELevelTick TickType, FActorComponentTickFunction *ThisTickFunction) override;
virtual void PostLoad() override;
virtual void Deactivate() override;
//End UActorComponent Interface
//BEGIN UMovementComponent Interface
virtual float GetMaxSpeed() const override;
virtual void StopActiveMovement() override;
virtual bool IsFalling() const override;
virtual bool IsWallWalking() const;
virtual bool IsMovingOnGround() const override;
virtual float GetGravityZ() const override;
virtual void AddRadialForce(const FVector& Origin, float Radius, float Strength, enum ERadialImpulseFalloff Falloff) override;
virtual void AddRadialImpulse(const FVector& Origin, float Radius, float Strength, enum ERadialImpulseFalloff Falloff, bool bVelChange) override;
//END UMovementComponent Interface
/** Returns true if the character is in the 'Walking' movement mode. */
UFUNCTION(BlueprintCallable, Category="Pawn|Components|CharacterMovement")
bool IsWalking() const;
/**
* Returns true if currently performing a movement update.
* @see bMovementInProgress
*/
bool IsMovementInProgress() const { return bMovementInProgress; }
/** Make movement impossible (sets movement mode to MOVE_None). */
UFUNCTION(BlueprintCallable, Category="Pawn|Components|CharacterMovement")
virtual void DisableMovement();
/** Return true if we have a valid CharacterOwner and UpdatedComponent. */
virtual bool HasValidData() const;
/** Transition from walking to falling */
virtual void StartFalling(int32 Iterations, float remainingTime, float timeTick, const FVector& Delta, const FVector& subLoc);
/** Adjust distance from floor, trying to maintain a slight offset from the floor when walking (based on CurrentFloor). */
virtual void AdjustFloorHeight();
/** Return PrimitiveComponent we are based on (standing and walking on). */
UFUNCTION(BlueprintCallable, Category="Pawn|Components|CharacterMovement")
UPrimitiveComponent* GetMovementBase() const;
/** true to update CharacterOwner and UpdatedComponent after movement ends */
UPROPERTY()
uint8 bDeferUpdateMoveComponent:1;
/** Update controller's view rotation as pawn's base rotates */
virtual void UpdateBasedRotation(FRotator& FinalRotation, const FRotator& ReducedRotation);
/** Update OldBaseLocation and OldBaseQuat if there is a valid movement base, and store the relative location/rotation if necessary. Ignores bDeferUpdateBasedMovement and forces the update. */
virtual void SaveBaseLocation();
/** changes physics based on MovementMode */
virtual void StartNewPhysics(float DeltaTime, int32 Iterations);
/**
* Perform jump. Called by Character when a jump has been detected because Character->bPressedJump was true. Checks CanJump().
* Note that you should usually trigger a jump through Character::Jump() instead.
* @return True if the jump was triggered successfully.
*/
virtual bool DoJump();
virtual bool DoWallWalk();
/** Queue a pending launch with velocity LaunchVel. */
virtual void Launch(FVector const& LaunchVel);
/** Handle a pending launch during an update. Returns true if the launch was triggered. */
virtual bool HandlePendingLaunch();
/**
* If we have a movement base, get the velocity that should be imparted by that base, usually when jumping off of it.
* Only applies the components of the velocity enabled by bImpartBaseVelocityX, bImpartBaseVelocityY, bImpartBaseVelocityZ.
*/
UFUNCTION(BlueprintCallable, Category="Pawn|Components|CharacterMovement")
virtual FVector GetImpartedMovementBaseVelocity() const;
/** Force this pawn to bounce off its current base, which isn't an acceptable base for it. */
virtual void JumpOff(AActor* MovementBaseActor);
/** Can be overridden to choose to jump based on character velocity, base actor dimensions, etc. */
virtual FVector GetBestDirectionOffActor(AActor* BaseActor) const; // Calculates the best direction to go to "jump off" an actor.
/**
* Updates Velocity and Acceleration based on the current state, applying the effects of friction and acceleration or deceleration. Does not apply gravity.
* This is used internally during movement updates. Normally you don't need to call this from outside code, but you might want to use it for custom movement modes.
*
* @param DeltaTime time elapsed since last frame.
* @param Friction coefficient of friction when not accelerating, or in the direction opposite acceleration.
* @param BrakingDeceleration deceleration applied when not accelerating, or when exceeding max velocity.
*/
virtual void CalcVelocity(float DeltaTime, float Friction, float BrakingDeceleration);
/**
* Compute the max jump height based on the JumpZVelocity velocity and gravity.
* This does not take into account the CharacterOwner's MaxJumpHoldTime.
*/
virtual float GetMaxJumpHeight() const;
/**
* Compute the max jump height based on the JumpZVelocity velocity and gravity.
* This does take into account the CharacterOwner's MaxJumpHoldTime.
*/
virtual float GetMaxJumpHeightWithJumpTime() const;
/** Returns maximum acceleration for the current state. */
virtual float GetMinAnalogSpeed() const;
/** Returns maximum acceleration for the current state. */
virtual float GetMaxAcceleration() const;
/** Returns maximum deceleration for the current state when braking (ie when there is no acceleration). */
virtual float GetMaxBrakingDeceleration() const;
/** Returns current acceleration, computed from input vector each update. */
FVector GetCurrentAcceleration() const;
/** Returns modifier [0..1] based on the magnitude of the last input vector, which is used to modify the acceleration and max speed during movement. */
float GetAnalogInputModifier() const;
/** Update the base of the character, which is the PrimitiveComponent we are standing on. */
virtual void SetBase(UPrimitiveComponent* NewBase, const FName BoneName = NAME_None, bool bNotifyActor=true);
/**
* Update the base of the character, using the given floor result if it is walkable, or null if not. Calls SetBase().
*/
void SetBaseFromFloor(const FRlFindFloorResult& FloorResult);
/** Applies momentum accumulated through AddImpulse() and AddForce(), then clears those forces. Does *not* use ClearAccumulatedForces() since that would clear pending launch velocity as well. */
virtual void ApplyAccumulatedForces(float DeltaSeconds);
/** Clears forces accumulated through AddImpulse() and AddForce(), and also pending launch velocity. */
virtual void ClearAccumulatedForces();
/** Handle falling movement. */
virtual void PhysFalling(float DeltaTime, int32 Iterations);
protected:
/** Handle landing against Hit surface over remaingTime and iterations, calling SetPostLandedPhysics() and starting the new movement mode. */
virtual void ProcessLanded(const FHitResult& Hit, float remainingTime, int32 Iterations);
/** Handle wall walking movement. */
virtual void PhysWallWalking(float DeltaTime, int32 Iterations);
public:
/** Called by owning Character upon successful teleport from AActor::TeleportTo(). */
virtual void OnTeleported() override;
/** Check if pawn is falling */
virtual bool CheckFall(const FRlFindFloorResult& OldFloor, const FHitResult& Hit, const FVector& Delta, const FVector& OldLocation, float remainingTime, float timeTick, int32 Iterations);
/**
* Revert to previous position OldLocation, return to being based on OldBase.
* if bFailMove, stop movement and notify controller
*/
void RevertMove(const FVector& OldLocation, UPrimitiveComponent* OldBase, const FVector& InOldBaseLocation, const FRlFindFloorResult& OldFloor, bool bFailMove);
/** Set movement mode to the default based on the current physics volume. */
virtual void SetDefaultMovementMode();
virtual void SetUpdatedComponent(USceneComponent* NewUpdatedComponent) override;
/** Returns MovementMode string */
virtual FString GetMovementName() const;
/**
* Add impulse to character. Impulses are accumulated each tick and applied together
* so multiple calls to this function will accumulate.
* An impulse is an instantaneous force, usually applied once. If you want to continually apply
* forces each frame, use AddForce().
* Note that changing the momentum of characters like this can change the movement mode.
*
* @param Impulse Impulse to apply.
* @param bVelocityChange Whether or not the impulse is relative to mass.
*/
virtual void AddImpulse( FVector Impulse, bool bVelocityChange = false );
/**
* Add force to character. Forces are accumulated each tick and applied together
* so multiple calls to this function will accumulate.
* Forces are scaled depending on timestep, so they can be applied each frame. If you want an
* instantaneous force, use AddImpulse.
* Adding a force always takes the actor's mass into account.
* Note that changing the momentum of characters like this can change the movement mode.
*
* @param Force Force to apply.
*/
virtual void AddForce( FVector Force );
/** Return true if the hit result should be considered a walkable surface for the character. */
UFUNCTION(BlueprintCallable, Category="Pawn|Components|CharacterMovement")
virtual bool IsWalkable(const FHitResult& Hit) const;
protected:
/** @note Movement update functions should only be called through StartNewPhysics()*/
virtual void PhysWalking(float DeltaTime, int32 Iterations);
/**
* Move along the floor, using CurrentFloor and ComputeGroundMovementDelta() to get a movement direction.
* If a second walkable surface is hit, it will also be moved along using the same approach.
*
* @param InVelocity: Velocity of movement
* @param DeltaSeconds: Time over which movement occurs
*/
virtual void MoveHorizontal(const FVector& InVelocity, float DeltaSeconds, bool bAlongFloor = true);
/** Notification that the character is stuck in geometry. Only called during walking movement. */
virtual void OnCharacterStuckInGeometry(const FHitResult* Hit);
/**
* Adjusts velocity when walking so that Z velocity is zero.
* When bMaintainHorizontalGroundVelocity is false, also rescales the velocity vector to maintain the original magnitude, but in the horizontal direction.
*/
virtual void MaintainHorizontalGroundVelocity();
/** Overridden to enforce max distances based on hit geometry. */
virtual FVector GetPenetrationAdjustment(const FHitResult& Hit) const override;
/** Overridden to set bJustTeleported to true, so we don't make incorrect velocity calculations based on adjusted movement. */
virtual bool ResolvePenetrationImpl(const FVector& Adjustment, const FHitResult& Hit, const FQuat& NewRotation) override;
/** Custom version of SlideAlongSurface that handles different movement modes separately; namely during walking physics we might not want to slide up slopes. */
virtual float SlideAlongSurface(const FVector& Delta, float Time, const FVector& Normal, FHitResult& Hit, bool bHandleImpact) override;
/**
* Calculate slide vector along a surface.
* Has special treatment when falling, to avoid boosting up slopes (calling HandleSlopeBoosting() in this case).
*
* @param Delta: Attempted move.
* @param Time: Amount of move to apply (between 0 and 1).
* @param Normal: Normal opposed to movement. Not necessarily equal to Hit.Normal (but usually is).
* @param Hit: HitResult of the move that resulted in the slide.
* @return New deflected vector of movement.
*/
virtual FVector ComputeSlideVector(const FVector& Delta, const float Time, const FVector& Normal, const FHitResult& Hit) const override;
/**
* Limit the slide vector when falling if the resulting slide might boost the character faster upwards.
* @param SlideResult: Vector of movement for the slide (usually the result of ComputeSlideVector)
* @param Delta: Original attempted move
* @param Time: Amount of move to apply (between 0 and 1).
* @param Normal: Normal opposed to movement. Not necessarily equal to Hit.Normal (but usually is).
* @param Hit: HitResult of the move that resulted in the slide.
* @return: New slide result.
*/
virtual FVector HandleSlopeBoosting(const FVector& SlideResult, const FVector& Delta, const float Time, const FVector& Normal, const FHitResult& Hit) const;
/** Slows towards stop. */
virtual void ApplyVelocityBraking(float DeltaTime, float Friction, float BrakingDeceleration);
public:
/**
* Return true if the 2D distance to the impact point is inside the edge tolerance (CapsuleRadius minus a small rejection threshold).
* Useful for rejecting adjacent hits when finding a floor or landing spot.
*/
virtual bool IsWithinEdgeTolerance(const FVector& CapsuleLocation, const FVector& TestImpactPoint, const float CapsuleRadius) const;
/**
* Sweeps a vertical trace to find the floor for the capsule at the given location. Will attempt to perch if ShouldComputePerchResult() returns true for the downward sweep result.
* No floor will be found if collision is disabled on the capsule!
*
* @param CapsuleLocation Location where the capsule sweep should originate
* @param OutFloorResult [Out] Contains the result of the floor check. The HitResult will contain the valid sweep or line test upon success, or the result of the sweep upon failure.
* @param bCanUseCachedLocation If true, may use a cached value (can be used to avoid unnecessary floor tests, if for example the capsule was not moving since the last test).
* @param DownwardSweepResult If non-null and it contains valid blocking hit info, this will be used as the result of a downward sweep test instead of doing it as part of the update.
*/
virtual void FindFloor(const FVector& CapsuleLocation, FRlFindFloorResult& OutFloorResult, bool bCanUseCachedLocation, const FHitResult* DownwardSweepResult = NULL) const;
/**
* Compute distance to the floor from bottom box and store the result in OutFloorResult.
* This distance is the swept distance of the box to the first point impacted by bottom, or distance from the bottom of the box in the case of a line trace.
* This function does not care if collision is disabled on the capsule (unlike FindFloor).
* @see FindFloor
*
* @param BoxLocation: Location of the box used for the query
* @param LineDistance: If non-zero, max distance to test for a simple line check from the capsule base. Used only if the sweep test fails to find a walkable floor, and only returns a valid result if the impact normal is a walkable normal.
* @param SweepDistance: If non-zero, max distance to use when sweeping a capsule downwards for the test. MUST be greater than or equal to the line distance.
* @param OutFloorResult: Result of the floor check. The HitResult will contain the valid sweep or line test upon success, or the result of the sweep upon failure.
* @param SweepRadius: The radius to use for sweep tests. Should be <= capsule radius.
* @param DownwardSweepResult: If non-null and it contains valid blocking hit info, this will be used as the result of a downward sweep test instead of doing it as part of the update.
*/
virtual void ComputeFloorDist(const FVector& BoxLocation, float LineDistance, float SweepDistance, FRlFindFloorResult& OutFloorResult, float SweepRadius, const FHitResult* DownwardSweepResult = NULL) const;
/**
* Sweep against the world and return the first blocking hit.
* Intended for tests against the floor, because it may change the result of impacts on the lower area of the test (especially if bUseFlatBaseForFloorChecks is true).
*
* @param OutHit First blocking hit found.
* @param Start Start location of the capsule.
* @param End End location of the capsule.
* @param TraceChannel The 'channel' that this trace is in, used to determine which components to hit.
* @param CollisionShape Box collision shape.
* @param Params Additional parameters used for the trace.
* @param ResponseParam ResponseContainer to be used for this trace.
* @return True if OutHit contains a blocking hit entry.
*/
virtual bool FloorSweepTest(
struct FHitResult& OutHit,
const FVector& Start,
const FVector& End,
ECollisionChannel TraceChannel,
const struct FCollisionShape& CollisionShape,
const struct FCollisionQueryParams& Params,
const struct FCollisionResponseParams& ResponseParam
) const;
/** Verify that the supplied hit result is a valid landing spot when falling. */
virtual bool IsValidLandingSpot(const FVector& CapsuleLocation, const FHitResult& Hit) const;
/**
* Determine whether we should try to find a valid landing spot after an impact with an invalid one (based on the Hit result).
* For example, landing on the lower portion of the capsule on the edge of geometry may be a walkable surface, but could have reported an unwalkable impact normal.
*/
virtual bool ShouldCheckForValidLandingSpot(float DeltaTime, const FVector& Delta, const FHitResult& Hit) const;
protected:
///** Called when the collision capsule touches another primitive component */
//UFUNCTION()
//virtual void CapsuleTouched(UPrimitiveComponent* OverlappedComp, AActor* Other, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult);
// Enum used to control GetPawnCapsuleExtent behavior
enum EShrinkBoxExtent
{
SHRINK_None, // Don't change the size of the capsule
SHRINK_XCustom, // Change only X, based on a supplied param
SHRINK_YCustom, // Change only X, based on a supplied param
SHRINK_ZCustom, // Change only X, based on a supplied param
SHRINK_AllCustom, // Change both radius and height, based on a supplied param
};
/** Get the box extent for the Pawn owner, possibly reduced in size depending on ShrinkMode.
* @param ShrinkMode Controls the way the box is resized.
* @param CustomShrinkAmount The amount to shrink the box, used only for ShrinkModes that specify custom.
* @return The capsule extent of the Pawn owner, possibly reduced in size depending on ShrinkMode.
*/
FVector GetPawnBoxExtent(const EShrinkBoxExtent ShrinkMode, const float CustomShrinkAmount = 0.f) const;
/** Get the collision shape for the Pawn owner, possibly reduced in size depending on ShrinkMode.
* @param ShrinkMode Controls the way the box is resized.
* @param CustomShrinkAmount The amount to shrink the box, used only for ShrinkModes that specify custom.
* @return The capsule extent of the Pawn owner, possibly reduced in size depending on ShrinkMode.
*/
FCollisionShape GetPawnBoxCollisionShape(const EShrinkBoxExtent ShrinkMode, const float CustomShrinkAmount = 0.f) const;
/** Enforce constraints on input given current state. For instance, don't move upwards if walking and looking up. */
virtual FVector ConstrainInputAcceleration(const FVector& InputAcceleration) const;
/** Scale input acceleration, based on movement acceleration rate. */
virtual FVector ScaleInputAcceleration(const FVector& InputAcceleration) const;
public:
/** React to instantaneous change in position. Invalidates cached floor recomputes it if possible if there is a current movement base. */
virtual void UpdateFloorFromAdjustment();
protected:
// Movement functions broken out based on owner's network Role.
// TickComponent calls the correct version based on the Role.
// These may be called during move playback and correction during network updates.
//
/** Perform movement on an autonomous client */
virtual void PerformMovement(float DeltaTime);
public:
/** Minimum delta time considered when ticking. Delta times below this are not considered. This is a very small non-zero value to avoid potential divide-by-zero in simulation code. */
static const float MIN_TICK_TIME;
/** Minimum acceptable distance for Character capsule to float above floor when walking. */
static const float MIN_FLOOR_DIST;
/** Maximum acceptable distance for Character capsule to float above floor when walking. */
static const float MAX_FLOOR_DIST;
/** Reject sweep impacts that are this close to the edge of the vertical portion of the capsule when performing vertical sweeps, and try again with a smaller capsule. */
static const float SWEEP_EDGE_REJECT_DISTANCE;
/** Stop completely when braking and velocity magnitude is lower than this. */
static const float BRAKE_TO_STOP_VELOCITY;
};
FORCEINLINE ARlCharacter* URlCharacterMovementComponent::GetCharacterOwner() const
{
return CharacterOwner;
}
FORCEINLINE_DEBUGGABLE bool URlCharacterMovementComponent::IsWalking() const
{
return IsMovingOnGround();
}<file_sep>// Fill out your copyright notice in the Description page of Project Settings.
#include "AudioManager.h"
#include "Sound/SoundCue.h"
#include "RlGameInstance.h"
#include "Components/AudioComponent.h"
AAudioManager::AAudioManager(const FObjectInitializer& ObjectInitializer)
{
AudioComponent = CreateDefaultSubobject<UAudioComponent>(TEXT("Audio Component"));
AudioComponent->bAutoActivate = false;
AudioComponent->SetupAttachment(RootComponent);
}
void AAudioManager::Init(URlGameInstance* InRlGI)
{
RlGI = InRlGI;
//if (Music)
//{
// AudioComponent->SetSound(Music);
//}
}
void AAudioManager::Play()
{
AudioComponent->Play();
}
void AAudioManager::SetIntro()
{
if (Intro)
{
AudioComponent->SetSound(Intro);
}
}
void AAudioManager::SetMusic()
{
if (Music)
{
AudioComponent->SetSound(Music);
}
}
void AAudioManager::SetWin()
{
if (Win)
{
AudioComponent->SetSound(Win);
}
}
<file_sep>// Fill out your copyright notice in the Description page of Project Settings.
#include "Stairs.h"
#include "Components/BoxComponent.h"
#include "RlCharacter.h"
#include "Paper2D/Classes/PaperSpriteComponent.h"
AStairs::AStairs()
{
TriggerComponent = CreateDefaultSubobject<UBoxComponent>("Collision Component");
TriggerComponent->InitBoxExtent(FVector(16.f));
TriggerComponent->OnComponentBeginOverlap.AddDynamic(this, &AStairs::OnOverlapBegin);
TriggerComponent->OnComponentEndOverlap.AddDynamic(this, &AStairs::OnOverlapEnd);
RootComponent = TriggerComponent;
UPaperSpriteComponent* InRenderComponent = GetRenderComponent();
InRenderComponent->SetMobility(EComponentMobility::Movable);
InRenderComponent->SetRelativeLocation(FVector(0.f, 0.f, 4.f));
InRenderComponent->SetCollisionProfileName(FName("NoCollision"));
InRenderComponent->SetupAttachment(TriggerComponent);
bCanEnter = false;
}
UBoxComponent* AStairs::GetTriggerComponent()
{
return TriggerComponent;
}
void AStairs::OnOverlapBegin(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult)
{
if (Cast<ARlCharacter>(OtherActor))
{
bCanEnter = true;
}
}
void AStairs::OnOverlapEnd(UPrimitiveComponent* OverlappedComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex)
{
if (Cast<ARlCharacter>(OtherActor))
{
bCanEnter = false;
}
}<file_sep>// Fill out your copyright notice in the Description page of Project Settings.
#include "RlGameMode.h"
#include "RlCharacter.h"
#include "RlGameInstance.h"
#include "RlPlayerController.h"
#include "Engine/World.h"
#include "SlateApplication.h"
#include "NavigationConfig.h"
#include "DeviceSelection.h"
#include "LevelManager.h"
#include "RlGameInstance.h"
#include "RlPlayerController.h"
#include "Kismet/GameplayStatics.h"
#include "HearRateModule.h"
#include "WidgetManager.h"
#include "AudioManager.h"
#include "Components/AudioComponent.h"
ARlGameMode::ARlGameMode()
{
// Set default pawn class to our character
DefaultPawnClass = ARlCharacter::StaticClass();
PlayerControllerClass = ARlPlayerController::StaticClass();
Difficulty = 0.5;
bGameStarted = false;
HeartRateModule = NewObject<UHearRateModule>();
HeartRateModule->GameMode = this;
}
void ARlGameMode::BeginPlay()
{
Super::BeginPlay();
FSlateApplication& SlateApplication = FSlateApplication::Get();
FNavigationConfig& NavigationConfig = SlateApplication.GetNavigationConfig().Get();
NavigationConfig.KeyEventRules.Remove(EKeys::Left);
NavigationConfig.KeyEventRules.Remove(EKeys::Right);
NavigationConfig.KeyEventRules.Remove(EKeys::Up);
NavigationConfig.KeyEventRules.Remove(EKeys::Down);
NavigationConfig.KeyEventRules.Add(EKeys::A, EUINavigation::Left);
NavigationConfig.KeyEventRules.Add(EKeys::D, EUINavigation::Right);
NavigationConfig.KeyEventRules.Add(EKeys::W, EUINavigation::Up);
NavigationConfig.KeyEventRules.Add(EKeys::S, EUINavigation::Down);
URlGameInstance* RlGI = Cast<URlGameInstance>(GetWorld()->GetGameInstance());
FRotator SpawnRotation(0.f);
FActorSpawnParameters SpawnInfo;
RlGI->AudioManager = GetWorld()->SpawnActor<AAudioManager>(RlGI->AudioManagerClass, FVector::ZeroVector, SpawnRotation, SpawnInfo);
RlGI->AudioManager->Init(RlGI);
RlGI->AudioManager->SetIntro();
RlGI->AudioManager->Play();
if (RlGI->bUseDevice)
{
UWidgetManager* WM = RlGI->WidgetManager;
if (WM->DeviceSelectionClass)
{
WM->DeviceSelection = CreateWidget<UDeviceSelection>(GetWorld(), WM->DeviceSelectionClass);
WM->DeviceSelection->AddToViewport();
auto PC = UGameplayStatics::GetPlayerController(GetWorld(), 0);
PC->SetInputMode(FInputModeUIOnly());
return;
}
}
else
{
UWidgetManager* WM = RlGI->WidgetManager;
// Swap to skip intro
if (RlGI->bIntro)
{
WM->StartIntro();
}
else
{
if (RlGI->AudioManager)
{
RlGI->AudioManager->SetMusic();
RlGI->AudioManager->Play();
}
ULevelManager* LM = Cast<URlGameInstance>(GetGameInstance())->LevelManager;
LM->SetLevel(ELevelState::Start);
}
}
}<file_sep>// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "Engine/LevelScriptActor.h"
#include "RlLevelScriptActor.generated.h"
/**
*
*/
UCLASS()
class RAGELITE_API ARlLevelScriptActor : public ALevelScriptActor
{
GENERATED_BODY()
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Camera, meta = (AllowPrivateAccess = "true"))
class ACameraActor* MainCamera;
public:
ARlLevelScriptActor();
protected:
virtual void BeginPlay() override;
};
<file_sep>// Fill out your copyright notice in the Description page of Project Settings.
#include "Dart.h"
#include "TimerManager.h"
#include "Engine/World.h"
#include "Projectile.h"
#include "RlGameInstance.h"
#include "LevelManager.h"
#include "Paper2D/Classes/PaperSpriteComponent.h"
ADart::ADart()
{
bEnabled = false;
Delay = 0.f;
Cooldown = 1.f;
Speed = 100.f;
}
void ADart::Enable(float InDelay, float InCooldown, float InSpeed)
{
bEnabled = true;
Delay = InDelay;
Cooldown = InCooldown;
if (InSpeed != 0.f)
{
Speed = InSpeed;
}
if (Delay == 0.f)
{
SpawnDart();
}
else
{
GetWorld()->GetTimerManager().SetTimer(SpawnDartHandle, this, &ADart::SpawnDart, Delay, false);
}
}
void ADart::Disable()
{
bEnabled = false;
GetWorld()->GetTimerManager().ClearTimer(SpawnDartHandle);
}
void ADart::SpawnDart()
{
FRotator SpawnRotation(0.f);
FActorSpawnParameters SpawnInfo;
ULevelManager* LM = Cast<URlGameInstance>(GetWorld()->GetGameInstance())->LevelManager;
AProjectile* Projectile = GetWorld()->SpawnActor<AProjectile>(GetActorLocation() + GetActorUpVector(), GetActorRotation(), SpawnInfo);
Projectile->InitialSpeed = Speed;
UPaperSpriteComponent* InRenderComponent = Projectile->GetRenderComponent();
InRenderComponent->SetSprite(LM->GetDartSprite());
InRenderComponent->SetMaterial(0, LM->Material);
GetWorld()->GetTimerManager().SetTimer(SpawnDartHandle, this, &ADart::SpawnDart, Cooldown, false);
}
#if WITH_EDITOR
void ADart::PostEditChangeProperty(FPropertyChangedEvent& PropertyChangedEvent)
{
Super::PostEditChangeProperty(PropertyChangedEvent);
FName PropertyName = (PropertyChangedEvent.MemberProperty != nullptr) ? PropertyChangedEvent.MemberProperty->GetFName() : NAME_None;
if (PropertyName == GET_MEMBER_NAME_CHECKED(ADart, bEnabled))
{
if (bEnabled)
{
Enable();
}
else
{
Disable();
}
}
}
#endif<file_sep>// Fill out your copyright notice in the Description page of Project Settings.
#include "DeviceSelection.h"
#include "Components/ScrollBox.h"
#include "Blueprint/WidgetTree.h"
#include "Components/Button.h"
#include "Components/TextBlock.h"
#include "Components/CanvasPanel.h"
#include "Components/PanelWidget.h"
#include "Kismet/GameplayStatics.h"
#include "RlCharacter.h"
#include "FocusButton.h"
#include "RlGameInstance.h"
#include "WidgetManager.h"
#include "LevelManager.h"
#include "RlGameInstance.h"
#include "RlGameMode.h"
#include "WidgetManager.h"
DEFINE_LOG_CATEGORY_STATIC(LogStatus, Log, All);
UDeviceSelection::UDeviceSelection(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer)
{
AccumulatedTime = 0;
LastFocusedButton = nullptr;
bPopUp = false;
}
void UDeviceSelection::NativeConstruct()
{
UTextBlock* TextBlock = WidgetTree->ConstructWidget<UTextBlock>(UTextBlock::StaticClass());
TextBlock->Text = FText::FromString("Meh");
UButton* Button = WidgetTree->ConstructWidget<UButton>(UButton::StaticClass());
Button->AddChild(TextBlock);
Devices->AddChild(Button);
UTextBlock* TextBlock2 = WidgetTree->ConstructWidget<UTextBlock>(UTextBlock::StaticClass());
TextBlock2->Text = FText::FromString("Meh2");
UButton* Button2 = WidgetTree->ConstructWidget<UButton>(UButton::StaticClass());
Button2->AddChild(TextBlock2);
//Devices->AddChild(Button2);
InsertChildAt(Devices, 1, Button2);
//DevicesMap.Add(FString("aa:bb:cc"), 16);
//DevicesMap.Add(FString("aa:bb:dd"), 16);
Update();
//ClearDevices();
bTryingToConnect = false;
//Cancel->OnClicked.RemoveDynamic(this, &UDeviceSelection::OnCancel);
Cancel->OnClicked.AddDynamic(this, &UDeviceSelection::OnCancel);
//Yes->OnClicked.RemoveDynamic(this, &UDeviceSelection::OnYes);
Yes->OnClicked.AddDynamic(this, &UDeviceSelection::OnYes);
//No->OnClicked.RemoveDynamic(this, &UDeviceSelection::OnNo);
No->OnClicked.AddDynamic(this, &UDeviceSelection::OnNo);
Super::NativeConstruct();
}
void UDeviceSelection::Update()
{
if (!DevicesMap.Num())
{
if (Devices->GetChildrenCount() == 1)
{
UFocusButton* Button = Cast<UFocusButton>(Devices->GetChildAt(0));
if (Button && !Button->GetIsEnabled())
{
return;
}
}
while (Devices->HasAnyChildren())
{
Devices->RemoveChildAt(0);
}
AddDeviceButton(FString("No nearby devices"));
Cancel->SetIsEnabled(true);
LastFocusedButton = Cancel;
if (!bPopUp)
{
Cancel->SetKeyboardFocus();
}
return;
}
Cancel->SetIsEnabled(false);
if (Devices->HasAnyChildren())
{
UFocusButton* Button = Cast<UFocusButton>(Devices->GetChildAt(0));
if (Button && !Button->GetIsEnabled())
{
Devices->RemoveChildAt(0);
}
}
UFocusButton* FocusedButton = nullptr;
int32 CurrentIndex = 0;
for (auto It = DevicesMap.CreateConstIterator(); It;)
{
auto Device = It.Key();
//if (DevicesArray.IsValidIndex(CurrentArrayIndex))
if (Devices->GetChildrenCount() > CurrentIndex)
{
bool bValidChildren = true;
UFocusButton* Button = Cast<UFocusButton>(Devices->GetChildAt(CurrentIndex));
if (Button && Button->GetChildrenCount() == 1)
{
UTextBlock* TextBlock = Cast<UTextBlock>(Button->GetChildAt(0));
if (TextBlock)
{
int32 Comparison = Device.Compare(TextBlock->Text.ToString());
if (!Comparison)
{
if (Button->HasKeyboardFocus() || (bPopUp && Button == LastFocusedButton))
{
FocusedButton = Button;
}
++It;
++CurrentIndex;
continue;
}
else if (Comparison > 0)
{
AddDeviceButton(Device, CurrentIndex++);
++It;
continue;
}
else
{
if ((Button->HasKeyboardFocus() || (bPopUp && Button == LastFocusedButton)) && CurrentIndex)
{
FocusedButton = Cast<UFocusButton>(Devices->GetChildAt(CurrentIndex - 1));
}
}
}
}
Devices->RemoveChildAt(CurrentIndex);
}
else
{
AddDeviceButton(Device);
++It;
++CurrentIndex;
}
}
while (Devices->GetChildrenCount() > CurrentIndex)
{
Devices->RemoveChildAt(CurrentIndex);
}
// Rebuild UI
auto Children = Devices->GetAllChildren();
while (Devices->HasAnyChildren())
{
Devices->RemoveChildAt(0);
}
for (auto& Child : Children)
{
Devices->AddChild(Child);
}
if (!FocusedButton)
{
FocusedButton = Cast<UFocusButton>(Devices->GetChildAt(0));
}
LastFocusedButton = FocusedButton;
if (!bPopUp)
{
FocusedButton->SetKeyboardFocus();
}
}
void UDeviceSelection::AddDevice(FString Device)
{
if (DevicesMap.Contains(Device))
{
DevicesMap[Device] = InitialLife;
return;
}
DevicesMap.Add(Device, InitialLife);
Update();
}
void UDeviceSelection::DeviceConnectionFailed()
{
Connecting->SetVisibility(ESlateVisibility::Hidden);
Failed->SetVisibility(ESlateVisibility::SelfHitTestInvisible);
ARlCharacter* RlCharacter = Cast<ARlCharacter>(UGameplayStatics::GetPlayerPawn(GetWorld(), 0));
RlCharacter->bConnectionAccepted = false;
GetWorld()->GetTimerManager().SetTimer(FailedHandle, this, &UDeviceSelection::ResetDeviceConnection, 2.f);
}
void UDeviceSelection::ResetDeviceConnection()
{
Failed->SetVisibility(ESlateVisibility::Hidden);
auto PC = UGameplayStatics::GetPlayerController(GetWorld(), 0);
PC->SetInputMode(FInputModeUIOnly());
UGameplayStatics::GetPlayerPawn(GetWorld(), 0)->EnableInput(PC);
}
void UDeviceSelection::NativeTick(const FGeometry& MyGeometry, float InDeltaTime)
{
Super::NativeTick(MyGeometry, InDeltaTime);
AccumulatedTime += InDeltaTime;
if (AccumulatedTime > 1.f)
{
AccumulatedTime = 0;
bool bUpdate = false;
TArray<FString> DevicesToRemove;
for (auto& Device : DevicesMap)
{
if (!--DevicesMap[Device.Key])
{
DevicesToRemove.Add(Device.Key);
bUpdate = true;
}
}
for (auto& Device : DevicesToRemove)
{
DevicesMap.Remove(Device);
}
if (bUpdate)
{
Update();
}
}
}
void UDeviceSelection::AddDeviceButton(FString Device, int32 Index /*= -1*/)
{
//UWidgetManager* WM = Cast<URlGameInstance>(GetWorld()->GetGameInstance())->WidgetManager;
UFocusButton* Button = WidgetTree->ConstructWidget<UFocusButton>(UFocusButton::StaticClass());
UTextBlock* TextBlock = WidgetTree->ConstructWidget<UTextBlock>(UTextBlock::StaticClass());
TextBlock->Text = FText::FromString(Device);
Button->AddChild(TextBlock);
if (!DevicesMap.Num())
{
Button->SetIsEnabled(false);
}
else
{
Button->OnClickDelegate.AddDynamic(this, &UDeviceSelection::OnButtonClicked);
}
if (Index == -1)
{
Devices->AddChild(Button);
}
else
{
InsertChildAt(Devices, Index, Button);
}
}
void UDeviceSelection::ClearDevices()
{
while (Devices->HasAnyChildren())
{
Devices->RemoveChildAt(0);
}
AddDeviceButton(FString("No nearby devices"));
Cancel->SetIsEnabled(true);
}
void UDeviceSelection::OnButtonClicked(UFocusButton* Button)
{
if (Button && Button->GetChildrenCount() == 1)
{
UTextBlock* TextBlock = Cast<UTextBlock>(Button->GetChildAt(0));
if (TextBlock)
{
//ULevelManager* LM = Cast<URlGameInstance>(GetWorld()->GetGameInstance())->LevelManager;
//if (LM->DeviceSelection && !LM->DeviceSelection->bTryingToConnect)
if (!bTryingToConnect)
{
bTryingToConnect = true;
ARlCharacter* RlCharacter = Cast<ARlCharacter>(UGameplayStatics::GetPlayerPawn(GetWorld(), 0));
// TODO Reply with a confirmation of the conection or try again
RlCharacter->Connect(TextBlock->Text.ToString());
Connecting->SetVisibility(ESlateVisibility::SelfHitTestInvisible);
auto PC = UGameplayStatics::GetPlayerController(GetWorld(), 0);
PC->SetInputMode(FInputModeGameOnly());
UGameplayStatics::GetPlayerPawn(GetWorld(), 0)->DisableInput(PC);
}
}
}
}
void UDeviceSelection::InsertChildAt(UPanelWidget* Widget, int32 Index, UWidget* Content)
{
UPanelSlot* NewSlot = Widget->AddChild(Content);
int32 CurrentIndex = Widget->GetChildIndex(Content);
TArray<UPanelSlot*> Slots = Widget->GetSlots();
Slots.RemoveAt(CurrentIndex);
Slots.Insert(Content->Slot, FMath::Clamp(Index, 0, Slots.Num()));
}
void UDeviceSelection::OnCancel()
{
bPopUp = true;
Confirmation->SetVisibility(ESlateVisibility::SelfHitTestInvisible);
No->SetKeyboardFocus();
}
void UDeviceSelection::OnYes()
{
ARlCharacter* RlCharacter = Cast<ARlCharacter>(UGameplayStatics::GetPlayerPawn(GetWorld(), 0));
RlCharacter->CloseConnection();
//auto PC = UGameplayStatics::GetPlayerController(GetWorld(), 0);
//PC->SetInputMode(FInputModeGameOnly());
//UE_LOG(LogStatus, Log, TEXT("Game Started"));
//if (ARlGameMode* GameMode = Cast<ARlGameMode>(GetWorld()->GetAuthGameMode()))
//{
// GameMode->bGameStarted = true;
//}
RemoveFromParent();
UWidgetManager* WM = Cast<URlGameInstance>(GetWorld()->GetGameInstance())->WidgetManager;
WM->StartIntro();
}
void UDeviceSelection::OnNo()
{
bPopUp = false;
Confirmation->SetVisibility(ESlateVisibility::Hidden);
LastFocusedButton->SetKeyboardFocus();
}<file_sep>// Fill out your copyright notice in the Description page of Project Settings.
#include "Hazard.h"
#include "Paper2D/Classes/PaperSpriteComponent.h"
AHazard::AHazard()
{
UPaperSpriteComponent* InRenderComponent = GetRenderComponent();
InRenderComponent->SetMobility(EComponentMobility::Movable);
InRenderComponent->SetCollisionProfileName(FName("NoCollision"));
InRenderComponent->SetGenerateOverlapEvents(false);
TileSize = 32;
}
void AHazard::Move(FVector Location, EHazardLocation HazardLocation)
{
float HazardSize = TileSize / 4;
float HalfHazardSize = HazardSize / 2;
Location.X -= 3 * HalfHazardSize;
Location.Z += 3 * HalfHazardSize;
FRotator Rotation(0.f);
switch (HazardLocation)
{
case EHazardLocation::B1:
case EHazardLocation::T2:
Location.X += HazardSize;
break;
case EHazardLocation::B2:
case EHazardLocation::T1:
Location.X += 2 * HazardSize;
break;
case EHazardLocation::B3:
case EHazardLocation::T0:
case EHazardLocation::R0:
case EHazardLocation::R1:
case EHazardLocation::R2:
case EHazardLocation::R3:
Location.X += 3 * HazardSize;
break;
default:
break;
}
switch (HazardLocation)
{
case EHazardLocation::L1:
case EHazardLocation::R2:
Location.Z -= HazardSize;
break;
case EHazardLocation::L2:
case EHazardLocation::R1:
Location.Z -= 2 * HazardSize;
break;
case EHazardLocation::L3:
case EHazardLocation::R0:
case EHazardLocation::B0:
case EHazardLocation::B1:
case EHazardLocation::B2:
case EHazardLocation::B3:
Location.Z -= 3 * HazardSize;
break;
default:
break;
}
switch (HazardLocation)
{
case EHazardLocation::R0:
case EHazardLocation::R1:
case EHazardLocation::R2:
case EHazardLocation::R3:
Rotation.Pitch = 90.f;
break;
case EHazardLocation::T0:
case EHazardLocation::T1:
case EHazardLocation::T2:
case EHazardLocation::T3:
Rotation.Pitch = 180.f;
break;
case EHazardLocation::L0:
case EHazardLocation::L1:
case EHazardLocation::L2:
case EHazardLocation::L3:
Rotation.Pitch = 270.f;
break;
default:
break;
}
SetActorLocationAndRotation(Location, Rotation);
}
<file_sep>// Fill out your copyright notice in the Description page of Project Settings.
#include "HazardPool.h"
#include "Hazard.h"
#include "Spike.h"
#include "Dart.h"
#include "Stone.h"
#include "Engine/World.h"
#include "RlGameInstance.h"
#include "RlGameMode.h"
#include "LevelManager.h"
#include "Paper2D/Classes/PaperSpriteComponent.h"
#include "Kismet/GameplayStatics.h"
AHazardPool::AHazardPool()
{
InitialSpikes = 30;
InitialDarts = 10;
InitialStones = 10;
}
void AHazardPool::AddSpikes(int32 SpikesNum)
{
FRotator SpawnRotation(0.f);
FActorSpawnParameters SpawnInfo;
ULevelManager* LM = Cast<URlGameInstance>(GetWorld()->GetGameInstance())->LevelManager;
for (int32 i = 0; i < SpikesNum; ++i)
{
ASpike* Spike = GetWorld()->SpawnActor<ASpike>(FVector(10000.f), SpawnRotation, SpawnInfo);
UPaperSpriteComponent* RenderComponent = Spike->GetRenderComponent();
RenderComponent->SetSprite(LM->GetSpikeSprite());
RenderComponent->SetMaterial(0, LM->Material);
Spikes.Add(Spike);
}
}
void AHazardPool::AddSpikesUntil(int32 SpikesNum)
{
AddSpikes(FMath::Max(0, SpikesNum - Spikes.Num()));
}
void AHazardPool::AddDarts(int32 DartsNum)
{
FRotator SpawnRotation(0.f);
FActorSpawnParameters SpawnInfo;
ULevelManager* LM = Cast<URlGameInstance>(GetWorld()->GetGameInstance())->LevelManager;
for (int32 i = 0; i < DartsNum; ++i)
{
ADart* Dart = GetWorld()->SpawnActor<ADart>(FVector(10000.f), SpawnRotation, SpawnInfo);
UPaperSpriteComponent* RenderComponent = Dart->GetRenderComponent();
RenderComponent->SetSprite(LM->DartSprite);
RenderComponent->SetMaterial(0, LM->Material);
Darts.Add(Dart);
}
}
void AHazardPool::AddDartsUntil(int32 DartssNum)
{
AddDarts(FMath::Max(0, DartssNum - Darts.Num()));
}
void AHazardPool::AddStones(int32 StonesNum)
{
FRotator SpawnRotation(0.f);
FActorSpawnParameters SpawnInfo;
ULevelManager* LM = Cast<URlGameInstance>(GetWorld()->GetGameInstance())->LevelManager;
for (int32 i = 0; i < StonesNum; ++i)
{
AStone* Stone = GetWorld()->SpawnActor<AStone>(FVector(10000.f), SpawnRotation, SpawnInfo);
UPaperSpriteComponent* RenderComponent = Stone->GetRenderComponent();
RenderComponent->SetSprite(LM->GetStoneSprite());
RenderComponent->SetMaterial(0, LM->Material);
Stones.Add(Stone);
}
}
void AHazardPool::AddStonesUntil(int32 StonesNum)
{
AddStones(FMath::Max(0, StonesNum - Stones.Num()));
}
void AHazardPool::ResetHazards(TArray<FHazardsData> HazardsData)
{
ARlGameMode* RlGameMode = Cast<ARlGameMode>(UGameplayStatics::GetGameMode(GetWorld()));
float CurrentDifficulty = RlGameMode->Difficulty;
ULevelManager* LM = Cast<URlGameInstance>(GetWorld()->GetGameInstance())->LevelManager;
int32 SpikesInUse = 0;
int32 DartsInUse = 0;
int32 StonesInUse = 0;
for (int32 i = 0; i < HazardsData.Num(); ++i)
{
// If bSpawnsFrom, the hazard will appear from the DifficultyFactor and beyond.
// If !bSpawsFrom, the hazard will appear until the DifficultyFactor.
if ((!HazardsData[i].bSpawnsFrom && HazardsData[i].DifficultyFactor > CurrentDifficulty)
|| (HazardsData[i].bSpawnsFrom && HazardsData[i].DifficultyFactor <= CurrentDifficulty))
{
int32 Count = 0;
for (int32 Number = HazardsData[i].HazardsLocations; Number; Number >>= 1, ++Count)
{
if (Number & 1)
{
if (HazardsData[i].HazardsType == EHazardType::Spikes)
{
Spikes[SpikesInUse++]->Move(LM->GetRelativeLocation(HazardsData[i].Coords, -5.f), static_cast<EHazardLocation>(Count));
}
else if (HazardsData[i].HazardsType == EHazardType::Darts)
{
Darts[DartsInUse]->Move(LM->GetRelativeLocation(HazardsData[i].Coords, -5.f), static_cast<EHazardLocation>(Count));
Darts[DartsInUse]->Enable(HazardsData[i].DartsDelay, HazardsData[i].DartsCooldown, HazardsData[i].DartsSpeed);
++DartsInUse;
}
else if (HazardsData[i].HazardsType == EHazardType::Stones)
{
Stones[StonesInUse++]->Move(LM->GetRelativeLocation(HazardsData[i].Coords, -5.f), static_cast<EHazardLocation>(Count));
}
}
}
}
}
for (int32 i = SpikesInUse; i < Spikes.Num(); ++i)
{
Spikes[i]->SetActorLocation(FVector(10000.f));
}
for (int32 i = DartsInUse; i < Darts.Num(); ++i)
{
Darts[i]->SetActorLocation(FVector(10000.f));
Darts[i]->Disable();
}
for (int32 i = StonesInUse; i < Stones.Num(); ++i)
{
Stones[i]->SetActorLocation(FVector(10000.f));
}
}
void AHazardPool::PostInitializeComponents()
{
Super::PostInitializeComponents();
AddSpikes(InitialSpikes);
AddDarts(InitialDarts);
}
void AHazardPool::EndPlay(const EEndPlayReason::Type EndPlayReason)
{
Super::EndPlay(EndPlayReason);
for (int32 i = 0; i < Spikes.Num(); ++i)
{
Spikes[i]->Destroy();
}
for (int32 i = 0; i < Darts.Num(); ++i)
{
Darts[i]->Destroy();
}
for (int32 i = 0; i < Stones.Num(); ++i)
{
Stones[i]->Destroy();
}
}<file_sep>// Fill out your copyright notice in the Description page of Project Settings.
#include "InputTutorial.h"
#include "Paper2D/Classes/PaperTileMapActor.h"
#include "Paper2D/Classes/PaperTileMapComponent.h"
#include "Paper2D/Classes/PaperTileMap.h"
#include "RlCharacter.h"
#include "Kismet/GameplayStatics.h"
#include "LevelManager.h"
#include "RlGameInstance.h"
UInputTutorial::UInputTutorial()
{
bWasUsingGamepad = false;
bLevelOneRight = false;
bInit = false;
}
UInputTutorial::~UInputTutorial()
{
bWasUsingGamepad = false;
bLevelOneRight = false;
bInit = false;
}
void UInputTutorial::Init(APaperTileMapActor* InTileMapActor, TArray<UPaperTileMap*> InTileMaps, URlGameInstance* InRlGameInstance)
{
TileMapActor = InTileMapActor;
TileMaps = InTileMaps;
RlGameInstance = InRlGameInstance;
GetWorld()->GetTimerManager().ClearTimer(MainAnimationHandle);
GetWorld()->GetTimerManager().ClearTimer(SecondaryAnimationHandle);
bInit = true;
}
UWorld* UInputTutorial::GetWorld() const
{
return RlGameInstance->GetWorld();
}
void UInputTutorial::Update(int32 CurrentLevelIndex, bool bIsUsingGamepad)
{
bool bLastWasUsingGamepad = bWasUsingGamepad;
bWasUsingGamepad = bIsUsingGamepad;
if (bInit)
{
if (TileMaps.IsValidIndex(CurrentLevelIndex - 1))
{
UPaperTileMap* CurrentTileMap = TileMaps[CurrentLevelIndex - 1];
if (CurrentTileMap != LastTileMap || LastLevel != CurrentLevelIndex)
{
LastTileMap = CurrentTileMap;
LastLevel = CurrentLevelIndex;
GetWorld()->GetTimerManager().ClearTimer(MainAnimationHandle);
GetWorld()->GetTimerManager().ClearTimer(SecondaryAnimationHandle);
UPaperTileMapComponent* RenderComponent = TileMapActor->GetRenderComponent();
RenderComponent->SetTileMap(TileMaps[CurrentLevelIndex - 1]);
RenderComponent->SetVisibility(true);
for (int32 i = 0; i < RenderComponent->TileMap->TileLayers.Num(); ++i)
{
HideLayer(i);
}
switch (CurrentLevelIndex)
{
case 1:
LevelOneOne();
break;
case 2:
case 5:
LevelTwoOne();
break;
case 3:
LevelThreeOne();
break;
case 4:
LevelFourOne();
break;
default:
break;
}
}
else if (bLastWasUsingGamepad != bWasUsingGamepad)
{
switch (CurrentLevelIndex)
{
case 1:
ToggleLayers(0, 3);
ToggleLayers(1, 4);
ToggleLayers(2, 5);
ToggleLayers(6, 8);
ToggleLayers(7, 9);
break;
case 2:
case 5:
ToggleLayers(0, 3);
ToggleLayers(1, 4);
ToggleLayers(2, 5);
break;
case 3:
case 4:
ToggleLayers(0, 2);
ToggleLayers(1, 3);
//ToggleLayers(0, 4);
//ToggleLayers(1, 5);
//ToggleLayers(2, 6);
//ToggleLayers(3, 7);
break;
default:
break;
}
}
}
else
{
TileMapActor->GetRenderComponent()->SetVisibility(false);
}
}
}
void UInputTutorial::HideLayer(int32 Layer)
{
SetLayerVisibility(Layer, false);
//SetLayerColor(Layer, FLinearColor(1.f, 1.f, 1.f, 0.f));
}
void UInputTutorial::ShowLayer(int32 Layer)
{
SetLayerVisibility(Layer, true);
//SetLayerColor(Layer, FLinearColor(1.f, 1.f, 1.f, 1.f));
}
void UInputTutorial::SetLayerColor(int32 Layer, FLinearColor Color)
{
if (TileMapActor)
{
UPaperTileMapComponent* RenderComponent = TileMapActor->GetRenderComponent();
if (RenderComponent->TileMap->TileLayers.IsValidIndex(Layer))
{
RenderComponent->TileMap->TileLayers[Layer]->SetLayerColor(Color);
RenderComponent->MarkRenderStateDirty();
}
}
}
void UInputTutorial::SetLayerVisibility(int32 Layer, bool bVisible)
{
if (TileMapActor)
{
UPaperTileMapComponent* RenderComponent = TileMapActor->GetRenderComponent();
if (RenderComponent->TileMap->TileLayers.IsValidIndex(Layer))
{
#if WITH_EDITOR
RenderComponent->TileMap->TileLayers[Layer]->SetShouldRenderInEditor(bVisible);
#else
RenderComponent->TileMap->TileLayers[Layer]->SetLayerColor(FLinearColor(1.f, 1.f, 1.f, bVisible ? 1.f : 0.f));
#endif
RenderComponent->MarkRenderStateDirty();
}
}
}
bool UInputTutorial::GetLayerVisibility(int32 Layer)
{
if (TileMapActor)
{
UPaperTileMapComponent* RenderComponent = TileMapActor->GetRenderComponent();
if (RenderComponent->TileMap->TileLayers.IsValidIndex(Layer))
{
#if WITH_EDITOR
return RenderComponent->TileMap->TileLayers[Layer]->ShouldRenderInEditor();
#else
return RenderComponent->TileMap->TileLayers[Layer]->GetLayerColor().A == 1.f;
#endif
}
}
return false;
}
void UInputTutorial::ToggleLayers(int32 KeyboardLayer, int32 GamepadLayer)
{
if (bWasUsingGamepad)
{
if (GetLayerVisibility(KeyboardLayer))
{
HideLayer(KeyboardLayer);
ShowLayer(GamepadLayer);
}
}
else
{
if (GetLayerVisibility(GamepadLayer))
{
HideLayer(GamepadLayer);
ShowLayer(KeyboardLayer);
}
}
}
void UInputTutorial::ShowLayers(int32 KeyboardLayer, int32 GamepadLayer)
{
if (bWasUsingGamepad)
{
HideLayer(KeyboardLayer);
ShowLayer(GamepadLayer);
}
else
{
HideLayer(GamepadLayer);
ShowLayer(KeyboardLayer);
}
}
void UInputTutorial::ShowOnlyLayers(int32 KeyboardLayer, int32 GamepadLayer)
{
for (int32 i = 0; i < TileMapActor->GetRenderComponent()->TileMap->TileLayers.Num(); ++i)
{
HideLayer(i);
}
ShowLayers(KeyboardLayer, GamepadLayer);
}
void UInputTutorial::LevelOneOne()
{
HideLayer(1);
HideLayer(2);
HideLayer(4);
HideLayer(5);
HideLayer(7);
HideLayer(9);
ShowLayers(0, 3);
ShowLayers(6, 8);
if (bLevelOneRight)
{
GetWorld()->GetTimerManager().SetTimer(MainAnimationHandle, this, &UInputTutorial::LevelOneThree, 0.5f);
}
else
{
GetWorld()->GetTimerManager().SetTimer(MainAnimationHandle, this, &UInputTutorial::LevelOneTwo, 0.5f);
}
GetWorld()->GetTimerManager().SetTimer(SecondaryAnimationHandle, this, &UInputTutorial::LevelOneStairs, 0.5f);
}
void UInputTutorial::LevelOneTwo()
{
bLevelOneRight = true;
HideLayer(0);
HideLayer(3);
ShowLayers(1, 4);
GetWorld()->GetTimerManager().SetTimer(MainAnimationHandle, this, &UInputTutorial::LevelOneOne, 0.5f);
}
void UInputTutorial::LevelOneThree()
{
bLevelOneRight = false;
HideLayer(0);
HideLayer(3);
ShowLayers(2, 5);
GetWorld()->GetTimerManager().SetTimer(MainAnimationHandle, this, &UInputTutorial::LevelOneOne, 0.5f);
}
void UInputTutorial::LevelOneStairs()
{
HideLayer(6);
HideLayer(8);
if (bWasUsingGamepad)
{
ShowLayer(9);
}
else
{
ShowLayer(7);
}
}
void UInputTutorial::LevelTwoOne()
{
ShowOnlyLayers(0, 3);
GetWorld()->GetTimerManager().SetTimer(MainAnimationHandle, this, &UInputTutorial::LevelTwoTwo, 0.25f);
}
void UInputTutorial::LevelTwoTwo()
{
ShowOnlyLayers(1, 4);
GetWorld()->GetTimerManager().SetTimer(MainAnimationHandle, this, &UInputTutorial::LevelTwoThree, 0.25f);
}
void UInputTutorial::LevelTwoThree()
{
ShowOnlyLayers(2, 5);
GetWorld()->GetTimerManager().SetTimer(MainAnimationHandle, this, &UInputTutorial::LevelTwoOne, 1.f);
}
//void UInputTutorial::LevelThreeOne()
//{
// ShowOnlyLayers(0, 2);
//
// GetWorld()->GetTimerManager().SetTimer(MainAnimationHandle, this, &UInputTutorial::LevelThreeTwo, 0.5f);
//}
//
//void UInputTutorial::LevelThreeTwo()
//{
// ShowOnlyLayers(1, 3);
//
// GetWorld()->GetTimerManager().SetTimer(MainAnimationHandle, this, &UInputTutorial::LevelThreeOne, 0.25f);
//}
void UInputTutorial::LevelThreeOne()
{
ShowOnlyLayers(0, 4);
GetWorld()->GetTimerManager().SetTimer(MainAnimationHandle, this, &UInputTutorial::LevelThreeTwo, 0.25f);
}
void UInputTutorial::LevelThreeTwo()
{
ShowOnlyLayers(1, 5);
GetWorld()->GetTimerManager().SetTimer(MainAnimationHandle, this, &UInputTutorial::LevelThreeThree, 0.25f);
}
void UInputTutorial::LevelThreeThree()
{
ShowOnlyLayers(2, 6);
GetWorld()->GetTimerManager().SetTimer(MainAnimationHandle, this, &UInputTutorial::LevelThreeFour, 0.25f);
}
void UInputTutorial::LevelThreeFour()
{
ShowOnlyLayers(3, 7);
GetWorld()->GetTimerManager().SetTimer(MainAnimationHandle, this, &UInputTutorial::LevelThreeOne, 0.25f);
}
void UInputTutorial::LevelFourOne()
{
ShowOnlyLayers(0, 2);
GetWorld()->GetTimerManager().SetTimer(MainAnimationHandle, this, &UInputTutorial::LevelFourTwo, 0.5f);
}
void UInputTutorial::LevelFourTwo()
{
ShowOnlyLayers(1, 3);
GetWorld()->GetTimerManager().SetTimer(MainAnimationHandle, this, &UInputTutorial::LevelFourOne, 1.f);
}<file_sep>// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "PaperSpriteActor.h"
#include "RLTypes.h"
#include "Hazard.generated.h"
/**
* A hazard.
*/
UCLASS()
class RAGELITE_API AHazard : public APaperSpriteActor
{
GENERATED_BODY()
public:
AHazard();
/** Size of the tile containing the hazard. A single tile can have up to 16 hazards. */
UPROPERTY(Category = Sprites, EditAnywhere)
int32 TileSize;
virtual void Move(FVector Location, EHazardLocation HazardLocation);
};
<file_sep>// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "Blueprint/UserWidget.h"
#include "TimerManager.h"
#include "Intro.generated.h"
class UWidgetAnimation;
/**
*
*/
UCLASS()
class RAGELITE_API UIntro : public UUserWidget
{
GENERATED_BODY()
public:
virtual void NativeConstruct() override;
UPROPERTY(meta = (BindWidgetAnim))
UWidgetAnimation* Meh;
UPROPERTY(meta = (BindWidgetAnim))
UWidgetAnimation* Meh2;
void MehStart();
void MehStart2();
private:
FTimerHandle MehHandle;
void MehEnd();
};
<file_sep>// Fill out your copyright notice in the Description page of Project Settings.
#include "RlCharacterMovementComponent.h"
#include "RlCharacter.h"
#include "GameFramework/PhysicsVolume.h"
#include "Components/PrimitiveComponent.h"
#include "Components/BoxComponent.h"
#include "GameFramework/Controller.h"
#include "Kismet/KismetMathLibrary.h"
#include "Kismet/KismetSystemLibrary.h"
#include "Spike.h"
DEFINE_LOG_CATEGORY_STATIC(LogCharacterMovement, Log, All);
// MAGIC NUMBERS
const float MAX_STEP_SIDE_Z = 0.08f; // maximum z value for the normal on the vertical side of steps
const float SWIMBOBSPEED = -80.f;
const float VERTICAL_SLOPE_NORMAL_Z = 0.001f; // Slope is vertical if Abs(Normal.Z) <= this threshold. Accounts for precision problems that sometimes angle normals slightly off horizontal for vertical surface.
const float URlCharacterMovementComponent::MIN_TICK_TIME = 1e-6f;
const float URlCharacterMovementComponent::MIN_FLOOR_DIST = 2.f;
const float URlCharacterMovementComponent::MAX_FLOOR_DIST = 2.4f;
const float URlCharacterMovementComponent::BRAKE_TO_STOP_VELOCITY = 10.f;
const float URlCharacterMovementComponent::SWEEP_EDGE_REJECT_DISTANCE = 0.15f;
void FRlFindFloorResult::SetFromSweep(const FHitResult& InHit, const float InSweepFloorDist, const bool bIsWalkableFloor)
{
bBlockingHit = InHit.IsValidBlockingHit();
bWalkableFloor = bIsWalkableFloor;
bLineTrace = false;
FloorDist = InSweepFloorDist;
LineDist = 0.f;
HitResult = InHit;
}
void FRlFindFloorResult::SetFromLineTrace(const FHitResult& InHit, const float InSweepFloorDist, const float InLineDist, const bool bIsWalkableFloor)
{
// We require a sweep that hit if we are going to use a line result.
check(HitResult.bBlockingHit);
if (HitResult.bBlockingHit && InHit.bBlockingHit)
{
// Override most of the sweep result with the line result, but save some values
FHitResult OldHit(HitResult);
HitResult = InHit;
// Restore some of the old values. We want the new normals and hit actor, however.
HitResult.Time = OldHit.Time;
HitResult.ImpactPoint = OldHit.ImpactPoint;
HitResult.Location = OldHit.Location;
HitResult.TraceStart = OldHit.TraceStart;
HitResult.TraceEnd = OldHit.TraceEnd;
bLineTrace = true;
FloorDist = InSweepFloorDist;
LineDist = InLineDist;
bWalkableFloor = bIsWalkableFloor;
}
}
// meh
URlCharacterMovementComponent::URlCharacterMovementComponent(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
{
bConstrainToPlane = true;
SetPlaneConstraintAxisSetting(EPlaneConstraintAxisSetting::Y);
GravityScale = 1.5f;
JumpZVelocity = 400.f;
JumpOffJumpZFactor = 0.5f;
NormalMaxAcceleration = 150.f;
NormalMaxWalkSpeed = 50.f;
SprintMaxAcceleration = 300.f;
SprintMaxWalkSpeed = 100.f;
bSprintStop = false;
LastSpeed = SprintMaxWalkSpeed;
MaxAcceleration = NormalMaxAcceleration;
BrakingFrictionFactor = 1.f;
BrakingFriction = 4.f;
bUseSeparateBrakingFriction = true;
GroundFriction = 6.f;
MaxWalkSpeed = NormalMaxWalkSpeed;
BrakingDecelerationWalking = 1.f;
bCustomTerminalVelocity = false;
TerminalVelocity = 50.f;
//bConstrainToPlane = true
//SetPlaneConstraintAxisSetting(EPlaneConstraintAxisSetting::Y);
//HorizontalVelocityFactor = 1.f;
MaxSimulationTimeStep = 0.05f;
MaxSimulationIterations = 8;
//MaxDepenetrationWithGeometry = 500.f;
//MaxDepenetrationWithPawn = 100.f;
FallingLateralFriction = 0.f;
BrakingSubStepTime = 1.0f / 33.0f;
BrakingDecelerationFalling = 0.f;
Mass = 10.0f;
bJustTeleported = true;
LastUpdateRotation = FQuat::Identity;
LastUpdateVelocity = FVector::ZeroVector;
PendingImpulseToApply = FVector::ZeroVector;
PendingLaunchVelocity = FVector::ZeroVector;
DefaultLandMovementMode = ERlMovementMode::Walking;
GroundMovementMode = ERlMovementMode::Walking;
bForceNextFloorCheck = true;
bImpartBaseVelocityX = true;
bImpartBaseVelocityY = true;
bImpartBaseVelocityZ = true;
bImpartBaseAngularVelocity = true;
bAlwaysCheckFloor = true;
OldBaseQuat = FQuat::Identity;
OldBaseLocation = FVector::ZeroVector;
}
// meh
void URlCharacterMovementComponent::TickComponent(float DeltaTime, enum ELevelTick TickType, FActorComponentTickFunction *ThisTickFunction)
{
const FVector InputVector = ConsumeInputVector();
if (!HasValidData() || ShouldSkipUpdate(DeltaTime))
{
return;
}
if (CharacterOwner->bDeath)
{
Velocity = FVector::ZeroVector;
return;
}
Super::TickComponent(DeltaTime, TickType, ThisTickFunction);
// Super tick may destroy/invalidate CharacterOwner or UpdatedComponent, so we need to re-check.
if (!HasValidData() || !CharacterOwner->CheckStillInWorld())
{
return;
}
if (CharacterOwner->IsLocallyControlled() || (!CharacterOwner->Controller && bRunPhysicsWithNoController))
{
// We need to check the jump state before adjusting input acceleration, to minimize latency
// and to make sure acceleration respects our potentially new falling state.
CharacterOwner->CheckJumpInput(DeltaTime);
// apply input to acceleration
Acceleration = ScaleInputAcceleration(ConstrainInputAcceleration(InputVector));
AnalogInputModifier = ComputeAnalogInputModifier();
PerformMovement(DeltaTime);
}
//UE_LOG(LogTemp, Warning, TEXT("Velocity: %f"), Velocity.Size());
}
// meh
void URlCharacterMovementComponent::PerformMovement(float DeltaSeconds)
{
const UWorld* MyWorld = GetWorld();
if (!HasValidData() || MyWorld == nullptr)
{
return;
}
// Force floor update if we've moved outside of CharacterMovement since last update.
bForceNextFloorCheck |= (IsMovingOnGround() && UpdatedComponent->GetComponentLocation() != LastUpdateLocation);
FVector OldVelocity;
FVector OldLocation;
// Scoped updates can improve performance of multiple MoveComponent calls.
{
FScopedMovementUpdate ScopedMovementUpdate(UpdatedComponent, bEnableScopedMovementUpdates ? EScopedUpdate::DeferredUpdates : EScopedUpdate::ImmediateUpdates);
OldVelocity = Velocity;
OldLocation = UpdatedComponent->GetComponentLocation();
ApplyAccumulatedForces(DeltaSeconds);
// Character::LaunchCharacter() has been deferred until now.
// Launch means overwrite the current velocity.
HandlePendingLaunch();
ClearAccumulatedForces();
// Clear jump input now, to allow movement events to trigger it for next update.
CharacterOwner->ClearJumpInput(DeltaSeconds);
// change position
StartNewPhysics(DeltaSeconds, 0);
if (!HasValidData())
{
return;
}
} // End scoped movement update
// Here the scoped movement is complete, we can create a delegate and call it here if needed
SaveBaseLocation();
// Update component velocity in case events want to read it
UpdateComponentVelocity();
const FVector NewLocation = UpdatedComponent ? UpdatedComponent->GetComponentLocation() : FVector::ZeroVector;
const FQuat NewRotation = UpdatedComponent ? UpdatedComponent->GetComponentQuat() : FQuat::Identity;
LastUpdateLocation = NewLocation;
LastUpdateRotation = NewRotation;
LastUpdateVelocity = Velocity;
}
// meh
void URlCharacterMovementComponent::StartNewPhysics(float DeltaTime, int32 Iterations)
{
if ((DeltaTime < MIN_TICK_TIME) || (Iterations >= MaxSimulationIterations) || !HasValidData())
{
return;
}
//UE_LOG(LogTemp, Warning, TEXT("%s"), *Velocity.ToString());
const bool bSavedMovementInProgress = bMovementInProgress;
bMovementInProgress = true;
switch (MovementMode)
{
case ERlMovementMode::Walking:
PhysWalking(DeltaTime, Iterations);
break;
case ERlMovementMode::Falling:
PhysFalling(DeltaTime, Iterations);
break;
case ERlMovementMode::WallWalking:
PhysWallWalking(DeltaTime, Iterations);
break;
}
bMovementInProgress = bSavedMovementInProgress;
if (bDeferUpdateMoveComponent)
{
SetUpdatedComponent(DeferredUpdatedMoveComponent);
}
}
// meh
void URlCharacterMovementComponent::PhysWalking(float DeltaTime, int32 Iterations)
{
if (DeltaTime < MIN_TICK_TIME)
{
return;
}
if (!CharacterOwner || (!CharacterOwner->Controller && !bRunPhysicsWithNoController))
{
Acceleration = FVector::ZeroVector;
Velocity = FVector::ZeroVector;
return;
}
if (!UpdatedComponent->IsQueryCollisionEnabled())
{
return;
}
bJustTeleported = false;
bool bCheckedFall = false;
float RemainingTime = DeltaTime;
// Perform the move
while ((RemainingTime >= MIN_TICK_TIME) && (Iterations < MaxSimulationIterations) && CharacterOwner && (CharacterOwner->Controller || bRunPhysicsWithNoController))
{
Iterations++;
bJustTeleported = false;
const float TimeTick = GetSimulationTimeStep(RemainingTime, Iterations);
RemainingTime -= TimeTick;
// Save current values
UPrimitiveComponent * const OldBase = GetMovementBase();
const FVector PreviousBaseLocation = (OldBase != NULL) ? OldBase->GetComponentLocation() : FVector::ZeroVector;
const FVector OldLocation = UpdatedComponent->GetComponentLocation();
const FRlFindFloorResult OldFloor = CurrentFloor;
// Ensure velocity is horizontal.
MaintainHorizontalGroundVelocity();
const FVector OldVelocity = Velocity;
Acceleration.Z = 0.f;
CalcVelocity(TimeTick, GroundFriction, GetMaxBrakingDeceleration());
// Compute move parameters
const FVector MoveVelocity = Velocity;
const FVector Delta = TimeTick * MoveVelocity;
const bool bZeroDelta = Delta.IsNearlyZero();
if (bZeroDelta)
{
RemainingTime = 0.f;
}
else
{
if (CheckSpikes())
{
return;
}
// try to move forward
MoveHorizontal(MoveVelocity, TimeTick);
if (IsFalling())
{
// pawn decided to jump up
const float DesiredDist = Delta.Size();
if (DesiredDist > KINDA_SMALL_NUMBER)
{
const float ActualDist = (UpdatedComponent->GetComponentLocation() - OldLocation).Size2D();
RemainingTime += TimeTick * (1.f - FMath::Min(1.f, ActualDist / DesiredDist));
}
StartNewPhysics(RemainingTime, Iterations);
return;
}
}
// Update floor.
FindFloor(UpdatedComponent->GetComponentLocation(), CurrentFloor, bZeroDelta, NULL);
// Validate the floor check
if (CurrentFloor.IsWalkableFloor())
{
AdjustFloorHeight();
SetBase(CurrentFloor.HitResult.Component.Get(), CurrentFloor.HitResult.BoneName);
}
else if (CurrentFloor.HitResult.bStartPenetrating && RemainingTime <= 0.f)
{
// The floor check failed because it started in penetration
// We do not want to try to move downward because the downward sweep failed, rather we'd like to try to pop out of the floor.
FHitResult Hit(CurrentFloor.HitResult);
Hit.TraceEnd = Hit.TraceStart + FVector(0.f, 0.f, MAX_FLOOR_DIST);
const FVector RequestedAdjustment = GetPenetrationAdjustment(Hit);
ResolvePenetration(RequestedAdjustment, Hit, UpdatedComponent->GetComponentQuat());
bForceNextFloorCheck = true;
}
// See if we need to start falling.
if (!CurrentFloor.IsWalkableFloor() && !CurrentFloor.HitResult.bStartPenetrating)
{
if (!bCheckedFall && CheckFall(OldFloor, CurrentFloor.HitResult, Delta, OldLocation, RemainingTime, TimeTick, Iterations))
{
return;
}
bCheckedFall = true;
}
// If we didn't move at all this iteration then abort (since future iterations will also be stuck).
if (UpdatedComponent->GetComponentLocation() == OldLocation)
{
RemainingTime = 0.f;
break;
}
}
if (IsMovingOnGround())
{
MaintainHorizontalGroundVelocity();
}
}
void URlCharacterMovementComponent::PhysFalling(float DeltaTime, int32 Iterations)
{
if (DeltaTime < MIN_TICK_TIME)
{
return;
}
FVector FallAcceleration(Acceleration.X, Acceleration.Y, 0.f);
float RemainingTime = DeltaTime;
while ((RemainingTime >= MIN_TICK_TIME) && (Iterations < MaxSimulationIterations))
{
Iterations++;
const float TimeTick = GetSimulationTimeStep(RemainingTime, Iterations);
RemainingTime -= TimeTick;
const FVector OldLocation = UpdatedComponent->GetComponentLocation();
const FQuat PawnRotation = UpdatedComponent->GetComponentQuat();
bJustTeleported = false;
FVector OldVelocity = Velocity;
FVector VelocityNoAirControl = Velocity;
// Apply input
const float MaxDecel = GetMaxBrakingDeceleration();
// Compute VelocityNoAirControl
{
// Find velocity *without* acceleration.
TGuardValue<FVector> RestoreAcceleration(Acceleration, FVector::ZeroVector);
TGuardValue<FVector> RestoreVelocity(Velocity, Velocity);
Velocity.Z = 0.f;
CalcVelocity(TimeTick, FallingLateralFriction, MaxDecel);
VelocityNoAirControl = FVector(Velocity.X, Velocity.Y, OldVelocity.Z);
}
// Compute Velocity
{
// Acceleration = FallAcceleration for CalcVelocity(), but we restore it after using it.
TGuardValue<FVector> RestoreAcceleration(Acceleration, FallAcceleration);
Velocity.Z = 0.f;
CalcVelocity(TimeTick, FallingLateralFriction, MaxDecel);
Velocity.Z = OldVelocity.Z;
}
// Apply gravity
const FVector Gravity(0.f, 0.f, GetGravityZ());
float GravityTime = TimeTick;
// If jump is providing force, gravity may be affected.
if (CharacterOwner->JumpForceTimeRemaining > 0.0f)
{
// Update Character state
CharacterOwner->JumpForceTimeRemaining -= FMath::Min(CharacterOwner->JumpForceTimeRemaining, TimeTick);
if (CharacterOwner->JumpForceTimeRemaining <= 0.0f)
{
CharacterOwner->ResetJumpState();
}
}
Velocity += Gravity * GravityTime;
VelocityNoAirControl += Gravity * GravityTime;
// Move
FHitResult Hit(1.f);
FVector Adjusted = 0.5f*(OldVelocity + Velocity) * TimeTick;
SafeMoveUpdatedComponent(Adjusted, PawnRotation, true, Hit);
if (!HasValidData())
{
return;
}
float LastMoveTimeSlice = TimeTick;
float subTimeTickRemaining = TimeTick * (1.f - Hit.Time);
if (Hit.bBlockingHit)
{
if (IsValidLandingSpot(UpdatedComponent->GetComponentLocation(), Hit))
{
RemainingTime += subTimeTickRemaining;
ProcessLanded(Hit, RemainingTime, Iterations);
return;
}
else
{
// Compute impact deflection based on final velocity, not integration step.
// This allows us to compute a new velocity from the deflected vector, and ensures the full gravity effect is included in the slide result.
Adjusted = Velocity * TimeTick;
if (Hit.Normal.Z < 0)
{
CharacterOwner->JumpForceTimeRemaining = 0.f;
CharacterOwner->ResetJumpState();
}
const FVector OldHitNormal = Hit.Normal;
const FVector OldHitImpactNormal = Hit.ImpactNormal;
FVector Delta = ComputeSlideVector(Adjusted, 1.f - Hit.Time, OldHitNormal, Hit);
// Compute velocity after deflection (only gravity component for RootMotion)
if (subTimeTickRemaining > KINDA_SMALL_NUMBER && !bJustTeleported)
{
const FVector NewVelocity = (Delta / subTimeTickRemaining);
Velocity = NewVelocity;
}
if (subTimeTickRemaining > KINDA_SMALL_NUMBER && (Delta | Adjusted) > 0.f)
{
// Move in deflected direction.
SafeMoveUpdatedComponent(Delta, PawnRotation, true, Hit);
if (Hit.bBlockingHit)
{
// hit second wall
LastMoveTimeSlice = subTimeTickRemaining;
subTimeTickRemaining = subTimeTickRemaining * (1.f - Hit.Time);
if (IsValidLandingSpot(UpdatedComponent->GetComponentLocation(), Hit))
{
RemainingTime += subTimeTickRemaining;
ProcessLanded(Hit, RemainingTime, Iterations);
return;
}
const FVector LastMoveNoAirControl = VelocityNoAirControl * LastMoveTimeSlice;
Delta = ComputeSlideVector(LastMoveNoAirControl, 1.f, OldHitNormal, Hit);
FVector PreTwoWallDelta = Delta;
TwoWallAdjust(Delta, Hit, OldHitNormal);
// Compute velocity after deflection (only gravity component for RootMotion)
if (subTimeTickRemaining > KINDA_SMALL_NUMBER && !bJustTeleported)
{
const FVector NewVelocity = (Delta / subTimeTickRemaining);
Velocity = NewVelocity;
}
SafeMoveUpdatedComponent(Delta, PawnRotation, true, Hit);
}
}
}
}
if (Velocity.SizeSquared2D() <= KINDA_SMALL_NUMBER * 10.f)
{
Velocity.X = 0.f;
Velocity.Y = 0.f;
}
}
}
// meh
void URlCharacterMovementComponent::PhysWallWalking(float DeltaTime, int32 Iterations)
{
if (DeltaTime < MIN_TICK_TIME)
{
return;
}
float RemainingTime = DeltaTime;
while ((RemainingTime >= MIN_TICK_TIME) && (Iterations < MaxSimulationIterations))
{
Iterations++;
const float TimeTick = GetSimulationTimeStep(RemainingTime, Iterations);
RemainingTime -= TimeTick;
if (CharacterOwner->WallWalkMaxHoldTime > 0.0f)
{
// Update Character state
CharacterOwner->WallWalkHoldTime += TimeTick;
if (CharacterOwner->WallWalkHoldTime > CharacterOwner->WallWalkMaxHoldTime || !CharacterOwner->bIsPressingJump)
{
CharacterOwner->ResetJumpState();
SetMovementMode(ERlMovementMode::Falling);
StartNewPhysics(DeltaTime, Iterations);
return;
}
}
if (Acceleration.X == 0.f || Velocity.X == 0.f)
{
CharacterOwner->ResetJumpState();
SetMovementMode(ERlMovementMode::Falling);
StartNewPhysics(DeltaTime, Iterations);
return;
}
// Ensure velocity is horizontal.
Velocity.Z = 0.f;
Acceleration.Z = 0.f;
CalcVelocity(TimeTick, GroundFriction, GetMaxBrakingDeceleration());
Velocity.X = FMath::Sign(Velocity.X) * FMath::Min(FMath::Abs(Velocity.X), LastSpeed);
LastSpeed = FMath::Abs(Velocity.X);
// Compute move parameters
const FVector MoveVelocity = Velocity;
const FVector Delta = TimeTick * MoveVelocity;
const bool bZeroDelta = Delta.IsNearlyZero();
if (bZeroDelta)
{
RemainingTime = 0.f;
}
else
{
// try to move forward
MoveHorizontal(MoveVelocity, TimeTick, false);
}
}
}
// meh
void URlCharacterMovementComponent::PostLoad()
{
Super::PostLoad();
CharacterOwner = Cast<ARlCharacter>(PawnOwner);
}
// meh
void URlCharacterMovementComponent::Deactivate()
{
Super::Deactivate();
if (!IsActive())
{
ClearAccumulatedForces();
if (CharacterOwner)
{
CharacterOwner->ResetJumpState();
}
}
}
// meh
void URlCharacterMovementComponent::SetUpdatedComponent(USceneComponent* NewUpdatedComponent)
{
if (NewUpdatedComponent)
{
const ARlCharacter* NewCharacterOwner = Cast<ARlCharacter>(NewUpdatedComponent->GetOwner());
if (NewCharacterOwner == NULL)
{
UE_LOG(LogCharacterMovement, Error, TEXT("%s owned by %s must update a component owned by a RlCharacter"), *GetName(), *GetNameSafe(NewUpdatedComponent->GetOwner()));
return;
}
// check that UpdatedComponent is a Box
if (Cast<UBoxComponent>(NewUpdatedComponent) == NULL)
{
UE_LOG(LogCharacterMovement, Error, TEXT("%s owned by %s must update a box component"), *GetName(), *GetNameSafe(NewUpdatedComponent->GetOwner()));
return;
}
}
if (bMovementInProgress)
{
// failsafe to avoid crashes in CharacterMovement.
bDeferUpdateMoveComponent = true;
DeferredUpdatedMoveComponent = NewUpdatedComponent;
return;
}
bDeferUpdateMoveComponent = false;
DeferredUpdatedMoveComponent = NULL;
USceneComponent* OldUpdatedComponent = UpdatedComponent;
UPrimitiveComponent* OldPrimitive = Cast<UPrimitiveComponent>(UpdatedComponent);
Super::SetUpdatedComponent(NewUpdatedComponent);
CharacterOwner = Cast<ARlCharacter>(PawnOwner);
if (UpdatedComponent != OldUpdatedComponent)
{
ClearAccumulatedForces();
}
if (UpdatedComponent == NULL)
{
StopActiveMovement();
}
const bool bValidUpdatedPrimitive = IsValid(UpdatedPrimitive);
}
// meh
bool URlCharacterMovementComponent::HasValidData() const
{
const bool bIsValid = UpdatedComponent && IsValid(CharacterOwner);
return bIsValid;
}
// meh
FCollisionShape URlCharacterMovementComponent::GetPawnBoxCollisionShape(const EShrinkBoxExtent ShrinkMode, const float CustomShrinkAmount) const
{
FVector Extent = GetPawnBoxExtent(ShrinkMode, CustomShrinkAmount);
return FCollisionShape::MakeBox(Extent);
}
// meh
FVector URlCharacterMovementComponent::GetPawnBoxExtent(const EShrinkBoxExtent ShrinkMode, const float CustomShrinkAmount) const
{
check(CharacterOwner);
FVector BoxExtent = CharacterOwner->GetBoxComponent()->GetScaledBoxExtent();
float XEpsilon = 0.f;
float YEpsilon = 0.f;
float ZEpsilon = 0.f;
switch (ShrinkMode)
{
case SHRINK_None:
return BoxExtent;
case SHRINK_XCustom:
XEpsilon = CustomShrinkAmount;
break;
case SHRINK_YCustom:
YEpsilon = CustomShrinkAmount;
break;
case SHRINK_ZCustom:
ZEpsilon = CustomShrinkAmount;
break;
case SHRINK_AllCustom:
XEpsilon = CustomShrinkAmount;
YEpsilon = CustomShrinkAmount;
ZEpsilon = CustomShrinkAmount;
break;
default:
UE_LOG(LogCharacterMovement, Warning, TEXT("Unknown EShrinkCapsuleExtent in URlCharacterMovementComponent::GetCapsuleExtent"));
break;
}
// Don't shrink to zero extent.
const float MinExtent = KINDA_SMALL_NUMBER * 10.f;
BoxExtent.X = FMath::Max(BoxExtent.X - XEpsilon, MinExtent);
BoxExtent.Y = FMath::Max(BoxExtent.Y - YEpsilon, MinExtent);
BoxExtent.Z = FMath::Max(BoxExtent.Z - ZEpsilon, MinExtent);
return BoxExtent;
}
// meh
bool URlCharacterMovementComponent::DoJump()
{
if (CharacterOwner && CharacterOwner->CanJump())
{
// Don't jump if we can't move up/down.
if (!bConstrainToPlane || FMath::Abs(PlaneConstraintNormal.Z) != 1.f)
{
float HoldJumpKeyFactor = 0.f;
if (CharacterOwner->bWasJumping && CharacterOwner->JumpMaxHoldTime > 0.f)
{
HoldJumpKeyFactor = FMath::Pow(1.f - (CharacterOwner->JumpForceTimeRemaining / CharacterOwner->JumpMaxHoldTime), CharacterOwner->JumpHoldForceFactor);
}
Velocity.Z = FMath::Max(Velocity.Z, JumpZVelocity * (1.f - HoldJumpKeyFactor));
SetMovementMode(ERlMovementMode::Falling);
return true;
}
}
return false;
}
// meh
bool URlCharacterMovementComponent::DoWallWalk()
{
if (CharacterOwner && CharacterOwner->CanWallWalk())
{
// Don't jump if we can't move up/down.
if (!bConstrainToPlane || FMath::Abs(PlaneConstraintNormal.Z) != 1.f)
{
//Velocity.X = FMath::Max(Velocity.Z, JumpZVelocity * (1.f - HoldJumpKeyFactor));
SetMovementMode(ERlMovementMode::WallWalking);
return true;
}
}
return false;
}
// meh
FVector URlCharacterMovementComponent::GetImpartedMovementBaseVelocity() const
{
FVector Result = FVector::ZeroVector;
if (CharacterOwner)
{
UPrimitiveComponent* MovementBase = CharacterOwner->GetMovementBase();
if (RlMovementBaseUtility::IsDynamicBase(MovementBase))
{
FVector BaseVelocity = RlMovementBaseUtility::GetMovementBaseVelocity(MovementBase, CharacterOwner->GetBasedMovement().BoneName);
if (bImpartBaseAngularVelocity)
{
const FVector CharacterBasePosition = (UpdatedComponent->GetComponentLocation() - FVector(0.f, 0.f, CharacterOwner->GetBoxComponent()->GetScaledBoxExtent().Z));
const FVector BaseTangentialVel = RlMovementBaseUtility::GetMovementBaseTangentialVelocity(MovementBase, CharacterOwner->GetBasedMovement().BoneName, CharacterBasePosition);
BaseVelocity += BaseTangentialVel;
}
if (bImpartBaseVelocityX)
{
Result.X = BaseVelocity.X;
}
if (bImpartBaseVelocityY)
{
Result.Y = BaseVelocity.Y;
}
if (bImpartBaseVelocityZ)
{
Result.Z = BaseVelocity.Z;
}
}
}
return Result;
}
// meh
void URlCharacterMovementComponent::Launch(FVector const& LaunchVel)
{
if (IsActive() && HasValidData())
{
PendingLaunchVelocity = LaunchVel;
}
}
// meh
bool URlCharacterMovementComponent::HandlePendingLaunch()
{
if (!PendingLaunchVelocity.IsZero() && HasValidData())
{
Velocity = PendingLaunchVelocity;
SetMovementMode(ERlMovementMode::Falling);
PendingLaunchVelocity = FVector::ZeroVector;
bForceNextFloorCheck = true;
return true;
}
return false;
}
// meh
void URlCharacterMovementComponent::JumpOff(AActor* MovementBaseActor)
{
if (!bPerformingJumpOff)
{
bPerformingJumpOff = true;
if (CharacterOwner)
{
const float MaxSpeed = GetMaxSpeed() * 0.85f;
Velocity += MaxSpeed * GetBestDirectionOffActor(MovementBaseActor);
if (Velocity.Size2D() > MaxSpeed)
{
Velocity = MaxSpeed * Velocity.GetSafeNormal();
}
Velocity.Z = JumpOffJumpZFactor * JumpZVelocity;
SetMovementMode(ERlMovementMode::Falling);
}
bPerformingJumpOff = false;
}
}
// meh
FVector URlCharacterMovementComponent::GetBestDirectionOffActor(AActor* BaseActor) const
{
// By default, just pick a random direction. Derived character classes can choose to do more complex calculations,
// such as finding the shortest distance to move in based on the BaseActor's Bounding Volume.
const float RandAngle = FMath::DegreesToRadians(FMath::SRand() * 360.f);
return FVector(FMath::Cos(RandAngle), FMath::Sin(RandAngle), 0.5f).GetSafeNormal();
}
// meh
void URlCharacterMovementComponent::SetDefaultMovementMode()
{
if (!CharacterOwner || MovementMode != DefaultLandMovementMode)
{
const float SavedVelocityZ = Velocity.Z;
SetMovementMode(DefaultLandMovementMode);
// Avoid 1-frame delay if trying to walk but walking fails at this location.
if (MovementMode == ERlMovementMode::Walking && GetMovementBase() == NULL)
{
Velocity.Z = SavedVelocityZ; // Prevent temporary walking state from zeroing Z velocity.
SetMovementMode(ERlMovementMode::Falling);
}
}
}
// meh
void URlCharacterMovementComponent::SetMovementMode(ERlMovementMode NewMovementMode)
{
// Do nothing if nothing is changing.
if (MovementMode == NewMovementMode)
{
return;
}
const ERlMovementMode PrevMovementMode = MovementMode;
MovementMode = NewMovementMode;
// We allow setting movement mode before we have a component to update, in case this happens at startup.
if (!HasValidData())
{
return;
}
// Handle change in movement mode
OnMovementModeChanged(PrevMovementMode);
}
// meh
void URlCharacterMovementComponent::OnMovementModeChanged(ERlMovementMode PreviousMovementMode)
{
if (!HasValidData())
{
return;
}
// React to changes in the movement mode.
if (MovementMode == ERlMovementMode::Walking)
{
// Walking uses only XY velocity, and must be on a walkable floor, with a Base.
Velocity.Z = 0.f;
// make sure we update our new floor/base on initial entry of the walking physics
FindFloor(UpdatedComponent->GetComponentLocation(), CurrentFloor, false);
AdjustFloorHeight();
SetBaseFromFloor(CurrentFloor);
CharacterOwner->ResetJumpState();
CharacterOwner->bWallWalkToggle = true;
LastSpeed = SprintMaxWalkSpeed;
}
else
{
CurrentFloor.Clear();
if (MovementMode == ERlMovementMode::Falling && PreviousMovementMode == ERlMovementMode::Walking)
{
// Add the valocity of the base;
Velocity += GetImpartedMovementBaseVelocity();
}
SetBase(NULL);
}
if (MovementMode == ERlMovementMode::WallWalking)
{
CharacterOwner->bWallWalkToggle = false;
}
};
// meh
UPrimitiveComponent* URlCharacterMovementComponent::GetMovementBase() const
{
return CharacterOwner ? CharacterOwner->GetMovementBase() : NULL;
}
// meh
void URlCharacterMovementComponent::SetBase(UPrimitiveComponent* NewBase, FName BoneName, bool bNotifyActor)
{
if (CharacterOwner)
{
CharacterOwner->SetBase(NewBase, NewBase ? BoneName : NAME_None, bNotifyActor);
}
}
// meh
void URlCharacterMovementComponent::SetBaseFromFloor(const FRlFindFloorResult& FloorResult)
{
if (FloorResult.IsWalkableFloor())
{
SetBase(FloorResult.HitResult.GetComponent(), FloorResult.HitResult.BoneName);
}
else
{
SetBase(nullptr);
}
}
// meh
void URlCharacterMovementComponent::UpdateBasedRotation(FRotator& FinalRotation, const FRotator& ReducedRotation)
{
AController* Controller = CharacterOwner ? CharacterOwner->Controller : NULL;
float ControllerRoll = 0.f;
if (Controller && !bIgnoreBaseRotation)
{
FRotator const ControllerRot = Controller->GetControlRotation();
ControllerRoll = ControllerRot.Roll;
Controller->SetControlRotation(ControllerRot + ReducedRotation);
}
// Remove roll
FinalRotation.Roll = 0.f;
if (Controller)
{
FinalRotation.Roll = UpdatedComponent->GetComponentRotation().Roll;
FRotator NewRotation = Controller->GetControlRotation();
NewRotation.Roll = ControllerRoll;
Controller->SetControlRotation(NewRotation);
}
}
// meh
void URlCharacterMovementComponent::DisableMovement()
{
//if (CharacterOwner)
//{
// SetMovementMode(MOVE_None);
//}
//else
//{
// MovementMode = MOVE_None;
// CustomMovementMode = 0;
//}
}
// meh
void URlCharacterMovementComponent::SaveBaseLocation()
{
if (!HasValidData())
{
return;
}
const UPrimitiveComponent* MovementBase = CharacterOwner->GetMovementBase();
if (RlMovementBaseUtility::UseRelativeLocation(MovementBase))
{
// Read transforms into OldBaseLocation, OldBaseQuat
RlMovementBaseUtility::GetMovementBaseTransform(MovementBase, CharacterOwner->GetBasedMovement().BoneName, OldBaseLocation, OldBaseQuat);
// Location
const FVector RelativeLocation = UpdatedComponent->GetComponentLocation() - OldBaseLocation;
// Rotation
if (bIgnoreBaseRotation)
{
// Absolute rotation
CharacterOwner->SaveRelativeBasedMovement(RelativeLocation, UpdatedComponent->GetComponentRotation(), false);
}
else
{
// Relative rotation
const FRotator RelativeRotation = (FQuatRotationMatrix(UpdatedComponent->GetComponentQuat()) * FQuatRotationMatrix(OldBaseQuat).GetTransposed()).Rotator();
CharacterOwner->SaveRelativeBasedMovement(RelativeLocation, RelativeRotation, true);
}
}
}
float URlCharacterMovementComponent::GetGravityZ() const
{
return Super::GetGravityZ() * GravityScale;
}
// meh
float URlCharacterMovementComponent::GetMaxSpeed() const
{
//switch (MovementMode)
return MaxWalkSpeed;
}
// meh
float URlCharacterMovementComponent::GetMinAnalogSpeed() const
{
return MinAnalogWalkSpeed;
}
// meh
FVector URlCharacterMovementComponent::GetPenetrationAdjustment(const FHitResult& Hit) const
{
FVector Result = Super::GetPenetrationAdjustment(Hit);
if (CharacterOwner)
{
float MaxDistance = MaxDepenetrationWithGeometry;
const AActor* HitActor = Hit.GetActor();
if (Cast<APawn>(HitActor))
{
MaxDistance = MaxDepenetrationWithPawn;
}
Result = Result.GetClampedToMaxSize(MaxDistance);
}
return Result;
}
// meh
bool URlCharacterMovementComponent::ResolvePenetrationImpl(const FVector& Adjustment, const FHitResult& Hit, const FQuat& NewRotation)
{
// If movement occurs, mark that we teleported, so we don't incorrectly adjust velocity based on a potentially very different movement than our movement direction.
bJustTeleported |= Super::ResolvePenetrationImpl(Adjustment, Hit, NewRotation);
return bJustTeleported;
}
// meh
float URlCharacterMovementComponent::SlideAlongSurface(const FVector& Delta, float Time, const FVector& InNormal, FHitResult& Hit, bool bHandleImpact)
{
if (!Hit.bBlockingHit)
{
return 0.f;
}
FVector Normal(InNormal);
if (IsMovingOnGround())
{
// We don't want to be pushed up an unwalkable surface.
if (Normal.Z > 0.f)
{
if (!IsWalkable(Hit))
{
Normal = Normal.GetSafeNormal2D();
}
}
else if (Normal.Z < -KINDA_SMALL_NUMBER)
{
// Don't push down into the floor when the impact is on the upper portion of the capsule.
if (CurrentFloor.FloorDist < MIN_FLOOR_DIST && CurrentFloor.bBlockingHit)
{
const FVector FloorNormal = CurrentFloor.HitResult.Normal;
const bool bFloorOpposedToMovement = (Delta | FloorNormal) < 0.f && (FloorNormal.Z < 1.f - DELTA);
if (bFloorOpposedToMovement)
{
Normal = FloorNormal;
}
Normal = Normal.GetSafeNormal2D();
}
}
}
return Super::SlideAlongSurface(Delta, Time, Normal, Hit, bHandleImpact);
}
// meh
FVector URlCharacterMovementComponent::ComputeSlideVector(const FVector& Delta, const float Time, const FVector& Normal, const FHitResult& Hit) const
{
FVector Result = Super::ComputeSlideVector(Delta, Time, Normal, Hit);
// prevent boosting up slopes
if (IsFalling())
{
Result = HandleSlopeBoosting(Result, Delta, Time, Normal, Hit);
}
return Result;
}
// meh
FVector URlCharacterMovementComponent::HandleSlopeBoosting(const FVector& SlideResult, const FVector& Delta, const float Time, const FVector& Normal, const FHitResult& Hit) const
{
FVector Result = SlideResult;
if (Result.Z > 0.f)
{
// Don't move any higher than we originally intended.
const float ZLimit = Delta.Z * Time;
if (Result.Z - ZLimit > KINDA_SMALL_NUMBER)
{
if (ZLimit > 0.f)
{
// Rescale the entire vector (not just the Z component) otherwise we change the direction and likely head right back into the impact.
const float UpPercent = ZLimit / Result.Z;
Result *= UpPercent;
}
else
{
// We were heading down but were going to deflect upwards. Just make the deflection horizontal.
Result = FVector::ZeroVector;
}
// Make remaining portion of original result horizontal and parallel to impact normal.
const FVector RemainderXY = (SlideResult - Result) * FVector(1.f, 1.f, 0.f);
const FVector NormalXY = Normal.GetSafeNormal2D();
const FVector Adjust = Super::ComputeSlideVector(RemainderXY, 1.f, NormalXY, Hit);
Result += Adjust;
}
}
return Result;
}
// meh
bool URlCharacterMovementComponent::IsMovingOnGround() const
{
return (MovementMode == ERlMovementMode::Walking) && UpdatedComponent;
}
// meh
bool URlCharacterMovementComponent::IsFalling() const
{
return (MovementMode == ERlMovementMode::Falling) && UpdatedComponent;
}
// meh
bool URlCharacterMovementComponent::IsWallWalking() const
{
return (MovementMode == ERlMovementMode::WallWalking) && UpdatedComponent;
}
// meh
void URlCharacterMovementComponent::CalcVelocity(float DeltaTime, float Friction, float BrakingDeceleration)
{
if (!HasValidData() || DeltaTime < MIN_TICK_TIME)
{
return;
}
Friction = FMath::Max(0.f, Friction);
const float MaxAccel = GetMaxAcceleration();
float MaxSpeed = GetMaxSpeed();
if (bForceMaxAccel)
{
// Force acceleration at full speed.
// In consideration order for direction: Acceleration, then Velocity, then Pawn's rotation.
if (Acceleration.SizeSquared() > SMALL_NUMBER)
{
Acceleration = Acceleration.GetSafeNormal() * MaxAccel;
}
else
{
Acceleration = MaxAccel * (Velocity.SizeSquared() < SMALL_NUMBER ? UpdatedComponent->GetForwardVector() : Velocity.GetSafeNormal());
}
AnalogInputModifier = 1.f;
}
MaxSpeed = FMath::Max(MaxSpeed * AnalogInputModifier, GetMinAnalogSpeed());
// Apply braking or deceleration
const bool bZeroAcceleration = Acceleration.IsZero();
const bool bVelocityOverMax = IsExceedingMaxSpeed(MaxSpeed);
// Only apply braking if there is no acceleration, or we are over our max speed and need to slow down to it.
if (bZeroAcceleration || bVelocityOverMax)
{
const FVector OldVelocity = Velocity;
const float ActualBrakingFriction = (bUseSeparateBrakingFriction ? BrakingFriction : Friction);
ApplyVelocityBraking(DeltaTime, ActualBrakingFriction, BrakingDeceleration);
//// Don't allow braking to lower us below max speed if we started above it.
//if (bVelocityOverMax && Velocity.SizeSquared() < FMath::Square(MaxSpeed) && FVector::DotProduct(Acceleration, OldVelocity) > 0.0f)
//{
// Velocity = OldVelocity.GetSafeNormal() * MaxSpeed;
//}
}
else if (!bZeroAcceleration)
{
// Friction affects our ability to change direction. This is only done for input acceleration, not path following.
const FVector AccelDir = Acceleration.GetSafeNormal();
const float VelSize = Velocity.Size();
Velocity = Velocity - (Velocity - AccelDir * VelSize) * FMath::Min(DeltaTime * Friction, 1.f);
}
// Apply input acceleration
if (!bZeroAcceleration)
{
Velocity += Acceleration * DeltaTime;
// This allows a delay when clamping the velocity
if (bSprintStop && FMath::Abs(Velocity.X) <= MaxSpeed)
{
bSprintStop = false;
}
if (!bSprintStop)
{
Velocity = Velocity.GetClampedToMaxSize(MaxSpeed);
}
}
}
// meh
float URlCharacterMovementComponent::GetMaxJumpHeight() const
{
const float Gravity = GetGravityZ();
if (FMath::Abs(Gravity) > KINDA_SMALL_NUMBER)
{
return FMath::Square(JumpZVelocity) / (-2.f * Gravity);
}
else
{
return 0.f;
}
}
// meh
float URlCharacterMovementComponent::GetMaxJumpHeightWithJumpTime() const
{
const float MaxJumpHeight = GetMaxJumpHeight();
if (CharacterOwner)
{
// When bApplyGravityWhileJumping is true, the actual max height will be lower than this.
// However, it will also be dependent on framerate (and substep iterations) so just return this
// to avoid expensive calculations.
// This can be imagined as the character being displaced to some height, then jumping from that height.
return (CharacterOwner->JumpMaxHoldTime * JumpZVelocity) + MaxJumpHeight;
}
return MaxJumpHeight;
}
// meh
float URlCharacterMovementComponent::GetMaxAcceleration() const
{
return MaxAcceleration;
}
// meh
float URlCharacterMovementComponent::GetMaxBrakingDeceleration() const
{
switch (MovementMode)
{
case ERlMovementMode::Walking:
case ERlMovementMode::WallWalking:
return BrakingDecelerationWalking;
case ERlMovementMode::Falling:
return BrakingDecelerationFalling;
default:
return 0.f;
}
}
// meh
FVector URlCharacterMovementComponent::GetCurrentAcceleration() const
{
return Acceleration;
}
// meh
void URlCharacterMovementComponent::ApplyVelocityBraking(float DeltaTime, float Friction, float BrakingDeceleration)
{
if (Velocity.IsZero() || !HasValidData() || DeltaTime < MIN_TICK_TIME)
{
return;
}
const float FrictionFactor = FMath::Max(0.f, BrakingFrictionFactor);
Friction = FMath::Max(0.f, Friction * FrictionFactor);
BrakingDeceleration = FMath::Max(0.f, BrakingDeceleration);
const bool bZeroFriction = (Friction == 0.f);
const bool bZeroBraking = (BrakingDeceleration == 0.f);
if (bZeroFriction && bZeroBraking)
{
return;
}
const FVector OldVel = Velocity;
// subdivide braking to get reasonably consistent results at lower frame rates
// (important for packet loss situations w/ networking)
float RemainingTime = DeltaTime;
const float MaxTimeStep = FMath::Clamp(BrakingSubStepTime, 1.0f / 75.0f, 1.0f / 20.0f);
// Decelerate to brake to a stop
const FVector RevAccel = (bZeroBraking ? FVector::ZeroVector : (-BrakingDeceleration * Velocity.GetSafeNormal()));
while (RemainingTime >= MIN_TICK_TIME)
{
// Zero friction uses constant deceleration, so no need for iteration.
const float dt = ((RemainingTime > MaxTimeStep && !bZeroFriction) ? FMath::Min(MaxTimeStep, RemainingTime * 0.5f) : RemainingTime);
RemainingTime -= dt;
// apply friction and braking
Velocity = Velocity + ((-Friction) * Velocity + RevAccel) * dt;
// Don't reverse direction
if ((Velocity | OldVel) <= 0.f)
{
Velocity = FVector::ZeroVector;
return;
}
}
// Clamp to zero if nearly zero, or if below min threshold and braking.
const float VSizeSq = Velocity.SizeSquared();
if (VSizeSq <= KINDA_SMALL_NUMBER || (!bZeroBraking && VSizeSq <= FMath::Square(BRAKE_TO_STOP_VELOCITY)))
{
Velocity = FVector::ZeroVector;
}
}
// meh
bool URlCharacterMovementComponent::CheckFall(const FRlFindFloorResult& OldFloor, const FHitResult& Hit, const FVector& Delta, const FVector& OldLocation, float RemainingTime, float TimeTick, int32 Iterations)
{
if (!HasValidData())
{
return false;
}
if (IsMovingOnGround())
{
// If still walking, then fall. If not, assume the user set a different mode they want to keep.
StartFalling(Iterations, RemainingTime, TimeTick, Delta, OldLocation);
}
return true;
}
// meh
void URlCharacterMovementComponent::StartFalling(int32 Iterations, float RemainingTime, float TimeTick, const FVector& Delta, const FVector& subLoc)
{
// start falling
const float DesiredDist = Delta.Size();
const float ActualDist = (UpdatedComponent->GetComponentLocation() - subLoc).Size2D();
RemainingTime = (DesiredDist < KINDA_SMALL_NUMBER)
? 0.f
: RemainingTime + TimeTick * (1.f - FMath::Min(1.f, ActualDist / DesiredDist));
if (IsMovingOnGround())
{
// This is to catch cases where the first frame of PIE is executed, and the
// level is not yet visible. In those cases, the player will fall out of the
// world... So, don't set ERlMovementMode::Falling straight away.
if (!GIsEditor || (GetWorld()->HasBegunPlay() && (GetWorld()->GetTimeSeconds() >= 1.f)))
{
SetMovementMode(ERlMovementMode::Falling); //default behavior if script didn't change physics
}
else
{
// Make sure that the floor check code continues processing during this delay.
bForceNextFloorCheck = true;
}
}
StartNewPhysics(RemainingTime, Iterations);
}
// meh
void URlCharacterMovementComponent::RevertMove(const FVector& OldLocation, UPrimitiveComponent* OldBase, const FVector& PreviousBaseLocation, const FRlFindFloorResult& OldFloor, bool bFailMove)
{
//UE_LOG(LogCharacterMovement, Log, TEXT("RevertMove from %f %f %f to %f %f %f"), CharacterOwner->Location.X, CharacterOwner->Location.Y, CharacterOwner->Location.Z, OldLocation.X, OldLocation.Y, OldLocation.Z);
UpdatedComponent->SetWorldLocation(OldLocation, false, nullptr, ETeleportType::None/*GetTeleportType()*/);
//UE_LOG(LogCharacterMovement, Log, TEXT("Now at %f %f %f"), CharacterOwner->Location.X, CharacterOwner->Location.Y, CharacterOwner->Location.Z);
bJustTeleported = false;
// if our previous base couldn't have moved or changed in any physics-affecting way, restore it
if (IsValid(OldBase) &&
(!RlMovementBaseUtility::IsDynamicBase(OldBase) ||
(OldBase->Mobility == EComponentMobility::Static) ||
(OldBase->GetComponentLocation() == PreviousBaseLocation)
)
)
{
CurrentFloor = OldFloor;
SetBase(OldBase, OldFloor.HitResult.BoneName);
}
else
{
SetBase(NULL);
}
if (bFailMove)
{
// end movement now
Velocity = FVector::ZeroVector;
Acceleration = FVector::ZeroVector;
//UE_LOG(LogCharacterMovement, Log, TEXT("%s FAILMOVE RevertMove"), *CharacterOwner->GetName());
}
}
// meh
void URlCharacterMovementComponent::OnCharacterStuckInGeometry(const FHitResult* Hit)
{
// Don't update velocity based on our (failed) change in position this update since we're stuck.
bJustTeleported = true;
}
// meh
void URlCharacterMovementComponent::MoveHorizontal(const FVector& InVelocity, float DeltaSeconds, bool bAlongFloor)
{
if (bAlongFloor && !CurrentFloor.IsWalkableFloor())
{
return;
}
// Move along the current floor
const FVector Delta = FVector(InVelocity.X, InVelocity.Y, 0.f) * DeltaSeconds;
FHitResult Hit(1.f);
SafeMoveUpdatedComponent(Delta, UpdatedComponent->GetComponentQuat(), true, Hit);
float LastMoveTimeSlice = DeltaSeconds;
if (Hit.bBlockingHit)
{
Velocity.X = 0.f;
}
if (Hit.bStartPenetrating)
{
// Allow this hit to be used as an impact we can deflect off, otherwise we do nothing the rest of the update and appear to hitch.
SlideAlongSurface(Delta, 1.f, Hit.Normal, Hit, true);
if (Hit.bStartPenetrating)
{
OnCharacterStuckInGeometry(&Hit);
}
}
}
// meh
void URlCharacterMovementComponent::MaintainHorizontalGroundVelocity()
{
if (Velocity.Z != 0.f)
{
// Rescale velocity to be horizontal but maintain magnitude of last update.
Velocity = Velocity.GetSafeNormal2D() * Velocity.Size();
}
}
// meh
void URlCharacterMovementComponent::AdjustFloorHeight()
{
// If we have a floor check that hasn't hit anything, don't adjust height.
if (!CurrentFloor.IsWalkableFloor())
{
return;
}
float OldFloorDist = CurrentFloor.FloorDist;
if (CurrentFloor.bLineTrace)
{
if (OldFloorDist < MIN_FLOOR_DIST && CurrentFloor.LineDist >= MIN_FLOOR_DIST)
{
// This would cause us to scale unwalkable walls
UE_LOG(LogCharacterMovement, VeryVerbose, TEXT("Adjust floor height aborting due to line trace with small floor distance (line: %.2f, sweep: %.2f)"), CurrentFloor.LineDist, CurrentFloor.FloorDist);
return;
}
else
{
// Falling back to a line trace means the sweep was unwalkable (or in penetration). Use the line distance for the vertical adjustment.
OldFloorDist = CurrentFloor.LineDist;
}
}
// Move up or down to maintain floor height.
//if (OldFloorDist < MIN_FLOOR_DIST || OldFloorDist > MAX_FLOOR_DIST)
// Move character to the ground
if (!FMath::IsNearlyZero(OldFloorDist) && OldFloorDist != 2.f)
{
FHitResult AdjustHit(1.f);
FVector Location = UpdatedComponent->GetComponentLocation();
// We leave the collision box 2 pixels above the floor in order to avoid stop collisions when walking
Location.Z = (float)UKismetMathLibrary::Round(Location.Z - OldFloorDist) + 2.f;
UpdatedComponent->SetRelativeLocation(Location);
CurrentFloor.FloorDist = 2.f;
//const float AvgFloorDist = (MIN_FLOOR_DIST + MAX_FLOOR_DIST) * 0.5f;
//const float MoveDist = AvgFloorDist - OldFloorDist;
//SafeMoveUpdatedComponent(FVector(0.f, 0.f, MoveDist), UpdatedComponent->GetComponentQuat(), true, AdjustHit);
//UE_LOG(LogCharacterMovement, VeryVerbose, TEXT("Adjust floor height %.3f (Hit = %d)"), MoveDist, AdjustHit.bBlockingHit);
UE_LOG(LogCharacterMovement, VeryVerbose, TEXT("Adjust floor height %.3f"), OldFloorDist);
CurrentFloor.FloorDist = 2.f;
//CurrentFloor.FloorDist = KINDA_SMALL_NUMBER;
//if (!AdjustHit.IsValidBlockingHit())
//{
// CurrentFloor.FloorDist += MoveDist;
//}
//else if (MoveDist > 0.f)
//{
// const float CurrentZ = UpdatedComponent->GetComponentLocation().Z;
// CurrentFloor.FloorDist += CurrentZ - InitialZ;
//}
//else
//{
// checkSlow(MoveDist < 0.f);
// const float CurrentZ = UpdatedComponent->GetComponentLocation().Z;
// CurrentFloor.FloorDist = CurrentZ - AdjustHit.Location.Z;
// if (IsWalkable(AdjustHit))
// {
// CurrentFloor.SetFromSweep(AdjustHit, CurrentFloor.FloorDist, true);
// }
//}
// Don't recalculate velocity based on this height adjustment, if considering vertical adjustments.
// Also avoid it if we moved out of penetration
bJustTeleported |= (OldFloorDist < 0.f);
// If something caused us to adjust our height (especially a depentration) we should ensure another check next frame or we will keep a stale result.
bForceNextFloorCheck = true;
//bForceNextFloorCheck = false;
}
}
// meh
void URlCharacterMovementComponent::StopActiveMovement()
{
Super::StopActiveMovement();
Acceleration = FVector::ZeroVector;
Velocity = FVector::ZeroVector;
}
// meh
void URlCharacterMovementComponent::ProcessLanded(const FHitResult& Hit, float RemainingTime, int32 Iterations)
{
if (IsFalling())
{
SetMovementMode(GroundMovementMode);
}
IPathFollowingAgentInterface* PFAgent = GetPathFollowingAgent();
if (PFAgent)
{
PFAgent->OnLanded();
}
StartNewPhysics(RemainingTime, Iterations);
}
// meh
void URlCharacterMovementComponent::OnTeleported()
{
if (!HasValidData())
{
return;
}
Super::OnTeleported();
bJustTeleported = true;
// Find floor at current location
UpdateFloorFromAdjustment();
// Validate it. We don't want to pop down to walking mode from very high off the ground, but we'd like to keep walking if possible.
UPrimitiveComponent* OldBase = CharacterOwner->GetMovementBase();
UPrimitiveComponent* NewBase = NULL;
if (OldBase && CurrentFloor.IsWalkableFloor() && CurrentFloor.FloorDist <= MAX_FLOOR_DIST && Velocity.Z <= 0.f)
{
// Close enough to land or just keep walking.
NewBase = CurrentFloor.HitResult.Component.Get();
}
else
{
CurrentFloor.Clear();
}
const bool bWasFalling = (MovementMode == ERlMovementMode::Falling);
if (!CurrentFloor.IsWalkableFloor() || (OldBase && !NewBase))
{
if (!bWasFalling)
{
SetMovementMode(ERlMovementMode::Falling);
}
}
else if (NewBase)
{
if (bWasFalling)
{
ProcessLanded(CurrentFloor.HitResult, 0.f, 0);
}
}
SaveBaseLocation();
}
// meh
void URlCharacterMovementComponent::AddImpulse(FVector Impulse, bool bVelocityChange)
{
if (!Impulse.IsZero() && IsActive() && HasValidData())
{
// handle scaling by mass
FVector FinalImpulse = Impulse;
if (!bVelocityChange)
{
if (Mass > SMALL_NUMBER)
{
FinalImpulse = FinalImpulse / Mass;
}
else
{
UE_LOG(LogCharacterMovement, Warning, TEXT("Attempt to apply impulse to zero or negative Mass in CharacterMovement"));
}
}
PendingImpulseToApply += FinalImpulse;
}
}
// meh
void URlCharacterMovementComponent::AddForce(FVector Force)
{
if (!Force.IsZero() && IsActive() && HasValidData())
{
if (Mass > SMALL_NUMBER)
{
PendingForceToApply += Force / Mass;
}
else
{
UE_LOG(LogCharacterMovement, Warning, TEXT("Attempt to apply force to zero or negative Mass in CharacterMovement"));
}
}
}
bool URlCharacterMovementComponent::IsWalkable(const FHitResult& Hit) const
{
if (!Hit.IsValidBlockingHit())
{
// No hit, or starting in penetration
return false;
}
// Never walk up vertical surfaces.
return Hit.ImpactNormal.Z > KINDA_SMALL_NUMBER;
}
bool URlCharacterMovementComponent::IsWithinEdgeTolerance(const FVector& BoxLocation, const FVector& TestImpactPoint, const float CapsuleRadius) const
{
const float DistFromCenterSq = (TestImpactPoint - BoxLocation).SizeSquared2D();
const float ReducedRadiusSq = FMath::Square(FMath::Max(SWEEP_EDGE_REJECT_DISTANCE + KINDA_SMALL_NUMBER, CapsuleRadius - SWEEP_EDGE_REJECT_DISTANCE));
return DistFromCenterSq < ReducedRadiusSq;
}
// meh
void URlCharacterMovementComponent::ComputeFloorDist(const FVector& BoxLocation, float LineDistance, float SweepDistance, FRlFindFloorResult& OutFloorResult, float SweepRadius, const FHitResult* DownwardSweepResult) const
{
OutFloorResult.Clear();
//float PawnRadius = CharacterOwner->GetBoxComponent()->GetScaledBoxExtent().X;
float PawnHalfWidth = CharacterOwner->GetBoxComponent()->GetScaledBoxExtent().X;
float PawnHalfHeight = CharacterOwner->GetBoxComponent()->GetScaledBoxExtent().Z;
//float PawnRadius, PawnHalfHeight;
//CharacterOwner->GetCapsuleComponent()->GetScaledCapsuleSize(PawnRadius, PawnHalfHeight);
bool bSkipSweep = false;
if (DownwardSweepResult != NULL && DownwardSweepResult->IsValidBlockingHit())
{
// Only if the supplied sweep was vertical and downward.
if ((DownwardSweepResult->TraceStart.Z > DownwardSweepResult->TraceEnd.Z) &&
(DownwardSweepResult->TraceStart - DownwardSweepResult->TraceEnd).SizeSquared2D() <= KINDA_SMALL_NUMBER)
{
// Reject hits that are barely on the cusp of the radius of the capsule
//if (IsWithinEdgeTolerance(DownwardSweepResult->Location, DownwardSweepResult->ImpactPoint, PawnRadius))
//{
// // Don't try a redundant sweep, regardless of whether this sweep is usable.
// bSkipSweep = true;
// const bool bIsWalkable = IsWalkable(*DownwardSweepResult);
// const float FloorDist = (BoxLocation.Z - DownwardSweepResult->Location.Z);
// OutFloorResult.SetFromSweep(*DownwardSweepResult, FloorDist, bIsWalkable);
// if (bIsWalkable)
// {
// // Use the supplied downward sweep as the floor hit result.
// return;
// }
//}
}
}
// We require the sweep distance to be >= the line distance, otherwise the HitResult can't be interpreted as the sweep result.
if (SweepDistance < LineDistance)
{
ensure(SweepDistance >= LineDistance);
return;
}
bool bBlockingHit = false;
FCollisionQueryParams QueryParams(SCENE_QUERY_STAT(ComputeFloorDist), false, CharacterOwner);
FCollisionResponseParams ResponseParam;
InitCollisionParams(QueryParams, ResponseParam);
const ECollisionChannel CollisionChannel = UpdatedComponent->GetCollisionObjectType();
// Sweep test
if (!bSkipSweep && SweepDistance > 0.f && SweepRadius > 0.f)
{
// Use a shorter height to avoid sweeps giving weird results if we start on a surface.
// This also allows us to adjust out of penetrations.
//const float ShrinkScale = 0.9f;
//const float ShrinkScaleOverlap = 0.1f;
//float ShrinkHeight = FMath::Abs(PawnHalfHeight - PawnRadius) * (1.f - ShrinkScale);
//float TraceDist = SweepDistance + ShrinkHeight;
//FCollisionShape CapsuleShape = FCollisionShape::MakeCapsule(SweepRadius, PawnHalfHeight - ShrinkHeight);
FHitResult Hit(1.f);
//bBlockingHit = FloorSweepTest(Hit, BoxLocation, BoxLocation + FVector(0.f, 0.f, -TraceDist), CollisionChannel, CapsuleShape, QueryParams, ResponseParam);
bBlockingHit = FloorSweepTest(Hit, BoxLocation, BoxLocation + FVector(0.f, 0.f, -SweepDistance), CollisionChannel, CharacterOwner->GetBoxComponent()->GetCollisionShape(), QueryParams, ResponseParam);
if (bBlockingHit)
{
// Reject hits adjacent to us, we only care about hits on the bottom portion of our capsule.
// Check 2D distance to impact point, reject if within a tolerance from radius.
//if (Hit.bStartPenetrating || !IsWithinEdgeTolerance(BoxLocation, Hit.ImpactPoint, CapsuleShape.Capsule.Radius))
//{
// // Use a capsule with a slightly smaller radius and shorter height to avoid the adjacent object.
// // Capsule must not be nearly zero or the trace will fall back to a line trace from the start point and have the wrong length.
// CapsuleShape.Capsule.Radius = FMath::Max(0.f, CapsuleShape.Capsule.Radius - SWEEP_EDGE_REJECT_DISTANCE - KINDA_SMALL_NUMBER);
// if (!CapsuleShape.IsNearlyZero())
// {
// ShrinkHeight = FMath::Abs(PawnHalfHeight - PawnRadius) * (1.f - ShrinkScaleOverlap);
// TraceDist = SweepDistance + ShrinkHeight;
// CapsuleShape.Capsule.HalfHeight = FMath::Max(FMath::Abs(PawnHalfHeight - ShrinkHeight), CapsuleShape.Capsule.Radius);
// Hit.Reset(1.f, false);
// bBlockingHit = FloorSweepTest(Hit, BoxLocation, BoxLocation + FVector(0.f, 0.f, -TraceDist), CollisionChannel, CapsuleShape, QueryParams, ResponseParam);
// }
//}
// Reduce hit distance by ShrinkHeight because we shrank the capsule for the trace.
// We allow negative distances here, because this allows us to pull out of penetrations.
//const float MaxPenetrationAdjust = FMath::Max(MAX_FLOOR_DIST, PawnRadius);
const float MaxPenetrationAdjust = FMath::Max(MAX_FLOOR_DIST, 2.f * PawnHalfWidth);
//const float SweepResult = FMath::Max(-MaxPenetrationAdjust, Hit.Time * TraceDist - ShrinkHeight);
const float SweepResult = FMath::Max(-MaxPenetrationAdjust, Hit.Time * SweepDistance);
OutFloorResult.SetFromSweep(Hit, SweepResult, false);
if (Hit.IsValidBlockingHit() && IsWalkable(Hit))
{
if (SweepResult <= SweepDistance)
{
// Hit within test distance.
OutFloorResult.bWalkableFloor = true;
return;
}
}
}
}
// Since we require a longer sweep than line trace, we don't want to run the line trace if the sweep missed everything.
// We do however want to try a line trace if the sweep was stuck in penetration.
if (!OutFloorResult.bBlockingHit && !OutFloorResult.HitResult.bStartPenetrating)
{
OutFloorResult.FloorDist = SweepDistance;
return;
}
// Line trace
if (LineDistance > 0.f)
{
//const float ShrinkHeight = PawnHalfHeight;
//const FVector LineTraceStart = BoxLocation;
//const float TraceDist = LineDistance + ShrinkHeight;
//const FVector Down = FVector(0.f, 0.f, -TraceDist);
//QueryParams.TraceTag = SCENE_QUERY_STAT_NAME_ONLY(FloorLineTrace);
//FHitResult Hit(1.f);
//bBlockingHit = GetWorld()->LineTraceSingleByChannel(Hit, LineTraceStart, LineTraceStart + Down, CollisionChannel, QueryParams, ResponseParam);
//if (bBlockingHit)
//{
// if (Hit.Time > 0.f)
// {
// // Reduce hit distance by ShrinkHeight because we started the trace higher than the base.
// // We allow negative distances here, because this allows us to pull out of penetrations.
// const float MaxPenetrationAdjust = FMath::Max(MAX_FLOOR_DIST, PawnRadius);
// const float LineResult = FMath::Max(-MaxPenetrationAdjust, Hit.Time * TraceDist - ShrinkHeight);
// OutFloorResult.bBlockingHit = true;
// if (LineResult <= LineDistance && IsWalkable(Hit))
// {
// OutFloorResult.SetFromLineTrace(Hit, OutFloorResult.FloorDist, LineResult, true);
// return;
// }
// }
//}
}
// No hits were acceptable.
OutFloorResult.bWalkableFloor = false;
OutFloorResult.FloorDist = SweepDistance;
}
// meh
void URlCharacterMovementComponent::FindFloor(const FVector& BoxLocation, FRlFindFloorResult& OutFloorResult, bool bCanUseCachedLocation, const FHitResult* DownwardSweepResult) const
{
// No collision, no floor...
if (!HasValidData() || !UpdatedComponent->IsQueryCollisionEnabled())
{
OutFloorResult.Clear();
return;
}
UE_LOG(LogCharacterMovement, VeryVerbose, TEXT("[Role:%d] FindFloor: %s at location %s"), (int32)CharacterOwner->Role, *GetNameSafe(CharacterOwner), *BoxLocation.ToString());
check(CharacterOwner->GetBoxComponent());
// Increase height check slightly if walking, to prevent floor height adjustment from later invalidating the floor result.
const float HeightCheckAdjust = (IsMovingOnGround() ? MAX_FLOOR_DIST + KINDA_SMALL_NUMBER : -MAX_FLOOR_DIST);
float FloorSweepTraceDist = FMath::Max(MAX_FLOOR_DIST,/* MaxStepHeight +*/ HeightCheckAdjust);
float FloorLineTraceDist = FloorSweepTraceDist;
bool bNeedToValidateFloor = true;
// Sweep floor
if (FloorLineTraceDist > 0.f || FloorSweepTraceDist > 0.f)
{
URlCharacterMovementComponent* MutableThis = const_cast<URlCharacterMovementComponent*>(this);
if (bAlwaysCheckFloor || !bCanUseCachedLocation || bForceNextFloorCheck || bJustTeleported)
{
MutableThis->bForceNextFloorCheck = false;
ComputeFloorDist(BoxLocation, FloorLineTraceDist, FloorSweepTraceDist, OutFloorResult, CharacterOwner->GetBoxComponent()->GetScaledBoxExtent().X/*CharacterOwner->GetCapsuleComponent()->GetScaledCapsuleRadius()*/, DownwardSweepResult);
}
else
{
// Force floor check if base has collision disabled or if it does not block us.
UPrimitiveComponent* MovementBase = CharacterOwner->GetMovementBase();
const AActor* BaseActor = MovementBase ? MovementBase->GetOwner() : NULL;
const ECollisionChannel CollisionChannel = UpdatedComponent->GetCollisionObjectType();
if (MovementBase != NULL)
{
MutableThis->bForceNextFloorCheck = !MovementBase->IsQueryCollisionEnabled()
|| MovementBase->GetCollisionResponseToChannel(CollisionChannel) != ECR_Block
|| RlMovementBaseUtility::IsDynamicBase(MovementBase);
}
const bool IsActorBasePendingKill = BaseActor && BaseActor->IsPendingKill();
if (!bForceNextFloorCheck && !IsActorBasePendingKill && MovementBase)
{
//UE_LOG(LogCharacterMovement, Log, TEXT("%s SKIP check for floor"), *CharacterOwner->GetName());
OutFloorResult = CurrentFloor;
bNeedToValidateFloor = false;
}
else
{
MutableThis->bForceNextFloorCheck = false;
ComputeFloorDist(BoxLocation, FloorLineTraceDist, FloorSweepTraceDist, OutFloorResult, CharacterOwner->GetBoxComponent()->GetScaledBoxExtent().X/*CharacterOwner->GetCapsuleComponent()->GetScaledCapsuleRadius()*/, DownwardSweepResult);
}
}
}
}
// meh
bool URlCharacterMovementComponent::FloorSweepTest(
FHitResult& OutHit,
const FVector& Start,
const FVector& End,
ECollisionChannel TraceChannel,
const struct FCollisionShape& CollisionShape,
const struct FCollisionQueryParams& Params,
const struct FCollisionResponseParams& ResponseParam
) const
{
return GetWorld()->SweepSingleByChannel(OutHit, Start, End, FQuat::Identity, TraceChannel, CollisionShape, Params, ResponseParam);
}
bool URlCharacterMovementComponent::IsValidLandingSpot(const FVector& BoxLocation, const FHitResult& Hit) const
{
if (!Hit.bBlockingHit)
{
return false;
}
// Skip some checks if penetrating. Penetration will be handled by the FindFloor call (using a smaller capsule)
if (!Hit.bStartPenetrating)
{
// Reject unwalkable floor normals.
if (!IsWalkable(Hit))
{
return false;
}
float PawnHalfWidth = CharacterOwner->GetBoxComponent()->GetScaledBoxExtent().X;
float PawnHalfHeight = CharacterOwner->GetBoxComponent()->GetScaledBoxExtent().Z;
//float PawnRadius, PawnHalfHeight;
//CharacterOwner->GetCapsuleComponent()->GetScaledCapsuleSize(PawnRadius, PawnHalfHeight);
// The it is using the same geometry as the main component. Previously a capsule, now a box
//// Reject hits that are above our lower hemisphere (can happen when sliding down a vertical surface).
//const float LowerHemisphereZ = Hit.Location.Z - PawnHalfHeight + PawnRadius;
// Only the hits that are on the lower quarter of the box are processed.
const float LowerHemisphereZ = Hit.Location.Z - PawnHalfHeight / 2.f;
if (Hit.ImpactPoint.Z >= LowerHemisphereZ)
{
return false;
}
// Reject hits that are barely on the cusp of the radius of the capsule
//if (!IsWithinEdgeTolerance(Hit.Location, Hit.ImpactPoint, PawnHalfWidth))
//{
// return false;
//}
}
else
{
// Penetrating
if (Hit.Normal.Z < KINDA_SMALL_NUMBER)
{
// Normal is nearly horizontal or downward, that's a penetration adjustment next to a vertical or overhanging wall. Don't pop to the floor.
return false;
}
}
FRlFindFloorResult FloorResult;
FindFloor(BoxLocation, FloorResult, false, &Hit);
if (!FloorResult.IsWalkableFloor())
{
return false;
}
return true;
}
bool URlCharacterMovementComponent::ShouldCheckForValidLandingSpot(float DeltaTime, const FVector& Delta, const FHitResult& Hit) const
{
// See if we hit an edge of a surface on the lower portion of the capsule.
// In this case the normal will not equal the impact normal, and a downward sweep may find a walkable surface on top of the edge.
if (Hit.Normal.Z > KINDA_SMALL_NUMBER && !Hit.Normal.Equals(Hit.ImpactNormal))
{
const FVector PawnLocation = UpdatedComponent->GetComponentLocation();
if (IsWithinEdgeTolerance(PawnLocation, Hit.ImpactPoint, CharacterOwner->GetBoxComponent()->GetScaledBoxExtent().X/*CharacterOwner->GetCapsuleComponent()->GetScaledCapsuleRadius()*/))
{
return true;
}
}
return false;
}
// meh
FString URlCharacterMovementComponent::GetMovementName() const
{
if (CharacterOwner)
{
if (CharacterOwner->GetRootComponent() && CharacterOwner->GetRootComponent()->IsSimulatingPhysics())
{
return TEXT("Rigid Body");
}
else if (CharacterOwner->IsMatineeControlled())
{
return TEXT("Matinee");
}
}
// Using character movement
switch (MovementMode)
{
case ERlMovementMode::Walking: return TEXT("Walking"); break;
case ERlMovementMode::Falling: return TEXT("Falling"); break;
case ERlMovementMode::WallWalking: return TEXT("Wall Walking"); break;
}
return TEXT("Unknown");
}
// meh
FVector URlCharacterMovementComponent::ConstrainInputAcceleration(const FVector& InputAcceleration) const
{
// walking or falling pawns ignore up/down sliding
if (InputAcceleration.Z != 0.f && (IsMovingOnGround() || IsFalling()))
{
return FVector(InputAcceleration.X, InputAcceleration.Y, 0.f);
}
return InputAcceleration;
}
// meh
FVector URlCharacterMovementComponent::ScaleInputAcceleration(const FVector& InputAcceleration) const
{
return GetMaxAcceleration() * InputAcceleration.GetClampedToMaxSize(1.0f);
}
// meh
void URlCharacterMovementComponent::SprintStart()
{
if (CharacterOwner->bRunEnabled)
{
CharacterOwner->bIsSprinting = true;
MaxAcceleration = SprintMaxAcceleration;
MaxWalkSpeed = SprintMaxWalkSpeed;
}
}
// meh
void URlCharacterMovementComponent::SprintStop()
{
CharacterOwner->bIsSprinting = false;
MaxAcceleration = NormalMaxAcceleration;
MaxWalkSpeed = NormalMaxWalkSpeed;
bSprintStop = true;
}
// meh
bool URlCharacterMovementComponent::CheckSpikes()
{
FVector Start = UpdatedComponent->GetComponentLocation();
Start.X += FMath::Sign(Velocity.X) * 9.f;
Start.Z -= 12.f;
FVector End = Start;
End.X -= FMath::Sign(Velocity.X) * 4.f;
TArray<FHitResult> OutHits;
UKismetSystemLibrary::LineTraceMulti(this, Start, End, UEngineTypes::ConvertToTraceType(ECollisionChannel::ECC_WorldStatic), false, TArray<AActor*>(), EDrawDebugTrace::None, OutHits, true);
if (OutHits.Num() == 1)
{
if (Cast<ASpike>(OutHits[0].Actor))
{
CharacterOwner->Death();
return true;
}
}
return false;
}
// meh
float URlCharacterMovementComponent::ComputeAnalogInputModifier() const
{
const float MaxAccel = GetMaxAcceleration();
if (Acceleration.SizeSquared() > 0.f && MaxAccel > SMALL_NUMBER)
{
return FMath::Clamp(Acceleration.Size() / MaxAccel, 0.f, 1.f);
}
return 0.f;
}
// meh
float URlCharacterMovementComponent::GetAnalogInputModifier() const
{
return AnalogInputModifier;
}
// meh
float URlCharacterMovementComponent::GetSimulationTimeStep(float RemainingTime, int32 Iterations) const
{
if (RemainingTime > MaxSimulationTimeStep)
{
if (Iterations < MaxSimulationIterations)
{
// Subdivide moves to be no longer than MaxSimulationTimeStep seconds
RemainingTime = FMath::Min(MaxSimulationTimeStep, RemainingTime * 0.5f);
}
else
{
// If this is the last iteration, just use all the remaining time. This is usually better than cutting things short, as the simulation won't move far enough otherwise.
}
}
// no less than MIN_TICK_TIME (to avoid potential divide-by-zero during simulation).
return FMath::Max(MIN_TICK_TIME, RemainingTime);
}
// meh
void URlCharacterMovementComponent::UpdateFloorFromAdjustment()
{
if (!HasValidData())
{
return;
}
// If walking, try to update the cached floor so it is current. This is necessary for UpdateBasedMovement() and MoveAlongFloor() to work properly.
// If base is now NULL, presumably we are no longer walking. If we had a valid floor but don't find one now, we'll likely start falling.
if (CharacterOwner->GetMovementBase())
{
FindFloor(UpdatedComponent->GetComponentLocation(), CurrentFloor, false);
}
else
{
CurrentFloor.Clear();
}
}
// meh
void URlCharacterMovementComponent::ApplyAccumulatedForces(float DeltaSeconds)
{
if (PendingImpulseToApply.Z != 0.f || PendingForceToApply.Z != 0.f)
{
// check to see if applied momentum is enough to overcome gravity
if (IsMovingOnGround() && (PendingImpulseToApply.Z + (PendingForceToApply.Z * DeltaSeconds) + (GetGravityZ() * DeltaSeconds) > SMALL_NUMBER))
{
SetMovementMode(ERlMovementMode::Falling);
}
}
Velocity += PendingImpulseToApply + (PendingForceToApply * DeltaSeconds);
// Don't call ClearAccumulatedForces() because it could affect launch velocity
PendingImpulseToApply = FVector::ZeroVector;
PendingForceToApply = FVector::ZeroVector;
}
// meh
void URlCharacterMovementComponent::ClearAccumulatedForces()
{
PendingImpulseToApply = FVector::ZeroVector;
PendingForceToApply = FVector::ZeroVector;
PendingLaunchVelocity = FVector::ZeroVector;
}
// meh
void URlCharacterMovementComponent::AddRadialForce(const FVector& Origin, float Radius, float Strength, enum ERadialImpulseFalloff Falloff)
{
FVector Delta = UpdatedComponent->GetComponentLocation() - Origin;
const float DeltaMagnitude = Delta.Size();
// Do nothing if outside radius
if (DeltaMagnitude > Radius)
{
return;
}
Delta = Delta.GetSafeNormal();
float ForceMagnitude = Strength;
if (Falloff == RIF_Linear && Radius > 0.0f)
{
ForceMagnitude *= (1.0f - (DeltaMagnitude / Radius));
}
AddForce(Delta * ForceMagnitude);
}
// meh
void URlCharacterMovementComponent::AddRadialImpulse(const FVector& Origin, float Radius, float Strength, enum ERadialImpulseFalloff Falloff, bool bVelChange)
{
FVector Delta = UpdatedComponent->GetComponentLocation() - Origin;
const float DeltaMagnitude = Delta.Size();
// Do nothing if outside radius
if (DeltaMagnitude > Radius)
{
return;
}
Delta = Delta.GetSafeNormal();
float ImpulseMagnitude = Strength;
if (Falloff == RIF_Linear && Radius > 0.0f)
{
ImpulseMagnitude *= (1.0f - (DeltaMagnitude / Radius));
}
AddImpulse(Delta * ImpulseMagnitude, bVelChange);
}<file_sep>// Copyright 1998-2018 Epic Games, Inc. All Rights Reserved.
#include "Ragelite.h"
#include "Modules/ModuleManager.h"
IMPLEMENT_PRIMARY_GAME_MODULE( FDefaultGameModuleImpl, Ragelite, "Ragelite" );
<file_sep>// Fill out your copyright notice in the Description page of Project Settings.
#include "RlPlayerController.h"
#include "Kismet/GameplayStatics.h"
#include "RlCharacter.h"
#include "Engine/World.h"
#include "RlGameInstance.h"
#include "LevelManager.h"
void ARlPlayerController::SetupInputComponent()
{
Super::SetupInputComponent();
InputComponent->BindAction("Exit", IE_Pressed, this, &ARlPlayerController::Exit);
}
void ARlPlayerController::FadeInBack(float Seconds)
{
if (PlayerCameraManager)
{
PlayerCameraManager->StartCameraFade(0.f, 1.f, Seconds, FLinearColor::Black, false, true);
}
}
void ARlPlayerController::FadeOutBack(float Seconds)
{
PlayerCameraManager->StartCameraFade(1.f, 0.f, Seconds, FLinearColor::Black, false, false);
}
void ARlPlayerController::Exit()
{
bMouseToggle = !bMouseToggle;
bShowMouseCursor = bMouseToggle;
ConsoleCommand("quit");
}
bool ARlPlayerController::InputKey(FKey Key, EInputEvent EventType, float AmountDepressed, bool bGamepad)
{
bool Result = Super::InputKey(Key, EventType, AmountDepressed, bGamepad);
ARlCharacter* RlCharacter = Cast<ARlCharacter>(UGameplayStatics::GetPlayerPawn(GetWorld(), 0));
if (RlCharacter)
{
//RlCharacter->bIsUsingGamepad = Key.IsGamepadKey();
RlCharacter->bIsUsingGamepad = bGamepad;
ULevelManager* LM = Cast<URlGameInstance>(GetGameInstance())->LevelManager;
if (LM->InputTutorial)
{
LM->UpdateInputTutorial();
}
}
return Result;
}<file_sep>// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "Hazard.h"
#include "Dart.generated.h"
/**
*
*/
UCLASS()
class RAGELITE_API ADart : public AHazard
{
GENERATED_BODY()
public:
ADart();
void Enable(float InDelay = 0.f, float InCoolDown = 1.f, float InSpeed = 100.f);
void Disable();
private:
UPROPERTY(EditAnywhere, Category = Dart, meta = (AllowPrivateAccess = "true"))
bool bEnabled;
FTimerHandle SpawnDartHandle;
void SpawnDart();
float Delay;
float Cooldown;
float Speed;
#if WITH_EDITOR
virtual void PostEditChangeProperty(FPropertyChangedEvent& PropertyChangedEvent) override;
#endif
};
<file_sep>// Fill out your copyright notice in the Description page of Project Settings.
#include "HearRateModule.h"
#include "Kismet/KismetSystemLibrary.h"
#include "Engine/World.h"
#include "RlGameMode.h"
#include "RlGameInstance.h"
DEFINE_LOG_CATEGORY_STATIC(LogHeartRateModule, Log, All);
UHearRateModule::UHearRateModule()
{
//ScopePercentage = 0.2f;
ScopePercentage = 0.15f;
//ScopePercentage = 0.1f;
//DeadZoneFactor = 0.25;
DeadZoneFactor = 0.375;
//DeadZoneFactor = 0.5;
HeartRateMin = -1;
HeartRateMax = 0;
//HeartRateMean = 0.f;
HeartRateMedian = -1 / 2;
bEnabled = false;
bCalibration = false;
}
void UHearRateModule::AddHeartRate(uint8 HeartRate)
{
if (bEnabled && HeartRate)
{
//UKismetSystemLibrary::PrintString(GameMode->GetWorld(), FString::Printf(TEXT("Heart Rate: %i"), HeartRate), true, true, FLinearColor(0.0, 0.66, 1.0), 20.f);
UE_LOG(LogHeartRateModule, Log, TEXT("Heart Rate: %i"), HeartRate);
if (bCalibration)
{
HeartRates.Add(HeartRate);
}
else
{
float Change = HeartRate - HeartRateMedian;
// The difficulty is calculated comparing the current heart rate with the min and max.
// Also the median and scope are adjusted.
// The median can vary at most one per input received
// Si su pulso se estabiliza en un nuevo valor debería considerarse estable luego de 2 minutos (30 mediciones aprox)
HeartRateMedian += Change / 30;
// El focus se reajusta de tal manera que a lo más cambie un 5% por minuto
// Para que esto ocurra al menos la mitad de las mediciones debieron estar al menos a un 100% de distancia de la deadzone
float DeadZone = HeartRateMedian * ScopePercentage * DeadZoneFactor;
float PercentageOutside = FMath::Clamp((FMath::Abs(Change) - DeadZone) / DeadZone, -1.f, 1.f);
ScopePercentage += 0.05f * PercentageOutside / 15;
HeartRateMin = (1.f - ScopePercentage) * HeartRateMedian;
HeartRateMax = (1.f + ScopePercentage) * HeartRateMedian;
if (GameMode)
{
float TargetDifficulty = FMath::Clamp((HeartRateMax - HeartRate) / (HeartRateMax - HeartRateMin), 0.f, 1.f);
URlGameInstance* RlGI = Cast<URlGameInstance>(GameMode->GetGameInstance());
if (RlGI->bDynamicDifficulty)
{
GameMode->Difficulty = TargetDifficulty;
}
//UKismetSystemLibrary::PrintString(GameMode->GetWorld(), FString::Printf(TEXT("HR Module: M %f P %f D %f"), HeartRateMedian, ScopePercentage, GameMode->Difficulty), true, true, FLinearColor(0.0, 0.66, 1.0), 20.f);
UE_LOG(LogHeartRateModule, Log, TEXT("HR Module: M %f P %f D %f"), HeartRateMedian, ScopePercentage, TargetDifficulty);
}
}
}
}
void UHearRateModule::AddHeartRate(FString HearRate)
{
AddHeartRate(FCString::Atoi(*HearRate));
}
void UHearRateModule::StartCalibration()
{
UE_LOG(LogHeartRateModule, Log, TEXT("Calibrarion Started"));
bEnabled = bCalibration = true;
}
void UHearRateModule::EndCalibration()
{
UE_LOG(LogHeartRateModule, Log, TEXT("Calibrarion Ended"));
bCalibration = false;
if (HeartRates.Num())
{
HeartRates.Sort();
HeartRateMedian = HeartRates[(HeartRates.Num() - 1) / 2];
float FirstHalfMean = 0.f;
float SecondHalfMean = 0.f;
for (int32 i = 0; i < HeartRates.Num(); ++i)
{
if (i < HeartRates.Num() / 2)
{
FirstHalfMean += HeartRates[i];
}
else
{
SecondHalfMean += HeartRates[i];
}
}
FirstHalfMean /= HeartRates.Num() / 2;
SecondHalfMean /= HeartRates.Num() - (HeartRates.Num() / 2);
float LowerDeadZone = HeartRateMedian - FirstHalfMean;
float HigherDeadZone = SecondHalfMean - HeartRateMedian;
float DeadZone = HeartRateMedian * ScopePercentage * DeadZoneFactor;
float PercentageFix = (FMath::Max(LowerDeadZone - DeadZone, 0.f) + FMath::Max(HigherDeadZone - DeadZone, 0.f)) / 2.f;
ScopePercentage += PercentageFix / HeartRateMedian;
HeartRateMin = (1.f - ScopePercentage) * HeartRateMedian;
HeartRateMax = (1.f + ScopePercentage) * HeartRateMedian;
UE_LOG(LogHeartRateModule, Log, TEXT("Result: %f -> %f - %f"), ScopePercentage, HeartRateMin, HeartRateMax);
}
}<file_sep>// Fill out your copyright notice in the Description page of Project Settings.
#include "RlGameInstance.h"
#include "LevelManager.h"
#include "WidgetManager.h"
#include "AudioManager.h"
#include "SpriteTextActor.h"
#include "RlSpriteHUD.h"
#include "Misc/CommandLine.h"
DEFINE_LOG_CATEGORY_STATIC(LogStatus, Log, All);
URlGameInstance::URlGameInstance(const FObjectInitializer& ObjectInitializer)
{
bUseDevice = !FParse::Param(FCommandLine::Get(), TEXT("nodevice"));
//bUseDevice = false;
UE_LOG(LogStatus, Log, TEXT("Use device? %i"), bUseDevice);
bDynamicDifficulty = !FParse::Param(FCommandLine::Get(), TEXT("nochange"));
//bDynamicDifficulty = false;
bIntro = !FParse::Param(FCommandLine::Get(), TEXT("nointro"));
//bIntro = false;
UE_LOG(LogStatus, Log, TEXT("Use dynamic difficulty? %i"), bDynamicDifficulty);
}
void URlGameInstance::Init()
{
LevelManager = LevelManagerPtr->GetDefaultObject<ULevelManager>();
LevelManager->Init(this);
WidgetManager = WidgetManagerClass->GetDefaultObject<UWidgetManager>();
WidgetManager->Init(this);
//AudioManager = AudioManagerClass->GetDefaultObject<AAudioManager>();
//FRotator SpawnRotation(0.f);
//FActorSpawnParameters SpawnInfo;
//AudioManager = GetWorld()->SpawnActor<AAudioManager>(AudioManagerClass, FVector::ZeroVector, SpawnRotation, SpawnInfo);
//AudioManager->Init(this);
}
void URlGameInstance::Shutdown()
{
OnShutdown.ExecuteIfBound();
}
<file_sep>// Fill out your copyright notice in the Description page of Project Settings.
// This file has utf-8 enconding
#include "RlCharacter.h"
#include "RlCharacterMovementComponent.h"
#include "PaperFlipbookComponent.h"
#include "PaperFlipbook.h"
#include "Components/BoxComponent.h"
#include "Components/ArrowComponent.h"
#include "Components/InputComponent.h"
#include "Engine/CollisionProfile.h"
#include "DisplayDebugHelpers.h"
#include "Engine/Canvas.h"
#include "GameFramework/DamageType.h"
#include "RlGameInstance.h"
#include "LevelManager.h"
#include "GameFramework/PlayerController.h"
#include "TimerManager.h"
#include "RlPlayerController.h"
#include "RlSpriteHUD.h"
#include "Kismet/GameplayStatics.h"
#include "Stairs.h"
#include "Particles/ParticleSystemComponent.h"
#include "Particles/ParticleEmitter.h"
#include "ConstructorHelpers.h"
#include "DeviceSelection.h"
#include "RlGameMode.h"
#include "HearRateModule.h"
#include "WidgetManager.h"
#include "Runtime/Networking/Public/Common/TcpSocketBuilder.h"
#include "Runtime/Networking/Public/Common/TcpListener.h"
#include "Runtime/Networking/Public/Interfaces/IPv4/IPv4Endpoint.h"
#include "Runtime/Networking/Public/Interfaces/IPv4/IPv4Address.h"
#include <string>
#include <sstream>
DEFINE_LOG_CATEGORY_STATIC(LogCharacter, Log, All);
DEFINE_LOG_CATEGORY_STATIC(LogAvatar, Log, All);
DEFINE_LOG_CATEGORY_STATIC(LogHeartRate, Log, All);
DEFINE_LOG_CATEGORY_STATIC(LogDevice, Log, All);
DEFINE_LOG_CATEGORY_STATIC(LogStatus, Log, All);
FName ARlCharacter::SpriteComponentName(TEXT("Sprite0"));
FName ARlCharacter::RlCharacterMovementComponentName(TEXT("RlCharMoveComp"));
FName ARlCharacter::BoxComponentName(TEXT("CollisionBox"));
ARlCharacter::ARlCharacter(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer)
{
//PrimaryActorTick.bCanEverTick = true;
// Structure to hold one-time initialization
struct FConstructorStatics
{
FName ID_Characters;
FText NAME_Characters;
FConstructorStatics()
: ID_Characters(TEXT("Characters"))
, NAME_Characters(NSLOCTEXT("SpriteCategory", "Characters", "Characters"))
{}
};
static FConstructorStatics ConstructorStatics;
// Character rotation only changes in Yaw, to prevent the capsule from changing orientation.
// Ask the Controller for the full rotation if desired (ie for aiming).
bUseControllerRotationPitch = false;
bUseControllerRotationRoll = false;
bUseControllerRotationYaw = true;
BoxComponent = CreateDefaultSubobject<UBoxComponent>(ARlCharacter::BoxComponentName);
//BoxComponent->InitBoxExtent(FVector(16.f));
BoxComponent->InitBoxExtent(FVector(9.f, 8.f, 10.f));
BoxComponent->SetCollisionProfileName(UCollisionProfile::Pawn_ProfileName);
BoxComponent->CanCharacterStepUpOn = ECB_No;
BoxComponent->SetShouldUpdatePhysicsVolume(true);
//BoxComponent->bCheckAsyncSceneOnMove = false;
BoxComponent->SetCanEverAffectNavigation(false);
BoxComponent->bDynamicObstacle = true;
RootComponent = BoxComponent;
JumpMaxHoldTime = 0.2f;
JumpHoldForceFactor = 7.f;
JumpMaxCount = 1;
JumpCurrentCount = 0;
bWasJumping = false;
WallWalkHoldTime = 0.f;
WallWalkMaxHoldTime = 1.f;
//AnimRootMotionTranslationScale = 1.0f;
AutoPossessPlayer = EAutoReceiveInput::Player0;
#if WITH_EDITORONLY_DATA
ArrowComponent = CreateEditorOnlyDefaultSubobject<UArrowComponent>(TEXT("Arrow"));
if (ArrowComponent)
{
ArrowComponent->ArrowColor = FColor(150, 200, 255);
ArrowComponent->bTreatAsASprite = true;
ArrowComponent->SpriteInfo.Category = ConstructorStatics.ID_Characters;
ArrowComponent->SpriteInfo.DisplayName = ConstructorStatics.NAME_Characters;
ArrowComponent->SetupAttachment(BoxComponent);
ArrowComponent->bIsScreenSizeScaled = true;
}
#endif // WITH_EDITORONLY_DATA
RlCharacterMovement = CreateDefaultSubobject<URlCharacterMovementComponent>(ARlCharacter::RlCharacterMovementComponentName);
if (RlCharacterMovement)
{
RlCharacterMovement->UpdatedComponent = RootComponent;
}
Sprite = CreateOptionalDefaultSubobject<UPaperFlipbookComponent>(ARlCharacter::SpriteComponentName);
if (Sprite)
{
Sprite->AlwaysLoadOnClient = true;
Sprite->AlwaysLoadOnServer = true;
Sprite->bOwnerNoSee = false;
Sprite->bAffectDynamicIndirectLighting = true;
Sprite->PrimaryComponentTick.TickGroup = TG_PrePhysics;
Sprite->SetupAttachment(GetBoxComponent());
static FName CollisionProfileName(TEXT("NoCollision"));
Sprite->SetCollisionProfileName(CollisionProfileName);
Sprite->SetGenerateOverlapEvents(false);
Sprite->SetRelativeLocation(FVector(0.f, 0.f, 3.f));
}
DustComponent = CreateDefaultSubobject<UParticleSystemComponent>(FName("Dust"));
DustComponent->SetRelativeLocation(FVector(0.f, 0.f, -12.f));
DustComponent->SetAutoActivate(false);
static ConstructorHelpers::FObjectFinder<UParticleSystem> DustRightRef(TEXT("/Game/Particles/P_DustRight"));
static ConstructorHelpers::FObjectFinder<UParticleSystem> DustLeftRef(TEXT("/Game/Particles/P_DustLeft"));
if (DustRightRef.Object)
{
DustRight = DustRightRef.Object;
}
if (DustLeftRef.Object)
{
DustLeft = DustLeftRef.Object;
}
BaseRotationOffset = FQuat::Identity;
// Animation
bDeath = false;
bInvincible = false;
WalkSpeed = RlCharacterMovement->NormalMaxWalkSpeed / 2.f;
bIsLastDirectionRight = true;
PreviousVelocityX = 0.f;
bIsChangingDirection = false;
// Enable features
bRunEnabled = true;
bJumpEnabled = true;
bLongJumpEnabled = true;
bWallWalkEnabled = true;
bIsSprinting = false;
bIsUsingGamepad = false;
bDust = false;
bDeviceConnected = false;
bConnectionAccepted = false;
}
// meh
void ARlCharacter::PostInitializeComponents()
{
Super::PostInitializeComponents();
// Animation
auto IdleLambda = [](ARlCharacter* This) -> UPaperFlipbook* { return This->bIsLastDirectionRight ? This->IdleRightAnimation : This->IdleLeftAnimation; };
auto ToIdleLambda = [](ARlCharacter* This) -> UPaperFlipbook* { return This->bIsLastDirectionRight ? This->ToIdleRightAnimation : This->ToIdleLeftAnimation; };
auto RunningLambda = [](ARlCharacter* This) -> UPaperFlipbook*
{
if (This->RlCharacterMovement->IsWallWalking())
{
return This->bIsLastDirectionRight ? This->WallWalkRightAnimation : This->WallWalkLeftAnimation;
}
else
{
return This->bIsLastDirectionRight ? This->RunningRightAnimation : This->RunningLeftAnimation;
}
};
// Jump
auto JumpingLambda = [](ARlCharacter* This) -> UPaperFlipbook* { return This->bIsLastDirectionRight ? This->JumpRightAnimation : This->JumpLeftAnimation; };
FRlAnimation IA(IdleLambda, true, false);
FRlAnimation TIA(ToIdleLambda, false, false, true);
FRlAnimation TIRA(ToIdleLambda, false, true, true);
FRlAnimation RA(RunningLambda, true, false);
FRlAnimation TJA(JumpingLambda, false, false, true, 0, 5);
FRlAnimation JA(JumpingLambda, true, false, false, 6, 6);
FRlAnimation TFA(JumpingLambda, false, false, false, 7, 8);
FRlAnimation FA(JumpingLambda, true, false, false, 9, 9);
FRlAnimation LA(JumpingLambda, false, false, false, 10, 11);
// Reached Start or End with bLoop false
auto AnimationStopped = [](ARlCharacter* This) -> bool { return !This->Sprite->IsPlaying(); };
auto JumpStart = [](ARlCharacter* This) -> bool { return This->bStoredJump; };
auto FallStart = [](ARlCharacter* This) -> bool { return This->RlCharacterMovement->Velocity.Z < 0.f; };
IA.Transitions.Add(FRlTransition(FallStart, ERlAnimationState::ToFalling));
IA.Transitions.Add(FRlTransition(JumpStart, ERlAnimationState::ToJumping));
IA.Transitions.Add(FRlTransition([](ARlCharacter* This) -> bool
{
return This->RlCharacterMovement->GetCurrentAcceleration().X != 0.f;
}, ERlAnimationState::ToIdleR));
TIA.Transitions.Add(FRlTransition(FallStart, ERlAnimationState::ToFalling));
TIA.Transitions.Add(FRlTransition(JumpStart, ERlAnimationState::ToJumping));
TIA.Transitions.Add(FRlTransition(AnimationStopped, ERlAnimationState::Idle));
TIA.Transitions.Add(FRlTransition([](ARlCharacter* This) -> bool
{
return FMath::Abs(This->RlCharacterMovement->Velocity.X) > This->WalkSpeed && This->RlCharacterMovement->GetCurrentAcceleration().X != 0.f;
}, ERlAnimationState::ToIdleR));
TIRA.Transitions.Add(FRlTransition(FallStart, ERlAnimationState::ToFalling));
TIRA.Transitions.Add(FRlTransition(JumpStart, ERlAnimationState::ToJumping));
TIRA.Transitions.Add(FRlTransition(AnimationStopped, ERlAnimationState::Running));
TIRA.Transitions.Add(FRlTransition([](ARlCharacter* This) -> bool
{
return FMath::Abs(This->RlCharacterMovement->Velocity.X) < This->WalkSpeed && This->RlCharacterMovement->GetCurrentAcceleration().X == 0.f;
}, ERlAnimationState::ToIdle));
RA.Transitions.Add(FRlTransition(FallStart, ERlAnimationState::ToFalling));
RA.Transitions.Add(FRlTransition(JumpStart, ERlAnimationState::ToJumping));
RA.Transitions.Add(FRlTransition([](ARlCharacter* This) -> bool
{
return !This->RlCharacterMovement->IsWallWalking() && This->RlCharacterMovement->GetCurrentAcceleration().X == 0.f && !This->bIsChangingDirection && FMath::Abs(This->RlCharacterMovement->Velocity.X) < This->WalkSpeed;
}, ERlAnimationState::ToIdle));
// Jumping
TJA.Transitions.Add(FRlTransition(AnimationStopped, ERlAnimationState::Jumping));
JA.Transitions.Add(FRlTransition([](ARlCharacter* This) -> bool
{
return This->RlCharacterMovement->Velocity.Z <= 0.f;
}, ERlAnimationState::ToFalling));
TFA.Transitions.Add(FRlTransition(AnimationStopped, ERlAnimationState::Falling));
FA.Transitions.Add(FRlTransition([](ARlCharacter* This) -> bool
{
return This->RlCharacterMovement->Velocity.Z == 0.f;
}, ERlAnimationState::Landing));
LA.Transitions.Add(FRlTransition(AnimationStopped, ERlAnimationState::Running));
AnimationLibrary.Add(ERlAnimationState::Idle, IA);
AnimationLibrary.Add(ERlAnimationState::ToIdle, TIA);
AnimationLibrary.Add(ERlAnimationState::ToIdleR, TIRA);
AnimationLibrary.Add(ERlAnimationState::Running, RA);
AnimationLibrary.Add(ERlAnimationState::ToJumping, TJA);
AnimationLibrary.Add(ERlAnimationState::Jumping, JA);
AnimationLibrary.Add(ERlAnimationState::ToFalling, TFA);
AnimationLibrary.Add(ERlAnimationState::Falling, FA);
AnimationLibrary.Add(ERlAnimationState::Landing, LA);
SetCurrentState(ERlAnimationState::Idle);
if (!IsPendingKill())
{
if (Sprite)
{
// force animation tick after movement component updates
if (Sprite->PrimaryComponentTick.bCanEverTick && RlCharacterMovement)
{
Sprite->PrimaryComponentTick.AddPrerequisite(RlCharacterMovement, RlCharacterMovement->PrimaryComponentTick);
}
}
if (Controller == nullptr)
{
if (RlCharacterMovement && RlCharacterMovement->bRunPhysicsWithNoController)
{
RlCharacterMovement->SetDefaultMovementMode();
}
}
}
}
// meh
void ARlCharacter::BeginPlay()
{
Super::BeginPlay();
URlGameInstance* RlGI = Cast<URlGameInstance>(GetGameInstance());
if (RlGI->bUseDevice)
{
//UKismetSystemLibrary::PrintString(GetWorld(), FString("Start Server"));
UE_LOG(LogStatus, Log, TEXT("Start Server"));
FIPv4Endpoint IPv4Endpoint(FIPv4Address(127, 0, 0, 1), 1242);
TcpListener = new FTcpListener(IPv4Endpoint);
TcpListener->OnConnectionAccepted().BindUObject(this, &ARlCharacter::OnConnection);
// This will start the client of the band, so HRM must be running. Move to a separated method later.
AdvertisementWatcher(true);
//UGameplayStatics::GetPlayerController(0);
}
}
void ARlCharacter::EndPlay(const EEndPlayReason::Type EndPlayReason)
{
Super::EndPlay(EndPlayReason);
URlGameInstance* RlGI = Cast<URlGameInstance>(GetGameInstance());
if (RlGI->bUseDevice)
{
HearRate(false);
if (!bDeviceConnected)
{
AdvertisementWatcher(false);
}
}
//UKismetSystemLibrary::PrintString(GetWorld(), FString("Stop"));
//UE_LOG(LogStatus, Log, TEXT("Stop"));
CloseConnection();
UKismetSystemLibrary::PrintString(GetWorld(), FString("Stop Success"));
UE_LOG(LogTemp, Warning, TEXT("Stop Success"));
}
void ARlCharacter::CloseConnection()
{
if (TcpListener)
{
TcpListener->Stop();
delete TcpListener;
TcpListener = nullptr;
}
if (ConnectionSocket)
{
ConnectionSocket->Close();
ConnectionSocket = nullptr;
}
}
UPawnMovementComponent* ARlCharacter::GetMovementComponent() const
{
return RlCharacterMovement;
}
// meh
float ARlCharacter::GetDefaultHalfHeight() const
{
UBoxComponent* DefaultBox = GetClass()->GetDefaultObject<ARlCharacter>()->BoxComponent;
if (DefaultBox)
{
return DefaultBox->GetScaledBoxExtent().Z / 2.f;
}
else
{
return Super::GetDefaultHalfHeight();
}
}
// meh
void ARlCharacter::Jump(FKey Key)
{
//bIsUsingGamepad = Key.IsGamepadKey();
//Cast<URlGameInstance>(GetGameInstance())->LevelManager->UpdateInputTutorial();
if (!IsMoveInputIgnored() && bJumpEnabled)
{
bIsPressingJump = true;
if (!bStoredJump && !bWantJump && !bWantWallWalk && RlCharacterMovement->Velocity.Z == 0.f)
{
bStoredJump = true;
}
if (!bStoredJump && !bWantJump)
{
bWantWallWalk = true;
}
JumpKeyHoldTime = 0.f;
WallWalkHoldTime = 0.f;
}
}
// meh
void ARlCharacter::StopJumping()
{
ResetJumpState();
}
// meh
void ARlCharacter::ResetJumpState()
{
bIsPressingJump = false;
bWantWallWalk = false;
bWantJump = false;
bWasJumping = false;
JumpKeyHoldTime = 0.0f;
JumpForceTimeRemaining = 0.0f;
WallWalkHoldTime = 0.f;
if (RlCharacterMovement && !RlCharacterMovement->IsFalling())
{
JumpCurrentCount = 0;
}
}
// meh
bool ARlCharacter::CanJump() const
{
// Can only jump from the ground, or multi-jump if already falling, not wall walking.
bool bCanJump = RlCharacterMovement && (RlCharacterMovement->IsMovingOnGround() || RlCharacterMovement->IsFalling());
if (bCanJump)
{
// Ensure JumpHoldTime and JumpCount are valid.
if (!bWasJumping || GetJumpMaxHoldTime() <= 0.0f)
{
if (JumpCurrentCount == 0 && RlCharacterMovement->IsFalling())
{
bCanJump = JumpCurrentCount + 1 < JumpMaxCount;
}
else
{
bCanJump = JumpCurrentCount < JumpMaxCount;
}
}
else
{
// Only consider JumpKeyHoldTime as long as:
// A) The jump limit hasn't been met OR
// B) The jump limit has been met AND we were already jumping
const bool bJumpKeyHeld = (bWantJump && JumpKeyHoldTime < GetJumpMaxHoldTime());
bCanJump = bLongJumpEnabled && bJumpKeyHeld && ((JumpCurrentCount < JumpMaxCount) || (bWasJumping && JumpCurrentCount == JumpMaxCount));
}
}
return bCanJump;
}
// meh
bool ARlCharacter::CanWallWalk() const
{
bool bCanWallWalk = RlCharacterMovement && RlCharacterMovement->IsFalling();
bCanWallWalk &= bWallWalkEnabled && bWantWallWalk && bWallWalkToggle && !CanJump() && WallWalkHoldTime < WallWalkMaxHoldTime;
return bCanWallWalk;
}
// meh
void ARlCharacter::CheckJumpInput(float DeltaTime)
{
if (RlCharacterMovement)
{
if (bWantJump)
{
if (!bIsPressingJump)
{
bWantJump = false;
}
// If this is the first jump and we're already falling,
// then increment the JumpCount to compensate.
const bool bFirstJump = JumpCurrentCount == 0;
if (bFirstJump && RlCharacterMovement->IsFalling())
{
JumpCurrentCount++;
}
const bool bDidJump = CanJump() && RlCharacterMovement->DoJump();
if (bDidJump)
{
// Transition from not (actively) jumping to jumping.
if (!bWasJumping)
{
JumpCurrentCount++;
JumpForceTimeRemaining = GetJumpMaxHoldTime();
}
}
bWasJumping = bDidJump;
}
if (bWantWallWalk)
{
const bool bDidWallWalk = CanWallWalk() && RlCharacterMovement->DoWallWalk();
if (bDidWallWalk)
{
if (!bWasWallWalking)
{
WallWalkHoldTime = 0.f;
}
}
bWasWallWalking = bDidWallWalk;
}
}
}
// meh
bool ARlCharacter::IsJumpProvidingForce() const
{
return JumpForceTimeRemaining > 0.0f;
}
// meh
void ARlCharacter::ApplyDamageMomentum(float DamageTaken, FDamageEvent const& DamageEvent, APawn* PawnInstigator, AActor* DamageCauser)
{
UDamageType const* const DmgTypeCDO = DamageEvent.DamageTypeClass->GetDefaultObject<UDamageType>();
float const ImpulseScale = DmgTypeCDO->DamageImpulse;
if ((ImpulseScale > 3.f) && (RlCharacterMovement != nullptr))
{
FHitResult HitInfo;
FVector ImpulseDir;
DamageEvent.GetBestHitInfo(this, PawnInstigator, HitInfo, ImpulseDir);
FVector Impulse = ImpulseDir * ImpulseScale;
bool const bMassIndependentImpulse = !DmgTypeCDO->bScaleMomentumByMass;
// limit Z momentum added if already going up faster than jump (to avoid blowing character way up into the sky)
{
FVector MassScaledImpulse = Impulse;
if (!bMassIndependentImpulse && RlCharacterMovement->Mass > SMALL_NUMBER)
{
MassScaledImpulse = MassScaledImpulse / RlCharacterMovement->Mass;
}
if ((RlCharacterMovement->Velocity.Z > GetDefault<URlCharacterMovementComponent>(RlCharacterMovement->GetClass())->JumpZVelocity) && (MassScaledImpulse.Z > 0.f))
{
Impulse.Z *= 0.5f;
}
}
RlCharacterMovement->AddImpulse(Impulse, bMassIndependentImpulse);
}
}
void ARlCharacter::ClearCrossLevelReferences()
{
if (BasedMovement.MovementBase != nullptr && GetOutermost() != BasedMovement.MovementBase->GetOutermost())
{
SetBase(nullptr);
}
Super::ClearCrossLevelReferences();
}
namespace RlMovementBaseUtility
{
// Checked
bool IsDynamicBase(const UPrimitiveComponent* MovementBase)
{
return (MovementBase && MovementBase->Mobility == EComponentMobility::Movable);
}
void AddTickDependency(FTickFunction& BasedObjectTick, UPrimitiveComponent* NewBase)
{
if (NewBase && RlMovementBaseUtility::UseRelativeLocation(NewBase))
{
if (NewBase->PrimaryComponentTick.bCanEverTick)
{
BasedObjectTick.AddPrerequisite(NewBase, NewBase->PrimaryComponentTick);
}
AActor* NewBaseOwner = NewBase->GetOwner();
if (NewBaseOwner)
{
if (NewBaseOwner->PrimaryActorTick.bCanEverTick)
{
BasedObjectTick.AddPrerequisite(NewBaseOwner, NewBaseOwner->PrimaryActorTick);
}
// @TODO: We need to find a more efficient way of finding all ticking components in an actor.
for (UActorComponent* Component : NewBaseOwner->GetComponents())
{
// Dont allow a based component (e.g. a particle system) to push us into a different tick group
if (Component && Component->PrimaryComponentTick.bCanEverTick && Component->PrimaryComponentTick.TickGroup <= BasedObjectTick.TickGroup)
{
BasedObjectTick.AddPrerequisite(Component, Component->PrimaryComponentTick);
}
}
}
}
}
void RemoveTickDependency(FTickFunction& BasedObjectTick, UPrimitiveComponent* OldBase)
{
if (OldBase && RlMovementBaseUtility::UseRelativeLocation(OldBase))
{
BasedObjectTick.RemovePrerequisite(OldBase, OldBase->PrimaryComponentTick);
AActor* OldBaseOwner = OldBase->GetOwner();
if (OldBaseOwner)
{
BasedObjectTick.RemovePrerequisite(OldBaseOwner, OldBaseOwner->PrimaryActorTick);
// @TODO: We need to find a more efficient way of finding all ticking components in an actor.
for (UActorComponent* Component : OldBaseOwner->GetComponents())
{
if (Component && Component->PrimaryComponentTick.bCanEverTick)
{
BasedObjectTick.RemovePrerequisite(Component, Component->PrimaryComponentTick);
}
}
}
}
}
FVector GetMovementBaseVelocity(const UPrimitiveComponent* MovementBase, const FName BoneName)
{
FVector BaseVelocity = FVector::ZeroVector;
if (RlMovementBaseUtility::IsDynamicBase(MovementBase))
{
if (BoneName != NAME_None)
{
const FBodyInstance* BodyInstance = MovementBase->GetBodyInstance(BoneName);
if (BodyInstance)
{
BaseVelocity = BodyInstance->GetUnrealWorldVelocity();
return BaseVelocity;
}
}
BaseVelocity = MovementBase->GetComponentVelocity();
if (BaseVelocity.IsZero())
{
// Fall back to actor's Root component
const AActor* Owner = MovementBase->GetOwner();
if (Owner)
{
// Component might be moved manually (not by simulated physics or a movement component), see if the root component of the actor has a velocity.
BaseVelocity = MovementBase->GetOwner()->GetVelocity();
}
}
// Fall back to physics velocity.
if (BaseVelocity.IsZero())
{
if (FBodyInstance* BaseBodyInstance = MovementBase->GetBodyInstance())
{
BaseVelocity = BaseBodyInstance->GetUnrealWorldVelocity();
}
}
}
return BaseVelocity;
}
FVector GetMovementBaseTangentialVelocity(const UPrimitiveComponent* MovementBase, const FName BoneName, const FVector& WorldLocation)
{
if (RlMovementBaseUtility::IsDynamicBase(MovementBase))
{
if (const FBodyInstance* BodyInstance = MovementBase->GetBodyInstance(BoneName))
{
const FVector BaseAngVelInRad = BodyInstance->GetUnrealWorldAngularVelocityInRadians();
if (!BaseAngVelInRad.IsNearlyZero())
{
FVector BaseLocation;
FQuat BaseRotation;
if (RlMovementBaseUtility::GetMovementBaseTransform(MovementBase, BoneName, BaseLocation, BaseRotation))
{
const FVector RadialDistanceToBase = WorldLocation - BaseLocation;
const FVector TangentialVel = BaseAngVelInRad ^ RadialDistanceToBase;
return TangentialVel;
}
}
}
}
return FVector::ZeroVector;
}
// Checked
bool GetMovementBaseTransform(const UPrimitiveComponent* MovementBase, const FName BoneName, FVector& OutLocation, FQuat& OutQuat)
{
if (MovementBase)
{
if (BoneName != NAME_None)
{
bool bFoundBone = false;
if (MovementBase)
{
// Check if this socket or bone exists (DoesSocketExist checks for either, as does requesting the transform).
if (MovementBase->DoesSocketExist(BoneName))
{
MovementBase->GetSocketWorldLocationAndRotation(BoneName, OutLocation, OutQuat);
bFoundBone = true;
}
else
{
UE_LOG(LogCharacter, Warning, TEXT("GetMovementBaseTransform(): Invalid bone or socket '%s' for PrimitiveComponent base %s"), *BoneName.ToString(), *GetPathNameSafe(MovementBase));
}
}
if (!bFoundBone)
{
OutLocation = MovementBase->GetComponentLocation();
OutQuat = MovementBase->GetComponentQuat();
}
return bFoundBone;
}
// No bone supplied
OutLocation = MovementBase->GetComponentLocation();
OutQuat = MovementBase->GetComponentQuat();
return true;
}
// nullptr MovementBase
OutLocation = FVector::ZeroVector;
OutQuat = FQuat::Identity;
return false;
}
}
/** Change the Pawn's base. */
void ARlCharacter::SetBase(UPrimitiveComponent* NewBaseComponent, const FName InBoneName, bool bNotifyPawn)
{
// If NewBaseComponent is nullptr, ignore bone name.
const FName BoneName = (NewBaseComponent ? InBoneName : NAME_None);
// See what changed.
const bool bBaseChanged = (NewBaseComponent != BasedMovement.MovementBase);
const bool bBoneChanged = (BoneName != BasedMovement.BoneName);
if (bBaseChanged || bBoneChanged)
{
// Verify no recursion.
APawn* Loop = (NewBaseComponent ? Cast<APawn>(NewBaseComponent->GetOwner()) : nullptr);
while (Loop)
{
if (Loop == this)
{
UE_LOG(LogCharacter, Warning, TEXT(" SetBase failed! Recursion detected. Pawn %s already based on %s."), *GetName(), *NewBaseComponent->GetName()); //-V595
return;
}
if (UPrimitiveComponent* LoopBase = Loop->GetMovementBase())
{
Loop = Cast<APawn>(LoopBase->GetOwner());
}
else
{
break;
}
}
// Set base.
UPrimitiveComponent* OldBase = BasedMovement.MovementBase;
BasedMovement.MovementBase = NewBaseComponent;
BasedMovement.BoneName = BoneName;
if (RlCharacterMovement)
{
const bool bBaseIsSimulating = NewBaseComponent && NewBaseComponent->IsSimulatingPhysics();
if (bBaseChanged)
{
RlMovementBaseUtility::RemoveTickDependency(RlCharacterMovement->PrimaryComponentTick, OldBase);
// We use a special post physics function if simulating, otherwise add normal tick prereqs.
if (!bBaseIsSimulating)
{
RlMovementBaseUtility::AddTickDependency(RlCharacterMovement->PrimaryComponentTick, NewBaseComponent);
}
}
if (NewBaseComponent)
{
// Update OldBaseLocation/Rotation as those were referring to a different base
// ... but not when handling replication for proxies (since they are going to copy this data from the replicated values anyway)
//if (!bInBaseReplication)
//{
// Force base location and relative position to be computed since we have a new base or bone so the old relative offset is meaningless.
RlCharacterMovement->SaveBaseLocation();
//}
}
else
{
BasedMovement.BoneName = NAME_None; // None, regardless of whether user tried to set a bone name, since we have no base component.
BasedMovement.bRelativeRotation = false;
RlCharacterMovement->CurrentFloor.Clear();
}
if (Role == ROLE_Authority || Role == ROLE_AutonomousProxy)
{
BasedMovement.bServerHasBaseComponent = (BasedMovement.MovementBase != nullptr); // Also set on proxies for nicer debugging.
UE_LOG(LogCharacter, Verbose, TEXT("Setting base on %s for '%s' to '%s'"), Role == ROLE_Authority ? TEXT("Server") : TEXT("AutoProxy"), *GetName(), *GetFullNameSafe(NewBaseComponent));
}
else
{
UE_LOG(LogCharacter, Verbose, TEXT("Setting base on Client for '%s' to '%s'"), *GetName(), *GetFullNameSafe(NewBaseComponent));
}
}
// Notify this actor of his new floor.
if (bNotifyPawn)
{
BaseChange();
}
}
}
void ARlCharacter::SaveRelativeBasedMovement(const FVector& NewRelativeLocation, const FRotator& NewRotation, bool bRelativeRotation)
{
checkSlow(BasedMovement.HasRelativeLocation());
BasedMovement.Location = NewRelativeLocation;
BasedMovement.Rotation = NewRotation;
BasedMovement.bRelativeRotation = bRelativeRotation;
}
// meh
void ARlCharacter::TurnOff()
{
if (RlCharacterMovement != nullptr)
{
RlCharacterMovement->StopMovementImmediately();
RlCharacterMovement->DisableMovement();
}
Super::TurnOff();
}
// meh
void ARlCharacter::Restart()
{
Super::Restart();
JumpCurrentCount = 0;
bWantJump = false;
ResetJumpState();
if (RlCharacterMovement)
{
RlCharacterMovement->SetDefaultMovementMode();
}
}
// meh
void ARlCharacter::NotifyActorBeginOverlap(AActor* OtherActor)
{
NumActorOverlapEventsCounter++;
Super::NotifyActorBeginOverlap(OtherActor);
}
// meh
void ARlCharacter::NotifyActorEndOverlap(AActor* OtherActor)
{
NumActorOverlapEventsCounter++;
Super::NotifyActorEndOverlap(OtherActor);
}
void ARlCharacter::BaseChange()
{
if (RlCharacterMovement)
{
AActor* ActualMovementBase = GetMovementBaseActor(this);
if ((ActualMovementBase != nullptr) && !ActualMovementBase->CanBeBaseForCharacter(this))
{
RlCharacterMovement->JumpOff(ActualMovementBase);
}
}
}
// meh
void ARlCharacter::DisplayDebug(UCanvas* Canvas, const FDebugDisplayInfo& DebugDisplay, float& YL, float& YPos)
{
Super::DisplayDebug(Canvas, DebugDisplay, YL, YPos);
float Indent = 0.f;
static FName NAME_Physics = FName(TEXT("Physics"));
if (DebugDisplay.IsDisplayOn(NAME_Physics))
{
FIndenter PhysicsIndent(Indent);
FString BaseString;
if (RlCharacterMovement == nullptr || BasedMovement.MovementBase == nullptr)
{
BaseString = "Not Based";
}
else
{
BaseString = BasedMovement.MovementBase->IsWorldGeometry() ? "World Geometry" : BasedMovement.MovementBase->GetName();
BaseString = FString::Printf(TEXT("Based On %s"), *BaseString);
}
FDisplayDebugManager& DisplayDebugManager = Canvas->DisplayDebugManager;
DisplayDebugManager.DrawString(FString::Printf(TEXT("RelativeLoc: %s Rot: %s %s"), *BasedMovement.Location.ToCompactString(), *BasedMovement.Rotation.ToCompactString(), *BaseString), Indent);
if (RlCharacterMovement != nullptr)
{
//RlCharacterMovement->DisplayDebug(Canvas, DebugDisplay, YL, YPos);
}
const bool Crouched = RlCharacterMovement && RlCharacterMovement->IsCrouching();
FString T = FString::Printf(TEXT("Crouched %i"), Crouched);
DisplayDebugManager.DrawString(T, Indent);
}
}
// meh
void ARlCharacter::LaunchCharacter(FVector LaunchVelocity, bool bXYOverride, bool bZOverride)
{
UE_LOG(LogCharacter, Verbose, TEXT("ARlCharacter::LaunchCharacter '%s' (%f,%f,%f)"), *GetName(), LaunchVelocity.X, LaunchVelocity.Y, LaunchVelocity.Z);
if (RlCharacterMovement)
{
FVector FinalVel = LaunchVelocity;
const FVector Velocity = GetVelocity();
if (!bXYOverride)
{
FinalVel.X += Velocity.X;
FinalVel.Y += Velocity.Y;
}
if (!bZOverride)
{
FinalVel.Z += Velocity.Z;
}
RlCharacterMovement->Launch(FinalVel);
}
}
void ARlCharacter::ClearJumpInput(float DeltaTime)
{
if (bWantJump)
{
JumpKeyHoldTime += DeltaTime;
// Don't disable bPressedJump right away if it's still held.
// Don't modify JumpForceTimeRemaining because a frame of update may be remaining.
if (JumpKeyHoldTime >= GetJumpMaxHoldTime())
{
bWantJump = false;
}
}
else
{
JumpForceTimeRemaining = 0.0f;
bWasJumping = false;
}
}
// meh
float ARlCharacter::GetJumpMaxHoldTime() const
{
return JumpMaxHoldTime;
}
// meh
void ARlCharacter::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
CurrentDeltaTime = DeltaTime;
UpdateAnimation();
URlGameInstance* RlGI = Cast<URlGameInstance>(GetGameInstance());
if (RlGI->bUseDevice)
{
CheckServer();
if (!bDeviceConnected && !bConnectionAccepted)
{
AdvertisementWatcher(true);
}
}
}
// meh
void ARlCharacter::MoveRight(float Value)
{
if (bIsSprinting)
{
if (Value > 0)
{
Value = FMath::Lerp(0.5f, 1.f, Value);
}
if (Value < 0)
{
Value = FMath::Lerp(-0.5f, -1.f, -Value);
}
}
//UE_LOG(LogTemp, Warning, TEXT("%f"), Value);
AddMovementInput(FVector(1.0f, 0.0f, 0.0f), Value);
}
// meh
void ARlCharacter::UpdateAnimation()
{
// Dust update
float VX = RlCharacterMovement->Velocity.X;
float AX = RlCharacterMovement->GetCurrentAcceleration().X;
float NMWS = RlCharacterMovement->NormalMaxWalkSpeed;
if (bDust && (!bIsSprinting || bIsChangingDirection || FMath::Abs(VX) < NMWS || RlCharacterMovement->IsFalling()))
{
bDust = false;
DustComponent->Deactivate();
}
if (!bDust && bIsSprinting && FMath::Abs(VX) > NMWS && !RlCharacterMovement->IsFalling())
{
bDust = true;
DustComponent->SetTemplate(AX > 0 ? DustRight : DustLeft);
DustComponent->Activate(true);
}
FRlAnimation CurrentAnimationInfo = AnimationLibrary[CurrentState];
// Check Start and End
if (CurrentAnimationInfo.bReverse)
{
if (CurrentAnimationInfo.Start != -1 && BelowFrame(CurrentAnimationInfo.Start))
{
if (CurrentAnimationInfo.bLoop)
{
Sprite->SetPlaybackPositionInFrames(CurrentAnimationInfo.End, false);
}
else
{
Sprite->Stop();
}
}
}
else
{
if (CurrentAnimationInfo.End != -1 && AboveFrame(CurrentAnimationInfo.End))
{
if (CurrentAnimationInfo.bLoop)
{
Sprite->SetPlaybackPositionInFrames(CurrentAnimationInfo.Start, false);
}
else
{
Sprite->Stop();
}
}
}
const float VelocityX = RlCharacterMovement->Velocity.X;
const float VelocityZ = RlCharacterMovement->Velocity.Z;
//UE_LOG(LogTemp, Warning, TEXT("X: %f Z: %f S: %i"), VelocityX, VelocityZ, (int)CurrentState);
bool bOldIsLastDirectionRight = bIsLastDirectionRight;
if (VelocityX > 0.f)
{
bIsLastDirectionRight = true;
}
else if (VelocityX < 0.f)
{
bIsLastDirectionRight = false;
}
const bool bSwitchDirection = bIsLastDirectionRight != bOldIsLastDirectionRight;
if (FMath::Sign(VelocityX * RlCharacterMovement->GetCurrentAcceleration().X) < 0.f)
{
bIsChangingDirection = true;
}
if (FMath::Abs(VelocityX) > WalkSpeed || RlCharacterMovement->GetCurrentAcceleration().X == 0.f)
{
bIsChangingDirection = false;
}
if (bSwitchDirection)
{
SetCurrentState(CurrentState);
//bIsChangingDirection = false;
}
if (AnimationLibrary.Contains(CurrentState))
{
for (FRlTransition Transition : AnimationLibrary[CurrentState].Transitions)
{
if (Transition.Predicate(this))
{
SetCurrentState(Transition.NextState);
break;
}
}
}
// Change start of TJA to match state of TIRA
if (CurrentState == ERlAnimationState::Running)
{
FScopedFlipbookMutator ScopedFlipbookMutator(Sprite->GetFlipbook());
ScopedFlipbookMutator.FramesPerSecond = FMath::Max(FMath::RoundToInt((WalkSpeed * FMath::Abs(RlCharacterMovement->Velocity.X)) / RlCharacterMovement->NormalMaxWalkSpeed), 10);
}
if (CurrentState == ERlAnimationState::Idle)
{
UPaperFlipbook* CurrentAnimation = AnimationLibrary[CurrentState].Animation(this);
UPaperFlipbook* CurrentAnimationExtras = bIsLastDirectionRight ? IdleRightAnimationExtras : IdleLeftAnimationExtras;
const float EffectiveDeltaTime = CurrentDeltaTime * Sprite->GetPlayRate();
float NewPosition = Sprite->GetPlaybackPosition() + EffectiveDeltaTime;
if (CurrentAnimation && CurrentAnimationExtras && NewPosition > Sprite->GetFlipbookLength())
{
FScopedFlipbookMutator ScopedFlipbookMutator(CurrentAnimation);
ScopedFlipbookMutator.KeyFrames[1] = CurrentAnimationExtras->GetKeyFrameChecked(FMath::RandRange(0, 1));
ScopedFlipbookMutator.KeyFrames[3] = CurrentAnimationExtras->GetKeyFrameChecked(FMath::RandRange(2, 4));
}
}
}
// meh
void ARlCharacter::SetCurrentState(ERlAnimationState State)
{
ERlAnimationState OldState = CurrentState;
CurrentState = State;
UPaperFlipbook* OldAnimation = AnimationLibrary[OldState].Animation(this);
UPaperFlipbook* CurrentAnimation = AnimationLibrary[CurrentState].Animation(this);
float OldFrame = Sprite->GetPlaybackPositionInFrames();
bool bChangedAnimation = OldAnimation != CurrentAnimation;
if (CurrentState == ERlAnimationState::Jumping)
{
if (bStoredJump)
{
bStoredJump = false;
bWantJump = true;
}
}
Sprite->SetFlipbook(CurrentAnimation);
Sprite->SetLooping(AnimationLibrary[CurrentState].bLoop);
if (OldState == ERlAnimationState::Idle && CurrentState == ERlAnimationState::ToJumping)
{
bChangedAnimation = false;
Sprite->SetPlaybackPositionInFrames(2, false);
}
if ((OldState == ERlAnimationState::ToIdle || OldState == ERlAnimationState::ToIdleR) && CurrentState == ERlAnimationState::ToJumping)
{
bChangedAnimation = false;
Sprite->SetPlaybackPositionInFrames(OldFrame, false);
}
if (AnimationLibrary[CurrentState].bReverse)
{
if (!AnimationLibrary[CurrentState].bKeepFrame || bChangedAnimation)
{
const int End = AnimationLibrary[CurrentState].End;
Sprite->SetPlaybackPositionInFrames(End != -1 ? End : Sprite->GetFlipbookLengthInFrames(), false);
}
Sprite->Reverse();
}
else
{
if (!AnimationLibrary[CurrentState].bKeepFrame || bChangedAnimation)
{
const int Start = AnimationLibrary[CurrentState].Start;
Sprite->SetPlaybackPositionInFrames(Start != -1 ? Start : 0.f, false);
}
Sprite->Play();
}
//UE_LOG(LogTemp, Warning, TEXT("%i"), CurrentState);
}
// meh
int ARlCharacter::GetFlipbookLengthInFrames(UPaperFlipbook* (*Animation)(ARlCharacter*))
{
UPaperFlipbook* PaperFlipbook = Animation(this);
return PaperFlipbook ? PaperFlipbook->GetNumFrames() : 0;
}
// meh
float ARlCharacter::NextAnimationPostion()
{
const float EffectiveDeltaTime = CurrentDeltaTime * Sprite->GetPlayRate();
return Sprite->GetPlaybackPosition() + EffectiveDeltaTime;
}
// meh
bool ARlCharacter::AboveFrame(int32 Frame)
{
return NextAnimationPostion() > Frame / Sprite->GetFlipbookFramerate();
}
// meh
bool ARlCharacter::BelowFrame(int32 Frame)
{
return NextAnimationPostion() < Frame / Sprite->GetFlipbookFramerate();
}
// meh
void ARlCharacter::Level()
{
ULevelManager* LM = Cast<URlGameInstance>(GetGameInstance())->LevelManager;
LM->SetLevel(ELevelState::Start);
}
// meh
void ARlCharacter::Skip()
{
ULevelManager* LM = Cast<URlGameInstance>(GetGameInstance())->LevelManager;
if (LM->CurrentLevel)
{
LM->SetLevel(ELevelState::Next);
}
}
// meh
void ARlCharacter::Reset()
{
ULevelManager* LM = Cast<URlGameInstance>(GetGameInstance())->LevelManager;
if (LM->CurrentLevel)
{
LM->RestartLevel();
}
}
// meh
void ARlCharacter::DifficultyDebug(float Value)
{
if (!Value)
{
return;
}
if (Value == -1.f)
{
Value = 0;
}
ARlGameMode* GameMode = Cast<ARlGameMode>(GetWorld()->GetAuthGameMode());
if (Value == GameMode->Difficulty)
{
return;
}
GameMode->Difficulty = Value;
UKismetSystemLibrary::PrintString(GetWorld(), FString::Printf(TEXT("Difficulty: %f"), GameMode->Difficulty));
}
// meh
void ARlCharacter::DifficultyAddDebug(float Value)
{
if (!Value)
{
bCanDA = true;
return;
}
if (bCanDA)
{
bCanDA = false;
ARlGameMode* GameMode = Cast<ARlGameMode>(GetWorld()->GetAuthGameMode());
GameMode->Difficulty += Value;
UKismetSystemLibrary::PrintString(GetWorld(), FString::Printf(TEXT("Difficulty: %f"), GameMode->Difficulty));
}
}
// meh
void ARlCharacter::Death()
{
if (!bDeath)
{
Vibrate(100);
bDeath = true;
Sprite->ToggleVisibility();
ResetJumpState();
bStoredJump = false;
if (ARlPlayerController* RlPlayerController = Cast<ARlPlayerController>(UGameplayStatics::GetPlayerController(GetWorld(), 0)))
{
RlPlayerController->SetIgnoreMoveInput(true);
}
URlGameInstance* RlGI = Cast<URlGameInstance>(GetGameInstance());
if (ARlSpriteHUD* RlSHUD = RlGI->RlSpriteHUD)
{
RlSHUD->IncreaseDeaths();
}
//std::ostringstream oss;
//oss << '\0' << RlGI->Deaths << '\0' << "Deaths" << '\0' << '\0';
//std::string Message = oss.str();
//WriteMessage((uint8*)Message.c_str(), Message.size());
// Timer to call LM->RestartLevel() on end of death animation
UGameplayStatics::SpawnEmitterAtLocation(GetWorld(), DeathAnimation, GetActorLocation() + FVector(0.f, 0.f, -6.f), FRotator(0.f, bIsLastDirectionRight ? 0.f : 180.f, 0.f));
ULevelManager* LM = RlGI->LevelManager;
GetWorld()->GetTimerManager().SetTimer(DeathHandle, LM, &ULevelManager::RestartLevel, 0.5f, false);
//LM->RestartLevel();
}
}
// meh
void ARlCharacter::Up()
{
//WriteMessage((uint8 *)u8"· o ·)>", 9);
//HearRate(true);
if (!bDeath)
{
TArray<AActor*> Stairs;
GetOverlappingActors(Stairs, AStairs::StaticClass());
if (Stairs.Num())
{
AStairs* OverlappingStairs = Cast<AStairs>(Stairs.Pop());
if (OverlappingStairs->bCanEnter && !bInvincible)
{
ULevelManager* LM = Cast<URlGameInstance>(GetGameInstance())->LevelManager;
LM->SetLevel(ELevelState::Next);
bInvincible = true;
}
}
}
}
// meh
void ARlCharacter::Vibrate(uint16 Milliseconds)
{
int32 Sent;
const uint8 Id = 0x04;
//const uint8 Data[] = { 0x00, (Milliseconds >> 8) & 0xff, Milliseconds & 0xff };
FIPv4Endpoint IPv4Endpoint(FIPv4Address(127, 0, 0, 1), 1243);
FSocket* Socket = FTcpSocketBuilder(TEXT("FTcpListener server"));
Socket->Connect(*IPv4Endpoint.ToInternetAddr());
Socket->Send(&Id, 1, Sent);
Socket->Send((const uint8*)&Milliseconds, 2, Sent);
Socket->Close();
}
// meh
void ARlCharacter::WriteMessage(uint8* Message, uint32 MessageSize)
{
//Message.
int32 Sent;
const uint8 Id = 0x02;
FIPv4Endpoint IPv4Endpoint(FIPv4Address(127, 0, 0, 1), 1243);
FSocket* Socket = FTcpSocketBuilder(TEXT("FTcpListener server"));
Socket->Connect(*IPv4Endpoint.ToInternetAddr());
Socket->Send(&Id, 1, Sent);
Socket->Send((const uint8*)&MessageSize, 4, Sent);
Socket->Send(Message, MessageSize, Sent);
Socket->Close();
}
// meh
void ARlCharacter::HearRate(bool bStart)
{
int32 Sent;
const uint8 Id = 0x03;
FIPv4Endpoint IPv4Endpoint(FIPv4Address(127, 0, 0, 1), 1243);
FSocket* Socket = FTcpSocketBuilder(TEXT("FTcpListener server"));
Socket->Connect(*IPv4Endpoint.ToInternetAddr());
Socket->Send(&Id, 1, Sent);
Socket->Send((const uint8*)&bStart, 1, Sent);
Socket->Close();
}
// meh
void ARlCharacter::AdvertisementWatcher(bool bStart)
{
int32 Sent;
const uint8 Id = 0x00;
FIPv4Endpoint IPv4Endpoint(FIPv4Address(127, 0, 0, 1), 1243);
FSocket* Socket = FTcpSocketBuilder(TEXT("FTcpListener server"));
Socket->Connect(*IPv4Endpoint.ToInternetAddr());
Socket->Send(&Id, 1, Sent);
Socket->Send((const uint8*)&bStart, 1, Sent);
Socket->Close();
}
// meh
void ARlCharacter::Connect(FString Device)
{
int32 Sent;
const uint8 Id = 0x01;
////auto a = Device.GetCharArray();
//auto a = *Device;
uint32 MessageSize = Device.Len();
char* Message = TCHAR_TO_ANSI(*Device);
auto a = Device;
FIPv4Endpoint IPv4Endpoint(FIPv4Address(127, 0, 0, 1), 1243);
FSocket* Socket = FTcpSocketBuilder(TEXT("FTcpListener server"));
Socket->Connect(*IPv4Endpoint.ToInternetAddr());
Socket->Send(&Id, 1, Sent);
Socket->Send((const uint8*)&MessageSize, 4, Sent);
Socket->Send((const uint8*)Message, MessageSize, Sent);
Socket->Close();
UWidgetManager* WM = Cast<URlGameInstance>(GetWorld()->GetGameInstance())->WidgetManager;
if (WM->DeviceSelection)
{
GetWorld()->GetTimerManager().SetTimer(DeviceConnectionHandle, WM->DeviceSelection, &UDeviceSelection::DeviceConnectionFailed, 20.f);
}
}
// meh
void ARlCharacter::Vibrate()
{
int32 Sent;
const uint8 Id = 0x05;
FIPv4Endpoint IPv4Endpoint(FIPv4Address(127, 0, 0, 1), 1243);
FSocket* Socket = FTcpSocketBuilder(TEXT("FTcpListener server"));
Socket->Connect(*IPv4Endpoint.ToInternetAddr());
Socket->Send(&Id, 1, Sent);
Socket->Close();
}
// meh
bool ARlCharacter::OnConnection(FSocket* Socket, const struct FIPv4Endpoint& IPv4Endpoint)
{
bConnectionAccepted = true;
//UKismetSystemLibrary::PrintString(GetWorld(), FString("Connection accepted"));
UE_LOG(LogStatus, Log, TEXT("Connection accepted"));
ConnectionSocket = Socket;
int32 NewSize;
if (!bDeviceConnected)
{
ConnectionSocket->SetReceiveBufferSize(17 * sizeof(uint8), NewSize);
}
else
{
ConnectionSocket->SetReceiveBufferSize(2 * sizeof(uint8), NewSize);
}
return true;
}
// meh
void ARlCharacter::CheckServer()
{
if (!ConnectionSocket)
{
return;
}
TArray<uint8> ReceivedData;
uint32 Size;
while (ConnectionSocket->HasPendingData(Size))
{
ReceivedData.Init(0, FMath::Min(Size, 65507u));
int32 Read = 0;
ConnectionSocket->Recv(ReceivedData.GetData(), ReceivedData.Num(), Read);
}
if (ReceivedData.Num() <= 0)
{
return;
}
ReceivedData.Add(0);
const FString ReceivedUE4String = FString(ANSI_TO_TCHAR(reinterpret_cast<const char*>(ReceivedData.GetData())));
ULevelManager* LM = Cast<URlGameInstance>(GetWorld()->GetGameInstance())->LevelManager;
UWidgetManager* WM = Cast<URlGameInstance>(GetWorld()->GetGameInstance())->WidgetManager;
if (!bDeviceConnected)
{
if (!ReceivedUE4String.Compare("Connected"))
{
GetWorld()->GetTimerManager().ClearTimer(DeviceConnectionHandle);
bDeviceConnected = true;
if (WM->DeviceSelection)
{
WM->DeviceSelection->RemoveFromParent();
}
UE_LOG(LogStatus, Log, TEXT("Hear Rate Measurement Started"));
HearRate(true);
if (ARlGameMode* GameMode = Cast<ARlGameMode>(GetWorld()->GetAuthGameMode()))
{
GameMode->HeartRateModule->StartCalibration();
}
if (Cast<URlGameInstance>(GetWorld()->GetGameInstance())->bIntro)
{
WM->StartIntro();
}
else
{
LM->SetLevel(ELevelState::Start);
}
//auto PC = UGameplayStatics::GetPlayerController(GetWorld(), 0);
//PC->SetInputMode(FInputModeGameOnly());
//EnableInput(PC);
}
else if (WM->DeviceSelection)
{
UE_LOG(LogDevice, Log, TEXT("%s"), *ReceivedUE4String);
WM->DeviceSelection->AddDevice(ReceivedUE4String);
}
}
else
{
if (ReceivedUE4String.Len() == 2)
{
if (ARlGameMode* GameMode = Cast<ARlGameMode>(GetWorld()->GetAuthGameMode()))
{
GameMode->HeartRateModule->AddHeartRate(ReceivedUE4String);
}
}
//UE_LOG(LogHeartRate, Log, TEXT("%s"), *ReceivedUE4String);
}
//UKismetSystemLibrary::PrintString(GetWorld(), FString::Printf(TEXT("Heart Rate: %s"), *ReceivedUE4String), true, true, FLinearColor(0.0, 0.66, 1.0), 20.f);
}
// meh
void ARlCharacter::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)
{
Super::SetupPlayerInputComponent(PlayerInputComponent);
PlayerInputComponent->BindAction("Jump", IE_Pressed, this, &ARlCharacter::Jump);
PlayerInputComponent->BindAction("Jump", IE_Released, this, &ARlCharacter::StopJumping);
PlayerInputComponent->BindAxis("MoveRight", this, &ARlCharacter::MoveRight);
// TODO Remove
PlayerInputComponent->BindAxis("DifficultyDebug", this, &ARlCharacter::DifficultyDebug);
PlayerInputComponent->BindAxis("DifficultyAddDebug", this, &ARlCharacter::DifficultyAddDebug);
PlayerInputComponent->BindAction("Up", IE_Pressed, this, &ARlCharacter::Up);
PlayerInputComponent->BindAction("Level", IE_Pressed, this, &ARlCharacter::Level);
PlayerInputComponent->BindAction("Skip", IE_Pressed, this, &ARlCharacter::Skip);
PlayerInputComponent->BindAction("Reset", IE_Pressed, this, &ARlCharacter::Reset);
PlayerInputComponent->BindAction("Vibrate", IE_Pressed, this, &ARlCharacter::Vibrate);
PlayerInputComponent->BindAction("Sprint", IE_Pressed, RlCharacterMovement, &URlCharacterMovementComponent::SprintStart);
PlayerInputComponent->BindAction("Sprint", IE_Released, RlCharacterMovement, &URlCharacterMovementComponent::SprintStop);
}
#if WITH_EDITOR
void ARlCharacter::PostEditChangeProperty(FPropertyChangedEvent& PropertyChangedEvent)
{
Super::PostEditChangeProperty(PropertyChangedEvent);
FName PropertyName = (PropertyChangedEvent.MemberProperty != nullptr) ? PropertyChangedEvent.MemberProperty->GetFName() : NAME_None;
if (PropertyName == GET_MEMBER_NAME_CHECKED(ARlCharacter, Difficulty))
{
ARlGameMode* GameMode = Cast<ARlGameMode>(GetWorld()->GetAuthGameMode());
GameMode->Difficulty = Difficulty;
}
}
#endif<file_sep>// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/GameModeBase.h"
#include "RlGameMode.generated.h"
class UHearRateModule;
/**
* The GameMode defines the game being played. It governs the game rules, scoring, what actors
* are allowed to exist in this game type, and who may enter the game.
*
* This game mode just sets the default pawn to be the MyCharacter asset, which is a subclass of RageliteCharacter
*/
UCLASS(minimalapi)
class /*RAGELITE_API*/ ARlGameMode : public AGameModeBase
{
GENERATED_BODY()
public:
ARlGameMode();
UPROPERTY(EditAnywhere, Category = Config)
float Difficulty;
bool bGameStarted;
UPROPERTY()
UHearRateModule* HeartRateModule;
//public:
// virtual void StartPlay() override;
//virtual void Tick() override;
protected:
virtual void BeginPlay() override;
//private:
// FTimerHandle TimeHandle;
//
// void TimeTick();
};
<file_sep>// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "UObject/NoExportTypes.h"
#include "WidgetManager.generated.h"
class UIntro;
class UDeviceSelection;
class URlGameInstance;
/**
*
*/
UCLASS(Blueprintable)
class RAGELITE_API UWidgetManager : public UObject
{
GENERATED_BODY()
public:
void Init(URlGameInstance* InRlGI);
URlGameInstance* RlGI;
UPROPERTY(Category = Devices, EditAnywhere)
TSubclassOf<UIntro> IntroClass;
UIntro* Intro;
UPROPERTY(Category = Devices, EditAnywhere)
TSubclassOf<UDeviceSelection> DeviceSelectionClass;
UPROPERTY()
UDeviceSelection* DeviceSelection;
void StartIntro();
void EndIntro();
void EndGame();
};
<file_sep># Ragelite
Game where the difficulty is dynamically adjusted using heart rate
<file_sep>// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "PaperSpriteActor.h"
#include "Projectile.generated.h"
DECLARE_DELEGATE(FHitSignature)
//class UProjectileMovementComponent;
class UDefaultMovementComponent;
/**
*
*/
UCLASS()
class RAGELITE_API AProjectile : public APaperSpriteActor
{
GENERATED_BODY()
public:
AProjectile();
virtual void Tick(float DeltaSeconds) override;
UPROPERTY(Category = Character, VisibleAnywhere, meta = (AllowPrivateAccess = "true"))
UDefaultMovementComponent* MovementComponent;
//UProjectileMovementComponent* MovementComponent;
FHitSignature OnRlCharacterHit;
FTimerHandle DestroyHandle;
float InitialSpeed;
private:
UFUNCTION()
void OnHit(UPrimitiveComponent* HitComponent, AActor* OtherActor, UPrimitiveComponent* OtherComp, FVector NormalImpulse, const FHitResult& Hit);
void DestroyWrapper();
};
<file_sep>// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "AudioManager.generated.h"
class URlGameInstance;
class USoundCue;
class UAudioComponent;
/**
*
*/
UCLASS(Blueprintable)
class RAGELITE_API AAudioManager : public AActor
{
GENERATED_BODY()
public:
AAudioManager(const FObjectInitializer& ObjectInitializer);
void Init(URlGameInstance* InRlGI);
void Play();
void SetIntro();
void SetMusic();
void SetWin();
URlGameInstance* RlGI;
UPROPERTY(VisibleAnywhere)
UAudioComponent* AudioComponent;
UPROPERTY(EditAnywhere)
USoundCue* Intro;
UPROPERTY(EditAnywhere)
USoundCue* Music;
UPROPERTY(EditAnywhere)
USoundCue* Win;
UPROPERTY(EditAnywhere)
USoundCue* Jump;
UPROPERTY(EditAnywhere)
USoundCue* Run;
UPROPERTY(EditAnywhere)
USoundCue* Walk;
UPROPERTY(EditAnywhere)
USoundCue* Death;
UPROPERTY(EditAnywhere)
USoundCue* Dart;
};
<file_sep>// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "UObject/NoExportTypes.h"
#include "TimerManager.h"
#include "RLTypes.h"
#include "Engine/World.h"
#include "LevelManager.generated.h"
class URlGameInstance;
class UPaperTileMap;
class UPaperTileMapComponent;
class APaperTileMapActor;
class UPaperSprite;
class APaperSpriteActor;
class UMaterialInterface;
class UWorld;
class AStairs;
class UPrimitiveComponent;
class AHazardPool;
class ARlSpikes;
class UInputTutorial;
class UUserWidget;
/**
*
*/
UCLASS(Blueprintable)
class RAGELITE_API ULevelManager : public UObject
{
GENERATED_BODY()
ULevelManager(const FObjectInitializer& ObjectInitializer);
public:
void Init(URlGameInstance* InRlGameInstance);
virtual UWorld* GetWorld() const override;
UPaperSprite* GetSpikeSprite() const;
UPaperSprite* GetDartSprite() const;
UPaperSprite* GetStoneSprite() const;
public:
UPROPERTY(Category = Levels, VisibleAnywhere)
FVector SpawnLocation;
UPROPERTY(Category = Levels, EditAnywhere)
TArray<FRlLevel> Levels;
UPROPERTY(Category = Sprites, EditAnywhere)
UPaperSprite* StairsSprite;
UPROPERTY(Category = Sprites, EditAnywhere)
TArray<UPaperSprite*> SpikesSprites;
UPROPERTY(Category = Sprites, EditAnywhere)
UPaperSprite* DartSprite;
UPROPERTY(Category = Sprites, EditAnywhere)
TArray<UPaperSprite*> DartsSprites;
UPROPERTY(Category = Sprites, EditAnywhere)
TArray<UPaperSprite*> StonesSprites;
UPROPERTY(Category = Input, EditAnywhere)
TArray<UPaperTileMap*> InputTutorialTileMaps;
UPROPERTY(Category = Sprites, EditAnywhere)
UMaterialInterface* Material;
UPROPERTY(Category = Sprites, EditAnywhere)
int32 TileSize;
UPROPERTY(Category = Camera, EditAnywhere)
float FadeTime;
UPROPERTY(Category = Debug, EditAnywhere)
float CurrentDifficulty_Debug = 0.5;
int32 CurrentLevelIndex;
APaperTileMapActor* CurrentLevel;
APaperTileMapActor* InputTutorialTileMapActor;
AHazardPool* HazardPool;
UPROPERTY()
UInputTutorial* InputTutorial;
public:
UFUNCTION()
void EndGame();
void SetLevel(ELevelState State);
void RestartLevel();
FVector GetRelativeLocation(FVector2D Coords, int32 Y = 0.f);
void UpdateInputTutorial();
private:
URlGameInstance* RlGameInstance;
FRotator SpawnRotation;
FActorSpawnParameters SpawnInfo;
AStairs* CurrentStairs;
UFUNCTION()
void StartLevel(ELevelState State);
void SetLevelTileMap();
void SpawnObstacles();
void MoveActors();
FTimerHandle FadeTimerHandle;
void FadeIn(FTimerDelegate TimerDelegate);
void FadeOut();
void FadeOutCallback();
void DestroyProjectiles();
bool bTimeStarted;
};
<file_sep>// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "Blueprint/UserWidget.h"
//#include "Styling/SlateTypes.h"
#include "RlButton.generated.h"
class UButton;
class UTextBlock;
//class ;
/**
*
*/
UCLASS()
class RAGELITE_API URlButton : public UUserWidget
{
GENERATED_BODY()
public:
URlButton(const FObjectInitializer& ObjectInitializer);
UPROPERTY(VisibleAnywhere, BlueprintReadWrite, meta = (BindWidget))
UButton* Button = nullptr;
UPROPERTY(VisibleAnywhere, BlueprintReadWrite, meta = (BindWidget))
UTextBlock* TextBlock = nullptr;
UPROPERTY(EditAnywhere, BlueprintReadWrite)
FText Text;
bool IsValid();
virtual void SetIsEnabled(bool bInIsEnabled) override;
#if WITH_EDITOR
virtual void PostEditChangeProperty(FPropertyChangedEvent& PropertyChangedEvent) override;
#endif
protected:
virtual void NativeConstruct() override;
virtual void NativeOnAddedToFocusPath(const FFocusEvent& InFocusEvent) override;
virtual void NativeOnRemovedFromFocusPath(const FFocusEvent& InFocusEvent) override;
virtual void NativeOnMouseEnter(const FGeometry& InGeometry, const FPointerEvent& InMouseEvent) override;
virtual bool Initialize() override;
private:
FButtonStyle ButtonStyle;
UFUNCTION()
FText Meh();
};
<file_sep>// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "Enums.h"
#include "SpriteTextActor.generated.h"
USTRUCT()
struct FSpriteCharacter
{
GENERATED_USTRUCT_BODY()
UPROPERTY(Category = SpriteText, VisibleAnywhere)
FName Name;
UPROPERTY(Category = SpriteText, EditAnywhere)
class UPaperSprite* Sprite;
FSpriteCharacter() : Sprite(nullptr) {};
FSpriteCharacter(FName InName) : Name(InName), Sprite(nullptr) {};
};
class UPaperSprite;
UCLASS()
class RAGELITE_API ASpriteTextActor : public AActor
{
GENERATED_UCLASS_BODY()
public:
void SetText(FString InText);
private:
UPROPERTY(Category = SpriteText, VisibleAnywhere)
class USceneComponent* SceneComponent;
class USceneComponent* STSceneComponent;
UPROPERTY(Category = SpriteText, EditAnywhere/*, meta = (MultiLine = "true")*/) // Add multiLine support if needed.
FString Text;
UPROPERTY(Category = SpriteText, EditAnywhere)
int TileWidth;
UPROPERTY(Category = SpriteText, EditAnywhere)
int TileHeight;
UPROPERTY(Category = SpriteText, EditAnywhere)
EHorizontalSpriteTextAligment HorizontalAlignment;
UPROPERTY(Category = SpriteText, EditAnywhere)
EVerticalSpriteTextAligment VerticalAlignment;
UPROPERTY(Category = SpriteText, EditAnywhere)
class UMaterialInterface* Material;
// Only use one character keys
UPROPERTY(Category = SpriteText, EditAnywhere)
TMap<FString, UPaperSprite*> CharacterMap;
UPROPERTY(Category = SpriteText, VisibleAnywhere)
TArray<class UPaperSpriteComponent*> SpriteTextComponents;
int TextLenght;
void UpdateMaterial();
void UpdateSprites();
void UpdateLocationHorizontal();
void UpdateHorizontal();
void UpdateAlignment();
public:
virtual void PostLoad() override;
#if WITH_EDITOR
virtual void PostEditChangeProperty(FPropertyChangedEvent& PropertyChangedEvent) override;
#endif
};
<file_sep>// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "Blueprint/UserWidget.h"
#include "TimerManager.h"
#include "DeviceSelection.generated.h"
class UScrollBox;
class UFocusButton;
class UCanvasPanel;
class UPanelWidget;
/**
*
*/
UCLASS()
class RAGELITE_API UDeviceSelection : public UUserWidget
{
GENERATED_BODY()
public:
UDeviceSelection(const FObjectInitializer& ObjectInitializer);
virtual void NativeConstruct() override;
UPROPERTY(EditAnywhere, meta = (BindWidget))
UScrollBox* Devices;
UPROPERTY(EditAnywhere, meta = (BindWidget))
UFocusButton* Cancel;
UPROPERTY(EditAnywhere, meta = (BindWidget))
UCanvasPanel* Confirmation;
UPROPERTY(EditAnywhere, meta = (BindWidget))
UFocusButton* Yes;
UPROPERTY(EditAnywhere, meta = (BindWidget))
UFocusButton* No;
UPROPERTY(EditAnywhere, meta = (BindWidget))
UCanvasPanel* Connecting;
UPROPERTY(EditAnywhere, meta = (BindWidget))
UCanvasPanel* Failed;
FTimerHandle FailedHandle;
void Update();
void AddDevice(FString Device);
bool bTryingToConnect;
void DeviceConnectionFailed();
void ResetDeviceConnection();
protected:
virtual void NativeTick(const FGeometry& MyGeometry, float InDeltaTime) override;
private:
// MAC and life of the device
TSortedMap<FString, uint8> DevicesMap;
float AccumulatedTime;
uint8 InitialLife = 30;
void AddDeviceButton(FString Device, int32 Index = -1);
void ClearDevices();
UFUNCTION()
void OnButtonClicked(UFocusButton* Button);
void InsertChildAt(UPanelWidget* Widget, int32 Index, UWidget* Content);
UFUNCTION()
void OnCancel();
UFUNCTION()
void OnYes();
UFUNCTION()
void OnNo();
UFocusButton* LastFocusedButton;
bool bPopUp;
};
<file_sep>// Fill out your copyright notice in the Description page of Project Settings.
#include "LevelManager.h"
#include "RlGameInstance.h"
#include "Paper2D/Classes/PaperTileMap.h"
#include "Paper2D/Classes/PaperTileMapComponent.h"
#include "Paper2D/Classes/PaperTileMapActor.h"
#include "Paper2D/Classes/PaperSprite.h"
#include "Paper2D/Classes/PaperSpriteComponent.h"
#include "Paper2D/Classes/PaperSpriteActor.h"
#include "Materials/Material.h"
#include "ConstructorHelpers.h"
#include "Kismet/GameplayStatics.h"
#include "RlCharacter.h"
#include "Stairs.h"
#include "Components/BoxComponent.h"
#include "RlCharacterMovementComponent.h"
#include "RlPlayerController.h"
#include "Hazard.h"
#include "Spike.h"
#include "HazardPool.h"
#include "RlGameMode.h"
#include "Paper2D/Classes/PaperFlipbookComponent.h"
#include "RlGameInstance.h"
#include "RlSpriteHUD.h"
#include "Projectile.h"
#include "InputTutorial.h"
#include "RlGameMode.h"
#include "HearRateModule.h"
#include "WidgetManager.h"
DEFINE_LOG_CATEGORY_STATIC(LogStatus, Log, All);
ULevelManager::ULevelManager(const FObjectInitializer& ObjectInitializer)
{
CurrentLevel = nullptr;
CurrentStairs = nullptr;
HazardPool = nullptr;
CurrentLevelIndex = 0;
SpawnLocation = FVector(-208.f, -15.0f, 89.f);
SpawnRotation = FRotator(0.f);
TileSize = 16;
FadeTime = 0.5f;
static ConstructorHelpers::FObjectFinder<UMaterialInterface> MaterialRef(TEXT("/Game/Materials/MaskedUnlitSpriteMaterial"));
if (MaterialRef.Object)
{
Material = MaterialRef.Object;
}
bTimeStarted = false;
}
void ULevelManager::Init(URlGameInstance* InRlGameInstance)
{
RlGameInstance = InRlGameInstance;
RlGameInstance->OnShutdown.BindUFunction(this, FName("EndGame"));
}
UWorld* ULevelManager::GetWorld() const
{
return RlGameInstance->GetWorld();
}
UPaperSprite* ULevelManager::GetSpikeSprite() const
{
if (SpikesSprites.Num())
{
return SpikesSprites[FMath::RandRange(0, SpikesSprites.Num() - 1)];
}
return nullptr;
}
UPaperSprite* ULevelManager::GetDartSprite() const
{
if (DartsSprites.Num())
{
return DartsSprites[FMath::RandRange(0, DartsSprites.Num() - 1)];
}
return nullptr;
}
UPaperSprite* ULevelManager::GetStoneSprite() const
{
if (StonesSprites.Num())
{
return StonesSprites[FMath::RandRange(0, StonesSprites.Num() - 1)];
}
return nullptr;
}
void ULevelManager::EndGame()
{
if (CurrentLevel && !CurrentLevel->IsPendingKill())
{
CurrentLevel->Destroy();
}
CurrentLevel = nullptr;
if (InputTutorialTileMapActor && !InputTutorialTileMapActor->IsPendingKill())
{
InputTutorialTileMapActor->Destroy();
}
InputTutorialTileMapActor = nullptr;
if (CurrentStairs && !CurrentStairs->IsPendingKill())
{
//CurrentStairs->OnRlCharacterOverlapBegin.Unbind();
CurrentStairs->Destroy();
}
CurrentStairs = nullptr;
if (HazardPool && !HazardPool->IsPendingKill())
{
HazardPool->Destroy();
}
HazardPool = nullptr;
if (InputTutorial)
{
delete InputTutorial;
}
InputTutorial = nullptr;
bTimeStarted = false;
}
void ULevelManager::SetLevel(ELevelState State)
{
ARlCharacter* RlCharacter = Cast<ARlCharacter>(UGameplayStatics::GetPlayerPawn(GetWorld(), 0));
if (State == ELevelState::Start)
{
// Change to one to skip debug level
CurrentLevelIndex = 1;
RlGameInstance->Level = 1;
UE_LOG(LogStatus, Log, TEXT("Current Level: %i"), CurrentLevelIndex);
}
if (State == ELevelState::Next)
{
++CurrentLevelIndex;
UE_LOG(LogStatus, Log, TEXT("Current Level: %i"), CurrentLevelIndex);
UE_LOG(LogStatus, Log, TEXT("Deaths: %i"), RlGameInstance->Deaths);
UE_LOG(LogStatus, Log, TEXT("Time: %i"), RlGameInstance->Time);
}
if (CurrentLevelIndex < Levels.Num())
{
if (CurrentLevelIndex == 1)
{
RlCharacter->bRunEnabled = false;
RlCharacter->bJumpEnabled = false;
RlCharacter->bLongJumpEnabled = false;
RlCharacter->bWallWalkEnabled = false;
}
if (CurrentLevelIndex == 2)
{
RlCharacter->bRunEnabled = true;
}
if (CurrentLevelIndex == 3)
{
RlCharacter->bJumpEnabled = true;
}
if (CurrentLevelIndex == 4)
{
RlCharacter->bLongJumpEnabled = true;
}
if (CurrentLevelIndex == 5)
{
RlCharacter->bWallWalkEnabled = true;
}
if (CurrentLevelIndex == 6)
{
if (ARlGameMode* GameMode = Cast<ARlGameMode>(GetWorld()->GetAuthGameMode()))
{
if (GameMode->HeartRateModule->bCalibration)
{
GameMode->HeartRateModule->EndCalibration();
}
}
}
if (CurrentLevelIndex == Levels.Num() - 1)
{
// Disable input
// Hide character
// Show last picture
RlGameInstance->WidgetManager->EndGame();
}
FTimerDelegate TimerDelegate;
TimerDelegate.BindUFunction(this, FName("StartLevel"), State);
FadeIn(TimerDelegate);
}
else
{
--CurrentLevelIndex;
// Finished game
}
}
void ULevelManager::RestartLevel()
{
SetLevel(ELevelState::Reset);
}
void ULevelManager::SetLevelTileMap()
{
if (Levels[CurrentLevelIndex].PaperTileMap && CurrentLevel)
{
CurrentLevel->GetRenderComponent()->SetTileMap(Levels[CurrentLevelIndex].PaperTileMap);
}
}
void ULevelManager::SpawnObstacles()
{
int32 SpikesNum = 0;
int32 DartsNum = 0;
int32 StonesNum = 0;
for (auto HazardsData : Levels[CurrentLevelIndex].Hazards)
{
if (HazardsData.HazardsType == EHazardType::Spikes)
{
SpikesNum += HazardsData.Num();
}
else if (HazardsData.HazardsType == EHazardType::Darts)
{
DartsNum += HazardsData.Num();
}
else if (HazardsData.HazardsType == EHazardType::Stones)
{
StonesNum += HazardsData.Num();
}
}
// We have to check the correct amount of spikes
while (SpikesNum > HazardPool->Spikes.Num())
{
//HazardPool->AddSpikesUntil(Spikes);
HazardPool->AddSpikes(HazardPool->InitialSpikes);
}
while (DartsNum > HazardPool->Darts.Num())
{
HazardPool->AddDarts(HazardPool->InitialDarts);
}
while (StonesNum > HazardPool->Stones.Num())
{
HazardPool->AddStones(HazardPool->InitialStones);
}
}
void ULevelManager::MoveActors()
{
// Move RlCharacter
ARlCharacter* RlCharacter = Cast<ARlCharacter>(UGameplayStatics::GetPlayerPawn(GetWorld(), 0));
RlCharacter->GetRlCharacterMovement()->StopActiveMovement();
RlCharacter->GetRlCharacterMovement()->bJustTeleported = true;
RlCharacter->SetActorLocation(GetRelativeLocation(Levels[CurrentLevelIndex].Start) - FVector(0.f, 0.f, 4.f));
CurrentStairs->SetActorLocation(GetRelativeLocation(Levels[CurrentLevelIndex].Stairs, -10.f));
HazardPool->ResetHazards(Levels[CurrentLevelIndex].Hazards);
}
void ULevelManager::UpdateInputTutorial()
{
ARlCharacter* RlCharacter = Cast<ARlCharacter>(UGameplayStatics::GetPlayerPawn(GetWorld(), 0));
InputTutorial->Update(CurrentLevelIndex, RlCharacter->bIsUsingGamepad);
}
FVector ULevelManager::GetRelativeLocation(FVector2D Coords, int32 Y)
{
return FVector(SpawnLocation.X + Coords.X * TileSize, Y, SpawnLocation.Z - Coords.Y * TileSize/* + 4.f*/);
}
void ULevelManager::StartLevel(ELevelState State)
{
if (State == ELevelState::Start)
{
EndGame();
//CurrentLevelIndex = 0;
CurrentStairs = GetWorld()->SpawnActor<AStairs>(GetRelativeLocation(Levels[CurrentLevelIndex].Stairs, -10.f), SpawnRotation, SpawnInfo);
UPaperSpriteComponent* CurrentStairsRC = CurrentStairs->GetRenderComponent();
CurrentStairsRC->SetSprite(StairsSprite);
CurrentStairsRC->SetMaterial(0, Material);
CurrentLevel = GetWorld()->SpawnActor<APaperTileMapActor>(SpawnLocation + FVector(-8.f, 0.f, 8.f), SpawnRotation, SpawnInfo);
CurrentLevel->GetRenderComponent()->SetMaterial(0, Material);
InputTutorialTileMapActor = GetWorld()->SpawnActor<APaperTileMapActor>(SpawnLocation + FVector(-8.f, 14.f, 0.f), SpawnRotation, SpawnInfo);
InputTutorialTileMapActor->GetRenderComponent()->SetMaterial(0, Material);
HazardPool = GetWorld()->SpawnActor<AHazardPool>(FVector::ZeroVector, SpawnRotation, SpawnInfo);
InputTutorial = NewObject<UInputTutorial>();
InputTutorial->Init(InputTutorialTileMapActor, InputTutorialTileMaps, RlGameInstance);
}
if (State != ELevelState::Reset)
{
SetLevelTileMap();
SpawnObstacles();
}
if (State == ELevelState::Next)
{
if (ARlSpriteHUD* RlSHUD = RlGameInstance->RlSpriteHUD)
{
RlSHUD->IncreaseLevel();
}
}
DestroyProjectiles();
MoveActors();
UpdateInputTutorial();
ARlCharacter* RlCharacter = Cast<ARlCharacter>(UGameplayStatics::GetPlayerPawn(GetWorld(), 0));
if (RlCharacter->bDeath)
{
RlCharacter->bDeath = false;
RlCharacter->GetSprite()->ToggleVisibility();
}
FadeOut();
}
void ULevelManager::FadeIn(FTimerDelegate TimerDelegate)
{
if (ARlPlayerController* RlPlayerController = Cast<ARlPlayerController>(UGameplayStatics::GetPlayerController(GetWorld(), 0)))
{
RlPlayerController->FadeInBack(FadeTime / 2.f);
//RlPlayerController->SetIgnoreMoveInput(true);
GetWorld()->GetTimerManager().SetTimer(FadeTimerHandle, TimerDelegate, FadeTime / 2.f, false);
}
}
void ULevelManager::FadeOut()
{
if (ARlPlayerController* RlPlayerController = Cast<ARlPlayerController>(UGameplayStatics::GetPlayerController(GetWorld(), 0)))
{
RlPlayerController->FadeOutBack(FadeTime / 2.f);
}
GetWorld()->GetTimerManager().SetTimer(FadeTimerHandle, this, &ULevelManager::FadeOutCallback, FadeTime / 2.f, false);
}
void ULevelManager::FadeOutCallback()
{
if (ARlPlayerController* RlPlayerController = Cast<ARlPlayerController>(UGameplayStatics::GetPlayerController(GetWorld(), 0)))
{
RlPlayerController->SetIgnoreMoveInput(false);
}
if (!bTimeStarted)
{
if (ARlGameMode* GameMode = Cast<ARlGameMode>(GetWorld()->GetAuthGameMode()))
{
GameMode->bGameStarted = true;
bTimeStarted = true;
}
}
ARlCharacter* RlCharacter = Cast<ARlCharacter>(UGameplayStatics::GetPlayerPawn(GetWorld(), 0));
RlCharacter->bInvincible = false;
}
void ULevelManager::DestroyProjectiles()
{
TArray<AActor*> Projectiles;
UGameplayStatics::GetAllActorsOfClass(GetWorld(), AProjectile::StaticClass(), Projectiles);
for (AActor* Projectile : Projectiles)
{
Projectile->Destroy();
}
}<file_sep>// Fill out your copyright notice in the Description page of Project Settings.
#include "Stone.h"
#include "Paper2D/Classes/PaperSpriteComponent.h"
AStone::AStone()
{
UPaperSpriteComponent* InRenderComponent = GetRenderComponent();
InRenderComponent->SetGenerateOverlapEvents(false);
InRenderComponent->SetCollisionProfileName(FName("BlockAllDynamic"));
}
void AStone::Move(FVector Location, EHazardLocation HazardLocation)
{
float HazardSize = TileSize / 2;
float HalfHazardSize = HazardSize / 2;
Location.X -= HalfHazardSize;
Location.Z += HalfHazardSize;
switch (HazardLocation)
{
case EHazardLocation::T0:
case EHazardLocation::T1:
case EHazardLocation::B2:
case EHazardLocation::B3:
case EHazardLocation::R0:
case EHazardLocation::R1:
case EHazardLocation::R2:
case EHazardLocation::R3:
Location.X += HazardSize;
break;
default:
break;
}
switch (HazardLocation)
{
case EHazardLocation::R0:
case EHazardLocation::R1:
case EHazardLocation::L2:
case EHazardLocation::L3:
case EHazardLocation::B0:
case EHazardLocation::B1:
case EHazardLocation::B2:
case EHazardLocation::B3:
Location.Z -= HazardSize;
break;
default:
break;
}
SetActorLocationAndRotation(Location, FRotator(0.f));
}
<file_sep>#include "SFocusButton.h"
FReply SFocusButton::OnFocusReceived(const FGeometry& MyGeometry, const FFocusEvent& InFocusEvent)
{
auto Reply = SWidget::OnFocusReceived(MyGeometry, InFocusEvent);
OnFocused.ExecuteIfBound();
return Reply;
}
void SFocusButton::OnFocusLost(const FFocusEvent& InFocusEvent)
{
SWidget::OnFocusLost(InFocusEvent);
OnUnfocused.ExecuteIfBound();
}
<file_sep>#pragma once
UENUM()
enum class EHorizontalSpriteTextAligment
{
Left,
Center,
Right
};
UENUM()
enum class EVerticalSpriteTextAligment
{
Top,
Center,
Bottom
};
<file_sep>// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "Hazard.h"
#include "Stone.generated.h"
/**
*
*/
UCLASS()
class RAGELITE_API AStone : public AHazard
{
GENERATED_BODY()
public:
AStone();
void Move(FVector Location, EHazardLocation HazardLocation) override;
};
<file_sep>// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "UObject/NoExportTypes.h"
#include "RLTypes.generated.h"
class UPaperTileMap;
UENUM()
enum class ELevelState : uint8
{
Start,
Next,
Reset
};
UENUM(Meta = (Bitflags))
enum class EHazardLocation : int32
{
// Bottom
B0,
B1,
B2,
B3,
// Right
R0,
R1,
R2,
R3,
// Top
T0,
T1,
T2,
T3,
// Left
L0,
L1,
L2,
L3
};
UENUM()
enum class EHazardType : uint8
{
Spikes,
Darts,
Stones
};
USTRUCT()
struct FHazardsData
{
GENERATED_BODY()
FHazardsData();
// 2D coordintes on the grid
UPROPERTY(EditAnywhere)
FVector2D Coords;
// Difficulty of all the hazards
UPROPERTY(EditAnywhere)
float DifficultyFactor;
UPROPERTY(EditAnywhere, Meta = (Bitmask, BitmaskEnum = "EHazardLocation"))
int32 HazardsLocations;
UPROPERTY(EditAnywhere)
EHazardType HazardsType;
int32 Num() const;
// Darts
UPROPERTY(EditAnywhere)
float DartsDelay;
UPROPERTY(EditAnywhere)
float DartsCooldown;
UPROPERTY(EditAnywhere)
float DartsSpeed;
UPROPERTY(EditAnywhere)
bool bSpawnsFrom;
};
USTRUCT()
struct FRlLevel
{
GENERATED_BODY()
UPROPERTY(EditAnywhere, Category = "Levels|Level")
UPaperTileMap* PaperTileMap;
UPROPERTY(EditAnywhere, Category = "Levels|Level")
FVector2D Start;
UPROPERTY(EditAnywhere, Category = "Levels|Level")
FVector2D Stairs;
UPROPERTY(EditAnywhere, Category = "Levels|Level")
TArray<FHazardsData> Hazards;
};<file_sep>// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "Input/SButton.h"
class RAGELITE_API SFocusButton : public SButton
{
public:
FSimpleDelegate OnFocused;
FSimpleDelegate OnUnfocused;
virtual FReply OnFocusReceived(const FGeometry& MyGeometry, const FFocusEvent& InFocusEvent) override;
virtual void OnFocusLost(const FFocusEvent& InFocusEvent) override;
};
|
69928dba471bce4462a57656b96a4886d2dacac0
|
[
"Markdown",
"C",
"C++"
] | 55
|
C++
|
elixs/Ragelite
|
117e0f0f446c9d3fe402ae53f01533ac81fcb97b
|
9a12ddcaa857a99de00393e5764dc60e7fef9b0b
|
refs/heads/master
|
<repo_name>EncryptedCow/phaser3-ts-boilerplate<file_sep>/src/Game.ts
import * as Phaser from "phaser";
import * as Scenes from "./Scenes";
const config: GameConfig = {
type: Phaser.AUTO,
backgroundColor: "#6495ED",
scene: [Scenes.Scene1]
}
window.addEventListener("load", () => {
const game = new Phaser.Game(config);
});
<file_sep>/README.md
# Phaser 3 TypeScript Boilerplate
A simple Phaser 3 TS boilerplate project, using v3.16.1.
### Install
```
git clone https://github.com/EncryptedCow/phaser3-ts-boilerplate.git my-project
cd my-project
npm install
```
### Development
```
npm run dev
```
### Build
```
npm run build:prod
```
OR
```
npm run build:dev
```
### Notes
The phaser npm module is not included in package.json and is instead loaded from the CDN in **www/index.html**, the **webpack.common.js** config 'externals' property is set to reflect this.
If you wish to include the phaser package in your build you can use the following command:
```
npm install phaser@3.16
```
Then remove the phaser script tag from **www/index.html**, and remove the externals property from **webpack.common.js**<file_sep>/src/Scenes/Scene1.ts
import { Scene } from "phaser";
export class Scene1 extends Scene {
constructor() {
super("Scene1");
}
preload() {
this.load.setBaseURL("textures/");
this.load.image("star", "star.png");
}
create() {
const scale = this.game.scale;
this.add.image(scale.width / 2, scale.height / 2, "star");
}
update(time: number, dt: number) {
}
}
|
62d8c628a9f41af42fbf3e4e04afbf1f65c1fe4b
|
[
"Markdown",
"TypeScript"
] | 3
|
TypeScript
|
EncryptedCow/phaser3-ts-boilerplate
|
72ca4febd1471f62cd6bb7e6d7cfb1ad48a119fc
|
da827399cc11b485a46e5d11c6efb1fc92d2099c
|
refs/heads/master
|
<file_sep>import axios from 'axios';
export const getPokemonList = () => {
// In real life, API URL should be declared in another file :)
return axios.get('https://pokeapi.co/api/v2/ability/')
.then((response) => {
return response.data;
})
.catch((error) => {
return error;
});
}<file_sep>import React from 'react';
import * as PokemonAPI from '../api/PokemonAPI';
class Pokemon extends React.Component {
state = {
pokemonList: null
}
componentDidMount() {
PokemonAPI.getPokemonList()
.then((pokemonList) => {
this.setState(() => ({
pokemonList: pokemonList
}));
});
}
render() {
if (this.state.pokemonList === null) {
return (<div>Loading...</div>);
}
return (
<div>
{
this.state.pokemonList.results.map((pokemon) => {
return (
<div key={pokemon.name}>{pokemon.name}</div>
)
})
}
</div>
);
}
}
export default Pokemon;<file_sep>## React - API call - external file
[](https://www.magicweb.pl)
Simple example of React and extract API call to external file.
### Installation:
Please clone/download repository and run:
```sh
npm install
npm start
```
---
### Article:
<https://www.magicweb.pl/programowanie/frontend/react/request-api-w-oddzielnym-pliku/> (Polish language)
|
0197e97ab3369fda26e30bdc19d748641b7f1247
|
[
"JavaScript",
"Markdown"
] | 3
|
JavaScript
|
magicwebpl/react-api-call-external-file
|
b4dbbe5e9de0b4da742df4d88bc0214034f1575d
|
bd6b53f61fbb7d1db964b1605591bccc848aa96c
|
refs/heads/master
|
<file_sep>#include<iostream>
using namespace std;
int countBits(int n){
int counter=0;
while(n){
n &= (n-1);
counter++;
}
return counter;
}
unsigned int solve(int a, int b){
unsigned int ctr = 0;
for(int i=a; i<=b; i++){
ctr += countBits(i);
}
return ctr;
}
int main(void) {
int q,a,b; cin>>q;
while(q--){
cin>>a>>b;
cout<<solve(a, b)<<"\n";
}
return 0;
}
<file_sep>#include<iostream>
#include<math.h>
#include<cstring>
using namespace std;
char *mystrtok(char str[], char delimiter){
static char *input = NULL;
if(str!=NULL){
input = str;
}
if(input == NULL)
return NULL;
char *output = new char[strlen(input) + 1];
int i;
for(i=0;input[i]!='\0';i++){
if(input[i]!=delimiter)
output[i] = input[i];
else{
output[i] = '\0';
input = input + i + 1;
return output;
}
}
input = NULL;
output[i] = '\0';
return output;
}
int main(void) {
char str[] = "Hello, I am: Ak";
char *ptr = mystrtok(str,',');
while(ptr!=NULL){
cout<<ptr<<"\n";
ptr = mystrtok(NULL,',');
}
return 0;
}
<file_sep>#include<iostream>
#include<stdio.h>
#include<cstring>
using namespace std;
unsigned int length = 0;
class node{
public:
int data;
node* next;
///constructor
node(int value):data(value),next(NULL){}
};
void insertHead(node* &head, int data){
length++;
node* newNode = new node(data);
if(head != NULL){
newNode -> next = head;
node* temp = head;
while( temp->next != head ){
temp = temp -> next;
}
temp -> next = newNode;
head = newNode;
}
else{
head = newNode;
newNode -> next = newNode;
}
}
void print(node* head){
unsigned int i = 0;
while( (i++) != length ){
cout << head->data<<" -> ";
head = head->next;
}
}
void build(node* &head){
int data ; cin >> data ;
while( data!= -1 ){
insertHead(head, data) ;
cin >> data ;
}
}
istream& operator >> (istream &is, node* &head){
build(head);
return is;
}
ostream& operator << (ostream &os, node* &head){
print(head);
return os;
}
bool FloydCycle(node* head){
if(head == NULL)
return false;
node* slow = head;
node* fast = head;
while( fast != NULL && fast->next != NULL ){
fast = fast -> next -> next ;
slow = slow -> next;
if(fast == slow)
return true;
}
return false;
}
int32_t main(void){
node* head = NULL;
cin>>head;
cout<<head<<"\n";
// cout<<"Enter number to delete: ";
// int key; cin>>key;
// deleteNode(head, key);
// cout<<"\n"<<head;
return 0;
}
<file_sep>#include<iostream>
#include<stdio.h>
#include<cstring>
using namespace std;
class node{
public:
int data;
node* next;
///constructor
node(int value):data(value),next(NULL){}
};
void insertHead(node* &head, int data){
node* newNode = new node(data);
newNode->next = head;
head = newNode;
}
void print(node* head){
while(head!=NULL){
cout << head->data<<" -> ";
head = head->next;
}
}
void build(node* &head){
int data ; cin >> data ;
while( data!= -1 ){
insertHead(head, data) ;
cin >> data ;
}
}
istream& operator >> (istream &is, node* &head){
build(head);
return is;
}
ostream& operator << (ostream &os, node* &head){
print(head);
return os;
}
node* mergeLL(node* a, node* b){
if( a == NULL ){
return b;
}
else if( b == NULL ){
return a;
}
node* c;
if( a->data < b->data ){
c = a;
c->next = mergeLL(a->next, b);
}
else{
c = b;
c -> next = mergeLL(a, b -> next);
}
return c;
}
int32_t main(void){
node* head = NULL;
node* head2 = NULL;
cin>>head>>head2;
cout<<head<<endl<<head2;
head = mergeLL(head, head2);
cout<<head<<"\n";
return 0;
}
<file_sep>#include<iostream>
#include<vector>
using namespace std;
class Student{
public:
int marks;
string name;
Student() : marks(), name() {
cin>>marks;
cin>>name;
}
};
void bucketSort(Student arr[], int n){
///Assuming the maximum marks is 100:
vector<Student> v[101];
int marks;
for(int i=0; i<n; i++){
marks = arr[i].marks;
v[marks].push_back(arr[i]);
}
for(int i=100; i>=0; i--){
for(vector<Student>::iterator it = v[i].begin(); it != v[i].end(); it++){
cout<<(*it).name<<" "<<(*it).marks<<"\n";
}
}
}
int32_t main(void){
int n; cin>>n;
Student arr[n];
// for(int i=0; i<n; i++){
// cin>>arr[i].marks;
// cin>>arr[i].name;
// }
bucketSort(arr, n);
return 0;
}
<file_sep>#include<iostream>
#include<limits.h>
using namespace std;
int main(void) {
int n,t; cin>>t;
while(t--){
int res=0;
cin>>n;
int arr[n];
for(int i=0; i<n; cin>>arr[i++]);
int mx = INT_MIN;
int curr = 0;
for(int i=0; i<n; i++){
curr+=arr[i];
if(curr < 0){
curr = 0;
//i++;
}
else if(curr > mx){
mx = curr;
}
}
cout<<mx<<"\n";
}
return 0;
}
<file_sep>#include<iostream>
#include<math.h>
#include<cstring>
using namespace std;
int main(void) {
bool flag = false;
int arr [4][4]= {{1,4,8,10}, {2,5,9,15}, {6, 16, 18, 20}, {11, 17, 19, 23} };
int k = 23;
for(int i=0,j=3; ;){
//cout<<"I :: "<<i<<" J:: "<<j<<"\n";
if(i<0 || j<0 || j>3 || i>3){
break;
}
if(arr[i][j] == k){
cout<<"Found!\n";
flag = true;
break;
}
else if (k>arr[i][j])
i++;
else if (k<arr[i][j])
j--;
}
if(!flag)
cout<<"Not Found\n";
return 0;
}
<file_sep>#include<iostream>
using namespace std;
int fastPower(int x, int y){
if( y==0 ){
return 1;
}
int halfAns = fastPower(x, y/2);
halfAns *= halfAns;
if(y&1){
return x*halfAns;
}
return halfAns;
}
int32_t main(void){
int x,y; cin>>x>>y;
cout<<fastPower(x, y);
return 0;
}
<file_sep>#include<iostream>
#include<cstring>
using namespace std;
void solve(char *input, char *op, int i, int j, char prev){
if( input[i] == '\0' ){
op[j] = '\0';
cout<<op<<"\n";
return;
}
if( prev == input[i] )
return solve(input, op, i+1, j, input[i]);
op[j] = input[i];
return solve(input, op, i+1, j+1, input[i]);
}
int main(void) {
// char input[1005];
// char op[1005];
// cin>>input;
// op[0] = input[0];
// solve(input, op, 1, 1, input[0]);
string s; cin>>s;
cout<<s.substr(1);
return 0;
}
<file_sep>//#include<iostream>
//#include<map>
//using namespace std;
//int main(void) {
// string s; cin>>s;
// map <char,int> mp;
// for(int i=0; i<(int)s.size(); i++)
// mp[s[i]]++;
// for(auto i : mp)
// cout<<i.first<<i.second;
// return 0;
//}
#include<iostream>
//#include<map>
using namespace std;
int main(void) {
string s; cin>>s;
int arr[26] = {0};
for(int i=0; i<(int)s.size(); i++){
arr[s[i] - 'a']++;
}
for(int i=0; i<26; i++)
if(arr[i]>0)
cout<<(char)(i + 'a')<<arr[i];
return 0;
}
<file_sep>#include<iostream>
using namespace std;
class Car{
private:
int price;
string name;
public:
///Setters:
void setPrice(int p){
price = p;
}
void setName(string s){
name = s;
}
///Getters:
int getPrice(){
return price;
}
string getName(){
return name;
}
};
int32_t main(void){
Car a;
int price; cin>>price;
string name; cin>>name;
a.setPrice(price);
a.setName(name);
cout<<a.getPrice()<<"\n";
cout<<a.getName()<<"\n";
return 0;
}
<file_sep>#include<iostream>
#include<cstring>
using namespace std;
class Car{
private:
int price;
public:
char* name;
Car(){
}
///DEEP Copy constructor
Car(Car &x){
price = x.price;
name = new char[strlen(x.name) + 1];
strcpy(name, x.name);
}
///Setters:
void setPrice(int p){
if( p < 1000 )
throw invalid_argument{"\nPrice cannot be less than 1000"};
price = p;
}
void setName(char* s){
name = s;
}
///Getters:
int getPrice(){
return price;
}
char* getName(){
return name;
}
};
int32_t main(void){
Car a;
int price; cin>>price;
char name[20]; cin>>name;
a.setPrice(price);
a.setName(name);
cout<<a.getPrice()<<"\n";
cout<<a.getName()<<"\n";
Car b = a;
b.name[0] = 'h';
cout<<"\nPRINTING AGAIN\n";
cout<<a.getPrice()<<"\n";
cout<<a.getName()<<"\n";
cout<<b.getPrice()<<"\n";
cout<<b.getName()<<"\n";
return 0;
}
<file_sep>#include<iostream>
#include<math.h>
#define ll long long
using namespace std;
ll solve(ll n, ll k){
ll s=0, ed = n;
ll mid,ans;
while(s<=ed){
mid = (s+ed)/(ll)(pow(2,k) + 0.5);
cout<<"MID:: "<<mid<<"\n";
cout<<"POW:: "<<(ll)(pow(mid,k) + 0.5)<<"\n";
if((ll)(pow(mid,k) + 0.5) == n){
ans = mid;
break;
}
else if( (ll)(pow(mid,k) + 0.5) > n )
ed = mid - 1;
else if( (ll)(pow(mid,k) + 0.5) < n ){
ans = mid;
s = mid + 1;
}
}
return ans;
}
int main(void) {
ll t,n,k; cin>>t;
while(t--){
cin>>n>>k;
cout<<solve(n,k)<<"\n";
}
return 0;
}
<file_sep>#include <iostream>
#define free_from_GS 1
#define In_formals 1
using namespace std;
int main(){
if(free_from_GS)
cout<< ((In_formals) ? "To Reading room" : "To 2C 186");
}
//#include<iostream>
//#include<math.h>
//using namespace std;
//int main(void) {
// char ch; long int n1,n2;
// while(true){
// cin>>ch;
// switch(ch){
// case '*' : cin>>n1>>n2;
// cout<<n1*n2<<"\n";
// break;
// case '/' : cin>>n1>>n2;
// cout<<n1/n2<<"\n";
// break;
// case '+' : cin>>n1>>n2;
// cout<<n1+n2<<"\n";
// break;
// case '-' : cin>>n1>>n2;
// cout<<n1-n2<<"\n";
// break;
// case '%' : cin>>n1>>n2;
// cout<<n1%n2<<"\n";
// break;
// case 'x' : exit(0);
// break;
// case 'X' : exit(0);
// break;
// default : cout<<"Invalid operation. Try again.\n";
// }
// }
// return 0;
//}
<file_sep>#include <iostream>
#include <unordered_map>
#include <algorithm>
using namespace std;
int main(void){
int n,k; cin>>n;
int arr[n];
unordered_map<int, int> m;
//Take input
for(int i=0;i<n;i++){
cin>>arr[i];
m[arr[i]]++;
}
sort(arr,arr+n);
//Key input
cin>>k;
for(int i=0;i<n;i++){
if( m.find(k-arr[i]) != m.end() ){
cout<<arr[i]<<" and "<<k-arr[i]<<"\n";
m.erase(arr[i]);
}
}
return 0;
}
<file_sep>#include<iostream>
#include<cstring>
using namespace std;
class node{
public:
int data;
node* next;
///constructor
node(int value):data(value),next(NULL){}
};
void insertHead(node* &head, int value);
void print(node *head){
while (head != NULL){
cout<<head->data<<"-> ";
head = head->next;
}
}
void insertHead(node* &head, int value){
node* temp = new node(value);
temp->next = head;
head = temp;
}
int32_t main(void){
node* head = NULL;
insertHead(head, 10);
insertHead(head, 20);
insertHead(head, 30);
print(head);
return 0;
}
<file_sep>#include<iostream>
using namespace std;
bool solve(int arr[], int start, int end){
if(start>=end)
return true;
if( arr[start] == arr[end] )
solve(arr, start + 1, end - 1);
else
return false;
}
int main(void) {
int n; cin>>n;
int arr[n];
for(int i=0; i<n; cin>>arr[i++]);
if( solve(arr, 0, n-1) )
cout<<"true\n";
else
cout<<"false\n";
return 0;
}
<file_sep>#include<iostream>
#include<math.h>
using namespace std;
int firstSetBit(int n){
return log2( n & -n) + 1;
}
int main(void) {
int n,tmp=0,ans,mask,toCheckBit,x,y,i; cin>>n;
int arr[n];
for(i=0; i<n; i++){
cin>>arr[i];
tmp ^= arr[i];
}
toCheckBit = firstSetBit(tmp);
ans = 0;
mask = 1<<toCheckBit;
for(i=0; i<n; i++){
if( arr[i] & mask != 0)
ans ^= arr[i];
}
x = ans;
y = tmp^x;
cout<<min(x,y)<<" "<<max(x,y);
return 0;
}
<file_sep>#include<iostream>
using namespace std;
int main(void) {
int n; cin>>n; int arr[n];
for(int i=0;i<n;cin>>arr[i++]);
//Generating sub arrays :
for(int i=0;i<n;i++)
for(int j=i;j<n;j++){
for(int k=i;k<=j;k++)
cout<<arr[k]<<" ";
cout<<"\n";
}
return 0;
}
<file_sep>#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
bool cmp(string a, string b){
if( a.find(b) != string::npos || b.find(a) != string::npos )
return a.length() > b.length();
else
return a<b;
}
int main(void) {
int n; cin>>n;
vector<string> v(n);
for(int i = 0; i<n; cin>>v[i++]);
sort(v.begin(), v.end(), cmp);
for(int i=0; i<n; cout<<v[i++]<<"\n");
return 0;
}
<file_sep>#include<iostream>
#include<cstring>
using namespace std;
class node{
public:
int data;
node* next;
///constructor
node(int value):data(value),next(NULL){}
};
void insertHead(node* &head, int data){
node* newNode = new node(data);
newNode->next = head;
head = newNode;
}
void print(node* head){
while(head!=NULL){
cout << head->data<<" -> ";
head = head->next;
}
}
void build(node* &head){
int data ; cin >> data ;
while( data!= -1 ){
insertHead(head, data) ;
cin >> data ;
}
}
istream& operator >> (istream &is, node* &head){
build(head);
return is;
}
ostream& operator << (ostream &os, node* &head){
print(head);
return os;
}
int32_t main(void){
node* head = NULL;
cin>>head;
cout<<head;
return 0;
}
<file_sep>#include<iostream>
#define ll long long
using namespace std;
ll fastExponentiation(ll x, ll y){
ll ans = 1;
while(y){
if(y&1)
ans *= x;
x *= x;
y >>= 1;
}
return ans;
}
int32_t main(void){
ll x,y; cin>>x>>y;
cout<<fastExponentiation(x, y)<<"\n";
return 0;
}
<file_sep>#include<iostream>
using namespace std;
int iterativeCount(int n){
int ans = 0;
while(n){
ans += (n&1);
n = n>>1;
}
return ans;
}
unsigned int brainKernighans(int n){
unsigned int ctr = 0;
while(n){
n &= (n-1);
ctr++;
}
return ctr;
}
int main(void) {
int n; cin>>n;
cout<<"Iterative Method: "<<iterativeCount(n);
cout<<"\nBrian Kernighan's Method: "<<brainKernighans(n);
cout<<"\nGCC: "<<__builtin_popcount(n);
return 0;
}
<file_sep># CB
DSA Practice from Coding blocks (C++ Interview Prep)
<file_sep>#include <iostream>
using namespace std;
int solve(int arr[], int n, int key){
int s = 0, ed = n-1;
int mid;
while(s<=ed){
mid = (s+ed)/2;
if(arr[mid] == key)
return mid+1;
else if(arr[mid] > key)
ed = mid-1;
else if(arr[mid] < key)
s = mid+1;
}
if(s>ed)
cout<<"Key Not present in the array!",exit(0);
}
int main(void){
int n; cin>>n;
int arr[n];
for(int i=0; i<n; cin>>arr[i++]);
int key; cin>>key;
cout<<solve(arr,n,key)<<"\n";
return 0;
}
<file_sep>#include<iostream>
using namespace std;
void Merge( int *arr, int s, int e ){
int mid = ( s + e )/2;
int i = s;
int j = mid+1;
int k = s;
int temp[100];
while( i <= mid && j <= e ){
if( arr[i] < arr[j] )
temp[k++] = arr[i++];
else if( arr[i] > arr[j] )
temp[k++] = arr[j++];
}
while( i<=mid )
temp[k++] = arr[i++];
while( j<=e )
temp[k++] = arr[j++];
}
void mergeSort( int *arr, int s, int e ){
if( s>=e )
return;
int mid = (s+e)/2;
mergeSort( arr, s, mid );
mergeSort( arr, mid+1, e );
Merge( arr, s, e );
}
int32_t main(void){
int n; cin>>n;
int *arr = (int *)malloc(n*sizeof(int));
for(int i=0; i<n; cin>>arr[i++]);
mergeSort(arr ,0, n);
for(int i=0; i<n; cout<<arr[i++]<<" ");
delete(arr);
return 0;
}
<file_sep>#include<iostream>
using namespace std;
void Merge( int *arr, int s, int e ){
int mid = ( s + e )/2;
int i = s;
int j = mid+1;
int k = s;
int temp[100];
while( i <= mid && j <= e ){
if( arr[i] <= arr[j] )
temp[k++] = arr[i++];
else
temp[k++] = arr[j++];
}
while( i<=mid )
temp[k++] = arr[i++];
while( j<=e )
temp[k++] = arr[j++];
for(int i=s; i<=e; arr[i] = temp[i++]);
}
void mergeSort( int *arr, int s, int e ){
if( s>=e )
return;
int mid = (s+e)/2;
mergeSort( arr, s, mid );
mergeSort( arr, mid+1, e );
Merge( arr, s, e );
}
int32_t main(void){
int n; cin>>n;
int *arr = (int *)malloc(n*sizeof(int));
for(int i=0; i<n; cin>>arr[i++]);
mergeSort(arr ,0, n-1);
for(int i=0; i<n; cout<<arr[i++]<<" ");
delete(arr);
return 0;
}
//
//#include<bits/stdc++.h>
//using namespace std;
//struct node
//{
//int key;
//struct node *left;
//struct node * right;
//};
//struct node *push(int ndata){
// struct node* newnode=(struct node*)malloc(sizeof(struct node));
// newnode->key=ndata;
// newnode->right=newnode->left=NULL;
// return newnode;
//}
//struct node *insert(struct node* temp,int key)
// {
// if(temp==NULL)
// return push(key);
// if(temp->key>key)
// temp->left=insert(temp->left,key);
// else if(temp->key<key)
// temp->right=insert(temp->right,key);
//
// return temp;
// }
//
//struct node* inorder(struct node *head)
//{
// if(head!=NULL)
// {
// inorder(head->left);
// cout<<head->key<<"\n";
// inorder(head->right);
// }
//
//}
//
//int main()
//{
// int n,n1;
// cin>>n;
// struct node *head=NULL;
// for(int i=0;i<n;i++)
// {
//
// cin>>n1;
// head = insert(head,n1);
// }
// inorder(head);
// return 0;
//
//}
<file_sep>#include <iostream>
using namespace std;
unsigned int length = 0;
class node{
public:
int data;
node* next;
///constructor
node(int value):data(value),next(NULL){}
};
void insertAtTail(node* &head, int data){
if(!head){
node* newNode = new node(data);
head = newNode;
}
else{
node* temp = head;
while(temp->next != NULL){
temp = temp->next;
}
node* newNode = new node(data);
temp->next = newNode;
}
}
void print(node* head){
while(head!=NULL){
cout << head->data<<" -> ";
head = head->next;
}
}
void build(node* &head){
int data ;
int n = length;
while( n-- ){
cin >> data ;
insertAtTail(head, data) ;
}
}
istream& operator >> (istream &is, node* &head){
build(head);
return is;
}
ostream& operator << (ostream &os, node* &head){
print(head);
return os;
}
node* appendK(node *head,int k){
node *oldHead = head;
node *fast = head;
node *slow = head;
for(long i=0;i < k && fast->next!=NULL ;i++){
fast = fast->next;
}
while(fast->next!=NULL && fast!=NULL){
fast = fast->next;
slow = slow->next;
}
node *newHead = slow->next;
slow->next = NULL;
fast->next = oldHead;
return newHead;
}
int32_t main(void){
int k ; cin >> length ;
node* head = NULL;
cin >> head >> k;
head = appendK(head, k);
cout<<head;
return 0 ;
}
<file_sep>#include<iostream>
using namespace std;
int main(void) {
int k; cin>>k;
string s; cin>>s;
int max_for_one=0,max_overall=0;
int ctr = 0;
for(int j=0; j<(int)s.size(); j++){
if(s[j] == 'a'){
for(int i=j; i<(int)s.size(); i++){
if(s[i] == 'a'){
ctr++;
continue;
}
else{
if(ctr<=k){
ctr++;
//max_for_one = max(max_for_one, ctr);
}
}
}
}
max_overall = max(max_overall, ctr);
ctr = 0;
//max_for_one=0;
}
max_for_one = 0, ctr = 0;
for(int j=0; j<(int)s.size(); j++){
if(s[j] == 'b'){
for(int i=j; i<(int)s.size(); i++){
if(s[i] == 'b'){
ctr++;
continue;
}
else{
if(ctr<=k){
ctr++;
//max_for_one = max(max_for_one, ctr);
}
}
}
}
max_overall = max(max_overall, ctr);
ctr = 0;
//max_for_one=0;
}
cout<<max_overall;
return 0;
}
<file_sep>#include<iostream>
using namespace std;
int binarySearch(int arr[], int s, int e, int key){
int mid = (s+e)/2;
int ans = -1;
if( arr[mid] == key )
ans = mid;
else if( arr[mid] > key )
return binarySearch( arr, s, mid - 1, key );
else if( arr[mid] < key )
return binarySearch( arr, mid + 1, e, key );
return ans;
}
int32_t main(void){
int n,key; cin>>n;
int arr[n];
for(int i=0; i<n; cin>>arr[i++]);
cin>>key;
cout<<binarySearch(arr, 0, n, key);
return 0;
}
<file_sep>#include<iostream>
#include<math.h>
#include<cstring>
using namespace std;
int main(void) {
// char ch[100];
// cin.getline(ch,100,'.');
// cout<<ch;
//int m; cin>>m;
//cin.ignore();
string s;
getline(cin,s);
// int n = s.size();
// int i = n-m,k=0;
// while(k<n)
// cout<<s[ i++ % (n) ],k++;
return 0;
}
<file_sep>#include<iostream>
using namespace std;
int main(void) {
long int N; cin>>N;
long int m,n;
if(N&1){
m = (N+1)/2;
n = (N-1)/2;
}
else{
m = N/2;
n= 1;
}
cout<<2*m*n<<" "<<(m*m) + (n*n)<<"\n";
return 0;
}
<file_sep>#include<iostream>
using namespace std;
void solve(char input[], int i){
if(input[i] == '\0')
return;
int digit = (input[i] - '0');
cout<<digit;
solve(input, i+1);
}
int main(void) {
char input[15];
cin>>input;
solve(input, 0);
return 0;
}
<file_sep>#include<iostream>
#include<list>
using namespace std;
template <typename T>
void print(T x){
for(auto s:x){
cout<<s<<"->";
}
cout<<"\n";
}
int32_t main(void){
list<int> l1{1,2,3,4,5,9,8,7,6,5};
list<string> l2{"a","b","c"};
l2.push_back("d");
print(l1);
l1.sort();
print(l1);
l1.reverse();
print(l1);
return 0;
}
<file_sep>#include<bits/stdc++.h>
//#define sync std::ios_base::sync_with_stdio(false), cin.tie(NULL),cout.tie(NULL)
//#define ll long long
//#define pb push_back
//#define eb emplace_back
//#define MOD 1000000007
//using namespace std;
//ll dp[10000005];
int main(void){
//sync;
int n;
string s;
cin>>s;
n = s.size()-1;
int dec = 0;
for(int i=0; i<=n; i++){
if(s[i] == '0')
continue;
else
dec = dec + (int)(pow(2,n-i) + 0.5);
}
cout<<dec<<"\n";
return 0;
}
<file_sep>#include<iostream>
#include<math.h>
using namespace std;
int main(void) {
int n,k,tmp,bit; cin>>n;
int bits[64] = {0};
for(int i=0; i<n; i++){
cin>>tmp;
k = 0;
while(tmp>0){
bit = tmp&1;
bits[k] += bit;
k++;
tmp = tmp>>1;
}
}
int ans = 0;
int p = 1;
for(int i=0; i<64; i++){
bits[i] %= 3;
ans += ( bits[i] * p );
p = p<<1;
}
cout<<ans;
return 0;
}
<file_sep>#include<iostream>
using namespace std;
unsigned int MergeSort(int* arr, int s, int e){
///Calculate Mid
int mid = (s+e)/2;
///Three Pointers for merging the arrays
int i = s;
int j = mid+1;
int k = s;
///The array to be merged into
int temp[10005];
///Counter
unsigned int counter = 0;
while( i<=mid && j<=e ){
if( arr[i] < arr[j] )
temp[k++] = arr[i++];
else{
temp[k++] = arr[j++];
counter += ( mid - (i-1) );
}
}
while( i <= mid )
temp[k++] = arr[i++];
while( j <= e )
temp[k++] = arr[j++];
for(int i=s; i<=e; i++)
arr[i] = temp[i];
return counter;
}
int Merge(int arr[], int s, int e){
///Base Case
if( s >= e )
return 0;
///Calculate Mid:
int mid = (s+e)/2;
///Divide:
int x = Merge(arr, s, mid);
int y = Merge(arr, mid+1, e);
int z = MergeSort(arr, s, e);
return x + y + z;
}
int32_t main(void){
int n; cin>>n;
int arr[n];
for(int i=0; i<n; cin>>arr[i++]);
cout<<Merge(arr, 0, n-1);
return 0;
}
<file_sep>#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
bool cmp(string X, string Y){
string XY = X.append(Y);
string YX = Y.append(X);
return XY.compare(YX) > 0 ? 1 : 0;
}
int main(void) {
int t,n; cin>>t;
while(t--){
cin>>n;
vector<string> arr;
for(int i=0; i<n; i++){
string temp;
cin>>temp;
arr.push_back(temp);
}
sort(arr.begin(), arr.end(), cmp);
for(int i=0; i<n; cout<<arr[i++]);
cout<<endl;
}
return 0;
}
<file_sep>#include<iostream>
using namespace std;
void permute( char *in, int i ){
if( in[i] == '\0' ){
cout<<in<<", ";
return;
}
for( int j=i; in[j] != '\0'; j++ ){
swap(in[i],in[j]);
permute( in, i+1 );
swap(in[i],in[j]);
}
}
int32_t main(void){
char in[100];
cin>>in;
permute( in, 0 );
return 0;
}
<file_sep>#include<iostream>
#include<string.h>
using namespace std;
unsigned long long ctr = 0;
void solve(char* input, char* ans, int i, int j){
///Base Case
if(input[i] == '\0'){
ans[j] = '\0';
cout<<ans;
return;
}
if(input[i] == 'x'){
ctr++;
return solve(input, ans, i+1, j);
}
else{
ans[j] = input[i];
return solve(input, ans, i+1, j+1);
}
}
int main(void) {
char input[1005];
char ans[3005];
cin>>input;
solve(input, ans, 0, 0);
for(int k=0; k<ctr; k++)
cout<<'x';
return 0;
}
<file_sep>#include<iostream>
#include<stdlib.h>
#include<math.h>
#include<cstring>
using namespace std;
int test(char c[]){
if(c=="x")
return 1;
else
return 0;
}
int main(void) {
// char ch[100];
// cin.getline(ch,100,'.');
// cout<<ch;
// int m; cin>>m;
// cin.ignore();
// string s1,s2;
// getline(cin,s1);
// getline(cin,s2);
// //cin>>s;
// int s1_Size = s1.size(), s2_Size = s2.size();
// int i = 0;
// int Hash[256] = {0};
// if( s1_Size != s2_Size )
// cout<<"No\n",exit(0);
// while(i<s1_Size){
// Hash[s1[i]]++;
// Hash[s2[i]]--;
// }
//
// for(int i=0; i<s1_Size; i++)
// if(Hash[i] - 48)
// cout<<"No\n",exit(0);
//
// cout<<"Yes\n";
char c[10];
scanf("%s",c);
printf("%d",test(c));
return 0;
}
<file_sep>#include<iostream>
using namespace std;
string solve(int n, string &s){
///Base case
if(n <= 0)
return "";
///extract last digit
int digit = n%10;
/// recursive call
solve(n/10, s);
switch (digit){
case 0 : s += "zero ";
break;
case 1 : s += "one ";
break;
case 2 : s += "two ";
break;
case 3 : s += "three ";
break;
case 4 : s += "four ";
break;
case 5 : s += "five ";
break;
case 6 : s += "six ";
break;
case 7 : s += "seven ";
break;
case 8 : s += "eight ";
break;
case 9 : s += "nine ";
break;
default: cout<<"\nInvalid Expression";
break;
}
return s;
}
int32_t main(void){
int n; cin>>n;
string s;
if(n<0) cout<<"Negative ";
cout<<solve(-n, s);
return 0;
}
<file_sep>#include <iostream>
#include <algorithm>
using namespace std;
int main(void){
int arr[] = {5,3,56,7,3,2,4,67,89,5,2,2,5,8,9,0};
int n = sizeof(arr)/sizeof(arr[0]);
int mx = *max_element(arr, arr+n);
int freq[mx+1] = {0};
for(int i=0; i<n; i++){
freq[arr[i]]++;
}
int res[n];
int k=0;
for(int i=0; i<=mx; i++){
if(freq[i] > 0){
while(freq[i]>0){
res[k++] = i;
freq[i]--;
}
}
}
for(int i=0; i<n; cout<<res[i++]<<" ");
return 0;
}
<file_sep>#include<iostream>
using namespace std;
int main(void) {
long int n; cin>>n;
bool flag = false;
if(!(n&1))
cout<<"Not Prime\n";
else{
for(long int i=3; i*i<n; i+=2){
if(n%i == 0){
flag = true;
break;
}
}
if(flag)
cout<<"Not Prime\n";
else
cout<<"Prime\n";
}
return 0;
}
<file_sep>#include <iostream>
#include <algorithm>
using namespace std;
int main(void){
int n,k; cin>>n;
int arr[n];
//Take input
for(int i=0;i<n;i++)
cin>>arr[i];
sort(arr,arr+n);
//Key input
cin>>k;
int l=0,r=n-1;
while(l<r){
if(arr[l] + arr[r] == k){
cout<<arr[l++]<<" and "<<arr[r--]<<"\n";
}
else if(arr[l] + arr[r] < k)
l++;
else if(arr[l] + arr[r] > k)
r--;
}
return 0;
}
<file_sep>#include<iostream>
using namespace std;
int factorial(int n){
int ans = 1;
for(int i=2; i<=n; ++i)
ans*=i;
return ans;
}
int NCR(int n, int r){
return factorial(n)/(factorial(r)*factorial(n-r));
}
int main(void) {
cout << factorial(5)<<"\n";
cout<< NCR(5,2);
return 0;
}
<file_sep>#include <iostream>
using namespace std;
int lowerBound(int arr[], int n, int key){
int s = 0, ed = n-1;
int mid,ans=-1;
while(s<=ed){
mid = (s+ed)/2;
if(arr[mid] == key){
ans = mid;
ed = mid - 1;
}
else if(arr[mid] > key)
ed = mid-1;
else if(arr[mid] < key)
s = mid+1;
}
// if(s>ed)
// cout<<"Key Not present in the array!",exit(0);
return ans;
}
int upperBound(int arr[], int n, int key){
int s = 0, ed = n-1;
int mid,ans=-1;
while(s<=ed){
mid = (s+ed)/2;
if(arr[mid] == key){
ans = mid;
s = mid + 1;
}
else if(arr[mid] > key)
ed = mid-1;
else if(arr[mid] < key)
s = mid+1;
}
// if(s>ed)
// cout<<"Key Not present in the array!",exit(0);
return ans;
}
int main(void){
int n; cin>>n;
int arr[n];
for(int i=0; i<n; cin>>arr[i++]);
int key; cin>>key;
cout<<"Lower Bound: "<<lowerBound(arr,n,key)<<"\n";
cout<<"Upper Bound: "<<upperBound(arr,n,key)<<"\n";
return 0;
}
<file_sep>#include<iostream>
using namespace std;
unsigned long long ctr = 0;
void solve(char* input, char* ans, int i, int j){
///Base Case
if(input[i] == '\0'){
ctr++;
ans[j] = '\0';
cout<<ans<<" ";
return;
}
///Inclusion of the letter:
ans[j] = input[i];
solve(input, ans, i+1, j+1);
///Exclusion of the letter:
solve(input, ans, i+1, j);
}
int main(void) {
char input[1005];
char ans[3005];
cin>>input;
solve(input, ans, 0, 0);
cout<<ctr;
return 0;
}
<file_sep>#include<iostream>
using namespace std;
int solve(int *arr, int n, int i, int key){
//Base Case:
if( i == n )
return -1;
int ans = solve( arr, n, i+1, key );
if( arr[i] == key && ans == -1 )
return i;
return ans;
}
int32_t main(void) {
int n; cin>>n;
int *arr = new int[n];
for(int i=0; i<n; cin>>arr[i++]);
int key; cin>>key;
cout<<solve(arr, n, 0, key);
delete(arr);
return 0;
}
<file_sep>#include<iostream>
using namespace std;
int countBits(int n){
int ctr = 0;
while(n){
n &= (n-1);
ctr++;
}
return ctr;
}
int minSteps(int n){
int ctr = 0;
if(countBits(n) == 1){
return 1;
}
else{
while(countBits(n--) != 1)
ctr++;
return 1 + minSteps(ctr);
}
}
int main(void) {
int t,n; cin>>t;
while(t--){
cin>>n;
cout<<minSteps(n)<<"\n";
}
return 0;
}
<file_sep>#include<iostream>
#include<string.h>
using namespace std;
void solve(char* input, char* ans, int i, int j){
//Base case
if( input[i] == '\0' ){
ans[j] = '\0';
cout<<ans<<"\n";
return;
}
//Recursive case
if( i < strlen(input) - 1 && input[i] == 'p' && input[i+1] == 'i' ){
ans[j] = '3';
ans[j+1] = '.';
ans[j+2] = '1';
ans[j+3] = '4';
return solve(input, ans, i+2, j+4);
}
else{
ans[j] = input[i];
return solve(input, ans, i+1, j+1);
}
}
int main(void) {
int t; cin>>t;
while(t--){
char input[1005];
char ans[3005];
cin>>input;
solve(input, ans, 0, 0);
}
return 0;
}
<file_sep>#include<iostream>
using namespace std;
void solve(int arr1[], int arr2[], int n, int m){
int sum[n];
int s=0,carry=0;
int i=n-1,j=m-1,k=n-1;
while(j>=0){
s = arr1[i] + arr2[j] + carry;
sum[k] = s%10;
carry = s/10;
i--;
j--;
k--;
}
while(i>=0){
s = arr1[i] + carry;
sum[k] = s%10;
carry = s/10;
i--;
k--;
}
for(int i=n-1;i>=0;i--){
if(carry){
cout<<carry<<", ";
carry = 0;
}
cout<<sum[i]<<", ";
}
cout<<"END";
}
void check(int arr1[], int arr2[], int n, int m){
if(n>m)
solve(arr1, arr2, n, m);
else
solve(arr2, arr1, m, n);
}
void init(){
int n; cin>>n;
int arr1[n];
for(int i=0; i<n; cin>>arr1[i++]);
int m; cin>>m;
int arr2[m];
for(int i=0; i<n; cin>>arr2[i++]);
check(arr1, arr2, n, m);
}
int main(void) {
init();
return 0;
}
<file_sep>#include<iostream>
using namespace std;
int main(void){
int r,c; cin>>r;
int** arr = new int*[r];
for(int i=0;i<r;i++){
cout<<"\nEnter the number of elements in the "<<i<<"th row: ";
cin>>c;
arr[i] = new int[c+1];
arr[i][0] = c;
cout<<"\nEnter the elements in the "<<i<<"th row: ";
for(int j=1;j<c+1;j++){
cin>>arr[i][j];
}
}
for(int i=0;i<r;i++){
for(int j=1;j<=arr[i][0];j++)
cout<<arr[i][j]<<" ";
cout<<"\n";
}
for(int i=0;i<r;i++)
delete [] arr[i];
delete []arr;
return 0;
}
<file_sep>#include<iostream>
using namespace std;
int decrease(int n){
if(n==0)
return 1;
cout<<n<<" ";
decrease(n-1);
}
int increase(int n){
if(n==0)
return 1;
increase(n-1);
cout<<n<<" ";
}
int32_t main(void){
int n; cin>>n;
increase(n);
cout<<"\n";
decrease(n);
return 0;
}
<file_sep>#include<iostream>
using namespace std;
int main(void) {
int start,stop,step; cin>>start>>stop>>step;
double c;
for(int i=start; i<=stop; i+=step){
c = (i-32)*(5/9.0);
cout<<i<<" "<<(int)c<<"\n";
}
return 0;
}
<file_sep>#include<iostream>
#include<math.h>
using namespace std;
int main(void) {
long int n,x,sum=0; cin>>n;
x=n;
while(x>0){
sum = sum + (int)(pow( (x%10), 3) + 0.5);
x/=10;
}
(sum==n) ? cout<<"true\n" : cout<<"false\n";
return 0;
}
<file_sep>#include<iostream>
using namespace std;
char letters [][10] = { "", "", "ABC", "DEF", "GHI", "JKL", "MNO", "PQRS", "TUV", "WXYZ" };
void keypad(char *arr, char *ans, int i, int j){
if( arr[i] == '\0' ){
ans[j] = '\0';
cout<<ans<<", ";
return;
}
///Extract the digit
int digit = (arr[i] - '0');
if( digit == 1 || digit == 0 ){
keypad( arr, ans, i+1, j );
}
///Inclusion
for( int k=0; letters[digit][k] != '\0'; k++ ){
ans[j] = letters[digit][k];
keypad( arr, ans, i+1, j+1 );
}
///Exclusion
// keypad( arr, ans, i+1, j );
}
int32_t main(void){
// int n; cin>>n;
// char *arr = (char *)malloc(n*sizeof(char));
// char *ans = (char *)malloc(n*sizeof(char));
// for(int i=0; i<n; cin>>arr[i++]);
char arr[100];
char ans[100];
cin>>arr;
keypad(arr ,ans, 0, 0);
// for(int i=0; i<n; cout<<arr[i++]<<" ");
// delete(arr);
// delete(ans);
return 0;
}
<file_sep>#include<iostream>
using namespace std;
int mul(int x, int y){
if(y==0)
return 0;
if(y>0) return x + mul(x,y-1);
else if(y<0) return -mul(x,-y);
}
int32_t main(void){
int x,y; cin>>x>>y;
cout<<mul(x,y);
return 0;
}
<file_sep>#include<iostream>
using namespace std;
int solve(int n){
if( n >= 1 || n <= 4 )
return n;
n = solve(n-1) + solve(n-4);
}
int32_t main(void){
int n; cin>>n;
cout<<solve(n);
return 0;
}
<file_sep>#include<iostream>
#include<cstring>
using namespace std;
class node{
public:
int data;
node* next;
///constructor
node(int value):data(value),next(NULL){}
};
int searchIterative(node* head, int key){
if(head == NULL){
cout<<"Linked list does not exist";
return -1;
}
else{
int index = 0;
while(head->data != key && head->next != NULL){
head = (*head).next;
index++;
}
return ( (head->data == key) ? index : -1 );
}
}
int searchRecursive(node* head, int key, int idx=0){
if(head == NULL)
return -1;
if(head->data == key)
return idx;
return searchRecursive(head->next, key, idx+=1);
}
int len(node* head){
int ctr = 0;
while(head != NULL){
head = head->next;
ctr++;
}
return ctr;
}
void print(node *head){
while (head != NULL){
cout<<head->data<<"-> ";
head = head->next;
}
}
void insertHead(node* &head, int value){
node* temp = new node(value);
temp->next = head;
head = temp;
}
int32_t main(void){
node* head = NULL;
insertHead(head, 10);
insertHead(head, 20);
insertHead(head, 30);
print(head);
cout<<"\n"<<searchIterative(head, 20);
cout<<"\n"<<searchRecursive(head, 0);
return 0;
}
<file_sep>#include<iostream>
using namespace std;
int main(void) {
int n1,n2,k,i=1,j=0; cin>>n1>>n2;
while(j!=n1){
k = (3*i + 2);
if(k % n2 != 0){
cout<<k<<"\n";
j++;
}
if(j == n1)
break;
i++;
}
return 0;
}
<file_sep>#include<iostream>
using namespace std;
bool isSorted(int *arr, int n){
if(n == 1)
return true;
if( (arr[0] < arr[1]) && isSorted(arr+1, n-1) )
return true;
return false;
}
int32_t main(void){
int n; cin>>n;
int *arr = (int *)malloc(n*sizeof(int));
for(int i=0; i<n; cin>>arr[i++]);
cout<< ( isSorted(arr, n) ? "True" : "False" );
return 0;
}
<file_sep>#include<iostream>
using namespace std;
char digits[][10] = {"zero ", "one ", "two ", "three ", "four ", "five ", "six ", "seven ", "eight ", "nine " };
void solve(int n){
///Base case
if( n == 0 )
return;
solve(n/10);
cout<<digits[n%10];
}
int32_t main(void){
int n; cin>>n;
if(n<0)
cout<<"Negative ",solve(-n);
else
solve(n);
return 0;
}
<file_sep>#include<iostream>
using namespace std;
int main(void) {
int n; cin>>n;
int arr[n];
for(int i=0; i<n; cin>>arr[i++]);
int left[n],right[n];
left[0] = arr[0];
right[n-1] = arr[n-1];
for(int i=1; i<n; i++)
left[i] = max(left[i-1],arr[i]);
for(int i=n-2; i>=0; i--)
right[i] = max(right[i+1],arr[i]);
int res=0;
for(int i=0; i<n; i++)
res = res + min(right[i],left[i]) - arr[i];
cout<<res;
return 0;
}
<file_sep>#include<iostream>
using namespace std;
class Car{
private:
int price;
string name;
public:
Car(){
}
///Copy constructor
Car(Car &x){
price = x.price;
name = x.name;
}
///Setters:
void setPrice(int p){
if( p < 1000 )
throw invalid_argument{"\nPrice cannot be less than 1000"};
price = p;
}
void setName(string s){
name = s;
}
///Getters:
int getPrice(){
return price;
}
string getName(){
return name;
}
};
int32_t main(void){
Car a;
int price; cin>>price;
string name; cin>>name;
a.setPrice(price);
a.setName(name);
cout<<a.getPrice()<<"\n";
cout<<a.getName()<<"\n\n";
Car b(a);
cout<<b.getPrice()<<"\n";
cout<<b.getName()<<"\n\n";
Car c = b;
cout<<c.getPrice()<<"\n";
cout<<c.getName()<<"\n";
return 0;
}
<file_sep>#include <iostream>
#include <list>
using namespace std;
int32_t main(void){
list <int> l;
int input,k;
cin>>input;
while(input != -1){
l.push_back(input);
cin>>input;
}
cin>>k;
list<int>::iterator fast = l.begin();
list<int>::iterator slow = l.begin();
while(k-- > 0)
fast++;
while(fast != l.end()){
fast ++ ;
slow ++ ;
}
cout<<*slow;
return 0;
}<file_sep>#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
bool isPaliondrome(string s, int n){
int l=0,h = n-1;
while(l<h){
if(s[l++] != s[h--]){
return false;
}
}
return true;
}
int main(void) {
int t; cin>>t;
string s;
while(t--){
cin>>s;
vector <string> v;
int n = (int)s.size();
for(int i=0; i<n; i++){
for(int j=1; j<= n-i; j++){
if( (s.substr(i,j)).size() % 3 ==0 )
v.push_back( (s.substr(i,j)) );
}
}
int ctr = 0;
for(int i=0; i<v.size(); i++){
if(isPaliondrome(v[i], (int)v[i].size()))
ctr++;
}
if(ctr == v.size())
cout<<"YES"<<"\n";
else
cout<<"NO"<<"\n";
}
return 0;
}
<file_sep>#include<iostream>
using namespace std;
int main(void) {
int n; cin>>n;
int arr[n][n];
for(int i=0; i<n; i++)
for(int j=0; j<n; j++)
cin>>arr[i][j];
int l,r;
for(int i=0; i<n; i++){
for(int j=i+1; j<n; j++)
swap(arr[i][j], arr[j][i]);
l = 0;
r = n-1;
while(l<r){
swap(arr[l++][i], arr[r--][i]);
}
}
for(int i=0; i<n; i++){
for(int j=0; j<n; j++)
cout<<arr[i][j]<<" ";
cout<<"\n";
}
return 0;
}
<file_sep>#include<iostream>
using namespace std;
int main(void){
int arr [3][3] = { {1,2,3},
{4,5,6},
{7,8,9} };
int temp;
//Transpose + Row reversal
int l,r;
for(int i=0;i<3;i++)
{
for(int j=i+1;j<3;j++){
temp = arr[i][j];
arr[i][j] = arr[j][i];
arr[j][i] = temp;
}
l=0;r=2;
while(l!=r){
temp = arr[i][l];
arr[i][l] = arr[i][r];
arr[i][r] = temp;
l++,r--;
}
}
for(int i=0;i<3;i++){
for(int j=0;j<3;j++)
cout<<arr[i][j]<<" ";
cout<<"\n";
}
return 0;
}
<file_sep>#include<iostream>
using namespace std;
int linearSearch(int arr[], int i, int n, int key){
if( i == n )
return -1;
if( arr[i] == key )
return i+1;
return linearSearch(arr, i+1, n, key);
}
int32_t main(void){
int n,key; cin>>n;
int arr[n];
for(int i=0; i<n; cin>>arr[i++]);
cin>>key;
cout<<linearSearch(arr, 0, n, key);
return 0;
}
<file_sep>#include<iostream>
#include<string>
using namespace std;
int main(void) {
string s; cin>>s;
string res = "";
int dif;
int i;
for(i=0; i<(int)s.size()-1; i++){
dif = s[i+1] - s[i];
res+=s[i];
res+=to_string(dif);
}
res+=s[i];
cout<<res<<"\n";
return 0;
}
<file_sep>#include<iostream>
using namespace std;
int main(void) {
int n; cin>>n;
int arr1[n],arr2[n];
int arr3[n+n];
for(int i=0;i<n;cin>>arr1[i++]);
for(int i=0;i<n;cin>>arr2[i++]);
int k=0;
int i=0,j=0;
while(i<n && j<n){
if(arr1[i]<arr2[j]){
arr3[k++] = arr1[i++];
}
else{
arr3[k++] = arr2[j++];
}
}
while(i<n)
arr3[k++] = arr1[i++];
while(j<n)
arr3[k++] = arr2[j++];
//for(int o=0;o<2*n;cout<<arr3[o++]<<" ");
cout<<(arr3[(n-1)] + arr3[(n)])/2;
return 0;
}
<file_sep>#include<iostream>
using namespace std;
int main(void) {
int n=3;
int arr[n] = {1,2,3};
for(int i=0;i<n;i++)
cout<<arr[n-i-1]<<" ";
return 0;
}
<file_sep>#include<iostream>
#include<string.h>
using namespace std;
const long long mod = 1000000007;
int32_t main(void) {
// int t,n,m; cin>>t;
char input[100];
cin>>input;
cout<<strlen(input);
// while(t--){
// cin>>n>>m;
//
// }
return 0;
}
<file_sep>#include<iostream>
using namespace std;
void solve(char input[], char prev, int i){
if( input[i] == '\0' )
return;
if(input[i] == prev)
cout<<"*";
cout<<input[i];
solve(input, input[i], i+1);
}
int main(void) {
char input[10005];
cin>>input;
char prev = input[0];
cout<<prev;
solve(input, prev, 1);
return 0;
}
<file_sep>//#include<iostream>
//#define ll long long int
//using namespace std;
//
//string convertNumIntoString(int num) {
//
// // base case:
// if (num == 0)
// return "0";
//
// string Snum = "";
// while (num > 0) {
// cout<<"SNUM :: "<<Snum<<"\n";
// Snum += (num % 10 - '0');
// num /= 10;
// }
// return Snum;
//}
//
//int main(void) {
//// string s; cin>>s;
//// int i=0;
//// if(s[i] == '9')
//// i++;
//// for(;s[i]!='\0';i++){
//// int digit = s[i] - '0';
//// if(digit>=5){
//// digit = 9 - digit;
//// s[i] = digit + '0';
//// }
//// }
//// cout<<s;
// int num; cin>>num;
// cout<<convertNumIntoString(num);
// return 0;
//}
// C++ Program to find the closest Palindrome
// number
#include <bits/stdc++.h>
using namespace std;
// function check Palindrome
bool isPalindrome(string n) {
for (int i = 0; i < n.size() / 2; i++)
if (n[i] != n[n.size() - 1 - i])
return false;
return true;
}
// convert number into String
string convertNumIntoString(int num) {
// base case:
if (num == 0)
return "0";
string Snum = "";
while (num > 0) {
Snum += (num % 10 - '0');
num /= 10;
}
cout<<"SNUM :: "<<Snum<<"\n";
return Snum;
}
// function return closest Palindrome number
int closestPlandrome(int num) {
// case1 : largest palindrome number
// which is smaller to given number
int RPNum = num - 1;
while (!isPalindrome(convertNumIntoString(abs(RPNum))))
RPNum--;
// Case 2 : smallest palindrome number
// which is greater than given number
int SPNum = num + 1;
while (!isPalindrome(convertNumIntoString(SPNum)))
SPNum++;
// check absolute difference
if (abs(num - RPNum) > abs(num - SPNum))
return SPNum;
else
return RPNum;
}
// Driver program to test above function
int main() {
int num = 121;
cout << closestPlandrome(num) << endl;
return 0;
}
<file_sep>#include<iostream>
using namespace std;
int main(void) {
int n,m; cin>>n>>m;
int arr[n][m];
for(int i=0; i<n; i++){
for(int j=0; j<m; j++)
cin>>arr[i][j];
}
int k; cin>>k;
bool flag = false;
for(int i=n-1,j=m-1; (i<0 || j<0 || j>m-1 || i>n-1);){
if(arr[i][j] < k)
j++;
else if(arr[i][j] > k)
i--;
else if(arr[i][j] == k){
cout<<1;
flag = true;
break;
}
}
if(!flag)
cout<<0;
return 0;
}
<file_sep>#include <iostream>
using namespace std;
float solve(int no, int p){
int s=0, ed = no;
int mid;
float ans;
while(s<=ed){
mid = (s+ed)/2;
if( mid*mid == no ){
ans = mid;
break;
}
else if( mid*mid > no ){
ed = mid - 1;
}
else if( mid*mid < no ){
ans = mid;
s = mid + 1;
}
}
float inc = 0.1;
for(int i=0; i<p; i++){
while( ans*ans <= no ){
ans+=inc;
}
ans-=inc;
inc/=10;
}
return ans;
}
int main(void){
int n,no,p; //cin>>n;
// for(int i=0; i<n; i++){
cin>>no>>p;
cout.precision(18);
cout<<solve(no,p);
// }
return 0;
}
<file_sep>#include<iostream>
using namespace std;
int main(void) {
int t; cin>>t;
long int n,even_sum,odd_sum;
while(t-- > 0){
cin>>n;
even_sum = 0;
odd_sum = 0;
while(n>0){
if( (n%10) & 1 )
odd_sum += n%10;
else
even_sum += n%10;
n/=10;
}
if(odd_sum % 3 == 0 || even_sum % 4 ==0)
cout<<"\nYES";
else
cout<<"NO\n";
}
return 0;
}
<file_sep>#include<iostream>
#include<stdio.h>
#include<cstring>
using namespace std;
class node{
public:
int data;
node* next;
///constructor
node(int value):data(value),next(NULL){}
};
void insertAtTail(node* &head, int data){
if(!head){
node* newNode = new node(data);
head = newNode;
}
else{
node* temp = head;
while(temp->next != NULL){
temp = temp->next;
}
node* newNode = new node(data);
temp->next = newNode;
}
}
void print(node* head){
while(head!=NULL){
cout << head->data<<" ";
head = head->next;
}
}
void build(node* &head){
int data ; cin >> data ;
while( data!= -1 ){
insertAtTail(head, data) ;
cin >> data ;
}
}
istream& operator >> (istream &is, node* &head){
build(head);
return is;
}
ostream& operator << (ostream &os, node* &head){
print(head);
return os;
}
bool Floydcycle(node* head){
node* slow = head ;
node* fast = head ;
while( fast != NULL && fast -> next != NULL ){
fast = fast -> next -> next ;
slow = slow -> next ;
if( fast == slow )
return true ;
}
return false ;
}
int breakCycle(node* &head){
if( !(head) || !( Floydcycle(head) ) )
return -1;
else{
node* fast = head;
node* slow = head;
while( fast != NULL && fast -> next != NULL ){
fast = fast -> next -> next ;
slow = slow -> next;
if( fast == slow ){
slow = head;
break;
}
}
int indexToBreak = 0;
node* prev = fast;
while( slow != fast ){
indexToBreak++;
prev = fast;
fast = fast -> next;
slow = slow -> next;
}
prev -> next = NULL;
return indexToBreak;
}
}
int32_t main(void){
node* head = NULL;
cin>>head;
cout<<Floydcycle(head)<<endl;
cout<<head;
return 0;
}
<file_sep>#include<iostream>
using namespace std;
int mul(int x, int y){
int ctr = 0;
while(x){
if(y&1)
ctr += y;
// cout<<"\nX:: "<<x<<" Y:: "<<y<<"\n";
y <<= 1;
x >>= 1;
}
return ctr + (y>>1);
}
int32_t main(void){
int x,y; cin>>x>>y;
cout<<mul(x,y);
return 0;
}
<file_sep>#include <iostream>
#include <list>
using namespace std;
template <typename T>
void print(T x){
for(auto s:x){
cout<<s<<"->";
}
cout<<"\n";
}
int32_t main(void){
cout<<"Enter the number of points: ";
int n; cin>>n;
list<pair<int, int >> l[n];
cout<<"Enter the number of edges: ";
int e; cin>>e;
int x,y,wt;
for(int i=0; i<e; i++){
cin>>x>>y>>wt;
///Bidirectional graph
l[x].push_back(make_pair(y,wt));
l[y].push_back(make_pair(x,wt));
}
///Print LL:
for(int i=0; i<n; i++){
cout<<"Linked List "<<i<<": ->";
for( auto x:l[i] ){
cout<<"("<<x.first<<", "<<x.second<<"), ";
}
cout<<"\n";
}
return 0;
}
<file_sep>#include<iostream>
#include<cstring>
using namespace std;
class node{
public:
int data;
node* next;
///constructor
node(int value):data(value),next(NULL){}
};
void insertHead(node* &head, int data){
node* newNode = new node(data);
newNode->next = head;
head = newNode;
}
void print(node* head){
while(head!=NULL){
cout << head->data<<" -> ";
head = head->next;
}
}
void build(node* &head){
int data ; cin >> data ;
while( data!= -1 ){
insertHead(head, data) ;
cin >> data ;
}
}
istream& operator >> (istream &is, node* &head){
build(head);
return is;
}
ostream& operator << (ostream &os, node* &head){
print(head);
return os;
}
void reverse(node* &head){
node* current = head;
node* previous = NULL;
node* next;
while(current != NULL){
next = current->next;
current->next = previous;
previous = current;
current = next;
}
head = previous;
}
//
//void recReverse(node* &head){
// if(head == NULL)
// return;
//
//}
int32_t main(void){
node* head = NULL;
cin>>head;
cout<<head<<"\n";
reverse(head);
cout<<head;
return 0;
}
<file_sep>#include<iostream>
using namespace std;
bool cmp(int a, int b){
return a < b;
}
void bubbleSort( int arr[], int n, bool (&cmp)(int a, int b) ){
///Bubble sort
for(int i=0; i<n; i++){
for(int j=0; j<n-i-1; j++){
if( cmp( arr[j+1], arr[j] ) )
swap( arr[j], arr[j+1] );
}
}
}
int32_t main(void){
int n; cin>>n;
int arr[n];
for(int i=0; i<n; cin>>arr[i++]);
bubbleSort(arr, n, cmp);
for(int i=0; i<n; cout<<arr[i++]<<" ");
return 0;
}
<file_sep>#include<iostream>
#include<cstring>
using namespace std;
class node{
public:
int data;
node* next;
///constructor
node(int value):data(value),next(NULL){}
};
void insertHead(node* &head, int value);
int len(node* head){
int ctr = 0;
while(head != NULL){
head = head->next;
ctr++;
}
return ctr;
}
void insertAtTail(node* &head, int data){
node* temp = head;
while(temp->next != NULL){
temp = temp->next;
}
node* newNode = new node(data);
temp->next = newNode;
}
void insertAtMiddle(node* &head, int data, int p){
if(head == NULL || p == 0){
insertHead(head, data);
return;
}
else if(p > len(head)){
insertAtTail(head, data);
return;
}
else{
int i=0;
node* temp = head;
///Take p-1 jumps
while(i<p-1){
temp = temp->next;
i++;
}
node* newNode = new node(data);
newNode->next = temp->next;
temp->next = newNode;
}
}
void print(node *head){
while (head != NULL){
cout<<head->data<<"-> ";
head = head->next;
}
}
void insertHead(node* &head, int value){
node* temp = new node(value);
temp->next = head;
head = temp;
}
int32_t main(void){
node* head = NULL;
insertHead(head, 10);
insertHead(head, 20);
insertHead(head, 30);
insertAtMiddle(head, 25, 6);
insertAtMiddle(head, 15, 1);
print(head);
return 0;
}
<file_sep>#include<iostream>
using namespace std;
void solve(int *arr, int n, int i, int key){
if( i == n-1 )
return;
if(arr[i] == key)
cout<<i<<" ";
solve(arr, n, i+1, key);
}
int main(void) {
int n,key; cin>>n;
int *arr = new int[n];
for(int i=0; i<n; cin>>arr[i++]);
cin>>key;
solve(arr, n, 0, key);
return 0;
}
<file_sep>#include<iostream>
#include<limits.h>
#define ll long long int
using namespace std;
int main(void) {
string s; cin>>s;
for(ll i=0;i<s.size();i++){
if('9' - s[i] < s[i] - '0') ///{57 - 52 < }
s[i] = ('9' - s[i]) + '0';
//cout<<(int)('9' - s[i]);
cout<<s[i]<<" ";
}
cout<<"\n";
return 0;
}
<file_sep>#include<iostream>
#include<string.h>
using namespace std;
int main(void) {
string a; int b,ctr = 0; cin>>a>>b;
for(long int i=0; i<a.size(); i++){
if(a[i]-48 == b) ctr++;
}
cout<<ctr<<"\n";
return 0;
}
<file_sep>#include<iostream>
using namespace std;
void solve(int arr[], int n){
int lo = 0;
int hi = n-1;
int mid = 0;
while(mid<=hi){
if(arr[mid] == 0){
swap(arr[mid], arr[lo]);
lo++;
mid++;
}
else if(arr[mid] == 1){
mid++;
}
else if(arr[mid] == 2){
swap(arr[mid], arr[hi]);
hi--;
}
}
}
int32_t main(void){
int n; cin>>n;
int arr[n];
for(int i=0; i<n; cin>>arr[i++]);
solve(arr, n);
for(int i=0; i<n; cout<<arr[i++]<<" ");
return 0;
}
<file_sep>#include<iostream>
using namespace std;
void filterChars(string s, int n){
int j = 0;
while(n){
if(n&1)
cout<<s[j];
j++;
n >>= 1;
}
cout<<"\n";
}
void subsets(string s){
int n = s.size();
for(int i=0; i<(1<<n); i++ )
filterChars(s,i);
}
int32_t main(void){
string s; cin>>s;
subsets(s);
return 0;
}
<file_sep>#include<iostream>
#include<limits.h>
using namespace std;
int main(void) {
int n; cin>>n; int arr[n];
for(int i=0;i<n;cin>>arr[i++]);
int max_sum=INT_MIN;
int cur_sum=0,l,r;
//Generating sub arrays :
for(int i=0;i<n;i++)
for(int j=i;j<n;j++){
cur_sum = 0;
for(int k=i;k<=j;k++){
//cout<<arr[k]<<" ";
cur_sum +=arr[k];
}
if(cur_sum>max_sum){
max_sum = cur_sum;
l = i;
r = j;
}
cout<<"\n";
}
for(int i=l;i<=r;i++)
cout<<arr[i]<<" ";
cout<<"\n";
return 0;
}
<file_sep>#include<iostream>
using namespace std;
int clearBits(int n, int i, int j){
int a = (~0) <<(j + 1);
int b = (1<<i) - 1;
int mask = a|b;
return n & mask;;
}
int main(void) {
int n,m,i,j; cin>>n>>m>>i>>j;
n = clearBits(n,i,j);
cout<<(n|(m<<i));
return 0;
}
<file_sep>#include<iostream>
#include<math.h>
using namespace std;
int main(void) {
int n,temp,ans=0; cin>>n;
// while(n--){
// cin>>temp;
// ans ^= temp;
// }
// for(int i=1; i<=n; i++){
// ans ^= i;
// }
cout<< log2(n&(-n)) + 1;
return 0;
}
<file_sep>#include<iostream>
using namespace std;
int ctr = 0;
bool solve( char in[10][10], int soln[10][10], int i, int j, int m, int n ){
///Base case
if( (i == m-1) && (j == n-1) ){
ctr++;
for(int i=0; i<m; i++){
for(int j=0; j<n; j++)
cout<<soln[i][j]<<" ";
cout<<"\n";
}
cout<<"\n";
return true;
}
/// 'X' case:
if( in[i][j] == 'X' )
return false;
/// Array out of bounds exception
if( i>=m || j>=n )
return false;
///Recursive case:
soln[i][j] = 1;
bool Right = solve(in, soln, i, j+1, m, n);
bool Down = solve(in, soln, i+1, j, m, n);
///Backtracking
soln[i][j] = 0;
if( Right || Down )
return true;
return false;
}
int32_t main(void){
char in[10][10] = {"0000",
"00X0",
"000X",
"0X00"};
int soln[10][10] = {0};
solve( in, soln, 0, 0, 4, 4 );
cout<<"Total number of paths: "<<ctr;
return 0;
}
<file_sep>#include<iostream>
using namespace std;
int32_t main(void) {
std::ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
int n,m,k,s; cin>>n>>m>>k>>s;
char arr[n][m];
for(int i=0; i<n; i++){
for(int j=0; j<m; j++){
cin>>arr[i][j];
}
}
for(int i=0;i<n;i++){
for(int j=0; j<m; j++){
if(arr[i][j] == '.' && j != m-1)
s-=3,cout<<s<<" Encountered: "<<arr[i][j]<<"\n";
else if (arr[i][j] == '.' && j == m-1)
s-=2,cout<<s<<" Encountered: "<<arr[i][j]<<"\n";
if(arr[i][j] == '*' && j != m-1)
s+=4,cout<<s<<" Encountered: "<<arr[i][j]<<"\n";
else if (arr[i][j] == '*' && j == m-1)
s+=5,cout<<s<<" Encountered: "<<arr[i][j]<<"\n";
if(arr[i][j] == '#' && i != n-1){
// for(int k=j; k<m; cin>>arr[i][k++]);
cout<<"Changed Row\n";
break;
}
else if( ((arr[i][j] == '#' && i == n-1) || (i == n-1 && j == m-1)) && s >= k ){
cout<<"Yes\n"<<s;
exit(0);
}
}
}
cout<<"No\n";
return 0;
}
<file_sep>#include<iostream>
#include<limits.h>
using namespace std;
int main(void) {
int n; cin>>n; int arr[n];
for(int i=0;i<n;cin>>arr[i++]);
int max_sum=INT_MIN;
int cur_sum=0,l=0,r;
//Generating sub arrays :
for(int i=0;i<n;i++){
if(cur_sum<0){
cur_sum = 0;
l = i;
}
cur_sum+=arr[i];
if(cur_sum>max_sum){
max_sum=cur_sum;
r = i;
}
}
cout<<"max sum is : "<<max_sum<<"\n";
for(int i=l;i<=r;i++)
cout<<arr[i]<<" ";
cout<<"\n";
return 0;
}
<file_sep>#include <iostream>
#include <algorithm>
using namespace std;
bool cmp(pair<string, int> &p1, pair<string, int> &p2){
if(p1.second == p2.second)
return p1.first < p2.first;
return p1.second > p2.second;
}
int32_t main(void){
int k; cin>>k;
int n; cin>>n;
pair<string, int> p[n];
for(int i=0; i<n; i++){
cin>>p[i].first;
cin>>p[i].second;
}
sort(p, p+n, cmp);
for(int i=0; i<n; i++)
if(p[i].second >= k)
cout<<p[i].first<<" "<<p[i].second<<"\n";
return 0;
}
<file_sep>#include<iostream>
using namespace std;
int main(void){
int r,c; cin>>r>>c;
int arr[r][c];
for(int i=0;i<r;i++)
for(int j=0;j<c;j++)
cin>>arr[i][j];
for(int i=0;i<c;i++){
if(!(i&1)){
for(int j=0;j<r;j++){
cout<<arr[j][i]<<", ";
}
}
else{
for(int j=r-1;j>=0;j--){
cout<<arr[j][i]<<", ";
}
}
}
cout<<"END";
return 0;
}
<file_sep>#include <iostream>
using namespace std;
int main(void){
int n; cin>>n;
int arr[n];
for(int i=0; i<n; cin>>arr[i++]);
for(int i=0; i<n; i+=2){
if(i>0 && arr[i-1] > arr[i])
swap(arr[i-1], arr[i]);
if(i<n-1 && arr[i+1] > arr[i])
swap(arr[i+1], arr[i]);
}
cout<<"\n";
for(int i=0; i<n; cout<<arr[i++]<<" ");
cout<<"\n";
return 0;
}
|
e69e5ea0784fe10c7f6e102a8c18cf62bc588d28
|
[
"Markdown",
"C++"
] | 99
|
C++
|
vanshBhatia-A4k9/CB
|
3f6b5a6105c8f0833da4d521457c1f12b4d68fb4
|
b0a366aa8bdd372aab620b20e4f8dc40a18e7357
|
refs/heads/master
|
<file_sep># TimesheetManager
Timesheet manager is currently being build in Kotlin and TornadoFx. The goal is to create and store timesheets for different projects, and to export those timesheets to a spreadsheet.
This project is an exercise in Kotlin and TornadoFx. It is very much incomplete but *eventually* I'll get around to completing it.
<file_sep>/*
Main class that controls the application
*/
import javafx.beans.property.SimpleStringProperty
import tornadofx.*
import java.io.File
class Application : View("Timesheet Manager") {
val name = SimpleStringProperty()
private val mainTabPane = tabpane{
tab("New Sheet") {
val sw = StopWatch()
content = sw.root
subscribe<SaveTabEvent> { _ ->
print(sw.listOfTimes.items)
}
}
// Add tabs on demand when NewDocumentEvent is emitted
subscribe<NewSheetEvent> { event ->
tab(event.message){
val sw = StopWatch()
content = sw.root
subscribe<SaveTabEvent> { _ ->
print(sw.listOfTimes.items)
}
}
}
}
override val root = borderpane{
left = vbox {
button("New Timesheet").setOnAction{
find<NewModalWindow>().openModal()
}
button("Write to file").setOnAction {
fire(SaveTabEvent())
val newFile = File("tmp.text")
newFile.writeText("Hello there")
}
}
center = mainTabPane
}
init {
subscribe<SaveTabEvent> { _ ->
print(mainTabPane.selectionModel.selectedIndex)
mainTabPane.selectionModel.selectedItem.text = "lol"
}
}
}
<file_sep>/*
Event that fires when user creates new timesheet
*/
import tornadofx.FXEvent
class NewSheetEvent(var message: String = "New Sheet") : FXEvent()
<file_sep>/*
Event that fires when user saves timesheet
*/
import tornadofx.FXEvent
class SaveTabEvent : FXEvent()
<file_sep>/*
Calculates time elapsed between a user starting and completing a task
*/
import javafx.animation.AnimationTimer
import javafx.beans.binding.Bindings
import javafx.beans.property.*
import javafx.scene.control.ListView
import javafx.scene.layout.VBox
import tornadofx.*
class StopWatch: Fragment("Default") {
override val root = VBox()
val time = SimpleStringProperty() //stores current time as string
var times = mutableListOf<String>().observable() //list of times
private val defaultTime = "00 : 00 : 00"
val listOfTimes: ListView<String>
/* Stopwatch states */
val running = SimpleBooleanProperty()
var paused = SimpleBooleanProperty()
/* Formats time string */
fun timeFormatter(difference: Long): String{
var seconds = difference
val hours = (difference/3600).toInt()
seconds -= hours*3600
val minutes = (difference/60).toInt()
seconds -= minutes*60
// 9 minutes -> 09 minutes
val precedingZero = fun(quantum: Int): String { return if (quantum < 10 ) "0$quantum" else "$quantum"}
return "${precedingZero(hours)} : ${precedingZero(minutes)} : ${precedingZero(seconds.toInt())}"
}
init{
time.set(defaultTime)
val elapsedTimeLabel = label() //displays elapsed time
val startStopButton = button()
val resumeButton = button()
listOfTimes = listview(times)
elapsedTimeLabel.textProperty().bind(time)
val timer = object : AnimationTimer() {
private var startTime: Long = 0
var elapsedTime: Long = 0 //when the timer is paused the elapsed time is updated and the start time is reset
override fun start() { //resets start and elapsed time
elapsedTime = 0
startTime = System.nanoTime()
running.set(true)
super.start()
}
override fun stop() {
running.set(false)
paused.set(false)
super.stop()
}
fun pause() {
paused.set(true)
elapsedTime += System.nanoTime() - startTime
super.stop()
}
fun resume(){
paused.set(false)
startTime = System.nanoTime() //time is updated to reflect pause
super.start()
}
override fun handle(timestamp: Long) {
val now = System.nanoTime()
time.set( timeFormatter((now-startTime+elapsedTime)/1000000000) )//Divide converts nano->sec
}
}
startStopButton.textProperty().bind(
Bindings.`when`(running)
.then("Stop")
.otherwise("Start")
)
resumeButton.textProperty().bind(
Bindings.`when`(paused)
.then("Resume")
.otherwise("Pause")
)
startStopButton.setOnAction {
if (running.get()) {
timer.stop()
times.add(elapsedTimeLabel.text)
time.set(defaultTime)
} else {
timer.start()
}
}
resumeButton.setOnAction {
if (paused.get()){
timer.resume()
} else if (!paused.get() && running.get()){
timer.pause()
}
}
with(root){
style {
padding = box(20.px)
}
listOfTimes
}
}
}
<file_sep>/*
Pop up window that asks user for name of new timesheet
*/
import javafx.animation.AnimationTimer
import javafx.beans.binding.Bindings
import javafx.beans.property.*
import javafx.scene.layout.VBox
import tornadofx.*
class NewModalWindow() : Fragment("New Timesheet") {
override val root = VBox()
var newSheetName = SimpleStringProperty()
init {
form{
fieldset("New Sheet") {
field("New Sheet Name:") {
textfield().bind(newSheetName)
}
}
}
button("save").setOnAction {
val sheetName = if (newSheetName.get().isNullOrBlank()) "New Sheet" else newSheetName.get()
fire(NewSheetEvent(sheetName))
close()
}
}
}
|
4f3d2748280a1fd9ae4181265531066959fc2daa
|
[
"Markdown",
"Kotlin"
] | 6
|
Markdown
|
Creavin/TimesheetManager
|
01464e8d7d74fcbb09aa33083c2679689f3c41bc
|
dc1499b345dcbab30836a70bc3d3a4688a7c332e
|
refs/heads/master
|
<file_sep>import {TICK, TIMER_TOGGLED} from '../actions/types';
const INITIAL_STATE = {
running: false,
timerStart: null,
seconds: 0
};
export default (state = INITIAL_STATE, action) => {
switch (action.type) {
case TIMER_TOGGLED:
if (state.running) {
return {...state, running: false, timerStart: null, seconds: 0};
} else {
return {...state, running: true, timerStart: action.payload};
}
case TICK:
return {...state, seconds: Math.round(action.payload / 1000 - state.timerStart / 1000)};
default:
return state;
}
}<file_sep>rootProject.name = 'timer_demo'
include ':react-native-notification-library'
project(':react-native-notification-library').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-notification-library/android')
include ':app'
<file_sep>export const TIMER_TOGGLED = 'timer_toggled';
export const TICK = 'tick';<file_sep>import React, {Component} from 'react';
import {PermissionsAndroid, DeviceEventEmitter, Alert} from 'react-native';
import {Provider} from 'react-redux';
import {createStore, applyMiddleware} from 'redux';
import ReduxThunk from 'redux-thunk';
import reducers from './reducers';
import {tick} from './actions';
import MainScreen from "./MainScreen";
const PHONE_STATE_PERMISSION = PermissionsAndroid.PERMISSIONS.READ_PHONE_STATE;
export default class App extends Component {
store = createStore(reducers, {}, applyMiddleware(ReduxThunk));
interval = null;
componentDidMount() {
//TODO: bind event listener to stop and start timer accordingly
DeviceEventEmitter.addListener('AppOpened', () => console.log('app opened'));
DeviceEventEmitter.addListener('AppClosed', () => console.log('app closed'));
DeviceEventEmitter.addListener('ScreenLocked', () => console.log('screen locked'));
DeviceEventEmitter.addListener('PopupDetected', () => console.log('popup detected'));
//check phone state permission
PermissionsAndroid.check(PHONE_STATE_PERMISSION).then(chRes => {
if (!chRes) {
PermissionsAndroid.request(PHONE_STATE_PERMISSION).then(reRes => {
if (reRes) {
console.log('accepted read phone state permission');
} else {
console.log('declined read phone state permission');
}
})
}
});
}
componentWillUnmount() {
//TODO unbind event listener
}
render() {
this.store.subscribe(() => {
const {running} = this.store.getState();
if (running && this.interval === null) {
this.interval = setInterval(() => {
this.store.dispatch(tick(Date.now()));
}, 1000)
}
if (!running && this.interval !== null) {
clearInterval(this.interval);
this.interval = null;
}
});
return(
<Provider store={this.store}>
<MainScreen/>
</Provider>
)
}
}
<file_sep>import {TICK, TIMER_TOGGLED} from './types';
export const timerToggle = (timerStart) => {
return {
type: TIMER_TOGGLED,
payload: timerStart
}
};
export const tick = (currentTime) => {
return {
type: TICK,
payload: currentTime
}
};
|
d8e3cdae05dec915b134fe33e77c307b057d9b70
|
[
"JavaScript",
"Gradle"
] | 5
|
JavaScript
|
effeffdev/timer_demo
|
a460db5ecf56d26fd3e52f7b0bf7519f34877293
|
24ccafdb346faff6f2edbc8f5871a3a41a786f2e
|
refs/heads/master
|
<repo_name>h-mj/morkovka-web<file_sep>/src/components/Progresses/index.js
import Progresses from "./Progresses";
export default Progresses;
<file_sep>/src/models/Foodstuff.js
import { extendObservable } from "mobx";
import { client } from "../utils/ApiClient";
import t9n from "./Translator";
export default class Foodstuff {
constructor(data) {
extendObservable(this, data);
}
get quantity() {
if (this.unit === "pc") {
return 1;
}
return 100;
}
get quantityWithUnit() {
return this.quantity + t9n.t[this.unit.trim()];
}
get caloriesWithUnit() {
return this.getFieldWithUnit("calories", false);
}
get carbsWithUnit() {
return this.getFieldWithUnit("carbs");
}
get proteinsWithUnit() {
return this.getFieldWithUnit("proteins");
}
get fatsWithUnit() {
return this.getFieldWithUnit("fats");
}
getFieldWithUnit(field, grams = true) {
return Math.round(this.quantity * this[field]) + (grams ? t9n.t.g : "");
}
delete = () => {
console.log("Hello");
return client
.delete("/foodstuff", {
foodstuff_id: this.id
});
}
}
<file_sep>/src/components/FoodAdd/FoodAdd.js
import React, { Component } from "react";
import styled from "styled-components";
import styles from "../../styles/constants";
import { decorate, observable, action } from "mobx";
import { inject, observer } from "mobx-react";
import Input from "../Input";
import Button from "../Button";
import ActionButton from "../ActionButton";
import Container from "../Container";
import Modal from "../Modal";
import FoodstuffAdd from "../FoodstuffAdd";
import Labels from "./components/Labels";
import Foodstuff from "./components/Foodstuff";
import Add from "./components/Add";
class FoodAdd extends Component {
constructor(props) {
super(props);
this.query = "";
this.quantity = "";
this.loaded = true;
this.foodstuffs = [];
this.foodstuff = null;
this.adding = false;
this.invalid = {
query: false,
quantity: false
};
}
render() {
return (
<Modal>
<Container>
<Form onSubmit={this.submit} noValidate>
<Input
onChange={this.find}
name="query"
autoFocus
autoComplete="off"
value={this.query}
invalid={this.invalid.query}
placeholder={this.props.t9n.t.name}
/>
<Section>
<Input
onChange={event => {
this.quantity = event.target.value;
}}
name="quantity"
value={this.quantity}
invalid={this.invalid.quantity}
placeholder={this.props.t9n.t.quantity}
type="number"
/>
</Section>
<Unit>
{this.foodstuff && this.props.t9n.t[this.foodstuff.unit.trim()]}
</Unit>
<Section>
<ActionButton type="submit">{this.props.t9n.t.add}</ActionButton>
</Section>
<Section>
<Button type="button" onClick={this.close}>
{this.props.t9n.t.back}
</Button>
</Section>
</Form>
{this.query && this.foodstuff === null && (
<div>
{this.foodstuffs.length > 0 && <Labels />}
{this.foodstuffs.map((value, index) => (
<Foodstuff
key={value.name + "@" + value.unit}
foodstuff={value}
use={this.use}
remove={this.remove}
/>
))}
{(this.loaded || this.foodstuffs.length > 0) && (
<Add onClick={this.openFoodstuff}>
{this.props.t9n.t.foodstuffAdd}
</Add>
)}
</div>
)}
</Container>
{this.adding && (
<FoodstuffAdd use={this.use} close={this.closeFoodstuff} />
)}
</Modal>
);
}
openFoodstuff = () => {
this.adding = true;
};
closeFoodstuff = () => {
this.adding = false;
};
clear = () => {
this.query = "";
this.quantity = "";
this.foodstuff = null;
this.foodstuffs = [];
this.loaded = true;
this.adding = false;
this.setValid([], true);
};
close = () => {
this.clear();
this.props.close();
};
setValid = (names, valid) => {
if (!(names instanceof Array)) {
names = [names];
}
for (const key in this.invalid) {
this.invalid[key] = false;
}
for (let i = 0; i < names.length; ++i) {
this.invalid[names[i]] = !valid;
}
};
remove = foodstuff => {
foodstuff.delete();
this.foodstuffs = [];
this.find(null, true);
};
find = (event, previous = false) => {
this.foodstuff = null;
this.loaded = false;
if (!previous) {
this.query = event.target.value;
}
if (!this.query) {
return;
}
this.props.auth.foodstuffs
.find(this.query)
.then(data => {
this.foodstuffs = data;
this.loaded = true;
})
.catch(error => {
if (error.code === 422) {
this.foodstuffs = [];
} else {
console.log(error);
}
this.loaded = true;
});
};
use = foodstuff => {
this.foodstuff = foodstuff;
this.query = foodstuff.name;
this.setValid("query", true);
};
submit = event => {
event.preventDefault();
if (!this.foodstuff) {
return this.setValid("query", false);
}
if (!this.quantity) {
return this.setValid("quantity", false);
}
this.props.meal
.add(this.foodstuff.id, this.quantity)
.then(() => {
this.close();
})
.catch(error => {
if (error.code === 422) {
this.setValid(error.details.invalid, false);
} else {
console.error(error);
}
});
};
}
decorate(FoodAdd, {
query: observable,
quantity: observable,
loaded: observable,
foodstuffs: observable,
foodstuff: observable,
adding: observable,
invalid: observable,
openFoodstuff: action,
closeFoodstuff: action,
setValid: action,
find: action,
use: action,
submit: action
});
const Form = styled.form`
display: flex;
height: 3.5rem;
`;
const Section = styled.div`
width: 5.5rem;
flex-shrink: 0;
`;
const Unit = styled.div`
width: 0;
display: flex;
align-items: center;
justify-content: center;
text-align: center;
line-height: 3.5rem;
color: ${styles.color.text};
padding: 0 1rem;
`;
export default inject("auth", "t9n")(observer(FoodAdd));
<file_sep>/src/components/Error/Error.js
import styled from "styled-components";
export default styled.div`
color: red;
line-height: 1.5rem;
margin-bottom: 1rem;
text-align: center;
`;
<file_sep>/src/components/QuantityList/index.js
import QuantityList from "./QuantityList";
export default QuantityList;
<file_sep>/src/components/RatioChanger/components/SliderSection.js
import React from "react";
import ReactSlider from "react-slider";
import styled from "styled-components";
import { inject, observer } from "mobx-react";
import round from "../../../utils/round";
import Container from "../../Container";
import styles from "../../../styles/constants";
import Flex from "../../Flex";
function SliderSection({ t9n, ratios, totals, measurements, ...rest }) {
return (
<Div>
<Slider value={[ratios.carbs, ratios.carbs + ratios.proteins]} {...rest}>
<Handle />
<Handle />
</Slider>
<Sections>
{["carbs", "proteins", "fats"].map(value => (
<Section
key={value}
title={t9n.t[value]}
percentage={ratios[value]}
total={totals ? totals[value] : null}
mass={measurements ? measurements.mass : null}
t9n={t9n}
/>
))}
</Sections>
</Div>
);
}
const Div = styled(Container)`
height: 100%;
flex-shrink: 1;
display: flex;
flex-direction: column;
`;
const Slider = styled(ReactSlider)`
height: 2rem;
flex-shrink: 0;
border-bottom: solid 1px ${styles.borderColor.gray};
`;
const Sections = styled(Flex)`
width: 100%;
height: 100%;
`;
function Section({ t9n, title, percentage, total, mass }) {
return (
<SectionDiv>
<Title>{title}</Title>
<Percentage>{percentage}%</Percentage>
{total !== null && (
<Total>
{Math.round(total)}
{t9n.t.g}, {round(total / mass, 2)}
{t9n.t.g}/{t9n.t.kg}
</Total>
)}
</SectionDiv>
);
}
const SectionDiv = styled.div`
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
`;
const Title = styled.div`
font-size: 0.9rem;
white-space: nowrap;
color: ${styles.color.text};
`;
const Percentage = styled.div`
margin: 0.25rem 0;
font-size: 1.5rem;
color: ${styles.color.text};
`;
const Total = styled.div`
font-size: 0.9rem;
color: ${styles.color.textLight};
white-space: nowrap;
min-width: 0;
`;
const Handle = styled.div`
width: 0.5rem;
height: 2rem;
cursor: ew-resize;
background-color: ${styles.backgroundColor.primary};
`;
export default inject("t9n")(observer(SliderSection));
<file_sep>/src/components/Progresses/components/ProgressBar.js
import React from "react";
import styled from "styled-components";
import styles from "../../../styles/constants";
export default function ProgressBar({ percentage, over }) {
return (
<Container over={over}>
<Progress over={over} percentage={percentage} />
</Container>
);
}
const Container = styled.div`
width: 100%;
height: 4px;
background-color: ${props =>
(props.over && styles.backgroundColor.primary) ||
styles.backgroundColor.slate};
`;
const Progress = styled.div`
width: ${props => props.percentage + "%"};
height: 100%;
background-color: ${props =>
(props.over && "red") || styles.backgroundColor.primary};
`;
<file_sep>/src/components/ConsumptionChart/index.js
import ConsumptionChart from "./ConsumptionChart";
export default ConsumptionChart;
<file_sep>/src/components/Meal/components/Labels.js
import React from "react";
import styled, { css } from "styled-components";
import { inject, observer } from "mobx-react";
import Flex from "../../Flex";
import Column from "./Column";
import FixedColumn from "./FixedColumn";
import ThinColumn from "./ThinColumn";
function Labels({ t9n, deletable }) {
return (
<Flex>
<LabelFixedColumn>
<span>{t9n.t.quantity}</span>
</LabelFixedColumn>
<LabelColumn>
<span>{t9n.t.name}</span>
</LabelColumn>
<LabelFixedColumn>
<span>{t9n.t.calories}</span>
</LabelFixedColumn>
<LabelFixedColumn>
<span>{t9n.t.carbs}</span>
</LabelFixedColumn>
<LabelFixedColumn>
<span>{t9n.t.proteins}</span>
</LabelFixedColumn>
<LabelFixedColumn>
<span>{t9n.t.fats}</span>
</LabelFixedColumn>
{deletable && <LabelThinColumn />}
</Flex>
);
}
const style = css`
font-size: 0.9rem;
line-height: 1.5rem;
justify-content: center;
color: rgba(0, 0, 0, 0.5);
white-space: nowrap;
@media screen and (max-width: 40rem) {
& > span {
overflow: hidden;
text-overflow: ellipsis;
}
}
`;
const LabelColumn = styled(Column)(style);
const LabelFixedColumn = styled(FixedColumn)(style);
const LabelThinColumn = styled(ThinColumn)(style);
export default inject("t9n")(observer(Labels));
<file_sep>/src/models/Measurement.js
import { extendObservable } from "mobx";
import { client } from "../utils/ApiClient";
export default class Measurement {
quantity = null;
constructor(data, quantity) {
extendObservable(this, data);
this.quantity = quantity;
}
delete = () => {
return client
.delete("/user/quantity/measurement", {
user_id: this.quantity.quantities.user.id,
measurement_id: this.id
})
.then(data => {
this.quantity.remove(this);
});
};
}
<file_sep>/src/translations/ru.js
export default {
calories: "Калории",
carbs: "Углеводы",
proteins: "Белки",
fats: "Жиры",
g: "г",
kg: "кг",
pc: "шт",
ml: "мл",
cm: "см",
registration: {
language: "Язык",
name: "Имя",
sex: "Пол",
date: "Число",
month: "Месяц",
year: "Год",
email: "Адрес электронной почты",
password: "<PASSWORD>",
code: "Код",
register: "Зарегистрироваться",
emailUsed: "Этот адрес электронной почты уже используется."
},
user: {
female: "Женщина",
male: "Мужчина",
sex: "Пол",
age: "Возраст"
},
progress: {
left: "осталось",
under: "недоедено",
over: "превышено"
},
days: [
"Воскресенье",
"Понедельник",
"Вторник",
"Среда",
"Четверг",
"Пятница",
"Суббота"
],
navigation: {
counter: "Ввод",
quantities: "Замеры",
progress: "Прогресс",
history: "История",
clients: "Клиенты",
settings: "Настройки",
logout: "Выйти"
},
title: {
bmi: "Индекс массы тела",
calories: "Дневной калораж",
carbs: "Дневное количество углеводов",
proteins: "Дневное количество белков",
fats: "Дневное количество жиров"
},
bmi: {
noData: "Добавьте значения массы, высоты и активности."
},
bmiRanges: {
0: "Выраженный дефицит массы",
1: "Недостаточная масса тела",
2: "Норма",
3: "Предожирение",
4: "Ожирение первой степени",
5: "Ожирение второй степени",
6: "Ожирение третьей степени"
},
name: "Название",
quantity: "Количество",
unit: "Едини́ца",
add: "Добавить",
update: "Обновить",
back: "Назад",
cancel: "Отмена",
saved: "Сохранено",
addMeal: {
breakfast: "Добавить завтрак",
lunch: "Добавить обед",
dinner: "Добавить ужин",
snack: "Добавить закуску"
},
deleteAccount: "Удалить аккаунт",
foodstuffAdd: "Добавить продукт",
quantityAdd: "Добавить размер",
consumptionData: "Детали",
generatedCode: "Сгенерированная код",
label: {
calories: "Энергия",
carbs: "Углеводы (г)",
proteins: "Белки (г)",
fats: "Жиры (г)",
sugars: "Сахар (г)",
salt: "Соль (г)",
saturates: "Насыщенные жирные кислоты (г)"
},
activeness: {
minimal: "Минимальная",
low: "Низкая",
medium: "Средняя",
high: "Высокая",
veryHigh: "Очень высокая"
},
mealNames: {
0: "Завтрак",
1: "Обед",
2: "Ужин",
3: "Закуска"
},
quantityNames: {
1: "Масса",
2: "Рост",
3: "Активность",
4: "Oбъем груди",
5: "Oбъем талии",
6: "Oбъем бедер",
7: "Oбъем бедра",
8: "Oбъем икры",
9: "Oбъем бицепса",
10: "Oбъем запястья",
11: "Oбъем голени"
},
confirm: {
yes: "Да",
no: "Нет",
food: "Уверены ли вы, что хотите удалить этот продукт?",
foodstuff: "Уверены ли вы, что хотите удалить этот продукт?",
quantity: "Уверены ли вы, что хотите удалить этот размер?",
measurement: "Уверены ли вы, что хотите удалить этот замер?",
user: "Уверены ли вы, что хотите удалить свой аккаунт?",
client: "Уверены ли вы, что хотите удалить аккаунт клиента?"
},
ratioChanger: {
calories: "Калораж",
change: "Процент рациона"
},
measurement: {
date: "Дата",
value: "Данные"
},
settings: {
language: "Язык",
email: "Адрес электронной почты",
newPassword: "<PASSWORD>",
repeatPassword: "<PASSWORD>",
currentPassword: "<PASSWORD>",
save: "Сохранить"
}
};
<file_sep>/src/models/Stats.js
import { decorate, observable } from "mobx";
export default class Stats {
consumption = false;
constructor(consumption, user) {
this.consumption = consumption;
this.user = user;
}
}
decorate(Stats, {
consumption: observable
});
<file_sep>/src/components/FoodstuffAdd/index.js
import FoodstuffAdd from "./FoodstuffAdd";
export default FoodstuffAdd;
<file_sep>/src/utils/ApiClient.js
import auth from "../models/Auth";
export default class ApiClient {
fetch(path, method, data) {
let body;
if (method === "GET") {
path = data ? path + "?" + this.createQueryString(data) : path;
} else {
body = data ? JSON.stringify(data) : undefined;
}
const headers = {
Accept: "application/json",
"Content-Type": "application/json"
};
if (auth && auth.authenticated) {
headers["Authorization"] = "Bearer " + auth.token;
}
const request = fetch("/api" + path, {
method: method,
body,
headers
});
return new Promise((resolve, reject) => {
request
.then(response => response.json())
.then(
json => {
const { data, error } = json;
if (error) {
throw error;
}
return resolve(data);
},
error => {
throw error;
}
)
.catch(error => {
if (error.code === 401) {
auth.logout();
}
return reject(error);
});
});
}
get(path, data) {
return this.fetch(path, "GET", data);
}
post(path, data) {
return this.fetch(path, "POST", data);
}
patch(path, data) {
return this.fetch(path, "PATCH", data);
}
delete(path, data) {
return this.fetch(path, "DELETE", data);
}
createQueryString = data => {
return Object.keys(data)
.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(data[key])}`)
.join("&");
};
}
export const client = new ApiClient();
<file_sep>/src/models/Day.js
import { decorate, observable } from "mobx";
import Meals from "./Meals";
export default class Day {
date = null;
user = null;
meals = null;
ratios = null;
measurements = null;
constructor({ date, meals, measurements, ratios }, user) {
this.date = date;
this.user = user;
this.meals = new Meals(meals, this);
this.ratios = ratios;
this.measurements = measurements;
}
}
decorate(Day, {
date: observable,
user: observable,
meals: observable,
ratios: observable,
measurements: observable
});
<file_sep>/src/next/style/declarations.ts
interface IDeclarations {
borderColor: IBorderColorDeclarations;
color: IColorDeclarations;
}
interface IBorderColorDeclarations {
default: string;
defaultAction: string;
active: string;
error: string;
errorAction: string;
}
interface IColorDeclarations {
default: string;
defaultAction: string;
active: string;
error: string;
errorAction: string;
}
export const declarations: IDeclarations = {
borderColor: {
default: "rgba(0, 0, 0, 0.35)",
defaultAction: "rgba(0, 0, 0, 0.60)",
active: "rgba(0, 0, 0, 0.65)",
error: "rgba(255, 0, 0, 0.65)",
errorAction: "rgba(255, 0, 0.75)"
},
color: {
default: "rgba(0, 0, 0, 0.55)",
defaultAction: "rgba(0, 0, 0, 0.80)",
active: "rgba(0, 0, 0, 0.95)",
error: "rgba(255, 0, 0, 0.95)",
errorAction: "rgba(255, 0, 0, 1)"
}
};
<file_sep>/src/components/QuantityList/components/QuantityPlus.js
import styled from "styled-components";
import styles from "../../../styles/constants";
import Item from "./Item";
export default styled(Item)`
display: flex;
align-items: center;
justify-content: center;
font-size: 2.5rem;
height: 6rem;
color: ${styles.color.text};
`;
<file_sep>/src/scenes/Clients/Clients.js
import React, { Component } from "react";
import styled from "styled-components";
import { decorate, observable, action } from "mobx";
import { inject, observer } from "mobx-react";
import totals from "../../utils/totals";
import Body from "../../components/Body";
import Tabs from "../../components/Tabs";
import ClientList from "../../components/ClientList";
import RatioChanger from "../../components/RatioChanger";
import BodyMassIndexScale from "../../components/BodyMassIndexScale";
import ConsumptionHistory from "../../components/ConsumptionHistory";
import MeasurementHistory from "../../components/MeasurementHistory";
class Clients extends Component {
constructor(props) {
super(props);
this.selected = 0;
this.client = null;
this.data = null;
this.tabs = [
props.t9n.t.navigation.progress,
props.t9n.t.navigation.history
];
document.title = props.t9n.t.navigation.clients;
}
render() {
const user = this.props.auth.user;
if (user.type !== 1) {
return null;
}
const { clients } = user;
if (clients === null) {
return null;
}
if (this.client === null && clients.clients.length > 0) {
this.select(clients.clients[0]);
}
if (!this.client || !this.client.stats || !this.client.quantities) {
return (
<Content>
<ClientList clients={clients} select={this.select} />
</Content>
);
}
const data = this.client.stats.consumption;
const quantities = this.client.quantities;
for (let i = 0; i < data.length; ++i) {
data[i].totals = totals(this.client, data[i]);
}
return (
<Content>
<ClientList
clients={clients}
select={this.select}
client={this.client}
/>
{this.client && (
<Main>
<Tabs
tabs={this.tabs}
selected={this.selected}
select={this.selectTab}
/>
{this.selected === 0 && (
<Body>
<RatioChanger user={this.client} onChange={this.update} />
<BodyMassIndexScale user={this.client} />
<MeasurementHistory quantities={quantities} />
</Body>
)}
{this.selected === 1 && (
<Body>
<ConsumptionHistory user={this.client} data={data} />
</Body>
)}
</Main>
)}
</Content>
);
}
selectTab = index => {
this.selected = index;
};
select = client => {
this.client = client;
this.client.loadStats();
};
update = ratios => {
const data = this.client.stats.consumption;
const last = data[data.length - 1];
last.ratios = ratios;
last.totals = totals(this.client, last);
};
}
decorate(Clients, {
selected: observable,
client: observable,
selectTab: action,
select: action,
update: action
});
const Content = styled.div`
display: flex;
flex-direction: row;
flex: 1 1 100%;
min-height: 0;
@media screen and (max-width: 40rem) {
overflow-y: auto;
}
`;
const Main = styled.div`
width: 100%;
height: 100%;
overflow: auto;
@media screen and (max-width: 40rem) {
min-width: 100vw;
}
`;
export default inject("auth", "t9n")(observer(Clients));
<file_sep>/src/components/ConsumptionHistory/index.js
import ConsumptionHistory from "./ConsumptionHistory";
export default ConsumptionHistory;
<file_sep>/src/components/QuantityList/components/Item.js
import styled from "styled-components";
import styles from "../../../styles/constants";
export default styled.div`
width: 100%;
height: 6rem;
position: relative;
color: ${styles.color.text};
border-bottom: solid 1px ${styles.borderColor.gray};
&:last-child {
border-bottom: 0;
}
cursor: pointer;
user-select: none;
transition: 0.2s;
&:hover {
background-color: #f5f5f5;
}
`;
<file_sep>/src/components/ConsumptionData/ConsumptionData.js
import React from "react";
import { inject, observer } from "mobx-react";
import Modal from "../Modal";
import ModalHeader from "../ModalHeader";
import Body from "../Body";
import Meal from "../Meal";
import Progresses from "../Progresses";
function ConsumptionData({ t9n, date, user, close }) {
return (
<Modal>
{user.day && (
<Body>
<ModalHeader title={t9n.t.consumptionData} close={close} />
<Progresses day={user.day} past />
{user.day.meals.meals.map(meal => (
<Meal key={meal.id.toString()} meal={meal} readOnly />
))}
</Body>
)}
</Modal>
);
}
export default inject("t9n")(observer(ConsumptionData));
<file_sep>/src/components/SectionTitle/SectionTitle.js
import styled from "styled-components";
import styles from "../../styles/constants";
export default styled.div`
width: 100%;
font-size: 1.2rem;
margin-bottom: 1rem;
color: ${styles.color.text};
`;
<file_sep>/src/components/ConsumptionHistory/ConsumptionHistory.js
import React, { Component } from "react";
import { action, decorate, observable } from "mobx";
import { inject, observer } from "mobx-react";
import Section from "../Section";
import SectionTitle from "../SectionTitle";
import ConsumptionChart from "../ConsumptionChart";
import ConsumptionData from "../ConsumptionData/ConsumptionData";
class ConsumptionHistory extends Component {
render() {
const { t9n, data, user } = this.props;
return (
<Section>
{["calories", "carbs", "proteins", "fats"].map(value => (
<Section key={value}>
<SectionTitle>{t9n.t.title[value]}</SectionTitle>
<ConsumptionChart
of={value}
label={t9n.t.label[value]}
data={data}
onElementsClick={this.onElementsClick}
/>
</Section>
))}
{this.date && <ConsumptionData user={user} close={this.hideData} />}
</Section>
);
}
onElementsClick = elements => {
if (elements.length === 0) {
return;
}
const data = this.props.data[elements[0]._index];
if (data.consumed.calories > 0) {
this.showData(data.date);
}
};
showData = date => {
this.date = date;
const user = this.props.user;
if (!user.day || user.day.date !== date) {
user.loadDay(this.date);
}
};
hideData = () => {
this.date = null;
};
}
decorate(ConsumptionHistory, {
date: observable,
showData: action,
hideData: action
});
export default inject("t9n")(observer(ConsumptionHistory));
<file_sep>/src/components/QuantityDetails/index.js
import QuantityDetails from "./QuantityDetails";
export default QuantityDetails;
<file_sep>/src/components/QuantityList/QuantityList.js
import React from "react";
import styled from "styled-components";
import { observer } from "mobx-react";
import Quantity from "./components/Quantity";
import QuantityPlus from "./components/QuantityPlus";
function QuantityList({ quantities, showDetails, showAdder }) {
const tiles = quantities.quantities.map(quantity => (
<Quantity
key={quantity.id.toString()}
quantity={quantity}
showDetails={showDetails}
/>
));
tiles.unshift(
<QuantityPlus key="TileAdd" onClick={showAdder}>
+
</QuantityPlus>
);
return <Tiles>{tiles}</Tiles>;
}
const Tiles = styled.div`
width: 20rem;
height: 100%;
overflow: auto;
flex-shrink: 0;
background-color: white;
`;
export default observer(QuantityList);
<file_sep>/src/components/BodyMassIndexScale/index.js
import BodyMassIndexScale from "./BodyMassIndexScale";
export default BodyMassIndexScale;
<file_sep>/src/components/ActionButton/ActionButton.js
import styled from "styled-components";
import styles from "../../styles/constants";
import Button from "../Button";
export default styled(Button)`
color: white;
background-color: ${styles.backgroundColor.primary};
&:hover {
background-color: ${styles.backgroundColor.primaryAction};
}
`;
<file_sep>/src/components/Button/Button.js
import styled from "styled-components";
import styles from "../../styles/constants";
export default styled.button`
width: 100%;
border: none;
outline: none;
margin: 0;
padding: 0;
background: none;
padding: 1rem 0;
line-height: 1.5rem;
box-sizing: border-box;
background-color: ${styles.backgroundColor.slate};
color: ${styles.color.text};
cursor: pointer;
transition: 0.2s;
:hover {
background-color: ${styles.backgroundColor.slateAction};
}
`;
<file_sep>/src/components/ConfirmationWithPassword/ConfirmationWithPassword.js
import React, { Component } from "react";
import styled from "styled-components";
import styles from "./../../styles/constants";
import { action, decorate, observable } from "mobx";
import { inject, observer } from "mobx-react";
import Modal from "../Modal";
import Input from "../Input";
import Separator from "../Separator";
import Button from "../Button";
import ActionButton from "../ActionButton";
import Container from "../Container";
class ConfirmationWithPassword extends Component {
constructor(props) {
super(props);
this.password = "";
this.invalid = false;
}
render() {
const { t9n, message, onNo } = this.props;
return (
<Modal>
<Div>
<MessageDiv>
<Message>{message}</Message>
</MessageDiv>
<Separator />
<Input
onChange={this.change}
value={this.password}
invalid={this.invalid}
name="password"
type="password"
placeholder={t9n.t.registration.password}
/>
<Buttons>
<Button onClick={this.submit}>{t9n.t.confirm.yes}</Button>
<ActionButton onClick={onNo}>{t9n.t.confirm.no}</ActionButton>
</Buttons>
</Div>
</Modal>
);
}
change = event => {
this.password = event.target.value;
this.invalid = false;
};
submit = () => {
if (!this.password) {
this.invalid = true;
return;
}
this.props.onYes(this.password).catch(error => {
this.invalid = true;
});
};
}
decorate(ConfirmationWithPassword, {
password: observable,
invalid: observable,
change: action,
submit: action
});
const Div = styled(Container)`
width: 30rem;
margin: 4rem auto;
position: relative;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
cursor: default;
`;
const MessageDiv = styled.div`
width: 100%;
height: 8rem;
padding: 0 4rem;
line-height: 1.5rem;
box-sizing: border-box;
text-align: center;
display: flex;
align-items: center;
justify-content: center;
`;
const Message = styled.div`
font-size: 1.1rem;
color: ${styles.color.text};
`;
const Buttons = styled.div`
display: flex;
flex-shrink: 0;
width: 100%;
`;
export default inject("t9n")(observer(ConfirmationWithPassword));
<file_sep>/src/components/ConfirmationWithPassword/index.js
import ConfirmationWithPassword from "./ConfirmationWithPassword";
export default ConfirmationWithPassword;
<file_sep>/src/components/FoodAdd/components/Foodstuff.js
import React from "react";
import styled from "styled-components";
import styles from "../../../styles/constants";
import { inject, observer } from "mobx-react";
import Flex from "../../Flex";
import Column from "./Column";
import FixedColumn from "./FixedColumn";
import ThinColumn from "./ThinColumn";
import Remove from "../../Remove";
function Foodstuff({ auth, t9n, foodstuff, use, remove }) {
console.log("Hello", foodstuff);
return (
<FoodstuffRow onClick={() => use(foodstuff)}>
<FixedColumn>{foodstuff.quantityWithUnit}</FixedColumn>
<Column>{foodstuff.name}</Column>
<FixedColumn>{foodstuff.caloriesWithUnit}</FixedColumn>
<FixedColumn>{foodstuff.carbsWithUnit}</FixedColumn>
<FixedColumn>{foodstuff.proteinsWithUnit}</FixedColumn>
<FixedColumn>{foodstuff.fatsWithUnit}</FixedColumn>
{auth.user.type === 1 && <ThinColumn>
<Remove message={t9n.t.confirm.foodstuff} remove={() => remove(foodstuff)} />
</ThinColumn>}
</FoodstuffRow>
);
}
const FoodstuffRow = styled(Flex)`
border-bottom: solid 1px ${styles.borderColor.gray};
cursor: pointer;
user-select: none;
&:hover {
background-color: #f5f5f5;
}
&:last-child {
border-bottom: 0;
}
`;
export default inject("auth", "t9n")(observer(Foodstuff));
<file_sep>/src/components/FoodstuffAdd/FoodstuffAdd.js
import React, { Component } from "react";
import styled from "styled-components";
import styles from "../../styles/constants";
import { decorate, observable, action } from "mobx";
import { inject, observer } from "mobx-react";
import Flex from "../Flex";
import Modal from "../Modal";
import Input from "../Input";
import Select from "../Select";
import Button from "../Button";
import ActionButton from "../ActionButton";
import Container from "../Container";
class FoodstuffAdd extends Component {
constructor(props) {
super(props);
this.values = {
name: "",
quantity: "",
unit: "",
calories: "",
carbs: "",
proteins: "",
fats: "",
sugars: "",
salt: "",
saturates: ""
};
this.invalid = {
name: false,
quantity: false,
unit: false,
calories: false,
carbs: false,
proteins: false,
fats: false,
sugars: false,
salt: false,
saturates: false
};
}
render() {
return (
<Modal>
<Div>
<Row>
<Input
onChange={this.change}
value={this.values.name}
invalid={this.invalid.name}
name="name"
placeholder={this.props.t9n.t.name}
/>
</Row>
<Row>
<Input
onChange={this.change}
value={this.values.quantity}
invalid={this.invalid.quantity}
name="quantity"
placeholder={this.props.t9n.t.quantity}
/>
<Select
onChange={this.change}
value={this.values.unit}
invalid={this.invalid.unit}
name="unit"
placeholder={this.props.t9n.t.unit}
options={[
{ value: "g", name: this.props.t9n.t.g },
{ value: "pc", name: this.props.t9n.t.pc },
{ value: "ml", name: this.props.t9n.t.ml }
]}
/>
</Row>
{[
"calories",
"fats",
"saturates",
"carbs",
"sugars",
"proteins",
"salt"
].map(value => (
<Row key={value}>
<Input
onChange={this.change}
value={this.values[value]}
invalid={this.invalid[value]}
name={value}
placeholder={this.props.t9n.t.label[value]}
/>
</Row>
))}
<Row>
<ActionButton onClick={this.submit}>
{this.props.t9n.t.add}
</ActionButton>
<Button
onClick={() => {
this.props.close();
this.clear();
}}
>
{this.props.t9n.t.cancel}
</Button>
</Row>
</Div>
</Modal>
);
}
change = event => {
const { name, value } = event.target;
this.values[name] = value;
};
clear = event => {
for (const key in this.values) {
this.values[key] = "";
this.invalid[key] = false;
}
};
setValid = (names, valid) => {
if (!(names instanceof Array)) {
names = [names];
}
for (const key in this.invalid) {
this.invalid[key] = false;
}
for (let i = 0; i < names.length; ++i) {
this.invalid[names[i]] = !valid;
}
};
submit = () => {
this.props.auth.foodstuffs
.add(this.values)
.then(data => {
this.props.close();
this.props.use(data);
})
.catch(error => {
if (error.code === 422) {
this.setValid(error.details.invalid, false);
} else {
console.error(error);
}
});
};
}
decorate(FoodstuffAdd, {
values: observable,
invalid: observable,
setValid: action,
change: action
});
const Div = styled(Container)`
width: 35rem;
margin: auto;
`;
const Row = styled(Flex)`
border-bottom: solid 1px ${styles.borderColor.gray};
&:last-child {
border-bottom: 0;
}
`;
export default inject("auth", "t9n")(observer(FoodstuffAdd));
<file_sep>/src/components/ChartContainer/ChartContainer.js
import styled from "styled-components";
import Container from "../Container";
export default styled(Container)`
padding: 1rem;
box-sizing: border-box;
`;
<file_sep>/src/scenes/Quantities/Quantities.js
import React, { Component } from "react";
import styled from "styled-components";
import { action, decorate, observable } from "mobx";
import { inject, observer } from "mobx-react";
import Body from "../../components/Body";
import QuantityList from "../../components/QuantityList";
import QuantityDetails from "../../components/QuantityDetails";
import QuantityAdd from "../../components/QuantityAdd";
class Quantities extends Component {
constructor(props) {
super(props);
this.quantity = null;
this.adding = false;
document.title = props.t9n.t.navigation.quantities;
}
render() {
const { quantities } = this.props.auth.user;
if (quantities === null) {
return null;
}
if (this.quantity === null) {
this.quantity = quantities.quantities[0];
}
return (
<Content>
<QuantityList
quantities={quantities}
showDetails={this.showDetails}
showAdder={this.showAdder}
/>
<Main>
<Body>
{this.quantity && !this.quantity.deleted && (
<QuantityDetails
quantity={this.quantity}
close={this.hideDetails}
/>
)}
{this.adding && (
<QuantityAdd
close={this.hideAdder}
showDetails={this.showDetails}
/>
)}
</Body>
</Main>
</Content>
);
}
showAdder = () => {
this.adding = true;
};
hideAdder = () => {
this.adding = false;
};
showDetails = quantity => {
this.quantity = quantity;
};
hideDetails = () => {
this.quantity = null;
};
}
decorate(Quantities, {
quantity: observable,
adding: observable,
showAdder: action,
hideAdder: action,
showDetails: action,
hideDetails: action
});
const Content = styled.div`
display: flex;
flex-direction: row;
flex: 1 1 100%;
min-height: 0;
@media screen and (max-width: 40rem) {
overflow-y: auto;
}
`;
const Main = styled.div`
width: 100%;
height: 100%;
overflow: auto;
@media screen and (max-width: 40rem) {
min-width: 100vw;
}
`;
export default inject("auth", "t9n")(observer(Quantities));
<file_sep>/src/models/Food.js
import { computed, decorate, extendObservable, observable } from "mobx";
import { client } from "../utils/ApiClient";
import t9n from "./Translator";
export default class Food {
meal = null;
constructor(data, meal) {
extendObservable(this, data);
this.meal = meal;
}
get quantityWithUnit() {
if (this.unit === "pc") {
return parseFloat(this.quantity.toFixed(2)) + t9n.t[this.unit.trim()];
}
return Math.round(this.quantity) + t9n.t[this.unit.trim()];
}
get caloriesWithUnit() {
return Math.round(this.calories);
}
get carbsWithUnit() {
return Math.round(this.carbs) + t9n.t.g;
}
get proteinsWithUnit() {
return Math.round(this.proteins) + t9n.t.g;
}
get fatsWithUnit() {
return Math.round(this.fats) + t9n.t.g;
}
delete() {
return client
.delete("/user/meal/food", {
user_id: this.meal.meals.day.user.id,
food_id: this.id
})
.then(data => {
this.meal.remove(this);
});
}
}
decorate(Food, {
_meal: observable,
quantityWithUnit: computed,
caloriesWithUnit: computed,
carbsWithUnit: computed,
proteinsWithUnit: computed,
fatsWithUnit: computed
});
<file_sep>/src/models/Meal.js
import { action, computed, extendObservable, decorate } from "mobx";
import { client } from "../utils/ApiClient";
import t9n from "./Translator";
import Food from "./Food";
export default class Meal {
meals = null;
constructor(data, meals) {
this.meals = meals;
data.foods = data.foods.map(food => new Food(food, this));
extendObservable(this, data);
}
get name() {
return t9n.t.mealNames[this.type];
}
get calories() {
return this.sumValues("calories");
}
get carbs() {
return this.sumValues("carbs");
}
get proteins() {
return this.sumValues("proteins");
}
get fats() {
return this.sumValues("fats");
}
get caloriesWithUnit() {
return Math.round(this.calories);
}
get carbsWithUnit() {
return Math.round(this.carbs) + t9n.t.g;
}
get proteinsWithUnit() {
return Math.round(this.proteins) + t9n.t.g;
}
get fatsWithUnit() {
return Math.round(this.fats) + t9n.t.g;
}
get empty() {
return this.foods.length === 0;
}
sumValues(key) {
let sum = 0;
for (let i = 0; i < this.foods.length; ++i) {
sum += this.foods[i][key];
}
return sum;
}
findFoodIndexByFoodstuffId(foodstuff_id) {
for (let i = 0; i < this.foods.length; ++i) {
if (this.foods[i].foodstuff_id === foodstuff_id) {
return i;
}
}
return -1;
}
findFoodIndexById(id) {
for (let i = 0; i < this.foods.length; ++i) {
if (this.foods[i].id === id) {
return i;
}
}
return -1;
}
add(foodstuff_id, quantity) {
quantity = parseFloat(quantity.replace(",", "."));
const index = this.findFoodIndexByFoodstuffId(foodstuff_id);
if (index !== -1) {
quantity += this.foods[index].quantity;
}
return client
.post("/user/meal/food", {
user_id: this.meals.day.user.id,
meal_id: this.id,
foodstuff_id: foodstuff_id,
quantity: quantity
})
.then(data => {
const food = new Food(data, this);
if (index === -1) {
this.foods.push(food);
} else {
this.foods[index] = food;
}
});
}
remove(food) {
const index = this.findFoodIndexById(food.id);
if (index >= 0) {
this.foods.splice(index, 1);
}
}
}
decorate(Meal, {
name: computed,
calories: computed,
carbs: computed,
proteins: computed,
fats: computed,
empty: computed,
add: action,
remove: action
});
<file_sep>/src/components/QuantityDetails/components/MeasurementAdd.js
import React, { Component } from "react";
import styled from "styled-components";
import styles from "../../../styles/constants";
import { action, decorate, observable } from "mobx";
import { inject, observer } from "mobx-react";
import Input from "../../Input";
import Select from "../../Select";
import ActionButton from "../../ActionButton";
import Quantity from "../../../models/Quantity";
class MeasurementAdd extends Component {
constructor(props) {
super(props);
this.value = "";
this.invalid = false;
}
render() {
const quantity = this.props.quantity;
if (quantity.type === Quantity.ACTIVENESS) {
return (
<Form onSubmit={this.update}>
<Select
placeholder={quantity.prettyName}
value={this.value}
invalid={this.invalid}
onChange={this.change}
options={[
{ value: 0, name: this.props.t9n.t.activeness.minimal },
{ value: 1, name: this.props.t9n.t.activeness.low },
{ value: 2, name: this.props.t9n.t.activeness.medium },
{ value: 3, name: this.props.t9n.t.activeness.high },
{ value: 4, name: this.props.t9n.t.activeness.veryHigh }
]}
/>
</Form>
);
}
return (
<Form onSubmit={this.update} noValidate>
<Input
placeholder={quantity.prettyName}
value={this.value}
invalid={this.invalid}
onChange={this.change}
innerRef={input => input && input.focus()}
noAnimation
type={"number"}
/>
<Unit>{quantity.prettyUnit}</Unit>
<NarrowActionButton>{this.props.t9n.t.update}</NarrowActionButton>
</Form>
);
}
clear = () => {
this.value = "";
this.invalid = false;
};
change = event => {
this.value = event.target.value;
if (this.props.quantity.type === Quantity.ACTIVENESS) {
this.update();
}
};
update = event => {
if (event) {
event.preventDefault();
}
if (this.value === "") {
this.invalid = true;
return;
}
this.props.quantity
.add(this.value)
.then(() => {
this.clear();
})
.catch(error => {
if (error.code === 422) {
this.invalid = true;
} else {
console.error(error);
}
});
};
}
decorate(MeasurementAdd, {
value: observable,
invalid: observable,
change: action,
update: action
});
const Form = styled.form`
display: flex;
width: 100%;
box-sizing: border-box;
height: 3.5rem;
background-color: white;
box-shadow: ${styles.boxShadow._1};
`;
const NarrowActionButton = styled(ActionButton)`
width: 8rem;
flex-shrink: 0;
`;
const Unit = styled.div`
line-height: 3.5rem;
color: ${styles.color.text};
padding: 0 1rem;
`;
export default inject("t9n")(observer(MeasurementAdd));
<file_sep>/src/components/FoodAdd/index.js
import FoodAdd from "./FoodAdd";
export default FoodAdd;
<file_sep>/src/components/MeasurementChart/index.js
import MeasurementChart from "./MeasurementChart";
export default MeasurementChart;
<file_sep>/src/components/Progresses/components/Progress.js
import React from "react";
import styled from "styled-components";
import styles from "../../../styles/constants";
import { inject, observer } from "mobx-react";
import ProgressBar from "./ProgressBar";
import Container from "../../Container";
function Progress({ t9n, title, progress, total, calories, past }) {
let difference, message, over;
let percentage = progress / total * 100;
if (progress < total) {
difference = Math.round(total) - Math.round(progress);
message = past ? t9n.t.progress.under : t9n.t.progress.left;
over = false;
} else {
difference = Math.round(progress) - Math.round(total);
message = t9n.t.progress.over;
percentage = Math.min(percentage - 100, 100);
over = true;
}
let unit = t9n.t.g;
if (calories) {
unit = "";
}
return (
<Div>
<ProgressBar percentage={percentage} over={over} />
<Header>
<Title>{title}</Title>
<Status>
({Math.round(progress)}
{unit}/{Math.round(total)}
{unit})
</Status>
<Left>
<strong>
{difference}
{unit}
</strong>{" "}
{message}
</Left>
</Header>
</Div>
);
}
const Div = styled(Container)`
margin-right: 1rem;
&:last-child {
margin-right: 0;
}
`;
const Header = styled.div`
display: flex;
padding: 0 1rem;
align-items: center;
justify-content: center;
line-height: 3.5rem;
color: ${styles.color.text};
`;
const Title = styled.div`
font-weight: bold;
`;
const Status = styled.div`
margin-left: 0.5rem;
font-size: 0.9rem;
width: 100%;
`;
const Left = styled.div`
white-space: nowrap;
`;
export default inject("t9n")(observer(Progress));
<file_sep>/src/components/RatioChanger/RatioChanger.js
import React, { Component } from "react";
import styled from "styled-components";
import { action, decorate, observable } from "mobx";
import { inject, observer } from "mobx-react";
import getTotals from "../../utils/totals";
import styles from "../../styles/constants";
import Section from "../Section";
import InputSection from "./components/InputSection";
import SliderSection from "./components/SliderSection";
class RatioChanger extends Component {
constructor(props) {
super(props);
let { date, measurements, ratios, totals } = this.props.user;
this.ratios = ratios
? { ...ratios }
: { delta: 0, carbs: 40, proteins: 30, fats: 30 };
if (!totals && measurements) {
totals = getTotals(this.props.user, {
date,
measurements,
ratios: this.ratios
});
}
if (totals) {
this.totals = { ...totals };
this.totals.calories = Math.round(this.totals.calories);
}
}
render() {
return (
<FlexSection>
{this.totals && (
<Column>
<InputSection
title={this.props.t9n.t.ratioChanger.calories}
value={this.totals.calories}
onChange={this.onCalorieChange}
/>
</Column>
)}
<Column>
<InputSection
title={this.props.t9n.t.ratioChanger.change}
value={this.ratios.delta}
onChange={this.onDeltaChange}
/>
</Column>
<FillColumn>
<SliderSection
ratios={this.ratios}
totals={this.totals}
measurements={this.props.user.measurements}
onChange={this.onSliderChange}
onAfterChange={this.updateRatios}
/>
</FillColumn>
</FlexSection>
);
}
onCalorieChange = event => {
const value = event.target.value;
const intValue = parseInt(value, 10);
if (!isNaN(intValue)) {
const defaultTotal = this.totals.defaultCalories;
this.totals.calories = intValue;
this.ratios.delta = Math.round((intValue / defaultTotal - 1) * 100);
this.updateRatios("calories");
} else {
this.totals.calories = value;
}
};
onDeltaChange = event => {
const value = event.target.value;
const intValue = parseInt(value, 10);
if (!isNaN(intValue)) {
this.ratios.delta = intValue;
this.updateRatios("delta");
} else {
this.ratios.delta = value;
}
};
onSliderChange = values => {
const [first, second] = values;
this.ratios.carbs = first;
this.ratios.proteins = second - first;
this.ratios.fats = 100 - second;
if (this.totals) {
const { date, measurements } = this.props.user;
this.totals = getTotals(this.props.user, {
date,
measurements,
ratios: this.ratios
});
this.totals.calories = Math.round(this.totals.calories);
}
};
updateRatios = (by = null) => {
this.props.user.addRatios(this.ratios).then(ratios => {
if (by === "delta") {
const delta = this.ratios.delta;
this.props.user.ratios = ratios;
this.ratios = ratios;
this.ratios.delta = delta;
} else {
this.props.user.ratios = ratios;
this.ratios = ratios;
}
if (this.props.onChange) {
this.props.onChange(ratios);
}
const totals = this.props.user.totals;
if (!totals) {
return;
}
if (by === "calories") {
const calories = this.totals.calories;
this.totals = totals;
this.totals.calories = calories;
} else {
this.totals = totals;
this.totals.calories = Math.round(this.totals.calories);
}
});
};
}
decorate(RatioChanger, {
ratios: observable,
totals: observable,
onCalorieChange: action,
onDeltaChange: action,
onSliderChange: action,
updateRatios: action
});
const FlexSection = styled(Section)`
display: flex;
`;
const Column = styled.div`
width: 20%;
height: 8rem;
margin-right: 1rem;
flex-shrink: 0;
&:last-child {
margin-right: 0;
}
@media screen and (max-width: 40rem) {
margin-right: 0;
border-right: solid 1px ${styles.borderColor.gray};
&:last-child {
border-right: 0;
}
}
`;
const FillColumn = styled(Column)`
width: 100%;
flex-shrink: 1;
`;
export default inject("t9n")(observer(RatioChanger));
<file_sep>/src/components/Remove/Remove.js
import React, { Component } from "react";
import styled from "styled-components";
import styles from "../../styles/constants";
import { action, decorate, observable } from "mobx";
import { observer } from "mobx-react";
import Confirmation from "../Confirmation";
import ConfirmationWithPassword from "../ConfirmationWithPassword";
class Remove extends Component {
constructor(props) {
super(props);
this.confirmation = false;
}
render() {
const { remove, message, withPassword, children } = this.props;
return (
<div>
{(children && (
<Button onClick={this.showConfirmation}>{children}</Button>
)) || <Button onClick={this.showConfirmation}>✖</Button>}
{this.confirmation &&
(withPassword ? (
<ConfirmationWithPassword
message={message}
onYes={remove}
onNo={this.hideConfirmation}
/>
) : (
<Confirmation
message={message}
onYes={remove}
onNo={this.hideConfirmation}
/>
))}
</div>
);
}
showConfirmation = event => {
this.confirmation = true;
event.stopPropagation();
};
hideConfirmation = () => {
this.confirmation = false;
};
}
const Button = styled.div`
cursor: pointer;
user-select: none;
color: ${styles.color.text};
transition: 0.2s;
&:hover {
color: red;
}
`;
decorate(Remove, {
confirmation: observable,
showConfirmation: action,
hideConfirmation: action
});
export default observer(Remove);
<file_sep>/src/components/ClientList/components/CodeGenerator.js
import React, { Component } from "react";
import { inject, observer } from "mobx-react";
import Modal from "../../Modal";
import ModalHeader from "../../ModalHeader";
import Body from "../../Section";
import Container from "../../Container";
import Flex from "../../Flex";
import Input from "../../Input";
class CodeGenerator extends Component {
render() {
return (
<Modal>
<ModalHeader
title={this.props.t9n.t.generatedCode}
close={this.props.close}
/>
{this.props.code && (
<Body>
<Container>
<Flex>
<Input
value={this.props.code}
innerRef={input => input && input.select()}
readOnly
/>
</Flex>
</Container>
</Body>
)}
</Modal>
);
}
copy = () => {};
}
export default inject("t9n")(observer(CodeGenerator));
<file_sep>/src/components/QuantityDetails/components/Measurements.js
import React from "react";
import styled from "styled-components";
import { inject, observer } from "mobx-react";
import styles from "../../../styles/constants";
import moment from "moment";
import Flex from "../../Flex";
import Container from "../../Container";
import Remove from "../../Remove";
import Quantity from "../../../models/Quantity";
function Measurements({ t9n, measurements }) {
return (
<Div>
<Flex>
<TitleColumn>{t9n.t.measurement.date}</TitleColumn>
<TitleColumn>{t9n.t.measurement.value}</TitleColumn>
<RemoveColumn />
</Flex>
{measurements.map(measurement => (
<Flex key={measurement.id.toString()}>
<Column>{moment(measurement.date).format("DD.MM.YYYY")}</Column>
<Column>
{measurement.quantity.type === Quantity.ACTIVENESS
? t9n.t.activeness[Quantity.ACTIVENESS_NAMES[measurement.value]]
: measurement.value}
</Column>
<RemoveColumn>
<Remove
remove={measurement.delete}
message={t9n.t.confirm.measurement}
/>
</RemoveColumn>
</Flex>
))}
</Div>
);
}
const Div = styled(Container)`
max-width: 30rem;
margin: auto;
color: ${styles.color.text};
`;
const Column = styled.div`
width: 100%;
padding: 0 1rem;
line-height: 3.5rem;
text-align: center;
`;
const RemoveColumn = styled(Column)`
width: 2.5rem;
display: flex;
align-items: center;
justify-content: center;
`;
const TitleColumn = styled(Column)`
font-weight: bold;
`;
export default inject("t9n")(observer(Measurements));
<file_sep>/src/scenes/Login/Login.js
import React, { Component } from "react";
import styled from "styled-components";
import { Redirect } from "react-router-dom";
import { inject, observer } from "mobx-react";
import Error from "../../components/Error";
import { Input } from "../../next/component/Input";
import { Button } from "../../next/component/Button";
import { declarations } from "../../next/style/declarations";
class Login extends Component {
constructor(props) {
super(props);
this.state = {
values: {
email: "",
password: ""
},
invalid: {
global: false,
emai: false,
password: false
},
redirect: false
};
document.title = "Logi sisse";
}
render() {
if (this.state.redirect) {
return <Redirect to="/" />;
}
return (
<Div>
<Form onSubmit={this.login} noValidate>
<Title>Morkovka</Title>
<CustomError>
{this.state.invalid.global && "E-posti aadress ja parool ei kattu."}
</CustomError>
<Input
onChange={this.change}
value={this.state.values.email}
error={
this.state.invalid.email
? "Sisestage e-posti aadress."
: undefined
}
name="email"
type="email"
placeholder="E-posti aadress"
/>
<Input
onChange={this.change}
value={this.state.values.password}
error={
this.state.invalid.password ? "<PASSWORD>." : undefined
}
name="password"
type="password"
placeholder="<PASSWORD>"
/>
<Button
type="submit"
hasError={
this.state.invalid.emai ||
this.state.invalid.password ||
this.state.invalid.global
}
>
Logi sisse
</Button>
</Form>
</Div>
);
}
change = event => {
const { name, value } = event.target;
const values = this.state.values;
const invalid = this.state.invalid;
values[name] = value;
invalid[name] = false;
invalid.global = false;
this.setState({ values, invalid });
};
setValid = (names, valid) => {
if (!(names instanceof Array)) {
names = [names];
}
const invalid = this.state.invalid;
for (const key in invalid) {
invalid[key] = false;
}
for (let i = 0; i < names.length; ++i) {
invalid[names[i]] = !valid;
}
this.setState({ invalid });
};
login = event => {
event.preventDefault();
if (!this.state.values.email && !this.state.values.password) {
return this.setValid(["email", "password"], false);
} else if (!this.state.values.email) {
return this.setValid("email", false);
} else if (!this.state.values.password) {
return this.setValid("password", false);
}
this.props.auth
.login(this.state.values)
.then(() => {
this.setState({ redirect: true });
})
.catch(error => {
if (error.code === 400) {
return this.setValid("global", false);
}
if (error.code === 422) {
return this.setValid(error.details.invalid, false);
}
console.log(error);
});
};
}
const Div = styled.div`
max-width: 32rem;
height: 100%;
overflow-y: auto;
box-sizing: border-box;
background-color: white;
box-shadow: 0 0 1rem rgba(0, 0, 0, 0.16);
@media screen and (max-width: 40rem) {
max-width: 100%;
box-shadow: none;
}
`;
const CustomError = styled(Error)`
width: 100%;
height: 1rem;
font-weight: 300;
color: ${declarations.color.error};
display: flex;
align-items: center;
margin-bottom: 2rem;
justify-content: center;
`;
const Title = styled.div`
width: 100%;
height: 2.5rem;
font-size: 1.5rem;
display: flex;
align-items: center;
justify-content: center;
`;
const Form = styled.form`
width: 100%;
max-width: 30rem;
padding: 2rem;
box-sizing: border-box;
margin: 4rem auto;
`;
export default inject("auth")(observer(Login));
<file_sep>/src/components/MealAdd/MealAdd.js
import React, { Component } from "react";
import styled from "styled-components";
import styles from "../../styles/constants";
import ActionButton from "../ActionButton";
import { observer, inject } from "mobx-react";
class MealAdd extends Component {
render() {
const { t9n, meals } = this.props;
return (
<Container>
{["breakfast", "lunch", "dinner", "snack"].map(
value =>
!meals.existsByName(value) && (
<AddButton key={value} name={value} onClick={this.add}>
{t9n.t.addMeal[value]}
</AddButton>
)
)}
</Container>
);
}
add = event => {
this.props.meals.add(event.target.name);
};
}
const Container = styled.div`
display: flex;
transition: 0.2s;
`;
const AddButton = styled(ActionButton)`
box-shadow: ${styles.boxShadow._1};
margin-right: 1rem;
min-width: 0;
&:last-child {
margin-right: 0;
}
@media screen and (max-width: 40rem) {
white-space: pre-wrap;
line-height: 1.15rem;
}
`;
export default inject("t9n")(observer(MealAdd));
<file_sep>/src/components/BodyMassIndexScale/BodyMassIndexScale.js
import React from "react";
import styled from "styled-components";
import round from "../../utils/round";
import { Link } from "react-router-dom";
import { inject, observer } from "mobx-react";
import Flex from "../Flex";
import Section from "../Section";
import SectionTitle from "../SectionTitle";
import Container from "../Container";
import styles from "../../styles/constants";
const bodyMassIndexRanges = [
{ class: 0, min: -Infinity, lt: 16 },
{ class: 1, min: 16, lt: 18.5 },
{ class: 2, min: 18.5, lt: 25 },
{ class: 3, min: 25, lt: 30 },
{ class: 4, min: 30, lt: 35 },
{ class: 5, min: 35, lt: 40 },
{ class: 6, min: 40, lt: Infinity }
];
function getRangeIndex(bodyMassIndex) {
for (let i = 0; i < bodyMassIndexRanges.length; ++i) {
const range = bodyMassIndexRanges[i];
if (range.min <= bodyMassIndex && bodyMassIndex < range.lt) {
return i;
}
}
}
function BodyMassIndexScale({ t9n, user }) {
const { measurements } = user;
if (!measurements) {
return (
<Section>
<SectionTitle>{t9n.t.title.bmi}</SectionTitle>
<Div>
<A to="/quantities">
{t9n.t.bmi.noData}
</A>
</Div>
</Section>
);
}
const { mass, height } = measurements;
const heightSquared = height * height / 100 / 100;
const bmi = mass / heightSquared;
const index = getRangeIndex(bmi);
const range = bodyMassIndexRanges[index];
const lowerRange = bodyMassIndexRanges[index - 1];
const upperRange = bodyMassIndexRanges[index + 1];
const lowerMass = round(range.min * heightSquared, 1);
const upperMass = round(range.lt * heightSquared, 1);
let percentage;
if (lowerRange && upperRange) {
percentage = (mass - lowerMass) / (upperMass - lowerMass) * 100;
} else {
percentage = lowerRange ? 10 : 90;
}
return (
<Section>
<SectionTitle>{t9n.t.title.bmi}</SectionTitle>
<Div>
{lowerRange && <Side>{t9n.t.bmiRanges[lowerRange.class]}</Side>}
{lowerRange && <Post value={lowerMass} />}
<Background>
{t9n.t.bmiRanges[range.class]}
<Post value={mass} primary percentage={percentage} />
</Background>
{upperRange && <Post value={upperMass} />}
{upperRange && <Side>{t9n.t.bmiRanges[upperRange.class]}</Side>}
</Div>
</Section>
);
}
const Div = styled(Container)`
display: flex;
height: 3.5rem;
align-items: center;
justify-content: center;
white-space: pre-wrap;
text-align: center;
`;
const A = styled(Link)`
color: red;
text-decoration: underline;
`;
const Background = styled(Flex)`
height: 100%;
position: relative;
align-items: center;
justify-content: center;
color: ${styles.color.text};
`;
const Side = styled(Background)`
width: 25%;
flex-shrink: 0;
`;
function Post({ value, primary, percentage }) {
if (primary) {
return (
<ZeroWidthAbsolute percentage={percentage}>
<PostValue primary>{value}</PostValue>
<PostBody primary />
</ZeroWidthAbsolute>
);
}
return (
<ZeroWidth>
<PostValue>{value}</PostValue>
<PostBody />
</ZeroWidth>
);
}
const ZeroWidth = styled(Background)`
width: 0;
flex-direction: column;
`;
const ZeroWidthAbsolute = styled(ZeroWidth)`
bottom: 0;
position: absolute;
z-index: 1;
left: ${props => props.percentage + "%"};
`;
const PostValue = styled.div`
padding: 0.2rem 0.5rem;
color: ${styles.color.text};
font-size: 0.9rem;
white-space: nowrap;
${props =>
props.primary &&
"background: linear-gradient(90deg, #ffffff00 0%, #ffffff 10%, #ffffff 90%, #ffffff00 100%)"};
`;
const PostBody = styled.div`
width: ${props => (props.primary && "0.5rem") || "0.25rem"};
height: 100%;
opacity: ${props => (props.primary && 1) || 0.6};
background-color: ${styles.backgroundColor.primary};
`;
export default inject("t9n")(observer(BodyMassIndexScale));
<file_sep>/src/components/ConsumptionChart/ConsumptionChart.js
import React from "react";
import { Bar } from "react-chartjs-2";
import ChartContainer from "../ChartContainer";
export default function ConsumptionChart({ of, label, data, onElementsClick }) {
const labels = data.map(({ date }) => date);
const consumed = data.map(({ consumed }) => Math.round(consumed[of]));
const totals = data.map(({ totals }) =>
totals ? Math.round(totals[of]) : null
);
const backgroundColors = [];
const borderColors = [];
for (let i = 0; i < totals.length; ++i) {
let limit = totals[i];
let actual = consumed[i];
if (limit === null) {
backgroundColors.push("#f5f5f5");
borderColors.push("#333333");
} else if (Math.abs(limit - actual) / limit <= 0.15) {
backgroundColors.push("#92e492");
borderColors.push("#279f27");
} else {
backgroundColors.push("#ff9784");
borderColors.push("#fa2600");
}
}
const chartData = {
labels,
datasets: [
{
type: "line",
label,
data: totals,
fill: false,
borderColor: "#279f27",
pointBackgroundColor: "#279f27"
},
{
type: "bar",
label,
data: consumed,
backgroundColor: backgroundColors,
borderColor: borderColors,
borderWidth: 1
}
]
};
const chartOptions = {
elements: {
point: {
radius: 0
}
},
legend: {
display: false
},
layout: {
padding: {
top: 5
}
},
scales: {
xAxes: [
{
ticks: {
maxRotation: 0,
minRotation: 0,
autoSkip: true
},
gridLines: {
display: false
},
offset: true,
type: "time",
time: {
unit: "day",
stepSize: 1,
displayFormats: {
day: "DD"
},
tooltipFormat: "DD.MM.YYYY"
}
}
],
yAxes: [
{
display: false,
gridLines: {
display: false
},
ticks: {
beginAtZero: true
}
}
]
}
};
return (
<ChartContainer>
<Bar
height={100}
data={chartData}
options={chartOptions}
onElementsClick={onElementsClick}
/>
</ChartContainer>
);
}
<file_sep>/src/components/Tabs/Tabs.js
import React from "react";
import styled from "styled-components";
import styles from "../../styles/constants";
export default function Tabs({ tabs, selected, select }) {
return (
<Container>
<TabPlacer>
<TabList selected={selected}>
{tabs.map((value, index) => (
<Tab
key={index.toString()}
selected={index === selected}
onClick={() => select(index)}
>
{value}
</Tab>
))}
</TabList>
</TabPlacer>
</Container>
);
}
const Container = styled.div`
width: 100%;
overflow: hidden;
background-color: white;
`;
const TabPrototype = styled.div`
width: 15rem;
height: 3.5rem;
`;
const TabPlacer = styled(TabPrototype)`
margin: 0 auto;
position: relative;
`;
const TabList = styled.div`
display: flex;
position: absolute;
left: ${props => props.selected * -100 + "%"};
transition: 0.2s;
`;
const Tab = styled(TabPrototype)`
flex-shrink: 0;
color: ${props =>
(props.selected && styles.color.textDark) || styles.color.textLight};
display: flex;
align-items: center;
justify-content: center;
cursor: pointer;
user-select: none;
transition: 0.2s;
&:hover {
color: ${styles.color.textDark};
}
`;
<file_sep>/src/components/QuantityList/components/Quantity.js
import React from "react";
import styled from "styled-components";
import { inject, observer } from "mobx-react";
import Remove from "../../Remove";
import Item from "./Item";
function Quantity({ t9n, quantity, showDetails }) {
return (
<Item onClick={() => showDetails(quantity)}>
<Center>
<Aligner>
{quantity.value !== null && <Value>{quantity.prettyValue}</Value>}
{quantity.prettyName}
</Aligner>
</Center>
{quantity.deletable && (
<RemoveContainer>
<Remove
message={t9n.t.confirm.quantity}
remove={() => quantity.delete()}
/>
</RemoveContainer>
)}
</Item>
);
}
const Center = styled.div`
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
`;
const Aligner = styled.div`
display: flex;
align-items: center;
flex-direction: column;
`;
const Value = styled.div`
font-size: 1.8rem;
margin-bottom: 0.5rem;
`;
const RemoveContainer = styled.div`
position: absolute;
top: 0;
right: 0;
padding: 1rem;
`;
export default inject("t9n")(observer(Quantity));
<file_sep>/src/models/Foodstuffs.js
import { client } from "../utils/ApiClient";
import Foodstuff from "./Foodstuff";
export default class Foodstuffs {
find(query) {
return client
.get("/foodstuffs", { query })
.then(data => data.map(foodstuff => new Foodstuff(foodstuff)));
}
add(foodstuff) {
return client.post("/foodstuffs", foodstuff);
}
}
<file_sep>/src/styles/constants.js
export default {
color: {
text: "rgba(0, 0, 0, 0.7)",
textDark: "rgba(0, 0, 0, 9)",
textLight: "rgba(0, 0, 0, 0.5)",
textAction: "#119527"
},
backgroundColor: {
slate: "#dddddd",
slateAction: "#d0d0d0",
primary: "#11aa33",
primaryAction: "#119527",
primaryLight: "#11aa3333"
},
borderColor: {
gray: "rgba(0, 0, 0, 0.2)"
},
boxShadow: {
_1: "0 2px 3px rgba(0, 0, 0, 0.2)"
}
};
<file_sep>/src/components/RatioChanger/components/InputSection.js
import React from "react";
import styled from "styled-components";
import styles from "../../../styles/constants";
import Container from "../../Container";
import Input from "../../Input";
export default function InputSection({ title, ...props }) {
return (
<Div>
<Title>{title}</Title>
<ActualInput {...props} />
</Div>
);
}
const Div = styled(Container)`
height: 100%;
display: flex;
flex-direction: column;
`;
const Title = styled.div`
height: 2rem;
line-height: 2rem;
font-size: 0.9rem;
text-align: center;
flex-shrink: 0;
color: ${styles.color.text};
border-bottom: solid 1px ${styles.borderColor.gray};
overflow: hidden;
text-overflow: ellipsis;
`;
const ActualInput = styled(Input)`
text-align: center;
height: 100%;
font-size: 1.5rem;
position: absolute;
`;
<file_sep>/src/components/Input/Input.js
import React from "react";
import styled, { css } from "styled-components";
import styles from "../../styles/constants";
export default function Input({
value,
placeholder,
disabled,
noAnimation,
...rest
}) {
return (
<Div>
<ActualInput
value={value}
disabled={disabled}
placeholder={noAnimation && placeholder}
{...rest}
/>
{placeholder && !noAnimation && (
<Placeholder
valueExists={!!value}
disabled={disabled}
noAnimation={noAnimation}
>
{placeholder}
</Placeholder>
)}
</Div>
);
}
const Div = styled.div`
position: relative;
width: 100%;
height: 100%;
`;
const ActualInput = styled.input`
width: 100%;
border: none;
outline: none;
margin: 0;
padding: 0;
background: none;
color: ${styles.color.text};
padding: 1rem;
line-height: 1.5rem;
box-sizing: border-box;
background-color: white;
&::placeholder,
&:disabled {
color: ${styles.color.textLight};
}
${props => props.invalid && "background-color: #ffdddd"};
`;
const smallText = css`
padding-top: 0.5rem;
font-size: 0.8rem;
line-height: 0;
color: ${styles.color.text};
`;
const Placeholder = styled.div`
color: ${styles.color.textLight};
padding: 1rem;
line-height: 1.5rem;
position: absolute;
pointer-events: none;
top: 0;
left: 0;
transition: 0.2s;
${ActualInput}:focus ~ & {
${smallText};
}
${props => props.valueExists && smallText};
`;
<file_sep>/src/components/Navigation/Navigation.js
import React, { Component } from "react";
import { inject, observer } from "mobx-react";
import styled from "styled-components";
import { Link } from "react-router-dom";
import styles from "../../styles/constants";
import Flex from "../Flex";
class Navigation extends Component {
render() {
const { user } = this.props.auth;
if (user === null) {
return <Container />;
}
return (
<Container>
<Section>
<Item to="/counter">{this.props.t9n.t.navigation.counter}</Item>
<Item to="/quantities">{this.props.t9n.t.navigation.quantities}</Item>
<Item to="/progress">{this.props.t9n.t.navigation.progress}</Item>
<Item to="/history">{this.props.t9n.t.navigation.history}</Item>
{user.type === 1 && (
<Item to="/clients">{this.props.t9n.t.navigation.clients}</Item>
)}
</Section>
<Section>
<Item to="/settings">{this.props.t9n.t.navigation.settings}</Item>
<Item to="/logout" onClick={this.logout}>
{this.props.t9n.t.navigation.logout}
</Item>
</Section>
</Container>
);
}
logout = event => {
event.preventDefault();
this.props.auth.logout();
};
}
const Container = styled(Flex)`
flex-shrink: 0;
width: 100%;
overflow-x: auto;
min-height: 3.5rem;
justify-content: space-between;
background-color: ${styles.backgroundColor.slate};
`;
const Section = styled.div`
display: flex;
`;
const Item = styled(Link)`
line-height: 3.5rem;
padding: 0 1.5rem;
text-decoration: none;
color: ${styles.color.text};
cursor: pointer;
user-select: none;
transition: 0.2s;
&:hover {
color: ${styles.color.textDark};
}
`;
export default inject("auth", "t9n")(observer(Navigation));
<file_sep>/src/components/MealAdd/index.js
import MealAdd from "./MealAdd";
export default MealAdd;
<file_sep>/src/components/ClientList/ClientList.js
import React, { Component } from "react";
import styled from "styled-components";
import { inject, observer } from "mobx-react";
import ActionButton from "../ActionButton";
import Client from "./components/Client";
import CodeGenerator from "./components/CodeGenerator";
import { decorate, observable, action } from "mobx";
class ClientList extends Component {
constructor(props) {
super(props);
this.visible = false;
this.code = null;
}
render() {
const { t9n, clients, select, client: current } = this.props;
return (
<Container>
<ActionButton onClick={this.show}>{t9n.t.add}</ActionButton>
{this.visible && <CodeGenerator close={this.hide} code={this.code} />}
{clients.clients.map(client => (
<Client
key={client.id}
client={client}
select={select}
current={client === current}
/>
))}
</Container>
);
}
show = () => {
this.visible = true;
this.props.clients.generateLink().then(code => {
this.code = code;
});
};
hide = () => {
this.visible = false;
this.code = null;
};
}
decorate(ClientList, {
visible: observable,
code: observable,
show: action,
hide: action
});
const Container = styled.div`
width: 25rem;
height: 100%;
overflow-y: auto;
flex-shrink: 0;
background-color: white;
`;
export default inject("t9n")(observer(ClientList));
<file_sep>/src/scenes/Counter/Counter.js
import React, { Component } from "react";
import moment from "moment";
import { action, decorate, observable } from "mobx";
import { inject, observer } from "mobx-react";
import Body from "../../components/Body";
import Tabs from "../../components/Tabs";
import Section from "../../components/Section";
import Subsection from "../../components/Subsection";
import Progresses from "../../components/Progresses";
import MealAdd from "../../components/MealAdd";
import Meal from "../../components/Meal";
import FoodAdd from "../../components/FoodAdd";
class Counter extends Component {
constructor(props) {
super(props);
let day = new Date();
this.days = [];
for (let i = 0; i < 7; ++i) {
this.days.unshift(new Date(day));
day.setDate(day.getDate() - 1);
}
this.tabs = this.days.map(day => {
return `${props.t9n.t.days[day.getDay()]} (${moment(day).format(
"DD.MM"
)})`;
});
this.meal = null;
this.select(this.tabs.length - 1);
document.title = props.t9n.t.navigation.counter;
}
render() {
const day = this.props.auth.user.day;
return (
<div>
<Tabs tabs={this.tabs} selected={this.selected} select={this.select} />
{day && (
<Body>
<Section>
<Subsection>
<Progresses day={day} />
</Subsection>
<Subsection>
<MealAdd meals={day.meals} />
</Subsection>
</Section>
{day.meals.meals.map((meal, index) => (
<Meal
key={meal.id.toString()}
meal={meal}
addFood={this.addFood}
/>
))}
{this.meal && (
<FoodAdd
meal={this.meal}
close={this.closeFoodAdd}
openFoodstuff={this.openFoodstuff}
/>
)}
</Body>
)}
</div>
);
}
select = index => {
if (this.selected === index) {
return;
}
this.selected = index;
this.props.auth.user.loadDay(
this.days[this.selected].toISOString().split("T")[0]
);
};
addFood = meal => {
this.meal = meal;
};
closeFoodAdd = () => {
this.meal = null;
};
}
decorate(Counter, {
selected: observable,
meal: observable,
select: action,
addFood: action,
closeFoodAdd: action
});
export default inject("auth", "t9n")(observer(Counter));
<file_sep>/src/models/Clients.js
import { decorate, observable } from "mobx";
import User from "./User";
import { client } from "../utils/ApiClient";
export default class Clients {
clients = null;
user = null;
constructor(data, user) {
this.clients = data.map(user => new User(user, this));
this.user = user;
}
generateLink() {
return client.post("/user/client/code", { user_id: this.user.id });
}
remove(user) {
this.clients.remove(user);
}
}
decorate(Clients, {
clients: observable
});
<file_sep>/src/components/Meal/components/ExpandButton.js
import React from "react";
import styled from "styled-components";
import styles from "../../../styles/constants";
import Flex from "../../Flex";
export default function Add({ onClick }) {
return (
<Container>
<Button onClick={onClick}>+</Button>
</Container>
);
}
const Container = styled(Flex)`
height: 0;
align-items: center;
justify-content: center;
`;
const Button = styled.div`
width: 3.5rem;
height: 3.5rem;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
background-color: ${styles.backgroundColor.primary};
box-shadow: ${styles.boxShadow._1};
font-size: 1.5rem;
color: white;
cursor: pointer;
user-select: none;
transition: 0.2s;
:hover {
background-color: ${styles.backgroundColor.primaryAction};
}
`;
<file_sep>/src/utils/totals.js
import moment from "moment";
const activenessMultipliers = {
0: 1.2,
1: 1.375,
2: 1.55,
3: 1.725,
4: 1.9
};
export default function totals(user, day) {
const { date, ratios, measurements } = day;
if (!ratios || !measurements) {
return null;
}
const { sex, date_of_birth } = user;
const { mass, height, activeness } = measurements;
const { delta, carbs, proteins, fats } = ratios;
const age = moment(date).diff(moment(date_of_birth), "years");
const activenessMultiplier = activenessMultipliers[activeness];
let calories;
if (sex === "f") {
calories =
(655 + 9.5 * mass + 1.9 * height - 4.7 * age) * activenessMultiplier;
} else {
calories =
(66 + 13.8 * mass + 5.0 * height - 6.8 * age) * activenessMultiplier;
}
const totalCalories = calories * (100 + delta) / 100;
const totalCarbs = totalCalories * carbs / 100 / 4;
const totalProteins = totalCalories * proteins / 100 / 4;
const totalFats = totalCalories * fats / 100 / 9;
return {
defaultCalories: calories,
calories: totalCalories,
carbs: totalCarbs,
proteins: totalProteins,
fats: totalFats
};
}
<file_sep>/src/scenes/Settings/Settings.js
import React, { Component } from "react";
import styled from "styled-components";
import styles from "../../styles/constants";
import fadeIn from "../../styles/fadeIn";
import { action, decorate, observable } from "mobx";
import { inject, observer } from "mobx-react";
import Body from "../../components/Body";
import Error from "../../components/Error";
import Container from "../../components/Container";
import ActionButton from "../../components/ActionButton";
import Input from "../../components/Input";
import Select from "../../components/Select";
import SectionTitle from "../../components/SectionTitle";
import Section from "../../components/Section";
import Subsection from "../../components/Subsection";
import Separator from "../../components/Separator";
import Remove from "../../components/Remove";
class Settings extends Component {
constructor(props) {
super(props);
this.values = {
language: props.auth.user.language,
email: props.auth.user.email,
new_password: "",
repeated_password: "",
password: ""
};
this.invalid = {
language: false,
email: false,
new_password: false,
repeated_password: false,
password: <PASSWORD>
};
this.saved = false;
this.emailTaken = false;
document.title = props.t9n.t.navigation.settings;
}
render() {
const { t9n } = this.props;
return (
<Body>
<Subsection>
<Placeholder>
{this.saved && <Saved>{t9n.t.saved}</Saved>}
{this.emailTaken && <Error>{t9n.t.registration.emailUsed}</Error>}
</Placeholder>
</Subsection>
<Subsection>
<Section>
<SectionTitle>{t9n.t.settings.language}</SectionTitle>
<Container>
<Select
value={this.values.language}
onChange={this.change}
name="language"
placeholder={t9n.t.settings.language}
options={[
{ value: "ru", name: "Русский" },
{ value: "ee", name: "eesti" }
]}
/>
</Container>
</Section>
<Section>
<SectionTitle>{t9n.t.settings.email}</SectionTitle>
<Container>
<Input
value={this.values.email}
invalid={this.invalid.email}
onChange={this.change}
name="email"
placeholder={t9n.t.settings.email}
/>
</Container>
</Section>
<Section>
<SectionTitle>{t9n.t.settings.newPassword}</SectionTitle>
<Container>
<Input
value={this.values.new_password}
invalid={this.invalid.new_password}
onChange={this.change}
name="new_password"
placeholder={t9n.t.settings.newPassword}
type="password"
/>
<Separator />
<Input
value={this.values.repeated_password}
invalid={this.invalid.repeated_password}
onChange={this.change}
name="repeated_password"
placeholder={t9n.t.settings.repeatPassword}
type="password"
/>
</Container>
</Section>
<Section>
<SectionTitle>{t9n.t.settings.currentPassword}</SectionTitle>
<Container>
<Input
value={this.values.password}
invalid={this.invalid.password}
onChange={this.change}
name="password"
placeholder={t9n.t.settings.currentPassword}
type="password"
/>
</Container>
</Section>
</Subsection>
<Section>
<Container>
<ActionButton onClick={this.submit}>
{t9n.t.settings.save}
</ActionButton>
</Container>
</Section>
<Section>
<Remove
message={t9n.t.confirm.user}
remove={password => this.props.auth.user.remove(password)}
withPassword
>
{t9n.t.deleteAccount}
</Remove>
</Section>
</Body>
);
}
componentWillUnmount() {
const { user } = this.props.auth;
if (user) {
this.props.t9n.setLanguage(user.language);
}
}
change = event => {
const { name, value } = event.target;
this.values[name] = value;
this.setValid(name, true, false);
this.saved = false;
if (name === "language") {
this.props.t9n.setLanguage(value);
document.title = this.props.t9n.t.navigation.settings;
}
if (name === "email") {
this.emailTaken = false;
}
};
setValid = (names, valid, reset = true) => {
if (!(names instanceof Array)) {
names = [names];
}
if (reset) {
for (const key in this.invalid) {
this.invalid[key] = false;
}
}
for (let i = 0; i < names.length; ++i) {
this.invalid[names[i]] = !valid;
}
};
submit = event => {
const { user } = this.props.auth;
if (
this.values.language === user.language &&
this.values.email === user.email &&
this.values.new_password === "" &&
this.values.new_password === this.values.repeated_password
) {
return this.clear();
}
if (!this.values.password) {
return this.setValid("password", false);
}
if (
this.values.new_password &&
this.values.new_password !== this.values.repeated_password
) {
return this.setValid(["new_password", "repeated_password"], false);
}
user
.update(this.values)
.then(() => {
this.clear();
})
.catch(error => {
if (error.code === 400) {
return this.setValid("password", false);
}
if (error.code === 409) {
this.emailTaken = true;
return this.setValid("email", false);
}
if (error.code === 422) {
return this.setValid(error.details.invalid, false);
}
console.log(error);
});
};
clear = () => {
const { user } = this.props.auth;
this.values = {
language: user.language,
email: user.email,
new_password: "",
repeated_password: "",
password: ""
};
this.setValid([], true);
this.saved = true;
this.emailTaken = false;
setTimeout(() => {
this.saved = false;
}, 3000);
};
}
decorate(Settings, {
values: observable,
invalid: observable,
saved: observable,
emailTaken: observable,
change: action,
setValid: action,
submit: action,
clear: action
});
const Placeholder = styled.div`
width: 100%;
height: 3.5rem;
display: flex;
align-items: center;
justify-content: center;
`;
const Saved = styled.div`
color: ${styles.color.textAction};
text-align: center;
font-size: 1.2rem;
animation: ${fadeIn} 0.2s;
`;
export default inject("t9n", "auth")(observer(Settings));
<file_sep>/src/components/Meal/Meal.js
import React from "react";
import { observer } from "mobx-react";
import Section from "../Section";
import Container from "../Container";
import Header from "./components/Header";
import Labels from "./components/Labels";
import Food from "./components/Food";
import ExpandButton from "./components/ExpandButton";
function Meal({ meal, addFood, readOnly }) {
return (
<Section>
<Container>
<Header meal={meal} deletable={!readOnly} />
{!meal.empty && <Labels deletable={!readOnly} />}
<div>
{meal.foods.map(food => (
<Food food={food} key={food.id.toString()} deletable={!readOnly} />
))}
</div>
{!readOnly && <ExpandButton onClick={() => addFood(meal)} />}
</Container>
</Section>
);
}
export default observer(Meal);
<file_sep>/src/components/Meal/components/ThinColumn.js
import styled from "styled-components";
import FixedColumn from "./FixedColumn";
export default styled(FixedColumn)`
width: 2.5rem;
padding: 0;
padding-right: 1rem;
`;
<file_sep>/src/components/Meal/components/Header.js
import React from "react";
import styled, { css } from "styled-components";
import { observer } from "mobx-react";
import Flex from "../../Flex";
import Column from "./Column";
import FixedColumn from "./FixedColumn";
import ThinColumn from "./ThinColumn";
function Header({ meal, deletable }) {
if (meal.empty) {
return <HeaderColumn>{meal.name}</HeaderColumn>;
}
return (
<Flex>
<HeaderColumn>{meal.name}</HeaderColumn>
<HeaderFixedColumn>{meal.caloriesWithUnit}</HeaderFixedColumn>
<HeaderFixedColumn>{meal.carbsWithUnit}</HeaderFixedColumn>
<HeaderFixedColumn>{meal.proteinsWithUnit}</HeaderFixedColumn>
<HeaderFixedColumn>{meal.fatsWithUnit}</HeaderFixedColumn>
{deletable && <ThinColumn />}
</Flex>
);
}
const style = css`
font-size: 1.15rem;
font-weight: bold;
`;
const HeaderColumn = styled(Column)(style);
const HeaderFixedColumn = styled(FixedColumn)(style);
export default observer(Header);
<file_sep>/src/scenes/Home/Home.js
import React from "react";
import { inject, observer } from "mobx-react";
import { Redirect } from "react-router-dom";
const Home = ({ auth }) => {
if (auth.authenticated) {
return <Redirect to="/counter" />;
}
return <Redirect to="/login" />;
};
export default inject("auth")(observer(Home));
<file_sep>/src/components/RatioChanger/index.js
import RatioChager from "./RatioChanger";
export default RatioChager;
<file_sep>/src/components/MeasurementChart/MeasurementChart.js
import React from "react";
import { Line } from "react-chartjs-2";
import styles from "../../styles/constants";
import { inject, observer } from "mobx-react";
import * as ChartDataLabels from "chartjs-plugin-datalabels";
import ChartContainer from "../ChartContainer";
import Quantity from "../../models/Quantity";
function MeasurementChart({ t9n, quantity }) {
const values = quantity.measurements.map(({ date, value }) => ({
t: date,
y: value
}));
const data = {
datasets: [
{
label: `${quantity.prettyName} (${quantity.prettyUnit})`,
data: values,
pointBackgroundColor: styles.backgroundColor.primaryAction,
borderColor: styles.backgroundColor.primary,
backgroundColor: styles.backgroundColor.primaryLight
}
]
};
const options = {
layout: {
padding: {
top: 25,
}
},
legend: {
display: false
},
plugins: {
datalabels: {
align: "top",
formatter: value => {
return quantity.type === Quantity.ACTIVENESS
? t9n.t.activeness[Quantity.ACTIVENESS_NAMES[value.y]]
: value.y;
}
}
},
tooltips: {
enabled: true,
mode: "single",
callbacks: {
label: function(tooltipItems, data) {
return (
data.datasets[tooltipItems.datasetIndex].label +
": " +
(quantity.type === Quantity.ACTIVENESS
? t9n.t.activeness[Quantity.ACTIVENESS_NAMES[tooltipItems.yLabel]]
: tooltipItems.yLabel)
);
}
}
},
scales: {
xAxes: [
{
gridLines: {
display: false
},
offset: true,
type: "time",
time: {
unit: "day",
stepSize: 1,
displayFormats: {
day: "DD.MM.YYYY"
},
tooltipFormat: "DD.MM.YYYY"
},
ticks: {
maxRotation: 0,
minRotation: 0,
autoSkip: true,
maxTicksLimit: 7
}
}
],
yAxes: [
{
gridLines: {
display: false
},
ticks: {
autoSkip: true,
maxTicksLimit: 5,
callback: value =>
quantity.type === Quantity.ACTIVENESS
? t9n.t.activeness[Quantity.ACTIVENESS_NAMES[value]]
: value
}
}
]
}
};
return (
<ChartContainer>
<Line
height={100}
data={data}
options={options}
plugins={[ChartDataLabels]}
/>
</ChartContainer>
);
}
export default inject("t9n")(observer(MeasurementChart));
<file_sep>/src/components/ModalHeader/ModalHeader.js
import React from "react";
import styled from "styled-components";
import styles from "../../styles/constants";
import Section from "../Section";
export default function ModalHeader({ title, close }) {
return (
<Section>
<Div>
<Title>{title}</Title>
<Close onClick={close}>✖</Close>
</Div>
</Section>
);
}
const Div = styled.div`
display: flex;
width: 100%;
height: 3.5rem;
align-items: center;
justify-content: space-between;
`;
const Title = styled.div`
font-size: 1.5rem;
color: ${styles.color.text};
`;
const Close = styled.div`
color: ${styles.color.text};
font-size: 1.5rem;
user-select: none;
cursor: pointer;
transition: 0.2s;
&:hover {
color: red;
}
`;
<file_sep>/src/components/Modal/Modal.js
import React from "react";
import styled from "styled-components";
import Body from "../Body";
export default function Modal({ children }) {
return (
<Container onClick={event => event.stopPropagation()}>
<Body>{children}</Body>
</Container>
);
}
const Container = styled.div`
top: 0;
left: 0;
right: 0;
bottom: 0;
position: fixed;
z-index: 1000;
overflow: auto;
margin: 0;
padding: 0;
background-color: #f5f5f5;
`;
<file_sep>/src/scenes/Quantities/index.js
import Quantities from "./Quantities";
export default Quantities;
|
fcfb150cafe9ed33cfe1f1c4e0cbcea41e40318f
|
[
"JavaScript",
"TypeScript"
] | 71
|
JavaScript
|
h-mj/morkovka-web
|
f7668010d7b3658559d5ae2882a6c43f97001dea
|
73d109d268a10dee115d43eead6f561e2138bb5b
|
refs/heads/master
|
<repo_name>kayvank/dynamodb-streams<file_sep>/app.py
""" AWS lambda function for dynamodb streams
Archive dynamodb streams to kinesis -> s3
"""
import logging
from common import processor
log_format = (
"%(asctime)s::%(levelname)s::%(name)s::" "%(filename)s::%(lineno)d::%(message)s"
)
logging.basicConfig(level="INFO", format=log_format)
# Lazy-eval the dynamodb attribute (boto3 is dynamic!)
def main(event, ctx):
""" main entrace to the lambda function
"""
try:
f = processor()
f(event)
except Exception as error:
logging.error(f"Error. Exception <<{error}>> was thrown")
return "Error"
return f"records processed: {len(event)}"
<file_sep>/common.py
"""Dynamodb stream processor
Process dynamodb streams filtering for inserts and modify payloads
"""
import json
import math
import time
import boto3
try:
import unzip_requirements
except ImportError:
pass
from dynamodb_json import json_util as ddbjson
delivery_stream_name = "core-dynamodb-v1"
firehose_client = boto3.client("firehose", region_name="us-west-2")
def compose(f, g):
return lambda x: f(g(x))
def newImage(record, event_name):
"""Return paylods of interest
function does:
1- strips dynamodb `json-typed-tags`
2- return `NewImage`, a dynamdb term for the actual user-data
"""
record_data = record["dynamodb"]["NewImage"]
record_data.update({"timestamp": math.floor(time.time() * 1000)})
record_data.update({"dynamodbEvent": event_name})
return json.dumps(record_data)
def generate(event):
""" record generator
generator strips the dyamodb `type-tags`
"""
for record in event["Records"]:
yield ddbjson.loads(record)
def inserted(record):
""" process dynamo insert events
"""
return f"{newImage(record, 'INSERT')}\n"
def modified(record):
""" process dynamo modify events
"""
return f"{newImage(record, 'MODIFY')}\n"
def removed(record):
""" process dynamo remove events
"""
return f"{newImage(record, 'REMOVE')}\n"
def event_router(dynamo_event):
""" event router returns to the appropirate function
"""
routes = {"INSERT": inserted, "MODIFY": modified, "REMOVE": removed}
return routes[dynamo_event]
def as_kcl_record(payload):
""" string to kinesis record
"""
return {"Data": payload, "PartitionKey": str(hash(payload))}
def as_firehose_record(payload):
""" string to kinesis record
"""
return {"Data": payload.encode()}
def ddb_to_firehose(record):
"""process dynamodb stream record to kinesis record
"""
f = event_router(dynamo_event=record["eventName"])
process_function = compose(as_firehose_record, f)
return process_function(record)
def dispatcher(event):
""" dispatches the dynamodb events to the corresponding processor
"""
def batch_events(kcls):
for record in generate(event):
kcl_record = ddb_to_firehose(record)
kcls.append(kcl_record)
return kcls
return batch_events([])
def firehose_writer(records):
""" writes to aws firehose
"""
firehose_client.put_record_batch(
DeliveryStreamName=delivery_stream_name, Records=records
)
def processor():
"""Process a batch of dynamodb records
returns a function that transforms and writes dynamodb records to firehose
"""
f = compose(firehose_writer, dispatcher)
return f
<file_sep>/README.md
dynamodb-streams
---
dynamodb-streams is a python3 serverless project with CircleCi that persistes dynamodb changes of interest to AWS s3
## Intallation
* Dependencies
* Install Source
* Tests
* Enironment valiables
### Dependencies
- [serverless framework](https://www.serverless.com/)
- [python virtualenv](https://python-guide-pt-br.readthedocs.io/pt_BR/latest/dev/virtualenvs.html)
- [npm](https://www.npmjs.com/get-npm)
### Install Source
``` sh
npm install -g serverless
cd dynamodb-stream.git
virtualenv venv --python=python3
source venv/bin/activate
```
### Tests

``` sh
pip install pytest-watch
ptw
```
### Enironment variables
``` sh
export PYTHONPATH="~/dynamodb-streams-lambda/src"
export AWS_REGION='us-east-1'
export AWS_ACCEWSS_KEY_ID= 'my-aws-access-key'
export AWS_SECRET_ACCESS_KEY='my-secret-key'
```
### Local deployment
make sure your environmnet variables are set
``` sh
serverless deploy -s local -v
```
## References
- [serverless framework](https://www.serverless.com/)
- [aws fireohose](https://aws.amazon.com/kinesis/data-firehose/)
- [dynamodb streams](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Streams.html)
<file_sep>/test/test_stream_processor.py
"""unit test
"""
import unittest
import json
import logging
from dynamodb_json import json_util as ddbjson
import common as sp
import app as m
class TestStramProcessor(unittest.TestCase):
""" test class
"""
def setUp(self):
with open("./test/test-data.txt") as fp:
self.lines = fp.readlines()
def test_inserted(self):
"""insert spec:
given insert record
display transformed record to be archived
verify lastname
"""
dynamo_record = json.loads(self.lines[1])["Records"][0]
result = sp.inserted(ddbjson.loads(dynamo_record))
logging.info(result)
self.assertEqual(json.loads(result)["lastName"], "Ice")
def test_dispatcher(self):
"""dispatch spec:
given insert record
route to correct handerl
verify string is returned
"""
dynamo_record = json.loads(self.lines[1])
result = sp.dispatcher(dynamo_record)
logging.info(result)
self.assertTrue(len(result) == 1)
if __name__ == "__main__":
unittest.main()
<file_sep>/requirements.txt
boto3 #no-deploy
botocore #no-deploy
docutils==0.15.2
dynamodb-json==1.3
jmespath==0.10.0
python-dateutil
s3transfer #no-deploy
simplejson==3.17.0
six==1.15.0
urllib3==1.25.9
|
3a723e343145fcc5c6737262fe96641224bc1415
|
[
"Markdown",
"Python",
"Text"
] | 5
|
Python
|
kayvank/dynamodb-streams
|
2c2d3e2dec379e6160c57eda93d36a371e00a32b
|
9f6b0e91b30353352175bdb0fee4338cfb301170
|
refs/heads/master
|
<file_sep>function calcCircleArea(rad){
var area = Math.PI * rad * rad ;
return area;
}
document.write("Area of the circle with radiis 7 = " + calcCircleArea(7) + "<br><br>");
document.write("Area of the circle with radiis 1.5 = " +calcCircleArea(1.5) + "<br><br>");
document.write("Area of the circle with radiis 20 = " +calcCircleArea(20) + "<br><br>");
|
8d26b20fad6755896a55668f0a7e88f4deb5257e
|
[
"JavaScript"
] | 1
|
JavaScript
|
drishyams/S5-Assgn1
|
963c3c807a1d2b51962a95a077376346beb030c9
|
8fc4694cc4cd026ab6ff6854911a51ff311ab828
|
refs/heads/master
|
<file_sep>/*
serialCommander.h - Interactive commands over serial port.
Created by <NAME>, April 2016.
Released into the public domain.
*/
#ifndef SERIAL_COMMANDER
#define SERIAL_COMMANDER
#define SERIAL_COMMANDER_MAX_LENGTH 30
#include <Arduino.h>
class SerialCommander
{
private:
Stream * Serial;
char input[SERIAL_COMMANDER_MAX_LENGTH + 1];
public:
void setPort(Stream *SerialPort);
bool read(unsigned int timeout = 10000);
bool readTo(char *buffer, unsigned int size, unsigned int timeout = 10000);
bool available();
bool is(const char *command);
bool confirm(const __FlashStringHelper *question, unsigned int timeout = 10000);
};
#endif
<file_sep>
Serial Commander
-------------------------------
Provide an interactive command line through Serial port in your Arduino / Platformio project.
This library allows you to react to user activity on the serial port and guide the user while accepting commands or values.

**Behaviour**
When user activity is detected you can provide a welcome message and wait for a command.
A command is accepted when a new line is received (user press enter).
A timeout is in place to continue with code execution if the user does not answer.
The user input is ignored if is longer than expected or longer than the command buffer.
The received command can be compared to execute actions or can be used as input.
It allows the user to ESC or CTRL+C to cancel and allow the code to continue before timeout.
BACKSPACE is allowed to correct mistakes.
**Manual Installation**
[Download](https://github.com/cristianszwarc/SerialCommander/archive/master.zip) and decompress into your libraries folder.
**Platformio Installation**
By command line: `platformio lib install 288`
By platformio.ini:
```
...
lib_deps =
SerialCommander
...
```
**Initialize**
```C++
#include <SerialCommander.h> // Include library.
SerialCommander MyCommander; // Initialize an object to use.
void setup()
{
Serial.begin(9600); // Initialize a serial port.
while (!Serial) { ; }
MyCommander.setPort(&Serial); // Set the serial port to use.
}
```
**Detect user activity**
```C++
void loop()
{
...
if (MyCommander.available()) { // If we have serial activity.
presentOptions(); // Show some options to the user.
};
...
}
void presentOptions()
{
Serial.println(F("Serial Commander")); // A welcome msg (optional)
Serial.println(F("conquer / surrender?")); // Some help.
if (MyCommander.read()) { // Wait for user input.
// check if we have a match
if (MyCommander.is("conquer")) conquerFunction();
if (MyCommander.is("surrender")) surrenderFunction();
}
Serial.println(F("Bye")); // An end msg (optional)
}
```
**Request input from user**
```C++
void conquerFunction() {
char country[10]; // a buffer to store the input
Serial.println(F("What country?"));
if (MyCommander.readTo(country, sizeof(country))) {
if (MyCommander.confirm(F("Are you sure?"))) {
// move trops to *country
}
}
}
```
**Confirm Actions**
Confirm a command before execute an action.
Note: this expects a ```__FlashStringHelper``` .
```C++
...
if (MyCommander.is("surrender") && MyCommander.confirm(F("Are you sure?")) {
// do something
}
...
```
**Buffer Size**
By default SerialCommander is set to read up to 30 characters plus a terminator.
You can override this by changing the line:
```C++
...
#define SERIAL_COMMANDER_MAX_LENGTH 30
...
```
in `SerialCommander.h`
**Methods**
```void setPort(SerialPort);``` Set the serial port to use.
```bool available();``` Check if there are characters waiting on the serial port.
```bool read(timeout = 10000);``` Accept user input as a command for later use with ```.is("something")```
```bool is(command);``` Compare the last user input with a string.
```bool readTo(output, output_size, timeout = 10000);``` Accept user input into an array.
```bool confirm(question, timeout = 10000);``` Helper to require Y/n confirmations. **It expects the question as a FlashStringHelper!**.
**License**
MIT
<file_sep>name=SerialCommander
version=1.0.0
author=<NAME>
maintainer=<NAME> <<EMAIL>>
sentence=Arduino library to interactively receive commands over serial port.
paragraph=
category=Communication
url=https://github.com/cristianszwarc/SerialCommander.git
architectures=avr
<file_sep>/*
serialCommander.cpp - Interactive commands over serial port.
Created by <NAME>, April 2016.
Released into the public domain.
*/
#include "SerialCommander.h"
// attach a given serial port to be used accross our methods
void SerialCommander::setPort(Stream *SerialPort)
{
this->Serial = SerialPort;
}
// check activity on the serial port
bool SerialCommander::available()
{
if (this->Serial && this->Serial->available()) {
return true;
}
return false;
}
// accept a command from the user for later comparison at SerialCommander::is();
bool SerialCommander::read(unsigned int timeout)
{
return this->readTo(this->input, sizeof(this->input), timeout);
}
// check if the last received command matches with the given one
bool SerialCommander::is(const char *command)
{
if (strncmp(command, this->input, SERIAL_COMMANDER_MAX_LENGTH) == 0) {
return true;
}
return false;
}
// accept user's input into a given array.
// (checks for timeout and max size)
bool SerialCommander::readTo(char *buffer, unsigned int size, unsigned int timeout)
{
unsigned int count = 0;
unsigned long currentMillis = millis();
unsigned long previousMillis = currentMillis;
char inChar;
buffer[count] = '\0'; // clean the output buffer to avoid sequence issues
// if input detected on time
while( currentMillis - previousMillis < timeout )
{
// input available?
if (this->Serial->available()) {
inChar=this->Serial->read();
// append the character when is not newline, carrie return, backspace, etx
if (inChar != '\n' && inChar != '\r' && inChar != '\b' && inChar != 3 && inChar != 27) {
buffer[count] = inChar;
count++;
buffer[count] = '\0'; // terminator is now at the new end
} else if (inChar == '\b') {
count--; // step back (unsigned, will never go lower than 0)
buffer[count] = '\0'; // terminator is back again
} else if (inChar == 3 || inChar == 27) {
return false; // user cancelation CTRL + C or ESC
}
this->Serial->print(inChar); // user feedback
if (inChar == '\n') { // ends reading on newline
return true; // input correct, return!
}
if ( count >= size ) { // invalid if longer than allowed
return false;
}
}
currentMillis = millis(); // keep time tracking
}
// timeout
return false;
}
// Helper to confirm yes/no
bool SerialCommander::confirm(const __FlashStringHelper *question, unsigned int timeout)
{
this->Serial->print(question);
this->Serial->println(F(" Y/n"));
if (this->readTo(this->input, 2, timeout) && this->is("Y")) {
return true;
}
return false;
}
|
3df9c5e9cb3b7b8b684d053aa82a8e36fe395769
|
[
"Markdown",
"C++",
"INI"
] | 4
|
C++
|
cristianszwarc/SerialCommander
|
dd6cd96dbf1de215d4df74eda6f4cfaffad2ad74
|
16faa468fd52ce81c84cad63022fe790a96348af
|
refs/heads/main
|
<repo_name>ArtemTepes/TechForum<file_sep>/TechForum/Controllers/ItemController.cs
using Microsoft.Ajax.Utilities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TechForum.Models;
using TechForum.Models.Items;
namespace TechForum.Controllers
{
public class ItemController : Controller
{
// GET: Item
public ActionResult Index()
{
using (ItemContext db = new ItemContext())
{
var Topics = db.Topics;
return View(Topics.ToList());
}
}
[Authorize]
[HttpGet]
public ActionResult CreateTopic()
{
return View();
}
[HttpPost]
public ActionResult CreateTopic(Topic model)
{
if (!ModelState.IsValid)
{
return View(model);
}
using (ItemContext db = new ItemContext())
{
Topic topic = new Topic();
if (db.Topics.Where(x => x.Id != model.Id).Any(x => x.Title == model.Title))
{
ModelState.AddModelError("Title", "Topic with such title already exists");
return View(model);
}
if (model.Text.IsNullOrWhiteSpace())
{
ModelState.AddModelError("Text", "Please enter text");
return View(model);
}
if (model.Title.IsNullOrWhiteSpace())
{
ModelState.AddModelError("Title", "Please enter title");
return View(model);
}
else if (model.Title.Length < 3 || model.Title.Length > 20)
{
ModelState.AddModelError("Title", "Title length must be in range from 3 to 20");
return View(model);
}
topic.Title = model.Title;
topic.PostDate = DateTime.Now;
topic.Text = model.Text;
topic.UserName = User.Identity.Name;
topic.Posts = new List<Post>();
db.Topics.Add(topic);
db.SaveChanges();
}
TempData["SM"] = "You have added a new page";
return RedirectToAction("Index");
}
public ActionResult Delete(int id)
{
using (ItemContext db = new ItemContext())
{
var topic = db.Topics.Find(id);
db.Topics.Remove(topic);
db.SaveChanges();
}
TempData["SM"] = "You have deleted a new page successfully";
return RedirectToAction("Index");
}
public ActionResult Details(int id)
{
using (ItemContext db = new ItemContext())
{
var topic = db.Topics.Find(id);
return View(topic);
}
}
}
}<file_sep>/TechForum/Controllers/PostsController.cs
using Microsoft.Ajax.Utilities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TechForum.Models;
using TechForum.Models.Items;
namespace TechForum.Controllers
{
public class PostsController : Controller
{
public ActionResult Init(int id)
{
Session["TopicId"] = id;
return RedirectToAction("Index");
}
// GET: Topic
public ActionResult Index()
{
using (ItemContext db = new ItemContext())
{
var Posts = db.Topics.Find(Session["TopicId"]).Posts;
return View(Posts.ToList());
}
}
[Authorize]
[HttpGet]
public ActionResult CreatePost()
{
return View();
}
[HttpPost]
public ActionResult CreatePost(Post model)
{
if (!ModelState.IsValid)
{
return View(model);
}
using (ItemContext db = new ItemContext())
{
Post post = new Post();
var topic = db.Topics.Find(Session["TopicId"]);
var posts = topic.Posts;
if (posts.Any(x => x.Title == model.Title))
{
ModelState.AddModelError("", "Post with such title already exist");
return View(model);
}
if (model.Text.IsNullOrWhiteSpace())
{
ModelState.AddModelError("Text", "Please enter text");
return View(model);
}
if (model.Title.IsNullOrWhiteSpace())
{
ModelState.AddModelError("Title", "Please enter title");
return View(model);
}
else if (model.Title.Length < 3 || model.Title.Length > 20)
{
ModelState.AddModelError("Title", "Title length must be in range from 3 to 20");
return View(model);
}
post.Title = model.Title;
post.PostDate = DateTime.Now;
post.Text = model.Text;
post.UserName = User.Identity.Name;
post.Topic = topic;
posts.Add(post);
db.SaveChanges();
}
TempData["SM"] = "You have added a new post";
return RedirectToAction("Index");
}
[Authorize]
public ActionResult DeletePost(int id)
{
using (ItemContext db = new ItemContext())
{
var posts = db.Posts;
foreach (var i in posts.ToList())
{
if (i.PostId == id)
{
posts.Remove(i);
}
}
db.SaveChanges();
}
TempData["SM"] = "You have deleted a new page successfully";
return RedirectToAction("Index");
}
[Authorize]
[HttpGet]
public ActionResult EditPost(int id)
{
using (ItemContext db = new ItemContext())
{
Post post = db.Posts.Find(id);
if (post == null)
{
return Content("This page does not exist.");
}
return View(post);
}
}
[HttpPost]
public ActionResult EditPost(Post model)
{
if (!ModelState.IsValid)
{
return View(model);
}
using (ItemContext db = new ItemContext())
{
int id = model.PostId;
Post post = db.Posts.Find(id);
post.Title = model.Title;
if (db.Posts.Where(x => x.PostId != id).Any(x => x.Title == model.Title))
{
ModelState.AddModelError("", "This title already exists");
return View(model);
}
post.Text = model.Text;
db.SaveChanges();
}
TempData["SM"] = "Post was successfully edited";
return RedirectToAction("Index");
}
}
}<file_sep>/TechForum/Models/Items/Post.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace TechForum.Models.Items
{
public class Post
{
public int PostId { get; set; }
[Required]
[Display(Name = "Post Title")]
public string Title { get; set; }
[Required]
[Display(Name = "Post body")]
public string Text { get; set; }
[Display(Name = "Created")]
public DateTime? PostDate { get; set; }
[Display(Name = "Name of creator")]
public string UserName { get; set; }
public virtual Topic Topic { get; set; }
public int TopicId { get; set; }
}
}<file_sep>/TechForum/Models/Items/Topic.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace TechForum.Models.Items
{
public class Topic
{
[Key]
public int Id { get; set; }
[Display(Name = "Created")]
public DateTime? PostDate { get; set; }
[Display(Name = "Topic description")]
public string Text { get; set; }
[Display(Name = "Topic title")]
public string Title { get; set; }
[Display(Name = "Name of creator")]
public string UserName { get; set; }
public virtual ICollection<Post> Posts { get; set; }
public Topic()
{
Posts = new List<Post>();
}
}
}<file_sep>/TechForum/Models/DataContext.cs
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.UI;
using TechForum.Models.Items;
namespace TechForum.Models
{
public class UserContext : DbContext
{
public UserContext() : base("DefaultConnection") { }
public DbSet<User> Users { get; set; }
}
public class ItemContext : DbContext
{
public DbSet<Topic> Topics { get; set; }
public DbSet<Post> Posts { get; set; }
}
}<file_sep>/TechForum/Controllers/PostContentController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TechForum.Models;
namespace TechForum.Controllers
{
public class PostContentController : Controller
{
// GET: PostContent
public ActionResult Index(int id)
{
using(ItemContext db = new ItemContext())
{
var post = db.Posts.Find(id);
return View(post);
}
}
}
}
|
7460e42b64a049f7cbcfb5a54a148b2b2d0008d0
|
[
"C#"
] | 6
|
C#
|
ArtemTepes/TechForum
|
729d8922ca3f88e59b6a653a63e521476c786787
|
723a223d90487288c14d399d874d15ed304f22e3
|
refs/heads/master
|
<repo_name>netspencer/service<file_sep>/cmd/sidecar/metrics/main.go
package main
import (
"encoding/json"
"log"
"net/http"
_ "net/http/pprof"
"os"
"os/signal"
"syscall"
"time"
"github.com/ardanlabs/service/cmd/sidecar/metrics/collector"
"github.com/ardanlabs/service/cmd/sidecar/metrics/publisher"
"github.com/ardanlabs/service/cmd/sidecar/metrics/publisher/expvar"
"github.com/kelseyhightower/envconfig"
)
func main() {
// =========================================================================
// Logging
log := log.New(os.Stdout, "TRACER : ", log.LstdFlags|log.Lmicroseconds|log.Lshortfile)
defer log.Println("main : Completed")
// =========================================================================
// Configuration
var cfg struct {
Web struct {
DebugHost string `default:"0.0.0.0:4001" envconfig:"DEBUG_HOST"`
ReadTimeout time.Duration `default:"5s" envconfig:"READ_TIMEOUT"`
WriteTimeout time.Duration `default:"5s" envconfig:"WRITE_TIMEOUT"`
ShutdownTimeout time.Duration `default:"5s" envconfig:"SHUTDOWN_TIMEOUT"`
}
Expvar struct {
Host string `default:"0.0.0.0:3001" envconfig:"HOST"`
Route string `default:"/metrics" envconfig:"ROUTE"`
ReadTimeout time.Duration `default:"5s" envconfig:"READ_TIMEOUT"`
WriteTimeout time.Duration `default:"5s" envconfig:"WRITE_TIMEOUT"`
ShutdownTimeout time.Duration `default:"5s" envconfig:"SHUTDOWN_TIMEOUT"`
}
Collect struct {
From string `default:"http://sales-api:4000/debug/vars" envconfig:"FROM"`
}
Publish struct {
To string `default:"console" envconfig:"TO"`
Interval time.Duration `default:"5s" envconfig:"INTERVAL"`
}
}
if err := envconfig.Process("METRICS", &cfg); err != nil {
log.Fatalf("main : Parsing Config : %v", err)
}
cfgJSON, err := json.MarshalIndent(cfg, "", " ")
if err != nil {
log.Fatalf("main : Marshalling Config to JSON : %v", err)
}
log.Printf("config : %v\n", string(cfgJSON))
// =========================================================================
// Start Debug Service
// /debug/pprof - Added to the default mux by the net/http/pprof package.
debug := http.Server{
Addr: cfg.Web.DebugHost,
Handler: http.DefaultServeMux,
ReadTimeout: cfg.Web.ReadTimeout,
WriteTimeout: cfg.Web.WriteTimeout,
MaxHeaderBytes: 1 << 20,
}
// Not concerned with shutting this down when the
// application is being shutdown.
go func() {
log.Printf("main : Debug Listening %s", cfg.Web.DebugHost)
log.Printf("main : Debug Listener closed : %v", debug.ListenAndServe())
}()
// =========================================================================
// Start expvar Service
exp := expvar.New(log, cfg.Expvar.Host, cfg.Expvar.Route, cfg.Expvar.ReadTimeout, cfg.Expvar.WriteTimeout)
defer exp.Stop(cfg.Expvar.ShutdownTimeout)
// =========================================================================
// Start collectors and publishers
// Initalize to allow for the collection of metrics.
collector, err := collector.New(cfg.Collect.From)
if err != nil {
log.Fatalf("main : Starting collector : %v", err)
}
// Create a stdout publisher.
// TODO: Respect the cfg.publish.to config option.
stdout := publisher.NewStdout(log)
// Start the publisher to collect/publish metrics.
publish, err := publisher.New(log, collector, cfg.Publish.Interval, exp.Publish, stdout.Publish)
if err != nil {
log.Fatalf("main : Starting publisher : %v", err)
}
defer publish.Stop()
// =========================================================================
// Shutdown
// Make a channel to listen for an interrupt or terminate signal from the OS.
// Use a buffered channel because the signal package requires it.
shutdown := make(chan os.Signal, 1)
signal.Notify(shutdown, os.Interrupt, syscall.SIGTERM)
<-shutdown
log.Println("main : Start shutdown...")
}
<file_sep>/cmd/sales-api/handlers/product.go
package handlers
import (
"context"
"log"
"net/http"
"github.com/ardanlabs/service/internal/platform/db"
"github.com/ardanlabs/service/internal/platform/web"
"github.com/ardanlabs/service/internal/product"
"github.com/pkg/errors"
"go.opencensus.io/trace"
)
// Product represents the Product API method handler set.
type Product struct {
MasterDB *db.DB
// ADD OTHER STATE LIKE THE LOGGER AND CONFIG HERE.
}
// List returns all the existing products in the system.
func (p *Product) List(ctx context.Context, log *log.Logger, w http.ResponseWriter, r *http.Request, params map[string]string) error {
ctx, span := trace.StartSpan(ctx, "handlers.Product.List")
defer span.End()
dbConn := p.MasterDB.Copy()
defer dbConn.Close()
products, err := product.List(ctx, dbConn)
if err = translate(err); err != nil {
return errors.Wrap(err, "")
}
web.Respond(ctx, log, w, products, http.StatusOK)
return nil
}
// Retrieve returns the specified product from the system.
func (p *Product) Retrieve(ctx context.Context, log *log.Logger, w http.ResponseWriter, r *http.Request, params map[string]string) error {
ctx, span := trace.StartSpan(ctx, "handlers.Product.Retrieve")
defer span.End()
dbConn := p.MasterDB.Copy()
defer dbConn.Close()
prod, err := product.Retrieve(ctx, dbConn, params["id"])
if err = translate(err); err != nil {
return errors.Wrapf(err, "ID: %s", params["id"])
}
web.Respond(ctx, log, w, prod, http.StatusOK)
return nil
}
// Create inserts a new product into the system.
func (p *Product) Create(ctx context.Context, log *log.Logger, w http.ResponseWriter, r *http.Request, params map[string]string) error {
ctx, span := trace.StartSpan(ctx, "handlers.Product.Create")
defer span.End()
dbConn := p.MasterDB.Copy()
defer dbConn.Close()
v, ok := ctx.Value(web.KeyValues).(*web.Values)
if !ok {
return web.Shutdown("web value missing from context")
}
var np product.NewProduct
if err := web.Unmarshal(r.Body, &np); err != nil {
return errors.Wrap(err, "")
}
nUsr, err := product.Create(ctx, dbConn, &np, v.Now)
if err = translate(err); err != nil {
return errors.Wrapf(err, "Product: %+v", &np)
}
web.Respond(ctx, log, w, nUsr, http.StatusCreated)
return nil
}
// Update updates the specified product in the system.
func (p *Product) Update(ctx context.Context, log *log.Logger, w http.ResponseWriter, r *http.Request, params map[string]string) error {
ctx, span := trace.StartSpan(ctx, "handlers.Product.Update")
defer span.End()
dbConn := p.MasterDB.Copy()
defer dbConn.Close()
v, ok := ctx.Value(web.KeyValues).(*web.Values)
if !ok {
return web.Shutdown("web value missing from context")
}
var up product.UpdateProduct
if err := web.Unmarshal(r.Body, &up); err != nil {
return errors.Wrap(err, "")
}
err := product.Update(ctx, dbConn, params["id"], up, v.Now)
if err = translate(err); err != nil {
return errors.Wrapf(err, "ID: %s Update: %+v", params["id"], up)
}
web.Respond(ctx, log, w, nil, http.StatusNoContent)
return nil
}
// Delete removes the specified product from the system.
func (p *Product) Delete(ctx context.Context, log *log.Logger, w http.ResponseWriter, r *http.Request, params map[string]string) error {
ctx, span := trace.StartSpan(ctx, "handlers.Product.Delete")
defer span.End()
dbConn := p.MasterDB.Copy()
defer dbConn.Close()
err := product.Delete(ctx, dbConn, params["id"])
if err = translate(err); err != nil {
return errors.Wrapf(err, "Id: %s", params["id"])
}
web.Respond(ctx, log, w, nil, http.StatusNoContent)
return nil
}
<file_sep>/cmd/sales-api/tests/product_test.go
package tests
import (
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/ardanlabs/service/internal/platform/tests"
"github.com/ardanlabs/service/internal/platform/web"
"github.com/ardanlabs/service/internal/product"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
"gopkg.in/mgo.v2/bson"
)
// TestProducts is the entry point for the products
func TestProducts(t *testing.T) {
defer tests.Recover(t)
t.Run("getProducts200Empty", getProducts200Empty)
t.Run("postProduct400", postProduct400)
t.Run("postProduct401", postProduct401)
t.Run("getProduct404", getProduct404)
t.Run("getProduct400", getProduct400)
t.Run("deleteProduct404", deleteProduct404)
t.Run("putProduct404", putProduct404)
t.Run("crudProducts", crudProduct)
}
// getProducts200Empty validates an empty products list can be retrieved with the endpoint.
func getProducts200Empty(t *testing.T) {
r := httptest.NewRequest("GET", "/v1/products", nil)
w := httptest.NewRecorder()
r.Header.Set("Authorization", userAuthorization)
a.ServeHTTP(w, r)
t.Log("Given the need to fetch an empty list of products with the products endpoint.")
{
t.Log("\tTest 0:\tWhen fetching an empty product list.")
{
if w.Code != http.StatusOK {
t.Fatalf("\t%s\tShould receive a status code of 200 for the response : %v", tests.Failed, w.Code)
}
t.Logf("\t%s\tShould receive a status code of 200 for the response.", tests.Success)
recv := w.Body.String()
resp := `[]`
if resp != recv {
t.Log("Got :", recv)
t.Log("Want:", resp)
t.Fatalf("\t%s\tShould get the expected result.", tests.Failed)
}
t.Logf("\t%s\tShould get the expected result.", tests.Success)
}
}
}
// postProduct400 validates a product can't be created with the endpoint
// unless a valid product document is submitted.
func postProduct400(t *testing.T) {
np := map[string]string{
"notes": "missing fields",
}
body, err := json.Marshal(&np)
if err != nil {
t.Fatal(err)
}
r := httptest.NewRequest("POST", "/v1/products", bytes.NewBuffer(body))
w := httptest.NewRecorder()
r.Header.Set("Authorization", userAuthorization)
a.ServeHTTP(w, r)
t.Log("Given the need to validate a new product can't be created with an invalid document.")
{
t.Log("\tTest 0:\tWhen using an incomplete product value.")
{
if w.Code != http.StatusBadRequest {
t.Fatalf("\t%s\tShould receive a status code of 400 for the response : %v", tests.Failed, w.Code)
}
t.Logf("\t%s\tShould receive a status code of 400 for the response.", tests.Success)
// Inspect the response.
var got web.JSONError
if err := json.NewDecoder(w.Body).Decode(&got); err != nil {
t.Fatalf("\t%s\tShould be able to unmarshal the response to an error type : %v", tests.Failed, err)
}
t.Logf("\t%s\tShould be able to unmarshal the response to an error type.", tests.Success)
// Define what we want to see.
want := web.JSONError{
Error: "field validation failure",
Fields: web.InvalidError{
{Fld: "Name", Err: "required"},
{Fld: "Family", Err: "required"},
{Fld: "UnitPrice", Err: "required"},
{Fld: "Quantity", Err: "required"},
},
}
// We can't rely on the order of the field errors so they have to be
// sorted. Tell the cmp package how to sort them.
sorter := cmpopts.SortSlices(func(a, b web.Invalid) bool {
return a.Fld < b.Fld
})
if diff := cmp.Diff(want, got, sorter); diff != "" {
t.Fatalf("\t%s\tShould get the expected result. Diff:\n%s", tests.Failed, diff)
}
t.Logf("\t%s\tShould get the expected result.", tests.Success)
}
}
}
// postProduct401 validates a product can't be created with the endpoint
// unless the user is authenticated
func postProduct401(t *testing.T) {
np := product.NewProduct{
Name: "<NAME>",
Notes: "Various conditions.",
Family: "Kennedy",
UnitPrice: 25,
Quantity: 60,
}
body, err := json.Marshal(&np)
if err != nil {
t.Fatal(err)
}
r := httptest.NewRequest("POST", "/v1/products", bytes.NewBuffer(body))
w := httptest.NewRecorder()
// Not setting an authorization header
a.ServeHTTP(w, r)
t.Log("Given the need to validate a new product can't be created with an invalid document.")
{
t.Log("\tTest 0:\tWhen using an incomplete product value.")
{
if w.Code != http.StatusUnauthorized {
t.Fatalf("\t%s\tShould receive a status code of 401 for the response : %v", tests.Failed, w.Code)
}
t.Logf("\t%s\tShould receive a status code of 401 for the response.", tests.Success)
}
}
}
// getProduct400 validates a product request for a malformed id.
func getProduct400(t *testing.T) {
id := "12345"
r := httptest.NewRequest("GET", "/v1/products/"+id, nil)
w := httptest.NewRecorder()
r.Header.Set("Authorization", userAuthorization)
a.ServeHTTP(w, r)
t.Log("Given the need to validate getting a product with a malformed id.")
{
t.Logf("\tTest 0:\tWhen using the new product %s.", id)
{
if w.Code != http.StatusBadRequest {
t.Fatalf("\t%s\tShould receive a status code of 400 for the response : %v", tests.Failed, w.Code)
}
t.Logf("\t%s\tShould receive a status code of 400 for the response.", tests.Success)
recv := w.Body.String()
resp := `{
"error": "ID is not in its proper form"
}`
if resp != recv {
t.Log("Got :", recv)
t.Log("Want:", resp)
t.Fatalf("\t%s\tShould get the expected result.", tests.Failed)
}
t.Logf("\t%s\tShould get the expected result.", tests.Success)
}
}
}
// getProduct404 validates a product request for a product that does not exist with the endpoint.
func getProduct404(t *testing.T) {
id := bson.NewObjectId().Hex()
r := httptest.NewRequest("GET", "/v1/products/"+id, nil)
w := httptest.NewRecorder()
r.Header.Set("Authorization", userAuthorization)
a.ServeHTTP(w, r)
t.Log("Given the need to validate getting a product with an unknown id.")
{
t.Logf("\tTest 0:\tWhen using the new product %s.", id)
{
if w.Code != http.StatusNotFound {
t.Fatalf("\t%s\tShould receive a status code of 404 for the response : %v", tests.Failed, w.Code)
}
t.Logf("\t%s\tShould receive a status code of 404 for the response.", tests.Success)
recv := w.Body.String()
resp := "Entity not found"
if !strings.Contains(recv, resp) {
t.Log("Got :", recv)
t.Log("Want:", resp)
t.Fatalf("\t%s\tShould get the expected result.", tests.Failed)
}
t.Logf("\t%s\tShould get the expected result.", tests.Success)
}
}
}
// deleteProduct404 validates deleting a product that does not exist.
func deleteProduct404(t *testing.T) {
id := bson.NewObjectId().Hex()
r := httptest.NewRequest("DELETE", "/v1/products/"+id, nil)
w := httptest.NewRecorder()
r.Header.Set("Authorization", userAuthorization)
a.ServeHTTP(w, r)
t.Log("Given the need to validate deleting a product that does not exist.")
{
t.Logf("\tTest 0:\tWhen using the new product %s.", id)
{
if w.Code != http.StatusNotFound {
t.Fatalf("\t%s\tShould receive a status code of 404 for the response : %v", tests.Failed, w.Code)
}
t.Logf("\t%s\tShould receive a status code of 404 for the response.", tests.Success)
recv := w.Body.String()
resp := "Entity not found"
if !strings.Contains(recv, resp) {
t.Log("Got :", recv)
t.Log("Want:", resp)
t.Fatalf("\t%s\tShould get the expected result.", tests.Failed)
}
t.Logf("\t%s\tShould get the expected result.", tests.Success)
}
}
}
// putProduct404 validates updating a product that does not exist.
func putProduct404(t *testing.T) {
up := product.UpdateProduct{
Name: tests.StringPointer("Nonexistent"),
}
id := bson.NewObjectId().Hex()
body, err := json.Marshal(&up)
if err != nil {
t.Fatal(err)
}
r := httptest.NewRequest("PUT", "/v1/products/"+id, bytes.NewBuffer(body))
w := httptest.NewRecorder()
r.Header.Set("Authorization", userAuthorization)
a.ServeHTTP(w, r)
t.Log("Given the need to validate updating a product that does not exist.")
{
t.Logf("\tTest 0:\tWhen using the new product %s.", id)
{
if w.Code != http.StatusNotFound {
t.Fatalf("\t%s\tShould receive a status code of 404 for the response : %v", tests.Failed, w.Code)
}
t.Logf("\t%s\tShould receive a status code of 404 for the response.", tests.Success)
recv := w.Body.String()
resp := "Entity not found"
if !strings.Contains(recv, resp) {
t.Log("Got :", recv)
t.Log("Want:", resp)
t.Fatalf("\t%s\tShould get the expected result.", tests.Failed)
}
t.Logf("\t%s\tShould get the expected result.", tests.Success)
}
}
}
// crudProduct performs a complete test of CRUD against the api.
func crudProduct(t *testing.T) {
p := postProduct201(t)
defer deleteProduct204(t, p.ID.Hex())
getProduct200(t, p.ID.Hex())
putProduct204(t, p.ID.Hex())
}
// postProduct201 validates a product can be created with the endpoint.
func postProduct201(t *testing.T) product.Product {
np := product.NewProduct{
Name: "<NAME>",
Notes: "Various conditions.",
Family: "Kennedy",
UnitPrice: 25,
Quantity: 60,
}
body, err := json.Marshal(&np)
if err != nil {
t.Fatal(err)
}
r := httptest.NewRequest("POST", "/v1/products", bytes.NewBuffer(body))
w := httptest.NewRecorder()
r.Header.Set("Authorization", userAuthorization)
a.ServeHTTP(w, r)
// p is the value we will return.
var p product.Product
t.Log("Given the need to create a new product with the products endpoint.")
{
t.Log("\tTest 0:\tWhen using the declared product value.")
{
if w.Code != http.StatusCreated {
t.Fatalf("\t%s\tShould receive a status code of 201 for the response : %v", tests.Failed, w.Code)
}
t.Logf("\t%s\tShould receive a status code of 201 for the response.", tests.Success)
if err := json.NewDecoder(w.Body).Decode(&p); err != nil {
t.Fatalf("\t%s\tShould be able to unmarshal the response : %v", tests.Failed, err)
}
// Define what we wanted to receive. We will just trust the generated
// fields like ID and Dates so we copy p.
want := p
want.Name = "<NAME>"
want.Notes = "Various conditions."
want.Family = "Kennedy"
want.UnitPrice = 25
want.Quantity = 60
if diff := cmp.Diff(want, p); diff != "" {
t.Fatalf("\t%s\tShould get the expected result. Diff:\n%s", tests.Failed, diff)
}
t.Logf("\t%s\tShould get the expected result.", tests.Success)
}
}
return p
}
// deleteProduct200 validates deleting a product that does exist.
func deleteProduct204(t *testing.T, id string) {
r := httptest.NewRequest("DELETE", "/v1/products/"+id, nil)
w := httptest.NewRecorder()
r.Header.Set("Authorization", userAuthorization)
a.ServeHTTP(w, r)
t.Log("Given the need to validate deleting a product that does exist.")
{
t.Logf("\tTest 0:\tWhen using the new product %s.", id)
{
if w.Code != http.StatusNoContent {
t.Fatalf("\t%s\tShould receive a status code of 204 for the response : %v", tests.Failed, w.Code)
}
t.Logf("\t%s\tShould receive a status code of 204 for the response.", tests.Success)
}
}
}
// getProduct200 validates a product request for an existing id.
func getProduct200(t *testing.T, id string) {
r := httptest.NewRequest("GET", "/v1/products/"+id, nil)
w := httptest.NewRecorder()
r.Header.Set("Authorization", userAuthorization)
a.ServeHTTP(w, r)
t.Log("Given the need to validate getting a product that exists.")
{
t.Logf("\tTest 0:\tWhen using the new product %s.", id)
{
if w.Code != http.StatusOK {
t.Fatalf("\t%s\tShould receive a status code of 200 for the response : %v", tests.Failed, w.Code)
}
t.Logf("\t%s\tShould receive a status code of 200 for the response.", tests.Success)
var p product.Product
if err := json.NewDecoder(w.Body).Decode(&p); err != nil {
t.Fatalf("\t%s\tShould be able to unmarshal the response : %v", tests.Failed, err)
}
// Define what we wanted to receive. We will just trust the generated
// fields like Dates so we copy p.
want := p
want.ID = bson.ObjectIdHex(id)
want.Name = "<NAME>"
want.Notes = "Various conditions."
want.Family = "Kennedy"
want.UnitPrice = 25
want.Quantity = 60
if diff := cmp.Diff(want, p); diff != "" {
t.Fatalf("\t%s\tShould get the expected result. Diff:\n%s", tests.Failed, diff)
}
t.Logf("\t%s\tShould get the expected result.", tests.Success)
}
}
}
// putProduct204 validates updating a product that does exist.
func putProduct204(t *testing.T, id string) {
body := `{"name": "<NAME>", "unit_price": 100}`
r := httptest.NewRequest("PUT", "/v1/products/"+id, strings.NewReader(body))
w := httptest.NewRecorder()
r.Header.Set("Authorization", userAuthorization)
a.ServeHTTP(w, r)
t.Log("Given the need to update a product with the products endpoint.")
{
t.Log("\tTest 0:\tWhen using the modified product value.")
{
if w.Code != http.StatusNoContent {
t.Fatalf("\t%s\tShould receive a status code of 204 for the response : %v", tests.Failed, w.Code)
}
t.Logf("\t%s\tShould receive a status code of 204 for the response.", tests.Success)
r = httptest.NewRequest("GET", "/v1/products/"+id, nil)
w = httptest.NewRecorder()
r.Header.Set("Authorization", userAuthorization)
a.ServeHTTP(w, r)
if w.Code != http.StatusOK {
t.Fatalf("\t%s\tShould receive a status code of 200 for the retrieve : %v", tests.Failed, w.Code)
}
t.Logf("\t%s\tShould receive a status code of 200 for the retrieve.", tests.Success)
var ru product.Product
if err := json.NewDecoder(w.Body).Decode(&ru); err != nil {
t.Fatalf("\t%s\tShould be able to unmarshal the response : %v", tests.Failed, err)
}
if ru.Name != "Graphic Novels" {
t.Fatalf("\t%s\tShould see an updated Name : got %q want %q", tests.Failed, ru.Name, "Graphic Novels")
}
t.Logf("\t%s\tShould see an updated Name.", tests.Success)
if ru.Family != "Kennedy" {
t.Fatalf("\t%s\tShould not affect other fields like Family : got %q want %q", tests.Failed, ru.Family, "Kennedy")
}
t.Logf("\t%s\tShould not affect other fields like Family.", tests.Success)
}
}
}
<file_sep>/internal/product/product_test.go
package product_test
import (
"os"
"testing"
"time"
"github.com/ardanlabs/service/internal/platform/tests"
"github.com/ardanlabs/service/internal/product"
"github.com/google/go-cmp/cmp"
"github.com/pkg/errors"
)
var test *tests.Test
// TestMain is the entry point for testing.
func TestMain(m *testing.M) {
os.Exit(testMain(m))
}
func testMain(m *testing.M) int {
test = tests.New()
defer test.TearDown()
return m.Run()
}
// TestProduct validates the full set of CRUD operations on Product values.
func TestProduct(t *testing.T) {
defer tests.Recover(t)
t.Log("Given the need to work with Product records.")
{
t.Log("\tWhen handling a single Product.")
{
ctx := tests.Context()
dbConn := test.MasterDB.Copy()
defer dbConn.Close()
np := product.NewProduct{
Name: "<NAME>",
Notes: "Various conditions.",
Family: "Kennedy",
UnitPrice: 25,
Quantity: 60,
}
p, err := product.Create(ctx, dbConn, &np, time.Now().UTC())
if err != nil {
t.Fatalf("\t%s\tShould be able to create a product : %s.", tests.Failed, err)
}
t.Logf("\t%s\tShould be able to create a product.", tests.Success)
savedP, err := product.Retrieve(ctx, dbConn, p.ID.Hex())
if err != nil {
t.Fatalf("\t%s\tShould be able to retrieve product by ID: %s.", tests.Failed, err)
}
t.Logf("\t%s\tShould be able to retrieve product by ID.", tests.Success)
if diff := cmp.Diff(p, savedP); diff != "" {
t.Fatalf("\t%s\tShould get back the same product. Diff:\n%s", tests.Failed, diff)
}
t.Logf("\t%s\tShould get back the same product.", tests.Success)
upd := product.UpdateProduct{
Name: tests.StringPointer("Comics"),
Notes: tests.StringPointer(""),
Family: tests.StringPointer("walker"),
UnitPrice: tests.IntPointer(50),
Quantity: tests.IntPointer(40),
}
if err := product.Update(ctx, dbConn, p.ID.Hex(), upd, time.Now().UTC()); err != nil {
t.Fatalf("\t%s\tShould be able to update product : %s.", tests.Failed, err)
}
t.Logf("\t%s\tShould be able to update product.", tests.Success)
savedP, err = product.Retrieve(ctx, dbConn, p.ID.Hex())
if err != nil {
t.Fatalf("\t%s\tShould be able to retrieve updated product : %s.", tests.Failed, err)
}
t.Logf("\t%s\tShould be able to retrieve updated product.", tests.Success)
// Build a product matching what we expect to see. We just use the
// modified time from the database.
want := &product.Product{
ID: p.ID,
Name: *upd.Name,
Notes: *upd.Notes,
Family: *upd.Family,
UnitPrice: *upd.UnitPrice,
Quantity: *upd.Quantity,
DateCreated: p.DateCreated,
DateModified: savedP.DateModified,
}
if diff := cmp.Diff(want, savedP); diff != "" {
t.Fatalf("\t%s\tShould get back the same product. Diff:\n%s", tests.Failed, diff)
}
t.Logf("\t%s\tShould get back the same product.", tests.Success)
upd = product.UpdateProduct{
Name: tests.StringPointer("Graphic Novels"),
}
if err := product.Update(ctx, dbConn, p.ID.Hex(), upd, time.Now().UTC()); err != nil {
t.Fatalf("\t%s\tShould be able to update just some fields of product : %s.", tests.Failed, err)
}
t.Logf("\t%s\tShould be able to update just some fields of product.", tests.Success)
savedP, err = product.Retrieve(ctx, dbConn, p.ID.Hex())
if err != nil {
t.Fatalf("\t%s\tShould be able to retrieve updated product : %s.", tests.Failed, err)
}
t.Logf("\t%s\tShould be able to retrieve updated product.", tests.Success)
if savedP.Name != *upd.Name {
t.Fatalf("\t%s\tShould be able to see updated Name field : got %q want %q.", tests.Failed, savedP.Name, *upd.Name)
} else {
t.Logf("\t%s\tShould be able to see updated Name field.", tests.Success)
}
if savedP.Family != "walker" {
t.Fatalf("\t%s\tShould not see updates in other fields : Family was %q want %q.", tests.Failed, savedP.Family, "walker")
} else {
t.Logf("\t%s\tShould not see updates in other fields.", tests.Success)
}
if err := product.Delete(ctx, dbConn, p.ID.Hex()); err != nil {
t.Fatalf("\t%s\tShould be able to delete product : %s.", tests.Failed, err)
}
t.Logf("\t%s\tShould be able to delete product.", tests.Success)
savedP, err = product.Retrieve(ctx, dbConn, p.ID.Hex())
if errors.Cause(err) != product.ErrNotFound {
t.Fatalf("\t%s\tShould NOT be able to retrieve deleted product : %s.", tests.Failed, err)
}
t.Logf("\t%s\tShould NOT be able to retrieve deleted product.", tests.Success)
}
}
}
<file_sep>/internal/user/user.go
package user
import (
"context"
"fmt"
"time"
"github.com/ardanlabs/service/internal/platform/auth"
"github.com/ardanlabs/service/internal/platform/db"
"github.com/pkg/errors"
"go.opencensus.io/trace"
"golang.org/x/crypto/bcrypt"
mgo "gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)
const usersCollection = "users"
var (
// ErrNotFound abstracts the mgo not found error.
ErrNotFound = errors.New("Entity not found")
// ErrInvalidID occurs when an ID is not in a valid form.
ErrInvalidID = errors.New("ID is not in its proper form")
// ErrAuthenticationFailure occurs when a user attempts to authenticate but
// anything goes wrong.
ErrAuthenticationFailure = errors.New("Authentication failed")
// ErrForbidden occurs when a user tries to do something that is forbidden to them according to our access control policies.
ErrForbidden = errors.New("Attempted action is not allowed")
)
// List retrieves a list of existing users from the database.
func List(ctx context.Context, dbConn *db.DB) ([]User, error) {
ctx, span := trace.StartSpan(ctx, "internal.user.List")
defer span.End()
u := []User{}
f := func(collection *mgo.Collection) error {
return collection.Find(nil).All(&u)
}
if err := dbConn.Execute(ctx, usersCollection, f); err != nil {
return nil, errors.Wrap(err, "db.users.find()")
}
return u, nil
}
// Retrieve gets the specified user from the database.
func Retrieve(ctx context.Context, claims auth.Claims, dbConn *db.DB, id string) (*User, error) {
ctx, span := trace.StartSpan(ctx, "internal.user.Retrieve")
defer span.End()
if !bson.IsObjectIdHex(id) {
return nil, ErrInvalidID
}
// If you are not an admin and looking to retrieve someone else then you are rejected.
if !claims.HasRole(auth.RoleAdmin) && claims.Subject != id {
return nil, ErrForbidden
}
q := bson.M{"_id": bson.ObjectIdHex(id)}
var u *User
f := func(collection *mgo.Collection) error {
return collection.Find(q).One(&u)
}
if err := dbConn.Execute(ctx, usersCollection, f); err != nil {
if err == mgo.ErrNotFound {
return nil, ErrNotFound
}
return nil, errors.Wrap(err, fmt.Sprintf("db.users.find(%s)", db.Query(q)))
}
return u, nil
}
// Create inserts a new user into the database.
func Create(ctx context.Context, dbConn *db.DB, nu *NewUser, now time.Time) (*User, error) {
ctx, span := trace.StartSpan(ctx, "internal.user.Create")
defer span.End()
// Mongo truncates times to milliseconds when storing. We and do the same
// here so the value we return is consistent with what we store.
now = now.Truncate(time.Millisecond)
pw, err := bcrypt.GenerateFromPassword([]byte(nu.Password), bcrypt.DefaultCost)
if err != nil {
return nil, errors.Wrap(err, "generating password hash")
}
u := User{
ID: bson.NewObjectId(),
Name: nu.Name,
Email: nu.Email,
PasswordHash: pw,
Roles: nu.Roles,
DateCreated: now,
DateModified: now,
}
f := func(collection *mgo.Collection) error {
return collection.Insert(&u)
}
if err := dbConn.Execute(ctx, usersCollection, f); err != nil {
return nil, errors.Wrap(err, fmt.Sprintf("db.users.insert(%s)", db.Query(&u)))
}
return &u, nil
}
// Update replaces a user document in the database.
func Update(ctx context.Context, dbConn *db.DB, id string, upd *UpdateUser, now time.Time) error {
ctx, span := trace.StartSpan(ctx, "internal.user.Update")
defer span.End()
if !bson.IsObjectIdHex(id) {
return ErrInvalidID
}
fields := make(bson.M)
if upd.Name != nil {
fields["name"] = *upd.Name
}
if upd.Email != nil {
fields["email"] = *upd.Email
}
if upd.Roles != nil {
fields["roles"] = upd.Roles
}
if upd.Password != nil {
pw, err := bcrypt.GenerateFromPassword([]byte(*upd.Password), bcrypt.DefaultCost)
if err != nil {
return errors.Wrap(err, "generating password hash")
}
fields["password_hash"] = pw
}
// If there's nothing to update we can quit early.
if len(fields) == 0 {
return nil
}
fields["date_modified"] = now
m := bson.M{"$set": fields}
q := bson.M{"_id": bson.ObjectIdHex(id)}
f := func(collection *mgo.Collection) error {
return collection.Update(q, m)
}
if err := dbConn.Execute(ctx, usersCollection, f); err != nil {
if err == mgo.ErrNotFound {
return ErrNotFound
}
return errors.Wrap(err, fmt.Sprintf("db.customers.update(%s, %s)", db.Query(q), db.Query(m)))
}
return nil
}
// Delete removes a user from the database.
func Delete(ctx context.Context, dbConn *db.DB, id string) error {
ctx, span := trace.StartSpan(ctx, "internal.user.Update")
defer span.End()
if !bson.IsObjectIdHex(id) {
return ErrInvalidID
}
q := bson.M{"_id": bson.ObjectIdHex(id)}
f := func(collection *mgo.Collection) error {
return collection.Remove(q)
}
if err := dbConn.Execute(ctx, usersCollection, f); err != nil {
if err == mgo.ErrNotFound {
return ErrNotFound
}
return errors.Wrap(err, fmt.Sprintf("db.users.remove(%s)", db.Query(q)))
}
return nil
}
// TokenGenerator is the behavior we need in our Authenticate to generate
// tokens for authenticated users.
type TokenGenerator interface {
GenerateToken(auth.Claims) (string, error)
}
// Authenticate finds a user by their email and verifies their password. On
// success it returns a Token that can be used to authenticate in the future.
//
// The key, keyID, and alg are required for generating the token.
func Authenticate(ctx context.Context, dbConn *db.DB, tknGen TokenGenerator, now time.Time, email, password string) (Token, error) {
ctx, span := trace.StartSpan(ctx, "internal.user.Authenticate")
defer span.End()
q := bson.M{"email": email}
var u *User
f := func(collection *mgo.Collection) error {
return collection.Find(q).One(&u)
}
if err := dbConn.Execute(ctx, usersCollection, f); err != nil {
// Normally we would return ErrNotFound in this scenario but we do not want
// to leak to an unauthenticated user which emails are in the system.
if err == mgo.ErrNotFound {
return Token{}, ErrAuthenticationFailure
}
return Token{}, errors.Wrap(err, fmt.Sprintf("db.users.find(%s)", db.Query(q)))
}
// Compare the provided password with the saved hash. Use the bcrypt
// comparison function so it is cryptographically secure.
if err := bcrypt.CompareHashAndPassword(u.PasswordHash, []byte(password)); err != nil {
return Token{}, ErrAuthenticationFailure
}
// If we are this far the request is valid. Create some claims for the user
// and generate their token.
claims := auth.NewClaims(u.ID.Hex(), u.Roles, now, time.Hour)
tkn, err := tknGen.GenerateToken(claims)
if err != nil {
return Token{}, errors.Wrap(err, "generating token")
}
return Token{Token: tkn}, nil
}
<file_sep>/cmd/sales-api/handlers/check.go
package handlers
import (
"context"
"log"
"net/http"
"github.com/ardanlabs/service/internal/platform/db"
"github.com/ardanlabs/service/internal/platform/web"
"go.opencensus.io/trace"
)
// Check provides support for orchestration health checks.
type Check struct {
MasterDB *db.DB
}
// Health validates the service is healthy and ready to accept requests.
func (c *Check) Health(ctx context.Context, log *log.Logger, w http.ResponseWriter, r *http.Request, params map[string]string) error {
ctx, span := trace.StartSpan(ctx, "handlers.Check.Health")
defer span.End()
dbConn := c.MasterDB.Copy()
defer dbConn.Close()
if err := dbConn.StatusCheck(ctx); err != nil {
return err
}
status := struct {
Status string `json:"status"`
}{
Status: "ok",
}
web.Respond(ctx, log, w, status, http.StatusOK)
return nil
}
<file_sep>/internal/mid/metrics.go
package mid
import (
"context"
"expvar"
"log"
"net/http"
"runtime"
"github.com/ardanlabs/service/internal/platform/web"
"go.opencensus.io/trace"
)
// m contains the global program counters for the application.
var m = struct {
gr *expvar.Int
req *expvar.Int
err *expvar.Int
}{
gr: expvar.NewInt("goroutines"),
req: expvar.NewInt("requests"),
err: expvar.NewInt("errors"),
}
// Metrics updates program counters.
func Metrics(before web.Handler) web.Handler {
// Wrap this handler around the next one provided.
h := func(ctx context.Context, log *log.Logger, w http.ResponseWriter, r *http.Request, params map[string]string) error {
ctx, span := trace.StartSpan(ctx, "internal.mid.Metrics")
defer span.End()
// If the context is missing this value, request the service
// to be shutdown gracefully.
v, ok := ctx.Value(web.KeyValues).(*web.Values)
if !ok {
return web.Shutdown("web value missing from context")
}
err := before(ctx, log, w, r, params)
// Add one to the request counter.
m.req.Add(1)
// Include the current count for the number of goroutines.
if m.req.Value()%100 == 0 {
m.gr.Set(int64(runtime.NumGoroutine()))
}
// Add one to the errors counter if an error occured
// on this reuqest.
if v.Error {
m.err.Add(1)
}
return err
}
return h
}
<file_sep>/cmd/sidecar/tracer/handlers/routes.go
package handlers
import (
"log"
"net/http"
"os"
"time"
"github.com/ardanlabs/service/internal/mid"
"github.com/ardanlabs/service/internal/platform/web"
)
// API returns a handler for a set of routes.
func API(shutdown chan os.Signal, log *log.Logger, zipkinHost string, apiHost string) http.Handler {
app := web.New(shutdown, log, mid.RequestLogger, mid.ErrorHandler)
z := NewZipkin(zipkinHost, apiHost, time.Second)
app.Handle("POST", "/v1/publish", z.Publish)
h := Health{}
app.Handle("GET", "/v1/health", h.Check)
return app
}
<file_sep>/internal/mid/auth.go
package mid
import (
"context"
"log"
"net/http"
"strings"
"github.com/ardanlabs/service/internal/platform/auth"
"github.com/ardanlabs/service/internal/platform/web"
"github.com/pkg/errors"
"go.opencensus.io/trace"
)
// Auth is used to authenticate and authorize HTTP requests.
type Auth struct {
Authenticator *auth.Authenticator
}
// Authenticate validates a JWT from the `Authorization` header.
func (a *Auth) Authenticate(after web.Handler) web.Handler {
// Wrap this handler around the next one provided.
h := func(ctx context.Context, log *log.Logger, w http.ResponseWriter, r *http.Request, params map[string]string) error {
ctx, span := trace.StartSpan(ctx, "internal.mid.RequestLogger")
defer span.End()
authHdr := r.Header.Get("Authorization")
if authHdr == "" {
return errors.Wrap(web.ErrUnauthorized, "Missing Authorization header")
}
tknStr, err := parseAuthHeader(authHdr)
if err != nil {
return errors.Wrap(web.ErrUnauthorized, err.Error())
}
claims, err := a.Authenticator.ParseClaims(tknStr)
if err != nil {
return errors.Wrap(web.ErrUnauthorized, err.Error())
}
// Add claims to the context so they can be retrieved later.
ctx = context.WithValue(ctx, auth.Key, claims)
return after(ctx, log, w, r, params)
}
return h
}
// parseAuthHeader parses an authorization header. Expected header is of
// the format `Bearer <token>`.
func parseAuthHeader(bearerStr string) (string, error) {
split := strings.Split(bearerStr, " ")
if len(split) != 2 || strings.ToLower(split[0]) != "bearer" {
return "", errors.New("Expected Authorization header format: Bearer <token>")
}
return split[1], nil
}
// HasRole validates that an authenticated user has at least one role from a
// specified list. This method constructs the actual function that is used.
func (a *Auth) HasRole(roles ...string) func(next web.Handler) web.Handler {
mw := func(next web.Handler) web.Handler {
h := func(ctx context.Context, log *log.Logger, w http.ResponseWriter, r *http.Request, params map[string]string) error {
claims, ok := ctx.Value(auth.Key).(auth.Claims)
if !ok {
return web.ErrUnauthorized
}
if !claims.HasRole(roles...) {
return web.ErrForbidden
}
return next(ctx, log, w, r, params)
}
return h
}
return mw
}
<file_sep>/makefile
SHELL := /bin/bash
all: keys sales-api metrics tracer
keys:
go run ./cmd/sales-admin/main.go --cmd keygen
admin:
go run ./cmd/sales-admin/main.go --cmd useradd --user_email <EMAIL> --user_password <PASSWORD>
sales-api:
docker build \
-t sales-api-amd64:1.0 \
--build-arg PACKAGE_NAME=sales-api \
--build-arg VCS_REF=`git rev-parse HEAD` \
--build-arg BUILD_DATE=`date -u +”%Y-%m-%dT%H:%M:%SZ”` \
.
docker system prune -f
metrics:
docker build \
-t metrics-amd64:1.0 \
--build-arg PACKAGE_NAME=metrics \
--build-arg PACKAGE_PREFIX=sidecar/ \
--build-arg VCS_REF=`git rev-parse HEAD` \
--build-arg BUILD_DATE=`date -u +”%Y-%m-%dT%H:%M:%SZ”` \
.
docker system prune -f
tracer:
cd "$$GOPATH/src/github.com/ardanlabs/service"
docker build \
-t tracer-amd64:1.0 \
--build-arg PACKAGE_NAME=tracer \
--build-arg PACKAGE_PREFIX=sidecar/ \
--build-arg VCS_REF=`git rev-parse HEAD` \
--build-arg BUILD_DATE=`date -u +”%Y-%m-%dT%H:%M:%SZ”` \
.
docker system prune -f
up:
docker-compose up
down:
docker-compose down
test:
cd "$$GOPATH/src/github.com/ardanlabs/service"
go test ./...
clean:
docker system prune -f
stop-all:
docker stop $(docker ps -aq)
remove-all:
docker rm $(docker ps -aq)
<file_sep>/internal/platform/docker/docker.go
package docker
import (
"bytes"
"encoding/json"
"fmt"
"log"
"os/exec"
)
// Container contains the information about the conainer.
type Container struct {
ID string
Port string
}
// StartMongo runs a mongo container to execute commands.
func StartMongo(log *log.Logger) (*Container, error) {
cmd := exec.Command("docker", "run", "-P", "-d", "mongo:3-jessie")
var out bytes.Buffer
cmd.Stdout = &out
if err := cmd.Run(); err != nil {
return nil, fmt.Errorf("starting container: %v", err)
}
id := out.String()[:12]
log.Println("DB ContainerID:", id)
cmd = exec.Command("docker", "inspect", id)
out.Reset()
cmd.Stdout = &out
if err := cmd.Run(); err != nil {
return nil, fmt.Errorf("inspect container: %v", err)
}
var doc []struct {
NetworkSettings struct {
Ports struct {
TCP27017 []struct {
HostPort string `json:"HostPort"`
} `json:"27017/tcp"`
} `json:"Ports"`
} `json:"NetworkSettings"`
}
if err := json.Unmarshal(out.Bytes(), &doc); err != nil {
return nil, fmt.Errorf("decoding json: %v", err)
}
c := Container{
ID: id,
Port: doc[0].NetworkSettings.Ports.TCP27017[0].HostPort,
}
log.Println("DB Port:", c.Port)
return &c, nil
}
// StopMongo stops and removes the specified container.
func StopMongo(log *log.Logger, c *Container) error {
if err := exec.Command("docker", "stop", c.ID).Run(); err != nil {
return err
}
log.Println("Stopped:", c.ID)
if err := exec.Command("docker", "rm", c.ID, "-v").Run(); err != nil {
return err
}
log.Println("Removed:", c.ID)
return nil
}
<file_sep>/internal/user/models.go
package user
import (
"time"
"gopkg.in/mgo.v2/bson"
)
// User represents someone with access to our system.
type User struct {
ID bson.ObjectId `bson:"_id" json:"id"`
Name string `bson:"name" json:"name"`
Email string `bson:"email" json:"email"` // TODO(jlw) enforce uniqueness
Roles []string `bson:"roles" json:"roles"`
PasswordHash []byte `bson:"password_hash" json:"-"`
DateModified time.Time `bson:"date_modified" json:"date_modified"`
DateCreated time.Time `bson:"date_created,omitempty" json:"date_created"`
}
// NewUser contains information needed to create a new User.
type NewUser struct {
Name string `json:"name" validate:"required"`
Email string `json:"email" validate:"required"` // TODO(jlw) enforce uniqueness.
Roles []string `json:"roles" validate:"required"` // TODO(jlw) Ensure only includes valid roles.
Password string `json:"password" validate:"required"`
PasswordConfirm string `json:"password_confirm" validate:"eqfield=Password"`
}
// UpdateUser defines what information may be provided to modify an existing
// User. All fields are optional so clients can send just the fields they want
// changed. It uses pointer fields so we can differentiate between a field that
// was not provided and a field that was provided as explicitly blank. Normally
// we do not want to use pointers to basic types but we make exceptions around
// marshalling/unmarshalling.
type UpdateUser struct {
Name *string `json:"name"`
Email *string `json:"email"` // TODO(jlw) enforce uniqueness.
Roles []string `json:"roles"` // TODO(jlw) Ensure only includes valid roles.
Password *string `json:"password"`
PasswordConfirm *string `json:"password_confirm" validate:"omitempty,eqfield=Password"`
}
// Token is the payload we deliver to users when they authenticate.
type Token struct {
Token string `json:"token"`
}
<file_sep>/cmd/sidecar/tracer/main.go
package main
import (
"context"
"encoding/json"
"log"
"net/http"
_ "net/http/pprof"
"os"
"os/signal"
"syscall"
"time"
"github.com/ardanlabs/service/cmd/sidecar/tracer/handlers"
"github.com/kelseyhightower/envconfig"
)
func main() {
// =========================================================================
// Logging
log := log.New(os.Stdout, "TRACER : ", log.LstdFlags|log.Lmicroseconds|log.Lshortfile)
defer log.Println("main : Completed")
// =========================================================================
// Configuration
var cfg struct {
Web struct {
APIHost string `default:"0.0.0.0:3002" envconfig:"API_HOST"`
DebugHost string `default:"0.0.0.0:4002" envconfig:"DEBUG_HOST"`
ReadTimeout time.Duration `default:"5s" envconfig:"READ_TIMEOUT"`
WriteTimeout time.Duration `default:"5s" envconfig:"WRITE_TIMEOUT"`
ShutdownTimeout time.Duration `default:"5s" envconfig:"SHUTDOWN_TIMEOUT"`
}
Zipkin struct {
Host string `default:"http://zipkin:9411/api/v2/spans" envconfig:"HOST"`
}
}
if err := envconfig.Process("TRACER", &cfg); err != nil {
log.Fatalf("main : Parsing Config : %v", err)
}
cfgJSON, err := json.MarshalIndent(cfg, "", " ")
if err != nil {
log.Fatalf("main : Marshalling Config to JSON : %v", err)
}
log.Printf("config : %v\n", string(cfgJSON))
// =========================================================================
// Start Debug Service
// /debug/pprof - Added to the default mux by the net/http/pprof package.
debug := http.Server{
Addr: cfg.Web.DebugHost,
Handler: http.DefaultServeMux,
ReadTimeout: cfg.Web.ReadTimeout,
WriteTimeout: cfg.Web.WriteTimeout,
MaxHeaderBytes: 1 << 20,
}
// Not concerned with shutting this down when the
// application is being shutdown.
go func() {
log.Printf("main : Debug Listening %s", cfg.Web.DebugHost)
log.Printf("main : Debug Listener closed : %v", debug.ListenAndServe())
}()
// =========================================================================
// Start API Service
// Make a channel to listen for an interrupt or terminate signal from the OS.
// Use a buffered channel because the signal package requires it.
shutdown := make(chan os.Signal, 1)
signal.Notify(shutdown, os.Interrupt, syscall.SIGTERM)
api := http.Server{
Addr: cfg.Web.APIHost,
Handler: handlers.API(shutdown, log, cfg.Zipkin.Host, cfg.Web.APIHost),
ReadTimeout: cfg.Web.ReadTimeout,
WriteTimeout: cfg.Web.WriteTimeout,
MaxHeaderBytes: 1 << 20,
}
// Make a channel to listen for errors coming from the listener. Use a
// buffered channel so the goroutine can exit if we don't collect this error.
serverErrors := make(chan error, 1)
// Start the service listening for requests.
go func() {
log.Printf("main : API Listening %s", cfg.Web.APIHost)
serverErrors <- api.ListenAndServe()
}()
// =========================================================================
// Shutdown
// Blocking main and waiting for shutdown.
select {
case err := <-serverErrors:
log.Fatalf("main : Error starting server: %v", err)
case sig := <-shutdown:
log.Printf("main : %v : Start shutdown..", sig)
// Create context for Shutdown call.
ctx, cancel := context.WithTimeout(context.Background(), cfg.Web.ShutdownTimeout)
defer cancel()
// Asking listener to shutdown and load shed.
err := api.Shutdown(ctx)
if err != nil {
log.Printf("main : Graceful shutdown did not complete in %v : %v", cfg.Web.ShutdownTimeout, err)
err = api.Close()
}
// Log the status of this shutdown.
switch {
case sig == syscall.SIGSTOP:
log.Fatal("main : Integrity issue caused shutdown")
case err != nil:
log.Fatalf("main : Could not stop server gracefully : %v", err)
}
}
}
<file_sep>/cmd/sales-api/handlers/errors.go
package handlers
import (
"github.com/ardanlabs/service/internal/platform/web"
"github.com/ardanlabs/service/internal/product"
"github.com/ardanlabs/service/internal/user"
"github.com/pkg/errors"
)
// translate looks for certain error types and transforms
// them into web errors. We are losing the trace when this
// error is converted. But we don't log traces for these.
func translate(err error) error {
switch errors.Cause(err) {
case user.ErrNotFound, product.ErrNotFound:
return web.ErrNotFound
case user.ErrInvalidID, product.ErrInvalidID:
return web.ErrInvalidID
case user.ErrAuthenticationFailure:
return web.ErrUnauthorized
case user.ErrForbidden:
return web.ErrForbidden
}
return err
}
<file_sep>/README.md
# Ultimate Service
Copyright 2018, <NAME>
<EMAIL>
## Licensing
```
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
```
## Description
Service is a project that provides a starter-kit for a REST based web service. It provides best practices around Go web services using POD architecture and design. It contains the following features:
* Minimal application web framework.
* Middleware integration.
* Database support using MongoDB.
* CRUD based pattern.
* Distributed logging and tracing.
* Testing patterns.
* User authentication.
* POD architecture with sidecars for metrics and tracing.
* Use of Docker, Docker Compose, and Makefiles.
* Vendoring dependencies with Modules, requires Go 1.11 or higher.
## Local Installation
This project contains three services and uses 3rd party services such as MongoDB and Zipkin. Docker is required to run this software on your local machine.
### Getting the project
You can use the traditional `go get` command to download this project into your configured GOPATH.
```
$ go get -u github.com/ardanlabs/service
```
### Go Modules
This project is using Go Module support for vendoring dependencies. We are using the `tidy` and `vendor` commands to maintain the dependencies and make sure the project can create reproducible builds. This project assumes the source code will be inside your GOPATH within the traditional location.
```
cd $GOPATH/src/github.com/ardanlabs/service
GO111MODULE=on go mod tidy
GO111MODULE=on go mod vendor
```
### Installing Docker
Docker is a critical component to managing and running this project. It kills me to just send you to the Docker installation page but it's all I got for now.
https://docs.docker.com/install/
If you are having problems installing docker reach out or jump on [Gopher Slack](http://invite.slack.golangbridge.org/) for help.
## Running The Project
All the source code, including any dependencies, have been vendored into the project. There is a single `dockerfile`and a `docker-compose` file that knows how to build and run all the services.
A `makefile` has also been provide to make building, running and testing the software easier.
### Building the project
Navigate to the root of the project and use the `makefile` to build all of the services.
```
$ cd $GOPATH/src/github.com/ardanlabs/service
$ make all
```
### Running the project
Navigate to the root of the project and use the `makefile` to run all of the services.
```
$ cd $GOPATH/src/github.com/ardanlabs/service
$ make up
```
The `make up` command will leverage Docker Compose to run all the services, including the 3rd party services. The first time to run this command, Docker will download the required images for the 3rd party services.
Default configuration is set which should be valid for most systems. Use the `docker-compose.yaml` file to configure the services differently is necessary. Email me if you have issues or questions.
### Stopping the project
You can hit <ctrl>C in the terminal window running `make up`. Once that shutdown sequence is complete, it is important to run the `make down` command.
```
$ <ctrl>C
$ make down
```
Running `make down` will properly stop and terminate the Docker Compose session.
## About The Project
The service provides record keeping for someone running a multi-family garage sale. Authenticated users can maintain a list of products for sale.
<!--The service uses the following models:-->
<!--<img src="https://raw.githubusercontent.com/ardanlabs/service/master/models.jpg" alt="Garage Sale Service Models" title="Garage Sale Service Models" />-->
<!--(Diagram generated with draw.io using `models.xml` file)-->
### Making Requests
#### Initial User
To make a request to the service you must have an authenticated user. Users can be created with the API but an initial admin user must first be created. While the service is running you can create the initial user with the command `make admin`
```
$ make admin
```
This will create a user with email `<EMAIL>` and password `<PASSWORD>`.
#### Authenticating
Before any authenticated requests can be sent you must acquire an auth token. Make a request using HTTP Basic auth with your email and password to get the token.
```
$ curl --user "<EMAIL>:gophers" http://localhost:3000/v1/users/token
```
I suggest putting the resulting token in an environment variable like `$TOKEN`.
#### Authenticated Requests
To make authenticated requests put the token in the `Authorization` header with the `Bearer ` prefix.
```
$ curl -H "Authorization: Bearer ${TOKEN}" http://localhost:3000/v1/users
```
## What's Next
We are in the process of writing more documentation about this code. Classes are being finalized as part of the Ultimate series.
<file_sep>/internal/platform/trace/trace.go
package trace
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net"
"net/http"
"sync"
"time"
"go.opencensus.io/trace"
)
// Error variables for factory validation.
var (
ErrLoggerNotProvided = errors.New("logger not provided")
ErrHostNotProvided = errors.New("host not provided")
)
// Log provides support for logging inside this package.
// Unfortunately, the opentrace API calls into the ExportSpan
// function directly with no means to pass user defined arguments.
type Log func(format string, v ...interface{})
// Exporter provides support to batch spans and send them
// to the sidecar for processing.
type Exporter struct {
log Log // Handler function for logging.
host string // IP:port of the sidecare consuming the trace data.
batchSize int // Size of the batch of spans before sending.
sendInterval time.Duration // Time to send a batch if batch size is not met.
sendTimeout time.Duration // Time to wait for the sidecar to respond on send.
client http.Client // Provides APIs for performing the http send.
batch []*trace.SpanData // Maintains the batch of span data to be sent.
mu sync.Mutex // Provide synchronization to access the batch safely.
timer *time.Timer // Signals when the sendInterval is met.
}
// NewExporter creates an exporter for use.
func NewExporter(log Log, host string, batchSize int, sendInterval, sendTimeout time.Duration) (*Exporter, error) {
if log == nil {
return nil, ErrLoggerNotProvided
}
if host == "" {
return nil, ErrHostNotProvided
}
tr := http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
DualStack: true,
}).DialContext,
MaxIdleConns: 2,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
}
e := Exporter{
log: log,
host: host,
batchSize: batchSize,
sendInterval: sendInterval,
sendTimeout: sendTimeout,
client: http.Client{
Transport: &tr,
},
batch: make([]*trace.SpanData, 0, batchSize),
timer: time.NewTimer(sendInterval),
}
return &e, nil
}
// Close sends the remaining spans that have not been sent yet.
func (e *Exporter) Close() (int, error) {
var sendBatch []*trace.SpanData
e.mu.Lock()
{
sendBatch = e.batch
}
e.mu.Unlock()
err := e.send(sendBatch)
if err != nil {
return len(sendBatch), err
}
return len(sendBatch), nil
}
// ExportSpan is called by opentracing when spans are created. It implements
// the Exporter interface.
func (e *Exporter) ExportSpan(span *trace.SpanData) {
sendBatch := e.saveBatch(span)
if sendBatch != nil {
go func() {
e.log("trace : Exporter : ExportSpan : Sending Batch[%d]", len(sendBatch))
if err := e.send(sendBatch); err != nil {
e.log("trace : Exporter : ExportSpan : ERROR : %v", err)
}
}()
}
}
// Saves the span data to the batch. If the batch should be sent,
// returns a batch to send.
func (e *Exporter) saveBatch(span *trace.SpanData) []*trace.SpanData {
var sendBatch []*trace.SpanData
e.mu.Lock()
{
// We want to append this new span to the collection.
e.batch = append(e.batch, span)
// Do we need to send the current batch?
switch {
case len(e.batch) == e.batchSize:
// We hit the batch size. Now save the current
// batch for sending and start a new batch.
sendBatch = e.batch
e.batch = make([]*trace.SpanData, 0, e.batchSize)
e.timer.Reset(e.sendInterval)
default:
// We did not hit the batch size but maybe send what
// we have based on time.
select {
case <-e.timer.C:
// The time has expired so save the current
// batch for sending and start a new batch.
sendBatch = e.batch
e.batch = make([]*trace.SpanData, 0, e.batchSize)
e.timer.Reset(e.sendInterval)
// It's not time yet, just move on.
default:
}
}
}
e.mu.Unlock()
return sendBatch
}
// send uses HTTP to send the data to the tracing sidecare for processing.
func (e *Exporter) send(sendBatch []*trace.SpanData) error {
data, err := json.Marshal(sendBatch)
if err != nil {
return err
}
req, err := http.NewRequest("POST", e.host, bytes.NewBuffer(data))
if err != nil {
return err
}
ctx, cancel := context.WithTimeout(req.Context(), e.sendTimeout)
defer cancel()
req = req.WithContext(ctx)
ch := make(chan error)
go func() {
resp, err := e.client.Do(req)
if err != nil {
ch <- err
return
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusNoContent {
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
ch <- fmt.Errorf("error on call : status[%s]", resp.Status)
return
}
ch <- fmt.Errorf("error on call : status[%s] : %s", resp.Status, string(data))
return
}
ch <- nil
}()
return <-ch
}
<file_sep>/internal/product/product.go
package product
import (
"context"
"fmt"
"time"
"github.com/ardanlabs/service/internal/platform/db"
"github.com/pkg/errors"
"go.opencensus.io/trace"
mgo "gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)
const productsCollection = "products"
var (
// ErrNotFound abstracts the mgo not found error.
ErrNotFound = errors.New("Entity not found")
// ErrInvalidID occurs when an ID is not in a valid form.
ErrInvalidID = errors.New("ID is not in its proper form")
)
// List retrieves a list of existing products from the database.
func List(ctx context.Context, dbConn *db.DB) ([]Product, error) {
ctx, span := trace.StartSpan(ctx, "internal.product.List")
defer span.End()
p := []Product{}
f := func(collection *mgo.Collection) error {
return collection.Find(nil).All(&p)
}
if err := dbConn.Execute(ctx, productsCollection, f); err != nil {
return nil, errors.Wrap(err, "db.products.find()")
}
return p, nil
}
// Retrieve gets the specified product from the database.
func Retrieve(ctx context.Context, dbConn *db.DB, id string) (*Product, error) {
ctx, span := trace.StartSpan(ctx, "internal.product.Retrieve")
defer span.End()
if !bson.IsObjectIdHex(id) {
return nil, ErrInvalidID
}
q := bson.M{"_id": bson.ObjectIdHex(id)}
var p *Product
f := func(collection *mgo.Collection) error {
return collection.Find(q).One(&p)
}
if err := dbConn.Execute(ctx, productsCollection, f); err != nil {
if err == mgo.ErrNotFound {
return nil, ErrNotFound
}
return nil, errors.Wrap(err, fmt.Sprintf("db.products.find(%s)", db.Query(q)))
}
return p, nil
}
// Create inserts a new product into the database.
func Create(ctx context.Context, dbConn *db.DB, cp *NewProduct, now time.Time) (*Product, error) {
ctx, span := trace.StartSpan(ctx, "internal.product.Create")
defer span.End()
// Mongo truncates times to milliseconds when storing. We and do the same
// here so the value we return is consistent with what we store.
now = now.Truncate(time.Millisecond)
p := Product{
ID: bson.NewObjectId(),
Name: cp.Name,
Notes: cp.Notes,
UnitPrice: cp.UnitPrice,
Quantity: cp.Quantity,
Family: cp.Family,
DateCreated: now,
DateModified: now,
}
f := func(collection *mgo.Collection) error {
return collection.Insert(&p)
}
if err := dbConn.Execute(ctx, productsCollection, f); err != nil {
return nil, errors.Wrap(err, fmt.Sprintf("db.products.insert(%s)", db.Query(&p)))
}
return &p, nil
}
// Update replaces a product document in the database.
func Update(ctx context.Context, dbConn *db.DB, id string, upd UpdateProduct, now time.Time) error {
ctx, span := trace.StartSpan(ctx, "internal.product.Update")
defer span.End()
if !bson.IsObjectIdHex(id) {
return ErrInvalidID
}
fields := make(bson.M)
if upd.Name != nil {
fields["name"] = *upd.Name
}
if upd.Notes != nil {
fields["notes"] = *upd.Notes
}
if upd.UnitPrice != nil {
fields["unit_price"] = *upd.UnitPrice
}
if upd.Quantity != nil {
fields["quantity"] = *upd.Quantity
}
if upd.Family != nil {
fields["family"] = *upd.Family
}
// If there's nothing to update we can quit early.
if len(fields) == 0 {
return nil
}
fields["date_modified"] = now
m := bson.M{"$set": fields}
q := bson.M{"_id": bson.ObjectIdHex(id)}
f := func(collection *mgo.Collection) error {
return collection.Update(q, m)
}
if err := dbConn.Execute(ctx, productsCollection, f); err != nil {
if err == mgo.ErrNotFound {
return ErrNotFound
}
return errors.Wrap(err, fmt.Sprintf("db.customers.update(%s, %s)", db.Query(q), db.Query(m)))
}
return nil
}
// Delete removes a product from the database.
func Delete(ctx context.Context, dbConn *db.DB, id string) error {
ctx, span := trace.StartSpan(ctx, "internal.product.Delete")
defer span.End()
if !bson.IsObjectIdHex(id) {
return ErrInvalidID
}
q := bson.M{"_id": bson.ObjectIdHex(id)}
f := func(collection *mgo.Collection) error {
return collection.Remove(q)
}
if err := dbConn.Execute(ctx, productsCollection, f); err != nil {
if err == mgo.ErrNotFound {
err = ErrNotFound
}
return errors.Wrap(err, fmt.Sprintf("db.products.remove(%v)", q))
}
return nil
}
<file_sep>/docker-compose.yaml
# https://docs.docker.com/compose/compose-file
# docker-compose up
# docker-compose stop
# docker-compose down
version: '3'
networks:
shared-network:
driver: bridge
services:
# This starts a local mongo DB.
mongo:
container_name: mongo
networks:
- shared-network
image: mongo:3-jessie
ports:
- 27017:27017
command: --bind_ip 0.0.0.0
# This is the core CRUD based service.
sales-api:
container_name: sales-api
networks:
- shared-network
image: sales-api-amd64:1.0
ports:
- 3000:3000 # CRUD API
- 4000:4000 # DEBUG API
volumes:
- ${PWD}/private.pem:/app/private.pem
environment:
- SALES_AUTH_KEY_ID=1
# - SALES_DB_HOST=got:<EMAIL>:39441/gotraining
# - GODEBUG=gctrace=1
# This sidecar publishes metrics to the console by default.
metrics:
container_name: metrics
networks:
- shared-network
image: metrics-amd64:1.0
ports:
- 3001:3001 # EXPVAR API
- 4001:4001 # DEBUG API
# This sidecar publishes tracing to the console by default.
tracer:
container_name: tracer
networks:
- shared-network
image: tracer-amd64:1.0
ports:
- 3002:3002 # TRACER API
- 4002:4002 # DEBUG API
# environment:
# - SALES_ZIPKIN_HOST=http://zipkin:9411/api/v2/spans
# This sidecar allows for the viewing of traces.
zipkin:
container_name: zipkin
networks:
- shared-network
image: openzipkin/zipkin:2.11
ports:
- 9411:9411
<file_sep>/cmd/sidecar/tracer/handlers/zipkin.go
package handlers
import (
"bytes"
"context"
"encoding/binary"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net"
"net/http"
"strconv"
"strings"
"time"
"github.com/ardanlabs/service/internal/platform/web"
"github.com/openzipkin/zipkin-go/model"
"go.opencensus.io/trace"
)
// Zipkin represents the API to collect span data and send to zipkin.
type Zipkin struct {
zipkinHost string // IP:port of the zipkin service.
localHost string // IP:port of the sidecare consuming the trace data.
sendTimeout time.Duration // Time to wait for the sidecar to respond on send.
client http.Client // Provides APIs for performing the http send.
}
// NewZipkin provides support for publishing traces to zipkin.
func NewZipkin(zipkinHost string, localHost string, sendTimeout time.Duration) *Zipkin {
tr := http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
DualStack: true,
}).DialContext,
MaxIdleConns: 2,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
}
z := Zipkin{
zipkinHost: zipkinHost,
localHost: localHost,
sendTimeout: sendTimeout,
client: http.Client{
Transport: &tr,
},
}
return &z
}
// Publish takes a batch and publishes that to a host system.
func (z *Zipkin) Publish(ctx context.Context, log *log.Logger, w http.ResponseWriter, r *http.Request, params map[string]string) error {
var sd []trace.SpanData
if err := json.NewDecoder(r.Body).Decode(&sd); err != nil {
return err
}
if err := z.send(sd); err != nil {
return err
}
web.Respond(ctx, log, w, nil, http.StatusNoContent)
return nil
}
// send uses HTTP to send the data to the tracing sidecar for processing.
func (z *Zipkin) send(sendBatch []trace.SpanData) error {
le, err := newEndpoint("sales-api", z.localHost)
if err != nil {
return err
}
sm := convertForZipkin(sendBatch, le)
data, err := json.Marshal(sm)
if err != nil {
return err
}
req, err := http.NewRequest("POST", z.zipkinHost, bytes.NewBuffer(data))
if err != nil {
return err
}
ctx, cancel := context.WithTimeout(req.Context(), z.sendTimeout)
defer cancel()
req = req.WithContext(ctx)
ch := make(chan error)
go func() {
resp, err := z.client.Do(req)
if err != nil {
ch <- err
return
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusAccepted {
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
ch <- fmt.Errorf("error on call : status[%s]", resp.Status)
return
}
ch <- fmt.Errorf("error on call : status[%s] : %s", resp.Status, string(data))
return
}
ch <- nil
}()
return <-ch
}
// =============================================================================
const (
statusCodeTagKey = "error"
statusDescriptionTagKey = "opencensus.status_description"
)
var (
sampledTrue = true
canonicalCodes = [...]string{
"OK",
"CANCELLED",
"UNKNOWN",
"INVALID_ARGUMENT",
"DEADLINE_EXCEEDED",
"NOT_FOUND",
"ALREADY_EXISTS",
"PERMISSION_DENIED",
"RESOURCE_EXHAUSTED",
"FAILED_PRECONDITION",
"ABORTED",
"OUT_OF_RANGE",
"UNIMPLEMENTED",
"INTERNAL",
"UNAVAILABLE",
"DATA_LOSS",
"UNAUTHENTICATED",
}
)
func convertForZipkin(spanData []trace.SpanData, localEndpoint *model.Endpoint) []model.SpanModel {
sm := make([]model.SpanModel, len(spanData))
for i := range spanData {
sm[i] = zipkinSpan(&spanData[i], localEndpoint)
}
return sm
}
func newEndpoint(serviceName string, hostPort string) (*model.Endpoint, error) {
e := &model.Endpoint{
ServiceName: serviceName,
}
if hostPort == "" || hostPort == ":0" {
if serviceName == "" {
// if all properties are empty we should not have an Endpoint object.
return nil, nil
}
return e, nil
}
if strings.IndexByte(hostPort, ':') < 0 {
hostPort += ":0"
}
host, port, err := net.SplitHostPort(hostPort)
if err != nil {
return nil, err
}
p, err := strconv.ParseUint(port, 10, 16)
if err != nil {
return nil, err
}
e.Port = uint16(p)
addrs, err := net.LookupIP(host)
if err != nil {
return nil, err
}
for i := range addrs {
addr := addrs[i].To4()
if addr == nil {
// IPv6 - 16 bytes
if e.IPv6 == nil {
e.IPv6 = addrs[i].To16()
}
} else {
// IPv4 - 4 bytes
if e.IPv4 == nil {
e.IPv4 = addr
}
}
if e.IPv4 != nil && e.IPv6 != nil {
// Both IPv4 & IPv6 have been set, done...
break
}
}
// default to 0 filled 4 byte array for IPv4 if IPv6 only host was found
if e.IPv4 == nil {
e.IPv4 = make([]byte, 4)
}
return e, nil
}
func canonicalCodeString(code int32) string {
if code < 0 || int(code) >= len(canonicalCodes) {
return "error code " + strconv.FormatInt(int64(code), 10)
}
return canonicalCodes[code]
}
func convertTraceID(t trace.TraceID) model.TraceID {
return model.TraceID{
High: binary.BigEndian.Uint64(t[:8]),
Low: binary.BigEndian.Uint64(t[8:]),
}
}
func convertSpanID(s trace.SpanID) model.ID {
return model.ID(binary.BigEndian.Uint64(s[:]))
}
func spanKind(s *trace.SpanData) model.Kind {
switch s.SpanKind {
case trace.SpanKindClient:
return model.Client
case trace.SpanKindServer:
return model.Server
}
return model.Undetermined
}
func zipkinSpan(s *trace.SpanData, localEndpoint *model.Endpoint) model.SpanModel {
sc := s.SpanContext
z := model.SpanModel{
SpanContext: model.SpanContext{
TraceID: convertTraceID(sc.TraceID),
ID: convertSpanID(sc.SpanID),
Sampled: &sampledTrue,
},
Kind: spanKind(s),
Name: s.Name,
Timestamp: s.StartTime,
Shared: false,
LocalEndpoint: localEndpoint,
}
if s.ParentSpanID != (trace.SpanID{}) {
id := convertSpanID(s.ParentSpanID)
z.ParentID = &id
}
if s, e := s.StartTime, s.EndTime; !s.IsZero() && !e.IsZero() {
z.Duration = e.Sub(s)
}
// construct Tags from s.Attributes and s.Status.
if len(s.Attributes) != 0 {
m := make(map[string]string, len(s.Attributes)+2)
for key, value := range s.Attributes {
switch v := value.(type) {
case string:
m[key] = v
case bool:
if v {
m[key] = "true"
} else {
m[key] = "false"
}
case int64:
m[key] = strconv.FormatInt(v, 10)
}
}
z.Tags = m
}
if s.Status.Code != 0 || s.Status.Message != "" {
if z.Tags == nil {
z.Tags = make(map[string]string, 2)
}
if s.Status.Code != 0 {
z.Tags[statusCodeTagKey] = canonicalCodeString(s.Status.Code)
}
if s.Status.Message != "" {
z.Tags[statusDescriptionTagKey] = s.Status.Message
}
}
// construct Annotations from s.Annotations and s.MessageEvents.
if len(s.Annotations) != 0 || len(s.MessageEvents) != 0 {
z.Annotations = make([]model.Annotation, 0, len(s.Annotations)+len(s.MessageEvents))
for _, a := range s.Annotations {
z.Annotations = append(z.Annotations, model.Annotation{
Timestamp: a.Time,
Value: a.Message,
})
}
for _, m := range s.MessageEvents {
a := model.Annotation{
Timestamp: m.Time,
}
switch m.EventType {
case trace.MessageEventTypeSent:
a.Value = "SENT"
case trace.MessageEventTypeRecv:
a.Value = "RECV"
default:
a.Value = "<?>"
}
z.Annotations = append(z.Annotations, a)
}
}
return z
}
<file_sep>/internal/mid/logger.go
package mid
import (
"context"
"log"
"net/http"
"time"
"github.com/ardanlabs/service/internal/platform/web"
"go.opencensus.io/trace"
)
// RequestLogger writes some information about the request to the logs in
// the format: TraceID : (200) GET /foo -> IP ADDR (latency)
func RequestLogger(before web.Handler) web.Handler {
// Wrap this handler around the next one provided.
h := func(ctx context.Context, log *log.Logger, w http.ResponseWriter, r *http.Request, params map[string]string) error {
ctx, span := trace.StartSpan(ctx, "internal.mid.RequestLogger")
defer span.End()
// If the context is missing this value, request the service
// to be shutdown gracefully.
v, ok := ctx.Value(web.KeyValues).(*web.Values)
if !ok {
return web.Shutdown("web value missing from context")
}
err := before(ctx, log, w, r, params)
log.Printf("%s : (%d) : %s %s -> %s (%s)",
v.TraceID,
v.StatusCode,
r.Method, r.URL.Path,
r.RemoteAddr, time.Since(v.Now),
)
// For consistency return the error we received.
return err
}
return h
}
<file_sep>/internal/platform/tests/main.go
package tests
import (
"context"
"fmt"
"log"
"os"
"runtime/debug"
"testing"
"time"
"github.com/ardanlabs/service/internal/platform/db"
"github.com/ardanlabs/service/internal/platform/docker"
"github.com/ardanlabs/service/internal/platform/web"
"github.com/pborman/uuid"
)
// Success and failure markers.
const (
Success = "\u2713"
Failed = "\u2717"
)
// Test owns state for running/shutting down tests.
type Test struct {
Log *log.Logger
MasterDB *db.DB
container *docker.Container
}
// New is the entry point for tests.
func New() *Test {
// =========================================================================
// Logging
log := log.New(os.Stdout, "TEST : ", log.LstdFlags|log.Lmicroseconds|log.Lshortfile)
// ============================================================
// Startup Mongo container
container, err := docker.StartMongo(log)
if err != nil {
log.Fatalln(err)
}
// ============================================================
// Configuration
dbDialTimeout := 25 * time.Second
dbHost := fmt.Sprintf("mongodb://localhost:%s/gotraining", container.Port)
// ============================================================
// Start Mongo
log.Println("main : Started : Initialize Mongo")
masterDB, err := db.New(dbHost, dbDialTimeout)
if err != nil {
log.Fatalf("startup : Register DB : %v", err)
}
return &Test{log, masterDB, container}
}
// TearDown is used for shutting down tests. Calling this should be
// done in a defer immediately after calling New.
func (t *Test) TearDown() {
t.MasterDB.Close()
if err := docker.StopMongo(t.Log, t.container); err != nil {
t.Log.Println(err)
}
}
// Recover is used to prevent panics from allowing the test to cleanup.
func Recover(t *testing.T) {
if r := recover(); r != nil {
t.Fatal("Unhandled Exception:", string(debug.Stack()))
}
}
// Context returns an app level context for testing.
func Context() context.Context {
values := web.Values{
TraceID: uuid.New(),
Now: time.Now(),
}
return context.WithValue(context.Background(), web.KeyValues, &values)
}
<file_sep>/cmd/sidecar/tracer/handlers/health.go
package handlers
import (
"context"
"log"
"net/http"
"github.com/ardanlabs/service/internal/platform/web"
)
// Health provides support for orchestration health checks.
type Health struct{}
// Check validates the service is ready and healthy to accept requests.
func (h *Health) Check(ctx context.Context, log *log.Logger, w http.ResponseWriter, r *http.Request, params map[string]string) error {
status := struct {
Status string `json:"status"`
}{
Status: "ok",
}
web.Respond(ctx, log, w, status, http.StatusOK)
return nil
}
<file_sep>/internal/platform/tests/type_helpers.go
package tests
// StringPointer is a helper to get a *string from a string. It is in the tests
// package because we normally don't want to deal with pointers to basic types
// but it's useful in some tests.
func StringPointer(s string) *string {
return &s
}
// IntPointer is a helper to get a *int from a int. It is in the tests package
// because we normally don't want to deal with pointers to basic types but it's
// useful in some tests.
func IntPointer(i int) *int {
return &i
}
<file_sep>/internal/platform/web/middleware.go
package web
// A Middleware is a type that wraps a handler to remove boilerplate or other
// concerns not direct to any given Handler.
type Middleware func(Handler) Handler
// wrapMiddleware wraps a handler with some middleware.
func wrapMiddleware(handler Handler, mw []Middleware) Handler {
// Wrap with our group specific middleware.
for _, h := range mw {
if h != nil {
handler = h(handler)
}
}
return handler
}
<file_sep>/go.mod
module github.com/ardanlabs/service
require (
github.com/dgrijalva/jwt-go v3.2.0+incompatible
github.com/dimfeld/httptreemux v5.0.1+incompatible
github.com/google/go-cmp v0.2.0
github.com/kelseyhightower/envconfig v1.3.0
github.com/kr/pretty v0.1.0 // indirect
github.com/openzipkin/zipkin-go v0.1.1
github.com/pborman/uuid v0.0.0-20180122190007-c65b2f87fee3
github.com/pkg/errors v0.8.0
go.opencensus.io v0.14.0
golang.org/x/crypto v0.0.0-20180910181607-0e37d006457b
golang.org/x/net v0.0.0-20180724234803-3673e40ba225 // indirect
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 // indirect
gopkg.in/go-playground/assert.v1 v1.2.1 // indirect
gopkg.in/go-playground/validator.v8 v8.18.2
gopkg.in/mgo.v2 v2.0.0-20180705113604-9856a29383ce
gopkg.in/yaml.v2 v2.2.1 // indirect
)
<file_sep>/internal/platform/flag/flag_test.go
package flag
import (
"encoding/json"
"testing"
"time"
)
const (
success = "\u2713"
failed = "\u2717"
)
// TestProcessNoArgs validates when no arguments are passed to the Process API.
func TestProcessNoArgs(t *testing.T) {
var cfg struct {
Web struct {
APIHost string `default:"0.0.0.0:3000" flag:"a" flagdesc:"The ip:port for the api endpoint."`
BatchSize int `default:"1000" flagdesc:"Represets number of items to move."`
ReadTimeout time.Duration `default:"5s"`
}
DialTimeout time.Duration `default:"5s"`
Host string `default:"mongo:27017/gotraining" flag:"h"`
}
t.Log("Given the need to validate was handle no arguments.")
{
t.Log("\tWhen there are no OS arguments.")
{
if err := Process(&cfg); err != nil {
t.Fatalf("\t%s\tShould be able to call Process with no arguments : %s.", failed, err)
}
t.Logf("\t%s\tShould be able to call Process with no arguments.", success)
}
}
}
// TestParse validates the ability to reflect and parse out the argument
// metadata from the provided struct value.
func TestParse(t *testing.T) {
var cfg struct {
Web struct {
APIHost string `default:"0.0.0.0:3000" flag:"a" flagdesc:"The ip:port for the api endpoint."`
BatchSize int `default:"1000" flagdesc:"Represets number of items to move."`
ReadTimeout time.Duration `default:"5s"`
}
DialTimeout time.Duration `default:"5s"`
Host string `default:"mongo:27017/gotraining" flag:"h"`
Insecure bool `flag:"i"`
}
parseOutput := `[{"Short":"a","Long":"web_apihost","Default":"0.0.0.0:3000","Type":"string","Desc":"The ip:port for the api endpoint."},{"Short":"","Long":"web_batchsize","Default":"1000","Type":"int","Desc":"Represets number of items to move."},{"Short":"","Long":"web_readtimeout","Default":"5s","Type":"Duration","Desc":""},{"Short":"","Long":"dialtimeout","Default":"5s","Type":"Duration","Desc":""},{"Short":"h","Long":"host","Default":"mongo:27017/gotraining","Type":"string","Desc":""},{"Short":"i","Long":"insecure","Default":"","Type":"bool","Desc":""}]`
t.Log("Given the need to validate we can parse a struct value.")
{
t.Log("\tWhen parsing the test config.")
{
args, err := parse("", &cfg)
if err != nil {
t.Fatalf("\t%s\tShould be able to parse arguments without error : %s.", failed, err)
}
t.Logf("\t%s\tShould be able to parse arguments without error.", success)
d, _ := json.Marshal(args)
if string(d) != parseOutput {
t.Log("\t\tGot :", string(d))
t.Log("\t\tWant:", parseOutput)
t.Fatalf("\t%s\tShould get back the expected arguments.", failed)
}
t.Logf("\t%s\tShould get back the expected arguments.", success)
}
}
}
// TestApply validates the ability to apply overrides to a struct value
// based on provided flag arguments.
func TestApply(t *testing.T) {
var cfg struct {
Web struct {
APIHost string `default:"0.0.0.0:3000" flag:"a" flagdesc:"The ip:port for the api endpoint."`
BatchSize int `default:"1000" flagdesc:"Represets number of items to move."`
ReadTimeout time.Duration `default:"5s"`
}
DialTimeout time.Duration `default:"5s"`
Host string `default:"mongo:27017/gotraining" flag:"h"`
Insecure bool `flag:"i"`
}
osArgs := []string{"./sales-api", "-i", "-a", "0.0.1.1:5000", "--web_batchsize", "300", "--dialtimeout", "10s"}
expected := `{"Web":{"APIHost":"0.0.1.1:5000","BatchSize":300,"ReadTimeout":0},"DialTimeout":10000000000,"Host":"","Insecure":true}`
t.Log("Given the need to validate we can apply overrides a struct value.")
{
t.Log("\tWhen parsing the test config.")
{
args, err := parse("", &cfg)
if err != nil {
t.Fatalf("\t%s\tShould be able to parse arguments without error : %s.", failed, err)
}
t.Logf("\t%s\tShould be able to parse arguments without error.", success)
if err := apply(osArgs, args); err != nil {
t.Fatalf("\t%s\tShould be able to apply arguments without error : %s.", failed, err)
}
t.Logf("\t%s\tShould be able to apply arguments without error.", success)
d, _ := json.Marshal(&cfg)
if string(d) != expected {
t.Log("\t\tGot :", string(d))
t.Log("\t\tWant:", expected)
t.Fatalf("\t%s\tShould get back the expected struct value.", failed)
}
t.Logf("\t%s\tShould get back the expected struct value.", success)
}
}
}
// TestApplyBad validates the ability to handle bad arguments on the command line.
func TestApplyBad(t *testing.T) {
var cfg struct {
Web struct {
APIHost string `default:"0.0.0.0:3000" flag:"a" flagdesc:"The ip:port for the api endpoint."`
BatchSize int `default:"1000" flagdesc:"Represets number of items to move."`
ReadTimeout time.Duration `default:"5s"`
}
DialTimeout time.Duration `default:"5s"`
Host string `default:"mongo:27017/gotraining" flag:"h"`
Insecure bool
}
tests := []struct {
osArg []string
}{
{[]string{"testapp", "-help"}},
{[]string{"testapp", "-bad", "value"}},
{[]string{"testapp", "-insecure", "value"}},
}
t.Log("Given the need to validate we can parse a struct value with bad OS arguments.")
{
for i, tt := range tests {
t.Logf("\tTest: %d\tWhen checking %v", i, tt.osArg)
{
args, err := parse("", &cfg)
if err != nil {
t.Fatalf("\t%s\tShould be able to parse arguments without error : %s.", failed, err)
}
t.Logf("\t%s\tShould be able to parse arguments without error.", success)
if err := apply(tt.osArg, args); err != nil {
t.Logf("\t%s\tShould not be able to apply arguments.", success)
} else {
t.Errorf("\t%s\tShould not be able to apply arguments.", failed)
}
}
}
}
}
// TestDisplay provides a test for displaying the command line arguments.
func TestDisplay(t *testing.T) {
var cfg struct {
Web struct {
APIHost string `default:"0.0.0.0:3000" flag:"a" flagdesc:"The ip:port for the api endpoint."`
BatchSize int `default:"1000" flagdesc:"Represets number of items to move."`
ReadTimeout time.Duration `default:"5s"`
}
DialTimeout time.Duration `default:"5s"`
Host string `default:"mongo:27017/gotraining" flag:"h"`
Insecure bool `flag:"i"`
}
want := `
Usage of TestApp
-a --web_apihost string <0.0.0.0:3000> : The ip:port for the api endpoint.
--web_batchsize int <1000> : Represets number of items to move.
--web_readtimeout Duration <5s>
--dialtimeout Duration <5s>
-h --host string <mongo:27017/gotraining>
-i --insecure bool
`
got := display("TestApp", &cfg)
if got != want {
t.Log("\t\tGot :", []byte(got))
t.Log("\t\tWant:", []byte(want))
t.Fatalf("\t%s\tShould get back the expected help output.", failed)
}
t.Logf("\t%s\tShould get back the expected help output.", success)
}
<file_sep>/internal/mid/errors.go
package mid
import (
"context"
"log"
"net/http"
"runtime/debug"
"github.com/ardanlabs/service/internal/platform/web"
"github.com/pkg/errors"
"go.opencensus.io/trace"
)
// ErrorHandler for catching and responding to errors.
func ErrorHandler(before web.Handler) web.Handler {
// Create the handler that will be attached in the middleware chain.
h := func(ctx context.Context, log *log.Logger, w http.ResponseWriter, r *http.Request, params map[string]string) error {
ctx, span := trace.StartSpan(ctx, "internal.mid.ErrorHandler")
defer span.End()
// If the context is missing this value, request the service
// to be shutdown gracefully.
v, ok := ctx.Value(web.KeyValues).(*web.Values)
if !ok {
return web.Shutdown("web value missing from context")
}
// In the event of a panic, we want to capture it here so we can send an
// error down the stack.
defer func() {
if r := recover(); r != nil {
// Indicate this request had an error.
v.Error = true
// Log the panic.
log.Printf("%s : ERROR : Panic Caught : %s\n", v.TraceID, r)
// Respond with the error.
web.Error(ctx, log, w, errors.New("unhandled"))
// Print out the stack.
log.Printf("%s : ERROR : Stacktrace\n%s\n", v.TraceID, debug.Stack())
}
}()
if err := before(ctx, log, w, r, params); err != nil {
// Indicate this request had an error.
v.Error = true
// What is the root error.
err = errors.Cause(err)
// If we receive the shutdown err we need to return it
// back to the base handler to shutdown the service.
if ok := web.IsShutdown(err); ok {
web.Error(ctx, log, w, errors.New("unhandled"))
return err
}
// Don't log errors based on not found issues. This has
// the potential to create noise in the logs.
if err != web.ErrNotFound {
log.Printf("%s : ERROR : %v\n", v.TraceID, err)
}
// Respond with the error.
web.Error(ctx, log, w, err)
// The error has been handled so we can stop propagating it.
return nil
}
return nil
}
return h
}
<file_sep>/internal/platform/web/web.go
package web
import (
"context"
"log"
"net/http"
"os"
"syscall"
"time"
"github.com/dimfeld/httptreemux"
"go.opencensus.io/plugin/ochttp/propagation/tracecontext"
"go.opencensus.io/trace"
)
// ctxKey represents the type of value for the context key.
type ctxKey int
// KeyValues is how request values or stored/retrieved.
const KeyValues ctxKey = 1
// Values represent state for each request.
type Values struct {
TraceID string
Now time.Time
StatusCode int
Error bool
}
// A Handler is a type that handles an http request within our own little mini
// framework.
type Handler func(ctx context.Context, log *log.Logger, w http.ResponseWriter, r *http.Request, params map[string]string) error
// App is the entrypoint into our application and what configures our context
// object for each of our http handlers. Feel free to add any configuration
// data/logic on this App struct
type App struct {
*httptreemux.TreeMux
shutdown chan os.Signal
log *log.Logger
mw []Middleware
}
// New creates an App value that handle a set of routes for the application.
func New(shutdown chan os.Signal, log *log.Logger, mw ...Middleware) *App {
return &App{
TreeMux: httptreemux.New(),
shutdown: shutdown,
log: log,
mw: mw,
}
}
// SignalShutdown is used to gracefully shutdown the app when an integrity
// issue is identified.
func (a *App) SignalShutdown() {
a.log.Println("error returned from handler indicated integrity issue, shutting down service")
a.shutdown <- syscall.SIGSTOP
}
// Handle is our mechanism for mounting Handlers for a given HTTP verb and path
// pair, this makes for really easy, convenient routing.
func (a *App) Handle(verb, path string, handler Handler, mw ...Middleware) {
// Wrap up the application-wide first, this will call the first function
// of each middleware which will return a function of type Handler.
handler = wrapMiddleware(wrapMiddleware(handler, mw), a.mw)
// The function to execute for each request.
h := func(w http.ResponseWriter, r *http.Request, params map[string]string) {
// This API is using pointer semantic methods on this empty
// struct type :( This is causing the need to declare this
// variable here at the top.
var hf tracecontext.HTTPFormat
// Check the request for an existing Trace. The WithSpanContext
// function can unmarshal any existing context or create a new one.
var ctx context.Context
var span *trace.Span
if sc, ok := hf.SpanContextFromRequest(r); ok {
ctx, span = trace.StartSpanWithRemoteParent(r.Context(), "internal.platform.web", sc)
} else {
ctx, span = trace.StartSpan(r.Context(), "internal.platform.web")
}
defer span.End()
// Set the context with the required values to
// process the request.
v := Values{
TraceID: span.SpanContext().TraceID.String(),
Now: time.Now(),
}
ctx = context.WithValue(ctx, KeyValues, &v)
// Set the parent span on the outgoing requests before any other header to
// ensure that the trace is ALWAYS added to the request regardless of
// any error occuring or not.
hf.SpanContextToRequest(span.SpanContext(), r)
// Call the wrapped handler functions.
if err := handler(ctx, a.log, w, r, params); err != nil {
a.log.Printf("*****> critical shutdown error: %v", err)
a.SignalShutdown()
return
}
}
// Add this handler for the specified verb and route.
a.TreeMux.Handle(verb, path, h)
}
// shutdown is a type used to help with the graceful termination of the service.
type shutdown struct {
Message string
}
// Error is the implementation of the error interface.
func (s *shutdown) Error() string {
return s.Message
}
// Shutdown returns an error that causes the framework to signal
// a graceful shutdown.
func Shutdown(message string) error {
return &shutdown{message}
}
// IsShutdown checks to see if the shutdown error is contained
// in the specified error value.
func IsShutdown(err error) bool {
if _, ok := err.(*shutdown); ok {
return true
}
return false
}
<file_sep>/internal/platform/web/validation.go
package web
import (
"encoding/json"
"fmt"
"io"
validator "gopkg.in/go-playground/validator.v8"
)
// validate provides a validator for checking models.
var validate = validator.New(&validator.Config{
TagName: "validate",
FieldNameTag: "json",
})
// Invalid describes a validation error belonging to a specific field.
type Invalid struct {
Fld string `json:"field_name"`
Err string `json:"error"`
}
// InvalidError is a custom error type for invalid fields.
type InvalidError []Invalid
// Error implements the error interface for InvalidError.
func (err InvalidError) Error() string {
var str string
for _, v := range err {
str = fmt.Sprintf("%s,{%s:%s}", str, v.Fld, v.Err)
}
return str
}
// Unmarshal decodes the input to the struct type and checks the
// fields to verify the value is in a proper state.
func Unmarshal(r io.Reader, v interface{}) error {
if err := json.NewDecoder(r).Decode(v); err != nil {
return err
}
var inv InvalidError
if fve := validate.Struct(v); fve != nil {
for _, fe := range fve.(validator.ValidationErrors) {
inv = append(inv, Invalid{Fld: fe.Field, Err: fe.Tag})
}
return inv
}
return nil
}
<file_sep>/internal/platform/web/response.go
package web
import (
"context"
"encoding/json"
"log"
"net/http"
"github.com/pkg/errors"
)
var (
// ErrNotHealthy occurs when the service is having problems.
ErrNotHealthy = errors.New("Not healthy")
// ErrNotFound is abstracting the mgo not found error.
ErrNotFound = errors.New("Entity not found")
// ErrInvalidID occurs when an ID is not in a valid form.
ErrInvalidID = errors.New("ID is not in its proper form")
// ErrValidation occurs when there are validation errors.
ErrValidation = errors.New("Validation errors occurred")
// ErrUnauthorized occurs when there was an issue validing the client's
// credentials.
ErrUnauthorized = errors.New("Unauthorized")
// ErrForbidden occurs when we know who the user is but they attempt a
// forbidden action.
ErrForbidden = errors.New("Forbidden")
)
// JSONError is the response for errors that occur within the API.
type JSONError struct {
Error string `json:"error"`
Fields InvalidError `json:"fields,omitempty"`
}
// Error handles all error responses for the API.
func Error(ctx context.Context, log *log.Logger, w http.ResponseWriter, err error) {
switch errors.Cause(err) {
case ErrNotHealthy:
Respond(ctx, log, w, JSONError{Error: err.Error()}, http.StatusInternalServerError)
return
case ErrNotFound:
Respond(ctx, log, w, JSONError{Error: err.Error()}, http.StatusNotFound)
return
case ErrValidation, ErrInvalidID:
Respond(ctx, log, w, JSONError{Error: err.Error()}, http.StatusBadRequest)
return
case ErrUnauthorized:
Respond(ctx, log, w, JSONError{Error: err.Error()}, http.StatusUnauthorized)
return
case ErrForbidden:
Respond(ctx, log, w, JSONError{Error: err.Error()}, http.StatusForbidden)
return
}
switch e := errors.Cause(err).(type) {
case InvalidError:
je := JSONError{
Error: "field validation failure",
Fields: e,
}
Respond(ctx, log, w, je, http.StatusBadRequest)
return
}
Respond(ctx, log, w, JSONError{Error: err.Error()}, http.StatusInternalServerError)
}
// Respond sends JSON to the client.
// If code is StatusNoContent, v is expected to be nil.
func Respond(ctx context.Context, log *log.Logger, w http.ResponseWriter, data interface{}, code int) {
// Set the status code for the request logger middleware.
v := ctx.Value(KeyValues).(*Values)
v.StatusCode = code
// Just set the status code and we are done. If there is nothing to marshal
// set status code and return.
if code == http.StatusNoContent || data == nil {
w.WriteHeader(code)
return
}
// Marshal the data into a JSON string.
jsonData, err := json.MarshalIndent(data, "", " ")
if err != nil {
log.Printf("%s : Respond %v Marshalling JSON response\n", v.TraceID, err)
// Should respond with internal server error.
Error(ctx, log, w, err)
return
}
// Set the content type and headers once we know marshaling has succeeded.
w.Header().Set("Content-Type", "application/json")
// Write the status code to the response and context.
w.WriteHeader(code)
// Send the result back to the client.
w.Write(jsonData)
}
<file_sep>/internal/product/models.go
package product
import (
"time"
"gopkg.in/mgo.v2/bson"
)
// Product is something we have for sale.
type Product struct {
ID bson.ObjectId `bson:"_id" json:"id"` // Unique identifier.
Name string `bson:"name" json:"name"` // Display name of the product.
Notes string `bson:"notes" json:"notes"` // Optional descriptive field.
Family string `bson:"family" json:"family"` // Which family provided the product.
UnitPrice int `bson:"unit_price" json:"unit_price"` // Price for one item in cents.
Quantity int `bson:"quantity" json:"quantity"` // Original number of items available.
DateCreated time.Time `bson:"date_created" json:"date_created"` // When the product was added.
DateModified time.Time `bson:"date_modified" json:"date_modified"` // When the product record was lost modified.
}
// NewProduct defines the information we need when adding a Product to
// our offerings.
type NewProduct struct {
Name string `json:"name" validate:"required"`
Notes string `json:"notes"`
Family string `json:"family" validate:"required"`
UnitPrice int `json:"unit_price" validate:"required,gte=0"`
Quantity int `json:"quantity" validate:"required,gte=1"`
}
// UpdateProduct defines what information may be provided to modify an
// existing Product. All fields are optional so clients can send just the
// fields they want changed. It uses pointer fields so we can differentiate
// between a field that was not provided and a field that was provided as
// explicitly blank. Normally we do not want to use pointers to basic types but
// we make exceptions around marshalling/unmarshalling.
type UpdateProduct struct {
Name *string `json:"name"`
Notes *string `json:"notes"`
Family *string `json:"family"`
UnitPrice *int `json:"unit_price" validate:"omitempty,gte=0"`
Quantity *int `json:"quantity" validate:"omitempty,gte=1"`
}
// Sale represents a transaction where we sold some quantity of a
// Product.
type Sale struct{}
// NewSale defines what we require when creating a Sale record.
type NewSale struct{}
<file_sep>/internal/user/user_test.go
package user_test
import (
"fmt"
"os"
"testing"
"time"
"github.com/ardanlabs/service/internal/platform/auth"
"github.com/ardanlabs/service/internal/platform/tests"
"github.com/ardanlabs/service/internal/user"
"github.com/google/go-cmp/cmp"
"github.com/pkg/errors"
"gopkg.in/mgo.v2/bson"
)
var test *tests.Test
// TestMain is the entry point for testing.
func TestMain(m *testing.M) {
os.Exit(testMain(m))
}
func testMain(m *testing.M) int {
test = tests.New()
defer test.TearDown()
return m.Run()
}
// TestUser validates the full set of CRUD operations on User values.
func TestUser(t *testing.T) {
defer tests.Recover(t)
t.Log("Given the need to work with User records.")
{
t.Log("\tWhen handling a single User.")
{
ctx := tests.Context()
dbConn := test.MasterDB.Copy()
defer dbConn.Close()
now := time.Date(2018, time.October, 1, 0, 0, 0, 0, time.UTC)
// claims is information about the person making the request.
claims := auth.NewClaims(bson.NewObjectId().Hex(), []string{auth.RoleAdmin}, now, time.Hour)
nu := user.NewUser{
Name: "<NAME>",
Email: "<EMAIL>",
Roles: []string{auth.RoleAdmin},
Password: "<PASSWORD>",
PasswordConfirm: "<PASSWORD>",
}
u, err := user.Create(ctx, dbConn, &nu, now)
if err != nil {
t.Fatalf("\t%s\tShould be able to create user : %s.", tests.Failed, err)
}
t.Logf("\t%s\tShould be able to create user.", tests.Success)
savedU, err := user.Retrieve(ctx, claims, dbConn, u.ID.Hex())
if err != nil {
t.Fatalf("\t%s\tShould be able to retrieve user by ID: %s.", tests.Failed, err)
}
t.Logf("\t%s\tShould be able to retrieve user by ID.", tests.Success)
if diff := cmp.Diff(u, savedU); diff != "" {
t.Fatalf("\t%s\tShould get back the same user. Diff:\n%s", tests.Failed, diff)
}
t.Logf("\t%s\tShould get back the same user.", tests.Success)
upd := user.UpdateUser{
Name: tests.StringPointer("<NAME>"),
Email: tests.StringPointer("<EMAIL>"),
}
if err := user.Update(ctx, dbConn, u.ID.Hex(), &upd, now); err != nil {
t.Fatalf("\t%s\tShould be able to update user : %s.", tests.Failed, err)
}
t.Logf("\t%s\tShould be able to update user.", tests.Success)
savedU, err = user.Retrieve(ctx, claims, dbConn, u.ID.Hex())
if err != nil {
t.Fatalf("\t%s\tShould be able to retrieve user : %s.", tests.Failed, err)
}
t.Logf("\t%s\tShould be able to retrieve user.", tests.Success)
if savedU.Name != *upd.Name {
t.Log("\t\tGot :", savedU.Name)
t.Log("\t\tWant:", *upd.Name)
t.Errorf("\t%s\tShould be able to see updates to LastName.", tests.Failed)
} else {
t.Logf("\t%s\tShould be able to see updates to LastName.", tests.Success)
}
if err := user.Delete(ctx, dbConn, u.ID.Hex()); err != nil {
t.Fatalf("\t%s\tShould be able to delete user : %s.", tests.Failed, err)
}
t.Logf("\t%s\tShould be able to delete user.", tests.Success)
savedU, err = user.Retrieve(ctx, claims, dbConn, u.ID.Hex())
if errors.Cause(err) != user.ErrNotFound {
t.Fatalf("\t%s\tShould NOT be able to retrieve user : %s.", tests.Failed, err)
}
t.Logf("\t%s\tShould NOT be able to retrieve user.", tests.Success)
}
}
}
// mockTokenGenerator is used for testing that Authenticate calls its provided
// token generator in a specific way.
type mockTokenGenerator struct{}
// GenerateToken implements the TokenGenerator interface. It returns a "token"
// that includes some information about the claims it was passed.
func (mockTokenGenerator) GenerateToken(claims auth.Claims) (string, error) {
return fmt.Sprintf("sub:%q iss:%d", claims.Subject, claims.IssuedAt), nil
}
// TestAuthenticate validates the behavior around authenticating users.
func TestAuthenticate(t *testing.T) {
defer tests.Recover(t)
t.Log("Given the need to authenticate users")
{
t.Log("\tWhen handling a single User.")
{
ctx := tests.Context()
dbConn := test.MasterDB.Copy()
defer dbConn.Close()
nu := user.NewUser{
Name: "<NAME>",
Email: "<EMAIL>",
Roles: []string{auth.RoleAdmin},
Password: "<PASSWORD>",
PasswordConfirm: "<PASSWORD>",
}
now := time.Date(2018, time.October, 1, 0, 0, 0, 0, time.UTC)
u, err := user.Create(ctx, dbConn, &nu, now)
if err != nil {
t.Fatalf("\t%s\tShould be able to create user : %s.", tests.Failed, err)
}
t.Logf("\t%s\tShould be able to create user.", tests.Success)
var tknGen mockTokenGenerator
tkn, err := user.Authenticate(ctx, dbConn, tknGen, now, "<EMAIL>", "goroutines")
if err != nil {
t.Fatalf("\t%s\tShould be able to generate a token : %s.", tests.Failed, err)
}
t.Logf("\t%s\tShould be able to generate a token.", tests.Success)
want := fmt.Sprintf("sub:%q iss:1538352000", u.ID.Hex())
if tkn.Token != want {
t.Log("\t\tGot :", tkn.Token)
t.Log("\t\tWant:", want)
t.Fatalf("\t%s\tToken should indicate the specified user and time were used.", tests.Failed)
}
t.Logf("\t%s\tToken should indicate the specified user and time were used.", tests.Success)
if err := user.Delete(ctx, dbConn, u.ID.Hex()); err != nil {
t.Fatalf("\t%s\tShould be able to delete user : %s.", tests.Failed, err)
}
t.Logf("\t%s\tShould be able to delete user.", tests.Success)
}
}
}
<file_sep>/internal/platform/flag/doc.go
/*
Package flag is compatible with the GNU extensions to the POSIX recommendations
for command-line options. See
http://www.gnu.org/software/libc/manual/html_node/Argument-Syntax.html
There are no hard bindings for this package. This package takes a struct
value and parses it for flags. It supports three tags to customize the
flag options.
flag - Denotes a shorthand option
flagdesc - Provides a description for the help
default - Provides the default value for the help
The field name and any parent struct name will be used for the long form of
the command name.
As an example, this config struct:
var cfg struct {
Web struct {
APIHost string `default:"0.0.0.0:3000" flag:"a" flagdesc:"The ip:port for the api endpoint."`
BatchSize int `default:"1000" flagdesc:"Represents number of items to move."`
ReadTimeout time.Duration `default:"5s"`
}
DialTimeout time.Duration `default:"5s"`
Host string `default:"mongo:27017/gotraining" flag:"h"`
Insecure bool `flag:"i"`
}
Would produce the following flag output:
Useage of <app name>
-a --web_apihost string <0.0.0.0:3000> : The ip:port for the api endpoint.
--web_batchsize int <1000> : Represents number of items to move.
--web_readtimeout Duration <5s>
--dialtimeout Duration <5s>
-h --host string <mongo:27017/gotraining>
-i --insecure bool
The command line flag syntax assumes a regular or shorthand version based on the
type of dash used.
Regular versions
--flag=x
--flag x
Shorthand versions
-f=x
-f x
The API is a single call to `Process`
if err := envconfig.Process("CRUD", &cfg); err != nil {
log.Fatalf("main : Parsing Config : %v", err)
}
if err := flag.Process(&cfg); err != nil {
if err != flag.ErrHelp {
log.Fatalf("main : Parsing Command Line : %v", err)
}
return
}
This call should be done after the call to process the environmental variables.
*/
package flag
<file_sep>/cmd/sales-admin/main.go
// This program performs administrative tasks for the garage sale service.
//
// Run it with --cmd keygen or --cmd useradd
package main
import (
"context"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"fmt"
"log"
"os"
"time"
"github.com/ardanlabs/service/internal/platform/auth"
"github.com/ardanlabs/service/internal/platform/db"
"github.com/ardanlabs/service/internal/platform/flag"
"github.com/ardanlabs/service/internal/user"
"github.com/kelseyhightower/envconfig"
"github.com/pkg/errors"
)
func main() {
// =========================================================================
// Logging
log := log.New(os.Stdout, "sales-admin : ", log.LstdFlags|log.Lmicroseconds|log.Lshortfile)
// =========================================================================
// Configuration
var cfg struct {
CMD string `envconfig:"CMD"`
DB struct {
DialTimeout time.Duration `default:"5s" envconfig:"DIAL_TIMEOUT"`
Host string `default:"localhost:27017/gotraining" envconfig:"HOST"`
}
Auth struct {
PrivateKeyFile string `default:"private.pem" envconfig:"PRIVATE_KEY_FILE"`
}
User struct {
Email string
Password string
}
}
if err := envconfig.Process("SALES", &cfg); err != nil {
log.Fatalf("main : Parsing Config : %v", err)
}
if err := flag.Process(&cfg); err != nil {
if err != flag.ErrHelp {
log.Fatalf("main : Parsing Command Line : %v", err)
}
return // We displayed help.
}
var err error
switch cfg.CMD {
case "keygen":
err = keygen(cfg.Auth.PrivateKeyFile)
case "useradd":
err = useradd(cfg.DB.Host, cfg.DB.DialTimeout, cfg.User.Email, cfg.User.Password)
default:
err = errors.New("Must provide --cmd keygen or --cmd useradd")
}
if err != nil {
log.Fatal(err)
}
}
// keygen creates an x509 private key for signing auth tokens.
func keygen(path string) error {
key, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return errors.Wrap(err, "generating keys")
}
file, err := os.Create(path)
if err != nil {
return errors.Wrap(err, "creating private file")
}
block := pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: x509.MarshalPKCS1PrivateKey(key),
}
if err := pem.Encode(file, &block); err != nil {
return errors.Wrap(err, "encoding to private file")
}
if err := file.Close(); err != nil {
return errors.Wrap(err, "closing private file")
}
return nil
}
func useradd(dbHost string, dbTimeout time.Duration, email, pass string) error {
dbConn, err := db.New(dbHost, dbTimeout)
if err != nil {
return err
}
defer dbConn.Close()
if email == "" {
return errors.New("Must provide --user_email")
}
if pass == "" {
return errors.New("Must provide --user_password or set the env var SALES_USER_PASSWORD")
}
ctx := context.Background()
newU := user.NewUser{
Email: email,
Password: <PASSWORD>,
PasswordConfirm: <PASSWORD>,
Roles: []string{auth.RoleAdmin, auth.RoleUser},
}
usr, err := user.Create(ctx, dbConn, &newU, time.Now())
if err != nil {
return err
}
fmt.Printf("User created with id: %v\n", usr.ID.Hex())
return nil
}
<file_sep>/internal/platform/flag/flag.go
package flag
import (
"errors"
"fmt"
"os"
"reflect"
"strconv"
"strings"
"time"
)
// ErrHelp is provided to identify when help is being displayed.
var ErrHelp = errors.New("providing help")
// Process compares the specified command line arguments against the provided
// struct value and updates the fields that are identified.
func Process(v interface{}) error {
if len(os.Args) == 1 {
return nil
}
if os.Args[1] == "-h" || os.Args[1] == "--help" {
fmt.Print(display(os.Args[0], v))
return ErrHelp
}
args, err := parse("", v)
if err != nil {
return err
}
if err := apply(os.Args, args); err != nil {
return err
}
return nil
}
// display provides a pretty print display of the command line arguments.
func display(appName string, v interface{}) string {
/*
Current display format for a field.
Usage of <app name>
-short --long type <default> : description
-a --web_apihost string <0.0.0.0:3000> : The ip:port for the api endpoint.
*/
args, err := parse("", v)
if err != nil {
return fmt.Sprint("unable to display help", err)
}
var b strings.Builder
b.WriteString(fmt.Sprintf("\nUsage of %s\n", appName))
for _, arg := range args {
if arg.Short != "" {
b.WriteString(fmt.Sprintf("-%s ", arg.Short))
}
b.WriteString(fmt.Sprintf("--%s %s", arg.Long, arg.Type))
if arg.Default != "" {
b.WriteString(fmt.Sprintf(" <%s>", arg.Default))
}
if arg.Desc != "" {
b.WriteString(fmt.Sprintf(" : %s", arg.Desc))
}
b.WriteString("\n")
}
return b.String()
}
// configArg represents a single argument for a given field
// in the config structure.
type configArg struct {
Short string
Long string
Default string
Type string
Desc string
field reflect.Value
}
// parse will reflect over the provided struct value and build a
// collection of all possible config arguments.
func parse(parentField string, v interface{}) ([]configArg, error) {
// Reflect on the value to get started.
rawValue := reflect.ValueOf(v)
// If a parent field is provided we are recursing. We are now
// processing a struct within a struct. We need the parent struct
// name for namespacing.
if parentField != "" {
parentField = strings.ToLower(parentField) + "_"
}
// We need to check we have a pointer else we can't modify anything
// later. With the pointer, get the value that the pointer points to.
// With a struct, that means we are recursing and we need to assert to
// get the inner struct value to process it.
var val reflect.Value
switch rawValue.Kind() {
case reflect.Ptr:
val = rawValue.Elem()
if val.Kind() != reflect.Struct {
return nil, fmt.Errorf("incompatible type `%v` looking for a pointer", val.Kind())
}
case reflect.Struct:
var ok bool
if val, ok = v.(reflect.Value); !ok {
return nil, fmt.Errorf("internal recurse error")
}
default:
return nil, fmt.Errorf("incompatible type `%v`", rawValue.Kind())
}
var cfgArgs []configArg
// We need to iterate over the fields of the struct value we are processing.
// If the field is a struct then recurse to process its fields. If we have
// a field that is not a struct, pull the metadata. The `field` field is
// important because it is how we update things later.
for i := 0; i < val.NumField(); i++ {
field := val.Type().Field(i)
if field.Type.Kind() == reflect.Struct {
args, err := parse(parentField+field.Name, val.Field(i))
if err != nil {
return nil, err
}
cfgArgs = append(cfgArgs, args...)
continue
}
cfgArg := configArg{
Short: field.Tag.Get("flag"),
Long: parentField + strings.ToLower(field.Name),
Type: field.Type.Name(),
Default: field.Tag.Get("default"),
Desc: field.Tag.Get("flagdesc"),
field: val.Field(i),
}
cfgArgs = append(cfgArgs, cfgArg)
}
return cfgArgs, nil
}
// apply reads the command line arguments and applies any overrides to
// the provided struct value.
func apply(osArgs []string, cfgArgs []configArg) (err error) {
// There is so much room for panics here it hurts.
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("unhandled exception %v", r)
}
}()
lArgs := len(osArgs[1:])
for i := 1; i <= lArgs; i++ {
osArg := osArgs[i]
// Capture the next flag.
var flag string
switch {
case strings.HasPrefix(osArg, "-test"):
return nil
case strings.HasPrefix(osArg, "--"):
flag = osArg[2:]
case strings.HasPrefix(osArg, "-"):
flag = osArg[1:]
default:
return fmt.Errorf("invalid command line %q", osArg)
}
// Is this flag represented in the config struct.
var cfgArg configArg
for _, arg := range cfgArgs {
if arg.Short == flag || arg.Long == flag {
cfgArg = arg
break
}
}
// Did we find this flag represented in the struct?
if !cfgArg.field.IsValid() {
return fmt.Errorf("unknown flag %q", flag)
}
if cfgArg.Type == "bool" {
if err := update(cfgArg, ""); err != nil {
return err
}
continue
}
// Capture the value for this flag.
i++
value := osArgs[i]
// Process the struct value.
if err := update(cfgArg, value); err != nil {
return err
}
}
return nil
}
// update applies the value provided on the command line to the struct.
func update(cfgArg configArg, value string) error {
switch cfgArg.Type {
case "string":
cfgArg.field.SetString(value)
case "int":
i, err := strconv.Atoi(value)
if err != nil {
return fmt.Errorf("unable to convert value %q to int", value)
}
cfgArg.field.SetInt(int64(i))
case "Duration":
d, err := time.ParseDuration(value)
if err != nil {
return fmt.Errorf("unable to convert value %q to duration", value)
}
cfgArg.field.SetInt(int64(d))
case "bool":
cfgArg.field.SetBool(true)
default:
return fmt.Errorf("type not supported %q", cfgArg.Type)
}
return nil
}
<file_sep>/cmd/sales-api/handlers/routes.go
package handlers
import (
"log"
"net/http"
"os"
"github.com/ardanlabs/service/internal/mid"
"github.com/ardanlabs/service/internal/platform/auth"
"github.com/ardanlabs/service/internal/platform/db"
"github.com/ardanlabs/service/internal/platform/web"
)
// API returns a handler for a set of routes.
func API(shutdown chan os.Signal, log *log.Logger, masterDB *db.DB, authenticator *auth.Authenticator) http.Handler {
app := web.New(shutdown, log, mid.ErrorHandler, mid.Metrics, mid.RequestLogger)
// authmw is used for authentication/authorization middleware.
authmw := mid.Auth{
Authenticator: authenticator,
}
// Register health check endpoint. This route is not authenticated.
check := Check{
MasterDB: masterDB,
}
app.Handle("GET", "/v1/health", check.Health)
// Register user management and authentication endpoints.
u := User{
MasterDB: masterDB,
TokenGenerator: authenticator,
}
app.Handle("GET", "/v1/users", u.List, authmw.HasRole(auth.RoleAdmin), authmw.Authenticate)
app.Handle("POST", "/v1/users", u.Create, authmw.HasRole(auth.RoleAdmin), authmw.Authenticate)
app.Handle("GET", "/v1/users/:id", u.Retrieve, authmw.Authenticate)
app.Handle("PUT", "/v1/users/:id", u.Update, authmw.HasRole(auth.RoleAdmin), authmw.Authenticate)
app.Handle("DELETE", "/v1/users/:id", u.Delete, authmw.HasRole(auth.RoleAdmin), authmw.Authenticate)
// This route is not authenticated
app.Handle("GET", "/v1/users/token", u.Token)
// Register product and sale endpoints.
p := Product{
MasterDB: masterDB,
}
app.Handle("GET", "/v1/products", p.List, authmw.Authenticate)
app.Handle("POST", "/v1/products", p.Create, authmw.Authenticate)
app.Handle("GET", "/v1/products/:id", p.Retrieve, authmw.Authenticate)
app.Handle("PUT", "/v1/products/:id", p.Update, authmw.Authenticate)
app.Handle("DELETE", "/v1/products/:id", p.Delete, authmw.Authenticate)
return app
}
<file_sep>/cmd/sales-api/main.go
package main
import (
"context"
"crypto/rsa"
"encoding/json"
_ "expvar"
"io/ioutil"
"log"
"net/http"
_ "net/http/pprof"
"os"
"os/signal"
"syscall"
"time"
"github.com/ardanlabs/service/cmd/sales-api/handlers"
"github.com/ardanlabs/service/internal/platform/auth"
"github.com/ardanlabs/service/internal/platform/db"
"github.com/ardanlabs/service/internal/platform/flag"
itrace "github.com/ardanlabs/service/internal/platform/trace"
jwt "github.com/dgrijalva/jwt-go"
"github.com/kelseyhightower/envconfig"
"go.opencensus.io/trace"
)
/*
ZipKin: http://localhost:9411
AddLoad: hey -m GET -c 10 -n 10000 "http://localhost:3000/v1/users"
expvarmon -ports=":3001" -endpoint="/metrics" -vars="requests,goroutines,errors,mem:memstats.Alloc"
*/
/*
Need to figure out timeouts for http service.
You might want to reset your DB_HOST env var during test tear down.
Service should start even without a DB running yet.
symbols in profiles: https://github.com/golang/go/issues/23376 / https://github.com/google/pprof/pull/366
*/
// build is the git version of this program. It is set using build flags in the makefile.
var build = "develop"
func main() {
// =========================================================================
// Logging
log := log.New(os.Stdout, "SALES : ", log.LstdFlags|log.Lmicroseconds|log.Lshortfile)
// =========================================================================
// Configuration
var cfg struct {
Web struct {
APIHost string `default:"0.0.0.0:3000" envconfig:"API_HOST"`
DebugHost string `default:"0.0.0.0:4000" envconfig:"DEBUG_HOST"`
ReadTimeout time.Duration `default:"5s" envconfig:"READ_TIMEOUT"`
WriteTimeout time.Duration `default:"5s" envconfig:"WRITE_TIMEOUT"`
ShutdownTimeout time.Duration `default:"5s" envconfig:"SHUTDOWN_TIMEOUT"`
}
DB struct {
DialTimeout time.Duration `default:"5s" envconfig:"DIAL_TIMEOUT"`
Host string `default:"mongo:27017/gotraining" envconfig:"HOST"`
}
Trace struct {
Host string `default:"http://tracer:3002/v1/publish" envconfig:"HOST"`
BatchSize int `default:"1000" envconfig:"BATCH_SIZE"`
SendInterval time.Duration `default:"15s" envconfig:"SEND_INTERVAL"`
SendTimeout time.Duration `default:"500ms" envconfig:"SEND_TIMEOUT"`
}
Auth struct {
KeyID string `envconfig:"KEY_ID"`
PrivateKeyFile string `default:"private.pem" envconfig:"PRIVATE_KEY_FILE"`
Algorithm string `default:"RS256" envconfig:"ALGORITHM"`
}
}
if err := envconfig.Process("SALES", &cfg); err != nil {
log.Fatalf("main : Parsing Config : %v", err)
}
if err := flag.Process(&cfg); err != nil {
if err != flag.ErrHelp {
log.Fatalf("main : Parsing Command Line : %v", err)
}
return // We displayed help.
}
// =========================================================================
// App Starting
log.Printf("main : Started : Application Initializing version %q", build)
defer log.Println("main : Completed")
cfgJSON, err := json.MarshalIndent(cfg, "", " ")
if err != nil {
log.Fatalf("main : Marshalling Config to JSON : %v", err)
}
// TODO: Validate what is being written to the logs. We don't
// want to leak credentials or anything that can be a security risk.
log.Printf("main : Config : %v\n", string(cfgJSON))
// =========================================================================
// Find auth keys
keyContents, err := ioutil.ReadFile(cfg.Auth.PrivateKeyFile)
if err != nil {
log.Fatalf("main : Reading auth private key : %v", err)
}
key, err := jwt.ParseRSAPrivateKeyFromPEM(keyContents)
if err != nil {
log.Fatalf("main : Parsing auth private key : %v", err)
}
publicKeyLookup := auth.NewSingleKeyFunc(cfg.Auth.KeyID, key.Public().(*rsa.PublicKey))
authenticator, err := auth.NewAuthenticator(key, cfg.Auth.KeyID, cfg.Auth.Algorithm, publicKeyLookup)
if err != nil {
log.Fatalf("main : Constructing authenticator : %v", err)
}
// =========================================================================
// Start Mongo
log.Println("main : Started : Initialize Mongo")
masterDB, err := db.New(cfg.DB.Host, cfg.DB.DialTimeout)
if err != nil {
log.Fatalf("main : Register DB : %v", err)
}
defer masterDB.Close()
// =========================================================================
// Start Tracing Support
logger := func(format string, v ...interface{}) {
log.Printf(format, v...)
}
log.Printf("main : Tracing Started : %s", cfg.Trace.Host)
exporter, err := itrace.NewExporter(logger, cfg.Trace.Host, cfg.Trace.BatchSize, cfg.Trace.SendInterval, cfg.Trace.SendTimeout)
if err != nil {
log.Fatalf("main : RegiTracingster : ERROR : %v", err)
}
defer func() {
log.Printf("main : Tracing Stopping : %s", cfg.Trace.Host)
batch, err := exporter.Close()
if err != nil {
log.Printf("main : Tracing Stopped : ERROR : Batch[%d] : %v", batch, err)
} else {
log.Printf("main : Tracing Stopped : Flushed Batch[%d]", batch)
}
}()
trace.RegisterExporter(exporter)
trace.ApplyConfig(trace.Config{DefaultSampler: trace.AlwaysSample()})
// =========================================================================
// Start Debug Service
// /debug/vars - Added to the default mux by the expvars package.
// /debug/pprof - Added to the default mux by the net/http/pprof package.
debug := http.Server{
Addr: cfg.Web.DebugHost,
Handler: http.DefaultServeMux,
ReadTimeout: cfg.Web.ReadTimeout,
WriteTimeout: cfg.Web.WriteTimeout,
MaxHeaderBytes: 1 << 20,
}
// Not concerned with shutting this down when the
// application is being shutdown.
go func() {
log.Printf("main : Debug Listening %s", cfg.Web.DebugHost)
log.Printf("main : Debug Listener closed : %v", debug.ListenAndServe())
}()
// =========================================================================
// Start API Service
// Make a channel to listen for an interrupt or terminate signal from the OS.
// Use a buffered channel because the signal package requires it.
shutdown := make(chan os.Signal, 1)
signal.Notify(shutdown, os.Interrupt, syscall.SIGTERM)
api := http.Server{
Addr: cfg.Web.APIHost,
Handler: handlers.API(shutdown, log, masterDB, authenticator),
ReadTimeout: cfg.Web.ReadTimeout,
WriteTimeout: cfg.Web.WriteTimeout,
MaxHeaderBytes: 1 << 20,
}
// Make a channel to listen for errors coming from the listener. Use a
// buffered channel so the goroutine can exit if we don't collect this error.
serverErrors := make(chan error, 1)
// Start the service listening for requests.
go func() {
log.Printf("main : API Listening %s", cfg.Web.APIHost)
serverErrors <- api.ListenAndServe()
}()
// =========================================================================
// Shutdown
// Blocking main and waiting for shutdown.
select {
case err := <-serverErrors:
log.Fatalf("main : Error starting server: %v", err)
case sig := <-shutdown:
log.Printf("main : %v : Start shutdown..", sig)
// Create context for Shutdown call.
ctx, cancel := context.WithTimeout(context.Background(), cfg.Web.ShutdownTimeout)
defer cancel()
// Asking listener to shutdown and load shed.
err := api.Shutdown(ctx)
if err != nil {
log.Printf("main : Graceful shutdown did not complete in %v : %v", cfg.Web.ShutdownTimeout, err)
err = api.Close()
}
// Log the status of this shutdown.
switch {
case sig == syscall.SIGSTOP:
log.Fatal("main : Integrity issue caused shutdown")
case err != nil:
log.Fatalf("main : Could not stop server gracefully : %v", err)
}
}
}
<file_sep>/cmd/sales-api/tests/tests_test.go
package tests
import (
"crypto/rand"
"crypto/rsa"
"os"
"testing"
"time"
"github.com/ardanlabs/service/cmd/sales-api/handlers"
"github.com/ardanlabs/service/internal/platform/auth"
"github.com/ardanlabs/service/internal/platform/tests"
"github.com/ardanlabs/service/internal/platform/web"
"github.com/ardanlabs/service/internal/user"
)
var a *web.App
var test *tests.Test
// Information about the users we have created for testing.
var adminAuthorization string
var adminID string
var userAuthorization string
var userID string
// TestMain is the entry point for testing.
func TestMain(m *testing.M) {
os.Exit(testMain(m))
}
func testMain(m *testing.M) int {
test = tests.New()
defer test.TearDown()
// Create RSA keys to enable authentication in our service.
key, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
panic(err)
}
kid := "4754d86b-7a6d-4df5-9c65-224741361492"
kf := auth.NewSingleKeyFunc(kid, key.Public().(*rsa.PublicKey))
authenticator, err := auth.NewAuthenticator(key, kid, "RS256", kf)
if err != nil {
panic(err)
}
shutdown := make(chan os.Signal, 1)
a = handlers.API(shutdown, test.Log, test.MasterDB, authenticator).(*web.App)
// Create an admin user directly with our business logic. This creates an
// initial user that we will use for admin validated endpoints.
nu := user.NewUser{
Email: "<EMAIL>",
Name: "<NAME>",
Roles: []string{auth.RoleAdmin, auth.RoleUser},
Password: "<PASSWORD>",
PasswordConfirm: "<PASSWORD>",
}
admin, err := user.Create(tests.Context(), test.MasterDB, &nu, time.Now())
if err != nil {
panic(err)
}
adminID = admin.ID.Hex()
tkn, err := user.Authenticate(tests.Context(), test.MasterDB, authenticator, time.Now(), nu.Email, nu.Password)
if err != nil {
panic(err)
}
adminAuthorization = "Bearer " + tkn.Token
// Create a regular user to use when calling regular validated endpoints.
nu = user.NewUser{
Email: "<EMAIL>",
Name: "<NAME>",
Roles: []string{auth.RoleUser},
Password: "<PASSWORD>",
PasswordConfirm: "<PASSWORD>",
}
usr, err := user.Create(tests.Context(), test.MasterDB, &nu, time.Now())
if err != nil {
panic(err)
}
userID = usr.ID.Hex()
tkn, err = user.Authenticate(tests.Context(), test.MasterDB, authenticator, time.Now(), nu.Email, nu.Password)
if err != nil {
panic(err)
}
userAuthorization = "Bearer " + tkn.Token
return m.Run()
}
|
d17019f54e449126e59b432d6a549f3195e5028d
|
[
"YAML",
"Markdown",
"Makefile",
"Go",
"Go Module"
] | 38
|
Go
|
netspencer/service
|
3a1960d7dc544e4545f79b207ef6518c32e7ed8f
|
f3ca0323848c8733adb4836f0fda7388df1b5c6b
|
refs/heads/master
|
<repo_name>0trebor0/luigi<file_sep>/lib/packetize.js
var Readable = require('stream').Readable,
util = require('util'),
_ = require('lodash'),
EventEmitter = require('events').EventEmitter;
// I hate node streams sometimes
var Packetize = module.exports = function Packetize(socket) {
var self = this;
Readable.call(this);
var buffer = this.buffer = [];
var socketBuffer = this.socketBuffer = new Buffer(0);
var ee = this.ee = new EventEmitter;
socket.on('data', function bufferize(chunk) {
if (self.socketBuffer.length)
chunk = Buffer.concat([self.socketBuffer, chunk]);
self.socketBuffer = self.socketBuffer = new Buffer(0);
if (!chunk.length)
throw new Error;
var length = chunk.readUIntBE(2, 3),
payload = chunk.slice(7);
if (payload.length < length)
self.socketBuffer = chunk;
else if (payload.length == length) {
self.buffer.push(chunk);
ee.emit('data');
}
else if (payload.length > length) {
self.buffer.push(chunk.slice(0, 7 + length));
ee.emit('data');
bufferize(chunk.slice(7 + length));
}
});
};
util.inherits(Packetize, Readable);
Packetize.prototype._read = function() {
var self = this;
if (this.ee.listeners('data').length)
return;
this.ee.on('data', function() {
self.buffer.forEach(function(packet) {
self.push(packet);
});
self.buffer = [];
});
};
<file_sep>/lib/middleware.js
var Transform = require('stream').Transform,
util = require('util'),
fs = require('fs'),
crypto = require('crypto'),
scrambler = require('./scrambler');
var dump = [14102, 24104, 14113, 24101, 24113, 25003];
var Middleware = module.exports = function Middleware() {
Transform.call(this);
this.buffer = [];
this.o = 0;
this.startDecipherStreams('fhsd6f86f67rt8fw78fw789we78r9789wer6renonce');
this.events = {
10101: this.login,
20000: this.encryption,
14102: this.endClientTurn
};
};
util.inherits(Middleware, Transform);
Middleware.prototype.startDecipherStreams = function(key) {
if (key)
this.key = key;
this.decipherStreamClient = crypto.createDecipheriv("rc4", this.key, '');
this.decipherStreamServer = crypto.createDecipheriv("rc4", this.key, '');
this.decipherStreamClient.update(
new Array(this.key.length + 1).join('a') // skips key.length bytes from decipher
);
this.decipherStreamServer.update(
new Array(this.key.length + 1).join('a') // skips key.length bytes from decipher
);
};
Middleware.prototype.decipherPayload = function(id, payload) {
var decipherStream = (id < 20000) ? this.decipherStreamClient : this.decipherStreamServer;
return decipherStream.update(payload);
};
Middleware.prototype.dispatch = function(id, payload) {
if (!this.events[id])
return;
return this.events[id].call(this, id, payload);
};
Middleware.prototype.login = function(id, payload) {
this.seed = payload.readInt32BE(payload.length - 13);
if (this.serverMid)
this.serverMid.seed = this.seed;
};
Middleware.prototype.hookSeed = function(m) {
this.serverMid = m;
};
Middleware.prototype.hookKey = function(m) {
this.clientMid = m;
};
Middleware.prototype.encryption = function(id, payload) {
this.serverRandom = payload.slice(4, payload.length - 4);
var scramblerStream = scrambler(this.seed),
nonce = new Buffer(this.serverRandom),
hByte;
for (var i = 0; i < 100; i++)
hByte = scramblerStream.next().value;
for (var x = 0; x < nonce.length; x++) {
var n = scramblerStream.next().value,
byteKey = n & hByte;
nonce[x] = nonce[x] ^ byteKey;
}
var key = Buffer.concat([
new Buffer('fhsd6f86f67rt8fw78fw789we78r9789wer6re'),
nonce
]);
this.startDecipherStreams(key);
if (this.clientMid)
this.clientMid.startDecipherStreams(key);
};
Middleware.prototype.endClientTurn = function(id, payload) {
var newPayload = new Buffer(payload);
for (var i = 4; i < 8; i++)
newPayload[i] = 0;
};
Middleware.prototype._transform = function(data, encoding, callback) {
var id = data.readUInt16BE(0),
payload = data.slice(7), // id (2) + length (3) + <unknown> (2)
payloadLength = data.readUIntBE(2, 3),
interesting = id !== 14102 && id !== 20108 && id !== 24715 && id !== 10108;
var decryptedPayload = this.decipherPayload(id, payload);
var newPayload = this.dispatch(id, decryptedPayload);
console.log(id);
if (~dump.indexOf(id)) {
console.log('[+] Dumping %d bytes... (%d)', data.readUIntBE(2, 3), decryptedPayload.length);
console.log(decryptedPayload);
fs.writeFileSync(
'dumps/' + id.toString(),
Buffer.concat([data.slice(0, 7), decryptedPayload])
);
console.log('[+] Done');
}
if (newPayload) {
var keyByte;
for (var i = 0; i < payloadLength; i++) {
keyByte = payload[i] ^ decryptedPayload[i]; // this will get the original rc4 byte used in the keystream
payload[i] = newPayload[i] ^ keyByte; // now we re-encode the new payload
}
data = Buffer.concat([
data.slice(0, 7),
payload
]);
}
callback(null, data);
};
<file_sep>/lib/scrambler.js
// Pretty much copied from https://github.com/clanner/cocdp/wiki/Protocol, thank you clanner!
var Long = require('long');
Long.prototype.rshift = function(n) { // for whatevs reason, this is _not_ equal to the normal right shift
var highbits = 0,
num = this.getLowBitsUnsigned();
if (num & Math.pow(2, 31))
highbits = (Math.pow(2, n)-1) * Math.pow(2, (32-n));
var pow = Math.pow(2, n),
lowbits = Math.floor(num/pow);
return new Long(lowbits|highbits, 0, true);
};
function mixbuffer(buffer) {
var i = 0,
j = 0, v4, v6;
while (i < 624) {
i++;
// v4 = (buffer[i % 624] & 0x7FFFFFFF) + (buffer[j] & 0x80000000);
v4 = buffer[i % 624].and(0x7FFFFFFF).add(buffer[j].and(0x80000000));
// v6 = (v4 >> 1) ^ buffer[(i+396) % 624];
v6 = v4.rshift(1).xor(buffer[(i+396) % 624]);
if (v4.and(1).getLowBits())
v6 = v6.xor(0x9908B0DF);
buffer[j] = v6;
j++;
}
}
module.exports = function *scrambler(seed) {
var buffer = [],
bufferIndex = 0, currentValue;
seed = Long.fromInt(seed);
// seedbuffer
for (var i = 0; i < 624; i++) {
buffer.push(seed);
seed = new Long(1812433253).multiply( seed.xor( seed.rshift(30) ).add(1) );
seed.high = 0;
}
while (true) {
if (!bufferIndex)
mixbuffer(buffer);
currentValue = buffer[bufferIndex];
bufferIndex = (bufferIndex + 1) % 624;
// currentValue ^= (currentValue >> 11) ^ ((currentValue ^ (currentValue >> 11)) << 7) & 0x9D2C5680;
currentValue = currentValue.xor( currentValue.rshift(11) )
.xor( currentValue.xor( currentValue.rshift(11) )
.shiftLeft(7)
.and( 0x9D2C5680 ));
currentValue = currentValue.xor( currentValue.shiftLeft(15).and( 0xEFC60000 ) )
.rshift(18)
.xor(currentValue)
.xor( currentValue.shiftLeft(15).and(0xEFC60000) );
// currentValue = ((currentValue ^ (currentValue << 15) & 0xEFC60000) >> 18) ^
// currentValue ^ (currentValue << 15) & 0xEFC60000;
// if (currentValue < 0)
// currentValue = ~currentValue + 1;
yield currentValue.getLowBitsUnsigned() % 256;
}
};
<file_sep>/README.md
# luigi
--
A Node.js COC proxy for fun and profit
Development is **HIGHLY** in early stages so expect bugs, debug messages and shit like that.
|
fe06db4712f0c0f776eb522aa4e5739c9e116ff6
|
[
"JavaScript",
"Markdown"
] | 4
|
JavaScript
|
0trebor0/luigi
|
dc724619f605d6cf29d9c2250fecc0b47332ec31
|
eabbb9f242ea64b1727a226b15ab55e5dc4235e4
|
refs/heads/master
|
<repo_name>ZaifSenpai/Ass-Font-Changer<file_sep>/README.md
# Ass-Font-Changer
Font changer for ASS subtitle files. C++ code which simply reads file, do some string manipulations, write result to same file.
# Usage
This program accepts command line arguments. No, one or two arguments for the execution.
No argument will mean to use file 'subtitle.ass' and change the font to Arial. Like:
changeAssFont
1st argument is file name, the font of that subtitle will be set to Arial. Like:
changeAssFont english.ass
2.d argument is the font name to be set to/ Example
changeAssFont english.ass Algerian
# Example of changes

# Before:
```
[Script Info]...
[V4+ Styles]
Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding
Style: Default,Arial,20,&H00FFFFFF,&H000000FF,&H00000000,&H00000000,0,0,0,0,100,100,0,0,1,2,2,2,10,10,10,1
Style: EpDBZ,Arial,36,&H00D5DDDC,&H000000FF,&HEB000000,&H55000000,-1,0,0,0,100,100,0,0,1,1,0,2,10,10,10,1
Style: GolpeDown,20 CENTS MARKER,42,&H00C5F7F0,&H00040405,&H001104D9,&H00000000,-1,-1,0,0,100,100,0,0,1,2,0,2,10,10,10,1
Style: GolpeUp,Myriad Pro Cond,34,&H00FFFFFF,&H00040405,&H00801722,&H00000000,-1,-1,0,0,100,100,0,0,1,2,0,8,10,10,10,1
Style: Karaoke,Another,28,&H00169F19,&H000000FF,&H00FFFFFF,&H00000000,0,0,0,0,100,100,0,0,1,2,1,8,10,10,4,1
Style: Karaoke02,Kronika,28,&H00F6F5F3,&H00000000,&H00000000,&H00000000,-1,0,0,0,100,100,0,0,1,0,0,2,10,10,5,1
Style: Karaoke03,20 CENTS MARKER,34,&H00C3EEBB,&H000000FF,&H000B0909,&H00000000,-1,0,0,0,100,100,0,0,1,3,0,7,10,10,5,1
Style: Karaoke04,GosmickSans,30,&H00FFFFFF,&H000000FF,&H000B0909,&H00000000,-1,0,0,0,100,100,0,0,1,1,0,3,10,10,5,1
Style: narrador,Monotype Corsiva,34,&H00FFFFFF,&H000000FF,&H00171D04,&H00000000,-1,0,0,0,100,100,0,0,1,2,0,2,10,10,5,1
Style: Nota,GosmickSans,28,&H00FFFFFF,&H000000FF,&H003E529A,&H00000000,-1,0,0,0,100,100,0,0,1,0,0,8,10,10,10,1
Style: padrao,Myriad Pro Cond,39,&H00FFFFFF,&H00000000,&H64000000,&H00000041,-1,0,0,0,100,100,0,0,1,2,0,2,10,10,10,1
Style: preview,Myriad Pro Cond,39,&H00FFFFFF,&H00040405,&H00376530,&H00000000,-1,-1,0,0,100,100,0,0,1,2,0,2,10,10,10,1
Style: Titulo,Arial,28,&H00BDB8B8,&H00040405,&HD3040405,&H78000000,-1,0,0,0,100,100,0,0,1,0,0,2,10,10,10,1
[Events]...
```
# After using Ass Font Changer:
```
[Script Info]...
Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding
Style: Default,Arial,20,&H00FFFFFF,&H000000FF,&H00000000,&H00000000,0,0,0,0,100,100,0,0,1,2,2,2,10,10,10,1
Style: EpDBZ,Arial,36,&H00D5DDDC,&H000000FF,&HEB000000,&H55000000,-1,0,0,0,100,100,0,0,1,1,0,2,10,10,10,1
Style: GolpeDown,Arial,42,&H00C5F7F0,&H00040405,&H001104D9,&H00000000,-1,-1,0,0,100,100,0,0,1,2,0,2,10,10,10,1
Style: GolpeUp,Arial,34,&H00FFFFFF,&H00040405,&H00801722,&H00000000,-1,-1,0,0,100,100,0,0,1,2,0,8,10,10,10,1
Style: Karaoke,Arial,28,&H00169F19,&H000000FF,&H00FFFFFF,&H00000000,0,0,0,0,100,100,0,0,1,2,1,8,10,10,4,1
Style: Karaoke02,Arial,28,&H00F6F5F3,&H00000000,&H00000000,&H00000000,-1,0,0,0,100,100,0,0,1,0,0,2,10,10,5,1
Style: Karaoke03,Arial,34,&H00C3EEBB,&H000000FF,&H000B0909,&H00000000,-1,0,0,0,100,100,0,0,1,3,0,7,10,10,5,1
Style: Karaoke04,Arial,30,&H00FFFFFF,&H000000FF,&H000B0909,&H00000000,-1,0,0,0,100,100,0,0,1,1,0,3,10,10,5,1
Style: narrador,Arial,34,&H00FFFFFF,&H000000FF,&H00171D04,&H00000000,-1,0,0,0,100,100,0,0,1,2,0,2,10,10,5,1
Style: Nota,Arial,28,&H00FFFFFF,&H000000FF,&H003E529A,&H00000000,-1,0,0,0,100,100,0,0,1,0,0,8,10,10,10,1
Style: padrao,Arial,39,&H00FFFFFF,&H00000000,&H64000000,&H00000041,-1,0,0,0,100,100,0,0,1,2,0,2,10,10,10,1
Style: preview,Arial,39,&H00FFFFFF,&H00040405,&H00376530,&H00000000,-1,-1,0,0,100,100,0,0,1,2,0,2,10,10,10,1
Style: Titulo,Arial,28,&H00BDB8B8,&H00040405,&HD3040405,&H78000000,-1,0,0,0,100,100,0,0,1,0,0,2,10,10,10,1
[Events]...
```
<file_sep>/changeAssFont.cpp
#include <iostream>
#include <vector>
#include <fstream>
#include <algorithm>
#include <string.h>
using namespace std;
int getFontPlace(string line);
int main(int argc, char *argv[]) {
int start, end, i, j, place, _place = 0, oldFontLength = 0, oldFontStart = 0, sizeB4Font = 0;
bool inc = false, startRec = false;
string filename = "", dummy = "", fontToAdd = "";
vector<string> filecontent;
if (argc > 1) filename = argv[1];
else filename = "subtitle.ass";
// Reading whole file
cout << "Reading from file...\n";
ifstream filein(filename);
if (filein == NULL) {
cout << "Error opening file " << filename << endl;
exit(1);
}
for (string ch; getline(filein, ch); filecontent.push_back(ch));
filein.close();
cout << "Looking for Styles...\n";
for (i = 0; i < filecontent.size(); i++) {
if (filecontent[i].find("[V4+ Styles]") != string::npos) {
start = i+1;
}
if (filecontent[i].find("[Events]") != string::npos) {
end = i-2;
}
}
place = getFontPlace(filecontent[start]);
// So "Fontname" is now written after Place`th coma
if (argc == 3) fontToAdd = argv[2];
else fontToAdd = "Arial";
// Doing the work now
cout << "Computing...\n";
for (i = start+1; i <= end; i++) {
for (j = 0; j < filecontent[i].length(); j++) {
if (filecontent[i][j] == ',' && inc == true) break;
if (filecontent[i][j] == ',' && inc == false) {
_place++;
inc = true;
startRec = true;
}
if (inc == true && startRec == true) {
oldFontLength++;
}
}
oldFontStart = j - oldFontLength + 1;
oldFontLength--;
dummy = filecontent[i].substr(0, oldFontStart);
sizeB4Font = dummy.length();
dummy = dummy + fontToAdd;
dummy = dummy + filecontent[i].substr(oldFontStart + oldFontLength, filecontent[i].length() - sizeB4Font);
filecontent[i] = dummy;
// Resetting variables for next iteration
oldFontLength = 0;
inc = false;
startRec = false;
_place = 0;
dummy = "";
}
// Writting output to file
cout << "Writting output to "<< filename << " ...\n";
ofstream fileout(filename);
for (i = 0; i < filecontent.size(); i++) fileout << filecontent[i] << endl;
fileout.close();
cout << "Done!\n\n";
return 0;
}
int getFontPlace(string line) {
int i, pos = 0;
for (i = 0; i < line.length(); i++) {
if (line[i] == ',') pos++;
if (!strcmp(line.substr(i, 8).c_str(), "Fontname")) break;
}
return pos;
}
|
059cb85cf89f88102ccc6aff6ee4bc7512d15904
|
[
"Markdown",
"C++"
] | 2
|
Markdown
|
ZaifSenpai/Ass-Font-Changer
|
ee7ead376eee11dcd3148197d61673a5da7c0b4e
|
8129f20e058ea35cec3a19fd1f3329a4a1ad0ab8
|
refs/heads/master
|
<repo_name>hongkai-dai/drake<file_sep>/tools/wheel/image/dependencies/projects/clp.cmake
ExternalProject_Add(clp
URL ${clp_url}
URL_MD5 ${clp_md5}
DOWNLOAD_NAME ${clp_dlname}
DEPENDS coinutils
${COMMON_EP_ARGS}
BUILD_IN_SOURCE 1
CONFIGURE_COMMAND ./configure
--prefix=${CMAKE_INSTALL_PREFIX}
--disable-shared
CFLAGS=-fPIC
CXXFLAGS=-fPIC
BUILD_COMMAND make
INSTALL_COMMAND make install
)
extract_license(clp
Clp/LICENSE
)
<file_sep>/bindings/pydrake/geometry/test/optimization_test.py
import pydrake.geometry.optimization as mut
import os.path
import unittest
import numpy as np
from pydrake.common import RandomGenerator, temp_directory
from pydrake.common.test_utilities.deprecation import catch_drake_warnings
from pydrake.common.test_utilities.pickle_compare import assert_pickle
from pydrake.geometry import (
Box, Capsule, Cylinder, Ellipsoid, FramePoseVector, GeometryFrame,
GeometryInstance, ProximityProperties, SceneGraph, Sphere,
)
from pydrake.math import RigidTransform
from pydrake.multibody.inverse_kinematics import InverseKinematics
from pydrake.multibody.parsing import Parser
from pydrake.multibody.plant import AddMultibodyPlantSceneGraph
from pydrake.systems.framework import DiagramBuilder
from pydrake.solvers import (
Binding, ClpSolver, Constraint, Cost, MathematicalProgram,
MathematicalProgramResult, SolverOptions,
)
from pydrake.symbolic import Variable
class TestGeometryOptimization(unittest.TestCase):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.A = np.eye(3)
self.b = [1.0, 1.0, 1.0]
self.prog = MathematicalProgram()
self.x = self.prog.NewContinuousVariables(3, "x")
self.t = self.prog.NewContinuousVariables(1, "t")[0]
self.Ay = np.array([[1., 0.], [0., 1.], [1., 0.]])
self.by = np.ones(3)
self.cz = np.ones(2)
self.dz = 1.
self.y = self.prog.NewContinuousVariables(2, "y")
self.z = self.prog.NewContinuousVariables(2, "z")
def test_point_convex_set(self):
mut.Point()
p = np.array([11.1, 12.2, 13.3])
point = mut.Point(p)
self.assertFalse(point.IsEmpty())
self.assertEqual(point.ambient_dimension(), 3)
np.testing.assert_array_equal(point.x(), p)
np.testing.assert_array_equal(point.MaybeGetPoint(), p)
np.testing.assert_array_equal(point.MaybeGetFeasiblePoint(), p)
point.set_x(x=2*p)
np.testing.assert_array_equal(point.x(), 2*p)
point.set_x(x=p)
assert_pickle(self, point, lambda S: S.x())
# TODO(SeanCurtis-TRI): This doesn't test the constructor that
# builds from shape.
def test_h_polyhedron(self):
mut.HPolyhedron()
hpoly = mut.HPolyhedron(A=self.A, b=self.b)
self.assertEqual(hpoly.ambient_dimension(), 3)
np.testing.assert_array_equal(hpoly.A(), self.A)
np.testing.assert_array_equal(hpoly.b(), self.b)
self.assertTrue(hpoly.PointInSet(x=[0, 0, 0], tol=0.0))
self.assertFalse(hpoly.IsEmpty())
self.assertFalse(hpoly.MaybeGetFeasiblePoint() is None)
self.assertTrue(hpoly.PointInSet(hpoly.MaybeGetFeasiblePoint()))
self.assertFalse(hpoly.IsBounded())
new_vars, new_constraints = hpoly.AddPointInSetConstraints(
self.prog, self.x)
self.assertEqual(new_vars.size, 0)
constraints = hpoly.AddPointInNonnegativeScalingConstraints(
prog=self.prog, x=self.x, t=self.t)
self.assertGreaterEqual(len(constraints), 2)
self.assertIsInstance(constraints[0], Binding[Constraint])
constraints = hpoly.AddPointInNonnegativeScalingConstraints(
prog=self.prog, A=self.Ay, b=self.by, c=self.cz, d=self.dz,
x=self.y, t=self.z)
self.assertGreaterEqual(len(constraints), 2)
self.assertIsInstance(constraints[0], Binding[Constraint])
with self.assertRaisesRegex(
RuntimeError, ".*not implemented yet for HPolyhedron.*"):
hpoly.ToShapeWithPose()
assert_pickle(self, hpoly, lambda S: np.vstack((S.A(), S.b())))
h_box = mut.HPolyhedron.MakeBox(
lb=[-1, -1, -1], ub=[1, 1, 1])
self.assertTrue(h_box.IntersectsWith(hpoly))
h_unit_box = mut.HPolyhedron.MakeUnitBox(dim=3)
np.testing.assert_array_equal(h_box.A(), h_unit_box.A())
np.testing.assert_array_equal(h_box.b(), h_unit_box.b())
A_l1 = np.array([[1, 1, 1],
[-1, 1, 1],
[1, -1, 1],
[-1, -1, 1],
[1, 1, -1],
[-1, 1, -1],
[1, -1, -1],
[-1, -1, -1]])
b_l1 = np.ones(8)
h_l1_ball = mut.HPolyhedron.MakeL1Ball(dim=3)
np.testing.assert_array_equal(A_l1, h_l1_ball.A())
np.testing.assert_array_equal(b_l1, h_l1_ball.b())
self.assertIsInstance(
h_box.MaximumVolumeInscribedEllipsoid(),
mut.Hyperellipsoid)
np.testing.assert_array_almost_equal(
h_box.ChebyshevCenter(), [0, 0, 0])
h_scaled = h_box.Scale(scale=2.0, center=[1, 2, 3])
self.assertIsInstance(h_scaled, mut.HPolyhedron)
h_scaled = h_box.Scale(scale=2.0)
self.assertIsInstance(h_scaled, mut.HPolyhedron)
h2 = h_box.CartesianProduct(other=h_unit_box)
self.assertIsInstance(h2, mut.HPolyhedron)
self.assertEqual(h2.ambient_dimension(), 6)
h3 = h_box.CartesianPower(n=3)
self.assertIsInstance(h3, mut.HPolyhedron)
self.assertEqual(h3.ambient_dimension(), 9)
h4 = h_box.Intersection(other=h_unit_box)
self.assertIsInstance(h4, mut.HPolyhedron)
self.assertEqual(h4.ambient_dimension(), 3)
h5 = h_box.PontryaginDifference(other=h_unit_box)
self.assertIsInstance(h5, mut.HPolyhedron)
np.testing.assert_array_equal(h5.A(), h_box.A())
np.testing.assert_array_equal(h5.b(), np.zeros(6))
generator = RandomGenerator()
sample = h_box.UniformSample(generator=generator)
self.assertEqual(sample.shape, (3,))
self.assertEqual(
h_box.UniformSample(generator=generator,
previous_sample=sample).shape, (3, ))
h_half_box = mut.HPolyhedron.MakeBox(
lb=[-0.5, -0.5, -0.5], ub=[0.5, 0.5, 0.5])
self.assertTrue(h_half_box.ContainedIn
(other=h_unit_box, tol=1E-9))
h_half_box2 = h_half_box.Intersection(
other=h_unit_box, check_for_redundancy=True, tol=1E-9)
self.assertIsInstance(h_half_box2, mut.HPolyhedron)
self.assertEqual(h_half_box2.ambient_dimension(), 3)
np.testing.assert_array_almost_equal(
h_half_box2.A(), h_half_box.A())
np.testing.assert_array_almost_equal(
h_half_box2.b(), h_half_box.b())
# Intersection of 1/2*unit_box and unit_box and reducing the redundant
# inequalities should result in the 1/2*unit_box.
h_half_box_intersect_unit_box = h_half_box.Intersection(
other=h_unit_box,
check_for_redundancy=False)
# Check that the ReduceInequalities binding works.
redundant_indices = h_half_box_intersect_unit_box.FindRedundant(
tol=1E-9)
# Check FindRedundant with default tol.
h_half_box_intersect_unit_box.FindRedundant()
h_half_box3 = h_half_box_intersect_unit_box.ReduceInequalities(
tol=1E-9)
# This polyhedron is intentionally constructed to be an empty set.
A_empty = np.vstack([np.eye(3), -np.eye(3)])
b_empty = -np.ones(6)
h_empty = mut.HPolyhedron(A_empty, b_empty)
self.assertTrue(h_empty.IsEmpty())
self.assertFalse(h_l1_ball.IsEmpty())
vpoly = mut.VPolytope(np.array(
[[0., 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]))
hpoly = mut.HPolyhedron(vpoly=vpoly)
self.assertEqual(hpoly.ambient_dimension(), 3)
self.assertEqual(hpoly.A().shape, (4, 3))
def test_hyper_ellipsoid(self):
mut.Hyperellipsoid()
ellipsoid = mut.Hyperellipsoid(A=self.A, center=self.b)
self.assertEqual(ellipsoid.ambient_dimension(), 3)
self.assertFalse(ellipsoid.IsEmpty())
self.assertFalse(ellipsoid.MaybeGetFeasiblePoint() is None)
self.assertTrue(ellipsoid.PointInSet(
ellipsoid.MaybeGetFeasiblePoint()))
np.testing.assert_array_equal(ellipsoid.A(), self.A)
np.testing.assert_array_equal(ellipsoid.center(), self.b)
self.assertTrue(ellipsoid.PointInSet(x=self.b, tol=0.0))
new_vars, new_constraints = ellipsoid.AddPointInSetConstraints(
self.prog, self.x)
self.assertEqual(new_vars.size, 0)
self.assertGreater(len(new_constraints), 0)
constraints = ellipsoid.AddPointInNonnegativeScalingConstraints(
prog=self.prog, x=self.x, t=self.t)
self.assertGreaterEqual(len(constraints), 2)
self.assertIsInstance(constraints[0], Binding[Constraint])
constraints = ellipsoid.AddPointInNonnegativeScalingConstraints(
prog=self.prog, A=self.Ay, b=self.by, c=self.cz, d=self.dz,
x=self.y, t=self.z)
self.assertGreaterEqual(len(constraints), 2)
self.assertIsInstance(constraints[0], Binding[Constraint])
shape, pose = ellipsoid.ToShapeWithPose()
self.assertIsInstance(shape, Ellipsoid)
self.assertIsInstance(pose, RigidTransform)
p = np.array([11.1, 12.2, 13.3])
point = mut.Point(p)
scale, witness = ellipsoid.MinimumUniformScalingToTouch(point)
self.assertTrue(scale > 0.0)
np.testing.assert_array_almost_equal(witness, p)
assert_pickle(self, ellipsoid,
lambda S: np.vstack((S.A(), S.center())))
e_ball = mut.Hyperellipsoid.MakeAxisAligned(
radius=[1, 1, 1], center=self.b)
np.testing.assert_array_equal(e_ball.A(), self.A)
np.testing.assert_array_equal(e_ball.center(), self.b)
e_ball2 = mut.Hyperellipsoid.MakeHypersphere(
radius=1, center=self.b)
np.testing.assert_array_equal(e_ball2.A(), self.A)
np.testing.assert_array_equal(e_ball2.center(), self.b)
e_ball3 = mut.Hyperellipsoid.MakeUnitBall(dim=3)
np.testing.assert_array_equal(e_ball3.A(), self.A)
np.testing.assert_array_equal(e_ball3.center(), [0, 0, 0])
def test_minkowski_sum(self):
mut.MinkowskiSum()
point = mut.Point(np.array([11.1, 12.2, 13.3]))
hpoly = mut.HPolyhedron(A=self.A, b=self.b)
sum = mut.MinkowskiSum(setA=point, setB=hpoly)
self.assertEqual(sum.ambient_dimension(), 3)
self.assertEqual(sum.num_terms(), 2)
sum2 = mut.MinkowskiSum(sets=[point, hpoly])
self.assertEqual(sum2.ambient_dimension(), 3)
self.assertEqual(sum2.num_terms(), 2)
self.assertIsInstance(sum2.term(0), mut.Point)
self.assertFalse(sum.IsEmpty())
self.assertFalse(sum.MaybeGetFeasiblePoint() is None)
self.assertTrue(sum.PointInSet(sum.MaybeGetFeasiblePoint()))
def test_spectrahedron(self):
s = mut.Spectrahedron()
prog = MathematicalProgram()
X = prog.NewSymmetricContinuousVariables(3)
prog.AddPositiveSemidefiniteConstraint(X)
prog.AddLinearEqualityConstraint(X[0, 0] + X[1, 1] + X[2, 2], 1)
s = mut.Spectrahedron(prog=prog)
self.assertEqual(s.ambient_dimension(), 6)
self.assertFalse(s.IsEmpty())
self.assertFalse(s.MaybeGetFeasiblePoint() is None)
self.assertTrue(s.PointInSet(s.MaybeGetFeasiblePoint()))
def test_v_polytope(self):
mut.VPolytope()
vertices = np.array([[0.0, 1.0, 2.0], [3.0, 7.0, 5.0]])
vpoly = mut.VPolytope(vertices=vertices)
self.assertFalse(vpoly.IsEmpty())
self.assertFalse(vpoly.MaybeGetFeasiblePoint() is None)
self.assertTrue(vpoly.PointInSet(vpoly.MaybeGetFeasiblePoint()))
self.assertEqual(vpoly.ambient_dimension(), 2)
np.testing.assert_array_equal(vpoly.vertices(), vertices)
self.assertTrue(vpoly.PointInSet(x=[1.0, 5.0], tol=1e-8))
new_vars, new_constraints = vpoly.AddPointInSetConstraints(
self.prog, self.x[0:2])
self.assertEqual(new_vars.size, vertices.shape[1])
constraints = vpoly.AddPointInNonnegativeScalingConstraints(
prog=self.prog, x=self.x[:2], t=self.t)
self.assertGreaterEqual(len(constraints), 2)
self.assertIsInstance(constraints[0], Binding[Constraint])
constraints = vpoly.AddPointInNonnegativeScalingConstraints(
prog=self.prog, A=self.Ay[:2], b=self.by[:2], c=self.cz, d=self.dz,
x=self.y, t=self.z)
self.assertGreaterEqual(len(constraints), 2)
self.assertIsInstance(constraints[0], Binding[Constraint])
assert_pickle(self, vpoly, lambda S: S.vertices())
v_box = mut.VPolytope.MakeBox(
lb=[-1, -1, -1], ub=[1, 1, 1])
self.assertTrue(v_box.PointInSet([0, 0, 0]))
self.assertAlmostEqual(v_box.CalcVolume(), 8, 1E-10)
v_unit_box = mut.VPolytope.MakeUnitBox(dim=3)
self.assertTrue(v_unit_box.PointInSet([0, 0, 0]))
v_from_h = mut.VPolytope(H=mut.HPolyhedron.MakeUnitBox(dim=3))
self.assertTrue(v_from_h.PointInSet([0, 0, 0]))
# Test creating a vpolytope from a non-minimal set of vertices
# 2D: Random points inside a circle
r = 2.0
n = 400
vertices = np.zeros((2, n + 4))
theta = np.linspace(0, 2 * np.pi, n, endpoint=False)
vertices[0, 0:n] = r * np.cos(theta)
vertices[1, 0:n] = r * np.sin(theta)
vertices[:, n:] = np.array([
[r/2, r/3, r/4, r/5],
[r/2, r/3, r/4, r/5]
])
vpoly = mut.VPolytope(vertices=vertices).GetMinimalRepresentation()
self.assertAlmostEqual(vpoly.CalcVolume(), np.pi * r * r, delta=1e-3)
self.assertEqual(vpoly.vertices().shape[1], n)
# Calculate the length of the path that visits all the vertices
# sequentially.
# If the vertices are in clockwise/counter-clockwise order,
# the length of the path will coincide with the perimeter of a
# circle.
self.assertAlmostEqual(self._calculate_path_length(vpoly.vertices()),
2 * np.pi * r, delta=1e-3)
# 3D: Random points inside a box
a = 2.0
vertices = np.array([
[0, a, 0, a, 0, a, 0, a, a/2, a/3, a/4, a/5],
[0, 0, a, a, 0, 0, a, a, a/2, a/3, a/4, a/5],
[0, 0, 0, 0, a, a, a, a, a/2, a/3, a/4, a/5]
])
vpoly = mut.VPolytope(vertices=vertices).GetMinimalRepresentation()
self.assertAlmostEqual(vpoly.CalcVolume(), a * a * a)
self.assertEqual(vpoly.vertices().shape[1], 8)
temp_file_name = f"{temp_directory()}/vpoly.obj"
vpoly.WriteObj(filename=temp_file_name)
self.assertTrue(os.path.isfile(temp_file_name))
def _calculate_path_length(self, vertices):
n = vertices.shape[1]
length = 0
for i in range(n):
j = (i + 1) % n
diff = vertices[:, i] - vertices[:, j]
length += np.sqrt(np.dot(diff, diff))
return length
def test_cartesian_product(self):
mut.CartesianProduct()
point = mut.Point(np.array([11.1, 12.2, 13.3]))
h_box = mut.HPolyhedron.MakeBox(
lb=[-1, -1, -1], ub=[1, 1, 1])
sum = mut.CartesianProduct(setA=point, setB=h_box)
self.assertFalse(sum.IsEmpty())
self.assertFalse(sum.MaybeGetFeasiblePoint() is None)
self.assertTrue(sum.PointInSet(sum.MaybeGetFeasiblePoint()))
self.assertEqual(sum.ambient_dimension(), 6)
self.assertEqual(sum.num_factors(), 2)
sum2 = mut.CartesianProduct(sets=[point, h_box])
self.assertEqual(sum2.ambient_dimension(), 6)
self.assertEqual(sum2.num_factors(), 2)
self.assertIsInstance(sum2.factor(0), mut.Point)
sum2 = mut.CartesianProduct(
sets=[point, h_box], A=np.eye(6, 3), b=[0, 1, 2, 3, 4, 5])
self.assertEqual(sum2.ambient_dimension(), 3)
self.assertEqual(sum2.num_factors(), 2)
self.assertIsInstance(sum2.factor(1), mut.HPolyhedron)
def test_intersection(self):
mut.Intersection()
point = mut.Point(np.array([0.1, 0.2, 0.3]))
h_box = mut.HPolyhedron.MakeBox(
lb=[-1, -1, -1], ub=[1, 1, 1])
intersect = mut.Intersection(setA=point, setB=h_box)
self.assertFalse(intersect.IsEmpty())
self.assertFalse(intersect.MaybeGetFeasiblePoint() is None)
self.assertTrue(intersect.PointInSet(
intersect.MaybeGetFeasiblePoint()))
self.assertEqual(intersect.ambient_dimension(), 3)
self.assertEqual(intersect.num_elements(), 2)
intersect2 = mut.Intersection(sets=[point, h_box])
self.assertEqual(intersect2.ambient_dimension(), 3)
self.assertEqual(intersect2.num_elements(), 2)
self.assertIsInstance(intersect2.element(0), mut.Point)
def test_make_from_scene_graph_and_iris(self):
"""
Tests the make from scene graph and iris functionality together as
the Iris code makes obstacles from geometries registered in SceneGraph.
"""
scene_graph = SceneGraph()
source_id = scene_graph.RegisterSource("source")
frame_id = scene_graph.RegisterFrame(
source_id=source_id, frame=GeometryFrame("frame"))
box_geometry_id = scene_graph.RegisterGeometry(
source_id=source_id, frame_id=frame_id,
geometry=GeometryInstance(X_PG=RigidTransform(),
shape=Box(1., 1., 1.),
name="box"))
cylinder_geometry_id = scene_graph.RegisterGeometry(
source_id=source_id, frame_id=frame_id,
geometry=GeometryInstance(X_PG=RigidTransform(),
shape=Cylinder(1., 1.),
name="cylinder"))
sphere_geometry_id = scene_graph.RegisterGeometry(
source_id=source_id, frame_id=frame_id,
geometry=GeometryInstance(X_PG=RigidTransform(),
shape=Sphere(1.), name="sphere"))
capsule_geometry_id = scene_graph.RegisterGeometry(
source_id=source_id,
frame_id=frame_id,
geometry=GeometryInstance(X_PG=RigidTransform(),
shape=Capsule(1., 1.0),
name="capsule"))
for geometry_id in [box_geometry_id, cylinder_geometry_id,
sphere_geometry_id, capsule_geometry_id]:
scene_graph.AssignRole(source_id, geometry_id,
properties=ProximityProperties())
context = scene_graph.CreateDefaultContext()
pose_vector = FramePoseVector()
pose_vector.set_value(frame_id, RigidTransform())
scene_graph.get_source_pose_port(source_id).FixValue(
context, pose_vector)
query_object = scene_graph.get_query_output_port().Eval(context)
H = mut.HPolyhedron(
query_object=query_object, geometry_id=box_geometry_id,
reference_frame=scene_graph.world_frame_id())
self.assertEqual(H.ambient_dimension(), 3)
C = mut.CartesianProduct(
query_object=query_object, geometry_id=cylinder_geometry_id,
reference_frame=scene_graph.world_frame_id())
self.assertEqual(C.ambient_dimension(), 3)
E = mut.Hyperellipsoid(
query_object=query_object, geometry_id=sphere_geometry_id,
reference_frame=scene_graph.world_frame_id())
self.assertEqual(E.ambient_dimension(), 3)
S = mut.MinkowskiSum(
query_object=query_object, geometry_id=capsule_geometry_id,
reference_frame=scene_graph.world_frame_id())
self.assertEqual(S.ambient_dimension(), 3)
P = mut.Point(
query_object=query_object, geometry_id=sphere_geometry_id,
reference_frame=scene_graph.world_frame_id(),
maximum_allowable_radius=1.5)
self.assertEqual(P.ambient_dimension(), 3)
V = mut.VPolytope(
query_object=query_object, geometry_id=box_geometry_id,
reference_frame=scene_graph.world_frame_id())
self.assertEqual(V.ambient_dimension(), 3)
obstacles = mut.MakeIrisObstacles(
query_object=query_object,
reference_frame=scene_graph.world_frame_id())
self.assertGreater(len(obstacles), 0)
for obstacle in obstacles:
self.assertIsInstance(obstacle, mut.ConvexSet)
options = mut.IrisOptions()
options.require_sample_point_is_contained = True
options.iteration_limit = 1
options.termination_threshold = 0.1
options.relative_termination_threshold = 0.01
options.random_seed = 1314
options.starting_ellipse = mut.Hyperellipsoid.MakeUnitBall(3)
self.assertNotIn("object at 0x", repr(options))
region = mut.Iris(
obstacles=obstacles, sample=[2, 3.4, 5],
domain=mut.HPolyhedron.MakeBox(
lb=[-5, -5, -5], ub=[5, 5, 5]), options=options)
self.assertIsInstance(region, mut.HPolyhedron)
obstacles = [
mut.HPolyhedron.MakeUnitBox(3),
mut.Hyperellipsoid.MakeUnitBall(3),
mut.Point([0, 0, 0]),
mut.VPolytope.MakeUnitBox(3)]
region = mut.Iris(
obstacles=obstacles, sample=[2, 3.4, 5],
domain=mut.HPolyhedron.MakeBox(
lb=[-5, -5, -5], ub=[5, 5, 5]), options=options)
self.assertIsInstance(region, mut.HPolyhedron)
def test_iris_cspace(self):
limits_urdf = """
<robot name="limits">
<link name="movable">
<collision>
<geometry><box size="1 1 1"/></geometry>
</collision>
</link>
<joint name="movable" type="prismatic">
<axis xyz="1 0 0"/>
<limit lower="-2" upper="2"/>
<parent link="world"/>
<child link="movable"/>
</joint>
</robot>"""
builder = DiagramBuilder()
plant, scene_graph = AddMultibodyPlantSceneGraph(builder, 0.0)
Parser(plant).AddModelsFromString(limits_urdf, "urdf")
plant.Finalize()
diagram = builder.Build()
context = diagram.CreateDefaultContext()
options = mut.IrisOptions()
options.num_collision_infeasible_samples = 3
ik = InverseKinematics(plant)
options.prog_with_additional_constraints = ik.prog()
options.num_additional_constraint_infeasible_samples = 2
plant.SetPositions(plant.GetMyMutableContextFromRoot(context), [0])
region = mut.IrisInConfigurationSpace(
plant=plant, context=plant.GetMyContextFromRoot(context),
options=options)
self.assertIsInstance(region, mut.ConvexSet)
self.assertEqual(region.ambient_dimension(), 1)
self.assertTrue(region.PointInSet([1.0]))
self.assertFalse(region.PointInSet([3.0]))
options.configuration_obstacles = [mut.Point([-0.5])]
point, = options.configuration_obstacles
self.assertEqual(point.x(), [-0.5])
point2, = options.configuration_obstacles
self.assertIs(point2, point)
region = mut.IrisInConfigurationSpace(
plant=plant, context=plant.GetMyContextFromRoot(context),
options=options)
self.assertIsInstance(region, mut.ConvexSet)
self.assertEqual(region.ambient_dimension(), 1)
self.assertTrue(region.PointInSet([1.0]))
self.assertFalse(region.PointInSet([-1.0]))
def test_serialize_iris_regions(self):
iris_regions = {
"box1":
mut.HPolyhedron.MakeBox(lb=[-1, -2, -3], ub=[1, 2, 3]),
"box2":
mut.HPolyhedron.MakeBox(lb=[-4.1, -5.2, -6.3], ub=[4.1, 4.2, 6.3])
}
temp_file_name = f"{temp_directory()}/iris.yaml"
mut.SaveIrisRegionsYamlFile(filename=temp_file_name,
regions=iris_regions,
child_name="test")
loaded_regions = mut.LoadIrisRegionsYamlFile(filename=temp_file_name,
child_name="test")
self.assertEqual(iris_regions.keys(), loaded_regions.keys())
for k in iris_regions.keys():
np.testing.assert_array_equal(iris_regions[k].A(),
loaded_regions[k].A())
np.testing.assert_array_equal(iris_regions[k].b(),
loaded_regions[k].b())
def test_graph_of_convex_sets(self):
options = mut.GraphOfConvexSetsOptions()
self.assertIsNone(options.convex_relaxation)
self.assertIsNone(options.preprocessing)
self.assertIsNone(options.max_rounded_paths)
options.convex_relaxation = True
options.preprocessing = False
options.max_rounded_paths = 0
options.max_rounding_trials = 5
options.flow_tolerance = 1e-6
options.rounding_seed = 1
options.solver = ClpSolver()
options.solver_options = SolverOptions()
options.solver_options.SetOption(ClpSolver.id(), "scaling", 2)
options.rounding_solver_options = SolverOptions()
options.rounding_solver_options.SetOption(ClpSolver.id(), "dual", 0)
self.assertIn("scaling",
options.solver_options.GetOptions(ClpSolver.id()))
self.assertIn(
"dual", options.rounding_solver_options.GetOptions(ClpSolver.id()))
self.assertIn("convex_relaxation", repr(options))
spp = mut.GraphOfConvexSets()
source = spp.AddVertex(set=mut.Point([0.1]), name="source")
target = spp.AddVertex(set=mut.Point([0.2]), name="target")
edge0 = spp.AddEdge(u=source, v=target, name="edge0")
with catch_drake_warnings(expected_count=1) as w:
edge1 = spp.AddEdge(u_id=source.id(),
v_id=target.id(),
name="edge1")
self.assertEqual(len(spp.Vertices()), 2)
self.assertEqual(len(spp.Edges()), 2)
with catch_drake_warnings(expected_count=1) as w:
result = spp.SolveShortestPath(
source_id=source.id(), target_id=target.id(), options=options)
self.assertIsInstance(result, MathematicalProgramResult)
self.assertIsInstance(spp.SolveShortestPath(
source=source, target=target, options=options),
MathematicalProgramResult)
self.assertIsInstance(
spp.SolveConvexRestriction(active_edges=[edge0, edge1],
options=options),
MathematicalProgramResult)
self.assertEqual(
len(
spp.GetSolutionPath(source=source,
target=target,
result=result,
tolerance=0.1)), 1)
self.assertIn("source", spp.GetGraphvizString(
result=result, show_slacks=True, precision=2, scientific=False))
# Vertex
self.assertAlmostEqual(
source.GetSolutionCost(result=result), 0.0, 1e-6)
np.testing.assert_array_almost_equal(
source.GetSolution(result), [0.1], 1e-6)
self.assertIsInstance(source.id(), mut.GraphOfConvexSets.VertexId)
self.assertEqual(source.ambient_dimension(), 1)
self.assertEqual(source.name(), "source")
self.assertIsInstance(source.x()[0], Variable)
self.assertIsInstance(source.set(), mut.Point)
var, binding = source.AddCost(e=1.0+source.x()[0])
self.assertIsInstance(var, Variable)
self.assertIsInstance(binding, Binding[Cost])
var, binding = source.AddCost(binding=binding)
self.assertIsInstance(var, Variable)
self.assertIsInstance(binding, Binding[Cost])
self.assertEqual(len(source.GetCosts()), 2)
binding = source.AddConstraint(f=(source.x()[0] <= 1.0))
self.assertIsInstance(binding, Binding[Constraint])
binding = source.AddConstraint(binding=binding)
self.assertIsInstance(binding, Binding[Constraint])
self.assertEqual(len(source.GetConstraints()), 2)
self.assertEqual(len(source.incoming_edges()), 0)
self.assertEqual(len(source.outgoing_edges()), 2)
self.assertEqual(len(target.incoming_edges()), 2)
self.assertEqual(len(target.outgoing_edges()), 0)
# Edge
self.assertAlmostEqual(edge0.GetSolutionCost(result=result), 0.0, 1e-6)
np.testing.assert_array_almost_equal(
edge0.GetSolutionPhiXu(result=result), [0.1], 1e-6)
np.testing.assert_array_almost_equal(
edge0.GetSolutionPhiXv(result=result), [0.2], 1e-6)
self.assertIsInstance(edge0.id(), mut.GraphOfConvexSets.EdgeId)
self.assertEqual(edge0.name(), "edge0")
self.assertEqual(edge0.u(), source)
self.assertEqual(edge0.v(), target)
self.assertIsInstance(edge0.phi(), Variable)
self.assertIsInstance(edge0.xu()[0], Variable)
self.assertIsInstance(edge0.xv()[0], Variable)
var, binding = edge0.AddCost(e=1.0+edge0.xu()[0])
self.assertIsInstance(var, Variable)
self.assertIsInstance(binding, Binding[Cost])
var, binding = edge0.AddCost(binding=binding)
self.assertIsInstance(var, Variable)
self.assertIsInstance(binding, Binding[Cost])
self.assertEqual(len(edge0.GetCosts()), 2)
binding = edge0.AddConstraint(f=(edge0.xu()[0] == edge0.xv()[0]))
self.assertIsInstance(binding, Binding[Constraint])
binding = edge0.AddConstraint(binding=binding)
self.assertIsInstance(binding, Binding[Constraint])
self.assertEqual(len(edge0.GetConstraints()), 2)
edge0.AddPhiConstraint(phi_value=False)
edge0.ClearPhiConstraints()
edge1.AddPhiConstraint(phi_value=True)
spp.ClearAllPhiConstraints()
# Remove Edges
self.assertEqual(len(spp.Edges()), 2)
spp.RemoveEdge(edge0)
self.assertEqual(len(spp.Edges()), 1)
with catch_drake_warnings(expected_count=1) as w:
spp.RemoveEdge(edge1.id())
self.assertEqual(len(spp.Edges()), 0)
# Remove Vertices
self.assertEqual(len(spp.Vertices()), 2)
spp.RemoveVertex(source)
self.assertEqual(len(spp.Vertices()), 1)
with catch_drake_warnings(expected_count=1) as w:
spp.RemoveVertex(target.id())
self.assertEqual(len(spp.Vertices()), 0)
<file_sep>/tools/wheel/image/dependencies/projects/coinutils.cmake
ExternalProject_Add(coinutils
URL ${coinutils_url}
URL_MD5 ${coinutils_md5}
DOWNLOAD_NAME ${coinutils_dlname}
${COMMON_EP_ARGS}
BUILD_IN_SOURCE 1
CONFIGURE_COMMAND ./configure
--prefix=${CMAKE_INSTALL_PREFIX}
--disable-shared
CFLAGS=-fPIC
CXXFLAGS=-fPIC
BUILD_COMMAND make
INSTALL_COMMAND make install
)
extract_license(coinutils
CoinUtils/LICENSE
)
<file_sep>/multibody/plant/multibody_plant_config_functions.h
#pragma once
#include <string>
#include "drake/geometry/query_results/contact_surface.h"
#include "drake/multibody/plant/multibody_plant.h"
#include "drake/multibody/plant/multibody_plant_config.h"
#include "drake/systems/framework/diagram_builder.h"
namespace drake {
namespace multibody {
/// Adds a new MultibodyPlant and SceneGraph to the given `builder`. The
/// plant's settings such as `time_step` are set using the given `config`.
AddMultibodyPlantSceneGraphResult<double> AddMultibodyPlant(
const MultibodyPlantConfig& config,
systems::DiagramBuilder<double>* builder);
namespace internal {
// (Exposed for unit testing only.)
// Parses a string name for a contact model and returns the enumerated value.
// Valid string names are listed in MultibodyPlantConfig's class overview.
// @throws std::exception if an invalid string is passed in.
ContactModel GetContactModelFromString(std::string_view contact_model);
// (Exposed for unit testing only.)
// Returns the string name of an enumerated value for a contact model.
std::string GetStringFromContactModel(ContactModel contact_model);
// (Exposed for unit testing only.)
// Parses a string name for a contact solver type and returns the enumerated
// value. Valid string names are listed in MultibodyPlantConfig's class
// overview.
// @throws std::exception if an invalid string is passed in.
DiscreteContactSolver GetDiscreteContactSolverFromString(
std::string_view discrete_contact_solver);
// (Exposed for unit testing only.) Returns the string name of an enumerated
// value for a discrete contact solver type.
std::string GetStringFromDiscreteContactSolver(
DiscreteContactSolver discrete_contact_solver);
// (Exposed for unit testing only.)
// Parses a string name for a contact representation and returns the enumerated
// value. Valid string names are listed in MultibodyPlantConfig's class
// overview.
// @throws std::exception if an invalid string is passed in.
geometry::HydroelasticContactRepresentation
GetContactSurfaceRepresentationFromString(
std::string_view contact_representation);
// (Exposed for unit testing only.)
// Returns the string name of an enumerated value for a contact representation.
std::string GetStringFromContactSurfaceRepresentation(
geometry::HydroelasticContactRepresentation contact_representation);
} // namespace internal
} // namespace multibody
} // namespace drake
<file_sep>/multibody/tree/unit_inertia.cc
#include "drake/multibody/tree/unit_inertia.h"
#include "drake/common/fmt_eigen.h"
namespace drake {
namespace multibody {
template <typename T>
UnitInertia<T>& UnitInertia<T>::SetFromRotationalInertia(
const RotationalInertia<T>& I, const T& mass) {
DRAKE_THROW_UNLESS(mass > 0);
RotationalInertia<T>::operator=(I / mass);
return *this;
}
template <typename T>
UnitInertia<T> UnitInertia<T>::PointMass(const Vector3<T>& p_FQ) {
// Square each coefficient in p_FQ, perhaps better with p_FQ.array().square()?
const Vector3<T> p2m = p_FQ.cwiseAbs2(); // [x² y² z²].
const T mp0 = -p_FQ(0); // -x
const T mp1 = -p_FQ(1); // -y
return UnitInertia<T>(
// Gxx = y² + z², Gyy = x² + z², Gzz = x² + y²
p2m[1] + p2m[2], p2m[0] + p2m[2], p2m[0] + p2m[1],
// Gxy = -x y, Gxz = -x z, Gyz = -y z
mp0 * p_FQ[1], mp0 * p_FQ[2], mp1 * p_FQ[2]);
}
template <typename T>
UnitInertia<T> UnitInertia<T>::SolidEllipsoid(
const T& a, const T& b, const T& c) {
const T a2 = a * a;
const T b2 = b * b;
const T c2 = c * c;
return UnitInertia<T>(0.2 * (b2 + c2), 0.2 * (a2 + c2), 0.2 * (a2 + b2));
}
template <typename T>
UnitInertia<T> UnitInertia<T>::SolidCylinder(
const T& r, const T& L, const Vector3<T>& b_E) {
DRAKE_THROW_UNLESS(r >= 0);
DRAKE_THROW_UNLESS(L >= 0);
// TODO(Mitiguy) Throw if |b_E| is not within 1.0E-14 of 1 (breaking change).
DRAKE_THROW_UNLESS(b_E.norm() > std::numeric_limits<double>::epsilon());
const T J = r * r / T(2);
const T K = (T(3) * r * r + L * L) / T(12);
return AxiallySymmetric(J, K, b_E);
}
template <typename T>
UnitInertia<T> UnitInertia<T>::SolidCylinderAboutEnd(const T& r, const T& L) {
// TODO(Mitiguy) add @param[in] unit_vector as with SolidCapsule.
DRAKE_THROW_UNLESS(r >= 0);
DRAKE_THROW_UNLESS(L >= 0);
const T Iz = r * r / T(2);
const T Ix = (T(3) * r * r + L * L) / T(12) + L * L / T(4);
return UnitInertia(Ix, Ix, Iz);
}
template <typename T>
UnitInertia<T> UnitInertia<T>::AxiallySymmetric(const T& J, const T& K,
const Vector3<T>& b_E) {
DRAKE_THROW_UNLESS(J >= 0.0);
DRAKE_THROW_UNLESS(K >= 0.0);
// The triangle inequalities for this case reduce to J <= 2*K:
DRAKE_THROW_UNLESS(J <= 2.0 * K);
// TODO(Mitiguy) Throw if |b_E| is not within 1.0E-14 of 1 (breaking change).
DRAKE_THROW_UNLESS(b_E.norm() > std::numeric_limits<double>::epsilon());
// Normalize b_E before using it. Only direction matters:
Vector3<T> bhat_E = b_E.normalized();
Matrix3<T> G_matrix =
K * Matrix3<T>::Identity() + (J - K) * bhat_E * bhat_E.transpose();
return UnitInertia<T>(G_matrix(0, 0), G_matrix(1, 1), G_matrix(2, 2),
G_matrix(0, 1), G_matrix(0, 2), G_matrix(1, 2));
}
template <typename T>
UnitInertia<T> UnitInertia<T>::StraightLine(const T& K, const Vector3<T>& b_E) {
// TODO(Mitiguy) Throw if |b_E| is not within 1.0E-14 of 1 (breaking change).
DRAKE_DEMAND(K > 0.0);
return AxiallySymmetric(0.0, K, b_E);
}
template <typename T>
UnitInertia<T> UnitInertia<T>::ThinRod(const T& L, const Vector3<T>& b_E) {
// TODO(Mitiguy) Throw if |b_E| is not within 1.0E-14 of 1 (breaking change).
DRAKE_DEMAND(L > 0.0);
return StraightLine(L * L / 12.0, b_E);
}
template <typename T>
UnitInertia<T> UnitInertia<T>::SolidBox(const T& Lx, const T& Ly, const T& Lz) {
if (Lx < T(0) || Ly < T(0) || Lz < T(0)) {
const std::string msg =
"A length argument to UnitInertia::SolidBox() "
"is negative.";
throw std::logic_error(msg);
}
const T one_twelfth = T(1) / T(12);
const T Lx2 = Lx * Lx, Ly2 = Ly * Ly, Lz2 = Lz * Lz;
return UnitInertia(one_twelfth * (Ly2 + Lz2), one_twelfth * (Lx2 + Lz2),
one_twelfth * (Lx2 + Ly2));
}
template <typename T>
UnitInertia<T> UnitInertia<T>::SolidCapsule(const T& r, const T& L,
const Vector3<T>& unit_vector) {
DRAKE_THROW_UNLESS(r >= 0);
DRAKE_THROW_UNLESS(L >= 0);
// Ensure ‖unit_vector‖ is within ≈ 5.5 bits of 1.0.
// Note: 1E-14 ≈ 2^5.5 * std::numeric_limits<double>::epsilon();
using std::abs;
constexpr double kTolerance = 1E-14;
if (abs(unit_vector.norm() - 1) > kTolerance) {
std::string error_message =
fmt::format("{}(): The unit_vector argument {} is not a unit vector.",
__func__, fmt_eigen(unit_vector.transpose()));
throw std::logic_error(error_message);
}
// A special case is required for r = 0 because r = 0 creates a zero volume
// capsule (and we divide by volume later on). No special case for L = 0 is
// needed because the capsule degenerates into a sphere (non-zero volume).
if (r == 0.0) {
return UnitInertia<T>::ThinRod(L, unit_vector);
}
// The capsule is regarded as a cylinder C of length L and radius r and two
// half-spheres (each of radius r). The first half-sphere H is rigidly fixed
// to one end of cylinder C so that the intersection between H and C forms
// a circle centered at point Ho. Similarly, the other half-sphere is rigidly
// fixed to the other end of cylinder C.
// The capsule's unit inertia about its center of mass is calculated using
// tabulated analytical expressions from [Kane] "Dynamics: Theory and
// Applications," McGraw-Hill, New York, 1985, by <NAME> and <NAME>,
// available for electronic download from Cornell digital library.
// Calculate vc (the volume of cylinder C) and vh (volume of half-sphere H).
const T r2 = r * r;
const T r3 = r2 * r;
const T vc = M_PI * r2 * L; // vc = π r² L
const T vh = 2.0 / 3.0 * M_PI * r3; // vh = 2/3 π r³
// Denoting mc as the mass of cylinder C and mh as the mass of half-sphere H,
// and knowing the capsule has a uniform density and the capsule's mass is 1
// (for unit inertia), calculate mc and mh.
const T v = vc + 2 * vh; // Volume of capsule.
const T mc = vc / v; // Mass in the cylinder (relates to volume).
const T mh = vh / v; // Mass in each half-sphere (relates to volume).
// The distance dH between Hcm (the half-sphere H's center of mass) and Ccm
// (the cylinder C's center of mass) is from [Kane, Figure A23, pg. 369].
// dH = 3.0 / 8.0 * r + L / 2.0;
const T dH = 0.375 * r + 0.5 * L;
// The discussion that follows assumes Ic_zz is the axial moment of inertia
// and Ix_xx = Ic_yy is the transverse moment of inertia.
// Form cylinder C's moments of inertia about Ccm (C's center of mass).
// Ic_xx = Ic_yy = mc(L²/12 + r²/4) From [Kane, Figure A20, pg. 368].
// Ic_zz = mc r²/2 From [Kane, Figure A20, pg. 368].
// Form half-sphere H's moments of inertia about Hcm (H's center of mass).
// Ih_xx = Ih_yy = 83/320 mh r² From [Kane, Figure A23, pg. 369].
// Ih_zz = 2/5 mh r² From [Kane, Figure A23, pg. 369].
// Pedagogical note: H's inertia matrix about Ho (as compared with about Hcm)
// is instead diag(2/5 mh r², 2/5 mh r², 2/5 mh r²).
// The capsule's inertia about Ccm is calculated with the shift theorem
// (parallel axis theorem) in terms of dH (distance between Hcm and Ccm) as
// follows where the factor of 2 is due to the 2 half-spheres.
// Note: The capsule's center of mass is coincident with Ccm.
// Ixx = Ic_xx + 2 Ih_xx + 2 mh dH²
// Izz = Ic_zz + 2 Ih_zz;
// The previous algorithm for Ixx and Izz is algebraically manipulated to a
// more efficient result by factoring on mh and mc and computing numbers as
const T Ixx = mc * (L*L/12.0 + 0.25*r2) + mh * (0.51875*r2 + 2*dH*dH);
const T Izz = (0.5*mc + 0.8*mh) * r2; // Axial moment of inertia.
// Note: Although a check is made that ‖unit_vector‖ ≈ 1, even if imperfect,
// UnitInertia::AxiallySymmetric() normalizes unit_vector before use.
// TODO(Mitiguy) remove normalization in UnitInertia::AxiallySymmetric().
return UnitInertia<T>::AxiallySymmetric(Izz, Ixx, unit_vector);
}
namespace {
// Returns a 3x3 matrix whose upper-triangular part contains the outer product
// of vector a * vector b [i.e., a * b.transpose()] and whose lower-triangular
// part is uninitialized.
// @param[in] a vector expressed in a frame E.
// @param[in] b vector expressed in a frame E.
// @note This function is an efficient way to calculate outer-products that
// contribute via a sum to a symmetric matrix.
template <typename T>
Matrix3<T> UpperTriangularOuterProduct(
const Eigen::Ref<const Vector3<T>>& a,
const Eigen::Ref<const Vector3<T>>& b) {
Matrix3<T> M;
M(0, 0) = a(0) * b(0); M(0, 1) = a(0) * b(1); M(0, 2) = a(0) * b(2);
M(1, 1) = a(1) * b(1); M(1, 2) = a(1) * b(2);
M(2, 2) = a(2) * b(2);
return M;
}
} // namespace
template <typename T>
UnitInertia<T> UnitInertia<T>::SolidTetrahedronAboutPoint(
const Vector3<T>& p0, const Vector3<T>& p1, const Vector3<T>& p2,
const Vector3<T>& p3) {
// This method calculates a tetrahedron B's unit inertia G_BA about a point A
// by first calculating G_BB0 (B's unit inertia about vertex B0 of B).
// To calculate G_BB0, 3 new position vectors are formed, namely the position
// vectors from vertex B0 to vertices B1, B2, B3 (B's other three vertices).
const Vector3<T> p_B0B1 = p1 - p0; // Position from vertex B0 to vertex B1.
const Vector3<T> p_B0B2 = p2 - p0; // Position from vertex B0 to vertex B2.
const Vector3<T> p_B0B3 = p3 - p0; // Position from vertex B0 to vertex B3.
UnitInertia<T> G_BB0 =
UnitInertia<T>::SolidTetrahedronAboutVertex(p_B0B1, p_B0B2, p_B0B3);
// Shift unit inertia from about point B0 to about point A.
const Vector3<T> p_B0Bcm = 0.25 * (p_B0B1 + p_B0B2 + p_B0B3);
const Vector3<T>& p_AB0 = p0; // Alias with monogram notation to clarify.
const Vector3<T> p_ABcm = p_AB0 + p_B0Bcm;
RotationalInertia<T>& I_BA = G_BB0.ShiftToThenAwayFromCenterOfMassInPlace(
/* mass = */ 1, p_B0Bcm, p_ABcm);
return UnitInertia<T>(I_BA); // Returns G_BA (B's unit inertia about A).
}
template <typename T>
UnitInertia<T> UnitInertia<T>::SolidTetrahedronAboutVertex(
const Vector3<T>& p1, const Vector3<T>& p2, const Vector3<T>& p3) {
// This method calculates G_BB0 (a tetrahedron B's unit inertia about a
// vertex B0 of B) using the position vectors from vertex B0 to B's three
// other vertices, herein named P, Q, R to be consistent with the
// tetrahedron inertia formulas from the mass/inertia appendix in
// [Mitiguy, 2017]: "Advanced Dynamics and Motion Simulation,
// For professional engineers and scientists,"
const Vector3<T>& p = p1; // Position from vertex B0 to vertex P.
const Vector3<T>& q = p2; // Position from vertex B0 to vertex Q.
const Vector3<T>& r = p3; // Position from vertex B0 to vertex R.
const Vector3<T> q_plus_r = q + r;
const T p_dot_pqr = p.dot(p + q_plus_r);
const T q_dot_qr = q.dot(q_plus_r);
const T r_dot_r = r.dot(r);
const T scalar = 0.1 * (p_dot_pqr + q_dot_qr + r_dot_r);
const Vector3<T> p_half = 0.5 * p;
const Vector3<T> q_half = 0.5 * q;
const Vector3<T> r_half = 0.5 * r;
const Matrix3<T> G = UpperTriangularOuterProduct<T>(p, p + q_half + r_half)
+ UpperTriangularOuterProduct<T>(q, p_half + q + r_half)
+ UpperTriangularOuterProduct<T>(r, p_half + q_half + r);
const T Ixx = scalar - 0.1 * G(0, 0);
const T Iyy = scalar - 0.1 * G(1, 1);
const T Izz = scalar - 0.1 * G(2, 2);
const T Ixy = -0.1 * G(0, 1);
const T Ixz = -0.1 * G(0, 2);
const T Iyz = -0.1 * G(1, 2);
return UnitInertia(Ixx, Iyy, Izz, Ixy, Ixz, Iyz);
}
template <typename T>
std::pair<Vector3<double>, math::RotationMatrix<double>>
UnitInertia<T>::CalcPrincipalHalfLengthsAndAxesForEquivalentShape(
double inertia_shape_factor) const {
DRAKE_THROW_UNLESS(inertia_shape_factor > 0 && inertia_shape_factor <= 1);
// The formulas below are derived for a shape D whose principal unit moments
// of inertia Gmin, Gmed, Gmax about Dcm (D's center of mass) have the form:
// Gmin = inertia_shape_factor * (b² + c²)
// Gmed = inertia_shape_factor * (a² + c²)
// Gmax = inertia_shape_factor * (a² + b²)
// Casting these equations into matrix form, gives
// ⌈0 1 1⌉ ⌈a²⌉ ⌈Gmin ⌉
// |1 0 1⌉ |b²⌉ = |Gmed ⌉ / inertia_shape_factor
// ⌊1 1 0⌋ ⌊c²⌋ ⌊Gmax ⌉
// Inverting the coefficient matrix and solving for a², b², c² leads to
// ⌈a²⌉ ⌈-1 1 1⌉ ⌈Gmin ⌉
// |b²⌉ = | 1 -1 1⌉ |Gmed ⌉ * 0.5 / inertia_shape_factor
// ⌊c²⌋ ⌊ 1 1 -1⌋ ⌊Gmax ⌉
// Since Gmin ≤ Gmed ≤ Gmax, we can deduce a² ≥ b² ≥ c², so we designate
// lmax² = a², lmed² = b², lmin² = c².
// Form principal moments Gmoments and principal axes stored in R_EA.
auto [Gmoments, R_EA] = this->CalcPrincipalMomentsAndAxesOfInertia();
const double Gmin = Gmoments(0);
const double Gmed = Gmoments(1);
const double Gmax = Gmoments(2);
DRAKE_ASSERT(Gmin <= Gmed && Gmed <= Gmax);
const double coef = 0.5 / inertia_shape_factor;
using std::max; // Avoid round-off issues that result in e.g., sqrt(-1E-15).
const double lmax_squared = max(coef * (Gmed + Gmax - Gmin), 0.0);
const double lmed_squared = max(coef * (Gmin + Gmax - Gmed), 0.0);
const double lmin_squared = max(coef * (Gmin + Gmed - Gmax), 0.0);
const double lmax = std::sqrt(lmax_squared);
const double lmed = std::sqrt(lmed_squared);
const double lmin = std::sqrt(lmin_squared);
return std::pair(Vector3<double>(lmax, lmed, lmin), R_EA);
}
} // namespace multibody
} // namespace drake
DRAKE_DEFINE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS(
class drake::multibody::UnitInertia)
<file_sep>/geometry/render_gl/render_engine_gl_params.h
#pragma once
#include "drake/common/name_value.h"
#include "drake/geometry/render/render_label.h"
#include "drake/geometry/rgba.h"
namespace drake {
namespace geometry {
/** Construction parameters for RenderEngineGl. */
struct RenderEngineGlParams {
/** Passes this object to an Archive.
Refer to @ref yaml_serialization "YAML Serialization" for background. */
template <typename Archive>
void Serialize(Archive* a) {
a->Visit(DRAKE_NVP(default_label));
a->Visit(DRAKE_NVP(default_diffuse));
a->Visit(DRAKE_NVP(default_clear_color));
}
/** Default render label to apply to a geometry when none is otherwise
specified. */
render::RenderLabel default_label{render::RenderLabel::kUnspecified};
/** Default diffuse color to apply to a geometry when none is otherwise
specified in the (phong, diffuse) property. */
Rgba default_diffuse{0.9, 0.7, 0.2, 1.0};
/** The default background color for color images. */
Rgba default_clear_color{204 / 255., 229 / 255., 255 / 255., 1.0};
};
} // namespace geometry
} // namespace drake
<file_sep>/bindings/pydrake/geometry/test/render_deprecation_test.py
from pydrake.common.test_utilities.deprecation import catch_drake_warnings
import unittest
class TestDeprecation(unittest.TestCase):
"""
2023-08-01 Remove this file upon completion of deprecation.
"""
def test_deprecated_symbols_exist(self):
# The whole point of this test is that we can access all the symbols in
# the deprecated module path.
with catch_drake_warnings(expected_count=1) as w:
from pydrake.geometry.render import (
ClippingRange,
ColorRenderCamera,
DepthRange,
DepthRenderCamera,
MakeRenderEngineGl,
MakeRenderEngineGltfClient,
MakeRenderEngineVtk,
RenderCameraCore,
RenderEngine,
RenderEngineGlParams,
RenderEngineGltfClientParams,
RenderEngineVtkParams,
RenderLabel,
)
self.assertIn("2023-08-01", str(w[0].message))
<file_sep>/tools/workspace/gym_py/README.md
gym
===
This imports the OpenAI Gym RL tool into our build.
Note on Upgrading
=================
`stable_baselines3` lags `gym` by more than `gym`'s deprecation window and
does not document its compatibility limit correctly (claims to support `gym`
<0.24 but in fact uses classes removed in 0.22, for example).
Because of this, it is unlikely that upgrading this package beyond 0.21 will
succeed, or is even desirable.
* Check https://github.com/DLR-RM/stable-baselines3/pull/780 for status.
* `stable_baselines3` allegedly will fix all of this version shear when gym
hits 1.0.
* `gym` will allegedly remove all the deprecated APIs that SB3 uses in 0.26.
A full upgrade of `gym` to 1.0 and correspondingly of `stable_baselines3` to
HEAD will be necessary in the future, but will require substantial changes to
the `stable_baselines3_internal` stub and to any corresponding unit tests.
<file_sep>/multibody/fem/test/fem_solver_test.cc
#include "drake/multibody/fem/fem_solver.h"
#include <gtest/gtest.h>
#include "drake/common/test_utilities/eigen_matrix_compare.h"
#include "drake/common/test_utilities/expect_throws_message.h"
#include "drake/multibody/fem/acceleration_newmark_scheme.h"
#include "drake/multibody/fem/test/dummy_model.h"
namespace drake {
namespace multibody {
namespace fem {
namespace internal {
namespace {
using Eigen::MatrixXd;
constexpr double kEps = 4.75 * std::numeric_limits<double>::epsilon();
/* Parameters for the Newmark-beta integration scheme. */
constexpr double kDt = 0.01;
constexpr double kGamma = 0.5;
constexpr double kBeta = 0.25;
class FemSolverTest : public ::testing::Test {
protected:
DummyModel model_{};
AccelerationNewmarkScheme<double> integrator_{kDt, kGamma, kBeta};
FemSolver<double> solver_{&model_, &integrator_};
};
TEST_F(FemSolverTest, CloneScratchData) {
FemSolverScratchData<double> scratch(model_);
std::unique_ptr<FemSolverScratchData<double>> clone = scratch.Clone();
EXPECT_EQ(clone->b(), scratch.b());
EXPECT_EQ(clone->dz(), scratch.dz());
const MatrixXd tangent_matrix = scratch.tangent_matrix().MakeDenseMatrix();
const MatrixXd tangent_matrix_clone =
clone->tangent_matrix().MakeDenseMatrix();
EXPECT_EQ(tangent_matrix, tangent_matrix_clone);
}
TEST_F(FemSolverTest, Tolerance) {
/* Default values. */
EXPECT_EQ(solver_.relative_tolerance(), 1e-4);
EXPECT_EQ(solver_.absolute_tolerance(), 1e-6);
/* Test Setters. */
constexpr double kTol = 1e-8;
solver_.set_relative_tolerance(kTol);
solver_.set_absolute_tolerance(kTol);
EXPECT_EQ(solver_.relative_tolerance(), kTol);
EXPECT_EQ(solver_.absolute_tolerance(), kTol);
}
/* Tests that the behavior of FemSolver::AdvanceOneTimeStep agrees with analytic
results. The DummyModel contains DummyElements that give non-zero residual at
zero state and zero residual everywhere else. The dummy element also has
constant stiffness, damping, and mass matrix (aka they are state-independent).
As a result, we expect AdvanceOneTimeStep to converge after exactly one Newton
iteration, and the unknown variable z (acceleration in this case) should
satisfy A*z = -b, where A is the constant tangent matrix and b is the nonzero
residual evaluated at the zero state. */
TEST_F(FemSolverTest, AdvanceOneTimeStep) {
DummyModel::DummyBuilder builder(&model_);
builder.AddTwoElementsWithSharedNodes();
builder.Build();
std::unique_ptr<FemState<double>> state0 = model_.MakeFemState();
std::unique_ptr<FemState<double>> state = model_.MakeFemState();
FemSolverScratchData<double> scratch(model_);
const int num_iterations =
solver_.AdvanceOneTimeStep(*state0, state.get(), &scratch);
EXPECT_EQ(num_iterations, 1);
/* Compute the expected result from AdvanceOneTimeStep(). */
std::unique_ptr<FemState<double>> expected_state = model_.MakeFemState();
auto tangent_matrix = model_.MakePetscSymmetricBlockSparseTangentMatrix();
model_.CalcTangentMatrix(*state0, integrator_.GetWeights(),
tangent_matrix.get());
tangent_matrix->AssembleIfNecessary();
const MatrixXd A = tangent_matrix->MakeDenseMatrix();
VectorX<double> b(model_.num_dofs());
model_.CalcResidual(*state0, &b);
/* The solver is not considered as "converged" with the initial state. */
EXPECT_FALSE(solver_.solver_converged(b.norm(), b.norm()));
Eigen::ConjugateGradient<MatrixXd> cg;
cg.compute(A);
const VectorX<double> dz = cg.solve(-b);
integrator_.UpdateStateFromChangeInUnknowns(dz, expected_state.get());
EXPECT_TRUE(CompareMatrices(expected_state->GetPositions(),
state->GetPositions(), kEps));
EXPECT_TRUE(CompareMatrices(expected_state->GetAccelerations(),
state->GetAccelerations(), kEps));
EXPECT_TRUE(CompareMatrices(expected_state->GetVelocities(),
state->GetVelocities(), kEps));
}
// TODO(xuchenhan-tri): Unit tests that cover other exit conditions of
// the iterative solver are missing.
} // namespace
} // namespace internal
} // namespace fem
} // namespace multibody
} // namespace drake
<file_sep>/geometry/optimization/vpolytope.cc
#include "drake/geometry/optimization/vpolytope.h"
#include <algorithm>
#include <array>
#include <cmath>
#include <fstream>
#include <limits>
#include <memory>
#include <numeric>
#include <string>
#include <drake_vendor/libqhullcpp/Qhull.h>
#include <drake_vendor/libqhullcpp/QhullVertexSet.h>
#include <fmt/format.h>
#include "drake/common/is_approx_equal_abstol.h"
#include "drake/geometry/read_obj.h"
#include "drake/solvers/solve.h"
namespace drake {
namespace geometry {
namespace optimization {
using Eigen::Matrix3Xd;
using Eigen::MatrixXd;
using Eigen::RowVectorXd;
using Eigen::Vector3d;
using Eigen::VectorXd;
using math::RigidTransformd;
using solvers::Binding;
using solvers::Constraint;
using solvers::MathematicalProgram;
using solvers::VectorXDecisionVariable;
using symbolic::Variable;
namespace {
/* Given a matrix containing a set of 2D vertices, return a copy
of the matrix where the vertices are ordered counter-clockwise
from the negative X axis. */
MatrixXd OrderCounterClockwise(const MatrixXd& vertices) {
const size_t dim = vertices.rows();
const size_t num_vertices = vertices.cols();
DRAKE_DEMAND(dim == 2);
std::vector<size_t> indices(num_vertices);
std::vector<double> angles(num_vertices);
double center_x = 0;
double center_y = 0;
std::iota(indices.begin(), indices.end(), 0);
for (const auto& i : indices) {
center_x += vertices.col(i)[0];
center_y += vertices.col(i)[1];
}
center_x /= num_vertices;
center_y /= num_vertices;
for (const auto& i : indices) {
const double x = vertices.col(i)[0] - center_x;
const double y = vertices.col(i)[1] - center_y;
angles[i] = std::atan2(y, x);
}
std::sort(indices.begin(), indices.end(), [&angles](size_t a, size_t b) {
return angles[a] > angles[b];
});
MatrixXd sorted_vertices(dim, num_vertices);
for (size_t i = 0; i < num_vertices; ++i) {
sorted_vertices.col(i) = vertices.col(indices[i]);
}
return sorted_vertices;
}
MatrixXd GetConvexHullFromObjFile(const std::string& filename,
const std::string& extension, double scale,
std::string_view prefix) {
if (extension != ".obj") {
throw std::runtime_error(fmt::format(
"{} can only use mesh shapes (i.e.., Convex, Mesh) with a .obj file "
"type; given '{}'.",
prefix, filename));
}
const auto [tinyobj_vertices, faces, num_faces] =
internal::ReadObjFile(filename, scale, /* triangulate = */ false);
unused(faces);
unused(num_faces);
orgQhull::Qhull qhull;
const int dim = 3;
std::vector<double> tinyobj_vertices_flat(tinyobj_vertices->size() * dim);
for (int i = 0; i < ssize(*tinyobj_vertices); ++i) {
for (int j = 0; j < dim; ++j) {
tinyobj_vertices_flat[dim * i + j] = (*tinyobj_vertices)[i](j);
}
}
qhull.runQhull("", dim, tinyobj_vertices->size(),
tinyobj_vertices_flat.data(), "");
if (qhull.qhullStatus() != 0) {
throw std::runtime_error(
fmt::format("Qhull terminated with status {} and message:\n{}",
qhull.qhullStatus(), qhull.qhullMessage()));
}
Matrix3Xd vertices(3, qhull.vertexCount());
int vertex_count = 0;
for (const auto& qhull_vertex : qhull.vertexList()) {
vertices.col(vertex_count++) =
Eigen::Map<Vector3d>(qhull_vertex.point().toStdVector().data());
}
return vertices;
}
} // namespace
VPolytope::VPolytope() : VPolytope(MatrixXd(0, 0)) {}
VPolytope::VPolytope(const Eigen::Ref<const MatrixXd>& vertices)
: ConvexSet(vertices.rows()), vertices_(vertices) {}
VPolytope::VPolytope(const QueryObject<double>& query_object,
GeometryId geometry_id,
std::optional<FrameId> reference_frame)
: ConvexSet(3) {
Matrix3Xd vertices;
query_object.inspector().GetShape(geometry_id).Reify(this, &vertices);
const RigidTransformd X_WE =
reference_frame ? query_object.GetPoseInWorld(*reference_frame)
: RigidTransformd::Identity();
const RigidTransformd& X_WG = query_object.GetPoseInWorld(geometry_id);
const RigidTransformd X_EG = X_WE.InvertAndCompose(X_WG);
vertices_ = X_EG * vertices;
}
VPolytope::VPolytope(const HPolyhedron& hpoly)
: ConvexSet(hpoly.ambient_dimension()) {
DRAKE_THROW_UNLESS(hpoly.IsBounded());
MatrixXd coeffs(hpoly.A().rows(), hpoly.A().cols() + 1);
coeffs.leftCols(hpoly.A().cols()) = hpoly.A();
coeffs.col(hpoly.A().cols()) = -hpoly.b();
MatrixXd coeffs_t = coeffs.transpose();
std::vector<double> flat_coeffs;
flat_coeffs.resize(coeffs_t.size());
VectorXd::Map(&flat_coeffs[0], coeffs_t.size()) =
VectorXd::Map(coeffs_t.data(), coeffs_t.size());
VectorXd eigen_center = hpoly.ChebyshevCenter();
std::vector<double> center;
center.resize(eigen_center.size());
VectorXd::Map(¢er[0], eigen_center.size()) = eigen_center;
orgQhull::Qhull qhull;
qhull.setFeasiblePoint(orgQhull::Coordinates(center));
// By default, Qhull takes in a sequence of vertices and generates a convex
// hull from them. Alternatively it can generate the convex hull from a
// sequence of halfspaces (requested via the "H" argument). In that case the
// inputs are overloaded with the `pointDimension` representing the dimension
// the convex hull exists in plus the offset and the `pointCount`
// representing the number of faces. Slightly more documentation can be found
// here: http://www.qhull.org/html/qhull.htm.
qhull.runQhull("", hpoly.A().cols() + 1, hpoly.A().rows(), flat_coeffs.data(),
"H");
if (qhull.qhullStatus() != 0) {
throw std::runtime_error(
fmt::format("Qhull terminated with status {} and message:\n{}",
qhull.qhullStatus(), qhull.qhullMessage()));
}
// Qhull flips some notation when you use the halfspace intersection:
// http://www.qhull.org/html/qh-code.htm#facet-cpp . Each facet from qhull
// represents an intersection between halfspaces of the H polyhedron.
// However, I could not figure out if each QhullFacet stored the exact
// location of the intersection (i.e. the vertex). Instead, this code takes
// each intersection of hyperplanes (QhullFacet), pulls out the hyperplanes
// that are part of the intersection (facet.vertices()) and solves for the
// vertex that lies at the intersection of these hyperplanes.
vertices_.resize(hpoly.ambient_dimension(), qhull.facetCount());
int ii = 0;
for (const auto& facet : qhull.facetList()) {
auto incident_hyperplanes = facet.vertices();
MatrixXd vertex_A(incident_hyperplanes.count(), hpoly.ambient_dimension());
for (int jj = 0; jj < incident_hyperplanes.count(); jj++) {
std::vector<double> hyperplane =
incident_hyperplanes.at(jj).point().toStdVector();
vertex_A.row(jj) = Eigen::Map<Eigen::RowVectorXd, Eigen::Unaligned>(
hyperplane.data(), hyperplane.size());
}
vertices_.col(ii) = vertex_A.partialPivLu().solve(
VectorXd::Ones(incident_hyperplanes.count())) +
eigen_center;
ii++;
}
}
VPolytope::~VPolytope() = default;
VPolytope VPolytope::MakeBox(const Eigen::Ref<const VectorXd>& lb,
const Eigen::Ref<const VectorXd>& ub) {
DRAKE_THROW_UNLESS(lb.size() == ub.size());
DRAKE_THROW_UNLESS((lb.array() <= ub.array()).all());
const int n = lb.size();
DRAKE_THROW_UNLESS(n > 0);
// Make sure that n is small enough to avoid overflow
DRAKE_THROW_UNLESS(n <= static_cast<int>(sizeof(Eigen::Index)) * 8 - 2);
// Create all 2^n vertices.
MatrixXd vertices = lb.replicate(1, 1 << n);
for (int i = 1; i < vertices.cols(); ++i) {
for (int j = 0; j < n; j++) {
if (i >> j & 1) {
vertices(j, i) = ub[j];
}
}
}
return VPolytope(vertices);
}
VPolytope VPolytope::MakeUnitBox(int dim) {
return MakeBox(VectorXd::Constant(dim, -1.0), VectorXd::Constant(dim, 1.0));
}
VPolytope VPolytope::GetMinimalRepresentation() const {
if (ambient_dimension() == 0) {
return VPolytope();
}
orgQhull::Qhull qhull;
qhull.runQhull("", vertices_.rows(), vertices_.cols(), vertices_.data(), "");
if (qhull.qhullStatus() != 0) {
throw std::runtime_error(
fmt::format("Qhull terminated with status {} and message:\n{}",
qhull.qhullStatus(), qhull.qhullMessage()));
}
MatrixXd minimal_vertices(vertices_.rows(), qhull.vertexCount());
size_t j = 0;
for (const auto& qhull_vertex : qhull.vertexList()) {
size_t i = 0;
for (const auto& val : qhull_vertex.point()) {
minimal_vertices(i, j) = val;
++i;
}
++j;
}
// The qhull C++ interface iterates over the vertices in no specific order.
// For the 2D case, reorder the vertices according to the counter-clockwise
// convention.
if (vertices_.rows() == 2) {
minimal_vertices = OrderCounterClockwise(minimal_vertices);
}
return VPolytope(minimal_vertices);
}
double VPolytope::CalcVolume() const {
if (ambient_dimension() == 0) {
return 0.0;
}
orgQhull::Qhull qhull;
try {
qhull.runQhull("", ambient_dimension(), vertices_.cols(), vertices_.data(),
"");
} catch (const orgQhull::QhullError& e) {
if (e.errorCode() == qh_ERRsingular) {
// The convex hull is singular. It has 0 volume.
return 0;
}
}
if (qhull.qhullStatus() != 0) {
throw std::runtime_error(
fmt::format("Qhull terminated with status {} and message:\n{}",
qhull.qhullStatus(), qhull.qhullMessage()));
}
return qhull.volume();
}
void VPolytope::WriteObj(const std::filesystem::path& filename) const {
DRAKE_THROW_UNLESS(ambient_dimension() == 3);
const Vector3d center = vertices_.rowwise().mean();
orgQhull::Qhull qhull;
// http://www.qhull.org/html/qh-quick.htm#options
// Pp avoids complaining about precision (it was used by trimesh).
// Qt requests a triangulation.
constexpr char qhull_options[] = "Pp Qt";
qhull.runQhull("", vertices_.rows(), vertices_.cols(), vertices_.data(),
qhull_options);
if (qhull.qhullStatus() != 0) {
throw std::runtime_error(
fmt::format("Qhull terminated with status {} and message:\n{}",
qhull.qhullStatus(), qhull.qhullMessage()));
}
std::ofstream file;
file.exceptions(~std::ofstream::goodbit);
file.open(filename);
std::vector<int> vertex_id_to_index(qhull.vertexCount() + 1);
int index = 1;
for (const auto& vertex : qhull.vertexList()) {
fmt::print(file, "v {}\n", fmt::join(vertex.point(), " "));
vertex_id_to_index.at(vertex.id()) = index++;
}
for (const auto& facet : qhull.facetList()) {
DRAKE_DEMAND(facet.vertices().size() == 3);
// Map the Qhull IDs into the obj file's "v" indices.
const orgQhull::QhullVertex& v0 = facet.vertices()[0];
const orgQhull::QhullVertex& v1 = facet.vertices()[1];
const orgQhull::QhullVertex& v2 = facet.vertices()[2];
std::array<int, 3> face_indices = {
vertex_id_to_index.at(v0.id()),
vertex_id_to_index.at(v1.id()),
vertex_id_to_index.at(v2.id()),
};
// Adjust the normal to point away from the center.
const Eigen::Map<Vector3d> a(v0.point().coordinates());
const Eigen::Map<Vector3d> b(v1.point().coordinates());
const Eigen::Map<Vector3d> c(v2.point().coordinates());
const Vector3d normal = (b - a).cross(c - a);
if (normal.dot(a - center) < 0) {
std::swap(face_indices[0], face_indices[1]);
}
fmt::print(file, "f {}\n", fmt::join(face_indices, " "));
}
file.close();
}
std::unique_ptr<ConvexSet> VPolytope::DoClone() const {
return std::make_unique<VPolytope>(*this);
}
bool VPolytope::DoIsBounded() const {
return true;
}
bool VPolytope::DoIsEmpty() const {
return vertices_.cols() == 0;
}
std::optional<VectorXd> VPolytope::DoMaybeGetPoint() const {
if (vertices_.cols() == 1) {
return vertices_.col(0);
}
return std::nullopt;
}
std::optional<VectorXd> VPolytope::DoMaybeGetFeasiblePoint() const {
if (IsEmpty()) {
return std::nullopt;
} else {
return vertices_.col(0);
}
}
bool VPolytope::DoPointInSet(const Eigen::Ref<const VectorXd>& x,
double tol) const {
if (vertices_.cols() == 0) {
return false;
}
const int n = ambient_dimension();
const int m = vertices_.cols();
const double inf = std::numeric_limits<double>::infinity();
// min z s.t. |(v α - x)ᵢ| ≤ z, αᵢ ≥ 0, ∑ᵢ αᵢ = 1.
MathematicalProgram prog;
VectorXDecisionVariable z = prog.NewContinuousVariables<1>("z");
VectorXDecisionVariable alpha = prog.NewContinuousVariables(m, "a");
// min z
prog.AddLinearCost(Vector1d(1.0), z);
// |(v α - x)ᵢ| ≤ z as -z ≤ vᵢ α - xᵢ ≤ z as vᵢ α - z ≤ xᵢ && xᵢ ≤ vᵢ α + z
MatrixXd A(n, m + 1);
A.leftCols(m) = vertices_;
A.col(m) = -VectorXd::Ones(n);
prog.AddLinearConstraint(A, VectorXd::Constant(n, -inf), x, {alpha, z});
A.col(m) = VectorXd::Ones(n);
prog.AddLinearConstraint(A, x, VectorXd::Constant(n, inf), {alpha, z});
// 0 ≤ αᵢ ≤ 1. The one is redundant, but may be better than inf for some
// solvers.
prog.AddBoundingBoxConstraint(0, 1.0, alpha);
// ∑ᵢ αᵢ = 1
prog.AddLinearEqualityConstraint(RowVectorXd::Ones(m), 1.0, alpha);
auto result = solvers::Solve(prog);
// The formulation was chosen so that it always has a feasible solution.
DRAKE_DEMAND(result.is_success());
// To decouple the solver tolerance from the requested tolerance, we solve the
// LP, but then evaluate the constraints ourselves.
// Note: The max(alpha, 0) and normalization were required for Gurobi.
const VectorXd alpha_sol = result.GetSolution(alpha).cwiseMax(0);
const VectorXd x_sol = vertices_ * alpha_sol / (alpha_sol.sum());
return is_approx_equal_abstol(x, x_sol, tol);
}
std::pair<VectorX<Variable>, std::vector<Binding<Constraint>>>
VPolytope::DoAddPointInSetConstraints(
solvers::MathematicalProgram* prog,
const Eigen::Ref<const solvers::VectorXDecisionVariable>& x) const {
std::vector<Binding<Constraint>> new_constraints;
const int n = ambient_dimension();
const int m = vertices_.cols();
VectorXDecisionVariable alpha = prog->NewContinuousVariables(m, "a");
// 0 ≤ αᵢ ≤ 1. The one is redundant, but may be better than inf for some
// solvers.
new_constraints.push_back(prog->AddBoundingBoxConstraint(0, 1.0, alpha));
// v α - x = 0.
MatrixXd A(n, m + n);
A.leftCols(m) = vertices_;
A.rightCols(n) = -MatrixXd::Identity(n, n);
new_constraints.push_back(
prog->AddLinearEqualityConstraint(A, VectorXd::Zero(n), {alpha, x}));
// ∑ αᵢ = 1.
new_constraints.push_back(
prog->AddLinearEqualityConstraint(RowVectorXd::Ones(m), 1.0, alpha));
return {std::move(alpha), std::move(new_constraints)};
}
std::vector<Binding<Constraint>>
VPolytope::DoAddPointInNonnegativeScalingConstraints(
solvers::MathematicalProgram* prog,
const Eigen::Ref<const solvers::VectorXDecisionVariable>& x,
const Variable& t) const {
std::vector<Binding<Constraint>> constraints;
const int n = ambient_dimension();
const int m = vertices_.cols();
VectorXDecisionVariable alpha = prog->NewContinuousVariables(m, "a");
// αᵢ ≥ 0.
constraints.emplace_back(prog->AddBoundingBoxConstraint(
0, std::numeric_limits<double>::infinity(), alpha));
// v α = x.
MatrixXd A(n, m + n);
A.leftCols(m) = vertices_;
A.rightCols(n) = -MatrixXd::Identity(n, n);
constraints.emplace_back(
prog->AddLinearEqualityConstraint(A, VectorXd::Zero(n), {alpha, x}));
// ∑ αᵢ = t.
RowVectorXd a = RowVectorXd::Ones(m + 1);
a[m] = -1;
constraints.emplace_back(
prog->AddLinearEqualityConstraint(a, 0.0, {alpha, Vector1<Variable>(t)}));
return constraints;
}
std::vector<Binding<Constraint>>
VPolytope::DoAddPointInNonnegativeScalingConstraints(
solvers::MathematicalProgram* prog, const Eigen::Ref<const MatrixXd>& A,
const Eigen::Ref<const VectorXd>& b, const Eigen::Ref<const VectorXd>& c,
double d, const Eigen::Ref<const VectorXDecisionVariable>& x,
const Eigen::Ref<const VectorXDecisionVariable>& t) const {
std::vector<Binding<Constraint>> constraints;
const int n = ambient_dimension();
const int m = vertices_.cols();
VectorXDecisionVariable alpha = prog->NewContinuousVariables(m, "a");
// αᵢ ≥ 0.
constraints.emplace_back(prog->AddBoundingBoxConstraint(
0, std::numeric_limits<double>::infinity(), alpha));
// v α = A * x + b.
MatrixXd A_combination(n, m + x.size());
A_combination.leftCols(m) = vertices_;
A_combination.rightCols(x.size()) = -A;
constraints.emplace_back(
prog->AddLinearEqualityConstraint(A_combination, b, {alpha, x}));
// ∑ αᵢ = c' * t + d.
RowVectorXd a = RowVectorXd::Ones(m + t.size());
a.tail(t.size()) = -c.transpose();
constraints.emplace_back(prog->AddLinearEqualityConstraint(a, d, {alpha, t}));
return constraints;
}
std::pair<std::unique_ptr<Shape>, math::RigidTransformd>
VPolytope::DoToShapeWithPose() const {
throw std::runtime_error(
"ToShapeWithPose is not implemented yet for VPolytope. Implementing "
"this will likely require additional support from the Convex shape "
"class (to support in-memory mesh data, or file I/O).");
}
void VPolytope::ImplementGeometry(const Box& box, void* data) {
const double x = box.width() / 2.0;
const double y = box.depth() / 2.0;
const double z = box.height() / 2.0;
DRAKE_ASSERT(data != nullptr);
Matrix3Xd* vertices = static_cast<Matrix3Xd*>(data);
vertices->resize(3, 8);
// clang-format off
*vertices << -x, x, x, -x, -x, x, x, -x,
y, y, -y, -y, -y, -y, y, y,
-z, -z, -z, -z, z, z, z, z;
// clang-format on
}
void VPolytope::ImplementGeometry(const Convex& convex, void* data) {
DRAKE_ASSERT(data != nullptr);
Matrix3Xd* vertex_data = static_cast<Matrix3Xd*>(data);
*vertex_data = GetConvexHullFromObjFile(convex.filename(), convex.extension(),
convex.scale(), "VPolytope");
}
void VPolytope::ImplementGeometry(const Mesh& mesh, void* data) {
DRAKE_ASSERT(data != nullptr);
Matrix3Xd* vertex_data = static_cast<Matrix3Xd*>(data);
*vertex_data = GetConvexHullFromObjFile(mesh.filename(), mesh.extension(),
mesh.scale(), "VPolytope");
}
MatrixXd GetVertices(const Convex& convex) {
return GetConvexHullFromObjFile(convex.filename(), convex.extension(),
convex.scale(), "GetVertices()");
}
} // namespace optimization
} // namespace geometry
} // namespace drake
<file_sep>/bindings/pydrake/common/text_logging_pybind.h
#pragma once
namespace drake {
namespace pydrake {
namespace internal {
/* If possible, redirects Drake's C++ logs to Python's `logging` module. */
void MaybeRedirectPythonLogging();
} // namespace internal
} // namespace pydrake
} // namespace drake
<file_sep>/geometry/render_gltf_client/test/render_engine_gltf_client_params_test.cc
#include "drake/geometry/render_gltf_client/render_engine_gltf_client_params.h"
#include <gtest/gtest.h>
namespace drake {
namespace geometry {
namespace {
GTEST_TEST(RenderEngineGltfClientParams, GetUrl) {
struct TestData {
std::string base_url;
std::string render_endpoint;
std::string expected_full_url;
};
std::vector<TestData> all_test_cases{{
// Check that sandwiched slashes are added or removed correctly.
{"127.0.0.1:8000", "render", "127.0.0.1:8000/render"},
{"127.0.0.1:8000/", "render", "127.0.0.1:8000/render"},
{"127.0.0.1:8000//", "render", "127.0.0.1:8000/render"},
{"127.0.0.1:8000", "/render", "127.0.0.1:8000/render"},
{"127.0.0.1:8000", "//render", "127.0.0.1:8000/render"},
{"127.0.0.1:8000/", "/render", "127.0.0.1:8000/render"},
{"127.0.0.1:8000//", "//render", "127.0.0.1:8000/render"},
// Check that an empty (or vacuous) endpoint is allowed.
{"127.0.0.1:8000", "", "127.0.0.1:8000/"},
{"127.0.0.1:8000", "/", "127.0.0.1:8000/"},
{"127.0.0.1:8000", "//", "127.0.0.1:8000/"},
{"127.0.0.1:8000//", "//", "127.0.0.1:8000/"},
// Check that non-sandwiched slashes in are kept as-is.
{"127.0.0.1:8000", "render/", "127.0.0.1:8000/render/"},
{"/127.0.0.1:8000", "render", "/127.0.0.1:8000/render"},
{"http://host:8000", "render", "http://host:8000/render"},
// A questionable base_url still produces the specified results.
{"", "", "/"},
{"///", "///", "/"},
{"///", "render", "/render"},
}};
for (const auto& one_case : all_test_cases) {
RenderEngineGltfClientParams dut;
dut.base_url = one_case.base_url;
dut.render_endpoint = one_case.render_endpoint;
EXPECT_EQ(dut.GetUrl(), one_case.expected_full_url);
}
}
} // namespace
} // namespace geometry
} // namespace drake
<file_sep>/bindings/pydrake/geometry/geometry_py_optimization.cc
/* @file The contains all of the public entities found in the
drake::geometry::optimization namespace. They can be found in the
pydrake.geometry.optimization module. */
#include "drake/bindings/pydrake/common/default_scalars_pybind.h"
#include "drake/bindings/pydrake/common/deprecation_pybind.h"
#include "drake/bindings/pydrake/common/identifier_pybind.h"
#include "drake/bindings/pydrake/documentation_pybind.h"
#include "drake/bindings/pydrake/geometry/geometry_py.h"
#include "drake/bindings/pydrake/geometry/optimization_pybind.h"
#include "drake/common/yaml/yaml_io.h"
#include "drake/geometry/optimization/cartesian_product.h"
#include "drake/geometry/optimization/graph_of_convex_sets.h"
#include "drake/geometry/optimization/hpolyhedron.h"
#include "drake/geometry/optimization/hyperellipsoid.h"
#include "drake/geometry/optimization/intersection.h"
#include "drake/geometry/optimization/iris.h"
#include "drake/geometry/optimization/minkowski_sum.h"
#include "drake/geometry/optimization/point.h"
#include "drake/geometry/optimization/spectrahedron.h"
#include "drake/geometry/optimization/vpolytope.h"
namespace drake {
namespace pydrake {
void DefineGeometryOptimization(py::module m) {
// NOLINTNEXTLINE(build/namespaces): Emulate placement in namespace.
using namespace drake;
// NOLINTNEXTLINE(build/namespaces): Emulate placement in namespace.
using namespace drake::geometry;
// NOLINTNEXTLINE(build/namespaces): Emulate placement in namespace.
using namespace drake::geometry::optimization;
m.doc() = "Local bindings for `drake::geometry::optimization`";
constexpr auto& doc = pydrake_doc.drake.geometry.optimization;
py::module::import("pydrake.solvers");
// ConvexSet
{
const auto& cls_doc = doc.ConvexSet;
py::class_<ConvexSet>(m, "ConvexSet", cls_doc.doc)
.def("Clone", &ConvexSet::Clone, cls_doc.Clone.doc)
.def("ambient_dimension", &ConvexSet::ambient_dimension,
cls_doc.ambient_dimension.doc)
.def("IntersectsWith", &ConvexSet::IntersectsWith, py::arg("other"),
cls_doc.IntersectsWith.doc)
.def("IsBounded", &ConvexSet::IsBounded, cls_doc.IsBounded.doc)
.def("IsEmpty", &ConvexSet::IsEmpty, cls_doc.IsEmpty.doc)
.def("MaybeGetPoint", &ConvexSet::MaybeGetPoint,
cls_doc.MaybeGetPoint.doc)
.def("MaybeGetFeasiblePoint", &ConvexSet::MaybeGetFeasiblePoint,
cls_doc.MaybeGetFeasiblePoint.doc)
.def("PointInSet", &ConvexSet::PointInSet, py::arg("x"),
py::arg("tol") = 1e-8, cls_doc.PointInSet.doc)
.def("AddPointInSetConstraints", &ConvexSet::AddPointInSetConstraints,
py::arg("prog"), py::arg("vars"),
cls_doc.AddPointInSetConstraints.doc)
.def("AddPointInNonnegativeScalingConstraints",
overload_cast_explicit<
std::vector<solvers::Binding<solvers::Constraint>>,
solvers::MathematicalProgram*,
const Eigen::Ref<const solvers::VectorXDecisionVariable>&,
const symbolic::Variable&>(
&ConvexSet::AddPointInNonnegativeScalingConstraints),
py::arg("prog"), py::arg("x"), py::arg("t"),
cls_doc.AddPointInNonnegativeScalingConstraints.doc_3args)
.def("AddPointInNonnegativeScalingConstraints",
overload_cast_explicit<
std::vector<solvers::Binding<solvers::Constraint>>,
solvers::MathematicalProgram*,
const Eigen::Ref<const Eigen::MatrixXd>&,
const Eigen::Ref<const Eigen::VectorXd>&,
const Eigen::Ref<const Eigen::VectorXd>&, double,
const Eigen::Ref<const solvers::VectorXDecisionVariable>&,
const Eigen::Ref<const solvers::VectorXDecisionVariable>&>(
&ConvexSet::AddPointInNonnegativeScalingConstraints),
py::arg("prog"), py::arg("A"), py::arg("b"), py::arg("c"),
py::arg("d"), py::arg("x"), py::arg("t"),
cls_doc.AddPointInNonnegativeScalingConstraints.doc_7args)
.def("ToShapeWithPose", &ConvexSet::ToShapeWithPose,
cls_doc.ToShapeWithPose.doc);
}
// CartesianProduct
{
const auto& cls_doc = doc.CartesianProduct;
py::class_<CartesianProduct, ConvexSet>(m, "CartesianProduct", cls_doc.doc)
.def(py::init<>(), cls_doc.ctor.doc_0args)
.def(py::init([](const std::vector<ConvexSet*>& sets) {
return std::make_unique<CartesianProduct>(CloneConvexSets(sets));
}),
py::arg("sets"), cls_doc.ctor.doc_1args_sets)
.def(py::init<const ConvexSet&, const ConvexSet&>(), py::arg("setA"),
py::arg("setB"), cls_doc.ctor.doc_2args_setA_setB)
.def(py::init([](const std::vector<ConvexSet*>& sets,
const Eigen::Ref<const Eigen::MatrixXd>& A,
const Eigen::Ref<const Eigen::VectorXd>& b) {
return std::make_unique<CartesianProduct>(
CloneConvexSets(sets), A, b);
}),
py::arg("sets"), py::arg("A"), py::arg("b"),
cls_doc.ctor.doc_3args_sets_A_b)
.def(py::init<const QueryObject<double>&, GeometryId,
std::optional<FrameId>>(),
py::arg("query_object"), py::arg("geometry_id"),
py::arg("reference_frame") = std::nullopt,
cls_doc.ctor.doc_3args_query_object_geometry_id_reference_frame)
.def("num_factors", &CartesianProduct::num_factors,
cls_doc.num_factors.doc)
.def("factor", &CartesianProduct::factor, py_rvp::reference_internal,
py::arg("index"), cls_doc.factor.doc);
}
// HPolyhedron
{
const auto& cls_doc = doc.HPolyhedron;
py::class_<HPolyhedron, ConvexSet>(m, "HPolyhedron", cls_doc.doc)
.def(py::init<>(), cls_doc.ctor.doc_0args)
.def(py::init<const Eigen::Ref<const Eigen::MatrixXd>&,
const Eigen::Ref<const Eigen::VectorXd>&>(),
py::arg("A"), py::arg("b"), cls_doc.ctor.doc_2args)
.def(py::init<const QueryObject<double>&, GeometryId,
std::optional<FrameId>>(),
py::arg("query_object"), py::arg("geometry_id"),
py::arg("reference_frame") = std::nullopt, cls_doc.ctor.doc_3args)
.def(py::init<const VPolytope&>(), py::arg("vpoly"),
cls_doc.ctor.doc_1args)
.def("A", &HPolyhedron::A, cls_doc.A.doc)
.def("b", &HPolyhedron::b, cls_doc.b.doc)
.def("ContainedIn", &HPolyhedron::ContainedIn, py::arg("other"),
py::arg("tol") = 1E-9, cls_doc.ContainedIn.doc)
.def("Intersection", &HPolyhedron::Intersection, py::arg("other"),
py::arg("check_for_redundancy") = false, py::arg("tol") = 1E-9,
cls_doc.Intersection.doc)
.def("ReduceInequalities", &HPolyhedron::ReduceInequalities,
py::arg("tol") = 1E-9, cls_doc.ReduceInequalities.doc)
.def("FindRedundant", &HPolyhedron::FindRedundant,
py::arg("tol") = 1E-9, cls_doc.FindRedundant.doc)
.def("MaximumVolumeInscribedEllipsoid",
&HPolyhedron::MaximumVolumeInscribedEllipsoid,
cls_doc.MaximumVolumeInscribedEllipsoid.doc)
.def("ChebyshevCenter", &HPolyhedron::ChebyshevCenter,
cls_doc.ChebyshevCenter.doc)
.def("Scale", &HPolyhedron::Scale, py::arg("scale"),
py::arg("center") = std::nullopt, cls_doc.Scale.doc)
.def("CartesianProduct", &HPolyhedron::CartesianProduct,
py::arg("other"), cls_doc.CartesianProduct.doc)
.def("CartesianPower", &HPolyhedron::CartesianPower, py::arg("n"),
cls_doc.CartesianPower.doc)
.def("PontryaginDifference", &HPolyhedron::PontryaginDifference,
py::arg("other"), cls_doc.PontryaginDifference.doc)
.def("UniformSample",
overload_cast_explicit<Eigen::VectorXd, RandomGenerator*,
const Eigen::Ref<const Eigen::VectorXd>&>(
&HPolyhedron::UniformSample),
py::arg("generator"), py::arg("previous_sample"),
cls_doc.UniformSample.doc_2args)
.def("UniformSample",
overload_cast_explicit<Eigen::VectorXd, RandomGenerator*>(
&HPolyhedron::UniformSample),
py::arg("generator"), cls_doc.UniformSample.doc_1args)
.def_static("MakeBox", &HPolyhedron::MakeBox, py::arg("lb"),
py::arg("ub"), cls_doc.MakeBox.doc)
.def_static("MakeUnitBox", &HPolyhedron::MakeUnitBox, py::arg("dim"),
cls_doc.MakeUnitBox.doc)
.def_static("MakeL1Ball", &HPolyhedron::MakeL1Ball, py::arg("dim"),
cls_doc.MakeL1Ball.doc)
.def(py::pickle(
[](const HPolyhedron& self) {
return std::make_pair(self.A(), self.b());
},
[](std::pair<Eigen::MatrixXd, Eigen::VectorXd> args) {
return HPolyhedron(std::get<0>(args), std::get<1>(args));
}));
}
// Hyperellipsoid
{
const auto& cls_doc = doc.Hyperellipsoid;
py::class_<Hyperellipsoid, ConvexSet>(m, "Hyperellipsoid", cls_doc.doc)
.def(py::init<>(), cls_doc.ctor.doc_0args)
.def(py::init<const Eigen::Ref<const Eigen::MatrixXd>&,
const Eigen::Ref<const Eigen::VectorXd>&>(),
py::arg("A"), py::arg("center"), cls_doc.ctor.doc_2args)
.def(py::init<const QueryObject<double>&, GeometryId,
std::optional<FrameId>>(),
py::arg("query_object"), py::arg("geometry_id"),
py::arg("reference_frame") = std::nullopt, cls_doc.ctor.doc_3args)
.def("A", &Hyperellipsoid::A, cls_doc.A.doc)
.def("center", &Hyperellipsoid::center, cls_doc.center.doc)
.def("Volume", &Hyperellipsoid::Volume, cls_doc.Volume.doc)
.def("MinimumUniformScalingToTouch",
&Hyperellipsoid::MinimumUniformScalingToTouch, py::arg("other"),
cls_doc.MinimumUniformScalingToTouch.doc)
.def_static("MakeAxisAligned", &Hyperellipsoid::MakeAxisAligned,
py::arg("radius"), py::arg("center"), cls_doc.MakeAxisAligned.doc)
.def_static("MakeHypersphere", &Hyperellipsoid::MakeHypersphere,
py::arg("radius"), py::arg("center"), cls_doc.MakeHypersphere.doc)
.def_static("MakeUnitBall", &Hyperellipsoid::MakeUnitBall,
py::arg("dim"), cls_doc.MakeUnitBall.doc)
.def(py::pickle(
[](const Hyperellipsoid& self) {
return std::make_pair(self.A(), self.center());
},
[](std::pair<Eigen::MatrixXd, Eigen::VectorXd> args) {
return Hyperellipsoid(std::get<0>(args), std::get<1>(args));
}));
}
// Intersection
{
const auto& cls_doc = doc.Intersection;
py::class_<Intersection, ConvexSet>(m, "Intersection", cls_doc.doc)
.def(py::init<>(), cls_doc.ctor.doc_0args)
.def(py::init([](const std::vector<ConvexSet*>& sets) {
return std::make_unique<Intersection>(CloneConvexSets(sets));
}),
py::arg("sets"), cls_doc.ctor.doc_1args)
.def(py::init<const ConvexSet&, const ConvexSet&>(), py::arg("setA"),
py::arg("setB"), cls_doc.ctor.doc_2args)
.def("num_elements", &Intersection::num_elements,
cls_doc.num_elements.doc)
.def("element", &Intersection::element, py_rvp::reference_internal,
py::arg("index"), cls_doc.element.doc);
}
// MinkowskiSum
{
const auto& cls_doc = doc.MinkowskiSum;
py::class_<MinkowskiSum, ConvexSet>(m, "MinkowskiSum", cls_doc.doc)
.def(py::init<>(), cls_doc.ctor.doc_0args)
.def(py::init([](const std::vector<ConvexSet*>& sets) {
return std::make_unique<MinkowskiSum>(CloneConvexSets(sets));
}),
py::arg("sets"), cls_doc.ctor.doc_1args)
.def(py::init<const ConvexSet&, const ConvexSet&>(), py::arg("setA"),
py::arg("setB"), cls_doc.ctor.doc_2args)
.def(py::init<const QueryObject<double>&, GeometryId,
std::optional<FrameId>>(),
py::arg("query_object"), py::arg("geometry_id"),
py::arg("reference_frame") = std::nullopt, cls_doc.ctor.doc_3args)
.def("num_terms", &MinkowskiSum::num_terms, cls_doc.num_terms.doc)
.def("term", &MinkowskiSum::term, py_rvp::reference_internal,
py::arg("index"), cls_doc.term.doc);
}
// Point
{
const auto& cls_doc = doc.Point;
py::class_<Point, ConvexSet>(m, "Point", cls_doc.doc)
.def(py::init<>(), cls_doc.ctor.doc_0args)
.def(py::init<const Eigen::Ref<const Eigen::VectorXd>&>(), py::arg("x"),
cls_doc.ctor.doc_1args)
.def(py::init<const QueryObject<double>&, GeometryId,
std::optional<FrameId>, double>(),
py::arg("query_object"), py::arg("geometry_id"),
py::arg("reference_frame") = std::nullopt,
py::arg("maximum_allowable_radius") = 0.0, cls_doc.ctor.doc_4args)
.def("x", &Point::x, cls_doc.x.doc)
.def("set_x", &Point::set_x, py::arg("x"), cls_doc.set_x.doc)
.def(py::pickle([](const Point& self) { return self.x(); },
[](Eigen::VectorXd arg) { return Point(arg); }));
}
// Spectrahedron
{
const auto& cls_doc = doc.Spectrahedron;
py::class_<Spectrahedron, ConvexSet>(m, "Spectrahedron", cls_doc.doc)
.def(py::init<>(), cls_doc.ctor.doc_0args)
.def(py::init<const solvers::MathematicalProgram&>(), py::arg("prog"),
cls_doc.ctor.doc_1args);
}
// VPolytope
{
const auto& cls_doc = doc.VPolytope;
py::class_<VPolytope, ConvexSet>(m, "VPolytope", cls_doc.doc)
.def(py::init<>(), cls_doc.ctor.doc)
.def(py::init<const Eigen::Ref<const Eigen::MatrixXd>&>(),
py::arg("vertices"), cls_doc.ctor.doc_vertices)
.def(py::init<const HPolyhedron&>(), py::arg("H"),
cls_doc.ctor.doc_hpolyhedron)
.def(py::init<const QueryObject<double>&, GeometryId,
std::optional<FrameId>>(),
py::arg("query_object"), py::arg("geometry_id"),
py::arg("reference_frame") = std::nullopt,
cls_doc.ctor.doc_scenegraph)
.def("GetMinimalRepresentation", &VPolytope::GetMinimalRepresentation,
cls_doc.GetMinimalRepresentation.doc)
.def("vertices", &VPolytope::vertices, cls_doc.vertices.doc)
.def_static("MakeBox", &VPolytope::MakeBox, py::arg("lb"),
py::arg("ub"), cls_doc.MakeBox.doc)
.def_static("MakeUnitBox", &VPolytope::MakeUnitBox, py::arg("dim"),
cls_doc.MakeUnitBox.doc)
.def("CalcVolume", &VPolytope::CalcVolume, cls_doc.CalcVolume.doc)
.def("WriteObj", &VPolytope::WriteObj, py::arg("filename"),
cls_doc.WriteObj.doc)
.def(py::pickle([](const VPolytope& self) { return self.vertices(); },
[](Eigen::MatrixXd arg) { return VPolytope(arg); }));
}
{
const auto& cls_doc = doc.IrisOptions;
py::class_<IrisOptions> iris_options(m, "IrisOptions", cls_doc.doc);
iris_options.def(py::init<>(), cls_doc.ctor.doc)
.def_readwrite("require_sample_point_is_contained",
&IrisOptions::require_sample_point_is_contained,
cls_doc.require_sample_point_is_contained.doc)
.def_readwrite("iteration_limit", &IrisOptions::iteration_limit,
cls_doc.iteration_limit.doc)
.def_readwrite("termination_threshold",
&IrisOptions::termination_threshold,
cls_doc.termination_threshold.doc)
.def_readwrite("relative_termination_threshold",
&IrisOptions::relative_termination_threshold,
cls_doc.relative_termination_threshold.doc)
.def_readwrite("configuration_space_margin",
&IrisOptions::configuration_space_margin,
cls_doc.configuration_space_margin.doc)
.def_readwrite("num_collision_infeasible_samples",
&IrisOptions::num_collision_infeasible_samples,
cls_doc.num_collision_infeasible_samples.doc)
.def_property(
"configuration_obstacles",
[](const IrisOptions& self) {
std::vector<const ConvexSet*> convex_sets;
for (const copyable_unique_ptr<ConvexSet>& convex_set :
self.configuration_obstacles) {
convex_sets.push_back(convex_set.get());
}
py::object self_py = py::cast(self, py_rvp::reference);
// Keep alive, ownership: each item in `convex_sets` keeps `self`
// alive.
return py::cast(convex_sets, py_rvp::reference_internal, self_py);
},
[](IrisOptions& self, const std::vector<ConvexSet*>& sets) {
self.configuration_obstacles = CloneConvexSets(sets);
},
cls_doc.configuration_obstacles.doc)
.def_readwrite("starting_ellipse", &IrisOptions::starting_ellipse,
cls_doc.starting_ellipse.doc)
.def_readwrite("num_additional_constraint_infeasible_samples",
&IrisOptions::num_additional_constraint_infeasible_samples,
cls_doc.num_additional_constraint_infeasible_samples.doc)
.def_readwrite(
"random_seed", &IrisOptions::random_seed, cls_doc.random_seed.doc)
.def("__repr__", [](const IrisOptions& self) {
return py::str(
"IrisOptions("
"require_sample_point_is_contained={}, "
"iteration_limit={}, "
"termination_threshold={}, "
"relative_termination_threshold={}, "
"configuration_space_margin={}, "
"num_collision_infeasible_samples={}, "
"configuration_obstacles {}, "
"prog_with_additional_constraints {}, "
"num_additional_constraint_infeasible_samples={}, "
"random_seed={}"
")")
.format(self.require_sample_point_is_contained,
self.iteration_limit, self.termination_threshold,
self.relative_termination_threshold,
self.configuration_space_margin,
self.num_collision_infeasible_samples,
self.configuration_obstacles,
self.prog_with_additional_constraints ? "is set"
: "is not set",
self.num_additional_constraint_infeasible_samples,
self.random_seed);
});
DefReadWriteKeepAlive(&iris_options, "prog_with_additional_constraints",
&IrisOptions::prog_with_additional_constraints,
cls_doc.prog_with_additional_constraints.doc);
}
m.def(
"Iris",
[](const std::vector<ConvexSet*>& obstacles,
const Eigen::Ref<const Eigen::VectorXd>& sample,
const HPolyhedron& domain, const IrisOptions& options) {
return Iris(CloneConvexSets(obstacles), sample, domain, options);
},
py::arg("obstacles"), py::arg("sample"), py::arg("domain"),
py::arg("options") = IrisOptions(), doc.Iris.doc);
m.def(
"MakeIrisObstacles",
[](const QueryObject<double>& query_object,
std::optional<FrameId> reference_frame) {
std::vector<copyable_unique_ptr<ConvexSet>> copyable_result =
MakeIrisObstacles(query_object, reference_frame);
std::vector<std::unique_ptr<ConvexSet>> result(
std::make_move_iterator(copyable_result.begin()),
std::make_move_iterator(copyable_result.end()));
return result;
},
py::arg("query_object"), py::arg("reference_frame") = std::nullopt,
doc.MakeIrisObstacles.doc);
m.def("IrisInConfigurationSpace",
py::overload_cast<const multibody::MultibodyPlant<double>&,
const systems::Context<double>&, const IrisOptions&>(
&IrisInConfigurationSpace),
py::arg("plant"), py::arg("context"), py::arg("options") = IrisOptions(),
doc.IrisInConfigurationSpace.doc);
// TODO(#19597) Deprecate and remove these functions once Python
// can natively handle the file I/O.
m.def(
"SaveIrisRegionsYamlFile",
[](const std::filesystem::path& filename, const IrisRegions& regions,
const std::optional<std::string>& child_name) {
yaml::SaveYamlFile(filename, regions, child_name);
},
py::arg("filename"), py::arg("regions"),
py::arg("child_name") = std::nullopt,
"Calls SaveYamlFile() to serialize an IrisRegions object.");
m.def(
"LoadIrisRegionsYamlFile",
[](const std::filesystem::path& filename,
const std::optional<std::string>& child_name) {
return yaml::LoadYamlFile<IrisRegions>(filename, child_name);
},
py::arg("filename"), py::arg("child_name") = std::nullopt,
"Calls LoadYamlFile() to deserialize an IrisRegions object.");
// GraphOfConvexSetsOptions
{
const auto& cls_doc = doc.GraphOfConvexSetsOptions;
py::class_<GraphOfConvexSetsOptions> gcs_options(
m, "GraphOfConvexSetsOptions", cls_doc.doc);
gcs_options.def(py::init<>(), cls_doc.ctor.doc)
.def_readwrite("convex_relaxation",
&GraphOfConvexSetsOptions::convex_relaxation,
cls_doc.convex_relaxation.doc)
.def_readwrite("preprocessing",
&GraphOfConvexSetsOptions::preprocessing, cls_doc.preprocessing.doc)
.def_readwrite("max_rounded_paths",
&GraphOfConvexSetsOptions::max_rounded_paths,
cls_doc.max_rounded_paths.doc)
.def_readwrite("max_rounding_trials",
&GraphOfConvexSetsOptions::max_rounding_trials,
cls_doc.max_rounding_trials.doc)
.def_readwrite("flow_tolerance",
&GraphOfConvexSetsOptions::flow_tolerance,
cls_doc.flow_tolerance.doc)
.def_readwrite("rounding_seed",
&GraphOfConvexSetsOptions::rounding_seed, cls_doc.rounding_seed.doc)
.def_property("solver_options",
py::cpp_function(
[](GraphOfConvexSetsOptions& self) {
return &(self.solver_options);
},
py_rvp::reference_internal),
py::cpp_function([](GraphOfConvexSetsOptions& self,
solvers::SolverOptions solver_options) {
self.solver_options = std::move(solver_options);
}),
cls_doc.solver_options.doc)
.def_property("rounding_solver_options",
py::cpp_function(
[](GraphOfConvexSetsOptions& self) {
return &(self.rounding_solver_options);
},
py_rvp::reference_internal),
py::cpp_function(
[](GraphOfConvexSetsOptions& self,
solvers::SolverOptions rounding_solver_options) {
self.rounding_solver_options =
std::move(rounding_solver_options);
}),
cls_doc.rounding_solver_options.doc)
.def("__repr__", [](const GraphOfConvexSetsOptions& self) {
return py::str(
"GraphOfConvexSetsOptions("
"convex_relaxation={}, "
"preprocessing={}, "
"max_rounded_paths={}, "
"max_rounding_trials={}, "
"flow_tolerance={}, "
"rounding_seed={}, "
"solver={}, "
"solver_options={}, "
"rounding_solver_options={}, "
")")
.format(self.convex_relaxation, self.preprocessing,
self.max_rounded_paths, self.max_rounding_trials,
self.flow_tolerance, self.rounding_seed, self.solver,
self.solver_options, self.rounding_solver_options);
});
DefReadWriteKeepAlive(&gcs_options, "solver",
&GraphOfConvexSetsOptions::solver, cls_doc.solver.doc);
}
// GraphOfConvexSets
{
const auto& cls_doc = doc.GraphOfConvexSets;
py::class_<GraphOfConvexSets> graph_of_convex_sets(
m, "GraphOfConvexSets", cls_doc.doc);
BindIdentifier<GraphOfConvexSets::VertexId>(
graph_of_convex_sets, "VertexId", doc.GraphOfConvexSets.VertexId.doc);
BindIdentifier<GraphOfConvexSets::EdgeId>(
graph_of_convex_sets, "EdgeId", doc.GraphOfConvexSets.EdgeId.doc);
// Vertex
const auto& vertex_doc = doc.GraphOfConvexSets.Vertex;
py::class_<GraphOfConvexSets::Vertex>(
graph_of_convex_sets, "Vertex", vertex_doc.doc)
.def("id", &GraphOfConvexSets::Vertex::id, vertex_doc.id.doc)
.def("ambient_dimension", &GraphOfConvexSets::Vertex::ambient_dimension,
vertex_doc.ambient_dimension.doc)
.def("name", &GraphOfConvexSets::Vertex::name, vertex_doc.name.doc)
// As in trajectory_optimization_py.cc, we use a lambda to *copy*
// the decision variables; otherwise we get dtype=object arrays
// cannot be referenced.
.def(
"x",
[](const GraphOfConvexSets::Vertex& self)
-> const VectorX<symbolic::Variable> { return self.x(); },
vertex_doc.x.doc)
.def("set", &GraphOfConvexSets::Vertex::set, py_rvp::reference_internal,
vertex_doc.set.doc)
.def("AddCost",
py::overload_cast<const symbolic::Expression&>(
&GraphOfConvexSets::Vertex::AddCost),
py::arg("e"), vertex_doc.AddCost.doc_expression)
.def("AddCost",
py::overload_cast<const solvers::Binding<solvers::Cost>&>(
&GraphOfConvexSets::Vertex::AddCost),
py::arg("binding"), vertex_doc.AddCost.doc_binding)
.def("AddConstraint",
overload_cast_explicit<solvers::Binding<solvers::Constraint>,
const symbolic::Formula&>(
&GraphOfConvexSets::Vertex::AddConstraint),
py::arg("f"), vertex_doc.AddConstraint.doc_formula)
.def("AddConstraint",
overload_cast_explicit<solvers::Binding<solvers::Constraint>,
const solvers::Binding<solvers::Constraint>&>(
&GraphOfConvexSets::Vertex::AddConstraint),
py::arg("binding"), vertex_doc.AddCost.doc_binding)
.def("GetCosts", &GraphOfConvexSets::Vertex::GetCosts,
vertex_doc.GetCosts.doc)
.def("GetConstraints", &GraphOfConvexSets::Vertex::GetConstraints,
vertex_doc.GetConstraints.doc)
.def("GetSolutionCost", &GraphOfConvexSets::Vertex::GetSolutionCost,
py::arg("result"), vertex_doc.GetSolutionCost.doc)
.def("GetSolution", &GraphOfConvexSets::Vertex::GetSolution,
py::arg("result"), vertex_doc.GetSolution.doc)
.def("incoming_edges", &GraphOfConvexSets::Vertex::incoming_edges,
py_rvp::reference_internal, vertex_doc.incoming_edges.doc)
.def("outgoing_edges", &GraphOfConvexSets::Vertex::outgoing_edges,
py_rvp::reference_internal, vertex_doc.outgoing_edges.doc);
// Edge
const auto& edge_doc = doc.GraphOfConvexSets.Edge;
py::class_<GraphOfConvexSets::Edge>(
graph_of_convex_sets, "Edge", edge_doc.doc)
.def("id", &GraphOfConvexSets::Edge::id, edge_doc.id.doc)
.def("name", &GraphOfConvexSets::Edge::name, edge_doc.name.doc)
.def("u",
overload_cast_explicit<GraphOfConvexSets::Vertex&>(
&GraphOfConvexSets::Edge::u),
py_rvp::reference_internal, edge_doc.u.doc_0args_nonconst)
.def("v",
overload_cast_explicit<GraphOfConvexSets::Vertex&>(
&GraphOfConvexSets::Edge::v),
py_rvp::reference_internal, edge_doc.v.doc_0args_nonconst)
.def("phi", &GraphOfConvexSets::Edge::phi, py_rvp::reference_internal,
edge_doc.phi.doc)
.def(
"xu",
[](const GraphOfConvexSets::Edge& self)
-> const VectorX<symbolic::Variable> { return self.xu(); },
edge_doc.xu.doc)
.def(
"xv",
[](const GraphOfConvexSets::Edge& self)
-> const VectorX<symbolic::Variable> { return self.xv(); },
edge_doc.xv.doc)
.def("AddCost",
py::overload_cast<const symbolic::Expression&>(
&GraphOfConvexSets::Edge::AddCost),
py::arg("e"), edge_doc.AddCost.doc_expression)
.def("AddCost",
py::overload_cast<const solvers::Binding<solvers::Cost>&>(
&GraphOfConvexSets::Edge::AddCost),
py::arg("binding"), edge_doc.AddCost.doc_binding)
.def("AddConstraint",
overload_cast_explicit<solvers::Binding<solvers::Constraint>,
const symbolic::Formula&>(
&GraphOfConvexSets::Edge::AddConstraint),
py::arg("f"), edge_doc.AddConstraint.doc_formula)
.def("AddConstraint",
overload_cast_explicit<solvers::Binding<solvers::Constraint>,
const solvers::Binding<solvers::Constraint>&>(
&GraphOfConvexSets::Edge::AddConstraint),
py::arg("binding"), edge_doc.AddCost.doc_binding)
.def("AddPhiConstraint", &GraphOfConvexSets::Edge::AddPhiConstraint,
py::arg("phi_value"), edge_doc.AddPhiConstraint.doc)
.def("ClearPhiConstraints",
&GraphOfConvexSets::Edge::ClearPhiConstraints,
edge_doc.ClearPhiConstraints.doc)
.def("GetCosts", &GraphOfConvexSets::Edge::GetCosts,
edge_doc.GetCosts.doc)
.def("GetConstraints", &GraphOfConvexSets::Edge::GetConstraints,
edge_doc.GetConstraints.doc)
.def("GetSolutionCost", &GraphOfConvexSets::Edge::GetSolutionCost,
py::arg("result"), edge_doc.GetSolutionCost.doc)
.def("GetSolutionPhiXu", &GraphOfConvexSets::Edge::GetSolutionPhiXu,
py::arg("result"), edge_doc.GetSolutionPhiXu.doc)
.def("GetSolutionPhiXv", &GraphOfConvexSets::Edge::GetSolutionPhiXv,
py::arg("result"), edge_doc.GetSolutionPhiXv.doc);
graph_of_convex_sets // BR
.def(py::init<>(), cls_doc.ctor.doc)
.def("AddVertex", &GraphOfConvexSets::AddVertex, py::arg("set"),
py::arg("name") = "", py_rvp::reference_internal,
cls_doc.AddVertex.doc)
.def("AddEdge",
py::overload_cast<GraphOfConvexSets::Vertex*,
GraphOfConvexSets::Vertex*, std::string>(
&GraphOfConvexSets::AddEdge),
py::arg("u"), py::arg("v"), py::arg("name") = "",
py_rvp::reference_internal, cls_doc.AddEdge.doc)
.def("RemoveVertex",
py::overload_cast<GraphOfConvexSets::Vertex*>(
&GraphOfConvexSets::RemoveVertex),
py::arg("vertex"), cls_doc.RemoveVertex.doc)
.def("RemoveEdge",
py::overload_cast<GraphOfConvexSets::Edge*>(
&GraphOfConvexSets::RemoveEdge),
py::arg("edge"), cls_doc.RemoveEdge.doc)
.def("Vertices",
overload_cast_explicit<std::vector<GraphOfConvexSets::Vertex*>>(
&GraphOfConvexSets::Vertices),
py_rvp::reference_internal, cls_doc.Vertices.doc)
.def("Edges",
overload_cast_explicit<std::vector<GraphOfConvexSets::Edge*>>(
&GraphOfConvexSets::Edges),
py_rvp::reference_internal, cls_doc.Edges.doc)
.def("ClearAllPhiConstraints",
&GraphOfConvexSets::ClearAllPhiConstraints,
cls_doc.ClearAllPhiConstraints.doc)
.def("GetGraphvizString", &GraphOfConvexSets::GetGraphvizString,
py::arg("result") = std::nullopt, py::arg("show_slacks") = true,
py::arg("precision") = 3, py::arg("scientific") = false,
cls_doc.GetGraphvizString.doc)
.def("SolveShortestPath",
overload_cast_explicit<solvers::MathematicalProgramResult,
const GraphOfConvexSets::Vertex&,
const GraphOfConvexSets::Vertex&,
const GraphOfConvexSetsOptions&>(
&GraphOfConvexSets::SolveShortestPath),
py::arg("source"), py::arg("target"),
py::arg("options") = GraphOfConvexSetsOptions(),
cls_doc.SolveShortestPath.doc)
.def("GetSolutionPath", &GraphOfConvexSets::GetSolutionPath,
py::arg("source"), py::arg("target"), py::arg("result"),
py::arg("tolerance") = 1e-3, cls_doc.GetSolutionPath.doc)
.def("SolveConvexRestriction",
&GraphOfConvexSets::SolveConvexRestriction, py::arg("active_edges"),
py::arg("options") = GraphOfConvexSetsOptions(),
cls_doc.SolveConvexRestriction.doc);
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
graph_of_convex_sets
.def("AddEdge",
WrapDeprecated(cls_doc.AddEdge.doc_deprecated,
py::overload_cast<GraphOfConvexSets::VertexId,
GraphOfConvexSets::VertexId, std::string>(
&GraphOfConvexSets::AddEdge)),
py::arg("u_id"), py::arg("v_id"), py::arg("name") = "",
py_rvp::reference_internal, cls_doc.AddEdge.doc_deprecated)
.def("RemoveVertex",
WrapDeprecated(cls_doc.RemoveVertex.doc_deprecated,
py::overload_cast<GraphOfConvexSets::VertexId>(
&GraphOfConvexSets::RemoveVertex)),
py::arg("vertex_id"), cls_doc.RemoveVertex.doc_deprecated)
.def("RemoveEdge",
WrapDeprecated(cls_doc.RemoveEdge.doc_deprecated,
py::overload_cast<GraphOfConvexSets::EdgeId>(
&GraphOfConvexSets::RemoveEdge)),
py::arg("edge_id"), cls_doc.RemoveEdge.doc_deprecated)
.def("SolveShortestPath",
WrapDeprecated(cls_doc.SolveShortestPath.doc_deprecated,
overload_cast_explicit<solvers::MathematicalProgramResult,
GraphOfConvexSets::VertexId, GraphOfConvexSets::VertexId,
const GraphOfConvexSetsOptions&>(
&GraphOfConvexSets::SolveShortestPath)),
py::arg("source_id"), py::arg("target_id"),
py::arg("options") = GraphOfConvexSetsOptions(),
cls_doc.SolveShortestPath.doc_deprecated);
#pragma GCC diagnostic pop
}
// NOLINTNEXTLINE(readability/fn_size)
}
} // namespace pydrake
} // namespace drake
<file_sep>/systems/primitives/trajectory_source.h
#pragma once
#include <memory>
#include <vector>
#include "drake/common/drake_copyable.h"
#include "drake/common/eigen_types.h"
#include "drake/common/trajectories/trajectory.h"
#include "drake/systems/framework/context.h"
#include "drake/systems/framework/single_output_vector_source.h"
namespace drake {
namespace systems {
/// Given a Trajectory, this System provides an output port with the value of
/// the trajectory evaluated at the current time.
///
/// If the particular Trajectory is not available at the time the System /
/// Diagram is being constructed, one can create a TrajectorySource with a
/// placeholder trajectory (e.g. PiecewisePolynomimal(Eigen::VectorXd)) with the
/// correct number of rows, and then use UpdateTrajectory().
///
/// @system
/// name: TrajectorySource
/// output_ports:
/// - y0
/// @endsystem
///
/// @tparam_double_only
/// @ingroup primitive_systems
template <typename T>
class TrajectorySource final : public SingleOutputVectorSource<T> {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(TrajectorySource)
/// @param trajectory Trajectory used by the system.
/// @param output_derivative_order The number of times to take the derivative.
/// Must be greater than or equal to zero.
/// @param zero_derivatives_beyond_limits All derivatives will be zero before
/// the start time or after the end time of @p trajectory.
/// @pre The value of `trajectory` is a column vector. More precisely,
/// trajectory.cols() == 1.
explicit TrajectorySource(const trajectories::Trajectory<T>& trajectory,
int output_derivative_order = 0,
bool zero_derivatives_beyond_limits = true);
~TrajectorySource() final = default;
/// Updates the stored trajectory. @p trajectory must have the same number of
/// rows as the trajectory passed to the constructor.
void UpdateTrajectory(const trajectories::Trajectory<T>& trajectory);
private:
// Outputs a vector of values evaluated at the context time of the trajectory
// and up to its Nth derivatives, where the trajectory and N are passed to
// the constructor. The size of the vector is:
// (1 + output_derivative_order) * rows of the trajectory passed to the
// constructor.
void DoCalcVectorOutput(const Context<T>& context,
Eigen::VectorBlock<VectorX<T>>* output) const final;
std::unique_ptr<trajectories::Trajectory<T>> trajectory_;
const bool clamp_derivatives_;
std::vector<std::unique_ptr<trajectories::Trajectory<T>>> derivatives_;
};
} // namespace systems
} // namespace drake
<file_sep>/multibody/contact_solvers/block_sparse_cholesky_solver.cc
#include "drake/multibody/contact_solvers/block_sparse_cholesky_solver.h"
#include <algorithm>
#include <utility>
#include <vector>
#include "drake/multibody/contact_solvers/minimum_degree_ordering.h"
namespace drake {
namespace multibody {
namespace contact_solvers {
namespace internal {
template <typename BlockType>
BlockSparseCholeskySolver<BlockType>::~BlockSparseCholeskySolver() = default;
template <typename BlockType>
void BlockSparseCholeskySolver<BlockType>::SetMatrix(const SymmetricMatrix& A) {
const BlockSparsityPattern& A_block_pattern = A.sparsity_pattern();
/* Compute the elimination ordering using Minimum Degree algorithm. */
const std::vector<int> elimination_ordering =
ComputeMinimumDegreeOrdering(A_block_pattern);
BlockSparsityPattern L_block_pattern =
SymbolicFactor(A, elimination_ordering);
SetMatrixImpl(A, elimination_ordering, std::move(L_block_pattern));
}
template <typename BlockType>
void BlockSparseCholeskySolver<BlockType>::UpdateMatrix(
const SymmetricMatrix& A) {
PermuteAndCopyToL(A);
solver_mode_ = SolverMode::kAnalyzed;
}
template <typename BlockType>
bool BlockSparseCholeskySolver<BlockType>::Factor() {
DRAKE_THROW_UNLESS(solver_mode() == SolverMode::kAnalyzed);
for (int j = 0; j < L_->block_cols(); ++j) {
/* Update diagonal. */
const BlockType& Ajj = L_->diagonal_block(j);
L_diag_[j].compute(Ajj);
if (L_diag_[j].info() != Eigen::Success) {
solver_mode_ = SolverMode::kEmpty;
return false;
}
L_->SetBlockFlat(0, j, L_diag_[j].matrixL());
/* Update L₂₁ column.
| a₁₁ * | = | λ₁₁ 0 | * | λ₁₁ᵀ L₂₁ᵀ |
| a₂₁ a₂₂ | | L₂₁ L₂₂| | 0 L₂₂ᵀ |
So we have
L₂₁λ₁₁ᵀ = a₂₁, and thus
λ₁₁L₂₁ᵀ = a₂₁ᵀ */
const std::vector<int>& row_blocks = L_->block_row_indices(j);
const auto Ljj = L_diag_[j].matrixL();
/* We start from flat = 1 here to skip the j,j diagonal entry. */
for (int flat = 1; flat < ssize(row_blocks); ++flat) {
const BlockType& Aij = L_->block_flat(flat, j);
BlockType Lij = Ljj.solve(Aij.transpose()).transpose();
L_->SetBlockFlat(flat, j, std::move(Lij));
}
/* Update L₂₂ according to L₂₂ = a₂₂ - L₂₁⋅L₂₁ᵀ. */
RightLookingSymmetricRank1Update(j);
}
solver_mode_ = SolverMode::kFactored;
return true;
}
template <typename BlockType>
VectorX<double> BlockSparseCholeskySolver<BlockType>::Solve(
const Eigen::Ref<const VectorX<double>>& b) const {
VectorX<double> x(b);
SolveInPlace(&x);
return x;
}
template <typename BlockType>
void BlockSparseCholeskySolver<BlockType>::SolveInPlace(
VectorX<double>* b) const {
DRAKE_THROW_UNLESS(solver_mode() == SolverMode::kFactored);
DRAKE_THROW_UNLESS(b != nullptr);
DRAKE_THROW_UNLESS(b->size() == L_->cols());
VectorX<double> permuted_b(*b);
scalar_permutation_.Apply(*b, &permuted_b);
const BlockSparsityPattern& block_sparsity_pattern = L_->sparsity_pattern();
const std::vector<int>& block_sizes = block_sparsity_pattern.block_sizes();
const std::vector<int>& starting_cols = L_->starting_cols();
/* Solve Lz = b in place. */
for (int j = 0; j < L_->block_cols(); ++j) {
const int block_size = block_sizes[j];
const int offset = starting_cols[j];
/* Solve for the j-th block entry. */
const VectorX<double> bj =
L_diag_[j].matrixL().solve(permuted_b.segment(offset, block_size));
permuted_b.segment(offset, block_size) = bj;
/* Eliminate for the j-th block entry from the system. */
const auto& blocks_in_col_j = L_->block_row_indices(j);
for (int flat = 1; flat < ssize(blocks_in_col_j); ++flat) {
const int i = blocks_in_col_j[flat];
permuted_b.segment(starting_cols[i], block_sizes[i]).noalias() -=
L_->block_flat(flat, j) * bj;
}
}
VectorX<double>& permuted_z = permuted_b;
/* Solve Lᵀx = z in place. */
for (int j = L_->block_cols() - 1; j >= 0; --j) {
/* Eliminate all solved variables. */
const auto& blocks_in_col_j = L_->block_row_indices(j);
for (int flat = 1; flat < ssize(blocks_in_col_j); ++flat) {
const int i = blocks_in_col_j[flat];
permuted_z.segment(starting_cols[j], block_sizes[j]).noalias() -=
L_->block_flat(flat, j).transpose() *
permuted_z.segment(starting_cols[i], block_sizes[i]);
}
/* Solve for the j-th block entry. */
const VectorX<double> zj = L_diag_[j].matrixU().solve(
permuted_z.segment(starting_cols[j], block_sizes[j]));
permuted_z.segment(starting_cols[j], block_sizes[j]) = zj;
}
scalar_permutation_.ApplyInverse(permuted_z, b);
}
template <typename BlockType>
typename BlockSparseCholeskySolver<BlockType>::LowerTriangularMatrix
BlockSparseCholeskySolver<BlockType>::L() const {
DRAKE_THROW_UNLESS(solver_mode() == SolverMode::kFactored);
return *L_;
}
template <typename BlockType>
Eigen::PermutationMatrix<Eigen::Dynamic>
BlockSparseCholeskySolver<BlockType>::CalcPermutationMatrix() const {
DRAKE_THROW_UNLESS(solver_mode() != SolverMode::kEmpty);
const std::vector<int>& p = scalar_permutation_.permutation();
return Eigen::PermutationMatrix<Eigen::Dynamic>(
Eigen::Map<const VectorX<int>>(p.data(), p.size()));
}
template <typename BlockType>
void BlockSparseCholeskySolver<BlockType>::SetMatrixImpl(
const SymmetricMatrix& A, const std::vector<int>& elimination_ordering,
BlockSparsityPattern&& L_pattern) {
/* First documented responsibility: set `block_permutation_`. */
/* Construct the inverse of the elimination ordering, which permutes the
original indices to new indices. */
std::vector<int> permutation(elimination_ordering.size());
for (int i = 0; i < ssize(permutation); ++i) {
permutation[elimination_ordering[i]] = i;
}
block_permutation_ = PartialPermutation(std::move(permutation));
/* Second documented responsibility: set `scalar_permutation_`. */
SetScalarPermutation(A, elimination_ordering);
/* Third documented responsibility: allocate for `L_` and `L_diag_`. */
L_ = std::make_unique<LowerTriangularMatrix>(std::move(L_pattern));
L_diag_.resize(A.block_cols());
/* Fourth documented responsibility: UpdateMatrix. */
UpdateMatrix(A);
}
template <typename BlockType>
void BlockSparseCholeskySolver<BlockType>::SetScalarPermutation(
const SymmetricMatrix& A, const std::vector<int>& elimination_ordering) {
/* It's easier to build the scalar elimination ordering first from block
elimination ordering and then convert it to the scalar permutation (the
inverse of the scalar elimination ordering) that induces the permutation P
such that L⋅Lᵀ = P⋅A⋅Pᵀ.
More specificially, Pᵢⱼ = 1 for j = scalar_elimination_ordering[i] (or
equivalently i = scalar_permutation_[j]) and Pᵢⱼ = 0 otherwise. See
CalcPermutationMatrix(). */
std::vector<int> scalar_elimination_ordering(A.cols());
{
const BlockSparsityPattern& A_block_pattern = A.sparsity_pattern();
const std::vector<int>& A_block_sizes = A_block_pattern.block_sizes();
const std::vector<int>& starting_indices = A.starting_cols();
int i_permuted = 0;
for (int block_permuted = 0; block_permuted < ssize(elimination_ordering);
++block_permuted) {
const int block = elimination_ordering[block_permuted];
const int start = starting_indices[block];
const int size = A_block_sizes[block];
for (int i = start; i < start + size; ++i) {
scalar_elimination_ordering[i_permuted++] = i;
}
}
}
/* Invert the elimination ordering to get the permutation. */
std::vector<int> scalar_permutation(scalar_elimination_ordering.size());
for (int i_permuted = 0; i_permuted < ssize(scalar_permutation);
++i_permuted) {
scalar_permutation[scalar_elimination_ordering[i_permuted]] = i_permuted;
}
scalar_permutation_ = PartialPermutation(std::move(scalar_permutation));
}
template <typename BlockType>
BlockSparsityPattern BlockSparseCholeskySolver<BlockType>::SymbolicFactor(
const SymmetricMatrix& A, const std::vector<int>& elimination_ordering) {
/* 1. Compute the block permutation as well as the scalar permutation. */
const int n = elimination_ordering.size();
/* Construct the inverse of the elimination ordering, which permutes the
original indices to new indices. */
std::vector<int> permutation(n);
for (int i = 0; i < n; ++i) {
permutation[elimination_ordering[i]] = i;
}
const PartialPermutation block_permutation(std::move(permutation));
/* Find the sparsity pattern of the permuted A (under the permutation induced
by the elimination ordering). */
const BlockSparsityPattern& A_block_pattern = A.sparsity_pattern();
const std::vector<int>& A_block_sizes = A_block_pattern.block_sizes();
const std::vector<std::vector<int>>& sparsity_pattern =
A_block_pattern.neighbors();
std::vector<std::vector<int>> permuted_sparsity_pattern(
sparsity_pattern.size());
for (int i = 0; i < ssize(sparsity_pattern); ++i) {
const int pi = block_permutation.permuted_index(i);
for (int j : sparsity_pattern[i]) {
const int pj = block_permutation.permuted_index(j);
permuted_sparsity_pattern[std::min(pi, pj)].emplace_back(
std::max(pi, pj));
}
}
std::vector<int> permuted_block_sizes(A.block_cols());
block_permutation.Apply(A_block_sizes, &permuted_block_sizes);
/* Compute the sparsity pattern of L given the sparsity pattern of A in the
new ordering. */
return contact_solvers::internal::SymbolicCholeskyFactor(
BlockSparsityPattern(permuted_block_sizes, permuted_sparsity_pattern));
}
template <typename BlockType>
void BlockSparseCholeskySolver<BlockType>::RightLookingSymmetricRank1Update(
int j) {
const std::vector<int>& blocks_in_col_j = L_->block_row_indices(j);
const int n = blocks_in_col_j.size();
/* We start from k = 1 here to skip the j,j diagonal entry. */
for (int k = 1; k < n; ++k) {
const int col = blocks_in_col_j[k];
const BlockType& B = L_->block_flat(k, j);
for (int l = k; l < n; ++l) {
const int row = blocks_in_col_j[l];
const BlockType& A = L_->block_flat(l, j);
L_->AddToBlock(row, col, -A * B.transpose());
}
}
}
template <typename BlockType>
void BlockSparseCholeskySolver<BlockType>::PermuteAndCopyToL(
const SymmetricMatrix& A) {
const int n = A.block_cols();
DRAKE_DEMAND(n == block_permutation_.domain_size());
DRAKE_DEMAND(n == block_permutation_.permuted_domain_size());
L_->SetZero();
for (int j = 0; j < n; ++j) {
const std::vector<int>& row_indices = A.block_row_indices(j);
for (int i : row_indices) {
const BlockType& block = A.block(i, j);
const int pi = block_permutation_.permuted_index(i);
const int pj = block_permutation_.permuted_index(j);
if (pi >= pj) {
L_->SetBlock(pi, pj, block);
} else {
L_->SetBlock(pj, pi, block.transpose());
}
}
}
}
template class BlockSparseCholeskySolver<MatrixX<double>>;
template class BlockSparseCholeskySolver<Matrix3<double>>;
} // namespace internal
} // namespace contact_solvers
} // namespace multibody
} // namespace drake
<file_sep>/bindings/pydrake/manipulation/kuka_iiwa.py
"""Shim module that provides vestigial names for pydrake.manipulation.
Prefer not to use this import path in new code; all of the code in
this module can be imported from pydrake.manipulation directly.
This module will be deprecated at some point in the future.
"""
from pydrake.manipulation import (
ApplyDriverConfig,
BuildIiwaControl,
IiwaCommandReceiver,
IiwaCommandSender,
IiwaControlMode,
IiwaDriver,
IiwaStatusReceiver,
IiwaStatusSender,
ParseIiwaControlMode,
get_iiwa_max_joint_velocities,
kIiwaArmNumJoints,
kIiwaLcmStatusPeriod,
position_enabled,
torque_enabled,
)
<file_sep>/planning/test/planning_test_helpers.h
#pragma once
#include <memory>
#include "drake/multibody/parsing/model_directives.h"
#include "drake/planning/collision_checker.h"
#include "drake/planning/robot_diagram.h"
namespace drake {
namespace planning {
namespace test {
/* Creates a RobotDiagram from the given directives. */
std::unique_ptr<RobotDiagram<double>> MakePlanningTestModel(
const multibody::parsing::ModelDirectives& directives);
/* Returns a particular ConfigurationDistanceFunction for a 7-dof iiwa.
The weights are non-uniform. */
ConfigurationDistanceFunction MakeWeightedIiwaConfigurationDistanceFunction();
// TODO(rpoyner-tri): fix the naming scheme, maybe.
/* Adds a new model to @p plant, consisting of @p n bodies, connected by
revolute joints. The geometry for each body consists of @p num_geo small
spheres. @note: the model name is based on @p n, so adding chains of the
same length will fail. */
multibody::ModelInstanceIndex AddChain(multibody::MultibodyPlant<double>* plant,
int n, int num_geo = 1);
} // namespace test
} // namespace planning
} // namespace drake
<file_sep>/systems/controllers/inverse_dynamics.cc
#include "drake/systems/controllers/inverse_dynamics.h"
#include <utility>
#include <vector>
using drake::multibody::MultibodyForces;
using drake::multibody::MultibodyPlant;
namespace drake {
namespace systems {
namespace controllers {
template <typename T>
InverseDynamics<T>::InverseDynamics(
std::unique_ptr<multibody::MultibodyPlant<T>> owned_plant,
const MultibodyPlant<T>* plant, const InverseDynamicsMode mode)
: LeafSystem<T>(SystemTypeTag<InverseDynamics>{}),
owned_plant_(std::move(owned_plant)),
plant_(owned_plant_ ? owned_plant_.get() : plant),
mode_(mode),
q_dim_(plant_->num_positions()),
v_dim_(plant_->num_velocities()) {
// Check that only one of owned_plant and plant where set.
DRAKE_DEMAND(owned_plant_ == nullptr || plant == nullptr);
DRAKE_DEMAND(plant_ != nullptr);
DRAKE_DEMAND(plant_->is_finalized());
input_port_index_state_ =
this->DeclareInputPort(kUseDefaultName, kVectorValued, q_dim_ + v_dim_)
.get_index();
// We declare the all_input_ports ticket so that GetDirectFeedthrough does
// not try to cast to Symbolic for feedthrough evaluation.
output_port_index_force_ =
this->DeclareVectorOutputPort(kUseDefaultName, v_dim_,
&InverseDynamics<T>::CalcOutputForce,
{this->all_input_ports_ticket()})
.get_index();
auto plant_context = plant_->CreateDefaultContext();
// Gravity compensation mode requires velocities to be zero.
if (this->is_pure_gravity_compensation()) {
plant_->SetVelocities(plant_context.get(),
VectorX<T>::Zero(plant_->num_velocities()));
}
// Declare cache entry for the multibody plant context.
plant_context_cache_index_ =
this->DeclareCacheEntry(
"plant_context_cache", *plant_context,
&InverseDynamics<T>::SetMultibodyContext,
{this->input_port_ticket(
get_input_port_estimated_state().get_index())})
.cache_index();
// Declare external forces cache entry and desired acceleration input port if
// this is doing inverse dynamics.
if (!this->is_pure_gravity_compensation()) {
external_forces_cache_index_ =
this->DeclareCacheEntry(
"external_forces_cache", MultibodyForces<T>(*plant_),
&InverseDynamics<T>::CalcMultibodyForces,
{this->cache_entry_ticket(plant_context_cache_index_)})
.cache_index();
input_port_index_desired_acceleration_ =
this->DeclareInputPort(kUseDefaultName, kVectorValued, v_dim_)
.get_index();
}
}
template <typename T>
InverseDynamics<T>::InverseDynamics(const MultibodyPlant<T>* plant,
const InverseDynamicsMode mode)
: InverseDynamics(nullptr, plant, mode) {}
template <typename T>
InverseDynamics<T>::InverseDynamics(
std::unique_ptr<multibody::MultibodyPlant<T>> plant,
const InverseDynamicsMode mode)
: InverseDynamics(std::move(plant), nullptr, mode) {}
template <typename T>
template <typename U>
InverseDynamics<T>::InverseDynamics(const InverseDynamics<U>& other)
: InverseDynamics(
systems::System<U>::template ToScalarType<T>(*other.plant_),
other.is_pure_gravity_compensation() ? kGravityCompensation
: kInverseDynamics) {}
template <typename T>
InverseDynamics<T>::~InverseDynamics() = default;
template <typename T>
void InverseDynamics<T>::SetMultibodyContext(const Context<T>& context,
Context<T>* plant_context) const {
const VectorX<T>& x = get_input_port_estimated_state().Eval(context);
if (this->is_pure_gravity_compensation()) {
// Velocities remain zero, as set in the constructor, for pure gravity
// compensation mode.
const VectorX<T> q = x.head(plant_->num_positions());
plant_->SetPositions(plant_context, q);
} else {
// Set the plant positions and velocities.
plant_->SetPositionsAndVelocities(plant_context, x);
}
}
template <typename T>
void InverseDynamics<T>::CalcMultibodyForces(
const Context<T>& context, MultibodyForces<T>* cache_value) const {
const auto& plant_context = this->get_cache_entry(plant_context_cache_index_)
.template Eval<Context<T>>(context);
plant_->CalcForceElementsContribution(plant_context, cache_value);
}
template <typename T>
void InverseDynamics<T>::CalcOutputForce(const Context<T>& context,
BasicVector<T>* output) const {
const auto& plant_context = this->get_cache_entry(plant_context_cache_index_)
.template Eval<Context<T>>(context);
if (this->is_pure_gravity_compensation()) {
output->get_mutable_value() =
-plant_->CalcGravityGeneralizedForces(plant_context);
} else {
const auto& external_forces =
this->get_cache_entry(external_forces_cache_index_)
.template Eval<MultibodyForces<T>>(context);
// Compute inverse dynamics.
const VectorX<T>& desired_vd =
get_input_port_desired_acceleration().Eval(context);
output->get_mutable_value() =
plant_->CalcInverseDynamics(plant_context, desired_vd, external_forces);
}
}
} // namespace controllers
} // namespace systems
} // namespace drake
DRAKE_DEFINE_CLASS_TEMPLATE_INSTANTIATIONS_ON_DEFAULT_SCALARS(
class ::drake::systems::controllers::InverseDynamics)
<file_sep>/bindings/pydrake/geometry/render.py
"""Deprecated aliases to pydrake.geometry.render resources."""
from pydrake.common.deprecation import _warn_deprecated
from pydrake.geometry import *
_warn_deprecated(
"Please import the render-related symbols from pydrake.geometry instead "
f"of the deprecated {__name__} submodule.",
date="2023-08-01", stacklevel=3)
<file_sep>/multibody/fem/fem_solver.h
#pragma once
#include <memory>
#include "drake/common/eigen_types.h"
#include "drake/multibody/fem/discrete_time_integrator.h"
#include "drake/multibody/fem/fem_model.h"
#include "drake/multibody/fem/fem_state.h"
namespace drake {
namespace multibody {
namespace fem {
namespace internal {
/* Holds the scratch data used in the solver to avoid unnecessary
reallocation.
@tparam_double_only */
template <typename T>
class FemSolverScratchData {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(FemSolverScratchData);
/* Constructs a scratch data that is compatible with the given model. */
explicit FemSolverScratchData(const FemModel<T>& model) { Resize(model); }
/* Resizes scratch data to have sizes compatible with the given `model`. */
void Resize(const FemModel<T>& model);
std::unique_ptr<FemSolverScratchData<T>> Clone() const;
int num_dofs() const { return b_.size(); }
/* Returns the residual of the model. */
const VectorX<T>& b() const { return b_; }
/* Returns the solution to A * dz = -b, where A is the tangent matrix. */
const VectorX<T>& dz() const { return dz_; }
const internal::PetscSymmetricBlockSparseMatrix& tangent_matrix() const {
return *tangent_matrix_;
}
VectorX<T>& mutable_b() { return b_; }
VectorX<T>& mutable_dz() { return dz_; }
internal::PetscSymmetricBlockSparseMatrix& mutable_tangent_matrix() {
return *tangent_matrix_;
}
private:
/* Private default constructor to facilitate cloning. */
FemSolverScratchData() = default;
std::unique_ptr<internal::PetscSymmetricBlockSparseMatrix> tangent_matrix_;
VectorX<T> b_;
VectorX<T> dz_;
};
/* FemSolver solves discrete dynamic elasticity problems. The governing PDE of
the dynamics is spatially discretized in FemModel and temporally discretized by
DiscreteTimeIntegrator. FemSolver provides the `AdvanceOneTimeStep()` function
that advances the free-motion states (i.e. without considering contacts or
constraints) of the spatially discretized FEM model by one time step according
to the prescribed discrete time integration scheme using a Newton-Raphson
solver.
@tparam_double_only */
template <typename T>
class FemSolver {
public:
DRAKE_NO_COPY_NO_MOVE_NO_ASSIGN(FemSolver);
/* Constructs a new FemSolver that solves the given `model` with the
`integrator` provided to advance time.
@note The `model` and `integrator` pointers persist in `this` FemSolver and
thus the model and the integrator must outlive this solver.
@pre model != nullptr.
@pre integrator != nullptr.*/
FemSolver(const FemModel<T>* model,
const DiscreteTimeIntegrator<T>* integrator);
/* Advances the state of the FEM model by one time step with the integrator
prescribed at construction.
@param[in] prev_state The state of the FEM model evaluated at the previous
time step.
@param[out] next_state The state of the FEM model evaluated at the next
time step.
@param[in, out] scratch A scratch pad for storing intermediary data used in
the computation. We use this scratch only to avoid
memory allocation. The actual value of scratch is
unused. The size of scratch will be set to be
compatible with the model referenced by this solver
on output if it's not already appropriately sized.
@returns the number of Newton-Raphson iterations the solver takes to
converge if the solver converges or -1 if the solver fails to converge.
@pre next_state != nullptr.
@throws std::exception if the input `prev_state` or `next_state` is
incompatible with the FEM model solved by this solver. */
int AdvanceOneTimeStep(const FemState<T>& prev_state, FemState<T>* next_state,
FemSolverScratchData<T>* scratch) const;
/* Returns the FEM model that this solver solves for. */
const FemModel<T>& model() const { return *model_; }
/* Returns the discrete time integrator that this solver uses. */
const DiscreteTimeIntegrator<T>& integrator() const { return *integrator_; }
/* Sets the relative tolerance, unitless. See solver_converged() for how
the tolerance is used. The default value is 1e-4. */
void set_relative_tolerance(double tolerance) {
relative_tolerance_ = tolerance;
}
double relative_tolerance() const { return relative_tolerance_; }
/* Sets the absolute tolerance with unit Newton. See solver_converged() for
how the tolerance is used. The default value is 1e-6. */
void set_absolute_tolerance(double tolerance) {
absolute_tolerance_ = tolerance;
}
double absolute_tolerance() const { return absolute_tolerance_; }
/* The solver is considered as converged if ‖r‖ <= max(εᵣ * ‖r₀‖, εₐ) where r
and r₀ are `residual_norm` and `initial_residual_norm` respectively, and εᵣ
and εₐ are relative and absolute tolerance respectively. */
bool solver_converged(const T& residual_norm,
const T& initial_residual_norm) const;
private:
/* Uses a Newton-Raphson solver to solve for the unknown z such that the
residual is zero, i.e. b(z) = 0, up to the specified tolerances. The input
FEM state is non-null and is guaranteed to be compatible with the FEM model.
@param[in, out] state As input, `state` provides an initial guess of
the solution. As output, `state` reports the equilibrium state.
@returns the number of iterations it takes for the solver to converge or -1
if the solver fails to converge. */
int SolveWithInitialGuess(FemState<T>* state,
FemSolverScratchData<T>* scratch) const;
/* Returns the relative tolerance for the linear solver used in the
Newton-Raphson iterations based on the residual norm if the linear solver
is iterative. More specifically, it is set to
tol = min(k * εᵣ, ‖r‖ / max(‖r₀‖, εₐ)),
where k is a constant scaling factor < 1, εᵣ and εₐ are the relative and
absolute tolerances for newton iterations (see set_relative_tolerance() and
set_absolute_tolerance()), and ‖r‖ and ‖r₀‖ are `residual_norm` and
`initial_residual_norm`. */
double linear_solve_tolerance(const T& residual_norm,
const T& initial_residual_norm) const;
/* The FEM model being solved by `this` solver. */
const FemModel<T>* model_{nullptr};
/* The discrete time integrator the solver uses. */
const DiscreteTimeIntegrator<T>* integrator_{nullptr};
/* Tolerance for convergence. */
double relative_tolerance_{1e-4}; // unitless.
double absolute_tolerance_{1e-6}; // unit N.
/* Max number of Newton-Raphson iterations the solver takes before it gives
up. */
int kMaxIterations_{100};
};
} // namespace internal
} // namespace fem
} // namespace multibody
} // namespace drake
<file_sep>/bindings/pydrake/manipulation/util.py
"""Shim module that provides vestigial names for pydrake.manipulation.
Prefer not to use this import path in new code; all of the code in
this module can be imported from pydrake.manipulation directly.
This module will be deprecated at some point in the future.
"""
from pydrake.manipulation import (
ApplyDriverConfig,
ZeroForceDriver,
)
<file_sep>/systems/sensors/sim_rgbd_sensor.cc
#include "drake/systems/sensors/sim_rgbd_sensor.h"
#include <memory>
#include <optional>
#include <regex>
#include "drake/systems/lcm/lcm_publisher_system.h"
#include "drake/systems/sensors/image_to_lcm_image_array_t.h"
namespace drake {
namespace systems {
namespace sensors {
namespace internal {
using geometry::SceneGraph;
using geometry::render::ColorRenderCamera;
using geometry::render::DepthRenderCamera;
using math::RigidTransformd;
using multibody::MultibodyPlant;
RgbdSensor* AddSimRgbdSensor(const SceneGraph<double>& scene_graph,
const MultibodyPlant<double>& plant,
const SimRgbdSensor& sim_rgbd_sensor,
DiagramBuilder<double>* builder) {
DRAKE_DEMAND(builder != nullptr);
// TODO(eric.cousineau): Simplify this if drake#10247 is resolved.
// 'A' is the body for the parent sensor frame.
// `P` is the parent of the sensor frame.
// `B` is the sensor frame.
const auto& frame_P = sim_rgbd_sensor.frame();
const auto& body_A = frame_P.body();
const std::optional<geometry::FrameId> body_A_id =
plant.GetBodyFrameIdIfExists(body_A.index());
DRAKE_THROW_UNLESS(body_A_id.has_value());
// We must include the offset of the body to ensure that we posture the camera
// appropriately.
const RigidTransformd X_AP = frame_P.GetFixedPoseInBodyFrame();
const RigidTransformd X_AB = X_AP * sim_rgbd_sensor.X_PB();
auto* rgbd_sensor_sys = builder->AddSystem<RgbdSensor>(
*body_A_id, X_AB, sim_rgbd_sensor.color_properties(),
sim_rgbd_sensor.depth_properties());
// `set_name` is only used for debugging.
rgbd_sensor_sys->set_name("rgbd_sensor_" + sim_rgbd_sensor.serial());
builder->Connect(scene_graph.get_query_output_port(),
rgbd_sensor_sys->query_object_input_port());
return rgbd_sensor_sys;
}
void AddSimRgbdSensorLcmPublisher(const SimRgbdSensor& sim_rgbd_sensor,
const OutputPort<double>* rgb_port,
const OutputPort<double>* depth_16u_port,
bool do_compress,
DiagramBuilder<double>* builder,
drake::lcm::DrakeLcmInterface* lcm) {
DRAKE_DEMAND(builder != nullptr);
DRAKE_DEMAND(lcm != nullptr);
if (!rgb_port && !depth_16u_port) return;
auto image_to_lcm_image_array =
builder->AddSystem<ImageToLcmImageArrayT>(do_compress);
image_to_lcm_image_array->set_name("image_to_lcm_" +
sim_rgbd_sensor.serial());
if (depth_16u_port) {
const auto& lcm_depth_port =
image_to_lcm_image_array->DeclareImageInputPort<PixelType::kDepth16U>(
"depth");
builder->Connect(*depth_16u_port, lcm_depth_port);
}
if (rgb_port) {
const auto& lcm_rgb_port =
image_to_lcm_image_array->DeclareImageInputPort<PixelType::kRgba8U>(
"rgb");
builder->Connect(*rgb_port, lcm_rgb_port);
}
auto image_array_lcm_publisher =
builder->AddSystem(lcm::LcmPublisherSystem::Make<lcmt_image_array>(
"DRAKE_RGBD_CAMERA_IMAGES_" + sim_rgbd_sensor.serial(), lcm,
1. / sim_rgbd_sensor.rate_hz()));
builder->Connect(image_to_lcm_image_array->image_array_t_msg_output_port(),
image_array_lcm_publisher->get_input_port());
}
} // namespace internal
} // namespace sensors
} // namespace systems
} // namespace drake
<file_sep>/bindings/pydrake/manipulation/schunk_wsg.py
"""Shim module that provides vestigial names for pydrake.manipulation.
Prefer not to use this import path in new code; all of the code in
this module can be imported from pydrake.manipulation directly.
This module will be deprecated at some point in the future.
"""
from pydrake.manipulation import (
ApplyDriverConfig,
BuildSchunkWsgControl,
GetSchunkWsgOpenPosition,
MakeMultibodyForceToWsgForceSystem,
MakeMultibodyStateToWsgStateSystem,
SchunkWsgCommandReceiver,
SchunkWsgCommandSender,
SchunkWsgController,
SchunkWsgDriver,
SchunkWsgPositionController,
SchunkWsgStatusReceiver,
SchunkWsgStatusSender,
)
<file_sep>/multibody/fem/fem_solver.cc
#include "drake/multibody/fem/fem_solver.h"
#include <algorithm>
#include "drake/common/text_logging.h"
namespace drake {
namespace multibody {
namespace fem {
namespace internal {
template <typename T>
void FemSolverScratchData<T>::Resize(const FemModel<T>& model) {
b_.resize(model.num_dofs());
dz_.resize(model.num_dofs());
tangent_matrix_ = model.MakePetscSymmetricBlockSparseTangentMatrix();
}
template <typename T>
std::unique_ptr<FemSolverScratchData<T>> FemSolverScratchData<T>::Clone()
const {
std::unique_ptr<FemSolverScratchData<T>> clone(new FemSolverScratchData<T>());
clone->b_ = this->b_;
clone->dz_ = this->dz_;
DRAKE_DEMAND(tangent_matrix_ != nullptr);
tangent_matrix_->AssembleIfNecessary();
clone->tangent_matrix_ = this->tangent_matrix_->Clone();
return clone;
}
template <typename T>
FemSolver<T>::FemSolver(const FemModel<T>* model,
const DiscreteTimeIntegrator<T>* integrator)
: model_(model), integrator_(integrator) {
DRAKE_DEMAND(model_ != nullptr);
DRAKE_DEMAND(integrator_ != nullptr);
}
template <typename T>
int FemSolver<T>::AdvanceOneTimeStep(const FemState<T>& prev_state,
FemState<T>* next_state,
FemSolverScratchData<T>* scratch) const {
DRAKE_DEMAND(next_state != nullptr);
model_->ThrowIfModelStateIncompatible(__func__, prev_state);
model_->ThrowIfModelStateIncompatible(__func__, *next_state);
const VectorX<T>& unknown_variable = integrator_->GetUnknowns(prev_state);
integrator_->AdvanceOneTimeStep(prev_state, unknown_variable, next_state);
/* Run Newton-Raphson iterations. */
return SolveWithInitialGuess(next_state, scratch);
}
template <typename T>
bool FemSolver<T>::solver_converged(const T& residual_norm,
const T& initial_residual_norm) const {
return residual_norm < std::max(relative_tolerance_ * initial_residual_norm,
absolute_tolerance_);
}
template <typename T>
double FemSolver<T>::linear_solve_tolerance(
const T& residual_norm, const T& initial_residual_norm) const {
/* The relative tolerance when solving for A * dz = -b, where A is the tangent
matrix. We set it to be on the order of the residual norm to achieve local
second order convergence [Nocedal and Wright, section 7.1]. We also set it to
be smaller than the relative tolerance to ensure that linear models converge
in exact one Newton iteration.
[Nocedal and Wright] <NAME>., & <NAME>. (2006). Numerical
optimization. Springer Science & Business Media. */
constexpr double kLinearToleranceFactor = 0.2;
double linear_solve_tolerance =
std::min(kLinearToleranceFactor * relative_tolerance_,
ExtractDoubleOrThrow(residual_norm) /
std::max(ExtractDoubleOrThrow(initial_residual_norm),
absolute_tolerance_));
return linear_solve_tolerance;
}
template <typename T>
int FemSolver<T>::SolveWithInitialGuess(
FemState<T>* state, FemSolverScratchData<T>* scratch) const {
/* Make sure the scratch quantities are of the correct sizes. */
scratch->Resize(*model_);
VectorX<T>& b = scratch->mutable_b();
VectorX<T>& dz = scratch->mutable_dz();
internal::PetscSymmetricBlockSparseMatrix& tangent_matrix =
scratch->mutable_tangent_matrix();
model_->ApplyBoundaryCondition(state);
model_->CalcResidual(*state, &b);
T residual_norm = b.norm();
const T initial_residual_norm = residual_norm;
int iter = 0;
/* Newton-Raphson iterations. We iterate until any of the following is true:
1. The max number of allowed iterations is reached;
2. The norm of the residual is smaller than the absolute tolerance.
3. The relative error (the norm of the residual divided by the norm of the
initial residual) is smaller than the unitless relative tolerance. */
while (iter < kMaxIterations_ &&
/* Equivalent to residual_norm < absolute_tolerance_ on first
iteration. */
!solver_converged(residual_norm, initial_residual_norm)) {
model_->CalcTangentMatrix(*state, integrator_->GetWeights(),
&tangent_matrix);
tangent_matrix.AssembleIfNecessary();
/* Solve for A * dz = -b, where A is the tangent matrix. */
tangent_matrix.set_relative_tolerance(
linear_solve_tolerance(residual_norm, initial_residual_norm));
const auto linear_solve_status =
tangent_matrix.Solve(internal::PetscSymmetricBlockSparseMatrix::
SolverType::kConjugateGradient,
internal::PetscSymmetricBlockSparseMatrix::
PreconditionerType::kIncompleteCholesky,
-b, &dz);
if (linear_solve_status == PetscSolverStatus::kFailure) {
drake::log()->warn(
"Linear solve did not converge in Newton iterations in FemSolver.");
return -1;
}
integrator_->UpdateStateFromChangeInUnknowns(dz, state);
model_->CalcResidual(*state, &b);
residual_norm = b.norm();
++iter;
}
if (!solver_converged(residual_norm, initial_residual_norm)) {
return -1;
}
return iter;
}
} // namespace internal
} // namespace fem
} // namespace multibody
} // namespace drake
template class drake::multibody::fem::internal::FemSolverScratchData<double>;
template class drake::multibody::fem::internal::FemSolver<double>;
<file_sep>/tools/wheel/image/provision-base.sh
#!/bin/bash
# Internal script to install common (non-Python) build dependencies.
# Docker (Linux) only.
set -eu -o pipefail
readonly BAZEL_VERSION=6.2.0
readonly BAZEL_ROOT=https://github.com/bazelbuild/bazel/releases/download
# Fix ssh permissions.
chmod 700 ~/.ssh
chmod 600 ~/.ssh/known_hosts
# Prepare system to install packages, and apply any updates.
apt-get -y update
apt-get -y upgrade
apt-get -y install lsb-release
# Install prerequisites.
readonly DISTRO=$(lsb_release -sc)
mapfile -t PACKAGES < <(sed -e '/^#/d' < /image/packages-${DISTRO})
apt-get -y install --no-install-recommends ${PACKAGES[@]}
# Install Bazel.
cd /tmp
wget ${BAZEL_ROOT}/${BAZEL_VERSION}/bazel-${BAZEL_VERSION}-installer-linux-x86_64.sh
bash /tmp/bazel-${BAZEL_VERSION}-installer-linux-x86_64.sh
rm /tmp/bazel-${BAZEL_VERSION}-installer-linux-x86_64.sh
<file_sep>/tools/workspace/stable_baselines3_internal/README.md
stable_baselines3_internal
==========================
A local import of `stable_baselines3` that *does not* have its dependencies
(such as `pytorch`). As such, code using this module will have a
`ModuleNotFoundError` error if it attempts to use any functions that depend on
those modules.
The resulting `stable_baselines3` workalike is available via the bazel::
deps = [
"@stable_baselines3_internal//:stable_baselines3",
],
and then, in python::
import stable_baselines3
Code that wants to import the most featureful version of `stable_baselines3`
available (i.e., to use a locally installed `stable_baselines3` if available
and the Drake-provided workalike otherwise) can rely on the presence of the
string `"drake_internal"` in the `__version__` attribute. For instance::
sb3_is_fully_featured = False
try:
import stable_baselines3
if "drake_internal" not in stable_baselines3.__version__:
sb3_is_fully_featured = True
else:
print("stable_baselines3 found, but was drake internal")
except ImportError:
print("stable_baselines3 not found")
<file_sep>/geometry/optimization/cspace_free_internal.h
#pragma once
#include <map>
#include <memory>
#include <utility>
#include <vector>
#include "drake/geometry/optimization/c_iris_collision_geometry.h"
#include "drake/geometry/optimization/cspace_free_structs.h"
#include "drake/geometry/optimization/cspace_separating_plane.h"
#include "drake/multibody/rational/rational_forward_kinematics.h"
// Note: the user should not include this header in their code. This header is
// created for internal use only.
namespace drake {
namespace geometry {
namespace optimization {
namespace internal {
/*
Generate all the conditions (certain rationals being non-negative, and
certain vectors with length <= 1) such that the robot configuration is
collision free.
@param[in] separating_planes A vector to non-null pointers to
CSpaceSeparatingPlane objects containing the plane parameters as well as
information about which bodies to separate.
@param[in] y_slack The auxiliary variables required to enforce that capsules,
spheres, and cylinders are on the correct side. See
c_iris_collision_geometry.h/cc for details.
@param[in] q_star The point about which the rational forward kinematics are
taken. See rational_forward_kinematics.h/cc for details.
@param[in] plane_geometries A non-null pointer to an empty vector.
@param[out] plane_geometries Contains the separation information.
*/
void GenerateRationals(
const std::vector<std::unique_ptr<
CSpaceSeparatingPlane<symbolic::Variable>>>& separating_planes,
const Vector3<symbolic::Variable>& y_slack,
const Eigen::Ref<const Eigen::VectorXd>& q_star,
const multibody::RationalForwardKinematics& rational_forward_kin,
std::vector<PlaneSeparatesGeometries>* plane_geometries);
/*
Overloads GenerateRationals.
Use separating_planes as the map of the plane_index to the separating plane.
*/
void GenerateRationals(
const std::map<int, const CSpaceSeparatingPlane<symbolic::Variable>*>&
separating_planes,
const Vector3<symbolic::Variable>& y_slack,
const Eigen::Ref<const Eigen::VectorXd>& q_star,
const multibody::RationalForwardKinematics& rational_forward_kin,
std::vector<PlaneSeparatesGeometries>* plane_geometries);
/*
Returns the number of y_slack variables in `rational`.
Not all y_slack necessarily appear in `rational`.
*/
[[nodiscard]] int GetNumYInRational(const symbolic::RationalFunction& rational,
const Vector3<symbolic::Variable>& y_slack);
/*
Given a plant and associated scene graph, returns all
the collision geometries.
@return A map ret, such that ret[body_index] returns all the
CIrisCollisionGeometries attached to the body as body_index.
*/
[[nodiscard]] std::map<multibody::BodyIndex,
std::vector<std::unique_ptr<CIrisCollisionGeometry>>>
GetCollisionGeometries(const multibody::MultibodyPlant<double>& plant,
const geometry::SceneGraph<double>& scene_graph);
/*
Given a plant and associated scene graph compute all the possible collision
pairs between the bodies.
@param[in] link_geometries A map from body indices to a vector of non-null
pointers to CIrisCollisionGeometry.
@param[in, out] collision_pairs A non-null pointer to a map from pairs of
body indices to pairs of collision geometries which can collide on each of
the body indices.
@return The total number of collision pairs in the scene graph.
*/
[[nodiscard]] int GenerateCollisionPairs(
const multibody::MultibodyPlant<double>& plant,
const geometry::SceneGraph<double>& scene_graph,
const std::map<multibody::BodyIndex,
std::vector<std::unique_ptr<CIrisCollisionGeometry>>>&
link_geometries,
std::map<SortedPair<multibody::BodyIndex>,
std::vector<std::pair<const CIrisCollisionGeometry*,
const CIrisCollisionGeometry*>>>*
collision_pairs);
/*
Solves a SeparationCertificateProgram with the given options
@param[in, out] result Will always contain the MathematicalProgramResult and
plane_index associated to solving certificate_program. If a separation
certificate is found (i.e. result->result.is_success) then result will also
contain the plane parameters of the separating plane.
*/
void SolveSeparationCertificateProgramBase(
const SeparationCertificateProgramBase& certificate_program,
const FindSeparationCertificateOptions& options,
const CSpaceSeparatingPlane<symbolic::Variable>& separating_plane,
SeparationCertificateResultBase* result);
} // namespace internal
} // namespace optimization
} // namespace geometry
} // namespace drake
<file_sep>/multibody/plant/test/sap_driver_test.cc
#include "drake/multibody/plant/sap_driver.h"
#include <gtest/gtest.h>
#include "drake/common/test_utilities/eigen_matrix_compare.h"
#include "drake/common/test_utilities/expect_throws_message.h"
#include "drake/multibody/contact_solvers/contact_solver_results.h"
#include "drake/multibody/contact_solvers/contact_solver_utils.h"
#include "drake/multibody/contact_solvers/sap/sap_contact_problem.h"
#include "drake/multibody/contact_solvers/sap/sap_friction_cone_constraint.h"
#include "drake/multibody/contact_solvers/sap/sap_solver.h"
#include "drake/multibody/contact_solvers/sap/sap_solver_results.h"
#include "drake/multibody/plant/compliant_contact_manager.h"
#include "drake/multibody/plant/multibody_plant.h"
#include "drake/multibody/plant/test/compliant_contact_manager_tester.h"
#include "drake/multibody/plant/test/spheres_stack.h"
using drake::multibody::contact_solvers::internal::ContactSolverResults;
using drake::multibody::contact_solvers::internal::MergeNormalAndTangent;
using drake::multibody::contact_solvers::internal::SapContactProblem;
using drake::multibody::contact_solvers::internal::SapFrictionConeConstraint;
using drake::multibody::contact_solvers::internal::SapSolver;
using drake::multibody::contact_solvers::internal::SapSolverParameters;
using drake::multibody::contact_solvers::internal::SapSolverResults;
using drake::multibody::internal::DiscreteContactPair;
using drake::systems::Context;
using Eigen::MatrixXd;
using Eigen::Vector3d;
using Eigen::VectorXd;
// TODO(amcastro-tri): Implement AutoDiffXd testing.
namespace drake {
namespace multibody {
namespace internal {
constexpr double kEps = std::numeric_limits<double>::epsilon();
// Friend class used to provide access to a selection of private functions in
// SapDriver for testing purposes.
class SapDriverTest {
public:
static const ContactProblemCache<double>& EvalContactProblemCache(
const SapDriver<double>& driver, const Context<double>& context) {
return driver.EvalContactProblemCache(context);
}
static VectorXd CalcFreeMotionVelocities(const SapDriver<double>& driver,
const Context<double>& context) {
VectorXd v_star(driver.plant().num_velocities());
driver.CalcFreeMotionVelocities(context, &v_star);
return v_star;
}
static std::vector<MatrixXd> CalcLinearDynamicsMatrix(
const SapDriver<double>& driver, const Context<double>& context) {
std::vector<MatrixXd> A;
driver.CalcLinearDynamicsMatrix(context, &A);
return A;
}
static void PackContactSolverResults(
const SapDriver<double>& driver, const Context<double>& context,
const contact_solvers::internal::SapContactProblem<double>& problem,
int num_contacts,
const contact_solvers::internal::SapSolverResults<double>& sap_results,
contact_solvers::internal::ContactSolverResults<double>*
contact_results) {
driver.PackContactSolverResults(context, problem, num_contacts, sap_results,
contact_results);
}
};
// Test fixture to test the functionality provided by SapDriver, with the
// problem configuration implemented in SpheresStack (refer to that testing
// class for details on the configuration.)
class SpheresStackTest : public SpheresStack, public ::testing::Test {
public:
const SapDriver<double>& sap_driver() const {
return CompliantContactManagerTester::sap_driver(*contact_manager_);
}
// The functions below provide access to private SapDriver functions for unit
// testing.
const ContactProblemCache<double>& EvalContactProblemCache(
const Context<double>& context) const {
return SapDriverTest::EvalContactProblemCache(sap_driver(), context);
}
VectorXd CalcFreeMotionVelocities(const Context<double>& context) const {
VectorXd v_star(plant_->num_velocities());
return SapDriverTest::CalcFreeMotionVelocities(sap_driver(), context);
}
std::vector<MatrixXd> CalcLinearDynamicsMatrix(
const Context<double>& context) const {
return SapDriverTest::CalcLinearDynamicsMatrix(sap_driver(), context);
}
void PackContactSolverResults(
const Context<double>& context,
const contact_solvers::internal::SapContactProblem<double>& problem,
int num_contacts,
const contact_solvers::internal::SapSolverResults<double>& sap_results,
contact_solvers::internal::ContactSolverResults<double>* contact_results)
const {
SapDriverTest::PackContactSolverResults(sap_driver(), context, problem,
num_contacts, sap_results,
contact_results);
}
// The functions below provide access to private CompliantContactManager
// functions for unit testing.
const internal::MultibodyTreeTopology& topology() const {
return CompliantContactManagerTester::topology(*contact_manager_);
}
const std::vector<DiscreteContactPair<double>>& EvalDiscreteContactPairs(
const Context<double>& context) const {
return CompliantContactManagerTester::EvalDiscreteContactPairs(
*contact_manager_, context);
}
std::vector<ContactPairKinematics<double>> CalcContactKinematics(
const Context<double>& context) const {
return CompliantContactManagerTester::CalcContactKinematics(
*contact_manager_, context);
}
};
// This test verifies that the SapContactProblem built by the driver is
// consistent with the contact kinematics computed with CalcContactKinematics().
TEST_F(SpheresStackTest, EvalContactProblemCache) {
SetupRigidGroundCompliantSphereAndNonHydroSphere();
const ContactProblemCache<double>& problem_cache =
EvalContactProblemCache(*plant_context_);
const SapContactProblem<double>& problem = *problem_cache.sap_problem;
const std::vector<drake::math::RotationMatrix<double>>& R_WC =
problem_cache.R_WC;
const std::vector<DiscreteContactPair<double>>& pairs =
EvalDiscreteContactPairs(*plant_context_);
const int num_contacts = pairs.size();
// Verify sizes.
EXPECT_EQ(problem.num_cliques(), topology().num_trees());
EXPECT_EQ(problem.num_velocities(), plant_->num_velocities());
EXPECT_EQ(problem.num_constraints(), num_contacts);
EXPECT_EQ(problem.num_constraint_equations(), 3 * num_contacts);
EXPECT_EQ(problem.time_step(), plant_->time_step());
ASSERT_EQ(R_WC.size(), num_contacts);
// Verify dynamics data.
const VectorXd& v_star = CalcFreeMotionVelocities(*plant_context_);
const std::vector<MatrixXd>& A = CalcLinearDynamicsMatrix(*plant_context_);
EXPECT_EQ(problem.v_star(), v_star);
EXPECT_EQ(problem.dynamics_matrix(), A);
// Verify each of the contact constraints.
const std::vector<ContactPairKinematics<double>> contact_kinematics =
CalcContactKinematics(*plant_context_);
for (size_t i = 0; i < contact_kinematics.size(); ++i) {
const DiscreteContactPair<double>& discrete_pair = pairs[i];
const ContactPairKinematics<double>& pair_kinematics =
contact_kinematics[i];
const auto* constraint =
dynamic_cast<const SapFrictionConeConstraint<double>*>(
&problem.get_constraint(i));
// In this test we do know all constraints are contact constraints.
ASSERT_NE(constraint, nullptr);
EXPECT_EQ(constraint->num_cliques(), pair_kinematics.jacobian.size());
EXPECT_EQ(constraint->first_clique(), pair_kinematics.jacobian[0].tree);
EXPECT_EQ(constraint->first_clique_jacobian().MakeDenseMatrix(),
pair_kinematics.jacobian[0].J.MakeDenseMatrix());
if (constraint->num_cliques() == 2) {
EXPECT_EQ(constraint->second_clique(), pair_kinematics.jacobian[1].tree);
EXPECT_EQ(constraint->second_clique_jacobian().MakeDenseMatrix(),
pair_kinematics.jacobian[1].J.MakeDenseMatrix());
}
EXPECT_EQ(constraint->parameters().mu, discrete_pair.friction_coefficient);
EXPECT_EQ(constraint->parameters().stiffness, discrete_pair.stiffness);
EXPECT_EQ(constraint->parameters().dissipation_time_scale,
discrete_pair.dissipation_time_scale);
EXPECT_EQ(constraint->parameters().beta,
plant_->get_sap_near_rigid_threshold());
// This parameter sigma is for now hard-code in the manager to these value.
// Here we simply test they are consistent with those hard-coded values.
EXPECT_EQ(constraint->parameters().sigma, 1.0e-3);
// Verify contact configuration.
const contact_solvers::internal::ContactConfiguration<double>&
configuration = pair_kinematics.configuration;
EXPECT_EQ(constraint->configuration().objectA, configuration.objectA);
EXPECT_EQ(constraint->configuration().objectB, configuration.objectB);
EXPECT_EQ(constraint->configuration().p_ApC_W, configuration.p_ApC_W);
EXPECT_EQ(constraint->configuration().p_BqC_W, configuration.p_BqC_W);
EXPECT_EQ(constraint->configuration().phi, configuration.phi);
EXPECT_EQ(constraint->configuration().R_WC.matrix(), R_WC[i].matrix());
}
}
// Verifies the correctness of the computation of free motion velocities when
// external forces are applied.
TEST_F(SpheresStackTest, CalcFreeMotionVelocitiesWithExternalForces) {
SetupRigidGroundCompliantSphereAndNonHydroSphere();
// We set an arbitrary non-zero external force to the plant to verify it gets
// properly applied as part of the computation.
const int nv = plant_->num_velocities();
const VectorXd tau = VectorXd::LinSpaced(nv, 1.0, 2.0);
plant_->get_applied_generalized_force_input_port().FixValue(plant_context_,
tau);
// Set arbitrary non-zero velocities.
const VectorXd v0 = VectorXd::LinSpaced(nv, 2.0, 3.0);
plant_->SetVelocities(plant_context_, v0);
// Since the spheres's frames are located at their COM and since their
// rotational inertias are triaxially symmetric, the Coriolis term is zero.
// Therefore the momentum equation reduces to: M * (v-v0)/dt = tau_g + tau.
const double dt = plant_->time_step();
const VectorXd tau_g = plant_->CalcGravityGeneralizedForces(*plant_context_);
MatrixXd M(nv, nv);
plant_->CalcMassMatrix(*plant_context_, &M);
const VectorXd v_expected = v0 + dt * M.ldlt().solve(tau_g + tau);
// Compute the velocities the system would have next time step in the absence
// of constraints.
const VectorXd v_star = CalcFreeMotionVelocities(*plant_context_);
EXPECT_TRUE(
CompareMatrices(v_star, v_expected, kEps, MatrixCompareType::relative));
}
// Verifies that joint limit forces are applied.
TEST_F(SpheresStackTest, CalcFreeMotionVelocitiesWithJointLimits) {
// In this model sphere 1 is attached to the world by a prismatic joint with
// lower limit z = 0.
const bool sphere1_on_prismatic_joint = true;
SetupRigidGroundCompliantSphereAndNonHydroSphere(sphere1_on_prismatic_joint);
const int nv = plant_->num_velocities();
// Set arbitrary non-zero velocities.
const VectorXd non_zero_vs = VectorXd::LinSpaced(nv, 2.0, 3.0);
plant_->SetVelocities(plant_context_, non_zero_vs);
// The slider velocity is set to be negative to ensure the joint limit is
// active. That is, the position was set to be below the lower limit and in
// addition it is decreasing.
slider1_->set_translation_rate(plant_context_, -1.0);
// Initial velocities.
const VectorXd v0 = plant_->GetVelocities(*plant_context_);
// Compute slider1's velocity in the absence of joint limits. This is
// equivalent to computing the free motion velocities before constraints are
// applied.
const VectorXd v_expected = CalcFreeMotionVelocities(*plant_context_);
const double v_slider_no_limits = v_expected(slider1_->velocity_start());
// Compute slider1's velocity with constraints applied. This corresponds to
// the full discrete update computation.
ContactSolverResults<double> contact_results;
contact_manager_->CalcContactSolverResults(*plant_context_, &contact_results);
const VectorXd v_star = contact_results.v_next;
const double v_slider_star = v_star(slider1_->velocity_start());
// While other solver specific tests verify the correctness of joint limit
// forces, this test is simply limited to verifying the manager applied them.
// Therefore we only check the force limits have the effect of making the
// slider velocity larger than if not present.
EXPECT_GT(v_slider_star, v_slider_no_limits);
}
TEST_F(SpheresStackTest, CalcLinearDynamicsMatrix) {
SetupRigidGroundCompliantSphereAndNonHydroSphere();
const std::vector<MatrixXd> A = CalcLinearDynamicsMatrix(*plant_context_);
const int nv = plant_->num_velocities();
MatrixXd Adense = MatrixXd::Zero(nv, nv);
for (TreeIndex t(0); t < topology().num_trees(); ++t) {
const int tree_start = topology().tree_velocities_start(t);
const int tree_nv = topology().num_tree_velocities(t);
Adense.block(tree_start, tree_start, tree_nv, tree_nv) = A[t];
}
MatrixXd Aexpected(nv, nv);
plant_->CalcMassMatrix(*plant_context_, &Aexpected);
EXPECT_TRUE(
CompareMatrices(Adense, Aexpected, kEps, MatrixCompareType::relative));
}
// Here we test the function CompliantContactManager::PackContactSolverResults()
// which takes SapSolverResults and packs them into ContactSolverResults as
// consumed by MultibodyPlant.
TEST_F(SpheresStackTest, PackContactSolverResults) {
SetupRigidGroundCompliantSphereAndNonHydroSphere();
// We form an arbitrary set of SAP results consistent with the contact
// kinematics for the configuration of our model.
const std::vector<ContactPairKinematics<double>> contact_kinematics =
CalcContactKinematics(*plant_context_);
const int num_contacts = contact_kinematics.size();
const int nv = plant_->num_velocities();
SapSolverResults<double> sap_results;
sap_results.Resize(nv, 3 * num_contacts);
sap_results.v = VectorXd::LinSpaced(nv, -3.0, 14.0);
sap_results.gamma = VectorXd::LinSpaced(3 * num_contacts, -12.0, 8.0);
sap_results.vc = VectorXd::LinSpaced(3 * num_contacts, -1.0, 11.0);
// Not used to pack contact results.
sap_results.j = VectorXd::Constant(nv, NAN);
// Pack SAP results into contact results.
const SapContactProblem<double>& sap_problem =
*EvalContactProblemCache(*plant_context_).sap_problem;
ContactSolverResults<double> contact_results;
PackContactSolverResults(*plant_context_, sap_problem, num_contacts,
sap_results, &contact_results);
// Verify against expected values.
VectorXd gamma(3 * num_contacts);
MergeNormalAndTangent(contact_results.fn, contact_results.ft, &gamma);
gamma *= plant_->time_step();
EXPECT_TRUE(CompareMatrices(gamma, sap_results.gamma, kEps,
MatrixCompareType::relative));
VectorXd vc(3 * num_contacts);
MergeNormalAndTangent(contact_results.vn, contact_results.vt, &vc);
EXPECT_TRUE(
CompareMatrices(vc, sap_results.vc, kEps, MatrixCompareType::relative));
const MatrixXd J_AcBc_C =
CompliantContactManagerTester::CalcDenseJacobianMatrixInContactFrame(
*contact_manager_, contact_kinematics);
const VectorXd tau_expected =
J_AcBc_C.transpose() * sap_results.gamma / plant_->time_step();
EXPECT_TRUE(CompareMatrices(contact_results.tau_contact, tau_expected,
2.0 * kEps, MatrixCompareType::relative));
}
// Unit test that the manager throws an exception whenever SAP fails to
// converge.
TEST_F(SpheresStackTest, SapFailureException) {
SetupRigidGroundCompliantSphereAndNonHydroSphere();
ContactSolverResults<double> contact_results;
// To trigger SAP's failure, we limit the maximum number of iterations to
// zero.
SapSolverParameters parameters;
parameters.max_iterations = 0;
contact_manager_->set_sap_solver_parameters(parameters);
DRAKE_EXPECT_THROWS_MESSAGE(contact_manager_->CalcContactSolverResults(
*plant_context_, &contact_results),
"The SAP solver failed to converge(.|\n)*");
}
} // namespace internal
} // namespace multibody
} // namespace drake
|
b79922441be78aa772787c5e2f2fbcc4e27a40fa
|
[
"CMake",
"Markdown",
"Python",
"C++",
"Shell"
] | 28
|
CMake
|
hongkai-dai/drake
|
7904810e90b91fdef2bef54d7a5d806940165626
|
7fd528b9da306ac5045d9ac50a468118b043cd84
|
refs/heads/main
|
<repo_name>15831944/BoysGirl<file_sep>/src/BoysGirl/BoysGirl/BoysGirlApp.h
// BoysGirl.h : main header file for the PROJECT_NAME application
//
#pragma once
#ifndef __AFXWIN_H__
#error "include 'pch.h' before including this file for PCH"
#endif
#include "resource.h" // main symbols
#include "BoysGirlDlg.h"
#include "FloatDlg.h"
// CBoysGirlApp:
// See BoysGirl.cpp for the implementation of this class
//
class CBoysGirlApp : public CWinApp
{
public:
CBoysGirlApp();
// Overrides
public:
virtual BOOL InitInstance();
virtual int ExitInstance();
// Implementation
DECLARE_MESSAGE_MAP()
public:
std::shared_ptr<CBoysGirlDlg> m_pMainDlg = nullptr;
std::shared_ptr<CFloatDlg> m_pFloatDlg = nullptr;
};
extern CBoysGirlApp theApp;
<file_sep>/README.md
# BoysGirl
BoysGirl
<file_sep>/src/BoysGirl/BoysGirl/framework.h
#pragma once
#ifndef VC_EXTRALEAN
#define VC_EXTRALEAN // Exclude rarely-used stuff from Windows headers
#endif
#include "targetver.h"
#define _ATL_CSTRING_EXPLICIT_CONSTRUCTORS // some CString constructors will be explicit
// turns off MFC's hiding of some common and often safely ignored warning messages
#define _AFX_ALL_WARNINGS
#include <afxwin.h> // MFC core and standard components
#include <afxext.h> // MFC extensions
#include <afxdisp.h> // MFC Automation classes
#ifndef _AFX_NO_OLE_SUPPORT
#include <afxdtctl.h> // MFC support for Internet Explorer 4 Common Controls
#endif
#ifndef _AFX_NO_AFXCMN_SUPPORT
#include <afxcmn.h> // MFC support for Windows Common Controls
#endif // _AFX_NO_AFXCMN_SUPPORT
#include <afxcontrolbars.h> // MFC support for ribbons and control bars
#include <afxsock.h> // MFC socket extensions
#include <gdiplus.h>
#pragma comment(lib, "gdiplus")
#include <string>
#include <unordered_map>
#define WM_USER_NOTIFYICON WM_USER + WM_NOTIFY + 1
#if !defined(UNICODE) && !defined(_UNICODE)
#define TSTRING std::string
#else
#define TSTRING std::wstring
#endif
template <typename ...Args>
__inline static std::string format_string(const char* format, Args... args) {
char buffer[BUFSIZ] = { 0 };
size_t newlen = _snprintf(buffer, BUFSIZ, format, args...);
if (newlen > BUFSIZ)
{
std::vector<char> newbuffer(newlen + 1);
snprintf(newbuffer.data(), newlen, format, args...);
return std::string(newbuffer.data());
}
return buffer;
}
template <typename ...Args>
__inline static std::wstring format_string(const wchar_t* format, Args... args) {
wchar_t buffer[BUFSIZ] = { 0 };
size_t newlen = _snwprintf(buffer, BUFSIZ, format, args...);
if (newlen > BUFSIZ)
{
std::vector<wchar_t> newbuffer(newlen + 1);
_snwprintf(newbuffer.data(), newlen, format, args...);
return std::wstring(newbuffer.data());
}
return buffer;
}
//通用版将wstring转化为string
__inline std::string WToA(const std::wstring& ws, unsigned int cp = CP_ACP)
{
if (!ws.empty())
{
std::string s(WideCharToMultiByte(cp, 0, ws.data(), -1, NULL, 0, NULL, NULL), ('\0'));
return s.substr(0, WideCharToMultiByte(cp, 0, ws.c_str(), -1, (LPSTR)s.data(), (int)s.size(), NULL, NULL) - 1);
}
return ("");
}
//通用版将string转化为wstring
__inline std::wstring AToW(const std::string& s, unsigned int cp = CP_ACP)
{
if (!s.empty())
{
std::wstring ws(MultiByteToWideChar(cp, 0, s.data(), -1, NULL, 0), (L'\0'));
return ws.substr(0, MultiByteToWideChar(cp, 0, s.data(), -1, (LPWSTR)ws.data(), (int)ws.size()) - 1);
}
return (L"");
}
__inline static
#if !defined(UNICODE) && !defined(_UNICODE)
std::string
#else
std::wstring
#endif
AToT(const std::string& str)
{
#if !defined(UNICODE) && !defined(_UNICODE)
return str;
#else
return AToW(str);
#endif
}
__inline static
#if !defined(UNICODE) && !defined(_UNICODE)
std::string
#else
std::wstring
#endif
WToT(const std::wstring& wstr)
{
#if !defined(UNICODE) && !defined(_UNICODE)
return WToA(wstr);
#else
return wstr;
#endif
}
__inline static std::string TToA(
const
#if !defined(UNICODE) && !defined(_UNICODE)
std::string
#else
std::wstring
#endif
& tsT)
{
#if !defined(UNICODE) && !defined(_UNICODE)
return tsT;
#else
return WToA(tsT);
#endif
}
__inline static std::wstring TToW(
const
#if !defined(UNICODE) && !defined(_UNICODE)
std::string
#else
std::wstring
#endif
& tsT)
{
#if !defined(UNICODE) && !defined(_UNICODE)
return AToW(tsT);
#else
return tsT;
#endif
}
#define WToUTF8(X) WToA(X, CP_UTF8)
#define UTF8ToW(X) AToW(X, CP_UTF8)
#define AToUTF8(X) WToUTF8(AToW(X))
#define UTF8ToA(X) WToA(UTF8ToW(X))
//将From编码转化为To编码
__inline static std::string CodePage_FromTo(const std::string& str,
unsigned int from_codepage, unsigned int to_codepage)
{
return WToA(AToW(str, from_codepage), to_codepage);
}
//将UTF8转化为ANSI
__inline static std::string UTF8ToANSI(const std::string& str)
{
return CodePage_FromTo(str, CP_UTF8, CP_ACP);
}
//将ANSI转化为UTF8
__inline static std::string ANSIToUTF8(const std::string& str)
{
return CodePage_FromTo(str, CP_ACP, CP_UTF8);
}
__inline static std::string GetAppExe()
{
CHAR tFilePath[MAX_PATH] = { 0 };
GetModuleFileNameA(GetModuleHandleA(NULL), tFilePath, MAX_PATH);
return tFilePath;
}
__inline static std::string GetAppDir()
{
auto path = GetAppExe();
return path.substr(0, path.rfind("\\"));
}
// This macro is the same as IMPLEMENT_OLECREATE, except it passes TRUE
// for the bMultiInstance parameter to the COleObjectFactory constructor.
// We want a separate instance of this application to be launched for
// each automation proxy object requested by automation controllers.
#ifndef IMPLEMENT_OLECREATE2
#define IMPLEMENT_OLECREATE2(class_name, external_name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \
AFX_DATADEF COleObjectFactory class_name::factory(class_name::guid, \
RUNTIME_CLASS(class_name), TRUE, _T(external_name)); \
const AFX_DATADEF GUID class_name::guid = \
{ l, w1, w2, { b1, b2, b3, b4, b5, b6, b7, b8 } };
#endif // IMPLEMENT_OLECREATE2
#ifdef _UNICODE
#if defined _M_IX86
#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='x86' publicKeyToken='<KEY>' language='*'\"")
#elif defined _M_X64
#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='amd64' publicKeyToken='<KEY>' language='*'\"")
#else
#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='<KEY>' language='*'\"")
#endif
#endif
<file_sep>/src/BoysGirl/BoysGirl/CustomButton.cpp
// CustomButton.cpp : implementation file
//
#include "pch.h"
#include "CustomButton.h"
// CCustomButton
IMPLEMENT_DYNAMIC(CCustomButton, CButton)
CCustomButton::CCustomButton()
{
#ifndef _WIN32_WCE
EnableActiveAccessibility();
#endif
}
CCustomButton::~CCustomButton()
{
}
BEGIN_MESSAGE_MAP(CCustomButton, CButton)
END_MESSAGE_MAP()
// CCustomButton message handlers
void CCustomButton::DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct)
{
// TODO: Add your code to draw the specified item
int nOldBkMode = SetBkMode(lpDrawItemStruct->hDC, TRANSPARENT);
UINT uStyle = DFCS_BUTTONPUSH;
// This code only works with buttons.
ASSERT(lpDrawItemStruct->CtlType == ODT_BUTTON);
// If drawing selected, add the pushed style to DrawFrameControl.
if (lpDrawItemStruct->itemState & ODS_SELECTED)
{
//鼠标被按下
uStyle |= DFCS_PUSHED;
}
else
{
//鼠标不操作或被弹起
}
if ((lpDrawItemStruct->itemState & ODS_SELECTED) && (lpDrawItemStruct->itemAction & (ODA_SELECT | ODA_DRAWENTIRE)))
{
//选中了本控件,高亮边框
}
if (!(lpDrawItemStruct->itemState & ODS_SELECTED) && (lpDrawItemStruct->itemAction & ODA_SELECT))
{
//控制的选中状态结束,去掉边框
}
// Draw the button frame.
::DrawFrameControl(lpDrawItemStruct->hDC, &lpDrawItemStruct->rcItem, DFC_BUTTON, uStyle);
{
std::wstring btnokImgFile = AToW(GetAppDir() + "\\res\\btnbg.png");
Gdiplus::Graphics g(lpDrawItemStruct->hDC);
Gdiplus::Image* btnokImg = Gdiplus::Image::FromFile(btnokImgFile.c_str());
if (btnokImg != nullptr)
{
if (btnokImg->GetLastStatus() == Gdiplus::Ok)
{
//Gdiplus::SolidBrush borderBrush(Gdiplus::Color(100, 20, 20, 20));
//g.FillRectangle(&borderBrush, lpDrawItemStruct->rcItem.left, lpDrawItemStruct->rcItem.top, lpDrawItemStruct->rcItem.right, lpDrawItemStruct->rcItem.bottom);
g.DrawImage(btnokImg, lpDrawItemStruct->rcItem.left+1, lpDrawItemStruct->rcItem.top+1, lpDrawItemStruct->rcItem.right-2, lpDrawItemStruct->rcItem.bottom-2);
}
delete btnokImg;
}
}
// Get the button's text.
CString strText;
GetWindowText(strText);
// Draw the button text using the text color red.
COLORREF crOldColor = ::SetTextColor(lpDrawItemStruct->hDC, RGB(255, 0, 0));
::DrawText(lpDrawItemStruct->hDC, strText, strText.GetLength(), &lpDrawItemStruct->rcItem, DT_SINGLELINE | DT_VCENTER | DT_CENTER);
::SetTextColor(lpDrawItemStruct->hDC, crOldColor);
SetBkMode(lpDrawItemStruct->hDC, nOldBkMode);
}
void CCustomButton::PreSubclassWindow()
{
CButton::PreSubclassWindow();
ModifyStyle(0, BS_OWNERDRAW);
ModifyStyleEx(0, WS_EX_TRANSPARENT);
}
<file_sep>/src/BoysGirl/BoysGirl/FloatDlg.cpp
// FloatDlg.cpp : implementation file
//
#include "pch.h"
#include "BoysGirlApp.h"
#include "FloatDlg.h"
#include "afxdialogex.h"
// CFloatDlg dialog
IMPLEMENT_DYNAMIC(CFloatDlg, CDialogEx)
CFloatDlg::CFloatDlg(CWnd* pParent /*=nullptr*/)
: CDialogEx(IDD_FLOAT_DIALOG, pParent)
{
m_isDlgInited = false;
}
CFloatDlg::~CFloatDlg()
{
}
void CFloatDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CFloatDlg, CDialogEx)
ON_WM_MOVE()
ON_WM_LBUTTONDOWN()
ON_WM_LBUTTONDBLCLK()
END_MESSAGE_MAP()
// CFloatDlg message handlers
BOOL CFloatDlg::OnInitDialog()
{
LoadPosition();
::SetWindowLongPtr(this->GetSafeHwnd(), GWL_STYLE, GetWindowLongPtr(this->GetSafeHwnd(), GWL_STYLE) & (~WS_CAPTION));
::SetWindowLongPtr(this->GetSafeHwnd(), GWL_EXSTYLE, GetWindowLongPtr(this->GetSafeHwnd(), GWL_EXSTYLE) | WS_EX_TOPMOST | WS_EX_TOOLWINDOW & (~WS_EX_APPWINDOW));
GetDlgItem(IDOK)->ShowWindow(SW_HIDE);
GetDlgItem(IDCANCEL)->ShowWindow(SW_HIDE);
SetWindowPos(&CWnd::wndNoTopMost, 0, 0, 64, 64, SWP_NOZORDER | SWP_NOMOVE | SWP_FRAMECHANGED);
m_isDlgInited = true;
return FALSE;
}
void CFloatDlg::OnMove(int x, int y)
{
CDialogEx::OnMove(x, y);
// TODO: Add your message handler code here
if (m_isDlgInited == true)
{
SavePosition();
}
}
void CFloatDlg::OnLButtonDown(UINT nFlags, CPoint point)
{
// TODO: Add your message handler code here and/or call default
PostMessage(WM_NCLBUTTONDOWN, HTCAPTION, MAKELPARAM(point.x, point.y));
CDialogEx::OnLButtonDown(nFlags, point);
}
void CFloatDlg::OnLButtonDblClk(UINT nFlags, CPoint point)
{
// TODO: Add your message handler code here and/or call default
CDialogEx::OnLButtonDblClk(nFlags, point);
theApp.m_pMainDlg->ShowOrHideWindow();
}
void CFloatDlg::ShowTopMost()
{
SetWindowPos(&CWnd::wndTopMost, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_SHOWWINDOW);
}
void CFloatDlg::LoadPosition()
{
CString text = theApp.GetProfileString(TEXT("POINT"), TEXT("FLOAT"), TEXT("(0,0)"));
_stscanf_s(text, TEXT("(%d,%d)"), &m_ptPos.x, &m_ptPos.y);
SetWindowPos(&CWnd::wndTopMost, m_ptPos.x, m_ptPos.y, 0, 0, SWP_NOSIZE | SWP_NOACTIVATE | SWP_FRAMECHANGED);
}
void CFloatDlg::SavePosition()
{
CRect rc = { 0 };
CString text(TEXT(""));
this->GetWindowRect(rc);
m_ptPos.x = rc.left;
m_ptPos.y = rc.top;
text.Format(TEXT("(%d,%d)"), m_ptPos.x, m_ptPos.y);
theApp.WriteProfileString(TEXT("POINT"), TEXT("FLOAT"), text);
}<file_sep>/src/BoysGirl/BoysGirl/CustomButton.h
#pragma once
// CCustomButton
class CCustomButton : public CButton
{
DECLARE_DYNAMIC(CCustomButton)
public:
CCustomButton();
virtual ~CCustomButton();
protected:
virtual void PreSubclassWindow();
virtual void DrawItem(LPDRAWITEMSTRUCT /*lpDrawItemStruct*/);
DECLARE_MESSAGE_MAP()
};
<file_sep>/src/BoysGirl/BoysGirl/BoysGirlDlg.cpp
// BoysGirlDlg.cpp : implementation file
//
#include "pch.h"
#include "framework.h"
#include "BoysGirlApp.h"
#include "BoysGirlDlg.h"
#include "BoysGirlDlgProxy.h"
#include "afxdialogex.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CAboutDlg dialog used for App About
class CAboutDlg : public CDialogEx
{
public:
CAboutDlg();
// Dialog Data
#ifdef AFX_DESIGN_TIME
enum { IDD = IDD_ABOUTBOX };
#endif
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
// Implementation
protected:
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialogEx(IDD_ABOUTBOX)
{
EnableActiveAccessibility();
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
END_MESSAGE_MAP()
// CBoysGirlDlg dialog
IMPLEMENT_DYNAMIC(CBoysGirlDlg, CDialogEx);
CBoysGirlDlg::CBoysGirlDlg(CWnd* pParent /*=nullptr*/)
: CDialogEx(IDD_BOYSGIRL_DIALOG, pParent)
{
}
CBoysGirlDlg::~CBoysGirlDlg()
{
}
void CBoysGirlDlg::DoDataExchange(CDataExchange* pDX)
{
CDialogEx::DoDataExchange(pDX);
DDX_Control(pDX, IDOK, m_btnOk);
DDX_Control(pDX, IDCANCEL, m_btnCancel);
}
BEGIN_MESSAGE_MAP(CBoysGirlDlg, CDialogEx)
ON_WM_SYSCOMMAND()
ON_WM_CLOSE()
ON_WM_PAINT()
ON_WM_SIZE()
ON_WM_NCCALCSIZE()
ON_WM_NCHITTEST()
ON_WM_ERASEBKGND()
ON_COMMAND(RESTYPEID::IDMENU_CONFIG, OnMenuConfig)
ON_MESSAGE(WM_USER_NOTIFYICON, OnNotifyMsg)
ON_REGISTERED_MESSAGE(WMEX_TASKBARCREATED, OnRestartExplorer)
ON_WM_CTLCOLOR()
ON_WM_CREATE()
ON_WM_GETMINMAXINFO()
END_MESSAGE_MAP()
// CBoysGirlDlg message handlers
void CBoysGirlDlg::Init()
{
EnableActiveAccessibility();
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
m_pAutoProxy = nullptr;
{
IconBitmapHandle iconBitmapHandle = { 0 };
GdiplusBitmapFromHICON(iconBitmapHandle, m_hIcon);
}
AddNotifyIcon();
SystemParametersInfo(SPI_SETDRAGFULLWINDOWS, FALSE, NULL, 0);
/*#ifndef SPI_GETWINARRANGING
#define SPI_GETWINARRANGING 0x0082
#endif
#ifndef SPI_SETWINARRANGING
#define SPI_SETWINARRANGING 0x0083
#endif
#ifndef SPI_GETSNAPSIZING
#define SPI_GETSNAPSIZING 0x008E
#endif
#ifndef SPI_SETSNAPSIZING
#define SPI_SETSNAPSIZING 0x008F
#endif*/
// 拖拽前
//BOOL fWinArrange;
//BOOL fSnapSizing;
//SystemParametersInfo(SPI_GETWINARRANGING, 0, (LPVOID)&fWinArrange, 0);
//SystemParametersInfo(SPI_GETSNAPSIZING, 0, (LPVOID)&fSnapSizing, 0);
//SystemParametersInfo(SPI_SETWINARRANGING, 0, (LPVOID)FALSE, 0);
//SystemParametersInfo(SPI_SETSNAPSIZING, 0, (LPVOID)TRUE, 0);
//SystemParametersInfo(SPI_SETSNAPSIZING, 0, NULL, SPIF_SENDCHANGE | SPIF_UPDATEINIFILE);
// 拖拽后
//SystemParametersInfo(SPI_SETWINARRANGING, 0, (LPVOID)fWinArrange, 0);
//SystemParametersInfo(SPI_SETSNAPSIZING, 0, (LPVOID)fSnapSizing, 0);
}
void CBoysGirlDlg::Exit()
{
// If there is an automation proxy for this dialog, set
// its back pointer to this dialog to null, so it knows
// the dialog has been deleted.
if (m_pAutoProxy != nullptr)
{
m_pAutoProxy->m_pDialog = nullptr;
}
DelNotifyIcon();
if (!m_iconBitmapHandleMap.empty())
{
for (auto& it : m_iconBitmapHandleMap)
{
if (it.second.pBitmapArgb != nullptr)
{
delete it.second.pBitmapArgb;
}
if (it.second.pBitmapIcon != nullptr)
{
delete it.second.pBitmapIcon;
}
}
m_iconBitmapHandleMap.clear();
}
SystemParametersInfo(SPI_SETDRAGFULLWINDOWS, TRUE, NULL, 0);
}
BOOL CBoysGirlDlg::OnInitDialog()
{
CDialogEx::OnInitDialog();
// Add "About..." menu item to system menu.
// IDM_ABOUTBOX must be in the system command range.
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != nullptr)
{
BOOL bNameValid;
CString strAboutMenu;
bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
ASSERT(bNameValid);
if (!strAboutMenu.IsEmpty())
{
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
}
}
Init();
// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
// TODO: Add extra initialization here
SetWindowPos(&CWnd::wndNoTopMost, 0, 0, 0, 0, SWP_NOZORDER | SWP_NOMOVE | SWP_NOSIZE | SWP_FRAMECHANGED);
theApp.m_pFloatDlg->ShowTopMost();
return TRUE; // return TRUE unless you set the focus to a control
}
void CBoysGirlDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == IDM_ABOUTBOX)
{
CAboutDlg dlgAbout;
dlgAbout.DoModal();
}
else
{
CDialogEx::OnSysCommand(nID, lParam);
NotifyUpdate();
}
}
// If you add a minimize button to your dialog, you will need the code below
// to draw the icon. For MFC applications using the document/view model,
// this is automatically done for you by the framework.
void CBoysGirlDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // device context for painting
SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);
// Center icon in client rectangle
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// Draw the icon
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CPaintDC dc(this);
MemoryDoubleBuffer(dc.m_hDC);
ReleaseDC(&dc);
CDialogEx::OnPaint();
}
}
// The system calls this function to obtain the cursor to display while the user drags
// the minimized window.
HCURSOR CBoysGirlDlg::OnQueryDragIcon()
{
return static_cast<HCURSOR>(m_hIcon);
}
// Automation servers should not exit when a user closes the UI
// if a controller still holds on to one of its objects. These
// message handlers make sure that if the proxy is still in use,
// then the UI is hidden but the dialog remains around if it
// is dismissed.
void CBoysGirlDlg::OnClose()
{
if (CanExit())
{
CDialogEx::OnClose();
}
}
void CBoysGirlDlg::OnOK()
{
if (CanExit())
{
CDialogEx::OnOK();
}
}
void CBoysGirlDlg::OnCancel()
{
if (CanExit())
{
CDialogEx::OnCancel();
}
}
BOOL CBoysGirlDlg::CanExit()
{
// If the proxy object is still around, then the automation
// controller is still holding on to this application. Leave
// the dialog around, but hide its UI.
if (m_pAutoProxy != nullptr)
{
ShowWindow(SW_HIDE);
return FALSE;
}
Exit();
return TRUE;
}
LRESULT CBoysGirlDlg::OnNcHitTest(CPoint point)
{
// TODO: Add your message handler code here and/or call default
UINT uHitTest = 0;
CRect rect = {};
GetWindowRect(&rect);
CRect rectNoBorder = rect;
rectNoBorder.DeflateRect(BORDER_SIZE, BORDER_SIZE, -BORDER_SIZE, -BORDER_SIZE);
rectNoBorder.NormalizeRect();
if (point.x <= rect.left + BORDER_SIZE && point.y <= rect.top + BORDER_SIZE)
{
uHitTest = HTTOPLEFT;
}
else if (point.x >= rect.right - BORDER_SIZE && point.y <= rect.top + BORDER_SIZE)
{
uHitTest = HTTOPRIGHT;
}
else if (point.x <= rect.left + BORDER_SIZE && point.y >= rect.bottom - BORDER_SIZE)
{
uHitTest = HTBOTTOMLEFT;
}
else if (point.x >= rect.right - BORDER_SIZE && point.y >= rect.bottom - BORDER_SIZE)
{
uHitTest = HTBOTTOMRIGHT;
}
else if (point.x <= rect.left + BORDER_SIZE)
{
uHitTest = HTLEFT;
}
else if (point.x >= rect.right - BORDER_SIZE)
{
uHitTest = HTRIGHT;
}
else if (point.y <= rect.top + BORDER_SIZE)
{
uHitTest = HTTOP;
}
else if (point.y >= rect.bottom - BORDER_SIZE)
{
uHitTest = HTBOTTOM;
}
else if (!rectNoBorder.IsRectEmpty())
{
if (point.y > 0 && point.y < (rect.top + m_titleBarHeight))
{
uHitTest = HTCAPTION;
}
else
{
uHitTest = (decltype(uHitTest))CWnd::OnNcHitTest(point);
}
//LRESULT lRet = CWnd::OnNcHitTest(point);
//lRet = (lRet == HTCLIENT) ? HTCAPTION : lRet;
//return lRet;
}
else
{
uHitTest = (decltype(uHitTest))CWnd::OnNcHitTest(point);
}
return (LRESULT)uHitTest;
//return CDialogEx::OnNcHitTest(point);
}
void CBoysGirlDlg::OnMenuConfig(void)
{
AfxMessageBox(TEXT("配置"));
}
LRESULT CBoysGirlDlg::OnNotifyMsg(WPARAM wParam, LPARAM lParam)
{
//wParam接收的是图标的ID,而lParam接收的是鼠标的行为
if (wParam != IDR_MAINFRAME)
{
return TRUE;
}
switch (lParam)
{
case WM_RBUTTONUP:
{
CMenu menu = {};
POINT pt = { 0 };
::GetCursorPos(&pt);
menu.CreatePopupMenu();
menu.AppendMenu(MF_STRING, IDMENU_CONFIG, TEXT("配置"));
menu.AppendMenu(MF_STRING, WM_DESTROY, TEXT("退出"));
menu.TrackPopupMenu(TPM_LEFTALIGN, pt.x, pt.y, this);
menu.Detach();
menu.DestroyMenu();
}
break;
case WM_LBUTTONDBLCLK:
{
ShowOrHideWindow();
}
break;
}
return FALSE;
}
LRESULT CBoysGirlDlg::OnRestartExplorer(WPARAM wParam, LPARAM lParam)
{
AddNotifyIcon();
return TRUE;
}
void CBoysGirlDlg::OnNcCalcSize(BOOL bCalcValidRects, NCCALCSIZE_PARAMS* lpncsp)
{
if (bCalcValidRects == TRUE)
{
if (IsZoomed())
{
CRect rc = {};
SystemParametersInfo(SPI_GETWORKAREA, 0, (PVOID)&rc, 0);
lpncsp->rgrc[0].left = 0;
lpncsp->rgrc[0].top = 0;
lpncsp->rgrc[0].right += lpncsp->lppos->x;
lpncsp->rgrc[0].bottom += lpncsp->lppos->y;
lpncsp->rgrc[0].right = rc.Width();
lpncsp->rgrc[0].bottom = rc.Height();
lpncsp->lppos->x = 0;
lpncsp->lppos->y = 0;
}
lpncsp->rgrc[2] = lpncsp->rgrc[1];
lpncsp->rgrc[1] = lpncsp->rgrc[0];
}
}
void CBoysGirlDlg::OnSize(UINT nType, int cx, int cy)
{
// TODO: Add your message handler code here and/or call default
CDialogEx::OnSize(nType, cx, cy);
NotifyUpdate();
}
BOOL CBoysGirlDlg::OnEraseBkgnd(CDC* pDC)
{
// TODO: Add your message handler code here and/or call default
return TRUE;// CDialogEx::OnEraseBkgnd(pDC);
}
HBRUSH CBoysGirlDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
HBRUSH hbr = CDialogEx::OnCtlColor(pDC, pWnd, nCtlColor);
// TODO: Change any attributes of the DC here
switch (nCtlColor)
{
case CTLCOLOR_STATIC:
{
pDC->SetBkMode(TRANSPARENT);
hbr = (HBRUSH) ::GetStockObject(HOLLOW_BRUSH);
}
break;
}
switch (pWnd->GetDlgCtrlID())
{
case IDOK:
case IDCANCEL:
case IDC_STATIC:
{
pDC->SetBkMode(TRANSPARENT);
hbr = (HBRUSH) ::GetStockObject(HOLLOW_BRUSH);
}
break;
}
// TODO: Return a different brush if the default is not desired
return hbr;
}
int CBoysGirlDlg::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CDialogEx::OnCreate(lpCreateStruct) == -1)
return -1;
// TODO: Add your specialized creation code here
CRect rc = {};
SystemParametersInfo(SPI_GETWORKAREA, 0, (PVOID)&rc, 0);
SetClassLongPtr(this->GetSafeHwnd(), GCL_STYLE, GetClassLongPtr(this->GetSafeHwnd(), GCL_STYLE) | CS_DROPSHADOW);
if (IsVistaOrLater())
{
SetWindowLongPtr(this->GetSafeHwnd(), GWL_STYLE, GetWindowLongPtr(this->GetSafeHwnd(), GWL_STYLE) | (WS_SYSMENU | WS_MINIMIZEBOX | WS_MAXIMIZEBOX | WS_SIZEBOX | WS_THICKFRAME) & (~WS_DLGFRAME) & (~WS_BORDER));
SetWindowLongPtr(this->GetSafeHwnd(), GWL_EXSTYLE, GetWindowLongPtr(this->GetSafeHwnd(), GWL_EXSTYLE) | (WS_EX_LEFT | WS_EX_LTRREADING | WS_EX_RIGHTSCROLLBAR) & (~WS_EX_CLIENTEDGE) & (~WS_EX_WINDOWEDGE));
}
else
{
SetWindowLongPtr(this->GetSafeHwnd(), GWL_STYLE, GetStyle()&(WS_OVERLAPPED | WS_VISIBLE | WS_SYSMENU | WS_MINIMIZEBOX | WS_MAXIMIZEBOX | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_SIZEBOX | WS_THICKFRAME | WS_DLGFRAME));
SetWindowLongPtr(this->GetSafeHwnd(), GWL_EXSTYLE, GetExStyle()&(WS_EX_LEFT | WS_EX_LTRREADING | WS_EX_RIGHTSCROLLBAR));
}
return 0;
}
void CBoysGirlDlg::OnGetMinMaxInfo(MINMAXINFO* lpMMI)
{
// TODO: Add your message handler code here and/or call default
// 调整最小宽度与高度
lpMMI->ptMinTrackSize.x = 800;
lpMMI->ptMinTrackSize.y = 600;
// 调整最大宽度与高度
lpMMI->ptMaxTrackSize.x = GetSystemMetrics(SM_CXSCREEN) + GetSystemMetrics(SM_CYFIXEDFRAME) + GetSystemMetrics(SM_CXEDGE) + GetSystemMetrics(SM_CXBORDER) + GetSystemMetrics(SM_CYFIXEDFRAME) + GetSystemMetrics(SM_CXEDGE) + GetSystemMetrics(SM_CXBORDER);
lpMMI->ptMaxTrackSize.y = GetSystemMetrics(SM_CYSCREEN);
CDialogEx::OnGetMinMaxInfo(lpMMI);
}
<file_sep>/src/BoysGirl/BoysGirl/FloatDlg.h
#pragma once
// CFloatDlg dialog
class CFloatDlg : public CDialogEx
{
DECLARE_DYNAMIC(CFloatDlg)
public:
CFloatDlg(CWnd* pParent = nullptr); // standard constructor
virtual ~CFloatDlg();
// Dialog Data
#ifdef AFX_DESIGN_TIME
enum { IDD = IDD_FLOAT_DIALOG };
#endif
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
virtual BOOL OnInitDialog();
afx_msg void OnMove(int x, int y);
afx_msg void OnLButtonDown(UINT nFlags, CPoint point);
afx_msg void OnLButtonDblClk(UINT nFlags, CPoint point);
DECLARE_MESSAGE_MAP()
private:
POINT m_ptPos = { 0,0 };
bool m_isDlgInited = false;
public:
void ShowTopMost();
void LoadPosition();
void SavePosition();
};
<file_sep>/src/BoysGirl/BoysGirl/BoysGirlDlgProxy.h
// BoysGirlDlgProxy.h: header file
//
#pragma once
class CBoysGirlDlg;
// CBoysGirlDlgAutoProxy command target
class CBoysGirlDlgAutoProxy : public CCmdTarget
{
DECLARE_DYNCREATE(CBoysGirlDlgAutoProxy)
CBoysGirlDlgAutoProxy(); // protected constructor used by dynamic creation
// Attributes
public:
CBoysGirlDlg* m_pDialog;
// Operations
public:
// Overrides
public:
virtual void OnFinalRelease();
// Implementation
protected:
virtual ~CBoysGirlDlgAutoProxy();
// Generated message map functions
DECLARE_MESSAGE_MAP()
DECLARE_OLECREATE(CBoysGirlDlgAutoProxy)
// Generated OLE dispatch map functions
DECLARE_DISPATCH_MAP()
DECLARE_INTERFACE_MAP()
};
<file_sep>/src/BoysGirl/BoysGirl/BoysGirlDlg.h
// BoysGirlDlg.h : header file
//
#pragma once
#include <CustomButton.h>
class CBoysGirlDlgAutoProxy;
const UINT WMEX_TASKBARCREATED = ::RegisterWindowMessage(TEXT("TaskbarCreated"));
typedef enum RESTYPEID {
ID_NULLPTR = 1000,
IDMENU_CONFIG,
}RESTYPEID;
// CBoysGirlDlg dialog
class CBoysGirlDlg : public CDialogEx
{
DECLARE_DYNAMIC(CBoysGirlDlg);
friend class CBoysGirlDlgAutoProxy;
// Construction
public:
CBoysGirlDlg(CWnd* pParent = nullptr); // standard constructor
virtual ~CBoysGirlDlg();
// Dialog Data
#ifdef AFX_DESIGN_TIME
enum { IDD = IDD_BOYSGIRL_DIALOG };
#endif
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
// Implementation
protected:
CBoysGirlDlgAutoProxy* m_pAutoProxy;
HICON m_hIcon;
BOOL CanExit();
// Generated message map functions
virtual BOOL OnInitDialog();
virtual void OnOK();
virtual void OnCancel();
afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
afx_msg void OnPaint();
afx_msg HCURSOR OnQueryDragIcon();
afx_msg void OnClose();
afx_msg BOOL OnEraseBkgnd(CDC* pDC);
afx_msg void OnSize(UINT nType, int cx, int cy);
afx_msg HBRUSH OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor);
afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
afx_msg void OnGetMinMaxInfo(MINMAXINFO* lpMMI);
afx_msg LRESULT OnNcHitTest(CPoint point);
afx_msg void OnNcCalcSize(BOOL bCalcValidRects, NCCALCSIZE_PARAMS* lpncsp);
afx_msg LRESULT OnNotifyMsg(WPARAM wParam, LPARAM lParam);
afx_msg LRESULT OnRestartExplorer(WPARAM wParam, LPARAM lParam);
afx_msg void OnMenuConfig(void);
DECLARE_MESSAGE_MAP()
private:
void Init();
void Exit();
private:
typedef struct MsgCursor {
UINT uMsg;
LPTSTR pCursor;
}MsgCursor;
const std::unordered_map<UINT, MsgCursor> m_mapMsgCursor = {
{HTTOP, {SC_SIZE | WMSZ_TOP, IDC_SIZENS}},
{HTBOTTOM, {SC_SIZE | WMSZ_BOTTOM, IDC_SIZENS}},
{HTLEFT, {SC_SIZE | WMSZ_LEFT, IDC_SIZEWE}},
{HTRIGHT, {SC_SIZE | WMSZ_RIGHT, IDC_SIZEWE}},
{HTTOPLEFT, {SC_SIZE | WMSZ_TOPLEFT, IDC_SIZENWSE}},
{HTTOPRIGHT, {SC_SIZE | WMSZ_TOPRIGHT, IDC_SIZENESW}},
{HTBOTTOMLEFT, {SC_SIZE | WMSZ_BOTTOMLEFT, IDC_SIZENESW}},
{HTBOTTOMRIGHT, {SC_SIZE | WMSZ_BOTTOMRIGHT, IDC_SIZENWSE}},
{HTCAPTION, {SC_MOVE | WMSZ_TOPLEFT, NULL}},
};
private:
int BORDER_SIZE = 6;
int m_titleBarHeight = 30;
private:
NOTIFYICONDATA m_notifyIconData = { 0 };
void AddNotifyIcon()
{
m_notifyIconData.cbSize = sizeof NOTIFYICONDATA;
m_notifyIconData.hWnd = this->m_hWnd;
m_notifyIconData.uID = IDR_MAINFRAME;
m_notifyIconData.hIcon = m_hIcon;
lstrcpy(m_notifyIconData.szTip, TEXT("BoysGirl"));
m_notifyIconData.uCallbackMessage = WM_USER_NOTIFYICON;
m_notifyIconData.uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
Shell_NotifyIcon(NIM_ADD, &m_notifyIconData);
}
void ModNotifyIconText(const TSTRING& text)
{
lstrcpy(m_notifyIconData.szTip, text.c_str());
}
void DelNotifyIcon()
{
Shell_NotifyIcon(NIM_DELETE, &m_notifyIconData);
}
private:
typedef struct IconBitmapHandle {
Gdiplus::Bitmap* pBitmapArgb;
Gdiplus::Bitmap* pBitmapIcon;
}IconBitmapHandle;
std::unordered_map<HICON, IconBitmapHandle> m_iconBitmapHandleMap = {};
private:
IconBitmapHandle& GdiplusBitmapFromHICON(IconBitmapHandle & iconBitmapHandle, HICON hIcon)
{
iconBitmapHandle.pBitmapArgb = nullptr;
iconBitmapHandle.pBitmapIcon = nullptr;
auto it = m_iconBitmapHandleMap.find(hIcon);
if (it == m_iconBitmapHandleMap.end())
{
ICONINFO iconInfo = { 0 };
if (GetIconInfo(hIcon, &iconInfo) && iconInfo.fIcon == TRUE)
{
iconBitmapHandle.pBitmapIcon = Gdiplus::Bitmap::FromHBITMAP(iconInfo.hbmColor, NULL);
if (iconBitmapHandle.pBitmapIcon != nullptr)
{
Gdiplus::BitmapData bitmapData = {};
Gdiplus::Rect rcImage(0, 0, iconBitmapHandle.pBitmapIcon->GetWidth(), iconBitmapHandle.pBitmapIcon->GetHeight());
iconBitmapHandle.pBitmapIcon->LockBits(&rcImage, Gdiplus::ImageLockModeRead, iconBitmapHandle.pBitmapIcon->GetPixelFormat(), &bitmapData);
iconBitmapHandle.pBitmapArgb = new Gdiplus::Bitmap(bitmapData.Width, bitmapData.Height, bitmapData.Stride, PixelFormat32bppARGB, (BYTE*)bitmapData.Scan0);
if (iconBitmapHandle.pBitmapArgb != nullptr)
{
m_iconBitmapHandleMap.emplace(m_hIcon, iconBitmapHandle);
}
iconBitmapHandle.pBitmapIcon->UnlockBits(&bitmapData);
}
}
}
return iconBitmapHandle;
}
void MemoryDoubleBuffer(HDC hDC)
{
CRect rc = {};
GetClientRect(&rc);
Gdiplus::Bitmap bitmapMem(rc.Width(), rc.Height());
Gdiplus::Graphics graphicsMem(&bitmapMem);
graphicsMem.Clear(Gdiplus::Color(0, 255, 255, 255));
graphicsMem.SetSmoothingMode(Gdiplus::SmoothingModeHighQuality);
PaintBackground(graphicsMem, rc);
PaintTitleBar(graphicsMem, rc);
Gdiplus::Graphics graphics(hDC);
Gdiplus::CachedBitmap cachedBmp(&bitmapMem, &graphics);
graphics.DrawCachedBitmap(&cachedBmp, 0, 0);
Gdiplus::Image* btnokImg = Gdiplus::Image::FromFile(this->btnokImg.c_str());
Gdiplus::Graphics g(GetDlgItem(IDOK)->GetWindowDC()->m_hDC);
g.DrawImage(btnokImg, 0, 0);
delete btnokImg;
}
void PaintBackground(Gdiplus::Graphics& graphicsMem, const CRect& rc)
{
Gdiplus::Image* bg = Gdiplus::Image::FromFile(bgImg.c_str());
if (bg != nullptr)
{
if (bg->GetLastStatus() == Gdiplus::Ok)
{
graphicsMem.DrawImage(bg, 0, 0, rc.Width(), rc.Height());
}
else
{
Gdiplus::SolidBrush bgBrush(Gdiplus::Color(60, 90, 20));
graphicsMem.FillRectangle(&bgBrush, rc.left, rc.top, rc.Width(), rc.Height());
}
delete bg;
}
}
void PaintTitleBar(Gdiplus::Graphics& graphicsMem, const CRect & rc)
{
Gdiplus::SolidBrush titleBrush(Gdiplus::Color(20, 150, 250));
Gdiplus::SolidBrush borderBrush(Gdiplus::Color(20, 150, 250));
//绘制标题栏
graphicsMem.FillRectangle(&titleBrush, rc.left, rc.top, rc.Width(), m_titleBarHeight);
//绘制左边框
graphicsMem.FillRectangle(&borderBrush, rc.left, rc.top, BORDER_SIZE, rc.Height());
//绘制上边框
graphicsMem.FillRectangle(&borderBrush, rc.left, rc.top, rc.Width(), BORDER_SIZE);
//绘制右边框
graphicsMem.FillRectangle(&borderBrush, rc.right - BORDER_SIZE, rc.top, BORDER_SIZE, rc.Height());
//绘制下边框
graphicsMem.FillRectangle(&borderBrush, rc.left, rc.bottom - BORDER_SIZE, rc.Width(), BORDER_SIZE);
Gdiplus::SolidBrush maxBoxBrush(Gdiplus::Color(100, 20, 20, 20));
graphicsMem.FillRectangle(&maxBoxBrush, rc.right - BORDER_SIZE - 10, rc.top + BORDER_SIZE, 10, 10);
if ((m_iconBitmapHandleMap.find(m_hIcon) != m_iconBitmapHandleMap.end())
&& (m_iconBitmapHandleMap.at(m_hIcon).pBitmapArgb != nullptr))
{
graphicsMem.DrawImage(m_iconBitmapHandleMap.at(m_hIcon).pBitmapArgb, 0, 0, m_titleBarHeight, m_titleBarHeight);
}
Gdiplus::FontFamily fontFamily(L"Times New Roman");
Gdiplus::Font font(&fontFamily, 28, Gdiplus::FontStyleRegular, Gdiplus::UnitPixel);
Gdiplus::PointF pointF(m_titleBarHeight + 1.0f, 0.0f);
Gdiplus::SolidBrush textBrush(Gdiplus::Color(255, 0, 0, 255));
graphicsMem.DrawString(L"TitleBar", -1, &font, pointF, &textBrush);
}
void NotifyUpdate()
{
RedrawWindow(NULL, NULL, RDW_UPDATENOW | RDW_INVALIDATE);
}
BOOL IsVistaOrLater()
{
OSVERSIONINFO osvi = { 0 };
ZeroMemory(&osvi, sizeof(OSVERSIONINFO));
osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
GetVersionEx(&osvi);
if (osvi.dwMajorVersion >= 6)
{
return TRUE;
}
return FALSE;
}
public:
std::wstring bgImg = AToW(GetAppDir() + "\\res\\bg.png");
std::wstring btnokImg = AToW(GetAppDir() + "\\res\\btnok.png");
public:
void ShowOrHideWindow()
{
if (IsWindowVisible())
{
ShowWindow(SW_HIDE);
}
else
{
ShowWindow(SW_SHOW);
BringWindowToTop();
}
}
protected:
CCustomButton m_btnOk;
CCustomButton m_btnCancel;
};
<file_sep>/src/BoysGirl/BoysGirl/BoysGirlDlgProxy.cpp
// BoysGirlDlgProxy.cpp : implementation file
//
#include "pch.h"
#include "framework.h"
#include "BoysGirlApp.h"
#include "BoysGirlDlgProxy.h"
#include "BoysGirlDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CBoysGirlDlgAutoProxy
IMPLEMENT_DYNCREATE(CBoysGirlDlgAutoProxy, CCmdTarget)
CBoysGirlDlgAutoProxy::CBoysGirlDlgAutoProxy()
{
EnableAutomation();
// To keep the application running as long as an automation
// object is active, the constructor calls AfxOleLockApp.
AfxOleLockApp();
// Get access to the dialog through the application's
// main window pointer. Set the proxy's internal pointer
// to point to the dialog, and set the dialog's back pointer to
// this proxy.
ASSERT_VALID(AfxGetApp()->m_pMainWnd);
if (AfxGetApp()->m_pMainWnd)
{
ASSERT_KINDOF(CBoysGirlDlg, AfxGetApp()->m_pMainWnd);
if (AfxGetApp()->m_pMainWnd->IsKindOf(RUNTIME_CLASS(CBoysGirlDlg)))
{
m_pDialog = reinterpret_cast<CBoysGirlDlg*>(AfxGetApp()->m_pMainWnd);
m_pDialog->m_pAutoProxy = this;
}
}
}
CBoysGirlDlgAutoProxy::~CBoysGirlDlgAutoProxy()
{
// To terminate the application when all objects created with
// with automation, the destructor calls AfxOleUnlockApp.
// Among other things, this will destroy the main dialog
if (m_pDialog != nullptr)
m_pDialog->m_pAutoProxy = nullptr;
AfxOleUnlockApp();
}
void CBoysGirlDlgAutoProxy::OnFinalRelease()
{
// When the last reference for an automation object is released
// OnFinalRelease is called. The base class will automatically
// deletes the object. Add additional cleanup required for your
// object before calling the base class.
CCmdTarget::OnFinalRelease();
}
BEGIN_MESSAGE_MAP(CBoysGirlDlgAutoProxy, CCmdTarget)
END_MESSAGE_MAP()
BEGIN_DISPATCH_MAP(CBoysGirlDlgAutoProxy, CCmdTarget)
END_DISPATCH_MAP()
// Note: we add support for IID_IBoysGirl to support typesafe binding
// from VBA. This IID must match the GUID that is attached to the
// dispinterface in the .IDL file.
// {9b0dfc5a-ec68-4a68-8474-703071e47634}
static const IID IID_IBoysGirl =
{0x9b0dfc5a,0xec68,0x4a68,{0x84,0x74,0x70,0x30,0x71,0xe4,0x76,0x34}};
BEGIN_INTERFACE_MAP(CBoysGirlDlgAutoProxy, CCmdTarget)
INTERFACE_PART(CBoysGirlDlgAutoProxy, IID_IBoysGirl, Dispatch)
END_INTERFACE_MAP()
// The IMPLEMENT_OLECREATE2 macro is defined in pch.h of this project
// {4a56caea-6378-42b0-9031-812b950d715d}
IMPLEMENT_OLECREATE2(CBoysGirlDlgAutoProxy, "BoysGirl.Application", 0x4a56caea,0x6378,0x42b0,0x90,0x31,0x81,0x2b,0x95,0x0d,0x71,0x5d)
// CBoysGirlDlgAutoProxy message handlers
|
c88b8bce5ce9c8fa6b22c5d7a8a73f110f014ca1
|
[
"Markdown",
"C++"
] | 11
|
C++
|
15831944/BoysGirl
|
598454c93fcd548b3aa7eb8e5b5c3fbc78fbef9e
|
d34da59aa4396e72ba33749d6c33c4c43f94f245
|
refs/heads/master
|
<file_sep>#!/usr/bin/python
import logging
import random
# default values
logging.basicConfig(level=logging.INFO)
class HistItem():
def __init__(self,timestamp,cmd):
self.ts = timestamp
self.cmd = cmd
def __repr__(self):
return "<HistItem ts:%lf command:%s>"%(self.ts,self.cmd)
class Node():
def __init__(self,ip,color=None,nick=None,hst=None,ram=None):
""" """
if hst is None:
self.hst = []
if nick is None:
self.nick=ip
self.ip=ip
if color is None:
self.color = random.randint(32,35)
else:
self.color = color
if ram is None:
self.ram = {}
def __repr__(self):
return "<Node ip:%s nick:%s hst:%s ram:%s >"% (self.ip,self.nick,self.hst,self.ram)
def cleanup(self):
"""
do cleanup here ( remove history partly,... )
"""
pass
# our printThread is able to stop ( which is important!)
class parser():
"""
generic parser class
depricated
"""
def __init__(self,chat):
self.chat = chat
<file_sep>import logging
import threading
class IOFile:
def __init__(self,chat,filename,chunksize=901,st=None,numchunks=0):
self.fname = filename
self.chat = chat
self.timer = threading.Timer(1,self.watchdog)
if st is not None:
# then generate chunks from the provided string
print "adding iofile"
self.fparts = self._to_chunks(st,chunksize)
self.numchunks = len(self.fparts)
else:
self.fparts = {}
self.numchunks = numchunks
self.chunksize = None
self.timer.start()
pass
self.stopped = False
def _to_chunks(self,st,chunksize):
ret = {}
rest = st.encode("base64").replace('\n','')
i=0
while len(rest) > chunksize:
ret[i]=rest[:chunksize]
rest = rest[chunksize:]
i +=1
ret[i] = rest
return ret
def send_out(self):
for i in range(self.numchunks):
print i
self.send_chunk(i)
def send_chunk(self,chid):
logging.debug("sending file :%s num %d"%(self.fname,chid))
self.chat.send_mc("/fpart \"%s\" \"%d\" \"%d\" \"%s\"" %(
self.fname,self.numchunks,chid,self.fparts[chid]))
def watchdog(self):
""" watcher function which tries to
find ``missed'' chunks and demands them via
Multicast """
d = ""
for i in range(self.numchunks):
if not i in self.fparts.keys():
logging.debug("For %s demanding %s"%(self.fname,i))
d += "%d "%i
#logging.debug("/fmoar %s %d %s"%(
self.chat.send_mc("/fmoar %s %d \"%s\""%(
self.fname,self.numchunks,d))
self.timer = threading.Timer(1,self.watchdog)
self.timer.start()
def unpack(self,path):
""" unpacks ( un-base64 ) the file into
a given file-path"""
logging.debug("beginning to write file")
try:
out = ""
f = open(path,"w+")
for i in range(self.numchunks):
out += self.fparts[i]
#logging.debug("original : %s"%out)
#logging.debug("base64: %s"%out.decode("base64"))
f.write(out.decode("base64"))
f.close()
except Exception as e:
print "something went wrong:",e
def complete(self):
""" Tells if the Multicast File is complete"""
return self.numchunks == len(self.fparts.keys())
def stopdl(self):
""" stop the current download, stops the
request for new chunks """
self.timer.cancel()
self.stopped = True
def startdl(self):
""" starts the download again """
self.timer = threading.Timer(1,self.watchdog)
self.timer.start()
self.started = True
<file_sep>#!/usr/bin/env python
import curses
from threading import thread
<file_sep>from mc_parser import parser,Node,HistItem
import subprocess
import shlex
import sys
from time import time
import logging
import string
import warnings
from mc_file import IOFile
class remoteParser(parser):
""" parses commands received over the Multicast link and evaluate them"""
def __init__(self,chat):
""" Internal function """
parser.__init__(self,chat)
def nick(self,args,addr):
"""the nick will be associated with the ip-address the message it is from
the iplist associated will be changed for that
%MC% sets the nick name for your ip-address
usage: \\nick "bob Ros$"
"""
args = ' '.join(shlex.split(' '.join(args)))
logging.debug("%s"%args)
msg = "'%s' now known as '%s'" % (self.chat.resolveNick(addr[0]),args)
self.chat.iplist[addr[0]].nick = args
return msg
def rot13(self,args,addr):
""" rot13 decodes text with command /rot13 encryption """
args = " ".join(args)
return "%s : rot13 : %s" % (self.chat.resolveNick(addr[0]),
args.encode('rot13'))
def hello(self,args,addr):
"""Tries to parse a hello message to find own IP
it will contain a challenge cookie which will be tested
against the generated one.
This should happen only once ( at beginning of the session)
if the challenge is not taken, the message will be printed out"""
if int(args[-1]) == self.chat.rnd and self.chat.ip is None:
print "challenge succeeded. Found your IP: %s"%addr[0]
self.chat.ip=addr[0]
else:
return "hello from \"%s\" : \"%s\"" % (addr[0],args)
def beep(self,args,addr):
"""Parses beep messages.
These may contain a frequency and a length
The parameters will be passed to the "beep" program with the
corresponding flags
%MC% When activated by user, a beep tone will be produced. Default tone length is 1000, default frequency is 2000"""
if self.chat.beep==False:
return "beeping is turned off, ignoring request from %s with freq/length %s"% (addr[0],args)
cmd = [ "/usr/bin/beep" ]
if len(args) >= 1:
cmd.append("-f%s"%args[0])
if len(args) >= 2:
try:
length = int(args[1])
except:
logging.info("malformed length %s" %sys.exc_info()[0])
length = 100
if length > 1000:
length = 1000
cmd.append("-l%d"%length)
p = subprocess.Popen(cmd)
return "%s demands beep (%s)" % (self.chat.resolveNick(addr[0]) ,args)
def espeak(self,args,addr):
"""when activated, will say args via espeak voice synthesizer
%MC% when activated by user, a synthesized voice will be produced by the machine.
"""
if self.chat.espeak==False:
return "espeak is turned off,ignoring request from %s with args %s" % (addr[0], args)
cmd = [ "/usr/bin/espeak" ]
cmd.extend(args)
p = subprocess.Popen(cmd)
return "%s demands '%s'" %(self.chat.resolveNick(addr[0]),args)
def isMcFunct(self,funct):
if funct.__doc__ is None:
logging.warning("function %s has no docstring"%funct)
return False
return "%MC%" in funct.__doc__
def caps(self,cmd,addr):
"""writes the capabilities to the multicast channel
%MC% returns the available capabilities of this client. Specific help can be retrieved by appending the function name to the caps-command
usage: /caps beep espeak """
ret = ""
if len(cmd) is 0:
for r in dir(self):
h = getattr(self,r)
if self.isMcFunct(h):
ret += "%s "% r
self.chat.send_mc("/echo \"%s\""%ret)
else:
for i in cmd:
ret += "%s: "%i
try:
fun = getattr(self,i)
index = string.find(fun.__doc__,"%MC%")
index +=4
ret += "%s"% fun.__doc__[index:]
except Exception as e:
ret += "No such function"# %s"%e
self.chat.send_mc("/echo \"%s\""%ret)
ret = ""
return
def echo (self,args,addr):
""" replaces the original ``chat''
%MC% Original Chat mode, messages will be written like a normal text message by the user
"""
args = " ".join(args)
logging.debug("echo COLOR: %d"%self.chat.iplist[addr[0]].color)
return "[%dm%s[0m: %s"%(self.chat.iplist[addr[0]].color,self.chat.resolveNick(addr[0]), args)
def parse(self,cmd,addr):
"""parses a message
the message should contain a function and a number of
parameters together in one string:
/beep 1000 230
If there is no such function, the exception will be catched and printed
"""
if not self.chat.iplist.has_key(addr[0]):
self.chat.iplist[addr[0]] = Node(addr[0])
self.chat.iplist[addr[0]].hst.append( HistItem(time(),cmd ) )
cmd = cmd[1:]
logging.debug("REMOTE PARSE:%s"%cmd)
cmd = shlex.split(cmd)
funct = cmd[0]
try:
return getattr(self,funct)(cmd[1:],addr)
except Exception as e:
return "FAIL: '/%s': %s" %(cmd,e)
def pset(self,args,addr):
"""saves a ``private'' value for a node
%MC% Saves a private key-value pair on this machine """
self.chat.iplist[addr[0]].ram[args[0]]=' '.join(args[1:])
return "for %s: saved %s => %s" %(addr[0],args[0],' '.join(args[1:]))
def pget(self,args,addr):
"""tries to retrieve value based on a given key
%MC% Tries to retrieve a given key from the private storage of this machine """
ret = self.chat.iplist[addr[0]].ram.get(args[0],None)
if ret is None:
self.chat.send_mc("/error 404 Not Found")
else:
self.chat.send_mc("/value %s %s"%(args[0].replace('"','\\"'),ret.replace('"','\\"')))
def set(self,args,addr):
""" globally sets a value in all multicast nodes
%MC% saves a global variable ( available for everyone in the Multicast ) """
logging.debug("SET %s"%args)
k = args[0]
v = " ".join(args[1:])
self.chat.gset(k,v)
return "saved globaly %s = %s"%(k,v)
def get(self,args,addr):
""" tries to retrieve a value globally saved in the struct
%MC% tries to retrieve a value from the global key-value storage of this node """
ret = self.chat.gget(args[0])
# thy shall not unescape thy single ' when inside thy double "
key = args[0].replace('"','\\"')#.replace('\'','\\\'')
if ret is None:
self.chat.send_mc("/error 404 %s Not Found "%key)
return
ret = ret.replace('"','\\"') #.replace('\'','\\\'')
self.chat.send_mc("/set \"%s\" \"%s\""%(key,ret))
def error(self,args,addr):
""" parses and handles errors """
return "Received from %s Error: %s"%(self.chat.resolveNick(addr[0])," ".join(args))
def value(self,args,addr):
""" 1. check if we actually requested this value
2. print it
3. do something with it
4. probably save it if its already global """
return "Received from %s : %s = %s" %(self.chat.resolveNick(addr[0]),args[0]," ".join(args[1:]))
def file(self,args,addr):
""" starts a file transfer """
fi = self.chat.files.get(args[0],None)
if fi is None:
logging.debug("Do not have requested file %s "%args[0])
if fi.complete():
fi.send_out()
else:
return "Do not have requested file complete: %s"%fi
return "%s is offering %s with %s chunks"%(self.chat.resolveNick(addr[0]),args[0],args[1])
###
warnings.warn("deprecated", DeprecationWarning)
pass
def fmoar(self,args,addr):
""" sends moar of the requested file """
fname = args[0]
numchunks = args[1]
seq_nrs = args[2:]
logging.debug("%s"%seq_nrs)
fi = self.chat.files.get(fname,None)
if fi is None and not fi.complete():
return ""# kick the messages which are not for us
for i in seq_nrs: #send the requested messages to the network
fi.send_chunk(int(i))
def fget(self):
"""docstring for fget"""
pass
def fpart(self,args,addr):
""" parses fpart messages and saves the content into the
corresponding file """
curr_file = self.chat.files.get(args[0],None)
if curr_file is None:
curr_file = self.chat.files[args[0]] = IOFile(self.chat,filename=args[0], numchunks=int(args[1]))
if curr_file.stopped:
return ""
# seqnr data
curr_file.fparts[int(args[2])] = args[3]
if curr_file.complete() and curr_file.numchunks is int(args[1]):
# unpack the file and write to disk
#print "finished with file %s"%curr_file.fname
curr_file.timer.cancel()
curr_file = None
else:
if curr_file.numchunks != int(args[1]):
logging.warn("num of sequences CHANGED! Restarting Download")
curr_file = self.chat.files[args[0]] = IOFile(filename=args[0],
numchunks=int(args[1]),chat=self.chat)
"""
try:
curr_file.timer.cancel()
curr_file.timer = threading.Timer(1,curr_file.watchdog)
curr_file.timer.start()
except:
pass
"""
<file_sep>#!/usr/bin/python
from socket import socket, AF_INET,SOCK_DGRAM,IPPROTO_UDP,SOL_SOCKET,SO_REUSEADDR,IP_MULTICAST_TTL,IP_MULTICAST_LOOP,INADDR_ANY,inet_aton,IP_ADD_MEMBERSHIP,IPPROTO_IP
import random
import sys,signal
import os
import struct
from select import select
from threading import Thread
from mc_remote import remoteParser
from mc_local import localParser
#defaults
GROUP = '172.16.58.3'
PORT = 42023
CLIENTNAME = "<NAME>"
MCMESSAGE="/hello \"%s\" Says Hello! \"%s\""
# end defaults
var = None
class chatter():
'''
initializes a chat socket
'''
def __init__ ( self, group=GROUP, port=PORT, nick=CLIENTNAME):
'''
the chatter class provides a number of parameters
first is the multicast group, second is the ip and port
the nick
iplist provides a dictionary for mapping ip-addresses to a nick name
a local parser will be instanciated
the variable beep tells if the client should beep or not
'''
self.group=group
self.ip=None
self.port=port
self.nick=nick
self.iplist = {}
self.localParser= localParser(self)
self.beep = False
self.espeak = True
self.encoding = "utf-8"
self.gram= {}
self.files = {}
self.currdir = os.curdir
def send_mc(self,arg):
try:
arg = arg.encode(self.encoding)
self.s.sendto("%s" %
arg,0,(self.group,self.port))
except Exception as e:
print "IN send_mc:%s"%e
def gset(self,key,value):
"""
here you may want to add some persistency stuff
"""
self.gram[key] = value
def gget(self,key):
"""
persistency goes here
"""
return self.gram.get(key,None)
pass
def initSocket (self,rcv=1):
'''
Initializes a Multicast socket
additionally it will send an ip_add_membership
a random seed will be generated for the /hello message
'''
host = ''
self.s = socket(AF_INET,SOCK_DGRAM, IPPROTO_UDP)
self.s.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
#s.setsockopt(SOL_SOCKET,socket.SO_REUSEPORT,1)
self.s.setsockopt(IPPROTO_IP, IP_MULTICAST_TTL, 32)
self.s.setsockopt(IPPROTO_IP,IP_MULTICAST_LOOP,1)
# just send or also recieve
if rcv==1:
self.s.bind((host,PORT))
mreq = struct.pack("4sl", inet_aton(GROUP), INADDR_ANY)
self.s.setsockopt(IPPROTO_IP,IP_ADD_MEMBERSHIP,mreq)
# anouncement message
# seeds
random.seed()
# generate seed
self.rnd = random.randint(42,23000)
self.send_mc(MCMESSAGE % ( self.nick, self.rnd))
self.localParser.nick((self.nick,))
def send(self,msg=""):
if msg.startswith('/'):
ret= self.localParser.parse(msg)
if ret is not None:
print ret
else:
"""
this is the default case
"""
self.send_mc("/echo %s" %msg)
def resolveNick(self,ip):
'''
Tries to resolve an ip-addres to a nickname via the
iplist dictionary. if the ip-address is unkown to the
local host, the ip will be returned
'''
return self.iplist[ip].nick if ip in self.iplist else ip
#########################
# boring stuff from here:
##########################
def threadedRecv(self,cl=None,killthreadfunct=None):
'''
cl is the class which should be started ( shall be a class extending Thread )
killthreadfunction is the function which we use to kill the thread
We need to know which the function is to kill the thread
'''
# thread into receiveloop
if cl==None:
self.rcvthread=printThread(self.s,self)
else:
self.rcvthread=cl
if killthreadfunct==None:
self.rcvthread.killfunct=self.rcvthread.requeststop
else:
self.rcvthread.killfunct=killthreadfunct
self.rcvthread.start()
def cleanup(self):
"""
public function, wrapper for _cleanup, which is used for
the signal and does what we need to have
"""
self._cleanup(1,2)
def _cleanup(self,sig,frame):
'''
cleans up the socket and kills the read-thread
'''
print "cleaning up"
# we need this to stop the thread
self.rcvthread.killfunct()
self.rcvthread.join(1)
self.s.close()
sys.exit()
class printThread(Thread):
'''
Printing thread which is able to stop
'''
def __init__(self,sock,chat):
'''
constructor for printing Loop
the chat is the reference to the original chat object
a remote parser will be instanciated
'''
Thread.__init__(self)
self.s=sock
self.stop=0
self.chat=chat
self.remoteParser= remoteParser(self.chat)
def run(self,*args):
'''
Thread function
It is able to stop via setting self.stop to 1
It will wait for a max of 1 second on a socket
via select.
If the text received is a command ( /bla )
it will be evaulated and eventually executed
'''
while 1:
# break if we do not want to loop on
if self.stop == 1:
print "stopping"
break
ready,output,exception = select([self.s],[],[],1) # try every second
for r in ready:
if r == self.s:
(data,addr) = self.s.recvfrom(1024)
try:
data = str(data.decode(self.chat.encoding))
except Exception as e:
print "FAIL:%s"%e
if data.startswith('/'):
ret=self.remoteParser.parse(data,addr)
if ret is not None:
try:
print "%s" %(ret)
except:
print "malformed return value"
else:
"""
default case : no /command
"""
print "%s: %s"%(self.chat.resolveNick(addr[0]),
data)
def requeststop(self):
'''
sets stop to 1
'''
self.stop=1
def main():
chat = chatter()
signal.signal(signal.SIGINT,chat._cleanup)
registerChat(chat)
chat.initSocket()
chat.threadedRecv()
while 1:
try:
msg = raw_input()
chat.send(msg)
except KeyboardInterrupt:
chat.cleanup()
break
def registerChat(chat):
""" registers ONE global variable, needed for the chat """
global glob
glob = chat
def cleanup(chat):
global glob
glob.cleanup()
if __name__ == "__main__":
main()
<file_sep>import mc_con
import
class TestThread(
<file_sep>import logging
import warnings
import os
from mc_parser import parser
from mc_file import IOFile
class localParser(parser):
""" parses local command calls ( like /nick or /togglebeep )
initial parsing is done with the "parse" function"
it will evaluate the function given and tries to call
the function with that name
"""
def __init__(self,chat):
""" """
parser.__init__(self,chat)
def rot13(self,args):
"""
rot13 encrypts a given text and sends it over the line
magic is done via string.encode('rot13')
the string is written into the multicast channel
"""
args = ' '.join(args)
self.chat.send_mc("/rot13 %s"% args.encode('rot13'))
return "Encoded to %s" % (args.encode('rot13'))
def help(self,args):
"""dummy function
needs args as argument ( because of parsing )
returns a status ( or message) string
if the return string is 'None', the string will not be printed """
print help(self)
return "this is the help file you appended %s" % args
def flushnicks(self,args):
"""flushes the nick table"""
self.chat.iplist.clear()
return "nicks flushed"
def encoding(self,args):
enc = "ascii" if len(args) == 0 else args[0]
self.chat.encoding = args[0]
def nick(self,args):
"""writes our new nick onto the line"""
args = ' '.join(args)
self.chat.send_mc("/nick %s" % args )
#return "You are now known as %s" % args
def echo8(self,args):
self.chat.send_mc(args[0].encode("UTF-8"))
def espeak(self,args):
""" """
args = ' '.join(args)
self.chat.send_mc("/espeak %s" % args )
def beep(self,args):
"""sends beep to the multicast group """
args = ' '.join(args)
self.chat.send_mc("/beep \"%s\"" % args )
def togglebeep(self,args):
"""toggles beep on or off
this is important when to read remote beep commands
These can be turned on or off with this command """
self.chat.beep=not self.chat.beep
return "Beep is now ",self.chat.beep
def toggleespeak(self,args):
self.chat.espeak=not self.chat.espeak
return "Espeak is now ",self.chat.espeak
def caps(self,args):
return "not yet implemented!"
def togglesuper(self,args):
""" """
self.chat.super = not self.chat.super
def raw(self,args):
""" """
msg = ' '.join(args)
logging.debug("RAW:%s"%msg)
#msg = ' '.join(args)
self.chat.send_mc(msg)
def py (self,args):
""" """
return eval(" ".join(args))
def hist (self,args):
""" """
str = ""
for (k,i) in self.chat.iplist.items():
str +="User: %s\n"%self.chat.resolveNick( k)
for h in i.hst:
str += "%s\n"%h
return str
def setall(self,args):
""" """
for k,v in self.chat.gram.items():
self.chat.send_mc("/set \"%s\" \"%s\""%(k,v))
def ack(self,args):
""" acknowledges a file !! to be implemented"""
pass
def parse(self,cmd):
"""parses a command string
looks like: /beep 1000 200
it will try/catch unknown commands
"""
cmd = cmd[1:]
#cmd = shlex.split(cmd)
cmd = cmd.split()
funct = cmd[0]
logging.debug(cmd)
try:
return getattr(self,funct)(cmd[1:])
except Exception as e:
return "no such local command '/%s' : %s" %(cmd,e)
def ld(self,args):
""" lists the current downloads"""
for v in self.chat.files.values():
if v.stopped:
compstr = "[33m[#][0m"
elif v.complete():
compstr = "[32m[+][0m"
else: # running
compstr = "[31m[-][0m"
print "%s %s : %d of %d fparts"%(
compstr,v.fname,len(v.fparts.keys()),v.numchunks)
def ls(self,args):
directory = args[0] if len(args) > 0 else "."
return os.listdir(directory)
def cd(self,args):
if len(args[0]) is 0:
return "need to supply a path"
os.chdir(args[0])
def saveas(self,args):
""" saves a download to the file to a specific place"""
curr_file = self.chat.files[args[0]]
if not curr_file.complete():
warnings.warn("download not yet completed!")
else:
outfile = args[1] if len(args) is 2 else args[0]
curr_file.unpack(outfile)
print "unpacking %s to %s" %(args[0],outfile)
def stopdl(self,args):
""" somewhat tries to ignore specific download """
self.chat.files[args[0]].stopdl()
return "stopped %s"%args[0]
def killdl(self,args):
curr_file = self.chat.files[args[0]]
curr_file.stopdl()
self.chat.files[args[0]] = None
return "killed %s"%args[0]
def startdl(self,args):
self.chat.files[args[0]].startdl()
return "started %s"%args[0]
def lol(self,args):
""" be able to set the log level (100(fatal) - 0(debug))
i am not sure if it really works :("""
logging.basicConfig(level=int(args[0]))
return "Loglevel is now at %s"%args[0]
def sendsf(self,args):
""" send string via file interface"""
fname = args[0] if len(args) > 0 else "custom_string"
st = args[1] if len(args) > 1 else "THIS IS A TEST STRRIIIIING"*2000
chsz = int(args[2]) if len(args) > 2 else 901
aut = self.chat.files[fname]= IOFile(self.chat,filename=fname,st=st,chunksize=chsz)
aut.send_out()
def loadfile(self,args):
fname = args[0]
if self.chat.files.get(fname,None) is not None:
warnings.warn("overwriting existing file!")
chsz = int(args[2]) if len(args) > 1 else 901
with open(fname) as fil:
self.chat.files[fname] = IOFile(self.chat,fname,chsz,fil.read())
def sendfile(self,args):
fname = args[0] if len(args) > 0 else "sample_file"
if self.chat.files.get(fname,None) is not None:
logging.info("will not load existing file again, load if you still want to send a new file!")
else:
self.loadfile([fname])
fil = self.chat.files.get(fname,None)
assert fil is not None # this should never happen(TM)
fil.send_out()
|
65f7025a12c6341668bfc25b3aaabdf3c82759f9
|
[
"Python"
] | 7
|
Python
|
makefu/Multichaos
|
3a079b916ecd31881766bd8dfd433bbb0a076051
|
7feacd9fb19c05d9f955af4af517bd6c4f420fae
|
refs/heads/master
|
<repo_name>ayee-hatfield/Naif.Data<file_sep>/src/Naif.Data.NPoco/NPocoMapper.cs
//******************************************
// Copyright (C) 2014-2015 <NAME> *
// *
// Licensed under MIT License *
// (see included LICENSE) *
// *
// *****************************************
using System;
using System.Reflection;
using Naif.Data.ComponentModel;
using NPoco;
namespace Naif.Data.NPoco
{
public class NPocoMapper : IMapper
{
private readonly string _tablePrefix;
public NPocoMapper(string tablePrefix)
{
_tablePrefix = tablePrefix;
}
public void GetTableInfo(Type t, TableInfo ti)
{
//Table Name
ti.TableName = Util.GetAttributeValue<ComponentModel.TableNameAttribute, string>(t, "TableName", ti.TableName + "s");
ti.TableName = _tablePrefix + ti.TableName;
//Primary Key
ti.PrimaryKey = Util.GetPrimaryKeyName(t.GetTypeInfo());
ti.AutoIncrement = true;
}
public bool MapMemberToColumn(MemberInfo mi, ref string columnName, ref bool resultColumn)
{
var ci = ColumnInfo.FromMemberInfo(mi);
//Column Name
columnName = Util.GetAttributeValue<ColumnNameAttribute, string>(mi, "ColumnName", ci.ColumnName);
return true;
}
public Func<object, object> GetFromDbConverter(MemberInfo mi, Type sourceType)
{
return null;
}
public Func<object, object> GetFromDbConverter(Type destType, Type sourceType)
{
return null;
}
public Func<object, object> GetParameterConverter(Type sourceType)
{
return null;
}
public Func<object, object> GetToDbConverter(Type destType, Type sourceType)
{
return null;
}
public Func<object, object> GetToDbConverter(Type destType, MemberInfo sourceMemberInfo)
{
return null;
}
}
}<file_sep>/src/Naif.Data/RepositoryBase.cs
//******************************************
// Copyright (C) 2014-2015 <NAME> *
// *
// Licensed under MIT License *
// (see included LICENSE) *
// *
// *****************************************
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using Naif.Core.Caching;
using Naif.Core.Collections;
using Naif.Core.Contracts;
using Naif.Data.ComponentModel;
namespace Naif.Data
{
public abstract class RepositoryBase<TModel> : IRepository<TModel> where TModel : class
{
private readonly ICacheProvider _cache;
protected RepositoryBase(ICacheProvider cache)
{
Requires.NotNull("cache", cache);
_cache = cache;
Initialize();
}
public string CacheKey { get; set; }
public bool IsCacheable { get; set; }
public bool IsScoped { get; set; }
public string Scope { get; set; }
public void Add(TModel item)
{
AddInternal(item);
ClearCache(item);
}
public void Delete(TModel item)
{
DeleteInternal(item);
ClearCache(item);
}
public abstract IEnumerable<TModel> Find(string sqlCondition, params object[] args);
public abstract IPagedList<TModel> Find(int pageIndex, int pageSize, string sqlCondition, params object[] args);
public abstract IEnumerable<TModel> Find(Expression<Func<TModel, bool>> predicate);
public abstract IPagedList<TModel> Find(int pageIndex, int pageSize, Expression<Func<TModel, bool>> predicate);
public IEnumerable<TModel> Get<TScopeType>(TScopeType scopeValue)
{
CheckIfScoped();
return IsCacheable
? _cache.GetCachedObject(String.Format(CacheKey, scopeValue), () => GetByScopeInternal(scopeValue))
: GetByScopeInternal(scopeValue);
}
public IEnumerable<TModel> GetAll()
{
IEnumerable<TModel> items = IsCacheable && !IsScoped
? _cache.GetCachedObject(CacheKey, GetAllInternal)
: GetAllInternal();
return items;
}
public TModel GetById<TProperty>(TProperty id)
{
TModel item = IsCacheable && !IsScoped
? GetAll().SingleOrDefault(t => CompareTo(GetPrimaryKey<TProperty>(t), id) == 0)
: GetByIdInternal(id);
return item;
}
public TModel GetById<TProperty, TScopeType>(TProperty id, TScopeType scopeValue)
{
CheckIfScoped();
return Get(scopeValue).SingleOrDefault(t => CompareTo(GetPrimaryKey<TProperty>(t), id) == 0);
}
public IPagedList<TModel> GetPage(int pageIndex, int pageSize)
{
return IsCacheable && !IsScoped
? GetAll().InPagesOf(pageSize).GetPage(pageIndex)
: GetPageInternal(pageIndex, pageSize);
}
public IPagedList<TModel> GetPage<TScopeType>(TScopeType scopeValue, int pageIndex, int pageSize)
{
CheckIfScoped();
return IsCacheable
? Get(scopeValue).InPagesOf(pageSize).GetPage(pageIndex)
: GetPageByScopeInternal(scopeValue, pageIndex, pageSize);
}
public void Update(TModel item)
{
UpdateInternal(item);
ClearCache(item);
}
private void CheckIfScoped()
{
if (!IsScoped)
{
throw new NotSupportedException("This method requires the model to be cacheable and have a cache scope defined");
}
}
private void ClearCache(TModel item)
{
if (IsCacheable)
{
_cache.Remove(IsScoped
? String.Format(CacheKey, GetScopeValue<object>(item))
: CacheKey);
}
}
private int CompareTo<TProperty>(TProperty first, TProperty second)
{
Requires.IsTypeOf<IComparable>("first", first);
Requires.IsTypeOf<IComparable>("second", second);
var firstComparable = first as IComparable;
var secondComparable = second as IComparable;
// ReSharper disable PossibleNullReferenceException
return firstComparable.CompareTo(secondComparable);
// ReSharper restore PossibleNullReferenceException
}
private TProperty GetPrimaryKey<TProperty>(TModel item)
{
TypeInfo modelType = typeof(TModel).GetTypeInfo();
//Get the primary key
var primaryKeyName = Util.GetPrimaryKeyName(modelType);
return GetPropertyValue<TProperty>(modelType, item, primaryKeyName);
}
private TProperty GetPropertyValue<TProperty>(TypeInfo modelType, TModel item, string propertyName)
{
var property = GetProperty(modelType, propertyName);
return (TProperty)property.GetValue(item, null);
}
private PropertyInfo GetProperty(TypeInfo typeInfo, string propertyName)
{
var property = typeInfo.GetDeclaredProperty(propertyName);
if (property == null && typeInfo.BaseType != typeof(object))
{
property = GetProperty(typeInfo.BaseType.GetTypeInfo(), propertyName);
}
return property;
}
private TProperty GetPropertyValue<TProperty>(TModel item, string propertyName)
{
return GetPropertyValue<TProperty>(typeof(TModel).GetTypeInfo(), item, propertyName);
}
private TProperty GetScopeValue<TProperty>(TModel item)
{
return GetPropertyValue<TProperty>(item, Scope);
}
private void Initialize()
{
var type = typeof(TModel);
var typeInfo = type.GetTypeInfo();
Scope = Util.GetScope(type.GetTypeInfo());
IsScoped = (!String.IsNullOrEmpty(Scope));
IsCacheable = Util.IsCacheable(typeInfo);
CacheKey = Util.GetCacheKey(typeInfo);
if (IsScoped)
{
CacheKey += "_" + Scope + "_{0}";
}
}
protected abstract void AddInternal(TModel item);
protected abstract void DeleteInternal(TModel item);
protected abstract IEnumerable<TModel> GetAllInternal();
protected abstract TModel GetByIdInternal(object id);
protected abstract IEnumerable<TModel> GetByScopeInternal(object scopeValue);
protected abstract IPagedList<TModel> GetPageByScopeInternal(object scopeValue, int pageIndex, int pageSize);
protected abstract IPagedList<TModel> GetPageInternal(int pageIndex, int pageSize);
protected abstract void UpdateInternal(TModel item);
[Obsolete("Deprecated in version 1.2.0. Use one of the Find methods which provide more flexibility")]
public IEnumerable<TModel> GetByProperty<TProperty>(string propertyName, TProperty propertyValue)
{
IEnumerable<TModel> items = IsCacheable && !IsScoped
? GetAll().Where(t => CompareTo(GetPropertyValue<TProperty>(t, propertyName), propertyValue) == 0)
: GetByPropertyInternal(propertyName, propertyValue);
return items;
}
[Obsolete("Deprecated in version 1.2.0. Use one of the Find methods which provide more flexibility")]
protected abstract IEnumerable<TModel> GetByPropertyInternal<TProperty>(string propertyName, TProperty propertyValue);
}
}
<file_sep>/tests/Naif.TestUtilities/TestConstants.cs
//******************************************
// Copyright (C) 2014-2015 <NAME> *
// *
// Licensed under MIT License *
// (see included LICENSE) *
// *
// *****************************************
// ReSharper disable InconsistentNaming
namespace Naif.TestUtilities
{
public class TestConstants
{
public const string CACHE_DogsKey = "Dogs";
public const string CACHE_CatsKey = "Cats";
public const string CACHE_ScopeAll = "";
public const string CACHE_ScopeModule = "ModuleId";
public const int MODULE_ValidId = 23;
public const int CACHE_ValidCatId = 34;
public const string NPOCO_DatabaseName = "Test.sdf";
public const string NPOCO_TableName = "Dogs";
public const string NPOCO_CreateTableSql = "CREATE TABLE Dogs (ID int IDENTITY(1,1) NOT NULL, Name nvarchar(100) NOT NULL, Age int NULL)";
public const string NPOCO_InsertRow = "INSERT INTO Dogs (Name, Age) VALUES ('{0}', {1})";
public const string NPOCO_DogNames = "Spot,Buster,Buddy,Spot,Gizmo";
public const string NPOCO_DogAges = "1,5,3,4,6";
public const int NPOCO_RecordCount = 5;
public const string NPOCO_InsertDogName = "Milo";
public const int NPOCO_InsertDogAge = 3;
public const int NPOCO_DeleteDogId = 2;
public const string NPOCO_DeleteDogName = "Buster";
public const int NPOCO_DeleteDogAge = 5;
public const int NPOCO_ValidDogId = 3;
public const string NPOCO_ValidDogName = "Buddy";
public const int NPOCO_ValidDogAge = 3;
public const int NPOCO_InvalidDogId = 999;
public const string NPOCO_UpdateDogName = "Milo";
public const int NPOCO_UpdateDogAge = 6;
public const int NPOCO_UpdateDogId = 3;
public const string PETAPOCO_DatabaseName = "Test.sdf";
public const string PETAPOCO_TableName = "Dogs";
public const string PETAPOCO_CreateTableSql = "CREATE TABLE Dogs (ID int IDENTITY(1,1) NOT NULL, Name nvarchar(100) NOT NULL, Age int NULL)";
public const string PETAPOCO_InsertRow = "INSERT INTO Dogs (Name, Age) VALUES ('{0}', {1})";
public const string PETAPOCO_DogNames = "Spot,Buster,Buddy,Spot,Gizmo";
public const string PETAPOCO_DogAges = "1,5,3,4,6";
public const int PETAPOCO_RecordCount = 5;
public const string PETAPOCO_InsertDogName = "Milo";
public const int PETAPOCO_InsertDogAge = 3;
public const int PETAPOCO_DeleteDogId = 2;
public const string PETAPOCO_DeleteDogName = "Buster";
public const int PETAPOCO_DeleteDogAge = 5;
public const int PETAPOCO_ValidDogId = 3;
public const string PETAPOCO_ValidDogName = "Buddy";
public const int PETAPOCO_ValidDogAge = 3;
public const int PETAPOCO_InvalidDogId = 999;
public const string PETAPOCO_UpdateDogName = "Milo";
public const int PETAPOCO_UpdateDogAge = 6;
public const int PETAPOCO_UpdateDogId = 3;
public const string EF_DatabaseName = "Test.sdf";
public const string EF_TableName = "Dogs";
public const string EF_CreateTableSql = "CREATE TABLE Dogs (ID int IDENTITY(1,1) NOT NULL, Name nvarchar(100) NOT NULL, Age int NULL)";
public const string EF_InsertRow = "INSERT INTO Dogs (Name, Age) VALUES ('{0}', {1})";
public const string EF_DogNames = "Spot,Buster,Buddy,Spot,Gizmo";
public const string EF_DogAges = "1,5,3,4,6";
public const int EF_RecordCount = 5;
public const string EF_InsertDogName = "Milo";
public const int EF_InsertDogAge = 3;
public const int EF_DeleteDogId = 2;
public const string EF_DeleteDogName = "Buster";
public const int EF_DeleteDogAge = 5;
public const int EF_ValidDogId = 3;
public const string EF_ValidDogName = "Buddy";
public const int EF_ValidDogAge = 3;
public const int EF_InvalidDogId = 999;
public const string EF_UpdateDogName = "Milo";
public const int EF_UpdateDogAge = 6;
public const int EF_UpdateDogId = 3;
public const int PAGE_First = 0;
public const int PAGE_Second = 1;
public const int PAGE_Last = 4;
public const int PAGE_RecordCount = 5;
public const int PAGE_TotalCount = 22;
public const int PAGE_NegativeIndex = -1;
public const int PAGE_OutOfRange = 5;
// ReSharper restore InconsistentNaming
}
}<file_sep>/tests/Naif.TestUtilities/Models/Person.cs
//******************************************
// Copyright (C) 2014-2015 <NAME> *
// *
// Licensed under MIT License *
// (see included LICENSE) *
// *
// *****************************************
using System;
namespace Naif.TestUtilities.Models
{
public class Person //: IIdentifiable
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual DateTime Birthdate { get; set; }
public bool IsNew
{
get
{
throw new NotImplementedException();
}
}
}
}
<file_sep>/tests/Naif.Data.PetaPoco.Tests/PetaPocoRepositoryTests.cs
//******************************************
// Copyright (C) 2012-2013 <NAME> *
// *
// Licensed under MIT License *
// (see included License.txt file) *
// *
// *****************************************
using System;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using Naif.Core.Caching;
using PetaPoco;
using Naif.Data.PetaPoco;
using Naif.TestUtilities;
using Naif.TestUtilities.Models;
using Moq;
using System.Data;
namespace Naif.Data.PetaPoco.Tests
{
[TestFixture]
public class PetaPocoRepositoryTests
{
private const string ConnectionStringName = "PetaPoco";
private readonly string[] _dogAges = TestConstants.PETAPOCO_DogAges.Split(',');
private readonly string[] _dogNames = TestConstants.PETAPOCO_DogNames.Split(',');
private PetaPocoUnitOfWork _petaPocoUnitOfWork;
private Mock<ICacheProvider> _cache;
[SetUp]
public void SetUp()
{
_cache = new Mock<ICacheProvider>();
_petaPocoUnitOfWork = CreatePetaPocoUnitOfWork();
}
[TearDown]
public void TearDown()
{
DataUtil.DeleteDatabase(TestConstants.PETAPOCO_DatabaseName);
}
[Test]
public void PetaPocoRepository_Constructor_Throws_On_Null_ICacheProvider()
{
//Arrange, Act, Assert
Assert.Throws<ArgumentNullException>(() => new PetaPocoRepository<Dog>(_petaPocoUnitOfWork, null));
}
[Test]
public void PetaPocoRepository_Constructor_Throws_On_Null_UnitOfWork()
{
//Arrange
var mockCache = new Mock<ICacheProvider>();
//Act, Assert
Assert.Throws<ArgumentNullException>(() => new PetaPocoRepository<Dog>(null, mockCache.Object));
}
[Test]
public void PetaPocoRepository_Add_Inserts_Item_Into_DataBase()
{
//Arrange
var mockCache = new Mock<ICacheProvider>();
SetUpDatabase(TestConstants.PETAPOCO_RecordCount);
var repository = new PetaPocoRepository<Dog>(_petaPocoUnitOfWork, mockCache.Object);
var dog = new Dog
{
Age = TestConstants.PETAPOCO_InsertDogAge,
Name = TestConstants.PETAPOCO_InsertDogName
};
//Act
repository.Add(dog);
//Assert
int actualCount = DataUtil.GetRecordCount(TestConstants.PETAPOCO_DatabaseName,
TestConstants.PETAPOCO_TableName);
Assert.AreEqual(TestConstants.PETAPOCO_RecordCount + 1, actualCount);
}
[Test]
public void PetaPocoRepository_Add_Inserts_Item_Into_DataBase_With_Correct_ID()
{
//Arrange
var mockCache = new Mock<ICacheProvider>();
SetUpDatabase(TestConstants.PETAPOCO_RecordCount);
var repository = new PetaPocoRepository<Dog>(_petaPocoUnitOfWork, mockCache.Object);
var dog = new Dog
{
Age = TestConstants.PETAPOCO_InsertDogAge,
Name = TestConstants.PETAPOCO_InsertDogName
};
//Act
repository.Add(dog);
//Assert
int newId = DataUtil.GetLastAddedRecordID(TestConstants.PETAPOCO_DatabaseName,
TestConstants.PETAPOCO_TableName, "ID");
Assert.AreEqual(TestConstants.PETAPOCO_RecordCount + 1, newId);
}
[Test]
public void PetaPocoRepository_Add_Inserts_Item_Into_DataBase_With_Correct_ColumnValues()
{
//Arrange
var mockCache = new Mock<ICacheProvider>();
SetUpDatabase(TestConstants.PETAPOCO_RecordCount);
var repository = new PetaPocoRepository<Dog>(_petaPocoUnitOfWork, mockCache.Object);
var dog = new Dog
{
Age = TestConstants.PETAPOCO_InsertDogAge,
Name = TestConstants.PETAPOCO_InsertDogName
};
//Act
repository.Add(dog);
//Assert
DataTable table = DataUtil.GetTable(TestConstants.PETAPOCO_DatabaseName, TestConstants.PETAPOCO_TableName);
DataRow row = table.Rows[table.Rows.Count - 1];
Assert.AreEqual(TestConstants.PETAPOCO_InsertDogAge, row["Age"]);
Assert.AreEqual(TestConstants.PETAPOCO_InsertDogName, row["Name"]);
}
[Test]
public void PetaPocoRepository_Delete_Deletes_Item_From_DataBase()
{
//Arrange
var mockCache = new Mock<ICacheProvider>();
SetUpDatabase(TestConstants.PETAPOCO_RecordCount);
var repository = new PetaPocoRepository<Dog>(_petaPocoUnitOfWork, mockCache.Object);
var dog = new Dog
{
ID = TestConstants.PETAPOCO_DeleteDogId,
Age = TestConstants.PETAPOCO_DeleteDogAge,
Name = TestConstants.PETAPOCO_DeleteDogName
};
//Act
repository.Delete(dog);
//Assert
int actualCount = DataUtil.GetRecordCount(TestConstants.PETAPOCO_DatabaseName,
TestConstants.PETAPOCO_TableName);
Assert.AreEqual(TestConstants.PETAPOCO_RecordCount - 1, actualCount);
}
[Test]
public void PetaPocoRepository_Delete_Deletes_Item_From_DataBase_With_Correct_ID()
{
//Arrange
var mockCache = new Mock<ICacheProvider>();
SetUpDatabase(TestConstants.PETAPOCO_RecordCount);
var repository = new PetaPocoRepository<Dog>(_petaPocoUnitOfWork, mockCache.Object);
var dog = new Dog
{
ID = TestConstants.PETAPOCO_DeleteDogId,
Age = TestConstants.PETAPOCO_DeleteDogAge,
Name = TestConstants.PETAPOCO_DeleteDogName
};
//Act
repository.Delete(dog);
//Assert
DataTable table = DataUtil.GetTable(TestConstants.PETAPOCO_DatabaseName, TestConstants.PETAPOCO_TableName);
foreach (DataRow row in table.Rows)
{
Assert.IsFalse((int)row["ID"] == TestConstants.PETAPOCO_DeleteDogId);
}
}
[Test]
public void PetaPocoRepository_Delete_Does_Nothing_With_Invalid_ID()
{
//Arrange
var mockCache = new Mock<ICacheProvider>();
SetUpDatabase(TestConstants.PETAPOCO_RecordCount);
var repository = new PetaPocoRepository<Dog>(_petaPocoUnitOfWork, mockCache.Object);
var dog = new Dog
{
ID = TestConstants.PETAPOCO_InvalidDogId,
Age = TestConstants.PETAPOCO_DeleteDogAge,
Name = TestConstants.PETAPOCO_DeleteDogName
};
//Act
repository.Delete(dog);
//Assert
//Assert
int actualCount = DataUtil.GetRecordCount(TestConstants.PETAPOCO_DatabaseName,
TestConstants.PETAPOCO_TableName);
Assert.AreEqual(TestConstants.PETAPOCO_RecordCount, actualCount);
}
[Test]
[TestCase(1, "WHERE ID < @0", 2)]
[TestCase(4, "WHERE Age <= @0", 5)]
[TestCase(2, "WHERE Name LIKE @0", "S%")]
public void PetaPocoRepository_Find_Returns_Correct_Rows(int count, string sqlCondition, object arg)
{
//Arrange
var mockCache = new Mock<ICacheProvider>();
SetUpDatabase(TestConstants.PETAPOCO_RecordCount);
var repository = new PetaPocoRepository<Dog>(_petaPocoUnitOfWork, mockCache.Object);
//Act
IEnumerable<Dog> dogs = repository.Find(sqlCondition, arg);
//Assert
Assert.AreEqual(count, dogs.Count());
}
[Test]
public void PetaPocoRepository_Find_Overload_Returns_Correct_Rows()
{
//Arrange
var count = 4;
var mockCache = new Mock<ICacheProvider>();
SetUpDatabase(TestConstants.PETAPOCO_RecordCount);
var repository = new PetaPocoRepository<Dog>(_petaPocoUnitOfWork, mockCache.Object);
//Act
IEnumerable<Dog> dogs = repository.Find((d) => d.Age <= 5);
//Assert
Assert.AreEqual(count, dogs.Count());
}
[Test]
[TestCase(0)]
[TestCase(1)]
[TestCase(5)]
public void PetaPocoRepository_GetAll_Returns_All_Rows(int count)
{
//Arrange
var mockCache = new Mock<ICacheProvider>();
SetUpDatabase(count);
var repository = new PetaPocoRepository<Dog>(_petaPocoUnitOfWork, mockCache.Object);
//Act
IEnumerable<Dog> dogs = repository.GetAll();
//Assert
Assert.AreEqual(count, dogs.Count());
}
[Test]
public void PetaPocoRepository_GetAll_Returns_List_Of_Models()
{
//Arrange
var mockCache = new Mock<ICacheProvider>();
SetUpDatabase(5);
var repository = new PetaPocoRepository<Dog>(_petaPocoUnitOfWork, mockCache.Object);
//Act
var dogs = repository.GetAll().ToList();
//Assert
for (int i = 0; i < dogs.Count(); i++)
{
Assert.IsInstanceOf<Dog>(dogs[i]);
}
}
[Test]
public void PetaPocoRepository_GetAll_Returns_Models_With_Correct_Properties()
{
//Arrange
var mockCache = new Mock<ICacheProvider>();
SetUpDatabase(5);
var repository = new PetaPocoRepository<Dog>(_petaPocoUnitOfWork, mockCache.Object);
//Act
var dogs = repository.GetAll();
//Assert
var dog = dogs.First();
Assert.AreEqual(_dogAges[0], dog.Age.ToString());
Assert.AreEqual(_dogNames[0], dog.Name);
}
[Test]
public void PetaPocoRepository_GetById_Returns_Instance_Of_Model_If_Valid_Id()
{
//Arrange
var mockCache = new Mock<ICacheProvider>();
SetUpDatabase(5);
var repository = new PetaPocoRepository<Dog>(_petaPocoUnitOfWork, mockCache.Object);
//Act
var dog = repository.GetById(TestConstants.PETAPOCO_ValidDogId);
//Assert
Assert.IsInstanceOf<Dog>(dog);
}
[Test]
public void PetaPocoRepository_GetById_Returns_Null_If_InValid_Id()
{
//Arrange
var mockCache = new Mock<ICacheProvider>();
SetUpDatabase(5);
var repository = new PetaPocoRepository<Dog>(_petaPocoUnitOfWork, mockCache.Object);
//Act
var dog = repository.GetById(TestConstants.PETAPOCO_InvalidDogId);
//Assert
Assert.IsNull(dog);
}
[Test]
public void PetaPocoRepository_GetById_Returns_Model_With_Correct_Properties()
{
//Arrange
var mockCache = new Mock<ICacheProvider>();
SetUpDatabase(5);
var repository = new PetaPocoRepository<Dog>(_petaPocoUnitOfWork, mockCache.Object);
//Act
var dog = repository.GetById(TestConstants.PETAPOCO_ValidDogId);
//Assert
Assert.AreEqual(TestConstants.PETAPOCO_ValidDogAge, dog.Age);
Assert.AreEqual(TestConstants.PETAPOCO_ValidDogName, dog.Name);
}
[Test]
[TestCase("Spot", 2)]
[TestCase("Buddy", 1)]
public void PetaPocoRepository_GetByProperty_Returns_List_Of_Models_If_Valid_Property(string dogName, int count)
{
//Arrange
var mockCache = new Mock<ICacheProvider>();
SetUpDatabase(5);
var repository = new PetaPocoRepository<Dog>(_petaPocoUnitOfWork, mockCache.Object);
//Act
var dogs = repository.GetByProperty("Name", dogName);
//Assert
Assert.IsInstanceOf<IEnumerable<Dog>>(dogs);
Assert.AreEqual(count, dogs.Count());
}
[Test]
public void PetaPocoRepository_GetByProperty_Returns_Instance_Of_Model_If_Valid_Property()
{
//Arrange
var mockCache = new Mock<ICacheProvider>();
SetUpDatabase(5);
var dogName = _dogNames[2];
var repository = new PetaPocoRepository<Dog>(_petaPocoUnitOfWork, mockCache.Object);
//Act
var dog = repository.GetByProperty("Name", dogName).FirstOrDefault();
//Assert
Assert.IsInstanceOf<Dog>(dog);
}
[Test]
public void PetaPocoRepository_GetByProperty_Returns_Empty_List_If_InValid_Proeprty()
{
//Arrange
var mockCache = new Mock<ICacheProvider>();
SetUpDatabase(5);
const string dogName = "Invalid";
var repository = new PetaPocoRepository<Dog>(_petaPocoUnitOfWork, mockCache.Object);
//Act
var dogs = repository.GetByProperty("Name", dogName);
//Assert
Assert.IsInstanceOf<IEnumerable<Dog>>(dogs);
Assert.AreEqual(0, dogs.Count());
}
[Test]
[TestCase("Spot")]
[TestCase("Buddy")]
public void PetaPocoRepository_GetByProperty_Returns_Models_With_Correct_Properties(string dogName)
{
//Arrange
var mockCache = new Mock<ICacheProvider>();
SetUpDatabase(5);
var repository = new PetaPocoRepository<Dog>(_petaPocoUnitOfWork, mockCache.Object);
//Act
var dogs = repository.GetByProperty("Name", dogName);
//Assert
foreach (Dog dog in dogs)
{
Assert.AreEqual(dogName, dog.Name);
}
}
[Test]
[TestCase(TestConstants.PAGE_First, TestConstants.PAGE_RecordCount)]
[TestCase(TestConstants.PAGE_Second, TestConstants.PAGE_RecordCount)]
[TestCase(TestConstants.PAGE_Last, TestConstants.PAGE_RecordCount)]
public void PetaPocoRepository_GetPage_Returns_Page_Of_Rows(int pageIndex, int pageSize)
{
//Arrange
var mockCache = new Mock<ICacheProvider>();
SetUpDatabase(TestConstants.PAGE_TotalCount);
var repository = new PetaPocoRepository<Dog>(_petaPocoUnitOfWork, mockCache.Object);
//Act
var dogs = repository.GetPage(pageIndex, pageSize);
//Assert
Assert.AreEqual(pageSize, dogs.PageSize);
}
[Test]
public void PetaPocoRepository_GetPage_Returns_List_Of_Models()
{
//Arrange
var mockCache = new Mock<ICacheProvider>();
SetUpDatabase(TestConstants.PAGE_TotalCount);
var repository = new PetaPocoRepository<Dog>(_petaPocoUnitOfWork, mockCache.Object);
//Act
var dogs = repository.GetPage(TestConstants.PAGE_First, TestConstants.PAGE_RecordCount);
//Assert
for (int i = 0; i < dogs.Count(); i++)
{
Assert.IsInstanceOf<Dog>(dogs[i]);
}
}
[Test]
public void PetaPocoRepository_GetPage_Returns_Models_With_Correct_Properties()
{
//Arrange
var mockCache = new Mock<ICacheProvider>();
SetUpDatabase(TestConstants.PAGE_TotalCount);
var repository = new PetaPocoRepository<Dog>(_petaPocoUnitOfWork, mockCache.Object);
//Act
var dogs = repository.GetPage(TestConstants.PAGE_First, TestConstants.PAGE_RecordCount);
//Assert
var dog = dogs.First();
Assert.AreEqual(_dogAges[0], dog.Age.ToString());
Assert.AreEqual(_dogNames[0], dog.Name);
}
[Test]
[TestCase(TestConstants.PAGE_First, TestConstants.PAGE_RecordCount, 1)]
[TestCase(TestConstants.PAGE_Second, TestConstants.PAGE_RecordCount, 6)]
[TestCase(2, 4, 9)]
public void PetaPocoRepository_GetPage_Returns_Correct_Page(int pageIndex, int pageSize, int firstId)
{
//Arrange
var mockCache = new Mock<ICacheProvider>();
SetUpDatabase(TestConstants.PAGE_TotalCount);
var repository = new PetaPocoRepository<Dog>(_petaPocoUnitOfWork, mockCache.Object);
//Act
var dogs = repository.GetPage(pageIndex, pageSize);
//Assert
var dog = dogs.First();
Assert.AreEqual(firstId, dog.ID);
}
[Test]
public void PetaPocoRepository_Update_Updates_Item_In_DataBase()
{
//Arrange
var mockCache = new Mock<ICacheProvider>();
SetUpDatabase(TestConstants.PETAPOCO_RecordCount);
var repository = new PetaPocoRepository<Dog>(_petaPocoUnitOfWork, mockCache.Object);
var dog = new Dog
{
ID = TestConstants.PETAPOCO_UpdateDogId,
Age = TestConstants.PETAPOCO_UpdateDogAge,
Name = TestConstants.PETAPOCO_UpdateDogName
};
//Act
repository.Update(dog);
//Assert
int actualCount = DataUtil.GetRecordCount(TestConstants.PETAPOCO_DatabaseName,
TestConstants.PETAPOCO_TableName);
Assert.AreEqual(TestConstants.PETAPOCO_RecordCount, actualCount);
}
[Test]
public void PetaPocoRepository_Update_Updates_Item_With_Correct_ID()
{
//Arrange
var mockCache = new Mock<ICacheProvider>();
SetUpDatabase(TestConstants.PETAPOCO_RecordCount);
var repository = new PetaPocoRepository<Dog>(_petaPocoUnitOfWork, mockCache.Object);
var dog = new Dog
{
ID = TestConstants.PETAPOCO_UpdateDogId,
Age = TestConstants.PETAPOCO_UpdateDogAge,
Name = TestConstants.PETAPOCO_UpdateDogName
};
//Act
repository.Update(dog);
//Assert
DataTable table = DataUtil.GetTable(TestConstants.PETAPOCO_DatabaseName, TestConstants.PETAPOCO_TableName);
foreach (DataRow row in table.Rows)
{
if ((int)row["ID"] == TestConstants.PETAPOCO_UpdateDogId)
{
Assert.AreEqual(TestConstants.PETAPOCO_UpdateDogAge, row["Age"]);
Assert.AreEqual(TestConstants.PETAPOCO_UpdateDogName, row["Name"]);
}
}
}
private PetaPocoUnitOfWork CreatePetaPocoUnitOfWork()
{
return new PetaPocoUnitOfWork(ConnectionStringName, _cache.Object);
}
private void SetUpDatabase(int count)
{
DataUtil.CreateDatabase(TestConstants.PETAPOCO_DatabaseName);
DataUtil.ExecuteNonQuery(TestConstants.PETAPOCO_DatabaseName, TestConstants.PETAPOCO_CreateTableSql);
for (int i = 0; i < count; i++)
{
var name = (i < _dogNames.Length) ? _dogNames[i] : String.Format("Name_{0}", i);
var age = (i < _dogNames.Length) ? _dogAges[i] : i.ToString();
DataUtil.ExecuteNonQuery(TestConstants.PETAPOCO_DatabaseName, String.Format(TestConstants.PETAPOCO_InsertRow, name, age));
}
}
}
}
<file_sep>/tests/Naif.Data.PetaPoco.Tests/PetaPocoUnitOfWorkTests.cs
//******************************************
// Copyright (C) 2012-2013 <NAME> *
// *
// Licensed under MIT License *
// (see included License.txt file) *
// *
// *****************************************
using System;
using Moq;
using Naif.Core.Caching;
using Naif.TestUtilities.Models;
using NUnit.Framework;
using PetaPoco;
namespace Naif.Data.PetaPoco.Tests
{
[TestFixture]
public class PetaPocoUnitOfWorkTests
{
private const string ConnectionStringName = "PetaPoco";
private Mock<ICacheProvider> _cache;
[SetUp]
public void SetUp()
{
_cache = new Mock<ICacheProvider>();
}
[Test]
public void PetaPocoUnitOfWork_Constructor_Throws_On_Null_Cache()
{
//Arrange, Act, Assert
Assert.Throws<ArgumentNullException>(() => new PetaPocoUnitOfWork(ConnectionStringName, null));
}
[Test]
public void PetaPocoUnitOfWork_Constructor_Throws_On_Null_ConnectionString()
{
//Arrange, Act, Assert
Assert.Throws<ArgumentException>(() => new PetaPocoUnitOfWork(null, _cache.Object));
}
[Test]
public void PetaPocoUnitOfWork_Constructor_Throws_On_Empty_ConnectionString()
{
//Arrange, Act, Assert
Assert.Throws<ArgumentException>(() => new PetaPocoUnitOfWork(String.Empty, _cache.Object));
}
[Test]
public void PetaPocoUnitOfWork_Constructor_Initialises_Database_Field()
{
//Arrange, Act
var context = new PetaPocoUnitOfWork(ConnectionStringName, _cache.Object);
//Assert
Assert.IsInstanceOf<Database>(context.Database);
}
[Test]
public void PetaPocoUnitOfWork_Constructor_Initialises_Mapper_Field()
{
//Arrange, Act
var context = new PetaPocoUnitOfWork(ConnectionStringName, _cache.Object);
//Assert
Assert.IsInstanceOf<IMapper>(context.Mapper);
}
[Test]
public void PetaPocoUnitOfWork_GetRepository_Returns_Repository()
{
//Arrange, Act
var context = new PetaPocoUnitOfWork(ConnectionStringName, _cache.Object);
//Act
var rep = context.GetRepository<Dog>();
//Assert
Assert.IsInstanceOf<IRepository<Dog>>(rep);
}
}
}
<file_sep>/src/Naif.Data.NPoco/NPocoRepository.cs
//******************************************
// Copyright (C) 2014-2015 <NAME> *
// *
// Licensed under MIT License *
// (see included LICENSE) *
// *
// *****************************************
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Reflection;
using Naif.Core.Caching;
using Naif.Core.Collections;
using Naif.Core.Contracts;
using Naif.Data.ComponentModel;
using NPoco;
// ReSharper disable UseStringInterpolation
namespace Naif.Data.NPoco
{
public class NPocoRepository<TModel> : RepositoryBase<TModel> where TModel : class
{
private readonly Database _database;
public NPocoRepository(IUnitOfWork unitOfWork, ICacheProvider cache) : base(cache)
{
Requires.NotNull("unitOfWork", unitOfWork);
var nPocoUnitOfWork = unitOfWork as NPocoUnitOfWork;
if (nPocoUnitOfWork == null)
{
throw new Exception("Must be NPocoUnitOfWork"); // TODO: Typed exception
}
_database = nPocoUnitOfWork.Database;
}
public override IEnumerable<TModel> Find(string sqlCondition, params object[] args)
{
return _database.Fetch<TModel>(sqlCondition, args);
}
public override IPagedList<TModel> Find(int pageIndex, int pageSize, string sqlCondition, params object[] args)
{
//Make sure that the sql Condition contains an ORDER BY Clause
if (!sqlCondition.ToUpperInvariant().Contains("ORDER BY"))
{
sqlCondition = String.Format("{0} ORDER BY {1}", sqlCondition, Util.GetPrimaryKeyName(typeof(TModel).GetTypeInfo()));
}
Page<TModel> petaPocoPage = _database.Page<TModel>(pageIndex + 1, pageSize, sqlCondition, args);
return new PagedList<TModel>(petaPocoPage.Items, (int)petaPocoPage.TotalItems, pageIndex, pageSize);
}
public override IEnumerable<TModel> Find(Expression<Func<TModel, bool>> predicate)
{
return _database.FetchWhere(predicate);
}
public override IPagedList<TModel> Find(int pageIndex, int pageSize, Expression<Func<TModel, bool>> predicate)
{
return Find(predicate).InPagesOf(pageSize).GetPage(pageIndex);
}
protected override void AddInternal(TModel item)
{
_database.Insert(item);
}
protected override void DeleteInternal(TModel item)
{
_database.Delete(item);
}
protected override IEnumerable<TModel> GetAllInternal()
{
return _database.Fetch<TModel>("");
}
protected override TModel GetByIdInternal(object id)
{
return _database.SingleOrDefault<TModel>(String.Format("WHERE {0} = @0", Util.GetPrimaryKeyName(typeof(TModel).GetTypeInfo())), id);
}
protected override IEnumerable<TModel> GetByScopeInternal(object scopeValue)
{
return _database.Fetch<TModel>(GetScopeSql(), scopeValue);
}
protected override IPagedList<TModel> GetPageInternal(int pageIndex, int pageSize)
{
return Find(pageIndex, pageSize, String.Empty);
}
protected override IPagedList<TModel> GetPageByScopeInternal(object propertyValue, int pageIndex, int pageSize)
{
return Find(pageIndex, pageSize, GetScopeSql(), propertyValue);
}
private string GetScopeSql()
{
return String.Format("WHERE {0} = @0", Util.GetColumnName(typeof(TModel).GetTypeInfo(), Scope));
}
protected override void UpdateInternal(TModel item)
{
_database.Update(item);
}
[Obsolete("Deprecated in version 1.2.0. Use one of the Find methods which provide more flexibility")]
protected override IEnumerable<TModel> GetByPropertyInternal<TProperty>(string propertyName, TProperty propertyValue)
{
return _database.Query<TModel>(String.Format("WHERE {0} = @0", propertyName), propertyValue);
}
}
}
<file_sep>/src/Naif.Data/ComponentModel/Util.cs
//******************************************
// Copyright (C) 2014-2015 <NAME> *
// *
// Licensed under MIT License *
// (see included LICENSE) *
// *
// *****************************************
using System;
using System.Linq;
using System.Reflection;
namespace Naif.Data.ComponentModel
{
public static class Util
{
private static TAttribute GetAttribute<TAttribute>(MemberInfo member) where TAttribute : class
{
return member.GetCustomAttributes(true).FirstOrDefault(a => a.GetType() == typeof(TAttribute)) as TAttribute;
}
private static PropertyInfo GetProperty(Attribute attribute, string propertyName)
{
var type = attribute.GetType().GetTypeInfo();
return type.DeclaredProperties.SingleOrDefault(p => p.Name == propertyName);
}
public static TValue GetAttributeValue<TAttribute, TValue>(MemberInfo member, string argumentName, TValue defaultValue) where TAttribute : Attribute
{
TValue attributeValue = defaultValue;
var attribute = GetAttribute<TAttribute>(member) as Attribute;
if (attribute != null)
{
var property = GetProperty(attribute, argumentName);
attributeValue = (TValue)property.GetValue(attribute, null);
}
return attributeValue;
}
public static string GetCacheKey(TypeInfo type)
{
var cacheKey = String.Empty;
if (IsCacheable(type))
{
cacheKey = GetAttributeValue<CacheableAttribute, string>(type, "CacheKey", String.Format("NAIF_{0}", type.Name));
}
return cacheKey;
}
public static string GetColumnName(TypeInfo type, string propertyName)
{
return GetColumnName(type.GetDeclaredProperty(propertyName), propertyName);
}
public static string GetColumnName(PropertyInfo propertyInfo, string defaultName)
{
var columnName = defaultName;
var columnNameAttributes = propertyInfo.GetCustomAttributes(typeof(ColumnNameAttribute), true).ToList();
if (columnNameAttributes.Count > 0)
{
var columnNameAttribute = (ColumnNameAttribute)columnNameAttributes[0];
columnName = columnNameAttribute.ColumnName;
}
return columnName;
}
public static string GetPrimaryKeyName(TypeInfo type)
{
return GetAttributeValue<PrimaryKeyAttribute, string>(type, "KeyField", String.Empty);
}
public static string GetScope(TypeInfo type)
{
return GetAttributeValue<ScopeAttribute, string>(type, "Scope", String.Empty);
}
public static string GetTableName(TypeInfo type, string defaultName)
{
return GetAttributeValue<TableNameAttribute, string>(type, "TableName", defaultName);
}
public static bool IsCacheable(TypeInfo type)
{
return (GetAttribute<CacheableAttribute>(type) != null);
}
public static bool IsScoped(TypeInfo type)
{
return (GetAttribute<ScopeAttribute>(type) != null);
}
}
}
<file_sep>/src/Naif.Data.NPoco/NPocoUnitOfWork.cs
//******************************************
// Copyright (C) 2014-2015 <NAME> *
// *
// Licensed under MIT License *
// (see included LICENSE) *
// *
// *****************************************
using System;
using Naif.Core.Caching;
using Naif.Core.Contracts;
using NPoco;
namespace Naif.Data.NPoco
{
public class NPocoUnitOfWork : IUnitOfWork
{
private readonly ICacheProvider _cache;
public NPocoUnitOfWork(string connectionStringName, ICacheProvider cache)
: this(connectionStringName, String.Empty, cache)
{
}
public NPocoUnitOfWork(string connectionStringName, string tablePrefix, ICacheProvider cache)
{
Requires.NotNullOrEmpty("connectionStringName", connectionStringName);
Requires.NotNull("cache", cache);
Database = new Database(connectionStringName) {Mapper = new NPocoMapper(tablePrefix)};
_cache = cache;
}
public void Commit() { }
public IRepository<T> GetRepository<T>() where T : class
{
return new NPocoRepository<T>(this, _cache);
}
internal Database Database { get; private set; }
public void Dispose()
{
Database.Dispose();
}
}
}<file_sep>/src/Naif.Data/ComponentModel/ScopeAttribute.cs
//******************************************
// Copyright (C) 2014-2015 <NAME> *
// *
// Licensed under MIT License *
// (see included LICENSE) *
// *
// *****************************************
using System;
namespace Naif.Data.ComponentModel
{
public class ScopeAttribute : Attribute
{
public ScopeAttribute(string scope)
{
Scope = scope;
}
/// <summary>
/// The property to use to scope the cache. The default is an empty string.
/// </summary>
public string Scope { get; set; }
}
}
<file_sep>/tests/Naif.Data.EntityFramework.Tests/EFUnitOfWorkTests.cs
//******************************************
// Copyright (C) 2014-2015 <NAME> *
// *
// Licensed under MIT License *
// (see included LICENSE) *
// *
// *****************************************
using System;
using Moq;
using Naif.Core.Caching;
using Naif.TestUtilities;
using Naif.TestUtilities.Models;
using NUnit.Framework;
namespace Naif.Data.EntityFramework.Tests
{
[TestFixture]
public class EFUnitOfWorkTests
{
private const string ConnectionStringName = "NaifDbContext";
private Mock<ICacheProvider> _cache;
[SetUp]
public void SetUp()
{
_cache = new Mock<ICacheProvider>();
}
[Test]
public void EFUnitOfWork_Constructor_Throws_On_Null_Cache()
{
//Arrange, Act, Assert
Assert.Throws<ArgumentNullException>(() => new EFUnitOfWork(ConnectionStringName, null, null));
}
[Test]
public void EFUnitOfWork_Constructor_Throws_On_Null_ConnectionString()
{
//Arrange, Act, Assert
Assert.Throws<ArgumentException>(() => new EFUnitOfWork(null, null, _cache.Object));
}
[Test]
public void EFUnitOfWork_Constructor_Throws_On_Empty_ConnectionString()
{
//Arrange, Act, Assert
Assert.Throws<ArgumentException>(() => new EFUnitOfWork(String.Empty, null, _cache.Object));
}
[Test]
public void EFUnitOfWork_Constructor_Initialises_Database_Field()
{
//Arrange, Act
var context = new EFUnitOfWork(ConnectionStringName, null, _cache.Object);
//Assert
Assert.IsInstanceOf<NaifDbContext>(Util.GetPrivateField<EFUnitOfWork, NaifDbContext>(context, "_dbContext"));
}
[Test]
public void EFUnitOfWork_Constructor_Overload_Throws_On_Null_DbContext()
{
//Arrange, Act, Assert
Assert.Throws<ArgumentNullException>(() => new EFUnitOfWork(null, _cache.Object));
}
[Test]
public void EFUnitOfWork_GetRepository_Returns_Repository()
{
//Arrange, Act
var context = new EFUnitOfWork(ConnectionStringName, null, _cache.Object);
//Act
var rep = context.GetRepository<Dog>();
//Assert
Assert.IsInstanceOf<IRepository<Dog>>(rep);
}
[Test]
public void EFUnitOfWork_SupportsLinq_Property_Returns_True()
{
//Arrange
var context = new EFUnitOfWork(ConnectionStringName, null, _cache.Object);
//Assert
Assert.IsTrue(context.SupportsLinq);
}
}
}
<file_sep>/src/Naif.Data/IRepository.cs
//******************************************
// Copyright (C) 2014-2015 <NAME> *
// *
// Licensed under MIT License *
// (see included LICENSE) *
// *
// *****************************************
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using Naif.Core.Collections;
namespace Naif.Data
{
public interface IRepository<TModel> where TModel : class
{
/// <summary>
/// Add an Item into the repository
/// </summary>
/// <param name="item">The item to be added</param>
void Add(TModel item);
/// <summary>
/// Delete an Item from the repository
/// </summary>
/// <param name="item">The item to be deleted</param>
void Delete(TModel item);
/// <summary>
/// Find items from the repository based on a sql condition
/// </summary>
/// <remarks>Find supports both full SQL statements such as "SELECT * FROM table WHERE ..."
/// as well as a SQL condition like "WHERE ..."</remarks>
/// <param name="sqlCondition">The sql condition e.g. "WHERE ArticleId = @0"</param>
/// <param name="args">A collection of arguments to be mapped to the tokens in the sqlCondition</param>
/// <example>Find("where ArticleId = @0 and UserId = @1", articleId, userId)</example>
/// <returns>A list of items</returns>
IEnumerable<TModel> Find(string sqlCondition, params object[] args);
/// <summary>
/// Find a GetPage of items from the repository based on a sql condition
/// </summary>
/// <remarks>Find supports both full SQL statements such as "SELECT * FROM table WHERE ..."
/// as well as a SQL condition like "WHERE ..."</remarks>
/// <param name="pageIndex">The page Index to fetch</param>
/// <param name="pageSize">The size of the page to fetch</param>
/// <param name="sqlCondition">The sql condition e.g. "WHERE ArticleId = @0"</param>
/// <param name="args">A collection of arguments to be mapped to the tokens in the sqlCondition</param>
/// <returns>A list of items</returns>
IPagedList<TModel> Find(int pageIndex, int pageSize, string sqlCondition, params object[] args);
/// <summary>
/// Find items from the repository based on a Linq predicate
/// </summary>
/// <param name="predicate">The Linq predicate"</param>
/// <returns>A list of items</returns>
IEnumerable<TModel> Find(Expression<Func<TModel, bool>> predicate);
/// <summary>
/// Find a Page of items from the repository based on a Linq predicate
/// </summary>
/// <param name="pageIndex">The page Index to fetch</param>
/// <param name="pageSize">The size of the page to fetch</param>
/// <param name="predicate">The Linq predicate"</param>
/// <returns>A list of items</returns>
IPagedList<TModel> Find(int pageIndex, int pageSize, Expression<Func<TModel, bool>> predicate);
/// <summary>
/// Returns an enumerable list of items filtered by scope
/// </summary>
/// <remarks>
/// This overload should be used to get a list of items for a specific module
/// instance or for a specific portal dependening on how the items in the repository
/// are scoped.
/// </remarks>
/// <typeparam name="TScopeType">The type of the scope field</typeparam>
/// <param name="scopeValue">The value of the scope to filter by</param>
/// <returns>The list of items</returns>
IEnumerable<TModel> Get<TScopeType>(TScopeType scopeValue);
/// <summary>
/// Returns all the items in the repository as an enumerable list
/// </summary>
/// <returns>The list of items</returns>
IEnumerable<TModel> GetAll();
/// <summary>
/// Get an individual item based on the items Id field
/// </summary>
/// <typeparam name="TProperty">The type of the Id field</typeparam>
/// <param name="id">The value of the Id field</param>
/// <returns>An item</returns>
TModel GetById<TProperty>(TProperty id);
/// <summary>
/// Get an individual item based on the items Id field
/// </summary>
/// <remarks>
/// This overload should be used to get an item for a specific module
/// instance or for a specific portal dependening on how the items in the repository
/// are scoped. This will allow the relevant cache to be searched first.
/// </remarks>
/// <typeparam name="TProperty">The type of the Id field</typeparam>
/// <param name="id">The value of the Id field</param>
/// <typeparam name="TScopeType">The type of the scope field</typeparam>
/// <param name="scopeValue">The value of the scope to filter by</param>
/// <returns>An item</returns>
TModel GetById<TProperty, TScopeType>(TProperty id, TScopeType scopeValue);
/// <summary>
/// Returns a page of items in the repository as a paged list
/// </summary>
/// <param name="pageIndex">The page Index to fetch</param>
/// <param name="pageSize">The size of the page to fetch</param>
/// <returns>The list of items</returns>
IPagedList<TModel> GetPage(int pageIndex, int pageSize);
/// <summary>
/// Returns a page of items in the repository as a paged list filtered by scope
/// </summary>
/// <remarks>
/// This overload should be used to get a list of items for a specific module
/// instance or for a specific portal dependening on how the items in the repository
/// are scoped.
/// </remarks>
/// <typeparam name="TScopeType">The type of the scope field</typeparam>
/// <param name="scopeValue">The value of the scope to filter by</param>
/// <param name="pageIndex">The page Index to fetch</param>
/// <param name="pageSize">The size of the page to fetch</param>
/// <returns>The list of items</returns>
IPagedList<TModel> GetPage<TScopeType>(TScopeType scopeValue, int pageIndex, int pageSize);
/// <summary>
/// Updates an Item in the repository
/// </summary>
/// <param name="item">The item to be updated</param>
void Update(TModel item);
[ObsoleteAttribute("Deprecated in version 1.2.0. Use one of the Find methods which provide more flexibility")]
IEnumerable<TModel> GetByProperty<TProperty>(string propertyName, TProperty propertyValue);
}
}<file_sep>/tests/Naif.Data.EntityFramework.Tests/EFRepositoryTests.cs
//******************************************
// Copyright (C) 2012-2013 <NAME> *
// *
// Licensed under MIT License *
// (see included License.txt file) *
// *
// *****************************************
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using Moq;
using Naif.Core.Caching;
using Naif.TestUtilities;
using Naif.TestUtilities.Models;
using NUnit.Framework;
namespace Naif.Data.EntityFramework.Tests
{
[TestFixture]
public class EFRepositoryTests
{
private const string ConnectionStringName = "EntityFramework";
private readonly string[] _dogAges = TestConstants.EF_DogAges.Split(',');
private readonly string[] _dogNames = TestConstants.EF_DogNames.Split(',');
private Mock<ICacheProvider> _cache;
private EFUnitOfWork _efUnitOfWork;
[SetUp]
public void SetUp()
{
_cache = new Mock<ICacheProvider>();
}
[TearDown]
public void TearDown()
{
DataUtil.DeleteDatabase(TestConstants.EF_DatabaseName);
}
[Test]
public void EFRepository_Constructor_Throws_On_Null_DbContext()
{
//Arrange, Act, Assert
Assert.Throws<ArgumentNullException>(() => new EFRepository<Dog>(null, _cache.Object));
}
[Test]
public void EFRepository_Add_Inserts_Item_Into_DataBase()
{
//Arrange
SetUpDatabase(TestConstants.EF_RecordCount);
var repository = new EFRepository<Dog>(_efUnitOfWork, _cache.Object);
var dog = new Dog
{
Age = TestConstants.EF_InsertDogAge,
Name = TestConstants.EF_InsertDogName
};
//Act
repository.Add(dog);
_efUnitOfWork.Commit();
//Assert
int actualCount = DataUtil.GetRecordCount(TestConstants.EF_DatabaseName, TestConstants.EF_TableName);
Assert.AreEqual(TestConstants.EF_RecordCount + 1, actualCount);
}
[Test]
public void EFRepository_Add_Inserts_Item_Into_DataBase_With_Correct_ID()
{
//Arrange
SetUpDatabase(TestConstants.EF_RecordCount);
var repository = new EFRepository<Dog>(_efUnitOfWork, _cache.Object);
var dog = new Dog
{
Age = TestConstants.EF_InsertDogAge,
Name = TestConstants.EF_InsertDogName
};
//Act
repository.Add(dog);
_efUnitOfWork.Commit();
//Assert
int newId = DataUtil.GetLastAddedRecordID(TestConstants.EF_DatabaseName, TestConstants.EF_TableName, "ID");
Assert.AreEqual(TestConstants.EF_RecordCount + 1, newId);
}
[Test]
public void EFRepository_Add_Inserts_Item_Into_DataBase_With_Correct_ColumnValues()
{
//Arrange
SetUpDatabase(TestConstants.EF_RecordCount);
var repository = new EFRepository<Dog>(_efUnitOfWork, _cache.Object);
var dog = new Dog
{
Age = TestConstants.EF_InsertDogAge,
Name = TestConstants.EF_InsertDogName
};
//Act
repository.Add(dog);
_efUnitOfWork.Commit();
//Assert
DataTable table = DataUtil.GetTable(TestConstants.EF_DatabaseName, TestConstants.EF_TableName);
DataRow row = table.Rows[table.Rows.Count - 1];
Assert.AreEqual(TestConstants.EF_InsertDogAge, row["Age"]);
Assert.AreEqual(TestConstants.EF_InsertDogName, row["Name"]);
}
[Test]
public void EFRepository_Delete_Deletes_Item_From_DataBase()
{
//Arrange
SetUpDatabase(TestConstants.EF_RecordCount);
var repository = new EFRepository<Dog>(_efUnitOfWork, _cache.Object);
var dog = new Dog
{
ID = TestConstants.EF_DeleteDogId,
Age = TestConstants.EF_DeleteDogAge,
Name = TestConstants.EF_DeleteDogName
};
//Act
repository.Delete(dog);
_efUnitOfWork.Commit();
//Assert
int actualCount = DataUtil.GetRecordCount(TestConstants.EF_DatabaseName, TestConstants.EF_TableName);
Assert.AreEqual(TestConstants.EF_RecordCount - 1, actualCount);
}
[Test]
public void EFRepository_Delete_Deletes_Item_From_DataBase_With_Correct_ID()
{
//Arrange
SetUpDatabase(TestConstants.EF_RecordCount);
var repository = new EFRepository<Dog>(_efUnitOfWork, _cache.Object);
var dog = new Dog
{
ID = TestConstants.EF_DeleteDogId,
Age = TestConstants.EF_DeleteDogAge,
Name = TestConstants.EF_DeleteDogName
};
//Act
repository.Delete(dog);
_efUnitOfWork.Commit();
//Assert
DataTable table = DataUtil.GetTable(TestConstants.EF_DatabaseName, TestConstants.EF_TableName);
foreach (DataRow row in table.Rows)
{
Assert.IsFalse((int)row["ID"] == TestConstants.EF_DeleteDogId);
}
}
[Test]
public void EFRepository_Delete_Throws_With_Invalid_ID()
{
//Arrange
SetUpDatabase(TestConstants.EF_RecordCount);
var repository = new EFRepository<Dog>(_efUnitOfWork, _cache.Object);
var dog = new Dog
{
ID = TestConstants.EF_InvalidDogId,
Age = TestConstants.EF_DeleteDogAge,
Name = TestConstants.EF_DeleteDogName
};
//Act
var success = false;
try
{
repository.Delete(dog);
_efUnitOfWork.Commit();
success = true;
}
catch (Exception)
{
}
//Assert
Assert.IsFalse(success);
}
[Test]
[TestCase("Spot", 2)]
[TestCase("Buddy", 1)]
public void EFRepository_Find_Returns_List_Of_Models_If_Valid_Property(string dogName, int count)
{
//Arrange
SetUpDatabase(5);
var repository = new EFRepository<Dog>(_efUnitOfWork, _cache.Object);
//Act
var dogs = repository.Find((d) => d.Name == dogName);
//Assert
Assert.IsInstanceOf<IEnumerable<Dog>>(dogs);
Assert.AreEqual(count, dogs.Count());
}
[Test]
public void EFRepository_Find_Returns_Instance_Of_Model_If_Valid_Property()
{
//Arrange
SetUpDatabase(5);
var dogName = _dogNames[2];
var repository = new EFRepository<Dog>(_efUnitOfWork, _cache.Object);
//Act
var dog = repository.Find((d) => d.Name == dogName).FirstOrDefault();
//Assert
Assert.IsInstanceOf<Dog>(dog);
}
[Test]
public void EFRepository_Find_Returns_Empty_List_If_InValid_Proeprty()
{
//Arrange
SetUpDatabase(5);
const string dogName = "Invalid";
var repository = new EFRepository<Dog>(_efUnitOfWork, _cache.Object);
//Act
var dogs = repository.Find((d) => d.Name == dogName);
//Assert
Assert.IsInstanceOf<IEnumerable<Dog>>(dogs);
Assert.AreEqual(0, dogs.Count());
}
[Test]
[TestCase("Spot")]
[TestCase("Buddy")]
public void EFRepository_Find_Returns_Models_With_Correct_Properties(string dogName)
{
//Arrange
SetUpDatabase(5);
var repository = new EFRepository<Dog>(_efUnitOfWork, _cache.Object);
//Act
var dogs = repository.Find((d) => d.Name == dogName);
//Assert
foreach (Dog dog in dogs)
{
Assert.AreEqual(dogName, dog.Name);
}
}
[Test]
[TestCase(0)]
[TestCase(1)]
[TestCase(5)]
public void EFRepository_GetAll_Returns_All_Rows(int count)
{
//Arrange
SetUpDatabase(count);
var repository = new EFRepository<Dog>(_efUnitOfWork, _cache.Object);
//Act
IEnumerable<Dog> dogs = repository.GetAll();
//Assert
Assert.AreEqual(count, dogs.Count());
}
[Test]
public void EFRepository_GetAll_Returns_List_Of_Models()
{
//Arrange
var mockCache = new Mock<ICacheProvider>();
SetUpDatabase(5);
var repository = new EFRepository<Dog>(_efUnitOfWork, _cache.Object);
//Act
var dogs = repository.GetAll().ToList();
//Assert
for (int i = 0; i < dogs.Count(); i++)
{
Assert.IsInstanceOf<Dog>(dogs[i]);
}
}
[Test]
public void EFRepository_GetAll_Returns_Models_With_Correct_Properties()
{
//Arrange
SetUpDatabase(5);
var repository = new EFRepository<Dog>(_efUnitOfWork, _cache.Object);
//Act
var dogs = repository.GetAll();
//Assert
var dog = dogs.First();
Assert.AreEqual(_dogAges[0], dog.Age.ToString());
Assert.AreEqual(_dogNames[0], dog.Name);
}
[Test]
[TestCase(TestConstants.PAGE_First, TestConstants.PAGE_RecordCount)]
[TestCase(TestConstants.PAGE_Second, TestConstants.PAGE_RecordCount)]
[TestCase(TestConstants.PAGE_Last, TestConstants.PAGE_RecordCount)]
public void EFRepository_GetPage_Returns_Page_Of_Rows(int pageIndex, int pageSize)
{
//Arrange
SetUpDatabase(TestConstants.PAGE_TotalCount);
var repository = new EFRepository<Dog>(_efUnitOfWork, _cache.Object);
//Act
var dogs = repository.GetPage(pageIndex, pageSize);
//Assert
Assert.AreEqual(pageSize, dogs.PageSize);
}
[Test]
public void EFRepository_GetPage_Returns_List_Of_Models()
{
//Arrange
SetUpDatabase(TestConstants.PAGE_TotalCount);
var repository = new EFRepository<Dog>(_efUnitOfWork, _cache.Object);
//Act
var dogs = repository.GetPage(TestConstants.PAGE_First, TestConstants.PAGE_RecordCount);
//Assert
for (int i = 0; i < dogs.Count(); i++)
{
Assert.IsInstanceOf<Dog>(dogs[i]);
}
}
[Test]
public void EFRepository_GetPage_Returns_Models_With_Correct_Properties()
{
//Arrange
SetUpDatabase(TestConstants.PAGE_TotalCount);
var repository = new EFRepository<Dog>(_efUnitOfWork, _cache.Object);
//Act
var dogs = repository.GetPage(TestConstants.PAGE_First, TestConstants.PAGE_RecordCount);
//Assert
var dog = dogs.First();
Assert.AreEqual(_dogAges[0], dog.Age.ToString());
Assert.AreEqual(_dogNames[0], dog.Name);
}
[Test]
[TestCase(TestConstants.PAGE_First, TestConstants.PAGE_RecordCount, 1)]
[TestCase(TestConstants.PAGE_Second, TestConstants.PAGE_RecordCount, 6)]
[TestCase(2, 4, 9)]
public void EFRepository_GetPage_Returns_Correct_Page(int pageIndex, int pageSize, int firstId)
{
//Arrange
SetUpDatabase(TestConstants.PAGE_TotalCount);
var repository = new EFRepository<Dog>(_efUnitOfWork, _cache.Object);
//Act
var dogs = repository.GetPage(pageIndex, pageSize);
//Assert
var dog = dogs.First();
Assert.AreEqual(firstId, dog.ID);
}
//[Test]
//public void EFRepository_GetSingle_Returns_Instance_Of_Model_If_Valid_Id()
//{
// //Arrange
// SetUpDatabase(5);
// var repository = new EFRepository<Dog>(_efUnitOfWork, _cache.Object);
// //Act
// var dog = repository.GetSingle((d) => d.ID == TestConstants.EF_ValidDogId);
// //Assert
// Assert.IsInstanceOf<Dog>(dog);
//}
//[Test]
//public void EFRepository_GetSingle_Returns_Null_If_InValid_Id()
//{
// //Arrange
// var mockCache = new Mock<ICacheProvider>();
// SetUpDatabase(5);
// var repository = new EFRepository<Dog>(_efUnitOfWork, _cache.Object);
// //Act
// var dog = repository.GetSingle((d) => d.ID == TestConstants.EF_InvalidDogId);
// //Assert
// Assert.IsNull(dog);
//}
//[Test]
//public void EFRepository_GetSingle_Returns_Model_With_Correct_Properties()
//{
// //Arrange
// var mockCache = new Mock<ICacheProvider>();
// SetUpDatabase(5);
// var repository = new EFRepository<Dog>(_efUnitOfWork, _cache.Object);
// //Act
// var dog = repository.GetSingle((d) => d.ID == TestConstants.EF_ValidDogId);
// //Assert
// Assert.AreEqual(TestConstants.EF_ValidDogAge, dog.Age);
// Assert.AreEqual(TestConstants.EF_ValidDogName, dog.Name);
//}
[Test]
public void EFRepository_Update_Updates_Item_In_DataBase()
{
//Arrange
SetUpDatabase(TestConstants.EF_RecordCount);
var repository = new EFRepository<Dog>(_efUnitOfWork, _cache.Object);
var dog = new Dog
{
ID = TestConstants.EF_UpdateDogId,
Age = TestConstants.EF_UpdateDogAge,
Name = TestConstants.EF_UpdateDogName
};
//Act
repository.Update(dog);
_efUnitOfWork.Commit();
//Assert
int actualCount = DataUtil.GetRecordCount(TestConstants.EF_DatabaseName, TestConstants.EF_TableName);
Assert.AreEqual(TestConstants.EF_RecordCount, actualCount);
}
[Test]
public void EFRepository_Update_Updates_Item_With_Correct_ID()
{
//Arrange
SetUpDatabase(TestConstants.EF_RecordCount);
var repository = new EFRepository<Dog>(_efUnitOfWork, _cache.Object);
var dog = new Dog
{
ID = TestConstants.EF_UpdateDogId,
Age = TestConstants.EF_UpdateDogAge,
Name = TestConstants.EF_UpdateDogName
};
//Act
repository.Update(dog);
_efUnitOfWork.Commit();
//Assert
DataTable table = DataUtil.GetTable(TestConstants.EF_DatabaseName, TestConstants.EF_TableName);
foreach (DataRow row in table.Rows)
{
if ((int)row["ID"] == TestConstants.EF_UpdateDogId)
{
Assert.AreEqual(TestConstants.EF_UpdateDogAge, row["Age"]);
Assert.AreEqual(TestConstants.EF_UpdateDogName, row["Name"]);
}
}
}
private EFUnitOfWork CreateEFUnitOfWork()
{
return new EFUnitOfWork(ConnectionStringName, (modelBuilder) => modelBuilder.Entity<Dog>().ToTable("Dogs"), _cache.Object);
}
private void SetUpDatabase(int count)
{
DataUtil.CreateDatabase(TestConstants.EF_DatabaseName);
DataUtil.ExecuteNonQuery(TestConstants.EF_DatabaseName, TestConstants.EF_CreateTableSql);
for (int i = 0; i < count; i++)
{
var name = (i < _dogNames.Length) ? _dogNames[i] : String.Format("Name_{0}", i);
var age = (i < _dogNames.Length) ? _dogAges[i] : i.ToString();
DataUtil.ExecuteNonQuery(TestConstants.EF_DatabaseName, String.Format(TestConstants.EF_InsertRow, name, age));
}
_efUnitOfWork = CreateEFUnitOfWork();
}
}
}
<file_sep>/README.md
# Naif.Data
A set of simple data access components
<file_sep>/src/Naif.Data/ComponentModel/CacheableAttribute.cs
//******************************************
// Copyright (C) 2014-2015 <NAME> *
// *
// Licensed under MIT License *
// (see included LICENSE) *
// *
// *****************************************
using System;
namespace Naif.Data.ComponentModel
{
public class CacheableAttribute : Attribute
{
public CacheableAttribute()
{
}
public CacheableAttribute(string cacheKey)
{
CacheKey = cacheKey;
}
public string CacheKey { get; set; }
}
}
<file_sep>/src/Naif.Data/ComponentModel/ColumnNameAttribute.cs
//******************************************
// Copyright (C) 2014-2015 <NAME> *
// *
// Licensed under MIT License *
// (see included LICENSE) *
// *
// *****************************************
using System;
namespace Naif.Data.ComponentModel
{
public class ColumnNameAttribute : Attribute
{
public string ColumnName { get; set; }
}
}
<file_sep>/tests/Naif.TestUtilities/Util.cs
//******************************************
// Copyright (C) 2014-2015 <NAME> *
// *
// Licensed under MIT License *
// (see included LICENSE) *
// *
// *****************************************
using System;
using System.Reflection;
namespace Naif.TestUtilities
{
public static class Util
{
public static TField GetPrivateField<TInstance, TField>(TInstance instance, string fieldName)
{
Type type = typeof(TInstance);
const BindingFlags privateBindings = BindingFlags.NonPublic | BindingFlags.Instance;
// retrive private field from class
FieldInfo field = type.GetField(fieldName, privateBindings);
return (TField)field.GetValue(instance);
}
public static TField GetPrivateProperty<TInstance, TField>(TInstance instance, string fieldName)
{
Type type = typeof(TInstance);
const BindingFlags privateBindings = BindingFlags.NonPublic | BindingFlags.Instance;
// retrive private property from class
PropertyInfo property = type.GetProperty(fieldName, privateBindings);
return (TField)property.GetValue(instance);
}
}
}
<file_sep>/src/Naif.Data.PetaPoco/PetaPocoMapper.cs
//******************************************
// Copyright (C) 2014-2015 <NAME> *
// *
// Licensed under MIT License *
// (see included LICENSE) *
// *
// *****************************************
using System;
using System.Reflection;
using PetaPoco;
using Naif.Data.ComponentModel;
namespace Naif.Data.PetaPoco
{
public class PetaPocoMapper : IMapper
{
private readonly string _tablePrefix;
public PetaPocoMapper(string tablePrefix)
{
_tablePrefix = tablePrefix;
}
public TableInfo GetTableInfo(Type pocoType)
{
var ti = TableInfo.FromPoco(pocoType);
//Table Name
ti.TableName = Util.GetAttributeValue<ComponentModel.TableNameAttribute, string>(pocoType, "TableName", ti.TableName + "s");
ti.TableName = _tablePrefix + ti.TableName;
//Primary Key
ti.PrimaryKey = Util.GetPrimaryKeyName(pocoType.GetTypeInfo());
ti.AutoIncrement = true;
return ti;
}
public ColumnInfo GetColumnInfo(PropertyInfo pocoProperty)
{
var ci = ColumnInfo.FromProperty(pocoProperty);
//Column Name
ci.ColumnName = Util.GetAttributeValue<ColumnNameAttribute, string>(pocoProperty, "ColumnName", ci.ColumnName);
return ci;
}
public Func<object, object> GetFromDbConverter(PropertyInfo pi, Type sourceType)
{
return null;
}
public Func<object, object> GetToDbConverter(PropertyInfo sourceProperty)
{
return null;
}
}
}<file_sep>/tests/Naif.Data.Tests/RepositoryBaseTests.cs
//******************************************
// Copyright (C) 2014-2015 <NAME> *
// *
// Licensed under MIT License *
// (see included LICENSE) *
// *
// *****************************************
using System;
using System.Collections.Generic;
using Moq;
using Moq.Protected;
using Naif.Core.Caching;
using Naif.Core.Collections;
using Naif.TestUtilities;
using Naif.TestUtilities.Fakes;
using Naif.TestUtilities.Models;
using NUnit.Framework;
namespace Naif.Data.Tests
{
[TestFixture]
public class RepositoryBaseTests
{
// ReSharper disable InconsistentNaming
private Mock<ICacheProvider> _mockCache;
[SetUp]
public void SetUp()
{
_mockCache = new Mock<ICacheProvider>();
}
[Test]
public void RepositoryBase_Constructor_Sets_CacheKey_Empty_If_Not_Cacheable()
{
//Arrange
//Act
var repo = new FakeRepository<Dog>(_mockCache.Object);
//Assert
Assert.AreEqual(String.Empty, repo.CacheKey);
}
[Test]
public void RepositoryBase_Constructor_Sets_CacheKey_If_Cacheable()
{
//Arrange
//Act
var repo = new FakeRepository<CacheableDog>(_mockCache.Object);
//Assert
Assert.AreEqual(TestConstants.CACHE_DogsKey, repo.CacheKey);
}
[Test]
public void RepositoryBase_Constructor_Sets_IsCacheable_False_If_Not_Cacheable()
{
//Arrange
//Act
var repo = new FakeRepository<Dog>(_mockCache.Object);
//Assert
Assert.IsFalse(repo.IsCacheable);
}
[Test]
public void RepositoryBase_Constructor_Sets_IsCacheable_True_If_Cacheable()
{
//Arrange
//Act
var repo = new FakeRepository<CacheableDog>(_mockCache.Object);
//Assert
Assert.IsTrue(repo.IsCacheable);
}
[Test]
public void RepositoryBase_Constructor_Sets_IsScoped_False_If_Not_Scoped()
{
//Arrange
//Act
var repo = new FakeRepository<Dog>(_mockCache.Object);
//Assert
Assert.IsFalse(repo.IsScoped);
}
[Test]
public void RepositoryBase_Constructor_Sets_IsScoped_False_If_Cacheable_And_Not_Scoped()
{
//Arrange
//Act
var repo = new FakeRepository<CacheableDog>(_mockCache.Object);
//Assert
Assert.IsFalse(repo.IsScoped);
}
[Test]
public void RepositoryBase_Constructor_Sets_IsScoped_True_If_Scoped()
{
//Arrange
//Act
var repo = new FakeRepository<Cat>(_mockCache.Object);
//Assert
Assert.IsTrue(repo.IsScoped);
}
[Test]
public void RepositoryBase_Constructor_Sets_IsScoped_True_If_Cacheable_And_Scoped()
{
//Arrange
//Act
var repo = new FakeRepository<CacheableCat>(_mockCache.Object);
//Assert
Assert.IsTrue(repo.IsScoped);
}
[Test]
public void RepositoryBase_Constructor_Sets_Scope_Empty_If_Not_Scoped()
{
//Arrange
//Act
var repo = new FakeRepository<Dog>(_mockCache.Object);
//Assert
Assert.AreEqual(String.Empty, repo.Scope);
}
[Test]
public void RepositoryBase_Constructor_Sets_Scope_Empty_If_Cacheable_And_Not_Scoped()
{
//Arrange
//Act
var repo = new FakeRepository<CacheableDog>(_mockCache.Object);
//Assert
Assert.AreEqual(String.Empty, repo.Scope);
}
[Test]
public void RepositoryBase_Constructor_Sets_Scope_If_Scoped()
{
//Arrange
//Act
var repo = new FakeRepository<Cat>(_mockCache.Object);
//Assert
Assert.AreEqual(TestConstants.CACHE_ScopeModule, repo.Scope);
}
[Test]
public void RepositoryBase_Constructor_Sets_Scope_If_Cacheable_And_Scoped()
{
//Arrange
//Act
var repo = new FakeRepository<CacheableCat>(_mockCache.Object);
//Assert
Assert.AreEqual(TestConstants.CACHE_ScopeModule, repo.Scope);
}
[Test]
public void RepositoryBase_Add_Clears_Cache_If_Cacheable()
{
//Arrange
var cacheKey = TestConstants.CACHE_DogsKey;
_mockCache.Setup(c => c.Get(cacheKey)).Returns(new List<CacheableDog>());
var mockRepository = new Mock<RepositoryBase<CacheableDog>>(_mockCache.Object);
//Act
mockRepository.Object.Add(new CacheableDog());
//Assert
_mockCache.Verify(c => c.Remove(cacheKey), Times.Once());
}
[Test]
public void RepositoryBase_Add_Clears_Cache_If_Cacheable_And_Scoped()
{
//Arrange
var cacheKey = String.Format(TestConstants.CACHE_CatsKey + "_" + TestConstants.CACHE_ScopeModule + "_{0}", TestConstants.MODULE_ValidId);
_mockCache.Setup(c => c.Get(cacheKey)).Returns(new List<CacheableCat>());
var mockRepository = new Mock<RepositoryBase<CacheableCat>>(_mockCache.Object);
//Act
mockRepository.Object.Add(new CacheableCat { ModuleId = TestConstants.MODULE_ValidId });
//Assert
_mockCache.Verify(c => c.Remove(cacheKey), Times.Once());
}
[Test]
public void RepositoryBase_Add_Does_Not_Clear_Cache_If_Not_Cacheable()
{
//Arrange
var mockRepository = new Mock<RepositoryBase<Dog>>(_mockCache.Object);
//Act
mockRepository.Object.Add(new Dog());
//Assert
_mockCache.Verify(c => c.Remove(It.IsAny<string>()), Times.Never());
}
[Test]
public void RepositoryBase_Add_Calls_AddInternal()
{
//Arrange
var mockRepository = new Mock<RepositoryBase<Dog>>(_mockCache.Object);
mockRepository.Protected().Setup("AddInternal", ItExpr.IsAny<Dog>());
//Act
mockRepository.Object.Add(new Dog());
//Assert
mockRepository.Protected().Verify("AddInternal", Times.Once(), ItExpr.IsAny<Dog>());
}
[Test]
public void RepositoryBase_Delete_Clears_Cache_If_Cacheable()
{
//Arrange
var cacheKey = TestConstants.CACHE_DogsKey;
_mockCache.Setup(c => c.Get(cacheKey)).Returns(new List<CacheableDog>());
var mockRepository = new Mock<RepositoryBase<CacheableDog>>(_mockCache.Object);
//Act
mockRepository.Object.Delete(new CacheableDog());
//Assert
_mockCache.Verify(c => c.Remove(cacheKey), Times.Once());
}
[Test]
public void RepositoryBase_Delete_Clears_Cache_If_Cacheable_And_Scoped()
{
//Arrange
var cacheKey = String.Format(TestConstants.CACHE_CatsKey + "_" + TestConstants.CACHE_ScopeModule + "_{0}", TestConstants.MODULE_ValidId);
_mockCache.Setup(c => c.Get(cacheKey)).Returns(new List<CacheableCat>());
var mockRepository = new Mock<RepositoryBase<CacheableCat>>(_mockCache.Object);
//Act
mockRepository.Object.Delete(new CacheableCat { ModuleId = TestConstants.MODULE_ValidId });
//Assert
_mockCache.Verify(c => c.Remove(cacheKey), Times.Once());
}
[Test]
public void RepositoryBase_Delete_Does_Not_Clear_Cache_If_Not_Cacheable()
{
//Arrange
var mockRepository = new Mock<RepositoryBase<Dog>>(_mockCache.Object);
//Act
mockRepository.Object.Delete(new Dog());
//Assert
_mockCache.Verify(c => c.Remove(It.IsAny<string>()), Times.Never());
}
[Test]
public void RepositoryBase_Delete_Calls_DeleteInternal()
{
//Arrange
var mockRepository = new Mock<RepositoryBase<Dog>>(_mockCache.Object);
mockRepository.Protected().Setup("DeleteInternal", ItExpr.IsAny<Dog>());
//Act
mockRepository.Object.Delete(new Dog());
//Assert
mockRepository.Protected().Verify("DeleteInternal", Times.Once(), ItExpr.IsAny<Dog>());
}
[Test]
public void RepositoryBase_GetAll_Checks_Cache_If_Cacheable()
{
//Arrange
var cacheKey = TestConstants.CACHE_DogsKey;
_mockCache.Setup(c => c.Get(cacheKey)).Returns(new List<CacheableDog>());
var mockRepository = new Mock<RepositoryBase<CacheableDog>>(_mockCache.Object);
//Act
var list = mockRepository.Object.GetAll();
//Assert
_mockCache.Verify(c => c.Get(cacheKey));
}
[Test]
public void RepositoryBase_GetAll_Does_Not_Check_Cache_If_Not_Cacheable()
{
//Arrange
var cacheKey = TestConstants.CACHE_DogsKey;
var mockRepository = new Mock<RepositoryBase<Dog>>(_mockCache.Object);
//Act
var list = mockRepository.Object.GetAll();
//Assert
_mockCache.Verify(c => c.Get(cacheKey), Times.Never());
}
[Test]
public void RepositoryBase_GetAll_Does_Not_Check_Cache_If_Cacheable_But_Not_Scoped()
{
//Arrange
var cacheKey = TestConstants.CACHE_DogsKey;
var mockRepository = new Mock<RepositoryBase<CacheableCat>>(_mockCache.Object);
//Act
var list = mockRepository.Object.GetAll();
//Assert
_mockCache.Verify(c => c.Get(cacheKey), Times.Never());
}
[Test]
public void RepositoryBase_GetAll_Calls_GetAllInternal_If_Cacheable_And_Cache_Expired()
{
//Arrange
var cacheKey = TestConstants.CACHE_DogsKey;
_mockCache.Setup(c => c.Get(cacheKey)).Returns(null);
var mockRepository = new Mock<RepositoryBase<CacheableDog>>(_mockCache.Object);
mockRepository.Protected().Setup("GetAllInternal");
//Act
var list = mockRepository.Object.GetAll();
//Assert
mockRepository.Protected().Verify("GetAllInternal", Times.Once());
}
[Test]
public void RepositoryBase_GetAll_Calls_GetAllInternal_If_Not_Cacheable()
{
//Arrange
var mockRepository = new Mock<RepositoryBase<Dog>>(_mockCache.Object);
mockRepository.Protected().Setup("GetAllInternal");
//Act
var list = mockRepository.Object.GetAll();
//Assert
mockRepository.Protected().Verify("GetAllInternal", Times.Once());
}
[Test]
public void RepositoryBase_GetAll_Calls_GetAllInternal_If_Cacheable_But_Not_Scoped()
{
//Arrange
var mockRepository = new Mock<RepositoryBase<CacheableCat>>(_mockCache.Object);
mockRepository.Protected().Setup("GetAllInternal");
//Act
var list = mockRepository.Object.GetAll();
//Assert
mockRepository.Protected().Verify("GetAllInternal", Times.Once());
}
[Test]
public void RepositoryBase_GetAll_Does_Not_Call_GetAllInternal_If_Cacheable_And_Cache_Valid()
{
//Arrange
var cacheKey = TestConstants.CACHE_DogsKey;
_mockCache.Setup(c => c.Get(cacheKey)).Returns(new List<CacheableDog>());
var mockRepository = new Mock<RepositoryBase<CacheableDog>>(_mockCache.Object);
mockRepository.Protected().Setup("GetAllInternal");
//Act
var list = mockRepository.Object.GetAll();
//Assert
mockRepository.Protected().Verify("GetAllInternal", Times.Never());
}
[Test]
public void RepositoryBase_Get_Checks_Cache_If_Cacheable_And_Scoped()
{
//Arrange
var cacheKey = String.Format(TestConstants.CACHE_CatsKey + "_" + TestConstants.CACHE_ScopeModule + "_{0}", TestConstants.MODULE_ValidId);
_mockCache.Setup(c => c.Get(cacheKey)).Returns(new List<CacheableCat>());
var mockRepository = new Mock<RepositoryBase<CacheableCat>>(_mockCache.Object);
//Act
var list = mockRepository.Object.Get<int>(TestConstants.MODULE_ValidId);
//Assert
_mockCache.Verify(c => c.Get(cacheKey));
}
[Test]
public void RepositoryBase_Get_Throws_If_Not_Cacheable()
{
//Arrange
var mockRepository = new Mock<RepositoryBase<Dog>>(_mockCache.Object);
//Act, Assert
Assert.Throws<NotSupportedException>(() => mockRepository.Object.Get<int>(TestConstants.MODULE_ValidId));
}
[Test]
public void RepositoryBase_Get_Throws_If_Not_Scoped()
{
//Arrange
var mockRepository = new Mock<RepositoryBase<Dog>>(_mockCache.Object);
//Act, Assert
Assert.Throws<NotSupportedException>(() => mockRepository.Object.Get<int>(TestConstants.MODULE_ValidId));
}
[Test]
public void RepositoryBase_Get_Throws_If_Cacheable_But_Not_Scoped()
{
//Arrange
var mockRepository = new Mock<RepositoryBase<CacheableDog>>(_mockCache.Object);
//Act, Assert
Assert.Throws<NotSupportedException>(() => mockRepository.Object.Get<int>(TestConstants.MODULE_ValidId));
}
[Test]
public void RepositoryBase_Get_Calls_GetByScopeInternal_If_Not_Cacheable_And_Is_Scoped()
{
//Arrange
var mockRepository = new Mock<RepositoryBase<Cat>>(_mockCache.Object);
mockRepository.Protected().Setup<IEnumerable<Cat>>("GetByScopeInternal", ItExpr.IsAny<object>());
//Act
var list = mockRepository.Object.Get<int>(TestConstants.MODULE_ValidId);
//Assert
mockRepository.Protected().Verify<IEnumerable<Cat>>("GetByScopeInternal", Times.Once(), ItExpr.IsAny<object>());
}
[Test]
public void RepositoryBase_Get_Calls_GetByScopeInternal_If_Cacheable_And_Cache_Expired()
{
//Arrange
var cacheKey = String.Format(TestConstants.CACHE_CatsKey + "_" + TestConstants.CACHE_ScopeModule + "_{0}", TestConstants.MODULE_ValidId);
_mockCache.Setup(c => c.Get(cacheKey)).Returns(null);
var mockRepository = new Mock<RepositoryBase<CacheableCat>>(_mockCache.Object);
mockRepository.Protected().Setup<IEnumerable<CacheableCat>>("GetByScopeInternal", ItExpr.IsAny<object>());
//Act
var list = mockRepository.Object.Get<int>(TestConstants.MODULE_ValidId);
//Assert
mockRepository.Protected().Verify<IEnumerable<CacheableCat>>("GetByScopeInternal", Times.Once(), ItExpr.IsAny<object>());
}
[Test]
public void RepositoryBase_Get_Does_Not_Call_GetByScopeInternal_If_Cacheable_And_Cache_Valid()
{
//Arrange
var cacheKey = String.Format(TestConstants.CACHE_CatsKey + "_" + TestConstants.CACHE_ScopeModule + "_{0}", TestConstants.MODULE_ValidId);
_mockCache.Setup(c => c.Get(cacheKey)).Returns(new List<CacheableCat>());
var mockRepository = new Mock<RepositoryBase<CacheableCat>>(_mockCache.Object);
mockRepository.Protected().Setup<IEnumerable<CacheableCat>>("GetByScopeInternal", ItExpr.IsAny<object>());
//Act
var list = mockRepository.Object.Get<int>(TestConstants.MODULE_ValidId);
//Assert
mockRepository.Protected().Verify<IEnumerable<CacheableCat>>("GetByScopeInternal", Times.Never(), ItExpr.IsAny<object>());
}
[Test]
public void RepositoryBase_GetById_Checks_Cache_If_Cacheable()
{
//Arrange
var cacheKey = TestConstants.CACHE_DogsKey;
_mockCache.Setup(c => c.Get(cacheKey)).Returns(new List<CacheableDog>());
var mockRepository = new Mock<RepositoryBase<CacheableDog>>(_mockCache.Object);
//Act
var dog = mockRepository.Object.GetById(TestConstants.PETAPOCO_ValidDogId);
//Assert
_mockCache.Verify(c => c.Get(cacheKey));
}
[Test]
public void RepositoryBase_GetById_Does_Not_Check_Cache_If_Not_Cacheable()
{
//Arrange
var cacheKey = TestConstants.CACHE_DogsKey;
var mockRepository = new Mock<RepositoryBase<Dog>>(_mockCache.Object);
//Act
var dog = mockRepository.Object.GetById(TestConstants.PETAPOCO_ValidDogId);
//Assert
_mockCache.Verify(c => c.Get(cacheKey), Times.Never());
}
[Test]
public void RepositoryBase_GetById_Does_Not_Check_Cache_If_Cacheable_But_Not_Scoped()
{
//Arrange
var cacheKey = TestConstants.CACHE_CatsKey;
var mockRepository = new Mock<RepositoryBase<CacheableCat>>(_mockCache.Object);
//Act
var cat = mockRepository.Object.GetById(TestConstants.CACHE_ValidCatId);
//Assert
_mockCache.Verify(c => c.Get(cacheKey), Times.Never());
}
[Test]
public void RepositoryBase_GetById_Calls_GetByIdInternal_If_Not_Cacheable()
{
//Arrange
var mockRepository = new Mock<RepositoryBase<Dog>>(_mockCache.Object);
mockRepository.Protected().Setup<Dog>("GetByIdInternal", ItExpr.IsAny<object>());
//Act
var dog = mockRepository.Object.GetById(TestConstants.PETAPOCO_ValidDogId);
//Assert
mockRepository.Protected().Verify<Dog>("GetByIdInternal", Times.Once(), ItExpr.IsAny<object>());
}
[Test]
public void RepositoryBase_GetById_Calls_GetByIdInternal_If_Cacheable_But_Not_Scoped()
{
//Arrange
var mockRepository = new Mock<RepositoryBase<CacheableCat>>(_mockCache.Object);
mockRepository.Protected().Setup<CacheableCat>("GetByIdInternal", ItExpr.IsAny<object>());
//Act
var cat = mockRepository.Object.GetById(TestConstants.CACHE_ValidCatId);
//Assert
mockRepository.Protected().Verify<CacheableCat>("GetByIdInternal", Times.Once(), ItExpr.IsAny<object>());
}
[Test]
public void RepositoryBase_GetById_Does_Not_Call_GetByIdInternal_If_Cacheable_And_Cache_Valid()
{
//Arrange
var cacheKey = TestConstants.CACHE_DogsKey;
_mockCache.Setup(c => c.Get(cacheKey)).Returns(new List<CacheableDog>());
var mockRepository = new Mock<RepositoryBase<CacheableDog>>(_mockCache.Object);
mockRepository.Protected().Setup<CacheableDog>("GetByIdInternal", ItExpr.IsAny<object>());
//Act
var dog = mockRepository.Object.GetById(TestConstants.PETAPOCO_ValidDogId);
//Assert
mockRepository.Protected().Verify<CacheableDog>("GetByIdInternal", Times.Never(), ItExpr.IsAny<object>());
}
[Test]
public void RepositoryBase_GetById_Overload_Checks_Cache_If_Cacheable_And_Scoped()
{
//Arrange
var cacheKey = String.Format(TestConstants.CACHE_CatsKey + "_" + TestConstants.CACHE_ScopeModule + "_{0}", TestConstants.MODULE_ValidId);
_mockCache.Setup(c => c.Get(cacheKey)).Returns(new List<CacheableCat>());
var mockRepository = new Mock<RepositoryBase<CacheableCat>>(_mockCache.Object);
//Act
var cat = mockRepository.Object.GetById(TestConstants.CACHE_ValidCatId, TestConstants.MODULE_ValidId);
//Assert
_mockCache.Verify(c => c.Get(cacheKey));
}
[Test]
public void RepositoryBase_GetById_Overload_Throws_If_Not_Cacheable()
{
//Arrange
var mockRepository = new Mock<RepositoryBase<Dog>>(_mockCache.Object);
//Act, Assert
Assert.Throws<NotSupportedException>(() => mockRepository.Object.GetById(TestConstants.PETAPOCO_ValidDogId, TestConstants.MODULE_ValidId));
}
[Test]
public void RepositoryBase_GetById_Overload_Throws__If_Cacheable_But_Not_Scoped()
{
//Arrange
var mockRepository = new Mock<RepositoryBase<CacheableDog>>(_mockCache.Object);
//Act, Assert
Assert.Throws<NotSupportedException>(() => mockRepository.Object.GetById(TestConstants.PETAPOCO_ValidDogId, TestConstants.MODULE_ValidId));
}
[Test]
public void RepositoryBase_GetPage_Checks_Cache_If_Cacheable()
{
//Arrange
var cacheKey = TestConstants.CACHE_DogsKey;
_mockCache.Setup(c => c.Get(cacheKey)).Returns(new List<CacheableDog>());
var mockRepository = new Mock<RepositoryBase<CacheableDog>>(_mockCache.Object);
//Act
var dogs = mockRepository.Object.GetPage(TestConstants.PAGE_First, TestConstants.PAGE_RecordCount);
//Assert
_mockCache.Verify(c => c.Get(cacheKey));
}
[Test]
public void RepositoryBase_GetPage_Does_Not_Check_Cache_If_Not_Cacheable()
{
//Arrange
var cacheKey = TestConstants.CACHE_DogsKey;
var mockRepository = new Mock<RepositoryBase<Dog>>(_mockCache.Object);
//Act
var dogs = mockRepository.Object.GetPage(TestConstants.PAGE_First, TestConstants.PAGE_RecordCount);
//Assert
_mockCache.Verify(c => c.Get(cacheKey), Times.Never());
}
[Test]
public void RepositoryBase_GetPage_Does_Not_Check_Cache_If_Cacheable_But_Not_Scoped()
{
//Arrange
var cacheKey = TestConstants.CACHE_DogsKey;
var mockRepository = new Mock<RepositoryBase<CacheableCat>>(_mockCache.Object);
//Act
var cats = mockRepository.Object.GetPage(TestConstants.PAGE_First, TestConstants.PAGE_RecordCount);
//Assert
_mockCache.Verify(c => c.Get(cacheKey), Times.Never());
}
[Test]
public void RepositoryBase_GetPage_Calls_GetPageInternal_If_Not_Cacheable()
{
//Arrange
var mockRepository = new Mock<RepositoryBase<Dog>>(_mockCache.Object);
mockRepository.Protected().Setup<IPagedList<Dog>>("GetPageInternal", ItExpr.IsAny<int>(), ItExpr.IsAny<int>());
//Act
var dogs = mockRepository.Object.GetPage(TestConstants.PAGE_First, TestConstants.PAGE_RecordCount);
//Assert
mockRepository.Protected().Verify<IPagedList<Dog>>("GetPageInternal", Times.Once(), ItExpr.IsAny<int>(), ItExpr.IsAny<int>());
}
[Test]
public void RepositoryBase_GetPage_Calls_GetPageInternal_If_Cacheable_But_Not_Scoped()
{
//Arrange
var mockRepository = new Mock<RepositoryBase<CacheableCat>>(_mockCache.Object);
mockRepository.Protected().Setup<IPagedList<CacheableCat>>("GetPageInternal", ItExpr.IsAny<int>(), ItExpr.IsAny<int>());
//Act
var cats = mockRepository.Object.GetPage(TestConstants.PAGE_First, TestConstants.PAGE_RecordCount);
//Assert
mockRepository.Protected().Verify<IPagedList<CacheableCat>>("GetPageInternal", Times.Once(), ItExpr.IsAny<int>(), ItExpr.IsAny<int>());
}
[Test]
public void RepositoryBase_GetPage_Does_Not_Call_GetPageInternal_If_Cacheable_And_Cache_Valid()
{
//Arrange
var cacheKey = TestConstants.CACHE_DogsKey;
_mockCache.Setup(c => c.Get(cacheKey))
.Returns(new List<CacheableDog>() { new CacheableDog() });
var mockRepository = new Mock<RepositoryBase<CacheableDog>>(_mockCache.Object);
mockRepository.Protected().Setup<IPagedList<CacheableDog>>("GetPageInternal", ItExpr.IsAny<int>(), ItExpr.IsAny<int>());
//Act
var dogs = mockRepository.Object.GetPage(TestConstants.PAGE_First, TestConstants.PAGE_RecordCount);
//Assert
mockRepository.Protected().Verify<IPagedList<CacheableDog>>("GetPageInternal", Times.Never(), ItExpr.IsAny<int>(), ItExpr.IsAny<int>());
}
[Test]
public void RepositoryBase_GetPage_Overload_Checks_Cache_If_Cacheable_And_Scoped()
{
//Arrange
var cacheKey = String.Format(TestConstants.CACHE_CatsKey + "_" + TestConstants.CACHE_ScopeModule + "_{0}", TestConstants.MODULE_ValidId);
_mockCache.Setup(c => c.Get(cacheKey)).Returns(new List<CacheableCat>());
var mockRepository = new Mock<RepositoryBase<CacheableCat>>(_mockCache.Object);
//Act
var cats = mockRepository.Object.GetPage<int>(TestConstants.MODULE_ValidId, TestConstants.PAGE_First, TestConstants.PAGE_RecordCount);
//Assert
_mockCache.Verify(c => c.Get(cacheKey));
}
[Test]
public void RepositoryBase_GetPage_Overload_Throws_If_Not_Cacheable()
{
//Arrange
var mockRepository = new Mock<RepositoryBase<Dog>>(_mockCache.Object);
//Act, Assert
Assert.Throws<NotSupportedException>(() => mockRepository.Object.GetPage<int>(TestConstants.MODULE_ValidId, TestConstants.PAGE_First, TestConstants.PAGE_RecordCount));
}
[Test]
public void RepositoryBase_GetPage_Overload_Throws_If_Not_Scoped()
{
//Arrange
var mockRepository = new Mock<RepositoryBase<Dog>>(_mockCache.Object);
//Act, Assert
Assert.Throws<NotSupportedException>(() => mockRepository.Object.GetPage<int>(TestConstants.MODULE_ValidId, TestConstants.PAGE_First, TestConstants.PAGE_RecordCount));
}
[Test]
public void RepositoryBase_GetPage_Overload_Throws_If_Cacheable_But_Not_Scoped()
{
//Arrange
var mockRepository = new Mock<RepositoryBase<CacheableDog>>(_mockCache.Object);
//Act, Assert
Assert.Throws<NotSupportedException>(() => mockRepository.Object.GetPage<int>(TestConstants.MODULE_ValidId, TestConstants.PAGE_First, TestConstants.PAGE_RecordCount));
}
[Test]
public void RepositoryBase_GetPage_Overload_Calls_GetPageByScopeInternal_If_Not_Cacheable_And_Is_Scoped()
{
//Arrange
var mockRepository = new Mock<RepositoryBase<Cat>>(_mockCache.Object);
mockRepository.Protected().Setup<IEnumerable<Cat>>("GetPageByScopeInternal", ItExpr.IsAny<object>(), ItExpr.IsAny<int>(), ItExpr.IsAny<int>());
//Act
var cats = mockRepository.Object.GetPage<int>(TestConstants.MODULE_ValidId, TestConstants.PAGE_First, TestConstants.PAGE_RecordCount);
//Assert
mockRepository.Protected().Verify<IEnumerable<Cat>>("GetPageByScopeInternal", Times.Once(), ItExpr.IsAny<object>(), ItExpr.IsAny<int>(), ItExpr.IsAny<int>());
}
[Test]
public void RepositoryBase_GetPage_Overload_Calls_GetByScopeInternal_If_Cacheable_And_Cache_Expired()
{
//Arrange
var cacheKey = String.Format(TestConstants.CACHE_CatsKey + "_" + TestConstants.CACHE_ScopeModule + "_{0}", TestConstants.MODULE_ValidId);
_mockCache.Setup(c => c.Get(cacheKey)).Returns(null);
var mockRepository = new Mock<RepositoryBase<CacheableCat>>(_mockCache.Object);
mockRepository.Protected().Setup<IEnumerable<CacheableCat>>("GetByScopeInternal", ItExpr.IsAny<object>())
.Returns(new List<CacheableCat>());
//Act
var cats = mockRepository.Object.GetPage<int>(TestConstants.MODULE_ValidId, TestConstants.PAGE_First, TestConstants.PAGE_RecordCount);
//Assert
mockRepository.Protected().Verify<IEnumerable<CacheableCat>>("GetByScopeInternal", Times.Once(), ItExpr.IsAny<object>());
}
[Test]
public void RepositoryBase_GetPage_Overload_Does_Not_Call_GetByScopeInternal_If_Cacheable_And_Cache_Valid()
{
//Arrange
var cacheKey = String.Format(TestConstants.CACHE_CatsKey + "_" + TestConstants.CACHE_ScopeModule + "_{0}", TestConstants.MODULE_ValidId);
_mockCache.Setup(c => c.Get(cacheKey)).Returns(new List<CacheableCat>());
var mockRepository = new Mock<RepositoryBase<CacheableCat>>(_mockCache.Object);
mockRepository.Protected().Setup<IEnumerable<CacheableCat>>("GetByScopeInternal", ItExpr.IsAny<object>());
//Act
var cats = mockRepository.Object.GetPage<int>(TestConstants.MODULE_ValidId, TestConstants.PAGE_First, TestConstants.PAGE_RecordCount);
//Assert
mockRepository.Protected().Verify<IEnumerable<CacheableCat>>("GetByScopeInternal", Times.Never(), ItExpr.IsAny<object>());
}
[Test]
public void RepositoryBase_Update_Clears_Cache_If_Cacheable()
{
//Arrange
var cacheKey = TestConstants.CACHE_DogsKey;
_mockCache.Setup(c => c.Get(cacheKey)).Returns(new List<CacheableDog>());
var mockRepository = new Mock<RepositoryBase<CacheableDog>>(_mockCache.Object);
//Act
mockRepository.Object.Update(new CacheableDog());
//Assert
_mockCache.Verify(c => c.Remove(cacheKey), Times.Once());
}
[Test]
public void RepositoryBase_Update_Clears_Cache_If_Cacheable_And_Scoped()
{
//Arrange
var cacheKey = String.Format(TestConstants.CACHE_CatsKey + "_" + TestConstants.CACHE_ScopeModule + "_{0}", TestConstants.MODULE_ValidId);
_mockCache.Setup(c => c.Get(cacheKey)).Returns(new List<CacheableCat>());
var mockRepository = new Mock<RepositoryBase<CacheableCat>>(_mockCache.Object);
//Act
mockRepository.Object.Update(new CacheableCat { ModuleId = TestConstants.MODULE_ValidId });
//Assert
_mockCache.Verify(c => c.Remove(cacheKey), Times.Once());
}
[Test]
public void RepositoryBase_Update_Does_Not_Clear_Cache_If_Not_Cacheable()
{
//Arrange
var mockRepository = new Mock<RepositoryBase<Dog>>(_mockCache.Object);
//Act
mockRepository.Object.Update(new Dog());
//Assert
_mockCache.Verify(c => c.Remove(It.IsAny<string>()), Times.Never());
}
[Test]
public void RepositoryBase_Update_Calls_UpdateInternal()
{
//Arrange
var mockRepository = new Mock<RepositoryBase<Dog>>(_mockCache.Object);
mockRepository.Protected().Setup("UpdateInternal", ItExpr.IsAny<Dog>());
//Act
mockRepository.Object.Update(new Dog());
//Assert
mockRepository.Protected().Verify("UpdateInternal", Times.Once(), ItExpr.IsAny<Dog>());
}
// ReSharper restore InconsistentNaming
}
}
<file_sep>/src/Naif.Data/ComponentModel/PrimaryKeyAttribute.cs
//******************************************
// Copyright (C) 2014-2015 <NAME> *
// *
// Licensed under MIT License *
// (see included LICENSE) *
// *
// *****************************************
using System;
namespace Naif.Data.ComponentModel
{
public class PrimaryKeyAttribute : Attribute
{
public PrimaryKeyAttribute()
{
AutoIncrement = true;
}
public bool AutoIncrement { get; set; }
public string KeyField { get; set; }
}
}
<file_sep>/src/Naif.Data.PetaPoco/PetaPocoUnitOfWork.cs
//******************************************
// Copyright (C) 2014-2015 <NAME> *
// *
// Licensed under MIT License *
// (see included LICENSE) *
// *
// *****************************************
using System;
using System.CodeDom;
using Naif.Core.Caching;
using Naif.Core.Contracts;
using PetaPoco;
namespace Naif.Data.PetaPoco
{
public class PetaPocoUnitOfWork : IUnitOfWork
{
private readonly ICacheProvider _cache;
public PetaPocoUnitOfWork(string connectionStringName, ICacheProvider cache)
: this(connectionStringName, String.Empty, cache)
{
}
public PetaPocoUnitOfWork(string connectionStringName, string tablePrefix, ICacheProvider cache)
{
Requires.NotNullOrEmpty("connectionStringName", connectionStringName);
Requires.NotNull("cache", cache);
Database = new Database(connectionStringName);
Mapper = new PetaPocoMapper(tablePrefix);
_cache = cache;
}
public void Commit() { }
public IRepository<T> GetRepository<T>() where T : class
{
return new PetaPocoRepository<T>(this, _cache);
}
internal Database Database { get; private set; }
internal IMapper Mapper { get; private set; }
public void Dispose()
{
Database.Dispose();
}
}
}<file_sep>/src/Naif.Data.EntityFramework/NaifDbContext.cs
//******************************************
// Copyright (C) 2014-2015 <NAME> *
// *
// Licensed under MIT License *
// (see included LICENSE) *
// *
// *****************************************
using System;
using System.Data.Entity;
namespace Naif.Data.EntityFramework
{
public class NaifDbContext : DbContext
{
private readonly Action<DbModelBuilder> _modelCreateCallback ;
public NaifDbContext(string connectionString, Action<DbModelBuilder> modelCreateCallback) : base(connectionString)
{
_modelCreateCallback = modelCreateCallback;
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// ReSharper disable once UseNullPropagation
if (_modelCreateCallback != null)
{
_modelCreateCallback(modelBuilder);
}
}
}
}
<file_sep>/tests/Naif.TestUtilities/Fakes/FakeRepository.cs
//******************************************
// Copyright (C) 2014-2015 <NAME> *
// *
// Licensed under MIT License *
// (see included LICENSE) *
// *
// *****************************************
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using Naif.Core.Caching;
using Naif.Core.Collections;
using Naif.Data;
namespace Naif.TestUtilities.Fakes
{
public class FakeRepository<TModel> : RepositoryBase<TModel> where TModel : class
{
public FakeRepository(ICacheProvider cache) : base(cache)
{
}
public override IEnumerable<TModel> Find(string sqlCondition, params object[] args)
{
throw new System.NotImplementedException();
}
public override IPagedList<TModel> Find(int pageIndex, int pageSize, string sqlCondition, params object[] args)
{
throw new System.NotImplementedException();
}
public override IEnumerable<TModel> Find(Expression<Func<TModel, bool>> predicate)
{
throw new NotImplementedException();
}
public override IPagedList<TModel> Find(int pageIndex, int pageSize, Expression<Func<TModel, bool>> predicate)
{
throw new NotImplementedException();
}
protected override void AddInternal(TModel item)
{
throw new System.NotImplementedException();
}
protected override void DeleteInternal(TModel item)
{
throw new System.NotImplementedException();
}
protected override IEnumerable<TModel> GetAllInternal()
{
throw new System.NotImplementedException();
}
protected override TModel GetByIdInternal(object id)
{
throw new System.NotImplementedException();
}
protected override IEnumerable<TModel> GetByPropertyInternal<TProperty>(string propertyName, TProperty propertyValue)
{
throw new System.NotImplementedException();
}
protected override IEnumerable<TModel> GetByScopeInternal(object propertyValue)
{
throw new System.NotImplementedException();
}
protected override IPagedList<TModel> GetPageInternal(int pageIndex, int pageSize)
{
throw new System.NotImplementedException();
}
protected override IPagedList<TModel> GetPageByScopeInternal(object propertyValue, int pageIndex, int pageSize)
{
throw new System.NotImplementedException();
}
protected override void UpdateInternal(TModel item)
{
throw new System.NotImplementedException();
}
}
}
<file_sep>/tests/Naif.Data.NPoco.Tests/NPocoRepositoryTests.cs
//******************************************
// Copyright (C) 2014-2015 <NAME> *
// *
// Licensed under MIT License *
// (see included LICENSE) *
// *
// *****************************************
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using Moq;
using Naif.Core.Caching;
using Naif.TestUtilities;
using Naif.TestUtilities.Models;
using NPoco;
using NUnit.Framework;
namespace Naif.Data.NPoco.Tests
{
[TestFixture]
public class NPocoRepositoryTests
{
private const string ConnectionStringName = "NPoco";
private readonly string[] _dogAges = TestConstants.NPOCO_DogAges.Split(',');
private readonly string[] _dogNames = TestConstants.NPOCO_DogNames.Split(',');
private NPocoUnitOfWork _nPocoUnitOfWork;
private Mock<ICacheProvider> _cache;
[SetUp]
public void SetUp()
{
_cache = new Mock<ICacheProvider>();
_nPocoUnitOfWork = CreateNPocoUnitOfWork();
}
[TearDown]
public void TearDown()
{
DataUtil.DeleteDatabase(TestConstants.NPOCO_DatabaseName);
}
[Test]
public void NPocoRepository_Constructor_Throws_On_Null_ICacheProvider()
{
//Arrange, Act, Assert
Assert.Throws<ArgumentNullException>(() => new NPocoRepository<Dog>(_nPocoUnitOfWork, null));
}
[Test]
public void NPocoRepository_Constructor_Throws_On_Null_UnitOfWork()
{
//Arrange
var mockCache = new Mock<ICacheProvider>();
//Act, Assert
Assert.Throws<ArgumentNullException>(() => new NPocoRepository<Dog>(null, mockCache.Object));
}
[Test]
public void NPocoRepository_Add_Inserts_Item_Into_DataBase()
{
//Arrange
var mockCache = new Mock<ICacheProvider>();
SetUpDatabase(TestConstants.NPOCO_RecordCount);
var repository = new NPocoRepository<Dog>(_nPocoUnitOfWork, mockCache.Object);
var dog = new Dog
{
Age = TestConstants.NPOCO_InsertDogAge,
Name = TestConstants.NPOCO_InsertDogName
};
//Act
repository.Add(dog);
//Assert
int actualCount = DataUtil.GetRecordCount(TestConstants.NPOCO_DatabaseName, TestConstants.NPOCO_TableName);
Assert.AreEqual(TestConstants.NPOCO_RecordCount + 1, actualCount);
}
[Test]
public void NPocoRepository_Add_Inserts_Item_Into_DataBase_With_Correct_ID()
{
//Arrange
var mockCache = new Mock<ICacheProvider>();
SetUpDatabase(TestConstants.NPOCO_RecordCount);
var repository = new NPocoRepository<Dog>(_nPocoUnitOfWork, mockCache.Object);
var dog = new Dog
{
Age = TestConstants.NPOCO_InsertDogAge,
Name = TestConstants.NPOCO_InsertDogName
};
//Act
repository.Add(dog);
//Assert
int newId = DataUtil.GetLastAddedRecordID(TestConstants.NPOCO_DatabaseName,
TestConstants.NPOCO_TableName, "ID");
Assert.AreEqual(TestConstants.NPOCO_RecordCount + 1, newId);
}
[Test]
public void NPocoRepository_Add_Inserts_Item_Into_DataBase_With_Correct_ColumnValues()
{
//Arrange
var mockCache = new Mock<ICacheProvider>();
SetUpDatabase(TestConstants.NPOCO_RecordCount);
var repository = new NPocoRepository<Dog>(_nPocoUnitOfWork, mockCache.Object);
var dog = new Dog
{
Age = TestConstants.NPOCO_InsertDogAge,
Name = TestConstants.NPOCO_InsertDogName
};
//Act
repository.Add(dog);
//Assert
DataTable table = DataUtil.GetTable(TestConstants.NPOCO_DatabaseName, TestConstants.NPOCO_TableName);
DataRow row = table.Rows[table.Rows.Count - 1];
Assert.AreEqual(TestConstants.NPOCO_InsertDogAge, row["Age"]);
Assert.AreEqual(TestConstants.NPOCO_InsertDogName, row["Name"]);
}
[Test]
public void NPocoRepository_Delete_Deletes_Item_From_DataBase()
{
//Arrange
var mockCache = new Mock<ICacheProvider>();
SetUpDatabase(TestConstants.NPOCO_RecordCount);
var repository = new NPocoRepository<Dog>(_nPocoUnitOfWork, mockCache.Object);
var dog = new Dog
{
ID = TestConstants.NPOCO_DeleteDogId,
Age = TestConstants.NPOCO_DeleteDogAge,
Name = TestConstants.NPOCO_DeleteDogName
};
//Act
repository.Delete(dog);
//Assert
int actualCount = DataUtil.GetRecordCount(TestConstants.NPOCO_DatabaseName,
TestConstants.NPOCO_TableName);
Assert.AreEqual(TestConstants.NPOCO_RecordCount - 1, actualCount);
}
[Test]
public void NPocoRepository_Delete_Deletes_Item_From_DataBase_With_Correct_ID()
{
//Arrange
var mockCache = new Mock<ICacheProvider>();
SetUpDatabase(TestConstants.NPOCO_RecordCount);
var repository = new NPocoRepository<Dog>(_nPocoUnitOfWork, mockCache.Object);
var dog = new Dog
{
ID = TestConstants.NPOCO_DeleteDogId,
Age = TestConstants.NPOCO_DeleteDogAge,
Name = TestConstants.NPOCO_DeleteDogName
};
//Act
repository.Delete(dog);
//Assert
DataTable table = DataUtil.GetTable(TestConstants.NPOCO_DatabaseName, TestConstants.NPOCO_TableName);
foreach (DataRow row in table.Rows)
{
Assert.IsFalse((int)row["ID"] == TestConstants.NPOCO_DeleteDogId);
}
}
[Test]
public void NPocoRepository_Delete_Does_Nothing_With_Invalid_ID()
{
//Arrange
var mockCache = new Mock<ICacheProvider>();
SetUpDatabase(TestConstants.NPOCO_RecordCount);
var repository = new NPocoRepository<Dog>(_nPocoUnitOfWork, mockCache.Object);
var dog = new Dog
{
ID = TestConstants.NPOCO_InvalidDogId,
Age = TestConstants.NPOCO_DeleteDogAge,
Name = TestConstants.NPOCO_DeleteDogName
};
//Act
repository.Delete(dog);
//Assert
//Assert
int actualCount = DataUtil.GetRecordCount(TestConstants.NPOCO_DatabaseName,
TestConstants.NPOCO_TableName);
Assert.AreEqual(TestConstants.NPOCO_RecordCount, actualCount);
}
[Test]
[TestCase(1, "WHERE ID < @0", 2)]
[TestCase(4, "WHERE Age <= @0", 5)]
[TestCase(2, "WHERE Name LIKE @0", "S%")]
public void NPocoRepository_Find_Returns_Correct_Rows(int count, string sqlCondition, object arg)
{
//Arrange
var mockCache = new Mock<ICacheProvider>();
SetUpDatabase(TestConstants.PETAPOCO_RecordCount);
var repository = new NPocoRepository<Dog>(_nPocoUnitOfWork, mockCache.Object);
//Act
IEnumerable<Dog> dogs = repository.Find(sqlCondition, arg);
//Assert
Assert.AreEqual(count, dogs.Count());
}
[Test]
public void NPocoRepository_Find_Overload_Returns_Correct_Rows()
{
//Arrange
var count = 4;
var mockCache = new Mock<ICacheProvider>();
SetUpDatabase(TestConstants.PETAPOCO_RecordCount);
var repository = new NPocoRepository<Dog>(_nPocoUnitOfWork, mockCache.Object);
//Act
IEnumerable<Dog> dogs = repository.Find((d) => d.Age <= 5);
//Assert
Assert.AreEqual(count, dogs.Count());
}
[Test]
[TestCase(0)]
[TestCase(1)]
[TestCase(5)]
public void NPocoRepository_GetAll_Returns_All_Rows(int count)
{
//Arrange
var mockCache = new Mock<ICacheProvider>();
SetUpDatabase(count);
var repository = new NPocoRepository<Dog>(_nPocoUnitOfWork, mockCache.Object);
//Act
IEnumerable<Dog> dogs = repository.GetAll();
//Assert
Assert.AreEqual(count, dogs.Count());
}
[Test]
public void NPocoRepository_GetAll_Returns_List_Of_Models()
{
//Arrange
var mockCache = new Mock<ICacheProvider>();
SetUpDatabase(5);
var repository = new NPocoRepository<Dog>(_nPocoUnitOfWork, mockCache.Object);
//Act
var dogs = repository.GetAll().ToList();
//Assert
for (int i = 0; i < dogs.Count(); i++)
{
Assert.IsInstanceOf<Dog>(dogs[i]);
}
}
[Test]
public void NPocoRepository_GetAll_Returns_Models_With_Correct_Properties()
{
//Arrange
var mockCache = new Mock<ICacheProvider>();
SetUpDatabase(5);
var repository = new NPocoRepository<Dog>(_nPocoUnitOfWork, mockCache.Object);
//Act
var dogs = repository.GetAll();
//Assert
var dog = dogs.First();
Assert.AreEqual(_dogAges[0], dog.Age.ToString());
Assert.AreEqual(_dogNames[0], dog.Name);
}
[Test]
public void NPocoRepository_GetById_Returns_Instance_Of_Model_If_Valid_Id()
{
//Arrange
var mockCache = new Mock<ICacheProvider>();
SetUpDatabase(5);
var repository = new NPocoRepository<Dog>(_nPocoUnitOfWork, mockCache.Object);
//Act
var dog = repository.GetById(TestConstants.NPOCO_ValidDogId);
//Assert
Assert.IsInstanceOf<Dog>(dog);
}
[Test]
public void NPocoRepository_GetById_Returns_Null_If_InValid_Id()
{
//Arrange
var mockCache = new Mock<ICacheProvider>();
SetUpDatabase(5);
var repository = new NPocoRepository<Dog>(_nPocoUnitOfWork, mockCache.Object);
//Act
var dog = repository.GetById(TestConstants.NPOCO_InvalidDogId);
//Assert
Assert.IsNull(dog);
}
[Test]
public void NPocoRepository_GetById_Returns_Model_With_Correct_Properties()
{
//Arrange
var mockCache = new Mock<ICacheProvider>();
SetUpDatabase(5);
var repository = new NPocoRepository<Dog>(_nPocoUnitOfWork, mockCache.Object);
//Act
var dog = repository.GetById(TestConstants.NPOCO_ValidDogId);
//Assert
Assert.AreEqual(TestConstants.NPOCO_ValidDogAge, dog.Age);
Assert.AreEqual(TestConstants.NPOCO_ValidDogName, dog.Name);
}
[Test]
[TestCase("Spot", 2)]
[TestCase("Buddy", 1)]
public void NPocoRepository_GetByProperty_Returns_List_Of_Models_If_Valid_Property(string dogName, int count)
{
//Arrange
var mockCache = new Mock<ICacheProvider>();
SetUpDatabase(5);
var repository = new NPocoRepository<Dog>(_nPocoUnitOfWork, mockCache.Object);
//Act
var dogs = repository.GetByProperty("Name", dogName);
//Assert
Assert.IsInstanceOf<IEnumerable<Dog>>(dogs);
Assert.AreEqual(count, dogs.Count());
}
[Test]
public void NPocoRepository_GetByProperty_Returns_Instance_Of_Model_If_Valid_Property()
{
//Arrange
var mockCache = new Mock<ICacheProvider>();
SetUpDatabase(5);
var dogName = _dogNames[2];
var repository = new NPocoRepository<Dog>(_nPocoUnitOfWork, mockCache.Object);
//Act
var dog = repository.GetByProperty("Name", dogName).FirstOrDefault();
//Assert
Assert.IsInstanceOf<Dog>(dog);
}
[Test]
public void NPocoRepository_GetByProperty_Returns_Empty_List_If_InValid_Proeprty()
{
//Arrange
var mockCache = new Mock<ICacheProvider>();
SetUpDatabase(5);
const string dogName = "Invalid";
var repository = new NPocoRepository<Dog>(_nPocoUnitOfWork, mockCache.Object);
//Act
var dogs = repository.GetByProperty("Name", dogName);
//Assert
Assert.IsInstanceOf<IEnumerable<Dog>>(dogs);
Assert.AreEqual(0, dogs.Count());
}
[Test]
[TestCase("Spot")]
[TestCase("Buddy")]
public void NPocoRepository_GetByProperty_Returns_Models_With_Correct_Properties(string dogName)
{
//Arrange
var mockCache = new Mock<ICacheProvider>();
SetUpDatabase(5);
var repository = new NPocoRepository<Dog>(_nPocoUnitOfWork, mockCache.Object);
//Act
var dogs = repository.GetByProperty("Name", dogName);
//Assert
foreach (Dog dog in dogs)
{
Assert.AreEqual(dogName, dog.Name);
}
}
[Test]
[TestCase(TestConstants.PAGE_First, TestConstants.PAGE_RecordCount)]
[TestCase(TestConstants.PAGE_Second, TestConstants.PAGE_RecordCount)]
[TestCase(TestConstants.PAGE_Last, TestConstants.PAGE_RecordCount)]
public void NPocoRepository_GetPage_Returns_Page_Of_Rows(int pageIndex, int pageSize)
{
//Arrange
var mockCache = new Mock<ICacheProvider>();
SetUpDatabase(TestConstants.PAGE_TotalCount);
var repository = new NPocoRepository<Dog>(_nPocoUnitOfWork, mockCache.Object);
//Act
var dogs = repository.GetPage(pageIndex, pageSize);
//Assert
Assert.AreEqual(pageSize, dogs.PageSize);
}
[Test]
public void NPocoRepository_GetPage_Returns_List_Of_Models()
{
//Arrange
var mockCache = new Mock<ICacheProvider>();
SetUpDatabase(TestConstants.PAGE_TotalCount);
var repository = new NPocoRepository<Dog>(_nPocoUnitOfWork, mockCache.Object);
//Act
var dogs = repository.GetPage(TestConstants.PAGE_First, TestConstants.PAGE_RecordCount);
//Assert
for (int i = 0; i < dogs.Count(); i++)
{
Assert.IsInstanceOf<Dog>(dogs[i]);
}
}
[Test]
public void NPocoRepository_GetPage_Returns_Models_With_Correct_Properties()
{
//Arrange
var mockCache = new Mock<ICacheProvider>();
SetUpDatabase(TestConstants.PAGE_TotalCount);
var repository = new NPocoRepository<Dog>(_nPocoUnitOfWork, mockCache.Object);
//Act
var dogs = repository.GetPage(TestConstants.PAGE_First, TestConstants.PAGE_RecordCount);
//Assert
var dog = dogs.First();
Assert.AreEqual(_dogAges[0], dog.Age.ToString());
Assert.AreEqual(_dogNames[0], dog.Name);
}
[Test]
[TestCase(TestConstants.PAGE_First, TestConstants.PAGE_RecordCount, 1)]
[TestCase(TestConstants.PAGE_Second, TestConstants.PAGE_RecordCount, 6)]
[TestCase(2, 4, 9)]
public void NPocoRepository_GetPage_Returns_Correct_Page(int pageIndex, int pageSize, int firstId)
{
//Arrange
var mockCache = new Mock<ICacheProvider>();
SetUpDatabase(TestConstants.PAGE_TotalCount);
var repository = new NPocoRepository<Dog>(_nPocoUnitOfWork, mockCache.Object);
//Act
var dogs = repository.GetPage(pageIndex, pageSize);
//Assert
var dog = dogs.First();
Assert.AreEqual(firstId, dog.ID);
}
[Test]
public void NPocoRepository_Update_Updates_Item_In_DataBase()
{
//Arrange
var mockCache = new Mock<ICacheProvider>();
SetUpDatabase(TestConstants.NPOCO_RecordCount);
var repository = new NPocoRepository<Dog>(_nPocoUnitOfWork, mockCache.Object);
var dog = new Dog
{
ID = TestConstants.NPOCO_UpdateDogId,
Age = TestConstants.NPOCO_UpdateDogAge,
Name = TestConstants.NPOCO_UpdateDogName
};
//Act
repository.Update(dog);
//Assert
int actualCount = DataUtil.GetRecordCount(TestConstants.NPOCO_DatabaseName,
TestConstants.NPOCO_TableName);
Assert.AreEqual(TestConstants.NPOCO_RecordCount, actualCount);
}
[Test]
public void NPocoRepository_Update_Updates_Item_With_Correct_ID()
{
//Arrange
var mockCache = new Mock<ICacheProvider>();
SetUpDatabase(TestConstants.NPOCO_RecordCount);
var repository = new NPocoRepository<Dog>(_nPocoUnitOfWork, mockCache.Object);
var dog = new Dog
{
ID = TestConstants.NPOCO_UpdateDogId,
Age = TestConstants.NPOCO_UpdateDogAge,
Name = TestConstants.NPOCO_UpdateDogName
};
//Act
repository.Update(dog);
//Assert
DataTable table = DataUtil.GetTable(TestConstants.NPOCO_DatabaseName, TestConstants.NPOCO_TableName);
foreach (DataRow row in table.Rows)
{
if ((int)row["ID"] == TestConstants.NPOCO_UpdateDogId)
{
Assert.AreEqual(TestConstants.NPOCO_UpdateDogAge, row["Age"]);
Assert.AreEqual(TestConstants.NPOCO_UpdateDogName, row["Name"]);
}
}
}
private NPocoUnitOfWork CreateNPocoUnitOfWork()
{
return new NPocoUnitOfWork(ConnectionStringName, _cache.Object);
}
private void SetUpDatabase(int count)
{
DataUtil.CreateDatabase(TestConstants.NPOCO_DatabaseName);
DataUtil.ExecuteNonQuery(TestConstants.NPOCO_DatabaseName, TestConstants.NPOCO_CreateTableSql);
for (int i = 0; i < count; i++)
{
var name = (i < _dogNames.Length) ? _dogNames[i] : String.Format("Name_{0}", i);
var age = (i < _dogNames.Length) ? _dogAges[i] : i.ToString();
DataUtil.ExecuteNonQuery(TestConstants.NPOCO_DatabaseName, String.Format(TestConstants.PETAPOCO_InsertRow, name, age));
}
}
}
}
<file_sep>/src/Naif.Data.EntityFramework/EFUnitOfWork.cs
//******************************************
// Copyright (C) 2014-2015 <NAME> *
// *
// Licensed under MIT License *
// (see included LICENSE) *
// *
// *****************************************
using System;
using System.Data.Entity;
using Naif.Core.Caching;
using Naif.Core.Contracts;
namespace Naif.Data.EntityFramework
{
public class EFUnitOfWork : IUnitOfWork
{
private readonly ICacheProvider _cache;
private readonly NaifDbContext _dbContext;
public EFUnitOfWork(string connectionString, Action<DbModelBuilder> modelCreateCallback, ICacheProvider cache)
{
Requires.NotNull(cache);
Requires.NotNullOrEmpty("connectionString", connectionString);
_dbContext = new NaifDbContext(connectionString, modelCreateCallback);
_cache = cache;
}
public EFUnitOfWork(NaifDbContext dbContext, ICacheProvider cache)
{
Requires.NotNull(dbContext);
Requires.NotNull(cache);
_dbContext = dbContext;
_cache = cache;
}
public void Commit()
{
_dbContext.SaveChanges();
}
public IRepository<T> GetRepository<T>() where T : class
{
throw new NotImplementedException();
}
internal NaifDbContext DbContext()
{
return _dbContext;
}
public bool SupportsLinq
{
get { return true; }
}
public void Dispose()
{
_dbContext.Dispose();
}
}
}
<file_sep>/src/Naif.Data.EntityFramework/EFRepository.cs
//******************************************
// Copyright (C) 2014-2015 <NAME> *
// *
// Licensed under MIT License *
// (see included LICENSE) *
// *
// *****************************************
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using Naif.Core.Caching;
using Naif.Core.Collections;
using Naif.Core.Contracts;
namespace Naif.Data.EntityFramework
{
public class EFRepository<TModel> : RepositoryBase<TModel> where TModel : class
{
private readonly NaifDbContext _context;
private readonly IDbSet<TModel> _dbSet;
public EFRepository(IUnitOfWork unitOfWork, ICacheProvider cache) :base(cache)
{
Requires.NotNull("unitOfWork", unitOfWork);
var efUnitOfWork = unitOfWork as EFUnitOfWork;
if (efUnitOfWork == null)
{
throw new Exception("Must be EFUnitOfWork"); // TODO: Typed exception
}
_context = efUnitOfWork.DbContext();
_dbSet = _context.Set<TModel>();
}
public override IEnumerable<TModel> Find(string sqlCondition, params object[] args)
{
throw new NotImplementedException();
}
public override IPagedList<TModel> Find(int pageIndex, int pageSize, string sqlCondition, params object[] args)
{
throw new NotImplementedException();
}
public override IEnumerable<TModel> Find(Expression<Func<TModel, bool>> predicate)
{
return _dbSet.Where(predicate);
}
public override IPagedList<TModel> Find(int pageIndex, int pageSize, Expression<Func<TModel, bool>> predicate)
{
return _dbSet.Where(predicate).InPagesOf(pageSize).GetPage(pageIndex);
}
protected override void AddInternal(TModel item)
{
_dbSet.Add(item);
}
protected override void DeleteInternal(TModel item)
{
_dbSet.Remove(item);
}
protected override IEnumerable<TModel> GetAllInternal()
{
return _dbSet;
}
protected override TModel GetByIdInternal(object id)
{
throw new NotImplementedException();
}
protected override IEnumerable<TModel> GetByScopeInternal(object scopeValue)
{
throw new NotImplementedException();
}
protected override IPagedList<TModel> GetPageByScopeInternal(object scopeValue, int pageIndex, int pageSize)
{
throw new NotImplementedException();
}
protected override IPagedList<TModel> GetPageInternal(int pageIndex, int pageSize)
{
throw new NotImplementedException();
}
protected override void UpdateInternal(TModel item)
{
}
protected override IEnumerable<TModel> GetByPropertyInternal<TProperty>(string propertyName, TProperty propertyValue)
{
throw new NotImplementedException();
}
}
}
<file_sep>/tests/Naif.TestUtilities/DataUtil.cs
//******************************************
// Copyright (C) 2014-2015 <NAME> *
// *
// Licensed under MIT License *
// (see included LICENSE) *
// *
// *****************************************
using System;
using System.Data;
using System.Data.SqlServerCe;
using System.IO;
namespace Naif.TestUtilities
{
public class DataUtil
{
public static void CreateDatabase(string databaseName)
{
if (File.Exists(databaseName))
{
File.Delete(databaseName);
}
var engine = new SqlCeEngine(GetConnectionString(databaseName));
engine.CreateDatabase();
engine.Dispose();
}
public static void DeleteDatabase(string databaseName)
{
if (File.Exists(databaseName))
{
File.Delete(databaseName);
}
}
public static void ExecuteNonQuery(string databaseName, string sqlScript)
{
ExecuteNonQuery(databaseName, sqlScript, cmd => cmd.ExecuteNonQuery());
}
public static SqlCeDataReader ExecuteReader(string databaseName, string sqlScript)
{
return ExecuteQuery(databaseName, sqlScript, cmd => cmd.ExecuteReader());
}
public static int ExecuteScalar(string databaseName, string sqlScript)
{
return ExecuteQuery(databaseName, sqlScript, cmd => (int)cmd.ExecuteScalar());
}
public static string GetConnectionString(string databaseName)
{
return String.Format("Data Source = {0};", databaseName);
}
public static int GetLastAddedRecordID(string databaseName, string tableName, string primaryKeyField)
{
return ExecuteScalar(databaseName, String.Format(DataResources.GetLastAddedRecordID, tableName, primaryKeyField));
}
public static int GetRecordCount(string databaseName, string tableName)
{
return ExecuteScalar(databaseName, String.Format(DataResources.RecordCountScript, tableName));
}
public static DataTable GetTable(string databaseName, string tableName)
{
return ExecuteQuery(databaseName, String.Format(DataResources.GetTable, tableName),
cmd =>
{
var reader = cmd.ExecuteReader();
var table = new DataTable();
table.Load(reader);
return table;
});
}
public static DataTable GetRecordsByField(string databaseName, string tableName, string fieldName, string fieldValue)
{
var reader = ExecuteReader(databaseName, String.Format(DataResources.GetRecordsByField, tableName, fieldName, fieldValue));
var table = new DataTable();
table.Load(reader);
return table;
}
private static TReturn ExecuteQuery<TReturn>(string databaseName, string sqlScript, Func<SqlCeCommand, TReturn> command)
{
using (var connection = new SqlCeConnection(GetConnectionString(databaseName)))
{
connection.Open();
using (SqlCeCommand cmd = connection.CreateCommand())
{
cmd.CommandText = sqlScript;
return command(cmd);
}
}
}
private static void ExecuteNonQuery(string databaseName, string sqlScript, Action<SqlCeCommand> command)
{
using (var connection = new SqlCeConnection(GetConnectionString(databaseName)))
{
connection.Open();
using (SqlCeCommand cmd = connection.CreateCommand())
{
cmd.CommandText = sqlScript;
command(cmd);
}
}
}
}
}
<file_sep>/tests/Naif.Data.NPoco.Tests/NPocoUnitOfWorkTests.cs
//******************************************
// Copyright (C) 2014-2015 <NAME> *
// *
// Licensed under MIT License *
// (see included LICENSE) *
// *
// *****************************************
using System;
using Moq;
using Naif.Core.Caching;
using Naif.TestUtilities;
using Naif.TestUtilities.Models;
using NPoco;
using NUnit.Framework;
namespace Naif.Data.NPoco.Tests
{
[TestFixture]
public class NPocoUnitOfWorkTests
{
private const string ConnectionStringName = "NPoco";
private Mock<ICacheProvider> _cache;
[SetUp]
public void SetUp()
{
_cache = new Mock<ICacheProvider>();
}
[Test]
public void NPocoUnitOfWork_Constructor_Throws_On_Null_Cache()
{
//Arrange, Act, Assert
Assert.Throws<ArgumentNullException>(() => new NPocoUnitOfWork(ConnectionStringName, null));
}
[Test]
public void NPocoUnitOfWork_Constructor_Throws_On_Null_ConnectionString()
{
//Arrange, Act, Assert
Assert.Throws<ArgumentException>(() => new NPocoUnitOfWork(null, _cache.Object));
}
[Test]
public void NPocoUnitOfWork_Constructor_Throws_On_Empty_ConnectionString()
{
//Arrange, Act, Assert
Assert.Throws<ArgumentException>(() => new NPocoUnitOfWork(String.Empty, _cache.Object));
}
[Test]
public void NPocoUnitOfWork_Constructor_Initialises_Database_Field()
{
//Arrange
//Act
var context = new NPocoUnitOfWork(ConnectionStringName, _cache.Object);
//Assert
Assert.IsInstanceOf<Database>(context.Database);
}
[Test]
public void NPocoUnitOfWork_GetRepository_Returns_Repository()
{
//Arrange, Act
var context = new NPocoUnitOfWork(ConnectionStringName, _cache.Object);
//Act
var rep = context.GetRepository<Dog>();
//Assert
Assert.IsInstanceOf<IRepository<Dog>>(rep);
}
}
}
|
9cb8b7ea08821684fcab1968eb0fc20e2c1c0ff5
|
[
"Markdown",
"C#"
] | 28
|
C#
|
ayee-hatfield/Naif.Data
|
eb323f1c1b1209f45f75539ad02bdafd49fa0e48
|
68461dcce158f03f955e7a976fb4985724dfb75f
|
refs/heads/master
|
<file_sep>rootProject.name = 'accountkata'
<file_sep>package kata.bank.project.model.operation;
import kata.bank.project.model.account.Account.AccountType;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.util.Random;
@Component
public class Transaction {
private int numID;
private LocalDateTime transactionDateTime;
private AccountType accountType;
private TransactionType type;
private Double amount;
public enum TransactionType {
DEPOSIT,
WITHDRAWAL
}
public Transaction() {
}
public Transaction(final LocalDateTime transactionDateTime,
final AccountType accountType,
final TransactionType type,
final Double amount) {
this.numID = (new Random()).nextInt(1000000) + 1;
this.transactionDateTime = transactionDateTime;
this.accountType = accountType;
this.type = type;
this.amount = amount;
}
public int getNumID() {
return numID;
}
public void setNumID(final int numID) {
this.numID = numID;
}
public LocalDateTime getTransactionDateTime() {
return transactionDateTime;
}
public void setTransactionDateTime(final LocalDateTime transactionDateTime) {
this.transactionDateTime = transactionDateTime;
}
public AccountType getAccountType() {
return accountType;
}
public void setAccountType(final AccountType accountType) {
this.accountType = accountType;
}
public TransactionType getType() {
return type;
}
public void setType(final TransactionType type) {
this.type = type;
}
public Double getAmount() {
return amount;
}
public void setAmount(final Double amount) {
this.amount = amount;
}
}
<file_sep>package kata.bank.project.model.account;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;
import kata.bank.project.model.operation.Transaction;
public abstract class Account {
public enum AccountType {
CURRENT,
SAVINGS
}
private AccountType type;
private int accountNumber;
private Double amount;
private AccountStatement statement;
private List<Transaction> operations;
public class AccountStatement {
private LocalDateTime start;
private LocalDateTime end;
private Double balance; // with transactions awaiting
public AccountStatement(final LocalDateTime start,
final LocalDateTime end,
final Double balance) {
this.start = start;
this.end = end;
this.balance = balance;
}
private Double buildBalance(final LocalDateTime startDate, final LocalDateTime endDate) {
List<Transaction> operationsInBalance = operations.stream()
.filter(o -> o.getTransactionDateTime()
.isAfter(startDate)
&& o.getTransactionDateTime()
.isBefore(endDate))
.collect(Collectors.toList());
return operationsInBalance.stream()
.map(Transaction::getAmount)
.mapToDouble(Double::doubleValue)
.sum();
}
public LocalDateTime getStart() {
return start;
}
public void setStart(final LocalDateTime start) {
this.start = start;
}
public LocalDateTime getEnd() {
return end;
}
public void setEnd(final LocalDateTime end) {
this.end = end;
}
public Double getBalance() {
return balance;
}
public void setBalance(final Double balance) {
this.balance = balance;
}
}
public Account(final AccountType type,
final int accountNumber,
final Double amount,
final AccountStatement statement,
final List<Transaction> operations) {
this.type = type;
this.accountNumber = accountNumber;
this.amount = amount;
this.statement = statement;
this.operations = operations;
}
public Account(final AccountType type) {
this(
type,
(new Random()).nextInt(1000000) + 1,
0.0,
null, // TODO correct statement initialisation
new ArrayList<>(0)
);
}
public Account() {}
public AccountType getType() {
return type;
}
public void setType(final AccountType type) {
this.type = type;
}
public int getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(final int accountNumber) {
this.accountNumber = accountNumber;
}
public Double getAmount() {
return amount;
}
public void setAmount(final Double amount) {
this.amount = amount;
}
public AccountStatement getStatement() {
return statement;
}
public void setStatement(final AccountStatement statement) {
this.statement = statement;
}
public List<Transaction> getOperations() {
return operations;
}
public void setOperations(final List<Transaction> operations) {
this.operations = operations;
operations.forEach(o -> amount += o.getAmount());
}
// public abstract void makeWithdrawal(final Account account, final Double value);
}
<file_sep>package kata.bank.project.service;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import kata.bank.project.model.account.Account;
import kata.bank.project.model.operation.Transaction;
public class AccountService implements IAccountService {
private final TransactionService service;
@Autowired
public AccountService(final TransactionService service) {
this.service = service;
}
@Override
public Double buildBalance(final Account account, final LocalDateTime start, final LocalDateTime end) {
List<Transaction> operationsInBalance = account.getOperations()
.stream()
.filter(o -> (o.getTransactionDateTime()
.isAfter(start)
||
o.getTransactionDateTime()
.equals(start)
)
&&
(o.getTransactionDateTime()
.isBefore(end)
||
o.getTransactionDateTime()
.equals(end)
)
)
.collect(Collectors.toList());
return service.calculateOperationsAmount(operationsInBalance);
}
@Override
public Double getBalanceBefore(final LocalDateTime dateTime, final Account account) {
return account.getOperations()
.stream()
.filter(o -> o.getTransactionDateTime()
.isBefore(dateTime)
||
o.getTransactionDateTime()
.equals(dateTime))
.map(Transaction::getAmount)
.mapToDouble(Double::doubleValue)
.sum();
}
}
<file_sep>package kata.bank.project.service;
import java.time.LocalDateTime;
import java.util.List;
import kata.bank.project.model.account.Account;
import kata.bank.project.model.operation.Transaction;
public interface ITransactionService {
void makeDeposit(final Account account, final Double amount);
void makeWithdrawal(final Account account, final Double amount);
double calculateOperationsAmount(final List<Transaction> operations);
double getDepositsAmount(final Account account);
double getWithdrawalsAmount(final Account account);
long returnTransactionsCountBefore(final LocalDateTime dateTime, final Account account);
long returnTransactionsCountAfter(final LocalDateTime dateTime, final Account account);
}
<file_sep>group 'kata.bank.project'
version '1.0-SNAPSHOT'
apply plugin: 'java'
apply plugin: 'idea'
sourceCompatibility = 1.8
targetCompatibility = 1.8
repositories {
mavenCentral()
jcenter()
}
dependencies {
compile 'org.springframework:spring-core:5.0.4.RELEASE'
compile 'org.springframework:spring-context:5.0.4.RELEASE'
// testCompile group: 'junit', name: 'junit', version: '4.12'
testCompile(
'junit:junit:4.12',
'org.codehaus.groovy:groovy-all:2.4.4',
'org.spockframework:spock-core:1.0-groovy-2.4'
)
}
|
6e53e504d216ac7b1481d769159f4da01065e347
|
[
"Java",
"Gradle"
] | 6
|
Gradle
|
mickael-saraga/account-kata
|
7302c9668b2ba215a9cec8cd722edbeeba713c3c
|
15073ca040cc70e13f5d43f245252f1db4369054
|
refs/heads/master
|
<file_sep># EDANet-pytorch-chapter5
The chapter5 of the segmentation network summary:
### Real-time semantic segmentation network.
External links: Efficient Dense Modules of Asymmetric Convolution for Real-Time Semantic Segmentation [paper](https://arxiv.org/abs/1809.06323).
The innovation of this network is employing an asymmetric convolution structure and incorporating the dilated convolution and dense connectivity.

### Environment:
Pytorch version >> 0.4.1; [Python 2.7]
<file_sep>'''
Code written by: <NAME>
If you use significant portions of this code or the ideas from our paper, please cite it :)
'''
import os
import random
import time
import numpy as np
import torch
import math
import torch.nn as nn
from PIL import Image, ImageOps
from argparse import ArgumentParser
from torch.optim import SGD, Adam, lr_scheduler
from torch.autograd import Variable
from torch.utils.data import DataLoader
from torchvision.transforms import Compose, CenterCrop, Normalize, Resize, Pad
from torchvision.transforms import ToTensor, ToPILImage
from dataset import train,test
from transform import Relabel, ToLabel, Colorize
import importlib
from iouEval import iouEval, getColorEntry
from shutil import copyfile
from edanet import EDANet
NUM_CHANNELS = 3
NUM_CLASSES = 2 #pascal=22, cityscapes=20
color_transform = Colorize(NUM_CLASSES)
image_transform = ToPILImage()
image_transform = ToPILImage()
input_transform = Compose([
Resize((512,512)),
#CenterCrop(256),
ToTensor(),
#Normalize([112.65,112.65,112.65],[32.43,32.43,32.43])
#Normalize([.485, .456, .406], [.229, .224, .225]),
])
target_transform = Compose([
Resize((512,512)),
#CenterCrop(324),
ToLabel(),
#Relabel(255, 1),
])
class CrossEntropyLoss2d(torch.nn.Module):
def __init__(self, weight=None):
super(CrossEntropyLoss2d,self).__init__()
self.loss = torch.nn.NLLLoss2d(weight)
def forward(self, outputs, targets):
return self.loss(torch.nn.functional.log_softmax(outputs, dim=1), targets)
def train( model):
best_acc = 0
num_epochs=60
loader = DataLoader(train(input_transform, target_transform),num_workers=1, batch_size=4, shuffle=True)
criterion = nn.CrossEntropyLoss()
savedir = './save'
automated_log_path = savedir + "/log.txt"
modeltxtpath = savedir + "/model.txt"
with open(modeltxtpath, "w") as myfile:
myfile.write(str(model))
optimizer = Adam(model.parameters(), 1e-4, (0.9, 0.999), eps=1e-08, weight_decay=2e-4) ## scheduler 1
start_epoch = 1
lr_updater = lr_scheduler.StepLR(optimizer, 100,
0.1) ## scheduler 2
#Note: this only loads initialized weights. If you want to resume a training use "--resume" option!!
def load_my_state_dict(model, state_dict): #custom function to load model when not all dict keys are there
own_state = model.state_dict()
for name, param in state_dict.items():
if name not in own_state:
continue
own_state[name].copy_(param)
return model
for epoch in range(start_epoch, num_epochs+1):
print("----- TRAINING - EPOCH", epoch, "-----")
lr_updater.step()
epoch_loss = []
time_train = []
usedLr = 0
for param_group in optimizer.param_groups:
print("LEARNING RATE: ", param_group['lr'])
usedLr = float(param_group['lr'])
model.train()
for step, (images, labels) in enumerate(loader):
start_time = time.time()
images = images.cuda()
labels = labels.cuda()
inputs = Variable(images)
targets = Variable(labels)
#print inputs.size(),targets.size()
outputs = model(inputs)
#print outputs.size()
optimizer.zero_grad()
loss = criterion(outputs, targets[:,0])
loss.backward()
optimizer.step()
#print loss.item()
epoch_loss.append(loss.item())
time_train.append(time.time() - start_time)
if step % 100 == 0:
average = sum(epoch_loss) / len(epoch_loss)
print('epoch:%f'%epoch,'step:%f'%step,'loss:%f'%average)
with open(automated_log_path, "a") as myfile:
myfile.write("\n%d\t\t%d\t\t%.4f" % (epoch, step,average ))
if epoch % 1 == 0 and epoch != 0:
filename = 'main-'+'eda'+'-step-'+str(step)+'-epoch-'+str(epoch)+'.pth'
torch.save(model.state_dict(), './save/model/'+filename)
return(model)
def save_checkpoint(state, is_best, filenameCheckpoint, filenameBest):
torch.save(state, filenameCheckpoint)
if is_best:
print ("Saving model as best")
torch.save(state, filenameBest)
def main():
savedir = './save'
Net = EDANet(NUM_CLASSES)
Net = Net.cuda()
train(Net)
if __name__ == '__main__':
main()
|
bcb80be4b0e558e3ecd2f8490396975636b0a1ce
|
[
"Markdown",
"Python"
] | 2
|
Markdown
|
hydxqing/EDANet-pytorch-chapter5
|
c5554848f1e8e5362b837858e6fe210d7ff70444
|
beb97915e45909cc65da058e4aee2c6a13336bfb
|
refs/heads/main
|
<file_sep>import turtle
import grille
papier = turtle.Screen()
crayon = turtle.Turtle()
papier.setup(width=500,height=500)
papier.bgcolor("white")
#a.trace()
papier.update()
grille.set_crayon(grille.Axe.tortue_axe,couleur="darkgray")
grille.set_crayon(grille.Graduation.tortue_graduation,couleur="darkgray")
grille.set_crayon(grille.Pattern.tortue_pattern,couleur="darkgray")
p = grille.Pattern(20,(' ','-'),(90,10))
g = grille.Grille(50,p,50,p)
a = grille.Axe()
grad = grille.Graduation(50,20,label=("Arial",14,"normal"))
grad2 =grille.Graduation(10,5,sub=5,show_label=False)
'''grad.affiche()
grad2.affiche()
g.trace()
a.trace()'''
papier.title('carres imbriques')
grille.set_crayon(crayon,epaisseur=1,couleur="gray")
def carre(c):
crayon.penup()
crayon.setheading(90)
crayon.forward(taille/2)
crayon.setheading(0)
crayon.forward(taille/2)
crayon.pendown()
crayon.setheading(180)
for _ in range(4):
crayon.forward(taille)
crayon.left(90)
crayon.penup()
crayon.setheading(270)
crayon.forward(taille/2)
crayon.setheading(180)
crayon.forward(taille/2)
crayon.pendown()
taille = 200
while taille>=10:
carre(taille)
taille=taille-20
papier.update()
filename = input("Entrer le nom du fichier de sauvegarde : ")
papier.getcanvas().postscript(file=filename)
<file_sep>def somme_recursive(n):
if n==0:
return 0
else:
return n + somme_recursive(n-1)
test = somme_recursive(3000)
<file_sep># Scripts d'administration
## Gestion des qcm
* Partie barre de navigation du fichier mkdocs.yml :
{{ genere_nav() }}<file_sep>import turtle
# Création du "papier" et du "crayon"
crayon = turtle.Turtle()
papier = turtle.Screen()
# Taille, dimension et couleur pour le papier et le crayon
papier.bgcolor("beige")
papier.setup(width=500,height=500)
crayon.color("navy")
crayon.pensize(5)
# Tracé d'un trait avec les coordonnées des extrémités
crayon.penup()
crayon.goto(-50,-150)
crayon.pendown()
crayon.goto(-50,150)
# Tracé d'un trait en orientant et en faisant avancer la tortue
crayon.penup()
crayon.goto(50,-150)
crayon.pendown()
crayon.setheading(90)
crayon.forward(300)
# Attends un clic pour fermer la fenêtre de dessin
papier.exitonclick()<file_sep>import turtle
# Création du "papier" et du "crayon"
crayon = turtle.Turtle()
papier = turtle.Screen()
# Taille, dimension et couleur pour le papier et le crayon
papier.bgcolor("beige")
papier.setup(width=500,height=500)
crayon.color("navy")
crayon.pensize(5)
# Tracé d'un trait avec les coordonnées des extrémités
crayon.penup()
crayon.goto(-50,-150)
crayon.pendown()
crayon.goto(-50,150)
# Tracé d'un trait en orientant et en faisant avancer la tortue
crayon.penup()
crayon.goto(50,-150)
crayon.pendown()
crayon.setheading(90)
crayon.forward(300)
# Correction question 2 : tracé des traits manquants
crayon.penup()
crayon.goto(-150,-50)
crayon.pendown()
crayon.goto(150,-50)
crayon.penup()
crayon.goto(-150,50)
crayon.pendown()
crayon.goto(150,50)
# Correction question 3 : tracé du cercle
crayon.color("darkred")
crayon.pensize(7)
crayon.penup()
crayon.goto(40,0)
crayon.pendown()
crayon.setheading(90)
crayon.circle(40)
# Attends un clic pour fermer la fenêtre de dessin
papier.exitonclick()<file_sep>def envers(chaine):
resultat = ""
for caractere in chaine:
resultat = caractere + resultat
return resultat
print(envers("super"))<file_sep>
{% set num = 1 %}
{% set titre = "TITRE_CHAPITRE_ICI"%}
{% set theme = "THEME" %}
{{ titre_chapitre(num,titre,theme)}}
## Activités
{{ titre_activite("TITRE_ACTIVITE_1",[],0) }}
CONTENU ACTIVITE 1
{{ titre_activite("TITRE_ACTIVITE_2",[]) }}
CONTENU ACTIVITE 2
...
## Cours
{{ aff_cours(num) }}
## Exercices
{{ exo("TITRE_EXO_1",[],0) }}
CONTENU EXO 1
{{ exo("TITRE_EXO_2",[]) }}
CONTENU EXO 2
{{ exo("TITRE_EXO_3",[]) }}
CONTENU EXO 3<file_sep>
{% set num = 2 %}
{% set titre = "Bases de données et SQL"%}
{% set theme = "db" %}
{{ titre_chapitre(num,titre,theme)}}
## Activités
{{ titre_activite("Un peu d'histoire et de théorie",["video"],0) }}
<div class="centre"><iframe width="560" height="315" src="https://www.youtube.com/embed/pqoIBiM2AvE" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
En utilisant la vidéo ci-dessus et en faisant vos propres recherches sur le *Web*, répondre aux questions suivantes :
1. Quel mathématicien est à l'origine de la théorie des bases de données ? En quelle année ?
2. Avant l'avènement des bases de données, les données étaient stockés sous la forme de simples fichiers, quels étaient les inconvénients de ce fonctionnement ?
3. Que signifie l'*absence de redondance* pour une base de données ?
4. Que signifie l'*indépendance logique* pour une base de données ?
5. Que signifie l'*intégrité* pour une base de données ?
6. Donner les noms de quelques {{ sc("sgbd") }} connus en indiquant s'il s'agit de logiciels libres ou propriétaires.
{{ titre_activite("A la découverte de SQL",[]) }}
## Cours
{{ aff_cours(num) }}
## Exercices
{{ exo("Prix Nobel",[],0) }}
<file_sep>import turtle
#Positionne la tortue en (x,y)
def origine(tortue,x,y):
tortue.penup()
tortue.goto((x,y))
tortue.pendown()
def courbe_koch(tortue,longueur,ordre):
if ordre==0:
tortue.forward(longueur)
else:
ordre=ordre-1
longueur=longueur//3
courbe_koch(tortue,longueur,ordre)
tortue.left(60)
courbe_koch(tortue,longueur,ordre)
tortue.right(120)
courbe_koch(tortue,longueur,ordre)
tortue.left(60)
courbe_koch(tortue,longueur,ordre)
def flocon(tortue,longueur,profondeur):
for _ in range(3):
courbe_koch(tortue,longueur,profondeur)
tortue.right(120)
#On crée une fenêtre et on fixe sa taille
fenetre = turtle.Screen()
fenetre.title("Courbe de Koch")
fenetre.setup(width=600,height=400)
#On crée une tortue (on l'appelle ... caroline)
caroline=turtle.Turtle()
caroline.speed(0)
#Pour dessiner il suffit maintenant de donner des instructions à la tortue : avancer, tourner, ...
origine(caroline,-250,-100)
courbe_koch(caroline,500,4)
#On termine le programme lorsqu'on click sur la fenetre
caroline.hideturtle()
fenetre.exitonclick()
<file_sep>
{% set num = 0 %}
{% set titre = "Révisions"%}
{% set theme = "python" %}
{{ titre_chapitre(num,titre,theme)}}
## Activités
{{ titre_activite("Ligne de commande",[],0) }}
Le but de cette activité est de redécouvrir les bases de la ligne de commande. On utilisera [gameshell](https://github.com/phyver/GameShell){target=_blank}, un mini-jeu d'aventure où les commandes servent à accomplir des missions.
1. Installation de Gameshell :
1. Télécharger le fichier [gameshell](./files/C0/gameshell.sh).
2. Ouvrir l'explorateur de fichier.
3. Créer un répertoire `gameshell` dans votre dossier personnel (en faisant un clic-droit et en sélectionnant *nouveau dossier*)
4. Dans ce répertoire, copier le fichier gameshell que vous avez téléchargé.
4. Faire un clic droit sur le fichier et dans l'onglet permission cocher la case '*Autoriser l'exécution du fichier comme un programme*', comme illustré ci-dessous : {: .imgcentre}
5. Faire un clic droit dans la fenêtre de l'explorateur de fichier et sélectionner "*ouvrir dans un terminal*" comme illustré ci-dessous :{: .imgcentre}
6. Dans le terminal taper :
```bash
./gameshell.sh
```
2. Parallèlement à l'exécution des missions :
* Noter les commandes que vous utilisez et leur signification
* Tenir à jour un plan du monde dans lequel se déroule le jeu
!!! aide "Aide"
Pour la première mission, vous devez donc noter le sens des commandes `cd`, `ls` et `pwd` et commencer le schéma suivant qui sera à poursuivre tout au long des missions :
```mermaid
graph TD
A[Monde] --> B[Chateau]
A --> C[Echoppe]
A --> D[Forêt]
A --> E[Jardin]
A --> F[Montagne]
```
3. L'installation de Gameshell, faite ci-dessus à l'aide de l'interface graphique aurait pu être réalisé en ligne de commande.
1. Quelle commande permet de créer un répertoire `gameshell` dans votre dossier personnel (question *1.c* ci-dessus) ?
2. Quelle commande correspond à la copie du fichier (question *1.d* ci-dessus) ?
3. Quelle commande correspond à la modification des droits d'exécution (question *1.e* ci-dessus) ?
{{ titre_activite("Module `turtle` de Python",[]) }}
Le but de cette activité est de redécouvrir les bases de la programmation en python en utilisant le module `turtle` qui permet de dessiner à l'aide d'une "*tortue*" (équivalente à un crayon) à laquelle on donne des instructions (se déplacer, avancer, tourner, ...) de façon à former le dessin désiré. Cette tortue se déplace sur un écran (équivalent au papier), doté d'un repère comme en mathématiques.
1. Dessiner une grille de morpion <br>
On souhaite dessiner une grille du [jeu de morpion](https://fr.wikipedia.org/wiki/Morpion_(jeu)){target=_blank} comme ci-dessous (où le repère du papier est tracé de façon à connaître les dimensions et positions des traits) :
{: .imgcentre}
1. Recopier et executer le programme suivant :
```python
import turtle
# Création du "papier" et du "crayon"
crayon = turtle.Turtle()
papier = turtle.Screen()
# Taille, dimension et couleur pour le papier et le crayon
papier.bgcolor("beige")
papier.setup(width=500,height=500)
crayon.color("navy")
crayon.pensize(5)
# Tracé d'un trait avec les coordonnées des extrémités
crayon.penup()
crayon.goto(-50,-150)
crayon.pendown()
crayon.goto(-50,150)
# Tracé d'un trait en orientant et en faisant avancer la tortue
crayon.penup()
crayon.goto(50,-150)
crayon.pendown()
crayon.setheading(90)
crayon.forward(300)
# Attends un clic pour fermer la fenêtre de dessin
papier.exitonclick()
```
2. Expliquer le rôle des instructions suivantes :
* `pensize` et `color`
* `penup` et `pendown`
* `goto` et `forward`
* `setheading`
!!! Aide
Vous pouvez modifier les paramètres ou supprimer certaines instructions pour en voir l'effet sur le dessin. Aider vous aussi des commentaires.
3. Compléter ce programme en traçant les deux traits horizontaux manquants afin de compléter le dessin de la grille de morpion.
2. Dessiner en cercle au centre de la grille de morpion (de rayon 40, de couleur `darkred` avec un crayon d'épaisseur 7) de façon à obtenir le dessin final suivant :
{: .imgcentre}
!!! Aide
Utiliser `circle(r)` où `r` est le rayon du cercle à tracer, on fera attention que le centre du cercle se situe toujours à *gauche* de l'orientation de la tortue et à une distance `r` comme représenté ci-dessous :
{: .imgcentre}
{{ titre_activite("De l'utilité des fonctions",[]) }}
!!! Attention
Cette activité est la suite de la précédente, on doit donc déjà disposer d'un programme Python permettant de tracer la grille de morpion ainsi que le cercle central. Même si vous pouvez télécharger ce programme [ici](./files/C0/correction_activite2.py), il est fortement conseillé d'avoir assimilé les notions de l'activité précédente (tracé des lignes et des cercles) avant de continuer.
1. On propose d'écrire une fonction `ligne` permettant de tracer avec la tortue `crayon` un trait en donnant les coordonnées `x1` et `y1` de l'origine et `x2` et `y2` de l'extrémité.
1. Par quel mot clé commence la définition d'une fonction en Python ?
2. Quels seront ici les arguments de la fonction ?
3. Recopier et compléter le code de cette fonction :
``` python
... ligne(..,..,..,..):
crayon....()
crayon....(..,..)
crayon.....()
crayon.....(..,..)
```
4. Ajouter une chaîne de documentation à cette fonction
5. Faire le tracé de la grille de morpion en vous aidant de cette fonction.
6. Que peut-on dire par rapport à version du programme qui n'utilisait pas de fonction ?
2. En vous inspirant de l'exemple précédent, écrire une fonction `ligne2` permettant de tracer un trait en donnant les coordonnées `x` et `y` de son origine, ainsi que sa longueur `l` et sa direction `d` (sous la forme d'un angle).
!!! Aide
On utilisera `forward` pour avancer de la longueur indiquée et `setheading` pour positionner la tortue avec l'orientation désirée.
3. Ecrire une fonction `cercle` permettant de tracer un cercle dont on donne les coordonnées du centre `x` et `y` et le rayon `r`
4. Ecrire une fonction `croix` qui permet de tracer une croix (:fontawesome-solid-times:) en donnant son centre et la longueur des branches.
{{ titre_activite("Une boucle pour répéter",[]) }}
On souhaite dessiner la grille suivante à l'aide du module `turtle` de Python :
{: .imgcentre}
On dispose déjà d'un début de programme qui définit les propriétés du papier et du crayon ainsi que la fonction `ligne` permettant de tracer une ligne en donnant les deux extrémités (voir activités précédentes) :
```python
import turtle
# Création du "papier" et du "crayon"
crayon = turtle.Turtle()
papier = turtle.Screen()
# Taille, dimension et couleur pour le papier et le crayon
papier.bgcolor("beige")
papier.setup(width=500,height=500)
crayon.color("navy")
crayon.pensize(5)
def ligne(x1,y1,x2,y2):
crayon.penup()
crayon.goto(x1,y1)
crayon.pendown()
crayon.goto(x2,y2)
```
1. Écrire les instructions permettant de tracer les lignes horizontales.
2. Une (bien) meilleure solution
1. Vérifier que les instructions suivantes permettent de tracer les lignes verticales :
```python
for abscisse in range(-200,250,50):
ligne(abscisse,-200,abscisse,200)
```
2. Quelles sont les valeurs prises successives prises par la variable `abscisse` dans le programme précédant ?
3. Rappeler le rôle des paramètres de `range`
{{ titre_activite("Instructions conditionnelles",[]) }}
On souhaite dessiner la figure suivante à l'aide du module `turtle` de Python :
{: .imgcentre}
1. Ecrire une fonction `carre(x,y,c)` qui trace le carré de côté `c` dont le coin inférieur gauche a pour coordonnées `(x,y)`.
2. Ecrire une boucle à l'aide d'une instruction `for ... in range(....):` de façon à tracer la suite de carré bleu.
3. Ajouter une instruction conditionnelle dans la boucle de façon à ce que le septième carré soit tracé en rouge et avec un crayon plus épais comme sur la figure.
!!! Rappel
On rappelle que la syntaxe d'une instruction conditionnelle est :
```python
if <condition>:
<instructions1>
else:
<instructions2>
```
{{ titre_activite("Le problème de Josephus",["video"]) }}
<div class="centre"><iframe width="560" height="315" src="https://www.youtube.com/embed/uCsD3ZGzMgE" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
Le but de l'activité est d'écrire un programme permettant de résoudre le [problème de Joséphus](https://fr.wikipedia.org/wiki/Probl%C3%A8me_de_Jos%C3%A8phe){target=_blank} en révisant les listes de Python.
1. On représente un cercle de `n` soldats par la liste `[1,2,...,n]`
1. Ecrire une fonction `soldats(n)` qui renvoie la liste `[1,2,....,n]`
2. Verifier que `n` est bien un entier strictement positif à l'aide d'instruction `assert`
3. Ajouter une chaîne documentation.
2. Afin de repérer l'épée, on décide que le soldat qui la tient se situe *toujours en première position de la liste*.
1. Compléter l'évolution de la liste de soldat ci-dessous
| Etat de la liste | Explications |
|------------------|--------------|
|[==1==,~~2~~,3,4,5,6] | `1` élimine `2` et passe l'épée à `3` qui passe donc en tête de liste |
|[==3==,...,5,6,1] | `3` élimine `...` et passe l'épée à `...` qui passe donc en tête de liste |
|[==...==,~~6~~,1,3] | `...` élimine `...` et passe l'épée à `...` qui passe donc en tête de liste |
|[...,...,...] | ..... |
|[...,...] | ..... |
|[...] | ..... |
2. Compléter l'algorithme suivant d'évolution de la liste et indiquer les instructions Python correspondantes (on désigne par `cercle` la liste représentant le cercle de soldats):
|Etapes | Opération sur la liste | Instructions Python |
|-|------------------------|---------------------|
|:one:| .......... | `tueur=cercle.pop(0)`
|:two:| Ajouter cet élément en fin de liste| ...... |
|:three:| Supprimer le premier élément | ...... |
3. Quel est la condition d'arrêt de l'algorithme ?
4. Exprimer cette condition par un test en python sur `cercle`
3. Programmer une fonction `josephus(n)` qui renvoie le soldat survivant pour un cercle de `n` soldats.
## Cours
{{ aff_cours(num) }}
## Exercices
{{ exo("Les bases de la ligne de commande",[],0) }}
1. En utilisant uniquement la ligne de commande, créer l'arborescence suivante dans votre répertoire personnel :
```mermaid
graph TD
A[Cours] --> B[C0-Révisions]
A[Cours] --> G[C1-Récursivité]
B --> C[Exercices]
B --> D[Activités]
B --> E[Notes]
B --> F[Python]
```
2. Renommer le dossier `Cours` en `NSI`
3. Créer un fichier vide `exercice2.txt` dans le dossier `Exercices`
{{ exo("Quelques commandes",[]) }}
1. **Sans les tester**, écrire dans le fichier `exercice2.txt` crée à l'exercice précédent l'effet des commandes suivantes :
* `cd ~`
* `mkdir Partage`
* `chmod a+rwx Partage`
* `cd Partage`
* `touch hello.txt`
* `echo "Salut tout le monde" > hello.txt`
* `cat hello.txt`
2. Taper ces commandes pour vérifier vos précisions.
{{ exo("Arborescence",[]) }}
1. Rechercher l'aide de la commande `tree`, quel est l'effet de cette commande ?
2. Afficher l'arborescence de votre répertoire personnel
3. Afficher l'arborescence de la racine *en limitant à un la profondeur*
4. Rechercher sur le *Web* le rôle des dossiers suivants :
* `/etc`
* `/home`
* `/dev`
* `/tmp`
!!! Aide
Pour les exercices avec `turtle`, on peut consulter [la page de documentation officielle du module](https://docs.python.org/fr/3/library/turtle.html){target=_blank}
{{ exo("Figures géométriques avec Turtle",[]) }}
1. Ecrire une fonction `rectangle(x,y,l1,l2)` qui trace le rectangle de dimensions `l1` $\times$ `l2` et dont le coin inférieur gauche à pour coordonnées `x` et `y`.
2. On peut remplir une surface construite avec un `crayon` du module `turtle` :
* Spécifier une couleur de remplissage par exemple `crayon.fillcolor(red)`
* Au début du tracé de la figure écrire l'instruction `crayon.begin_fill()`
* A la fin du tracé de la figure écrire l'instruction `crayon.end_fill()`
Modifier votre fonction rectangle de façon à pouvoir tracer un rectangle rempli avec une couleur passée en paramètre.
{{ exo("Quelques figures avec `turtle`",[]) }}
Construire les figures suivantes (le repère est là pour vous aider et ne dois pas être reproduit):
1. L'escalier
{: .imgcentre}
2. Cercles concentriques (les couleurs alternent entre `blue` et `lightblue`, le crayon a une épaisseur de 10, les cercles ont pour rayon 10,20,30, ...)
{: .imgcentre}
{{ exo("Polygone régulier",["maths"]) }}
1. Ecrire une fonction `triangle_equilateral(c)` qui trace un triangle équilatéral de côte `c` à partir de la position courante de la tortue.
2. Ecrire une fonction `carre(c)` qui trace un carré de côte `c` à partir de la position courante de la tortue.
3. Ecrire une fonction `polygone_regulier(n,c)` qui trace un polygone régulier de côte `c` à partir de la position courante de la tortue.
!!! Rappel
* Un polygone régulier est un polygone dont tous les côtés sont de la même longueur et tous les angles sont égaux.
* Les angles d'un polygone régulier à $n$ côtés mesurent $\dfrac{360}{n}$
{{ exo("Panneau de signalisation",[]) }}
Ecrire un programme Python permettant de dessiner le panneau de signalisation de votre choix. Quelques exemples sont proposés ci-dessous.<br>
{width=150px}
{width=150px}
{width=150px}
{width=150px} <file_sep>def fibonnaci(n):
if n<2:
return n
else:
return fibonnaci(n-1)+fibonnaci(n-2)
print(fibonnaci(10))<file_sep>import turtle
import grille
papier = turtle.Screen()
crayon = turtle.Turtle()
papier.setup(width=500,height=500)
#a.trace()
papier.update()
grille.set_crayon(grille.Axe.tortue_axe,couleur="darkgray")
grille.set_crayon(grille.Graduation.tortue_graduation,couleur="darkgray")
grille.set_crayon(grille.Pattern.tortue_pattern,couleur="darkgray")
p = grille.Pattern(20,(' ','-'),(90,10))
g = grille.Grille(50,p,50,p)
g.trace()
a = grille.Axe()
a.trace()
grad = grille.Graduation(50,20,label=("Arial",14,"normal"))
grad.affiche()
grad2 =grille.Graduation(10,5,sub=5,show_label=False)
grad2.affiche()
papier.bgcolor('beige')
papier.title('morpion')
grille.set_crayon(crayon,epaisseur=5,couleur="navy")
grille.ligne_bis(crayon,-50,-150,-50,150)
grille.ligne_bis(crayon,50,-150,50,150)
grille.ligne_bis(crayon,-150,-50,150,-50)
grille.ligne_bis(crayon,-150,50,150,50)
grille.set_crayon(crayon,epaisseur=7,couleur="darkred")
crayon.penup()
crayon.goto(0,-40)
crayon.pendown()
crayon.setheading(0)
crayon.circle(40)
papier.update()
filename = input("Entrer le nom du fichier de sauvegarde : ")
papier.getcanvas().postscript(file=filename)
<file_sep>def est_pair(n):
''' Renvoie True ou False suivant que n est pair ou non'''
assert type(n)==int, "le paramètre n'est pas un nombre entier"
return n%2==0
print(est_pair(14))<file_sep># Cours de NSI en Terminale du lycée Hintermann-Afféjee
## Liste des chapitres
{{ affiche_progression() }}
## Thèmes traités sur l'année :
{{ sec_titre("histoire","Histoire de l'informatique")}}
{{ sec_titre("projet","Projet")}}
## Système d'exploitation
Ce cours est construit pour être utilisé **en classe**, les élèves disposent d'un ordinateur fonctionnant sous [Ubuntu](https://www.ubuntu.com){target=_blank}.
## Applications
Les applications suivants sont utilisés dans le cours, leur compatibilité avec les systèmes d'exploitation est indiqué.
| Applications | {{ sc("gnu")}}/Linux | Windows | MacOS |
| ----------|----------------------|------------|----------|
| [Python](../install) | {{ ok() }} | {{ ok() }} | {{ ok() }} |
| Jupyter | {{ ok() }} | {{ ok() }} | {{ ok() }} |
| Filius | {{ ok() }} | {{ ok() }} | {{ ok() }} |
| Gameshell | {{ ok() }} | {{ nok() }} | {{ ok() }} |
--8<-- "includes/glossaire.md"<file_sep>import turtle
import grille
papier = turtle.Screen()
crayon = turtle.Turtle()
papier.setup(width=500,height=500)
papier.bgcolor("white")
#a.trace()
papier.update()
grille.set_crayon(grille.Axe.tortue_axe,couleur="darkgray")
grille.set_crayon(grille.Graduation.tortue_graduation,couleur="darkgray")
grille.set_crayon(grille.Pattern.tortue_pattern,couleur="darkgray")
p = grille.Pattern(20,(' ','-'),(90,10))
g = grille.Grille(50,p,50,p)
a = grille.Axe()
grad = grille.Graduation(50,20,label=("Arial",14,"normal"))
grad2 =grille.Graduation(10,5,sub=5,show_label=False)
#grad.affiche()
#grad2.affiche()
#g.trace()
#a.trace()
papier.title('Spirale')
grille.set_crayon(crayon,epaisseur=1,couleur="black")
taille = 200
while taille>10:
for _ in range(4):
crayon.forward(taille)
crayon.left(90)
crayon.left(20)
taille=taille*0.9
papier.update()
filename = input("Entrer le nom du fichier de sauvegarde : ")
papier.getcanvas().postscript(file=filename)
<file_sep>import turtle
import grille
papier = turtle.Screen()
crayon = turtle.Turtle()
papier.setup(width=500,height=500)
#a.trace()
papier.update()
grille.set_crayon(grille.Axe.tortue_axe,couleur="darkgray")
grille.set_crayon(grille.Graduation.tortue_graduation,couleur="darkgray")
grille.set_crayon(grille.Pattern.tortue_pattern,couleur="darkgray")
p = grille.Pattern(20,(' ','-'),(90,10))
g = grille.Grille(50,p,50,p)
g.trace()
a = grille.Axe()
a.trace()
grad = grille.Graduation(50,20,label=("Arial",14,"normal"))
grad.affiche()
grad2 =grille.Graduation(10,5,sub=5,show_label=False)
grad2.affiche()
papier.bgcolor('white')
papier.title('Carrés')
grille.set_crayon(crayon,epaisseur=2,couleur="navy")
for l in range(-200,250,50):
if l==100:
grille.set_crayon(crayon,epaisseur=4,couleur="darkred")
else:
grille.set_crayon(crayon,epaisseur=2,couleur="navy")
grille.rectangle(crayon,l,l,40,40)
papier.update()
filename = input("Entrer le nom du fichier de sauvegarde : ")
papier.getcanvas().postscript(file=filename)
<file_sep>import turtle
def origine(tortue,x,y):
tortue.penup()
tortue.goto(x,y)
tortue.pendown()
def ecrit(tortue,x,y,texte,fonte,alig="center"):
origine(tortue,x,y)
tortue.write(texte,font=fonte,align=alig)
def ligne_bis(tortue,x1,y1,x2,y2):
origine(tortue,x1,y1)
tortue.goto(x2,y2)
def ligne(tortue,x,y,l,angle):
'''Trace le segment de droite d'origne (x,y) et de longueur l dans la direction angle'''
origine(tortue,x,y)
tortue.setheading(angle)
tortue.forward(l)
def rectangle(tortue,x,y,lx,ly):
origine(tortue,x,y)
tortue.begin_fill()
for _ in range(2):
tortue.forward(lx)
tortue.left(90)
tortue.forward(ly)
tortue.left(90)
tortue.end_fill()
def cercle(tortue,x,y,r,angle=360):
origine(tortue,x+r,y)
tortue.setheading(90)
tortue.pendown()
tortue.begin_fill()
tortue.circle(r)
tortue.end_fill()
def set_crayon(tortue,epaisseur=1,couleur="black",remplissage="white",visible=False):
tortue.pensize(epaisseur)
tortue.color(couleur)
tortue.fillcolor(remplissage)
if visible:
tortue.showturtle()
else:
tortue.hideturtle()
class Pattern:
tortue_pattern = turtle.Turtle()
tortue_pattern.hideturtle()
tortue_pattern.speed(0)
tortue_pattern.getscreen().tracer(400)
def __init__(self,size,formes,longueur):
self.size = size
self.formes = formes
self.longueur = longueur
self.nb = len(formes)
def dessine(self,ox,oy,l,a):
origine(Pattern.tortue_pattern,ox,oy)
Pattern.tortue_pattern.setheading(a)
k = 0
while l > k*self.size:
for ind in range(self.nb):
# '-' = Trait continu
if self.formes[ind]=='-':
Pattern.tortue_pattern.forward(self.size*self.longueur[ind]/100)
# '.' = Dot
if self.formes[ind]=='.':
Pattern.tortue_pattern.right(90)
Pattern.tortue_pattern.circle(self.size//2*self.longueur[ind]/100)
Pattern.tortue_pattern.left(90)
Pattern.tortue_pattern.penup()
Pattern.tortue_pattern.forward(self.size*self.longueur[ind]/100)
Pattern.tortue_pattern.pendown()
# ' ' = Espaces
if self.formes[ind]==" ":
Pattern.tortue_pattern.penup()
Pattern.tortue_pattern.forward(self.size*self.longueur[ind]/100)
Pattern.tortue_pattern.pendown()
k=k+1
class Grille:
def __init__(self,xgrad,xpattern,ygrad,ypattern):
self.xgrad = xgrad
self.ygrad = ygrad
self.xpattern = xpattern
self.ypattern = ypattern
def trace(self):
# Récupération taille du papier
hauteur = turtle.window_height()
largeur = turtle.window_width()
for x in range(0,largeur//2,self.xgrad):
self.ypattern.dessine(x,-hauteur//2,hauteur,90)
self.ypattern.dessine(-x,-hauteur//2,hauteur,90)
for y in range(0,hauteur//2,self.ygrad):
self.ypattern.dessine(-largeur//2,y,largeur,0)
self.ypattern.dessine(-largeur//2,-y,largeur,0)
class Graduation:
tortue_graduation = turtle.Turtle()
tortue_graduation.hideturtle()
tortue_graduation.speed(0)
tortue_graduation.getscreen().tracer(400)
def __init__(self,pas,tick,sub=False,show_label=True,label=("Courier",10,"normal"),offset = 15):
self.pas = pas
self.tick = tick
self.sub = sub
self.show_label = show_label
self.label = label
self.offset = offset
def affiche(self):
# Récupération taille du papier
hauteur = turtle.window_height()
largeur = turtle.window_width()
for x in range(self.pas,largeur//2,self.pas):
if not self.sub or (x//self.pas)%self.sub != 0:
ligne(Graduation.tortue_graduation, x, -self.tick//2,self.tick,90)
ligne(Graduation.tortue_graduation, -x, -self.tick//2,self.tick,90)
if self.show_label:
ecrit(Graduation.tortue_graduation,x,-self.tick//2-self.offset,x,self.label)
ecrit(Graduation.tortue_graduation,-x,-self.tick//2-self.offset,-x,self.label)
for y in range(self.pas,hauteur//2,self.pas):
if not self.sub or (y//self.pas)%self.sub != 0:
ligne(Graduation.tortue_graduation, -self.tick//2, y,self.tick,0)
ligne(Graduation.tortue_graduation, -self.tick//2, -y,self.tick,0)
if self.show_label:
ecrit(Graduation.tortue_graduation,-self.tick//2-self.offset,y-self.label[1],y,self.label)
ecrit(Graduation.tortue_graduation,-self.tick//2-self.offset,-y-self.label[1],-y,self.label)
class Axe:
tortue_axe = turtle.Turtle()
tortue_axe.hideturtle()
tortue_axe.speed(0)
tortue_axe.getscreen().tracer(400)
def __init__(self):
self.hauteur=None
self.largeur=None
def trace(self):
# Récupération taille du papier
self.hauteur = turtle.window_height()
self.largeur = turtle.window_width()
xstampsize = Axe.tortue_axe.shapesize()[0] * 5
ystampsize = 0
ligne(Axe.tortue_axe,-self.largeur//2,0,self.largeur-xstampsize,0)
Axe.tortue_axe.stamp()
ligne(Axe.tortue_axe,0,-self.hauteur//2,self.hauteur-ystampsize,90)
Axe.tortue_axe.stamp()
def taille_fleche(self,sizex,sizey):
Axe.tortue_axe.shapesize(sizex,sizey)
<file_sep>
{% set num = 1 %}
{% set titre = "Récursivité"%}
{% set theme = "python" %}
{{ titre_chapitre(num,titre,theme)}}
## Activités
{{ titre_activite("A la découverte de la récursivité",[],0) }}
1. Ecrire un programme Python permettant de tracer la spirale de carré suivante sachant que :
* Le côté du grand carré initial mesure 200 pixels
* Le coin inférieur gauche des carrés est l'origine du repère
* A chaque étape les carrés tournent de 20°
* A chaque étape la côté du carré diminue de 10% de sa longueur.
* On interrompt la construction lorsque la taille est inférieure ou égale à 10 pixels
{: .imgcentre}
2. Pour réaliser le dessin ci-dessus vous avez probablement utilisé une boucle, votre programme est dit **itératif**. Remarquons à présent que cette spirale peut se décomposer en un premier carré (en trait épais ci dessous), suivi d'une spirale de carrés (en gris et traits fin ci-dessous) :
{: .imgcentre}
On pourrait donc définir qu'une spirale est constitué (compléter):
* :one: d'un .....
* :two: et d'une ........... plus petite !
La particularité de ce type de définition est de faire appel à elle-même, on, dit qu'elle est **récursive**.
1. Construction récursive d'une spirale.
1. En utilisant la définition précédente, compléter le code de la fonction Python suivant :
```python
def spirale_recursive(tortue,taille):
# Un carré
carre(tortue,taille)
# Et une spirale plus petite
tortue.left(....)
taille = .......
spirale_recursive(tortue,taille)
```
2. Quelle est la particularité de cette fonction ?
3. Que se passe-t-il à l'exécution ? Pourquoi ?
4. Modifier la définition de cette fonction en introduisant la condition d'arrêt (`taille<=10`)
2. Proposer une définition récursive d'un escalier, en déduire une construction récursive de la figure suivante :
{: .imgcentre}
{{ titre_activite("D'autres exemples de récursivité",[]) }}
1. Somme des `n` premiers entiers
1. Ecrire une fonction python `somme(n)` itérative qui calcule la somme des `n` premiers entiers. Par exemple `somme(5)` renvoie `15` puisque `1+2+3+4+5=15`.
2. Compléter l'égalité mathématique suivante entre `somme(n)` et `somme(n-1)` : <br>
`somme(n) = somme(n-1) + ... `
3. En déduire une version itérative de la fonction `somme(n)`
2. Écrire à l'envers
1. Compléter puis tester le code de la fonction Python ci-dessous qui prend en argument une chaine de caractère et la renvoie écrite à l'envers
```python
def envers(chaine):
resultat = ""
for caractere in .....:
resultat = ...... + resultat
return .....
```
2. On décompose une `chaine` en `chaine = debut + dernier caractère`, compléter la définition récursive suivante :
`envers(chaine) = .......... + envers(.......)`
3. En déduire une version récursive de la fonction `envers`
!!! Aide
On pourra écrire au préalable une fonction `debut(chaine)` qui renvoie la chaine privée de son dernier caractère. On rapelle que le dernier caractère de `chaine` s'obtient avec `chaine[-1]`.
{{ titre_activite("Soulever le capot de la récursivité",[]) }}
1. Se rendre sur le site [Python tutor](http://www.pythontutor.com/visualize.html){target=_blank}, un outil en ligne permettant de visualiser le fonctionnement d'un programme Python. Laisser les options par défaut à l'exception de `inline primitives don't nest objects [default]` ) à remplacer par `render all objects on the heap (Python/Java)` comme ci-dessous :
{: .imgcentre}
2. Entrer sur Python tutor le code de fonction `somme(n)` itérative, qu'on teste avec `n=5` :
```python
def somme(n):
s = 0
for i in range(n):
s+=i
return s
test = somme(5)
```
Suivre l'exécution pas à pas du calcul.
3. Faire de même mais avec la fonction `somme_recursive(n)` :
```python
def somme_recursive(n):
if n==0:
return 0
else:
return n + somme_recursive(n-1)
test = somme_recursive(5)
```
4. La figure suivante représente une étape de l'exécution. Comment expliquer que les entiers sont "stockés" à droite mais qu'aucun calcul n'a encore été effectué ?
{: .imgcentre}
5. La colonne de droite où sont stockés les entiers s'appelle une **pile**, (*heap* en anglais). La taille maximale de cette pile est la profondeur maximale de récursion (*recursion depth*). Quitter Python Tutor et tester la fonction `somme_recursive` avec une valeur élevée de `n` (par exemple `n=3000`). Que se passe-t-il ? Expliquer.
6. La version itérative est-elle concernée par ce problème ?
## Cours
{{ aff_cours(num) }}
## Exercices
{{ exo("Factorielle",["maths"],0) }}
En mathématiques, on appel *factorielle* d'un entier $n$ et on $n!$ le produit de cet entier par tous ceux qui le précèdent à l'exception de zéro. On convient d'autre part que $0!=1$. Par exemple, <br>
$5! = 5 \times 4 \times 3 \times 2 \times 1 = 120$.
1. Programmer une version itérative d'une fonction `factorielle(n)` qui renvoie factorielle de l'entier positif `n` passé en argument.
2. Recopier et compléter : <br>
$n! = n\times \underbrace{(n-1) \times \dots \times 1}_{...}$ <br>
$n! = n \times \dots$
3. En déduire une version récursive de la fonction `factorielle(n)`.
{{ exo("Analyser un programme récursif",[]) }}
On considère la fonction `mystere` ci-dessous :
```python
def mystere(liste):
if len(liste)==1:
return liste[0]
else:
if liste[0]<liste[1]:
liste.pop(1)
else:
liste.pop(0)
return mystere(liste)
```
1. Analyser ce programme, en déduire le rôle de cette fonction.
!!! aide
Faire fonctionner "à la main" ce programme sur une liste de petite taille, revoir le rôle de `pop` si nécessaire.
2. Donner une version itérative de cette fonction
{{ exo("Comprendre un programme récursif",[]) }}
On donne le code incomplet d'une fonction récursive permettant de calculer le produit de deux entiers positifs `a` et `b` en effectuant uniquement des additions :
```python
def produit(a,b):
if b==...:
return ...
else:
return ...+produit(...,...)
```
1. Compléter les égalités suivantes :
* $a \times 0 = \dots$
* $a \times b = a + a \times (\dots \dots)$
2. Compléter le code de la fonction ci-dessus et la tester
3. Que se passe-t-il si on choisit une valeur assez grande pour `b`, par exemple 5000 ? Pourquoi ? En est-il de même pour de grandes valeurs de `a` ? Pourquoi ?
4. Améliorer le code de cette fonction de façon à ce que le dépassement de pile de récursion n'arrive que lorsque `a` et `b` sont tous deux supérieurs à la taille maximale.
{{ exo("Additions et soustractions",[]) }}
On suppose qu'on ne dispose que de deux opérations : ajouter 1 ou retrancher 1.
1. Écrire à l'aide de ces deux opérations, une version itérative de l'addition de deux entiers.
2. Même question avec une version itérative.
{{ exo("Dessin récursif",[]) }}
1. Dessiner une suite de carré imbriqués comme ci-dessous (la carré initial mesure 200 pixels et diminue de 20 pixels à chaque carré suivant)
{: .imgcentre}
2. Si vous aviez donné une version itérative de ce dessin, en faire une version récursive et inversement.
{{ exo("Comparaison de deux chaines de caractères",[]) }}
1. Ecrire de façon itérative, une fonction `compare(chaine1,chaine2)` qui renvoie le nombre de fois où `chaine1` et `chaine2` ont le même caractère au même emplacement. A titre d'exemples :
* `compare("recursif","iteratif")` renvoie 2,
* `compare("Python","Javascript")` renvoie 0.
2. Écrire cette même fonction de façon récursive.
!!! aide
Vous aurez peut être besoin d'une fonction `reste(chaine)` qui renvoie la chaine passée en paramètre privée de son premier élément. Par exemple `reste("python")` renvoie `ython`. Ecrire vous même cette fonction, ou chercher comment utiliser les *slices* de Python.
{{ exo("Recherche dichotomique dans un tableau trié",["rappel"]) }}
1. Rappeler l'algorithme de recherche dichotomique dans un tableau trié vu en classe de première et donner son fonctionnement sur un exemple simple.
!!! aide
Voir [cette page](https://fabricenativel.github.io/NSIPremiere/notionsalgo/#activite-2-recherche-dichotomique){taget=_blank} du cours de première.
2. Coder cet algorithme de façon itérative
3. Coder cet algorithme de façon récursive
{{ exo("<NAME> <NAME>",["dur"]) }}
La courbe de Koch est une figure qui se construit de manière récursive. Le cas de base (ordre 0) s'obtient en traçant un segment de longueur $l$. Le cas récursif d'ordre $n>0$ s'obtient en effectuant les transformations suivantes :
|Etape | Illustration | Commentaire |
|------|--------------|-------------|
|:one: |{width=400px} | Partager le segment en trois morceaux de longueur égale |
|:two: |{width=400px} | Construire un triangle équilatéral à partir du segment du milieu |
|:three: |{width=400px} | Supprimer le segment du milieu |
On a écrit une fonction `courbe_koch` permettant de tracer à l'aide du module turtle de Python la courbe de Koch en donnant en paramètre la longueur initiale du segment et l'ordre. On donne ci-dessous ce code incomplet :
```python
def courbe_koch(tortue,longueur,ordre):
if ........
........
else:
ordre=........
longueur=........
courbe_koch(tortue,longueur,ordre)
.................
courbe_koch(tortue,longueur,ordre)
................
courbe_koch(tortue,longueur,ordre)
................
courbe_koch(tortue,longueur,ordre)
```
1. Compléter et tester ce code pour tracer une courbe de Koch d'ordre 4. Vous devriez obtenir une figure similaire à celle représentée ci-dessous :
{: .imgcentre}
2. En utilisant cette fonction construire le [flocon de Koch](https://fr.wikipedia.org/wiki/Flocon_de_Koch){target=_blank}, c'est à dire la figure obtenu en construisant les courbe de Koch sur les trois côtés d'un triangle équilatéral.
3. Le flocon de Koch est un exemple classique de courbe *fractale*, construire un autre exemple de fractale : [le triangle de Sierpinski](https://fr.wikipedia.org/wiki/Triangle_de_Sierpi%C5%84ski){target=_blank}.
{{ exo("Algorithme d'Euclide de calcul du pgcd",["rappel","maths"]) }}
1. Faites des recherches sur [l'algorithme d'Euclide](https://fr.wikipedia.org/wiki/Algorithme_d%27Euclide){target=_blank}.
1. Que permet de faire cet algorithme ?
2. Faire fonctionner cet algorithme à la main avec les valeurs suivantes en donnant les étapes:
* $a=48$ et $b=36$
* $a=13$ et $b=9$
2. Rappeler les instructions Python permettant d'obtenir le reste et le quotient d'une division euclidienne.
3. Donner une implémentation itérative de cet algorithme
4. Donner une implémentation récursive de cet algorithme
{{ exo("Suite de Fibonnaci",["maths"]) }}
La suite de Fibonnaci $(f_n)$ est définie par :
$$\left\{ \begin{array}{lll}
f_0&=&0, \\
f_1&=&1, \\
f_{n}&=&f_{n-1}+f_{n-2} \mathrm{\ \ pour\ tout\ \ } n\geq2. \end{array} \right.$$
C'est à dire que chaque terme de la suite est la somme des deux précédents.
1. Calculer à la main les premières valeurs de cette suite en complétant le tableau suivant :
<table>
<tr> <td>\(\textcolor{darkred}{n}\)</td> <td>0</td> <td>1</td> <td>\(\dots\)</td> <td>\(\dots\)</td> <td>\(\dots\)</td> <td>\(\dots\)</td> <td>\(\dots\)</td> <td>\(\dots\)</td> </tr>
<tr> <td>\(\textcolor{darkred}{f_n}\)</td> <td>0</td> <td>1</td> <td>\(\dots\)</td> <td>\(\dots\)</td> <td>\(\dots\)</td> <td>\(\dots\)</td> <td>\(\dots\)</td> <td>\(\dots\)</td> </tr>
</table>
2. Compléter le code suivant permettant de calculer les termes de cette suite :
```python
def fibonnaci(n):
if n<2:
return ....
else:
return ........+............
```
3. Tester cette fonction en écrivant une boucle qui écrit les termes de la suite de Fibonnaci pour les entiers de 1 à 50.
4. Que remarquez-vous ?
5. Recopier et compléter le schéma suivant qui montre les appels récursifs nécessaires au calcul de $f_5$.
```mermaid
graph TD
f5[f5] --> f4[f4]
f5 --> f3[f3]
f4 --> f32[f3]
f4 --> f2[...]
f3 --> f33[...]
f3 --> f34[...]
```
6. En déduire une explication de la lenteur observée à la question 4.
7. Proposer une version itérative du calcul du énième terme de la suite de Fibonnaci.
!!! lien "Pour aller plus loin"
La vidéo suivante (en anglais) reprend ce problème et propose une solution pour coder un algorithme plus efficace
<div class="centre"><iframe width="560" height="315" src="https://www.youtube.com/embed/Qk0zUZW-U_M" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe></div>
|
e8b68d5d99f30c723b27a289ef49ad9e2e980780
|
[
"Markdown",
"Python"
] | 18
|
Python
|
sebhoa/NSITerminale
|
369929362fc61c8a9d5b6463ab60e14b0b281a19
|
a9682a0894f94f5a0a6974653e5437541ffc8821
|
refs/heads/master
|
<file_sep>/**
* Copyright 2016 Smart Society Services B.V.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*/
package com.alliander.osgp.simulator.protocol.iec61850.server.logicaldevices;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import org.openmuc.openiec61850.BasicDataAttribute;
import org.openmuc.openiec61850.Fc;
import org.openmuc.openiec61850.ServerModel;
import com.alliander.osgp.simulator.protocol.iec61850.server.QualityType;
public class Battery extends LogicalDevice {
private static final String DSCH1_SCHDID_SETVAL = "DSCH1.SchdId.setVal";
private static final String DSCH1_SCHDTYP_SETVAL = "DSCH1.SchdTyp.setVal";
private static final String DSCH1_SCHDCAT_SETVAL = "DSCH1.SchCat.setVal";
private static final String DSCH1_SCHDABSTM_VAL_0 = "DSCH1.SchdAbsTm.val.0";
private static final String DSCH1_SCHDABSTM_TIME_0 = "DSCH1.SchdAbsTm.time.0";
private static final String DSCH1_SCHDABSTM_VAL_1 = "DSCH1.SchdAbsTm.val.1";
private static final String DSCH1_SCHDABSTM_TIME_1 = "DSCH1.SchdAbsTm.time.1";
private static final String DSCH1_SCHDABSTM_VAL_2 = "DSCH1.SchdAbsTm.val.2";
private static final String DSCH1_SCHDABSTM_TIME_2 = "DSCH1.SchdAbsTm.time.2";
private static final String DSCH1_SCHDABSTM_VAL_3 = "DSCH1.SchdAbsTm.val.3";
private static final String DSCH1_SCHDABSTM_TIME_3 = "DSCH1.SchdAbsTm.time.3";
private static final String DSCH2_SCHDID_SETVAL = "DSCH2.SchdId.setVal";
private static final String DSCH2_SCHDTYP_SETVAL = "DSCH2.SchdTyp.setVal";
private static final String DSCH2_SCHDCAT_SETVAL = "DSCH2.SchCat.setVal";
private static final String DSCH2_SCHDABSTM_VAL_0 = "DSCH2.SchdAbsTm.val.0";
private static final String DSCH2_SCHDABSTM_TIME_0 = "DSCH2.SchdAbsTm.time.0";
private static final String DSCH2_SCHDABSTM_VAL_1 = "DSCH2.SchdAbsTm.val.1";
private static final String DSCH2_SCHDABSTM_TIME_1 = "DSCH2.SchdAbsTm.time.1";
private static final String DSCH2_SCHDABSTM_VAL_2 = "DSCH2.SchdAbsTm.val.2";
private static final String DSCH2_SCHDABSTM_TIME_2 = "DSCH2.SchdAbsTm.time.2";
private static final String DSCH2_SCHDABSTM_VAL_3 = "DSCH2.SchdAbsTm.val.3";
private static final String DSCH2_SCHDABSTM_TIME_3 = "DSCH2.SchdAbsTm.time.3";
private static final String DSCH3_SCHDID_SETVAL = "DSCH3.SchdId.setVal";
private static final String DSCH3_SCHDTYP_SETVAL = "DSCH3.SchdTyp.setVal";
private static final String DSCH3_SCHDCAT_SETVAL = "DSCH3.SchCat.setVal";
private static final String DSCH3_SCHDABSTM_VAL_0 = "DSCH3.SchdAbsTm.val.0";
private static final String DSCH3_SCHDABSTM_TIME_0 = "DSCH3.SchdAbsTm.time.0";
private static final String DSCH3_SCHDABSTM_VAL_1 = "DSCH3.SchdAbsTm.val.1";
private static final String DSCH3_SCHDABSTM_TIME_1 = "DSCH3.SchdAbsTm.time.1";
private static final String DSCH3_SCHDABSTM_VAL_2 = "DSCH3.SchdAbsTm.val.2";
private static final String DSCH3_SCHDABSTM_TIME_2 = "DSCH3.SchdAbsTm.time.2";
private static final String DSCH3_SCHDABSTM_VAL_3 = "DSCH3.SchdAbsTm.val.3";
private static final String DSCH3_SCHDABSTM_TIME_3 = "DSCH3.SchdAbsTm.time.3";
private static final String DSCH4_SCHDID_SETVAL = "DSCH4.SchdId.setVal";
private static final String DSCH4_SCHDTYP_SETVAL = "DSCH4.SchdTyp.setVal";
private static final String DSCH4_SCHDCAT_SETVAL = "DSCH4.SchCat.setVal";
private static final String DSCH4_SCHDABSTM_VAL_0 = "DSCH4.SchdAbsTm.val.0";
private static final String DSCH4_SCHDABSTM_TIME_0 = "DSCH4.SchdAbsTm.time.0";
private static final String DSCH4_SCHDABSTM_VAL_1 = "DSCH4.SchdAbsTm.val.1";
private static final String DSCH4_SCHDABSTM_TIME_1 = "DSCH4.SchdAbsTm.time.1";
private static final String DSCH4_SCHDABSTM_VAL_2 = "DSCH4.SchdAbsTm.val.2";
private static final String DSCH4_SCHDABSTM_TIME_2 = "DSCH4.SchdAbsTm.time.2";
private static final String DSCH4_SCHDABSTM_VAL_3 = "DSCH4.SchdAbsTm.val.3";
private static final String DSCH4_SCHDABSTM_TIME_3 = "DSCH4.SchdAbsTm.time.3";
private static final String LLN0_HEALTH_STVAL = "LLN0.Health.stVal";
private static final String LLN0_HEALTH_Q = "LLN0.Health.q";
private static final String LLN0_HEALTH_T = "LLN0.Health.t";
private static final String LLN0_BEH_STVAL = "LLN0.Beh.stVal";
private static final String LLN0_BEH_Q = "LLN0.Beh.q";
private static final String LLN0_BEH_T = "LLN0.Beh.t";
private static final String LLN0_MOD_STVAL = "LLN0.Mod.stVal";
private static final String LLN0_MOD_Q = "LLN0.Mod.q";
private static final String LLN0_MOD_T = "LLN0.Mod.t";
private static final String MMXU1_MAXWPHS_MAG_F = "MMXU1.MaxWPhs.mag.f";
private static final String MMXU1_MAXWPHS_Q = "MMXU1.MaxWPhs.q";
private static final String MMXU1_MAXWPHS_T = "MMXU1.MaxWPhs.t";
private static final String MMXU1_MINWPHS_MAG_F = "MMXU1.MinWPhs.mag.f";
private static final String MMXU1_MINWPHS_Q = "MMXU1.MinWPhs.q";
private static final String MMXU1_MINWPHS_T = "MMXU1.MinWPhs.t";
private static final String MMXU1_TOTW_MAG_F = "MMXU1.TotW.mag.f";
private static final String MMXU1_TOTW_Q = "MMXU1.TotW.q";
private static final String MMXU1_TOTW_T = "MMXU1.TotW.t";
private static final String MMXU1_TOTPF_MAG_F = "MMXU1.TotPF.mag.f";
private static final String MMXU1_TOTPF_Q = "MMXU1.TotPF.q";
private static final String MMXU1_TOTPF_T = "MMXU1.TotPF.t";
private static final String DRCC1_OUTWSET_SUBVAL_F = "DRCC1.OutWSet.subVal.f";
private static final String DRCC1_OUTWSET_SUBQ = "DRCC1.OutWSet.subQ";
private static final String DGEN1_TOTWH_MAG_F = "DGEN1.TotWh.mag.f";
private static final String DGEN1_TOTWH_Q = "DGEN1.TotWh.q";
private static final String DGEN1_TOTWH_T = "DGEN1.TotWh.t";
private static final String DGEN1_GNOPST_STVAL = "DGEN1.GnOpSt.stVal";
private static final String DGEN1_GNOPST_Q = "DGEN1.GnOpSt.q";
private static final String DGEN1_GNOPST_T = "DGEN1.GnOpSt.t";
private static final String DGEN1_OPTMSRS_STVAL = "DGEN1.OpTmsRs.stVal";
private static final String DGEN1_OPTMSRS_Q = "DGEN1.OpTmsRs.q";
private static final String DGEN1_OPTMSRS_T = "DGEN1.OpTmsRs.t";
private static final String GGIO1_ALM1_STVAL = "GGIO1.Alm1.stVal";
private static final String GGIO1_ALM1_Q = "GGIO1.Alm1.q";
private static final String GGIO1_ALM1_T = "GGIO1.Alm1.t";
private static final String GGIO1_ALM2_STVAL = "GGIO1.Alm2.stVal";
private static final String GGIO1_ALM2_Q = "GGIO1.Alm2.q";
private static final String GGIO1_ALM2_T = "GGIO1.Alm2.t";
private static final String GGIO1_ALM3_STVAL = "GGIO1.Alm3.stVal";
private static final String GGIO1_ALM3_Q = "GGIO1.Alm3.q";
private static final String GGIO1_ALM3_T = "GGIO1.Alm3.t";
private static final String GGIO1_ALM4_STVAL = "GGIO1.Alm4.stVal";
private static final String GGIO1_ALM4_Q = "GGIO1.Alm4.q";
private static final String GGIO1_ALM4_T = "GGIO1.Alm4.t";
private static final String GGIO1_INTIN1_STVAL = "GGIO1.IntIn1.stVal";
private static final String GGIO1_INTIN1_Q = "GGIO1.IntIn1.q";
private static final String GGIO1_INTIN1_T = "GGIO1.IntIn1.t";
private static final String GGIO1_INTIN2_STVAL = "GGIO1.IntIn2.stVal";
private static final String GGIO1_INTIN2_Q = "GGIO1.IntIn2.q";
private static final String GGIO1_INTIN2_T = "GGIO1.IntIn2.t";
private static final String GGIO1_WRN1_STVAL = "GGIO1.Wrn1.stVal";
private static final String GGIO1_WRN1_Q = "GGIO1.Wrn1.q";
private static final String GGIO1_WRN1_T = "GGIO1.Wrn1.t";
private static final String GGIO1_WRN2_STVAL = "GGIO1.Wrn2.stVal";
private static final String GGIO1_WRN2_Q = "GGIO1.Wrn2.q";
private static final String GGIO1_WRN2_T = "GGIO1.Wrn2.t";
private static final String GGIO1_WRN3_STVAL = "GGIO1.Wrn3.stVal";
private static final String GGIO1_WRN3_Q = "GGIO1.Wrn3.q";
private static final String GGIO1_WRN3_T = "GGIO1.Wrn3.t";
private static final String GGIO1_WRN4_STVAL = "GGIO1.Wrn4.stVal";
private static final String GGIO1_WRN4_Q = "GGIO1.Wrn4.q";
private static final String GGIO1_WRN4_T = "GGIO1.Wrn4.t";
private static final Set<String> BOOLEAN_NODES = Collections
.unmodifiableSet(new TreeSet<>(Arrays.asList(GGIO1_ALM1_STVAL, GGIO1_ALM2_STVAL, GGIO1_ALM3_STVAL,
GGIO1_ALM4_STVAL, GGIO1_WRN1_STVAL, GGIO1_WRN2_STVAL, GGIO1_WRN3_STVAL, GGIO1_WRN4_STVAL)));
private static final Set<String> FLOAT32_NODES = Collections
.unmodifiableSet(new TreeSet<>(Arrays.asList(MMXU1_MAXWPHS_MAG_F, MMXU1_MINWPHS_MAG_F, MMXU1_TOTW_MAG_F,
DRCC1_OUTWSET_SUBVAL_F, DGEN1_TOTWH_MAG_F, MMXU1_TOTPF_MAG_F, DSCH1_SCHDABSTM_VAL_0,
DSCH1_SCHDABSTM_VAL_1, DSCH1_SCHDABSTM_VAL_2, DSCH1_SCHDABSTM_VAL_3, DSCH2_SCHDABSTM_VAL_0,
DSCH2_SCHDABSTM_VAL_1, DSCH2_SCHDABSTM_VAL_2, DSCH2_SCHDABSTM_VAL_3, DSCH3_SCHDABSTM_VAL_0,
DSCH3_SCHDABSTM_VAL_1, DSCH3_SCHDABSTM_VAL_2, DSCH3_SCHDABSTM_VAL_3)));
private static final Set<String> INT8_NODES = Collections.unmodifiableSet(
new TreeSet<>(Arrays.asList(LLN0_HEALTH_STVAL, LLN0_BEH_STVAL, LLN0_MOD_STVAL, DGEN1_GNOPST_STVAL)));
private static final Set<String> INT32_NODES = Collections
.unmodifiableSet(new TreeSet<>(Arrays.asList(DGEN1_OPTMSRS_STVAL, GGIO1_INTIN1_STVAL, GGIO1_INTIN2_STVAL,
DSCH1_SCHDID_SETVAL, DSCH1_SCHDTYP_SETVAL, DSCH1_SCHDCAT_SETVAL, DSCH2_SCHDID_SETVAL,
DSCH2_SCHDTYP_SETVAL, DSCH2_SCHDCAT_SETVAL, DSCH3_SCHDID_SETVAL, DSCH3_SCHDTYP_SETVAL,
DSCH3_SCHDCAT_SETVAL, DSCH4_SCHDID_SETVAL, DSCH4_SCHDTYP_SETVAL, DSCH4_SCHDCAT_SETVAL)));
private static final Set<String> QUALITY_NODES = Collections
.unmodifiableSet(new TreeSet<>(Arrays.asList(LLN0_HEALTH_Q, LLN0_BEH_Q, LLN0_MOD_Q, MMXU1_MAXWPHS_Q,
MMXU1_MINWPHS_Q, MMXU1_TOTW_Q, DRCC1_OUTWSET_SUBQ, MMXU1_TOTPF_Q, DGEN1_TOTWH_Q, DGEN1_GNOPST_Q,
DGEN1_OPTMSRS_Q, GGIO1_ALM1_Q, GGIO1_ALM2_Q, GGIO1_ALM3_Q, GGIO1_ALM4_Q, GGIO1_INTIN1_Q,
GGIO1_INTIN2_Q, GGIO1_WRN1_Q, GGIO1_WRN2_Q, GGIO1_WRN3_Q, GGIO1_WRN4_Q)));
private static final Set<String> TIMESTAMP_NODES = Collections
.unmodifiableSet(new TreeSet<>(Arrays.asList(LLN0_HEALTH_T, LLN0_BEH_T, LLN0_MOD_T, MMXU1_MAXWPHS_T,
MMXU1_MINWPHS_T, MMXU1_TOTW_T, MMXU1_TOTPF_T, DGEN1_TOTWH_T, DGEN1_GNOPST_T, DGEN1_OPTMSRS_T,
GGIO1_ALM1_T, GGIO1_ALM2_T, GGIO1_ALM3_T, GGIO1_ALM4_T, GGIO1_INTIN1_T, GGIO1_INTIN2_T,
GGIO1_WRN1_T, GGIO1_WRN2_T, GGIO1_WRN3_T, GGIO1_WRN4_T, DSCH1_SCHDABSTM_TIME_0,
DSCH1_SCHDABSTM_TIME_1, DSCH1_SCHDABSTM_TIME_2, DSCH1_SCHDABSTM_TIME_3, DSCH2_SCHDABSTM_TIME_0,
DSCH2_SCHDABSTM_TIME_1, DSCH2_SCHDABSTM_TIME_2, DSCH2_SCHDABSTM_TIME_3, DSCH3_SCHDABSTM_TIME_0,
DSCH3_SCHDABSTM_TIME_1, DSCH3_SCHDABSTM_TIME_2, DSCH3_SCHDABSTM_TIME_3, DSCH4_SCHDABSTM_TIME_0,
DSCH4_SCHDABSTM_TIME_1, DSCH4_SCHDABSTM_TIME_2, DSCH4_SCHDABSTM_TIME_3)));
private static final Map<String, Fc> FC_BY_NODE;
static {
final Map<String, Fc> fcByNode = new TreeMap<>();
fcByNode.put(DSCH1_SCHDID_SETVAL, Fc.SP);
fcByNode.put(DSCH1_SCHDTYP_SETVAL, Fc.SP);
fcByNode.put(DSCH1_SCHDCAT_SETVAL, Fc.SP);
fcByNode.put(DSCH1_SCHDABSTM_VAL_0, Fc.SP);
fcByNode.put(DSCH1_SCHDABSTM_TIME_0, Fc.SP);
fcByNode.put(DSCH1_SCHDABSTM_VAL_1, Fc.SP);
fcByNode.put(DSCH1_SCHDABSTM_TIME_1, Fc.SP);
fcByNode.put(DSCH1_SCHDABSTM_VAL_2, Fc.SP);
fcByNode.put(DSCH1_SCHDABSTM_TIME_2, Fc.SP);
fcByNode.put(DSCH1_SCHDABSTM_VAL_3, Fc.SP);
fcByNode.put(DSCH1_SCHDABSTM_TIME_3, Fc.SP);
fcByNode.put(DSCH2_SCHDID_SETVAL, Fc.SP);
fcByNode.put(DSCH2_SCHDTYP_SETVAL, Fc.SP);
fcByNode.put(DSCH2_SCHDCAT_SETVAL, Fc.SP);
fcByNode.put(DSCH2_SCHDABSTM_VAL_0, Fc.SP);
fcByNode.put(DSCH2_SCHDABSTM_TIME_0, Fc.SP);
fcByNode.put(DSCH2_SCHDABSTM_VAL_1, Fc.SP);
fcByNode.put(DSCH2_SCHDABSTM_TIME_1, Fc.SP);
fcByNode.put(DSCH2_SCHDABSTM_VAL_2, Fc.SP);
fcByNode.put(DSCH2_SCHDABSTM_TIME_2, Fc.SP);
fcByNode.put(DSCH2_SCHDABSTM_VAL_3, Fc.SP);
fcByNode.put(DSCH2_SCHDABSTM_TIME_3, Fc.SP);
fcByNode.put(DSCH3_SCHDID_SETVAL, Fc.SP);
fcByNode.put(DSCH3_SCHDTYP_SETVAL, Fc.SP);
fcByNode.put(DSCH3_SCHDCAT_SETVAL, Fc.SP);
fcByNode.put(DSCH3_SCHDABSTM_VAL_0, Fc.SP);
fcByNode.put(DSCH3_SCHDABSTM_TIME_0, Fc.SP);
fcByNode.put(DSCH3_SCHDABSTM_VAL_1, Fc.SP);
fcByNode.put(DSCH3_SCHDABSTM_TIME_1, Fc.SP);
fcByNode.put(DSCH3_SCHDABSTM_VAL_2, Fc.SP);
fcByNode.put(DSCH3_SCHDABSTM_TIME_2, Fc.SP);
fcByNode.put(DSCH3_SCHDABSTM_VAL_3, Fc.SP);
fcByNode.put(DSCH3_SCHDABSTM_TIME_3, Fc.SP);
fcByNode.put(DSCH4_SCHDID_SETVAL, Fc.SP);
fcByNode.put(DSCH4_SCHDTYP_SETVAL, Fc.SP);
fcByNode.put(DSCH4_SCHDCAT_SETVAL, Fc.SP);
fcByNode.put(DSCH4_SCHDABSTM_VAL_0, Fc.SP);
fcByNode.put(DSCH4_SCHDABSTM_TIME_0, Fc.SP);
fcByNode.put(DSCH4_SCHDABSTM_VAL_1, Fc.SP);
fcByNode.put(DSCH4_SCHDABSTM_TIME_1, Fc.SP);
fcByNode.put(DSCH4_SCHDABSTM_VAL_2, Fc.SP);
fcByNode.put(DSCH4_SCHDABSTM_TIME_2, Fc.SP);
fcByNode.put(DSCH4_SCHDABSTM_VAL_3, Fc.SP);
fcByNode.put(DSCH4_SCHDABSTM_TIME_3, Fc.SP);
fcByNode.put(LLN0_HEALTH_STVAL, Fc.ST);
fcByNode.put(LLN0_HEALTH_Q, Fc.ST);
fcByNode.put(LLN0_HEALTH_T, Fc.ST);
fcByNode.put(LLN0_BEH_STVAL, Fc.ST);
fcByNode.put(LLN0_BEH_Q, Fc.ST);
fcByNode.put(LLN0_BEH_T, Fc.ST);
fcByNode.put(LLN0_MOD_STVAL, Fc.ST);
fcByNode.put(LLN0_MOD_Q, Fc.ST);
fcByNode.put(LLN0_MOD_T, Fc.ST);
fcByNode.put(MMXU1_MAXWPHS_MAG_F, Fc.MX);
fcByNode.put(MMXU1_MAXWPHS_Q, Fc.MX);
fcByNode.put(MMXU1_MAXWPHS_T, Fc.MX);
fcByNode.put(MMXU1_MINWPHS_MAG_F, Fc.MX);
fcByNode.put(MMXU1_MINWPHS_Q, Fc.MX);
fcByNode.put(MMXU1_MINWPHS_T, Fc.MX);
fcByNode.put(MMXU1_TOTW_MAG_F, Fc.MX);
fcByNode.put(MMXU1_TOTW_Q, Fc.MX);
fcByNode.put(MMXU1_TOTW_T, Fc.MX);
fcByNode.put(MMXU1_TOTPF_MAG_F, Fc.MX);
fcByNode.put(MMXU1_TOTPF_Q, Fc.MX);
fcByNode.put(MMXU1_TOTPF_T, Fc.MX);
fcByNode.put(DRCC1_OUTWSET_SUBVAL_F, Fc.SV);
fcByNode.put(DRCC1_OUTWSET_SUBQ, Fc.SV);
fcByNode.put(DGEN1_TOTWH_MAG_F, Fc.MX);
fcByNode.put(DGEN1_TOTWH_Q, Fc.MX);
fcByNode.put(DGEN1_TOTWH_T, Fc.MX);
fcByNode.put(DGEN1_GNOPST_STVAL, Fc.ST);
fcByNode.put(DGEN1_GNOPST_Q, Fc.ST);
fcByNode.put(DGEN1_GNOPST_T, Fc.ST);
fcByNode.put(DGEN1_OPTMSRS_STVAL, Fc.ST);
fcByNode.put(DGEN1_OPTMSRS_Q, Fc.ST);
fcByNode.put(DGEN1_OPTMSRS_T, Fc.ST);
fcByNode.put(GGIO1_ALM1_STVAL, Fc.ST);
fcByNode.put(GGIO1_ALM1_Q, Fc.ST);
fcByNode.put(GGIO1_ALM1_T, Fc.ST);
fcByNode.put(GGIO1_ALM2_STVAL, Fc.ST);
fcByNode.put(GGIO1_ALM2_Q, Fc.ST);
fcByNode.put(GGIO1_ALM2_T, Fc.ST);
fcByNode.put(GGIO1_ALM3_STVAL, Fc.ST);
fcByNode.put(GGIO1_ALM3_Q, Fc.ST);
fcByNode.put(GGIO1_ALM3_T, Fc.ST);
fcByNode.put(GGIO1_ALM4_STVAL, Fc.ST);
fcByNode.put(GGIO1_ALM4_Q, Fc.ST);
fcByNode.put(GGIO1_ALM4_T, Fc.ST);
fcByNode.put(GGIO1_INTIN1_STVAL, Fc.ST);
fcByNode.put(GGIO1_INTIN1_Q, Fc.ST);
fcByNode.put(GGIO1_INTIN1_T, Fc.ST);
fcByNode.put(GGIO1_INTIN2_STVAL, Fc.ST);
fcByNode.put(GGIO1_INTIN2_Q, Fc.ST);
fcByNode.put(GGIO1_INTIN2_T, Fc.ST);
fcByNode.put(GGIO1_WRN1_STVAL, Fc.ST);
fcByNode.put(GGIO1_WRN1_Q, Fc.ST);
fcByNode.put(GGIO1_WRN1_T, Fc.ST);
fcByNode.put(GGIO1_WRN2_STVAL, Fc.ST);
fcByNode.put(GGIO1_WRN2_Q, Fc.ST);
fcByNode.put(GGIO1_WRN2_T, Fc.ST);
fcByNode.put(GGIO1_WRN3_STVAL, Fc.ST);
fcByNode.put(GGIO1_WRN3_Q, Fc.ST);
fcByNode.put(GGIO1_WRN3_T, Fc.ST);
fcByNode.put(GGIO1_WRN4_STVAL, Fc.ST);
fcByNode.put(GGIO1_WRN4_Q, Fc.ST);
fcByNode.put(GGIO1_WRN4_T, Fc.ST);
FC_BY_NODE = Collections.unmodifiableMap(fcByNode);
}
public Battery(final String physicalDeviceName, final String logicalDeviceName, final ServerModel serverModel) {
super(physicalDeviceName, logicalDeviceName, serverModel);
}
@Override
public List<BasicDataAttribute> getAttributesAndSetValues(final Date timestamp) {
final List<BasicDataAttribute> values = new ArrayList<>();
values.add(this.setRandomByte(LLN0_HEALTH_STVAL, Fc.ST, 1, 2));
values.add(this.setQuality(LLN0_HEALTH_Q, Fc.ST, QualityType.VALIDITY_GOOD.getValue()));
values.add(this.setTime(LLN0_HEALTH_T, Fc.ST, timestamp));
values.add(this.setRandomByte(LLN0_BEH_STVAL, Fc.ST, 1, 2));
values.add(this.setQuality(LLN0_BEH_Q, Fc.ST, QualityType.VALIDITY_GOOD.getValue()));
values.add(this.setTime(LLN0_BEH_T, Fc.ST, timestamp));
values.add(this.setRandomByte(LLN0_MOD_STVAL, Fc.ST, 1, 2));
values.add(this.setQuality(LLN0_MOD_Q, Fc.ST, QualityType.VALIDITY_GOOD.getValue()));
values.add(this.setTime(LLN0_MOD_T, Fc.ST, timestamp));
values.add(this.setRandomFloat(MMXU1_MAXWPHS_MAG_F, Fc.MX, 500, 1000));
values.add(this.setQuality(MMXU1_MAXWPHS_Q, Fc.MX, QualityType.VALIDITY_GOOD.getValue()));
values.add(this.setTime(MMXU1_MAXWPHS_T, Fc.MX, timestamp));
values.add(this.setRandomFloat(MMXU1_MINWPHS_MAG_F, Fc.MX, 0, 500));
values.add(this.setQuality(MMXU1_MINWPHS_Q, Fc.MX, QualityType.VALIDITY_GOOD.getValue()));
values.add(this.setTime(MMXU1_MINWPHS_T, Fc.MX, timestamp));
values.add(this.setRandomFloat(MMXU1_TOTW_MAG_F, Fc.MX, 0, 1000));
values.add(this.setQuality(MMXU1_TOTW_Q, Fc.MX, QualityType.VALIDITY_GOOD.getValue()));
values.add(this.setTime(MMXU1_TOTW_T, Fc.MX, timestamp));
values.add(this.setRandomFloat(MMXU1_TOTPF_MAG_F, Fc.MX, 0, 1000));
values.add(this.setQuality(MMXU1_TOTPF_Q, Fc.MX, QualityType.VALIDITY_GOOD.getValue()));
values.add(this.setTime(MMXU1_TOTPF_T, Fc.MX, timestamp));
values.add(this.setRandomFloat(DRCC1_OUTWSET_SUBVAL_F, Fc.SV, 0, 1000));
values.add(this.setQuality(DRCC1_OUTWSET_SUBQ, Fc.SV, QualityType.VALIDITY_GOOD.getValue()));
values.add(this.setRandomFloat(DGEN1_TOTWH_MAG_F, Fc.MX, 0, 1000));
values.add(this.setQuality(DGEN1_TOTWH_Q, Fc.MX, QualityType.VALIDITY_GOOD.getValue()));
values.add(this.setTime(DGEN1_TOTWH_T, Fc.MX, timestamp));
values.add(this.setRandomByte(DGEN1_GNOPST_STVAL, Fc.ST, 1, 2));
values.add(this.setQuality(DGEN1_GNOPST_Q, Fc.ST, QualityType.VALIDITY_GOOD.getValue()));
values.add(this.setTime(DGEN1_GNOPST_T, Fc.ST, timestamp));
values.add(this.incrementInt(DGEN1_OPTMSRS_STVAL, Fc.ST));
values.add(this.setQuality(DGEN1_OPTMSRS_Q, Fc.ST, QualityType.VALIDITY_GOOD.getValue()));
values.add(this.setTime(DGEN1_OPTMSRS_T, Fc.ST, timestamp));
values.add(this.setBoolean(GGIO1_ALM1_STVAL, Fc.ST, false));
values.add(this.setQuality(GGIO1_ALM1_Q, Fc.ST, QualityType.VALIDITY_GOOD.getValue()));
values.add(this.setTime(GGIO1_ALM1_T, Fc.ST, timestamp));
values.add(this.setBoolean(GGIO1_ALM2_STVAL, Fc.ST, false));
values.add(this.setQuality(GGIO1_ALM2_Q, Fc.ST, QualityType.VALIDITY_GOOD.getValue()));
values.add(this.setTime(GGIO1_ALM2_T, Fc.ST, timestamp));
values.add(this.setBoolean(GGIO1_ALM3_STVAL, Fc.ST, false));
values.add(this.setQuality(GGIO1_ALM3_Q, Fc.ST, QualityType.VALIDITY_GOOD.getValue()));
values.add(this.setTime(GGIO1_ALM3_T, Fc.ST, timestamp));
values.add(this.setBoolean(GGIO1_ALM4_STVAL, Fc.ST, false));
values.add(this.setQuality(GGIO1_ALM4_Q, Fc.ST, QualityType.VALIDITY_GOOD.getValue()));
values.add(this.setTime(GGIO1_ALM4_T, Fc.ST, timestamp));
values.add(this.setRandomInt(GGIO1_INTIN1_STVAL, Fc.ST, 1, 100));
values.add(this.setQuality(GGIO1_INTIN1_Q, Fc.ST, QualityType.VALIDITY_GOOD.getValue()));
values.add(this.setTime(GGIO1_INTIN1_T, Fc.ST, timestamp));
values.add(this.setRandomInt(GGIO1_INTIN2_STVAL, Fc.ST, 1, 100));
values.add(this.setQuality(GGIO1_INTIN2_Q, Fc.ST, QualityType.VALIDITY_GOOD.getValue()));
values.add(this.setTime(GGIO1_INTIN2_T, Fc.ST, timestamp));
values.add(this.setBoolean(GGIO1_WRN1_STVAL, Fc.ST, false));
values.add(this.setQuality(GGIO1_WRN1_Q, Fc.ST, QualityType.VALIDITY_GOOD.getValue()));
values.add(this.setTime(GGIO1_WRN1_T, Fc.ST, timestamp));
values.add(this.setBoolean(GGIO1_WRN2_STVAL, Fc.ST, false));
values.add(this.setQuality(GGIO1_WRN2_Q, Fc.ST, QualityType.VALIDITY_GOOD.getValue()));
values.add(this.setTime(GGIO1_WRN2_T, Fc.ST, timestamp));
values.add(this.setBoolean(GGIO1_WRN3_STVAL, Fc.ST, false));
values.add(this.setQuality(GGIO1_WRN3_Q, Fc.ST, QualityType.VALIDITY_GOOD.getValue()));
values.add(this.setTime(GGIO1_WRN3_T, Fc.ST, timestamp));
values.add(this.setBoolean(GGIO1_WRN4_STVAL, Fc.ST, false));
values.add(this.setQuality(GGIO1_WRN4_Q, Fc.ST, QualityType.VALIDITY_GOOD.getValue()));
values.add(this.setTime(GGIO1_WRN4_T, Fc.ST, timestamp));
values.add(this.setRandomInt(DSCH1_SCHDID_SETVAL, Fc.SP, 1, 100));
values.add(this.setRandomInt(DSCH1_SCHDTYP_SETVAL, Fc.SP, 1, 100));
values.add(this.setRandomInt(DSCH1_SCHDCAT_SETVAL, Fc.SP, 1, 100));
values.add(this.setRandomFloat(DSCH1_SCHDABSTM_VAL_0, Fc.SP, 0, 1000));
values.add(this.setTime(DSCH1_SCHDABSTM_TIME_0, Fc.SP, timestamp));
values.add(this.setRandomFloat(DSCH1_SCHDABSTM_VAL_1, Fc.SP, 0, 1000));
values.add(this.setTime(DSCH1_SCHDABSTM_TIME_1, Fc.SP, timestamp));
values.add(this.setRandomFloat(DSCH1_SCHDABSTM_VAL_2, Fc.SP, 0, 1000));
values.add(this.setTime(DSCH1_SCHDABSTM_TIME_2, Fc.SP, timestamp));
values.add(this.setRandomFloat(DSCH1_SCHDABSTM_VAL_3, Fc.SP, 0, 1000));
values.add(this.setTime(DSCH1_SCHDABSTM_TIME_3, Fc.SP, timestamp));
values.add(this.setRandomInt(DSCH2_SCHDID_SETVAL, Fc.SP, 1, 100));
values.add(this.setRandomInt(DSCH2_SCHDTYP_SETVAL, Fc.SP, 1, 100));
values.add(this.setRandomInt(DSCH2_SCHDCAT_SETVAL, Fc.SP, 1, 100));
values.add(this.setRandomFloat(DSCH2_SCHDABSTM_VAL_0, Fc.SP, 0, 1000));
values.add(this.setTime(DSCH2_SCHDABSTM_TIME_0, Fc.SP, timestamp));
values.add(this.setRandomFloat(DSCH2_SCHDABSTM_VAL_1, Fc.SP, 0, 1000));
values.add(this.setTime(DSCH2_SCHDABSTM_TIME_1, Fc.SP, timestamp));
values.add(this.setRandomFloat(DSCH2_SCHDABSTM_VAL_2, Fc.SP, 0, 1000));
values.add(this.setTime(DSCH2_SCHDABSTM_TIME_2, Fc.SP, timestamp));
values.add(this.setRandomFloat(DSCH2_SCHDABSTM_VAL_3, Fc.SP, 0, 1000));
values.add(this.setTime(DSCH2_SCHDABSTM_TIME_3, Fc.SP, timestamp));
values.add(this.setRandomInt(DSCH3_SCHDID_SETVAL, Fc.SP, 1, 100));
values.add(this.setRandomInt(DSCH3_SCHDTYP_SETVAL, Fc.SP, 1, 100));
values.add(this.setRandomInt(DSCH3_SCHDCAT_SETVAL, Fc.SP, 1, 100));
values.add(this.setRandomFloat(DSCH3_SCHDABSTM_VAL_0, Fc.SP, 0, 1000));
values.add(this.setTime(DSCH3_SCHDABSTM_TIME_0, Fc.SP, timestamp));
values.add(this.setRandomFloat(DSCH3_SCHDABSTM_VAL_1, Fc.SP, 0, 1000));
values.add(this.setTime(DSCH3_SCHDABSTM_TIME_1, Fc.SP, timestamp));
values.add(this.setRandomFloat(DSCH3_SCHDABSTM_VAL_2, Fc.SP, 0, 1000));
values.add(this.setTime(DSCH3_SCHDABSTM_TIME_2, Fc.SP, timestamp));
values.add(this.setRandomFloat(DSCH3_SCHDABSTM_VAL_3, Fc.SP, 0, 1000));
values.add(this.setTime(DSCH3_SCHDABSTM_TIME_3, Fc.SP, timestamp));
values.add(this.setRandomInt(DSCH4_SCHDID_SETVAL, Fc.SP, 1, 100));
values.add(this.setRandomInt(DSCH4_SCHDTYP_SETVAL, Fc.SP, 1, 100));
values.add(this.setRandomInt(DSCH4_SCHDCAT_SETVAL, Fc.SP, 1, 100));
values.add(this.setRandomFloat(DSCH4_SCHDABSTM_VAL_0, Fc.SP, 0, 1000));
values.add(this.setTime(DSCH4_SCHDABSTM_TIME_0, Fc.SP, timestamp));
values.add(this.setRandomFloat(DSCH4_SCHDABSTM_VAL_1, Fc.SP, 0, 1000));
values.add(this.setTime(DSCH4_SCHDABSTM_TIME_1, Fc.SP, timestamp));
values.add(this.setRandomFloat(DSCH4_SCHDABSTM_VAL_2, Fc.SP, 0, 1000));
values.add(this.setTime(DSCH4_SCHDABSTM_TIME_2, Fc.SP, timestamp));
values.add(this.setRandomFloat(DSCH4_SCHDABSTM_VAL_3, Fc.SP, 0, 1000));
values.add(this.setTime(DSCH4_SCHDABSTM_TIME_3, Fc.SP, timestamp));
return values;
}
@Override
public BasicDataAttribute getAttributeAndSetValue(final String node, final String value) {
final Fc fc = this.getFunctionalConstraint(node);
if (fc == null) {
throw this.illegalNodeException(node);
}
if (BOOLEAN_NODES.contains(node)) {
return this.setBoolean(node, fc, Boolean.parseBoolean(value));
}
if (FLOAT32_NODES.contains(node)) {
return this.setFixedFloat(node, fc, Float.parseFloat(value));
}
if (INT8_NODES.contains(node)) {
return this.setByte(node, fc, Byte.parseByte(value));
}
if (INT32_NODES.contains(node)) {
return this.setInt(node, fc, Integer.parseInt(value));
}
if (QUALITY_NODES.contains(node)) {
return this.setQuality(node, fc, QualityType.valueOf(value).getValue());
}
if (TIMESTAMP_NODES.contains(node)) {
return this.setTime(node, fc, new Date()); // TODO parse value
}
throw this.nodeTypeNotConfiguredException(node);
}
@Override
public Fc getFunctionalConstraint(final String node) {
return FC_BY_NODE.get(node);
}
}
<file_sep>/**
* Copyright 2014-2016 Smart Society Services B.V.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*/
package com.alliander.osgp.simulator.protocol.iec61850.server.logicaldevices;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import org.openmuc.openiec61850.BasicDataAttribute;
import org.openmuc.openiec61850.Fc;
import org.openmuc.openiec61850.ServerModel;
import com.alliander.osgp.simulator.protocol.iec61850.server.QualityType;
public class Load extends LogicalDevice {
private static final String LLN0_MOD_STVAL = "LLN0.Mod.stVal";
private static final String LLN0_MOD_Q = "LLN0.Mod.q";
private static final String LLN0_MOD_T = "LLN0.Mod.t";
private static final String LLN0_BEH_STVAL = "LLN0.Beh.stVal";
private static final String LLN0_BEH_Q = "LLN0.Beh.q";
private static final String LLN0_BEH_T = "LLN0.Beh.t";
private static final String LLN0_HEALTH_STVAL = "LLN0.Health.stVal";
private static final String LLN0_HEALTH_Q = "LLN0.Health.q";
private static final String LLN0_HEALTH_T = "LLN0.Health.t";
private static final String MMXU1_TOTW_MAG_F = "MMXU1.TotW.mag.f";
private static final String MMXU1_TOTW_Q = "MMXU1.TotW.q";
private static final String MMXU1_TOTW_T = "MMXU1.TotW.t";
private static final String MMXU1_MINWPHS_MAG_F = "MMXU1.MinWPhs.mag.f";
private static final String MMXU1_MINWPHS_Q = "MMXU1.MinWPhs.q";
private static final String MMXU1_MINWPHS_T = "MMXU1.MinWPhs.t";
private static final String MMXU1_MAXWPHS_MAG_F = "MMXU1.MaxWPhs.mag.f";
private static final String MMXU1_MAXWPHS_Q = "MMXU1.MaxWPhs.q";
private static final String MMXU1_MAXWPHS_T = "MMXU1.MaxWPhs.t";
private static final String MMXU2_TOTW_MAG_F = "MMXU2.TotW.mag.f";
private static final String MMXU2_TOTW_Q = "MMXU2.TotW.q";
private static final String MMXU2_TOTW_T = "MMXU2.TotW.t";
private static final String MMXU2_MINWPHS_MAG_F = "MMXU2.MinWPhs.mag.f";
private static final String MMXU2_MINWPHS_Q = "MMXU2.MinWPhs.q";
private static final String MMXU2_MINWPHS_T = "MMXU2.MinWPhs.t";
private static final String MMXU2_MAXWPHS_MAG_F = "MMXU2.MaxWPhs.mag.f";
private static final String MMXU2_MAXWPHS_Q = "MMXU2.MaxWPhs.q";
private static final String MMXU2_MAXWPHS_T = "MMXU2.MaxWPhs.t";
private static final String MMTR1_TOTWH_ACTVAL = "MMTR1.TotWh.actVal";
private static final String MMTR1_TOTWH_Q = "MMTR1.TotWh.q";
private static final String MMTR1_TOTWH_T = "MMTR1.TotWh.t";
private static final String GGIO1_ALM1_STVAL = "GGIO1.Alm1.stVal";
private static final String GGIO1_ALM1_Q = "GGIO1.Alm1.q";
private static final String GGIO1_ALM1_T = "GGIO1.Alm1.t";
private static final String GGIO1_ALM2_STVAL = "GGIO1.Alm2.stVal";
private static final String GGIO1_ALM2_Q = "GGIO1.Alm2.q";
private static final String GGIO1_ALM2_T = "GGIO1.Alm2.t";
private static final String GGIO1_ALM3_STVAL = "GGIO1.Alm3.stVal";
private static final String GGIO1_ALM3_Q = "GGIO1.Alm3.q";
private static final String GGIO1_ALM3_T = "GGIO1.Alm3.t";
private static final String GGIO1_ALM4_STVAL = "GGIO1.Alm4.stVal";
private static final String GGIO1_ALM4_Q = "GGIO1.Alm4.q";
private static final String GGIO1_ALM4_T = "GGIO1.Alm4.t";
private static final String GGIO1_INTIN1_STVAL = "GGIO1.IntIn1.stVal";
private static final String GGIO1_INTIN1_Q = "GGIO1.IntIn1.q";
private static final String GGIO1_INTIN1_T = "GGIO1.IntIn1.t";
private static final String GGIO1_INTIN2_STVAL = "GGIO1.IntIn2.stVal";
private static final String GGIO1_INTIN2_Q = "GGIO1.IntIn2.q";
private static final String GGIO1_INTIN2_T = "GGIO1.IntIn2.t";
private static final String GGIO1_WRN1_STVAL = "GGIO1.Wrn1.stVal";
private static final String GGIO1_WRN1_Q = "GGIO1.Wrn1.q";
private static final String GGIO1_WRN1_T = "GGIO1.Wrn1.t";
private static final String GGIO1_WRN2_STVAL = "GGIO1.Wrn2.stVal";
private static final String GGIO1_WRN2_Q = "GGIO1.Wrn2.q";
private static final String GGIO1_WRN2_T = "GGIO1.Wrn2.t";
private static final String GGIO1_WRN3_STVAL = "GGIO1.Wrn3.stVal";
private static final String GGIO1_WRN3_Q = "GGIO1.Wrn3.q";
private static final String GGIO1_WRN3_T = "GGIO1.Wrn3.t";
private static final String GGIO1_WRN4_STVAL = "GGIO1.Wrn4.stVal";
private static final String GGIO1_WRN4_Q = "GGIO1.Wrn4.q";
private static final String GGIO1_WRN4_T = "GGIO1.Wrn4.t";
private static final Set<String> BOOLEAN_NODES = Collections
.unmodifiableSet(new TreeSet<>(Arrays.asList(GGIO1_ALM1_STVAL, GGIO1_ALM2_STVAL, GGIO1_ALM3_STVAL,
GGIO1_ALM4_STVAL, GGIO1_WRN1_STVAL, GGIO1_WRN2_STVAL, GGIO1_WRN3_STVAL, GGIO1_WRN4_STVAL)));
private static final Set<String> FLOAT32_NODES = Collections
.unmodifiableSet(new TreeSet<>(Arrays.asList(MMXU1_MAXWPHS_MAG_F, MMXU1_MINWPHS_MAG_F, MMXU1_TOTW_MAG_F,
MMXU2_MAXWPHS_MAG_F, MMXU2_MINWPHS_MAG_F, MMXU2_TOTW_MAG_F)));
private static final Set<String> INT8_NODES = Collections
.unmodifiableSet(new TreeSet<>(Arrays.asList(LLN0_HEALTH_STVAL, LLN0_MOD_STVAL, LLN0_BEH_STVAL)));
private static final Set<String> INT32_NODES = Collections
.unmodifiableSet(new TreeSet<>(Arrays.asList(GGIO1_INTIN1_STVAL, GGIO1_INTIN2_STVAL)));
private static final Set<String> QUALITY_NODES = Collections
.unmodifiableSet(new TreeSet<>(Arrays.asList(LLN0_HEALTH_Q, LLN0_BEH_Q, LLN0_MOD_Q, MMXU1_MAXWPHS_Q,
MMXU1_MINWPHS_Q, MMXU1_TOTW_Q, MMXU2_MAXWPHS_Q, MMXU2_MINWPHS_Q, MMXU2_TOTW_Q, GGIO1_ALM1_Q,
GGIO1_ALM2_Q, GGIO1_ALM3_Q, GGIO1_ALM4_Q, GGIO1_INTIN1_Q, GGIO1_INTIN2_Q, GGIO1_WRN1_Q,
GGIO1_WRN2_Q, GGIO1_WRN3_Q, GGIO1_WRN4_Q)));
private static final Set<String> TIMESTAMP_NODES = Collections
.unmodifiableSet(new TreeSet<>(Arrays.asList(LLN0_HEALTH_T, LLN0_BEH_T, LLN0_MOD_T, MMXU1_MAXWPHS_T,
MMXU1_MINWPHS_T, MMXU1_TOTW_T, MMXU2_MAXWPHS_T, MMXU2_MINWPHS_T, MMXU2_TOTW_T, GGIO1_ALM1_T,
GGIO1_ALM2_T, GGIO1_ALM3_T, GGIO1_ALM4_T, GGIO1_INTIN1_T, GGIO1_INTIN2_T, GGIO1_WRN1_T,
GGIO1_WRN2_T, GGIO1_WRN3_T, GGIO1_WRN4_T)));
private static final Map<String, Fc> FC_BY_NODE;
static {
final Map<String, Fc> fcByNode = new TreeMap<>();
fcByNode.put(LLN0_HEALTH_STVAL, Fc.ST);
fcByNode.put(LLN0_HEALTH_Q, Fc.ST);
fcByNode.put(LLN0_HEALTH_T, Fc.ST);
fcByNode.put(LLN0_BEH_STVAL, Fc.ST);
fcByNode.put(LLN0_BEH_Q, Fc.ST);
fcByNode.put(LLN0_BEH_T, Fc.ST);
fcByNode.put(LLN0_MOD_STVAL, Fc.ST);
fcByNode.put(LLN0_MOD_Q, Fc.ST);
fcByNode.put(LLN0_MOD_T, Fc.ST);
fcByNode.put(MMXU1_MAXWPHS_MAG_F, Fc.MX);
fcByNode.put(MMXU1_MAXWPHS_Q, Fc.MX);
fcByNode.put(MMXU1_MAXWPHS_T, Fc.MX);
fcByNode.put(MMXU1_MINWPHS_MAG_F, Fc.MX);
fcByNode.put(MMXU1_MINWPHS_Q, Fc.MX);
fcByNode.put(MMXU1_MINWPHS_T, Fc.MX);
fcByNode.put(MMXU1_TOTW_MAG_F, Fc.MX);
fcByNode.put(MMXU1_TOTW_Q, Fc.MX);
fcByNode.put(MMXU1_TOTW_T, Fc.MX);
fcByNode.put(MMXU2_MAXWPHS_MAG_F, Fc.MX);
fcByNode.put(MMXU2_MAXWPHS_Q, Fc.MX);
fcByNode.put(MMXU2_MAXWPHS_T, Fc.MX);
fcByNode.put(MMXU2_MINWPHS_MAG_F, Fc.MX);
fcByNode.put(MMXU2_MINWPHS_Q, Fc.MX);
fcByNode.put(MMXU2_MINWPHS_T, Fc.MX);
fcByNode.put(MMXU2_TOTW_MAG_F, Fc.MX);
fcByNode.put(MMXU2_TOTW_Q, Fc.MX);
fcByNode.put(MMXU2_TOTW_T, Fc.MX);
fcByNode.put(GGIO1_ALM1_STVAL, Fc.ST);
fcByNode.put(GGIO1_ALM1_Q, Fc.ST);
fcByNode.put(GGIO1_ALM1_T, Fc.ST);
fcByNode.put(GGIO1_ALM2_STVAL, Fc.ST);
fcByNode.put(GGIO1_ALM2_Q, Fc.ST);
fcByNode.put(GGIO1_ALM2_T, Fc.ST);
fcByNode.put(GGIO1_ALM3_STVAL, Fc.ST);
fcByNode.put(GGIO1_ALM3_Q, Fc.ST);
fcByNode.put(GGIO1_ALM3_T, Fc.ST);
fcByNode.put(GGIO1_ALM4_STVAL, Fc.ST);
fcByNode.put(GGIO1_ALM4_Q, Fc.ST);
fcByNode.put(GGIO1_ALM4_T, Fc.ST);
fcByNode.put(GGIO1_INTIN1_STVAL, Fc.ST);
fcByNode.put(GGIO1_INTIN1_Q, Fc.ST);
fcByNode.put(GGIO1_INTIN1_T, Fc.ST);
fcByNode.put(GGIO1_INTIN2_STVAL, Fc.ST);
fcByNode.put(GGIO1_INTIN2_Q, Fc.ST);
fcByNode.put(GGIO1_INTIN2_T, Fc.ST);
fcByNode.put(GGIO1_WRN1_STVAL, Fc.ST);
fcByNode.put(GGIO1_WRN1_Q, Fc.ST);
fcByNode.put(GGIO1_WRN1_T, Fc.ST);
fcByNode.put(GGIO1_WRN2_STVAL, Fc.ST);
fcByNode.put(GGIO1_WRN2_Q, Fc.ST);
fcByNode.put(GGIO1_WRN2_T, Fc.ST);
fcByNode.put(GGIO1_WRN3_STVAL, Fc.ST);
fcByNode.put(GGIO1_WRN3_Q, Fc.ST);
fcByNode.put(GGIO1_WRN3_T, Fc.ST);
fcByNode.put(GGIO1_WRN4_STVAL, Fc.ST);
fcByNode.put(GGIO1_WRN4_Q, Fc.ST);
fcByNode.put(GGIO1_WRN4_T, Fc.ST);
FC_BY_NODE = Collections.unmodifiableMap(fcByNode);
}
public Load(final String physicalDeviceName, final String logicalDeviceName, final ServerModel serverModel) {
super(physicalDeviceName, logicalDeviceName, serverModel);
}
@Override
public List<BasicDataAttribute> getAttributesAndSetValues(final Date timestamp) {
final List<BasicDataAttribute> values = new ArrayList<>();
values.add(this.setRandomByte(LLN0_HEALTH_STVAL, Fc.ST, 1, 2));
values.add(this.setQuality(LLN0_HEALTH_Q, Fc.ST, QualityType.VALIDITY_GOOD.getValue()));
values.add(this.setTime(LLN0_HEALTH_T, Fc.ST, timestamp));
values.add(this.setRandomByte(LLN0_BEH_STVAL, Fc.ST, 1, 2));
values.add(this.setQuality(LLN0_BEH_Q, Fc.ST, QualityType.VALIDITY_GOOD.getValue()));
values.add(this.setTime(LLN0_BEH_T, Fc.ST, timestamp));
values.add(this.setRandomByte(LLN0_MOD_STVAL, Fc.ST, 1, 2));
values.add(this.setQuality(LLN0_MOD_Q, Fc.ST, QualityType.VALIDITY_GOOD.getValue()));
values.add(this.setTime(LLN0_MOD_T, Fc.ST, timestamp));
values.add(this.setRandomFloat(MMXU1_MAXWPHS_MAG_F, Fc.MX, 500, 1000));
values.add(this.setQuality(MMXU1_MAXWPHS_Q, Fc.ST, QualityType.VALIDITY_GOOD.getValue()));
values.add(this.setTime(MMXU1_MAXWPHS_T, Fc.MX, timestamp));
values.add(this.setRandomFloat(MMXU1_MINWPHS_MAG_F, Fc.MX, 0, 500));
values.add(this.setQuality(MMXU1_MINWPHS_Q, Fc.ST, QualityType.VALIDITY_GOOD.getValue()));
values.add(this.setTime(MMXU1_MINWPHS_T, Fc.MX, timestamp));
values.add(this.setFixedFloat(MMXU1_TOTW_MAG_F, Fc.MX, 1));
values.add(this.setQuality(MMXU1_TOTW_Q, Fc.ST, QualityType.VALIDITY_GOOD.getValue()));
values.add(this.setTime(MMXU1_TOTW_T, Fc.MX, timestamp));
values.add(this.setRandomFloat(MMXU2_MAXWPHS_MAG_F, Fc.MX, 500, 1000));
values.add(this.setQuality(MMXU2_MAXWPHS_Q, Fc.ST, QualityType.VALIDITY_GOOD.getValue()));
values.add(this.setTime(MMXU2_MAXWPHS_T, Fc.MX, timestamp));
values.add(this.setRandomFloat(MMXU2_MINWPHS_MAG_F, Fc.MX, 0, 500));
values.add(this.setQuality(MMXU2_MINWPHS_Q, Fc.ST, QualityType.VALIDITY_GOOD.getValue()));
values.add(this.setTime(MMXU2_MINWPHS_T, Fc.MX, timestamp));
values.add(this.setFixedFloat(MMXU2_TOTW_MAG_F, Fc.MX, 1));
values.add(this.setQuality(MMXU2_TOTW_Q, Fc.ST, QualityType.VALIDITY_GOOD.getValue()));
values.add(this.setTime(MMXU2_TOTW_T, Fc.MX, timestamp));
values.add(this.setFixedInt(MMTR1_TOTWH_ACTVAL, Fc.ST, 1));
values.add(this.setQuality(MMTR1_TOTWH_Q, Fc.ST, QualityType.VALIDITY_GOOD.getValue()));
values.add(this.setTime(MMTR1_TOTWH_T, Fc.ST, timestamp));
values.add(this.setBoolean(GGIO1_ALM1_STVAL, Fc.ST, false));
values.add(this.setQuality(GGIO1_ALM1_Q, Fc.ST, QualityType.VALIDITY_GOOD.getValue()));
values.add(this.setTime(GGIO1_ALM1_T, Fc.ST, timestamp));
values.add(this.setBoolean(GGIO1_ALM2_STVAL, Fc.ST, false));
values.add(this.setQuality(GGIO1_ALM2_Q, Fc.ST, QualityType.VALIDITY_GOOD.getValue()));
values.add(this.setTime(GGIO1_ALM2_T, Fc.ST, timestamp));
values.add(this.setBoolean(GGIO1_ALM3_STVAL, Fc.ST, false));
values.add(this.setQuality(GGIO1_ALM3_Q, Fc.ST, QualityType.VALIDITY_GOOD.getValue()));
values.add(this.setTime(GGIO1_ALM3_T, Fc.ST, timestamp));
values.add(this.setBoolean(GGIO1_ALM4_STVAL, Fc.ST, false));
values.add(this.setQuality(GGIO1_ALM4_Q, Fc.ST, QualityType.VALIDITY_GOOD.getValue()));
values.add(this.setTime(GGIO1_ALM4_T, Fc.ST, timestamp));
values.add(this.setRandomInt(GGIO1_INTIN1_STVAL, Fc.ST, 1, 100));
values.add(this.setQuality(GGIO1_INTIN1_Q, Fc.ST, QualityType.VALIDITY_GOOD.getValue()));
values.add(this.setTime(GGIO1_INTIN1_T, Fc.ST, timestamp));
values.add(this.setBoolean(GGIO1_WRN1_STVAL, Fc.ST, false));
values.add(this.setQuality(GGIO1_WRN1_Q, Fc.ST, QualityType.VALIDITY_GOOD.getValue()));
values.add(this.setTime(GGIO1_WRN1_T, Fc.ST, timestamp));
values.add(this.setBoolean(GGIO1_WRN2_STVAL, Fc.ST, false));
values.add(this.setQuality(GGIO1_WRN2_Q, Fc.ST, QualityType.VALIDITY_GOOD.getValue()));
values.add(this.setTime(GGIO1_WRN2_T, Fc.ST, timestamp));
values.add(this.setBoolean(GGIO1_WRN3_STVAL, Fc.ST, false));
values.add(this.setQuality(GGIO1_WRN3_Q, Fc.ST, QualityType.VALIDITY_GOOD.getValue()));
values.add(this.setTime(GGIO1_WRN3_T, Fc.ST, timestamp));
values.add(this.setBoolean(GGIO1_WRN4_STVAL, Fc.ST, false));
values.add(this.setQuality(GGIO1_WRN4_Q, Fc.ST, QualityType.VALIDITY_GOOD.getValue()));
values.add(this.setTime(GGIO1_WRN4_T, Fc.ST, timestamp));
values.add(this.setRandomInt(GGIO1_INTIN2_STVAL, Fc.ST, 1, 100));
values.add(this.setQuality(GGIO1_INTIN2_Q, Fc.ST, QualityType.VALIDITY_GOOD.getValue()));
values.add(this.setTime(GGIO1_INTIN2_T, Fc.ST, timestamp));
return values;
}
@Override
public BasicDataAttribute getAttributeAndSetValue(final String node, final String value) {
final Fc fc = this.getFunctionalConstraint(node);
if (fc == null) {
throw this.illegalNodeException(node);
}
if (BOOLEAN_NODES.contains(node)) {
return this.setBoolean(node, fc, Boolean.parseBoolean(value));
}
if (FLOAT32_NODES.contains(node)) {
return this.setFixedFloat(node, fc, Float.parseFloat(value));
}
if (INT8_NODES.contains(node)) {
return this.setByte(node, fc, Byte.parseByte(value));
}
if (INT32_NODES.contains(node)) {
return this.setInt(node, fc, Integer.parseInt(value));
}
if (QUALITY_NODES.contains(node)) {
return this.setQuality(node, fc, QualityType.valueOf(value).getValue());
}
if (TIMESTAMP_NODES.contains(node)) {
return this.setTime(node, fc, this.parseDate(value));
}
throw this.nodeTypeNotConfiguredException(node);
}
@Override
public Fc getFunctionalConstraint(final String node) {
return FC_BY_NODE.get(node);
}
}
|
46a5c10231ff509ed667d4c00e15e2242c7870db
|
[
"Java"
] | 2
|
Java
|
cerfarrow/Protocol-Adapter-IEC61850
|
e3fb7c14c8cdfd2f0b3daf5fc7f5cce1a8468de1
|
961ce1b6d0f0cab86201b8b93b568ce9ff0a5ea1
|
refs/heads/master
|
<repo_name>lurenjiamax/gonelist<file_sep>/refresh_cache.sh
#!/bin/bash
touch conf && echo "*/10 * * * * /home/vcap/app/php/bin/php /home/vcap/app/web/one.php cache:refresh" >> conf && crontab conf && rm -f conf
|
a26f53ad380fc9e7426c759533e0c69c26fe9ed4
|
[
"Shell"
] | 1
|
Shell
|
lurenjiamax/gonelist
|
64089d6f4e73573d1808e092c96d5ecc4151d347
|
2f6dae6621db96545d137663da8ae047d9b26e4c
|
refs/heads/master
|
<file_sep><?php
$nav_width = get_theme_mod('create_navbar_layout-width');
$nav_layout = get_theme_mod('create_navbar_layout-layout');
$nav_pos = get_theme_mod('create_navbar_layout-nav-pos');
$logo = get_theme_mod('create_navbar_layout-logo');
?>
<?php
if($nav_layout !== 'navbar-static-top') {
echo '<div class="container">';
}elseif(($nav_layout === 'navbar-static-top' || $nav_layout === 'navbar-fixed-top' || $nav_layout === 'navbar-fixed-bottom') && ($nav_width === 'full')){
echo '<div class="container-full">';
}else {
echo '<div>';
}
?>
<header class="navbar navbar-default <?php echo $nav_layout; ?>" role="navigation">
<?php if ($nav_width !== 'full'): ?>
<div class="<?php echo ($nav_layout == 'navbar-static-top' ? 'container' : 'container-fluid'); ?>">
<?php endif ?>
<div class="navbar-header">
<button class="navbar-toggle collapsed" data-toggle="collapse" data-target=".navbar-collapse" type="button">
<span class="sr-only">Toggle Navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<?php if($logo === ""): ?>
<a href="<?php echo esc_url(home_url('/')); ?>" class="navbar-brand"><?php bloginfo('name'); ?></a>
<?php else: ?>
<a href="<?php echo esc_url(home_url('/')); ?>" class="logo"><img src="<?php echo $logo; ?>"></a>
<?php endif; ?>
</div>
<nav class="collapse navbar-collapse" role="navigation">
<?php
if(($nav_layout === 'navbar-static-top' || $nav_layout === 'navbar-fixed-top' || $nav_layout === 'navbar-fixed-bottom') && ($nav_width === 'full')){
echo '<div class="container-fluid">';
}else {
echo '<div>';
}
?>
<?php
if(has_nav_menu('primary')):
$nav_class = 'nav navbar-nav ' . $nav_pos;
wp_nav_menu(array('theme_location' => 'primary', 'menu_class' => $nav_class));
endif;
?>
</div>
</nav>
<?php if ($nav_width !== 'full'): ?>
</div>
<?php endif; ?>
</header>
</div>
<?php echo ($nav_layout !== 'navbar-static-top' ? '</div>' : ''); ?><file_sep><?php
function tmod($p, $s, $s) {
$mod = get_theme_mod("create_{$p}_{$s}-{$s}");
return $mod;
}<file_sep><?php $text_content = get_theme_mod('create_footer_layout-text-content'); ?>
<div class="row">
<div class="col-md-6 col-md-push-6">
<?php echo '<span class="text-content">' . $text_content . '</span>'; ?>
<span class="sep"> | </span>
<?php printf( __( 'Theme: %1$s by %2$s.', 'create' ), 'Create', '<a href="http://thecreate.com" rel="designer">Thecreate</a>' ); ?>
</div>
</div><file_sep><?php
class Blox {
public $path;
public $tpath;
public function __construct() {
$this->path = get_template_directory() . '/functions/blox/';
$this->tpath = $this->path . 'templates/';
add_action('add_meta_boxes', array($this, 'add_meta_boxes'), 1);
}
public function add_meta_boxes() {
add_meta_box(
'create-blox',
__('Blox', 'create'),
array($this, 'display_blox'),
'page',
'normal',
'high'
);
}
public function display_blox() {
// Display the base template for blox.
echo 'TEST';
}
}<file_sep>Create
======
[](https://gitter.im/FolsomCreative/Create?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
Create is version 1 of the thecreate framework and is intended to be an R&D platform for creating WordPress themes.
This project is based on based on Underscores, Bootstrap, and WordPress.
##Todo
- [ ] Cleanup Readme
- [ X ] Create a separate dev branch
- [ X ] Explore package management - NPM & Bower
- [ X ] Explore task runner - Gulp
- [ X ] Integrate Bootstrap
- [ ] Decide on menu support
- [ ] Segment theme functions
- [ ] Setup Post Format Support
- [ ] Setup WP theme customizer
- [ ] Setup Drag and Drop Theme Customizer using WP Metaboxes
- [ ] Setup theme updates / updates system
- [ ] Add in 3rd party support. Gravity forms, Contact Form 7<file_sep><?php
/**
* Create functions and definitions
*
* @package Create
*/
// Setup
require get_template_directory() . '/functions/setup.php';
// Add scripts
require get_template_directory() . '/functions/scripts.php';
// Create widget areas
require get_template_directory() . '/functions/widget-areas.php';
// Custom template tags
require get_template_directory() . '/functions/template-tags.php';
// Extra things
require get_template_directory() . '/functions/extras.php';
// Add jetpack support
require get_template_directory() . '/functions/jetpack.php';
// WP Nav Walker for bootstrap
require get_template_directory() . '/functions/walker.php';
// WP Shortcodes
require get_template_directory() . '/functions/shortcodes.php';
// TinyMCE Customizations
require get_template_directory() . '/functions/editor.php';
// WP Customizer setup
require get_template_directory() . '/functions/customizer/customizer.php';
new CreateCustomizer;
// WP Meta Boxes
// require get_template_directory() . '/functions/blox/blox.php';
// new Blox;
function create_body_container() {
echo 'container';
}<file_sep><?php $text_content = get_theme_mod('create_footer_layout-text-content'); ?>
<div class="row">
<div class="col-md-6">
<?php echo '<span class="text-content">' . $text_content . '</span>'; ?>
<span class="sep"> | </span>
<?php printf( __( 'Theme: %1$s by %2$s.', 'create' ), 'Create', '<a href="http://thecreate.com" rel="designer">Thecreate</a>' ); ?>
</div>
<div class="col-md-6">
<?php
if(has_nav_menu('footer')):
wp_nav_menu(array('theme_location' => 'footer', 'menu_class' => 'footer-menu'));
endif;
?>
</div>
</div><file_sep><?php
/**
* Scripts and stylesheets
*
* Enqueue stylesheets in the following order:
* 1. Application
*
* Enqueue scripts in the following order:
* 1. jQuery via Google CDN
* 2. Theme
*
*/
function create_scripts() {
// Stylesheets
wp_enqueue_style('app_css', get_template_directory_uri() . '/assets/css/app.min.css');
// Scripts
if(!is_admin()){
wp_deregister_script('jquery');
wp_register_script('jquery', '//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js', false, null, true);
wp_enqueue_script('jquery');
}
if(is_single() && comments_open() && get_option('thread_comments')) {
wp_enqueue_script('comment-reply');
}
wp_enqueue_script('create_js', get_template_directory_uri() . '/assets/js/app.min.js', array(), null, true);
wp_enqueue_script('customize', get_template_directory_uri() . '/assets/js/customizer/wp-customizer.js', array(), null, true);
}
add_action('wp_enqueue_scripts', 'create_scripts', 100);
function create_admin_scripts() {
wp_enqueue_style('create_admin_css', get_template_directory_uri() . '/assets/css/admin.min.css');
}
add_action('admin_enqueue_scripts', 'create_admin_scripts');
function add_conditional_scripts() {
echo '<!--[if lt IE 9]>';
echo '<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>';
echo '<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>';
echo '<![endif]-->';
}
add_action('wp_head', 'add_conditional_scripts', 101);<file_sep><?php
/**
* Register widget area.
*
* @link http://codex.wordpress.org/Function_Reference/register_sidebar
*/
function create_widgets_init() {
register_sidebar(array(
'name' => __('Footer 1', 'create'),
'id' => 'footer-1',
'description' => '',
'before_widget' => '',
'after_widget' => '',
'before_title' => '',
'after_title' => ''
));
register_sidebar(array(
'name' => __('Footer 2', 'create'),
'id' => 'footer-2',
'description' => '',
'before_widget' => '',
'after_widget' => '',
'before_title' => '',
'after_title' => ''
));
register_sidebar(array(
'name' => __('Footer 3', 'create'),
'id' => 'footer-3',
'description' => '',
'before_widget' => '',
'after_widget' => '',
'before_title' => '',
'after_title' => ''
));
register_sidebar(array(
'name' => __('Footer 4', 'create'),
'id' => 'footer-4',
'description' => '',
'before_widget' => '',
'after_widget' => '',
'before_title' => '',
'after_title' => ''
));
register_sidebar( array(
'name' => __( 'Sidebar', 'create' ),
'id' => 'sidebar-1',
'description' => '',
'before_widget' => '<aside id="%1$s" class="widget %2$s">',
'after_widget' => '</aside>',
'before_title' => '<h1 class="widget-title">',
'after_title' => '</h1>',
));
}
add_action( 'widgets_init', 'create_widgets_init' );<file_sep><div class="col-md-6">
<?php
if(has_nav_menu('footer')):
wp_nav_menu(array('theme_location' => 'footer', 'menu_class' => 'footer-menu'));
endif;
?>
</div><file_sep><?php $layout = get_theme_mod('create_footer_layout-layout'); ?>
</div> <!-- #content -->
</div>
<div class="container">
<footer id="colophon" class="site-footer" role="contentinfo">
<?php if($layout === '' || $layout === 'nav-left'): ?>
<?php get_template_part('partials/footer/nav-left'); ?>
<?php elseif($layout === 'no-nav'): ?>
<?php get_template_part('partials/footer/no-nav'); ?>
<?php elseif($layout === 'no-text'): ?>
<?php get_template_part('partials/footer/no-text'); ?>
<?php elseif($layout === 'nav-right'): ?>
<?php get_template_part('partials/footer/nav-right'); ?>
<?php endif; ?>
</footer><!-- #colophon -->
</div>
</div><!-- #page -->
<?php wp_footer(); ?>
</body>
</html>
|
9c3e69f425f40d3007ccb57a942c4117145c2669
|
[
"Markdown",
"PHP"
] | 11
|
PHP
|
FolsomCreative/Create
|
6555eb73356f1ec3f6cafe1a26394b30e137f988
|
1fb328791293c833ece00ae1b8fbb953ec0fafd4
|
refs/heads/master
|
<repo_name>joker1007/refining<file_sep>/Gemfile
source 'https://rubygems.org'
# Specify your gem's dependencies in refining.gemspec
gemspec
<file_sep>/lib/refining.rb
require "refining/version"
require "refining/core_ext/class"
module Refining
end
<file_sep>/lib/refining/core_ext/class.rb
class Class
def refining(topic, &block)
raise "refining needs block" unless block
klass = self
const_set topic, Module.new {
refine klass do
module_eval(&block)
end
}
end
end
<file_sep>/README.md
# Refining
This gem defines `Class#refining`.
`Class#refining` is helper of defining refinement module at inner class.
### before
```ruby
class User
module AdministratorRoll
refine User do
def delete_post(name)
"Delete: #{name}"
end
end
end
end
class DeletePostContext
using User::AdministratorRoll
def execute
user = User.new
user.delete_post
end
end
```
### after
```ruby
require 'refining'
class User
refining :AdministratorRoll do
def delete_post(name)
"Delete: #{name}"
end
end
end
class DeletePostContext
using User::AdministratorRoll
def execute
user = User.new
user.delete_post
end
end
```
## Installation
Add this line to your application's Gemfile:
gem 'refining'
And then execute:
$ bundle
Or install it yourself as:
$ gem install refining
## Contributing
1. Fork it ( https://github.com/joker1007/refining/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create a new Pull Request
<file_sep>/spec/refining_spec.rb
require 'spec_helper'
class Foo
refining :HasName do
def name
"foo"
end
end
end
describe Foo do
context "Using Foo::HasName" do
using Foo::HasName
subject { Foo.new.name }
it { is_expected.to eq "foo" }
end
context "no Using" do
subject { Foo.new.name }
it { expect{ subject }.to raise_error(NoMethodError) }
end
end
|
fcc201bf9cfc86520070b6f3c47958ae79368a7a
|
[
"Markdown",
"Ruby"
] | 5
|
Ruby
|
joker1007/refining
|
fc5fe452818a50af2aa2ae8e261666bf4e973249
|
a04d9cb19496f04bfe24689db02117d6a33d7617
|
refs/heads/master
|
<repo_name>khadirpatan/moviesearch<file_sep>/script/script.js
$(document).ready( ()=>{
$('#inputName , #inputYear').keypress(function(e) {
var key = e.which;
if (key == 13) // the enter key code
{
$('#search').click();
return false;
}
});
// clearing all values in form on click
$("#reset").click(function(){
$("#inputYear").val("");
$("#inputName").val("");
$(".output").empty();
});
// clearing all values in form on click, hiding year input, changing placeholder
$("#idLink").click(function(){
$("#inputYear").hide();
$("#inputName").val("");
$(".output").empty();
$("#inputName").attr('placeholder', 'ImdbId..');
});
// clearing all values in form on click, displaying year input, changing placeholder
$("#titleLink").click(function(){
if($('#inputYear').is(':hidden')) {
$("#inputYear").show();
$("#inputName").val("");
$("#inputYear").val("");
$(".output").empty();
}
$("#inputName").attr('placeholder', 'Title..');
});
let getcard =(data)=>{
const poster= data.Poster == "N/A" ? "images/poster.jpg" : data.Poster;
let output= `
<div class="col-sm-6 col-md-4 col-lg-3 col-10 posterCard">
<div class="card" style="margin-bottom:10px" >
<img class="card-img-top img-fluid" id="outputImg2" style="" src="${poster}" alt="Card image cap">
<div class="card-body text-center" style="">
<p class="card-text">
${data.Title}<hr>
Year : ${data.Year}<br>
Type : ${data.Type}<br>
<b>ImdbID: ${data.imdbID}<br></b>
</p>
</div>
</div>
</div>`;
$('.output').append(output);
return(output);
}
$("#search").click(function(){
var placeholder = $("#inputName").attr('placeholder');
$(".output").empty();
// Movie serach based on title and year
if( placeholder == 'Title..'){
$.ajax({
type : 'GET',
datatype : 'json',
async:true,
url :' https://www.omdbapi.com/?apikey=133949cb&s='+ $("#inputName").val() ,
success : (data) =>{
if (data.Response=="False"){
let output= `<div class=msg >No details found</div>`
$('.output').append(output); };
if ( data.Response=="True"){
let movieArray=data.Search;
if($("#inputYear").val()){
var isFound=false;
for(currentMoive in movieArray){
if(movieArray[currentMoive].Year== $("#inputYear").val()){
isFound=true;
let data=movieArray[currentMoive];
getcard(data);
}
}
if(isFound==false){
let output=`<div class=msg >Please check the Entered Parameters</div> `
$('.output').append(output);
}
}
if(!$("#inputYear").val()){
for(currentMoive in movieArray){
let data=movieArray[currentMoive];
getcard(data);
}
}
}
},
error : (errorMsg)=>{
let output=`<div class=msg >We cant process your request right now</div>`
$('.output').append(output);
},
});
}
//if condition ends
//moive search based on ImdbID
else{
$.ajax({
type : 'GET',
datatype : 'json',
async:true,
url :' https://www.omdbapi.com/?apikey=133949cb&i='+ $("#inputName").val() ,
success : (data) =>{
if (data.Response=="False"){
let output=`<div class=msg > <b>Enter valid ImdbID</b></div>`
$('.output').append(output);
}
else if ( data.Response=="True"){
const poster= data.Poster == "N/A" ? "images/poster.jpg" : data.Poster;
let output= `
<div class="col-sm-6 col-md-6 col-lg-4 col-10 posterCard">
<div class="card" >
<img class="card-img-top img-fluid" id="outputImg" style="" src="${poster}" alt="Card image cap">
<div class="card-body text-center">
<p class="card-text">
<h5>${data.Title}</h5><hr>
Year : ${data.Year}<br>
Type : ${data.Type}<br>
Rating : ${data.imdbRating}<br>
<b>ImdbID: ${data.imdbID}<br></b>
<br>
</p>
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#moreData">
more details...
</button>
<!-- Modal -->
<div class="modal fade" id="moreData" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog " role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">${data.Title}</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<img class="card-img-top img-fluid" id="modalOutputImg" style="height:200px; width:200px" src="${poster}" alt="Card image cap">
<div class="card-body" style="text-align:left">
<table class="table">
<tbody>
<tr>
<td>Title </td>
<td>${data.Title}</td>
</tr>
<tr>
<td> Year</td>
<td>${data.Year}</td>
</tr>
<tr>
<td>Type</td>
<td>${data.Type}</td>
</tr>
<tr>
<td>Genre</td>
<td>${data.Genre}</td>
</tr>
<tr>
<td>Actors</td>
<td>${data.Actors}</td>
</tr>
<tr>
<td>Director</td>
<td>${data.Director}</td>
</tr>
<tr>
<td>Writer</td>
<td>${data.Writer}</td>
</tr>
<tr>
<td>Language</td>
<td>${data.Language}</td>
</tr>
<tr>
<td>imdbRating</td>
<td>${data.imdbRating}</td>
</tr>
<tr>
<td>imdbVotes</td>
<td>${data.imdbVotes}</td>
</tr>
<tr>
<td>Runtime</td>
<td>${data.Runtime}</td>
</tr>
<tr>
<td>Production</td>
<td>${data.Production}</td>
</tr>
<tr>
<td>Released</td>
<td>${data.Released}</td>
</tr>
<tr>
<td>Website</td>
<td>${data.Website}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</p>
</div>
</div>
</div>
</div>`;
$('.output').append(output);
}
},
error : (errorMsg)=>{
let output=`<div class=msg >We cant process your request right now</div>`
$('.output').append(output);
},
});
}
});
});
|
6eaea1bcd08614ebc1084f0b99f86a2c1b27f276
|
[
"JavaScript"
] | 1
|
JavaScript
|
khadirpatan/moviesearch
|
8f9f44f81da1daba901881c1c3b90acd47cb2bf4
|
75169bea01662d750e3e6d1f64a104bf62a1d185
|
refs/heads/master
|
<file_sep>class Animal {
constructor() {}
giveVoice() {
console.log(`Nazywam sie ${this.name}!`);
}
}
class Dog extends Animal {
constructor() {
super(name);
}
giveVoice() {
super.giveVoice();
}
eat() {
console.log('yummy');
}
}
const pies = new Dog('reksio');
pies.giveVoice();<file_sep>function solution(A) {
let zen = Math.floor(Math.random()*6);
let ten = A[zen]*A[zen]*A[zen];
let men = ten.toString();
let find = men.replace('1', '');
let ans = parseInt(find);
console.log(men);
console.log(find);
console.log(ans);
}
let A = [25, 10, 25, 10, 32];
let B = [7, 15, 6, 20, 5, 10]
solution(A);
solution(B);<file_sep>function myFunction() {
let a = prompt('write value a');
let b = prompt('write value b');
let value =(a*a)-(2*a*b)-(b*b);
if ((a != null) && (b != null)) {
if(value>0) {
document.getElementById("demo").innerHTML='This phrase (a^2)-2ab-(b^2) is equal to: '+ value + '. The result is positive';
console.log('This value:(a^2)-2ab-(b^2) is is equal to: '+ value + '. The result and is positive.');
}
else if(value<0) {
document.getElementById("demo").innerHTML='This phrase (a^2)-2ab-(b^2) is equal to: '+ value + '. The result is negative';
console.log('This value:(a^2)-2ab-(b^2) is is equal to: '+ value + '. The result is negative');
}
else {
document.getElementById("demo").innerHTML='This phrase (a^2)-2ab-(b^2) is equal zero: ' + value;
console.log('This value:(a^2)-2ab-(b^2) is is equal to: '+ value + '. The result is zero');
}
}
else {
document.getElementById("demo").innerHTML='no valid entered value b or/and a';
console.log('no valid entered value b or/and a');
}
}
document.getElementById("value").addEventListener("click",myFunction);
<file_sep>// 1. The combination of two strings using the + operator is a very easy task.
// Another way is to use the concat or join method, but what if we could not use
// any of these options? Your task will be to create two variables with Hello and
// World values, and then combine them with a method other than those mentioned above.
const firstWord = 'Hello';
const secondWord = 'World';
const sumStrings = `${firstWord} ${secondWord}`;
console.log(sumStrings);
// or
const sumStrings = (firstWord = 'Hello', secondWord = 'World') =>
console.log(`${firstWord} ${secondWord}`);
sumStrings();
// 2. Create a multiply function that will return the result of the multiplication
// operation of two values a and b. We want the result of such a call to be also
// correct - you can assume that if the user does not provide any parameter,
// it is to be replaced 1. Do not use conditional instructions !
const multiply = (multi1 , multi2 = 1) => console.log(multi1 * multi2);
multiply(5);
multiply(2,5);
multiply(6,6);
// 3. Write an average function that calculates the arithmetic mean of all arguments
// that will be passed to it. Assume that the arguments will always be numbers
const average = (...num) => console.log( num.reduce( (a, b) => a + b ) / num.length );
average(1);
average(1, 3);
average(1, 3, 6, 6);
// [1, 4, 'Iwona', false, 'Nowak']. Your task is to use destructuring to get
// the firstname and lastname variables from the array.
const array = [1, 4, 'Iwona', false, 'Nowak'];
const [ , ,name, ,surname] = array;
const fullName = `${name} ${surname}`
console.log(fullName);<file_sep>let text = "Velociraptor is a dinosaur.";
let dinosaur = "Triceratops";
let dinosaurUppercase = dinosaur.toUpperCase();
let newText = text.replace("Velociraptor", dinosaur);
console.log(newText.length / 2);
console.log(newText.slice(0, 72));
<file_sep>let dog = {
sound: 'woof',
talk: function(){
console.log(this.sound);
document.getElementById("spot").innerHTML = this.sound;
}}
/*let talkFunction = dog.talk
let boundFunction = talkFunction.bind(dog)
talkFunction()
boundFunction()
let boundedFunction = dog.talk.bind(dog)
boundedFunction()*/
let button = document.getElementById('myButton')
button.addEventListener('click', dog.talk.bind(dog))
<file_sep>document.querySelector('.pres').addEventListener('click', function(){
this.classList.toggle('pres')});
document.querySelector('.prez').addEventListener('click', function(){
this.classList.toggle('prez')});
document.querySelector('.pren').addEventListener('click', function(){
this.classList.toggle('pren');});
document.querySelector('.pref').addEventListener('click', function(){
this.classList.toggle('pref');});
<file_sep># JS-exercises
live on Codepen:
+ <a href="https://codepen.io/TomaszPieta/pen/ZMmovr">js-stone-paper-scisors</a>
+ <a href="https://codepen.io/TomaszPieta/pen/bxoLJZ">js-aos-animations</a>
+ <a href="https://codepen.io/TomaszPieta/pen/YjzZRV">js-bottle-of-wine</a>
+ <a href="https://codepen.io/TomaszPieta/pen/oyWYxV">js-random-query</a>
+ <a href="https://codepen.io/TomaszPieta/pen/eKWRrO">js-color-squares</a>
+ <a href="https://codepen.io/TomaszPieta/pen/zabwaO">js-dog-api</a>
+ <a href="https://codepen.io/TomaszPieta/pen/GGjdjp">js-memory-game</a>
+ <a href="https://codepen.io/TomaszPieta/pen/ELqRey">js-todo</a>
+ <a href="https://codepen.io/TomaszPieta/pen/LmwrJy">js-tomato</a>
+ <a href="https://codepen.io/TomaszPieta/pen/QroZqE">js-country-finder</a>
+ <a href="https://codepen.io/TomaszPieta/pen/Zomdez">js-local-storage-counter</a>
+ <a href="https://codepen.io/TomaszPieta/pen/vjQwxN">js-local-storage</a>
+ <a href="https://codepen.io/TomaszPieta/pen/aqJPWW">js-input-form</a>
+ <a href="https://codepen.io/TomaszPieta/pen/mXWaMG">js-classlist-add</a>
+ <a href="https://codepen.io/TomaszPieta/pen/eVWggb">js-slide-text</a>
+ <a href="https://codepen.io/TomaszPieta/pen/rJmWxG">js-edit-real</a>
+ <a href="https://codepen.io/TomaszPieta/pen/BYJeQw">js-query-selector</a>
+ <a href="https://codepen.io/TomaszPieta/pen/oEPVKN">js-event-delegation</a>
+ <a href="https://codepen.io/TomaszPieta/pen/pLVOoP">js-progress-bar</a>
+ <a href="https://codepen.io/TomaszPieta/pen/eMrjQR">js-autohide-nav</a>
+ <a href="https://codepen.io/TomaszPieta/pen/aYGaZa">js-smooth-scroll</a>
<file_sep>function przelicz(kwota){
return 1.23*kwota}
var kwota = prompt("podaj wartość");
document.getElementById("span").innerHTML = "Cena po dodaniu podatku 23% wynosi " + przelicz(kwota) + " złotych.";<file_sep>function time(){
const event = (
<div>
<h1>Current Time:</h1>
<h2>{new Date().toLocaleTimeString()}</h2>
</div>
);
ReactDOM.render(
event,
document.getElementById("root")
);
}
setInterval(time, 1000);
<file_sep><!DOCTYPE html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="style.css">
<title>JS Local Storage</title>
</head>
<body>
<div>LocalStorage: <span id="text"></span></div>
<p><button onclick="counter()" type="button">Click me!</button></p>
<div id="result"></div>
<p>Click the button to see the counter increase.</p>
<p>Close the browser tab (or window), and try again, and the counter will continue to count (is not reset).</p>
<p><button onclick="remove()" type="button">Remove LocalStorage</button></p>
<script type="text/javascript" src="script.js"></script>
</body>
</html><file_sep>function progress(){
let top = window.scrollY;
docHeight = document.documentElement.scrollHeight;
winHeight = window.innerHeight;
let totalScroll = (top/(docHeight-winHeight))*100;
document.querySelector('.fill').style.width = totalScroll + '%';}
window.addEventListener('scroll', progress);<file_sep>You have to create a function that takes a positive integer number and returns the biggest number formed by the same digits. If no bigger number can be composed using those digits, return -1.<file_sep>function sumStrings(a,b){
let numbers = (parseInt(a)+parseInt(b)).toString();
console.log(numbers);}
sumStrings('1','3');<file_sep>$(document).ready(function() {
colorNum = 1;
let quotes = [{
author: "Dr. Seuss",
quote: "Don't cry because it's over, smile because it happened."
}, {
author: "<NAME>",
quote: "Be yourself; everyone else is already taken."
}, {
author: "<NAME>",
quote: "He who has a why to live can bear any how."
}, {
author: "<NAME>",
quote: "It is better to be hated for what you are than to be loved for what you are not."
}, {
author: "<NAME>",
quote:"There are only two ways to live your life. One is as though nothing is a miracle. The other is as though everything is a miracle."
}, {
author: "Dr. Seuss",
quote: "I like nonsense, it wakes up the brain cells. Fantasy is a necessary ingredient in living."
}, {
author: "<NAME>",
quote: "Never put off till tomorrow what may be done day after tomorrow just as well."
}, {
author: "<NAME>",
quote: "I love deadlines. I love the whooshing noise they make as they go by."
}, {
author: "<NAME>",
quote: "Do what you can, with what you have, where you are."
}, {
author: "Rumi",
quote: "Let the beauty of what you love be what you do."
}, {
author: "<NAME>",
quote: "Your pain is the breaking of the shell that encloses your understanding."
}, {
author: "<NAME>",
quote: "Life is not a problem to be solved, but a reality to be experienced."
}, {
author: "<NAME>",
quote: "Immaturity is the incapacity to use one's intelligence without the guidance of another."
}];
function getRandomInt(min,max) {
min = Math.ceil(min);
max = Math.ceil(max);
return Math.floor(Math.random()*(max-min))+min;
}
function changeColor() {
let colors = ['red', 'blue', 'orange', 'green', 'purple'];
if(colorNum == colors.length)
colorNum = 0;
let css =
$(".quote").css("transition","color 3s ease" ).css("color", colors[colorNum]);
$("button").css("transition", "background-color 3s ease").css("background-color", colors[colorNum]);
$("body").css("transition", "background-color 3s ease").css("background-color", colors[colorNum]);
}
function obtainQuote() {
let number = getRandomInt(0,quotes.length);
$('#quote').html(quotes[number].quote);
$('#author').html(quotes[number].author);
}
obtainQuote();
$('#gen').on('click', function() {
obtainQuote();
changeColor();
colorNum++
})
})<file_sep>var zmienna1 = 12;
var zmienna2 = 16;
var zmienna3 = zmienna1+zmienna2;
function wypisz(){
document.getElementById("wstaw1").innerHTML = "Zmienna pierwsza to "+zmienna1;
document.getElementById("wstaw2").innerHTML = "Zmienna druga to "+zmienna2;
document.getElementById("wstaw3").innerHTML = "Suma dwoch zmiennych to "+zmienna3;
}
<file_sep>var akapit = document.getElementById('klasa');
akapit.contentEditable="true";
akapit.designMode="on";<file_sep>Given the string representations of two integers, return the string representation of the sum of those integers<file_sep>function klik(){document.getElementById("change").innerHTML = "Inny tekst";}
function klikaj(){document.getElementById("change").innerHTML = "Kolejny tekst";}
<file_sep>let firstName = 'John';
let hobby = 'browsing the web with you';
function sayHi(){
console.log(`Hello ${firstName}, are you into ${hobby}?`)}
const marcin = {
firstName: 'Marcin', age: 23,
hobby: 'Weights lifting'}
const sylwia = {
firstName: 'Sylwia', gender: 'female',
hobby: 'Reading books',}
sayHi();
sayHi.call(marcin);
sayHi.call(sylwia);
const sayHiToMarcin = sayHi.bind(marcin);
sayHiToMarcin();<file_sep>let num = 9;
while (num >=1) {
if (num===2) {
let two = `<p>${num} bottles of juice on the wall! ${num} bottles of juice! Take one down, pass it around… ${num-1} bottle of juice on the wall!</p>`;
document.write(two);
}
else if(num===1) {
let one = `<p>${num} bottle of juice on the wall! ${num} bottle of juice! Take one down, pass it around… ${num-1} bottles of juice on the wall!</p>`;
document.write(one);
} else {
let other = `<p>${num} bottles of juice on the wall! ${num} bottles of juice! Take one down, pass it around… ${num-1} bottles of juice on the wall!</p>`;
document.write(other);
}
num -=1;
}<file_sep>localStorage.setItem('lastName', "Smith");
document.getElementById('text').innerHTML = localStorage.getItem('lastName');
let counter =()=> {
if (localStorage.clicks) {
localStorage.clicks = Number(localStorage.clicks)+1;
} else {
localStorage.clicks = 1;
}
document.getElementById("result").innerHTML = "You have clicked the button " + localStorage.clicks + " time(s).";
}
let remove =()=> {
localStorage.clicks = 0;
document.getElementById("result").innerHTML = "LocalStorage has been deleted.";
}<file_sep>function triangle() {
let h = prompt("Please enter height your triangle [m]");
let a = prompt("Please enter basic your triangle [m]");
let triangleArea = (h * a) / 2;
if ((h != null) && (a != null)) {
document.getElementById("demo").innerHTML =
"Triangle field with base: " + a + "m and height: " + h + "m is equal to: " + triangleArea + "m2";
}
}
<file_sep>const doggos = document.querySelector('.doggos');
fetch("https://dog.ceo/api/breeds/image/random")
.then(res=>res.json())
.then(res=>{
const img = document.createElement('img');
img.src = res.message;
img.alt = "cute dog";
doggos.appendChild(img)
});
<file_sep>function alfa(word){
let spell = word.toString().split('').sort((a, b) => b-a).join('');
(spell==word) ? (console.log(-1)) : (console.log(spell));
}
alfa(2017);<file_sep>function hide(){
var sal = document.getElementById("b1").style;
var sel = document.getElementById("1").style;
if (sel.color == "black"){
document.getElementById("b1").innerHTML="Pokaz";
sel.height="0px";
sel.padding="0";
sel.color="transparent";
sel.fontSize="0";
sal.margin="0 auto";
sal.borderTopRightRadius="0";
sal.borderTopLeftRadius="0";
sal.borderBottomRightRadius="5px";
sal.borderBottomLeftRadius="5px";
}
else{
document.getElementById("b1").innerHTML="Ukryj";
sel.height="190px";
sel.padding="1.5em";
sel.color="black";
sel.fontSize="100%";
sal.margin="-70px auto";
sal.borderRadius="3px";
}}<file_sep>let parent = document.getElementById('parent');
let widget = document.getElementById('widget');
let mouseDowns = Observable.fromEvent(widget, 'mousedown');
let parentMouseMoves = Observable.fromEvent(parent, 'mousemove');
let parentMouseMoveUps = Observable.fromEvent(parent, 'mouseup');
let drags = mouseDowns.
map(function(e){
return parentMouseMoves.
takeUntil(parentMouseUps);}).
concatAll();
let subscription = drags.forEach(
function(e){
widget.style.left = e.clientX + 'px';
widget.style.top = e.clientY + 'px';
}, function onError(error) {
}, function onCompleted() {
});<file_sep>const form = document.querySelector('.form');
const container = document.querySelector('.tomato-container');
form.addEventListener('submit', event => {
event.preventDefault();
const div = document.createElement('div');
div.textContent = 'tomato!!';
div.style.color = 'tomato';
div.addEventListener('click', ({ target }) => {
target.parentNode.removeChild(target);
})
container.appendChild(div);
})<file_sep>function solution(A) {
A = A.toString();
let ln = A.length;
let a1 = A[0];
let a2 = A[A.length-1];
let a3 = A[1];
let a4 = A[A.length-2];
let a5 = A[2];
let a6 = A[A.length-3];
let a7 = A[3];
let a8 = A[A.length-4];
let a9 = A[4];
let result = null;
if(ln===9){
result = parseInt(`${a1}${a2}${a3}${a4}${a5}${a6}${a7}${a8}${a9}`);
} else if(ln===8){
result = parseInt(`${a1}${a2}${a3}${a4}${a5}${a6}${a7}${a8}`);
} else if(ln===7){
result = parseInt(`${a1}${a2}${a3}${a4}${a5}${a6}${a7}`);
} else if(ln===6){
result = parseInt(`${a1}${a2}${a3}${a4}${a5}${a6}`);
} else if(ln===5){
result = parseInt(`${a1}${a2}${a3}${a4}${a5}`);
} else if(ln===4){
result = parseInt(`${a1}${a2}${a3}${a4}`);
} else if(ln===3){
result = parseInt(`${a1}${a2}${a3}`);
} else if(ln===2){
result = parseInt(`${a1}${a2}`);
} else if(ln===1){
result = parseInt(`${a1}`);
} else {
return null;
}
console.log(result);
}
solution(123456789);
|
f68ecd1e26b4a50e213e77177d3f95ec6c3f313f
|
[
"JavaScript",
"HTML",
"Markdown"
] | 29
|
JavaScript
|
TomaszPieta/JS-exercises
|
9f337bbb86d67465ec390bd5882e1edb156c846d
|
f314df230f1acf78ae8d98ab48e1bf9c98fd0034
|
refs/heads/master
|
<repo_name>Ash-oi/string-services<file_sep>/public/js/scripts.js
function splitString() {
let body = document.getElementById('input-body').value;
let character = document.getElementById('split-on-character').value;
let isRegex = document.getElementById("split-regex").checked;
let str = '';
if (character.length === 0) {
return false;
} else if (isRegex) {
try {
let splitRegex = new RegExp(character, 'g');
body.split(splitRegex).map(param => str += param+'\n')
document.getElementById('input-body').value = str;
} catch (error) {
alert("Not valid regex, or something else, who knows. ")
}
} else {
body.split(character).map(param => str += param+'\n')
document.getElementById('input-body').value = str;
}
}
function urlDecode() {
document.getElementById('input-body').value = decodeURIComponent(document.getElementById('input-body').value);
}
function urlEncode() {
document.getElementById('input-body').value = encodeURIComponent(document.getElementById('input-body').value);
}
function base64Encode() {
document.getElementById('input-body').value = btoa(document.getElementById('input-body').value);
}
function base64Decode() {
document.getElementById('input-body').value = atob(document.getElementById('input-body').value);
}
function isThisRegex(string) {
try {
let test = new RegExp(string)
} catch (error) {
return false;
}
return true;
}
function findAndReplace() {
let body = document.getElementById('input-body').value;
let character = document.getElementById('replace-on-character').value;
let withCharacter = document.getElementById('replace-with-character').value;
let isRegex = document.getElementById("replace-regex").checked;
if (character.length === 0) {
return false;
} else {
if (isRegex) { // regex
try {
let replaceRegex = new RegExp(character, 'g');
document.getElementById('input-body').value = body.replace(replaceRegex, withCharacter);
} catch (error) {
alert("Not valid regex, or something else, who knows. ")
}
} else { // not regex
let replaceRegex = new RegExp(character, 'g');
document.getElementById('input-body').value = body.replace(replaceRegex, withCharacter);
}
}
}
function jsonFormat() {
let body = document.getElementById('input-body').value
try {
let parsedBody = JSON.parse(body)
document.getElementById('input-body').value = JSON.stringify(parsedBody, null, 2)
} catch (err) {
alert("Invalid JSON (need quotes around keys etc.)");
}
}
//https://api.github.com/repos/AshleyMcVeigh/string-services/commits
function loadLastCommit() {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.github.com/repos/AshleyMcVeigh/string-services/commits');
xhr.onload = function() {
if (xhr.status === 200) {
const parsed = JSON.parse(xhr.response)
let date = new Date(parsed[0].commit.committer.date)
let dateDisplay = document.getElementById('lastUpdate')
dateDisplay.innerText = `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`
dateDisplay.href = parsed[0].html_url;
}
else {
alert('Request failed. Returned status of ' + xhr.status);
}
};
xhr.send();
}<file_sep>/README.md
#string-services
use `pug index.pug -w -P --out ./public/` to compile the pug files to html inside the "public" folder
|
9fe349655d870d5757f8406b5a181caf2d17e081
|
[
"JavaScript",
"Markdown"
] | 2
|
JavaScript
|
Ash-oi/string-services
|
3f717d9bf8d1a67a21f859787bbefa3fc5ba2ad0
|
ff11c9db0dfc4ef9e801e0d840f649581697d442
|
refs/heads/master
|
<repo_name>sanyco92/successfactors<file_sep>/src/main/java/pages/AddAlarmPage.java
/**
* Created by aleksandr.kot on 4/26/18.
*/
package pages;
import io.appium.java_client.AppiumDriver;
import io.appium.java_client.MobileElement;
import io.appium.java_client.ios.IOSElement;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.support.FindBy;
import support.Time;
public class AddAlarmPage extends BasePage {
@FindBy(xpath = "//XCUIElementTypePickerWheel[1]")
private IOSElement hoursWheel;
@FindBy(xpath = "//XCUIElementTypePickerWheel[2]")
private IOSElement minutesWheel;
@FindBy(xpath = "//XCUIElementTypePickerWheel[3]")
private IOSElement timeFormatWheel;
@FindBy(name = "ADD ALARM")
private IOSElement addAlarmButton;
@FindBy(name = "Ringtones")
private IOSElement ringtonesCell;
@FindBy(name = "Tasks")
private IOSElement tasksCell;
@FindBy(name = "Alarm Description")
private IOSElement descriptionCell;
@FindBy(xpath = "//XCUIElementTypeCell[1]")
private IOSElement ringroneCell;
@FindBy(name = "Face Recognition")
private IOSElement faceRecognitionCell;
@FindBy(name = "Add Alarm")
private IOSElement backButton;
@FindBy(xpath = "//XCUIElementTypePicker/XCUIElementTypePickerWheel")
private IOSElement difficultyPicker;
@FindBy(name = "Toolbar Done Button")
private IOSElement toolbarDoneButton;
public AddAlarmPage(AppiumDriver<MobileElement> driver) {
super(driver);
}
public void setHoursWheel(String hours) {
hoursWheel.sendKeys(hours);
}
public void setMinutesWheel(String minutes) {
minutesWheel.sendKeys(minutes);
}
public void setTimeFormatWheel(String timeFormat) {
timeFormatWheel.sendKeys(timeFormat);
}
public void setTimeWheel(Time time) {
hoursWheel.sendKeys(time.getHours());
minutesWheel.sendKeys(time.getMinutes());
if (!time.getTimeFormat().equals("24h"))
timeFormatWheel.sendKeys(time.getTimePeriod());
}
public void setDescription(String text) {
descriptionCell.sendKeys(text);
toolbarDoneButton.click();
}
public void clickAddAlarmButton() {
addAlarmButton.click();
}
public void clickRingtonesCell() {
ringtonesCell.click();
}
public void clickTasksCell() {
tasksCell.click();
}
public void clickDoneButton() {
toolbarDoneButton.click();
}
public void clickBackButton() {
backButton.click();
}
public void selectRingtone() {
ringroneCell.click();
}
public void selectTask(String name) {
MobileElement cell = driver.findElement(By.name(name));
cell.click();
try {
driver.findElement(By.name("OK")).click();
} catch (NoSuchElementException e) {
System.out.println("There's no request for the Camera permission");
}
}
public void setDifficulty(String difficulty) {
difficultyPicker.sendKeys(difficulty);
toolbarDoneButton.click();
}
public String getMinutes() {
return minutesWheel.getText();
}
public void incrementAlarmTimeByMinute() {
int currentMinutes = Integer.valueOf(getMinutes().substring(0, Math.min(getMinutes().length(), 2))) + 1;
String strCurrentMinutes;
if (currentMinutes < 10) {
strCurrentMinutes = "0" + String.valueOf(currentMinutes);
setMinutesWheel(strCurrentMinutes);
} else setMinutesWheel(String.valueOf(currentMinutes));
}
}
<file_sep>/src/main/java/support/Time.java
package support;
/**
* Created by aleksandr.kot on 8/14/18.
*/
public class Time {
private String hours;
private String minutes;
private String timeFormat;
private String timePeriod;
private static final String[] timePeriods = {"AM", "PM"};
public Time(String timeFormat) {
this.timeFormat = timeFormat;
if (timeFormat == "12h") {
this.timePeriod = timePeriods[(int) (Math.random() * 2)];
this.hours = String.valueOf((int) (Math.random() * 12 + 1));
String minutesValue = String.valueOf((int) (Math.random() * 60));
if (Integer.parseInt(minutesValue) < 10)
this.minutes = "0" + minutesValue;
else
this.minutes = minutesValue;
}
else if (timeFormat == "24h") {
String hoursValue = String.valueOf((int) (Math.random() * 24));
String minutesValue = String.valueOf((int) (Math.random() * 60));
if (Integer.parseInt(hoursValue) < 10) {
this.hours = "0" + hoursValue;
}
else this.hours = hoursValue;
if (Integer.parseInt(minutesValue) < 10) {
this.minutes = "0" + minutesValue;
}
else this.minutes = minutesValue;
}
else System.out.println("Wrong time format!");
}
public String getHours() {
return hours;
}
public String getMinutes() {
return minutes;
}
public String getTimeFormat() {
return timeFormat;
}
public String getTimePeriod() {
return timePeriod;
}
public void setHours(String hours) {
this.hours = hours;
}
public void setMinutes(String minutes) {
this.minutes = minutes;
}
public void setTimeFormat(String timeFormat) {
this.timeFormat = timeFormat;
}
public void setTimePeriod(String timePeriod) {
this.timePeriod = timePeriod;
}
}
<file_sep>/src/main/java/pages/AlarmStartedPage.java
/**
* Created by aleksandr.kot on 4/26/18.
*/
package pages;
import io.appium.java_client.AppiumDriver;
import io.appium.java_client.MobileElement;
import io.appium.java_client.TouchAction;
import io.appium.java_client.ios.IOSElement;
import org.openqa.selenium.By;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.ui.ExpectedConditions;
public class AlarmStartedPage extends BasePage {
@FindBy(name = "ic_sleep_close")
private IOSElement cancelSliderButton;
@FindBy(name = "ic_sleep_checkmark")
private IOSElement performSliderButton;
public AlarmStartedPage(AppiumDriver<MobileElement> driver) {
super(driver);
}
public void swipeCancelSlider() {
TouchAction action = new TouchAction(driver);
action.tap(cancelSliderButton).waitAction(3000).moveTo(
cancelSliderButton.getCoordinates().inViewPort().getX() + 250,
cancelSliderButton.getCoordinates().inViewPort().getY()).perform();
}
public void swipePerformSlider() {
TouchAction action = new TouchAction(driver);
wait.until(ExpectedConditions.presenceOfElementLocated(By.name("ic_sleep_checkmark")));
System.out.println("Alarm Fire!");
action.tap(performSliderButton).waitAction(3000).moveTo(
performSliderButton.getCoordinates().inViewPort().getX() + 250,
performSliderButton.getCoordinates().inViewPort().getY()).perform();
}
}
<file_sep>/src/main/java/pages/PerformTasksPage.java
/**
* Created by aleksandr.kot on 4/26/18.
*/
package pages;
import io.appium.java_client.AppiumDriver;
import io.appium.java_client.MobileElement;
import io.appium.java_client.TouchAction;
import io.appium.java_client.ios.IOSElement;
import org.openqa.selenium.support.FindBy;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class PerformTasksPage extends BasePage {
@FindBy(xpath = "//XCUIElementTypeCell/XCUIElementTypeStaticText[2]")
private IOSElement equation;
@FindBy(name = "Answer")
private IOSElement answerField;
public PerformTasksPage(AppiumDriver<MobileElement> driver) {
super(driver);
}
public String getEquationText() {
return equation.getText();
}
public String solveEquation(String equation) throws ScriptException {
String answer;
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
System.out.println("The answer is " + engine.eval(equation));
answer = String.valueOf(engine.eval(equation));
return answer;
}
public void enterAnswer(String answer) {
answerField.sendKeys(answer);
}
}
|
91de264095b17d700d913177d0b970a30022f1b4
|
[
"Java"
] | 4
|
Java
|
sanyco92/successfactors
|
158884acd9c92352622b45070efcc5a47b17888b
|
4ada90fa129b044fc254227e9fa3e5498a10fffa
|
refs/heads/main
|
<file_sep>#! /bin/bash
sudo yum update
sudo yum install -y httpd
sudo chkconfig httpd on
sudo service httpd start
|
7264f1cb94b7349c731eb874f45f4de4f7f36bb3
|
[
"Shell"
] | 1
|
Shell
|
bridgecrew-perf4/terraform_test-6
|
cb9281d83c925cca4138d3c1b69025c6251ba0d4
|
406b4705d0cab342f620f7549b3fca0f77ae3c0d
|
refs/heads/master
|
<repo_name>BastrakovDmitry/Tasker<file_sep>/src/ru/Bastrakov/Tasker/Main.java
package ru.Bastrakov.Tasker;
import ru.Bastrakov.Tasker.GUI.GUIFrame;
public class Main {
public static GUIFrame frame;
public static void main(String[] args) {
frame = new GUIFrame();
}
}
<file_sep>/src/ru/Bastrakov/Tasker/WorkWithFiles/SLFile.java
package ru.Bastrakov.Tasker.WorkWithFiles;
import java.io.*;
import java.util.Scanner;
public class SLFile {
public static void save(String[] adressTaskData) throws IOException {
String adress = adressTaskData[0];
String task = adressTaskData[1];
String data = adressTaskData[2];
File file = new File(adress);
FileWriter fileWriter = new FileWriter(file, false);
fileWriter.write(task + ";\n");
fileWriter.write(data);
fileWriter.flush();
}
public static String[] load(String adress) throws FileNotFoundException {
String result = "";
File file = new File(adress);
FileReader fileReader = new FileReader(file);
Scanner scan = new Scanner(fileReader);
while (scan.hasNextLine()) {
if (result == "") {
result = scan.nextLine() + "\n";
} else {
result = result + scan.nextLine() + "\n";
}
}
return result.substring(0, result.length() - 1).split(";\n");
}
}
<file_sep>/src/ru/Bastrakov/Tasker/Tasks/TaskTwo.java
package ru.Bastrakov.Tasker.Tasks;
import java.util.Arrays;
public class TaskTwo {
public static String expanded(int num) {
String result;
String[] str = Integer.toString(num).split("");
for (int i = 0; i < str.length - 1; i++) {
if (Integer.valueOf(str[i]) > 0) {
for (int j = i; j < str.length - 1; j++) {
str[i] += "0";
}
}
}
result = Arrays.toString(str);
result = result.substring(1, result.length() - 1).replace(", 0", "").replace(",", " +");
return result;
}
}
<file_sep>/README.md
# Tasker
Task_1:
Given two arrays of strings 1 and 2 return a new sorted array in lexicographical order of the strings of 1 which are substrings of strings of 2.
Example:
arp, live, strong
lively, alive, harp, sharp, armstrong
returns:
arp, live, strong
-------------------------------
Task_2:
You will be given a number and you will need to return it as a string in Expanded Form.
Example:
12
returns:
10 + 2
beware: input num int type!
|
82ea73ccae402622bdf9acd4b58cdbb265504f06
|
[
"Markdown",
"Java"
] | 4
|
Java
|
BastrakovDmitry/Tasker
|
090c7b0bdcabaa1b709e58971152902564fa065b
|
29ee65e8230c2e30e4cd67e89435186a5a3182a8
|
refs/heads/master
|
<file_sep>import java.util.LinkedList;
public class Hand
{
private LinkedList<Card> cardList = new LinkedList<Card>();
public Hand(){}
public void add(Card card)
{
cardList.addLast(card);
}
public void clear()
{
cardList.clear();
}
public LinkedList<Integer> count()
{
LinkedList<Integer> count = new LinkedList<Integer>();
count.add(0);
int tmp;
for(int i=0; i<cardList.size(); i++)
{
for (int j=0; j<count.size(); ++j)
{
tmp=count.get(j);
count.set(j, tmp+cardList.get(i).getPoints());
if(cardList.get(i).getPoints()==1)
{
count.add(tmp+11);
}
}
}
return count;
}
public int best()
{
LinkedList<Integer> count = new LinkedList<Integer>();
int best;
count=count();
best=count.get(0);
for(int i=1; i<count.size(); ++i)
{
if(best==21)
{
return best;
}
else if(count.get(i)<=21)
{
if(count.get(i)<=21 && count.get(i)>best)
{
best=count.get(i);
}
}
else
{
if(best>21 && count.get(i)<best)
{
best=count.get(i);
}
}
}
return best;
}
@Override
public String toString()
{
return cardList.toString();
}
}
<file_sep>public class BlackJack
{
private Deck deck;
private Hand playerhand;
private Hand bankHand;
public boolean gameFinished;
public BlackJack()
{
deck = new Deck(4);
bankHand = new Hand();
playerhand = new Hand();
try
{
reset();
}
catch (EmptyDeckException ex)
{
System.err.println(ex.getMessage());
System.exit(-1);
}
}
public void reset() throws EmptyDeckException
{
playerhand.clear();
bankHand.clear();
bankHand.add(deck.draw());
playerhand.add(deck.draw());
playerhand.add(deck.draw());
}
public String getPlayerHandString()
{
return (playerhand.toString() + " : " + playerhand.count());
}
public String getBankHandString()
{
return (bankHand.toString() + " : " + bankHand.count());
}
public int getPlayerBest()
{
return playerhand.best();
}
public int getBankBest()
{
return bankHand.best();
}
public boolean isPlayerWinner()
{
if(gameFinished)
{
if(getPlayerBest()<=21)
{
if(getBankBest()>21)
{
return true;
}
else if(getBankBest()>getPlayerBest())
{
return false;
}
else if(getBankBest()==getPlayerBest())
{
return true;
}
}
}
return false;
}
public boolean isBankWinner()
{
if(gameFinished)
{
if(getBankBest()<=21)
{
if(getPlayerBest()>21)
{
return true;
}
else if(getPlayerBest()>getBankBest())
{
return false;
}
else if(getBankBest()==getPlayerBest())
{
return true;
}
}
}
return false;
}
public boolean isGameFinished()
{
if(getBankBest()>=21)
{
return true;
}
if(getPlayerBest()>=21)
{
return true;
}
if(gameFinished)
{
return true;
}
return false;
}
public void playerDrawAnotherCard() throws EmptyDeckException
{
if(!gameFinished)
{
playerhand.add(deck.draw());
if(getPlayerBest()>21)
{
gameFinished=true;
}
}
}
public void bankLastTurn() throws EmptyDeckException
{
if(!gameFinished)
{
while(getBankBest()<getPlayerBest())
{
bankHand.add(deck.draw());
}
gameFinished=true;
}
}
}
<file_sep>import java.io.FileNotFoundException;
import java.io.File;
import java.util.Scanner;
public class Dictionary
{
private String[] wordsList;
public Dictionary(String fileName) throws FileNotFoundException
{
File file = new File(fileName);
if(!file.exists())
{
throw new FileNotFoundException();
}
Scanner scan = new Scanner(file);
int size = Integer.parseInt(scan.next());
wordsList = new String[size];
for(int i=0; i<size; ++i)
{
wordsList[i]=scan.next();
}
}
public Dictionary()
{
wordsList = new String[]{"abricot", "châtaigne", "groseille", "pomme", "tomate"};
}
public String[] getWordsList()
{
return wordsList;
}
public boolean isValidWord(String word)
{
boolean found=false;
for (int i=0; i<wordsList.length; i++)
{
if(word.equals(wordsList[i]))
{
found=true;
break;
}
}
return found;
}
}
<file_sep>import java.lang.Exception;
@SuppressWarnings("serial")
public class EmptyDeckException extends Exception
{
public EmptyDeckException()
{
super("Error, the deck has insuffisent cards");
}
}
|
77614812aaec60b41a08c9f969fd34deb6f397ff
|
[
"Java"
] | 4
|
Java
|
Squadella/TD_java
|
77ab9531f8200e162b2db5159851a6940afd6205
|
f443f0e4645e1f5c416bea89f8155973d7699fa8
|
refs/heads/master
|
<repo_name>sherzodv/ai<file_sep>/3dex.py
from random import *
from math import pi, sin, cos
from colorsys import hsv_to_rgb as h2r
from direct.showbase.ShowBase import ShowBase
from direct.task import Task
from panda3d.core import Point3
from panda3d.core import *
import numpy as np
import pandas as pd
from sklearn.datasets import load_iris
iris = load_iris()
def frange(start, stop, step):
while start < stop:
yield float(start)
start += step
class App(ShowBase):
def spinCameraTask(self, task):
t = task.time * 0.1
angleRadians = t * (pi / 180.0)
self.camera.setPos(10 * sin(t), 10 * cos(t), 0)
self.camera.lookAt(0, 0, 0)
return Task.cont
def grid(self, scene):
l = LineSegs()
for x in range(-10, 10):
for y in range(-10, 10):
l.setColor(0.1, 0.1, 0.1, 1.0)
l.setThickness(1)
l.moveTo(x, -10, 0)
l.drawTo(x, 10, 0)
l.moveTo(-10, x, 0)
l.drawTo(10, x, 0)
lp = NodePath(l.create(scene))
lp.setAntialias(AntialiasAttrib.MMultisample)
lp.reparentTo(scene)
def meshGrid(self, meshd, camera, scene):
lp = meshd.getRoot()
lp.reparentTo(scene)
lp.setDepthWrite(False)
lp.setTransparency(True)
lp.setTwoSided(True)
lp.setBin("fixed",0)
lp.setLightOff(True)
meshd.setBudget(1000)
meshd.begin(camera, scene)
for x in range(-10, 10):
for y in range(-10, 10):
meshd.segment(
(x, -10, 0),
(x, 10, 0),
randint(181,207),
10,
(1, 1, 1, 1)
)
meshd.end()
def create(self, scene, material):
for x in range(-5, 5):
for y in range(-5, 5):
for z in range(-5, 5):
rx = 0# random.randint(1, 10) / 10.0
ry = 0# random.randint(1, 10) / 10.0
rz = 0# random.randint(1, 10) / 10.0
p = self.loader.loadModel("sphere.bam")
p.reparentTo(scene)
p.setPos(x + rx, y + ry, z + rz)
p.setMaterial(material)
p.setScale(0.1)
def createM(self, h, s, v):
m = Material()
m.setShininess(0.9)
(r, g, b) = h2r(h, s, v)
m.setAmbient((r, g, b, 1))
m.setDiffuse((0.3, 0.3, 0.3, 1))
# m.setEmission((0.3, 0.1, 0.1, 1))
return m
def point(self, scene, location, material):
p = self.loader.loadModel("sphere.bam")
p.reparentTo(scene)
p.setPos(location[0], location[1], location[2])
p.setScale(0.1)
p.setMaterial(material)
return p
def showIris(self, iris, scene):
m1 = self.createM(0.3, 0.7, 0.5)
m2 = self.createM(0.1, 0.7, 0.5)
m3 = self.createM(0.7, 0.7, 0.5)
m = [m1, m2, m3 ]
for i in range(0, len(iris.data)):
item = iris.data[i]
label = iris.target[i]
x1 = item[0] * 2.5 - 10
y1 = item[1] * 2.5 - 10
z1 = item[2] * 2.5
x2 = item[0] * 2.5 - 20
y2 = item[1] * 2.5 - 20
z2 = item[3] * 2.5
self.point(scene, (x1, y1, z1), m[label])
self.point(scene, (x2, y2, z2), m[label])
def __init__(self):
ShowBase.__init__(self)
#self.taskMgr.add(self.spinCameraTask, "SpinCameraTask")
base.setBackgroundColor(0, 0, 0)
base.cam.setPos(0, -40, 10)
base.cam.lookAt(0, 0, 10)
scene = self.render
scene.setAntialias(AntialiasAttrib.MAuto)
#grid = Shader.load(Shader.SL_GLSL, vertex="grid.vert", fragment="grid.frag")
#scene.set_shader(grid)
aLight = AmbientLight('al')
aLightP = scene.attachNewNode(aLight)
aLightP.setPos(10, -20, 0)
dl = DirectionalLight('dl')
dlp = scene.attachNewNode(dl)
dlp.lookAt(0, 0, 0)
dlp.setPos(10, -20, 0)
scene.setLight(aLightP)
scene.setLight(dlp)
self.grid(scene)
self.showIris(iris, scene)
taskMgr.add(self.spinCameraTask, "draw task")
app = App()
app.run()
|
957c9c5f5aeab3aee0194b6dbf4ade9386de79a9
|
[
"Python"
] | 1
|
Python
|
sherzodv/ai
|
7f310c17ffc7a1473d397933a37da5d16889d088
|
c98bc2e2bc63af688b0eb1faf2f496752f89defc
|
refs/heads/main
|
<repo_name>almoretto/GerenciadorEstoqueFiscal<file_sep>/StockManagerCore/Data/SeedDataService.cs
#region --== Dependency declaration ==--
using System;
using System.Collections.Generic;
using System.Linq;
using StockManagerCore.Models;
#endregion
namespace StockManagerCore.Data
{
class SeedDataService
{
#region --== Constructor for dependency injection ==--
private StockDBContext _Context;
//This Constructor is for Injection of Dependency
public SeedDataService(StockDBContext context) { _Context = context; }
#endregion
#region --== Properties ==--
private List<Product> Ps { get; set; } = new List<Product>();
private List<Company> Cs { get; set; } = new List<Company>();
#endregion
//Seeding data region
public void Seed()
{
#region --== Seeding Products groups ==--
if (!_Context.Products.Any())
{
Ps.Add(new Product("ANEL"));
Ps.Add(new Product("ARGOLA"));
Ps.Add(new Product("BRACELETE"));
Ps.Add(new Product("BRINCO"));
Ps.Add(new Product("CHOKER"));
Ps.Add(new Product("COLAR"));
Ps.Add(new Product("CORRENTE"));
Ps.Add(new Product("PINGENTE"));
Ps.Add(new Product("PULSEIRA"));
Ps.Add(new Product("TORNOZELEIRA"));
Ps.Add(new Product("PEÇAS"));
Ps.Add(new Product("VARIADOS"));
Ps.Add(new Product("BROCHE"));
Ps.Add(new Product("CONJUNTO"));
Ps.Add(new Product("ACESSORIO"));
_Context.Products.AddRange(Ps); //Adding to DBSet
_Context.SaveChanges(); //Saving changes persisting;
}
#endregion
#region --== Seeding Companies ==--
if (!_Context.Companies.Any())
{
Cs.Add(new Company("ATACADAO", 1600000.00));
Cs.Add(new Company("JR", 1600000.00));
Cs.Add(new Company("FABRICACAO", 1600000.00));
Cs.Add(new Company("ATACADAO MCP", 1600000.00));
_Context.Companies.AddRange(Cs); //Add to dbset
_Context.SaveChanges(); //Persist
}
#endregion
#region --== Seeding Stocks ==--
if (!_Context.Stocks.Any())
{
#region --== Seeding Stocks Company Atacadao ==--
var com = _Context.Companies.Where(c => c.Name == "ATACADAO").FirstOrDefault();
var prd = _Context.Products.Where(p => p.GroupP == "ANEL").FirstOrDefault();
Stock s1 = new Stock(prd, 142019, 106319, 76819.44, 406753.01, new DateTime(2019, 12, 31), new DateTime(2019,12,31), com);
prd = _Context.Products.Where(p => p.GroupP == "ARGOLA").FirstOrDefault();
Stock s2 = new Stock(prd, 34773, 28596, 26462.60, 107119.72, new DateTime(2019, 12, 31), new DateTime(2019, 12, 31), com);
prd = _Context.Products.Where(p => p.GroupP == "BRACELETE").FirstOrDefault();
Stock s3 = new Stock(prd, 21239, 10263, 33939.80, 74116.11, new DateTime(2019, 12, 31), new DateTime(2019, 12, 31), com);
prd = _Context.Products.Where(p => p.GroupP == "BRINCO").FirstOrDefault();
Stock s4 = new Stock(prd, 208071, 156291, 149007.39, 495604.81, new DateTime(2019, 12, 31), new DateTime(2019, 12, 31), com);
prd = _Context.Products.Where(p => p.GroupP == "CHOKER").FirstOrDefault();
Stock s5 = new Stock(prd, 0, 0, 0.0, 0.0, new DateTime(2020, 01, 01), com);
prd = _Context.Products.Where(p => p.GroupP == "COLAR").FirstOrDefault();
Stock s6 = new Stock(prd, 66801, 50189, 75709.71, 321378.54, new DateTime(2019, 12, 31), new DateTime(2019, 12, 31), com);
prd = _Context.Products.Where(p => p.GroupP == "CORRENTE").FirstOrDefault();
Stock s7 = new Stock(prd, 27218, 26379, 29582.35, 92188.25, new DateTime(2019, 12, 31), new DateTime(2019, 12, 31), com);
prd = _Context.Products.Where(p => p.GroupP == "PINGENTE").FirstOrDefault();
Stock s8 = new Stock(prd, 30177, 21240, 11661.92, 38930.58, new DateTime(2019, 12, 31), new DateTime(2019, 12, 31), com);
prd = _Context.Products.Where(p => p.GroupP == "PULSEIRA").FirstOrDefault();
Stock s9 = new Stock(prd, 83160, 37040, 76877.02, 180068.76, new DateTime(2019, 12, 31), new DateTime(2019, 12, 31), com);
prd = _Context.Products.Where(p => p.GroupP == "TORNOZELEIRA").FirstOrDefault();
Stock s10 = new Stock(prd, 4115, 2221, 9490.42, 7638.90, new DateTime(2019, 12, 31), new DateTime(2019, 12, 31), com);
prd = _Context.Products.Where(p => p.GroupP== "PEÇAS").FirstOrDefault();
Stock s11 = new Stock(prd, 0, 0, 0.0, 0.0, new DateTime(2020, 01, 01), com);
prd = _Context.Products.Where(p => p.GroupP== "VARIADOS").FirstOrDefault();
Stock s12 = new Stock(prd, 7399, 6838, 3278.92, 11014.06, new DateTime(2019, 12, 31), new DateTime(2019, 12, 31), com);
prd = _Context.Products.Where(p => p.GroupP== "BROCHE").FirstOrDefault();
Stock s13 = new Stock(prd, 0, 0, 0.0, 0.0, new DateTime(2020, 01, 01), com);
prd = _Context.Products.Where(p => p.GroupP== "CONJUNTO").FirstOrDefault();
Stock s27 = new Stock(prd, 2771, 1945, 6694.93, 9741.07, new DateTime(2019, 12, 31), new DateTime(2019, 12, 31), com);
prd = _Context.Products.Where(p => p.GroupP== "ACESSORIO").FirstOrDefault();
Stock s57 = new Stock(prd, 0, 0, 0.0, 0.0, new DateTime(2020, 01, 01), com);
#endregion
#region --== Dbset and commit Company Atacadao ==--
_Context.Stocks.AddRange(s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s27);
_Context.SaveChanges();
#endregion
#region --== Seeding Stocks Company JR ==--
com = _Context.Companies.Where(c => c.Name == "JR").FirstOrDefault();
prd = _Context.Products.Where(p => p.GroupP == "ANEL").FirstOrDefault();
Stock s14 = new Stock(prd, 180892, 0, 91078.69, 0.0, new DateTime(2020, 01, 01), com);
prd = _Context.Products.Where(p => p.GroupP == "ARGOLA").FirstOrDefault();
Stock s15 = new Stock(prd, 6913, 0, 1337.70, 0.0, new DateTime(2020, 01, 01), com);
prd = _Context.Products.Where(p => p.GroupP == "BRACELETE").FirstOrDefault();
Stock s16 = new Stock(prd, 4659, 0, 3116.88, 0.0, new DateTime(2020, 01, 01), com);
prd = _Context.Products.Where(p => p.GroupP == "BRINCO").FirstOrDefault();
Stock s17 = new Stock(prd, 238034, 0, 126968.50, 0.0, new DateTime(2020, 01, 01), com);
prd = _Context.Products.Where(p => p.GroupP == "CHOKER").FirstOrDefault();
Stock s18 = new Stock(prd, 0, 0, 0.0, 0.0, new DateTime(2020, 01, 01), com);
prd = _Context.Products.Where(p => p.GroupP == "COLAR").FirstOrDefault();
Stock s19 = new Stock(prd, 9264, 0, 6786.61, 0.0, new DateTime(2020, 01, 01), com);
prd = _Context.Products.Where(p => p.GroupP == "CORRENTE").FirstOrDefault();
Stock s20 = new Stock(prd, 20464, 0, 19476.01, 0.0, new DateTime(2020, 01, 01), com);
prd = _Context.Products.Where(p => p.GroupP == "PINGENTE").FirstOrDefault();
Stock s21 = new Stock(prd, 16209, 0, 8971.30, 0.0, new DateTime(2020, 01, 01), com);
prd = _Context.Products.Where(p => p.GroupP == "PULSEIRA").FirstOrDefault();
Stock s22 = new Stock(prd, 31514, 0, 22208.20, 0.0, new DateTime(2020, 01, 01), com);
prd = _Context.Products.Where(p => p.GroupP == "TORNOZELEIRA").FirstOrDefault();
Stock s23 = new Stock(prd, 5000, 0, 1364.09, 0.0, new DateTime(2020, 01, 01), com);
prd = _Context.Products.Where(p => p.GroupP == "PEÇAS").FirstOrDefault();
Stock s24 = new Stock(prd, 0, 0, 0.0, 0.0, new DateTime(2020, 01, 01), com);
prd = _Context.Products.Where(p => p.GroupP == "VARIADOS").FirstOrDefault();
Stock s25 = new Stock(prd, 3518, 0, 5295.52, 0.0, new DateTime(2020, 01, 01), com);
prd = _Context.Products.Where(p => p.GroupP == "BROCHE").FirstOrDefault();
Stock s26 = new Stock(prd, 0, 0, 0.0, 0.0, new DateTime(2020, 01, 01), com);
prd = _Context.Products.Where(p => p.GroupP == "CONJUNTO").FirstOrDefault();
Stock s28 = new Stock(prd, 5898, 0, 6786.61, 0.0, new DateTime(2020, 01, 01), com);
prd = _Context.Products.Where(p => p.GroupP == "ACESSORIO").FirstOrDefault();
Stock s58 = new Stock(prd, 0, 0, 0.0, 0.0, new DateTime(2020, 01, 01), com);
#endregion
#region --== Dbset and commit Company 2 ==--
_Context.Stocks.AddRange(s14, s15, s16, s17, s18, s19, s20, s21, s22, s23, s24, s25, s26, s28);
_Context.SaveChanges();
#endregion
#region --== Seeding Stocks Company FABRICACAO ==--
com = _Context.Companies.Where(c => c.Name == "FABRICACAO").FirstOrDefault();
prd = _Context.Products.Where(p => p.GroupP == "ANEL").FirstOrDefault();
Stock s29 = new Stock(prd, 0, 0, 0.0, 0.0, new DateTime(2020, 01, 01), com);
prd = _Context.Products.Where(p => p.GroupP == "ARGOLA").FirstOrDefault();
Stock s30 = new Stock(prd, 0, 0, 0.0, 0.0, new DateTime(2020, 01, 01), com);
prd = _Context.Products.Where(p => p.GroupP == "BRACELETE").FirstOrDefault();
Stock s31 = new Stock(prd, 0, 0, 0.0, 0.0, new DateTime(2020, 01, 01), com);
prd = _Context.Products.Where(p => p.GroupP == "BRINCO").FirstOrDefault();
Stock s32 = new Stock(prd, 0, 0, 0.0, 0.0, new DateTime(2020, 01, 01), com);
prd = _Context.Products.Where(p => p.GroupP == "CHOKER").FirstOrDefault();
Stock s33 = new Stock(prd, 0, 0, 0.0, 0.0, new DateTime(2020, 01, 01), com);
prd = _Context.Products.Where(p => p.GroupP == "COLAR").FirstOrDefault();
Stock s34 = new Stock(prd, 0, 0, 0.0, 0.0, new DateTime(2020, 01, 01), com);
prd = _Context.Products.Where(p => p.GroupP == "CORRENTE").FirstOrDefault();
Stock s35 = new Stock(prd, 0, 0, 0.0, 0.0, new DateTime(2020, 01, 01), com);
prd = _Context.Products.Where(p => p.GroupP == "PINGENTE").FirstOrDefault();
Stock s36 = new Stock(prd, 0, 0, 0.0, 0.0, new DateTime(2020, 01, 01), com);
prd = _Context.Products.Where(p => p.GroupP == "PULSEIRA").FirstOrDefault();
Stock s37 = new Stock(prd, 0, 0, 0.0, 0.0, new DateTime(2020, 01, 01), com);
prd = _Context.Products.Where(p => p.GroupP == "TORNOZELEIRA").FirstOrDefault();
Stock s38 = new Stock(prd, 0, 0, 0.0, 0.0, new DateTime(2020, 01, 01), com);
prd = _Context.Products.Where(p => p.GroupP == "PEÇAS").FirstOrDefault();
Stock s39 = new Stock(prd, 0, 0, 0.0, 0.0, new DateTime(2020, 01, 01), com);
prd = _Context.Products.Where(p => p.GroupP == "VARIADOS").FirstOrDefault();
Stock s40 = new Stock(prd, 0, 0, 0.0, 0.0, new DateTime(2020, 01, 01), com);
prd = _Context.Products.Where(p => p.GroupP == "BROCHE").FirstOrDefault();
Stock s41 = new Stock(prd, 0, 0, 0.0, 0.0, new DateTime(2020, 01, 01), com);
prd = _Context.Products.Where(p => p.GroupP == "CONJUNTO").FirstOrDefault();
Stock s42 = new Stock(prd, 0, 0, 0.0, 0.0, new DateTime(2020, 01, 01), com);
prd = _Context.Products.Where(p => p.GroupP == "ACESSORIO").FirstOrDefault();
Stock s59 = new Stock(prd, 0, 0, 0.0, 0.0, new DateTime(2020, 01, 01), com);
#endregion
#region --== Dbset and commit Company 3 ==--
_Context.Stocks.AddRange(s29, s30, s31, s32, s33, s34, s35, s36, s37, s38, s39, s40, s41, s42);
_Context.SaveChanges();
#endregion
#region --== Seeding Stocks Company ATACADAO MCP ==--
com = _Context.Companies.Where(c => c.Name == "ATACADAO MCP").FirstOrDefault();
prd = _Context.Products.Where(p => p.GroupP == "ANEL").FirstOrDefault();
Stock s43 = new Stock(prd, 0, 0, 0.0, 0.0, new DateTime(2020, 01, 01), com);
prd = _Context.Products.Where(p => p.GroupP == "ARGOLA").FirstOrDefault();
Stock s44 = new Stock(prd, 0, 0, 0.0, 0.0, new DateTime(2020, 01, 01), com);
prd = _Context.Products.Where(p => p.GroupP == "BRACELETE").FirstOrDefault();
Stock s45 = new Stock(prd, 0, 0, 0.0, 0.0, new DateTime(2020, 01, 01), com);
prd = _Context.Products.Where(p => p.GroupP == "BRINCO").FirstOrDefault();
Stock s46 = new Stock(prd, 0, 0, 0.0, 0.0, new DateTime(2020, 01, 01), com);
prd = _Context.Products.Where(p => p.GroupP == "CHOKER").FirstOrDefault();
Stock s47 = new Stock(prd, 0, 0, 0.0, 0.0, new DateTime(2020, 01, 01), com);
prd = _Context.Products.Where(p => p.GroupP == "COLAR").FirstOrDefault();
Stock s48 = new Stock(prd, 0, 0, 0.0, 0.0, new DateTime(2020, 01, 01), com);
prd = _Context.Products.Where(p => p.GroupP == "CORRENTE").FirstOrDefault();
Stock s49 = new Stock(prd, 0, 0, 0.0, 0.0, new DateTime(2020, 01, 01), com);
prd = _Context.Products.Where(p => p.GroupP == "PINGENTE").FirstOrDefault();
Stock s50 = new Stock(prd, 0, 0, 0.0, 0.0, new DateTime(2020, 01, 01), com);
prd = _Context.Products.Where(p => p.GroupP == "PULSEIRA").FirstOrDefault();
Stock s51 = new Stock(prd, 0, 0, 0.0, 0.0, new DateTime(2020, 01, 01), com);
prd = _Context.Products.Where(p => p.GroupP == "TORNOZELEIRA").FirstOrDefault();
Stock s52 = new Stock(prd, 0, 0, 0.0, 0.0, new DateTime(2020, 01, 01), com);
prd = _Context.Products.Where(p => p.GroupP == "PEÇAS").FirstOrDefault();
Stock s53 = new Stock(prd, 0, 0, 0.0, 0.0, new DateTime(2020, 01, 01), com);
prd = _Context.Products.Where(p => p.GroupP == "VARIADOS").FirstOrDefault();
Stock s54 = new Stock(prd, 0, 0, 0.0, 0.0, new DateTime(2020, 01, 01), com);
prd = _Context.Products.Where(p => p.GroupP == "BROCHE").FirstOrDefault();
Stock s55 = new Stock(prd, 0, 0, 0.0, 0.0, new DateTime(2020, 01, 01), com);
prd = _Context.Products.Where(p => p.GroupP == "CONJUNTO").FirstOrDefault();
Stock s56 = new Stock(prd, 0, 0, 0.0, 0.0, new DateTime(2020, 01, 01), com);
prd = _Context.Products.Where(p => p.GroupP == "ACESSORIO").FirstOrDefault();
Stock s60 = new Stock(prd, 0, 0, 0.0, 0.0, new DateTime(2020, 01, 01), com);
#endregion
#region --== Dbset and commit Company 4 ==--
_Context.Stocks.AddRange(s43, s44, s45, s46, s47, s48, s49, s50, s51, s52, s53, s54, s55, s56);
_Context.SaveChanges();
#endregion
}
#endregion
//#region --== Seeding Cities ==--
//if (!_Context.Cities.Any())
//{
// Cty.Add(new City("CURITIBA", State.PR));
// Cty.Add(new City("BIRIGUI", State.SP));
// Cty.Add(new City("MANHAÇU", State.MG));
// Cty.Add(new City("LONDRINA", State.PR));
// Cty.Add(new City("SAO LUIZ", State.MA));
// Cty.Add(new City("SAO PAULO", State.SP));
// Cty.Add(new City("PARANAVAI", State.PR));
// Cty.Add(new City("GOIANIA", State.GO));
// Cty.Add(new City("MANAUS", State.AM));
// Cty.Add(new City("SALVADOR", State.BA));
// Cty.Add(new City("ERECHIM", State.RS));
// Cty.Add(new City("BELEM", State.PA));
// Cty.Add(new City("<NAME>", State.PE));
// Cty.Add(new City("CAMPO GRANDE", State.MS));
// Cty.Add(new City("CUIABA", State.MT));
// Cty.Add(new City("FORTALEZA", State.CE));
// Cty.Add(new City("TEREZINA", State.PI));
// Cty.Add(new City("SOROCABA", State.SP));
// Cty.Add(new City("TRES ARROIOS", State.RS));
// Cty.Add(new City("LAURO DE FREITAS", State.BA));
// Cty.Add(new City("ARAGUAINA", State.TO));
// Cty.Add(new City("GURUPI", State.TO));
// Cty.Add(new City("ADAMANTINA", State.SP));
// _Context.Cities.AddRange(Cty); //Adding to DBSet
// _Context.SaveChanges();
//}
//#endregion
//#region ---== Seeding People ==--
//if (!_Context.People.Any())
//{
// Pep.Add(new Person("ADILSON",
// "",
// _Context.Cities
// .Where(c => c.CityName == "ADAMANTINA")
// .FirstOrDefault(),
// State.SP,
// PersonType.PF,
// PersonCategory.Representante));
// Pep.Add(new Person("ALBERTO",
// "",
// _Context.Cities
// .Where(c => c.CityName == "CUIABA")
// .FirstOrDefault(),
// State.MT,
// PersonType.PF,
// PersonCategory.Representante));
// Pep.Add(new Person("CYNTHIA",
// "",
// _Context.Cities
// .Where(c => c.CityName == "TEREZINA")
// .FirstOrDefault(),
// State.PI,
// PersonType.PF,
// PersonCategory.Representante));
// _Context.People.AddRange(Pep);
// _Context.SaveChanges();
//}
//else
//{
// return;//Seed Realized
//}
//#endregion
}
}
}
<file_sep>/StockManagerCore/Models/InputProduct.cs
#region --== Dependency declaration ==--
using System.ComponentModel.DataAnnotations;
using System;
#endregion
namespace StockManagerCore.Models
{
public class InputProduct
{
#region --== Model Properties ==--
[Key]
public int Id { get; set; }
public string NItem { get; set; }
public string XProd { get; set; }
public int QCom { get; set; }
public double VUnCom { get; set; }
public string UCom { get; set; }
public double Vtotal { get; set; }
public double VUnTrib { get; set; }
public double VTotTrib { get; set; }
public DateTime DhEmi { get; set; }
// public string Filename { get; set; }
[Required]
public Company Company { get; set; }
//Navigation prop
[Required]
public Product Product { get; set; }
#endregion
#region --== Constructors ==--
public InputProduct() { }
public InputProduct(string nItem, string xProd, int qCom, double vUnCom, string uCom, double vtotal,
double vUnTrib, double vTotTrib, Product product, DateTime dhEmi, Company company)
{
NItem = nItem;
XProd = xProd;
QCom = qCom;
VUnCom = vUnCom;
UCom = uCom;
Vtotal = vtotal;
VUnTrib = vUnTrib;
VTotTrib = vTotTrib;
Product = product;
DhEmi = dhEmi;
Company = company;
}
#endregion
}
}
<file_sep>/StockManagerCore/Data/StockDBContext.cs
#region --== Dependency declaration ==--
using Microsoft.EntityFrameworkCore;
using StockManagerCore.Models;
#endregion
namespace StockManagerCore.Data
{
public class StockDBContext : DbContext
{
//DbContext dependency injection
public StockDBContext(DbContextOptions<StockDBContext> options) : base(options){ }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer( "server=tcp:=192.168.100.2,1433;Network Library = DBMSSOCN;Initial Catalog=StockKManagerDB;User Id=appuser;Password=<PASSWORD>;" );
}
#region --== DB Sets table links ==--
//Tables conections declaration dor codeFirst approuch on EFcore
public DbSet<InputProduct> InputProducts { get; set; }
public DbSet<Product> Products { get; set; }
public DbSet<SoldProduct> SoldProducts { get; set; }
public DbSet<Stock> Stocks { get; set; }
public DbSet<Company> Companies { get; set; }
public DbSet<User> Users { get; set; }
#endregion
}
}
<file_sep>/StockManagerCore/MainWindow.xaml.cs
#region --== Dependency Declaration ==--
using System.Windows;
using StockManagerCore.Services;
using StockManagerCore.UserInterface;
#endregion
namespace StockManagerCore
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
#region --== Instances of Context, Provider and StringBuilder ==--
/*Declatarions for dependency injection of services classes.
* Each one of the services are responsible for the model thats concern to
* Each method in the single service is designed to a single purpose.
* trying to obey SOLID principles.
*/
private readonly InputService _inputService;
private readonly SaleService _saleService;
private readonly ProductService _productService;
private readonly CompanyService _companyService;
private readonly StockService _stockService;
#endregion
public MainWindow(InputService inputService, SaleService saleService, ProductService productService,
CompanyService companyService, StockService stockService)
{
//Constructor of the form MainWindow here we call the dependency injection
_inputService = inputService;
_saleService = saleService;
_productService = productService;
_companyService = companyService;
_stockService = stockService;
InitializeComponent();
}
#region --== Buttons Methods==--
private void btnOpenStockInput_Click(object sender, RoutedEventArgs e)
{
WdnProcessFiles processFilesWindow = new WdnProcessFiles(_inputService, _saleService, _productService,
_companyService, _stockService);
processFilesWindow.Show();
}
private void btnOpenStockCRUD_Click(object sender, RoutedEventArgs e)
{
WdnStockCrud stockCrud = new WdnStockCrud(_productService, _companyService, _stockService);
stockCrud.Show();
}
private void btnExit_Click(object sender, RoutedEventArgs e)
{
this.Close();
Application.Current.Shutdown();
}
private void btnLogin_Click( object sender, RoutedEventArgs e )
{
}
private void btnChangePass_Click( object sender, RoutedEventArgs e )
{
}
#endregion
#region --== Action Methods ==--
#endregion
}
}
<file_sep>/StockManagerCore/Services/Exceptions/NotFoundException.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace StockManagerCore.Services.Exceptions
{
//Custom Exception Handler
class NotFoundException : MyApplicationException { public NotFoundException(string message) : base(message) { } }
}
<file_sep>/StockManagerCore/Services/StockService.cs
#region --== Dependency declaration ==--
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using Microsoft.EntityFrameworkCore;
using StockManagerCore.Data;
using StockManagerCore.Models;
using StockManagerCore.Services.Exceptions;
#endregion
namespace StockManagerCore.Services
{
public class StockService
{
#region --== Constructor for dependency injection ==--
//Constructor of the service class and dbcontext dependency injection
private readonly StockDBContext _context;
public StockService(StockDBContext context) { _context = context; }
#endregion
#region --== Methods ==--
//Querry all stocks selecting by an specific company
public List<Stock> GetStocksByCompany(Company company)
{
if (company == null)
{
throw new RequiredFieldException("Empresa é obrigatoria para retornar lista de estoques");
}
try
{
//Entity Framework Querry including related product and company entities.
return _context.Stocks
.Include(s => s.Product)
.Include(s => s.Company)
.Where(s => s.Company.Id == company.Id).ToList();
}
catch (NotFoundException ex)
{
throw new NotFoundException(ex.Message);
}
}
//Querry Stock filtering by company and product
public Stock GetStockByCompanyAndGroup(Company co, string grp)
{
Stock stock = new Stock();
if (co == null || grp == null || grp == "")
{
throw new RequiredFieldException("Empresa e Produto são obrigatórios para localizar um estoque");
}
//EF query filtering company and product and including related company and product entities.
stock = (_context.Stocks
.Where(s => s.Company.Id == co.Id))
.Where(s => s.Product.GroupP == grp)
.Include(s => s.Product)
.Include(s => s.Company)
.FirstOrDefault();
if (stock == null)
{
throw new NotFoundException("Estoque não encontrado com os parâmetros");
}
return stock;
}
//Querry all Stocks from database
public List<Stock> GetStocks()
{
List<Stock> stocks = _context.Stocks
.Include(s => s.Product)
.Include(s => s.Company)
.OrderBy(s => s.Product.GroupP).ToList();
_context.Database.CloseConnection();
return stocks;
}
//Querry all stocks and returns a formated list. Includin product name and company name.
public IEnumerable<object> GetStocksFormated(Company company)
{
var query = from s in _context.Stocks
join c in _context.Companies on s.Company.Id equals c.Id
join p in _context.Products on s.Product.Id equals p.Id
where s.Company.Id == company.Id
select new
{
Produto = s.Product.GroupP,
QteComprada = s.QtyPurchased,
ValorMedio = 0.0,
QteVendida = s.QtySold,
QteSaldo = s.ProdQtyBalance,
ValorSaldo = 0.0,
DataSaldo = s.BalanceDate.ToString("dd/MM/yyyy"),
ValorCompra = s.AmountPurchased.ToString("C2"),
ValorVenda = s.AmountSold.ToString("C2"),
UltimaSaída = s.LastSales.ToString("dd/MM/yyyy"),
UltimaEntrada = s.LastInput.ToString("dd/MM/yyyy")
};
return query.ToList();
}
public List<DispStockCompany> GetStocksStructured(Company company)
{
List<DispStockCompany> outList = new List<DispStockCompany>();
DispStockCompany stockToDisplay;
List<Stock> query = _context.Stocks
.Include(s => s.Company)
.Include(s => s.Product)
.Where(s => s.Company.Id == company.Id).ToList();
foreach (Stock st in query)
{
stockToDisplay = new DispStockCompany();
stockToDisplay.Produto = st.Product.GroupP.ToString();
stockToDisplay.QteCompra = st.QtyPurchased;
stockToDisplay.QteVendida = st.QtySold;
stockToDisplay.QteSaldo = st.ProdQtyBalance;
stockToDisplay.ValorCompra = st.AmountPurchased.ToString("C2");
stockToDisplay.ValorVenda = st.AmountSold.ToString("C2");
stockToDisplay.DataSaldo = st.BalanceDate.Date.ToString("dd/MM/yyyy");
stockToDisplay.UltimaEntrada = st.LastInput.Date.ToString("dd/MM/yyyy");
stockToDisplay.UltimaSaída = st.LastSales.Date.ToString("dd/MM/yyyy");
if (st.QtyPurchased > 0)
{
double vm = st.AmountPurchased / st.QtyPurchased;
stockToDisplay.ValorMedio = (vm).ToString("C2");
stockToDisplay.ValorSaldo = (st.ProdQtyBalance * vm).ToString("C2");
}
else
{
stockToDisplay.ValorMedio = "R$0,0";
stockToDisplay.ValorSaldo = "R$0,0";
}
outList.Add(stockToDisplay);
}
return outList;
}
public List<DispStockCompany> CalculateBalance(Company company)
{
try
{
List<Stock> stocks = new List<Stock>();
stocks = GetStocksByCompany(company);
foreach (Stock item in stocks)
{
item.SetBalance();
}
_context.UpdateRange(stocks);
_context.SaveChanges();
}
catch (DbComcurrancyException ex)
{
MessageBox.Show("Erro ao tentar fazer update!\n" + ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
throw new DbUpdateConcurrencyException(ex.Message);
}
return GetStocksStructured(company);
}
#region --== Crud ==--
//Method to Create new Stock
public string Create(Product product, int? qtyPurchased, int? qtySold, double? amountPurchased,
double? amountSold, DateTime? lstImput, DateTime? lstSale, Company company)
{
Stock stk = new Stock();
string result;
try
{
if (product != null
&& qtyPurchased.HasValue
&& qtySold.HasValue
&& amountPurchased.HasValue
&& amountSold.HasValue
&& lstImput != null
&& lstSale != null
&& company != null)
{
stk = new Stock(product, qtyPurchased.Value, qtySold.Value, amountPurchased.Value, amountSold.Value,
(DateTime)lstImput, (DateTime)lstSale.Value, company);
_context.Stocks.Add(stk);
_context.SaveChanges();
}
else
{
throw new RequiredFieldException("Todos os campos deste registro são obrigatórios");
}
var test = _context.Stocks.Where(s => s.Company == stk.Company && s.Product == stk.Product).FirstOrDefault();
if (test == null)
{
throw new NotFoundException("Estoque adicionado não foi localizado tente outra vez! \n Clique em visualizar para mostrar todos");
}
result = test.Id.ToString() + " Empresa: " + test.Company.Name + " Produto: " + test.Product.GroupP;
}
catch (DbUpdateException ex)
{
MessageBox.Show("Erro ao tetar criar novo!\n" + ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
throw new DbUpdateException(ex.Message);
}
return "Criado com sucesso estoque id: " + result;
}
//Method to Find a Strock of a specific product to edit.
public Stock FindToUpdate(Company co, Product prod)
{
Stock stk = new Stock();
if (co != null && prod != null)
{
stk = _context.Stocks
.Where(s => s.Company.Id == co.Id && s.Product.Id == prod.Id)
.FirstOrDefault();
if (stk == null)
{
throw new NotFoundException("Estoque com empresa :"
+ co.Name
+ " e Produto: "
+ prod.GroupP
+ "Não encontrado");
}
return stk;
}
throw new NotFoundException("Insuficient Data to find entity!");
}
//Method to Update/edit a stock on database
public void Update(Stock stk)
{
try
{
_context.Stocks.Update(stk);
_context.SaveChanges();
_context.Database.CloseConnection();
}
catch (DbUpdateConcurrencyException ex)
{
MessageBox.Show("Erro ao tentar fazer update!\n" + ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
throw new DbUpdateConcurrencyException(ex.Message);
}
}
public void UpdateRange(IEnumerable<Stock> stks)
{
try
{
_context.Stocks.UpdateRange(stks);
_context.SaveChanges();
_context.Database.CloseConnection();
}
catch (DbUpdateConcurrencyException ex)
{
MessageBox.Show("Erro ao tentar fazer update!\n" + ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
throw new DbUpdateConcurrencyException(ex.Message);
}
}
#endregion
#endregion
}
}
<file_sep>/StockManagerCore/UserInterface/WdnStockGrid.xaml.cs
using StockManagerCore.Models;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Windows;
namespace StockManagerCore.UserInterface
{
/// <summary>
/// Lógica interna para WdnStockGrid.xaml
/// </summary>
public partial class WdnStockGrid : Window
{
private List<DispStockCompany> _gridStockDisplay { get; set; } = new List<DispStockCompany>();
private Company _companyToDisplay { get; set; } = new Company();
public WdnStockGrid( List<DispStockCompany> gridContent, Company company )
{
_gridStockDisplay = gridContent;
_companyToDisplay = company;
InitializeComponent();
}
private void WdnStockGrid_Loaded( object sender, RoutedEventArgs e )
{
GenerateGrid( _gridStockDisplay, _companyToDisplay );
}
private void btnClear_Click( object sender, RoutedEventArgs e )
{
GrdStock.Items.Clear();
}
private void btnExit_Click( object sender, RoutedEventArgs e )
{
btnClear_Click( btnClear, new RoutedEventArgs()); //Calling the Clear button
this.Close();
}
//Methods
private void GenerateGrid( List<DispStockCompany> gridContent, Company c )
{
int tq = 0;
double tv = 0.0;
foreach ( var item in gridContent )
{
tq += item.QteSaldo;
tv += double.Parse( item.ValorSaldo.Replace( "R$", "" ).Trim(), CultureInfo.CurrentCulture );
}
//Activates the auto generate columns for the grid manages himself
GrdStock.AutoGenerateColumns = true;
//attributes the data to grid
TxtBCompany.Text += ": " + c.Name; //Label on top
//attach list to grid for result
lblTotalQtyInStock.Content = tq.ToString( "N0", CultureInfo.CurrentCulture );
lblTotalAmtInStock.Content = tv.ToString( "C2" );
GrdStock.ItemsSource = gridContent.ToList();
//Changes view to the tab of dataview and makes visible
InitializeComponent();
}
}
}
<file_sep>/StockManagerCore/UserInterface/WdwGenericGridData.xaml.cs
using StockManagerCore.Models;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Windows;
namespace StockManagerCore.UserInterface
{
/// <summary>
/// Lógica interna para WdwGenericGridData.xaml
/// </summary>
public partial class WdwGenericGridData : Window
{
#region --== Instances of Context, Provider and StringBuilder ==--
/*Declatarions for dependency injection of services classes.
* Each one of the services are responsible for the model thats concern to
* Each method in the single service is designed to a single purpose.
* trying to obey SOLID principles.
*/
private readonly List<object> _inputObject;
private readonly Company _company = new Company();
private List<DispStockCompany> DispStocks { get; set; } = new List<DispStockCompany>();
private string GridTitle { get; set; }
//declaration of culture info for less verbose code
CultureInfo provider = CultureInfo.InvariantCulture;
//Declaration of the log string builder. This log is merely for information and its not stored in any place for a while.
StringBuilder log = new StringBuilder();
#endregion
public WdwGenericGridData( List<object> inputObject, string title )
{
_inputObject = inputObject;
GridTitle = title;
InitializeComponent();
txtBGridLabel.Visibility = Visibility.Hidden;
lblTotalQty.Visibility = Visibility.Hidden;
lblTotalAmt.Visibility = Visibility.Hidden;
lblGridTittle.Content += GridTitle;
PreparingView();
}
public WdwGenericGridData( List<DispStockCompany> stocks, string title, Company comp )
{
DispStocks = stocks;
_company = comp;
GridTitle = title;
InitializeComponent();
txtBGridLabel.Visibility = Visibility.Hidden;
lblTotalQty.Visibility = Visibility.Hidden;
lblTotalAmt.Visibility = Visibility.Hidden;
lblGridTittle.Content += GridTitle;
PreparingView();
}
private void btnClear_Click( object sender, RoutedEventArgs e )
{
GrdGenericGridView.Items.Clear();
}
#region --== Methods ==--
private void PreparingView()
{
switch ( GridTitle )
{
case "Produtos":
txtBGridLabel.Visibility = Visibility.Visible;
txtBGridLabel.Text = "Listagem de Produtos";
GenerateGrid( _inputObject );
break;
case "Estoques":
txtBGridLabel.Visibility = Visibility.Visible;
txtBGridLabel.Text = "Estoque Empresa: " + _company.Name;
GenerateGridStock( DispStocks );
break;
case "Empresas":
txtBGridLabel.Visibility = Visibility.Visible;
txtBGridLabel.Text = "Listagem de Empresas";
GenerateGrid( _inputObject );
break;
default:
txtBGridLabel.Visibility = Visibility.Hidden;
txtBGridLabel.Text = GridTitle;
GenerateGrid( _inputObject );
break;
}
}
private void GenerateGridStock( List<DispStockCompany> gridContent )
{
//Preparing data for Grid
int tq = 0;
double tv = 0.0;
foreach ( var item in gridContent )
{
tq += item.QteSaldo;
tv += double.Parse( item.ValorSaldo.Replace( "R$", "" ).Trim(), CultureInfo.CurrentCulture );
}
//Activates the auto generate columns for the grid manages himself
GrdGenericGridView.AutoGenerateColumns = true;
GrdGenericGridView.ItemsSource = gridContent.ToList();
//attach list to grid for result
lblTotalQty.Content += tq.ToString( "N0", CultureInfo.CurrentCulture );
lblTotalAmt.Content += tv.ToString( "C2" );
InitializeComponent();
}
private void GenerateGrid( List<object> gridContent )
{
//Preparing Grid
//Activates the auto generate columns for the grid manages himself
GrdGenericGridView.AutoGenerateColumns = true;
GrdGenericGridView.ItemsSource = gridContent.ToList();
//attach list to grid for result
InitializeComponent();
}
#endregion
}
}<file_sep>/StockManagerCore/Services/ProductService.cs
#region --== Dependency Declaration ==--
using System.Linq;
using System.Collections.Generic;
using StockManagerCore.Data;
using StockManagerCore.Models;
using StockManagerCore.Services.Exceptions;
#endregion
namespace StockManagerCore.Services
{
public class ProductService
{
#region --== Constructor for dependency injection ==--
//Constructor and dependency Injection to DbContext
private readonly StockDBContext _context;
public ProductService(StockDBContext context) { _context = context; }
#endregion
#region --== Methods ==--
//Querry to fetch all products from database
public IEnumerable<Product> GetProducts()
{
return _context.Products;
}
//Querry to Find a producta By Entity
public Product Find(Product p)
{
Product product = new Product();
if (p==null)
{
throw new RequiredFieldException("Campo requerido para pesquisa");
}
product= _context.Products
.Where(pr => pr.Id == p.Id)
.SingleOrDefault();
if (product == null)
{
throw new NotFoundException("Entidade não encontrada");
}
return product;
}
//Querry to find product by Name
public Product FindByGroup(string gr)
{
Product product = new Product();
if (gr==null || gr=="")
{
throw new RequiredFieldException("Campo requerido para busca");
}
product = _context.Products.Where(p => p.GroupP == gr).FirstOrDefault();
if (product==null)
{
throw new NotFoundException("Entidade não encontrada");
}
return product;
}
public IEnumerable<object> GetObjProducts()
{
var query = from p in _context.Products
select new
{
Produto = p.GroupP,
Codigo = p.Id,
};
return query.ToList();
}
#region --== CRUD ==--
//Method to create a new product on database
public string Create(string name)
{
Product p = new Product(name);
_context.Products.Add(p);
_context.SaveChanges();
var test = _context.Products.Where(t => t.GroupP == p.GroupP).FirstOrDefault();
string response = "Id: " + test.Id.ToString() + " Produto: " + test.GroupP.ToUpper();
return response;
}
//Querry to find a specific product to edit
public Product FindToUdate(string name, int? id)
{
Product prd = new Product();
if (id.HasValue)
{
prd = _context.Products.Find(id);
if (prd == null)
{
throw new NotFoundException("Id :" + id.ToString() + "Não encontrado");
}
return prd;
}
else if (name != "")
{
prd = _context.Products.Where(c => c.GroupP == name).FirstOrDefault();
if (prd == null)
{
throw new NotFoundException("Id :" + id.ToString() + "Não encontrado");
}
return prd;
}
throw new NotFoundException("Insuficient Data to find entity!");
}
//Method to update an edited product
public string Update(Product p)
{
try
{
if (p == null)
{
throw new DbComcurrancyException("Entity could not be null or empty!");
}
_context.Products.Update(p);
_context.SaveChanges();
}
catch (DbComcurrancyException ex)
{
string msg = ex.Message;
if (ex.InnerException != null)
{
msg += "\n" + ex.InnerException;
}
throw new DbComcurrancyException("Não foi possivel atualizar veja mensagem: \n" + msg);
}
return "Update realizado com sucesso!";
}
#endregion
#endregion
}
}
<file_sep>/StockManagerCore/Models/SoldProduct.cs
#region --== Dependency declaration ==--
using System.ComponentModel.DataAnnotations;
using System;
#endregion
namespace StockManagerCore.Models
{
public class SoldProduct
{
#region --== Model properties ==--
[Key]
public int Id { get; set; }
public string NItem { get; set; } //number
public string XProd { get; set; } //group
public int QCom { get; set; } //Qty
public double VUnCom { get; set; } //Unitary Valor
public double Vtotal { get; set; } // Total Valor
public DateTime DhEmi { get; set; } //Input data
[Required]
public Company Company { get; set; }
//Navigation Prop
[Required]
public Product Product { get; set; }
#endregion
#region --== Constructors ==--
public SoldProduct() { }
public SoldProduct(string nItem, string xProd, int qCom, double vUnCom, double vtotal, DateTime dhEmi,
Product product, Company company)
{
NItem = nItem;
XProd = xProd;
QCom = qCom;
VUnCom = vUnCom;
Vtotal = vtotal;
DhEmi = dhEmi;
Product = product;
Company = company;
}
#endregion
}
}
<file_sep>/StockManagerCore/Migrations/20201028132422_v1.0InitialNewModel.cs
using System;
using Microsoft.EntityFrameworkCore.Migrations;
namespace StockManagerCore.Migrations
{
public partial class v10InitialNewModel : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Companies",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Name = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Companies", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Products",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Group = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Products", x => x.Id);
});
migrationBuilder.CreateTable(
name: "InputProducts",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
NItem = table.Column<string>(nullable: true),
XProd = table.Column<string>(nullable: true),
QCom = table.Column<int>(nullable: false),
VUnCom = table.Column<double>(nullable: false),
UCom = table.Column<string>(nullable: true),
Vtotal = table.Column<double>(nullable: false),
VUnTrib = table.Column<double>(nullable: false),
VTotTrib = table.Column<double>(nullable: false),
DhEmi = table.Column<DateTime>(nullable: false),
CompanyId = table.Column<int>(nullable: true),
ProductId = table.Column<int>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_InputProducts", x => x.Id);
table.ForeignKey(
name: "FK_InputProducts_Companies_CompanyId",
column: x => x.CompanyId,
principalTable: "Companies",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_InputProducts_Products_ProductId",
column: x => x.ProductId,
principalTable: "Products",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "SoldProducts",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
NItem = table.Column<string>(nullable: true),
XProd = table.Column<string>(nullable: true),
QCom = table.Column<int>(nullable: false),
VUnCom = table.Column<double>(nullable: false),
Vtotal = table.Column<double>(nullable: false),
DhEmi = table.Column<DateTime>(nullable: false),
CompanyId = table.Column<int>(nullable: true),
ProductId = table.Column<int>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_SoldProducts", x => x.Id);
table.ForeignKey(
name: "FK_SoldProducts_Companies_CompanyId",
column: x => x.CompanyId,
principalTable: "Companies",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_SoldProducts_Products_ProductId",
column: x => x.ProductId,
principalTable: "Products",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "Stocks",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
ProductId = table.Column<int>(nullable: true),
QtyPurchased = table.Column<int>(nullable: false),
QtySold = table.Column<int>(nullable: false),
AmountPurchased = table.Column<double>(nullable: false),
AmountSold = table.Column<double>(nullable: false),
CalcDate = table.Column<DateTime>(nullable: false),
CompanyId = table.Column<int>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Stocks", x => x.Id);
table.ForeignKey(
name: "FK_Stocks_Companies_CompanyId",
column: x => x.CompanyId,
principalTable: "Companies",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_Stocks_Products_ProductId",
column: x => x.ProductId,
principalTable: "Products",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateIndex(
name: "IX_InputProducts_CompanyId",
table: "InputProducts",
column: "CompanyId");
migrationBuilder.CreateIndex(
name: "IX_InputProducts_ProductId",
table: "InputProducts",
column: "ProductId");
migrationBuilder.CreateIndex(
name: "IX_SoldProducts_CompanyId",
table: "SoldProducts",
column: "CompanyId");
migrationBuilder.CreateIndex(
name: "IX_SoldProducts_ProductId",
table: "SoldProducts",
column: "ProductId");
migrationBuilder.CreateIndex(
name: "IX_Stocks_CompanyId",
table: "Stocks",
column: "CompanyId");
migrationBuilder.CreateIndex(
name: "IX_Stocks_ProductId",
table: "Stocks",
column: "ProductId");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "InputProducts");
migrationBuilder.DropTable(
name: "SoldProducts");
migrationBuilder.DropTable(
name: "Stocks");
migrationBuilder.DropTable(
name: "Companies");
migrationBuilder.DropTable(
name: "Products");
}
}
}
<file_sep>/StockManagerCore/Models/User.cs
#region --== Using includes ==--
using StockManagerCore.Models.Enum;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using StockManagerCore.Models.CryptoService;
using System.Windows;
using System;
#endregion
namespace StockManagerCore.Models
{
public class User
{
#region --== Properties ==--
[Key]
public int Id { get; set; }
public string UserName { get; set; }
public string Name { get; set; }
public UserType UserType { get; set; }
public string Email { get; set; }
private string MD5Password { get; set; }
public bool Status { get; set; }
#endregion
#region --== Private Props ==--
[NotMapped]
private string Keychange;
#endregion
#region --== Constructors ==--
public User() { }
public User(string name,
string userName,
UserType userType,
string email,
string openPass,
bool status )
{
Name = name;
UserName = userName;
UserType = userType;
Email = email;
Keychange = "";
SetPass( openPass );
Status= status;
}
#endregion
#region --== Public Methods ==--
public bool SetPass( string password )
{
try
{
Keychange = password;
MD5Password = CypherPass( Keychange );
return true;
}
catch ( ApplicationException ex )
{
MessageBox.Show(
ex.Message,
"Erro ao gravar senha!",
MessageBoxButton.OK,
MessageBoxImage.Error );
}
return false;
}
public bool CheckPass( string passKey )
{
if ( CypherCheck( passKey ) )
{
return true;
}
else
{
return false;
}
}
public bool ChangePass( string passkey, string newPass )
{
if ( CheckPass( passkey ) )
{
return SetPass( newPass );
}
else
{
MessageBox.Show(
"Não foi possivel trocar a senha!\n Verifique a senha atual e tente novamente!",
"Erro ao gravar senha!",
MessageBoxButton.OK,
MessageBoxImage.Error );
return false;
}
}
#endregion
#region --== Private Methods ==--
private string CypherPass( string password )
{ return CypherModule.MD5Return( password ); }
private bool CypherCheck( string passKey )
{ return CypherModule.MD5Compare( passKey, MD5Password ); }
#endregion
}
}
<file_sep>/StockManagerCore/Models/Stock.cs
#region --== Dependencies declaration ==--
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
#endregion
namespace StockManagerCore.Models
{
public class Stock
{
#region --== Model Properties ==--
[Key]
public int Id { get; set; }
[Required]
[Display(Name ="Produto")]
public Product Product { get; set; }
[Display(Name ="Qte. Comprada")]
public int QtyPurchased { get; private set; }
[Display(Name ="Qte. Vendida")]
public int QtySold { get; private set; }
[Display(Name ="Valor Compra")]
public double AmountPurchased { get; set; }
[Display(Name ="Valor Venda")]
public double AmountSold { get; set; }
[Display(Name ="Ultima Entrada")]
public DateTime LastInput { get; set; }
[Display(Name ="Ultima Saída")]
public DateTime LastSales { get; set; }
[Required]
[Display(Name ="Empresa")]
public Company Company { get; set; }
[Display(Name = "Saldo Qte Estoque")]
public int ProdQtyBalance { get; private set; }
[Display(Name = "Data do Saldo")]
public DateTime BalanceDate { get; private set; }
#endregion
#region --== Class Properties Not Mapped ==--
[NotMapped]
public List<InputProduct> InputProducts { get; set; }
[NotMapped]
public List<SoldProduct> SoldProducts { get; set; }
#endregion
#region --== Constructors ==--
public Stock() { }
public Stock(Product product, int qtyPurchased, int qtySold, double amountPurchased,
double amountSold, DateTime lstImput, Company company)
{
Product = product;
QtyPurchased = qtyPurchased;
QtySold = qtySold;
AmountPurchased = amountPurchased;
AmountSold = amountSold;
LastInput = lstImput;
Company = company;
}
public Stock(Product product, int qtyPurchased, int qtySold, double amountPurchased,
double amountSold, DateTime lstImput, DateTime lstSale, Company company)
{
Product = product;
QtyPurchased = qtyPurchased;
QtySold = qtySold;
AmountPurchased = amountPurchased;
AmountSold = amountSold;
LastInput = lstImput;
LastSales = lstSale;
Company = company;
}
#endregion
#region --== Methods ==--
//Method to make a moviment of purchase and add itens to stock
public void MovimentInput(int qty, double amount, DateTime lstD)
{
QtyPurchased += qty;
AmountPurchased += amount;
LastInput = lstD.Date;
}
//Method to make moviment of sale and subtract itens of the stock
public void MovimentSale(int qty, double amount, DateTime lstD)
{
QtySold += qty;
AmountSold += amount;
LastSales = lstD.Date;
}
public void SetBalance()
{
BalanceDate = DateTime.Now.Date;
ProdQtyBalance = QtyPurchased - QtySold;
}
#endregion
}
}
<file_sep>/StockManagerCore/Services/FileReader.cs
#region --== Dependency declaration ==--
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
#endregion
namespace StockManagerCore.Services
{
class FileReader
{
/// <summary>
/// Class destinated to process the files for import data to system model and Database.
/// This class has two ways import input records or sale records.
/// in both the treatment occurrs on the same method but in separate decisions because of the layout
/// the input file is close received, and the sales is created by the client.
/// </summary>
#region --== Local variables declarations ==--
CultureInfo provider = CultureInfo.InvariantCulture;
DateTime dhEmi;
string nItem;
string xProd;
int qCom;
double vUnCom;
string uCom;
double vTotal;
double vUnTrib;
double vTotTrib;
double totalNFe;
double somaNFe = 0.0;
int qteTotal = 0;
double dif, difUn;
#endregion
#region --== Class properties ==--
public List<InputNFe> Inputs { get; set; } = new List<InputNFe>();
public List<string[]> FileNfe { get; set; }
public string Path { get; set; }
public bool IsSales { get; set; }
#endregion
#region --== Constructors ==--
public FileReader(string path, bool isSales)
{
Path = path;
IsSales = isSales;
}
#endregion
#region --== Functional methods ==--
//Method to read the file and get the data to inside.
public string GetInputItens()
{
FileNfe = new List<string[]>();
int count = 0;
//Using method to open file and read content on the provided path
using (StreamReader sr = File.OpenText(Path)) //reduced form
{
//Loop until not the end
while (!sr.EndOfStream)
{
if (!IsSales) //If the boolean Sales seted as False - we treat Incomes.
{
//Here the method split the line by the tabulator character | in an string vector and store in an list of vectors.
string[] line = sr.ReadLine().ToUpper().Split("|");
if (count != 0) //the method disregards the header line.
{
//the decision will save only lines with these initial collumns to cleam the final matrix.
if (line[0] == "B" || line[0] == "H" || line[0] == "I" || line[0] == "N10h" || line[0] == "O07" || line[0] == "W02")
{
FileNfe.Add(line); //Matrix Created
}
}
count++;
}
else //If the Boolean was true then it is Sales so treated here.
{
//the decision splits each line by the tabulator ; in a string vector
//and add each line to an list creating a matrix
string[] line = sr.ReadLine().ToUpper().Split(";");
if (count != 0) //the method disregards the header line.
{
FileNfe.Add(line);//Matrix Created
}
count++;
}
}
//On the end of the matrix creation the process continues.
if (!IsSales) //Method for inputs bool = false
{
ProcessInputFile(); //calling input file process method
}
else //method for sales bool = true
{
ProcessOutputFile(); //calling output file process method.
}
}
return "Inputs Added : " + Inputs.Count; // returns the processed inputs at the end.
}
//Method to generate the name of the product as groupnames, getting in the description name of each product
private void GenerateGroups()
{
//get names of the groups from name of product
for (int i = 0; i < Inputs.Count; i++)
{
if (Inputs[i].XProd.Contains("ANEL") || Inputs[i].XProd.Contains("ANEIS") || Inputs[i].XProd.Contains("ANÉIS"))
{
Inputs[i].Group = "ANEL";
}
else if (Inputs[i].XProd.Contains("ARGOLA") || Inputs[i].XProd.Contains("Trio de Argolas") || Inputs[i].XProd.Contains("ARGOLAS"))
{
Inputs[i].Group = "ARGOLA";
}
else if (Inputs[i].XProd.Contains("BRACELETE") || Inputs[i].XProd.Contains("BRACELETES"))
{
Inputs[i].Group = "BRACELETE";
}
else if (Inputs[i].XProd.Contains("BRINCO") || Inputs[i].XProd.Contains("BRINCOS"))
{
Inputs[i].Group = "BRINCO";
}
else if (Inputs[i].XProd.Contains("CHOKER") || Inputs[i].XProd.Contains("GARGANTILHA") || Inputs[i].XProd.Contains("GARGANTILHAS"))
{
Inputs[i].Group = "CHOKER";
}
else if (Inputs[i].XProd.Contains("COLAR") || Inputs[i].XProd.Contains("CORDAO")
|| Inputs[i].XProd.Contains("CORDÃO") || Inputs[i].XProd.Contains("ESCAPULARIO")
|| Inputs[i].XProd.Contains("ESCAPULÁRIO") || Inputs[i].XProd.Contains("COLARES")
|| Inputs[i].XProd.Contains("CORDÕES") || Inputs[i].XProd.Contains("CORDOES")
|| Inputs[i].XProd.Contains("ESCAPULARIOS") || Inputs[i].XProd.Contains("ESCAPULÁRIOS"))
{
Inputs[i].Group = "COLAR";
}
else if (Inputs[i].XProd.Contains("CORRENTE") || Inputs[i].XProd.Contains("CORRENTES"))
{
Inputs[i].Group = "CORRENTE";
}
else if (Inputs[i].XProd.Contains("PINGENTE") || Inputs[i].XProd.Contains("PINGENTES"))
{
Inputs[i].Group = "PINGENTE";
}
else if (Inputs[i].XProd.Contains("PULSEIRA") || Inputs[i].XProd.Contains("PULSEIRAS"))
{
Inputs[i].Group = "PULSEIRA";
}
else if (Inputs[i].XProd.Contains("TORNOZELEIRA") || Inputs[i].XProd.Contains("TORNOZELEIRAS"))
{
Inputs[i].Group = "TORNOZELEIRA";
}
else if (Inputs[i].XProd.Contains("VARIADOS") || Inputs[i].XProd.Contains("VARIADO")
|| Inputs[i].XProd.Contains("VARIADA") || Inputs[i].XProd.Contains("VARIADAS"))
{
Inputs[i].Group = "VARIADOS";
}
else if (Inputs[i].XProd.Contains("BROCHE") || Inputs[i].XProd.Contains("BROCHES"))
{
Inputs[i].Group = "BROCHE";
}
else if (Inputs[i].XProd.Contains("PARTES E") || Inputs[i].XProd.Contains("PECAS") || Inputs[i].XProd.Contains("PEÇAS"))
{
Inputs[i].Group = "PEÇAS";
}
else if (Inputs[i].XProd.Contains("CONJUNTO") || Inputs[i].XProd.Contains("KIT") || Inputs[i].XProd.Contains("CONJUNTOS"))
{
Inputs[i].Group = "CONJUNTO";
}
else if (Inputs[i].XProd.Contains("ACESSÓRIOS") || Inputs[i].XProd.Contains("ACESSORIOS")
|| Inputs[i].XProd.Contains("acessorios") || Inputs[i].XProd.Contains("acessórios"))
{
Inputs[i].Group = "ACESSORIO";
}
else
{
Inputs[i].Group = "VARIADOS";
}
}
}
//Process the lines of the Incomings, treat each line on collumn 0 to identificate each field data
//on the tabulated string.
private void ProcessLines(string[] line)
{
if (line[0] == "B") //Lines that begins with B have the date on position 7 of the tabulated vector
{
DateTime date = new DateTime();
date = DateTime.Parse(line[7], provider, DateTimeStyles.None);
dhEmi = date.Date;
}
else if (line[0] == "H")//Lines that begins with H have the item number on position 1 of the tabulated vector
{
nItem = line[1];
}
else if (line[0] == "I")//Lines that begins with I have the Products xpecs on position 3, 7, 8 and 9 of the tabulated vector
{
qCom = 0;
vUnCom = 0.0;
xProd = "";
uCom = "";
xProd = line[3];
qCom = Convert.ToInt32(Math.Round(double.Parse(line[8], CultureInfo.InvariantCulture)));
vUnCom = double.Parse(line[9], CultureInfo.InvariantCulture);
uCom = line[7];
vTotal = qCom * vUnCom;
}
else if (line[0] == "N10h")//Lines that begins with N10h have the ICMS Taxes on position 7 of the tabulated vector
{
//ICMS
vTotTrib = 0.0;
vTotTrib = double.Parse(line[7], CultureInfo.InvariantCulture);
}
else if (line[0] == "O07")//Lines that begins with O07 have the IPI Tax on position 2 of the tabulated vector
{
//IPI
vTotTrib += double.Parse(line[2], CultureInfo.InvariantCulture);
vUnTrib = vTotTrib / qCom;
}
else if (line[0] == "W02") //Lines that begins with W02 have the Total amount on position 19 of the tabulated vector
{
totalNFe = double.Parse(line[19], CultureInfo.InvariantCulture);
}
}
//Process the file of Inputs
private void ProcessInputFile()
{
Inputs.Clear();
int count = 0;
for (int i = 0; i < FileNfe.Count; i++)
{
if (i == 0)
{
ProcessLines(FileNfe[i]); //Call the Method to process the lines of the file
}
else
{
string[] test = FileNfe[i];
if (test[0] == "H")// Verifys if the line is An item inicialization.
{
count++;
for (int j = 0; j < 4; j++)
{
ProcessLines(FileNfe[i + j]);//Process the products expecs of each item
}
InputNFe p = new InputNFe(); //Create a new temporary instance of the mirror model.
p.DhEmi = dhEmi;
p.NItem = nItem;
p.XProd = xProd;
p.QCom = qCom;
p.VUnCom = vUnCom;
p.UCom = uCom;
p.Vtotal = vTotal;
p.Vtotal = vTotal + vTotTrib;
p.VTotTrib = vTotTrib;
p.VUnTrib = vUnTrib + vUnCom;
Inputs.Add(p); //Add the temporary to a list
}
else if (test[0] == "W02") // if this came to true the the file came to end and the method will get the total amount
{
ProcessLines(FileNfe[i]);
}
}
}
foreach (InputNFe item in Inputs)
{
//Creates an total of Products purchased and total qty
somaNFe += item.Vtotal;
qteTotal += item.QCom;
}
if (totalNFe > somaNFe) //tests if the amount of the file is greater than the sum got above.
{
//Calculates the difference beetween total and the sum of products total.
dif = totalNFe - somaNFe;
//Divides the difference by the totoal qty
difUn = dif / qteTotal;
foreach (InputNFe item in Inputs)
{
//Adds the unitary difference multiplied by qty purchased and sum to total of that product.
item.Vtotal += (difUn * item.QCom);
//Sum the unitary difference to the unitary value
item.VUnCom += difUn;
}
}
GenerateGroups(); //Call the method to generate the name as groups.
}
//Process the file of sales
private void ProcessOutputFile()
{
Inputs.Clear();
foreach (string[] line in FileNfe)
{
//Instances the temporary mirror model
InputNFe sl = new InputNFe();
//attributes all values from the matrix line to the model
sl.NItem = line[0];
sl.XProd = line[1].ToUpper();
sl.QCom = int.Parse(line[2]);
sl.VUnCom = double.Parse(line[4]);
sl.Vtotal = double.Parse(line[3]);
sl.DhEmi = DateTime.ParseExact(line[5], "dd/MM/yyyy", provider);
sl.Group = "";
sl.UCom = "";
sl.VTotTrib = 0.0;
sl.VUnTrib = 0.0;
//add the instance to the list.
Inputs.Add(sl);
}
GenerateGroups();
}
#endregion
}
}
<file_sep>/StockManagerCore/Models/DispStockCompany.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace StockManagerCore.Models
{
public struct DispStockCompany
{
public string Produto { get; set; }
public int QteCompra { get; set; }
public String ValorMedio { get; set; } //Formated
public int QteVendida { get; set; }
public int QteSaldo { get; set; }
public String ValorSaldo { get; set; } //Formated
public String DataSaldo { get; set; }// Formated
public String ValorCompra { get; set; } //Formated
public String ValorVenda { get; set; } //Formated
public String UltimaSaída { get; set; }
public String UltimaEntrada { get; set; }
}
}
<file_sep>/StockManagerCore/Migrations/20201119143358_NFControl.cs
using System;
using Microsoft.EntityFrameworkCore.Migrations;
namespace StockManagerCore.Migrations
{
public partial class NFControl : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Cities",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
CityName = table.Column<string>(nullable: true),
State = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Cities", x => x.Id);
});
migrationBuilder.CreateTable(
name: "People",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Name = table.Column<string>(nullable: false),
Doc = table.Column<string>(nullable: true),
CityId = table.Column<int>(nullable: true),
State = table.Column<int>(nullable: false),
Type = table.Column<int>(nullable: false),
Category = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_People", x => x.Id);
table.ForeignKey(
name: "FK_People_Cities_CityId",
column: x => x.CityId,
principalTable: "Cities",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "NFControls",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
NFNumber = table.Column<int>(nullable: false),
Value = table.Column<double>(nullable: false),
Operation = table.Column<int>(nullable: false),
Expiration = table.Column<DateTime>(nullable: false),
OperationType = table.Column<int>(nullable: false),
CompanyId = table.Column<int>(nullable: false),
DestinataryId = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_NFControls", x => x.Id);
table.ForeignKey(
name: "FK_NFControls_Companies_CompanyId",
column: x => x.CompanyId,
principalTable: "Companies",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_NFControls_People_DestinataryId",
column: x => x.DestinataryId,
principalTable: "People",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_NFControls_CompanyId",
table: "NFControls",
column: "CompanyId");
migrationBuilder.CreateIndex(
name: "IX_NFControls_DestinataryId",
table: "NFControls",
column: "DestinataryId");
migrationBuilder.CreateIndex(
name: "IX_People_CityId",
table: "People",
column: "CityId");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "NFControls");
migrationBuilder.DropTable(
name: "People");
migrationBuilder.DropTable(
name: "Cities");
}
}
}
<file_sep>/StockManagerCore/Migrations/20210521110857_UserInterface.cs
using Microsoft.EntityFrameworkCore.Migrations;
namespace StockManagerCore.Migrations
{
public partial class UserInterface : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.RenameColumn(
name: "UserTyoe",
table: "Users",
newName: "UserType");
migrationBuilder.RenameColumn(
name: "Password",
table: "Users",
newName: "Name");
migrationBuilder.AddColumn<bool>(
name: "Status",
table: "Users",
type: "bit",
nullable: false,
defaultValue: false);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "Status",
table: "Users");
migrationBuilder.RenameColumn(
name: "UserType",
table: "Users",
newName: "UserTyoe");
migrationBuilder.RenameColumn(
name: "Name",
table: "Users",
newName: "Password");
}
}
}
<file_sep>/StockManagerCore/Models/Enum/UserType.cs
namespace StockManagerCore.Models.Enum
{
public enum UserType : int
{
Administrador = 1,
Usuario = 2
}
}
<file_sep>/StockManagerCore/Models/Product.cs
#region --== Dependency declaration ==--
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
#endregion
namespace StockManagerCore.Models
{
public class Product
{
#region --== Model properties ==--
[Required]
[Key]
public int Id { get; set; }
[Required]
public string GroupP { get; set; }
//navigation to IncomeProduct
public ICollection<InputProduct> InputProduct { get; set; }
//Navigation to Sales Product
public ICollection<SoldProduct> SoldProduct { get; set; }
#endregion
#region --== Constructors ==--
public Product() { }
public Product(string group)
{
GroupP = group;
}
#endregion
}
}
<file_sep>/StockManagerCore/Services/Exceptions/DbRelationalException.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace StockManagerCore.Services.Exceptions
{
//Custom Exception Handler
class DbRelationalException : ApplicationException { public DbRelationalException(string message) : base(message) { } }
}
<file_sep>/StockManagerCore/UserInterface/WdnUserCRUD.xaml.cs
using StockManagerCore.Models;
using StockManagerCore.Services;
using System.Collections.Generic;
using System.Windows;
using System.Linq;
using StockManagerCore.Models.Enum;
namespace StockManagerCore.UserInterface
{
public partial class WdnUserCRUD : Window
{
private readonly UserService _userServices;
private User UserToShow { get; set; } = null;
private List<User> UserList { get; set; }
public int UserId { get; set; }
public WdnUserCRUD( UserService userService )
{
_userServices = userService;
UserList = _userServices.GetUsers();
txtPassword.IsEnabled = false;
txtNewPass.IsEnabled = false;
txtPassConfirmation.IsEnabled = false;
foreach ( User u in UserList )
{
cmbUserList.Items.Add( u.Name );
}
InitializeComponent();
}
#region --== Action Buttons ==--
private void btnListUsers_Click( object sender, RoutedEventArgs e )
{
IEnumerable<object> list = from u
in UserList
select new
{
Nome = u.Name,
Usuario = u.UserName,
Permissao = u.UserType,
Status = u.Status
};
WdwGenericGridData userGrid = new WdwGenericGridData( list.ToList(), "Lista de Usuários" );
userGrid.ShowDialog();
}
private void btnUserSearch_Click( object sender, RoutedEventArgs e )
{
UserToShow = UserList
.Where( u => u.Name == cmbUserList.SelectedItem.ToString() )
.FirstOrDefault();
if ( UserToShow == null )
{
MessageBox.Show( "Usuário não encontrado",
"Manutenção de usuários",
MessageBoxButton.OK,
MessageBoxImage.Error );
ClearForm();
return;
}
FillForm( UserToShow );
}
private void btnChangePassword_Click( object sender, RoutedEventArgs e )
{
if ( UserId == -1 || UserToShow == null )
{
MessageBox.Show( "Necessário selecionar o usuário",
"Erro de senha",
MessageBoxButton.OK,
MessageBoxImage.Error );
return;
}
if ( txtPassword.Text.Trim() == string.Empty )
{
MessageBox.Show( "Necessário digitar senha",
"Erro de senha",
MessageBoxButton.OK,
MessageBoxImage.Error );
return;
}
if ( txtPassConfirmation.Text.Trim() == string.Empty || txtNewPass.Text.Trim() == string.Empty )
{
MessageBox.Show( "Necessário digitar senha nova",
"Erro de senha",
MessageBoxButton.OK,
MessageBoxImage.Error );
return;
}
if ( txtNewPass.Text != txtPassConfirmation.Text )
{
MessageBox.Show( "Nova senha e Confirmação não coincidem",
"Erro de senha",
MessageBoxButton.OK,
MessageBoxImage.Error );
return;
}
User changePass = new User();
changePass = _userServices.Find( UserId );
if ( changePass.CheckPass( txtPassword.Text ) )
{
if ( changePass.SetPass( txtPassConfirmation.Text.Trim() ) )
{
MessageBox.Show(
"Senha Alterada com Sucesso",
"Alteração de senha",
MessageBoxButton.OK,
MessageBoxImage.Information );
ClearForm();
}
else
{
MessageBox.Show(
"Senha não pode ser alterada, tente novamente!",
"Alteração de senha",
MessageBoxButton.OK,
MessageBoxImage.Exclamation );
}
}
}
private void btnSave_Click( object sender, RoutedEventArgs e )
{
txtNewPass.IsEnabled = false;
txtPassword.IsEnabled = false;
txtPassConfirmation.IsEnabled = false;
if ( UserToShow == null )
{
MessageBox.Show( "Busque novamente o usuário para alterar!",
"Manutenção de usuários",
MessageBoxButton.OK,
MessageBoxImage.Error );
ClearForm();
return;
}
UserToShow.Name = txtName.Text.Trim().ToUpper();
UserToShow.UserName = txtUsername.Text.Trim().ToLower();
if ( txtEmail.Text.Trim().Contains( "@" )
&& ( txtEmail.Text.Trim().Contains( ".com" ) || txtEmail.Text.Trim().Contains( ".net" ) ) )
{ UserToShow.Email = txtEmail.Text.Trim().ToLower(); }
if ( rbtAdmin.IsChecked == true )
{ UserToShow.UserType = UserType.Administrador; }
else
{ UserToShow.UserType = UserType.Usuario; }
if ( rbtActive.IsChecked == true )
{ UserToShow.Status = true; }
else
{ UserToShow.Status = false; }
string update = _userServices.Update( UserToShow );
if ( update == string.Empty )
{
MessageBox.Show( "Usuário não pode ser atualizado",
"Atualização de Usuário",
MessageBoxButton.OK,
MessageBoxImage.Error );
return;
}
MessageBox.Show( update,
"Atualização de Usuário",
MessageBoxButton.OK,
MessageBoxImage.Information );
}
private void btnClear_Click( object sender, RoutedEventArgs e )
{
ClearForm();
}
private void btnAddUser_Click( object sender, RoutedEventArgs e )
{
if ( txtName.Text.Trim() != string.Empty )
{
MessageBox.Show( "Necessário preencher nome",
"Cadastro de Usuários",
MessageBoxButton.OK,
MessageBoxImage.Exclamation );
return;
}
if ( txtEmail.Text.Trim() != string.Empty )
{
MessageBox.Show( "Necessário preencher email",
"Cadastro de Usuários",
MessageBoxButton.OK,
MessageBoxImage.Exclamation );
return;
}
if ( txtUsername.Text.Trim() != string.Empty )
{
MessageBox.Show( "Necessário preencher usuário",
"Cadastro de Usuários",
MessageBoxButton.OK,
MessageBoxImage.Exclamation );
return;
}
if ( !txtNewPass.Text.Trim().Equals( txtPassConfirmation.Text.Trim() ) )
{
MessageBox.Show( "Senha Nova e Confirmação não coincidem digite novamente.",
"Cadastro de Usuários",
MessageBoxButton.OK,
MessageBoxImage.Exclamation );
return;
}
string create = _userServices.Create( UserToShow );
if ( create == string.Empty )
{
MessageBox.Show( "Usuário não pode ser criado",
"Cadastro de Usuário",
MessageBoxButton.OK,
MessageBoxImage.Error );
return;
}
MessageBox.Show( create,
"Cadastro de Usuário",
MessageBoxButton.OK,
MessageBoxImage.Information );
}
private void btnDeleteUser_Click( object sender, RoutedEventArgs e )
{
if ( cmbUserList.SelectedItem == null )
{
MessageBox.Show( "Necessário selecionar para deletar",
"Manutenção de usuários",
MessageBoxButton.OK,
MessageBoxImage.Information );
}
UserToShow = UserList
.Where( u => u.Name == cmbUserList.SelectedItem.ToString() )
.FirstOrDefault();
if ( UserToShow == null )
{
MessageBox.Show( "Usuário não encontrado",
"Manutenção de usuários",
MessageBoxButton.OK,
MessageBoxImage.Error );
ClearForm();
return;
}
FillForm( UserToShow );
MessageBoxResult mr = MessageBox.Show(
"Desativar usuário: "
+ UserToShow.Name,
"Confirmação de Desativação",
MessageBoxButton.YesNo,
MessageBoxImage.Question );
if ( mr == MessageBoxResult.Yes )
{
UserToShow.Status = false;
UserToShow.UserType = UserType.Usuario;
string delete = _userServices.Update( UserToShow );
MessageBox.Show( delete,
"Desativação de usuários",
MessageBoxButton.OK,
MessageBoxImage.Information );
ClearForm();
}
else
{
MessageBox.Show( "Desativação Cancelada",
"Desativação de usuários",
MessageBoxButton.OK,
MessageBoxImage.Information );
return;
}
}
private void btnExit_Click( object sender, RoutedEventArgs e )
{
ClearForm();
this.Close();
}
#endregion
#region --== Local Methods ==--
private void FillForm( User u )
{
UserId = u.Id;
txtName.Text = u.Name;
txtUsername.Text = u.UserName;
txtEmail.Text = u.Email;
txtPassword.IsEnabled = true;
txtNewPass.IsEnabled = true;
txtPassConfirmation.IsEnabled = true;
}
private void ClearForm()
{
UserId = -1;
UserToShow = null;
cmbUserList.SelectedItem = null;
txtEmail.Text = string.Empty;
txtName.Text = string.Empty;
txtNewPass.Text = string.Empty;
txtPassConfirmation.Text = string.Empty;
txtPassword.Text = string.Empty;
txtUsername.Text = string.Empty;
rbtUser.IsChecked = false;
rbtAdmin.IsChecked = false;
rbtActive.IsChecked = false;
rbtInactive.IsChecked = false;
txtNewPass.IsEnabled = false;
txtPassConfirmation.IsEnabled = false;
txtPassword.IsEnabled = false;
}
#endregion
}
}
<file_sep>/StockManagerCore/Services/SaleService.cs
#region --== Dependency declatation ==--
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using StockManagerCore.Data;
using StockManagerCore.Models;
#endregion
namespace StockManagerCore.Services
{
public class SaleService
{
#region --== Constructor for dependency injections ==--
//Constructor and dependency injection to DBContext
private readonly StockDBContext _context;
public SaleService(StockDBContext context) { _context = context; }
#endregion
#region --== Methods ==--
//Method to insert multiple sales on database
public void InsertMultiSales(List<SoldProduct> sales)
{
try
{
_context.SoldProducts.AddRange(sales);
_context.SaveChanges();
}
catch (DbUpdateConcurrencyException ex)
{
throw new DbUpdateConcurrencyException(ex.Message);
}
}
//Querry to retrieve all sales from database
public IEnumerable<SoldProduct> GetSales()
{
return _context.SoldProducts
.Include(s => s.Company)
.Include(s => s.Product).OrderBy(s => s.Company);
}
//Querry to find sales filtering by date and company
public IEnumerable<SoldProduct> GetSalesByDateAndCompany(DateTime di, DateTime df, Company co)
{
return _context.SoldProducts
.Include(s => s.Product)
.Include(s => s.Company)
.Where(c => c.Company.Id == co.Id)
.Where(s => s.DhEmi.Year >= di.Year
&& s.DhEmi.Month >= di.Month
&& s.DhEmi.Day >= di.Day
&& s.DhEmi.Year <= df.Year
&& s.DhEmi.Month <= df.Month
&& s.DhEmi.Day <= df.Day);
}
//Querry to find sales filtering by date.
public IEnumerable<SoldProduct> GetSalesByDate(DateTime di, DateTime df)
{
return _context.SoldProducts
.Include(s => s.Product)
.Include(s => s.Company)
.Where(s => s.DhEmi.Year >= di.Year
&& s.DhEmi.Month >= di.Month
&& s.DhEmi.Day >= di.Day
&& s.DhEmi.Year <= df.Year
&& s.DhEmi.Month <= df.Month
&& s.DhEmi.Day <= df.Day);
}
#endregion
}
}
<file_sep>/StockManagerCore/Startup.cs
#region --== Dependency declaration ==--
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using StockManagerCore.Data;
#endregion
namespace StockManagerCore
{
public class StartupFactory : IDesignTimeDbContextFactory<StockDBContext>
{
public StockDBContext CreateDbContext(string[] args)
{
var optionsBuilder = new DbContextOptionsBuilder<StockDBContext>();
optionsBuilder.UseSqlServer("server=tcp:=192.168.100.2,1433;Network Library = DBMSSOCN;Initial Catalog=StockKManagerDB;User Id=appuser;Password=<PASSWORD>;");
return new StockDBContext(optionsBuilder.Options);
}
}
}
<file_sep>/StockManagerCore/Services/InputNFe.cs
using System;
namespace StockManagerCore.Services
{
public class InputNFe
{
//Auxiliary Class to avoid interact directly to the model.
// Used to temporary store the inputs and treat the names of the products.
#region --== Field properties ==--
public DateTime DhEmi { get; set; }
public string NItem { get; set; }
public string XProd { get; set; }
public int QCom { get; set; }
public double VUnCom { get; set; }
public string UCom { get; set; }
public double Vtotal { get; set; }
public double VUnTrib { get; set; }
public double VTotTrib { get; set; }
public string Group { get; set; }
#endregion
//Method to Alternat the name of the product as groups name
public void AlternateNames()
{
//get names of the groups from name of product
if (XProd.Contains("ANEL"))
{
XProd = "ANEL";
}
else if (XProd.Contains("ARGOLA") || XProd.Contains("Trio de Argolas"))
{
XProd = "ARGOLA";
}
else if (XProd.Contains("BRACELETE"))
{
XProd = "BRACELETE";
}
else if (XProd.Contains("BRINCO"))
{
XProd = "BRINCO";
}
else if (XProd.Contains("CHOKER") || XProd.Contains("GARGANTILHA")
|| XProd.Contains("GARGANTILHAS"))
{
XProd = "CHOKER";
}
else if (XProd.Contains("COLAR") || XProd.Contains("CORDAO"))
{
XProd = "COLAR";
}
else if (XProd.Contains("CORRENTE"))
{
XProd = "CORRENTE";
}
else if (XProd.Contains("PINGENTE"))
{
XProd = "PINGENTE";
}
else if (XProd.Contains("PULSEIRA"))
{
XProd = "PULSEIRA";
}
else if (XProd.Contains("TORNOZELEIRA"))
{
XProd = "TORNOZELEIRA";
}
else if (XProd.Contains("VARIADOS")|| XProd.Contains("VARIADAS")|| XProd.Contains("VARIADO") || XProd.Contains("VARIADA"))
{
XProd = "VARIADOS";
}
else if (XProd.Contains("BROCHE"))
{
XProd = "BROCHE";
}
else if (XProd.Contains("PARTES E"))
{
XProd = "PEÇAS";
}
else if (XProd.Contains("CONJUNTO") || XProd.Contains("KIT"))
{
XProd = "CONJUNTO";
}
else if (XProd.Contains("ACESSÓRIOS") || XProd.Contains("ACESSORIOS")
|| XProd.Contains("acessorios") || XProd.Contains("acessórios"))
{
XProd = "ACESSORIO";
}
else
{
XProd = "VARIADOS";
}
}
}
}
<file_sep>/StockManagerCore/Services/InputService.cs
#region --== Dependency declaration ==--
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using StockManagerCore.Data;
using StockManagerCore.Models;
#endregion
namespace StockManagerCore.Services
{
public class InputService
{
#region --== Constructor for dependency injector ==--
private readonly StockDBContext _context;
public InputService(StockDBContext context) { _context = context; }
#endregion
#region --== Methods ==--
//Querry to fetch all inputs from Db
public IEnumerable<InputProduct> GetInputs()
{
return _context.InputProducts
.Include(i => i.Product)
.Include(i => i.Company);
}
//Querry to fetch inputs by date
public IEnumerable<InputProduct> GetInputsByDate(DateTime date)
{
return _context.InputProducts
.Where(i => i.DhEmi.Year == date.Year
&& i.DhEmi.Month == date.Month
&& i.DhEmi.Day == date.Day)
.Include(i => i.Product)
.Include(i => i.Company)
.ToList();
}
//Querry to fetch inputs by date and Company
public IEnumerable<InputProduct> GetInputsByDateAndCompany(DateTime date, Company co)
{
return _context.InputProducts
.Where(i => i.Company.Id == co.Id)
.Where(i => i.DhEmi.Year == date.Year
&& i.DhEmi.Month == date.Month
&& i.DhEmi.Day == date.Day)
.Include(i => i.Product)
.Include(i => i.Company);
}
//Querry to InsertNew Inputs
public void InsertInputs(InputProduct input)
{
try
{
_context.InputProducts.Add(input);
_context.SaveChanges();
}
catch (DbUpdateConcurrencyException ex)
{
throw new DbUpdateConcurrencyException(ex.Message);
}
}
#endregion
}
}
<file_sep>/StockManagerCore/UserInterface/WdnStockCrud.xaml.cs
using StockManagerCore.Models;
using StockManagerCore.Services;
using StockManagerCore.Services.Exceptions;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Windows;
using StockManagerCore.UserInterface;
namespace StockManagerCore.UserInterface
{
/// <summary>
/// Lógica interna para WdnStockCrud.xaml
/// </summary>
public partial class WdnStockCrud : Window
{
#region --== Instances of Context, Provider and StringBuilder ==--
/*Declatarions for dependency injection of services classes.
* Each one of the services are responsible for the model thats concern to
* Each method in the single service is designed to a single purpose.
* trying to obey SOLID principles.
*/
private readonly ProductService _productService;
private readonly CompanyService _companyService;
private readonly StockService _stockService;
//declaration of culture info for less verbose code
//CultureInfo provider = CultureInfo.CurrentCulture;
//Declaration of the log string builder. This log is merely for information and its not stored in any place for a while.
StringBuilder log = new StringBuilder();
#endregion
#region --== Models instantitation and support Lists ==--
/*Private declaration of the models extructure for local use only and in order to facilitate
the management of data*/
private Company SelectedCompany { get; set; } = new Company();
private Product SelectedProduct { get; set; } = new Product();
private Stock SelectedStock { get; set; } = new Stock();
private IEnumerable<Company> ListCompanies { get; set; }
private List<DispStockCompany> ListOfStocksStruct { get; set; }
private IEnumerable<Product> ListOfProducts { get; set; }
private IEnumerable<object> GridList { get; set; }
public WdwGenericGridData companyGrid { get; set; }
#endregion
public WdnStockCrud(ProductService productService, CompanyService companyService,
StockService stockService)
{
_productService = productService;
_companyService = companyService;
_stockService = stockService;
InitializeComponent();
//these is for populate de comboboxes.
ListCompanies = _companyService.GetCompanies();
ListOfProducts = _productService.GetProducts();
foreach (Company c in ListCompanies)
{
CmbStkCompany.Items.Add(c.Name);
}
foreach (Product product in ListOfProducts)
{
CmbStkProduct.Items.Add(product.GroupP);
}
InitializeComponent();
}
#region --== CRUD Companies, Products and Stock==--
private void Btn_Select_Click(object sender, RoutedEventArgs e)
{
switch (CmbSwitch.SelectedItem.ToString())
{
//Selects the type of Searching service to use according to the user selection
//And populates the controls with the returned data.
case "Empresa":
SelectedCompany = _companyService.FindByName(TxtSelection.Text.ToUpper());
TxtCoId.Text = SelectedCompany.Id.ToString();
TxtCoName.Text = SelectedCompany.Name;
txtCompanyMaxRevenues.Text = SelectedCompany.MaxRevenues.ToString("C2");
txtCompanyBalance.Text = SelectedCompany.Balance.ToString("C2");
InitializeComponent();
break;
case "Produto":
SelectedProduct = _productService.FindByGroup(TxtSelection.Text.ToUpper());
TxtProdId.Text = SelectedProduct.Id.ToString();
TxtProdGroupP.Text = SelectedProduct.GroupP;
InitializeComponent();
break;
case "Estoque":
string[] pars = TxtSelection.Text.Split(',');
SelectedCompany = _companyService.FindByName(pars[0]);
SelectedStock = _stockService.GetStockByCompanyAndGroup(SelectedCompany, pars[1]);
TxtStkId.Text = SelectedStock.ToString();
TxtStkQtyPurchased.Text = SelectedStock.QtyPurchased.ToString();
TxtStkQtySold.Text = SelectedStock.QtySold.ToString();
TxtStkAmountPurchased.Text = SelectedStock.AmountPurchased.ToString("C2");
TxtStkAmountSold.Text = SelectedStock.AmountSold.ToString("C2");
CmbStkCompany.SelectedItem = SelectedStock.Company.Name;
CmbStkProduct.SelectedItem = SelectedStock.Product.GroupP;
DPkrStkLastInput.DisplayDate = SelectedStock.LastInput.Date;
DPkrStkLastSale.DisplayDate = SelectedStock.LastSales.Date;
InitializeComponent();
break;
default:
break;
}
}
//Crud Company
private void Btn_CreateComp_Click(object sender, RoutedEventArgs e)
{
//Method for Create a New Company Record
try
{
if (TxtCoName == null)
{
//Validation required field
throw new RequiredFieldException("Favor preencher o nome da empresa para cadastrar");
}
//Calling Method Create from service layer and Returning to the log
log.AppendLine(_companyService.Create(TxtCoName.Text, Convert.ToDouble(txtCompanyMaxRevenues.Text)));
TxtBlkLogCRUD.Text = log.ToString();
}
catch (Exception ex)
{
TxtBlkLogCRUD.Text = "";
log.Clear();
log.AppendLine(ex.Message);
if (ex.InnerException != null)
{
log.AppendLine(ex.InnerException.Message);
}
TxtBlkLogCRUD.Text = log.ToString();
}
}
private void Btn_ReadComp_Click(object sender, RoutedEventArgs e)
{
//Geting the formated List of Companies
GridList = _companyService.GetObjCompanies();
// Creating Window
companyGrid = new WdwGenericGridData(GridList.ToList(), "Empresas");
// Open Window
companyGrid.ShowDialog();
}
private void Btn_UpdateComp_Click(object sender, RoutedEventArgs e)
{
//Method to update a company
Company toUpdate = new Company();
if (TxtCoId.Text == null && TxtCoName == null)
{
//validation for update
throw new RequiredFieldException("Favor preencher o nome ou ID da empresa para Editar");
}
else
{
//calling method to find company
toUpdate = _companyService.FindToUdate(Convert.ToInt32(TxtCoId.Text));
}
if (toUpdate == null || toUpdate.Id.ToString() != TxtCoId.Text)
{
//validation of the return
throw new NotFoundException("Nenhuma empresa localizada");
}
//Updating temporary model for further update in db context
toUpdate.Name = TxtCoName.Text;
toUpdate.Id = Convert.ToInt32(TxtCoId.Text);
toUpdate.MaxRevenues = Convert.ToDouble(txtCompanyMaxRevenues.Text);
toUpdate.SetBalance(_companyService.CalculateCompanyBalance(_stockService.GetStocksByCompany(toUpdate), toUpdate));
//Calling update method in service layer and returning result to log
log.AppendLine(_companyService.Update(toUpdate));
TxtBlkLogCRUD.Text = log.ToString();
}
//Products CRUD
private void Btn_CreateProd_Click(object sender, RoutedEventArgs e)
{
//Method for create a new Product follows the same logic of the create company
try
{
if (TxtProdGroupP == null)
{
throw new RequiredFieldException("Favor preencher o nome do produto para cadastrar");
}
log.AppendLine(_productService.Create(TxtProdGroupP.Text));
TxtBlkLogCRUD.Text = log.ToString();
}
catch (Exception ex)
{
TxtBlkLogCRUD.Text = "";
log.Clear();
log.AppendLine(ex.Message);
if (ex.InnerException != null)
{
log.AppendLine(ex.InnerException.Message);
}
TxtBlkLogCRUD.Text = log.ToString();
}
}
private void Btn_ReadProd_Click(object sender, RoutedEventArgs e)
{
//Geting the formated List of Companies
GridList = _productService.GetObjProducts();
// Creating Window
companyGrid = new WdwGenericGridData(GridList.ToList(), "Produtos");
// Open Window
companyGrid.ShowDialog();
}
private void Btn_UpdateProd_Click(object sender, RoutedEventArgs e)
{
//Method to update product follows the same logic of the update company
Product toUpdate = new Product();
if (TxtProdId.Text == null && TxtProdGroupP == null)
{
throw new RequiredFieldException("Favor preencher o nome ou ID do Produto para Editar");
}
else
{
toUpdate = _productService.FindToUdate(TxtProdGroupP.Text, null);
}
if (toUpdate == null || toUpdate.Id.ToString() != TxtProdId.Text)
{
throw new NotFoundException("Nenhum Produto localizado");
}
toUpdate.GroupP = TxtProdGroupP.Text;
toUpdate.Id = Convert.ToInt32(TxtCoId.Text);
log.AppendLine(_productService.Update(toUpdate));
TxtBlkLogCRUD.Text = log.ToString();
}
//Crud Stock
private void Btn_CreateStock_Click(object sender, RoutedEventArgs e)
{
//Method to create new Stock control, follows same logic as before.
try
{
SelectedProduct = _productService.FindByGroup(CmbStkProduct.SelectedItem.ToString());
SelectedCompany = _companyService.FindByName(CmbStkCompany.SelectedItem.ToString());
if (SelectedProduct == null)
{
throw new NotFoundException("Produto não encontrado!");
}
if (SelectedCompany == null)
{
throw new NotFoundException("Empresa não encontrada!");
}
DateTime lstin = (DateTime)DPkrStkLastInput.SelectedDate;
DateTime lstout = (DateTime)DPkrStkLastSale.SelectedDate;
log.AppendLine(_stockService.Create(SelectedProduct,
Convert.ToInt32(TxtStkQtyPurchased.Text),
Convert.ToInt32(TxtStkQtySold.Text),
Convert.ToDouble(TxtStkAmountPurchased.Text),
Convert.ToDouble(TxtStkAmountSold.Text),
lstin.Date, lstout.Date,
SelectedCompany));
TxtBlkLogCRUD.Text = log.ToString();
}
catch (MyApplicationException ex)
{
TxtBlkLogCRUD.Text = "";
log.AppendLine(ex.Message);
if (ex.InnerException != null)
{
log.AppendLine(ex.InnerException.Message);
}
TxtBlkLogCRUD.Text = log.ToString();
}
}
private void Btn_ReadStock_Click(object sender, RoutedEventArgs e)
{
//Method to List all Stocks By Company
if (CmbStkCompany != null)
{
SelectedCompany = _companyService.FindByName(CmbStkCompany.SelectedItem.ToString());
if (SelectedCompany == null)
{
throw new NotFoundException("Empresa não localizada");
}
//Geting the formated List of Companies
if (chkFormated.IsChecked == true)
{
ListOfStocksStruct = _stockService.GetStocksStructured(SelectedCompany);
companyGrid = new WdwGenericGridData(ListOfStocksStruct, "Estoques", SelectedCompany);
}
else
{
GridList = _stockService.GetStocksByCompany(SelectedCompany);
companyGrid = new WdwGenericGridData(GridList.ToList(), "Estoque "+ SelectedCompany.Name);
}
// Creating Window
// Open Window
companyGrid.ShowDialog();
}
else
{
throw new RequiredFieldException("Informa a empresa para filtrar os estoques");
}
}
private void BtnBalanceCalc_Click(object sender, RoutedEventArgs e)
{
SelectedCompany = _companyService.FindByName(CmbStkCompany.SelectedItem.ToString());
if (SelectedCompany == null)
{
//Company must not be null
throw new ApplicationException("Selecione uma empresa!");
}
ListOfStocksStruct = _stockService.CalculateBalance(SelectedCompany);
GridList = (IEnumerable<object>)ListOfStocksStruct;
// Creating Window
WdwGenericGridData companyGrid = new WdwGenericGridData(GridList.ToList(), "Estoques Consolidado");
// Open Window
companyGrid.ShowDialog();
}
//Method to create an manual stock entry
private void BtnEntryStock_Click(object sender, RoutedEventArgs e)
{
SelectedProduct = _productService.FindByGroup(CmbStkProduct.SelectedItem.ToString());
SelectedCompany = _companyService.FindByName(CmbStkCompany.SelectedItem.ToString());
SelectedStock = _stockService.GetStockByCompanyAndGroup(SelectedCompany, SelectedProduct.GroupP);
SelectedStock.MovimentInput(
Convert.ToInt32(TxtStkQtyPurchased.Text),
Convert.ToDouble(TxtStkAmountPurchased.Text),
DateTime.Now.Date);
try
{
_stockService.Update(SelectedStock);
TxtBlkLogCRUD.Text = "Atualizado com sucesso";
CmbStkCompany.SelectedIndex = -1;
CmbStkProduct.SelectedIndex = -1;
TxtStkAmountPurchased.Text = string.Empty;
TxtStkAmountSold.Text = string.Empty;
TxtStkQtyPurchased.Text = string.Empty;
TxtStkQtySold.Text = string.Empty;
}
catch (ApplicationException ex)
{
TxtBlkLogCRUD.Text = "Erro ao Atualizar" + ex.Message;
throw new ApplicationException("Erro na Atualização" + ex.Message);
}
}
//Method to create an manual stock sale
private void BtnSaleStock_Click(object sender, RoutedEventArgs e)
{
SelectedProduct = _productService.FindByGroup(CmbStkProduct.SelectedItem.ToString());
SelectedCompany = _companyService.FindByName(CmbStkCompany.SelectedItem.ToString());
SelectedStock = _stockService.GetStockByCompanyAndGroup(SelectedCompany, SelectedProduct.GroupP);
SelectedStock.MovimentSale(
Convert.ToInt32(TxtStkQtySold.Text),
Convert.ToDouble(TxtStkAmountSold.Text),
DateTime.Now.Date);
try
{
_stockService.Update(SelectedStock);
TxtBlkLogCRUD.Text = "Atualizado com sucesso";
CmbStkCompany.SelectedIndex = -1;
CmbStkProduct.SelectedIndex = -1;
TxtStkAmountPurchased.Text = string.Empty;
TxtStkAmountSold.Text = string.Empty;
TxtStkQtyPurchased.Text = string.Empty;
TxtStkQtySold.Text = string.Empty;
}
catch (ApplicationException ex)
{
TxtBlkLogCRUD.Text = "Erro ao Atualizar" + ex.Message;
throw new ApplicationException("Erro na Atualização" + ex.Message);
}
}
#endregion
}
}
<file_sep>/StockManagerCore/Migrations/20201029165437_v2DataAnotations.cs
using Microsoft.EntityFrameworkCore.Migrations;
namespace StockManagerCore.Migrations
{
public partial class v2DataAnotations : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_InputProducts_Companies_CompanyId",
table: "InputProducts");
migrationBuilder.DropForeignKey(
name: "FK_InputProducts_Products_ProductId",
table: "InputProducts");
migrationBuilder.DropForeignKey(
name: "FK_SoldProducts_Companies_CompanyId",
table: "SoldProducts");
migrationBuilder.DropForeignKey(
name: "FK_SoldProducts_Products_ProductId",
table: "SoldProducts");
migrationBuilder.DropForeignKey(
name: "FK_Stocks_Companies_CompanyId",
table: "Stocks");
migrationBuilder.DropForeignKey(
name: "FK_Stocks_Products_ProductId",
table: "Stocks");
migrationBuilder.AlterColumn<int>(
name: "ProductId",
table: "Stocks",
nullable: false,
oldClrType: typeof(int),
oldType: "int",
oldNullable: true);
migrationBuilder.AlterColumn<int>(
name: "CompanyId",
table: "Stocks",
nullable: false,
oldClrType: typeof(int),
oldType: "int",
oldNullable: true);
migrationBuilder.AlterColumn<int>(
name: "ProductId",
table: "SoldProducts",
nullable: false,
oldClrType: typeof(int),
oldType: "int",
oldNullable: true);
migrationBuilder.AlterColumn<int>(
name: "CompanyId",
table: "SoldProducts",
nullable: false,
oldClrType: typeof(int),
oldType: "int",
oldNullable: true);
migrationBuilder.AlterColumn<string>(
name: "Group",
table: "Products",
nullable: false,
oldClrType: typeof(string),
oldType: "nvarchar(max)",
oldNullable: true);
migrationBuilder.AlterColumn<int>(
name: "ProductId",
table: "InputProducts",
nullable: false,
oldClrType: typeof(int),
oldType: "int",
oldNullable: true);
migrationBuilder.AlterColumn<int>(
name: "CompanyId",
table: "InputProducts",
nullable: false,
oldClrType: typeof(int),
oldType: "int",
oldNullable: true);
migrationBuilder.AlterColumn<string>(
name: "Name",
table: "Companies",
nullable: false,
oldClrType: typeof(string),
oldType: "nvarchar(max)",
oldNullable: true);
migrationBuilder.AddForeignKey(
name: "FK_InputProducts_Companies_CompanyId",
table: "InputProducts",
column: "CompanyId",
principalTable: "Companies",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_InputProducts_Products_ProductId",
table: "InputProducts",
column: "ProductId",
principalTable: "Products",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_SoldProducts_Companies_CompanyId",
table: "SoldProducts",
column: "CompanyId",
principalTable: "Companies",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_SoldProducts_Products_ProductId",
table: "SoldProducts",
column: "ProductId",
principalTable: "Products",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_Stocks_Companies_CompanyId",
table: "Stocks",
column: "CompanyId",
principalTable: "Companies",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_Stocks_Products_ProductId",
table: "Stocks",
column: "ProductId",
principalTable: "Products",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_InputProducts_Companies_CompanyId",
table: "InputProducts");
migrationBuilder.DropForeignKey(
name: "FK_InputProducts_Products_ProductId",
table: "InputProducts");
migrationBuilder.DropForeignKey(
name: "FK_SoldProducts_Companies_CompanyId",
table: "SoldProducts");
migrationBuilder.DropForeignKey(
name: "FK_SoldProducts_Products_ProductId",
table: "SoldProducts");
migrationBuilder.DropForeignKey(
name: "FK_Stocks_Companies_CompanyId",
table: "Stocks");
migrationBuilder.DropForeignKey(
name: "FK_Stocks_Products_ProductId",
table: "Stocks");
migrationBuilder.AlterColumn<int>(
name: "ProductId",
table: "Stocks",
type: "int",
nullable: true,
oldClrType: typeof(int));
migrationBuilder.AlterColumn<int>(
name: "CompanyId",
table: "Stocks",
type: "int",
nullable: true,
oldClrType: typeof(int));
migrationBuilder.AlterColumn<int>(
name: "ProductId",
table: "SoldProducts",
type: "int",
nullable: true,
oldClrType: typeof(int));
migrationBuilder.AlterColumn<int>(
name: "CompanyId",
table: "SoldProducts",
type: "int",
nullable: true,
oldClrType: typeof(int));
migrationBuilder.AlterColumn<string>(
name: "Group",
table: "Products",
type: "nvarchar(max)",
nullable: true,
oldClrType: typeof(string));
migrationBuilder.AlterColumn<int>(
name: "ProductId",
table: "InputProducts",
type: "int",
nullable: true,
oldClrType: typeof(int));
migrationBuilder.AlterColumn<int>(
name: "CompanyId",
table: "InputProducts",
type: "int",
nullable: true,
oldClrType: typeof(int));
migrationBuilder.AlterColumn<string>(
name: "Name",
table: "Companies",
type: "nvarchar(max)",
nullable: true,
oldClrType: typeof(string));
migrationBuilder.AddForeignKey(
name: "FK_InputProducts_Companies_CompanyId",
table: "InputProducts",
column: "CompanyId",
principalTable: "Companies",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_InputProducts_Products_ProductId",
table: "InputProducts",
column: "ProductId",
principalTable: "Products",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_SoldProducts_Companies_CompanyId",
table: "SoldProducts",
column: "CompanyId",
principalTable: "Companies",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_SoldProducts_Products_ProductId",
table: "SoldProducts",
column: "ProductId",
principalTable: "Products",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_Stocks_Companies_CompanyId",
table: "Stocks",
column: "CompanyId",
principalTable: "Companies",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_Stocks_Products_ProductId",
table: "Stocks",
column: "ProductId",
principalTable: "Products",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
}
}
}
<file_sep>/StockManagerCore/UserInterface/WdnProcessFiles.xaml.cs
#region --== Classes Dependencies using area ==--
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Windows;
using StockManagerCore.Models;
using StockManagerCore.Services;
#endregion
namespace StockManagerCore.UserInterface
{
/// <summary>
/// Lógica interna para WdnProcessFiles.xaml
/// </summary>
public partial class WdnProcessFiles : Window
{
#region --== Instances of Context, Provider and StringBuilder ==--
/*Declatarions for dependency injection of services classes.
* Each one of the services are responsible for the model thats concern to
* Each method in the single service is designed to a single purpose.
* trying to obey SOLID principles.
*/
private readonly InputService _inputService;
private readonly SaleService _saleService;
private readonly ProductService _productService;
private readonly CompanyService _companyService;
private readonly StockService _stockService;
//declaration of culture info for less verbose code
CultureInfo provider = CultureInfo.InvariantCulture;
//Declaration of the log string builder. This log is merely for information and its not stored in any place for a while.
StringBuilder log = new StringBuilder();
#endregion
#region --== Local Variables ==--
int importCount = 0;
string lastfile;
string filename;
FileReader nfeReader;
bool isSales;
DateTime dateInitial = new DateTime();
DateTime dateFinal = new DateTime();
int qteTot = 0;
int qty = 0;
double amount = 0.0;
double totAmount = 0.0;
int anyId = 0;
#endregion
#region --== Models instantitation and support Lists ==--
/*Private declaration of the models extructure for local use only and in order to facilitate
the management of data*/
private Company SelectedCompany { get; set; } = new Company();
private InputProduct InputProduct { get; set; } = new InputProduct();
private List<SoldProduct> ListOfSales { get; set; } = new List<SoldProduct>();
private IEnumerable<Company> ListCompanies { get; set; }
private List<DispStockCompany> ListOfStocksStruct { get; set; }
#endregion
public WdnProcessFiles(InputService inputService, SaleService saleService, ProductService productService,
CompanyService companyService, StockService stockService)
{
//Constructor of the form MainWindow here we call the dependency injection
_inputService = inputService;
_saleService = saleService;
_productService = productService;
_companyService = companyService;
_stockService = stockService;
InitializeComponent();
//these is for populate de comboboxes.
ListCompanies = _companyService.GetCompanies();
btnBalanceAll.IsEnabled = false;
btnProcessFile.IsEnabled = false;
btnProcessSales.IsEnabled = false;
BtnCalculate.IsEnabled = false;
foreach (Company c in ListCompanies)
{
CmbCompany.Items.Add(c.Name);
}
InitializeComponent();
}
#region --== Functions of Tb_Functions TAB ==--
private void BtnFileOpen_Click(object sender, RoutedEventArgs e)
{
//This method opens the dialog and permits to select a file to import.
try
{
// Create OpenFileDialog
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
// Set filter for file extension and default file extension
dlg.DefaultExt = ".txt";
dlg.Filter = "TXT Document (.TXT;.CSV)|*.TXT;*.CSV";
// Display OpenFileDialog by calling ShowDialog method
Nullable<bool> result = dlg.ShowDialog();
// Get the selected file name and display in a TextBox
if (result == true)
{
// Open document
filename = dlg.FileName;
FileNameTextBox.Text = filename;
}
}
catch (Exception ex)
{
//writing log if there is any error and showing in an textBlock
LogTextBlock.Text = "";
log.AppendLine(ex.Message);
LogTextBlock.Text = log.ToString();
}
}
private void ProcessInputs_Click(object sender, RoutedEventArgs e)
{
importCount++;
//This Method is responsible to care of process the import files in input records.
try
{
//Clean log
LogTextBlock.Text = string.Empty;
LogTextBlock.Text = "Iniciando importação em: " + importCount.ToString();
//Geting the Entity Company by mane selected in combo
SelectedCompany = _companyService.FindByName((string)CmbCompany.SelectedItem);
if (filename.EndsWith("csv") || filename.EndsWith("CSV"))
{
/*This test is simple in rule allways the file thats contains the inputs came in .TXT extention so,
* if selected was diferent throw exception */
throw new ApplicationException("Não pode processar arquivo de venda como entrada!");
}
if (SelectedCompany == null)
{
//Any company must be selected to create a link between products and company, so if its null, throw exception.
throw new ApplicationException("Selecione uma empresa!");
}
if (lastfile == filename)
{
throw new ApplicationException("Nota já Inserida");
}
//Here just inform that imports is occurring
LogTextBlock.Text = "\nImportando: " + filename;
//Sets the bool variable to False to indicate to the service class where to process this file,
//because this file is input record.
isSales = false;
log.Clear();
if (!isSales) //If Sales = False or !(not) True
{
btnProcessFile.IsEnabled = false; //Disable the ProcessFile Button
//Instance the service that process the file.
//Calling the constructor for reading the file passing the File Path and
//the Bool variable to indicate where to process
nfeReader = new FileReader(filename, isSales);
//Reading inputs and returning Log
log.AppendLine(nfeReader.GetInputItens()); //Call the Method GetInputItens that returns an string as result.
LogTextBlock.Text = log.ToString(); // Showing the result.
//Reading all imported records
foreach (InputNFe item in nfeReader.Inputs)
{
//Instances a new Product
Product p = new Product();
//Getting the entity product by his group name in the service class.
p = _productService.FindByGroup(item.Group);
//callcing an method to padronize the names of the products as groups.
item.AlternateNames();
//Instancing model class and calling constructor for each item record in service class to place data.
//Working in a private unique local instance of the model
InputProduct = new InputProduct
(item.NItem,
item.XProd,
item.QCom,
item.VUnCom,
item.UCom,
item.Vtotal,
item.VUnTrib,
item.VTotTrib,
p,
item.DhEmi,
SelectedCompany);
//calling the method to insert the data in model on db context
_inputService.InsertInputs(InputProduct);
}
}
else //Exception
{
//When this occur user trying to procees sales as inputs
LogTextBlock.Text = "";
log.AppendLine("Não pode processar venda como Compra!");
LogTextBlock.Text = log.ToString();
throw new ApplicationException("Não pode processar venda como Compra!");
}
MessageBoxResult result = MessageBox.Show("Upload Terminado, Inserir nova? " +
"\n Ao pressionar não o sistema irá limpar tudo!" +
"\n Inseridos: " + LogTextBlock.Text + " registros",
"Controle de Estoque",
MessageBoxButton.YesNo,
MessageBoxImage.Question);
if (result == MessageBoxResult.Yes)
{
LogTextBlock.Text = String.Empty;
lastfile = filename;
ClearFile();
importCount = 0;
btnProcessFile.IsEnabled = true;
}
else
{
ClearForm();
}
}
catch (Exception ex)
{
//Error Exception for whole method above.
LogTextBlock.Text = "";
log.AppendLine(ex.Message);
if (ex.InnerException != null)
{
log.AppendLine(ex.InnerException.Message);
}
LogTextBlock.Text = log.ToString();
}
}
private void ProcessSales_Click(object sender, RoutedEventArgs e)
{
//This Method is responsible to care of process the import files in Sales records.
try
{
//clean log
LogTextBlock.Text = string.Empty;
//Geting the Entity Company by mane selected in combo
SelectedCompany = _companyService.FindByName((string)CmbCompany.SelectedItem);
if (filename.EndsWith("TXT") || filename.EndsWith("txt"))
{
/*This test is simple in rule allways the file thats contains the inputs came in .CSV extention so,
* if selected was diferent throw exception */
throw new ApplicationException("Não pode processar arquivo de entrada como venda!");
}
if (SelectedCompany == null)
{
//Any company must be selected to create a link between products and company, so if its null, throw exception.
throw new ApplicationException("Selecione uma empresa!");
}
if (lastfile == filename)
{
throw new ApplicationException("Nota já Inserida");
}
//Here just inform that imports is occurring
LogTextBlock.Text = "Importando: " + filename;
//Sets the bool variable to TRUE to indicate to the service class where to process this file,
//because this file is Sales record.
isSales = true;
log.Clear();
if (isSales)
{
btnProcessSales.IsEnabled = false;
//Instance the service
nfeReader = new FileReader(filename, isSales);
//Reading inputs and returning Log
log.AppendLine(nfeReader.GetInputItens());
LogTextBlock.Text = log.ToString();
//Reading all imported records
foreach (InputNFe item in nfeReader.Inputs)
{
//Instancing a new product.
Product p = new Product();
//Getting the entity product by his group name in the service class.
p = _productService.FindByGroup(item.Group);
if (p == null)
{
//verifys if the return of the query above is null, and throw exceptios, because have to be a product
throw new ApplicationException(" Pelo menos um produto da Nota não foi encontrado! \n Importação abortada!");
}
//Instances a New Sale and call the Constructor
ListOfSales.Add(new SoldProduct
(item.NItem,
item.XProd,
item.QCom,
item.VUnCom,
item.Vtotal,
item.DhEmi,
p,
SelectedCompany));
}
//call the method to insert into db context, on services layer
_saleService.InsertMultiSales(ListOfSales);
}
else
{
//If isn´t any of the above, we throw an exception.
LogTextBlock.Text = "";
log.AppendLine("Não pode processar entrada como venda!");
LogTextBlock.Text = log.ToString();
throw new ApplicationException("Não pode processar entrada como venda!");
}
MessageBoxResult result = MessageBox.Show("Upload Terminado, Inserir nova? " +
"\n Ao pressionar não o sistema irá limpar tudo!" +
"\n Inseridos: " + LogTextBlock.Text + " registros",
"Controle de Estoque",
MessageBoxButton.YesNo,
MessageBoxImage.Question);
if (result == MessageBoxResult.Yes)
{
LogTextBlock.Text = String.Empty;
lastfile = filename;
ClearFile();
importCount = 0;
btnProcessSales.IsEnabled = true;
}
else
{
ClearForm();
}
}
catch (Exception ex)
{
//General method exception
LogTextBlock.Text = "";
log.AppendLine(ex.Message);
if (ex.InnerException != null)
{
log.AppendLine(ex.InnerException.Message);
}
LogTextBlock.Text = log.ToString();
}
}
private void Btn_Calculate_Click(object sender, RoutedEventArgs e)
{
try
{
//counter for checking purpose
int count = 0;
//get the selected company in combobox
SelectedCompany = _companyService.FindByName((string)CmbCompany.SelectedItem);
if (SelectedCompany == null)
{
//If company is null then throw exception
throw new ApplicationException("Empresa deve ser selecionada!");
}
if (RdnIn.IsChecked == true)
{
BtnCalculate.IsEnabled = false;
//Here is the separation for calcularion of inputs
//Get the inicial date typed on textBox
dateInitial = DateTime.ParseExact(TxtDateInitial.Text, "dd/MM/yyyy", provider);
//Get a List of purchased products filtered by date and company
IEnumerable<InputProduct> listInputProduct = _inputService.GetInputsByDateAndCompany(dateInitial, SelectedCompany);
//transform the list in a grouping query, grouped by Product
var groupProducts = listInputProduct.GroupBy(p => p.XProd);
//moving through grouping for process
foreach (IGrouping<string, InputProduct> group in groupProducts)
{
//instances a new stock and gte the entity Stock related to the company and the product and assign to the instance.
Stock stock = new Stock();
stock = _stockService.GetStockByCompanyAndGroup(SelectedCompany, group.Key);
//information on log
log.Append("Produto: " + group.Key);
TxtConsole.Text = log.ToString();
//sub loop moving through products in each group.
foreach (InputProduct item in group)
{
//Accumulating Quantity of purchased products
qty += item.QCom;
//accumulating value of the purchased products
amount += item.Vtotal;
//increment counter
count++;
}
//Call the inner method of stock for register de moviment.
stock.MovimentInput(qty, amount, dateInitial);
//Updates the Stock om db context using service layer
_stockService.Update(stock);
//Log to demonstrate what was carried.
log.Append(" | Qte: " + qty.ToString());
log.AppendLine(" | Valor: " + amount.ToString("C2", CultureInfo.CurrentCulture));
TxtConsole.Text = log.ToString();
qteTot += qty;
totAmount += amount;
//Zero fill the temporary variable.
qty = 0;
amount = 0.0;
}
//Final Log Sumarazing.
log.Append("QteTotal: " + qteTot.ToString());
log.AppendLine(" | ValorTotal: " + totAmount.ToString("C2", CultureInfo.CurrentCulture));
TxtConsole.Text = log.ToString();
}
if (RdnOut.IsChecked == true && SelectedCompany != null)//Continue from here 30/10
{
//Here is the separation for calcularion of Sales
//Get the inicial and final date typed on textBox
BtnCalculate.IsEnabled = false;
dateInitial = DateTime.ParseExact(TxtDateInitial.Text, "dd/MM/yyyy", provider);
dateFinal = DateTime.ParseExact(TxtDateFinal.Text, "dd/MM/yyyy", provider);
// list of sales by date and company
IEnumerable<SoldProduct> salesByDateAndCompany = _saleService.GetSalesByDateAndCompany(dateInitial, dateFinal, SelectedCompany);
//Grouping query by product
var groupOfSales = salesByDateAndCompany.GroupBy(p => p.Product.GroupP);
//moving through grouping
foreach (IGrouping<string, SoldProduct> group in groupOfSales)
{
//Instances new Stock and gets the Entity Stock by company and Product and atributes to instance
Stock stock = new Stock();
stock = _stockService.GetStockByCompanyAndGroup(SelectedCompany, group.Key);
//Log information
log.Append("Produto: " + group.Key);
TxtConsole.Text = log.ToString();
//Moving through the sales in groups
foreach (SoldProduct item in group)
{
//Accumulating Quantity and values of purchased products
qty += item.QCom;
amount += item.Vtotal;
}
//Call method for process moviment of sales in the stock
stock.MovimentSale(qty, amount, dateInitial);
//Recalculates the inputs
stock.MovimentInput(qty, amount, dateInitial);
//update the stock in dbcontext
_stockService.Update(stock);
//Log demonstration of what been prossessed
log.Append(" | Qte: " + qty.ToString());
log.AppendLine(" | Valor: " + amount.ToString("C2", CultureInfo.CurrentCulture));
TxtConsole.Text = log.ToString();
qteTot += qty;
totAmount += amount;
qty = 0;
amount = 0.0;
}
log.Append("QteTotal: " + qteTot.ToString());
log.AppendLine(" | ValorTotal: " + totAmount.ToString("C2", CultureInfo.CurrentCulture));
TxtConsole.Text = log.ToString();
}
//Counting the two lists
log.AppendLine("Lista Entradas: " + count.ToString());
log.AppendLine("Lista Saídas: " + ListOfSales.Count);
MessageBoxResult result = MessageBox.Show("Processamento Terminado, efetuar novo? " +
"\n Ao pressionar não o sistema irá limpar tudo!",
"Controle de Estoque",
MessageBoxButton.YesNo,
MessageBoxImage.Question);
if (result == MessageBoxResult.Yes)
{
LogTextBlock.Text = String.Empty;
lastfile = filename;
ClearFile();
importCount = 0;
BtnCalculate.IsEnabled = true;
TxtConsole.Text = string.Empty;
}
else
{
ClearForm();
}
}
catch (ApplicationException ex)
{
//Any Application Exception
LogTextBlock.Text = "";
log.AppendLine(ex.Message);
if (ex.InnerException != null)
{
log.AppendLine(ex.InnerException.Message);
}
LogTextBlock.Text = log.ToString();
}
}
private void Btn_ShowStock_Click(object sender, RoutedEventArgs e)
{
try
{
//Get Selected company in combo
SelectedCompany = _companyService.FindByName((string)CmbCompany.SelectedItem);
if (SelectedCompany == null)
{
//Company must not be null
throw new ApplicationException("Selecione uma empresa!");
}
ListOfStocksStruct = _stockService.GetStocksStructured(SelectedCompany); //list Resulkt
//Method to generate GridView
WdnStockGrid viewStockGrid = new WdnStockGrid( ListOfStocksStruct , SelectedCompany );
viewStockGrid.ShowDialog();
}
catch (ApplicationException ex)
{
LogTextBlock.Text = "";
log.AppendLine(ex.Message);
if (ex.InnerException != null)
{
log.AppendLine(ex.InnerException.Message);
}
LogTextBlock.Text = log.ToString();
}
}
private void BtnBalanceAll_Click(object sender, RoutedEventArgs e)
{
List<Stock> stocksToCalc;
stocksToCalc = _stockService.GetStocks();
foreach (Stock item in stocksToCalc)
{
try
{
item.SetBalance();
}
catch (Exception ex)
{
LogTextBlock.Text = "Erro ao Tentar atualizar item"
+ item.Product.GroupP
+ ", "
+ item.Company.Name
+ "."
+ "\n"
+ ex.Message;
throw new Exception(ex.Message);
}
}
_stockService.UpdateRange(stocksToCalc);
MessageBox.Show("Calculo Efetuado em:" + DateTime.Now.ToString("dd/MMM/yyyy"),
"Atualização de Saldo",
MessageBoxButton.OK,
MessageBoxImage.Information);
}
private void btnExit_Click(object sender, RoutedEventArgs e)
{
ClearFile();
ClearForm();
this.Close();
}
#endregion
#region --== Local Methods ==--
private void ClearFile()
{
filename = string.Empty;
FileNameTextBox.Text = string.Empty;
}
private void ClearForm()
{
LogTextBlock.Text = String.Empty;
TxtConsole.Text = String.Empty;
lastfile = filename;
ClearFile();
importCount = 0;
BtnCalculate.IsEnabled = true;
btnProcessSales.IsEnabled = true;
btnProcessFile.IsEnabled = true;
btnBalanceAll.IsEnabled = true;
}
#endregion
}
}
<file_sep>/StockManagerCore/Services/Session.cs
using StockManagerCore.Models;
using StockManagerCore.Models.Enum;
namespace StockManagerCore.Services
{
public class Session
{
private static Session UserSessionInstance;
public static Entity User { get; set; }
public static UserType UserType { get; set; }
public static Session GetUserSessionInstance
{
get
{
if ( UserSessionInstance == null )
{
UserSessionInstance = new Session();
}
return UserSessionInstance;
}
}
}
}
<file_sep>/StockManagerCore/Services/UserService.cs
#region --== Dependency Declaration ==--
using System.Linq;
using System.Collections.Generic;
using StockManagerCore.Data;
using StockManagerCore.Models;
using StockManagerCore.Services.Exceptions;
using StockManagerCore.Models.Enum;
#endregion
namespace StockManagerCore.Services
{
public class UserService
{
#region --== Constructor for dependency injection ==--
private readonly StockDBContext _context;
//Constructor and dependency Injection to DbContext
public UserService( StockDBContext context ) { _context = context; }
#endregion
#region --== Methods ==--
//Querry to fetch all users from database
public List<User> GetUsers()
{
return _context.Users.ToList();
}
//Querry to Find a producta By Entity
public User Find( int id )
{
User user = new User();
try
{
user = _context.Users
.Where( us => us.Id == id )
.SingleOrDefault();
if ( user.UserName == string.Empty )
{
throw new NotFoundException( "Entidade não encontrada" );
}
}
catch ( DbComcurrancyException e)
{
throw new DbComcurrancyException(e.Message);
}
return user;
}
//Querry to find product by Name
public List<User> FindByType( int type )
{
List<User> listUserType = new List<User>();
if ( type <= 0 )
{
throw new RequiredFieldException( "Campo requerido para busca" );
}
listUserType = _context.Users.Where( us => us.UserType == (UserType)type ).ToList();
if ( listUserType.Count < 1 )
{
throw new NotFoundException( "Nenhuma entidade encontrada" );
}
return listUserType;
}
#region --== CRUD ==--
//Method to create a new product on database
public string Create( User user )
{
string response = string.Empty;
try
{
_context.Users.Add( user );
_context.SaveChanges();
var test = _context.Users.Where( t => t.UserName == user.UserName ).FirstOrDefault();
response = "Id: " + test.Id.ToString() + " Usuário: " + test.UserName.ToUpper();
}
catch ( DbComcurrancyException ex )
{
if ( ex.InnerException != null )
{
response = ex.Message + "\n InnerError:" + ex.InnerException;
}
else
{
response = ex.Message;
}
throw new DbComcurrancyException( "Erro ao tentar criar usuário!\n" + response );
}
return response;
}
//Querry to find a specific product to edit
public User FindToUdate( string name, int? id )
{
User usr = new User();
if ( id.HasValue )
{
usr = _context.Users.Find( id );
if ( usr.UserName == string.Empty )
{
throw new NotFoundException( "Id :" + id.ToString() + "Não encontrado" );
}
return usr;
}
else if ( name != "" )
{
usr = _context.Users.Where( c => c.UserName == name ).FirstOrDefault();
if ( usr.UserName == string.Empty )
{
throw new NotFoundException( "Usuário :" + name + "Não encontrado" );
}
return usr;
}
throw new NotFoundException( "Insuficient Data to find entity!" );
}
//Method to update an edited product
public string Update( User u )
{
string returnMsg = string.Empty;
try
{
if ( u.UserName == string.Empty )
{
throw new DbComcurrancyException( "Entity could not be null or empty!" );
}
_context.Users.Update( u );
_context.SaveChanges();
returnMsg = "Update realizado com sucesso!";
}
catch ( DbComcurrancyException ex )
{
string msg = ex.Message;
if ( ex.InnerException != null )
{
msg += "\n InnerException: " + ex.InnerException;
}
throw new DbComcurrancyException( "Não foi possivel atualizar veja mensagem: \n" + msg );
}
return returnMsg;
}
#endregion
#endregion
}
}<file_sep>/StockManagerCore/Migrations/20210511193152_GeneralRebuil.cs
using System;
using Microsoft.EntityFrameworkCore.Migrations;
namespace StockManagerCore.Migrations
{
public partial class GeneralRebuil : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_Stocks_Products_ProductId",
table: "Stocks");
migrationBuilder.DropTable(
name: "NFControls");
migrationBuilder.DropTable(
name: "People");
migrationBuilder.DropTable(
name: "Cities");
migrationBuilder.AlterColumn<int>(
name: "ProductId",
table: "Stocks",
type: "int",
nullable: true,
oldClrType: typeof(int),
oldType: "int");
migrationBuilder.AddForeignKey(
name: "FK_Stocks_Products_ProductId",
table: "Stocks",
column: "ProductId",
principalTable: "Products",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_Stocks_Products_ProductId",
table: "Stocks");
migrationBuilder.AlterColumn<int>(
name: "ProductId",
table: "Stocks",
type: "int",
nullable: false,
defaultValue: 0,
oldClrType: typeof(int),
oldType: "int",
oldNullable: true);
migrationBuilder.CreateTable(
name: "Cities",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
CityName = table.Column<string>(type: "nvarchar(max)", nullable: true),
State = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Cities", x => x.Id);
});
migrationBuilder.CreateTable(
name: "People",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Category = table.Column<int>(type: "int", nullable: false),
CityId = table.Column<int>(type: "int", nullable: true),
Doc = table.Column<string>(type: "nvarchar(max)", nullable: true),
Name = table.Column<string>(type: "nvarchar(max)", nullable: false),
State = table.Column<int>(type: "int", nullable: false),
Type = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_People", x => x.Id);
table.ForeignKey(
name: "FK_People_Cities_CityId",
column: x => x.CityId,
principalTable: "Cities",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateTable(
name: "NFControls",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
CompanyId = table.Column<int>(type: "int", nullable: false),
DestinataryId = table.Column<int>(type: "int", nullable: false),
Expiration = table.Column<DateTime>(type: "datetime2", nullable: false),
GeneratorProposals = table.Column<string>(type: "nvarchar(max)", nullable: true),
NFNumber = table.Column<int>(type: "int", nullable: false),
Operation = table.Column<int>(type: "int", nullable: false),
OperationType = table.Column<int>(type: "int", nullable: false),
Value = table.Column<double>(type: "float", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_NFControls", x => x.Id);
table.ForeignKey(
name: "FK_NFControls_Companies_CompanyId",
column: x => x.CompanyId,
principalTable: "Companies",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_NFControls_People_DestinataryId",
column: x => x.DestinataryId,
principalTable: "People",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_NFControls_CompanyId",
table: "NFControls",
column: "CompanyId");
migrationBuilder.CreateIndex(
name: "IX_NFControls_DestinataryId",
table: "NFControls",
column: "DestinataryId");
migrationBuilder.CreateIndex(
name: "IX_People_CityId",
table: "People",
column: "CityId");
migrationBuilder.AddForeignKey(
name: "FK_Stocks_Products_ProductId",
table: "Stocks",
column: "ProductId",
principalTable: "Products",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
}
}
}
<file_sep>/StockManagerCore/Services/CompanyService.cs
#region --== Dependency declaration ==--
using System.Linq;
using System.Collections.Generic;
using StockManagerCore.Data;
using StockManagerCore.Models;
using StockManagerCore.Services.Exceptions;
using System.Windows;
#endregion
namespace StockManagerCore.Services
{
public class CompanyService
{
#region --== Dependency Injection and constructor ==--
private readonly StockDBContext _context;
public CompanyService(StockDBContext context) { _context = context; }
#endregion
#region --== Methods ==--
//Querry to fetch all Companies Records
public IEnumerable<Company> GetCompanies()
{
return _context.Companies.OrderBy(c => c.Name);
}
//Querry to find a specific company
public Company Find(Company c)
{
Company company = new Company();
if (c == null)
{
throw new RequiredFieldException("Informe uma empresa para localizar");
}
company = _context.Companies
.Where(co => co.Id == c.Id)
.SingleOrDefault();
if (company == null)
{
throw new NotFoundException("Entidade não encontrada");
}
return company;
}
//Querry to find a company by name
public Company FindByName(string name)
{
try
{
Company company = new Company();
if (name == "" || name == null)
{
throw new RequiredFieldException("Campo necessario para busca");
}
company = _context.Companies.Where(c => c.Name == name).SingleOrDefault();
return company;
}
catch (NotFoundException ex)
{
throw new NotFoundException("Empresa Não encontrada" + ex.Message);
}
}
//Querry to Find a specific company by Id to update.
public Company FindToUdate(int id)
{
Company co = new Company();
if (id != 0)
{
co = _context.Companies.Find(id);
if (co == null)
{
throw new NotFoundException("Id :" + id.ToString() + "Não encontrado");
}
return co;
}
throw new NotFoundException("Insuficient Data to find entity!");
}
public IEnumerable<object> GetObjCompanies()
{
var query = from c in _context.Companies
join s in _context.Stocks on c.Id equals s.Company.Id
select new
{
Nome = c.Name,
Codigo = c.Id,
MaxFaturamento = c.MaxRevenues.ToString("C2"),
SaldoFaturavel = c.Balance.ToString("C2")
};
return query.ToList();
}
public double CalculateCompanyBalance(IEnumerable<Stock> list, Company c)
{
double sum = 0.0d;
try
{
foreach (Stock item in list)
{
sum += item.AmountSold;
}
_context.Companies.Update(c);
_context.SaveChanges();
MessageBox.Show("Saldo Atualizado! "+ sum.ToString("C2"),
"Resultado",
MessageBoxButton.OK,
MessageBoxImage.Information);
}
catch (DbComcurrancyException ex)
{
MessageBox.Show("Saldo não atualizado!\n " + ex.Message,
"Erro",
MessageBoxButton.OK,
MessageBoxImage.Error);
throw new DbComcurrancyException(ex.Message);
}
return sum;
}
#region --== CRUD ==--
//Methods to Create New and Update records of companies.
public string Create(string name, double maxR)
{
try
{
Company c = new Company(name, maxR);
_context.Companies.Add(c);
_context.SaveChanges();
var test = _context.Companies.Where(t => t.Name == c.Name).FirstOrDefault();
string response = "Id: " + test.Id.ToString() + " Nome: " + test.Name.ToUpper();
return response;
}
catch (DbComcurrancyException ex)
{
string msg = ex.Message;
if (ex.InnerException != null)
{
msg += "\n" + ex.InnerException;
}
throw new DbComcurrancyException("Não foi possivel atualizar veja mensagem: \n" + msg);
}
}
public string Create(Company c)
{
try
{
_context.Companies.Add(c);
_context.SaveChanges();
}
catch (DbComcurrancyException ex)
{
string msg = ex.Message;
if (ex.InnerException != null)
{
msg += "\n" + ex.InnerException;
}
throw new DbComcurrancyException("Não foi possivel atualizar veja mensagem: \n" + msg);
}
return "Adicionado com sucesso";
}
public string Update(Company co)
{
try
{
if (co == null)
{
throw new DbComcurrancyException("Entity could not be null or empty!");
}
_context.Companies.Update(co);
_context.SaveChanges();
}
catch (DbComcurrancyException ex)
{
string msg = ex.Message;
if (ex.InnerException != null)
{
msg += "\n" + ex.InnerException;
}
throw new DbComcurrancyException("Não foi possivel atualizar veja mensagem: \n" + msg);
}
return "Update realizado com sucesso!";
}
#endregion
#endregion
}
}
<file_sep>/StockManagerCore/App.xaml.cs
#region --== Dependency declaration ==--
using Microsoft.Extensions.DependencyInjection;
using System.Windows;
using Microsoft.EntityFrameworkCore;
using StockManagerCore.Data;
using StockManagerCore.Services;
#endregion
namespace StockManagerCore
{
/// <summary>
/// This aplication is for control stock of purchased and sold products with Nfe invoice.
/// The primary objective of this is to load the data of the Nfe invoices
/// from txt files of the Imported products sended from Import/Export Company
/// and csv file from solds order.
/// After that the system carry on of process all data and calculate que total itens purchased and amount of them.
/// and the total item sold and so the amount of them. Separated by group of product.
/// Them user can see on a grid.
/// The system has a sencond separated function that is to control shipping invoices and return invoices
/// for each seller representative or client that could be necessary use this kind of invoice.
/// its only a log and do not have any control of emmited or returned invoices if not informed.
/// Other functios is to inputs manualy data that don´t have file to load.
/// The system doesn´t have reports for printing pourpose.
/// The system must calculate the total invoices of sales emited and register
/// a balance of the Max renenues less the total sales per company
/// </summary>
public partial class App : Application
{
private readonly ServiceProvider serviceProvider;
public App()
{
/*Application inicialization and injection of dependency of services, DBContext and Seed Data service.
* Any Service is from each kind of Model.
*/
ServiceCollection services = new ServiceCollection();
services.AddDbContext<StockDBContext>(options =>
{
options.UseSqlServer( "server=tcp:=192.168.100.2,1433;Network Library = DBMSSOCN;Initial Catalog=StockKManagerDB;User Id=appuser;Password=<PASSWORD>;" );
});
services.AddScoped<InputService>();
services.AddScoped<SaleService>();
services.AddScoped<CompanyService>();
services.AddScoped<ProductService>();
services.AddScoped<StockService>();
services.AddScoped<SeedDataService>();//Initiates the service in the injection dependecy of application
services.AddSingleton<MainWindow>();
serviceProvider = services.BuildServiceProvider();
}
private void OnStartup(object s, StartupEventArgs e)
{
SeedDataService seedDataService = new SeedDataService(serviceProvider.GetService<StockDBContext>());
var mainWindow = serviceProvider.GetService<MainWindow>();
mainWindow.Show();
seedDataService.Seed();
}
}
}
<file_sep>/StockManagerCore/Models/Company.cs
#region --== Dependency declaration ==--
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
#endregion
namespace StockManagerCore.Models
{
public class Company
{
#region --== Model properties ==--
[Required]
public int Id { get; set; }
[Required]
public string Name { get; set; }
public double MaxRevenues { get; set; }
public double Balance { get; private set; }
public ICollection<InputProduct> InputProducts { get; set; }
public ICollection<SoldProduct> SoldProducts { get; set; }
public ICollection<Stock> Stocks { get; set; }
#endregion
#region --== Constructors ==--
public Company() { }
public Company( string name, double maxRev)
{
Name = name;
MaxRevenues = maxRev;
}
#endregion
#region --== Methods ==--
public void SetBalance(double billed)
{
Balance = MaxRevenues - billed;
}
#endregion
}
}
<file_sep>/StockManagerCore/Models/Entity.cs
namespace StockManagerCore.Models
{
public class Entity : IEntity
{
public int Id { get; set; }
public string Description { get; set; }
public Entity() { }
public Entity( int id, string description )
{
Id = id;
Description = description;
}
}
}
<file_sep>/StockManagerCore/Models/CryptoService/CypherModule.cs
using System;
using System.Security.Cryptography;
using System.Text;
namespace StockManagerCore.Models.CryptoService
{
/// <summary>
/// Module for encript the system password and put them on database.
/// Public methods for encriptation and comparisson.
/// Private methods those who create hash and eventualy compares them
/// </summary>
public static class CypherModule
{
public static string MD5Return( string password ) //Public Metod to return encripted value
{
try
{
using ( MD5 md5Hash = MD5.Create() )
{
return HashReturn( md5Hash, password );
}
}
catch ( CryptographicException ex )
{
string message = ex.Message;
if ( ex.InnerException != null )
{
message += "\n" + ex.InnerException;
}
throw new CryptographicException( message );
}
}
public static bool MD5Compare( string dbPass, string MD5Pass ) //Comparrison result return method
{
try
{
using ( MD5 md5Hash = MD5.Create() )
{
var Password = MD5Return( dbPass );
if ( HashCheck( md5Hash, MD5Pass, Password ) )
{
return true;
}
else
{
return false;
}
}
}
catch ( CryptographicException ex )
{
string message = ex.Message;
if ( ex.InnerException != null )
{
message += "\n" + ex.InnerException;
}
throw new CryptographicException( message );
}
}
private static string HashReturn( MD5 md5Hash, string input ) //Private encriptor method
{
StringBuilder sb = new StringBuilder();
try
{
byte[] inputData = md5Hash.ComputeHash( Encoding.UTF8.GetBytes( input ) );
for ( int i = 0; i < inputData.Length; i++ )
{
sb.Append( inputData[i].ToString( "x2" ) );
}
}
catch ( CryptographicException ex )
{
string message = ex.Message;
if ( ex.InnerException != null )
{
message += "\n" + ex.InnerException;
}
throw new CryptographicException( message );
}
return sb.ToString();
}
private static bool HashCheck( MD5 md5Hash, string input, string hash ) //Comparrison method
{
try
{
StringComparer scComparisson = StringComparer.OrdinalIgnoreCase;
if ( 0 == scComparisson.Compare( input, hash ) )
{
return true;
}
else
{
return false;
}
}
catch ( CryptographicException ex )
{
string message = ex.Message;
if ( ex.InnerException != null )
{
message += "\n" + ex.InnerException;
}
throw new CryptographicException( message );
}
}
}
}
<file_sep>/StockManagerCore/Services/Exceptions/MyApplicationException.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace StockManagerCore.Services.Exceptions
{
//Custom Exception Handler
class MyApplicationException : ApplicationException { public MyApplicationException(string message) : base(message) { } }
}
|
0d821d10f201545e62189837b0630f1656caf073
|
[
"C#"
] | 37
|
C#
|
almoretto/GerenciadorEstoqueFiscal
|
bb869a32f7e8a7b3e7e2348831f1ef310cf7d62a
|
e6e19298d734ad5e7e839ce7f5c035122fd842a6
|
refs/heads/master
|
<repo_name>noname-username/kluch<file_sep>/dist/js/main.js
//анимированная прокрутка страницы
function scrollToAnchor(aid){
let aTag = $('#' + aid);
$('html,body').animate({scrollTop: aTag.offset().top},'ease');
}
$(function () {
//якоря
$('[data-anchor]').click(function () {
let aid = $(this).attr('data-anchor');
if ($('.toggleMenu').hasClass('active')) {
$('.toggleMenu').toggleClass('active');
$('.header__menu').toggleClass('active');
$('body').toggleClass('noScroll');
setTimeout(scrollToAnchor, 500, aid);
}
else {
scrollToAnchor(aid);
}
});
//тогл меню
$('.toggleMenu').click(function () {
$(this).toggleClass('active');
$('.header__menu').toggleClass('active');
$('body').toggleClass('noScroll');
});
$('#infographicsSection').waypoint(function (direction) {
$('#infographicsSection').addClass('active')
});
//слайдер видео на главной
$('#sliderSection .casesSlider').slick({
slidesToShow: 1,
slidesToScroll: 1,
arrows: true,
autoplay: false,
prevArrow: '<div class="casesSlider__arrow casesSlider__arrow_prev"></div>',
nextArrow: '<div class="casesSlider__arrow casesSlider__arrow_next"></div>'
});
//маски на инпуты телефонов
//$('input[name="phone"]').inputmask('+7999999-999-999');
$('[data-popup]').click(function () {
$('.popupBox').addClass('active');
$('.popup').removeClass('active');
$('.' + $(this).data('popup')).addClass('active');
});
//попап
$('.popupBtn, .popup > .close, .overlay').click(function () {
$('.popupBox').toggleClass('active');
$('.fixedHeader').toggleClass('active');
$('[data-wrap-form]').removeClass('hidden');
$('[data-wrap-sent]').addClass('hidden');
});
$('.popup form').submit(function (e) {
e.preventDefault();
let popup = $(this).data('form-popup');
$('[data-wrap-form="' + popup + '"]').toggleClass('hidden');
$('[data-wrap-sent="' + popup + '"]').toggleClass('hidden');
});
//синхронизация виджета навигации со слайдером
$('.answerSlider .answerSlider__videoSlider').on('afterChange', function (e, slick, currentSlide) {
$('.answerSlider .answerSlider__navSlider .navSlider__item').removeClass('navSlider__item_active');
$('.answerSlider .answerSlider__navSlider .navSlider__item[data-slide-num=' + currentSlide + ']').addClass('navSlider__item_active');
});
//навигация слайдера видео на главной
$('.answerSlider .answerSlider__navSlider .navSlider__item').click(function (e) {
$('.answerSlider .answerSlider__videoSlider').slick('slickGoTo', $(this).attr('data-slide-num'));
});
})
|
90231ae54adea556c682168de354904fa265c561
|
[
"JavaScript"
] | 1
|
JavaScript
|
noname-username/kluch
|
7c4701b5ff977bc9e8785b8bfd574dcab68ec9e5
|
ff6b2f42c7e1c2620ec98d350a0cb2c8bb7be6b2
|
refs/heads/master
|
<repo_name>BnayaZil/favoriteProject<file_sep>/src/app/shared/services/data/data.srv.js
/**
* User service
*/
class Data {
constructor($http, localStorageService, $rootScope) {
'ngInject';
this.$http = $http;
this.$rootScope = $rootScope;
this.localStorageService = localStorageService;
const limit = 50;
const wikiReq = `https://en.wikipedia.org/w/api.php?action=query&origin=*&list=random&format=json&rnnamespace=0&rnlimit=${limit}`;
this.init(wikiReq);
this.favorites = [];
}
/**
* init
* initiating the Service - update user's account balance before doing any action
* @param user - user details object
*/
init(wiki) {
this.asyncData = this.$http.get(wiki).then(res => res.data.query.random).then((res) => {
this.syncData = res.map((val) => ({id: val.id, title: val.title, description: val.description}));
return this.syncData;
});
}
getFavorites() {
const localStorageFavorites = this.localStorageService.get('favorites');
if(_.isEmpty(this.favorites)) {
if(!_.isNull(localStorageFavorites))
this.favorites = localStorageFavorites;
}
return this.favorites;
}
addFavorite(item){
this.favorites.push(item);
this.$rootScope.$broadcast('favoritesUpdated');
this.localStorageService.set('favorites', this.favorites);
}
updateFavorite(item, index){
this.favorites[index] = item;
this.$rootScope.$broadcast('favoritesUpdated');
this.localStorageService.set('favorites', this.favorites);
}
removeFavorite(item, index) {
this.favorites.splice(index, 1);
this.localStorageService.set('favorites', this.favorites);
this.$rootScope.$broadcast('favoritesUpdated');
}
}
const dataModule = angular.module(`app.shared.data`, [])
.service(`dataService`, Data);
export default dataModule;
<file_sep>/src/app/components/header/header.drv.js
/*
Created by bnaya on 23/10/16,
@Component Name: header.drv
@Description:
@Params:
@Return:
@Methods:
*/
import './header.less';
class headerController {
constructor() {
this.tabs = [
{
title: 'Favorites',
state: 'favorites'
},
{
title: 'Options',
state: 'options'
}
]
}
}
const template = require('./header.tpl.html');
const headerConfig = {
restrict: 'E',
bindings: {},
template,
controller: headerController,
controllerAs: 'vm'
};
export default angular.module('app.header', [])
.component('header', headerConfig);<file_sep>/src/app/shared/shared.js
import data from './services/data/data.srv';
const sharedModule = angular.module('app.shared', [
data.name
]);
export default sharedModule;<file_sep>/src/app/components/options-list/options-list.drv.js
/*
Created by bnaya on 23/10/16,
@Component Name: optinos-list.drv
@Description:
@Params:
@Return:
@Methods:
*/
import './options-list.less';
class optionsController {
constructor(dataService) {
'ngInject';
this.dataService = dataService;
}
checking(item, index) {
if(item.checked)
this.dataService.addFavorite(item);
else
this.dataService.removeFavorite(item);
}
}
const template = require('./options-list.tpl.html');
const optionsListConfig = {
restrict: 'E',
bindings: {
data: '='
},
template,
controller: optionsController,
controllerAs: 'vm'
};
export default angular.module('app.components.optionsList', [])
.component('optionsList', optionsListConfig);<file_sep>/README.md
# Favorite Test
# Getting started
## Dependencies
To run the app you will need globally install of `webpack` and `gulp`:
`npm i -g webpack gulp`
## Install
* `fork` this repository.
* `clone` your fork repository.
* `npm i -g gulp webpack` install global cli [Dependencies](#dependencies).
* `npm i` to install all project dependencies.
## Commands
### NPM
Here list of npm commands:
* `npm start` will serve the app on port 8080.
* `npm webpack` will bundle the app to dist folder.
### GULP
Here list of gulp commands:
* `gulp serve` will serve the app on port 8080.
* `gulp bundle` will bundle the app to dist folder.<file_sep>/src/app/app.config.js
const config = angular.module('app.config', [])
.config(['$compileProvider', '$stateProvider', '$urlRouterProvider', '$locationProvider', 'localStorageServiceProvider', '$provide', 'AnalyticsProvider', ($compileProvider, $stateProvider, $urlRouterProvider, $locationProvider, localStorageServiceProvider, $provide, AnalyticsProvider) => {
// Enabled debug info classes as "ng-scope".
$compileProvider.debugInfoEnabled(false);
// adding property 'next' to $state object for changing states dynamically by their name
$provide.decorator('$state', function ($delegate, $rootScope) {
$rootScope.$on('$stateChangeStart', function (event, state, params) {
$delegate.next = state;
$delegate.toParams = params;
});
return $delegate;
});
localStorageServiceProvider.setPrefix('favorite');
// if url does not match any of the states, go to homepage
$urlRouterProvider.otherwise('options');
// Set html5mode only for not localhost servers.
if (window.location.host !== 'localhost:8080' && window.history && history.pushState)
$locationProvider.html5Mode(true);
$stateProvider
.state('options', {
url: "/options",
template: `<md-content><options-list data="vm.optionsData"></options-list></md-content>`,
controller: function(optionsData) {
this.optionsData = optionsData;
},
resolve: {
optionsData: (dataService) => dataService.asyncData
},
controllerAs: "vm"
})
.state('favorites', {
url: "/favorites",
template: `<md-content><favorites-list data="vm.favoritesData"></favorites-list></md-content>`,
controller: function(favoritesData) {
this.favoritesData = favoritesData;
},
resolve: {
favoritesData: (dataService) => dataService.getFavorites()
},
controllerAs: "vm"
})
}]);
export default config;
|
94cb34592bd43129e364323992416bb2f981c573
|
[
"JavaScript",
"Markdown"
] | 6
|
JavaScript
|
BnayaZil/favoriteProject
|
6222840206a58c85424c400037e8b00b3c9d3d7a
|
8910e1a12243ea2046ffb047cef44ae9b3931825
|
refs/heads/master
|
<file_sep>#encoding: utf-8
import pyautogui
import time
import os
from fpdf import FPDF
import img2pdf
def main():
time.sleep(10)
page_count = 4046
for i in range(page_count):
region = (700, 0, 450, 950)
pyautogui.screenshot('screenshots\%d.png' % i, region = region)
pyautogui.press('right')
time.sleep(0.1)
# both image to pdf coversion methods are SLOW, use Photoshop to better do it
def pages_to_pdf(folder = 'screenshots'):
pdf = FPDF()
for i in range(6, 611):
pdf.add_page()
image_path = '%s\%d.png' % (folder, i)
pdf.image(image_path)
pdf.output('output.pdf')
def raw_pages_to_pdf(folder = 'screenshots'):
page_list = ['%s\%d.png' % (folder, i) for i in range(6, 611)]
with open('output.pdf', 'wb') as f:
f.write(img2pdf.convert(page_list))
if __name__ == '__main__':
main()
# pages_to_pdf()<file_sep># kindle-to-pdf
convert a kindle Ebook to PDF by taking screenshots and combining them into a PDF
|
7cb6de03aa891d4fc70dd3c954a6640fafc0f6a5
|
[
"Markdown",
"Python"
] | 2
|
Python
|
jeffli678/kindle-to-pdf
|
59fdb3410d44b9db075a420fbcce9528e21d1ed0
|
303ed2db22d45a8280092cd3e499c9673034ef30
|
refs/heads/master
|
<file_sep>import io from "socket.io-client";
import { flow } from "lodash";
const SIGNALING_SERVER_IP = `${window.location.protocol}//${window.location.hostname}:${window.location.port}`;
let socket = null;
function connectToSocket(namespace = "") {
if (!socket) {
socket = io(`${SIGNALING_SERVER_IP}/${namespace}`);
}
return socket;
}
function bindToSocket(socket, { onReady, onArrival, onReceived }) {
const bindEventToSocket = flow(
socket => _bindOnReceiverArrivalEvent(socket, onArrival),
socket => _bindSignalFromSocketReceivedEvent(socket, onReceived),
() => onReady()
);
socket.on("connect", () => {
bindEventToSocket(socket);
});
return socket;
}
function _bindOnReceiverArrivalEvent(socket, onArrival) {
socket.on("receiver-arrival", onArrival);
return socket;
}
function _bindSignalFromSocketReceivedEvent(socket, onReceived) {
socket.on("handshake", onReceived);
return socket;
}
function joinRoom(socket, roomId) {
socket.emit("join", roomId);
return socket;
}
function broadcastOfferToSocket(socket, signal, roomId) {
socket.emit("handshake", signal, roomId);
return socket;
}
export { connectToSocket, bindToSocket, joinRoom, broadcastOfferToSocket };
<file_sep>import React, { Component } from "react";
import { onDataReceive } from "../services/peer/index";
class PeerChat extends Component {
constructor(props) {
super(props);
onDataReceive(this.props.peer, this.onTextReceive);
this.state = {
text: ""
};
}
onTextReceive = text => {
this.setState({ text });
};
onTextChange = e => {
const text = e.target.value;
this.setState({ text });
this.props.peer.send(text);
};
render() {
return (
<textarea
className="textarea"
value={this.state.text}
onChange={this.onTextChange}
/>
);
}
}
export default PeerChat;
<file_sep>import { Component, Children, cloneElement } from "react";
import { connectToSocket } from "../services/signaling";
class SocketProvider extends Component {
constructor(props) {
super(props);
this.socket = connectToSocket();
}
render() {
const child = Children.only(this.props.children);
const propsWithSocket = {
...this.props,
socket: this.socket
};
return cloneElement(child, propsWithSocket, child.props.children);
}
}
export default SocketProvider;
<file_sep>import React, { Component } from "react";
import { initialize, offerToHash, hashToOffer } from "../services/peer";
import {
bindToSocket,
joinRoom,
broadcastOfferToSocket
} from "../services/signaling";
import PeerChat from "../components/PeerChat";
import SocketProvider from "../components/SocketProvider";
class Receiver extends Component {
constructor(props) {
super(props);
this.roomId = props.match.params.roomId;
this.peer = initialize(false, this.onPeerOffer, this.onPeerConnected);
bindToSocket(props.socket, {
onReady: this.onSocketReady,
onReceived: this.onOfferAnswerReceivedFromSocket
});
this.state = {
connected: false
};
}
onPeerOffer = offer => {
broadcastOfferToSocket(this.props.socket, offerToHash(offer), this.roomId);
};
onPeerConnected = () => {
this.setState({ connected: true });
alert("You are now connected");
};
onSocketReady = () => {
joinRoom(this.props.socket, this.roomId);
};
onOfferAnswerReceivedFromSocket = answer => {
console.log(answer);
this.peer.signal(hashToOffer(answer));
};
render() {
if (this.state.connected) {
return <PeerChat peer={this.peer} />;
}
return (
<SocketProvider>
<div className="notification">
<div>Connecting to your partner...</div>
</div>
</SocketProvider>
);
}
}
export default Receiver;
<file_sep>import React, { Component } from "react";
import { BrowserRouter as Router, Route } from "react-router-dom";
import Emitter from "./containers/Emitter";
import Receiver from "./containers/Receiver";
import SocketProvider from "./components/SocketProvider";
class App extends Component {
render() {
return (
<Router>
<div>
<nav className="navbar is-link">
<div className="navbar-brand">
<h1 className="title navbar-item">WebRTC-playground</h1>
</div>
</nav>
<div className="section">
<div className="container">
<Route
exact
path="/"
render={props => (
<SocketProvider {...props}>
<Emitter />
</SocketProvider>
)}
/>
<Route
exact
path="/r/:roomId"
render={props => (
<SocketProvider {...props}>
<Receiver />
</SocketProvider>
)}
/>
</div>
</div>
</div>
</Router>
);
}
}
export default App;
<file_sep>import Peer from "simple-peer";
import { flow } from "lodash";
function initialize(initiator, onSignal, onConnected) {
const createdPeer = new Peer({
initiator,
trickle: true,
config: {
iceServers: [
{
urls: "stun:numb.viagenie.ca"
}
]
}
});
const bindEventToPeer = flow(
peer => _bindConnectEvent(peer, onConnected),
peer => _bindSignalEvent(peer, onSignal)
);
return bindEventToPeer(createdPeer);
}
function _bindSignalEvent(peer, onSignal) {
peer.on("signal", onSignal);
return peer;
}
function _bindConnectEvent(peer, onConnected) {
const defaultConnectedHandler = () => console.log("connected");
peer.on("connect", onConnected || defaultConnectedHandler);
return peer;
}
function onDataReceive(peer, onData) {
peer.on("data", onData);
return peer;
}
function offerToHash(offer) {
return flow(JSON.stringify, btoa)(offer);
}
function hashToOffer(hash) {
return flow(atob, JSON.parse)(hash);
}
export { initialize, offerToHash, hashToOffer, onDataReceive };
|
e9a47fc3d2c655493f0554d227c1cd7b6c27d91a
|
[
"JavaScript"
] | 6
|
JavaScript
|
g3offrey/rtc-playground
|
a55ea0716a86b6187c6c80ba4429294dbb940bd8
|
ccf7f9f79d2b5b196d49f1deda8d2147e2869e97
|
refs/heads/main
|
<repo_name>kapustaxvx/bank_cinema<file_sep>/src/main/java/com/moskalenko/bankcinema/api/client/UserClient.java
package com.moskalenko.bankcinema.api.client;
import com.moskalenko.bankcinema.api.DTO.UserDTO;
import com.moskalenko.bankcinema.api.entity.Movie;
import com.moskalenko.bankcinema.api.entity.User;
import java.util.Collection;
public interface UserClient {
User addUser(UserDTO userData);
User getUserById(Long userId);
Collection<User> getAllUsers();
String addToUserMoviesList(Long userId, Long movieId);
String deleteFromUserMoviesList(Long userId, Long movieId);
String rateTheMovie(Long userId, Long movieId, Integer rate);
String updateMovieViewInfo(Long userId, Long movieId);
Collection<Movie> getAllMoviesFromUserMoviesList(Long userId);
Collection<Movie> getAllUnseenMoviesFromUserMoviesList(Long userId);
}
<file_sep>/src/main/java/com/moskalenko/bankcinema/api/entity/UserMovies.java
package com.moskalenko.bankcinema.api.entity;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.MapsId;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
@Entity
@Table(name = "user_movies",
uniqueConstraints = {@UniqueConstraint(columnNames = {"user_id","movie_id"})}
)
public class UserMovies {
@EmbeddedId
private UserMoviesKey userMoviesKey;
@ManyToOne
@MapsId("userId")
@JoinColumn(name = "user_id")
private User user;
@ManyToOne
@MapsId("movieId")
@JoinColumn(name = "movie_id")
private Movie movie;
@Column(name = "wathed")
private Boolean isWatched = false;
@Column(name = "rate", columnDefinition = "INT CHECK (rate>=0 AND rate<=10)")
private Integer rate;
public UserMovies() {
}
public UserMovies(User user, Movie movie) {
this.user = user;
this.movie = movie;
this.userMoviesKey = new UserMoviesKey(user.getId(), movie.getId());
}
public UserMoviesKey getUserMoviesKey() {
return userMoviesKey;
}
public void setUserMoviesKey(UserMoviesKey userMoviesKey) {
this.userMoviesKey = userMoviesKey;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Movie getMovie() {
return movie;
}
public void setMovie(Movie movie) {
this.movie = movie;
}
public Boolean getWatched() {
return isWatched;
}
public void setWatched(Boolean watched) {
isWatched = watched;
}
public Integer getRate() {
return rate;
}
public void setRate(Integer rate) {
this.rate = rate;
}
@Override
public String toString() {
return "UserMovies{" +
"userMoviesKey=" + userMoviesKey +
", user=" + user +
", movie=" + movie +
", isWatched=" + isWatched +
", rate=" + rate +
'}';
}
}<file_sep>/src/main/java/com/moskalenko/bankcinema/kafka/ProducerService.java
package com.moskalenko.bankcinema.kafka;
import com.moskalenko.bankcinema.api.DTO.ActorDTO;
import com.moskalenko.bankcinema.api.DTO.DirectorDTO;
import com.moskalenko.bankcinema.api.DTO.MovieDTO;
import com.moskalenko.bankcinema.api.DTO.UserDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
@Service
public class ProducerService {
private static final Logger log = LoggerFactory.getLogger(ProducerService.class);
private final KafkaTemplate<String, UserDTO> userDTOKafkaTemplate;
private final KafkaTemplate<String, ActorDTO> actorDTOKafkaTemplate;
private final KafkaTemplate<String, DirectorDTO> directorDTOKafkaTemplate;
private final KafkaTemplate<String, MovieDTO> movieDTOKafkaTemplate;
public ProducerService(KafkaTemplate<String, UserDTO> userDTOKafkaTemplate,
KafkaTemplate<String, ActorDTO> actorDTOKafkaTemplate,
KafkaTemplate<String, DirectorDTO> directorDTOKafkaTemplate,
KafkaTemplate<String, MovieDTO> movieDTOKafkaTemplate) {
this.userDTOKafkaTemplate = userDTOKafkaTemplate;
this.actorDTOKafkaTemplate = actorDTOKafkaTemplate;
this.directorDTOKafkaTemplate = directorDTOKafkaTemplate;
this.movieDTOKafkaTemplate = movieDTOKafkaTemplate;
}
public void produce(UserDTO user) {
log.info("Producing the user " + user);
userDTOKafkaTemplate.send("users", user);
}
public void produce(ActorDTO actor) {
log.info("Producing the actor " + actor);
actorDTOKafkaTemplate.send("actors", actor);
}
public void produce(DirectorDTO director) {
log.info("Producing the director " + director);
directorDTOKafkaTemplate.send("directors", director);
}
public void produce(MovieDTO movie) {
log.info("Producing the movie " + movie);
movieDTOKafkaTemplate.send("movies", movie);
}
}
<file_sep>/src/main/java/com/moskalenko/bankcinema/api/entity/UserMoviesKey.java
package com.moskalenko.bankcinema.api.entity;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import java.io.Serializable;
import java.util.Objects;
@Embeddable
public class UserMoviesKey implements Serializable {
@Column(name = "user_id")
private Long userId;
@Column(name = "movie_id")
private Long movieId;
public UserMoviesKey() {
}
public UserMoviesKey(Long userId, Long movieId) {
this.userId = userId;
this.movieId = movieId;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public Long getMovieId() {
return movieId;
}
public void setMovieId(Long movieId) {
this.movieId = movieId;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
UserMoviesKey that = (UserMoviesKey) o;
return Objects.equals(userId, that.userId) && Objects.equals(movieId, that.movieId);
}
@Override
public int hashCode() {
return Objects.hash(userId, movieId);
}
}<file_sep>/src/main/java/com/moskalenko/bankcinema/api/DTO/MovieDTO.java
package com.moskalenko.bankcinema.api.DTO;
import com.moskalenko.bankcinema.api.entity.Genre;
import com.moskalenko.bankcinema.api.entity.Movie;
public class MovieDTO {
private Long id;
private String title;
private String description;
private Genre genre;
private Double rating;
private Integer fees;
private Long directorId;
public MovieDTO() {
}
public MovieDTO(Long id, String title, String description, Genre genre, Double rating, Integer fees, Long directorId) {
this.id = id;
this.title = title;
this.description = description;
this.genre = genre;
this.rating = rating;
this.fees = fees;
this.directorId = directorId;
}
public MovieDTO(Movie movie) {
this.id = movie.getId();
this.title = movie.getTitle();
this.description = movie.getDescription();
this.genre = movie.getGenre();
this.rating = movie.getRating();
this.fees = movie.getFees();
this.directorId = movie.getDirector().getId();
}
public String getTitle() {
return title;
}
public Long getId() {
return id;
}
public String getDescription() {
return description;
}
public Genre getGenre() {
return genre;
}
public Double getRating() {
return rating;
}
public Integer getFees() {
return fees;
}
public Long getDirectorId() {
return directorId;
}
}
<file_sep>/src/main/java/com/moskalenko/bankcinema/api/client/MovieClient.java
package com.moskalenko.bankcinema.api.client;
import com.moskalenko.bankcinema.api.DTO.MovieDTO;
import com.moskalenko.bankcinema.api.entity.Movie;
import java.util.Collection;
public interface MovieClient {
Movie addMovie(MovieDTO movieData);
Movie getMovieById(Long movieId);
Collection<Movie> getAllMovies();
}
<file_sep>/src/main/java/com/moskalenko/bankcinema/api/entity/Genre.java
package com.moskalenko.bankcinema.api.entity;
public enum Genre {
DRAMA,
HORROR,
DETECTIVE,
COMEDY,
THRILLER,
FANTASTIC,
FANTASY,
WESTERN
}
<file_sep>/src/main/java/com/moskalenko/bankcinema/dao/MovieDAO.java
package com.moskalenko.bankcinema.dao;
import com.moskalenko.bankcinema.api.entity.Movie;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import java.util.Optional;
@Repository
public interface MovieDAO extends CrudRepository<Movie, Long> {
Optional<Movie> getMovieById(Long id);
}
<file_sep>/src/main/java/com/moskalenko/bankcinema/controller/GlobalDefaultExceptionHandler.java
package com.moskalenko.bankcinema.controller;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@ControllerAdvice("com.moskalenko.bankcinema.controller")
public class GlobalDefaultExceptionHandler {
@ExceptionHandler({Exception.class})
@ResponseBody
public String commonError() {
return "Error";
}
@ExceptionHandler({RuntimeException.class})
public ResponseEntity<String> serviceError(RuntimeException e) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
}
}<file_sep>/src/main/java/com/moskalenko/bankcinema/api/DTO/ActorDTO.java
package com.moskalenko.bankcinema.api.DTO;
import com.moskalenko.bankcinema.api.entity.Actor;
public class ActorDTO {
private Long id;
private String name;
private String surname;
public ActorDTO() {
}
public ActorDTO(Long id, String name, String surname) {
this.id = id;
this.name = name;
this.surname = surname;
}
public ActorDTO(Actor actor){
this.id = actor.getId();
this.name = actor.getName();
this.surname = actor.getSurname();
}
public Long getId() {
return id;
}
public String getName() {
return name;
}
public String getSurname() {
return surname;
}
}
<file_sep>/src/main/java/com/moskalenko/bankcinema/api/DTO/MovieRatingDTO.java
package com.moskalenko.bankcinema.api.DTO;
public class MovieRatingDTO {
private Long movieId;
private Long userId;
private Boolean isWatched;
private Integer rate;
public MovieRatingDTO() {
}
public Long getMovieId() {
return movieId;
}
public Long getUserId() {
return userId;
}
public Boolean getWatched() {
return isWatched;
}
public Integer getRate() {
return rate;
}
}
|
a14c0a50009c0059a1d82cd2cef8bfa04187b9bd
|
[
"Java"
] | 11
|
Java
|
kapustaxvx/bank_cinema
|
05f5e9b5966f7d1a5df2bc339c43c9579fd1cf33
|
a2eb0fcb5f257c306ebe98b3fb56c8d9677a1b69
|
refs/heads/master
|
<repo_name>GregoryError/xml_explorer<file_sep>/table_model.h
#ifndef TABLE_MODEL_H
#define TABLE_MODEL_H
#include <QObject>
#include <QAbstractTableModel>
#include <QMenu>
class TABLE_MODEL : public QAbstractTableModel
{
Q_OBJECT
private:
int m_nRows;
int m_nColumns;
QHash<QModelIndex, QVariant> m_hash;
QStringList objName;
QStringList rowsNames;
public:
//TABLE_MODEL() = default;
TABLE_MODEL(int nRows = 1, int nColumns = 1, QObject* pobj = nullptr)
: QAbstractTableModel(pobj), m_nRows(nRows), m_nColumns(nColumns) {}
void setSize(int rws, int clm) { m_nRows = rws; m_nColumns = clm; }
QVariant data(const QModelIndex& index, int nRole) const;
bool setData(const QModelIndex& index,
const QVariant& value,
int nRole);
int rowCount(const QModelIndex&) const
{
return m_nRows;
}
int columnCount(const QModelIndex&) const
{
return m_nColumns;
}
Qt::ItemFlags flags(const QModelIndex& index) const;
QVariant headerData(int nSection, Qt::Orientation orientation,
int nRole) const;
void setObjName(const QStringList& lst)
{
objName = lst;
}
void setRowsNames(const QStringList& lst)
{
rowsNames = lst;
}
void setValue(const int nRows, const int nColumns, const QVariant& val);
QVariant getCellContent(const int nRows, const int nColumns) const;
int getRowsCount() { return m_nRows; }
bool insertRows(int position, int rows, const QModelIndex &parent = QModelIndex());
bool removeRows(int position, int rows, const QModelIndex &index = QModelIndex());
void addColumt() { ++m_nColumns; }
// ~TABLE_MODEL();
public slots:
void clear();
};
#endif // TABLE_MODEL_H
<file_sep>/filesreader.h
#ifndef FILESREADER_H
#define FILESREADER_H
#include <QObject>
#include <QFileDialog>
#include <QString>
#include "xmlreader.h"
#include "filesproxy.h"
#include <QThread>
class FilesReader : public QObject
{
Q_OBJECT
private:
QFileDialog* dialog;
QStringList fileList;
xml_reader* xml_worker;
QThread worker_thread;
FilesProxy px_obj;
public:
explicit FilesReader(QObject *parent = nullptr);
void openOneFile(const QString& nm);
~FilesReader();
public slots:
void makeProxyObject();
FilesProxy getData();
void showDialog();
int getUnitsRead() const { return xml_worker->getLinesCount(); }
void addToProxyObj(const COMMUTATOR rslt);
signals:
void selectionDone();
void objectDone();
void newProgress(int);
void letsDo(const QString nm);
void clearWorker();
void setFilesNumber(const int);
};
#endif // FILESREADER_H
<file_sep>/mainwnd.cpp
#include "mainwnd.h"
#include <QDebug>
mainwnd::mainwnd(QObject *parent) : QObject(parent)
{
mainwgt = new QWidget;
table = new QTableView;
reader = new FilesReader;
import_Btn = new QPushButton;
clear_Btn = new QPushButton;
progressWnd = new QProgressDialog; // ("Импорт файлов...", "Закрыть", 0, 100);
lyt = new QVBoxLayout(progressWnd);
txt_edit = new QTextEdit;
lyt->addWidget(txt_edit);
progressWnd->close();
progressWnd->setLabelText("Импорт файлов...");
progressWnd->setCancelButtonText("Закрыть");
progressWnd->setMaximum(100);
progressWnd->setMinimum(1);
progressWnd->setAutoClose(false);
progressWnd->setAutoReset(false);
progressWnd->setFixedSize(mainwgt->width() * 0.8, mainwgt->width() / 2);
txt_edit->setFontPointSize(10);
txt_edit->setMaximumSize(progressWnd->width() - 30, progressWnd->height() / 2);
import_Btn->setText("ИМПОРТ");
import_Btn->setMinimumHeight(40);
clear_Btn->setIcon(QIcon(":/TrashBin.png"));
clear_Btn->setMinimumHeight(40);
connect(import_Btn, SIGNAL(clicked()), reader, SLOT(showDialog()));
connect(reader, SIGNAL(selectionDone()), this, SLOT(showProgress()));
connect(reader, SIGNAL(objectDone()), this, SLOT(addProgressInfo()));
connect(reader, SIGNAL(objectDone()), this, SLOT(setTableModel()));
connect(clear_Btn, SIGNAL(clicked()), this, SLOT(clearTable()));
connect(reader, SIGNAL(newProgress(int)), progressWnd, SLOT(setValue(int)));
table->setContextMenuPolicy(Qt::CustomContextMenu);
menu = new QMenu();
connect(table, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(customMenuRequested(QPoint)));
connect(menu, SIGNAL(triggered(QAction*)), this, SLOT(slotActivated(QAction*)));
menu->addAction(new QAction("Добавить", this));
menu->addAction(new QAction("Удалить", this));
menu->addAction(new QAction("Копировать", this));
menu->addAction(new QAction("Изменить здесь", this));
menu->addAction(new QAction("Очистить здесь", this));
menu->addAction(new QAction("Очистить все", this));
menu->addAction(new QAction("Выделить все", this));
menu->addAction(new QAction("Экспортировать все", this));
menu->setEnabled(false);
// Lyout setup
mainwgt->setMinimumSize(640, 480);
QHBoxLayout* phbxLayout = new QHBoxLayout;
phbxLayout->addWidget(clear_Btn);
phbxLayout->addSpacing(table->width() / 3);
phbxLayout->addWidget(import_Btn);
QVBoxLayout* pvbxLayout = new QVBoxLayout;
pvbxLayout->addLayout(phbxLayout);
pvbxLayout->addWidget(table);
mainwgt->setLayout(pvbxLayout);
mainwgt->show();
defaultFileSlot();
}
void mainwnd::setTableModel()
{
//ShowProgressBar();
p_tModel = new TABLE_MODEL();
objForModel = reader->getData();
p_tModel->setSize(objForModel.getSize(), 2); // size should`t be more than >setObjName(....
p_tModel->setObjName(QStringList() << "Имя:" << "Значение:");
QStringList rowsNums;
int rows;
for (rows = 0; rows < objForModel.getSize(); ++rows)
rowsNums << QString::number(rows + 1);
p_tModel->setRowsNames(rowsNums);
rows = 0;
for (QString& name : objForModel.getNamesLst())
{
for (const QString &str : objForModel.getFilePairs(name).first)
{
p_tModel->setValue(rows++, 0, str);
}
}
rows = 0;
for (QString& name : objForModel.getNamesLst())
{
for (const QString &str : objForModel.getFilePairs(name).second)
{
p_tModel->setValue(rows++, 1, str);
}
}
table->setModel(p_tModel);
table->setColumnWidth(0, mainwgt->width() / 2 - 45);
table->setColumnWidth(1, mainwgt->width() / 2 - 45);
menu->setEnabled(true);
setTable = true;
}
void mainwnd::clearTable()
{
delete p_tModel;
}
void mainwnd::addProgressInfo()
{
int count = 1;
QString err_str("Файлы:\n\n");
for (const QString& e : reader->getData().getNamesLst())
{
err_str += QString::number(count++) + ". " + e + ": \n";
err_str += ( reader->getData().getErrorMap()
.value(e).isEmpty() ? "Успешно!"
: reader->getData().getErrorMap().value(e) ) + "\n\n";
}
txt_edit->setPlainText(err_str);
}
void mainwnd::showProgress()
{
progressWnd->show();
}
void mainwnd::customMenuRequested(const QPoint &p)
{
if (table->indexAt(p).isValid())
{
currentIndex = table->indexAt(p);
menu->popup(table->viewport()->mapToGlobal(p));
menuStr = p_tModel->data(currentIndex, Qt::EditRole).toString();
}
}
void mainwnd::slotActivated(QAction *action)
{
// TODO here
if (action->text() == "Добавить")
p_tModel->insertRows(p_tModel->getRowsCount(), 1);
if (action->text() == "Удалить")
p_tModel->removeRows(p_tModel->getRowsCount() - 1, 1);
if (action->text() == "Копировать")
copyToClipboard(menuStr);
if (action->text() == "Изменить здесь")
table->edit(currentIndex);
if (action->text() == "Очистить здесь")
p_tModel->setData(currentIndex, "", Qt::EditRole);
if (action->text() == "Очистить все")
p_tModel->clear();
if (action->text() == "Выделить все")
table->selectAll();
if (action->text() == "Экспортировать все")
startExport();
qDebug() << action->text();
}
void mainwnd::copyToClipboard(const QString &str)
{
buf->setText(str, QClipboard::Clipboard);
}
void mainwnd::startExport()
{
if (QMessageBox::warning(nullptr,
("Экспорт записей"),
("Вы уверены, что хотите экспортировать все записи?\n"
"Файлы будут перезаписаны!"),
QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes)
{
recordData();
}
}
void mainwnd::recordData()
{
QStringList f_names = objForModel.getNamesLst();
QStringList column_0, column_1;
for (int i = 0; i < p_tModel->getRowsCount(); ++i)
{
column_0.append(p_tModel->getCellContent(i, 0).toString());
column_1.append(p_tModel->getCellContent(i, 1).toString());
}
QMessageBox msgBox;
msgBox.setText(xmlWriter.writeToFile(f_names, column_0, column_1));
msgBox.exec();
}
void mainwnd::defaultFileSlot()
{
xmlWriter.writeToFile(QStringList() << "default.xml", QStringList()
<< "tag", QStringList() << "data");
reader->openOneFile("default.xml");
}
<file_sep>/filesreader.cpp
#include "filesreader.h"
FilesReader::FilesReader(QObject *parent) : QObject(parent)
{
dialog = new QFileDialog;
qRegisterMetaType<COMMUTATOR>("COMMUTATOR");
xml_worker = new xml_reader;
connect(this, SIGNAL(selectionDone()), this, SLOT(makeProxyObject()));
connect(this, SIGNAL(letsDo(QString)), xml_worker, SLOT(doWork(QString)));
connect(this, SIGNAL(clearWorker()), xml_worker, SLOT(clear()));
connect(this, SIGNAL(setFilesNumber(int)), xml_worker, SLOT(setFilesCountSlot(int)));
connect(xml_worker, SIGNAL(resultReady(COMMUTATOR)), this, SLOT(addToProxyObj(COMMUTATOR)));
connect(&worker_thread, &QThread::finished, xml_worker, &QObject::deleteLater);
connect(xml_worker, SIGNAL(updateBar(int)), this, SIGNAL(newProgress(int)));
xml_worker->moveToThread(&worker_thread);
worker_thread.start();
}
FilesProxy FilesReader::getData()
{
return px_obj;
}
void FilesReader::showDialog()
{
fileList = dialog->getOpenFileNames(
nullptr,
"Select one or more files to open",
"/home",
"XML-files (*.xml)");
emit selectionDone();
}
void FilesReader::addToProxyObj(const COMMUTATOR rslt)
{
static int perc = 0;
px_obj.addName(rslt.f_nm);
px_obj.addValue(rslt.f_nm, rslt.getFileStrings());
px_obj.addError(rslt.f_nm, rslt.getErrors());
px_obj.addLinesCount(rslt.getLinesCount());
if (perc == fileList.size() || *(fileList.begin()) == "default.xml")
{
perc = 0;
emit objectDone();
}
++perc;
}
void FilesReader::makeProxyObject()
{
px_obj.clear();
emit setFilesNumber(fileList.size()); // setting data for xml_worker for ProgressBar calc
for (QString f_name : fileList)
{
emit letsDo(f_name);
emit clearWorker();
}
}
void FilesReader::openOneFile(const QString &nm)
{
fileList.append(nm);
makeProxyObject();
}
FilesReader::~FilesReader()
{
worker_thread.quit();
worker_thread.wait();
}
<file_sep>/main.cpp
#include <QApplication>
#include "mainwnd.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QDir::setCurrent(qApp->applicationDirPath());
mainwnd wnd;
return a.exec();
}
<file_sep>/xmlreader.h
#ifndef XMLREADER_H
#define XMLREADER_H
#include <QFile>
#include <QXmlStreamReader>
#include <QMap>
#include <QString>
#include <QObject>
#include "filesproxy.h"
Q_DECLARE_METATYPE(COMMUTATOR)
typedef QPair<QStringList, QStringList> MAP_lsts;
class xml_reader : public QObject
{
Q_OBJECT
private:
QFile f_in;
QXmlStreamReader xml;
MAP_lsts fileLsts;
QString errors;
int linesCount = 0;
int filesCount = 0;
double scale;
int calls = 0;
QString f_nm;
COMMUTATOR objToSend;
public:
// xml_reader() = default;
xml_reader(const QString& f_name = "", QObject* parent = nullptr);
MAP_lsts getFileStrings() const;
QString getErrors() const;
int getLinesCount() const;
void resetObj();
QString getFNm() { return f_nm; }
void setName(const QString& nm) { f_nm = nm; }
public slots:
void doWork(const QString nm);
void clear();
void setFilesCountSlot(const int cnt);
signals:
void resultReady(const COMMUTATOR result);
void updateBar(const int);
};
#endif // XMLREADER_H
<file_sep>/filesproxy.h
#ifndef FILESPROXY_H
#define FILESPROXY_H
// structure for store/transfer sets of data to model
#include <QMap>
#include <QString>
#include <QStringList>
typedef QMap<QString, QString> MAP_s_s_;
typedef QPair<QStringList, QStringList> MAP_lsts;
class FilesProxy
{
private:
int quantity = 0; // data strings counter
int size;
QStringList names; // file names
QMap<QString, MAP_lsts> files_maps; // stores maps of values by file name as a key
MAP_s_s_ errors_map; // stores errors in files by file name as a key
bool has_err = false;
public:
FilesProxy() = default;
FilesProxy(const int q, const QStringList &nm_lst,
const QMap<QString, MAP_lsts>& f_maps,
const MAP_s_s_& e_map);
void addLinesCount(int lines);
void addName(const QString& f_name);
void addValue(const QString& f_name, const MAP_lsts& f_lsts);
void addError(const QString& f_name, const QString& err_str);
bool hasErrors() const;
void setErr();
int obj_count() { return quantity; }
QStringList getNamesLst() const;
MAP_lsts getFilePairs(const QString& name) const;
MAP_s_s_ getErrorMap() const;
int getSize() const;
void clear();
};
class COMMUTATOR
{
public:
MAP_lsts fileLsts;
QString errors;
int linesCount = 0;
QString f_nm;
COMMUTATOR() = default;
MAP_lsts getFileStrings() const { return fileLsts; }
QString getErrors() const { return errors; }
int getLinesCount() const { return linesCount; }
QString getFNm() { return f_nm; }
};
#endif // FILESPROXY_H
<file_sep>/xmlwriter.cpp
#include "xmlwriter.h"
#include <QDebug>
#include <QMessageBox>
xml_writer::xml_writer(QObject *parent) : QObject(parent)
{
}
QString xml_writer::writeToFile(const QStringList &names, const QStringList &col_0, const QStringList &col_1)
{
qDebug() << "FileList: " << names;
int i = 0;
int n_count = 1;
for (const QString& nm : names)
{
f_out.setFileName(nm);
if (!f_out.open(QIODevice::WriteOnly/* | QFile::Text*/))
{
QMessageBox msgBox;
msgBox.setText("Произошла ошибка при открытии файла.\n"
+ f_out.errorString());
msgBox.exec();
}
xml.setDevice(&f_out);
xml.setAutoFormatting(true);
xml.writeStartDocument();
xml.writeStartElement("root"); // <root>
for (; i < col_0.size(); ++i)
{
if (!(n_count > names.size() - 1))
if (col_0[i] == names[n_count] && i > 1)
break;
if (col_0[i] != nm && col_0[i] != "root")
xml.writeTextElement(col_0[i], col_1[i]);
}
xml.writeEndElement(); // </root>
xml.writeEndDocument();
f_out.close();
++n_count;
}
if (xml.hasError())
return "Произошла ошибка при записи в файл.";
else
return "Данные успешно записаны.";
}
<file_sep>/table_model.cpp
#include "table_model.h"
#include <QDebug>
QVariant TABLE_MODEL::data(const QModelIndex &index, int nRole) const
{
if (!index.isValid())
{
return QVariant();
}
QString str =
QString("%1, %2").arg(index.row() + 1).arg(index.column() + 1);
return (nRole == Qt::DisplayRole || nRole == Qt::EditRole)
? m_hash.value(index, QVariant())
: QVariant();
}
bool TABLE_MODEL::setData(const QModelIndex &index, const QVariant &value, int nRole)
{
if (index.isValid() && nRole == Qt::EditRole)
{
m_hash[index] = value;
emit dataChanged(index, index);
return true;
}
return false;
}
Qt::ItemFlags TABLE_MODEL::flags(const QModelIndex &index) const
{
Qt::ItemFlags flags = QAbstractTableModel::flags(index);
return index.isValid() ? (flags | Qt::ItemIsEditable)
: flags;
}
QVariant TABLE_MODEL::headerData(int nSection, Qt::Orientation orientation, int nRole) const
{
if (nRole != Qt::DisplayRole)
{
return QVariant();
}
return (orientation == Qt::Horizontal) ?
objName[nSection]
: rowsNames[nSection];
}
void TABLE_MODEL::setValue(const int nRows, const int nColumns, const QVariant &val)
{
// TODO add range check
this->setData(this->index(nRows, nColumns, QModelIndex()), val, Qt::EditRole);
}
QVariant TABLE_MODEL::getCellContent(const int nRows, const int nColumns) const
{
return this->data(index(nRows, nColumns, QModelIndex()), Qt::EditRole);
}
bool TABLE_MODEL::insertRows(int position, int rows, const QModelIndex &parent)
{
Q_UNUSED(parent);
beginInsertRows(parent, position, position + rows - 1);
++m_nRows;
int rowNum = rowsNames.last().toInt();
rowsNames.append(QString::number(++rowNum));
endInsertRows();
return true;
}
bool TABLE_MODEL::removeRows(int position, int rows, const QModelIndex &index)
{
Q_UNUSED(index);
beginRemoveRows(QModelIndex(), position, position+rows-1);
--m_nRows;
endRemoveRows();
return true;
}
void TABLE_MODEL::clear()
{
this->beginResetModel();
setSize(0, 0);
m_hash.clear();
objName.clear();
rowsNames.clear();
this-> endResetModel();
}
<file_sep>/mainwnd.h
#ifndef MAINWND_H
#define MAINWND_H
#include <QObject>
#include <QWidget>
#include <QTableView>
#include <QPushButton>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QProgressDialog>
#include <QString>
#include <QLabel>
#include <QTextEdit>
#include <QPoint>
#include <QMenu>
#include <QAction>
#include <QClipboard>
#include <QApplication>
#include <QMessageBox>
#include <QPair>
#include <QStringList>
#include "filesreader.h"
#include "filesproxy.h"
#include "table_model.h"
#include "xmlwriter.h"
typedef QMap<QString, QString> MAP_s_s_;
typedef QPair<QStringList, QStringList> MAP_lsts;
class mainwnd : public QObject
{
Q_OBJECT
private:
QWidget* mainwgt;
QProgressDialog* progressWnd;
QTextEdit* txt_edit;
TABLE_MODEL* p_tModel = nullptr;
QTableView* table;
FilesReader* reader;
QPushButton* import_Btn;
QPushButton* clear_Btn;
QMenu *menu;
QString menuStr;
QClipboard *buf = QApplication::clipboard();
bool setTable = false;
QModelIndex currentIndex;
FilesProxy objForModel;
xml_writer xmlWriter;
QVBoxLayout* lyt;
public:
explicit mainwnd(QObject *parent = nullptr);
void setWidgetContent();
void copyToClipboard(const QString& str);
bool isTableFill() { return setTable; }
void startExport();
void recordData();
//signals:
public slots:
void setTableModel();
void clearTable();
void addProgressInfo();
void showProgress();
void customMenuRequested(const QPoint& p);
void slotActivated(QAction* action);
void defaultFileSlot();
};
#endif // MAINWND_H
<file_sep>/xmlreader.cpp
#include "xmlreader.h"
#include <QDebug>
#include <iostream>
#include <QMessageBox>
#include <QSharedPointer>
xml_reader::xml_reader(const QString& f_name, QObject *parent) : QObject(parent)
{
qRegisterMetaType<COMMUTATOR>("COMMUTATOR");
f_nm = f_name;
}
MAP_lsts xml_reader::getFileStrings() const
{
return fileLsts;
}
QString xml_reader::getErrors() const
{
return errors;
}
int xml_reader::getLinesCount() const
{
return linesCount;
}
void xml_reader::resetObj()
{
f_in.close();
xml.clear();
fileLsts.first.clear();
fileLsts.second.clear();
errors.clear();
linesCount = 0;
}
void xml_reader::doWork(const QString nm)
{
f_nm = nm;
f_in.setFileName(f_nm);
if (!f_in.open(QIODevice::ReadOnly/* | QFile::Text*/))
{
qDebug() << "Can`t read file";
qDebug() << f_in.errorString();
QMessageBox msgBox;
msgBox.setText("Произошла ошибка при открытии файла.\n"
+ f_in.errorString());
msgBox.exec();
}
xml.setDevice(&f_in);
xml.readNext();
fileLsts.first.append(f_nm); // Setup header (Name + Attributes)
fileLsts.second.append(xml.documentVersion().toString() + "; "
+ xml.documentEncoding().toString());
while (!xml.atEnd())
{
QXmlStreamReader::TokenType token = xml.readNext();
if (token == QXmlStreamReader::StartDocument)
continue;
if (token == QXmlStreamReader::StartElement)
{
QString t_str(xml.name().toString());
xml.readNext();
fileLsts.first.append(t_str);
fileLsts.second.append(xml.text().toString());
++linesCount;
}
}
if (xml.hasError())
{
errors = xml.errorString();
}
objToSend.fileLsts = fileLsts;
objToSend.errors = errors;
objToSend.linesCount = linesCount;
objToSend.f_nm = f_nm;
f_in.close();
// some progressBar math here
++calls; // filesCount - numser of files in list
qDebug() << "(calls * scale) = " << (calls * scale);
emit updateBar(calls * scale);
emit resultReady(objToSend);
}
void xml_reader::clear()
{
f_in.close();
xml.clear();
fileLsts.first.clear();
fileLsts.second.clear();
errors.clear();
// linesCount = 0;
f_nm.clear();
objToSend.f_nm.clear();
objToSend.errors.clear();
objToSend.fileLsts.first.clear();
objToSend.fileLsts.second.clear();
//objToSend.linesCount = 0;
}
void xml_reader::setFilesCountSlot(const int cnt)
{
filesCount = cnt;
scale = 100.0 / cnt;
calls = 0;
}
<file_sep>/filesproxy.cpp
#include "filesproxy.h"
#include <QDebug>
FilesProxy::FilesProxy(const int q, const QStringList &nm_lst,
const QMap<QString, MAP_lsts>& f_maps,
const MAP_s_s_& e_map)
: quantity(q), names(nm_lst), files_maps(f_maps), errors_map(e_map)
{
}
void FilesProxy::addLinesCount(int lines)
{
quantity += lines;
}
void FilesProxy::addName(const QString &f_name)
{
names.append(f_name);
}
void FilesProxy::addValue(const QString &f_name, const MAP_lsts& f_lsts)
{
files_maps.insert(f_name, f_lsts);
}
void FilesProxy::addError(const QString &f_name, const QString &err_str)
{
errors_map.insert(f_name, err_str);
}
bool FilesProxy::hasErrors() const
{
return has_err;
}
void FilesProxy::setErr()
{
has_err = true;
}
QStringList FilesProxy::getNamesLst() const
{
return names;
}
MAP_lsts FilesProxy::getFilePairs(const QString &name) const
{
return files_maps.value(name);
}
MAP_s_s_ FilesProxy::getErrorMap() const
{
return errors_map;
}
int FilesProxy::getSize() const
{
int comm_sz = 0;
for (auto& keyStr : names)
{
comm_sz += files_maps[keyStr].first.size();
}
return comm_sz;// + names.size();
}
void FilesProxy::clear()
{
quantity = 0;
size = 0;
names.clear();
files_maps.clear();
errors_map.clear();
has_err = false;
}
<file_sep>/xmlwriter.h
#ifndef XML_WRITER_H
#define XML_WRITER_H
#include <QObject>
#include <QFile>
#include <QXmlStreamWriter>
#include <QStringList>
class xml_writer : public QObject
{
Q_OBJECT
private:
QFile f_out;
QXmlStreamWriter xml;
public:
explicit xml_writer(QObject *parent = nullptr);
QString writeToFile(const QStringList& names, const QStringList& col_0, const QStringList& col_1);
signals:
public slots:
};
#endif // XML_WRITER_H
|
50c949cbe12c01412466864b016bc51a7ca2fbf3
|
[
"C++"
] | 13
|
C++
|
GregoryError/xml_explorer
|
84f74058681d29027728d4b6e28e475ac164f899
|
0ff30575af093e69cc91c7aa6e6ce49c516c2481
|
refs/heads/master
|
<file_sep>function load(page){
parent.parent.location.hash = page;
if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
var mainpage = parent.frames["main"];
mainpage.location.href=page;
return;
}
else{
parent.document.getElementById('frameSet1').cols = "20%,*,20%";
parent.document.getElementById('frameSet3').rows = "65%,*";
var mainpage = parent.frames["related"];
mainpage.location.href="related.html";
var mainpage = parent.frames["main"];
mainpage.location.href=page;
}
}
|
cd15bd2b7a6040f206660d64bdf643f50d19e99d
|
[
"JavaScript"
] | 1
|
JavaScript
|
gewl/gewl.github.io
|
9720a2a24205521ca675a671e66e6965b55a1e77
|
e5f59567320791f042f2797087c61fdd0d369ea7
|
refs/heads/master
|
<repo_name>hackerzgz/distortmirr<file_sep>/go.mod
module github.com/hackerzgz/distortmirr
go 1.12
require (
github.com/emirpasic/gods v1.12.0
github.com/hackez/distortmirr v0.0.0-20190716121658-7bf9685668cb
)
<file_sep>/mirror/davinci/render.go
package davinci
import (
"fmt"
"go/ast"
"html/template"
"io"
"strings"
"github.com/emirpasic/gods/maps/treemap"
"github.com/hackerzgz/distortmirr/mirror/brush"
)
type Davinci struct {
pkgname string
types *treemap.Map
meths *treemap.Map
funcs *treemap.Map
}
var (
typeTemp *template.Template
methTemp *template.Template
funcTemp *template.Template
)
func init() {
var err error
typeTemp, err = template.New("davinci-type").Parse(`
type {{ .TypeName }} struct {
{{ .InnerName }} {{ .PkgName }}.{{ .TypeName }}
}
`)
if err != nil {
panic(err)
}
methTemp, err = template.New("davinci-meth").Parse(`
func ({{ .InnerName }} {{ .TypeName }}) {{ .MethName }} ({{ .Input }}) {{ if ne .Output "" }}({{.Output}}){{ end }} {
{{ if eq .Output "" -}}
{{ .InnerName }}.{{ .InnerName }}.{{ .MethName }}({{ .Parameters }})
{{- else -}}
return {{ .InnerName }}.{{ .InnerName }}.{{ .MethName }}({{ .Parameters }})
{{- end }}
}
`)
if err != nil {
panic(err)
}
funcTemp, err = template.New("davinci-func").Parse(`
func {{ .FuncName }}({{ .Input }}) {{ if ne .Output "" }}({{.Output}}){{ end }} {
{{ if eq .Output "" -}}
{{ .PkgName }}.{{ .FuncName }}({{ .Parameters }})
{{- else -}}
return {{ .PkgName }}.{{ .FuncName }}({{ .Parameters }})
{{- end }}
}
`)
if err != nil {
panic(err)
}
}
func New(pkgname string, types *treemap.Map, meths *treemap.Map, funcs *treemap.Map,
) *Davinci {
return &Davinci{
pkgname: pkgname,
types: types,
meths: meths,
funcs: funcs,
}
}
// Render a wrapper of package
func (m *Davinci) Render(wr io.Writer) (err error) {
fmt.Println("davinci start printing...")
typeIter := m.types.Iterator()
for typeIter.Next() {
tname, typ := typeIter.Key().(string), typeIter.Value().(*ast.GenDecl)
err = m.renderType(wr, typ)
if err != nil {
return err
}
meths, found := m.meths.Get(tname)
if !found {
continue
}
methIter := meths.(*treemap.Map).Iterator()
for methIter.Next() {
meth := methIter.Value().(*ast.FuncDecl)
err = m.renderMeth(wr, tname, meth)
if err != nil {
return err
}
}
}
funcIter := m.funcs.Iterator()
for funcIter.Next() {
fn := funcIter.Value().(*ast.FuncDecl)
err = m.renderFunc(wr, fn)
if err != nil {
return err
}
}
return nil
}
func (m *Davinci) renderType(wr io.Writer, decl *ast.GenDecl) error {
typeDecl := decl.Specs[0].(*ast.TypeSpec)
data := struct {
TypeName string
InnerName string
PkgName string
}{
TypeName: typeDecl.Name.Name,
InnerName: strings.ToLower(typeDecl.Name.Name[:1]),
PkgName: m.pkgname,
}
return typeTemp.Execute(wr, data)
}
func (m *Davinci) renderMeth(wr io.Writer, typeName string, decl *ast.FuncDecl) error {
data := struct {
TypeName string
InnerName string
MethName string
Input string
Output string
Parameters string
}{
TypeName: typeName,
InnerName: strings.ToLower(typeName[:1]),
MethName: decl.Name.Name,
Input: strings.Join(brush.GetIOutput(decl.Type.Params), ", "),
Output: strings.Join(brush.GetIOutput(decl.Type.Results), ", "),
Parameters: strings.Join(brush.GetParamNames(decl.Type.Params), ", "),
}
return methTemp.Execute(wr, data)
}
func (m *Davinci) renderFunc(wr io.Writer, decl *ast.FuncDecl) error {
data := struct {
FuncName string
Input string
Output string
PkgName string
Parameters string
}{
FuncName: decl.Name.Name,
Input: strings.Join(brush.GetIOutput(decl.Type.Params), ", "),
Output: strings.Join(brush.GetIOutput(decl.Type.Results), ", "),
PkgName: m.pkgname,
Parameters: strings.Join(brush.GetParamNames(decl.Type.Params), ", "),
}
return funcTemp.Execute(wr, data)
}
<file_sep>/mirror/brush/brush.go
package brush
import (
"fmt"
"go/ast"
"strings"
)
func GetIOutput(fields *ast.FieldList) []string {
if fields == nil {
return nil
}
ioutputs := make([]string, 0, len(fields.List))
for _, f := range fields.List {
names := make([]string, 0, len(f.Names))
for _, n := range f.Names {
names = append(names, n.Name)
}
typeName := GetTypeName(f.Type)
ioutputs = append(ioutputs, strings.Join(names, ", ")+" "+typeName)
}
return ioutputs
}
func GetParamNames(fields *ast.FieldList) []string {
names := make([]string, 0, len(fields.List))
for _, f := range fields.List {
for _, n := range f.Names {
names = append(names, n.Name)
}
}
return names
}
func GetTypeName(f ast.Expr) string {
if f == nil {
return ""
}
switch f.(type) {
case *ast.StarExpr:
return "*" + GetTypeName(f.(*ast.StarExpr).X)
case *ast.Ident:
return f.(*ast.Ident).Name
case *ast.SelectorExpr:
return f.(*ast.SelectorExpr).X.(*ast.Ident).Name +
"." +
f.(*ast.SelectorExpr).Sel.Name
case *ast.InterfaceType:
if len(f.(*ast.InterfaceType).Methods.List) > 0 {
panic("anonymous interface not support")
}
return "interface{}"
case *ast.MapType:
t := f.(*ast.MapType)
return "map[ " + GetTypeName(t.Value) + " ]" +
GetTypeName(t.Value)
case *ast.ArrayType:
t := f.(*ast.ArrayType)
return "[" + GetTypeName(t.Len) + "]" + GetTypeName(t.Elt)
case *ast.ChanType:
t := f.(*ast.ChanType)
switch t.Dir {
case ast.SEND:
return "<-" + GetTypeName(t.Value)
case ast.RECV:
return GetTypeName(t.Value) + "<-"
default:
// must both SEND & RECV
return GetTypeName(t.Value)
}
case *ast.Ellipsis:
t := f.(*ast.Ellipsis)
return "..." + GetTypeName(t.Elt)
default:
// attempt to known what type is it for debug...
_ = f.(*ast.BadExpr)
panic(fmt.Errorf("unknown expression: %+v", f))
}
}
<file_sep>/main.go
package main
import (
"flag"
"fmt"
"os"
"github.com/hackerzgz/distortmirr/mirror"
)
var (
pkgFlag = flag.String("pkg", "", "the package name of Go style")
scanFlag = flag.Int("scan", int(mirror.ScanPublic), "the scan mode of distorting mirror")
modeFlag = flag.String("mode", "monet", "the render mode of distorting mirror")
outputFlag = flag.String("output", "", "the path of output file")
)
func init() {
flag.Parse()
}
func main() {
mirr, err := mirror.New(*pkgFlag, mirror.ScanMode(*scanFlag))
if err != nil {
fmt.Println("failed to new mirror: ", err)
os.Exit(-1)
}
err = mirr.Scan()
if err != nil {
fmt.Println("failed to scan package: ", err)
os.Exit(-1)
}
if *outputFlag != "" {
f, err := os.Create(*outputFlag)
if err != nil {
panic(err)
}
err = mirr.Render(*modeFlag, f)
} else {
err = mirr.Render(*modeFlag, os.Stdout)
}
if err != nil {
fmt.Println("failed to render package: ", err)
os.Exit(-1)
}
}
<file_sep>/mirror/monet/render.go
package monet
import (
"go/ast"
"html/template"
"io"
"strings"
"github.com/emirpasic/gods/maps/treemap"
"github.com/hackerzgz/distortmirr/mirror/brush"
)
var (
interfaceTemp *template.Template
)
func init() {
var err error
interfaceTemp, err = template.New("monet-interface").Parse(`
type {{ .TypeName }}er interface {
{{- range $idx, $meth := .Meths }}
{{ $meth.Name }} ({{ $meth.Input }}) {{- if ne $meth.Ouput "" }} ({{$meth.Ouput}}) {{ end -}}
{{ end }}
}
`)
if err != nil {
panic(err)
}
}
type Monet struct {
types *treemap.Map
meths *treemap.Map
}
func New(types *treemap.Map, meths *treemap.Map) *Monet {
return &Monet{
types: types,
meths: meths,
}
}
func (m *Monet) Render(wr io.Writer) (err error) {
typeIter := m.types.Iterator()
for typeIter.Next() {
tname := typeIter.Key().(string)
if err = m.renderInterface(wr, tname); err != nil {
return err
}
}
return nil
}
func (m *Monet) renderInterface(wr io.Writer, name string) error {
data := struct {
TypeName string
Meths []struct {
Name string
Input string
Ouput string
}
}{
TypeName: name,
}
var meths *treemap.Map
if mm, found := m.meths.Get(name); found {
meths = mm.(*treemap.Map)
} else {
return nil
}
data.Meths = make([]struct {
Name string
Input string
Ouput string
}, 0, meths.Size())
methIter := meths.Iterator()
for methIter.Next() {
mname, meth := methIter.Key().(string), methIter.Value().(*ast.FuncDecl)
data.Meths = append(data.Meths, struct {
Name string
Input string
Ouput string
}{
Name: mname,
Input: strings.Join(brush.GetIOutput(meth.Type.Params), ", "),
Ouput: strings.Join(brush.GetIOutput(meth.Type.Results), ", "),
})
}
// skip the struct have no methods
if len(data.Meths) == 0 {
return nil
}
return interfaceTemp.Execute(wr, data)
}
<file_sep>/mirror/mirror.go
package mirror
import (
"errors"
"fmt"
"go/ast"
"go/parser"
"go/token"
"io"
"os"
"path/filepath"
"strings"
"sync"
"github.com/emirpasic/gods/maps/treemap"
"github.com/hackerzgz/distortmirr/mirror/davinci"
"github.com/hackerzgz/distortmirr/mirror/monet"
)
type ScanMode int
const (
ScanAll ScanMode = iota
ScanPublic
)
type Mirror struct {
mode ScanMode
gopaths []string
pkgpath string
pkgname string
mtx *sync.Mutex
types *treemap.Map
meths *treemap.Map
funcs *treemap.Map
}
func New(pkgpath string, mode ScanMode) (*Mirror, error) {
if pkgpath == "" {
return nil, errors.New("invalid arguments: package path cannot be empty")
}
gopath := os.Getenv("GOPATH")
if "" == gopath {
return nil, errors.New("failed to find GOPATH environment")
}
m := &Mirror{
mode: mode,
gopaths: strings.Split(gopath, ":"),
pkgpath: strings.TrimSuffix(pkgpath, "/"),
}
m.pkgname = m.pkgpath[strings.LastIndex(m.pkgpath, "/")+1:]
m.mtx = new(sync.Mutex)
m.types = treemap.NewWithStringComparator()
m.meths = treemap.NewWithStringComparator()
m.funcs = treemap.NewWithStringComparator()
return m, nil
}
func (m *Mirror) Scan() error {
for _, p := range m.gopaths {
// create a new file set on each path
fs := token.NewFileSet()
// combine a complete package path
if !strings.HasSuffix(p, "/") {
p += "/"
}
p += "src/" + m.pkgpath
if _, err := os.Stat(p); err != nil {
continue
}
// attempt to find out package
err := filepath.Walk(p, func(path string, info os.FileInfo, err error) error {
switch {
case err != nil:
return err
// skip to next step if directory met
case info.IsDir(),
!strings.HasSuffix(info.Name(), ".go"),
strings.HasSuffix(info.Name(), "_test.go"):
return nil
}
return m.parseFile(fs, p+"/"+info.Name())
})
if err != nil {
if err == os.ErrNotExist {
continue
}
}
}
return nil
}
func (m *Mirror) parseFile(fs *token.FileSet, fname string) error {
f, err := parser.ParseFile(fs, fname, nil, 0)
if err != nil {
return err
}
for _, decl := range f.Decls {
switch decl.(type) {
case *ast.GenDecl:
if decl.(*ast.GenDecl).Tok == token.TYPE {
m.registerType(decl.(*ast.GenDecl))
}
case *ast.FuncDecl:
if decl.(*ast.FuncDecl).Recv != nil {
m.registerMeth(decl.(*ast.FuncDecl))
} else {
m.registerFunc(decl.(*ast.FuncDecl))
}
}
}
return nil
}
func (m *Mirror) registerType(decl *ast.GenDecl) {
var typeName string
for _, spec := range decl.Specs {
if s, ok := spec.(*ast.TypeSpec); ok {
typeName = s.Name.Name
break
}
}
if m.mode == ScanPublic && !ast.IsExported(typeName) {
return
}
m.mtx.Lock()
defer m.mtx.Unlock()
m.types.Put(typeName, decl)
}
func (m *Mirror) registerMeth(decl *ast.FuncDecl) {
if m.mode == ScanPublic && !ast.IsExported(decl.Name.Name) {
return
}
if len(decl.Recv.List) <= 0 {
panic("unknown method receiver: " + decl.Name.Name)
}
// find out the explicit type of method receiver
typeName := getTypeName(decl.Recv.List[0].Type)
if typeName == "" {
panic("failed to find out explicit type of method: " + decl.Name.Name)
}
typeName = strings.TrimPrefix(typeName, "*")
// lock the mirror for register methods
m.mtx.Lock()
defer m.mtx.Unlock()
var meths *treemap.Map
mm, found := m.meths.Get(typeName)
if found {
meths = mm.(*treemap.Map)
} else {
meths = treemap.NewWithStringComparator()
}
meths.Put(decl.Name.Name, decl)
m.meths.Put(typeName, meths)
}
func (m *Mirror) registerFunc(decl *ast.FuncDecl) {
if m.mode == ScanPublic && !ast.IsExported(decl.Name.Name) {
return
}
m.mtx.Lock()
defer m.mtx.Unlock()
m.funcs.Put(decl.Name.Name, decl)
}
type Renderer interface {
Render(wr io.Writer) error
}
func (m *Mirror) newRenderer(name string) (Renderer, error) {
switch name {
case "davinci":
return davinci.New(m.pkgname, m.types, m.meths, m.funcs), nil
case "monet":
return monet.New(m.types, m.meths), nil
default:
return nil, errors.New("renderer not supported: " + name)
}
}
// Render a wrapper of package
func (m *Mirror) Render(name string, wr io.Writer) (err error) {
fmt.Println("start render...")
m.mtx.Lock()
defer m.mtx.Unlock()
r, e := m.newRenderer(name)
if e != nil {
return e
}
return r.Render(wr)
}
<file_sep>/mirror/template.go
package mirror
import (
"fmt"
"go/ast"
"io"
"strings"
"text/template"
)
var (
typeTemp *template.Template
methTemp *template.Template
funcTemp *template.Template
)
func init() {
var err error
typeTemp, err = template.New("mirr-type").Parse(`
type {{ .TypeName }} struct {
{{ .InnerName }} {{ .PkgName }}.{{ .TypeName }}
}
`)
if err != nil {
panic(err)
}
methTemp, err = template.New("mirr-meth").Parse(`
func ({{ .InnerName }} {{ .TypeName }}) {{ .MethName }} ({{ .Input }}) {{ if ne .Output "" }}({{.Output}}){{ end }} {
{{ if eq .Output "" -}}
{{ .InnerName }}.{{ .InnerName }}.{{ .MethName }}({{ .Parameters }})
{{- else -}}
return {{ .InnerName }}.{{ .InnerName }}.{{ .MethName }}({{ .Parameters }})
{{- end }}
}
`)
if err != nil {
panic(err)
}
funcTemp, err = template.New("mirr-func").Parse(`
func {{ .FuncName }}({{ .Input }}) {{ if ne .Output "" }}({{.Output}}){{ end }} {
{{ if eq .Output "" -}}
{{ .PkgName }}.{{ .FuncName }}({{ .Parameters }})
{{- else -}}
return {{ .PkgName }}.{{ .FuncName }}({{ .Parameters }})
{{- end }}
}
`)
if err != nil {
panic(err)
}
}
func (m *Mirror) renderType(wr io.Writer, decl *ast.GenDecl) error {
typeDecl := decl.Specs[0].(*ast.TypeSpec)
data := struct {
TypeName string
InnerName string
PkgName string
}{
TypeName: typeDecl.Name.Name,
InnerName: strings.ToLower(typeDecl.Name.Name[:1]),
PkgName: m.pkgname,
}
return typeTemp.Execute(wr, data)
}
func (m *Mirror) renderMeth(wr io.Writer, typeName string, decl *ast.FuncDecl) error {
data := struct {
TypeName string
InnerName string
MethName string
Input string
Output string
Parameters string
}{
TypeName: typeName,
InnerName: strings.ToLower(typeName[:1]),
MethName: decl.Name.Name,
Input: strings.Join(getIOutput(decl.Type.Params), ", "),
Output: strings.Join(getIOutput(decl.Type.Results), ", "),
Parameters: strings.Join(getParamNames(decl.Type.Params), ", "),
}
return methTemp.Execute(wr, data)
}
func (m *Mirror) renderFunc(wr io.Writer, decl *ast.FuncDecl) error {
data := struct {
FuncName string
Input string
Output string
PkgName string
Parameters string
}{
FuncName: decl.Name.Name,
Input: strings.Join(getIOutput(decl.Type.Params), ", "),
Output: strings.Join(getIOutput(decl.Type.Results), ", "),
PkgName: m.pkgname,
Parameters: strings.Join(getParamNames(decl.Type.Params), ", "),
}
return funcTemp.Execute(wr, data)
}
func getIOutput(fields *ast.FieldList) []string {
if fields == nil {
return nil
}
ioutputs := make([]string, 0, len(fields.List))
for _, f := range fields.List {
names := make([]string, 0, len(f.Names))
for _, n := range f.Names {
names = append(names, n.Name)
}
typeName := getTypeName(f.Type)
ioutputs = append(ioutputs, strings.Join(names, ", ")+" "+typeName)
}
return ioutputs
}
func getParamNames(fields *ast.FieldList) []string {
names := make([]string, 0, len(fields.List))
for _, f := range fields.List {
for _, n := range f.Names {
names = append(names, n.Name)
}
}
return names
}
func getTypeName(f ast.Expr) string {
if f == nil {
return ""
}
switch f.(type) {
case *ast.StarExpr:
return "*" + getTypeName(f.(*ast.StarExpr).X)
case *ast.Ident:
return f.(*ast.Ident).Name
case *ast.SelectorExpr:
return f.(*ast.SelectorExpr).X.(*ast.Ident).Name +
"." +
f.(*ast.SelectorExpr).Sel.Name
case *ast.InterfaceType:
if len(f.(*ast.InterfaceType).Methods.List) > 0 {
panic("anonymous interface not support")
}
return "interface{}"
case *ast.MapType:
t := f.(*ast.MapType)
return "map[ " + getTypeName(t.Value) + " ]" +
getTypeName(t.Value)
case *ast.ArrayType:
t := f.(*ast.ArrayType)
return "[" + getTypeName(t.Len) + "]" + getTypeName(t.Elt)
case *ast.ChanType:
t := f.(*ast.ChanType)
switch t.Dir {
case ast.SEND:
return "<-" + getTypeName(t.Value)
case ast.RECV:
return getTypeName(t.Value) + "<-"
default:
// must both SEND & RECV
return getTypeName(t.Value)
}
default:
// attempt to known what type is it for debug...
_ = f.(*ast.BadExpr)
panic(fmt.Errorf("unknown expression: %+v", f))
}
}
|
68bcb64636419786f690eddaaefa80184af7fe55
|
[
"Go",
"Go Module"
] | 7
|
Go Module
|
hackerzgz/distortmirr
|
da651cafbef72c87c92c0758e8e1fd5063820d2b
|
39780342e4b735b2756eebbb72683309215dbcb9
|
refs/heads/master
|
<file_sep>/** A stack is a list that follows the last-in-first-out (LIFO)
* principle. An example is a stack of cafeteria trays. You take
* the top one, which is the last one that the staff put in.*/
public interface Stack<T> {
/** Push e on this stack. */
public void push(T e);
/** Pop the top element of this stack and return it.
* Throw RuntimeException if the stack is empty */
public T pop();
/** Return true iff this stack contains e. */
public boolean contains(T e);
/** Return the number of elements in this stack. */
public int size();
}
/** Stack cell (a helper class; visible to other classes in same package). */
class StackCell<T> {
public T datum; // Data for this cell
public StackCell<T> next; // Next cell in this Stack
/** Constructor: an instance with datum d and next cell next. */
public StackCell(T d, StackCell<T> next) {
datum= d;
this.next= next;
}
}
<file_sep>/** An array implementation of a stack. */
public class ArrayStack<T> implements Stack<T> {
// The elements of the list are in theArray[0..n-1], with the
// bottom element in theArray[0] and top in theArray{n-1]
// Thus, the stack contains n elements.
private Object[] theArray;
private int n;
/** Constructor: an empty stack with capacity c */
public ArrayStack(int c) {
theArray= new Object[c];
n= 0;
}
/** Constructor: an empty stack with capacity 10. */
public ArrayStack() {
this(10);
}
/** Push e on this stack. */
public @Override void push(T e) {
// if no room, allocate a new array, copy over old one
if (n == theArray.length) {
Object[] newArray= new Object[2 * theArray.length + 1];
System.arraycopy(theArray, 0, newArray, 0, n);
theArray= newArray;
}
theArray[n]= e;
n= n+1;
}
/** Pop the top element of this stack and return it.
* Throw RuntimeException if the stack is empty */
public @Override T pop() {
if (n == 0)
throw new RuntimeException("Cannot pop an empty Stack");
n= n-1;
return (T) theArray[n];
}
/** Return the number of elements. */
public @Override int size() {
return n;
}
/** Delete first (topmost) occurrence of e from this stack (if it is there). */
public void delete(T e) {
// invariant: theArray[i+1..] does not contain e
for (int i= n-1; 0 <= i; i= i-1) {
if (equal(e, theArray[i])) {
// Move theArray[i+1..n-1] down to theArray[i..n-2]
for (int j= i + 1; j < n; j= j+1) {
theArray[j-1]= theArray[j];
}
n= n-1;
return;
}
}
}
/** Return true iff x and y are both null or
* x is not null and x.equals(y). */
private boolean equal(T x, Object y) {
return (x != null && x.equals(y)) || (x == null && y == null);
}
/** Return true iff this stack contains e. */
public @Override boolean contains(T e) {
for (int i= 0; i < n; i= i+1)
if (equal(e, theArray[i])) return true;
return false;
}
/** Return the representation of this stack in this form:<br>
* [ e0, e1, ..., e(n-1)]<br>
* where e0 is the top element and elast is the bottom one. */
public String toString() {
String result = "[";
for (int i = n-1; 0 <= i; i= i-1) {
if (i < n-1)
result= result + ", ";
result= result + theArray[i];
}
return result + "]";
}
/** Reverse this list in place. */
public void ReverseInPlace() {
int h= 0;
int k= n-1;
// invariant: theArray[0..h-1] and theArray[k+1..n-1] already reversed,
// so theArray[h..k] needs to be reversed
while (0 < k-h) {
Object temp= theArray[h];
theArray[h]= theArray[k];
theArray[k]= temp;
h= h+1;
k= k-1;
}
}
}
<file_sep>/** A linked list implementation of a stack, with no recursion. */
public class LinkedListStackIt<T> implements Stack<T> {
// Head (first cell) of the List --null if list empty.
// When viewed as a stack, the first element on the list is the top
// and the last element on the list is the bottom.
private StackCell<T> head;
/**Constructor: An empty stack. */
public LinkedListStackIt() {
head= null;
}
/** Push e on this stack. */
public @Override void push(T e) {
head= new StackCell<T>(e, head);
}
/** Pop the top element of this stack and return it.
* Throw RuntimeException if the stack is empty */
public @Override T pop() {
if (head == null)
throw new RuntimeException("Cannot pop an empty Stack");
T h= head.datum;
head= head.next;
return h;
}
/** Return the number of elements. */
public @Override int size() {
int count= 0;
StackCell<T> current= head;
while (current != null) {
count= count + 1;
current= current.next;
}
return count;
}
/** Delete first (topmost) occurrence of e from this stack (if it is there). */
public void delete(T e) {
if (head == null) return;
if (equal(e, head.datum)) {
head= head.next;
return;
}
StackCell<T> current= head;
StackCell<T> scout= head.next;
// invariant: the cells head, head.next, ..., current
// do not contain e
// and scout = current.next.
while (scout != null) {
if (equal(e, scout.datum)) {
current.next= scout.next; // found--unlink cell
return;
}
current= scout;
scout= current.next;
}
}
/** Return true iff x and y are both null or
* x is not null and x.equals(y). */
private boolean equal(T x, T y) {
return (x == null && y == null) || (x != null && x.equals(y));
}
/** Return true iff this stack contains e. */
public @Override boolean contains(T e) {
StackCell<T> current= head;
// inv: e is not in head, head.next, ..., cell before current
while (current != null && !equal(e, current.datum)) {
current= current.next;
}
return current != null;
}
/** Return the representation of this stack in this form:<br>
* [ e0, e1, ..., elast]<br>
* where e0 is the top element and elast is the bottom one. */
public String toString() {
String result = "[";
StackCell<T> current = head;
while (current != null) {
if (current != head)
result= result + ", ";
result= result + current.datum;
current = current.next;
}
return result + "]";
}
/** Reverse this list in place. */
public void ReverseInPlace() {
// Initial list is head: A -> B -> ... -> C -> D -> ... -> E
// Final list is A <- B <- ... <- C <- D <- ... <- E :head
StackCell<T> rest= head;
head= null;
// invariant, in words: head is a list of the first elements of the
// list, reversed. rest is a list the rest of the elements.
// invariant in a diagram: A <- B <- ... <- C :head
// rest: D -> ... -> E
// So each iteration removes first node of rest and pushes it on head
while (rest != null) {
StackCell<T> temp= rest;
rest= rest.next;
temp.next= head;
head= temp;
}
}
}
|
563f86fe0f616a5e48623461479b711a47c1eafc
|
[
"Java"
] | 3
|
Java
|
NaturalisSelectio/javaDBS
|
c4c4fcd330bf27f86e181eb2674d41193e060436
|
d33ba5e13820df42a9d6bed6056ef3ff201417f1
|
refs/heads/master
|
<repo_name>200013546/bamazon<file_sep>/bamazonManager.js
var mysql = require("mysql");
var inquirer = require("inquirer");
var columnify = require('columnify');
// Connection to the DB
var connection = mysql.createConnection({
host: "localhost",
port: 3306,
user: "root",
password: "<PASSWORD>",
database: "bamazon"
});
connection.connect(function (err) {
if (err) throw err;
start();
});
// Initial menu items
function start() {
inquirer
.prompt([
{
type: "list",
message: "Which information do you want?",
choices: [
"View Products for Sale",
"View Low Inventory",
"Add to Inventory",
"Add New Product",
"Add item to Department",
"Exit"
],
name: "option"
}
])
.then(function (inquirerResponse) {
if (inquirerResponse.option) {
caseWhich(inquirerResponse.option);
}
});
}
// View products for sale
function viewProducts() {
connection.query("SELECT * FROM products LEFT JOIN departments ON products.department_id = departments.department_id ORDER BY item_id", function (err, results) {
if (err) throw err;
var columnData = '';
var columnArray = [];
for (var i = 0; i < results.length; i++) {
columnData = {
item: results[i].item_id,
product: results[i].product_name,
price: "$" + (results[i].price).toFixed(2),
quantity: (results[i].stock_quantity),
department: (results[i].department_name)
}
columnArray.push(columnData);
}
console.log(columnify(columnArray));
start();
});
}
// view low inventory
function viewLowInv() {
connection.query("SELECT * FROM products WHERE stock_quantity < 7", function (err, results) {
if (err) throw err;
var columnData = '';
var columnArray = [];
for (var i = 0; i < results.length; i++) {
columnData = {
item: results[i].item_id,
product: results[i].product_name,
price: "$" + (results[i].price).toFixed(2),
quantity: (results[i].stock_quantity)
}
columnArray.push(columnData);
}
console.log(columnify(columnArray));
start();
});
}
// add to inventory
function addInv() {
connection.query("SELECT * FROM products", function (err, results) {
if (err) throw err;
// Select item to purchase
inquirer
.prompt([
{
name: "choice",
type: "list",
choices: function () {
var choiceArray = [];
for (var i = 0; i < results.length; i++) {
choiceArray.push(
"Item: " +
results[i].item_id +
" || Prouct: " +
results[i].product_name +
" || Price: $" +
(results[i].price).toFixed(2) +
" || Quantity: " +
(results[i].stock_quantity)
);
}
return choiceArray;
},
message: "What item# would you like to Add to?"
},
{
name: "quantity",
type: "input",
message: "How many would you like to Add?"
}
])
.then(function (answer) {
var chosenItem;
for (var i = 0; i < results.length; i++) {
var answerChoice = answer.choice.split(" ");
if (parseInt(results[i].item_id) === parseInt(answerChoice[1])) {
chosenItem = results[i];
}
}
connection.query(
"UPDATE products SET ? WHERE ?",
[
{
stock_quantity: parseInt(chosenItem.stock_quantity) + parseInt(answer.quantity)
},
{
item_id: chosenItem.item_id
}
],
function (error) {
if (error) throw err;
// Successful prchase
console.log("\nQuantity added successfully!");
start();
}
);
});
});
}
// add new product
function addNewProd() {
// prompt for info about the item being put up for auction
inquirer
.prompt([
{
name: "product",
type: "input",
message: "What product you would like to add?"
},
{
name: "price",
type: "input",
message: "What is the price?"
},
{
name: "quantity",
type: "input",
message: "How many are there?",
}
])
.then(function (answer) {
// when finished prompting, insert a new item into the db with that info
connection.query(
"INSERT INTO products SET ?",
{
product_name: answer.product,
price: answer.price,
stock_quantity: answer.quantity
},
function (err) {
if (err) throw err;
console.log("Your product was added successfully!\n");
// re-prompt the user for if they want to bid or post
chooseDepartment();
}
);
});
}
function addItemToDepartment(department) {
connection.query("SELECT * FROM products", function (err, results) {
if (err) throw err;
// Select item to purchase
inquirer
.prompt([
{
name: "product",
type: "checkbox",
choices: function () {
var choiceArray = [];
for (var i = 0; i < results.length; i++) {
choiceArray.push(
"Item: " +
results[i].item_id +
" || Prouct: " +
results[i].product_name
);
}
return choiceArray;
},
message: "Choose items to put in this department."
}
])
.then(function (answer) {
for (var i = 0; i < answer.product.length; i++) {
product = answer.product[i].split(" ");
connection.query(
"UPDATE products SET ? WHERE ?",
[
{
department_id: department
},
{
item_id: product[1]
}
],
function (error) {
if (error) throw err;
});
}
console.log("\nProducts updated successfully!\n");
start();
});
});
}
function chooseDepartment() {
connection.query("SELECT * FROM departments", function (err, results) {
if (err) throw err;
// Select item to purchase
inquirer
.prompt([
{
name: "choice",
type: "list",
choices: function () {
var choiceArray = [];
for (var i = 0; i < results.length; i++) {
choiceArray.push(
"ID: " +
results[i].department_id +
" || Department: " +
results[i].department_name
);
}
return choiceArray;
},
message: "Which Department do you want to Add to?"
},
])
.then(function (answer) {
department = answer.choice.split(" ");
console.log(department[1]);
addItemToDepartment(department[1]);
});
});
}
// case choice function
function caseWhich(option) {
switch (option) {
case "View Products for Sale":
viewProducts();
break;
case "View Low Inventory":
viewLowInv();
break;
case "Add to Inventory":
addInv();
break;
case "Add New Product":
addNewProd();
break;
case "Add item to Department":
chooseDepartment();
break;
case "Exit":
connection.end();
break;
}
}
<file_sep>/products.sql
DROP TABLE IF EXISTS `products`;
CREATE TABLE `products` (
`item_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`product_name` varchar(100) NOT NULL,
`price` decimal(10,2) NOT NULL,
`stock_quantity` int(10) unsigned NOT NULL,
`product_sales` decimal(10,2) NOT NULL,
`department_id` int(10) unsigned NOT NULL,
PRIMARY KEY (`item_id`)
);
<file_sep>/bamazonSupervisor.js
var mysql = require("mysql");
var inquirer = require("inquirer");
var columnify = require('columnify');
// Connection to the DB
var connection = mysql.createConnection({
host: "localhost",
port: 3306,
user: "root",
password: "<PASSWORD>",
database: "bamazon"
});
connection.connect(function (err) {
if (err) throw err;
start();
});
// Initial menu items
function start() {
inquirer
.prompt([
{
type: "list",
message: "Which information do you want?",
choices: [
"View Product Sales by Department",
"Create New Department",
"Add item to Department",
"Exit"
],
name: "option"
}
])
.then(function (inquirerResponse) {
if (inquirerResponse.option) {
caseWhich(inquirerResponse.option);
}
});
}
// View Product Sales by Department
function viewSales() {
connection.query("SELECT departments.department_id, department_name, over_head_costs, SUM(product_sales) AS productsales, (SUM(product_sales) - over_head_costs) AS total_profit FROM departments INNER JOIN products ON departments.department_id = products.department_id GROUP BY departments.department_id", function (err, results) {
if (err) throw err;
var columnData = '';
var columnArray = [];
for (var i = 0; i < results.length; i++) {
columnData = {
id: results[i].department_id,
department: results[i].department_name,
costs: results[i].over_head_costs,
sales: results[i].productsales,
profit: results[i].total_profit
}
columnArray.push(columnData);
}
console.log(columnify(columnArray));
start();
});
}
// Create New Department
function createDepartment() {
// prompt for info about the item being put up for auction
inquirer
.prompt([
{
name: "department",
type: "input",
message: "What is the New Department?"
},
{
name: "overHeadCosts",
type: "input",
message: "What are the Over Head Costs?"
}
])
.then(function (answer) {
// when finished prompting, insert a new item into the db with that info
connection.query(
"INSERT INTO departments SET ?",
{
department_name: answer.department,
over_head_costs: answer.overHeadCosts
},
function (err, result) {
if (err) throw err;
console.log("Your Department was added successfully!");
// re-prompt the user for if they want to bid or post
addItemToDepartment(result.insertId);
// start();
}
);
});
}
function addItemToDepartment(department) {
connection.query("SELECT * FROM products", function (err, results) {
if (err) throw err;
// Select item to purchase
inquirer
.prompt([
{
name: "product",
type: "checkbox",
choices: function () {
var choiceArray = [];
for (var i = 0; i < results.length; i++) {
choiceArray.push(
"Item: " +
results[i].item_id +
" || Prouct: " +
results[i].product_name
);
}
return choiceArray;
},
message: "Choose items to put in this department."
}
])
.then(function (answer) {
for (var i = 0; i < answer.product.length; i++) {
product = answer.product[i].split(" ");
connection.query(
"UPDATE products SET ? WHERE ?",
[
{
department_id: department
},
{
item_id: product[1]
}
],
function (error) {
if (error) throw err;
});
}
console.log("\nProducts updated successfully!\n");
start();
});
});
}
function chooseDepartment() {
connection.query("SELECT * FROM departments", function (err, results) {
if (err) throw err;
// Select item to purchase
inquirer
.prompt([
{
name: "choice",
type: "list",
choices: function () {
var choiceArray = [];
for (var i = 0; i < results.length; i++) {
choiceArray.push(
"ID: " +
results[i].department_id +
" || Department: " +
results[i].department_name
);
}
return choiceArray;
},
message: "Which Department do you want to Add to?"
},
])
.then(function (answer) {
department = answer.choice.split(" ");
console.log(department[1]);
addItemToDepartment(department[1]);
});
});
}
// case choice function
function caseWhich(option) {
switch (option) {
case "View Product Sales by Department":
viewSales();
break;
case "Create New Department":
createDepartment();
break;
case "Add item to Department":
chooseDepartment();
break;
case "Exit":
connection.end();
break;
}
}
<file_sep>/README.md
## Bamazon Customer
This node application allows the customer to purchase items from the command line. After selecting the item you can designate the quantity. Afterwards the application will show the product and how much money the customer owes.
## Bamazon Manager
The Manager has the ability to manage the inventory and add new products with the following options:
* View Products for Sale
* View Low Inventory
* Add to Inventory
* Add New Product
* Add item to Department
* Exit
## Bamazon Supervisor
The Supervisor has the ability to manage departments and view sales and profits.
* View Product Sales by Department
* Create New Department
* Add item to Department
* Exit
<file_sep>/departments.sql
DROP TABLE IF EXISTS `departments`;
CREATE TABLE `departments` (
`department_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`department_name` varchar(45) NOT NULL,
`over_head_costs` int(10) unsigned NOT NULL,
PRIMARY KEY (`department_id`)
);
|
451dc68e748cac85f71f1e7d629ed98b7bf59e49
|
[
"JavaScript",
"SQL",
"Markdown"
] | 5
|
JavaScript
|
200013546/bamazon
|
c2699cbfe9fcf1fb62438d770d9c57449d513ec8
|
e49d3cd02c710f2b0aa84e995567a07c02f37368
|
refs/heads/master
|
<repo_name>ZainAahianZaman/API-regression<file_sep>/src/test/java/com/fitchconnect/fiscontent/fisCon_Sprint37.java
package com.fitchconnect.fiscontent;
import static com.jayway.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import java.io.IOException;
import java.net.URL;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.fitchconnect.api.Configuration;
import com.google.common.io.Resources;
import com.jayway.restassured.response.Response;
import groovy.json.internal.Charsets;
public class fisCon_Sprint37 extends Configuration {
@Test(enabled=false)
public void BMI_Dates_Monthly_quarterly_Annual_fisc2755() throws IOException{
URL file = Resources.getResource("bmi_dates_mthly_Quatrly.json");
String myJson = Resources.toString(file, Charsets.UTF_8);
Response res = given().header("Authorization", AuthrztionValue).header("X-App-Client-Id", XappClintIDvalue)
.contentType("application/vnd.api+json").body(myJson).with().when().post(dataPostUrl).then()
.assertThat().statusCode(200)
.body(containsString("Q1"))
.body(containsString("M8"))
.body(containsString("Annual"))
.body(containsString("2015"))
.extract().response();
Assert.assertFalse(res.asString().contains("isError"));
Assert.assertFalse(res.asString().contains("isMissing"));
Assert.assertFalse(res.asString().contains("isRestricted"));
}
@Test
public void BMI_Period_Monthly_quarterly_Annual_fisc2755() throws IOException{
URL file = Resources.getResource("bmi_Period_monthly_quarterly_annual.json");
String myJson = Resources.toString(file, Charsets.UTF_8);
//System.out.println(myJson);
Response res = given().header("Authorization", AuthrztionValue).header("X-App-Client-Id", XappClintIDvalue)
.contentType("application/vnd.api+json").body(myJson).with().when().post(dataPostUrl).then()
.assertThat().statusCode(200)
.body(containsString("Annual"))
.body(containsString("M10"))
.body(containsString("Q4"))
.body(containsString("2007"))
.extract().response();
Assert.assertFalse(res.asString().contains("isError"));
Assert.assertFalse(res.asString().contains("isMissing"));
Assert.assertFalse(res.asString().contains("isRestricted"));
}
@Test(enabled=false)
public void Fisc_2755_BMI_DatesPeriod_Monthly_quarterly_Annual() throws IOException{
URL file = Resources.getResource("bmi_datesPeriods_mnthly_QurtlyRange.json");
String myJson = Resources.toString(file, Charsets.UTF_8);
//System.out.println(myJson);
Response res = given().header("Authorization", AuthrztionValue).header("X-App-Client-Id", XappClintIDvalue)
.contentType("application/vnd.api+json").body(myJson).with().when().post(dataPostUrl).then()
.assertThat().statusCode(200)
.body(containsString("M9"))
.body(containsString("M10"))
.body(containsString("M11"))
.body(containsString("M12"))
.body(containsString("Q1"))
.body(containsString("Q2"))
.body(containsString("Q3"))
.body(containsString("Q4"))
.body(containsString("2004"))
.body(containsString("2015"))
.extract().response();
Assert.assertFalse(res.asString().contains("isError"));
Assert.assertFalse(res.asString().contains("isMissing"));
Assert.assertFalse(res.asString().contains("isRestricted"));
}
}
<file_sep>/pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.fitchsolutions.restassured</groupId>
<artifactId>restassuredtest</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>APItest</name>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<docker.image.prefix>fitch</docker.image.prefix>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<sonar.exclusions>**/MetadataApplication.java,**/config/*</sonar.exclusions>
<suiteXmlFile>src/main/resources/testng.xml</suiteXmlFile>
</properties>
<dependencies>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.8.8</version>
</dependency>
<dependency>
<groupId>com.jayway.restassured</groupId>
<artifactId>rest-assured</artifactId>
<version>2.4.1</version>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-all</artifactId>
<version>1.3</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-chrome-driver</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>json-path</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>pl.pragmatists</groupId>
<artifactId>JUnitParams</artifactId>
<version>1.0.4</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>19.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.10-FINAL</version>
</dependency>
<dependency>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-site-plugin</artifactId>
<version>3.5.1</version>
<type>maven-plugin</type>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.10-FINAL</version>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.2.2</version>
</dependency>
<dependency>
<groupId>org.codehaus.mojo</groupId>
<artifactId>xml-maven-plugin</artifactId>
<version>1.0.1</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.2.12</version>
</dependency>
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>com.lazerycode.jmeter</groupId>
<artifactId>jmeter-maven-plugin</artifactId>
<version>2.0.3</version>
<executions>
<execution>
<id>jmeter-tests</id>
<phase>verify</phase>
<goals>
<goal>jmeter</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>2.6</version>
<executions>
<execution>
<phase>test</phase>
<goals>
<goal>resources</goal>
<goal>testResources</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-project-info-reports-plugin</artifactId>
<version>2.7</version>
<configuration>
<dependencyLocationsEnabled>false</dependencyLocationsEnabled>
</configuration>
</plugin>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>2.5</version>
<configuration>
<filesets>
<fileset>
<directory>src/main/generated-groovy-stubs</directory>
</fileset>
</filesets>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<compilerVersion>1.8</compilerVersion>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.19.1</version>
<configuration>
<useSystemClassLoader>false</useSystemClassLoader>
<systemProperties>
<property>
<name>env</name>
<value>${env}</value>
</property>
</systemProperties>
<systemPropertyVariables>
<environment>${env.USER}</environment>
</systemPropertyVariables>
<suiteXmlFiles>
<suiteXmlFile>${suiteXmlFile}</suiteXmlFile>
</suiteXmlFiles>
</configuration>
</plugin>
</plugins>
</build>
<reporting>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jxr-plugin</artifactId>
<version>2.3</version>
</plugin>
</plugins>
</reporting>
<profiles>
<profile>
<id>integration-test</id>
<build>
<plugins>
<plugin>
<artifactId>maven-failsafe-plugin</artifactId>
<version>2.19.1</version>
<configuration>
<includes>
<include>**/*.class</include>
</includes>
</configuration>
<executions>
<execution>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>pl.project13.maven</groupId>
<artifactId>git-commit-id-plugin</artifactId>
</plugin>
</plugins>
</build>
</profile>
</profiles>
</project>
|
e2d4d41545a36ded625e454ce459acb995f19e10
|
[
"Java",
"Maven POM"
] | 2
|
Java
|
ZainAahianZaman/API-regression
|
9fb441afa36a3de29a664d6a146d995bd8d12d6a
|
f9aff21e61f9949faf8002ffa2b0a97261028786
|
refs/heads/master
|
<repo_name>opturo/liquidReporting<file_sep>/js/unionFile.js
/**
* Created by rocco on 2/6/2019.
* This will handle the union files for SAYS.
*/
var odinLite_unionFiles = {
/* Variables */
unionFiles: {},
/**
* getUnionWindow
* This will open the union files window.
*/
getUnionWindow: function () {
kendo.ui.progress($("body"), true);//Wait Message
//Get the window template
$.get("./html/unionFilesWindow.html", function (unionWindowTemplate) {
$('#odinLite_unionFilesWindow').remove();
$('body').append(unionWindowTemplate);
//Make the window.
var unionFilesWindow = $('#odinLite_unionFilesWindow').kendoWindow({
title: "Union Files",
draggable: false,
resizable: false,
width: "310px",
height: "290px",
modal: true,
close: true,
animation: false,
actions: [
"Minimize",
"Close"
],
close: function () {
unionFilesWindow = null;
$('#odinLite_unionFilesWindow').remove();
}
}).data("kendoWindow");
unionFilesWindow.center();
//Setup the union list
var dataSource = [];
$.each(odinLite_unionFiles.unionFiles,function(n,o){
dataSource.push({
text: n,
value: n
});
});
//Setup the Column List
var listbox = $("#unionFilesList").kendoListBox({
dataTextField: "text",
dataValueField: "text",
dataSource: dataSource
}).data('kendoListBox');
$('.unionFiles_deleteFile').click(function(){
var index = listbox.select().index();
var dataItem = listbox.dataSource.view()[index];
delete odinLite_unionFiles.unionFiles[dataItem.value];
listbox.dataSource.remove(dataItem);
odinLite_fileFormat.updateFilePreview();
});
//Shut off the wait
kendo.ui.progress($("body"), false);//Wait Message
});//End Template fetch
},
/**
* getUnionWindow
* This will open the union files window.
*/
getFileFormatWindow: function (data) {
kendo.ui.progress($("body"), true);//Wait Message
//Get the window template
$.get("./html/unionFileFormatWindow.html", function (unionWindowTemplate) {
$('#odinLite_unionFileFormatWindow').remove();
$('body').append(unionWindowTemplate);
//Make the window.
var unionFilesWindow = $('#odinLite_unionFileFormatWindow').kendoWindow({
title: "Union File Format",
draggable: false,
resizable: false,
width: "90%",
height: "90%",
modal: true,
close: true,
animation: false,
actions: [
"Close"
],
close: function () {
unionFilesWindow = null;
$('#odinLite_unionFileFormatWindow').remove();
}
}).data("kendoWindow");
unionFilesWindow.center();
//Process the upload info
var form = $('#odinLite_unionFileFormatWindow').find('form')[0];
var uploadInfo = new UploadInfo(form,data);
uploadInfo.initUI();
$('#odinLite_unionFileFormatWindow').data("uploadInfo",uploadInfo);
//Shut off the wait
kendo.ui.progress($("body"), false);//Wait Message
});//End Template fetch
},
/**
* showUploadFiles
* This will take you back to file upload
*/
showUnionUpload: function(){
var win = $('#odinLite_unionFilesWindow').data('kendoWindow');
if(!via.undef(win)){
win.close();
}
via.kendoAlert("Union File","On the next screen import the files you wish to union to the main data tables.",function(){
odinLite_fileFormat.isUnionFile=true;
odinLite_fileFormat.hideFileFormat();
odinLite_uploadFiles.init(true);
});
},
/**
* acceptUnionFileFormat
* This will accept the formatting for the union file.
*/
acceptUnionFileFormat: function(){
var uploadInfo = $('#odinLite_unionFileFormatWindow').data("uploadInfo");
$('#odinLite_unionFileFormatWindow').data('kendoWindow').close();
uploadInfo.formattingOptions = uploadInfo.getFormattingOptions();
odinLite_unionFiles.getRowHeaderWindow(uploadInfo);
},
/**
* getRowHeaderWindow
* This will open the row header chooser window.
*/
getRowHeaderWindow: function (uploadInfo) {
kendo.ui.progress($("body"), true);//Wait Message
//Get the window template
$.get("./html/unionRowHeaderWindow.html", function (unionWindowTemplate) {
$('#odinLite_unionRowHeaderWindow').remove();
$('body').append(unionWindowTemplate);
//Make the window.
var unionFilesWindow = $('#odinLite_unionRowHeaderWindow').kendoWindow({
title: "Choose Row Headers",
draggable: false,
resizable: false,
width: "830px",
height: "465px",
modal: true,
close: true,
animation: false,
actions: [
"Maximize",
"Close"
],
close: function () {
unionFilesWindow = null;
$('#odinLite_unionRowHeaderWindow').remove();
}
}).data("kendoWindow");
unionFilesWindow.center();
$('#odinLite_unionRowHeaderWindow').data("uploadInfo",uploadInfo);
//Row Headers
var headers = [];
var headerArr = (!via.undef(odinLite_fileFormat.unionHeaders))?odinLite_fileFormat.unionHeaders:odinLite_fileFormat.originalHeaders;
for(var i=0;i<headerArr.length;i++){
var col = headerArr[i];
headers.push({ text: col, value: col });
}
$("#originalRowHeaders_unselected").kendoListBox({
dataSource: headers,
draggable: true,
connectWith: "originalRowHeaders_selected",
dropSources: ["originalRowHeaders_selected"],
dataTextField: "text",
dataValueField: "value",
remove: function (e) {
//setDiscontinued(e, false);
},
add: function (e) {
//setDiscontinued(e, true);
}
});
$("#originalRowHeaders_selected").kendoListBox({
draggable: true,
connectWith: "originalRowHeaders_unselected",
dropSources: ["originalRowHeaders_unselected"],
dataTextField: "text",
dataValueField: "text"
});
//Row Headers - union
$("#unionRowHeaders_unselected").kendoListBox({
dataSource: uploadInfo.getColumnHeaderObject(),
draggable: true,
connectWith: "unionRowHeaders_selected",
dropSources: ["unionRowHeaders_selected"],
dataTextField: "text",
dataValueField: "text",
remove: function (e) {
//setDiscontinued(e, false);
},
add: function (e) {
//setDiscontinued(e, true);
}
});
$("#unionRowHeaders_selected").kendoListBox({
draggable: true,
connectWith: "unionRowHeaders_unselected",
dropSources: ["unionRowHeaders_unselected"],
dataTextField: "text",
dataValueField: "text"
});
//Shut off the wait
kendo.ui.progress($("body"), false);//Wait Message
});//End Template fetch
},
/**
* completeUnion
* This will finish the union.
*/
completeUnion: function(){
var uploadInfo = $('#odinLite_unionRowHeaderWindow').data("uploadInfo");
//Original Row Headers
var originalSelected = $("#originalRowHeaders_selected").data('kendoListBox');
var originalRowHeaderArr = originalSelected.dataItems().map(function(o){
return o.value;
});
//Union Row Headers
var unionSelected = $("#unionRowHeaders_selected").data('kendoListBox');
var unionRowHeaderArr = unionSelected.dataItems().map(function(o){
return o.value;
});
if(via.undef(originalRowHeaderArr) || originalRowHeaderArr.length < 1){
via.kendoAlert("Select Row Headers","Select at least one row header for the original file.");
return;
}
if(via.undef(unionRowHeaderArr) || unionRowHeaderArr.length < 1){
via.kendoAlert("Select Row Headers","Select at least one row header for the union file.")
return;
}
var innerJoin = $('#odinLite_unionRowHeaderWindow').find('.innerJoin').prop("checked");
var overrideValue = $('#odinLite_unionRowHeaderWindow').find('.overrideValue').prop("checked");
//Set the row headers and accept the union
uploadInfo.setRowHeaders(unionRowHeaderArr,originalRowHeaderArr,innerJoin,overrideValue);
var fileNames = uploadInfo.data.localFiles.join(", ");
odinLite_unionFiles.unionFiles[fileNames] = uploadInfo;
//Close the window.
$('#odinLite_unionRowHeaderWindow').data("kendoWindow").close();
//Perform the union.
odinLite_fileFormat.updateFilePreview();
},
/**
* getUnionData
* This will gather the data the server needs about the union files.
*/
getUnionData: function(){
var unionData = [];
if(!via.undef(odinLite_unionFiles.unionFiles)){
$.each(odinLite_unionFiles.unionFiles,function(n,o){
var uploadInfo = {};
uploadInfo.unionRowHeaderArr = o.unionRowHeaderArr;
uploadInfo.originalRowHeaderArr = o.originalRowHeaderArr;
uploadInfo.innerJoin = o.innerJoin;
uploadInfo.overrideValue = o.overrideValue;
uploadInfo.type = o.data.type;
uploadInfo = $.extend(uploadInfo,o.formattingOptions);
uploadInfo.files = o.data.files;
uploadInfo.localFiles = o.data.localFiles;
uploadInfo.isMultiSheet = o.isMultiSheet;
uploadInfo.sheetNames = o.sheetNames;
uploadInfo.entityDir = odinLite_modelCache.currentEntity.entityDir;
uploadInfo.modelId = odinLite_modelCache.currentModel.value;
unionData.push(uploadInfo);
});
}
return unionData;
}
};<file_sep>/js/uploadFiles.js
/**
* Created by rocco on 3/21/2018.
* This is the upload files js file for the ODIN Lite application.
* This will handle everything to do with uploading and parsing the uploaded files.
*/
var odinLite_uploadFiles = {
/* Variables */
hasBeenLoaded: false,//Whether this has been loaded before.
//Platform Settings
fileExtension: null,
fileSavedReport: null,
initialValues: null, //This holds the initial guessed values for fileFormat in case it fails.
//Max file Settings
maxSingleFile: null,
maxTotalFiles: null,
/**
* init
* This will initialize ODIN Lite Upload Files and set it up
*/
init: function (isUnionFile) {
if(!via.undef(isUnionFile) && isUnionFile===true) {
$('.upload_unionFileLabel').show();
}else{
$('.upload_unionFileLabel').hide();
odinLite_fileFormat.isUnionFile = false;
}
kendo.ui.progress($("body"), true);//Wait Message
//Make the call to get the settings for the platform
$.post(odin.SERVLET_PATH,
{
action: 'odinLite.uploadFiles.getPlatformSpecSettings',
modelId: odinLite_modelCache.currentModel.value,
platform: odinLite_modelCache.currentPlatform.platform,
uploadSpec: odinLite_modelCache.currentPlatform.specification
},
function (data) {
kendo.ui.progress($("body"), false);//Wait Message off
if (!via.undef(data, true) && data.success === false) {
via.debug("Failure getting Platform Settings:", data.message);
via.alert("Platform Settings Failure", data.message);
} else {
via.debug("Successful getting Platform Settings:", data);
//Max Settings
odinLite_uploadFiles.maxSingleFile = via.getReadableFileSizeString(data.maxSingleFile);
odinLite_uploadFiles.maxTotalFiles = via.getReadableFileSizeString(data.maxTotalFiles);
//Extension - don't worry about if a union file
if(odinLite_fileFormat.isUnionFile === false) {
if (!via.undef(data.fileSelectionCriteria, true)) {
var idx = data.fileSelectionCriteria.lastIndexOf(".");
data.fileSelectionCriteria = data.fileSelectionCriteria.substring(idx);
odinLite_uploadFiles.fileExtension = data.fileSelectionCriteria;
} else {
odinLite_uploadFiles.fileExtension = null;
}
//Save Report
if (!via.undef(data.fileFormatReportSetting)) {
odinLite_uploadFiles.fileSavedReport = data.fileFormatReportSetting;
} else {
odinLite_uploadFiles.fileSavedReport = null;
}
}
//init ui and reset if it was accessed before.
odinLite_uploadFiles.initUI();
//Cleanup the staging area if it needs it
odinLite_uploadFiles.deleteStagingAreaFiles();
//Show the panels.
$("#uploadFilesPanel").show();
$("#uploadPanel").show();
//Update app and model
$(".applicationAndModelName").html("(<strong>Application:</strong>" + odinLite_modelCache.currentModel.application + "; <strong>Model:</strong>" + odinLite_modelCache.currentModel.text + ")");
odinLite_uploadFiles.hasBeenLoaded = true;//Set the loaded variable after first load.
kendo.ui.progress($("body"), false);//Wait Message
}
},
'json');
},
/**
* initUI
* This will return the upload files section to its original state and setup the events if need be
*/
initUI: function () {
//Hide Panels
$("#uploadProgressPanel").hide();
$("#uploadFilesPanel").hide();
//Hide Template
if(odinLite_modelCache.currentPlatform.platform !== 'Custom'){
$('.templateCheckContainer').hide();
}else{
$('.templateCheckContainer').show();
}
//Setup the events if they have not been setup
if (!odinLite_uploadFiles.hasBeenLoaded) {
$("#fileUpload_form").submit(function (e) {
e.preventDefault();
var formData = new FormData($(this)[0]);
odinLite_uploadFiles.uploadFilesToStagingArea(formData);
});
//Initializa the tree
$(".importTypesTree").empty();
//Datasource for the tree
var importDataSource = new kendo.data.HierarchicalDataSource({
data: [
{
text: "Files",
expanded: true,
items: [
{ text: "Local Computer",value: "Local Computer" },
{ text: "FTP Site",value: "FTP Site" }
]
},
{
text: "Database",
expanded: true,
items: [
{ text: "SQL Server",value: "SQL Server" },
{ text: "MySQL",value: "MySQL" },
{ text: "Oracle",value: "Oracle" },
{ text: "DB2",value: "DB2" }
]
},
{
text: "Web Service",
expanded: true,
items: [
{ text: "Text",value: "webService Text" }
]
}
]
});
//Make the tree
var treeview = $(".importTypesTree").kendoTreeView({
dataSource: importDataSource,
select: function(e){
var dataItem = this.dataItem(e.node);
if(dataItem.hasChildren === true){
//$(".k-state-selected")
//.removeClass("k-state-selected");
return;
}
//Remove Selected Class
//$.each($('.importTypesTree li'), function() {
// var node = treeview.dataItem($(this));
// $(this).find('.k-in').removeClass('importSelected');
//});
//$(e.node).find('.k-in').addClass('importSelected');
switch(dataItem.value) {
case 'Local Computer':
$('#uploadFiles_otherSources').empty();
$('#uploadFiles_otherSources').hide();
$('#uploadFiles_localComputer').fadeIn();
break;
case 'FTP Site':
odinLite_uploadFiles.createFtpSettingsWindow();
break;
case 'SQL Server':
odinLite_uploadFiles.createDatabaseSettingsWindow("sqlserver",'SQL Server',31);
break;
case 'MySQL':
odinLite_uploadFiles.createDatabaseSettingsWindow("mysql",'MySQL',32);
break;
case 'Oracle':
odinLite_uploadFiles.createDatabaseSettingsWindow("oracle","Oracle",33);
break;
case 'DB2':
odinLite_uploadFiles.createDatabaseSettingsWindow("db2","DB2",34);
break;
case 'webService Text':
odinLite_uploadFiles.createWebServiceSettingsWindow();
break;
}
}
}).data('kendoTreeView');
//Style the tree
$.each($('.importTypesTree li'), function() {
var node = treeview.dataItem($(this));
if (node.hasChildren === true) {
//$(this).find('.k-in').addClass('importFolder');
$(this).find('.k-in').addClass('btn');
$(this).find('.k-in').addClass('btn-info');
} else {
//$(this).find('.k-in').addClass('importLeaf');
//$(this).find('.k-in').removeClass('btn-info');
//$(this).find('.k-in').addClass('btn-success');
$(this).find('.k-in').removeClass('btn-info');
$(this).find('.k-in').addClass('importLeaf');
if(node.text === 'Local Computer'){
//$(this).find('.k-in').addClass('importSelected');
$(this).find('.k-in').addClass('k-state-selected');
}
}
});
//FTP Transfer Button
$('#ftpDownloadButton').show();
$('#ftpDownloadButton').off();
$('#ftpDownloadButton').click(function () {
odinLite_uploadFiles.createFtpSettingsWindow();
});
//DB load button
$('#dbDownloadButton').show();
$('#dbDownloadButton').off();
$('#dbDownloadButton').click(function () {
odinLite_uploadFiles.createDatabaseSettingsWindow();
});
//Web Service load button
$('#webServiceDownloadButton').show();
$('#webServiceDownloadButton').off();
$('#webServiceDownloadButton').click(function () {
odinLite_uploadFiles.createWebServiceSettingsWindow();
});
//Style the upload box
var uploadFilesSettings = {};
if (!via.undef(odinLite_uploadFiles.fileExtension, true)) {
uploadFilesSettings.localization = {
select: "Select your " + odinLite_uploadFiles.fileExtension + " files..."
};
/*
uploadFilesSettings.validation = {
allowedExtensions: [odinLite_uploadFiles.fileExtension]
};
*/
} else {
uploadFilesSettings.localization = {
select: "Select your files..."
};
}
$("#uploadFiles").kendoUpload(uploadFilesSettings);
//Setup the upload progress bar
$('#uploadProgressbar').kendoProgressBar({
animation: {
duration: 100
},
min: 0,
max: 100,
//type: "percent",
change: function (e) {
$('.k-progress-status-wrap').css("text-align", "center");
this.progressStatus.text(e.value + "% Complete");
if (e.value < 33) {
this.progressWrapper.css({
"background-color": "#EE9F05",
"border-color": "#EE9F05",
"text-align": "center"
});
} else if (e.value < 66) {
this.progressWrapper.css({
"background-color": "#428bca",
"border-color": "#428bca",
"text-align": "center"
});
} else {
this.progressWrapper.css({
"background-color": "#8EBC00",
"border-color": "#8EBC00",
"text-align": "center"
});
}
}
});
$('#uploadProgressbar .k-progress-status-wrap').css("text-align", "center");//Center text
$("#uploadProgressbar").data("kendoProgressBar").value(0);
$("#uploadProgressbar").data("kendoProgressBar").progressStatus.text("0% Complete");
} else {
if (!via.undef(odinLite_uploadFiles.fileExtension, true)) {
$(".k-upload-button span").html("Select your " + odinLite_uploadFiles.fileExtension + " files...");
} else {
$(".k-upload-button span").html("Select your files...");
}
//Reset Progress Bar
if (!via.undef($("#uploadProgressbar").data("kendoProgressBar"))) {
try {
$("#uploadProgressbar").data("kendoProgressBar").value(0);
} catch (e) {
}
}
//Clear Files
if (!via.undef($("#uploadFiles").data("kendoUpload"))) {
try {
$("#uploadFiles").data("kendoUpload").clearAllFiles();
} catch (e) {
}
}
//Reset selection
var treeview = $(".importTypesTree").data('kendoTreeView');
var node = treeview.findByText("Local Computer");
treeview.select(node);
treeview.trigger( 'select', {node: node} );
}
},
uploadFilesToStagingArea: function (formData) {
//Check to make sure there are files
var upload = $("#uploadFiles").data("kendoUpload"),
files = upload.getFiles();
via.debug("Uploading these files:", files);
if (via.undef(files, true)) {
via.alert("<i class=\"fa fa-file-o\"></i> Select a file", "No files were selected for upload.");
return;
}
odinLite_uploadFiles.confirmPlatformFiles(function(){
checkFiles(function () {
//Display warning message if needed.
if (files.length > 1) {
via.confirm("<i class=\"fa fa-files-o\"></i> Multiple Files", "You have chosen to upload multiple files. Please confirm that each file you are uploading has the same format.", function () {
uploadFiles();
});
} else {
uploadFiles();
}
})
});
function checkFiles(callbackFn) {
var fileNames = JSON.stringify(files.map(function (o) {
return o.name;
}));
var fileSizes = JSON.stringify(files.map(function (o) {
return o.size;
}));
$.post(odin.SERVLET_PATH,
{
action: 'odinLite.uploadFiles.preUploadFileCheck',
overrideUser: odinLite.OVERRIDE_USER,
modelId: odinLite_modelCache.currentModel.value,
platform: odinLite_modelCache.currentPlatform.platform,
uploadSpec: odinLite_modelCache.currentPlatform.specification,
fileNames: fileNames,
fileSizes: fileSizes
},
function (data, status) {
if (!via.undef(data, true) && data.success === false) {
via.debug("Check Files Error:", data.message);
via.kendoAlert("Check Files Error", data.message);
} else {//Success - File Preview
via.debug("Check Files Success:", data.message);
if (!via.undef(data.validatePlatformErrorString, true)) {
via.kendoConfirm("File Check", data.validatePlatformErrorString, callbackFn)
} else {
callbackFn();
}
}
},
'json');
}
function uploadFiles() {
//Append the srcApp
formData.append('srcApp', odinLite.APP_NAME);
//Append the files
formData.append('fileNames', JSON.stringify(files.map(function (o) {
return o.name;
})));
//Get the template check box.
var isTemplateFile = $('#uploadFiles_templateCheck').is(':checked');
formData.append('isTemplateFile', isTemplateFile);
formData.append('modelId', odinLite_modelCache.currentModel.value);
formData.append('entityDir', odinLite_modelCache.currentEntity.entityDir);
formData.append('overrideUser', odinLite.OVERRIDE_USER);
//Show the progress bar
$('#uploadPanel').hide();
$('#cancelUploadButton').prop("disabled", false);
$('#uploadProgressPanel').fadeIn();
var pb = $("#uploadProgressbar").data("kendoProgressBar");
pb.value(0);
//Make the call to the upload.
var xhr = $.ajax({
url: odin.SERVLET_PATH,
type: 'POST',
data: formData,
async: true,
cache: false,
contentType: false,
processData: false,
dataType: 'json',
success: function (data) {
if (!via.undef(data, true) && data.success === false) {
via.debug("File Upload Failure:", data.message);
via.alert("File Upload Error", data.message, function () {
odinLite_uploadFiles.init();
});
} else {//Success - Files Uploaded
via.debug("Files Uploaded Successfully:", data);
$('#cancelUploadButton').prop("disabled", true);
$('#uploadProgressPanel').fadeOut(function () {
//Move onto the import wizard.
data.isTemplateFile = isTemplateFile;
//Import Data and move to file format
odinLite_uploadFiles.importData(data);
});
}
},
error: function (jqXHR, textStatus, errorThrown) {
via.debug("Error", jqXHR, textStatus, errorThrown);
via.alert("Failure", "Files failed to upload.", function () {
odinLite_uploadFiles.init();
});
},
xhr: function () {
var xhr = new window.XMLHttpRequest();
//Upload progress
xhr.upload.addEventListener("progress", function (evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
percentComplete = Math.round((percentComplete * 100));
via.debug("Upload % Complete:", percentComplete);
//Update the progress bar
pb.value(percentComplete);
}
}, false);
/*
//Download progress
xhr.addEventListener("progress", function(evt){
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
//Do something with download progress
console.log('dl',percentComplete);
}
}, false);
*/
return xhr;
}
});
//Set the event for cancelling the upload.
$('#cancelUploadButton').one("click", function () {
$('#cancelUploadButton').prop("disabled", true);
xhr.abort();
via.alert("Upload Canceled", "The file upload has been canceled.", function () {
odinLite_uploadFiles.init();
});
});
}
},
/**
* confirmPlatformFiles
* Creates a qindow displaying the platfoirm spec.
*/
confirmPlatformFiles: function(callbackFn){
if(odinLite_fileFormat.isUnionFile === true && !via.undef(callbackFn)){
callbackFn();
}else if(!via.undef(odinLite_modelCache.currentPlatform.helpLink)){
$("#kendoDialog").remove();//Remove if it is already there.
kendo.ui.progress($("body"), true);
$.post(odin.SERVLET_PATH,
{
action: 'admin.getHtmlPageContents',
url: odinLite_modelCache.currentPlatform.helpLink
},
function(data, status){
kendo.ui.progress($("body"), false);//wait off
if(!via.undef(data,true) && data.success === false){
via.debug("Help Link Error:", data.message);
via.alert("Help Link Error",data.message);
}else{//Success - File Preview
via.debug("Help Link Successful:", data);
if(!via.undef(data.html)){
$('body').append(` <div id="kendoDialog">
Please confirm that the upload ${odinLite_modelCache.currentPlatform.platform} data/files match the criteria below?
<button class="btn btn-danger pull-right platformDeny" style="margin:0 0 10px 10px;">No</button>
<button class="btn btn-success pull-right platformConfirm">Yes</button>
<hr style="clear:both;"/>
${data.html}
</div>`);
var dialog = $("#kendoDialog").kendoWindow({
width: "75%",
height: "75%",
title: odinLite_modelCache.currentPlatform.specification,
actions: ["Maximize", "Close"],
modal: true,
close: function () {
$("#kendoDialog").remove();
}
}).data("kendoWindow");
dialog.center();
$('.platformDeny').click(function(){
dialog.close();
});
$('.platformConfirm').click(function(){
dialog.close();
if(!via.undef(callbackFn)){
callbackFn(data);
}
});
}
}
},
'json');
}else if(!via.undef(callbackFn)){
callbackFn();
}
},
/**
* createWebServiceSettingsWindow
* Creates Web Service window for importing data.
*/
createWebServiceSettingsWindow: function () {
$('#uploadFiles_localComputer').hide();
$('#uploadFiles_otherSources').empty();
$('#uploadFiles_otherSources').show();
//Get the window template
$.get("./html/webServiceSettingsWindow.html", function (windowTemplate) {
$('#odinLite_webServiceSettingsWindow').remove();
$('#uploadFiles_otherSources').html(windowTemplate);
//Button Events
$(".odinLite_webServiceTransfer_connect").on("click", function () {
var url = $('#odinLite_webService_url').val();
if(via.undef(url,true)){
via.kendoAlert("Missing URL", "Please specify a url.");
return;
}
kendo.ui.progress($('body'), true);//Wait Message
$.post(odin.SERVLET_PATH,
{
action: 'odinLite.uploadFiles.webServiceImport',
overrideUser: odinLite.OVERRIDE_USER,
url: url
},
function (data, status) {
kendo.ui.progress($('body'), false);//Wait Message
if (!via.undef(data, true) && data.success === false) {
via.kendoAlert("Web Service Error",data.message);
via.debug("Web Service Error:", data.message);
} else {//Success - FTP
via.debug("Web Service success:", data.message);
//Import Data and move to file format
odinLite_uploadFiles.confirmPlatformFiles(function(){
odinLite_uploadFiles.importData(data);
});
}
},
'json');
});
});
/*
via.kendoPrompt("Web Service Import","Enter the URL of the web service to import data from.",function(url){
kendo.ui.progress($('body'), true);//Wait Message
$.post(odin.SERVLET_PATH,
{
action: 'odinLite.uploadFiles.webServiceImport',
overrideUser: odinLite.OVERRIDE_USER,
url: url
},
function (data, status) {
kendo.ui.progress($('body'), false);//Wait Message
if (!via.undef(data, true) && data.success === false) {
via.kendoAlert("Web Service Error",data.message);
via.debug("Web Service Error:", data.message);
} else {//Success - FTP
via.debug("Web Service success:", data.message);
odinLite_uploadFiles.initialValues = JSON.parse(JSON.stringify(data));//Store the initial values for possible use later if loading a saved report fails.
odinLite_fileFormat.init(data);
}
},
'json');
},function(){
},500);
*/
},
/**
* createDatabaseSettingsWindow
* Creates Database window for database settings.
* @param data
*/
createDatabaseSettingsWindow: function (dbType,dbName,saveId) {
//Get the window template
$.get("./html/dbSettingsWindow.html", function (windowTemplate) {
$('#odinLite_dbSettingsWindow').remove();
windowTemplate = (windowTemplate + "").replace('loadDatabaseSettingsWindow()','loadDatabaseSettingsWindow('+saveId+')');
windowTemplate = (windowTemplate + "").replace('saveDatabaseSettingsWindow()','saveDatabaseSettingsWindow('+saveId+')');
$('#uploadFiles_otherSources').empty();
$('#uploadFiles_otherSources').html(windowTemplate);
$('.import_dbName').html(dbName);
$('#uploadFiles_localComputer').hide();
$('#uploadFiles_otherSources').fadeIn();
/*
//Make the window.
var dbSettingsWindow = $('#odinLite_dbSettingsWindow').kendoWindow({
title: "Database Settings",
draggable: false,
resizable: false,
width: "450px",
height: "410px",
modal: true,
close: false,
actions: [
"Close"
],
close: function () {
dbSettingsWindow = null;
$('#odinLite_dbSettingsWindow').remove();
}
}).data("kendoWindow");
dbSettingsWindow.center();
*/
//Style the combo
//$("#odinLite_database_type").kendoDropDownList();
$("#odinLite_database_type").val(dbType);
//Button Events
$(".odinLite_dbTransfer_connect").on("click", function () {
testDatabaseConnection(dbType,dbName,saveId);
});
});
/* Functions */
function testDatabaseConnection(dbType,dbName,saveId){
kendo.ui.progress($('#odinLite_dbSettingsWindow'), true);//Wait Message
//Get the values for ftp connection
var formData = new FormData($('#odinLite_dbTransferWindow_form')[0]);
var serverVars = {};
formData.forEach(function(value, key){
serverVars[key] = value;
});
$.post(odin.SERVLET_PATH,
$.extend(serverVars,{
action: 'odinLite.uploadFiles.dbTransferTesting',
overrideUser: odinLite.OVERRIDE_USER
}),
function (data, status) {
kendo.ui.progress($('#odinLite_dbSettingsWindow'), false);//Wait Message
if (!via.undef(data, true) && data.success === false) {
via.kendoAlert("Database Connection Error",data.message);
via.debug("Database Connection Error:", data.message);
} else {//Success - FTP
via.debug("Database Connection success:", data.message);
odinLite_uploadFiles.createDatabaseImportWindow(dbType,dbName,serverVars,saveId);
}
},
'json');
}
},
/**
* createDatabaseTransferWindow
* Creates database window for importing data.
* @param data
*/
createDatabaseImportWindow: function (dbType,dbName,serverVars,saveId) {
//Get the window template
$.get("./html/dbTransferWindow.html", function (ftpWindowTemplate) {
$('#odinLite_dbTransferWindow').remove();
$('#uploadFiles_otherSources').empty();
saveId = saveId + 10;
ftpWindowTemplate = (ftpWindowTemplate + "").replace('loadDatabaseSQLWindow()','loadDatabaseSQLWindow('+saveId+')');
ftpWindowTemplate = (ftpWindowTemplate + "").replace('saveDatabaseSQLWindow()','saveDatabaseSQLWindow('+saveId+')');
$('#uploadFiles_otherSources').html(ftpWindowTemplate);
$('.import_dbName').html(dbName);
/*
//Make the window.
var dbWindow = $('#odinLite_dbTransferWindow').kendoWindow({
title: "Database Data Load",
draggable: false,
resizable: false,
width: "850px",
height: "590px",
modal: true,
close: false,
actions: [
"Maximize",
"Close"
],
close: function () {
dbWindow = null;
$('#odinLite_dbTransferWindow').remove();
}
}).data("kendoWindow");
dbWindow.center();
settingsWindow.close();
*/
//Style the code editor
var editor = CodeMirror.fromTextArea(document.getElementById("odinLite_dbTransfer_sqlArea"), {
mode: "text/x-sql",
indentWithTabs: true,
smartIndent: true,
lineWrapping: true,
lineNumbers: true,
matchBrackets : true,
autofocus: true,
extraKeys: {"Ctrl-Space": "autocomplete"}
});
editor.setSize("100%", 200);
// store it
$('#odinLite_dbTransfer_sqlArea').data('CodeMirrorInstance', editor);
//Button Events
$("#odinLite_dbQueryButton").on("click", function () {
runDbQuery(dbType,dbName,serverVars);
});
$("#odinLite_dbImportButton").on("click", function () {
odinLite_uploadFiles.confirmPlatformFiles(function(){
importDbData(dbType,dbName,serverVars);
});
});
/* Functions */
function importDbData(dbType,dbName,serverVars){
var sqlString = $('#odinLite_dbResultGrid').data("gridSql");
if(via.undef(sqlString,true)) {
via.kendoAlert("Data Missing","Please run SQL Query.");
return;
}
kendo.ui.progress($('#odinLite_dbTransferWindow'), true);//Wait Message
$.post(odin.SERVLET_PATH,
$.extend(serverVars, {
action: 'odinLite.uploadFiles.dbTransferImport',
overrideUser: odinLite.OVERRIDE_USER,
query: sqlString
}),
function (data, status) {
kendo.ui.progress($('#odinLite_dbTransferWindow'), false);//Wait Message
if (!via.undef(data, true) && data.success === false) {
via.kendoAlert("Database Connection Error", data.message);
via.debug("Database Import Error:", data.message);
} else {//Success - DB Query
via.debug("Database Import success:", data.message);
//Import Data and move to file format
odinLite_uploadFiles.importData(data);
}
},
'json');
}
function runDbQuery(dbType,dbName,serverVars){
//var sqlString = $('#odinLite_dbTransfer_sqlArea').val();
var sqlString = editor.getValue();
if(via.undef(sqlString,true)) {
via.kendoAlert("SQL Missing","Please enter SQL Query.");
return;
}
$('#odinLite_dbResultGrid').empty();
$('#odinLite_dbResultGrid').data("gridSql",null);
kendo.ui.progress($('#odinLite_dbTransferWindow'), true);//Wait Message
$.post(odin.SERVLET_PATH,
$.extend(serverVars, {
action: 'odinLite.uploadFiles.dbTransferTesting',
overrideUser: odinLite.OVERRIDE_USER,
query: sqlString
}),
function (data, status) {
kendo.ui.progress($('#odinLite_dbTransferWindow'), false);//Wait Message
if (!via.undef(data, true) && data.success === false) {
via.kendoAlert("Database Connection Error", data.message);
via.debug("Database Connection Error:", data.message);
} else {//Success - DB Query
via.debug("Database Connection success:", data.message);
odinTable.createTable("sqlDataTable",data.reportData,"#odinLite_dbResultGrid");
$('#sqlDataTable').data('kendoGrid').setOptions({
groupable:false,
height:'99%'
});
$('#odinLite_dbResultGrid').css("padding","0");
$('#odinLite_dbResultGrid').data("gridSql",sqlString);
}
},
'json');
}
});
},
/**
* saveWebServiceSettingsWindow
* This will save the web service settings sql.
*/
saveWebServiceSettingsWindow: function(){
//var formData = new FormData($('#odinLite_dbTransferWindow_form')[0]);
var saveJson = {};
var urlString = $('#odinLite_webService_url').val();
if(via.undef(urlString,true)){
via.kendoAlert("Missing Value","Specify a URL string to save.");
}
saveJson.url = urlString;
//console.log('saveJson',saveJson);
//Perform the save.
via.saveWindow(odin.ODIN_LITE_APP_ID,5,JSON.stringify(saveJson),function(){
},false);
},
/**
* loadDatabaseSQLWindow
* This will load database settings.
*/
loadWebServiceSettingsWindow: function(saveId){
via.loadWindow(odin.ODIN_LITE_APP_ID,5,function(loadJson){
$('#odinLite_webService_url').val(loadJson.url);
});
},
/**
* loadDatabaseSQLWindow
* This will load database settings.
*/
loadDatabaseSQLWindow: function(saveId){
via.loadWindow(odin.ODIN_LITE_APP_ID,saveId,function(loadJson){
var editor = $('#odinLite_dbTransfer_sqlArea').data('CodeMirrorInstance');
editor.setValue(loadJson.sql);
});
},
/**
* saveDatabaseSQLWindow
* This will save the database sql.
*/
saveDatabaseSQLWindow: function(saveId){
//var formData = new FormData($('#odinLite_dbTransferWindow_form')[0]);
var saveJson = {};
//var sqlString = $('#odinLite_dbTransfer_sqlArea').val();
var editor = $('#odinLite_dbTransfer_sqlArea').data('CodeMirrorInstance');
var sqlString = editor.getValue();
if(via.undef(sqlString,true)){
via.kendoAlert("Missing Value","Specify a SQL string to save.");
}
saveJson.sql = sqlString;
//console.log('saveJson',saveJson);
//Perform the save.
via.saveWindow(odin.ODIN_LITE_APP_ID,saveId,JSON.stringify(saveJson),function(){
},false);
},
/**
* loadDatabaseSettingsWindow
* This will load database settings.
*/
loadDatabaseSettingsWindow: function(saveId){
via.loadWindow(odin.ODIN_LITE_APP_ID,saveId,function(loadJson){
$.each(loadJson,function(key,value){
if(key === 'password'){
value = CryptoJS.AES.decrypt(value, via.ENCRYPT_KEY).toString(CryptoJS.enc.Utf8);
}
//if(key === 'type') {
// $("#odinLite_database_type").data('kendoDropDownList').value(value);
// return;
//}else {
var input = $("#odinLite_dbTransferWindow_form [name='" + key + "']");
if (!via.undef(input) && !via.undef(value, true)) {
$(input).val(value);
}
//}
});
});
},
/**
* saveDatabaseSettingsWindow
* This will save the database settings.
*/
saveDatabaseSettingsWindow: function(saveId){
var formData = new FormData($('#odinLite_dbTransferWindow_form')[0]);
var saveJson = {};
var failedVars = [];
formData.forEach(function(value, key){
saveJson[key] = value;
var input = $("#odinLite_dbTransferWindow_form [name='"+key+"']");
if(!via.undef(input) && !via.undef($(input).attr('required') && $(input).attr('required') === true) && via.undef(value,true)){
failedVars.push(key);
return false;
}
});
if(failedVars.length > 0){
via.kendoAlert("Missing Value","Missing required values: "+failedVars.join(", "));
return;
}
//Encrypt the password
if(!via.undef(saveJson.password,true)) {
saveJson.password = CryptoJS.AES.encrypt(saveJson.password, via.ENCRYPT_KEY).toString();
}
//Perform the save.
via.saveWindow(odin.ODIN_LITE_APP_ID,saveId,JSON.stringify(saveJson),function(){
var win = $('#odinLite_dbTransferWindow').data('kendoWindow');
if(!via.undef(win)) {
win.close();
}
},false);
},
/**
* createFtpSettingsWindow
* Creates ftp window for ftp settings.
* @param data
*/
createFtpSettingsWindow: function () {
//Get the window template
$.get("./html/ftpSettingsWindow.html", function (windowTemplate) {
$('#odinLite_ftpSettingsWindow').remove();
$('#uploadFiles_otherSources').empty();
$('#uploadFiles_otherSources').html(windowTemplate);
$('#uploadFiles_localComputer').hide();
$('#uploadFiles_otherSources').fadeIn();
/*
//Make the window.
var ftpWindow = $('#odinLite_ftpSettingsWindow').kendoWindow({
title: "FTP Settings",
draggable: false,
resizable: false,
width: "450px",
height: "420px",
modal: true,
close: false,
actions: [
"Close"
],
close: function () {
ftpWindow = null;
$('#odinLite_ftpSettingsWindow').remove();
}
}).data("kendoWindow");
ftpWindow.center();
*/
//Style the combo
$("#odinLite_ftpTransfer_type").kendoDropDownList();
//Button Events
$(".odinLite_ftpTransfer_connect").on("click", function () {
odinLite_uploadFiles.createFtpTransferWindow();
});
});
},
/**
* createFtpTransferWindow
* Creates ftp window for transferring files.
* @param data
*/
createFtpTransferWindow: function () {
//Get the values for ftp connection
var formData = new FormData($('#odinLite_ftpTransferWindow_form')[0]);
var serverVars = {};
formData.forEach(function(value, key){
serverVars[key] = value;
});
kendo.ui.progress($('#odinLite_ftpSettingsWindow'), true);//Wait Message
//Get the window template
$.get("./html/ftpTransferWindow.html", function (ftpWindowTemplate) {
kendo.ui.progress($('#odinLite_ftpSettingsWindow'), false);//Wait Message
$('#odinLite_ftpTransferWindow').remove();
$('#uploadFiles_otherSources').html(ftpWindowTemplate);
/*
//Make the window.
var ftpWindow = $('#odinLite_ftpTransferWindow').kendoWindow({
title: "FTP Transfer",
draggable: false,
resizable: false,
width: "850px",
height: "590px",
modal: true,
close: false,
actions: [
"Maximize",
"Close"
],
close: function () {
ftpWindow = null;
$('#odinLite_ftpTransferWindow').remove();
}
}).data("kendoWindow");
ftpWindow.center();
*/
//Call the grid functions
getFTPGrid(serverVars);
getFileManagerGrid();
//Button Events
$('#odinLite_ftpTransfer_directoryField').on('keyup',function(e){
if(e.keyCode === 13){
serverVars.path = $('#odinLite_ftpTransfer_directoryField').val();
getFTPGrid(serverVars);
}
});
//Set the button action
$('#odinLite_ftpFileManager_addButton').click(function(){
addItemToFileManager();
});
$('#odinLite_ftpFileManager_transferButton').click(function(){
odinLite_uploadFiles.confirmPlatformFiles(function(){
transferFtpFiles();
});
});
/* Functions */
//Transfer the ftp files
function transferFtpFiles(){
var fileManagerGrid = $("#odinLite_ftpFileManager").data('kendoGrid');
var gridData = fileManagerGrid.dataSource.data();
if(gridData.length === 0){
via.kendoAlert("FTP Transfer","There are no files in the list.");
return;
}else if(gridData.length > 1){
via.confirm("<i class=\"fa fa-files-o\"></i> Multiple Files", "You have chosen to upload multiple files. Please confirm that each file you are uploading has the same format.", function () {
performFtpTransfer();
});
}else{
performFtpTransfer();
}
}
/*This handles the actual transfer from ftp.*/
function performFtpTransfer(){
var fileManagerGrid = $("#odinLite_ftpFileManager").data('kendoGrid');
var gridData = fileManagerGrid.dataSource.data();
odin.progressBar("FTP Transfer",100,"Transferring " + gridData.length + ((gridData.length>1)?" files.":" file."));
$.post(odin.SERVLET_PATH,
$.extend(serverVars,{
action: 'odinLite.uploadFiles.transferFtpFiles',
overrideUser: odinLite.OVERRIDE_USER,
ftpFiles: JSON.stringify(gridData)
}),
function (data, status) {
odin.progressBar("FTP Transfer",100,null,true);
fileManagerGrid.dataSource.data([]);
if (!via.undef(data, true) && data.success === false) {
via.kendoAlert("FTP Transfer","Error: " + data.message);
via.debug("FTP Transfer Error:", data.message);
} else {//Success - FTP
via.debug("FTP Transfer Success:", data.message);
//Import Data and move to file format
odinLite_uploadFiles.importData(data);
}
},
'json');
}
//Add the item to the file manager grid.
function addItemToFileManager() {
var tree = $("#odinLite_ftpTreeview").data('kendoTreeList');
var selected = tree.select();
for(var i=0;i<selected.length;i++) {
var dataItem = tree.dataItem(selected[i]);
if (dataItem.isFolder === true) {
continue;
}
var fileManagerGrid = $("#odinLite_ftpFileManager").data('kendoGrid');
//Prevent Duplicates
var inGrid = false;
var gridData = fileManagerGrid.dataSource.data();
for (var i = 0; i < gridData.length; i++) {
if (dataItem.path === gridData[i].path) {
via.kendoAlert("FTP Transfer", "\"" + dataItem.name + "\" has already been added to the list.");
inGrid = true;
}
}
//Add to grid
if(!inGrid) {
fileManagerGrid.dataSource.add(dataItem);
}
}
}
//Get the ftp transfer files
function getFileManagerGrid(){
$("#odinLite_ftpFileManager").empty();
$("#odinLite_ftpFileManager").kendoGrid({
dataSource: {
data: [],
schema: {
model: {
fields: {
name: { field: "name"},
fileSize: { field: "fileSize",type: "number"},
lastModified: { field: "lastModified",type: "number"}
}
}
}
},
scrollable: true,
editable: false,
columns: [
{
//template: "<img src='#:imageUrl#'/> " + "#: name #",
template: "<img src='#:imageUrl#'/> " + "#: name #",
field: "name",
expandable: true,
title: "Selected Files",
width: 400
},
{
template: function(dataItem) {
if(via.undef(dataItem.fileSize)){
return "";
}else{
return via.getReadableFileSizeString(dataItem.fileSize);
}
},
field: "fileSize",
title: "Size",
attributes: { style:"text-align:right" },
headerAttributes: { style:"text-align:center" },
width: 150
},
{
template: function(dataItem) {
if(via.undef(dataItem.lastModified)){
return "";
}else{
var d = new Date(dataItem.lastModified)
return kendo.toString(d,"g");
}
},
field: "lastModified",
title: "Last Modified",
headerAttributes: { style:"text-align:center" }
},
{
title: "Delete",
width: "80px",
iconClass: "fa fa-trash",
command: {
text: " ",
iconClass: "fa fa-trash",
click: function(e){
e.preventDefault();
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
this.dataSource.remove(dataItem);
}
}
}
]
});
}
//Get the tree data
function getFTPGrid(serverVars){
$("#odinLite_ftpTreeview").empty();
$('#odinLite_ftpTransfer_directoryField').prop("disabled",true);
var dirStructure = new kendo.data.TreeListDataSource({
transport: {
read: function(options) {
// make JSON request to server
$.ajax({
url: odin.SERVLET_PATH + "?action=odinLite.uploadFiles.getFtpFilesGrid",
data: $.extend(serverVars,{
entityDir:odinLite.ENTITY_DIR,
path:options.data.id
}),
dataType: "json",
success: function(result) {
console.log(result);
$('#odinLite_ftpTransfer_directoryField').val("");
$('#odinLite_ftpTransfer_directoryField').prop("disabled",false);
if(result.success === false){
if(!via.undef(result.message)) {
via.kendoAlert("Error retrieving files",result.message);
}else{
via.kendoAlert("Error retrieving files", "Please check your connection.");
}
}else {
$('#odinLite_ftpTransfer_directoryField').val(result.path==="."?"./":result.path);
// notify the data source that the request succeeded
for(var i in result.childNodes){
if(via.undef(result.childNodes[i].parentId)) {
result.childNodes[i].parentId = null;
}``
if(!via.undef(result.childNodes[i].lastModified) && (result.childNodes[i].lastModified+"").length === 10){
result.childNodes[i].lastModified = result.childNodes[i].lastModified * 1000;
}
}
$("#odinLite_ftpTreeview").data("maxSingleFileSize");
$("#odinLite_ftpTreeview").data("maxTotalFileSize");
options.success(result.childNodes);
}
},
error: function(result) {
$('#odinLite_ftpTransfer_directoryField').val("");
$('#odinLite_ftpTransfer_directoryField').prop("disabled",false);
// notify the data source that the request failed
options.error(result);
}
});
}
},
schema: {
model: {
id: "path",
hasChildren: "hasChildren",
//parentId: "parentId",
fields: {
name: { field: "name"},
fileSize: { field: "fileSize",type: "number"},
lastModified: { field: "lastModified",type: "number"}
}
}
}
});
var grid = $("#odinLite_ftpTreeview").kendoTreeList({
dataSource: dirStructure,
selectable: "multiple, row",
sortable:true,
columns: [
{
//template: "<img src='#:imageUrl#'/> " + "#: name #",
template: "<img src='#:imageUrl#'/> " + "#: name #",
field: "name",
expandable: true,
title: "Name",
width: 400
},
{
template: function(dataItem) {
if(via.undef(dataItem.fileSize)){
return "";
}else{
return via.getReadableFileSizeString(dataItem.fileSize);
}
},
field: "fileSize",
title: "Size",
attributes: { style:"text-align:right" },
headerAttributes: { style:"text-align:center" },
width: 150
},
{
template: function(dataItem) {
if(via.undef(dataItem.lastModified)){
return "";
}else{
var d = new Date(dataItem.lastModified)
return kendo.toString(d,"g");
}
},
field: "lastModified",
title: "Last Modified",
headerAttributes: { style:"text-align:center" }
}
],
dataBound: function (e) {
var grid = this;
//for paging
//if (this.dataSource.total() <= this.dataSource.pageSize) this.options.pageable = false;
//For double clicking
grid.tbody.find("tr").dblclick(function (e) {
var dataItem = grid.dataItem(this);
if(dataItem.isFolder === true){
if(dataItem.path === ".."){
var currentPath = $('#odinLite_ftpTransfer_directoryField').val();
var pos = currentPath.lastIndexOf("/");
if(pos !== -1){
serverVars.path = currentPath.substring(0,pos);
}
}else {
serverVars.path = dataItem.path;
}
getFTPGrid(serverVars);
}else{
addItemToFileManager();
}
});
}
}).data('kendoTreeList');
//$("#odinLite_ftpTreeview").on("dblclick", "tr.k-state-selected", function () {
// console.log(grid.select());
//});
}
/*
function getFileTree(serverVars){
$("#odinLite_ftpTreeview").empty();
var dirStructure = new kendo.data.HierarchicalDataSource({
transport: {
read: function(options) {
console.log('options',options);
$('#odinLite_ftpTransfer_directoryField').val("");
// make JSON request to server
$.ajax({
url: odin.SERVLET_PATH + "?action=odinLite.uploadFiles.getFtpFilesGrid",
data: $.extend(serverVars,{path:options.data.path}),
dataType: "json",
success: function(result) {
console.log('getFileTree',getFileTree);
if(result.success === false){
if(!via.undef(result.message)) {
via.kendoAlert("Error retrieving files",result.message);
}else{
via.kendoAlert("Error retrieving files", "Please check your connection.");
}
ftpWindow.close();
}else {
// notify the data source that the request succeeded
options.success(result.childNodes);
$('#odinLite_ftpTransfer_directoryField').val(result.path);
settingsWindow.close();
}
},
error: function(result) {
// notify the data source that the request failed
options.error(result);
}
});
}
},
schema: {
model: {
id: "path",
hasChildren: "hasChildren"
}
}
});
$("#odinLite_ftpTreeview").kendoTreeView({
dataSource: dirStructure,
dataTextField: "name"
});
}
*/
});
},
/**
* loadFtpSettingsWindow
* This will load ftp settings.
*/
loadFtpSettingsWindow: function(){
via.loadWindow(odin.ODIN_LITE_APP_ID,2,function(loadJson){
$.each(loadJson,function(key,value){
if(key === 'password' || key === 'keyfile'){
value = CryptoJS.AES.decrypt(value, via.ENCRYPT_KEY).toString(CryptoJS.enc.Utf8);
}
if(key === 'type') {
$("#odinLite_ftpTransfer_type").data('kendoDropDownList').value(value);
}else {
var input = $("#odinLite_ftpTransferWindow_form [name='" + key + "']");
if (!via.undef(input) && !via.undef(value, true)) {
$(input).val(value);
}
}
});
});
},
/**
* saveFtpSettingsWindow
* This will save ftp settings.
*/
saveFtpSettingsWindow: function(){
var formData = new FormData($('#odinLite_ftpTransferWindow_form')[0]);
var saveJson = {};
var failedVars = [];
formData.forEach(function(value, key){
saveJson[key] = value;
var input = $("#odinLite_ftpTransferWindow_form [name='"+key+"']");
if(!via.undef(input) && !via.undef($(input).attr('required') && $(input).attr('required') === true) && via.undef(value,true)){
failedVars.push(key);
return false;
}
});
if(failedVars.length > 0){
via.kendoAlert("Missing Value","Missing required values: "+failedVars.join(", "));
return;
}
//Encrypt the password and key file
if(!via.undef(saveJson.password,true)) {
saveJson.password = CryptoJS.AES.encrypt(saveJson.password, via.ENCRYPT_KEY).toString();
}
if(!via.undef(saveJson.keyfile,true)) {
saveJson.keyfile = CryptoJS.AES.encrypt(saveJson.keyfile, via.ENCRYPT_KEY).toString();
}
console.log('saveJson',saveJson);
//Perform the save.
via.saveWindow(odin.ODIN_LITE_APP_ID,2,JSON.stringify(saveJson),function(){
var win = $('#odinLite_ftpTransferWindow').data('kendoWindow');
if(!via.undef(win)) {
win.close();
}
},false);
},
/**
* displayHelpLink
* This will display a window that shows the help for various fields.
* @param helpName
* @param title
*/
displayHelpLink: function (helpName, title) {
var isURL = false;
var content = null;
var width = "75%";
var height = "50%";
switch (helpName) {
case 'UPLOAD_FILES':
content = "You can upload one or more files. The files must be of the same type and format if you wish to upload multiple files at once. Max size for a single file is " + odinLite_uploadFiles.maxSingleFile + ". Max upload size for all files combined is " + odinLite_uploadFiles.maxTotalFiles + ".";
width = "500px";
height = "100px";
break;
case 'COLUMN_HEADERS':
content = "This box will determine if your data has <b>column labels</b> to determine the names of the columns.";
width = "500px";
height = "100px";
break;
case 'START_ROW':
content = "This is the row that your data starts, inclusive of your columns labels.";
width = "500px";
height = "100px";
break;
case 'END_ROW':
content = "This is the last row of your data. This can be determined automatically by leaving this column blank. If your data has a footer you can set this number to negative to remove the last <i>n</i> lines.";
width = "500px";
height = "100px";
break;
case 'TEMPLATE_FILE':
content = "If you are using an excel based template file that has been downloaded from the previous template screen check this box.";
width = "500px";
height = "100px";
break;
case 'START_COLUMN':
content = "This will be the column where your data starts.";
width = "500px";
height = "100px";
break;
case 'END_COLUMN':
content = "This will be the last column of your data.";
width = "500px";
height = "100px";
break;
case 'TEXT_QUALIFIER':
content = "This is for use in ',' separated text files. If your data is encased in quotes or another character you may enter it here.";
width = "500px";
height = "100px";
break;
case 'DATE_FORMAT':
content = "The format that dates use in the file(s) being uploaded.";
width = "500px";
height = "100px";
break;
case 'TIME_SERIES_MERGE':
content = "Allows merge of static data to persisted time series data. For instance, merging account-level currency code which is static through time to account time-series return data.";
width = "500px";
height = "100px";
break;
case 'TIME_SERIES_PORTFOLIO_MERGE':
content = "Allows merge of Non-Portfolio specific Time-Series data to Portfolio time series persisted data. For instance, merging security-level price data to portfolio holdings.";
width = "600px";
height = "100px";
break;
case 'ADVANCED_SETTINGS_COLUMNS':
content = "If newly Mapped and Added Columns are not in this list, please click 'Apply Settings' before continuing.";
width = "600px";
height = "100px";
break;
case 'ATTRIBUTE_DATA':
content = "Generates attribute data set (Columns: Key Column, Start Date Column, End Date Column, Attribute Columns..) from time series account or security time series data. For instance, track the change in sector, industry and country for an account or security over a period of time. Map the Value Date to the Attribute Start Date column.";
width = "800px";
height = "200px";
break;
default:
content = "";
}
via.displayHelpLink(title, content, height, width);
},
/**
* hideUploadFiles
* This will hide upload files section
*/
hideUploadFiles: function () {
$('#uploadFilesPanel').hide();
$('#uploadPanel').hide();
$('#uploadProgressPanel').hide();
},
/**
* deleteStagingAreaFiles
* This will cleanup the staging area. It does this silently.
*/
deleteStagingAreaFiles: function () {
if(odinLite_fileFormat.isUnionFile!==true) {
$.post(odin.SERVLET_PATH,
{
action: 'odinLite.uploadFiles.deleteStagingAreaFiles',
overrideUser: odinLite.OVERRIDE_USER
},
function (data, status) {
if (!via.undef(data, true) && data.success === false) {
via.debug("Delete Files Error:", data.message);
} else {//Success - File Preview
via.debug("Delete Files Success:", data.message);
}
},
'json');
}
},
/**
* importData
* This method will init the next step of the upload process.
* It will also check if it is a union file.
* @param data - the data returned from the file upload.
*/
importData: function(data){
if(odinLite_fileFormat.isUnionFile!==true) {
odinLite_uploadFiles.initialValues = JSON.parse(JSON.stringify(data));//Store the initial values for possible use later if loading a saved report fails.
}
odinLite_fileFormat.init(data);
},
previousButton: function(){
if(odinLite_fileFormat.isUnionFile!==true) {
odinLite.loadModelCacheApplication();
}else{
//Show the file format panel
odinLite_uploadFiles.hideUploadFiles();
$('#fileFormatPanel').fadeIn();
}
},
};<file_sep>/js/support.js
/**
* Created by rocco on 9/13/2018.
* This is the support section of ODIN Lite.
* This will handle everything to do with support.
*/
var odinLite_support = {
/**
* testing
* FOR TESTING ONLY
*/
testing: function(){
odinLite_support.getOpenIssues();
},
init: function(){
$('#li_accountSettings_support').show();
$.post(odin.SERVLET_PATH,
{
action: 'odinLite.support.initSupport'
},
function(data, status){
if(!via.undef(data,true) && data.success === false){
via.debug("Failure retrieving support:", data.message);
}else{
via.debug("Successful retrieving support:", data);
//DD List - Categories
var requestList = [];
$.each(data.requestTypes,function(key,value){
requestList.push({
text: key,
value: value
});
});
$("#accountSettings_support_category").kendoDropDownList({
dataTextField: "text",
dataValueField: "value",
dataSource: requestList,
optionLabel: "",
change: function(e){
//var category = e.sender.value();
}
});
//DD List - Applications - sort
var apps = [];
for (var property in data.applications) {
if (data.applications.hasOwnProperty(property)) {
apps.push(data.applications[property]);
}
}
apps.sort();
var appList = [];
$.each(apps,function(i){
appList.push({
text: apps[i],
value: apps[i]
});
});
$("#accountSettings_support_application").kendoDropDownList({
dataTextField: "text",
dataValueField: "value",
dataSource: appList,
optionLabel: "",
change: function(e){
//var app = e.sender.text();
}
});
//Style the file boxes
$("#accountSettings_support_attachments").kendoUpload({
multiple: true,
localization: {
select: "Select a file to upload..."
}
});
/* Submit the form */
$("#accountSettings_support_form").submit(function(e) {
e.preventDefault();
var formData = new FormData($(this)[0]);
odinLite_support.createSupportTicket(formData);
});
}
},
'json');
},
createSupportTicket: function(formData){
//Check for required values
if(via.undef(formData.get("summary"),true)){
via.kendoAlert("Support Submit Error","Please provide a summary.");
return;
}
if(via.undef(formData.get("application"),true)){
via.kendoAlert("Support Submit Error","Please provide an application.");
return;
}
if(via.undef(formData.get("category"),true)){
via.kendoAlert("Support Submit Error","Please provide a category.");
return;
}
if(via.undef(formData.get("description"),true)){
via.kendoAlert("Support Submit Error","Please provide a description.");
return;
}
//Add the specific action
formData.append('action','odinLite.support.createSupportRequest');
kendo.ui.progress($("body"), true);
//Make the call to the run.
$.ajax({
url: odin.SERVLET_PATH,
type: 'POST',
data: formData,
async: true,
cache: false,
contentType: false,
processData: false,
dataType: 'json',
success: function (data) {
kendo.ui.progress($("body"), false);
if(!via.undef(data,true) && data.success === false){
via.debug("Support Form Failure:", data.message);
via.alert("Support Submit Error",data.message);
}else{
via.debug("Support Form Success:", data.message);
var attachTxt = "";
if(!via.undef(data.numAttachments) && data.numAttachments > 0){
attachTxt = "<br>Uploaded " + data.numAttachments + " attachment(s).";
}
via.alert("Support Submit Success","Support Ticket Submitted.<br>Ticket reference #: " + data.issueKey + attachTxt,function(){
//Reset the form
$('#accountSettings_support_attachments').data('kendoUpload').removeAllFiles();
$('#accountSettings_support_description').val(null);
$('#accountSettings_support_summary').val(null);
$('#accountSettings_support_category').data('kendoDropDownList').select(0);
$('#accountSettings_support_application').data('kendoDropDownList').select(0);
});
}
}
});
},
getOpenIssues: function(){
kendo.ui.progress($("body"), true);
$.post(odin.SERVLET_PATH,
{
action: 'odinLite.support.getOpenIssues'
},
function(data, status){
kendo.ui.progress($("body"), false);
console.log('getOpenIssues',data);
if(!via.undef(data,true) && data.success === false){
via.debug("Failure getting issues:", data.message);
}else{
via.debug("Successful getting issues:", data);
}
},
'json');
}
};<file_sep>/js/modelCache.js
/**
* Created by rocco on 3/16/2018.
* This is the model cache file for the ODIN Lite application.
* This will handle everything to do with models.
*/
var odinLite_modelCache = {
/* Variables */
currentModel: null, //Placeholder for the currently selected model.
currentEntity: null, //Placeholder for the currently selected entity.
columnTemplate: null, //Placeholder for the html template for each column
currentPlatform: null, //Placeholder for the current platform
dataMgmtModel: null, //PLaceholder for the data management model
/**
* init
* This will initialize ODIN Lite Model Cache and set it up
*/
init: function(){
$('#modelDefinition_modelPlatforms').hide();
kendo.ui.progress($("body"), true);//Wait Message
//Make the call to get the initial values for Model Cache
$.post(odin.SERVLET_PATH,
{
action: 'odinLite.cacheModel.init',
overrideUser: odinLite.OVERRIDE_USER,
isDataManagerUser: odinLite.isDataManagerUser,
appId: odinLite.currentApplication
},
function(data, status){
kendo.ui.progress($("body"), false);//Wait Message off
if(!via.undef(data,true) && data.success === false){
via.debug("Failure getting model data:", data.message);
via.kendoAlert("Load Failure", data.message);
}else{
via.debug("Successful getting model data:", data);
//Models Missing
if(via.undef(data.modelList)){
via.kendoAlert("Load Failure", "No models contained in list.");
return;
}
//Zero Models
var modelListLength = Object.keys(data.modelList).length;
if(modelListLength === 0){
via.kendoAlert("Load Failure", "User not permissioned for any models.");
return;
}
//Required and Optional Models
if(via.undef(odinLite.isDataManagerUser) || odinLite.isDataManagerUser !== true) {
if (via.undef(data.requiredModels) && via.undef(data.optionalModels)) {
via.kendoAlert("Load Failure", "Required and optional models not found.");
return;
}
var requiredModelsLength = 0;
if (!via.undef(data.requiredModels)) {
requiredModelsLength = Object.keys(data.requiredModels).length;
}
var optionalModelsLength = 0;
if (!via.undef(data.optionalModels)) {
optionalModelsLength = Object.keys(data.optionalModels).length;
}
if (optionalModelsLength === 0 && requiredModelsLength === 0) {
via.kendoAlert("Load Failure", "No Data Models defined for Reports in your Profile.");
return;
}
}
//Reset in case they were accessed before:
$('#entityList_message').fadeIn();
$('#entityList_existingEntity').hide();
$('#modelDefinition_existingModel').hide();
$('#modelDefinition_editModel').hide();
//Check for data management model
odinLite_modelCache.dataMgmtModel = data.dataMgmtModel;
if(via.undef(odinLite.isDataManagerUser) || odinLite.isDataManagerUser !== true) {
odinLite_modelCache.createModelTree(data.modelList, data.requiredModels, data.optionalModels);
}else{
odinLite_modelCache.createDataManagerModelTree(data);
}
$('#modelCachePanel').fadeIn();
}
},
'json');
},
/**
* createDataManagerModelTree
* This will create the tree to allow model selection for a data manager user
*/
createDataManagerModelTree: function(data){
//Get the data in the correct format.
var treeData = JSON.parse(JSON.stringify(data.modelList));
var kendoTreeData = [];
for(var i=0;i<treeData.length;i++) {
var node = treeData[i];
kendoTreeData = renameChildren(kendoTreeData,node,true);
}
function renameChildren(kendoTreeData,node,isRoot){//Recursive function. All it does it rename children to items.
//Recursive - If it has children call this method again.
if(!via.undef(node.children) && node.children.length > 0 ){
for(var i=0;i<node.children.length;i++){
var childNode = node.children[i];
kendoTreeData = renameChildren(kendoTreeData,childNode,false);
}
node.items = node.children;
node.children = null;
delete node.children;
}
if(isRoot === true){
kendoTreeData.push(node);
}
return kendoTreeData;
}
//End - Get data
//Create the Data Source
var processDataSource = new kendo.data.HierarchicalDataSource({
sort: { field: "text", dir: "asc" },
data: kendoTreeData
});
//Make the tree
//$("#modelCacheSelection_treeview").empty();
if(!via.undef($("#modelCacheSelection_treeview").data('kendoTreeView'))){
$("#modelCacheSelection_treeview").data('kendoTreeView').destroy();
$("#modelCacheSelection_treeview").empty();
}
$("#modelCacheSelection_treeview").kendoTreeView({
dataSource: processDataSource,
dataSpriteCssClassField: "iconCls",
expand: function(e){
if ($("#modelCacheSelection_filterText").val() == "") {
$(e.node).find("li").show();
}
},
change: function(e) {
var selected = this.select();
if(via.undef(selected)){return false;}
var item = this.dataItem(selected);
if(via.undef(item)){return false;}
if(item.hasChildren){return false;}
if(via.undef(item.value)){return false;}
//get application
var parent = this.parent(selected);
while(!via.undef(this.dataItem(this.parent(parent)))){
parent = this.parent(parent);
}
//Get the current model
odinLite_modelCache.currentModel = {
value: item.value,
text: item.text,
description: item.description,
application: this.dataItem(parent).text
};
odinLite_modelCache.getModelInfo(item.value);
}
});
//Expand and Collapse Tree
$('#modelCacheSelection_expandButton').click(function(){
var treeview = $("#modelCacheSelection_treeview").data("kendoTreeView");
treeview.expand(".k-item");
});
$('#modelCacheSelection_collapseButton').click(function(){
var treeview = $("#modelCacheSelection_treeview").data("kendoTreeView");
treeview.collapse(".k-item");
});
$("#modelCacheSelection_filterText").keyup(function (e) {
var changeReport_filterText = $(this).val();
if (changeReport_filterText !== "") {
$("#modelCacheSelection_treeview .k-group .k-group .k-in").closest("li").hide();
$("#modelCacheSelection_treeview .k-group").closest("li").hide();
$("#modelCacheSelection_treeview .k-group .k-group .k-in:containsi(" + changeReport_filterText + ")").each(function () {
$(this).parents("ul, li").each(function () {
var treeView = $("#modelCacheSelection_treeview").data("kendoTreeView");
treeView.expand($(this).parents("li"));
$(this).show();
});
});
}
else {
$("#modelCacheSelection_treeview .k-group").find("li").show();
var nodes = $("#modelCacheSelection_treeview > .k-group > li");
$.each(nodes, function (i, val) {
if (nodes[i].getAttribute("data-expanded") === null) {
$(nodes[i]).find("li").hide();
}
});
}
});
},
/**
* createModelTree
* This will create the tree to allow model selection.
*/
createModelTree: function(modelList,requiredModels,optionalModels){
//Build the Tree Data
var kendoTreeData = [];
$.each( modelList, function( key, modelArr ) {
if(via.undef(modelArr)){return;}
var applicationObj = {};
applicationObj.text = key;
applicationObj.value = key;
applicationObj.expanded = true;
applicationObj.items = [];
applicationObj.iconCls = "folderCls";
var requiredObj = {};
requiredObj.text = " Required";
requiredObj.value = "Required";
requiredObj.expanded = true;
requiredObj.items = [];
requiredObj.iconCls = "folderCls";
var optionalObj = {};
optionalObj.text = "Optional";
optionalObj.value = "Optional";
optionalObj.expanded = true;
optionalObj.items = [];
optionalObj.iconCls = "folderCls";
for(var i=0;i<modelArr.length;i++){
var modelObj = {};
modelObj.text = modelArr[i][1];
modelObj.value = modelArr[i][0];
if(modelArr[i].length > 2) {
modelObj.description = modelArr[i][2];
}
modelObj.iconCls = "leafArrowCls";
//Optional / Required
if(!via.undef(requiredModels) && $.inArray(modelObj.value,requiredModels)!==-1){
requiredObj.items.push(modelObj);
}else if(!via.undef(optionalModels) && $.inArray(modelObj.value,optionalModels)!==-1){
optionalObj.items.push(modelObj);
}else{
continue;
}
}
if(requiredObj.items.length > 0){
applicationObj.items.push(requiredObj);
}
if(optionalObj.items.length > 0){
applicationObj.items.push(optionalObj);
}
if(applicationObj.items.length > 0) {
kendoTreeData.push(applicationObj);
}
});
//End - Build the Tree Data
//Create the Data Source
var processDataSource = new kendo.data.HierarchicalDataSource({
sort: { field: "text", dir: "asc" },
data: kendoTreeData
});
//Make the tree
//$("#modelCacheSelection_treeview").empty();
if(!via.undef($("#modelCacheSelection_treeview").data('kendoTreeView'))){
$("#modelCacheSelection_treeview").data('kendoTreeView').destroy();
$("#modelCacheSelection_treeview").empty();
}
$("#modelCacheSelection_treeview").kendoTreeView({
dataSource: processDataSource,
dataSpriteCssClassField: "iconCls",
expand: function(e){
if ($("#modelCacheSelection_filterText").val() == "") {
$(e.node).find("li").show();
}
},
change: function(e) {
var selected = this.select();
if(via.undef(selected)){return false;}
var item = this.dataItem(selected);
if(via.undef(item)){return false;}
if(item.hasChildren){return false;}
if(via.undef(item.value)){return false;}
//get application
var parent = this.parent(selected);
while(!via.undef(this.dataItem(this.parent(parent)))){
parent = this.parent(parent);
}
//Get the current model
odinLite_modelCache.currentModel = {
value: item.value,
text: item.text,
description: item.description,
application: this.dataItem(parent).text
};
odinLite_modelCache.getModelInfo(item.value);
}
});
//Expand and Collapse Tree
$('#modelCacheSelection_expandButton').click(function(){
var treeview = $("#modelCacheSelection_treeview").data("kendoTreeView");
treeview.expand(".k-item");
});
$('#modelCacheSelection_collapseButton').click(function(){
var treeview = $("#modelCacheSelection_treeview").data("kendoTreeView");
treeview.collapse(".k-item");
});
$("#modelCacheSelection_filterText").keyup(function (e) {
var changeReport_filterText = $(this).val();
if (changeReport_filterText !== "") {
$("#modelCacheSelection_treeview .k-group .k-group .k-in").closest("li").hide();
$("#modelCacheSelection_treeview .k-group").closest("li").hide();
$("#modelCacheSelection_treeview .k-group .k-group .k-in:containsi(" + changeReport_filterText + ")").each(function () {
$(this).parents("ul, li").each(function () {
var treeView = $("#modelCacheSelection_treeview").data("kendoTreeView");
treeView.expand($(this).parents("li"));
$(this).show();
});
});
}
else {
$("#modelCacheSelection_treeview .k-group").find("li").show();
var nodes = $("#modelCacheSelection_treeview > .k-group > li");
$.each(nodes, function (i, val) {
if (nodes[i].getAttribute("data-expanded") === null) {
$(nodes[i]).find("li").hide();
}
});
}
});
},
/**
* getModelInfo
* This will retrieve model information
*/
getModelInfo: function(modelId,isSkipPlatform){
kendo.ui.progress($("body"), true);//Wait Message
var entityDir = odinLite.ENTITY_DIR;
//Make the call to get the model info
$.post(odin.SERVLET_PATH,
{
action: 'odinLite.cacheModel.getModelInfo',
modelId: modelId,
entityDir: entityDir,
overrideUser: odinLite.OVERRIDE_USER
},
function(data, status){
kendo.ui.progress($("body"), false);//Wait Message off
odinLite_modelCache.hideModelDefinition();
$("html, body").animate({
scrollTop: 0
}, 250);
if(!via.undef(data,true) && data.success === false){
via.debug("Failure getting model:", data.message);
via.kendoAlert("Model Failure", data.message);
}else {
via.debug("Successful getting model:", data);
if (!via.undef(data.modelInfo.errorString, true)) {
via.kendoAlert("Problem with data model", data.modelInfo.errorString);
return;
}
$("#entityList_message").hide();
$(".entityList_modelName").html(odinLite_modelCache.currentModel.text);
$(".entityList_modelDescription").empty();
if (!via.undef(odinLite_modelCache.currentModel.description)) {
$(".entityList_modelDescription").html(odinLite_modelCache.currentModel.description);
}
$("#entityList_existingEntity").fadeIn();
//Save the modelInfo
data.modelInfo.modelId = modelId;
odinLite_modelCache.currentEntity = data.modelInfo;
//Display the selected model and get the template to use.
$.get('./html/modelCache_columnTemplate.html', function(data) {
odinLite_modelCache.columnTemplate = data;
//Launch the Platform Chooser or display the saved model.
if((!via.undef(isSkipPlatform,true) && isSkipPlatform===true) || (odinLite_modelCache.dataMgmtModel === odinLite_modelCache.currentEntity.modelId)){
odinLite_modelCache.displaySelectedModelTemplate();
}else {
odinLite_modelCache.displayPlatformChooser();
}
//Check for Demo Account
if(modelId.startsWith("DEMO_")){
$(".demoButton").prop("disabled",true);
}else{
$(".demoButton").prop("disabled",false);
}
}, 'text');
}
},
'json');
},
/**
* createNewEntity
* This will create a new entity for a user
*/
createNewEntity: function(callbackFn){
via.kendoPrompt("Create New Entity","Please enter an entity name.",function(name){
kendo.ui.progress($("body"), true);//Wait Message off
//Make the call to create the entity
$.post(odin.SERVLET_PATH,
{
action: 'odinLite.cacheModel.createApplicationEntity',
entityName: name,
overrideUser: odinLite.OVERRIDE_USER
},
function(data, status){
kendo.ui.progress($("body"), false);//Wait Message off
if(!via.undef(data,true) && data.success === false){
via.debug("Failure creating entity:", data.message);
via.kendoAlert("Entity Create Failure", data.message);
}else{
via.debug("Successful creating entity:", data);
via.kendoAlert("Entity Create Success", data.message);
}
if(!via.undef(callbackFn)){
callbackFn(data);
}
},
'json');
});
},
/**
* deleteEntity
* This will delete am entity for a given user
*/
deleteEntity: function(entityDir,entityName,callbackFn){
via.confirm("Delete Entity","Are you sure you want to delete the entity " + entityName + "? This action cannot be undone and will purge all data for the entity.",function(){
via.inputDialog("Confirm Delete","This will <b>purge</b> all data for this entity. Type the word \"<span style=\"color:red;\">delete</span>\" below to confirm.",function(val){
if(!via.undef(val,true) && val==='delete'){
//Make the call to delete the entity
$.post(odin.SERVLET_PATH,
{
action: 'odinLite.cacheModel.deleteApplicationEntity',
entityDir: entityDir,
overrideUser: odinLite.OVERRIDE_USER
},
function(data, status){
kendo.ui.progress($("body"), false);//Wait Message off
if(!via.undef(data,true) && data.success === false){
via.debug("Failure deleting entity:", data.message);
via.kendoAlert("Entity Delete Failure", data.message);
}else{
via.debug("Successful deleting entity:", data);
via.kendoAlert("Entity Delete Success", data.message);
}
if(!via.undef(callbackFn)){
callbackFn(data);
}
},
'json');
}else{
via.kendoAlert("Delete Entity", "Entity not deleted.");
}
});
});
},
/**
* hideModelDefinition
* This will hide the model selection
*/
hideModelDefinition: function(){
$(".modelColumnContainer").empty();
$('#modelDefinition_existingModel').hide();
$("#modelDefinition_editModel").hide();
},
/**
* displayPlatformChooser
* This will display the platform chooser panel.
*/
displayPlatformChooser: function(){
$("#modelDefinition_modelPlatforms").fadeIn();
//Create the inputs
$(".modelDefinition_platformNameContainer").empty();
$(".modelDefinition_platformNameContainer").append('<input style="width:450px;" class="modelDefinition_platformNameInput" />');
$(".modelDefinition_platformSpecContainer").empty();
$(".modelDefinition_platformSpecContainer").append('<input style="width:450px;" class="modelDefinition_platformSpecInput" />');
//Platform Specs
var platformSpecInput = $(".modelDefinition_platformSpecInput").kendoDropDownList({
dataTextField: "specification",
dataValueField: "specification",
dataSource: [],
change: function (e) {
var dataItem = e.sender.dataItem();
//Update the description
$('.modelDefinition_platformSpecDefinition').html(dataItem.description);
$(".modelDefinition_platformSpecContainer_helpLink").empty();
if(!via.undef(dataItem.helpLink)) {
$(".modelDefinition_platformSpecContainer_helpLink").empty();
$(".modelDefinition_platformSpecContainer_helpLink").append(`<button title="Additional Information"
onclick="via.displayHelpLink('${dataItem.specification}','${dataItem.helpLink}');"
style="margin-left:10px;margin-bottom:2px;" type="button" class="tr btn btn-primary">
<i class="fa fa-question-circle"></i></button>
`);
}
}
}).data('kendoDropDownList');
//Platform Names
var platformNames = getPlatformNames();
var platformNameInput = $(".modelDefinition_platformNameInput").kendoDropDownList({
dataTextField: "platform",
dataValueField: "platform",
dataSource: platformNames,
index: 0,
change: function (e) {
var dataItem = e.sender.dataItem();
if(dataItem === undefined){
$('.modelDefinition_platformNameDefinition').html("");
platformNameInput.dataSource.data([]);
return;
}
//Update the description
$('.modelDefinition_platformNameDefinition').html(dataItem.description);
//Update the specs
var platformSpecs = getPlatformSpecs(dataItem.platform);
platformSpecInput.dataSource.data([]);
platformSpecInput.dataSource.data(platformSpecs);
platformSpecInput.select(0);
platformSpecInput.trigger('change');
}
}).data('kendoDropDownList');
if(!via.undef(odinLite_modelCache.currentEntity.savedPlatformList)){
platformNameInput.search(odinLite_modelCache.currentEntity.savedPlatformList[0][0]);
}
platformNameInput.trigger("change");
/** Button Event **/
$(".modelDefinition_choosePlatformButton").off("click");
$(".modelDefinition_choosePlatformButton").click(function(){
var dataItem = platformSpecInput.dataItem().toJSON();
odinLite_modelCache.currentPlatform = dataItem;
platformChosen();
});
function platformChosen(){
//Hide Template
if(odinLite_modelCache.currentPlatform.platform !== 'Custom'){
$('.exampleTemplateFile').hide();
}else{
$('.exampleTemplateFile').show();
}
//Check to see if the model is already a saved model
var platform = odinLite_modelCache.currentPlatform.platform;
var usePresavedTemplate = odinLite_modelCache.currentEntity.usePlatformDefinedMetaDataFileMap;
if(odinLite_modelCache.currentEntity.savedModelExists === true){
odinLite_modelCache.displaySelectedModelTemplate();
}else if(!via.undef(usePresavedTemplate,true) && usePresavedTemplate[platform] === true &&
odinLite_modelCache.currentEntity.savedModelExists === false){
//Make the call to copy the model
kendo.ui.progress($("body"), true);//Wait Message off
$.post(odin.SERVLET_PATH,
{
action: 'odinLite.cacheModel.saveModelPlatformDefinition',
platform: platform,
entityDir: odinLite_modelCache.currentEntity.entityDir,
modelId: odinLite_modelCache.currentModel.value,
overrideUser: odinLite.OVERRIDE_USER
},
function(data, status){
kendo.ui.progress($("body"), false);//Wait Message off
if(!via.undef(data,true) && data.success === false){
via.debug("Platform Copy Failure:", data.message);
via.kendoAlert("Platform Copy Failure", data.message);
}else{
via.debug("Success copying platform:", data);
//Save the modelInfo
odinLite_modelCache.currentEntity = data.modelInfo;
//Display the saved template
odinLite_modelCache.displaySelectedModelTemplate();
}
},
'json');
}else{
odinLite_modelCache.displaySelectedModelTemplate();
}
}
/** Functions **/
//Return a list of platform names
function getPlatformNames(){
var platforms = [];
//Check for data
if(via.undef(odinLite_modelCache.currentEntity.platformList)){
via.debug("No Platforms found for this model.");
return [];
}
//Build the dropdown model
for(var i in odinLite_modelCache.currentEntity.platformList){
var platform = odinLite_modelCache.currentEntity.platformList[i];
if(via.undef(platform)){ continue; }
platforms.push({
platform: platform[0],
description: platform[1],
helpLink: platform.length>3?platform[3]:null
});
}
return platforms;
}
//Returns the specs for the passed platform
function getPlatformSpecs(platformName){
var specArray = odinLite_modelCache.currentEntity.platformSpecMap[platformName];
if(via.undef(odinLite_modelCache.currentEntity.platformList)){
via.debug("No Platforms Specifications found for this model.");
return [];
}
var platformSpecs = [];
for(var i in specArray){
var spec = specArray[i];
if(via.undef(spec)){ continue; }
platformSpecs.push({
platform: spec[0],
specification: spec[1],
description: spec[2],
helpLink: spec.length>3?spec[3]:null
});
}
return platformSpecs;
}
},
/**
* displaySelectedModelTemplate
* This will display the current model on the screen for editing
*/
displaySelectedModelTemplate: function(edit){
$("#modelDefinition_modelPlatforms").hide();
odinLite_modelCache.hideModelDefinition();//Hide the Model Definition and reset it.
if(odinLite_modelCache.currentEntity.savedModelExists === false || edit === true){
$("#modelDefinition_editModel").fadeIn();
buildColumnModel();
//Check to see id it is the data management model.
if((odinLite_modelCache.dataMgmtModel === odinLite_modelCache.currentEntity.modelId) &&
(odinLite_modelCache.currentEntity.savedModelExists === false)){
odinLite_modelCache.saveModelDefinition();
}
}else{
$("#modelDefinition_existingModel").fadeIn();
if(odinLite_modelCache.dataMgmtModel === odinLite_modelCache.currentEntity.modelId){
$('.dataMgmtHide').hide();
odinLite_modelCache.currentPlatform = {"platform":"Custom","specification":"Custom Upload"};
}else{
$('.dataMgmtHide').show();
}
}
function buildColumnModel(){
var isSavedModel = false;
var modelData = odinLite_modelCache.currentEntity.columnInfo;
if(odinLite_modelCache.currentEntity.savedModelExists === true &&
!via.undef(odinLite_modelCache.currentEntity.savedColumnInfo)){
modelData = updateSavedModelData( odinLite_modelCache.currentEntity.savedColumnInfo, odinLite_modelCache.currentEntity.columnInfo);
isSavedModel = true;
}
var hasCustom = false;//Track if it has a custom column
for(var i=0;i<modelData.length;i++) {
var colObj = modelData[i];
if(!via.undef(colObj.isCustom) && colObj.isCustom===true){hasCustom = true;}
//if(isSavedModel === false && colObj.isCustom === true){ continue; }//Don't add custom models the first run.
odinLite_modelCache.addModelColumnTemplate(colObj,odinLite_modelCache.currentEntity.allowEditOfExistingTemplateColumns);
}
if(hasCustom === true){
$('#modelDefinition_editModel').find('.customColumnButton').fadeIn();
}else{
$('#modelDefinition_editModel').find('.customColumnButton').hide();
}
//Disable the save button
if(!via.undef(odinLite_modelCache.currentEntity.allowEditOfExistingTemplateColumns) &&
odinLite_modelCache.currentEntity.allowEditOfExistingTemplateColumns === false){
$('.modelDefinition_saveModelButton').prop('disabled',true);
}
}
function updateSavedModelData(savedColumnInfo,columnInfo){
var modelInfo = [];
for(var i in savedColumnInfo){
var savedColumn = savedColumnInfo[i];
//Make the model for the column
var columnModel = {};
columnModel.id = savedColumn.id;
columnModel.isCustom = savedColumn.isCustom;
columnModel.isNullAllowed = savedColumn.isNullAllowed;
columnModel.name = savedColumn.name;
for(var j in columnInfo){
var colInfo = columnInfo[j];
if(colInfo.id === savedColumn.id){
columnModel.description = colInfo.description;//Update description. it doesn't come through
//Define all the params
columnModel.applyDataTypeList = $.extend({},colInfo.applyDataTypeList);
columnModel.applyFXRateList = $.extend({},colInfo.applyFXRateList);
columnModel.applyFXReturnList = $.extend({},colInfo.applyFXReturnList);
columnModel.applyFactorList = $.extend({},colInfo.applyFactorList);
columnModel.applyUseColumnList = $.extend({},colInfo.applyUseColumnList);
columnModel.applyAllowableTextLengthList = $.extend({},colInfo.applyAllowableTextLengthList);
columnModel.applyIsNullAllowedList = $.extend({},colInfo.applyIsNullAllowedList);
//Get the default Values
if(!via.undef(savedColumn.applyDataTypeList) && !via.undef(savedColumn.applyDataTypeList.options) && savedColumn.applyDataTypeList.options.length>0){
columnModel.applyDataTypeList.defaultValue = savedColumn.applyDataTypeList.options[0];
}
if(!via.undef(savedColumn.applyFXRateList) && !via.undef(savedColumn.applyFXRateList.options) && savedColumn.applyFXRateList.options.length>0){
columnModel.applyFXRateList.defaultValue = savedColumn.applyFXRateList.options[0];
}
if(!via.undef(savedColumn.applyFXReturnList) && !via.undef(savedColumn.applyFXReturnList.options) && savedColumn.applyFXReturnList.options.length>0){
columnModel.applyFXReturnList.defaultValue = savedColumn.applyFXReturnList.options[0];
}
if(!via.undef(savedColumn.applyFactorList) && !via.undef(savedColumn.applyFactorList.options) && savedColumn.applyFactorList.options.length>0){
columnModel.applyFactorList.defaultValue = savedColumn.applyFactorList.options[0];
}
if(!via.undef(savedColumn.applyUseColumnList) && !via.undef(savedColumn.applyUseColumnList.options) && savedColumn.applyUseColumnList.options.length>0){
columnModel.applyUseColumnList.defaultValue = savedColumn.applyUseColumnList.options[0];
}
if(!via.undef(savedColumn.applyAllowableTextLengthList) && !via.undef(savedColumn.applyAllowableTextLengthList.options) && savedColumn.applyAllowableTextLengthList.options.length>0){
columnModel.applyAllowableTextLengthList.defaultValue = savedColumn.applyAllowableTextLengthList.options[0];
}
if(!via.undef(savedColumn.applyAllowableTextLengthList) && !via.undef(savedColumn.applyAllowableTextLengthList.defaultValue)){
columnModel.applyAllowableTextLengthList.maxLength = savedColumn.applyAllowableTextLengthList.defaultValue;
}
if(!via.undef(savedColumn.applyIsNullAllowedList) && !via.undef(savedColumn.applyIsNullAllowedList.options) && savedColumn.applyIsNullAllowedList.options.length>0){
columnModel.applyIsNullAllowedList.defaultValue = savedColumn.applyIsNullAllowedList.options[0];
}
break;
}
}
modelInfo.push(columnModel);
}
return modelInfo;
}
},
/**
* addModelColumnTemplate
* This will add a column to the template
*/
addModelColumnTemplate: function(colObj,allowEditOfExistingTemplateColumns){
if(via.undef(allowEditOfExistingTemplateColumns,true)){//Set to false if it is missing
allowEditOfExistingTemplateColumns = true;
}
var colTemplate = odinLite_modelCache.columnTemplate + "";
//Edit the column template for this column
//Replace the ID
colTemplate = colTemplate.replace(/{column_idName}/g,colObj.id);
//Replace the name
colTemplate = colTemplate.replace(/{column_displayName}/g,colObj.name);
//Add the columns to the template
var newColumn = $(colTemplate);
$(".modelColumnContainer").append( newColumn );
//Apply Data Type List
if(via.undef(colObj.applyDataTypeList) || via.undef(colObj.applyDataTypeList.label) || via.undef(colObj.applyDataTypeList.comboOptions,true)){
newColumn.find(".applyDataTypeList_selector").hide();
}else {
newColumn.find(".applyDataTypeList_label").html(colObj.applyDataTypeList.label);
var ddList = newColumn.find(".applyDataTypeList_input").kendoDropDownList({
dataTextField: "text",
dataValueField: "value",
dataSource: colObj.applyDataTypeList.comboOptions,
index: 0
}).data('kendoDropDownList');
if(colObj.applyDataTypeList.comboOptions.length === 1 || allowEditOfExistingTemplateColumns===false){
ddList.enable(false);
}
if(!via.undef(colObj.applyDataTypeList.defaultValue)){
ddList.value(colObj.applyDataTypeList.defaultValue);
}
}
//applyFXRateList
if(via.undef(colObj.applyFXRateList) || via.undef(colObj.applyFXRateList.label) || via.undef(colObj.applyFXRateList.comboOptions,true)){
newColumn.find(".applyFXRateList_selector").hide();
}else {
newColumn.find(".applyFXRateList_label").html(colObj.applyFXRateList.label);
var ddList = newColumn.find(".applyFXRateList_input").kendoDropDownList({
dataTextField: "text",
dataValueField: "value",
dataSource: colObj.applyFXRateList.comboOptions,
index: 0
}).data('kendoDropDownList');
if(colObj.applyFXRateList.comboOptions.length === 1 || allowEditOfExistingTemplateColumns===false){
ddList.enable(false);
}
if(!via.undef(colObj.applyFXRateList.defaultValue)){
ddList.value(colObj.applyFXRateList.defaultValue);
}
}
//applyFXReturnList
if(via.undef(colObj.applyFXReturnList) || via.undef(colObj.applyFXReturnList.label) || via.undef(colObj.applyFXReturnList.comboOptions,true)){
newColumn.find(".applyFXReturnList_selector").hide();
}else {
newColumn.find(".applyFXReturnList_label").html(colObj.applyFXReturnList.label);
var ddList = newColumn.find(".applyFXReturnList_input").kendoDropDownList({
dataTextField: "text",
dataValueField: "value",
dataSource: colObj.applyFXReturnList.comboOptions,
index: 0
}).data('kendoDropDownList');
if(colObj.applyFXReturnList.comboOptions.length === 1 || allowEditOfExistingTemplateColumns===false){
ddList.enable(false);
}
if(!via.undef(colObj.applyFXReturnList.defaultValue)){
ddList.value(colObj.applyFXReturnList.defaultValue);
}
}
//applyFactorList
if(via.undef(colObj.applyFactorList) || via.undef(colObj.applyFactorList.label) || via.undef(colObj.applyFactorList.comboOptions,true)){
newColumn.find(".applyFactorList_selector").hide();
}else {
newColumn.find(".applyFactorList_label").html(colObj.applyFactorList.label);
var ddList = newColumn.find(".applyFactorList_input").kendoDropDownList({
dataTextField: "text",
dataValueField: "value",
dataSource: colObj.applyFactorList.comboOptions,
index: 0
}).data('kendoDropDownList');
if(colObj.applyFactorList.comboOptions.length === 1 || allowEditOfExistingTemplateColumns===false){
ddList.enable(false);
}
if(!via.undef(colObj.applyFactorList.defaultValue)){
ddList.value(colObj.applyFactorList.defaultValue);
}
}
//applyUseColumnList
if(via.undef(colObj.applyUseColumnList) || via.undef(colObj.applyUseColumnList.label) || via.undef(colObj.applyUseColumnList.comboOptions,true)){
newColumn.find(".applyUseColumnList_selector").hide();
}else {
newColumn.find(".applyUseColumnList_label").html(colObj.applyUseColumnList.label);
var ddList = newColumn.find(".applyUseColumnList_input").kendoDropDownList({
dataTextField: "text",
dataValueField: "value",
dataSource: colObj.applyUseColumnList.comboOptions,
index: 0
}).data('kendoDropDownList');
if(colObj.applyUseColumnList.comboOptions.length === 1 || allowEditOfExistingTemplateColumns===false){
ddList.enable(false);
}
if(!via.undef(colObj.applyUseColumnList.defaultValue)){
ddList.value(colObj.applyUseColumnList.defaultValue);
}
}
//applyAllowableTextLengthList
if(via.undef(colObj.applyAllowableTextLengthList) || via.undef(colObj.applyAllowableTextLengthList.label) || via.undef(colObj.applyAllowableTextLengthList.comboOptions,true)){
newColumn.find(".applyAllowableTextLengthList_selector").hide();
newColumn.find(".applyAllowableTextLengthList_number_selector").hide();
}else {
newColumn.find(".applyAllowableTextLengthList_label").html(colObj.applyAllowableTextLengthList.label);
var ddList = newColumn.find(".applyAllowableTextLengthList_input").kendoDropDownList({
dataTextField: "text",
dataValueField: "value",
dataSource: colObj.applyAllowableTextLengthList.comboOptions,
index: 0,
change: function(e){
if(e.sender.value()==='DEFINED LENGTH'){
newColumn.find('.applyAllowableTextLengthList_number_selector').show();
}else{
newColumn.find('.applyAllowableTextLengthList_number_selector').hide();
}
}
}).data('kendoDropDownList');
var numBox = newColumn.find(".applyAllowableTextLengthList_number_input").kendoNumericTextBox({
format: 'n0',
min: 1,
max: 8000,
step: 1,
decimals: 0,
restrictDecimals: true
}).data('kendoNumericTextBox');
newColumn.data('numbox',numBox);
if(colObj.applyAllowableTextLengthList.comboOptions.length === 1 || allowEditOfExistingTemplateColumns===false){
ddList.enable(false);
}
if(!via.undef(colObj.applyAllowableTextLengthList.defaultValue)){
ddList.value(colObj.applyAllowableTextLengthList.defaultValue);
//Hide the numberic box
if(colObj.applyAllowableTextLengthList.defaultValue === "DEFINED LENGTH"){
newColumn.find('.applyAllowableTextLengthList_number_selector').show();
if(!via.undef(colObj.applyAllowableTextLengthList.maxLength)){
numBox.value(colObj.applyAllowableTextLengthList.maxLength);
}else if(!via.undef(colObj.applyAllowableTextLengthList.additionalDefaultValue)){
numBox.value(colObj.applyAllowableTextLengthList.additionalDefaultValue);
}
}else{
newColumn.find('.applyAllowableTextLengthList_number_selector').hide();
}
}
}
//applyIsNullAllowedList
if(via.undef(colObj.applyIsNullAllowedList) || via.undef(colObj.applyIsNullAllowedList.label) || via.undef(colObj.applyIsNullAllowedList.comboOptions,true)){
newColumn.find(".applyIsNullAllowedList_selector").hide();
}else {
newColumn.find(".applyIsNullAllowedList_label").html(colObj.applyIsNullAllowedList.label);
var ddList = newColumn.find(".applyIsNullAllowedList_input").kendoDropDownList({
dataTextField: "text",
dataValueField: "value",
dataSource: colObj.applyIsNullAllowedList.comboOptions,
index: 0
}).data('kendoDropDownList');
if(colObj.applyIsNullAllowedList.comboOptions.length === 1 || allowEditOfExistingTemplateColumns===false){
ddList.enable(false);
}
if(!via.undef(colObj.applyIsNullAllowedList.defaultValue)){
ddList.value(colObj.applyIsNullAllowedList.defaultValue);
}
}
//isCustom
if(!via.undef(colObj.isCustom) && colObj.isCustom===true && allowEditOfExistingTemplateColumns === true){
newColumn.find(".column_displayName").removeAttr("disabled");
newColumn.find(".deleteCustomButton").show();
newColumn.addClass("customColumnBorder");
newColumn.find(".column_displayName").css("color","#0066cc");
}else{
newColumn.find(".column_displayName").css("color","#808080");
}
},
/**
* addCustomColumn
* This will add a custom column to the model column definition
*/
addCustomColumn: function(){
var customColumns = [];
for(var idx in odinLite_modelCache.currentEntity.columnInfo){
var col = odinLite_modelCache.currentEntity.columnInfo[idx];
if(col.isCustom === true){
customColumns.push(col);
}
}
$.get( "./html/modelCache_customColumnWindow.html", function( data ) {
$('body').append(data);
//Remove when closed
$('#customColumnModalWindow').on('hidden.bs.modal', function (e) {
$('#customColumnModalWindow').remove();
});
//Show the window
$('#customColumnModalWindow').modal('show');
//Populate the dd list
var ddList = $('#customColumnModalWindow').find('.customColumnInput').kendoDropDownList({
dataTextField: "name",
dataValueField: "id",
dataSource: customColumns,
width: "300px",
index: 0,
change: function(e){
$('#customColumnModalWindow').find('.customColumnDescription').html(customColumns[e.sender.select()].description);
}
}).data('kendoDropDownList');
//Set the Description
$('#customColumnModalWindow').find('.customColumnDescription').html(customColumns[0].description);
//Handle the event
$('#customColumnModalWindow').find('.ok-customColumn-button').click(function(){
var selectedColumn = customColumns[ddList.select()];
odinLite_modelCache.addModelColumnTemplate(selectedColumn);
$('.modelDefinition_saveModelButton').prop('disabled',false);
});
});
},
/**
* deleteCustomColumn
* This will delete a custom column from the model definition
*/
deleteCustomColumn: function(id,btn){
via.confirm("Delete Custom Column","Are you sure you want to delete this column?",function(){
$(btn).parent().remove();
});
},
/**
* saveModelDefinition
* This will save the model definition.
*/
saveModelDefinition: function(){
kendo.ui.progress($("body"), true);//Wait Message on
//Get the save column objects
var container = $('.modelColumnContainer');
var saveColumns = [];
for(var idx in odinLite_modelCache.currentEntity.columnInfo){
var colInfo = odinLite_modelCache.currentEntity.columnInfo[idx];
var columnContainers = container.find("."+colInfo.id);
for(var i=0;i<columnContainers.length;i++){
var colContainer = columnContainers[i];
var addColumn = odinLite_modelCache.getColumnSaveDefinition(colContainer);
if(!via.undef(addColumn.applyAllowableTextLength,true) && addColumn.applyAllowableTextLength.startsWith("DEFINED LENGTH") &&
addColumn.applyAllowableTextLength.endsWith("null") ) {
via.kendoAlert("Maximum Text Length", "Please define a maximum text length for "+addColumn.name+".");
kendo.ui.progress($("body"), false);//Wait Message on
return;
}
saveColumns.push(addColumn);
}
}
//Check to make sure all custom columns that are required have at least one entry.
//Also check if they have a name
for(var idx in odinLite_modelCache.currentEntity.columnInfo){
var col = odinLite_modelCache.currentEntity.columnInfo[idx];
if(col.isCustom === true &&
!via.undef(col.applyUseColumnList) &&
!via.undef(col.applyUseColumnList.options) &&
col.applyUseColumnList.options.length === 1){
var isColIncluded = false;
for(var i in saveColumns){
//Name Defined Check
if(via.undef(saveColumns[i].name) || saveColumns[i].name.trim().length === 0){
via.kendoAlert("Model Save Failed","All Columns required a name. Please check to be sure you named your columns.");
return;
}
//Custom Included Check
if(saveColumns[i].id === col.id){
isColIncluded = true;
break;
}
}
//Custom Column is required and not found.
if(isColIncluded === false){
via.kendoAlert("Model Save Failed","Custom Column \"" + col.name + "\" is not in the model definition.");
return;
}
}
}
//Make the call to save the model
$.post(odin.SERVLET_PATH,
{
action: 'odinLite.cacheModel.saveModelDefinition',
saveColumns: JSON.stringify(saveColumns),
modelId: odinLite_modelCache.currentModel.value,
entityDir: odinLite.ENTITY_DIR,
overrideUser: odinLite.OVERRIDE_USER
},
function(data, status){
kendo.ui.progress($("body"), false);//Wait Message off
if(!via.undef(data,true) && data.success === false){
via.debug("Failure saving model:", data.message);
via.kendoAlert("Save Model Failure", data.message);
}else{
via.debug("Successful saving model:", data);
odinLite_modelCache.getModelInfo(odinLite_modelCache.currentModel.value,true);
}
},
'json');
},
/**
* downloadModelTemplate
* download excel template for the saved model.
*/
downloadModelTemplate: function() {
if(via.undef(odinLite_modelCache.currentEntity.savedColumnInfo)){return;}
var url = odin.SERVLET_PATH + "?action=odinLite.cacheModel.downloadTemplate" +
"&modelId=" + odinLite_modelCache.currentModel.value +
"&overrideUser=" + odinLite.OVERRIDE_USER +
"&entityDir=" + odinLite.ENTITY_DIR;
window.location = url;
},
/**
* getColumnSaveDefinition
* This will get the save info for a specific column
*/
getColumnSaveDefinition: function(colContainer){
var colObj = {};
//ID
colObj.id = $(colContainer).data("colid");
//display name
var displayName_textBox = $(colContainer).find('.column_displayName');
if(!via.undef(displayName_textBox) && !via.undef(displayName_textBox.val())){
colObj.name = displayName_textBox.val();
};
//applyUseColumnList
var applyUseColumnList_dd = $(colContainer).find('span .applyUseColumnList_input').data('kendoDropDownList');
if(!via.undef(applyUseColumnList_dd) && !via.undef(applyUseColumnList_dd.value())){
colObj.applyUseColumn = applyUseColumnList_dd.value();
};
//applyDataTypeList
var applyDataTypeList_dd = $(colContainer).find('span .applyDataTypeList_input').data('kendoDropDownList');
if(!via.undef(applyDataTypeList_dd) && !via.undef(applyDataTypeList_dd.value())){
colObj.applyDataType = applyDataTypeList_dd.value();
};
//applyFXRateList
var applyFXRateList_dd = $(colContainer).find('span .applyFXRateList_input').data('kendoDropDownList');
if(!via.undef(applyFXRateList_dd) && !via.undef(applyFXRateList_dd.value())){
colObj.applyFXRate = applyFXRateList_dd.value();
};
//applyFXReturnList
var applyFXReturnList_dd = $(colContainer).find('span .applyFXReturnList_input').data('kendoDropDownList');
if(!via.undef(applyFXReturnList_dd) && !via.undef(applyFXReturnList_dd.value())){
colObj.applyFXReturn = applyFXReturnList_dd.value();
};
//applyFactorList
var applyFactorList_dd = $(colContainer).find('span .applyFactorList_input').data('kendoDropDownList');
if(!via.undef(applyFactorList_dd) && !via.undef(applyFactorList_dd.value())){
colObj.applyFactor = applyFactorList_dd.value();
};
//applyAllowableTextLengthList
var applyAllowableTextLengthList_dd = $(colContainer).find('span .applyAllowableTextLengthList_input').data('kendoDropDownList');
if(!via.undef(applyAllowableTextLengthList_dd) && !via.undef(applyAllowableTextLengthList_dd.value())){
var applyAllowableTextLengthListVal = applyAllowableTextLengthList_dd.value();
if(applyAllowableTextLengthListVal === "DEFINED LENGTH"){
//var applyAllowableTextLengthList_num_dd = $(colContainer).find('.applyAllowableTextLengthList_number_input').data('kendoNumericTextBox');
var applyAllowableTextLengthList_num_dd = $(colContainer).data('numbox');
var numericVal = applyAllowableTextLengthList_num_dd.value();
colObj.applyAllowableTextLength = applyAllowableTextLengthListVal+";"+numericVal;
}else{
colObj.applyAllowableTextLength = applyAllowableTextLengthListVal;
}
};
//applyIsNullAllowedList
var applyIsNullAllowedList_dd = $(colContainer).find('span .applyIsNullAllowedList_input').data('kendoDropDownList');
if(!via.undef(applyIsNullAllowedList_dd) && !via.undef(applyIsNullAllowedList_dd.value())){
colObj.applyIsNullAllowed = applyIsNullAllowedList_dd.value();
};
return colObj;
},
/**
* getHelpLink
* displays a help link window for the column
*/
getHelpLink: function(colId){
for(var i in odinLite_modelCache.currentEntity.columnInfo){
var col = odinLite_modelCache.currentEntity.columnInfo[i];
if(colId.indexOf(col.id)!==-1){
via.displayHelpLink(col.name,col.description);
break;
}
}
},
/**
* goToUploadFiles
* This will check to make sure everything is correct and then navigate to upload files.
*/
goToUploadFiles: function(){
$("#modelCachePanel").fadeOut(function(){
//Initialize the upload files portion of the application
odinLite_uploadFiles.init();
});
},
displayColumnListInfo: function(){
$.ajax({
url: '/ODIN/ODINServlet/ODIN_LITE/GET_DISPLAY_COLUMN_LIST?modelId=' + odinLite_modelCache.currentModel.value,
method: 'POST', // or GET
success: function (response) {
var sampleDataJSON = JSON.parse(response);
odinLite_modelCache.displayGridWindow(sampleDataJSON.columnListSet);
}
});
},
displaySampleData: function(){
$.ajax({
url: '/ODIN/ODINServlet/ODIN_LITE/MODEL_SAMPLE_DATA?modelId=' + odinLite_modelCache.currentModel.value,
method: 'POST', // or GET
success: function (response) {
var sampleDataJSON = JSON.parse(response);
console.log(sampleDataJSON);
odinLite_modelCache.displayGridWindow(sampleDataJSON.modelTemplate);
}
});
},
/** Displays sample input table data in modal **/
displayGridWindow: function(sampleData) {
var columnHeaders = sampleData['columnHeaders'];
var tableSet = sampleData['data'];
var sampleDataTitle = sampleData['tableLabel'];
sampleData['columnWidths'] = [];
$('body').append('<div id="sample-data-modal"><div id="sample-data-table"></div></div>');
odinTable.createTable("sample-table", sampleData, '#sample-data-table', null);
var grid = $('#sample-table').data("kendoGrid");
if(grid.columns.length > 6 && grid.columns[6].title === 'Column Description'){
var col = grid.columns[6];
col.template = function(dataItem) {
console.log(dataItem['_Column_Description6']);
return dataItem['_Column_Description6'];
}
grid.columns[6] = col;
}
grid.setOptions({
columns: grid.columns,
pageable: false,
groupable: false,
scrollable: false
});
var dialog = $('#sample-data-modal');
var window;
//Make the window.
window = dialog.kendoWindow({
title: sampleDataTitle,
draggable: false,
modal:true,
width: "75%",
height: "75%",
actions: [
"Maximize",
"Close"
],
resize: function () {
},
close: function () {
window = null;
$('#sample-data-modal').remove();
}
}).data("kendoWindow");
window.center();
}
};<file_sep>/js/modelMapping.js
/**
* Created by rocco on 4/10/2018.
* This is the model mapping js file for the ODIN Lite application.
* This will handle everything to do with mapping the tableset to the correct columns.
*/
var odinLite_modelMapping = {
/* Variables */
hasBeenLoaded: false,//Whether this has been loaded before.
columnTemplate: null,
fileIdx: 0,
dateFormat: null,//Date format of the date based fields for formatting a date
/**
* init
* This will initialize ODIN Lite Import Wizard and set it up
*/
init: function() {
$('body').scrollTop(0);
//Empty the spreadsheet data if it was there before
$("#modelMapping_spreadsheet").empty();
//update the preview in case it was not called
//odinLite_fileFormat.updateFilePreview(function(){
kendo.ui.progress($("body"), true);//Wait Message
//Hide the Previous Step
odinLite_fileFormat.hideFileFormat();
//Show the application and initialize
if (via.undef(odinLite_modelMapping.columnTemplate)){
//Get the column template
$.get('./html/modelMapping_columnTemplate.html', function (data) {
kendo.ui.progress($("body"), false);//Wait Message
odinLite_modelMapping.columnTemplate = data;
odinLite_modelMapping.showModelMapping();
odinLite_modelMapping.initUI();
//Get the initial preview
odinLite_modelMapping.updateFilePreview();
odinLite_modelMapping.hasBeenLoaded = true;//Set the loaded variable after first load.
//Enable or diable columns based on the data merge options.
odinLite_modelMapping.checkDataMergeOptions();
}, 'text');
}else{//Template already fetched
kendo.ui.progress($("body"), false);//Wait Message
odinLite_modelMapping.showModelMapping();
odinLite_modelMapping.initUI();
//Get the initial preview
odinLite_modelMapping.updateFilePreview();
odinLite_modelMapping.hasBeenLoaded = true;//Set the loaded variable after first load.
//Enable or diable columns based on the data merge options.
odinLite_modelMapping.checkDataMergeOptions();
}
//});
//Enable/Disable Date Format
var hasDate = false;
for(var i=0;i<odinLite_modelCache.currentEntity.mappedColumnDataType.length;i++){
if(odinLite_modelCache.currentEntity.mappedColumnDataType[i] === 3) {
hasDate = true;
break;
}
}
if(hasDate === true){
$('#modelMapping_dateFormatButton').prop("disabled",false);
}else{
$('#modelMapping_dateFormatButton').prop("disabled",true);
}
},
/**
* checkDataMergeOptions
* This will check to see if the data merge options is enabled and disable/enable columns based on what is checked.
* NOTE: This is no longer used. It has been moved to advanced settings.
*/
checkDataMergeOptions: function() {
//Time Series
if (!via.undef(odinLite_fileFormat.dataMergeOptions.timeSeries) && odinLite_fileFormat.dataMergeOptions.timeSeries === true) {
//get the columns to be disabled
var arr = [];
var savedCol = odinLite_modelCache.currentEntity.savedColumnInfo;
var timeSeriesCol = odinLite_modelCache.currentEntity.staticToTimeSeriesSavedColumnInfo;
for (var i = 0; i < savedCol.length; i++) {
var saved = savedCol[i];
var timeSeries = timeSeriesCol[i];
if (saved.isRequired === true && timeSeries.isRequired === false) {
arr.push(timeSeries);
}
}
for (var i = 0; i < arr.length; i++) {
var columnContainers = $('#modelMappingColumnPanel').find("." + arr[i].id + "_" + via.cleanId(arr[i].name));
for (var j = 0; j < columnContainers.length; j++) {
var colContainer = columnContainers[j];
$(colContainer).find('span .mappingColumnList_input').data('kendoDropDownList').value(null);
$(colContainer).find('span .mappingColumnList_input').data('kendoDropDownList').enable(false);
}
}
}
//Portfolio Indexed Time Series Data
if (!via.undef(odinLite_fileFormat.dataMergeOptions.portIndex) && odinLite_fileFormat.dataMergeOptions.portIndex === true) {
var portIndexTimeSeriesColumns = odinLite_modelCache.currentEntity.timeSeriesToPortIndexTimeSeriesColumns
var requiredColumns = portIndexTimeSeriesColumns[0];
var oneOrMoreColumns = portIndexTimeSeriesColumns[1];
var savedCol = odinLite_modelCache.currentEntity.savedColumnInfo;
for(var i=0;i<savedCol.length;i++){
var saved = savedCol[i];
if (saved.isRequired === true && $.inArray(saved.name, requiredColumns) === -1) {
var columnContainers = $('#modelMappingColumnPanel').find("." + saved.id + "_" + via.cleanId(saved.name));
for (var j = 0; j < columnContainers.length; j++) {
var colContainer = columnContainers[j];
$(colContainer).find('span .mappingColumnList_input').data('kendoDropDownList').value(null);
$(colContainer).find('span .mappingColumnList_input').data('kendoDropDownList').enable(false);
}
}
}
}
},
/**
* initUI
* This will setup the UI elements.
*/
initUI: function(){
via.debug("Using Model Cache Current Database",odinLite_modelCache.currentEntity);
//Remove the columns and redraw using template
$('#modelMappingColumnPanel').empty();
//Check for undefined variables which would lead to error.
if(via.undef(odinLite_modelCache) || via.undef(odinLite_modelCache.currentEntity) || via.undef(odinLite_modelCache.currentEntity.savedColumnInfo,true)){
via.kendoAlert("Model Mapping Error","Please try again.");
return;
}
// create DropDownList for rows
$("#modelMapping_rows").kendoDropDownList({
dataTextField: "text",
dataValueField: "value",
dataSource: odinLite_fileFormat.rowData,
index: 0,
change: function(e){
odinLite_modelMapping.updateFilePreview();
}
});
//Get the column list for the dropdown
var comboArr = odinLite_modelMapping.getColumnListFromTableSet();
//Setup the file list combo
$('#modelMapping_fileList').kendoDropDownList({
dataTextField: "text",
dataValueField: "value",
dataSource: odinLite_fileFormat.getDropdownList(),
value: odinLite_modelMapping.fileIdx,
change: function(a){
odinLite_modelMapping.fileIdx = a.sender.value();
odinLite_modelMapping.updateFilePreview(false);
}
});
//Get the columns to loop through.
var columns = odinLite_modelCache.currentEntity.savedColumnInfo;
for(var i=0;i<columns.length;i++){
var col = columns[i];
this.addModelColumnFromTemplate(col,comboArr);
}
$("#modelMappingColumnPanel").fadeIn();
},
/**
* getColumnListFromTableSet
* This will get the column list for the mapping columns.
*/
getColumnListFromTableSet: function(){
if(via.undef(odinLite_fileFormat.FILE_DATA) || via.undef(odinLite_fileFormat.FILE_DATA.tsEncoded) ||
via.undef(odinLite_fileFormat.FILE_DATA.tsEncoded.columnHeaders)){
via.kendoAlert("Model Mapping Error","No data in uploaded file.");
return null;
}
var columnHeaders = odinLite_fileFormat.FILE_DATA.tsEncoded.columnHeaders;
//var hasHeader = odinLite_fileFormat.FILE_DATA.hasColumnHeader;
var hasHeader = true;//Changed this. I now apply the column header on the server itself.
var comboArr = [{text:"",value:null}];
for(var i=0;i<columnHeaders.length;i++){
var comboObj = null;
if(hasHeader && !via.undef(columnHeaders[i],true)){
comboObj = {
text: columnHeaders[i],
value: columnHeaders[i]
};
}else{
comboObj = {
text: via.toExcelColumnName(i+1),
value: i
};
}
comboArr.push(comboObj);
}
return comboArr;
},
/**
* updateFilePreview
* This will update the preview for model mapping. this will call the server
*/
updateFilePreview: function(){
$('#modelMapping_updatePreviewButton').removeClass('btn-danger');
$('#modelMapping_updatePreviewButton').addClass('btn-success');
kendo.ui.progress($("#modelMapping_spreadsheet"), true);//Wait Message
//Update the formatting options.
var formattingOptions = odinLite_fileFormat.getFormattingOptions();
//Get the Column Mapping
formattingOptions = odinLite_modelMapping.getColumnMappingValues(formattingOptions,false);
//Sheet Names
var sheetNames = null;
if(!via.undef(odinLite_fileFormat.FILE_DATA.sheetNames,true)){
sheetNames = JSON.stringify(odinLite_fileFormat.FILE_DATA.sheetNames);
}
//Clear the total rows
$('#modelMapping_totalRows').empty();
//Get the advanced settings options
var advancedSettingsOptions = odinLite_fileFormat.getAdvancedSettingsOptions();
//Get the file preview from the server based on the settings.
$.post(odin.SERVLET_PATH,
$.extend({
action: 'odinLite.modelMapping.getFilePreview',
type: odinLite_fileFormat.FILE_DATA.type,
files: JSON.stringify(odinLite_fileFormat.FILE_DATA.files),
localFiles: JSON.stringify(odinLite_fileFormat.FILE_DATA.localFiles),
idx: odinLite_modelMapping.fileIdx,
sheetNames: sheetNames,
dateFormat: odinLite_modelMapping.dateFormat,
unionData: JSON.stringify(odinLite_unionFiles.getUnionData()),
overrideUser: odinLite.OVERRIDE_USER
},formattingOptions,advancedSettingsOptions),
function(data, status){
kendo.ui.progress($("#modelMapping_spreadsheet"), false);//Wait Message off
//JSON parse does not like NaN
if(!via.undef(data,true)){
data = JSON.parse(data.replace(/\bNaN\b/g, "null"));
}
if(!via.undef(data,true) && data.success === false){
via.debug("Failure generating Model Mapping preview:", data.message);
via.kendoAlert("Failure generating preview", data.message);
}else{
via.debug("Successful generating Model Mapping preview:", data);
//Get the # of rows to display
var maxRows = $("#modelMapping_rows").data('kendoDropDownList').value();
if(maxRows === "All"){
maxRows = null;
}
//Add the total rows
if(!via.undef(data.tsEncoded)) {
$('#modelMapping_totalRows').html(" of " + kendo.toString(data.tsEncoded.data.length,"#,##0"));
}
var sheetData = odinLite_fileFormat.getSpreadsheetDataFromTableSet(data.tsEncoded,false,false,maxRows);
//Color the headers.
if(!via.undef(sheetData.rows) && sheetData.rows.length > 0) {
var firstRow = sheetData.rows[0];
//Turn red
for (var i=0;i<firstRow.cells.length;i++) {
firstRow.cells[i].background = "#C0C0C0";
}
//Turn green
if(!via.undef(data.updatedColumns) && data.updatedColumns.length > 0) {
for (var i = 0; i < data.updatedColumns.length; i++) {
var idx = data.updatedColumns[i];
firstRow.cells[idx].background = "green";
}
}
}
//Freeze the top Row.
sheetData.frozenRows = 1;
//Insert the sheet preview.
$("#modelMapping_spreadsheet").empty();
$("#modelMapping_spreadsheet").kendoSpreadsheet({
height: '200px',
headerHeight: 20,
//headerWidth: 0,
rows: 20,
toolbar: false,
sheetsbar: false,
columns: null,
sheets: [sheetData]
});
$("#modelMapping_spreadsheet .k-spreadsheet-sheets-bar-add").hide();
$("#modelMapping_spreadsheet .k-link").prop( "disabled", true );
}
},
'text');
},
/**
* addModelColumnFromTemplate
* This will add a column to the model mapping screen
*/
addModelColumnFromTemplate: function(colObj,comboArr){
if(!via.undef(colObj.applyUseColumnList) && !via.undef(colObj.applyUseColumnList.options,true) &&
colObj.applyUseColumnList.options[0]==="FALSE"){
return;
}
var colTemplate = odinLite_modelMapping.columnTemplate + "";
//Edit the column template for this column
//Replace the ID
colTemplate = colTemplate.replace(/{column_idName}/g,colObj.id + "_" + via.cleanId(colObj.name));
//Replace the name
colTemplate = colTemplate.replace(/{column_displayName}/g,colObj.name);
//Replace the type
var dataType = odinLite_modelCache.currentEntity.columnDataMapList[colObj.name]
colTemplate = colTemplate.replace(/{column_dataType}/g,dataType);
//Add the columns to the template
var newColumn = $(colTemplate);
$("#modelMappingColumnPanel").append( newColumn );
//Add the combobox
var nameArray = comboArr.map(function(o){
return o.text;
});
newColumn.find(".mappingColumnList_input").kendoDropDownList({
dataTextField: "text",
dataValueField: "value",
dataSource: comboArr,
index: 0,
value: ($.inArray(colObj.name,nameArray))?colObj.name:null,
change: function(){
$('#modelMapping_updatePreviewButton').removeClass('btn-success');
$('#modelMapping_updatePreviewButton').addClass('btn-danger');;
}
}).data('kendoDropDownList');
if(colObj.isRequired === true){
newColumn.addClass('customColumnBorder');
}
},
/**
* persistFilesToCache
* This will persist the data and complete file upload step.
*/
persistFilesToCache: function(){
//console.log("odinLite_modelCache",odinLite_modelCache);
//console.log("odinLite_uploadFiles",odinLite_uploadFiles);
//console.log("odinLite_fileFormat",odinLite_fileFormat);
//Get the advanced settings options
var advancedSettingsOptions = odinLite_fileFormat.getAdvancedSettingsOptions();
//Will contain the data to be passed to the server. Including the mapping. Includes the advanced settings for processing
var serverParams = advancedSettingsOptions;
//Get the mappings
serverParams = odinLite_modelMapping.getColumnMappingValues(serverParams,true);
if(serverParams == null){return;}
//Get the modelID being uploaded to.
if(via.undef(odinLite_modelCache.currentModel) || via.undef(odinLite_modelCache.currentModel.value)){
via.kendoAlert("Persist Data Error","Cannot find the model ID.");
return;
}
serverParams.modelID = odinLite_modelCache.currentModel.value;
//Get the databaseDir
if(via.undef(odinLite_modelCache.currentEntity) || via.undef(odinLite_modelCache.currentEntity.entityDir)){
via.kendoAlert("Persist Data Error","Cannot find the database directory.");
return;
}
serverParams.entityDir = odinLite_modelCache.currentEntity.entityDir;
//Get the file information
if(via.undef(odinLite_fileFormat.FILE_DATA)){
via.kendoAlert("Persist Data Error","Cannot find the file data needed to save data.");
return;
}
if(via.undef(odinLite_fileFormat.FILE_DATA.files,true)){
via.kendoAlert("Persist Data Error","Cannot find the files needed to save data.");
return;
}
serverParams.type = odinLite_fileFormat.FILE_DATA.type;
serverParams.files = JSON.stringify(odinLite_fileFormat.FILE_DATA.files);
serverParams.localFiles = JSON.stringify(odinLite_fileFormat.FILE_DATA.localFiles);
serverParams.startRow = odinLite_fileFormat.FILE_DATA.startRow;
serverParams.endRow = odinLite_fileFormat.FILE_DATA.endRow;
serverParams.startColumn = odinLite_fileFormat.FILE_DATA.startColumn;
serverParams.endColumn = odinLite_fileFormat.FILE_DATA.endColumn;
serverParams.hasColumnHeader = odinLite_fileFormat.FILE_DATA.hasColumnHeader;
serverParams.unionData = JSON.stringify(odinLite_unionFiles.getUnionData());
serverParams.overrideUser = odinLite.OVERRIDE_USER;
//Model and Entity Info
serverParams.entityDir = odinLite_modelCache.currentEntity.entityDir;
serverParams.modelId = odinLite_modelCache.currentModel.value;
if(!via.undef(odinLite_fileFormat.FILE_DATA.sheetNames,true)){
serverParams.sheetNames = JSON.stringify(odinLite_fileFormat.FILE_DATA.sheetNames);
}
if(!via.undef(odinLite_fileFormat.FILE_DATA.delimType,true)){
serverParams.delimType = odinLite_fileFormat.FILE_DATA.delimType;
}if(!via.undef(odinLite_fileFormat.FILE_DATA.delimType,true)){
serverParams.userDefinedDelim = odinLite_fileFormat.FILE_DATA.userDefinedDelim;
}
if(!via.undef(odinLite_fileFormat.FILE_DATA.textQualifier,true)){
serverParams.textQualifier = odinLite_fileFormat.FILE_DATA.textQualifier;
}
//Date Format
serverParams.dateFormat = odinLite_modelMapping.dateFormat;
//Add the server location
serverParams.action = 'odinLite.modelMapping.persistFilesToCache';
//Add the override user
serverParams.overrideUser = odinLite.OVERRIDE_USER;
/**************************************/
/* Call to the server for persisting */
odin.progressBar("Persisting Data",0,"Initializing...");
var intervalId = setInterval(function(){
odinLite_modelMapping.getCurrentProgress();
},1000);
$.post(odin.SERVLET_PATH,
serverParams,
function(data, status){
odin.progressBar(null,100,null,true);
clearInterval(intervalId);
if(!via.undef(data,true) && data.success === false){
via.debug("Persist Failure:", data);
via.kendoAlert("Persist Failure", data.message);
}else{
via.debug("Persist Successful", data);
//Review the errors and return home when done.
$('#modelMappingPanel').hide();
odinLite_modelMapping.reviewPersistErrors(data, function(){
odinLite.loadApplicationHome();
});
}
},
'json');
},
/**
* getCurrentProgress
* This will get the current progress of the persist
*/
getCurrentProgress: function(){
$.post(odin.SERVLET_PATH,
{
action: 'odinLite.modelMapping.getCurrentProgress'
},
function(data){
if(!via.undef(data) && !via.undef(data.currentProgress)){
odin.progressBar("Persisting Data",data.currentProgress[1],data.currentProgress[0]);
}
},
'json');
},
/**
* getColumnMappingValues
* This will contain the mapping data for the columns to be sent to the server for persisting.
*/
getColumnMappingValues: function(serverParams,emptyCheck){
serverParams.mappingsNames = [];
serverParams.mappingsValues = [];
serverParams.dataTypes = [];
serverParams.fileOverrideDataTypes = odinLite_fileFormat.FILE_DATA.tsEncoded.columnDataTypes;
var allDataTypes = odinLite_modelCache.currentEntity.mappedColumnDataType;
//Get the column mapping info
var columns = odinLite_modelCache.currentEntity.savedColumnInfo;
var container = $('#modelMappingColumnPanel');
var hasRequired = false;
//Time Series To Port Index Merge
var timeSeriesToPortIndexMerge = via.undef(odinLite_fileFormat.dataMergeOptions.portIndex,true)?false:odinLite_fileFormat.dataMergeOptions.portIndex;
if(timeSeriesToPortIndexMerge){
var idx = 0;
var hasOptional = false;
for (var i = 0; i < columns.length; i++) {
var colInfo = columns[i];
var columnContainers = container.find("." + colInfo.id + "_" + via.cleanId(colInfo.name));
for (var j = 0; j < columnContainers.length; j++) {
var colContainer = columnContainers[j];
var mapping_dd = $(colContainer).find('span .mappingColumnList_input').data('kendoDropDownList');
if (!via.undef(mapping_dd)) {
if(emptyCheck === true){//Check for unmapped.
//Required
if(via.undef(odinLite_modelCache.currentEntity.timeSeriesToPortIndexTimeSeriesColumns)){
via.kendoAlert("Mapping Error", "Cannot find required columns for Time Series To Port Index Merge.");
return null;
}else if($.inArray(colInfo.name,odinLite_modelCache.currentEntity.timeSeriesToPortIndexTimeSeriesColumns[0]) !== -1 &&
via.undef(mapping_dd.value(), true)){
via.kendoAlert("Mapping Error", "Choose a mapping column for " + colInfo.name + ".");
return null;
}
//Optional
if(!via.undef(odinLite_modelCache.currentEntity.timeSeriesToPortIndexTimeSeriesColumns) &&
$.inArray(colInfo.name,odinLite_modelCache.currentEntity.timeSeriesToPortIndexTimeSeriesColumns[1]) !== -1 &&
!via.undef(mapping_dd.value(),true)){
hasOptional = true;
}
}
if (!via.undef(mapping_dd.value(), true)) {
serverParams.mappingsNames.push(colInfo.name);
serverParams.mappingsValues.push(mapping_dd.value());
serverParams.dataTypes.push(allDataTypes[idx]);
serverParams.fileOverrideDataTypes[odinLite_modelMapping.getColumnIdx(mapping_dd.value())] = allDataTypes[idx];//This is the override data types to use for preview.
}
idx++;
}
}
}
if(hasOptional === false && emptyCheck === true){
via.kendoAlert("Mapping Error", "Choose at least one optional column.");
return null;
}
}else { //All other types
var timeSeriesMerge = via.undef(odinLite_fileFormat.dataMergeOptions.timeSeries,true)?false:odinLite_fileFormat.dataMergeOptions.timeSeries;
if (timeSeriesMerge === true) {
columns = odinLite_modelCache.currentEntity.staticToTimeSeriesSavedColumnInfo;
}
var idx = 0;
for (var i = 0; i < columns.length; i++) {
var colInfo = columns[i];
var columnContainers = container.find("." + colInfo.id + "_" + via.cleanId(colInfo.name));
for (var j = 0; j < columnContainers.length; j++) {
var colContainer = columnContainers[j];
var mapping_dd = $(colContainer).find('span .mappingColumnList_input').data('kendoDropDownList');
//if(!via.undef(mapping_dd) && !via.undef(mapping_dd.value())){
if (!via.undef(mapping_dd)) {
//For type 3 - in static merge
if ($('#modelMapping_timeSeriesMerge').prop('checked') === true && odinLite_modelCache.currentEntity.tableIndexType === 3 && emptyCheck === true && colInfo.isRequired && !via.undef(mapping_dd.value(), true)) {
hasRequired = true;
}else if(emptyCheck === true && via.undef(mapping_dd.value(), true) && colInfo.isRequired){
via.kendoAlert("Mapping Error", "Choose a mapping column for " + colInfo.name + ".");
return null;
}
if (!via.undef(mapping_dd.value(), true)) {
serverParams.mappingsNames.push(colInfo.name);
serverParams.mappingsValues.push(mapping_dd.value());
serverParams.dataTypes.push(allDataTypes[idx]);
serverParams.fileOverrideDataTypes[odinLite_modelMapping.getColumnIdx(mapping_dd.value())] = allDataTypes[idx];//This is the override data types to use for preview.
}
idx++;
}
}
}
//For table type 3 only - error if no required columns are checked.
if ($('#modelMapping_timeSeriesMerge').prop('checked') === true && odinLite_modelCache.currentEntity.tableIndexType === 3 && hasRequired === false && emptyCheck === true) {
via.kendoAlert("Mapping Error", "Choose at least one required column.");
return null;
}
}
serverParams.mappingsNames = JSON.stringify(serverParams.mappingsNames);
serverParams.mappingsValues = JSON.stringify(serverParams.mappingsValues);
serverParams.dataTypes = JSON.stringify(serverParams.dataTypes);
serverParams.fileOverrideDataTypes = JSON.stringify(serverParams.fileOverrideDataTypes);
return serverParams;
},
/**
* reviewPersistErrors
* This will bring up the review screen for persist errors.
*/
reviewPersistErrors: function(data, callbackFn){
//Reset
$('#modelMapping_errorsFound').hide();
$('#modelMapping_noErrorsFound').hide();
if(!via.undef($('#modelMapping_errorTSList').data('kendoDropDownList'))){
$('#modelMapping_errorTSList').data('kendoDropDownList').destroy();
$('#modelMapping_errorTSList').empty();
}
if(!via.undef(data.isErrors) && data.isErrors === true){
$('#modelMapping_reviewErrorsButton').show();
var comboArray = [];
for(var i=0;i<data.errorSetsEncoded.length;i++){
comboArray.push({ text: "Exception Data " + (i+1), value: i });
}
//Setup the error list combo
$('#modelMapping_errorTSList').kendoDropDownList({
dataTextField: "text",
dataValueField: "value",
dataSource: comboArray,
value: odinLite_modelMapping.fileIdx,
change: function(a){
//odinLite_modelMapping.fileIdx = a.sender.value();
//odinLite_modelMapping.updateFilePreview(false);
updateSheet(data.errorSetsEncoded[a.sender.value()]);
}
});
//Show the first sheet
$('#modelMapping_errorsFound').show();
$('#modelMappingErrorsPanel').fadeIn();
updateSheet(data.errorSetsEncoded[0]);
}else{//Everything uploaded fine.
$('#modelMapping_noErrorsFound').show();
$('#modelMappingErrorsPanel').fadeIn();
}
//Setup the event for the button.
$( ".modelMapping_reviewErrorsButton" ) .off();
$( ".modelMapping_reviewErrorsButton" ).one( "click", function() {
if(!via.undef(callbackFn)){
callbackFn(data);
}
});
function updateSheet(tsEncoded){
var sheetData = odinLite_fileFormat.getSpreadsheetDataFromTableSet(tsEncoded,false,false);
//Insert the sheet preview.
if(!via.undef($("#modelMapping_errorSpreadsheet").data('kendoSpreadsheet'))){
$("#modelMapping_errorSpreadsheet").data('kendoSpreadsheet').destroy();
}
$("#modelMapping_errorSpreadsheet").empty();
$("#modelMapping_errorSpreadsheet").kendoSpreadsheet({
height: '200px',
headerHeight: 20,
//headerWidth: 0,
rows: 20,
toolbar: false,
sheets: [sheetData]
});
$("#modelMapping_errorSpreadsheet .k-spreadsheet-sheets-bar-add").hide();
$("#modelMapping_errorSpreadsheet .k-link").prop( "disabled", true );
}
},
/**
* dateFormatWindow
* This will open the date format window
*/
dateFormatWindow: function(){
//Get the window template
$.get("./html/dateFormatWindow.html", function (dateFormatWindowTemplate) {
$('#odinLite_dateFormatWindow').remove();
$('body').append(dateFormatWindowTemplate);
//Make the window.
var dateFormatWindow = $('#odinLite_dateFormatWindow').kendoWindow({
title: "Date Format",
draggable: false,
resizable: false,
width: "340px",
height: "175px",
modal: true,
close: true,
actions: [
"Close"
],
close: function () {
dateFormatWindow = null;
$('#odinLite_dateFormatWindow').remove();
}
}).data("kendoWindow");
dateFormatWindow.center();
//Date Columns
$("#modelMapping_dateColumnDisplay").empty();
var dateColumns = [];
for(var i=0;i<odinLite_modelCache.currentEntity.mappedColumnDataType.length;i++){
if(odinLite_modelCache.currentEntity.mappedColumnDataType[i] === 3) {
dateColumns.push(odinLite_modelCache.currentEntity.mappedColumnDisplay[i]);
}
}
$("#modelMapping_dateColumnDisplay").html("Applies to date based column(s): "+ (dateColumns.join(", ")));
//Date format box.
$('#modelMapping_dateFormatList').kendoComboBox({
dataTextField: "text",
dataValueField: "value",
autoWidth: true,
dataSource: odinLite_fileFormat.FILE_DATA.dateFormats,
change: function(e){
//odinLite_modelMapping.dateFormat = e.sender.value();
}
});
//Button Events
$('.modelMapping_dateFormatButton').click(function(){
//Set the format
odinLite_modelMapping.dateFormat = $('#modelMapping_dateFormatList').data('kendoComboBox').value();
//Update the preview
odinLite_modelMapping.updateFilePreview();
//close the window
dateFormatWindow.close();
});
//Shut off the wait
kendo.ui.progress($("body"), false);//Wait Message
});//End Template fetch
},
/**
* getColumnIdx
* This will return the index of the column
*/
getColumnIdx: function(colName){
var idx = -1;
if(odinLite_fileFormat.FILE_DATA.hasColumnHeader === true) {
idx = odinLite_fileFormat.FILE_DATA.tsEncoded.columnHeaders.indexOf(colName);
}else{
return colName;
}
return idx;
},
/**
* hideModelMapping
* This will hide file format
*/
hideModelMapping: function(){
$('#fileFormatPanel').hide();
},
/**
* showModelMapping
* This will hide file format
*/
showModelMapping: function(){
$('#modelMappingPanel').show();
},
/**
* showModelMapping
* This will hide file format
*/
hideModelMapping: function(){
$('#modelMappingPanel').hide();
$('#modelMappingColumnPanel').hide();
}
};<file_sep>/js/userTour.js
var userTour = {
/* Tour of the Application Home Page */
appPageTour: new Tour({
storage : false,
backdrop: false
}),
/* Tour of the Home Page */
homeTour: new Tour({
storage : false,
backdrop: false
}),
/* Tour of Account Settings */
accountSettingsTour: new Tour({
storage : false,
backdrop: false
}),
/* Tour of the Template Page */
templateTour: new Tour({
storage : false,
backdrop: true
}),
/* Tour of the Browsing for files and loading to site */
loadTour: new Tour({
storage : false,
backdrop: false
}),
/* Tour of Import Wizard */
formattingTour: new Tour({
storage : false,
backdrop: false
}),
/* Tour of Import Wizard Column Mapping */
modelMappingTour: new Tour({
storage : false,
backdrop: false
}),
/* Tour of managing the data */
manageDataTour: new Tour({
storage : false,
backdrop: true
}),
initAppPageTour: function(){
userTour.appPageTour.addSteps([
{
element: ".tour-step.app-page-tour-step-1",
placement: "left",
title: "List of Applications",
content: "Once you've signed up for packages in the upper right you will see the list of applications available below.<br></br>You can select <b>All</b> to list all of them or <b>Grouped</b> to see the applications grouped by functionality.",
animation: true
},
{
element: ".tour-step.home-tour-step-4",
placement: "left",
title: "Selecting Packages",
content: "Here is where you can subscribe to <b>FREE</b> or <b>PAID</b> report packages you're interested in.",
animation: true
},
{
element: ".tour-step.home-tour-step-5",
placement: "left",
title: "More Help",
content: "This help button will take you to the Help Guide. Use this in conjunction with the <b>Application Overview</b> available when you select an Application.",
animation: true
},
{
element: ".tour-step.home-tour-step-6",
placement: "left",
title: "Messages",
content: "This will contain messages that are specific to your account and system-related alerts.",
animation: true
},
{
element: ".tour-step.home-tour-step-7",
placement: "left",
title: "User Settings",
content: "Click here to view/edit your user settings, billing information and password. It also provides a section to <b>Submit a Support Ticket</b>.",
animation: true,
onNext: function(tour){
}
}
]);
userTour.appPageTour.init();
userTour.appPageTour.start(true);
},
initTour: function(){
userTour.homeTour.addSteps([
{
element: ".imageDisplayButton",
placement: "bottom",
title: "Application Overview",
content: "Click here to get a detailed overview of the selected Application.",
animation: true
},
{
element: ".tour-step.home-tour-step-1",
placement: "bottom",
title: "Uploading Data",
content: "The SAYS Platform provides tools designed to easily upload data from any third-party platform including custom Excel/Text files. <br></br>For custom data upload the system provides Data Model specific downloadable Excel templates.",
animation: true
},
{
element: ".tour-step.home-tour-step-2",
placement: "bottom",
title: "Managing Data",
content: "Data uploaded to your profile can viewed, edited or deleted. It also allows for download of your data in Excel and Text formats.",
animation: true
},
{
element: ".tour-step.home-tour-step-3",
placement: "bottom",
title: "Generating Reports",
content: "Use the Application UI to select/edit/save settings and generate custom reports.",
animation: true
},
{
element: ".tour-step.home-tour-step-4",
placement: "left",
title: "Selecting Packages",
content: "Here is where you can subscribe to <b>FREE</b> or <b>PAID</b> report packages you're interested in.",
animation: true
},
{
element: ".tour-step.home-tour-step-5",
placement: "left",
title: "More Help",
content: "This help button will take you to the Help Guide. Use this in conjunction with the <b>Application Overview</b> available when you select an Application.",
animation: true
},
{
element: ".tour-step.home-tour-step-6",
placement: "left",
title: "Messages",
content: "This will contain messages that are specific to your account and system-related alerts.",
animation: true
},
{
element: ".tour-step.home-tour-step-7",
placement: "left",
title: "User Settings",
content: "Click here to view/edit your user settings, billing information and password. It also provides a section to <b>Submit a Support Ticket</b>.",
animation: true,
onNext: function(tour){
// document.getElementById("accountButton").click();
// userTour.initAccountSettingsTour();
}
},
{
element: ".tour-step.home-tour-step-8",
placement: "bottom",
title: "Uploading Data",
content: "Click \"Upload Data\" and follow along with the green tour buttons to continue with the tour.",
animation: true
}
]);
userTour.homeTour.init();
userTour.homeTour.start(true);
},
/* No longer used
initAccountSettingsTour: function(){
//Helper function to cycle through the nav pills on account settings page
function nextSettingScreen(linkId){
var current = $(".active");
//Remove active screen
current.eq(0).removeClass("active").addClass("");
current.eq(1).removeClass("active").addClass("");
$("#li_"+linkId).addClass("active");
$("#"+linkId).addClass("active");
};
userTour.accountSettingsTour.addSteps([
{
element: ".tour-step.tour-account-settings-step",
placement: "bottom",
title: "User Settings",
content: "This shows your basic account settings like First Name, Last Name, and user name.",
animation: true,
onNext: function(tour){ nextSettingScreen("accountSettings_reportPackages");}
},
{
element: ".tour-step.tour-account-settings-step",
placement: "bottom",
title: "Reporting Packages",
content: "Reporting Packages",
animation: true,
onNext: function(tour){ nextSettingScreen("accountSettings_billing");}
},
{
element: ".tour-step.tour-account-settings-step",
placement: "bottom",
title: "Billing",
content: "Billing",
animation: true,
onNext: function(tour){ nextSettingScreen("accountSettings_settings");}
},
{
element: ".tour-step.tour-account-settings-step",
placement: "bottom",
title: "Settings",
content: "Settings",
animation: true,
onNext: function(tour){ nextSettingScreen("accountSettings_password");}
},
{
element: ".tour-step.tour-account-settings-step",
placement: "bottom",
title: "Password",
content: "Password",
animation: true,
onNext: function(tour){ nextSettingScreen("accountSettings_support");}
},
{
element: ".tour-step.tour-account-settings-step",
placement: "bottom",
title: "Support",
content: "Support",
animation: true,
onNext: function(tour){odinLite.loadHome();}
},
{
element: ".tour-step.tour-step-five",
placement: "bottom",
title: "Uploading Data",
content: "Now we will show you how to upload data.",
animation: true,
onNext: function(tour){
odinLite.loadModelCacheApplication();
userTour.initTemplateTour();
}
},
{}
]);
userTour.accountSettingsTour.init();
userTour.accountSettingsTour.start(true);
},
*/
initStandardUploadTour: function(){
userTour.templateTour.addSteps([
{
element: ".tour-step.template-tour-step-1",
placement: "right",
title: "Selecting a Data Model",
content: "For each application there are different data inputs that are needed.<br></br>For example, the Return/Risk Analysis application would need time-series of \"Investment Returns\" to be uploaded.",
animation: true
},
{
element: ".tour-step.template-tour-step-2",
placement: "right",
title: "Required vs. Optional Models",
content: "The Data Models under Required are needed for any Application core analysis or report generation. Optional Data Models are required or not required based on the user's setting selection under Application Interface.",
animation: true
},
{
element: ".tour-step.template-tour-step-3",
placement: "right",
title: "Structure of a Data Model",
content: "A Data Model has a Row and Column Structure similar to a Relational Database Table. Certain Data Model Column(s) are designated as primary keys to keep records unique. Some Data Models allow adding one or more user-defined Custom Columns.",
animation: true
},
{
element: ".tour-step.template-tour-step-4",
placement: "bottom",
title: "Data Model Description",
content: "Review the description text carefully to understand the data requirements for each Data Model.",
animation: true
},
{
element: ".tour-step.template-tour-step-5",
placement: "bottom",
title: "View Sample Data",
content: "Click this button to view sample data for a data model. This should help provide further insight to the data requirements for each Data Model.",
animation: true
},
{
element: ".tour-step.template-tour-step-6",
placement: "bottom",
title: "View Data Column Structure",
content: "Click this button to view the list of required/optional, null/non-null, custom/non-custom and other attributes for each data columns associated with this data model.<br></br>Explanations of data types and descriptions of the columns are provided.",
animation: true
},
{
element: ".tour-step.template-tour-step-7",
placement: "bottom",
title: "Platform Selection",
content: "SAYS has a flexible upload interface that allows upload of data files from any third-party and/or in-house platform.<br></br>For certain Data Models, SAYS is pre-configured (mapping and validation) to accept certain types of file extracts from certain widely used third-party platforms/systems. If required, we work with clients to integrate third-party platforms that are not currently supported.",
animation: true,
onNext: function(tour){
var nextButton = $(".modelDefinition_choosePlatformButton");
nextButton[0].click();
}
},
{
element: ".tour-step.template-tour-step-8",
placement: "left",
title: "Edit the Data Model",
content: "Prior to initial data upload, users can Edit the Data Model.<br></br>Certain column attributes such as Text Length, Use Column, Column Name, Apply FX Return, Upload Value In Percentage, Is Null Value Allowed and other column attributes can be configured.<br></br>Once data has been loaded for the Data Model, the system will not allow updates to the Data Model structure. To Edit structure, all data persisted under the Data Model should be deleted in the <b>Manage Data</b> section of the Application.",
animation: true,
onNext: function(tour){
var nextButton = $(".template-tour-step-8");
nextButton[0].click();
}
},
{
element: ".tour-step.template-tour-step-9",
placement: "left",
title: "Sample Data Column",
content: "Relevant Attribute information related to each column of the selected Data Model is available for review and update in certain cases.<br></br>Click the blue question mark for details on each column.",
animation: true,
onNext: function(tour){
// Hit cancel button to get to the upload button
odinLite_modelCache.displaySelectedModelTemplate()
}
},
{
element: ".tour-step.template-tour-step-10",
placement: "left",
title: "Uploading Data",
content: "Once you have reviewed, customized and saved the Data Model structure, the system will take you to the Upload Screen.<br></br>If Data Model structure has already been saved, you can skip to this step.",
animation: true
}
]);
var modelTree = $("#modelCacheSelection_treeview");
//Application Name, e.g. Composite Reporting
var reportTree = modelTree.find(".k-top").eq(0);
reportTree.addClass("tour-step template-tour-step-1");
//Required template tree
var requiredTemplates = modelTree.find(".k-top").eq(1);
requiredTemplates.addClass("tour-step template-tour-step-2");
var modelGroup = modelTree.find(".k-group").eq(1);
var modelList = modelGroup.find("li").eq(0);
var requiredList = modelList.find("ul").eq(0);
var requiredFirstItem = requiredList.find("li").eq(0);
//Select the template so the modelCache field gets populated
var firstItem = requiredFirstItem.find(".k-in").eq(0);
firstItem.click();
firstItem.addClass("tour-step template-tour-step-3");
userTour.templateTour.init();
userTour.templateTour.start(true);
},
initCustomColumnUploadTour: function(modelExample){
userTour.templateTour.addSteps([
{
element: ".tour-step.template-tour-step-1",
placement: "right",
title: "Selecting a Data Model",
content: "For each application there are different data inputs that are needed.<br></br>For example, the Return/Risk Analysis application would need time-series of \"Investment Returns\" to be uploaded.",
animation: true
},
{
element: ".tour-step.template-tour-step-2",
placement: "right",
title: "Required vs. Optional Models",
content: "The Data Models under Required are needed for any Application core analysis or report generation. Optional Data Models are required or not required based on the user's setting selection under Application Interface.",
animation: true
},
{
element: ".tour-step.template-tour-step-3",
placement: "right",
title: "Structure of a Data Model",
content: "A Data Model has a Row and Column Structure similar to a Relational Database Table. Certain Data Model Column(s) are designated as primary keys to keep records unique. Some Data Models allow adding one or more user-defined Custom Columns.",
animation: true
},
{
element: ".tour-step.template-tour-step-4",
placement: "bottom",
title: "Data Model Description",
content: "Review the description text carefully to understand the data requirements for each Data Model.",
animation: true
},
{
element: ".tour-step.template-tour-step-5",
placement: "bottom",
title: "View Sample Data",
content: "Click this button to view sample data for a data model. This should help provide further insight to the data requirements for each Data Model.",
animation: true
},
{
element: ".tour-step.template-tour-step-6",
placement: "bottom",
title: "View Data Column Structure",
content: "Click this button to view the list of required/optional, null/non-null, custom/non-custom and other attributes for each data columns associated with this data model.<br></br>Explanations of data types and descriptions of the columns are provided.",
animation: true
},
{
element: ".tour-step.template-tour-step-7",
placement: "bottom",
title: "Platform Selection",
content: "SAYS has a flexible upload interface that allows upload of data files from any third-party and/or in-house platform.<br></br>For certain Data Models, SAYS is pre-configured (mapping and validation) to accept certain types of file extracts from certain widely used third-party platforms/systems. If required, we work with clients to integrate third-party platforms that are not currently supported.",
animation: true,
onNext: function(tour){
var nextButton = $(".modelDefinition_choosePlatformButton");
nextButton[0].click();
}
},
{
element: ".tour-step.template-tour-step-8",
placement: "left",
title: "Edit the Data Model",
content: "Prior to initial data upload, users can Edit the Data Model.<br></br>Certain column attributes such as Text Length, Use Column, Column Name, Apply FX Return, Upload Value In Percentage, Is Null Value Allowed and other column attributes can be configured.<br></br>Once data has been loaded for the Data Model, the system will not allow updates to the Data Model structure. To Edit structure, all data persisted under the Data Model should be deleted in the <b>Manage Data</b> section of the Application.",
animation: true,
onNext: function(tour){
var nextButton = $(".template-tour-step-8");
nextButton[0].click();
}
},
{
element: ".tour-step.customColumnButton",
placement: "bottom",
title: "Adding a Custom Column",
content: "Certain Data Models allow for one or more Custom Columns to be defined. Click <b>Add Custom Column</b> to define the type of custom column to be added. It will then allow the attributes of the custom column to be configured. Users can also delete an existing Custom Column assumming no data is persisted in the Data Model.",
animation: true
},
{
element: ".tour-step.template-tour-step-9",
placement: "left",
title: "Sample Data Column",
content: "Relevant Attribute information related to each column of the selected Data Model is available for review and update in certain cases.<br></br>Click the blue question mark for details on each column.",
animation: true,
onNext: function(tour){
// Hit cancel button to get to the upload button
odinLite_modelCache.displaySelectedModelTemplate()
}
},
{
element: ".tour-step.template-tour-step-10",
placement: "left",
title: "Uploading Data",
content: "Once you have reviewed, customized and saved the Data Model structure, the system will take you to the Upload Screen.<br></br>If Data Model structure has already been saved, you can skip to this step.",
animation: true
}
]);
var modelTree = $("#modelCacheSelection_treeview");
//Application Name, e.g. Composite Reporting
var reportTree = modelTree.find(".k-top").eq(0);
reportTree.addClass("tour-step template-tour-step-1");
//Required template tree
var requiredTemplates = modelTree.find(".k-top").eq(1);
requiredTemplates.addClass("tour-step template-tour-step-2");
//Example of a data template
var sampleTemplate = modelTree.find(".k-top").eq(2);
var modelGroup = modelTree.find(".k-group").eq(1);
var modelList = modelGroup.find("li").eq(0);
var requiredList = modelList.find("ul").eq(0);
var requiredFirstItem = requiredList.find("li").eq(0);
//Select the template so the modelCache field gets populated - specific for model with custom column
//TODO: get model text specific for the data model if it has custom columns
var dataModelText = modelExample;
var dataModelExample = $('span:contains('+ dataModelText + ')');
dataModelExample.click();
dataModelExample.addClass("tour-step template-tour-step-3");
userTour.templateTour.init();
userTour.templateTour.start(true);
},
initSupportedPlatformUploadTour: function(modelExample){
userTour.templateTour.addSteps([
{
element: ".tour-step.template-tour-step-1",
placement: "right",
title: "Selecting a Data Model",
content: "For each application there are different data inputs that are needed.<br></br>For example, the Return/Risk Analysis application would need time-series of \"Investment Returns\" to be uploaded.",
animation: true
},
{
element: ".tour-step.template-tour-step-2",
placement: "right",
title: "Required vs. Optional Models",
content: "The Data Models under Required are needed for any Application core analysis or report generation. Optional Data Models are required or not required based on the user's setting selection under Application Interface.",
animation: true
},
{
element: ".tour-step.template-tour-step-3",
placement: "right",
title: "Structure of a Data Model",
content: "A Data Model has a Row and Column Structure similar to a Relational Database Table. Certain Data Model Column(s) are designated as primary keys to keep records unique. Some Data Models allow adding one or more user-defined Custom Columns.",
animation: true
},
{
element: ".tour-step.template-tour-step-4",
placement: "bottom",
title: "Data Model Description",
content: "Review the description text carefully to understand the data requirements for each Data Model.",
animation: true
},
{
element: ".tour-step.template-tour-step-5",
placement: "bottom",
title: "View Sample Data",
content: "Click this button to view sample data for a data model. This should help provide further insight to the data requirements for each Data Model.",
animation: true
},
{
element: ".tour-step.template-tour-step-6",
placement: "bottom",
title: "View Data Column Structure",
content: "Click this button to view the list of required/optional, null/non-null, custom/non-custom and other attributes for each data columns associated with this data model.<br></br>Explanations of data types and descriptions of the columns are provided.",
animation: true
},
{
element: ".tour-step.template-tour-step-7",
placement: "bottom",
title: "Platform Selection",
content: "SAYS has a flexible upload interface that allows upload of data files from any third-party and/or in-house platform.<br></br>For certain Data Models, SAYS is pre-configured (mapping and validation) to accept certain types of file extracts from certain widely used third-party platforms/systems. If required, we work with clients to integrate third-party platforms that are not currently supported.",
animation: true
},
{
element: ".tour-step.template-tour-step-7a",
placement: "bottom",
title: "Selecting Your Platform",
content: "Depending on the Data Model, SAYS has a list of <b>supported third-party platforms</b> that the user can select from for data upload.<br></br>If your platform is not supported, select <b>Custom</b> and proceed. We also work with clients to integrate third-party platforms that are not currently supported. ",
animation: true,
},
{
element: ".tour-step.template-tour-step-7b",
placement: "bottom",
title: "Platform Upload Steps",
content: "Depending on the platform selection, SAYS is pre-configured to load certain types of Data Extract files which are provided as Options or Multi-Step upload process.<br></br>Click the blue help button to determine the third-party platform extract file and format matches the one that is supported by the system. We also work with clients to integrate third-party platform Data Extracts that are not currently supported.",
animation: true,
onNext: function(tour){
var nextButton = $(".modelDefinition_choosePlatformButton");
nextButton[0].click();
}
},
{
element: ".tour-step.template-tour-step-8",
placement: "left",
title: "Edit the Data Model",
content: "Prior to initial data upload, users can Edit the Data Model.<br></br>Certain column attributes such as Text Length, Use Column, Column Name, Apply FX Return, Upload Value In Percentage, Is Null Value Allowed and other column attributes can be configured.<br></br>Once data has been loaded for the Data Model, the system will not allow updates to the Data Model structure. To Edit structure, all data persisted under the Data Model should be deleted in the <b>Manage Data</b> section of the Application.",
animation: true,
onNext: function(tour){
var nextButton = $(".template-tour-step-8");
nextButton[0].click();
}
},
{
element: ".tour-step.customColumnButton",
placement: "bottom",
title: "Adding a Custom Column",
content: "Certain Data Models allow for one or more Custom Columns to be defined. Click <b>Add Custom Column</b> to define the type of custom column to be added. It will then allow the attributes of the custom column to be configured. Users can also delete an existing Custom Column assumming no data is persisted in the Data Model.",
animation: true
},
{
element: ".tour-step.template-tour-step-9",
placement: "left",
title: "Sample Data Column",
content: "Relevant Attribute information related to each column of the selected Data Model is available for review and update in certain cases.<br></br>Click the blue question mark for details on each column.",
animation: true,
onNext: function(tour){
// Hit cancel button to get to the upload button
odinLite_modelCache.displaySelectedModelTemplate()
}
},
{
element: ".tour-step.template-tour-step-10",
placement: "left",
title: "Uploading Data",
content: "Once you have reviewed, customized and saved the Data Model structure, the system will take you to the Upload Screen.<br></br>If Data Model structure has already been saved, you can skip to this step.",
animation: true
}
]);
var modelTree = $("#modelCacheSelection_treeview");
//Application Name, e.g. Composite Reporting
var reportTree = modelTree.find(".k-top").eq(0);
reportTree.addClass("tour-step template-tour-step-1");
//Required template tree
var requiredTemplates = modelTree.find(".k-top").eq(1);
requiredTemplates.addClass("tour-step template-tour-step-2");
//Example of a data template
var sampleTemplate = modelTree.find(".k-top").eq(2);
var modelGroup = modelTree.find(".k-group").eq(1);
var modelList = modelGroup.find("li").eq(0);
var requiredList = modelList.find("ul").eq(0);
var requiredFirstItem = requiredList.find("li").eq(0);
//Select the template so the modelCache field gets populated - specific for model with custom column
//TODO: get model text specific for the data model if it has custom columns
var dataModelText = modelExample;
var dataModelExample = $('span:contains('+ dataModelText + ')');
dataModelExample.click();
dataModelExample.addClass("tour-step template-tour-step-3");
userTour.templateTour.init();
userTour.templateTour.start(true);
},
initUploadTour: function(){
$.get(odin.SERVLET_PATH + "/ODIN_LITE/GET_PACKAGE_TOUR?packageId=" + odinLite.currentApplicationPackage,
function (data) {
if(via.undef(data)){ return; }
var jsonResponse = JSON.parse(data);
var tourList = jsonResponse.tourText.split(";");
if (tourList.length > 0){
var tourType = tourList[0];
var modelExample = tourList[1];
if (tourType === 'SupportedPlatformsUploadTour'){
userTour.initSupportedPlatformUploadTour(modelExample);
} else if (tourType === 'CustomColumnUploadTour'){
userTour.initCustomColumnUploadTour(modelExample);
} else {
userTour.initStandardUploadTour();
}
}
}
);
},
initManageDataTour: function(){
userTour.manageDataTour.addSteps([
{
element: ".tour-step.tour-step-manage-data-1",
placement: "right",
title: "View/Edit/Delete Uploaded Data",
content: "Select the appropiate Data Model and Review uploaded data for accuracy and consistancy.",
animation: true
},
{
element: ".tour-step.tour-step-manage-data-2",
placement: "left",
title: "Data Element Selection",
content: "Depending on the Data Model, time series data is organized by date or identifier and non-time series data/static data is persisted as a StaticDataSet",
animation: true
},
{
element: ".tour-step.tour-step-manage-data-3",
placement: "right",
title: "Execute Custom SQL Queries On Data",
content: "Click this icon to execute simple SQL queries against the uploaded data. The selected data model items create a temporary database that can be queried.",
animation: true
},
{
element: ".tour-step.tour-step-manage-data-4",
placement: "right",
title: "Review and Export Data",
content: "Click this icon to view the file structure of your persisted data. System allows any data files to be extracted as CSV and other formats. Multiple extract files are exported as a ZIP file.",
animation: true
}
]);
var modelTree = $("#manageData_modelTreeview");
//Application Name, e.g. Composite Reporting
var reportTree = modelTree.find(".k-top").eq(0);
reportTree.addClass("tour-step tour-step-manage-data-1");
//Required template tree
//var requiredTemplates = modelTree.find(".k-top").eq(1);
// requiredTemplates.addClass("tour-step tour-step-seven");
//Example of a data template
var sampleTemplate = modelTree.find(".k-top").eq(2);
var modelGroup = modelTree.find(".k-group").eq(1);
var modelList = modelGroup.find("li").eq(0);
var requiredList = modelList.find("ul").eq(0);
var requiredItem = requiredList.find("li").eq(0);
//Select the template so the modelCache field gets populated
var selectedItem = requiredItem.find(".k-in").eq(0);
selectedItem.click();
var modelTable = $("#manageData_tableSelection");
modelTable.addClass("tour-step tour-step-manage-data-2");
userTour.manageDataTour.init();
userTour.manageDataTour.start(true);
}
}
<file_sep>/js/fileFormat.js
/**
* Created by rocco on 3/23/2018.
* This is the import wizard js file for the ODIN Lite application.
* This will handle everything to do with importing uploaded files.
*/
var odinLite_fileFormat = {
/* Variables */
hasBeenLoaded: false,//Whether this has been loaded before.
FILE_DATA: null, //This holds the data for the files.
//Advanced Settings
staticColumns: [], //This will hold all the static columns, their value, and type
mappedColumns: [],
dataMergeOptions: {},
dataManagementPlugin: null,
filterRules: [],
validationRules: [],
loadedReport: null, //holds the name of the currently loaded report.
rowData: [
{text: "50",value:50},
{text: "500",value:500},
{text: "1,000",value:1000},
{text: "2,500",value:2500},
{text: "5,000",value:5000},
{text: "10,000",value:10000},
{text: "20,000",value:20000},
{text: "All Rows",value:"All"}
], //Holds the row variables.
/**
* init
* This will initialize ODIN Lite Import Wizard and set it up
*/
init: function(data){
$('body').scrollTop(0);
//Check to see if this is a Union file. If so handle it
if(odinLite_fileFormat.isUnionFile===true){
odinLite_fileFormat.isUnionFile=false;
//Show the file format panel
odinLite_uploadFiles.hideUploadFiles();
$('#fileFormatPanel').fadeIn();
odinLite_unionFiles.getFileFormatWindow(data);
return;
}
//Reset the union
odinLite_unionFiles.unionFiles = {};
//Empty the preview
$('#import_fileFormat_spreadsheet').empty();
kendo.ui.progress($("body"), true);//Wait Message
odinLite_fileFormat.FILE_DATA = null;
odinLite_fileFormat.clearAdvancedSettings();//Clear advanced settings
odinLite_uploadFiles.hideUploadFiles();
$('.fileFormat_reportName').empty();//Clear the saved report.
//Assign the uploaded files. That way we know what files we are working with.
odinLite_fileFormat.FILE_DATA = data;
odinLite_fileFormat.FILE_DATA.fileIdx = 0;
delete(odinLite_fileFormat.FILE_DATA.message);
delete(odinLite_fileFormat.FILE_DATA.success);
// create DropDownList for rows
$("#import_fileFormat_rows").kendoDropDownList({
dataTextField: "text",
dataValueField: "value",
dataSource: odinLite_fileFormat.rowData,
index: 0,
change: function(e){
odinLite_fileFormat.updateFilePreview();
}
});
//Hide the next button if it is a data management model
if(odinLite_modelCache.dataMgmtModel === odinLite_modelCache.currentEntity.modelId){
$('#fileFormat_nextButton').hide();
$('#fileFormat_exportFilesButton_bottom').show();
$('#fileFormat_exportFilesButton').show();
}else{
$('#fileFormat_exportFilesButton_bottom').hide();
$('#fileFormat_exportFilesButton').hide();
$('#fileFormat_nextButton').show();
}
//Check multiple sheets for excel
odinLite_fileFormat.isMultiSheet = false;
if(!via.undef(odinLite_fileFormat.FILE_DATA.sheetNames) && odinLite_fileFormat.FILE_DATA.sheetNames.length > 1
&& odinLite_fileFormat.FILE_DATA.files.length === 1) {
odinLite_fileFormat.isMultiSheet = true;
odinLite_fileFormat.excelSheetChooser(function(){
//Go to step 1 of the import wizard using the new data
odinLite_fileFormat.initFilePreview(true);//Override the Initial Values
odinLite_fileFormat.hasBeenLoaded = true;//Set the loaded variable after first load.
kendo.ui.progress($("body"), false);//Wait Message
});
}else {
//Go to step 1 of the import wizard using the new data
odinLite_fileFormat.initFilePreview();
odinLite_fileFormat.hasBeenLoaded = true;//Set the loaded variable after first load.
kendo.ui.progress($("body"), false);//Wait Message
}
},
/**
* excelSheetChooser
* This will allow choosing of the sheets the user wants to upload from their excel document.
*/
excelSheetChooser: function(callbackFn){
//Get the window template
$.get("./html/excelSheetChooserWindow.html", function (entityWindowTemplate) {
$('#odinLite_excelSheetChooserWindow').remove();
$('body').append(entityWindowTemplate);
//Make the window.
var excelSheetsWindow = $('#odinLite_excelSheetChooserWindow').kendoWindow({
title: "Excel Sheet Chooser",
draggable: false,
resizable: false,
width: "450px",
height: "325px",
modal: false,
close: false,
actions: [
//"Maximize"
],
close: function () {
excelSheetsWindow = null;
$('#odinLite_excelSheetChooserWindow').remove();
}
}).data("kendoWindow");
excelSheetsWindow.center();
for(var i=0;i<odinLite_fileFormat.FILE_DATA.sheetNames.length;i++) {
var sheetName = odinLite_fileFormat.FILE_DATA.sheetNames[i];
$('#odinLite_excelSheetChooserWindow').find(".sheetList").append(
'<li>'+
'<input type="checkbox" id="sheet'+i+'" class="excelSheetsCheckbox k-checkbox" checked="checked" data-sheet-name="'+ sheetName +'">'+
'<label class="k-checkbox-label" for="sheet'+i+'">'+sheetName+'</label>'+
'</li>');
}
//Button Events
$("#fileFormat_excelSheetsSelectButton").on("click",function(){
$(".excelSheetsCheckbox").prop('checked', true);
});
$("#fileFormat_excelSheetsDeselectButton").on("click",function(){
$(".excelSheetsCheckbox").prop('checked', false);
});
$(".fileFormat_selectExcelSheets").on("click",function(){//Callback function when finished.
//Reset sheets
var selectedSheets = [];
var checkboxes = $(".excelSheetsCheckbox");
for(var i=0;i<checkboxes.length;i++){
var check = checkboxes[i];
if($(check).prop("checked") === true){
selectedSheets.push($(check).data("sheetName"));
}
}
//Assign the selected sheets
if(selectedSheets.length === 0){
via.kendoAlert("Excel Sheet Select","Select at least one sheet to upload.");
return;
}
odinLite_fileFormat.FILE_DATA.sheetNames = selectedSheets;
//Get rid of the window
excelSheetsWindow.close();
$('#odinLite_excelSheetChooserWindow').remove();
//Callback
if(!via.undef(callbackFn)){
callbackFn();
}
});
});
kendo.ui.progress($("body"), false);//Wait Message
},
/**
* advancedSettingsWindow_addColumn
* This is for the add column tab
*/
advancedSettingsWindow_addColumn: function(){
//Dropdown box of columns
var columnList = [];
for(var i=0;i<odinLite_modelCache.currentEntity.mappedColumnDisplay.length;i++){
var col = odinLite_modelCache.currentEntity.mappedColumnDisplay[i];
columnList.push({ text: col, value: col });
}
//Check for data management
if(odinLite_modelCache.dataMgmtModel === odinLite_modelCache.currentEntity.modelId){
columnList = [];
}
$('#fileFormat_addColumn_columnList').kendoComboBox({
dataTextField: "text",
dataValueField: "value",
dataSource: columnList,
value: 0,
change: function(a){
checkTemplateColumn(a.sender.value());
addInputBox(a.sender.value());
}
});
if(!via.undef(columnList) && columnList.length > 0) {
addInputBox(columnList[0].text);
}
//Column Type
$("#fileFormat_addColumn_columnType").kendoDropDownList({
dataTextField: "text",
dataValueField: "value",
autoWidth: true,
index: 0,
dataSource: [
{text:"Assign Value",value:"Assign Value"},
{text:"Extract Value from File/Sheet Name",value:"Extract Value from File/Sheet Name"},
{text:"Multi-Column Operation",value:"Multi-Column Operation"},
{text:"Create Index",value:"Create Index"}
],
change: function(e){
if(e.sender.value() === 'Extract Value from File/Sheet Name') {
$('#fileFormat_testExtractContainer').show();
$('.fileFormat_addColumn_assignContainer').hide();
$('.fileFormat_addColumn_multiContainer').hide();
$('.fileFormat_addColumn_extractContainer').show();
}else if(e.sender.value() === 'Multi-Column Operation') {
$('#fileFormat_testExtractContainer').hide();
$('.fileFormat_addColumn_extractContainer').hide();
$('.fileFormat_addColumn_assignContainer').hide();
$('.fileFormat_addColumn_multiContainer').show();
}else if(e.sender.value() === 'Create Index') {
$('#fileFormat_testExtractContainer').hide();
$('.fileFormat_addColumn_extractContainer').hide();
$('.fileFormat_addColumn_assignContainer').hide();
$('.fileFormat_addColumn_multiContainer').hide();
$("#fileFormat_addColumn_columnList").data("kendoComboBox").value(null);
}else{;
$('#fileFormat_testExtractContainer').hide();
$('.fileFormat_addColumn_extractContainer').hide();
$('.fileFormat_addColumn_multiContainer').hide();
$('.fileFormat_addColumn_assignContainer').show();
}
}
});
/** Data Type **/
var dataTypeList = [];
for(var i=0;i<odinLite_modelCache.currentEntity.compareDataTypes.length;i++){
var col = odinLite_modelCache.currentEntity.compareDataTypes[i];
dataTypeList.push({ text: col, value: col });
}
$('#fileFormat_addColumn_dataType').kendoDropDownList({
dataTextField: "text",
dataValueField: "value",
dataSource: dataTypeList,
index: 0,
change: function(e){
addInputBox($('#fileFormat_addColumn_columnList').data('kendoComboBox').value());
}
});
//Extract - Date format combo
$('#fileFormat_addColumn_dateFormat').kendoComboBox({
dataTextField: "text",
dataValueField: "value",
autoWidth: true,
dataSource: odinLite_fileFormat.FILE_DATA.dateFormats
});
//Multi-column - Operation List
var operationList = [];
for(var i=0;i<odinLite_modelCache.currentEntity.multiColumnOperations.length;i++){
var col = odinLite_modelCache.currentEntity.multiColumnOperations[i];
operationList.push({ text: col, value: col });
}
$('#fileFormat_addColumn_multiColumnOperationType').kendoDropDownList({
dataTextField: "text",
dataValueField: "value",
autoWidth: true,
dataSource: operationList
});
//Multi-column - Header List
var headers = odinLite_modelMapping.getColumnListFromTableSet();
headers.splice(0,1);
$('#fileFormat_addColumn_multiColumnColumnList').kendoMultiSelect({
dataTextField: "text",
dataValueField: "text",
autoWidth: true,
dataSource: headers
});
//Add Column to Grid - Button Click
$(".fileFormat_addColumnButton").on("click",function(){
var colObject = {};
colObject.columnType = $("#fileFormat_addColumn_columnType").data("kendoDropDownList").value();
colObject.columnName = $("#fileFormat_addColumn_columnList").data("kendoComboBox").value();
colObject.type = getCurrentType();
//sanity checks to make sure the column does not already exist
//Check the tableset
/*
if(!via.undef(odinLite_fileFormat.FILE_DATA.tsEncoded) &&
!via.undef(odinLite_fileFormat.FILE_DATA.tsEncoded.columnHeaders) &&
odinLite_fileFormat.FILE_DATA.tsEncoded.columnHeaders.length>0){
for(var i=0;i<odinLite_fileFormat.FILE_DATA.tsEncoded.columnHeaders.length;i++){
if(colObject.columnName === odinLite_fileFormat.FILE_DATA.tsEncoded.columnHeaders[i]){
via.kendoAlert("Add Column Error","Column Name already exists in dataset.");
return;
}
}
}
*/
//check the other static columns
if(!via.undef(odinLite_fileFormat.staticColumns) &&
odinLite_fileFormat.staticColumns.length>0){
for(var i=0;i<odinLite_fileFormat.staticColumns.length;i++){
var staticCol = odinLite_fileFormat.staticColumns[i];
if(colObject.columnName === staticCol.columnName){
via.kendoAlert("Add Column Error","Column Name already exists in static columns.");
return;
}
}
}
//End Column Checks
//Extract
if(colObject.columnType === 'Extract Value from File/Sheet Name'){
colObject.prefix = $('#fileFormat_addColumn_prefix').val();
colObject.suffix = $('#fileFormat_addColumn_suffix').val();
colObject.prefixRegex = $('#fileFormat_addColumn_prefixIsRegex').prop('checked');
colObject.suffixRegex = $('#fileFormat_addColumn_suffixIsRegex').prop('checked');
/*if(via.undef(colObject.prefix,true) && via.undef(colObject.suffix,true)){
via.kendoAlert("Add Column Error","Enter a prefix or a suffix.");
return;
}*/
if(colObject.type===3) {
colObject.dateFormat = $('#fileFormat_addColumn_dateFormat').data('kendoComboBox').value();
}
if(colObject.type===3 && via.undef(colObject.dateFormat)){
via.kendoAlert("Add Column Error","Select a date format.");
return;
}
}else if(colObject.columnType === 'Multi-Column Operation'){
var operationType = $('#fileFormat_addColumn_multiColumnOperationType').data("kendoDropDownList").value();
if(via.undef(operationType,true)){
via.kendoAlert("Add Column Error","Select an operation type.");
return;
}
var columnList = $('#fileFormat_addColumn_multiColumnColumnList').data("kendoMultiSelect").value();
if(via.undef(operationType,true) || columnList.length === 0){
via.kendoAlert("Add Column Error","Select at least one column.");
return;
}
/*if(columnList.length < 2 && operationType !== 'Inverse Value'){
via.kendoAlert("Add Column Error","Select two or more columns for this operation.");
return;
}*/
if(columnList.length > 1 && operationType === 'Inverse Value'){
via.kendoAlert("Add Column Error","Select only one column for this operation.");
return;
}
colObject.operationType = operationType;
colObject.columnList = columnList.join("::");
}else if(colObject.columnType === 'Create Index'){//Create Index
}else{//Assign
//Check the value
colObject.value = getInputBoxValue();
//Add the data type if it is a custom column
if($('#fileFormat_addColumn_dataType').prop("disabled") === false) {
colObject.dataType = $('#fileFormat_addColumn_dataType').data('kendoDropDownList').value();
}
//Check for a value
if(via.undef(colObject.value,true)){
via.kendoAlert("Add Column Error","Set a value for the column you want to add.");
return;
}
}
//Add everything to the grid
var grid = $("#fileFormat_addColumn_grid").data('kendoGrid');
grid.dataSource.add(colObject);
//Reset form
$("#fileFormat_addColumn_columnList").data("kendoComboBox").value(null);
$('#fileFormat_addColumn_dataType').data('kendoDropDownList').select(0);
$('#fileFormat_addColumn_prefix').val(null);
$('#fileFormat_addColumn_suffix').val(null);
$('#fileFormat_addColumn_dateFormat').data('kendoComboBox').value(null);
$('#fileFormat_addColumn_prefixIsRegex').prop('checked',false);
$('#fileFormat_addColumn_suffixIsRegex').prop('checked',false);
$("#fileFormat_addColumn_columnList").data("kendoComboBox").trigger('change');
$('#fileFormat_addColumn_multiColumnOperationType').data("kendoDropDownList").value(null);
$('#fileFormat_addColumn_multiColumnColumnList').data("kendoMultiSelect").value(null);
});
//Grid for add column
$("#fileFormat_addColumn_grid").kendoGrid({
height: 145,
dataSource: {
data: odinLite_fileFormat.staticColumns,
schema: {
model: {
fields: {
columnName: { type: "string" },
columnType: { type: "string" },
dataType: { type: "string" },
value: { type: "string" },
prefix: { type: "string" },
prefixRegex: { type: "boolean" },
suffix: { type: "string" },
suffixRegex: { type: "boolean" },
dateFormat: { type: "string" },
operationType: { type: "string" },
columnList: { type: "string" }
}
}
}
},
scrollable: true,
sortable: false,
filterable: false,
columns: [
{ field: "columnName", title: "Column Name", width: "130px" },
{ field: "columnType", title: "Column Type", width: "100px" },
{ field: "dataType", title: "Data Type", width: "100px" },
{ field: "value", title: "Value", width: "100px"},
{ field: "prefix", title: "Prefix", width: "100px" },
{ field: "prefixRegex", title: "Regex", width: "60px" },
{ field: "suffix", title: "Suffix", width: "100px" },
{ field: "suffixRegex", title: "Regex", width: "60px" },
{ field: "dateFormat", title: "Date Format", width: "100px" },
{ field: "operationType", title: "Operation Type", width: "100px" },
{ field: "columnList", title: "Column List", width: "100px" },
{ title: "Edit", width: "85px",
command: {
text: "Edit",
click: editColumn
}
},
{ title: "Delete", width: "85px",
command: {
text: "Delete",
click: deleteColumn
}
}
]
});
//Load the initial/saved settings
var grid = $("#fileFormat_addColumn_grid").data('kendoGrid');
grid.dataSource.data([]);
grid.dataSource.data(odinLite_fileFormat.staticColumns);
/****************/
/* Function */
/***************/
//Check to see if it is a template column
function checkTemplateColumn(colName){
var isTemplate = false;
var cols = odinLite_modelCache.currentEntity.mappedColumnDisplay;
for(var i in cols){
if(via.undef(cols[i])){ continue; }
if(cols[i].toUpperCase() === colName.toUpperCase()){
isTemplate = true;
break;
}
}
var dataTypeInput = $('#fileFormat_addColumn_dataType').data('kendoDropDownList');
if(isTemplate !== true){
dataTypeInput.select(0);
$('#fileFormat_addColumn_dataType').prop("disabled",false);
$('#fileFormat_addColumn_dataType').data('kendoDropDownList').enable(true);
}else{
dataTypeInput.select(0);
$('#fileFormat_addColumn_dataType').prop("disabled",true);
$('#fileFormat_addColumn_dataType').data('kendoDropDownList').enable(false);
}
}
//Edits a column from the table
function editColumn(e) {
e.preventDefault();
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
//Remove from the grid
var grid = $("#fileFormat_addColumn_grid").data('kendoGrid');
grid.dataSource.remove(dataItem);
//Remove from the static
var idx = -1;
for(var i=0;i<odinLite_fileFormat.staticColumns.length;i++){
var col = odinLite_fileFormat.staticColumns[i];
if(col.columnName === dataItem.columnName){
idx = i;
break;
}
}
if(idx!==-1){
odinLite_fileFormat.staticColumns.splice(i,1);
}
//Set the column type
$("#fileFormat_addColumn_columnType").data('kendoDropDownList').value(dataItem.columnType);
$("#fileFormat_addColumn_columnList").data("kendoComboBox").value(dataItem.columnName);
if(dataItem.columnType === 'Extract Value from File/Sheet Name'){
$('#fileFormat_addColumn_dateFormat').data('kendoComboBox').value(dataItem.dateFormat);
$('#fileFormat_addColumn_prefix').val(dataItem.prefix);
$('#fileFormat_addColumn_suffix').val(dataItem.suffix);
$('#fileFormat_addColumn_prefixIsRegex').prop('checked',dataItem.prefixRegex);
$('#fileFormat_addColumn_suffixIsRegex').prop('checked',dataItem.suffixRegex);
}else if(dataItem.columnType === 'Multi-Column Operation'){
$('#fileFormat_addColumn_multiColumnOperationType').data('kendoDropDownList').value(dataItem.operationType);
var arr = [];
if(!via.undef(dataItem.columnList,true)){ arr = dataItem.columnList.split(";");}
$('#fileFormat_addColumn_multiColumnColumnList').data('kendoMultiSelect').value(arr);
}else{
if(!via.undef(dataItem.dataType,true)) {
$("#fileFormat_addColumn_dataType").prop("disabled",false);
$("#fileFormat_addColumn_dataType").data('kendoDropDownList').enable();
$("#fileFormat_addColumn_dataType").data('kendoDropDownList').value(dataItem.dataType);
$("#fileFormat_addColumn_dataType").data('kendoDropDownList').trigger("change");
}else{
$("#fileFormat_addColumn_dataType").prop("diabled",true);
$("#fileFormat_addColumn_dataType").data('kendoDropDownList').enable(false);
$("#fileFormat_addColumn_dataType").data('kendoDropDownList').select(0);
//$("#fileFormat_addColumn_dataType").data('kendoDropDownList').trigger("change");
}
addInputBox(dataItem.columnName);
getInputBoxValue(dataItem.value);
}
$("#fileFormat_addColumn_columnType").data('kendoDropDownList').trigger("change")
}
//Delete a column from the table
function deleteColumn(e){
e.preventDefault();
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
//Remove from the grid
var grid = $("#fileFormat_addColumn_grid").data('kendoGrid');
grid.dataSource.remove(dataItem);
//Remove from the static
var idx = -1;
for(var i=0;i<odinLite_fileFormat.staticColumns.length;i++){
var col = odinLite_fileFormat.staticColumns[i];
if(col.columnName === dataItem.columnName){
idx = i;
break;
}
}
if(idx!==-1){
odinLite_fileFormat.staticColumns.splice(i,1);
}
}
//addInputBox - adds an input box based on the type.
function addInputBox(columnName){
$(".fileFormat_addColumn_columnValue").empty();
$(".fileFormat_addColumn_columnValue").append('<input style="width:300px;" id="fileFormat_addColumn_value"/>');
var idx = $.inArray(columnName,odinLite_modelCache.currentEntity.mappedColumnDisplay);
var type = 0;
if(idx !== -1){
type = odinLite_modelCache.currentEntity.mappedColumnDataType[idx];
}else if($('#fileFormat_addColumn_dataType').prop("disabled") === false){
var textType = $('#fileFormat_addColumn_dataType').data('kendoDropDownList').value();
type = odinLite_modelCache.currentEntity.compareDataTypeCodes[textType];
}
switch(type){
case 1:
$('#fileFormat_addColumn_value').kendoNumericTextBox();
break;
case 4:
$('#fileFormat_addColumn_value').kendoNumericTextBox({
decimals: 0,
restrictDecimals: true
});
break;
case 3:
$("#fileFormat_addColumn_value").kendoDatePicker();
break;
default://Text
$('#fileFormat_addColumn_value').addClass("k-textbox");
}
}
//getInputBoxValue - can get or set the value of the input box
function getInputBoxValue(setValue){
var columnName = $("#fileFormat_addColumn_columnList").data("kendoComboBox").value();
var idx = $.inArray(columnName,odinLite_modelCache.currentEntity.mappedColumnDisplay);
var type = 0;
if(idx !== -1){
type = odinLite_modelCache.currentEntity.mappedColumnDataType[idx];
}else if($('#fileFormat_addColumn_dataType').prop("disabled") === false){
var textType = $('#fileFormat_addColumn_dataType').data('kendoDropDownList').value();
type = odinLite_modelCache.currentEntity.compareDataTypeCodes[textType];
}
var value = null;
switch(type){
case 1:
case 4:
value = $('#fileFormat_addColumn_value').data("kendoNumericTextBox").value();
if(!via.undef(setValue,true)){
$('#fileFormat_addColumn_value').data("kendoNumericTextBox").value(setValue);
}
break;
case 3:
var date = $("#fileFormat_addColumn_value").data("kendoDatePicker").value();
if(!via.undef(setValue,true)){
$('#fileFormat_addColumn_value').data("kendoDatePicker").value(kendo.parseDate(setValue, "yyyyMMdd"));
}
if(date===null){return null;}
value = (date.getFullYear() +
('0' + (date.getMonth() + 1)).slice(-2) +
('0' + (date.getDate())).slice(-2));
break;
default://Text
value = $('#fileFormat_addColumn_value').val();
if(!via.undef(setValue,true)){
$('#fileFormat_addColumn_value').val(setValue);
}
}
return value;
}
//getCurrentType - get the type of the current column chosen
function getCurrentType(){
var columnName = $("#fileFormat_addColumn_columnList").data("kendoComboBox").value();
var idx = $.inArray(columnName,odinLite_modelCache.currentEntity.mappedColumnDisplay);
var type = 0;
if(idx !== -1){
type = odinLite_modelCache.currentEntity.mappedColumnDataType[idx];
}
return type;
}
},
advancedSettingsWindow_addColumn_regexHelp: function(){
kendo.ui.progress($("body"), true);
$.post(odin.SERVLET_PATH,
{
action: 'odinLite.uploadFiles.getRegexExamples'
},
function(data, status){
kendo.ui.progress($("body"), false);//wait off
if(!via.undef(data,true) && data.success === false){
via.debug("Regex Help Error:", data.message);
via.alert("Regex Help Error",data.message);
}else{//Success - RegEx
via.debug("Regex Help Successful:", data);
if(!via.undef(data.tsEncoded)) {
var grid = via.displayPopupGrid("Regex Help", data.tsEncoded, 400, 900);
grid.setOptions({
groupable: false
});
}
}
},
'json');
},
/**
* advancedSettingsWindow_mapColumn
* This is for the map column tab
*/
advancedSettingsWindow_mapColumn: function(){
//Header List
//var headers = odinLite_modelMapping.getColumnListFromTableSet();
//headers.splice(0,1);
var headerArr = (!via.undef(odinLite_fileFormat.unionHeaders))?odinLite_fileFormat.unionHeaders:odinLite_fileFormat.originalHeaders;
var headers = [];
for(var i=0;i<headerArr.length;i++){
var col = headerArr[i];
headers.push({ text: col, value: col });
}
//Dropdown box of columns
var columnList = [];
for(var i=0;i<odinLite_modelCache.currentEntity.mappedColumnDisplay.length;i++){
var col = odinLite_modelCache.currentEntity.mappedColumnDisplay[i];
columnList.push({ text: col, value: col });
}
//Check for data management
if(odinLite_modelCache.dataMgmtModel === odinLite_modelCache.currentEntity.modelId){
columnList = [];
}
$('#fileFormat_mapColumn_columnList').kendoComboBox({
dataTextField: "text",
dataValueField: "value",
dataSource: columnList,
value: null,
change: function(e){
//Check the template Column
checkTemplateColumn(e.sender.value());
//Set the date format
setDateFormat();
}
});
//Extract - Date format combo
$('#fileFormat_mapColumn_dateFormat').kendoComboBox({
dataTextField: "text",
dataValueField: "value",
autoWidth: true,
value: null,
dataSource: odinLite_fileFormat.FILE_DATA.dateFormats
});
setDateFormat();
//Header List
$('#fileFormat_mapColumn_headerList').kendoDropDownList({
dataTextField: "text",
dataValueField: "text",
autoWidth: true,
dataSource: headers,
value: null
});
/** Data Type **/
var dataTypeList = [];
for(var i=0;i<odinLite_modelCache.currentEntity.compareDataTypes.length;i++){
var col = odinLite_modelCache.currentEntity.compareDataTypes[i];
dataTypeList.push({ text: col, value: col });
}
$('#fileFormat_mapColumn_dataType').kendoDropDownList({
dataTextField: "text",
dataValueField: "value",
dataSource: dataTypeList,
value: null,
change: function(e){
//Set the date format
setDateFormat();
}
});
//Add Column to Grid - Button Click
$(".fileFormat_mapColumnButton").on("click",function(){
var colObject = {};
colObject.dataColumn = $("#fileFormat_mapColumn_headerList").data("kendoDropDownList").value();
colObject.templateColumn = $("#fileFormat_mapColumn_columnList").data("kendoComboBox").value();
if($("#fileFormat_mapColumn_dataType").prop("disabled") === false) {
colObject.dataType = $("#fileFormat_mapColumn_dataType").data("kendoDropDownList").value();
}
colObject.dateFormat = $("#fileFormat_mapColumn_dateFormat").data("kendoComboBox").value();
colObject.type = getCurrentType();
//Data Column Check
if(via.undef(colObject.dataColumn,true)){
via.kendoAlert("Map Column Error","Choose a data column.");
return;
}
//Template Column Check
if(via.undef(colObject.templateColumn,true)){
via.kendoAlert("Map Column Error","Choose a template column.");
return;
}
//Date Format Check
if(via.undef(colObject.dateFormat,true) && colObject.type === 3){
via.kendoAlert("Map Column Error","Choose a date format.");
return;
}
if(colObject.dataType === "Date" && via.undef(colObject.dateFormat,true)){
via.kendoAlert("Map Column Error","Choose a date format.");
return;
}
//Mapped Column Check
for(var i in odinLite_fileFormat.mappedColumns){
var obj = odinLite_fileFormat.mappedColumns[i];
if(obj.dataColumn === colObject.dataColumn){
via.kendoAlert("Map Column Error","Data Column already mapped.");
return;
}
if(obj.templateColumn === colObject.templateColumn){
via.kendoAlert("Map Column Error","Template Column already mapped.");
return;
}
}
//Add everything to the grid
var grid = $("#fileFormat_mapColumn_grid").data('kendoGrid');
grid.dataSource.add(colObject);
//Reset form
$("#fileFormat_mapColumn_headerList").data("kendoDropDownList").value(null);
$("#fileFormat_mapColumn_dataType").data("kendoDropDownList").value(null);
$("#fileFormat_mapColumn_columnList").data("kendoComboBox").value(null);
$('#fileFormat_mapColumn_dateFormat').data('kendoComboBox').value(null);
});
//Grid for add column
$("#fileFormat_mapColumn_grid").kendoGrid({
height: 190,
dataSource: {
data: odinLite_fileFormat.staticColumns,
schema: {
model: {
fields: {
dataColumn: { type: "string" },
templateColumn: { type: "string" },
dataType: { type: "string" },
dateFormat: { type: "string" }
}
}
}
},
scrollable: true,
sortable: false,
filterable: false,
columns: [
{ field: "dataColumn", title: "Data Column", width: "130px" },
{ field: "templateColumn", title: "Template Column", width: "100px" },
{ field: "dataType", title: "Data Type", width: "100px"},
{ field: "dateFormat", title: "Date Format", width: "100px"},
{ title: "Delete", width: "85px",
command: {
text: "Delete",
click: deleteColumn
}
}
]
});
//Load the initial/saved settings
var grid = $("#fileFormat_mapColumn_grid").data('kendoGrid');
grid.dataSource.data([]);
grid.dataSource.data(odinLite_fileFormat.mappedColumns);
/****************/
/* Function */
/***************/
//Check to see if it is a template column
function checkTemplateColumn(colName){
var isTemplate = false;
var cols = odinLite_modelCache.currentEntity.mappedColumnDisplay;
for(var i in cols){
if(via.undef(cols[i])){ continue; }
if(cols[i].toUpperCase() === colName.toUpperCase()){
isTemplate = true;
break;
}
}
var dataTypeInput = $('#fileFormat_mapColumn_dataType').data('kendoDropDownList');
if(isTemplate !== true){
dataTypeInput.select(0);
$('#fileFormat_mapColumn_dataType').prop("disabled",false);
$('#fileFormat_mapColumn_dataType').data('kendoDropDownList').enable(true);
}else{
dataTypeInput.select(0);
$('#fileFormat_mapColumn_dataType').prop("disabled",true);
$('#fileFormat_mapColumn_dataType').data('kendoDropDownList').enable(false);
}
}
//Delete a column from the table
function deleteColumn(e){
e.preventDefault();
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
//Remove from the grid
var grid = $("#fileFormat_mapColumn_grid").data('kendoGrid');
grid.dataSource.remove(dataItem);
//Remove from the mapped array
var idx = -1;
for(var i=0;i<odinLite_fileFormat.mappedColumns.length;i++){
var col = odinLite_fileFormat.mappedColumns[i];
if(col.dataColumn === dataItem.dataColumn){
idx = i;
break;
}
}
if(idx!==-1){
odinLite_fileFormat.mappedColumns.splice(i,1);
}
}
//getCurrentType - get the type of the current column chosen
function setDateFormat(){
var type = getCurrentType();
if(type === 3){
$('#fileFormat_mapColumn_dateFormat').prop("disabled",false);
$('#fileFormat_mapColumn_dateFormat').data('kendoComboBox').enable(true);
$('#fileFormat_mapColumn_dateFormat').data('kendoComboBox').select(0);
}else{
$('#fileFormat_mapColumn_dateFormat').data('kendoComboBox').value(null);
$('#fileFormat_mapColumn_dateFormat').data('kendoComboBox').enable(false);
}
//This is for a custom column / not a template
if($('#fileFormat_mapColumn_dataType').prop("disabled") === false &&
$('#fileFormat_mapColumn_dataType').data("kendoDropDownList").value() === "Date"){
$('#fileFormat_mapColumn_dateFormat').prop("disabled",false);
$('#fileFormat_mapColumn_dateFormat').data('kendoComboBox').enable(true);
}
return type;
}
//getCurrentType - get the type of the current column chosen
function getCurrentType(){
var columnName = $("#fileFormat_mapColumn_columnList").data("kendoComboBox").value();
var idx = $.inArray(columnName,odinLite_modelCache.currentEntity.mappedColumnDisplay);
var type = 0;
if(idx !== -1){
type = odinLite_modelCache.currentEntity.mappedColumnDataType[idx];
}
return type;
}
},
/**
* advancedSettingsWindow_dataMergeOptions
* This will setup the data merge options
*/
advancedSettingsWindow_dataMergeOptions: function(){
//Initial Values
if(!via.undef(odinLite_fileFormat.dataMergeOptions.timeSeries) && odinLite_fileFormat.dataMergeOptions.timeSeries === true){
$('#modelMapping_timeSeriesMerge').prop("checked",odinLite_fileFormat.dataMergeOptions.timeSeries);
$('#modelMapping_timeSeriesToPortIndexMerge').prop("checked",false);
$('#modelMapping_attributeData').prop("checked",false);
}else if(!via.undef(odinLite_fileFormat.dataMergeOptions.portIndex) && odinLite_fileFormat.dataMergeOptions.portIndex === true){
$('#modelMapping_timeSeriesToPortIndexMerge').prop("checked",odinLite_fileFormat.dataMergeOptions.portIndex);
$('#modelMapping_timeSeriesMerge').prop("checked",false);
$('#modelMapping_attributeData').prop("checked",false);
}else if(!via.undef(odinLite_fileFormat.dataMergeOptions.attributeData) && odinLite_fileFormat.dataMergeOptions.attributeData === true){
$('#modelMapping_attributeData').prop("checked",odinLite_fileFormat.dataMergeOptions.attributeData);
$('#modelMapping_timeSeriesToPortIndexMerge').prop("checked",false);
$('#modelMapping_timeSeriesMerge').prop("checked",false);
}
//Check to see if it is enabled. Disable and uncheck if it is not.
if(odinLite_modelCache.currentEntity.isTimeSeriesToPortIndexTimeSeriesAllowed === false){
$('#modelMapping_timeSeriesToPortIndexMerge').prop("checked",false);
$('#modelMapping_timeSeriesToPortIndexMerge').prop("disabled",true);
}
if(odinLite_modelCache.currentEntity.isStaticToTimeSeriesAllowed === false){
$('#modelMapping_timeSeriesMerge').prop("checked",false);
$('#modelMapping_timeSeriesMerge').prop("disabled",true);
}
if(odinLite_modelCache.currentEntity.isAttributeAllowed === false){
$('#modelMapping_attributeData').prop("checked",false);
$('#modelMapping_attributeData').prop("disabled",true);
}
//Events - disable the other if checked
$('#modelMapping_timeSeriesToPortIndexMerge').on('change',function() {
if($('#modelMapping_timeSeriesToPortIndexMerge').prop('checked')) {
$('#modelMapping_timeSeriesMerge').prop("checked",false);
$('#modelMapping_attributeData').prop("checked",false);
}
});
$('#modelMapping_timeSeriesMerge').on('change',function() {
if($('#modelMapping_timeSeriesMerge').prop('checked')) {
$('#modelMapping_timeSeriesToPortIndexMerge').prop("checked",false);
$('#modelMapping_attributeData').prop("checked",false);
}
});
$('#modelMapping_attributeData').on('change',function() {
if($('#modelMapping_attributeData').prop('checked')) {
$('#modelMapping_timeSeriesToPortIndexMerge').prop("checked",false);
$('#modelMapping_timeSeriesMerge').prop("checked",false);
}
});
},
/**
* advancedSettingsWindow_dataManagementPlugins
* This handle the data management plugins tab
*/
advancedSettingsWindow_dataManagementPlugins: function(){
var plugins = [{ text: "", value: null }];
if(!via.undef(odinLite_modelCache.currentEntity.dataManagementPlugins)) {
for(var i=0;i<odinLite_modelCache.currentEntity.dataManagementPlugins.length;i++){
var plug = odinLite_modelCache.currentEntity.dataManagementPlugins[i];
plugins.push({ text: plug, value: plug });
}
}
$('#fileFormat_dataManagementPlugin').kendoDropDownList({
dataTextField: "text",
dataValueField: "value",
dataSource: plugins,
value: odinLite_fileFormat.dataManagementPlugin
});
},
/**
* advancedSettingsWindow_filterData
* This handles the filter data tab
*/
advancedSettingsWindow_filterData: function(){
/** Where Clause Type **/
$('#fileFormat_filterData_whereClauseType').kendoDropDownList({
dataTextField: "text",
dataValueField: "value",
dataSource: [{text:'OR',value:'OR'},{text:'AND',value:'AND'}],
index: 0,
change: function(e){}
});
/** Data Column **/
$('#fileFormat_filterData_dataColumn').kendoDropDownList({
dataTextField: "text",
dataValueField: "text",
dataSource: odinLite_fileFormat.getColumnListWithAdvancedColumns(),
index: 0,
change: function(e){
$('#fileFormat_filterData_dataType').data('kendoDropDownList').value(null);
enableComparisonValueInputBox(false);
}
});
/** Data Type **/
var dataTypeList = [];
for(var i=0;i<odinLite_modelCache.currentEntity.compareDataTypes.length;i++){
var col = odinLite_modelCache.currentEntity.compareDataTypes[i];
dataTypeList.push({ text: col, value: col });
}
$('#fileFormat_filterData_dataType').kendoDropDownList({
dataTextField: "text",
dataValueField: "value",
dataSource: dataTypeList,
index: 0,
change: function(e){
updateDataTypeOperations();
addComparisonValueInputBox();
}
});
/** Comparison Operation **/
$('#fileFormat_filterData_operation').kendoDropDownList({
dataTextField: "text",
dataValueField: "value",
dataSource: [],
change: function(e){
var comparisonTypeDD = $('#fileFormat_filterData_comparisonType').data('kendoDropDownList');
var comparisonColumnDD = $('#fileFormat_filterData_comparisonColumn').data('kendoDropDownList');
//Enable the boxes
comparisonTypeDD.enable(true);
comparisonColumnDD.enable(true);
enableComparisonValueInputBox(true);
var val = e.sender.value();
if(val === 'Is Missing' || val==='Not Missing'){
comparisonTypeDD.value('Value');
comparisonTypeDD.enable(false);
comparisonColumnDD.value(null);
comparisonColumnDD.enable(false);
getComparisonValueInputBoxValue(null);
enableComparisonValueInputBox(false);
}else if(val === 'Contains' || val==='Not Contains' || val==='Between' || val==='Not Between'){
comparisonTypeDD.value('Value');
comparisonTypeDD.enable(false);
comparisonColumnDD.value(null);
comparisonColumnDD.enable(false);
getComparisonValueInputBoxValue(null);
}else{
comparisonColumnDD.value(null);
getComparisonValueInputBoxValue(null);
}
}
});
//Function to update the data type operations.
function updateDataTypeOperations(){
//Reset the values
var ddList = $('#fileFormat_filterData_operation').data('kendoDropDownList');
ddList.dataSource.data([]);
//get the list for the currently selected data type.
var value = $('#fileFormat_filterData_dataType').data('kendoDropDownList').value();
var list = odinLite_modelCache.currentEntity.compareOperations[value];
if(via.undef(list,true)){return;}
var operationList = [];
for(var i=0;i<list.length;i++){
var col = list[i];
operationList.push({ text: col, value: col });
}
ddList.dataSource.data(operationList);
}
updateDataTypeOperations();
/** Comparison Type **/
$('#fileFormat_filterData_comparisonType').kendoDropDownList({
dataTextField: "text",
dataValueField: "value",
dataSource: [{text:'Value',value:'Value'},{text:'Column',value:'Column'}],
change: function(e){
updateComparisonType();
}
});
function updateComparisonType(){
var val = $('#fileFormat_filterData_comparisonType').data('kendoDropDownList').value();
if(val === "Column"){
enableComparisonValueInputBox(false);
getComparisonValueInputBoxValue(null);
$('#fileFormat_filterData_comparisonColumn').data('kendoDropDownList').enable(true);
}else{
enableComparisonValueInputBox(true);
$('#fileFormat_filterData_comparisonColumn').data('kendoDropDownList').enable(false);
}
}
/** Comparison Value **/
addComparisonValueInputBox();
//addInputBox - adds an input box based on the type.
function addComparisonValueInputBox(){
$(".fileFormat_filterData_comparisonValue").empty();
$(".fileFormat_filterData_comparisonValue").append('<input style="width:200px;" id="fileFormat_filterData_comparisonValue"/>');
var type = $("#fileFormat_filterData_dataType").data("kendoDropDownList").value();
switch(type){
case "Number":
$('#fileFormat_filterData_comparisonValue').addClass("k-textbox");
$('#fileFormat_filterData_comparisonValue').keyup(function () {
this.value = this.value.replace(/[^0-9\.-]/g,'');
});
break;
case "Date":
$("#fileFormat_filterData_comparisonValue").kendoDatePicker();
break;
default://Text
$('#fileFormat_filterData_comparisonValue').addClass("k-textbox");
}
}
function enableComparisonValueInputBox(enable){
var type = $("#fileFormat_filterData_dataType").data("kendoDropDownList").value();
switch(type){
case "Number":
//$('#fileFormat_filterData_comparisonValue').data('kendoNumericTextBox').enable(enable);
$('#fileFormat_filterData_comparisonValue').prop("disabled",!enable);
break;
case "Date":
$('#fileFormat_filterData_comparisonValue').data('kendoDatePicker').enable(enable);
break;
default://Text
$('#fileFormat_filterData_comparisonValue').prop("disabled",!enable);
}
}
//getInputBoxValue - can get or set the value of the input box
function getComparisonValueInputBoxValue(setValue){
var type = $("#fileFormat_filterData_dataType").data("kendoDropDownList").value();
switch(type){
/*
case "Number":
value = $('#fileFormat_filterData_comparisonValue').data("kendoNumericTextBox").value();
if(setValue!==undefined){
$('#fileFormat_filterData_comparisonValue').data("kendoNumericTextBox").value(setValue);
}
break;
*/
case "Date":
var date = $("#fileFormat_filterData_comparisonValue").data("kendoDatePicker").value();
if(setValue!==undefined){
$('#fileFormat_filterData_comparisonValue').data("kendoDatePicker").value(setValue);
}
if(date===null){return null;}
value = (date.getFullYear() +
('0' + (date.getMonth() + 1)).slice(-2) +
('0' + (date.getDate())).slice(-2));
break;
case "Number":
default://Text
value = $('#fileFormat_filterData_comparisonValue').val();
if(setValue!==undefined){
$('#fileFormat_filterData_comparisonValue').val(setValue);
}
}
return value;
}
/** Comparison Column **/
$('#fileFormat_filterData_comparisonColumn').kendoDropDownList({
dataTextField: "text",
dataValueField: "text",
dataSource: odinLite_fileFormat.getColumnListWithAdvancedColumns(),
value: null,
change: function(e){}
});
/** Trigger events **/
$('#fileFormat_filterData_comparisonType').data('kendoDropDownList').trigger('change');
updateComparisonType();
/** Intermediate Rules Grid **/
$("#fileFormat_filterData_intermediateGrid").kendoGrid({
height: 120,
dataSource: {
data: [],
schema: {
model: {
fields: {
whereClauseType: { type: "string" },
dataColumn: { type: "string" },
dataType: { type: "string" },
operation: { type: "string" },
comparisonType: { type: "string" },
comparisonValue: { type: "string" },
comparisonColumn: { type: "string" }
}
}
}
},
scrollable: true,
sortable: false,
filterable: false,
columns: [
{ field: "whereClauseType", title: "Where Clause Type", width: "120px" },
{ field: "dataColumn", title: "Data Column", width: "130px" },
{ field: "dataType", title: "Data Type", width: "120px" },
{ field: "operation", title: "Operation", width: "120px" },
{ field: "comparisonType", title: "Comparison Type", width: "130px" },
{ field: "comparisonValue", title: "Comparison Value", width: "130px" },
{ field: "comparisonColumn", title: "Comparison Column", width: "130px" },
{ title: "Delete", width: "85px",
command: {
text: "Delete",
click: deleteRowIntermediate
}
}
]
});
//Delete a column from the table
function deleteRowIntermediate(e){
e.preventDefault();
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
//Remove from the grid
var grid = $("#fileFormat_filterData_intermediateGrid").data('kendoGrid');
grid.dataSource.remove(dataItem);
}
/** Final Rules Grid **/
$("#fileFormat_filterData_finalGrid").kendoGrid({
height: 120,
dataSource: {
data: odinLite_fileFormat.filterRules,
schema: {
model: {
fields: {
whereClause: { type: "string" }
}
}
}
},
scrollable: true,
sortable: false,
filterable: false,
columns: [
{ field: "whereClause", title: "Where Clause"},
{ title: "Delete", width: "85px",
command: {
text: "Delete",
click: deleteRowFinal
}
}
]
});
//Delete a column from the table
function deleteRowFinal(e){
e.preventDefault();
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
//Remove from the grid
var grid = $("#fileFormat_filterData_finalGrid").data('kendoGrid');
grid.dataSource.remove(dataItem);
//Remove from the Filter Rules array
var idx = -1;
for(var i=0;i<odinLite_fileFormat.filterRules.length;i++){
var col = odinLite_fileFormat.filterRules[i];
if(col.whereClause === dataItem.whereClause){
idx = i;
break;
}
}
if(idx!==-1){
odinLite_fileFormat.filterRules.splice(i,1);
}
}
/** Button events **/
//Intermediate add button
$('.fileFormat_addFilterIntermediateButton').click(function(){
var comparisonObj = {};
comparisonObj.whereClauseType = $('#fileFormat_filterData_whereClauseType').data('kendoDropDownList').value();
comparisonObj.dataColumn = $('#fileFormat_filterData_dataColumn').data('kendoDropDownList').value();
comparisonObj.dataType = $('#fileFormat_filterData_dataType').data('kendoDropDownList').value();
comparisonObj.operation = $('#fileFormat_filterData_operation').data('kendoDropDownList').value();
if(via.undef(comparisonObj.operation,true)){
via.kendoAlert("Add Filter Error","Select a value for operation.");
return;
}
comparisonObj.comparisonType = $('#fileFormat_filterData_comparisonType').data('kendoDropDownList').value();
if(comparisonObj.comparisonType === "Column"){
comparisonObj.comparisonColumn = $('#fileFormat_filterData_comparisonColumn').data('kendoDropDownList').value();
if(comparisonObj.comparisonColumn === comparisonObj.dataColumn){
via.kendoAlert("Add Filter Error","Data column and comparison column cannot be the same.");
return;
}
}else{
comparisonObj.comparisonValue = getComparisonValueInputBoxValue();
if(via.undef(comparisonObj.comparisonValue,true) &&
(comparisonObj.operation!=="Is Missing" && comparisonObj.operation!=="Not Missing")){
via.kendoAlert("Add Filter Error","Select a value for comparison.");
return;
}
}
$("#fileFormat_filterData_intermediateGrid").data('kendoGrid').dataSource.add(comparisonObj);
});
//Final add button
$('.fileFormat_addFilterFinalButton').click(function(){
var data = $("#fileFormat_filterData_intermediateGrid").data('kendoGrid').dataSource.data();
//check for blanks
if(via.undef(data) || data.length === 0){
return;
}
//Populate the rule string in the right format
var ruleString = "";
for(var i=0;i<data.length;i++){
var whereClause = data[i];
ruleString += "[";//Open Rule
/* Collect Variables */
ruleString += whereClause.whereClauseType + ";";
ruleString += whereClause.dataColumn + ";";
ruleString += whereClause.dataType + ";";
ruleString += whereClause.operation + ";";
ruleString += whereClause.comparisonType + ";";
ruleString += (via.undef(whereClause.comparisonValue,true))?";":whereClause.comparisonValue + ";";
ruleString += (via.undef(whereClause.comparisonColumn,true))?"":whereClause.comparisonColumn;
ruleString += "]";//Close Rule
}
//Clear the intermediate grid
$("#fileFormat_filterData_intermediateGrid").data('kendoGrid').dataSource.data([]);
//Add to final grid and the filter rule array
$("#fileFormat_filterData_finalGrid").data('kendoGrid').dataSource.add({whereClause:ruleString});
});
},
/**
* advancedSettingsWindow_validateData
* This handles the validate data tab
*/
advancedSettingsWindow_validateData: function(){
/** Where Clause Type **/
$('#fileFormat_validateData_whereClauseType').kendoDropDownList({
dataTextField: "text",
dataValueField: "value",
dataSource: [{text:'OR',value:'OR'},{text:'AND',value:'AND'}],
value: odinLite_fileFormat.dataManagementPlugin,
change: function(e){}
});
/** Data Column **/
$('#fileFormat_validateData_dataColumn').kendoDropDownList({
dataTextField: "text",
dataValueField: "text",
dataSource: odinLite_fileFormat.getColumnListWithAdvancedColumns(),
index: 0,
change: function(e){
$('#fileFormat_validateData_dataType').data('kendoDropDownList').value(null);
enableComparisonValueInputBox(false);
}
});
/** Data Type **/
var dataTypeList = [];
for(var i=0;i<odinLite_modelCache.currentEntity.compareDataTypes.length;i++){
var col = odinLite_modelCache.currentEntity.compareDataTypes[i];
dataTypeList.push({ text: col, value: col });
}
$('#fileFormat_validateData_dataType').kendoDropDownList({
dataTextField: "text",
dataValueField: "value",
dataSource: dataTypeList,
index: 0,
change: function(e){
updateDataTypeOperations();
addComparisonValueInputBox();
}
});
/** Comparison Operation **/
$('#fileFormat_validateData_operation').kendoDropDownList({
dataTextField: "text",
dataValueField: "value",
dataSource: [],
change: function(e){
var comparisonTypeDD = $('#fileFormat_validateData_comparisonType').data('kendoDropDownList');
var comparisonColumnDD = $('#fileFormat_validateData_comparisonColumn').data('kendoDropDownList');
//Enable the boxes
comparisonTypeDD.enable(true);
comparisonColumnDD.enable(true);
enableComparisonValueInputBox(true);
var val = e.sender.value();
if(val === 'Is Missing' || val==='Not Missing'){
comparisonTypeDD.value('Value');
comparisonTypeDD.enable(false);
comparisonColumnDD.value(null);
comparisonColumnDD.enable(false);
getComparisonValueInputBoxValue(null);
enableComparisonValueInputBox(false);
}else if(val === 'Contains' || val==='Not Contains' || val==='Between' || val==='Not Between'){
comparisonTypeDD.value('Value');
comparisonTypeDD.enable(false);
comparisonColumnDD.value(null);
comparisonColumnDD.enable(false);
getComparisonValueInputBoxValue(null);
}else{
comparisonColumnDD.value(null);
getComparisonValueInputBoxValue(null);
}
}
});
//Function to update the data type operations.
function updateDataTypeOperations(){
//Reset the values
var ddList = $('#fileFormat_validateData_operation').data('kendoDropDownList');
ddList.dataSource.data([]);
//get the list for the currently selected data type.
var value = $('#fileFormat_validateData_dataType').data('kendoDropDownList').value();
var list = odinLite_modelCache.currentEntity.compareOperations[value];
if(via.undef(list,true)){return;}
var operationList = [];
for(var i=0;i<list.length;i++){
var col = list[i];
operationList.push({ text: col, value: col });
}
ddList.dataSource.data(operationList);
}
updateDataTypeOperations();
/** Comparison Type **/
$('#fileFormat_validateData_comparisonType').kendoDropDownList({
dataTextField: "text",
dataValueField: "value",
dataSource: [{text:'Value',value:'Value'},{text:'Column',value:'Column'}],
change: function(e){
updateComparisonType();
}
});
function updateComparisonType(){
var val = $('#fileFormat_validateData_comparisonType').data('kendoDropDownList').value();
if(val === "Column"){
enableComparisonValueInputBox(false);
getComparisonValueInputBoxValue(null);
$('#fileFormat_validateData_comparisonColumn').data('kendoDropDownList').enable(true);
}else{
enableComparisonValueInputBox(true);
$('#fileFormat_validateData_comparisonColumn').data('kendoDropDownList').enable(false);
}
}
enableComparisonValueInputBox(false);
/** Comparison Value **/
addComparisonValueInputBox();
//addInputBox - adds an input box based on the type.
function addComparisonValueInputBox(){
$(".fileFormat_validateData_comparisonValue").empty();
$(".fileFormat_validateData_comparisonValue").append('<input style="width:200px;" id="fileFormat_validateData_comparisonValue"/>');
var type = $("#fileFormat_validateData_dataType").data("kendoDropDownList").value();
switch(type){
case "Number":
$('#fileFormat_validateData_comparisonValue').addClass("k-textbox");
$('#fileFormat_validateData_comparisonValue').keyup(function () {
this.value = this.value.replace(/[^0-9\.-]/g,'');
});
break;
case "Date":
$("#fileFormat_validateData_comparisonValue").kendoDatePicker();
break;
default://Text
$('#fileFormat_validateData_comparisonValue').addClass("k-textbox");
}
}
function enableComparisonValueInputBox(enable){
var type = $("#fileFormat_validateData_dataType").data("kendoDropDownList").value();
switch(type){
case "Number":
//$('#fileFormat_validateData_comparisonValue').data('kendoNumericTextBox').enable(enable);
$('#fileFormat_validateData_comparisonValue').prop("disabled",!enable);
break;
case "Date":
$('#fileFormat_validateData_comparisonValue').data('kendoDatePicker').enable(enable);
break;
default://Text
$('#fileFormat_validateData_comparisonValue').prop("disabled",!enable);
}
}
//getInputBoxValue - can get or set the value of the input box
function getComparisonValueInputBoxValue(setValue){
var type = $("#fileFormat_validateData_dataType").data("kendoDropDownList").value();
switch(type){
/*
case "Number":
value = $('#fileFormat_validateData_comparisonValue').data("kendoNumericTextBox").value();
if(setValue!==undefined){
$('#fileFormat_validateData_comparisonValue').data("kendoNumericTextBox").value(setValue);
}
break;
*/
case "Date":
var date = $("#fileFormat_validateData_comparisonValue").data("kendoDatePicker").value();
if(setValue!==undefined){
$('#fileFormat_validateData_comparisonValue').data("kendoDatePicker").value(setValue);
}
if(date===null){return null;}
value = (date.getFullYear() +
('0' + (date.getMonth() + 1)).slice(-2) +
('0' + (date.getDate())).slice(-2));
break;
case "Number":
default://Text
value = $('#fileFormat_validateData_comparisonValue').val();
if(setValue!==undefined){
$('#fileFormat_validateData_comparisonValue').val(setValue);
}
}
return value;
}
/** Comparison Column **/
$('#fileFormat_validateData_comparisonColumn').kendoDropDownList({
dataTextField: "text",
dataValueField: "text",
dataSource: odinLite_fileFormat.getColumnListWithAdvancedColumns(),
value: null,
change: function(e){}
});
/** Validation Operation **/
var validationOperationList = [];
for(var i=0;i<odinLite_modelCache.currentEntity.dataValidationOperations.length;i++){
var col = odinLite_modelCache.currentEntity.dataValidationOperations[i];
validationOperationList.push({ text: col, value: col });
}
$('#fileFormat_validateData_validationOperation').kendoDropDownList({
dataTextField: "text",
dataValueField: "value",
dataSource: validationOperationList,
index: 0,
change: function(e){
updateValidationOperation();
}
});
function updateValidationOperation(){
var val = $('#fileFormat_validateData_validationOperation').data('kendoDropDownList').value();
if(val === "Replace Value" || val === "Multiply Factor"){
getValidationValueInputBoxValue(null);
enableValidationValueInputBox(true);
$('#fileFormat_validateData_validationValueFetchColumn').data('kendoDropDownList').enable(false);
}else if(val === "Fetch Value"){
getValidationValueInputBoxValue(null);
enableValidationValueInputBox(false);
$('#fileFormat_validateData_validationValueFetchColumn').data('kendoDropDownList').enable(true);
}else{
enableComparisonValueInputBox(true);
$('#fileFormat_validateData_validationValueFetchColumn').data('kendoDropDownList').enable(true);
}
}
/** Validation Column **/
$('#fileFormat_validateData_validationColumn').kendoDropDownList({
dataTextField: "text",
dataValueField: "text",
dataSource: odinLite_fileFormat.getColumnListWithAdvancedColumns(),
index: 0,
change: function(e){
addValidationValueInputBox();
}
});
/** Validation Value **/
//fileFormat_validateData_validationValue
addValidationValueInputBox();
//addInputBox - adds an input box based on the type.
function addValidationValueInputBox(){
$(".fileFormat_validateData_validationValue").empty();
$(".fileFormat_validateData_validationValue").append('<input style="width:200px;" id="fileFormat_validateData_validationValue"/>');
var colSelected = $("#fileFormat_validateData_validationColumn").data("kendoDropDownList").value();
var type = getColumnDataType(colSelected);
switch(type){
case 1:
$('#fileFormat_validateData_validationValue').addClass("k-textbox");
$('#fileFormat_validateData_validationValue').keyup(function () {
this.value = this.value.replace(/[^0-9\.-]/g,'');
});
break;
case 3:
$("#fileFormat_validateData_validationValue").kendoDatePicker();
break;
default://Text
$('#fileFormat_validateData_validationValue').addClass("k-textbox");
}
}
function enableValidationValueInputBox(enable){
var colSelected = $("#fileFormat_validateData_validationColumn").data("kendoDropDownList").value();
var type = getColumnDataType(colSelected);
switch(type){
case 1:
//$('#fileFormat_validateData_validationValue').data('kendoNumericTextBox').enable(enable);
$('#fileFormat_validateData_validationValue').prop("disabled",!enable);
break;
case 3:
$('#fileFormat_validateData_validationValue').data('kendoDatePicker').enable(enable);
break;
default://Text
$('#fileFormat_validateData_validationValue').prop("disabled",!enable);
}
}
//getColumnDataType - get the data type of the selected column.
function getColumnDataType(columnName){
//Check Mapped Columns
for(var i=0;i<odinLite_fileFormat.mappedColumns.length;i++){
var col = odinLite_fileFormat.mappedColumns[i];
if(col.templateColumn === columnName){
return col.type;
}
}
//Check Add Columns
for(var i=0;i<odinLite_fileFormat.staticColumns.length;i++){
var col = odinLite_fileFormat.staticColumns[i];
if(col.columnName === columnName){
return col.type;
}
}
//Check tableset
var index = $('#fileFormat_validateData_validationColumn').data('kendoDropDownList').select();
if(via.undef(odinLite_fileFormat.FILE_DATA.tsEncoded) || via.undef(odinLite_fileFormat.FILE_DATA.tsEncoded.columnDataTypes) || index === -1){
return 0;
}
return odinLite_fileFormat.FILE_DATA.tsEncoded.columnDataTypes[index];
}
//getInputBoxValue - can get or set the value of the input box
function getValidationValueInputBoxValue(setValue){
var colSelected = $("#fileFormat_validateData_validationColumn").data("kendoDropDownList").value();
var type = getColumnDataType(colSelected);
switch(type){
/*
case "Number":
value = $('#fileFormat_validateData_validationValue').data("kendoNumericTextBox").value();
if(setValue!==undefined){
$('#fileFormat_validateData_validationValue').data("kendoNumericTextBox").value(setValue);
}
break;
*/
case 3:
var date = $("#fileFormat_validateData_validationValue").data("kendoDatePicker").value();
if(setValue!==undefined){
$('#fileFormat_validateData_validationValue').data("kendoDatePicker").value(setValue);
}
if(date===null){return null;}
value = (date.getFullYear() +
('0' + (date.getMonth() + 1)).slice(-2) +
('0' + (date.getDate())).slice(-2));
break;
case 1:
default://Text
value = $('#fileFormat_validateData_validationValue').val();
if(setValue!==undefined){
$('#fileFormat_validateData_validationValue').val(setValue);
}
}
return value;
}
/** Validation Fetch Column **/
//var validationHeaders = odinLite_modelMapping.getColumnListFromTableSet();
//validationHeaders.splice(0,1);
$('#fileFormat_validateData_validationValueFetchColumn').kendoDropDownList({
dataTextField: "text",
dataValueField: "text",
dataSource: odinLite_fileFormat.getColumnListWithAdvancedColumns(),
index: 0,
change: function(e){}
});
updateValidationOperation();//Call this to set the intital enabled disabled
/** Trigger events **/
$('#fileFormat_validateData_comparisonType').data('kendoDropDownList').trigger('change');
updateComparisonType();
/** Intermediate Rules Grid **/
$("#fileFormat_validateData_intermediateGrid").kendoGrid({
height: 120,
dataSource: {
data: [],
schema: {
model: {
fields: {
whereClauseType: { type: "string" },
dataColumn: { type: "string" },
dataType: { type: "string" },
operation: { type: "string" },
comparisonType: { type: "string" },
comparisonValue: { type: "string" },
comparisonColumn: { type: "string" }
}
}
}
},
scrollable: true,
sortable: false,
filterable: false,
columns: [
{ field: "whereClauseType", title: "Where Clause Type", width: "120px" },
{ field: "dataColumn", title: "Data Column", width: "130px" },
{ field: "dataType", title: "Data Type", width: "120px" },
{ field: "operation", title: "Operation", width: "120px" },
{ field: "comparisonType", title: "Comparison Type", width: "130px" },
{ field: "comparisonValue", title: "Comparison Value", width: "130px" },
{ field: "comparisonColumn", title: "Comparison Column", width: "130px" },
{ title: "Delete", width: "85px",
command: {
text: "Delete",
click: deleteRowIntermediate
}
}
]
});
//Delete a column from the table
function deleteRowIntermediate(e){
e.preventDefault();
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
//Remove from the grid
var grid = $("#fileFormat_validateData_intermediateGrid").data('kendoGrid');
grid.dataSource.remove(dataItem);
}
/** Final Rules Grid **/
$("#fileFormat_validateData_finalGrid").kendoGrid({
height: 120,
dataSource: {
data: odinLite_fileFormat.validationRules,
schema: {
model: {
fields: {
whereClause: { type: "string" },
validationOperation: { type: "string" },
validationColumn: { type: "string" },
validationValue: { type: "string" },
validationFetchColumn: { type: "string" }
}
}
}
},
scrollable: true,
sortable: false,
filterable: false,
columns: [
{ field: "whereClause", title: "Where Clause"},
{ field: "validationOperation", title: "Data Validation Operation"},
{ field: "validationColumn", title: "Data Validation Column"},
{ field: "validationValue", title: "Validation Value"},
{ field: "validationFetchColumn", title: "Validation Value Fetch Column "},
{ title: "Delete", width: "85px",
command: {
text: "Delete",
click: deleteRowFinal
}
}
]
});
//Delete a column from the final table
function deleteRowFinal(e){
e.preventDefault();
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
//Remove from the grid
var grid = $("#fileFormat_validateData_finalGrid").data('kendoGrid');
grid.dataSource.remove(dataItem);
//Remove from the Filter Rules array
var idx = -1;
for(var i=0;i<odinLite_fileFormat.validationRules.length;i++){
var col = odinLite_fileFormat.validationRules[i];
if(col.whereClause === dataItem.whereClause){
idx = i;
break;
}
}
if(idx!==-1){
odinLite_fileFormat.validationRules.splice(i,1);
}
}
/** Button events **/
//Intermediate add button
$('.fileFormat_addValidateIntermediateButton').click(function(){
var comparisonObj = {};
comparisonObj.whereClauseType = $('#fileFormat_validateData_whereClauseType').data('kendoDropDownList').value();
comparisonObj.dataColumn = $('#fileFormat_validateData_dataColumn').data('kendoDropDownList').value();
comparisonObj.dataType = $('#fileFormat_validateData_dataType').data('kendoDropDownList').value();
comparisonObj.operation = $('#fileFormat_validateData_operation').data('kendoDropDownList').value();
if(via.undef(comparisonObj.operation,true)){
via.kendoAlert("Add Validation Error","Select a value for operation.");
return;
}
comparisonObj.comparisonType = $('#fileFormat_validateData_comparisonType').data('kendoDropDownList').value();
if(comparisonObj.comparisonType === "Column"){
comparisonObj.comparisonColumn = $('#fileFormat_validateData_comparisonColumn').data('kendoDropDownList').value();
if(comparisonObj.comparisonColumn === comparisonObj.dataColumn){
via.kendoAlert("Add Filter Error","Data column and comparison column cannot be the same.");
return;
}
}else{
comparisonObj.comparisonValue = getComparisonValueInputBoxValue();
if(via.undef(comparisonObj.comparisonValue,true) &&
(comparisonObj.operation!=="Is Missing" && comparisonObj.operation!=="Not Missing")){
via.kendoAlert("Add Validation Error","Select a value for comparison.");
return;
}
}
$("#fileFormat_validateData_intermediateGrid").data('kendoGrid').dataSource.add(comparisonObj);
});
//Final add button
$('.fileFormat_addValidationRuleFinalButton').click(function(){
var data = $("#fileFormat_validateData_intermediateGrid").data('kendoGrid').dataSource.data();
//check for blanks
if(via.undef(data) || data.length === 0){
return;
}
//Populate the rule string in the right format
var ruleString = "";
for(var i=0;i<data.length;i++){
var whereClause = data[i];
ruleString += "[";//Open Rule
/* Collect Variables */
ruleString += whereClause.whereClauseType + ";";
ruleString += whereClause.dataColumn + ";";
ruleString += whereClause.dataType + ";";
ruleString += whereClause.operation + ";";
ruleString += whereClause.comparisonType + ";";
ruleString += (via.undef(whereClause.comparisonValue,true))?";":whereClause.comparisonValue + ";";
ruleString += (via.undef(whereClause.comparisonColumn,true))?"":whereClause.comparisonColumn;
ruleString += "]";//Close Rule
}
var colObj = {};
colObj.whereClause = ruleString;
colObj.validationOperation = $("#fileFormat_validateData_validationOperation").data('kendoDropDownList').value();
colObj.validationColumn = $("#fileFormat_validateData_validationColumn").data('kendoDropDownList').value();
colObj.validationValue = getValidationValueInputBoxValue();
colObj.validationFetchColumn = $("#fileFormat_validateData_validationValueFetchColumn").data('kendoDropDownList').value();
//Check the values and columns for errors
if(colObj.validationOperation === "Fetch Value"){
colObj.validationValue = "";
if(colObj.validationColumn === colObj.validationFetchColumn){
via.kendoAlert("Add Validation Error","Fetch Column cannot match Validation Column.");
return;
}
}else{
colObj.validationFetchColumn = "";
if(via.undef(colObj.validationValue,true)){
via.kendoAlert("Add Validation Error","Select a validation value.");
return;
}
}
//Add to final grid and the filter rule array
$("#fileFormat_validateData_finalGrid").data('kendoGrid').dataSource.add(colObj);
//Clear the intermediate grid
$("#fileFormat_validateData_intermediateGrid").data('kendoGrid').dataSource.data([]);
//Clear the form
getValidationValueInputBoxValue(null);
});
},
/**
* getColumnListWithAdvancedColumns
* This will get the column list with the mappings
*/
getColumnListWithAdvancedColumns: function(){
if(via.undef(odinLite_fileFormat.FILE_DATA) || via.undef(odinLite_fileFormat.FILE_DATA.tsEncoded) ||
via.undef(odinLite_fileFormat.FILE_DATA.tsEncoded.columnHeaders)){
via.kendoAlert("Model Mapping Error","No data in uploaded file.");
return null;
}
var columnHeaders = odinLite_fileFormat.FILE_DATA.tsEncoded.columnHeaders;
var hasHeader = odinLite_fileFormat.FILE_DATA.hasColumnHeader;
var comboArr = [];
for(var i=0;i<columnHeaders.length;i++){
var comboObj = null;
//if(hasHeader){
comboObj = {
text: columnHeaders[i],
value: columnHeaders[i]
};
/*}else{
comboObj = {
text: via.toExcelColumnName(i+1),
value: i
};
}*/
comboArr.push(comboObj);
}
/*
//Add Column Columns
if(!via.undef(odinLite_fileFormat.staticColumns,true)){
for (var i in odinLite_fileFormat.staticColumns) {
var addColumn = odinLite_fileFormat.staticColumns[i];
var comboObj = {};
comboObj.text = addColumn.columnName;
comboObj.value = addColumn.columnName;
comboArr.push(comboObj);
}
}
//Mapping Column Columns
if(!via.undef(odinLite_fileFormat.mappedColumns,true)) {
for (var i in odinLite_fileFormat.mappedColumns) {
var mapColumn = odinLite_fileFormat.mappedColumns[i];
var idx = getColumnIndex(mapColumn.dataColumn);
if(idx === -1){
//via.kendoAlert("Get Column Error","Cannot find ("+mapColumn.dataColumn+") in dataset.");
//return;
continue;
}
comboArr[idx].text = mapColumn.templateColumn;
comboArr[idx].value = mapColumn.templateColumn;
}
}
*/
return comboArr;
/** Functions **/
function getColumnIndex(columnName){
var headers = odinLite_modelMapping.getColumnListFromTableSet();
headers.splice(0,1);
for(var i=0;i<headers.length;i++){
if(headers[i].text === columnName){
return i;
}
}
return -1;
}
},
/**
* advancedSettingsWindow
* This will a user to add a static column
*/
advancedSettingsWindow: function(tabName){
if(via.undef(odinLite_fileFormat.FILE_DATA) || via.undef(odinLite_fileFormat.FILE_DATA.tsEncoded) ||
via.undef(odinLite_fileFormat.FILE_DATA.tsEncoded.columnHeaders)){
return;
}
//Get the window template
$.get("./html/advancedSettingsWindow.html", function (entityWindowTemplate) {
$('#odinLite_advancedSettingsWindow').remove();
$('body').append(entityWindowTemplate);
//Make the window.
var addColumnWindow = $('#odinLite_advancedSettingsWindow').kendoWindow({
title: "Advanced ETL Settings",
draggable: false,
resizable: false,
width: "1050px",
height: "550px",
modal: true,
close: true,
animation: false,
actions: [
"Minimize",
"Maximize",
"Close"
],
close: function () {
addColumnWindow = null;
$('#odinLite_advancedSettingsWindow').remove();
}
}).data("kendoWindow");
addColumnWindow.center();
var isSqlLoaded = false;
var tab = $("#advancedSettings_tabstrip").kendoTabStrip({
animation: {
open: {
effects: "fadeIn"
}
},
select: function(e){
var selectedTab = $(e.item).find("> .k-link").text();
if(selectedTab === 'Data Merge Options'){
$('.fileFormat_runToAdvancedSettingsButton').hide();
}else{
$('.fileFormat_runToAdvancedSettingsButton').show();
}
//SQL Query
if(selectedTab === 'SQL Engine'){
//Get the file preview from the server based on the settings.
$.post(odin.SERVLET_PATH,
{
action: 'odinLite.uploadFiles.getH2SqlDefaultQuery',
columnHeaders: JSON.stringify(odinLite_fileFormat.FILE_DATA.tsEncoded.columnHeaders)
},
function(data, status){
if(!via.undef(data,true) && data.success === false) {
via.debug("Failure getting default query:", data.message);
via.kendoAlert("Failure getting default query", data.message);
odinLite_fileFormat.defaultSQLQuery = null;
odinLite_fileFormat.sqlQuery = null;
}else{
//Populate the default query
if(!via.undef(data.defaultQuery,true) && isSqlLoaded === false) {
$('#fileFormat_dbTransfer_sqlArea').val(data.defaultQuery);
odinLite_fileFormat.defaultSQLQuery = data.defaultQuery;
if(!via.undef(odinLite_fileFormat.FILE_DATA.tsEncoded)) {
odinTable.createTable("fileFormat_sqlDataTable", odinLite_fileFormat.FILE_DATA.tsEncoded, "#fileFormat_dbResultGrid");
$('#fileFormat_sqlDataTable').data('kendoGrid').setOptions({
groupable: false,
height: '99%'
});
$('#odinLite_dbResultGrid').css("padding", "0");
}
}
//Update the column list
if(!via.undef(data.columnHeaders)) {
var listBox = $("#fileFormat_sqlColumnNames").data('kendoListBox');
var colArr = [];
for (var i = 0; i < data.columnHeaders.length; i++) {
colArr.push({text: data.columnHeaders[i]});
}
listBox.setDataSource(colArr);
$(".fileFormat_sqlColumnNames li").bind('dblclick', function (e) {
var tree = $("#fileFormat_sqlColumnNames").data('kendoListBox');
var selected = tree.select();
var dataItem = tree.dataItem(selected);
var cm = $('#fileFormat_dbTransfer_sqlArea').data('CodeMirrorInstance');
var doc = cm.getDoc();
doc.replaceRange(" "+dataItem.text, {line: Infinity}); // adds a new line
});
}
//Style the code editor
if(via.undef($('#fileFormat_dbTransfer_sqlArea').data('CodeMirrorInstance'))){
kendo.ui.progress($('#odinLite_advancedSettingsWindow'), true);//Wait Message
$("#fileFormat_dbTransfer_sqlArea").hide();
setTimeout(function () {
$("#fileFormat_dbTransfer_sqlArea").show();
var editor = CodeMirror.fromTextArea(document.getElementById("fileFormat_dbTransfer_sqlArea"), {
mode: "text/x-sql",
indentWithTabs: true,
smartIndent: true,
lineWrapping: true,
lineNumbers: true,
matchBrackets: true,
autofocus: true,
extraKeys: {"Ctrl-Space": "autocomplete"},
value: (via.undef(odinLite_fileFormat.sqlQuery, true)) ? "" : odinLite_fileFormat.sqlQuery
});
editor.setSize("100%", 200);
kendo.ui.progress($('#odinLite_advancedSettingsWindow'), false);//Wait Message
// store it
$('#fileFormat_dbTransfer_sqlArea').data('CodeMirrorInstance', editor);
}, 500);
}
isSqlLoaded = true;
}
},
'json');
}
},
value: tabName
});
/*
if(!via.undef(selectedTab,true)) {
console.log('selecting ' + selectedTab);
tab.activateTab(selectedTab);
}
*/
//Button Events
$('.fileFormat_applyAdvancedSettingsButton').click(function(){
/** Set the Data **/
odinLite_fileFormat.mappedColumns = $("#fileFormat_mapColumn_grid").data('kendoGrid').dataSource.data().toJSON();
odinLite_fileFormat.staticColumns = $("#fileFormat_addColumn_grid").data('kendoGrid').dataSource.data().toJSON();
odinLite_fileFormat.filterRules = $("#fileFormat_filterData_finalGrid").data('kendoGrid').dataSource.data().toJSON();
odinLite_fileFormat.validationRules = $("#fileFormat_validateData_finalGrid").data('kendoGrid').dataSource.data().toJSON();
odinLite_fileFormat.dataManagementPlugin = $('#fileFormat_dataManagementPlugin').data('kendoDropDownList').value();
odinLite_fileFormat.dataMergeOptions.timeSeries = $('#modelMapping_timeSeriesMerge').prop("checked");
odinLite_fileFormat.dataMergeOptions.portIndex = $('#modelMapping_timeSeriesToPortIndexMerge').prop("checked");
odinLite_fileFormat.dataMergeOptions.attributeData = $('#modelMapping_attributeData').prop("checked");
//SQL editor
var codeEditor = $('#fileFormat_dbTransfer_sqlArea').data('CodeMirrorInstance');
if(!via.undef(codeEditor)) {
odinLite_fileFormat.sqlQuery = codeEditor.getValue();
}
//Close the window
addColumnWindow.close();
//Update the preview based on the settings
odinLite_fileFormat.updateFilePreview();
});
//Run to here data.
$('.fileFormat_runToAdvancedSettingsButton').click(function(){
var tabstrip = $("#advancedSettings_tabstrip").data('kendoTabStrip');
var selectedTab = tabstrip.select();
var tabName = $(selectedTab).children(".k-link").text();
var settingTypes = [];
switch(tabName){
case 'Data Management Plug-in':
settingTypes = ['dataManagementPlugin'];
break;
case 'Map Column':
settingTypes = ['dataManagementPlugin','mappedColumns'];
break;
case 'Add Column':
settingTypes = ['dataManagementPlugin','mappedColumns','staticColumns'];
break;
case 'Filter Data':
settingTypes = ['dataManagementPlugin','mappedColumns','staticColumns','filterRules'];
break;
case 'Validate Data':
settingTypes = ['dataManagementPlugin','mappedColumns','staticColumns','filterRules','validationRules'];
break;
case 'SQL Engine':
settingTypes = ['dataManagementPlugin','mappedColumns','staticColumns','filterRules','validationRules','sqlQuery'];
break;
};
//Store the temp values
var tmpMappedColumns = $("#fileFormat_mapColumn_grid").data('kendoGrid').dataSource.data().toJSON();
var tmpStaticColumns = $("#fileFormat_addColumn_grid").data('kendoGrid').dataSource.data().toJSON();
var tmpFilterRules = $("#fileFormat_filterData_finalGrid").data('kendoGrid').dataSource.data().toJSON();
var tmpValidationRules = $("#fileFormat_validateData_finalGrid").data('kendoGrid').dataSource.data().toJSON();
var tmpDataManagementPlugin = $('#fileFormat_dataManagementPlugin').data('kendoDropDownList').value();
var tmpDataMergeOptions = {};
tmpDataMergeOptions.timeSeries = $('#modelMapping_timeSeriesMerge').prop("checked");
tmpDataMergeOptions.portIndex = $('#modelMapping_timeSeriesToPortIndexMerge').prop("checked");
tmpDataMergeOptions.attributeData = $('#modelMapping_attributeData').prop("checked");
//SQL editor
var tmpSqlQuery = null;
var codeEditor = $('#fileFormat_dbTransfer_sqlArea').data('CodeMirrorInstance');
if(!via.undef(codeEditor)) {
tmpSqlQuery = codeEditor.getValue();
}
//Reset the Advanced Setting
odinLite_fileFormat.mappedColumns = [];
odinLite_fileFormat.staticColumns = [];
odinLite_fileFormat.filterRules = [];
odinLite_fileFormat.validationRules = [];
odinLite_fileFormat.dataManagementPlugin = null;
odinLite_fileFormat.dataMergeOptions = {};
odinLite_fileFormat.sqlQuery = null;
//Build the Advanced Settings
if($.inArray('dataManagementPlugin',settingTypes)!== -1){
odinLite_fileFormat.dataManagementPlugin = $('#fileFormat_dataManagementPlugin').data('kendoDropDownList').value();
}
if($.inArray('mappedColumns',settingTypes)!== -1){
odinLite_fileFormat.mappedColumns = $("#fileFormat_mapColumn_grid").data('kendoGrid').dataSource.data().toJSON();
}
if($.inArray('staticColumns',settingTypes)!== -1){
odinLite_fileFormat.staticColumns = $("#fileFormat_addColumn_grid").data('kendoGrid').dataSource.data().toJSON();
}
if($.inArray('filterRules',settingTypes)!== -1){
odinLite_fileFormat.filterRules = $("#fileFormat_filterData_finalGrid").data('kendoGrid').dataSource.data().toJSON();
}
if($.inArray('validationRules',settingTypes)!== -1){
odinLite_fileFormat.validationRules = $("#fileFormat_validateData_finalGrid").data('kendoGrid').dataSource.data().toJSON();
}
if($.inArray('sqlQuery',settingTypes)!== -1){
odinLite_fileFormat.sqlQuery = tmpSqlQuery + "";
}
odinLite_fileFormat.dataMergeOptions.timeSeries = $('#modelMapping_timeSeriesMerge').prop("checked");
odinLite_fileFormat.dataMergeOptions.portIndex = $('#modelMapping_timeSeriesToPortIndexMerge').prop("checked");
odinLite_fileFormat.dataMergeOptions.attributeData = $('#modelMapping_attributeData').prop("checked");
//Update the preview based on the settings
odinLite_fileFormat.updateFilePreview(function(){
//Close the window
addColumnWindow.close();
//Launch the window
odinLite_fileFormat.advancedSettingsWindow(tabName);
});
//Reset the values
odinLite_fileFormat.mappedColumns = tmpMappedColumns;
odinLite_fileFormat.staticColumns = tmpStaticColumns;
odinLite_fileFormat.filterRules = tmpFilterRules;
odinLite_fileFormat.validationRules = tmpValidationRules;
odinLite_fileFormat.dataManagementPlugin = tmpDataManagementPlugin;
odinLite_fileFormat.dataMergeOptions = tmpDataMergeOptions;
odinLite_fileFormat.sqlQuery = tmpSqlQuery + "";
});
/* Add Column */
odinLite_fileFormat.advancedSettingsWindow_addColumn();
/* Map Column */
odinLite_fileFormat.advancedSettingsWindow_mapColumn();
/* Data Merge Options */
odinLite_fileFormat.advancedSettingsWindow_dataMergeOptions();
/* Data Management Plugins */
odinLite_fileFormat.advancedSettingsWindow_dataManagementPlugins();
/* Filter Data */
odinLite_fileFormat.advancedSettingsWindow_filterData();
/* Validate Data */
odinLite_fileFormat.advancedSettingsWindow_validateData();
/* SQL Query */
isSqlLoaded = odinLite_fileFormat.advancedSettingsWindow_sqlQuery(isSqlLoaded);
//Shut off the wait
kendo.ui.progress($("body"), false);//Wait Message
});//End Template fetch
},
/**
* advancedSettingsWindow_sqlQuery
* Setup the advanced settings for SQL query
*/
advancedSettingsWindow_sqlQuery: function(isSqlLoaded){
//Setup the Column List
$("#fileFormat_sqlColumnNames").kendoListBox({
dataTextField: "text",
dataValueField: "text",
dataSource: []
});
//Button Events
$('.fileFormat_sqlQuery_refresh').click(function(){
var codeeditor = $('#fileFormat_dbTransfer_sqlArea').data('CodeMirrorInstance');
codeeditor.setValue(via.undef(odinLite_fileFormat.defaultSQLQuery)?"":odinLite_fileFormat.defaultSQLQuery);
});
$('#fileFormat_dbQueryButton').click(function(){
kendo.ui.progress($('#odinLite_advancedSettingsWindow'), true);//Wait Message
var tmpSql = odinLite_fileFormat.sqlQuery;
var codeeditor = $('#fileFormat_dbTransfer_sqlArea').data('CodeMirrorInstance');
odinLite_fileFormat.sqlQuery = codeeditor.getValue(odinLite_fileFormat.sqlQuery);
odinLite_fileFormat.updateFilePreview(function(data){
kendo.ui.progress($('#odinLite_advancedSettingsWindow'), false);//Wait Message
$('#fileFormat_dbResultGrid').empty();
if(data.success === false && !via.undef(data.message)) {
var dialog = $('.k-dialog').data('kendoDialog');
if (!via.undef(dialog)) {
dialog.close();
}
$('#fileFormat_dbResultGrid').html('<div class="well" style="color:red;margin-top:5px;">'+data.message+"</div>");
}else if(!via.undef(data.tsEncoded)) {
odinLite_fileFormat.sqlQuery = tmpSql;
odinTable.createTable("fileFormat_sqlDataTable", data.tsEncoded, "#fileFormat_dbResultGrid");
$('#fileFormat_sqlDataTable').data('kendoGrid').setOptions({
groupable: false,
height: '99%'
});
$('#odinLite_dbResultGrid').css("padding", "0");
}
if(!via.undef($('#odinLite_advancedSettingsWindow').data('kendoWindow'))) {
$('#odinLite_advancedSettingsWindow').data('kendoWindow').center();
}
});
});
return isSqlLoaded;
},
/**
* getAdvancedSettingsOptions
* Returns the advanced settings in the format they need to be for the server.
*/
getAdvancedSettingsOptions: function() {
var advancedSettingsOptions = {};
//Add Column
advancedSettingsOptions.staticColumns = JSON.stringify(odinLite_fileFormat.staticColumns);
//Map Column
advancedSettingsOptions.mappedColumns = JSON.stringify(odinLite_fileFormat.mappedColumns);
//Data Merge Options
advancedSettingsOptions.dataMergeTimeSeries = false;
advancedSettingsOptions.dataMergePortfolioIndexed = false;
advancedSettingsOptions.attributeData = false;
if(!via.undef(odinLite_fileFormat.dataMergeOptions,true)){
advancedSettingsOptions.dataMergeTimeSeries = via.undef(odinLite_fileFormat.dataMergeOptions.timeSeries,true)?false:odinLite_fileFormat.dataMergeOptions.timeSeries;
advancedSettingsOptions.dataMergePortfolioIndexed = via.undef(odinLite_fileFormat.dataMergeOptions.portIndex,true)?false:odinLite_fileFormat.dataMergeOptions.portIndex;
advancedSettingsOptions.attributeData = via.undef(odinLite_fileFormat.dataMergeOptions.attributeData,true)?false:odinLite_fileFormat.dataMergeOptions.attributeData;
}
//Data Management Plugin
advancedSettingsOptions.dataManagementPlugin = null;
if(!via.undef(odinLite_fileFormat.dataManagementPlugin,true)){
advancedSettingsOptions.dataManagementPlugin = odinLite_fileFormat.dataManagementPlugin;
}
//Filter Rules
advancedSettingsOptions.filterRules = JSON.stringify(odinLite_fileFormat.filterRules);
//Validation Rules
advancedSettingsOptions.validationRules = JSON.stringify(odinLite_fileFormat.validationRules);
//SQL Query
if(odinLite_fileFormat.sqlQuery !== odinLite_fileFormat.defaultSQLQuery) {
advancedSettingsOptions.sqlQuery = odinLite_fileFormat.sqlQuery;
}
//console.log('advancedSettingsOptions',advancedSettingsOptions);
return advancedSettingsOptions;
},
//getAdvancedSettingsOptionsOLD: function() {
// var advancedSettingsOptions = {};
//
// /** Static Columns **/
// advancedSettingsOptions.staticColumns = null;
// if(!via.undef(odinLite_fileFormat.staticColumns,true)){
// //Rows: List of row they added. Save in format:
// // Template Column 1; Operation Type 1; Assign Value; Prefix Value 1; Prefix Is RegEx Format 1; Suffix Value 1; Suffix Is RegEx Format 1; Value Date Format 1;Column Operation Type 1;Column List 1|||Template Column 2; Operation Type 2; Assign Value; Prefix Value 2; Prefix Is RegEx Format 2; Suffix Value 2; Suffix Is RegEx Format 2; Value Date Format 2;Column Operation Type 2;Column List 2
// var addString = "";
// for(var i in odinLite_fileFormat.staticColumns) {
// var col = odinLite_fileFormat.staticColumns[i];
//
// //Separate
// if(addString.length > 0){
// addString+="|||";
// }
//
// //Template Column
// addString += (via.undef(col.columnName)?"":col.columnName) + ";";
//
// //Operation Type
// addString += (via.undef(col.columnType)?"":col.columnType) + ";";
//
// //Data Type
// addString += (via.undef(col.dataType)?"":col.dataType) + ";";
//
// //Assign Value
// addString += (via.undef(col.value)?"":col.value) + ";";
//
// //Prefix Value
// addString += (via.undef(col.prefix)?"":col.prefix) + ";";
//
// //Prefix Is RegEx Format
// addString += (via.undef(col.prefixRegex)?"false":col.prefixRegex) + ";";
//
// //Suffix Value
// addString += (via.undef(col.suffix)?"":col.suffix) + ";";
//
// //Suffix Is RegEx Format
// addString += (via.undef(col.suffixRegex)?"false":col.suffixRegex) + ";";
//
// //Value Date Format
// addString += (via.undef(col.dateFormat)?"":col.dateFormat) + ";";
//
// //Column Operation Type
// addString += (via.undef(col.operationType)?"":col.operationType) + ";";
//
// //Column List
// addString += (via.undef(col.columnList)?"":col.columnList);
// }
// advancedSettingsOptions.staticColumns = addString;
// }
//
//
//
// /** Mapped Columns **/
// advancedSettingsOptions.mappedColumns = null;
// if(!via.undef(odinLite_fileFormat.mappedColumns,true)){
// //Data Column 1;Template Column 1;Data Type 1;Date Format 1|||Data Column 2;Template Column 2;Data Type 2;Date Format 2
// var mapString = "";
// for(var i in odinLite_fileFormat.mappedColumns){
// var col = odinLite_fileFormat.mappedColumns[i];
// if(mapString.length > 0){
// mapString+="|||";
// }
// //Column and template col
// mapString += col.dataColumn +";"+ col.templateColumn;
// //Data Type
// mapString += ";";
// mapString += ((via.undef(col.dataType,true))?"":col.dataType);
// //Date Format
// mapString += ";";
// mapString += ((via.undef(col.dateFormat,true))?"":col.dateFormat);
// }
// advancedSettingsOptions.mappedColumns = mapString;
// }
//
// /** Data Merge Options **/
// advancedSettingsOptions.dataMergeTimeSeries = false;
// advancedSettingsOptions.dataMergePortfolioIndexed = false;
// if(!via.undef(odinLite_fileFormat.dataMergeOptions,true)){
// advancedSettingsOptions.dataMergeTimeSeries = via.undef(odinLite_fileFormat.dataMergeOptions.timeSeries,true)?false:odinLite_fileFormat.dataMergeOptions.timeSeries;
// advancedSettingsOptions.dataMergePortfolioIndexed = via.undef(odinLite_fileFormat.dataMergeOptions.portIndex,true)?false:odinLite_fileFormat.dataMergeOptions.portIndex;
// }
//
// /** Data Management Plugin **/
// advancedSettingsOptions.dataManagementPlugin = null;
// if(!via.undef(odinLite_fileFormat.dataManagementPlugin,true)){
// advancedSettingsOptions.dataManagementPlugin = odinLite_fileFormat.dataManagementPlugin;
// }
//
// /** Filter Rules **/
// advancedSettingsOptions.filterRules = null;
// if(!via.undef(odinLite_fileFormat.filterRules,true)){
// //[Where Clause Type 1; Data Column 1; Date Type 1; Operation 1; Comparison Type 1; Comparison Value 1; Comparison Column 1][Where Clause Type 2; Data Column 2; ; Date Type 2; Operation 2; Comparison Type 2; Comparison Value 2; Comparison Column 2]
// var filterString = "";
// for(var i in odinLite_fileFormat.filterRules){
// //Seperate
// if(i>0){
// filterString += "|||";
// }
// filterString += odinLite_fileFormat.filterRules[i].whereClause;
// }
// advancedSettingsOptions.filterRules = filterString;
// }
//
// /** Validation Rules **/
// advancedSettingsOptions.validationRules = null;
// if(!via.undef(odinLite_fileFormat.validationRules,true)){
// var validationString = "";
// for(var i in odinLite_fileFormat.validationRules){
// //Seperate
// if(i>0){
// validationString += "|||";
// }
// //Add the where clause
// validationString += odinLite_fileFormat.validationRules[i].whereClause;
//
// //Add the Validation rules.
// validationString += ":::";
// validationString += odinLite_fileFormat.validationRules[i].validationOperation + ";";
// validationString += odinLite_fileFormat.validationRules[i].validationColumn + ";";
// validationString += (via.undef(odinLite_fileFormat.validationRules[i].validationValue,true))?";":(odinLite_fileFormat.validationRules[i].validationValue + ";");
// validationString += (via.undef(odinLite_fileFormat.validationRules[i].validationFetchColumn,true))?";":(odinLite_fileFormat.validationRules[i].validationFetchColumn);
// }
// advancedSettingsOptions.validationRules = validationString;
// }
//
// console.log("advancedSettingsOptions old",advancedSettingsOptions);
// return advancedSettingsOptions;
//},
/**
* saveSettings
* This will save the file format settings to the server.
*/
saveSettings: function(){
var formattingObj = odinLite_fileFormat.getFormattingOptions();
var saveJson = {
//Save the file formatting
delimType:formattingObj.delimType,
endColumn:JSON.stringify(formattingObj.endColumn),
endRow:JSON.stringify(formattingObj.endRow),
hasColumnHeader:JSON.stringify(formattingObj.hasColumnHeader),
startColumn:JSON.stringify(formattingObj.startColumn),
startRow:JSON.stringify(formattingObj.startRow),
textQualifier:JSON.stringify(formattingObj.textQualifier),
//Save the Advanced Settings
//staticColumns: JSON.stringify(odinLite_fileFormat.staticColumns),
//mappedColumns: JSON.stringify(odinLite_fileFormat.mappedColumns),
//dataMergeOptions: JSON.stringify(odinLite_fileFormat.dataMergeOptions),
//dataManagementPlugin: odinLite_fileFormat.dataManagementPlugin,
//filterRules: JSON.stringify(odinLite_fileFormat.filterRules),
//validationRules: JSON.stringify(odinLite_fileFormat.validationRules)
};
$.extend(saveJson,odinLite_fileFormat.getAdvancedSettingsOptions());
//console.log('saveJson',saveJson);
//console.log('saveJsonStr',JSON.stringify(saveJson));
via.saveWindow(odin.ODIN_LITE_APP_ID,odinLite_modelCache.currentEntity.saveId,JSON.stringify(saveJson),function(reportName){
$('.fileFormat_reportName').html("<b>Loaded: </b>" + reportName);
},true);
},
/**
* loadSettings
* This will load launch the load window.
*/
loadSettingsWindow: function(){
via.loadWindow(odin.ODIN_LITE_APP_ID,odinLite_modelCache.currentEntity.saveId,function(loadJson){
//console.log('loadJson',loadJson);
odinLite_fileFormat.loadSettings(loadJson);
});
},
/**
* loadSettings
* This will load the saved file format settings from the passed json and update the preview.
*/
loadSettings: function(loadJson){
if(via.undef(loadJson,true)){
via.kendoAlert("Load Error","Report not found.");
return;
}
//console.log('loadJson',loadJson);
//Display the name of the report.
odinLite_fileFormat.loadedReport = null;
$('.fileFormat_reportName').empty();
if(!via.undef(loadJson.reportName)){
odinLite_fileFormat.loadedReport = loadJson.reportName;
$('.fileFormat_reportName').html("<b>Loaded: </b>" + loadJson.reportName);
}
//Load the file formatting
odinLite_fileFormat.FILE_DATA.endColumn = JSON.parse(loadJson.endColumn);
odinLite_fileFormat.FILE_DATA.endRow = JSON.parse(loadJson.endRow);
odinLite_fileFormat.FILE_DATA.hasColumnHeader = JSON.parse(loadJson.hasColumnHeader);
odinLite_fileFormat.FILE_DATA.isTemplateFile = via.undef(loadJson.isTemplateFile,true)?false:JSON.parse(loadJson.isTemplateFile);
odinLite_fileFormat.FILE_DATA.startColumn = JSON.parse(loadJson.startColumn);
odinLite_fileFormat.FILE_DATA.startRow = JSON.parse(loadJson.startRow);
odinLite_fileFormat.FILE_DATA.textQualifier = JSON.parse(loadJson.textQualifier);
odinLite_fileFormat.FILE_DATA.delimType = loadJson.delimType;
//Load the Advanced Settings
odinLite_fileFormat.staticColumns = JSON.parse(loadJson.staticColumns);
odinLite_fileFormat.mappedColumns = JSON.parse(loadJson.mappedColumns);
odinLite_fileFormat.dataMergeOptions = {};
odinLite_fileFormat.dataMergeOptions.portIndex = via.undef(loadJson.dataMergePortfolioIndexed,true)?false:JSON.parse(loadJson.dataMergePortfolioIndexed);
odinLite_fileFormat.dataMergeOptions.timeSeries = via.undef(loadJson.dataMergeTimeSeries,true)?false:JSON.parse(loadJson.dataMergeTimeSeries);
odinLite_fileFormat.dataMergeOptions.attributeData = via.undef(loadJson.attributeData,true)?false:JSON.parse(loadJson.attributeData);
odinLite_fileFormat.dataManagementPlugin = loadJson.dataManagementPlugin;
odinLite_fileFormat.filterRules = JSON.parse(loadJson.filterRules);
odinLite_fileFormat.validationRules = JSON.parse(loadJson.validationRules);
odinLite_fileFormat.sqlQuery = loadJson.sqlQuery;
//Set the formatting
odinLite_fileFormat.setFormattingOptions();
//Update the preview
odinLite_fileFormat.updateFilePreview();
},
/**
* initFilePreview
* This will setup the file preview section
* overrideInitialValues - this is for the excel sheet viewer to override the start row and end column
*/
initFilePreview: function(overrideInitialValues){
kendo.ui.progress($("body"), true);//Wait Message
//Show the panel
$('#fileFormatPanel').fadeIn();
//List of files uploaded or sheets if it multi-sheet one excel.
$('#fileFormat_fileList').kendoDropDownList({
dataTextField: "text",
dataValueField: "value",
dataSource: odinLite_fileFormat.getDropdownList(),
value: odinLite_fileFormat.FILE_DATA.fileIdx,
change: function(a){
odinLite_fileFormat.FILE_DATA.fileIdx = a.sender.value();
odinLite_fileFormat.updateFilePreview();
}
});
//Based on the type set the appropriate settings
if(odinLite_fileFormat.FILE_DATA.isTemplateFile===true){
$("#fileFormatDelimiterPanel").hide();
$(".fileFormat_settingText").hide();
$("#fileFormat_settingsPanel").hide();
}else if(!odinLite_fileFormat.isExcel()){
$("#fileFormatDelimiterPanel").show();
$("#fileFormat_textQualifierBox").show();
}else{
$("#fileFormatDelimiterPanel").hide();
$("#fileFormat_textQualifierBox").hide();
}
//apply the kendo widgets
if(odinLite_fileFormat.hasBeenLoaded === false) {
$("#fileFormat_startRow").kendoNumericTextBox({
format: "n0",
min: 1,
decimals: 0,
restrictDecimals: true
});
$("#fileFormat_endRow").kendoNumericTextBox({
format: "n0",
decimals: 0,
restrictDecimals: true
});
$("#fileFormat_startColumn").kendoNumericTextBox({
format: "n0",
min: 1,
decimals: 0,
restrictDecimals: true
});
$("#fileFormat_endColumn").kendoNumericTextBox({
format: "n0",
decimals: 0,
restrictDecimals: true
});
}
//See if there is a Platform Saved Report otherwise look for default, then just try to guess.
if(!via.undef(odinLite_uploadFiles.fileSavedReport)){
via.confirm("Load System Report","Would you like to load the system report: " + odinLite_uploadFiles.fileSavedReport,function(){
via.debug("Loading System Report:",odinLite_uploadFiles.fileSavedReport);
//Load the system saved report.
via.loadReport(odin.ODIN_LITE_APP_ID,odinLite_modelCache.currentEntity.saveId,odinLite_uploadFiles.fileSavedReport,"Common",
function(loadJson){
odinLite_fileFormat.loadSettings(loadJson);
});
},
function(){//No
//Update the initial values
odinLite_fileFormat.setFormattingOptions();
//Update the preview for the first time.
odinLite_fileFormat.updateFilePreview(null, overrideInitialValues);
});
}else {
//Check for a default report. Otherwise guess at the format.
via.loadDefaultReport(odin.ODIN_LITE_APP_ID, odinLite_modelCache.currentEntity.saveId,
function (loadJson) {//There is a default report.
odinLite_fileFormat.loadSettings(loadJson);
},
function () {//No Default Report Exists
//Update the initial values
odinLite_fileFormat.setFormattingOptions();
//Update the preview for the first time.
odinLite_fileFormat.updateFilePreview(null, overrideInitialValues);
}
);
}
},
/**
* getDropdownList
* Returns the dropdown list for the file preview / also used in Model Mapping
*/
getDropdownList: function(){
//Setup the file drop down list - sheets or files.
var dropDownList = odinLite_fileFormat.FILE_DATA.localFiles;//Default to files
//Check for sheets
//if(!via.undef(odinLite_fileFormat.FILE_DATA.sheetNames) && odinLite_fileFormat.FILE_DATA.sheetNames.length > 1
// && odinLite_fileFormat.FILE_DATA.files.length === 1){
if(odinLite_fileFormat.isMultiSheet === true){
dropDownList = odinLite_fileFormat.FILE_DATA.sheetNames;
}
var fileData = [];
for(var i=0;i<dropDownList.length;i++){
fileData.push({ text: dropDownList[i], value: i });
}
//Sort the object.
fileData.sort(function(a, b){
var textA=null;
if(!via.undef(a) && !via.undef(a.text,true)){
textA=(a.text+"").toLowerCase();
}
var textB=null;
if(!via.undef(b) && !via.undef(b.text,true)){
textB=(b.text+"").toLowerCase();
}
if (textA < textB) //sort string ascending
return -1;
if (textA > textB)
return 1;
return 0;
});
return fileData;
},
/**
* updateFilePreview
* Updates the file preview based on the settings passed.
*/
updateFilePreview: function(callbackFn,overrideInitialValues){
kendo.ui.progress($("#import_fileFormat_spreadsheet"), true);//Wait Message
//Update the formatting options.
var formattingOptions = odinLite_fileFormat.getFormattingOptions();
$.extend(odinLite_fileFormat.FILE_DATA,formattingOptions);
//Get the advanced settings options
var advancedSettingsOptions = odinLite_fileFormat.getAdvancedSettingsOptions();
//Sheet Names
var sheetNames = null;
if(!via.undef(odinLite_fileFormat.FILE_DATA.sheetNames,true)){
sheetNames = JSON.stringify(odinLite_fileFormat.FILE_DATA.sheetNames);
}
//Clear the total rows
$('#import_fileFormat_totalRows').empty();
var serverVars = $.extend({
action: 'odinLite.uploadFiles.getFilePreview',
type: odinLite_fileFormat.FILE_DATA.type,
files: JSON.stringify(odinLite_fileFormat.FILE_DATA.files),
localFiles: JSON.stringify(odinLite_fileFormat.FILE_DATA.localFiles),
idx: odinLite_fileFormat.FILE_DATA.fileIdx,
sheetNames: sheetNames,
overrideInitialValues: overrideInitialValues,
unionData: JSON.stringify(odinLite_unionFiles.getUnionData()),
overrideUser: odinLite.OVERRIDE_USER
},formattingOptions,advancedSettingsOptions);
//Get the file preview from the server based on the settings.
$.post(odin.SERVLET_PATH,
serverVars,
function(data, status){
kendo.ui.progress($("#import_fileFormat_spreadsheet"), false);//Wait Message off
//JSON parse does not like NaN
if(!via.undef(data,true)){
data = JSON.parse(data.replace(/\bNaN\b/g, "null"));
}
if(!via.undef(data,true) && data.success === false){
via.debug("Failure generating preview:", data.message);
if(!via.undef(odinLite_fileFormat.loadedReport,true)){
via.kendoAlert("Failure generating preview", data.message,function(){
$('#import_fileFormat_spreadsheet').empty();
});
/*via.kendoAlert("Failure generating preview", data.message + "<br/><b>Unloading saved report:</b> " + odinLite_fileFormat.loadedReport, function () {
odinLite_fileFormat.loadedReport = null;
$('.fileFormat_reportName').empty();//Remove the loaded report text
odinLite_fileFormat.clearAdvancedSettings();//Clear advanced settings.
//Update the initial values
odinLite_fileFormat.setInitialValues();
odinLite_fileFormat.setFormattingOptions();
//Update the preview for the first time.
odinLite_fileFormat.updateFilePreview(null, overrideInitialValues);
$('#fileFormat_nextButton').prop("disabled",false);
$('#fileFormat_downloadButton').prop("disabled",false);
});*/
}else {
via.kendoAlert("Failure generating preview", data.message, function () {
if (via.undef(data.tsEncoded)) {
//odinLite_fileFormat.clearAdvancedSettings();//Clear advanced settings.
$("#import_fileFormat_spreadsheet").empty();
$("#import_fileFormat_spreadsheet").html("<p style=\"margin:10px;\"><b>Error found:</b> Please review Advanced Settings.</p>");
$('#fileFormat_nextButton').prop("disabled",true);
$('#fileFormat_downloadButton').prop("disabled",true);
}
});
}
}else{
//Re-enable the next button and the download button.
$('#fileFormat_nextButton').prop("disabled",false);
$('#fileFormat_downloadButton').prop("disabled",false);
via.debug("Successful generating preview:", data);
odinLite_fileFormat.originalHeaders = data.originalHeaders;
odinLite_fileFormat.unionHeaders = data.unionHeaders;
odinLite_fileFormat.FILE_DATA.tsEncoded = data.tsEncoded;
//if(via.undef(data.tsEncoded)){//Clear the advanced settings if the tableset is null
// odinLite_fileFormat.clearAdvancedSettings();
//}
if(overrideInitialValues===true && !via.undef(data.tsEncoded.columnHeaders)){//override the end column if needed.
$('#fileFormat_endColumn').data("kendoNumericTextBox").value(data.tsEncoded.columnHeaders.length);
odinLite_fileFormat.FILE_DATA.endColumn = data.tsEncoded.columnHeaders.length;
}
$('#fileFormat_advancedSettingsButton').prop("disabled",false);//Enable the advanced settings button
//Get the # of rows to display
var maxRows = $("#import_fileFormat_rows").data('kendoDropDownList').value();
if(maxRows === "All"){
maxRows = null;
}
//Add the total rows
if(!via.undef(odinLite_fileFormat.FILE_DATA.tsEncoded)) {
$('#import_fileFormat_totalRows').html(" of " + kendo.toString(odinLite_fileFormat.FILE_DATA.tsEncoded.data.length,"#,##0"));
}
var sheetData = odinLite_fileFormat.getSpreadsheetDataFromTableSet(odinLite_fileFormat.FILE_DATA.tsEncoded,false,false,maxRows);
//Freeze the top Row.
sheetData.frozenRows = 1;
//Insert the sheet preview.
$("#import_fileFormat_spreadsheet").empty();
$("#import_fileFormat_spreadsheet").kendoSpreadsheet({
height: '200px',
headerHeight: 20,
//headerWidth: 0,
rows: 20,
toolbar: false,
sheetsbar: false,
sheets: [sheetData]
});
$("#import_fileFormat_spreadsheet .k-spreadsheet-sheets-bar-add").hide();
$("#import_fileFormat_spreadsheet .k-link").prop( "disabled", true );
}
//Callback function - used in model mapping and in sql
if(!via.undef(callbackFn)) {
callbackFn(data);
}
},
'text');
},
/**
* This will get the file export window that will export the files and figure out the type.
*/
getExportFilesWindow: function(){
odinLite.getExportFilesWindow(function(fileType,delimiter){
kendo.ui.progress($("body"), true);//Wait Message
//Update the formatting options.
var formattingOptions = odinLite_fileFormat.getFormattingOptions();
$.extend(odinLite_fileFormat.FILE_DATA,formattingOptions);
//Get the advanced settings options
var advancedSettingsOptions = odinLite_fileFormat.getAdvancedSettingsOptions();
//Sheet Names
var sheetNames = null;
if(!via.undef(odinLite_fileFormat.FILE_DATA.sheetNames,true)){
sheetNames = JSON.stringify(odinLite_fileFormat.FILE_DATA.sheetNames);
}
var serverVars = $.extend({
action: 'odinLite.uploadFilesExport.exportFiles',
type: odinLite_fileFormat.FILE_DATA.type,
files: JSON.stringify(odinLite_fileFormat.FILE_DATA.files),
localFiles: JSON.stringify(odinLite_fileFormat.FILE_DATA.localFiles),
idx: odinLite_fileFormat.FILE_DATA.fileIdx,
sheetNames: sheetNames,
unionData: JSON.stringify(odinLite_unionFiles.getUnionData()),
overrideUser: odinLite.OVERRIDE_USER,
fileType: fileType,
fileDelimiter: delimiter
},formattingOptions,advancedSettingsOptions);
$.post(odin.SERVLET_PATH,
serverVars,
function(data, status){
kendo.ui.progress($("body"), false);//wait off
if(!via.undef(data,true) && data.success === false){
via.debug("File Export Error:", data.message);
via.alert("File Export Error",data.message);
}else{//Success - export
via.debug("File Export Successful:", data);
via.downloadFile(odin.SERVLET_PATH + "?action=admin.streamFile&reportName=" + encodeURIComponent(data.fileName));
}
},
'json');
});
},
/**
* clearAdvancedSettings
* This will reset the advanced settings
*/
clearAdvancedSettings: function() {
odinLite_fileFormat.staticColumns = [];
odinLite_fileFormat.mappedColumns = [];
odinLite_fileFormat.dataMergeOptions = {};
odinLite_fileFormat.dataManagementPlugin = null;
odinLite_fileFormat.filterRules = [];
odinLite_fileFormat.validationRules = [];
odinLite_fileFormat.sqlQuery = null;
},
/**
* setInitialValues
* This will set the intial values back to what was oringinally guessed by the system
*/
setInitialValues: function(){
odinLite_fileFormat.FILE_DATA.hasColumnHeader = odinLite_uploadFiles.initialValues.hasColumnHeader;
odinLite_fileFormat.FILE_DATA.delimType = odinLite_uploadFiles.initialValues.delimType;
odinLite_fileFormat.FILE_DATA.startColumn = odinLite_uploadFiles.initialValues.startColumn;
odinLite_fileFormat.FILE_DATA.endColumn = odinLite_uploadFiles.initialValues.endColumn;
odinLite_fileFormat.FILE_DATA.startRow = odinLite_uploadFiles.initialValues.startRow;
odinLite_fileFormat.FILE_DATA.endRow = odinLite_uploadFiles.initialValues.endRow;
odinLite_fileFormat.FILE_DATA.textQualifier = odinLite_uploadFiles.initialValues.textQualifier;
},
/**
* setFormattingOptions
* This will set the formatting options into the form boxes from the FILE_DATA var
*/
setFormattingOptions: function(){
//Column Headers - starts at true
$('#fileFormat_columnHeaders').prop('checked', true);
if(!via.undef(odinLite_fileFormat.FILE_DATA.hasColumnHeader,true)){
$('#fileFormat_columnHeaders').prop('checked', odinLite_fileFormat.FILE_DATA.hasColumnHeader)
}
//Delimiter
if(!via.undef(odinLite_fileFormat.FILE_DATA.delimType,true)) {
odinLite_fileFormat.FILE_DATA.delimType = odinLite_fileFormat.FILE_DATA.delimType.replace(/\"/g, "");//Fix for legacy saves
}
if(!odinLite_fileFormat.isExcel() && !via.undef(odinLite_fileFormat.FILE_DATA.delimType,true)){
$('input[name="fileFormat_delimiterType"][value="' + odinLite_fileFormat.FILE_DATA.delimType + '"]').prop('checked', true);
}
//End Column
if(!via.undef(odinLite_fileFormat.FILE_DATA.endColumn)) {
$('#fileFormat_endColumn').data("kendoNumericTextBox").value(odinLite_fileFormat.FILE_DATA.endColumn);
}
//Start Column
if(!via.undef(odinLite_fileFormat.FILE_DATA.startColumn)) {
$('#fileFormat_startColumn').data("kendoNumericTextBox").value(odinLite_fileFormat.FILE_DATA.startColumn);
}
//Start Row
if(!via.undef(odinLite_fileFormat.FILE_DATA.startRow)) {
$('#fileFormat_startRow').data("kendoNumericTextBox").value(odinLite_fileFormat.FILE_DATA.startRow);
}
//End Row
if(!via.undef(odinLite_fileFormat.FILE_DATA.endRow)) {
$('#fileFormat_endRow').data("kendoNumericTextBox").value(odinLite_fileFormat.FILE_DATA.endRow);
}
//Text Qualifier
if(!via.undef(odinLite_fileFormat.FILE_DATA.textQualifier)) {
$('#fileFormat_textQualifier').val(odinLite_fileFormat.FILE_DATA.textQualifier);
}
},
/**
* getFormattingOptions
* This will get the formatting options in the form boxes and put them in the FILE_DATA var
*/
getFormattingOptions: function(){
var formDataObj = {};
//Delimiter
if(!odinLite_fileFormat.isExcel()) {
formDataObj.delimType = $("input:radio[name ='fileFormat_delimiterType']:checked").val();
if (formDataObj.delimType === 'other') {
var otherType = $('#fileFormat_delimiterOther_textBox').val();
if (via.undef(otherType, true)) {
via.kendoAlert("Specify a Delimiter", "Please enter a file delimiter.");
return null;
}
formDataObj.userDefinedDelim = otherType;
}
}
//Text Qual & col headers
formDataObj.textQualifier = $('#fileFormat_textQualifier').val();
formDataObj.hasColumnHeader = $("#fileFormat_columnHeaders").prop('checked');
//Rows & Cols
formDataObj.startRow = $('#fileFormat_startRow').data("kendoNumericTextBox").value();
formDataObj.endRow = $('#fileFormat_endRow').data("kendoNumericTextBox").value();
formDataObj.startColumn = $('#fileFormat_startColumn').data("kendoNumericTextBox").value();
formDataObj.endColumn = $('#fileFormat_endColumn').data("kendoNumericTextBox").value();
//Model and Entity Info
formDataObj.entityDir = odinLite_modelCache.currentEntity.entityDir;
formDataObj.modelId = odinLite_modelCache.currentModel.value;
return formDataObj;
},
/**
* isXLS
* This will return whether the files are excel or not
*/
isExcel: function(){
if(odinLite_fileFormat.FILE_DATA.type === ".xls" || odinLite_fileFormat.FILE_DATA.type === ".xlsx"){
return true;
}else{
return false;
}
},
/**
* buildSpreadsheetFromTableSet
* Makes a spreadsheet form tableset data
*/
getSpreadsheetDataFromTableSet: function(tsData,isEnabled,displayDataTypes,maxRows){
var rows = [];
var columns = [];
if(via.undef(isEnabled,true)){ isEnabled = true; }
if(via.undef(maxRows,true)) {
maxRows = tsData.data.length;
}
if(maxRows > tsData.data.length){
maxRows = tsData.data.length;
}
//Display the data types
if(!via.undef(displayDataTypes) && displayDataTypes===true){
var row = [];
for(var i=0;i<tsData.columnDataTypes.length;i++){
var cellObject = {value: via.getStringDataTypeName(tsData.columnDataTypes[i]),textAlign: "center", enable: isEnabled, color: "#ffffff", background:"#800000",
borderBottom:{ size: 2, color: "black" },borderRight:{ size: 1, color: "black" }};
row.push(cellObject);
}
rows.push({cells: row});
}
//Add the column headers
if(!via.undef(tsData) && !via.undef(tsData.columnHeaders,true)){
var row = [];
for(var i=0;i<tsData.columnHeaders.length;i++){
var cellObject = {value: tsData.columnHeaders[i],textAlign: "center", enable: isEnabled, color: "#ffffff", background:"#00a5d0"};
row.push(cellObject);
}
rows.push({cells: row});
}
//Add the row data
if(!via.undef(tsData) && !via.undef(tsData.data,true)) {
for (var i = 0; i < maxRows; i++) {
var row = [];
var rowData = tsData.data[i];
var cellObject = null;
for (var j = 0; j < rowData.length; j++) {
if (i === 0) {
columns.push({width: 250});
}
var cellValue = rowData[j];
var cellDataType = tsData.columnDataTypes[j];
switch (cellDataType) {
case via.DATA_TYPE_DOUBLE:
var value = parseFloat(cellValue);
value = isNaN(value) ? null : value;
cellObject = {
value: kendo.toString(value, "#,###0.00####"),
textAlign: "right",
enable: isEnabled,
color: "rgb(0,0,0)"
};
break;
case via.DATA_TYPE_LONG:
var value = parseInt(cellValue);
value = isNaN(value) ? null : value;
cellObject = {
value: value,
textAlign: "right",
enable: isEnabled,
color: "rgb(0,0,0)",
format: "#,###0"
};
break;
case via.DATA_TYPE_DATE:
var dteFormat = 'yyyyMMdd';
var dateVar = kendo.parseDate(cellValue, dteFormat);
var formattedDate = null;
if (via.undef(cellValue, true)){
formattedDate = null;
}else if (dateVar !== null) {
formattedDate = kendo.toString(dateVar, odin.DEFAULT_DATE_FORMAT);
} else {
formattedDate = "Unparsable Date";
}
cellObject = {
value: formattedDate,
textAlign: "right",
enable: isEnabled,
color: "rgb(0,0,0)"
};
break;
case via.DATA_TYPE_INTEGER:
var value = parseInt(cellValue);
value = isNaN(value)?null:value;
cellObject = {
value: value,
textAlign: "right",
enable: isEnabled,
color: "rgb(0,0,0)",
format: "#,###0"
};
break;
case via.DATA_TYPE_BOOLEAN:
cellObject = {
value: cellValue,
textAlign: "center",
enable: isEnabled,
color: "rgb(0,0,0)"
};
break;
case via.DATA_TYPE_FLOAT:
var value = parseFloat(cellValue);
value = isNaN(value)?null:value;
cellObject = {
value: value,
textAlign: "right",
enable: isEnabled,
color: "rgb(0,0,0)",
format: "#,###0.000000"
};
break;
case via.DATA_TYPE_SKIP:
cellObject = {value: cellValue, textAlign: "left", enable: isEnabled, color: "#adadad"};
break;
case via.DATA_TYPE_STRING:
case via.DATA_TYPE_OBJECT:
default:
cellObject = {value: cellValue, textAlign: "left", enable: isEnabled, color: "#000000"};
}
row.push(cellObject);
}
rows.push({cells: row});
}
}
return {
name: "File Preview",
rows: rows,
columns: columns
};
},
/**
* testFileNameExtract
* This will ttest the fileName extract.
*/
testFileNameExtract: function(){
var colObject = {};
colObject.prefix = $('#fileFormat_addColumn_prefix').val();
colObject.suffix = $('#fileFormat_addColumn_suffix').val();
colObject.prefixRegex = $('#fileFormat_addColumn_prefixIsRegex').prop('checked');
colObject.suffixRegex = $('#fileFormat_addColumn_suffixIsRegex').prop('checked');
colObject.type = getCurrentType();
if(colObject.type===3) {
colObject.dateFormat = $('#fileFormat_addColumn_dateFormat').data('kendoComboBox').value();
}
if(colObject.type===3 && via.undef(colObject.dateFormat,true)){
via.kendoAlert("Add Column Error","Select a date format.");
return;
}
var files = null;
if(odinLite_fileFormat.isMultiSheet === true){
files = odinLite_fileFormat.FILE_DATA.sheetNames;
}else{
files = odinLite_fileFormat.FILE_DATA.localFiles;
}
//Get the file preview from the server based on the settings.
$.post(odin.SERVLET_PATH,
{
action: 'odinLite.uploadFiles.testFileNameExtract',
settings: JSON.stringify(colObject),
fileJson: JSON.stringify(files)
},
function(data, status){
data = JSON.parse(data);
if(!via.undef(data,true) && data.success === false) {
via.debug("Failure getting filename extract:", data.message);
via.kendoAlert("Failure getting filename extract", data.message);
}else{
var idx = $('#fileFormat_fileList').data('kendoDropDownList').value();
if(!via.undef(data.fileNameExtract)){
//var fileNames = data.fileNameExtract.join(", ");
via.kendoAlert("File Name Extract",data.fileNameExtract[idx]);
}else if(!via.undef(data.dateFileNameExtract)){
//var fileNames = data.dateFileNameExtract.join(", ");
via.kendoAlert("File Name Extract",data.dateFileNameExtract[idx]);
}else{
via.kendoAlert("File Name Extract","No data contasined in extract.");
}
}
},
'text');
//getCurrentType - get the type of the current column chosen
function getCurrentType(){
var columnName = $("#fileFormat_addColumn_columnList").data("kendoComboBox").value();
var idx = $.inArray(columnName,odinLite_modelCache.currentEntity.mappedColumnDisplay);
var type = 0;
if(idx !== -1){
type = odinLite_modelCache.currentEntity.mappedColumnDataType[idx];
}
return type;
}
},
/**
* showUploadFiles
* This will take you back to file upload
*/
showUploadFiles: function(){
odinLite_fileFormat.hideFileFormat();
odinLite_uploadFiles.init();
},
/**
* hideFileFormat
* This will hide file format
*/
hideFileFormat: function(){
$('#fileFormatPanel').hide();
},
/**
* showFileFormat
* This will show file format
*/
showFileFormat: function(){
odinLite_modelMapping.hideModelMapping();
$('#fileFormatPanel').show();
},
};<file_sep>/js/odinLite.js
/**
* Created by rocco on 3/16/2018.
* This is the main file for the ODIN Lite application.
*/
var odinLite = {
//Variables
APP_NAME: null,//Name of the application
ENTITY_CODE: null,//This is the ODIN Entity Code
ENTITY_DIR: null,//Holds the directory of the current entity
ENTITY_NAME: null,//Holds the current entity being worked with
LOGIN_SETTINGS: null,
OVERRIDE_USER: null,//Override user for admin functionality.
systemNotifications: null,//holds the list of current system notifications
subscribedPackageList: null,//holds the list of subscribed packages.
isDataManagerUser: false,
//Variables used for free only users.
MAX_SIGNUP_WITHOUT_CARD: null,
ALLOW_SUB_WITHOUT_CARD: null,
userSignupMap: null,
isFreeOnlyUser: false,
//For tracking the application
appList: null, //This contains the list of applications a user is permissioned for.
currentApplication: null,
/**
* init
* This will initialize ODIN Lite and check if a user is properly logged in.
*/
init: function () {
kendo.ui.progress($("body"), true);//Wait Message
//Add a case insensitive contains selector to jquery. Used for Filtering Report Names
$.extend($.expr[':'], {
'containsi': function (elem, i, match, array) {
return (elem.textContent || elem.innerText || '').toLowerCase()
.indexOf((match[3] || "").toLowerCase()) >= 0;
}
});
//Check if a user is logged in and setup the application if they are.
odin.userIsLoggedIn(odinLite.setUserLoggedIn, function (data) {
odinLite.ENTITY_CODE = data.ODIN_LITE_ENTITY_CODE;
odinLite.APP_NAME = data.ODIN_LITE_APP_NAME;
if (via.undef(odinLite.ENTITY_CODE, true)) {
window.location = '../index.jsp?referrer=./' + odin.ODIN_LITE_DIR + '/' + encodeURIComponent(document.location.search);
} else {
var params = via.getQueryParams();
var isFirst = true;
var queryString = "";
$.each(params, function (key, value) {
if (key === "appname")return;
if (isFirst) {
queryString = "?" + key + "=" + value;
} else {
queryString += "&" + key + "=" + value;
}
isFirst = false;
});
window.location = '../index.jsp?referrer=./' + odin.ODIN_LITE_DIR + '/' + encodeURIComponent(queryString) + "&entity=" + odinLite.ENTITY_CODE + "&appName=" + odinLite.APP_NAME;
}
});
},
/**
* setupDataManagerUser
* This will check and setup the initial data manager user
*/
setupDataManagerUser: function () {
var dmUser = via.getParamsValue("isdm");
if (via.undef(dmUser, true) || dmUser.toLowerCase() !== "true") {
return;
}
odinLite.isDataManagerUser = true;
/*Initialize the screen for the DM user.*/
//Hide certain elements
$('.hideDMUser').hide();
//Fix home page spacing
$('.home_sideSpacers').removeClass("col-md-3");
$('.home_sideSpacers').addClass("col-md-4");
odinLite.loadApplicationHome();
$(".breadcrumbNav").hide();
$("#homeButton").click(function(){
odinLite.loadApplicationHome();
});
},
/**
* setUserLoggedIn
* This will setup ODIN Lite and will get called only if a user is logged into ODIN.
*/
setUserLoggedIn: function () {
//Make the call to initialize the application
$.post(odin.SERVLET_PATH,
{
action: 'odinLite.init',
overrideUser: odinLite.OVERRIDE_USER
},
function (data, status) {
kendo.ui.progress($("body"), false);//Wait Message off
if (!via.undef(data, true) && data.success === false) {
via.debug("Failure Initializing:", data.message);
via.alert("Failure Initializing", data.message);
} else {
via.debug("Successful Initializing:", data);
/**TESTING**/
/* setTimeout(function(){
odinLite_billing.packageTesting();
},3500);
*/
//var localTs = '{"tableLabel":"10312008.txt","columnHeaders":["Currency Code","FX Rate"],"columnDataTypes":[0,0],"totalRows":4,"data":[["CAD","0.79760718"],["EUR","1.18889948"],["GBP","1.28855020"],["USD","1.00000000"]],"lockedColumns":0}';
//via.downloadLocalTableSet(JSON.parse(localTs));
/**END TESTING**/
//Set some billing vars
odinLite.MAX_SIGNUP_WITHOUT_CARD = data.maxSignupWithoutCard;
odinLite.ALLOW_SUB_WITHOUT_CARD = data.allowSubWithoutCard;
odinLite.userSignupMap = data.userSignupMap;
odinLite.appList = data.appList;
odinLite.dataMgmtModel = data.dataMgmtModel;
odinLite.dataMgmtAppId = data.dataMgmtAppId;
//Check to make sure they have verified billing if they are a billing client.
odinLite_billing.checkBillingIsVerified(function () {
//Check if an entity was passed from appbuilder
if (!via.undef(via.getParamsValue("entityname")) && !via.undef(via.getParamsValue("entitydir"))) {
odinLite.ENTITY_DIR = via.getParamsValue("entitydir");
odinLite.ENTITY_NAME = via.getParamsValue("entityname");
odinLite.OVERRIDE_USER = via.getParamsValue("overrideuser");
odinLite.currentApplication = via.getParamsValue("appid");
odinLite.currentApplicationName = via.getParamsValue("appname");
odinLite.currentApplicationPackage = via.getParamsValue("apppackage");
odinLite.ENTITY_CODE = data.entityCode;
odinLite.APP_NAME = data.appName;
odinLite.systemNotifications = data.systemNotifications;
odinLite.subscribedPackageList = data.packageList;
odinLite.isFromAppBuilder = true;
//Hide the query string
window.history.replaceState("From App Builder", data.appName, "./");
odinLite.initOdinLite();
//Check to see if there is an app selected.
if(!via.undef(odinLite.currentApplication) && !via.undef(odinLite.currentApplicationName)){
odinLite.loadApplicationHome();
}
} else if (odinLite.isMultiEntity()) {
odinLite.createMultiEntityWindow(data, function () {
//The entity dir and name is set in the multi entity window
odinLite.ENTITY_CODE = data.entityCode;
odinLite.APP_NAME = data.appName;
odinLite.systemNotifications = data.systemNotifications;
odinLite.subscribedPackageList = data.packageList;
odinLite.initOdinLite();
});
} else {
if (data.entityList.length === 0) {
via.alert("Entity Error", "Cannot find an entity.", function () {
odinLite.setUserLoggedIn();
});
return;
}
odinLite.ENTITY_DIR = data.entityList[0][2];
odinLite.ENTITY_NAME = data.entityList[0][1];
odinLite.ENTITY_CODE = data.entityCode;
odinLite.APP_NAME = data.appName;
odinLite.systemNotifications = data.systemNotifications;
odinLite.subscribedPackageList = data.packageList;
odinLite.initOdinLite();
}
});
}
},
'json');
},
/**
* setOverrideHtml
* for an override user
*/
setOverrideHtml: function () {
var overrideHtml = "";
if (!via.undef(odinLite.OVERRIDE_USER, true)) {
overrideHtml = ',<span style="color:red;"> Override User:' + odinLite.OVERRIDE_USER + "</span>";
}
$('.appTitle').html(odinLite.APP_NAME + " <i><small>(Entity: " + odinLite.ENTITY_NAME + overrideHtml + ")</small></i>");
},
/**
* initOdinLite
* Inits the odin lite user
* @param data
*/
initOdinLite: function () {
//For the override user
odinLite.setOverrideHtml();
//Perform translation if needed.
odin.performTranslation('body');
//Change the theme if needed
via.changeThemeApplicationOptions(odin.getUserSpecificSetting("theme"));
//Get the Query String Parameters
var params = via.getQueryParams();
//Logout Button Visible and Set Action
if (via.undef(params['hideLogout'], true) || params['hideLogout'].toLowerCase() !== 'true') {
$('#odinLogoutButton').click(function () {
//Log the user out
odin.logoutUser();
}).fadeIn();
} else {
$('.resultDivider').hide();
}
//Account Button
if (via.undef(params['hideaccount'], true) || params['hideaccount'].toLowerCase() !== 'true') {
$('#accountButton').click(function () {
odinLite.loadAccountSettings();
}).fadeIn();
//$('#accountSettings').load('accountSettings.html',function() {
// odin.initAccountSettings();
//});
odin.initAccountSettings();
}
//System Notifications Button
if (via.undef(params['hidenotifications'], true) || params['hidenotifications'].toLowerCase() !== 'true') {
if (via.undef(odinLite.systemNotifications, true)) {
$('#home_systemNotificationButton').prop("disabled", true);
$('#home_systemNotificationBadge').html("0");
$('#home_systemNotificationButton').fadeIn();
} else {
$('#home_systemNotificationButton').prop("disabled", false);
$('#home_systemNotificationBadge').html(odinLite.systemNotifications.length);
$('#home_systemNotificationBadge').css("background-color", "red");
$('#home_systemNotificationButton').click(function () {
odinLite.showSystemNotifications();
}).fadeIn();
}
}
//Switch User Button
if (odin.USER_INFO.isAdminUser === true) {
$('#switchUserButton').fadeIn();
$('#switchUserButton').off();
$('#switchUserButton').click(function () {
odinLite.createSwitchUserWindow();
});
}
//Setup the Landing Page
if (via.undef(params['hidehome'], true) || params['hidehome'].toLowerCase() !== 'true') {
$('#homeButton').off();
$('#homeButton').click(function () {
odinLite.navigateToOption('HOME');
}).fadeIn();
}
odinLite.resetHomeApplications();
$('#homePanel').fadeIn();
//Show the Opturo logo
$('.poweredPanel').fadeIn();
//Used for Package sign up - hide if they are not a billing customer.
var isOdinLiteUser = odin.getUserSpecificSetting("isOdinLiteUser");
if (!via.undef(isOdinLiteUser, true) && isOdinLiteUser === "true") {//They are not a billable client
//if (via.undef(params['hideaccount'], true) || params['hideaccount'].toLowerCase() !== 'true') {
$('#home_yourPackagesButton').off();
$('#home_yourPackagesButton').click(function () {
odinLite.loadAccountPackages();
}).fadeIn();
var packageList = odinLite.subscribedPackageList;
if (via.undef(packageList, true)) {
//$('#home_yourPackagesButton').addClass("formError");
var packageTooltip = $("#home_yourPackagesButton").kendoTooltip({
autoHide: false,
content: "Start by adding packages to your account.",
width: 200,
height: 50,
position: "top",
animation: {
open: {
effects: "zoom",
duration: 250
}
}
}).data("kendoTooltip");
packageTooltip.show();
}
}
//Help Button
$('#home_helpButton').fadeIn();
//Check for Data Manager mode
odinLite.setupDataManagerUser();
//remove the loading message
kendo.ui.progress($("body"), false);//Wait Message off
},
/**
* resetHomeApplications
*/
resetHomeApplications: function(allApps){
var homePanel = $('.applicationHomePanel');
homePanel.empty();
//Display a message if the user has no applications.
if(via.undef(odinLite.appList)){
homePanel.html(`<h4>You are not currently subscribed to any applications. Start by adding packages by clicking <a href="#" onclick="odinLite.loadAccountPackages();">here</a>.</h4>`);
return;
}
//Order the Groups
const orderedGroups = {};
Object.keys(JSON.parse(JSON.stringify(odinLite.appList))).sort().forEach(function(key) {
orderedGroups[key] = JSON.parse(JSON.stringify(odinLite.appList[key]));
});
//Loop the app groups.
if(allApps === true) {//List application groups.
$.each(orderedGroups, function (group, apps) {
homePanel.append(`<div style="clear:both;padding-bottom: 10px;border-bottom: 1px solid #ccc;" />`);
homePanel.append(`<h3 style="clear:both;"><i class="fa fa-list-alt" aria-hidden="true"></i> ${group}</h3>`);
var unorderedApps = {};
$.each(apps, function (appId, appArr) {
var appName = appArr[0];
appArr.unshift(appId);
unorderedApps[appName] = appArr;
});
const orderedApps = {};
Object.keys(unorderedApps).sort().forEach(function(key) {
orderedApps[key] = unorderedApps[key];
});
$.each(orderedApps, function (appName, appArr) {
var appId = appArr[0];
var appImage = appArr[3];
homePanel.append(`
<div class="well appContainer" onclick="odinLite.selectApplication('${appId}');">
<h4>${appName}</h4>
<hr/>
<img src="${appImage}" alt="${appName}" />
</div>`);
});
});
}else{//List all applications.
//Order the applications
var unorderedApps = {};
$.each(orderedGroups, function (group, apps) {
$.each(apps, function (appId, appArr) {
var appName = appArr[0];
appArr.unshift(appId);
unorderedApps[appName] = appArr;
});
});
const orderedApps = {};
Object.keys(unorderedApps).sort().forEach(function(key) {
orderedApps[key] = unorderedApps[key];
});
$.each(orderedApps, function (appName, appArr) {
var appId = appArr[0];
var appImage = appArr[3];
homePanel.append(`
<div class="well appContainer" onclick="odinLite.selectApplication('${appId}');">
<h4>${appName}</h4>
<hr/>
<img src="${appImage}" alt="${appName}" />
</div>`);
});
}
},
/**
* showSystemNotifications
* Shows the system notifications.
*/
showSystemNotifications: function () {
var gridData = [];
odinLite.systemNotifications.map(function (o) {
gridData.push({
message: o
})
});
//Get the window template
$.get("./html/systemNotificationWindow.html", function (entityWindowTemplate) {
$('#odinLite_systemNotificationWindow').remove();
$('body').append(entityWindowTemplate);
//Make the window.
var switchUserWindow = $('#odinLite_systemNotificationWindow').kendoWindow({
title: "System Notification Window",
draggable: false,
resizable: false,
width: "850px",
height: "500px",
modal: true,
close: true,
actions: [
//"Maximize"
"Close"
],
close: function () {
switchUserWindow = null;
$('#odinLite_systemNotificationWindow').remove();
}
}).data("kendoWindow");
switchUserWindow.center();
//Grid
$('#odinLite_systemNotificationGrid').kendoGrid({
dataSource: {
data: gridData,
schema: {
model: {
fields: {
message: {type: "string"}
}
}
},
pageSize: 20
},
height: 430,
scrollable: true,
sortable: false,
filterable: false,
pageable: {
input: true,
numeric: false
},
columns: [
{
template: "<img src='../images/24_mail.png'/> #: message #",
//template: "<span class='glyphicon glyphicon-envelope' aria-hidden='true'></span> #: message #",
field: "message",
title: "System Notification"
},
]
});
//Button Events
$(".odinLite_systemNotificationCloseButton").click(function () {
switchUserWindow.close();
switchUserWindow = null;
$('#odinLite_systemNotificationWindow').remove();
});
});
},
/**
* getUnionWindow
* This will open the union files window.
*/
getExportFilesWindow: function (callbackFn) {
kendo.ui.progress($("body"), true);//Wait Message
//Get the window template
$.get("./html/exportFilesWindow.html", function (unionWindowTemplate) {
$('#odinLite_exportFilesWindow').remove();
$('body').append(unionWindowTemplate);
//Make the window.
var exportFilesWindow = $('#odinLite_exportFilesWindow').kendoWindow({
title: "Export File Format",
draggable: false,
resizable: false,
width: "310px",
height: "250px",
modal: true,
close: true,
animation: false,
actions: [
"Minimize",
"Close"
],
close: function () {
exportFilesWindow = null;
$('#odinLite_exportFilesWindow').remove();
}
}).data("kendoWindow");
exportFilesWindow.center();
$( "#odinLite_exportFilesWindow input[name='fileExportFormat_type']" ).change(function(){
var selected = $(this).val();
if(selected === 'delimited'){
$('#fileExportFormat_delimiterTypeSpan').show();
}else{
$('#fileExportFormat_delimiterTypeSpan').hide();
}
});
//Shut off the wait
kendo.ui.progress($("body"), false);//Wait Message
$('.exportFiles_exportButton').click(function(){
var fileType = $( "#odinLite_exportFilesWindow input[name='fileExportFormat_type']:checked" ).val();
var delimiter = null;
if(fileType === 'delimited'){
delimiter = $('#fileExportFormat_delimiterType').val();
if(via.undef(delimiter,true)){
via.kendoAlert("Delimiter","Please enter a delimiter.");
return;
}
}
if(!via.undef(callbackFn)){
exportFilesWindow.close();
callbackFn(fileType,delimiter);
}
});
});//End Template fetch
},
/**
* createSwitchUserWindow
* Creates the window for switching users
*/
createSwitchUserWindow: function () {
kendo.ui.progress($("body"), true);
$.post(odin.SERVLET_PATH,
{
action: 'odinLite.getODINLiteUserList'
},
function (data, status) {
kendo.ui.progress($("body"), false);//Wait Message off
if (!via.undef(data, true) && data.success === false) {
via.debug("Failure getting users:", data.message);
via.alert("Failure getting users", data.message);
} else {
via.debug("Successful getting users:", data);
//Get the Entity List
var userArr = [];
if (!via.undef(data.userIdList)) {
for (var i = 0; i < data.userIdList.length; i++) {
userArr.push({
text: data.userNameList[i],
value: data.userIdList[i]
});
}
}
//DD List
$("#odinLite_switchUserName").kendoDropDownList({
dataTextField: "text",
dataValueField: "value",
dataSource: userArr,
index: 0,
change: function (e) {
var userId = e.sender.value();
var ds = updateEntityList(data, userId);
$("#odinLite_switchUserEntity").data('kendoDropDownList').setDataSource(ds);
$("#odinLite_switchUserEntity").data('kendoDropDownList').select(0);
}
});
//DD EntityList
$("#odinLite_switchUserEntity").kendoDropDownList({
dataTextField: "text",
dataValueField: "value",
dataSource: userArr,
index: 0
});
//Set the initial value
var ds = updateEntityList(data, data.userIdList[0]);
$("#odinLite_switchUserEntity").data('kendoDropDownList').setDataSource(ds);
$("#odinLite_switchUserEntity").data('kendoDropDownList').select(0);
}
},
'json');
//Get the window template
$.get("./html/switchUserWindow.html", function (entityWindowTemplate) {
$('#odinLite_switchUserWindow').remove();
$('body').append(entityWindowTemplate);
//Make the window.
var switchUserWindow = $('#odinLite_switchUserWindow').kendoWindow({
title: "Choose a User",
draggable: false,
resizable: false,
width: "450px",
height: "135px",
modal: true,
close: true,
actions: [
//"Maximize",
"Close"
],
close: function () {
switchUserWindow = null;
$('#odinLite_switchUserWindow').remove();
}
}).data("kendoWindow");
switchUserWindow.center();
//Button Events
//Switch User
$(".odinLite_selectSwitchUser").on("click", function () {
var userDD = $("#odinLite_switchUserName").data('kendoDropDownList');
var entityDD = $("#odinLite_switchUserEntity").data('kendoDropDownList');
odinLite.OVERRIDE_USER = userDD.value();
odinLite.ENTITY_DIR = entityDD.value();
odinLite.ENTITY_NAME = entityDD.text();
odinLite.init();
odinLite.setOverrideHtml();
switchUserWindow.close();
$('#odinLite_switchUserWindow').remove();
switchUserWindow = null;
});
//User Info
$(".odinLite_selectUserInfo").click(function(){
var userDD = $("#odinLite_switchUserName").data('kendoDropDownList');
var entityDD = $("#odinLite_switchUserEntity").data('kendoDropDownList');
var userId = userDD.value();
var userName = userDD.text();
var entityDir = entityDD.value();
var entityName = entityDD.text();
kendo.ui.progress($("#odinLite_switchUserWindow"), true);//Wait Message off
$.post(odin.SERVLET_PATH,
{
action: 'odinLite.getAdminUserInfo',
userId: userId,
userName: userName
},
function (data, status) {
kendo.ui.progress($("#odinLite_switchUserWindow"), false);//Wait Message off
if (!via.undef(data, true) && data.success === false) {
via.debug("Failure getting user info:", data.message);
via.kendoAlert("Failure getting user info", data.message);
} else {
via.debug("Successful getting user info:", data);
//Get the window template
$.get("./html/userInfoWindow.html", function (entityWindowTemplate) {
switchUserWindow.close();
switchUserWindow = null;
$('#odinLite_switchUserWindow').remove();
$('#odinLite_userInfoWindow').remove();
$('body').append(entityWindowTemplate);
//Make the window.
var userInfoWindow = $('#odinLite_userInfoWindow').kendoWindow({
title: "User Info",
draggable: false,
resizable: false,
width: "1080px",
height: "75%",
modal: true,
close: true,
actions: [
"Maximize",
"Close"
],
close: function () {
userInfoWindow = null;
$('#odinLite_userInfoWindow').remove();
}
}).data("kendoWindow");
userInfoWindow.center();
//User Object Data//
$('#userInfo_home span').empty();
$('#userInfo_home span').append("<pre>" + via.jsonSyntaxHighlight(JSON.stringify(data.userObject, null, 4)) + "</pre>");
//User Settings Update
function userSettingUpdate(){
if(!via.undef($("#userInfo_settings_key").data('kendoComboBox'))){ return; }
var ds = [];
$.each(data.userSettings,function(k,v){
ds.push({
text: k, value: v
});
});
var userSettingCombo = $("#userInfo_settings_key").kendoComboBox({
dataTextField: "text",
dataValueField: "value",
dataSource: ds,
filter: "contains",
suggest: true,
value: null,
change: function(e){
if(via.undef(e.sender.value(),true) || e.sender.value() === e.sender.text()){
$("#userInfo_settings_value").val(null);
}else{
$("#userInfo_settings_value").val(e.sender.value());
}
}
}).data('kendoComboBox');
//Button Events
//Add/Update
$(".userInfo_settings_update_button").click(function(){
var key = userSettingCombo.text();
var val = $("#userInfo_settings_value").val();
if(via.undef(key,true)){ return; }
if(via.undef(val,true)){ return; }
via.kendoConfirm("Delete User Setting","Are you sure you want to change the user setting <b>"+key+"</b> to:<br/><b>"+val+"</b>.",function(){
//Post to the server
kendo.ui.progress($("#odinLite_userInfoWindow"), true);
$.post(odin.SERVLET_PATH,
{
action: "admin.setUserSettings",
userId: userId,
userName: userName,
keys: JSON.stringify([key]),
values: JSON.stringify([val]),
isOdinLite: true
},
function (data, status) {
kendo.ui.progress($("#odinLite_userInfoWindow"), false);//Wait Message off
if (!via.undef(data, true) && data.success === false) {
via.debug("Failure updating user settings:", data.message);
via.alert("Failure updating user settings", data.message);
} else {
via.debug("Successful updating user settings:", data);
via.kendoAlert("Update User Settings",data.message,function(){
//User Object Data//
$('#userInfo_home span').empty();
$('#userInfo_home span').append("<pre>" + via.jsonSyntaxHighlight(JSON.stringify(data.userObject, null, 4)) + "</pre>");
var ds = [];
$.each(data.userSettings,function(k,v){
ds.push({
text: k, value: v
});
});
userSettingCombo.setDataSource(ds);
userSettingCombo.value(null);
$("#userInfo_settings_value").val(null);
});
}
},
'json');
});
});
//Delete
$(".userInfo_settings_delete_button").click(function(){
var key = userSettingCombo.text();
if(via.undef(key,true)){ return; }
via.kendoConfirm("Delete User Setting","Are you sure you want to remove the user setting <b>"+key+"</b>.",function(){
//Post to the server
kendo.ui.progress($("#odinLite_userInfoWindow"), true);
$.post(odin.SERVLET_PATH,
{
action: "admin.deleteUserSettings",
userId: userId,
userName: userName,
keys: JSON.stringify([key]),
isOdinLite: true
},
function (data, status) {
kendo.ui.progress($("#odinLite_userInfoWindow"), false);//Wait Message off
if (!via.undef(data, true) && data.success === false) {
via.debug("Failure deleting user settings:", data.message);
via.alert("Failure deleting user settings", data.message);
} else {
via.debug("Successful deleting user settings:", data);
via.kendoAlert("Deleting User Settings",data.message,function(){
//User Object Data//
$('#userInfo_home span').empty();
$('#userInfo_home span').append("<pre>" + via.jsonSyntaxHighlight(JSON.stringify(data.userObject, null, 4)) + "</pre>");
var ds = [];
$.each(data.userSettings,function(k,v){
ds.push({
text: k, value: v
});
});
userSettingCombo.setDataSource(ds);
userSettingCombo.value(null);
$("#userInfo_settings_value").val(null);
});
}
},
'json');
});
});
}
//Transaction Data//
var grid = null;
function updateTransactionData(transactionsTs) {
if(via.undef(transactionsTs)){return;}
$('#userInfo_transactions span').empty();
odinTable.createTable("odinLite_userInfoTransactionTable", transactionsTs, '#userInfo_transactions span');
grid = $('#odinLite_userInfoTransactionTable').data('kendoGrid');
grid.setOptions({
sortable: true,
groupable: false,
columnMenu: false,
height: "275px",
filterable: false,
pageable: false,
selectable: true
});
}
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
var target = $(e.target).attr("href"); // activated tab
if(target === '#userInfo_transactions') {
updateTransactionData(data.transactionsTs);
}else if(target === '#userInfo_settings'){
userSettingUpdate();
}
});
//One Off Billing
$('.odinLite_selectUserOneOffBilling').click(function(){
via.kendoPrompt("One off Billing","What is the amount you would like to charge?",function(total){
var regex = /^\d+(?:\.\d{0,2})$/;
if (!regex.test(total)){
via.kendoAlert("Invalid Total","Total is invalid: " + total);
}else{
via.kendoPrompt("One off Billing","What is the reason for the one off billing?",function(description) {
via.kendoConfirm("Check Charges", "This will charge <b>" + total + "</b> using authorization id <b>" +
data.userSettings.authorizationId + "</b>.<br/>When complete an email receipt will be sent to <b>" + userName + "</b>.<br/>" +
"With the reason: <b>"+description+"</b>", function () {
//Post to the server
kendo.ui.progress($("#odinLite_userInfoWindow"), true);
$.post(odin.SERVLET_PATH,
{
action: 'odinLite.billing.doAdhocBilling',
userId: userId,
userName: userName,
totalAmount:total,
billingDescription:description
},
function (data, status) {
kendo.ui.progress($("#odinLite_userInfoWindow"), false);//Wait Message off
if (!via.undef(data, true) && data.success === false) {
via.debug("Failure billing user:", data.message);
via.alert("Failure billing user", data.message);
} else {
via.debug("Successful billing user:", data);
if (!via.undef(data.message, true)) {
via.kendoAlert("Billing Successful",data.message,function(){
updateTransactionData(data.transactionsTs);
});
}else{
via.kendoAlert("Billing Successful","Successfully billed.",function(){
updateTransactionData(data.transactionsTs);
});
}
}
},
'json');
});
});
}
});
});
//Refund Transaction
$('.odinLite_selectUserRefundTransaction').click(function(){
//Get Transaction ID
var selectedItem = grid.dataItem(grid.select());
if(via.undef(selectedItem)){return;}
var identifierName = "Transaction ID";
var billingName = "Billing Amount";
var id = null;
var billingAmount = null;
$.each( selectedItem, function(k,v){
if(k.startsWith(via.cleanId(identifierName))){
id = v;
}else if(k.startsWith(via.cleanId(billingName))){
billingAmount = v;
}
});
if(via.undef(id)){return;}
if(via.undef(billingAmount,true) || billingAmount === 0){
via.kendoAlert("Refund Error","There was no charge for this transaction.");
return;
}
via.kendoPrompt("Process Refund","What is the amount you would like to refund for transaction id <b>"+id+"</b>? Total transaction was <b>" + billingAmount + "</b>.",function(total){
var regex = /^\d+(?:\.\d{0,2})$/;
if (!regex.test(total)){
via.kendoAlert("Invalid Total","Total is invalid: " + total);
}else{
total = parseFloat(total);
if(billingAmount < total){
via.kendoAlert("Refund Error","The total refund is more than the billed amount.");
return;
}
via.kendoPrompt("Process Refund","What is the reason for the refund?",function(description) {
via.kendoConfirm("Check Charges", "This will refund <b>" + total + "</b> for transaction id <b>" +
id + "</b>.<br/>When complete an email receipt will be sent to <b>" + userName + "</b>.<br/>With the description: <b>"+description+"</b>", function () {
//Post to the server
kendo.ui.progress($("#odinLite_userInfoWindow"), true);
$.post(odin.SERVLET_PATH,
{
action: 'odinLite.billing.processRefund',
userId: userId,
userName: userName,
totalAmount:total,
refundDescription:description,
saleId: id
},
function (data, status) {
kendo.ui.progress($("#odinLite_userInfoWindow"), false);//Wait Message off
if (!via.undef(data, true) && data.success === false) {
via.debug("Failure refunding user:", data.message);
via.alert("Failure refunding user", data.message);
} else {
via.debug("Successful refunding user:", data);
if (!via.undef(data.message, true)) {
via.kendoAlert("Refund Successful",data.message,function(){
updateTransactionData(data.transactionsTs);
});
}else{
via.kendoAlert("Refund Successful","Successfully refunded.",function(){
updateTransactionData(data.transactionsTs);
});
}
}
},
'json');
});
});
}
});
});
//Transaction Detail
$('.odinLite_selectUserTransactionDetail').click(function(){
var selectedItem = grid.dataItem(grid.select());
if(via.undef(selectedItem)){return;}
var identifierName = "Transaction ID";
var id = null;
$.each( selectedItem, function(k,v){
if(k.startsWith(via.cleanId(identifierName))){
id = v;
return;
}
});
if(via.undef(id)){return;}
kendo.ui.progress($("body"), true);
$.post(odin.SERVLET_PATH,
{
action: 'odinLite.billing.getTransactionDetails',
id : id
},
function(data, status){
kendo.ui.progress($("body"), false);
$('#accountSettings_updatePasswordButton').prop( "disabled", false );
if(!via.undef(data,true) && data.success === false){
via.debug("Get Transaction Details Error:", data.message);
via.kendoAlert("Get Transaction Details Error",data.message);
}else{//Success - File Preview
via.debug("Get Transaction Details success:", data);
via.kendoAlert(identifierName +": "+ id,"<pre>" + via.jsonSyntaxHighlight(JSON.stringify(data.transactionResponse, null, 4)) + "</pre>");
}
},
'json');
});
});
}
},
'json');
});
//Become User
$(".odinLite_becomeUser").on("click", function () {
kendo.ui.progress($("body"), true);
var userDD = $("#odinLite_switchUserName").data('kendoDropDownList');
$.post(odin.SERVLET_PATH,
{
action: 'admin.becomeAnotherUser',
userName: userDD.text(),
entity: odinLite.ENTITY_CODE
},
function (data, status) {
kendo.ui.progress($("body"), false);//Wait Message off
if (!via.undef(data, true) && data.success === false) {
via.debug("Failure getting users:", data.message);
via.kendoAlert("Failure getting users", data.message);
} else {
via.debug("Successful getting users:", data);
var loginString = "&user="+data.userName +
"&entity="+data.entity +
"&apiKey="+encodeURIComponent(data.apiKey) +
"&encKey="+encodeURIComponent(data.encKey);
if(!via.undef(data.lastAccessTime,true)) {
via.kendoConfirm("User Logged In", "User may be logged in. Last access time was: " + data.lastAccessTime, function () {
odin.logoutUser(function(){
window.location = '../index.jsp?referrer=./' + odin.ODIN_LITE_DIR + '/' + loginString;
},true);
});
}else {
odin.logoutUser(function(){
window.location = '../index.jsp?referrer=./' + odin.ODIN_LITE_DIR + '/' + loginString;
},true);
}
}
},
'json');
});
$(".odinLite_deleteSwitchUser").on("click", function () {
/*
odinLite.OVERRIDE_USER = null;
odinLite.ENTITY_DIR = null;
odinLite.ENTITY_NAME = null;
odinLite.setOverrideHtml();
switchUserWindow.close();
$('#odinLite_switchUserWindow').remove();
switchUserWindow = null;
*/
location.reload();
});
});
//To update the entity list
function updateEntityList(data, userId) {
var entityArr = data.entityHash[userId];
if (via.undef(entityArr) || entityArr.length === 0) {
return [];
}
var entityDsArr = [];
for (var i = 0; i < entityArr.length; i++) {
entityDsArr.push({
text: entityArr[i][1],
value: entityArr[i][0]
});
}
return entityDsArr;
}
},
/**
* createMultiEntityWindow
* Creates the window for multi entity
* @param data
*/
createMultiEntityWindow: function (data, selectFn) {
//Get the window template
$.get("./html/entityWindow.html", function (entityWindowTemplate) {
$('#odinLite_entityWindow').remove();
$('body').append(entityWindowTemplate);
//Make the window.
var entityWindow = $('#odinLite_entityWindow').kendoWindow({
title: "Choose an Entity",
draggable: false,
resizable: false,
width: "450px",
height: "90px",
modal: false,
close: false,
actions: [
//"Maximize"
],
close: function () {
entityWindow = null;
$('#odinLite_entityWindow').remove();
}
}).data("kendoWindow");
entityWindow.center();
//Get the Entity List
var entityArr = [];
if (!via.undef(data.entityList)) {
entityArr = data.entityList.map(function (item) {
return {
text: item[1],
value: item[2]
}
});
}
//DD List
$("#odinLite_multiEntityName").kendoDropDownList({
dataTextField: "text",
dataValueField: "value",
dataSource: entityArr,
index: 0
});
//Button Events
$(".odinLite_selectEntity").on("click", function () {
var dataItem = $("#odinLite_multiEntityName").data("kendoDropDownList").dataItem();
if (via.undef(dataItem, true) || via.undef(dataItem.value, true)) {
return;
}
odinLite.ENTITY_DIR = dataItem.value;
odinLite.ENTITY_NAME = dataItem.text;
entityWindow.close();
if (!via.undef(selectFn)) {
selectFn();
}
});
$(".odinLite_createEntity").on("click", function () {
odinLite_modelCache.createNewEntity(function (data) {
entityWindow.close();
odinLite.setUserLoggedIn();
});
});
$(".odinLite_deleteEntity").on("click", function () {
var dataItem = $("#odinLite_multiEntityName").data("kendoDropDownList").dataItem();
if (via.undef(dataItem, true) || via.undef(dataItem.value, true)) {
return;
}
odinLite_modelCache.deleteEntity(dataItem.value, dataItem.text, function (data) {
entityWindow.close();
odinLite.setUserLoggedIn();
});
});
});
},
/**
* navigateToOption
* Navigate to a particular application location.
* @param option
*/
navigateToOption: function (option) {
switch (option) {
case "HOME":
odinLite.loadHome();
break;
case "UPLOAD":
odinLite.loadModelCacheApplication();
break;
case "VIEW":
odinLite.loadViewApplication();
break;
case "REPORTING":
odinLite.loadReportingApplication();
break;
default:
odinLite.goToJob(option);
}
},
/**
* loadHome
* This will bring a user home.
* This is the starting screen.
*/
loadHome: function () {
//Hide the other panels
odinLite.hideAllApplications();
//Update Breadcrumb
$('.breadcrumbNav').empty();
$('#homePanel').fadeIn();
},
/**
* selectApplication
* This will select a new application
*/
selectApplication: function (appId) {
var appInfo = null;
if(!via.undef(odinLite.appList)) {
$.each(odinLite.appList, function (group, app) {
if(!via.undef(app)) {
$.each(app, function (currAppId, arr) {
if(appId === currAppId && !via.undef(arr)){
odinLite.currentApplicationName = arr[0];
odinLite.currentApplicationPackage = arr[4];
appInfo = arr;
return;
}
});
}
});
}
var appDisplayList = null;
if(!via.undef(appInfo) && appInfo.length >= 4){
appDisplayList = appInfo[3];
}
odinLite.currentApplication = appId;
$(".appHome_upload").show();
$(".appHome_manage").show();
$(".appHome_reporting").show();
$(".appHome_extraSpacer").hide();
//Hide Interface
if (!via.undef(appDisplayList) && appDisplayList.indexOf("I")===-1) {
$(".appHome_reporting").hide();
}
//Hide Manage
if (!via.undef(appDisplayList) && appDisplayList.indexOf("M")===-1) {
$(".appHome_manage").hide();
}
//Hide Upload
if (!via.undef(appDisplayList) && appDisplayList.indexOf("U")===-1) {
$(".appHome_upload").hide();
}
//For Data Management
if (odinLite.dataMgmtAppId === odinLite.currentApplication) {
$(".appHome_extraSpacer").show();
$(".appHome_reporting").hide();
$(".appHome_manage").hide();
}
//Check the tour and user images.
$('.imageDisplayButton').hide();
odinLite.appImageList = null;
$.get(odin.SERVLET_PATH + "/ODIN_LITE/GET_PACKAGE_TOUR?packageId=" + odinLite.currentApplicationPackage,
function (data) {
if(via.undef(data)){ return; }
var jsonResponse = JSON.parse(data);
if(via.undef(jsonResponse) || via.undef(jsonResponse.imageList) || jsonResponse.imageList.length === 0){ return; }
odinLite.appImageList = jsonResponse.imageList.split(";;");
$('.imageDisplayButton').fadeIn();
}
);
odinLite.loadApplicationHome();
},
/**
* Loads the image window.
*/
appImageWindow: function(){
if(via.undef(odinLite.appImageList)){
return;
}
var imageList = [];
for(var idx in odinLite.appImageList){
var [caption,imageUrl] = odinLite.appImageList[idx].split(";");
imageList.push({
src: imageUrl,
title: caption
});
}
$.magnificPopup.open({
items: imageList,
type: 'image',
gallery: {
enabled: true
},
callbacks: {
imageLoadComplete: function() {
var img = this.content.find('img');
img.css('max-height', parseFloat(img.css('max-height')) * 0.95);
}
}
});
},
/**
* loadApplicationHome
* This will bring a user to the application homepage.
*/
loadApplicationHome: function () {
//Hide the other panels
odinLite.hideAllApplications();
//Update Breadcrumb
$('.breadcrumbNav').html(`<a href="#" onclick="odinLite.loadApplicationHome();"><i class="fa fa-arrow-circle-o-left" aria-hidden="true"></i> ${odinLite.currentApplicationName}</a>`);
$('#appHomePanel').fadeIn();
},
/**
* Hides all the applications
*/
hideAllApplications: function () {
odinLite.hideModelCacheApplication();
odinLite.hideViewApplication();
odinLite.hideReportingApplication();
odinLite.hideAccountSettings();
odinLite.hideAccountPackages();
odinLite.hidePaymentPage();
$('#appHomePanel').hide();
$('#homePanel').hide();
},
/**
* ----------------------
* Model Application
*/
/**
* loadUploadApplication
* This will load the upload application.
* It will default on the screen where you can choose files to upload.
*/
loadModelCacheApplication: function () {
odinLite.hideAllApplications();
//Model Cache init();
odinLite_modelCache.init();
},
/**
* Hides the components of the application
*/
hideModelCacheApplication: function () {
$('#modelCachePanel').hide();
$('#uploadFilesPanel').hide();
$('#fileFormatPanel').hide();
$('#modelMappingPanel').hide();
$('#modelMappingErrorsPanel').hide();
},
/**
* End Model Application
* ----------------------
*/
/**
* ----------------------
* View Application
*/
loadViewApplication: function () {
odinLite.hideAllApplications();
//Model Cache init();
odinLite_manageData.init();
},
/**
* Hides the components of the view application
*/
hideViewApplication: function () {
$('#viewPanel').hide();
},
/**
* End View Application
* ----------------------
*/
/**
* ----------------------
* Reporting Application
*/
loadReportingApplication: function () {
var params = via.getQueryParams();
var debug = "";
if(!via.undef(params.debug,true)){
debug = "&debug=true";
}
$('body').fadeOut(function () {
//console.log("../appBuilder/?entityDir=" + odinLite.ENTITY_DIR + "&entityName=" + odinLite.ENTITY_NAME + "&appName=" + odinLite.APP_NAME +
// "&overrideUser=" + (via.undef(odinLite.OVERRIDE_USER, true) ? "" : odinLite.OVERRIDE_USER) + debug + "&isFreeOnlyUser=" + odinLite.isFreeOnlyUser
// + "&appId=" + odinLite.currentApplication);
window.location = "../appBuilder/?entityDir=" + odinLite.ENTITY_DIR + "&entityName=" + odinLite.ENTITY_NAME + "&appName=" + odinLite.APP_NAME +
"&overrideUser=" + (via.undef(odinLite.OVERRIDE_USER, true) ? "" : odinLite.OVERRIDE_USER) + debug + "&isFreeOnlyUser=" + odinLite.isFreeOnlyUser
+ "&appId=" + odinLite.currentApplication + "&appName=" + odinLite.currentApplicationName + "&appPackage=" + odinLite.currentApplicationPackage;
});
},
/**
* Hides the components of the reporting application
*/
hideReportingApplication: function () {
$('#reportPanel').hide();
},
/**
* End Reporting Application
* ----------------------
*/
/**
* ----------------------
* Account Settings
*/
loadAccountSettings: function () {
//Hide the other panels
odinLite.hideAllApplications();
$('#accountSettings').fadeIn();
},
hideAccountSettings: function () {
$('#accountSettings').hide();
},
/**
* End Account Settings
* ----------------------
*/
/**
* ----------------------
* Account Packages
*/
loadAccountPackages: function () {
//Hide the other panels
odinLite.hideAllApplications();
$('#packages').fadeIn();
packageSelection.init();
var tooltip = $("#home_yourPackagesButton").data('kendoTooltip');
if (!via.undef(tooltip)) {
tooltip.hide();
}
window.scrollTo(0, 0);
},
hideAccountPackages: function () {
$('#packages').hide();
},
/**
* End Account Packages
* ----------------------
*/
/**
* ----------------------
* Payment Confirmation Page
*/
loadPaymentPage: function (packageUpdates) {
//Hide the other panels
odinLite.hideAllApplications();
$('#payment').fadeIn(function(){
window.scrollTo(0, 0);
});
packageSelection.getPackageUpdateDetails(packageUpdates);
},
hidePaymentPage: function () {
$('#payment').hide();
},
/**
* End Payment Confirmation Page
* ----------------------
*/
/**
* isMultiEntity
* this will display the help link. it will test if it is a url and if it is then display the url other wise the text
*/
isMultiEntity: function () {
var isMultiEntity = odin.getUserSpecificSetting("isMultiEntity");
if (via.undef(isMultiEntity, true)) {
return false;
} else if (isMultiEntity === "true" || isMultiEntity === true) {
return true;
} else {
return false;
}
}
};
<file_sep>/js/billing.js
/**
* Created by rocco on 9/6/2018.
* This is the billing section of ODIN Lite.
* This will handle everything to do with billing and pricing.
*/
var odinLite_billing = {
/**
* packageTesting
* FOR TESTING ONLY
*/
packageTesting: function () {
var addPackageList = ["VICAP_REPORTING_STANDARD_USER_GROUP"];
var deletePackageList = ["VICAP_REPORTING_ADVANCED_USER_GROUP"];
odinLite_billing.updateUserPackage(addPackageList, deletePackageList, true);
//odinLite_billing.checkBillingIsVerified(addPackageList);
//odinLite_billing.doInitialSignupBillingByPackage(addPackageList);
},
/**
* signupPackagePricing
* This method gets the initial signup pricing.
*/
signupPackagePricing: function (packageList, discountCode, callbackFn,failCallbackFn) {
$.post(odin.SERVLET_PATH,
{
action: 'odinLite.billing.getSignupPackagePricing',
addPackageList: JSON.stringify(packageList),
discountCode: discountCode
},
function (data, status) {
if (!via.undef(data, true) && data.success === false) {
via.debug("Failure getting pricing info:", data.message);
if (!via.undef(data.failureType, true) &&
(data.failureType === "billing_paylaneRequest" || data.failureType === "billing_paylaneResponse")) {
via.alert("Billing Data Expired.", "Please update you billing information on the next screen. <br>Error: " + data.message, function () {
location.reload();
});
}else {
via.alert("Failure getting pricing info", data.message, function () {
if(!via.undef(failCallbackFn)){
failCallbackFn(data);
}
});
}
return;
} else {//Success
via.debug("Pricing Success Info", data);
if(!via.undef(callbackFn)){
callbackFn(data);
}
}
},
'json');
},
/**
* reoccurringPackagePricing
* This method gets the reoccurring monthly package pricing.
*/
reoccurringPackagePricing: function (packageList) {
if (via.undef(packageList, true)) {
via.alert("Missing Arguments", "Specify a Package List.");
return;
}
kendo.ui.progress($("body"), true);//Wait Message on
$.post(odin.SERVLET_PATH,
{
action: 'odinLite.billing.getReoccurringPricing',
packageList: JSON.stringify(packageList)
},
function (data, status) {
kendo.ui.progress($("body"), false);//Wait Message off
if (!via.undef(data, true) && data.success === false) {
via.debug("Failure getting pricing info:", data.message);
via.alert("Failure getting pricing info", data.message, function () {
});
return;
} else {//Success
via.debug("Pricing Success Info", data);
console.log("reoccurringPackagePricing", data);//Testing
}
},
'json');
},
/**
* getAutoApplyDiscountCode
* This method gets the auto apply discount code for the packages sent
*/
getAutoApplyDiscountCode: function (packageList) {
if (via.undef(packageList, true)) {
via.alert("Missing Arguments", "Specify a Package List.");
return;
}
kendo.ui.progress($("body"), true);//Wait Message on
$.post(odin.SERVLET_PATH,
{
action: 'odinLite.billing.getAutoApplyDiscountCode',
packageList: JSON.stringify(packageList)
},
function (data, status) {
kendo.ui.progress($("body"), false);//Wait Message off
if (!via.undef(data, true) && data.success === false) {
via.debug("Failure getting discount code:", data.message);
via.alert("Failure getting discount code", data.message, function () {
});
return;
} else {//Success
via.debug("Discount code success", data);
}
},
'json');
},
/**
* checkBillingIsVerified
* This checks to make sure their billing information has been verified. If not it would popup the modal window for credit card entry
* If they have been verified it will continue to the application.
*/
checkBillingIsVerified: function (callbackFn) {
var isBillingVerified = odin.getUserSpecificSetting("isBillingVerified");
var isOdinLiteUser = odin.getUserSpecificSetting("isOdinLiteUser");
if (via.undef(isOdinLiteUser, true) || isOdinLiteUser !== "true") {//They are not a billable client
via.debug("Skipping billing, not a billing customer.");
console.log("checkBillingIsVerified: Skipping billing, not a billing customer.");
callbackFn();//Call the function to continue the login.
return;
}
//Check if they have been verified.
if (via.undef(isBillingVerified, true) || isBillingVerified === "false") {//Not Verified
/*For the text in the header of the popup window.*/
var popupType = -1;
if(via.undef(isBillingVerified, true)){
//New user
popupType = 1;
}else{
//Existing user
popupType = 2;
}
/** Not verified popup billing window. **/
console.log("checkBillingIsVerified: Not verified. Make them enter credit card info.");
if (via.undef(via.getParamsValue("entityname")) && via.undef(via.getParamsValue("entitydir"))) {
odinLite_billing.billingWindowPopup(popupType, callbackFn, false, odinLite.ALLOW_SUB_WITHOUT_CARD);
}else if(!via.undef(callbackFn)){
callbackFn();
}
} else {//They are verified. Call the function to continue the login.
console.log("checkBillingIsVerified: They are verified. Call the function to continue the login.");
//See if there is any past due balance.
odinLite_billing.pastDueWindowPopup();
if (!via.undef(callbackFn)) {
callbackFn();//Call the function to continue the login.
}
}
},
/**
* pastDueWindowPopup
* This is used for initial billing, expired or failed billing as well as updating a payment type.
*/
pastDueWindowPopup: function(){
var billingDataSet = odin.getUserSpecificSetting("billingDataSet");
var billingFailureDate = odin.getUserSpecificSetting("billingFailureDate");
//Check to see if they have a past due bill. Otherwise return.
if(via.undef(billingDataSet,true) || via.undef(billingFailureDate,true)){ return; }
billingDataSet = JSON.parse(billingDataSet);//Parse the table
$.get("./html/pastDueBillWindow.html", function (billingWindowTemplate) {
$('#odinLite_pastDueBillingWindow').remove();
$('body').append(billingWindowTemplate);
var billingWindow = $('#odinLite_pastDueBillingWindow').kendoWindow({
title: "Past Due Bill ",
draggable: false,
resizable: false,
width: "850px",
height: "500px",
modal: true,
close: false,
actions: [],
close: function () {
billingWindow = null;
$('#odinLite_pastDueBillingWindow').remove();
}
}).data("kendoWindow");
billingWindow.center();
billingWindow.open();
//Update - Empty
var updateTable = $("#pastDue-update-table tbody");
updateTable.empty();
//Get the packages to be billed
var itemizedArr = [];
var itemizedSet = billingDataSet.tablesets[0];
for(var r=0;r<itemizedSet.data.length;r++){
var data = itemizedSet.data[r];
itemizedArr.push({
application: data[0],
package: data[1],
cost: kendo.toString(data[2], "c"),
});
}
//Loop through the lines and build the table.
$.each(itemizedArr, function (index, row) {
var html = null;
if (via.undef(row.package, true) && via.undef(row.cost, true)) {
html = "<tr><td colspan='5'>{{application}}</td></tr>";
} else if (!via.undef(row.application, true) && row.application.toLowerCase() === 'total') {
html = "<tr><td><b>{{application}}</b></td><td>{{package}}</td><td align='right' style='color:red;font-weight:bold;'>{{cost}}</td></tr>";
} else {
html = "<tr><td>{{application}}</td><td>{{package}}</td><td align='right'>{{cost}}</td></tr>";
}
var output = Mustache.render(html, row);
updateTable.append(output);
});
//Update the due date.
$('#odinLite_pastDueBillingWindow .failedBillingDate').append(billingFailureDate + ".");
var totalSet = billingDataSet.tablesets[1];
var total = totalSet.data[0][0];
if(via.undef(total,true)){
via.kendoAlert("Billing Error","Total owed is undefined.");
}
$('#pastDue-makePayment-button').click(function(){
var submitText = "Your credit card will be charged <b>" + kendo.toString(total, "c") + "</b> for the past-due bill period. Click OK to continue.";
via.kendoConfirm("Submit Past-Due Payment",submitText,function(){
odinLite_billing.pastDueBilling(billingDataSet,function(data){
billingWindow.close();
via.kendoAlert("Billing Complete",data.message,function(){
odin.USER_INFO.userSettings = data.userSettings;
});
});
});
});
});
},
/**
* pastDueBilling
* Use this for billing a past due bill.
*/
pastDueBilling: function (datasetJson,successCallbackFn,failCallbackFn) {
if (via.undef(datasetJson, true) && via.undef(removePackageList, true)) {
via.alert("Missing Arguments", "No DataSet Specified.");
return;
}
kendo.ui.progress($("#odinLite_pastDueBillingWindow"), true);//Wait Message on
$.post(odin.SERVLET_PATH,
{
action: 'odinLite.billing.performPastDueBilling',
datasetJson: JSON.stringify(datasetJson)
},
function (data, status) {
kendo.ui.progress($("#odinLite_pastDueBillingWindow"), false);//Wait Message off
if (!via.undef(data, true) && data.success === false) {
via.debug("Failure Past-Due Billing:", data.message);
via.alert("Failure Past-Due Billing", data.message, function () {
if(!via.undef(failCallbackFn)){
failCallbackFn(data);
}
});
return;
} else {//Success
via.debug("Past-Due Billing Success", data);
if(!via.undef(successCallbackFn)){
successCallbackFn(data);
}
}
},
'json');
},
/**
* billingWindowPopup
* This is used for initial billing, expired or failed billing as well as updating a payment type.
*/
billingWindowPopup: function (popupType,callbackFn,allowClosing,allowSubWithoutCard) {
kendo.ui.progress($("body"), true);//Wait Message on
$.post(odin.SERVLET_PATH,
{
action: 'odinLite.billing.init'
},
function (data, status) {
//console.log('odinLite.billing.init', data);
kendo.ui.progress($("body"), false);//Wait Message off
if (!via.undef(data, true) && data.success === false) {//Failure
via.debug("Failure getting billing info:", data.message);
via.alert("Failure getting billing info", data.message);
return;
} else {//Success
//Get the window template
$.get("./html/ccBillingWindow.html", function (billingWindowTemplate) {
$('#odinLite_ccBillingWindow').remove();
$('body').append(billingWindowTemplate);
//Populate known values
$("#cc-billing-form input[name='name']").val(odin.USER_INFO.firstName + " " + odin.USER_INFO.lastName);
$("#cc-billing-form input[name='email']").val(odin.USER_INFO.userName);
//Add Country Box
var ccDropDown = $("#cc-billing-form input[name='countryCode']").kendoDropDownList({
dataTextField: "text",
dataValueField: "value",
dataSource: data.countryCombo,
value: 'US',
change: function(e){
var value = e.sender.value();
if(value === 'US'){
$('.ccBillingSpan').show();
}else{
$('.ccBillingSpan').hide();
}
}
}).data('kendoDropDownList');
ccDropDown.trigger('change');
//Add State Box
$("#cc-billing-form input[name='state']").kendoDropDownList({
dataTextField: "text",
dataValueField: "value",
dataSource: data.states,
index: 1
});
//Add Months
$("#cc-billing-form input[name='expirationMonth']").kendoDropDownList({
dataTextField: "text",
dataValueField: "value",
dataSource: data.expirationMonths,
index: 0
});
//Add Months
$("#cc-billing-form input[name='expirationYear']").kendoDropDownList({
dataTextField: "text",
dataValueField: "value",
dataSource: data.expirationYears,
index: 0
});
//Validation zip code
$("#cc-billing-form input[name='zip']").keyup(function () {
this.value = this.value.replace(/[^0-9-]/g, '');
});
//Validation Credit Card
$("#cc-billing-form input[name='cardNumber']").keyup(function () {
this.value = this.value.replace(/[^0-9-]/g, '');
});
//Validation CVV
$("#cc-billing-form input[name='cardCode']").keyup(function () {
this.value = this.value.replace(/[^0-9]/g, '');
});
//Check for first time user and update.
var isFirstTimeUser = false;
if (popupType === 1) {
isFirstTimeUser = true;
//$('#billing_verifyModal .modal-title').append(" - First Time User");
$('#odinLite_ccBillingWindow .panel-heading-color').removeClass('panel-danger');
$('#odinLite_ccBillingWindow .panel-heading-color').addClass('panel-warning');
$('#odinLite_ccBillingWindow .panel-heading-title').html("First Time User: Billing Information");
}else if(popupType === 3){
$('#odinLite_ccBillingWindow .panel-heading-color').removeClass('panel-danger');
$('#odinLite_ccBillingWindow .panel-heading-color').addClass('panel-warning');
$('#odinLite_ccBillingWindow .panel-heading-title').html("Update Billing Information");
}
//Launch the modal and make it non-dismiss
/*$('#billing_verifyModal').modal({
backdrop: 'static',
keyboard: false
});*/
//Make the window.
var actions = [];
if(allowClosing===true){
actions.push("Close");
}
var billingWindow = $('#odinLite_ccBillingWindow').kendoWindow({
title: "Credit Card Authorization",
draggable: false,
resizable: false,
width: "850px",
height: "90%",
modal: true,
close: (allowClosing===true)?true:false,
actions: actions,
close: function () {
billingWindow = null;
$('#odinLite_ccBillingWindow').remove();
}
}).data("kendoWindow");
billingWindow.center();
billingWindow.open();
//Set the HTML title
billingWindow.wrapper.find('.k-window-title').html("<div class='creditCardIcon'></div> Credit Card Authorization");
/** Button Events **/
if(!via.undef(allowSubWithoutCard) && allowSubWithoutCard === "true") {//Check to make sure they can subscribe without cards.
//Check to make sure their number if subscriptions are less then the max amount allowed.
var isMaxSignupAttempts = false;
if(!via.undef(odinLite.MAX_SIGNUP_WITHOUT_CARD) ){
odinLite.MAX_SIGNUP_WITHOUT_CARD = parseInt(odinLite.MAX_SIGNUP_WITHOUT_CARD+"");
if(!via.undef(odinLite.userSignupMap) && !via.undef(odinLite.userSignupMap['SignUp Attempts'])) {
odinLite.userSignupMap['SignUp Attempts'] = parseInt(odinLite.userSignupMap['SignUp Attempts'] + "");
if(odinLite.userSignupMap['SignUp Attempts'] > odinLite.MAX_SIGNUP_WITHOUT_CARD){
isMaxSignupAttempts = true;
}
}
}
//Check to make sure they do not have a past due bill.
var hasPastDueBill = false;
var billingDataSet = odin.getUserSpecificSetting("billingDataSet");
var billingFailureDate = odin.getUserSpecificSetting("billingFailureDate");
if(!via.undef(billingDataSet,true) && !via.undef(billingFailureDate,true)){
hasPastDueBill = true;
}
//Enable the skip if needed.
if(isMaxSignupAttempts === false && hasPastDueBill === false) {
$(".skip-billing-button").show();
$(".skip-billing-button").click(function (e) {
e.preventDefault();
via.kendoConfirm("Skip this step", "Please confirm that you would like to skip this step. <br/>" +
"Without a credit card on file, you can only subscribe to Free and Demo Reports.", function () {
billingWindow.close();
odinLite.isFreeOnlyUser = true;
if (!via.undef(callbackFn)) {
callbackFn(isFirstTimeUser);//Continue with the login
}
})
});
}
}
$('#cc-billing-form').submit(function (e) {
//Don't submit
e.preventDefault();
//Get everything into form values
var formValues = {};
$.each($('#cc-billing-form').serializeArray(), function (i, field) {
formValues[field.name] = field.value;
});
/* Validate */
//Zip Code
$("#cc-billing-form input[name='zip']").removeClass("formError");//Clear error
if (formValues.countryCode === "US") {
var isValidZip = /(^\d{5}$)|(^\d{5}-\d{4}$)/.test(formValues.zip);
if (isValidZip === false) {
via.kendoAlert("Invalid Zip Code", "Please Enter a valid zip code.");
$("#cc-billing-form input[name='zip']").addClass("formError");
return;
}
}
//CVV
$("#cc-billing-form input[name='cardCode']").removeClass("formError");//Clear error
var isValidCVV = /(^\d{3}$)|(^\d{4}$)/.test(formValues.cardCode);
if (isValidCVV === false) {
via.kendoAlert("Invalid CVV", "Please Enter a valid Card Verification Value.");
$("#cc-billing-form input[name='cardCode']").addClass("formError");
return;
}
/* End - Validate */
/* Authorize card on server. */
odinLite_billing.authorizeCard(formValues,callbackFn,isFirstTimeUser);
});
});
}
},
'json');
},
/**
* authorizeCard
* This will make a call to the server to authorize the card.
*/
authorizeCard: function (formValues,callbackFn,isFirstTimeUser) {
kendo.ui.progress($("#odinLite_ccBillingWindow"), true);//Wait Message on
$.post(odin.SERVLET_PATH,
$.extend(formValues, {
action: 'odinLite.billing.authorizeCard'
}),
function (data, status) {
kendo.ui.progress($("#odinLite_ccBillingWindow"), false);//Wait Message off
if (!via.undef(data, true) && data.success === false) {
via.debug("Failure authorizing user:", data.message);
via.kendoAlert("Failure authorizing", data.message, function () {
//console.log("Popup modal window, again. User failed to authorize for whatever reason.");
});
return;
} else {//Success
//Hide the billing screen.
$('#odinLite_ccBillingWindow').data('kendoWindow').close();
via.alert("Credit Card Authorization Successful", data.message, function () {
odin.USER_INFO.userSettings = data.userSettings;//Update user settings with the new values.
if (!via.undef(callbackFn)) {
callbackFn(isFirstTimeUser);//Continue with the login
}
//See if there is any past due balance.
odinLite_billing.pastDueWindowPopup();
});
return;
}
},
'json');
},
/**
* chargeBillingByPackage
* Use this for billing packages.
* This will bill the current user based on the packages selected.
*/
chargeBillingByPackage: function (addPackageList,removePackageList,discountCode,countryCode,successCallbackFn,failCallbackFn) {
if (via.undef(addPackageList, true) && via.undef(removePackageList, true)) {
via.alert("Missing Arguments", "No packages specified.");
return;
}
kendo.ui.progress($("body"), true);//Wait Message on
$.post(odin.SERVLET_PATH,
{
action: 'odinLite.billing.chargeBillingByPackage',
addPackageList: addPackageList, //The packages to be added
removePackageList: removePackageList, //This is the list of packages to be removed and deleted.
discountCode: discountCode,
countryCode: countryCode
},
function (data, status) {
kendo.ui.progress($("body"), false);//Wait Message off
if (!via.undef(data, true) && data.success === false) {
via.debug("Failure billing for sign-up:", data.message);
via.alert("Failure Billing for Sign-up", data.message, function () {
if(!via.undef(failCallbackFn)){
failCallbackFn(data);
}
});
return;
} else {//Success
via.debug("Signup Billing Success Info", data);
if(!via.undef(data.message)){
via.kendoAlert("Signup Message",data.message,function(){
if(!via.undef(successCallbackFn)){
successCallbackFn(data);
}
});
}else if(!via.undef(successCallbackFn)){
successCallbackFn(data);
}
}
},
'json');
},
/**
* updateUserPackage
* This will update/delete packages and optionally delete the data models associated with the packages that are being deleted.
*/
updateUserPackage: function (addPackageList, deletePackageList, isDeleteData) {
if (via.undef(addPackageList, true) && via.undef(deletePackageList, true)) {
via.alert("Missing Arguments", "Specify an add package list or a delete package List.");
return;
}
if (via.undef(isDeleteData, true)) {
isDeleteData = false;
}
$.post(odin.SERVLET_PATH,
{
action: 'odinLite.billing.updateUserPackage',
addPackageList: JSON.stringify(addPackageList),
deletePackageList: JSON.stringify(deletePackageList),
isDeleteData: isDeleteData,
entityDir: odinLite.ENTITY_DIR
},
function (data, status) {
if (!via.undef(data, true) && data.success === false) {
via.debug("Failure updating package:", data.message);
via.alert("Failure Updating Package", data.message, function () {
});
return;
} else {//Success
via.debug("Success updating package", data);
}
},
'json');
},
/* Converts modal form with credit card information into JSON data
that will be sent to Paylane for authorization */
getBillingInfo: function () {
var data = {};
$("#billing-form").serializeArray().map(function (x) {
data[x.name] = x.value;
});
return data;
}
};
<file_sep>/js/manageData.js
/**
* Created by rocco on 4/17/2018.
* This is the manage data js file for the ODIN Lite application.
* This will handle everything to do with the manage data part of the application.
*/
var odinLite_manageData = {
/* Variables */
hasBeenLoaded: false,//Whether this has been loaded before.
tableIndexType: -1, //Table Index Type for the currently selected model.
currentDataItem: null,//Will hold the last loaded data item
currentTableData: null, //Will hold the current table
currentTotalItems: 0, //Will hold the total number of items of the current table
parentVal: null, //holds the parent val of the last selected node
currentDataItemList: null,
/**
* init
* This will initialize ODIN Lite Upload Files and set it up
*/
init: function () {
kendo.ui.progress($("body"), true);//Wait Message
//Reset the items
odinLite_manageData.currentDataItem = null;
odinLite_manageData.currentTableData = null;
$('#manageData_tableSelection').hide();
$("#manageData_existingEntity").removeClass("col-md-12");
$("#manageData_existingEntity").addClass("col-md-6");
$(".manageData_tableSpreadhseetContainer").find(".maximizeButton").attr("title", "Maximize");
$(".manageData_tableSpreadhseetContainer").find(".maximizeButtonIcon").removeClass("fa-compress");
$(".manageData_tableSpreadhseetContainer").find(".maximizeButtonIcon").addClass("fa-expand");
$('.manageData_entityInfo').show();
$('.manageData_modelInfo').show();
$(".manageData_entitySize").empty();
//Make the call to get the initial values for Model Cache
$.post(odin.SERVLET_PATH,
{
action: 'odinLite.manageData.init',
entityDir: odinLite.ENTITY_DIR,
overrideUser: odinLite.OVERRIDE_USER,
isDataManagerUser: odinLite.isDataManagerUser,
appId: odinLite.currentApplication
},
function (data, status) {
odinLite_manageData.hasBeenLoaded = true;//Set the loaded variable after first load.
kendo.ui.progress($("body"), false);//Wait Message off
if (!via.undef(data, true) && data.success === false) {
via.debug("Failure getting model data:", data.message);
via.kendoAlert("Load Failure", data.message);
} else {
via.debug("Successful getting model data:", data);
//Show the panels.
$('#viewPanel').fadeIn();
var modelListLength = Object.keys(data.modelList).length;
if (modelListLength === 0) {
via.kendoAlert("Load Failure", "User not permissioned for any models.");
return;
}
//Reset in case they were accessed before:
$('#manageData_welcomeMessage').fadeIn();
$('#manageData_existingEntity').hide();
//Display the size of the entity
//Model Size
if (!via.undef(data.entitySize)) {
var formattedSize = via.getReadableFileSizeString(data.entitySize);
$(".manageData_entitySize").html(" <i><small>(size: " + formattedSize + ") </small></i>");
}
if (!via.undef(odinLite.isDataManagerUser) && odinLite.isDataManagerUser === true) {
odinLite_manageData.createDataManagerModelTree(data);
} else {
odinLite_manageData.createModelTree(data.modelList, data.requiredModels, data.optionalModels);
}
$('#viewPanel').fadeIn();
}
},
'json');
},
/**
* deleteTablesWindow
* This will allow choosing of the tables for deletion.
*/
deleteTablesWindow: function () {
if (via.undef(odinLite_manageData.currentDataItemList) || odinLite_manageData.currentDataItemList.length === 0) {
return;
}
/** Window Setup **/
kendo.ui.progress($("body"), true);//Wait Message
$.get("./html/deleteTablesWindow.html", function (deleteTablesWindowTemplate) {
kendo.ui.progress($("body"), false);//Wait Message
$('#odinLite_deleteTablesWindow').remove();
$('body').append(deleteTablesWindowTemplate);
//Make the window.
var deleteTablesWindow = $('#odinLite_deleteTablesWindow').kendoWindow({
title: "Delete Data Item Chooser",
draggable: false,
resizable: false,
width: "450px",
height: "450px",
modal: true,
close: false,
actions: [
"Maximize",
"Close"
],
close: function () {
deleteTablesWindow = null;
$('#odinLite_deleteTablesWindow').remove();
}
}).data("kendoWindow");
deleteTablesWindow.center();
//Check for Demo Account
if (odinLite_manageData.currentModel.value.startsWith("DEMO_")) {
$(".fileFormat_deleteDataItemButton").prop("disabled", true);
} else {
$(".fileFormat_deleteDataItemButton").prop("disabled", false);
}
/** Window Setup **/
$('.fileFormat_deleteDataItemButton').click(function () {
var checkedNodes = [];
var parentNodes = [];
var treeView = $("#manageData_deleteTreeview").data('kendoTreeView');
checkedNodeIds(treeView.dataSource.view(), checkedNodes, parentNodes);
//We need to null out port dir.
if (odinLite_manageData.tableIndexType !== 3) {
parentNodes = null;
}
if (checkedNodes.length === 0) {
return;
}//Don't delete if zero selected.
//Close the window.
deleteTablesWindow.close();
via.confirm("Delete Data Items", "Are you sure you want to delete " + checkedNodes.length + " data item(s)? This action cannot be undone.", function () {
deleteFromServer();
});
//Delete form the server.
function deleteFromServer() {
kendo.ui.progress($("#odinLite_deleteTablesWindow"), true);//Wait Message
$.post(odin.SERVLET_PATH,
{
action: 'odinLite.manageData.deleteTableFromCache',
modelId: odinLite_manageData.currentModel.value,
portDir: (parentNodes === null) ? null : JSON.stringify(parentNodes),
dataItems: JSON.stringify(checkedNodes),
entityDir: odinLite.ENTITY_DIR,
overrideUser: odinLite.OVERRIDE_USER
},
function (data, status) {
kendo.ui.progress($("#odinLite_deleteTablesWindow"), false);//Wait Message off
if (!via.undef(data, true) && data.success === false) {
via.debug("Failure deleting table:", data.message);
via.kendoAlert("Delete Failure", data.message);
} else {
via.debug("Successful delete:", data);
odinLite_manageData.getItemTreeList();
}
},
'json');
}
});
/** For the data item tree **/
//Create the Data Source
var processDataSource = new kendo.data.HierarchicalDataSource({
sort: {field: "text", dir: "asc"},
data: odinLite_manageData.currentDataItemList
});
//Make the tree and get rid of old tree.
if (!via.undef($("#manageData_deleteTreeview").data('kendoTreeView'))) {
$("#manageData_tableTreeview").data('kendoTreeView').destroy();
}
$("#manageData_deleteTreeview").empty();
$("#manageData_deleteTreeview").kendoTreeView({
checkboxes: {
checkChildren: true,
//template: "<input style='position:relative;top:3px;left:3px;' type='checkbox' name='checkedFiles[#= item.id #]' value='true' />"
template: "# if(!item.hasChildren){# <input style='position:relative;top:3px;left:3px;' type='checkbox' name='checkedFiles[#= item.id #]' value='true' />#}#"
},
dataSource: processDataSource,
//dataSpriteCssClassField: "iconCls",
expand: function (e) {
if ($("#manageData_deleteFilterText").val() == "") {
$(e.node).find("li").show();
}
}
});
//Check and unchck all nodes
$('#manageData_selectAllButton').click(function () {
selectAll();
});
$('#manageData_deselectAllButton').click(function () {
deselectAll();
});
//Expand and Collapse Tree
$('#manageData_deleteExpandButton').click(function () {
var treeview = $("#manageData_deleteTreeview").data("kendoTreeView");
treeview.expand(".k-item");
});
$('#manageData_deleteCollapseButton').click(function () {
var treeview = $("#manageData_deleteTreeview").data("kendoTreeView");
treeview.collapse(".k-item");
});
$("#manageData_deleteFilterText").keyup(function (e) {
if (e.keyCode == 13) {
var changeReport_filterText = $(this).val();
filterTableList(changeReport_filterText);
}
});
$("#manageData_deleteFilterButton").click(function () {
var changeReport_filterText = $("#manageData_deleteFilterText").val();
filterTableList(changeReport_filterText);
});
//function that filters the table.
function filterTableList(changeReport_filterText) {
deselectAll();
if (changeReport_filterText !== "") {
$("#manageData_deleteTreeview .k-group .k-group .k-in").closest("li").hide();
$("#manageData_deleteTreeview .k-group").closest("li").hide();
$("#manageData_deleteTreeview .k-group .k-group .k-in:containsi(" + changeReport_filterText + ")").each(function () {
$(this).parents("ul, li").each(function () {
var treeView = $("#manageData_tableTreeview").data("kendoTreeView");
treeView.expand($(this).parents("li"));
$(this).show();
});
});
$("#manageData_deleteTreeview .k-group .k-in:contains(" + changeReport_filterText + ")").each(function () {
$(this).parents("ul, li").each(function () {
$(this).show();
});
});
}
else {
$("#manageData_deleteTreeview .k-group").find("li").show();
var nodes = $("#manageData_tableTreeview > .k-group > li");
$.each(nodes, function (i, val) {
if (nodes[i].getAttribute("data-expanded") == null) {
$(nodes[i]).find("li").hide();
}
});
}
}
// function that gathers IDs of checked nodes
function checkedNodeIds(nodes, checkedNodes, parentNodes) {
for (var i = 0; i < nodes.length; i++) {
if (nodes[i].checked) {
checkedNodes.push(nodes[i].text);
if (!via.undef(nodes[i].parentNode()) && odinLite_manageData.tableIndexType === 3) {
parentNodes.push(nodes[i].parentNode().text);
}
}
if (nodes[i].hasChildren) {
checkedNodeIds(nodes[i].children.view(), checkedNodes, parentNodes);
}
}
}
// function that unchecks all nodes
function deselectAll() {
$("#manageData_deleteTreeview input").prop("checked", false).trigger("change");
}
// function that checks all nodes that are visible
function selectAll() {
$("#manageData_deleteTreeview input:visible").prop("checked", true).trigger("change");
}
/******/
});
kendo.ui.progress($("body"), false);//Wait Message
},
/**
* createDataManagerModelTree
* This will create the tree to allow model selection for Data Manager Users
*/
createDataManagerModelTree: function (data) {
odinLite_manageData.currentDataItem = null;
odinLite_manageData.currentTableData = null;
//Get the data in the correct format.
var treeData = JSON.parse(JSON.stringify(data.modelList));
var kendoTreeData = [];
for (var i = 0; i < treeData.length; i++) {
var node = treeData[i];
kendoTreeData = renameChildren(kendoTreeData, node, true);
}
function renameChildren(kendoTreeData, node, isRoot) {//Recursive function. All it does it rename children to items.
//Recursive - If it has children call this method again.
if (!via.undef(node.children) && node.children.length > 0) {
for (var i = 0; i < node.children.length; i++) {
var childNode = node.children[i];
kendoTreeData = renameChildren(kendoTreeData, childNode, false);
}
node.items = node.children;
node.children = null;
delete node.children;
}
if (isRoot === true) {
kendoTreeData.push(node);
}
return kendoTreeData;
}
//End - Get data
//Create the Data Source
var processDataSource = new kendo.data.HierarchicalDataSource({
sort: {field: "text", dir: "asc"},
data: kendoTreeData
});
//Make the tree
//$("#modelCacheSelection_treeview").empty();
if (!via.undef($("#manageData_modelTreeview").data('kendoTreeView'))) {
$("#manageData_modelTreeview").data('kendoTreeView').destroy();
$("#manageData_modelTreeview").empty();
}
$("#manageData_modelTreeview").kendoTreeView({
dataSource: processDataSource,
dataSpriteCssClassField: "iconCls",
expand: function (e) {
if ($("#modelCacheSelection_filterText").val() == "") {
$(e.node).find("li").show();
}
},
change: function (e) {
var selected = this.select();
if (via.undef(selected)) {
return false;
}
var item = this.dataItem(selected);
if (via.undef(item)) {
return false;
}
if (item.hasChildren) {
return false;
}
if (via.undef(item.value)) {
return false;
}
//Get the current model selected
odinLite_manageData.currentModel = {
value: item.value,
text: item.text,
description: item.description
};
$(".manageData_tableSpreadhseetContainer").hide();
odinLite_manageData.getItemTreeList();
//(item.value,true);
//Check for Demo Account
if (item.value.startsWith("DEMO_")) {
$(".demoButton").prop("disabled", true);
} else {
$(".demoButton").prop("disabled", false);
}
}
});
//Expand and Collapse Tree
$('#manageData_modelExpandButton').click(function () {
var treeview = $("#manageData_modelTreeview").data("kendoTreeView");
treeview.expand(".k-item");
});
$('#manageData_modelCollapseButton').click(function () {
var treeview = $("#manageData_modelTreeview").data("kendoTreeView");
treeview.collapse(".k-item");
});
$("#manageData_modelFilterText").keyup(function (e) {
var changeReport_filterText = $(this).val();
if (changeReport_filterText !== "") {
$("#manageData_modelTreeview .k-group .k-group .k-in").closest("li").hide();
$("#manageData_modelTreeview .k-group").closest("li").hide();
$("#manageData_modelTreeview .k-group .k-group .k-in:containsi(" + changeReport_filterText + ")").each(function () {
$(this).parents("ul, li").each(function () {
var treeView = $("#manageData_modelTreeview").data("kendoTreeView");
treeView.expand($(this).parents("li"));
$(this).show();
});
});
}
else {
$("#manageData_modelTreeview .k-group").find("li").show();
var nodes = $("#manageData_modelTreeview > .k-group > li");
$.each(nodes, function (i, val) {
if (nodes[i].getAttribute("data-expanded") === null) {
$(nodes[i]).find("li").hide();
}
});
}
});
},
/**
* createModelTree
* This will create the tree to allow model selection.
*/
createModelTree: function (modelList, requiredModels, optionalModels) {
odinLite_manageData.currentDataItem = null;
odinLite_manageData.currentTableData = null;
//Build the Tree Data
var kendoTreeData = [];
$.each(modelList, function (key, modelArr) {
if (via.undef(modelArr)) {
return;
}
var applicationObj = {};
applicationObj.text = key;
applicationObj.value = key;
applicationObj.expanded = true;
applicationObj.items = [];
applicationObj.iconCls = "folderCls";
var requiredObj = {};
requiredObj.text = " Required";
requiredObj.value = "Required";
requiredObj.expanded = true;
requiredObj.items = [];
requiredObj.iconCls = "folderCls";
var optionalObj = {};
optionalObj.text = "Optional";
optionalObj.value = "Optional";
optionalObj.expanded = true;
optionalObj.items = [];
optionalObj.iconCls = "folderCls";
for (var i = 0; i < modelArr.length; i++) {
var modelObj = {};
modelObj.text = modelArr[i][1];
modelObj.value = modelArr[i][0];
if (modelArr[i].length > 2) {
modelObj.description = modelArr[i][2];
}
modelObj.iconCls = "leafArrowCls";
//Optional / Required
if (!via.undef(requiredModels) && $.inArray(modelObj.value, requiredModels) !== -1) {
requiredObj.items.push(modelObj);
} else if (!via.undef(optionalModels) && $.inArray(modelObj.value, optionalModels) !== -1) {
optionalObj.items.push(modelObj);
} else {
continue;
}
}
if (requiredObj.items.length > 0) {
applicationObj.items.push(requiredObj);
}
if (optionalObj.items.length > 0) {
applicationObj.items.push(optionalObj);
}
if (applicationObj.items.length > 0) {
kendoTreeData.push(applicationObj);
}
});
//End - Build the Tree Data
//Create the Data Source
var processDataSource = new kendo.data.HierarchicalDataSource({
sort: {field: "text", dir: "asc"},
data: kendoTreeData
});
//Make the tree
//$("#modelCacheSelection_treeview").empty();
if (!via.undef($("#manageData_modelTreeview").data('kendoTreeView'))) {
$("#manageData_modelTreeview").data('kendoTreeView').destroy();
$("#manageData_modelTreeview").empty();
}
$("#manageData_modelTreeview").kendoTreeView({
dataSource: processDataSource,
dataSpriteCssClassField: "iconCls",
expand: function (e) {
if ($("#modelCacheSelection_filterText").val() == "") {
$(e.node).find("li").show();
}
},
change: function (e) {
var selected = this.select();
if (via.undef(selected)) {
return false;
}
var item = this.dataItem(selected);
if (via.undef(item)) {
return false;
}
if (item.hasChildren) {
return false;
}
if (via.undef(item.value)) {
return false;
}
//Get the current model selected
odinLite_manageData.currentModel = {
value: item.value,
text: item.text,
description: item.description
};
$("#manageData_tableFilterText").val(null);
$("#manageData_folderFilterText").val(null);
$(".manageData_tableSpreadhseetContainer").hide();
odinLite_manageData.getItemTreeList();
//(item.value,true);
//Check for Demo Account
if (item.value.startsWith("DEMO_")) {
$(".demoButton").prop("disabled", true);
} else {
$(".demoButton").prop("disabled", false);
}
}
});
//Expand and Collapse Tree
$('#manageData_modelExpandButton').click(function () {
var treeview = $("#manageData_modelTreeview").data("kendoTreeView");
treeview.expand(".k-item");
});
$('#manageData_modelCollapseButton').click(function () {
var treeview = $("#manageData_modelTreeview").data("kendoTreeView");
treeview.collapse(".k-item");
});
$("#manageData_modelFilterText").keyup(function (e) {
var changeReport_filterText = $(this).val();
if (changeReport_filterText !== "") {
$("#manageData_modelTreeview .k-group .k-group .k-in").closest("li").hide();
$("#manageData_modelTreeview .k-group").closest("li").hide();
$("#manageData_modelTreeview .k-group .k-group .k-in:containsi(" + changeReport_filterText + ")").each(function () {
$(this).parents("ul, li").each(function () {
var treeView = $("#manageData_modelTreeview").data("kendoTreeView");
treeView.expand($(this).parents("li"));
$(this).show();
});
});
}
else {
$("#manageData_modelTreeview .k-group").find("li").show();
var nodes = $("#manageData_modelTreeview > .k-group > li");
$.each(nodes, function (i, val) {
if (nodes[i].getAttribute("data-expanded") === null) {
$(nodes[i]).find("li").hide();
}
});
}
});
},
/**
* getItemTreeList
* This will return the tree list of items/tables for the selected model.
*/
getItemTreeList: function (isFilter,maxElements) {
if (isFilter) {
kendo.ui.progress($('#manageData_tableSelection'), true);//Wait Message
} else {
kendo.ui.progress($("body"), true);//Wait Message
}
var entityDir = odinLite.ENTITY_DIR;
var modelId = odinLite_manageData.currentModel.value;
odinLite_manageData.currentDataItem = null;
//Show the model name and desc
$("#manageData_existingEntity").fadeIn();
$("#manageData_welcomeMessage").hide();
$(".manageData_modelName").html(odinLite_manageData.currentModel.text);
if (!via.undef(odinLite_manageData.currentModel.description)) {
$(".manageData_modelDescription").html(odinLite_manageData.currentModel.description);
}
if (!isFilter) {
$('#manageData_tableSelection').hide();
}
$(".manageData_tableSpreadhseetContainer").hide();
$('#manageData_totalRows').empty();
$('#manageData_deleteTableButton').attr("disabled", true);
//Make the call to get the initial values for Model Cache
$.post(odin.SERVLET_PATH,
{
action: 'odinLite.manageData.getItemTreeList',
entityDir: entityDir,
modelId: modelId,
itemFilter: $("#manageData_tableFilterText").val(),
portFilter: $("#manageData_folderFilterText").val(),
overrideUser: odinLite.OVERRIDE_USER,
isRefresh: isFilter,
maxElementsOverride: maxElements
},
function (data, status) {
if (isFilter) {
kendo.ui.progress($('#manageData_tableSelection'), false);//Wait Message
} else {
kendo.ui.progress($("body"), false);//Wait Message
}
//Model Size
if (!via.undef(data.modelSize)) {
var formattedSize = via.getReadableFileSizeString(data.modelSize);
$(".manageData_modelName").append(" <i><small>(size: " + formattedSize + ") </small></i>");
}
//Save the index table type
odinLite_manageData.tableIndexType = data.tableIndexType;
$(".manageData_zeroTablesFound").hide();
$(".manageData_tablesFound").hide();
$(".manageData_zeroTablesFound").empty();
if (odinLite_manageData.tableIndexType === 3) {
$("#manageData_folderFilterText").show();
} else {
$("#manageData_folderFilterText").hide();
}
if (!via.undef(data, true) && data.success === false && !isFilter && data.totalItems === 0) {
via.debug("Failure getting model items:", data.message);
//via.kendoAlert("Load Failure", data.message);
$(".manageData_zeroTablesFound").html(data.message);
$(".manageData_zeroTablesFound").show();
$(".manageData_tableTreeview").hide();
$('#manageData_tableSelection').fadeIn();
odinLite_manageData.currentDataItemList = null;
return;
}
//Update Total Rows
if (via.undef(isFilter) || isFilter !== true) {
odinLite_manageData.currentTotalItems = data.totalItems;
}
//Found tables
via.debug("Successful getting model items:", data);
$(".manageData_tablesFound").show();
//Show rows
if (data.totalItems > data.MAX_ELEMENTS || !via.undef(maxElements,true)) {
//$('#manageData_totalRows').html("<i>Displaying only " + kendo.toString(data.MAX_ELEMENTS, "#,###") + " of " + kendo.toString(data.totalItems, "#,###") + " items. Please apply Data Item Filter.</i>");
$('#manageData_totalRows').html("Displaying only " + "<input style=\"width:85px;\" class=\"itemList_maxElements\"/>" + " of " + kendo.toString(data.totalItems, "#,###") + " items. Please apply Data Item Filter.</i>");
$(".itemList_maxElements").kendoDropDownList({
dataTextField: "text",
dataValueField: "value",
dataSource: [
{text: "200",value:200},
{text: "500",value:500},
{text: "1,000",value:1000}
],
value: data.MAX_ELEMENTS,
change: function(e){
var val = e.sender.value();
odinLite_manageData.getItemTreeList(false,val);
}
});
} else if (!via.undef(isFilter) && isFilter === true) {
$('#manageData_totalRows').html("<b>Filter:</b> Displaying " + kendo.toString(data.totalItems, "#,###") + " of " + kendo.toString(odinLite_manageData.currentTotalItems, "#,###") + " items.")
}
if (data.totalItems === 0) {
$('#manageData_deleteTableButton').attr("disabled", true);
} else {
$('#manageData_deleteTableButton').attr("disabled", false);
}
/*******/
//Populate data item tree
//Get the data in the correct format.
var treeData = [];
if (!via.undef(data) && !via.undef(data.itemList) && data.itemList.length > 0) {
treeData = JSON.parse(JSON.stringify(data.itemList));
}
var kendoTreeData = [];
for (var i = 0; i < treeData.length; i++) {
var node = treeData[i];
kendoTreeData = renameChildren(kendoTreeData, node, true);
}
odinLite_manageData.currentDataItemList = kendoTreeData;
function renameChildren(kendoTreeData, node, isRoot) {//Recursive function. All it does it rename children to items.
//Recursive - If it has children call this method again.
if (!via.undef(node.children) && node.children.length > 0) {
for (var i = 0; i < node.children.length; i++) {
var childNode = node.children[i];
kendoTreeData = renameChildren(kendoTreeData, childNode, false);
}
node.items = node.children;
node.children = null;
delete node.children;
}
if (isRoot === true) {
kendoTreeData.push(node);
}
return kendoTreeData;
}
//End - Get data
//Create the Data Source
var processDataSource = new kendo.data.HierarchicalDataSource({
sort: {field: "text", dir: "asc"},
data: kendoTreeData
});
//Make the tree and get rid of old tree.
var manageData_tableTreeview = $("#manageData_tableTreeview");
if (!via.undef(manageData_tableTreeview.data('kendoTreeView'))) {
manageData_tableTreeview.data('kendoTreeView').destroy();
}
manageData_tableTreeview.empty();
manageData_tableTreeview.kendoTreeView({
dataSource: processDataSource,
dataSpriteCssClassField: "iconCls",
expand: function (e) {
if ($("#manageData_tableFilterText").val() == "") {
$(e.node).find("li").show();
}
},
change: function (e) {
var selected = this.select();
if (via.undef(selected)) {
return false;
}
var item = this.dataItem(selected);
if (via.undef(item)) {
return false;
}
if (item.hasChildren) {
return false;
}
if (via.undef(item.value)) {
return false;
}
odinLite_manageData.parentVal = null;
if (!via.undef(item.parentNode()) && odinLite_manageData.tableIndexType === 3) {
odinLite_manageData.parentVal = item.parentNode().value;
}
odinLite_manageData.getDataItemTable(item.value);//Display the table on the screen
}
});
//Expand and Collapse Tree
$('#manageData_tableExpandButton').off();
$('#manageData_tableExpandButton').click(function () {
var treeview = $("#manageData_tableTreeview").data("kendoTreeView");
treeview.expand(".k-item");
});
$('#manageData_tableCollapseButton').off();
$('#manageData_tableCollapseButton').click(function () {
var treeview = $("#manageData_tableTreeview").data("kendoTreeView");
treeview.collapse(".k-item");
});
$('#manageData_tableFilterText').off();
$("#manageData_tableFilterText").keyup(function (e) {
if (e.keyCode == 13) {
//var changeReport_filterText = $(this).val();
//filterTableList(changeReport_filterText);
odinLite_manageData.getItemTreeList(true);
}
});
$('#manageData_folderFilterText').off();
$("#manageData_folderFilterText").keyup(function (e) {
if (e.keyCode == 13) {
//var changeReport_filterText = $(this).val();
//filterTableList(changeReport_filterText);
odinLite_manageData.getItemTreeList(true);
}
});
$('#manageData_tableSearchButton').off();
$("#manageData_tableSearchButton").click(function () {
//var changeReport_filterText = $("#manageData_tableFilterText").val();
//filterTableList(changeReport_filterText);
odinLite_manageData.getItemTreeList(true);
});
/******/
$('#manageData_tableSelection').fadeIn();
},
'json');
function filterTableList(changeReport_filterText) {
if (changeReport_filterText !== "") {
$("#manageData_tableTreeview .k-group .k-group .k-in").closest("li").hide();
$("#manageData_tableTreeview .k-group").closest("li").hide();
$("#manageData_tableTreeview .k-group .k-group .k-in:containsi(" + changeReport_filterText + ")").each(function () {
$(this).parents("ul, li").each(function () {
var treeView = $("#manageData_tableTreeview").data("kendoTreeView");
treeView.expand($(this).parents("li"));
$(this).show();
});
});
$("#manageData_tableTreeview .k-group .k-in:contains(" + changeReport_filterText + ")").each(function () {
$(this).parents("ul, li").each(function () {
$(this).show();
});
});
}
else {
$("#manageData_tableTreeview .k-group").find("li").show();
var nodes = $("#manageData_tableTreeview > .k-group > li");
$.each(nodes, function (i, val) {
if (nodes[i].getAttribute("data-expanded") == null) {
$(nodes[i]).find("li").hide();
}
});
}
}
},
filterDataItemTable: function (portId, item) {
kendo.ui.progress($("body"), true);//Wait Message off
//Make the call to get the table selected for this model
$.post(odin.SERVLET_PATH,
{
action: 'odinLite.manageData.getDataItemTable',
modelId: modelId,
entityDir: entityDir,
dataItem: dataItem,
portDir: odinLite_manageData.parentVal,
overrideUser: odinLite.OVERRIDE_USER
},
function (data, status) {
kendo.ui.progress($("body"), false);//Wait Message off
$("html, body").animate({
scrollTop: 0
}, 250);
if (!via.undef(data, true) && data.success === false) {
via.debug("Failure getting data items:", data.message);
via.kendoAlert("Get Data Items Failure", data.message);
} else {
via.debug("Successful getting data item:", data);
}
},
'json');
},
/**
* getDataItemTable
* This will retrieve a data item and display it on the screen
*/
getDataItemTable: function (dataItem) {
var entityDir = odinLite.ENTITY_DIR;
var modelId = odinLite_manageData.currentModel.value;
$('#manageData_editModeLabel').hide();
//if(odinLite_manageData.currentDataItem === dataItem && odinLite_manageData.tableIndexType !== 3){ return; }
odinLite_manageData.currentDataItem = dataItem;
kendo.ui.progress($("body"), true);//Wait Message
//Make the call to get the table selected for this model
$.post(odin.SERVLET_PATH,
{
action: 'odinLite.manageData.getDataItemTable',
modelId: modelId,
entityDir: entityDir,
dataItem: dataItem,
portDir: odinLite_manageData.parentVal,
overrideUser: odinLite.OVERRIDE_USER
},
function (data, status) {
kendo.ui.progress($("body"), false);//Wait Message off
$("html, body").animate({
scrollTop: 0
}, 250);
//JSON parse does not like NaN
if (!via.undef(data, true)) {
data = JSON.parse(data.replace(/\bNaN\b/g, "null"));
}
if (!via.undef(data, true) && data.success === false) {
via.debug("Failure getting data item:", data.message);
via.kendoAlert("Get Data Item Failure", data.message);
} else {
via.debug("Successful getting data item:", data);
odinLite_manageData.currentTableData = data.tsEncoded;
odinLite_manageData.currentTableData.requiredColumns = data.requiredColumns;
var sheetData = odinLite_fileFormat.getSpreadsheetDataFromTableSet(data.tsEncoded, false, false);
if (!via.undef(data.tsEncoded.tableLabel, true)) {
sheetData.name = data.tsEncoded.tableLabel;
$('.manageData_tableSpreadhseetName').html(data.tsEncoded.tableLabel);
} else {
$('.manageData_tableSpreadhseetName').html("Table Preview");
}
//Insert the sheet preview.
if (!via.undef($("#manageData_tableSpreadhseet").data('kendoSpreadsheet'))) {
$("#manageData_tableSpreadhseet").data('kendoSpreadsheet').destroy();
}
//Freeze the top Row.
sheetData.frozenRows = 1;
$(".manageData_tableSpreadhseetContainer").show();
$("#manageData_tableSpreadhseet").empty();
$("#manageData_tableSpreadhseet").kendoSpreadsheet({
//height: '200px',
headerHeight: 20,
//headerWidth: 0,
toolbar: false,
sheetsbar: false,
rows: null,
columns: null,
sheets: [sheetData]
});
$("#manageData_tableSpreadhseet .k-spreadsheet-sheets-bar-add").hide();
$("#manageData_tableSpreadhseet .k-link").prop("disabled", true);
$('.manageData_tableSpreadhseetContainer').fadeIn();
}
},
'text');
},
/**
* maximizeSheet
* This will attempt to maximize a the spreadsheet
*/
maximizeSheet: function () {
$('.manageData_entityInfo').toggle();
$('.manageData_modelInfo').toggle();
$('#manageData_tableSelection').toggle();
if ($("#manageData_existingEntity").hasClass("col-md-6")) {
$("#manageData_existingEntity").removeClass("col-md-6");
$("#manageData_existingEntity").addClass("col-md-12");
$(".manageData_tableSpreadhseetContainer").find(".maximizeButton").attr("title", "Minimize");
$(".manageData_tableSpreadhseetContainer").find(".maximizeButtonIcon").removeClass("fa-expand");
$(".manageData_tableSpreadhseetContainer").find(".maximizeButtonIcon").addClass("fa-compress");
$("#manageData_tableSpreadhseet").data("kendoSpreadsheet").resize();
} else {
$("#manageData_existingEntity").removeClass("col-md-12");
$("#manageData_existingEntity").addClass("col-md-6");
$(".manageData_tableSpreadhseetContainer").find(".maximizeButton").attr("title", "Maximize");
$(".manageData_tableSpreadhseetContainer").find(".maximizeButtonIcon").removeClass("fa-compress");
$(".manageData_tableSpreadhseetContainer").find(".maximizeButtonIcon").addClass("fa-expand");
$("#manageData_tableSpreadhseet").data("kendoSpreadsheet").resize();
}
//Scroll
$("html, body").animate({
scrollTop: 0
}, 250);
},
/**
* exportSheet
* This will export the sheet to excel
*/
exportSheet: function () {
kendo.ui.progress($("body"), true);//Wait Message on
//via.downloadFile(odin.SERVLET_PATH + "?action=admin.streamFile&reportName=" + encodeURIComponent(data.reportName));
var portDir = null;
if(odinLite_manageData.tableIndexType===3){
portDir = odinLite_manageData.parentVal;
}
$.post(odin.SERVLET_PATH,
{
action: 'odinLite.manageData.exportFile',
modelId: odinLite_manageData.currentModel.value,
entityDir: odinLite.ENTITY_DIR,
dataItem: odinLite_manageData.currentDataItem,
portDir: portDir,
overrideUser: odinLite.OVERRIDE_USER
},
function (data, status) {
odinLite_manageData.hasBeenLoaded = true;//Set the loaded variable after first load.
kendo.ui.progress($("body"), false);//Wait Message off
if (!via.undef(data, true) && data.success === false) {
via.debug("Failure downloading file:", data.message);
via.kendoAlert("Download Failure", data.message);
} else {
via.debug("Successful getting model data:", data);
via.downloadFile(odin.SERVLET_PATH + "?action=admin.streamFile&reportName=" + encodeURIComponent(data.reportName));
}
},
'json');
/*
$.post(odin.SERVLET_PATH,
{
action: 'admin.createFileFromGrid',
reportData: JSON.stringify(odinLite_manageData.currentTableData),
type: 'xlsx',
overrideUser: odinLite.OVERRIDE_USER
},
function (data, status) {
odinLite_manageData.hasBeenLoaded = true;//Set the loaded variable after first load.
kendo.ui.progress($("body"), false);//Wait Message off
if (!via.undef(data, true) && data.success === false) {
via.debug("Failure downloading file:", data.message);
via.kendoAlert("Download Failure", data.message);
} else {
via.debug("Successful getting model data:", data);
via.downloadFile(odin.SERVLET_PATH + "?action=admin.streamFile&reportName=" + encodeURIComponent(data.reportName));
}
},
'json');
*/
},
/**
* getFolderStructure
* This will get the folder structure tree for manage data
*/
getFolderStructure: function(){
kendo.ui.progress($("body"), true);//Wait Message
$.get("./html/fileStructureWindow.html", function (deleteTablesWindowTemplate) {
kendo.ui.progress($("body"), false);//Wait Message
$('#odinLite_fileStructureWindow').remove();
$('body').append(deleteTablesWindowTemplate);
//Make the window.
var deleteTablesWindow = $('#odinLite_fileStructureWindow').kendoWindow({
title: odinLite.ENTITY_NAME + " Entity Data Model",
draggable: false,
resizable: false,
width: "800px",
height: ($( window ).height() * .85) + "px",
modal: true,
close: false,
actions: [
"Maximize",
"Close"
],
resize: function(){
$('#manageData_fileStructureTreeview').css("height",($('#odinLite_fileStructureWindow').height() - 40) + "px");
},
close: function () {
deleteTablesWindow = null;
$('#odinLite_deleteTablesWindow').remove();
}
}).data("kendoWindow");
deleteTablesWindow.center();
//Set the size
$('#manageData_fileStructureTreeview').css("height",($('#odinLite_fileStructureWindow').height() - 40) + "px");
//Make the call to the tree
odinLite_manageData.getFileTreeGrid("#manageData_fileStructureTreeview");
$("#manageData_fileStructureTreeview tbody").bind('dblclick', function (e) {
var tree = $("#manageData_fileStructureTreeview").data('kendoTreeList');
var selected = tree.select();
var dataItem = tree.dataItem(selected);
if (dataItem.hasChildren === true) {
if(dataItem.expanded === true) {
tree.collapse(selected);
}else{
tree.expand(selected);
}
}
});
//Set the button action
$('#manageData_downloadFileStructureButton').click(function(){
var tree = $("#manageData_fileStructureTreeview").data('kendoTreeList');
var selected = tree.select();
var dataItem = tree.dataItem(selected);
//if(dataItem.hasChildren === true){ return; }
//download the file to csv
downloadFile(dataItem.path,dataItem.hasChildren);
});
/*Functions*/
//Download the selected file
function downloadFile(filePath,isFolder){
odinLite.getExportFilesWindow(function(fileType,delimiter) {
kendo.ui.progress($("#odinLite_fileStructureWindow"), true);//Wait Message on
$.post(odin.SERVLET_PATH,
{
action: 'odinLite.manageData.exportCacheFile',
filePath: filePath,
isFolder: isFolder,
entityDir: odinLite.ENTITY_DIR,
overrideUser: odinLite.OVERRIDE_USER,
fileType: fileType,
fileDelimiter: delimiter
},
function (data, status) {
kendo.ui.progress($("#odinLite_fileStructureWindow"), false);//Wait Message off
if (!via.undef(data, true) && data.success === false) {
via.debug("Failure downloading file:", data.message);
via.kendoAlert("Download Failure", data.message);
} else {
via.debug("Successful download:", data);
console.log();
via.downloadFile(odin.SERVLET_PATH + "?action=admin.streamFile&reportName=" + encodeURIComponent(data.reportName));
}
},
'json');
});
}
});
},
/**
* getSQLImportWindow
* This will import the sql tables
*/
getSQLImportWindow: function(){
kendo.ui.progress($("body"), true);//Wait Message
$.get("./html/sqlTableChooserWindow.html", function (sqlWindowTemplate) {
kendo.ui.progress($("body"), false);//Wait Message
$('#odinLite_sqlTableWindow').remove();
$('body').append(sqlWindowTemplate);
//Make the window.
var sqlTablesWindow = $('#odinLite_sqlTableWindow').kendoWindow({
title: "Select Tables to Query",
draggable: false,
resizable: false,
width: "950px",
height: "580px",
modal: true,
close: false,
actions: [
"Maximize",
"Close"
],
close: function () {
sqlTablesWindow = null;
$('#odinLite_sqlTableWindow').remove();
}
}).data("kendoWindow");
sqlTablesWindow.center();
//Make the call to the tree
odinLite_manageData.getFileTreeGrid("#odinLite_sqlFolderStructure");
$("#odinLite_sqlFolderStructure tbody").bind('dblclick', function (e) {
var tree = $("#odinLite_sqlFolderStructure").data('kendoTreeList');
var selected = tree.select();
var dataItem = tree.dataItem(selected);
if (dataItem.hasChildren === true) {
if(dataItem.expanded === true) {
tree.collapse(selected);
}else{
tree.expand(selected);
}
}else {
addItemToFileManager();
}
});
getFileManagerGrid();
//Set the button action
$('#odinLite_sqlTable_addButton').click(function(){
addItemToFileManager();
});
$('#odinLite_sqlManager_createButton').click(function(){
var fileManagerGrid = $("#odinLite_sqlFileManager").data('kendoGrid');
var gridData = fileManagerGrid.dataSource.data();
if(gridData.length === 0){
via.kendoAlert("SQL Table Import","There are no files in the list.");
return;
}
sqlTablesWindow.close();
odin.progressBar("SQL Table Import",100,"Importing " + gridData.length + ((gridData.length>1)?" files.":" file."));
var records = JSON.stringify(gridData);
$.post(odin.SERVLET_PATH,
{
action: 'odinLite.manageData.importDatabaseTables',
overrideUser: odinLite.OVERRIDE_USER,
records: records,
entityDir:odinLite.ENTITY_DIR
},
function (data, status) {
odin.progressBar("SQL Table Import",100,null,true);
if (!via.undef(data, true) && data.success === false) {
via.kendoAlert("SQL Table Import","Error: " + data.message);
via.debug("SQL Table Import", data.message);
} else {//Success - SQL Import
via.debug("SQL Table Import Success:", data.message);
odinLite_manageData.getSQLQueryWindow(data);
}
},
'json');
});
/*Functions*/
//Add the item to the file manager grid.
function addItemToFileManager() {
var tree = $("#odinLite_sqlFolderStructure").data('kendoTreeList');
var selected = tree.select();
var dataItem = tree.dataItem(selected);
if (dataItem.hasChildren === true) {
return;
}
var fileManagerGrid = $("#odinLite_sqlFileManager").data('kendoGrid');
//Prevent Duplicates
var gridData = fileManagerGrid.dataSource.data();
for(var i=0;i<gridData.length;i++){
if(dataItem.path === gridData[i].path){
via.kendoAlert("SQL Import","\""+dataItem.name + "\" has already been added to the list.");
return;
}
}
//Add to grid
fileManagerGrid.dataSource.add(dataItem);
}
//Get the ftp transfer files
function getFileManagerGrid(){
$("#odinLite_sqlFileManager").empty();
$("#odinLite_sqlFileManager").kendoGrid({
dataSource: {
data: [],
schema: {
model: {
fields: {
path: { field: "path"},
fileSize: { field: "fileSize",type: "number"},
lastModified: { field: "lastModified",type: "number"}
}
}
}
},
scrollable: true,
editable: false,
columns: [
{
//template: "<img src='#:imageUrl#'/> " + "#: name #",
template: "<img src='#:imageUrl#'/> " + "#: path #",
field: "path",
expandable: true,
title: "Selected Tables",
width: 550
},
{
template: function(dataItem) {
if(via.undef(dataItem.fileSize)){
return "";
}else{
return via.getReadableFileSizeString(dataItem.fileSize);
}
},
field: "fileSize",
title: "Size",
attributes: { style:"text-align:right" },
headerAttributes: { style:"text-align:center" },
width: 100
},
{
template: function(dataItem) {
if(via.undef(dataItem.lastModified)){
return "";
}else{
var d = new Date(dataItem.lastModified)
return kendo.toString(d,"g");
}
},
field: "lastModified",
title: "Last Modified",
headerAttributes: { style:"text-align:center" },
width: 180
},
{
title: "Delete",
width: "80px",
iconClass: "fa fa-trash",
command: {
text: " ",
iconClass: "fa fa-trash",
click: function(e){
e.preventDefault();
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
this.dataSource.remove(dataItem);
}
}
}
]
});
}
});
},
/**
* getSQLImportWindow
* This will import the sql tables
*/
getSQLQueryWindow: function(data){
kendo.ui.progress($("body"), true);//Wait Message
$.get("./html/sqlQueryWindow.html", function (sqlWindowTemplate) {
kendo.ui.progress($("body"), false);//Wait Message
$('#odinLite_sqlQueryWindow').remove();
$('body').append(sqlWindowTemplate);
//Make the window.
var sqlTablesWindow = $('#odinLite_sqlQueryWindow').kendoWindow({
title: "Select Tables to Query",
draggable: false,
resizable: false,
width: "950px",
height: "650px",
modal: true,
close: false,
actions: [
"Maximize",
"Close"
],
close: function () {
sqlTablesWindow = null;
$('#odinLite_sqlQueryWindow').remove();
}
}).data("kendoWindow");
sqlTablesWindow.center();
//Style the code editor
var editor = CodeMirror.fromTextArea(document.getElementById("manageData_sqlQuery_sqlArea"), {
mode: "text/x-sql",
indentWithTabs: true,
smartIndent: true,
lineWrapping: true,
lineNumbers: true,
matchBrackets: true,
autofocus: true,
extraKeys: {"Ctrl-Space": "autocomplete"}
});
editor.setSize("100%", 200);
// store it
$('#manageData_sqlQuery_sqlArea').data('CodeMirrorInstance', editor);
//Setup the treeview
var tableData = [];
$.each(data.tableColMap,function(t,c){
var obj = {text: "["+t+"]",items:[]};
for(var i in c){
obj.items.push({text:"["+c[i]+"]"});
}
tableData.push(obj);
});
var dataSource = new kendo.data.HierarchicalDataSource({
data: tableData
});
//Treeview init
$("#manageData_sqlColumnNames").kendoTreeView({
dataSource: dataSource
});
$("#manageData_sqlColumnNames li").bind('dblclick', function (e) {
var tree = $("#manageData_sqlColumnNames").data('kendoTreeView');
var selected = tree.select();
var dataItem = tree.dataItem(selected);
var cm = $('#manageData_sqlQuery_sqlArea').data('CodeMirrorInstance');
var doc = cm.getDoc();
doc.replaceRange(dataItem.text, {line: Infinity}); // adds a new line
});
//Add Button Events
$('#manageData_sqlQueryButton').click(function(){
var codeeditor = $('#manageData_sqlQuery_sqlArea').data('CodeMirrorInstance');
var sql = codeeditor.getValue();
if(via.undef(sql,true)){
via.kendoAlert("Define Query","Specify a query.");
return;
}
kendo.ui.progress($("#odinLite_sqlQueryWindow"), true);//Wait Message off
$('#manageData_dbResultGrid').empty();
$('#manageData_exportSqlQueryButton').hide();
$.post(odin.SERVLET_PATH,
{
action: 'odinLite.manageData.queryDatabaseTables',
schema: data.schema,
query: sql,
overrideUser: odinLite.OVERRIDE_USER
},
function (data, status) {
kendo.ui.progress($("#odinLite_sqlQueryWindow"), false);//Wait Message off
if (!via.undef(data, true) && data.success === false) {
via.debug("Failure running query:", data.message);
via.kendoAlert("Query Failure", data.message);
$('#manageData_dbResultGrid').html('<div class="well" style="color:red;margin-top:5px;">'+data.message+"</div>");
} else {
via.debug("Successful Query:", data);
if(via.undef(data.tableData)){
via.kendoAlert("Query Failure", "No data found.");
return;
}
odinTable.createTable("sqlQueryTable",data.tableData,"#manageData_dbResultGrid");
$('#sqlQueryTable').data('kendoGrid').setOptions({
groupable:false,
height:'99%',
width:'99%'
});
$('#manageData_dbResultGrid').css("padding","0");
$('#manageData_dbResultGrid').data("gridSql",sql);
$('#manageData_dbResultGrid').data("schema",data.schema);
$('#manageData_exportSqlQueryButton').show();
}
},
'json');
});
//Export Data Button
$('#manageData_exportSqlQueryButton').click(function(){
var sqlString = $('#manageData_dbResultGrid').data("gridSql");
var schema = $('#manageData_dbResultGrid').data("schema");
if(via.undef(sqlString,true)){
via.kendoAlert("Define Query","Specify a query.");
return;
}
kendo.ui.progress($("#odinLite_sqlQueryWindow"), true);//Wait Message off
$.post(odin.SERVLET_PATH,
{
action: 'odinLite.manageData.exportDatabaseQuery',
schema: schema,
query: sqlString,
overrideUser: odinLite.OVERRIDE_USER
},
function (data, status) {
kendo.ui.progress($("#odinLite_sqlQueryWindow"), false);//Wait Message off
if (!via.undef(data, true) && data.success === false) {
via.debug("Failure downloading file:", data.message);
via.kendoAlert("Download Failure", data.message);
} else {
via.debug("Successful Download:", data);
via.downloadFile(odin.SERVLET_PATH + "?action=admin.streamFile&reportName=" + encodeURIComponent(data.reportName));
}
},
'json');
});
});
},
/**
* getFileTreeGrid
* This will populate the file tree in the selector.
*/
getFileTreeGrid: function(selector){
var dirStructure = new kendo.data.TreeListDataSource({
transport: {
read: function(options) {
// make JSON request to server
$.ajax({
url: odin.SERVLET_PATH + "?action=odinLite.manageData.getFolderStructure",
data: {
entityDir:odinLite.ENTITY_DIR,
path:options.data.id
},
dataType: "json",
success: function(result) {
if(result.success === false){
if(!via.undef(result.message)) {
via.kendoAlert("Error retrieving files",result.message);
}else{
via.kendoAlert("Error retrieving files", "Please check your connection.");
}
}else {
// notify the data source that the request succeeded
for(var i in result){
if(via.undef(result[i].parentId)) {
result[i].parentId = null;
}
}
options.success(result);
}
},
error: function(result) {
// notify the data source that the request failed
options.error(result);
}
});
}
},
schema: {
model: {
id: "path",
hasChildren: "hasChildren",
//parentId: "parentId",
fields: {
name: { field: "name"},
fileSize: { field: "fileSize",type: "number"},
lastModified: { field: "lastModified",type: "number"}
}
}
}
});
$(selector).kendoTreeList({
dataSource: dirStructure,
selectable: true,
sortable:true,
columns: [
{
//template: "<img src='#:imageUrl#'/> " + "#: name #",
template: "<img src='#:imageUrl#'/> " + "#: name #",
field: "name",
expandable: true,
title: "Name",
width: 400
},
{
template: function(dataItem) {
if(via.undef(dataItem.fileSize)){
return "";
}else{
return via.getReadableFileSizeString(dataItem.fileSize);
}
},
field: "fileSize",
title: "Size",
attributes: { style:"text-align:right" },
headerAttributes: { style:"text-align:center" },
width: 150
},
{
template: function(dataItem) {
if(via.undef(dataItem.lastModified)){
return "";
}else{
var d = new Date(dataItem.lastModified)
return kendo.toString(d,"g");
}
},
field: "lastModified",
title: "Last Modified",
headerAttributes: { style:"text-align:center" }
}
]
});
},
/**
* deleteModelData
* This will delete the model data of the currently selected model
*/
deleteModelData: function () {
if (via.undef(odinLite_manageData.currentModel) || via.undef(odinLite_manageData.currentModel.value)) {
return;
}//No model selected.
via.confirm("Confirm Delete", "Are you sure you want to delete the model \"" + odinLite_manageData.currentModel.text + "\"? This action cannot be undone.", function () {
via.inputDialog("Confirm Delete", "This will <b>purge</b> all data for this model. Type the word \"<span style=\"color:red;\">delete</span>\" below to confirm.", function (val) {
if (!via.undef(val, true) && val === 'delete') {
kendo.ui.progress($("body"), true);//Wait Message on
$.post(odin.SERVLET_PATH,
{
action: 'odinLite.manageData.deleteModelDataItems',
modelId: odinLite_manageData.currentModel.value,
entityDir: odinLite.ENTITY_DIR,
overrideUser: odinLite.OVERRIDE_USER
},
function (data, status) {
kendo.ui.progress($("body"), false);//Wait Message off
if (!via.undef(data, true) && data.success === false) {
via.debug("Failure deleting model:", data.message);
via.kendoAlert("Delete Failure", data.message);
} else {
via.debug("Successful delete:", data);
odinLite_manageData.getItemTreeList();
odinLite_manageData.currentModel = null;
}
},
'json');
}
});
});
},
/**
* deleteTable
* This will delete the table currently displayed
*/
deleteTable: function () {
via.confirm("Confirm Delete", "Are you sure you want to delete the \"" + odinLite_manageData.currentDataItem + "\" table?", function () {
kendo.ui.progress($("body"), true);//Wait Message on
var portDir = null;
if (odinLite_manageData.tableIndexType === 3) {//We need port dir if type 3
portDir = [odinLite_manageData.parentVal];
}
$.post(odin.SERVLET_PATH,
{
action: 'odinLite.manageData.deleteTableFromCache',
modelId: odinLite_manageData.currentModel.value,
portDir: (portDir === null) ? portDir : JSON.stringify(portDir),
dataItems: JSON.stringify([odinLite_manageData.currentDataItem]),
entityDir: odinLite.ENTITY_DIR,
overrideUser: odinLite.OVERRIDE_USER
},
function (data, status) {
kendo.ui.progress($("body"), false);//Wait Message off
if (!via.undef(data, true) && data.success === false) {
via.debug("Failure deleting table:", data.message);
via.kendoAlert("Delete Failure", data.message);
} else {
via.debug("Successful delete:", data);
odinLite_manageData.getItemTreeList();
}
},
'json');
});
},
/**
* editSheet
* This will put the sheet in edit mode.
*/
editSheet: function () {
var sheetData = odinLite_fileFormat.getSpreadsheetDataFromTableSet(odinLite_manageData.currentTableData, true, false);
//Update the sheetName
if (!via.undef(odinLite_manageData.currentTableData.tableLabel, true)) {
sheetData.name = odinLite_manageData.currentTableData.tableLabel;
$('.manageData_tableSpreadhseetName').html(odinLite_manageData.currentTableData.tableLabel);
} else {
$('.manageData_tableSpreadhseetName').html("Table Preview");
}
if (!via.undef(sheetData.rows) && !via.undef(sheetData.rows[0])) {
console.log(sheetData);
sheetData.rows.push({
cells:[{},{},{}]
});
//First row is not editable
for (var i = 0; i < sheetData.rows[0].cells.length; i++) {
sheetData.rows[0].cells[i].enable = false;
if (!via.undef(odinLite_manageData.currentTableData.requiredColumns, true)) {
var isRequired = false;
for (var k = 0; k < odinLite_manageData.currentTableData.requiredColumns.length; k++) {
if (odinLite_manageData.currentTableData.requiredColumns[k] === sheetData.rows[0].cells[i].value) {
isRequired = true;
break;
}
}
//Loop through all the rows and shut off required columns
if (isRequired) {
for (var j = 1; j < sheetData.rows.length-1; j++) {
sheetData.rows[j].cells[i].enable = false;
sheetData.rows[j].cells[i].color = "#888888";
}
}
}
}
}
//Insert the sheet preview.
if (!via.undef($("#manageData_tableSpreadhseet").data('kendoSpreadsheet'))) {
$("#manageData_tableSpreadhseet").data('kendoSpreadsheet').destroy();
}
$(".manageData_tableSpreadhseetContainer").show();
$("#manageData_tableSpreadhseet").empty();
$("#manageData_tableSpreadhseet").kendoSpreadsheet({
//height: '200px',
headerHeight: 20,
//headerWidth: 0,
toolbar: false,
sheetsbar: false,
rows: null,
columns: null,
sheets: [sheetData]
});
$("#manageData_tableSpreadhseet .k-spreadsheet-sheets-bar-add").hide();
$("#manageData_tableSpreadhseet .k-link").prop("disabled", true);
$('#manageData_editModeLabel').show();
},
/**
* editSheet
* This will save the edits to the current sheet
*/
saveSheetEdits: function () {
//kendo.ui.progress($("body"), true);//Wait Message
var ts = odinLite_manageData.currentTableData;
$("#manageData_tableSpreadhseet").data('kendoSpreadsheet').refresh();
var json = $("#manageData_tableSpreadhseet").data('kendoSpreadsheet').toJSON();
//Check data
if (via.undef(json.sheets) || json.sheets.length == 0 || via.undef(json.sheets[0].rows)) {
via.kendoAlert("Save Error", "Invalid sheet data.");
return;
}
if (json.sheets[0].rows.length == 0) {
via.kendoAlert("Save Error", "Zero rows contained in data.");
return;
}
//Get the idx for the required columns. Those should not be set.
var requiredMap = {};
var headerRow = json.sheets[0].rows[0].cells;
for (var k = 0; k < odinLite_manageData.currentTableData.requiredColumns.length; k++) {
for (var c = 0; c < headerRow.length; c++) {
if (headerRow[c].value === odinLite_manageData.currentTableData.requiredColumns[k]) {
requiredMap[c] = c;
break;
}
}
}
//Set the data
for (var r = 1; r < (ts.data.length+1); r++) {//Don't add last row.
var cells = json.sheets[0].rows[r].cells;
var rowIdx = r - 1;
for (var c = 0; c < cells.length; c++) {
var header = json.sheets[0].rows[0].cells[c].value;
var value = cells[c].value;
if (via.undef(requiredMap[c])) {
ts.data[rowIdx][c] = value;
}
}
}
//Check to see if we should add a new row.
if(json.sheets[0].rows.length > (ts.data.length+1)) {
console.log('here');
var lastRow = json.sheets[0].rows[json.sheets[0].rows.length - 1].cells;
var isValid = true;
for(var i in requiredMap){
var idx = requiredMap[i];
if(via.undef(lastRow[idx],true)){
isValid = false;
}
}
if(isValid === true) {
var row = [];
for(var j in lastRow){
row.push(lastRow[j].value+"");
}
ts.data.push(row);
}
}
//Get the variables
var dataItem = odinLite_manageData.currentDataItem + "";
odinLite_manageData.currentDataItem = null;//Reset the data item so it updates.
var entityDir = odinLite.ENTITY_DIR;
var modelId = odinLite_manageData.currentModel.value;
//Make the call to update
via.debug("Saving JSON TS:", ts);
console.log("Saving JSON TS:", ts);
$.post(odin.SERVLET_PATH,
{
action: 'odinLite.manageData.persistSheetEditToCache',
modelId: modelId,
entityDir: entityDir,
dataItem: dataItem,
tsJson: JSON.stringify(ts),
overrideUser: odinLite.OVERRIDE_USER
},
function (data, status) {
kendo.ui.progress($("body"), false);//Wait Message off
if (!via.undef(data, true) && data.success === false) {
via.debug("Failure getting data item:", data.message);
via.kendoAlert("Get Data Item Failure", data.message);
} else {
via.debug("Successful getting data item:", data);
$('#viewPanel').hide();
//Review the upload
odinLite_modelMapping.reviewPersistErrors(data, function () {
$('#modelMappingErrorsPanel').hide();
$('#viewPanel').show();
odinLite_manageData.getDataItemTable(dataItem);
});
}
},
'json');
},
/**
* cancelSheetEdits
* Cancels the editing without saving
*/
cancelSheetEdits: function () {
var dataItem = odinLite_manageData.currentDataItem + "";
odinLite_manageData.currentDataItem = null;//Reset the data item so it updates.
odinLite_manageData.getDataItemTable(dataItem);
}
};
|
d5bb6571a49401611a376751ee189d15a0fad81d
|
[
"JavaScript"
] | 10
|
JavaScript
|
opturo/liquidReporting
|
1772b7a63371d94cc0af8285107bd78d9a8530ce
|
c84ca9cc5125d86e3598661be080a1733e7d8783
|
refs/heads/master
|
<file_sep>package com.hjx.pzwdshxzt.controller;
import com.hjx.pzwdshxzt.constants.Constants;
import com.hjx.pzwdshxzt.model.Lottery.Lottery;
import com.hjx.pzwdshxzt.model.R;
import com.hjx.pzwdshxzt.service.CoreService;
import com.hjx.pzwdshxzt.service.InitService;
import com.hjx.pzwdshxzt.service.LotteryService;
import com.hjx.pzwdshxzt.util.SignUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author hjx
*/
@RestController
@RequestMapping("" )
public class CoreController {
@Autowired
private CoreService coreService;
private static Logger log = LoggerFactory.getLogger(CoreController.class);
@Autowired
private LotteryService lotteryService;
public static final String PATTERN_NUM_STR = "[0-9]*";
/**
* 验证是否来自微信服务器的消息
*/
@RequestMapping(value = "/wx", method = RequestMethod.GET)
public String checkSignature(@RequestParam(name = "signature", required = false) String signature,
@RequestParam(name = "nonce", required = false) String nonce,
@RequestParam(name = "timestamp", required = false) String timestamp,
@RequestParam(name = "echostr", required = false) String echostr) {
/**
* 通过检验signature对请求进行校验,若校验成功则原样返回echostr,表示接入成功,否则接入失败
*/
if (SignUtil.checkSignature(signature, timestamp, nonce)) {
log.info("接入成功" );
return echostr;
}
log.error("接入失败" );
return "";
}
/**
* 抽奖结果
*/
@RequestMapping(value = "/insertLottery", method = {RequestMethod.GET, RequestMethod.POST})
public R getResult(@RequestParam(name = "title", required = false) String title,
@RequestParam(name = "rule", required = false) String rule,
@RequestParam(name = "token", required = false) String token,
@RequestParam(name = "time", required = false) String time,
@RequestParam(name = "results", required = false) String results) {
if (!InitService.tokenList.containsKey(token)) {
InitService.tokenList.put(token, time);
}
Lottery lottery = new Lottery();
lottery.setResults(results);
lottery.setTitle(title);
lottery.setRule(rule);
lottery.setToken(token);
lottery.setTime(time);
lottery.setCreateTime(new Date().toString());
lotteryService.insertLottery(lottery);
return R.ok();
}
/**
* 验证抽奖结果
*/
@RequestMapping(value = "/check", method = {RequestMethod.GET, RequestMethod.POST})
public R checkResult(@RequestParam(name = "token", required = false) String token,
@RequestParam(name = "num", required = false) String num) {
if (!isNumeric(num) || "".equals(num) || num == null) {
return R.error(522, "请输入数字." );
}
if (token == null && "".equals(token)) {
return R.error(520, "系统异常,请联系Huangjinxing" );
}
if (num == null && "".equals(num)) {
return R.error(521, "请输入你的号码" );
}
String s = lotteryService.checkResult(token, num);
if (s != null && !"".equals(s)) {
return R.ok().put("data", s);
}
return R.ok();
}
/**
* 查询抽奖场次
*/
@RequestMapping(value = "/queryTokenList", method = {RequestMethod.GET, RequestMethod.POST})
public R checkResult() {
if (InitService.tokenList.isEmpty()) {
HashMap<String, String> s = lotteryService.queryTokenList();
if (s != null && s.size() > 0) {
return R.ok().put("data", s);
}
return R.ok();
}
return R.ok().put("data", InitService.tokenList);
}
/**
* 调用核心业务类接收消息、处理消息跟推送消息
*/
@RequestMapping(value = "/wx", method = RequestMethod.POST)
public String post(HttpServletRequest req) throws Exception {
String respMessage = coreService.processRequest(req);
return respMessage;
}
public static Map<String, String> setAppcode() {
Map<String, String> headers = new HashMap<>();
headers.put("Authorization", "APPCODE " + Constants.APPCODE);
return headers;
}
/**
* 利用正则表达式判断字符串是否是数字
*
* @param str
* @return
*/
public boolean isNumeric(String str) {
Pattern pattern = Pattern.compile(PATTERN_NUM_STR);
Matcher isNum = pattern.matcher(str);
if (!isNum.matches()) {
return false;
}
return true;
}
}
<file_sep>package com.hjx.pzwdshxzt.util;
import static org.junit.Assert.*;
public class SerialzerUtilTest {
}<file_sep>package com.hjx.pzwdshxzt.model.price;
/**
* Description
*
* @Author : huangjinxing
* @Email : <EMAIL>
* @Date : 2018/11/6 10:53
* @Version :
*/
public class AlimamaPid {
private String tkkey;
private String mmpid;
private String adzoneid;
private String opentype;
private String isvcode;
public String getTkkey() {
return tkkey;
}
public void setTkkey(String tkkey) {
this.tkkey = tkkey;
}
public String getMmpid() {
return mmpid;
}
public void setMmpid(String mmpid) {
this.mmpid = mmpid;
}
public String getAdzoneid() {
return adzoneid;
}
public void setAdzoneid(String adzoneid) {
this.adzoneid = adzoneid;
}
public String getOpentype() {
return opentype;
}
public void setOpentype(String opentype) {
this.opentype = opentype;
}
public String getIsvcode() {
return isvcode;
}
public void setIsvcode(String isvcode) {
this.isvcode = isvcode;
}
}
<file_sep>package com.hjx.pzwdshxzt.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
/**
* @author hjx
*/
@Component
public class CustomConfig {
private static Logger log = LoggerFactory.getLogger(CustomConfig.class);
private volatile static CustomConfig instance = null;
public static CustomConfig getInstance() {
if (null == instance) {
synchronized (CustomConfig.class) {
if (null == instance) {
instance = (CustomConfig) SpringHelper.getBean("customConfig" );
}
}
}
return instance;
}
}
<file_sep>package com.hjx.pzwdshxzt.service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import java.util.*;
/**
* @author szzt
* 系统启动时加载
*/
@Component
public class InitService implements CommandLineRunner {
private static final Logger logger = LoggerFactory.getLogger(InitService.class);
public static final Map<String, Object> maps = new HashMap<>();
public static final Map<String, Object> results = new HashMap<>();
public static final Map<String, Object> tokenList = new HashMap<>();
@Autowired
private LotteryService lotteryService;
@Override
public void run(String... args) {
logger.info("开始加载启动项......" );
maps.put("cookie", "99D7CCBE579EEA4C4CA68C571EB89E1E" );
HashMap<String, String> lists = lotteryService.queryTokenList();
if (lists != null && lists.size() > 0) {
tokenList.putAll(lists);
}
logger.info("加载启动项结束......" );
}
}
<file_sep>package com.hjx.pzwdshxzt.model;
/**
* Description
* 取消关注表
*
* @Author : huangjinxing
* @Email : <EMAIL>
* @Date : 2018/8/7 12:54
* @Version : 0.0.1
*/
public class UnSubscribe {
private String openId;
public String getOpenId() {
return openId;
}
public void setOpenId(String openId) {
this.openId = openId;
}
}
<file_sep>package com.hjx.pzwdshxzt.service;
import com.hjx.pzwdshxzt.model.Lottery.Lottery;
import java.util.HashMap;
import java.util.List;
/**
* Description
* 抽奖
*
* @Author : huangjinxing
* @Email : <EMAIL>
* @Date : 2018/11/9 10:05
* @Version :
*/
public interface LotteryService {
/**
* 插入lottery
*
* @param lottery
*/
void insertLottery(Lottery lottery);
/**
* 查询中奖信息
*
* @param token
*/
String checkResult(String token, String num);
/**
* 查询所有Token
*/
HashMap<String, String> queryTokenList();
}
<file_sep>package com.hjx.pzwdshxzt.model.price;
/**
* Description
* 查询接口返回
*
* @Author : huangjinxing
* @Email : <EMAIL>
* @Date : 2018/11/6 10:20
* @Version :
*/
public class PriceResult {
private Integer ok;
private String msg;
private Single single;
public Integer getOk() {
return ok;
}
public void setOk(Integer ok) {
this.ok = ok;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Single getSingle() {
return single;
}
public void setSingle(Single single) {
this.single = single;
}
@Override
public String toString() {
return "PriceResult{" +
"ok=" + ok +
", msg='" + msg + '\'' +
", single=" + single +
'}';
}
}
<file_sep>package com.hjx.pzwdshxzt.service;
import com.hjx.pzwdshxzt.model.UnSubscribe;
import com.hjx.pzwdshxzt.model.User;
/**
* Description
* 用户信息
*
* @Author : huangjinxing
* @Email : <EMAIL>
* @Date : 2018/8/6 16:09
* @Version : 0.0.1
*/
public interface UserService {
/**
* 新增用户
*
* @param user
*/
void insertUser(User user);
/**
* 校验是否存在openId
*
* @param openId
* @return
*/
User selectUser(String openId);
/**
* 修改深圳通卡号
*
* @param user
*/
void updateNum(User user);
/**
* 修改倒计时时间
*
* @param user
*/
void updateEndTime(User user);
/**
* 新增取消关注用户
*/
void addUnSubscribe(String openId);
/**
* 删除取消关注用户
*/
void deleteUnSubscribe(String openId);
/**
* 删除取消关注用户
*/
UnSubscribe selectUnSubscribe(String openId);
/**
* 修改地理位置
*/
void updateLocal(User user);
/**
* 修改地理位置
*/
void updateUrl(User user);
}
<file_sep>package com.hjx.pzwdshxzt.util;
import java.io.*;
/**
* @author <EMAIL> 整理
* @version 1.0
* @desc 将java可以序列化的类序列化到本地文件。
* @see 如果你想知道那个类可以序列化,那个类不可用序列化,在控制台输入:serialver -show
*/
public class SerialzerUtil {
/**
* @param filePath 文件路径
* @return 读取的对象
* @throws FileNotFoundException
* @throws IOException
* @throws ClassNotFoundException
* @DESCRIBE 读取对象从一个序列化的文件里面
*/
public static Object readObject(String filePath) throws FileNotFoundException, IOException, ClassNotFoundException {
Object o = null;
FileInputStream fis = null;
ObjectInputStream ois = null;
try {
fis = new FileInputStream(filePath);
ois = new ObjectInputStream(fis);
o = ois.readObject();
} catch (FileNotFoundException e) {
System.out.println("文件未找到:" + filePath);
e.printStackTrace();
throw e;
} catch (IOException e) {
System.out.println("文件读取IO异常:" + filePath);
e.printStackTrace();
throw e;
} catch (ClassNotFoundException e) {
System.out.println("类反序列化异常:" + filePath);
e.printStackTrace();
throw e;
} finally {
if (ois != null){
ois.close();
}
if (fis != null){
fis.close();
}
}
return o;
}
/**
* @param obj 写入的对象
* @param filePath 文件路径
* @throws FileNotFoundException
* @throws IOException
* @DESCRIBE 写入序列化的对象到文件
*/
public static void WriteObject(Object obj, String filePath) throws FileNotFoundException, IOException {
FileOutputStream fis = null;
ObjectOutputStream ois = null;
try {
fis = new FileOutputStream(filePath);
ois = new ObjectOutputStream(fis);
ois.writeObject(obj);
ois.flush();
} catch (FileNotFoundException e) {
System.out.println("文件未找到:" + filePath);
e.printStackTrace();
throw e;
} catch (IOException e) {
System.out.println("文件读取IO异常:" + filePath);
e.printStackTrace();
throw e;
} finally {
if (ois != null){
ois.close();
}
if (fis != null){
fis.close();
}
}
}
/**
* 序列化对象为字符串
*
* @param obj
* @return
*/
public static String objectToString(Object obj) {
String serStr = "";
try {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(
byteArrayOutputStream);
objectOutputStream.writeObject(obj);
serStr = byteArrayOutputStream.toString("ISO-8859-1" );
serStr = java.net.URLEncoder.encode(serStr, "UTF-8" );
objectOutputStream.close();
byteArrayOutputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
return serStr;
}
/**
* 反序列化字符串为对象
*
* @param serStr
* @return
*/
public static Object stringToObject(String serStr) {
String redStr = "";
Object obj = null;
try {
redStr = java.net.URLDecoder.decode(serStr, "UTF-8" );
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(
redStr.getBytes("ISO-8859-1" ));
ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
obj = objectInputStream.readObject();
objectInputStream.close();
byteArrayInputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
return obj;
}
}<file_sep>package com.hjx.pzwdshxzt.model.price;
import java.util.List;
/**
* Description
*
* @Author : huangjinxing
* @Email : <EMAIL>
* @Date : 2018/11/6 10:42
* @Version :
*/
public class Single {
private String id;
private String title;
private String smallpic;
private String bigpic;
private String jiagequshi;
private Integer lowerPrice;
private String JGQSDIV;
private String insertdiv;
private String lowerDate;
private List<Shop> bj;
private String qushi;
private String morepriceurl;
private String zk_count;
private String zk_scname;
private Integer zk_scid;
private String zk_link;
private String spbh;
private String MobileUrl;
private String MobileErweima;
private String WeixinUrl;
private String WeixinErweima;
private String soujiwzzx;
private String soujiwzja;
private boolean kucunshow;
private String bjfrom;
private String shoucang_url;
private String url;
private String gotourl;
private String spmoney;
private String fromType;
private String slogtime;
private String baichuan_gylink;
private String baichuan_yslink;
private String baichuan_itemid;
private AlimamaPid alimamaPID;
private String changPriceRemark;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getSmallpic() {
return smallpic;
}
public void setSmallpic(String smallpic) {
this.smallpic = smallpic;
}
public String getBigpic() {
return bigpic;
}
public void setBigpic(String bigpic) {
this.bigpic = bigpic;
}
public String getJiagequshi() {
return jiagequshi;
}
public void setJiagequshi(String jiagequshi) {
this.jiagequshi = jiagequshi;
}
public Integer getLowerPrice() {
return lowerPrice;
}
public void setLowerPrice(Integer lowerPrice) {
this.lowerPrice = lowerPrice;
}
public String getJGQSDIV() {
return JGQSDIV;
}
public void setJGQSDIV(String JGQSDIV) {
this.JGQSDIV = JGQSDIV;
}
public String getInsertdiv() {
return insertdiv;
}
public void setInsertdiv(String insertdiv) {
this.insertdiv = insertdiv;
}
public String getLowerDate() {
return lowerDate;
}
public void setLowerDate(String lowerDate) {
this.lowerDate = lowerDate;
}
public List<Shop> getBj() {
return bj;
}
public void setBj(List<Shop> bj) {
this.bj = bj;
}
public String getQushi() {
return qushi;
}
public void setQushi(String qushi) {
this.qushi = qushi;
}
public String getMorepriceurl() {
return morepriceurl;
}
public void setMorepriceurl(String morepriceurl) {
this.morepriceurl = morepriceurl;
}
public String getZk_count() {
return zk_count;
}
public void setZk_count(String zk_count) {
this.zk_count = zk_count;
}
public String getZk_scname() {
return zk_scname;
}
public void setZk_scname(String zk_scname) {
this.zk_scname = zk_scname;
}
public Integer getZk_scid() {
return zk_scid;
}
public void setZk_scid(Integer zk_scid) {
this.zk_scid = zk_scid;
}
public String getZk_link() {
return zk_link;
}
public void setZk_link(String zk_link) {
this.zk_link = zk_link;
}
public String getSpbh() {
return spbh;
}
public void setSpbh(String spbh) {
this.spbh = spbh;
}
public String getMobileUrl() {
return MobileUrl;
}
public void setMobileUrl(String mobileUrl) {
MobileUrl = mobileUrl;
}
public String getMobileErweima() {
return MobileErweima;
}
public void setMobileErweima(String mobileErweima) {
MobileErweima = mobileErweima;
}
public String getWeixinUrl() {
return WeixinUrl;
}
public void setWeixinUrl(String weixinUrl) {
WeixinUrl = weixinUrl;
}
public String getWeixinErweima() {
return WeixinErweima;
}
public void setWeixinErweima(String weixinErweima) {
WeixinErweima = weixinErweima;
}
public String getSoujiwzzx() {
return soujiwzzx;
}
public void setSoujiwzzx(String soujiwzzx) {
this.soujiwzzx = soujiwzzx;
}
public String getSoujiwzja() {
return soujiwzja;
}
public void setSoujiwzja(String soujiwzja) {
this.soujiwzja = soujiwzja;
}
public boolean isKucunshow() {
return kucunshow;
}
public void setKucunshow(boolean kucunshow) {
this.kucunshow = kucunshow;
}
public String getBjfrom() {
return bjfrom;
}
public void setBjfrom(String bjfrom) {
this.bjfrom = bjfrom;
}
public String getShoucang_url() {
return shoucang_url;
}
public void setShoucang_url(String shoucang_url) {
this.shoucang_url = shoucang_url;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getGotourl() {
return gotourl;
}
public void setGotourl(String gotourl) {
this.gotourl = gotourl;
}
public String getSpmoney() {
return spmoney;
}
public void setSpmoney(String spmoney) {
this.spmoney = spmoney;
}
public String getFromType() {
return fromType;
}
public void setFromType(String fromType) {
this.fromType = fromType;
}
public String getSlogtime() {
return slogtime;
}
public void setSlogtime(String slogtime) {
this.slogtime = slogtime;
}
public String getBaichuan_gylink() {
return baichuan_gylink;
}
public void setBaichuan_gylink(String baichuan_gylink) {
this.baichuan_gylink = baichuan_gylink;
}
public String getBaichuan_yslink() {
return baichuan_yslink;
}
public void setBaichuan_yslink(String baichuan_yslink) {
this.baichuan_yslink = baichuan_yslink;
}
public String getBaichuan_itemid() {
return baichuan_itemid;
}
public void setBaichuan_itemid(String baichuan_itemid) {
this.baichuan_itemid = baichuan_itemid;
}
public AlimamaPid getAlimamaPID() {
return alimamaPID;
}
public void setAlimamaPID(AlimamaPid alimamaPID) {
this.alimamaPID = alimamaPID;
}
public String getChangPriceRemark() {
return changPriceRemark;
}
public void setChangPriceRemark(String changPriceRemark) {
this.changPriceRemark = changPriceRemark;
}
}
|
d64b534b1a09a404b595384bc4187cf7a64b3071
|
[
"Java"
] | 11
|
Java
|
pzwdshxzt/weixinpublic
|
6ba01b519f1db12e47a579acbb090dc64babc1d8
|
447580f0dab5d4f23592118dd47fc1f8e6070304
|
refs/heads/main
|
<file_sep>const { ipcRenderer } = require("electron");
const fetch = require("node-fetch");
const FormData = require("form-data");
const categoryUl = document.getElementById("category_item");
const foodList = document.getElementById("foods");
const foodByAllCategory = document.getElementById("allCategory");
const cartData = document.getElementById("items_cart");
const cartTable = document.getElementById("itemsOnCart");
const cartImage = document.getElementById("myImg");
const itemsCart = document.querySelector("#items_cart");
//different tabs
function pos(evt, posSytem) {
var i, tabcontent, tablinks;
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}
tablinks = document.getElementsByClassName("tablinks");
for (i = 0; i < tablinks.length; i++) {
tablinks[i].className = tablinks[i].className.replace(" active", "");
}
document.getElementById(posSytem).style.display = "block";
evt.currentTarget.className += " active";
}
const form = new FormData();
form.append("android", 123);
fetch("https://soft14.bdtask.com/bhojonapp/app/categorylist", {
method: "POST",
body: form,
})
.then((response) => response.json())
.then((data) => {
console.log(data);
})
.catch((error) => {
console.error("Error:", error);
});
function removeCartItem(id) {
let fID = id;
let trs = [...document.querySelectorAll("#items_cart tr")];
console.log("trs type ", typeof trs);
trs.map((tr) => {
if (tr.id == fID) {
tr.remove();
}
});
}
function updatePriceOnCart(e) {
var quantity = e.target.value;
var price = e.target.parentElement.previousElementSibling.textContent;
var subTotal = quantity * price;
var total = e.target.parentElement.nextElementSibling;
total.textContent = subTotal;
}
//Foods on cart
ipcRenderer.on("ItemsOnBasketSent", (e, items) => {
cartImage.style.display = "none";
cartTable.style.display = "block";
let data = items;
data.map((x) => {
var addOnItems = x.addonItems;
var tr = document.createElement("tr");
tr.id = x.foodVarients[0].foodId;
var itemName = document.createElement("td");
itemName.textContent = x.foodVarients[0].itemName;
var varient = document.createElement("td");
varient.textContent = x.foodVarients[0].varient;
var price = document.createElement("td");
price.textContent = x.foodVarients[0].foodPrice;
var qty = document.createElement("td");
var inpt = document.createElement("input");
inpt.id = "quantity_input";
inpt.classList.add("cart-quantity-input");
inpt.type = "number";
inpt.value = x.foodVarients[0].quantity;
inpt.onchange = () => calculatePriceQty();
inpt.style.width = "5em";
inpt.style.border = "1px solid black";
qty.appendChild(inpt);
var total = document.createElement("td");
total.textContent = x.foodVarients[0].foodTotal;
var remove = document.createElement("td");
var input = document.createElement("input");
input.id = "remove_cart_item";
input.classList.add("cart-quantity");
input.type = "button";
input.value = "X";
input.onclick = () => removeCartItem(x.foodVarients[0].foodId);
remove.appendChild(input);
tr.append(itemName, varient, price, qty, total, remove);
cartData.appendChild(tr);
var trV;
addOnItems.map((addOnItem) => {
trV = document.createElement("tr");
trV.id = addOnItem.foodId;
var addOnName = document.createElement("td");
addOnName.textContent = addOnItem.addOnName;
var emp = document.createElement("td");
emp.textContent = "";
var priceVarient = document.createElement("td");
priceVarient.textContent = addOnItem.price;
var qtyV = document.createElement("td");
qtyV.textContent = addOnItem.addsOnquantity;
var totalV = document.createElement("td");
totalV.textContent = addOnItem.addOntotal;
var removeV = document.createElement("td");
removeV.textContent = "";
trV.append(addOnName, emp, priceVarient, qtyV, totalV, removeV);
cartData.append(trV);
});
});
const allTrFromCart = [...itemsCart.querySelectorAll("tr")];
allTrFromCart.map((item) => {
let rowID = item.id;
console.log(rowID);
});
});
function getFoodId(id) {
ipcRenderer.send("foodIdSent", id);
}
//sending category id to fetch foods by specific category
function getCategoryId(id) {
ipcRenderer.send("categoryId", id);
}
//creating dynamic category on pos page
document.addEventListener("DOMContentLoaded", () => {
ipcRenderer.send("categoryNamesLoaded");
});
ipcRenderer.on("categoryNamesReplySent", function (event, results) {
results.forEach(function (result) {
let li = document.createElement("li");
let a = document.createElement("a");
a.textContent = result.name;
li.appendChild(a);
li.onclick = () => getCategoryId(result.id);
categoryUl.appendChild(li);
});
});
//end of dynamic category on pos page
// displaying food by category
ipcRenderer.on("foodsByCategoryReplySent", (evt, foods) => {
foodList.innerHTML = "";
var div = "";
foods.forEach((food) => {
div += `
<div class=" col-lg-3 col-sm-4 col-6">
<div class="card">
<img src="${food.product_image}" height="100" width="206" class="card-img-top">
<div class="food_items" style="text-align: center;"><p><a href="#" style="text-decoration:none; color:black;" id=${food.id} onclick = {getFoodId(${food.id})}>
${food.product_name}
</a></p>
</div>
</div>
</div>`;
});
foodList.innerHTML += div;
});
// displaying food by all category
foodByAllCategory.addEventListener("click", () => {
ipcRenderer.send("foodByALlCategory");
});
ipcRenderer.on("foodsByAllCategoryReplySent", (evt, foods) => {
foodList.innerHTML = "";
var div = "";
foods.forEach((food) => {
div += `
<div class="col-lg-3 col-sm-4 col-6">
<div class="card">
<img src="${food.product_image}" height="100" width="206" class="card-img-top">
<div class="food_items" style="text-align: center;"><p><a href="#" style="text-decoration:none; color:black;" id=${food.id} onclick = {getFoodId(${food.id})}>
${food.product_name}
</a></p>
</div>
</div>
</div>`;
});
foodList.innerHTML += div;
});
// end of displaying food by all category
// displaying the foods when the page loaded
document.addEventListener("DOMContentLoaded", () => {
ipcRenderer.send("foodOnPageLoaded");
});
ipcRenderer.on("foodOnPageLoadedReplySent", (evt, foods) => {
foodList.innerHTML = "";
var div = "";
foods.forEach((food) => {
div += `
<div class=" col-lg-3 col-sm-4 col-6" >
<div class="card">
<img src="${food.product_image}" height="100" width="206" class="card-img-top">
<div class="food_items" style="text-align: center;"><p><a href="#" style="text-decoration:none; color:black;" id=${food.id} onclick = {getFoodId(${food.id})}>
${food.product_name}
</a></p>
</div>
</div>
</div>`;
});
foodList.innerHTML += div;
});
|
e6c340a44f26c9cf8f22d077cfcb0809c0d932e1
|
[
"JavaScript"
] | 1
|
JavaScript
|
Hawa-Akter/Bhojonjune19
|
8fa797b26497fe40b2bd3d9c6d51b82e347cae13
|
e6d52e9e5d9e567fa6c8973e83d49bb11540aa62
|
refs/heads/master
|
<file_sep>const lowerSlider = document.querySelector("#lower"),
upperSlider = document.querySelector("#upper");
let filters = {
price: {
lowerPriceVal: parseFloat(lowerSlider.value).toFixed(2),
upperPriceVal: parseFloat(upperSlider.value).toFixed(2),
},
};
const products = [
{
reviewsCount: 4,
ratingsCount: 4,
imgs: [
"diamond-silver-ring.png",
"diamond-silver-ring.png",
"diamond-silver-ring.png",
],
name: "<NAME>",
price: 589.99,
},
{
reviewsCount: 4,
ratingsCount: 4,
imgs: ["necklace (2).png", "necklace (2).png", "necklace (2).png"],
name: "Necklace",
price: 589.99,
},
{
reviewsCount: 4,
ratingsCount: 4,
imgs: [
"diamond-bracelet.png",
"diamond-bracelet.png",
"diamond-bracelet.png",
],
name: "Bracelet",
price: 589.99,
},
{
reviewsCount: 4,
ratingsCount: 4,
imgs: ["diamond-ring.png", "diamond-ring.png", "diamond-ring.png"],
name: "Ring",
price: 589.99,
},
{
reviewsCount: 4,
ratingsCount: 4,
imgs: [
"diamond-silver-ring.png",
"diamond-silver-ring.png",
"diamond-silver-ring.png",
],
name: "<NAME>",
price: 589.99,
},
{
reviewsCount: 4,
ratingsCount: 4,
imgs: ["necklace (2).png", "necklace (2).png", "necklace (2).png"],
name: "Necklace",
price: 589.99,
},
{
reviewsCount: 4,
ratingsCount: 4,
imgs: [
"diamond-bracelet.png",
"diamond-bracelet.png",
"diamond-bracelet.png",
],
name: "Bracelet",
price: 589.99,
},
{
reviewsCount: 4,
ratingsCount: 4,
imgs: ["diamond-ring.png", "diamond-ring.png", "diamond-ring.png"],
name: "Ring",
price: 589.99,
},
{
reviewsCount: 4,
ratingsCount: 4,
imgs: [
"diamond-silver-ring.png",
"diamond-silver-ring.png",
"diamond-silver-ring.png",
],
name: "<NAME>",
price: 589.99,
},
{
reviewsCount: 4,
ratingsCount: 4,
imgs: ["necklace (2).png", "necklace (2).png", "necklace (2).png"],
name: "Necklace",
price: 589.99,
},
{
reviewsCount: 4,
ratingsCount: 4,
imgs: [
"diamond-bracelet.png",
"diamond-bracelet.png",
"diamond-bracelet.png",
],
name: "Bracelet",
price: 589.99,
},
{
reviewsCount: 4,
ratingsCount: 4,
imgs: ["diamond-ring.png", "diamond-ring.png", "diamond-ring.png"],
name: "Ring",
price: 589.99,
},
{
reviewsCount: 4,
ratingsCount: 4,
imgs: [
"diamond-silver-ring.png",
"diamond-silver-ring.png",
"diamond-silver-ring.png",
],
name: "<NAME>",
price: 589.99,
},
{
reviewsCount: 4,
ratingsCount: 4,
imgs: ["necklace (2).png", "necklace (2).png", "necklace (2).png"],
name: "Necklace",
price: 589.99,
},
{
reviewsCount: 4,
ratingsCount: 4,
imgs: [
"diamond-bracelet.png",
"diamond-bracelet.png",
"diamond-bracelet.png",
],
name: "Bracelet",
price: 589.99,
},
{
reviewsCount: 4,
ratingsCount: 4,
imgs: ["diamond-ring.png", "diamond-ring.png", "diamond-ring.png"],
name: "Ring",
price: 589.99,
},
{
reviewsCount: 4,
ratingsCount: 4,
imgs: [
"diamond-silver-ring.png",
"diamond-silver-ring.png",
"diamond-silver-ring.png",
],
name: "<NAME>",
price: 589.99,
},
{
reviewsCount: 4,
ratingsCount: 4,
imgs: ["necklace (2).png", "necklace (2).png", "necklace (2).png"],
name: "Necklace",
price: 589.99,
},
{
reviewsCount: 4,
ratingsCount: 4,
imgs: [
"diamond-bracelet.png",
"diamond-bracelet.png",
"diamond-bracelet.png",
],
name: "Bracelet",
price: 589.99,
},
{
reviewsCount: 4,
ratingsCount: 4,
imgs: ["diamond-ring.png", "diamond-ring.png", "diamond-ring.png"],
name: "Ring",
price: 589.99,
},
{
reviewsCount: 4,
ratingsCount: 4,
imgs: [
"diamond-silver-ring.png",
"diamond-silver-ring.png",
"diamond-silver-ring.png",
],
name: "<NAME>",
price: 589.99,
},
{
reviewsCount: 4,
ratingsCount: 4,
imgs: ["necklace (2).png", "necklace (2).png", "necklace (2).png"],
name: "Necklace",
price: 589.99,
},
{
reviewsCount: 4,
ratingsCount: 4,
imgs: [
"diamond-bracelet.png",
"diamond-bracelet.png",
"diamond-bracelet.png",
],
name: "Bracelet",
price: 589.99,
},
{
reviewsCount: 4,
ratingsCount: 4,
imgs: ["diamond-ring.png", "diamond-ring.png", "diamond-ring.png"],
name: "Ring",
price: 589.99,
},
{
reviewsCount: 4,
ratingsCount: 4,
imgs: [
"diamond-silver-ring.png",
"diamond-silver-ring.png",
"diamond-silver-ring.png",
],
name: "<NAME>",
price: 589.99,
},
{
reviewsCount: 4,
ratingsCount: 4,
imgs: ["necklace (2).png", "necklace (2).png", "necklace (2).png"],
name: "Necklace",
price: 589.99,
},
{
reviewsCount: 4,
ratingsCount: 4,
imgs: [
"diamond-bracelet.png",
"diamond-bracelet.png",
"diamond-bracelet.png",
],
name: "Bracelet",
price: 589.99,
},
{
reviewsCount: 4,
ratingsCount: 4,
imgs: ["diamond-ring.png", "diamond-ring.png", "diamond-ring.png"],
name: "Ring",
price: 589.99,
},
{
reviewsCount: 4,
ratingsCount: 4,
imgs: [
"diamond-silver-ring.png",
"diamond-silver-ring.png",
"diamond-silver-ring.png",
],
name: "<NAME>",
price: 589.99,
},
{
reviewsCount: 4,
ratingsCount: 4,
imgs: ["necklace (2).png", "necklace (2).png", "necklace (2).png"],
name: "Necklace",
price: 589.99,
},
{
reviewsCount: 4,
ratingsCount: 4,
imgs: [
"diamond-bracelet.png",
"diamond-bracelet.png",
"diamond-bracelet.png",
],
name: "Bracelet",
price: 589.99,
},
{
reviewsCount: 4,
ratingsCount: 4,
imgs: ["diamond-ring.png", "diamond-ring.png", "diamond-ring.png"],
name: "Ring",
price: 589.99,
},
{
reviewsCount: 4,
ratingsCount: 4,
imgs: [
"diamond-silver-ring.png",
"diamond-silver-ring.png",
"diamond-silver-ring.png",
],
name: "<NAME>",
price: 589.99,
},
{
reviewsCount: 4,
ratingsCount: 4,
imgs: ["necklace (2).png", "necklace (2).png", "necklace (2).png"],
name: "Necklace",
price: 589.99,
},
{
reviewsCount: 4,
ratingsCount: 4,
imgs: [
"diamond-bracelet.png",
"diamond-bracelet.png",
"diamond-bracelet.png",
],
name: "Bracelet",
price: 589.99,
},
{
reviewsCount: 4,
ratingsCount: 4,
imgs: ["diamond-ring.png", "diamond-ring.png", "diamond-ring.png"],
name: "Ring",
price: 589.99,
},
{
reviewsCount: 4,
ratingsCount: 4,
imgs: [
"diamond-silver-ring.png",
"diamond-silver-ring.png",
"diamond-silver-ring.png",
],
name: "<NAME>",
price: 589.99,
},
{
reviewsCount: 4,
ratingsCount: 4,
imgs: ["necklace (2).png", "necklace (2).png", "necklace (2).png"],
name: "Necklace",
price: 589.99,
},
{
reviewsCount: 4,
ratingsCount: 4,
imgs: [
"diamond-bracelet.png",
"diamond-bracelet.png",
"diamond-bracelet.png",
],
name: "Bracelet",
price: 589.99,
},
{
reviewsCount: 4,
ratingsCount: 4,
imgs: ["diamond-ring.png", "diamond-ring.png", "diamond-ring.png"],
name: "Ring",
price: 589.99,
},
{
reviewsCount: 4,
ratingsCount: 4,
imgs: [
"diamond-silver-ring.png",
"diamond-silver-ring.png",
"diamond-silver-ring.png",
],
name: "<NAME>",
price: 589.99,
},
{
reviewsCount: 4,
ratingsCount: 4,
imgs: ["necklace (2).png", "necklace (2).png", "necklace (2).png"],
name: "Necklace",
price: 589.99,
},
{
reviewsCount: 4,
ratingsCount: 4,
imgs: [
"diamond-bracelet.png",
"diamond-bracelet.png",
"diamond-bracelet.png",
],
name: "Bracelet",
price: 589.99,
},
{
reviewsCount: 4,
ratingsCount: 4,
imgs: ["diamond-ring.png", "diamond-ring.png", "diamond-ring.png"],
name: "Ring",
price: 589.99,
},
{
reviewsCount: 4,
ratingsCount: 4,
imgs: [
"diamond-silver-ring.png",
"diamond-silver-ring.png",
"diamond-silver-ring.png",
],
name: "<NAME>",
price: 589.99,
},
{
reviewsCount: 4,
ratingsCount: 4,
imgs: ["necklace (2).png", "necklace (2).png", "necklace (2).png"],
name: "Necklace",
price: 589.99,
},
{
reviewsCount: 4,
ratingsCount: 4,
imgs: [
"diamond-bracelet.png",
"diamond-bracelet.png",
"diamond-bracelet.png",
],
name: "Bracelet",
price: 589.99,
},
{
reviewsCount: 4,
ratingsCount: 4,
imgs: ["diamond-ring.png", "diamond-ring.png", "diamond-ring.png"],
name: "Ring",
price: 589.99,
},
{
reviewsCount: 4,
ratingsCount: 4,
imgs: [
"diamond-silver-ring.png",
"diamond-silver-ring.png",
"diamond-silver-ring.png",
],
name: "<NAME>",
price: 589.99,
},
{
reviewsCount: 4,
ratingsCount: 4,
imgs: ["necklace (2).png", "necklace (2).png", "necklace (2).png"],
name: "Necklace",
price: 589.99,
},
{
reviewsCount: 4,
ratingsCount: 4,
imgs: [
"diamond-bracelet.png",
"diamond-bracelet.png",
"diamond-bracelet.png",
],
name: "Bracelet",
price: 589.99,
},
{
reviewsCount: 4,
ratingsCount: 4,
imgs: ["diamond-ring.png", "diamond-ring.png", "diamond-ring.png"],
name: "Ring",
price: 589.99,
},
{
reviewsCount: 4,
ratingsCount: 4,
imgs: [
"diamond-silver-ring.png",
"diamond-silver-ring.png",
"diamond-silver-ring.png",
],
name: "<NAME>",
price: 589.99,
},
{
reviewsCount: 4,
ratingsCount: 4,
imgs: ["necklace (2).png", "necklace (2).png", "necklace (2).png"],
name: "Necklace",
price: 589.99,
},
{
reviewsCount: 4,
ratingsCount: 4,
imgs: [
"diamond-bracelet.png",
"diamond-bracelet.png",
"diamond-bracelet.png",
],
name: "Bracelet",
price: 589.99,
},
{
reviewsCount: 4,
ratingsCount: 4,
imgs: ["diamond-ring.png", "diamond-ring.png", "diamond-ring.png"],
name: "Ring",
price: 589.99,
},
{
reviewsCount: 4,
ratingsCount: 4,
imgs: [
"diamond-silver-ring.png",
"diamond-silver-ring.png",
"diamond-silver-ring.png",
],
name: "<NAME>",
price: 589.99,
},
{
reviewsCount: 4,
ratingsCount: 4,
imgs: ["necklace (2).png", "necklace (2).png", "necklace (2).png"],
name: "Necklace",
price: 589.99,
},
{
reviewsCount: 4,
ratingsCount: 4,
imgs: [
"diamond-bracelet.png",
"diamond-bracelet.png",
"diamond-bracelet.png",
],
name: "Bracelet",
price: 589.99,
},
{
reviewsCount: 4,
ratingsCount: 4,
imgs: ["diamond-ring.png", "diamond-ring.png", "diamond-ring.png"],
name: "Ring",
price: 589.99,
},
// {
// reviewsCount: 4,
// ratingsCount: 4,
// imgs: [
// "diamond-silver-ring.png",
// "diamond-silver-ring.png",
// "diamond-silver-ring.png",
// ],
// name: "<NAME>",
// price: 589.99,
// },
// {
// reviewsCount: 4,
// ratingsCount: 4,
// imgs: ["necklace (2).png", "necklace (2).png", "necklace (2).png"],
// name: "Necklace",
// price: 589.99,
// },
// {
// reviewsCount: 4,
// ratingsCount: 4,
// imgs: [
// "diamond-bracelet.png",
// "diamond-bracelet.png",
// "diamond-bracelet.png",
// ],
// name: "Bracelet",
// price: 589.99,
// },
// {
// reviewsCount: 4,
// ratingsCount: 4,
// imgs: ["diamond-ring.png", "diamond-ring.png", "diamond-ring.png"],
// name: "Ring",
// price: 589.99,
// },
// {
// reviewsCount: 4,
// ratingsCount: 4,
// imgs: [
// "diamond-silver-ring.png",
// "diamond-silver-ring.png",
// "diamond-silver-ring.png",
// ],
// name: "<NAME>",
// price: 589.99,
// },
// {
// reviewsCount: 4,
// ratingsCount: 4,
// imgs: ["necklace (2).png", "necklace (2).png", "necklace (2).png"],
// name: "Necklace",
// price: 589.99,
// },
// {
// reviewsCount: 4,
// ratingsCount: 4,
// imgs: [
// "diamond-bracelet.png",
// "diamond-bracelet.png",
// "diamond-bracelet.png",
// ],
// name: "Bracelet",
// price: 589.99,
// },
// {
// reviewsCount: 4,
// ratingsCount: 4,
// imgs: ["diamond-ring.png", "diamond-ring.png", "diamond-ring.png"],
// name: "Ring",
// price: 589.99,
// },
// {
// reviewsCount: 4,
// ratingsCount: 4,
// imgs: [
// "diamond-silver-ring.png",
// "diamond-silver-ring.png",
// "diamond-silver-ring.png",
// ],
// name: "<NAME>",
// price: 589.99,
// },
// {
// reviewsCount: 4,
// ratingsCount: 4,
// imgs: ["necklace (2).png", "necklace (2).png", "necklace (2).png"],
// name: "Necklace",
// price: 589.99,
// },
// {
// reviewsCount: 4,
// ratingsCount: 4,
// imgs: [
// "diamond-bracelet.png",
// "diamond-bracelet.png",
// "diamond-bracelet.png",
// ],
// name: "Bracelet",
// price: 589.99,
// },
// {
// reviewsCount: 4,
// ratingsCount: 4,
// imgs: ["diamond-ring.png", "diamond-ring.png", "diamond-ring.png"],
// name: "Ring",
// price: 589.99,
// },
// {
// reviewsCount: 4,
// ratingsCount: 4,
// imgs: [
// "diamond-silver-ring.png",
// "diamond-silver-ring.png",
// "diamond-silver-ring.png",
// ],
// name: "<NAME>",
// price: 589.99,
// },
// {
// reviewsCount: 4,
// ratingsCount: 4,
// imgs: ["necklace (2).png", "necklace (2).png", "necklace (2).png"],
// name: "Necklace",
// price: 589.99,
// },
// {
// reviewsCount: 4,
// ratingsCount: 4,
// imgs: [
// "diamond-bracelet.png",
// "diamond-bracelet.png",
// "diamond-bracelet.png",
// ],
// name: "Bracelet",
// price: 589.99,
// },
// {
// reviewsCount: 4,
// ratingsCount: 4,
// imgs: ["diamond-ring.png", "diamond-ring.png", "diamond-ring.png"],
// name: "Ring",
// price: 589.99,
// },
// {
// reviewsCount: 4,
// ratingsCount: 4,
// imgs: [
// "diamond-silver-ring.png",
// "diamond-silver-ring.png",
// "diamond-silver-ring.png",
// ],
// name: "<NAME>",
// price: 589.99,
// },
// {
// reviewsCount: 4,
// ratingsCount: 4,
// imgs: ["necklace (2).png", "necklace (2).png", "necklace (2).png"],
// name: "Necklace",
// price: 589.99,
// },
// {
// reviewsCount: 4,
// ratingsCount: 4,
// imgs: [
// "diamond-bracelet.png",
// "diamond-bracelet.png",
// "diamond-bracelet.png",
// ],
// name: "Bracelet",
// price: 589.99,
// },
// {
// reviewsCount: 4,
// ratingsCount: 4,
// imgs: ["diamond-ring.png", "diamond-ring.png", "diamond-ring.png"],
// name: "Ring",
// price: 589.99,
// },
// {
// reviewsCount: 4,
// ratingsCount: 4,
// imgs: [
// "diamond-silver-ring.png",
// "diamond-silver-ring.png",
// "diamond-silver-ring.png",
// ],
// name: "<NAME>",
// price: 589.99,
// },
// {
// reviewsCount: 4,
// ratingsCount: 4,
// imgs: ["necklace (2).png", "necklace (2).png", "necklace (2).png"],
// name: "Necklace",
// price: 589.99,
// },
// {
// reviewsCount: 4,
// ratingsCount: 4,
// imgs: [
// "diamond-bracelet.png",
// "diamond-bracelet.png",
// "diamond-bracelet.png",
// ],
// name: "Bracelet",
// price: 589.99,
// },
// {
// reviewsCount: 4,
// ratingsCount: 4,
// imgs: ["diamond-ring.png", "diamond-ring.png", "diamond-ring.png"],
// name: "Ring",
// price: 589.99,
// },
// {
// reviewsCount: 4,
// ratingsCount: 4,
// imgs: [
// "diamond-silver-ring.png",
// "diamond-silver-ring.png",
// "diamond-silver-ring.png",
// ],
// name: "<NAME>",
// price: 589.99,
// },
// {
// reviewsCount: 4,
// ratingsCount: 4,
// imgs: ["necklace (2).png", "necklace (2).png", "necklace (2).png"],
// name: "Necklace",
// price: 589.99,
// },
// {
// reviewsCount: 4,
// ratingsCount: 4,
// imgs: [
// "diamond-bracelet.png",
// "diamond-bracelet.png",
// "diamond-bracelet.png",
// ],
// name: "Bracelet",
// price: 589.99,
// },
// {
// reviewsCount: 4,
// ratingsCount: 4,
// imgs: ["diamond-ring.png", "diamond-ring.png", "diamond-ring.png"],
// name: "Ring",
// price: 589.99,
// },
// {
// reviewsCount: 4,
// ratingsCount: 4,
// imgs: [
// "diamond-silver-ring.png",
// "diamond-silver-ring.png",
// "diamond-silver-ring.png",
// ],
// name: "<NAME>",
// price: 589.99,
// },
// {
// reviewsCount: 4,
// ratingsCount: 4,
// imgs: ["necklace (2).png", "necklace (2).png", "necklace (2).png"],
// name: "Necklace",
// price: 589.99,
// },
// {
// reviewsCount: 4,
// ratingsCount: 4,
// imgs: [
// "diamond-bracelet.png",
// "diamond-bracelet.png",
// "diamond-bracelet.png",
// ],
// name: "Bracelet",
// price: 589.99,
// },
// {
// reviewsCount: 4,
// ratingsCount: 4,
// imgs: ["diamond-ring.png", "diamond-ring.png", "diamond-ring.png"],
// name: "Ring",
// price: 589.99,
// },
// {
// reviewsCount: 4,
// ratingsCount: 4,
// imgs: [
// "diamond-silver-ring.png",
// "diamond-silver-ring.png",
// "diamond-silver-ring.png",
// ],
// name: "<NAME>",
// price: 589.99,
// },
// {
// reviewsCount: 4,
// ratingsCount: 4,
// imgs: ["necklace (2).png", "necklace (2).png", "necklace (2).png"],
// name: "Necklace",
// price: 589.99,
// },
// {
// reviewsCount: 4,
// ratingsCount: 4,
// imgs: [
// "diamond-bracelet.png",
// "diamond-bracelet.png",
// "diamond-bracelet.png",
// ],
// name: "Bracelet",
// price: 589.99,
// },
// {
// reviewsCount: 4,
// ratingsCount: 4,
// imgs: ["diamond-ring.png", "diamond-ring.png", "diamond-ring.png"],
// name: "Ring",
// price: 589.99,
// },
// {
// reviewsCount: 4,
// ratingsCount: 4,
// imgs: [
// "diamond-silver-ring.png",
// "diamond-silver-ring.png",
// "diamond-silver-ring.png",
// ],
// name: "<NAME>",
// price: 589.99,
// },
// {
// reviewsCount: 4,
// ratingsCount: 4,
// imgs: ["necklace (2).png", "necklace (2).png", "necklace (2).png"],
// name: "Necklace",
// price: 589.99,
// },
// {
// reviewsCount: 4,
// ratingsCount: 4,
// imgs: [
// "diamond-bracelet.png",
// "diamond-bracelet.png",
// "diamond-bracelet.png",
// ],
// name: "Bracelet",
// price: 589.99,
// },
// {
// reviewsCount: 4,
// ratingsCount: 4,
// imgs: ["diamond-ring.png", "diamond-ring.png", "diamond-ring.png"],
// name: "Ring",
// price: 589.99,
// },
// {
// reviewsCount: 4,
// ratingsCount: 4,
// imgs: [
// "diamond-silver-ring.png",
// "diamond-silver-ring.png",
// "diamond-silver-ring.png",
// ],
// name: "<NAME>",
// price: 589.99,
// },
// {
// reviewsCount: 4,
// ratingsCount: 4,
// imgs: ["necklace (2).png", "necklace (2).png", "necklace (2).png"],
// name: "Necklace",
// price: 589.99,
// },
// {
// reviewsCount: 4,
// ratingsCount: 4,
// imgs: [
// "diamond-bracelet.png",
// "diamond-bracelet.png",
// "diamond-bracelet.png",
// ],
// name: "Bracelet",
// price: 589.99,
// },
// {
// reviewsCount: 4,
// ratingsCount: 4,
// imgs: ["diamond-ring.png", "diamond-ring.png", "diamond-ring.png"],
// name: "Ring",
// price: 589.99,
// },
// {
// reviewsCount: 4,
// ratingsCount: 4,
// imgs: [
// "diamond-silver-ring.png",
// "diamond-silver-ring.png",
// "diamond-silver-ring.png",
// ],
// name: "<NAME>",
// price: 589.99,
// },
// {
// reviewsCount: 4,
// ratingsCount: 4,
// imgs: ["necklace (2).png", "necklace (2).png", "necklace (2).png"],
// name: "Necklace",
// price: 589.99,
// },
// {
// reviewsCount: 4,
// ratingsCount: 4,
// imgs: [
// "diamond-bracelet.png",
// "diamond-bracelet.png",
// "diamond-bracelet.png",
// ],
// name: "Bracelet",
// price: 589.99,
// },
// {
// reviewsCount: 4,
// ratingsCount: 4,
// imgs: ["diamond-ring.png", "diamond-ring.png", "diamond-ring.png"],
// name: "Ring",
// price: 589.99,
// },
// {
// reviewsCount: 4,
// ratingsCount: 4,
// imgs: [
// "diamond-silver-ring.png",
// "diamond-silver-ring.png",
// "diamond-silver-ring.png",
// ],
// name: "<NAME>",
// price: 589.99,
// },
// {
// reviewsCount: 4,
// ratingsCount: 4,
// imgs: ["necklace (2).png", "necklace (2).png", "necklace (2).png"],
// name: "Necklace",
// price: 589.99,
// },
// {
// reviewsCount: 4,
// ratingsCount: 4,
// imgs: [
// "diamond-bracelet.png",
// "diamond-bracelet.png",
// "diamond-bracelet.png",
// ],
// name: "Bracelet",
// price: 589.99,
// },
// {
// reviewsCount: 4,
// ratingsCount: 4,
// imgs: ["diamond-ring.png", "diamond-ring.png", "diamond-ring.png"],
// name: "Ring",
// price: 589.99,
// },
// {
// reviewsCount: 4,
// ratingsCount: 4,
// imgs: ["diamond-ring.png", "diamond-ring.png", "diamond-ring.png"],
// name: "Ring",
// price: 589.99,
// },
];
function updatePagination() {
let paginationLen = 24;
let items = $(".product-card");
const paginationItemsLen = Math.ceil(items.length / paginationLen);
let paginationMarkup = `<li data-page-num=${"prev"}><span><img src='./assets/images/pagination-arrow.svg' /></span></li>`;
if (paginationItemsLen > 1) {
for (let i = 0; i < paginationItemsLen; i++) {
paginationMarkup += `
<li data-page-num='${i + 1}' class='${i === 0 ? "active" : ""}' ><span>${
i + 1
}</span></li>
`;
}
}
paginationMarkup += `<li data-page-num=${"next"}><span><img src='./assets/images/pagination-arrow.svg' style='transform: rotate(180deg)' /></span></li>`;
if (paginationItemsLen <= 1) {
paginationMarkup = "";
}
$(".pagination").html(paginationMarkup);
items.parent().hide();
items.each(function (i, el) {
i += 1;
if (i > paginationLen) {
return;
}
$(el).parent().show();
});
$(".pagination li").click(function () {
$this = $(this);
let paginationNum;
if ($(this).attr("data-page-num") === "prev") {
paginationNum = +$(".pagination > li.active").find("span").html() - 2;
if (paginationNum + 1 < 1) {
return;
}
} else if ($(this).attr("data-page-num") === "next") {
paginationNum = +$(".pagination > li.active").find("span").html();
if (paginationNum + 1 > paginationItemsLen) {
return;
}
} else {
paginationNum = +$this.find("span").html() - 1;
}
$(".pagination li").removeClass("active");
$(`.pagination li[data-page-num='${paginationNum + 1}']`).addClass(
"active"
);
items.parent().hide();
items.each(function (i, el) {
if (
i < paginationNum * paginationLen ||
i >= paginationNum * paginationLen + paginationLen
) {
return;
}
$(el).parent().show();
});
});
}
$(".ranger .btn").click(filterByPrice);
function sliderHandler() {
const minPriceWrapper = $("#min-price-filter");
const maxPriceWrapper = $("#max-price-filter");
minPriceWrapper.html(filters.price.lowerPriceVal);
maxPriceWrapper.html(filters.price.upperPriceVal);
function changeValues() {
filters.price.lowerPriceVal = parseFloat(lowerSlider.value).toFixed(2);
filters.price.upperPriceVal = parseFloat(upperSlider.value).toFixed(2);
minPriceWrapper.html(filters.price.lowerPriceVal);
maxPriceWrapper.html(filters.price.upperPriceVal);
}
upperSlider.oninput = changeValues;
lowerSlider.oninput = changeValues;
}
function showProductsOnDOM(prods) {
let productsMarkup = "";
$(".product-card").parent().remove();
let filteredProducts;
filteredProducts = products;
if (prods) {
filteredProducts = prods;
}
filteredProducts.forEach((el, index) => {
let { reviewsCount, ratingsCount, imgs, name, price } = el;
let reviewsMarkup = "";
let imagesMarkup = `
<div class="product-slider">
<div class="swiper-wrapper">
`;
for (let i = 0; i < reviewsCount; i++) {
reviewsMarkup += `<img src="./assets/images/star-fill.png" alt="" />`;
}
for (let i = 0; i < 5 - reviewsCount; i++) {
reviewsMarkup += `<img src="./assets/images/star-no-fill.png" alt="" />`;
}
for (const img of imgs) {
imagesMarkup += `
<div class="swiper-slide">
<img
src="./assets/images/${img}"
alt=""
/>
</div>
`;
}
imagesMarkup += `
</div>
<div class="swiper-pagination"></div>
</div>
`;
productsMarkup += `
<a href="./product.html" class="col-12 col-sm-6 col-md-4 col-lg-3">
<div class="product-card">
${imagesMarkup}
<div class="product-details">
<div class="reviews">
<div class="stars">
${reviewsMarkup}
</div>
<span class='counter fit'>(${ratingsCount} Customer Review)</span>
</div>
<h3>${name} (${index + 1})</h3>
<h2>$${price}</h2>
</div>
</div>
</a>
`;
});
$(".products_container .row").append(productsMarkup);
$("#result-count").html(filteredProducts.length);
const filtersLen = Object.keys(filters).length;
$("#filters-names").html(
`${
filtersLen > 0
? filtersLen + ` ${filtersLen === 1 ? "Filter" : "Filters"} Applied`
: "No Filters Applied"
}`
);
new Swiper(".product-slider", {
spaceBetween: 30,
centeredSlides: true,
autoplay: {
delay: 2500,
disableOnInteraction: false,
},
pagination: {
el: ".swiper-pagination",
clickable: true,
},
});
textFit(document.querySelectorAll(".fit"));
updatePagination();
}
function filterByPrice() {
let filtered = products.filter(
(el) =>
el.price > filters.price.lowerPriceVal &&
el.price < filters.price.upperPriceVal
);
showProductsOnDOM(filtered);
}
showProductsOnDOM();
filterByPrice();
sliderHandler();
<file_sep>textFit(document.querySelectorAll(".fit"));
var swiper = new Swiper(".mySwiper", {
slidesPerView: 1,
spaceBetween: 30,
navigation: {
nextEl: ".swiper-button-next",
prevEl: ".swiper-button-prev",
},
breakpoints: {
576: {
slidesPerView: 4,
},
400: {
slidesPerView: 2,
},
},
});
var swiper = new Swiper(".mySwiper2", {
slidesPerView: 1,
spaceBetween: 30,
navigation: {
nextEl: ".swiper-button-next",
prevEl: ".swiper-button-prev",
},
breakpoints: {
992: {
slidesPerView: 4,
},
576: {
slidesPerView: 3,
},
451: {
slidesPerView: 2,
},
0: {
slidesPerView: 1,
},
},
});
new Swiper(".product-slider", {
spaceBetween: 30,
centeredSlides: true,
autoplay: {
delay: 2500,
disableOnInteraction: false,
},
pagination: {
el: ".swiper-pagination",
clickable: true,
},
});
function toggleCart() {
$("#dark-overlay").toggleClass("active");
$("#cart-wrapper").toggleClass("active");
$("html").toggleClass("inactive");
}
$(".cart_icon, #close, #dark-overlay").click(toggleCart);
$(".quantity-wrapper > button").click(function () {
$this = $(this);
let text = $this.html();
let input = $this.siblings("input");
let newVal;
if (text === "+") {
newVal = +input.val() + 1;
} else {
newVal = +input.val() - 1;
if (newVal < 0) {
newVal = 0;
}
}
input.val(newVal);
});
<file_sep>AOS.init();
$("#preloader").hide();
$("html").css("overflow", "unset");
$(window).on("scroll", function (e) {
$("#back-home").hide();
let scroll = $(window).scrollTop();
if (scroll > 600) {
$("#back-home").show();
}
});
$("#back-home").click(function () {
$(window).scrollTop(0);
});
|
b5083ce5990b99a6ffc3ed37b1100be2fe5193bc
|
[
"JavaScript"
] | 3
|
JavaScript
|
tayyabferozi/moncheri-jewelery
|
66ccb7c7bbae9231301d4be2b7b4a910908e921e
|
a064bc5bbf53321bd73b170812ac7886750cb264
|
refs/heads/master
|
<repo_name>leechangtaek/spring-seminar<file_sep>/Springboot-restapi/src/main/java/com/kh/springboot/menu/controller/MenuController.java
package com.kh.springboot.menu.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.kh.springboot.menu.model.service.MenuService;
import com.kh.springboot.menu.model.vo.Menu;
import lombok.extern.slf4j.Slf4j;
@RestController
@Slf4j
@CrossOrigin(origins = "*")
public class MenuController {
@Autowired
private MenuService menuService;
@GetMapping("/menus")
public List<Menu> selectAll(){
return menuService.selectAll();
}
@GetMapping("/menus/{type}")
public List<Menu> selectMenuByType(@PathVariable("type") String type){
Map<String,String> param = new HashMap<>();
param.put("type", type);
log.debug("param={}", param);
return menuService.selectMenuByType(param);
}
@GetMapping("/menus/{type}/{taste}")
public List<Menu> selectMenuByTypeAndTaste(@PathVariable ("type") String type, @PathVariable ("taste") String taste, HttpServletResponse response){
Map<String,String> param = new HashMap<>();
param.put("type", type);
param.put("taste", taste);
log.debug("param={}", param);
//CORS 허용하기 : 응답헤더에 해당Origin을 작성해서 허용한다.
// response.setHeader("Access-Control-Allow-Origin", "http://localhost:9090");//protocol+hostname+port
// response.setHeader("Access-Control-Allow-Origin", "*");//모든 Origin에 대해 허용하기
return menuService.selectMenuByTypeAndTaste(param);
}
@PostMapping("/menu")
public Map<String,String> insertMenu(@RequestBody Menu menu){
log.info("menu="+menu.toString());
String msg = menuService.insertMenu(menu)>0?"메뉴입력 성공":"메뉴입력 실패";
//리턴타입도 json변환가능한 map 전송함.
Map<String,String> map = new HashMap<>();
map.put("msg", msg);
return map;
}
@GetMapping("/menu/{id}")
public Menu selectOneMenu(@PathVariable("id") int id){
log.debug("메뉴 선택 : "+id);
Menu menu = menuService.selectOneMenu(id);
if(menu==null) menu = new Menu();//null데이터를 json으로 변환불가하므로, 빈객체 전달
return menu;
}
@PutMapping("/menu")
public Map<String,String> updateMenu(@RequestBody Menu menu){
log.info(menu.toString());
String msg = menuService.updateMenu(menu)>0?"메뉴수정 성공":"메뉴수정 실패";
//리턴타입도 json변환가능한 map 전송함.
Map<String,String> map = new HashMap<>();
map.put("msg", msg);
return map;
}
@DeleteMapping("/menu/{id}")
public Map<String,String> deleteMenu(@PathVariable("id") int id){
log.info("삭제할 메뉴번호 : "+id);
String msg = menuService.deleteMenu(id)>0?"메뉴삭제 성공":"메뉴삭제 실패";
//리턴타입도 json변환가능한 map 전송함.
Map<String,String> map = new HashMap<>();
map.put("msg", msg);
return map;
}
}
<file_sep>/Springboot-restapi/README.md
# Springboot x RestAPI
[Springboot x RestAPI Tutorial](https://www.notion.so/khjava/Springboot-x-RestAPI-12195ba63a424f2daeada604a326acea)
<file_sep>/Springboot-restapi/sql/menu@spring.sql
--------------------------------------------------------
-- File created - Monday-March-23-2020
--------------------------------------------------------
DROP SEQUENCE "SPRING"."SEQ_MENU";
DROP TABLE "SPRING"."MENU" cascade constraints;
--------------------------------------------------------
-- DDL for Sequence SEQ_MENU
--------------------------------------------------------
CREATE SEQUENCE "SPRING"."SEQ_MENU" MINVALUE 1 MAXVALUE 9999999999999999999999999999 INCREMENT BY 1 START WITH 30 NOCACHE NOORDER NOCYCLE ;
--------------------------------------------------------
-- DDL for Table MENU
--------------------------------------------------------
select * from menu;
CREATE TABLE "SPRING"."MENU"
( "ID" NUMBER,
"RESTAURANT" VARCHAR2(100 BYTE),
"NAME" VARCHAR2(100 BYTE),
"PRICE" NUMBER,
"TYPE" VARCHAR2(10 BYTE),
"TASTE" VARCHAR2(30 BYTE)
) SEGMENT CREATION IMMEDIATE
PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255 NOCOMPRESS LOGGING
STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
TABLESPACE "USERS" ;
REM INSERTING into SPRING.MENU
SET DEFINE OFF;
Insert into SPRING.MENU (ID,RESTAURANT,NAME,PRICE,TYPE,TASTE) values (24,'스타동','사케동',8400,'jp','mild');
Insert into SPRING.MENU (ID,RESTAURANT,NAME,PRICE,TYPE,TASTE) values (1,'두리순대국','순대국',7000,'kr','mild');
Insert into SPRING.MENU (ID,RESTAURANT,NAME,PRICE,TYPE,TASTE) values (2,'두리순대국','순대국',7000,'kr','hot');
Insert into SPRING.MENU (ID,RESTAURANT,NAME,PRICE,TYPE,TASTE) values (3,'장터','뚝배기 김치찌게',7000,'kr','hot');
Insert into SPRING.MENU (ID,RESTAURANT,NAME,PRICE,TYPE,TASTE) values (4,'만리향','간짜장',5000,'ch','mild');
Insert into SPRING.MENU (ID,RESTAURANT,NAME,PRICE,TYPE,TASTE) values (5,'만리향','짬뽕',6000,'ch','hot');
Insert into SPRING.MENU (ID,RESTAURANT,NAME,PRICE,TYPE,TASTE) values (6,'짬뽕지존','짬뽕',9000,'ch','mild');
Insert into SPRING.MENU (ID,RESTAURANT,NAME,PRICE,TYPE,TASTE) values (8,'김남완초밥집','완초밥',13000,'jp','mild');
Insert into SPRING.MENU (ID,RESTAURANT,NAME,PRICE,TYPE,TASTE) values (9,'김남완초밥집','런치초밥',10000,'jp','mild');
Insert into SPRING.MENU (ID,RESTAURANT,NAME,PRICE,TYPE,TASTE) values (10,'김남완초밥집','참치도로초밥',33000,'jp','mild');
Insert into SPRING.MENU (ID,RESTAURANT,NAME,PRICE,TYPE,TASTE) values (11,'진가와','자루소면',8000,'jp','mild');
Insert into SPRING.MENU (ID,RESTAURANT,NAME,PRICE,TYPE,TASTE) values (12,'진가와','자루소바',9000,'jp','mild');
Insert into SPRING.MENU (ID,RESTAURANT,NAME,PRICE,TYPE,TASTE) values (13,'백운봉','막국수',9000,'kr','hot');
Insert into SPRING.MENU (ID,RESTAURANT,NAME,PRICE,TYPE,TASTE) values (14,'대우부대찌게','부대지게',10000,'kr','hot');
Insert into SPRING.MENU (ID,RESTAURANT,NAME,PRICE,TYPE,TASTE) values (15,'봉된장','열무비빔밥+우렁된장',7000,'kr','hot');
Insert into SPRING.MENU (ID,RESTAURANT,NAME,PRICE,TYPE,TASTE) values (17,'대우부대찌게','부대찌게',10000,'kr','hot');
Insert into SPRING.MENU (ID,RESTAURANT,NAME,PRICE,TYPE,TASTE) values (20,'산들애','딸기',500,'kr','hot');
Insert into SPRING.MENU (ID,RESTAURANT,NAME,PRICE,TYPE,TASTE) values (19,'대우부대찌게','청국장',13000,'kr','mild');
Insert into SPRING.MENU (ID,RESTAURANT,NAME,PRICE,TYPE,TASTE) values (29,'진씨화로','돌솥비빔밥',7000,'kr','mild');
--------------------------------------------------------
-- DDL for Index UQ_MENU
--------------------------------------------------------
CREATE UNIQUE INDEX "SPRING"."UQ_MENU" ON "SPRING"."MENU" ("RESTAURANT", "NAME", "TASTE")
PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS
STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
TABLESPACE "USERS" ;
--------------------------------------------------------
-- DDL for Index SYS_C007273
--------------------------------------------------------
CREATE UNIQUE INDEX "SPRING"."SYS_C007273" ON "SPRING"."MENU" ("ID")
PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS
STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
TABLESPACE "USERS" ;
--------------------------------------------------------
-- Constraints for Table MENU
--------------------------------------------------------
ALTER TABLE "SPRING"."MENU" ADD CONSTRAINT "UQ_MENU" UNIQUE ("RESTAURANT", "NAME", "TASTE")
USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS
STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
TABLESPACE "USERS" ENABLE;
ALTER TABLE "SPRING"."MENU" ADD PRIMARY KEY ("ID")
USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS
STORAGE(INITIAL 65536 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT FLASH_CACHE DEFAULT CELL_FLASH_CACHE DEFAULT)
TABLESPACE "USERS" ENABLE;
ALTER TABLE "SPRING"."MENU" MODIFY ("TASTE" NOT NULL ENABLE);
ALTER TABLE "SPRING"."MENU" MODIFY ("TYPE" NOT NULL ENABLE);
ALTER TABLE "SPRING"."MENU" MODIFY ("PRICE" NOT NULL ENABLE);
ALTER TABLE "SPRING"."MENU" MODIFY ("NAME" NOT NULL ENABLE);
ALTER TABLE "SPRING"."MENU" MODIFY ("RESTAURANT" NOT NULL ENABLE);
commit;
<file_sep>/Springboot-restapi/src/main/java/com/kh/springboot/menu/model/service/MenuServieImpl.java
package com.kh.springboot.menu.model.service;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.kh.springboot.menu.model.dao.MenuDAO;
import com.kh.springboot.menu.model.vo.Menu;
@Service
public class MenuServieImpl implements MenuService {
@Autowired
private MenuDAO menuDAO;
@Override
public List<Menu> selectAll() {
return menuDAO.selectAll();
}
@Override
public List<Menu> selectMenuByTypeAndTaste(Map<String, String> param) {
return menuDAO.selectMenuByTypeAndTaste(param);
}
@Override
public List<Menu> selectMenuByType(Map<String, String> param) {
return menuDAO.selectMenuByType(param);
}
@Override
public int insertMenu(Menu menu) {
return menuDAO.insertMenu(menu);
}
@Override
public int updateMenu(Menu menu) {
return menuDAO.updateMenu(menu);
}
@Override
public int deleteMenu(int id) {
return menuDAO.deleteMenu(id);
}
@Override
public Menu selectOneMenu(int id) {
return menuDAO.selectOneMenu(id);
}
}
<file_sep>/.metadata/version.ini
#Mon Jun 01 15:01:52 KST 2020
org.eclipse.core.runtime=2
org.eclipse.platform=4.8.0.v20180611-0500
|
d0ba44fa9f8cf3521b33f343d394b2a6e8631e76
|
[
"Markdown",
"Java",
"SQL",
"INI"
] | 5
|
Java
|
leechangtaek/spring-seminar
|
a9241f78e65d06eb2db77d45f35fc8e25574e7b7
|
b6704fc871d0169bd608f66355552329a843e775
|
refs/heads/master
|
<file_sep>#include <linux/module.h>
#include <linux/sched.h>
#include <linux/uaccess.h>
#include <linux/fs.h>
#include <linux/miscdevice.h>
#include <linux/types.h>
#include <linux/atomic.h>
#include <linux/delay.h>
#include <linux/vmalloc.h>
#include <linux/string.h>
#include <linux/kernel.h>
#include <linux/io.h>
#include <linux/mm.h>
#define MY_SET_LEN _IOW('t', 1, uint32_t)
#define MY_GET_LEN _IOR('t', 2, uint64_t)
#define BUF_SIZE 20971520 /* 20*2^20 */
atomic_t my_len = ATOMIC_INIT(4);
atomic_t my_opened = ATOMIC_INIT(0);
DEFINE_MUTEX(lock);
char *buf;
ssize_t my_read(struct file *filp, char __user *ptr, size_t count, loff_t *off)
{
int read;
if (*off >= BUF_SIZE || !count)
return 0;
read = (count + *off >= BUF_SIZE) ? BUF_SIZE - *off : count;
/* lock before reading the buffer */
mutex_lock(&lock);
if (copy_to_user(ptr, &buf[*off], read) != 0) {
mutex_unlock(&lock);
return -EFAULT;
}
/* unlock after reading the buffer */
mutex_unlock(&lock);
*off += read;
return read;
}
ssize_t my_write(struct file *filp, const char __user *ptr, size_t count,
loff_t *off)
{
int write;
if (*off >= BUF_SIZE || !count)
return 0;
write = (count + *off >= BUF_SIZE) ? BUF_SIZE - *off : count;
/* lock lock before writing, we want some consistency... */
mutex_lock(&lock);
if (copy_from_user(&buf[*off], ptr, write) != 0) {
mutex_unlock(&lock);
return -EFAULT;
}
/* no more work with buffer, free the lock */
mutex_unlock(&lock);
*off += count;
printk(KERN_INFO "User wrote: \"%s\"\n", buf);
return write;
}
int my_open(struct inode *inode, struct file *filp)
{
if ((filp->f_mode & FMODE_WRITE) != 0 &&
atomic_add_unless(&my_opened, 1, 1) == 0) {
printk(KERN_INFO "Device is already opened for writing.\n");
return -EBUSY;
}
printk(KERN_INFO "Device opened.\n");
return 0;
}
int my_release(struct inode *inode, struct file *filp)
{
if ((filp->f_mode & FMODE_WRITE) != 0)
atomic_set(&my_opened, 0);
printk(KERN_INFO "Closing device.\n");
return 0;
}
long my_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
{
uint32_t len;
/* check command number */
switch (cmd) {
case MY_SET_LEN:
len = (uint32_t) arg;
if (len > 4 || len < 1)
return -EINVAL;
atomic_set(&my_len, len);
break;
case MY_GET_LEN:
/* read my_len atomicaly and work with local copy */
len = atomic_read(&my_len);
if (copy_to_user((uint32_t *) arg, &len,
sizeof(len)) != 0)
return -EFAULT;
break;
default:
return -EINVAL;
break;
}
return 0;
}
const struct file_operations myfops = {
.owner = THIS_MODULE,
.read = my_read,
.open = my_open,
.write = my_write,
.release = my_release,
.unlocked_ioctl = my_ioctl,
};
struct miscdevice mydevice = {
.minor = MISC_DYNAMIC_MINOR,
.name = "mydevice",
.fops = &myfops,
};
static int my_init(void)
{
char str[100], *ptr;
buf = vzalloc(BUF_SIZE);
if (buf == NULL)
return -ENOMEM;
/* write page virtual and physical address to every page */
for (ptr = buf; ptr < buf + BUF_SIZE; ptr += PAGE_SIZE) {
sprintf(str, "%p: %lx\n", ptr,
(unsigned long) vmalloc_to_pfn(ptr) << PAGE_SHIFT);
strcpy(ptr, str);
}
misc_register(&mydevice);
printk(KERN_INFO "MY_SET_LEN: %u\n", MY_SET_LEN);
printk(KERN_INFO "MY_GET_LEN: %u\n", MY_GET_LEN);
return 0;
}
static void my_exit(void)
{
misc_deregister(&mydevice);
vfree((void *) buf);
}
module_init(my_init);
module_exit(my_exit);
MODULE_LICENSE("GPL");
<file_sep>#include <linux/io.h>
#include <linux/module.h>
#include <linux/delay.h>
#include <linux/list.h>
#include <linux/pci.h>
/* structure in the list */
struct my_struct {
struct pci_dev *pdev;
struct list_head list;
};
LIST_HEAD(device_list);
/* help function printing info about the device */
static void print_dev(struct pci_dev *pdev)
{
printk(KERN_INFO "%.2x:%.2x.%.2x, vendor: %.4x, device %.4x\n",
pdev->bus->number, PCI_SLOT(pdev->devfn),
PCI_FUNC(pdev->devfn), pdev->vendor, pdev->device);
}
static int my_init(void)
{
struct my_struct *s;
struct pci_dev *pdev = NULL;
/* go over all pci devices */
while ((pdev = pci_get_device(PCI_ANY_ID, PCI_ANY_ID, pdev))) {
/* allocate memory for list item */
s = kmalloc(sizeof(*s), GFP_KERNEL);
/* just stop looping on error. */
if (s == NULL) {
pci_dev_put(pdev);
break;
}
/* add the item to the list */
pci_dev_get(pdev);
s->pdev = pdev;
list_add(&s->list, &device_list);
}
return 0;
}
/* this function loops simultaneously through both stored and current
pci device list. both lists are sorted by domain, bus, slot and function
(at least it appears that it is always so). */
static void my_exit(void)
{
struct my_struct *s, *s1;
struct pci_dev *pdev = NULL;
/* get first current item */
pdev = pci_get_device(PCI_ANY_ID, PCI_ANY_ID, pdev);
/* loop over stored list */
list_for_each_entry_safe_reverse(s, s1, &device_list, list) {
/* while current item is < than stored, print it and try next */
/* this is most ugly and unreadable and deserves own function */
while (pdev &&
((pci_domain_nr(pdev->bus) <
pci_domain_nr(s->pdev->bus)) ||
(pci_domain_nr(pdev->bus) <=
pci_domain_nr(s->pdev->bus) &&
(pdev->bus->number < s->pdev->bus->number)) ||
((pci_domain_nr(pdev->bus) <=
pci_domain_nr(s->pdev->bus) &&
(pdev->bus->number <= s->pdev->bus->number)) &&
(PCI_SLOT(pdev->devfn) < PCI_SLOT(s->pdev->devfn))) ||
((pci_domain_nr(pdev->bus) <=
pci_domain_nr(s->pdev->bus) &&
(pdev->bus->number <= s->pdev->bus->number) &&
(PCI_SLOT(pdev->devfn) <=
PCI_SLOT(s->pdev->devfn)) &&
(PCI_FUNC(pdev->devfn) <
PCI_FUNC(s->pdev->devfn)))))) {
print_dev(pdev);
pdev = pci_get_device(PCI_ANY_ID, PCI_ANY_ID, pdev);
}
/* when items are different, stored item is smaller */
if (!pdev ||
pci_domain_nr(s->pdev->bus) !=
pci_domain_nr(pdev->bus) ||
s->pdev->bus->number != pdev->bus->number ||
PCI_SLOT(s->pdev->devfn) != PCI_SLOT(pdev->devfn) ||
PCI_FUNC(s->pdev->devfn) != PCI_FUNC(pdev->devfn)) {
print_dev(s->pdev);
} else if (pdev) { /* otherwise increment current item */
pdev = pci_get_device(PCI_ANY_ID, PCI_ANY_ID, pdev);
}
/* always remove stored item fromthe list */
pci_dev_put(s->pdev);
list_del(&s->list);
kfree(s);
}
/* there still might be some new devices, print them */
while (pdev && (pdev = pci_get_device(PCI_ANY_ID, PCI_ANY_ID, pdev)))
print_dev(pdev);
}
module_init(my_init);
module_exit(my_exit);
MODULE_LICENSE("GPL");
<file_sep>#include <linux/module.h>
#include <linux/sched.h>
#include <linux/uaccess.h>
#include <linux/fs.h>
#include <linux/miscdevice.h>
#include <linux/types.h>
#define MY_SET_LEN _IOW('t', 1, uint32_t)
#define MY_GET_LEN _IOR('t', 2, uint64_t)
uint32_t my_len = 4;
ssize_t my_read(struct file *filp, char __user *ptr, size_t count, loff_t *off)
{
char ret[] = "Ahoj";
ret[my_len] = '\0'; /* always terminate the string */
if (copy_to_user(ptr, ret, my_len+1) != 0)
return -EFAULT;
return my_len+1;
}
ssize_t my_write(struct file *filp, const char __user *ptr, size_t count,
loff_t *off)
{
char buf[100];
int read = (count > 99) ? 99 : count;
if (copy_from_user(buf, ptr, read) != 0)
return -EFAULT;
buf[read] = '\0';
printk(KERN_INFO "User wrote: \"%s\"\n", buf);
return read;
}
int my_open(struct inode *inode, struct file *filp)
{
printk(KERN_INFO "File opened\n");
return 0;
}
int my_release(struct inode *inode, struct file *filp)
{
printk(KERN_INFO "Closing file\n");
return 0;
}
long my_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
{
/* check command number */
switch (cmd) {
case MY_SET_LEN:
if ((uint32_t) arg > 4 || (uint32_t) arg < 1)
return -EINVAL;
my_len = (uint32_t) arg;
break;
case MY_GET_LEN:
if (copy_to_user((uint32_t *) arg, &my_len,
sizeof(my_len)) != 0)
return -EFAULT;
break;
default:
return -EINVAL;
break;
}
return 0;
}
const struct file_operations myfops = {
.owner = THIS_MODULE,
.read = my_read,
.open = my_open,
.write = my_write,
.release = my_release,
.unlocked_ioctl = my_ioctl,
};
struct miscdevice mydevice = {
.minor = MISC_DYNAMIC_MINOR,
.name = "mydevice",
.fops = &myfops,
};
static int my_init(void)
{
misc_register(&mydevice);
printk(KERN_INFO "MY_SET_LEN: %u\n", MY_SET_LEN);
printk(KERN_INFO "MY_GET_LEN: %u\n", MY_GET_LEN);
return 0;
}
static void my_exit(void)
{
misc_deregister(&mydevice);
}
module_init(my_init);
module_exit(my_exit);
MODULE_LICENSE("GPL");
<file_sep>#include <linux/module.h>
#include <linux/vmalloc.h>
#include <linux/gfp.h>
#include <linux/fs.h>
#include <linux/mm.h>
#include <linux/io.h>
#include <linux/miscdevice.h>
#include <linux/module.h>
#include <linux/string.h>
#include <linux/uaccess.h>
void *ptr[4];
struct page *my_nopage(struct vm_area_struct *vma, unsigned long address,
int *type)
{
unsigned long offset = vma->vm_pgoff << PAGE_SHIFT;
struct page *page = NULL;
int offset_page;
offset += address - vma->vm_start;
offset_page = offset / PAGE_SIZE;
if (offset_page < 2)
page = vmalloc_to_page(ptr[offset_page]);
else if (offset_page < 4)
page = virt_to_page(ptr[offset_page]);
if (!page)
return NOPAGE_SIGBUS;
get_page(page);
if (type)
*type = VM_FAULT_MINOR;
return page;
}
struct vm_operations_struct vos = {
.nopage = &my_nopage,
};
int my_mmap(struct file *filp, struct vm_area_struct *vma)
{
vma->vm_ops = &vos;
return 0;
}
static const struct file_operations my_fops = {
.owner = THIS_MODULE,
.mmap = my_mmap,
};
static struct miscdevice my_misc = {
.minor = MISC_DYNAMIC_MINOR,
.fops = &my_fops,
.name = "my_name",
};
static int my_init(void)
{
int i;
for (i = 0; i < 2; i++)
ptr[i] = vmalloc_user(PAGE_SIZE);
for (i = 2; i < 4; i++)
ptr[i] = (void *) __get_free_page(GFP_KERNEL);
strcpy(ptr[0], "nazdar");
strcpy(ptr[1], "cau");
strcpy(ptr[2], "ahoj");
strcpy(ptr[3], "bye");
return misc_register(&my_misc);
}
static void my_exit(void)
{
int i;
for (i = 0; i < 2; i++)
vfree(ptr[i]);
for (i = 2; i < 4; i++)
free_page((unsigned long) ptr[i]);
misc_deregister(&my_misc);
}
module_init(my_init);
module_exit(my_exit);
MODULE_LICENSE("GPL");
<file_sep>ioctl argument pro nastaveni poctu znaku je 1074033665
ioctl argument pro zjisteni poctu znaku je 2148037634
<file_sep>#include <linux/io.h>
#include <linux/module.h>
#include <linux/delay.h>
#include <linux/pci.h>
#include <linux/timer.h>
#include <linux/interrupt.h>
#define VENDOR 0x18ec
#define DEVICE 0xc058
#define REGION 0
#define INT_ENABLE(addr) ((addr)+0x0044)
#define INT_RAISED(addr) ((addr)+0x0040)
#define INT_RAISE(addr) ((addr)+0x0060)
#define INT_ACK(addr) ((addr)+0x0064)
#define TIMER_MSEC 100
/* pointer to requested region (static, this will work only for one card!) */
void *regionPtr;
static irqreturn_t my_handler(int irq, void *data, struct pt_regs *ptr)
{
if (!printk_ratelimit()) {
printk(KERN_INFO "Combo IRQ: offset 0x0040: %x\n",
readl(INT_RAISED(regionPtr)));
}
if (readl(INT_RAISED(regionPtr))) {
writel(0x1000, INT_ACK(regionPtr));
return IRQ_HANDLED;
}
return IRQ_NONE;
}
static void my_func(unsigned long data);
static DEFINE_TIMER(my_timer, my_func, 0, 30);
/* timer function */
static void my_func(unsigned long data)
{
writel(0x1000, INT_RAISE(regionPtr));
mod_timer(&my_timer, jiffies + msecs_to_jiffies(TIMER_MSEC));
}
int my_probe(struct pci_dev *pdev, const struct pci_device_id *id)
{ /* variable to hold read time field */
u32 time;
int ret;
printk(KERN_INFO "Adding driver for device [%.4x:%.4x]\n",
VENDOR, DEVICE);
/* enable device */
if (pci_enable_device(pdev) != 0)
return -EIO;
/* request region, undo previous on fail */
if (pci_request_region(pdev, REGION, "my_driver") != 0) {
pci_disable_device(pdev);
return -EIO;
}
/* remap region, undo previous actions on fail */
regionPtr = pci_ioremap_bar(pdev, REGION);
if (regionPtr == NULL) {
pci_disable_device(pdev);
pci_release_region(pdev, REGION);
return -EIO;
}
/* print physical memory address */
printk(KERN_INFO "Region %i phys addr: %lx\n", REGION,
(unsigned long) pci_resource_start(pdev, REGION));
/* read time data */
time = readl(regionPtr+4);
/* print formatted time data */
printk(KERN_INFO "ID & revision: %.8x, %s %.4i/%.2i/%.2i %.2i:%.2i\n",
readl(regionPtr), "build time (YYYY/MM/DD hh:mm):",
((time & 0xF0000000) >> 28) + 2000, (time & 0x0F000000) >> 24,
(time & 0x00FF0000) >> 16, (time & 0x0000FF00) >> 8,
time & 0x000000FF);
/* setup IRQ */
ret = request_irq(pdev->irq, my_handler, IRQF_SHARED, "my_interrupt",
(void *) regionPtr);
if (ret != 0) {
printk(KERN_INFO "Cannot request irq\n");
pci_disable_device(pdev);
pci_release_region(pdev, REGION);
}
/* allow interrupts in card */
writel(0x1000, INT_ENABLE(regionPtr));
/* start the timer */
mod_timer(&my_timer, jiffies);
return 0;
}
void my_remove(struct pci_dev *pdev)
{
/* stop the timer*/
del_timer_sync(&my_timer);
/* remove IRQ */
free_irq(pdev->irq, (void *) regionPtr);
printk(KERN_INFO "Removing driver for device [%.4x:%.4x]\n",
VENDOR, DEVICE);
/* unmap requested region */
iounmap(regionPtr);
/* release the region */
pci_release_region(pdev, REGION);
/* disable the device */
pci_disable_device(pdev);
}
struct pci_device_id my_table[] = {
{PCI_DEVICE(VENDOR, DEVICE)},
{0,}
};
struct pci_driver my_pci_driver = {
.name = "my_driver",
.id_table = my_table,
.probe = my_probe,
.remove = my_remove,
};
MODULE_DEVICE_TABLE(pci, my_table);
static int my_init(void)
{
return pci_register_driver(&my_pci_driver);
}
static void my_exit(void)
{
pci_unregister_driver(&my_pci_driver);
}
module_init(my_init);
module_exit(my_exit);
MODULE_LICENSE("GPL");
<file_sep>#include <linux/module.h>
#include <linux/slab.h>
#include <linux/device.h>
#include <linux/jiffies.h>
void my_function(void)
{
}
static int my_init(void)
{
void *p = kmalloc(10, GFP_KERNEL);
char c;
if (p)
printk(KERN_INFO "%p", p);
kfree(p);
printk(KERN_INFO "%p", &c);
printk(KERN_INFO "%p", &jiffies);
printk(KERN_INFO "%p", &my_function);
printk(KERN_INFO "%p", &bus_register);
printk(KERN_INFO "%pF", __builtin_return_address(0));
return 0;
}
static void my_exit(void)
{
char *str = kmalloc(100, GFP_KERNEL);
if (str) {
strcpy(str, "Bye");
printk(KERN_INFO "%s", str);
}
kfree(str);
}
module_init(my_init);
module_exit(my_exit);
MODULE_LICENSE("GPL");
<file_sep>#include <linux/io.h>
#include <linux/module.h>
#include <linux/delay.h>
#include <linux/pci.h>
#include <linux/timer.h>
#include <linux/interrupt.h>
#include <linux/dma-mapping.h>
#include <linux/miscdevice.h>
#define VENDOR 0x18ec
#define DEVICE 0xc058
#define REGION 0
#define INT_ENABLE(addr) ((addr)+0x0044)
#define INT_RAISED(addr) ((addr)+0x0040)
#define INT_RAISE(addr) ((addr)+0x0060)
#define INT_ACK(addr) ((addr)+0x0064)
#define DMA_SRC(addr) ((addr)+0x0080)
#define DMA_DST(addr) ((addr)+0x0084)
#define DMA_COUNT(addr) ((addr)+0x0088)
#define DMA_CMD(addr) ((addr)+0x008c)
#define TIMER_MSEC 100
/* pointer to requested region (static, this will work only for one card!) */
struct holder {
void *regionPtr;
dma_addr_t phys;
void *virt;
struct tasklet_struct *tasklet;
};
/* store the pointer to virt memory for misc device */
void *miscPtr;
static irqreturn_t my_handler(int irq, void *data, struct pt_regs *ptr)
{
u32 intr = 0;
struct holder *holder = (struct holder *) data;
if (printk_ratelimit()) {
printk(KERN_INFO "Combo IRQ: offset 0x0040: %x\n",
readl(INT_RAISED(holder->regionPtr)));
}
/* read which interrupt arrived */
intr = readl(INT_RAISED(holder->regionPtr));
switch (intr) {
case 0x0100:
writel(0x1 << 31, DMA_CMD(holder->regionPtr));
writel(intr, INT_ACK(holder->regionPtr));
/* schedule the tasklet to write out the output */
tasklet_schedule(holder->tasklet);
return IRQ_HANDLED;
default: return IRQ_NONE;
}
}
void tasklet_func(unsigned long data)
{
printk(KERN_INFO "%s\n", ((char *) data)+20);
}
struct page *my_nopage(struct vm_area_struct *vma, unsigned long address,
int *type)
{
unsigned long offset = vma->vm_pgoff << PAGE_SHIFT;
struct page *page = NULL;
int offset_page;
offset += address - vma->vm_start;
offset_page = offset / PAGE_SIZE;
if (offset_page == 0)
page = virt_to_page(miscPtr);
if (!page)
return NOPAGE_SIGBUS;
get_page(page);
if (type)
*type = VM_FAULT_MINOR;
return page;
}
struct vm_operations_struct vos = {
.nopage = &my_nopage,
};
int my_mmap(struct file *filp, struct vm_area_struct *vma)
{
vma->vm_ops = &vos;
return 0;
}
static const struct file_operations my_fops = {
.owner = THIS_MODULE,
.mmap = my_mmap,
};
static struct miscdevice my_misc = {
.minor = MISC_DYNAMIC_MINOR,
.fops = &my_fops,
.name = "my_device",
};
int my_probe(struct pci_dev *pdev, const struct pci_device_id *id)
{ /* variable to hold read time field */
u32 time;
int ret;
struct holder *holder;
printk(KERN_INFO "Adding driver for device [%.4x:%.4x]\n",
VENDOR, DEVICE);
/* enable device */
if (pci_enable_device(pdev) != 0)
return -EIO;
/* request region, undo previous on fail */
if (pci_request_region(pdev, REGION, "my_driver") != 0) {
pci_disable_device(pdev);
return -EIO;
}
/* allocate structure to hold others */
holder = kmalloc(sizeof(struct holder), GFP_KERNEL);
if (holder == NULL) {
pci_disable_device(pdev);
pci_release_region(pdev, REGION);
return -EIO;
}
/* create new tasklet */
holder->tasklet = kmalloc(sizeof(struct tasklet_struct), GFP_KERNEL);
if (holder->tasklet == NULL) {
kfree(holder);
pci_disable_device(pdev);
pci_release_region(pdev, REGION);
return -EIO;
}
/* remap region, undo previous actions on fail */
holder->regionPtr = pci_ioremap_bar(pdev, REGION);
if (holder->regionPtr == NULL) {
kfree(holder->tasklet);
kfree(holder);
pci_disable_device(pdev);
pci_release_region(pdev, REGION);
return -EIO;
}
/* set local data for this device */
pci_set_drvdata(pdev, (void *) holder);
/* print physical memory address */
printk(KERN_INFO "Region %i phys addr: %lx\n", REGION,
(unsigned long) pci_resource_start(pdev, REGION));
/* read time data */
time = readl(holder->regionPtr+4);
/* print formatted time data */
printk(KERN_INFO "ID & revision: %.8x, %s %.4i/%.2i/%.2i %.2i:%.2i\n",
readl(holder->regionPtr), "build time (YYYY/MM/DD hh:mm):",
((time & 0xF0000000) >> 28) + 2000, (time & 0x0F000000) >> 24,
(time & 0x00FF0000) >> 16, (time & 0x0000FF00) >> 8,
time & 0x000000FF);
/* setup IRQ */
ret = request_irq(pdev->irq, my_handler, IRQF_SHARED, "my_interrupt",
(void *) holder);
if (ret != 0) {
printk(KERN_INFO "Cannot request irq\n");
kfree(holder->tasklet);
kfree(holder);
pci_disable_device(pdev);
pci_release_region(pdev, REGION);
return -EIO;
}
/* setup DMA */
pci_set_dma_mask(pdev, DMA_BIT_MASK(32));
pci_set_master(pdev);
holder->virt = dma_alloc_coherent(&pdev->dev, PAGE_SIZE, &holder->phys,
GFP_KERNEL);
/* initialise tasklet (we have the virt memory pointer now) */
tasklet_init(holder->tasklet, &tasklet_func,
(unsigned long) holder->virt);
/* register the device that allows to mmap the memory */
/* let the device access the memory: won't work with multiple devs */
miscPtr = holder->virt;
ret = misc_register(&my_misc);
if (ret != 0) {
dma_free_coherent(&pdev->dev, PAGE_SIZE, holder->virt,
holder->phys);
kfree(holder->tasklet);
kfree(holder);
pci_disable_device(pdev);
pci_release_region(pdev, REGION);
return ret;
}
/* allow interrupts in card */
writel(0x1000|0x0100, INT_ENABLE(holder->regionPtr));
/* copy to card */
strcpy(holder->virt, "retezec10b");
writel(holder->phys, DMA_SRC(holder->regionPtr));
writel(0x40000, DMA_DST(holder->regionPtr));
writel(10, DMA_COUNT(holder->regionPtr));
writel(0x1 | (0x1 << 7) | (0x2 << 1) | (0x4 << 4),
DMA_CMD(holder->regionPtr));
/* wait for the transfer to finish */
while (readl(DMA_CMD(holder->regionPtr)) & 0x01)
;
/* copy from card */
writel(0x40000, DMA_SRC(holder->regionPtr));
writel(holder->phys+10, DMA_DST(holder->regionPtr));
writel(10, DMA_COUNT(holder->regionPtr));
writel(0x1 | (0x1 << 7) | (0x2 << 4) | (0x4 << 1),
DMA_CMD(holder->regionPtr));
/* wait for the transfer to finish */
while (readl(DMA_CMD(holder->regionPtr)) & 0x01)
;
/* copy from card with IRQ */
writel(0x40000, DMA_SRC(holder->regionPtr));
writel(holder->phys+20, DMA_DST(holder->regionPtr));
writel(10, DMA_COUNT(holder->regionPtr));
writel(0x1 | (0x2 << 4) | (0x4 << 1), DMA_CMD(holder->regionPtr));
return 0;
}
void my_remove(struct pci_dev *pdev)
{
struct holder *holder = (struct holder *) pci_get_drvdata(pdev);
printk(KERN_INFO "Removing driver for device [%.4x:%.4x]\n",
VENDOR, DEVICE);
/* disable interrups */
writel(0x0000, INT_ENABLE(holder->regionPtr));
/* remove IRQ */
free_irq(pdev->irq, (void *) holder);
/* remove the device that mmaps the memory */
misc_deregister(&my_misc);
/* free DMA memory */
dma_free_coherent(&pdev->dev, PAGE_SIZE, holder->virt, holder->phys);
/* unmap requested region */
iounmap(holder->regionPtr);
/* stop and delete the tasklet */
tasklet_kill(holder->tasklet);
kfree(holder->tasklet);
/* free the holder structure */
kfree(holder);
/* release the region */
pci_release_region(pdev, REGION);
/* disable the device */
pci_disable_device(pdev);
}
struct pci_device_id my_table[] = {
{PCI_DEVICE(VENDOR, DEVICE)},
{0,}
};
struct pci_driver my_pci_driver = {
.name = "my_driver",
.id_table = my_table,
.probe = my_probe,
.remove = my_remove,
};
MODULE_DEVICE_TABLE(pci, my_table);
static int my_init(void)
{
return pci_register_driver(&my_pci_driver);
}
static void my_exit(void)
{
pci_unregister_driver(&my_pci_driver);
}
module_init(my_init);
module_exit(my_exit);
MODULE_LICENSE("GPL");
<file_sep>#include <linux/module.h>
#include <linux/etherdevice.h>
#include <linux/netdevice.h>
#include <linux/skbuff.h>
#include <linux/kfifo.h>
#include <linux/miscdevice.h>
#define FIFO_SIZE 4096
/* define up structure for eth devise */
struct net_device *myeth;
struct net_device_ops myops;
/* define fifo for data */
DEFINE_KFIFO(myfifo, char, FIFO_SIZE);
/* eth device open function */
int my_open(struct net_device *dev)
{
printk(KERN_INFO "my_open\n");
return 0;
}
/* eth device close function */
int my_close(struct net_device *dev)
{
printk(KERN_INFO "my_close\n");
return 0;
}
/* eth device xmit function */
int my_xmit(struct sk_buff *buff, struct net_device *dev)
{
printk(KERN_INFO "my_xmit\n");
/* just copy the data to the buffer */
kfifo_in(&myfifo, buff->data, buff->len);
dev_kfree_skb(buff);
return NETDEV_TX_OK;
}
static ssize_t my_write(struct file *filp, const char __user *buf, size_t count,
loff_t *off)
{
ssize_t ret = count;
/* create the sk_buff structure */
struct sk_buff *skb = netdev_alloc_skb(myeth, count);
skb->len = ret;
/* copy the data from user to the structure */
if (copy_from_user(skb->data, buf, count))
ret = -EFAULT;
/* set protocol and transmit the data */
skb->protocol = (eth_type_trans(skb, myeth));
netif_rx(skb);
return ret;
}
static ssize_t my_read(struct file *filp, char __user *buf, size_t count,
loff_t *off)
{
int read;
/* just read the data from fifo to user */
if (kfifo_to_user(&myfifo, buf, count, &read))
return -EFAULT;
return read;
}
static const struct file_operations my_fops = {
.owner = THIS_MODULE,
.read = my_read,
.write = my_write,
};
static struct miscdevice my_misc = {
.minor = MISC_DYNAMIC_MINOR,
.fops = &my_fops,
.name = "my_name",
};
static int my_init(void)
{
/* setup the eth device */
myeth = alloc_etherdev(0);
if (myeth == NULL)
return -EFAULT;
myeth->netdev_ops = &myops;
myops.ndo_open = &my_open;
myops.ndo_stop = &my_close;
myops.ndo_start_xmit = &my_xmit;
random_ether_addr(myeth->dev_addr);
if (register_netdev(myeth)) {
free_netdev(myeth);
return -EFAULT;
}
/* register the misc device */
if (misc_register(&my_misc)) {
unregister_netdev(myeth);
free_netdev(myeth);
return -EFAULT;
}
return 0;
}
static void my_exit(void)
{
/* deregister the devices */
misc_deregister(&my_misc);
unregister_netdev(myeth);
free_netdev(myeth);
}
module_init(my_init);
module_exit(my_exit);
MODULE_LICENSE("GPL");
<file_sep>#include <linux/io.h>
#include <linux/module.h>
#include <linux/delay.h>
#include <linux/pci.h>
#define VENDOR 0x18ec
#define DEVICE 0xc058
#define REGION 0
/* pointer to requested region */
void *regionPtr;
int my_probe(struct pci_dev *pdev, const struct pci_device_id *id)
{ /* variable to hold read time field */
u32 time;
printk(KERN_INFO "Adding driver for device [%.4x:%.4x]\n",
VENDOR, DEVICE);
/* enable device */
if (pci_enable_device(pdev) != 0)
return -EIO;
/* request region, undo previous on fail */
if (pci_request_region(pdev, REGION, "my_driver") != 0) {
pci_disable_device(pdev);
return -EIO;
}
/* remap region, undo previous actions on fail */
regionPtr = pci_ioremap_bar(pdev, REGION);
if (regionPtr == NULL) {
pci_disable_device(pdev);
pci_release_region(pdev, REGION);
return -EIO;
}
/* print physical memory address */
printk(KERN_INFO "Region %i phys addr: %lx\n", REGION,
(unsigned long) pci_resource_start(pdev, REGION));
/* read time data */
time = readl(regionPtr+4);
/* print formatted time data */
printk(KERN_INFO "ID & revision: %.8x, %s %.4i/%.2i/%.2i %.2i:%.2i\n",
readl(regionPtr), "build time (YYYY/MM/DD hh:mm):",
((time & 0xF0000000) >> 28) + 2000, (time & 0x0F000000) >> 24,
(time & 0x00FF0000) >> 16, (time & 0x0000FF00) >> 8,
time & 0x000000FF);
return 0;
}
void my_remove(struct pci_dev *pdev)
{
printk(KERN_INFO "Removing driver for device [%.4x:%.4x]\n",
VENDOR, DEVICE);
iounmap(regionPtr);
pci_release_region(pdev, REGION);
pci_disable_device(pdev);
}
DEFINE_PCI_DEVICE_TABLE(my_table) = {
{PCI_DEVICE(VENDOR, DEVICE)},
{0,}
};
struct pci_driver my_pci_driver = {
.name = "my_driver",
.id_table = my_table,
.probe = my_probe,
.remove = my_remove,
};
MODULE_DEVICE_TABLE(pci, my_table);
static int my_init(void)
{
return pci_register_driver(&my_pci_driver);
}
static void my_exit(void)
{
pci_unregister_driver(&my_pci_driver);
}
module_init(my_init);
module_exit(my_exit);
MODULE_LICENSE("GPL");
<file_sep>#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/miscdevice.h>
#include <linux/module.h>
#include <linux/string.h>
#include <linux/uaccess.h>
#include <linux/delay.h>
char buff[128];
DEFINE_MUTEX(lock);
static ssize_t my_read(struct file *filp, char __user *buf, size_t count,
loff_t *off)
{
int c;
if (*off >= sizeof(buff) || !count)
return 0;
c = (count + *off >= sizeof(buff)) ? sizeof(buff) - *off : count;
/* lock before reading the buffer */
mutex_lock(&lock);
if (copy_to_user(buf, &buff[*off], c) != 0) {
mutex_unlock(&lock);
return -EFAULT;
}
/* unlock after reading the buffer */
mutex_unlock(&lock);
*off += c;
return c;
}
ssize_t my_write(struct file *file, const char __user *ptr, size_t count,
loff_t *off)
{
int c, i;
if (*off >= sizeof(buff) || !count)
return 0;
/* allow at most 5 characters */
c = (count > 5) ? 5 : count;
/* check how much space remains in the buffer */
if (sizeof(buff) - *off < c)
c = sizeof(buff) - *off;
/* critical section: work with buffer */
mutex_lock(&lock);
/* copy to buffer one character per iteration */
for (i = 0; i < c; i++) {
if (copy_from_user(&buff[*off+i], ptr+i, 1) != 0) {
/* don't forget to release the lock on error */
mutex_unlock(&lock);
return -EFAULT;
}
msleep(10);
}
*off += c;
/* unlock after write */
mutex_unlock(&lock);
/* debug output */
printk(KERN_INFO "User wrote: \"%s\"\n", buff);
return c;
}
static const struct file_operations my_fops_read = {
.owner = THIS_MODULE,
.read = my_read,
};
static struct miscdevice my_misc_read = {
.minor = MISC_DYNAMIC_MINOR,
.fops = &my_fops_read,
.name = "mydeviceR",
};
static const struct file_operations my_fops_write = {
.owner = THIS_MODULE,
.write = my_write,
};
static struct miscdevice my_misc_write = {
.minor = MISC_DYNAMIC_MINOR,
.fops = &my_fops_write,
.name = "mydeviceW",
};
static int my_init(void)
{
int err;
err = misc_register(&my_misc_write);
if (err != 0)
return err;
return misc_register(&my_misc_read);
}
static void my_exit(void)
{
misc_deregister(&my_misc_write);
misc_deregister(&my_misc_read);
}
module_init(my_init);
module_exit(my_exit);
MODULE_LICENSE("GPL");
|
46b0f025673136df445c590a7cc565e00e39c3f3
|
[
"C",
"Text"
] | 11
|
C
|
thorgrin/pb173
|
8f8f434b3f4bd5d180e685214e00624e60e32cb6
|
fe00bcb99d7cc4e7fa30c34f942163c2009620ca
|
refs/heads/master
|
<file_sep># dungeons-and-pythons<file_sep>class Weapon:
def __init__(self, name, damage=0):
self.name = name
self.damage = damage
class Spell(Weapon):
def __init__(self, name, damage, mana_cost, cast_range):
super.__init__(self, name, damage)
self.mana_cost = mana_cost
self.cast_range = cast_range
<file_sep>class BaseClass:
def __init__(self, health, mana):
self.health = health
self.mana = mana
self.max_health = health
self.equipped_weapon = None
self.equipped_spell = None
def get_health(self):
return self.health
def get_mana(self):
return self.mana
def is_alive(self):
if self.health < 1:
return False
return True
def can_cast(self, distance_to_enemy):
if self.mana >= self.equipped_spell.mana_cost and self.equipped_spell.cast_range >= distance_to_enemy:
return True
else:
return False
def take_damage(self, damage_points):
if self.health < damage_points:
self.health = 0
else:
self.health -= damage_points
def take_healing(self, healing_points):
if self.is_alive() is False:
return False
else:
if self.health + healing_points > self.max_health:
self.health = self.max_health
else:
self.health += healing_points
return True
def equip(self, weapon):
self.equipped_weapon = weapon
def learn(self, spell):
self.equipped_spell = spell
def attack(self, enemy, by=None):
if by == 'weapon':
if self.equipped_weapon:
enemy.health -= self.equipped_weapon.damage
if by == 'magic':
if self.can_cast():
enemy.health -= self.equipped_spell.damage
<file_sep>from base_class import BaseClass
class Hero(BaseClass):
def __init__(self, name, title, health, mana, mana_regeneration_rate):
super.__init__(self, health, mana)
self.name = name
self. title = title
self.mana_regeneration_rate = mana_regeneration_rate
self.max_mana = mana
self.location = None
def known_as(self):
return "{} the {}".format(self.name, self.title)
def take_mana(self, mana_points):
if self.mana + mana_points > self.max_mana:
self.mana = self.max_mana
else:
self.mana += mana_points
|
b73448c911a863e1b2ee7d90cf2518f18d03dbf5
|
[
"Markdown",
"Python"
] | 4
|
Markdown
|
nemalp/dungeons-and-pythons
|
9d2904fa72fd1c685d79927483f8430e9faa119f
|
399f3d72c1b581d39a37c4f900152b92b59fd5fb
|
refs/heads/master
|
<file_sep>package com.arch.controller;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import com.arch.constants.Constants;
import com.arch.model.AllCategory;
import com.arch.model.Category;
import com.arch.model.Commercial;
import com.arch.model.Entrepot;
import com.arch.model.HotProduct;
import com.arch.model.Product;
import com.arch.model.Resource;
import com.arch.service.EntrepotService;
import com.arch.service.ProductService;
import com.arch.service.ResourceService;
import com.arch.tools.Tools;
@Controller
@RequestMapping("/product")
public class ProductController{
@Autowired
private ProductService productService;
@Autowired
private EntrepotService entrepotService;
@Autowired
private ResourceService resourceService;
@RequestMapping("/save")
public String save(HttpServletRequest request,HttpServletResponse response){
JSONObject json = new JSONObject();
Product product = new Product();
// String createUser = request.getParameter("createUser") != null ? request.getParameter("createUser") : ((Commercial) request.getSession().getAttribute("commercial")).getCommercialName();
try {
product.setAdvertise(request.getParameter("advertise"));
product.setBradeId(Long.parseLong(request.getParameter("bradeId")));
product.setCategoryId(request.getParameter("categoryId"));
product.setCostPrice(request.getParameter("costPrice"));//成本价
product.setDescription(request.getParameter("description"));
product.setEntrepotId(Long.parseLong(request.getParameter("entrepotId")));
product.setIsPopular(request.getParameter("isPopular"));//是否推广
product.setStatus("入库");
product.setType(request.getParameter("type"));
product.setKeyWord(request.getParameter("keyWord"));//关键词
product.setPrice(request.getParameter("price"));//售价
product.setPriceSection(request.getParameter("priceSection"));//价格区间
product.setProduceAddr(request.getParameter("produceAddr"));//产地
product.setProductName(request.getParameter("productName"));
product.setRepelnDesc(request.getParameter("repelnDesc"));//补充说明
product.setRepertoryCount(Long.parseLong(request.getParameter("repertoryCount")));//库存
product.setSelfSupport(request.getParameter("selfSupport"));//是否自营
product.setSupply(request.getParameter("supply"));//厂商
product.setCreateTime(Tools.formatDate(new Date()));
product.setCreateUser("");
product.setRemark(request.getParameter("remark"));
product.setBrandName(request.getParameter("brandName"));
Long returnCode = productService.save(product);
//这样就得到了自增的id
if(null != returnCode){//返回保存的id值
long startTime=System.currentTimeMillis();
//将当前上下文初始化给 CommonsMutipartResolver (多部分解析器)
CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(
request.getSession().getServletContext());
//检查form中是否有enctype="multipart/form-data"
if(multipartResolver.isMultipart(request))
{
List<Resource> resourceList = new ArrayList<Resource>();
//将request变成多部分request
MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;
//获取multiRequest 中所有的文件名
Iterator iter=multiRequest.getFileNames();
String realPath = request.getSession().getServletContext().getRealPath("resouce");
int i = 0;
while(iter.hasNext())
{
i++;
//一次遍历所有文件
MultipartFile file=multiRequest.getFile(iter.next().toString());
if(file!=null)
{
String uuid = UUID.randomUUID().toString();
String [] fileNameArr = file.getOriginalFilename().split("\\.");
String fileName = uuid + "." + fileNameArr[1];
// String path=realPath+"/"+file.getOriginalFilename();
String path=realPath+"/"+fileName;
//上传
file.transferTo(new File(path));
Resource resource = new Resource();
resource.setUrl("resouce/"+fileName);
resource.setProductId(product.getProductId());
resource.setSort(i+"");
resource.setCreateUser("");
resource.setCreateTime(Tools.formatDate(new Date()));
resourceList.add(resource);
}
}
//上传完成,将资源数据保存至数据库
//TODO 后期优化为批量操作
// resourceService.batchSave(resourceList);
if(null!=resourceList && resourceList.size() > 0){
for(Resource resource:resourceList){
resourceService.save(resource);
}
}
}
long endTime=System.currentTimeMillis();
// System.out.println("方法三的运行时间:"+String.valueOf(endTime-startTime)+"ms");
}
json.put("returnCode", Constants.SUCCESS_CODE);
json.put("returnMsg", Constants.SUCCESS_MSG);
json.put("addCode", returnCode);
// Tools.returnAjaxDataOut(json,response);
} catch (Exception e) {
e.printStackTrace();
json.put("returnCode", Constants.FAILUER_CODE);
json.put("returnMsg", e.getLocalizedMessage());
try {
Tools.returnAjaxDataOut(json,response);
} catch (IOException e1) {
e1.printStackTrace();
}
}
request.setAttribute("entrepotId", request.getParameter("entrepotId"));
return "/admin/productList";
}
@RequestMapping("/likeProducts")
public void likeProducts(HttpServletRequest request,HttpServletResponse response){
JSONObject json = new JSONObject();
Product product = new Product();
try {
product.setAdvertise(request.getParameter("advertise"));
Long bradeId = null;
if(request.getParameter("bradeId") != null){
bradeId = Long.parseLong(request.getParameter("bradeId"));
}
Long productId = null;
if(request.getParameter("productId") != null){
productId = Long.parseLong(request.getParameter("productId"));
}
product.setBradeId(bradeId);
product.setBrandName(request.getParameter("brandName"));
product.setIsNew(request.getParameter("isNew"));
product.setIsUse(request.getParameter("isUse"));
product.setProductId(productId);
product.setType(request.getParameter("type"));
product.setCategoryId(request.getParameter("categoryId"));
product.setCostPrice(request.getParameter("costPrice"));//成本价
product.setDescription(request.getParameter("description"));
Long entrepotId = null;
if(request.getParameter("entrepotId") != null){
entrepotId = Long.parseLong(request.getParameter("entrepotId"));
}
product.setEntrepotId(entrepotId);
product.setIsPopular(request.getParameter("isPopular"));//是否推广
product.setKeyWord(request.getParameter("keyWord"));//关键词
product.setPrice(request.getParameter("price"));//售价
product.setPriceSection(request.getParameter("priceSection"));//价格区间
product.setProduceAddr(request.getParameter("produceAddr"));//产地
product.setProductName(request.getParameter("productName"));
product.setRepelnDesc(request.getParameter("repelnDesc"));//补充说明
Long repertoryCount = null;
if(request.getParameter("repertoryCount") != null){
repertoryCount = Long.parseLong(request.getParameter("repertoryCount"));
}
product.setRepertoryCount(repertoryCount);//库存
product.setSelfSupport(request.getParameter("selfSupport"));//是否自营
product.setStatus(request.getParameter("status"));
product.setSupply(request.getParameter("supply"));//厂商
product.setCreateTime(request.getParameter("createTime"));
product.setCreateUser(request.getParameter("createUser"));
product.setUpdateTime(request.getParameter("updateTime"));
product.setUpdateUser(request.getParameter("updateUser"));
product.setRemark(request.getParameter("remark"));
product.setUserLocation(request.getParameter("userLocation"));
List<Product> likeProducts = productService.likeProducts(product);
for (int i = 0; i < likeProducts.size(); i++) {
Resource re = new Resource();
re.setProductId(likeProducts.get(i).getProductId());
List<Resource> resourceList = resourceService.findByProAndType(re);
likeProducts.get(i).setResourceList(resourceList);
resourceList=null;
}
json.put("returnCode", Constants.SUCCESS_CODE);
json.put("returnMsg", Constants.SUCCESS_MSG);
json.put("likeProducts", likeProducts);
Tools.returnAjaxDataOut(json,response);
} catch (Exception e) {
e.printStackTrace();
json.put("returnCode", Constants.FAILUER_CODE);
json.put("returnMsg", e.getLocalizedMessage());
try {
Tools.returnAjaxDataOut(json,response);
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
@RequestMapping("/isHot")
public void isHot(HttpServletRequest request,HttpServletResponse response){
JSONObject json = new JSONObject();
Product product = new Product();
try {
product.setIsHot("1");
List<HotProduct> likeProducts = productService.isHot(product);
/*for (int i = 0; i < likeProducts.size(); i++) {
Resource re = new Resource();
re.setProductId(likeProducts.get(i).getProductId());
List<Resource> resourceList = resourceService.findByProAndType(re);
likeProducts.get(i).setResourceList(resourceList);
resourceList=null;
}*/
json.put("returnCode", Constants.SUCCESS_CODE);
json.put("returnMsg", Constants.SUCCESS_MSG);
json.put("likeProducts", likeProducts);
Tools.returnAjaxDataOut(json,response);
} catch (Exception e) {
e.printStackTrace();
json.put("returnCode", Constants.FAILUER_CODE);
json.put("returnMsg", e.getLocalizedMessage());
try {
Tools.returnAjaxDataOut(json,response);
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
@RequestMapping("/saveApp")
public void saveApp(HttpServletRequest request,HttpServletResponse response){
JSONObject json = new JSONObject();
Product product = new Product();
String createUser = request.getParameter("createUser") != null ? request.getParameter("createUser") : ((Commercial) request.getSession().getAttribute("commercial")).getCommercialName();
try {
product.setAdvertise(request.getParameter("advertise"));
product.setBradeId(Long.parseLong(request.getParameter("bradeId")));
product.setBrandName(request.getParameter("brandName"));
product.setCategoryId(request.getParameter("categoryId"));
product.setCostPrice(request.getParameter("costPrice"));//成本价
product.setDescription(request.getParameter("description"));
product.setEntrepotId(Long.parseLong(request.getParameter("entrepotId")));
product.setIsPopular(request.getParameter("isPopular"));//是否推广
product.setIsNew(request.getParameter("isNew"));
product.setStatus("入库");
product.setType(request.getParameter("type"));
product.setKeyWord(request.getParameter("keyWord"));//关键词
product.setPrice(request.getParameter("price"));//售价
product.setPriceSection(request.getParameter("priceSection"));//价格区间
product.setProduceAddr(request.getParameter("produceAddr"));//产地
product.setProductName(request.getParameter("productName"));
product.setRepelnDesc(request.getParameter("repelnDesc"));//补充说明
product.setRepertoryCount(Long.parseLong(request.getParameter("repertoryCount")));//库存
product.setSelfSupport(request.getParameter("selfSupport"));//是否自营
product.setStatus(request.getParameter("status"));
product.setSupply(request.getParameter("supply"));//厂商
product.setCreateTime(Tools.formatDate(new Date()));
product.setCreateUser(createUser);
product.setRemark(request.getParameter("remark"));
Long returnCode = productService.save(product);
//这样就得到了自增的id
if(null != returnCode){//返回保存的id值
long startTime=System.currentTimeMillis();
//将当前上下文初始化给 CommonsMutipartResolver (多部分解析器)
CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(
request.getSession().getServletContext());
//检查form中是否有enctype="multipart/form-data"
if(multipartResolver.isMultipart(request))
{
List<Resource> resourceList = new ArrayList<Resource>();
//将request变成多部分request
MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;
//获取multiRequest 中所有的文件名
Iterator iter=multiRequest.getFileNames();
String realPath = request.getSession().getServletContext().getRealPath("resouce");
int i = 0;
while(iter.hasNext())
{
i++;
//一次遍历所有文件
MultipartFile file=multiRequest.getFile(iter.next().toString());
if(file!=null)
{
String uuid = UUID.randomUUID().toString();
String [] fileNameArr = file.getOriginalFilename().split("\\.");
String fileName = uuid + "." + fileNameArr[1];
// String path=realPath+"/"+file.getOriginalFilename();
String path=realPath+"/"+fileName;
//上传
file.transferTo(new File(path));
Resource resource = new Resource();
resource.setUrl("resouce/"+fileName);
resource.setProductId(product.getProductId());
resource.setSort(i+"");
resource.setCreateUser(createUser);
resource.setCreateTime(Tools.formatDate(new Date()));
resourceList.add(resource);
}
}
//上传完成,将资源数据保存至数据库
//TODO 后期优化为批量操作
// resourceService.batchSave(resourceList);
if(null!=resourceList && resourceList.size() > 0){
for(Resource resource:resourceList){
resourceService.save(resource);
}
}
}
long endTime=System.currentTimeMillis();
// System.out.println("方法三的运行时间:"+String.valueOf(endTime-startTime)+"ms");
}
json.put("returnCode", Constants.SUCCESS_CODE);
json.put("returnMsg", Constants.SUCCESS_MSG);
json.put("addCode", returnCode);
Tools.returnAjaxDataOut(json,response);
} catch (Exception e) {
e.printStackTrace();
json.put("returnCode", Constants.FAILUER_CODE);
json.put("returnMsg", e.getLocalizedMessage());
// try {
// Tools.returnAjaxDataOut(json,response);
// } catch (IOException e1) {
// e1.printStackTrace();
// }
}
request.setAttribute("entrepotId", request.getParameter("entrepotId"));
}
@RequestMapping("/selectByCity")
public void selectByCity(HttpServletRequest request,HttpServletResponse response){
JSONObject json = new JSONObject();
try {
Map map = new HashMap();
map.put("type", request.getParameter("type"));//加盟商
map.put("city", request.getParameter("city"));
List<Product> products = productService.selectByCity(map);
json.put("returnCode", Constants.SUCCESS_CODE);
json.put("returnMsg", Constants.SUCCESS_MSG);
json.put("products", products);
json.put("isStop", 1);
Tools.returnAjaxDataOut(json,response);
} catch (Exception e) {
e.printStackTrace();
json.put("returnCode", Constants.FAILUER_CODE);
json.put("returnMsg", e.getLocalizedMessage());
try {
Tools.returnAjaxDataOut(json,response);
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
@RequestMapping("/selectByGroupType")
public void selectByGroupType(HttpServletRequest request,HttpServletResponse response){
JSONObject json = new JSONObject();
try {
Map map = new HashMap();
map.put("type", request.getParameter("type"));//加盟商
List<Category> categories = productService.selectByGroupType(map);
json.put("returnCode", Constants.SUCCESS_CODE);
json.put("returnMsg", Constants.SUCCESS_MSG);
json.put("categories", categories);
json.put("isStop", 1);
Tools.returnAjaxDataOut(json,response);
} catch (Exception e) {
e.printStackTrace();
json.put("returnCode", Constants.FAILUER_CODE);
json.put("returnMsg", e.getLocalizedMessage());
try {
Tools.returnAjaxDataOut(json,response);
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
@RequestMapping("/selectCategory")
public void selectCategory(HttpServletRequest request,HttpServletResponse response){
JSONObject json = new JSONObject();
try {
Map map = new HashMap();
map.put("type", request.getParameter("type"));//加盟商
List<AllCategory> allCategories = productService.selectCategory(map);
json.put("returnCode", Constants.SUCCESS_CODE);
json.put("returnMsg", Constants.SUCCESS_MSG);
json.put("categories", allCategories);
Tools.returnAjaxDataOut(json,response);
} catch (Exception e) {
e.printStackTrace();
json.put("returnCode", Constants.FAILUER_CODE);
json.put("returnMsg", e.getLocalizedMessage());
try {
Tools.returnAjaxDataOut(json,response);
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
@RequestMapping("/update")
public void update(HttpServletRequest request,HttpServletResponse response){
JSONObject json = new JSONObject();
Product product = new Product();
try {
product.setAdvertise(request.getParameter("advertise"));
Long bradeId = null;
if(request.getParameter("bradeId") != null){
bradeId = Long.parseLong(request.getParameter("bradeId"));
}
product.setBradeId(bradeId);
product.setBrandName(request.getParameter("brandName"));
product.setType(request.getParameter("type"));
product.setIsNew(request.getParameter("isNew"));
product.setCategoryId(request.getParameter("categoryId"));
product.setCostPrice(request.getParameter("costPrice"));//成本价
product.setDescription(request.getParameter("description"));
Long entrepotId = null;
if(request.getParameter("entrepotId") != null){
entrepotId = Long.parseLong(request.getParameter("entrepotId"));
}
product.setEntrepotId(entrepotId);
product.setProductId(Long.parseLong(request.getParameter("productId")));
product.setIsPopular(request.getParameter("isPopular"));//是否推广
product.setKeyWord(request.getParameter("keyWord"));//关键词
product.setPrice(request.getParameter("price"));//售价
product.setPriceSection(request.getParameter("priceSection"));//价格区间
product.setProduceAddr(request.getParameter("produceAddr"));//产地
product.setProductName(request.getParameter("productName"));
product.setRepelnDesc(request.getParameter("repelnDesc"));//补充说明
Long repertoryCount = null;
if(request.getParameter("repertoryCount") != null){
repertoryCount = Long.parseLong(request.getParameter("repertoryCount"));
}
product.setRepertoryCount(repertoryCount);//库存
product.setSelfSupport(request.getParameter("selfSupport"));//是否自营
product.setStatus(request.getParameter("status"));
product.setSupply(request.getParameter("supply"));//厂商
product.setUpdateTime(Tools.formatDate(new Date()));
product.setUpdateUser(request.getParameter("loginName"));
product.setRemark(request.getParameter("remark"));
product.setIsUse(request.getParameter("isUse"));
product.setIsHot(request.getParameter("isHot"));
int updCode = productService.update(product);
json.put("returnCode", Constants.SUCCESS_CODE);
json.put("returnMsg", Constants.SUCCESS_MSG);
json.put("updCode", updCode);
Tools.returnAjaxDataOut(json,response);
} catch (Exception e) {
e.printStackTrace();
json.put("returnCode", Constants.FAILUER_CODE);
json.put("returnMsg", e.getLocalizedMessage());
try {
Tools.returnAjaxDataOut(json,response);
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
/*@RequestMapping("/delete")
public void delete(HttpServletRequest request,HttpServletResponse response){
JSONObject json = new JSONObject();
try {
Long productId = Long.parseLong(request.getParameter("productId"));
int delCode = productService.delete(productId);
json.put("returnCode", Constants.SUCCESS_CODE);
json.put("returnMsg", Constants.SUCCESS_MSG);
json.put("delCode", delCode);
Tools.returnAjaxDataOut(json,response);
} catch (Exception e) {
e.printStackTrace();
json.put("returnCode", Constants.FAILUER_CODE);
json.put("returnMsg", e.getLocalizedMessage());
try {
Tools.returnAjaxDataOut(json,response);
} catch (IOException e1) {
e1.printStackTrace();
}
}
}*/
@RequestMapping("/likePageProducts")
public void likePageProducts(HttpServletRequest request,HttpServletResponse response){
JSONObject json = new JSONObject();
Product product = new Product();
int currentNum = request.getParameter("currentNum") == null ? 1 : Integer.parseInt(request.getParameter("currentNum"));
int pageSize = Constants.PAGE_SIZE;
int firstResult = (currentNum-1)*pageSize;
/*firstResult = (currentNum-1)*pageSize;
if(1 != currentNum){
firstResult = (currentNum-1)*pageSize + 1;
}else{
firstResult = (currentNum-1)*pageSize;
}*/
try {
product.setFirstResult(firstResult);
product.setPageSize(pageSize);
product.setAdvertise(request.getParameter("advertise"));
Long bradeId = null;
if(request.getParameter("bradeId") != null){
bradeId = Long.parseLong(request.getParameter("bradeId"));
}
product.setBradeId(bradeId);
product.setBrandName(request.getParameter("brandName"));
product.setType(request.getParameter("type"));
product.setCategoryId(request.getParameter("categoryId"));
product.setCostPrice(request.getParameter("costPrice"));//成本价
product.setDescription(request.getParameter("description"));
Long entrepotId = null;
if(request.getParameter("entrepotId") != null){
entrepotId = Long.parseLong(request.getParameter("entrepotId"));
}
product.setEntrepotId(entrepotId);
product.setIsPopular(request.getParameter("isPopular"));//是否推广
product.setKeyWord(request.getParameter("keyWord"));//关键词
product.setPrice(request.getParameter("price"));//售价
product.setPriceSection(request.getParameter("priceSection"));//价格区间
product.setProduceAddr(request.getParameter("produceAddr"));//产地
product.setProductName(request.getParameter("productName"));
product.setRepelnDesc(request.getParameter("repelnDesc"));//补充说明
Long repertoryCount = null;
if(request.getParameter("repertoryCount") != null){
repertoryCount = Long.parseLong(request.getParameter("repertoryCount"));
}
product.setRepertoryCount(repertoryCount);//库存
product.setSelfSupport(request.getParameter("selfSupport"));//是否自营
product.setStatus(request.getParameter("status"));
product.setSupply(request.getParameter("supply"));//厂商
product.setCreateTime(request.getParameter("createTime"));
product.setCreateUser(request.getParameter("createUser"));
product.setUpdateTime(request.getParameter("updateTime"));
product.setUpdateUser(request.getParameter("updateUser"));
product.setRemark(request.getParameter("remark"));
List<Product> likeProducts = productService.likePageProducts(product);
//总共的行数
int levelCount = productService.getCount(product);
//总共的页数
int pageCount=(int)Math.ceil(levelCount*1.0/pageSize);
json.put("returnCode", Constants.SUCCESS_CODE);
json.put("returnMsg", Constants.SUCCESS_MSG);
json.put("currentNum", currentNum);
json.put("pageCount", pageCount);
json.put("likeProducts", likeProducts);
Tools.returnAjaxDataOut(json,response);
} catch (Exception e) {
e.printStackTrace();
json.put("returnCode", Constants.FAILUER_CODE);
json.put("returnMsg", e.getLocalizedMessage());
try {
Tools.returnAjaxDataOut(json,response);
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
@RequestMapping("/findById")
public void findById(HttpServletRequest request,HttpServletResponse response){
JSONObject json = new JSONObject();
try {
Product product = productService.findById(Long.parseLong(request.getParameter("productId")));
Resource resource = new Resource();
resource.setProductId(Long.parseLong(request.getParameter("productId")));
List<Resource> resourceList = resourceService.findByProAndType(resource);
product.setResourceList(resourceList);
json.put("returnCode", Constants.SUCCESS_CODE);
json.put("returnMsg", Constants.SUCCESS_MSG);
json.put("product", product);
Tools.returnAjaxDataOut(json,response);
} catch (Exception e) {
e.printStackTrace();
json.put("returnCode", Constants.FAILUER_CODE);
json.put("returnMsg", e.getLocalizedMessage());
try {
Tools.returnAjaxDataOut(json,response);
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
@RequestMapping("/productList")
public String productList(HttpServletRequest request){
request.setAttribute("entrepotId", request.getParameter("entrepotId"));
return "/admin/productList";
}
@RequestMapping("/saveUI")
public String saveUI(HttpServletRequest request){
Long entrepotId = Long.parseLong(request.getParameter("entrepotId"));
Entrepot entrepot = entrepotService.findById(entrepotId);
request.setAttribute("entrepot", entrepot);
return "/admin/product/save";
}
@RequestMapping("/detailUI")
public String detailUI(HttpServletRequest request){
Long productId = Long.parseLong(request.getParameter("productId"));
request.setAttribute("productId", productId);
return "/admin/product/detail";
}
@RequestMapping("/findDetByH5Id")
public String findDetByH5Id(HttpServletRequest request){
Long productId = Long.parseLong(request.getParameter("productId"));
request.setAttribute("productId", productId);
return "/proDetH5";
}
}
|
6cdfca5a38c21cdf5e1c87ebca7990dfd27196ce
|
[
"Java"
] | 1
|
Java
|
baiwei0205/test
|
73c3c09e679e824139eb96fbbb2ff4bf5df77cdd
|
363d2044aaa1da317a3f4bdf5b69ffe95ee12279
|
refs/heads/master
|
<repo_name>sam888/jhipster_i18n<file_sep>/src/main/webapp/app/entities/resource-bundle/resource-bundle-util.js
(function() {
'use strict';
angular.module('jhipsterI18NApp').factory('ResourceBundleUtil', ResourceBundleUtil);
function ResourceBundleUtil() {
var factory = {};
factory.printLocale = function( locale ) {
if ( !locale ) return '';
return 'Name = ' + locale.name + ', Language Code = ' + locale.languageCode + ', Country Code = ' + locale.countryCode;
}
return factory;
}
})();
<file_sep>/src/main/webapp/app/entities/resource-bundle/resource-bundle.controller.js
(function() {
'use strict';
angular
.module('jhipsterI18NApp')
.controller('ResourceBundleController', ResourceBundleController);
ResourceBundleController.$inject = ['$scope', '$state', 'ResourceBundle', 'ResourceBundleSearch'];
function ResourceBundleController ($scope, $state, ResourceBundle, ResourceBundleSearch) {
var vm = this;
vm.resourceBundles = [];
vm.search = search;
vm.loadAll = loadAll;
loadAll();
function loadAll() {
ResourceBundle.query(function(result) {
vm.resourceBundles = result;
});
}
function search () {
if (!vm.searchQuery) {
return vm.loadAll();
}
ResourceBundleSearch.query({query: vm.searchQuery}, function(result) {
vm.resourceBundles = result;
});
} }
})();
<file_sep>/src/main/webapp/app/entities/resource-bundle/resource-bundle-delete-dialog.controller.js
(function() {
'use strict';
angular
.module('jhipsterI18NApp')
.controller('ResourceBundleDeleteController',ResourceBundleDeleteController);
ResourceBundleDeleteController.$inject = ['$uibModalInstance', 'entity', 'ResourceBundle'];
function ResourceBundleDeleteController($uibModalInstance, entity, ResourceBundle) {
var vm = this;
vm.resourceBundle = entity;
vm.clear = clear;
vm.confirmDelete = confirmDelete;
function clear () {
$uibModalInstance.dismiss('cancel');
}
function confirmDelete (id) {
ResourceBundle.delete({id: id},
function () {
$uibModalInstance.close(true);
});
}
}
})();
<file_sep>/src/main/webapp/app/entities/key-value/key-value-delete-dialog.controller.js
(function() {
'use strict';
angular
.module('jhipsterI18NApp')
.controller('KeyValueDeleteController',KeyValueDeleteController);
KeyValueDeleteController.$inject = ['$scope','$uibModalInstance', 'entity', 'KeyValue'];
function KeyValueDeleteController($scope, $uibModalInstance, entity, KeyValue) {
var vm = this;
vm.keyValue = entity;
vm.clear = clear;
vm.confirmDelete = confirmDelete;
function clear () {
$uibModalInstance.dismiss('cancel');
}
function confirmDelete (id) {
KeyValue.delete({id: id},
function () {
$scope.$emit('jhipsterI18NApp:keyValueDeleted', vm.keyValue);
$uibModalInstance.close(true);
});
}
}
})();
<file_sep>/src/main/webapp/app/entities/module/module-detail.controller.js
(function() {
'use strict';
angular
.module('jhipsterI18NApp')
.controller('ModuleDetailController', ModuleDetailController);
ModuleDetailController.$inject = ['$scope', '$rootScope', '$stateParams', 'entity', 'Module'];
function ModuleDetailController($scope, $rootScope, $stateParams, entity, Module) {
var vm = this;
vm.module = entity;
var unsubscribe = $rootScope.$on('jhipsterI18NApp:moduleUpdate', function(event, result) {
vm.module = result;
});
$scope.$on('$destroy', unsubscribe);
}
})();
<file_sep>/src/main/webapp/app/entities/resource-bundle/resource-bundle.search.service.js
(function() {
'use strict';
angular
.module('jhipsterI18NApp')
.factory('ResourceBundleSearch', ResourceBundleSearch);
ResourceBundleSearch.$inject = ['$resource'];
function ResourceBundleSearch($resource) {
var resourceUrl = 'api/_search/resource-bundles/:id';
return $resource(resourceUrl, {}, {
'query': { method: 'GET', isArray: true}
});
}
})();
<file_sep>/src/main/java/org/jhipster/i18n/web/rest/util/UrlUtil.java
package org.jhipster.i18n.web.rest.util;
import javax.servlet.http.HttpServletRequest;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
/**
* @author <NAME>
* Created on 21-Jun-16.
*/
public class UrlUtil {
public static URI getContextURI( HttpServletRequest request ) throws URISyntaxException {
URI requestUri = new URI( request.getRequestURL().toString() );
URI contextUri = new URI( requestUri.getScheme(),
requestUri.getAuthority(), request.getContextPath(), null, null);
/*
System.out.println("request.getRequestURL(): " + request.getRequestURL());
System.out.println("requestUri.getScheme(): " + requestUri.getScheme());
System.out.println("requestUri.getAuthority(): " + requestUri.getAuthority());
System.out.println("request.getContextPath(): " + request.getContextPath());
*/
return contextUri;
}
public static String getBaseURL(HttpServletRequest request) throws MalformedURLException {
URL requestURL = new URL(request.getRequestURL().toString());
String port = requestURL.getPort() == -1 ? "" : ":" + requestURL.getPort();
return requestURL.getProtocol() + "://" + requestURL.getHost() + port;
}
}
<file_sep>/src/main/webapp/app/entities/module/module-dialog.controller.js
(function() {
'use strict';
angular
.module('jhipsterI18NApp')
.controller('ModuleDialogController', ModuleDialogController);
ModuleDialogController.$inject = ['$timeout', '$scope', '$stateParams', '$uibModalInstance', 'entity', 'Module'];
function ModuleDialogController ($timeout, $scope, $stateParams, $uibModalInstance, entity, Module) {
var vm = this;
vm.module = entity;
vm.clear = clear;
vm.save = save;
$timeout(function (){
angular.element('.form-group:eq(1)>input').focus();
});
function clear () {
$uibModalInstance.dismiss('cancel');
}
function save () {
vm.isSaving = true;
if (vm.module.id !== null) {
Module.update(vm.module, onSaveSuccess, onSaveError);
} else {
Module.save(vm.module, onSaveSuccess, onSaveError);
}
}
function onSaveSuccess (result) {
$scope.$emit('jhipsterI18NApp:moduleUpdate', result);
$uibModalInstance.close(result);
vm.isSaving = false;
}
function onSaveError () {
vm.isSaving = false;
}
}
})();
<file_sep>/src/main/java/org/jhipster/i18n/repository/search/ResourceBundleSearchRepository.java
package org.jhipster.i18n.repository.search;
import org.jhipster.i18n.domain.ResourceBundle;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
/**
* Spring Data ElasticSearch repository for the ResourceBundle entity.
*/
public interface ResourceBundleSearchRepository extends ElasticsearchRepository<ResourceBundle, Long> {
}
<file_sep>/src/main/java/org/jhipster/i18n/repository/ResourceBundleRepository.java
package org.jhipster.i18n.repository;
import org.jhipster.i18n.domain.ResourceBundle;
import org.springframework.data.jpa.repository.*;
import org.springframework.data.repository.query.Param;
import java.util.List;
/**
* Spring Data JPA repository for the ResourceBundle entity.
*/
@SuppressWarnings("unused")
public interface ResourceBundleRepository extends JpaRepository<ResourceBundle,Long> {
@Query( "select rb from ResourceBundle rb where rb.module.id = :moduleId and rb.locale.id = :localeId")
ResourceBundle getResourceBundleByModuleIdAndLocaleId( @Param("moduleId") Long moduleId,
@Param("localeId") Long localeId);
}
<file_sep>/src/main/webapp/app/entities/module/module.search.service.js
(function() {
'use strict';
angular
.module('jhipsterI18NApp')
.factory('ModuleSearch', ModuleSearch);
ModuleSearch.$inject = ['$resource'];
function ModuleSearch($resource) {
var resourceUrl = 'api/_search/modules/:id';
return $resource(resourceUrl, {}, {
'query': { method: 'GET', isArray: true}
});
}
})();
<file_sep>/src/test/java/org/jhipster/i18n/web/rest/ResourceBundleResourceIntTest.java
package org.jhipster.i18n.web.rest;
import org.jhipster.i18n.JhipsterI18NApp;
import org.jhipster.i18n.domain.ResourceBundle;
import org.jhipster.i18n.repository.ResourceBundleRepository;
import org.jhipster.i18n.repository.search.ResourceBundleSearchRepository;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.hamcrest.Matchers.hasItem;
import org.mockito.MockitoAnnotations;
import org.springframework.boot.test.IntegrationTest;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.data.web.PageableHandlerMethodArgumentResolver;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import org.jhipster.i18n.domain.enumeration.ResourceBundleStatus;
/**
* Test class for the ResourceBundleResource REST controller.
*
* @see ResourceBundleResource
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = JhipsterI18NApp.class)
@WebAppConfiguration
@IntegrationTest
public class ResourceBundleResourceIntTest {
private static final String DEFAULT_RESOURCE_BUNDLE_NAME = "AAAAA";
private static final String UPDATED_RESOURCE_BUNDLE_NAME = "BBBBB";
private static final String DEFAULT_DESCRIPTION = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
private static final String UPDATED_DESCRIPTION = "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB";
private static final ResourceBundleStatus DEFAULT_STATUS = ResourceBundleStatus.DISABLED;
private static final ResourceBundleStatus UPDATED_STATUS = ResourceBundleStatus.STATIC_JSON;
@Inject
private ResourceBundleRepository resourceBundleRepository;
@Inject
private ResourceBundleSearchRepository resourceBundleSearchRepository;
@Inject
private MappingJackson2HttpMessageConverter jacksonMessageConverter;
@Inject
private PageableHandlerMethodArgumentResolver pageableArgumentResolver;
private MockMvc restResourceBundleMockMvc;
private ResourceBundle resourceBundle;
@PostConstruct
public void setup() {
MockitoAnnotations.initMocks(this);
ResourceBundleResource resourceBundleResource = new ResourceBundleResource();
ReflectionTestUtils.setField(resourceBundleResource, "resourceBundleSearchRepository", resourceBundleSearchRepository);
ReflectionTestUtils.setField(resourceBundleResource, "resourceBundleRepository", resourceBundleRepository);
this.restResourceBundleMockMvc = MockMvcBuilders.standaloneSetup(resourceBundleResource)
.setCustomArgumentResolvers(pageableArgumentResolver)
.setMessageConverters(jacksonMessageConverter).build();
}
@Before
public void initTest() {
resourceBundleSearchRepository.deleteAll();
resourceBundle = new ResourceBundle();
resourceBundle.setResourceBundleName(DEFAULT_RESOURCE_BUNDLE_NAME);
resourceBundle.setDescription(DEFAULT_DESCRIPTION);
resourceBundle.setStatus(DEFAULT_STATUS);
}
@Test
@Transactional
public void createResourceBundle() throws Exception {
int databaseSizeBeforeCreate = resourceBundleRepository.findAll().size();
// Create the ResourceBundle
restResourceBundleMockMvc.perform(post("/api/resource-bundles")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(resourceBundle)))
.andExpect(status().isCreated());
// Validate the ResourceBundle in the database
List<ResourceBundle> resourceBundles = resourceBundleRepository.findAll();
assertThat(resourceBundles).hasSize(databaseSizeBeforeCreate + 1);
ResourceBundle testResourceBundle = resourceBundles.get(resourceBundles.size() - 1);
assertThat(testResourceBundle.getResourceBundleName()).isEqualTo(DEFAULT_RESOURCE_BUNDLE_NAME);
assertThat(testResourceBundle.getDescription()).isEqualTo(DEFAULT_DESCRIPTION);
assertThat(testResourceBundle.getStatus()).isEqualTo(DEFAULT_STATUS);
// Validate the ResourceBundle in ElasticSearch
ResourceBundle resourceBundleEs = resourceBundleSearchRepository.findOne(testResourceBundle.getId());
assertThat(resourceBundleEs).isEqualToComparingFieldByField(testResourceBundle);
}
@Test
@Transactional
public void getAllResourceBundles() throws Exception {
// Initialize the database
resourceBundleRepository.saveAndFlush(resourceBundle);
// Get all the resourceBundles
restResourceBundleMockMvc.perform(get("/api/resource-bundles?sort=id,desc"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.[*].id").value(hasItem(resourceBundle.getId().intValue())))
.andExpect(jsonPath("$.[*].resourceBundleName").value(hasItem(DEFAULT_RESOURCE_BUNDLE_NAME.toString())))
.andExpect(jsonPath("$.[*].description").value(hasItem(DEFAULT_DESCRIPTION.toString())))
.andExpect(jsonPath("$.[*].status").value(hasItem(DEFAULT_STATUS.toString())));
}
@Test
@Transactional
public void getResourceBundle() throws Exception {
// Initialize the database
resourceBundleRepository.saveAndFlush(resourceBundle);
// Get the resourceBundle
restResourceBundleMockMvc.perform(get("/api/resource-bundles/{id}", resourceBundle.getId()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.id").value(resourceBundle.getId().intValue()))
.andExpect(jsonPath("$.resourceBundleName").value(DEFAULT_RESOURCE_BUNDLE_NAME.toString()))
.andExpect(jsonPath("$.description").value(DEFAULT_DESCRIPTION.toString()))
.andExpect(jsonPath("$.status").value(DEFAULT_STATUS.toString()));
}
@Test
@Transactional
public void getNonExistingResourceBundle() throws Exception {
// Get the resourceBundle
restResourceBundleMockMvc.perform(get("/api/resource-bundles/{id}", Long.MAX_VALUE))
.andExpect(status().isNotFound());
}
@Test
@Transactional
public void updateResourceBundle() throws Exception {
// Initialize the database
resourceBundleRepository.saveAndFlush(resourceBundle);
resourceBundleSearchRepository.save(resourceBundle);
int databaseSizeBeforeUpdate = resourceBundleRepository.findAll().size();
// Update the resourceBundle
ResourceBundle updatedResourceBundle = new ResourceBundle();
updatedResourceBundle.setId(resourceBundle.getId());
updatedResourceBundle.setResourceBundleName(UPDATED_RESOURCE_BUNDLE_NAME);
updatedResourceBundle.setDescription(UPDATED_DESCRIPTION);
updatedResourceBundle.setStatus(UPDATED_STATUS);
restResourceBundleMockMvc.perform(put("/api/resource-bundles")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(updatedResourceBundle)))
.andExpect(status().isOk());
// Validate the ResourceBundle in the database
List<ResourceBundle> resourceBundles = resourceBundleRepository.findAll();
assertThat(resourceBundles).hasSize(databaseSizeBeforeUpdate);
ResourceBundle testResourceBundle = resourceBundles.get(resourceBundles.size() - 1);
assertThat(testResourceBundle.getResourceBundleName()).isEqualTo(UPDATED_RESOURCE_BUNDLE_NAME);
assertThat(testResourceBundle.getDescription()).isEqualTo(UPDATED_DESCRIPTION);
assertThat(testResourceBundle.getStatus()).isEqualTo(UPDATED_STATUS);
// Validate the ResourceBundle in ElasticSearch
ResourceBundle resourceBundleEs = resourceBundleSearchRepository.findOne(testResourceBundle.getId());
assertThat(resourceBundleEs).isEqualToComparingFieldByField(testResourceBundle);
}
@Test
@Transactional
public void deleteResourceBundle() throws Exception {
// Initialize the database
resourceBundleRepository.saveAndFlush(resourceBundle);
resourceBundleSearchRepository.save(resourceBundle);
int databaseSizeBeforeDelete = resourceBundleRepository.findAll().size();
// Get the resourceBundle
restResourceBundleMockMvc.perform(delete("/api/resource-bundles/{id}", resourceBundle.getId())
.accept(TestUtil.APPLICATION_JSON_UTF8))
.andExpect(status().isOk());
// Validate ElasticSearch is empty
boolean resourceBundleExistsInEs = resourceBundleSearchRepository.exists(resourceBundle.getId());
assertThat(resourceBundleExistsInEs).isFalse();
// Validate the database is empty
List<ResourceBundle> resourceBundles = resourceBundleRepository.findAll();
assertThat(resourceBundles).hasSize(databaseSizeBeforeDelete - 1);
}
@Test
@Transactional
public void searchResourceBundle() throws Exception {
// Initialize the database
resourceBundleRepository.saveAndFlush(resourceBundle);
resourceBundleSearchRepository.save(resourceBundle);
// Search the resourceBundle
restResourceBundleMockMvc.perform(get("/api/_search/resource-bundles?query=id:" + resourceBundle.getId()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("$.[*].id").value(hasItem(resourceBundle.getId().intValue())))
.andExpect(jsonPath("$.[*].resourceBundleName").value(hasItem(DEFAULT_RESOURCE_BUNDLE_NAME.toString())))
.andExpect(jsonPath("$.[*].description").value(hasItem(DEFAULT_DESCRIPTION.toString())))
.andExpect(jsonPath("$.[*].status").value(hasItem(DEFAULT_STATUS.toString())));
}
}
<file_sep>/src/main/java/org/jhipster/i18n/async/package-info.java
/**
* Async helpers.
*/
package org.jhipster.i18n.async;
<file_sep>/src/main/webapp/app/entities/resource-bundle/resource-bundle-detail.controller.js
(function() {
'use strict';
angular
.module('jhipsterI18NApp')
.controller('ResourceBundleDetailController', ResourceBundleDetailController);
ResourceBundleDetailController.$inject = ['$scope', '$rootScope', '$stateParams', 'entity', 'ResourceBundle',
'Locale', 'Module', 'ResourceBundleUtil', 'KeyValueSearchBy_RB_Id'];
function ResourceBundleDetailController($scope, $rootScope, $stateParams, entity, ResourceBundle, Locale, Module,
ResourceBundleUtil, KeyValueSearchBy_RB_Id) {
var vm = this;
vm.resourceBundle = entity;
vm.keyValues = KeyValueSearchBy_RB_Id.query( {id : $stateParams.id} );
var unsubscribe = $rootScope.$on('jhipsterI18NApp:resourceBundleUpdate', function(event, result) {
vm.resourceBundle = result;
});
$scope.$on('$destroy', unsubscribe);
vm.printLocale = function(locale) {
return ResourceBundleUtil.printLocale(locale);
}
vm.printLocale = function(locale) {
return ResourceBundleUtil.printLocale(locale);
}
}
})();
<file_sep>/src/main/java/org/jhipster/i18n/web/rest/ResourceBundleResource.java
package org.jhipster.i18n.web.rest;
import com.codahale.metrics.annotation.Timed;
import org.jhipster.i18n.domain.ResourceBundle;
import org.jhipster.i18n.repository.ResourceBundleRepository;
import org.jhipster.i18n.repository.search.ResourceBundleSearchRepository;
import org.jhipster.i18n.service.I18nService;
import org.jhipster.i18n.web.rest.util.HeaderUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.inject.Inject;
import javax.validation.Valid;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import static org.elasticsearch.index.query.QueryBuilders.*;
/**
* REST controller for managing ResourceBundle.
*/
@RestController
@RequestMapping("/api")
public class ResourceBundleResource {
private final Logger log = LoggerFactory.getLogger(ResourceBundleResource.class);
@Inject
private ResourceBundleRepository resourceBundleRepository;
@Inject
private ResourceBundleSearchRepository resourceBundleSearchRepository;
@Inject
private I18nService i18nService;
/**
* POST /resource-bundles : Create a new resourceBundle.
*
* @param resourceBundle the resourceBundle to create
* @return the ResponseEntity with status 201 (Created) and with body the new resourceBundle, or with status 400 (Bad Request) if the resourceBundle has already an ID
* @throws URISyntaxException if the Location URI syntax is incorrect
*/
@RequestMapping(value = "/resource-bundles",
method = RequestMethod.POST,
produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public ResponseEntity<ResourceBundle> createResourceBundle(@Valid @RequestBody ResourceBundle resourceBundle) throws URISyntaxException {
log.debug("REST request to save ResourceBundle : {}", resourceBundle);
if (resourceBundle.getId() != null) {
return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert("resourceBundle", "idexists", "A new resourceBundle cannot already have an ID")).body(null);
}
ResourceBundle result = resourceBundleRepository.save(resourceBundle);
resourceBundleSearchRepository.save(result);
return ResponseEntity.created(new URI("/api/resource-bundles/" + result.getId()))
.headers(HeaderUtil.createEntityCreationAlert("resourceBundle", result.getId().toString()))
.body(result);
}
/**
* PUT /resource-bundles : Updates an existing resourceBundle.
*
* @param resourceBundle the resourceBundle to update
* @return the ResponseEntity with status 200 (OK) and with body the updated resourceBundle,
* or with status 400 (Bad Request) if the resourceBundle is not valid,
* or with status 500 (Internal Server Error) if the resourceBundle couldnt be updated
* @throws URISyntaxException if the Location URI syntax is incorrect
*/
@RequestMapping(value = "/resource-bundles",
method = RequestMethod.PUT,
produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public ResponseEntity<ResourceBundle> updateResourceBundle(@Valid @RequestBody ResourceBundle resourceBundle) throws URISyntaxException {
log.debug("REST request to update ResourceBundle : {}", resourceBundle);
if (resourceBundle.getId() == null) {
return createResourceBundle(resourceBundle);
}
ResourceBundle result = resourceBundleRepository.save(resourceBundle);
resourceBundleSearchRepository.save(result);
return ResponseEntity.ok()
.headers(HeaderUtil.createEntityUpdateAlert("resourceBundle", resourceBundle.getId().toString()))
.body(result);
}
/**
* GET /resource-bundles : get all the resourceBundles.
*
* @return the ResponseEntity with status 200 (OK) and the list of resourceBundles in body
*/
@RequestMapping(value = "/resource-bundles",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public List<ResourceBundle> getAllResourceBundles() {
log.debug("REST request to get all ResourceBundles");
List<ResourceBundle> resourceBundles = resourceBundleRepository.findAll();
return resourceBundles;
}
/**
* GET /resource-bundles/:id : get the "id" resourceBundle.
*
* @param id the id of the resourceBundle to retrieve
* @return the ResponseEntity with status 200 (OK) and with body the resourceBundle, or with status 404 (Not Found)
*/
@RequestMapping(value = "/resource-bundles/{id}",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public ResponseEntity<ResourceBundle> getResourceBundle(@PathVariable Long id) {
log.debug("REST request to get ResourceBundle : {}", id);
ResourceBundle resourceBundle = resourceBundleRepository.findOne(id);
return Optional.ofNullable(resourceBundle)
.map(result -> new ResponseEntity<>(
result,
HttpStatus.OK))
.orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
}
/**
* DELETE /resource-bundles/:id : delete the "id" resourceBundle.
*
* @param id the id of the resourceBundle to delete
* @return the ResponseEntity with status 200 (OK)
*/
@RequestMapping(value = "/resource-bundles/{id}",
method = RequestMethod.DELETE,
produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public ResponseEntity<Void> deleteResourceBundle(@PathVariable Long id) {
log.debug("REST request to delete ResourceBundle : {}", id);
resourceBundleRepository.delete(id);
resourceBundleSearchRepository.delete(id);
return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert("resourceBundle", id.toString())).build();
}
/**
* SEARCH /_search/resource-bundles?query=:query : search for the resourceBundle corresponding
* to the query.
*
* @param query the query of the resourceBundle search
* @return the result of the search
*/
@RequestMapping(value = "/_search/resource-bundles",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public List<ResourceBundle> searchResourceBundles(@RequestParam String query) {
log.debug("REST request to search ResourceBundles for query {}", query);
return StreamSupport
.stream(resourceBundleSearchRepository.search(queryStringQuery(query)).spliterator(), false)
.collect(Collectors.toList());
}
/**
* POST /resource-bundles/:id/clear-cache : clear the key-value map cache for the "id" resourceBundle
*
* @param resourceBundle the ResourceBundle to clear key-value map cache
* @return the ResponseEntity with status 200 (OK)
*/
@RequestMapping(value = "/resource-bundles/clear-cache",
method = RequestMethod.PUT,
produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public ResponseEntity<Void> clearCache(@RequestBody ResourceBundle resourceBundle) {
log.debug("REST request to clear cache for ResourceBundle: {}", resourceBundle.getId());
i18nService.clearCache( resourceBundle );
return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert("resourceBundle", "CLEAR_CACHE_SUCCESS" )).build();
}
}
<file_sep>/settings.gradle
rootProject.name = 'jhipster_i18n'
<file_sep>/src/main/webapp/app/entities/key-value/key-value-detail.controller.js
(function() {
'use strict';
angular
.module('jhipsterI18NApp')
.controller('KeyValueDetailController', KeyValueDetailController);
KeyValueDetailController.$inject = ['$scope', '$rootScope', '$stateParams', 'entity', 'KeyValue', 'ResourceBundle'];
function KeyValueDetailController($scope, $rootScope, $stateParams, entity, KeyValue, ResourceBundle) {
var vm = this;
vm.keyValue = entity;
var unsubscribe = $rootScope.$on('jhipsterI18NApp:keyValueUpdate', function(event, result) {
vm.keyValue = result;
});
$scope.$on('$destroy', unsubscribe);
}
})();
<file_sep>/i18n.sql
--
-- PostgreSQL database dump
--
SET statement_timeout = 0;
SET lock_timeout = 0;
SET client_encoding = 'UTF8';
SET standard_conforming_strings = on;
SET check_function_bodies = false;
SET client_min_messages = warning;
--
-- Name: plpgsql; Type: EXTENSION; Schema: -; Owner:
--
CREATE EXTENSION IF NOT EXISTS plpgsql WITH SCHEMA pg_catalog;
--
-- Name: EXTENSION plpgsql; Type: COMMENT; Schema: -; Owner:
--
COMMENT ON EXTENSION plpgsql IS 'PL/pgSQL procedural language';
SET search_path = public, pg_catalog;
SET default_tablespace = '';
SET default_with_oids = false;
--
-- Name: databasechangelog; Type: TABLE; Schema: public; Owner: i18n; Tablespace:
--
CREATE TABLE databasechangelog (
id character varying(255) NOT NULL,
author character varying(255) NOT NULL,
filename character varying(255) NOT NULL,
dateexecuted timestamp without time zone NOT NULL,
orderexecuted integer NOT NULL,
exectype character varying(10) NOT NULL,
md5sum character varying(35),
description character varying(255),
comments character varying(255),
tag character varying(255),
liquibase character varying(20),
contexts character varying(255),
labels character varying(255)
);
ALTER TABLE databasechangelog OWNER TO i18n;
--
-- Name: databasechangeloglock; Type: TABLE; Schema: public; Owner: i18n; Tablespace:
--
CREATE TABLE databasechangeloglock (
id integer NOT NULL,
locked boolean NOT NULL,
lockgranted timestamp without time zone,
lockedby character varying(255)
);
ALTER TABLE databasechangeloglock OWNER TO i18n;
--
-- Name: hibernate_sequence; Type: SEQUENCE; Schema: public; Owner: i18n
--
CREATE SEQUENCE hibernate_sequence
START WITH 1000
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
ALTER TABLE hibernate_sequence OWNER TO i18n;
--
-- Name: jhi_authority; Type: TABLE; Schema: public; Owner: i18n; Tablespace:
--
CREATE TABLE jhi_authority (
name character varying(50) NOT NULL
);
ALTER TABLE jhi_authority OWNER TO i18n;
--
-- Name: jhi_persistent_audit_event; Type: TABLE; Schema: public; Owner: i18n; Tablespace:
--
CREATE TABLE jhi_persistent_audit_event (
event_id bigint NOT NULL,
principal character varying(255) NOT NULL,
event_date timestamp without time zone,
event_type character varying(255)
);
ALTER TABLE jhi_persistent_audit_event OWNER TO i18n;
--
-- Name: jhi_persistent_audit_event_event_id_seq; Type: SEQUENCE; Schema: public; Owner: i18n
--
CREATE SEQUENCE jhi_persistent_audit_event_event_id_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
ALTER TABLE jhi_persistent_audit_event_event_id_seq OWNER TO i18n;
--
-- Name: jhi_persistent_audit_event_event_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: i18n
--
ALTER SEQUENCE jhi_persistent_audit_event_event_id_seq OWNED BY jhi_persistent_audit_event.event_id;
--
-- Name: jhi_persistent_audit_evt_data; Type: TABLE; Schema: public; Owner: i18n; Tablespace:
--
CREATE TABLE jhi_persistent_audit_evt_data (
event_id bigint NOT NULL,
name character varying(255) NOT NULL,
value character varying(255)
);
ALTER TABLE jhi_persistent_audit_evt_data OWNER TO i18n;
--
-- Name: jhi_user; Type: TABLE; Schema: public; Owner: i18n; Tablespace:
--
CREATE TABLE jhi_user (
id bigint NOT NULL,
login character varying(50) NOT NULL,
password_hash character varying(60),
first_name character varying(50),
last_name character varying(50),
email character varying(100),
activated boolean NOT NULL,
lang_key character varying(5),
activation_key character varying(20),
reset_key character varying(20),
created_by character varying(50) NOT NULL,
created_date timestamp without time zone NOT NULL,
reset_date timestamp without time zone,
last_modified_by character varying(50),
last_modified_date timestamp without time zone
);
ALTER TABLE jhi_user OWNER TO i18n;
--
-- Name: jhi_user_authority; Type: TABLE; Schema: public; Owner: i18n; Tablespace:
--
CREATE TABLE jhi_user_authority (
user_id bigint NOT NULL,
authority_name character varying(50) NOT NULL
);
ALTER TABLE jhi_user_authority OWNER TO i18n;
--
-- Name: jhi_user_id_seq; Type: SEQUENCE; Schema: public; Owner: i18n
--
CREATE SEQUENCE jhi_user_id_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
ALTER TABLE jhi_user_id_seq OWNER TO i18n;
--
-- Name: jhi_user_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: i18n
--
ALTER SEQUENCE jhi_user_id_seq OWNED BY jhi_user.id;
--
-- Name: key_value; Type: TABLE; Schema: public; Owner: i18n; Tablespace:
--
CREATE TABLE key_value (
key_value_id bigint NOT NULL,
property character varying(255) NOT NULL,
property_value character varying(255) NOT NULL,
description character varying(255),
resource_bundle_id bigint
);
ALTER TABLE key_value OWNER TO i18n;
--
-- Name: key_value_key_value_id_seq; Type: SEQUENCE; Schema: public; Owner: i18n
--
CREATE SEQUENCE key_value_key_value_id_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
ALTER TABLE key_value_key_value_id_seq OWNER TO i18n;
--
-- Name: key_value_key_value_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: i18n
--
ALTER SEQUENCE key_value_key_value_id_seq OWNED BY key_value.key_value_id;
--
-- Name: locale; Type: TABLE; Schema: public; Owner: i18n; Tablespace:
--
CREATE TABLE locale (
locale_id bigint NOT NULL,
name character varying(255) NOT NULL,
language_code character varying(255) NOT NULL,
country_code character varying(255)
);
ALTER TABLE locale OWNER TO i18n;
--
-- Name: locale_locale_id_seq; Type: SEQUENCE; Schema: public; Owner: i18n
--
CREATE SEQUENCE locale_locale_id_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
ALTER TABLE locale_locale_id_seq OWNER TO i18n;
--
-- Name: locale_locale_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: i18n
--
ALTER SEQUENCE locale_locale_id_seq OWNED BY locale.locale_id;
--
-- Name: module; Type: TABLE; Schema: public; Owner: i18n; Tablespace:
--
CREATE TABLE module (
module_id bigint NOT NULL,
name character varying(255) NOT NULL,
description character varying(255)
);
ALTER TABLE module OWNER TO i18n;
--
-- Name: module_module_id_seq; Type: SEQUENCE; Schema: public; Owner: i18n
--
CREATE SEQUENCE module_module_id_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
ALTER TABLE module_module_id_seq OWNER TO i18n;
--
-- Name: module_module_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: i18n
--
ALTER SEQUENCE module_module_id_seq OWNED BY module.module_id;
--
-- Name: resource_bundle; Type: TABLE; Schema: public; Owner: i18n; Tablespace:
--
CREATE TABLE resource_bundle (
resource_bundle_id bigint NOT NULL,
resource_bundle_name character varying(255),
description character varying(100),
status character varying(255),
locale_id bigint NOT NULL,
module_id bigint NOT NULL
);
ALTER TABLE resource_bundle OWNER TO i18n;
--
-- Name: resource_bundle_resource_bundle_id_seq; Type: SEQUENCE; Schema: public; Owner: i18n
--
CREATE SEQUENCE resource_bundle_resource_bundle_id_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
ALTER TABLE resource_bundle_resource_bundle_id_seq OWNER TO i18n;
--
-- Name: resource_bundle_resource_bundle_id_seq; Type: SEQUENCE OWNED BY; Schema: public; Owner: i18n
--
ALTER SEQUENCE resource_bundle_resource_bundle_id_seq OWNED BY resource_bundle.resource_bundle_id;
--
-- Name: event_id; Type: DEFAULT; Schema: public; Owner: i18n
--
ALTER TABLE ONLY jhi_persistent_audit_event ALTER COLUMN event_id SET DEFAULT nextval('jhi_persistent_audit_event_event_id_seq'::regclass);
--
-- Name: id; Type: DEFAULT; Schema: public; Owner: i18n
--
ALTER TABLE ONLY jhi_user ALTER COLUMN id SET DEFAULT nextval('jhi_user_id_seq'::regclass);
--
-- Name: key_value_id; Type: DEFAULT; Schema: public; Owner: i18n
--
ALTER TABLE ONLY key_value ALTER COLUMN key_value_id SET DEFAULT nextval('key_value_key_value_id_seq'::regclass);
--
-- Name: locale_id; Type: DEFAULT; Schema: public; Owner: i18n
--
ALTER TABLE ONLY locale ALTER COLUMN locale_id SET DEFAULT nextval('locale_locale_id_seq'::regclass);
--
-- Name: module_id; Type: DEFAULT; Schema: public; Owner: i18n
--
ALTER TABLE ONLY module ALTER COLUMN module_id SET DEFAULT nextval('module_module_id_seq'::regclass);
--
-- Name: resource_bundle_id; Type: DEFAULT; Schema: public; Owner: i18n
--
ALTER TABLE ONLY resource_bundle ALTER COLUMN resource_bundle_id SET DEFAULT nextval('resource_bundle_resource_bundle_id_seq'::regclass);
--
-- Data for Name: databasechangelog; Type: TABLE DATA; Schema: public; Owner: i18n
--
COPY databasechangelog (id, author, filename, dateexecuted, orderexecuted, exectype, md5sum, description, comments, tag, liquibase, contexts, labels) FROM stdin;
00000000000000 jhipster classpath:config/liquibase/changelog/00000000000000_initial_schema.xml 2016-07-08 00:16:33.467 1 EXECUTED 7:eda8cd7fd15284e6128be97bd8edea82 createSequence \N 3.4.2 \N \N
00000000000001 jhipster classpath:config/liquibase/changelog/00000000000000_initial_schema.xml 2016-07-08 00:16:34.431 2 EXECUTED 7:4ad265793158c33b98858df1278027d3 createTable, createIndex (x2), createTable (x2), addPrimaryKey, addForeignKeyConstraint (x2), loadData, dropDefaultValue, loadData (x2), createTable (x2), addPrimaryKey, createIndex (x2), addForeignKeyConstraint \N 3.4.2 \N \N
20160629121218-1 jhipster classpath:config/liquibase/changelog/20160629121218_added_entity_Locale.xml 2016-07-08 00:16:34.581 3 EXECUTED 7:ae62b16ce79e33d0fd477ec15b075621 createTable \N 3.4.2 \N \N
20160629121219-1 jhipster classpath:config/liquibase/changelog/20160629121219_added_entity_Module.xml 2016-07-08 00:16:34.667 4 EXECUTED 7:7246880ddefe533865b86adc7facc72a createTable \N 3.4.2 \N \N
20160629121220-1 jhipster classpath:config/liquibase/changelog/20160629121220_added_entity_ResourceBundle.xml 2016-07-08 00:16:34.771 5 EXECUTED 7:3924358fe0acdbeb938a1c17b199859f createTable \N 3.4.2 \N \N
20160629121221-1 jhipster classpath:config/liquibase/changelog/20160629121221_added_entity_KeyValue.xml 2016-07-08 00:16:34.85 6 EXECUTED 7:f0cf9d2def70efaaa99bd4f6eff9d962 createTable \N 3.4.2 \N \N
20160629121220-2 jhipster classpath:config/liquibase/changelog/20160629121220_added_entity_constraints_ResourceBundle.xml 2016-07-08 00:16:34.867 7 EXECUTED 7:f5456ef783f912e8e8f0dbed1ab3df4b addForeignKeyConstraint (x2) \N 3.4.2 \N \N
20160629121221-2 jhipster classpath:config/liquibase/changelog/20160629121221_added_entity_constraints_KeyValue.xml 2016-07-08 00:16:34.882 8 EXECUTED 7:7998d85f46c190f11e877a35357deb0f addForeignKeyConstraint \N 3.4.2 \N \N
1467615754770-2 Sam (generated) classpath:config/liquibase/changelog/20160704190219_changelog.xml 2016-07-08 00:16:34.922 9 EXECUTED 7:c8105a766544a90884f36f0eb5f88093 addUniqueConstraint \N 3.4.2 \N \N
1467615754770-12 Sam (generated) classpath:config/liquibase/changelog/20160704190219_changelog.xml 2016-07-08 00:16:34.929 10 EXECUTED 7:0e590015cebaf9cfa397bff1099703a2 addNotNullConstraint \N 3.4.2 \N \N
1467615754770-13 Sam (generated) classpath:config/liquibase/changelog/20160704190219_changelog.xml 2016-07-08 00:16:34.935 11 EXECUTED 7:2adeb50f0b48c2d614f6a89618029cef addNotNullConstraint \N 3.4.2 \N \N
1467888310341-2 Sam (generated) classpath:config/liquibase/changelog/20160704190219_changelog.xml 2016-07-08 00:16:34.985 12 EXECUTED 7:61762f778e98dc0bbac106d78d622974 addUniqueConstraint \N 3.4.2 \N \N
1467893366830-1 Sam (generated) classpath:config/liquibase/changelog/20160704190219_changelog.xml 2016-07-08 00:16:35.035 13 EXECUTED 7:609e2c50c862bf4384d07c7028895e4d addUniqueConstraint \N 3.4.2 \N \N
1467893366830-2 Sam (generated) classpath:config/liquibase/changelog/20160704190219_changelog.xml 2016-07-08 00:16:35.094 14 EXECUTED 7:08665db9bf32f393019b323d4c9c58b6 addUniqueConstraint \N 3.4.2 \N \N
1467893366830-3 Sam (generated) classpath:config/liquibase/changelog/20160704190219_changelog.xml 2016-07-08 00:16:35.145 15 EXECUTED 7:70da9fdb23b3f3883198323a15cf9eee addUniqueConstraint \N 3.4.2 \N \N
\.
--
-- Data for Name: databasechangeloglock; Type: TABLE DATA; Schema: public; Owner: i18n
--
COPY databasechangeloglock (id, locked, lockgranted, lockedby) FROM stdin;
1 f \N \N
\.
--
-- Name: hibernate_sequence; Type: SEQUENCE SET; Schema: public; Owner: i18n
--
SELECT pg_catalog.setval('hibernate_sequence', 1063, true);
--
-- Data for Name: jhi_authority; Type: TABLE DATA; Schema: public; Owner: i18n
--
COPY jhi_authority (name) FROM stdin;
ROLE_ADMIN
ROLE_USER
\.
--
-- Data for Name: jhi_persistent_audit_event; Type: TABLE DATA; Schema: public; Owner: i18n
--
COPY jhi_persistent_audit_event (event_id, principal, event_date, event_type) FROM stdin;
1015 admin 2016-07-11 15:12:07.314 AUTHENTICATION_SUCCESS
1023 admin 2016-07-12 15:21:30.008 AUTHENTICATION_SUCCESS
\.
--
-- Name: jhi_persistent_audit_event_event_id_seq; Type: SEQUENCE SET; Schema: public; Owner: i18n
--
SELECT pg_catalog.setval('jhi_persistent_audit_event_event_id_seq', 1, false);
--
-- Data for Name: jhi_persistent_audit_evt_data; Type: TABLE DATA; Schema: public; Owner: i18n
--
COPY jhi_persistent_audit_evt_data (event_id, name, value) FROM stdin;
\.
--
-- Data for Name: jhi_user; Type: TABLE DATA; Schema: public; Owner: i18n
--
COPY jhi_user (id, login, password_hash, first_name, last_name, email, activated, lang_key, activation_key, reset_key, created_by, created_date, reset_date, last_modified_by, last_modified_date) FROM stdin;
1 system $2a$10$mE.qmcV0mFU5NcKh73TZx.z4ueI/.bDWbj0T1BYyqP481kGGarKLG System System system@localhost t en \N \N system 2016-07-08 00:16:33.487 \N \N \N
2 anonymoususer $2a$10$j8S5d7Sr7.8VTOYNviDPOeWX8KcYILUVJBsYV83Y5NtECayypx9lO Anonymous User anonymous@localhost t en \N \N system 2016-07-08 00:16:33.487 \N \N \N
3 admin $2a$10$gSAhZrxMllrbgj/kkK9UceBPpChGWJA7SYIb1Mqo.n5aNLq1/oRrC Administrator Administrator <EMAIL>@<EMAIL> t en \N \N system 2016-07-08 00:16:33.487 \N \N \N
4 user $2a$10$VEjxo0jq2YG9Rbk2HmX9S.k1uZBGYUHdUcid3g/vfiEl7lwWgOH/K User User user@<EMAIL> t en \N \N system 2016-07-08 00:16:33.487 \N \N \N
\.
--
-- Data for Name: jhi_user_authority; Type: TABLE DATA; Schema: public; Owner: i18n
--
COPY jhi_user_authority (user_id, authority_name) FROM stdin;
1 ROLE_ADMIN
1 ROLE_USER
3 ROLE_ADMIN
3 ROLE_USER
4 ROLE_USER
\.
--
-- Name: jhi_user_id_seq; Type: SEQUENCE SET; Schema: public; Owner: i18n
--
SELECT pg_catalog.setval('jhi_user_id_seq', 1, false);
--
-- Data for Name: key_value; Type: TABLE DATA; Schema: public; Owner: i18n
--
COPY key_value (key_value_id, property, property_value, description, resource_bundle_id) FROM stdin;
1014 aa bb \N 1006
\.
--
-- Name: key_value_key_value_id_seq; Type: SEQUENCE SET; Schema: public; Owner: i18n
--
SELECT pg_catalog.setval('key_value_key_value_id_seq', 1, false);
--
-- Data for Name: locale; Type: TABLE DATA; Schema: public; Owner: i18n
--
COPY locale (locale_id, name, language_code, country_code) FROM stdin;
1001 English en \N
\.
--
-- Name: locale_locale_id_seq; Type: SEQUENCE SET; Schema: public; Owner: i18n
--
SELECT pg_catalog.setval('locale_locale_id_seq', 1, false);
--
-- Data for Name: module; Type: TABLE DATA; Schema: public; Owner: i18n
--
COPY module (module_id, name, description) FROM stdin;
1004 resourceBundle \N
1019 global For English verison of global.json
1021 module \N
1024 locale \N
1025 activate \N
1026 audits \N
1027 configuration \N
1028 error \N
1029 gateway \N
1031 health \N
1032 home \N
1033 keyValue \N
1034 login \N
1035 logs \N
1036 metrics \N
1037 password \N
1038 register \N
1039 reset \N
1040 sessions \N
1041 resourceBundleStatus \N
1042 settings \N
1043 tracker \N
1044 user-management \N
\.
--
-- Name: module_module_id_seq; Type: SEQUENCE SET; Schema: public; Owner: i18n
--
SELECT pg_catalog.setval('module_module_id_seq', 1, false);
--
-- Data for Name: resource_bundle; Type: TABLE DATA; Schema: public; Owner: i18n
--
COPY resource_bundle (resource_bundle_id, resource_bundle_name, description, status, locale_id, module_id) FROM stdin;
1006 resourceBundle_en \N STATIC_JSON 1001 1004
1020 global_en \N STATIC_JSON 1001 1019
1022 module_en \N STATIC_JSON 1001 1021
1045 resourceBundleStatus_en \N STATIC_JSON 1001 1041
1046 activate_en \N STATIC_JSON 1001 1025
1047 audits_en \N STATIC_JSON 1001 1026
1048 configuration_en \N STATIC_JSON 1001 1027
1049 error_en \N STATIC_JSON 1001 1028
1050 gateway_en \N STATIC_JSON 1001 1029
1051 health_en \N STATIC_JSON 1001 1031
1052 home_en \N STATIC_JSON 1001 1032
1053 keyValue_en \N STATIC_JSON 1001 1033
1054 login_en \N STATIC_JSON 1001 1034
1055 logs_en \N STATIC_JSON 1001 1035
1056 metrics_en \N STATIC_JSON 1001 1036
1057 password_en \N STATIC_JSON 1001 1037
1058 register_en \N STATIC_JSON 1001 1038
1059 reset_en \N STATIC_JSON 1001 1039
1060 sessions_en \N STATIC_JSON 1001 1040
1061 settings_en \N STATIC_JSON 1001 1042
1062 tracker_en \N STATIC_JSON 1001 1043
1063 user-management_en \N STATIC_JSON 1001 1044
\.
--
-- Name: resource_bundle_resource_bundle_id_seq; Type: SEQUENCE SET; Schema: public; Owner: i18n
--
SELECT pg_catalog.setval('resource_bundle_resource_bundle_id_seq', 1, false);
--
-- Name: jhi_persistent_audit_evt_data_pkey; Type: CONSTRAINT; Schema: public; Owner: i18n; Tablespace:
--
ALTER TABLE ONLY jhi_persistent_audit_evt_data
ADD CONSTRAINT jhi_persistent_audit_evt_data_pkey PRIMARY KEY (event_id, name);
--
-- Name: jhi_user_authority_pkey; Type: CONSTRAINT; Schema: public; Owner: i18n; Tablespace:
--
ALTER TABLE ONLY jhi_user_authority
ADD CONSTRAINT jhi_user_authority_pkey PRIMARY KEY (user_id, authority_name);
--
-- Name: jhi_user_email_key; Type: CONSTRAINT; Schema: public; Owner: i18n; Tablespace:
--
ALTER TABLE ONLY jhi_user
ADD CONSTRAINT jhi_user_email_key UNIQUE (email);
--
-- Name: jhi_user_login_key; Type: CONSTRAINT; Schema: public; Owner: i18n; Tablespace:
--
ALTER TABLE ONLY jhi_user
ADD CONSTRAINT jhi_user_login_key UNIQUE (login);
--
-- Name: locale_language_code_country_code_key; Type: CONSTRAINT; Schema: public; Owner: i18n; Tablespace:
--
ALTER TABLE ONLY locale
ADD CONSTRAINT locale_language_code_country_code_key UNIQUE (language_code, country_code);
--
-- Name: locale_name_key; Type: CONSTRAINT; Schema: public; Owner: i18n; Tablespace:
--
ALTER TABLE ONLY locale
ADD CONSTRAINT locale_name_key UNIQUE (name);
--
-- Name: module_name_key; Type: CONSTRAINT; Schema: public; Owner: i18n; Tablespace:
--
ALTER TABLE ONLY module
ADD CONSTRAINT module_name_key UNIQUE (name);
--
-- Name: pk_databasechangeloglock; Type: CONSTRAINT; Schema: public; Owner: i18n; Tablespace:
--
ALTER TABLE ONLY databasechangeloglock
ADD CONSTRAINT pk_databasechangeloglock PRIMARY KEY (id);
--
-- Name: pk_jhi_authority; Type: CONSTRAINT; Schema: public; Owner: i18n; Tablespace:
--
ALTER TABLE ONLY jhi_authority
ADD CONSTRAINT pk_jhi_authority PRIMARY KEY (name);
--
-- Name: pk_jhi_persistent_audit_event; Type: CONSTRAINT; Schema: public; Owner: i18n; Tablespace:
--
ALTER TABLE ONLY jhi_persistent_audit_event
ADD CONSTRAINT pk_jhi_persistent_audit_event PRIMARY KEY (event_id);
--
-- Name: pk_jhi_user; Type: CONSTRAINT; Schema: public; Owner: i18n; Tablespace:
--
ALTER TABLE ONLY jhi_user
ADD CONSTRAINT pk_jhi_user PRIMARY KEY (id);
--
-- Name: pk_key_value; Type: CONSTRAINT; Schema: public; Owner: i18n; Tablespace:
--
ALTER TABLE ONLY key_value
ADD CONSTRAINT pk_key_value PRIMARY KEY (key_value_id);
--
-- Name: pk_locale; Type: CONSTRAINT; Schema: public; Owner: i18n; Tablespace:
--
ALTER TABLE ONLY locale
ADD CONSTRAINT pk_locale PRIMARY KEY (locale_id);
--
-- Name: pk_module; Type: CONSTRAINT; Schema: public; Owner: i18n; Tablespace:
--
ALTER TABLE ONLY module
ADD CONSTRAINT pk_module PRIMARY KEY (module_id);
--
-- Name: pk_resource_bundle; Type: CONSTRAINT; Schema: public; Owner: i18n; Tablespace:
--
ALTER TABLE ONLY resource_bundle
ADD CONSTRAINT pk_resource_bundle PRIMARY KEY (resource_bundle_id);
--
-- Name: resource_bundle_locale_id_module_id_key; Type: CONSTRAINT; Schema: public; Owner: i18n; Tablespace:
--
ALTER TABLE ONLY resource_bundle
ADD CONSTRAINT resource_bundle_locale_id_module_id_key UNIQUE (locale_id, module_id);
--
-- Name: resource_bundle_resource_bundle_name_key; Type: CONSTRAINT; Schema: public; Owner: i18n; Tablespace:
--
ALTER TABLE ONLY resource_bundle
ADD CONSTRAINT resource_bundle_resource_bundle_name_key UNIQUE (resource_bundle_name);
--
-- Name: idx_persistent_audit_event; Type: INDEX; Schema: public; Owner: i18n; Tablespace:
--
CREATE INDEX idx_persistent_audit_event ON jhi_persistent_audit_event USING btree (principal, event_date);
--
-- Name: idx_persistent_audit_evt_data; Type: INDEX; Schema: public; Owner: i18n; Tablespace:
--
CREATE INDEX idx_persistent_audit_evt_data ON jhi_persistent_audit_evt_data USING btree (event_id);
--
-- Name: idx_user_email; Type: INDEX; Schema: public; Owner: i18n; Tablespace:
--
CREATE UNIQUE INDEX idx_user_email ON jhi_user USING btree (email);
--
-- Name: idx_user_login; Type: INDEX; Schema: public; Owner: i18n; Tablespace:
--
CREATE UNIQUE INDEX idx_user_login ON jhi_user USING btree (login);
--
-- Name: fk_authority_name; Type: FK CONSTRAINT; Schema: public; Owner: i18n
--
ALTER TABLE ONLY jhi_user_authority
ADD CONSTRAINT fk_authority_name FOREIGN KEY (authority_name) REFERENCES jhi_authority(name);
--
-- Name: fk_evt_pers_audit_evt_data; Type: FK CONSTRAINT; Schema: public; Owner: i18n
--
ALTER TABLE ONLY jhi_persistent_audit_evt_data
ADD CONSTRAINT fk_evt_pers_audit_evt_data FOREIGN KEY (event_id) REFERENCES jhi_persistent_audit_event(event_id);
--
-- Name: fk_keyvalue_resourcebundle; Type: FK CONSTRAINT; Schema: public; Owner: i18n
--
ALTER TABLE ONLY key_value
ADD CONSTRAINT fk_keyvalue_resourcebundle FOREIGN KEY (resource_bundle_id) REFERENCES resource_bundle(resource_bundle_id);
--
-- Name: fk_resourcebundle_locale; Type: FK CONSTRAINT; Schema: public; Owner: i18n
--
ALTER TABLE ONLY resource_bundle
ADD CONSTRAINT fk_resourcebundle_locale FOREIGN KEY (locale_id) REFERENCES locale(locale_id);
--
-- Name: fk_resourcebundle_module; Type: FK CONSTRAINT; Schema: public; Owner: i18n
--
ALTER TABLE ONLY resource_bundle
ADD CONSTRAINT fk_resourcebundle_module FOREIGN KEY (module_id) REFERENCES module(module_id);
--
-- Name: fk_user_id; Type: FK CONSTRAINT; Schema: public; Owner: i18n
--
ALTER TABLE ONLY jhi_user_authority
ADD CONSTRAINT fk_user_id FOREIGN KEY (user_id) REFERENCES jhi_user(id);
--
-- Name: public; Type: ACL; Schema: -; Owner: postgres
--
REVOKE ALL ON SCHEMA public FROM PUBLIC;
REVOKE ALL ON SCHEMA public FROM postgres;
GRANT ALL ON SCHEMA public TO postgres;
GRANT ALL ON SCHEMA public TO PUBLIC;
--
-- PostgreSQL database dump complete
--
<file_sep>/src/main/java/org/jhipster/i18n/web/rest/KeyValueResource.java
package org.jhipster.i18n.web.rest;
import com.codahale.metrics.annotation.Timed;
import org.jhipster.i18n.domain.KeyValue;
import org.jhipster.i18n.repository.KeyValueRepository;
import org.jhipster.i18n.repository.search.KeyValueSearchRepository;
import org.jhipster.i18n.web.rest.util.HeaderUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import javax.inject.Inject;
import javax.validation.Valid;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import static org.elasticsearch.index.query.QueryBuilders.*;
/**
* REST controller for managing KeyValue.
*/
@RestController
@RequestMapping("/api")
public class KeyValueResource {
private final Logger log = LoggerFactory.getLogger(KeyValueResource.class);
@Inject
private KeyValueRepository keyValueRepository;
@Inject
private KeyValueSearchRepository keyValueSearchRepository;
/**
* POST /key-values : Create a new keyValue.
*
* @param keyValue the keyValue to create
* @return the ResponseEntity with status 201 (Created) and with body the new keyValue, or with status 400 (Bad Request) if the keyValue has already an ID
* @throws URISyntaxException if the Location URI syntax is incorrect
*/
@RequestMapping(value = "/key-values",
method = RequestMethod.POST,
produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
@Transactional @Modifying
public ResponseEntity<KeyValue> createKeyValue(@Valid @RequestBody KeyValue keyValue) throws URISyntaxException {
log.debug("REST request to save KeyValue : {}", keyValue);
if (keyValue.getId() != null) {
return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert("keyValue", "idexists", "A new keyValue cannot already have an ID")).body(null);
}
KeyValue result = keyValueRepository.save(keyValue);
keyValueSearchRepository.save(result);
return ResponseEntity.created(new URI("/api/key-values/" + result.getId()))
.headers(HeaderUtil.createEntityCreationAlert("keyValue", result.getId().toString()))
.body(result);
}
/**
* PUT /key-values : Updates an existing keyValue.
*
* @param keyValue the keyValue to update
* @return the ResponseEntity with status 200 (OK) and with body the updated keyValue,
* or with status 400 (Bad Request) if the keyValue is not valid,
* or with status 500 (Internal Server Error) if the keyValue couldnt be updated
* @throws URISyntaxException if the Location URI syntax is incorrect
*/
@RequestMapping(value = "/key-values",
method = RequestMethod.PUT,
produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
@Transactional @Modifying
public ResponseEntity<KeyValue> updateKeyValue(@Valid @RequestBody KeyValue keyValue) throws URISyntaxException {
log.debug("REST request to update KeyValue : {}", keyValue);
if (keyValue.getId() == null) {
return createKeyValue(keyValue);
}
KeyValue result = keyValueRepository.save(keyValue);
keyValueSearchRepository.save(result);
return ResponseEntity.ok()
.headers(HeaderUtil.createEntityUpdateAlert("keyValue", keyValue.getId().toString()))
.body(result);
}
/**
* GET /key-values : get all the keyValues.
*
* @return the ResponseEntity with status 200 (OK) and the list of keyValues in body
*/
@RequestMapping(value = "/key-values",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public List<KeyValue> getAllKeyValues() {
log.debug("REST request to get all KeyValues");
List<KeyValue> keyValues = keyValueRepository.findAll();
return keyValues;
}
/**
* GET /key-values/:id : get the "id" keyValue.
*
* @param id the id of the keyValue to retrieve
* @return the ResponseEntity with status 200 (OK) and with body the keyValue, or with status 404 (Not Found)
*/
@RequestMapping(value = "/key-values/{id}",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public ResponseEntity<KeyValue> getKeyValue(@PathVariable Long id) {
log.debug("REST request to get KeyValue : {}", id);
KeyValue keyValue = keyValueRepository.findOne(id);
return Optional.ofNullable(keyValue)
.map(result -> new ResponseEntity<>(
result,
HttpStatus.OK))
.orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
}
/**
* DELETE /key-values/:id : delete the "id" keyValue.
*
* @param id the id of the keyValue to delete
* @return the ResponseEntity with status 200 (OK)
*/
@RequestMapping(value = "/key-values/{id}",
method = RequestMethod.DELETE,
produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
@Transactional @Modifying
public ResponseEntity<Void> deleteKeyValue(@PathVariable Long id) {
log.debug("REST request to delete KeyValue : {}", id);
keyValueRepository.delete(id);
keyValueSearchRepository.delete(id);
return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert("keyValue", id.toString())).build();
}
/**
* SEARCH /_search/key-values?query=:query : search for the keyValue corresponding
* to the query.
*
* @param query the query of the keyValue search
* @return the result of the search
*/
@RequestMapping(value = "/_search/key-values",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public List<KeyValue> searchKeyValues(@RequestParam String query) {
log.debug("REST request to search KeyValues for query {}", query);
return StreamSupport
.stream(keyValueSearchRepository.search(queryStringQuery(query)).spliterator(), false)
.collect(Collectors.toList());
}
@Timed
@RequestMapping(value = "/key-values/rb/{id}",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
public List<KeyValue> getKeyValuesByResourceBundleId(@PathVariable Long id) {
log.debug("REST request to get all KeyValues by Resource Bundle Id");
List<KeyValue> keyValues = keyValueRepository.getKeyValuesByResourceBundleId( id );
return keyValues;
}
}
<file_sep>/src/main/java/org/jhipster/i18n/web/websocket/package-info.java
/**
* WebSocket services, using Spring Websocket.
*/
package org.jhipster.i18n.web.websocket;
|
44b53ca8006f582c1735bb4efcb867da93dbdf3c
|
[
"JavaScript",
"Java",
"SQL",
"Gradle"
] | 20
|
JavaScript
|
sam888/jhipster_i18n
|
90dd72129eba760f424533408bca36267c8b6c19
|
cfc6cdbbd20e21f8ab30f01717fb2a811808396f
|
refs/heads/master
|
<repo_name>MinecraftDawn/testEZRPG<file_sep>/Assets/Script/Player/PlayerController.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : Entity
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
moving();
roateing();
}
public override void moving()
{
//往前
if (Input.GetKey(KeyCode.W))
{
this.transform.Translate(Vector3.forward *speed);
}
//往後
if (Input.GetKey(KeyCode.S))
{
this.transform.Translate(Vector3.back*speed);
}
//往左
if (Input.GetKey(KeyCode.A))
{
this.transform.Translate(Vector3.left*speed);
}
//往右
if (Input.GetKey(KeyCode.D))
{
this.transform.Translate(Vector3.right*speed);
}
}
private void roateing()
{
//向左轉
if (Input.GetKey(KeyCode.LeftArrow))
{
this.transform.Rotate(0f,2f,0f);
}
//向左轉
if (Input.GetKey(KeyCode.RightArrow))
{
this.transform.Rotate(0f,-2f,0f);
}
}
private void OnCollisionEnter(Collision other)
{
Entity otherEntity = other.gameObject.GetComponent<Entity>();
if (otherEntity != null)
{
Damage(otherEntity.AttackPower);
}
}
}
<file_sep>/Assets/Script/Entity.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public abstract class Entity : MonoBehaviour
{
protected int health = 100;
public int Health
{
get { return health;}
protected set { health = value; }
}
protected float speed = 0.05f;
protected int attackPower = 10;
public int AttackPower
{
get { return attackPower;}
protected set { attackPower = value; }
}
public virtual void Damage(int damage)
{
if(damage < 0 ) return;
if (Health - damage < 0)
{
Health = 0;
Destroy(this.gameObject);
}
else
{
Health -= damage;
}
}
public abstract void moving();
}
|
8b0ed0ae2a6897ce54239487058033426f5286e1
|
[
"C#"
] | 2
|
C#
|
MinecraftDawn/testEZRPG
|
859f6c78e0653cc80a2fba21ca2653d990537320
|
8be8835fa30dfba8c0684217ec85c7b7ef00342b
|
refs/heads/master
|
<file_sep> <NAME>
2328529
<NAME>
2290555
Assignment 4
CPSC 350-01<file_sep>#include "Window.h"
#include <iostream>
using namespace std;
Window::Window(){
status = false;
idleTime = 0;
}
Window::~Window(){
//idk what goes here, nothing to delete
}
void Window::updateStatus(bool isFull){
status = isFull;
}
bool Window::getStatus(){
return status;
}
void Window::setIdle(int t){
idleTime = 0;
}
int Window::getIdle(){
return idleTime;
}
//All basic accessor/mutator fuctions
//increments the idle time
void Window::increment(){
idleTime++;
}
<file_sep>#include <iostream>
using namespace std;
class Window{
public:
Window(); //default (and only) constructor
//no overloaded needed because no window customization
~Window(); //deconstructor
void updateStatus(bool isFull); //set the window status to the parameter
bool getStatus(); //return the status
void setIdle(int t); //set the idle time
int getIdle(); //return the idletime
void increment(); //increment the idle time
//probably should have added an increment() to student...
private:
int idleTime;
bool status; //true if talking with student;
};
<file_sep>//#include "GenQueue2.h"
//#include "GenLinkedList.h"
#include "Register.h"
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char **argv){
string input;
int windows;
if(argc > 1){
input = argv[1];
}
else{
cout << "No command line argument provided, try again." << endl;
exit(0);
}
ifstream check(input);
if(check){
string numWindow;
getline(check, numWindow);
windows = stoi(numWindow);
check.close();
//read in the given file and take in the first line to initialize number of windows
}
else{
cout << "[Error] Could not find file: " << input << endl;
exit(0);
}
Register office(windows, input); //constructor
office.simulate(); //simulates everything basically
}
<file_sep>#include <iostream>
using namespace std;
class Student{
public:
Student(); //default constructor
Student(int needs); //overloaded construct. passing in needed time
void setTime(int time); //mutator for wait time
int getTime(); //accessor for wait time
void setCount(int count); //mutator for needed time
int getCount();//accessor for needed time
private:
int neededTime; //amount of time needed at window
int waitTime; //amount of time waiting in queue
};
<file_sep>#include "Register.h"
#include <iostream>
#include <fstream>
#include <algorithm>
using namespace std;
Register::Register(){
myQueue = new GenQueue<Student>();
windowArray = NULL;
studentArray = NULL;
totalWindows = 0;
totalStudents = 0;
file = " ";
}
Register::Register(int num, string fileName){
myQueue = new GenQueue<Student>();
waitTimes = new GenQueue<int>();
windowArray = new Window[num];
for(int i = 0; i < num; ++i){
windowArray[i] = Window();
}
studentArray = new int[num];
totalWindows = num;
totalStudents = 0;
file = fileName;
}
Register::~Register(){
delete[] windowArray;
delete[] studentArray;
delete waitTimes;
delete myQueue;
}
void Register::simulate(){
//Student temp;
bool isNotDone = true; //to check if file is done reading
string currentLine;
int num, hold;
ifstream stream(file);
if(stream){
getline(stream, currentLine);
//skip over first line, already read in main
while(isNotDone){
//read in the current line
if(getline(stream,currentLine)){
num = stoi(currentLine);
//store int conversion
}
else{
isNotDone = false;
num = 0;
} //allow loop to continue even after end of file
//until last student fully passes through the system
while(time != num){
time++;
removeAndDrop();
//increment all remaining students
fillWindows();
incrementIdle();
incrementWait();
/**
printData();
cout << "Time: " << time << endl;
**/
//once the time matches, add the students to queue
if(time == num){
getline(stream,currentLine);
hold = stoi(currentLine);
for(int i = 0; i < hold; i++){
getline(stream,currentLine);
myQueue->insert(Student(stoi(currentLine)));
}
}
if(!(isNotDone || stillStudents())){
break;
} //once file read is done AND all students are
//out of the office, break the loop
//windowArray[2].setIdle(3);
}
}
}
else{
cout << "[Error] Could not find file: " << file << endl;
exit(0);
}
storeVals();
printData();
/**
cout << "\nTotal window idle times: " << endl;
for(int i = 0; i < totalWindows; ++i){
cout << "Window " << i << ": "<< windowArray[i].getIdle() << endl;
}
cout << "Student Wait Times:" << endl;
for(int j = 0; j < totalStudents; ++j){
cout << waitCalcs[j] << endl;
}
**/
}
void Register::incrementWait(){
Student temp;
for(int i = 0; i < myQueue->getSize(); ++i){
temp = myQueue->remove();
temp.setTime((temp.getTime()) + 1);
myQueue->insert(temp);
}
//increment the wait time of all students in the Queue
//by removing each one, incrementing its waittime,
//then re-inserting them at the back; this is
//repeated as many times as the size.
}
void Register::incrementIdle(){
for(int i = 0; i < totalWindows; ++i){
if(windowArray[i].getStatus()){
windowArray[i].increment();
}
//incrememnt the idle time of any open window
}
}
void Register::removeAndDrop(){
for(int i = 0; i < totalWindows; ++i){
if(studentArray[i] == 0){
windowArray[i].updateStatus(false);
//if a getCount in the studentarray is 0, open the window up
}
else{
studentArray[i]--;
//else, decrement the amount of time needed
}
}
}
void Register::fillWindows(){
for(int i = 0; i < totalWindows; ++i){
if(!windowArray[i].getStatus()){
if(!myQueue->isEmpty()){
Student temp = myQueue->remove();
studentArray[i] = temp.getCount();
waitTimes->insert(temp.getTime());
windowArray[i].updateStatus(true);
totalStudents++;
//removes a student from Queue
//stores wait time into a queue of wait times
//puts time needed into an array of ints
//updates any now occupied window to have true getStatus
//increments number of students present
}
}
}
}
void Register::printData(){
cout << "Mean student wait time: " << meanWait() << " minutes"<< endl;
cout << "Median student wait time: " << medianWait() << " minutes" <<endl;
cout << "Longest student wait time: " << longestWait() << " minutes" << endl;
cout << "Number of students waiting over ten minutes: " << waitOverTen() << endl;
cout << endl;
cout << "Mean window idle time: " << meanIdle() << " minutes" << endl;
cout << "Longest window idle time: " << longestIdle() << " minutes" << endl;
cout << "Number of windows idle for over five minutes: " << idleOverFive() << endl;
/**
cout << " " << endl;
for(int i = 0; i < totalWindows; ++i){
cout << "Window " << i << ": ";
if(!windowArray[i].getStatus()){
cout << "Open" << endl;
}
else{
cout << "Full - Time remaining: " << studentArray[i] <<endl;
}
}
**/
}
//checks if there are still students in the queue/window
//even after file is done reading
bool Register::stillStudents(){
for(int i = 0; i < totalWindows; ++i){
if(windowArray[i].getStatus()){
return true;
}
}
if(!myQueue->isEmpty()){
return true;
}
return false;
//meant to return true if the queue is occupied or any window is occupied
}
void Register::storeVals(){
waitCalcs = new int[totalStudents]; //new int array of length
//equal to number of students
for(int i = 0; i < totalStudents; ++i){
waitCalcs[i] = waitTimes->remove();
}
sort(waitCalcs, waitCalcs+totalStudents);
//puts all the wait times into an array and sorts it
idleCalcs = new int[totalWindows];
for(int i = 0; i < totalWindows; ++i){
idleCalcs[i] = windowArray[i].getIdle();
}
sort(idleCalcs, idleCalcs+totalWindows);
//puts all the idle times into an array and sorts it
}
int Register::longestWait(){ //returns last element of sorted array
//
return waitCalcs[totalStudents-1];
}
int Register::longestIdle(){
return idleCalcs[totalWindows-1];
}
double Register::meanWait(){
double sum1 = 0;
for(int i = 0; i < totalStudents; ++i){
sum1 += waitCalcs[i];
} //total all the values then divide by total amount
cout << sum1 << endl;
cout << totalStudents << endl;
return sum1/totalStudents;
}
double Register::meanIdle(){
double sum2 = 0;
for(int i = 0; i < totalWindows; ++i){
sum2 += idleCalcs[i];
}
//total all the values then divide by total amount
return sum2/totalWindows;
}
double Register::medianWait(){
int idx;
if(totalStudents%2 == 0){
idx = totalStudents/2;
return (((double)waitCalcs[idx] + waitCalcs[idx + 1])/2);
//if even, return avg of two middle values
}
else{
return (double)waitCalcs[(idx + 1)/2];
//if odd number, return the middle
}
}
int Register::waitOverTen(){
int count = 0;
for(int i = 0; i < totalStudents; ++i){
if(waitCalcs[i] > 10){
count++; //increment if wait time was over 10min
}
}
return count;
}
int Register::idleOverFive(){
int count = 0;
for(int i = 0; i < totalWindows; ++i){
if(idleCalcs[i] > 5){
count++; //increment if idle time was over 5min
}
}
return count;
}
<file_sep>#include "Student.h"
#include <iostream>
using namespace std;
Student::Student(){
waitTime = 0;
neededTime = 0; //default both to 0
}
Student::Student(int needs){
neededTime = needs;
waitTime = 0; //set needed time to param. and wait to zero
}
void Student::setTime(int time){
waitTime = time; //update the wait time
}
int Student::getTime(){
return waitTime; //return wait time
}
void Student::setCount(int count){
neededTime = count; //update needed time
}
int Student::getCount(){
return neededTime; //literally what the line says
}
<file_sep>#include "GenLinkedList.h"
#include <iostream>
using namespace std;
template <class T>
class GenQueue{
public:
GenQueue();
~GenQueue();
void insert(T data);
T remove();
T peek();
bool isEmpty();
int getSize();
GenLinkedList<T> *myList;
private:
int numElements;
};
template <class T>
GenQueue<T>::GenQueue(){
myList = new GenLinkedList<T>();
numElements = 0;
}
template <class T>
GenQueue<T>::~GenQueue(){
delete myList;
}
template <class T>
void GenQueue<T>::insert(T data){
myList->insertBack(data);
numElements++;
}
template <class T>
T GenQueue<T>::remove(){
numElements--;
return myList->removeFront();
}
template <class T>
T GenQueue<T>::peek(){
return myList->front;
}
template <class T>
bool GenQueue<T>::isEmpty(){
return (numElements==0);
}
template <class T>
int GenQueue<T>::getSize(){
return numElements;
}
<file_sep>#include <iostream>
#include "Student.h"
#include "Window.h"
#include "GenQueue.h"
using namespace std;
class Register{
public:
Register(); //default constructor
Register(int num, string fileName); //overloaded,takes number of windows and fileName
~Register(); //deconstructor
void simulate(); //runs whole simulation loop
void printData(); //prints all statistics at end
//void newStudents();
void incrementWait(); //increments wait time of all students in queue
void incrementIdle(); //increments idle time of all open windows
void removeAndDrop(); //opens up windows that are done with students
void fillWindows(); //fills any open windows students in queue
//lol
bool stillStudents(); //experiment
void storeVals(); //moves all values from queues/object arrays to int arrays and sorts them
double meanWait(); //returns mean wait time
double medianWait(); //returns median wait time
int longestWait(); //returns longest wait time
int waitOverTen(); //returns number of students who waited over ten minutes
double meanIdle(); //returns mean window idle time
int longestIdle(); //returns longest window idle time
int idleOverFive(); //returns number of windows idle for over 5 minutes
private:
GenQueue<Student> *myQueue; //queue that holds new studends
GenQueue<int> *waitTimes; //queue that stores final wait time of students
Window* windowArray; //array storing each Window object
int* studentArray; //array that stores the remaining time needed for students at fillWindows
//is parallel to windowArray
int* waitCalcs; //array that the waitTimes pushes data to for sorting
int* idleCalcs; //array that all idle times are pushed to for sorting
int totalStudents; //total number of students passed through
int totalWindows; //total number of windows initialized
string file; //passed in string for filena,me
int time; //represents clock ticks
};
<file_sep>#include <iostream>
using namespace std;
template <class T>
class GenQueue2{
public:
GenQueue2();
GenQueue2(int maxSize);
~GenQueue2();
void insert(T data);
T remove();
T peek();
bool isFull();
bool isEmpty();
int getSize();
int head;
int tail;
int mSize;
int numElements;
T *myQueue;
private:
};
template <class T>
GenQueue2<T>::GenQueue2(){
myQueue = new T[25];
mSize = 25;
numElements = 0;
head = 0;
tail = -1;
}
template <class T>
GenQueue2<T>::GenQueue2(int maxSize){
myQueue = new T[maxSize];
mSize = maxSize;
numElements = 0;
head = 0;
tail = -1;
}
template <class T>
GenQueue2<T>::~GenQueue2(){
delete myQueue;
}
template <class T>
void GenQueue2<T>::insert(T data){
if(isFull()){
T* newArr = new T[2*mSize];
for(int i = 0; i < mSize; ++i){
newArr[i] = myQueue[i];
}
mSize *= 2;
delete myQueue;
myQueue = newArr;
}
myQueue[++tail] = data;
++numElements;
}
template <class T>
T GenQueue2<T>::remove(){
if(numElements > 0){
T c;
c = myQueue[head];
++head;
--numElements;
return c;
}
else{
cout << "Queue is empty. Remove failed." << endl;
exit(0);
}
}
template <class T>
T GenQueue2<T>::peek(){
if(numElements > 0){
return myQueue[head];
}
else{
cout << "Queue is empty. Peek failed." << endl;
exit(0);
}
}
template <class T>
bool GenQueue2<T>::isFull(){
return (numElements == mSize);
}
template <class T>
bool GenQueue2<T>::isEmpty(){
return (numElements == 0);
}
template <class T>
int GenQueue2<T>::getSize(){
return numElements;
}
|
464c151c0a66cf8d63e21aadb8726daab93c1d9e
|
[
"Text",
"C++"
] | 10
|
Text
|
RyanMillares/Assignment-4
|
8cf1ff32228e7279568a8478211c0818d8b75bd4
|
f9f527e3b8cdf0fd14453306ebd316362ff7348e
|
refs/heads/master
|
<file_sep>package com.mvc.App.controller;
import com.mvc.App.entity.Patient;
import com.mvc.App.service.PatientService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@Controller
public class PatientController {
@Autowired
PatientService patientService;
@GetMapping("/")
public String patientsList(Model model, @Param("keyword") String keyword) {
List<Patient> listPatients = patientService.findAll(keyword);
model.addAttribute("patients", listPatients);
model.addAttribute("keyword", keyword);
return "patient-list";
}
@GetMapping("/create")
public String createForm(Model model) {
model.addAttribute("form", new Patient());
return "create-patient-form";
}
@PostMapping("/save")
public String savePatients(Patient patient, Model model) {
patientService.save(patient);
return "redirect:/";
}
@GetMapping("/edit/{id}")
public String showEditForm(@PathVariable Long id, Model model) {
model.addAttribute("form", patientService.findById(id).orElse(new Patient()));
return "create-patient-form";
}
@GetMapping("/delete/{id}")
public String deletePatient(@PathVariable Long id) {
patientService.deleteById(id);
return "redirect:/";
}
}
<file_sep>package com.mvc.App.config;
import com.mvc.App.entity.Patient;
import com.mvc.App.entity.Tested;
import com.mvc.App.repository.PatientRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Configuration;
@Configuration
public class PatientConfig implements CommandLineRunner {
@Autowired
PatientRepository repository;
@Override
public void run(String... args) throws Exception {
repository.deleteAll();
repository.save(new Patient(1, "elena", "prisca", "<EMAIL>", Tested.POSITIVE));
repository.save(new Patient(2, "Alba", "villa", "<EMAIL>", Tested.NEGATIVE));
repository.save(new Patient(3, "John", "Roger", "<EMAIL>", Tested.NOT_TESTED));
repository.findAll();
}
}
<file_sep>package com.mvc.App.service;
import com.mvc.App.entity.Patient;
import java.util.List;
import java.util.Optional;
public interface PatientService {
Optional<Patient> findById(Long id);
List<Patient> findAll(String keyword);
Patient save(Patient patient);
void deleteById(Long id);
}
|
e9f9bed4e6d56d2fc5a0cb08db406a535f46c643
|
[
"Java"
] | 3
|
Java
|
Patounet/SpringBoot-WebMVC-Thymeleaf-App
|
b7541008218d85425ddf4f27c5dfb54875d6202f
|
0effe41b1fd6d9334ab844316582d3c9f9dba6bd
|
refs/heads/main
|
<repo_name>madhavsv/final<file_sep>/kwitter_room.js
var firebaseConfig = {
apiKey: "<KEY>",
authDomain: "kwitter-9399e.firebaseapp.com",
databaseURL: "https://kwitter-9399e-default-rtdb.firebaseio.com",
projectId: "kwitter-9399e",
storageBucket: "kwitter-9399e.appspot.com",
messagingSenderId: "193141302378",
appId: "1:193141302378:web:a3eea371e248ffdb711613"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
login_name=localStorage.getItem("user_name");
document.getElementById("welcome").innerHTML="Welcome " + login_name + "!";
function addroom() {
room=document.getElementById("roomname").value;
firebase.database().ref("/").child(room).update({
purpose:"adding room name"
});
localStorage.setItem("room_name",room);
window.location="kwitter_page.html";
}
function getData() {firebase.database().ref("/").on('value', function(snapshot) {document.getElementById("output").innerHTML = "";snapshot.forEach(function(childSnapshot) {childKey = childSnapshot.key;
Room_names = childKey;
//Start code
row="<div class='room_name' id='" + Room_names + "'onclick='redirectetoroomname(this.id)'>#" + Room_names + "</div><hr>";
document.getElementById("output").innerHTML+=row;
//End code
});});}
getData();
function redirectetoroomname(name) {
localStorage.setItem("room_name",name);
window.location="kwitter_page.html";
}
function logout() {
localStorage.removeItem("user_name");
localStorage.removeItem("room_name");
window.location="index.html";
}
|
479b4773dfc8839d57361d9b1b86897cf81bcc53
|
[
"JavaScript"
] | 1
|
JavaScript
|
madhavsv/final
|
10a234d7597ea1211c894bcef17268ada8884d86
|
85447c1d25da99644db3bb502cdcd3c29f7854bd
|
refs/heads/master
|
<file_sep># 
The front-end for [konarium.io](https://github.com/roqueando/konarium.io)<file_sep>const {app, BrowserWindow} = require ("electron");
const URL = `http://localhost:7373/`;
app.on ("ready", () => {
const Window = new BrowserWindow ({
webPreferences: {
nodeIntegration: false
}
});
Window.loadURL (URL);
});
|
7a0f86e076b5056450b32407fbb7a43b96b4ee33
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
roqueando/konarium.io-front-end
|
a776712ebef15f619dd9800c1a1d5e375d1d1b41
|
b462a12b41a7e8b7e3fc0fb5e44d317bf06f7cff
|
refs/heads/main
|
<repo_name>torisuta1/food-takeout-map<file_sep>/spec/system/users_spec.rb
require "rails_helper"
RSpec.describe "User", type: :system do
let(:user) { create(:user) }
let(:token) { user.send_reset_password_instructions }
let!(:other_user) { create(:other_user) }
before do
ActionMailer::Base.deliveries.clear
end
describe "about sign_up" do
before do
visit new_user_registration_path
end
context "if entered successfully" do
it "Successful registration(Unauthorized)" do
fill_in "ユーザーネーム", with: "test"
fill_in "メールアドレス", with: "<EMAIL>"
fill_in "パスワード", with: "<PASSWORD>"
fill_in "確認用パスワード", with: "<PASSWORD>"
check "同意"
click_button "サインアップ"
expect(current_path).to eq root_path
expect(page).to have_content "本人確認用のメールを送信しました。メール内のリンクからアカウントを有効化させてください。"
end
end
context "abnormal value" do
it "Registration fails" do
fill_in "ユーザーネーム", with: ""
fill_in "メールアドレス", with: ""
fill_in "パスワード", with: ""
fill_in "確認用パスワード", with: ""
check "同意"
click_button "サインアップ"
expect(page).to have_content "3 件のエラーが発生したため処理されませんでした:"
end
end
context "username not entered" do
it "Registration fails" do
fill_in "ユーザーネーム", with: ""
fill_in "メールアドレス", with: "<EMAIL>"
fill_in "パスワード", with: "<PASSWORD>"
fill_in "確認用パスワード", with: "<PASSWORD>"
check "同意"
click_button "サインアップ"
expect(page).to have_content "エラーが発生したため処理されませんでした:"
end
end
context "email not entered" do
it "Registration fails" do
fill_in "ユーザーネーム", with: "test"
fill_in "メールアドレス", with: ""
fill_in "パスワード", with: "<PASSWORD>"
fill_in "確認用パスワード", with: "<PASSWORD>"
check "同意"
click_button "サインアップ"
expect(page).to have_content "エラーが発生したため処理されませんでした:"
end
end
context "password not entered" do
it "Registration fails" do
fill_in "ユーザーネーム", with: "test"
fill_in "メールアドレス", with: "<EMAIL>"
fill_in "パスワード", with: ""
fill_in "確認用パスワード", with: "<PASSWORD>"
check "同意"
click_button "サインアップ"
expect(page).to have_content "2 件のエラーが発生したため処理されませんでした:"
end
end
context "password confirmation not entered" do
it "Registration fails" do
fill_in "ユーザーネーム", with: "test"
fill_in "メールアドレス", with: "<EMAIL>"
fill_in "パスワード", with: "<PASSWORD>"
fill_in "確認用パスワード", with: ""
check "同意"
click_button "サインアップ"
expect(page).to have_content "エラーが発生したため処理されませんでした:"
end
end
context "if do not agree" do
it "Registration fails" do
fill_in "ユーザーネーム", with: "test"
fill_in "メールアドレス", with: "<EMAIL>"
fill_in "パスワード", with: "<PASSWORD>"
fill_in "確認用パスワード", with: "<PASSWORD>"
uncheck "同意"
click_button "サインアップ"
expect(page).to have_content "エラーが発生したため処理されませんでした:"
end
end
context "transition to the login screen" do
it "go to the login screen" do
click_link "log_in"
expect(current_path).to eq new_user_session_path
end
end
context "transition to the resend authentication email screen" do
it "go to the resend authentication email" do
click_on "認証メールが届かない場合"
expect(current_path).to eq new_user_confirmation_path
end
end
context "send authentication email" do
it "successful authentication" do
Devise::Mailer.confirmation_instructions(user)
expect(ActionMailer::Base.deliveries.size).to eq(1)
mail = ActionMailer::Base.deliveries.last
mail_body = mail.body.encoded
expect(mail_body).to have_link "アカウントを認証する"
end
end
end
describe "about log_in" do
before do
visit new_user_session_path
user1 = user
user1.confirm
end
context "normal input" do
it "successfully logged in" do
fill_in "メールアドレス", with: "<EMAIL>"
fill_in "パスワード", with: "<PASSWORD>"
click_button "ログイン"
expect(current_path).to eq root_path
expect(page).to have_content "ログインしました。"
end
end
context "email not entered" do
it "login fails" do
fill_in "メールアドレス", with: ""
fill_in "パスワード", with: "<PASSWORD>"
click_button "ログイン"
expect(current_path).to eq user_session_path
expect(page).to have_content "メールアドレス もしくはパスワードが不正です。"
end
end
context "password not entered" do
it "login fails" do
fill_in "メールアドレス", with: "<EMAIL>"
fill_in "パスワード", with: ""
click_button "ログイン"
expect(current_path).to eq user_session_path
expect(page).to have_content "メールアドレス もしくはパスワードが不正です。"
end
end
context "go to the sign-up screen" do
it "go to the sign-up screen" do
click_link "sign_up"
expect(current_path).to eq new_user_registration_path
end
end
context "go to the password reset screen" do
it "go to the password reset screen" do
click_on "パスワードを忘れた場合"
expect(current_path).to eq new_user_password_path
end
end
context "transition to the resend authentication email screen" do
it "go to the resend authentication email" do
click_on "認証メールが届かない場合"
expect(current_path).to eq new_user_confirmation_path
end
end
context "if unauthenticated" do
it "can not log in" do
fill_in "メールアドレス", with: "<EMAIL>"
fill_in "パスワード", with: "<PASSWORD>"
click_button "ログイン"
expect(current_path).to eq user_session_path
expect(page).to have_content "メールアドレスの本人確認が必要です。"
end
end
context "not registered." do
it "can not log in" do
fill_in "メールアドレス", with: "<EMAIL>"
fill_in "パスワード", with: "<PASSWORD>"
click_button "ログイン"
expect(current_path).to eq user_session_path
expect(page).to have_content "メールアドレス もしくはパスワードが不正です。"
end
end
end
describe "about reset_password" do
before do
visit new_user_password_path
end
context "normal input" do
it "transmission successful" do
fill_in "メールアドレス", with: "<EMAIL>"
click_on "パスワードリセットメールを送信"
expect(current_path).to eq new_user_session_path
expect(page).to have_content "パスワードの再設定について数分以内にメールでご連絡いたします。"
end
end
context "unentered" do
it "transmission fails" do
fill_in "メールアドレス", with: ""
click_on "パスワードリセットメールを送信"
expect(current_path).to eq new_user_password_path
expect(page).to have_content "エラーが発生したため処理されませんでした:"
end
end
context "unsigned email input" do
it "transmission fails" do
fill_in "メールアドレス", with: "<EMAIL>"
click_on "パスワードリセットメールを送信"
expect(current_path).to eq new_user_password_path
expect(page).to have_content "エラーが発生したため処理されませんでした:"
end
end
context "transition to the login screen" do
it "go to the login screen" do
click_link "log_in"
expect(current_path).to eq new_user_session_path
end
end
context "go to the sign-up screen" do
it "go to the sign-up screen" do
click_link "sign_up"
expect(current_path).to eq new_user_registration_path
end
end
context "transition to the resend authentication email screen" do
it "go to the resend authentication email" do
click_on "認証メールが届かない場合"
expect(current_path).to eq new_user_confirmation_path
end
end
context "send change email" do
it "successful change" do
ActionMailer::Base.deliveries
user.confirm
fill_in "メールアドレス", with: "<EMAIL>"
click_on "パスワードリセットメールを送信"
expect(ActionMailer::Base.deliveries.size).to eq(2)
mail = ActionMailer::Base.deliveries.last
mail_body = mail.body.encoded
expect(mail_body).to have_link "パスワード変更"
end
end
end
describe "about change_password" do
before do
user.confirm
visit edit_user_password_path(reset_password_token: token)
end
context "normal input" do
it "successful change" do
fill_in "新パスワード", with: "<PASSWORD>"
fill_in "パスワード確認", with: "<PASSWORD>"
click_on "パスワード変更"
expect(current_path).to eq root_path
expect(page).to have_content "パスワードが正しく変更されました。"
end
end
context "password not entered" do
it "change fails" do
fill_in "新パスワード", with: ""
fill_in "パスワード確認", with: ""
click_on "パスワード変更"
expect(page).to have_content "エラーが発生したため処理されませんでした:"
end
end
context "transition to the login screen" do
it "go to the login screen" do
click_link "log_in"
expect(current_path).to eq new_user_session_path
end
end
context "go to the sign-up screen" do
it "go to the sign-up screen" do
click_link "sign_up"
expect(current_path).to eq new_user_registration_path
end
end
context "transition to the resend authentication email screen" do
it "go to the resend authentication email" do
click_on "認証メールが届かない場合"
expect(current_path).to eq new_user_confirmation_path
end
end
context "if unauthenticated" do
it "will be changed and prompted for authentication" do
other_token = other_user.send_reset_password_instructions
visit edit_user_password_path(reset_password_token: other_token)
fill_in "新パスワード", with: "<PASSWORD>"
fill_in "パスワード確認", with: "<PASSWORD>"
click_on "パスワード変更"
expect(current_path).to eq new_user_session_path
expect(page).to have_content "パスワードが正しく変更されました。"
expect(page).to have_content "メールアドレスの本人確認が必要です。"
end
end
context "token is invalid." do
it "change fails" do
visit edit_user_password_path(reset_password_token: "<PASSWORD>")
fill_in "新パスワード", with: "<PASSWORD>"
fill_in "パスワード確認", with: "<PASSWORD>"
click_on "パスワード変更"
expect(page).to have_content "エラーが発生したため処理されませんでした:"
end
end
end
describe "about resend_email" do
before do
visit user_confirmation_path
end
context "normal input" do
it "transmission successful" do
user
fill_in "メールアドレス", with: "<EMAIL>"
click_on "認証メール再送"
expect(current_path).to eq new_user_session_path
expect(page).to have_content "アカウントの有効化について数分以内にメールでご連絡します。"
end
end
context "email not entered" do
it "resend fails" do
fill_in "メールアドレス", with: ""
click_on "認証メール再送"
expect(page).to have_content "エラーが発生したため処理されませんでした:"
end
end
context "unsigned email" do
it "resend fails" do
fill_in "メールアドレス", with: "<EMAIL>"
click_on "認証メール再送"
expect(page).to have_content "エラーが発生したため処理されませんでした:"
end
end
context "transition to the login screen" do
it "go to the login screen" do
click_link "log_in"
expect(current_path).to eq new_user_session_path
end
end
context "go to the sign-up screen" do
it "go to the sign-up screen" do
click_link "sign_up"
expect(current_path).to eq new_user_registration_path
end
end
context "go to the password reset screen" do
it "go to the password reset screen" do
click_on "パスワードを忘れた場合"
expect(current_path).to eq new_user_password_path
end
end
end
describe "about user_edit" do
let(:user) { create(:user, email: "<EMAIL>") }
before do
user.confirm
visit new_user_session_path
fill_in "メールアドレス", with: "<EMAIL>"
fill_in "パスワード", with: "<PASSWORD>"
click_button "ログイン"
click_on "navbarDropdown"
click_link "ユーザー編集"
end
context "normal input" do
it "successful update" do
fill_in "ユーザーネーム", with: "hoge"
fill_in "メールアドレス", with: "<EMAIL>"
fill_in "パスワード", with: "<PASSWORD>"
fill_in "確認用パスワード", with: "<PASSWORD>"
fill_in "現在のパスワード", with: "<PASSWORD>"
click_on "更新"
expect(current_path).to eq root_path
expect(page).to have_content "アカウント情報を変更しました。"
end
end
context "username not enterd" do
it "update fails" do
fill_in "ユーザーネーム", with: ""
fill_in "メールアドレス", with: "<EMAIL>"
fill_in "パスワード", with: "<PASSWORD>"
fill_in "確認用パスワード", with: "<PASSWORD>"
fill_in "現在のパスワード", with: "<PASSWORD>"
click_on "更新"
expect(current_path).to eq edit_user_registration_path
expect(page).to have_content "エラーが発生したため処理されませんでした:"
end
end
context "email not enterd" do
it "update fails" do
fill_in "ユーザーネーム", with: "hoge"
fill_in "メールアドレス", with: ""
fill_in "パスワード", with: "<PASSWORD>"
fill_in "確認用パスワード", with: "<PASSWORD>"
fill_in "現在のパスワード", with: "<PASSWORD>"
click_on "更新"
expect(current_path).to eq edit_user_registration_path
expect(page).to have_content "エラーが発生したため処理されませんでした:"
end
end
context "password not enterd" do
it "update fails" do
fill_in "ユーザーネーム", with: "hoge"
fill_in "メールアドレス", with: "<EMAIL>"
fill_in "パスワード", with: ""
fill_in "確認用パスワード", with: "<PASSWORD>"
fill_in "現在のパスワード", with: "<PASSWORD>"
click_on "更新"
expect(current_path).to eq edit_user_registration_path
expect(page).to have_content "2 件のエラーが発生したため処理されませんでした:"
end
end
context "password confirmation not enterd" do
it "update fails" do
fill_in "ユーザーネーム", with: "hoge"
fill_in "メールアドレス", with: "<EMAIL>"
fill_in "パスワード", with: "<PASSWORD>"
fill_in "確認用パスワード", with: ""
fill_in "現在のパスワード", with: "<PASSWORD>"
click_on "更新"
expect(current_path).to eq edit_user_registration_path
expect(page).to have_content "エラーが発生したため処理されませんでした:"
end
end
context "password not enterd & current password normal input" do
it "successful update" do
fill_in "ユーザーネーム", with: "hoge1"
fill_in "メールアドレス", with: "<EMAIL>"
fill_in "パスワード", with: ""
fill_in "確認用パスワード", with: ""
fill_in "現在のパスワード", with: "<PASSWORD>"
click_on "更新"
expect(current_path).to eq root_path
expect(page).to have_content "アカウント情報を変更しました。変更されたメールアドレスの本人確認のため、本人確認用メールより確認処理をおこなってください。"
end
end
context "current password not enterd" do
it "update falis" do
fill_in "ユーザーネーム", with: "hoge"
fill_in "メールアドレス", with: "<EMAIL>"
fill_in "パスワード", with: "<PASSWORD>"
fill_in "確認用パスワード", with: "<PASSWORD>"
fill_in "現在のパスワード", with: ""
click_on "更新"
expect(current_path).to eq edit_user_registration_path
expect(page).to have_content "エラーが発生したため処理されませんでした:"
end
end
context "abnormal value input" do
it "update falis" do
fill_in "ユーザーネーム", with: "hoge"
fill_in "メールアドレス", with: "<EMAIL>"
fill_in "パスワード", with: "<PASSWORD>"
fill_in "確認用パスワード", with: "<PASSWORD>"
fill_in "現在のパスワード", with: ""
click_on "更新"
expect(current_path).to eq edit_user_registration_path
expect(page).to have_content "エラーが発生したため処理されませんでした:"
end
end
context "delete Account" do
it "account will be deleted." do
click_on "アカウント削除"
page.accept_confirm
expect(current_path).to eq root_path
expect(page).to have_content "アカウントを削除しました。またのご利用をお待ちしております。"
end
end
context "not logged in" do
it "will be asked to log in" do
click_on "ログアウト"
visit edit_user_registration_path
expect(current_path).to eq new_user_session_path
end
end
end
end
<file_sep>/spec/views/devises/change_password_spec.rb
require "rails_helper"
RSpec.describe "password_change_page" do
let!(:user) { create(:user) }
before do
visit edit_user_password_path(reset_password_token: "<PASSWORD>")
end
context "change password" do
it "existing change your password" do
expect(page).to have_selector "h2", text: "パスワード変更"
end
end
context "new password" do
it "existing new password" do
expect(page).to have_content "新パスワード"
end
end
context "confirm new password" do
it "existing confirm new password" do
expect(page).to have_content "パスワード確認"
end
end
context "change button" do
it "existing change button" do
expect(page).to have_button "パスワード変更"
end
end
context "log_in_link" do
it "existing log_inn_link" do
expect(page).to have_link "ログイン"
end
end
context "sign_up_link" do
it "existing sign_up_link" do
expect(page).to have_link "サインアップ"
end
end
context "Authentication email" do
it "existing 認証メールが届かない場合" do
expect(page).to have_link "認証メールが届かない場合"
end
end
end
<file_sep>/spec/models/relationship_spec.rb
require "rails_helper"
RSpec.describe Relationship, type: :model do
describe "association" do
it "belongs_to user" do
expect(Relationship.reflect_on_association(:user).macro).to eq :belongs_to
end
end
end
<file_sep>/app/helpers/application_helper.rb
module ApplicationHelper
def user_logged_in?
!current_user.nil?
end
end
<file_sep>/spec/system/my_post_spec.rb
require "rails_helper"
RSpec.describe "My_post", type: :system do
describe "my_post" do
let!(:post) { create(:post) }
let!(:post3) { create(:post3) }
before do
visit root_path
click_on "ログイン"
fill_in "メールアドレス", with: "<EMAIL>"
fill_in "パスワード", with: "<PASSWORD>"
click_button "ログイン"
end
it "my posts are displayed correctly" do
click_on "navbarDropdown"
click_on "投稿する"
fill_in "new-store-name", with: "test"
fill_in "new-review", with: "test"
select "~1500円", from: "価格帯(必須)"
click_on "投稿"
click_on "navbarDropdown"
click_on "マイ投稿"
expect(page).to have_content "店名: test"
expect(page).to have_content "レビュー: hoge_review"
date = DateTime.now
expect(page).to have_content "投稿日: #{date.strftime("%Y年 %m月 %d日 %H時 %M分")}"
expect(page).to have_content "いいね件数: 1"
expect(page).to have_link "削除"
expect(page).to have_content "店名: test"
expect(page).to have_content "レビュー: test"
end
it "other people is posts will not be displayed" do
click_on "navbarDropdown"
click_on "マイ投稿"
expect(page).to_not have_content "店名: piyo"
expect(page).to_not have_content "レビュー: test_review"
end
it "deleted normally" do
click_on "navbarDropdown"
click_on "マイ投稿"
click_on "削除"
page.accept_confirm
expect(page).to have_content "投稿が削除されました"
expect(page).to_not have_content "店名: test"
end
end
end
<file_sep>/db/migrate/20210726081608_add_genre_to_posts.rb
class AddGenreToPosts < ActiveRecord::Migration[6.1]
def change
add_reference :posts, :genre, foreign_key: true
end
end
<file_sep>/spec/system/my_page_spec.rb
require "rails_helper"
RSpec.describe "My_page", type: :system do
describe "my_page" do
let!(:post2) { create(:post2) }
let!(:post3) { create(:post3) }
before do
visit root_path
click_on "ログイン"
fill_in "メールアドレス", with: "<EMAIL>"
fill_in "パスワード", with: "<PASSWORD>"
click_button "ログイン"
click_on "マイページ"
end
context "user submissions" do
it "my user information and posts are displayed" do
expect(page).to have_content "ユーザー投稿一覧"
expect(page).to have_content "店名: hoge"
expect(page).to have_content "レビュー: fuga_review"
date = DateTime.now
expect(page).to have_content "投稿日: #{date.strftime("%Y年 %m月 %d日 %H時 %M分")}"
expect(page).to have_content "投稿者:"
expect(page).to have_link "hoge3"
expect(page).to have_content "いいね件数: 0"
expect(page).to have_button "like-button-user-show"
expect(page).to have_content "いいねしたユーザー"
end
end
context "like function" do
it "Functioning normally" do
click_button "like-button-user-show"
expect(page).to have_content "いいね件数: 1"
expect(page).to have_link("hoge3", count: 2)
end
end
context "user profile" do
it "user information is displayed" do
expect(page).to have_content "ユーザーネーム: hoge3"
expect(page).to have_content "プロフィール:"
expect(page).to have_content "test"
end
end
context "posts I am liking" do
it "Displayed normally" do
click_button "like-button-user-show"
visit current_path
expect(page).to have_link "hoge"
click_on "hoge"
expect(current_path).to eq post_path(post2)
end
end
context "follow list" do
it "functioning normally" do
click_on "フォロワー: 1"
click_link "hoge"
expect(page).to have_content "ユーザーネーム: hoge"
end
end
context "following list" do
it "functioning normally" do
click_on "フォロー: 1"
click_link "hoge"
expect(page).to have_content "ユーザーネーム: hoge"
end
end
context "follow button" do
it "will not appear on your own my page" do
expect(page).to_not have_button "フォロー"
expect(page).to_not have_button "フォロー解除"
end
end
context "follow button" do
it "shows up on other people is my page" do
visit posts_path
click_on "hoge2"
expect(page).to have_button "フォロー"
end
end
context "when not logged in" do
it "follow button is not displayed on the user details screen" do
click_on "ログアウト"
visit posts_path
click_on "hoge2"
expect(page).to_not have_button "フォロー"
expect(page).to_not have_button "フォロー解除"
end
end
end
end
<file_sep>/spec/views/home_spec.rb
require "rails_helper"
RSpec.describe "home_page" do
before do
visit root_path
end
context "sign_up" do
it "existing サインアップ" do
expect(page).to have_selector "li", text: "サインアップ"
end
end
context "log_in" do
it "existing ログイン" do
expect(page).to have_selector "li", text: "ログイン"
end
end
context "search" do
it "existing 検索" do
expect(page).to have_selector "li", text: "検索"
end
end
context "view" do
it "existing 一覧" do
expect(page).to have_selector "li", text: "一覧"
end
end
context "guest_log_in" do
it "existing ゲストログイン" do
expect(page).to have_selector "li", text: "ゲストログイン(閲覧用)"
end
end
context "post" do
it "existing 投稿する" do
expect(page).to have_selector "li", text: "投稿する"
end
end
context "terms_of_use" do
it "existing 利用規約" do
expect(page).to have_content "利用規約"
end
end
context "privacy_policy" do
it "existing プライバシーポリシー" do
expect(page).to have_content "プライバシーポリシー"
end
end
context "home" do
it "existing ホーム" do
expect(page).to have_selector "li", text: "ホーム"
end
end
context "log_out" do
it "not existing ログアウト" do
expect(page).to_not have_selector "li", text: "ログアウト"
end
end
context "my_page" do
it "not existing マイページ" do
expect(page).to_not have_selector "li", text: "マイページ"
end
end
context "my_posts" do
it "not existing マイ投稿" do
expect(page).to_not have_selector "li", text: "マイ投稿"
end
end
context "user_edit" do
it "not existing ユーザー編集" do
expect(page).to_not have_selector "li", text: "ユーザー編集"
end
end
end
<file_sep>/spec/models/image_spec.rb
require "rails_helper"
RSpec.describe Image, type: :model do
describe "association" do
it "belongs_to post" do
expect(Image.reflect_on_association(:post).macro).to eq :belongs_to
end
end
end
<file_sep>/spec/system/homes_spec.rb
require "rails_helper"
RSpec.describe "Home", type: :system do
describe "when not logged in" do
before do
visit root_path
end
context "guest_log_in" do
it "guest login is available" do
click_link "ゲストログイン(閲覧用)"
expect(current_path).to eq root_path
expect(page).to have_content "ゲストユーザーとしてログインしました。"
end
end
context "log_in" do
it "login is available" do
click_link "ログイン"
expect(current_path).to eq new_user_session_path
end
end
context "sign_up" do
it "sign_up is available" do
click_link "サインアップ"
expect(current_path).to eq new_user_registration_path
end
end
context "search" do
it "search is available" do
click_on "navbarDropdown"
click_link "検索"
expect(current_path).to eq search_posts_path
end
end
context "lists" do
it "lists is available" do
click_on "navbarDropdown"
click_link "一覧"
expect(current_path).to eq posts_path
end
end
context "submit" do
it "submit is available" do
click_on "navbarDropdown"
click_link "投稿する"
expect(current_path).to eq new_post_path
end
end
context "home" do
it "home is available" do
click_on "navbarDropdown"
click_link "ホーム"
expect(current_path).to eq root_path
end
end
context "terms of use" do
it "Terms of Use is available" do
click_link "利用規約"
expect(page).to have_selector "h3", text: "利用規約"
end
end
context "privacy policy" do
it "privacy policy is available" do
click_link "プライバシーポリシー"
expect(page).to have_selector "h3", text: "プライバシーポリシー"
end
end
end
describe "when logged in" do
before do
visit root_path
click_link "ゲストログイン(閲覧用)"
end
context "log_out" do
it "existing ログアウト" do
expect(page).to have_selector "li", text: "ログアウト"
end
end
context "my_page" do
it "existing マイページ" do
expect(page).to have_selector "li", text: "マイページ"
end
end
context "log_out" do
it "existing ログアウト" do
expect(page).to have_selector "li", text: "ログアウト"
end
end
context "my_posts" do
it "my_posts is available" do
click_on "navbarDropdown"
click_link "マイ投稿"
expect(page).to have_selector "h2", text: "My Posted Articles"
end
end
context "user_edit" do
it "user_edit is available" do
click_on "navbarDropdown"
click_link "ユーザー編集"
expect(current_path).to eq edit_user_registration_path
end
end
end
end
<file_sep>/spec/factories/posts.rb
FactoryBot.define do
factory :post do
title { "test" }
content { "hoge_review" }
association :user, factory: :hoge_user
association :genre
after(:create) do |post|
create_list(:like, 1, post: post, user: create(:user))
end
end
factory :post2, class: Post do
title { "hoge" }
content { "fuga_review" }
association :user, factory: :hoge_user
association :genre, factory: :genre2
end
factory :post3, class: Post do
title { "piyo" }
content { "test_review" }
association :user, factory: :other_user
association :genre, factory: :genre3
end
end
<file_sep>/app/controllers/relationships_controller.rb
class RelationshipsController < ApplicationController
before_action :authenticate_user!
before_action :set_user
def create
if Relationship.create(user_id: current_user.id, follow_id: @user.id)
respond_to do |format|
format.js { flash[:alert] = "ユーザーをフォローしました" }
end
end
end
def destroy
@relation = Relationship.find_by(user_id: current_user.id, follow_id: @user.id)
if @relation.destroy
respond_to do |format|
format.js { flash[:alert] = "ユーザーのフォローを解除しました" }
end
end
end
private
def set_user
@user = User.find(params[:user_id])
end
end
<file_sep>/spec/views/devises/resend_email_spec.rb
require "rails_helper"
RSpec.describe "resend_email_page" do
let!(:user) { create(:user) }
before do
visit user_confirmation_path
end
context "resend email" do
it "existing resend confirmation instructions" do
expect(page).to have_selector "h2", text: "認証メール再送"
end
end
context "email" do
it "existing email" do
expect(page).to have_content "メールアドレス"
end
end
context "resend button" do
it "existing resend button" do
expect(page).to have_button "認証メール再送"
end
end
context "log_in_link" do
it "existing log_inn_link" do
expect(page).to have_link "ログイン"
end
end
context "sign_up_link" do
it "existing sign_up_link" do
expect(page).to have_link "サインアップ"
end
end
context "password_link" do
it "existing Forgot your password?" do
expect(page).to have_link "パスワードを忘れた場合"
end
end
end
<file_sep>/spec/models/like_spec.rb
require "rails_helper"
RSpec.describe Genre, type: :model do
describe "association" do
it "belongs_to posts" do
expect(Like.reflect_on_association(:post).macro).to eq :belongs_to
end
it "belongs_to user" do
expect(Like.reflect_on_association(:user).macro).to eq :belongs_to
end
end
end
<file_sep>/spec/views/posts/new_post_spec.rb
require "rails_helper"
RSpec.describe "new_post_page" do
before do
visit root_path
click_link "ゲストログイン(閲覧用)"
visit new_post_path
end
context "store name" do
it "existing 店名" do
expect(page).to have_content "店名(必須)"
end
end
context "review" do
it "existing レビュー" do
expect(page).to have_content "レビュー"
end
end
context "image" do
it "existing 画像" do
expect(page).to have_content "画像"
end
end
context "genre" do
it "existing 価格帯" do
expect(page).to have_content "価格帯(必須)"
end
end
context "post button" do
it "existing 投稿" do
expect(page).to have_button "投稿"
end
end
end
<file_sep>/app/models/user.rb
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable, :confirmable
has_many :posts, dependent: :destroy
has_many :likes, dependent: :destroy
has_many :liked_posts, through: :likes, source: :post
has_many :relationships, foreign_key: "user_id", dependent: :destroy
has_many :followings, through: :relationships, source: :follow
has_many :reverse_of_relationships, class_name: "Relationship", foreign_key: "follow_id", dependent: :destroy
has_many :followers, through: :reverse_of_relationships, source: :user
validates :username, presence: true
validates_acceptance_of :agreement, allow_nil: false, on: :create
def already_liked?(like, current_user_id)
like.pluck(:user_id).include?(current_user_id)
end
def self.guest
User.find_or_create_by!(email: "<EMAIL>") do |user|
user.password = <PASSWORD>
user.username = "ゲスト"
user.agreement = true
user.confirmed_at = Time.now
end
end
end
<file_sep>/app/models/post.rb
class Post < ApplicationRecord
belongs_to :user
belongs_to :genre
has_many :likes, dependent: :destroy
has_many :liked_users, through: :likes, source: :user
has_many :images, dependent: :destroy
accepts_nested_attributes_for :images
validates :user_id, presence: true
validates :title, presence: true, length: { maximum: 40 }
def self.search(search, genre)
if search.blank? && genre.blank?
Post.preload(:user, :images, :likes)
elsif search.blank?
Post.preload(:user, :images, :likes).where(genre_id: genre)
else
Post.preload(:user, :images, :likes).where(["title LIKE ? or content LIKE ? ", "%#{search}%", "%#{search}%"]).or(Post.where(genre_id: genre))
end
end
end
<file_sep>/spec/models/post_spec.rb
require "rails_helper"
RSpec.describe Post, type: :model do
let(:user) { create(:user) }
context "store names, reviews, and genres are entered" do
let(:post) { build(:post, user_id: user.id) }
it "can register" do
expect(post).to be_valid
end
end
context "can register without a review" do
let(:post) { build(:post, user_id: user.id, content: "") }
it "can register" do
expect(post).to be_valid
end
end
context "no user information" do
let(:post) { build(:post, user_id: "") }
it "can not register" do
expect(post).to_not be_valid
end
end
context "store name not entered" do
let(:post) { build(:post, user_id: user.id, title: "") }
it "can not register" do
expect(post).to_not be_valid
end
end
context "genre not entered" do
let(:post) { build(:post, user_id: user.id, genre_id: "") }
it "can not register" do
expect(post).to_not be_valid
end
end
context "belongs_to" do
it "belongs_to user" do
expect(Post.reflect_on_association(:user).macro).to eq :belongs_to
end
end
context "belongs_to" do
it "belongs_to genre" do
expect(Post.reflect_on_association(:genre).macro).to eq :belongs_to
end
end
context "has_many" do
it "has_many likes" do
expect(Post.reflect_on_association(:likes).macro).to eq :has_many
end
end
context "has_many" do
it "has_many images" do
expect(Post.reflect_on_association(:images).macro).to eq :has_many
end
end
end
<file_sep>/spec/models/genre_spec.rb
require "rails_helper"
RSpec.describe Genre, type: :model do
describe "association" do
it "has_many posts" do
expect(Genre.reflect_on_association(:posts).macro).to eq :has_many
end
end
end
<file_sep>/spec/factories/users.rb
FactoryBot.define do
factory :user do
username { "hoge" }
sequence(:email) { |n| "<EMAIL>" }
profile { "test" }
password { "<PASSWORD>" }
password_confirmation { "<PASSWORD>" }
agreement { true }
end
factory :other_user, class: "User" do
username { "hoge2" }
sequence(:email) { |n| "<EMAIL>" }
password { "<PASSWORD>" }
password_confirmation { "<PASSWORD>" }
agreement { true }
end
factory :hoge_user, class: "User" do
username { "hoge3" }
sequence(:email) { |n| "<EMAIL>" }
profile { "test" }
password { "<PASSWORD>" }
password_confirmation { "<PASSWORD>" }
agreement { true }
confirmed_at { Time.now }
after(:create) do |user|
create_list(:relationship, 1, user: create(:user), follow: user)
end
after(:create) do |user|
create_list(:relationship, 1, user: user, follow: create(:user))
end
end
end
<file_sep>/README.md
# Food-TakeOut-Map
テイクアウトに対応しているお店や、テイクアウト独自の商品情報を共有する飲食のテイクアウト専門サービスです。
<br>
<img src= "https://i.gyazo.com/aff95a87b3a93bbe8b31503cc88cc7cd.jpg" width= "320">
<br>
<br>
* 遅くなってしまったお仕事の帰りに晩ご飯をテイクアウトで頼みたい時や、のんびり持ち帰って自宅で食べたい時などにお店の情報を参照して参考にできます。
* 実際に頼んだ商品の情報を投稿することで他者と共有でき、おすすめのお店の商品を広めていくことができます。
<br>
### サービスの制作背景
新型コロナウイルスの影響で多くの飲食店は営業時間を縮小して営業していたり、店内での飲食可能時間を限定的にしてテイクアウトのみでの体制に変更してお店を稼働させている状況が続いております。<br>
お店側としてはコロナウイルスによる影響前の営業時間や体制で営業することが難しくなっており、心理的にも経済的にも負担が続いております。また利用者側としても従来のように好きな時間に来店し飲食をすることができなくなっており、注文できる商品もテイクアウトのみという制限下で限定されている状況です。このような状況下で双方の負担を軽減できるサービスはないかと思案し、お店の商品情報を共有できるサービスにたどり着きました。<br>
純粋な飲食店情報であれば既に大手のサービスが展開されておりますが、コロナウイルス情勢下でのテイクアウトによる体制が反映されているものはなく、また店舗情報までの記載がメインであり個別での商品情報が載っているものはありませんでした。<br>
テイクアウトに対応しているお店の情報と実際の商品情報、この2点に着目してサービスを作ることでお店側としてはテイクアウト限定であっても利用者に商品情報を認識してもらえ、利用者側としてはお店の情報を共有できることで縮小体制に困惑することなく、テイクアウトでの利用が円滑に進み、先に挙げました双方の負担の解消を狙えると思いこのサービスを制作致しました。
<br>
<br>
## App URL
https://www.food-takeout-map.work
<br>
<br>
## 基本的な利用方法の流れ
ログイン後ヘッダータブから「投稿する」ボタンを押し、投稿画面から投稿
<br>
<img src= "https://i.gyazo.com/274fb4e2bd8e506e2ff7e09bc69adf52.png" width= "320">
<br>
<br>
投稿一覧から各投稿内容を確認でき店舗情報の確認
<br>
<img src= "https://i.gyazo.com/7e3e2019032cf41d16b55be026509e85.png" width= "320">
<br>
<br>
## 制作にあたり意識した点
<br>
### 技術面
* DBでのN+1問題について余分なSQLが発行されないようにgemのbulletを使用し意識しました
* RuboCopを用い規約に沿ったコードになるよう可読性に努めました
* サービスの品質を維持し向上させるためテストコードを大事に行いました(184examples)
<br>
### 開発面
* 実際の現場でのチーム開発を意識しissueの発行からプルリクまでの流れを想定し開発しました
* ユーザーの利便性を図るため各種画面遷移の連結を意識しました
<br>
<br>
## 機能一覧
* ユーザー認証機能(サインアップ、サインイン、サインアウト)
* メールアドレス認証機能
* パスワード再設定機能
* ユーザー編集機能
* ゲストログイン機能
* 管理者機能
* 店舗情報投稿機能
* 投稿一覧機能
* 投稿検索機能
* マイ投稿表示機能
* マイページ詳細機能
* 投稿詳細表示機能
* いいね機能(非同期)
* ユーザーフォロー機能(非同期)
<br>
## 使用技術
<br>
バックエンド
* Ruby 3.0.1
* Rails 6.1.3.2
<br>
フロンドエンド
* HTML
* CSS
* jQuery
* Bootstrap
<br>
インフラ
* MYSQL 8.0.26
* Nginx
* Puma
* AWS
* VPC
* EC2
* RDS
* ELB
* Route53
* S3
* ACM
<br>
テスト
* RSpec
<br>
## 画面遷移フロー
<img src= "https://i.gyazo.com/e7038ef83bb49abfb5ea009866b4cbad.png" width= "320">
<br>
<br>
<br>
## ER図
<img src= "https://i.gyazo.com/aa5e27bccc2f9ce92ee921e366fd940a.png" width= "320">
<br>
<br>
<br>
## インフラ構成図
<img src= "https://i.gyazo.com/b0b4b8c2debb80aa1c6f03d9a22dc99f.jpg" width= "320"><file_sep>/app/javascript/packs/users/sign_up_render.js
history.replaceState('', '', 'users/sign_up')<file_sep>/app/controllers/admin/users_controller.rb
class Admin::UsersController < ApplicationController
def index
@users = User.includes(:posts).order("created_at DESC").page(params[:page]).per(15)
end
def destroy
if user_logged_in? && current_user.admin?
@user = User.find(params[:user_id])
@user.destroy
redirect_to root_path
flash[:notice] = "アカウントを削除しました"
end
end
end
<file_sep>/db/seeds.rb
# User.all.each do |user|
# user.posts.create! ([
# {
# title: 'テストタイトル',
# content: 'テストコンテンツ'
# }
# ])
# end
# 30.times do |n|
# Post.create! (
# {
# title:"テスト#{n+1}回目",
# content: "テスト#{n+1}回目の投稿",
# user_id: rand(1..7),
# genre_id: rand(1..2)
# }
# )
# end
# 5.times do |n|
# User.create! ([
# username: "テスト#{n+1}",
# email: "<EMAIL>",
# password: "<PASSWORD>",
# confirmed_at: Time.current
# ])
# end
# User.create!(username: "管理者",
# email: "<EMAIL>",
# password: "<PASSWORD>",
# password_confirmation: "<PASSWORD>",
# confirmed_at: Time.current,
# agreement: true,
# admin: true)
<file_sep>/spec/views/posts/search_spec.rb
require "rails_helper"
RSpec.describe "search_page" do
before do
visit search_posts_path
end
context "search term" do
it "existing 検索ワード" do
expect(page).to have_content "検索ワード"
end
end
context "price range" do
it "existing 価格帯" do
expect(page).to have_content "価格帯"
end
end
end
<file_sep>/app/models/genre.rb
class Genre < ApplicationRecord
validates :genre, presence: true
has_many :posts, dependent: :destroy
end
<file_sep>/Dockerfile
# https://hub.docker.com/_/ruby
FROM ruby:3.0.1-alpine
RUN apk update && apk add --no-cache --update build-base tzdata bash yarn python2 imagemagick graphviz mysql-dev mysql-client
WORKDIR /food-takeout-map
ENV LANG="ja_JP.UTF-8"
COPY Gemfile Gemfile.lock ./
RUN bundle install --no-cache
COPY package.json yarn.lock ./
RUN yarn install && yarn cache clean
COPY entrypoint.sh /usr/bin/
RUN chmod +x /usr/bin/entrypoint.sh
ENTRYPOINT ["entrypoint.sh"]
EXPOSE 3000
CMD ["rails", "server", "-b", "0.0.0.0"]
<file_sep>/app/controllers/users_controller.rb
class UsersController < ApplicationController
def show
@user = User.find(params[:id])
@posts = Post.includes(:images, :likes, :liked_users).where(user_id: @user.id).page(params[:page])
# @post = Post.find_by(user_id: params[:id])
end
end
<file_sep>/spec/system/new_post_spec.rb
require "rails_helper"
RSpec.describe "New_post_page", type: :system do
describe "submission process" do
let!(:genre) { create(:genre) }
before do
visit root_path
click_link "ゲストログイン(閲覧用)"
visit new_post_path
end
context "for normal input" do
it "successful submission" do
fill_in "new-store-name", with: "test"
fill_in "new-review", with: "test"
attach_file "new-post-image", "app/assets/images/4036048_m.jpg"
select "~1500円", from: "価格帯(必須)"
click_on "投稿"
expect(page).to have_content "投稿が完了しました"
end
end
context "store name not into the force" do
it "submission fails" do
fill_in "new-store-name", with: ""
fill_in "new-review", with: "test"
select "~1500円", from: "価格帯(必須)"
click_on "投稿"
expect(page).to have_content "投稿に失敗しました"
end
end
context "review not into the force" do
it "successful submission" do
fill_in "new-store-name", with: "test"
fill_in "new-review", with: ""
select "~1500円", from: "価格帯(必須)"
click_on "投稿"
expect(page).to have_content "投稿が完了しました"
end
end
context "posting an image" do
it "processed normally" do
fill_in "new-store-name", with: "test"
fill_in "new-review", with: "test"
select "~1500円", from: "価格帯(必須)"
attach_file "new-post-image", "app/assets/images/4036048_m.jpg"
click_on "投稿"
expect(page).to have_content "投稿が完了しました"
visit posts_path
expect(page).to have_selector("img[src$='4036048_m.jpg']")
end
end
context "genre not into the force" do
it "submission fails" do
fill_in "new-store-name", with: "test"
fill_in "new-review", with: "test"
click_on "投稿"
expect(page).to have_content "投稿に失敗しました"
end
end
end
end
<file_sep>/config/routes.rb
Rails.application.routes.draw do
devise_for :users, controllers: {
registrations: "users/registrations",
sessions: "users/sessions",
passwords: "<PASSWORD>"
}
devise_scope :user do
post "users/guest_sign_in", to: "users/sessions#guest_sign_in"
end
resources :users, only: [:show] do
namespace :admin do
resources :users, only: [:destroy, :index]
end
resource :relationship, only: [:create, :destroy]
resources :followings, only: [:index]
resources :followers, only: [:index]
end
root to: "homes#index"
resources :posts, only: [:new, :create, :destroy, :show, :index] do
resource :like, only: [:create, :destroy]
collection do
get "search"
end
member do
get "my_post"
end
resources :genres, only: [:new, :create, :index]
end
end
<file_sep>/spec/views/devises/sign_up_spec.rb
require "rails_helper"
RSpec.describe "sign_up_page" do
before do
visit new_user_registration_path
end
context "sign_up" do
it "existing SIGN UP" do
expect(page).to have_selector "h2", text: "サインアップ"
end
end
context "user_name" do
it "existing Username" do
expect(page).to have_content "ユーザーネーム"
end
end
context "email" do
it "existing Email" do
expect(page).to have_content "メールアドレス"
end
end
context "password" do
it "existing Password" do
expect(page).to have_content "パスワード (6文字以上)"
end
end
context "password confirmation" do
it "existing Password confirmation" do
expect(page).to have_content "確認用パスワード"
end
end
context "check_box" do
it "existing check_box" do
expect(page).to have_field ("")
end
end
context "agree with the text" do
it "existing agree with the text" do
expect(page).to have_content "利用規約と プライバシーポリシーに同意する"
end
end
context "sign_up_button" do
it "existing Sign_up button" do
expect(page).to have_button "サインアップ"
end
end
context "log_in" do
it "existing log_in link" do
expect(page).to have_link "ログイン"
end
end
context "authentication email" do
it "existing 認証メールが届かない場合" do
expect(page).to have_link "認証メールが届かない場合"
end
end
end
<file_sep>/spec/system/search_spec.rb
require "rails_helper"
RSpec.describe "Search", type: :system do
let!(:post) { create(:post) }
let!(:post2) { create(:post2) }
describe "When not logged in" do
before do
visit search_posts_path
end
context "if no input" do
it "view all posts" do
click_on "検索"
expect(page).to have_content "検索条件が指定されていません、全投稿を表示します。"
expect(page).to have_content "店名: test"
expect(page).to have_content "レビュー: hoge_review"
date = DateTime.now
expect(page).to have_content "投稿日: #{date.strftime("%Y年 %m月 %d日 %H時 %M分")}"
expect(page).to have_content "投稿者: hoge"
expect(page).to have_content "いいね件数: 1"
expect(page).to have_content "店名: hoge"
expect(page).to have_content "レビュー: fuga_review"
end
end
context "to search by store name" do
it "search and display by store name" do
fill_in "search-words", with: "test"
click_on "検索"
expect(page).to have_content "店名: test"
expect(page).to have_content "レビュー: hoge_review"
end
end
context "to search by review" do
it "search and display by review" do
fill_in "search-words", with: "fuga_review"
click_on "検索"
expect(page).to have_content "店名: hoge"
expect(page).to have_content "レビュー: fuga_review"
end
end
context "to search by store name and reviews" do
it "show the matches for each condition" do
fill_in "search-words", with: "hoge"
click_on "検索"
expect(page).to have_content "店名: test"
expect(page).to have_content "レビュー: hoge_review"
expect(page).to have_content "店名: hoge"
expect(page).to have_content "レビュー: fuga_review"
end
end
context "to search by price range" do
it "show less than 1500 yen" do
select "~1500円", from: "genre-select"
click_on "検索"
expect(page).to have_content "店名: test"
expect(page).to have_content "レビュー: hoge_review"
end
end
context "to search by price range" do
it "show more than 1500 yen" do
select "1500円~", from: "genre-select"
click_on "検索"
expect(page).to have_content "店名: hoge"
expect(page).to have_content "レビュー: fuga_review"
end
end
context "to search by search term and price range" do
it "show the matches for each condition" do
fill_in "search-words", with: "test"
select "1500円~", from: "genre-select"
click_on "検索"
expect(page).to have_content "店名: test"
expect(page).to have_content "レビュー: hoge_review"
expect(page).to have_content "店名: hoge"
expect(page).to have_content "レビュー: fuga_review"
end
end
context "like function" do
it "works fine" do
click_on "検索"
expect(page).to have_content "いいね件数: 1"
expect(page).to have_content "いいね件数: 0"
end
end
context "link to contributors" do
it "works fine" do
fill_in "search-words", with: "test"
click_on "検索"
expect(page).to have_link "hoge"
click_link "hoge"
expect(page).to have_content "ユーザー詳細"
end
end
end
describe "When logged in" do
before do
visit root_path
click_on "ゲストログイン(閲覧用)"
visit search_posts_path
end
context "like button" do
it "view all posts" do
fill_in "search-words", with: "test"
click_on "検索"
find(".like-button").click
expect(page).to have_content "いいね件数: 2"
find(".like-button").click
expect(page).to have_content "いいね件数: 1"
end
end
end
end
<file_sep>/spec/views/devises/my_page_spec.rb
require "rails_helper"
RSpec.describe "my_page" do
let(:user) { create(:user, email: "<EMAIL>") }
before do
user.confirm
visit new_user_session_path
fill_in "メールアドレス", with: "<EMAIL>"
fill_in "パスワード", with: "<PASSWORD>"
click_button "ログイン"
click_on "ユーザー編集"
end
context "edit_user" do
it "existing edit user" do
expect(page).to have_selector "h2", text: "ユーザー編集"
end
end
context "user_name" do
it "existing Username" do
expect(page).to have_content "ユーザーネーム"
end
end
context "email" do
it "existing Email" do
expect(page).to have_content "メールアドレス"
end
end
context "password" do
it "existing Password" do
expect(page).to have_content "パスワード (変更希望がなければ空欄でも可能です)"
end
end
context "password confirmation" do
it "existing Password confirmation" do
expect(page).to have_content "確認用パスワード"
end
end
context "current password" do
it "existing current Password" do
expect(page).to have_content "現在のパスワード (変更を反映するには必要です)"
end
end
context "profile" do
it "existing profile" do
expect(page).to have_content "プロフィール"
end
end
context "sign_up_button" do
it "existing update button" do
expect(page).to have_button "更新"
end
end
context "cancel_account" do
it "existing cancel account" do
expect(page).to have_selector "h3", text: "アカウント削除"
end
end
context "cancel_account_button" do
it "existing cancel button" do
expect(page).to have_button "アカウント削除"
end
end
end
<file_sep>/spec/views/devises/reset_password_spec.rb
require "rails_helper"
RSpec.describe "reset_password_page" do
before do
visit new_user_password_path
end
context "reset_password" do
it "existing forgot your password?" do
expect(page).to have_selector "h2", text: "パスワードを忘れた場合"
end
end
context "email" do
it "existing email" do
expect(page).to have_content "メールアドレス"
end
end
context "send_button" do
it "existing send_button" do
expect(page).to have_button "パスワードリセットメールを送信"
end
end
context "log_in_link" do
it "existing log_inn_link" do
expect(page).to have_link "ログイン"
end
end
context "sign_up_link" do
it "existing sign_up_link" do
expect(page).to have_link "サインアップ"
end
end
context "Authentication email" do
it "existing 認証メールが届かない場合" do
expect(page).to have_link "認証メールが届かない場合"
end
end
end
<file_sep>/spec/system/posts_list_spec.rb
require "rails_helper"
RSpec.describe "Search", type: :system do
let!(:post) { create(:post) }
describe "when not logged in" do
before do
visit posts_path
end
it "the like button is not displayed" do
expect(page).to_not have_button "like-button"
end
end
describe "when logged in" do
before do
visit root_path
click_on "ゲストログイン(閲覧用)"
visit posts_path
end
it "the like button is displayed" do
expect(page).to have_button "like-button"
end
end
end
<file_sep>/spec/factories/genres.rb
FactoryBot.define do
factory :genre do
id { 1 }
genre { "1500円以下" }
end
factory :genre2, class: "Genre" do
id { 2 }
genre { "1500円以上" }
end
factory :genre3, class: "Genre" do
id { 3 }
genre { "1500円以下" }
end
end
<file_sep>/app/controllers/posts_controller.rb
class PostsController < ApplicationController
before_action :authenticate_user!, except: [:index, :search]
before_action :set_post, only: [:destroy]
before_action :if_not_admin_or_current_in_user_posts, only: [:destroy]
def index
@posts = Post.preload(:user, :images, :likes).order("created_at DESC").page(params[:page]).per(15)
end
def new
@post = Post.new
@post.images.build
end
def create
@post = Post.new(post_params)
@post.user_id = current_user.id
if @post.save
if params[:image_files].present?
params[:image_files][:file].each do |a|
@image_file = @post.images.create!(image: a, post_id: @post.id)
end
end
flash[:notice] = "投稿が完了しました"
redirect_to root_path
else
flash.now[:alert] = "投稿に失敗しました"
@post.images.build
render :new
end
end
def destroy
@post.destroy
redirect_to my_post_post_path(current_user)
flash[:notice] = "投稿が削除されました"
end
def show
@post = Post.find(params[:id])
end
def search
@posts = Post.search(params[:search], params[:genre_id]).order("created_at DESC").page(params[:page]).per(10)
end
def my_post
@posts = Post.includes(:images, :likes, :liked_users).where(user_id: params[:id]).order("created_at DESC").page(params[:page]).per(10)
end
private
def post_params
params.require(:post).permit(:title, :content, :genre_id, images_attributes: [:image])
end
def set_post
@post = Post.find(params[:id])
end
def if_not_admin_or_current_in_user_posts
unless current_user.admin? || @post.user_id == current_user.id
flash[:notice] = "権限がありません"
redirect_to root_path
end
end
end
<file_sep>/spec/views/devises/log_in_spec.rb
require "rails_helper"
RSpec.describe "log_in_page" do
before do
visit new_user_session_path
end
context "log_in" do
it "existing LOG IN" do
expect(page).to have_selector "h2", text: "ログイン"
end
end
context "email" do
it "existing Email" do
expect(page).to have_content "メールアドレス"
end
end
context "password" do
it "existing Password" do
expect(page).to have_content "パスワード"
end
end
context "remember me" do
it "existing Remember me" do
expect(page).to have_content "次回から自動的にログイン"
end
end
context "check_box" do
it "existing check_box" do
expect(page).to have_field ("次回から自動的にログイン")
end
end
context "log_in_button" do
it "existing log_in_button" do
expect(page).to have_button "ログイン"
end
end
context "sign_up_link" do
it "existing sign_up_link" do
expect(page).to have_link "サインアップ"
end
end
context "password_link" do
it "existing Forgot your password?" do
expect(page).to have_link "パスワードを忘れた場合"
end
end
context "Authentication email" do
it "existing 認証メールが届かない場合" do
expect(page).to have_link "認証メールが届かない場合"
end
end
end
<file_sep>/spec/models/user_spec.rb
require "rails_helper"
RSpec.describe User, type: :model do
context "username,email,password,password confirmation enterd" do
let(:user) { build(:user) }
it "can register" do
expect(user).to be_valid
end
end
context "username is not enterd" do
let(:user) { build(:user, username: "") }
it "cannot register" do
expect(user).not_to be_valid
end
end
context "email is not entered" do
let(:user) { build(:user, email: "") }
it "cannot register" do
expect(user).not_to be_valid
end
end
context "Duplicate email" do
let(:user1) { create(:user, email: "<EMAIL>") }
let(:user2) { build(:user, email: "<EMAIL>") }
it "cannot register" do
user1
expect(user2).not_to be_valid
end
end
context "password is not entered" do
let(:user) { build(:user, password: "") }
it "cannot register" do
expect(user).not_to be_valid
end
end
context "password confirmation is not entered" do
let(:user) { build(:user, password_confirmation: "") }
it "cannot register" do
expect(user).not_to be_valid
end
end
context "password is less than 6 characters" do
let(:user) { build(:user, password_confirmation: "<PASSWORD>") }
it "cannot register" do
expect(user).not_to be_valid
end
end
context "if you do not agree" do
let(:user) { build(:user, agreement: false) }
it "cannot register" do
expect(user).not_to be_valid
end
end
context "has_many" do
it "has_many posts" do
expect(User.reflect_on_association(:posts).macro).to eq :has_many
end
end
context "has_many" do
it "has_many likes" do
expect(User.reflect_on_association(:likes).macro).to eq :has_many
end
end
context "has_many" do
it "has_many Relationships" do
expect(User.reflect_on_association(:relationships).macro).to eq :has_many
end
end
end
|
e9e761a1a19712745d81253ebd272fb34fecdd64
|
[
"Markdown",
"JavaScript",
"Ruby",
"Dockerfile"
] | 39
|
Ruby
|
torisuta1/food-takeout-map
|
8579febebe0398600e254408b07696cc3182e734
|
dafe350ee9838389b4bc254735cdf0aa51f56b37
|
refs/heads/master
|
<repo_name>polinadotio/windows8appsample<file_sep>/windows8appsample/CareLink/GroupedItemsPage.xaml.cs
using CareLink.Data;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Grouped Items Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234231
namespace CareLink
{
/// <summary>
/// A page that displays a grouped collection of items.
/// </summary>
/// <common:LayoutAwarePage
/*
<Page.Resources>
<!-- TODO: Delete this line if the key AppName is declared in App.xaml -->
<x:String x:Key="AppName">Hello, world!</x:String>
</Page.Resources>
<!--
This grid acts as a root panel for the page that defines two rows:
* Row 0 contains the back button and page title
* Row 1 contains the rest of the page layout
-->
<Grid Style="{StaticResource LayoutRootStyle}">
<Grid.RowDefinitions>
<RowDefinition Height="140"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<!-- Back button and page title -->
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Button x:Name="backButton" Click="GoBack"
IsEnabled="{Binding Frame.CanGoBack, ElementName=pageRoot}"
Style="{StaticResource BackButtonStyle}"/>
<TextBlock x:Name="pageTitle" Grid.Column="1"
Text="{StaticResource AppName}"
Style="{StaticResource PageHeaderTextStyle}"/>
</Grid>
<!-- Controls added in PART 1. -->
<StackPanel Grid.Row="1" Margin="120,30,0,0">
<TextBlock Text="What's your name?" Style="{StaticResource BasicTextStyle}"/>
<StackPanel Orientation="Horizontal" Margin="0,20,0,20">
<TextBox x:Name="nameInput" Width="300" HorizontalAlignment="Left"/>
<Button Content="Say "Hello"" Click="Button_Click"/>
</StackPanel>
<TextBlock x:Name="greetingOutput" Style="{StaticResource BigGreenTextStyle}"/>
</StackPanel>
<!-- End -->
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="ApplicationViewStates">
<VisualState x:Name="FullScreenLandscape"/>
<VisualState x:Name="Filled"/>
<!-- The entire page respects the narrower 100-pixel margin convention for portrait -->
<VisualState x:Name="FullScreenPortrait">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="backButton"
Storyboard.TargetProperty="Style">
<DiscreteObjectKeyFrame KeyTime="0"
Value="{StaticResource PortraitBackButtonStyle}"/>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
<!-- The back button and title have different styles when snapped -->
<VisualState x:Name="Snapped">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="backButton"
Storyboard.TargetProperty="Style">
<DiscreteObjectKeyFrame KeyTime="0"
Value="{StaticResource SnappedBackButtonStyle}"/>
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="pageTitle"
Storyboard.TargetProperty="Style">
<DiscreteObjectKeyFrame KeyTime="0"
Value="{StaticResource SnappedPageHeaderTextStyle}"/>
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
</Grid>
</common:LayoutAwarePage>
*/
public sealed partial class GroupedItemsPage : CareLink.Common.LayoutAwarePage
{
public GroupedItemsPage()
{
this.InitializeComponent();
}
/// <summary>
/// Populates the page with content passed during navigation. Any saved state is also
/// provided when recreating a page from a prior session.
/// </summary>
/// <param name="navigationParameter">The parameter value passed to
/// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
/// </param>
/// <param name="pageState">A dictionary of state preserved by this page during an earlier
/// session. This will be null the first time a page is visited.</param>
protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
{
// TODO: Create an appropriate data model for your problem domain to replace the sample data
var sampleDataGroups = SampleDataSource.GetGroups((String)navigationParameter);
this.DefaultViewModel["Groups"] = sampleDataGroups;
}
/// <summary>
/// Invoked when a group header is clicked.
/// </summary>
/// <param name="sender">The Button used as a group header for the selected group.</param>
/// <param name="e">Event data that describes how the click was initiated.</param>
void Header_Click(object sender, RoutedEventArgs e)
{
// Determine what group the Button instance represents
var group = (sender as FrameworkElement).DataContext;
// Navigate to the appropriate destination page, configuring the new page
// by passing required information as a navigation parameter
this.Frame.Navigate(typeof(GroupDetailPage), ((SampleDataGroup)group).UniqueId);
}
/// <summary>
/// Invoked when an item within a group is clicked.
/// </summary>
/// <param name="sender">The GridView (or ListView when the application is snapped)
/// displaying the item clicked.</param>
/// <param name="e">Event data that describes the item clicked.</param>
void ItemView_ItemClick(object sender, ItemClickEventArgs e)
{
// Navigate to the appropriate destination page, configuring the new page
// by passing required information as a navigation parameter
var itemId = ((SampleDataItem)e.ClickedItem).UniqueId;
this.Frame.Navigate(typeof(ItemDetailPage), itemId);
}
private void itemGridView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
}
}
}
<file_sep>/windows8appsample/CareLink/DataModel/SampleDataSource.cs
using System;
using System.Linq;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using Windows.ApplicationModel.Resources.Core;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;
using System.Collections.Specialized;
// The data model defined by this file serves as a representative example of a strongly-typed
// model that supports notification when members are added, removed, or modified. The property
// names chosen coincide with data bindings in the standard item templates.
//
// Applications may use this model as a starting point and build on it, or discard it entirely and
// replace it with something appropriate to their needs.
namespace CareLink.Data
{
/// <summary>
/// Base class for <see cref="SampleDataItem"/> and <see cref="SampleDataGroup"/> that
/// defines properties common to both.
/// </summary>
[Windows.Foundation.Metadata.WebHostHidden]
public abstract class SampleDataCommon : CareLink.Common.BindableBase
{
private static Uri _baseUri = new Uri("ms-appx:///");
public SampleDataCommon(String uniqueId, String title, String subtitle, String imagePath, String description)
{
this._uniqueId = uniqueId;
this._title = title;
this._subtitle = subtitle;
this._description = description;
this._imagePath = imagePath;
}
private string _uniqueId = string.Empty;
public string UniqueId
{
get { return this._uniqueId; }
set { this.SetProperty(ref this._uniqueId, value); }
}
private string _title = string.Empty;
public string Title
{
get { return this._title; }
set { this.SetProperty(ref this._title, value); }
}
private string _subtitle = string.Empty;
public string Subtitle
{
get { return this._subtitle; }
set { this.SetProperty(ref this._subtitle, value); }
}
private string _description = string.Empty;
public string Description
{
get { return this._description; }
set { this.SetProperty(ref this._description, value); }
}
private ImageSource _image = null;
private String _imagePath = null;
public ImageSource Image
{
get
{
if (this._image == null && this._imagePath != null)
{
this._image = new BitmapImage(new Uri(SampleDataCommon._baseUri, this._imagePath));
}
return this._image;
}
set
{
this._imagePath = null;
this.SetProperty(ref this._image, value);
}
}
public void SetImage(String path)
{
this._image = null;
this._imagePath = path;
this.OnPropertyChanged("Image");
}
public override string ToString()
{
return this.Title;
}
}
/// <summary>
/// Generic item data model.
/// </summary>
public class SampleDataItem : SampleDataCommon
{
public SampleDataItem(String uniqueId, String title, String subtitle, String imagePath, String description, String content, SampleDataGroup group)
: base(uniqueId, title, subtitle, imagePath, description)
{
this._content = content;
this._group = group;
}
private string _content = string.Empty;
public string Content
{
get { return this._content; }
set { this.SetProperty(ref this._content, value); }
}
private SampleDataGroup _group;
public SampleDataGroup Group
{
get { return this._group; }
set { this.SetProperty(ref this._group, value); }
}
}
/// <summary>
/// Generic group data model.
/// </summary>
public class SampleDataGroup : SampleDataCommon
{
public SampleDataGroup(String uniqueId, String title, String subtitle, String imagePath, String description)
: base(uniqueId, title, subtitle, imagePath, description)
{
Items.CollectionChanged += ItemsCollectionChanged;
}
private void ItemsCollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
// Provides a subset of the full items collection to bind to from a GroupedItemsPage
// for two reasons: GridView will not virtualize large items collections, and it
// improves the user experience when browsing through groups with large numbers of
// items.
//
// A maximum of 12 items are displayed because it results in filled grid columns
// whether there are 1, 2, 3, 4, or 6 rows displayed
switch (e.Action)
{
case NotifyCollectionChangedAction.Add:
if (e.NewStartingIndex < 12)
{
TopItems.Insert(e.NewStartingIndex,Items[e.NewStartingIndex]);
if (TopItems.Count > 12)
{
TopItems.RemoveAt(12);
}
}
break;
case NotifyCollectionChangedAction.Move:
if (e.OldStartingIndex < 12 && e.NewStartingIndex < 12)
{
TopItems.Move(e.OldStartingIndex, e.NewStartingIndex);
}
else if (e.OldStartingIndex < 12)
{
TopItems.RemoveAt(e.OldStartingIndex);
TopItems.Add(Items[11]);
}
else if (e.NewStartingIndex < 12)
{
TopItems.Insert(e.NewStartingIndex, Items[e.NewStartingIndex]);
TopItems.RemoveAt(12);
}
break;
case NotifyCollectionChangedAction.Remove:
if (e.OldStartingIndex < 12)
{
TopItems.RemoveAt(e.OldStartingIndex);
if (Items.Count >= 12)
{
TopItems.Add(Items[11]);
}
}
break;
case NotifyCollectionChangedAction.Replace:
if (e.OldStartingIndex < 12)
{
TopItems[e.OldStartingIndex] = Items[e.OldStartingIndex];
}
break;
case NotifyCollectionChangedAction.Reset:
TopItems.Clear();
while (TopItems.Count < Items.Count && TopItems.Count < 12)
{
TopItems.Add(Items[TopItems.Count]);
}
break;
}
}
private ObservableCollection<SampleDataItem> _items = new ObservableCollection<SampleDataItem>();
public ObservableCollection<SampleDataItem> Items
{
get { return this._items; }
}
private ObservableCollection<SampleDataItem> _topItem = new ObservableCollection<SampleDataItem>();
public ObservableCollection<SampleDataItem> TopItems
{
get {return this._topItem; }
}
}
/// <summary>
/// Creates a collection of groups and items with hard-coded content.
///
/// SampleDataSource initializes with placeholder data rather than live production
/// data so that sample data is provided at both design-time and run-time.
/// </summary>
public sealed class SampleDataSource
{
private static SampleDataSource _sampleDataSource = new SampleDataSource();
private ObservableCollection<SampleDataGroup> _allGroups = new ObservableCollection<SampleDataGroup>();
public ObservableCollection<SampleDataGroup> AllGroups
{
get { return this._allGroups; }
}
public static IEnumerable<SampleDataGroup> GetGroups(string uniqueId)
{
if (!uniqueId.Equals("AllGroups")) throw new ArgumentException("Only 'AllGroups' is supported as a collection of groups");
return _sampleDataSource.AllGroups;
}
public static SampleDataGroup GetGroup(string uniqueId)
{
// Simple linear search is acceptable for small data sets
var matches = _sampleDataSource.AllGroups.Where((group) => group.UniqueId.Equals(uniqueId));
if (matches.Count() == 1) return matches.First();
return null;
}
public static SampleDataItem GetItem(string uniqueId)
{
// Simple linear search is acceptable for small data sets
var matches = _sampleDataSource.AllGroups.SelectMany(group => group.Items).Where((item) => item.UniqueId.Equals(uniqueId));
if (matches.Count() == 1) return matches.First();
return null;
}
public SampleDataSource()
{
String ITEM_CONTENT = String.Format("Age : 12 years" + "\n" + "\n" + "Weight : 74.3 pounds" + "\n" + "\n" + "Sex : M" + "\n" + "\n" + "Medical Number : " + "\n" + "1234567" + "\n" + "\n" + "Location : " + "\n" + "Dodoma, Tanzania" + "\n" + "\n" + "Last Updated : " + "\n" + "2/23/2013 12:43:56 ",
"");
var group1 = new SampleDataGroup("Group-1",
"List of Patients",
"",
"Assets/Resized-8MBZ6.jpg",
"This is a list of all the patients in the directory");
group1.Items.Add(new SampleDataItem("Group-1-PATIENT 1",
"<NAME>",
"",
"Assets/p1.png",
"Incision and Drainage",
ITEM_CONTENT,
group1));
group1.Items.Add(new SampleDataItem("Group-1-PATIENT 2",
"<NAME>",
"",
"Assets/p2.png",
"Central Venous Pressure Monitoring",
ITEM_CONTENT,
group1));
group1.Items.Add(new SampleDataItem("Group-1-PATIENT 3",
"<NAME>",
"",
"Assets/p3.png",
"Tracheostomy",
ITEM_CONTENT,
group1));
group1.Items.Add(new SampleDataItem("Group-1-PATIENT 4",
"<NAME>",
"",
"Assets/p4.png",
"Thoracentesis",
ITEM_CONTENT,
group1));
group1.Items.Add(new SampleDataItem("Group-1-PATIENT 5",
"<NAME>",
"",
"Assets/p5.png",
"Pericardiocentesis",
ITEM_CONTENT,
group1));
group1.Items.Add(new SampleDataItem("Group-1-PATIENT 6",
"<NAME>",
"",
"Assets/p6.png",
"Pericardiocentesis",
ITEM_CONTENT,
group1));
group1.Items.Add(new SampleDataItem("Group-1-PATIENT 7",
"<NAME>",
"",
"Assets/p7.png",
"Paracentesis abdominis",
ITEM_CONTENT,
group1));
group1.Items.Add(new SampleDataItem("Group-1-PATIENT 8",
"<NAME>",
"",
"Assets/p8.png",
"Incision and Drainage",
ITEM_CONTENT,
group1));
group1.Items.Add(new SampleDataItem("Group-1-PATIENT 9",
"<NAME>",
"",
"Assets/p9.png",
"Central Venous Pressure Monitoring",
ITEM_CONTENT,
group1));
group1.Items.Add(new SampleDataItem("Group-1-PATIENT 10",
"<NAME>",
"",
"Assets/p10.png",
"ACL reconstruction",
ITEM_CONTENT,
group1));
group1.Items.Add(new SampleDataItem("Group-1-wound",
"<NAME>",
"",
"Assets/p11.png",
"Shin replacement",
ITEM_CONTENT,
group1));
group1.Items.Add(new SampleDataItem("Group-1-PATIENT 12",
"<NAME>",
"",
"Assets/p12.png",
"Thoracentesis",
ITEM_CONTENT,
group1));
/*group1.Items.Add(new SampleDataItem("Group-1-PATIENT 13",
"PATIENT 13",
"",
"Assets/p13.png",
"Surgery 10",
ITEM_CONTENT,
group1));
group1.Items.Add(new SampleDataItem("Group-1-PATIENT 14",
"PATIENT 14",
"",
"Assets/p14.png",
"Surgery 10",
ITEM_CONTENT,
group1));
group1.Items.Add(new SampleDataItem("Group-1-PATIENT 15",
"PATIENT 15",
"",
"Assets/p15.png",
"Surgery 10",
ITEM_CONTENT,
group1));
group1.Items.Add(new SampleDataItem("Group-1-PATIENT 16",
"PATIENT 16",
"",
"Assets/p16.png",
"Surgery 10",
ITEM_CONTENT,
group1));
group1.Items.Add(new SampleDataItem("Group-1-PATIENT 17",
"PATIENT 17",
"",
"Assets/p17.png",
"Surgery 10",
ITEM_CONTENT,
group1));
group1.Items.Add(new SampleDataItem("Group-1-PATIENT 18",
"PATIENT 18",
"",
"Assets/p18.png",
"Surgery 10",
ITEM_CONTENT,
group1));
group1.Items.Add(new SampleDataItem("Group-1-PATIENT 19",
"PATIENT 19",
"",
"Assets/p19.png",
"Surgery 10",
ITEM_CONTENT,
group1));
group1.Items.Add(new SampleDataItem("Group-1-PATIENT 20",
"PATIENT 20",
"",
"Assets/p20.png",
"Surgery 10",
ITEM_CONTENT,
group1)); */
this.AllGroups.Add(group1);
var group2 = new SampleDataGroup("Group-2",
"Group Title: 2",
"Group Subtitle: 2",
"Assets/LightGray.png",
"Group Description: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus tempor scelerisque lorem in vehicula. Aliquam tincidunt, lacus ut sagittis tristique, turpis massa volutpat augue, eu rutrum ligula ante a ante");
group2.Items.Add(new SampleDataItem("Group-1-PATIENT 13",
"<NAME>",
"",
"Assets/p13.png",
"Tracheostomy",
ITEM_CONTENT,
group2));
group2.Items.Add(new SampleDataItem("Group-1-PATIENT 14",
"<NAME>",
"",
"Assets/p14.png",
"Appendectomy",
ITEM_CONTENT,
group2));
group2.Items.Add(new SampleDataItem("Group-1-PATIENT 15",
"<NAME>",
"",
"Assets/p15.png",
"Incision and Drainage",
ITEM_CONTENT,
group2));
group2.Items.Add(new SampleDataItem("Group-1-PATIENT 16",
"<NAME>",
"",
"Assets/p16.png",
"Skin graft",
ITEM_CONTENT,
group2));
group2.Items.Add(new SampleDataItem("Group-1-PATIENT 17",
"<NAME>",
"",
"Assets/p17.png",
"Pracentesis abdominis",
ITEM_CONTENT,
group2));
group2.Items.Add(new SampleDataItem("Group-1-PATIENT 18",
"<NAME>",
"",
"Assets/p18.png",
"Incision and Drainage",
ITEM_CONTENT,
group2));
group2.Items.Add(new SampleDataItem("Group-1-PATIENT 19",
"<NAME>",
"",
"Assets/p19.png",
"Thoracentesis",
ITEM_CONTENT,
group2));
group2.Items.Add(new SampleDataItem("Group-1-PATIENT 20",
"<NAME>",
"",
"Assets/p20.png",
"Tracheostomy",
ITEM_CONTENT,
group2));
this.AllGroups.Add(group2);
/*group2.Items.Add(new SampleDataItem("Group-2-Item-1",
"Item Title: 1",
"Item Subtitle: 1",
"Assets/DarkGray.png",
"Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
ITEM_CONTENT,
group2));
group2.Items.Add(new SampleDataItem("Group-2-Item-2",
"Item Title: 2",
"Item Subtitle: 2",
"Assets/MediumGray.png",
"Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
ITEM_CONTENT,
group2));
group2.Items.Add(new SampleDataItem("Group-2-Item-3",
"Item Title: 3",
"Item Subtitle: 3",
"Assets/LightGray.png",
"Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
ITEM_CONTENT,
group2));
this.AllGroups.Add(group2);
var group3 = new SampleDataGroup("Group-3",
"Group Title: 3",
"Group Subtitle: 3",
"Assets/MediumGray.png",
"Group Description: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus tempor scelerisque lorem in vehicula. Aliquam tincidunt, lacus ut sagittis tristique, turpis massa volutpat augue, eu rutrum ligula ante a ante");
group3.Items.Add(new SampleDataItem("Group-3-Item-1",
"Item Title: 1",
"Item Subtitle: 1",
"Assets/MediumGray.png",
"Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
ITEM_CONTENT,
group3));
group3.Items.Add(new SampleDataItem("Group-3-Item-2",
"Item Title: 2",
"Item Subtitle: 2",
"Assets/LightGray.png",
"Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
ITEM_CONTENT,
group3));
group3.Items.Add(new SampleDataItem("Group-3-Item-3",
"Item Title: 3",
"Item Subtitle: 3",
"Assets/DarkGray.png",
"Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
ITEM_CONTENT,
group3));
group3.Items.Add(new SampleDataItem("Group-3-Item-4",
"Item Title: 4",
"Item Subtitle: 4",
"Assets/LightGray.png",
"Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
ITEM_CONTENT,
group3));
group3.Items.Add(new SampleDataItem("Group-3-Item-5",
"Item Title: 5",
"Item Subtitle: 5",
"Assets/MediumGray.png",
"Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
ITEM_CONTENT,
group3));
group3.Items.Add(new SampleDataItem("Group-3-Item-6",
"Item Title: 6",
"Item Subtitle: 6",
"Assets/DarkGray.png",
"Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
ITEM_CONTENT,
group3));
group3.Items.Add(new SampleDataItem("Group-3-Item-7",
"Item Title: 7",
"Item Subtitle: 7",
"Assets/MediumGray.png",
"Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
ITEM_CONTENT,
group3));
this.AllGroups.Add(group3);
var group4 = new SampleDataGroup("Group-4",
"Group Title: 4",
"Group Subtitle: 4",
"Assets/LightGray.png",
"Group Description: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus tempor scelerisque lorem in vehicula. Aliquam tincidunt, lacus ut sagittis tristique, turpis massa volutpat augue, eu rutrum ligula ante a ante");
group4.Items.Add(new SampleDataItem("Group-4-Item-1",
"Item Title: 1",
"Item Subtitle: 1",
"Assets/DarkGray.png",
"Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
ITEM_CONTENT,
group4));
group4.Items.Add(new SampleDataItem("Group-4-Item-2",
"Item Title: 2",
"Item Subtitle: 2",
"Assets/LightGray.png",
"Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
ITEM_CONTENT,
group4));
group4.Items.Add(new SampleDataItem("Group-4-Item-3",
"Item Title: 3",
"Item Subtitle: 3",
"Assets/DarkGray.png",
"Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
ITEM_CONTENT,
group4));
group4.Items.Add(new SampleDataItem("Group-4-Item-4",
"Item Title: 4",
"Item Subtitle: 4",
"Assets/LightGray.png",
"Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
ITEM_CONTENT,
group4));
group4.Items.Add(new SampleDataItem("Group-4-Item-5",
"Item Title: 5",
"Item Subtitle: 5",
"Assets/MediumGray.png",
"Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
ITEM_CONTENT,
group4));
group4.Items.Add(new SampleDataItem("Group-4-Item-6",
"Item Title: 6",
"Item Subtitle: 6",
"Assets/LightGray.png",
"Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
ITEM_CONTENT,
group4));
this.AllGroups.Add(group4);
var group5 = new SampleDataGroup("Group-5",
"Group Title: 5",
"Group Subtitle: 5",
"Assets/MediumGray.png",
"Group Description: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus tempor scelerisque lorem in vehicula. Aliquam tincidunt, lacus ut sagittis tristique, turpis massa volutpat augue, eu rutrum ligula ante a ante");
group5.Items.Add(new SampleDataItem("Group-5-Item-1",
"Item Title: 1",
"Item Subtitle: 1",
"Assets/LightGray.png",
"Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
ITEM_CONTENT,
group5));
group5.Items.Add(new SampleDataItem("Group-5-Item-2",
"Item Title: 2",
"Item Subtitle: 2",
"Assets/DarkGray.png",
"Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
ITEM_CONTENT,
group5));
group5.Items.Add(new SampleDataItem("Group-5-Item-3",
"Item Title: 3",
"Item Subtitle: 3",
"Assets/LightGray.png",
"Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
ITEM_CONTENT,
group5));
group5.Items.Add(new SampleDataItem("Group-5-Item-4",
"Item Title: 4",
"Item Subtitle: 4",
"Assets/MediumGray.png",
"Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
ITEM_CONTENT,
group5));
this.AllGroups.Add(group5);
var group6 = new SampleDataGroup("Group-6",
"Group Title: 6",
"Group Subtitle: 6",
"Assets/DarkGray.png",
"Group Description: Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus tempor scelerisque lorem in vehicula. Aliquam tincidunt, lacus ut sagittis tristique, turpis massa volutpat augue, eu rutrum ligula ante a ante");
group6.Items.Add(new SampleDataItem("Group-6-Item-1",
"Item Title: 1",
"Item Subtitle: 1",
"Assets/LightGray.png",
"Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
ITEM_CONTENT,
group6));
group6.Items.Add(new SampleDataItem("Group-6-Item-2",
"Item Title: 2",
"Item Subtitle: 2",
"Assets/DarkGray.png",
"Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
ITEM_CONTENT,
group6));
group6.Items.Add(new SampleDataItem("Group-6-Item-3",
"Item Title: 3",
"Item Subtitle: 3",
"Assets/MediumGray.png",
"Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
ITEM_CONTENT,
group6));
group6.Items.Add(new SampleDataItem("Group-6-Item-4",
"Item Title: 4",
"Item Subtitle: 4",
"Assets/DarkGray.png",
"Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
ITEM_CONTENT,
group6));
group6.Items.Add(new SampleDataItem("Group-6-Item-5",
"Item Title: 5",
"Item Subtitle: 5",
"Assets/LightGray.png",
"Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
ITEM_CONTENT,
group6));
group6.Items.Add(new SampleDataItem("Group-6-Item-6",
"Item Title: 6",
"Item Subtitle: 6",
"Assets/MediumGray.png",
"Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
ITEM_CONTENT,
group6));
group6.Items.Add(new SampleDataItem("Group-6-Item-7",
"Item Title: 7",
"Item Subtitle: 7",
"Assets/DarkGray.png",
"Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
ITEM_CONTENT,
group6));
group6.Items.Add(new SampleDataItem("Group-6-Item-8",
"Item Title: 8",
"Item Subtitle: 8",
"Assets/LightGray.png",
"Item Description: Pellentesque porta, mauris quis interdum vehicula, urna sapien ultrices velit, nec venenatis dui odio in augue. Cras posuere, enim a cursus convallis, neque turpis malesuada erat, ut adipiscing neque tortor ac erat.",
ITEM_CONTENT,
group6));
this.AllGroups.Add(group6);
*/
/*
var group2 = new SampleDataGroup("Patient Images", "Post Operative Images", "", "", "");
int count = 30;
for (int i = 1; i <= count; i++)
{
if (i < 10)
{
group2.Items.Add(new SampleDataItem("Group-2-Item-" + i,
"2012-06-30 TR 10:45:0" + i + " UTC-05:00",
"",
"Assets/" + i + ".png",
"",
"",
group2));
}
else
{
group2.Items.Add(new SampleDataItem("Group-2-Item-" + i,
"2012-06-30 TR 10:45:" + i + " UTC-05:00",
"",
"Assets/" + i + ".png",
"",
"",
group2));
}
*/
}
}
}
<file_sep>/windows8appsample/CareLink/ItemDetailPage.xaml.cs
using CareLink.Data;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Media.Capture;
using Windows.Storage;
using Windows.Storage.Streams;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;
using Windows.UI.Xaml.Navigation;
// The Item Detail Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234232
namespace CareLink
{
/// <summary>
/// A page that displays details for a single item within a group while allowing gestures to
/// flip through other items belonging to the same group.
/// </summary>
public sealed partial class ItemDetailPage : CareLink.Common.LayoutAwarePage
{
public ItemDetailPage()
{
this.InitializeComponent();
}
/// <summary>
/// Populates the page with content passed during navigation. Any saved state is also
/// provided when recreating a page from a prior session.
/// </summary>
/// <param name="navigationParameter">The parameter value passed to
/// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
/// </param>
/// <param name="pageState">A dictionary of state preserved by this page during an earlier
/// session. This will be null the first time a page is visited.</param>
protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
{
// Allow saved page state to override the initial item to display
if (pageState != null && pageState.ContainsKey("SelectedItem"))
{
navigationParameter = pageState["SelectedItem"];
}
// TODO: Create an appropriate data model for your problem domain to replace the sample data
var item = SampleDataSource.GetItem((String)navigationParameter);
this.DefaultViewModel["Group"] = item.Group;
this.DefaultViewModel["Items"] = item.Group.Items;
this.flipView.SelectedItem = item;
}
/// <summary>
/// Preserves state associated with this page in case the application is suspended or the
/// page is discarded from the navigation cache. Values must conform to the serialization
/// requirements of <see cref="SuspensionManager.SessionState"/>.
/// </summary>
/// <param name="pageState">An empty dictionary to be populated with serializable state.</param>
protected override void SaveState(Dictionary<String, Object> pageState)
{
var selectedItem = (SampleDataItem)this.flipView.SelectedItem;
pageState["SelectedItem"] = selectedItem.UniqueId;
}
private async void NextButton_click(object sender, RoutedEventArgs e)
{
// Using Windows.Media.Capture.CameraCaptureUI API to capture a photo
CameraCaptureUI dialog = new CameraCaptureUI();
Size aspectRatio = new Size(16, 9);
dialog.PhotoSettings.CroppedAspectRatio = aspectRatio;
StorageFile file = await dialog.CaptureFileAsync(CameraCaptureUIMode.Photo);
if (file != null)
{
BitmapImage bitmapImage = new BitmapImage();
using (IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.Read))
{
bitmapImage.SetSource(fileStream);
}
//get a pic for this in a momo
photoImage.Source = bitmapImage;
//ResetButton.Visibility = Visibility.Visible;
// Store the file path in Application Data
//where we will store photo
//appSettings[photoKey] = file.Path;
}
}
private void flipView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
}
private void QuizButton_Click(object sender, RoutedEventArgs e)
{
if (this.Frame != null)
{
this.Frame.Navigate(typeof(QuizPage));
}
}
private void TakeNotes_Button(object sender, RoutedEventArgs e)
{
if (this.Frame != null)
{
this.Frame.Navigate(typeof(NotesPage));
}
}
}
}
|
a1ca0914a0c3045bb9caa44c77235fe19cd067b5
|
[
"C#"
] | 3
|
C#
|
polinadotio/windows8appsample
|
90a9b47f63b42db0befa0e931c2bd8c7b050f977
|
7c4cb1ca16c2c78a739db51f5d94c413722aed71
|
refs/heads/master
|
<repo_name>SalimBerk/kodluyoruz--dev--2<file_sep>/ekle.js
function newElement() {
const task = document.querySelector("#task");
let message = task.value;
let list = document.querySelector("#list");
let li = document.createElement("li");
li.setAttribute("class", "list-group-item list-group-item-action");
li.style.border = "solid #ff7f00";
li.style.marginBottom = "50px";
li.style.color = "#ff7f00";
li.innerHTML = message;
if (message){
list.appendChild(li);
}else{
const alert_dom=document.querySelector("#alert");
const alert=`<div class="alert alert-warning alert-dismissible fade show" role="alert">
<strong>UYARI!</strong> Veri girişi yapılmadı !!!.
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>`
alert_dom.innerHTML=alert;
}
var span = document.createElement("span");
var text = document.createTextNode("X");
span.className = "close";
span.appendChild(text);
li.appendChild(span);
span.addEventListener("click", function () {
list.removeChild(li);
});
}
|
6297a19b3cce24718d3047ae572f91e73962eccb
|
[
"JavaScript"
] | 1
|
JavaScript
|
SalimBerk/kodluyoruz--dev--2
|
0f1335519ba007b1ef5fb7bc05236f0612730931
|
0dc3ee52afcab5ca5c1531720053386986e6f11a
|
refs/heads/master
|
<file_sep>/*
A test to verify the correct naming adopted by ROOT.
It is intended to collect all the issues encountered with naming
during the development, testing and production phase of ROOT6.
"Stat rosa pristina nomine, nomina nuda tenemus"
*/
#include <algorithm>
namespace std {
class Something {};
typedef Something Something_t;
}
void checkTypedef(const std::string& name)
{
std::cout << "@" << name << "@ --> @" << TClassEdit::ResolveTypedef(name.c_str()) << "@" << std::endl;
}
void checkShortType(const std::string& name)
{
std::cout << "@" << name << "@ --> @" << TClassEdit::ShortType(name.c_str(), 1186) << "@" << std::endl;
}
int execCheckNaming(){
using namespace std::placeholders;
// The role of ResolveTypedef is to remove typedef and should be given
// an almost normalized name. The main purpose of this test is to
// insure that nothing is removed and no stray space is added.
// However, (at least for now), it is allowed to remove some spaces
// but does not have to remove them (this is the job of ShortType
// or the name normalization routine).
const std::vector<const char*> tceTypedefNames={"const Something_t&",
"const std::Something&",
"const string&",
"A<B>[2]",
"X<A<B>[2]>"};
const std::vector<const char*> tceNames={"const std::Something&",
"const std::Something &",
"const std::string&",
"const std::string &",
"const std::string &",
"A<B>[2]",
"X<A<B>[2]>",
"__shared_ptr<TObject>"};
std::cout << "Check TClassEdit::ResolveTypedef\n";
for (auto& name : tceTypedefNames)
checkTypedef(name);
std::cout << "Check TClassEdit::ShortType\n";
for (auto& name : tceNames)
checkShortType(name);
// GetNormalizedName
// Here tests for Norm Name
return 0;
}
<file_sep>ROOTTEST_ADD_TEST(TEnv
MACRO testTEnv.C
OUTREF testTEnv.ref)
<file_sep>#include "testSelector.h"
<file_sep>#include "gtest/gtest.h"
#include "TH1.h"
#include "ROOT/THist.h"
// Test "x + 0 = x"
TEST(HistAddTest, AddEmptyHist) {
EXPECT_EQ(0, 0);
}
// Test addition of a hist range
TEST(HistAddTest, AddView) {
EXPECT_EQ(1, 1);
}
<file_sep>#include "Pythonizables.h"
//===========================================================================
MyBufferReturner::MyBufferReturner(int size) : m_size(size) {
m_Xbuf = new double[size];
m_Ybuf = new double[size];
for (int i=0; i<size; ++i) {
m_Xbuf[i] = 2.0;
m_Ybuf[i] = 5.0;
}
}
MyBufferReturner::~MyBufferReturner() {
delete[] m_Xbuf;
delete[] m_Ybuf;
}
int MyBufferReturner::GetN() { return m_size; }
double* MyBufferReturner::GetX() { return m_Xbuf; }
double* MyBufferReturner::GetY() { return m_Ybuf; }
<file_sep>{
gROOT->ProcessLine(".L testSel.C+");
// Insure that the library is not loaded instead of the
// script
gInterpreter->UnloadLibraryMap("testSelector_C");
#if !defined(ClingWorkAroundMissingUnloading) && !defined(ClingWorkAroundJITandInline)
gROOT->ProcessLine(".L testSelector.C");
bool res = runtest();
if (!res) return !res;
#else
fprintf(stderr,"testSelector result is 1 0 1\n");
fprintf(stderr,"Info in <ACLiC>: script has already been loaded in interpreted mode\n");
fprintf(stderr,"Info in <ACLiC>: unloading testSelector.C and compiling it\n");
#endif
gROOT->ProcessLine(".L testSelector.C+");
#if defined(ClingWorkAroundMissingDynamicScope) || defined(ClingWorkAroundBrokenUnnamedReturn)
bool res;
res = gROOT->ProcessLine("runtest();");
res = !res;
#else
bool res = runtest();
return !res;
#endif
}
<file_sep># File: roottest/python/pythonizations/PyROOT_pythonizationstests.py
# Author: <NAME> (LBNL, <EMAIL>)
# Created: 07/03/15
# Last: 07/03/15
"""Pythonization tests for PyROOT package."""
import os, sys
sys.path.append( os.path.join( os.getcwd(), os.pardir ) )
from common import *
from pytest import raises
def setup_module(mod):
import sys, os
sys.path.append( os.path.join( os.getcwd(), os.pardir ) )
err = os.system("make Pythonizables_C")
if err:
raise OSError("'make' failed (see stderr)")
class TestClassPYTHONIZATIONS:
def setup_class(cls):
import cppyy
cls.test_dct = "Pythonizables_C"
cls.pythonizables = cppyy.load_reflection_info(cls.test_dct)
def test01_size_mapping(self):
"""Use composites to map GetSize() onto buffer returns"""
import cppyy
def set_size(self, buf):
buf.SetSize(self.GetN())
return buf
cppyy.add_pythonization(
cppyy.compose_method('MyBufferReturner$', 'Get[XY]$', set_size))
m = cppyy.gbl.MyBufferReturner
class TestClassPYTHONIZATIONS_FRAGILITY:
def setup_class(cls):
import cppyy
cls.test_dct = "Pythonizables_C"
cls.pythonizables = cppyy.load_reflection_info(cls.test_dct)
class TestClassROOT_PYTHONIZATIONS:
def test01_tgraph(self):
"""TGraph has GetN() mapped as size to its various buffer returns"""
import ROOT
## actual test run
if __name__ == '__main__':
result = run_pytest(__file__)
sys.exit(result)
<file_sep>#!/bin/sh
cat $1/test.csv | ./readFromCin
<file_sep>1# File: roottest/python/stl/PyROOT_stltests.py
# Author: <NAME> (LBNL, <EMAIL>)
# Created: 10/25/05
# Last: 05/01/15
"""STL unit tests for PyROOT package."""
import sys, os, unittest
sys.path.append( os.path.join( os.getcwd(), os.pardir ) )
from ROOT import *
from common import *
__all__ = [
'STL1VectorTestCase',
'STL2ListTestCase',
'STL3MapTestCase',
'STL4STLLikeClassTestCase',
'STL5StringHandlingTestCase',
'STL6IteratorTestCase',
'STL7StreamTestCase',
]
gROOT.LoadMacro( "StlTypes.C+" )
### STL vector test case =====================================================
class STL1VectorTestCase( MyTestCase ):
N = 13
def test1BuiltinVectorType( self ):
"""Test access to a vector<int> (part of cintdlls)"""
a = std.vector( int )( self.N )
self.assertEqual( len(a), self.N )
for i in range(self.N):
a[i] = i
self.assertEqual( a[i], i )
self.assertEqual( a.at(i), i )
self.assertEqual( a.size(), self.N )
self.assertEqual( len(a), self.N )
def test2BuiltinVectorType( self ):
"""Test access to a vector<double> (part of cintdlls)"""
a = std.vector( 'double' )()
for i in range(self.N):
a.push_back( i )
self.assertEqual( a.size(), i+1 )
self.assertEqual( a[i], i )
self.assertEqual( a.at(i), i )
self.assertEqual( a.size(), self.N )
self.assertEqual( len(a), self.N )
def test3GeneratedVectorType( self ):
"""Test access to a ACLiC generated vector type"""
a = std.vector( JustAClass )()
self.assert_( hasattr( a, 'size' ) )
self.assert_( hasattr( a, 'push_back' ) )
self.assert_( hasattr( a, '__getitem__' ) )
self.assert_( hasattr( a, 'begin' ) )
self.assert_( hasattr( a, 'end' ) )
self.assertEqual( a.size(), 0 )
for i in range(self.N):
a.push_back( JustAClass() )
a[i].m_i = i
self.assertEqual( a[i].m_i, i )
self.assertEqual( len(a), self.N )
def test4EmptyVectorType( self ):
"""Test behavior of empty vector<int> (part of cintdlls)"""
a = std.vector( int )()
for arg in a:
pass
def test5PushbackIterablesWithIAdd( self ):
"""Test usage of += of iterable on push_back-able container"""
a = std.vector( int )()
a += [ 1, 2, 3 ]
self.assertEqual( len(a), 3 )
self.assertEqual( a[0], 1 )
self.assertEqual( a[1], 2 )
self.assertEqual( a[2], 3 )
a += ( 4, 5, 6 )
self.assertEqual( len(a), 6 )
self.assertEqual( a[3], 4 )
self.assertEqual( a[4], 5 )
self.assertEqual( a[5], 6 )
self.assertRaises( TypeError, a.__iadd__, ( 7, '8' ) )
def test6VectorReturnDowncasting( self ):
"""Pointer returns of vector indexing must be down cast"""
v = PR_Test.mkVect()
self.assertEqual( type(v), std.vector( 'PR_Test::Base*' ) )
self.assertEqual( len(v), 1 )
self.assertEqual( type(v[0]), PR_Test.Derived )
self.assertEqual( PR_Test.checkType(v[0]), PR_Test.checkType(PR_Test.Derived()) )
p = PR_Test.check()
self.assertEqual( type(p), PR_Test.Derived )
self.assertEqual( PR_Test.checkType(p), PR_Test.checkType(PR_Test.Derived()) )
### STL list test case =======================================================
class STL2ListTestCase( MyTestCase ):
N = 13
def test1BuiltinListType( self ):
"""Test access to a list<int> (part of cintdlls)"""
a = std.list( int )()
for i in range(self.N):
a.push_back( i )
self.assertEqual( len(a), self.N )
self.failUnless( 11 in a )
ll = list(a)
for i in range(self.N):
self.assertEqual( ll[i], i )
for val in a:
self.assertEqual( ll[ ll.index(val) ], val )
def test2EmptyListType( self ):
"""Test behavior of empty list<int> (part of cintdlls)"""
a = std.list( int )()
for arg in a:
pass
### STL map test case ========================================================
class STL3MapTestCase( MyTestCase ):
N = 13
def test01BuiltinMapType( self ):
"""Test access to a map<int,int> (part of cintdlls)"""
a = std.map( int, int )()
for i in range(self.N):
a[i] = i
self.assertEqual( a[i], i )
self.assertEqual( len(a), self.N )
for key, value in a:
self.assertEqual( key, value )
self.assertEqual( key, self.N-1 )
self.assertEqual( value, self.N-1 )
# add a variation, just in case
m = std.map( int, int )()
for i in range(self.N):
m[i] = i*i
self.assertEqual( m[i], i*i )
for key, value in m:
self.assertEqual( key*key, value )
self.assertEqual( key, self.N-1 )
self.assertEqual( value, (self.N-1)*(self.N-1) )
def test02KeyedMapType( self ):
"""Test access to a map<std::string,int> (part of cintdlls)"""
a = std.map( std.string, int )()
for i in range(self.N):
a[str(i)] = i
self.assertEqual( a[str(i)], i )
self.assertEqual( i, self.N-1 )
self.assertEqual( len(a), self.N )
def test03EmptyMapType( self ):
"""Test behavior of empty map<int,int> (part of cintdlls)"""
m = std.map( int, int )()
for key, value in m:
pass
def test04UnsignedvalueTypeMapTypes( self ):
"""Test assignability of maps with unsigned value types (not part of cintdlls)"""
import math
mui = std.map( str, 'unsigned int' )()
mui[ 'one' ] = 1
self.assertEqual( mui[ 'one' ], 1 )
self.assertRaises( ValueError, mui.__setitem__, 'minus one', -1 )
# UInt_t is always 32b, sys.maxint follows system int
maxint32 = int(math.pow(2,31)-1)
mui[ 'maxint' ] = maxint32 + 3
self.assertEqual( mui[ 'maxint' ], maxint32 + 3 )
mul = std.map( str, 'unsigned long' )()
mul[ 'two' ] = 2
self.assertEqual( mul[ 'two' ], 2 )
mul[ 'maxint' ] = maxvalue + 3
self.assertEqual( mul[ 'maxint' ], maxvalue + 3 )
self.assertRaises( ValueError, mul.__setitem__, 'minus two', -2 )
def test05FreshlyInstantiatedMapType( self ):
"""Instantiate a map from a newly defined class"""
gInterpreter.Declare( 'template<typename T> struct Data { T fVal; };' )
results = std.map( std.string, Data(int) )()
d = Data(int)(); d.fVal = 42
results[ 'summary' ] = d
self.assertEqual( results.size(), 1 )
for tag, data in results:
self.assertEqual( data.fVal, 42 )
### Protocol mapping for an STL like class ===================================
class STL4STLLikeClassTestCase( MyTestCase ):
def test1STLLikeClassIndexingOverloads( self ):
"""Test overloading of operator[] in STL like class"""
a = STLLikeClass( int )()
self.assertEqual( a[ "some string" ], 'string' )
self.assertEqual( a[ 3.1415 ], 'double' )
def test2STLLikeClassIterators( self ):
"""Test the iterator protocol mapping for an STL like class"""
a = STLLikeClass( int )()
for i in a:
pass
self.assertEqual( i, 3 )
### String handling ==========================================================
class STL5StringHandlingTestCase( MyTestCase ):
def test1StringArgumentPassing( self ):
"""Test mapping of python strings and std::string"""
c, s = StringyClass(), std.string( "test1" )
# pass through const std::string&
c.SetString1( s )
self.assertEqual( type(c.GetString1()), str )
self.assertEqual( c.GetString1(), s )
c.SetString1( "test2" )
self.assertEqual( c.GetString1(), "test2" )
# pass through std::string (by value)
s = std.string( "test3" )
c.SetString2( s )
self.assertEqual( c.GetString1(), s )
c.SetString2( "test4" )
self.assertEqual( c.GetString1(), "test4" )
# getting through std::string&
s2 = std.string()
c.GetString2( s2 )
self.assertEqual( s2, "test4" )
self.assertRaises( TypeError, c.GetString2, "temp string" )
def test2StringDataAccess( self ):
"""Test access to std::string object data members"""
c, s = StringyClass(), std.string( "test string" )
c.m_string = s
self.assertEqual( c.m_string, s )
self.assertEqual( c.GetString1(), s )
c.m_string = "another test"
self.assertEqual( c.m_string, "another test" )
self.assertEqual( c.GetString1(), "another test" )
def test3StringWithNullCharacter( self ):
"""Test that strings with NULL do not get truncated"""
t0 = "aap\0noot"
self.assertEqual( t0, "aap\0noot" )
c, s = StringyClass(), std.string( t0, len(t0) )
c.SetString1( s )
self.assertEqual( t0, c.GetString1() )
self.assertEqual( s, c.GetString1() )
### Iterator comparison ======================================================
class STL6IteratorComparisonTestCase( MyTestCase ):
def __run_tests( self, container ):
self.assertEqual( len(container), 1 )
b1, e1 = container.begin(), container.end()
b2, e2 = container.begin(), container.end()
self.assert_( b1.__eq__( b2 ) )
self.assert_( not b1.__ne__( b2 ) )
if sys.hexversion < 0x3000000:
self.assertEqual( cmp( b1, b2 ), 0 )
self.assert_( e1.__eq__( e2 ) )
self.assert_( not e1.__ne__( e2 ) )
if sys.hexversion < 0x3000000:
self.assertEqual( cmp( e1, e2 ), 0 )
self.assert_( not b1.__eq__( e1 ) )
self.assert_( b1.__ne__( e1 ) )
if sys.hexversion < 0x3000000:
self.assertNotEqual( cmp( b1, e1 ), 0 )
b1.__preinc__()
self.assert_( not b1.__eq__( b2 ) )
self.assert_( b1.__eq__( e2 ) )
if sys.hexversion < 0x3000000:
self.assertNotEqual( cmp( b1, b2 ), 0 )
self.assertEqual( cmp( b1, e1 ), 0 )
self.assertNotEqual( b1, b2 )
self.assertEqual( b1, e2 )
def test1BuiltinVectorIterators( self ):
"""Test iterator comparison for vector"""
v = std.vector( int )()
v.resize( 1 )
self.__run_tests( v )
def test2BuiltinListIterators( self ):
"""Test iterator comparison for list"""
l = std.list( int )()
l.push_back( 1 )
self.__run_tests( l )
def test3BuiltinMapIterators( self ):
"""Test iterator comparison for map"""
m = std.map( int, int )()
m[1] = 1
self.__run_tests( m )
### Stream usage =============================================================
class STL7StreamTestCase( MyTestCase ):
def test1_PassStringStream( self ):
"""Pass stringstream through ostream&"""
s = std.stringstream()
o = StringStreamUser()
o.fillStream( s )
self.assertEqual( "StringStreamUser Says Hello!", s.str() )
## actual test run
if __name__ == '__main__':
from MyTextTestRunner import MyTextTestRunner
loader = unittest.TestLoader()
testSuite = loader.loadTestsFromModule( sys.modules[ __name__ ] )
runner = MyTextTestRunner( verbosity = 2 )
result = not runner.run( testSuite ).wasSuccessful()
sys.exit( result )
<file_sep>{
#ifdef ClingWorkAroundMissingImplicitAuto
TClonesArray *tc, *tc2;
#endif
tc = new TClonesArray("TNamed",5); for(int i=0; i<20; ++i) tc->ConstructedAt(i);
tc2 = new TClonesArray("TNamed",5); for(int i=0; i<20; ++i) tc2->ConstructedAt(i);
tc->AbsorbObjects(tc2);
delete tc2;
delete tc;
}
<file_sep>ROOTTEST_GENERATE_EXECUTABLE(readFromCin readFromCin.cxx LIBRARIES Core Hist RIO Net Graf Graf3d Gpad Tree Rint Postscript Matrix Physics MathCore Thread MultiProc)
ROOTTEST_ADD_TEST(roottest-root-tree-readcin-readFromCin
COMMAND readFromCin ${CMAKE_CURRENT_SOURCE_DIR}/test.csv
OUTREF ${CMAKE_CURRENT_SOURCE_DIR}/readcin.ref
DEPENDS ${GENERATE_EXECUTABLE_TEST})
ROOTTEST_ADD_TEST(roottest-root-tree-readcin-parseCin
COMMAND ${CMAKE_CURRENT_SOURCE_DIR}/parseCin.sh ${CMAKE_CURRENT_SOURCE_DIR}
OUTREF ${CMAKE_CURRENT_SOURCE_DIR}/readcin.ref )
ROOTTEST_ADD_TESTDIRS()
|
a41eb0ff0933e89e42e519b38fd3cd3f7135c4f8
|
[
"CMake",
"Python",
"C",
"C++",
"Shell"
] | 11
|
C
|
bbockelm/roottest
|
19f5bc7fb0a0704bee6c3d3ab32e8fdc3efbc3f8
|
4d3642190a1f3b77c0eeaf28ed3df4414f9194bd
|
refs/heads/master
|
<repo_name>kasceus/NetFrameworkHelper<file_sep>/ImageHelper.cs
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
namespace NetFrameworkHelper
{
/// <summary>
/// Class that contains common operations for handling images
/// </summary>
public static class ImageHelper
{
/// <summary>
/// Convert an image to a blob (byte array) for storage in a database or for further byte manipulation
/// </summary>
/// <param name="image">Image this operation will be carried out against</param>
/// <returns>byte[]</returns>
public static byte[] ToBlob(this Image image)
{
//check if the byte array is compressed before moving on
if (image == null)
{
throw new ArgumentNullException(nameof(image), "The image passed was null;");
}
return image.ToBlob(false);
}
/// <summary>
/// Convert an image to a blob (byte array) for storage in a database or for further byte manipulation.
/// Specify true to return a compressed byte array.
/// </summary>
/// <param name="image">Image this operation will be carried out against</param>
/// <param name="compress">Specify wether or not to compress the byte array using GZip. Default is false</param>
/// <returns></returns>
public static byte[] ToBlob(this Image image, bool compress = false)
{
//check if the byte array is compressed before moving on
if (image == null)
{
throw new ArgumentNullException(nameof(image), "The image passed was null;");
}
ImageConverter imageConverter = new ImageConverter();
byte[] byteArr = (byte[])imageConverter.ConvertTo(image, typeof(byte[]));
if (compress)
{
return byteArr.Compress();
}
return byteArr;
}
/// <summary>
/// Convert a blob (byte array) to Image. Automatically checks for compression.
/// </summary>
/// <param name="byteArray"></param>
/// <returns></returns>
public static Image ToImage(this byte[] byteArray)
{
if (byteArray == null)
{
throw new ArgumentNullException(nameof(byteArray), "Byte array was null.");
}
using (MemoryStream ms = new MemoryStream(byteArray))
{
return Image.FromStream(ms);
}
}
/// <summary>
/// Resize an image. Maintains aspect ratio
/// </summary>
/// <param name="image">Image to apply this to</param>
/// <param name="size"> new size parameters</param>
/// <returns></returns>
public static Image Resize(this Image image, Size size)
{
if (image == null)
{
throw new ArgumentNullException(nameof(image), "image passed as null.");
}
if (size == null)
{
throw new ArgumentNullException(nameof(size), "Size cannot be null");
}
int sourceWidth = image.Width;
int sourceHeight = image.Height;
float nPercentW = size.Width / (float)sourceWidth;
float nPercentH = size.Height / (float)sourceHeight;
float nPercent;
if (nPercentH < nPercentW)
{
nPercent = nPercentH;
}
else
{
nPercent = nPercentW;
}
int destWidth = (int)(sourceWidth * nPercent);
int destHeight = (int)(sourceHeight * nPercent);
Bitmap b = new Bitmap(destWidth, destHeight);
Graphics g = Graphics.FromImage((Image)b);
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.DrawImage(image, 0, 0, destWidth, destHeight);
g.Dispose();
return (Image)b;
}
}
/// <summary>
/// ImageMetaData class. Used to hold basic image meta data for quick access.
/// </summary>
public class ImageMetaData
{
/// <summary>
/// File name of the image
/// </summary>
public string ImageName { get; set; }
/// <summary>
/// File extension of the image
/// </summary>
public string ImageExtension { get; set; }
/// <summary>
/// Mime type for the image
/// </summary>
public string MimeType { get; set; }
}
}
<file_sep>/README.md
# NetFrameworkHelper
dll used in .net framework projects. This project contains extension methods for quick actions when dealing with strings, files, bytes, and a few other tools to help out along the way
>Currently targets framework 4.8.
*This is a work in progress, and changes will be made frequently.
## Setup
Pull this to your local machine. Build the solution. Find the path to the NetFrameworkHelper.dll in the bin\release folder. Add that to references in your project.
To use the library, simply add the namespace via a using statement.
Ex: `using NetFrameworkHelper;`
<file_sep>/CustomActionFilters.cs
using System;
using System.Linq;
using System.Net;
using System.Web.Mvc;
namespace NetFrameworkHelper
{
/// <summary>
/// The ValidateAjaxAttribute is usesd like standard MVC model validation. This is to enable the model errors to be passed
/// back to the client as JAON data - instead of sending back a partial view with the errors plugged into the model errors.
/// This is best used with the universalAjax.js file since it handles pluggin in the data into the appropriate areas.
/// </summary>
public class ValidateAjaxAttribute : ActionFilterAttribute
{
/// <summary>
/// Validates a model that was submitted with Ajax. Will return a 400 error with a JSON containing the error model.
/// </summary>
/// <param name="filterContext"></param>
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext == null)
{
throw new ArgumentNullException(nameof(filterContext), "filter context was passed in as null.");
}
if (!filterContext.HttpContext.Request.IsAjaxRequest())
return;
var modelState = filterContext.Controller.ViewData.ModelState;
if (!modelState.IsValid)
{
var errorModel =
from x in modelState.Keys
where modelState[x].Errors.Count > 0
select new
{
key = x,
errors = modelState[x].Errors.Select(y => y.ErrorMessage).ToArray()
};
filterContext.Result = new JsonResult()
{
Data = errorModel
};
filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
}
}
}
}
<file_sep>/FileHelper.cs
using System;
using System.IO;
using System.Web;
using System.Web.Mvc;
namespace NetFrameworkHelper
{
/// <summary>
/// The FileHelper is used for common file operations. While most of these are custom string extensions, they
/// are used with handling file operations.
/// </summary>
public static class FileHelper
{
/// <summary>
/// This extension method will retun a FileContentResult from a path to a file.
/// <para>This result is return ready- includes mime-type for the specified file</para>
/// </summary>
/// <param name="pathToFile">Full path to a file</param>
/// <returns>FileCointentResult</returns>
public static FileContentResult FileContentResultFromString(this string pathToFile)
{
try
{
FileAttributes attr = File.GetAttributes(pathToFile);
if (attr.HasFlag(FileAttributes.Directory))
{
throw new Exception("The specified path is a directory. Please supply the file name in addition to the file path.");
}
}
catch
{
throw;
}
if (File.Exists(pathToFile))
{
return new FileContentResult(pathToFile.FileBytesFromPath(), pathToFile.GetMimeFromFilePath());
}
else
{
throw new FileNotFoundException(nameof(pathToFile), "The file you requested was not found.");
}
}
/// <summary>
/// Get a mime type for a file path
/// </summary>
/// <param name="pathToFile"></param>
/// <returns></returns>
public static string GetMimeFromFilePath(this string pathToFile)
{
try
{
FileAttributes attr = File.GetAttributes(pathToFile);
if (attr.HasFlag(FileAttributes.Directory))
{
throw new Exception("The specified path is a directory. Please supply the file name in addition to the file path.");
}
}
catch
{
throw;
}
if (File.Exists(pathToFile))
{
string fileName = Path.GetFileName(pathToFile);
return fileName.GetMimeFromFileName();
}
else
{
throw new FileNotFoundException("File not found.");
}
}
/// <summary>
/// Get a mime type for a file name
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
public static string GetMimeFromFileName(this string fileName)
{
try
{
FileAttributes attr = File.GetAttributes(fileName);
if (attr.HasFlag(FileAttributes.Directory))
{
throw new Exception("The specified path is a directory. Please supply the file name.");
}
}
catch
{
throw;
}
return MimeMapping.GetMimeMapping(fileName);
}
/// <summary>
/// Returns the byte array for a specified file path
/// </summary>
/// <param name="pathToFile">File Path string</param>
/// <returns>byte[]</returns>
public static byte[] FileBytesFromPath(this string pathToFile)
{
if (File.Exists(pathToFile))
{
return File.ReadAllBytes(pathToFile);
}
else
{
throw new FileNotFoundException(nameof(pathToFile), "The file you requested was not found.");
}
}
/// <summary>
/// Useful for deleting a file given the full path to the file
/// </summary>
/// <param name="pathToFile">path to the file</param>
public static void DeleteFile(this string pathToFile)
{
try
{
FileAttributes attr = File.GetAttributes(pathToFile);
if (attr.HasFlag(FileAttributes.Directory))
{
throw new Exception("The specified path is a directory. Please supply the file name in addition to the file.");
}
}
catch
{
throw;
}
if (File.Exists(pathToFile))
{
try
{
File.Delete(pathToFile);
}
catch
{ //catch any exceptions and rethrow them
throw;
}
}
else
{
throw new FileNotFoundException("The file was not found");
}
}
}
}
<file_sep>/CustomStringExtensions.cs
using System;
namespace NetFrameworkHelper
{
/// <summary>
/// This class contains custom extensions for use with strings
/// </summary>
public static class CustomStringExtensions
{
/// <summary>
/// Returns a string literal from a specified number of characters from the right of a string
/// </summary>
/// <param name="str">sting this method is called against</param>
/// <param name="start">Number of characters to return from the right side of a string</param>
/// <returns>String</returns>
public static string Right(this string str, int start)
{
if (string.IsNullOrEmpty(str))
{
throw new ArgumentNullException(nameof(str), "String cannot be null or empty");
}
if (start > str.Length)
{
throw new ArgumentOutOfRangeException(nameof(str), "Number of characters greater than the string length");
}
return str.Substring(str.Length - start, start);
}
/// <summary>
/// Returns a string literal from a specified number of characters from the start of a string
/// </summary>
/// <param name="str">sting this method is called against</param>
/// <param name="nCount">Number of characters to return from the left</param>
/// <returns>String</returns>
public static string Left(this string str, int nCount)
{
if (string.IsNullOrEmpty(str))
{
throw new ArgumentNullException(nameof(str), "String cannot be null or empty");
}
if (nCount > str.Length)
{
throw new ArgumentOutOfRangeException(nameof(str), "Number of characters greater than the string length");
}
return str.Substring(0, nCount);
}
/// <summary>
/// Returns a string from a specified start position
/// </summary>
/// <param name="str">sting this method is called against</param>
/// <param name="start">Character number to start with</param>
/// <returns>String</returns>
public static string Mid(this string str, int start)
{
if (string.IsNullOrEmpty(str))
{
throw new ArgumentNullException(nameof(str), "String cannot be null or empty");
}
if (start > str.Length)
{
throw new ArgumentOutOfRangeException(nameof(str), "Number of characters greater than the string length");
}
return str.Substring(start);
}
/// <summary>
/// Returns a string from a specified start position
/// </summary>
/// <param name="str">sting this method is called against</param>
/// <param name="start">Character number to start with</param>
/// <param name="stop">Character number to stop with</param>
/// <returns>String</returns>
public static string Mid(this string str, int start, int stop)
{
if (string.IsNullOrEmpty(str))
{
throw new ArgumentNullException(nameof(str), "String cannot be null or empty");
}
if (start > str.Length)
{
throw new ArgumentOutOfRangeException(nameof(str), "Number of characters greater than the string length");
}
//Check if start is less than 0
start = (start < 0) ? 0 : start;
//check if the requested stop position is longer than the returnes tring would be minus the start position
//if it is, then set stop to the string length minus the start position
stop = (stop > (str.Length - start)) ? str.Length - start : stop;
return str.Substring(start, stop);
}
}
}
<file_sep>/ByteCompression.cs
using System;
using System.IO;
using System.IO.Compression;
namespace NetFrameworkHelper
{
/// <summary>
/// Common byte array extension methods.
/// </summary>
/// <remarks>Byte array extension methods specific to Image operations are located in the Image Helper.</remarks>
public static class ByteCompression
{
/// <summary>
/// Compress a byte array using Gzip
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public static byte[] Compress(this byte[] data)
{
if (data == null)
{
throw new ArgumentNullException(nameof(data), "The byte array was passed as null");
}
using (MemoryStream compressedStream = new MemoryStream())
using (GZipStream zipStream = new GZipStream(compressedStream, CompressionMode.Compress))
{
zipStream.Write(data, 0, data.Length);
zipStream.Close();
return compressedStream.ToArray();
}
}
/// <summary>
/// Decompress a byte array using gzip
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public static byte[] Decompress(this byte[] data)
{
try
{
using (MemoryStream memStream = new MemoryStream(data))
using (GZipStream zipStream = new GZipStream(memStream, CompressionMode.Decompress))
using (MemoryStream resultStream = new MemoryStream())
{
zipStream.CopyTo(resultStream);
zipStream.Dispose();
byte[] retArray = resultStream.ToArray();
return retArray;
}
}
catch {/*not compressed*/}
return data;
}
}
}
<file_sep>/HttpPostedFileBaseExtensions.cs
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Threading.Tasks;
using System.Web;
namespace NetFrameworkHelper
{
/// <summary>
/// Extension methods for handling HttpPostedFileBase files.
/// </summary>
public static class HttpPostedFileBaseExtensions
{
/// <summary>
/// Convert a HttpPostedFileBase to an byte array. To compress the byte array, specify true when calling the extension.
/// </summary>
/// <param name="file">Posted file to apply this to</param>
/// <returns>byte[]</returns>
public static byte[] ConvertToBytes(this HttpPostedFileBase file)
{
if (file == null)
{
throw new ArgumentNullException(nameof(file), "The passed in file parameter was null.");
}
return file.ConvertToBytes(false);
}
/// <summary>
/// Convert a HttpPostedFileBase to an byte array. To compress the byte array, specify true when calling the extension.
/// </summary>
/// <param name="file">Posted file to apply this to</param>
/// <param name="compress">Set to true to compress the returned byte array. Default is false.</param>
/// <returns>byte[]</returns>
public static byte[] ConvertToBytes(this HttpPostedFileBase file, bool compress = false)
{
if (file == null)
{
throw new ArgumentNullException(nameof(file), "The passed in file parameter was null.");
}
BinaryReader rdr = new BinaryReader(file.InputStream);
byte[] byteArr = rdr.ReadBytes(file.ContentLength);
rdr.Dispose();
if (compress)
{
return byteArr.Compress();
}
return byteArr;
}
/// <summary>
/// Convert a list of HttpPostedFileBase to a List of Images. Can specify to convert the images. Default is false.
/// </summary>
/// <param name="files">List of HttpPostedFileBase to run this against</param>
/// <returns></returns>
public static List<Image> ToImageList(this List<HttpPostedFileBase> files)
{
if (files == null)
{
throw new ArgumentNullException(nameof(files), "No files passed in.");
}
List<Image> images = new List<Image>();
Parallel.ForEach(files, file =>
{
images.Add(file.ToImage());
});
return images;
}
/// <summary>
/// Convert <see cref="HttpPostedFileBase"/> to Image. To get Image meta data, cast Image.Tags to <see cref="ImageMetaData"/>
/// </summary>
/// <param name="file">file to apply this method to.</param>
/// <returns>Image</returns>
public static Image ToImage(this HttpPostedFileBase file)
{
if (file == null)
{
throw new ArgumentNullException(nameof(file), "File passed was null");
}
Image img = Image.FromStream(file.InputStream, true, true);
img.Tag = new ImageMetaData
{
ImageName = file.FileName,
ImageExtension = file.FileName.GetFileExtension(),
MimeType = file.FileName.GetMimeFromFileName()
};
return img;
}
/// <summary>
/// Gets file extensions of files.
/// </summary>
/// <param name="fileName"></param>
/// <returns>string with the file extension</returns>
private static string GetFileExtension(this string fileName)
{
if (fileName == null)
{
throw new ArgumentNullException(nameof(fileName), "File name not passed in");
}
string extension;
try
{
extension = Path.GetExtension(fileName);
}
catch (ArgumentException)
{
extension = fileName.Mid(fileName.LastIndexOf('.'));
}
return extension;
}
}
}
|
16a09891cba146de99f53e1f0089e6a2b85b6226
|
[
"Markdown",
"C#"
] | 7
|
C#
|
kasceus/NetFrameworkHelper
|
532c07dceaa39ff3a69cffd2af2995b060dc3cc9
|
2d928c697956a4cecc6c7f1e5c184465f0d18329
|
refs/heads/master
|
<repo_name>FedericoHan/ProgrammingAssignment2<file_sep>/cachematrix.R
## Put comments here that give an overall description of what your
## functions do
## First, we create a list of the following 4 functions
##Set and get matrix
##Set and get inverse of matrix
makeCacheMatrix <- function(x = matrix()) {
TA_invert_matrix <- NULL
set <- function(y){
x <<- y
TA_invert_matrix <<- NULL
}
get <- function() x
setinverse_matrix <- function(inverse) TA_invert_matrix <<- inverse
getinverse_matrix <- function() TA_invert_matrix
list(set = set, get= get, setinverse_matrix = setinverse_matrix,
getinverse_matrix = getinverse_matrix)
}
## Now checks if the inverse of matrix exists in cache, if does, retrives it
## otherwise uses the function solve() to retrieve the inverse of a matrix
## which is the matrix that multiplied to the original, returns the identity matrix
cacheSolve <- function(x, ...) {
TA_invert_matrix <- NULL
set <- function(y){
x <<- y
TA_invert_matrix <<- NULL
}
get <- function() x
setinverse_matrix <- function(inverse) TA_invert_matrix <<- inverse
getinverse_matrix <- function() TA_invert_matrix
list(set = set, get= get, setinverse_matrix = setinverse_matrix,
getinverse_matrix = getinverse_matrix)
}
|
3e7c2d282b6afd440c1e7648e89db32097491497
|
[
"R"
] | 1
|
R
|
FedericoHan/ProgrammingAssignment2
|
979ddd79362fec407bfbdfa9b38a00f6dddb5db8
|
8b39222f2a7c91a02acf6326137a71fc21a76afc
|
refs/heads/master
|
<file_sep><?php
if (!defined('_VALID_MOS') && !defined('_JEXEC'))
die('Direct Access to ' . basename(__FILE__) . ' is not allowed.');
/**
*
* @package RealEstateManager
* @copyright 2012 <NAME>-OrdaSoft(<EMAIL>); <NAME>(<EMAIL>);
* Homepage: http://www.ordasoft.com
* @version: 3.8 Pro
*
*
*/
/**
* Legacy function, use <jdoc:include type="module" /> instead
*
* @deprecated As of version 1.5
*/
if (!defined('DS'))
define('DS', DIRECTORY_SEPARATOR);
if (!function_exists('mosLoadModule')) {
function mosLoadModule($name, $style = - 1) {
?><jdoc:include type="module" name="<?php echo $name ?>" style="<?php echo $style ?>" /><?php
}
}
if (!isset($GLOBALS['realestatemanager_configuration'])) {
require_once (JPATH_ROOT . DS . 'administrator' . DS . 'components' . DS
. 'com_realestatemanager' . DS . 'realestatemanager.class.conf.php' );
$GLOBALS['realestatemanager_configuration'] =
isset($realestatemanager_configuration) ? $realestatemanager_configuration : null;
}
/**
* Legacy function, using <jdoc:include type="modules" /> instead
*
* @deprecated As of version 1.5
*/
//if (!function_exists('clearDate')) {
//
// function clearDate($date) {
// $date = preg_replace('/%/', '', $date);
// return $date;
// }
//
//}
if (!function_exists('mosMail')) {
function mosMail($from, $fromname, $recipient, $subject, $body, $mode = 0, $cc = NULL,
$bcc = NULL, $attachment = NULL, $replyto = NULL, $replytoname = NULL) {
$mailer = JFactory::getMailer();
$mailer->setSender(array($from, $fromname));
$mailer->setSubject($subject);
$mailer->setBody($body);
// Are we sending the email as HTML?
if ($mode) {
$mailer->isHTML(true);
}
if (!is_array($recipient)) {
$recipient = explode(',', $recipient);
}
$mailer->addRecipient($recipient);
$mailer->addCC($cc);
$mailer->addBCC($bcc);
$mailer->addAttachment($attachment);
// Take care of reply email addresses
if (is_array($replyto)) {
$numReplyTo = count($replyto);
for ($i=0; $i < $numReplyTo; $i++){
$mailer->addReplyTo(array($replyto[$i], $replytoname[$i]));
}
} elseif (isset($replyto)) {
$mailer->addReplyTo(array($replyto, $replytoname));
}
return $mailer->Send();
}
}
if (!function_exists('mosLoadAdminModules')) {
function mosLoadAdminModules($position = 'left', $style = 0) {
// Select the module chrome function
if (is_numeric($style)) {
switch ($style) {
case 2:
$style = 'xhtml';
break;
case 0:
default:
$style = 'raw';
break;
}
}
?><jdoc:include type="modules" name="<?php echo $position ?>" style="<?php echo $style ?>" /><?php
}
}
/**
* Legacy function, using <jdoc:include type="module" /> instead
*
* @deprecated As of version 1.5
*/
if (!function_exists('mosLoadAdminModule')) {
function mosLoadAdminModule($name, $style = 0) {
?><jdoc:include type="module" name="<?php echo $name ?>" style="<?php echo $style ?>" /><?php
}
}
/**
* Legacy function, always use {@link JRequest::getVar()} instead
*
* @deprecated As of version 1.5
*/
if (!function_exists('mosStripslashes')) {
function mosStripslashes(&$value) {
$ret = '';
if (is_string($value)) {
$ret = stripslashes($value);
} else {
if (is_array($value)) {
$ret = array();
foreach ($value as $key => $val)
$ret[$key] = mosStripslashes($val);
} else
$ret = $value;
}
return $ret;
}
}
if (!function_exists("formatMoney")) {
function formatMoney($number, $fractional = false, $pattern = ".") {
if(preg_match("/\d/", $pattern)){
$msg = "Your separator: $pattern - incorrect, you can not use numbers, to split price" ;
echo '<script>alert("'.$msg.'");</script>';
$pattern = ".";
}
if ($fractional) {
$number = sprintf('%.2f', $number);
}
if ($pattern == ".")
$number = str_replace(".", ",", $number);
while (true) {
$replaced = preg_replace('/(-?\d+)(\d\d\d)/', '$1' . $pattern . '$2', $number);
//echo $replaced."<br>";
if ($replaced != $number) {
$number = $replaced;
} else {
break;
}
}
// $number = preg_replace('/\^/', $number, $pattern);
return $number;
}
}
/**
* Legacy function, use {@link JFolder::files()} or {@link JFolder::folders()} instead
*
* @deprecated As of version 1.5
*/
if (!function_exists('mosReadDirectory')) {
function mosReadDirectory($path, $filter = '.', $recurse = false, $fullpath = false) {
$arr = array(null);
// Get the files and folders
jimport('joomla.filesystem.folder');
$files = JFolder::files($path, $filter, $recurse, $fullpath);
$folders = JFolder::folders($path, $filter, $recurse, $fullpath);
// Merge files and folders into one array
$arr = array();
if (is_array($files))
$arr = $files;
if (is_array($folders))
$arr = array_merge($arr, $folders);
// Sort them all
asort($arr);
return $arr;
}
}
/**
* Legacy function, use {@link JApplication::redirect() JApplication->redirect()} instead
*
* @deprecated As of version 1.5
*/
if (!function_exists('date_to_data_ms')){
function date_to_data_ms($data_string){ // 2014-01-25 covetr to date in ms
global $database;
// $date = data_transform_rem($data_string);
/* $query = "SELECT UNIX_TIMESTAMP('$data_string')";
$database->setQuery($query);
$rent_ms = $database->loadResult();
return $rent_ms;*/
if($data_string){
$rent_mas = explode('-', $data_string);
$month=$rent_mas[1];
$day=$rent_mas[2];
$year=$rent_mas[0];
$rent_ms = mktime ( 0 ,0, 0, $month , $day , $year);
return $rent_ms;
}else{
exit;
}
}
}
if (!function_exists('mosRedirect')) {
function mosRedirect($url, $msg = '') {
$mainframe = JFactory::getApplication(); // for J 1.6
$mainframe->redirect($url, $msg);
}
}
/**
* Legacy function, use {@link JArrayHelper::getValue()} instead
*
* @deprecated As of version 1.5
*/
if (!function_exists('mosGetParam')) {
function mosGetParam(&$arr, $name, $def = null, $mask = 0) {
// Static input filters for specific settings
static $noHtmlFilter = null;
static $safeHtmlFilter = null;
$var = JArrayHelper::getValue($arr, $name, $def, '');
// If the no trim flag is not set, trim the variable
if (!($mask & 1) && is_string($var))
$var = trim($var);
// Now we handle input filtering
if ($mask & 2) {
// If the allow html flag is set, apply a safe html filter to the variable
if (is_null($safeHtmlFilter))
$safeHtmlFilter = JFilterInput::getInstance(null, null, 1, 1);
$var = $safeHtmlFilter->clean($var, 'none');
} elseif ($mask & 4) {
// If the allow raw flag is set, do not modify the variable
$var = $var;
} else {
// Since no allow flags were set, we will apply the most strict filter to the variable
if (is_null($noHtmlFilter)) {
$noHtmlFilter = JFilterInput::getInstance(/* $tags, $attr, $tag_method, $attr_method, $xss_auto */
);
}
$var = $noHtmlFilter->clean($var, 'none');
}
return $var;
}
}
/**
* Legacy function, use {@link JEditor::save()} or {@link JEditor::getContent()} instead
*
* @deprecated As of version 1.5
*/
if (!function_exists('getEditorContents')) {
function getEditorContents($editorArea, $hiddenField) {
jimport('joomla.html.editor');
$editor = JFactory::getEditor();
echo $editor->save($hiddenField);
}
}
/**
* Legacy function, use {@link JFilterOutput::objectHTMLSafe()} instead
*
* @deprecated As of version 1.5
*/
if (!function_exists('mosMakeHtmlSafe')) {
function mosMakeHtmlSafe(&$mixed, $quote_style = ENT_QUOTES, $exclude_keys = '') {
JFilterOutput::objectHTMLSafe($mixed, $quote_style, $exclude_keys);
}
}
/**
* Legacy utility function to provide ToolTips
*
* @deprecated As of version 1.5
*/
if (!function_exists('mosToolTip')) {
function mosToolTip($tooltip, $title = '', $width = '', $image = 'tooltip.png', $text = '', $href = '', $link = 1) {
// Initialize the toolips if required
static $init;
if (!$init) {
JHTML::_('behavior.tooltip');
$init = true;
}
return JHTML::_('tooltip', $tooltip, $title, $image, $text, $href, $link);
}
}
/**
* Legacy function to replaces & with & for xhtml compliance
*
* @deprecated As of version 1.5
*/
if (!function_exists('mosTreeRecurseREM')) {
function mosTreeRecurseREM($id, $indent, $list, &$children, $maxlevel = 9999, $level = 0, $type = 1) {
if (@$children[$id] && $level <= $maxlevel) {
$parent_id = $id;
foreach ($children[$id] as $v) {
$id = $v->id;
if ($type) {
$pre = 'L ';
$spacer = '. ';
} else {
$pre = '- ';
$spacer = ' ';
}
if ($v->parent == 0)
$txt = $v->name;
else
$txt = $pre . $v->name;
$pt = $v->parent;
$list[$id] = $v;
$list[$id]->treename = "$indent$txt";
$list[$id]->children = count(@$children[$id]);
$list[$id]->all_fields_in_list = count(@$children[$parent_id]);
$list = mosTreeRecurseREM($id, $indent . $spacer, $list, $children, $maxlevel, $level + 1, $type);
}
}
return $list;
}
}
if (!function_exists('getGroupsByUser')) {
function getGroupsByUser($uid, $recurse) {
if (version_compare(JVERSION, "1.6.0", "lt")) {
} else if (version_compare(JVERSION, "1.6.0", "ge")) {
$database = JFactory::getDBO();
// Custom algorythm
$usergroups = array();
if ($recurse == 'RECURSE') {
// [1]: Recurse getting the usergroups
$id_group = array();
$q1 = "SELECT group_id FROM `#__user_usergroup_map` WHERE user_id={$uid}";
$database->setQuery($q1);
$rows1 = $database->loadObjectList();
foreach ($rows1 as $v)
$id_group[] = $v->group_id;
for ($k = 0; $k < count($id_group); $k++) {
$q = "SELECT g2.id FROM `#__usergroups` g1 "
. " LEFT JOIN `#__usergroups` g2 ON g1.lft > g2.lft AND g1.lft < g2.rgt "
. " WHERE g1.id={$id_group[$k]} ORDER BY g2.lft";
$database->setQuery($q);
$rows = $database->loadObjectList();
foreach ($rows as $r)
$usergroups[] = $r->id;
}
$usergroups = array_unique($usergroups);
}
// [2]: Non-Recurse getting usergroups
$q = "SELECT * FROM #__user_usergroup_map WHERE user_id = {$uid}";
$database->setQuery($q);
$rows = $database->loadObjectList();
foreach ($rows as $k => $v)
$usergroups[] = $rows[$k]->group_id;
// If user is unregistered, Joomla contains it into standard group (Public by default).
// So, groupId for anonymous users is 1 (by default).
// But custom algorythm doesnt do this: if user is not autorised, he will NOT connected to any group.
// And groupId will be 0.
if (count($rows) == 0)
$usergroups[] = - 2;
return $usergroups;
} else {
echo "Sanity test. Error version check!";
exit;
}
}
}
if (!function_exists('getWhereUsergroupsCondition')) {
function getWhereUsergroupsCondition($table_alias) {
$my = JFactory::getUser();
if (isset($my->id) AND $my->id != 0)
$usergroups_sh = getGroupsByUser($my->id, '');
else
$usergroups_sh = array();
$usergroups_sh[] = - 2;
$s = '';
for ($i = 0; $i < count($usergroups_sh); $i++) {
$g = $usergroups_sh[$i];
$s.= " $table_alias.params LIKE '%,{$g}' or $table_alias.params = '{$g}' or " .
"$table_alias.params LIKE '{$g},%' or $table_alias.params LIKE '%,{$g},%' ";
if (($i + 1) < count($usergroups_sh))
$s.= ' or ';
}
return $s;
}
}
if (!function_exists('addSubMenuRealEstate')) {
function addSubMenuRealEstate($vName) {
if (!defined('_HEADER_NUMBER')) loadConstRem();
JSubMenuHelper::addEntry(JText::_(_HEADER_NUMBER),
'index.php?option=com_realestatemanager', $vName == 'Houses');
JSubMenuHelper::addEntry(JText::_(_CATEGORIES_NAME),
'index.php?option=com_realestatemanager§ion=categories', $vName == 'Categories');
JSubMenuHelper::addEntry(JText::_(_REALESTATE_MANAGER_LABEL_REVIEWS),
'index.php?option=com_realestatemanager&task=manage_review', $vName == 'Reviews');
JSubMenuHelper::addEntry(JText::_(_REALESTATE_MANAGER_ADMIN_RENT_REQUESTS),
'index.php?option=com_realestatemanager&task=rent_requests', $vName == 'Rent Requests');
JSubMenuHelper::addEntry(JText::_(_REALESTATE_MANAGER_ADMIN_RENT_HISTORY),
'index.php?option=com_realestatemanager&task=users_rent_history', $vName == 'Users Booking History');
JSubMenuHelper::addEntry(JText::_(_REALESTATE_MANAGER_ADMIN_SALE_MANAGER_MENU),
'index.php?option=com_realestatemanager&task=buying_requests', $vName == 'Sale Manager');
JSubMenuHelper::addEntry(JText::_(_REALESTATE_MANAGER_ADMIN_IMPORT_EXPORT),
'index.php?option=com_realestatemanager&task=show_import_export', $vName == 'Import/Export');
JSubMenuHelper::addEntry(JText::_(_REALESTATE_MANAGER_LABEL_FEATURED_MANAGER_FEATURE_MANAGER),
'index.php?option=com_realestatemanager§ion=featured_manager', $vName == 'Features Manager');
JSubMenuHelper::addEntry(JText::_(_REALESTATE_MANAGER_LABEL_LANGUAGE_MENU),
'index.php?option=com_realestatemanager§ion=language_manager', $vName == 'Language Manager');
JSubMenuHelper::addEntry(JText::_(_REALESTATE_MANAGER_ADMIN_LABEL_SETTINGS),
'index.php?option=com_realestatemanager&task=config', $vName == 'Settings');
JSubMenuHelper::addEntry(JText::_(_REALESTATE_MANAGER_ADMIN_ABOUT_ORDERS),
'index.php?option=com_realestatemanager&task=orders', $vName == 'Orders');
JSubMenuHelper::addEntry(JText::_(_REALESTATE_MANAGER_ADMIN_ABOUT_ABOUT),
'index.php?option=com_realestatemanager&task=about', $vName == 'About');
}
}
if (!function_exists('loadConstRem')) {
function loadConstRem() {
global $database, $mosConfig_absolute_path;
$is_exception = false;
$database->setQuery("SELECT * FROM #__rem_languages");
$langs = $database->loadObjectList();
$component_path = JPath::clean($mosConfig_absolute_path . '/components/com_realestatemanager/lang/');
$component_constans = array();
if (is_dir($component_path) && ($component_constans =
JFolder::files($component_path, '^[^_]*\.php$', false, true))) {
//check and add constants file in DB
foreach ($component_constans as $i => $file) {
$file_name = pathinfo($file);
$file_name = $file_name['filename'];
if ($file_name === 'constant') {
require($mosConfig_absolute_path . "/components/com_realestatemanager/lang/$file_name.php");
foreach ( $constMas as $mas ) {
$database->setQuery(
"INSERT IGNORE INTO #__rem_const (const, sys_type) VALUES ('".
$mas["const"]."','".$mas["value_const"]."')");
$database->query();
}
}
}
//check and add new text files in DB
$flag1=true;
print_r("<b>These constants exit in Languages files but not exist in file constants:</b><br><br>");
foreach ($component_constans as $i => $file) {
$file_name = pathinfo($file);
$file_name = $file_name['filename'];
$LangLocal = '';
if ($file_name != 'constant') {
require($mosConfig_absolute_path . "/components/com_realestatemanager/lang/$file_name.php");
try {
$database->setQuery("INSERT IGNORE INTO #__rem_languages (lang_code,title) VALUES ('"
. $LangLocal['lang_code'] . "','" . $LangLocal['title'] . "')");
$database->query();
$database->setQuery("SELECT id FROM #__rem_languages " .
" WHERE lang_code = '" . $LangLocal['lang_code'] . "' AND title='".$LangLocal['title']."'");
$idLang = $database->loadResult();
foreach ($constLang as $item) {
//if(!isset($item['value_const'])) var_dump($item);
$database->setQuery("SELECT id FROM #__rem_const WHERE const = '" . $item['const'] . "'");
$idConst = $database->loadResult();
if(!array_key_exists ( 'value_const' , $item ) || !$idConst){
print_r($item['const']." not exist in file <b>'constant'</b> for this language: <b>"
. $LangLocal['title']."</b>.");
$flag1 = false;
} else {
$database->setQuery(
"INSERT IGNORE INTO #__rem_const_languages (fk_constid,fk_languagesid,value_const) "
. " VALUES ($idConst, $idLang, " . $database->quote($item['value_const']) . ")");
$database->query();
}
}
} catch (Exception $e) {
$is_exception = true;
//echo 'Send exception, please write to admin for language check: ', $e->getMessage(), "\n";
}
}
}
if($flag1){
print_r("<br /><p style='color:green;'><b>Everything is [ OK ]</b></p><br />");
}
else{
print_r("<br><b style='color:red;'>This constants not loaded.!</b><br><br>");
}
//if text constant missing recover they in DB
if (!defined('_HEADER_NUMBER')) {
$query = "SELECT c.const, cl.value_const ";
$query .= "FROM #__rem_const_languages as cl ";
$query .= "LEFT JOIN #__rem_languages AS l ON cl.fk_languagesid=l.id ";
$query .= "LEFT JOIN #__rem_const AS c ON cl.fk_constid=c.id ";
$query .= "WHERE l.lang_code = 'en-GB'";
$database->setQuery($query);
$langConst = $database->loadObjectList();
foreach ($langConst as $item) {
if(!defined($item->const)){
defined($item->const) or define($item->const, $item->value_const);
}
}
}
}
//if some language file missing recover it
$component_path = JPath::clean($mosConfig_absolute_path . '/components/com_realestatemanager/lang/');
$component_constans = array();
if (is_dir($component_path) && ($component_constans = JFolder::files($component_path, '^[^_]*\.php$', false, true))) {
foreach ($component_constans as $i => $file) {
$isLang = 0;
$file_name = pathinfo($file);
$file_name = $file_name['filename'];
if ($file_name != 'constant') {
require($mosConfig_absolute_path . "/components/com_realestatemanager/lang/$file_name.php");
//$fileMas[] = $LangLocal;
$fileMas[] = $LangLocal['title'];
}
}
}
$database->setQuery("SELECT title FROM #__rem_languages");
if (version_compare(JVERSION, '3.0', 'lt')) {
$langs = $database->loadResultArray();
} else {
$langs = $database->loadColumn();
}
if (count($langs) > count($fileMas)) {
$results = array_diff($langs, $fileMas);
foreach ($results as $result) {
$database->setQuery("SELECT lang_code FROM #__rem_languages WHERE title = '$result'");
$lang_code = $database->loadResult();
$langfile = "<?php if( !defined( '_VALID_MOS' ) && !defined( '_JEXEC' ) ) "
. "die( 'Direct Access to '.basename(__FILE__).' is not allowed.' );";
$langfile .= "\n\n/**\n*\n* @package RealestateManager\n"
. "* @copyright 2012 <NAME>-OrdaSoft(<EMAIL>); <NAME>(<EMAIL>);\n"
. "* Homepage: http://www.ordasoft.com\n* @version: 3.0 Pro\n*\n* */\n\n";
$langfile .= "\$LangLocal = array('lang_code'=>'$lang_code', 'title'=>'$result');\n\n";
$langfile .= "\$constLang = array();\n\n";
$query = "SELECT c.const, cl.value_const ";
$query .= "FROM #__rem_const_languages as cl ";
$query .= "LEFT JOIN #__rem_languages AS l ON cl.fk_languagesid=l.id ";
$query .= "LEFT JOIN #__rem_const AS c ON cl.fk_constid=c.id ";
$query .= "WHERE l.title = '$result'";
$database->setQuery($query);
$constlanguages = $database->loadObjectList();
foreach ($constlanguages as $constlanguage) {
$langfile .= "\$constLang[] = array('const'=>'" . $constlanguage->const
. "', 'value_const'=>'" . $database->quote($constlanguage->value_const) . "');\n";
}
// Write out new initialization file
$fd = fopen($mosConfig_absolute_path . "/components/com_realestatemanager/lang/$result.php", "w")
or die("Cannot create language file.");
fwrite($fd, $langfile);
fclose($fd);
}
}
}
}
if (!function_exists('language_check')) {
function language_check($component_db_name = 'rem' ) {
global $database;
$database->setQuery("SELECT * FROM #__".$component_db_name."_languages");
$langIds = $database->loadObjectList();
$flag2=true;
print_r("<br /><b>These constants exit in file constants but not exist in Languages files:</b><br />");
foreach ($langIds as $langId){
$query = " SELECT lc.* FROM #__".$component_db_name."_const as lc ";
$query .= " WHERE NOT EXISTS ";
$query .= " ( SELECT l1.* FROM #__".$component_db_name."_const_languages as l1 ";
$query .= " WHERE lc.id = l1.`fk_constid` and l1.fk_languagesid = ".$langId->id.") ";
$database->setQuery($query);
$badLangConsts = $database->loadObjectList();
if($badLangConsts){
$flag2 = false;
print_r("<br />Languages: ".$langId->title."<br />");
print_r($badLangConsts);
echo "<br><br>";
}
}
if($flag2)
print_r("<br /><p style='color:green;'><b>Everything is [ OK ]</b></p><br /><br />");
}
}
if (!function_exists('remove_langs')) {
function remove_langs($component_db_name = 'rem' ) {
global $database;
$query = " TRUNCATE TABLE #__".$component_db_name."_languages; ";
$database->setQuery($query);
$database->query();
$query = " TRUNCATE TABLE #__".$component_db_name."_const; ";
$database->setQuery($query);
$database->query();
$query = " TRUNCATE TABLE #__".$component_db_name."_const_languages ;";
$database->setQuery($query);
$database->query();
}
}
// Updated on June 25, 2011
// accessgroupid - array which contains accepted user groups for this item
// usersgroupid - groupId of the user
// For anonymous user Uid = 0 and Gid = 0
if (!function_exists('checkAccess_REM')) {
function checkAccess_REM($accessgroupid, $recurse, $usersgroupid, $acl) {
if (!is_array($usersgroupid)) {
$usersgroupid = explode(',', $usersgroupid);
}
//parse usergroups
$tempArr = array();
$tempArr = explode(',', $accessgroupid);
for ($i = 0; $i < count($tempArr); $i++) {
if (((!is_array($usersgroupid) && $tempArr[$i] == $usersgroupid) OR
(is_array($usersgroupid) && in_array($tempArr[$i], $usersgroupid))) || $tempArr[$i] == - 2) {
//allow access
return true;
} else {
if ($recurse == 'RECURSE') {
if (is_array($usersgroupid)) {
foreach ($usersgroupid as $j)
if (in_array($j, $tempArr))
return 1;
} else {
if (in_array($usersgroupid, $tempArr))
return 1;
}
}
}
} // end for
//deny access
return 0;
}
}
if (!function_exists('editorArea')) {
function editorArea($name, $content, $hiddenField, $width, $height, $col, $row, $option = true) {
jimport('joomla.html.editor');
$editor = JFactory::getEditor();
echo $editor->display($hiddenField, $content, $width, $height, $col, $row, $option);
}
}
if(!function_exists('protectInjection')){
function protectInjection($element, $def = '', $filter = "STRING",$bypass_get=false){
global $database;
if(!$bypass_get){
$value = JFactory::getApplication()->input->get($element, $def, $filter);
// $value = $element;
}else{
$value = $element;
}
if(empty($value)) return $value;
if(is_array($value)){
$start_array = $value;
}else {
$hash_string_start = md5($value);
}
$value = str_ireplace(array("/*","*/","select", "insert", "update", "drop", "delete", "alter"), "", $value);
if(is_array($value)){
$end_array = $value;
}else {
$hash_string_end = md5($value);
}
if((!is_array($value) && $hash_string_start != $hash_string_end)
||
is_array($value) && count(array_diff($start_array, $end_array)))
{
return protectInjection($value, $def , $filter ,true);
}
return $database->quote($value);
}
}
if(!function_exists('protectInjectionWithoutQuote')){
function protectInjectionWithoutQuote($element, $def = '', $filter = "STRING",$bypass_get=false){
global $database;
if(!$bypass_get){
$value = JFactory::getApplication()->input->get($element, $def, $filter);
// $value = $element;
}else{
$value = $element;
}
if(empty($value)) return $value;
if(is_array($value)){
$start_array = $value;
}else {
$hash_string_start = md5($value);
}
$value = str_ireplace(array("/*","*/","select", "insert", "update", "drop", "delete", "alter"), "", $value);
if(is_array($value)){
$end_array = $value;
}else {
$hash_string_end = md5($value);
}
if((!is_array($value) && $hash_string_start != $hash_string_end)
||
is_array($value) && count(array_diff($start_array, $end_array)))
{
return protectInjectionWithoutQuote($value, $def , $filter ,true);
}
return $database->escape($value);
}
}
if (!class_exists('getLayoutPath')) {
class getLayoutPath {
static function getLayoutPathCom($components, $type, $layout = 'default') {
$template = JFactory::getApplication()->getTemplate();
$defaultLayout = $layout;
if (strpos($layout, ':') !== false) {
// Get the template and file name from the string
$temp = explode(':', $layout);
$template = ($temp[0] == '_') ? $template : $temp[0];
$layout = $temp[1];
$defaultLayout = ($temp[1]) ? $temp[1] : 'default';
}
// Build the template and base path for the layout
$tPath = JPATH_THEMES . '/' . $template . '/html/' . $components . '/' . $type . '/' . $layout . '.php';
$cPath = JPATH_BASE . '/components/' . $components . '/views/' . $type . '/tmpl/' . $layout . '.php';
$dPath = JPATH_BASE . '/components/' . $components . '/views/' . $type . '/tmpl/default.php';
// If the template has a layout override use it
if (file_exists($tPath)) {
return $tPath;
} else if (file_exists($cPath)) {
return $cPath;
} else if (file_exists($dPath)) {
return $dPath;
} else {
echo "Bad layout path, please write to admin";
exit;
}
}
}
}
if (!function_exists('getLayoutsRem')) {
function getLayoutsRem($components, $type) {
global $database;
$database = JFactory::getDBO();
// get current template on frontend
$template = '';
$query = "SELECT template FROM #__template_styles WHERE client_id=0 AND home=1";
$database->setQuery($query);
$template = $database->loadResult();
// Build the template and base path for the layout
$tPath = JPATH_SITE . '/templates/' . $template . '/html/' . $components . '/' . $type . '/';
$cPath = JPATH_SITE . '/components/' . $components . '/views/' . $type . '/tmpl/';
$layouts1 = array();
$layouts3 = array();
if (is_dir($tPath) && ($layouts1 = JFolder::files($tPath, '^[^_]*\.php$', false, true))) {
foreach ($layouts1 as $i => $file) {
$select_file_name = pathinfo($file);
$select_file_name = $select_file_name['filename'];
$layouts3[] = $select_file_name;
}
}
$layouts2 = array();
$layouts4 = array();
if (is_dir($cPath) && ($layouts2 = JFolder::files($cPath, '^[^_]*\.php$', false, true))) {
foreach ($layouts2 as $i => $file) {
$select_file_name = pathinfo($file);
$select_file_name = $select_file_name['filename'];
$layouts4[] = $select_file_name;
}
}
$layouts = array_merge($layouts3,$layouts4);
$layouts = array_unique($layouts);
return $layouts;
}
}
if(!function_exists('transforDateFromPhpToJquery')){
function transforDateFromPhpToJquery(){
global $realestatemanager_configuration;
$DateToFormat = str_replace("d",'dd',(str_replace("m",'mm',(str_replace("Y",'yy',(
str_replace('%','',$realestatemanager_configuration['date_format'])))))));
return $DateToFormat;
}
}
if (!function_exists('data_transform_rem')) {
function data_transform_rem($date, $date_format = "from") {
global $realestatemanager_configuration, $database;
if (strstr($date, "00:00:00") OR strlen($date) < 11) {
$format = $realestatemanager_configuration['date_format'];
$formatForDateFormat = 'Y-m-d';
} else {
$format = $realestatemanager_configuration['date_format']. " "
. $realestatemanager_configuration['datetime_format'];
$formatForDateFormat = 'Y-m-d H:i:s';
}
$formatForCreateObjDate = str_replace("%","",$format);
if(function_exists('date_format')){
$dateObject = date_create_from_format($formatForCreateObjDate, $date);
if($dateObject){
$date = date_format($dateObject, $formatForDateFormat);
}else{
$dateObject = date_create_from_format($formatForDateFormat, $date);
if($dateObject){
$date = date_format($dateObject, $formatForDateFormat);
}
}
}else{
$query = "SELECT STR_TO_DATE('$date','$format')";
$database->setQuery($query);
$normaDat = $database->loadResult();
if(strlen($normaDat) > 0){
$date = $normaDat;
}
}
return $date;
}
}
if(!function_exists('checkRentDayNightREM')){
function checkRentDayNightREM ($from, $until, $rent_from, $rent_until, $realestatemanager_configuration){
if(isset($realestatemanager_configuration) && $realestatemanager_configuration['special_price']['show']){
if (( $rent_from >= $from &&
$rent_from <= $until) || ($rent_from <= $from &&
$rent_until >= $until) || (
$rent_until >= $from && $rent_until <= $until))
{
return 'Sorry, this item not is available from " '. $from .' " until " '. $until . '"';
}
}else{
if($rent_from === $rent_until){
return 'Sorry, not one night, not selected';
}
if($rent_from < $until && $rent_until > $from){
return 'Sorry, this item not is available from " '. $from .' " until " '. $until . '"';
}
}
}
}
if(!function_exists('createRentTable')){
function createRentTable($rentTerm, $massage, $typeMessage){
global $realestatemanager_configuration;
if($typeMessage === 'error'){
echo '<div id ="message-here" style ="color: red; font-size: 18px;" >'.$massage.'</div>';
}else{
echo '<div id ="message-here" style ="color: gray; font-size: 18px;" >'.$massage.'</div>';
}
echo '<div id ="SpecialPriseBlock">';
echo '<table class="adminlist_04" width ="100%" align ="center">';
echo '<tr>';
echo '<th class="title" align ="center" width ="25%">'.
_REALESTATE_MANAGER_RENT_PRICE_PER_DAY.'</th>';
echo '<th class="title" align ="center" width ="25%">'.
_REALESTATE_MANAGER_FROM.'</th>';
echo '<th class="title" align ="center" width ="25%" >'
._REALESTATE_MANAGER_TO.'</th>';
echo '<th class="title" >'._REALESTATE_MANAGER_LABEL_REVIEW_COMMENT.'</th>';
echo '<th class="title" align ="center" width ="25%">'.
_REALESTATE_MANAGER_LABEL_CALENDAR_SELECT_DELETE.'</th>';
echo '</tr>';
for ($i = 0; $i < count($rentTerm); $i++) {
$DateToFormat = str_replace("D",'d',(str_replace("M",'m',(str_replace('%','',
$realestatemanager_configuration['date_format'])))));
$date_from = new DateTime($rentTerm[$i]->price_from);
$date_to = new DateTime($rentTerm[$i]->price_to);
echo '<tr>';
echo '<td align ="center">'.$rentTerm[$i]->special_price.'</td>';
echo '<td align ="center">'.date_format($date_from, $DateToFormat).'</td>';
echo '<td align ="center">'.date_format($date_to, $DateToFormat).'</td>';
echo '<td>'.$rentTerm[$i]->comment_price.'</td>';
echo '<td align ="center"><input type="checkbox" name="del_rent_sal[]" value="'
.$rentTerm[$i]->id.'"</td>';
echo '</tr>';
}
echo '</table>';
echo '<p>';
echo '<p>';
echo '</div>' ;
exit;
}
}
if(!function_exists('rentPriceREM')){
function rentPriceREM($bid,$rent_from,$rent_until,$special_price,
$comment_price,$currency_spacial_price){
global $database, $realestatemanager_configuration;
$rent_from_transf = data_transform_rem($rent_from);
$rent_until_transf = data_transform_rem($rent_until);
if($bid==''){
$rentTerm = array();
createRentTable($rentTerm, 'Please save or apply this item first','error');
return;
}
$query = "SELECT * FROM #__rem_rent_sal where fk_houseid = " . $bid;
$database->setQuery($query);
$rentTerm = $database->loadObjectList();
if($special_price==''){
createRentTable($rentTerm, 'You need fill Price','error');
}
if($rent_from==''){
createRentTable($rentTerm, 'You need fill Check In','error');
}
if($rent_until==''){
createRentTable($rentTerm, 'You need fill Check Out','error');
}
if($rent_from_transf >$rent_until_transf){
createRentTable($rentTerm, 'Incorrect Check Out','error');
}
foreach ($rentTerm as $oneTerm){
$returnMessage = checkRentDayNightREM (($oneTerm->price_from),($oneTerm->price_to),
$rent_from_transf, $rent_until_transf, $realestatemanager_configuration);
if(strlen($returnMessage) > 0){
createRentTable($rentTerm, $returnMessage, 'error');
}
}
$sql = "INSERT INTO #__rem_rent_sal (fk_houseid, price_from, price_to,
special_price, priceunit, comment_price) VALUES (" . $bid . ", '" .
$rent_from_transf . "', '" . $rent_until_transf . "', '" .
$special_price . "','" . $currency_spacial_price . "','" .
$comment_price . "')";
$database->setQuery($sql);
$database->query();
$query = "SELECT * FROM #__rem_rent_sal where fk_houseid = " . $bid;
$database->setQuery($query);
$rentTerm = $database->loadObjectList();
createRentTable($rentTerm, 'Add special price on data: from "'.
$rent_from.'" to "'.$rent_until.'"','');
}
}
if(!function_exists('calculatePriceREM')){
function calculatePriceREM ($hid,$rent_from,$rent_until,$realestatemanager_configuration,$database,$week){
$week = intval($week);
$date_from = $rent_from;
$date_until = $rent_until;
$rent_from = data_transform_rem($rent_from);
$rent_until = data_transform_rem($rent_until);
if($rent_from >$rent_until){
echo '0';exit;
}
if($realestatemanager_configuration['special_price']['show']){
$query = "SELECT * FROM #__rem_rent_sal WHERE fk_houseid = ".$hid .
" AND (price_from <= ('" .$rent_until. "') AND price_to >= ('" .$rent_from. "'))";
}else{
$query = "SELECT * FROM #__rem_rent_sal WHERE fk_houseid = ".$hid .
" AND (price_from < ('" .$rent_until. "') AND price_to > ('" .$rent_from. "'))";
}
$database->setQuery($query);
$data_for_price = $database->loadObjectList();
$zapros = "SELECT price, priceunit FROM #__rem_houses WHERE id=" . $hid . ";";
$database->setQuery($zapros);
$item_rem = $database->loadObjectList();
$rent_from_ms = date_to_data_ms($rent_from);
$rent_to_ms = date_to_data_ms($rent_until);
if($realestatemanager_configuration['special_price']['show']){
$rent_to_ms = $rent_to_ms + (60*60*24);
}
$count_day = (($rent_to_ms - $rent_from_ms)/60/60/24);
$count_day = round($count_day);
$array_day_between_to_from[0]=$rent_from;
for($i = 1; $i < $count_day; $i++){
$array_day_between_to_from[]=date('Y-m-d',$rent_from_ms + (60*60*24)*($i));
}
$count_day_spashal_price = 0;
$comment_rent_price = '';
$count_spashal_price = 0;
foreach ($data_for_price as $one_period){
$from = $one_period->price_from;
$to = $one_period->price_to;
for ($day = 0; $day < $count_day; $day++){
$currentday = ($array_day_between_to_from[$day]);
if(isset($realestatemanager_configuration)
&& $realestatemanager_configuration['special_price']['show']){
if (($currentday >= $from) && ($currentday <= $to)){
$count_day_spashal_price++;
$count_spashal_price += $one_period->special_price;
}
}else{
if (($currentday >= $from) && ($currentday < $to)){
$count_day_spashal_price++;
$count_spashal_price += $one_period->special_price;
}
}
}
}
$count_day_not_sp_price = $count_day - $count_day_spashal_price;
$sum_price_not_sp_price = $count_day_not_sp_price * $item_rem[0]->price;
$sum_price = $sum_price_not_sp_price + $count_spashal_price;
if ($week == 1)
{
$sum_price = $sum_price/6;
}
elseif ($week == 2)
{
$sum_price = 2*$sum_price/13;
}
else {
$sum_price = 3*$sum_price/20;
}
//modification par Skorweb
$returnArr[0]=$sum_price;
$returnArr[1]=$item_rem[0]->priceunit;
$returnArr[2]=$comment_rent_price;
return $returnArr;
}
}
if(!function_exists('getCountHouseForSingleUserREM')){
function getCountHouseForSingleUserREM($my,$database,$realestatemanager_configuration){
$user_group = userGID_REM($my->id);
$user_group_mas = explode(',', $user_group);
$max_count_house = 0;
foreach ($user_group_mas as $value) {
$count_house_for_single_group =
$realestatemanager_configuration['user_manager_rem'][$value]['count_homes'];
if($count_house_for_single_group>$max_count_house){
$max_count_house = $count_house_for_single_group;
}
}
$count_house_for_single_group = $max_count_house;
$database->setQuery("SELECT COUNT('houseid') as `count_homes` " .
"FROM #__rem_houses WHERE owner_id= '" . $my->id. "'AND published='1'" );
$house_single_user = $database->loadObject();
$count_house_single_user = $house_single_user->count_homes;
$returnarray = array();
$returnarray[0] = $count_house_single_user;
$returnarray[1] = $count_house_for_single_group;
return $returnarray;
}
}
if(!function_exists('getHTMLPayPalRM')){
function getHTMLPayPalRM($realestate,$plugin_name_select){
global $database;
if(!getPublicPlugin()){
echo "<div class='alert alert-error'>" . _REALESTATE_MANAGER_RENT_INSTALL_PAYPAL . "</div>";
}else{
$dispatcher = JDispatcher::getInstance();
$plugin = JPluginHelper::importPlugin( 'payment',$plugin_name_select);
$query = "SELECT profile_value FROM #__user_profiles "
."\n WHERE profile_key = 'profile.paypal_email' AND user_id = ".$realestate->owner_id;
$database->setQuery($query);
$paypal_email = $database->loadResult();
$data = array('vtitle' => $realestate->htitle, 'price' => $realestate->price, 'currency_code' => $realestate->priceunit,'owner_paypal_email' => $paypal_email);
$html = $dispatcher->trigger('getHTMLPayPal', array($data));
echo $html[0];
}
}
}
if(!function_exists('getPublicPlugin')){
function getPublicPlugin(){
$db = JFactory::getDBO();
$condtion = array(0 => '\'payment\'');
$condtionatype = join(',',$condtion);
if(JVERSION >= '1.6.0')
{
$query = "SELECT extension_id as id,name,element,enabled as published
FROM #__extensions
WHERE folder in ($condtionatype) AND enabled=1";
}
else
{
$query = "SELECT id,name,element,published
FROM #__plugins
WHERE folder in ($condtionatype) AND published=1";
}
$db->setQuery($query);
$gatewayplugin = $db->loadobjectList();
$retr = count($gatewayplugin);
if($retr>0){
$ret_string = "";
for($i=0;$i<$retr;$i++){
$ret_string .= "<option value='".$gatewayplugin[$i]->name."'>"
.$gatewayplugin[$i]->name."</option>";
}
return $ret_string;
}
else{
return false;
}
}
}
if(!function_exists('saveAssociateCayegoriesREM')){
function saveAssociateCayegoriesREM($post, $database){
$currentId = $post['id'];
if($currentId){
$i = 1;
$assocArray = array();
$assocCategoryId = array();
while(isset($post['associate_category'.$i])){
$langAssoc = $post['associate_category_lang'.$i];
$valAssoc = $post['associate_category'.$i];
$assocArray[$langAssoc] = $valAssoc;
if($valAssoc){
$assocCategoryId[] = $valAssoc;
}
$i++;
}
$currentId = $post['id'];
$currentLang = $post['language'];
$assocArray[$currentLang] = $currentId;
$assocStr = serialize($assocArray);
$query = "select `associate_category` from #__rem_main_categories where `id` = ".$currentId."";
$database->setQuery($query);
$oldAssociate = $database->loadResult();
$oldAssociateArray = unserialize($oldAssociate);
if($oldAssociateArray){
foreach ($oldAssociateArray as $key => $value) {
if($value && !isset($assocCategoryId[$value])){
$assocCategoryId[] = $value;
}
}
}
if(!isset($assocCategoryId[$currentId])){
$assocCategoryId[] = $currentId;
}
$idToChange = implode(',' , $assocCategoryId);
if(count($idToChange) && !empty($idToChange)){
$query = "UPDATE #__rem_main_categories SET `associate_category`='"
.$assocStr."' where `id` in (".$idToChange.")";
$database->setQuery($query);
$database->query();
}
}
}
}
if(!function_exists('getAssociateHousesLang')){
function getAssociateHousesLang($hoseIds){
global $database;
$query = "select associate_house from #__rem_houses where id = ".$hoseIds.
" and associate_house is not null";
$database->setQuery($query);
$houseAssociateHouse = $database->loadResult();
if (!empty($houseAssociateHouse)){
$houseLangIds = unserialize($houseAssociateHouse);
return $houseLangIds;
}
}
}
if(!function_exists('getAssociateHouses')){
function getAssociateHouses($hoseIds){
global $database;
$one = array();
$query = "select associate_house from #__rem_houses where id = ".$hoseIds.
" and associate_house is not null";
$database->setQuery($query);
$houseAssociateHouse = $database->loadResult();
if (!empty($houseAssociateHouse)){
$hoseIds = unserialize($houseAssociateHouse);
foreach($hoseIds as $oneHouse){
if($oneHouse != 0){
$one[] = $oneHouse;
}
}
$bids = implode(',', $one);
return $bids;
}
}
}
if(!function_exists('getAssociateDiff')){
function getAssociateDiff($assocArray1,$assocArray2){
global $database;
$diff_ids = array();
$diff = array_diff($assocArray1,$assocArray2);
foreach($diff as $key => $value){
if($value != 0){
$diff_ids[] = $value;
}
}
return $diff_ids ;
}
}
if(!function_exists('getAssociateOld')){
function getAssociateOld(){
global $database;
$id_check = JRequest::getVar('id', "");
$query = "select `associate_house` from #__rem_houses where `id` = ".$id_check."";
$database->setQuery($query);
$oldAssociate = $database->loadResult();
$oldAssoc_func = unserialize($oldAssociate);
return $oldAssoc_func;
}
}
if(!function_exists('ClearAssociateDiff')){
function ClearAssociateDiff(){
global $database;
$old_ids_assoc=array();
$new_ids_assoc=array();
$id_check = JRequest::getVar('id', "");
$language_post = JRequest::getVar('language', "");
$oldAssociateArray = getAssociateOld();
$i = 1;
$assocArray = array();
while(count(JRequest::getVar("associate_house".$i))){
$langAssoc = JRequest::getVar("associate_house_lang".$i);
$valAssoc = JRequest::getVar("language_associate_house".$i);
$assocArray[$langAssoc] = $valAssoc;
$i++;
}
$assocArray[$language_post] = $id_check;
if(!empty($oldAssociateArray) && !empty($assocArray))
$old_ids_assoc = getAssociateDiff($oldAssociateArray,$assocArray);
if(count($old_ids_assoc)>0)
{
foreach($old_ids_assoc as $key => $value) {
$diff_assoc2 = getAssociateHouses($value);
if(!empty($diff_assoc2)){
$ids_assoc_diff2 = explode(',', $diff_assoc2);
foreach ($ids_assoc_diff2 as $key2 => $value2){
if(!in_array($value2,$old_ids_assoc)){
$assoc_lang = getAssociateHousesLang($value);
foreach ($assoc_lang as $key3 => $value3){
if($value3 == $value2){
$assoc_lang[$key3] = 0;
}
}
$houseLangIds = serialize($assoc_lang);
$query = "UPDATE #__rem_houses SET `associate_house`='".$houseLangIds.
"' where `id` = ".$value."";
$database->setQuery($query);
$database->query();
}
}
}
}
}
if(!empty($oldAssociateArray) && !empty($assocArray))
$new_ids_assoc = getAssociateDiff($assocArray,$oldAssociateArray);
if(count($new_ids_assoc)>0)
{
foreach($new_ids_assoc as $key => $value) {
$diff_assoc2 = getAssociateHouses($value);
if(!empty($diff_assoc2)){
$ids_assoc_diff2 = explode(',', $diff_assoc2);
foreach ($ids_assoc_diff2 as $key2 => $value2){
if($value2 == $value || $value2 == 0 ) continue;
$assoc_lang = getAssociateHousesLang($value2);
foreach ($assoc_lang as $key3 => $value3){
if($value3 == $value){
$assoc_lang[$key3] = 0;
}
}
$houseLangIds = serialize($assoc_lang);
$query = "UPDATE #__rem_houses SET `associate_house`='".$houseLangIds.
"' where `id` = ".$value2."";
$database->setQuery($query);
$database->query();
}
}
}
}
}
}
if(!function_exists('edit_house_associate')){
function edit_house_associate($house,$call_from){
global $my, $database;
$associateArray = array();
$userid = $my->id;
$query = "SELECT lang_code FROM `#__languages` ";
$database->setQuery($query);
$allLanguages = $database->loadColumn();
//bch
if($call_from=='backend')
{
$query = "SELECT id,language,htitle FROM `#__rem_houses`";
}
else
{
$query = "SELECT id,language,htitle FROM `#__rem_houses` WHERE owner_id = " . $userid . "";
}
$database->setQuery($query);
$allhouse = $database->loadObjectlist();
$query = "select associate_house from #__rem_houses where id =".$house->id;
$database->setQuery($query);
$houseAssociateHouse = $database->loadResult();
if(!empty($houseAssociateHouse)){
$houseAssociateHouse = unserialize($houseAssociateHouse);
}else{
$houseAssociateHouse = array();
}
$i=0;
foreach ($allLanguages as $oneLang) {
$i++;
$associate_house = array();
$associate_house[] = mosHtml::makeOption(0, 'select');
foreach($allhouse as $oneHouse){
if($oneLang == $oneHouse->language && $oneHouse->id != $house->id){
$associate_house[] = mosHtml::makeOption(($oneHouse->id), $oneHouse->htitle);
}
}
if($house->language != $oneLang){
if(isset($houseAssociateHouse[$oneLang]) &&
$houseAssociateHouse[$oneLang] !== $house->id ){
$associateArray[$oneLang]['assocId'] = $houseAssociateHouse[$oneLang];
}else{
$associateArray[$oneLang]['assocId'] = 0;
}
$associate_house_list = mosHTML :: selectList($associate_house,
'language_associate_house'.$i,
'class="inputbox" size="1"', 'value', 'text',
$associateArray[$oneLang]['assocId']);
}else{
$associate_house_list = null;
}
$associateArray[$oneLang]['list'] = $associate_house_list;
if(isset($houseAssociateHouse[$oneLang]) &&
$houseAssociateHouse[$oneLang] !== $house->id ){
$associateArray[$oneLang]['assocId'] = $houseAssociateHouse[$oneLang];
}else{
$associateArray[$oneLang]['assocId'] = 0;
}
}
return $associateArray;
}
}
if(!function_exists('save_house_associate')){
function save_house_associate(){
global $database;
$id_check = JRequest::getVar('id', "");
$id_true = JRequest::getVar('idtrue', "");
$language_post = JRequest::getVar('language', "");
if($id_check){
if(empty($id_true)){
//----------get new values (what house we choose for chaque language) --------------------------//
$i = 1;
$assocArray = array();
$assocHouseId = array();
while(count(JRequest::getVar("associate_house".$i))){
$langAssoc = JRequest::getVar("associate_house_lang".$i, '');
$valAssoc = JRequest::getVar("language_associate_house".$i,'');
if($valAssoc == '' ) {
$i++;
continue;
}
$assocArray[$langAssoc] = $valAssoc;
if($valAssoc){
$assocHouseId[] = $valAssoc; //----Array of new house_ids
}
$i++;
}
if(count($assocArray) > 0 ) {
$assocArray[$language_post] = $id_check;
$assocStr = serialize($assocArray);
//-----------slect associate with old values------------------------------------------//
$oldAssociateArray = getAssociateOld();
//----------------------------------------------------------------//
if(!isset($assocHouseId[$id_check])){
$assocHouseId[] = $id_check;
}
if($assocArray && $oldAssociateArray){
ksort($assocArray);
ksort($oldAssociateArray);
}
if($assocArray !== $oldAssociateArray){ //-----------compare old and new values--
//---------set null for houses that are not more in associates----------------//
ClearAssociateDiff();
//---------set new associates for houses that are choosed----------------//
//--ids of new houses where we set new values for column associate_house
$idToChange = implode(',' , $assocHouseId);
if(count($idToChange) && !empty($idToChange)){
$query = "select * from #__rem_rent where `fk_houseid` in (".$idToChange.
") and `rent_return` is NULL";
$database->setQuery($query);
$CheckAssociate = $database->loadObjectList();
if(!empty($CheckAssociate))
{
echo "<script> alert('"._REALESTATE_MANAGER_MUST_RETURN_HOUSES_FROM_RENT
."'); window.history.go(-1); </script>";
exit;
}
$query = "UPDATE #__rem_houses SET `associate_house`='".$assocStr.
"' where `id` in (".$idToChange.")";
$database->setQuery($query);
$database->query();
}else{
$query = "UPDATE #__rem_houses SET `associate_house`= null where `id` = ".$id_check."";
$database->setQuery($query);
$database->query();
}
}
}
}
}
}
}
if(!function_exists('available_dates')){
function available_dates($house_id){
global $database,$realestatemanager_configuration;
$date_NA='';
$query = "SELECT rent_from, rent_until FROM #__rem_rent WHERE fk_houseid='".$house_id.
"' AND rent_return is null";
$database->setQuery($query);
$calenDate = $database->loadObjectList();
// create a massiv of all dates when houses are in rent and then is used for
// make dates unavailable in calendar for rent
foreach($calenDate as $calenDate){
$not_av_from = $calenDate->rent_from;
$not_av_until = $calenDate->rent_until;
$not_av_from_begin = new DateTime( $not_av_from);
$not_av_until_end = new DateTime( $not_av_until);
if($realestatemanager_configuration['special_price']['show']){
$not_av_until_end = $not_av_until_end->modify( '+1 day' );
}
// else{
// $not_av_from_begin = $not_av_from_begin->modify( '+1 day' );
// }
$interval = new DateInterval('P1D');
$daterange = new DatePeriod($not_av_from_begin, $interval, $not_av_until_end);
foreach($daterange as $datess){
$date_NA[] = $datess->format("Y-m-d");
$date_NA[] = $datess->format("d-m-Y");
}
}
return $date_NA;
}
}
////////////////////////////STORE video/track functions START\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
if (!function_exists('storeTrack')) {
function storeTrack(&$house) {
global $realestatemanager_configuration, $mosConfig_absolute_path;
for ($i = 1;isset($_FILES['new_upload_track' . $i])
|| array_key_exists('new_upload_track_url' . $i, $_POST);$i++) {
$track_name = '';
if (isset($_FILES['new_upload_track' . $i]) && $_FILES['new_upload_track' . $i]['name'] != "") {
//storing e-Document
$track = JRequest::getVar('new_upload_track' . $i, '', 'files');
$ext = pathinfo($track['name'], PATHINFO_EXTENSION);
$allowed_exts = explode(",", $realestatemanager_configuration['allowed_exts_track']);
$ext = strtolower($ext);
if (!in_array($ext, $allowed_exts)) {
echo "<script> alert(' File ext. not allowed to upload! - " . $ext .
"'); window.history.go(-1); </script>\n";
exit();
}
$code = guid();
$track_name = $code . '_' . filter($track['name']);
if (intval($track['error']) > 0 && intval($track['error']) < 4) {
echo "<script> alert('" . _REALESTATE_MANAGER_LABEL_TRACK_UPLOAD_ERROR . " - " .
$track_name . "'); window.history.go(-1); </script>\n";
exit();
} else if (intval($track['error']) != 4) {
$track_new = $mosConfig_absolute_path . $realestatemanager_configuration['tracks']['location'] . $track_name;
if (!move_uploaded_file($track['tmp_name'], $track_new)) {
echo "<script> alert('" . _REALESTATE_MANAGER_LABEL_TRACK_UPLOAD_ERROR . " - " .
$track_name . "'); window.history.go(-1); </script>\n";
exit();
}
}
}
if (array_key_exists('new_upload_track_kind' . $i, $_POST)
&& $_POST['new_upload_track_kind' . $i] != "") {
$uploadTrackKind = JRequest::getVar('new_upload_track_kind' . $i, '', 'post');
$uploadTrackKind = strip_tags(trim($uploadTrackKind));
}
if (array_key_exists('new_upload_track_scrlang' . $i, $_POST)
&& $_POST['new_upload_track_scrlang' . $i] != "") {
$uploadTrackScrlang = JRequest::getVar('new_upload_track_scrlang' . $i, '', 'post');
$uploadTrackScrlang = strip_tags(trim($uploadTrackScrlang));
}
if (array_key_exists('new_upload_track_label' . $i, $_POST)
&& $_POST['new_upload_track_label' . $i] != "") {
$uploadTrackLabel = JRequest::getVar('new_upload_track_label' . $i, '', 'post');
$uploadTrackLabel = strip_tags(trim($uploadTrackLabel));
}
if (array_key_exists('new_upload_track_url' . $i, $_POST) && $_POST['new_upload_track_url' . $i] != "") {
$uploadTrackURL = JRequest::getVar('new_upload_track_url' . $i, '', 'post');
$uploadTrackURL = strip_tags(trim($uploadTrackURL));
if (empty($track_name) && !empty($uploadTrackURL))
saveTracks($house->id, $uploadTrackURL, $uploadTrackKind, $uploadTrackScrlang, $uploadTrackLabel);
}
if (!empty($track_name))
saveTracks($house->id, $track_name, $uploadTrackKind, $uploadTrackScrlang, $uploadTrackLabel);
}
}
}
if (!function_exists('checkMimeType')) {
function checkMimeType($ext) {
global $database;
$database->setQuery("SELECT mime_type FROM #__rem_mime_types WHERE mime_ext=".$database->quote($ext));
$type = $database->loadResult();
if(!$type)
$type = 'unknown';
return $type;
}
}
if (!function_exists('filter')) {
function filter($value) {
$value = str_replace(array("/", "|", "\\", "?", ":", ";", "*", "#", "%", "$", "+", "=", ";", " "), "_", $value);
return $value;
}
}
if (!function_exists('guid')) {
function guid() {
if (function_exists('com_create_guid')) {
return com_create_guid();
} else {
mt_srand((double)microtime() * 10000); //optional for php 4.2.0 and up.
$charid = strtoupper(md5(uniqid(rand(), true)));
$hyphen = chr(45); // "-"
$uuid = //chr(123)// "{"
substr($charid, 0, 8) . $hyphen . substr($charid, 8, 4) . $hyphen . substr($charid, 12, 4) . $hyphen . substr($charid, 16, 4) . $hyphen . substr($charid, 20, 12);
//.chr(125);// "}"
return $uuid;
}
}
}
jimport( 'joomla.filesystem.file' );
if(!function_exists('rem_createImage')){
function rem_createImage($imgSrc, $imgDest, $width, $height, $crop = true, $quality = 90) {
if (JFile::exists($imgDest)) {
$info = getimagesize($imgDest, $imageinfo);
if (($info[0] == $width) && ($info[1] == $height)) {
return;
}
}
if (JFile::exists($imgSrc)) {
$info = getimagesize($imgSrc, $imageinfo);
$sWidth = $info[0];
$sHeight = $info[1];
rem_resize_img($imgSrc, $imgDest, $width, $height, $crop, $quality);
}
}
}
if(!function_exists('rem_resize_img')){
function rem_resize_img($imgSrc, $imgDest, $tmp_width, $tmp_height, $crop = true, $quality = 90) {
global $mosConfig_absolute_path;
$info = getimagesize($imgSrc, $imageinfo);
$sWidth = $info[0];
$sHeight = $info[1];
if($sWidth == 0 || $tmp_width == 0 ) {
$logPath = $mosConfig_absolute_path . "/administrator/components/com_realestatemanager/my_log.log";
file_put_contents($logPath, " rem_resize_img zero ".$imgSrc."::".$sWidth ."::" . $tmp_width."\n", FILE_APPEND );
$imgSrc = $mosConfig_absolute_path."/components/com_realestatemanager/photos/"."no-img_eng_big.gif";
$info = getimagesize($imgSrc, $imageinfo);
$sWidth = $info[0];
$sHeight = $info[1];
}
if ($sHeight / $sWidth > $tmp_height / $tmp_width) {
$width = $sWidth;
$height = round(($tmp_height * $sWidth) / $tmp_width);
$sx = 0;
$sy = round(($sHeight - $height) / 3);
}
else {
$height = $sHeight;
$width = round(($sHeight * $tmp_width) / $tmp_height);
$sx = round(($sWidth - $width) / 2);
$sy = 0;
}
if (!$crop) {
$sx = 0;
$sy = 0;
$width = $sWidth;
$height = $sHeight;
}
$ext = str_replace('image/', '', $info['mime']);
$imageCreateFunc = rem_getImageCreateFunction($ext);
$imageSaveFunc = rem_getImageSaveFunction($ext);
$sImage = $imageCreateFunc($imgSrc);
$dImage = imagecreatetruecolor($tmp_width, $tmp_height);
// Make transparent
if ($ext == 'png') {
imagealphablending($dImage, false);
imagesavealpha($dImage,true);
$transparent = imagecolorallocatealpha($dImage, 255, 255, 255, 127);
imagefilledrectangle($dImage, 0, 0, $tmp_width, $tmp_height, $transparent);
}
imagecopyresampled($dImage, $sImage, 0, 0, $sx, $sy, $tmp_width, $tmp_height, $width, $height);
if ($ext == 'png') {
$imageSaveFunc($dImage, $imgDest, 9);
}
else if ($ext == 'gif') {
$imageSaveFunc($dImage, $imgDest, $quality);
}
else {
$imageSaveFunc($dImage, $imgDest, $quality);
}
}
}
if(!function_exists('rem_getImageCreateFunction')){
function rem_getImageCreateFunction($type) {
switch ($type) {
case 'jpeg':
case 'jpg':
$imageCreateFunc = 'imagecreatefromjpeg';
break;
case 'png':
$imageCreateFunc = 'imagecreatefrompng';
break;
case 'bmp':
$imageCreateFunc = 'imagecreatefrombmp';
break;
case 'gif':
$imageCreateFunc = 'imagecreatefromgif';
break;
case 'vnd.wap.wbmp':
$imageCreateFunc = 'imagecreatefromwbmp';
break;
case 'xbm':
$imageCreateFunc = 'imagecreatefromxbm';
break;
default:
$imageCreateFunc = 'imagecreatefromjpeg';
}
return $imageCreateFunc;
}
}
if(!function_exists('rem_getImageSaveFunction')){
function rem_getImageSaveFunction($type) {
switch ($type) {
case 'jpeg':
$imageSaveFunc = 'imagejpeg';
break;
case 'png':
$imageSaveFunc = 'imagepng';
break;
case 'bmp':
$imageSaveFunc = 'imagebmp';
break;
case 'gif':
$imageSaveFunc = 'imagegif';
break;
case 'vnd.wap.wbmp':
$imageSaveFunc = 'imagewbmp';
break;
case 'xbm':
$imageSaveFunc = 'imagexbm';
break;
default:
$imageSaveFunc = 'imagejpeg';
}
return $imageSaveFunc;
}
}
/**
* Saves the record on an edit form submit
* @param database A database connector object
*/
if (!function_exists('rem_picture_thumbnail')) {
function rem_picture_thumbnail($file, $high_original, $width_original) {
global $mosConfig_absolute_path, $realestatemanager_configuration;
$params3 = $realestatemanager_configuration['thumb_param']['show'];
$uploaddir = $mosConfig_absolute_path . '/components/com_realestatemanager/photos/';
//file name and extention
if(!file_exists($mosConfig_absolute_path .
'/components/com_realestatemanager/photos/' . $file))
$file = 'no-img_eng_big.gif';
$file_inf = pathinfo($file);
$file_type = '.' . $file_inf['extension'];
$file_name = basename($file, $file_type);
$index = '';
// Setting the resize parameters
list($width, $height) = getimagesize($mosConfig_absolute_path .
'/components/com_realestatemanager/photos/' . $file);
$size = "_" . $high_original . "_" . $width_original;
if (file_exists($mosConfig_absolute_path . '/components/com_realestatemanager/photos/'
. $file_name . $size . $index . $file_type)) {
return $file_name . $size . $index . $file_type;
} else {
if ($width < $height) {
if ($height > $high_original) {
$k = $height / $high_original;
} else if ($width > $width_original) {
$k = $width / $width_original;
}
else
$k = 1;
} else {
if ($width > $width_original) {
$k = $width / $width_original;
} else if ($height > $high_original) {
$k = $height / $high_original;
}
else
$k = 1;
}
$w_ = $width / $k;
$h_ = $height / $k;
}
if($params3 == 1){
$index = "_2_";
$CreateNewImage = rem_createImage($uploaddir.$file, $uploaddir.$file_name . $size
. $index . $file_type, $high_original, $width_original);
return $file_name . $size . $index . $file_type;
}
// Creating the Canvas
$tn = imagecreatetruecolor($w_, $h_);
$index = "_1_";
switch (strtolower($file_type)) {
case '.png':
$source = imagecreatefrompng($mosConfig_absolute_path .
'/components/com_realestatemanager/photos/' . $file);
$file = imagecopyresampled($tn, $source, 0, 0, 0, 0, $w_, $h_, $width, $height);
imagepng($tn, $mosConfig_absolute_path .
'/components/com_realestatemanager/photos/' . $file_name . $size . $index . $file_type);
break;
case '.jpg':
$source = imagecreatefromjpeg($mosConfig_absolute_path .
'/components/com_realestatemanager/photos/' . $file);
$file = imagecopyresampled($tn, $source, 0, 0, 0, 0, $w_, $h_, $width, $height);
imagejpeg($tn, $mosConfig_absolute_path .
'/components/com_realestatemanager/photos/' . $file_name . $size . $index . $file_type);
break;
case '.jpeg':
$source = imagecreatefromjpeg($mosConfig_absolute_path .
'/components/com_realestatemanager/photos/' . $file);
$file = imagecopyresampled($tn, $source, 0, 0, 0, 0, $w_, $h_, $width, $height);
imagejpeg($tn, $mosConfig_absolute_path .
'/components/com_realestatemanager/photos/' . $file_name . $size . $index . $file_type);
break;
case '.gif':
$source = imagecreatefromgif($mosConfig_absolute_path .
'/components/com_realestatemanager/photos/' . $file);
$file = imagecopyresampled($tn, $source, 0, 0, 0, 0, $w_, $h_, $width, $height);
imagegif($tn, $mosConfig_absolute_path .
'/components/com_realestatemanager/photos/' . $file_name . $size . $index . $file_type);
break;
default:
echo 'not support';
return;
}
return $file_name . $size . $index . $file_type;
}
}
if (!function_exists('storeVideo')) {
function storeVideo(&$house) {
global $realestatemanager_configuration, $mosConfig_absolute_path;
for ($i = 1;isset($_FILES['new_upload_video' . $i])
|| array_key_exists('new_upload_video_url' . $i, $_POST)
|| array_key_exists('new_upload_video_youtube_code' . $i, $_POST);$i++) {
$video_name = '';
if (isset($_FILES['new_upload_video' . $i]) && $_FILES['new_upload_video' . $i]['name'] != "") {
//storing e-Document
$video = JRequest::getVar('new_upload_video' . $i, '', 'files');
$ext = pathinfo($video['name'], PATHINFO_EXTENSION);
$allowed_exts = explode(",", $realestatemanager_configuration['allowed_exts_video']);
$ext = strtolower($ext);
if (!in_array($ext, $allowed_exts)) {
echo "<script> alert(' File ext. not allowed to upload! - " . $ext.
"'); window.history.go(-1); </script>\n";
exit();
}
$type = checkMimeType($ext);
if (stripos($type, $video['type'])===false) {
echo "<script> alert(' File ext. not allowed to upload! - " . $ext.
"'); window.history.go(-1); </script>\n";
exit();
}
$code = guid();
$video_name = $code . '_' . filter($video['name']);
if (intval($video['error']) > 0 && intval($video['error']) < 4) {
echo "<script> alert('" . _REALESTATE_MANAGER_LABEL_VIDEO_UPLOAD_ERROR . " - " .
$video_name . "'); window.history.go(-1); </script>\n";
exit();
} else if (intval($video['error']) != 4) {
$video_new = $mosConfig_absolute_path . $realestatemanager_configuration['videos']['location'] . $video_name;
if (!move_uploaded_file($video['tmp_name'], $video_new)) {
echo "<script> alert('" . _REALESTATE_MANAGER_LABEL_VIDEO_UPLOAD_ERROR . " - " .
$video_name . "'); window.history.go(-1); </script>\n";
exit();
}
saveVideos($video_name, $house->id, $type);
}
}
if (array_key_exists('new_upload_video_url' . $i, $_POST) && $_POST['new_upload_video_url' . $i] != "") {
$uploadVideoURL = JRequest::getVar('new_upload_video_url' . $i, '', 'post');
$uploadVideoURL = strip_tags(trim($uploadVideoURL));
$end = explode(".", $uploadVideoURL);
$ext = end($end);
$type = checkMimeType($ext);
if(empty($video_name) && !empty($uploadVideoURL))
saveVideos($uploadVideoURL, $house->id, $type);
}
if (array_key_exists('new_upload_video_youtube_code' . $i, $_POST)
&& $_POST['new_upload_video_youtube_code' . $i] != "") {
$uploadVideoYoutubeCode = JRequest::getVar('new_upload_video_youtube_code' . $i, '', 'post');
$uploadVideoYoutubeCode = strip_tags(trim($uploadVideoYoutubeCode));
saveYouTubeCode($uploadVideoYoutubeCode, $house->id);
}
}
}
}
if (!function_exists('saveTracks')) {
function saveTracks($h_id, $src, $uploadTrackKind, $uploadTrackScrlang, $uploadTrackLabel) {
global $database,$realestatemanager_configuration, $mosConfig_absolute_path;
if ($src != "" && !strstr($src, "http")) {
$query = "INSERT INTO #__rem_track_source (fk_house_id,src,kind,scrlang,label)".
"\n VALUE ($h_id,
'" . $realestatemanager_configuration['tracks']['location'].$src . "',
'" . $uploadTrackKind . "',
'" . $uploadTrackScrlang . "',
'" . $uploadTrackLabel . "')";
}else{
$query ="INSERT INTO #__rem_track_source (fk_house_id,src,kind,scrlang,label)".
"\n VALUE ($h_id,
'" . $src."',
'" . $uploadTrackKind . "',
'" . $uploadTrackScrlang . "',
'" . $uploadTrackLabel . "')";
}
$database->setQuery($query);
$database->query();
}
}
if (!function_exists('saveVideos')) {
function saveVideos($src, $h_id, $type) {
global $database,$realestatemanager_configuration, $mosConfig_absolute_path;
if ($src != "" && strstr($src, "http")) {
$query = "INSERT INTO #__rem_video_source(fk_house_id, src, type)".
"\n VALUE($h_id,'" . $src . "', '" . $type . "')";
}else{
$query = "INSERT INTO #__rem_video_source(fk_house_id,src,type)".
"\n VALUE($h_id,
'".$realestatemanager_configuration['videos']['location'].$src."',
'".$type."')";
}
$database->setQuery($query);
$database->query();
}
}
if (!function_exists('saveYouTubeCode')) {
function saveYouTubeCode($youtube_code, $h_id) {
global $database;
$database->setQuery("SELECT id FROM #__rem_video_source
WHERE youtube != ''
AND fk_house_id = $h_id");
$database->query();
$youtubeId = $database->LoadResult();
if ($youtube_code != '' && !empty($youtubeId)) {
$query = "UPDATE #__rem_video_source".
"\n SET youtube = '" . $youtube_code . "'".
"\n WHERE id = $youtubeId";
} else {
$query = "INSERT INTO #__rem_video_source (fk_house_id,youtube)".
"\n VALUE($h_id,'" . $youtube_code . "')";
}
$database->setQuery($query);
$database->query();
}
}
////////////////////////////STORE video/track functions END\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
///////////////////////////DELETE video/track functions START\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
if (!function_exists('deleteTracks')) {
function deleteTracks($h_id) {
global $database, $mosConfig_absolute_path, $mosConfig_live_site, $realestatemanager_configuration;
$database->setQuery("SELECT id FROM #__rem_track_source where fk_house_id = $h_id;");
$tdiles_id = $database->loadColumn();
$deleteTr_id = array();
foreach($tdiles_id as $key => $value) {
if (isset($_POST['track_option_del' . $value])) {
array_push($deleteTr_id, JRequest::getVar('track_option_del' . $value, '', 'post'));
}
}
if ($deleteTr_id) {
$del_tid = implode(',', $deleteTr_id);
$sql = "SELECT src FROM #__rem_track_source WHERE id IN (" .$del_tid . ")";
$database->setQuery($sql);
$tracks = $database->loadColumn();
if ($tracks) {
foreach($tracks as $name) {
if (substr($name, 0, 4) != "http") unlink($mosConfig_absolute_path . $name);
}
}
$sql = "DELETE FROM #__rem_track_source WHERE (id IN (" . $del_tid . "))
AND (fk_house_id = $h_id)";
$database->setQuery($sql);
$database->query();
}
}
}
if (!function_exists('deleteVideos')) {
function deleteVideos($h_id) {
global $database, $mosConfig_absolute_path, $mosConfig_live_site, $realestatemanager_configuration;
$database->setQuery("SELECT id FROM #__rem_video_source where fk_house_id = $h_id;");
$vdiles_id = $database->loadColumn();
$deleteVid_id = array();
foreach($vdiles_id as $key => $value) {
if (isset($_POST['video_option_del' . $value])) {
array_push($deleteVid_id, JRequest::getVar('video_option_del' . $value, '', 'post'));
}
}
$database->setQuery("SELECT id FROM #__rem_video_source where fk_house_id = $h_id AND youtube IS NOT NULL;");
$youtubeid = $database->loadResult();
if (!empty($youtubeid)) {
if (isset($_POST['youtube_option_del' . $youtubeid])) {
$y_t_id = mosGetParam($_REQUEST, 'youtube_option_del' . $youtubeid, '');
$sql = "DELETE FROM #__rem_video_source
WHERE id = $y_t_id
AND fk_house_id=$h_id";
$database->setQuery($sql);
$database->query();
}
}
if ($deleteVid_id) {
$del_id = implode(',', $deleteVid_id);
$sql = "SELECT src FROM #__rem_video_source WHERE id IN (". $del_id . ")";
$database->setQuery($sql);
$videos = $database->loadColumn();
if ($videos) {
foreach($videos as $name) {
if (substr($name, 0, 4) != "http" && file_exists($mosConfig_absolute_path . $name))
unlink($mosConfig_absolute_path . $name);
}
}
$sql = "DELETE FROM #__rem_video_source
WHERE (id IN (" . $del_id . "))
AND (fk_house_id=$h_id)";
$database->setQuery($sql);
$database->query();
}
}
}
///////////////////////////DELETE video/track fucntions END\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
if(!function_exists('return_bytes')){
function return_bytes($val) {
$val = trim($val);
$last = strtolower($val[strlen($val)-1]);
switch($last) {
// Модификатор 'G' доступен, начиная с PHP 5.1.0
case 'g':
$val *= 1024;
case 'm':
$val *= 1024;
case 'k':
$val *= 1024;
}
return $val;
}
}
if(!function_exists('getAvilableRM')){
function getAvilableRM ($calenDate,$month,$year,$realestatemanager_configuration,$day){
global $flag3;
if(strlen($month) == 1){
$month = '0'.$month ;
}
if(strlen($day) == 1){
$day = '0'.$day ;
}
$toDay = $day+1;
if(strlen($toDay) == 1){
$toDay = '0'.$toDay ;
}
$cheackDataFrom = $year.'-'.$month.'-'.$day;
$cheackDataTo = $year.'-'.$month.'-'.$toDay;
foreach ($calenDate as $oneTerm){
$from=explode(' ',$oneTerm->rent_from);
$until=explode(' ',$oneTerm->rent_until);
if($cheackDataFrom >= $oneTerm->rent_until)continue;
$resultmsg = checkRentDayNightREM (($oneTerm->rent_from),($oneTerm->rent_until), $cheackDataFrom, $cheackDataTo, $realestatemanager_configuration);
if($cheackDataTo <= date('Y-m-d') && strlen($resultmsg) > 1){
if(!$realestatemanager_configuration['special_price']['show']
&& ($cheackDataFrom == $until[0] || $cheackDataFrom == $from[0] )){
if($flag3){
$flag3 = false;
return 'calendar_day_gone_not_avaible_night_end';
}else{
$flag3 = true;
return 'calendar_day_gone_not_avaible_night_start';
}
}
return 'calendar_day_gone_not_avaible';
}
if(strlen($resultmsg) > 1){
if(!$realestatemanager_configuration['special_price']['show']
&& ($cheackDataFrom == $until[0] || $cheackDataFrom == $from[0] )){
if($flag3){
$flag3 = false;
return 'calendar_not_available_night_end';
}else{
$flag3 = true;
return 'calendar_not_available_night_start';
}
}
return 'calendar_not_available';
}
if($cheackDataTo <= date('Y-m-d')){
return 'calendar_day_gone_avaible';
}
}
if(isset($cheackDataTo) && $cheackDataTo <= date('Y-m-d')){
return 'calendar_day_gone_avaible';
}
return 'calendar_available';
}
}
if(!function_exists('com_house_categoryTreeList')){
function com_house_categoryTreeList($id, $action, $is_new, &$options = array(), $catid='', $lang='') {
global $database;
if($lang){
$list = com_house_categoryArray($lang);
} else {
$list = com_house_categoryArray();
}
$cat = new mainRealEstateCategories($database);
$cat->load($id);
$this_treename = '';
$childs_ids = Array();
foreach ($list as $item) {
if ($item->id == $cat->id || array_key_exists($item->parent_id, $childs_ids))
$childs_ids[$item->id] = $item->id;
}
foreach ($list as $item) {
if ($this_treename) {
if ($item->id != $cat->id
&& strpos($item->treename, $this_treename) === false
&& array_key_exists($item->id, $childs_ids) === false) {
$options[] = mosHTML::makeOption($item->id, $item->treename);
}
} else {
if ($item->id != $cat->id) {
$options[] = mosHTML::makeOption($item->id, $item->treename);
} else {
$this_treename = "$item->treename/";
}
}
}
$parent = null;
$parent = mosHTML::selectList($options, 'catid', 'class="inputbox" size="1" style="width: 115px"', 'value', 'text', $catid);
return $parent;
}
}
if(!function_exists('com_house_categoryArray')){
function com_house_categoryArray($lang='') {
global $database, $my, $acl;
// get a list of the menu items
$query = "SELECT c.*, c.parent_id AS parent, c.params AS access"
. "\n FROM #__rem_main_categories c"
. "\n WHERE section='com_realestatemanager'"
. "\n AND published <> 0 ";
if($lang){
$query .= " AND ($lang)"
. "\n ORDER BY ordering";
} else {
$query .= " ORDER BY ordering";
}
$database->setQuery($query);
$items = $database->loadObjectList();
foreach ($items as $r => $cat_item) {
if (!checkAccess_REM($cat_item->access, 'NORECURSE', userGID_REM($my->id), $acl)) {
//if have not access then remove item from search
unset($items[$r]);
}
}
$items = array_values($items);
// establish the hierarchy of the menu
$children = array();
// first pass - collect children
foreach ($items as $v) {
$pt = $v->parent;
$list = @$children[$pt] ? $children[$pt] : array();
array_push($list, $v);
$children[$pt] = $list;
}
// second pass - get an indent list of the items
$array = mosTreeRecurseREM(0, '', array(), $children);
return $array;
}
}
if (!function_exists('checkJavaScriptIncludedRE')) {
function checkJavaScriptIncludedRE($name) {
$doc = JFactory::getDocument();
foreach($doc->_scripts as $script_path=>$value){
if(strpos( $script_path, $name ) !== false ) return true ;
}
return false;
}
}<file_sep><?php
if (!defined('_VALID_MOS') && !defined('_JEXEC'))
die('Direct Access to ' . basename(__FILE__) . ' is not allowed.');
defined("DS") OR define("DS", DIRECTORY_SEPARATOR);
/**
*
* @package RealEstateManager
* @copyright 2012 <NAME>-OrdaSoft(<EMAIL>); <NAME>(<EMAIL>)
* Homepage: http://www.ordasoft.com
* @version: 3.9 Pro
*
* */
$mosConfig_absolute_path = $GLOBALS['mosConfig_absolute_path'] = JPATH_SITE;
global $mosConfig_lang, $user_configuration; // for 1.6
$mainframe = JFactory::getApplication(); // for 1.6
$GLOBALS['mainframe'] = $mainframe;
if (get_magic_quotes_gpc()) {
function stripslashes_gpc(&$value) {
$value = stripslashes($value);
}
array_walk_recursive($_GET, 'stripslashes_gpc');
array_walk_recursive($_POST, 'stripslashes_gpc');
array_walk_recursive($_COOKIE, 'stripslashes_gpc');
array_walk_recursive($_REQUEST, 'stripslashes_gpc');
}
jimport('joomla.html.pagination');
require_once($mosConfig_absolute_path . "/components/com_realestatemanager/compat.joomla1.5.php");
if (version_compare(JVERSION, "3.0.0", "lt"))
include_once($mosConfig_absolute_path . '/libraries/joomla/application/pathway.php'); // for 1.6
include_once($mosConfig_absolute_path .
'/components/com_realestatemanager/realestatemanager.main.categories.class.php');
jimport('joomla.application.pathway');
jimport('joomla.html.pagination');
jimport('joomla.filesystem.folder');
$database = JFactory::getDBO();
require_once $mosConfig_absolute_path .
"/administrator/components/com_realestatemanager/language.php";
require_once($mosConfig_absolute_path .
"/components/com_realestatemanager/captcha.php");
/** load the html drawing class */
require_once ($mosConfig_absolute_path .
"/components/com_realestatemanager/realestatemanager.class.rent.php");
require_once ($mosConfig_absolute_path .
"/components/com_realestatemanager/realestatemanager.html.php"); // for 1.6
require_once ($mosConfig_absolute_path .
"/components/com_realestatemanager/realestatemanager.class.php"); // for 1.6
require_once ($mosConfig_absolute_path .
"/components/com_realestatemanager/realestatemanager.class.rent_request.php");
require_once ($mosConfig_absolute_path .
"/components/com_realestatemanager/realestatemanager.class.buying_request.php");
require_once ($mosConfig_absolute_path .
"/components/com_realestatemanager/realestatemanager.class.rent.php");
require_once ($mosConfig_absolute_path .
"/components/com_realestatemanager/realestatemanager.class.review.php");
require_once ($mosConfig_absolute_path .
"/administrator/components/com_realestatemanager/realestatemanager.class.others.php");
//added 2012_06_05 that's because it doesn't work with enabled plugin System-Legacy, so if it works, let it work :)
require_once($mosConfig_absolute_path .
"/components/com_realestatemanager/functions.php");
require_once($mosConfig_absolute_path .
"/components/com_realestatemanager/includes/menu.php");
require_once ($mosConfig_absolute_path .
"/administrator/components/com_realestatemanager/realestatemanager.class.impexp.php");
//added 2012_06_05 that's because it doesn't work with enabled plugin System-Legacy, so if it works, let it work :)
if (!array_key_exists('realestatemanager_configuration', $GLOBALS)) {
require_once ($mosConfig_absolute_path .
"/administrator/components/com_realestatemanager/realestatemanager.class.conf.php");
$GLOBALS['realestatemanager_configuration'] = $realestatemanager_configuration;
} else
global $realestatemanager_configuration;
if (!isset($option))
$GLOBALS['option'] = $option = mosGetParam($_REQUEST, 'option', 'com_realestatemanager');
else
$GLOBALS['option'] = $option;
if (isset($option) && $option == "com_simplemembership") {
if (!array_key_exists('user_configuration2', $GLOBALS)) {
require_once (JPATH_SITE . DS . 'administrator' . DS . 'components' . DS .
'com_simplemembership' . DS . 'admin.simplemembership.class.conf.php');
$GLOBALS['user_configuration2'] = $user_configuration;
} else {
global $user_configuration;
}
}
//remove_langs();exit;
$my = JFactory::getUser();
$acl = JFactory::getACL();
$GLOBALS['my'] = $my;
$GLOBALS['acl'] = $acl;
$id = intval(protectInjectionWithoutQuote('id', 0));
$catid = intval(mosGetParam($_REQUEST,'catid', 0));
$bids = mosGetParam($_REQUEST, 'bid', array(0));
$Itemid = protectInjectionWithoutQuote('Itemid', 0);
$printItem = trim(mosGetParam($_REQUEST, 'printItem', ""));
$doc = JFactory::getDocument(); // for 1.6
$GLOBALS['doc'] = $doc; // for 1.6
$GLOBALS['op'] = $doc; // for 1.6
$doc->setTitle(_REALESTATE_MANAGER_TITLE); // for 1.6
if (!isset($GLOBALS['Itemid']))
$GLOBALS['Itemid'] = JRequest::getInt('Itemid');
if (!isset($GLOBALS['Itemid']))
$GLOBALS['Itemid'] = $Itemid = intval(protectInjectionWithoutQuote('Itemid', 0));
// paginations
$intro = $realestatemanager_configuration['page']['items']; // page length
if ($intro) {
$paginations = 1;
$limit = intval(protectInjectionWithoutQuote('limit', $intro));
$GLOBALS['limit'] = $limit;
$limitstart = intval(protectInjectionWithoutQuote('limitstart', 0));
$GLOBALS['limitstart'] = $limitstart;
$total = 0;
$LIMIT = 'LIMIT ' . $limitstart . ',' . $limit;
} else {
$paginations = 0;
$LIMIT = '';
}
$session = JFactory::getSession();
$session->set("array", $paginations);
if (!isset($task))
$GLOBALS['task'] = $task = mosGetParam($_REQUEST, 'task', '');
else {
$GLOBALS['task'] = $task;
}
if (isset($_REQUEST['view']))
$view = protectInjectionWithoutQuote('view', '');
if ((!isset($task) OR $task == '') AND isset($view))
$GLOBALS['task'] = $task = $view;
// if ((!isset($task) OR $task == '') AND (protectInjectionWithoutQuote('start', '') != '')){
// $GLOBALS['task'] = $task = protectInjectionWithoutQuote('start', '');
// }
if ( (!isset($task) OR $task == '' ) && (!isset($view) OR $view == '') ){
$app = new JSite();
$menu = $app->getMenu() ;
$item = $menu->getActive();
if( isset($item) ) $GLOBALS['task'] = $task = $item->query['view'];
}
if (isset($_REQUEST['submit']) && $_REQUEST['submit'] == "[ Rent Request ]")
$task = "rent_request";
if ($realestatemanager_configuration['debug'] == '1') {
echo "Task: " . $task . "<br />";
print_r($_REQUEST);
echo "<hr /><br />";
}
$bid = mosGetParam($_REQUEST, 'bid', array(0));
// -
if(isset($_REQUEST["bid"]) AND isset ($_REQUEST["rent_from"]) AND isset($_REQUEST["rent_until"])){
$bid_ajax_rent = $_REQUEST["bid"];
$rent_from = $_REQUEST["rent_from"];
$rent_until = $_REQUEST["rent_until"];
$week = $_REQUEST["week"];
if(isset($_REQUEST["special_price"])){
$special_price = $_REQUEST["special_price"];
}
if(isset($_REQUEST["currency_spacial_price"])){
$currency_spacial_price = $_REQUEST["currency_spacial_price"];
}
if(isset($_REQUEST["comment_price"])){
$comment_price = $_REQUEST["comment_price"];
} else {
$comment_price = '';
}
}
// print_r($task);exit;
switch ($task) {
case 'paypal':
PHP_realestatemanager::paypal();
break;
case 'ajax_rent_calcualete':
PHP_realestatemanager::ajax_rent_calcualete($bid_ajax_rent,$rent_from,$rent_until,$week);
break;
case 'ajax_update_check_payment':
PHP_realestatemanager::ajax_update_check_payment($order_id);
break;
case 'secret_image':
PHP_realestatemanager::secretImage();
break;
case 'show_search_house':
if (version_compare(JVERSION, '3.0', 'ge')) {
$menu = new JTableMenu($database);
$menu->load($GLOBALS['Itemid']);
$params = new JRegistry;
$params->loadString($menu->params);
} else {
$menu = new mosMenu($database);
$menu->load($GLOBALS['Itemid']);
$params = new mosParameters($menu->params);
}
$layout = $params->get('showsearchhouselayout', '');
PHP_realestatemanager::showSearchHouses($option, $catid, $option, $layout);
break;
case 'show_search':
PHP_realestatemanager::showSearchHouses($option, $catid, $option);
break;
case 'search':
PHP_realestatemanager::searchHouses($option, $catid, $option, $languagelocale);
break;
case 'all_houses':
if (version_compare(JVERSION, '3.0', 'ge')) {
$menu = new JTableMenu($database);
$menu->load($GLOBALS['Itemid']);
$params = new JRegistry;
$params->loadString($menu->params);
} else {
$menu = new mosMenu($database);
$menu->load($GLOBALS['Itemid']);
$params = new mosParameters($menu->params);
}
$layout = $params->get('allhouselayout', '');
if ($layout == '')
$layout = 'default';
PHP_realestatemanager::ShowAllHouses($layout, $printItem);
break;
case 'view_house':
case 'view':
if (version_compare(JVERSION, '3.0', 'ge')) {
$menu = new JTableMenu($database);
$menu->load($GLOBALS['Itemid']);
$params = new JRegistry;
$params->loadString($menu->params);
} else {
$menu = new mosMenu($database);
$menu->load($GLOBALS['Itemid']);
$params = new mosParameters($menu->params);
}
$layout = $params->get('viewhouselayout', '');
if ($layout == '' && isset($catid) && $catid != 0) {
$query = "SELECT params2 FROM #__rem_main_categories WHERE id =" . $catid;
$database->setQuery($query);
$params2 = $database->loadResult();
$object_params = unserialize($params2);
if (isset($object_params->view_house))
$layout = $object_params->view_house;
}
if ($id) {
$query = "SELECT id FROM #__rem_houses WHERE id =" . $id;
$database->setQuery($query);
$id_tmp = $database->loadObjectList();
if( !isset( $id_tmp[0] ) ){
echo"<br /><br /><h1 style='text-align:center'>" . _REALESTATE_MANAGER_LABEL_SEARCH_NOTHING_FOUND . "</h1>";
return;
}
$query = "SELECT idcat AS catid FROM #__rem_categories WHERE iditem=" . $id;
$database->setQuery($query);
$catid = $database->loadObjectList();
$logPath = $mosConfig_absolute_path . "/administrator/components/com_realestatemanager/my_log.log";
if( !isset( $catid[0] ) ) file_put_contents($logPath, " Get category ".$id."::".$task." ".time()." \n", FILE_APPEND );
$catid = $catid[0]->catid;
PHP_realestatemanager::showItemREM($option, $id, $catid, $printItem, $layout);
} else {
if (version_compare(JVERSION, '3.0', 'ge')) {
$menu = new JTableMenu($database);
$menu->load($Itemid);
$params = new JRegistry;
$params->loadString($menu->params);
} else {
$menu = new mosMenu($database);
$menu->load($GLOBALS['Itemid']);
$params = new mosParameters($menu->params);
}
if (version_compare(JVERSION, "1.6.0", "lt")) {
$id = $params->get('house');
} else if (version_compare(JVERSION, "1.6.0", "ge") ) {
$view_house_id = ''; // for 1.6
$view_house_id = $params->get('house');
if ($view_house_id > 0) {
$id = $view_house_id;
}
}
$query = "SELECT idcat AS catid FROM #__rem_categories WHERE iditem=" . $id;
$database->setQuery($query);
$catid = $database->loadObject();
if(isset($catid))
$catid = $catid->catid;
PHP_realestatemanager::showItemREM($option, $id, $catid, $printItem, $layout);
}
break;
case 'review_house':
case 'review':
PHP_realestatemanager::reviewHouse($option);
break;
case 'alone_category':
case 'showCategory':
if (version_compare(JVERSION, '3.0', 'ge')) {
$menu = new JTableMenu($database);
$menu->load($Itemid);
$params = new JRegistry;
$params->loadString($menu->params);
} else {
$menu = new mosMenu($database);
$menu->load($GLOBALS['Itemid']);
$params = new mosParameters($menu->params);
}
$layout = $params->get('categorylayout', '');
if ($layout == '' && isset($catid) && $catid != 0) {
$query = "SELECT params2 FROM #__rem_main_categories WHERE id =" . $catid;
$database->setQuery($query);
$params2 = $database->loadResult();
$object_params = unserialize($params2);
if (isset($object_params->alone_category))
$layout = $object_params->alone_category;
}
if ($catid) {
PHP_realestatemanager::showCategory($catid, $printItem, $option, $layout, $languagelocale);
} else {
$menu = new mosMenu($database);
$menu->load($GLOBALS['Itemid']);
$params = new mosParameters($menu->params);
if (version_compare(JVERSION, "1.6.0", "lt")) {
$catid = $params->get('catid');
} else if (version_compare(JVERSION, "1.6.0", "ge")) {
$single_category_id = ''; // for 1.6
$single_category_id = $params->get('single_category');
if ($single_category_id > 0)
$catid = $single_category_id;
}
PHP_realestatemanager::showCategory($catid, $printItem, $option, $layout, $languagelocale);
}
break;
case "rets_link_import":
PHP_realestatemanager::rets_link_import($option);
break;
// case "link_import":
// PHP_realestatemanager::link_import($option);
// break;
// case "update_map":
// PHP_realestatemanager::updateMap($option);
// break;
case "link_import":
PHP_realestatemanager::link_import($option);
break;
case "update_map":
PHP_realestatemanager::updateMap($option);
break;
case 'rent_request':
PHP_realestatemanager::showRentRequest($option, $bids);
break;
case 'rent_requests':
PHP_realestatemanager::rent_requests($option, $bids);
break;
case 'rent':
if (protectInjectionWithoutQuote('save') == 1)
PHP_realestatemanager::saveRent($option, $bid);
else
PHP_realestatemanager::rent($option, $bid);
break;
case 'rent_return':
if (protectInjectionWithoutQuote('save') == 1)
PHP_realestatemanager::saveRent_return($option, $bid); else
PHP_realestatemanager::rent_return($option, $bid);
break;
case "edit_rent":
case "edit_rent_houses":
if (mosGetParam($_POST, 'save') == 1) {
if (count($bid) > 1) {
echo "<script> alert('". _REALESTATE_MANAGER_ADMIN_ONE_ITEM_ALERT .
"'); window.history.go(-1); </script>\n";
exit;
}
PHP_realestatemanager::saveRent($option, $bid, "edit_rent",false);
} else
PHP_realestatemanager::edit_rent($option, $bid);
break;
case 'accept_rent_requests':
PHP_realestatemanager::accept_rent_requests($option, $bids);
break;
case 'decline_rent_requests':
PHP_realestatemanager::decline_rent_requests($option, $bids);
break;
case 'buying_requests':
PHP_realestatemanager::buying_requests($option, $bids);
break;
case 'accept_buying_requests':
PHP_realestatemanager::accept_buying_requests($option, $bids);
break;
case 'decline_buying_requests':
PHP_realestatemanager::decline_buying_requests($option, $bids);
break;
case 'rent_history':
PHP_realestatemanager::rent_history($option);
break;
case 'save_rent_request':
PHP_realestatemanager::saveRentRequest($option, $bids);
break;
case 'buying_request':
PHP_realestatemanager::saveBuyingRequest($option, $bids);
break;
case 'mdownload':
PHP_realestatemanager::mydownload($id);
break;
case 'downitsf':
PHP_realestatemanager::downloaditself($id);
break;
case 'add_house' :
case 'show_add' :
PHP_realestatemanager::editHouse($option, 0);
break;
case 'edit_house':
PHP_realestatemanager::editHouse($option, $id);
break;
case 'save_add' :
PHP_realestatemanager::saveHouse($option, $id);
break;
case 'my_houses':
case 'edit_my_houses':
PHP_realestatemanager::editMyHouses($option);
break;
case 'show_rss_categories':
PHP_realestatemanager::listRssCategories($languagelocale);
break;
case 'owners_list':
case 'ownerslist':
PHP_realestatemanager::ownersList($option);
break;
case 'owner_houses':
case 'view_user_houses':
case 'showownerhouses':
PHP_realestatemanager::viewUserHouses($option, $languagelocale);
break;
case 'show_my_houses':
case 'showmyhouses':
PHP_realestatemanager::viewUserHouses($option, $languagelocale);
break;
case 'rent_before_end_notify':
PHP_realestatemanager::rentBeforeEndNotify($option);
break;
case 'publish_house':
PHP_realestatemanager::publishHouse();
break;
case 'unpublish_house':
PHP_realestatemanager::unpublishHouse();
break;
case 'delete_house':
PHP_realestatemanager::deleteHouse();
break;
case "ajax_rent_price":
rentPriceREM($bid_ajax_rent,$rent_from,$rent_until,$special_price,$comment_price,$currency_spacial_price);
break;
case 'all_categories':
if (version_compare(JVERSION, '2.5', 'ge')) {
$menu = new JTableMenu($database);
$menu->load($GLOBALS['Itemid']);
$params = new JRegistry;
$params->loadString($menu->params);
} else {
$menu = new mosMenu($database);
$menu->load($GLOBALS['Itemid']);
$params = new mosParameters($menu->params);
}
$layout = $params->get('allcategorylayout', '');
if ($layout == '')
$layout = "default";
PHP_realestatemanager::listCategories($catid, $layout, $languagelocale);
break;
case 'add_to_wishlist':
PHP_realestatemanager::addHouseToWishlist();
break;
case 'remove_from_wishlist':
PHP_realestatemanager::removeHouseFromWishlist();
break;
case 'wishlist':
PHP_realestatemanager::showWishlist($option, $task);
break;
default:
if (version_compare(JVERSION, '3.0', 'ge')) {
$menu = new JTableMenu($database);
$menu->load($GLOBALS['Itemid']);
$params = new JRegistry;
$params->loadString($menu->params);
} else {
$menu = new mosMenu($database);
$menu->load($GLOBALS['Itemid']);
$params = new mosParameters($menu->params);
}
$layout = $params->get('allhouselayout', '');
if ($layout == '')
$layout = 'default';
PHP_realestatemanager::ShowAllHouses($layout, $printItem);
break;
}
class PHP_realestatemanager {
static function mylenStr($str, $lenght) {
if (strlen($str) > $lenght) {
$str = substr($str, 0, $lenght);
$str = substr($str, 0, strrpos($str, " "));
}
return $str;
}
static function addTitleAndMetaTags($idHouse = 0) {
global $database, $doc, $mainframe, $Itemid;
$view = JREQUEST::getCmd('view', null);
$catid = JREQUEST::getInt('catid', null);
$id = JREQUEST::getInt('id', null);
$lang = JREQUEST::getString('lang', null);
$title = array();
$sitename = htmlspecialchars($mainframe->getCfg('sitename'));
if (isset($view)) {
$view = str_replace("_", " ", $view);
$view = ucfirst($view);
$title[] = $view;
}
$s = getWhereUsergroupsCondition('c');
if (!isset($catid)) {
// Parameters
if (version_compare(JVERSION, '3.0', 'ge')) {
$menu = new JTableMenu($database);
$menu->load($Itemid);
$params = new JRegistry;
$params->loadString($menu->params);
} else {
$menu = new mosMenu($database);
$menu->load($Itemid);
$params = new mosParameters($menu->params);
}
if (version_compare(JVERSION, "1.6.0", "lt")) {
$catid = $params->get('catid');
} else if (version_compare(JVERSION, "1.6.0", "ge")) {
$single_category_id = ''; // for 1.6
$single_category_id = $params->get('single_category');
if ($single_category_id > 0)
$catid = $single_category_id;
}
}
//To get name of category
if (isset($catid)) {
$query = "SELECT c.name, c.title, c.id AS catid, c.parent_id
FROM #__rem_main_categories AS c
WHERE ($s) AND c.id = " . intval($catid);
$database->setQuery($query);
$row = null;
$row = $database->loadObject();
if (isset($row)) {
$cattitle = array();
if ($row->title != '') {
$cattitle[] = $row->title; //$row->name
} else {
$cattitle[] = $row->name;
}
while (isset($row) && $row->parent_id > 0) {
$query = "SELECT name, title, c.id AS catid, parent_id
FROM #__rem_main_categories AS c
WHERE ($s) AND c.id = " . intval($row->parent_id);
$database->setQuery($query);
$row = $database->loadObject();
if (isset($row)) {
if ($row->title == '' && $row->name != '') {
$cattitle[] = $row->name; //$row->name
} else {
$cattitle[] = $row->title; //$row->name
}
}
}
$title = array_merge($title, array_reverse($cattitle));
}
}
//To get Name of the houses
if (isset($id)) {
$query = "SELECT h.htitle, c.id AS catid
FROM #__rem_houses AS h
LEFT JOIN #__rem_categories AS hc ON h.id=hc.iditem
LEFT JOIN #__rem_main_categories AS c ON c.id=hc.idcat
WHERE ({$s}) AND h.id=" . intval($id) . "
GROUP BY h.id";
$database->setQuery($query);
$row = null;
$row = $database->loadObject();
if (isset($row)) {
$idtitle = array();
$idtitle[] = $row->htitle;
$title = array_merge($title, $idtitle);
}
}
if (empty($title) && $idHouse != 0) {
$query = "SELECT h.htitle
FROM #__rem_houses AS h
WHERE h.id=" . $idHouse;
$database->setQuery($query);
$row = null;
$row = $database->loadObject();
if (isset($row)) {
$idtitle = array();
$idtitle[] = $row->htitle;
$title = array_merge($title, $idtitle);
}
}
$tagtitle = "";
for ($i = 0; $i < count($title); $i++) {
$tagtitle = trim($tagtitle) . " | " . trim($title[$i]);
}
/*******************************************/
$app = JFactory::getApplication();
if ($app->getParams()->get('page_title') !='') $rem = $app->getParams()->get('page_title');
else $rem = $app->getMenu()->getActive()->title;
/*******************************************/
// $rem = $menu->getActive()->title; //"RealEstate Manager ";
//To set Title
$title_tag = PHP_realestatemanager::mylenStr($rem . $tagtitle, 75);
//To set meta Description
$metadata_description_tag = PHP_realestatemanager::mylenStr($rem . $tagtitle, 200);
//To set meta KeywordsTag
$metadata_keywords_tag = PHP_realestatemanager::mylenStr($rem . $tagtitle, 250);
$doc->setTitle($title_tag);
$doc->setMetaData('description', $metadata_description_tag);
$doc->setMetaData('keywords', $metadata_keywords_tag);
}
static function output_file($file, $name, $mime_type = '') {
/*
This function takes a path to a file to output ($file),
the filename that the browser will see ($name) and
the MIME type of the file ($mime_type, optional).
If you want to do something on download abort/finish,
register_shutdown_function('function_name');
*/
if (!is_readable($file))
die('File not found or inaccessible!');
$size = filesize($file);
$name = rawurldecode($name);
/* Figure out the MIME type (if not specified) */
$known_mime_types = array(
"pdf" => "application/pdf",
"txt" => "text/plain",
"html" => "text/html",
"htm" => "text/html",
"exe" => "application/octet-stream",
"zip" => "application/zip",
"doc" => "application/msword",
"xls" => "application/vnd.ms-excel",
"ppt" => "application/vnd.ms-powerpoint",
"gif" => "image/gif",
"png" => "image/png",
"jpeg" => "image/jpg",
"jpg" => "image/jpg",
"php" => "text/plain"
);
if ($mime_type == '') {
$file_extension = strtolower(substr(strrchr($file, "."), 1));
if (array_key_exists($file_extension, $known_mime_types)) {
$mime_type = $known_mime_types[$file_extension];
} else
$mime_type = "application/force-download";
};
$name = str_replace(" ", "", $name);
ob_end_clean(); //turn off output buffering to decrease cpu usage
// required for IE, otherwise Content-Disposition may be ignored
if (ini_get('zlib.output_compression'))
ini_set('zlib.output_compression', 'Off');
header('Content-Type: application/force-download');
header("Content-Disposition: inline; filename=$name");
header("Content-Transfer-Encoding: binary");
header('Accept-Ranges: bytes');
/* The three lines below basically make the download non-cacheable */
header("Cache-control: private");
header('Pragma: private');
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
// multipart-download and download resuming support
if (isset($_SERVER['HTTP_RANGE'])) {
list($a, $range) = explode("=", $_SERVER['HTTP_RANGE'], 2);
list($range) = explode(",", $range, 2);
list($range, $range_end) = explode("-", $range);
$range = intval($range);
if (!$range_end)
$range_end = $size - 1; else
$range_end = intval($range_end);
$new_length = $range_end - $range + 1;
header("HTTP/1.1 206 Partial Content");
header("Content-Length: $new_length");
} else {
$new_length = $size;
header("Content-Length: " . $size);
}
$chunksize = 1 * (1024 * 1024); //you may want to change this
$bytes_send = 0;
if ($file = fopen($file, 'r')) {
if (isset($_SERVER['HTTP_RANGE']))
fseek($file, $range);
while (!feof($file) && (!connection_aborted()) && ($bytes_send < $new_length)) {
$buffer = fread($file, $chunksize);
print($buffer); // is also possible
flush();
$bytes_send += strlen($buffer);
}
fclose($file);
} else
die('Error - can not open file.');
die();
}
static function mydownload($id) {
global $realestatemanager_configuration;
global $mosConfig_absolute_path;
$session = JFactory::getSession();
$pas = $session->get("ssmid", "default");
$sid_1 = $session->getId();
if (!($session->get("ssmid", "default")) || $pas == "" || $pas != $sid_1 || $_COOKIE['ssd'] != $sid_1 ||
!array_key_exists("HTTP_REFERER", $_SERVER) || $_SERVER["HTTP_REFERER"] == "" ||
strpos($_SERVER["HTTP_REFERER"], $_SERVER['SERVER_NAME']) === false) {
echo '<H3 align="center">Link failure</H3>';
exit;
}
if ($realestatemanager_configuration['license']['show']) {
$fd = fopen($mosConfig_absolute_path . "/components/com_realestatemanager/mylicense.php", "w")
or die("Config license file is failure");
fwrite($fd, _REALESTATE_MANAGER_ADMIN_CONFIG_LICENSE_TEXT);
fclose($fd);
HTML_realestatemanager :: displayLicense($id);
} else
PHP_realestatemanager::downloaditself($id);
}
static function downloaditself($idt) {
global $database, $my, $realestatemanager_configuration, $mosConfig_absolute_path;
$session = JFactory::getSession();
$pas = $session->get("ssmid", "default");
$sid_1 = $session->getId();
if (!($session->get("ssmid", "default")) || $pas == "" || $pas != $sid_1 ||
$_COOKIE['ssd'] != $sid_1 || !array_key_exists("HTTP_REFERER", $_SERVER) ||
$_SERVER["HTTP_REFERER"] == "" ||
strpos($_SERVER["HTTP_REFERER"], $_SERVER['SERVER_NAME']) === false) {
echo '<H3 align="center">Link failure</H3>';
exit;
}
$session->set("ssmid", "default");
if (array_key_exists("id", $_POST))
$id = intval($_POST['id']); else
$id = $idt;
$query = "SELECT * from #__rem_houses where id = " . $id;
$database->setQuery($query);
$house = $database->loadObjectList();
if (strpos($_SERVER["HTTP_REFERER"], $_SERVER['SERVER_NAME']) !== false) {
$name = explode('/', $house[0]->edok_link);
$file_path = $mosConfig_absolute_path .
$realestatemanager_configuration['edocs']['location'] . $name[count($name) - 1];
set_time_limit(0);
PHP_realestatemanager::output_file($file_path, $name[count($name) - 1]);
exit;
} else {
header("Cache-control: private");
header('Pragma: private');
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("HTTP/1.1 301 Moved Permanently");
header('Content-Type: application/force-download');
header("Location: " . $house[0]->edok_link);
exit;
}
}
static function saveRentRequest($option, $bids) {
global $mainframe, $database, $my, $acl, $realestatemanager_configuration, $mosConfig_mailfrom, $Itemid;
$pathway = sefRelToAbs('index.php?option=' . $option . '&task=rent_request&Itemid=' . $Itemid);
$transform_from = data_transform_rem($_POST['rent_from']);
$transform_until = data_transform_rem($_POST['rent_until']);
//Modification par Skorweb//
$week=$_POST['week'];
$acompte=0.30;
$data = JFactory::getDBO();
PHP_realestatemanager::addTitleAndMetaTags();
$jinput = JFactory::getApplication()->input;
if(isset($_POST['user_email']) && $_POST['user_email'] != '') {
$email = $jinput->getString('user_email');
$houseId = $jinput->get('houseid');
$name = $jinput->getString('user_name');
$calculated_price = JRequest::getVar('calculated_price');///with currency//akosha
$calculated_price = $calculated_price*$acompte.' EUR';
$sql = "SELECT u.id as userID, u.email, u.name FROM #__users AS u WHERE u.email =".
$data->Quote($email);
$database->setQuery($sql);
$result = $database->loadObjectList();
if($result == '0' || $result == null) {
$name = $name;
$email = $email;
$user = '';
} else {
$email = $result[0]->email;
$user = $result[0]->userID;
$name = $result[0]->name;
}
$_REQUEST['userId'] = $user;
$_REQUEST['id'] = $houseId;
$_REQUEST['name_bayer'] = $name;
$calculated_price = JRequest::getVar('calculated_price');
$calculated_price = $calculated_price*$acompte.' EUR';
$sql = "SELECT htitle FROM #__rem_houses WHERE id='".$houseId."'";
$database->setQuery($sql);
$htitle = $database->loadResult();
$sql = "INSERT INTO `#__rem_orders`(fk_user_id, status, name,email, fk_house_id,fk_houses_htitle,order_calculated_price, order_date)
VALUES ('".$user."', 'En attente de paiement', '".$name."', ".$database->Quote($email).",
'".$houseId."', '".$htitle."', '".$calculated_price."',now())";
$database->setQuery($sql);
$database->query();
$orderId = $database->insertid();
$text = "Rent request<br>(From:".JRequest::getVar('rent_from')
." - To: ".JRequest::getVar('rent_until').")";
$sql = "INSERT INTO `#__rem_orders_details`(fk_order_id,fk_user_id,email,fk_houses_htitle,name,status,order_date,
fk_house_id,txn_type,order_calculated_price)
VALUES ('".$orderId."','".$user."',". $database->Quote($email) .",
'".$htitle."','".$name."','En attente de paiement',now(),
'".$houseId."','".$text."','".$calculated_price."')";
$database->setQuery($sql);
$database->query();
$_REQUEST['orderID'] =$orderId;
}
$path_way = $mainframe->getPathway();
$path_way->addItem(_REALESTATE_MANAGER_LABEL_TITLE_RENT_REQUEST, $pathway);
// --
if (!($realestatemanager_configuration['rentstatus']['show'])
|| !checkAccess_REM($realestatemanager_configuration['rentrequest']['registrationlevel'],
'NORECURSE', userGID_REM($my->id), $acl)) {
echo _REALESTATE_MANAGER_NOT_AUTHORIZED;
return;
}
$help = array();
$rent_request = new mosRealEstateManager_rent_request($database);
$post = JRequest::get('post');
if (!$rent_request->bind($post)) {
echo "<script> alert('" . $rent_request->getError() . "'); window.history.go(-1); </script>\n";
exit;
}
//********************* begin compare to key ***************************
$session = JFactory::getSession();
$password = $session->get('captcha_keystring', 'default');
if (array_key_exists('keyguest', $_POST) && ($_POST['keyguest'] != $password) && (userGID_REM($my->id) <= 0)) {
mosRedirect("index.php?option=com_realestatemanager&task=view&catid=" . intval($_POST["catid"]) . "&id=" .
intval($_POST["fk_houseid"]) . "&Itemid=$Itemid&title=" . $_POST['title'] . "&comment=" .
$_POST['comment'] . "&rating=" . $_POST['rating'], "You typed bad characters from picture!");
exit;
}
//********************** end compare to key *****************************
$date_format = $realestatemanager_configuration['date_format'];
if(phpversion() >= '5.3.0') {
$date_format = str_replace('%', '', $date_format);
$d_from = DateTime::createFromFormat($date_format, $post['rent_from']);
$d_until = DateTime::createFromFormat($date_format, $post['rent_until']);
if ($d_from === FALSE or $d_until === FALSE) {
echo "<script> alert('". _REALESTATE_MANAGER_ADMIN_BAD_DATE_ALERT .
"'); window.history.go(-1); </script>\n";
exit;
}
$rent_request->rent_from = $d_from->format('Y-m-d');
$rent_request->rent_until = $d_until->format('Y-m-d');
} else {
$rent_request->rent_from = data_transform_rem($post['rent_from'],'to');
$rent_request->rent_until = data_transform_rem($post['rent_until'],'to');
}
$rent_request->user_email = ($rent_request->user_email);
$rent_request->rent_request = date("Y-m-d H:i:s");
$rent_request->fk_houseid = intval($_REQUEST["houseid"]);
if ($rent_request->rent_from > $rent_request->rent_until) {
echo "<script> alert('" . $rent_request->rent_from . " is more than " . $rent_request->rent_until .
"'); window.history.go(-1); </script>\n";
exit;
}
$query = "SELECT * FROM #__rem_houses where id= " . $rent_request->fk_houseid;
$data->setQuery($query);
$houseid = $data->loadObject();
$rent_from = substr($rent_request->rent_from, 0, 10);
$rent_until = substr($rent_request->rent_until, 0, 10);
if ($my->id != 0)
$rent_request->fk_userid = $my->id;
if (!$rent_request->check()) {
echo "<script> alert('" . $rent_request->getError() . "'); window.history.go(-1); </script>\n";
exit;
}
if (!$rent_request->store()) {
echo "<script> alert('" . $rent_request->getError() . "'); window.history.go(-1); </script>\n";
exit;
}
$time_difference = calculatePriceREM($houseid->id,$rent_from,$rent_until,
$realestatemanager_configuration,$database,$week);
$rent_request->checkin();
array_push($help, $rent_request);
$currentcat = new stdClass();
// Parameters
$menu = new mosMenu($database);
$menu->load($Itemid);
$params = new mosParameters($menu->params);
$menu_name = set_header_name_rem($menu, $Itemid);
$params->def('header', $menu_name);
$params->def('pageclass_sfx', '');
$params->def('back_button', $mainframe->getCfg('back_button'));
// --
$currentcat->descrip = _REALESTATE_MANAGER_LABEL_RENT_REQUEST_THANKS;
$currentcat->img = "./components/com_realestatemanager/images/rem_logo.png";
$currentcat->header = $params->get('header');
// used to show table rows in alternating colours
$tabclass = array('sectiontableentry1', 'sectiontableentry2');
if ($realestatemanager_configuration['rentrequest_email']['show']) {
$params->def('show_email', 1);
if (checkAccess_REM($realestatemanager_configuration['rentrequest_email']['registrationlevel'],
'NORECURSE', userGID_REM($my->id), $acl)) {
$params->def('show_input_email', 1);
}
}
if ($realestatemanager_configuration['paypal_buy_status']['show']) {
$params->def('paypal_buy_status', 1);
if (checkAccess_REM($realestatemanager_configuration['paypal_buy']['registrationlevel'],
'NORECURSE', userGID_REM($my->id), $acl)) {
$params->def('paypal_buy_status_rl', 1);
}
}
if ($params->get('show_input_email')) {
if (trim($realestatemanager_configuration['rentrequest_email']['address']) != "") {
$mail_to = explode(",", $realestatemanager_configuration['rentrequest_email']['address']);
$userid = $my->id;
//select user (added rent request)
$zapros = "SELECT name, email FROM #__users WHERE id=" . $userid . ";";
$database->setQuery($zapros);
$item_user = $database->loadObjectList();
echo $database->getErrorMsg();
$zapros = "SELECT r.`id`, r.`houseid`, r.`htitle`, r.`owneremail` " .
" FROM #__rem_houses AS r WHERE r.`id`='" . $rent_request->fk_houseid . "';";
$database->setQuery($zapros);
$item_house = $database->loadObjectList();
echo $database->getErrorMsg();
if (trim($item_house[0]->owneremail) != '')
$mail_to[] = $item_house[0]->owneremail;
if (count($mail_to) > 0)
$username = $_POST['user_name'];
$user_email = $_POST['user_email'];
$user_mailing = $_POST['user_mailing'];
$rent_from = $_POST['rent_from'];
$rent_until = $_POST['rent_until'];
$week = $_POST['week'];
$price=$_POST['calculated_price'];
$acompte=$_POST['calculated_price']*0.30;
$message = str_replace("{username}", $username, _REALESTATE_MANAGER_EMAIL_NOTIFICATION_RENT_REQUEST);
$message = str_replace("{hid_value}", $item_house[0]->houseid, $message);
$message = str_replace("{user_name}", $rent_request->user_name, $message);
$message = str_replace("{user_email}", $user_email, $message);
$message = str_replace("{user_mailing}", $user_mailing, $message);
$message = str_replace("{price}", $price, $message);
$message = str_replace("{acompte}", $acompte, $message);
$message = str_replace("{week}", $week, $message);
$message = str_replace("{rent_from}", $rent_from, $message);
$message = str_replace("{rent_until}", $rent_until, $message);
$message = str_replace("{house_title}", $item_house[0]->htitle, $message);
if ($userid == 0) {
mosMail($mosConfig_mailfrom, _REALESTATE_MANAGER_LABEL_ANONYMOUS, $mail_to,
_REALESTATE_MANAGER_NEW_RENT_REQUEST_ADDED, $message, true);
} else {
mosMail($mosConfig_mailfrom, $item_user[0]->name, $mail_to,
_REALESTATE_MANAGER_NEW_RENT_REQUEST_ADDED, $message, true);
}
}
}
//******************** end add send mail for admin ****************
$backlink = JRoute::_($_SERVER['HTTP_REFERER']);
HTML_realestatemanager :: showRentRequestThanks($params, $backlink, $currentcat, $houseid, $time_difference);
}
static function saveBuyingRequest($option, $bids) {
global $mainframe, $database, $my, $Itemid, $acl;
global $realestatemanager_configuration, $mosConfig_mailfrom;
// echo __FILE__.": ".__LINE__."<br />";
$acompte = 0.30;
$jinput = JFactory::getApplication()->input;
if(isset($_POST['customer_email']) && $_POST['customer_email'] != '') {
$email = $jinput->getString('customer_email');
$bId = $jinput->get('bid', 0, 'ARRAY');
$name = $jinput->getString('customer_name');
$time_difference = null;
$sql = "SELECT u.id as userID, u.email, u.name FROM `#__users` AS u WHERE u.email ='". $email."'";
$database->setQuery($sql);
$result = $database->loadObjectList();
if($result == '0' || $result == null) {
$name = $name;
$email = $email;
$user = '';
} else {
$email = $result[0]->email;
$user = $result[0]->userID;
$name = $result[0]->name;
}
$_REQUEST['userId'] = $user;
$_REQUEST['user_email'] = $email;
$_REQUEST['name_bayer'] = $name;
$_REQUEST['id'] = $houseId = $bId[0];
if($realestatemanager_configuration['special_price']['show']){
$rent_from = data_transform_rem(date('Y-m-d'));
$rent_until = data_transform_rem(date('Y-m-d'));
$query = "SELECT special_price as price,priceunit FROM `#__rem_rent_sal` WHERE fk_houseid = ".$houseId .
" AND (price_from <= ('" .$rent_until. "') AND price_to >= ('" .$rent_from. "'))";
$database->setQuery($query);
$res = $database->loadObjectList();
if($res){
$time_difference = array();
$time_difference['0'] = $res['0']->price;
$time_difference['1'] = $res['0']->priceunit;
$sql = "SELECT htitle FROM #__rem_houses WHERE id='".$houseId."'";
$database->setQuery($sql);
$htitle = $database->loadResult();
}else{
$sql = "SELECT price,priceunit,htitle FROM #__rem_houses WHERE id='".$houseId."'";
$database->setQuery($sql);
$res = $database->loadObjectList();
$htitle = $res[0]->htitle;
}
}else{
$sql = "SELECT price,priceunit,htitle FROM #__rem_houses WHERE id='".$houseId."'";
$database->setQuery($sql);
$res = $database->loadObjectList();
$htitle = $res[0]->htitle;
}
$calculated_price = $res['0']->price*$acompte.' '.$res['0']->priceunit;
$sql = "INSERT INTO `#__rem_orders`(fk_user_id, status, name,email, fk_house_id,fk_houses_htitle,order_calculated_price, order_date)
VALUES ('".$user."', 'En attente de paiement', '".$name."', ".$database->Quote($email).",'".$houseId."', '".$htitle."', '".$calculated_price."',now())";
$database->setQuery($sql);
$database->query();
$orderId = $database->insertid();
$sql = "INSERT INTO `#__rem_orders_details`(fk_order_id,fk_user_id,email,
fk_houses_htitle,name,status,order_date,
fk_house_id,txn_type,order_calculated_price)
VALUES (".$orderId.",'".$user."',". $database->Quote($email) .",
'".$htitle."','".$name."','En attente de paiement',now(),
'".$houseId."','Buy request','".$calculated_price."')";
$database->setQuery($sql);
$database->query();
$_REQUEST['orderID'] =$orderId;
}// order in #__rem_orders
if (!($realestatemanager_configuration['buystatus']['show']) ||
!checkAccess_REM($realestatemanager_configuration['buyrequest']['registrationlevel'],
'NORECURSE', userGID_REM($my->id), $acl)) {
echo _REALESTATE_MANAGER_NOT_AUTHORIZED;
return;
}
$buying_request = new mosRealEstateManager_buying_request($database);
$post = JRequest::get('post');
if (!$buying_request->bind($post)) {
echo $buying_request->getError();
exit;
}
//********************* begin compare to key ***************************
$session = JFactory::getSession();
$password = $session->get('captcha_keystring', 'default');
if (array_key_exists('keyguest', $_POST) && ($_POST['keyguest'] != $password) && (userGID_REM($my->id) <= 0)) {
mosRedirect("index.php?option=com_realestatemanager&task=view&catid=" . intval($_POST["catid"]) . "&id=" .
intval($_POST["fk_houseid"]) . "&Itemid=$Itemid&title=" . $_POST['title'] . "&comment=" .
$_POST['comment'] . "&rating=" . $_POST['rating'], "You typed bad characters from picture!");
exit;
}
//********************** end compare to key *****************************
$buying_request->customer_email = ($buying_request->customer_email);
$buying_request->buying_request = date("Y-m-d H:i:s");
$buying_request->fk_houseid = $bids[0];
if (!$buying_request->store())
echo "error:" . $buying_request->getError();
$currentcat = new stdClass();
// Parameters
$menu = new JTableMenu($database);
$menu->load($Itemid);
$params = new mosParameters($menu->params);
$menu_name = set_header_name_rem($menu, $Itemid);
$params->def('header', $menu_name);
$params->def('pageclass_sfx', '');
$params->def('back_button', $mainframe->getCfg('back_button'));
$currentcat->descrip = _REALESTATE_MANAGER_LABEL_BUYING_REQUEST_THANKS;
// page image
$currentcat->img = "./components/com_realestatemanager/images/rem_logo.png";
$currentcat->header = $params->get('header');
//sending notification
if (($realestatemanager_configuration['buyingrequest_email']['show'])) {
$params->def('show_email', 1);
if (checkAccess_REM($realestatemanager_configuration['buyingrequest_email']['registrationlevel'],
'NORECURSE', userGID_REM($my->id), $acl))
$params->def('show_input_email', 1);
}
if ($realestatemanager_configuration['paypal_buy_status_sale']['show']) {
$params->def('paypal_buy_status', 2);
if (checkAccess_REM($realestatemanager_configuration['paypal_buy_sale']['registrationlevel'],
'NORECURSE', userGID_REM($my->id), $acl)) {
$params->def('paypal_buy_status_rl', 2);
}
}
if ($params->get('show_input_email')) {
$mail_to = array();
if (trim($realestatemanager_configuration['buyingrequest_email']['address']) != "")
$mail_to = explode(",", $realestatemanager_configuration['buyingrequest_email']['address']);
$userid = $my->id;
//select user (added rent request)
$zapros = "SELECT name, email FROM #__users WHERE id=" . $userid . ";";
$database->setQuery($zapros);
$item_user = $database->loadObjectList();
echo $database->getErrorMsg();
for ($i = 0; $i < count($bids); $i++) {
$zapros = "SELECT `id`, `houseid`, `htitle`,`owneremail` FROM #__rem_houses WHERE `id`='" . $bids[$i] . "';";
$database->setQuery($zapros);
$item_house = $database->loadObjectList();
echo $database->getErrorMsg();
if (trim($item_house[0]->owneremail) != '')
$mail_to[] = $item_house[0]->owneremail;
if (count($mail_to) > 0) {
$username = (isset($item_user[0]->name)) ? $item_user[0]->name : _REALESTATE_MANAGER_LABEL_ANONYMOUS;
$message = str_replace("{username}", $username, _REALESTATE_MANAGER_EMAIL_NOTIFICATION_BUYING_REQUEST);
$message = str_replace("{customer_name}", $buying_request->customer_name, $message);
$message = str_replace("{customer_email}", $buying_request->customer_email, $message);
$message = str_replace("{customer_phone}", $buying_request->customer_phone, $message);
$message = str_replace("{customer_comment}", $buying_request->customer_comment, $message);
$message = str_replace("{hid_value}", $item_house[0]->houseid, $message);
$message = str_replace("{house_title}", $item_house[0]->htitle, $message);
if ($userid == 0) {
mosMail($mosConfig_mailfrom, _REALESTATE_MANAGER_LABEL_ANONYMOUS, $mail_to,
_REALESTATE_MANAGER_BUYING_REQUEST_ADDED, $message, true);
} else {
mosMail($mosConfig_mailfrom, $item_user[0]->name, $mail_to,
_REALESTATE_MANAGER_BUYING_REQUEST_ADDED, $message, true);
}
}
}
}
$query = "SELECT * FROM #__rem_houses where id= " . $buying_request->fk_houseid;
$database->setQuery($query);
$houseid = $database->loadObject();
$backlink = JRoute::_($_SERVER['HTTP_REFERER']);
HTML_realestatemanager :: showRentRequestThanks($params, $backlink, $currentcat, $houseid);
}
static function showRentRequest($option, $bid) { exit;
global $mainframe, $database, $my, $Itemid, $acl, $realestatemanager_configuration;
$pathway = sefRelToAbs('index.php?option=' . $option . '&task=rent_request&Itemid=' . $Itemid);
// for 1.6
$path_way = $mainframe->getPathway();
$path_way->addItem(_REALESTATE_MANAGER_LABEL_TITLE_RENT_REQUEST, $pathway);
// --
if (!($realestatemanager_configuration['rentstatus']['show']) ||
!checkAccess_REM($realestatemanager_configuration['rentrequest']['registrationlevel'],
'NORECURSE', userGID_REM($my->id), $acl)) {
echo _REALESTATE_MANAGER_NOT_AUTHORIZED;
return;
}
$bids = implode(',', $bid);
// getting all houses for this category
$query = "SELECT * FROM #__rem_houses"
. "\nWHERE `id` IN (" . $bids . ") ORDER BY `catid`, `ordering`";
$database->setQuery($query);
$houses = $database->loadObjectList();
$currentcat = new stdClass();
// Parameters
$menu = new mosMenu($database);
$menu->load($Itemid);
$params = new mosParameters($menu->params);
$menu_name = set_header_name_rem($menu, $Itemid);
$params->def('header', $menu_name);
// --
$params->def('pageclass_sfx', '');
$params->def('show_rentstatus', 1);
$params->def('show_rentrequest', 1);
$params->def('rent_save', 1);
$params->def('back_button', $mainframe->getCfg('back_button'));
// page description
$currentcat->descrip = _REALESTATE_MANAGER_DESC_RENT;
// page image
$currentcat->img = null;
$currentcat->header = $params->get('header');
// used to show table rows in alternating colours
$tabclass = array('sectiontableentry1', 'sectiontableentry2');
HTML_realestatemanager::showRentRequest($houses, $currentcat, $params, $tabclass,
$catid, $sub_categories, false, $option);
}
/**
* comments for registered users
*/
static function reviewHouse() {
global $mainframe, $database, $my, $Itemid, $acl, $realestatemanager_configuration,
$mosConfig_absolute_path, $catid;
global $mosConfig_mailfrom, $session, $option;
if (!($realestatemanager_configuration['reviews']['show']) ||
!checkAccess_REM($realestatemanager_configuration['reviews']['registrationlevel'],
'NORECURSE', userGID_REM($my->id), $acl)) {
echo _REALESTATE_MANAGER_NOT_AUTHORIZED;
return;
}
$review = new mosRealEstateManager_review($database);
//************publish_on_review begin
if ($realestatemanager_configuration['publish_on_review']['show']) {
if (checkAccess_REM($realestatemanager_configuration['publish_on_review']['registrationlevel'],
'NORECURSE', userGID_REM($my->id), $acl)) {
$review->published = 1;
}
else
$review->published = 0;
}
else
$review->published = 0;
//************publish on add end
$review->date = date("Y-m-d H:i:s");
$review->getReviewFrom($my->id);
//********************* begin compare to key ***************************
$session = JFactory::getSession();
$password = $session->get('captcha_keystring', 'default');
if (array_key_exists('keyguest', $_POST) && ($_POST['keyguest'] != $password) && (userGID_REM($my->id) <= 0)) {
mosRedirect("index.php?option=com_realestatemanager&task=view&catid=" . intval($_POST["catid"]) . "&id=" .
intval($_POST["fk_houseid"]) . "&Itemid=$Itemid&title=" . $_POST['title'] . "&comment=" .
$_POST['comment'] . "&rating=" . $_POST['rating'], "You typed bad characters from picture!");
exit;
}
//********************** end compare to key *****************************
$post = JRequest::get('post');
if (!$review->bind($post)) {
echo "<script> alert('" . $house->getError() . "'); window.history.go(-1); </script>\n";
exit;
}
$review->rating = $_POST['rating'];
if (version_compare(JVERSION, "3.0", "ge"))
$review->rating *= 2;
if (!$review->check()) {
echo "<script> alert('" . $house->getError() . "'); window.history.go(-1); </script>\n";
exit;
}
if (!$review->store()) {
echo "<script> alert('" . $house->getError() . "'); window.history.go(-1); </script>\n";
exit;
}
//*************** begin add send mail for admin ******************
$menu = new mosMenu($database);
$menu->load($Itemid);
$params = new mosParameters($menu->params);
if (($realestatemanager_configuration['review_added_email']['show']) &&
trim($realestatemanager_configuration['review_email']['address']) != "") {
$params->def('show_email', 1);
if (checkAccess_REM($realestatemanager_configuration['review_added_email']['registrationlevel'],
'NORECURSE', userGID_REM($my->id), $acl)) {
$params->def('show_input_email', 1);
}
}
if ($params->get('show_input_email')) {
$mail_to = explode(",", $realestatemanager_configuration['review_email']['address']);
//select house title
$zapros = "SELECT htitle FROM #__rem_houses WHERE houseid = '" . intval($_POST['fk_houseid']) . "';";
$database->setQuery($zapros);
$house_title = $database->loadObjectList();
echo $database->getErrorMsg();
$rating = (($item_review[0]->rating) / 2);
$username = (isset($review->user_name)) ? $review->user_name : _REALESTATE_MANAGER_LABEL_ANONYMOUS;
$message = str_replace("{username}", $username, _REALESTATE_MANAGER_EMAIL_NOTIFICATION_REVIEW);
$message = str_replace("{house_title}", $house_title[0]->htitle, $message);
$message = str_replace("{title}", $review->title, $message);
$message = str_replace("{rating}", $rating, $message);
$message = str_replace("{comment}", $review->comment, $message);
mosMail($mosConfig_mailfrom, $username, $mail_to, _REALESTATE_MANAGER_NEW_REVIEW_ADDED, $message, true);
}
//******************** end add send mail for admin ************
//showing the original entries
mosRedirect("index.php?option=" . $option . "&task=view_house&catid=" . intval($_POST['catid'])
. "&id=$review->fk_houseid&Itemid=$Itemid");
}
static function link_import($option) {
global $database, $my;
$catid = '';
$retVal = mosRealEstateManagerImportExport :: importHousesXMLFromTREB($catid);
//HTML_realestatemanager:: showImportResult($retVal, $option);
//break;
echo "Import Success";
exit;
//*********************** end add for XML format *****************************************
}
static function rets_link_import($option) {
global $database, $my;
$catid = '';
$retVal = mosRealEstateManagerImportExport :: importHousesXMLFromRETS($catid);
//HTML_realestatemanager:: showImportResult($retVal, $option);
//break;
echo "Import Success";
exit;
//*********************** end add for XML format *****************************************
}
static function updateMap($option){
global $database,$option;
global $mosConfig_absolute_path, $mosConfig_live_site, $realestatemanager_configuration;
$logPath = $mosConfig_absolute_path . "/administrator/components/com_realestatemanager/my_log.log";
//exit if now import or map update is going
if (file_exists($logPath)) {
clearstatcache();
$ret = time() - filemtime($logPath) ;
if($ret < 600){
echo "updateMap exit, file accessed : " . $ret ."seconds ago <br />";
file_put_contents($logPath, "updateMap exit, file accessed : " . $ret ."seconds ago \n\n", FILE_APPEND );
exit ;
}
}
file_put_contents($logPath, " updateMap start ".time()." \n", FILE_APPEND );
$api_key = $realestatemanager_configuration['api_key'];
// SELECT count(*)
// FROM zm8wo_rem_houses AS h
// WHERE h.hlatitude = '' AND h.hlongitude = ''
$query = "SELECT h.id,h.hlocation,h.hcountry,h.hregion,h.hcity "
. "\n FROM #__rem_houses AS h"
. "\n WHERE h.hlatitude = '' AND h.hlongitude = '' "
. "\n ORDER BY h.id ASC LIMIT 1000";
$database->setQuery($query);
$datas = $database->loadObjectList();
if (!file_exists($logPath)) exit; //remove file and break import
file_put_contents($logPath," updateMap 2 " . count($datas) . " ".time()." \n\n", FILE_APPEND );
foreach ($datas as $data) {
$address="";
$address .= ($data->hcountry != "null")? $data->hcountry : "";
$address .= ($data->hregion != "null")? ", ". $data->hregion : "";
$address .= ($data->hcity != "null")? ", ". $data->hcity : "";
$address .= ($data->hlocation != "null")? ", " . $data->hlocation : "";
//$address = str_replace(" ", "+", $address);
$address = urlencode($address);
$url = "https://maps.googleapis.com/maps/api/geocode/json?address=$address&key=$api_key";//http:
$response = file_get_contents($url);
$json = json_decode($response,TRUE);
print_r($response);
echo "updateMap:".$address." \n"; flush(); if( ob_get_level() > 0 ) ob_flush(); //fix error: Maximum execution time
if (!file_exists($logPath)) exit; //remove file and break import
file_put_contents($logPath," updateMap 3 " . $address . "::".$json['status'] ." ".time()." \n\n", FILE_APPEND );
if( (isset($json['error_message']) && $json['error_message'] == "You have exceeded your daily request quota for this API." )
|| $json['status'] == "OVER_QUERY_LIMIT" ) return ;
if(isset($json['error_message']) || $json['status'] == "ZERO_RESULTS" ) {
if( $json['status'] = "ZERO_RESULTS") {
$house_class = new mosRealEstateManager($database);
$house_class->load($data->id);
$house_class->hlatitude = "ZERO_RESULTS";
if (!$house_class->check() || !$house_class->store()) {
echo $house_class->getError();
}
unset($house_class);
}
continue ;
}
$lat = $json['results'][0]['geometry']['location']['lat'];
$lng = $json['results'][0]['geometry']['location']['lng'];
$house_class = new mosRealEstateManager($database);
$house_class->load($data->id);
$house_class->hlatitude = $lat;
$house_class->hlongitude = $lng;
$house_class->map_zoom = '14';
if (!$house_class->check() || !$house_class->store()) {
echo $house_class->getError();
}
file_put_contents($logPath," updateMap 4 " . $address . "::".$data->id ." ".time()." \n\n", FILE_APPEND );
unset($house_class);
}
mosRedirect("index.php?option=com_realestatemanager&option=".$option);
}
static function constructPathway($cat) {
global $mainframe, $database, $option, $Itemid, $mosConfig_absolute_path;
$app = JFactory::getApplication();
$path_way = $app->getPathway();
$query = "SELECT * FROM #__rem_main_categories WHERE section = 'com_realestatemanager' AND published = 1";
$database->setQuery($query);
$rows = $database->loadObjectlist('id');
if ($cat != NULL)
$pid = $cat->id; //need check
$pathway = array();
$pathway_name = array();
while ($pid != 0) {
$cat = @$rows[$pid];
$pathway[] = sefRelToAbs('index.php?option=' . $option .
'&task=showCategory&catid=' . @$cat->id . '&Itemid=' . $Itemid);
$pathway_name[] = @$cat->title;
$pid = @$cat->parent_id;
}
$pathway = array_reverse($pathway);
$pathway_name = array_reverse($pathway_name);
for ($i = 0, $n = count($pathway); $i < $n; $i++) {
$path_way->addItem($pathway_name[$i], $pathway[$i]);
}
}
//get current user groups
static function getUserGroups() {
$my = JFactory::getUser();
$acl = JFactory::getACL();
$usergroups = $acl->get_group_parents($my->gid, 'ARO', 'NORECURSE');
if ($usergroups)
$usergroups = ',' . implode(',', $usergroups); else
$usergroups = '';
return '-2,' . $my->gid . $usergroups;
}
static function showCategory($catid, $printItem, $option, $layout, $languagelocale) {
global $mainframe, $database, $acl, $my, $langContent;
global $mosConfig_shownoauth, $mosConfig_live_site, $mosConfig_absolute_path;
global $cur_template, $Itemid, $realestatemanager_configuration;
global $mosConfig_list_limit, $limit, $total, $limitstart;
PHP_realestatemanager::addTitleAndMetaTags();
//getting the current category informations
$database->setQuery("SELECT * FROM #__rem_main_categories WHERE id='" . intval($catid) . "'");
$category = $database->loadObjectList();
if (isset($category[0]))
$category = $category[0];
else {
echo _REALESTATE_MANAGER_ERROR_ACCESS_PAGE;
return;
}
if ($category->params == '') $category->params = '-2';
if (!checkAccess_REM($category->params, 'NORECURSE', userGID_REM($my->id), $acl)) {
echo _REALESTATE_MANAGER_ERROR_ACCESS_PAGE;
return;
}
//sorting
$item_session = JFactory::getSession();
$sort_arr = $item_session->get('rem_housesort', '');
if (is_array($sort_arr)) {
$tmp1 = mosGetParam($_POST, 'order_direction');
if ($tmp1 != '') {
$sort_arr['order_direction'] = $tmp1;
}
$tmp1 = mosGetParam($_POST, 'order_field');
//$tmp1= $database->Quote($tmp1);
if ($tmp1 != '') {
$sort_arr['order_field'] = $tmp1;
}
$item_session->set('rem_housesort', $sort_arr);
} else {
$sort_arr = array();
$sort_arr['order_field'] = 'htitle';
$sort_arr['order_direction'] = 'asc';
$item_session->set('rem_housesort', $sort_arr);
}
if ($sort_arr['order_field'] == "price")
$sort_string = "CAST( " . $sort_arr['order_field'] . " AS SIGNED)" . " " . $sort_arr['order_direction'];
else
$sort_string = $sort_arr['order_field'] . " " . $sort_arr['order_direction'];
if (isset($langContent)) {
$lang = $langContent;
// $query = "SELECT lang_code FROM #__languages WHERE sef = '$lang'";
// $database->setQuery($query);
// $lang = $database->loadResult();
$lang = " and ( h.language = '$lang' or h.language like 'all' or h.language like '' "
. " or h.language like '*' or h.language is null) "
. " AND ( c.language = '$lang' or c.language like 'all' or c.language like '' or "
. " c.language like '*' or c.language is null) ";
} else {
$lang = "";
}
$s = getWhereUsergroupsCondition('c');
$query = "SELECT COUNT(DISTINCT h.id)
\nFROM #__rem_houses AS h"
. "\nLEFT JOIN #__rem_categories AS hc ON hc.iditem=h.id"
. "\nLEFT JOIN #__rem_main_categories AS c ON c.id=hc.idcat"
. "\nWHERE c.id = '$catid' AND h.published='1' $lang AND h.approved='1' AND c.published='1'
AND ($s)";
//getting groups of user
$s = getWhereUsergroupsCondition('c');
$database->setQuery($query);
$total = $database->loadResult();
$pageNav = new JPagination($total, $limitstart, $limit); // for J 1.6
// getting all houses for this category
$query = "SELECT h.*,hc.idcat AS catid,hc.idcat AS idcat, c.title as category_title "
. "\nFROM #__rem_houses AS h "
. "\nLEFT JOIN #__rem_categories AS hc ON hc.iditem=h.id "
. "\nLEFT JOIN #__rem_main_categories AS c ON c.id=hc.idcat "
. "\nWHERE hc.idcat = '" . $catid . "' AND h.published='1' "
. "\n AND c.published='1' $lang AND ($s)"
. "\nGROUP BY h.id"
. "\nORDER BY " . $sort_string
. "\nLIMIT $pageNav->limitstart,$pageNav->limit;";
$database->setQuery($query);
$houses = $database->loadObjectList();
// For show all houses from subcategories which are included in main category use this request
//(just comment request to not display subcategory houses)
// $query = "SELECT id FROM #__rem_main_categories WHERE parent_id = '" . $catid . "'";
// $database->setQuery($query);
// $if_parent = $database->loadColumn();
// if(!empty($if_parent)){
// foreach($if_parent as $parent_cat){
// $query = "SELECT h.*,hc.idcat AS catid,hc.idcat AS idcat, c.title as category_title "
// . "\nFROM #__rem_houses AS h "
// . "\nLEFT JOIN #__rem_categories AS hc ON hc.iditem=h.id "
// . "\nLEFT JOIN #__rem_main_categories AS c ON c.id=hc.idcat "
// . "\nWHERE hc.idcat = '" . $parent_cat . "' AND h.published='1' "
// . "\n AND c.published='1' $lang AND ($s)"
// . "\nGROUP BY h.id"
// . "\nORDER BY " . $sort_string
// . "\nLIMIT $pageNav->limitstart,$pageNav->limit;";
// $database->setQuery($query);
// $child_houses = $database->loadObjectList();
// $houses = array_merge($child_houses,$houses);
// $query = "SELECT id FROM #__rem_main_categories WHERE parent_id = '" . $parent_cat . "'";
// $database->setQuery($query);
// $if_parent2 = $database->loadColumn();
// foreach($if_parent2 as $child_id){
// $query = "SELECT h.*,hc.idcat AS catid,hc.idcat AS idcat, c.title as category_title "
// . "\nFROM #__rem_houses AS h "
// . "\nLEFT JOIN #__rem_categories AS hc ON hc.iditem=h.id "
// . "\nLEFT JOIN #__rem_main_categories AS c ON c.id=hc.idcat "
// . "\nWHERE hc.idcat = '" . $child_id . "' AND h.published='1' "
// . "\n AND c.published='1' $lang AND ($s)"
// . "\nGROUP BY h.id"
// . "\nORDER BY " . $sort_string
// . "\nLIMIT $pageNav->limitstart,$pageNav->limit;";
// $database->setQuery($query);
// $child_houses = $database->loadObjectList();
// $houses = array_merge($child_houses,$houses);
// }
// }
// }
$query = "SELECT h.*,c.id, c.parent_id, c.title, c.image,COUNT(hc.iditem) as houses,
'1' as display" .
" \n FROM #__rem_main_categories as c " .
" \n LEFT JOIN #__rem_categories AS hc ON hc.idcat=c.id " .
" \n LEFT JOIN #__rem_houses AS h ON h.id=hc.iditem " .
" \n WHERE c.section='com_realestatemanager' $lang "
. " AND c.published=1 AND ({$s})
\n GROUP BY c.id
\n ORDER BY c.parent_id DESC, c.ordering ";
$database->setQuery($query);
$cat_all = $database->loadObjectList();
foreach ($cat_all as $k1 => $cat_item1) {
$query = "SELECT COUNT(hc.iditem) as houses" .
"\n FROM #__rem_main_categories as c " .
"\n LEFT JOIN #__rem_categories AS hc ON hc.idcat=c.id " .
"\n LEFT JOIN #__rem_houses AS h ON h.id=hc.iditem " .
"\n WHERE c.section='com_realestatemanager' AND c.published=1 $lang
\n AND ( h.published || isnull(h.published) ) AND ( h.approved || isnull(h.approved )) AND ({$s})
\n AND c.id = " . $cat_all[$k1]->id . "
\n GROUP BY c.id";
$database->setQuery($query);
$houses_count = $database->loadObjectList();
if($houses_count)
$cat_all[$k1]->houses = $houses_count[0]->houses;
else
$cat_all[$k1]->houses = 0;
}
$currentcat = new stdClass();
// Parameters
$menu = new JTableMenu($database); //for 1.6
$menu->load($Itemid);
$menu_name = set_header_name_rem($menu, $Itemid);
$params = new mosParameters($menu->params);
$params->def('rss_show', $realestatemanager_configuration['rss']['show']);
$params->def('show_category', 1);
// $params->def('header', $menu_name); // for 1.6
$params->def('pageclass_sfx', '');
$params->def('category_name', $category->title);
// add wishlist markers ------------------------------------------
$query = "SELECT fk_houseid FROM `#__rem_users_wishlist` " .
"WHERE fk_userid =" . $my->id;
$database->setQuery($query);
$result = $database->loadColumn();
$params->def('wishlist', $result);
//-----------------------------------------------------------------
if ($layout==''){
$layout = ($params->get('allhouselayout'));
}
if(JRequest::getVar('module') == 'mod_realestatemanager_featured_pro_j3'){
$layout = 'default';
}
PHP_realestatemanager::constructPathway($category);
// wish list
if (($realestatemanager_configuration['wishlist']['show'])) {
if (checkAccess_REM($realestatemanager_configuration['wishlist']['registrationlevel'],
'RECURSE', userGID_REM($my->id), $acl)) {
$params->def('show_add_to_wishlist', 1);
}
}
//*************** begin show search_option *********************
if ($realestatemanager_configuration['search_option']['show']) {
$params->def('search_option', 1);
if (checkAccess_REM($realestatemanager_configuration['search_option']['registrationlevel'],
'NORECURSE', userGID_REM($my->id), $acl)) {
$params->def('search_option_registrationlevel', 1);
}
}
//************** end show search_option ******************************
if (($realestatemanager_configuration['rentstatus']['show'])) {
if (checkAccess_REM($realestatemanager_configuration['rentrequest']['registrationlevel'],
'RECURSE', userGID_REM($my->id), $acl)) {
$params->def('show_rentstatus', 1);
$params->def('show_rentrequest', 1);
}
}
if ($realestatemanager_configuration['housestatus']['show']) {
$params->def('show_housestatus', 1);
if (checkAccess_REM($realestatemanager_configuration['houserequest']['registrationlevel'],
'NORECURSE', userGID_REM($my->id), $acl)) {
$params->def('show_houserequest', 1);
}
}
if ($realestatemanager_configuration['price']['show']) {
$params->def('show_pricestatus', 1);
if (checkAccess_REM($realestatemanager_configuration['price']['registrationlevel'],
'NORECURSE', userGID_REM($my->id), $acl)) {
$params->def('show_pricerequest', 1);
}
}
//********* begin add for Manager print pdf: button 'print PDF' *******
if (($realestatemanager_configuration['print_pdf']['show'])) {
$params->def('show_print_pdf', 1);
if (checkAccess_REM($realestatemanager_configuration['print_pdf']['registrationlevel'],
'NORECURSE', userGID_REM($my->id), $acl)) {
$params->def('show_input_print_pdf', 1);
}
}
//************************* end add for Manager print pdf: button 'print PDF' **************/
//************************* begin add for Manager print view: button 'print VIEW' **********/
if ($realestatemanager_configuration['print_view']['show']) {
$params->def('show_print_view', 1);
if (checkAccess_REM($realestatemanager_configuration['print_view']['registrationlevel'],
'NORECURSE', userGID_REM($my->id), $acl)) {
$params->def('show_input_print_view', 1);
}
}
//************************* end add for Manager print view: button 'print VIEW' *******/
//************************* begin add for Manager mail to: button 'mail to' ***********/
if ($realestatemanager_configuration['mail_to']['show']) {
$params->def('show_mail_to', 1);
if (checkAccess_REM($realestatemanager_configuration['mail_to']['registrationlevel'],
'NORECURSE', userGID_REM($my->id), $acl)) {
$params->def('show_input_mail_to', 1);
}
}
//************************* end add for Manager mail to: button 'mail to' ************/
//***** begin add for Manager Add house: button 'Add a house'
if ($realestatemanager_configuration['add_house']['show']) {
$params->def('show_add_house', 1);
if (checkAccess_REM($realestatemanager_configuration['add_house']['registrationlevel'],
'NORECURSE', userGID_REM($my->id), $acl)) {
$params->def('show_input_add_house', 1);
}
}
//********* end add for Manager Add house: button 'Add a house' */
//*************** begin show search_option *********************/
if ($realestatemanager_configuration['search_option']['show']) {
$params->def('search_option', 1);
if (checkAccess_REM($realestatemanager_configuration['search_option']['registrationlevel'],
'NORECURSE', userGID_REM($my->id), $acl)) {
$params->def('search_option_registrationlevel', 1);
}
}
//************** end show search_option ******************************
$params->def('sort_arr_order_direction', $sort_arr['order_direction']);
$params->def('sort_arr_order_field', $sort_arr['order_field']);
//add for show in category picture
if ($realestatemanager_configuration['cat_pic']['show'])
$params->def('show_cat_pic', 1);
$params->def('show_rating', 1);
$params->def('hits', 1);
$params->def('back_button', $mainframe->getCfg('back_button'));
$currentcat->descrip = $category->description;
$params->def('show_rating', 1);
$params->def('hits', 1);
$params->def('back_button', $mainframe->getCfg('back_button'));
$currentcat->descrip = $category->description;
// page image
$currentcat->img = null;
$path = $mosConfig_live_site . '/images/stories/';
$currentcat->header = $params->get('header');
$currentcat->header = ((trim($currentcat->header)) ? $currentcat->header . ":" : "") . $category->title;
$currentcat->img = null;
// used to show table rows in alternating colours
$tabclass = array('sectiontableentry1', 'sectiontableentry2');
$params->def('minifotohigh', $realestatemanager_configuration['foto']['high']);
$params->def('minifotowidth', $realestatemanager_configuration['foto']['width']);
foreach ($houses as $house) {
if ($house->language != '*') {
$query = "SELECT sef FROM #__languages WHERE lang_code = '$house->language'";
$database->setQuery($query);
$house->language = $database->loadResult();
}
}
$params->def('singlecategory01', "{loadposition com_realestatemanager_single_category_01,xhtml}");
$params->def('singlecategory02', "{loadposition com_realestatemanager_single_category_02,xhtml}");
$params->def('singlecategory03', "{loadposition com_realestatemanager_single_category_03,xhtml}");
$params->def('singlecategory04', "{loadposition com_realestatemanager_single_category_04,xhtml}");
$params->def('singlecategory05', "{loadposition com_realestatemanager_single_category_05,xhtml}");
$params->def('singlecategory06', "{loadposition com_realestatemanager_single_category_06,xhtml}");
$params->def('singlecategory07', "{loadposition com_realestatemanager_single_category_07,xhtml}");
$params->def('singlecategory08', "{loadposition com_realestatemanager_single_category_08,xhtml}");
$params->def('singlecategory09', "{loadposition com_realestatemanager_single_category_09,xhtml}");
$params->def('singlecategory10', "{loadposition com_realestatemanager_single_category_10,xhtml}");
$params->def('singlecategory11', "{loadposition com_realestatemanager_single_category_11,xhtml}");
$params->def('typeLayout', 'alone_category');
if (empty($houses)) {
HTML_realestatemanager::displayHouses_empty($houses, $currentcat, $params,
$tabclass, $catid, $cat_all, $pageNav,PHP_realestatemanager::is_exist_subcategory_houses($catid), $option);
} else {
switch ($printItem) {
case 'pdf':
HTML_realestatemanager::displayHousesPdf($houses, $currentcat,
$params, $tabclass, $catid, $cat_all, $pageNav);
break;
case 'print':
HTML_realestatemanager::displayHousesPrint($houses, $currentcat,
$params, $tabclass, $catid, $cat_all, $pageNav);
break;
default:
HTML_realestatemanager::displayHouses($houses, $currentcat, $params,
$tabclass, $catid, $cat_all, $pageNav,PHP_realestatemanager::is_exist_subcategory_houses($catid), $option, $layout);
break;
}
}
}
static function showItemREM($option, $id, $catid, $printItem, $layout) {
global $mainframe, $database, $my, $acl, $option;
global $mosConfig_shownoauth, $mosConfig_live_site, $mosConfig_absolute_path;
global $cur_template, $Itemid, $realestatemanager_configuration;
PHP_realestatemanager::addTitleAndMetaTags($id);
$database->setQuery("SELECT id FROM #__rem_houses where id=$id ");
if (version_compare(JVERSION, "3.0.0", "lt"))
$trueid = $database->loadResultArray();
else
$trueid = $database->loadColumn();
if (!in_array(intval($id), $trueid)) {
echo _REALESTATE_MANAGER_ERROR_ACCESS_PAGE;
return;
}
//add to path category name
//getting the current category informations
$query = "SELECT * FROM #__rem_main_categories WHERE id='" . intval($catid) . "'";
$database->setQuery($query);
$category = $database->loadObjectList();
if (isset($category[0]))
$category = $category[0];
else {
echo _REALESTATE_MANAGER_ERROR_ACCESS_PAGE;
return;
}
//Record the hit
$sql = "UPDATE #__rem_houses SET hits = hits + 1 WHERE id = " . $id . "";
$database->setQuery($sql);
$database->query();
$sql2 = "UPDATE #__rem_houses SET featured_clicks = featured_clicks - 1 "
. " WHERE featured_clicks > 0 and id = " . $id . "";
$database->setQuery($sql2);
$database->query();
$sql3 = "UPDATE #__rem_houses SET featured_shows = featured_shows - 1 "
. " WHERE featured_shows > 0 and id = " . $id . "";
$database->setQuery($sql3);
$database->query();
//load the house
$house = new mosRealEstateManager($database);
$house->load($id);
$house->setOwnerName();
$access = $house->getAccess_REM();
// for breadcrumbs
PHP_realestatemanager::constructPathway($category);
$path_way = $mainframe->getPathway();
$path_way->addItem(substr($house->htitle, 0, 32) . "");
$selectstring = "SELECT a.* FROM #__rem_houses AS a";
$database->setQuery($selectstring);
$rows = $database->loadObjectList();
$date = date(time());
foreach ($rows as $row) {
$check = strtotime($row->checked_out_time);
$remain = 7200 - ($date - $check);
if (($remain <= 0) && ($row->checked_out != 0)) {
$database->setQuery("UPDATE #__rem_houses SET checked_out=0,checked_out_time=0");
$database->query();
}
}
if (!checkAccess_REM($access, 'RECURSE', userGID_REM($my->id), $acl)) {
echo _REALESTATE_MANAGER_ERROR_ACCESS_PAGE;
return;
}
if ($house->owneremail != $my->email) {
if ($house->published == 0) {
echo _REALESTATE_MANAGER_ERROR_HOUSE_NOT_PUBLISHED;
return;
}
if ($house->approved == 0) {
echo _REALESTATE_MANAGER_ERROR_HOUSE_NOT_APPROVED;
return;
}
}
// $path_way->addItem(substr($house->htitle, 0, 32) . "");
/////////////////////////////////////////////////////////////////////////////////////
//Select list for listing type
$listing_type[0] = _REALESTATE_MANAGER_OPTION_SELECT;
$listing_type[1] = _REALESTATE_MANAGER_OPTION_FOR_RENT;
$listing_type[2] = _REALESTATE_MANAGER_OPTION_FOR_SALE;
//Select list for listing status
$listing_status[_REALESTATE_MANAGER_OPTION_SELECT] = 0;
$listing_status1 = explode(',', _REALESTATE_MANAGER_OPTION_LISTING_STATUS);
$i = 1;
foreach ($listing_status1 as $listing_status2) {
$listing_status[$listing_status2] = $i;
$i++;
}
//Select list for property type
$property_type[_REALESTATE_MANAGER_OPTION_SELECT] = 0;
$property_type1 = explode(',', _REALESTATE_MANAGER_OPTION_PROPERTY_TYPE);
$i = 1;
foreach ($property_type1 as $property_type2) {
$property_type[$property_type2] = $i;
$i++;
}
////////////////////////////////////////////////////////////
//$app = JFactory::getApplication();
//$menu1 = $app->getMenu();
//if ( $menu1->getItem($Itemid) )
//$menu_name = $menu1->getItem($Itemid)->title ;
//else $menu_name = '';
// --
// Parameters
$menu = new JTableMenu($database); // for 1.6
// Parameters
$menu = new mosMenu($database);
$menu->load($Itemid);
$menu_name = set_header_name_rem($menu, $Itemid);
$params = new mosParameters($menu->params);
$params->def('header', $menu_name); //for 1.6
$params->def('pageclass_sfx', '');
if (!isset($my->id)) { //for 1.6
$my->id = 0;
}
// add wishlist markers ------------------------------------------
$query = "SELECT fk_houseid FROM `#__rem_users_wishlist` " .
"WHERE fk_userid =" . $my->id;
$database->setQuery($query);
$result = $database->loadColumn();
$params->def('wishlist', $result);
//-----------------------------------------------------------------
// wish list
if (($realestatemanager_configuration['wishlist']['show'])) {
if (checkAccess_REM($realestatemanager_configuration['wishlist']['registrationlevel'],
'RECURSE', userGID_REM($my->id), $acl)) {
$params->def('show_add_to_wishlist', 1);
}
}
//******* begin add for Manager print pdf: button 'print PDF' ***********
if ($realestatemanager_configuration['print_pdf']['show']) {
$params->def('show_print_pdf', 1);
if (checkAccess_REM($realestatemanager_configuration['print_pdf']['registrationlevel'],
'NORECURSE', userGID_REM($my->id), $acl)) {
$params->def('show_input_print_pdf', 1);
}
}
//**** end add for Manager print pdf: button 'print PDF' *************
//**** begin add for Manager print view: button 'print VIEW' **********
if ($realestatemanager_configuration['print_view']['show']) {
$params->def('show_print_view', 1);
if (checkAccess_REM($realestatemanager_configuration['print_view']['registrationlevel'],
'NORECURSE', userGID_REM($my->id), $acl)) {
$params->def('show_input_print_view', 1);
}
}
//**** end add for Manager print view: button 'print VIEW' ********
//**** begin add for Manager mail to: button 'mail to' *************
if ($realestatemanager_configuration['mail_to']['show']) {
$params->def('show_mail_to', 1);
if (checkAccess_REM($realestatemanager_configuration['mail_to']['registrationlevel'],
'NORECURSE', userGID_REM($my->id), $acl)) {
$params->def('show_input_mail_to', 1);
}
}
if ($realestatemanager_configuration['calendar']['show']) {
$params->def('calendar_show', 1);
if (checkAccess_REM($realestatemanager_configuration['calendarlist']['registrationlevel'],
'NORECURSE', userGID_REM($my->id), $acl)) {
$params->def('calendarlist_show', 1);
}
}
//*** end add for Manager mail to: button 'mail to' **********
if ($realestatemanager_configuration['rentstatus']['show']) {
$params->def('show_rentstatus', 1);
if (checkAccess_REM($realestatemanager_configuration['rentrequest']['registrationlevel'],
'NORECURSE', userGID_REM($my->id), $acl)) {
$params->def('show_rentrequest', 1);
}
}
if ($realestatemanager_configuration['buystatus']['show']) {
$params->def('show_buystatus', 1);
if (checkAccess_REM($realestatemanager_configuration['buyrequest']['registrationlevel'],
'NORECURSE', userGID_REM($my->id), $acl)) {
$params->def('show_buyrequest', 1);
}
}
if ($realestatemanager_configuration['reviews']['show']) {
$params->def('show_reviews', 1);
if (checkAccess_REM($realestatemanager_configuration['reviews']['registrationlevel'],
'NORECURSE', userGID_REM($my->id), $acl)) {
$params->def('show_inputreviews', 1);
}
}
if ($realestatemanager_configuration['edocs']['show']) {
$params->def('show_edocstatus', 1);
if (checkAccess_REM($realestatemanager_configuration['edocs']['registrationlevel'],
'NORECURSE', userGID_REM($my->id), $acl)) {
$params->def('show_edocsrequest', 1); //+18.01
//+18.01
}
}
if ($realestatemanager_configuration['price']['show']) {
$params->def('show_pricestatus', 1);
if (checkAccess_REM($realestatemanager_configuration['price']['registrationlevel'],
'NORECURSE', userGID_REM($my->id), $acl)) {
$params->def('show_pricerequest', 1); //+18.01
}
}
if ($realestatemanager_configuration['sale_separator']) {
$params->def('show_sale_separator', 1);
}
//************ begin show 'location and reviews tab' ***************
if (($realestatemanager_configuration['location_tab']['show'])) {
$params->def('show_location', 1);
if (checkAccess_REM($realestatemanager_configuration['location_tab']['registrationlevel'],
'NORECURSE', userGID_REM($my->id), $acl)) {
$params->def('show_locationtab_registrationlevel', 1); //+18.01
}
}
//************ begin show 'location and reviews tab' ***************
if (($realestatemanager_configuration['street_view']['show'])) {
$params->def('street_view', 1);
if (checkAccess_REM($realestatemanager_configuration['street_view']['registrationlevel'],
'NORECURSE', userGID_REM($my->id), $acl)) {
$params->def('street_view_registrationlevel', 1); //+18.01
}
}
if (($realestatemanager_configuration['reviews_tab']['show'])) {
$params->def('show_reviews_tab', 1);
if (checkAccess_REM($realestatemanager_configuration['reviews_tab']['registrationlevel'],
'NORECURSE', userGID_REM($my->id), $acl)) {
$params->def('show_reviewstab_registrationlevel', 1); //+18.01
}
}
//************ end show 'location and reviews tab' ***************
//************ begin show 'contacts' ***************************
if (($realestatemanager_configuration['contacts']['show'])) {
$params->def('show_contacts_line', 1);
$i = checkAccess_REM($realestatemanager_configuration['contacts']['registrationlevel'],
'NORECURSE', userGID_REM($my->id), $acl);
if ($i) {
$params->def('show_contacts_registrationlevel', 1); //+18.01
}
}
if (($realestatemanager_configuration['owner']['show'])) {
$params->def('show_owner_line', 1);
$i = checkAccess_REM($realestatemanager_configuration['owner']['registrationlevel'],
'NORECURSE', userGID_REM($my->id), $acl);
if ($i) {
$params->def('show_owner_registrationlevel', 1); //+18.01
}
}
if (($realestatemanager_configuration['captcha_option']['show'])) {
$params->def('captcha_option', 1);
$i = checkAccess_REM($realestatemanager_configuration['captcha_option']['registrationlevel'],
'NORECURSE', userGID_REM($my->id), $acl);
if ($i) {
$params->def('captcha_option_registrationlevel', 1); //+18.01
}
}
if (($realestatemanager_configuration['captcha_option_booking']['show'])) {
$params->def('captcha_option_booking', 1);
$i = checkAccess_REM($realestatemanager_configuration['captcha_option_booking']['registrationlevel'],
'NORECURSE', userGID_REM($my->id), $acl);
if ($i) {
$params->def('captcha_option_booking_registrationlevel', 1); //+18.01
}
}
if (($realestatemanager_configuration['captcha_option_sendmessage']['show'])) {
$params->def('captcha_option_sendmessage', 1);
$i = checkAccess_REM($realestatemanager_configuration['captcha_option_sendmessage']['registrationlevel'],
'NORECURSE', userGID_REM($my->id), $acl);
if ($i) {
$params->def('captcha_option_sendmessage_registrationlevel', 1); //+18.01
}
}
if (($realestatemanager_configuration['calendar']['show'])) {
$params->def('calendar_option', 1);
$i = checkAccess_REM($realestatemanager_configuration['calendarlist']['registrationlevel'],
'NORECURSE', userGID_REM($my->id), $acl);
if ($i) {
$params->def('calendar_option_registrationlevel', 1); //+18.01
}
}
$params->def('pageclass_sfx', '');
$params->def('item_description', 1);
$params->def('show_edoc', $realestatemanager_configuration['edocs']['show']);
$params->def('back_button', $mainframe->getCfg('back_button'));
// page header
$currentcat = new stdClass();
$currentcat->header = $params->get('header');
$currentcat->header = ((trim($currentcat->header)) ? $currentcat->header . ":" : "") . $house->htitle;
$currentcat->img = null;
$query = "select main_img from #__rem_photos WHERE fk_houseid='$house->id' order by img_ordering,id";
$database->setQuery($query);
$house_photos = $database->loadObjectList();
// show the house
$query = "SELECT f.* ";
$query .= "FROM #__rem_feature as f ";
$query .= "LEFT JOIN #__rem_feature_houses as fv ON f.id = fv.fk_featureid ";
$query .= "WHERE f.published = 1 and fv.fk_houseid = $id ";
$query .= "ORDER BY f.categories";
$database->setQuery($query);
$house_feature = $database->loadObjectList();
/**********************************************/
$currencyArr = array();
$currentCurrency='';
$currencys = explode(';', $realestatemanager_configuration['currency']);
foreach ($currencys as $oneCurency) {
$oneCurrArr = explode('=', $oneCurency);
if(!empty($oneCurrArr[0]) && !empty($oneCurrArr[1])){
$currencyArr[$oneCurrArr[0]] = $oneCurrArr[1];
if($house->priceunit == $oneCurrArr[0]){
$currentCurrency = $oneCurrArr[1];
}
}
}
if($currentCurrency){
foreach ($currencyArr as $key=>$value) {
$currencys_price[$key] = round($value / $currentCurrency * $house->price, 2);
}
}else{
if($house->owner_id == $my->id){
JError::raiseWarning( 100, _REALESTATE_MANAGER_CURRENCY_ERROR);
}
}
/**********************************************/
$params->def('view01', "{loadposition com_realestatemanager_view_house_01,xhtml}");
$params->def('view02', "{loadposition com_realestatemanager_view_house_02,xhtml}");
$params->def('view03', "{loadposition com_realestatemanager_view_house_03,xhtml}");
$params->def('viewdescription', "{loadposition com_realestatemanager_view_house_description,xhtml}");
$params->def('view04', "{loadposition com_realestatemanager_view_house_04,xhtml}");
$params->def('view05', "{loadposition com_realestatemanager_view_house_05,xhtml}");
$params->def('view06', "{loadposition com_realestatemanager_view_house_06,xhtml}");
$params->def('view07', "{loadposition com_realestatemanager_view_house_07,xhtml}");
$params->def('similaires', "{loadposition com_realestatemanager_similaires,xhtml}");
//////////////start select video/tracks
$query = "SELECT src,type,youtube FROM #__rem_video_source AS r
LEFT JOIN #__rem_houses AS h ON r.fk_house_id=h.id
WHERE r.fk_house_id =" . $house->id;
$database->setQuery($query);
$videos = $database->loadObjectList();
$query = "SELECT src,kind,scrlang,label FROM #__rem_track_source AS t
LEFT JOIN #__rem_houses AS h ON t.fk_house_id = h.id
WHERE t.fk_house_id = " . $house->id;
$database->setQuery($query);
$tracks = $database->loadObjectList();
/////////////////////end
switch ($printItem) {
case 'pdf': HTML_realestatemanager::displayHouseMainPdf($house, $tabclass,
$params, $currentcat, $ratinglist, $house_photos);
break;
case 'print': HTML_realestatemanager::displayHouseMainprint($house,
$tabclass, $params, $currentcat, $ratinglist, $house_photos);
break;
default: HTML_realestatemanager::displayHouse($house, $tabclass,
$params, $currentcat, $ratinglist, $house_photos,$videos,$tracks, $id, $catid,
$option, $house_feature, $currencys_price, $layout);
break;
}
}
static function getMonth($month) {
switch ($month) {
case 1:
$smonth = JText::_('JANUARY');
break;
case 2:
$smonth = JText::_('FEBRUARY');
break;
case 3:
$smonth = JText::_('MARCH');
break;
case 4:
$smonth = JText::_('APRIL');
break;
case 5:
$smonth = JText::_('MAY');
break;
case 6:
$smonth = JText::_('JUNE');
break;
case 7:
$smonth = JText::_('JULY');
break;
case 8:
$smonth = JText::_('AUGUST');
break;
case 9:
$smonth = JText::_('SEPTEMBER');
break;
case 10:
$smonth = JText::_('OCTOBER');
break;
case 11:
$smonth = JText::_('NOVEMBER');
break;
case 12:
$smonth = JText::_('DECEMBER');
break;
}
return $smonth;
}
static function showSearchHouses($options, $catid, $option, $layout = "default") {
global $mainframe, $database, $my, $langContent, $acl;
global $mosConfig_shownoauth, $mosConfig_live_site, $mosConfig_absolute_path, $realestatemanager_configuration;
global $cur_template, $Itemid;
PHP_realestatemanager::addTitleAndMetaTags();
$currentcat = new stdClass();
//if it is't from menus, get layout from config.
$jinput = JFactory::getApplication()->input;
//parameters
$menu = new mosMenu($database);
$menu->load($Itemid);
$params = new mosParameters($menu->params);
$menu_name = set_header_name_rem($menu, $Itemid);
$params->def('header', $menu_name);
$params->def('pageclass_sfx', '');
$params->def('show_category', '1');
$params->def('back_button', $mainframe->getCfg('back_button'));
$pathway = sefRelToAbs('index.php?option=' . $option . '&task=show_search&Itemid=' . $Itemid);
$pathway_name = _REALESTATE_MANAGER_LABEL_SEARCH;
$currentcat->descrip = " ";
$currentcat->align = 'right';
//page image
$currentcat->img = "./components/com_realestatemanager/images/rem_logo.png";
//used to show table rows in alternating colours
$tabclass = array('sectiontableentry1', 'sectiontableentry2');
//listing type
$hlisting = $jinput->get('listing_type') ? $jinput->get('listing_type') : _REALESTATE_MANAGER_LABEL_ALL;
$listing_type[] = mosHtml::makeOption(_REALESTATE_MANAGER_LABEL_ALL, _REALESTATE_MANAGER_LABEL_ALL);
$listing_type[] = mosHtml::makeOption(1, _REALESTATE_MANAGER_OPTION_FOR_RENT);
$listing_type[] = mosHtml::makeOption(2, _REALESTATE_MANAGER_OPTION_FOR_SALE);
$listing_type_list = mosHTML :: selectList($listing_type, 'listing_type',
'class="inputbox" size="1" style="width: 115px"', 'value', 'text', $hlisting);
$params->def('listing_type_list', $listing_type_list);
//listing status
$hlistingstatus = $jinput->get('listing_status') ? $jinput->get('listing_status') : _REALESTATE_MANAGER_LABEL_ALL;
$listing_status[] = mosHtml::makeOption(_REALESTATE_MANAGER_LABEL_ALL, _REALESTATE_MANAGER_LABEL_ALL);
$listing_status1 = explode(',', _REALESTATE_MANAGER_OPTION_LISTING_STATUS);
$i = 1;
foreach ($listing_status1 as $listing_status2) {
$listing_status[] = mosHtml::makeOption($i, $listing_status2);
$i++;
}
$listing_status_list = mosHTML :: selectList($listing_status, 'listing_status',
'class="inputbox" size="1" style="width: 115px"', 'value', 'text', $hlistingstatus);
$params->def('listing_status_list', $listing_status_list);
//property type
$hproperty = $jinput->get('property_type') ? $jinput->get('property_type') : _REALESTATE_MANAGER_LABEL_ALL;
$property_type[] = mosHtml::makeOption(_REALESTATE_MANAGER_LABEL_ALL, _REALESTATE_MANAGER_LABEL_ALL);
$property_type1 = explode(',', _REALESTATE_MANAGER_OPTION_PROPERTY_TYPE);
$i = 1;
foreach ($property_type1 as $property_type2) {
$property_type[] = mosHtml::makeOption($i, $property_type2);
$i++;
}
$property_type_list = mosHTML :: selectList($property_type, 'property_type', 'class="inputbox"
size="1" style="width: 115px"', 'value', 'text', $hproperty);
$params->def('property_type_list', $property_type_list);
//categories
if (isset($langContent)) {
$lang = $langContent;
// $query = "SELECT lang_code FROM #__languages WHERE sef = '$lang'";
// $database->setQuery($query);
// $lang = $database->loadResult();
$lang = " c.language = '$lang' or c.language like 'all' or c.language like '' "
. " or c.language like '*' or c.language is null ";
} else {
$lang = "";
}
$categories[] = mosHTML :: makeOption(_REALESTATE_MANAGER_LABEL_ALL, _REALESTATE_MANAGER_LABEL_ALL);
$clist = com_house_categoryTreeList(0, '', true, $categories, $catid, $lang);
//price
$db = JFactory::getDBO();
$query = "SELECT price FROM #__rem_houses ";
$database->setQuery($query);
if (version_compare(JVERSION, "3.0.0", "lt"))
$prices = $database->loadResultArray();
else
$prices = $database->loadColumn();
rsort($prices, SORT_NUMERIC);
$max_price = $prices[0];
$price[] = mosHTML :: makeOption(_REALESTATE_MANAGER_LABEL_FROM, _REALESTATE_MANAGER_LABEL_FROM);
$price_to[] = mosHTML :: makeOption(_REALESTATE_MANAGER_LABEL_TO, _REALESTATE_MANAGER_LABEL_TO);
$stepPrice = $max_price / 50;
$stepPrice = (string) $stepPrice;
$stepCount = strlen($stepPrice);
if ($stepCount > 2) {
$stepFinalPrice = $stepPrice[0] . $stepPrice[1];
for ($i = 2; $i < $stepCount; $i++) {
$stepFinalPrice .= '0';
}
$stepFinalPrice = (int) $stepFinalPrice;
}
else
$stepFinalPrice = (int) $stepPrice;
if($max_price == 0 || $stepFinalPrice == 0){
$price[] = mosHTML :: makeOption(0, 0);
$price_to[] = mosHTML :: makeOption(0, 0);
}
for ($i = 0; $i < $max_price; $i = $i + $stepFinalPrice) {
$price[] = mosHTML :: makeOption($i, $i);
$price_to[] = mosHTML :: makeOption($i, $i);
}
//*************** begin show search_option *********************
if ($realestatemanager_configuration['search_option']['show']) {
$params->def('search_option', 1);
if (checkAccess_REM($realestatemanager_configuration['search_option']['registrationlevel'],
'NORECURSE', userGID_REM($my->id), $acl)) {
$params->def('search_option_registrationlevel', 1);
}
}
//************** end show search_option ******************************
$pricelist = mosHTML :: selectList($price, 'pricefrom2', 'class="inputbox" size="1"', 'value', 'text');
$params->def('pricefrom2', $pricelist);
$pricelistto = mosHTML :: selectList($price_to, 'priceto2', 'class="inputbox" size="1"', 'value', 'text');
$params->def('priceto2', $pricelistto);
$params->def('showsearch01', "{loadposition com_realestatemanager_show_search_01,xhtml}");
$params->def('showsearch02', "{loadposition com_realestatemanager_show_search_02,xhtml}");
$params->def('showsearch03', "{loadposition com_realestatemanager_show_search_03,xhtml}");
$params->def('showsearch04', "{loadposition com_realestatemanager_show_search_04,xhtml}");
$params->def('showsearch05', "{loadposition com_realestatemanager_show_search_05,xhtml}");
HTML_realestatemanager::showSearchHouses($params, $currentcat, $clist, $option, $layout);
}
static function searchHouses($options, $catid, $option, $languagelocale, $ownername = '') {
global $mainframe, $database, $my, $acl, $limitstart, $limit, $langContent;
global $mosConfig_shownoauth, $mosConfig_live_site, $mosConfig_absolute_path;
global $cur_template, $Itemid, $realestatemanager_configuration,$task, $layout;
PHP_realestatemanager::addTitleAndMetaTags();
$ownernameTMP = $ownername;
//get current user groups
$s = getWhereUsergroupsCondition("c");
$session = JFactory::getSession();
if ($ownername == '') {
$pathway = sefRelToAbs('index.php?option=' . $option . '&task=show_search&Itemid=' . $Itemid);
$pathway_name = _REALESTATE_MANAGER_LABEL_SEARCH;
}
if (array_key_exists("searchtext", $_REQUEST)) {
$search = protectInjectionWithoutQuote('searchtext', '');
$search = addslashes($search);
$session->set("poisk", $search);
}
$poisk_search = $session->get("poisk", "");
$where = array();
$Houseid = " ";
$Description = " ";
$Title = " ";
$Address = " ";
$Country = " ";
$Region = " ";
$City = " ";
$Zipcode = " ";
$Extra1 = " ";
$Extra2 = " ";
$Extra3 = " ";
$Extra4 = " ";
$Extra5 = " ";
$Extra6 = " ";
$Extra7 = " ";
$Extra8 = " ";
$Extra9 = " ";
$Extra10 = " ";
$Rooms = " ";
$Bathrooms = " ";
$Bedrooms = " ";
$Contacts = " ";
$Agent = " ";
$House_size = " ";
$Lot_size = " ";
$Built_year = " ";
$Rent = " ";
$RentSQL = " ";
$RentSQL_JOIN_1 = " ";
$RentSQL_JOIN_2 = " ";
$RentSQL_rent_until = " ";
if (isset($_REQUEST['exactly']) && $_REQUEST['exactly'] == "on") {
$exactly = $poisk_search;
} else {
$exactly = "%$poisk_search%";
}
//sorting
$item_session = JFactory::getSession();
$sort_arr = $item_session->get('rem_housesort', '');
if (is_array($sort_arr)) {
$tmp1 = protectInjectionWithoutQuote('order_direction');
//$tmp1= $database->Quote($tmp1);
if ($tmp1 != '')
$sort_arr['order_direction'] = $tmp1;
$tmp1 = protectInjectionWithoutQuote('order_field');
if ($tmp1 != '')
$sort_arr['order_field'] = $tmp1;
$item_session->set('rem_housesort', $sort_arr);
} else {
$sort_arr = array();
$sort_arr['order_field'] = 'htitle';
$sort_arr['order_direction'] = 'asc';
$item_session->set('rem_housesort', $sort_arr);
}
if ($sort_arr['order_field'] == "price")
$sort_string = "CAST( " . $sort_arr['order_field'] . " AS SIGNED)" . " " . $sort_arr['order_direction'];
else
$sort_string = $sort_arr['order_field'] . " " . $sort_arr['order_direction']; //end sortering
$is_add_or = false;
$add_or_value = " ";
if ($poisk_search != '') {
if (isset($_REQUEST['Houseid']) && $_REQUEST['Houseid'] == "on") {
$Houseid = " ";
if ($is_add_or)
$Houseid = " or ";
$is_add_or = true;
$Houseid .= "LOWER(b.houseid) LIKE '$exactly' ";
}
if (isset($_REQUEST['Description']) && $_REQUEST['Description'] == "on") {
$Description = " ";
if ($is_add_or)
$Description = " or ";
$is_add_or = true;
$Description .=" LOWER(b.description) LIKE '$exactly' ";
}
if (isset($_REQUEST['Title']) && $_REQUEST['Title'] == "on") {
$Title = " ";
if ($is_add_or)
$Title = " or ";
$is_add_or = true;
$Title .=" LOWER(b.htitle) LIKE '$exactly' ";
}
if (isset($_REQUEST['Address']) && $_REQUEST['Address'] == "on") {
$Address = " ";
if ($is_add_or)
$Address = " or ";
$is_add_or = true;
$Address .=" LOWER(b.hlocation) LIKE '$exactly' ";
}
if (isset($_REQUEST['Country']) && $_REQUEST['Country'] == "on") {
$Country = " ";
if ($is_add_or)
$Country = " or ";
$is_add_or = true;
$Country .= "LOWER(b.hcountry) LIKE '$exactly' ";
}
if (isset($_REQUEST['Region']) && $_REQUEST['Region'] == "on") {
$Region = " ";
if ($is_add_or)
$Region = " or ";
$is_add_or = true;
$Region .= "LOWER(b.hregion) LIKE '$exactly' ";
}
if (isset($_REQUEST['City']) && $_REQUEST['City'] == "on") {
$City = " ";
if ($is_add_or)
$City = " or ";
$is_add_or = true;
$City .= "LOWER(b.hcity) LIKE '$exactly' ";
}
if (isset($_REQUEST['Zipcode']) && $_REQUEST['Zipcode'] == "on") {
$Zipcode = " ";
if ($is_add_or)
$Zipcode = " or ";
$is_add_or = true;
$Zipcode .= "LOWER(b.hzipcode) LIKE '$exactly' ";
}
if (isset($_REQUEST['extra1']) && $_REQUEST['extra1'] == "on") {
$Extra1 = " ";
if ($is_add_or)
$Extra1 = " or ";
$is_add_or = true;
$Extra1 .= "LOWER(b.extra1) LIKE '$exactly' ";
}
if (isset($_REQUEST['extra2']) && $_REQUEST['extra2'] == "on") {
$Extra2 = " ";
if ($is_add_or)
$Extra2 = " or ";
$is_add_or = true;
$Extra2 .= "LOWER(b.extra2) LIKE '$exactly' ";
}
if (isset($_REQUEST['extra3']) && $_REQUEST['extra3'] == "on") {
$Extra3 = " ";
if ($is_add_or)
$Extra3 = " or ";
$is_add_or = true;
$Extra3 .= "LOWER(b.extra3) LIKE '$exactly' ";
}
if (isset($_REQUEST['extra4']) && $_REQUEST['extra4'] == "on") {
$Extra4 = " ";
if ($is_add_or)
$Extra4 = " or ";
$is_add_or = true;
$Extra4 .= "LOWER(b.extra4) LIKE '$exactly' ";
}
if (isset($_REQUEST['extra5']) && $_REQUEST['extra5'] == "on") {
$Extra5 = " ";
if ($is_add_or)
$Extra5 = " or ";
$is_add_or = true;
$Extra5 .= "LOWER(b.extra5) LIKE '$exactly' ";
}
if (isset($_REQUEST['rooms']) && $_REQUEST['rooms'] == "on") {
$Rooms = " ";
if ($is_add_or)
$Rooms = " or ";
$is_add_or = true;
$Rooms .= "LOWER(b.Rooms) LIKE '$exactly' ";
}
// if (isset($_REQUEST['Bathrooms']) && $_REQUEST['Bathrooms'] == "on") {
// $Bathrooms = " ";
// if ($is_add_or)
// $Bathrooms = " or ";
// $is_add_or = true;
// $Bathrooms .= "LOWER(b.bathrooms) LIKE '$exactly' ";
// }
// if (isset($_REQUEST['Bedrooms']) && $_REQUEST['Bedrooms'] == "on") {
// $Bedrooms = " ";
// if ($is_add_or)
// $Bedrooms = " or ";
// $is_add_or = true;
// $Bedrooms .= "LOWER(b.bedrooms) LIKE '$exactly' ";
// }
if (isset($_REQUEST['Contacts']) && $_REQUEST['Contacts'] == "on") {
$Contacts = " ";
if ($is_add_or)
$Contacts = " or ";
$is_add_or = true;
$Contacts .=" LOWER(b.contacts) LIKE '$exactly' ";
}
if (isset($_REQUEST['Agent']) && $_REQUEST['Agent'] == "on") {
$Agent = " ";
if ($is_add_or)
$Agent = " or ";
$is_add_or = true;
$Agent .=" LOWER(b.agent) LIKE '$exactly' ";
}
if (isset($_REQUEST['house_size']) && $_REQUEST['house_size'] = "on") {
$House_size = " ";
if ($is_add_or)
$House_size = " or ";
$is_add_or = true;
$House_size .=" LOWER(b.house_size) LIKE '$exactly' ";
}
if (isset($_REQUEST['Lot_size']) && $_REQUEST['Lot_size'] = "on") {
$Lot_size = " ";
if ($is_add_or)
$Lot_size = " or ";
$is_add_or = true;
$Lot_size .=" LOWER(b.lot_size) LIKE '$exactly' ";
}
if (isset($_REQUEST['year']) && $_REQUEST['year'] = "on") {
$House_size = " ";
if ($is_add_or)
$House_size = " or ";
$is_add_or = true;
$House_size .=" LOWER(b.year) LIKE '$exactly' ";
}
if (isset($_REQUEST['Garages']) && $_REQUEST['Garages'] = "on") {
$Garages = " ";
if ($is_add_or)
$Garages = " or ";
$is_add_or = true;
$Garages .=" LOWER(b.garages) LIKE '$exactly' ";
}
}
if (isset($_REQUEST['bathrooms']) ) {
$where[] = " LOWER(b.bathrooms) >= ".(int)($_REQUEST['bathrooms'] )."";
}
if (isset($_REQUEST['bedrooms']) ) {
$where[] = " LOWER(b.bedrooms) >= ".(int)($_REQUEST['bedrooms'] )."";
}
$listing_type = protectInjectionWithoutQuote('listing_type', '');
$listing_status = protectInjectionWithoutQuote('listing_status', '');
$property_type = protectInjectionWithoutQuote('property_type', '');
$extra6 = protectInjectionWithoutQuote('extra6', '');
$extra7 = protectInjectionWithoutQuote('extra7', '');
$extra8 = protectInjectionWithoutQuote('extra8', '');
$extra9 = protectInjectionWithoutQuote('extra9', '');
$extra10 = protectInjectionWithoutQuote('extra10', '');
if ($listing_type != _REALESTATE_MANAGER_LABEL_ALL && $listing_type != '') {
$where[] = " LOWER(b.listing_type)='$listing_type'";
}
if ($listing_status != _REALESTATE_MANAGER_LABEL_ALL && $listing_status != '') {
$where[] = " LOWER(b.listing_status)='$listing_status'";
}
if ($property_type != _REALESTATE_MANAGER_LABEL_ALL && $property_type != '') {
$where[] = " LOWER(b.property_type)='$property_type'";
}
if ($extra6 != _REALESTATE_MANAGER_LABEL_ALL && $extra6 != '') {
$where[] = " LOWER(b.extra6)='$extra6'";
}
if ($extra7 != _REALESTATE_MANAGER_LABEL_ALL && $extra7 != '') {
$where[] = " LOWER(b.extra7)='$extra7'";
}
if ($extra8 != _REALESTATE_MANAGER_LABEL_ALL && $extra8 != '') {
$where[] = " LOWER(b.extra8)='$extra8'";
}
if ($extra9 != _REALESTATE_MANAGER_LABEL_ALL && $extra9 != '') {
$where[] = " LOWER(b.extra9)='$extra9'";
}
if ($extra10 != _REALESTATE_MANAGER_LABEL_ALL && $extra10 != '') {
$where[] = " LOWER(b.extra10)='$extra10'";
}
$pricefrom = intval(protectInjectionWithoutQuote('pricefrom2', ''));
$priceto = intval(protectInjectionWithoutQuote('priceto2', ''));
if ($pricefrom > 0)
$where[] = " CAST( b.price AS SIGNED) >= $pricefrom ";
if ($priceto > 0)
$where[] = " CAST( b.price AS SIGNED) <= $priceto ";
if (isset($_REQUEST['ownername']) && $_REQUEST['ownername'] == "on")
$ownername = "$exactly";
if ($ownername != '' && $ownername != '%%'
&& !( $ownername == 'Guest' || $ownername == 'anonymous' || $ownername == _REALESTATE_MANAGER_LABEL_ANONYMOUS ) ) {
$query = "SELECT u.id FROM #__users AS u WHERE LOWER(u.id) LIKE '$ownername' OR LOWER(u.name) LIKE '$ownername';";
$database->setQuery($query);
if (version_compare(JVERSION, "3.0.0", "lt"))
$owner_ids = $database->loadResultArray();
else
$owner_ids = $database->loadColumn();
$ownername = "";
if (count($owner_ids)) {
foreach ($owner_ids as $owner_id) {
if (isset($_REQUEST['ownername']) && $_REQUEST['ownername'] == "on") {
//search from frontend
if ($is_add_or)
$ownername .= " or ";
$is_add_or = true;
$ownername .= "b.owner_id='$owner_id'";
} else {
//show owner houses
$where[] = "b.owner_id='$owner_id'";
}
}
} else if (!$is_add_or) {
echo"<h1 style='text-align:center'>" . _REALESTATE_MANAGER_LABEL_SEARCH_NOTHING_FOUND . "</h1>";
return;
}
} else if($ownername == 'Guest' || $ownername == 'anonymous' || $ownername == _REALESTATE_MANAGER_LABEL_ANONYMOUS ){
if (isset($_REQUEST['ownername']) && $_REQUEST['ownername'] == "on") {
//search from frontend
if ($is_add_or)
$ownername .= " or ";
$is_add_or = true;
$ownername .= "b.owner_id=''";
} else {
//show owner houses
$where[] = "b.owner_id=''";
}
}
$search_date_from = protectInjectionWithoutQuote('search_date_from', '');
$search_date_from = addslashes(data_transform_rem($search_date_from, 'to'));
$search_date_until = protectInjectionWithoutQuote('search_date_until', '');
$search_date_until = addslashes(data_transform_rem($search_date_until, 'to'));
if($realestatemanager_configuration['special_price']['show']){
$sign = '=';
}else{
$sign = '';
}
if (isset($_REQUEST['search_date_from']) && (trim($_REQUEST['search_date_from']) ) &&
trim($_REQUEST['search_date_until']) == "") {
$RentSQL = "((fk_rentid = 0 OR b.id NOT IN (select dd.fk_houseid " .
" from #__rem_rent AS dd where dd.rent_until >".$sign." ' " . $search_date_from .
"' and dd.rent_from <= '" . $search_date_from .
"' and dd.fk_houseid=b.id and dd.rent_return is null)) AND (listing_type = \"1\"))";
// print_r($RentSQL);
// exit;
if ($is_add_or)
$RentSQL .= " AND ";
$RentSQL_JOIN_1 = "\nLEFT JOIN #__rem_rent AS d ";
$RentSQL_JOIN_2 = "\nON d.fk_houseid=b.id ";
}
if (isset($_REQUEST['search_date_until']) && (trim($_REQUEST['search_date_until']) )
&& trim($_REQUEST['search_date_from']) == "") {
$RentSQL = "((fk_rentid = 0 OR b.id NOT IN (select dd.fk_houseid "
. "from #__rem_rent AS dd where dd.rent_from <".$sign." '" . $search_date_until . "' and dd.rent_until >= '"
. $search_date_until . "' and dd.fk_houseid=b.id and dd.rent_return is null)) AND (listing_type = \"1\"))";
if ($is_add_or)
$RentSQL .= " AND ";
$RentSQL_JOIN_1 = "\nLEFT JOIN #__rem_rent AS d ";
$RentSQL_JOIN_2 = "\nON d.fk_houseid=b.id ";
}
if (isset($_REQUEST['search_date_until']) && (trim($_REQUEST['search_date_until']))
&& isset($_REQUEST['search_date_from']) && ( trim($_REQUEST['search_date_from']))) {
$RentSQL = "((fk_rentid = 0 OR b.id NOT IN (select dd.fk_houseid from #__rem_rent AS dd
where (dd.rent_until >".$sign." '" . $search_date_from . "' and dd.rent_from <".$sign." '" . $search_date_from . "') or " .
" (dd.rent_from <".$sign." ' " . $search_date_until . "' and dd.rent_until >".$sign." '" . $search_date_until . "' ) or " .
" (dd.rent_from >= '" . $search_date_from . "' and dd.rent_until <= '" . $search_date_until . "') and dd.rent_return is null ) ) " .
" AND (listing_type = \"1\"))";
if ($is_add_or)
$RentSQL .= " AND ";
$RentSQL_JOIN_1 = "\nLEFT JOIN #__rem_rent AS d ";
$RentSQL_JOIN_2 = "\nON d.fk_houseid=b.id ";
}
$RentSQL = $RentSQL . (($is_add_or) ? ( "( ( " . $Houseid . " " . $Description .
" " . $Title . " " . $Address .
" " . $Country . " " . $Region . " " . $City . " " . $Zipcode . " " . $Extra1 .
" " . $Extra2 . " " . $Extra3 . " " . $Extra4 . " " . $Extra5 . " " . $Rooms .
" " . $Bathrooms . " " . $Bedrooms . " " . $Contacts . " " . $Agent .
" " . $House_size . " " . $Lot_size . " " . $Built_year . " " . $ownername . " ))") : (" "));
if (trim($RentSQL) != "")
array_push($where, $RentSQL);
//select category, to which user has access
$where[] = " ($s) ";
$where[] = " c.published = '1' ";
//select published and approved houses
array_push($where, " b.published = '1' ");
array_push($where, " b.approved = '1' ");
if (isset($langContent)) {
$lang = $langContent;
// $query = "SELECT lang_code FROM #__languages WHERE sef = '$lang'";
// $database->setQuery($query);
// $lang = $database->loadResult();
$where[] = " ( b.language = '$lang' or b.language like 'all' or b.language like '' "
." or b.language like '*' or b.language is null) ";
$where[] = " ( c.language = '$lang' or c.language like 'all' or c.language like '' "
." or c.language like '*' or c.language is null) ";
}
if ($catid)
array_push($where, "c.id=" . intval($catid) . "");
$query = "SELECT COUNT(DISTINCT b.id)
FROM #__rem_houses AS b
LEFT JOIN #__rem_categories AS hc ON b.id=hc.iditem
LEFT JOIN #__rem_main_categories AS c ON hc.idcat = c.id " .
$RentSQL_JOIN_1 . $RentSQL_JOIN_2 .
((count($where) ? "\n WHERE " . implode(' AND ', $where) : ""));
$database->setQuery($query);
$total = $database->loadResult();
$pageNav = new JPagination($total, $limitstart, $limit); // for J 1.6
// getting all houses for this category
$query = "SELECT distinct hc.idcat as idcat, b . * , c.title AS category_titel, c.ordering AS category_ordering, c.id as catid
FROM #__rem_houses AS b
LEFT JOIN #__rem_categories AS hc ON b.id=hc.iditem
LEFT JOIN #__rem_main_categories AS c ON hc.idcat = c.id " .
$RentSQL_JOIN_1 . $RentSQL_JOIN_2 .
((count($where) ? "\n WHERE " . implode(' AND ', $where) : "")) .
" GROUP BY b.id ORDER BY $sort_string
\nLIMIT " . $pageNav->limitstart . "," . $pageNav->limit;
$database->setQuery($query);
$houses = $database->loadObjectList();
$currentcat = new stdClass();
//parameters
if (version_compare(JVERSION, '3.0', 'ge')) {
$menu = new JTableMenu($database);
$menu->load($Itemid);
$params = new JRegistry;
$params->loadString($menu->params);
} else {
$menu = new mosMenu($database);
$menu->load($Itemid);
$params = new mosParameters($menu->params);
}
$menu_name = set_header_name_rem($menu, $Itemid);
$params->def('header', $menu_name);
$params->def('pageclass_sfx', '');
$params->def('category_name', _REALESTATE_MANAGER_LABEL_SEARCH);
$params->def('search_request', '1');
$params->def('hits', 1);
$params->def('show_rating', 1);
$params->def('sort_arr_order_direction', $sort_arr['order_direction']);
$params->def('sort_arr_order_field', $sort_arr['order_field']);
// add wishlist markers ------------------------------------------
$query = "SELECT fk_houseid FROM `#__rem_users_wishlist` " .
"WHERE fk_userid =" . $my->id;
$database->setQuery($query);
$result = $database->loadColumn();
$params->def('wishlist', $result);
//-----------------------------------------------------------------
$database->setQuery("SELECT id FROM #__menu WHERE link='index.php?option=com_realestatemanager'");
if ($database->loadResult() != $Itemid)
$params->def('wrongitemid', '1');
if ($realestatemanager_configuration['rentstatus']['show']) {
$params->def('show_rentstatus', 1);
if (checkAccess_REM($realestatemanager_configuration['rentrequest']['registrationlevel'],
'NORECURSE', userGID_REM($my->id), $acl)) {
$params->def('show_rentrequest', 1);
}
}
if ($realestatemanager_configuration['housestatus']['show']) {
$params->def('show_housestatus', 1);
if (checkAccess_REM($realestatemanager_configuration['houserequest']['registrationlevel'],
'NORECURSE', userGID_REM($my->id), $acl)) {
$params->def('show_houserequest', 1);
}
}
if ($realestatemanager_configuration['buystatus']['show']) {
$params->def('show_buystatus', 1);
if (checkAccess_REM($realestatemanager_configuration['buyrequest']['registrationlevel'],
'NORECURSE', userGID_REM($my->id), $acl)) {
$params->def('show_buyrequest', 1);
}
}
//***** begin add for Manager Add house: button 'Add a house'
if ($realestatemanager_configuration['add_house']['show']) {
$params->def('show_add_house', 1);
if (checkAccess_REM($realestatemanager_configuration['add_house']['registrationlevel'],
'NORECURSE', userGID_REM($my->id), $acl)) {
$params->def('show_input_add_house', 1);
}
}
//********* end add for Manager Add house: button 'Add a house' **
if ($realestatemanager_configuration['price']['show']) {
$params->def('show_pricestatus', 1);
if (checkAccess_REM($realestatemanager_configuration['price']['registrationlevel'],
'NORECURSE', userGID_REM($my->id), $acl)) {
$params->def('show_pricerequest', 1);
}
}
if ($realestatemanager_configuration['cat_pic']['show'])
$params->def('show_cat_pic', 1);
$params->def('back_button', $mainframe->getCfg('back_button'));
$currentcat->descrip = " ";
$currentcat->align = 'right';
//page image
//$currentcat->img = "./components/com_realestatemanager/images/rem_logo.png";
$currentcat->img = null;
//$currentcat->header = $params->get( 'header' );
//$currentcat->header = $currentcat->header .":". _REALESTATE_MANAGER_LABEL_SEARCH;
//used to show table rows in alternating colours
$tabclass = array('sectiontableentry1', 'sectiontableentry2');
// $params->def('rss_show', $realestatemanager_configuration['rss']['show']);
// if ($realestatemanager_configuration['print_pdf']['show']) {
// $params->def('show_print_pdf', 1);
// if (checkAccess_REM($realestatemanager_configuration['print_pdf']['registrationlevel'],
// 'NORECURSE', userGID_REM($my->id), $acl)) {
// $params->def('show_input_print_pdf', 1);
// }
// }
// if ($realestatemanager_configuration['print_view']['show']) {
// $params->def('show_print_view', 1);
// if (checkAccess_REM($realestatemanager_configuration['print_view']['registrationlevel'],
// 'NORECURSE', userGID_REM($my->id), $acl)) {
// $params->def('show_input_print_view', 1);
// }
// }
if ($realestatemanager_configuration['mail_to']['show']) {
$params->def('show_mail_to', 1);
if (checkAccess_REM($realestatemanager_configuration['mail_to']['registrationlevel'],
'NORECURSE', userGID_REM($my->id), $acl)) {
$params->def('show_input_mail_to', 1);
}
}
if ($realestatemanager_configuration['add_house']['show']) {
$params->def('show_add_house', 1);
if (checkAccess_REM($realestatemanager_configuration['add_house']['registrationlevel'],
'NORECURSE', userGID_REM($my->id), $acl)) {
$params->def('show_input_add_house', 1);
}
}
if ($realestatemanager_configuration['search_option']['show']) {
$params->def('search_option', 1);
if (checkAccess_REM($realestatemanager_configuration['search_option']['registrationlevel'],
'NORECURSE', userGID_REM($my->id), $acl)) {
$params->def('search_option_registrationlevel', 1);
}
}
// wish list
if (($realestatemanager_configuration['wishlist']['show'])) {
if (checkAccess_REM($realestatemanager_configuration['wishlist']['registrationlevel'],
'RECURSE', userGID_REM($my->id), $acl)) {
$params->def('show_add_to_wishlist', 1);
}
}
// show map for layout search_result list
if (($realestatemanager_configuration['searchlayout_map']['show'])) {
if (checkAccess_REM($realestatemanager_configuration['searchlayout_map']['registrationlevel'],
'RECURSE', userGID_REM($my->id), $acl)) {
$params->def('show_searchlayout_map', 1);
}
}
// show order by form for layout search_result list
if (($realestatemanager_configuration['searchlayout_orderby']['show'])) {
if (checkAccess_REM($realestatemanager_configuration['searchlayout_orderby']['registrationlevel'],
'RECURSE', userGID_REM($my->id), $acl)) {
$params->def('show_searchlayout_orderby', 1);
}
}
// show search form
if (($realestatemanager_configuration['searchlayout_form']['show'])) {
if (checkAccess_REM($realestatemanager_configuration['searchlayout_form']['registrationlevel'],
'RECURSE', userGID_REM($my->id), $acl)) {
$params->def('show_searchlayout_form', 1);
}
}
$params->def('singleuser01', "{loadposition com_realestatemanager_single_user_house_01,xhtml}");
$params->def('singleuser02', "{loadposition com_realestatemanager_single_user_house_02,xhtml}");
$params->def('singleuser03', "{loadposition com_realestatemanager_single_user_house_03,xhtml}");
$params->def('singleuser04', "{loadposition com_realestatemanager_single_user_house_04,xhtml}");
$params->def('singleuser05', "{loadposition com_realestatemanager_single_user_house_05,xhtml}");
$params->def('notfound01', "{loadposition com_realestatemanager_nothing_found_house_01,xhtml}");
$params->def('notfound02', "{loadposition com_realestatemanager_nothing_found_house_02,xhtml}");
$params->def('view05', "{loadposition com_realestatemanager_view_house_05,xhtml}");
$params->def('ownerlist03', "{loadposition com_realestatemanager_owner_list_03,xhtml}");
if (isset($_REQUEST['searchLayout'])){
$layout = $_REQUEST['searchLayout'];
} else {
$layout = '';
}
if (isset($_REQUEST['typeLayout'])){
$type = $_REQUEST['typeLayout'];
} else {
$type = '';
}
if (count($houses)) {
if ( $task == 'my_houses' || $task == 'show_my_houses' || $task == 'showmyhouses' ) PHP_realestatemanager::showTabs();
if ($task == 'search') {
if( !isset($_REQUEST['searchLayout']) ) {
$layout = $params->get('searchresultlayout');
$layoutsearch = $params->get('showsearchhouselayout');
}
if (empty($layout)) $layout = 'default';
if (empty($layoutsearch)) $layoutsearch = 'default';
HTML_realestatemanager::displaySearchHouses($houses, $currentcat, $params, $tabclass, $catid, null,
$pageNav, false, $option, $layout, $layoutsearch);
} else {
HTML_realestatemanager::displayHouses($houses, $currentcat, $params, $tabclass, $catid, null,
$pageNav, false, $option, $layout, $type);
}
} else {
if ( $task == 'my_houses'
|| $task == 'show_my_houses' || $task == 'showmyhouses' )
PHP_realestatemanager::showTabs();
positions_rem($params->get('notfound01'));
$layoutsearch = $params->get('showsearchhouselayout', 'default');
if ($params->get('show_searchlayout_form'))
PHP_realestatemanager::showSearchHouses($option, $catid, $option, $layoutsearch);
print_r("<h1 style='text-align:center'>" . _REALESTATE_MANAGER_LABEL_SEARCH_NOTHING_FOUND .
" </h1><br><br><div class='row-fluid'><div class='span9'></div></div>");
positions_rem($params->get('notfound02'));
// "<div class='span3'><div class='rem_house_contacts'>
// <div id='rem_house_titlebox'>" . _REALESTATE_MANAGER_SHOW_SEARCH . "</div> "
// PHP_realestatemanager::showSearchHouses($option, $catid, $option, $layout);
// print_r('</div></div></div>');
}
}
/**
* Compiles information to add or edit houses
* @param integer bid The unique id of the record to edit (0 if new)
* @param array option the current options
*/
static function editHouse($option, $bid) {
global $database, $my, $mosConfig_live_site, $realestatemanager_configuration, $Itemid, $acl, $mainframe;
PHP_realestatemanager::addTitleAndMetaTags();
$house = new mosRealEstateManager($database);
// load the row from the db table
$house->load(intval($bid));
$numeric_houseids = Array();
if (empty($house->houseid) &&
$realestatemanager_configuration['houseid']['auto-increment']['boolean'] == 1) {
$database->setQuery("select houseid from #__rem_houses order by houseid");
$houseids = $database->loadObjectList();
foreach ($houseids as $houseid) {
if (is_numeric($houseid->houseid)) {
$numeric_houseids[] = intval($houseid->houseid);
}
}
if (count($numeric_houseids) > 0) {
sort($numeric_houseids);
$house->houseid = $numeric_houseids[count($numeric_houseids) - 1] + 1;
}
else
$house->houseid = 1;
}
$houseTMP = $house;
$is_edit_all_houses = false ;
if (checkAccess_REM($realestatemanager_configuration['option_edit']['registrationlevel'], 'RECURSE', userGID_REM($my->id), $acl)) {
$is_edit_all_houses = true ;
}
if ($bid != 0 && $my->id != $house->owner_id && $is_edit_all_houses==false) {
mosRedirect("index.php?option=$option");
exit;
}
if ($bid == 0) {
if (!$realestatemanager_configuration['add_house']['show'] ||
!checkAccess_REM($realestatemanager_configuration['add_house']['registrationlevel'],
'NORECURSE', userGID_REM($my->id), $acl)) {
echo "<script> alert('" . _REALESTATE_MANAGER_ERROR_ACCESS_PAGE .
"'); window.history.go(-1); </script>\n";
exit();
}
$pathway = sefRelToAbs('index.php?option=' . $option .
'&task=show_add&Itemid=' . $Itemid);
$pathway_name = _REALESTATE_MANAGER_LABEL_TITLE_ADD_HOUSE;
} else {
$pathway = sefRelToAbs('index.php?option=' . $option .
'&task=edit_house&Itemid=' . $Itemid . '&id=' . $bid);
$pathway_name = _REALESTATE_MANAGER_LABEL_TITLE_EDIT_HOUSE;
}
$associateArray = array();
if($bid){
//bch
$call_from = 'frontend';
$associateArray = edit_house_associate($house,$call_from);
}
$categories = array();
com_house_categoryTreeList(0, '', true, $categories);
if (count($categories) <= 1)
mosRedirect("index.php?option=$option§ion=categories",
_REALESTATE_MANAGER_ADMIN_IMPEXP_ADD);
if (trim($house->id) != "")
$house->setCatIds();
$maxsize = 5;
if (count($categories) > 6)
$maxsize = 6;
$clist = mosHTML :: selectList($categories, 'catid[]', 'class="inputbox"
multiple', 'value', 'text', ($house->catid));
//get Rating
$retVal2 = mosRealEstateManagerOthers :: getRatingArray();
$rating = null;
for ($i = 0, $n = count($retVal2); $i < $n; $i++) {
$help = $retVal2[$i];
$rating[] = mosHTML :: makeOption($help[0], $help[1]);
}
//delete ehouse?
$help = str_replace($mosConfig_live_site, "", $house->edok_link);
$delete_ehouse_yesno[] = mosHTML :: makeOption($help, _REALESTATE_MANAGER_YES);
$delete_ehouse_yesno[] = mosHTML :: makeOption('0', _REALESTATE_MANAGER_NO);
$delete_edoc = mosHTML :: RadioList($delete_ehouse_yesno, 'delete_edoc',
'class="inputbox"', '0', 'value', 'text');
// fail if checked out not by 'me'
if ($house->checked_out && $house->checked_out <> $my->id)
mosRedirect("index2.php?option=$option", _REALESTATE_MANAGER_IS_EDITED);
if ($bid) {
$house->checkout($my->id);
} else {
// initialise new record
$house->published = 0;
$house->approved = 0;
}
//Select list for listing type
$listing_type[] = mosHtml::makeOption(0, _REALESTATE_MANAGER_OPTION_SELECT);
$listing_type[] = mosHtml::makeOption(1, _REALESTATE_MANAGER_OPTION_FOR_RENT);
$listing_type[] = mosHtml::makeOption(2, _REALESTATE_MANAGER_OPTION_FOR_SALE);
$listing_type_list = mosHTML :: selectList($listing_type, 'listing_type',
'class="inputbox" size="1"', 'value', 'text', $house->listing_type);
//Select list for listing status
$listing_status[] = mosHtml::makeOption(0, _REALESTATE_MANAGER_OPTION_SELECT);
$listing_status1 = explode(',', _REALESTATE_MANAGER_OPTION_LISTING_STATUS);
$i = 1;
foreach ($listing_status1 as $listing_status2) {
$listing_status[] = mosHtml::makeOption($i, $listing_status2);
$i++;
}
$listing_status_list = mosHTML :: selectList($listing_status, 'listing_status',
'class="inputbox" size="1"', 'value', 'text', $house->listing_status);
//Select list for property type
$property_type[] = mosHtml::makeOption(0, _REALESTATE_MANAGER_OPTION_SELECT);
$property_type1 = explode(',', _REALESTATE_MANAGER_OPTION_PROPERTY_TYPE);
$i = 1;
foreach ($property_type1 as $property_type2) {
$property_type[] = mosHtml::makeOption($i, $property_type2);
$i++;
}
$property_type_list = mosHTML :: selectList($property_type, 'property_type',
'class="inputbox" size="1"', 'value', 'text', $house->property_type);
if (trim($house->id) != "") {
$query = "select * from #__rem_rent_sal WHERE fk_houseid='$house->id' order by `yearW`, `monthW`";
$database->setQuery($query);
$house_rent_sal = $database->loadObjectList();
}
if (trim($house->id) != "") {
$query = "select main_img from #__rem_photos WHERE fk_houseid='$house->id' order by img_ordering,id";
$database->setQuery($query);
$house_temp_photos = $database->loadObjectList();
foreach ($house_temp_photos as $house_temp_photo) {
$house_photos[] = array($house_temp_photo->main_img,
rem_picture_thumbnail($house_temp_photo->main_img, '150', '150'));
}
$query = "select image_link from #__rem_houses WHERE id='$house->id'";
$database->setQuery($query);
$house_photo = $database->loadResult();
if ($house_photo != '')
$house_photo = array($house_photo, rem_picture_thumbnail($house_photo, '150', '150'));
}
if (trim($house->id) != "") {
$query = "select * from #__rem_rent_sal WHERE fk_houseid='$house->id' order by `yearW`, `monthW`";
$database->setQuery($query);
$house_rent_sal = $database->loadObjectList();
}
///////////START check video/audio files\\\\\\\\\\\\\\\\\\\\\\
$tracks = array();
$videos = array();
$youtubeId = "";
if (!empty($house->id)) {
$database->setQuery("SELECT * FROM #__rem_video_source WHERE fk_house_id=" . $house->id);
$videos = $database->loadObjectList();
}
$youtube = new stdClass();
for ($i = 0;$i < count($videos);$i++) {
if (!empty($videos[$i]->youtube)) {
$youtube->code = $videos[$i]->youtube;
$youtube->id = $videos[$i]->id;
break;
}
}
if (!empty($house->id)) { //check video file
$database->setQuery("SELECT * FROM #__rem_track_source WHERE fk_house_id=" . $house->id);
$tracks = $database->loadObjectList();
}
////////////////////////////////END check video/audio files \\\\\\\\\\\\\\\\\\
$query = "SELECT * ";
$query .= "FROM #__rem_feature as f ";
$query .= "WHERE f.published = 1 ";
$query .= "ORDER BY f.categories";
$database->setQuery($query);
$house_feature = $database->loadObjectList();
for ($i = 0; $i < count($house_feature); $i++) {
$feature = "";
if (!empty($house->id)) {
$query = "SELECT COUNT(id) ";
$query .= "FROM #__rem_feature_houses ";
$query .= "WHERE fk_featureid =" . $house_feature[$i]->id . " AND fk_houseid =" . $house->id;
$database->setQuery($query);
$feature = $database->loadResult();
if ($feature == 1)
$house_feature[$i]->check = 1; else
$house_feature[$i]->check = 0;
} else {
$house_feature[$i]->check = 0;
}
}
$currencys = explode(';', $realestatemanager_configuration['currency']);
foreach ($currencys as $row) {
if ($row != '') {
$row = explode("=", $row);
// $currency[] = mosHTML::makeOption($row[0], $row[0]);
$temp_currency[] = mosHTML::makeOption($row[0], $row[0]);
}
}
$currency = mosHTML :: selectList($temp_currency, 'priceunit', 'class="inputbox" size="1"',
'value', 'text', $house->priceunit);
$currency_spacial_price = mosHTML :: selectList($temp_currency, 'currency_spacial_price',
'class="inputbox" size="1"', 'value', 'text', $house->priceunit);
$query = "SELECT lang_code, title FROM #__languages";
$database->setQuery($query);
$languages = $database->loadObjectList();
$languages_row[] = mosHTML::makeOption('*', 'All');
foreach ($languages as $language) {
$languages_row[] = mosHTML::makeOption($language->lang_code, $language->title);
}
$languages = mosHTML :: selectList($languages_row, 'language',
'class="inputbox" size="1"', 'value', 'text', $house->language);
for ($i = 6; $i <= 10; $i++) {
$name = "_REALESTATE_MANAGER_EXTRA" . $i . "_SELECTLIST";
$extra = explode(',', constant($name));
$extraOption = '';
$extraOption[] = mosHtml::makeOption(0, _REALESTATE_MANAGER_OPTION_SELECT);
foreach ($extra as $key =>$extr) {
$extraOption[] = mosHTML::makeOption($key+1, $extr);
}
switch ($i) {
case 6:
$extraSelect = $house->extra6;
break;
case 7:
$extraSelect = $house->extra7;
break;
case 8:
$extraSelect = $house->extra8;
break;
case 9:
$extraSelect = $house->extra9;
break;
case 10:
$extraSelect = $house->extra10;
break;
}
$extra_list[] = mosHTML :: selectList($extraOption, 'extra' . $i,
'class="inputbox" size="1"', 'value', 'text', $extraSelect);
}
// if ($my->id == $houseTMP->id)
// PHP_realestatemanager::showTabs();
HTML_realestatemanager :: editHouse($option, $house, $clist, $ratinglist,
$delete_edoc,$videos,$youtube, $tracks, $listing_status_list, $property_type_list, $listing_type_list,
$house_photo, $house_temp_photos, $house_photos, $house_rent_sal, $house_feature, $currency,
$languages, $extra_list, $currency_spacial_price, $associateArray);
}
static function ajax_rent_calcualete($bid,$rent_from,$rent_until,$week){
global $realestatemanager_configuration;
$database = JFactory::getDBO();
$resulArr = calculatePriceREM ($bid,$rent_from,$rent_until,$realestatemanager_configuration,$database,$week);
echo $resulArr[0].' '.$resulArr[1];
exit;
}
static function ajax_update_check_payment(){
if (isset($_POST['order_id']))
{
$order_id = $_POST['order_id'];
}
$database = JFactory::getDBO();
$query = "UPDATE `val_rem_orders` SET `status` = 'En attente du chèque' WHERE `val_rem_orders`.`id` =" . $order_id;
$database->setQuery($query);
$database->query();
$query = "UPDATE `val_rem_orders_details` SET `status` = 'En attente du chèque' WHERE `val_rem_orders`.`fk_order_id` =" . $order_id;
$database->setQuery($query);
$database->query();
exit;
}
static function saveHouse($option, $id) {
global $database, $menu, $Itemid, $mainframe, $my, $mosConfig_absolute_path,
$mosConfig_live_site, $realestatemanager_configuration, $params, $catid,
$currentcat, $acl;
global $mosConfig_mailfrom, $session;
///////////////
if (!$realestatemanager_configuration['add_house']['show']
|| !checkAccess_REM($realestatemanager_configuration['add_house']['registrationlevel'],
'RECURSE', userGID_REM($my->id), $acl)) {
mosRedirect('index.php?option=com_realestatemanager&Itemid=' . $Itemid);
exit;
}
//check how the other info should be provided
$house = new mosRealEstateManager($database);
$post = JRequest::get('post', JREQUEST_ALLOWHTML);
if (!$house->bind($post)) {
echo "<script> alert('" . $house->getError() . "'); window.history.go(-1); </script>\n";
exit();
}
if ((strlen($house->owneremail) > 0) && ($house->owner_id == 0))
$house->owner_id = $my->id;
/*************Call function to Save changes for associated houses*************************/
save_house_associate();
/*****************************************************************************************/
// $house->save();
//save of the main image
if (isset($_POST['yearW']) || isset($_POST['monthW'])) {
$id = $_POST['id'];
$monthW = $_POST['monthW'];
$yearW = $_POST['yearW'];
$week = $_POST['week'];
$midweek = $_POST['midweek'];
$weekend = $_POST['weekend'];
for ($i = 0; $i < count($_POST['yearW']); $i++) {
//if (($week[$i]!='') and ($weekend[$i]!='') and ($midweek[$i]!='')) {
$database->setQuery("INSERT INTO #__rem_rent_sal (fk_houseid, monthW, yearW, week, weekend, midweek) "
."VALUES (" . $id . ", " . $monthW[$i] . ", " . $yearW[$i] . ", '" .
$week[$i] . "', '" . $weekend[$i] . "', '"
. $midweek[$i] . "')");
$database->query();
//}
}
} //end if
if (isset($_POST['edok_link']))
$house->edok_link = protectInjectionWithoutQuote('edok_link', '');
//delete ehouse file if neccesary
$delete_edoc = mosGetParam($_POST, 'delete_edoc', 0);
if ($delete_edoc != '0') {
$retVal = @unlink($mosConfig_absolute_path . $delete_edoc);
$house->edok_link = "";
}
//storing e-house
if (isset($_FILES['edoc_file'])){
$edfile = $_FILES['edoc_file'];
$uid = md5(uniqid(rand(), 1));
$edfile['name'] = $uid . $edfile['name'];
$newpath = JPATH_COMPONENT . '/edocs/' . $edfile['name'];
//check if fileupload is correct
if ($realestatemanager_configuration['edocs']['allow']
&& intval($edfile['error']) > 0 && intval($edfile['error']) < 4) {
echo "<script> alert('" . _REALESTATE_MANAGER_LABEL_EDOCUMENT_UPLOAD_ERROR .
"'); window.history.go(-1); </script>\n";
exit();
} else if ($realestatemanager_configuration['edocs']['allow'] && intval($edfile['error']) != 4) {
$uploaddir = $mosConfig_absolute_path .
$realestatemanager_configuration['edocs']['location'];
$file_new = $uploaddir . $uid . $_FILES['edoc_file']['name'];
///
$ext = pathinfo($_FILES['edoc_file']['name'], PATHINFO_EXTENSION);
$ext = strtolower($ext);
$allowed_exts = explode(",", $realestatemanager_configuration['allowed_exts']);
foreach ($allowed_exts as $key => $allowed_ext) {
$allowed_exts[$key] = strtolower($allowed_ext);
}
$file['type'] = $_FILES['edoc_file']['type'];
$db = JFactory::getDbo();
$db->setQuery("SELECT mime_type FROM #__rem_mime_types WHERE `mime_ext` = " . $db->quote($ext) .
" and mime_type = " . $db->quote($file['type']));
$file_db_mime = $db->loadResult();
if ($file_db_mime != $file['type']) {
echo "<script> alert(' ". _REALESTATE_MANAGER_FILE_MIME_TYPE_NOT_MATCH . " - " .
$_FILES['edoc_file']['name'] . "'); window.history.go(-1); </script>\n";
exit();
}
if (!copy($edfile['tmp_name'], $file_new)) {
echo "<script> alert('error: not copy'); window.history.go(-1); </script>\n";
exit();
} else {
$house->edok_link = $mosConfig_live_site .
$realestatemanager_configuration['edocs']['location'] . $edfile['name'];
}
}
}
if (is_string($house)) {
echo "<script> alert('" . $house . "'); window.history.go(-1); </script>\n";
exit();
}
$house->date = date("Y-m-d H:i:s");
if (!$house->check()) {
echo "<script> alert('" . $house->getError() . "'); window.history.go(-1); </script>\n";
exit();
}
//************approve on add begin
if ($realestatemanager_configuration['approve_on_add']['show']) {
if (checkAccess_REM($realestatemanager_configuration['approve_on_add']['registrationlevel'],
'NORECURSE', userGID_REM($my->id), $acl)) {
$house->approved = 1;
}
}
//************approve on add begin
if ($realestatemanager_configuration['publish_on_add']['show']) {
if (checkAccess_REM($realestatemanager_configuration['publish_on_add']['registrationlevel'],
'NORECURSE', userGID_REM($my->id), $acl)) {
$house->published = 1;
}
}
/********************************** if count car group > count car user set status unpulish***************************/
$count_house_single_all = getCountHouseForSingleUserREM($my, $database, $realestatemanager_configuration);
$count_house_single_user = $count_house_single_all[0];
$count_house_for_single_group = $count_house_single_all[1];
if($count_house_single_user >= $count_house_for_single_group){
$house->published = 0;
}
/**********************************************************************************************************************/
$house->checked_out = 0;
if (!$house->store()) {
echo "<script> alert('" . $house->getError() . "'); window.history.go(-1); </script>\n";
exit();
}
$uploaddir = $mosConfig_absolute_path . '/components/com_realestatemanager/photos/';
$code = guid();
if ($_FILES['image_link']['name'] != '') {
///
$ext = pathinfo($_FILES['image_link']['name'], PATHINFO_EXTENSION);
$ext = strtolower($ext);
$allowed_exts = explode(",", $realestatemanager_configuration['allowed_exts_img']);
foreach ($allowed_exts as $key => $allowed_ext) {
$allowed_exts[$key] = strtolower($allowed_ext);
}
$file['type'] = $_FILES['image_link']['type'];
$db = JFactory::getDbo();
$db->setQuery("SELECT mime_type FROM #__rem_mime_types WHERE `mime_ext` = " .
$db->quote($ext) . " and mime_type = " . $db->quote($file['type']));
$file_db_mime = $db->loadResult();
if ($file_db_mime != $file['type']) {
echo "<script> alert(' " . _REALESTATE_MANAGER_FILE_MIME_TYPE_NOT_MATCH . ". - " .
$_FILES['image_link']['name'] . "'); window.history.go(-1); </script>\n";
exit();
}
///
$uploadfile = $uploaddir . $code . "_" . $_FILES['image_link']['name'];
$file_name = $code . "_" . $_FILES['image_link']['name'];
if (copy($_FILES['image_link']['tmp_name'], $uploadfile)) {
$database->setQuery("UPDATE #__rem_houses SET image_link='$file_name' WHERE id=" . $house->id);
if (!$database->query())
echo "<script> alert('" . $database->getErrorMsg() . "');</script>\n";
}
} //end if
$house->saveCatIds($house->catid);
$house->checkin();
/********************************** if count photo group > count photo user not published*****************/
$count_foto_for_single_group = '';
$user_group = userGID_REM($my->id);
$user_group_mas = explode(',', $user_group);
$max_count_foto = 0;
foreach ($user_group_mas as $value) {
$count_foto_for_single_group = $realestatemanager_configuration['user_manager_rem'][$value]['count_foto'];
if($count_foto_for_single_group>$max_count_foto){
$max_count_foto = $count_foto_for_single_group;
}
}
$count_foto_for_single_group = $max_count_foto;
$query = "select main_img from #__rem_photos WHERE fk_houseid='$house->id' order by img_ordering,id";
$database->setQuery($query);
$house_temp_photos = $database->loadObjectList();
if(count($house_temp_photos) != 0)
{
$count_foto_for_single_group = $count_foto_for_single_group - count($house_temp_photos);
}
/*********************************************************************************************************/
//save photos
$uploaddir = $mosConfig_absolute_path . '/components/com_realestatemanager/photos/';
if (array_key_exists("new_photo_file", $_FILES)) {
for ($i = 0; $i < $count_foto_for_single_group; $i++) {
if (!empty($_FILES['new_photo_file']['name'][$i])) {
$code = guid();
////
$ext = pathinfo($_FILES['new_photo_file']['name'][$i], PATHINFO_EXTENSION);
$ext = strtolower($ext);
$allowed_exts = explode(",", $realestatemanager_configuration['allowed_exts_img']);
foreach ($allowed_exts as $key => $allowed_ext) {
$allowed_exts[$key] = strtolower($allowed_ext);
}
if (!in_array($ext, $allowed_exts)) {
echo "<script> alert(' File ext. not allowed to upload! - " .
$_FILES['new_photo_file']['name'][$i] . "'); window.history.go(-1); </script>\n";
exit();
}
$file['type'] = $_FILES['new_photo_file']['type'][$i];
$db = JFactory::getDbo();
$db->setQuery("SELECT mime_type FROM #__rem_mime_types WHERE `mime_ext` = " .
$db->quote($ext) . " and mime_type = " . $db->quote($file['type']));
$file_db_mime = $db->loadResult();
if ($file_db_mime != $file['type']) {
echo "<script> alert(' " . _REALESTATE_MANAGER_FILE_MIME_TYPE_NOT_MATCH . " - " .
$_FILES['new_photo_file']['name'][$i] . "'); window.history.go(-1); </script>\n";
exit();
}
////
$uploadfile = $uploaddir . $code . "_" . $_FILES['new_photo_file']['name'][$i];
if (copy($_FILES['new_photo_file']['tmp_name'][$i], $uploadfile)) {
$file_name = $code . "_" . $_FILES['new_photo_file']['name'][$i];
$database->setQuery("INSERT INTO #__rem_photos (fk_houseid,main_img) VALUES ('$house->id','$file_name')");
if (!$database->query()) {
echo "<script> alert('" . $database->getErrorMsg() . "');</script>\n";
$mini_file_name = rem_picture_thumbnail($file_name, 1);
}
}
}
} //for
} //end if
//ordering_photo
if(JRequest::getVar('rem_img_ordering')){
$ordering = JRequest::getVar('rem_img_ordering');
$ordering = explode(',', $ordering);
foreach ($ordering as $key => $value) {
$query = "UPDATE #__rem_photos SET img_ordering = $key WHERE main_img='".$value."'";
$database->setQuery($query);
$database->query();
}
}
/////////////save video/tracks functions\\\\\\\\\\\\\\\\\\\\\\
storeVideo($house);
storeTrack($house);
/////////////////////////\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
//check the files marked for deletion
if (array_key_exists("del_main_photo", $_POST)) {
$del_main_photo = $_POST['del_main_photo'];
if ($del_main_photo != '') {
$database->setQuery("select image_link FROM #__rem_houses where houseid ="
. $house->houseid . "");
$image_link = $database->loadObjectList();
$house->image_link = '';
unlink($mosConfig_absolute_path . '/components/com_realestatemanager/photos/'
. $image_link[0]->image_link);
//separation of the file name in the name and extension
$del_main_phot = pathinfo($image_link[0]->image_link);
$del_main_photo_type = '.' . $del_main_phot['extension'];
$del_main_photo_name = basename($image_link[0]->image_link, $del_main_photo_type);
$path = $mosConfig_absolute_path . '/components/com_realestatemanager/photos/';
$check_files = JFolder::files($path, '^' . $del_main_photo_name . '.*$', false, true);
foreach ($check_files as $check_file) {
unlink($check_file);
}
}
//Update DB
$database->setQuery("UPDATE #__rem_houses SET image_link='' WHERE id=" . $house->id);
if (!$database->query())
echo "<script> alert('" . $database->getErrorMsg() . "');</script>\n";
} //end if
if (isset($_POST['del_photos']) && (count($_POST['del_photos']) != 0)) {
foreach ($_POST['del_photos'] as $del_photo) {
$database->setQuery("DELETE FROM #__rem_photos WHERE main_img='$del_photo'");
if ($database->query()) {
unlink($mosConfig_absolute_path . '/components/com_realestatemanager/photos/' . $del_photo);
} else {
echo '<script>alert("Can\'t delete");window.history.go(-1);</script>';
}
}
}
$house->checkin();
if (isset($_POST['del_rent_sal'])) {
for ($i = 0; $i < count($_POST['del_rent_sal']); $i++) {
$del_rent_sal = $_POST['del_rent_sal'][$i];
$database->setQuery("DELETE FROM #__rem_rent_sal WHERE id ='$del_rent_sal'");
$database->query();
}
}
if(!empty($_POST['feature'])) {
$feature = $_POST['feature'];
$database->setQuery("DELETE FROM #__rem_feature_houses WHERE fk_houseid = ".$house->id );
$database->query();
for ($i=0;$i<count($feature);$i++) {
$database->setQuery("INSERT INTO #__rem_feature_houses (fk_houseid, fk_featureid) VALUES ("
.$house->id . ", " . $feature[$i] . ")");
$database->query();
}
} else {
$database->setQuery("DELETE FROM #__rem_feature_houses WHERE fk_houseid = " . $house->id);
$database->query();
}
deleteVideos($house->id);
deleteTracks($house->id);
// Parameters
if (version_compare(JVERSION, '3.0', 'ge')) {
$menu = new JTableMenu($database);
$menu->load($Itemid);
$params = new JRegistry;
$params->loadString($menu->params);
} else {
$menu = new mosMenu($database);
$menu->load($Itemid);
$params = new mosParameters($menu->params);
}
//$app = JFactory::getApplication();
//$menu1 = $app->getMenu();
$menu_name = set_header_name_rem($menu, $Itemid);
//if ($menu1->getItem($Itemid)) $menu_name = $menu1->getItem($Itemid)->title; else $menu_name = '';
$params->def('header', $menu_name);
$params->def('pageclass_sfx', '');
$params->def('back_button', $mainframe->getCfg('back_button'));
$currentcat = new stdClass();
$currentcat->descrip = _REALESTATE_MANAGER_LABEL_REAL_ESTATE_THANKS;
// page image
$currentcat->img = "./components/com_realestatemanager/images/rem_logo.png";
$currentcat->header = $params->get('header');
if ($realestatemanager_configuration['add_email']['show'] &&
$realestatemanager_configuration['add_email']['address'] != "") {
$params->def('show_email', 1);
if (checkAccess_REM($realestatemanager_configuration['add_email']['registrationlevel'],
'NORECURSE', userGID_REM($my->id), $acl)) {
$params->def('show_input_email', 1);
}
}
if ($params->get('show_input_email')) {
$mail_to = explode(",", $realestatemanager_configuration['add_email']['address']);
$userid = $my->id;
//select user (added rent request)
$select = "SELECT name, email FROM #__users WHERE id=" . $userid . ";";
$database->setQuery($select);
$item_user = $database->loadObjectList();
echo $database->getErrorMsg();
$select = "SELECT a.*, cc.name AS category " .
"\nFROM #__rem_houses AS a" .
"\nLEFT JOIN #__rem_categories as hc on hc.iditem = a.id" .
"\nLEFT JOIN #__rem_main_categories AS cc ON cc.id = hc.idcat" .
"\nWHERE a.id = " . $house->id . "";
$database->setQuery($select);
$item_house = $database->loadObjectList();
echo $database->getErrorMsg();
$houseid = _REALESTATE_MANAGER_LABEL_PROPERTYID;
//for ($i = 0;$i < count($mail_to);$i++){
$username = ($userid == 0) ? $item_user[0]->name : _REALESTATE_MANAGER_LABEL_ANONYMOUS;
$message = str_replace("{username}", $username, _REALESTATE_MANAGER_EMAIL_NOTIFICATION_ADD_HOUSE);
$message = str_replace("{title}", $item_house[0]->htitle, $message);
$message = str_replace("{id}", $item_house[0]->houseid, $message);
$message = str_replace("{date}", $item_house[0]->date, $message);
$message = str_replace("{category}", $item_house[0]->category, $message);
mosMail($mosConfig_mailfrom, _REALESTATE_MANAGER_LABEL_ANONYMOUS, $mail_to, _REALESTATE_MANAGER_NEW_HOUSE_ADDED,
$message, true);
//}
}
//******************** end add send mail for admin ****************
$backlink = JRoute::_($_SERVER['HTTP_REFERER']);
HTML_realestatemanager :: showRentRequestThanks($params, $backlink, $currentcat);
}
static function secretImage() {
$session = JFactory::getSession();
$pas = $session->get('captcha_keystring', 'default');
$new_img = new PWImageRealestate();
$new_img->set_show_string($pas);
$new_img->get_show_image(2.2, array(mt_rand(0, 50), mt_rand(0, 50), mt_rand(0, 50)), array(mt_rand(200, 255),
mt_rand(200, 255), mt_rand(200, 255)));
exit;
}
function checkAccess_REM($accessgroupid, $recurse, $usersgroupid, $acl) {
$usersgroupid = explode(',', $usersgroupid);
//parse usergroups
$tempArr = array();
$tempArr = explode(',', $accessgroupid);
for ($i = 0; $i < count($tempArr); $i++) {
if (($tempArr[$i] == $usersgroupid OR in_array($tempArr[$i], $usersgroupid)) || $tempArr[$i] == -2) {
//allow access
return true;
} else {
if ($recurse == 'RECURSE') {
if (is_array($usersgroupid)) {
for ($j = 0; $j < count($usersgroupid); $j++) {
if (in_array($usersgroupid[$j], $tempArr))
return 1;
}
} else {
if (in_array($usersgroupid, $tempArr))
return 1;
}
}
}
} // end for
//deny access
return 0;
}
static function showTabs() {
global $mosConfig_live_site, $realestatemanager_configuration, $database, $Itemid, $my, $option;
$acl = JFactory::getACL();
$doc = JFactory::getDocument();
$doc->addStyleSheet($mosConfig_live_site . '/components/com_realestatemanager/includes/realestatemanager.css');
$menu = new mosMenu($database);
$menu->load($Itemid);
$params = new mosParameters($menu->params);
if ($option == "com_comprofiler") {
return;
}
$userid = $my->id;
$query = "SELECT u.id, u.name AS username FROM #__users AS u WHERE u.id = " . $userid;
$database->setQuery($query);
$ownerslist = $database->loadObjectList();
foreach ($ownerslist as $owner) {
$username = $owner->username;
}
$query = "SELECT h.owner_id FROM #__rem_houses AS h" .
" INNER JOIN #__rem_rent_request AS r ON h.id=r.fk_houseid " .
" WHERE h.owner_id = '" . $my->id . "' AND r.status=0";
$database->setQuery($query);
$ownerrenthouse = $database->loadObjectList();
foreach ($ownerrenthouse as $owner) {
$rent_owner_id = $owner->owner_id;
break;
}
$query = "SELECT h.owner_id FROM #__rem_houses AS h" .
" INNER JOIN #__rem_buying_request AS br ON h.id=br.fk_houseid" .
" WHERE h.owner_id = '" . $my->id . "'";
$database->setQuery($query);
$ownerbuyhouse = $database->loadObjectList();
foreach ($ownerbuyhouse as $owner) {
$buy_owner_id = $owner->owner_id;
break;
}
$query = "SELECT * FROM #__rem_rent AS r WHERE r.fk_userid = " . $my->id;
$database->setQuery($query);
$current_user_rent_history_array = $database->loadObjectList();
$check_for_show_rent_history = 0;
if (isset($current_user_rent_history_array)) {
foreach ($current_user_rent_history_array as $temp) {
if ($temp->fk_userid == $my->id)
$check_for_show_rent_history = 1;
}
}
if ($realestatemanager_configuration['cb_edit']['show']) {
$params->def('show_edit', 1);
$i = checkAccess_REM($realestatemanager_configuration['cb_edit']['registrationlevel'],
'NORECURSE', userGID_REM($my->id), $acl);
if ($i)
$params->def('show_edit_registrationlevel', 1);
}
if (isset($rent_owner_id) && $my->id == $rent_owner_id) {
if (($realestatemanager_configuration['cb_rent']['show'])) {
$params->def('show_rent', 1);
$i = checkAccess_REM($realestatemanager_configuration['cb_rent']['registrationlevel'],
'NORECURSE', userGID_REM($my->id), $acl);
if ($i)
$params->def('show_rent_registrationlevel', 1);
}
}
if (isset($buy_owner_id) && $my->id == $buy_owner_id) {
if (($realestatemanager_configuration['cb_buy']['show'])) {
$params->def('show_buy', 1);
$i = checkAccess_REM($realestatemanager_configuration['cb_buy']['registrationlevel'],
'NORECURSE', userGID_REM($my->id), $acl);
if ($i)
$params->def('show_buy_registrationlevel', 1);
}
}
if ($check_for_show_rent_history != 0) {
if (($realestatemanager_configuration['cb_history']['show'])) {
$params->def('show_history', 1);
$i = checkAccess_REM($realestatemanager_configuration['cb_history']['registrationlevel'],
'NORECURSE', userGID_REM($my->id), $acl);
if ($i)
$params->def('show_history_registrationlevel', 1);
}
}
HTML_realestatemanager::showTabs($params, $userid, $username, $comprofiler, $option);
}
static function editMyHouses($option) {
global $database, $Itemid, $mainframe, $my, $realestatemanager_configuration, $acl;
PHP_realestatemanager::addTitleAndMetaTags();
$is_edit_all_houses = false ;
if (checkAccess_REM($realestatemanager_configuration['option_edit']['registrationlevel'], 'RECURSE', userGID_REM($my->id), $acl)) {
$is_edit_all_houses = true ;
}
$menu = new JTableMenu($database);
$menu->load($Itemid);
$params = new mosParameters($menu->params);
$limit = $realestatemanager_configuration['page']['items'];
$limitstart = protectInjectionWithoutQuote('limitstart', 0);
$menu_name = set_header_name_rem($menu, $Itemid);
$params->def('header', $menu_name);
//check user
if ($my->email == null) {
mosRedirect("index.php", "Please login");
exit;
}
if( !$is_edit_all_houses ) $who_edit = " owner_id='$my->id' ";
else $who_edit = " ";
$database->setQuery("SELECT COUNT(id) FROM `#__rem_houses` " .
($who_edit == " " ? "" : " WHERE $who_edit"));
$total = $database->loadResult();
$pageNav = new JPagination($total, $limitstart, $limit); // for J 1.6
//getting my cars
$selectstring = "SELECT a.*, GROUP_CONCAT(cc.title SEPARATOR ', ') AS category,
l.id as rentid, l.rent_from as rent_from, l.rent_return as rent_return,
l.rent_until as rent_until, u.name AS editor" .
"\nFROM #__rem_houses AS a" .
"\nLEFT JOIN #__rem_categories AS hc ON hc.iditem = a.id" .
"\nLEFT JOIN #__categories AS cc ON cc.id = hc.idcat" .
"\nLEFT JOIN #__rem_rent AS l ON l.fk_houseid = a.id and l.rent_return is null " .
"\nLEFT JOIN #__users AS u ON u.id = a.checked_out" .
($who_edit == " " ? "" : " WHERE $who_edit") .
// "\nWHERE owner_id='" . $my->id . "' " .
"\nGROUP BY a.id" .
"\nORDER BY a.htitle " .
"\nLIMIT " . $pageNav->limitstart . "," . $pageNav->limit . ";";
$database->setQuery($selectstring);
$houses = $database->loadObjectList();
$rows = $database->loadObjectList();
$date = date(time());
foreach ($houses as $row) {
$check = strtotime($row->checked_out_time);
$remain = 7200 - ($date - $check);
if (($remain <= 0) && ($row->checked_out != 0)) {
$database->setQuery("UPDATE #__rem_houses SET checked_out=0,checked_out_time=0");
$database->query();
}
}
/****************************add block filter**********************************/
// $usermenu[] = mosHTML::makeOption('0', _REALESTATE_MANAGER_LABEL_SELECT_ALL_USERS);
// $selectstring = "SELECT usr.id,jei.owner_id, usr.username
// FROM #__rem_houses AS jei \n
// LEFT JOIN #__users AS usr ON usr.id = jei.owner_id" . "
// GROUP BY usr.id " . "\n
// ORDER BY usr.username ";
// $database->setQuery($selectstring);
// $users_list = $database->loadObjectList();
// $useranonimus = new stdClass();
// $useranonimus->username = 'anonymous';
// $useranonimus->owner_id = 'anonymous';
// if (count($users_list) >=1) {
// $users_list[] = $useranonimus;
// }
// if ($database->getErrorNum()) {
// echo $database->stderr();
// return false;
// }
// foreach($users_list as $item) {
// if ($item->owner_id == 0 and $item->username == '') continue;
// $usermenu[] = mosHTML::makeOption($item->owner_id, $item->username);
// }
// // print_r($usermenu);exit;
// $userlist = mosHTML::selectList($usermenu, 'select_owner_id', 'class="inputbox" size="1"
// onchange="bl_buttonClickSelectOwnerId();"', 'value', 'text', $select_owner_id);
/****************************end block filter**********************************/
$params->def('my01', "{loadposition com_realestatemanager_my_house_01,xhtml}");
$params->def('my02', "{loadposition com_realestatemanager_my_house_02,xhtml}");
$params->def('my03', "{loadposition com_realestatemanager_my_house_03,xhtml}");
$params->def('my04', "{loadposition com_realestatemanager_my_house_04,xhtml}");
$params->def('my05', "{loadposition com_realestatemanager_my_house_05,xhtml}");
HTML_realestatemanager::showMyHouses($houses, $params, $pageNav, $option);
}
static function deleteHouse() {
global $database, $my, $option, $Itemid, $mosConfig_absolute_path;
$do = protectInjectionWithoutQuote('task');
$bid = mosGetParam($_REQUEST, 'bid');
//get real user houses id
if (count($bid)) {
$database->setQuery("SELECT id FROM #__rem_houses WHERE owner_id='" . $my->id
. "' AND id IN (" . implode(', ', $bid) . ")");
if (version_compare(JVERSION, "3.0.0", "lt"))
$bid = $database->loadResultArray();
else
$bid = $database->loadColumn();
if (count($bid)) {
$bids = implode(',', $bid);
foreach ($bid as $h_id) {
$sql = "SELECT src FROM #__rem_video_source WHERE fk_house_id =". $h_id;
$database->setQuery($sql);
$videos = $database->loadColumn();
if ($videos) {
foreach($videos as $name) {
if (substr($name, 0, 4) != "http" && file_exists($mosConfig_absolute_path . $name))
unlink($mosConfig_absolute_path . $name);
}
}
$sql = "DELETE FROM #__rem_video_source
WHERE (fk_house_id = $h_id)";
$database->setQuery($sql);
$database->query();
$sql = "SELECT src FROM #__rem_track_source WHERE fk_house_id =". $h_id;
$database->setQuery($sql);
$track = $database->loadColumn();
if ($track) {
foreach($track as $name) {
if (substr($name, 0, 4) != "http" && file_exists($mosConfig_absolute_path . $name))
unlink($mosConfig_absolute_path . $name);
}
}
$sql = "DELETE FROM #__rem_track_source
WHERE (fk_house_id = $h_id)";
$database->setQuery($sql);
$database->query();
}
$database->setQuery("SELECT image_link FROM #__rem_houses WHERE id IN (" . $bids . ")");
$image_link = $database->loadObjectList();
for ($i = 0; $i < count($image_link); $i++) {
$image_link_name = substr($image_link[$i]->image_link, 0, strrpos($image_link[$i]->image_link, "."));
$image_link_type = substr($image_link[$i]->image_link, strrpos($image_link[$i]->image_link, "."));
@unlink($mosConfig_absolute_path . "/components/com_realestatemanager/photos/"
. $image_link_name . "_gallery" . $image_link_type);
@unlink($mosConfig_absolute_path . "/components/com_realestatemanager/photos/"
. $image_link_name . "_mini" . $image_link_type);
@unlink($mosConfig_absolute_path . "/components/com_realestatemanager/photos/"
. $image_link[$i]->image_link);
}
$database->setQuery("SELECT thumbnail_img, main_img FROM #__rem_photos WHERE fk_houseid IN (" . $bids . ")");
$del_photos = $database->loadObjectList();
for ($i = 0; $i <= count($del_photos); $i++) {
@unlink($mosConfig_absolute_path . "/components/com_realestatemanager/photos/"
. $del_photos[$i]->thumbnail_img);
@unlink($mosConfig_absolute_path . "/components/com_realestatemanager/photos/"
. $del_photos[$i]->main_img);
}
$database->setQuery("DELETE FROM #__rem_photos WHERE fk_houseid IN (" . $bids . ")");
$database->query();
$database->setQuery("DELETE FROM #__rem_review WHERE fk_houseid IN (" . $bids . ")");
$database->query();
$database->setQuery("DELETE FROM #__rem_categories WHERE iditem IN (" . $bids . ");");
$database->query();
$database->setQuery("DELETE FROM #__rem_houses WHERE id IN (" . $bids . ");");
$database->query();
$database->setQuery("DELETE FROM #__rem_feature_houses WHERE fk_houseid IN ($bids)");
$database->query();
}
}
if ($option == 'com_comprofiler') {
$redirect = JRoute::_("index.php?option=" . $option .
"&task=show_add&is_show_data=1&task=edit_my_houses&Itemid=" . $Itemid);
} else {
$redirect = JRoute::_("index.php?option=" . $option . "&task=edit_my_houses&Itemid=" . $Itemid);
}
mosRedirect($redirect);
}
static function publishHouse() {
global $database, $my, $option, $Itemid, $realestatemanager_configuration;
$do = protectInjectionWithoutQuote('task');
$bid = mosGetParam($_REQUEST, 'bid');
/**************************************if mass publish cheack count car***********************************************/
if (count($bid)){
$count_house_all = getCountHouseForSingleUserREM($my,$database,$realestatemanager_configuration);
$count_house_single_user = $count_house_all[0];
$count_house_for_single_group = $count_house_all[1];
if(($count_house_single_user + count($bid))<= $count_house_for_single_group){
$database->setQuery("SELECT id FROM #__rem_houses WHERE owner_id='" . $my->id .
"' AND id IN (" . implode(', ', $bid) . ")");
if (version_compare(JVERSION, '3.0', 'lt')){
$bid = $database->loadResultArray();
}else{
$bid = $database->loadColumn();
}
$bids = implode(',', $bid);
$database->setQuery("UPDATE #__rem_houses SET published = 1
\n WHERE owner_id='" . $my->id . "' AND id IN (" . $bids . ");");
$database->query();
}else{
echo "<script> alert('"._REALESTATE_MANAGER_YOU_CAN_PUBLISH_ONLY. " "
. $count_house_for_single_group. " " . _REALESTATE_MANAGER_ADMIN_COUNT_OF_ITEMS .
"'); window.history.go(-1); </script>\n";
exit;
}
}
/**************************************************************************************************/
if ($option == 'com_comprofiler') {
$redirect = JRoute::_("index.php?option=" . $option .
"&task=show_add&is_show_data=1&task=edit_my_houses&Itemid=" . $Itemid);
} else {
$redirect = JRoute::_("index.php?option=" . $option . "&task=edit_my_houses&Itemid=" . $Itemid);
}
mosRedirect($redirect);
}
static function unpublishHouse() {
global $database, $my, $option, $Itemid;
$do = protectInjectionWithoutQuote('task');
$bid = mosGetParam($_REQUEST, 'bid');
//get real user houses id
if (count($bid)) {
$database->setQuery("SELECT id FROM #__rem_houses WHERE owner_id='"
. $my->id . "' AND id IN (" . implode(', ', $bid) . ")");
if (version_compare(JVERSION, "3.0.0", "lt"))
$bid = $database->loadResultArray();
else
$bid = $database->loadColumn();
if (count($bid)) {
$bids = implode(',', $bid);
$database->setQuery("UPDATE #__rem_houses SET published = 0
\n WHERE owner_id='" . $my->id . "' AND id IN (" . $bids . ");");
$database->query();
}
}
if ($option == 'com_comprofiler') {
$redirect = JRoute::_("index.php?option=" . $option .
"&task=show_add&is_show_data=1&task=edit_my_houses&Itemid=" . $Itemid);
} else {
$redirect = JRoute::_("index.php?option=" . $option .
"&task=edit_my_houses&Itemid=" . $Itemid);
}
mosRedirect($redirect);
}
static function listRssCategories($languagelocale) {
global $mainframe, $database, $my, $acl, $LIMIT, $total, $langContent;
global $mosConfig_shownoauth, $mosConfig_live_site, $mosConfig_absolute_path;
global $cur_template, $Itemid, $realestatemanager_configuration;
$catid = mosGetParam($_REQUEST, 'catid', "");
$s = getWhereUsergroupsCondition("c");
if ($catid == "")
$where_catid = ""; else
$where_catid = " AND idcat=" . intval($catid);
if (isset($langContent)) {
$lang = $langContent;
// $query = "SELECT lang_code FROM #__languages WHERE sef = '$lang'";
// $database->setQuery($query);
// $lang = $database->loadResult();
$lang = " and ( h.language = '$lang' or h.language like 'all' or "
." h.language like '' or h.language like '*' or h.language is null) "
. " AND ( c.language = '$lang' or c.language like 'all' or "
." c.language like '' or c.language like '*' or c.language is null) ";
} else {
$lang = "";
}
$query = "SELECT c.id AS cid, c.title as ctitle, c.description as cdesc, h.id as bid, h.*, " .
" r.rent_from, r.rent_until, r.user_name, u.name as ownername " .
" FROM #__rem_main_categories AS c " .
" LEFT JOIN #__rem_categories AS hc ON hc.idcat=c.id" .
" LEFT JOIN #__rem_houses AS h ON h.id=hc.iditem " .
" LEFT JOIN #__users as u ON u.id=h.owner_id" .
" LEFT JOIN #__rem_rent AS r ON r.fk_houseid=h.id" .
" WHERE c.section='com_realestatemanager' " . $lang .
" AND c.published='1' " .
" AND h.published='1' " .
" AND h.approved='1'" .
" AND ($s)" .
$where_catid .
" GROUP BY h.id " .
" ORDER BY h.date desc";
$database->setQuery($query);
$cat_all = $database->loadObjectList();
// Parameters
$menu = new mosMenu($database);
$menu->load($Itemid);
$params = new mosParameters($menu->params);
if (($realestatemanager_configuration['contacts']['show'])) {
$params->def('show_contacts_line', 1);
$i = checkAccess_REM($realestatemanager_configuration['contacts']['registrationlevel'],
'NORECURSE', userGID_REM($my->id), $acl);
if ($i)
$params->def('show_contacts_registrationlevel', 1);
}
//take all efiles
HTML_realestatemanager :: showRssCategories($params, $cat_all, $catid);
}
static function ownersList($option) {
global $database, $my, $Itemid, $mainframe, $realestatemanager_configuration,
$langContent, $acl, $mosConfig_list_limit, $limit, $limitstart;
PHP_realestatemanager::addTitleAndMetaTags();
$symbol = protectInjectionWithoutQuote('letindex', '');
$symbol_str = '';
if ($symbol) {
$symbol_str = " AND (LOWER(u.name) LIKE '$symbol%' ) ";
}
//getting groups of user
$s = getWhereUsergroupsCondition("c");
$menu = new JTableMenu($database);
$menu->load($Itemid);
$params = new mosParameters($menu->params);
$database->setQuery("SELECT id FROM #__menu WHERE link='index.php?option=com_realestatemanager'");
$params->def('header', _REALESTATE_MANAGER_LABEL_TITLE_OWNERSLIST);
if (checkAccess_REM($realestatemanager_configuration['ownerslist']['registrationlevel'],
'NORECURSE', userGID_REM($my->id), $acl) &&
$realestatemanager_configuration['ownerslist']['show']) {
$params->def('ownerslist_show', 1);
}
if (isset($langContent)) {
$lang = $langContent;
// $query = "SELECT lang_code FROM #__languages WHERE sef = '$lang'";
// $database->setQuery($query);
// $lang = $database->loadResult();
$lang = " and ( rm.language = '$lang' or rm.language like 'all' or "
. " rm.language like '' or rm.language like '*' or rm.language is null) "
. " AND ( c.language = '$lang' or c.language like 'all' or "
. " c.language like '' or c.language like '*' or c.language is null) ";
} else {
$lang = "";
}
$db = JFactory::getDBO();
$query = "SELECT COUNT(DISTINCT u.email)
\nFROM #__rem_houses AS rm
\nLEFT JOIN #__rem_categories AS rc ON rc.iditem=rm.id
\nLEFT JOIN #__rem_main_categories AS c ON c.id=rc.idcat
\nLEFT JOIN #__users AS u ON rm.owner_id=u.id
\nWHERE rm.published=1 AND rm.approved=1 AND c.published=1" .
" AND ($s) $lang $symbol_str ";
$db->setQuery($query);
$total = $db->loadResult();
$pageNav = new JPagination($total, $limitstart, $limit); // for J 1.6
$query = "SELECT u.name, COUNT( rm.id ) AS houses
FROM #__rem_houses AS rm
LEFT JOIN #__rem_categories AS rc ON rc.iditem=rm.id
LEFT JOIN #__rem_main_categories AS c ON c.id=rc.idcat
LEFT JOIN #__users AS u ON rm.owner_id = u.id
WHERE rm.published=1 AND rm.approved=1 " . $lang . " and c.published=1 AND rm.owner_id>0
AND ($s) $symbol_str
GROUP BY u.name
ORDER BY u.name
LIMIT $pageNav->limitstart,$pageNav->limit;";
$db->setQuery($query);
$ownerslist = $db->loadObjectList();
$query = "SELECT DISTINCT UPPER( SUBSTRING( u.name, 1, 1 ) ) AS symb
FROM #__rem_houses AS rm
LEFT JOIN #__rem_categories AS rc ON rc.iditem=rm.id
LEFT JOIN #__rem_main_categories AS c ON c.id=rc.idcat
LEFT JOIN #__users AS u ON rm.owner_id = u.id
WHERE rm.published=1 AND rm.approved=1 AND c.published=1 AND rm.owner_id>0
AND ($s) $lang
ORDER BY u.name";
$db->setQuery($query);
$symb = $db->loadObjectList();
if (count($symb) > 0) {
$symb_list_str = '<div style="display:inline; margin-left:auto;margin-right:auto;">';
foreach ($symb as $symbol) {
$symb_list_str .= '<span style="padding:5px; ">' .
'<a href="index.php?option=' . $option .
'&task=owners_list' .
'&letindex=' . $symbol->symb . '&Itemid=' . $Itemid .
'">' . $symbol->symb . '</a></span>';
}
$symb_list_str.="</div>";
$params->def('symb_list_str', $symb_list_str);
}
$params->def('ownerlist01', "{loadposition com_realestatemanager_owner_list_01,xhtml}");
$params->def('ownerlist02', "{loadposition com_realestatemanager_owner_list_02,xhtml}");
$params->def('ownerlist03', "{loadposition com_realestatemanager_owner_list_03,xhtml}");
HTML_realestatemanager :: showOwnersList($params, $ownerslist, $pageNav);
}
static function viewUserHouses($option, $languagelocale) {
global $database, $my, $Itemid, $mainframe, $user_configuration,$task;
PHP_realestatemanager::addTitleAndMetaTags();
if (version_compare(JVERSION, '3.0', 'ge')) {
$menu = new JTableMenu($database);
$menu->load($Itemid);
$menu_name = set_header_name_rem($menu, $Itemid);
$params = new JRegistry;
$params->loadString($menu->params);
} else {
$menu = new mosMenu($database);
$menu->load($Itemid);
$menu_name = set_header_name_rem($menu, $Itemid);
$params = new mosParameters($menu->params);
}
$database->setQuery("SELECT id FROM #__menu WHERE link='index.php?option=com_realestatemanager'");
// if ($my->email == null && !(JRequest::getVar('owners'))) {
// mosRedirect("index.php?option=com_realestatemanager&Itemid=" . $Itemid, _REALESTATE_MANAGER_PLEASE_LOGIN);
// exit;
// }
$user = mosGetParam($_REQUEST, 'name');
if (!isset($user)) {
$params = @$mainframe->getParams();
$user = $params->get('username');
if (!isset($user) OR $user == '') {
if (isset($_REQUEST['name'])) {
$user = $_REQUEST['name'];
}elseif(isset($_REQUEST['userId'])) {
$user = intval($_REQUEST['userId']);
$query='SELECT * FROM #__users WHERE id='.$user;
$database->setQuery($query);
$info=$database->loadObject();
$user = $info->name;
} elseif (isset($_SESSION) && isset($_SESSION['rem_user']) ) {
$user = $_SESSION['rem_user']; // for SMS
} elseif (isset($_SESSION) && isset($_SESSION['sms_user']) ) {
$user = $_SESSION['sms_user']; // for SMS
} else {
$user = "Guest";
}
}
}
$anonym_flag = false;
if ($user == '' || $user == 'Guest' || $user == 'anonymous' || $user == _REALESTATE_MANAGER_LABEL_ANONYMOUS ) {
$user = _REALESTATE_MANAGER_LABEL_ANONYMOUS;
$anonym_flag = true;
}
$params->def('header', ((trim($menu_name)) ? $menu_name . ":" : "") .
_REALESTATE_MANAGER_LABEL_TITLE_USER_HOUSES);
$pathway = sefRelToAbs('index.php?option=' . $option . '&task=owners_list&Itemid=' . $Itemid);
$pathway_name = $user;
$pathway = sefRelToAbs('index.php?option=' . $option . '&task=view_user_houses&Itemid='
. $Itemid . '&name=' . $user);
// for 1.6
$path_way = $mainframe->getPathway();
$path_way->addItem($pathway_name, $pathway);
PHP_realestatemanager::searchHouses($option, 0, $option, $languagelocale, $user);
}
static function rentBeforeEndNotify($option) {
global $database, $realestatemanager_configuration, $Itemid, $mosConfig_mailfrom;
$send_email = 0;
if (($realestatemanager_configuration['rent_before_end_notify']) &&
trim($realestatemanager_configuration['rent_before_end_notify_email']) != ""
&& is_numeric($realestatemanager_configuration['rent_before_end_notify_days'])) {
$send_email = 1;
}
if ($send_email) {
$mail_to = explode(",", $realestatemanager_configuration['rent_before_end_notify_email']);
$zapros = "SELECT h.id, h.houseid, h.htitle, r.rent_from,r.rent_until,r.user_name,r.user_email " .
" FROM #__rem_houses as h " .
" left join #__rem_rent as r on r.fk_houseid = v.id " .
" WHERE r.rent_return IS NULL and TIMESTAMPDIFF(DAY, now(),rent_until ) = " .
$realestatemanager_configuration['rent_before_end_notify_days'] . " ; ";
$database->setQuery($zapros);
$item_house = $database->loadObjectList();
echo $database->getErrorMsg();
$message = _REALESTATE_MANAGER_HOUSES_EXPIRE_NOTICE . '<br /><br />';
foreach ($item_house as $item) {
$message .= str_replace("{username}", $item->user_name,
_REALESTATE_MANAGER_EMAIL_NOTIFICATION_RENT_BEFORE_END);
$message = str_replace("{user_email}", $item->user_email, $message);
$message = str_replace("{house_title}", $item->htitle, $message);
$message = str_replace("{ID}", $item->id, $message);
$message = str_replace("{PropertyID}", $item->houseid, $message);
}
if (count($item_house) > 0)
mosMail($mosConfig_mailfrom, _REALESTATE_MANAGER_RENT_EXPIRE_NOTICE, $mail_to,
_REALESTATE_MANAGER_RENT_EXPIRE_NOTICE, $message, true);
}
}
static function rent_requests($option, $bid) {
global $database, $my, $mainframe, $mosConfig_list_limit, $realestatemanager_configuration, $Itemid;
PHP_realestatemanager::addTitleAndMetaTags();
if ($my->email == null) {
mosRedirect("index.php?option=com_realestatemanager&Itemid=" . $Itemid, _REALESTATE_MANAGER_PLEASE_LOGIN);
exit;
}
$limit = $realestatemanager_configuration['page']['items'];
$limitstart = mosGetParam($_REQUEST, 'limitstart', 0);
$database->setQuery("SELECT count(*) FROM #__rem_houses AS a" .
"\nLEFT JOIN #__rem_rent_request AS l" .
"\nON l.fk_houseid = a.id" .
"\nWHERE l.status = 0 AND a.owner_id LIKE '$my->id'");
$total = $database->loadResult();
echo $database->getErrorMsg();
$pageNav = new JPagination($total, $limitstart, $limit); // for J 1.6
$database->setQuery("SELECT * FROM #__rem_houses AS a" .
"\nLEFT JOIN #__rem_rent_request AS l" .
"\nON l.fk_houseid = a.id" .
"\nWHERE l.status = 0 AND a.owner_id LIKE '$my->id'" .
"\nORDER BY l.id DESC" .
"\nLIMIT $pageNav->limitstart,$pageNav->limit;");
$rent_requests = $database->loadObjectList();
echo $database->getErrorMsg();
foreach ($rent_requests as $request) {
if($request->associate_house){
if($assoc_rem = getAssociateHouses($request->fk_houseid)){
$database->setQuery("SELECT group_concat(distinct a.htitle) FROM #__rem_houses AS a" .
"\n LEFT JOIN #__rem_rent_request AS l ON l.fk_houseid = a.id" .
"\n WHERE a.id in ($assoc_rem) AND a.id != $request->fk_houseid");
$request->title_assoc = $database->loadResult();
}
}
}
PHP_realestatemanager::showTabs();
HTML_realestatemanager :: showRequestRentHouses($option, $rent_requests, $pageNav);
}
static function decline_rent_requests($option, $bids) {
global $database, $realestatemanager_configuration, $Itemid;
$datas = array();
foreach ($bids as $bid) {
$rent_request = new mosRealEstateManager_rent_request($database);
$rent_request->load($bid);
$tmp = $rent_request->decline();
if ($tmp != null) {
echo "<script> alert('" . $tmp . "'); window.history.go(-1); </script>\n";
exit;
}
foreach ($datas as $c => $data) {
if ($rent_request->user_email == $data['email']) {
$datas[$c]['ids'][] = $rent_request->fk_houseid;
continue 2;
}
}
$datas[] = array('email' => $rent_request->user_email,
'name' => $rent_request->user_name, 'id' => $rent_request->fk_houseid);
}
if ($realestatemanager_configuration['rent_answer']) {
if (isset($datas[0]['name']) || isset($datas[0]['email']) || isset($datas[0]['id'])) {
PHP_realestatemanager::sendMailRentRequest($datas, _REALESTATE_MANAGER_ADMIN_CONFIG_RENT_ANSWER_DECLINED);
}
}
if ($option == "com_comprofiler") {
mosRedirect("index.php?option=" . $option .
"&task=rent_requests&is_show_data=1&Itemid=" . $Itemid);
} else {
mosRedirect("index.php?option=" . $option .
"&task=rent_requests&Itemid=" . $Itemid);
}
}
static function accept_rent_requests($option, $bids) {
global $database, $realestatemanager_configuration, $Itemid;
$datas = array();
foreach ($bids as $bid) {
$rent_request = new mosRealEstateManager_rent_request($database);
$rent_request->load($bid);
$tmp = $rent_request->accept();
if ($tmp != null) {
echo "<script> alert('" . $tmp . "'); window.history.go(-1); </script>\n";
exit;
}
foreach ($datas as $c => $data) {
if ($rent_request->user_email == $data['email']) {
$datas[$c]['ids'][] = $rent_request->fk_houseid;
continue 2;
}
}
$datas[] = array('email' => $rent_request->user_email,
'name' => $rent_request->user_name, 'id' => $rent_request->fk_houseid);
}
if ($realestatemanager_configuration['rent_answer']) {
if (isset($datas[0]['name']) || isset($datas[0]['email']) || isset($datas[0]['id'])) {
PHP_realestatemanager::sendMailRentRequest($datas, _REALESTATE_MANAGER_ADMIN_CONFIG_RENT_ANSWER_ACCEPTED);
}
}
if ($option == "com_comprofiler") {
mosRedirect("index.php?option=" . $option .
"&task=rent_requests&is_show_data=1&Itemid=" . $Itemid);
} else {
mosRedirect("index.php?option=" . $option . "&task=rent_requests&Itemid=" . $Itemid);
}
}
static function sendMailRentRequest($datas, $answer) {
global $database, $mosConfig_mailfrom, $realestatemanager_configuration;
$conf = JFactory::getConfig();
foreach ($datas as $key => $data) {
$mess = null;
$zapros = "SELECT htitle FROM #__rem_houses WHERE id=" . $data['id'];
$database->setQuery($zapros);
$item = $database->loadResult();
echo $database->getErrorMsg();
$database->setQuery("SELECT u.name AS ownername,u.email as owneremail
\nFROM #__users AS u
\nLEFT JOIN #__rem_houses AS rm ON rm.owner_id=u.id
\nWHERE rm.id=" . $data['id']);
echo $database->getErrorMsg();
$ownerdata = $database->loadObjectList();
$datas[$key]['title'] = $item;
$message = _REALESTATE_MANAGER_EMAIL_NOTIFICATION_RENT_REQUEST_ANSWER;
$message = str_replace("{title}", $datas[$key]['title'], $message);
$message = str_replace("{answer}", $answer, $message);
$message = str_replace("{username}", $datas[$key]['name'], $message);
if ($answer == _REALESTATE_MANAGER_ADMIN_CONFIG_RENT_ANSWER_ACCEPTED) {
$message = str_replace("{ownername}", $ownerdata[0]->ownername, $message);
$message = str_replace("{owneremail}", $ownerdata[0]->owneremail, $message);
} else {
$message = str_replace("{ownername}", '', $message);
$message = str_replace("{owneremail}", '', $message);
}
mosMail($mosConfig_mailfrom, $conf->_registry['config']['data']->fromname, $data['email']
,_REALESTATE_MANAGER_EMAIL_RENT_ANSWER_SUBJECT, $message, true);
}
}
static function sendMailBuyingRequest($datas, $answer) {
global $database, $mosConfig_mailfrom, $realestatemanager_configuration;
$conf = JFactory::getConfig();
foreach ($datas as $key => $data) {
$mess = null;
$zapros = "SELECT htitle FROM #__rem_houses WHERE id=" . $data['id'];
$database->setQuery($zapros);
$item = $database->loadResult();
echo $database->getErrorMsg();
$database->setQuery("SELECT u.name AS ownername,u.email AS owneremail
\nFROM #__users AS u
\nLEFT JOIN #__rem_houses AS rm ON rm.owner_id=u.id
\nWHERE rm.id=" . $data['id']);
echo $database->getErrorMsg();
$ownerdata = $database->loadObjectList();
$datas[$key]['title'] = $item;
$message = _REALESTATE_MANAGER_EMAIL_NOTIFICATION_BUYING_REQUEST_ANSWER;
$message = str_replace("{title}", $datas[$key]['title'], $message);
$message = str_replace("{answer}", $answer, $message);
$message = str_replace("{username}", $datas[$key]['name'], $message);
if ($answer == _REALESTATE_MANAGER_ADMIN_CONFIG_RENT_ANSWER_ACCEPTED) {
$message = str_replace("{ownername}", $ownerdata[0]->ownername, $message);
$message = str_replace("{owneremail}", $ownerdata[0]->owneremail, $message);
} else {
$message = str_replace("{ownername}", '', $message);
$message = str_replace("{owneremail}", '', $message);
}
mosMail($mosConfig_mailfrom, $conf->_registry['config']['data']->fromname, $data['email'],
_REALESTATE_MANAGER_EMAIL_RENT_ANSWER_SUBJECT, $message, true);
}
}
static function buying_requests($option) {
global $database, $mainframe, $my, $mosConfig_list_limit, $realestatemanager_configuration, $Itemid;
if ($my->email == null) {
mosRedirect("index.php?option=com_realestatemanager&Itemid=" . $Itemid, _REALESTATE_MANAGER_PLEASE_LOGIN);
exit;
}
$limit = $realestatemanager_configuration['page']['items'];
$limitstart = mosGetParam($_REQUEST, 'limitstart', 0);
$database->setQuery("SELECT count(*) FROM #__rem_houses AS a" .
"\n LEFT JOIN #__rem_buying_request AS s" .
"\n ON s.fk_houseid = a.id" .
"\n WHERE s.status = 0 AND a.owner_id LIKE '" . $my->id . "'");
$total = $database->loadResult();
echo $database->getErrorMsg();
$pageNav = new JPagination($total, $limitstart, $limit); // for J 1.6
$database->setQuery("SELECT * FROM #__rem_houses AS a" .
"\n LEFT JOIN #__rem_buying_request AS s" .
"\n ON s.fk_houseid = a.id" .
"\n WHERE s.status = 0 AND a.owner_id LIKE '" . $my->id . "'" .
"\n ORDER BY s.id DESC" .
"\n LIMIT " . $pageNav->limitstart . "," . $pageNav->limit . ";");
$buy_requests = $database->loadObjectList();
foreach ($buy_requests as $request) {
if($request->associate_house){
if($assoc_rem = getAssociateHouses($request->fk_houseid)){
$database->setQuery("SELECT group_concat(distinct a.htitle) FROM #__rem_houses AS a" .
"\n LEFT JOIN #__rem_buying_request AS s ON s.fk_houseid = a.id" .
"\n WHERE a.id in ($assoc_rem) AND a.id != $request->fk_houseid");
$request->tiitle_assoc = $database->loadResult();
}
}
}
echo $database->getErrorMsg();
PHP_realestatemanager::showTabs();
HTML_realestatemanager::showRequestBuyingHouses($option, $buy_requests, $pageNav, $Itemid);
}
static function accept_buying_requests($option, $bids) {
global $database, $Itemid, $realestatemanager_configuration;
foreach ($bids as $bid) {
$buying_request = new mosRealEstateManager_buying_request($database);
$buying_request->load($bid);
$datas[] = array('name' => $buying_request->customer_name,
'email' => $buying_request->customer_email,
'id' => $buying_request->fk_houseid);
$buying_request->delete();
/* if ($tmp!=null){
echo "<script> alert('".$tmp."'); window.history.go(-1); </script>\n";
exit;
} */
}
if ($realestatemanager_configuration['buy_answer']) {
if (isset($datas[0]['name']) || isset($datas[0]['email']) || isset($datas[0]['id'])) {
PHP_realestatemanager::sendMailBuyingRequest($datas, _REALESTATE_MANAGER_ADMIN_CONFIG_RENT_ANSWER_ACCEPTED);
}
}
if ($option == "com_comprofiler") {
mosRedirect(JRoute::_("index.php?option=" . $option .
"&task=buying_requests&is_show_data=1&Itemid=" . $Itemid));
} else {
mosRedirect(JRoute::_("index.php?option=" . $option .
"&task=buying_requests&Itemid=" . $Itemid));
}
}
static function decline_buying_requests($option, $bids) {
global $database, $Itemid;
foreach ($bids as $bid) {
$buying_request = new mosRealEstateManager_buying_request($database);
$buying_request->load($bid);
$datas[] = array('name' => $buying_request->customer_name,
'email' => $buying_request->customer_email,
'id' => $buying_request->fk_houseid
);
$tmp = $buying_request->decline();
if ($tmp != null) {
echo "<script> alert('" . $tmp . "'); window.history.go(-1); </script>\n";
exit();
}
}
if ($realestatemanager_configuration['buy_answer']) {
if (isset($datas[0]['name']) || isset($datas[0]['email']) || isset($datas[0]['id'])) {
PHP_realestatemanager::sendMailBuyingRequest($datas, _REALESTATE_MANAGER_ADMIN_CONFIG_RENT_ANSWER_DECLINED);
}
}
if ($option == "com_comprofiler") {
mosRedirect("index.php?option=" . $option .
"&task=buying_requests&is_show_data=1&Itemid=" . $Itemid);
} else {
mosRedirect("index.php?option=" . $option . "&task=buying_requests&Itemid=" . $Itemid);
}
}
static function rent($option, $bid) {
global $database, $my;
PHP_realestatemanager::addTitleAndMetaTags();
if (!is_array($bid) || count($bid) !== 1) {
echo "<script> alert('". _REALESTATE_MANAGER_ADMIN_SELECT_ONE_ITEM .
"'); window.history.go(-1);</script>\n";
exit;
}
if (!array_key_exists("bid", $_REQUEST)) {
echo "<script> alert('" . _REALESTATE_MANAGER_TOOLBAR_RENT_HOUSES .
"'); window.history.go(-1);</script>\n";
exit;
}
$bid_house = implode(',', $bid);
$select = "SELECT a.*, cc.name AS category, l.id as rentid, l.rent_from as rent_from, " .
"l.rent_return as rent_return, l.rent_until as rent_until, " .
"l.user_name as user_name, l.user_email as user_email " .
"\nFROM #__rem_houses AS a" .
"\nLEFT JOIN #__rem_categories as hc on hc.iditem = a.id" .
"\nLEFT JOIN #__rem_main_categories AS cc ON cc.id = hc.idcat" .
"\nLEFT JOIN #__rem_rent AS l ON l.id = a.fk_rentid" .
"\nWHERE a.id = $bid_house";
$database->setQuery($select);
$house1 = $database->loadObject();
if ($house1->listing_type != 1) {
?>
<script type = "text/JavaScript" language = "JavaScript">
alert("<?php echo _REALESTATE_MANAGER_ADMIN_NOT_FOR_RENT ?>");
window.history.go(-1);
</script>
<?php
exit;
}
$bids = implode(',', $bid);
$bids = getAssociateHouses($bids);
$houses_assoc[]= $house1;
if($bids){
$select = "SELECT a.*, cc.name AS category, l.id as rentid, l.rent_from as rent_from, " .
"l.rent_return as rent_return, l.rent_until as rent_until, " .
"l.user_name as user_name, l.user_email as user_email " .
"\nFROM #__rem_houses AS a" .
"\nLEFT JOIN #__rem_categories as hc on hc.iditem = a.id" .
"\nLEFT JOIN #__rem_main_categories AS cc ON cc.id = hc.idcat" .
"\nLEFT JOIN #__rem_rent AS l ON l.id = a.fk_rentid" .
"\nWHERE a.id in ($bids)";
$database->setQuery($select);
$houses_assoc = $database->loadObjectList();
//for rent or not
$count = count($houses_assoc);
for ($i = 0; $i < $count; $i++) {
if ($houses_assoc[$i]->listing_type != 1) {
?>
<script type = "text/JavaScript" language = "JavaScript">
alert("<?php echo _REALESTATE_MANAGER_ADMIN_NOT_FOR_RENT_ASOC ?>");
window.history.go(-1);
</script>
<?php
exit;
}
}
}
// get list of categories
$userlist[] = mosHTML :: makeOption('-1', '----------');
$database->setQuery("SELECT id AS value, name AS text from #__users ORDER BY name");
$userlist = array_merge($userlist, $database->loadObjectList());
$usermenu = mosHTML :: selectList($userlist, 'userid', 'class="inputbox" size="1"', 'value', 'text', '-1');
HTML_realestatemanager :: showRentHouses($option, $house1, $houses_assoc, $usermenu, "rent");
}
static function saveRent($option, $bids, $task = "") {
global $database, $Itemid, $realestatemanager_configuration;
$checkh = mosGetParam($_REQUEST, 'checkHouse');
if ($checkh != "on") {
echo "<script> alert('". _REALESTATE_MANAGER_ADMIN_SELECT_ONE_ITEM .
"'); window.history.go(-1);</script>\n";
exit;
}
/////////////////////
if (isset($id)
&& $id != 0
&& $my->id
!= $house->owner_id
) {
mosRedirect('index.php?option=com_realestatemanager&Itemid=' . $Itemid);
exit;
}
$data = JFactory::getDBO();
$houseid = protectInjectionWithoutQuote('houseid');
$id = protectInjectionWithoutQuote('id');
$rent_from = protectInjectionWithoutQuote('rent_from');
$rent_until = protectInjectionWithoutQuote('rent_until');
$rent_from = data_transform_rem($rent_from);
$rent_until = data_transform_rem($rent_until);
$ids[] = $id ;
$ids = implode(',', $ids);
$ids = getAssociateHouses($ids);
if($ids == "") $ids = $id;
$ids = explode(',', $ids);
if( $task == "edit_rent" ){
$ids = explode(',', $bids[0]);
}
for($i = 0, $n = count($ids); $i < $n; $i++){
$rent = new mosRealEstateManager_rent($database);
if($task == "edit_rent" ){
$rent->load($ids[$i]);
$fk_houseid = $rent->fk_houseid;
} else {
$fk_houseid = $ids[$i] ;
}
$query = "SELECT * FROM #__rem_rent where fk_houseid= " . $fk_houseid . " AND rent_return is NULL ";
$database->setQuery($query);
$rentTerm = $database->loadObjectList();
$rent_from = substr($rent_from, 0, 10);
$rent_until = substr($rent_until, 0, 10);
foreach ($rentTerm as $oneTerm){
if($task == "edit_rent" ){
if ($ids[$i] == $oneTerm->id)
continue;
}
$oneTerm->rent_from = substr($oneTerm->rent_from, 0, 10);
$oneTerm->rent_until = substr($oneTerm->rent_until, 0, 10);
$returnMessage = checkRentDayNightREM (($oneTerm->rent_from),($oneTerm->rent_until),
$rent_from, $rent_until, $realestatemanager_configuration);
if(strlen($returnMessage) > 0){
echo "<script> alert('$returnMessage'); window.history.go(-1); </script>\n";
exit;
}
}
$rent->rent_from = $rent_from;
$rent->rent_until = $rent_until;
$rent->fk_houseid = $fk_houseid;
$userid = protectInjectionWithoutQuote('userid');
if ($userid == "-1") {
$rent->user_name = mosGetParam($_REQUEST, 'user_name', '');
$rent->user_email = mosGetParam($_REQUEST, 'user_email', '');
} else {
$rent->fk_userid = $userid;
$query = "SELECT name FROM #__users WHERE id=" . $userid . "";
$database->setQuery($query);
$user_name_for_rent = $database->loadObjectList();
$rent->user_name = $user_name_for_rent[0]->name;
$rent->user_email = mosGetParam($_REQUEST, 'user_email', '');
}
if (!$rent->check($rent)) {
echo "<script> alert('" . addslashes($rent->getError()) .
"'); window.history.go(-1); </script>\n";
exit();
}
if (!$rent->store()) {
echo "<script> alert('" . addslashes($rent->getError()) .
"'); window.history.go(-1); </script>\n";
exit();
}
$rent->checkin();
$house = new mosRealEstateManager($database);
$house->load($fk_houseid);
$house->fk_rentid = $rent->id;
$house->store();
$house->checkin();
}
if ($option == 'com_comprofiler')
$link_for_mosRedirect = JRoute::_("index.php?option=" . $option .
"&task=edit_my_houses&Itemid=" . $Itemid); else
$link_for_mosRedirect = JRoute::_("index.php?option=" . $option .
"&task=edit_my_houses&Itemid=" . $Itemid);
mosRedirect($link_for_mosRedirect);
}
static function edit_rent($option, $bid) {
global $database, $my;
if (!is_array($bid) || count($bid) !== 1) {
echo "<script> alert('". _REALESTATE_MANAGER_ADMIN_SELECT_ONE_ITEM ."'); window.history.go(-1);</script>\n";
exit;
}
$bid_house = implode(',', $bid);
$select = "SELECT a.*, cc.name AS category, l.id as rentid, l.rent_from as rent_from, " .
"l.rent_return as rent_return, l.rent_until as rent_until, " .
"l.user_name as user_name, l.user_email as user_email " .
"\nFROM #__rem_houses AS a" .
"\nLEFT JOIN #__rem_categories as hc on hc.iditem = a.id" .
"\nLEFT JOIN #__rem_main_categories AS cc ON cc.id = hc.idcat" .
"\nLEFT JOIN #__rem_rent AS l ON l.fk_houseid = a.id" .
"\nWHERE a.id = $bid_house";
$database->setQuery($select);
$house1 = $database->loadObject();
if ($house1->listing_type != 1) {
?>
<script type = "text/JavaScript" language = "JavaScript">
alert("<?php echo _REALESTATE_MANAGER_ADMIN_NOT_FOR_RENT ?>");
window.history.go(-1);
</script>
<?php
exit;
}
$bids = implode(',', $bid);
$bids = getAssociateHouses($bids);
if($bids == "") $bids = implode(',', $bid);
$houses_rents_assoc= array();
$title_assoc = array();
if($bids){
$select = "SELECT a.*, cc.name AS category, l.id as rentid, l.rent_from as rent_from, " .
"l.rent_return as rent_return, l.rent_until as rent_until, " .
"l.user_name as user_name, l.user_email as user_email " .
"\nFROM #__rem_houses AS a" .
"\nLEFT JOIN #__rem_categories as hc on hc.iditem = a.id" .
"\nLEFT JOIN #__rem_main_categories AS cc ON cc.id = hc.idcat" .
"\nLEFT JOIN #__rem_rent AS l ON l.fk_houseid = a.id" .
"\nWHERE a.id in ($bids)";
$database->setQuery($select);
$houses_rents_assoc = $database->loadObjectList();
$select = "SELECT a.htitle " .
"\nFROM #__rem_houses AS a" .
"\nLEFT JOIN #__rem_rent AS l ON l.fk_houseid = a.id" .
"\nWHERE a.id in ($bids)";
$database->setQuery($select);
$title_assoc = $database->loadObjectList();
$count = count($houses_rents_assoc);
for ($i = 0; $i < $count; $i++) {
if ($houses_rents_assoc[$i]->listing_type != 1) {
?>
<script type = "text/JavaScript" language = "JavaScript">
alert("<?php echo _REALESTATE_MANAGER_ADMIN_NOT_FOR_RENT_ASOC ?>");
window.history.go(-1);
</script>
<?php
exit;
}
}
$is_rent_out = false;
for ($i = 0; $i < count($houses_rents_assoc); $i++) {
if ( $houses_rents_assoc[$i]->rent_from != '' && $houses_rents_assoc[$i]->rent_return == '' )
{
$is_rent_out = true ;
break ;
}
}
if ( !$is_rent_out ){
?>
<script type = "text/JavaScript" language = "JavaScript">
alert("<?php echo _REALESTATE_MANAGER_ADMIN_HOUSE_NOT_IN_RENT ?>");
window.history.go(-1);
</script>
<?php
exit;
}
//check rent_return == null count for all assosiate
$ids = explode(',', $bids);
$rent_count = -1;
$all_assosiate_rent = array();
$count = count($ids);
for ($i = 0; $i < $count; $i++) {
$query = "SELECT * FROM #__rem_rent WHERE fk_houseid = " . $ids[$i] .
" and rent_return is null ORDER BY rent_from";
// print_r($query);
$database->setQuery($query);
$all_assosiate_rent_item = $database->loadObjectList();
if ( $rent_count != -1 && $rent_count != count($all_assosiate_rent_item) )
{
?>
<script type = "text/JavaScript" language = "JavaScript">
alert("<?php echo _REALESTATE_MANAGER_ADMIN_RENT_ASSOCIATED ?>");
window.history.go(-1);
</script>
<?php
exit;
}
$rent_count = count($all_assosiate_rent_item);
// print_r($rent_count);exit;
$all_assosiate_rent[] = $all_assosiate_rent_item;
}
}
// get list of users
$userlist[] = mosHTML :: makeOption('-1', '----------');
$database->setQuery("SELECT id AS value, name AS text from #__users ORDER BY name");
$userlist = array_merge($userlist, $database->loadObjectList());
$usermenu = mosHTML :: selectList($userlist, 'userid', 'class="inputbox" size="1"', 'value', 'text', '-1');
HTML_realestatemanager :: editRentHouses($option, $house1, $houses_rents_assoc,
$title_assoc, $usermenu, $all_assosiate_rent, "edit_rent");
}
static function rent_return($option, $bid) {
global $database, $my, $Itemid;
PHP_realestatemanager::addTitleAndMetaTags();
if (!is_array($bid) || count($bid) !== 1) {
echo "<script> alert('". _REALESTATE_MANAGER_ADMIN_SELECT_ONE_ITEM .
"'); window.history.go(-1);</script>\n";
exit;
}
$bid_house = implode(',', $bid);
$select = "SELECT a.*, cc.name AS category, l.id as rentid, l.rent_from as rent_from, " .
"l.rent_return as rent_return, l.rent_until as rent_until, " .
"l.user_name as user_name, l.user_email as user_email " .
"\nFROM #__rem_houses AS a" .
"\nLEFT JOIN #__rem_categories as hc on hc.iditem = a.id" .
"\nLEFT JOIN #__rem_main_categories AS cc ON cc.id = hc.idcat" .
"\nLEFT JOIN #__rem_rent AS l ON l.fk_houseid = a.id" .
"\nWHERE a.id = $bid_house";
$database->setQuery($select);
$house1 = $database->loadObject();
if ($house1->listing_type != 1) {
?>
<script type = "text/JavaScript" language = "JavaScript">
alert("<?php echo _REALESTATE_MANAGER_ADMIN_NOT_FOR_RENT ?>");
window.history.go(-1);
</script>
<?php
exit;
}
$bids = getAssociateHouses($bid_house);
if($bids == "") $bids = $bid_house;
$houses_rents_assoc = array();
$title_assoc = array();
if($bids){
$select = "SELECT a.*, cc.name AS category, l.id as rentid, l.rent_from as rent_from, " .
"l.rent_return as rent_return, l.rent_until as rent_until, " .
"l.user_name as user_name, l.user_email as user_email " .
"\nFROM #__rem_houses AS a" .
"\nLEFT JOIN #__rem_categories as hc on hc.iditem = a.id" .
"\nLEFT JOIN #__rem_main_categories AS cc ON cc.id = hc.idcat" .
"\nLEFT JOIN #__rem_rent AS l ON l.fk_houseid = a.id" .
"\nWHERE a.id in ($bids)";
$database->setQuery($select);
$houses_rents_assoc = $database->loadObjectList();
$select = "SELECT a.htitle " .
"\nFROM #__rem_houses AS a" .
"\nLEFT JOIN #__rem_rent AS l ON l.fk_houseid = a.id" .
"\nWHERE a.id in ($bids)";
$database->setQuery($select);
$title_assoc = $database->loadObjectList();
$count = count($houses_rents_assoc);
for ($i = 0; $i < $count; $i++) {
if ($houses_rents_assoc[$i]->listing_type != 1) {
?>
<script type = "text/JavaScript" language = "JavaScript">
alert("<?php echo _REALESTATE_MANAGER_ADMIN_NOT_FOR_RENT_ASOC ?>");
window.history.go(-1);
</script>
<?php
exit;
}
}
$is_rent_out = false;
for ($i = 0; $i < count($houses_rents_assoc); $i++) {
if ( $houses_rents_assoc[$i]->rent_from != '' && $houses_rents_assoc[$i]->rent_return == '' )
{
$is_rent_out = true ;
break ;
}
}
if (!$is_rent_out )
{
?>
<script type = "text/JavaScript" language = "JavaScript">
alert("<?php echo _REALESTATE_MANAGER_ADMIN_ALERT_NOT_IN_RENT ?>");
window.history.go(-1);
</script>
<?php
exit;
}
//check rent_return == null count for all assosiate
$ids = explode(',', $bids);
$rent_count = -1;
$all_assosiate_rent = array();
$count = count($ids);
for ($i = 0; $i < $count; $i++) {
$query = "SELECT * FROM #__rem_rent WHERE fk_houseid = " . $ids[$i] .
" and rent_return is null ORDER BY rent_from";
// print_r($query);
$database->setQuery($query);
$all_assosiate_rent_item = $database->loadObjectList();
if ( $rent_count != -1 && $rent_count != count($all_assosiate_rent_item) )
{
?>
<script type = "text/JavaScript" language = "JavaScript">
alert("<?php echo _REALESTATE_MANAGER_ADMIN_RENT_ASSOCIATED ?>");
window.history.go(-1);
</script>
<?php
exit;
}
$rent_count = count($all_assosiate_rent_item);
// print_r($rent_count);exit;
$all_assosiate_rent[] = $all_assosiate_rent_item;
}
}
// get list of users
$userlist[] = mosHTML :: makeOption('-1', '----------');
$database->setQuery("SELECT id AS value, name AS text from #__users ORDER BY name");
$userlist = array_merge($userlist, $database->loadObjectList());
$usermenu = mosHTML :: selectList($userlist, 'userid', 'class="inputbox" size="1"', 'value', 'text', '-1');
HTML_realestatemanager :: editRentHouses($option, $house1, $houses_rents_assoc,
$title_assoc, $usermenu, $all_assosiate_rent, "rent_return");
}
static function saveRent_return($option, $lids) {
global $database, $my, $Itemid;
$houseid = mosGetParam($_REQUEST, 'houseid');
$id = mosGetParam($_REQUEST, 'id');
$rent_from = mosGetParam($_REQUEST, 'rent_from');
$rent_until = mosGetParam($_REQUEST, 'rent_until');
$check_vids = implode(',', $lids);
if ($check_vids == 0 || count($lids) > 1)
{
echo "<script> alert('". _REALESTATE_MANAGER_ADMIN_SELECT_ONE_ITEM .
"'); window.history.go(-1);</script>\n";
exit;
}
$r_ids = explode(',', $lids[0]);
$rent = new mosRealEstateManager_rent($database);
for ($i = 0, $n = count($r_ids); $i < $n; $i++) {
$rent->load($r_ids[$i]);
if ($rent->rent_return != null) {
echo "<script> alert('". _REALESTATE_MANAGER_ADMIN_RENT_ALERT_RETURNED .
"'); window.history.go(-1);</script>\n";
exit;
}
$rent->rent_return = date("Y-m-d H:i:s");
if (!$rent->check($rent)) {
echo "<script> alert('" . $rent->getError() . "'); window.history.go(-1); </script>\n";
exit;
}
if (!$rent->store()) {
echo "<script> alert('" . $rent->getError() . "'); window.history.go(-1); </script>\n";
exit;
}
$rent->checkin();
$is_update_house_lend = true;
if ($is_update_house_lend) {
$house = new mosRealEstateManager($database);
$house->load($id);
$query = "SELECT * FROM #__rem_rent where fk_houseid= " . $id . " AND rent_return is NULL";
$database->setQuery($query);
$info_rents = $database->loadObjectList();
if (isset($info_rents[0])) {
$house->fk_rentid = $info_rents[0]->id;
$is_update_house_lend = FALSE;
} else {
$house->fk_rentid = 0;
}
$house->store();
$house->checkin();
}
}
if ($option == 'com_comprofiler') {
$link_for_mosRedirect = JRoute::_("index.php?option=" . $option .
"&task=edit_my_houses&Itemid=" . $Itemid);
} else {
$link_for_mosRedirect = JRoute::_("index.php?option=" . $option .
"&task=edit_my_houses&Itemid=" . $Itemid);
}
mosRedirect($link_for_mosRedirect);
}
static function rent_history($option) {
global $database, $my, $Itemid, $realestatemanager_configuration, $mosConfig_list_limit;
PHP_realestatemanager::addTitleAndMetaTags();
if ($my->email == null) {
mosRedirect("index.php?option=com_realestatemanager&Itemid=" .
$Itemid, _REALESTATE_MANAGER_PLEASE_LOGIN);
exit;
}
$menu = new mosMenu($database);
$menu->load($Itemid);
$params = new mosParameters($menu->params);
$limit = $realestatemanager_configuration['page']['items'];
$limitstart = mosGetParam($_REQUEST, 'limitstart', 0);
$database->setQuery("SELECT count(*) FROM #__rem_rent AS l " .
"\nLEFT JOIN #__rem_houses AS a ON a.id = l.fk_houseid" .
"\nWHERE l.fk_userid = '" . $my->id . "'");
$total = $database->loadResult();
echo $database->getErrorMsg();
$pageNav = new JPagination($total, $limitstart, $limit); // for J 1.6
$query = "SELECT l.*,a.* FROM #__rem_rent AS l " .
"\nLEFT JOIN #__rem_houses AS a ON a.id = l.fk_houseid" .
"\nWHERE l.fk_userid = '" . $my->id . "' ORDER BY l.id DESC LIMIT " .
$pageNav->limitstart . "," . $pageNav->limit . ";";
$database->setQuery($query);
$houses = $database->loadObjectList();
PHP_realestatemanager::showTabs();
HTML_realestatemanager :: showRentHistory($option, $houses, $pageNav);
}
static function ShowAllHouses($layout = "default", $printItem) {
global $mainframe, $database, $acl, $my, $langContent;
global $mosConfig_shownoauth, $mosConfig_live_site, $mosConfig_absolute_path;
global $cur_template, $Itemid, $realestatemanager_configuration,
$mosConfig_list_limit, $limit, $total, $limitstart;
PHP_realestatemanager::addTitleAndMetaTags();
if (isset($langContent)) {
$lang = $langContent;
// $query = "SELECT lang_code FROM #__languages WHERE sef = '$lang'";
// $database->setQuery($query);
// $lang = $database->loadResult();
$lang = " and ( h.language = '$lang' or h.language like 'all' or "
." h.language like '' or h.language like '*' or h.language is null) "
. " AND ( c.language = '$lang' or c.language like 'all' or "
." c.language like '' or c.language like '*' or c.language is null) ";
} else {
$lang = "";
}
//sorting
$item_session = JFactory::getSession();
$sort_arr = $item_session->get('rem_housesort', '');
if (is_array($sort_arr)) {
$tmp1 = protectInjectionWithoutQuote('order_direction');
if ($tmp1 != '')
$sort_arr['order_direction'] = $tmp1;
$tmp1 = protectInjectionWithoutQuote('order_field');
if ($tmp1 != '')
$sort_arr['order_field'] = $tmp1;
$item_session->set('rem_housesort', $sort_arr);
} else {
$sort_arr = array();
$sort_arr['order_field'] = 'htitle';
$sort_arr['order_direction'] = 'asc';
$item_session->set('rem_housesort', $sort_arr);
}
if ($sort_arr['order_field'] == "price")
$sort_string = "CAST( " . $sort_arr['order_field'] . " AS SIGNED)" . " " .
$sort_arr['order_direction'];
else
$sort_string = $sort_arr['order_field'] . " " . $sort_arr['order_direction'];
//getting groups of user
$s = getWhereUsergroupsCondition("c");
$query = "SELECT COUNT(DISTINCT h.id)
\nFROM #__rem_houses AS h"
. "\nLEFT JOIN #__rem_categories AS hc ON hc.iditem=h.id"
. "\nLEFT JOIN #__rem_main_categories AS c ON c.id=hc.idcat"
. "\nWHERE h.published='1' AND h.approved='1' AND c.published='1' $lang
AND ($s)";
$database->setQuery($query);
$total = $database->loadResult();
$pageNav = new JPagination($total, $limitstart, $limit);
// getting all items for this category
$query = "SELECT h.*,hc.idcat AS catid,hc.idcat AS idcat, c.title as category_titel
\nFROM #__rem_houses AS h "
. "\nLEFT JOIN #__rem_categories AS hc ON hc.iditem=h.id "
. "\nLEFT JOIN #__rem_main_categories AS c ON c.id=hc.idcat "
. "\nWHERE h.published='1' AND h.approved='1' "
. "\nAND c.published='1' $lang AND ($s) "
. "\nGROUP BY h.id "
. "\nORDER BY " . $sort_string
. "\nLIMIT $pageNav->limitstart,$pageNav->limit;";
$database->setQuery($query);
$houses = $database->loadObjectList();
$query = "SELECT h.*,c.id, c.parent_id, c.title, c.published, c.image,COUNT(hc.iditem) as houses, '1' as display" .
" \n FROM #__rem_main_categories as c
\n LEFT JOIN #__rem_categories AS hc ON hc.idcat=c.id
\n LEFT JOIN #__rem_houses AS h ON h.id=hc.iditem
\n WHERE c.section='com_realestatemanager'
AND c.published=1 AND ({$s}) $lang
\n GROUP BY c.id
\n ORDER BY c.parent_id DESC, c.ordering ";
$database->setQuery($query);
$cat_all = $database->loadObjectList();
foreach ($cat_all as $k1 => $cat_item1) {
if (PHP_realestatemanager::is_exist_curr_and_subcategory_houses($cat_all[$k1]->id)) {
foreach ($cat_all as $cat_item2) {
if ($cat_item1->id == $cat_item2->parent_id) {
$cat_all[$k1]->houses += $cat_item2->houses;
}
}
} else
$cat_all[$k1]->display = 0;
}
if (version_compare(JVERSION, '3.0', 'ge')) {
$menu = new JTableMenu($database);
$menu->load($Itemid);
$params = new JRegistry;
$params->loadString($menu->params);
} else {
$menu = new mosMenu($database);
$menu->load($Itemid);
$params = new mosParameters($menu->params);
}
$menu_name = set_header_name_rem($menu, $Itemid);
// add wishlist markers ------------------------------------------
$query = "SELECT fk_houseid FROM `#__rem_users_wishlist` " .
"WHERE fk_userid =" . $my->id;
$database->setQuery($query);
$result = $database->loadColumn();
$params->def('wishlist', $result);
//-----------------------------------------------------------------
$params->def('rss_show', $realestatemanager_configuration['rss']['show']);
$params->def('header', $menu_name);
$params->def('pageclass_sfx', '');
//$params->set('category_name', $category->title);
$params->def('show_category', '1');
// wish list
if (($realestatemanager_configuration['wishlist']['show'])) {
if (checkAccess_REM($realestatemanager_configuration['wishlist']['registrationlevel'],
'RECURSE', userGID_REM($my->id), $acl)) {
$params->def('show_add_to_wishlist', 1);
}
}
if (($realestatemanager_configuration['rentstatus']['show'])) {
if (checkAccess_REM($realestatemanager_configuration['rentrequest']['registrationlevel'],
'RECURSE', userGID_REM($my->id), $acl)) {
$params->def('show_rentstatus', 1);
$params->def('show_rentrequest', 1);
}
}
if (($realestatemanager_configuration['housestatus']['show'])) {
if (checkAccess_REM($realestatemanager_configuration['houserequest']['registrationlevel'],
'RECURSE', userGID_REM($my->id), $acl)) {
$params->def('show_housestatus', 1);
$params->def('show_houserequest', 1);
}
}
// //add to path category name
// PHP_realestatemanager::constructPathway($category);
if ($realestatemanager_configuration['reviews']['show']) {
$params->def('show_reviews', 1);
if (checkAccess_REM($realestatemanager_configuration['reviews']['registrationlevel'],
'NORECURSE', userGID_REM($my->id), $acl)) {
$params->def('show_inputreviews', 1);
}
}
//*************** begin add for Manager print pdf: button 'print PDF' *********************
if ($realestatemanager_configuration['print_pdf']['show']) {
$params->def('show_print_pdf', 1);
if (checkAccess_REM($realestatemanager_configuration['print_pdf']['registrationlevel'],
'NORECURSE', userGID_REM($my->id), $acl)) {
$params->def('show_input_print_pdf', 1);
}
}
//************** end add for Manager print pdf: button 'print PDF' ******************************
//************* begin add for Manager print view: button 'print VIEW' **************************
if ($realestatemanager_configuration['print_view']['show']) {
$params->def('show_print_view', 1);
if (checkAccess_REM($realestatemanager_configuration['print_view']['registrationlevel'],
'NORECURSE', userGID_REM($my->id), $acl)) {
$params->def('show_input_print_view', 1);
}
}
//******************** end add for Manager print view: button 'print VIEW' ********************
//******************* begin add for Manager mail to: button 'mail to' ************************
if ($realestatemanager_configuration['mail_to']['show']) {
$params->def('show_mail_to', 1);
if (checkAccess_REM($realestatemanager_configuration['mail_to']['registrationlevel'],
'NORECURSE', userGID_REM($my->id), $acl)) {
$params->def('show_input_mail_to', 1);
}
}
//******************** end add for Manager mail to: button 'mail to' *************************
//************** begin add for Manager add_house: button 'Add house' *********************
if ($realestatemanager_configuration['add_house']['show']) {
$params->def('show_add_house', 1);
if (checkAccess_REM($realestatemanager_configuration['add_house']['registrationlevel'],
'NORECURSE', userGID_REM($my->id), $acl)) {
$params->def('show_input_add_house', 1);
}
}
//************* end add for Manager add_house: button 'Add house' ***********************
//*************** begin show search_option *********************
if ($realestatemanager_configuration['search_option']['show']) {
$params->def('search_option', 1);
if (checkAccess_REM($realestatemanager_configuration['search_option']['registrationlevel'],
'NORECURSE', userGID_REM($my->id), $acl)) {
$params->def('search_option_registrationlevel', 1);
}
}
//************** end show search_option ******************************
$params->def('sort_arr_order_direction', $sort_arr['order_direction']);
$params->def('sort_arr_order_field', $sort_arr['order_field']);
//add for show in category picture
if ($realestatemanager_configuration['cat_pic']['show'])
$params->def('show_cat_pic', 1);
$params->def('search_request', 1);
$params->def('show_rating', 1);
$params->def('hits', 1);
$params->def('back_button', $mainframe->getCfg('back_button'));
// used to show table rows in alternating colours
$tabclass = array('sectiontableentry1', 'sectiontableentry2');
$params->def('minifotohigh', $realestatemanager_configuration['foto']['high']);
$params->def('minifotowidth', $realestatemanager_configuration['foto']['width']);
// price
if ($realestatemanager_configuration['price']['show']) {
$params->def('show_pricestatus', 1);
if (checkAccess_REM($realestatemanager_configuration['price']['registrationlevel'],
'NORECURSE', userGID_REM($my->id), $acl)) {
$params->def('show_pricerequest', 1);
}
}
$params->def('singlecategory01', "{loadposition com_realestatemanager_all_house_01,xhtml}");
$params->def('singlecategory02', "{loadposition com_realestatemanager_all_house_02,xhtml}");
$params->def('singlecategory03', "{loadposition com_realestatemanager_all_house_03,xhtml}");
$params->def('singlecategory04', "{loadposition com_realestatemanager_all_house_04,xhtml}");
$params->def('singlecategory05', "{loadposition com_realestatemanager_all_house_05,xhtml}");
$params->def('singlecategory06', "{loadposition com_realestatemanager_all_house_06,xhtml}");
$params->def('singlecategory07', "{loadposition com_realestatemanager_all_house_07,xhtml}");
$params->def('singlecategory08', "{loadposition com_realestatemanager_all_house_08,xhtml}");
$params->def('singlecategory09', "{loadposition com_realestatemanager_all_house_09,xhtml}");
$params->def('singlecategory10', "{loadposition com_realestatemanager_all_house_10,xhtml}");
$params->def('singlecategory11', "{loadposition com_realestatemanager_all_house_11,xhtml}");
switch ($printItem) {
case 'pdf':
HTML_realestatemanager::displayAllHousesPdf($houses, $params, $tabclass, $pageNav);
break;
case 'print':
HTML_realestatemanager::displayAllHousePrint($houses, $params, $tabclass, $pageNav);
break;
default:
HTML_realestatemanager::displayAllHouses($houses, $params, $tabclass, $pageNav, $layout);
break;
}
}
//this function check - is exist folders under this category
static function is_exist_subcategory_houses($catid)
{
global $database, $my;
$s = getWhereUsergroupsCondition("cc");
$query = "SELECT *, COUNT(a.id) AS numlinks FROM #__rem_main_categories AS cc"
. "\n JOIN #__rem_categories AS hc ON hc.idcat = cc.id"
. "\n JOIN #__rem_houses AS a ON a.id = hc.iditem"
. "\n WHERE a.published='1' AND a.approved='1' AND section='com_realestatemanager' "
. " AND cc.parent_id='" . intval($catid) . "' AND cc.published='1' AND ($s) "
. "\n GROUP BY cc.id"
. "\n ORDER BY cc.ordering";
$database->setQuery($query);
$categories = $database->loadObjectList();
if (count($categories) != 0)
return true;
$query = "SELECT id "
. "FROM #__rem_main_categories AS cc "
. " WHERE section='com_realestatemanager' AND parent_id='" .
intval($catid) . "' AND published='1' AND ($s) ";
$database->setQuery($query);
$categories = $database->loadObjectList();
if (count($categories) == 0)
return false;
foreach ($categories as $k) {
if (PHP_realestatemanager::is_exist_subcategory_houses($k->id))
return true;
}
return false;
}
static function is_exist_curr_and_subcategory_houses($catid) {
global $database, $my;
$s = getWhereUsergroupsCondition("cc");
$query = "SELECT *, COUNT(a.id) AS numlinks FROM #__rem_main_categories AS cc"
. "\n JOIN #__rem_categories AS hc ON hc.idcat = cc.id"
. "\n JOIN #__rem_houses AS a ON a.id = hc.iditem"
. "\n WHERE a.published='1' AND a.approved='1' AND section='com_realestatemanager' "
. " AND cc.id='" . intval($catid) . "' AND cc.published='1' AND ($s) "
. "\n GROUP BY cc.id"
. "\n ORDER BY cc.ordering";
$database->setQuery($query);
$categories = $database->loadObjectList();
if (count($categories) != 0)
return true;
$query = "SELECT id "
. "FROM #__rem_main_categories AS cc "
. " WHERE section='com_realestatemanager' AND parent_id='" .
intval($catid) . "' AND published='1' AND ($s) ";
$database->setQuery($query);
$categories = $database->loadObjectList();
if (count($categories) == 0)
return false;
foreach ($categories as $k) {
if (PHP_realestatemanager::is_exist_curr_and_subcategory_houses($k->id))
return true;
}
return false;
}
static function listCategories($catid, $layout, $languagelocale) {
global $mainframe, $database, $my, $acl, $langContent;
global $mosConfig_shownoauth, $mosConfig_live_site, $mosConfig_absolute_path;
global $cur_template, $Itemid, $realestatemanager_configuration;
PHP_realestatemanager::addTitleAndMetaTags();
$s = getWhereUsergroupsCondition("c");
if (isset($langContent)) {
$lang = $langContent;
// $query = "SELECT lang_code FROM #__languages WHERE sef = '$lang'";
// $database->setQuery($query);
// $lang = $database->loadResult();
$lang = " and ( h.language = '$lang' or h.language like 'all' or "
." h.language like '' or h.language like '*' or h.language is null) "
. " AND ( c.language = '$lang' or c.language like 'all' or "
. " c.language like '' or c.language like '*' or c.language is null) ";
} else {
$lang = "";
}
$query = "SELECT h.*,c.id, c.parent_id, c.title, c.image,COUNT(hc.iditem) as houses, '1' as display" .
"\n FROM #__rem_main_categories as c " .
"\n LEFT JOIN #__rem_categories AS hc ON hc.idcat=c.id " .
"\n LEFT JOIN #__rem_houses AS h ON h.id=hc.iditem AND ".
"( h.published || isnull(h.published) ) AND ( h.approved || isnull(h.approved ) )" .
"\n WHERE c.section='com_realestatemanager' AND c.published=1 AND h.published = 1 AND h.approved = 1
\n $lang AND ({$s})
\n GROUP BY c.id ORDER BY c.parent_id DESC, c.ordering";
$database->setQuery($query);
$cat_all = $database->loadObjectList();
// print_r($query);print_r($cat_all); exit;
foreach ($cat_all as $k1 => $cat_item1) {
$cat_all[$k1]->display = PHP_realestatemanager::is_exist_curr_and_subcategory_houses($cat_all[$k1]->id);
}
$currentcat = new stdClass();
// Parameters
$menu = new JTableMenu($database);
$menu->load($Itemid);
$params = new mosParameters($menu->params);
$menu_name = set_header_name_rem($menu, $Itemid);
$params->def('header', $menu_name);
$params->def('pageclass_sfx', '');
$params->def('back_button', $mainframe->getCfg('back_button'));
// page header
$currentcat->header = $params->get('header');
//***** begin add for Manager Add house: button 'Add a house'
if (($realestatemanager_configuration['add_house']['show'])) {
$params->def('show_add_house', 1);
if (checkAccess_REM($realestatemanager_configuration['add_house']['registrationlevel'],
'NORECURSE', userGID_REM($my->id), $acl)) {
$params->def('show_input_add_house', 1);
}
}
//********* end add for Manager Add house: button 'Add a house' **
//show_button_my_houses
if ($my->email != null) {
$params->def('show_button_my_houses', 1);
}
if (checkAccess_REM($realestatemanager_configuration['rss']['registrationlevel'],
'RECURSE', userGID_REM($my->id), $acl) &&
$realestatemanager_configuration['rss']['show']) {
$params->def('rss_show', 1);
}
if (checkAccess_REM($realestatemanager_configuration['ownerslist']['registrationlevel'],
'RECURSE', userGID_REM($my->id), $acl) &&
$realestatemanager_configuration['ownerslist']['show']) {
$params->def('ownerslist_show', 1);
}
//*************** begin show search_option *********************
if ($realestatemanager_configuration['search_option']['show']) {
$params->def('search_option', 1);
if (checkAccess_REM($realestatemanager_configuration['search_option']['registrationlevel'],
'NORECURSE', userGID_REM($my->id), $acl)) {
$params->def('search_option_registrationlevel', 1);
}
}
//************** end show search_option ******************************
//add for show in category picture
if ($realestatemanager_configuration['cat_pic']['show'])
$params->def('show_cat_pic', 1);
// page description
$currentcat->descrip = _REALESTATE_MANAGER_DESC;
// used to show table rows in alternating colours
$tabclass = array('sectiontableentry1', 'sectiontableentry2');
$params->def('allcategories01', "{loadposition com_realestatemanager_all_categories_01,xhtml}");
$params->def('allcategories02', "{loadposition com_realestatemanager_all_categories_02,xhtml}");
$params->def('allcategories03', "{loadposition com_realestatemanager_all_categories_03,xhtml}");
$params->def('allcategories04', "{loadposition com_realestatemanager_all_categories_04,xhtml}");
$params->def('allcategories05', "{loadposition com_realestatemanager_all_categories_05,xhtml}");
$params->def('allcategories06', "{loadposition com_realestatemanager_all_categories_06,xhtml}");
$params->def('allcategories07', "{loadposition com_realestatemanager_all_categories_07,xhtml}");
$params->def('allcategories08', "{loadposition com_realestatemanager_all_categories_08,xhtml}");
$params->def('allcategories09', "{loadposition com_realestatemanager_all_categories_09,xhtml}");
$params->def('allcategories10', "{loadposition com_realestatemanager_all_categories_10,xhtml}");
HTML_realestatemanager::showCategories($params, $cat_all, $catid, $tabclass, $currentcat, $layout);
}
static function paypal() {
global $database, $realestatemanager_configuration;
$operation=JRequest::getVar('operation');
if(isset($operation) && $operation == 'success') {
$dispatcher = JDispatcher::getInstance();
$plugin_name = 'paypal';
$plugin = JPluginHelper::importPlugin( 'payment',$plugin_name);
$a = '';
$userName = '';
$userEmail = '';
$html = $dispatcher->trigger('validateIPN');
if(isset($html[0]))$html = $html[0];
if(JRequest::getVar('payer_email','') || count($html)>2){
$userId = JRequest::getVar('userId');
if(JRequest::getVar('userId','')){
$sql = "SELECT name,username,email FROM `#__users` WHERE id= '".JRequest::getVar('userId')."'";
$database->setQuery($sql);
$result = $database->loadObjectList();
$result = $result['0'];
$userName = $result->name;
$userEmail = $result->email;
}
if(!$userName)$userName = JRequest::getVar('first_name');
if(!$userEmail)$userEmail = JRequest::getVar('payer_email');
$house_id = JRequest::getVar('houseId');
if($house_id){
if(count($html)>2){///paralel payment
if($html['payKey']){
$query = "SELECT id FROM #__rem_orders_details "
."\n WHERE txn_id = '".$html['payKey']."' "
."\n AND status='".$html['responseEnvelope']['ack']."'";
$database->setQuery($query);
$result = $database->loadResult();
if(!empty($result)){
JError::raiseWarning(0,_REALESTATE_MANAGER_PAYPAL_F5_ERROR);
return;
}
}
$status = $html['responseEnvelope']['ack'];
$payer_id = '';
$txn_id = $html['payKey'];
$txn_type = 'comission_payment';
$order_currency_code = JRequest::getVar('currency_code');
$orderId = JRequest::getVar('orderId');
$payer_status = '';
$mc_gross = 0;
$userEmail = $html['senderEmail'];
$html['En attente de paiement_reason'] = 'Receiver List:<br>________________________';
foreach ($html['paymentInfoList']['paymentInfo'] as $value) {
$mc_gross += $value['receiver']['amount'];
$html['En attente de paiement_reason'] .= '<br>Email:'.$value['receiver']['email']
.'<br>Amount:'.$value['receiver']['amount']
.'<br>Status:'.$value['senderTransactionStatus'];
if($value['senderTransactionStatus'] == 'En attente de paiement'){
$html['En attente de paiement_reason'] .= '<br>Reason:'.$value['En attente de paiementReason'];
}
$html['En attente de paiement_reason'] .= '<br>________________________';
}
$raw_data = serialize($html);
}else{
$status = JRequest::getVar('payment_status');
$payer_id = JRequest::getVar('payer_id');
$txn_id = JRequest::getVar('txn_id');
$txn_type = JRequest::getVar('txn_type');
$payer_status = JRequest::getVar('payer_status');
$mc_gross = JRequest::getVar('mc_gross');
$order_currency_code = JRequest::getVar('mc_currency');
$orderId = JRequest::getVar('orderId');
$raw_data = serialize($_REQUEST);
}
$sql = "SELECT order_calculated_price FROM #__rem_orders_details
WHERE fk_order_id='".$orderId."'
AND status = 'En attente de paiement'
ORDER BY order_date DESC";
$database->setQuery($sql);
$calculated_price = $database->loadResult();
$sql = "SELECT htitle FROM #__rem_houses WHERE id='".$house_id."'";
$database->setQuery($sql);
$htitle = $database->loadResult();
$sql = "UPDATE #__rem_orders SET order_date = now(), status='".$status."',
payer_id='".$payer_id."',
order_price='".$mc_gross."',
order_currency_code='".$order_currency_code."',
txn_id='".$txn_id."',
txn_type='".$txn_type."',
fk_user_id = '".$userId."',
email = '".$userEmail."',
name = '".$userName."',
order_calculated_price = '".$calculated_price."',
payer_status='".$payer_status."' WHERE id = '".$orderId."'";
$database->setQuery($sql);
$database->query();
$sql = "INSERT INTO `#__rem_orders_details`(fk_order_id,fk_user_id,email,fk_houses_htitle,
name,status,order_date,fk_house_id,
txn_type,txn_id,payer_id,payer_status,order_calculated_price,order_price,
order_currency_code, payment_details)
VALUES ('".$orderId."',
'".JRequest::getVar('userId')."',
'".$userEmail."',
'".$htitle."',
'".$userName."',
'".$status."',
now(),
'".$house_id."',
'".$txn_type."',
'".$txn_id."',
'".$payer_id."',
'".$payer_status."',
'".$calculated_price."',
'".$mc_gross."',
'".$order_currency_code."',
".$database->Quote($raw_data).")";
$database->setQuery($sql);
$database->query();
}else{
JError::raiseWarning(0,_REALESTATE_MANAGER_PAYPAL_ERROR);
return;
}
echo _REALESTATE_MANAGER_MESSAGE_SUCCESSFULL_PAYMENT;
}
} elseif(isset($_GET['operation']) && JRequest::getVar('operation') == 'cancel') {
echo _REALESTATE_MANAGER_MESSAGE_UNSUCCESSFULL_PAYMENT;
}
}
static function getMonthCal($month, $year, $id) {
global $database, $realestatemanager_configuration;
$query = "SELECT rent_from, rent_until, rent_return FROM #__rem_rent WHERE fk_houseid='$id' ORDER BY rent_from";
$database->setQuery($query);
$calenDate = $database->loadObjectList();
$skip = date("w", mktime(0, 0, 0, $month, 1, $year)) - 1;
if ($skip < 0){
$skip = 6;
}
$daysInMonth = date("t", mktime(0, 0, 0, $month, 1, $year));
/*******************************get only rent days*****************************/
$rentDataArr = array();
$i=0;
foreach ($calenDate as &$value) {
if(!($value->rent_return)){
if(isset($calenDate[($i+1)]) && $calenDate[($i+1)]->rent_from == $calenDate[$i]->rent_until){
$calenDate[($i+1)]->rent_from = $calenDate[$i]->rent_from;
unset($calenDate[$i]);
$i++;
continue;
}
array_push($rentDataArr, $value);
}$i++;
}
$calenDate = $rentDataArr;
$calendar = '';
$day = 1;
$smonth = PHP_realestatemanager::getMonth($month);
$calendar = '<table class="rem_tableC" style="border-collapse: separate;'.
' border-spacing: 2px;text-align:center"><tr class="year"><th colspan = "7">' .
$smonth . ' ' . $year . '</th></tr><tr class="days"><th>' . JText::_('MON') .
'</th><th>' . JText::_('TUE') . '</th><th>' . JText::_('WED') . '</th><th>' .
JText::_('THU') . '</th><th>' . JText::_('FRI') . '</th><th>' . JText::_('SAT') .
'</th><th>' . JText::_('SUN') . '</th></tr>';
for ($i = 0; $i < 6; $i++) {
$calendar .= '<tr>';
for ($j = 0; $j < 7; $j++) {
if (($skip > 0) or ($day > $daysInMonth)){
$calendar .= '<td> </td>';
$skip--;
}else{
$isAvilable = getAvilableRM($calenDate,$month,$year,$realestatemanager_configuration,$day);
$calendar .= '<td class="'.$isAvilable.'">' . $day . '</td>';
$day++;
}
}
$calendar .= '</tr>';
}
$calendar .= '</table>';
return $calendar;
}
static function getCalendarPrice($month, $year, $id){
global $database;
$query = "SELECT * FROM `#__rem_rent_sal` " .
" WHERE (`fk_houseid`='$id') and (`yearW`='$year') and (`monthW`='$month')";
$database->setQuery($query);
$calenWeeks = $database->loadObjectList();
if (!empty($calenWeeks)){
$calenWeek = $calenWeeks[0];
$calendar = "";
$calendar = '<table style="text-align:left">';
$calendar .= '<tr><td><b>' . _REALESTATE_MANAGER_LABEL_CALENDAR_WEEK . '<b></td></tr>';
$calendar .= '<tr><td>' . str_replace("\n", "<br>\n", $calenWeek->week) . '</td></tr>';
$calendar .= '<tr><td><b>' . _REALESTATE_MANAGER_LABEL_CALENDAR_WEEKEND . '<b></td></tr>';
$calendar .= '<tr><td>' . str_replace("\n", "<br>\n", $calenWeek->weekend) . '</td></tr>';
$calendar .= '<tr><td><b>' . _REALESTATE_MANAGER_LABEL_CALENDAR_MIDWEEK . '</b></td></tr>';
$calendar .= '<tr><td><span>' . str_replace("\n", "<br>\n", $calenWeek->midweek) . '<span></td></tr>';
$calendar .= '</table>';
return $calendar;
}
}
static function getCalendar($month, $year, $id){
$month = (int) $month;
$year = (int) $year;
if ($month == 1)
{
$month1 = 12;
$year1 = $year - 1;
} else
{
$month1 = $month - 1;
$year1 = $year;
}
if ($month == 12)
{
$month2 = 1;
$month3 = 2;
$year2 = $year3 = $year + 1;
} else
{
$month2 = $month + 1;
$month3 = $month + 2;
$year2 =$year3 = $year;
}
if($month3 > 12){
$month3 = $month3 - 12;
$year3 = $year + 1;
}
$calendar = new stdClass();
$calendar->tab1 = PHP_realestatemanager::getMonthCal($month1, $year1, $id);
$calendar->tab2 = PHP_realestatemanager::getMonthCal($month, $year, $id);
$calendar->tab3 = PHP_realestatemanager::getMonthCal($month2, $year2, $id);
$calendar->tab4 = PHP_realestatemanager::getMonthCal($month3, $year3, $id);
$calendar->tab21 = PHP_realestatemanager::getCalendarPrice($month1, $year1, $id);
$calendar->tab22 = PHP_realestatemanager::getCalendarPrice($month, $year, $id);
$calendar->tab23 = PHP_realestatemanager::getCalendarPrice($month2, $year2, $id);
$calendar->tab24 = PHP_realestatemanager::getCalendarPrice($month3, $year3, $id);
return $calendar;
}
static function addHouseToWishlist() {
global $database, $my;
$owner_id = $my->id;
$houseid = JFactory::getApplication()->input->getInt('id', '');
if ($houseid != '') {
$query = "SELECT id FROM `#__rem_users_wishlist`
WHERE fk_houseid = $houseid AND fk_userid=$owner_id";
$database->setQuery($query);
$result = $database->loadResult();
if ($result) {
$message = _REALESTATE_MANAGER_LABEL_WISHLIST_ALREDY_IN;
echo new JResponseJson(true, $message);
jexit();
}
$query = "INSERT INTO `#__rem_users_wishlist` (fk_houseid,fk_userid) VALUES ($houseid, $owner_id)";
$database->setQuery($query);
$database->query();
$message = _REALESTATE_MANAGER_LABEL_WISHLIST_ADDED;
} else {
$message = 'Error adding to wish list!'; // _BOOKLIBRARY_LABEL_ERRORWISHLIST;
}
echo new JResponseJson(true, $message);
jexit();
}
static function removeHouseFromWishlist() {
global $database, $my;
$owner_id = $my->id;
$houseid = JFactory::getApplication()->input->getInt('id', '');
if ($houseid != '') {
$query = "DELETE FROM `#__rem_users_wishlist`
WHERE fk_houseid = $houseid AND fk_userid=$owner_id";
$database->setQuery($query);
$database->query();
$message = _REALESTATE_MANAGER_LABEL_WISHLIST_REMOVED;
} else {
$message = 'Error to delete from wish list';
}
echo new JResponseJson(true, $message );
jexit();
}
static function showWishlist($option, $task) {
global $mainframe, $database, $my, $acl, $realestatemanager_configuration, $Itemid, $limit;
$owner_id = $my->id;
if(empty($owner_id) && $task == 'wishlist'){
// mosRedirect("index.php?", "Please login");
JFactory::getApplication()->enqueueMessage('Please login');
return;
}
PHP_realestatemanager::addTitleAndMetaTags();
//parameters
if (version_compare(JVERSION, '3.0', 'ge')) {
$menu = new JTableMenu($database);
$menu->load($Itemid);
$params = new JRegistry;
$params->loadString($menu->params);
} else {
$menu = new mosMenu($database);
$menu->load($Itemid);
$params = new mosParameters($menu->params);
}
$database->setQuery("SELECT id FROM `#__menu` WHERE link='index.php?option=com_realestatemanager'");
if ($database->loadResult() != $Itemid){
$params->def('wrongitemid', '1');
}
// $limit = $realestatemanager_configuration['page']['items'];
$limitstart = JFactory::getApplication()->input->getInt('limitstart', 0);
if (!$params->get('wrongitemid')){
$pathway = sefRelToAbs('index.php?option=' . $option . '&task=wishlist&Itemid=' . $Itemid);
$path_way = $mainframe->getPathway();
$path_way->addItem(_REALESTATE_MANAGER_LABEL_SEARCH, $pathway);
}
$menu_name = set_header_name_rem($menu, $Itemid);
$params->def('header', $menu_name);
$query = "SELECT COUNT(id)
FROM `#__rem_users_wishlist` \n " . "
WHERE fk_userid=$owner_id";
$database->setQuery($query);
$total = $database->loadResult();
$pageNav = new JPagination($total, $limitstart, $limit); // for J 1.6
$selectstring = "SELECT a.*, GROUP_CONCAT(cc.title SEPARATOR ', ') AS category, l.id AS rentid, l.rent_from AS rent_from, l.rent_return AS rent_return, l.rent_until AS rent_until, u.name AS editor, l.user_name AS user_name,l.user_email AS user_email, l.user_mailing AS user_mailing, cc.title AS category_titel, cc.id AS idcat
FROM #__rem_houses AS a " .
"\n LEFT JOIN #__rem_categories AS vc ON vc.iditem = a.id " .
"\n LEFT JOIN #__rem_main_categories AS cc ON cc.id = vc.idcat " .
"\n LEFT JOIN #__rem_rent AS l ON a.fk_rentid = l.id " .
"\n LEFT JOIN #__users AS u ON u.id = a.checked_out " .
"\n WHERE a.id in (SELECT fk_houseid FROM " .
"\n #__rem_users_wishlist WHERE fk_userid=$owner_id)" .
"\n GROUP BY a.id" .
"\n LIMIT " . $pageNav->limitstart . "," . $pageNav->limit . ";";
$database->setQuery($selectstring);
$houses = $database->loadObjectList();
if (!$houses) {
// mosRedirect("index.php?", "Wishlist is empty!");
JFactory::getApplication()->enqueueMessage('Wishlist is empty!');
return;
}
$params->def('wishlist01', "{loadposition com_realestatemanager_my_house_01,xhtml}");
$params->def('wishlist02', "{loadposition com_realestatemanager_my_house_02,xhtml}");
$params->def('wishlist03', "{loadposition com_realestatemanager_my_house_03,xhtml}");
$params->def('wishlist04', "{loadposition com_realestatemanager_my_house_04,xhtml}");
$params->def('wishlist05', "{loadposition com_realestatemanager_my_house_05,xhtml}");
HTML_realestatemanager::showWishlist($houses, $params, $pageNav, $option);
}
}<file_sep><?php
if (!defined('_VALID_MOS') && !defined('_JEXEC'))
die('Direct Access to ' . basename(__FILE__) . ' is not allowed.');
/**
*
* @package RealestateManager
* @copyright 2012 <NAME>-OrdaSoft(<EMAIL>); <NAME>(<EMAIL>);
* Homepage: http://www.ordasoft.com
* @version: 3.9 PRO
*
*
*/
global $hide_js, $mainframe, $Itemid, $realestatemanager_configuration,
$mosConfig_live_site, $mosConfig_absolute_path, $my, $doc, $arr, $acl,$langContent;
if (version_compare(JVERSION, "3.0.0", "lt"))
JHTML::_('behavior.mootools');
else
JHtml::_('behavior.framework', true);
if (!JFactory::getApplication()->get('os_lightbox'))
JFactory::getApplication()->set('os_lightbox', true);
// add os_lightbox
////////////Adding google map
$realestatemanager_configuration = $GLOBALS['realestatemanager_configuration'];
if ($realestatemanager_configuration['location_tab']['show']
|| $realestatemanager_configuration['street_view']['show']) {
$api_key = $realestatemanager_configuration['api_key'] ? "key=" . $realestatemanager_configuration['api_key'] : JFactory::getApplication()->enqueueMessage("<a target='_blank' href='//developers.google.com/maps/documentation/geocoding/get-api-key'>" . _REALESTATE_MANAGER_GOOGLEMAP_API_KEY_LINK_MESSAGE . "</a>", _REALESTATE_MANAGER_GOOGLEMAP_API_KEY_ERROR);
$doc->addScript("//maps.googleapis.com/maps/api/js?$api_key");
if($realestatemanager_configuration['street_view']['show']){
?>
<script type="text/javascript">
window.addEvent('domready', function() {
initialize();
});
var map;
var myLatlng=new google.maps.LatLng(<?php
if ($house->hlatitude && $house->hlatitude != '')
echo $house->hlatitude;
else
echo 0;
?>,<?php
if ($house->hlongitude && $house->hlongitude != '')
echo $house->hlongitude;
else
echo 0;
?>);
var sv = new google.maps.StreetViewService();
var panorama;
function initialize(){
var myOptions = {
zoom: <?php if ($house->map_zoom)
echo $house->map_zoom;
else
echo 1;
?>,
center: myLatlng,
scrollwheel: false,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.LARGE
},
mapTypeId: google.maps.MapTypeId.ROADMAP
};
if(document.getElementById("map_canvas") != undefined){
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
var imgCatalogPath = "<?php echo $mosConfig_live_site;
?>/components/com_realestatemanager/";
<?php
$newArr = explode(",", _REALESTATE_MANAGER_HOUSE_MARKER);
$numPick = '';
if (isset($newArr[$house->property_type])) {
$numPick = $newArr[$house->property_type];
}
?>
var srcForPic = "<?php echo $numPick; ?>";
var image = '';
if(srcForPic.length){
var image = new google.maps.MarkerImage(imgCatalogPath + srcForPic,
new google.maps.Size(32, 32),
new google.maps.Point(0,0),
new google.maps.Point(16, 32));
}
var marker = new google.maps.Marker({ icon: image,position: myLatlng });
marker.setMap(map);
var panoramaOptions = {
position: myLatlng,
pov: {
heading: 34,
pitch: 10
}
};
var streetViewService = new google.maps.StreetViewService();
var STREETVIEW_MAX_DISTANCE = 50;
streetViewService.getPanoramaByLocation(myLatlng, STREETVIEW_MAX_DISTANCE, function (streetViewPanoramaData, status) {
if (status === google.maps.StreetViewStatus.OK) {
// ok
var panorama = new google.maps.StreetViewPanorama(document.getElementById('map_pano'), panoramaOptions);
map.setStreetView(panorama);
} else {
document.getElementById('map_pano').style.display = "none";
// no street view available in this range, or some error occurred
}
});
}
</script>
<?php
}else{
?>
<script type="text/javascript">
window.addEvent('domready', function() {
initialize();
});
var map;
var myLatlng=new google.maps.LatLng(<?php
if ($house->hlatitude && $house->hlatitude != '')
echo $house->hlatitude;
else
echo 0;
?>,<?php
if ($house->hlongitude && $house->hlongitude != '')
echo $house->hlongitude;
else
echo 0;
?>);
function initialize(){
var myOptions = {
zoom: <?php if ($house->map_zoom)
echo $house->map_zoom;
else
echo 1;
?>,
center: myLatlng,
scrollwheel: false,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.LARGE
},
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var imgCatalogPath = "<?php echo $mosConfig_live_site;
?>/components/com_realestatemanager/";
<?php
$newArr = explode(",", _REALESTATE_MANAGER_HOUSE_MARKER);
$numPick = '';
if (isset($newArr[$house->property_type])) {
$numPick = $newArr[$house->property_type];
}
?>
var srcForPic = "<?php echo $numPick; ?>";
var image = '';
if(srcForPic.length){
var image = new google.maps.MarkerImage(imgCatalogPath + srcForPic,
new google.maps.Size(32, 32),
new google.maps.Point(0,0),
new google.maps.Point(16, 32));
}
var marker = new google.maps.Marker({ icon: image,position: myLatlng });
marker.setMap(map);
}
</script>
<?php }
}
?>
<div id="overDiv" ></div>
<?php
JPluginHelper::importPlugin('content');
$dispatcher = JDispatcher::getInstance();
?>
<script language="javascript" type="text/javascript">
function review_submitbutton() {
var form = document.review_house;
// do field validation
var rating_checked = false;
for (c = 0; c < form.rating.length; c++){
if (form.rating[c].checked){
rating_checked = true;
form.rating.value = c ;
}
}
if (form.title.value == "") {
alert( "<?php echo _REALESTATE_MANAGER_INFOTEXT_JS_REVIEW_TITLE; ?>" );
} else if (form.comment == "") {
alert( "<?php echo _REALESTATE_MANAGER_INFOTEXT_JS_REVIEW_COMMENT; ?>" );
} else if (! form.rating.value) {
alert( "<?php echo _REALESTATE_MANAGER_INFOTEXT_JS_REVIEW_RATING; ?>" );
} else {
form.submit();
}
}
//***************** begin add for show/hiden button "Add review" ********************
function button_hidden( is_hide ) {
var el = document.getElementById('button_hidden_review');
var el2 = document.getElementById('hidden_review');
if(is_hide){
el.style.display = 'none';
el2.style.display = 'block';
} else {
el.style.display = 'block';
el2.style.display = 'none';
}
}
function buying_request_submitbutton() {
var form = document.buying_request;
if (form.customer_name.value == "") {
document.getElementById('customer_name_warning').innerHTML =
"<?php echo _REALESTATE_MANAGER_INFOTEXT_JS_RENT_REQ_NAME; ?>";
document.getElementById('customer_name_warning').style.color = "red";
document.getElementById('alert_name_buy').style.borderColor = "red";
document.getElementById('alert_name_buy').style.color = "red";
} else if (form.customer_email.value == ""|| !isValidEmail(form.customer_email.value)) {
document.getElementById('customer_email_warning').innerHTML =
"<?php echo _REALESTATE_MANAGER_INFOTEXT_JS_RENT_REQ_EMAIL; ?>";
document.getElementById('customer_email_warning').style.color = "red";
document.getElementById('alert_mail_buy').style.borderColor = "red";
document.getElementById('alert_mail_buy').style.color = "red";
} else if (!isValidPhoneNumber(form.customer_phone.value)){
document.getElementById('customer_phone_warning').innerHTML =
"<?php echo _REALESTATE_MANAGER_REQUEST_PHONE; ?>";
document.getElementById('customer_phone_warning').style.color = "red";
document.getElementById('customer_phone').style.borderColor = "red";
document.getElementById('customer_phone').style.color = "red";
} else {
form.submit();
}
}
function isValidPhoneNumber(str){
myregexp = new RegExp("^([_0-9() -;,]*)$");
mymatch = myregexp.exec(str);
if(str == "")
return true;
if(mymatch != null)
return true;
return false;
}
function isValidEmail(str){
myregexp = new RegExp("^([a-zA-Z0-9_-]+\.)*[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)*\.[a-zA-Z]{2,6}$");
mymatch = myregexp.exec(str);
if(str == "")
return false;
if(mymatch != null)
return true;
return false;
}
</script>
<?php
if ($params->get('show_rentstatus') && $params->get('show_rentrequest')
&& !$params->get('rent_save') && !$params->get('search_request')) {
?>
<!--///////////////////////////////calendar///////////////////////////////////////-->
<script language="javascript" type="text/javascript">
<?php
$house_id_fordate = $house->id;
$date_NA = available_dates($house_id_fordate);
?>
var unavailableDates = Array();
jQuerREL(document).ready(function() {
var k=0;
<?php if(!empty($date_NA)){?>
<?php foreach ($date_NA as $N_A){ ?>
unavailableDates[k]= '<?php echo $N_A; ?>';
k++;
<?php } ?>
<?php } ?>
function unavailableFrom(date) {
dmy = date.getFullYear() + "-" + ('0'+(date.getMonth() + 1)).slice(-2) +
"-" + ('0'+date.getDate()).slice(-2);
if (jQuerREL.inArray(dmy, unavailableDates) == -1) {
return [true, ""];
} else {
return [false, "", "Unavailable"];
}
}
function unavailableUntil(date) {
dmy = date.getFullYear() + "-" + ('0'+(date.getMonth() + 1)).slice(-2) +
"-" + ('0'+(date.getDate()-("<?php if(!$realestatemanager_configuration['special_price']['show']) echo '1';?>"))).slice(-2);
if (jQuerREL.inArray(dmy, unavailableDates) == -1) {
return [true, ""];
} else {
return [false, "", "Unavailable"];
}
}
jQuerREL( "#rent_from" ).datepicker(
{
minDate: "+0",
dateFormat: "<?php echo transforDateFromPhpToJquery();?>",
beforeShowDay: unavailableFrom,
onClose: function () {
jQuerREL.ajax({
type: "POST",
update: jQuerREL(" #alert_date "),
success: function( data ) {
jQuerREL("#alert_date").html("");
}
});
var rent_from = jQuerREL(" #rent_from ").val();
var rent_until = jQuerREL(" #rent_until ").val();
var week = jQuerREL(" #week ").val();
jQuerREL.ajax({
type: "POST",
url: "index.php?option=com_realestatemanager&task=ajax_rent_calcualete"
+"&bid=<?php echo $house->id; ?>&rent_from="+
rent_from+"&rent_until="+rent_until+"&week="+week,
data: { " #do " : " #1 " },
update: jQuerREL(" #message-here "),
success: function( data ) {
jQuerREL("#message-here").html(data);
jQuerREL("#calculated_price").val(data);
}
});
}
});
jQuerREL( "#rent_until" ).datepicker(
{
minDate: "+0",
dateFormat: "<?php echo transforDateFromPhpToJquery();?>",
beforeShowDay: unavailableUntil,
onClose: function () {
jQuerREL.ajax({
type: "POST",
update: jQuerREL(" #alert_date "),
success: function( data ) {
jQuerREL("#alert_date").html("");
}
});
var rent_from = jQuerREL(" #rent_from ").val();
var rent_until = jQuerREL(" #rent_until ").val();
var week = jQuerREL(" #week ").val();
jQuerREL.ajax({
type: "POST",
url: "index.php?option=com_realestatemanager&task=ajax_rent_calcualete"
+"&bid=<?php echo $house->id; ?>&rent_from="+
rent_from+"&rent_until="+rent_until+"&week="+week,
data: { " #do " : " #1 " },
update: jQuerREL(" #message-here "),
success: function( data ) {
jQuerREL("#message-here").html(data);
jQuerREL("#calculated_price").val(data);
}
});
}
});
});
<!--///////////////////////////////////////////////////////////////////////////-->
function rem_rent_request_submitbutton() {
var form = document.rent_request_form;
var datef = form.rent_from.value;
var dateu = form.rent_until.value;
var dayornight = "<?php echo $realestatemanager_configuration['special_price']['show']?>";
var frep = datef.replace(/\//gi,"-").replace(/\s/gi,"-").replace(/\*/gi,"-");
var urep = dateu.replace(/\//gi,"-").replace(/\s/gi,"-").replace(/\*/gi,"-");
var re = /\n*\-\d\d\d\d/;
var found = urep.match(re);
if(found){
var dfrom = (frep.split ('-').reverse ());
var duntil = (urep.split ('-').reverse ());
} else {
var dfrom = (frep.split ('-'));
var duntil = (urep.split ('-'));
}
var dmin=dfrom[0]*10000+dfrom[1]*100+dfrom[2]*1;
var dmax=duntil[0]*10000+duntil[1]*100+duntil[2]*1;
if (form.user_name.value == "") {
document.getElementById('user_name_warning').innerHTML =
"<?php echo _REALESTATE_MANAGER_INFOTEXT_JS_RENT_REQ_NAME; ?>";
document.getElementById('user_name_warning').style.color = "red";
document.getElementById('alert_name').style.borderColor = "red";
document.getElementById('alert_name').style.color = "red";
} else if (form.user_email.value == "" || !isValidEmail(form.user_email.value)) {
document.getElementById('user_email_warning').innerHTML =
"<?php echo _REALESTATE_MANAGER_INFOTEXT_JS_RENT_REQ_EMAIL; ?>";
document.getElementById('user_email_warning').style.color = "red";
document.getElementById('alert_mail').style.borderColor = "red";
document.getElementById('alert_mail').style.color = "red";
} else if (dmax<dmin) {
document.getElementById('alert_date').innerHTML =
"<?php echo _REALESTATE_MANAGER_INFOTEXT_JS_RENT_REQ_ALERT; ?>";
document.getElementById('alert_date').style.borderColor = "red";
document.getElementById('alert_date').style.color = "red";
} else if (unavailableDates.indexOf(form.rent_until.value) >= 0
|| unavailableDates.indexOf(form.rent_from.value) >= 0) {
document.getElementById('alert_date').innerHTML =
"<?php echo _REALESTATE_MANAGER_INFOTEXT_JS_RENT_REQ_DATE; ?>";
document.getElementById('alert_date').style.borderColor = "red";
document.getElementById('alert_date').style.color = "red";
} else if (dmax==dmin && dayornight == 0) {
document.getElementById('alert_date').innerHTML =
"<?php echo _REALESTATE_MANAGER_INFOTEXT_JS_RENT_REQ_ALERT; ?>";
document.getElementById('alert_date').style.borderColor = "red";
document.getElementById('alert_date').style.color = "red";
}else {
form.submit();
}
}
</script>
<?php
}
?>
<script type="text/javascript" charset="utf-8" async defer>
jQuerREL(document).ready(function () {
jQuerREL('input,textarea').focus(function(){
jQuerREL(this).data('placeholder',jQuerREL(this).attr('placeholder'))
jQuerREL(this).attr('placeholder','')
jQuerREL(this).css('color','#a3a3a3');
jQuerREL(this).css('border-color','#ddd');
});
jQuerREL('input,textarea').blur(function(){
jQuerREL(this).attr('placeholder',jQuerREL(this).data('placeholder'));
});
});
function allreordering(){
if(document.orderForm.order_direction.value=='asc')
document.orderForm.order_direction.value='desc';
else document.orderForm.order_direction.value='asc';
document.orderForm.submit();
}
</script>
<?php positions_rem($params->get('view01')); ?>
<div class="row-fluid">
<div class="span9">
<div id="rem_house_galery">
<!-- ********************** begin add for show/hiden button "Edit house"___c************* -->
<?php
$is_edit_all_houses = false ;
if (checkAccess_REM($realestatemanager_configuration['option_edit']['registrationlevel'], 'RECURSE', userGID_REM($my->id), $acl)) {
$is_edit_all_houses = true ;
}
if ($my->id == $house->owner_id && $my->id != '' || $is_edit_all_houses):
global $option;
if ($option != 'com_realestatemanager') {
$form_action = "index.php?option=" . $option .
"&task=edit_house&Itemid=" . $Itemid ;
}
else
$form_action = "index.php?option=com_realestatemanager&task=edit_house&Itemid=" . $Itemid;
?>
<form action="<?php echo sefRelToAbs($form_action); ?>" method="post"
name="show_add" enctype="multipart/form-data">
<div id ="button">
<input type="hidden" name="id" value="<?php echo $house->id; ?>"/>
<input class="button" type="submit" name="submit" value="<?php
echo _REALESTATE_MANAGER_LABEL_BUTTON_EDIT_HOUSE; ?>"/>
</div>
</form>
<?php endif;?>
<!-- ************************* end add for show/hiden button "Edit house"***************** -->
<div class="componentheading<?php echo $params->get('pageclass_sfx'); ?> ">
<?php if (trim($house->htitle)) { ?>
<span class="col_text_2"><?php echo $house->htitle; ?></span>
<?php } ?>
<?php if($params->get('show_pricerequest')){ ?>
<div class="rem_house_price">
Tarif à la semaine à partir de :
<?php
if ($realestatemanager_configuration['price_unit_show'] == '1') {
if ($params->get('show_sale_separator')) {
echo "<div class=\"pricemoney\">
<span class=\"money\">"
. formatMoney($house->price, true, $realestatemanager_configuration['price_format']) .
"</span>";
echo "<span class=\"price\"> " . $house->priceunit . "</span></div>";
} else {
echo "<div class=\"pricemoney\"><span class=\"money\">" . $house->price . "</span>";
echo "<span class=\"price\"> " . $house->priceunit . "</span></div>";
}
} else {
if ($params->get('show_sale_separator')) {
echo "<div class=\"pricemoney\"><span class=\"price\">" . $house->priceunit . "</span>";
echo " <span class=\"money\">"
. formatMoney($house->price, true, $realestatemanager_configuration['price_format'])
. "</span></div>";
} else {
echo "<div class=\"pricemoney\"><span class=\"price\">" . $house->priceunit . "</span>";
echo " <span class=\"money\">" . $house->price . "</span></div>";
}
}
if($currencys_price){
foreach ($currencys_price as $key => $row) {
if ($house->priceunit != $key) {
if ($realestatemanager_configuration['price_unit_show'] == '1') {
if ($params->get('show_sale_separator')) {
echo "<div class=\"pricemoney\"><span class=\"money\">"
. formatMoney($row, true, $realestatemanager_configuration['price_format']) . "</span>";
echo "<span class=\"price\"> " . $key . "</span></div>";
} else {
echo "<div class=\"pricemoney\"><span class=\"money\">" . $row . "</span>";
echo "<span class=\"price\"> " . $key . "</span></div>";
}
} else {
if ($params->get('show_sale_separator')) {
echo "<div class=\"pricemoney\"><span class=\"price\">" . $key . "</span>";
echo " <span class=\"money\">"
. formatMoney($row, true, $realestatemanager_configuration['price_format']) .
"</span></div>";
} else {
echo "<div class=\"pricemoney\"><span class=\"price\">" . $key . "</span>";
echo " <span class=\"money\">" . $row . "</span></div>";
}
}
}
}
}
?>
</div>
<?php
} ?>
</div>
<div style="clear:both"></div>
<div class="button_ppe">
<span>
<?php if ($params->get('show_input_print_pdf')) { ?>
<a onclick="window.open(
this.href,'win2','status=no,toolbar=no,scrollbars=yes,titlebar=no,menubar=no,resizable=yes,width=640,height=480,directories=no,location=no');
return false;" rel="nofollow"
href='<?php echo JRoute::_("index.php?option=com_realestatemanager&task=view&id=$id&catid=$catid&Itemid=$Itemid&printItem=pdf&lang=$langContent")?>' title="PDF" rel="nofollow">
<i class="fa fa-file"></i>
</a>
<?php }
?>
<?php if ($params->get('show_input_print_view')) { ?>
<a onclick="window.open(
this.href,'win2','status=no,toolbar=no,scrollbars=yes,titlebar=no,menubar=no,resizable=yes,width=640,height=480,directories=no,location=no');
return false;" rel="nofollow"
href='<?php echo JRoute::_("index.php?option=com_realestatemanager&task=view&id=$id&catid=$catid&Itemid=$Itemid&printItem=print&tmpl=component");?>'
title="Print" rel="nofollow">
<i class="fa fa-print"></i>
</a>
<?php }
?>
<?php if ($params->get('show_input_mail_to')) {
if (version_compare(JVERSION, '1.6', 'lt')) {?>
<a href="<?php echo $mosConfig_live_site;
?>/index.php?option=com_mailto&tmpl=component&link=<?php $url = JFactory::getURI();
echo base64_encode($url->toString()); ?>"
title="E-mail"
onclick="window.open(this.href,'win2','width=400,height=350,menubar=yes,resizable=yes'); return false;">
<i class="fa fa-envelope"></i>
</a>
<?php }else{
require_once JPATH_SITE . '/components/com_mailto/helpers/mailto.php';
$url = JFactory::getURI();
$url_c = $url->toString();
$link = 'index.php?option=com_mailto&tmpl=component&Itemid='
.$Itemid.'&link='.MailToHelper::addLink($url_c);?>
<a href="<?php echo sefRelToAbs($link);?>"
title="E-mail"
onclick="window.open(this.href,'win2','width=400,height=350,menubar=yes,resizable=yes'); return false;">
<?php
if (version_compare(JVERSION, "1.6.0", "lt")) { ?>
<i class="fa fa-envelope"></i>
<?php }
else { ?>
<i class="fa fa-envelope"></i>
<?php } ?>
</a>
<?php }
}
?>
</span>
</div>
<div class="rem_house_location">
<i class="fa fa-map-marker"></i>
<?php if (isset($house->hcountry) && trim($house->hcountry)) { ?>
<span class="col_text_2"><?php echo $house->hcountry; ?></span>,
<?php } if (isset($house->hregion) && trim($house->hregion)) { ?>
<span class="col_text_2"><?php echo $house->hregion; ?></span>,
<?php } if (isset($house->hcity) && trim($house->hcity)) { ?>
<span class="col_text_2"><?php echo $house->hcity; ?></span>,
<?php } if (isset($house->hzipcode) && trim($house->hzipcode)) { ?>
<span class="col_text_2"><?php echo $house->hzipcode; ?></span>,
<?php } if (isset($house->hlocation) && trim($house->hlocation)) { ?>
<span class="col_02"><?php echo $house->hlocation; ?></span>.
<?php } ?>
</div>
<div style="clear:both"></div>
<span class="col_img">
<?php
//for local images
$imageURL = ($house->image_link);
if ($imageURL == '') $imageURL = _REALESTATE_MANAGER_NO_PICTURE_BIG;
$file_name = rem_picture_thumbnail($imageURL,
$realestatemanager_configuration['fotomain']['width'],
$realestatemanager_configuration['fotomain']['high']);
$file = $mosConfig_live_site . '/components/com_realestatemanager/photos/' . $file_name;
echo '<div style="position:relative">';
echo '<img alt="' . $house->htitle . '" title="' . $house->htitle . '" src="' . $file . '" >';
?>
<!-- add wishlist marker -->
<?php
?>
<?php if ($params->get('show_add_to_wishlist')) { ?>
<span class="fa-stack fa-lg i-wishlist i-wishlist-all" >
<?php
if (in_array($house->id, $params->get('wishlist'))) { ?>
<i class="fa fa-star fa-stack-1x" id="icon<?php echo $house->id ?>" title="<?php echo _REALESTATE_MANAGER_LABEL_WISHLIST_REMOVE ?>" onclick="addToWishlist(<?php echo $house->id ?>, <?php echo $my->id ?>)"> </i>
<?php } else { ?>
<i class="fa fa-star-o fa-stack-1x" id="icon<?php echo $house->id ?>" title="<?php echo _REALESTATE_MANAGER_LABEL_WISHLIST_ADD ?>" onclick="addToWishlist(<?php echo $house->id ?>, <?php echo $my->id ?>)"></i>
<?php } ?>
</span>
<?php }
echo '</div>';?>
<!-- end add wishlist marker -->
</span>
<div class="table_gallery table_07">
<?php if (count($house_photos) > 0) { ?>
<div class="gallery_img">
<?php for ($i = 0;$i < count($house_photos);$i++) { ?>
<div class="thumbnail viewHouses"
style="width: <?php echo $realestatemanager_configuration['fotogal']['width'];?>px; height: <?php
echo $realestatemanager_configuration['fotogal']['high'];?>px;" >
<a href="<?php echo $mosConfig_live_site; ?>/components/com_realestatemanager/photos/<?php
echo $house_photos[$i]->main_img; ?>" data-lightbox="rem_roadtrip" title="photo" >
<img alt="<?php echo $house->htitle; ?>" title="<?php echo $house->htitle; ?>"
src="./components/com_realestatemanager/photos/<?php
echo rem_picture_thumbnail($house_photos[$i]->main_img,
$realestatemanager_configuration['fotogal']['width'],
$realestatemanager_configuration['fotogal']['high']); ?>" style = "vertical-align:middle;" />
</a>
</div>
<?php
}
?>
</div>
<?php }
?>
</div>
</div>
<!--<form action="<?php //echo sefRelToAbs($form_action);
?>" method="post" name="house">-->
<?php positions_rem($params->get('view02')); ?>
<div id="rem_house_property">
<?php
$listing_status[0] = _REALESTATE_MANAGER_OPTION_SELECT;
$listing_status1 = explode(',', _REALESTATE_MANAGER_OPTION_LISTING_STATUS);
$i = 1;
foreach ($listing_status1 as $listing_status2) {
$listing_status[$i] = $listing_status2;
$i++;
}
if ($house->listing_status != 0) {
?>
<div class="row_text">
<span class="col_text_1"><?php echo _REALESTATE_MANAGER_LABEL_LISTING_STATUS; ?>:</span>
<span class="col_text_2"><?php echo $listing_status[$house->listing_status]; ?></span>
</div>
<?php
}
?>
<?php
$property_type[0] = _REALESTATE_MANAGER_OPTION_SELECT;
$property_type1 = explode(',', _REALESTATE_MANAGER_OPTION_PROPERTY_TYPE);
$i = 1;
foreach ($property_type1 as $property_type2) {
$property_type[$i] = $property_type2;
$i++;
}
if ($house->property_type != 0) {
?>
<div class="row_text">
<span class="col_text_1"><?php echo _REALESTATE_MANAGER_LABEL_PROPERTY_TYPE; ?>:</span>
<span class="col_text_2"><?php echo $property_type[$house->property_type]; ?></span>
</div>
<?php
}
?>
<?php if (trim($house->houseid)) { ?>
<div class="row_text">
<span class="col_text_1"><?php echo _REALESTATE_MANAGER_LABEL_PROPERTYID; ?>:</span>
<span class="col_text_2"><?php echo $house->houseid; ?></span>
</div>
<?php
}
?>
<?php
$listing_type[0] = _REALESTATE_MANAGER_OPTION_SELECT;
$listing_type[1] = _REALESTATE_MANAGER_OPTION_FOR_RENT;
$listing_type[2] = _REALESTATE_MANAGER_OPTION_FOR_SALE;
if ($house->listing_type != 0) {
?>
<div class="row_text">
<span class="col_text_icon"></span>
<span class="col_01"><?php echo _REALESTATE_MANAGER_LABEL_LISTING_TYPE; ?>:</span>
<span class="col_02"><?php echo $listing_type[$house->listing_type]; ?></span>
</div>
<?php
}
?>
<?php if ($realestatemanager_configuration['extra1'] == 1 && $house->extra1 != "") {
?>
<div class="row_text">
<span class="col_text_1"><?php echo _REALESTATE_MANAGER_LABEL_EXTRA1; ?>:</span>
<span class="col_text_2"><?php echo $house->extra1; ?></span>
</div>
<?php
}
if ($realestatemanager_configuration['extra2'] == 1 && $house->extra2 != "") {
?>
<div class="row_text">
<span class="col_text_1"><?php echo _REALESTATE_MANAGER_LABEL_EXTRA2; ?>:</span>
<span class="col_text_2"><?php echo $house->extra2; ?></span>
</div>
<?php
}
if ($realestatemanager_configuration['extra3'] == 1 && $house->extra3 != "") {
?>
<div class="row_text">
<span class="col_text_1"><?php echo _REALESTATE_MANAGER_LABEL_EXTRA3; ?>:</span>
<span class="col_text_2"><?php echo $house->extra3; ?></span>
</div>
<?php
}
if ($realestatemanager_configuration['extra4'] == 1 && $house->extra4 != "") {
?>
<div class="row_text">
<span class="col_text_1"><?php echo _REALESTATE_MANAGER_LABEL_EXTRA4; ?>:</span>
<span class="col_text_2"><?php echo $house->extra4; ?></span>
</div>
<?php
}
if ($realestatemanager_configuration['extra5'] == 1 && $house->extra5 != "") {
?>
<div class="row_text">
<span class="col_text_1"><?php echo _REALESTATE_MANAGER_LABEL_EXTRA5; ?>:</span>
<span class="col_text_2"><?php echo $house->extra5; ?></span>
</div>
<?php
}
if ($realestatemanager_configuration['extra6'] == 1 && $house->extra6 > 0) {
$extra1 = explode(',', _REALESTATE_MANAGER_EXTRA6_SELECTLIST);
$i = 1;
foreach ($extra1 as $extra2) {
$extra[$i] = $extra2;
$i++;
}
?>
<div class="row_text">
<span class="col_text_1"><?php echo _REALESTATE_MANAGER_LABEL_EXTRA6; ?>:</span>
<span class="col_text_2"><?php echo $extra[$house->extra6]; ?></span>
</div>
<?php
}
if ($realestatemanager_configuration['extra7'] == 1 && $house->extra7 > 0) {
$extra1 = explode(',', _REALESTATE_MANAGER_EXTRA7_SELECTLIST);
$i = 1;
foreach ($extra1 as $extra2) {
$extra[$i] = $extra2;
$i++;
}
?>
<div class="row_text">
<span class="col_text_1"><?php echo _REALESTATE_MANAGER_LABEL_EXTRA7; ?>:</span>
<span class="col_text_2"><?php echo $extra[$house->extra7]; ?></span>
</div>
<?php
}
if ($realestatemanager_configuration['extra8'] == 1 && $house->extra8 > 0) {
$extra1 = explode(',', _REALESTATE_MANAGER_EXTRA8_SELECTLIST);
$i = 1;
foreach ($extra1 as $extra2) {
$extra[$i] = $extra2;
$i++;
}
?>
<div class="row_text">
<span class="col_text_1"><?php echo _REALESTATE_MANAGER_LABEL_EXTRA8; ?>:</span>
<span class="col_text_2"><?php echo $extra[$house->extra8]; ?></span>
</div>
<?php
}
if ($realestatemanager_configuration['extra9'] == 1 && $house->extra9 > 0) {
$extra1 = explode(',', _REALESTATE_MANAGER_EXTRA9_SELECTLIST);
$i = 1;
foreach ($extra1 as $extra2) {
$extra[$i] = $extra2;
$i++;
}
?>
<div class="row_text">
<span class="col_text_1"><?php echo _REALESTATE_MANAGER_LABEL_EXTRA9; ?>:</span>
<span class="col_text_2"><?php echo $extra[$house->extra9]; ?></span>
</div>
<?php
}
if ($realestatemanager_configuration['extra10'] == 1 && $house->extra10 > 0) {
$extra1 = explode(',', _REALESTATE_MANAGER_EXTRA10_SELECTLIST);
$i = 1;
foreach ($extra1 as $extra2) {
$extra[$i] = $extra2;
$i++;
}
?>
<div class="row_text">
<span class="col_text_1"><?php echo _REALESTATE_MANAGER_LABEL_EXTRA10; ?>:</span>
<span class="col_text_2"><?php echo $extra[$house->extra10]; ?></span>
</div>
<?php }
?>
<!--add edocument -->
<?php
if ($params->get('show_edocsrequest') && $house->edok_link != null) {
$session = JFactory::getSession();
$sid = $session->getId();
$session->set("ssmid", $sid);
setcookie('ssd', $sid, time() + 60 * 60 * 24, "/");
?>
<div class="row_text">
<span class="col_text_1"><?php echo _REALESTATE_MANAGER_LABEL_EDOCUMENT; ?>:</span>
<span class="col_text_2">
<a href="<?php
echo sefRelToAbs('index.php?option=com_realestatemanager&task=mdownload&id='
. $house->id . '&Itemid=' . $Itemid); ?>" target="blank">
<?php echo _REALESTATE_MANAGER_LABEL_EDOCUMENT_DOWNLOAD; ?>
</a>
</span>
</div>
<?php
} //end if
?>
</div>
<div class="tabs_buttons">
<!--list of the tabs-->
<ul id="countrytabs" class="shadetabs">
<li>
<a href="#" rel="country1" class="selected"><?php echo _REALESTATE_MANAGER_TAB_DESCRIPTION; ?>
</a>
</li>
<?php
if (($params->get('show_location') && $params->get('show_locationtab_registrationlevel'))
|| ($params->get('street_view') && $params->get('street_view_registrationlevel'))) {
?>
<li>
<a href="#" rel="country2" onmouseup="setTimeout('initialize()',10)">
<?php echo _REALESTATE_MANAGER_TAB_LOCATION; ?>
</a>
</li>
<?php
}
?>
<?php
if ($params->get('show_reviews_tab')) {
if ($params->get('show_reviewstab_registrationlevel')) {
?>
<li>
<a href="#" rel="country4"><?php echo _REALESTATE_MANAGER_TAB_REVIEWS; ?></a>
</li>
<?php
}
}
?>
<?php
if ($params->get('calendar_show') && $house->listing_type == 1) {
if ($params->get('calendar_option_registrationlevel','')) {
?>
<li>
<a href="#" rel="country5"><?php echo _REALESTATE_MANAGER_LABEL_CALENDAR_CALENDAR; ?></a>
</li>
<?php
}
}
?>
</ul>
</div>
<?php positions_rem($params->get('view03')); ?>
<!--begin tabs-->
<div id="tabs">
<div id="country1" class="tabcontent">
<div class="rem_type_house">
<?php if (isset($house->rooms) && trim($house->rooms)) { ?>
<div class="row_text">
<i class="fa fa-building-o"></i>
<span class="col_text_1"><?php echo _REALESTATE_MANAGER_LABEL_ROOMS; ?>:</span>
<span class="col_text_2"><?php echo $house->rooms; ?></span>
</div>
<?php } if (isset($house->bathrooms) && trim($house->bathrooms)) { ?>
<div class="row_text">
<i class="fa fa-tint"></i>
<span class="col_text_1"><?php echo _REALESTATE_MANAGER_LABEL_BATHROOMS; ?>:</span>
<span class="col_text_2"><?php echo $house->bathrooms; ?></span>
</div>
<?php } if (isset($house->bedrooms) && trim($house->bedrooms)) { ?>
<div class="row_text">
<i class="fa fa-inbox"></i>
<span class="col_text_1"><?php echo _REALESTATE_MANAGER_LABEL_BEDROOMS; ?>:</span>
<span class="col_text_2"><?php echo $house->bedrooms; ?></span>
</div>
<?php
}
?>
<?php if (isset($house->year) && trim($house->year)) { ?>
<div class="row_text">
<i class="fa fa-calendar"></i>
<span class="col_text_1"><?php echo _REALESTATE_MANAGER_LABEL_BUILD_YEAR; ?>:</span>
<span class="col_text_2"><?php echo $house->year; ?></span>
</div>
<?php } ?>
<?php if (isset($house->garages) && trim($house->garages)) { ?>
<div class="row_text">
<i class="fa fa-truck"></i>
<span class="col_text_1"><?php echo _REALESTATE_MANAGER_LABEL_GARAGES; ?>:</span>
<span class="col_text_2"><?php echo $house->garages; ?></span>
</div>
<?php }
if (isset($house->lot_size) && trim($house->lot_size)) {
?>
<div class="row_text">
<i class="fa fa-arrows-alt"></i>
<span class="col_text_1"><?php echo _REALESTATE_MANAGER_LABEL_LOT_SIZE; ?>:</span>
<span class="col_text_2">
<?php echo $house->lot_size; ?> <?php echo _REALESTATE_MANAGER_LABEL_SIZE_SUFFIX_AR; ?>
</span>
</div>
<?php }
if (isset($house->house_size) && trim($house->house_size)) {
?>
<div class="row_text">
<i class="fa fa-expand"></i>
<span class="col_text_1"><?php echo _REALESTATE_MANAGER_LABEL_HOUSE_SIZE; ?>:</span>
<span class="col_text_2">
<?php echo $house->house_size; ?> <?php echo _REALESTATE_MANAGER_LABEL_SIZE_SUFFIX; ?>
</span>
</div>
<?php }
////////////////////////////////////START show video\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
if (!empty($videos)) {
$youtubeCode = "";
$videoSrc = array();
$videoSrcHttp = "";
$videoType = array();
foreach($videos as $video) {
if ($video->youtube) {
$youtubeCode = $video->youtube;
} else if ($video->src) {
$videoSrc[] = $video->src;
if($video->type)
$videoType[] = $video->type;
}
}?>
<div class="row_06">
<span class="realestate_video">
<strong class="col_01"><?php echo _REALESTATE_MANAGER_LABEL_VIDEO; ?>:</strong>
<?php
if (!empty($youtubeCode)) { ?>
<iframe width="420" height="315" frameborder="0"
src="//www.youtube.com/embed/<?php echo $youtubeCode ?>"></iframe>
<?php
} else if (!empty($videoSrc) && empty($youtubeCode)) { ?>
<video width="320" height="240" controls>
<?php
for ($i = 0;$i < count($videoSrc);$i++) {
if(!strstr($videoSrc[$i], "http") && $videoType) {
echo '<source src="' . $mosConfig_live_site . $videoSrc[$i] .'"'.
' type="' . $videoType[$i] .'">';
}else{
echo '<source src="' . $videoSrc[$i] .'"'.
' type="' . $videoType[$i] .'">';
}
}
if (!empty($tracks)) {
for ($i = 0;$i < count($tracks);$i++) {
($i==0)?$default='default="default"':$default='';
if (!strstr($tracks[$i]->src, "http")) {
echo '<track src="' . $mosConfig_live_site.$tracks[$i]->src . '"'.
' kind="' . $tracks[$i]->kind .'"'.
' srclang="' . $tracks[$i]->scrlang .'"'.
' label="' . $tracks[$i]->label . '" '.$default.'>';
}else{
echo '<track src="' .$src . '"'.
' kind="' . $tracks[$i]->kind .'"'.
' srclang="' . $tracks[$i]->scrlang .'"'.
' label="'.$tracks[$i]->label.'" '.$default.'>';
}
}
} ?>
</video>
</span>
<?php
} ?>
</div>
<?php
}
////////////////////////////////////END show video\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
if (isset($house->description) && trim($house->description)) {
?>
<div class="rem_house_desciption"><?php positions_rem($house->description); ?></div>
<?php
}
?>
</div>
<div class="table_tab_01 table_03">
<!-- ******************************************************************* -->
<?php
global $database, $realestatemanager_configuration;
if($realestatemanager_configuration['special_price']['show']){
$switchTranslateDayNight = _REALESTATE_MANAGER_RENT_SPECIAL_PRICE_PER_DAY;
}else{
$switchTranslateDayNight = _REALESTATE_MANAGER_RENT_SPECIAL_PRICE_PER_NIGHT;
}
$query = "select * from #__rem_rent_sal WHERE fk_houseid='$house->id'";
$database->setQuery($query);
$rentTerm = $database->loadObjectList();
if(isset($rentTerm[0]->special_price)) { ?>
<div class = "row_17">
<span class="col_01"><?php echo _REALESTATE_MANAGER_RENT_SPECIAL_PRICE; ?>:</span> </br>
<table class="adminlist adminlist_04">
<tr>
<th class="title" width = "15%" align ='center' ><?php
echo _REALESTATE_MANAGER_FROM; ?></th>
<th class="title" width = "15%" align ='center' ><?php
echo _REALESTATE_MANAGER_TO; ?></th>
<th class="title" width = "15%" align ='center'><?php
echo $switchTranslateDayNight; ?></th>
<th class="title" width = "20%" align ='center' ><?php
echo _REALESTATE_MANAGER_LABEL_REVIEW_COMMENT; ?></th>
</tr>
<?php
$DateToFormat = str_replace("D",'d',
(str_replace("M",'m',(str_replace('%','',
$realestatemanager_configuration['date_format'])))));
for ($i = 0; $i < count($rentTerm); $i++) {
$date_from = new DateTime($rentTerm[$i]->price_from);
$date_to = new DateTime($rentTerm[$i]->price_to);
?>
<tr>
<td align ='center'><?php echo date_format($date_from, "$DateToFormat"); ?></td>
<td align ='center'><?php echo date_format($date_to, "$DateToFormat"); ?></td>
<?php
if ($realestatemanager_configuration['sale_separator'] == '1') { ?>
<td align ='center'><?php
echo formatMoney($rentTerm[$i]->special_price, true,
$realestatemanager_configuration['price_format']); ?></td>
<?php } else { ?>
<td align ='center'><?php echo $rentTerm[$i]->special_price; ?></td>
<?php }
?>
<td align ='center'><?php echo $rentTerm[$i]->comment_price; ?></td>
</tr>
<?php } ?>
</table>
</div>
<?php } ?>
<!-- ******************************************************************* -->
<div class="table_country3 ">
<?php
if (count($house_feature)) {
?>
<div class="row_text">
<div class="rem_features_title">
<?php echo _REALESTATE_MANAGER_LABEL_FEATURED_MANAGER_FEATURE; ?>:
</div>
<span class="col_text_2">
<?php
for ($i = 0; $i < count($house_feature); $i++) {
if ($realestatemanager_configuration['manager_feature_category'] == 1) {
if ($i != 0) {
if ($house_feature[$i]->categories !== $house_feature[$i - 1]->categories)
echo "<div class='rem_features_category'>" . $house_feature[$i]->categories . "</div>";
} else
echo "<div class='rem_features_category'>" . $house_feature[$i]->categories . "</div>";
}
echo "<span class='rem_features_name'><i class='fa fa-check rem_fa'></i>"
. $house_feature[$i]->name . "</span>";
if ($i != count($house_feature)-1) {
if ($house_feature[$i]->categories == $house_feature[$i + 1]->categories);
}
?>
<?php }
?>
</span>
</div>
<?php }
?>
</div>
</div>
</div><!--end of tab-->
<div id="country2" class="tabcontent">
<!--if we are given the coordinates, then display latitude, longitude and a map with a marker -->
<?php if ($house->hlatitude && $house->hlongitude) {?>
<div class="table_latitude table_04">
<?php
if(($params->get('show_location') && $params->get('show_locationtab_registrationlevel'))){ ?>
<div id="map_canvas" class="re_map_canvas re_map_canvas_02"></div>
<?php
}
if($params->get('street_view') && $params->get('street_view_registrationlevel')){ ?>
<div id="map_pano" class="re_map_canvas re_map_canvas_02"></div>
<?php
} ?>
</div>
<?php
} else
echo _REALESTATE_MANAGER_LABEL_NO_LOCATION_AVAILIBLE;
?>
</div>
<!--tab for reviews-->
<div id="country4" class="tabcontent">
<?php
//show the reviews
if ($reviews = $house->getReviews()) {
?>
<br />
<div class="componentheading<?php echo $params->get('pageclass_sfx'); ?>">
<?php echo _REALESTATE_MANAGER_LABEL_REVIEWS; ?>
</div>
<div class="reviews_table table_06">
<?php
if ($reviews != null && count($reviews) > 0) {
for ($m = 0, $n = count($reviews); $m < $n; $m++) {
$review = $reviews[$m];
if ($review->published != 0) {
?>
<div class="box_comment">
<div class="user_name"><?php echo $review->user_name; ?></div>
<span class="arrow_up_comment"></span>
<div class="head_comment">
<div class="title_rating">
<h4 class="col_title_rev"><?php echo $review->title; ?></h4>
<span class="col_rating_rev">
<img src="./components/com_realestatemanager/images/rating-<?php
echo $review->rating; ?>.png"
alt="<?php echo ($review->rating) / 2; ?>" border="0" align="right"/>
</span>
</div>
<div class="row_comment">
<?php echo $review->comment; ?>
</div>
<div class="date">
<span class="date_format">
<?php echo data_transform_rem($review->date); ?>
</span>
</div>
</div>
</div>
<?php
}
}
}
?>
</div>
<?php
} else{
echo "<p>No reviews for house</p>";
}
if ($params->get('show_reviews')) {
$reviews = $house->getReviews();
?><?php
if ($params->get('show_inputreviews')) {
?><?php positions_rem($params->get('view07')); ?><div id="hidden_review">
<form action="<?php echo sefRelToAbs("index.php?option="
. $option . "&task=review_house&Itemid=" .
$Itemid); ?>" method="post" name="review_house">
<input type="hidden" name="user_name" value="<?php echo $my->username ?>">
<input type="hidden" name="fk_userid" value="<?php echo $my->id ?>">
<input type="hidden" name="user_email" value="<?php echo $my->email ?>">
<div class="componentheading<?php echo $params->get('pageclass_sfx'); ?>">
<hr />
<?php echo _REALESTATE_MANAGER_LABEL_ADDREVIEW; ?>
</div>
<div class="add_table_review table_09">
<div class="row_01"><?php echo _REALESTATE_MANAGER_LABEL_REVIEW_TITLE; ?></div>
<div class="row_02">
<input class="inputbox" type="text" name="title" size="80"
value="<?php if (isset($_REQUEST["title"])) {
echo $_REQUEST["title"]; } ?>" />
</div>
<div class="row_03"><?php echo _REALESTATE_MANAGER_LABEL_REVIEW_COMMENT; ?></div>
<div class="row_04">
<?php
$comm_val = "";
if (isset($_REQUEST["comment"])) {
$comm_val = protectInjectionWithoutQuote("comment",'','STRING');
}
//editorArea( 'editor1', $comm_val, 'comment', '410', '200', '60', '10' );
?>
<textarea name="comment" cols="50" rows="8" ><?php echo $comm_val; ?></textarea>
</div>
<!-- #### RATING #### -->
<?php if (version_compare(JVERSION, "3.0", "ge")): ?>
<script type="text/javascript">
os_img_path = '<?php echo $mosConfig_live_site . '/components/com_realestatemanager/images/'; ?>' ;
jQuerREL(document).ready(function(){
jQuerREL('#star').raty({
starHalf: os_img_path+'star-half.png',
starOff: os_img_path+'star-off.png',
starOn: os_img_path+'star-on.png'
});
});
</script>
<div class="row_rating_j3">
<span class="lable_rating"><?php echo _REALESTATE_MANAGER_LABEL_REVIEW_RATING; ?></span>
<span id="star"></span>
</div>
<?php else:
?>
<div class="row_rating_j2">
<span class="col_01"><?php echo _REALESTATE_MANAGER_LABEL_REVIEW_RATING; ?></span>
<br />
<span>
<?php
$k = 0;
while ($k < 11) {
?>
<input type="radio" name="rating" value="<?php echo $k; ?>" <?php
if (isset($_REQUEST["rating"]) && $_REQUEST["rating"] == $k) {
echo "CHECKED";
}
?> alt="Rating" />
<img src="./components/com_realestatemanager/images/rating-<?php echo $k; ?>.png"
alt="<?php echo ($k) / 2; ?>" border="0" /><br />
<?php
$k++;
}
?>
</span>
</div>
<?php endif; ?>
<!--************************* begin add antispam guest ********************-->
<?php if ($params->get('captcha_option')) {
if ($params->get('captcha_option_registrationlevel') && ($my->id == 0)) {
?>
<div class="row_capcha">
<!--************************* begin insetr image **********************-->
<?php
// begin create kod
$st = " ";
$algoritm = mt_rand(1, 2);
switch ($algoritm) {
case 1:
for ($j = 0; $j < 6; $j+= 2) {
$st = substr_replace($st, chr(mt_rand(97, 122)), $j, 1); //abc
$st = substr_replace($st, chr(mt_rand(50, 57)), $j + 1, 1); //23456789
}
break;
case 2:
for ($j = 0; $j < 6; $j+= 2) {
$st = substr_replace($st, chr(mt_rand(50, 57)), $j, 1); //23456789
$st = substr_replace($st, chr(mt_rand(97, 122)), $j + 1, 1); //abc
}
break;
}
//************** begin search in $st simbol 'o, l, i, j, t, f' ***************************
$st_validator = "olijtf";
for ($j = 0; $j < 6; $j++) {
for ($i = 0; $i < strlen($st_validator); $i++) {
if ($st[$j] == $st_validator[$i]) {
$st[$j] = chr(mt_rand(117, 122)); //uvwxyz
}
}
}
//************** end search in $st simbol 'o, l, i, j, t, f' *****************************
$session = JFactory::getSession();
$session->set('captcha_keystring', $st);
if (isset($_REQUEST['error']) && $_REQUEST['error'] != "")
echo "<font style='color:red'>" . $_REQUEST['error'] . "</font><br />";
$name_user = "";
if (isset($_REQUEST['name_user']))
$name_user = $_REQUEST['name_user'];
if (isset($_REQUEST["err_msg"]))
echo "<script> alert('Error: " . $_REQUEST["err_msg"] . "'); </script>\n";
echo "<br /><img src='" . JRoute::_( "index.php?option=com_realestatemanager&task=secret_image&Itemid=" . $Itemid)."'
alt='CAPTCHA_picture'/><br/>";
?>
<!--********************** end insert image *******************************-->
</div>
<div class="row_05"><?php echo _REALESTATE_MANAGER_LABEL_REVIEW_KEYGUEST; ?></div>
<div class="row_06">
<input class="inputbox" type="text" name="keyguest" size="6" maxlength="6" />
</div>
<?php
}
}
?>
<!--**************************** end add antispam guest ******************************-->
<div class="row_button_review">
<span class="button_save">
<!-- save review button-->
<input class="button" type="button" value="<?php
echo _REALESTATE_MANAGER_LABEL_BUTTON_SAVE; ?>" onclick="review_submitbutton()"/>
</span>
</div>
</div>
<input type="hidden" name="fk_houseid" value="<?php echo $house->id; ?>" />
<input type="hidden" name="catid" value="<?php $temp = $house->catid;
echo $temp[0]; ?>" />
</form>
</div>
<!-- end <div id="hidden_review"> -->
<?php
} //end if($params->get('show_inputreviews'))
} // end if( $params->get('show_reviews'))
?>
</div>
<?php
/////////////////////////////////////////////START CALENDAR\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
if ($house->listing_type == 1) {
if ($params->get('show_rentrequest') && $params->get('show_rentstatus') && $params->get('calendar_show')) {
?>
<div id="country5" class="tabcontent">
<div style="text-align: center;" >
<?php
if (isset($_POST['month']) && isset($_POST['year'])) {
$month = $_POST['month'];
$year = $_POST['year'];
$calendar = PHP_realestatemanager::getCalendar($month, $year, $house->id);
} else {
$month = date("m", mktime(0, 0, 0, date('m'), 1, date('Y')));
$year = date("Y", mktime(0, 0, 0, date('m'), 1, date('Y')));
$calendar = PHP_realestatemanager::getCalendar($month, $year, $house->id);
}
?>
<h4><?php echo _REALESTATE_MANAGER_LABEL_CALENDAR_TITLE; ?></h4>
<form action="" method="post" id="calendar" name="calendar" >
<select name="month" class="inputbox" onChange="form.submit()">
<option value="1" <?php if ($month == '1') echo "selected" ?> >
<?php echo JText::_('JANUARY'); ?>
</option>
<option value="2" <?php if ($month == '2') echo "selected" ?> >
<?php echo JText::_('FEBRUARY'); ?>
</option>
<option value="3" <?php if ($month == '3') echo "selected" ?> >
<?php echo JText::_('MARCH'); ?>
</option>
<option value="4" <?php if ($month == '4') echo "selected" ?> >
<?php echo JText::_('APRIL'); ?>
</option>
<option value="5" <?php if ($month == '5') echo "selected" ?> >
<?php echo JText::_('MAY'); ?>
</option>
<option value="6" <?php if ($month == '6') echo "selected" ?> >
<?php echo JText::_('JUNE'); ?>
</option>
<option value="7" <?php if ($month == '7') echo "selected" ?> >
<?php echo JText::_('JULY'); ?>
</option>
<option value="8" <?php if ($month == '8') echo "selected" ?> >
<?php echo JText::_('AUGUST'); ?>
</option>
<option value="9" <?php if ($month == '9') echo "selected" ?> >
<?php echo JText::_('SEPTEMBER'); ?>
</option>
<option value="10" <?php if ($month == '10') echo "selected" ?> >
<?php echo JText::_('OCTOBER'); ?>
</option>
<option value="11" <?php if ($month == '11') echo "selected" ?> >
<?php echo JText::_('NOVEMBER'); ?>
</option>
<option value="12" <?php if ($month == '12') echo "selected" ?> >
<?php echo JText::_('DECEMBER'); ?>
</option>
</select>
<select name="year" class="inputbox" onChange="form.submit()">
<option value="2012" <?php if ($year == '2012') echo "selected" ?> >2012</option>
<option value="2013" <?php if ($year == '2013') echo "selected" ?> >2013</option>
<option value="2014" <?php if ($year == '2014') echo "selected" ?> >2014</option>
<option value="2015" <?php if ($year == '2015') echo "selected" ?> >2015</option>
<option value="2016" <?php if ($year == '2016') echo "selected" ?> >2016</option>
<option value="2017" <?php if ($year == '2017') echo "selected" ?> >2017</option>
</select>
</form>
<div class="rem_tableC basictable">
<div class="row_01">
<span class="col_01"><?php echo $calendar->tab1; ?></span>
<span class="col_02"><?php echo $calendar->tab2; ?></span>
<span class="col_03"><?php echo $calendar->tab3; ?></span>
<span class="col_03"><?php echo $calendar->tab4; ?></span>
</div>
<div class="row_02">
<span class="col_01"><?php echo $calendar->tab21; ?></span>
<span class="col_02"><?php echo $calendar->tab22; ?></span>
<span class="col_02"><?php echo $calendar->tab23; ?></span>
<span class="col_03"><?php echo $calendar->tab24; ?><br /></span>
</div>
<div class="calendar_notation row_03">
<div class="row_calendar">
<span class="label_calendar_available">
<?php echo _REALESTATE_MANAGER_LABEL_CALENDAR_AVAILABLE; ?></span>
<div class="calendar_available_notation"></div>
</div>
<div class="row_calendar">
<span class="label_calendar_available">
<?php echo _REALESTATE_MANAGER_LABEL_CALENDAR_NOT_AVAILABLE; ?></span>
<div class="calendar_not_available_notation"></div>
</div>
</div>
</div>
</div>
</div>
<?php
}
}
/////////////////////////////////////////////END CALENDAR\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
?>
</div> <!--end all tabs -->
<script type="text/javascript">
var countries=new ddtabcontent("countrytabs")
countries.setpersist(true)
countries.setselectedClassTarget("link") //"link" or "linkparent"
countries.init()
</script>
</div>
<div class="span3">
<?php positions_rem($params->get('view05')); ?>
<?php if ($params->get('show_owner_line') ==1 && $params->get('show_owner_line') ==1) {
?>
<div class="rem_house_contacts">
<div id="rem_house_titlebox">
<?php echo _REALESTATE_MANAGER_LABEL_CONTACT_AGENT ; ?>
</div>
<?php if (isset($house->agent) && trim($house->agent)) { ?>
<span class="col_02"><?php echo $house->agent; ?></span>
<?php
}
?>
<?php
if ($params->get('show_owner_line') && $house->ownername != '' || $house->owneremail != '') {
if ($params->get('show_owner_registrationlevel')) {
?>
<span class="col_02"><?php echo $house->ownername, '</br>', $house->owneremail; ?></span>
<?php
}
}
?>
<?php
if ($params->get('show_contacts_line')) {
if ($params->get('show_contacts_registrationlevel')) {
if (isset($house->contacts) && trim($house->contacts)) {
?>
<span class="col_02"><?php echo $house->contacts; ?></span>
<?php
}
}
}
?>
</div>
<?php
} ?>
<?php
if($house->listing_type != 0) {?>
<div class="rem_buying_house">
<?php
if ($params->get('show_pricerequest')) {
?>
<?php
}
?>
<?php
if ($house->listing_type == 1) {
if ($params->get('show_rentrequest') && $params->get('show_rentstatus') && ($house->price > 0)) {
?>
<?php
if ($option != 'com_realestatemanager') {
$form_action = "index.php?option=" . $option .
"&task=save_rent_request&Itemid=" . $Itemid ;
} else
$form_action = "index.php?option=com_realestatemanager&task=save_rent_request&Itemid=" . $Itemid;
?>
<div id="rem_house_titlebox">
<?php echo _REALESTATE_MANAGER_LABEL_BOOK_NOW ; ?>
</div>
<form action="<?php echo sefRelToAbs($form_action); ?>" method="post" name="rent_request_form">
<div id="show_buying">
<input type="hidden" name="bid[]" value="<?php echo $house->id; ?>" />
<input type="hidden" name="houseid" id="houseid" value="<?php echo $house->id ?>" maxlength="80" />
<input type="hidden" name="calculated_price" id="calculated_price" value="" maxlength="80" />
<?php
global $my;
if ($my->guest) {
?>
<div class="row_01">
<div id="user_name_warning"></div>
<input class="inputbox" id="alert_name" type="text" name="user_name" size="38"
maxlength="80" placeholder="<?php echo _REALESTATE_MANAGER_LABEL_RENT_REQUEST_NAME ; ?>*" />
</div>
<div class="row_02">
<div id="user_email_warning"></div>
<input class="inputbox" id="alert_mail" type="text" name="user_email" size="30"
maxlength="80" placeholder="<?php echo _REALESTATE_MANAGER_LABEL_RENT_REQUEST_EMAIL; ?>*" />
</div>
<?php
} else {
?>
<div class="row_03">
<div id="user_name_warning"></div>
<input class="inputbox" id="alert_name" type="text" name="user_name" size="38"
maxlength="80" value="<?php echo $my->name; ?>"
placeholder="<?php echo _REALESTATE_MANAGER_LABEL_RENT_REQUEST_NAME; ?>*" />
</div>
<div class="row_04">
<div id="user_email_warning"></div>
<input id="alert_mail" class="inputbox" type="text" name="user_email" size="30"
maxlength="80" value="<?php echo $my->email; ?>"
placeholder="<?php echo _REALESTATE_MANAGER_LABEL_RENT_REQUEST_EMAIL; ?>*" />
</div>
<?php
}
?>
<script type="text/javascript">
Date.prototype.toLocaleFormat = function(format) {
var f = {Y : this.getYear() + 1900,m : this.getMonth() + 1,d : this.getDate(),
H : this.getHours(),M : this.getMinutes(),S : this.getSeconds()}
for(k in f)
format = format.replace('%' + k, f[k] < 10 ? "0" + f[k] : f[k]);
return format;
};
window.onload = function ()
{
var today = new Date();
var date = today.toLocaleFormat("<?php echo $realestatemanager_configuration['date_format'] ?>");
//fix later //first load date dug.
// document.getElementById('rent_from').value = date;
// document.getElementById('rent_until').value = date;
};
</script>
<div class="row_05">
<?php
// editorArea('editor1', '', 'user_mailing', '400', '200', '30', '5');
?>
<textarea name="user_mailing" cols="50" rows="8" placeholder="<?php
echo _REALESTATE_MANAGER_TAB_DESCRIPTION; ?>" ></textarea>
</div>
<div>
<p class="warning">Note : Les locations fonctionnent à la semaine.</p>
<p>Durée de réservation en semaine :</p>
<select id="week">
<option value="1" selected>1</option>
<option value="2" >2</option>
<option value="3">3</option>
</select>
</div>
<div class="row_06">
<p><?php echo _REALESTATE_MANAGER_LABEL_RENT_REQUEST_FROM; ?>:</p>
<?php global $realestatemanager_configuration;?>
<p><input type="text" id="rent_from" name="rent_from"></p>
</div>
<div class="row_07">
<p><?php echo _REALESTATE_MANAGER_LABEL_RENT_REQUEST_UNTIL; ?>:</p>
<p><input type="text" id="rent_until" name="rent_until"></p>
</div>
</div>
<script>
jQuerREL("#rent_from, #week").change(function() {
var rent_from_val = jQuerREL("#rent_from").val();
var week = jQuerREL("#week").val();
//var rent_until = jQuerREL("#rent_until");
if(week == 1)
{
var dataAsObject = jQuerREL("#rent_from").datepicker('getDate');
dataAsObject.setDate(dataAsObject.getDate() + 6);
var rent_until = new Date(dataAsObject);
var rent_until = getUntilDate(rent_until);
jQuerREL("#rent_until").val(rent_until);
jQuerREL("#rent_until").attr("disabled","disabled");
updatePrice();
}
else if (week == 2)
{
var dataAsObject = jQuerREL("#rent_from").datepicker('getDate');
dataAsObject.setDate(dataAsObject.getDate() + 13);
var rent_until = new Date(dataAsObject);
var rent_until = getUntilDate(rent_until);
jQuerREL("#rent_until").val(rent_until);
jQuerREL("#rent_until").attr("disabled","disabled");
updatePrice();
}
else
{
var dataAsObject = jQuerREL("#rent_from").datepicker('getDate');
dataAsObject.setDate(dataAsObject.getDate() + 20);
var rent_until = new Date(dataAsObject);
var rent_until = getUntilDate(rent_until);
jQuerREL("#rent_until").val(rent_until);
jQuerREL("#rent_until").attr("disabled","disabled");
updatePrice();
}
//newdate.setDate(newdate.getDate() - 7)
function updatePrice()
{
var rent_from = jQuerREL(" #rent_from ").val();
var rent_until = jQuerREL(" #rent_until ").val();
var week = jQuerREL(" #week ").val();
jQuerREL.ajax({
type: "POST",
url: "index.php?option=com_realestatemanager&task=ajax_rent_calcualete"
+"&bid=<?php echo $house->id; ?>&rent_from="+
rent_from+"&rent_until="+rent_until+"&week="+week,
data: { " #do " : " #1 " },
update: jQuerREL(" #message-here "),
success: function( data ) {
jQuerREL("#message-here").html(data);
jQuerREL("#calculated_price").val(data);
}
});
}
function getUntilDate(dateObject) {
var d = new Date(dateObject);
var day = d.getDate();
var month = d.getMonth() + 1;
var year = d.getFullYear();
if (day < 10) {
day = "0" + day;
}
if (month < 10) {
month = "0" + month;
}
var date = day + "-" + month + "-" + year;
return date;
};
});
</script>
<div id="alert_date" name = "alert_date"> <span id="alert_date"> </span> </div>
<div id="price_1">
<span><?php echo _REALESTATE_MANAGER_LABEL_PRICE. ': '; ?></span>
<span id="message-here"> </span>
<span><?php //echo $house->priceunit; ?></span>
</div>
<div id="message-here"> </div>
<div id="captcha-block">
<!--************************* begin add antispam guest ********************-->
<?php if ($params->get('captcha_option_booking')) {
if ($params->get('captcha_option_booking_registrationlevel') && ($my->id == 0)) {
?>
<div class="row_capcha">
<!--************************* begin insetr image **********************-->
<?php
// begin create kod
$st = " ";
$algoritm = mt_rand(1, 2);
switch ($algoritm) {
case 1:
for ($j = 0; $j < 6; $j+= 2) {
$st = substr_replace($st, chr(mt_rand(97, 122)), $j, 1); //abc
$st = substr_replace($st, chr(mt_rand(50, 57)), $j + 1, 1); //23456789
}
break;
case 2:
for ($j = 0; $j < 6; $j+= 2) {
$st = substr_replace($st, chr(mt_rand(50, 57)), $j, 1); //23456789
$st = substr_replace($st, chr(mt_rand(97, 122)), $j + 1, 1); //abc
}
break;
}
//************** begin search in $st simbol 'o, l, i, j, t, f' ***************************
$st_validator = "olijtf";
for ($j = 0; $j < 6; $j++) {
for ($i = 0; $i < strlen($st_validator); $i++) {
if ($st[$j] == $st_validator[$i]) {
$st[$j] = chr(mt_rand(117, 122)); //uvwxyz
}
}
}
//************** end search in $st simbol 'o, l, i, j, t, f' *****************************
$session = JFactory::getSession();
$session->set('captcha_keystring', $st);
if (isset($_REQUEST['error']) && $_REQUEST['error'] != "")
echo "<font style='color:red'>" . $_REQUEST['error'] . "</font><br />";
$name_user = "";
if (isset($_REQUEST['name_user']))
$name_user = $_REQUEST['name_user'];
if (isset($_REQUEST["err_msg"]))
echo "<script> alert('Error: " . $_REQUEST["err_msg"] . "'); </script>\n";
echo "<br /><img src='" . JRoute::_( "index.php?option=com_realestatemanager&task=secret_image")."'
alt='CAPTCHA_picture'/><br/>";
?>
<!--********************** end insert image *******************************-->
</div>
<div class="row_05"><?php echo _REALESTATE_MANAGER_LABEL_REVIEW_KEYGUEST; ?></div>
<div class="row_06">
<input class="inputbox" type="text" name="keyguest" size="6" maxlength="6" />
</div>
<?php
}
}
?>
<!--**************************** end add antispam guest ******************************-->
<?php
if ($params->get('show_rentstatus') && $params->get('show_rentrequest')
&& !$params->get('rent_save') && !$params->get('search_request')) {
?>
<br />
<input type="button" value="<?php echo _REALESTATE_MANAGER_LABEL_BUTTON_RENT_REQU ; ?>"
class="button" onclick="rem_rent_request_submitbutton()" />
<br />
<?php
} else if ($params->get('show_rentstatus') && $params->get('show_rentrequest') && $params->get('rent_save')
&& !$params->get('search_request')) {
?>
<input type="button" class="button" value="<?php echo _REALESTATE_MANAGER_LABEL_BUTTON_RENT_REQU_SAVE; ?>"
onclick="rem_rent_request_submitbutton()" />
<?php } else {
?>
<?php
}
?>
</div>
</form>
<?php
} else
echo "</form>";
} else if ($house->listing_type == 2) {
?>
</form>
<?php
if ($params->get('show_buyrequest') && $params->get('show_buystatus')) {
global $option;
if ($option != 'com_realestatemanager') {
$form_action = "index.php?option=" . $option
. "&task=buying_request&Itemid="
. $Itemid ;
} else
$form_action = "index.php?option=com_realestatemanager&task=buying_request&Itemid=" . $Itemid;
?>
<div id="rem_house_titlebox">
<?php echo _REALESTATE_MANAGER_LABEL_BUTTON_SEND_MESSAGE; ?>
</div>
<div id="show_buying">
<form action="<?php echo sefRelToAbs($form_action); ?>" method="post" name="buying_request">
<div class="table_08">
<?php
global $my;
if ($my->guest) {
?>
<div class="row_01">
<div id="customer_name_warning"></div>
<span class="col_02"><input id="alert_name_buy" class="inputbox" type="text"
name="customer_name" size="38" maxlength="80" placeholder="<?php
echo _REALESTATE_MANAGER_LABEL_RENT_REQUEST_NAME ; ?>*"/></span>
</div>
<div class="row_02">
<div id="customer_email_warning"></div>
<span class="col_02"><input id="alert_mail_buy" class="inputbox" type="text"
name="customer_email" size="38" maxlength="80" placeholder="<?php
echo _REALESTATE_MANAGER_LABEL_RENT_REQUEST_EMAIL; ?>*"/></span>
</div>
<?php
} else {
?>
<div class="row_03">
<div id="customer_name_warning"></div>
<span class="col_02">
<input id="alert_name_buy" class="inputbox" type="text" name="customer_name" size="38"
maxlength="80" placeholder="<?php echo _REALESTATE_MANAGER_LABEL_RENT_REQUEST_NAME; ?>"
value="<?php echo $my->name; ?> " /></span>
</div>
<div class="row_04">
<div id="customer_email_warning"></div>
<span class="col_02">
<input id="alert_mail_buy" class="inputbox" type="text" name="customer_email" size="38"
maxlength="80" placeholder="<?php echo _REALESTATE_MANAGER_LABEL_RENT_REQUEST_EMAIL; ?>"
value="<?php echo $my->email; ?>"/></span>
</div>
<?php
}
?>
<div class="row_05">
<div id="customer_phone_warning"></div>
<span class="col_02">
<input class="inputbox" type="text" id="customer_phone" name="customer_phone"
size="38" maxlength="80" placeholder="<?php echo _REALESTATE_MANAGER_REQUEST_PHONE; ?>" />
</span>
</div>
<div class="row_06">
<textarea name="customer_comment" cols="50" rows="8" placeholder="<?php
echo _REALESTATE_MANAGER_TAB_DESCRIPTION; ?>" ></textarea>
<input type="hidden" name="bid[]" value="<?php echo $house->id; ?>" />
</div>
<!--************************* begin add antispam guest ********************-->
<?php if ($params->get('captcha_option_sendmessage')) {
if ($params->get('captcha_option_sendmessage_registrationlevel') && ($my->id == 0)) {
?>
<div class="row_capcha">
<!--************************* begin insetr image **********************-->
<?php
// begin create kod
$st = " ";
$algoritm = mt_rand(1, 2);
switch ($algoritm) {
case 1:
for ($j = 0; $j < 6; $j+= 2) {
$st = substr_replace($st, chr(mt_rand(97, 122)), $j, 1); //abc
$st = substr_replace($st, chr(mt_rand(50, 57)), $j + 1, 1); //23456789
}
break;
case 2:
for ($j = 0; $j < 6; $j+= 2) {
$st = substr_replace($st, chr(mt_rand(50, 57)), $j, 1); //23456789
$st = substr_replace($st, chr(mt_rand(97, 122)), $j + 1, 1); //abc
}
break;
}
//************** begin search in $st simbol 'o, l, i, j, t, f' ***************************
$st_validator = "olijtf";
for ($j = 0; $j < 6; $j++) {
for ($i = 0; $i < strlen($st_validator); $i++) {
if ($st[$j] == $st_validator[$i]) {
$st[$j] = chr(mt_rand(117, 122)); //uvwxyz
}
}
}
//************** end search in $st simbol 'o, l, i, j, t, f' *****************************
$session = JFactory::getSession();
$session->set('captcha_keystring', $st);
if (isset($_REQUEST['error']) && $_REQUEST['error'] != "")
echo "<font style='color:red'>" . $_REQUEST['error'] . "</font><br />";
$name_user = "";
if (isset($_REQUEST['name_user']))
$name_user = $_REQUEST['name_user'];
if (isset($_REQUEST["err_msg"]))
echo "<script> alert('Error: " . $_REQUEST["err_msg"] . "'); </script>\n";
echo "<br /><img src='" . JRoute::_( "index.php?option=com_realestatemanager&task=secret_image")."'
alt='CAPTCHA_picture'/><br/>";
?>
<!--********************** end insert image *******************************-->
</div>
<div class="row_05"><?php echo _REALESTATE_MANAGER_LABEL_REVIEW_KEYGUEST; ?></div>
<div class="row_06">
<input class="inputbox" type="text" name="keyguest" size="6" maxlength="6" />
</div>
<?php
}
}
?>
<!--**************************** end add antispam guest ******************************-->
<div class="row_07">
<span class="col_01">
<input type="button" value="<?php echo _REALESTATE_MANAGER_LABEL_BUTTON_SEND_MESSAGE; ?>"
class="button" onclick="buying_request_submitbutton()"/>
</span>
</div>
</div>
</form>
</div>
<?php
}
} else
echo "</form>";
?>
</div>
<?php } ?>
</div> <!-- end span3-->
</div>
<?php positions_rem($params->get('similaires')); ?>
<div>
<?php
mosHTML::BackButton($params, $hide_js);
?>
</div>
<!-- Modal -->
<a href="#aboutus" class="rem-button-about"></a>
<a href="#rem-modal-css" class="rem-overlay" id="rem-aboutus" style="display: none;"></a>
<div class="rem-popup">
<div class="rem-modal-text">
Please past text to modal
</div>
<a class="rem-close" title="Close" href="#rem-close"></a>
</div><file_sep><?php
if (!defined('_VALID_MOS') && !defined('_JEXEC'))
die('Direct Access to ' . basename(__FILE__) . ' is not allowed.');
/**
*
* @package RealEstateManager
* @copyright 2012 <NAME>-OrdaSoft(<EMAIL>); <NAME>(<EMAIL>)
* Homepage: http://www.ordasoft.com
* @version: 3.9 Pro
*
* */
jimport( 'joomla.plugin.helper' );
if (version_compare(JVERSION, "3.0.0", "lt"))
jimport('joomla.html.toolbar');
JHTML::_('behavior.modal');
require_once($mosConfig_absolute_path . "/components/com_realestatemanager/functions.php");
require_once($mosConfig_absolute_path . "/components/com_realestatemanager/realestatemanager.php");
//require_once($mosConfig_absolute_path."/administrator/components/com_realestatemanager/menubar_ext.php");
$GLOBALS['mosConfig_live_site'] = $mosConfig_live_site = JURI::root();
$GLOBALS['mosConfig_absolute_path'] = $mosConfig_absolute_path; //for 1.6
$GLOBALS['mainframe'] = $mainframe = JFactory::getApplication();
$templateDir = JPATH_THEMES . DS . JFactory::getApplication()->getTemplate() . DS;
$GLOBALS['templateDir'] = $templateDir;
$GLOBALS['doc'] = $doc = JFactory::getDocument();
$g_item_count = 0;
// add stylesheet
$doc->addStyleSheet('//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css');
$doc->addStyleSheet('//maxcdn.bootstrapcdn.com/bootstrap/2.3.2/css/bootstrap.min.css');
$doc->addStyleSheet($mosConfig_live_site . '/components/com_realestatemanager/includes/animate.css');
//$doc->addScript('//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js');
$doc->addStyleSheet($mosConfig_live_site . '/components/com_realestatemanager/includes/jQuerREL-ui.css');
$doc->addStyleSheet($mosConfig_live_site . '/components/com_realestatemanager/includes/realestatemanager.css');
$doc->addStyleSheet($mosConfig_live_site . '/components/com_realestatemanager/lightbox/css/lightbox.css');
$doc->addStyleSheet($mosConfig_live_site . '/components/com_realestatemanager/TABS/tabcontent.css');
// add js
$doc->addScript($mosConfig_live_site . '/components/com_realestatemanager/includes/functions.js');
if(checkJavaScriptIncludedRE("jQuerREL-1.2.6.js") === false ) {
$doc->addScript(JURI::root(true) . '/components/com_realestatemanager/lightbox/js/jQuerREL-1.2.6.js');
}
$doc->addScriptDeclaration("jQuerREL=jQuerREL.noConflict();");
if(checkJavaScriptIncludedRE("jQuerREL-ui.js") === false ) {
$doc->addScript(JURI::root(true) . '/components/com_realestatemanager/includes/jQuerREL-ui.js');
}
$doc->addScript($mosConfig_live_site . '/components/com_realestatemanager/includes/wishlist.js');
$doc->addScript($mosConfig_live_site . '/components/com_realestatemanager/lightbox/js/lightbox-2.6.min.js');
$doc->addScript($mosConfig_live_site . '/components/com_realestatemanager/includes/jquery.raty.js');
$doc->addScript($mosConfig_live_site . '/components/com_realestatemanager/TABS/tabcontent.js');
class HTML_realestatemanager {
static function editHouse($option, & $row, & $clist, & $rating, & $delete_edoc, $videos,
& $youtube,
& $tracks, & $listing_status_list,
& $property_type_list, & $listing_type_list, & $house_photo,&$house_temp_photos, & $house_photos, & $house_rent_sal,
& $house_feature, & $currency, & $languages, & $extra_list, & $currency_spacial_price, & $associateArray) {
global $realestatemanager_configuration;
global $my, $mosConfig_live_site, $mainframe, $Itemid, $doc;
if($realestatemanager_configuration['special_price']['show']){
$switchTranslateDayNight = _REALESTATE_MANAGER_RENT_SPECIAL_PRICE_PER_DAY;
}else{
$switchTranslateDayNight = _REALESTATE_MANAGER_RENT_SPECIAL_PRICE_PER_NIGHT;
}
$acl = JFactory::getACL();
$allowed_exts_file = explode(",", $realestatemanager_configuration['allowed_exts']);
foreach ($allowed_exts_file as $key => $allowed_ext_file) {
$allowed_exts_file[$key] = strtolower($allowed_ext_file);
}
$allowed_exts = explode(",", $realestatemanager_configuration['allowed_exts_img']);
foreach ($allowed_exts as $key => $allowed_ext) {
$allowed_exts[$key] = strtolower($allowed_ext);
}
?>
<!---------------------------------Start AJAX load track------------------------------>
<script language="javascript" type="text/javascript">
var request = null;
var tid=1;
function createRequest_track() {
if (request != null)
return;
try {
request = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (othermicrosoft) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
request = null;
}
}
}
if (request == null)
alert(" :-( ___ Error creating request object! ");
}
function testInsert_track(id1,upload){
for(var i=1; i< t_counter; i++){
if(upload.id != ('new_upload_track'+i) &&
document.getElementById('new_upload_track'+i).value == upload.value){
return false;
}
}
return true;
}
function refreshRandNumber_track(id1,upload){
id=id1;
if(testInsert_track(id1,upload)){
createRequest_track();
var url = "<?php echo $mosConfig_live_site . "/administrator/index.php?option=$option&task=checkFile&format=raw";
?>&file="+upload.value+"&path=<?php
echo str_replace("\\", "/", $mosConfig_live_site) . '/components/com_realestatemanager/media/track/'?>";
try{
request.onreadystatechange = updateRandNumber_track;
request.open("GET", url,true);
request.send(null);
}catch (e)
{
alert(e);
}
}
else
{
alert("You alredy select this track file");
upload.value="";
}
}
function updateRandNumber_track() {
if (request.readyState == 4) {
document.getElementById("randNumTrack"+tid).innerHTML = request.responseText;
}
}
</script>
<!-------------------------------- END Ajax load track---------------------------------->
<!-------------------------------- START Ajax load video---------------------------------->
<script language="javascript" type="text/javascript">
var request = null;
var vid=1;
function createRequest_video(){
if (request != null)
return;
try {
request = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (othermicrosoft) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
request = null;
}
}
}
if (request == null)
alert(" :-( ___ Error creating request object! ");
}
function testInsertVideo(id1,upload){
for(var i=1 ;i< v_counter; i++){
if(upload.id != ('new_upload_video'+i) &&
document.getElementById('new_upload_video'+i).value == upload.value)
{
return false;
}
}
return true;
}
function refreshRandNumber_video(id1,upload){
id=id1;
if(testInsertVideo(id1,upload)){
createRequest_video();
var url = "<?php echo $mosConfig_live_site . "/administrator/index.php?option=$option&task=checkFile&format=raw";
?>&file="+upload.value+"&path=<?php
echo str_replace("\\", "/", $mosConfig_live_site) . '/components/com_realestatemanager/media/video/' ?>";
try{
request.onreadystatechange = updateRandNumber_video;
request.open("GET",url,true);
request.send(null);
}catch (e)
{
alert(e);
}
}
else
{
alert("You alredy select this video file");
upload.value="";
}
}
function updateRandNumber_video() {
if (request.readyState == 4) {
document.getElementById("randNumVideo"+vid).innerHTML = request.responseText;
}
}
</script>
<!-------------------------------- END Ajax load video---------------------------------->
<script language="javascript" type="text/javascript">
function changeButtomName() {
document.getElementById('v_add').value = "<?php echo _REALESTATE_MANAGER_LABEL_VIDEO_ADD_ALTERNATIVE_VIDEO ?>";
}
var v_counter=0;
function new_videos(){
div = document.getElementById("v_items");
button = document.getElementById("v_add");
v_counter++;
newitem='<div class="vm_video_block">'+
'<span class="rem_col_url">'+
'<strong>' +
"<?php echo _REALESTATE_MANAGER_LABEL_VIDEO_UPLOAD ?>"+v_counter+
': </strong>'+
'</span>'+
'<span>'+
'<input type="file"'+
'onClick="document.save_add.new_upload_video_url'+
v_counter+'" value =""'+
' onChange="refreshRandNumber_video('+v_counter+',this);"'+
' name="new_upload_video'+v_counter+'" id="new_upload_video'+v_counter+
'" value="" size="45">'+
'<span id="randNumVideo'+v_counter+'" style="color:red;"></span>'+
'</span>'+
'</div>'+
'<div><span style="text-align:center">OR</span></div>';
newnode = document.createElement("span");
newnode.innerHTML = newitem;
div.insertBefore(newnode,button);
newitem = '<div>'+
'<span class="rem_col_url">'+
'<strong>'+
"<?php echo _REALESTATE_MANAGER_LABEL_VIDEO_UPLOAD_URL; ?>" +v_counter+
': </strong>'+
'</span>'+
'<span>'+
'<input type="text"'+
' name="new_upload_video_url'+v_counter+'"'+
' id="new_upload_video_url'+v_counter+'" value="" size="45">'+
'</span>'+
'</div>'+
'<div><span>OR</span></div>';
newnode = document.createElement("span");
newnode.innerHTML = newitem;
div.insertBefore(newnode,button);
newitem = '<div>'+
'<span class="rem_col_url">'+
'<strong>'+
"<?php echo _REALESTATE_MANAGER_LABEL_VIDEO_UPLOAD_YOUTUBE_CODE; ?>" +
': </strong>'+
'</span>'+
'<span>'+
'<input type="text"'+
' name="new_upload_video_youtube_code'+v_counter+'"'+
' id="new_upload_video_youtube_code'+v_counter+'" value="" size="45">'+
'</span>'+
'</div>'+
'<?php echo _REALESTATE_MANAGER_LABEL_PRIOTITY; ?>'
newnode=document.createElement("span");
newnode.innerHTML=newitem;
div.insertBefore(newnode,button);
var allowed_files = 5;
if(v_counter + <?php echo count($videos); ?> >= allowed_files) {
button.setAttribute("style","display:none");
}
changeButtomName();
}
var t_counter=0;
function new_tracks(){
div = document.getElementById("t_items");
button = document.getElementById("t_add");
t_counter++;
newitem = '<div class="rem_video_block">'+
'<span class="rem_col_url">'+
'<strong>'+
"<?php echo _REALESTATE_MANAGER_LABEL_TRACK_UPLOAD ?>"+t_counter+
': </strong></span>'+
'<span>'+
'<input type="file"'+
' onClick="document.save_add.new_upload_track'+t_counter+'" value =""'+
' onChange="refreshRandNumber_track('+t_counter+',this);"'+
' name="new_upload_track'+t_counter+'"'+
' id="new_upload_track'+t_counter+'" value="" size="45">'+
'<span id="randNumTrack'+t_counter+'" style="color:red;"></span>'+
'</span>'+
'</div>'+
'<div><span> OR </span></div>';
newnode = document.createElement("span");
newnode.innerHTML = newitem;
div.insertBefore(newnode,button);
newitem = '<div>'+
'<span class="rem_col_url">'+
'<strong>'+
"<?php echo _REALESTATE_MANAGER_LABEL_TRACK_UPLOAD_URL; ?>"+t_counter+
': </strong></span>'+
'<span>'+
'<input type="text"'+
' name="new_upload_track_url'+t_counter+'"'+
' id="new_upload_track_url'+t_counter+'" value="" size="45">'+
'</span>'+
'</div><br/>';
newnode = document.createElement("span");
newnode.innerHTML=newitem;
div.insertBefore(newnode,button);
newitem = '<div>'+
'<span class="rem_col_url">'+
'<strong>'+
"<?php echo _REALESTATE_MANAGER_LABEL_TRACK_UPLOAD_KIND; ?>"+t_counter+
':</strong>'+
'</span>'+
'<span>'+
'<input type="text"'+
' name="new_upload_track_kind'+t_counter+'"'+
' id="new_upload_track_kind'+t_counter+'" value="" size="45">'+
'</span>'+
'</div><br/>';
newnode = document.createElement("span");
newnode.innerHTML=newitem;
div.insertBefore(newnode,button);
newitem = '<div>'+
'<span class="rem_col_url">'+
'<strong>'+
"<?php echo _REALESTATE_MANAGER_LABEL_TRACK_UPLOAD_SCRLANG; ?>"+t_counter+
':</strong>'+
'</span>'+
'<span>'+
'<input type="text"'+
' name="new_upload_track_scrlang'+t_counter+'"'+
' id="new_upload_track_scrlang'+t_counter+'" value="" size="45">'+
'</span>'+
'</div><br/>';
newnode = document.createElement("span");
newnode.innerHTML = newitem;
div.insertBefore(newnode,button);
newitem = '<div>'+
'<span class="rem_col_url">'+
'<strong>'+
"<?php echo _REALESTATE_MANAGER_LABEL_TRACK_UPLOAD_LABEL; ?>"+t_counter+
':</strong>'+
'</span>'+
'<span>'+
'<input type="text"'+
' name="new_upload_track_label'+t_counter+'"'+
' id="new_upload_track_label'+t_counter+'" value="" size="45">'+
'</span>'+
'</div><br/>';
newnode = document.createElement("span");
newnode.innerHTML=newitem;
div.insertBefore(newnode,button);
}
</script>
<script language="javascript" type="text/javascript">
jQuerREL(document).ready(function () {
jQuerREL('input,textarea').focus(function(){
jQuerREL(this).data('placeholder',jQuerREL(this).attr('placeholder'))
jQuerREL(this).attr('placeholder','')
jQuerREL(this).css('color','#a3a3a3');
jQuerREL(this).css('border-color','#ddd');
});
jQuerREL('input,textarea').blur(function(){
jQuerREL(this).attr('placeholder',jQuerREL(this).data('placeholder'));
});
});
</script>
<script language="javascript" type="text/javascript">
var availableExt = Array();
var k=0;
<?php foreach ($allowed_exts as $N_A){ ?>
availableExt[k]= '<?php echo strtolower($N_A); ?>';
k++;
<?php } ?>
var availableExtFile = Array();
var l=0;
<?php foreach ($allowed_exts_file as $N_A_file){ ?>
availableExtFile[l]= '<?php echo strtolower($N_A_file); ?>';
l++;
<?php } ?>
function findPosY(obj) {
var curtop = 0;
if (obj.offsetParent) {
while (1) {
curtop+=obj.offsetTop;
if (!obj.offsetParent) {
break;
}
obj=obj.offsetParent;
}
} else if (obj.y) {
curtop+=obj.y;
}
return curtop-20;
}
function trim(string){
return string.replace(/(^\s+)|(\s+$)/g, "");
}
function isValidNumber(str){
myregexp = new RegExp("^[0-9]*$");
mymatch = myregexp.exec(str);
if(str == "")
return true;
if(mymatch != null)
return true;
return false;
}
function isValidPrice(str){
myregexp = new RegExp("^[0-9]*\.{0,1}[0-9]*$");
mymatch = myregexp.exec(str);
if(str == "")
return true;
if(mymatch != null)
return true;
return false;
}
function submitbutton(pressbutton) {
var form = document.save_add;
if (pressbutton == 'submit2') {
var fileUrl = form.image_link.value,
parts, ext = ( parts = fileUrl.split("/").pop().split(".") ).length > 1 ? parts.pop().toLowerCase() : "";
if(form.edoc_file != undefined){
var fileUrl2 = form.edoc_file.value,
parts2, ext2 = ( parts2 = fileUrl2.split("/").pop().split(".") ).length > 1 ? parts2.pop().toLowerCase() : "";
}
var post_max_size = <?php echo return_bytes(ini_get('post_max_size')) ?>;
var upl_max_fsize = <?php echo return_bytes(ini_get('upload_max_filesize')) ?>;
var file_upl = <?php echo ini_get('file_uploads') ?>;
var total_file_size = 0;
if (trim(form.houseid.value) == '') {
window.scrollTo(0,findPosY(document.getElementById('houseid_label')));
document.getElementById('houseid').placeholder =
"<?php echo _REALESTATE_MANAGER_ADMIN_INFOTEXT_JS_EDIT_HOUSEID_CHECK; ?>";
document.getElementById('houseid').style.borderColor = "#FF0000";
document.getElementById('houseid').style.color = "#FF0000";
return;
} else if (form.catid.value == ''){
window.scrollTo(0,findPosY(document.getElementById('category_label')));
document.getElementById('alert_category').innerHTML =
"<?php echo _REALESTATE_MANAGER_ADMIN_INFOTEXT_JS_EDIT_CATEGORY; ?>";
document.getElementById('alert_category').style.color = "#FF0000";
return;
} else if (form.htitle.value == ''){
window.scrollTo(0,findPosY(document.getElementById('title_label')));
document.getElementById('alert_title').placeholder =
"<?php echo _REALESTATE_MANAGER_ADMIN_INFOTEXT_JS_EDIT_TITLE; ?>";
document.getElementById('alert_title').style.borderColor = "#FF0000";
document.getElementById('alert_title').style.color = "#FF0000";
return;
} else if (form.hlocation.value == ''){
window.scrollTo(0,findPosY(document.getElementById('hlocation')));
document.getElementById('hlocation').placeholder =
"<?php echo _REALESTATE_MANAGER_ADMIN_INFOTEXT_JS_EDIT_ADDRESS; ?>";
document.getElementById('hlocation').style.borderColor = "#FF0000";
document.getElementById('hlocation').style.color = "#FF0000";
return;
} else if (<?php echo(count($house_photo));?> < 2 && form.image_link.value == ''){
window.scrollTo(0,findPosY(document.getElementById('image_link_alert')));
document.getElementById('image_link_alert').innerHTML =
"<?php echo _REALESTATE_MANAGER_LABEL_PICTURE_URL_UPLOAD; ?>";
document.getElementById('image_link_alert').style.color = "#FF0000";
return;
} else if (form.image_link.value != '' && (jQuerREL.inArray(ext, availableExt) == -1)){
window.scrollTo(0,findPosY(document.getElementById('image_link_alert')));
document.getElementById('image_link_alert').innerHTML =
"<?php echo _REALESTATE_MANAGER_LABEL_PICTURE_FILE_NOT_ALLOWED; ?>";
document.getElementById('image_link_alert').style.color = "#FF0000";
return;
} else if (form.edoc_file != undefined && (form.edoc_file.value != '' && jQuerREL.inArray(ext2, availableExtFile) == -1)){
window.scrollTo(0,findPosY(document.getElementById('rooms_alert')));
document.getElementById('alert_edoc').innerHTML =
"<?php echo _REALESTATE_MANAGER_LABEL_PICTURE_FILE_NOT_ALLOWED; ?>";
document.getElementById('alert_edoc').style.color = "#FF0000";
return;
} else if (form.price.value == '' || form.price.value == 0 || !isValidPrice(form.price.value)){
window.scrollTo(0,findPosY(document.getElementById('price_alert')));
document.getElementById('price_alert_warning').innerHTML =
"<?php echo _REALESTATE_MANAGER_ADMIN_INFOTEXT_JS_EDIT_PRICE; ?>";
document.getElementById('price_alert_warning').style.color = "red";
document.getElementById('price').style.borderColor = "#FF0000";
document.getElementById('price').style.color = "#FF0000";
return;
} else if (form.house_size.value == '' || !isValidNumber(form.house_size.value)){
window.scrollTo(0,findPosY(document.getElementById('rooms_alert')));
document.getElementById('house_size_alert').innerHTML =
"<?php echo _REALESTATE_MANAGER_INFOTEXT_JS_BUILD_HOUSE_SIZE; ?>";
document.getElementById('house_size_alert').style.color = "red";
document.getElementById('house_size').style.borderColor = "#FF0000";
document.getElementById('house_size').style.color = "#FF0000";
return;
} else if (form.rooms.value == '' || !isValidNumber(form.rooms.value)){
window.scrollTo(0,findPosY(document.getElementById('rooms_alert')));
document.getElementById('rooms_alert').innerHTML =
"<?php echo _REALESTATE_MANAGER_INFOTEXT_JS_ROOMS; ?>";
document.getElementById('rooms_alert').style.color = "red";
document.getElementById('rooms').style.borderColor = "#FF0000";
document.getElementById('rooms').style.color = "#FF0000";
return;
} else if (form.bedrooms.value == '' || !isValidNumber(form.bedrooms.value)){
window.scrollTo(0,findPosY(document.getElementById('rooms_alert')));
document.getElementById('bedrooms_alert').innerHTML =
"<?php echo _REALESTATE_MANAGER_INFOTEXT_JS_BEDROOMS; ?>";
document.getElementById('bedrooms_alert').style.color = "red";
document.getElementById('bedrooms').style.borderColor = "#FF0000";
document.getElementById('bedrooms').style.color = "#FF0000";
return;
} else if (form.year.value == ''){
window.scrollTo(0,findPosY(document.getElementById('rooms_alert')));
document.getElementById('alert_year').innerHTML =
"<?php echo _REALESTATE_MANAGER_INFOTEXT_JS_BUILD_YEAR; ?>";
document.getElementById('alert_year').style.color = "red";
document.getElementById('alert_year').style.color = "#FF0000";
return;
} else if (document.getElementById('owneremail').value == ''){
window.scrollTo(0,findPosY(document.getElementById('owneremail_alert')));
document.getElementById('owneremail_alert').innerHTML =
"<?php echo _REALESTATE_MANAGER_INFOTEXT_JS_RENT_REQ_EMAIL; ?>";
document.getElementById('owneremail_alert').style.color = "red";
document.getElementById('owneremail').style.borderColor = "#FF0000";
document.getElementById('owneremail').style.color = "#FF0000";
return;
} else if (!isValidNumber(form.bathrooms.value)){
window.scrollTo(0,findPosY(document.getElementById('rooms_alert')));
document.getElementById('bathrooms_alert').innerHTML =
"<?php echo _REALESTATE_MANAGER_INFOTEXT_JS_INVALID_NUMBER; ?>";
document.getElementById('bathrooms_alert').style.color = "red";
document.getElementById('bathrooms').style.color = "#FF0000";
return;
} else if (!isValidNumber(form.lot_size.value)){
window.scrollTo(0,findPosY(document.getElementById('hzipcode')));
document.getElementById('lot_size_alert').innerHTML =
"<?php echo _REALESTATE_MANAGER_INFOTEXT_JS_INVALID_NUMBER; ?>";
document.getElementById('lot_size_alert').style.color = "red";
document.getElementById('lot_size').style.color = "#FF0000";
return;
} else if (!isValidNumber(form.garages.value)){
window.scrollTo(0,findPosY(document.getElementById('rooms_alert')));
document.getElementById('garages_alert').innerHTML =
"<?php echo _REALESTATE_MANAGER_INFOTEXT_JS_INVALID_NUMBER; ?>";
document.getElementById('garages_alert').style.color = "red";
document.getElementById('garages').style.color = "#FF0000";
return;
}else if(form.new_upload_track_url1){
for (i = 1;document.getElementById('new_upload_track_url'+i); i++) {
if(document.getElementById('new_upload_track'+i).value != ''
|| document.getElementById('new_upload_track_url'+i).value != ''){
if(document.getElementById('new_upload_track_kind'+i).value == ''){
window.scrollTo(0,findPosY(document.getElementById('new_upload_track_kind'+i))-100);
document.getElementById('new_upload_track_kind'+i).placeholder = "<?php
echo _REALESTATE_MANAGER_ADMIN_INFOTEXT_JS_TRACK_KIND; ?>";
document.getElementById('new_upload_track_kind'+i).style.borderColor = "#FF0000";
document.getElementById('new_upload_track_kind'+i).style.color = "#FF0000";
return;
}else if(document.getElementById('new_upload_track_scrlang'+i).value == ''){
window.scrollTo(0,findPosY(document.getElementById('new_upload_track_scrlang'+i))-100);
document.getElementById('new_upload_track_scrlang'+i).placeholder = "<?php
echo _REALESTATE_MANAGER_ADMIN_INFOTEXT_JS_TRACK_LANGUAGE; ?>";
document.getElementById('new_upload_track_scrlang'+i).style.borderColor = "#FF0000";
document.getElementById('new_upload_track_scrlang'+i).style.color = "#FF0000";
return;
}else if(document.getElementById('new_upload_track_label'+i).value == ''){
window.scrollTo(0,findPosY(document.getElementById('new_upload_track_label'+i))-100);
document.getElementById('new_upload_track_label'+i).placeholder = "<?php
echo _REALESTATE_MANAGER_ADMIN_INFOTEXT_JS_TRACK_TITLE; ?>";
document.getElementById('new_upload_track_label'+i).style.borderColor = "#FF0000";
document.getElementById('new_upload_track_label'+i).style.color = "#FF0000";
return;
}
}
}
}
for (i = 1;document.getElementById('new_upload_video'+i); i++){
if(document.getElementById('new_upload_video'+i).files.length){
if(document.getElementById('new_upload_video'+i).value != ''){
total_file_size += document.getElementById('new_upload_video'+i).files[0].size;
if(!file_upl){
window.scrollTo(0,findPosY(document.getElementById('new_upload_video'+i))-100);
document.getElementById('error_video').innerHTML = "<?php
echo _REALESTATE_MANAGER_SETTINGS_VIDEO_ERROR_UPLOAD_OFF; ?>";
document.getElementById('new_upload_video'+i).style.borderColor = "#FF0000";
document.getElementById('new_upload_video'+i).style.color = "#FF0000";
document.getElementById('error_video').style.color = "#FF0000";
return;
}
if(document.getElementById('new_upload_video'+i).files[0].size >= post_max_size){
window.scrollTo(0,findPosY(document.getElementById('new_upload_video'+i))-100);
document.getElementById('error_video').innerHTML = "<?php
echo _REALESTATE_MANAGER_SETTINGS_VIDEO_ERROR_POST_MAX_SIZE; ?>";
document.getElementById('new_upload_video'+i).style.borderColor = "#FF0000";
document.getElementById('new_upload_video'+i).style.color = "#FF0000";
document.getElementById('error_video').style.color = "#FF0000";
return;
}
if(document.getElementById('new_upload_video'+i).files[0].size >= upl_max_fsize){
window.scrollTo(0,findPosY(document.getElementById('new_upload_video'+i))-100);
document.getElementById('error_video').innerHTML = "<?php
echo _REALESTATE_MANAGER_SETTINGS_VIDEO_ERROR_UPLOAD_MAX_SIZE; ?>";
document.getElementById('new_upload_video'+i).style.borderColor = "#FF0000";
document.getElementById('new_upload_video'+i).style.color = "#FF0000";
document.getElementById('error_video').style.color = "#FF0000";
return;
}
}
}
}
if(total_file_size >= post_max_size){
if(document.getElementById('error_video')){
window.scrollTo(0,findPosY(document.getElementById('error_video'))-100);
document.getElementById('error_video').innerHTML = "<?php
echo JText::_('_REALESTATE_MANAGER_SETTINGS_VIDEO_ERROR_POST_MAX_SIZE'); ?>";
document.getElementById('error_video').style.borderColor = "#FF0000";
document.getElementById('error_video').style.color = "#FF0000";
document.getElementById('error_video').style.color = "#FF0000";
return;
}
}
}
form.submit();
}
</script>
<?php
if ($option != 'com_realestatemanager') {
$form_action = "index.php?option=" . $option .
"&task=save_add&is_show_data=1&Itemid=" . $Itemid ;
}
else
$form_action = "index.php?option=" . $option . "&task=save_add&Itemid=" . $Itemid;
?>
<form action="<?php echo sefRelToAbs($form_action); ?>" method="post" name="save_add"
id="save_add" enctype="multipart/form-data">
<div class="admin_table_47">
<div class="row_add_house" >
<?php if (!isset($my->email)) : ?>
<div class="alert alert-error" >
<button type="button" class="close" data-dismiss="alert">×</button>
<?php echo _REALESTATE_MANAGER_WARNING_NO_LOGIN; ?>
</div>
<?php else: ?>
<input type="hidden" name="owneremail" value="<?php echo $my->email; ?>"/>
<?php endif; ?>
<input type="hidden" name="id" value="<?php echo $row->id; ?>"/>
</div>
<div class="row-fluid">
<div class="span12">
<div class="rem_house_contacts">
<div id="rem_house_titlebox">
<?php echo _REALESTATE_MANAGER_LABEL_OVERVIEW; ?>
</div>
<div class="row_add_house" id="title_label" >
<span><?php echo _REALESTATE_MANAGER_LABEL_TITLE; ?>:*</span>
<input id="alert_title" class="inputbox" type="text"
name="htitle" size="60" value="<?php echo $row->htitle; ?>" />
</div>
<div class="row_add_house" id="category_label" >
<div id="alert_category"></div>
<span><?php echo _REALESTATE_MANAGER_LABEL_CATEGORY; ?>:*</span>
<span><?php echo $clist; ?></span>
</div>
<div class="row_add_house">
<span><?php echo _REALESTATE_MANAGER_LABEL_COMMENT; ?>:</span>
<div class="editor_area"><?php editorArea('editor1', $row->description,
'description', 300, 50, '70', '10', false); ?></div>
<!--<textarea name="description" cols="50" rows="8" ><?php //echo $row->description; ?></textarea>-->
</div>
<div class="row_add_house" id='houseid_label' >
<span><?php echo _REALESTATE_MANAGER_LABEL_PROPERTYID; ?>:*</span>
<input class="inputbox" type="text" id="houseid" name="houseid"
size="20" maxlength="20" value="<?php echo $row->houseid; ?>" />
<input type="hidden" name="idtrue" id="idtrue" value="<?php echo $row->id_true; ?>"/>
</div>
</div>
</div>
</div>
<div class="row-fluid">
<div class="span12">
<div class="rem_house_contacts">
<div id="rem_house_titlebox">
<?php echo _REALESTATE_MANAGER_LABEL_PHOTOS; ?>
</div>
<div class="row_add_house">
<div id="image_link_alert"></div>
<span><?php echo _REALESTATE_MANAGER_LABEL_PICTURE_URL_UPLOAD; ?>:*</span>
<input class="inputbox" type="file" name="image_link"
value="<?php echo $row->image_link; ?>" size="25" maxlength="250" />
</div>
<div class="row_add_house">
<?php if ($house_photo != '') { ?>
<span><?php echo _REALESTATE_MANAGER_LABEL_SELECT_PHOTO_TO_REMOVE; ?>:</span>
<div style="display:inline-block; margin-left:10px;">
<img alt="photo" src="<?php echo $mosConfig_live_site .
"/components/com_realestatemanager/photos/" . $house_photo[1]; ?>"/>
<div style="text-align:center">
<input type="checkbox" name="del_main_photo"
value="<?php echo $house_photo[0]; ?>" />
</div>
</div>
<?php } else echo '<span></span>'; ?>
</div>
<!--/////////////////////////////////////////////////upload other foto -->
<div class="row_add_house">
<?php
count($house_photos);
$user_group = userGID_REM($my->id);
$user_group_mas = explode(',', $user_group);
$max_count_foto = 0;
foreach ($user_group_mas as $value) {
$count_foto_for_single_group =
$realestatemanager_configuration['user_manager_rem'][$value]['count_foto'];
if($count_foto_for_single_group>$max_count_foto){
$max_count_foto = $count_foto_for_single_group;
}
}
$count_foto_for_single_group = $max_count_foto;
?>
<span> <?php echo _REALESTATE_MANAGER_LABEL_OTHER_PICTURES_URL_UPLOAD; ?>:</span>
<script language="javascript" type="text/javascript">
var photos=0;
function new_photos_rem(){
div= document.getElementById("items");
photos++;
var allowed_files = <?php echo $count_foto_for_single_group;?>;
if (<?php echo count($house_photos); ?> < allowed_files) {
newitem="<input type=\"file\" multiple='true' name=\"new_photo_file[]";
newitem+="\" value=\"\"size=\"45\"><br>";
newnode= document.createElement("span");
newnode.innerHTML=newitem;
div.appendChild(newnode);
}else{
newitem="<p> <?php echo _REALESTATE_MANAGER_MAX_PHOTOS_LIMIT; ?>: "+
<?php echo $count_foto_for_single_group;?> + " </p>";
newnode= document.createElement("span");
newnode.innerHTML=newitem;
div.appendChild(newnode);
}
}
</script>
<div ID="items">
<script> new_photos_rem();</script>
</div>
</div>
<!--/////////////////////////////////////////////////end to upload photos gallery -->
<?php if (count($house_photos) != 0) { ?>
<div class="row_add_house">
<span><?php echo _REALESTATE_MANAGER_LABEL_SELECT_PHOTO_FROM_GALLERY; ?>:</span>
<div id="rem_img_sortable" style="display:inline-block">
<?php
for ($i = 0; $i < count($house_photos); $i++) {
?>
<div id="<?php echo $house_temp_photos[$i]->main_img;?>" style="display:inline-block; margin-bottom:10px;">
<img src="<?php echo $mosConfig_live_site .
"/components/com_realestatemanager/photos/" .
$house_photos[$i][1]; ?>" alt="no such file"/>
<div style="text-align:center"><input type="checkbox"
name="del_photos[]" value="<?php echo $house_photos[$i][0]; ?>" /></div>
</div>
<?php } ?>
</div>
<input id="rem_img_ordering" type="hidden" name="rem_img_ordering" value="">
<script type="text/javascript">
jQuerREL( "#rem_img_sortable" ).sortable({
scroll: false,
'update': function (event, ui) {
var order = jQuerREL(this).sortable('toArray');
jQuerREL( "#rem_img_ordering" ).val(order);
}
});
</script>
</div>
<?php } ?>
</div>
</div>
</div>
<div class="row-fluid">
<div class="span12">
<div class="rem_house_contacts">
<div id="rem_house_titlebox">
<?php echo _REALESTATE_MANAGER_LABEL_PRICING; ?>
</div>
<div class="row_add_house">
<span><?php echo _REALESTATE_MANAGER_LABEL_LISTING_TYPE; ?>:</span>
<span><?php echo $listing_type_list; ?></span>
</div>
<div class="row_add_house">
<span><?php echo _REALESTATE_MANAGER_LABEL_LISTING_STATUS; ?>:</span>
<span><?php echo $listing_status_list; ?></span>
</div>
<div class="row_add_house" id="price_alert">
<div id="price_alert_warning"></div>
<span><?php echo _REALESTATE_MANAGER_LABEL_PRICE; ?>:*</span>
<div style="display:inline-block;">
<input class="inputbox" type="text" id="price" name="price" size="15"
value="<?php echo $row->price; ?>" />
<?php echo $currency; ?>
</div>
</div>
<div class="row_add_house">
<div class="rem_specprice">
<!-- begin sp price -->
<script language="javascript" type="text/javascript">
jQuerREL(document).ready(function() {
jQuerREL( "#price_from, #price_to" ).datepicker(
{
minDate: "+0",
dateFormat: "<?php echo transforDateFromPhpToJquery();?>"
});
});
</script>
<script language="javascript" type="text/javascript">
jQuerREL(document).ready(function() {
jQuerREL(" #subPrice ").bind(" click ", function( event ) {
var rent_from = jQuerREL("#price_from").val();
var rent_to = jQuerREL("#price_to").val();
var special_price = jQuerREL("#special_price").val();
var comment_price = jQuerREL('#comment_price').val();
var currency_spacial_price = "<?php echo $row->priceunit; ?>";
var id = <?php echo (0 + $row->id);?> ;
if(id && id > 0){
jQuerREL.ajax({
type: "POST",
url: "index.php?option=com_realestatemanager&task=ajax_rent_price&bid="+id+
"&rent_from="+rent_from+"&rent_until="+rent_to+
"&special_price="+special_price+"&comment_price="+comment_price+
"¤cy_spacial_price="+currency_spacial_price,
data: { " #do " : " #1 " },
update: jQuerREL(" #SpecialPriseBlock "),
success: function( data ) {
jQuerREL("#SpecialPriseBlock").html(data);
}
});
} else{
alert("<?php echo _REALESTATE_MANAGER_TO_ADD_SPRICE_YOU_NEED; ?>");
}
});
});
</script>
<div class="accordion" id="accordion2">
<div class="accordion-group">
<div class="accordion-heading" id="rem_house_titlebox">
<a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href="#collapseTwo">
<?php echo _REALESTATE_MANAGER_RENT_ADD_SPECIAL_PRICE; ?>
</a>
</div>
<div id="collapseTwo" class="accordion-body collapse">
<div class="accordion-inner">
<div class="price_col">
<div>
<div style="display:inline-block">
<div><?php echo _REALESTATE_MANAGER_LABEL_RENT_REQUEST_FROM; ?></div>
<p><input type="text" id="price_from" name="price_from"></p>
</div>
<div style="display:inline-block">
<div><?php echo _REALESTATE_MANAGER_LABEL_RENT_REQUEST_UNTIL; ?></div>
<p><input type="text" id="price_to" name="price_to"></p>
</div>
</div>
<div style="display:inline-block">
<div><?php echo _REALESTATE_MANAGER_LABEL_PRICE; ?></div>
<input id="special_price" class="inputbox price" type="text"
name="special_price" size="15" value="" />
</div>
<div>
<div><?php echo _REALESTATE_MANAGER_LABEL_REVIEW_COMMENT;?></div>
<textarea id="comment_price" rows="5" cols="25" name="comment_price"></textarea>
</div>
<div>
<input id="subPrice" class="inputbox" type="button" name="new_price"
value="<?php echo _REALESTATE_MANAGER_RENT_ADD_SPECIAL_PRICE; ?>"/>
</div>
</div>
<div id ="message-here" style ='color: red; font-size: 14px;' ></div>
<div id ='SpecialPriseBlock'>
<table class="adminlist adminlist_04" width ="100%" align ='center'>
<tr>
<th class="title" width ="15%" align ='center'><?php
echo $switchTranslateDayNight; ?></th>
<th class="title" align ='center' width ="20%"><?php
echo _REALESTATE_MANAGER_FROM; ?></th>
<th class="title" align ='center' width ="20%"><?php
echo _REALESTATE_MANAGER_TO; ?></th>
<th class="title" align ='center' width ="30%"><?php
echo _REALESTATE_MANAGER_LABEL_REVIEW_COMMENT; ?></th>
<th class="title" align ='center' width ="15%"><?php
echo _REALESTATE_MANAGER_LABEL_CALENDAR_SELECT_DELETE; ?></th>
</tr>
<?php
for ($i = 0; $i < count($house_rent_sal); $i++) {
$DateToFormat = str_replace("D",'d',(str_replace("M",'m',
(str_replace('%','',$realestatemanager_configuration['date_format'])))));
$date_from = new DateTime($house_rent_sal[$i]->price_from);
$date_to = new DateTime($house_rent_sal[$i]->price_to);
?>
<tr celpadding="5">
<?php
if ($realestatemanager_configuration['price_unit_show'] == '1') {
if ($realestatemanager_configuration['sale_separator']['show'] == '1') { ?>
<td align ='center'><?php echo
formatMoney($house_rent_sal[$i]->special_price, true,
$realestatemanager_configuration['price_format']). ' ' ?></td>
<?php } else { ?>
<td align ='center'><?php echo $house_rent_sal[$i]->special_price ?></td>
<?php }
} else {
if ($realestatemanager_configuration['sale_separator']['show'] == '1') { ?>
<td align ='center'><?php echo $house_rent_sal[$i]->priceunit.
' '.formatMoney($house_rent_sal[$i]->special_price, true,
$realestatemanager_configuration['price_format']); ?></td>
<?php } else { ?>
<td align ='center'><?php echo $house_rent_sal[$i]->priceunit ?></td>
<?php }
} ?>
<td align ='center'><?php echo date_format($date_from, "$DateToFormat"); ?></td>
<td align ='center'><?php echo date_format($date_to, "$DateToFormat"); ?></td>
<td align ='center'><?php echo $house_rent_sal[$i]->comment_price; ?></td>
<td align ='center'><input type="checkbox" name="del_rent_sal[]"
value="<?php echo $house_rent_sal[$i]->id; ?>" /></td>
</tr>
<?php } ?>
</table>
</div>
<!--******************************************************-->
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<?php
if(count($house_feature)){?>
<div class="row-fluid">
<div class="span12">
<div class="rem_house_contacts">
<div id="rem_house_titlebox">
<?php echo _REALESTATE_MANAGER_LABEL_AMENITIES; ?>
</div>
<div class="row_house_checkbox row_add_house">
<?php
for ($i = 0; $i < count($house_feature); $i++) {
if ($i != 0) {
if ($house_feature[$i]->categories !== $house_feature[$i - 1]->categories)
echo "<div class='rem_features_category'>" . $house_feature[$i]->categories . "</div>";
} else
echo "<div class='rem_features_category'>" . $house_feature[$i]->categories . "</div>";
?>
<div class="rem_features_name">
<input type="checkbox" <?php if ($house_feature[$i]->check)
echo "checked"; ?> name="feature[]" value="<?php
echo $house_feature[$i]->id; ?>"><?php echo $house_feature[$i]->name; ?>
<?php if ($house_feature[$i]->image_link != '') { ?>
<img alt="photo" src="<?php
echo "$mosConfig_live_site/components/com_realestatemanager/featured_ico/"
. $house_feature[$i]->image_link; ?>"></img>
<?php } ?>
</div>
<?php
} ?>
</div>
</div>
</div>
</div>
<?php
}?>
<div class="rem_house_contacts">
<div id="rem_house_titlebox">
<?php echo _REALESTATE_MANAGER_TAB_LOCATION; ?>
</div>
<div class="row-fluid">
<div class="span5 rem_addlocation">
<div class="row_add_house">
<span><?php echo _REALESTATE_MANAGER_LABEL_COUNTRY; ?>:</span>
<input class="inputbox" type="text" id="hcountry" name="hcountry"
size="30" value="<?php echo $row->hcountry; ?>" />
</div>
<div class="row_add_house">
<span><?php echo _REALESTATE_MANAGER_LABEL_ADDRESS; ?>:*</span>
<input class="inputbox" type="text" id="hlocation" name="hlocation"
size="60" value="<?php echo $row->hlocation; ?>" />
</div>
<div class="row_add_house">
<span><?php echo _REALESTATE_MANAGER_LABEL_CITY; ?>:</span>
<input class="inputbox" type="text" id="hcity" name="hcity" size="30"
value="<?php echo $row->hcity; ?>" />
</div>
<div class="row_add_house">
<span><?php echo _REALESTATE_MANAGER_LABEL_REGION; ?>:</span>
<input class="inputbox" type="text" id="hregion" name="hregion"
size="30" value="<?php echo $row->hregion; ?>" />
</div>
<div class="row_add_house">
<span><?php echo _REALESTATE_MANAGER_LABEL_ZIPCODE; ?>:</span>
<input class="inputbox" type="text" id="hzipcode" name="hzipcode"
size="30" value="<?php echo $row->hzipcode; ?>" />
</div>
<div class="row_add_house" style="display:none">
<input class="inputbox" type="text" id="hlatitude" name="hlatitude"
size="20" value="<?php echo $row->hlatitude; ?>" readonly/>
</div>
<div class="row_add_house" style="display:none">
<input class="inputbox" type="text" id="hlongitude" name="hlongitude"
size="20" value="<?php echo $row->hlongitude; ?>" readonly/>
<input type="hidden" id="map_zoom" name="map_zoom" value="<?php echo $row->map_zoom; ?>" />
</div>
<div class="row_add_house">
<span style="visibility:hidden"><?php echo _REALESTATE_MANAGER_LABEL_GEOCOOR; ?></span>
<input type="button" id="button_show_address" value="<?php
echo _REALESTATE_MANAGER_BUTTON_SHOW_ADDRESS; ?>" onclick="codeAddress()">
</div>
</div>
<div class="span7">
<div class="rem_addlocation_map">
<div id="map_canvas" class="re_map_canvas"></div>
<!--Image google map-->
<?php
$api_key = $realestatemanager_configuration['api_key'] ? "key=" . $realestatemanager_configuration['api_key'] : JFactory::getApplication()->enqueueMessage("<a target='_blank' href='//developers.google.com/maps/documentation/geocoding/get-api-key'>" . _REALESTATE_MANAGER_GOOGLEMAP_API_KEY_LINK_MESSAGE . "</a>", _REALESTATE_MANAGER_GOOGLEMAP_API_KEY_ERROR);
?>
<script src="//maps.googleapis.com/maps/api/js?<?php echo $api_key ?>"
type="text/javascript"></script>
<script type="text/javascript">
setTimeout(function() {
vm_initialize();
},20);
function vm_initialize(){
var map;
var lastmarker = null;
var marker = null;
var mapOptions;
var myOptions = {
zoom: <?php if ($row->map_zoom) echo $row->map_zoom;
else echo 1; ?>,
center: new google.maps.LatLng(<?php
if ($row->hlatitude) echo $row->hlatitude; else echo 0; ?>,<?php
if ($row->hlongitude) echo $row->hlongitude; else echo 0; ?>),
scrollwheel: false,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.LARGE
},
mapTypeId: google.maps.MapTypeId.ROADMAP
};
geocoder = new google.maps.Geocoder();
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var bounds = new google.maps.LatLngBounds ();
<?php if ($row->hlatitude && $row->hlongitude) {
?>
//Set the marker coordinates
var lastmarker = new google.maps.Marker({
position: new google.maps.LatLng(<?php
echo $row->hlatitude; ?>, <?php echo $row->hlongitude; ?>)
});
lastmarker.setMap(map);
<?php } ?>
//If the zoom, then store it in the field map_zoom
google.maps.event.addListener(map,"zoom_changed", function(){
document.getElementById("map_zoom").value=map.getZoom();
});
google.maps.event.addListener(map,"click", function(e){
//Initialize marker
marker = new google.maps.Marker({
position: new google.maps.LatLng(e.latLng.lat(),e.latLng.lng())
});
//Delete marker
if(lastmarker) lastmarker.setMap(null);;
//Add marker to the map
marker.setMap(map);
//Output marker information
document.getElementById("hlatitude").value=e.latLng.lat();
document.getElementById("hlongitude").value=e.latLng.lng();
//Memory marker to delete
lastmarker = marker;
});
}
function updateCoordinates(latlng)
{
if(latlng)
{
document.getElementById('hlatitude').value = latlng.lat();
document.getElementById('hlongitude').value = latlng.lng();
document.getElementById("map_zoom").value=map.getZoom();
}
}
function toggleBounce() {
if (marker.getAnimation() != null) {
marker.setAnimation(null);
} else {
marker.setAnimation(google.maps.Animation.BOUNCE);
}
}
function codeAddress() {
var marker;
myOptions = {
zoom:14,
scrollwheel: false,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.LARGE
},
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var address = document.getElementById('hlocation').value + " " +
document.getElementById('hcountry').value+ " " +
document.getElementById('hregion').value+ " " +
document.getElementById('hcity').value+ " " +
document.getElementById('hzipcode').value + " " +
document.getElementById('hlatitude').value + " " +
document.getElementById('hlongitude').value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
updateCoordinates(results[0].geometry.location);
if (marker) marker.setMap(null);
marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
draggable: true,
animation: google.maps.Animation.DROP
});
google.maps.event.addListener(marker, 'click', toggleBounce);
google.maps.event.addListener(marker, "dragend", function() {
updateCoordinates(marker.getPosition());
});
} else {
vm_initialize();
alert("Please check the accuracy of Address");
}
});
}
</script>
<span><?php echo _REALESTATE_MANAGER_LABEL_CLICKMAP; ?></span>
</div>
</div>
</div>
</div>
<div class="row-fluid">
<div class="span12">
<div class="rem_house_contacts">
<div id="rem_house_titlebox">
<?php echo _CATEGORIES__DETAILS; ?>
</div>
<div class="row_add_house">
<span><?php echo _REALESTATE_MANAGER_LABEL_PROPERTY_TYPE; ?>:</span>
<span><?php echo $property_type_list; ?></span>
</div>
<div class="row_add_house" id="rooms_alert">
<div id="lot_size_alert"></div>
<span><?php echo _REALESTATE_MANAGER_LABEL_LOT_SIZE; ?>, <?php
echo _REALESTATE_MANAGER_LABEL_SIZE_SUFFIX_AR; ?>:</span>
<input class="inputbox" type="text" id="lot_size" name="lot_size"
size="30" value="<?php echo $row->lot_size; ?>" />
</div>
<div class="row_add_house">
<div id="house_size_alert"></div>
<span><?php echo _REALESTATE_MANAGER_LABEL_HOUSE_SIZE; ?>, <?php
echo _REALESTATE_MANAGER_LABEL_SIZE_SUFFIX; ?>:*</span>
<input class="inputbox" type="text" id="house_size" name="house_size"
size="30" value="<?php echo $row->house_size; ?>" />
</div>
<div class="row_add_house">
<div id="rooms_alert"></div>
<span><?php echo _REALESTATE_MANAGER_LABEL_ROOMS; ?>:*</span>
<input class="inputbox" type="text" id="rooms" name="rooms"
size="10" value="<?php echo $row->rooms; ?>" />
</div>
<div class="row_add_house">
<div id="bathrooms_alert"></div>
<span><?php echo _REALESTATE_MANAGER_LABEL_BATHROOMS; ?>:</span>
<input class="inputbox" type="text" id="bathrooms" name="bathrooms"
size="10" value="<?php echo $row->bathrooms; ?>" />
</div>
<div class="row_add_house">
<div id="bedrooms_alert"></div>
<span><?php echo _REALESTATE_MANAGER_LABEL_BEDROOMS; ?>:*</span>
<input class="inputbox" type="text" id="bedrooms" name="bedrooms"
size="10" value="<?php echo $row->bedrooms; ?>" />
</div>
<div class="row_add_house">
<div id="garages_alert"></div>
<span><?php echo _REALESTATE_MANAGER_LABEL_GARAGES; ?>:</span>
<input class="inputbox" type="text" id="garages" name="garages"
size="30" value="<?php echo $row->garages; ?>" />
</div>
<div class="row_add_house">
<div id="alert_year"></div>
<span><?php echo _REALESTATE_MANAGER_LABEL_BUILD_YEAR; ?>:*</span>
<span>
<select name="year" id="year" class="inputbox" size="1">
<?php
print_r("<option value=''>");
print_r(_REALESTATE_MANAGER_OPTION_SELECT);
print_r("</option>");
$num = 1900;
for ($i = 0; $num <= date('Y'); $i++) {
print_r("<option value=\"");
print_r($num);
print_r("\"");
if ($num == $row->year) {
print(" selected= \"true\" ");
}
print_r(">");
print_r($num);
print_r("</option>");
$num++;
}
?>
</select>
</span>
</div>
<?php if ($realestatemanager_configuration['edocs']['allow']) { ?>
<div class="row_add_house">
<div id="alert_edoc"></div>
<span><?php echo _REALESTATE_MANAGER_LABEL_EDOCUMENT_UPLOAD; ?>:</span>
<input class="inputbox" type="file" name="edoc_file" value=""
size="25" maxlength="250" onClick="document.save_add.edok_link.value ='';"/>
</div>
<div class="row_add_house">
<span><?php echo _REALESTATE_MANAGER_LABEL_EDOCUMENT_UPLOAD_URL; ?>:</span>
<input class="inputbox" type="text" name="edok_link" value="<?php
echo $row->edok_link; ?>" size="50" maxlength="250"/>
</div>
<?php } if (strlen($row->edok_link) > 0) { ?>
<div class="row_add_house">
<span><?php echo _REALESTATE_MANAGER_LABEL_EDOCUMENT_DELETE; ?>:</span>
<span><?php echo $delete_edoc; ?></span>
</div>
<?php } ?>
<div>
<span id="error_video"></span>
</div>
<table>
<?php
///////////////////////////////START add video and track\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
if($realestatemanager_configuration['videos_tracks']['show']) {
$out='';
if (count($videos) > 0 && empty($youtube->code)) {
$out .= '<div>'.
'<span></span>'.
'</div>'.
'<div>'.
'<span>'._REALESTATE_MANAGER_LABEL_VIDEO.':</span>'.
'</div>';
for ($i = 0;$i < count($videos);$i++) {
$out .='<div>' .
'<span>'._REALESTATE_MANAGER_LABEL_VIDEO_ATTRIBUTE.($i+1).':</span>'.
'<span>';
if(isset($videos[$i]->src) && substr($videos[$i]->src, 0, 4) != "http"
&& empty($videos[$i]->youtube)){
$out .='<input type="text" name="video'.$i.'"'.
' id="video'.$i.'"' .
' size="60"'.
' value="'.$mosConfig_live_site . $videos[$i]->src.'"'.
' readonly="readonly" />';
}else{
$out .='<input type="text" name="video_url'.$i.'"'.
' id="video_url'.$i.'"'.
' size="60" value="'. $videos[$i]->src . '"'.
' readonly="readonly" />';
}
$out .='</span>'.
'</div>'.
'<div>'.
'<span>'._REALESTATE_MANAGER_LABEL_VIDEO_DELETE . ':</span>'.
'<span>';
if(isset($videos[$i]->id))
$out .= '<input type="checkbox" name="video_option_del'. $videos[$i]->id .'"'.
'value="' . $videos[$i]->id .'">'.
'</span>'.
'</div>';
}
} else if (!empty($youtube->code)) {
$out .= '<div>'.
'<span align="right">'._REALESTATE_MANAGER_LABEL_VIDEO_ATTRIBUTE.':</span>'.
'<span>'.
'<input type="text"'.
' name="youtube_code'.$youtube->id.'"'.
' id="youtube_code'.$youtube->id.'"'.
' size="60" value="' . $youtube->code .'" />'.
'</span>'.
'</div>'.
'<div>'.
'<span align="right">'._REALESTATE_MANAGER_LABEL_VIDEO_DELETE . ':</span>'.
'<span>'.
'<input type="checkbox"'.
' name="youtube_option_del'.$youtube->id.'"'.
' value="'.$youtube->id.'">'.
'</span>'.
'</div>';
}
$out .= '<div class="row_add_house">';
if(empty($youtube->code) && count($videos) < 5){
if(count($videos) > 0)
$out .= '<span></span>';
else
$out .= '<span>'._REALESTATE_MANAGER_LABEL_VIDEO.':</span>';
$out .= '<div id="v_items">'.
' <input id="v_add" type="button"'.
' name="new_video"'.
' value="'._REALESTATE_MANAGER_LABEL_ADD_NEW_VIDEO_FILE.'"'.
' onClick="new_videos()"/>'.
'</div>'.
'</div>';
}
if (count($tracks) > 0) {
$out .= '<div>'.
'<span></span>'.
'</div>'.
'<div>'.
'<span valign="top" align="left">'. _REALESTATE_MANAGER_LABEL_TRACK .':</span>'.
'</div>';
for ($i = 0;$i < count($tracks);$i++) {
$out .='<div>'.
'<span align="right">' . _REALESTATE_MANAGER_LABEL_TRACK_UPLOAD_URL.($i+1).':</span>'.
'<span>';
if (isset($tracks[$i]->src) && substr($tracks[$i]->src, 0, 4) != "http"){
$out .='<input type="text"'.
' class="trackitems"'.
' size="60"'.
' value="'.$mosConfig_live_site.$tracks[$i]->src.'"'.
' readonly="readonly"/>';
}else{
$out .='<input type="text"'.
' class="trackitems"'.
' size="60"'.
' value="'.$tracks[$i]->src.'"'.
' readonly="readonly"/>';
}
if (!empty($tracks[$i]->kind))
$out .= '<input class="trackitems"'.
' type="text"'.
' size="60"'.
' value="'.$tracks[$i]->kind.'"'.
' readonly="readonly"/>';
if (!empty($tracks[$i]->scrlang))
$out .= '<input class="trackitems"'.
' type="text"'.
' size="60"'.
' value="'.$tracks[$i]->scrlang.'"'.
' readonly="readonly"/>';
if (!empty($tracks[$i]->label))
$out .= '<input class="trackitems"'.
' type="text"'.
' size="60"'.
' value="'.$tracks[$i]->label.'"'.
' readonly="readonly"/>';
$out .= '</span>'.
'</div>'.
'<div>'.
'<span align="right">'._REALESTATE_MANAGER_LABEL_TRACK_DELETE.':</span>'.
'<span>';
if(isset($tracks[$i]->id))
$out .= '<input type="checkbox"'.
' name="track_option_del'.$tracks[$i]->id.'"'.
' value="'.$tracks[$i]->id .'">';
}
$out .= '<div class="row_add_house">';
if(count($tracks) > 0)
$out .= '<span></span>';
else
$out .= '<span>'._REALESTATE_MANAGER_LABEL_TRACK.'</span>';
$out .= '<span id="t_items">'.
' <input id="t_add" type="button"'.
' name="new_track"'.
' value="'._REALESTATE_MANAGER_LABEL_ADD_NEW_TRACK.'"'.
' onClick="new_tracks()"/>'.
'</span>'.
'</div>';
}else{
$out .='<div class="row_add_house">'.
'<span>'._REALESTATE_MANAGER_LABEL_TRACK.':</span>'.
'<span id="t_items">'.
'<input id="t_add" type="button" name="new_track"'.
' value="'._REALESTATE_MANAGER_LABEL_ADD_NEW_TRACK.'"'.
' onClick="new_tracks()"/>'.
'</span>'.
'</div>';
}
echo $out;
}
///////////////////////////////END edd video and track\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
?></table>
<!--******************************************************************-->
<?php
if ($realestatemanager_configuration['extra1'] == 0
&& $realestatemanager_configuration['extra2'] == 0
&& $realestatemanager_configuration['extra3'] == 0
&& $realestatemanager_configuration['extra4'] == 0
&& $realestatemanager_configuration['extra5'] == 0
&& $realestatemanager_configuration['extra6'] == 0
&& $realestatemanager_configuration['extra7'] == 0
&& $realestatemanager_configuration['extra8'] == 0
&& $realestatemanager_configuration['extra9'] == 0
&& $realestatemanager_configuration['extra10'] == 0) {
} else {
?>
<?php if ($realestatemanager_configuration['extra1'] == 1) { ?>
<div class="row_add_house">
<span><?php echo _REALESTATE_MANAGER_LABEL_EXTRA1; ?>:</span>
<input class="inputbox" type="text" name="extra1" size="30"
value="<?php echo $row->extra1; ?>" />
</div>
<?php
}
if ($realestatemanager_configuration['extra2'] == 1) {
?>
<div class="row_add_house">
<span><?php echo _REALESTATE_MANAGER_LABEL_EXTRA2; ?>:</span>
<input class="inputbox" type="text" name="extra2" size="30"
value="<?php echo $row->extra2; ?>" />
</div>
<?php
}
if ($realestatemanager_configuration['extra3'] == 1) {
?>
<div class="row_add_house">
<span><?php echo _REALESTATE_MANAGER_LABEL_EXTRA3; ?>:</span>
<input class="inputbox" type="text" name="extra3" size="30"
value="<?php echo $row->extra3; ?>" />
</div>
<?php
}
if ($realestatemanager_configuration['extra4'] == 1) {
?>
<div class="row_add_house">
<span><?php echo _REALESTATE_MANAGER_LABEL_EXTRA4; ?>:</span>
<input class="inputbox" type="text" name="extra4" size="30"
value="<?php echo $row->extra4; ?>" />
</div>
<?php
}
if ($realestatemanager_configuration['extra5'] == 1) {
?>
<div class="row_add_house">
<span><?php echo _REALESTATE_MANAGER_LABEL_EXTRA5; ?>:</span>
<input class="inputbox" type="text" name="extra5" size="30"
value="<?php echo $row->extra5; ?>" />
</div>
<?php
}
if ($realestatemanager_configuration['extra6'] == 1) {
?>
<div class="row_add_house">
<span><?php echo _REALESTATE_MANAGER_LABEL_EXTRA6; ?>:</span>
<span><?php echo $extra_list[0]; ?></span>
</div>
<?php
}
if ($realestatemanager_configuration['extra7'] == 1) {
?>
<div class="row_add_house">
<span><?php echo _REALESTATE_MANAGER_LABEL_EXTRA7; ?>:</span>
<span><?php echo $extra_list[1]; ?></span>
</div>
<?php
}
if ($realestatemanager_configuration['extra8'] == 1) {
?>
<div class="row_add_house">
<span><?php echo _REALESTATE_MANAGER_LABEL_EXTRA8; ?>:</span>
<span><?php echo $extra_list[2]; ?></span>
</div>
<?php
}
if ($realestatemanager_configuration['extra9'] == 1) {
?>
<div class="row_add_house">
<span><?php echo _REALESTATE_MANAGER_LABEL_EXTRA9; ?>:</span>
<span><?php echo $extra_list[3]; ?></span>
</div>
<?php
}
if ($realestatemanager_configuration['extra10'] == 1) {
?>
<div class="row_add_house">
<span><?php echo _REALESTATE_MANAGER_LABEL_EXTRA10; ?>:</span>
<span><?php echo $extra_list[4]; ?></span>
</div>
<?php } ?>
<?php } ?>
<!--**************************************************************-->
</div>
<div class="rem_house_contacts">
<div id="rem_house_titlebox">
<?php echo _REALESTATE_MANAGER_LABEL_AGENT_INFO; ?>
</div>
<div class="row_add_house">
<span><?php echo _REALESTATE_MANAGER_LABEL_AGENT; ?>:</span>
<input class="inputbox" type="text" name="agent" size="30"
value="<?php echo $row->agent; ?>" />
</div>
<div class="row_add_house">
<span><?php echo _REALESTATE_MANAGER_LABEL_CONTACTS; ?>:</span>
<input class="inputbox" type="text" name="contacts" size="40"
value="<?php echo $row->contacts; ?>" />
</div>
<div class="row_add_house">
<span><?php echo _REALESTATE_MANAGER_LABEL_OWNER; ?>:</span>
<span>
<?php if ($my->guest): ?>
<input type="text" name="name" readonly/>
<?php else: ?>
<input type="text" name="name" value="<?php echo $my->name; ?>" readonly/>
<?php endif; ?>
</span>
</div>
<div class="row_add_house" id="owneremail_alert">
<div id="owneremail_alert"></div>
<span><?php echo _REALESTATE_MANAGER_LABEL_RENT_REQUEST_EMAIL; ?>:*</span>
<span>
<?php if (trim($row->owneremail) != ""): ?>
<input type='text' name='owneremail' id="owneremail"
value="<?php echo $row->owneremail; ?>"/>
<?php else: ?>
<input type='text' name='owneremail' id="owneremail"
value="<?php echo $my->email; ?>"/>
<?php endif; ?>
</span>
</div>
</div>
<div class="rem_house_contacts">
<div id="rem_house_titlebox">
<?php echo _REALESTATE_MANAGER_LABEL_LANGUAGE_NAME; ?>
</div>
<div class="row_add_house">
<?php
/******************************************* language ***********************/
if(!empty($associateArray) && !empty($row->language) && $row->language != ''
&& $row->language != '*'){
?>
<div><?php echo _REALESTATE_MANAGER_LANG_ASSOCIATE_HOUSES; ?>:</div>
<?php
$j =1;
foreach ($associateArray as $lang=>$value) {
$displ = '';
if(!$value['list']){
$displ = 'none';
}
?>
<div style="display: <?php echo $displ?>">
<span style="display:inline-block; width:200px;"><?php echo $lang; ?>:</span>
<span><?php echo $value['list']; ?>
<input class="inputbox" id="associate_house" type="text"
name="associate_house<?php echo $j;?>" size="20" readonly="readonly"
maxlength="20" style="width:25px;" value="<?php echo $value['assocId']; ?>" />
<input style="display: none" name="associate_house_lang<?php
echo $j;?>" value="<?php echo $lang ?>"/></span>
</div>
<?php
$j++;
}
}else{
?>
<span><?php echo _REALESTATE_MANAGER_LANG_ASSOCIATE_HOUSES; ?>:</span>
<span><?php echo _REALESTATE_MANAGER_FOR_HOUSES_WITH_LANG; ?></span>
<?php
}
/*********************************************************************************************/
?>
</div>
<div class="row_add_house">
<span class="admin_col_01"><?php echo _REALESTATE_MANAGER_LABEL_LANGUAGE; ?>:</span>
<span class="admin_col_02"><?php echo $languages; ?></span>
</div>
</div>
</div>
</div>
<?php
$month = date("m", mktime(0, 0, 0, date('m'), 1, date('Y')));
$year = date("Y", mktime(0, 0, 0, date('m'), 1, date('Y')));
$placeholder = $realestatemanager_configuration['calendar']['placeholder'];
?>
<script language="javascript" type="text/javascript">
var itW=0;
function new_calen_rent(){
div=document.getElementById("itemsW");
button=document.getElementById("addW");
itW++;
newitem="<strong>" + "<?php echo _REALESTATE_MANAGER_LABEL_CALENDAR_NEW_PRICE; ?>"
+ itW + ": </strong><br />";
newitem+="<select name=\"yearW[]\"><option value=\"2012\" "
+ " <?php if ($year == '2012') echo "selected" ?> "
+ " >2012</option><option value=\"2013\" "
+ " <?php if ($year == '2013') echo "selected" ?> "
+ " >2013</option><option value=\"2014\" "
+ " <?php if ($year == '2014') echo "selected" ?> "
+ " >2014</option><option value=\"2015\" "
+ " <?php if ($year == '2015') echo "selected" ?> "
+ " >2015</option><option value=\"2016\" "
+ " <?php if ($year == '2016') echo "selected" ?> "
+ " >2016</option><option value=\"2017\" "
+ " <?php if ($year == '2017') echo "selected" ?> "
+ " >2017</option></select>";
newitem+="<select name=\"monthW[]\"><option value=\"1\" "
+ " <?php if ($month == '1') echo "selected" ?> "
+ " ><?php echo JText::_('JANUARY'); ?>"
+ "</option><option value=\"2\" "
+ " <?php if ($month == '2') echo "selected" ?> "
+ " ><?php echo JText::_('FEBRUARY'); ?>"
+ "</option><option value=\"3\" "
+ " <?php if ($month == '3') echo "selected" ?> " + " >"
+ "<?php echo JText::_('MARCH'); ?>" + "</option><option value=\"4\" "
+ " <?php if ($month == '4') echo "selected" ?> "
+ " >April</option><option value=\"5\" "
+ " <?php if ($month == '5') echo "selected" ?> " + " >"
+ "<?php echo JText::_('MAY'); ?>"
+ "</option><option value=\"6\" "
+ " <?php if ($month == '6') echo "selected" ?> "
+ " >" + "<?php echo JText::_('JUNE'); ?>"
+ "</option><option value=\"7\" "
+ " <?php if ($month == '7') echo "selected" ?> "
+ " >" + "<?php echo JText::_('JULY'); ?>" + "</option>";
newitem+="<option value=\"8\" " + " <?php if ($month == '8') echo "selected" ?> "
+ " >" + "<?php echo JText::_('AUGUST'); ?>"
+ "</option><option value=\"9\" "
+ " <?php if ($month == '9') echo "selected" ?> "
+ " >" + "<?php echo JText::_('SEPTEMBER'); ?>"
+ "</option><option value=\"10\" "
+ " <?php if ($month == '10') echo "selected" ?> "
+ " >" + "<?php echo JText::_('OCTOBER'); ?>"
+ "</option><option value=\"11\" "
+ " <?php if ($month == '11') echo "selected" ?> "
+ " >" + "<?php echo JText::_('NOVEMBER'); ?>"
+ "</option><option value=\"12\" "
+ " <?php if ($month == '12') echo "selected" ?> "
+ " >" + "<?php echo JText::_('DECEMBER'); ?>"
+ "</option></select><br />";
newitem+="<b>Week</b><br /><textarea rows=\"5\" cols=\"25\" name=\"week[]\">"
+ "<?php echo $placeholder; ?>"
+ "</textarea><br /><b>Weekend</b><br /><textarea rows=\"5\" cols=\"25\" name=\"weekend[]\">"
+ "<?php echo $placeholder; ?>"
+ "</textarea><br /><b>Midweek</b><br /><textarea rows=\"5\" cols=\"25\" name=\"midweek[]\">"
+ "<?php echo $placeholder; ?>" + "</textarea><br /><br /><br />";
newnode=document.createElement("span");
newnode.innerHTML=newitem;
div.insertBefore(newnode,button);
}
</script>
<?php if (checkAccess_REM($realestatemanager_configuration['add_house']['registrationlevel'],
'NORECURSE', userGID_REM($my->id), $acl) ) {
?>
<input type="button" name="submit2" value="<?php echo _REALESTATE_MANAGER_LABEL_BUTTON_SAVE; ?>"
class="button" onclick="javascript:submitbutton('submit2');">
<?php }
?>
</div>
<?php
//************publish on add begin
if ($realestatemanager_configuration['approve_on_add']['show']) {
if (checkAccess_REM($realestatemanager_configuration['approve_on_add']['registrationlevel'],
'NORECURSE', userGID_REM($my->id), $acl)) {
?><input type="hidden" name="approved" value="1"/><?php
} else {
?><input type="hidden" name="approved" value="0"/><?php
}
} else {
?><input type="hidden" name="approved" value="0"/><?php } ?>
<?php
if ($realestatemanager_configuration['publish_on_add']['show']) {
if (checkAccess_REM($realestatemanager_configuration['publish_on_add']['registrationlevel'],
'NORECURSE', userGID_REM($my->id), $acl)) {
?><input type="hidden" name="published" value="1"/><?php
} else {
?><input type="hidden" name="published" value="0"/><?php
}
} else {
?><input type="hidden" name="published" value="0"/><?php } ?>
</form>
<?php
}
static function displayLicense($id) {
global $mosConfig_live_site, $doc;
$doc->addStyleSheet($mosConfig_live_site . '/components/com_realestatemanager/includes/realestatemanager.css');
$session = JFactory::getSession();
$pas = $session->get("ssmid", "default");
$sid_1 = $session->getId();
$house = $session->get("obj_house", "default");
if (!($session->get("ssmid", "default")) || $pas == "" || $pas != $sid_1 || $_COOKIE['ssd'] != $sid_1 ||
!array_key_exists("HTTP_REFERER", $_SERVER) || $_SERVER["HTTP_REFERER"] == "" ||
strpos($_SERVER["HTTP_REFERER"], $_SERVER['SERVER_NAME']) === false) {
echo '<H3 align="center">Link failure</H3>';
exit;
}
echo '<style type="text/css"><!--#frm {width: 95%;height: 200px;border-width: thin;}--></style>';
echo '<form name="dlform" method="POST" action="' . sefRelToAbs($mosConfig_live_site .
'/index.php?option=com_realestatemanager&task=downitsf&id=' . @$house->id) . ' ">';
echo '<H2 align = "center" style="text-align: center;">' . _LICENSE_AGREEMENT_TITLE . '</H2>';
echo '';
echo '<IFRAME src="' . $mosConfig_live_site . '/components/com_realestatemanager/mylicense.php"
width="95%" height="230" name="frm" id="frm" SCROLLING="auto" noresize>';
echo '</IFRAME>';
echo '<input type="hidden" name="id" value="' . $id . '" />';
echo '<input type="hidden" name="task" value="downitsf" />';
echo '<input type="hidden" name="ssidPost" value="' . $session->getId() . '" >';
echo '<div align="right" style="text-align:right;>';
echo '<BR /> <font size="3"><strong>' . _LICENSE_AGREEMENT_ACCEPT . '</strong></font> <input
type="radio" name="choice" checked="checked" onclick="document.getElementById(\'DBB\').disabled=true;" />';
echo _REALESTATE_MANAGER_NO;
echo '<input type="radio" name="choice" onclick="document.getElementById(\'DBB\').removeAttribute(
\'disabled\');" >';
echo _REALESTATE_MANAGER_YES . ' ';
echo '<input type="submit" ID="DBB" name="downbutton" disabled="disabled"
value="download" /> ';
echo '<br /><br /><br /><br />';
echo '</div>';
echo '</form>';
}
static function showRentRequest(& $houses, & $currentcat, & $params, & $tabclass,
& $catid, & $sub_categories, $option) {
$pageNav = new JPagination(0, 0, 0);
HTML_realestatemanager::displayHouses($houses, $currentcat, $params, $tabclass,
$catid, $sub_categories, $pageNav, $option);
// add the formular for send to :-)
}
static function displayHouses_empty($rows, $currentcat, &$params, $tabclass, $catid,
$categories, &$pageNav = null,$is_exist_sub_categories=false, $option) {
positions_rem($params->get('allcategories01'));
?>
<div class="componentheading<?php echo $params->get('pageclass_sfx'); ?>">
<?php echo $currentcat->header; ?>
</div>
<?php positions_rem($params->get('allcategories02')); ?>
<table class="basictable table_48" border="0" cellpadding="4" cellspacing="0" width="100%">
<tr>
<td>
<?php echo $currentcat->descrip; ?>
</td>
<td width="120" align="center">
<img src="./components/com_realestatemanager/images/rem_logo.png"
align="right" alt="Real Estate Manager logo"/>
</td>
</tr>
</table>
<?php
if ($is_exist_sub_categories) {
?>
<?php positions_rem($params->get('singlecategory07')); ?>
<div class="componentheading<?php echo $params->get('pageclass_sfx'); ?>">
<?php echo _REALESTATE_MANAGER_LABEL_FETCHED_SUBCATEGORIES . " : " .
$params->get('category_name'); ?>
</div>
<?php positions_rem($params->get('singlecategory08')); ?>
<?php
HTML_realestatemanager::listCategories($params, $categories, $catid, $tabclass, $currentcat);
}
}
static function displayHouses(&$rows, $currentcat, &$params, $tabclass, $catid, $categories,
&$pageNav = null,$is_exist_sub_categories=false, $option, $layout = "default", $type = "alone_category") {
global $mosConfig_absolute_path, $Itemid;
$type = 'alone_category';
require getLayoutPath::getLayoutPathCom('com_realestatemanager', $type, $layout);
}
static function displaySearchHouses(&$rows, $currentcat, &$params, $tabclass, $catid, $categories,
&$pageNav = null,$is_exist_sub_categories=false, $option, $layout = "default", $layoutsearch = "default") {
global $mosConfig_absolute_path, $Itemid;
$type = 'search_result';
if ($params->get('show_searchlayout_form'))
PHP_realestatemanager::showSearchHouses($option, $catid, $option, $layoutsearch);
require getLayoutPath::getLayoutPathCom('com_realestatemanager', $type, $layout);
}
/*
* function for wishlist
*/
static function showWishlist(&$rows, &$params, &$pageNav, &$option){
global $mosConfig_absolute_path,$Itemid;
$layout = 'List';
$type = 'wishlist';
require getLayoutPath::getLayoutPathCom('com_realestatemanager',$type, $layout);
}
static function displayAllHouses(&$rows, &$params, $tabclass, &$pageNav, $layout = "default") {
global $mosConfig_absolute_path,$Itemid;
$type = 'all_houses';
require getLayoutPath::getLayoutPathCom('com_realestatemanager', $type, $layout);
}
//pdf0
static function displayHousesPdf($rows, $currentcat, &$params, $tabclass, $catid, $categories, &$pageNav) {
$session = JFactory::getSession();
$arr = $session->get("array", "default");
global $hide_js, $Itemid, $mosConfig_live_site, $mosConfig_absolute_path, $option;
global $limit, $total, $limitstart, $task, $paginations, $mainframe, $realestatemanager_configuration;
global $doc;
$doc->addStyleSheet($mosConfig_live_site . '/components/com_realestatemanager/includes/realestatemanager.css');
ob_end_clean();
ob_start();
?>
<div class="componentheading<?php echo $params->get('pageclass_sfx'); ?>">
<?php echo $currentcat->header; ?>
</div>
<br />
<div id="list">
<table class="basictable table_49" width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="10%" height="20" class="sectiontableheader<?php echo $params->get('pageclass_sfx'); ?>">
<?php echo _REALESTATE_MANAGER_LABEL_COVER; ?>
</td>
<td width="40%" height="20" class="sectiontableheader<?php echo $params->get('pageclass_sfx'); ?>">
<?php echo _REALESTATE_MANAGER_LABEL_TITLE; ?>
</td>
<td width="40%" height="20" class="sectiontableheader<?php echo $params->get('pageclass_sfx'); ?>">
<?php echo _REALESTATE_MANAGER_LABEL_ADDRESS; ?>
</td>
<td width="15%" height="20" class="sectiontableheader<?php echo $params->get('pageclass_sfx'); ?>">
<?php echo _REALESTATE_MANAGER_LABEL_PRICE ?>
</td>
<?php
if ($params->get('hits')) {
?>
<td height="20" class="sectiontableheader<?php echo $params->get('pageclass_sfx'); ?>" align="right">
<?php echo _REALESTATE_MANAGER_LABEL_HITS; ?>
</td>
<?php
}
if ($params->get('search_request')) {
?>
<td height="20" class="sectiontableheader<?php
echo $params->get('pageclass_sfx'); ?>" align="right">
<?php echo _REALESTATE_MANAGER_LABEL_CATEGORY; ?>
</td>
<?php
}
if ($params->get('show_rentstatus')) {
?>
<td height="20" class="sectiontableheader<?php echo $params->get('pageclass_sfx'); ?>">
<?php echo _REALESTATE_MANAGER_LABEL_RENT_CB; ?>
</td>
<?php
}
?>
</tr>
<?php
$available = false;
$k = 0;
//**************************************** add my perenos
$total = count($rows);
foreach ($rows as $row) {
//**************************************** add my perenos
$link = 'index.php?option=' . $option . '&task=view&id=' . $row->id
. '&catid=' . $row->catid[0] . '&Itemid=' . $Itemid; //
?>
<tr class="<?php echo $tabclass[$k]; ?>" >
<td style="padding-left:5px; padding-top:5px; padding-right:10px;">
<?php
$house = $row;
//for local images
$imageURL = ($house->image_link);
if ($imageURL == '') $imageURL = _REALESTATE_MANAGER_NO_PICTURE_BIG;
$file_name = rem_picture_thumbnail($imageURL,
$realestatemanager_configuration['fotogallery']['width'],
$realestatemanager_configuration['fotogallery']['high']);
$file = $mosConfig_live_site . '/components/com_realestatemanager/photos/' . $file_name;
echo '<img alt="' . $house->htitle . '" title="' . $house->htitle .
'" src="' . $file . '" border="0" class="little">';
?>
</td>
<td >
<a href="<?php echo sefRelToAbs($link); ?>" class="category<?php
echo $params->get('pageclass_sfx'); ?>">
<?php echo $row->htitle; ?>
</a>
</td>
<td>
<?php echo $row->hlocation; ?>
</td>
<td >
<?php echo $row->price . $row->priceunit; ?>
</td>
<?php
if ($params->get('hits')) {
?>
<td align="left">
<?php echo $row->hits; ?>
</td>
</tr>
<?php }
} ?>
</table>
</div>
<?php
$tbl = ob_get_contents();
ob_end_clean();
require_once($mosConfig_absolute_path . "/components/com_realestatemanager/tcpdf/config/lang/eng.php");
require_once($mosConfig_absolute_path . "/components/com_realestatemanager/tcpdf/tcpdf.php");
$pdf = new TCPDF1('P', 'mm', 'A4', true, 'UTF-8', false);
$pdf->SetTitle('Realestate Manager');
$pdf->SetFont('freesans', 'B', 20);
$pdf->AddPage();
$pdf->SetFont('freesans', '', 10);
$pdf->writeHTML($tbl, true, false, false, false, '');
$pdf->Output('Real_Estate_manager.pdf', 'I');
exit;
}
static function displayHousesPrint($rows, $currentcat, &$params, $tabclass, $catid, $categories, &$pageNav) {
$session = JFactory::getSession();
$arr = $session->get("array", "default");
global $hide_js, $Itemid, $mosConfig_live_site, $mosConfig_absolute_path;
global $limit, $total, $limitstart, $task, $paginations,
$mainframe, $realestatemanager_configuration;
global $doc;
$doc->addStyleSheet($mosConfig_live_site .
'/components/com_realestatemanager/includes/realestatemanager.css');
?>
<div class="componentheading<?php echo $params->get('pageclass_sfx'); ?>">
<table class="basictable table_50">
<tr>
<td>
<?php echo $currentcat->header; ?>
</td>
<td align="right">
<a href="#" onclick="window.print();return false;"><img
src="./components/com_realestatemanager/images/printButton.png" alt="Print" /></a>
</td>
</tr>
</table>
</div>
<br />
<div id="list">
<table class="basictable table_51" width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="10%" height="20" class="sectiontableheader<?php echo $params->get('pageclass_sfx'); ?>">
<?php echo _REALESTATE_MANAGER_LABEL_COVER; ?>
</td>
<td width="40%" height="20" class="sectiontableheader<?php echo $params->get('pageclass_sfx'); ?>">
<?php echo _REALESTATE_MANAGER_LABEL_TITLE; ?>
</td>
<td width="40%" height="20" class="sectiontableheader<?php echo $params->get('pageclass_sfx'); ?>">
<?php echo _REALESTATE_MANAGER_LABEL_ADDRESS; ?>
</td>
<td width="15%" height="20" class="sectiontableheader<?php echo $params->get('pageclass_sfx'); ?>">
<?php echo _REALESTATE_MANAGER_LABEL_PRICE ?>
</td>
<?php
if ($params->get('hits')) {
?>
<td height="20"
class="sectiontableheader<?php echo $params->get('pageclass_sfx'); ?>" align="right">
<?php echo _REALESTATE_MANAGER_LABEL_HITS; ?>
</td>
<?php
}
if ($params->get('search_request')) {
?>
<td height="20"
class="sectiontableheader<?php echo $params->get('pageclass_sfx'); ?>" align="right">
<?php echo _REALESTATE_MANAGER_LABEL_CATEGORY; ?>
</td>
<?php
}
if ($params->get('show_rentstatus')) {
?>
<td height="20" class="sectiontableheader<?php echo $params->get('pageclass_sfx'); ?>">
<?php echo _REALESTATE_MANAGER_LABEL_RENT_CB; ?>
</td>
<?php
}
?>
</tr>
<?php
$available = false;
$k = 0;
//**************************************** add my perenos
$total = count($rows);
foreach ($rows as $row) {
//**************************************** add my perenos
$link = 'index.php?option=com_realestatemanager&task=view&id='
. $row->id . '&catid=' . $row->catid[0] . '&Itemid=' . $Itemid; //
?>
<tr class="<?php echo $tabclass[$k]; ?>" >
<td style="padding-left:5px; padding-top:5px; padding-right:10px;">
<?php
$house = $row;
//for local images
$imageURL = ($house->image_link);
if ($imageURL == '') $imageURL = _REALESTATE_MANAGER_NO_PICTURE_BIG;
$file_name = rem_picture_thumbnail($imageURL,
$realestatemanager_configuration['fotogallery']['width'],
$realestatemanager_configuration['fotogallery']['high']);
$file = $mosConfig_live_site . '/components/com_realestatemanager/photos/' . $file_name;
echo '<img alt="' . $house->htitle . '" title="' . $house->htitle .
'" src="' . $file . '" border="0" class="little">';
?>
</td>
<td >
<a href="<?php echo sefRelToAbs($link); ?>"
class="category<?php echo $params->get('pageclass_sfx'); ?>">
<?php echo $row->htitle; ?>
</a>
</td>
<td>
<?php
echo $row->hlocation;
?>
</td>
<td >
<?php echo $row->price . $row->priceunit; ?>
</td>
<?php
if ($params->get('hits')) {
?>
<td align="left">
<?php echo $row->hits; ?>
</td>
</tr>
<?php }
} ?>
</table>
</div>
<?php
// exit;
}
static function displayAllHousesPdf($rows, &$params, $tabclass, &$pageNav) {
$session = JFactory::getSession();
$arr = $session->get("array", "default");
global $hide_js, $Itemid, $mosConfig_live_site, $mosConfig_absolute_path, $option;
global $limit, $total, $limitstart, $task, $paginations,
$mainframe, $realestatemanager_configuration;
global $doc;
$doc->addStyleSheet($mosConfig_live_site .
'/components/com_realestatemanager/includes/realestatemanager.css');
ob_end_clean();
ob_start();
?>
<div class="componentheading<?php echo $params->get('pageclass_sfx'); ?>">
</div>
<div id="list">
<table class="basictable table_52" width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="10%" height="20" class="sectiontableheader<?php
echo $params->get('pageclass_sfx'); ?>">
<?php echo _REALESTATE_MANAGER_LABEL_COVER; ?>
</td>
<td width="40%" height="20" class="sectiontableheader<?php
echo $params->get('pageclass_sfx'); ?>">
<?php echo _REALESTATE_MANAGER_LABEL_TITLE; ?>
</td>
<td width="40%" height="20" class="sectiontableheader<?php
echo $params->get('pageclass_sfx'); ?>">
<?php echo _REALESTATE_MANAGER_LABEL_ADDRESS; ?>
</td>
<td width="15%" height="20" class="sectiontableheader<?php
echo $params->get('pageclass_sfx'); ?>">
<?php echo _REALESTATE_MANAGER_LABEL_PRICE ?>
</td>
<?php
if ($params->get('hits')) {
?>
<td height="20" class="sectiontableheader<?php
echo $params->get('pageclass_sfx'); ?>" align="right">
<?php echo _REALESTATE_MANAGER_LABEL_HITS; ?>
</td>
<?php
}
if ($params->get('search_request')) {
?>
<td height="20" class="sectiontableheader<?php
echo $params->get('pageclass_sfx'); ?>" align="right">
<?php echo _REALESTATE_MANAGER_LABEL_CATEGORY; ?>
</td>
<?php
}
if ($params->get('show_rentstatus')) {
?>
<td height="20" class="sectiontableheader<?php
echo $params->get('pageclass_sfx'); ?>">
<?php echo _REALESTATE_MANAGER_LABEL_RENT_CB; ?>
</td>
<?php
}
?>
</tr>
<?php
$available = false;
$k = 0;
//**************************************** add my perenos
$total = count($rows);
if (isset($_GET['lang']))
$lang = $_GET['lang']; else
$lang = '*';
foreach ($rows as $row) {
//**************************************** add my perenos
$link = 'index.php?option=' . $option . '&task=view&id='
. $row->id . '&catid=' . $row->catid[0] . '&Itemid=' . $Itemid; //
?>
<tr class="<?php echo $tabclass[$k]; ?>" >
<td style="padding-left:5px; padding-top:5px; padding-right:10px;">
<?php
$house = $row;
//for local images
$imageURL = ($house->image_link);
if ($imageURL == '') $imageURL = _REALESTATE_MANAGER_NO_PICTURE_BIG;
$file_name = rem_picture_thumbnail($imageURL,
$realestatemanager_configuration['fotogallery']['width'],
$realestatemanager_configuration['fotogallery']['high']);
$file = $mosConfig_live_site . '/components/com_realestatemanager/photos/' . $file_name;
echo '<img alt="' . $house->htitle . '" title="' . $house->htitle .
'" src="' . $file . '" border="0" class="little">';
?>
</td>
<td >
<a href="<?php echo sefRelToAbs($link); ?>"
class="category<?php echo $params->get('pageclass_sfx'); ?>">
<?php echo $row->htitle; ?>
</a>
</td>
<td>
<?php echo $row->hlocation; ?>
</td>
<td >
<?php echo $row->price . $row->priceunit; ?>
</td>
<?php
if ($params->get('hits')) {
?>
<td align="left">
<?php echo $row->hits; ?>
</td>
<?php
}
if ($params->get('search_request')) {
?>
<td align="right">
<?php
$link1 = 'index.php?option=com_realestatemanager&task=showCategory&catid='
. $row->catid[0] . '&Itemid=' . $Itemid;
?>
<a href="<?php echo sefRelToAbs($link1); ?>"
class="category<?php echo $params->get('pageclass_sfx'); ?>">
<?php echo $row->category_titel; ?>
</a>
</td><?php
}
if ($params->get('show_rentstatus')) {
if ($params->get('show_rentrequest')) {
$data1 = JFactory::getDBO();
$query = "SELECT b.rent_from , b.rent_until FROM #__rem_rent AS b " .
" LEFT JOIN #__rem_houses AS c ON b.fk_houseid = c.id " .
" WHERE c.id=" . $row->id .
" AND c.published='1' AND c.approved='1' AND b.rent_return IS NULL";
$data1->setQuery($query);
$rents1 = $data1->loadObjectList();
?>
<td align="center" width="100%">
<?php
if (($row->listing_type == 1) && !isset($rents1[0]->rent_until)) {
echo "<img src='" . $mosConfig_live_site .
"/components/com_realestatemanager/images/available.png' ".
" alt='Available' name='image' border='0' align='middle' />";
} else if ($row->fk_rentid != 0 && isset($rents1[0]->rent_until)) {
echo _REALESTATE_MANAGER_LABEL_RENT_FROM_UNTIL . "<br />";
for ($a = 0; $a < count($rents1); $a++) {
$from_until = substr($rents1[$a]->rent_from, 0, 10) .
" / " .
substr($rents1[$a]->rent_until, 0, 10) . "\n";
print_r($from_until);
}
} else if (($row->listing_type != 1)) {
echo "<img src='" . $mosConfig_live_site .
"/components/com_realestatemanager/images/not_available.png' ".
"alt='Not Available' name='image' border='0' align='middle' />";
} ?>
</td>
<?php
}
}
?>
</tr>
<?php } ?>
</table>
</div>
<?php
$tbl = ob_get_contents();
ob_end_clean();
require_once($mosConfig_absolute_path . "/components/com_realestatemanager/tcpdf/config/lang/eng.php");
require_once($mosConfig_absolute_path . "/components/com_realestatemanager/tcpdf/tcpdf.php");
$pdf = new TCPDF1('P', 'mm', 'A4', true, 'UTF-8', false);
$pdf->SetTitle('Realestate Manager');
$pdf->SetFont('freesans', 'B', 20);
$pdf->AddPage();
$pdf->SetFont('freesans', '', 10);
$pdf->writeHTML($tbl, true, false, false, false, '');
$pdf->Output('Real_Estate_manager.pdf', 'I');
exit;
}
static function displayAllHousePrint($rows, &$params, $tabclass, &$pageNav) {
$session = JFactory::getSession();
$arr = $session->get("array", "default");
global $hide_js, $Itemid, $mosConfig_live_site, $mosConfig_absolute_path;
global $limit, $total, $limitstart, $task, $paginations, $mainframe, $realestatemanager_configuration;
global $doc;
$doc->addStyleSheet($mosConfig_live_site . '/components/com_realestatemanager/includes/realestatemanager.css');
?>
<div class="componentheading<?php echo $params->get('pageclass_sfx'); ?>">
<table class="basictable table_53">
<tr>
<td align="right">
<a href="#" onclick="window.print();return false;"><img
src="./components/com_realestatemanager/images/printButton.png" alt="Print" /></a>
</td>
</tr>
</table>
</div>
<div id="list">
<table class="basictable table_54" width="100%" border="1" cellspacing="0" cellpadding="0">
<tr>
<td width="10%" height="20" class="sectiontableheader<?php echo $params->get('pageclass_sfx'); ?>">
<?php echo _REALESTATE_MANAGER_LABEL_COVER; ?>
</td>
<td width="40%" height="20" class="sectiontableheader<?php echo $params->get('pageclass_sfx'); ?>">
<?php echo _REALESTATE_MANAGER_LABEL_TITLE; ?>
</td>
<td width="40%" height="20" class="sectiontableheader<?php echo $params->get('pageclass_sfx'); ?>">
<?php echo _REALESTATE_MANAGER_LABEL_ADDRESS; ?>
</td>
<td width="15%" height="20" class="sectiontableheader<?php echo $params->get('pageclass_sfx'); ?>">
<?php echo _REALESTATE_MANAGER_LABEL_PRICE ?>
</td>
<?php
if ($params->get('hits')) {
?>
<td height="20" class="sectiontableheader<?php echo $params->get('pageclass_sfx'); ?>" align="right">
<?php echo _REALESTATE_MANAGER_LABEL_HITS; ?>
</td>
<?php
}
if ($params->get('search_request')) {
?>
<td height="20" class="sectiontableheader<?php echo $params->get('pageclass_sfx'); ?>" align="right">
<?php echo _REALESTATE_MANAGER_LABEL_CATEGORY; ?>
</td>
<?php
}
if ($params->get('show_rentstatus')) {
?>
<td height="20" class="sectiontableheader<?php echo $params->get('pageclass_sfx'); ?>">
<?php echo _REALESTATE_MANAGER_LABEL_ACCESSED_FOR_RENT; ?>
</td>
<?php
}
?>
</tr>
<?php
$available = false;
$k = 0;
//**************************************** add my perenos
$total = count($rows);
foreach ($rows as $row) {
//**************************************** add my perenos
$link = 'index.php?option=com_realestatemanager&task=view&id='
. $row->id . '&catid=' . $row->catid[0] . '&Itemid=' . $Itemid; //
?>
<tr class="<?php echo $tabclass[$k]; ?>" >
<td style="padding-left:5px; padding-top:5px; padding-right:10px;">
<?php
$house = $row;
//for local images
$imageURL = ($house->image_link);
if ($imageURL == '') $imageURL = _REALESTATE_MANAGER_NO_PICTURE_BIG;
$file_name = rem_picture_thumbnail($imageURL,
$realestatemanager_configuration['fotogallery']['width'],
$realestatemanager_configuration['fotogallery']['high']);
$file = $mosConfig_live_site . '/components/com_realestatemanager/photos/' . $file_name;
echo '<img alt="' . $house->htitle . '" title="' . $house->htitle .
'" src="' . $file . '" border="0" class="little">';
?>
</td>
<td >
<a href="<?php echo sefRelToAbs($link); ?>" class="category<?php
echo $params->get('pageclass_sfx'); ?>">
<?php echo $row->htitle; ?>
</a>
</td>
<td>
<?php echo $row->hlocation; ?>
</td>
<td >
<?php echo $row->price . $row->priceunit; ?>
</td>
<?php
if ($params->get('hits')) {
?>
<td align="left">
<?php echo $row->hits; ?>
</td>
<?php
}
if ($params->get('search_request')) {
?>
<td align="right">
<?php
$link1 = 'index.php?option=com_realestatemanager&task=showCategory&catid='
. $row->catid[0] . '&Itemid=' . $Itemid;
?>
<a href="<?php echo sefRelToAbs($link1); ?>" class="category<?php
echo $params->get('pageclass_sfx'); ?>">
<?php echo $row->category_titel; ?>
</a>
</td><?php
}
if ($params->get('show_rentstatus')) {
if ($params->get('show_rentrequest')) {
$data1 = JFactory::getDBO();
$query = "SELECT b.rent_from , b.rent_until FROM #__rem_rent AS b " .
" LEFT JOIN #__rem_houses AS c ON b.fk_houseid = c.id " .
" WHERE c.id=" . $row->id .
" AND c.published='1' AND c.approved='1' AND b.rent_return IS NULL";
$data1->setQuery($query);
$rents1 = $data1->loadObjectList();
?>
<td align="center" width="100%">
<?php
if (($row->listing_type == 1) && !isset($rents1[0]->rent_until)) {
echo "<img src='" . $mosConfig_live_site .
"/components/com_realestatemanager/images/available.png' ".
" alt='Available' name='image' border='0' align='middle' />";
} else if ($row->fk_rentid != 0 && isset($rents1[0]->rent_until)) {
echo _REALESTATE_MANAGER_LABEL_RENT_FROM_UNTIL . "<br />";
for ($a = 0; $a < count($rents1); $a++) {
$from_until = substr($rents1[$a]->rent_from, 0, 10) .
" / " .
substr($rents1[$a]->rent_until, 0, 10) . "\n";
print_r($from_until);
}
} else if (($row->listing_type != 1)) {
echo "<img src='" . $mosConfig_live_site .
"/components/com_realestatemanager/images/not_available.png' ".
" alt='Not Available' name='image' border='0' align='middle' />";
} ?>
</td>
<?php
}
}
?>
</tr>
<?php } ?>
</table>
</div>
<?php
// exit;
}
/**
* Displays the house
*/
static function displayHouse(& $house, & $tabclass, & $params, & $currentcat, & $rating,
& $house_photos,$videos,$tracks, $id, $catid, $option, & $house_feature, & $currencys_price, $layout = "default") {
global $mosConfig_absolute_path;
$type = 'view_house';
require getLayoutPath::getLayoutPathCom('com_realestatemanager', $type, $layout);
}
static function displayHouseMainPdf(& $house, & $tabclass, & $params,
& $currentcat, & $rating, & $house_photos) {
global $hide_js, $mainframe, $Itemid, $realestatemanager_configuration,
$mosConfig_live_site, $mosConfig_absolute_path, $my;
global $doc;
$doc->addStyleSheet($mosConfig_live_site .
'/components/com_realestatemanager/includes/realestatemanager.css');
JPluginHelper::importPlugin('content');
$dispatcher = JDispatcher::getInstance();
ob_end_clean();
ob_start();
?>
<table class="basictable table_55" align="center">
<tr>
<td colspan ="2" align="center" class="title_td">
<?php echo $house->htitle; ?>
</td>
</tr>
<tr>
<td nowrap="nowrap" align="center" colspan="2">
<?php
//for local images
$imageURL = ($house->image_link);
if ($imageURL == '') $imageURL = _REALESTATE_MANAGER_NO_PICTURE_BIG;
$file_name = rem_picture_thumbnail($imageURL,
$realestatemanager_configuration['fotomain']['width'],
$realestatemanager_configuration['fotomain']['high']);
$file = $mosConfig_live_site . '/components/com_realestatemanager/photos/' . $file_name;
echo '<img alt="' . $house->htitle . '" title="' . $house->htitle .
'" src="' . $file . '" border="0" class="little">';
?>
</td>
</tr>
<tr>
<td class="first_td" align="right">
<strong><?php echo _REALESTATE_MANAGER_LABEL_ADDRESS; ?>:</strong>
</td>
<td width="270px" align="left" >
<?php echo $house->hlocation; ?>
</td>
</tr>
<?php if (trim($house->description)) { ?>
<tr>
<td valign="top" class="first_td">
<strong><?php echo _REALESTATE_MANAGER_LABEL_COMMENT; ?>:</strong>
</td>
<td width="270px" align="justify">
<?php
positions_rem($house->description);
?>
</td>
</tr>
<?php } if ($realestatemanager_configuration['owner']['show']
&& $house->ownername != '' && $house->owneremail != '') {
?>
<tr>
<td class="first_td" align="right">
<strong><?php echo _REALESTATE_MANAGER_LABEL_OWNER; ?>:</strong>
</td>
<td align="left">
<strong><?php echo $house->ownername, ', ', $house->owneremail; ?></strong>
</td>
</tr>
<?php
}
if ($house->listing_type != 0) {
?>
<tr>
<td class="first_td" align="right">
<strong><?php echo _REALESTATE_MANAGER_LABEL_LISTING_TYPE; ?>:</strong>
</td>
<td width="270px" align="left">
<?php
$listing_type[0] = _REALESTATE_MANAGER_OPTION_SELECT;
$listing_type[1] = _REALESTATE_MANAGER_OPTION_FOR_RENT;
$listing_type[2] = _REALESTATE_MANAGER_OPTION_FOR_SALE;
echo $listing_type[$house->listing_type];
?>
</td>
</tr>
<?php
}
if ($params->get('show_contacts_line')) {
if ($params->get('show_contacts_registrationlevel')) {
if (trim($house->contacts)) {
?>
<tr>
<td nowrap="nowrap" align="left" class="first_td">
<strong><?php echo _REALESTATE_MANAGER_LABEL_CONTACTS; ?>:</strong>
</td>
<td width="270px" align="left">
<?php echo $house->contacts; ?>
</td>
</tr>
<?php }
}
} ?>
<?php
if ($house->listing_type == 1) {
$rent = $house->getRent();
if ($rent == null) {
$help['name'] = '';
$help['until'] = '';
$help['rent'] = '';
} else {
if ($rent->rent_until != null) {
$help['rent'] = data_transform_rem($rents[$e]->rent_from) . " => "
. data_transform_rem($rents[$e]->rent_until);
$help['name'] = $rent->user_name;
$id = $rent->fk_houseid;
$database = JFactory::getDBO();
$select = "SELECT rent_from , rent_until FROM #__rem_rent AS a ".
" WHERE fk_houseid=" . $id . " AND rent_return IS NULL";
$database->setQuery($select);
$rents = 0;
$rents = $database->loadObjectList();
$num = count($rents);
} else {
$help['rent'] = $help['rent'] . _REALESTATE_MANAGER_LABEL_RENT_FROM_UNTIL_NOT_KNOWN;
}
} //end else
?>
<?php if (isset($rents)) { ?>
<tr>
<td align="right" class="title_td">
<strong><?php echo _REALESTATE_MANAGER_LABEL_RENT_FROM_UNTIL; ?>:</strong>
</td>
</tr>
<?php
for ($e = 0, $m = count($rents); $e < $m; $e++) {
print("<tr><td align=\"right\"><strong></strong></td><td>");
$date = data_transform_rem($rents[$e]->rent_from) . " => "
. data_transform_rem($rents[$e]->rent_until);
print_r($date);
print(" </td></tr>");
}
}
}
//end if
?>
<?php if ($house->price != "" && $params->get('show_pricerequest') == '1') { ?>
<tr>
<td nowrap="nowrap" align="right" class="title_td">
<strong><?php echo _REALESTATE_MANAGER_LABEL_PRICE; ?>:</strong>
</td>
<td align="left">
<?php echo $house->price . " " . $house->priceunit; ?>
</td>
</tr>
<?php
} ?>
<?php if (trim($house->rooms)) { ?>
<tr>
<td nowrap="nowrap" align="right" class="title_td" >
<strong><?php echo _REALESTATE_MANAGER_LABEL_ROOMS; ?>:</strong>
</td>
<td align="left">
<?php echo $house->rooms; ?>
</td>
</tr>
<?php } ?>
<?php if (trim($house->bathrooms)) { ?>
<tr>
<td nowrap="nowrap" align="right" class="title_td" >
<strong><?php echo _REALESTATE_MANAGER_LABEL_BATHROOMS; ?>:</strong>
</td>
<td align="left">
<?php echo $house->bathrooms; ?>
</td>
</tr>
<?php } ?>
<?php if (trim($house->bedrooms)) { ?>
<tr>
<td nowrap="nowrap" align="right" class="title_td">
<strong><?php echo _REALESTATE_MANAGER_LABEL_BEDROOMS; ?>:</strong>
</td>
<td align="left">
<?php echo $house->bedrooms; ?>
</td>
</tr>
<?php } ?>
<?php if (trim($house->agent)) { ?>
<tr>
<td nowrap="nowrap" align="right" class="title_td">
<strong><?php echo _REALESTATE_MANAGER_LABEL_AGENT; ?>:</strong>
</td>
<td align="left">
<?php echo $house->agent; ?>
</td>
</tr>
<?php } ?>
<?php
if ($params->get('show_contacts_line')) {
if ($params->get('show_contacts_registrationlevel')) {
if (trim($house->contacts)) {
?>
<tr>
<td nowrap="nowrap" align="right"class="title_td" >
<strong><?php echo _REALESTATE_MANAGER_LABEL_CONTACTS; ?>:</strong>
</td>
<td align="left">
<?php echo $house->contacts; ?>
</td>
</tr>
<?php }
}
} ?>
<?php
if ($house->listing_status != 0) {
$listing_status1 = explode(',', _REALESTATE_MANAGER_OPTION_LISTING_STATUS);
$i = 1;
foreach ($listing_status1 as $listing_status2) {
$listing_status[$i] = $listing_status2;
$i++;
}
?>
<tr>
<td nowrap="nowrap" align="right" class="title_td" >
<strong><?php echo _REALESTATE_MANAGER_LABEL_LISTING_STATUS; ?>:</strong>
</td>
<td align="left">
<?php echo $listing_status[$house->listing_status]; ?>
</td>
</tr>
<?php } ?>
<?php
if ($house->property_type != 0) {
$property_type1 = explode(',', _REALESTATE_MANAGER_OPTION_PROPERTY_TYPE);
$i = 1;
foreach ($property_type1 as $property_type2) {
$property_type[$i] = $property_type2;
$i++;
}
?>
<tr>
<td nowrap="nowrap" align="right" class="title_td">
<strong><?php echo _REALESTATE_MANAGER_LABEL_PROPERTY_TYPE; ?>:</strong>
</td>
<td align="left">
<?php echo $property_type[$house->property_type]; ?>
</td>
</tr>
<?php } ?>
<?php if (trim($house->lot_size)) { ?>
<tr>
<td nowrap="nowrap" align="right" class="title_td">
<strong><?php echo _REALESTATE_MANAGER_LABEL_LOT_SIZE; ?>:</strong>
</td>
<td>
<?php echo $house->lot_size; ?>
</td>
</tr>
<?php } ?>
<?php if (trim($house->house_size)) { ?>
<tr>
<td nowrap="nowrap" align="right" class="title_td">
<strong><?php echo _REALESTATE_MANAGER_LABEL_HOUSE_SIZE; ?>:</strong>
</td>
<td>
<?php echo $house->house_size; ?>
</td>
</tr>
<?php } ?>
<?php if (trim($house->garages)) { ?>
<tr>
<td nowrap="nowrap" align="right" class="title_td">
<strong><?php echo _REALESTATE_MANAGER_LABEL_GARAGES; ?>:</strong>
</td>
<td align="left">
<?php echo $house->garages; ?>
</td>
</tr>
<?php } ?>
<?php if (trim($house->year)) { ?>
<tr>
<td nowrap="nowrap" align="right" class="title_td">
<strong><?php echo _REALESTATE_MANAGER_LABEL_BUILD_YEAR; ?>:</strong>
</td>
<td align="left">
<?php echo $house->year; ?>
</td>
</tr>
<?php } ?>
</table>
<?php
$tbl = ob_get_contents();
ob_end_clean();
require_once($mosConfig_absolute_path . "/components/com_realestatemanager/tcpdf/config/lang/eng.php");
require_once($mosConfig_absolute_path . "/components/com_realestatemanager/tcpdf/tcpdf.php");
$pdf = new TCPDF1('P', 'mm', 'A4', true, 'UTF-8', false);
//$pdf->SetAuthor('');
$pdf->SetTitle('Real Estate manager');
$pdf->SetFont('freesans', 'B', 20);
$pdf->AddPage();
//$pdf->Write(0, 'Real Estate manager', '', 0, 'L', true, 0, false, false, 0);
$pdf->SetFont('freesans', '', 10);
$pdf->writeHTML($tbl, true, false, false, false, '');
$pdf->Output('Real_Estate_manager.pdf', 'I');
exit;
}
static function displayHouseMainprint(& $house, & $tabclass, & $params,
& $currentcat, & $rating, & $house_photos) {
global $hide_js, $mainframe, $Itemid, $realestatemanager_configuration,
$mosConfig_live_site, $mosConfig_absolute_path, $my;
global $doc;
$doc->addStyleSheet($mosConfig_live_site .
'/components/com_realestatemanager/includes/realestatemanager.css');
JPluginHelper::importPlugin('content');
$dispatcher = JDispatcher::getInstance();
?>
<table class="basictable table_56" align="center">
<tr>
<td colspan ="2" align="center" class="title_td">
<?php echo $house->htitle; ?>
<a href="#" onclick="window.print();return false;"><img
src="<?php echo $mosConfig_live_site;?>/components/com_realestatemanager/images/printButton.png" alt="Print"/></a>
</td>
</tr>
<tr>
<td nowrap="nowrap" align="center" colspan="2">
<?php
//for local images
$imageURL = ($house->image_link);
if ($imageURL == '') $imageURL = _REALESTATE_MANAGER_NO_PICTURE_BIG;
$file_name = rem_picture_thumbnail($imageURL,
$realestatemanager_configuration['fotomain']['width'],
$realestatemanager_configuration['fotomain']['high']);
$file = $mosConfig_live_site . '/components/com_realestatemanager/photos/' . $file_name;
echo '<img alt="' . $house->htitle . '" title="' . $house->htitle .
'" src="' . $file . '" border="0" class="little">';
?>
</td>
</tr>
<tr>
<td class="first_td" align="right">
<strong><?php echo _REALESTATE_MANAGER_LABEL_ADDRESS; ?>:</strong>
</td>
<td width="270px" align="left" >
<?php echo $house->hlocation; ?>
</td>
</tr>
<?php if (trim($house->description)) { ?> <tr>
<td valign="top" class="first_td" align="right">
<strong><?php echo _REALESTATE_MANAGER_LABEL_COMMENT; ?>:</strong>
</td>
<td width="270px" align="justify">
<?php
positions_rem($house->description);
?>
</td>
</tr>
<?php } if ($realestatemanager_configuration['owner']['show']
&& $house->ownername != '' && $house->owneremail != '') {
?>
<tr>
<td class="first_td" align="right">
<strong><?php echo _REALESTATE_MANAGER_LABEL_OWNER; ?>:</strong>
</td>
<td align="left">
<strong><div class="strong"><?php
echo $house->ownername, ', ', $house->owneremail; ?>
</div></strong>
</td>
</tr>
<?php
}
if ($house->listing_type != 0) {
?>
<tr>
<td class="first_td" align="right">
<strong><?php echo _REALESTATE_MANAGER_LABEL_LISTING_TYPE; ?>:</strong>
</td>
<td width="270px" align="left">
<?php
$listing_type[0] = _REALESTATE_MANAGER_OPTION_SELECT;
$listing_type[1] = _REALESTATE_MANAGER_OPTION_FOR_RENT;
$listing_type[2] = _REALESTATE_MANAGER_OPTION_FOR_SALE;
echo $listing_type[$house->listing_type];
?>
</td>
</tr>
<?php
}
if ($params->get('show_contacts_line')) {
if ($params->get('show_contacts_registrationlevel')) {
if (trim($house->contacts)) {
?>
<tr>
<td nowrap="nowrap" align="right" class="first_td">
<strong><?php echo _REALESTATE_MANAGER_LABEL_CONTACTS; ?>:</strong>
</td>
<td width="270px" align="left">
<?php echo $house->contacts; ?>
</td>
</tr>
<?php }
}
} ?>
<?php
if ($house->listing_type == 1) {
$rent = $house->getRent();
if ($rent == null) {
$help['name'] = '';
$help['until'] = '';
$help['rent'] = '';
} else {
if ($rent->rent_until != null) {
$help['rent'] = substr($rent->rent_from, 0, 10) . " " . substr($rent->rent_until, 0, 10);
$help['name'] = $rent->user_name;
$id = $rent->fk_houseid;
$database = JFactory::getDBO();
$select = "SELECT rent_from , rent_until FROM #__rem_rent AS a ".
" WHERE fk_houseid=" . $id . " AND rent_return IS NULL";
$database->setQuery($select);
$rents = 0;
$rents = $database->loadObjectList();
$num = count($rents);
} else {
$help['rent'] = $help['rent'] . _REALESTATE_MANAGER_LABEL_RENT_FROM_UNTIL_NOT_KNOWN;
}
} //end else
?>
<?php if (isset($rents)) { ?>
<td align="right" class="title_td">
<strong><?php echo _REALESTATE_MANAGER_LABEL_RENT_FROM_UNTIL; ?>:</strong>
</td>
<td>
</td>
</tr>
<?php
for ($e = 0, $m = count($rents); $e < $m; $e++) {
print("<td align=\"right\"><strong></strong></td><td>");
$date = substr($rents[$e]->rent_from, 0, 10) . " " . substr($rents[$e]->rent_until, 0, 10);
print_r($date);
print(" </td></tr>");
}
}
?>
<?php
}
//end if
?>
<?php if ($house->price != "" && $params->get('show_pricerequest') == '1') { ?>
<tr>
<td nowrap="nowrap" align="right" class="title_td">
<strong><?php echo _REALESTATE_MANAGER_LABEL_PRICE; ?>:</strong>
</td>
<td>
<?php echo $house->price . " " . $house->priceunit; ?>
</td>
</tr>
<?php
} ?>
<?php if (trim($house->rooms)) { ?>
<tr>
<td nowrap="nowrap" align="right" class="title_td" >
<strong><?php echo _REALESTATE_MANAGER_LABEL_ROOMS; ?>:</strong>
</td>
<td>
<?php echo $house->rooms; ?>
</td>
</tr>
<?php } ?>
<?php if (trim($house->bathrooms)) { ?>
<tr>
<td nowrap="nowrap" align="right" class="title_td" >
<strong><?php echo _REALESTATE_MANAGER_LABEL_BATHROOMS; ?>:</strong>
</td>
<td>
<?php echo $house->bathrooms; ?>
</td>
</tr>
<?php } ?>
<?php if (trim($house->bedrooms)) { ?>
<tr>
<td nowrap="nowrap" align="right" class="title_td">
<strong><?php echo _REALESTATE_MANAGER_LABEL_BEDROOMS; ?>:</strong>
</td>
<td>
<?php echo $house->bedrooms; ?>
</td>
</tr>
<?php } ?>
<?php if (trim($house->agent)) { ?>
<tr>
<td nowrap="nowrap" align="right" class="title_td">
<strong><?php echo _REALESTATE_MANAGER_LABEL_AGENT; ?>:</strong>
</td>
<td>
<?php echo $house->agent; ?>
</td>
</tr>
<?php } ?>
<?php
if ($params->get('show_contacts_line')) {
if ($params->get('show_contacts_registrationlevel')) {
if (trim($house->contacts)) {
?>
<tr>
<td nowrap="nowrap" align="right" class="title_td" >
<strong><?php echo _REALESTATE_MANAGER_LABEL_CONTACTS; ?>:</strong>
</td>
<td>
<?php echo $house->contacts; ?>
</td>
</tr>
<?php }
}
} ?>
<?php
if ($house->listing_status != 0) {
$listing_status1 = explode(',', _REALESTATE_MANAGER_OPTION_LISTING_STATUS);
$i = 1;
foreach ($listing_status1 as $listing_status2) {
$listing_status[$i] = $listing_status2;
$i++;
}
?>
<tr>
<td nowrap="nowrap" align="right" class="title_td" >
<strong><?php echo _REALESTATE_MANAGER_LABEL_LISTING_STATUS; ?>:</strong>
</td>
<td>
<?php echo $listing_status[$house->listing_status]; ?>
</td>
</tr>
<?php } ?>
<?php
if ($house->property_type != 0) {
$property_type1 = explode(',', _REALESTATE_MANAGER_OPTION_PROPERTY_TYPE);
$i = 1;
foreach ($property_type1 as $property_type2) {
$property_type[$i] = $property_type2;
$i++;
}
?>
<tr>
<td nowrap="nowrap" align="right" class="title_td">
<strong><?php echo _REALESTATE_MANAGER_LABEL_PROPERTY_TYPE; ?>:</strong>
</td>
<td>
<?php echo $property_type[$house->property_type]; ?>
</td>
</tr>
<?php } ?>
<?php if (trim($house->lot_size)) { ?>
<tr>
<td nowrap="nowrap" align="right" class="title_td">
<strong><?php echo _REALESTATE_MANAGER_LABEL_LOT_SIZE; ?>:</strong>
</td>
<td>
<?php echo $house->lot_size; ?>
</td>
</tr>
<?php } ?>
<?php if (trim($house->house_size)) { ?>
<tr>
<td nowrap="nowrap" align="right" class="title_td">
<strong><?php echo _REALESTATE_MANAGER_LABEL_HOUSE_SIZE; ?>:</strong>
</td>
<td>
<?php echo $house->house_size; ?>
</td>
</tr>
<?php } ?>
<?php if (trim($house->garages)) { ?>
<tr>
<td nowrap="nowrap" align="right" class="title_td">
<strong><?php echo _REALESTATE_MANAGER_LABEL_GARAGES; ?>:</strong>
</td>
<td>
<?php echo $house->garages; ?>
</td>
</tr>
<?php } ?>
<?php if (trim($house->year)) { ?>
<tr>
<td nowrap="nowrap" align="right" class="title_td">
<strong><?php echo _REALESTATE_MANAGER_LABEL_BUILD_YEAR; ?>:</strong>
</td>
<td>
<?php echo $house->year; ?>
</td>
</tr>
<?php } ?>
</table>
<?php
exit();
}
/**
* Display links to categories
*/
static function showCategories(&$params, &$categories, &$catid, &$tabclass, &$currentcat, $layout) {
global $mosConfig_absolute_path;
$type = 'all_categories';
require getLayoutPath::getLayoutPathCom('com_realestatemanager', $type, $layout);
}
static function showAddButton($Itemid) {
global $mosConfig_live_site;
?>
<form action="<?php
echo sefRelToAbs("index.php?option=com_realestatemanager&task=show_add&Itemid="
. $Itemid); ?>" method="post" name="show_add" enctype="multipart/form-data">
<input type="submit" name="submit" value="<?php
echo _REALESTATE_MANAGER_LABEL_BUTTON_ADD_HOUSE; ?>" class="button"/>
</form>
<?php
}
static function showButtonMyHouses() {
global $mosConfig_live_site, $Itemid;
?>
<form action="<?php
echo sefRelToAbs("index.php?option=com_realestatemanager&task=my_houses&Itemid="
. $Itemid); ?>" method="post" name="show_my_houses">
<input type="submit" name="submit" value="<?php
echo _REALESTATE_MANAGER_LABEL_SHOW_MY_HOUSES; ?>" class="button"/>
</form>
<?php
}
static function showOwnersButton() {
global $mosConfig_live_site, $Itemid;
?>
<form action="<?php
echo sefRelToAbs("index.php?option=com_realestatemanager&task=owners_list&Itemid="
. $Itemid); ?>" method="post" name="ownerslist">
<input type="submit" name="submit" value="<?php
echo _REALESTATE_MANAGER_LABEL_BUTTON_OWNERSLIST; ?>" class="button"/>
</form>
<?php
}
static function showSearchHouses($params, $currentcat, $clist, $option, $layout = "default") {
global $mosConfig_absolute_path, $task;
$type = $task == "search" ? "show_search_result" : "show_search_house";
// $type = 'show_search_house';
require getLayoutPath::getLayoutPathCom('com_realestatemanager', $type, $layout);
}
/////////////////////////////////////
static function showRssCategories($params, &$categories, &$catid) {
global $hide_js, $Itemid, $acl, $mosConfig_live_site, $my;
global $limit, $total, $limitstart, $paginations, $mainframe, $realestatemanager_configuration;
$mosConfig_live_site_http = JURI::root();
echo '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
echo '<!-- generator="Real Estate manager" -->' . "\n";
echo '<?xml-stylesheet href="" type="text/css"?>' . "\n";
echo '<?xml-stylesheet href="" type="text/xsl"?>' . "\n";
echo '<rss version="2.0">' . "\n";
echo "<channel>\n";
if (!$categories) {
echo "<title>" . $mosConfig_live_site_http . " - " .
_REALESTATE_MANAGER_TITLE . "</title>\n";
echo "<description>" . _REALESTATE_MANAGER_TITLE . " - " .
_REALESTATE_MANAGER_ERROR_HAVENOT_HOUSES_RSS . "</description>\n";
} else {
if (!$catid) {
echo "<title>" . $mosConfig_live_site_http . " - " .
_REALESTATE_MANAGER_TITLE . " - ALL</title>\n";
echo "<description><![CDATA[" . _REALESTATE_MANAGER_TITLE .
" " . $categories[0]->cdesc . "]]></description>\n";
} else {
echo "<title>" . $mosConfig_live_site_http . " - " .
_REALESTATE_MANAGER_TITLE . " - " . $categories[0]->ctitle . "</title>\n";
echo "<description><![CDATA[" . _REALESTATE_MANAGER_TITLE .
" " . $categories[0]->cdesc . "]]></description>\n";
}
}
echo "<link>" . $mosConfig_live_site . "</link>\n";
echo "<lastBuildDate>" . date("Y-m-d H:i:s") . "</lastBuildDate>\n";
echo "<generator>" . _REALESTATE_MANAGER_TITLE . "</generator>\n";
for ($i = 0; $i < count($categories); $i++) {
//Select list for listing type
$listing_type[0] = _REALESTATE_MANAGER_OPTION_SELECT;
$listing_type[1] = _REALESTATE_MANAGER_OPTION_FOR_RENT;
$listing_type[2] = _REALESTATE_MANAGER_OPTION_FOR_SALE;
//Select list for listing status type
$listing_status_type[0] = _REALESTATE_MANAGER_OPTION_SELECT;
$listing_status_type1 = explode(',', _REALESTATE_MANAGER_OPTION_LISTING_STATUS);
$j = 1;
foreach ($listing_status_type1 as $listing_status_type2) {
$listing_status_type[$j] = $listing_status_type2;
$j++;
}
//Select list for property type
$property_type[0] = _REALESTATE_MANAGER_OPTION_SELECT;
$property_type1 = explode(',', _REALESTATE_MANAGER_OPTION_PROPERTY_TYPE);
$j = 1;
foreach ($property_type1 as $property_type2) {
$property_type[$j] = $property_type2;
$j++;
}
$category = $categories[$i];
echo "<item>";
echo "<title>" . $category->htitle . "</title>" . "\n";
echo "<link>" . $mosConfig_live_site_http . "/index.php?option=com_realestatemanager&Itemid=" .
$Itemid . "&task=view&id=" . $category->bid . "&catid="
. $category->cid . "</link>" . "\n";
echo "<description><![CDATA[";
//for local images
$imageURL = ($category->image_link);
if ($imageURL == '') $imageURL = _REALESTATE_MANAGER_NO_PICTURE_BIG;
$file_name = rem_picture_thumbnail($imageURL,
$realestatemanager_configuration['fotomain']['width'],
$realestatemanager_configuration['fotomain']['high']);
$file = $mosConfig_live_site . '/components/com_realestatemanager/photos/' . $file_name;
echo '<br /><img alt="' . $category->htitle . '" title="' . $category->htitle .
'" src="' . $file . '" border="0" class="little">';
if (trim($category->description))
echo "<br /><description><b>" . _REALESTATE_MANAGER_LABEL_DESCRIPTION .
": </b>" . $category->description . "</description>";
if ($category->listing_type != 0)
echo "<br /><listing_type><b>" . _REALESTATE_MANAGER_LABEL_LISTING_TYPE .
": </b>" . $listing_type[$category->listing_type] . "</listing_type>";
if ($category->price > 0)
echo "<br /><price><b>" . _REALESTATE_MANAGER_LABEL_PRICE . ": </b>" .
$category->price . "</price>";
if (trim($category->hlocation))
echo "<br /><hlocation><b>" . _REALESTATE_MANAGER_LABEL_ADDRESS .
": </b>" . $category->hlocation . "</hlocation>";
echo "<br /><owner><b>" . _REALESTATE_MANAGER_LABEL_OWNER . ": </b>"
. $category->owneremail . "</owner>";
if (trim($category->year))
echo "<br /><year><b>" . _REALESTATE_MANAGER_LABEL_YEAR . ": </b>"
. $category->year . "</year>";
if (trim($category->rooms))
echo "<br /><rooms><b>" . _REALESTATE_MANAGER_LABEL_ROOMS . ": </b>"
. $category->rooms . "</rooms>";
if (trim($category->bathrooms))
echo "<br /><bathrooms><b>" . _REALESTATE_MANAGER_LABEL_BATHROOMS . ": </b>"
. $category->bathrooms . "</bathrooms>";
if (trim($category->bedrooms))
echo "<br /><bedrooms><b>" . _REALESTATE_MANAGER_LABEL_BEDROOMS . ": </b>"
. $category->bedrooms . "</bedrooms>";
if ($category->listing_status != 0)
echo "<br /><listing_status><b>" . _REALESTATE_MANAGER_LABEL_LISTING_STATUS
. ": </b>" . $listing_status_type[$category->listing_status] . "</listing_status>";
if (trim($category->contacts))
if ($params->get('show_contacts_line')) {
if ($params->get('show_contacts_registrationlevel')) {
echo "<br /><contacts><b>" . _REALESTATE_MANAGER_LABEL_CONTACTS
. ": </b>" . $category->contacts . "</contacts>";
}
}
echo "]]></description>\n";
echo "<pubDate>" . $category->date . "</pubDate>\n";
echo "</item>\n";
}
?>
</channel>
</rss>
<?php
exit;
}
static function showOwnersList(&$params, &$ownerslist, &$pageNav, &$layout = "default") {
global $mosConfig_absolute_path, $realestatemanager_configuration;
$type = 'owner_houses';
require getLayoutPath::getLayoutPathCom('com_realestatemanager', $type, $layout);
}
static function showRentRequestThanks($params, $backlink, $currentcat, $houseid=NULL, $time_difference=NULL) {
global $Itemid, $doc, $mosConfig_live_site, $hide_js, $catid,
$option, $realestatemanager_configuration;;
$doc->addStyleSheet($mosConfig_live_site .
'/components/com_realestatemanager/includes/realestatemanager.css');
?>
<div class="componentheading<?php echo $params->get('pageclass_sfx'); ?>">
</div>
<?php
if($houseid){
$item_name = $houseid->htitle; //'Donate to website.com';
$paypal_real_or_test = $realestatemanager_configuration['paypal_real_or_test']['show'];
if($paypal_real_or_test==0)
$paypal_path = 'www.sandbox.paypal.com';
else
$paypal_path = 'www.paypal.com';
if($time_difference){
$amount = $time_difference[0]; // price 198
$currency_code = $time_difference[1] ; // priceunit
}
else{
$amount= $houseid->price; // 210
$currency_code = $houseid->priceunit;
}
$amountLine='';
$amountLine .= '<input type="hidden" name="amount" value="'.$amount.'" />'."\n";
}
?>
<div class="save_add_table">
<div class="descrip"><?php echo $currentcat->descrip; ?></div>
</div>
<?php
if ($option != 'com_realestatemanager') {
$form_action = "index.php?option=" . $option . "&Itemid=" . $Itemid ;
}
else
$form_action = "index.php?option=com_realestatemanager&Itemid=" . $Itemid;
?>
<div class="basictable_15 basictable">
<div>
<?php
$acompte = 0.30;
echo '<br/> '._REALESTATE_MANAGER_TOTAL_PRICE .$amount.' '.$currency_code;
echo '<br/> '._REALESTATE_MANAGER_ACCOUNT_L_PRICE .$amount*$acompte.' '.$currency_code.'</div>';
?>
</div>
<div class="paypal"><h3>Paiement par PayPal</h3>
<?php
//paypal button denis 25.12.2013
if($params->get('paypal_buy_status') && $params->get('paypal_buy_status_rl')):
if($params->get('paypal_buy_status') == 1
and isset($amount) and isset($currency_code) ){
if($params->get('paypal_buy_status_rl') == 1){
echo '<br/> '._REALESTATE_MANAGER_RENT_NOW_BY_PAYPAL.' <br/><br/>';
$houseid->price=$amount*$acompte;
echo HTML_realestatemanager :: getSaleForm($houseid,$realestatemanager_configuration);
?>
<?php
}
}
if($params->get('paypal_buy_status') == 2 and isset($amount) and isset($currency_code) ){
if($params->get('paypal_buy_status_rl') == 2){
echo '<br/> '._REALESTATE_MANAGER_RENT_NOW_BY_PAYPAL.' <br/><br/>';
$houseid->price=$amount*$acompte;
echo HTML_realestatemanager :: getSaleForm($houseid,$realestatemanager_configuration);
}
}
?>
</form>
<?php //end paypal button
else:
?>
<input class="button" type="submit" ONCLICK="window.location.href='<?php $user = JFactory::getUser(); echo $backlink; ?>'" value="OK">
<?php endif;?>
</div>
<div class="cheque">
<h3>Paiement par chèque</h3>
<p>Veuillez adresser un chèque d'un montant de <?php echo $amount*$acompte.' '.$currency_code; ?> à l'odre : MME LETORT Monique</p>
<form action="index.php" method="post">
<input type="hidden" name="item_number" value="<?php echo $_REQUEST['orderID']; ?>" />
<input id="cheque" name="cheque" class="btn btn-info" type="button" onclick="updatechequepayment();" value="Payer par chèque"></input>
<script type="text/javascript">
function updatechequepayment() {
//instruction pour un paiement par chèque
var order_id = <?php echo $_REQUEST['orderID']; ?>;
jQuerREL.ajax({
type: "POST",
url: "index.php?option=com_realestatemanager&task=ajax_update_check_payment",
data : 'order_id=' + order_id,
success: function() {
//jQuerREL("#response-cheque").html(data);
var html = '<a href="#paiement-par-cheque" class="modal modal-cheque"><h4>Réservation en cours</h4><p>Nous validerons votre réservation lors de la récéption de votre chèque. Si toutefois entre-temps une réservation à lieu via paypal pour les mêmes dates de réservation que les vôtres, nous serions malheuresement contraints d\'annuler votre demande de réservation.</p></a>';
jQuerREL("#response-cheque").html(html);
}
});
}
jQuerREL('html').click(function() {
jQuerREL(".modal-cheque").hide();
});
jQuerREL(".modal-cheque").click(function(event){
event.stopPropagation();
});
</script>
</form>
<p id="response-cheque"></p>
</div>
</div>
<?php
}
//********************************************************************************************************
static function getSaleForm($realestate,$realestatemanager_configuration){
if($realestate){
getHTMLPayPalRM($realestate,$realestatemanager_configuration['plugin_name_select']);
}
}
//********************************************************************************************************
static function showTabs(&$params, &$userid, &$username, &$comprofiler, &$option) {
global $mosConfig_live_site, $doc;
$doc->addStyleSheet($mosConfig_live_site . '/components/com_realestatemanager/TABS/tabcontent.css');
$doc->addScript($mosConfig_live_site . '/components/com_realestatemanager/TABS/tabcontent.js');
?>
<?php
if(checkJavaScriptIncludedRE("jQuerREL-1.2.6.js") === false ) {
$doc->addScript(JURI::root(true) . '/components/com_realestatemanager/lightbox/js/jQuerREL-1.2.6.js');
}
?>
<script type="text/javascript">jQuerREL=jQuerREL.noConflict();</script>
</br> <!-- br for plugin simplemembership!!! -->
<div class='tabs_buttons'>
<ul id="countrytabs" class="shadetabs">
<?php
if ($params->get('show_edit_registrationlevel')) {
?>
<li>
<a class="my_houses_edit" href="<?php echo JRoute::_('index.php?option='
. $option .'&userId='.$userid . '&task=edit_my_houses' . $comprofiler, false);
?>"><?php echo _REALESTATE_MANAGER_SHOW_TABS_SHOW_MY_HOUSES; ?></a>
</li>
<?php
}
if ($params->get('show_rent')) {
if ($params->get('show_rent_registrationlevel')) {
?>
<li>
<a class="my_houses_rent" href="<?php echo JRoute::_('index.php?option='
. $option . '&userId='.$userid . '&task=rent_requests' . $comprofiler , false);
?>"><?php echo _REALESTATE_MANAGER_SHOW_TABS_RENT_REQUESTS; ?></a>
</li>
<?php
}
}
if ($params->get('show_buy')) {
if ($params->get('show_buy_registrationlevel')) {
?>
<li>
<a class="my_houses_buy" href="<?php echo JRoute::_('index.php?option='
. $option . '&userId='.$userid . '&task=buying_requests' . $comprofiler , false);
?>"><?php echo _REALESTATE_MANAGER_SHOW_TABS_BUYING_REQUESTS; ?></a>
</li>
<?php
}
}
if ($params->get('show_history')) {
if ($params->get('show_history_registrationlevel')) {
?>
<li>
<a class="my_houses_history" href="<?php echo JRoute::_('index.php?option='
. $option . '&userId='.$userid . '&task=rent_history' . $comprofiler , false);
?>"><?php echo _REALESTATE_MANAGER_LABEL_CBHISTORY_ML; ?></a>
</li>
<?php
}
}
?>
</ul>
</div>
<script type="text/javascript">
jQuerREL(document).ready(function(){
var atr = jQuerREL("#adminForm div:first-child").attr("id");
if(!atr){
atr = jQuerREL("#adminForm table:first-child").attr("id");
}
jQuerREL("#countrytabs > li > a."+atr).addClass("selected");
jQuerREL("#countrytabs > li > a").click(function(){
jQuerREL("#countrytabs > li > a").removeClass("selected");
jQuerREL(this).addClass("selected");
});
});
</script>
<?php
}
static function showMyHouses(&$houses, &$params, &$pageNav, $option, $layout = "default") {
global $mosConfig_absolute_path, $Itemid;
//require($mosConfig_absolute_path.
// "/components/com_realestatemanager/views/my_houses/tmpl/".$layout.".php");
$type = 'my_houses';
require getLayoutPath::getLayoutPathCom('com_realestatemanager', $type, $layout);
}
static function showRentHouses($option, $house1, $rows, & $userlist, $type) {
global $my, $mosConfig_live_site, $mainframe, $doc, $Itemid, $realestatemanager_configuration;
?>
<?php
if(checkJavaScriptIncludedRE("jQuerREL-1.2.6.js") === false ) {
$doc->addScript(JURI::root(true) . '/components/com_realestatemanager/lightbox/js/jQuerREL-1.2.6.js');
}
?>
<script type="text/javascript">jQuerREL=jQuerREL.noConflict();</script>
<?php
if(checkJavaScriptIncludedRE("jQuerREL-ui.js") === false ) {
$doc->addScript(JURI::root(true) . ' echo $mosConfig_live_site; ?>/components/com_realestatemanager/includes/jQuerREL-ui.js');
}
?>
<?php
$doc->addScript($mosConfig_live_site . '/components/com_realestatemanager/includes/functions.js');
$doc->addStyleSheet($mosConfig_live_site .
'/components/com_realestatemanager/includes/realestatemanager.css');
?>
<div id="overDiv" style="position:absolute; visibility:hidden; z-index:1000;"></div>
<form action="index.php" method="get" name="adminForm" id="adminForm">
<?php
if ($type == "rent" || $type == "edit_rent") {
?>
<div class="my_real_table_rent">
<div class="my_real">
<span class="col_01"><?php echo _REALESTATE_MANAGER_LABEL_RENT_TO . ":"; ?></span>
<span class="col_02"><?php echo $userlist; ?></span>
</div>
<div class="my_real">
<span class="col_01"><?php echo _REALESTATE_MANAGER_LABEL_RENT_USER . ":"; ?></span>
<span class="col_02"><input type="text" name="user_name" class="inputbox" /></span>
</div>
<div class="my_real">
<span class="col_01"><?php echo _REALESTATE_MANAGER_LABEL_RENT_EMAIL . ":"; ?></span>
<span class="col_02"><input type="text" name="user_email" class="inputbox" /></span>
</div>
<script>
Date.prototype.toLocaleFormat = function(format) {
var f = {Y : this.getYear() + 1900,m : this.getMonth() +
1,d : this.getDate(),H : this.getHours(),M : this.getMinutes(),S : this.getSeconds()}
for(k in f)
format = format.replace('%' + k, f[k] < 10 ? "0" + f[k] : f[k]);
return format;
};
window.onload = function ()
{
var today = new Date();
var date = today.toLocaleFormat("<?php echo $realestatemanager_configuration['date_format'] ?>");
document.getElementById('rent_from').value = date;
document.getElementById('rent_until').value = date;
};
</script>
<!--///////////////////////////////calendar///////////////////////////////////////-->
<script language="javascript" type="text/javascript">
<?php
$house_id_fordate = $house1->id;
$date_NA = available_dates($house_id_fordate);
?>
var unavailableDates = Array();
jQuerREL(document).ready(function() {
//var unavailableDates = Array();
var k=0;
<?php if(!empty($date_NA)){?>
<?php foreach ($date_NA as $N_A){ ?>
unavailableDates[k]= '<?php echo $N_A; ?>';
k++;
<?php } ?>
<?php } ?>
function unavailable(date) {
dmy = date.getFullYear() + "-" + ('0'+(date.getMonth() + 1)).slice(-2) +
"-" + ('0'+date.getDate()).slice(-2);
if (jQuerREL.inArray(dmy, unavailableDates) == -1) {
return [true, ""];
} else {
return [false, "", "Unavailable"];
}
}
jQuerREL( "#rent_from, #rent_until" ).datepicker(
{
minDate: "+0",
dateFormat: "<?php echo transforDateFromPhpToJquery();?>",
beforeShowDay: unavailable,
});
});
</script>
<!--///////////////////////////////////////////////////////////////////////////-->
<div class="my_real">
<span class="col_01"><?php echo _REALESTATE_MANAGER_LABEL_RENT_FROM . ":"; ?></span>
<p><input type="text" id="rent_from" name="rent_from"></p>
</div>
<div class="my_real">
<span class="col_01"><?php echo _REALESTATE_MANAGER_LABEL_RENT_TIME; ?></span>
<p><input type="text" id="rent_until" name="rent_until"></p>
</div>
</div>
<?php } else {
echo "";
}
$all = JFactory::getDBO();
$query = "SELECT * FROM #__rem_rent";
$all->setQuery($query);
$num = $all->loadObjectList();
?>
<div class="table_63">
<div class="row_01">
<span class="col_01">
<?php if ($type != 'rent') {
?>
<input type="checkbox" name="toggle" value="" onClick="rem_checkAll(this);" />
<span class="toggle_check">check All</span>
<?php } ?>
</span>
</div>
<?php
if ($type == "rent")
{
?>
<td align="center"> <input class="inputbox" type="checkbox"
name="checkHouse" id="checkHouse" size="0" maxlength="0" value="on" /></td>
<?php
} else if ($type == "edit_rent"){ ?>
<input type="hidden" name="checkHouse" id="checkHouse" value="on" /></td>
<?php
}
$assoc_title = '';
for ($t = 0, $z = count($rows); $t < $z; $t++) {
if($rows[$t]->id != $house1->id) $assoc_title .= " ".$rows[$t]->htitle;
}
print_r("
<td align=\"center\">". $house1->id ."</td>
<td align=\"center\">" . $house1->houseid . "</td>
<td align=\"center\">" . $house1->htitle . " ( " . $assoc_title ." ) " . "</td>
</tr>");
for ($j = 0, $n = count($rows); $j < $n; $j++) {
$row = $rows[$j];
?>
<input class="inputbox" type="hidden" name="houseid" id="houseid"
size="0" maxlength="0" value="<?php echo $house1->houseid; ?>" />
<input class="inputbox" type="hidden" name="id" id="id" size="0"
maxlength="0" value="<?php echo $row->id; ?>" />
<input class="inputbox" type="hidden" name="htitle" id="htitle"
size="0" maxlength="0" value="<?php echo $row->htitle; ?>" />
<?php
$house = $row->id;
$data = JFactory::getDBO();
$query = "SELECT * FROM #__rem_rent WHERE fk_houseid=" . $house . " ORDER BY rent_return ";
$data->setQuery($query);
$allrent = $data->loadObjectList();
$num = 1;
for ($i = 0, $nn = count($allrent); $i < $nn; $i++) {
?>
<div class="box_rent_real">
<div class="row_01 row_rent_real">
<?php if (!isset($allrent[$i]->rent_return) && $type != "rent") {
?>
<span class="rent_check_vid">
<input type="checkbox" id="cb<?php echo $i; ?>"
name="bid[]" value="<?php echo $allrent[$i]->id; ?>"
onClick="isChecked(this.checked);" />
</span>
<?php } else {
?>
<?php } ?>
<span class="col_01">id</span>
<span class="col_02"><?php echo $num; ?></span>
</div>
<div class="row_02 row_rent_real">
<span class="col_01"><?php echo _REALESTATE_MANAGER_LABEL_PROPERTYID; ?></span>
<span class="col_02"><?php echo $row->houseid; ?></span>
</div>
<div class="row_03 row_rent_real">
<?php echo $row->htitle; ?>
</div>
<div class="from_until_return">
<div class="row_04 row_rent_real">
<span class="col_01"><?php echo _REALESTATE_MANAGER_LABEL_RENT_FROM; ?></span>
<span class="col_02"><?php echo data_transform_rem($allrent[$i]->rent_from); ?></span>
</div>
<br />
<div class="row_05 row_rent_real">
<span class="col_01"><?php echo _REALESTATE_MANAGER_LABEL_RENT_UNTIL; ?></span>
<span class="col_02"><?php echo data_transform_rem($allrent[$i]->rent_until); ?></span>
</div>
<br />
<div class="row_06 row_rent_real">
<span class="col_01"><?php echo _REALESTATE_MANAGER_LABEL_RENT_RETURN; ?></span>
<span class="col_02"><?php echo data_transform_rem($allrent[$i]->rent_return); ?></span>
</div>
</div>
</div>
<?php
if ($allrent[$i]->fk_userid != null)
print_r("<div class='rent_user'>" . $allrent[$i]->user_name . "</div>");
else
print_r("<div class='rent_user'>" . $allrent[$i]->user_name . $allrent[$i]->user_email . "</div>");
$num++;
}
}
?>
</div> <!-- table_63 -->
<input type="hidden" name="option" value="<?php echo $option; ?>" />
<input type="hidden" id="adminFormTaskInput" name="task" value="" />
<input type="hidden" name="save" value="1" />
<input type="hidden" name="boxchecked" value="1" />
<?php
if ($option != "com_realestatemanager") {
?>
<input type="hidden" name="is_show_data" value="1" />
<?php
}
?>
<input type="hidden" name="Itemid" value="<?php echo $Itemid; ?>" />
<?php if ($type == "rent") { ?>
<input type="button" name="rent_save" value="<?php
echo _REALESTATE_MANAGER_LABEL_BUTTON_RENT; ?>" onclick="rem_buttonClickRent(this)"/>
<?php } ?>
<?php if ($type == "rent_return") { ?>
<input type="button" name="rentout_save" value="<?php
echo _REALESTATE_MANAGER_LABEL_RENT_RETURN; ?>" onclick="rem_buttonClickRent(this)"/>
<?php } ?>
</form>
<?php
}
static function editRentHouses($option, $house1, $rows, $title_assoc, & $userlist, & $all_assosiate_rent, $type) {
global $my, $mosConfig_live_site, $mainframe, $doc, $Itemid, $realestatemanager_configuration;
?>
<?php
if(checkJavaScriptIncludedRE("jQuerREL-1.2.6.js") === false ) {
$doc->addScript(JURI::root(true) . '/components/com_realestatemanager/lightbox/js/jQuerREL-1.2.6.js');
}
?>
<script type="text/javascript">jQuerREL=jQuerREL.noConflict();</script>
<?php
if(checkJavaScriptIncludedRE("jQuerREL-ui.js") === false ) {
$doc->addScript(JURI::root(true) . '/components/com_realestatemanager/includes/jQuerREL-ui.js');
}
?>
<?php
$doc->addScript($mosConfig_live_site . '/components/com_realestatemanager/includes/functions.js');
$doc->addStyleSheet($mosConfig_live_site . '/components/com_realestatemanager/includes/realestatemanager.css');
?>
<!--///////////////////////////////calendar///////////////////////////////////////-->
<script language="javascript" type="text/javascript">
jQuerREL(document).ready(function() {
jQuerREL( "#rent_from, #rent_until" ).datepicker(
{
dateFormat: "<?php echo transforDateFromPhpToJquery();?>",
});
});
</script>
<div id="overDiv" style="position:absolute; visibility:hidden; z-index:1000;"></div>
<form action="index.php" method="post" name="adminForm" id="adminForm">
<?php
if ($type == "rent" || $type == "edit_rent") {
?>
<div class="my_real_table_rent">
<div class="my_real">
<span class="col_01"><?php echo _REALESTATE_MANAGER_LABEL_RENT_TO . ":"; ?></span>
<span class="col_02"><?php echo $userlist; ?></span>
</div>
<div class="my_real">
<span class="col_01"><?php echo _REALESTATE_MANAGER_LABEL_RENT_USER . ":"; ?></span>
<span class="col_02"><input type="text" name="user_name" class="inputbox" /></span>
</div>
<div class="my_real">
<span class="col_01"><?php echo _REALESTATE_MANAGER_LABEL_RENT_EMAIL . ":"; ?></span>
<span class="col_02"><input type="text" name="user_email" class="inputbox" /></span>
</div>
<div class="my_real">
<span class="col_01"><?php echo _REALESTATE_MANAGER_LABEL_RENT_FROM . ":"; ?></span>
<p><input type="text" id="rent_from" name="rent_from"></p>
</div>
<div class="my_real">
<span class="col_01"><?php echo _REALESTATE_MANAGER_LABEL_RENT_TIME; ?></span>
<p><input type="text" id="rent_until" name="rent_until"></p>
</div>
</div>
<!--/////////////////////////////////////////////-->
<?php } else {
echo "";
}
$all = JFactory::getDBO();
$query = "SELECT * FROM #__rem_rent ";
$all->setQuery($query);
$num = $all->loadObjectList();
?>
<div class="table_63">
<div class="row_01">
<span class="col_01">
</span>
</div>
<?php
$assoc_title = '';
for ($t = 0, $z = count($title_assoc); $t < $z; $t++) {
if($title_assoc[$t]->htitle != $house1->htitle) $assoc_title .= " ".$title_assoc[$t]->htitle;
}
//show rent history what we may change
?>
<input class="inputbox" type="hidden" name="houseid" id="houseid" size="0"
maxlength="0" value="<?php echo $house1->houseid; ?>" />
<input class="inputbox" type="hidden" name="id" id="id" size="0" maxlength="0"
value="<?php echo $house1->id; ?>" />
<input class="inputbox" type="hidden" name="id2" id="id2" size="0" maxlength="0"
value="<?php echo $house1->id; ?>" />
<?php
if ($type == "edit_rent"){ ?>
<input type="hidden" name="checkHouse" id="checkHouse" value="on" />
<?php
}
$num = 1;
for ($y = 0, $n2 = count($all_assosiate_rent[0]); $y < $n2; $y++) {
$assoc_rent_ids = '';
for ($j = 0, $n3 = count($all_assosiate_rent); $j < $n3; $j++) {
if($assoc_rent_ids != "" ) $assoc_rent_ids .= ",".$all_assosiate_rent[$j][$y]->id;
else $assoc_rent_ids = $all_assosiate_rent[$j][$y]->id;
}
?>
<div class="box_rent_real">
<div class="row_01 row_rent_real">
<span class="rent_check_vid">
<input type="checkbox" id="cb<?php echo $y; ?>" name="bid[]"
value="<?php echo $assoc_rent_ids; ?>" onClick="Joomla.isChecked(this.checked);" />
</span>
<span class="col_01">id</span>
<span class="col_02"><?php echo $num; ?></span>
</div>
<div class="row_02 row_rent_real">
<span class="col_01"><?php echo _REALESTATE_MANAGER_LABEL_PROPERTYID; ?></span>
<span class="col_02"><?php echo $house1->houseid; ?></span>
</div>
<div class="row_03 row_rent_real">
<?php echo $house1->htitle . " ( " . $assoc_title ." ) " ?>
</div>
<div class="from_until_return">
<div class="row_04 row_rent_real">
<span class="col_01"><?php echo _REALESTATE_MANAGER_LABEL_RENT_USER; ?></span>
<span class="col_02"><?php echo $all_assosiate_rent[0][$y]->user_name; ?></span>
</div>
<br />
<div class="row_04 row_rent_real">
<span class="col_01"><?php echo _REALESTATE_MANAGER_LABEL_RENT_FROM; ?></span>
<span class="col_02"><?php echo data_transform_rem($all_assosiate_rent[0][$y]->rent_from); ?></span>
</div>
<br />
<div class="row_05 row_rent_real">
<span class="col_01"><?php echo _REALESTATE_MANAGER_LABEL_RENT_UNTIL; ?></span>
<span class="col_02"><?php echo data_transform_rem($all_assosiate_rent[0][$y]->rent_until); ?></span>
</div>
<br />
<div class="row_06 row_rent_real">
<span class="col_01"><?php echo _REALESTATE_MANAGER_LABEL_RENT_RETURN; ?></span>
<span class="col_02"><?php echo data_transform_rem($all_assosiate_rent[0][$y]->rent_return); ?></span>
</div>
</div>
</div>
<?php
$num++;
}
?>
<div class="box_rent_real">
<div class="row_01 row_rent_real">---------------------------------------
</div>
</div>
<?php
//show rent history what we can't change
for ($j = 0, $n = count($rows); $j < $n; $j++) {
$row = $rows[$j];
if($row->rent_return == "" ) continue ;
$num = 1;
?>
<div class="box_rent_real">
<div class="row_01 row_rent_real">
<span class="col_01">id</span>
<span class="col_02"><?php echo $num; ?></span>
</div>
<div class="row_01 row_rent_real">
<span class="col_01"><?php echo _REALESTATE_MANAGER_LABEL_PROPERTYID; ?></span>
<span class="col_02"><?php echo $row->houseid; ?></span>
</div>
<div class="row_02 row_rent_real"><?php echo $row->htitle ; ?> </div>
<div class="from_until_return">
<div class="row_04 row_rent_real">
<span class="col_01"><?php echo _REALESTATE_MANAGER_LABEL_RENT_USER; ?></span>
<span class="col_02"><?php echo $row->user_name; ?></span>
</div>
<br />
<div class="row_04 row_rent_real">
<span class="col_01"><?php echo _REALESTATE_MANAGER_LABEL_RENT_FROM; ?></span>
<span class="col_02"><?php echo data_transform_rem($row->rent_from); ?></span>
</div>
<br />
<div class="row_05 row_rent_real">
<span class="col_01"><?php echo _REALESTATE_MANAGER_LABEL_RENT_UNTIL; ?></span>
<span class="col_02"><?php echo data_transform_rem($row->rent_until); ?></span>
</div>
<br />
<div class="row_06 row_rent_real">
<span class="col_01"><?php echo _REALESTATE_MANAGER_LABEL_RENT_RETURN; ?></span>
<span class="col_02"><?php echo data_transform_rem($row->rent_return); ?></span>
</div>
</div>
</div>
<?php } ?>
</div> <!-- table_63 -->
<input type="hidden" name="option" value="<?php echo $option; ?>" />
<input type="hidden" id="adminFormTaskInput" name="task" value="" />
<input type="hidden" name="save" value="1" />
<input type="hidden" name="boxchecked" value="1" />
<?php
if ($option != "com_realestatemanager") {
?>
<input type="hidden" name="is_show_data" value="1" />
<?php
}
?>
<input type="hidden" name="Itemid" value="<?php echo $Itemid; ?>" />
<?php if ($type == "rent" ) { ?>
<input type="button" name="rent_save" value="<?php
echo _REALESTATE_MANAGER_LABEL_BUTTON_RENT; ?>" onclick="rem_buttonClickRent(this)"/>
<?php } ?>
<?php if ($type == "edit_rent") { ?>
<input type="button" name="edit_rent" value="<?php
echo _REALESTATE_MANAGER_LABEL_BUTTON_RENT; ?>" onclick="rem_buttonClickRent(this)"/>
<input type="hidden" name="save" value="1" />
<?php } ?>
<?php if ($type == "rent_return") { ?>
<input type="button" name="rentout_save" value="<?php
echo _REALESTATE_MANAGER_LABEL_RENT_RETURN; ?>" onclick="rem_buttonClickRent(this)"/>
<?php } ?>
</form>
<?php
}
static function showRentHistory($option, $rows, $pageNav) {
global $my, $Itemid, $mosConfig_live_site, $mainframe, $doc;
$session = JFactory::getSession();
$arr = $session->get("array", "default");
$doc->addStyleSheet($mosConfig_live_site . '/components/com_realestatemanager/includes/realestatemanager.css');
?>
<form action="index.php" method="get" name="adminForm" id="adminForm">
<table id="my_houses_history" class="table_64 basictable">
<tr>
<th align = "center" width="5%">#</th>
<th align = "center" class="title" width="5%" nowrap="nowrap"><?php
echo _REALESTATE_MANAGER_LABEL_PROPERTYID; ?></th>
<th align = "center" class="title" width="25%" nowrap="nowrap"><?php
echo _REALESTATE_MANAGER_LABEL_TITLE; ?></th>
<th align = "center" class="title" width="15%" nowrap="nowrap"><?php
echo _REALESTATE_MANAGER_LABEL_RENT_FROM; ?></th>
<th align = "center" class="title" width="20%" nowrap="nowrap"><?php
echo _REALESTATE_MANAGER_LABEL_RENT_UNTIL; ?></th>
<th align = "center" class="title" width="20%" nowrap="nowrap"><?php
echo _REALESTATE_MANAGER_LABEL_RENT_RETURN; ?></th>
</tr>
<?php
$numb = 0;
for ($i = 0, $n = count($rows); $i < $n; $i++) {
$row = $rows[$i];
$house = $row->id;
$title = $row->htitle;
$numb++;
print_r("<td align=\"center\">" . $numb . "</td>
<td align=\"center\">" . $row->houseid . "</td>
<td align=\"center\">" . $row->htitle . "</td>
<td align=\"center\">" . data_transform_rem($row->rent_from) . "</td>
<td align=\"center\">" . data_transform_rem($row->rent_until) . "</td>
<td align=\"center\">" . data_transform_rem($row->rent_return) . "</td></tr>");
}
?>
</table>
<div id="pagenavig">
<?php
$paginations = $arr;
if ($paginations && ($pageNav->total > $pageNav->limit))
echo $pageNav->getPagesLinks();
?>
</div>
</form>
<?php
}
static function showRequestRentHouses($option, $rent_requests, &$pageNav) {
global $my, $mosConfig_live_site, $mainframe, $doc, $Itemid;
$session = JFactory::getSession();
$arr = $session->get("array", "default");
$doc->addScript($mosConfig_live_site .
'/components/com_realestatemanager/includes/functions.js');
$doc->addStyleSheet($mosConfig_live_site .
'/components/com_realestatemanager/includes/realestatemanager.css');
?>
<form action="index.php" method="get" name="adminForm" id="adminForm">
<table id="my_houses_rent" cellpadding="4" cellspacing="0"
border="0" width="100%" class="basictable table_65">
<tr>
<th align = "center" width="20">
<input type="checkbox" name="toggle" value="" onClick="rem_checkAll(this);" />
</th>
<th align = "center" width="30">#</th>
<th align = "center" class="title" width="10%" nowrap="nowrap">
<?php echo _REALESTATE_MANAGER_LABEL_RENT_FROM; ?></th>
<th align = "center" class="title" width="10%" nowrap="nowrap">
<?php echo _REALESTATE_MANAGER_LABEL_RENT_UNTIL; ?></th>
<th align = "center" class="title" width="5%" nowrap="nowrap">
<?php echo _REALESTATE_MANAGER_LABEL_PROPERTYID; ?></th>
<th align = "center" class="title" width="15%" nowrap="nowrap">
<?php echo _REALESTATE_MANAGER_LABEL_TITLE; ?></th>
<th align = "center" class="title" width="15%" nowrap="nowrap">
<?php echo _REALESTATE_MANAGER_LABEL_RENT_USER; ?></th>
<th align = "center" class="title" width="15%" nowrap="nowrap">
<?php echo _REALESTATE_MANAGER_LABEL_RENT_EMAIL; ?></th>
<th align = "center" class="title" width="20%" nowrap="nowrap">
<?php echo _REALESTATE_MANAGER_LABEL_RENT_ADRES; ?></th>
</tr>
<?php
for ($i = 0, $n = count($rent_requests); $i < $n; $i++) {
$row = $rent_requests[$i];
$assoc_title = '';
$assoc_title = (isset($row->title_assoc))? " ( " . $row->title_assoc ." ) " : '';
if($assoc_title){
for ($t = 0, $z = count($assoc_title); $t < $z; $t++) {
if($assoc_title[$t]->htitle != $row->htitle)
$assoc_title .= " ".$assoc_title[$t]->htitle;
}
}
?>
<tr class="row<?php echo $i % 2; ?>">
<td width="20" align="center">
<?php
echo mosHTML::idBox($i, $row->id, 0, 'bid');
?>
</td>
<td align = "center"><?php echo $row->id; ?></td>
<td align = "center">
<?php echo $row->rent_from; ?>
</td>
<td align = "center">
<?php echo $row->rent_until; ?>
</td>
<td align = "center">
<?php
$data = JFactory::getDBO();
$query = "SELECT houseid FROM #__rem_houses where id = " . $row->fk_houseid . " ";
$data->setQuery($query);
$houseid = $data->loadObjectList();
echo $houseid[0]->houseid;
?>
</td>
<td align = "center">
<?php echo $row->htitle . $assoc_title; ?>
</td>
<td align = "center">
<?php echo $row->user_name; ?>
</td>
<td align = "center">
<a href=mailto:"<?php echo $row->user_email; ?>">
<?php echo $row->user_email; ?>
</a>
</td>
<td align = "center">
<?php echo $row->user_mailing; ?>
</td>
</tr>
<?php
}
?>
</table>
<div id="pagenavig">
<?php
$paginations = $arr;
if ($paginations && ($pageNav->total > $pageNav->limit)) {
echo $pageNav->getPagesLinks();
}
?>
</div>
<input type="hidden" name="option" value="<?php echo $option; ?>" />
<?php
if ($option != "com_realestatemanager") {
?>
<input type="hidden" name="is_show_data" value="1" />
<?php
}
?>
<input type="hidden" id="adminFormTaskInput" name="task" value="" />
<input type="hidden" name="boxchecked" value="0" />
<input type="hidden" name="Itemid" value="<?php echo $Itemid; ?>" />
<input type="button" name="acceptButton" value="<?php echo _REALESTATE_MANAGER_TOOLBAR_ADMIN_ACCEPT; ?>"
onclick="rem_buttonClickRentRequest(this)"/>
<input type="button" name="declineButton" value="<?php echo _REALESTATE_MANAGER_TOOLBAR_ADMIN_DECLINE; ?>"
onclick="rem_buttonClickRentRequest(this)"/>
</form>
<?php
}
static function listCategories(&$params, $cat_all, $catid, $tabclass, $currentcat) {
global $Itemid, $mosConfig_live_site, $doc;
$doc->addStyleSheet($mosConfig_live_site .
'/components/com_realestatemanager/includes/realestatemanager.css');
?>
<?php positions_rem($params->get('allcategories04')); ?>
<div class="basictable table_58">
<div class="row_01">
<span class="col_01 sectiontableheader<?php echo $params->get('pageclass_sfx'); ?>">
<?php echo _REALESTATE_MANAGER_LABEL_CATEGORY; ?>
</span>
<?php if ($params->get('rss_show')): ?>
<span class=" col_03 sectiontableheader">
<a href="<?php echo
sefRelToAbs("index.php?option=com_realestatemanager&task=show_rss_categories&Itemid="
. $Itemid); ?>">
<img src="./components/com_realestatemanager/images/rss.png"
alt="All categories RSS" align="right" title="All categories RSS"/>
</a>
</span>
<?php endif; ?>
<span class="col_02 sectiontableheader<?php echo $params->get('pageclass_sfx'); ?>">
<?php echo _REALESTATE_MANAGER_LABEL_HOUSES; ?>
</span>
</div>
<br/>
<div class="row_02">
<?php positions_rem($params->get('allcategories05')); ?>
<?php HTML_realestatemanager::showInsertSubCategory($catid, $cat_all, $params, $tabclass, $Itemid, 0); ?>
</div>
</div>
<?php positions_rem($params->get('allcategories06')); ?>
<?php
}
/* function for show subcategory */
static function showInsertSubCategory($id, $cat_all, $params, $tabclass, $Itemid, $deep) {
global $g_item_count, $realestatemanager_configuration, $mosConfig_live_site;
global $doc;
$doc->addStyleSheet($mosConfig_live_site .
'/components/com_realestatemanager/includes/realestatemanager.css');
$deep++;
for ($i = 0; $i < count($cat_all); $i++) {
if (($id == $cat_all[$i]->parent_id) && ($cat_all[$i]->display == 1)) {
$g_item_count++;
$link = 'index.php?option=com_realestatemanager&task=showCategory&catid='
. $cat_all[$i]->id . '&Itemid=' . $Itemid;
?>
<div class="table_59 <?php echo $tabclass[($g_item_count % 2)]; ?>">
<span class="col_01">
<?php
if ($deep != 1) {
$jj = $deep;
while ($jj--) {
echo " ";
}
echo " |_";
}
?>
</span>
<span class="col_01">
<?php if (($params->get('show_cat_pic')) && ($cat_all[$i]->image != "")) { ?>
<img src="./images/stories/<?php echo $cat_all[$i]->image; ?>"
alt="picture for subcategory" height="48" width="48" />
<?php } else {
?>
<a <?php echo "href=" . sefRelToAbs($link); ?> class="category<?php
echo $params->get('pageclass_sfx'); ?>" style="text-decoration: none"><img
src="./components/com_realestatemanager/images/folder.png"
alt="picture for subcategory" height="48" width="48" /></a>
<?php } ?>
</span>
<span class="col_02">
<a href="<?php echo sefRelToAbs($link); ?>"
class="category<?php echo $params->get('pageclass_sfx'); ?>">
<?php echo $cat_all[$i]->title; ?>
</a>
</span>
<span class="col_03">
<?php if ($cat_all[$i]->houses == '') echo "0";else echo $cat_all[$i]->houses; ?>
</span>
<?php if ($params->get('rss_show')): ?>
<span class="col_04">
<a href="<?php echo
sefRelToAbs("index.php?option=com_realestatemanager&task=show_rss_categories&catid="
. $cat_all[$i]->id . "&Itemid=" . $Itemid); ?>">
<img src="./components/com_realestatemanager/images/rss2.png"
alt="Category RSS" align="right" title="Category RSS"/>
</a>
</span>
<?php endif; ?>
</div>
<?php
if ($realestatemanager_configuration['subcategory']['show'])
HTML_realestatemanager::showInsertSubCategory($cat_all[$i]->id,
$cat_all, $params, $tabclass, $Itemid, $deep);
}//end if ($id == $cat_all[$i]->parent_id)
}//end for(...)
}
static function showRequestBuyingHouses($option, $buy_requests, $pageNav, $Itemid) {
global $my, $mosConfig_live_site, $mainframe, $doc;
$session = JFactory::getSession();
$arr = $session->get("array", "default");
$doc->addScript($mosConfig_live_site . '/components/com_realestatemanager/includes/functions.js');
$doc->addStyleSheet($mosConfig_live_site .
'/components/com_realestatemanager/includes/realestatemanager.css');
?>
<form action="index.php" method="get" name="adminForm" id="adminForm">
<table id="my_houses_buy" cellpadding="4" cellspacing="0" border="0"
width="100%" class="basictable table_66">
<tr>
<th align = "center" width="5%"><input type="checkbox" name="toggle"
value="" onClick="rem_checkAll(this);" /></th>
<th align = "center" width="5%">#</th>
<th align = "center" class="title" width="10%" nowrap="nowrap"><?php
echo _REALESTATE_MANAGER_LABEL_PROPERTYID; ?></th>
<th align = "center" class="title" width="15%" nowrap="nowrap"><?php
echo _REALESTATE_MANAGER_LABEL_ADDRESS; ?></th>
<th align = "center" class="title" width="15%" nowrap="nowrap"><?php
echo _REALESTATE_MANAGER_LABEL_RENT_USER; ?></th>
<th align = "center" class="title" width="20%" nowrap="nowrap"><?php
echo _REALESTATE_MANAGER_LABEL_COMMENT; ?></th>
<th align = "center" class="title" width="15%" nowrap="nowrap"><?php
echo _REALESTATE_MANAGER_LABEL_RENT_EMAIL; ?></th>
<th align = "center" class="title" width="15%" nowrap="nowrap"><?php
echo _REALESTATE_MANAGER_LABEL_BUYING_ADRES; ?></th>
</tr>
<?php
for ($i = 0, $n = count($buy_requests); $i < $n; $i++) {
$row = $buy_requests[$i];
?>
<tr class="row<?php echo $i % 2; ?>">
<td width="20">
<div align = "center">
<?php echo mosHTML::idBox($i, $row->id, 0, 'bid'); ?>
</div>
</td>
<td align = "center"><?php echo $row->id; ?></td>
<td align = "center"><?php echo $row->fk_houseid; ?></td>
<td align = "center"><?php echo $row->hlocation; ?></td>
<td align = "center"><?php echo $row->customer_name; ?></td>
<td align = "center" width="20%"><?php echo $row->customer_comment; ?></td>
<td align = "center">
<a href=mailto:"<?php echo $row->customer_email; ?>">
<?php echo $row->customer_email; ?>
</a>
</td>
<td align = "center"><?php echo $row->customer_phone; ?></td>
</tr>
<?php } ?>
</table>
<div id="pagenavig">
<?php
$paginations = $arr;
if ($paginations && ($pageNav->total > $pageNav->limit)) {
echo $pageNav->getPagesLinks();
}
?>
</div>
<input type="hidden" name="option" value="<?php echo $option; ?>" />
<?php
if ($option != "com_realestatemanager") {
?>
<input type="hidden" name="is_show_data" value="1" />
<?php
}
?>
<input type="hidden" id="adminFormTaskInput" name="task" value="" />
<input type="hidden" name="boxchecked" value="0" />
<input type="hidden" name="Itemid" value="<?php echo $Itemid; ?>" />
<input type="button" name="acceptButton" value="<?php echo _REALESTATE_MANAGER_TOOLBAR_ADMIN_ACCEPT; ?>"
onclick="rem_buttonClickBuyRequest(this)"/>
<input type="button" name="declineButton" value="<?php echo _REALESTATE_MANAGER_TOOLBAR_ADMIN_DECLINE; ?>"
onclick="rem_buttonClickBuyRequest(this)"/>
</form>
<?php
}
static function add_google_map(&$rows) {
global $realestatemanager_configuration, $doc, $mosConfig_live_site, $database, $Itemid;
$api_key = $realestatemanager_configuration['api_key'] ? "key=" . $realestatemanager_configuration['api_key'] : JFactory::getApplication()->enqueueMessage("<a target='_blank' href='//developers.google.com/maps/documentation/geocoding/get-api-key'>" . _REALESTATE_MANAGER_GOOGLEMAP_API_KEY_LINK_MESSAGE . "</a>", _REALESTATE_MANAGER_GOOGLEMAP_API_KEY_ERROR);
$doc->addScript("//maps.googleapis.com/maps/api/js?$api_key"); ?>
<script type="text/javascript">
window.addEvent('domready', function() {
initialize2();
});
function initialize2(){
var map;
var marker = new Array();
var myOptions = {
scrollwheel: false,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.LARGE
},
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var imgCatalogPath = "<?php echo $mosConfig_live_site; ?>/components/com_realestatemanager/";
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var bounds = new google.maps.LatLngBounds ();
<?php
$newArr = explode(",", _REALESTATE_MANAGER_HOUSE_MARKER);
$j = 0;
for ($i = 0;$i < count($rows);$i++) {
if ($rows[$i]->hlatitude && $rows[$i]->hlongitude) {
$numPick = '';
if (isset($newArr[$rows[$i]->property_type])) {
$numPick = $newArr[$rows[$i]->property_type];
}
?>
var srcForPic = "<?php echo $numPick; ?>";
var image = '';
if(srcForPic.length){
var image = new google.maps.MarkerImage(imgCatalogPath + srcForPic,
new google.maps.Size(32, 32),
new google.maps.Point(0,0),
new google.maps.Point(16, 32));
}
marker.push(new google.maps.Marker({
icon: image,
position: new google.maps.LatLng(<?php echo $rows[$i]->hlatitude; ?>,
<?php echo $rows[$i]->hlongitude; ?>),
map: map,
title: "<?php echo $database->Quote($rows[$i]->htitle); ?>"
}));
bounds.extend(new google.maps.LatLng(<?php echo $rows[$i]->hlatitude; ?>,
<?php echo $rows[$i]->hlongitude; ?>));
var infowindow = new google.maps.InfoWindow({});
google.maps.event.addListener(marker[<?php echo $j; ?>], 'mouseover',
function() {
<?php
if (strlen($rows[$i]->htitle) > 45)
$htitle = mb_substr($rows[$i]->htitle, 0, 25) . '...';
else {
$htitle = $rows[$i]->htitle;
}
?>
var title = "<?php echo $htitle ?>";
<?php
//for local images
$imageURL = ($rows[$i]->image_link);
if ($imageURL == '') $imageURL = _REALESTATE_MANAGER_NO_PICTURE_BIG;
$file_name = rem_picture_thumbnail($imageURL,
$realestatemanager_configuration['fotogal']['width'],
$realestatemanager_configuration['fotogal']['high']);
$file = $mosConfig_live_site . '/components/com_realestatemanager/photos/' . $file_name;
?>
var imgUrl = "<?php echo $file; ?>";
var price = "<?php echo $rows[$i]->price; ?>";
var priceunit = "<?php echo $rows[$i]->priceunit; ?>";
var contentStr = '<div>'+
'<a onclick=window.open("<?php echo JRoute::_("index.php?option=com_realestatemanager&task=view&id={$rows[$i]->id}&catid={$rows[$i]->idcat}&Itemid={$Itemid}");?>") >'+
'<img width = "100%" src = "'+imgUrl+'">'+
'</a>' +
'</div>'+
'<div id="marker_link">'+
'<a onclick=window.open("<?php echo JRoute::_("index.php?option=com_realestatemanager&task=view&id={$rows[$i]->id}&catid={$rows[$i]->idcat}&Itemid={$Itemid}");?>") >' + title + '</a>'+
'</div>'+
'<div id="marker_price">'+
'<a onclick=window.open("<?php echo JRoute::_("index.php?option=com_realestatemanager&task=view&id={$rows[$i]->id}&catid={$rows[$i]->idcat}&Itemid={$Itemid}");?>") >' + price +' ' + priceunit + '</a>'+
'</div>';
infowindow.setContent(contentStr);
infowindow.open(map,marker[<?php echo $j; ?>]);
});
var myLatlng = new google.maps.LatLng(<?php echo $rows[$i]->hlatitude;
?>,<?php echo $rows[$i]->hlongitude; ?>);
var myZoom = <?php echo $rows[$i]->map_zoom; ?>;
<?php
$j++;
}
}
?>
if (<?php echo $j; ?>>1) map.fitBounds(bounds);
else if (<?php echo $j; ?>==1) {map.setCenter(myLatlng);map.setZoom(myZoom)}
else {map.setCenter(new google.maps.LatLng(0,0));map.setZoom(0);}
}
</script>
<?php
}
}
//class html
<file_sep><?php
if (!defined('_VALID_MOS') && !defined('_JEXEC'))
die('Direct Access to ' . basename(__FILE__) . ' is not allowed.');
/**
*
* @package RealEstateManager
* @copyright 2012 <NAME>-OrdaSoft(<EMAIL>); <NAME>(<EMAIL>)
* Homepage: http://www.ordasoft.com
* @version: 3.0 Pro
*
*
*/
class mosRealEstateManager_rent_request extends JTable {
/** @var int Primary key */
var $id = null;
/** @var int - the house id this rent is assosiated with */
var $fk_houseid = null;
/** @var datetime - since when this house is rent out */
var $rent_from = null;
/** @var datetime - when the house should be returned */
var $rent_until = null;
/** @var datetime - when the house realy was/is returned */
var $rent_request = null;
/** @var boolean */
var $checked_out = null;
/** @var time */
var $checked_out_time = null;
/** @var string - the user who rent this house */
var $user_name = null;
/** @var string – the email of the user who rent this house */
var $user_email = null;
/** @var string – the mail address of the user who rent this house */
var $user_mailing = null;
/** @var string – the e-mail address of the user who rent this house if it's no user of the database */
var $status = 0;
var $fk_userid = null;
/**
* @param database - A database connector object
*/
function __construct(&$db) {
parent::__construct('#__rem_rent_request', 'id', $db);
}
// overloaded check function
function check() {
// check if house is already rent out
$this->_db->setQuery("SELECT fk_rentid FROM #__rem_houses " . "\nWHERE id='$this->fk_houseid' AND fk_rentid = null");
$xid = intval($this->_db->loadResult());
if ($xid) {
$this->_error = _HOUSE_RENT_OUT;
return false;
}
return true;
}
/**
* @return array – name: the string of the user the house is rent to - e-mail: the e-mail address of the user
*/
function getRentTo() {
$retVal['name'] = null;
$retVal['email'] = null;
if ($this->fk_userid != null && $this->fk_userid != 0) {
$this->_db->setQuery("SELECT name, email from #__users where id=$this->fk_userid");
$help = $this->_db->loadRow();
$retVal['name'] = $help[0];
$retVal['email'] = $help[1];
} else {
$retVal['name'] = $user_name;
$retVal['email'] = $user_email;
}
return $retVal;
}
//status codes
//0: just inserted
//1: accepted
//2: not accepted
function accept() {
global $database, $my, $realestatemanager_configuration;
if ($this->id == null) {
return "Method called on a non instant object";
}
$this->checkout($my->id);
//create new rent dataset
// print_r($house);exit;
//$house->load($this->fk_userid);
//print_r($this);exit;
//print_r($houseid);exit;
$data = JFactory::getDBO();
$query = "SELECT fk_houseid FROM #__rem_rent_request where fk_houseid = " . $this->fk_houseid;
$data->setQuery($query);
$h_assoc = $data->loadResult();
if($assoc_rem = getAssociateHouses($h_assoc)){
$assoc_rem = getAssociateHouses($h_assoc);
$assoc_rem = explode(',', $assoc_rem);
}else{
$assoc_rem = explode(',', $h_assoc);
}
for($i = 0, $n = count($assoc_rem); $i < $n; $i++){
$rent = new mosRealEstateManager_rent($database);
$house = new mosRealEstateManager($database);
//$house->checkout($my->id);
$house->load($assoc_rem[$i]);
$query = "SELECT * FROM #__rem_rent where fk_houseid = " . $assoc_rem[$i] . " AND rent_return IS NULL ";
$data->setQuery($query);
$rentTerm = $data->loadObjectList();
$rent_from = substr($this->rent_from, 0, 10);
$rent_until = substr($this->rent_until, 0, 10);
foreach ($rentTerm as $oneTerm){
$oneTerm->rent_from = substr($oneTerm->rent_from, 0, 10);
$oneTerm->rent_until = substr($oneTerm->rent_until, 0, 10);
$returnMessage = checkRentDayNightREM (($oneTerm->rent_from),($oneTerm->rent_until), $rent_from, $rent_until, $realestatemanager_configuration);
if($assoc_rem[$i] !== $oneTerm->id && strlen($returnMessage) > 0){
echo "<script> alert('$returnMessage'); window.history.go(-1); </script>\n";
exit;
}
}
$rent->rent_from = $this->rent_from;
$rent->fk_houseid = $assoc_rem[$i];
$rent->rent_until = $this->rent_until;
$rent->user_name = $this->user_name;
$rent->user_email = $this->user_email;
$rent->user_mailing = $this->user_mailing;
$rent->fk_userid = $this->fk_userid;
//$rent->rent_from = date("Y-m-d H:i:s");
$rent->rent_until = $this->rent_until;
if (!$rent->check($rent)) {
return $rent->getError();
}
if (!$rent->store()) {
return $rent->getError();
}
$rent->checkin();
//update house with rent id
$house->fk_rentid = $rent->id;
if (!$house->store()) {
return $house->getError();
}
//$house->checkin();
$this->status = 1;
if (!$this->store()) {
return $this->getError();
}
$house->checkin();
}
return null;
}
function decline() {
if ($this->id == null) {
return "Method called on a non instant object";
}
$this->status = 2;
if (!$this->store()) {
return $this->getError();
}
return null;
}
function toXML3($xmlDoc) {
//create and append name element
$retVal = $xmlDoc->createElement("rentrequest");
$fk_userid = $xmlDoc->createElement("fk_userid");
$fk_userid->appendChild($xmlDoc->createTextNode($this->fk_userid));
$retVal->appendChild($fk_userid);
$rent_from = $xmlDoc->createElement("rent_from");
$rent_from->appendChild($xmlDoc->createTextNode($this->rent_from));
$retVal->appendChild($rent_from);
$rent_until = $xmlDoc->createElement("rent_until");
$rent_until->appendChild($xmlDoc->createTextNode($this->rent_until));
$retVal->appendChild($rent_until);
$rent_request = $xmlDoc->createElement("rent_retquest");
$rent_request->appendChild($xmlDoc->createTextNode($this->rent_request));
$retVal->appendChild($rent_request);
$user_name = $xmlDoc->createElement("user_name");
$user_name->appendChild($xmlDoc->createTextNode($this->user_name));
$retVal->appendChild($user_name);
$user_email = $xmlDoc->createElement("user_email");
$user_email->appendChild($xmlDoc->createTextNode($this->user_email));
$retVal->appendChild($user_email);
$user_mailing = $xmlDoc->createElement("user_mailing");
$user_mailing->appendChild($xmlDoc->createTextNode($this->user_mailing));
$retVal->appendChild($user_mailing);
$status = $xmlDoc->createElement("status");
$status->appendChild($xmlDoc->createTextNode($this->status));
$retVal->appendChild($status);
return $retVal;
}
function toXML2() {
$retVal = "<rentrequest>\n";
$retVal.= "<fk_userid>" . $this->fk_userid . "</fk_userid>\n";
$retVal.= "<rent_from>" . $this->rent_from . "</rent_from>\n";
$retVal.= "<rent_until>" . $this->rent_until . "</rent_until>\n";
$retVal.= "<rent_request>" . $this->rent_request . "</rent_request>\n";
$retVal.= "<user_name>" . $this->user_name . "</user_name>\n";
$retVal.= "<user_email>" . $this->user_email . "</user_email>\n";
$retVal.= "<user_mailing><![CDATA[" . $this->user_mailing . "]]></user_mailing>\n";
$retVal.= "<status>" . $this->status . "</status>\n";
$retVal.= "</rentrequest>\n";
return $retVal;
}
}
|
8f7531b92e6368271a5d995124eba4b6f5920803
|
[
"PHP"
] | 5
|
PHP
|
Sebastien-Skorweb/com_realestatemanager
|
7442cea146a02410835a2aaab0fd3b175a277110
|
1cfe8015ef0a638a3f74a97177f0905b2413ace2
|
refs/heads/master
|
<file_sep>package edu.brilleslange.bl;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.regex.*;
public class Record implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
public String title;
public String author;
public String placement = "";
}
class PlacementO {
public ArrayList<String> placements = new ArrayList<String>();
public String placement = "";
boolean testValue(){
for(String s : placements){
placement+= " - " + s;
}
return Pattern.matches(".*UREAL.*", placement);
}
}
<file_sep>package edu.brilleslange.activities;
import edu.brilleslange.R;
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;
public class ArticleOfTheWeekActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.articleoftheweek);
WebView webview = (WebView) findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true);
String pdf = "http://www.adobe.com/devnet/acrobat/pdfs/pdf_open_parameters.pdf";
webview.loadUrl("http://docs.google.com/gview?embedded=true&url=" + pdf);
}
}
<file_sep>package edu.brilleslange.bl;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
public class MyXMLHandler extends DefaultHandler {
Boolean currentElement = false;
String currentValue = null;
boolean impElement = false;
boolean titleElement = false;
boolean placementElement = false;
boolean authorElement = false;
public static Records records = null;
Record currentRecord;
PlacementO currentPO = null;
public static Records getRecord() {
return records;
}
public static void setRecord(Records record) {
MyXMLHandler.records = record;
}
@Override
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
currentElement = true;
if(localName.equals("records") && uri.equals("http://www.loc.gov/zing/srw/")){
records = new Records();
}
if (localName.equals("record") && uri.equals("info:lc/xmlns/marcxchange-v1"))
{
currentRecord=new Record();
}
else if (localName.equals("datafield") && uri.equals("info:lc/xmlns/marcxchange-v1")) {
if(attributes.getValue("tag").compareTo("245")==0){
impElement=true;
}
else if(attributes.getValue("tag").compareTo("852")==0){
placementElement=true;
currentPO = new PlacementO();
}
}
else if (localName.equals("subfield") && uri.equals("info:lc/xmlns/marcxchange-v1")) {
if(attributes.getValue("code").compareTo("a")==0){
titleElement=true;
}
else if(attributes.getValue("code").compareTo("c")==0){
authorElement=true;
}
}
}
@Override
public void endElement(String uri, String localName, String qName)
throws SAXException {
currentElement = false;
if (localName.equals("record") && uri.equals("info:lc/xmlns/marcxchange-v1"))
{
if(currentRecord.title!=null)
records.addRecord(currentRecord);
}
/** set value */
if (impElement==true)
{
if(localName.equals("subfield") && uri.equals("info:lc/xmlns/marcxchange-v1")){
if(authorElement==true){
currentRecord.author=currentValue;
authorElement=false;
}
else if(titleElement==true){
currentRecord.title=currentValue;
titleElement=false;
}
}
if(localName.equals("datafield") && uri.equals("info:lc/xmlns/marcxchange-v1")){
impElement=false;
}
}
else if (placementElement==true)
{
if(localName.equals("subfield") && uri.equals("info:lc/xmlns/marcxchange-v1")){
currentPO.placements.add(currentValue);
/* if(currentRecord.placement!=null){
currentRecord.placement=currentRecord.placement+" " + currentValue + "\n";
}
else{
currentRecord.placement=currentValue;
}*/
}
if(localName.equals("datafield") && uri.equals("info:lc/xmlns/marcxchange-v1")){
placementElement=false;
if(currentPO.testValue()){
currentRecord.placement+=currentPO.placement + "\n\n";
}
}
}
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if (currentElement) {
currentValue = new String(ch, start, length);
currentElement = false;
}
}
}
<file_sep>package edu.brilleslange.activities;
import java.io.IOException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import edu.brilleslange.R;
import android.app.Activity;
import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
public class TwitterActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.twitter);
ListView lv = (ListView)findViewById(R.id.twitterlist);
lv.setAdapter(new ArrayAdapter<String>(this, R.layout.list_item, getTweets()));
lv.setTextFilterEnabled(true);
}
private String[] getTweets(){
HttpClient httpclient = new DefaultHttpClient();
String[] tweets = null;
try {
HttpGet httpget = new HttpGet("http://search.twitter.com/search.json?q=rfbibliotek&result_type=mixed&count=5");
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httpget, responseHandler);
JSONArray json = new JSONArray(new JSONObject(responseBody).getString("results"));
tweets = new String[json.length()];
for(int i = 0;i<json.length();i++){
JSONObject t = json.getJSONObject(i);
tweets[i] = t.getString("from_user") + ": " + t.getString("text");
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
httpclient.getConnectionManager().shutdown();
}
return tweets;
}
}
<file_sep>package edu.brilleslange.activities;
import java.util.List;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
import edu.brilleslange.R;
import edu.brilleslange.activities.MyLocation.LocationResult;
import edu.brilleslange.adapters.LaztAdapter;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;
public class FrontPageActivity extends MapActivity {
ListView list;
LaztAdapter adapt;
MapView map;
MapController controller;
MyLocationOverlay myLocationOverlay;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.frontpage);
map = (MapView) findViewById(R.id.mapview);
//Location:
myLocationOverlay = new MyLocationOverlay(this, map);
map.getOverlays().add(myLocationOverlay);
myLocationOverlay.enableMyLocation();
list = (ListView)findViewById(R.id.list);
adapt = new LaztAdapter(this);
list.setAdapter(adapt);
controller = map.getController();
controller.animateTo(new GeoPoint(59940127, 10723279));
controller.setZoom(14);
// Overlays:
List<Overlay> mapOverlays = map.getOverlays();
Drawable bib2Icon = this.getResources().getDrawable(R.drawable.maps2);
Drawable bib1Icon = this.getResources().getDrawable(R.drawable.maps1);
MyOverlay bib2Overlay = new MyOverlay(bib2Icon, this);
MyOverlay bib1Overlay = new MyOverlay(bib1Icon, this);
GeoPoint ojd = new GeoPoint(59944078, 10719089);
GeoPoint vbh = new GeoPoint(59940127, 10723279);
OverlayItem ojdItem = new OverlayItem(ojd, "<NAME>", "Gaustadalléen 23\n0373 Oslo, Norge");
OverlayItem vbhItem = new OverlayItem(vbh, "<NAME>", "<NAME>i 35\n0851 Oslo, Norge");
bib2Overlay.addOverlay(ojdItem);
bib1Overlay.addOverlay(vbhItem);
mapOverlays.add(bib2Overlay);
mapOverlays.add(bib1Overlay);
mapOverlays.add(myLocationOverlay);
final Class[] activitados = {
SearchScreenActivity.class,
BookALibrarianActivity.class,
ArticleOfTheWeekActivity.class,
FacebookActivity.class,
//BuildingPlanActivity.class,
TwitterActivity.class
};
list.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
Intent myIntent = new Intent(v.getContext(), activitados[position]);
startActivityForResult(myIntent, 0);
}
});
}
@Override
protected void onPause() {
super.onPause();
myLocationOverlay.disableMyLocation();
}
@Override
protected void onResume() {
super.onResume();
myLocationOverlay.enableMyLocation();
}
@Override //Denne m v¾re med nr aktiviteten viser et kart
protected boolean isRouteDisplayed() {
return false;
}
}
<file_sep>package edu.brilleslange.adapters;
import java.util.ArrayList;
import edu.brilleslange.R;
import android.app.Activity;
import android.content.Context;
import edu.brilleslange.bl.*;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class SearchResultsAdapter extends BaseAdapter {
private Activity activity;
private static LayoutInflater inflater=null;
private ArrayList<Record> data;
public SearchResultsAdapter(Activity a, ArrayList<Record> data) {
activity = a;
this.data = data;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.searchresultsitem, null);
TextView text=(TextView)vi.findViewById(R.id.searchresultitemtext);
text.setText(data.get(position).title);
return vi;
}
}
<file_sep>package edu.brilleslange.activities;
import edu.brilleslange.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageButton;
import android.widget.EditText;
public class BookALibrarianActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bookalibrarian);
ImageButton b = (ImageButton)findViewById(R.id.bookbutton);
EditText editTextUsername = (EditText)findViewById(R.id.bookALibrarianUsername);
InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(editTextUsername.getWindowToken(), 0);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
EditText editTextUsername = (EditText)findViewById(R.id.bookALibrarianUsername);
String username = editTextUsername.getText().toString();
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.setType("plain/text");
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{"<EMAIL>"});
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Testmail");
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Brukernavn: " + username);
startActivity(Intent.createChooser(emailIntent, "Send mail..."));
}
});
}
}
<file_sep>package edu.brilleslange.activities;
import edu.brilleslange.R;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class FacebookActivity extends Activity {
WebView mWebView;
String url = "http://m.facebook.com/pages/Det-nye-realfagsbiblioteket-i-Vilhelm-Bjerknes-hus/114911458561913";
ProgressBar fProgress;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.facebook);
fProgress = (ProgressBar) findViewById(R.id.fprogressbar);
mWebView = (WebView) findViewById(R.id.webview);
mWebView.setVisibility(View.INVISIBLE);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.loadUrl(url);
mWebView.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
fProgress.setVisibility(View.GONE);
mWebView.setVisibility(View.VISIBLE);
}
});
}
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
fProgress.setVisibility(View.GONE);
}};
}<file_sep>package edu.brilleslange.activities;
import java.util.ArrayList;
import edu.brilleslange.R;
import edu.brilleslange.adapters.LaztAdapter;
import edu.brilleslange.adapters.SearchResultsAdapter;
import edu.brilleslange.bl.BibsysBridge;
import edu.brilleslange.bl.Record;
import android.app.Activity;
import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class BookResultActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bookresult);
Bundle extras = getIntent().getExtras();
Record r = null;
if(extras !=null) {
r = (Record) getIntent().getSerializableExtra("Record");
}
TextView title = (TextView)findViewById(R.id.bookresulttitletext);
TextView author = (TextView)findViewById(R.id.bookresultauthortext);
TextView placement = (TextView)findViewById(R.id.bookresultplacementtext);
title.setText(r.title);
author.setText(r.author);
placement.setText(r.placement);
}
}
|
bb7bc7d4b981c3edbb45fca11fc110dcedb8e36b
|
[
"Java"
] | 9
|
Java
|
alexkempton/BrilleslangeApp
|
5ee5f1a5605a46ab39f1f531187d109550c82184
|
75e9bebd66c5fe30321fe9d1c5d16a8d1956d6bb
|
refs/heads/master
|
<file_sep>use bytes::Bytes;
use futures::stream::Stream;
use std::future::Future;
use std::pin::Pin;
use tokio::sync::mpsc;
mod common;
#[cfg(test)]
pub mod stream_connection;
pub mod tokio_connection;
pub type DataStream = Box<dyn Stream<Item = Bytes> + Unpin + Send>;
type Task = Pin<Box<dyn Future<Output = ()> + Send>>;
pub type NewConnection = Box<dyn FnOnce(mpsc::Sender<Message>, DataStream) -> Task + Send>;
pub enum Message {
Data(Bytes),
NewConnection(NewConnection),
}
<file_sep>use bytes::Bytes;
use futures::stream::StreamExt;
use std::marker::Unpin;
use tokio::{
io::{self, AsyncRead, AsyncWrite},
join,
sync::mpsc,
};
use tokio_stream::Stream;
use tokio_util::codec::{BytesCodec, FramedRead, FramedWrite};
use tracing::{debug, error};
use super::common::{stream_to_sender, stream_to_sink};
use super::{DataStream, Message, NewConnection};
// TODO: is it possible to replace this closure with a method call on a struct like the
// coordinator.run method? (May need to use async-trait)
pub fn new_tokio_connection<R, W>(read_socket: R, write_socket: W) -> NewConnection
where
R: AsyncRead + Unpin + Send + 'static,
W: AsyncWrite + Unpin + Send + 'static,
{
debug!("new_tokio_connection");
Box::new(move |sender: mpsc::Sender<Message>, receiver: DataStream| {
Box::pin(tokio_connection(
sender,
receiver,
read_socket,
write_socket,
))
})
}
pub fn new_spawner_connection<S, SS>(spawner: S) -> NewConnection
where
S: Stream<Item = Result<SS, std::io::Error>> + Unpin + Send + 'static,
SS: AsyncRead + AsyncWrite + Unpin + Send + 'static,
{
Box::new(move |sender: mpsc::Sender<Message>, receiver: DataStream| {
Box::pin(spawner_connection(sender, receiver, spawner))
})
}
async fn spawner_connection<S, SS>(
sender: mpsc::Sender<Message>,
_receiver: DataStream,
mut spawner: S,
) where
S: Stream<Item = Result<SS, std::io::Error>> + Unpin + Send + 'static,
SS: AsyncRead + AsyncWrite + Unpin + Send + 'static,
{
while let Some(stream) = spawner.next().await {
match stream {
Ok(stream) => {
let (read, write) = io::split(stream);
let connection = new_tokio_connection(read, write);
if let Err(err) = sender.send(Message::NewConnection(connection)).await {
error!("Queue error: {}", err);
break;
}
}
Err(err) => {
error!("Spawner error: {}", err);
}
}
}
}
async fn tokio_connection<S, R, W>(
sender: mpsc::Sender<Message>,
receiver: S,
read_socket: R,
write_socket: W,
) where
S: Stream<Item = Bytes> + Unpin,
R: AsyncRead + Unpin,
W: AsyncWrite + Unpin,
{
debug!("setting up tokio_connection");
let socket_in = Box::pin(FramedRead::new(read_socket, BytesCodec::new()).filter_map(
|item: Result<bytes::BytesMut, std::io::Error>| async {
match item {
Ok(bytes_mut) => Some(Message::Data(bytes_mut.freeze())),
Err(err) => {
error!("Read error: {}", err);
None
}
}
},
));
let socket_out = FramedWrite::new(write_socket, BytesCodec::new());
let input_fut = stream_to_sender(socket_in, sender);
let output_fut = stream_to_sink(receiver, socket_out);
join!(input_fut, output_fut);
}
pub mod new {
use anyhow::Result;
use tokio::io::{self, AsyncRead, AsyncWrite, DuplexStream};
pub struct TokioConnection<R, W>
where
R: AsyncRead + Unpin,
W: AsyncWrite + Unpin,
{
reader: R,
writer: W,
stream: DuplexStream,
}
pub struct ConnectionData {
stream: DuplexStream,
}
impl<R, W> TokioConnection<R, W>
where
R: AsyncRead + Unpin,
W: AsyncWrite + Unpin,
{
pub fn new(reader: R, writer: W) -> (Self, ConnectionData) {
let (connection_end, coordinator_end) = io::duplex(4096);
(
Self {
reader,
writer,
stream: connection_end,
},
ConnectionData {
stream: coordinator_end,
},
)
}
pub async fn run(mut self) -> Result<()> {
let (mut readstream, mut writestream) = io::split(self.stream);
let _ = tokio::try_join! {
io::copy(&mut self.reader, &mut writestream),
io::copy(&mut readstream, &mut self.writer),
}?;
Ok(())
}
}
}
<file_sep>[package]
name = "nettap"
version = "0.1.0"
authors = ["<NAME> <<EMAIL>>"]
edition = "2018"
[dependencies]
anyhow = "1.0.28"
async-stream = "0.3.0"
bytes = "1.0.1"
futures = "0.3.0"
log = "0.4.8"
structopt = "0.2.18"
tokio = { version = "1.1.0", features = ["full"] }
tokio-stream = { version = "0.1.2", features = ["net"] }
tokio-test = "0.2.1"
tokio-util = { version = "0.6.2", features = ["codec"] }
tracing = "0.1.21"
tracing-subscriber = "0.2.13"
uuid = { version = "0.8.1", features = ["v4"] }
<file_sep>use bytes::Bytes;
use futures::{future::FutureExt, sink::Sink, stream::Stream};
use tokio::sync::mpsc;
use super::common::{stream_to_sender, stream_to_sink};
use super::{DataStream, Message, NewConnection};
/// Creates a Connection from a Stream of Message and a Sink of Bytes
pub fn new<R, W>(read_stream: R, write_sink: W) -> NewConnection
where
R: Stream<Item = Message> + Unpin + Send + 'static,
W: Sink<Bytes> + Unpin + Send + 'static,
<W as Sink<Bytes>>::Error: std::fmt::Display,
{
Box::new(move |sender: mpsc::Sender<Message>, receiver: DataStream| {
Box::pin(
futures::future::join(
stream_to_sender(read_stream, sender),
stream_to_sink(receiver, write_sink),
)
.map(|_| ()),
)
})
}
<file_sep>use anyhow::{bail, Result};
use std::net::{SocketAddr, ToSocketAddrs};
use structopt::StructOpt;
use tokio::{
io,
net::{TcpListener, TcpStream},
};
use tokio_stream::wrappers::TcpListenerStream;
use tracing::debug;
mod broadcast_stream;
mod connection;
mod coordinator;
use connection::tokio_connection;
use coordinator::Coordinator;
#[derive(Debug, StructOpt)]
struct Opt {
#[structopt(short = "l", long = "listen")]
listen: bool,
#[structopt(min_values = 1, max_values = 2)]
args: Vec<String>,
}
async fn connect(addr: &SocketAddr, coordinator: &mut Coordinator) -> Result<()> {
let stream = TcpStream::connect(addr).await?;
let (read, write) = io::split(stream);
tokio::spawn(coordinator.add_connection(tokio_connection::new_tokio_connection(read, write)));
Ok(())
}
async fn listen(addr: &SocketAddr, coordinator: &mut Coordinator) -> Result<()> {
let listener = TcpListener::bind(addr).await?;
tokio::spawn(
coordinator.add_connection(tokio_connection::new_spawner_connection(
TcpListenerStream::new(listener),
)),
);
Ok(())
}
async fn start_console(coordinator: &mut Coordinator) -> Result<()> {
let stdout = io::stdout();
let stdin = io::stdin();
tokio::spawn(coordinator.add_connection(tokio_connection::new_tokio_connection(stdin, stdout)));
Ok(())
}
fn parse_options() -> Result<(bool, SocketAddr)> {
let opt = Opt::from_args();
tracing_subscriber::fmt::init();
let (address, port): (&str, &str) = if opt.listen {
match opt.args.as_slice() {
[port] => ("0.0.0.0", port),
[address, port] => (address, port),
_ => bail!("Invalid number of arguments"),
}
} else {
match opt.args.as_slice() {
[address, port] => (address, port),
_ => bail!("Invalid number of arguments"),
}
};
let port: u16 = port.parse()?;
let addr = (address, port).to_socket_addrs()?.next().unwrap();
debug!("address={:?} port={:?} addr={:?}", address, port, addr);
Ok((opt.listen, addr))
}
async fn run_main() -> Result<()> {
let (listen_mode, addr) = parse_options()?;
let mut coordinator = Coordinator::new();
if listen_mode {
listen(&addr, &mut coordinator).await?;
} else {
connect(&addr, &mut coordinator).await?;
}
start_console(&mut coordinator).await?;
coordinator.run().await;
Ok(())
}
#[tokio::main]
async fn main() {
run_main().await.expect("Error in main");
}
<file_sep>use futures::{
sink::{Sink, SinkExt},
stream::{Stream, StreamExt},
};
use tokio::sync::mpsc;
use tracing::{debug, error};
/// Forwards a Stream to a tokio::sync::mpsc::Sender of the same item type
pub async fn stream_to_sender<Item, S>(mut stream: S, sender: mpsc::Sender<Item>)
where
S: Stream<Item = Item> + Unpin,
{
debug!("stream_to_sender starting");
while let Some(next) = stream.next().await {
if let Err(err) = sender.send(next).await {
error!("Queue error: {}", err);
break;
}
}
debug!("stream_to_sender closing");
}
/// Forwards a Stream to a Sink of the same item type
pub async fn stream_to_sink<Item, S, K>(mut stream: S, mut sink: K)
where
S: Stream<Item = Item> + Unpin,
K: Sink<Item> + Unpin,
<K as Sink<Item>>::Error: std::fmt::Display,
{
debug!("stream_to_sink starting");
while let Some(item) = stream.next().await {
debug!("stream_to_sink got item");
if let Err(err) = sink.send(item).await {
error!("Write error: {}", err);
}
}
debug!("stream_to_sink closing");
}
<file_sep>/// Temporarily added until https://github.com/tokio-rs/tokio/pull/3384 is released
use async_stream::stream;
use std::pin::Pin;
use tokio::sync::broadcast::error::RecvError;
use tokio::sync::broadcast::Receiver;
use tokio_stream::Stream;
use std::fmt;
use std::task::{Context, Poll};
/// A wrapper around [`Receiver`] that implements [`Stream`].
///
/// [`Receiver`]: struct@tokio::sync::broadcast::Receiver
/// [`Stream`]: trait@crate::Stream
pub struct BroadcastStream<T> {
inner: Pin<Box<dyn Stream<Item = Result<T, BroadcastStreamRecvError>> + Send + Sync>>,
}
/// An error returned from the inner stream of a [`BroadcastStream`].
#[derive(Debug, PartialEq)]
pub enum BroadcastStreamRecvError {
/// The receiver lagged too far behind. Attempting to receive again will
/// return the oldest message still retained by the channel.
///
/// Includes the number of skipped messages.
Lagged(u64),
}
impl<T: Clone + Unpin + 'static + Send + Sync> BroadcastStream<T> {
/// Create a new `BroadcastStream`.
pub fn new(mut rx: Receiver<T>) -> Self {
let stream = stream! {
loop {
match rx.recv().await {
Ok(item) => yield Ok(item),
Err(err) => match err {
RecvError::Closed => break,
RecvError::Lagged(n) => yield Err(BroadcastStreamRecvError::Lagged(n)),
},
}
}
};
Self {
inner: Box::pin(stream),
}
}
}
impl<T: Clone> Stream for BroadcastStream<T> {
type Item = Result<T, BroadcastStreamRecvError>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
Pin::new(&mut self.inner).poll_next(cx)
}
}
impl<T: Clone> fmt::Debug for BroadcastStream<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("BroadcastStream").finish()
}
}
<file_sep>use bytes::Bytes;
use futures::Future;
use tokio::sync::{broadcast, mpsc};
use tokio_stream::{wrappers::ReceiverStream, StreamExt, StreamMap};
use tracing::error;
use uuid::Uuid;
use crate::broadcast_stream::BroadcastStream;
use crate::connection::{
DataStream,
Message::{self, *},
NewConnection,
};
const CHANNEL_CAPACITY: usize = 10;
pub struct Coordinator {
incoming: StreamMap<Uuid, ReceiverStream<Message>>,
broadcast_sender: broadcast::Sender<(Uuid, Bytes)>,
}
impl Coordinator {
pub fn new() -> Coordinator {
let (sender, _) = broadcast::channel(CHANNEL_CAPACITY);
Coordinator {
incoming: StreamMap::new(),
broadcast_sender: sender,
}
}
pub async fn run(mut self) {
while let Some((sender, message)) = self.incoming.next().await {
match message {
Data(bytes) => {
if let Err(err) = self.broadcast_sender.send((sender, bytes)) {
error!("Send error: {:?}", err);
}
}
NewConnection(nc) => {
tokio::spawn(self.add_connection(nc));
}
}
}
}
pub fn add_connection(
&mut self,
nc: NewConnection,
) -> impl Future<Output = ()> + Send + 'static {
let (input_sender, input_receiver) = mpsc::channel(CHANNEL_CAPACITY);
// Deliver messages to this Connection
let output_receiver = BroadcastStream::new(self.broadcast_sender.subscribe());
let id = Uuid::new_v4();
let output_receiver = filter_receiver(output_receiver, id);
// Listen for messages produced by this Connection
self.incoming
.insert(id, ReceiverStream::new(input_receiver));
// Return the Connection future
nc(input_sender, output_receiver)
}
}
pub fn filter_receiver(receiver: BroadcastStream<(Uuid, Bytes)>, id: Uuid) -> DataStream {
Box::new(receiver.filter_map(move |received| {
let (msg_id, data) = received.ok()?;
if msg_id == id {
None
} else {
Some(data)
}
}))
}
#[cfg(test)]
mod tests {
use futures::stream;
use tokio::join;
use crate::connection::*;
use crate::coordinator::*;
#[tokio::test]
async fn no_conns_succeeds() {
let c = Coordinator::new();
c.run().await;
}
#[tokio::test]
async fn send_succeeds() {
let mut coord = Coordinator::new();
let send_stream = Box::pin(stream::once(async { Data(Bytes::from("somestr")) }));
let (send1, mut recv1) = futures::channel::mpsc::unbounded();
let (send2, mut recv2) = futures::channel::mpsc::unbounded();
let conn1 = coord.add_connection(stream_connection::new(send_stream, send1));
let conn2 = coord.add_connection(stream_connection::new(stream::empty(), send2));
let (_, _, _, data1, data2) = join!(conn1, conn2, coord.run(), recv1.next(), recv2.next());
assert_eq!(data1, None);
assert_eq!(data2, Some(Bytes::from("somestr")));
}
}
|
6850dcbe69a4d7fe083ba83ae27d2c81fc1e767a
|
[
"TOML",
"Rust"
] | 8
|
Rust
|
LiptonB/nettap
|
75cec1573fc843e3441d43a96904b809448932e7
|
91fb4cc57295ad3a54c6dfd6c633d6fae35ba8a1
|
refs/heads/master
|
<repo_name>simonthompson99/ProgrammingAssignment2<file_sep>/cachematrix.R
#function to calculate inverse of matric and cache for future use
#makecachematrix creates the object
#cachesolve returns either a new solving of the matrix, or a cached version
makeCacheMatrix <- function(x = matrix()){
inv <- NULL #reset inv
setmat <- function(y){ #allows setting of a new matrix
x <<- y #overwrites original matrix
inv <<- NULL #resets inv
}
getmat <- function() x #function to return the current matrix
setinv <- function(invmat) inv <<- invmat #accepts inverted matrix from cacheSolve, and writes it into the makeCacheMatrix object
getinv <- function() inv #returns the cached matrix
list(setmat = setmat, getmat = getmat, setinv = setinv, getinv = getinv) #output is list of objects, allows use of $ to refer to individual objects
}
cacheSolve <- function(x, ...){
inv <- x$getinv() #gets a cached matrix (if there is one)
if(!is.null(inv)) { #checks to see if there is a cached matrix, returns it, then exits
message("getting cached inverse")
return(inv)
}
datamat <- x$getmat() #if no cached stored, then gets the matrix
inv <- solve(datamat) #gets the inverse
x$setinv(inv) #writes it to the cached inverse matrix
inv #returns the inverse
}
|
e40592a30281dbe0df2f991d5554b8cd02221901
|
[
"R"
] | 1
|
R
|
simonthompson99/ProgrammingAssignment2
|
72177a54b6b620a643ea82a71728de73637d5ab0
|
c3d3786c1588f46dc578663846b5111709b46d92
|
refs/heads/master
|
<file_sep><?php
namespace Hshn\AngularBundle\TemplateCache;
use Symfony\Component\Filesystem\Filesystem;
/**
* @author <NAME> <<EMAIL>>
*/
class Dumper
{
/**
* @var TemplateCacheManager
*/
private $manager;
/**
* @var TemplateFinder
*/
private $finder;
/**
* @var Compiler
*/
private $compiler;
/**
* @param TemplateCacheManager $manager
* @param TemplateFinder $finder
* @param Compiler $compiler
*/
public function __construct(TemplateCacheManager $manager, TemplateFinder $finder, Compiler $compiler)
{
$this->manager = $manager;
$this->finder = $finder;
$this->compiler = $compiler;
}
/**
* @param string $target
*/
public function dump($target)
{
$content = '';
foreach ($this->manager->getModules() as $name => $config) {
if ($templates = $this->finder->find($config)) {
$content .= $this->compiler->compile($templates, $config->getName(), $config->getCreate());
}
}
$fs = new Filesystem();
$fs->dumpFile($target, $content);
}
}
<file_sep>Installation
------------
### Download HshnAngularBundle using composer
```bash
$ php composer.phar require hshn/angular-bundle
```
### Enable the bundle
```php
<?php
// app/AppKernel.php
public function registerBundles()
{
$bundles = array(
// ...
new Hshn\AngularBundle\HshnAngularBundle(),
);
}
```
### Configure the HshnAngularBundle
```yaml
# app/config/config.yml
hshn_angular:
template_cache:
modules:
# "app" will be angular module name
app:
# When specify true, "app" module will be created.
create: true
# Specify a directory that angular templates are contained.
# It will be a base directory of this module and a template url will be relative path from the base directory.
targets:
- @YourBundle/Resources/public/js
assetic: ~
```
### Using AngularTemplateCache
In Twig:
If you configured as the sample above, the template cache of `app` module is available as `@ng_template_cache_app`.
```twig
{% javascripts
'@ng_template_cache_app'%}
<script src="{{ asset_url }}"></script>
{% endjavascripts %}
```
In Javascript:
If your directory structure is like this
```
@YourBundle/Resource/public/js
├── bar
│ └── a.html
└── foo
└── b.html
```
then you can use two angular templates named `bar/a.html` and `foo/b.html` in `app` module.
```js
angular
.module('bar', [
'app'
])
.directive('bar', function () {
return {
templateUrl: 'bar/a.html', // loads the template via template cache
link: function () {}
}
})
```
In tests:
If you want to load the template cache without using assetic, run command `hshn:angular:template-cache:dump` and the template cache will be generated to the file system.
<file_sep><?php
/**
* @author <NAME> <<EMAIL>>
*/
namespace Hshn\AngularBundle\Tests\Functional;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Component\Console\Tester\CommandTester;
class DebugTemplateCacheCommandTest extends WebTestCase
{
public function test()
{
static::bootKernel();
$command = static::$kernel->getContainer()->get('hshn_angular.command.debug_template_cache');
$app = new Application(static::$kernel);
$app->add($command);
$tester = new CommandTester($app->find('hshn:angular:template-cache:debug'));
$tester->execute(array());
$lines = preg_split('/[\r\n]+/', trim($tester->getDisplay()));
$this->assertCount(4, $lines);
$this->assertEquals('foo.templates', $lines[0]);
$templates = $this->logicalOr(
$this->matchesRegularExpression('/^ foo.html /'),
$this->matchesRegularExpression('/^ bar.html /'),
$this->matchesRegularExpression('/^ bar\/baz.html /')
);
$this->assertThat($lines[1], $templates);
$this->assertThat($lines[2], $templates);
$this->assertThat($lines[3], $templates);
}
}
<file_sep><?php
namespace Hshn\AngularBundle\Tests\Functional;
use Symfony\Component\Finder\Finder;
/**
* @author <NAME> <<EMAIL>>
*/
class WebTestCase extends \Symfony\Bundle\FrameworkBundle\Test\WebTestCase
{
/**
* {@inheritdoc}
*/
protected static function getKernelClass()
{
require __DIR__.'/AppKernel.php';
return 'Hshn\AngularBundle\Tests\Functional\AppKernel';
}
}
<file_sep><?php
namespace Hshn\AngularBundle\Tests\Functional;
/**
* @author <NAME> <<EMAIL>>
*/
class ServiceContainerTest extends WebTestCase
{
/**
* @test
*/
public function testServicesHaveRegistered()
{
static::bootKernel();
$container = static::$kernel->getContainer();
$ids = array(
'hshn_angular.template_cache.template_finder',
'hshn_angular.template_cache.manager',
'hshn_angular.template_cache.compiler',
'hshn_angular.template_cache.dumper',
'hshn_angular.command.dump_template_cache',
);
foreach ($ids as $id) {
$this->assertTrue($container->has($id), $id);
}
}
}
<file_sep><?php
/**
* @author <NAME> <<EMAIL>>
*/
namespace Hshn\AngularBundle\Command;
use Hshn\AngularBundle\TemplateCache\TemplateCacheManager;
use Hshn\AngularBundle\TemplateCache\TemplateFinder;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
class DebugTemplateCacheCommand extends Command
{
/**
* @var TemplateCacheManager
*/
private $manager;
/**
* @var TemplateFinder
*/
private $finder;
/**
* @param TemplateCacheManager $manager
* @param TemplateFinder $finder
*/
public function __construct(TemplateCacheManager $manager, TemplateFinder $finder)
{
parent::__construct();
$this->manager = $manager;
$this->finder = $finder;
}
/**
* {@inheritdoc}
*/
protected function configure()
{
$this
->setName('hshn:angular:template-cache:debug')
->setDescription('Displays configured template caches')
;
}
/**
* {@inheritdoc}
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
foreach ($this->manager->getModules() as $name => $module) {
$output->writeln(sprintf('<comment>%s</comment>', $module->getName()));
foreach ($this->finder->find($module) as $template) {
$output->writeln(sprintf(' %s (%s)', $template->getRelativePathname(), $template->getPathname()));
}
}
}
}
<file_sep><?php
namespace Hshn\AngularBundle\Command;
use Hshn\AngularBundle\TemplateCache\Dumper;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
/**
* @author <NAME> <<EMAIL>>
*/
class DumpTemplateCacheCommand extends Command
{
/**
* @var \Hshn\AngularBundle\TemplateCache\Dumper
*/
private $dumper;
/**
* @var string
*/
private $target;
/**
* @param Dumper $dumper
* @param string $target
*/
public function __construct(Dumper $dumper, $target)
{
parent::__construct();
$this->dumper = $dumper;
$this->target = $target;
}
/**
* {@inheritdoc}
*/
protected function configure()
{
$this
->setName('hshn:angular:template-cache:dump')
->setDescription('Dumps template cache to the filesystem')
->addOption('target', null, InputOption::VALUE_OPTIONAL, 'Override the target path to dump')
;
}
/**
* {@inheritdoc}
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$target = $input->getOption('target') ?: $this->target;
$output->writeln('<info>[file+]</info> ' . $target);
$this->dumper->dump($target);
}
}
<file_sep>module.exports = function (grunt) {
grunt.initConfig({
phpunit: {
classes: {
dir: 'Tests'
},
options: {
bin: './bin/phpunit',
colors: true,
followOutput: true
}
},
watch: {
phpunit: {
tasks: ['phpunit'],
files: [
'Tests/**/*Test.php'
],
options: {
nospawn: true
}
}
}
});
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-phpunit');
grunt.registerTask('test:phpunit', ['phpunit']);
grunt.registerTask('test', ['test:phpunit']);
grunt.event.on('watch', function (action, filepath) {
grunt.config(['phpunit', 'classes', 'dir'], filepath);
});
};
<file_sep><?php
/**
* @author <NAME> <<EMAIL>>
*/
namespace Hshn\AngularBundle\Tests\Functional\Bundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class TestBundle extends Bundle
{
}
<file_sep><?php
namespace Hshn\AngularBundle\Assetic\Asset;
use Assetic\Asset\BaseAsset;
use Assetic\Filter\FilterInterface;
use Hshn\AngularBundle\TemplateCache\Compiler;
use Hshn\AngularBundle\TemplateCache\ConfigurationInterface;
use Hshn\AngularBundle\TemplateCache\TemplateFinder;
use Symfony\Component\Finder\SplFileInfo;
class TemplateCacheAsset extends BaseAsset
{
/**
* @var \Hshn\AngularBundle\TemplateCache\TemplateFinder
*/
private $templateFinder;
/**
* @var \Hshn\AngularBundle\TemplateCache\Compiler
*/
private $compiler;
/**
* @var \Hshn\AngularBundle\TemplateCache\ConfigurationInterface
*/
private $configuration;
/**
* @var bool
*/
private $initialized;
/**
* @var SplFileInfo[]
*/
private $templates;
/**
* @param TemplateFinder $templateFinder
* @param Compiler $compiler
* @param ConfigurationInterface $configuration
*/
public function __construct(TemplateFinder $templateFinder, Compiler $compiler, ConfigurationInterface $configuration)
{
parent::__construct();
$this->templateFinder = $templateFinder;
$this->compiler = $compiler;
$this->configuration = $configuration;
$this->initialized = false;
}
/**
* {@inheritdoc}
*/
public function load(FilterInterface $additionalFilter = null)
{
$this->initialize();
$output = $this->compiler->compile($this->templates, $this->configuration->getName(), $this->configuration->getCreate());
$this->doLoad($output, $additionalFilter);
}
/**
* {@inheritdoc}
*/
public function getLastModified()
{
$this->initialize();
$lastModified = null;
foreach ($this->templates as $template) {
if ($lastModified === null) {
$lastModified = $template->getMTime();
} elseif ($lastModified < $template->getMTime()) {
$lastModified = $template->getMTime();
}
}
return $lastModified;
}
/**
* {@inheritdoc}
*/
private function initialize()
{
if ($this->initialized) {
return;
}
$this->initialized = true;
$this->templates = $this->templateFinder->find($this->configuration);
}
}
<file_sep><?php
namespace Hshn\AngularBundle\Tests\TemplateCache;
use Hshn\AngularBundle\TemplateCache\Compiler;
use Hshn\AngularBundle\TemplateCache\ConfigurationInterface;
use Hshn\AngularBundle\TemplateCache\TemplateFinder;
class CompilerTest extends \PHPUnit_Framework_TestCase
{
/**
* @var Compiler
*/
private $compiler;
/**
* @var TemplateFinder
*/
private $finder;
protected function setUp()
{
$this->compiler = new Compiler();
$this->finder = new TemplateFinder($this->getMock('Symfony\Component\HttpKernel\KernelInterface'));
}
/**
* @test
* @dataProvider provideCompileArgs
*/
public function testCompile(ConfigurationInterface $configuration, $expectedFileName, $newModule)
{
$files = $this->finder->find($configuration);
$this->assertStringEqualsFile(__DIR__.'/Fixtures/caches/'.$expectedFileName, $this->compiler->compile($files, $configuration->getName(), $newModule));
}
/**
* @return array
*/
public function provideCompileArgs()
{
return array(
array($this->getConfiguration('all', array('bar', 'foo')), 'all.js', false),
array($this->getConfiguration('all', array('')), 'all_recursive.js', false),
array($this->getConfiguration('bar', array('bar')), 'bar.js', false),
array($this->getConfiguration('all', array('bar', 'foo')), 'all_new.js', true),
array($this->getConfiguration('all', array('')), 'all_recursive_new.js', true),
array($this->getConfiguration('bar', array('bar')), 'bar_new.js', true),
);
}
/**
* @param string $name
* @param array $targets
*
* @return \PHPUnit_Framework_MockObject_MockObject|ConfigurationInterface
*/
private function getConfiguration($name, array $targets)
{
$targets = array_map(function ($target) {
return __DIR__.'/Fixtures/templates/' . $target;
}, $targets);
$configuration = $this->getMock('Hshn\AngularBundle\TemplateCache\ConfigurationInterface');
$configuration
->expects($this->atLeastOnce())
->method('getTargets')
->will($this->returnValue($targets));
$configuration
->expects($this->atLeastOnce())
->method('getName')
->will($this->returnValue($name));
return $configuration;
}
}
<file_sep>HshnAngularBundle
=================
[](https://travis-ci.org/hshn/HshnAngularBundle) [](https://scrutinizer-ci.com/g/hshn/HshnAngularBundle/?branch=master) [](https://packagist.org/packages/hshn/angular-bundle) [](https://packagist.org/packages/hshn/angular-bundle) [](https://packagist.org/packages/hshn/angular-bundle)
The HshnAngularBundle provides "template cache" auto generation that can be loaded via assetic. It can reduce http requests. (please see [$templateCache](https://docs.angularjs.org/api/ng/service/$templateCache)).
Documentation
-------------
[Read the Documentation for master](https://github.com/hshn/HshnAngularBundle/blob/master/Resources/doc/index.md)
License
-------
This bundle is under the MIT license. See the complete license in the bundle:
Resources/meta/LICENSE
<file_sep><?php
namespace Hshn\AngularBundle\Tests\TemplateCache;
use Hshn\AngularBundle\TemplateCache\TemplateCacheManager;
class TemplateCacheManagerTest extends \PHPUnit_Framework_TestCase
{
/**
* @var TemplateCacheManager
*/
private $manager;
/**
* {@inheritdoc}
*/
protected function setUp()
{
$this->manager = new TemplateCacheManager();
}
/**
* @test
*/
public function testAddModule()
{
$this->assertCount(0, $this->manager->getModules());
$this->manager->addModule('foo', $foo = $this->getConfiguration());
$this->assertCount(1, $this->manager->getModules());
$this->manager->addModule('bar', $bar = $this->getConfiguration());
$this->assertCount(2, $this->manager->getModules());
$modules = $this->manager->getModules();
$this->assertSame($foo, $modules['foo']);
$this->assertSame($bar, $modules['bar']);
}
/**
* @return \PHPUnit_Framework_MockObject_MockObject
*/
private function getConfiguration()
{
$configuration = $this->getMock('Hshn\AngularBundle\TemplateCache\ConfigurationInterface');
return $configuration;
}
}
<file_sep><?php
namespace Hshn\AngularBundle\Tests\Assetic\Asset;
use Hshn\AngularBundle\Assetic\Asset\TemplateCacheAsset;
use Hshn\AngularBundle\TemplateCache\Compiler;
use Hshn\AngularBundle\TemplateCache\ConfigurationInterface;
use Hshn\AngularBundle\TemplateCache\TemplateFinder;
class TemplateCacheAssetTest extends \PHPUnit_Framework_TestCase
{
/**
* @var TemplateCacheAsset
*/
private $asset;
/**
* @var TemplateFinder|\PHPUnit_Framework_MockObject_MockObject
*/
private $finder;
/**
* @var Compiler|\PHPUnit_Framework_MockObject_MockObject
*/
private $compiler;
/**
* @var ConfigurationInterface|\PHPUnit_Framework_MockObject_MockObject
*/
private $module;
protected function setUp()
{
$this->asset = new TemplateCacheAsset(
$this->finder = $this->getMockBuilder('Hshn\AngularBundle\TemplateCache\TemplateFinder')->disableOriginalConstructor()->getMock(),
$this->compiler = $this->getMockBuilder('Hshn\AngularBundle\TemplateCache\Compiler')->disableOriginalConstructor()->getMock(),
$this->module = $this->getMock('Hshn\AngularBundle\TemplateCache\ConfigurationInterface')
);
}
/**
* @test
*/
public function testGetLastModified()
{
$this
->finder
->expects($this->once())
->method('find')
->with($this->module)
->will($this->returnValue(array(
$this->getSplFileInfo(30),
$this->getSplFileInfo(80)
)));
$this->assertEquals(80, $this->asset->getLastModified());
$this->assertEquals(80, $this->asset->getLastModified());
}
/**
* @test
* @dataProvider provideDoLoadTests
*
* @param boolean $newModule
*/
public function testDoLoad($newModule)
{
$this
->finder
->expects($this->once())
->method('find')
->with($this->module)
->will($this->returnValue($templates = array(
$this->getSplFileInfo(),
$this->getSplFileInfo()
)));
$this
->module
->expects($this->once())
->method('getName')
->will($this->returnValue($moduleName = 'testModuleName'));
$this
->module
->expects($this->once())
->method('getCreate')
->will($this->returnValue($newModule));
$this
->compiler
->expects($this->once())
->method('compile')
->with($templates, $moduleName, $newModule)
->will($this->returnValue($content = 'test content'));
$this->assertEquals($content, $this->asset->dump());
}
/**
* @return array
*/
public function provideDoLoadTests()
{
return array(
array(true),
array(false),
);
}
/**
* @return \PHPUnit_Framework_MockObject_MockObject
*/
private function getSplFileInfo($lastModifiedTime = 0)
{
$file = $this->getMockBuilder('Symfony\Component\Finder\SplFileInfo')->setConstructorArgs(array(__FILE__, '', ''))->getMock();
$file
->expects($this->any())
->method('getMTime')
->will($this->returnValue($lastModifiedTime));
return $file;
}
}
<file_sep><?php
namespace Hshn\AngularBundle\TemplateCache;
class Configuration implements ConfigurationInterface
{
/**
* @var string
*/
private $name;
/**
* @var bool
*/
private $create;
/**
* @var string[]
*/
private $targets;
/**
* {@inheritdoc}
*/
public function setName($name)
{
$this->name = $name;
}
/**
* {@inheritdoc}
*/
public function getName()
{
return $this->name ?: $this->name;
}
/**
* {@inheritdoc}
*/
public function setTargets(array $targets)
{
$this->targets = $targets;
}
/**
* {@inheritdoc}
*/
public function getTargets()
{
return $this->targets;
}
/**
* @return boolean
*/
public function getCreate()
{
return $this->create;
}
/**
* @param boolean $create
*/
public function setCreate($create)
{
$this->create = $create;
}
}
<file_sep><?php
namespace Hshn\AngularBundle\Tests\Functional;
use Hshn\AngularBundle\HshnAngularBundle;
use Symfony\Bundle\AsseticBundle\AsseticBundle;
use Symfony\Bundle\FrameworkBundle\FrameworkBundle;
use Symfony\Bundle\TwigBundle\TwigBundle;
use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\HttpKernel\Kernel;
/**
* @author <NAME> <<EMAIL>>
*/
class AppKernel extends Kernel
{
/**
* {@inheritdoc}
*/
public function registerBundles()
{
return array(
new FrameworkBundle(),
new TwigBundle(),
new AsseticBundle(),
new HshnAngularBundle(),
);
}
/**
* {@inheritdoc}
*/
public function registerContainerConfiguration(LoaderInterface $loader)
{
$loader->load(__DIR__.'/config/config.yml');
}
}
<file_sep><?php
namespace Hshn\AngularBundle\TemplateCache;
interface ConfigurationInterface
{
/**
* @return string
*/
public function getName();
/**
* @param string $name
*
* @return void
*/
public function setName($name);
/**
* @param string[] $targets
* @return void
*/
public function setTargets(array $targets);
/**
* @return string[]
*/
public function getTargets();
/**
* @param boolean $newModule
*
* @return void
*/
public function setCreate($newModule);
/**
* @return boolean
*/
public function getCreate();
}
<file_sep><?php
namespace Hshn\AngularBundle\TemplateCache;
class TemplateCacheManager
{
/**
* @var ConfigurationInterface[]
*/
private $modules;
/**
*
*/
public function __construct()
{
$this->modules = array();
}
/**
* @param string $name
* @param ConfigurationInterface $configuration
*/
public function addModule($name, ConfigurationInterface $configuration)
{
$this->modules[$name] = $configuration;
}
/**
* @return ConfigurationInterface[]
*/
public function getModules()
{
return $this->modules;
}
}
<file_sep><?php
namespace Hshn\AngularBundle\TemplateCache;
use Symfony\Component\Finder\Finder;
use Symfony\Component\Finder\SplFileInfo;
use Symfony\Component\HttpKernel\KernelInterface;
class TemplateFinder
{
/**
* @var \Symfony\Component\HttpKernel\KernelInterface
*/
private $kernel;
/**
* @param KernelInterface $kernel
*/
public function __construct(KernelInterface $kernel)
{
$this->kernel = $kernel;
}
/**
* @param ConfigurationInterface $configuration
*
* @return SplFileInfo[]
*/
public function find(ConfigurationInterface $configuration)
{
$finder = Finder::create()
->in($this->getTargetDirectories($configuration))
->name('*.html')
->ignoreDotFiles(true)
->files()
->sort(function (SplFileInfo $a, SplFileInfo $b) {
return strcmp($a->getRelativePathname(), $b->getRelativePathname());
});
return iterator_to_array($finder->getIterator());
}
/**
* @param ConfigurationInterface $configuration
*
* @return array
*/
private function getTargetDirectories(ConfigurationInterface $configuration)
{
$kernel = $this->kernel;
$directories = array();
foreach ($configuration->getTargets() as $target) {
$directories[] = preg_replace_callback('/^@([^\/]+)/', function ($matches) use ($kernel) {
return $kernel->getBundle($matches[1])->getPath();
}, $target);
}
return $directories;
}
}
<file_sep><?php
namespace Hshn\AngularBundle\TemplateCache;
use Symfony\Component\Finder\SplFileInfo;
class Compiler
{
/**
* @param SplFileInfo[] $files
* @param string $moduleName
* @param bool $newModule
*
* @return string
*/
public function compile(array $files, $moduleName, $newModule = false)
{
$output = "'use strict';\n\n";
$output .= $newModule ? "angular.module('{$moduleName}', [])\n" : "angular.module('{$moduleName}')\n";
$output .= " .run(['\$templateCache', function (\$templateCache) {\n";
/* @var $file SplFileInfo */
foreach ($files as $file) {
$templateId = $file->getRelativePathname();
$output .= " \$templateCache.put('{$templateId}',\n";
$html = array();
foreach (new \SplFileObject($file->getPathname(), 'r') as $line) {
$html[] = ' \'' . str_replace(array("\r", "\n", '\''), array('\r', '\n', '\\\''), $line) . "'";
}
$output .= implode(" +\n", $html) . ");\n";
}
$output .= " }])\n";
$output .= ";\n";
return $output;
}
}
<file_sep><?php
/**
* @author <NAME> <<EMAIL>>
*/
namespace Hshn\AngularBundle\Tests\Command;
use Hshn\AngularBundle\Command\DebugTemplateCacheCommand;
use Symfony\Component\Console\Tester\CommandTester;
class DebugTemplateCacheCommandTest extends \PHPUnit_Framework_TestCase
{
/**
* @var DebugTemplateCacheCommand
*/
private $command;
/**
* @var \PHPUnit_Framework_MockObject_MockObject
*/
private $manager;
/**
* @var \PHPUnit_Framework_MockObject_MockObject
*/
private $finder;
/**
* {@inheritdoc}
*/
protected function setUp()
{
parent::setUp();
$this->command = new DebugTemplateCacheCommand(
$this->manager = $this->getMockBuilder('Hshn\AngularBundle\TemplateCache\TemplateCacheManager')->disableOriginalConstructor()->getMock(),
$this->finder = $this->getMockBuilder('Hshn\AngularBundle\TemplateCache\TemplateFinder')->disableOriginalConstructor()->getMock()
);
}
/**
* @test
*/
public function test()
{
$this
->manager
->expects($this->once())
->method('getModules')
->willReturn($configurations = array(
'foo' => $this->getConfiguration('foo'),
'bar' => $this->getConfiguration('bar'),
));
$this
->finder
->expects($this->exactly(count($configurations)))
->method('find')
->with($this->logicalOr(
$this->identicalTo($configurations['foo']),
$this->identicalTo($configurations['bar'])
))
->willReturnOnConsecutiveCalls(
array($this->getSplFileInfo('foo.html', '/path/to/foo.html'), $this->getSplFileInfo('bar.html', '/path/to/bar.html')),
array($this->getSplFileInfo('baz.html', '/path/to/baz.html'))
);
$tester = new CommandTester($this->command);
$tester->execute(array());
$expected = <<<OUT
foo
foo.html (/path/to/foo.html)
bar.html (/path/to/bar.html)
bar
baz.html (/path/to/baz.html)
OUT;
$this->assertEquals($expected, $tester->getDisplay());
}
/**
* @param $name
* @return \PHPUnit_Framework_MockObject_MockObject
*/
private function getConfiguration($name)
{
$config = $this->getMock('Hshn\AngularBundle\TemplateCache\ConfigurationInterface');
$config
->expects($this->once())
->method('getName')
->willReturn($name);
return $config;
}
/**
* @param $relativePathname
* @param $pathname
* @return \PHPUnit_Framework_MockObject_MockObject
*/
private function getSplFileInfo($relativePathname, $pathname)
{
$file = $this
->getMockBuilder('Symfony\Component\Finder\SplFileInfo')
->setConstructorArgs(array(__FILE__, '', ''))
->getMock();
$file
->expects($this->atLeastOnce())
->method('getRelativePathname')
->willReturn($relativePathname);
$file
->expects($this->atLeastOnce())
->method('getPathname')
->willReturn($pathname);
return $file;
}
}
<file_sep><?php
namespace Hshn\AngularBundle\Tests\Command;
use Hshn\AngularBundle\Command\DumpTemplateCacheCommand;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Tester\CommandTester;
/**
* @author <NAME> <<EMAIL>>
*/
class DumpTemplateCacheCommandTest extends \PHPUnit_Framework_TestCase
{
/**
* @var DumpTemplateCacheCommand
*/
private $command;
/**
* @var \PHPUnit_Framework_MockObject_MockObject
*/
private $dumper;
/**
* @var string
*/
private $path;
protected function setUp()
{
$this->command = new DumpTemplateCacheCommand(
$this->dumper = $this->getMockBuilder('Hshn\AngularBundle\TemplateCache\Dumper')->disableOriginalConstructor()->getMock(),
$this->path = 'dummy path'
);
}
/**
* @test
*/
public function test()
{
$this->dumper
->expects($this->once())
->method('dump')
->with($this->path);
$tester = $this->runCommand(array());
$this->assertContains('[file+] dummy path', $tester->getDisplay());
}
/**
* @test
*/
public function testOverrideTarget()
{
$path = 'overridden path';
$this->dumper
->expects($this->once())
->method('dump')
->with($path);
$tester = $this->runCommand(array('--target' => $path), array());
$this->assertContains("[file+] {$path}", $tester->getDisplay());
}
/**
* @param array $input
* @param array $options
*
* @return CommandTester
*/
private function runCommand(array $input, array $options = array())
{
$application = new Application();
$application->add($this->command);
$command = $application->find('hshn:angular:template-cache:dump');
$tester = new CommandTester($command);
$tester->execute($input, $options);
return $tester;
}
}
<file_sep><?php
namespace Hshn\AngularBundle\Tests\DependencyInjection;
use Hshn\AngularBundle\DependencyInjection\HshnAngularExtension;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
class HshnAngularExtensionTest extends \PHPUnit_Framework_TestCase
{
/**
* @var ContainerBuilder
*/
private $container;
/**
* @var HshnAngularExtension
*/
private $extension;
/**
*
*/
public function setUp()
{
$this->container = new ContainerBuilder(new ParameterBag());
$this->extension = new HshnAngularExtension();
}
/**
* @test
*/
public function testLoadDefaults()
{
$configs = $this->getConfiguration();
$this->extension->load($configs, $this->container);
$this->assertTrue($this->container->has('hshn_angular.asset.template_cache'));
$this->assertTrue($this->container->has('hshn_angular.template_cache.manager'));
$this->assertTrue($this->container->has('hshn_angular.template_cache.template_finder'));
$this->assertTrue($this->container->has('hshn_angular.template_cache.compiler'));
$calls = $this->container->getDefinition('hshn_angular.template_cache.manager')->getMethodCalls();
$this->assertCount(2, $calls);
$this->assertEquals('addModule', $calls[0][0]);
$this->assertEquals('addModule', $calls[1][0]);
$this->assertNotNull($config = $this->container->getDefinition('hshn_angular.template_cache.configuration.foo'));
$this->assertMethodCall($config->getMethodCalls(), 'setName', array('foo'));
$this->assertMethodCall($config->getMethodCalls(), 'setTargets', array(array('hoge')));
$this->assertMethodCall($config->getMethodCalls(), 'setCreate', array(false));
$this->assertNotNull($config = $this->container->getDefinition('hshn_angular.template_cache.configuration.bar'));
$this->assertMethodCall($config->getMethodCalls(), 'setName', array('bar'));
$this->assertMethodCall($config->getMethodCalls(), 'setTargets', array(array('path/to/dir-a', 'path/to/dir-b')));
$this->assertMethodCall($config->getMethodCalls(), 'setCreate', array(true));
$definition = $this->container->getDefinition('hshn_angular.command.dump_template_cache');
$this->assertEquals('%kernel.root_dir%/../web/js/hshn_angular_template_cache.js', $definition->getArgument(1));
}
/**
* @test
*/
public function testTemplateCacheModuleName()
{
$this->extension->load(array(
'hshn_angular' => array(
'template_cache' => array(
'modules' => array(
'foo' => array(
'targets' => 'foo'
),
'foo-template' => array(
'name' => 'foo-template',
'targets' => 'foo_template'
),
)
)
)
), $this->container);
$this->assertNotNull($definition = $this->container->getDefinition('hshn_angular.template_cache.configuration.foo'));
$this->assertMethodCall($definition->getMethodCalls(), 'setName', array('foo'));
$this->assertNotNull($definition = $this->container->getDefinition('hshn_angular.template_cache.configuration.foo_template'));
$this->assertMethodCall($definition->getMethodCalls(), 'setName', array('foo-template'));
}
/**
* @test
*/
public function testAssetic()
{
$configs = $this->getConfiguration();
$this->extension->load($configs, $this->container);
$this->assertNotNull($definition = $this->container->getDefinition('hshn_angular.asset.template_cache.foo'));
$this->assertMethodCall($definition->getMethodCalls(), 'setTargetPath', array('js/ng_template_cache/foo.js'));
$this->assertEquals(array(array('alias' => 'ng_template_cache_foo')), $definition->getTag('assetic.asset'));
$this->assertNotNull($definition = $this->container->getDefinition('hshn_angular.asset.template_cache.bar'));
$this->assertMethodCall($definition->getMethodCalls(), 'setTargetPath', array('js/ng_template_cache/bar.js'));
$this->assertEquals(array(array('alias' => 'ng_template_cache_bar')), $definition->getTag('assetic.asset'));
}
/**
* @test
*/
public function testLoadWithoutAssetic()
{
$configs = $this->getConfiguration();
unset($configs['hshn_angular']['assetic']);
$this->extension->load($configs, $this->container);
$this->assertFalse($this->container->has('hshn_angular.asset.template_cache'));
}
/**
* @return array
*/
private function getConfiguration()
{
return array(
'hshn_angular' => array(
'template_cache' => array(
'modules' => array(
'foo' => array(
'targets' => 'hoge'
),
'bar' => array(
'create' => true,
'targets' => array('path/to/dir-a', 'path/to/dir-b'),
)
)
),
'assetic' => null,
)
);
}
/**
* @param array $methodCalls
* @param string $name
* @param array $expectedValues
*/
private function assertMethodCall(array $methodCalls, $name, array $expectedValues)
{
foreach ($methodCalls as $methodCall) {
if ($methodCall[0] == $name) {
foreach ($methodCall[1] as $key => $parameter) {
$this->assertEquals($expectedValues[$key], $parameter);
}
return;
}
}
$this->fail("Failed asserting that method {$name} was called");
}
/**
* @param $id
*/
private function assertHasService($id)
{
$this->assertTrue($this->container->has($id) || $this->container->hasAlias($id), "service or alias {$id}");
}
}
<file_sep><?php
namespace Hshn\AngularBundle;
use Hshn\AngularBundle\DependencyInjection\Compiler\SetClosureParameterPass;
use Symfony\Component\Console\Application;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class HshnAngularBundle extends Bundle
{
/**
* {@inheritdoc}
*/
public function registerCommands(Application $application)
{
// disable auto registrations
}
}
<file_sep>'use strict';
angular.module('bar')
.run(['$templateCache', function ($templateCache) {
$templateCache.put('c.html',
'<div class="foo" id=\'bar\'>\n' +
' bar c\n' +
'</div>\n' +
'');
$templateCache.put('d.html',
'<div class="foo" id=\'bar\'>\n' +
' bar d\n' +
'</div>\n' +
'');
}])
;
<file_sep><?php
namespace Hshn\AngularBundle\Tests\TemplateCache;
use Hshn\AngularBundle\TemplateCache\Dumper;
/**
* @author <NAME> <<EMAIL>>
*/
class DumperTest extends \PHPUnit_Framework_TestCase
{
/**
* @var Dumper
*/
private $dumper;
/**
* @var \PHPUnit_Framework_MockObject_MockObject
*/
private $manager;
/**
* @var \PHPUnit_Framework_MockObject_MockObject
*/
private $finder;
/**
* @var \PHPUnit_Framework_MockObject_MockObject
*/
private $compiler;
/**
* @var string
*/
private $dumpPath;
protected function setUp()
{
$this->dumpPath = tempnam(sys_get_temp_dir(), md5(__CLASS__));
$this->dumper = new Dumper(
$this->manager = $this->getMockBuilder('Hshn\AngularBundle\TemplateCache\TemplateCacheManager')->disableOriginalConstructor()->getMock(),
$this->finder = $this->getMockBuilder('Hshn\AngularBundle\TemplateCache\TemplateFinder')->disableOriginalConstructor()->getMock(),
$this->compiler = $this->getMockBuilder('Hshn\AngularBundle\TemplateCache\Compiler')->disableOriginalConstructor()->getMock()
);
}
/**
* @test
*/
public function testDump()
{
$this
->manager
->expects($this->once())
->method('getModules')
->will($this->returnValue($modules = array(
'foo' => $this->getModule('foo'),
'bar' => $this->getModule('bar')
)));
$this
->finder
->expects($this->exactly(2))
->method('find')
->with($this->logicalOr($this->identicalTo($modules['foo']), $this->identicalTo($modules['bar'])))
->will($this->onConsecutiveCalls(
$templates1 = array('/path/foo/1', '/path/foo/2'),
$templates2 = array('/path/bar')
));
$this
->compiler
->expects($this->exactly(2))
->method('compile')
->with($this->logicalOr($templates1, $templates2), $this->logicalOr('foo', 'bar'))
->will($this->onConsecutiveCalls(
'foo_template_cache',
'bar_template_cache'
));
$this->dumper->dump($this->dumpPath);
$this->assertFileExists($this->dumpPath);
$this->assertEquals('foo_template_cachebar_template_cache', file_get_contents($this->dumpPath));
}
/**
* @param $name
*
* @return \PHPUnit_Framework_MockObject_MockObject
*/
private function getModule($name)
{
$config = $this->getMock('Hshn\AngularBundle\TemplateCache\ConfigurationInterface');
$config
->expects($this->atLeastOnce())
->method('getName')
->will($this->returnValue($name));
return $config;
}
}
<file_sep><?php
namespace Hshn\AngularBundle\DependencyInjection;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\DefinitionDecorator;
use Symfony\Component\DependencyInjection\Loader;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
class HshnAngularExtension extends Extension
{
/**
* {@inheritDoc}
*/
public function load(array $configs, ContainerBuilder $container)
{
$configuration = new Configuration();
$config = $this->processConfiguration($configuration, $configs);
$loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
if (isset($config['template_cache'])) {
$this->loadTemplateCache($container, $loader, $config['template_cache']);
}
if (isset($config['assetic'])) {
$moduleNames = isset($config['template_cache']) ? array_keys($config['template_cache']['modules']) : array();
$this->loadAssetic($container, $loader, $config['assetic'], $moduleNames);
}
}
/**
* @param ContainerBuilder $container
* @param LoaderInterface $loader
* @param array $config
*/
private function loadTemplateCache(ContainerBuilder $container, LoaderInterface $loader, array $config)
{
$loader->load('template_cache.yml');
$container
->getDefinition('hshn_angular.command.dump_template_cache')
->replaceArgument(1, $config['dump_path']);
$this->loadModuleInformation($container, $config['modules']);
}
/**
* @param ContainerBuilder $container
* @param array $modules
*/
private function loadModuleInformation(ContainerBuilder $container, array $modules)
{
$manager = $container->getDefinition('hshn_angular.template_cache.manager');
foreach ($modules as $name => $module) {
$configuration = new DefinitionDecorator('hshn_angular.template_cache.configuration');
$configuration
->addMethodCall('setName', array($module['name'] ?: $name))
->addMethodCall('setCreate', array($module['create']))
->addMethodCall('setTargets', array($module['targets']));
$container->setDefinition($id = sprintf('hshn_angular.template_cache.configuration.%s', $name), $configuration);
$manager->addMethodCall('addModule', array($name, new Reference($id)));
}
}
/**
* @param ContainerBuilder $container
* @param LoaderInterface $loader
* @param array $config
* @param array $moduleNames
*/
private function loadAssetic(ContainerBuilder $container, LoaderInterface $loader, array $config, array $moduleNames)
{
$loader->load('assetic.yml');
foreach ($moduleNames as $moduleName) {
$asset = new DefinitionDecorator('hshn_angular.asset.template_cache');
$asset->replaceArgument(2, new Reference(sprintf('hshn_angular.template_cache.configuration.%s', $moduleName)));
$asset->addMethodCall('setTargetPath', array(sprintf('js/ng_template_cache/%s.js', $moduleName)));
$asset->addTag('assetic.asset', array('alias' => 'ng_template_cache_' . $moduleName));
$container->setDefinition(sprintf('hshn_angular.asset.template_cache.%s', $moduleName), $asset);
}
}
}
<file_sep><?php
namespace Hshn\AngularBundle\Tests\Functional;
use Assetic\Factory\AssetFactory;
/**
* @author <NAME> <<EMAIL>>
*/
class DumpAssetTest extends WebTestCase
{
/**
* @test
*/
public function test()
{
static::bootKernel();
/* @var $factory AssetFactory */
$factory = static::$kernel->getContainer()->get('assetic.asset_factory');
$asset = $factory->createAsset(array('@ng_template_cache_foo'));
$asset->load();
$this->assertStringEqualsFile(__DIR__.'/Fixtures/ng_template_cache_foo.js', $asset->getContent());
}
}
<file_sep><?php
namespace Hshn\AngularBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
class Configuration implements ConfigurationInterface
{
/**
* {@inheritDoc}
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('hshn_angular');
$rootNode
->children()
->arrayNode('template_cache')
->addDefaultsIfNotSet()
->children()
->scalarNode('dump_path')->defaultValue('%kernel.root_dir%/../web/js/hshn_angular_template_cache.js')->end()
->arrayNode('modules')
->useAttributeAsKey('key')
->prototype('array')
->children()
->booleanNode('create')->cannotBeEmpty()->defaultFalse()->info('Generate template caches into the new module. If not, generate into existed one.')->end()
->scalarNode('name')->defaultNull()->end()
->arrayNode('targets')
->beforeNormalization()
->ifString()
->then(function ($v) {
return array($v);
})
->end()
->isRequired()
->prototype('scalar')->end()
->end()
->end()
->end()
->end()
->end()
->end()
->arrayNode('assetic')
->end()
->end()
;
return $treeBuilder;
}
}
|
4831f27d8f2b8a29a4a7bc0fc9a1a3a775bbc8c4
|
[
"Markdown",
"JavaScript",
"PHP"
] | 29
|
PHP
|
hshn/HshnAngularBundle
|
5c8137e029ef64d392f59f604de7eb0cddef0c18
|
ba810549350d628190c5b03eb935314a034fb23c
|
refs/heads/master
|
<repo_name>maateusilva/uknow<file_sep>/src/components/NewQuestion/styles.js
import { StyleSheet } from 'react-native'
import { darkGray, white, gray } from '../../styles'
export default StyleSheet.create({
container: {
flex: 1,
padding: 20,
backgroundColor: white,
justifyContent: 'center',
alignItems: 'stretch'
},
title: {
fontSize: 20,
textAlign: 'center',
color: darkGray,
fontWeight: 'bold'
},
input: {
backgroundColor: white,
borderRadius: 3,
height: 44,
paddingHorizontal: 10,
borderWidth: 1,
borderColor: gray,
}
})
<file_sep>/README.md
## What is uKnow?
*uKnow* is a flashcards mobile app that will help you to study anything! With a clean, interactive and beautiful interface, you will can easily create your study material!
# Requirements
- [Node.js and NPM](http://nodejs.org/)
- We recommend to use [yarn](https://yarnpkg.com) instead NPM for fastest installation, but it's not required;
- iOS or Android Emulator
- The app was built and tested with Galaxy S8 and iPhone X emulators and works fine in both platforms (iOS and Android). Preferably use one of these. *You can use your own device to run the app with [Expo](https://expo.io/)* too.
# Installation
The **uKnow** app it's so easy to install, let's move on:
*Assuming that you are using the expo:*
### Step 1
```sh
$ cd your/environment
$ git clone https://github.com/maateusilva/uknow.git
$ cd uknow
```
### Step 2
Now, open one of your emulators (or both).
### Step 3
In this step we just need to install the app dependencies, to do this, run this command:
```sh
$ yarn install
```
### Step 4 (the last one, I've said it would be easy)
In this step we just need to run our app! So then, run these following commands:
```sh
$ yarn start
```
After app finish to start, you just need to type letter `i` (in your shell) to run in iOS emulator (or device) and/or letter `a` to run in your Android environment.
<file_sep>/src/components/Header/styles.js
import { StyleSheet, Platform } from 'react-native'
import { primary, white } from '../../styles'
export default StyleSheet.create({
container: {
backgroundColor: primary,
height: Platform.OS === 'ios' ? 115 : 80,
paddingTop: 20,
paddingHorizontal: 30
},
appName: {
color: white,
fontSize: 20,
fontWeight: 'bold'
}
})
<file_sep>/src/components/DeckInfo/styles.js
import { StyleSheet } from 'react-native'
import { white, darkGray, gray, primary } from '../../styles'
export default StyleSheet.create({
content: {
flex: 1,
backgroundColor: white,
justifyContent: 'center',
alignItems: 'stretch'
},
deckTitle: {
fontSize: 22,
color: darkGray,
textAlign: 'center',
marginTop: 30,
fontWeight: 'bold'
},
questions: {
fontSize: 16,
color: darkGray,
textAlign: 'center',
marginBottom: 50
},
button: {
backgroundColor: primary,
justifyContent: 'center',
alignItems: 'center',
padding: 20,
marginBottom: 5,
marginHorizontal: 30,
borderRadius: 3
},
buttonText: {
color: white,
fontSize: 14
}
})
<file_sep>/src/components/Button/index.js
import React from 'react'
import { TouchableOpacity, Text } from 'react-native'
import PropTypes from 'prop-types'
import styles from './styles'
const propTypes = {
onPress: PropTypes.func.isRequired,
style: PropTypes.object,
}
function Button ({ onPress, children, style }) {
return (
<TouchableOpacity style={[styles.button, style]} onPress={onPress}>
<Text style={styles.buttonText}>
{children}
</Text>
</TouchableOpacity>
)
}
Button.propTypes = propTypes
export default Button
<file_sep>/src/components/NewQuestion/index.js
import React, { Component } from 'react'
import { connect } from 'react-redux'
import { View, Text, TextInput, Alert } from 'react-native'
import PropTypes from 'prop-types'
import { fetchCreateQuestion } from '../../store/ducks/decks'
import styles from './styles'
import Button from '../Button'
class NewQuestion extends Component {
static propTypes = {
addQuestion: PropTypes.func.isRequired
}
state = {
question: '',
answer: ''
}
handleSubmit = async () => {
const { question, answer } = this.state
const { deckTitle } = this.props.navigation.state.params
if (question.length < 1) {
return Alert.alert('OOPS!', 'You need to type something in Question field.')
}
if (answer.length < 1) {
return Alert.alert('OOPS!', 'You need to type something in Answer field.')
}
try {
await this.props.addQuestion(deckTitle, {
question,
answer
})
this.setState({ question: '', answer: '' })
this.props.navigation.navigate('DeckInfo', { deckId: deckTitle })
} catch (e) {
return Alert.alert('Error', 'An error has occurred while we try to create your Question. Please, try again.')
}
}
render() {
const { question, answer } = this.state
return (
<View style={styles.container}>
<Text style={styles.title}>
Create a new question in {this.props.navigation.state.params.deckTitle}
</Text>
<TextInput
style={[styles.input, {marginTop: 20}]}
autoCorrect={false}
placeholder="Question"
underlineColorAndroid="rgba(0, 0, 0, 0)"
value={question}
onChangeText={question => this.setState({ question })}
/>
<TextInput
style={[styles.input, {marginTop: 10}]}
autoCorrect={false}
placeholder="Answer"
underlineColorAndroid="rgba(0, 0, 0, 0)"
value={answer}
onChangeText={answer => this.setState({ answer })}
/>
<Button onPress={this.handleSubmit}>
Create
</Button>
</View>
)
}
}
const mapDispatchToProps = dispatch => ({
addQuestion: (deck, question) => dispatch(fetchCreateQuestion(deck, question))
})
export default connect(null, mapDispatchToProps)(NewQuestion)
|
705c997d4ca707befaf0b70b30acb44b20beabf4
|
[
"JavaScript",
"Markdown"
] | 6
|
JavaScript
|
maateusilva/uknow
|
4645b93bd3eb149d1928eb759990564d3319c589
|
52d947af6f358cfb9896106a30a0d0ca2aaeb833
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ISIEBackup
{
class Program
{
static void Main(string[] args)
{
string firstPartOfDirectory = Directory.GetCurrentDirectory();
string secondPartOfDirectory = "Config.txt";
string[] config = null;
string timeStamp = DateTime.UtcNow.ToString();
string correctTimeStamp = null;
foreach(char c in timeStamp)
{
if(c.ToString() == "/" || c.ToString() == ":")
{
correctTimeStamp = correctTimeStamp + "-";
}
else
{
correctTimeStamp = correctTimeStamp + c.ToString();
}
}
try
{
config = File.ReadAllLines(firstPartOfDirectory + "\\" + secondPartOfDirectory);
config[1] = config[1] + correctTimeStamp + " " + config[2];
Console.WriteLine("Config geimporteerd.");
Console.WriteLine(config[1]);
}
catch (Exception e)
{
Console.WriteLine("Configbestand is niet gevonden.");
Console.WriteLine(e.ToString());
}
try
{
Console.WriteLine();
File.Copy(config[0], config[1], true);
Console.WriteLine("Aan het kopieeren van " + config[0]);
Console.WriteLine("Naar " + config[1]);
Console.WriteLine();
Console.WriteLine("Bestand gekopieerd");
}
catch (Exception e)
{
Console.WriteLine();
Console.WriteLine("Er is iets fout gegaan, neem contact op met Erik");
Console.WriteLine(e.ToString());
}
Console.WriteLine();
Console.WriteLine("Klik op een knop om programma te sluiten");
Console.ReadKey();
}
}
}
|
7990e0775c76e045e132734b5c769e322020df8f
|
[
"C#"
] | 1
|
C#
|
ErikSteNL/CopyPaster
|
fc0d3eec890acf4bebe71d2e4d855d93f0b552dd
|
3b5e066568bfbe3f7262838d0b71accad5e6de57
|
refs/heads/master
|
<repo_name>sefarash/Diceproject<file_sep>/src/test/java/com/cybertek/SearchTests.java
package com.cybertek;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.Test;
import io.github.bonigarcia.wdm.WebDriverManager;
public class SearchTests {
@Test
public void amazonSearchOne() {
WebDriverManager.chromedriver().setup();
WebDriver driver = new ChromeDriver();
driver.get("http://amazon.com");
String str = "Selenium Testing Tools Cookbook";
driver.findElement(By.id("twotabsearchtextbox")).sendKeys(str+Keys.ENTER);
String xpath = "//h2[@class='a-size-medium s-inline s-access-title a-text-normal'][.='Selenium Testing Tools Cookbook']";
// isDisplayed -> returns true of the element we located is displayed on the page
//Assert.assertTrue(driver.findElement(By.xpath(xpath)).isDisplayed());
driver.findElement(By.id("twotabsearchtextbox")).clear();
driver.findElement(By.id("twotabsearchtextbox")).sendKeys("Java OCA book" +Keys.ENTER);
Assert.assertFalse(driver.findElement(By.xpath(xpath)).isDisplayed());
driver.close();
}
}
|
7c5ca2dbc3904ce0a4d88840462cef041daf7176
|
[
"Java"
] | 1
|
Java
|
sefarash/Diceproject
|
aacf2ae2aa388787d0d0564ea9070e3a592b39a0
|
af37b2ecaffa54e6196c6099b3bef985d94c9f82
|
refs/heads/master
|
<file_sep># Blok1-weektaak2-Stijn-Bruggink<file_sep>#!/usr/bin/env python
Seq = ''
Bestand = open("/home/stijn/Documents/Bio-informatica/blok_1/rna_data_weektaak_2/Zea_mays_mRNA.txt", "r")
for line in Bestand:
if not line.startswith(">"):
Seq = Seq + line
GC_percentage = (((Seq.count('G') + (Seq.count('C'))) / len(Seq)) * 100)
print(len(Seq))
print('Zea mays GC percentage is',GC_percentage, '%')
#GC% whole organism = 46.8248
Seq1 = ''
Bestand1 = open("/home/stijn/Documents/Bio-informatica/blok_1/rna_data_weektaak_2/Gallus_gallus_mRNA.txt", "r")
for line in Bestand1:
if not line.startswith(">"):
Seq1 = Seq1 + line
GC_percentage1 = (((Seq1.count('G') + (Seq1.count('C'))) / len(Seq1)) * 100)
print(len(Seq1))
print('Gallus gallus GC percentage is',GC_percentage1, '%')
#GC% whole organism = 41.9137
Seq2 = ''
Bestand2 = open("/home/stijn/Documents/Bio-informatica/blok_1/rna_data_weektaak_2/Mus_musculus_mRNA.txt", "r")
for line in Bestand2:
if not line.startswith(">"):
Seq2 = Seq2 + line
GC_percentage2 = (((Seq2.count('G') + (Seq2.count('C'))) / len(Seq2)) * 100)
print(len(Seq2))
print('Mus musculus GC percentage is',GC_percentage2, '%')
#GC% whole organism = 42.5
Seq3 = ''
Bestand3 = open("/home/stijn/Documents/Bio-informatica/blok_1/rna_data_weektaak_2/Saccharomyces_cerevisiae_mRNA.txt", "r")
for line in Bestand3:
if not line.startswith(">"):
Seq3 = Seq3 + line
GC_percentage3 = (((Seq3.count('G') + (Seq3.count('C'))) / len(Seq3)) * 100)
print(len(Seq3))
print('Saccharomyces cerevisiae GC percentage is',GC_percentage3, '%')
#GC% whole organism = 38.3758
Seq4 = ''
Bestand4 = open("/home/stijn/Documents/Bio-informatica/blok_1/rna_data_weektaak_2/Pseudomonas_syringae_mRNA.txt", "r")
for line in Bestand4:
if not line.startswith(">"):
Seq4 = Seq4 + line
GC_percentage4 = (((Seq4.count('G') + (Seq4.count('C'))) / len(Seq4)) * 100)
print(len(Seq4))
print('Pseudomonas syringae GC percentage is',GC_percentage4, '%')
#GC% whole organism = 58.7
|
e7bbb1214fa61d549ed7cc6afa4e6da9dfebee60
|
[
"Markdown",
"Python"
] | 2
|
Markdown
|
itbc-bin/Blok1-weektaak2-Stijn-Bruggink
|
ea15db3432f4a7eff0feb1d3896ef6ce1916fe7a
|
29a3640fd40d924b2c749fe284e36b8d178c1244
|
refs/heads/master
|
<repo_name>furdarius/steamprotocol<file_sep>/auth/module.go
package auth
import (
"bytes"
"time"
"crypto/sha1"
"github.com/furdarius/steamprotocol"
"github.com/furdarius/steamprotocol/crypto"
"github.com/furdarius/steamprotocol/messages"
"github.com/furdarius/steamprotocol/protobuf"
"github.com/golang/protobuf/proto"
"github.com/pkg/errors"
)
// Log on with the given details. You must always specify username and
// password. For the first login, don't set an authcode or a hash and you'll receive an error
// and Steam will send you an authcode. Then you have to login again, this time with the authcode.
// Shortly after logging in, you'll receive a MachineAuthUpdateEvent with a hash which allows
// you to login without using an authcode in the future.
//
// If you don't use Steam Guard, username and password are enough
// Details used to auth user
type Details struct {
Username string
Password string
AuthCode string
SharedSecret string
}
// Module used to auth user.
//
// The general gist of a Steam sign on is:
// ChannelEncryptRequest (server->client): The server is asking a user to negotiate
// encryption on the specified universe.
// ChannelEncryptResponse (client->server): The client generates a key and encrypts
// it with the universe public key. The specifics are in the implementation.
// ChannelEncryptResult (server->client): EResult of whether the negotiation was successful.
// ClientLogOn (client->server): Log on to service. Described in Steam and implementation.
// Multi (meta message, server->client): Server sent multiple messages, decompress and process, see implementation.
// ClientLogOnResponse (server->client): EResult of logon, as well as the authoritative steam id,
// session ID (needs to be in every message header like steamid), and the heartbeat interval.
// Every message after ClientLogOn needs the steamid and sessionID set in the header
// ClientGetAppOwnershipTicket (client->server): Client normally requests winui (appid 7) ownership ticket.
// ClientGetAppOwnershipTicketResponse (server->client): response to the above request,
// returns the ownership ticket for the request appid , or an error EResult.
// ClientAccountInfo/EmailInfo/VACBanStatus (server->client): Account info
// ClientFriendsList (server->client): List of friends by steam id. The readable info is sent in PersonaStates.
// ClientLicenseList (server->client): List of licenses, which correspond to subs.
// ClientAuthList (client->server): Request a batch of game connect tokens from Steam
// ClientGameConnectTokens (server->client): Game connect tokens (see topicof tokens/tickets)
// ClientSessionToken (server->client): Used for something!
// ClientCMList (server->client): Authoritive list of CM servers,
// for clients that use the bootstrap list of CM servers. CM servers are Steam servers.
// ClientHeartBeat (client->server): Heartbeat sent to server to signal connection is alive.
// Sent every few seconds, as specified in the LogOnResponse message.
type Module struct {
eventManager *steamprotocol.EventManager
cl *steamprotocol.Client
gen *TOTPGenerator
details Details
sessionKey []byte
steamID uint64
sessionID int32
}
// NewModule initialize new instance of auth Module.
func NewModule(
cl *steamprotocol.Client,
eventManager *steamprotocol.EventManager,
gen *TOTPGenerator,
details Details,
) *Module {
return &Module{
cl: cl,
eventManager: eventManager,
gen: gen,
details: details,
}
}
// Subscribe used to start listen event and packets from eventManager.
func (m *Module) Subscribe() {
m.eventManager.OnEvent(m.handleEvent)
m.eventManager.OnPacket(m.handlePacket)
}
func (m *Module) handleEvent(e interface{}) error {
switch e.(type) {
case crypto.ChannelReadyEvent:
return m.handleChannelEncryptedEvent()
}
return nil
}
func (m *Module) handlePacket(p *steamprotocol.Packet) error {
switch p.Type {
case steamprotocol.EMsg_ClientLogOnResponse:
return m.handleLogOnResponse(p)
case steamprotocol.EMsg_ClientLoggedOff:
return m.handleLoggedOff(p)
case steamprotocol.EMsg_ClientNewLoginKey:
return m.handleNewLoginKey(p)
case steamprotocol.EMsg_ClientUpdateMachineAuth:
return m.handleUpdateMachineAuth(p)
case steamprotocol.EMsg_ClientAccountInfo:
// TODO: return m.handleAccountInfo(cl, p)
}
return nil
}
func (m *Module) handleChannelEncryptedEvent() error {
if len(m.details.Username) == 0 {
return errors.New("empty username")
}
if len(m.details.Password) == 0 {
return errors.New("empty password")
}
responseHeader := messages.NewHeaderProto(steamprotocol.EMsg_ClientLogon)
steamID := steamprotocol.NewIdAdv(
0,
1,
int32(steamprotocol.EUniverse_Public),
int32(steamprotocol.EAccountType_Individual),
)
// Save for sending with SuccessfullyAuthenticatedEvent event
m.steamID = uint64(steamID)
m.sessionID = 0
responseHeader.Data.Steamid = proto.Uint64(m.steamID)
responseHeader.Data.ClientSessionid = proto.Int32(m.sessionID)
responseMsg := &protobuf.CMsgClientLogon{
AccountName: &m.details.Username,
Password: &<PASSWORD>,
ClientLanguage: proto.String("english"),
ProtocolVersion: proto.Uint32(messages.ClientLogonCurrentProtocol),
//ShaSentryfile: []byte{}, // TODO: Get hash from storage
}
if m.details.AuthCode != "" {
responseMsg.AuthCode = proto.String(m.details.AuthCode)
}
if m.details.SharedSecret != "" {
code, err := m.gen.TwoFactorSynced(m.details.SharedSecret)
if err != nil {
return errors.Wrap(err, "failed to fetch two factor code")
}
responseMsg.TwoFactorCode = proto.String(code)
}
buf := new(bytes.Buffer)
err := responseHeader.Serialize(buf)
if err != nil {
return errors.Wrap(err, "failed to serialize header")
}
body, err := proto.Marshal(responseMsg)
if err != nil {
return errors.Wrap(err, "failed to marshal response msg")
}
_, err = buf.Write(body)
if err != nil {
return errors.Wrap(err, "failed to append msg to buffer")
}
err = m.cl.Write(buf.Bytes())
if err != nil {
return errors.Wrap(err, "failed to write data")
}
return nil
}
func (m *Module) handleLogOnResponse(p *steamprotocol.Packet) error {
var (
header *messages.HeaderProto = messages.NewHeaderProto(steamprotocol.EMsg_Invalid)
msg protobuf.CMsgClientLogonResponse
)
dataBuf := bytes.NewBuffer(p.Data)
err := header.Deserialize(dataBuf)
if err != nil {
return errors.Wrap(err, "failed to deserialize logon response header")
}
err = proto.Unmarshal(dataBuf.Bytes(), &msg)
if err != nil {
return errors.Wrap(err, "failed to unmarshal logon response msg")
}
result := steamprotocol.EResult(msg.GetEresult())
if result == steamprotocol.EResult_OK {
return m.eventManager.FireEvent(SuccessfullyAuthenticatedEvent{
Heartbeat: time.Duration(msg.GetOutOfGameHeartbeatSeconds()) * time.Second,
SteamID: m.steamID,
SessionID: m.sessionID,
})
}
return m.eventManager.FireEvent(AuthenticationFailedEvent{
Result: result,
})
}
func (m *Module) handleLoggedOff(p *steamprotocol.Packet) error {
var (
header *messages.HeaderProto = messages.NewHeaderProto(steamprotocol.EMsg_Invalid)
msg protobuf.CMsgClientLoggedOff
)
dataBuf := bytes.NewBuffer(p.Data)
err := header.Deserialize(dataBuf)
if err != nil {
return errors.Wrap(err, "failed to deserialize logged off response header")
}
err = proto.Unmarshal(dataBuf.Bytes(), &msg)
if err != nil {
return errors.Wrap(err, "failed to unmarshal logged off response msg")
}
result := steamprotocol.EResult(msg.GetEresult())
return m.eventManager.FireEvent(LoggedOffEvent{
Result: result,
})
}
func (m *Module) handleNewLoginKey(p *steamprotocol.Packet) error {
var (
header *messages.HeaderProto = messages.NewHeaderProto(steamprotocol.EMsg_Invalid)
msg protobuf.CMsgClientNewLoginKey
)
dataBuf := bytes.NewBuffer(p.Data)
err := header.Deserialize(dataBuf)
if err != nil {
return errors.Wrap(err, "failed to deserialize new login key response header")
}
err = proto.Unmarshal(dataBuf.Bytes(), &msg)
if err != nil {
return errors.Wrap(err, "failed to unmarshal new login key response msg")
}
uniqID := msg.GetUniqueId()
key := msg.GetLoginKey()
responseHeader := messages.NewHeaderProto(steamprotocol.EMsg_ClientNewLoginKeyAccepted)
responseHeader.Data.Steamid = proto.Uint64(m.steamID)
responseHeader.Data.ClientSessionid = proto.Int32(m.sessionID)
responseMsg := &protobuf.CMsgClientNewLoginKeyAccepted{
UniqueId: proto.Uint32(uniqID),
}
buf := new(bytes.Buffer)
err = responseHeader.Serialize(buf)
if err != nil {
return errors.Wrap(err, "failed to serialize header")
}
body, err := proto.Marshal(responseMsg)
if err != nil {
return errors.Wrap(err, "failed to marshal response msg")
}
_, err = buf.Write(body)
if err != nil {
return errors.Wrap(err, "failed to append msg to buffer")
}
err = m.cl.Write(buf.Bytes())
if err != nil {
return errors.Wrap(err, "failed to write data")
}
return m.eventManager.FireEvent(NewLoginKeyAcceptedEvent{
UniqID: uniqID,
Key: key,
})
}
func (m *Module) handleUpdateMachineAuth(p *steamprotocol.Packet) error {
var (
header *messages.HeaderProto = messages.NewHeaderProto(steamprotocol.EMsg_Invalid)
msg protobuf.CMsgClientUpdateMachineAuth
)
dataBuf := bytes.NewBuffer(p.Data)
err := header.Deserialize(dataBuf)
if err != nil {
return errors.Wrap(err, "failed to deserialize new login key response header")
}
err = proto.Unmarshal(dataBuf.Bytes(), &msg)
if err != nil {
return errors.Wrap(err, "failed to unmarshal new login key response msg")
}
hash := sha1.New()
hash.Write(msg.Bytes)
shaHash := hash.Sum(nil)
responseHeader := messages.NewHeaderProto(steamprotocol.EMsg_ClientNewLoginKeyAccepted)
responseHeader.Data.Steamid = proto.Uint64(m.steamID)
responseHeader.Data.ClientSessionid = proto.Int32(m.sessionID)
responseHeader.Data.JobidTarget = header.Data.JobidSource
responseMsg := &protobuf.CMsgClientUpdateMachineAuthResponse{
ShaFile: shaHash,
}
buf := new(bytes.Buffer)
err = responseHeader.Serialize(buf)
if err != nil {
return errors.Wrap(err, "failed to serialize header")
}
body, err := proto.Marshal(responseMsg)
if err != nil {
return errors.Wrap(err, "failed to marshal response msg")
}
_, err = buf.Write(body)
if err != nil {
return errors.Wrap(err, "failed to append msg to buffer")
}
err = m.cl.Write(buf.Bytes())
if err != nil {
return errors.Wrap(err, "failed to write data")
}
return m.eventManager.FireEvent(MachineAuthUpdateEvent{
Hash: shaHash,
})
}
<file_sep>/messages/header_proto.go
package messages
import (
"encoding/binary"
"io"
"github.com/golang/protobuf/proto"
"github.com/furdarius/steamprotocol"
"github.com/furdarius/steamprotocol/protobuf"
)
type HeaderProto struct {
Type steamprotocol.EMsg
HeaderLength int32
Data *protobuf.CMsgProtoBufHeader
}
func NewHeaderProto(msgType steamprotocol.EMsg) *HeaderProto {
return &HeaderProto{
Type: msgType,
Data: &protobuf.CMsgProtoBufHeader{},
}
}
func (m *HeaderProto) Serialize(w io.Writer) error {
buf, err := proto.Marshal(m.Data)
if err != nil {
return err
}
msgType := steamprotocol.EMsg(uint32(m.Type) | steamprotocol.ProtoMask)
err = binary.Write(w, binary.LittleEndian, msgType)
if err != nil {
return err
}
headerLen := int32(len(buf))
err = binary.Write(w, binary.LittleEndian, headerLen)
if err != nil {
return err
}
_, err = w.Write(buf)
if err != nil {
return err
}
return nil
}
func (m *HeaderProto) Deserialize(r io.Reader) error {
var t int32
err := binary.Read(r, binary.LittleEndian, &t)
if err != nil {
return err
}
m.Type = steamprotocol.EMsg(uint32(t) & steamprotocol.EMsgMask)
err = binary.Read(r, binary.LittleEndian, &m.HeaderLength)
if err != nil {
return err
}
buf := make([]byte, m.HeaderLength)
_, err = io.ReadFull(r, buf)
if err != nil {
return err
}
err = proto.Unmarshal(buf, m.Data)
if err != nil {
return err
}
return nil
}
<file_sep>/messages/client_logon.go
package messages
const (
ClientLogonCurrentProtocol uint32 = 65579
)
<file_sep>/messages/encrypt_response.go
package messages
import (
"encoding/binary"
"io"
"github.com/furdarius/steamprotocol"
)
type EncryptResponse struct {
ProtocolVersion uint32
KeySize uint32
}
func NewEncryptResponse(protocolVersion uint32, keySize uint32) *EncryptResponse {
return &EncryptResponse{
ProtocolVersion: protocolVersion,
KeySize: keySize,
}
}
func (m *EncryptResponse) Type() steamprotocol.EMsg {
return steamprotocol.EMsg_ChannelEncryptResponse
}
func (m *EncryptResponse) Serialize(w io.Writer) error {
err := binary.Write(w, binary.LittleEndian, m.ProtocolVersion)
if err != nil {
return err
}
err = binary.Write(w, binary.LittleEndian, m.KeySize)
if err != nil {
return err
}
return nil
}
func (m *EncryptResponse) Deserialize(r io.Reader) error {
err := binary.Read(r, binary.LittleEndian, &m.ProtocolVersion)
if err != nil {
return err
}
err = binary.Read(r, binary.LittleEndian, &m.KeySize)
if err != nil {
return err
}
return nil
}
<file_sep>/cmlist/cmlist.go
package cmlist
import (
"net/http"
"encoding/json"
"math/rand"
"github.com/pkg/errors"
)
type CMList struct {
httpCl *http.Client
serversList []string
websocketsList []string
}
func NewCMList(httpCl *http.Client) *CMList {
return &CMList{
httpCl: httpCl,
}
}
// RefreshList refresh servers and websockets ips list
func (c *CMList) RefreshList() error {
// TODO: Get cellID as param
// 7 used randomly now
resp, err := c.httpCl.Get("https://api.steampowered.com/ISteamDirectory/GetCMList/v1/?cellId=7")
if err != nil {
return errors.Wrap(err, "failed to get cm list from steam api")
}
if resp.StatusCode != 200 {
return errors.New(http.StatusText(resp.StatusCode))
}
type Response struct {
Response struct {
Servers []string `json:"serverlist"`
WebSockets []string `json:"serverlist_websockets"`
Result int `json:"result"`
Message string `json:"message"`
} `json:"response"`
}
var response Response
if err = json.NewDecoder(resp.Body).Decode(&response); err != nil {
return errors.Wrap(err, "failed to decode response")
}
resp.Body.Close()
c.serversList = response.Response.Servers
c.websocketsList = response.Response.WebSockets
return nil
}
// GetRandomServer refresh servers list, if empty and
// return random server ip from list
func (c *CMList) GetRandomServer() (string, error) {
if c.serversList == nil {
err := c.RefreshList()
if err != nil {
return "", errors.Wrap(err, "failed to refresh servers list")
}
}
n := len(c.serversList)
return c.serversList[rand.Intn(n)], nil
}
<file_sep>/client.go
package steamprotocol
import (
"bytes"
"encoding/binary"
"io"
"net"
"time"
"fmt"
"github.com/pkg/errors"
)
const (
// Magic contains in all TCP packets, and must be read after packet length bytes.
Magic uint32 = 0x31305456 // "VT01"
// ProtoMask used to check is it protobuf message.
// Message is proto if expression "rawMsg & ProtoMask > 0" is true.
ProtoMask uint32 = 0x80000000
// EMsgMask used to get EMsg by rawMsg: EMsg(rawMsg & EMsgMask).
// Messages are identified by integer constants known as an EMsg.
EMsgMask = ^ProtoMask
)
// Encryptor used to encrypt data on write and decrypt on read.
// It's required after ChannelEncryptResult message gotten.
type Encryptor interface {
Encrypt(src []byte) ([]byte, error)
Decrypt(src []byte) []byte
}
// Packet is container of message data.
// It's used to broadcast message to packet handlers.
type Packet struct {
Type EMsg
Data []byte
}
// Client implements communication with Steam CM servers.
type Client struct {
conn net.Conn
eventManager *EventManager
crypto Encryptor
}
// NewClient initialize new instance of Client.
func NewClient(conn net.Conn, eventManager *EventManager) *Client {
return &Client{
conn: conn,
eventManager: eventManager,
}
}
// Listen start to read connection with Steam server.
// It uses endless cycle for reading.
func (c *Client) Listen() error {
var (
packetLen uint32
packetMagic uint32
packet *Packet
)
for {
err := binary.Read(c.conn, binary.LittleEndian, &packetLen)
if err != nil {
if err == io.EOF {
time.Sleep(time.Millisecond * 100)
continue
}
return errors.Wrap(err, "failed to read packet length")
}
err = binary.Read(c.conn, binary.LittleEndian, &packetMagic)
if err != nil {
return errors.Wrap(err, "failed to read packet magic")
}
if packetMagic != Magic {
return errors.New("invalid connection magic")
}
// Used to accumulate packet data and then broadcast it to handlers via EventManager
buf := make([]byte, packetLen)
_, err = io.ReadFull(c.conn, buf)
if err != nil {
return errors.Wrap(err, "failed to read packet data to buffer")
}
if c.crypto != nil {
buf = c.crypto.Decrypt(buf)
}
r := bytes.NewReader(buf)
var rawMsg uint32
err = binary.Read(r, binary.LittleEndian, &rawMsg)
if err != nil {
return errors.Wrap(err, "failed to read raw msg")
}
eMsg := EMsg(rawMsg & EMsgMask)
// Костыль, для того, что-бы в handlePacket не перечитывать значения заголовка заново
//startFrom, err := r.Seek(0, io.SeekCurrent)
//if err != nil {
// return errors.Wrap(err, "failed to seek reader position")
//}
packet = &Packet{
Type: eMsg,
Data: buf,
}
err = c.handlePacket(packet)
if err != nil {
return errors.Wrap(err, "failed to handle packet")
}
}
}
// Write is used to write byte array to Steam connection.
func (c *Client) Write(data []byte) (err error) {
if c.conn == nil {
return errors.New("connection is not defined")
}
if c.crypto != nil {
data, err = c.crypto.Encrypt(data)
if err != nil {
return errors.Wrap(err, "failed to encrypt data")
}
}
dataLen := uint32(len(data))
err = binary.Write(c.conn, binary.LittleEndian, dataLen)
if err != nil {
return errors.Wrap(err, "failed to write data len")
}
err = binary.Write(c.conn, binary.LittleEndian, Magic)
if err != nil {
return errors.Wrap(err, "failed to write magic")
}
n, err := c.conn.Write(data)
if err != nil {
return errors.Wrap(err, "failed to write data")
}
if uint32(n) != dataLen {
return errors.Wrap(err, "data wasn't fully sent")
}
return nil
}
func (c *Client) handlePacket(p *Packet) error {
fmt.Println("CLIENT GOT MESSAGE: ", p.Type)
return c.eventManager.FirePacket(p)
}
// SetEncryptor change data Encryptor in Client instance.
func (c *Client) SetEncryptor(enc Encryptor) {
c.crypto = enc
}
<file_sep>/enums.go
// Generated code
// DO NOT EDIT
// Generated code taken from https://github.com/Philipp15b/go-steam/blob/20a77335eb6c0df6eb7c555b4255e5d4091b1254/protocol/steamlang/enums.go
// TODO: Implement code generator
package steamprotocol
import (
"fmt"
"sort"
"strings"
)
type EMsg int32
const (
EMsg_Invalid EMsg = 0
EMsg_Multi EMsg = 1
EMsg_BaseGeneral EMsg = 100
EMsg_GenericReply EMsg = 100
EMsg_DestJobFailed EMsg = 113
EMsg_Alert EMsg = 115
EMsg_SCIDRequest EMsg = 120
EMsg_SCIDResponse EMsg = 121
EMsg_JobHeartbeat EMsg = 123
EMsg_HubConnect EMsg = 124
EMsg_Subscribe EMsg = 126
EMsg_RouteMessage EMsg = 127
EMsg_RemoteSysID EMsg = 128
EMsg_AMCreateAccountResponse EMsg = 129
EMsg_WGRequest EMsg = 130
EMsg_WGResponse EMsg = 131
EMsg_KeepAlive EMsg = 132
EMsg_WebAPIJobRequest EMsg = 133
EMsg_WebAPIJobResponse EMsg = 134
EMsg_ClientSessionStart EMsg = 135
EMsg_ClientSessionEnd EMsg = 136
EMsg_ClientSessionUpdateAuthTicket EMsg = 137
EMsg_StatsDeprecated EMsg = 138 // Deprecated
EMsg_Ping EMsg = 139
EMsg_PingResponse EMsg = 140
EMsg_Stats EMsg = 141
EMsg_RequestFullStatsBlock EMsg = 142
EMsg_LoadDBOCacheItem EMsg = 143
EMsg_LoadDBOCacheItemResponse EMsg = 144
EMsg_InvalidateDBOCacheItems EMsg = 145
EMsg_ServiceMethod EMsg = 146
EMsg_ServiceMethodResponse EMsg = 147
EMsg_BaseShell EMsg = 200
EMsg_AssignSysID EMsg = 200
EMsg_Exit EMsg = 201
EMsg_DirRequest EMsg = 202
EMsg_DirResponse EMsg = 203
EMsg_ZipRequest EMsg = 204
EMsg_ZipResponse EMsg = 205
EMsg_UpdateRecordResponse EMsg = 215
EMsg_UpdateCreditCardRequest EMsg = 221
EMsg_UpdateUserBanResponse EMsg = 225
EMsg_PrepareToExit EMsg = 226
EMsg_ContentDescriptionUpdate EMsg = 227
EMsg_TestResetServer EMsg = 228
EMsg_UniverseChanged EMsg = 229
EMsg_ShellConfigInfoUpdate EMsg = 230
EMsg_RequestWindowsEventLogEntries EMsg = 233
EMsg_ProvideWindowsEventLogEntries EMsg = 234
EMsg_ShellSearchLogs EMsg = 235
EMsg_ShellSearchLogsResponse EMsg = 236
EMsg_ShellCheckWindowsUpdates EMsg = 237
EMsg_ShellCheckWindowsUpdatesResponse EMsg = 238
EMsg_ShellFlushUserLicenseCache EMsg = 239
EMsg_BaseGM EMsg = 300
EMsg_Heartbeat EMsg = 300
EMsg_ShellFailed EMsg = 301
EMsg_ExitShells EMsg = 307
EMsg_ExitShell EMsg = 308
EMsg_GracefulExitShell EMsg = 309
EMsg_NotifyWatchdog EMsg = 314
EMsg_LicenseProcessingComplete EMsg = 316
EMsg_SetTestFlag EMsg = 317
EMsg_QueuedEmailsComplete EMsg = 318
EMsg_GMReportPHPError EMsg = 319
EMsg_GMDRMSync EMsg = 320
EMsg_PhysicalBoxInventory EMsg = 321
EMsg_UpdateConfigFile EMsg = 322
EMsg_TestInitDB EMsg = 323
EMsg_GMWriteConfigToSQL EMsg = 324
EMsg_GMLoadActivationCodes EMsg = 325
EMsg_GMQueueForFBS EMsg = 326
EMsg_GMSchemaConversionResults EMsg = 327
EMsg_GMSchemaConversionResultsResponse EMsg = 328
EMsg_GMWriteShellFailureToSQL EMsg = 329
EMsg_BaseAIS EMsg = 400
EMsg_AISRefreshContentDescription EMsg = 401
EMsg_AISRequestContentDescription EMsg = 402
EMsg_AISUpdateAppInfo EMsg = 403
EMsg_AISUpdatePackageInfo EMsg = 404
EMsg_AISGetPackageChangeNumber EMsg = 405
EMsg_AISGetPackageChangeNumberResponse EMsg = 406
EMsg_AISAppInfoTableChanged EMsg = 407
EMsg_AISUpdatePackageInfoResponse EMsg = 408
EMsg_AISCreateMarketingMessage EMsg = 409
EMsg_AISCreateMarketingMessageResponse EMsg = 410
EMsg_AISGetMarketingMessage EMsg = 411
EMsg_AISGetMarketingMessageResponse EMsg = 412
EMsg_AISUpdateMarketingMessage EMsg = 413
EMsg_AISUpdateMarketingMessageResponse EMsg = 414
EMsg_AISRequestMarketingMessageUpdate EMsg = 415
EMsg_AISDeleteMarketingMessage EMsg = 416
EMsg_AISGetMarketingTreatments EMsg = 419
EMsg_AISGetMarketingTreatmentsResponse EMsg = 420
EMsg_AISRequestMarketingTreatmentUpdate EMsg = 421
EMsg_AISTestAddPackage EMsg = 422
EMsg_AIGetAppGCFlags EMsg = 423
EMsg_AIGetAppGCFlagsResponse EMsg = 424
EMsg_AIGetAppList EMsg = 425
EMsg_AIGetAppListResponse EMsg = 426
EMsg_AIGetAppInfo EMsg = 427
EMsg_AIGetAppInfoResponse EMsg = 428
EMsg_AISGetCouponDefinition EMsg = 429
EMsg_AISGetCouponDefinitionResponse EMsg = 430
EMsg_BaseAM EMsg = 500
EMsg_AMUpdateUserBanRequest EMsg = 504
EMsg_AMAddLicense EMsg = 505
EMsg_AMBeginProcessingLicenses EMsg = 507
EMsg_AMSendSystemIMToUser EMsg = 508
EMsg_AMExtendLicense EMsg = 509
EMsg_AMAddMinutesToLicense EMsg = 510
EMsg_AMCancelLicense EMsg = 511
EMsg_AMInitPurchase EMsg = 512
EMsg_AMPurchaseResponse EMsg = 513
EMsg_AMGetFinalPrice EMsg = 514
EMsg_AMGetFinalPriceResponse EMsg = 515
EMsg_AMGetLegacyGameKey EMsg = 516
EMsg_AMGetLegacyGameKeyResponse EMsg = 517
EMsg_AMFindHungTransactions EMsg = 518
EMsg_AMSetAccountTrustedRequest EMsg = 519
EMsg_AMCompletePurchase EMsg = 521
EMsg_AMCancelPurchase EMsg = 522
EMsg_AMNewChallenge EMsg = 523
EMsg_AMFixPendingPurchaseResponse EMsg = 526
EMsg_AMIsUserBanned EMsg = 527
EMsg_AMRegisterKey EMsg = 528
EMsg_AMLoadActivationCodes EMsg = 529
EMsg_AMLoadActivationCodesResponse EMsg = 530
EMsg_AMLookupKeyResponse EMsg = 531
EMsg_AMLookupKey EMsg = 532
EMsg_AMChatCleanup EMsg = 533
EMsg_AMClanCleanup EMsg = 534
EMsg_AMFixPendingRefund EMsg = 535
EMsg_AMReverseChargeback EMsg = 536
EMsg_AMReverseChargebackResponse EMsg = 537
EMsg_AMClanCleanupList EMsg = 538
EMsg_AMGetLicenses EMsg = 539
EMsg_AMGetLicensesResponse EMsg = 540
EMsg_AllowUserToPlayQuery EMsg = 550
EMsg_AllowUserToPlayResponse EMsg = 551
EMsg_AMVerfiyUser EMsg = 552
EMsg_AMClientNotPlaying EMsg = 553
EMsg_ClientRequestFriendship EMsg = 554
EMsg_AMRelayPublishStatus EMsg = 555
EMsg_AMResetCommunityContent EMsg = 556
EMsg_AMPrimePersonaStateCache EMsg = 557
EMsg_AMAllowUserContentQuery EMsg = 558
EMsg_AMAllowUserContentResponse EMsg = 559
EMsg_AMInitPurchaseResponse EMsg = 560
EMsg_AMRevokePurchaseResponse EMsg = 561
EMsg_AMLockProfile EMsg = 562
EMsg_AMRefreshGuestPasses EMsg = 563
EMsg_AMInviteUserToClan EMsg = 564
EMsg_AMAcknowledgeClanInvite EMsg = 565
EMsg_AMGrantGuestPasses EMsg = 566
EMsg_AMClanDataUpdated EMsg = 567
EMsg_AMReloadAccount EMsg = 568
EMsg_AMClientChatMsgRelay EMsg = 569
EMsg_AMChatMulti EMsg = 570
EMsg_AMClientChatInviteRelay EMsg = 571
EMsg_AMChatInvite EMsg = 572
EMsg_AMClientJoinChatRelay EMsg = 573
EMsg_AMClientChatMemberInfoRelay EMsg = 574
EMsg_AMPublishChatMemberInfo EMsg = 575
EMsg_AMClientAcceptFriendInvite EMsg = 576
EMsg_AMChatEnter EMsg = 577
EMsg_AMClientPublishRemovalFromSource EMsg = 578
EMsg_AMChatActionResult EMsg = 579
EMsg_AMFindAccounts EMsg = 580
EMsg_AMFindAccountsResponse EMsg = 581
EMsg_AMSetAccountFlags EMsg = 584
EMsg_AMCreateClan EMsg = 586
EMsg_AMCreateClanResponse EMsg = 587
EMsg_AMGetClanDetails EMsg = 588
EMsg_AMGetClanDetailsResponse EMsg = 589
EMsg_AMSetPersonaName EMsg = 590
EMsg_AMSetAvatar EMsg = 591
EMsg_AMAuthenticateUser EMsg = 592
EMsg_AMAuthenticateUserResponse EMsg = 593
EMsg_AMGetAccountFriendsCount EMsg = 594
EMsg_AMGetAccountFriendsCountResponse EMsg = 595
EMsg_AMP2PIntroducerMessage EMsg = 596
EMsg_ClientChatAction EMsg = 597
EMsg_AMClientChatActionRelay EMsg = 598
EMsg_BaseVS EMsg = 600
EMsg_ReqChallenge EMsg = 600
EMsg_VACResponse EMsg = 601
EMsg_ReqChallengeTest EMsg = 602
EMsg_VSMarkCheat EMsg = 604
EMsg_VSAddCheat EMsg = 605
EMsg_VSPurgeCodeModDB EMsg = 606
EMsg_VSGetChallengeResults EMsg = 607
EMsg_VSChallengeResultText EMsg = 608
EMsg_VSReportLingerer EMsg = 609
EMsg_VSRequestManagedChallenge EMsg = 610
EMsg_VSLoadDBFinished EMsg = 611
EMsg_BaseDRMS EMsg = 625
EMsg_DRMBuildBlobRequest EMsg = 628
EMsg_DRMBuildBlobResponse EMsg = 629
EMsg_DRMResolveGuidRequest EMsg = 630
EMsg_DRMResolveGuidResponse EMsg = 631
EMsg_DRMVariabilityReport EMsg = 633
EMsg_DRMVariabilityReportResponse EMsg = 634
EMsg_DRMStabilityReport EMsg = 635
EMsg_DRMStabilityReportResponse EMsg = 636
EMsg_DRMDetailsReportRequest EMsg = 637
EMsg_DRMDetailsReportResponse EMsg = 638
EMsg_DRMProcessFile EMsg = 639
EMsg_DRMAdminUpdate EMsg = 640
EMsg_DRMAdminUpdateResponse EMsg = 641
EMsg_DRMSync EMsg = 642
EMsg_DRMSyncResponse EMsg = 643
EMsg_DRMProcessFileResponse EMsg = 644
EMsg_DRMEmptyGuidCache EMsg = 645
EMsg_DRMEmptyGuidCacheResponse EMsg = 646
EMsg_BaseCS EMsg = 650
EMsg_CSUserContentRequest EMsg = 652 // Deprecated
EMsg_BaseClient EMsg = 700
EMsg_ClientLogOn_Deprecated EMsg = 701 // Deprecated
EMsg_ClientAnonLogOn_Deprecated EMsg = 702 // Deprecated
EMsg_ClientHeartBeat EMsg = 703
EMsg_ClientVACResponse EMsg = 704
EMsg_ClientGamesPlayed_obsolete EMsg = 705 // Deprecated
EMsg_ClientLogOff EMsg = 706
EMsg_ClientNoUDPConnectivity EMsg = 707
EMsg_ClientInformOfCreateAccount EMsg = 708
EMsg_ClientAckVACBan EMsg = 709
EMsg_ClientConnectionStats EMsg = 710
EMsg_ClientInitPurchase EMsg = 711
EMsg_ClientPingResponse EMsg = 712
EMsg_ClientRemoveFriend EMsg = 714
EMsg_ClientGamesPlayedNoDataBlob EMsg = 715
EMsg_ClientChangeStatus EMsg = 716
EMsg_ClientVacStatusResponse EMsg = 717
EMsg_ClientFriendMsg EMsg = 718
EMsg_ClientGameConnect_obsolete EMsg = 719 // Deprecated
EMsg_ClientGamesPlayed2_obsolete EMsg = 720 // Deprecated
EMsg_ClientGameEnded_obsolete EMsg = 721 // Deprecated
EMsg_ClientGetFinalPrice EMsg = 722
EMsg_ClientSystemIM EMsg = 726
EMsg_ClientSystemIMAck EMsg = 727
EMsg_ClientGetLicenses EMsg = 728
EMsg_ClientCancelLicense EMsg = 729 // Deprecated
EMsg_ClientGetLegacyGameKey EMsg = 730
EMsg_ClientContentServerLogOn_Deprecated EMsg = 731 // Deprecated
EMsg_ClientAckVACBan2 EMsg = 732
EMsg_ClientAckMessageByGID EMsg = 735 // Deprecated
EMsg_ClientGetPurchaseReceipts EMsg = 736
EMsg_ClientAckPurchaseReceipt EMsg = 737
EMsg_ClientGamesPlayed3_obsolete EMsg = 738 // Deprecated
EMsg_ClientSendGuestPass EMsg = 739
EMsg_ClientAckGuestPass EMsg = 740
EMsg_ClientRedeemGuestPass EMsg = 741
EMsg_ClientGamesPlayed EMsg = 742
EMsg_ClientRegisterKey EMsg = 743
EMsg_ClientInviteUserToClan EMsg = 744
EMsg_ClientAcknowledgeClanInvite EMsg = 745
EMsg_ClientPurchaseWithMachineID EMsg = 746
EMsg_ClientAppUsageEvent EMsg = 747
EMsg_ClientGetGiftTargetList EMsg = 748 // Deprecated
EMsg_ClientGetGiftTargetListResponse EMsg = 749 // Deprecated
EMsg_ClientLogOnResponse EMsg = 751
EMsg_ClientVACChallenge EMsg = 753
EMsg_ClientSetHeartbeatRate EMsg = 755
EMsg_ClientNotLoggedOnDeprecated EMsg = 756 // Deprecated
EMsg_ClientLoggedOff EMsg = 757
EMsg_GSApprove EMsg = 758
EMsg_GSDeny EMsg = 759
EMsg_GSKick EMsg = 760
EMsg_ClientCreateAcctResponse EMsg = 761
EMsg_ClientPurchaseResponse EMsg = 763
EMsg_ClientPing EMsg = 764
EMsg_ClientNOP EMsg = 765
EMsg_ClientPersonaState EMsg = 766
EMsg_ClientFriendsList EMsg = 767
EMsg_ClientAccountInfo EMsg = 768
EMsg_ClientVacStatusQuery EMsg = 770
EMsg_ClientNewsUpdate EMsg = 771
EMsg_ClientGameConnectDeny EMsg = 773
EMsg_GSStatusReply EMsg = 774
EMsg_ClientGetFinalPriceResponse EMsg = 775
EMsg_ClientGameConnectTokens EMsg = 779
EMsg_ClientLicenseList EMsg = 780
EMsg_ClientCancelLicenseResponse EMsg = 781 // Deprecated
EMsg_ClientVACBanStatus EMsg = 782
EMsg_ClientCMList EMsg = 783
EMsg_ClientEncryptPct EMsg = 784
EMsg_ClientGetLegacyGameKeyResponse EMsg = 785
EMsg_ClientFavoritesList EMsg = 786
EMsg_CSUserContentApprove EMsg = 787 // Deprecated
EMsg_CSUserContentDeny EMsg = 788 // Deprecated
EMsg_ClientInitPurchaseResponse EMsg = 789
EMsg_ClientAddFriend EMsg = 791
EMsg_ClientAddFriendResponse EMsg = 792
EMsg_ClientInviteFriend EMsg = 793 // Deprecated
EMsg_ClientInviteFriendResponse EMsg = 794 // Deprecated
EMsg_ClientSendGuestPassResponse EMsg = 795 // Deprecated
EMsg_ClientAckGuestPassResponse EMsg = 796
EMsg_ClientRedeemGuestPassResponse EMsg = 797
EMsg_ClientUpdateGuestPassesList EMsg = 798
EMsg_ClientChatMsg EMsg = 799
EMsg_ClientChatInvite EMsg = 800
EMsg_ClientJoinChat EMsg = 801
EMsg_ClientChatMemberInfo EMsg = 802
EMsg_ClientLogOnWithCredentials_Deprecated EMsg = 803 // Deprecated
EMsg_ClientPasswordChangeResponse EMsg = 805
EMsg_ClientChatEnter EMsg = 807
EMsg_ClientFriendRemovedFromSource EMsg = 808
EMsg_ClientCreateChat EMsg = 809
EMsg_ClientCreateChatResponse EMsg = 810
EMsg_ClientUpdateChatMetadata EMsg = 811
EMsg_ClientP2PIntroducerMessage EMsg = 813
EMsg_ClientChatActionResult EMsg = 814
EMsg_ClientRequestFriendData EMsg = 815
EMsg_ClientGetUserStats EMsg = 818
EMsg_ClientGetUserStatsResponse EMsg = 819
EMsg_ClientStoreUserStats EMsg = 820
EMsg_ClientStoreUserStatsResponse EMsg = 821
EMsg_ClientClanState EMsg = 822
EMsg_ClientServiceModule EMsg = 830
EMsg_ClientServiceCall EMsg = 831
EMsg_ClientServiceCallResponse EMsg = 832
EMsg_ClientPackageInfoRequest EMsg = 833
EMsg_ClientPackageInfoResponse EMsg = 834
EMsg_ClientNatTraversalStatEvent EMsg = 839
EMsg_ClientAppInfoRequest EMsg = 840
EMsg_ClientAppInfoResponse EMsg = 841
EMsg_ClientSteamUsageEvent EMsg = 842
EMsg_ClientCheckPassword EMsg = 845
EMsg_ClientResetPassword EMsg = 846
EMsg_ClientCheckPasswordResponse EMsg = 848
EMsg_ClientResetPasswordResponse EMsg = 849
EMsg_ClientSessionToken EMsg = 850
EMsg_ClientDRMProblemReport EMsg = 851
EMsg_ClientSetIgnoreFriend EMsg = 855
EMsg_ClientSetIgnoreFriendResponse EMsg = 856
EMsg_ClientGetAppOwnershipTicket EMsg = 857
EMsg_ClientGetAppOwnershipTicketResponse EMsg = 858
EMsg_ClientGetLobbyListResponse EMsg = 860
EMsg_ClientGetLobbyMetadata EMsg = 861
EMsg_ClientGetLobbyMetadataResponse EMsg = 862
EMsg_ClientVTTCert EMsg = 863
EMsg_ClientAppInfoUpdate EMsg = 866
EMsg_ClientAppInfoChanges EMsg = 867
EMsg_ClientServerList EMsg = 880
EMsg_ClientEmailChangeResponse EMsg = 891
EMsg_ClientSecretQAChangeResponse EMsg = 892
EMsg_ClientDRMBlobRequest EMsg = 896
EMsg_ClientDRMBlobResponse EMsg = 897
EMsg_ClientLookupKey EMsg = 898
EMsg_ClientLookupKeyResponse EMsg = 899
EMsg_BaseGameServer EMsg = 900
EMsg_GSDisconnectNotice EMsg = 901
EMsg_GSStatus EMsg = 903
EMsg_GSUserPlaying EMsg = 905
EMsg_GSStatus2 EMsg = 906
EMsg_GSStatusUpdate_Unused EMsg = 907
EMsg_GSServerType EMsg = 908
EMsg_GSPlayerList EMsg = 909
EMsg_GSGetUserAchievementStatus EMsg = 910
EMsg_GSGetUserAchievementStatusResponse EMsg = 911
EMsg_GSGetPlayStats EMsg = 918
EMsg_GSGetPlayStatsResponse EMsg = 919
EMsg_GSGetUserGroupStatus EMsg = 920
EMsg_AMGetUserGroupStatus EMsg = 921
EMsg_AMGetUserGroupStatusResponse EMsg = 922
EMsg_GSGetUserGroupStatusResponse EMsg = 923
EMsg_GSGetReputation EMsg = 936
EMsg_GSGetReputationResponse EMsg = 937
EMsg_GSAssociateWithClan EMsg = 938
EMsg_GSAssociateWithClanResponse EMsg = 939
EMsg_GSComputeNewPlayerCompatibility EMsg = 940
EMsg_GSComputeNewPlayerCompatibilityResponse EMsg = 941
EMsg_BaseAdmin EMsg = 1000
EMsg_AdminCmd EMsg = 1000
EMsg_AdminCmdResponse EMsg = 1004
EMsg_AdminLogListenRequest EMsg = 1005
EMsg_AdminLogEvent EMsg = 1006
EMsg_LogSearchRequest EMsg = 1007
EMsg_LogSearchResponse EMsg = 1008
EMsg_LogSearchCancel EMsg = 1009
EMsg_UniverseData EMsg = 1010
EMsg_RequestStatHistory EMsg = 1014
EMsg_StatHistory EMsg = 1015
EMsg_AdminPwLogon EMsg = 1017
EMsg_AdminPwLogonResponse EMsg = 1018
EMsg_AdminSpew EMsg = 1019
EMsg_AdminConsoleTitle EMsg = 1020
EMsg_AdminGCSpew EMsg = 1023
EMsg_AdminGCCommand EMsg = 1024
EMsg_AdminGCGetCommandList EMsg = 1025
EMsg_AdminGCGetCommandListResponse EMsg = 1026
EMsg_FBSConnectionData EMsg = 1027
EMsg_AdminMsgSpew EMsg = 1028
EMsg_BaseFBS EMsg = 1100
EMsg_FBSReqVersion EMsg = 1100
EMsg_FBSVersionInfo EMsg = 1101
EMsg_FBSForceRefresh EMsg = 1102
EMsg_FBSForceBounce EMsg = 1103
EMsg_FBSDeployPackage EMsg = 1104
EMsg_FBSDeployResponse EMsg = 1105
EMsg_FBSUpdateBootstrapper EMsg = 1106
EMsg_FBSSetState EMsg = 1107
EMsg_FBSApplyOSUpdates EMsg = 1108
EMsg_FBSRunCMDScript EMsg = 1109
EMsg_FBSRebootBox EMsg = 1110
EMsg_FBSSetBigBrotherMode EMsg = 1111
EMsg_FBSMinidumpServer EMsg = 1112
EMsg_FBSSetShellCount_obsolete EMsg = 1113 // Deprecated
EMsg_FBSDeployHotFixPackage EMsg = 1114
EMsg_FBSDeployHotFixResponse EMsg = 1115
EMsg_FBSDownloadHotFix EMsg = 1116
EMsg_FBSDownloadHotFixResponse EMsg = 1117
EMsg_FBSUpdateTargetConfigFile EMsg = 1118
EMsg_FBSApplyAccountCred EMsg = 1119
EMsg_FBSApplyAccountCredResponse EMsg = 1120
EMsg_FBSSetShellCount EMsg = 1121
EMsg_FBSTerminateShell EMsg = 1122
EMsg_FBSQueryGMForRequest EMsg = 1123
EMsg_FBSQueryGMResponse EMsg = 1124
EMsg_FBSTerminateZombies EMsg = 1125
EMsg_FBSInfoFromBootstrapper EMsg = 1126
EMsg_FBSRebootBoxResponse EMsg = 1127
EMsg_FBSBootstrapperPackageRequest EMsg = 1128
EMsg_FBSBootstrapperPackageResponse EMsg = 1129
EMsg_FBSBootstrapperGetPackageChunk EMsg = 1130
EMsg_FBSBootstrapperGetPackageChunkResponse EMsg = 1131
EMsg_FBSBootstrapperPackageTransferProgress EMsg = 1132
EMsg_FBSRestartBootstrapper EMsg = 1133
EMsg_BaseFileXfer EMsg = 1200
EMsg_FileXferRequest EMsg = 1200
EMsg_FileXferResponse EMsg = 1201
EMsg_FileXferData EMsg = 1202
EMsg_FileXferEnd EMsg = 1203
EMsg_FileXferDataAck EMsg = 1204
EMsg_BaseChannelAuth EMsg = 1300
EMsg_ChannelAuthChallenge EMsg = 1300
EMsg_ChannelAuthResponse EMsg = 1301
EMsg_ChannelAuthResult EMsg = 1302
EMsg_ChannelEncryptRequest EMsg = 1303
EMsg_ChannelEncryptResponse EMsg = 1304
EMsg_ChannelEncryptResult EMsg = 1305
EMsg_BaseBS EMsg = 1400
EMsg_BSPurchaseStart EMsg = 1401
EMsg_BSPurchaseResponse EMsg = 1402
EMsg_BSSettleNOVA EMsg = 1404
EMsg_BSSettleComplete EMsg = 1406
EMsg_BSBannedRequest EMsg = 1407
EMsg_BSInitPayPalTxn EMsg = 1408
EMsg_BSInitPayPalTxnResponse EMsg = 1409
EMsg_BSGetPayPalUserInfo EMsg = 1410
EMsg_BSGetPayPalUserInfoResponse EMsg = 1411
EMsg_BSRefundTxn EMsg = 1413
EMsg_BSRefundTxnResponse EMsg = 1414
EMsg_BSGetEvents EMsg = 1415
EMsg_BSChaseRFRRequest EMsg = 1416
EMsg_BSPaymentInstrBan EMsg = 1417
EMsg_BSPaymentInstrBanResponse EMsg = 1418
EMsg_BSProcessGCReports EMsg = 1419
EMsg_BSProcessPPReports EMsg = 1420
EMsg_BSInitGCBankXferTxn EMsg = 1421
EMsg_BSInitGCBankXferTxnResponse EMsg = 1422
EMsg_BSQueryGCBankXferTxn EMsg = 1423
EMsg_BSQueryGCBankXferTxnResponse EMsg = 1424
EMsg_BSCommitGCTxn EMsg = 1425
EMsg_BSQueryTransactionStatus EMsg = 1426
EMsg_BSQueryTransactionStatusResponse EMsg = 1427
EMsg_BSQueryCBOrderStatus EMsg = 1428
EMsg_BSQueryCBOrderStatusResponse EMsg = 1429
EMsg_BSRunRedFlagReport EMsg = 1430
EMsg_BSQueryPaymentInstUsage EMsg = 1431
EMsg_BSQueryPaymentInstResponse EMsg = 1432
EMsg_BSQueryTxnExtendedInfo EMsg = 1433
EMsg_BSQueryTxnExtendedInfoResponse EMsg = 1434
EMsg_BSUpdateConversionRates EMsg = 1435
EMsg_BSProcessUSBankReports EMsg = 1436
EMsg_BSPurchaseRunFraudChecks EMsg = 1437
EMsg_BSPurchaseRunFraudChecksResponse EMsg = 1438
EMsg_BSStartShippingJobs EMsg = 1439
EMsg_BSQueryBankInformation EMsg = 1440
EMsg_BSQueryBankInformationResponse EMsg = 1441
EMsg_BSValidateXsollaSignature EMsg = 1445
EMsg_BSValidateXsollaSignatureResponse EMsg = 1446
EMsg_BSQiwiWalletInvoice EMsg = 1448
EMsg_BSQiwiWalletInvoiceResponse EMsg = 1449
EMsg_BSUpdateInventoryFromProPack EMsg = 1450
EMsg_BSUpdateInventoryFromProPackResponse EMsg = 1451
EMsg_BSSendShippingRequest EMsg = 1452
EMsg_BSSendShippingRequestResponse EMsg = 1453
EMsg_BSGetProPackOrderStatus EMsg = 1454
EMsg_BSGetProPackOrderStatusResponse EMsg = 1455
EMsg_BSCheckJobRunning EMsg = 1456
EMsg_BSCheckJobRunningResponse EMsg = 1457
EMsg_BSResetPackagePurchaseRateLimit EMsg = 1458
EMsg_BSResetPackagePurchaseRateLimitResponse EMsg = 1459
EMsg_BSUpdatePaymentData EMsg = 1460
EMsg_BSUpdatePaymentDataResponse EMsg = 1461
EMsg_BSGetBillingAddress EMsg = 1462
EMsg_BSGetBillingAddressResponse EMsg = 1463
EMsg_BSGetCreditCardInfo EMsg = 1464
EMsg_BSGetCreditCardInfoResponse EMsg = 1465
EMsg_BSRemoveExpiredPaymentData EMsg = 1468
EMsg_BSRemoveExpiredPaymentDataResponse EMsg = 1469
EMsg_BSConvertToCurrentKeys EMsg = 1470
EMsg_BSConvertToCurrentKeysResponse EMsg = 1471
EMsg_BSInitPurchase EMsg = 1472
EMsg_BSInitPurchaseResponse EMsg = 1473
EMsg_BSCompletePurchase EMsg = 1474
EMsg_BSCompletePurchaseResponse EMsg = 1475
EMsg_BSPruneCardUsageStats EMsg = 1476
EMsg_BSPruneCardUsageStatsResponse EMsg = 1477
EMsg_BSStoreBankInformation EMsg = 1478
EMsg_BSStoreBankInformationResponse EMsg = 1479
EMsg_BSVerifyPOSAKey EMsg = 1480
EMsg_BSVerifyPOSAKeyResponse EMsg = 1481
EMsg_BSReverseRedeemPOSAKey EMsg = 1482
EMsg_BSReverseRedeemPOSAKeyResponse EMsg = 1483
EMsg_BSQueryFindCreditCard EMsg = 1484
EMsg_BSQueryFindCreditCardResponse EMsg = 1485
EMsg_BSStatusInquiryPOSAKey EMsg = 1486
EMsg_BSStatusInquiryPOSAKeyResponse EMsg = 1487
EMsg_BSValidateMoPaySignature EMsg = 1488
EMsg_BSValidateMoPaySignatureResponse EMsg = 1489
EMsg_BSMoPayConfirmProductDelivery EMsg = 1490
EMsg_BSMoPayConfirmProductDeliveryResponse EMsg = 1491
EMsg_BSGenerateMoPayMD5 EMsg = 1492
EMsg_BSGenerateMoPayMD5Response EMsg = 1493
EMsg_BSBoaCompraConfirmProductDelivery EMsg = 1494
EMsg_BSBoaCompraConfirmProductDeliveryResponse EMsg = 1495
EMsg_BSGenerateBoaCompraMD5 EMsg = 1496
EMsg_BSGenerateBoaCompraMD5Response EMsg = 1497
EMsg_BaseATS EMsg = 1500
EMsg_ATSStartStressTest EMsg = 1501
EMsg_ATSStopStressTest EMsg = 1502
EMsg_ATSRunFailServerTest EMsg = 1503
EMsg_ATSUFSPerfTestTask EMsg = 1504
EMsg_ATSUFSPerfTestResponse EMsg = 1505
EMsg_ATSCycleTCM EMsg = 1506
EMsg_ATSInitDRMSStressTest EMsg = 1507
EMsg_ATSCallTest EMsg = 1508
EMsg_ATSCallTestReply EMsg = 1509
EMsg_ATSStartExternalStress EMsg = 1510
EMsg_ATSExternalStressJobStart EMsg = 1511
EMsg_ATSExternalStressJobQueued EMsg = 1512
EMsg_ATSExternalStressJobRunning EMsg = 1513
EMsg_ATSExternalStressJobStopped EMsg = 1514
EMsg_ATSExternalStressJobStopAll EMsg = 1515
EMsg_ATSExternalStressActionResult EMsg = 1516
EMsg_ATSStarted EMsg = 1517
EMsg_ATSCSPerfTestTask EMsg = 1518
EMsg_ATSCSPerfTestResponse EMsg = 1519
EMsg_BaseDP EMsg = 1600
EMsg_DPSetPublishingState EMsg = 1601
EMsg_DPGamePlayedStats EMsg = 1602
EMsg_DPUniquePlayersStat EMsg = 1603
EMsg_DPVacInfractionStats EMsg = 1605
EMsg_DPVacBanStats EMsg = 1606
EMsg_DPBlockingStats EMsg = 1607
EMsg_DPNatTraversalStats EMsg = 1608
EMsg_DPSteamUsageEvent EMsg = 1609
EMsg_DPVacCertBanStats EMsg = 1610
EMsg_DPVacCafeBanStats EMsg = 1611
EMsg_DPCloudStats EMsg = 1612
EMsg_DPAchievementStats EMsg = 1613
EMsg_DPAccountCreationStats EMsg = 1614
EMsg_DPGetPlayerCount EMsg = 1615
EMsg_DPGetPlayerCountResponse EMsg = 1616
EMsg_DPGameServersPlayersStats EMsg = 1617
EMsg_DPDownloadRateStatistics EMsg = 1618
EMsg_DPFacebookStatistics EMsg = 1619
EMsg_ClientDPCheckSpecialSurvey EMsg = 1620
EMsg_ClientDPCheckSpecialSurveyResponse EMsg = 1621
EMsg_ClientDPSendSpecialSurveyResponse EMsg = 1622
EMsg_ClientDPSendSpecialSurveyResponseReply EMsg = 1623
EMsg_DPStoreSaleStatistics EMsg = 1624
EMsg_ClientDPUpdateAppJobReport EMsg = 1625
EMsg_ClientDPSteam2AppStarted EMsg = 1627 // Deprecated
EMsg_DPUpdateContentEvent EMsg = 1626
EMsg_ClientDPContentStatsReport EMsg = 1630
EMsg_BaseCM EMsg = 1700
EMsg_CMSetAllowState EMsg = 1701
EMsg_CMSpewAllowState EMsg = 1702
EMsg_CMAppInfoResponseDeprecated EMsg = 1703 // Deprecated
EMsg_BaseDSS EMsg = 1800
EMsg_DSSNewFile EMsg = 1801
EMsg_DSSCurrentFileList EMsg = 1802
EMsg_DSSSynchList EMsg = 1803
EMsg_DSSSynchListResponse EMsg = 1804
EMsg_DSSSynchSubscribe EMsg = 1805
EMsg_DSSSynchUnsubscribe EMsg = 1806
EMsg_BaseEPM EMsg = 1900
EMsg_EPMStartProcess EMsg = 1901
EMsg_EPMStopProcess EMsg = 1902
EMsg_EPMRestartProcess EMsg = 1903
EMsg_BaseGC EMsg = 2200
EMsg_GCSendClient EMsg = 2200
EMsg_AMRelayToGC EMsg = 2201
EMsg_GCUpdatePlayedState EMsg = 2202
EMsg_GCCmdRevive EMsg = 2203
EMsg_GCCmdBounce EMsg = 2204
EMsg_GCCmdForceBounce EMsg = 2205
EMsg_GCCmdDown EMsg = 2206
EMsg_GCCmdDeploy EMsg = 2207
EMsg_GCCmdDeployResponse EMsg = 2208
EMsg_GCCmdSwitch EMsg = 2209
EMsg_AMRefreshSessions EMsg = 2210
EMsg_GCUpdateGSState EMsg = 2211
EMsg_GCAchievementAwarded EMsg = 2212
EMsg_GCSystemMessage EMsg = 2213
EMsg_GCValidateSession EMsg = 2214
EMsg_GCValidateSessionResponse EMsg = 2215
EMsg_GCCmdStatus EMsg = 2216
EMsg_GCRegisterWebInterfaces EMsg = 2217 // Deprecated
EMsg_GCRegisterWebInterfaces_Deprecated EMsg = 2217 // Deprecated
EMsg_GCGetAccountDetails EMsg = 2218 // Deprecated
EMsg_GCGetAccountDetails_DEPRECATED EMsg = 2218 // Deprecated
EMsg_GCInterAppMessage EMsg = 2219
EMsg_GCGetEmailTemplate EMsg = 2220
EMsg_GCGetEmailTemplateResponse EMsg = 2221
EMsg_ISRelayToGCH EMsg = 2222
EMsg_GCHRelayClientToIS EMsg = 2223
EMsg_GCHUpdateSession EMsg = 2224
EMsg_GCHRequestUpdateSession EMsg = 2225
EMsg_GCHRequestStatus EMsg = 2226
EMsg_GCHRequestStatusResponse EMsg = 2227
EMsg_BaseP2P EMsg = 2500
EMsg_P2PIntroducerMessage EMsg = 2502
EMsg_BaseSM EMsg = 2900
EMsg_SMExpensiveReport EMsg = 2902
EMsg_SMHourlyReport EMsg = 2903
EMsg_SMFishingReport EMsg = 2904
EMsg_SMPartitionRenames EMsg = 2905
EMsg_SMMonitorSpace EMsg = 2906
EMsg_SMGetSchemaConversionResults EMsg = 2907
EMsg_SMGetSchemaConversionResultsResponse EMsg = 2908
EMsg_BaseTest EMsg = 3000
EMsg_FailServer EMsg = 3000
EMsg_JobHeartbeatTest EMsg = 3001
EMsg_JobHeartbeatTestResponse EMsg = 3002
EMsg_BaseFTSRange EMsg = 3100
EMsg_FTSGetBrowseCounts EMsg = 3101
EMsg_FTSGetBrowseCountsResponse EMsg = 3102
EMsg_FTSBrowseClans EMsg = 3103
EMsg_FTSBrowseClansResponse EMsg = 3104
EMsg_FTSSearchClansByLocation EMsg = 3105
EMsg_FTSSearchClansByLocationResponse EMsg = 3106
EMsg_FTSSearchPlayersByLocation EMsg = 3107
EMsg_FTSSearchPlayersByLocationResponse EMsg = 3108
EMsg_FTSClanDeleted EMsg = 3109
EMsg_FTSSearch EMsg = 3110
EMsg_FTSSearchResponse EMsg = 3111
EMsg_FTSSearchStatus EMsg = 3112
EMsg_FTSSearchStatusResponse EMsg = 3113
EMsg_FTSGetGSPlayStats EMsg = 3114
EMsg_FTSGetGSPlayStatsResponse EMsg = 3115
EMsg_FTSGetGSPlayStatsForServer EMsg = 3116
EMsg_FTSGetGSPlayStatsForServerResponse EMsg = 3117
EMsg_FTSReportIPUpdates EMsg = 3118
EMsg_BaseCCSRange EMsg = 3150
EMsg_CCSGetComments EMsg = 3151
EMsg_CCSGetCommentsResponse EMsg = 3152
EMsg_CCSAddComment EMsg = 3153
EMsg_CCSAddCommentResponse EMsg = 3154
EMsg_CCSDeleteComment EMsg = 3155
EMsg_CCSDeleteCommentResponse EMsg = 3156
EMsg_CCSPreloadComments EMsg = 3157
EMsg_CCSNotifyCommentCount EMsg = 3158
EMsg_CCSGetCommentsForNews EMsg = 3159
EMsg_CCSGetCommentsForNewsResponse EMsg = 3160
EMsg_CCSDeleteAllCommentsByAuthor EMsg = 3161
EMsg_CCSDeleteAllCommentsByAuthorResponse EMsg = 3162
EMsg_BaseLBSRange EMsg = 3200
EMsg_LBSSetScore EMsg = 3201
EMsg_LBSSetScoreResponse EMsg = 3202
EMsg_LBSFindOrCreateLB EMsg = 3203
EMsg_LBSFindOrCreateLBResponse EMsg = 3204
EMsg_LBSGetLBEntries EMsg = 3205
EMsg_LBSGetLBEntriesResponse EMsg = 3206
EMsg_LBSGetLBList EMsg = 3207
EMsg_LBSGetLBListResponse EMsg = 3208
EMsg_LBSSetLBDetails EMsg = 3209
EMsg_LBSDeleteLB EMsg = 3210
EMsg_LBSDeleteLBEntry EMsg = 3211
EMsg_LBSResetLB EMsg = 3212
EMsg_BaseOGS EMsg = 3400
EMsg_OGSBeginSession EMsg = 3401
EMsg_OGSBeginSessionResponse EMsg = 3402
EMsg_OGSEndSession EMsg = 3403
EMsg_OGSEndSessionResponse EMsg = 3404
EMsg_OGSWriteAppSessionRow EMsg = 3406
EMsg_BaseBRP EMsg = 3600
EMsg_BRPStartShippingJobs EMsg = 3601
EMsg_BRPProcessUSBankReports EMsg = 3602
EMsg_BRPProcessGCReports EMsg = 3603
EMsg_BRPProcessPPReports EMsg = 3604
EMsg_BRPSettleNOVA EMsg = 3605
EMsg_BRPSettleCB EMsg = 3606
EMsg_BRPCommitGC EMsg = 3607
EMsg_BRPCommitGCResponse EMsg = 3608
EMsg_BRPFindHungTransactions EMsg = 3609
EMsg_BRPCheckFinanceCloseOutDate EMsg = 3610
EMsg_BRPProcessLicenses EMsg = 3611
EMsg_BRPProcessLicensesResponse EMsg = 3612
EMsg_BRPRemoveExpiredPaymentData EMsg = 3613
EMsg_BRPRemoveExpiredPaymentDataResponse EMsg = 3614
EMsg_BRPConvertToCurrentKeys EMsg = 3615
EMsg_BRPConvertToCurrentKeysResponse EMsg = 3616
EMsg_BRPPruneCardUsageStats EMsg = 3617
EMsg_BRPPruneCardUsageStatsResponse EMsg = 3618
EMsg_BRPCheckActivationCodes EMsg = 3619
EMsg_BRPCheckActivationCodesResponse EMsg = 3620
EMsg_BaseAMRange2 EMsg = 4000
EMsg_AMCreateChat EMsg = 4001
EMsg_AMCreateChatResponse EMsg = 4002
EMsg_AMUpdateChatMetadata EMsg = 4003
EMsg_AMPublishChatMetadata EMsg = 4004
EMsg_AMSetProfileURL EMsg = 4005
EMsg_AMGetAccountEmailAddress EMsg = 4006
EMsg_AMGetAccountEmailAddressResponse EMsg = 4007
EMsg_AMRequestFriendData EMsg = 4008
EMsg_AMRouteToClients EMsg = 4009
EMsg_AMLeaveClan EMsg = 4010
EMsg_AMClanPermissions EMsg = 4011
EMsg_AMClanPermissionsResponse EMsg = 4012
EMsg_AMCreateClanEvent EMsg = 4013
EMsg_AMCreateClanEventResponse EMsg = 4014
EMsg_AMUpdateClanEvent EMsg = 4015
EMsg_AMUpdateClanEventResponse EMsg = 4016
EMsg_AMGetClanEvents EMsg = 4017
EMsg_AMGetClanEventsResponse EMsg = 4018
EMsg_AMDeleteClanEvent EMsg = 4019
EMsg_AMDeleteClanEventResponse EMsg = 4020
EMsg_AMSetClanPermissionSettings EMsg = 4021
EMsg_AMSetClanPermissionSettingsResponse EMsg = 4022
EMsg_AMGetClanPermissionSettings EMsg = 4023
EMsg_AMGetClanPermissionSettingsResponse EMsg = 4024
EMsg_AMPublishChatRoomInfo EMsg = 4025
EMsg_ClientChatRoomInfo EMsg = 4026
EMsg_AMCreateClanAnnouncement EMsg = 4027
EMsg_AMCreateClanAnnouncementResponse EMsg = 4028
EMsg_AMUpdateClanAnnouncement EMsg = 4029
EMsg_AMUpdateClanAnnouncementResponse EMsg = 4030
EMsg_AMGetClanAnnouncementsCount EMsg = 4031
EMsg_AMGetClanAnnouncementsCountResponse EMsg = 4032
EMsg_AMGetClanAnnouncements EMsg = 4033
EMsg_AMGetClanAnnouncementsResponse EMsg = 4034
EMsg_AMDeleteClanAnnouncement EMsg = 4035
EMsg_AMDeleteClanAnnouncementResponse EMsg = 4036
EMsg_AMGetSingleClanAnnouncement EMsg = 4037
EMsg_AMGetSingleClanAnnouncementResponse EMsg = 4038
EMsg_AMGetClanHistory EMsg = 4039
EMsg_AMGetClanHistoryResponse EMsg = 4040
EMsg_AMGetClanPermissionBits EMsg = 4041
EMsg_AMGetClanPermissionBitsResponse EMsg = 4042
EMsg_AMSetClanPermissionBits EMsg = 4043
EMsg_AMSetClanPermissionBitsResponse EMsg = 4044
EMsg_AMSessionInfoRequest EMsg = 4045
EMsg_AMSessionInfoResponse EMsg = 4046
EMsg_AMValidateWGToken EMsg = 4047
EMsg_AMGetSingleClanEvent EMsg = 4048
EMsg_AMGetSingleClanEventResponse EMsg = 4049
EMsg_AMGetClanRank EMsg = 4050
EMsg_AMGetClanRankResponse EMsg = 4051
EMsg_AMSetClanRank EMsg = 4052
EMsg_AMSetClanRankResponse EMsg = 4053
EMsg_AMGetClanPOTW EMsg = 4054
EMsg_AMGetClanPOTWResponse EMsg = 4055
EMsg_AMSetClanPOTW EMsg = 4056
EMsg_AMSetClanPOTWResponse EMsg = 4057
EMsg_AMRequestChatMetadata EMsg = 4058
EMsg_AMDumpUser EMsg = 4059
EMsg_AMKickUserFromClan EMsg = 4060
EMsg_AMAddFounderToClan EMsg = 4061
EMsg_AMValidateWGTokenResponse EMsg = 4062
EMsg_AMSetCommunityState EMsg = 4063
EMsg_AMSetAccountDetails EMsg = 4064
EMsg_AMGetChatBanList EMsg = 4065
EMsg_AMGetChatBanListResponse EMsg = 4066
EMsg_AMUnBanFromChat EMsg = 4067
EMsg_AMSetClanDetails EMsg = 4068
EMsg_AMGetAccountLinks EMsg = 4069
EMsg_AMGetAccountLinksResponse EMsg = 4070
EMsg_AMSetAccountLinks EMsg = 4071
EMsg_AMSetAccountLinksResponse EMsg = 4072
EMsg_AMGetUserGameStats EMsg = 4073
EMsg_AMGetUserGameStatsResponse EMsg = 4074
EMsg_AMCheckClanMembership EMsg = 4075
EMsg_AMGetClanMembers EMsg = 4076
EMsg_AMGetClanMembersResponse EMsg = 4077
EMsg_AMJoinPublicClan EMsg = 4078
EMsg_AMNotifyChatOfClanChange EMsg = 4079
EMsg_AMResubmitPurchase EMsg = 4080
EMsg_AMAddFriend EMsg = 4081
EMsg_AMAddFriendResponse EMsg = 4082
EMsg_AMRemoveFriend EMsg = 4083
EMsg_AMDumpClan EMsg = 4084
EMsg_AMChangeClanOwner EMsg = 4085
EMsg_AMCancelEasyCollect EMsg = 4086
EMsg_AMCancelEasyCollectResponse EMsg = 4087
EMsg_AMGetClanMembershipList EMsg = 4088
EMsg_AMGetClanMembershipListResponse EMsg = 4089
EMsg_AMClansInCommon EMsg = 4090
EMsg_AMClansInCommonResponse EMsg = 4091
EMsg_AMIsValidAccountID EMsg = 4092
EMsg_AMConvertClan EMsg = 4093
EMsg_AMGetGiftTargetListRelay EMsg = 4094
EMsg_AMWipeFriendsList EMsg = 4095
EMsg_AMSetIgnored EMsg = 4096
EMsg_AMClansInCommonCountResponse EMsg = 4097
EMsg_AMFriendsList EMsg = 4098
EMsg_AMFriendsListResponse EMsg = 4099
EMsg_AMFriendsInCommon EMsg = 4100
EMsg_AMFriendsInCommonResponse EMsg = 4101
EMsg_AMFriendsInCommonCountResponse EMsg = 4102
EMsg_AMClansInCommonCount EMsg = 4103
EMsg_AMChallengeVerdict EMsg = 4104
EMsg_AMChallengeNotification EMsg = 4105
EMsg_AMFindGSByIP EMsg = 4106
EMsg_AMFoundGSByIP EMsg = 4107
EMsg_AMGiftRevoked EMsg = 4108
EMsg_AMCreateAccountRecord EMsg = 4109
EMsg_AMUserClanList EMsg = 4110
EMsg_AMUserClanListResponse EMsg = 4111
EMsg_AMGetAccountDetails2 EMsg = 4112
EMsg_AMGetAccountDetailsResponse2 EMsg = 4113
EMsg_AMSetCommunityProfileSettings EMsg = 4114
EMsg_AMSetCommunityProfileSettingsResponse EMsg = 4115
EMsg_AMGetCommunityPrivacyState EMsg = 4116
EMsg_AMGetCommunityPrivacyStateResponse EMsg = 4117
EMsg_AMCheckClanInviteRateLimiting EMsg = 4118
EMsg_AMGetUserAchievementStatus EMsg = 4119
EMsg_AMGetIgnored EMsg = 4120
EMsg_AMGetIgnoredResponse EMsg = 4121
EMsg_AMSetIgnoredResponse EMsg = 4122
EMsg_AMSetFriendRelationshipNone EMsg = 4123
EMsg_AMGetFriendRelationship EMsg = 4124
EMsg_AMGetFriendRelationshipResponse EMsg = 4125
EMsg_AMServiceModulesCache EMsg = 4126
EMsg_AMServiceModulesCall EMsg = 4127
EMsg_AMServiceModulesCallResponse EMsg = 4128
EMsg_AMGetCaptchaDataForIP EMsg = 4129
EMsg_AMGetCaptchaDataForIPResponse EMsg = 4130
EMsg_AMValidateCaptchaDataForIP EMsg = 4131
EMsg_AMValidateCaptchaDataForIPResponse EMsg = 4132
EMsg_AMTrackFailedAuthByIP EMsg = 4133
EMsg_AMGetCaptchaDataByGID EMsg = 4134
EMsg_AMGetCaptchaDataByGIDResponse EMsg = 4135
EMsg_AMGetLobbyList EMsg = 4136
EMsg_AMGetLobbyListResponse EMsg = 4137
EMsg_AMGetLobbyMetadata EMsg = 4138
EMsg_AMGetLobbyMetadataResponse EMsg = 4139
EMsg_CommunityAddFriendNews EMsg = 4140
EMsg_AMAddClanNews EMsg = 4141
EMsg_AMWriteNews EMsg = 4142
EMsg_AMFindClanUser EMsg = 4143
EMsg_AMFindClanUserResponse EMsg = 4144
EMsg_AMBanFromChat EMsg = 4145
EMsg_AMGetUserHistoryResponse EMsg = 4146
EMsg_AMGetUserNewsSubscriptions EMsg = 4147
EMsg_AMGetUserNewsSubscriptionsResponse EMsg = 4148
EMsg_AMSetUserNewsSubscriptions EMsg = 4149
EMsg_AMGetUserNews EMsg = 4150
EMsg_AMGetUserNewsResponse EMsg = 4151
EMsg_AMSendQueuedEmails EMsg = 4152
EMsg_AMSetLicenseFlags EMsg = 4153
EMsg_AMGetUserHistory EMsg = 4154
EMsg_CommunityDeleteUserNews EMsg = 4155
EMsg_AMAllowUserFilesRequest EMsg = 4156
EMsg_AMAllowUserFilesResponse EMsg = 4157
EMsg_AMGetAccountStatus EMsg = 4158
EMsg_AMGetAccountStatusResponse EMsg = 4159
EMsg_AMEditBanReason EMsg = 4160
EMsg_AMCheckClanMembershipResponse EMsg = 4161
EMsg_AMProbeClanMembershipList EMsg = 4162
EMsg_AMProbeClanMembershipListResponse EMsg = 4163
EMsg_AMGetFriendsLobbies EMsg = 4165
EMsg_AMGetFriendsLobbiesResponse EMsg = 4166
EMsg_AMGetUserFriendNewsResponse EMsg = 4172
EMsg_CommunityGetUserFriendNews EMsg = 4173
EMsg_AMGetUserClansNewsResponse EMsg = 4174
EMsg_AMGetUserClansNews EMsg = 4175
EMsg_AMStoreInitPurchase EMsg = 4176
EMsg_AMStoreInitPurchaseResponse EMsg = 4177
EMsg_AMStoreGetFinalPrice EMsg = 4178
EMsg_AMStoreGetFinalPriceResponse EMsg = 4179
EMsg_AMStoreCompletePurchase EMsg = 4180
EMsg_AMStoreCancelPurchase EMsg = 4181
EMsg_AMStorePurchaseResponse EMsg = 4182
EMsg_AMCreateAccountRecordInSteam3 EMsg = 4183
EMsg_AMGetPreviousCBAccount EMsg = 4184
EMsg_AMGetPreviousCBAccountResponse EMsg = 4185
EMsg_AMUpdateBillingAddress EMsg = 4186
EMsg_AMUpdateBillingAddressResponse EMsg = 4187
EMsg_AMGetBillingAddress EMsg = 4188
EMsg_AMGetBillingAddressResponse EMsg = 4189
EMsg_AMGetUserLicenseHistory EMsg = 4190
EMsg_AMGetUserLicenseHistoryResponse EMsg = 4191
EMsg_AMSupportChangePassword EMsg = 4194
EMsg_AMSupportChangeEmail EMsg = 4195
EMsg_AMSupportChangeSecretQA EMsg = 4196
EMsg_AMResetUserVerificationGSByIP EMsg = 4197
EMsg_AMUpdateGSPlayStats EMsg = 4198
EMsg_AMSupportEnableOrDisable EMsg = 4199
EMsg_AMGetComments EMsg = 4200
EMsg_AMGetCommentsResponse EMsg = 4201
EMsg_AMAddComment EMsg = 4202
EMsg_AMAddCommentResponse EMsg = 4203
EMsg_AMDeleteComment EMsg = 4204
EMsg_AMDeleteCommentResponse EMsg = 4205
EMsg_AMGetPurchaseStatus EMsg = 4206
EMsg_AMSupportIsAccountEnabled EMsg = 4209
EMsg_AMSupportIsAccountEnabledResponse EMsg = 4210
EMsg_AMGetUserStats EMsg = 4211
EMsg_AMSupportKickSession EMsg = 4212
EMsg_AMGSSearch EMsg = 4213
EMsg_MarketingMessageUpdate EMsg = 4216
EMsg_AMRouteFriendMsg EMsg = 4219
EMsg_AMTicketAuthRequestOrResponse EMsg = 4220
EMsg_AMVerifyDepotManagementRights EMsg = 4222
EMsg_AMVerifyDepotManagementRightsResponse EMsg = 4223
EMsg_AMAddFreeLicense EMsg = 4224
EMsg_AMGetUserFriendsMinutesPlayed EMsg = 4225
EMsg_AMGetUserFriendsMinutesPlayedResponse EMsg = 4226
EMsg_AMGetUserMinutesPlayed EMsg = 4227
EMsg_AMGetUserMinutesPlayedResponse EMsg = 4228
EMsg_AMValidateEmailLink EMsg = 4231
EMsg_AMValidateEmailLinkResponse EMsg = 4232
EMsg_AMAddUsersToMarketingTreatment EMsg = 4234
EMsg_AMStoreUserStats EMsg = 4236
EMsg_AMGetUserGameplayInfo EMsg = 4237
EMsg_AMGetUserGameplayInfoResponse EMsg = 4238
EMsg_AMGetCardList EMsg = 4239
EMsg_AMGetCardListResponse EMsg = 4240
EMsg_AMDeleteStoredCard EMsg = 4241
EMsg_AMRevokeLegacyGameKeys EMsg = 4242
EMsg_AMGetWalletDetails EMsg = 4244
EMsg_AMGetWalletDetailsResponse EMsg = 4245
EMsg_AMDeleteStoredPaymentInfo EMsg = 4246
EMsg_AMGetStoredPaymentSummary EMsg = 4247
EMsg_AMGetStoredPaymentSummaryResponse EMsg = 4248
EMsg_AMGetWalletConversionRate EMsg = 4249
EMsg_AMGetWalletConversionRateResponse EMsg = 4250
EMsg_AMConvertWallet EMsg = 4251
EMsg_AMConvertWalletResponse EMsg = 4252
EMsg_AMRelayGetFriendsWhoPlayGame EMsg = 4253
EMsg_AMRelayGetFriendsWhoPlayGameResponse EMsg = 4254
EMsg_AMSetPreApproval EMsg = 4255
EMsg_AMSetPreApprovalResponse EMsg = 4256
EMsg_AMMarketingTreatmentUpdate EMsg = 4257
EMsg_AMCreateRefund EMsg = 4258
EMsg_AMCreateRefundResponse EMsg = 4259
EMsg_AMCreateChargeback EMsg = 4260
EMsg_AMCreateChargebackResponse EMsg = 4261
EMsg_AMCreateDispute EMsg = 4262
EMsg_AMCreateDisputeResponse EMsg = 4263
EMsg_AMClearDispute EMsg = 4264
EMsg_AMClearDisputeResponse EMsg = 4265
EMsg_AMPlayerNicknameList EMsg = 4266
EMsg_AMPlayerNicknameListResponse EMsg = 4267
EMsg_AMSetDRMTestConfig EMsg = 4268
EMsg_AMGetUserCurrentGameInfo EMsg = 4269
EMsg_AMGetUserCurrentGameInfoResponse EMsg = 4270
EMsg_AMGetGSPlayerList EMsg = 4271
EMsg_AMGetGSPlayerListResponse EMsg = 4272
EMsg_AMUpdatePersonaStateCache EMsg = 4275
EMsg_AMGetGameMembers EMsg = 4276
EMsg_AMGetGameMembersResponse EMsg = 4277
EMsg_AMGetSteamIDForMicroTxn EMsg = 4278
EMsg_AMGetSteamIDForMicroTxnResponse EMsg = 4279
EMsg_AMAddPublisherUser EMsg = 4280
EMsg_AMRemovePublisherUser EMsg = 4281
EMsg_AMGetUserLicenseList EMsg = 4282
EMsg_AMGetUserLicenseListResponse EMsg = 4283
EMsg_AMReloadGameGroupPolicy EMsg = 4284
EMsg_AMAddFreeLicenseResponse EMsg = 4285
EMsg_AMVACStatusUpdate EMsg = 4286
EMsg_AMGetAccountDetails EMsg = 4287
EMsg_AMGetAccountDetailsResponse EMsg = 4288
EMsg_AMGetPlayerLinkDetails EMsg = 4289
EMsg_AMGetPlayerLinkDetailsResponse EMsg = 4290
EMsg_AMSubscribeToPersonaFeed EMsg = 4291
EMsg_AMGetUserVacBanList EMsg = 4292
EMsg_AMGetUserVacBanListResponse EMsg = 4293
EMsg_AMGetAccountFlagsForWGSpoofing EMsg = 4294
EMsg_AMGetAccountFlagsForWGSpoofingResponse EMsg = 4295
EMsg_AMGetFriendsWishlistInfo EMsg = 4296
EMsg_AMGetFriendsWishlistInfoResponse EMsg = 4297
EMsg_AMGetClanOfficers EMsg = 4298
EMsg_AMGetClanOfficersResponse EMsg = 4299
EMsg_AMNameChange EMsg = 4300
EMsg_AMGetNameHistory EMsg = 4301
EMsg_AMGetNameHistoryResponse EMsg = 4302
EMsg_AMUpdateProviderStatus EMsg = 4305
EMsg_AMClearPersonaMetadataBlob EMsg = 4306
EMsg_AMSupportRemoveAccountSecurity EMsg = 4307
EMsg_AMIsAccountInCaptchaGracePeriod EMsg = 4308
EMsg_AMIsAccountInCaptchaGracePeriodResponse EMsg = 4309
EMsg_AMAccountPS3Unlink EMsg = 4310
EMsg_AMAccountPS3UnlinkResponse EMsg = 4311
EMsg_AMStoreUserStatsResponse EMsg = 4312
EMsg_AMGetAccountPSNInfo EMsg = 4313
EMsg_AMGetAccountPSNInfoResponse EMsg = 4314
EMsg_AMAuthenticatedPlayerList EMsg = 4315
EMsg_AMGetUserGifts EMsg = 4316
EMsg_AMGetUserGiftsResponse EMsg = 4317
EMsg_AMTransferLockedGifts EMsg = 4320
EMsg_AMTransferLockedGiftsResponse EMsg = 4321
EMsg_AMPlayerHostedOnGameServer EMsg = 4322
EMsg_AMGetAccountBanInfo EMsg = 4323
EMsg_AMGetAccountBanInfoResponse EMsg = 4324
EMsg_AMRecordBanEnforcement EMsg = 4325
EMsg_AMRollbackGiftTransfer EMsg = 4326
EMsg_AMRollbackGiftTransferResponse EMsg = 4327
EMsg_AMHandlePendingTransaction EMsg = 4328
EMsg_AMRequestClanDetails EMsg = 4329
EMsg_AMDeleteStoredPaypalAgreement EMsg = 4330
EMsg_AMGameServerUpdate EMsg = 4331
EMsg_AMGameServerRemove EMsg = 4332
EMsg_AMGetPaypalAgreements EMsg = 4333
EMsg_AMGetPaypalAgreementsResponse EMsg = 4334
EMsg_AMGameServerPlayerCompatibilityCheck EMsg = 4335
EMsg_AMGameServerPlayerCompatibilityCheckResponse EMsg = 4336
EMsg_AMRenewLicense EMsg = 4337
EMsg_AMGetAccountCommunityBanInfo EMsg = 4338
EMsg_AMGetAccountCommunityBanInfoResponse EMsg = 4339
EMsg_AMGameServerAccountChangePassword EMsg = 4340
EMsg_AMGameServerAccountDeleteAccount EMsg = 4341
EMsg_AMRenewAgreement EMsg = 4342
EMsg_AMSendEmail EMsg = 4343
EMsg_AMXsollaPayment EMsg = 4344
EMsg_AMXsollaPaymentResponse EMsg = 4345
EMsg_AMAcctAllowedToPurchase EMsg = 4346
EMsg_AMAcctAllowedToPurchaseResponse EMsg = 4347
EMsg_AMSwapKioskDeposit EMsg = 4348
EMsg_AMSwapKioskDepositResponse EMsg = 4349
EMsg_AMSetUserGiftUnowned EMsg = 4350
EMsg_AMSetUserGiftUnownedResponse EMsg = 4351
EMsg_AMClaimUnownedUserGift EMsg = 4352
EMsg_AMClaimUnownedUserGiftResponse EMsg = 4353
EMsg_AMSetClanName EMsg = 4354
EMsg_AMSetClanNameResponse EMsg = 4355
EMsg_AMGrantCoupon EMsg = 4356
EMsg_AMGrantCouponResponse EMsg = 4357
EMsg_AMIsPackageRestrictedInUserCountry EMsg = 4358
EMsg_AMIsPackageRestrictedInUserCountryResponse EMsg = 4359
EMsg_AMHandlePendingTransactionResponse EMsg = 4360
EMsg_AMGrantGuestPasses2 EMsg = 4361
EMsg_AMGrantGuestPasses2Response EMsg = 4362
EMsg_AMSessionQuery EMsg = 4363
EMsg_AMSessionQueryResponse EMsg = 4364
EMsg_AMGetPlayerBanDetails EMsg = 4365
EMsg_AMGetPlayerBanDetailsResponse EMsg = 4366
EMsg_AMFinalizePurchase EMsg = 4367
EMsg_AMFinalizePurchaseResponse EMsg = 4368
EMsg_AMPersonaChangeResponse EMsg = 4372
EMsg_AMGetClanDetailsForForumCreation EMsg = 4373
EMsg_AMGetClanDetailsForForumCreationResponse EMsg = 4374
EMsg_AMGetPendingNotificationCount EMsg = 4375
EMsg_AMGetPendingNotificationCountResponse EMsg = 4376
EMsg_AMPasswordHashUpgrade EMsg = 4377
EMsg_AMMoPayPayment EMsg = 4378
EMsg_AMMoPayPaymentResponse EMsg = 4379
EMsg_AMBoaCompraPayment EMsg = 4380
EMsg_AMBoaCompraPaymentResponse EMsg = 4381
EMsg_AMExpireCaptchaByGID EMsg = 4382
EMsg_AMCompleteExternalPurchase EMsg = 4383
EMsg_AMCompleteExternalPurchaseResponse EMsg = 4384
EMsg_AMResolveNegativeWalletCredits EMsg = 4385
EMsg_AMResolveNegativeWalletCreditsResponse EMsg = 4386
EMsg_AMPayelpPayment EMsg = 4387
EMsg_AMPayelpPaymentResponse EMsg = 4388
EMsg_AMPlayerGetClanBasicDetails EMsg = 4389
EMsg_AMPlayerGetClanBasicDetailsResponse EMsg = 4390
EMsg_AMTwoFactorRecoverAuthenticatorRequest EMsg = 4402
EMsg_AMTwoFactorRecoverAuthenticatorResponse EMsg = 4403
EMsg_AMValidatePasswordResetCodeAndSendSmsRequest EMsg = 4406
EMsg_AMValidatePasswordResetCodeAndSendSmsResponse EMsg = 4407
EMsg_AMGetAccountResetDetailsRequest EMsg = 4408
EMsg_AMGetAccountResetDetailsResponse EMsg = 4409
EMsg_BasePSRange EMsg = 5000
EMsg_PSCreateShoppingCart EMsg = 5001
EMsg_PSCreateShoppingCartResponse EMsg = 5002
EMsg_PSIsValidShoppingCart EMsg = 5003
EMsg_PSIsValidShoppingCartResponse EMsg = 5004
EMsg_PSAddPackageToShoppingCart EMsg = 5005
EMsg_PSAddPackageToShoppingCartResponse EMsg = 5006
EMsg_PSRemoveLineItemFromShoppingCart EMsg = 5007
EMsg_PSRemoveLineItemFromShoppingCartResponse EMsg = 5008
EMsg_PSGetShoppingCartContents EMsg = 5009
EMsg_PSGetShoppingCartContentsResponse EMsg = 5010
EMsg_PSAddWalletCreditToShoppingCart EMsg = 5011
EMsg_PSAddWalletCreditToShoppingCartResponse EMsg = 5012
EMsg_BaseUFSRange EMsg = 5200
EMsg_ClientUFSUploadFileRequest EMsg = 5202
EMsg_ClientUFSUploadFileResponse EMsg = 5203
EMsg_ClientUFSUploadFileChunk EMsg = 5204
EMsg_ClientUFSUploadFileFinished EMsg = 5205
EMsg_ClientUFSGetFileListForApp EMsg = 5206
EMsg_ClientUFSGetFileListForAppResponse EMsg = 5207
EMsg_ClientUFSDownloadRequest EMsg = 5210
EMsg_ClientUFSDownloadResponse EMsg = 5211
EMsg_ClientUFSDownloadChunk EMsg = 5212
EMsg_ClientUFSLoginRequest EMsg = 5213
EMsg_ClientUFSLoginResponse EMsg = 5214
EMsg_UFSReloadPartitionInfo EMsg = 5215
EMsg_ClientUFSTransferHeartbeat EMsg = 5216
EMsg_UFSSynchronizeFile EMsg = 5217
EMsg_UFSSynchronizeFileResponse EMsg = 5218
EMsg_ClientUFSDeleteFileRequest EMsg = 5219
EMsg_ClientUFSDeleteFileResponse EMsg = 5220
EMsg_UFSDownloadRequest EMsg = 5221
EMsg_UFSDownloadResponse EMsg = 5222
EMsg_UFSDownloadChunk EMsg = 5223
EMsg_ClientUFSGetUGCDetails EMsg = 5226
EMsg_ClientUFSGetUGCDetailsResponse EMsg = 5227
EMsg_UFSUpdateFileFlags EMsg = 5228
EMsg_UFSUpdateFileFlagsResponse EMsg = 5229
EMsg_ClientUFSGetSingleFileInfo EMsg = 5230
EMsg_ClientUFSGetSingleFileInfoResponse EMsg = 5231
EMsg_ClientUFSShareFile EMsg = 5232
EMsg_ClientUFSShareFileResponse EMsg = 5233
EMsg_UFSReloadAccount EMsg = 5234
EMsg_UFSReloadAccountResponse EMsg = 5235
EMsg_UFSUpdateRecordBatched EMsg = 5236
EMsg_UFSUpdateRecordBatchedResponse EMsg = 5237
EMsg_UFSMigrateFile EMsg = 5238
EMsg_UFSMigrateFileResponse EMsg = 5239
EMsg_UFSGetUGCURLs EMsg = 5240
EMsg_UFSGetUGCURLsResponse EMsg = 5241
EMsg_UFSHttpUploadFileFinishRequest EMsg = 5242
EMsg_UFSHttpUploadFileFinishResponse EMsg = 5243
EMsg_UFSDownloadStartRequest EMsg = 5244
EMsg_UFSDownloadStartResponse EMsg = 5245
EMsg_UFSDownloadChunkRequest EMsg = 5246
EMsg_UFSDownloadChunkResponse EMsg = 5247
EMsg_UFSDownloadFinishRequest EMsg = 5248
EMsg_UFSDownloadFinishResponse EMsg = 5249
EMsg_UFSFlushURLCache EMsg = 5250
EMsg_UFSUploadCommit EMsg = 5251
EMsg_UFSUploadCommitResponse EMsg = 5252
EMsg_BaseClient2 EMsg = 5400
EMsg_ClientRequestForgottenPasswordEmail EMsg = 5401
EMsg_ClientRequestForgottenPasswordEmailResponse EMsg = 5402
EMsg_ClientCreateAccountResponse EMsg = 5403
EMsg_ClientResetForgottenPassword EMsg = 5404
EMsg_ClientResetForgottenPasswordResponse EMsg = 5405
EMsg_ClientCreateAccount2 EMsg = 5406
EMsg_ClientInformOfResetForgottenPassword EMsg = 5407
EMsg_ClientInformOfResetForgottenPasswordResponse EMsg = 5408
EMsg_ClientAnonUserLogOn_Deprecated EMsg = 5409 // Deprecated
EMsg_ClientGamesPlayedWithDataBlob EMsg = 5410
EMsg_ClientUpdateUserGameInfo EMsg = 5411
EMsg_ClientFileToDownload EMsg = 5412
EMsg_ClientFileToDownloadResponse EMsg = 5413
EMsg_ClientLBSSetScore EMsg = 5414
EMsg_ClientLBSSetScoreResponse EMsg = 5415
EMsg_ClientLBSFindOrCreateLB EMsg = 5416
EMsg_ClientLBSFindOrCreateLBResponse EMsg = 5417
EMsg_ClientLBSGetLBEntries EMsg = 5418
EMsg_ClientLBSGetLBEntriesResponse EMsg = 5419
EMsg_ClientMarketingMessageUpdate EMsg = 5420 // Deprecated
EMsg_ClientChatDeclined EMsg = 5426
EMsg_ClientFriendMsgIncoming EMsg = 5427
EMsg_ClientAuthList_Deprecated EMsg = 5428 // Deprecated
EMsg_ClientTicketAuthComplete EMsg = 5429
EMsg_ClientIsLimitedAccount EMsg = 5430
EMsg_ClientRequestAuthList EMsg = 5431
EMsg_ClientAuthList EMsg = 5432
EMsg_ClientStat EMsg = 5433
EMsg_ClientP2PConnectionInfo EMsg = 5434
EMsg_ClientP2PConnectionFailInfo EMsg = 5435
EMsg_ClientGetNumberOfCurrentPlayers EMsg = 5436
EMsg_ClientGetNumberOfCurrentPlayersResponse EMsg = 5437
EMsg_ClientGetDepotDecryptionKey EMsg = 5438
EMsg_ClientGetDepotDecryptionKeyResponse EMsg = 5439
EMsg_GSPerformHardwareSurvey EMsg = 5440
EMsg_ClientGetAppBetaPasswords EMsg = 5441
EMsg_ClientGetAppBetaPasswordsResponse EMsg = 5442
EMsg_ClientEnableTestLicense EMsg = 5443
EMsg_ClientEnableTestLicenseResponse EMsg = 5444
EMsg_ClientDisableTestLicense EMsg = 5445
EMsg_ClientDisableTestLicenseResponse EMsg = 5446
EMsg_ClientRequestValidationMail EMsg = 5448
EMsg_ClientRequestValidationMailResponse EMsg = 5449
EMsg_ClientCheckAppBetaPassword EMsg = 5450
EMsg_ClientCheckAppBetaPasswordResponse EMsg = 5451
EMsg_ClientToGC EMsg = 5452
EMsg_ClientFromGC EMsg = 5453
EMsg_ClientRequestChangeMail EMsg = 5454
EMsg_ClientRequestChangeMailResponse EMsg = 5455
EMsg_ClientEmailAddrInfo EMsg = 5456
EMsg_ClientPasswordChange3 EMsg = 5457
EMsg_ClientEmailChange3 EMsg = 5458
EMsg_ClientPersonalQAChange3 EMsg = 5459
EMsg_ClientResetForgottenPassword3 EMsg = 5460
EMsg_ClientRequestForgottenPasswordEmail3 EMsg = 5461
EMsg_ClientCreateAccount3 EMsg = 5462 // Deprecated
EMsg_ClientNewLoginKey EMsg = 5463
EMsg_ClientNewLoginKeyAccepted EMsg = 5464
EMsg_ClientLogOnWithHash_Deprecated EMsg = 5465 // Deprecated
EMsg_ClientStoreUserStats2 EMsg = 5466
EMsg_ClientStatsUpdated EMsg = 5467
EMsg_ClientActivateOEMLicense EMsg = 5468
EMsg_ClientRegisterOEMMachine EMsg = 5469
EMsg_ClientRegisterOEMMachineResponse EMsg = 5470
EMsg_ClientRequestedClientStats EMsg = 5480
EMsg_ClientStat2Int32 EMsg = 5481
EMsg_ClientStat2 EMsg = 5482
EMsg_ClientVerifyPassword EMsg = 5483
EMsg_ClientVerifyPasswordResponse EMsg = 5484
EMsg_ClientDRMDownloadRequest EMsg = 5485
EMsg_ClientDRMDownloadResponse EMsg = 5486
EMsg_ClientDRMFinalResult EMsg = 5487
EMsg_ClientGetFriendsWhoPlayGame EMsg = 5488
EMsg_ClientGetFriendsWhoPlayGameResponse EMsg = 5489
EMsg_ClientOGSBeginSession EMsg = 5490
EMsg_ClientOGSBeginSessionResponse EMsg = 5491
EMsg_ClientOGSEndSession EMsg = 5492
EMsg_ClientOGSEndSessionResponse EMsg = 5493
EMsg_ClientOGSWriteRow EMsg = 5494
EMsg_ClientDRMTest EMsg = 5495
EMsg_ClientDRMTestResult EMsg = 5496
EMsg_ClientServerUnavailable EMsg = 5500
EMsg_ClientServersAvailable EMsg = 5501
EMsg_ClientRegisterAuthTicketWithCM EMsg = 5502
EMsg_ClientGCMsgFailed EMsg = 5503
EMsg_ClientMicroTxnAuthRequest EMsg = 5504
EMsg_ClientMicroTxnAuthorize EMsg = 5505
EMsg_ClientMicroTxnAuthorizeResponse EMsg = 5506
EMsg_ClientAppMinutesPlayedData EMsg = 5507
EMsg_ClientGetMicroTxnInfo EMsg = 5508
EMsg_ClientGetMicroTxnInfoResponse EMsg = 5509
EMsg_ClientMarketingMessageUpdate2 EMsg = 5510
EMsg_ClientDeregisterWithServer EMsg = 5511
EMsg_ClientSubscribeToPersonaFeed EMsg = 5512
EMsg_ClientLogon EMsg = 5514
EMsg_ClientGetClientDetails EMsg = 5515
EMsg_ClientGetClientDetailsResponse EMsg = 5516
EMsg_ClientReportOverlayDetourFailure EMsg = 5517
EMsg_ClientGetClientAppList EMsg = 5518
EMsg_ClientGetClientAppListResponse EMsg = 5519
EMsg_ClientInstallClientApp EMsg = 5520
EMsg_ClientInstallClientAppResponse EMsg = 5521
EMsg_ClientUninstallClientApp EMsg = 5522
EMsg_ClientUninstallClientAppResponse EMsg = 5523
EMsg_ClientSetClientAppUpdateState EMsg = 5524
EMsg_ClientSetClientAppUpdateStateResponse EMsg = 5525
EMsg_ClientRequestEncryptedAppTicket EMsg = 5526
EMsg_ClientRequestEncryptedAppTicketResponse EMsg = 5527
EMsg_ClientWalletInfoUpdate EMsg = 5528
EMsg_ClientLBSSetUGC EMsg = 5529
EMsg_ClientLBSSetUGCResponse EMsg = 5530
EMsg_ClientAMGetClanOfficers EMsg = 5531
EMsg_ClientAMGetClanOfficersResponse EMsg = 5532
EMsg_ClientCheckFileSignature EMsg = 5533
EMsg_ClientCheckFileSignatureResponse EMsg = 5534
EMsg_ClientFriendProfileInfo EMsg = 5535
EMsg_ClientFriendProfileInfoResponse EMsg = 5536
EMsg_ClientUpdateMachineAuth EMsg = 5537
EMsg_ClientUpdateMachineAuthResponse EMsg = 5538
EMsg_ClientReadMachineAuth EMsg = 5539
EMsg_ClientReadMachineAuthResponse EMsg = 5540
EMsg_ClientRequestMachineAuth EMsg = 5541
EMsg_ClientRequestMachineAuthResponse EMsg = 5542
EMsg_ClientScreenshotsChanged EMsg = 5543
EMsg_ClientEmailChange4 EMsg = 5544
EMsg_ClientEmailChangeResponse4 EMsg = 5545
EMsg_ClientGetCDNAuthToken EMsg = 5546
EMsg_ClientGetCDNAuthTokenResponse EMsg = 5547
EMsg_ClientDownloadRateStatistics EMsg = 5548
EMsg_ClientRequestAccountData EMsg = 5549
EMsg_ClientRequestAccountDataResponse EMsg = 5550
EMsg_ClientResetForgottenPassword4 EMsg = 5551
EMsg_ClientHideFriend EMsg = 5552
EMsg_ClientFriendsGroupsList EMsg = 5553
EMsg_ClientGetClanActivityCounts EMsg = 5554
EMsg_ClientGetClanActivityCountsResponse EMsg = 5555
EMsg_ClientOGSReportString EMsg = 5556
EMsg_ClientOGSReportBug EMsg = 5557
EMsg_ClientSentLogs EMsg = 5558
EMsg_ClientLogonGameServer EMsg = 5559
EMsg_AMClientCreateFriendsGroup EMsg = 5560
EMsg_AMClientCreateFriendsGroupResponse EMsg = 5561
EMsg_AMClientDeleteFriendsGroup EMsg = 5562
EMsg_AMClientDeleteFriendsGroupResponse EMsg = 5563
EMsg_AMClientRenameFriendsGroup EMsg = 5564
EMsg_AMClientRenameFriendsGroupResponse EMsg = 5565
EMsg_AMClientAddFriendToGroup EMsg = 5566
EMsg_AMClientAddFriendToGroupResponse EMsg = 5567
EMsg_AMClientRemoveFriendFromGroup EMsg = 5568
EMsg_AMClientRemoveFriendFromGroupResponse EMsg = 5569
EMsg_ClientAMGetPersonaNameHistory EMsg = 5570
EMsg_ClientAMGetPersonaNameHistoryResponse EMsg = 5571
EMsg_ClientRequestFreeLicense EMsg = 5572
EMsg_ClientRequestFreeLicenseResponse EMsg = 5573
EMsg_ClientDRMDownloadRequestWithCrashData EMsg = 5574
EMsg_ClientAuthListAck EMsg = 5575
EMsg_ClientItemAnnouncements EMsg = 5576
EMsg_ClientRequestItemAnnouncements EMsg = 5577
EMsg_ClientFriendMsgEchoToSender EMsg = 5578
EMsg_ClientChangeSteamGuardOptions EMsg = 5579 // Deprecated
EMsg_ClientChangeSteamGuardOptionsResponse EMsg = 5580 // Deprecated
EMsg_ClientOGSGameServerPingSample EMsg = 5581
EMsg_ClientCommentNotifications EMsg = 5582
EMsg_ClientRequestCommentNotifications EMsg = 5583
EMsg_ClientPersonaChangeResponse EMsg = 5584
EMsg_ClientRequestWebAPIAuthenticateUserNonce EMsg = 5585
EMsg_ClientRequestWebAPIAuthenticateUserNonceResponse EMsg = 5586
EMsg_ClientPlayerNicknameList EMsg = 5587
EMsg_AMClientSetPlayerNickname EMsg = 5588
EMsg_AMClientSetPlayerNicknameResponse EMsg = 5589
EMsg_ClientRequestOAuthTokenForApp EMsg = 5590 // Deprecated
EMsg_ClientRequestOAuthTokenForAppResponse EMsg = 5591 // Deprecated
EMsg_ClientCreateAccountProto EMsg = 5590
EMsg_ClientCreateAccountProtoResponse EMsg = 5591
EMsg_ClientGetNumberOfCurrentPlayersDP EMsg = 5592
EMsg_ClientGetNumberOfCurrentPlayersDPResponse EMsg = 5593
EMsg_ClientServiceMethod EMsg = 5594
EMsg_ClientServiceMethodResponse EMsg = 5595
EMsg_ClientFriendUserStatusPublished EMsg = 5596
EMsg_ClientCurrentUIMode EMsg = 5597
EMsg_ClientVanityURLChangedNotification EMsg = 5598
EMsg_ClientUserNotifications EMsg = 5599
EMsg_BaseDFS EMsg = 5600
EMsg_DFSGetFile EMsg = 5601
EMsg_DFSInstallLocalFile EMsg = 5602
EMsg_DFSConnection EMsg = 5603
EMsg_DFSConnectionReply EMsg = 5604
EMsg_ClientDFSAuthenticateRequest EMsg = 5605
EMsg_ClientDFSAuthenticateResponse EMsg = 5606
EMsg_ClientDFSEndSession EMsg = 5607
EMsg_DFSPurgeFile EMsg = 5608
EMsg_DFSRouteFile EMsg = 5609
EMsg_DFSGetFileFromServer EMsg = 5610
EMsg_DFSAcceptedResponse EMsg = 5611
EMsg_DFSRequestPingback EMsg = 5612
EMsg_DFSRecvTransmitFile EMsg = 5613
EMsg_DFSSendTransmitFile EMsg = 5614
EMsg_DFSRequestPingback2 EMsg = 5615
EMsg_DFSResponsePingback2 EMsg = 5616
EMsg_ClientDFSDownloadStatus EMsg = 5617
EMsg_DFSStartTransfer EMsg = 5618
EMsg_DFSTransferComplete EMsg = 5619
EMsg_BaseMDS EMsg = 5800
EMsg_ClientMDSLoginRequest EMsg = 5801 // Deprecated
EMsg_ClientMDSLoginResponse EMsg = 5802 // Deprecated
EMsg_ClientMDSUploadManifestRequest EMsg = 5803 // Deprecated
EMsg_ClientMDSUploadManifestResponse EMsg = 5804 // Deprecated
EMsg_ClientMDSTransmitManifestDataChunk EMsg = 5805 // Deprecated
EMsg_ClientMDSHeartbeat EMsg = 5806 // Deprecated
EMsg_ClientMDSUploadDepotChunks EMsg = 5807 // Deprecated
EMsg_ClientMDSUploadDepotChunksResponse EMsg = 5808 // Deprecated
EMsg_ClientMDSInitDepotBuildRequest EMsg = 5809 // Deprecated
EMsg_ClientMDSInitDepotBuildResponse EMsg = 5810 // Deprecated
EMsg_AMToMDSGetDepotDecryptionKey EMsg = 5812
EMsg_MDSToAMGetDepotDecryptionKeyResponse EMsg = 5813
EMsg_MDSGetVersionsForDepot EMsg = 5814
EMsg_MDSGetVersionsForDepotResponse EMsg = 5815
EMsg_MDSSetPublicVersionForDepot EMsg = 5816 // Deprecated
EMsg_MDSSetPublicVersionForDepotResponse EMsg = 5817 // Deprecated
EMsg_ClientMDSInitWorkshopBuildRequest EMsg = 5816 // Deprecated
EMsg_ClientMDSInitWorkshopBuildResponse EMsg = 5817 // Deprecated
EMsg_ClientMDSGetDepotManifest EMsg = 5818 // Deprecated
EMsg_ClientMDSGetDepotManifestResponse EMsg = 5819 // Deprecated
EMsg_ClientMDSGetDepotManifestChunk EMsg = 5820 // Deprecated
EMsg_ClientMDSUploadRateTest EMsg = 5823 // Deprecated
EMsg_ClientMDSUploadRateTestResponse EMsg = 5824 // Deprecated
EMsg_MDSDownloadDepotChunksAck EMsg = 5825
EMsg_MDSContentServerStatsBroadcast EMsg = 5826
EMsg_MDSContentServerConfigRequest EMsg = 5827
EMsg_MDSContentServerConfig EMsg = 5828
EMsg_MDSGetDepotManifest EMsg = 5829
EMsg_MDSGetDepotManifestResponse EMsg = 5830
EMsg_MDSGetDepotManifestChunk EMsg = 5831
EMsg_MDSGetDepotChunk EMsg = 5832
EMsg_MDSGetDepotChunkResponse EMsg = 5833
EMsg_MDSGetDepotChunkChunk EMsg = 5834
EMsg_MDSUpdateContentServerConfig EMsg = 5835
EMsg_MDSGetServerListForUser EMsg = 5836
EMsg_MDSGetServerListForUserResponse EMsg = 5837
EMsg_ClientMDSRegisterAppBuild EMsg = 5838 // Deprecated
EMsg_ClientMDSRegisterAppBuildResponse EMsg = 5839 // Deprecated
EMsg_ClientMDSSetAppBuildLive EMsg = 5840
EMsg_ClientMDSSetAppBuildLiveResponse EMsg = 5841
EMsg_ClientMDSGetPrevDepotBuild EMsg = 5842
EMsg_ClientMDSGetPrevDepotBuildResponse EMsg = 5843
EMsg_MDSToCSFlushChunk EMsg = 5844
EMsg_ClientMDSSignInstallScript EMsg = 5845 // Deprecated
EMsg_ClientMDSSignInstallScriptResponse EMsg = 5846 // Deprecated
EMsg_CSBase EMsg = 6200
EMsg_CSPing EMsg = 6201
EMsg_CSPingResponse EMsg = 6202
EMsg_GMSBase EMsg = 6400
EMsg_GMSGameServerReplicate EMsg = 6401
EMsg_ClientGMSServerQuery EMsg = 6403
EMsg_GMSClientServerQueryResponse EMsg = 6404
EMsg_AMGMSGameServerUpdate EMsg = 6405
EMsg_AMGMSGameServerRemove EMsg = 6406
EMsg_GameServerOutOfDate EMsg = 6407
EMsg_ClientAuthorizeLocalDeviceRequest EMsg = 6501
EMsg_ClientAuthorizeLocalDevice EMsg = 6502
EMsg_ClientDeauthorizeDeviceRequest EMsg = 6503
EMsg_ClientDeauthorizeDevice EMsg = 6504
EMsg_ClientUseLocalDeviceAuthorizations EMsg = 6505
EMsg_ClientGetAuthorizedDevices EMsg = 6506
EMsg_ClientGetAuthorizedDevicesResponse EMsg = 6507
EMsg_MMSBase EMsg = 6600
EMsg_ClientMMSCreateLobby EMsg = 6601
EMsg_ClientMMSCreateLobbyResponse EMsg = 6602
EMsg_ClientMMSJoinLobby EMsg = 6603
EMsg_ClientMMSJoinLobbyResponse EMsg = 6604
EMsg_ClientMMSLeaveLobby EMsg = 6605
EMsg_ClientMMSLeaveLobbyResponse EMsg = 6606
EMsg_ClientMMSGetLobbyList EMsg = 6607
EMsg_ClientMMSGetLobbyListResponse EMsg = 6608
EMsg_ClientMMSSetLobbyData EMsg = 6609
EMsg_ClientMMSSetLobbyDataResponse EMsg = 6610
EMsg_ClientMMSGetLobbyData EMsg = 6611
EMsg_ClientMMSLobbyData EMsg = 6612
EMsg_ClientMMSSendLobbyChatMsg EMsg = 6613
EMsg_ClientMMSLobbyChatMsg EMsg = 6614
EMsg_ClientMMSSetLobbyOwner EMsg = 6615
EMsg_ClientMMSSetLobbyOwnerResponse EMsg = 6616
EMsg_ClientMMSSetLobbyGameServer EMsg = 6617
EMsg_ClientMMSLobbyGameServerSet EMsg = 6618
EMsg_ClientMMSUserJoinedLobby EMsg = 6619
EMsg_ClientMMSUserLeftLobby EMsg = 6620
EMsg_ClientMMSInviteToLobby EMsg = 6621
EMsg_ClientMMSFlushFrenemyListCache EMsg = 6622
EMsg_ClientMMSFlushFrenemyListCacheResponse EMsg = 6623
EMsg_ClientMMSSetLobbyLinked EMsg = 6624
EMsg_NonStdMsgBase EMsg = 6800
EMsg_NonStdMsgMemcached EMsg = 6801
EMsg_NonStdMsgHTTPServer EMsg = 6802
EMsg_NonStdMsgHTTPClient EMsg = 6803
EMsg_NonStdMsgWGResponse EMsg = 6804
EMsg_NonStdMsgPHPSimulator EMsg = 6805
EMsg_NonStdMsgChase EMsg = 6806
EMsg_NonStdMsgDFSTransfer EMsg = 6807
EMsg_NonStdMsgTests EMsg = 6808
EMsg_NonStdMsgUMQpipeAAPL EMsg = 6809
EMsg_NonStdMsgSyslog EMsg = 6810
EMsg_NonStdMsgLogsink EMsg = 6811
EMsg_UDSBase EMsg = 7000
EMsg_ClientUDSP2PSessionStarted EMsg = 7001
EMsg_ClientUDSP2PSessionEnded EMsg = 7002
EMsg_UDSRenderUserAuth EMsg = 7003
EMsg_UDSRenderUserAuthResponse EMsg = 7004
EMsg_ClientUDSInviteToGame EMsg = 7005
EMsg_UDSFindSession EMsg = 7006
EMsg_UDSFindSessionResponse EMsg = 7007
EMsg_MPASBase EMsg = 7100
EMsg_MPASVacBanReset EMsg = 7101
EMsg_KGSBase EMsg = 7200
EMsg_KGSAllocateKeyRange EMsg = 7201
EMsg_KGSAllocateKeyRangeResponse EMsg = 7202
EMsg_KGSGenerateKeys EMsg = 7203
EMsg_KGSGenerateKeysResponse EMsg = 7204
EMsg_KGSRemapKeys EMsg = 7205
EMsg_KGSRemapKeysResponse EMsg = 7206
EMsg_KGSGenerateGameStopWCKeys EMsg = 7207
EMsg_KGSGenerateGameStopWCKeysResponse EMsg = 7208
EMsg_UCMBase EMsg = 7300
EMsg_ClientUCMAddScreenshot EMsg = 7301
EMsg_ClientUCMAddScreenshotResponse EMsg = 7302
EMsg_UCMValidateObjectExists EMsg = 7303
EMsg_UCMValidateObjectExistsResponse EMsg = 7304
EMsg_UCMResetCommunityContent EMsg = 7307
EMsg_UCMResetCommunityContentResponse EMsg = 7308
EMsg_ClientUCMDeleteScreenshot EMsg = 7309
EMsg_ClientUCMDeleteScreenshotResponse EMsg = 7310
EMsg_ClientUCMPublishFile EMsg = 7311
EMsg_ClientUCMPublishFileResponse EMsg = 7312
EMsg_ClientUCMGetPublishedFileDetails EMsg = 7313 // Deprecated
EMsg_ClientUCMGetPublishedFileDetailsResponse EMsg = 7314 // Deprecated
EMsg_ClientUCMDeletePublishedFile EMsg = 7315
EMsg_ClientUCMDeletePublishedFileResponse EMsg = 7316
EMsg_ClientUCMEnumerateUserPublishedFiles EMsg = 7317
EMsg_ClientUCMEnumerateUserPublishedFilesResponse EMsg = 7318
EMsg_ClientUCMSubscribePublishedFile EMsg = 7319 // Deprecated
EMsg_ClientUCMSubscribePublishedFileResponse EMsg = 7320 // Deprecated
EMsg_ClientUCMEnumerateUserSubscribedFiles EMsg = 7321
EMsg_ClientUCMEnumerateUserSubscribedFilesResponse EMsg = 7322
EMsg_ClientUCMUnsubscribePublishedFile EMsg = 7323 // Deprecated
EMsg_ClientUCMUnsubscribePublishedFileResponse EMsg = 7324 // Deprecated
EMsg_ClientUCMUpdatePublishedFile EMsg = 7325
EMsg_ClientUCMUpdatePublishedFileResponse EMsg = 7326
EMsg_UCMUpdatePublishedFile EMsg = 7327
EMsg_UCMUpdatePublishedFileResponse EMsg = 7328
EMsg_UCMDeletePublishedFile EMsg = 7329
EMsg_UCMDeletePublishedFileResponse EMsg = 7330
EMsg_UCMUpdatePublishedFileStat EMsg = 7331
EMsg_UCMUpdatePublishedFileBan EMsg = 7332
EMsg_UCMUpdatePublishedFileBanResponse EMsg = 7333
EMsg_UCMUpdateTaggedScreenshot EMsg = 7334
EMsg_UCMAddTaggedScreenshot EMsg = 7335
EMsg_UCMRemoveTaggedScreenshot EMsg = 7336
EMsg_UCMReloadPublishedFile EMsg = 7337
EMsg_UCMReloadUserFileListCaches EMsg = 7338
EMsg_UCMPublishedFileReported EMsg = 7339
EMsg_UCMUpdatePublishedFileIncompatibleStatus EMsg = 7340
EMsg_UCMPublishedFilePreviewAdd EMsg = 7341
EMsg_UCMPublishedFilePreviewAddResponse EMsg = 7342
EMsg_UCMPublishedFilePreviewRemove EMsg = 7343
EMsg_UCMPublishedFilePreviewRemoveResponse EMsg = 7344
EMsg_UCMPublishedFilePreviewChangeSortOrder EMsg = 7345
EMsg_UCMPublishedFilePreviewChangeSortOrderResponse EMsg = 7346
EMsg_ClientUCMPublishedFileSubscribed EMsg = 7347
EMsg_ClientUCMPublishedFileUnsubscribed EMsg = 7348
EMsg_UCMPublishedFileSubscribed EMsg = 7349
EMsg_UCMPublishedFileUnsubscribed EMsg = 7350
EMsg_UCMPublishFile EMsg = 7351
EMsg_UCMPublishFileResponse EMsg = 7352
EMsg_UCMPublishedFileChildAdd EMsg = 7353
EMsg_UCMPublishedFileChildAddResponse EMsg = 7354
EMsg_UCMPublishedFileChildRemove EMsg = 7355
EMsg_UCMPublishedFileChildRemoveResponse EMsg = 7356
EMsg_UCMPublishedFileChildChangeSortOrder EMsg = 7357
EMsg_UCMPublishedFileChildChangeSortOrderResponse EMsg = 7358
EMsg_UCMPublishedFileParentChanged EMsg = 7359
EMsg_ClientUCMGetPublishedFilesForUser EMsg = 7360
EMsg_ClientUCMGetPublishedFilesForUserResponse EMsg = 7361
EMsg_UCMGetPublishedFilesForUser EMsg = 7362
EMsg_UCMGetPublishedFilesForUserResponse EMsg = 7363
EMsg_ClientUCMSetUserPublishedFileAction EMsg = 7364
EMsg_ClientUCMSetUserPublishedFileActionResponse EMsg = 7365
EMsg_ClientUCMEnumeratePublishedFilesByUserAction EMsg = 7366
EMsg_ClientUCMEnumeratePublishedFilesByUserActionResponse EMsg = 7367
EMsg_ClientUCMPublishedFileDeleted EMsg = 7368
EMsg_UCMGetUserSubscribedFiles EMsg = 7369
EMsg_UCMGetUserSubscribedFilesResponse EMsg = 7370
EMsg_UCMFixStatsPublishedFile EMsg = 7371
EMsg_UCMDeleteOldScreenshot EMsg = 7372
EMsg_UCMDeleteOldScreenshotResponse EMsg = 7373
EMsg_UCMDeleteOldVideo EMsg = 7374
EMsg_UCMDeleteOldVideoResponse EMsg = 7375
EMsg_UCMUpdateOldScreenshotPrivacy EMsg = 7376
EMsg_UCMUpdateOldScreenshotPrivacyResponse EMsg = 7377
EMsg_ClientUCMEnumerateUserSubscribedFilesWithUpdates EMsg = 7378
EMsg_ClientUCMEnumerateUserSubscribedFilesWithUpdatesResponse EMsg = 7379
EMsg_UCMPublishedFileContentUpdated EMsg = 7380
EMsg_UCMPublishedFileUpdated EMsg = 7381
EMsg_ClientWorkshopItemChangesRequest EMsg = 7382
EMsg_ClientWorkshopItemChangesResponse EMsg = 7383
EMsg_ClientWorkshopItemInfoRequest EMsg = 7384
EMsg_ClientWorkshopItemInfoResponse EMsg = 7385
EMsg_FSBase EMsg = 7500
EMsg_ClientRichPresenceUpload EMsg = 7501
EMsg_ClientRichPresenceRequest EMsg = 7502
EMsg_ClientRichPresenceInfo EMsg = 7503
EMsg_FSRichPresenceRequest EMsg = 7504
EMsg_FSRichPresenceResponse EMsg = 7505
EMsg_FSComputeFrenematrix EMsg = 7506
EMsg_FSComputeFrenematrixResponse EMsg = 7507
EMsg_FSPlayStatusNotification EMsg = 7508
EMsg_FSPublishPersonaStatus EMsg = 7509
EMsg_FSAddOrRemoveFollower EMsg = 7510
EMsg_FSAddOrRemoveFollowerResponse EMsg = 7511
EMsg_FSUpdateFollowingList EMsg = 7512
EMsg_FSCommentNotification EMsg = 7513
EMsg_FSCommentNotificationViewed EMsg = 7514
EMsg_ClientFSGetFollowerCount EMsg = 7515
EMsg_ClientFSGetFollowerCountResponse EMsg = 7516
EMsg_ClientFSGetIsFollowing EMsg = 7517
EMsg_ClientFSGetIsFollowingResponse EMsg = 7518
EMsg_ClientFSEnumerateFollowingList EMsg = 7519
EMsg_ClientFSEnumerateFollowingListResponse EMsg = 7520
EMsg_FSGetPendingNotificationCount EMsg = 7521
EMsg_FSGetPendingNotificationCountResponse EMsg = 7522
EMsg_ClientFSOfflineMessageNotification EMsg = 7523
EMsg_ClientFSRequestOfflineMessageCount EMsg = 7524
EMsg_ClientFSGetFriendMessageHistory EMsg = 7525
EMsg_ClientFSGetFriendMessageHistoryResponse EMsg = 7526
EMsg_ClientFSGetFriendMessageHistoryForOfflineMessages EMsg = 7527
EMsg_ClientFSGetFriendsSteamLevels EMsg = 7528
EMsg_ClientFSGetFriendsSteamLevelsResponse EMsg = 7529
EMsg_DRMRange2 EMsg = 7600
EMsg_CEGVersionSetEnableDisableRequest EMsg = 7600
EMsg_CEGVersionSetEnableDisableResponse EMsg = 7601
EMsg_CEGPropStatusDRMSRequest EMsg = 7602
EMsg_CEGPropStatusDRMSResponse EMsg = 7603
EMsg_CEGWhackFailureReportRequest EMsg = 7604
EMsg_CEGWhackFailureReportResponse EMsg = 7605
EMsg_DRMSFetchVersionSet EMsg = 7606
EMsg_DRMSFetchVersionSetResponse EMsg = 7607
EMsg_EconBase EMsg = 7700
EMsg_EconTrading_InitiateTradeRequest EMsg = 7701
EMsg_EconTrading_InitiateTradeProposed EMsg = 7702
EMsg_EconTrading_InitiateTradeResponse EMsg = 7703
EMsg_EconTrading_InitiateTradeResult EMsg = 7704
EMsg_EconTrading_StartSession EMsg = 7705
EMsg_EconTrading_CancelTradeRequest EMsg = 7706
EMsg_EconFlushInventoryCache EMsg = 7707
EMsg_EconFlushInventoryCacheResponse EMsg = 7708
EMsg_EconCDKeyProcessTransaction EMsg = 7711
EMsg_EconCDKeyProcessTransactionResponse EMsg = 7712
EMsg_EconGetErrorLogs EMsg = 7713
EMsg_EconGetErrorLogsResponse EMsg = 7714
EMsg_RMRange EMsg = 7800
EMsg_RMTestVerisignOTP EMsg = 7800
EMsg_RMTestVerisignOTPResponse EMsg = 7801
EMsg_RMDeleteMemcachedKeys EMsg = 7803
EMsg_RMRemoteInvoke EMsg = 7804
EMsg_BadLoginIPList EMsg = 7805
EMsg_UGSBase EMsg = 7900
EMsg_UGSUpdateGlobalStats EMsg = 7900
EMsg_ClientUGSGetGlobalStats EMsg = 7901
EMsg_ClientUGSGetGlobalStatsResponse EMsg = 7902
EMsg_StoreBase EMsg = 8000
EMsg_StoreUpdateRecommendationCount EMsg = 8000
EMsg_UMQBase EMsg = 8100
EMsg_UMQLogonRequest EMsg = 8100
EMsg_UMQLogonResponse EMsg = 8101
EMsg_UMQLogoffRequest EMsg = 8102
EMsg_UMQLogoffResponse EMsg = 8103
EMsg_UMQSendChatMessage EMsg = 8104
EMsg_UMQIncomingChatMessage EMsg = 8105
EMsg_UMQPoll EMsg = 8106
EMsg_UMQPollResults EMsg = 8107
EMsg_UMQ2AM_ClientMsgBatch EMsg = 8108
EMsg_UMQEnqueueMobileSalePromotions EMsg = 8109
EMsg_UMQEnqueueMobileAnnouncements EMsg = 8110
EMsg_WorkshopBase EMsg = 8200
EMsg_WorkshopAcceptTOSRequest EMsg = 8200
EMsg_WorkshopAcceptTOSResponse EMsg = 8201
EMsg_WebAPIBase EMsg = 8300
EMsg_WebAPIValidateOAuth2Token EMsg = 8300
EMsg_WebAPIValidateOAuth2TokenResponse EMsg = 8301
EMsg_WebAPIInvalidateTokensForAccount EMsg = 8302
EMsg_WebAPIRegisterGCInterfaces EMsg = 8303
EMsg_WebAPIInvalidateOAuthClientCache EMsg = 8304
EMsg_WebAPIInvalidateOAuthTokenCache EMsg = 8305
EMsg_BackpackBase EMsg = 8400
EMsg_BackpackAddToCurrency EMsg = 8401
EMsg_BackpackAddToCurrencyResponse EMsg = 8402
EMsg_CREBase EMsg = 8500
EMsg_CRERankByTrend EMsg = 8501 // Deprecated
EMsg_CRERankByTrendResponse EMsg = 8502 // Deprecated
EMsg_CREItemVoteSummary EMsg = 8503
EMsg_CREItemVoteSummaryResponse EMsg = 8504
EMsg_CRERankByVote EMsg = 8505 // Deprecated
EMsg_CRERankByVoteResponse EMsg = 8506 // Deprecated
EMsg_CREUpdateUserPublishedItemVote EMsg = 8507
EMsg_CREUpdateUserPublishedItemVoteResponse EMsg = 8508
EMsg_CREGetUserPublishedItemVoteDetails EMsg = 8509
EMsg_CREGetUserPublishedItemVoteDetailsResponse EMsg = 8510
EMsg_CREEnumeratePublishedFiles EMsg = 8511
EMsg_CREEnumeratePublishedFilesResponse EMsg = 8512
EMsg_CREPublishedFileVoteAdded EMsg = 8513
EMsg_SecretsBase EMsg = 8600
EMsg_SecretsRequestCredentialPair EMsg = 8600
EMsg_SecretsCredentialPairResponse EMsg = 8601
EMsg_SecretsRequestServerIdentity EMsg = 8602
EMsg_SecretsServerIdentityResponse EMsg = 8603
EMsg_SecretsUpdateServerIdentities EMsg = 8604
EMsg_BoxMonitorBase EMsg = 8700
EMsg_BoxMonitorReportRequest EMsg = 8700
EMsg_BoxMonitorReportResponse EMsg = 8701
EMsg_LogsinkBase EMsg = 8800
EMsg_LogsinkWriteReport EMsg = 8800
EMsg_PICSBase EMsg = 8900
EMsg_ClientPICSChangesSinceRequest EMsg = 8901
EMsg_ClientPICSChangesSinceResponse EMsg = 8902
EMsg_ClientPICSProductInfoRequest EMsg = 8903
EMsg_ClientPICSProductInfoResponse EMsg = 8904
EMsg_ClientPICSAccessTokenRequest EMsg = 8905
EMsg_ClientPICSAccessTokenResponse EMsg = 8906
EMsg_WorkerProcess EMsg = 9000
EMsg_WorkerProcessPingRequest EMsg = 9000
EMsg_WorkerProcessPingResponse EMsg = 9001
EMsg_WorkerProcessShutdown EMsg = 9002
EMsg_DRMWorkerProcess EMsg = 9100
EMsg_DRMWorkerProcessDRMAndSign EMsg = 9100
EMsg_DRMWorkerProcessDRMAndSignResponse EMsg = 9101
EMsg_DRMWorkerProcessSteamworksInfoRequest EMsg = 9102
EMsg_DRMWorkerProcessSteamworksInfoResponse EMsg = 9103
EMsg_DRMWorkerProcessInstallDRMDLLRequest EMsg = 9104
EMsg_DRMWorkerProcessInstallDRMDLLResponse EMsg = 9105
EMsg_DRMWorkerProcessSecretIdStringRequest EMsg = 9106
EMsg_DRMWorkerProcessSecretIdStringResponse EMsg = 9107
EMsg_DRMWorkerProcessGetDRMGuidsFromFileRequest EMsg = 9108
EMsg_DRMWorkerProcessGetDRMGuidsFromFileResponse EMsg = 9109
EMsg_DRMWorkerProcessInstallProcessedFilesRequest EMsg = 9110
EMsg_DRMWorkerProcessInstallProcessedFilesResponse EMsg = 9111
EMsg_DRMWorkerProcessExamineBlobRequest EMsg = 9112
EMsg_DRMWorkerProcessExamineBlobResponse EMsg = 9113
EMsg_DRMWorkerProcessDescribeSecretRequest EMsg = 9114
EMsg_DRMWorkerProcessDescribeSecretResponse EMsg = 9115
EMsg_DRMWorkerProcessBackfillOriginalRequest EMsg = 9116
EMsg_DRMWorkerProcessBackfillOriginalResponse EMsg = 9117
EMsg_DRMWorkerProcessValidateDRMDLLRequest EMsg = 9118
EMsg_DRMWorkerProcessValidateDRMDLLResponse EMsg = 9119
EMsg_DRMWorkerProcessValidateFileRequest EMsg = 9120
EMsg_DRMWorkerProcessValidateFileResponse EMsg = 9121
EMsg_DRMWorkerProcessSplitAndInstallRequest EMsg = 9122
EMsg_DRMWorkerProcessSplitAndInstallResponse EMsg = 9123
EMsg_DRMWorkerProcessGetBlobRequest EMsg = 9124
EMsg_DRMWorkerProcessGetBlobResponse EMsg = 9125
EMsg_DRMWorkerProcessEvaluateCrashRequest EMsg = 9126
EMsg_DRMWorkerProcessEvaluateCrashResponse EMsg = 9127
EMsg_DRMWorkerProcessAnalyzeFileRequest EMsg = 9128
EMsg_DRMWorkerProcessAnalyzeFileResponse EMsg = 9129
EMsg_DRMWorkerProcessUnpackBlobRequest EMsg = 9130
EMsg_DRMWorkerProcessUnpackBlobResponse EMsg = 9131
EMsg_DRMWorkerProcessInstallAllRequest EMsg = 9132
EMsg_DRMWorkerProcessInstallAllResponse EMsg = 9133
EMsg_TestWorkerProcess EMsg = 9200
EMsg_TestWorkerProcessLoadUnloadModuleRequest EMsg = 9200
EMsg_TestWorkerProcessLoadUnloadModuleResponse EMsg = 9201
EMsg_TestWorkerProcessServiceModuleCallRequest EMsg = 9202
EMsg_TestWorkerProcessServiceModuleCallResponse EMsg = 9203
EMsg_ClientGetEmoticonList EMsg = 9330
EMsg_ClientEmoticonList EMsg = 9331
EMsg_ClientSharedLibraryBase EMsg = 9400
EMsg_ClientSharedLicensesLockStatus EMsg = 9403 // Deprecated
EMsg_ClientSharedLicensesStopPlaying EMsg = 9404 // Deprecated
EMsg_ClientSharedLibraryLockStatus EMsg = 9405
EMsg_ClientSharedLibraryStopPlaying EMsg = 9406
EMsg_ClientUnlockStreaming EMsg = 9507
EMsg_ClientUnlockStreamingResponse EMsg = 9508
EMsg_ClientPlayingSessionState EMsg = 9600
EMsg_ClientKickPlayingSession EMsg = 9601
EMsg_ClientBroadcastInit EMsg = 9700
EMsg_ClientBroadcastFrames EMsg = 9701
EMsg_ClientBroadcastDisconnect EMsg = 9702
EMsg_ClientBroadcastScreenshot EMsg = 9703
EMsg_ClientBroadcastUploadConfig EMsg = 9704
EMsg_ClientVoiceCallPreAuthorize EMsg = 9800
EMsg_ClientVoiceCallPreAuthorizeResponse EMsg = 9801
)
var EMsg_name = map[EMsg]string{
0: "EMsg_Invalid",
1: "EMsg_Multi",
100: "EMsg_BaseGeneral",
113: "EMsg_DestJobFailed",
115: "EMsg_Alert",
120: "EMsg_SCIDRequest",
121: "EMsg_SCIDResponse",
123: "EMsg_JobHeartbeat",
124: "EMsg_HubConnect",
126: "EMsg_Subscribe",
127: "EMsg_RouteMessage",
128: "EMsg_RemoteSysID",
129: "EMsg_AMCreateAccountResponse",
130: "EMsg_WGRequest",
131: "EMsg_WGResponse",
132: "EMsg_KeepAlive",
133: "EMsg_WebAPIJobRequest",
134: "EMsg_WebAPIJobResponse",
135: "EMsg_ClientSessionStart",
136: "EMsg_ClientSessionEnd",
137: "EMsg_ClientSessionUpdateAuthTicket",
138: "EMsg_StatsDeprecated",
139: "EMsg_Ping",
140: "EMsg_PingResponse",
141: "EMsg_Stats",
142: "EMsg_RequestFullStatsBlock",
143: "EMsg_LoadDBOCacheItem",
144: "EMsg_LoadDBOCacheItemResponse",
145: "EMsg_InvalidateDBOCacheItems",
146: "EMsg_ServiceMethod",
147: "EMsg_ServiceMethodResponse",
200: "EMsg_BaseShell",
201: "EMsg_Exit",
202: "EMsg_DirRequest",
203: "EMsg_DirResponse",
204: "EMsg_ZipRequest",
205: "EMsg_ZipResponse",
215: "EMsg_UpdateRecordResponse",
221: "EMsg_UpdateCreditCardRequest",
225: "EMsg_UpdateUserBanResponse",
226: "EMsg_PrepareToExit",
227: "EMsg_ContentDescriptionUpdate",
228: "EMsg_TestResetServer",
229: "EMsg_UniverseChanged",
230: "EMsg_ShellConfigInfoUpdate",
233: "EMsg_RequestWindowsEventLogEntries",
234: "EMsg_ProvideWindowsEventLogEntries",
235: "EMsg_ShellSearchLogs",
236: "EMsg_ShellSearchLogsResponse",
237: "EMsg_ShellCheckWindowsUpdates",
238: "EMsg_ShellCheckWindowsUpdatesResponse",
239: "EMsg_ShellFlushUserLicenseCache",
300: "EMsg_BaseGM",
301: "EMsg_ShellFailed",
307: "EMsg_ExitShells",
308: "EMsg_ExitShell",
309: "EMsg_GracefulExitShell",
314: "EMsg_NotifyWatchdog",
316: "EMsg_LicenseProcessingComplete",
317: "EMsg_SetTestFlag",
318: "EMsg_QueuedEmailsComplete",
319: "EMsg_GMReportPHPError",
320: "EMsg_GMDRMSync",
321: "EMsg_PhysicalBoxInventory",
322: "EMsg_UpdateConfigFile",
323: "EMsg_TestInitDB",
324: "EMsg_GMWriteConfigToSQL",
325: "EMsg_GMLoadActivationCodes",
326: "EMsg_GMQueueForFBS",
327: "EMsg_GMSchemaConversionResults",
328: "EMsg_GMSchemaConversionResultsResponse",
329: "EMsg_GMWriteShellFailureToSQL",
400: "EMsg_BaseAIS",
401: "EMsg_AISRefreshContentDescription",
402: "EMsg_AISRequestContentDescription",
403: "EMsg_AISUpdateAppInfo",
404: "EMsg_AISUpdatePackageInfo",
405: "EMsg_AISGetPackageChangeNumber",
406: "EMsg_AISGetPackageChangeNumberResponse",
407: "EMsg_AISAppInfoTableChanged",
408: "EMsg_AISUpdatePackageInfoResponse",
409: "EMsg_AISCreateMarketingMessage",
410: "EMsg_AISCreateMarketingMessageResponse",
411: "EMsg_AISGetMarketingMessage",
412: "EMsg_AISGetMarketingMessageResponse",
413: "EMsg_AISUpdateMarketingMessage",
414: "EMsg_AISUpdateMarketingMessageResponse",
415: "EMsg_AISRequestMarketingMessageUpdate",
416: "EMsg_AISDeleteMarketingMessage",
419: "EMsg_AISGetMarketingTreatments",
420: "EMsg_AISGetMarketingTreatmentsResponse",
421: "EMsg_AISRequestMarketingTreatmentUpdate",
422: "EMsg_AISTestAddPackage",
423: "EMsg_AIGetAppGCFlags",
424: "EMsg_AIGetAppGCFlagsResponse",
425: "EMsg_AIGetAppList",
426: "EMsg_AIGetAppListResponse",
427: "EMsg_AIGetAppInfo",
428: "EMsg_AIGetAppInfoResponse",
429: "EMsg_AISGetCouponDefinition",
430: "EMsg_AISGetCouponDefinitionResponse",
500: "EMsg_BaseAM",
504: "EMsg_AMUpdateUserBanRequest",
505: "EMsg_AMAddLicense",
507: "EMsg_AMBeginProcessingLicenses",
508: "EMsg_AMSendSystemIMToUser",
509: "EMsg_AMExtendLicense",
510: "EMsg_AMAddMinutesToLicense",
511: "EMsg_AMCancelLicense",
512: "EMsg_AMInitPurchase",
513: "EMsg_AMPurchaseResponse",
514: "EMsg_AMGetFinalPrice",
515: "EMsg_AMGetFinalPriceResponse",
516: "EMsg_AMGetLegacyGameKey",
517: "EMsg_AMGetLegacyGameKeyResponse",
518: "EMsg_AMFindHungTransactions",
519: "EMsg_AMSetAccountTrustedRequest",
521: "EMsg_AMCompletePurchase",
522: "EMsg_AMCancelPurchase",
523: "EMsg_AMNewChallenge",
526: "EMsg_AMFixPendingPurchaseResponse",
527: "EMsg_AMIsUserBanned",
528: "EMsg_AMRegisterKey",
529: "EMsg_AMLoadActivationCodes",
530: "EMsg_AMLoadActivationCodesResponse",
531: "EMsg_AMLookupKeyResponse",
532: "EMsg_AMLookupKey",
533: "EMsg_AMChatCleanup",
534: "EMsg_AMClanCleanup",
535: "EMsg_AMFixPendingRefund",
536: "EMsg_AMReverseChargeback",
537: "EMsg_AMReverseChargebackResponse",
538: "EMsg_AMClanCleanupList",
539: "EMsg_AMGetLicenses",
540: "EMsg_AMGetLicensesResponse",
550: "EMsg_AllowUserToPlayQuery",
551: "EMsg_AllowUserToPlayResponse",
552: "EMsg_AMVerfiyUser",
553: "EMsg_AMClientNotPlaying",
554: "EMsg_ClientRequestFriendship",
555: "EMsg_AMRelayPublishStatus",
556: "EMsg_AMResetCommunityContent",
557: "EMsg_AMPrimePersonaStateCache",
558: "EMsg_AMAllowUserContentQuery",
559: "EMsg_AMAllowUserContentResponse",
560: "EMsg_AMInitPurchaseResponse",
561: "EMsg_AMRevokePurchaseResponse",
562: "EMsg_AMLockProfile",
563: "EMsg_AMRefreshGuestPasses",
564: "EMsg_AMInviteUserToClan",
565: "EMsg_AMAcknowledgeClanInvite",
566: "EMsg_AMGrantGuestPasses",
567: "EMsg_AMClanDataUpdated",
568: "EMsg_AMReloadAccount",
569: "EMsg_AMClientChatMsgRelay",
570: "EMsg_AMChatMulti",
571: "EMsg_AMClientChatInviteRelay",
572: "EMsg_AMChatInvite",
573: "EMsg_AMClientJoinChatRelay",
574: "EMsg_AMClientChatMemberInfoRelay",
575: "EMsg_AMPublishChatMemberInfo",
576: "EMsg_AMClientAcceptFriendInvite",
577: "EMsg_AMChatEnter",
578: "EMsg_AMClientPublishRemovalFromSource",
579: "EMsg_AMChatActionResult",
580: "EMsg_AMFindAccounts",
581: "EMsg_AMFindAccountsResponse",
584: "EMsg_AMSetAccountFlags",
586: "EMsg_AMCreateClan",
587: "EMsg_AMCreateClanResponse",
588: "EMsg_AMGetClanDetails",
589: "EMsg_AMGetClanDetailsResponse",
590: "EMsg_AMSetPersonaName",
591: "EMsg_AMSetAvatar",
592: "EMsg_AMAuthenticateUser",
593: "EMsg_AMAuthenticateUserResponse",
594: "EMsg_AMGetAccountFriendsCount",
595: "EMsg_AMGetAccountFriendsCountResponse",
596: "EMsg_AMP2PIntroducerMessage",
597: "EMsg_ClientChatAction",
598: "EMsg_AMClientChatActionRelay",
600: "EMsg_BaseVS",
601: "EMsg_VACResponse",
602: "EMsg_ReqChallengeTest",
604: "EMsg_VSMarkCheat",
605: "EMsg_VSAddCheat",
606: "EMsg_VSPurgeCodeModDB",
607: "EMsg_VSGetChallengeResults",
608: "EMsg_VSChallengeResultText",
609: "EMsg_VSReportLingerer",
610: "EMsg_VSRequestManagedChallenge",
611: "EMsg_VSLoadDBFinished",
625: "EMsg_BaseDRMS",
628: "EMsg_DRMBuildBlobRequest",
629: "EMsg_DRMBuildBlobResponse",
630: "EMsg_DRMResolveGuidRequest",
631: "EMsg_DRMResolveGuidResponse",
633: "EMsg_DRMVariabilityReport",
634: "EMsg_DRMVariabilityReportResponse",
635: "EMsg_DRMStabilityReport",
636: "EMsg_DRMStabilityReportResponse",
637: "EMsg_DRMDetailsReportRequest",
638: "EMsg_DRMDetailsReportResponse",
639: "EMsg_DRMProcessFile",
640: "EMsg_DRMAdminUpdate",
641: "EMsg_DRMAdminUpdateResponse",
642: "EMsg_DRMSync",
643: "EMsg_DRMSyncResponse",
644: "EMsg_DRMProcessFileResponse",
645: "EMsg_DRMEmptyGuidCache",
646: "EMsg_DRMEmptyGuidCacheResponse",
650: "EMsg_BaseCS",
652: "EMsg_CSUserContentRequest",
700: "EMsg_BaseClient",
701: "EMsg_ClientLogOn_Deprecated",
702: "EMsg_ClientAnonLogOn_Deprecated",
703: "EMsg_ClientHeartBeat",
704: "EMsg_ClientVACResponse",
705: "EMsg_ClientGamesPlayed_obsolete",
706: "EMsg_ClientLogOff",
707: "EMsg_ClientNoUDPConnectivity",
708: "EMsg_ClientInformOfCreateAccount",
709: "EMsg_ClientAckVACBan",
710: "EMsg_ClientConnectionStats",
711: "EMsg_ClientInitPurchase",
712: "EMsg_ClientPingResponse",
714: "EMsg_ClientRemoveFriend",
715: "EMsg_ClientGamesPlayedNoDataBlob",
716: "EMsg_ClientChangeStatus",
717: "EMsg_ClientVacStatusResponse",
718: "EMsg_ClientFriendMsg",
719: "EMsg_ClientGameConnect_obsolete",
720: "EMsg_ClientGamesPlayed2_obsolete",
721: "EMsg_ClientGameEnded_obsolete",
722: "EMsg_ClientGetFinalPrice",
726: "EMsg_ClientSystemIM",
727: "EMsg_ClientSystemIMAck",
728: "EMsg_ClientGetLicenses",
729: "EMsg_ClientCancelLicense",
730: "EMsg_ClientGetLegacyGameKey",
731: "EMsg_ClientContentServerLogOn_Deprecated",
732: "EMsg_ClientAckVACBan2",
735: "EMsg_ClientAckMessageByGID",
736: "EMsg_ClientGetPurchaseReceipts",
737: "EMsg_ClientAckPurchaseReceipt",
738: "EMsg_ClientGamesPlayed3_obsolete",
739: "EMsg_ClientSendGuestPass",
740: "EMsg_ClientAckGuestPass",
741: "EMsg_ClientRedeemGuestPass",
742: "EMsg_ClientGamesPlayed",
743: "EMsg_ClientRegisterKey",
744: "EMsg_ClientInviteUserToClan",
745: "EMsg_ClientAcknowledgeClanInvite",
746: "EMsg_ClientPurchaseWithMachineID",
747: "EMsg_ClientAppUsageEvent",
748: "EMsg_ClientGetGiftTargetList",
749: "EMsg_ClientGetGiftTargetListResponse",
751: "EMsg_ClientLogOnResponse",
753: "EMsg_ClientVACChallenge",
755: "EMsg_ClientSetHeartbeatRate",
756: "EMsg_ClientNotLoggedOnDeprecated",
757: "EMsg_ClientLoggedOff",
758: "EMsg_GSApprove",
759: "EMsg_GSDeny",
760: "EMsg_GSKick",
761: "EMsg_ClientCreateAcctResponse",
763: "EMsg_ClientPurchaseResponse",
764: "EMsg_ClientPing",
765: "EMsg_ClientNOP",
766: "EMsg_ClientPersonaState",
767: "EMsg_ClientFriendsList",
768: "EMsg_ClientAccountInfo",
770: "EMsg_ClientVacStatusQuery",
771: "EMsg_ClientNewsUpdate",
773: "EMsg_ClientGameConnectDeny",
774: "EMsg_GSStatusReply",
775: "EMsg_ClientGetFinalPriceResponse",
779: "EMsg_ClientGameConnectTokens",
780: "EMsg_ClientLicenseList",
781: "EMsg_ClientCancelLicenseResponse",
782: "EMsg_ClientVACBanStatus",
783: "EMsg_ClientCMList",
784: "EMsg_ClientEncryptPct",
785: "EMsg_ClientGetLegacyGameKeyResponse",
786: "EMsg_ClientFavoritesList",
787: "EMsg_CSUserContentApprove",
788: "EMsg_CSUserContentDeny",
789: "EMsg_ClientInitPurchaseResponse",
791: "EMsg_ClientAddFriend",
792: "EMsg_ClientAddFriendResponse",
793: "EMsg_ClientInviteFriend",
794: "EMsg_ClientInviteFriendResponse",
795: "EMsg_ClientSendGuestPassResponse",
796: "EMsg_ClientAckGuestPassResponse",
797: "EMsg_ClientRedeemGuestPassResponse",
798: "EMsg_ClientUpdateGuestPassesList",
799: "EMsg_ClientChatMsg",
800: "EMsg_ClientChatInvite",
801: "EMsg_ClientJoinChat",
802: "EMsg_ClientChatMemberInfo",
803: "EMsg_ClientLogOnWithCredentials_Deprecated",
805: "EMsg_ClientPasswordChangeResponse",
807: "EMsg_ClientChatEnter",
808: "EMsg_ClientFriendRemovedFromSource",
809: "EMsg_ClientCreateChat",
810: "EMsg_ClientCreateChatResponse",
811: "EMsg_ClientUpdateChatMetadata",
813: "EMsg_ClientP2PIntroducerMessage",
814: "EMsg_ClientChatActionResult",
815: "EMsg_ClientRequestFriendData",
818: "EMsg_ClientGetUserStats",
819: "EMsg_ClientGetUserStatsResponse",
820: "EMsg_ClientStoreUserStats",
821: "EMsg_ClientStoreUserStatsResponse",
822: "EMsg_ClientClanState",
830: "EMsg_ClientServiceModule",
831: "EMsg_ClientServiceCall",
832: "EMsg_ClientServiceCallResponse",
833: "EMsg_ClientPackageInfoRequest",
834: "EMsg_ClientPackageInfoResponse",
839: "EMsg_ClientNatTraversalStatEvent",
840: "EMsg_ClientAppInfoRequest",
841: "EMsg_ClientAppInfoResponse",
842: "EMsg_ClientSteamUsageEvent",
845: "EMsg_ClientCheckPassword",
846: "EMsg_ClientResetPassword",
848: "EMsg_ClientCheckPasswordResponse",
849: "EMsg_ClientResetPasswordResponse",
850: "EMsg_ClientSessionToken",
851: "EMsg_ClientDRMProblemReport",
855: "EMsg_ClientSetIgnoreFriend",
856: "EMsg_ClientSetIgnoreFriendResponse",
857: "EMsg_ClientGetAppOwnershipTicket",
858: "EMsg_ClientGetAppOwnershipTicketResponse",
860: "EMsg_ClientGetLobbyListResponse",
861: "EMsg_ClientGetLobbyMetadata",
862: "EMsg_ClientGetLobbyMetadataResponse",
863: "EMsg_ClientVTTCert",
866: "EMsg_ClientAppInfoUpdate",
867: "EMsg_ClientAppInfoChanges",
880: "EMsg_ClientServerList",
891: "EMsg_ClientEmailChangeResponse",
892: "EMsg_ClientSecretQAChangeResponse",
896: "EMsg_ClientDRMBlobRequest",
897: "EMsg_ClientDRMBlobResponse",
898: "EMsg_ClientLookupKey",
899: "EMsg_ClientLookupKeyResponse",
900: "EMsg_BaseGameServer",
901: "EMsg_GSDisconnectNotice",
903: "EMsg_GSStatus",
905: "EMsg_GSUserPlaying",
906: "EMsg_GSStatus2",
907: "EMsg_GSStatusUpdate_Unused",
908: "EMsg_GSServerType",
909: "EMsg_GSPlayerList",
910: "EMsg_GSGetUserAchievementStatus",
911: "EMsg_GSGetUserAchievementStatusResponse",
918: "EMsg_GSGetPlayStats",
919: "EMsg_GSGetPlayStatsResponse",
920: "EMsg_GSGetUserGroupStatus",
921: "EMsg_AMGetUserGroupStatus",
922: "EMsg_AMGetUserGroupStatusResponse",
923: "EMsg_GSGetUserGroupStatusResponse",
936: "EMsg_GSGetReputation",
937: "EMsg_GSGetReputationResponse",
938: "EMsg_GSAssociateWithClan",
939: "EMsg_GSAssociateWithClanResponse",
940: "EMsg_GSComputeNewPlayerCompatibility",
941: "EMsg_GSComputeNewPlayerCompatibilityResponse",
1000: "EMsg_BaseAdmin",
1004: "EMsg_AdminCmdResponse",
1005: "EMsg_AdminLogListenRequest",
1006: "EMsg_AdminLogEvent",
1007: "EMsg_LogSearchRequest",
1008: "EMsg_LogSearchResponse",
1009: "EMsg_LogSearchCancel",
1010: "EMsg_UniverseData",
1014: "EMsg_RequestStatHistory",
1015: "EMsg_StatHistory",
1017: "EMsg_AdminPwLogon",
1018: "EMsg_AdminPwLogonResponse",
1019: "EMsg_AdminSpew",
1020: "EMsg_AdminConsoleTitle",
1023: "EMsg_AdminGCSpew",
1024: "EMsg_AdminGCCommand",
1025: "EMsg_AdminGCGetCommandList",
1026: "EMsg_AdminGCGetCommandListResponse",
1027: "EMsg_FBSConnectionData",
1028: "EMsg_AdminMsgSpew",
1100: "EMsg_BaseFBS",
1101: "EMsg_FBSVersionInfo",
1102: "EMsg_FBSForceRefresh",
1103: "EMsg_FBSForceBounce",
1104: "EMsg_FBSDeployPackage",
1105: "EMsg_FBSDeployResponse",
1106: "EMsg_FBSUpdateBootstrapper",
1107: "EMsg_FBSSetState",
1108: "EMsg_FBSApplyOSUpdates",
1109: "EMsg_FBSRunCMDScript",
1110: "EMsg_FBSRebootBox",
1111: "EMsg_FBSSetBigBrotherMode",
1112: "EMsg_FBSMinidumpServer",
1113: "EMsg_FBSSetShellCount_obsolete",
1114: "EMsg_FBSDeployHotFixPackage",
1115: "EMsg_FBSDeployHotFixResponse",
1116: "EMsg_FBSDownloadHotFix",
1117: "EMsg_FBSDownloadHotFixResponse",
1118: "EMsg_FBSUpdateTargetConfigFile",
1119: "EMsg_FBSApplyAccountCred",
1120: "EMsg_FBSApplyAccountCredResponse",
1121: "EMsg_FBSSetShellCount",
1122: "EMsg_FBSTerminateShell",
1123: "EMsg_FBSQueryGMForRequest",
1124: "EMsg_FBSQueryGMResponse",
1125: "EMsg_FBSTerminateZombies",
1126: "EMsg_FBSInfoFromBootstrapper",
1127: "EMsg_FBSRebootBoxResponse",
1128: "EMsg_FBSBootstrapperPackageRequest",
1129: "EMsg_FBSBootstrapperPackageResponse",
1130: "EMsg_FBSBootstrapperGetPackageChunk",
1131: "EMsg_FBSBootstrapperGetPackageChunkResponse",
1132: "EMsg_FBSBootstrapperPackageTransferProgress",
1133: "EMsg_FBSRestartBootstrapper",
1200: "EMsg_BaseFileXfer",
1201: "EMsg_FileXferResponse",
1202: "EMsg_FileXferData",
1203: "EMsg_FileXferEnd",
1204: "EMsg_FileXferDataAck",
1300: "EMsg_BaseChannelAuth",
1301: "EMsg_ChannelAuthResponse",
1302: "EMsg_ChannelAuthResult",
1303: "EMsg_ChannelEncryptRequest",
1304: "EMsg_ChannelEncryptResponse",
1305: "EMsg_ChannelEncryptResult",
1400: "EMsg_BaseBS",
1401: "EMsg_BSPurchaseStart",
1402: "EMsg_BSPurchaseResponse",
1404: "EMsg_BSSettleNOVA",
1406: "EMsg_BSSettleComplete",
1407: "EMsg_BSBannedRequest",
1408: "EMsg_BSInitPayPalTxn",
1409: "EMsg_BSInitPayPalTxnResponse",
1410: "EMsg_BSGetPayPalUserInfo",
1411: "EMsg_BSGetPayPalUserInfoResponse",
1413: "EMsg_BSRefundTxn",
1414: "EMsg_BSRefundTxnResponse",
1415: "EMsg_BSGetEvents",
1416: "EMsg_BSChaseRFRRequest",
1417: "EMsg_BSPaymentInstrBan",
1418: "EMsg_BSPaymentInstrBanResponse",
1419: "EMsg_BSProcessGCReports",
1420: "EMsg_BSProcessPPReports",
1421: "EMsg_BSInitGCBankXferTxn",
1422: "EMsg_BSInitGCBankXferTxnResponse",
1423: "EMsg_BSQueryGCBankXferTxn",
1424: "EMsg_BSQueryGCBankXferTxnResponse",
1425: "EMsg_BSCommitGCTxn",
1426: "EMsg_BSQueryTransactionStatus",
1427: "EMsg_BSQueryTransactionStatusResponse",
1428: "EMsg_BSQueryCBOrderStatus",
1429: "EMsg_BSQueryCBOrderStatusResponse",
1430: "EMsg_BSRunRedFlagReport",
1431: "EMsg_BSQueryPaymentInstUsage",
1432: "EMsg_BSQueryPaymentInstResponse",
1433: "EMsg_BSQueryTxnExtendedInfo",
1434: "EMsg_BSQueryTxnExtendedInfoResponse",
1435: "EMsg_BSUpdateConversionRates",
1436: "EMsg_BSProcessUSBankReports",
1437: "EMsg_BSPurchaseRunFraudChecks",
1438: "EMsg_BSPurchaseRunFraudChecksResponse",
1439: "EMsg_BSStartShippingJobs",
1440: "EMsg_BSQueryBankInformation",
1441: "EMsg_BSQueryBankInformationResponse",
1445: "EMsg_BSValidateXsollaSignature",
1446: "EMsg_BSValidateXsollaSignatureResponse",
1448: "EMsg_BSQiwiWalletInvoice",
1449: "EMsg_BSQiwiWalletInvoiceResponse",
1450: "EMsg_BSUpdateInventoryFromProPack",
1451: "EMsg_BSUpdateInventoryFromProPackResponse",
1452: "EMsg_BSSendShippingRequest",
1453: "EMsg_BSSendShippingRequestResponse",
1454: "EMsg_BSGetProPackOrderStatus",
1455: "EMsg_BSGetProPackOrderStatusResponse",
1456: "EMsg_BSCheckJobRunning",
1457: "EMsg_BSCheckJobRunningResponse",
1458: "EMsg_BSResetPackagePurchaseRateLimit",
1459: "EMsg_BSResetPackagePurchaseRateLimitResponse",
1460: "EMsg_BSUpdatePaymentData",
1461: "EMsg_BSUpdatePaymentDataResponse",
1462: "EMsg_BSGetBillingAddress",
1463: "EMsg_BSGetBillingAddressResponse",
1464: "EMsg_BSGetCreditCardInfo",
1465: "EMsg_BSGetCreditCardInfoResponse",
1468: "EMsg_BSRemoveExpiredPaymentData",
1469: "EMsg_BSRemoveExpiredPaymentDataResponse",
1470: "EMsg_BSConvertToCurrentKeys",
1471: "EMsg_BSConvertToCurrentKeysResponse",
1472: "EMsg_BSInitPurchase",
1473: "EMsg_BSInitPurchaseResponse",
1474: "EMsg_BSCompletePurchase",
1475: "EMsg_BSCompletePurchaseResponse",
1476: "EMsg_BSPruneCardUsageStats",
1477: "EMsg_BSPruneCardUsageStatsResponse",
1478: "EMsg_BSStoreBankInformation",
1479: "EMsg_BSStoreBankInformationResponse",
1480: "EMsg_BSVerifyPOSAKey",
1481: "EMsg_BSVerifyPOSAKeyResponse",
1482: "EMsg_BSReverseRedeemPOSAKey",
1483: "EMsg_BSReverseRedeemPOSAKeyResponse",
1484: "EMsg_BSQueryFindCreditCard",
1485: "EMsg_BSQueryFindCreditCardResponse",
1486: "EMsg_BSStatusInquiryPOSAKey",
1487: "EMsg_BSStatusInquiryPOSAKeyResponse",
1488: "EMsg_BSValidateMoPaySignature",
1489: "EMsg_BSValidateMoPaySignatureResponse",
1490: "EMsg_BSMoPayConfirmProductDelivery",
1491: "EMsg_BSMoPayConfirmProductDeliveryResponse",
1492: "EMsg_BSGenerateMoPayMD5",
1493: "EMsg_BSGenerateMoPayMD5Response",
1494: "EMsg_BSBoaCompraConfirmProductDelivery",
1495: "EMsg_BSBoaCompraConfirmProductDeliveryResponse",
1496: "EMsg_BSGenerateBoaCompraMD5",
1497: "EMsg_BSGenerateBoaCompraMD5Response",
1500: "EMsg_BaseATS",
1501: "EMsg_ATSStartStressTest",
1502: "EMsg_ATSStopStressTest",
1503: "EMsg_ATSRunFailServerTest",
1504: "EMsg_ATSUFSPerfTestTask",
1505: "EMsg_ATSUFSPerfTestResponse",
1506: "EMsg_ATSCycleTCM",
1507: "EMsg_ATSInitDRMSStressTest",
1508: "EMsg_ATSCallTest",
1509: "EMsg_ATSCallTestReply",
1510: "EMsg_ATSStartExternalStress",
1511: "EMsg_ATSExternalStressJobStart",
1512: "EMsg_ATSExternalStressJobQueued",
1513: "EMsg_ATSExternalStressJobRunning",
1514: "EMsg_ATSExternalStressJobStopped",
1515: "EMsg_ATSExternalStressJobStopAll",
1516: "EMsg_ATSExternalStressActionResult",
1517: "EMsg_ATSStarted",
1518: "EMsg_ATSCSPerfTestTask",
1519: "EMsg_ATSCSPerfTestResponse",
1600: "EMsg_BaseDP",
1601: "EMsg_DPSetPublishingState",
1602: "EMsg_DPGamePlayedStats",
1603: "EMsg_DPUniquePlayersStat",
1605: "EMsg_DPVacInfractionStats",
1606: "EMsg_DPVacBanStats",
1607: "EMsg_DPBlockingStats",
1608: "EMsg_DPNatTraversalStats",
1609: "EMsg_DPSteamUsageEvent",
1610: "EMsg_DPVacCertBanStats",
1611: "EMsg_DPVacCafeBanStats",
1612: "EMsg_DPCloudStats",
1613: "EMsg_DPAchievementStats",
1614: "EMsg_DPAccountCreationStats",
1615: "EMsg_DPGetPlayerCount",
1616: "EMsg_DPGetPlayerCountResponse",
1617: "EMsg_DPGameServersPlayersStats",
1618: "EMsg_DPDownloadRateStatistics",
1619: "EMsg_DPFacebookStatistics",
1620: "EMsg_ClientDPCheckSpecialSurvey",
1621: "EMsg_ClientDPCheckSpecialSurveyResponse",
1622: "EMsg_ClientDPSendSpecialSurveyResponse",
1623: "EMsg_ClientDPSendSpecialSurveyResponseReply",
1624: "EMsg_DPStoreSaleStatistics",
1625: "EMsg_ClientDPUpdateAppJobReport",
1627: "EMsg_ClientDPSteam2AppStarted",
1626: "EMsg_DPUpdateContentEvent",
1630: "EMsg_ClientDPContentStatsReport",
1700: "EMsg_BaseCM",
1701: "EMsg_CMSetAllowState",
1702: "EMsg_CMSpewAllowState",
1703: "EMsg_CMAppInfoResponseDeprecated",
1800: "EMsg_BaseDSS",
1801: "EMsg_DSSNewFile",
1802: "EMsg_DSSCurrentFileList",
1803: "EMsg_DSSSynchList",
1804: "EMsg_DSSSynchListResponse",
1805: "EMsg_DSSSynchSubscribe",
1806: "EMsg_DSSSynchUnsubscribe",
1900: "EMsg_BaseEPM",
1901: "EMsg_EPMStartProcess",
1902: "EMsg_EPMStopProcess",
1903: "EMsg_EPMRestartProcess",
2200: "EMsg_BaseGC",
2201: "EMsg_AMRelayToGC",
2202: "EMsg_GCUpdatePlayedState",
2203: "EMsg_GCCmdRevive",
2204: "EMsg_GCCmdBounce",
2205: "EMsg_GCCmdForceBounce",
2206: "EMsg_GCCmdDown",
2207: "EMsg_GCCmdDeploy",
2208: "EMsg_GCCmdDeployResponse",
2209: "EMsg_GCCmdSwitch",
2210: "EMsg_AMRefreshSessions",
2211: "EMsg_GCUpdateGSState",
2212: "EMsg_GCAchievementAwarded",
2213: "EMsg_GCSystemMessage",
2214: "EMsg_GCValidateSession",
2215: "EMsg_GCValidateSessionResponse",
2216: "EMsg_GCCmdStatus",
2217: "EMsg_GCRegisterWebInterfaces",
2218: "EMsg_GCGetAccountDetails",
2219: "EMsg_GCInterAppMessage",
2220: "EMsg_GCGetEmailTemplate",
2221: "EMsg_GCGetEmailTemplateResponse",
2222: "EMsg_ISRelayToGCH",
2223: "EMsg_GCHRelayClientToIS",
2224: "EMsg_GCHUpdateSession",
2225: "EMsg_GCHRequestUpdateSession",
2226: "EMsg_GCHRequestStatus",
2227: "EMsg_GCHRequestStatusResponse",
2500: "EMsg_BaseP2P",
2502: "EMsg_P2PIntroducerMessage",
2900: "EMsg_BaseSM",
2902: "EMsg_SMExpensiveReport",
2903: "EMsg_SMHourlyReport",
2904: "EMsg_SMFishingReport",
2905: "EMsg_SMPartitionRenames",
2906: "EMsg_SMMonitorSpace",
2907: "EMsg_SMGetSchemaConversionResults",
2908: "EMsg_SMGetSchemaConversionResultsResponse",
3000: "EMsg_BaseTest",
3001: "EMsg_JobHeartbeatTest",
3002: "EMsg_JobHeartbeatTestResponse",
3100: "EMsg_BaseFTSRange",
3101: "EMsg_FTSGetBrowseCounts",
3102: "EMsg_FTSGetBrowseCountsResponse",
3103: "EMsg_FTSBrowseClans",
3104: "EMsg_FTSBrowseClansResponse",
3105: "EMsg_FTSSearchClansByLocation",
3106: "EMsg_FTSSearchClansByLocationResponse",
3107: "EMsg_FTSSearchPlayersByLocation",
3108: "EMsg_FTSSearchPlayersByLocationResponse",
3109: "EMsg_FTSClanDeleted",
3110: "EMsg_FTSSearch",
3111: "EMsg_FTSSearchResponse",
3112: "EMsg_FTSSearchStatus",
3113: "EMsg_FTSSearchStatusResponse",
3114: "EMsg_FTSGetGSPlayStats",
3115: "EMsg_FTSGetGSPlayStatsResponse",
3116: "EMsg_FTSGetGSPlayStatsForServer",
3117: "EMsg_FTSGetGSPlayStatsForServerResponse",
3118: "EMsg_FTSReportIPUpdates",
3150: "EMsg_BaseCCSRange",
3151: "EMsg_CCSGetComments",
3152: "EMsg_CCSGetCommentsResponse",
3153: "EMsg_CCSAddComment",
3154: "EMsg_CCSAddCommentResponse",
3155: "EMsg_CCSDeleteComment",
3156: "EMsg_CCSDeleteCommentResponse",
3157: "EMsg_CCSPreloadComments",
3158: "EMsg_CCSNotifyCommentCount",
3159: "EMsg_CCSGetCommentsForNews",
3160: "EMsg_CCSGetCommentsForNewsResponse",
3161: "EMsg_CCSDeleteAllCommentsByAuthor",
3162: "EMsg_CCSDeleteAllCommentsByAuthorResponse",
3200: "EMsg_BaseLBSRange",
3201: "EMsg_LBSSetScore",
3202: "EMsg_LBSSetScoreResponse",
3203: "EMsg_LBSFindOrCreateLB",
3204: "EMsg_LBSFindOrCreateLBResponse",
3205: "EMsg_LBSGetLBEntries",
3206: "EMsg_LBSGetLBEntriesResponse",
3207: "EMsg_LBSGetLBList",
3208: "EMsg_LBSGetLBListResponse",
3209: "EMsg_LBSSetLBDetails",
3210: "EMsg_LBSDeleteLB",
3211: "EMsg_LBSDeleteLBEntry",
3212: "EMsg_LBSResetLB",
3400: "EMsg_BaseOGS",
3401: "EMsg_OGSBeginSession",
3402: "EMsg_OGSBeginSessionResponse",
3403: "EMsg_OGSEndSession",
3404: "EMsg_OGSEndSessionResponse",
3406: "EMsg_OGSWriteAppSessionRow",
3600: "EMsg_BaseBRP",
3601: "EMsg_BRPStartShippingJobs",
3602: "EMsg_BRPProcessUSBankReports",
3603: "EMsg_BRPProcessGCReports",
3604: "EMsg_BRPProcessPPReports",
3605: "EMsg_BRPSettleNOVA",
3606: "EMsg_BRPSettleCB",
3607: "EMsg_BRPCommitGC",
3608: "EMsg_BRPCommitGCResponse",
3609: "EMsg_BRPFindHungTransactions",
3610: "EMsg_BRPCheckFinanceCloseOutDate",
3611: "EMsg_BRPProcessLicenses",
3612: "EMsg_BRPProcessLicensesResponse",
3613: "EMsg_BRPRemoveExpiredPaymentData",
3614: "EMsg_BRPRemoveExpiredPaymentDataResponse",
3615: "EMsg_BRPConvertToCurrentKeys",
3616: "EMsg_BRPConvertToCurrentKeysResponse",
3617: "EMsg_BRPPruneCardUsageStats",
3618: "EMsg_BRPPruneCardUsageStatsResponse",
3619: "EMsg_BRPCheckActivationCodes",
3620: "EMsg_BRPCheckActivationCodesResponse",
4000: "EMsg_BaseAMRange2",
4001: "EMsg_AMCreateChat",
4002: "EMsg_AMCreateChatResponse",
4003: "EMsg_AMUpdateChatMetadata",
4004: "EMsg_AMPublishChatMetadata",
4005: "EMsg_AMSetProfileURL",
4006: "EMsg_AMGetAccountEmailAddress",
4007: "EMsg_AMGetAccountEmailAddressResponse",
4008: "EMsg_AMRequestFriendData",
4009: "EMsg_AMRouteToClients",
4010: "EMsg_AMLeaveClan",
4011: "EMsg_AMClanPermissions",
4012: "EMsg_AMClanPermissionsResponse",
4013: "EMsg_AMCreateClanEvent",
4014: "EMsg_AMCreateClanEventResponse",
4015: "EMsg_AMUpdateClanEvent",
4016: "EMsg_AMUpdateClanEventResponse",
4017: "EMsg_AMGetClanEvents",
4018: "EMsg_AMGetClanEventsResponse",
4019: "EMsg_AMDeleteClanEvent",
4020: "EMsg_AMDeleteClanEventResponse",
4021: "EMsg_AMSetClanPermissionSettings",
4022: "EMsg_AMSetClanPermissionSettingsResponse",
4023: "EMsg_AMGetClanPermissionSettings",
4024: "EMsg_AMGetClanPermissionSettingsResponse",
4025: "EMsg_AMPublishChatRoomInfo",
4026: "EMsg_ClientChatRoomInfo",
4027: "EMsg_AMCreateClanAnnouncement",
4028: "EMsg_AMCreateClanAnnouncementResponse",
4029: "EMsg_AMUpdateClanAnnouncement",
4030: "EMsg_AMUpdateClanAnnouncementResponse",
4031: "EMsg_AMGetClanAnnouncementsCount",
4032: "EMsg_AMGetClanAnnouncementsCountResponse",
4033: "EMsg_AMGetClanAnnouncements",
4034: "EMsg_AMGetClanAnnouncementsResponse",
4035: "EMsg_AMDeleteClanAnnouncement",
4036: "EMsg_AMDeleteClanAnnouncementResponse",
4037: "EMsg_AMGetSingleClanAnnouncement",
4038: "EMsg_AMGetSingleClanAnnouncementResponse",
4039: "EMsg_AMGetClanHistory",
4040: "EMsg_AMGetClanHistoryResponse",
4041: "EMsg_AMGetClanPermissionBits",
4042: "EMsg_AMGetClanPermissionBitsResponse",
4043: "EMsg_AMSetClanPermissionBits",
4044: "EMsg_AMSetClanPermissionBitsResponse",
4045: "EMsg_AMSessionInfoRequest",
4046: "EMsg_AMSessionInfoResponse",
4047: "EMsg_AMValidateWGToken",
4048: "EMsg_AMGetSingleClanEvent",
4049: "EMsg_AMGetSingleClanEventResponse",
4050: "EMsg_AMGetClanRank",
4051: "EMsg_AMGetClanRankResponse",
4052: "EMsg_AMSetClanRank",
4053: "EMsg_AMSetClanRankResponse",
4054: "EMsg_AMGetClanPOTW",
4055: "EMsg_AMGetClanPOTWResponse",
4056: "EMsg_AMSetClanPOTW",
4057: "EMsg_AMSetClanPOTWResponse",
4058: "EMsg_AMRequestChatMetadata",
4059: "EMsg_AMDumpUser",
4060: "EMsg_AMKickUserFromClan",
4061: "EMsg_AMAddFounderToClan",
4062: "EMsg_AMValidateWGTokenResponse",
4063: "EMsg_AMSetCommunityState",
4064: "EMsg_AMSetAccountDetails",
4065: "EMsg_AMGetChatBanList",
4066: "EMsg_AMGetChatBanListResponse",
4067: "EMsg_AMUnBanFromChat",
4068: "EMsg_AMSetClanDetails",
4069: "EMsg_AMGetAccountLinks",
4070: "EMsg_AMGetAccountLinksResponse",
4071: "EMsg_AMSetAccountLinks",
4072: "EMsg_AMSetAccountLinksResponse",
4073: "EMsg_AMGetUserGameStats",
4074: "EMsg_AMGetUserGameStatsResponse",
4075: "EMsg_AMCheckClanMembership",
4076: "EMsg_AMGetClanMembers",
4077: "EMsg_AMGetClanMembersResponse",
4078: "EMsg_AMJoinPublicClan",
4079: "EMsg_AMNotifyChatOfClanChange",
4080: "EMsg_AMResubmitPurchase",
4081: "EMsg_AMAddFriend",
4082: "EMsg_AMAddFriendResponse",
4083: "EMsg_AMRemoveFriend",
4084: "EMsg_AMDumpClan",
4085: "EMsg_AMChangeClanOwner",
4086: "EMsg_AMCancelEasyCollect",
4087: "EMsg_AMCancelEasyCollectResponse",
4088: "EMsg_AMGetClanMembershipList",
4089: "EMsg_AMGetClanMembershipListResponse",
4090: "EMsg_AMClansInCommon",
4091: "EMsg_AMClansInCommonResponse",
4092: "EMsg_AMIsValidAccountID",
4093: "EMsg_AMConvertClan",
4094: "EMsg_AMGetGiftTargetListRelay",
4095: "EMsg_AMWipeFriendsList",
4096: "EMsg_AMSetIgnored",
4097: "EMsg_AMClansInCommonCountResponse",
4098: "EMsg_AMFriendsList",
4099: "EMsg_AMFriendsListResponse",
4100: "EMsg_AMFriendsInCommon",
4101: "EMsg_AMFriendsInCommonResponse",
4102: "EMsg_AMFriendsInCommonCountResponse",
4103: "EMsg_AMClansInCommonCount",
4104: "EMsg_AMChallengeVerdict",
4105: "EMsg_AMChallengeNotification",
4106: "EMsg_AMFindGSByIP",
4107: "EMsg_AMFoundGSByIP",
4108: "EMsg_AMGiftRevoked",
4109: "EMsg_AMCreateAccountRecord",
4110: "EMsg_AMUserClanList",
4111: "EMsg_AMUserClanListResponse",
4112: "EMsg_AMGetAccountDetails2",
4113: "EMsg_AMGetAccountDetailsResponse2",
4114: "EMsg_AMSetCommunityProfileSettings",
4115: "EMsg_AMSetCommunityProfileSettingsResponse",
4116: "EMsg_AMGetCommunityPrivacyState",
4117: "EMsg_AMGetCommunityPrivacyStateResponse",
4118: "EMsg_AMCheckClanInviteRateLimiting",
4119: "EMsg_AMGetUserAchievementStatus",
4120: "EMsg_AMGetIgnored",
4121: "EMsg_AMGetIgnoredResponse",
4122: "EMsg_AMSetIgnoredResponse",
4123: "EMsg_AMSetFriendRelationshipNone",
4124: "EMsg_AMGetFriendRelationship",
4125: "EMsg_AMGetFriendRelationshipResponse",
4126: "EMsg_AMServiceModulesCache",
4127: "EMsg_AMServiceModulesCall",
4128: "EMsg_AMServiceModulesCallResponse",
4129: "EMsg_AMGetCaptchaDataForIP",
4130: "EMsg_AMGetCaptchaDataForIPResponse",
4131: "EMsg_AMValidateCaptchaDataForIP",
4132: "EMsg_AMValidateCaptchaDataForIPResponse",
4133: "EMsg_AMTrackFailedAuthByIP",
4134: "EMsg_AMGetCaptchaDataByGID",
4135: "EMsg_AMGetCaptchaDataByGIDResponse",
4136: "EMsg_AMGetLobbyList",
4137: "EMsg_AMGetLobbyListResponse",
4138: "EMsg_AMGetLobbyMetadata",
4139: "EMsg_AMGetLobbyMetadataResponse",
4140: "EMsg_CommunityAddFriendNews",
4141: "EMsg_AMAddClanNews",
4142: "EMsg_AMWriteNews",
4143: "EMsg_AMFindClanUser",
4144: "EMsg_AMFindClanUserResponse",
4145: "EMsg_AMBanFromChat",
4146: "EMsg_AMGetUserHistoryResponse",
4147: "EMsg_AMGetUserNewsSubscriptions",
4148: "EMsg_AMGetUserNewsSubscriptionsResponse",
4149: "EMsg_AMSetUserNewsSubscriptions",
4150: "EMsg_AMGetUserNews",
4151: "EMsg_AMGetUserNewsResponse",
4152: "EMsg_AMSendQueuedEmails",
4153: "EMsg_AMSetLicenseFlags",
4154: "EMsg_AMGetUserHistory",
4155: "EMsg_CommunityDeleteUserNews",
4156: "EMsg_AMAllowUserFilesRequest",
4157: "EMsg_AMAllowUserFilesResponse",
4158: "EMsg_AMGetAccountStatus",
4159: "EMsg_AMGetAccountStatusResponse",
4160: "EMsg_AMEditBanReason",
4161: "EMsg_AMCheckClanMembershipResponse",
4162: "EMsg_AMProbeClanMembershipList",
4163: "EMsg_AMProbeClanMembershipListResponse",
4165: "EMsg_AMGetFriendsLobbies",
4166: "EMsg_AMGetFriendsLobbiesResponse",
4172: "EMsg_AMGetUserFriendNewsResponse",
4173: "EMsg_CommunityGetUserFriendNews",
4174: "EMsg_AMGetUserClansNewsResponse",
4175: "EMsg_AMGetUserClansNews",
4176: "EMsg_AMStoreInitPurchase",
4177: "EMsg_AMStoreInitPurchaseResponse",
4178: "EMsg_AMStoreGetFinalPrice",
4179: "EMsg_AMStoreGetFinalPriceResponse",
4180: "EMsg_AMStoreCompletePurchase",
4181: "EMsg_AMStoreCancelPurchase",
4182: "EMsg_AMStorePurchaseResponse",
4183: "EMsg_AMCreateAccountRecordInSteam3",
4184: "EMsg_AMGetPreviousCBAccount",
4185: "EMsg_AMGetPreviousCBAccountResponse",
4186: "EMsg_AMUpdateBillingAddress",
4187: "EMsg_AMUpdateBillingAddressResponse",
4188: "EMsg_AMGetBillingAddress",
4189: "EMsg_AMGetBillingAddressResponse",
4190: "EMsg_AMGetUserLicenseHistory",
4191: "EMsg_AMGetUserLicenseHistoryResponse",
4194: "EMsg_AMSupportChangePassword",
4195: "EMsg_AMSupportChangeEmail",
4196: "EMsg_AMSupportChangeSecretQA",
4197: "EMsg_AMResetUserVerificationGSByIP",
4198: "EMsg_AMUpdateGSPlayStats",
4199: "EMsg_AMSupportEnableOrDisable",
4200: "EMsg_AMGetComments",
4201: "EMsg_AMGetCommentsResponse",
4202: "EMsg_AMAddComment",
4203: "EMsg_AMAddCommentResponse",
4204: "EMsg_AMDeleteComment",
4205: "EMsg_AMDeleteCommentResponse",
4206: "EMsg_AMGetPurchaseStatus",
4209: "EMsg_AMSupportIsAccountEnabled",
4210: "EMsg_AMSupportIsAccountEnabledResponse",
4211: "EMsg_AMGetUserStats",
4212: "EMsg_AMSupportKickSession",
4213: "EMsg_AMGSSearch",
4216: "EMsg_MarketingMessageUpdate",
4219: "EMsg_AMRouteFriendMsg",
4220: "EMsg_AMTicketAuthRequestOrResponse",
4222: "EMsg_AMVerifyDepotManagementRights",
4223: "EMsg_AMVerifyDepotManagementRightsResponse",
4224: "EMsg_AMAddFreeLicense",
4225: "EMsg_AMGetUserFriendsMinutesPlayed",
4226: "EMsg_AMGetUserFriendsMinutesPlayedResponse",
4227: "EMsg_AMGetUserMinutesPlayed",
4228: "EMsg_AMGetUserMinutesPlayedResponse",
4231: "EMsg_AMValidateEmailLink",
4232: "EMsg_AMValidateEmailLinkResponse",
4234: "EMsg_AMAddUsersToMarketingTreatment",
4236: "EMsg_AMStoreUserStats",
4237: "EMsg_AMGetUserGameplayInfo",
4238: "EMsg_AMGetUserGameplayInfoResponse",
4239: "EMsg_AMGetCardList",
4240: "EMsg_AMGetCardListResponse",
4241: "EMsg_AMDeleteStoredCard",
4242: "EMsg_AMRevokeLegacyGameKeys",
4244: "EMsg_AMGetWalletDetails",
4245: "EMsg_AMGetWalletDetailsResponse",
4246: "EMsg_AMDeleteStoredPaymentInfo",
4247: "EMsg_AMGetStoredPaymentSummary",
4248: "EMsg_AMGetStoredPaymentSummaryResponse",
4249: "EMsg_AMGetWalletConversionRate",
4250: "EMsg_AMGetWalletConversionRateResponse",
4251: "EMsg_AMConvertWallet",
4252: "EMsg_AMConvertWalletResponse",
4253: "EMsg_AMRelayGetFriendsWhoPlayGame",
4254: "EMsg_AMRelayGetFriendsWhoPlayGameResponse",
4255: "EMsg_AMSetPreApproval",
4256: "EMsg_AMSetPreApprovalResponse",
4257: "EMsg_AMMarketingTreatmentUpdate",
4258: "EMsg_AMCreateRefund",
4259: "EMsg_AMCreateRefundResponse",
4260: "EMsg_AMCreateChargeback",
4261: "EMsg_AMCreateChargebackResponse",
4262: "EMsg_AMCreateDispute",
4263: "EMsg_AMCreateDisputeResponse",
4264: "EMsg_AMClearDispute",
4265: "EMsg_AMClearDisputeResponse",
4266: "EMsg_AMPlayerNicknameList",
4267: "EMsg_AMPlayerNicknameListResponse",
4268: "EMsg_AMSetDRMTestConfig",
4269: "EMsg_AMGetUserCurrentGameInfo",
4270: "EMsg_AMGetUserCurrentGameInfoResponse",
4271: "EMsg_AMGetGSPlayerList",
4272: "EMsg_AMGetGSPlayerListResponse",
4275: "EMsg_AMUpdatePersonaStateCache",
4276: "EMsg_AMGetGameMembers",
4277: "EMsg_AMGetGameMembersResponse",
4278: "EMsg_AMGetSteamIDForMicroTxn",
4279: "EMsg_AMGetSteamIDForMicroTxnResponse",
4280: "EMsg_AMAddPublisherUser",
4281: "EMsg_AMRemovePublisherUser",
4282: "EMsg_AMGetUserLicenseList",
4283: "EMsg_AMGetUserLicenseListResponse",
4284: "EMsg_AMReloadGameGroupPolicy",
4285: "EMsg_AMAddFreeLicenseResponse",
4286: "EMsg_AMVACStatusUpdate",
4287: "EMsg_AMGetAccountDetails",
4288: "EMsg_AMGetAccountDetailsResponse",
4289: "EMsg_AMGetPlayerLinkDetails",
4290: "EMsg_AMGetPlayerLinkDetailsResponse",
4291: "EMsg_AMSubscribeToPersonaFeed",
4292: "EMsg_AMGetUserVacBanList",
4293: "EMsg_AMGetUserVacBanListResponse",
4294: "EMsg_AMGetAccountFlagsForWGSpoofing",
4295: "EMsg_AMGetAccountFlagsForWGSpoofingResponse",
4296: "EMsg_AMGetFriendsWishlistInfo",
4297: "EMsg_AMGetFriendsWishlistInfoResponse",
4298: "EMsg_AMGetClanOfficers",
4299: "EMsg_AMGetClanOfficersResponse",
4300: "EMsg_AMNameChange",
4301: "EMsg_AMGetNameHistory",
4302: "EMsg_AMGetNameHistoryResponse",
4305: "EMsg_AMUpdateProviderStatus",
4306: "EMsg_AMClearPersonaMetadataBlob",
4307: "EMsg_AMSupportRemoveAccountSecurity",
4308: "EMsg_AMIsAccountInCaptchaGracePeriod",
4309: "EMsg_AMIsAccountInCaptchaGracePeriodResponse",
4310: "EMsg_AMAccountPS3Unlink",
4311: "EMsg_AMAccountPS3UnlinkResponse",
4312: "EMsg_AMStoreUserStatsResponse",
4313: "EMsg_AMGetAccountPSNInfo",
4314: "EMsg_AMGetAccountPSNInfoResponse",
4315: "EMsg_AMAuthenticatedPlayerList",
4316: "EMsg_AMGetUserGifts",
4317: "EMsg_AMGetUserGiftsResponse",
4320: "EMsg_AMTransferLockedGifts",
4321: "EMsg_AMTransferLockedGiftsResponse",
4322: "EMsg_AMPlayerHostedOnGameServer",
4323: "EMsg_AMGetAccountBanInfo",
4324: "EMsg_AMGetAccountBanInfoResponse",
4325: "EMsg_AMRecordBanEnforcement",
4326: "EMsg_AMRollbackGiftTransfer",
4327: "EMsg_AMRollbackGiftTransferResponse",
4328: "EMsg_AMHandlePendingTransaction",
4329: "EMsg_AMRequestClanDetails",
4330: "EMsg_AMDeleteStoredPaypalAgreement",
4331: "EMsg_AMGameServerUpdate",
4332: "EMsg_AMGameServerRemove",
4333: "EMsg_AMGetPaypalAgreements",
4334: "EMsg_AMGetPaypalAgreementsResponse",
4335: "EMsg_AMGameServerPlayerCompatibilityCheck",
4336: "EMsg_AMGameServerPlayerCompatibilityCheckResponse",
4337: "EMsg_AMRenewLicense",
4338: "EMsg_AMGetAccountCommunityBanInfo",
4339: "EMsg_AMGetAccountCommunityBanInfoResponse",
4340: "EMsg_AMGameServerAccountChangePassword",
4341: "EMsg_AMGameServerAccountDeleteAccount",
4342: "EMsg_AMRenewAgreement",
4343: "EMsg_AMSendEmail",
4344: "EMsg_AMXsollaPayment",
4345: "EMsg_AMXsollaPaymentResponse",
4346: "EMsg_AMAcctAllowedToPurchase",
4347: "EMsg_AMAcctAllowedToPurchaseResponse",
4348: "EMsg_AMSwapKioskDeposit",
4349: "EMsg_AMSwapKioskDepositResponse",
4350: "EMsg_AMSetUserGiftUnowned",
4351: "EMsg_AMSetUserGiftUnownedResponse",
4352: "EMsg_AMClaimUnownedUserGift",
4353: "EMsg_AMClaimUnownedUserGiftResponse",
4354: "EMsg_AMSetClanName",
4355: "EMsg_AMSetClanNameResponse",
4356: "EMsg_AMGrantCoupon",
4357: "EMsg_AMGrantCouponResponse",
4358: "EMsg_AMIsPackageRestrictedInUserCountry",
4359: "EMsg_AMIsPackageRestrictedInUserCountryResponse",
4360: "EMsg_AMHandlePendingTransactionResponse",
4361: "EMsg_AMGrantGuestPasses2",
4362: "EMsg_AMGrantGuestPasses2Response",
4363: "EMsg_AMSessionQuery",
4364: "EMsg_AMSessionQueryResponse",
4365: "EMsg_AMGetPlayerBanDetails",
4366: "EMsg_AMGetPlayerBanDetailsResponse",
4367: "EMsg_AMFinalizePurchase",
4368: "EMsg_AMFinalizePurchaseResponse",
4372: "EMsg_AMPersonaChangeResponse",
4373: "EMsg_AMGetClanDetailsForForumCreation",
4374: "EMsg_AMGetClanDetailsForForumCreationResponse",
4375: "EMsg_AMGetPendingNotificationCount",
4376: "EMsg_AMGetPendingNotificationCountResponse",
4377: "EMsg_AMPasswordHashUpgrade",
4378: "EMsg_AMMoPayPayment",
4379: "EMsg_AMMoPayPaymentResponse",
4380: "EMsg_AMBoaCompraPayment",
4381: "EMsg_AMBoaCompraPaymentResponse",
4382: "EMsg_AMExpireCaptchaByGID",
4383: "EMsg_AMCompleteExternalPurchase",
4384: "EMsg_AMCompleteExternalPurchaseResponse",
4385: "EMsg_AMResolveNegativeWalletCredits",
4386: "EMsg_AMResolveNegativeWalletCreditsResponse",
4387: "EMsg_AMPayelpPayment",
4388: "EMsg_AMPayelpPaymentResponse",
4389: "EMsg_AMPlayerGetClanBasicDetails",
4390: "EMsg_AMPlayerGetClanBasicDetailsResponse",
4402: "EMsg_AMTwoFactorRecoverAuthenticatorRequest",
4403: "EMsg_AMTwoFactorRecoverAuthenticatorResponse",
4406: "EMsg_AMValidatePasswordResetCodeAndSendSmsRequest",
4407: "EMsg_AMValidatePasswordResetCodeAndSendSmsResponse",
4408: "EMsg_AMGetAccountResetDetailsRequest",
4409: "EMsg_AMGetAccountResetDetailsResponse",
5000: "EMsg_BasePSRange",
5001: "EMsg_PSCreateShoppingCart",
5002: "EMsg_PSCreateShoppingCartResponse",
5003: "EMsg_PSIsValidShoppingCart",
5004: "EMsg_PSIsValidShoppingCartResponse",
5005: "EMsg_PSAddPackageToShoppingCart",
5006: "EMsg_PSAddPackageToShoppingCartResponse",
5007: "EMsg_PSRemoveLineItemFromShoppingCart",
5008: "EMsg_PSRemoveLineItemFromShoppingCartResponse",
5009: "EMsg_PSGetShoppingCartContents",
5010: "EMsg_PSGetShoppingCartContentsResponse",
5011: "EMsg_PSAddWalletCreditToShoppingCart",
5012: "EMsg_PSAddWalletCreditToShoppingCartResponse",
5200: "EMsg_BaseUFSRange",
5202: "EMsg_ClientUFSUploadFileRequest",
5203: "EMsg_ClientUFSUploadFileResponse",
5204: "EMsg_ClientUFSUploadFileChunk",
5205: "EMsg_ClientUFSUploadFileFinished",
5206: "EMsg_ClientUFSGetFileListForApp",
5207: "EMsg_ClientUFSGetFileListForAppResponse",
5210: "EMsg_ClientUFSDownloadRequest",
5211: "EMsg_ClientUFSDownloadResponse",
5212: "EMsg_ClientUFSDownloadChunk",
5213: "EMsg_ClientUFSLoginRequest",
5214: "EMsg_ClientUFSLoginResponse",
5215: "EMsg_UFSReloadPartitionInfo",
5216: "EMsg_ClientUFSTransferHeartbeat",
5217: "EMsg_UFSSynchronizeFile",
5218: "EMsg_UFSSynchronizeFileResponse",
5219: "EMsg_ClientUFSDeleteFileRequest",
5220: "EMsg_ClientUFSDeleteFileResponse",
5221: "EMsg_UFSDownloadRequest",
5222: "EMsg_UFSDownloadResponse",
5223: "EMsg_UFSDownloadChunk",
5226: "EMsg_ClientUFSGetUGCDetails",
5227: "EMsg_ClientUFSGetUGCDetailsResponse",
5228: "EMsg_UFSUpdateFileFlags",
5229: "EMsg_UFSUpdateFileFlagsResponse",
5230: "EMsg_ClientUFSGetSingleFileInfo",
5231: "EMsg_ClientUFSGetSingleFileInfoResponse",
5232: "EMsg_ClientUFSShareFile",
5233: "EMsg_ClientUFSShareFileResponse",
5234: "EMsg_UFSReloadAccount",
5235: "EMsg_UFSReloadAccountResponse",
5236: "EMsg_UFSUpdateRecordBatched",
5237: "EMsg_UFSUpdateRecordBatchedResponse",
5238: "EMsg_UFSMigrateFile",
5239: "EMsg_UFSMigrateFileResponse",
5240: "EMsg_UFSGetUGCURLs",
5241: "EMsg_UFSGetUGCURLsResponse",
5242: "EMsg_UFSHttpUploadFileFinishRequest",
5243: "EMsg_UFSHttpUploadFileFinishResponse",
5244: "EMsg_UFSDownloadStartRequest",
5245: "EMsg_UFSDownloadStartResponse",
5246: "EMsg_UFSDownloadChunkRequest",
5247: "EMsg_UFSDownloadChunkResponse",
5248: "EMsg_UFSDownloadFinishRequest",
5249: "EMsg_UFSDownloadFinishResponse",
5250: "EMsg_UFSFlushURLCache",
5251: "EMsg_UFSUploadCommit",
5252: "EMsg_UFSUploadCommitResponse",
5400: "EMsg_BaseClient2",
5401: "EMsg_ClientRequestForgottenPasswordEmail",
5402: "EMsg_ClientRequestForgottenPasswordEmailResponse",
5403: "EMsg_ClientCreateAccountResponse",
5404: "EMsg_ClientResetForgottenPassword",
5405: "EMsg_ClientResetForgottenPasswordResponse",
5406: "EMsg_ClientCreateAccount2",
5407: "EMsg_ClientInformOfResetForgottenPassword",
5408: "EMsg_ClientInformOfResetForgottenPasswordResponse",
5409: "EMsg_ClientAnonUserLogOn_Deprecated",
5410: "EMsg_ClientGamesPlayedWithDataBlob",
5411: "EMsg_ClientUpdateUserGameInfo",
5412: "EMsg_ClientFileToDownload",
5413: "EMsg_ClientFileToDownloadResponse",
5414: "EMsg_ClientLBSSetScore",
5415: "EMsg_ClientLBSSetScoreResponse",
5416: "EMsg_ClientLBSFindOrCreateLB",
5417: "EMsg_ClientLBSFindOrCreateLBResponse",
5418: "EMsg_ClientLBSGetLBEntries",
5419: "EMsg_ClientLBSGetLBEntriesResponse",
5420: "EMsg_ClientMarketingMessageUpdate",
5426: "EMsg_ClientChatDeclined",
5427: "EMsg_ClientFriendMsgIncoming",
5428: "EMsg_ClientAuthList_Deprecated",
5429: "EMsg_ClientTicketAuthComplete",
5430: "EMsg_ClientIsLimitedAccount",
5431: "EMsg_ClientRequestAuthList",
5432: "EMsg_ClientAuthList",
5433: "EMsg_ClientStat",
5434: "EMsg_ClientP2PConnectionInfo",
5435: "EMsg_ClientP2PConnectionFailInfo",
5436: "EMsg_ClientGetNumberOfCurrentPlayers",
5437: "EMsg_ClientGetNumberOfCurrentPlayersResponse",
5438: "EMsg_ClientGetDepotDecryptionKey",
5439: "EMsg_ClientGetDepotDecryptionKeyResponse",
5440: "EMsg_GSPerformHardwareSurvey",
5441: "EMsg_ClientGetAppBetaPasswords",
5442: "EMsg_ClientGetAppBetaPasswordsResponse",
5443: "EMsg_ClientEnableTestLicense",
5444: "EMsg_ClientEnableTestLicenseResponse",
5445: "EMsg_ClientDisableTestLicense",
5446: "EMsg_ClientDisableTestLicenseResponse",
5448: "EMsg_ClientRequestValidationMail",
5449: "EMsg_ClientRequestValidationMailResponse",
5450: "EMsg_ClientCheckAppBetaPassword",
5451: "EMsg_ClientCheckAppBetaPasswordResponse",
5452: "EMsg_ClientToGC",
5453: "EMsg_ClientFromGC",
5454: "EMsg_ClientRequestChangeMail",
5455: "EMsg_ClientRequestChangeMailResponse",
5456: "EMsg_ClientEmailAddrInfo",
5457: "EMsg_ClientPasswordChange3",
5458: "EMsg_ClientEmailChange3",
5459: "EMsg_ClientPersonalQAChange3",
5460: "EMsg_ClientResetForgottenPassword3",
5461: "EMsg_ClientRequestForgottenPasswordEmail3",
5462: "EMsg_ClientCreateAccount3",
5463: "EMsg_ClientNewLoginKey",
5464: "EMsg_ClientNewLoginKeyAccepted",
5465: "EMsg_ClientLogOnWithHash_Deprecated",
5466: "EMsg_ClientStoreUserStats2",
5467: "EMsg_ClientStatsUpdated",
5468: "EMsg_ClientActivateOEMLicense",
5469: "EMsg_ClientRegisterOEMMachine",
5470: "EMsg_ClientRegisterOEMMachineResponse",
5480: "EMsg_ClientRequestedClientStats",
5481: "EMsg_ClientStat2Int32",
5482: "EMsg_ClientStat2",
5483: "EMsg_ClientVerifyPassword",
5484: "EMsg_ClientVerifyPasswordResponse",
5485: "EMsg_ClientDRMDownloadRequest",
5486: "EMsg_ClientDRMDownloadResponse",
5487: "EMsg_ClientDRMFinalResult",
5488: "EMsg_ClientGetFriendsWhoPlayGame",
5489: "EMsg_ClientGetFriendsWhoPlayGameResponse",
5490: "EMsg_ClientOGSBeginSession",
5491: "EMsg_ClientOGSBeginSessionResponse",
5492: "EMsg_ClientOGSEndSession",
5493: "EMsg_ClientOGSEndSessionResponse",
5494: "EMsg_ClientOGSWriteRow",
5495: "EMsg_ClientDRMTest",
5496: "EMsg_ClientDRMTestResult",
5500: "EMsg_ClientServerUnavailable",
5501: "EMsg_ClientServersAvailable",
5502: "EMsg_ClientRegisterAuthTicketWithCM",
5503: "EMsg_ClientGCMsgFailed",
5504: "EMsg_ClientMicroTxnAuthRequest",
5505: "EMsg_ClientMicroTxnAuthorize",
5506: "EMsg_ClientMicroTxnAuthorizeResponse",
5507: "EMsg_ClientAppMinutesPlayedData",
5508: "EMsg_ClientGetMicroTxnInfo",
5509: "EMsg_ClientGetMicroTxnInfoResponse",
5510: "EMsg_ClientMarketingMessageUpdate2",
5511: "EMsg_ClientDeregisterWithServer",
5512: "EMsg_ClientSubscribeToPersonaFeed",
5514: "EMsg_ClientLogon",
5515: "EMsg_ClientGetClientDetails",
5516: "EMsg_ClientGetClientDetailsResponse",
5517: "EMsg_ClientReportOverlayDetourFailure",
5518: "EMsg_ClientGetClientAppList",
5519: "EMsg_ClientGetClientAppListResponse",
5520: "EMsg_ClientInstallClientApp",
5521: "EMsg_ClientInstallClientAppResponse",
5522: "EMsg_ClientUninstallClientApp",
5523: "EMsg_ClientUninstallClientAppResponse",
5524: "EMsg_ClientSetClientAppUpdateState",
5525: "EMsg_ClientSetClientAppUpdateStateResponse",
5526: "EMsg_ClientRequestEncryptedAppTicket",
5527: "EMsg_ClientRequestEncryptedAppTicketResponse",
5528: "EMsg_ClientWalletInfoUpdate",
5529: "EMsg_ClientLBSSetUGC",
5530: "EMsg_ClientLBSSetUGCResponse",
5531: "EMsg_ClientAMGetClanOfficers",
5532: "EMsg_ClientAMGetClanOfficersResponse",
5533: "EMsg_ClientCheckFileSignature",
5534: "EMsg_ClientCheckFileSignatureResponse",
5535: "EMsg_ClientFriendProfileInfo",
5536: "EMsg_ClientFriendProfileInfoResponse",
5537: "EMsg_ClientUpdateMachineAuth",
5538: "EMsg_ClientUpdateMachineAuthResponse",
5539: "EMsg_ClientReadMachineAuth",
5540: "EMsg_ClientReadMachineAuthResponse",
5541: "EMsg_ClientRequestMachineAuth",
5542: "EMsg_ClientRequestMachineAuthResponse",
5543: "EMsg_ClientScreenshotsChanged",
5544: "EMsg_ClientEmailChange4",
5545: "EMsg_ClientEmailChangeResponse4",
5546: "EMsg_ClientGetCDNAuthToken",
5547: "EMsg_ClientGetCDNAuthTokenResponse",
5548: "EMsg_ClientDownloadRateStatistics",
5549: "EMsg_ClientRequestAccountData",
5550: "EMsg_ClientRequestAccountDataResponse",
5551: "EMsg_ClientResetForgottenPassword4",
5552: "EMsg_ClientHideFriend",
5553: "EMsg_ClientFriendsGroupsList",
5554: "EMsg_ClientGetClanActivityCounts",
5555: "EMsg_ClientGetClanActivityCountsResponse",
5556: "EMsg_ClientOGSReportString",
5557: "EMsg_ClientOGSReportBug",
5558: "EMsg_ClientSentLogs",
5559: "EMsg_ClientLogonGameServer",
5560: "EMsg_AMClientCreateFriendsGroup",
5561: "EMsg_AMClientCreateFriendsGroupResponse",
5562: "EMsg_AMClientDeleteFriendsGroup",
5563: "EMsg_AMClientDeleteFriendsGroupResponse",
5564: "EMsg_AMClientRenameFriendsGroup",
5565: "EMsg_AMClientRenameFriendsGroupResponse",
5566: "EMsg_AMClientAddFriendToGroup",
5567: "EMsg_AMClientAddFriendToGroupResponse",
5568: "EMsg_AMClientRemoveFriendFromGroup",
5569: "EMsg_AMClientRemoveFriendFromGroupResponse",
5570: "EMsg_ClientAMGetPersonaNameHistory",
5571: "EMsg_ClientAMGetPersonaNameHistoryResponse",
5572: "EMsg_ClientRequestFreeLicense",
5573: "EMsg_ClientRequestFreeLicenseResponse",
5574: "EMsg_ClientDRMDownloadRequestWithCrashData",
5575: "EMsg_ClientAuthListAck",
5576: "EMsg_ClientItemAnnouncements",
5577: "EMsg_ClientRequestItemAnnouncements",
5578: "EMsg_ClientFriendMsgEchoToSender",
5579: "EMsg_ClientChangeSteamGuardOptions",
5580: "EMsg_ClientChangeSteamGuardOptionsResponse",
5581: "EMsg_ClientOGSGameServerPingSample",
5582: "EMsg_ClientCommentNotifications",
5583: "EMsg_ClientRequestCommentNotifications",
5584: "EMsg_ClientPersonaChangeResponse",
5585: "EMsg_ClientRequestWebAPIAuthenticateUserNonce",
5586: "EMsg_ClientRequestWebAPIAuthenticateUserNonceResponse",
5587: "EMsg_ClientPlayerNicknameList",
5588: "EMsg_AMClientSetPlayerNickname",
5589: "EMsg_AMClientSetPlayerNicknameResponse",
5590: "EMsg_ClientRequestOAuthTokenForApp",
5591: "EMsg_ClientRequestOAuthTokenForAppResponse",
5592: "EMsg_ClientGetNumberOfCurrentPlayersDP",
5593: "EMsg_ClientGetNumberOfCurrentPlayersDPResponse",
5594: "EMsg_ClientServiceMethod",
5595: "EMsg_ClientServiceMethodResponse",
5596: "EMsg_ClientFriendUserStatusPublished",
5597: "EMsg_ClientCurrentUIMode",
5598: "EMsg_ClientVanityURLChangedNotification",
5599: "EMsg_ClientUserNotifications",
5600: "EMsg_BaseDFS",
5601: "EMsg_DFSGetFile",
5602: "EMsg_DFSInstallLocalFile",
5603: "EMsg_DFSConnection",
5604: "EMsg_DFSConnectionReply",
5605: "EMsg_ClientDFSAuthenticateRequest",
5606: "EMsg_ClientDFSAuthenticateResponse",
5607: "EMsg_ClientDFSEndSession",
5608: "EMsg_DFSPurgeFile",
5609: "EMsg_DFSRouteFile",
5610: "EMsg_DFSGetFileFromServer",
5611: "EMsg_DFSAcceptedResponse",
5612: "EMsg_DFSRequestPingback",
5613: "EMsg_DFSRecvTransmitFile",
5614: "EMsg_DFSSendTransmitFile",
5615: "EMsg_DFSRequestPingback2",
5616: "EMsg_DFSResponsePingback2",
5617: "EMsg_ClientDFSDownloadStatus",
5618: "EMsg_DFSStartTransfer",
5619: "EMsg_DFSTransferComplete",
5800: "EMsg_BaseMDS",
5801: "EMsg_ClientMDSLoginRequest",
5802: "EMsg_ClientMDSLoginResponse",
5803: "EMsg_ClientMDSUploadManifestRequest",
5804: "EMsg_ClientMDSUploadManifestResponse",
5805: "EMsg_ClientMDSTransmitManifestDataChunk",
5806: "EMsg_ClientMDSHeartbeat",
5807: "EMsg_ClientMDSUploadDepotChunks",
5808: "EMsg_ClientMDSUploadDepotChunksResponse",
5809: "EMsg_ClientMDSInitDepotBuildRequest",
5810: "EMsg_ClientMDSInitDepotBuildResponse",
5812: "EMsg_AMToMDSGetDepotDecryptionKey",
5813: "EMsg_MDSToAMGetDepotDecryptionKeyResponse",
5814: "EMsg_MDSGetVersionsForDepot",
5815: "EMsg_MDSGetVersionsForDepotResponse",
5816: "EMsg_MDSSetPublicVersionForDepot",
5817: "EMsg_MDSSetPublicVersionForDepotResponse",
5818: "EMsg_ClientMDSGetDepotManifest",
5819: "EMsg_ClientMDSGetDepotManifestResponse",
5820: "EMsg_ClientMDSGetDepotManifestChunk",
5823: "EMsg_ClientMDSUploadRateTest",
5824: "EMsg_ClientMDSUploadRateTestResponse",
5825: "EMsg_MDSDownloadDepotChunksAck",
5826: "EMsg_MDSContentServerStatsBroadcast",
5827: "EMsg_MDSContentServerConfigRequest",
5828: "EMsg_MDSContentServerConfig",
5829: "EMsg_MDSGetDepotManifest",
5830: "EMsg_MDSGetDepotManifestResponse",
5831: "EMsg_MDSGetDepotManifestChunk",
5832: "EMsg_MDSGetDepotChunk",
5833: "EMsg_MDSGetDepotChunkResponse",
5834: "EMsg_MDSGetDepotChunkChunk",
5835: "EMsg_MDSUpdateContentServerConfig",
5836: "EMsg_MDSGetServerListForUser",
5837: "EMsg_MDSGetServerListForUserResponse",
5838: "EMsg_ClientMDSRegisterAppBuild",
5839: "EMsg_ClientMDSRegisterAppBuildResponse",
5840: "EMsg_ClientMDSSetAppBuildLive",
5841: "EMsg_ClientMDSSetAppBuildLiveResponse",
5842: "EMsg_ClientMDSGetPrevDepotBuild",
5843: "EMsg_ClientMDSGetPrevDepotBuildResponse",
5844: "EMsg_MDSToCSFlushChunk",
5845: "EMsg_ClientMDSSignInstallScript",
5846: "EMsg_ClientMDSSignInstallScriptResponse",
6200: "EMsg_CSBase",
6201: "EMsg_CSPing",
6202: "EMsg_CSPingResponse",
6400: "EMsg_GMSBase",
6401: "EMsg_GMSGameServerReplicate",
6403: "EMsg_ClientGMSServerQuery",
6404: "EMsg_GMSClientServerQueryResponse",
6405: "EMsg_AMGMSGameServerUpdate",
6406: "EMsg_AMGMSGameServerRemove",
6407: "EMsg_GameServerOutOfDate",
6501: "EMsg_ClientAuthorizeLocalDeviceRequest",
6502: "EMsg_ClientAuthorizeLocalDevice",
6503: "EMsg_ClientDeauthorizeDeviceRequest",
6504: "EMsg_ClientDeauthorizeDevice",
6505: "EMsg_ClientUseLocalDeviceAuthorizations",
6506: "EMsg_ClientGetAuthorizedDevices",
6507: "EMsg_ClientGetAuthorizedDevicesResponse",
6600: "EMsg_MMSBase",
6601: "EMsg_ClientMMSCreateLobby",
6602: "EMsg_ClientMMSCreateLobbyResponse",
6603: "EMsg_ClientMMSJoinLobby",
6604: "EMsg_ClientMMSJoinLobbyResponse",
6605: "EMsg_ClientMMSLeaveLobby",
6606: "EMsg_ClientMMSLeaveLobbyResponse",
6607: "EMsg_ClientMMSGetLobbyList",
6608: "EMsg_ClientMMSGetLobbyListResponse",
6609: "EMsg_ClientMMSSetLobbyData",
6610: "EMsg_ClientMMSSetLobbyDataResponse",
6611: "EMsg_ClientMMSGetLobbyData",
6612: "EMsg_ClientMMSLobbyData",
6613: "EMsg_ClientMMSSendLobbyChatMsg",
6614: "EMsg_ClientMMSLobbyChatMsg",
6615: "EMsg_ClientMMSSetLobbyOwner",
6616: "EMsg_ClientMMSSetLobbyOwnerResponse",
6617: "EMsg_ClientMMSSetLobbyGameServer",
6618: "EMsg_ClientMMSLobbyGameServerSet",
6619: "EMsg_ClientMMSUserJoinedLobby",
6620: "EMsg_ClientMMSUserLeftLobby",
6621: "EMsg_ClientMMSInviteToLobby",
6622: "EMsg_ClientMMSFlushFrenemyListCache",
6623: "EMsg_ClientMMSFlushFrenemyListCacheResponse",
6624: "EMsg_ClientMMSSetLobbyLinked",
6800: "EMsg_NonStdMsgBase",
6801: "EMsg_NonStdMsgMemcached",
6802: "EMsg_NonStdMsgHTTPServer",
6803: "EMsg_NonStdMsgHTTPClient",
6804: "EMsg_NonStdMsgWGResponse",
6805: "EMsg_NonStdMsgPHPSimulator",
6806: "EMsg_NonStdMsgChase",
6807: "EMsg_NonStdMsgDFSTransfer",
6808: "EMsg_NonStdMsgTests",
6809: "EMsg_NonStdMsgUMQpipeAAPL",
6810: "EMsg_NonStdMsgSyslog",
6811: "EMsg_NonStdMsgLogsink",
7000: "EMsg_UDSBase",
7001: "EMsg_ClientUDSP2PSessionStarted",
7002: "EMsg_ClientUDSP2PSessionEnded",
7003: "EMsg_UDSRenderUserAuth",
7004: "EMsg_UDSRenderUserAuthResponse",
7005: "EMsg_ClientUDSInviteToGame",
7006: "EMsg_UDSFindSession",
7007: "EMsg_UDSFindSessionResponse",
7100: "EMsg_MPASBase",
7101: "EMsg_MPASVacBanReset",
7200: "EMsg_KGSBase",
7201: "EMsg_KGSAllocateKeyRange",
7202: "EMsg_KGSAllocateKeyRangeResponse",
7203: "EMsg_KGSGenerateKeys",
7204: "EMsg_KGSGenerateKeysResponse",
7205: "EMsg_KGSRemapKeys",
7206: "EMsg_KGSRemapKeysResponse",
7207: "EMsg_KGSGenerateGameStopWCKeys",
7208: "EMsg_KGSGenerateGameStopWCKeysResponse",
7300: "EMsg_UCMBase",
7301: "EMsg_ClientUCMAddScreenshot",
7302: "EMsg_ClientUCMAddScreenshotResponse",
7303: "EMsg_UCMValidateObjectExists",
7304: "EMsg_UCMValidateObjectExistsResponse",
7307: "EMsg_UCMResetCommunityContent",
7308: "EMsg_UCMResetCommunityContentResponse",
7309: "EMsg_ClientUCMDeleteScreenshot",
7310: "EMsg_ClientUCMDeleteScreenshotResponse",
7311: "EMsg_ClientUCMPublishFile",
7312: "EMsg_ClientUCMPublishFileResponse",
7313: "EMsg_ClientUCMGetPublishedFileDetails",
7314: "EMsg_ClientUCMGetPublishedFileDetailsResponse",
7315: "EMsg_ClientUCMDeletePublishedFile",
7316: "EMsg_ClientUCMDeletePublishedFileResponse",
7317: "EMsg_ClientUCMEnumerateUserPublishedFiles",
7318: "EMsg_ClientUCMEnumerateUserPublishedFilesResponse",
7319: "EMsg_ClientUCMSubscribePublishedFile",
7320: "EMsg_ClientUCMSubscribePublishedFileResponse",
7321: "EMsg_ClientUCMEnumerateUserSubscribedFiles",
7322: "EMsg_ClientUCMEnumerateUserSubscribedFilesResponse",
7323: "EMsg_ClientUCMUnsubscribePublishedFile",
7324: "EMsg_ClientUCMUnsubscribePublishedFileResponse",
7325: "EMsg_ClientUCMUpdatePublishedFile",
7326: "EMsg_ClientUCMUpdatePublishedFileResponse",
7327: "EMsg_UCMUpdatePublishedFile",
7328: "EMsg_UCMUpdatePublishedFileResponse",
7329: "EMsg_UCMDeletePublishedFile",
7330: "EMsg_UCMDeletePublishedFileResponse",
7331: "EMsg_UCMUpdatePublishedFileStat",
7332: "EMsg_UCMUpdatePublishedFileBan",
7333: "EMsg_UCMUpdatePublishedFileBanResponse",
7334: "EMsg_UCMUpdateTaggedScreenshot",
7335: "EMsg_UCMAddTaggedScreenshot",
7336: "EMsg_UCMRemoveTaggedScreenshot",
7337: "EMsg_UCMReloadPublishedFile",
7338: "EMsg_UCMReloadUserFileListCaches",
7339: "EMsg_UCMPublishedFileReported",
7340: "EMsg_UCMUpdatePublishedFileIncompatibleStatus",
7341: "EMsg_UCMPublishedFilePreviewAdd",
7342: "EMsg_UCMPublishedFilePreviewAddResponse",
7343: "EMsg_UCMPublishedFilePreviewRemove",
7344: "EMsg_UCMPublishedFilePreviewRemoveResponse",
7345: "EMsg_UCMPublishedFilePreviewChangeSortOrder",
7346: "EMsg_UCMPublishedFilePreviewChangeSortOrderResponse",
7347: "EMsg_ClientUCMPublishedFileSubscribed",
7348: "EMsg_ClientUCMPublishedFileUnsubscribed",
7349: "EMsg_UCMPublishedFileSubscribed",
7350: "EMsg_UCMPublishedFileUnsubscribed",
7351: "EMsg_UCMPublishFile",
7352: "EMsg_UCMPublishFileResponse",
7353: "EMsg_UCMPublishedFileChildAdd",
7354: "EMsg_UCMPublishedFileChildAddResponse",
7355: "EMsg_UCMPublishedFileChildRemove",
7356: "EMsg_UCMPublishedFileChildRemoveResponse",
7357: "EMsg_UCMPublishedFileChildChangeSortOrder",
7358: "EMsg_UCMPublishedFileChildChangeSortOrderResponse",
7359: "EMsg_UCMPublishedFileParentChanged",
7360: "EMsg_ClientUCMGetPublishedFilesForUser",
7361: "EMsg_ClientUCMGetPublishedFilesForUserResponse",
7362: "EMsg_UCMGetPublishedFilesForUser",
7363: "EMsg_UCMGetPublishedFilesForUserResponse",
7364: "EMsg_ClientUCMSetUserPublishedFileAction",
7365: "EMsg_ClientUCMSetUserPublishedFileActionResponse",
7366: "EMsg_ClientUCMEnumeratePublishedFilesByUserAction",
7367: "EMsg_ClientUCMEnumeratePublishedFilesByUserActionResponse",
7368: "EMsg_ClientUCMPublishedFileDeleted",
7369: "EMsg_UCMGetUserSubscribedFiles",
7370: "EMsg_UCMGetUserSubscribedFilesResponse",
7371: "EMsg_UCMFixStatsPublishedFile",
7372: "EMsg_UCMDeleteOldScreenshot",
7373: "EMsg_UCMDeleteOldScreenshotResponse",
7374: "EMsg_UCMDeleteOldVideo",
7375: "EMsg_UCMDeleteOldVideoResponse",
7376: "EMsg_UCMUpdateOldScreenshotPrivacy",
7377: "EMsg_UCMUpdateOldScreenshotPrivacyResponse",
7378: "EMsg_ClientUCMEnumerateUserSubscribedFilesWithUpdates",
7379: "EMsg_ClientUCMEnumerateUserSubscribedFilesWithUpdatesResponse",
7380: "EMsg_UCMPublishedFileContentUpdated",
7381: "EMsg_UCMPublishedFileUpdated",
7382: "EMsg_ClientWorkshopItemChangesRequest",
7383: "EMsg_ClientWorkshopItemChangesResponse",
7384: "EMsg_ClientWorkshopItemInfoRequest",
7385: "EMsg_ClientWorkshopItemInfoResponse",
7500: "EMsg_FSBase",
7501: "EMsg_ClientRichPresenceUpload",
7502: "EMsg_ClientRichPresenceRequest",
7503: "EMsg_ClientRichPresenceInfo",
7504: "EMsg_FSRichPresenceRequest",
7505: "EMsg_FSRichPresenceResponse",
7506: "EMsg_FSComputeFrenematrix",
7507: "EMsg_FSComputeFrenematrixResponse",
7508: "EMsg_FSPlayStatusNotification",
7509: "EMsg_FSPublishPersonaStatus",
7510: "EMsg_FSAddOrRemoveFollower",
7511: "EMsg_FSAddOrRemoveFollowerResponse",
7512: "EMsg_FSUpdateFollowingList",
7513: "EMsg_FSCommentNotification",
7514: "EMsg_FSCommentNotificationViewed",
7515: "EMsg_ClientFSGetFollowerCount",
7516: "EMsg_ClientFSGetFollowerCountResponse",
7517: "EMsg_ClientFSGetIsFollowing",
7518: "EMsg_ClientFSGetIsFollowingResponse",
7519: "EMsg_ClientFSEnumerateFollowingList",
7520: "EMsg_ClientFSEnumerateFollowingListResponse",
7521: "EMsg_FSGetPendingNotificationCount",
7522: "EMsg_FSGetPendingNotificationCountResponse",
7523: "EMsg_ClientFSOfflineMessageNotification",
7524: "EMsg_ClientFSRequestOfflineMessageCount",
7525: "EMsg_ClientFSGetFriendMessageHistory",
7526: "EMsg_ClientFSGetFriendMessageHistoryResponse",
7527: "EMsg_ClientFSGetFriendMessageHistoryForOfflineMessages",
7528: "EMsg_ClientFSGetFriendsSteamLevels",
7529: "EMsg_ClientFSGetFriendsSteamLevelsResponse",
7600: "EMsg_DRMRange2",
7601: "EMsg_CEGVersionSetEnableDisableResponse",
7602: "EMsg_CEGPropStatusDRMSRequest",
7603: "EMsg_CEGPropStatusDRMSResponse",
7604: "EMsg_CEGWhackFailureReportRequest",
7605: "EMsg_CEGWhackFailureReportResponse",
7606: "EMsg_DRMSFetchVersionSet",
7607: "EMsg_DRMSFetchVersionSetResponse",
7700: "EMsg_EconBase",
7701: "EMsg_EconTrading_InitiateTradeRequest",
7702: "EMsg_EconTrading_InitiateTradeProposed",
7703: "EMsg_EconTrading_InitiateTradeResponse",
7704: "EMsg_EconTrading_InitiateTradeResult",
7705: "EMsg_EconTrading_StartSession",
7706: "EMsg_EconTrading_CancelTradeRequest",
7707: "EMsg_EconFlushInventoryCache",
7708: "EMsg_EconFlushInventoryCacheResponse",
7711: "EMsg_EconCDKeyProcessTransaction",
7712: "EMsg_EconCDKeyProcessTransactionResponse",
7713: "EMsg_EconGetErrorLogs",
7714: "EMsg_EconGetErrorLogsResponse",
7800: "EMsg_RMRange",
7801: "EMsg_RMTestVerisignOTPResponse",
7803: "EMsg_RMDeleteMemcachedKeys",
7804: "EMsg_RMRemoteInvoke",
7805: "EMsg_BadLoginIPList",
7900: "EMsg_UGSBase",
7901: "EMsg_ClientUGSGetGlobalStats",
7902: "EMsg_ClientUGSGetGlobalStatsResponse",
8000: "EMsg_StoreBase",
8100: "EMsg_UMQBase",
8101: "EMsg_UMQLogonResponse",
8102: "EMsg_UMQLogoffRequest",
8103: "EMsg_UMQLogoffResponse",
8104: "EMsg_UMQSendChatMessage",
8105: "EMsg_UMQIncomingChatMessage",
8106: "EMsg_UMQPoll",
8107: "EMsg_UMQPollResults",
8108: "EMsg_UMQ2AM_ClientMsgBatch",
8109: "EMsg_UMQEnqueueMobileSalePromotions",
8110: "EMsg_UMQEnqueueMobileAnnouncements",
8200: "EMsg_WorkshopBase",
8201: "EMsg_WorkshopAcceptTOSResponse",
8300: "EMsg_WebAPIBase",
8301: "EMsg_WebAPIValidateOAuth2TokenResponse",
8302: "EMsg_WebAPIInvalidateTokensForAccount",
8303: "EMsg_WebAPIRegisterGCInterfaces",
8304: "EMsg_WebAPIInvalidateOAuthClientCache",
8305: "EMsg_WebAPIInvalidateOAuthTokenCache",
8400: "EMsg_BackpackBase",
8401: "EMsg_BackpackAddToCurrency",
8402: "EMsg_BackpackAddToCurrencyResponse",
8500: "EMsg_CREBase",
8501: "EMsg_CRERankByTrend",
8502: "EMsg_CRERankByTrendResponse",
8503: "EMsg_CREItemVoteSummary",
8504: "EMsg_CREItemVoteSummaryResponse",
8505: "EMsg_CRERankByVote",
8506: "EMsg_CRERankByVoteResponse",
8507: "EMsg_CREUpdateUserPublishedItemVote",
8508: "EMsg_CREUpdateUserPublishedItemVoteResponse",
8509: "EMsg_CREGetUserPublishedItemVoteDetails",
8510: "EMsg_CREGetUserPublishedItemVoteDetailsResponse",
8511: "EMsg_CREEnumeratePublishedFiles",
8512: "EMsg_CREEnumeratePublishedFilesResponse",
8513: "EMsg_CREPublishedFileVoteAdded",
8600: "EMsg_SecretsBase",
8601: "EMsg_SecretsCredentialPairResponse",
8602: "EMsg_SecretsRequestServerIdentity",
8603: "EMsg_SecretsServerIdentityResponse",
8604: "EMsg_SecretsUpdateServerIdentities",
8700: "EMsg_BoxMonitorBase",
8701: "EMsg_BoxMonitorReportResponse",
8800: "EMsg_LogsinkBase",
8900: "EMsg_PICSBase",
8901: "EMsg_ClientPICSChangesSinceRequest",
8902: "EMsg_ClientPICSChangesSinceResponse",
8903: "EMsg_ClientPICSProductInfoRequest",
8904: "EMsg_ClientPICSProductInfoResponse",
8905: "EMsg_ClientPICSAccessTokenRequest",
8906: "EMsg_ClientPICSAccessTokenResponse",
9000: "EMsg_WorkerProcess",
9001: "EMsg_WorkerProcessPingResponse",
9002: "EMsg_WorkerProcessShutdown",
9100: "EMsg_DRMWorkerProcess",
9101: "EMsg_DRMWorkerProcessDRMAndSignResponse",
9102: "EMsg_DRMWorkerProcessSteamworksInfoRequest",
9103: "EMsg_DRMWorkerProcessSteamworksInfoResponse",
9104: "EMsg_DRMWorkerProcessInstallDRMDLLRequest",
9105: "EMsg_DRMWorkerProcessInstallDRMDLLResponse",
9106: "EMsg_DRMWorkerProcessSecretIdStringRequest",
9107: "EMsg_DRMWorkerProcessSecretIdStringResponse",
9108: "EMsg_DRMWorkerProcessGetDRMGuidsFromFileRequest",
9109: "EMsg_DRMWorkerProcessGetDRMGuidsFromFileResponse",
9110: "EMsg_DRMWorkerProcessInstallProcessedFilesRequest",
9111: "EMsg_DRMWorkerProcessInstallProcessedFilesResponse",
9112: "EMsg_DRMWorkerProcessExamineBlobRequest",
9113: "EMsg_DRMWorkerProcessExamineBlobResponse",
9114: "EMsg_DRMWorkerProcessDescribeSecretRequest",
9115: "EMsg_DRMWorkerProcessDescribeSecretResponse",
9116: "EMsg_DRMWorkerProcessBackfillOriginalRequest",
9117: "EMsg_DRMWorkerProcessBackfillOriginalResponse",
9118: "EMsg_DRMWorkerProcessValidateDRMDLLRequest",
9119: "EMsg_DRMWorkerProcessValidateDRMDLLResponse",
9120: "EMsg_DRMWorkerProcessValidateFileRequest",
9121: "EMsg_DRMWorkerProcessValidateFileResponse",
9122: "EMsg_DRMWorkerProcessSplitAndInstallRequest",
9123: "EMsg_DRMWorkerProcessSplitAndInstallResponse",
9124: "EMsg_DRMWorkerProcessGetBlobRequest",
9125: "EMsg_DRMWorkerProcessGetBlobResponse",
9126: "EMsg_DRMWorkerProcessEvaluateCrashRequest",
9127: "EMsg_DRMWorkerProcessEvaluateCrashResponse",
9128: "EMsg_DRMWorkerProcessAnalyzeFileRequest",
9129: "EMsg_DRMWorkerProcessAnalyzeFileResponse",
9130: "EMsg_DRMWorkerProcessUnpackBlobRequest",
9131: "EMsg_DRMWorkerProcessUnpackBlobResponse",
9132: "EMsg_DRMWorkerProcessInstallAllRequest",
9133: "EMsg_DRMWorkerProcessInstallAllResponse",
9200: "EMsg_TestWorkerProcess",
9201: "EMsg_TestWorkerProcessLoadUnloadModuleResponse",
9202: "EMsg_TestWorkerProcessServiceModuleCallRequest",
9203: "EMsg_TestWorkerProcessServiceModuleCallResponse",
9330: "EMsg_ClientGetEmoticonList",
9331: "EMsg_ClientEmoticonList",
9400: "EMsg_ClientSharedLibraryBase",
9403: "EMsg_ClientSharedLicensesLockStatus",
9404: "EMsg_ClientSharedLicensesStopPlaying",
9405: "EMsg_ClientSharedLibraryLockStatus",
9406: "EMsg_ClientSharedLibraryStopPlaying",
9507: "EMsg_ClientUnlockStreaming",
9508: "EMsg_ClientUnlockStreamingResponse",
9600: "EMsg_ClientPlayingSessionState",
9601: "EMsg_ClientKickPlayingSession",
9700: "EMsg_ClientBroadcastInit",
9701: "EMsg_ClientBroadcastFrames",
9702: "EMsg_ClientBroadcastDisconnect",
9703: "EMsg_ClientBroadcastScreenshot",
9704: "EMsg_ClientBroadcastUploadConfig",
9800: "EMsg_ClientVoiceCallPreAuthorize",
9801: "EMsg_ClientVoiceCallPreAuthorizeResponse",
}
func (e EMsg) String() string {
if s, ok := EMsg_name[e]; ok {
return s
}
var flags []string
for k, v := range EMsg_name {
if e&k != 0 {
flags = append(flags, v)
}
}
if len(flags) == 0 {
return fmt.Sprintf("%d", e)
}
sort.Strings(flags)
return strings.Join(flags, " | ")
}
type EResult int32
const (
EResult_Invalid EResult = 0
EResult_OK EResult = 1
EResult_Fail EResult = 2
EResult_NoConnection EResult = 3
EResult_InvalidPassword EResult = 5
EResult_LoggedInElsewhere EResult = 6
EResult_InvalidProtocolVer EResult = 7
EResult_InvalidParam EResult = 8
EResult_FileNotFound EResult = 9
EResult_Busy EResult = 10
EResult_InvalidState EResult = 11
EResult_InvalidName EResult = 12
EResult_InvalidEmail EResult = 13
EResult_DuplicateName EResult = 14
EResult_AccessDenied EResult = 15
EResult_Timeout EResult = 16
EResult_Banned EResult = 17
EResult_AccountNotFound EResult = 18
EResult_InvalidSteamID EResult = 19
EResult_ServiceUnavailable EResult = 20
EResult_NotLoggedOn EResult = 21
EResult_Pending EResult = 22
EResult_EncryptionFailure EResult = 23
EResult_InsufficientPrivilege EResult = 24
EResult_LimitExceeded EResult = 25
EResult_Revoked EResult = 26
EResult_Expired EResult = 27
EResult_AlreadyRedeemed EResult = 28
EResult_DuplicateRequest EResult = 29
EResult_AlreadyOwned EResult = 30
EResult_IPNotFound EResult = 31
EResult_PersistFailed EResult = 32
EResult_LockingFailed EResult = 33
EResult_LogonSessionReplaced EResult = 34
EResult_ConnectFailed EResult = 35
EResult_HandshakeFailed EResult = 36
EResult_IOFailure EResult = 37
EResult_RemoteDisconnect EResult = 38
EResult_ShoppingCartNotFound EResult = 39
EResult_Blocked EResult = 40
EResult_Ignored EResult = 41
EResult_NoMatch EResult = 42
EResult_AccountDisabled EResult = 43
EResult_ServiceReadOnly EResult = 44
EResult_AccountNotFeatured EResult = 45
EResult_AdministratorOK EResult = 46
EResult_ContentVersion EResult = 47
EResult_TryAnotherCM EResult = 48
EResult_PasswordRequiredToKickSession EResult = 49
EResult_AlreadyLoggedInElsewhere EResult = 50
EResult_Suspended EResult = 51
EResult_Cancelled EResult = 52
EResult_DataCorruption EResult = 53
EResult_DiskFull EResult = 54
EResult_RemoteCallFailed EResult = 55
EResult_PasswordNotSet EResult = 56 // Deprecated: renamed to PasswordUnset
EResult_PasswordUnset EResult = 56
EResult_ExternalAccountUnlinked EResult = 57
EResult_PSNTicketInvalid EResult = 58
EResult_ExternalAccountAlreadyLinked EResult = 59
EResult_RemoteFileConflict EResult = 60
EResult_IllegalPassword EResult = 61
EResult_SameAsPreviousValue EResult = 62
EResult_AccountLogonDenied EResult = 63
EResult_CannotUseOldPassword EResult = 64
EResult_InvalidLoginAuthCode EResult = 65
EResult_AccountLogonDeniedNoMailSent EResult = 66 // Deprecated: renamed to AccountLogonDeniedNoMail
EResult_AccountLogonDeniedNoMail EResult = 66
EResult_HardwareNotCapableOfIPT EResult = 67
EResult_IPTInitError EResult = 68
EResult_ParentalControlRestricted EResult = 69
EResult_FacebookQueryError EResult = 70
EResult_ExpiredLoginAuthCode EResult = 71
EResult_IPLoginRestrictionFailed EResult = 72
EResult_AccountLocked EResult = 73 // Deprecated: renamed to AccountLockedDown
EResult_AccountLockedDown EResult = 73
EResult_AccountLogonDeniedVerifiedEmailRequired EResult = 74
EResult_NoMatchingURL EResult = 75
EResult_BadResponse EResult = 76
EResult_RequirePasswordReEntry EResult = 77
EResult_ValueOutOfRange EResult = 78
EResult_UnexpectedError EResult = 79
EResult_Disabled EResult = 80
EResult_InvalidCEGSubmission EResult = 81
EResult_RestrictedDevice EResult = 82
EResult_RegionLocked EResult = 83
EResult_RateLimitExceeded EResult = 84
EResult_AccountLogonDeniedNeedTwoFactorCode EResult = 85 // Deprecated: renamed to AccountLoginDeniedNeedTwoFactor
EResult_AccountLoginDeniedNeedTwoFactor EResult = 85
EResult_ItemOrEntryHasBeenDeleted EResult = 86 // Deprecated: renamed to ItemDeleted
EResult_ItemDeleted EResult = 86
EResult_AccountLoginDeniedThrottle EResult = 87
EResult_TwoFactorCodeMismatch EResult = 88
EResult_TwoFactorActivationCodeMismatch EResult = 89
EResult_AccountAssociatedToMultiplePlayers EResult = 90 // Deprecated: renamed to AccountAssociatedToMultiplePartners
EResult_AccountAssociatedToMultiplePartners EResult = 90
EResult_NotModified EResult = 91
EResult_NoMobileDeviceAvailable EResult = 92 // Deprecated: renamed to NoMobileDevice
EResult_NoMobileDevice EResult = 92
EResult_TimeIsOutOfSync EResult = 93 // Deprecated: renamed to TimeNotSynced
EResult_TimeNotSynced EResult = 93
EResult_SMSCodeFailed EResult = 94
EResult_TooManyAccountsAccessThisResource EResult = 95 // Deprecated: renamed to AccountLimitExceeded
EResult_AccountLimitExceeded EResult = 95
EResult_AccountActivityLimitExceeded EResult = 96
EResult_PhoneActivityLimitExceeded EResult = 97
EResult_RefundToWallet EResult = 98
EResult_EmailSendFailure EResult = 99
EResult_NotSettled EResult = 100
EResult_NeedCaptcha EResult = 101
)
var EResult_name = map[EResult]string{
0: "EResult_Invalid",
1: "EResult_OK",
2: "EResult_Fail",
3: "EResult_NoConnection",
5: "EResult_InvalidPassword",
6: "EResult_LoggedInElsewhere",
7: "EResult_InvalidProtocolVer",
8: "EResult_InvalidParam",
9: "EResult_FileNotFound",
10: "EResult_Busy",
11: "EResult_InvalidState",
12: "EResult_InvalidName",
13: "EResult_InvalidEmail",
14: "EResult_DuplicateName",
15: "EResult_AccessDenied",
16: "EResult_Timeout",
17: "EResult_Banned",
18: "EResult_AccountNotFound",
19: "EResult_InvalidSteamID",
20: "EResult_ServiceUnavailable",
21: "EResult_NotLoggedOn",
22: "EResult_Pending",
23: "EResult_EncryptionFailure",
24: "EResult_InsufficientPrivilege",
25: "EResult_LimitExceeded",
26: "EResult_Revoked",
27: "EResult_Expired",
28: "EResult_AlreadyRedeemed",
29: "EResult_DuplicateRequest",
30: "EResult_AlreadyOwned",
31: "EResult_IPNotFound",
32: "EResult_PersistFailed",
33: "EResult_LockingFailed",
34: "EResult_LogonSessionReplaced",
35: "EResult_ConnectFailed",
36: "EResult_HandshakeFailed",
37: "EResult_IOFailure",
38: "EResult_RemoteDisconnect",
39: "EResult_ShoppingCartNotFound",
40: "EResult_Blocked",
41: "EResult_Ignored",
42: "EResult_NoMatch",
43: "EResult_AccountDisabled",
44: "EResult_ServiceReadOnly",
45: "EResult_AccountNotFeatured",
46: "EResult_AdministratorOK",
47: "EResult_ContentVersion",
48: "EResult_TryAnotherCM",
49: "EResult_PasswordRequiredToKickSession",
50: "EResult_AlreadyLoggedInElsewhere",
51: "EResult_Suspended",
52: "EResult_Cancelled",
53: "EResult_DataCorruption",
54: "EResult_DiskFull",
55: "EResult_RemoteCallFailed",
56: "EResult_PasswordNotSet",
57: "EResult_ExternalAccountUnlinked",
58: "EResult_PSNTicketInvalid",
59: "EResult_ExternalAccountAlreadyLinked",
60: "EResult_RemoteFileConflict",
61: "EResult_IllegalPassword",
62: "EResult_SameAsPreviousValue",
63: "EResult_AccountLogonDenied",
64: "EResult_CannotUseOldPassword",
65: "EResult_InvalidLoginAuthCode",
66: "EResult_AccountLogonDeniedNoMailSent",
67: "EResult_HardwareNotCapableOfIPT",
68: "EResult_IPTInitError",
69: "EResult_ParentalControlRestricted",
70: "EResult_FacebookQueryError",
71: "EResult_ExpiredLoginAuthCode",
72: "EResult_IPLoginRestrictionFailed",
73: "EResult_AccountLocked",
74: "EResult_AccountLogonDeniedVerifiedEmailRequired",
75: "EResult_NoMatchingURL",
76: "EResult_BadResponse",
77: "EResult_RequirePasswordReEntry",
78: "EResult_ValueOutOfRange",
79: "EResult_UnexpectedError",
80: "EResult_Disabled",
81: "EResult_InvalidCEGSubmission",
82: "EResult_RestrictedDevice",
83: "EResult_RegionLocked",
84: "EResult_RateLimitExceeded",
85: "EResult_AccountLogonDeniedNeedTwoFactorCode",
86: "EResult_ItemOrEntryHasBeenDeleted",
87: "EResult_AccountLoginDeniedThrottle",
88: "EResult_TwoFactorCodeMismatch",
89: "EResult_TwoFactorActivationCodeMismatch",
90: "EResult_AccountAssociatedToMultiplePlayers",
91: "EResult_NotModified",
92: "EResult_NoMobileDeviceAvailable",
93: "EResult_TimeIsOutOfSync",
94: "EResult_SMSCodeFailed",
95: "EResult_TooManyAccountsAccessThisResource",
96: "EResult_AccountActivityLimitExceeded",
97: "EResult_PhoneActivityLimitExceeded",
98: "EResult_RefundToWallet",
99: "EResult_EmailSendFailure",
100: "EResult_NotSettled",
101: "EResult_NeedCaptcha",
}
func (e EResult) String() string {
if s, ok := EResult_name[e]; ok {
return s
}
var flags []string
for k, v := range EResult_name {
if e&k != 0 {
flags = append(flags, v)
}
}
if len(flags) == 0 {
return fmt.Sprintf("%d", e)
}
sort.Strings(flags)
return strings.Join(flags, " | ")
}
type EUniverse int32
const (
EUniverse_Invalid EUniverse = 0
EUniverse_Public EUniverse = 1
EUniverse_Beta EUniverse = 2
EUniverse_Internal EUniverse = 3
EUniverse_Dev EUniverse = 4
EUniverse_Max EUniverse = 5
)
var EUniverse_name = map[EUniverse]string{
0: "EUniverse_Invalid",
1: "EUniverse_Public",
2: "EUniverse_Beta",
3: "EUniverse_Internal",
4: "EUniverse_Dev",
5: "EUniverse_Max",
}
func (e EUniverse) String() string {
if s, ok := EUniverse_name[e]; ok {
return s
}
var flags []string
for k, v := range EUniverse_name {
if e&k != 0 {
flags = append(flags, v)
}
}
if len(flags) == 0 {
return fmt.Sprintf("%d", e)
}
sort.Strings(flags)
return strings.Join(flags, " | ")
}
type EChatEntryType int32
const (
EChatEntryType_Invalid EChatEntryType = 0
EChatEntryType_ChatMsg EChatEntryType = 1
EChatEntryType_Typing EChatEntryType = 2
EChatEntryType_InviteGame EChatEntryType = 3
EChatEntryType_Emote EChatEntryType = 4 // Deprecated: No longer supported by clients
EChatEntryType_LobbyGameStart EChatEntryType = 5 // Deprecated: Listen for LobbyGameCreated_t callback instead
EChatEntryType_LeftConversation EChatEntryType = 6
EChatEntryType_Entered EChatEntryType = 7
EChatEntryType_WasKicked EChatEntryType = 8
EChatEntryType_WasBanned EChatEntryType = 9
EChatEntryType_Disconnected EChatEntryType = 10
EChatEntryType_HistoricalChat EChatEntryType = 11
EChatEntryType_Reserved1 EChatEntryType = 12
EChatEntryType_Reserved2 EChatEntryType = 13
EChatEntryType_LinkBlocked EChatEntryType = 14
)
var EChatEntryType_name = map[EChatEntryType]string{
0: "EChatEntryType_Invalid",
1: "EChatEntryType_ChatMsg",
2: "EChatEntryType_Typing",
3: "EChatEntryType_InviteGame",
4: "EChatEntryType_Emote",
5: "EChatEntryType_LobbyGameStart",
6: "EChatEntryType_LeftConversation",
7: "EChatEntryType_Entered",
8: "EChatEntryType_WasKicked",
9: "EChatEntryType_WasBanned",
10: "EChatEntryType_Disconnected",
11: "EChatEntryType_HistoricalChat",
12: "EChatEntryType_Reserved1",
13: "EChatEntryType_Reserved2",
14: "EChatEntryType_LinkBlocked",
}
func (e EChatEntryType) String() string {
if s, ok := EChatEntryType_name[e]; ok {
return s
}
var flags []string
for k, v := range EChatEntryType_name {
if e&k != 0 {
flags = append(flags, v)
}
}
if len(flags) == 0 {
return fmt.Sprintf("%d", e)
}
sort.Strings(flags)
return strings.Join(flags, " | ")
}
type EPersonaState int32
const (
EPersonaState_Offline EPersonaState = 0
EPersonaState_Online EPersonaState = 1
EPersonaState_Busy EPersonaState = 2
EPersonaState_Away EPersonaState = 3
EPersonaState_Snooze EPersonaState = 4
EPersonaState_LookingToTrade EPersonaState = 5
EPersonaState_LookingToPlay EPersonaState = 6
EPersonaState_Max EPersonaState = 7
)
var EPersonaState_name = map[EPersonaState]string{
0: "EPersonaState_Offline",
1: "EPersonaState_Online",
2: "EPersonaState_Busy",
3: "EPersonaState_Away",
4: "EPersonaState_Snooze",
5: "EPersonaState_LookingToTrade",
6: "EPersonaState_LookingToPlay",
7: "EPersonaState_Max",
}
func (e EPersonaState) String() string {
if s, ok := EPersonaState_name[e]; ok {
return s
}
var flags []string
for k, v := range EPersonaState_name {
if e&k != 0 {
flags = append(flags, v)
}
}
if len(flags) == 0 {
return fmt.Sprintf("%d", e)
}
sort.Strings(flags)
return strings.Join(flags, " | ")
}
type EAccountType int32
const (
EAccountType_Invalid EAccountType = 0
EAccountType_Individual EAccountType = 1
EAccountType_Multiseat EAccountType = 2
EAccountType_GameServer EAccountType = 3
EAccountType_AnonGameServer EAccountType = 4
EAccountType_Pending EAccountType = 5
EAccountType_ContentServer EAccountType = 6
EAccountType_Clan EAccountType = 7
EAccountType_Chat EAccountType = 8
EAccountType_ConsoleUser EAccountType = 9
EAccountType_AnonUser EAccountType = 10
EAccountType_Max EAccountType = 11
)
var EAccountType_name = map[EAccountType]string{
0: "EAccountType_Invalid",
1: "EAccountType_Individual",
2: "EAccountType_Multiseat",
3: "EAccountType_GameServer",
4: "EAccountType_AnonGameServer",
5: "EAccountType_Pending",
6: "EAccountType_ContentServer",
7: "EAccountType_Clan",
8: "EAccountType_Chat",
9: "EAccountType_ConsoleUser",
10: "EAccountType_AnonUser",
11: "EAccountType_Max",
}
func (e EAccountType) String() string {
if s, ok := EAccountType_name[e]; ok {
return s
}
var flags []string
for k, v := range EAccountType_name {
if e&k != 0 {
flags = append(flags, v)
}
}
if len(flags) == 0 {
return fmt.Sprintf("%d", e)
}
sort.Strings(flags)
return strings.Join(flags, " | ")
}
type EFriendRelationship int32
const (
EFriendRelationship_None EFriendRelationship = 0
EFriendRelationship_Blocked EFriendRelationship = 1
EFriendRelationship_RequestRecipient EFriendRelationship = 2
EFriendRelationship_Friend EFriendRelationship = 3
EFriendRelationship_RequestInitiator EFriendRelationship = 4
EFriendRelationship_Ignored EFriendRelationship = 5
EFriendRelationship_IgnoredFriend EFriendRelationship = 6
EFriendRelationship_SuggestedFriend EFriendRelationship = 7
EFriendRelationship_Max EFriendRelationship = 8
)
var EFriendRelationship_name = map[EFriendRelationship]string{
0: "EFriendRelationship_None",
1: "EFriendRelationship_Blocked",
2: "EFriendRelationship_RequestRecipient",
3: "EFriendRelationship_Friend",
4: "EFriendRelationship_RequestInitiator",
5: "EFriendRelationship_Ignored",
6: "EFriendRelationship_IgnoredFriend",
7: "EFriendRelationship_SuggestedFriend",
8: "EFriendRelationship_Max",
}
func (e EFriendRelationship) String() string {
if s, ok := EFriendRelationship_name[e]; ok {
return s
}
var flags []string
for k, v := range EFriendRelationship_name {
if e&k != 0 {
flags = append(flags, v)
}
}
if len(flags) == 0 {
return fmt.Sprintf("%d", e)
}
sort.Strings(flags)
return strings.Join(flags, " | ")
}
type EAccountFlags int32
const (
EAccountFlags_NormalUser EAccountFlags = 0
EAccountFlags_PersonaNameSet EAccountFlags = 1
EAccountFlags_Unbannable EAccountFlags = 2
EAccountFlags_PasswordSet EAccountFlags = 4
EAccountFlags_Support EAccountFlags = 8
EAccountFlags_Admin EAccountFlags = 16
EAccountFlags_Supervisor EAccountFlags = 32
EAccountFlags_AppEditor EAccountFlags = 64
EAccountFlags_HWIDSet EAccountFlags = 128
EAccountFlags_PersonalQASet EAccountFlags = 256
EAccountFlags_VacBeta EAccountFlags = 512
EAccountFlags_Debug EAccountFlags = 1024
EAccountFlags_Disabled EAccountFlags = 2048
EAccountFlags_LimitedUser EAccountFlags = 4096
EAccountFlags_LimitedUserForce EAccountFlags = 8192
EAccountFlags_EmailValidated EAccountFlags = 16384
EAccountFlags_MarketingTreatment EAccountFlags = 32768
EAccountFlags_OGGInviteOptOut EAccountFlags = 65536
EAccountFlags_ForcePasswordChange EAccountFlags = 131072
EAccountFlags_ForceEmailVerification EAccountFlags = 262144
EAccountFlags_LogonExtraSecurity EAccountFlags = 524288
EAccountFlags_LogonExtraSecurityDisabled EAccountFlags = 1048576
EAccountFlags_Steam2MigrationComplete EAccountFlags = 2097152
EAccountFlags_NeedLogs EAccountFlags = 4194304
EAccountFlags_Lockdown EAccountFlags = 8388608
EAccountFlags_MasterAppEditor EAccountFlags = 16777216
EAccountFlags_BannedFromWebAPI EAccountFlags = 33554432
EAccountFlags_ClansOnlyFromFriends EAccountFlags = 67108864
EAccountFlags_GlobalModerator EAccountFlags = 134217728
)
var EAccountFlags_name = map[EAccountFlags]string{
0: "EAccountFlags_NormalUser",
1: "EAccountFlags_PersonaNameSet",
2: "EAccountFlags_Unbannable",
4: "EAccountFlags_PasswordSet",
8: "EAccountFlags_Support",
16: "EAccountFlags_Admin",
32: "EAccountFlags_Supervisor",
64: "EAccountFlags_AppEditor",
128: "EAccountFlags_HWIDSet",
256: "EAccountFlags_PersonalQASet",
512: "EAccountFlags_VacBeta",
1024: "EAccountFlags_Debug",
2048: "EAccountFlags_Disabled",
4096: "EAccountFlags_LimitedUser",
8192: "EAccountFlags_LimitedUserForce",
16384: "EAccountFlags_EmailValidated",
32768: "EAccountFlags_MarketingTreatment",
65536: "EAccountFlags_OGGInviteOptOut",
131072: "EAccountFlags_ForcePasswordChange",
262144: "EAccountFlags_ForceEmailVerification",
524288: "EAccountFlags_LogonExtraSecurity",
1048576: "EAccountFlags_LogonExtraSecurityDisabled",
2097152: "EAccountFlags_Steam2MigrationComplete",
4194304: "EAccountFlags_NeedLogs",
8388608: "EAccountFlags_Lockdown",
16777216: "EAccountFlags_MasterAppEditor",
33554432: "EAccountFlags_BannedFromWebAPI",
67108864: "EAccountFlags_ClansOnlyFromFriends",
134217728: "EAccountFlags_GlobalModerator",
}
func (e EAccountFlags) String() string {
if s, ok := EAccountFlags_name[e]; ok {
return s
}
var flags []string
for k, v := range EAccountFlags_name {
if e&k != 0 {
flags = append(flags, v)
}
}
if len(flags) == 0 {
return fmt.Sprintf("%d", e)
}
sort.Strings(flags)
return strings.Join(flags, " | ")
}
type EClanPermission int32
const (
EClanPermission_Nobody EClanPermission = 0
EClanPermission_Owner EClanPermission = 1
EClanPermission_Officer EClanPermission = 2
EClanPermission_OwnerAndOfficer EClanPermission = 3
EClanPermission_Member EClanPermission = 4
EClanPermission_Moderator EClanPermission = 8
EClanPermission_OwnerOfficerModerator EClanPermission = EClanPermission_Owner | EClanPermission_Officer | EClanPermission_Moderator
EClanPermission_AllMembers EClanPermission = EClanPermission_Owner | EClanPermission_Officer | EClanPermission_Moderator | EClanPermission_Member
EClanPermission_OGGGameOwner EClanPermission = 16
EClanPermission_NonMember EClanPermission = 128
EClanPermission_MemberAllowed EClanPermission = EClanPermission_NonMember | EClanPermission_Member
EClanPermission_ModeratorAllowed EClanPermission = EClanPermission_NonMember | EClanPermission_Member | EClanPermission_Moderator
EClanPermission_OfficerAllowed EClanPermission = EClanPermission_NonMember | EClanPermission_Member | EClanPermission_Moderator | EClanPermission_Officer
EClanPermission_OwnerAllowed EClanPermission = EClanPermission_NonMember | EClanPermission_Member | EClanPermission_Moderator | EClanPermission_Officer | EClanPermission_Owner
EClanPermission_Anybody EClanPermission = EClanPermission_NonMember | EClanPermission_Member | EClanPermission_Moderator | EClanPermission_Officer | EClanPermission_Owner
)
var EClanPermission_name = map[EClanPermission]string{
0: "EClanPermission_Nobody",
1: "EClanPermission_Owner",
2: "EClanPermission_Officer",
3: "EClanPermission_OwnerAndOfficer",
4: "EClanPermission_Member",
8: "EClanPermission_Moderator",
11: "EClanPermission_OwnerOfficerModerator",
15: "EClanPermission_AllMembers",
16: "EClanPermission_OGGGameOwner",
128: "EClanPermission_NonMember",
132: "EClanPermission_MemberAllowed",
140: "EClanPermission_ModeratorAllowed",
142: "EClanPermission_OfficerAllowed",
143: "EClanPermission_OwnerAllowed",
}
func (e EClanPermission) String() string {
if s, ok := EClanPermission_name[e]; ok {
return s
}
var flags []string
for k, v := range EClanPermission_name {
if e&k != 0 {
flags = append(flags, v)
}
}
if len(flags) == 0 {
return fmt.Sprintf("%d", e)
}
sort.Strings(flags)
return strings.Join(flags, " | ")
}
type EChatPermission int32
const (
EChatPermission_Close EChatPermission = 1
EChatPermission_Invite EChatPermission = 2
EChatPermission_Talk EChatPermission = 8
EChatPermission_Kick EChatPermission = 16
EChatPermission_Mute EChatPermission = 32
EChatPermission_SetMetadata EChatPermission = 64
EChatPermission_ChangePermissions EChatPermission = 128
EChatPermission_Ban EChatPermission = 256
EChatPermission_ChangeAccess EChatPermission = 512
EChatPermission_EveryoneNotInClanDefault EChatPermission = EChatPermission_Talk
EChatPermission_EveryoneDefault EChatPermission = EChatPermission_Talk | EChatPermission_Invite
EChatPermission_MemberDefault EChatPermission = EChatPermission_Ban | EChatPermission_Kick | EChatPermission_Talk | EChatPermission_Invite
EChatPermission_OfficerDefault EChatPermission = EChatPermission_Ban | EChatPermission_Kick | EChatPermission_Talk | EChatPermission_Invite
EChatPermission_OwnerDefault EChatPermission = EChatPermission_ChangeAccess | EChatPermission_Ban | EChatPermission_SetMetadata | EChatPermission_Mute | EChatPermission_Kick | EChatPermission_Talk | EChatPermission_Invite | EChatPermission_Close
EChatPermission_Mask EChatPermission = 1019
)
var EChatPermission_name = map[EChatPermission]string{
1: "EChatPermission_Close",
2: "EChatPermission_Invite",
8: "EChatPermission_Talk",
16: "EChatPermission_Kick",
32: "EChatPermission_Mute",
64: "EChatPermission_SetMetadata",
128: "EChatPermission_ChangePermissions",
256: "EChatPermission_Ban",
512: "EChatPermission_ChangeAccess",
10: "EChatPermission_EveryoneDefault",
282: "EChatPermission_MemberDefault",
891: "EChatPermission_OwnerDefault",
1019: "EChatPermission_Mask",
}
func (e EChatPermission) String() string {
if s, ok := EChatPermission_name[e]; ok {
return s
}
var flags []string
for k, v := range EChatPermission_name {
if e&k != 0 {
flags = append(flags, v)
}
}
if len(flags) == 0 {
return fmt.Sprintf("%d", e)
}
sort.Strings(flags)
return strings.Join(flags, " | ")
}
type EFriendFlags int32
const (
EFriendFlags_None EFriendFlags = 0
EFriendFlags_Blocked EFriendFlags = 1
EFriendFlags_FriendshipRequested EFriendFlags = 2
EFriendFlags_Immediate EFriendFlags = 4
EFriendFlags_ClanMember EFriendFlags = 8
EFriendFlags_OnGameServer EFriendFlags = 16
EFriendFlags_RequestingFriendship EFriendFlags = 128
EFriendFlags_RequestingInfo EFriendFlags = 256
EFriendFlags_Ignored EFriendFlags = 512
EFriendFlags_IgnoredFriend EFriendFlags = 1024
EFriendFlags_Suggested EFriendFlags = 2048
EFriendFlags_FlagAll EFriendFlags = 65535
)
var EFriendFlags_name = map[EFriendFlags]string{
0: "EFriendFlags_None",
1: "EFriendFlags_Blocked",
2: "EFriendFlags_FriendshipRequested",
4: "EFriendFlags_Immediate",
8: "EFriendFlags_ClanMember",
16: "EFriendFlags_OnGameServer",
128: "EFriendFlags_RequestingFriendship",
256: "EFriendFlags_RequestingInfo",
512: "EFriendFlags_Ignored",
1024: "EFriendFlags_IgnoredFriend",
2048: "EFriendFlags_Suggested",
65535: "EFriendFlags_FlagAll",
}
func (e EFriendFlags) String() string {
if s, ok := EFriendFlags_name[e]; ok {
return s
}
var flags []string
for k, v := range EFriendFlags_name {
if e&k != 0 {
flags = append(flags, v)
}
}
if len(flags) == 0 {
return fmt.Sprintf("%d", e)
}
sort.Strings(flags)
return strings.Join(flags, " | ")
}
type EPersonaStateFlag int32
const (
EPersonaStateFlag_HasRichPresence EPersonaStateFlag = 1
EPersonaStateFlag_InJoinableGame EPersonaStateFlag = 2
EPersonaStateFlag_OnlineUsingWeb EPersonaStateFlag = 256
EPersonaStateFlag_OnlineUsingMobile EPersonaStateFlag = 512
EPersonaStateFlag_OnlineUsingBigPicture EPersonaStateFlag = 1024
)
var EPersonaStateFlag_name = map[EPersonaStateFlag]string{
1: "EPersonaStateFlag_HasRichPresence",
2: "EPersonaStateFlag_InJoinableGame",
256: "EPersonaStateFlag_OnlineUsingWeb",
512: "EPersonaStateFlag_OnlineUsingMobile",
1024: "EPersonaStateFlag_OnlineUsingBigPicture",
}
func (e EPersonaStateFlag) String() string {
if s, ok := EPersonaStateFlag_name[e]; ok {
return s
}
var flags []string
for k, v := range EPersonaStateFlag_name {
if e&k != 0 {
flags = append(flags, v)
}
}
if len(flags) == 0 {
return fmt.Sprintf("%d", e)
}
sort.Strings(flags)
return strings.Join(flags, " | ")
}
type EClientPersonaStateFlag int32
const (
EClientPersonaStateFlag_Status EClientPersonaStateFlag = 1
EClientPersonaStateFlag_PlayerName EClientPersonaStateFlag = 2
EClientPersonaStateFlag_QueryPort EClientPersonaStateFlag = 4
EClientPersonaStateFlag_SourceID EClientPersonaStateFlag = 8
EClientPersonaStateFlag_Presence EClientPersonaStateFlag = 16
EClientPersonaStateFlag_Metadata EClientPersonaStateFlag = 32
EClientPersonaStateFlag_LastSeen EClientPersonaStateFlag = 64
EClientPersonaStateFlag_ClanInfo EClientPersonaStateFlag = 128
EClientPersonaStateFlag_GameExtraInfo EClientPersonaStateFlag = 256
EClientPersonaStateFlag_GameDataBlob EClientPersonaStateFlag = 512
EClientPersonaStateFlag_ClanTag EClientPersonaStateFlag = 1024
EClientPersonaStateFlag_Facebook EClientPersonaStateFlag = 2048
)
var EClientPersonaStateFlag_name = map[EClientPersonaStateFlag]string{
1: "EClientPersonaStateFlag_Status",
2: "EClientPersonaStateFlag_PlayerName",
4: "EClientPersonaStateFlag_QueryPort",
8: "EClientPersonaStateFlag_SourceID",
16: "EClientPersonaStateFlag_Presence",
32: "EClientPersonaStateFlag_Metadata",
64: "EClientPersonaStateFlag_LastSeen",
128: "EClientPersonaStateFlag_ClanInfo",
256: "EClientPersonaStateFlag_GameExtraInfo",
512: "EClientPersonaStateFlag_GameDataBlob",
1024: "EClientPersonaStateFlag_ClanTag",
2048: "EClientPersonaStateFlag_Facebook",
}
func (e EClientPersonaStateFlag) String() string {
if s, ok := EClientPersonaStateFlag_name[e]; ok {
return s
}
var flags []string
for k, v := range EClientPersonaStateFlag_name {
if e&k != 0 {
flags = append(flags, v)
}
}
if len(flags) == 0 {
return fmt.Sprintf("%d", e)
}
sort.Strings(flags)
return strings.Join(flags, " | ")
}
type EAppUsageEvent int32
const (
EAppUsageEvent_GameLaunch EAppUsageEvent = 1
EAppUsageEvent_GameLaunchTrial EAppUsageEvent = 2
EAppUsageEvent_Media EAppUsageEvent = 3
EAppUsageEvent_PreloadStart EAppUsageEvent = 4
EAppUsageEvent_PreloadFinish EAppUsageEvent = 5
EAppUsageEvent_MarketingMessageView EAppUsageEvent = 6
EAppUsageEvent_InGameAdViewed EAppUsageEvent = 7
EAppUsageEvent_GameLaunchFreeWeekend EAppUsageEvent = 8
)
var EAppUsageEvent_name = map[EAppUsageEvent]string{
1: "EAppUsageEvent_GameLaunch",
2: "EAppUsageEvent_GameLaunchTrial",
3: "EAppUsageEvent_Media",
4: "EAppUsageEvent_PreloadStart",
5: "EAppUsageEvent_PreloadFinish",
6: "EAppUsageEvent_MarketingMessageView",
7: "EAppUsageEvent_InGameAdViewed",
8: "EAppUsageEvent_GameLaunchFreeWeekend",
}
func (e EAppUsageEvent) String() string {
if s, ok := EAppUsageEvent_name[e]; ok {
return s
}
var flags []string
for k, v := range EAppUsageEvent_name {
if e&k != 0 {
flags = append(flags, v)
}
}
if len(flags) == 0 {
return fmt.Sprintf("%d", e)
}
sort.Strings(flags)
return strings.Join(flags, " | ")
}
type ELicenseFlags int32
const (
ELicenseFlags_None ELicenseFlags = 0
ELicenseFlags_Renew ELicenseFlags = 0x01
ELicenseFlags_RenewalFailed ELicenseFlags = 0x02
ELicenseFlags_Pending ELicenseFlags = 0x04
ELicenseFlags_Expired ELicenseFlags = 0x08
ELicenseFlags_CancelledByUser ELicenseFlags = 0x10
ELicenseFlags_CancelledByAdmin ELicenseFlags = 0x20
ELicenseFlags_LowViolenceContent ELicenseFlags = 0x40
ELicenseFlags_ImportedFromSteam2 ELicenseFlags = 0x80
)
var ELicenseFlags_name = map[ELicenseFlags]string{
0: "ELicenseFlags_None",
1: "ELicenseFlags_Renew",
2: "ELicenseFlags_RenewalFailed",
4: "ELicenseFlags_Pending",
8: "ELicenseFlags_Expired",
16: "ELicenseFlags_CancelledByUser",
32: "ELicenseFlags_CancelledByAdmin",
64: "ELicenseFlags_LowViolenceContent",
128: "ELicenseFlags_ImportedFromSteam2",
}
func (e ELicenseFlags) String() string {
if s, ok := ELicenseFlags_name[e]; ok {
return s
}
var flags []string
for k, v := range ELicenseFlags_name {
if e&k != 0 {
flags = append(flags, v)
}
}
if len(flags) == 0 {
return fmt.Sprintf("%d", e)
}
sort.Strings(flags)
return strings.Join(flags, " | ")
}
type ELicenseType int32
const (
ELicenseType_NoLicense ELicenseType = 0
ELicenseType_SinglePurchase ELicenseType = 1
ELicenseType_SinglePurchaseLimitedUse ELicenseType = 2
ELicenseType_RecurringCharge ELicenseType = 3
ELicenseType_RecurringChargeLimitedUse ELicenseType = 4
ELicenseType_RecurringChargeLimitedUseWithOverages ELicenseType = 5
ELicenseType_RecurringOption ELicenseType = 6
)
var ELicenseType_name = map[ELicenseType]string{
0: "ELicenseType_NoLicense",
1: "ELicenseType_SinglePurchase",
2: "ELicenseType_SinglePurchaseLimitedUse",
3: "ELicenseType_RecurringCharge",
4: "ELicenseType_RecurringChargeLimitedUse",
5: "ELicenseType_RecurringChargeLimitedUseWithOverages",
6: "ELicenseType_RecurringOption",
}
func (e ELicenseType) String() string {
if s, ok := ELicenseType_name[e]; ok {
return s
}
var flags []string
for k, v := range ELicenseType_name {
if e&k != 0 {
flags = append(flags, v)
}
}
if len(flags) == 0 {
return fmt.Sprintf("%d", e)
}
sort.Strings(flags)
return strings.Join(flags, " | ")
}
type EPaymentMethod int32
const (
EPaymentMethod_None EPaymentMethod = 0
EPaymentMethod_ActivationCode EPaymentMethod = 1
EPaymentMethod_CreditCard EPaymentMethod = 2
EPaymentMethod_Giropay EPaymentMethod = 3
EPaymentMethod_PayPal EPaymentMethod = 4
EPaymentMethod_Ideal EPaymentMethod = 5
EPaymentMethod_PaySafeCard EPaymentMethod = 6
EPaymentMethod_Sofort EPaymentMethod = 7
EPaymentMethod_GuestPass EPaymentMethod = 8
EPaymentMethod_WebMoney EPaymentMethod = 9
EPaymentMethod_MoneyBookers EPaymentMethod = 10
EPaymentMethod_AliPay EPaymentMethod = 11
EPaymentMethod_Yandex EPaymentMethod = 12
EPaymentMethod_Kiosk EPaymentMethod = 13
EPaymentMethod_Qiwi EPaymentMethod = 14
EPaymentMethod_GameStop EPaymentMethod = 15
EPaymentMethod_HardwarePromo EPaymentMethod = 16
EPaymentMethod_MoPay EPaymentMethod = 17
EPaymentMethod_BoletoBancario EPaymentMethod = 18
EPaymentMethod_BoaCompraGold EPaymentMethod = 19
EPaymentMethod_BancoDoBrasilOnline EPaymentMethod = 20
EPaymentMethod_ItauOnline EPaymentMethod = 21
EPaymentMethod_BradescoOnline EPaymentMethod = 22
EPaymentMethod_Pagseguro EPaymentMethod = 23
EPaymentMethod_VisaBrazil EPaymentMethod = 24
EPaymentMethod_AmexBrazil EPaymentMethod = 25
EPaymentMethod_Aura EPaymentMethod = 26
EPaymentMethod_Hipercard EPaymentMethod = 27
EPaymentMethod_MastercardBrazil EPaymentMethod = 28
EPaymentMethod_DinersCardBrazil EPaymentMethod = 29
EPaymentMethod_AuthorizedDevice EPaymentMethod = 30
EPaymentMethod_MOLPoints EPaymentMethod = 31
EPaymentMethod_ClickAndBuy EPaymentMethod = 32
EPaymentMethod_Beeline EPaymentMethod = 33
EPaymentMethod_Konbini EPaymentMethod = 34
EPaymentMethod_EClubPoints EPaymentMethod = 35
EPaymentMethod_CreditCardJapan EPaymentMethod = 36
EPaymentMethod_BankTransferJapan EPaymentMethod = 37
EPaymentMethod_PayEasyJapan EPaymentMethod = 38
EPaymentMethod_Zong EPaymentMethod = 39
EPaymentMethod_CultureVoucher EPaymentMethod = 40
EPaymentMethod_BookVoucher EPaymentMethod = 41
EPaymentMethod_HappymoneyVoucher EPaymentMethod = 42
EPaymentMethod_ConvenientStoreVoucher EPaymentMethod = 43
EPaymentMethod_GameVoucher EPaymentMethod = 44
EPaymentMethod_Multibanco EPaymentMethod = 45
EPaymentMethod_Payshop EPaymentMethod = 46
EPaymentMethod_Maestro EPaymentMethod = 47
EPaymentMethod_OXXO EPaymentMethod = 48
EPaymentMethod_ToditoCash EPaymentMethod = 49
EPaymentMethod_Carnet EPaymentMethod = 50
EPaymentMethod_SPEI EPaymentMethod = 51
EPaymentMethod_ThreePay EPaymentMethod = 52
EPaymentMethod_IsBank EPaymentMethod = 53
EPaymentMethod_Garanti EPaymentMethod = 54
EPaymentMethod_Akbank EPaymentMethod = 55
EPaymentMethod_YapiKredi EPaymentMethod = 56
EPaymentMethod_Halkbank EPaymentMethod = 57
EPaymentMethod_BankAsya EPaymentMethod = 58
EPaymentMethod_Finansbank EPaymentMethod = 59
EPaymentMethod_DenizBank EPaymentMethod = 60
EPaymentMethod_PTT EPaymentMethod = 61
EPaymentMethod_CashU EPaymentMethod = 62
EPaymentMethod_OneCard EPaymentMethod = 63
EPaymentMethod_AutoGrant EPaymentMethod = 64
EPaymentMethod_WebMoneyJapan EPaymentMethod = 65
EPaymentMethod_Smart2PayTest EPaymentMethod = 66
EPaymentMethod_Wallet EPaymentMethod = 128
EPaymentMethod_Valve EPaymentMethod = 129
EPaymentMethod_SteamPressMaster EPaymentMethod = 130
EPaymentMethod_StorePromotion EPaymentMethod = 131
EPaymentMethod_OEMTicket EPaymentMethod = 256
EPaymentMethod_Split EPaymentMethod = 512
EPaymentMethod_Complimentary EPaymentMethod = 1024
)
var EPaymentMethod_name = map[EPaymentMethod]string{
0: "EPaymentMethod_None",
1: "EPaymentMethod_ActivationCode",
2: "EPaymentMethod_CreditCard",
3: "EPaymentMethod_Giropay",
4: "EPaymentMethod_PayPal",
5: "EPaymentMethod_Ideal",
6: "EPaymentMethod_PaySafeCard",
7: "EPaymentMethod_Sofort",
8: "EPaymentMethod_GuestPass",
9: "EPaymentMethod_WebMoney",
10: "EPaymentMethod_MoneyBookers",
11: "EPaymentMethod_AliPay",
12: "EPaymentMethod_Yandex",
13: "EPaymentMethod_Kiosk",
14: "EPaymentMethod_Qiwi",
15: "EPaymentMethod_GameStop",
16: "EPaymentMethod_HardwarePromo",
17: "EPaymentMethod_MoPay",
18: "EPaymentMethod_BoletoBancario",
19: "EPaymentMethod_BoaCompraGold",
20: "EPaymentMethod_BancoDoBrasilOnline",
21: "EPaymentMethod_ItauOnline",
22: "EPaymentMethod_BradescoOnline",
23: "EPaymentMethod_Pagseguro",
24: "EPaymentMethod_VisaBrazil",
25: "EPaymentMethod_AmexBrazil",
26: "EPaymentMethod_Aura",
27: "EPaymentMethod_Hipercard",
28: "EPaymentMethod_MastercardBrazil",
29: "EPaymentMethod_DinersCardBrazil",
30: "EPaymentMethod_AuthorizedDevice",
31: "EPaymentMethod_MOLPoints",
32: "EPaymentMethod_ClickAndBuy",
33: "EPaymentMethod_Beeline",
34: "EPaymentMethod_Konbini",
35: "EPaymentMethod_EClubPoints",
36: "EPaymentMethod_CreditCardJapan",
37: "EPaymentMethod_BankTransferJapan",
38: "EPaymentMethod_PayEasyJapan",
39: "EPaymentMethod_Zong",
40: "EPaymentMethod_CultureVoucher",
41: "EPaymentMethod_BookVoucher",
42: "EPaymentMethod_HappymoneyVoucher",
43: "EPaymentMethod_ConvenientStoreVoucher",
44: "EPaymentMethod_GameVoucher",
45: "EPaymentMethod_Multibanco",
46: "EPaymentMethod_Payshop",
47: "EPaymentMethod_Maestro",
48: "EPaymentMethod_OXXO",
49: "EPaymentMethod_ToditoCash",
50: "EPaymentMethod_Carnet",
51: "EPaymentMethod_SPEI",
52: "EPaymentMethod_ThreePay",
53: "EPaymentMethod_IsBank",
54: "EPaymentMethod_Garanti",
55: "EPaymentMethod_Akbank",
56: "EPaymentMethod_YapiKredi",
57: "EPaymentMethod_Halkbank",
58: "EPaymentMethod_BankAsya",
59: "EPaymentMethod_Finansbank",
60: "EPaymentMethod_DenizBank",
61: "EPaymentMethod_PTT",
62: "EPaymentMethod_CashU",
63: "EPaymentMethod_OneCard",
64: "EPaymentMethod_AutoGrant",
65: "EPaymentMethod_WebMoneyJapan",
66: "EPaymentMethod_Smart2PayTest",
128: "EPaymentMethod_Wallet",
129: "EPaymentMethod_Valve",
130: "EPaymentMethod_SteamPressMaster",
131: "EPaymentMethod_StorePromotion",
256: "EPaymentMethod_OEMTicket",
512: "EPaymentMethod_Split",
1024: "EPaymentMethod_Complimentary",
}
func (e EPaymentMethod) String() string {
if s, ok := EPaymentMethod_name[e]; ok {
return s
}
var flags []string
for k, v := range EPaymentMethod_name {
if e&k != 0 {
flags = append(flags, v)
}
}
if len(flags) == 0 {
return fmt.Sprintf("%d", e)
}
sort.Strings(flags)
return strings.Join(flags, " | ")
}
type EIntroducerRouting int32
const (
EIntroducerRouting_FileShare EIntroducerRouting = 0 // Deprecated
EIntroducerRouting_P2PVoiceChat EIntroducerRouting = 1
EIntroducerRouting_P2PNetworking EIntroducerRouting = 2
)
var EIntroducerRouting_name = map[EIntroducerRouting]string{
0: "EIntroducerRouting_FileShare",
1: "EIntroducerRouting_P2PVoiceChat",
2: "EIntroducerRouting_P2PNetworking",
}
func (e EIntroducerRouting) String() string {
if s, ok := EIntroducerRouting_name[e]; ok {
return s
}
var flags []string
for k, v := range EIntroducerRouting_name {
if e&k != 0 {
flags = append(flags, v)
}
}
if len(flags) == 0 {
return fmt.Sprintf("%d", e)
}
sort.Strings(flags)
return strings.Join(flags, " | ")
}
type EServerFlags int32
const (
EServerFlags_None EServerFlags = 0
EServerFlags_Active EServerFlags = 1
EServerFlags_Secure EServerFlags = 2
EServerFlags_Dedicated EServerFlags = 4
EServerFlags_Linux EServerFlags = 8
EServerFlags_Passworded EServerFlags = 16
EServerFlags_Private EServerFlags = 32
)
var EServerFlags_name = map[EServerFlags]string{
0: "EServerFlags_None",
1: "EServerFlags_Active",
2: "EServerFlags_Secure",
4: "EServerFlags_Dedicated",
8: "EServerFlags_Linux",
16: "EServerFlags_Passworded",
32: "EServerFlags_Private",
}
func (e EServerFlags) String() string {
if s, ok := EServerFlags_name[e]; ok {
return s
}
var flags []string
for k, v := range EServerFlags_name {
if e&k != 0 {
flags = append(flags, v)
}
}
if len(flags) == 0 {
return fmt.Sprintf("%d", e)
}
sort.Strings(flags)
return strings.Join(flags, " | ")
}
type EDenyReason int32
const (
EDenyReason_InvalidVersion EDenyReason = 1
EDenyReason_Generic EDenyReason = 2
EDenyReason_NotLoggedOn EDenyReason = 3
EDenyReason_NoLicense EDenyReason = 4
EDenyReason_Cheater EDenyReason = 5
EDenyReason_LoggedInElseWhere EDenyReason = 6
EDenyReason_UnknownText EDenyReason = 7
EDenyReason_IncompatibleAnticheat EDenyReason = 8
EDenyReason_MemoryCorruption EDenyReason = 9
EDenyReason_IncompatibleSoftware EDenyReason = 10
EDenyReason_SteamConnectionLost EDenyReason = 11
EDenyReason_SteamConnectionError EDenyReason = 12
EDenyReason_SteamResponseTimedOut EDenyReason = 13
EDenyReason_SteamValidationStalled EDenyReason = 14
EDenyReason_SteamOwnerLeftGuestUser EDenyReason = 15
)
var EDenyReason_name = map[EDenyReason]string{
1: "EDenyReason_InvalidVersion",
2: "EDenyReason_Generic",
3: "EDenyReason_NotLoggedOn",
4: "EDenyReason_NoLicense",
5: "EDenyReason_Cheater",
6: "EDenyReason_LoggedInElseWhere",
7: "EDenyReason_UnknownText",
8: "EDenyReason_IncompatibleAnticheat",
9: "EDenyReason_MemoryCorruption",
10: "EDenyReason_IncompatibleSoftware",
11: "EDenyReason_SteamConnectionLost",
12: "EDenyReason_SteamConnectionError",
13: "EDenyReason_SteamResponseTimedOut",
14: "EDenyReason_SteamValidationStalled",
15: "EDenyReason_SteamOwnerLeftGuestUser",
}
func (e EDenyReason) String() string {
if s, ok := EDenyReason_name[e]; ok {
return s
}
var flags []string
for k, v := range EDenyReason_name {
if e&k != 0 {
flags = append(flags, v)
}
}
if len(flags) == 0 {
return fmt.Sprintf("%d", e)
}
sort.Strings(flags)
return strings.Join(flags, " | ")
}
type EClanRank int32
const (
EClanRank_None EClanRank = 0
EClanRank_Owner EClanRank = 1
EClanRank_Officer EClanRank = 2
EClanRank_Member EClanRank = 3
EClanRank_Moderator EClanRank = 4
)
var EClanRank_name = map[EClanRank]string{
0: "EClanRank_None",
1: "EClanRank_Owner",
2: "EClanRank_Officer",
3: "EClanRank_Member",
4: "EClanRank_Moderator",
}
func (e EClanRank) String() string {
if s, ok := EClanRank_name[e]; ok {
return s
}
var flags []string
for k, v := range EClanRank_name {
if e&k != 0 {
flags = append(flags, v)
}
}
if len(flags) == 0 {
return fmt.Sprintf("%d", e)
}
sort.Strings(flags)
return strings.Join(flags, " | ")
}
type EClanRelationship int32
const (
EClanRelationship_None EClanRelationship = 0
EClanRelationship_Blocked EClanRelationship = 1
EClanRelationship_Invited EClanRelationship = 2
EClanRelationship_Member EClanRelationship = 3
EClanRelationship_Kicked EClanRelationship = 4
EClanRelationship_KickAcknowledged EClanRelationship = 5
)
var EClanRelationship_name = map[EClanRelationship]string{
0: "EClanRelationship_None",
1: "EClanRelationship_Blocked",
2: "EClanRelationship_Invited",
3: "EClanRelationship_Member",
4: "EClanRelationship_Kicked",
5: "EClanRelationship_KickAcknowledged",
}
func (e EClanRelationship) String() string {
if s, ok := EClanRelationship_name[e]; ok {
return s
}
var flags []string
for k, v := range EClanRelationship_name {
if e&k != 0 {
flags = append(flags, v)
}
}
if len(flags) == 0 {
return fmt.Sprintf("%d", e)
}
sort.Strings(flags)
return strings.Join(flags, " | ")
}
type EAuthSessionResponse int32
const (
EAuthSessionResponse_OK EAuthSessionResponse = 0
EAuthSessionResponse_UserNotConnectedToSteam EAuthSessionResponse = 1
EAuthSessionResponse_NoLicenseOrExpired EAuthSessionResponse = 2
EAuthSessionResponse_VACBanned EAuthSessionResponse = 3
EAuthSessionResponse_LoggedInElseWhere EAuthSessionResponse = 4
EAuthSessionResponse_VACCheckTimedOut EAuthSessionResponse = 5
EAuthSessionResponse_AuthTicketCanceled EAuthSessionResponse = 6
EAuthSessionResponse_AuthTicketInvalidAlreadyUsed EAuthSessionResponse = 7
EAuthSessionResponse_AuthTicketInvalid EAuthSessionResponse = 8
EAuthSessionResponse_PublisherIssuedBan EAuthSessionResponse = 9
)
var EAuthSessionResponse_name = map[EAuthSessionResponse]string{
0: "EAuthSessionResponse_OK",
1: "EAuthSessionResponse_UserNotConnectedToSteam",
2: "EAuthSessionResponse_NoLicenseOrExpired",
3: "EAuthSessionResponse_VACBanned",
4: "EAuthSessionResponse_LoggedInElseWhere",
5: "EAuthSessionResponse_VACCheckTimedOut",
6: "EAuthSessionResponse_AuthTicketCanceled",
7: "EAuthSessionResponse_AuthTicketInvalidAlreadyUsed",
8: "EAuthSessionResponse_AuthTicketInvalid",
9: "EAuthSessionResponse_PublisherIssuedBan",
}
func (e EAuthSessionResponse) String() string {
if s, ok := EAuthSessionResponse_name[e]; ok {
return s
}
var flags []string
for k, v := range EAuthSessionResponse_name {
if e&k != 0 {
flags = append(flags, v)
}
}
if len(flags) == 0 {
return fmt.Sprintf("%d", e)
}
sort.Strings(flags)
return strings.Join(flags, " | ")
}
type EChatRoomEnterResponse int32
const (
EChatRoomEnterResponse_Success EChatRoomEnterResponse = 1
EChatRoomEnterResponse_DoesntExist EChatRoomEnterResponse = 2
EChatRoomEnterResponse_NotAllowed EChatRoomEnterResponse = 3
EChatRoomEnterResponse_Full EChatRoomEnterResponse = 4
EChatRoomEnterResponse_Error EChatRoomEnterResponse = 5
EChatRoomEnterResponse_Banned EChatRoomEnterResponse = 6
EChatRoomEnterResponse_Limited EChatRoomEnterResponse = 7
EChatRoomEnterResponse_ClanDisabled EChatRoomEnterResponse = 8
EChatRoomEnterResponse_CommunityBan EChatRoomEnterResponse = 9
EChatRoomEnterResponse_MemberBlockedYou EChatRoomEnterResponse = 10
EChatRoomEnterResponse_YouBlockedMember EChatRoomEnterResponse = 11
EChatRoomEnterResponse_NoRankingDataLobby EChatRoomEnterResponse = 12 // Deprecated
EChatRoomEnterResponse_NoRankingDataUser EChatRoomEnterResponse = 13 // Deprecated
EChatRoomEnterResponse_RankOutOfRange EChatRoomEnterResponse = 14 // Deprecated
)
var EChatRoomEnterResponse_name = map[EChatRoomEnterResponse]string{
1: "EChatRoomEnterResponse_Success",
2: "EChatRoomEnterResponse_DoesntExist",
3: "EChatRoomEnterResponse_NotAllowed",
4: "EChatRoomEnterResponse_Full",
5: "EChatRoomEnterResponse_Error",
6: "EChatRoomEnterResponse_Banned",
7: "EChatRoomEnterResponse_Limited",
8: "EChatRoomEnterResponse_ClanDisabled",
9: "EChatRoomEnterResponse_CommunityBan",
10: "EChatRoomEnterResponse_MemberBlockedYou",
11: "EChatRoomEnterResponse_YouBlockedMember",
12: "EChatRoomEnterResponse_NoRankingDataLobby",
13: "EChatRoomEnterResponse_NoRankingDataUser",
14: "EChatRoomEnterResponse_RankOutOfRange",
}
func (e EChatRoomEnterResponse) String() string {
if s, ok := EChatRoomEnterResponse_name[e]; ok {
return s
}
var flags []string
for k, v := range EChatRoomEnterResponse_name {
if e&k != 0 {
flags = append(flags, v)
}
}
if len(flags) == 0 {
return fmt.Sprintf("%d", e)
}
sort.Strings(flags)
return strings.Join(flags, " | ")
}
type EChatRoomType int32
const (
EChatRoomType_Friend EChatRoomType = 1
EChatRoomType_MUC EChatRoomType = 2
EChatRoomType_Lobby EChatRoomType = 3
)
var EChatRoomType_name = map[EChatRoomType]string{
1: "EChatRoomType_Friend",
2: "EChatRoomType_MUC",
3: "EChatRoomType_Lobby",
}
func (e EChatRoomType) String() string {
if s, ok := EChatRoomType_name[e]; ok {
return s
}
var flags []string
for k, v := range EChatRoomType_name {
if e&k != 0 {
flags = append(flags, v)
}
}
if len(flags) == 0 {
return fmt.Sprintf("%d", e)
}
sort.Strings(flags)
return strings.Join(flags, " | ")
}
type EChatInfoType int32
const (
EChatInfoType_StateChange EChatInfoType = 1
EChatInfoType_InfoUpdate EChatInfoType = 2
EChatInfoType_MemberLimitChange EChatInfoType = 3
)
var EChatInfoType_name = map[EChatInfoType]string{
1: "EChatInfoType_StateChange",
2: "EChatInfoType_InfoUpdate",
3: "EChatInfoType_MemberLimitChange",
}
func (e EChatInfoType) String() string {
if s, ok := EChatInfoType_name[e]; ok {
return s
}
var flags []string
for k, v := range EChatInfoType_name {
if e&k != 0 {
flags = append(flags, v)
}
}
if len(flags) == 0 {
return fmt.Sprintf("%d", e)
}
sort.Strings(flags)
return strings.Join(flags, " | ")
}
type EChatAction int32
const (
EChatAction_InviteChat EChatAction = 1
EChatAction_Kick EChatAction = 2
EChatAction_Ban EChatAction = 3
EChatAction_UnBan EChatAction = 4
EChatAction_StartVoiceSpeak EChatAction = 5
EChatAction_EndVoiceSpeak EChatAction = 6
EChatAction_LockChat EChatAction = 7
EChatAction_UnlockChat EChatAction = 8
EChatAction_CloseChat EChatAction = 9
EChatAction_SetJoinable EChatAction = 10
EChatAction_SetUnjoinable EChatAction = 11
EChatAction_SetOwner EChatAction = 12
EChatAction_SetInvisibleToFriends EChatAction = 13
EChatAction_SetVisibleToFriends EChatAction = 14
EChatAction_SetModerated EChatAction = 15
EChatAction_SetUnmoderated EChatAction = 16
)
var EChatAction_name = map[EChatAction]string{
1: "EChatAction_InviteChat",
2: "EChatAction_Kick",
3: "EChatAction_Ban",
4: "EChatAction_UnBan",
5: "EChatAction_StartVoiceSpeak",
6: "EChatAction_EndVoiceSpeak",
7: "EChatAction_LockChat",
8: "EChatAction_UnlockChat",
9: "EChatAction_CloseChat",
10: "EChatAction_SetJoinable",
11: "EChatAction_SetUnjoinable",
12: "EChatAction_SetOwner",
13: "EChatAction_SetInvisibleToFriends",
14: "EChatAction_SetVisibleToFriends",
15: "EChatAction_SetModerated",
16: "EChatAction_SetUnmoderated",
}
func (e EChatAction) String() string {
if s, ok := EChatAction_name[e]; ok {
return s
}
var flags []string
for k, v := range EChatAction_name {
if e&k != 0 {
flags = append(flags, v)
}
}
if len(flags) == 0 {
return fmt.Sprintf("%d", e)
}
sort.Strings(flags)
return strings.Join(flags, " | ")
}
type EChatActionResult int32
const (
EChatActionResult_Success EChatActionResult = 1
EChatActionResult_Error EChatActionResult = 2
EChatActionResult_NotPermitted EChatActionResult = 3
EChatActionResult_NotAllowedOnClanMember EChatActionResult = 4
EChatActionResult_NotAllowedOnBannedUser EChatActionResult = 5
EChatActionResult_NotAllowedOnChatOwner EChatActionResult = 6
EChatActionResult_NotAllowedOnSelf EChatActionResult = 7
EChatActionResult_ChatDoesntExist EChatActionResult = 8
EChatActionResult_ChatFull EChatActionResult = 9
EChatActionResult_VoiceSlotsFull EChatActionResult = 10
)
var EChatActionResult_name = map[EChatActionResult]string{
1: "EChatActionResult_Success",
2: "EChatActionResult_Error",
3: "EChatActionResult_NotPermitted",
4: "EChatActionResult_NotAllowedOnClanMember",
5: "EChatActionResult_NotAllowedOnBannedUser",
6: "EChatActionResult_NotAllowedOnChatOwner",
7: "EChatActionResult_NotAllowedOnSelf",
8: "EChatActionResult_ChatDoesntExist",
9: "EChatActionResult_ChatFull",
10: "EChatActionResult_VoiceSlotsFull",
}
func (e EChatActionResult) String() string {
if s, ok := EChatActionResult_name[e]; ok {
return s
}
var flags []string
for k, v := range EChatActionResult_name {
if e&k != 0 {
flags = append(flags, v)
}
}
if len(flags) == 0 {
return fmt.Sprintf("%d", e)
}
sort.Strings(flags)
return strings.Join(flags, " | ")
}
type EAppInfoSection int32
const (
EAppInfoSection_Unknown EAppInfoSection = 0
EAppInfoSection_All EAppInfoSection = 1
EAppInfoSection_First EAppInfoSection = 2
EAppInfoSection_Common EAppInfoSection = 2
EAppInfoSection_Extended EAppInfoSection = 3
EAppInfoSection_Config EAppInfoSection = 4
EAppInfoSection_Stats EAppInfoSection = 5
EAppInfoSection_Install EAppInfoSection = 6
EAppInfoSection_Depots EAppInfoSection = 7
EAppInfoSection_VAC EAppInfoSection = 8
EAppInfoSection_DRM EAppInfoSection = 9
EAppInfoSection_UFS EAppInfoSection = 10
EAppInfoSection_OGG EAppInfoSection = 11
EAppInfoSection_Items EAppInfoSection = 12 // Deprecated
EAppInfoSection_ItemsUNUSED EAppInfoSection = 12 // Deprecated
EAppInfoSection_Policies EAppInfoSection = 13
EAppInfoSection_SysReqs EAppInfoSection = 14
EAppInfoSection_Community EAppInfoSection = 15
EAppInfoSection_Store EAppInfoSection = 16
EAppInfoSection_Max EAppInfoSection = 17
)
var EAppInfoSection_name = map[EAppInfoSection]string{
0: "EAppInfoSection_Unknown",
1: "EAppInfoSection_All",
2: "EAppInfoSection_First",
3: "EAppInfoSection_Extended",
4: "EAppInfoSection_Config",
5: "EAppInfoSection_Stats",
6: "EAppInfoSection_Install",
7: "EAppInfoSection_Depots",
8: "EAppInfoSection_VAC",
9: "EAppInfoSection_DRM",
10: "EAppInfoSection_UFS",
11: "EAppInfoSection_OGG",
12: "EAppInfoSection_Items",
13: "EAppInfoSection_Policies",
14: "EAppInfoSection_SysReqs",
15: "EAppInfoSection_Community",
16: "EAppInfoSection_Store",
17: "EAppInfoSection_Max",
}
func (e EAppInfoSection) String() string {
if s, ok := EAppInfoSection_name[e]; ok {
return s
}
var flags []string
for k, v := range EAppInfoSection_name {
if e&k != 0 {
flags = append(flags, v)
}
}
if len(flags) == 0 {
return fmt.Sprintf("%d", e)
}
sort.Strings(flags)
return strings.Join(flags, " | ")
}
type EContentDownloadSourceType int32
const (
EContentDownloadSourceType_Invalid EContentDownloadSourceType = 0
EContentDownloadSourceType_CS EContentDownloadSourceType = 1
EContentDownloadSourceType_CDN EContentDownloadSourceType = 2
EContentDownloadSourceType_LCS EContentDownloadSourceType = 3
EContentDownloadSourceType_ProxyCache EContentDownloadSourceType = 4
EContentDownloadSourceType_Max EContentDownloadSourceType = 5
)
var EContentDownloadSourceType_name = map[EContentDownloadSourceType]string{
0: "EContentDownloadSourceType_Invalid",
1: "EContentDownloadSourceType_CS",
2: "EContentDownloadSourceType_CDN",
3: "EContentDownloadSourceType_LCS",
4: "EContentDownloadSourceType_ProxyCache",
5: "EContentDownloadSourceType_Max",
}
func (e EContentDownloadSourceType) String() string {
if s, ok := EContentDownloadSourceType_name[e]; ok {
return s
}
var flags []string
for k, v := range EContentDownloadSourceType_name {
if e&k != 0 {
flags = append(flags, v)
}
}
if len(flags) == 0 {
return fmt.Sprintf("%d", e)
}
sort.Strings(flags)
return strings.Join(flags, " | ")
}
type EPlatformType int32
const (
EPlatformType_Unknown EPlatformType = 0
EPlatformType_Win32 EPlatformType = 1
EPlatformType_Win64 EPlatformType = 2
EPlatformType_Linux EPlatformType = 3
EPlatformType_OSX EPlatformType = 4
EPlatformType_PS3 EPlatformType = 5
EPlatformType_Max EPlatformType = 6
)
var EPlatformType_name = map[EPlatformType]string{
0: "EPlatformType_Unknown",
1: "EPlatformType_Win32",
2: "EPlatformType_Win64",
3: "EPlatformType_Linux",
4: "EPlatformType_OSX",
5: "EPlatformType_PS3",
6: "EPlatformType_Max",
}
func (e EPlatformType) String() string {
if s, ok := EPlatformType_name[e]; ok {
return s
}
var flags []string
for k, v := range EPlatformType_name {
if e&k != 0 {
flags = append(flags, v)
}
}
if len(flags) == 0 {
return fmt.Sprintf("%d", e)
}
sort.Strings(flags)
return strings.Join(flags, " | ")
}
type EOSType int32
const (
EOSType_Unknown EOSType = -1
EOSType_UMQ EOSType = -400
EOSType_PS3 EOSType = -300
EOSType_MacOSUnknown EOSType = -102
EOSType_MacOS104 EOSType = -101
EOSType_MacOS105 EOSType = -100
EOSType_MacOS1058 EOSType = -99
EOSType_MacOS106 EOSType = -95
EOSType_MacOS1063 EOSType = -94
EOSType_MacOS1064_slgu EOSType = -93
EOSType_MacOS1067 EOSType = -92
EOSType_MacOS107 EOSType = -90
EOSType_MacOS108 EOSType = -89
EOSType_MacOS109 EOSType = -88
EOSType_MacOS1010 EOSType = -87
EOSType_LinuxUnknown EOSType = -203
EOSType_Linux22 EOSType = -202
EOSType_Linux24 EOSType = -201
EOSType_Linux26 EOSType = -200
EOSType_Linux32 EOSType = -199
EOSType_Linux35 EOSType = -198
EOSType_Linux36 EOSType = -197
EOSType_Linux310 EOSType = -196
EOSType_WinUnknown EOSType = 0
EOSType_Win311 EOSType = 1
EOSType_Win95 EOSType = 2
EOSType_Win98 EOSType = 3
EOSType_WinME EOSType = 4
EOSType_WinNT EOSType = 5
EOSType_Win200 EOSType = 6
EOSType_WinXP EOSType = 7
EOSType_Win2003 EOSType = 8
EOSType_WinVista EOSType = 9
EOSType_Win7 EOSType = 10
EOSType_Windows7 EOSType = 10 // Deprecated: renamed to Win7
EOSType_Win2008 EOSType = 11
EOSType_Win2012 EOSType = 12
EOSType_Win8 EOSType = 13
EOSType_Windows8 EOSType = 13 // Deprecated: renamed to Win8
EOSType_Win81 EOSType = 14
EOSType_Windows81 EOSType = 14 // Deprecated: renamed to Win81
EOSType_Win2012R2 EOSType = 15
EOSType_Win10 EOSType = 16
EOSType_WinMAX EOSType = 15
EOSType_Max EOSType = 26
)
var EOSType_name = map[EOSType]string{
-1: "EOSType_Unknown",
-400: "EOSType_UMQ",
-300: "EOSType_PS3",
-102: "EOSType_MacOSUnknown",
-101: "EOSType_MacOS104",
-100: "EOSType_MacOS105",
-99: "EOSType_MacOS1058",
-95: "EOSType_MacOS106",
-94: "EOSType_MacOS1063",
-93: "EOSType_MacOS1064_slgu",
-92: "EOSType_MacOS1067",
-90: "EOSType_MacOS107",
-89: "EOSType_MacOS108",
-88: "EOSType_MacOS109",
-87: "EOSType_MacOS1010",
-203: "EOSType_LinuxUnknown",
-202: "EOSType_Linux22",
-201: "EOSType_Linux24",
-200: "EOSType_Linux26",
-199: "EOSType_Linux32",
-198: "EOSType_Linux35",
-197: "EOSType_Linux36",
-196: "EOSType_Linux310",
0: "EOSType_WinUnknown",
1: "EOSType_Win311",
2: "EOSType_Win95",
3: "EOSType_Win98",
4: "EOSType_WinME",
5: "EOSType_WinNT",
6: "EOSType_Win200",
7: "EOSType_WinXP",
8: "EOSType_Win2003",
9: "EOSType_WinVista",
10: "EOSType_Win7",
11: "EOSType_Win2008",
12: "EOSType_Win2012",
13: "EOSType_Win8",
14: "EOSType_Win81",
15: "EOSType_Win2012R2",
16: "EOSType_Win10",
26: "EOSType_Max",
}
func (e EOSType) String() string {
if s, ok := EOSType_name[e]; ok {
return s
}
var flags []string
for k, v := range EOSType_name {
if e&k != 0 {
flags = append(flags, v)
}
}
if len(flags) == 0 {
return fmt.Sprintf("%d", e)
}
sort.Strings(flags)
return strings.Join(flags, " | ")
}
type EServerType int32
const (
EServerType_Invalid EServerType = -1
EServerType_First EServerType = 0
EServerType_Shell EServerType = 0
EServerType_GM EServerType = 1
EServerType_BUM EServerType = 2
EServerType_AM EServerType = 3
EServerType_BS EServerType = 4
EServerType_VS EServerType = 5
EServerType_ATS EServerType = 6
EServerType_CM EServerType = 7
EServerType_FBS EServerType = 8
EServerType_FG EServerType = 9 // Deprecated: renamed to BoxMonitor
EServerType_BoxMonitor EServerType = 9
EServerType_SS EServerType = 10
EServerType_DRMS EServerType = 11
EServerType_HubOBSOLETE EServerType = 12 // Deprecated
EServerType_Console EServerType = 13
EServerType_ASBOBSOLETE EServerType = 14 // Deprecated
EServerType_PICS EServerType = 14
EServerType_Client EServerType = 15
EServerType_BootstrapOBSOLETE EServerType = 16 // Deprecated
EServerType_DP EServerType = 17
EServerType_WG EServerType = 18
EServerType_SM EServerType = 19
EServerType_UFS EServerType = 21
EServerType_Util EServerType = 23
EServerType_DSS EServerType = 24 // Deprecated: renamed to Community
EServerType_Community EServerType = 24
EServerType_P2PRelayOBSOLETE EServerType = 25 // Deprecated
EServerType_AppInformation EServerType = 26
EServerType_Spare EServerType = 27
EServerType_FTS EServerType = 28
EServerType_EPM EServerType = 29
EServerType_PS EServerType = 30
EServerType_IS EServerType = 31
EServerType_CCS EServerType = 32
EServerType_DFS EServerType = 33
EServerType_LBS EServerType = 34
EServerType_MDS EServerType = 35
EServerType_CS EServerType = 36
EServerType_GC EServerType = 37
EServerType_NS EServerType = 38
EServerType_OGS EServerType = 39
EServerType_WebAPI EServerType = 40
EServerType_UDS EServerType = 41
EServerType_MMS EServerType = 42
EServerType_GMS EServerType = 43
EServerType_KGS EServerType = 44
EServerType_UCM EServerType = 45
EServerType_RM EServerType = 46
EServerType_FS EServerType = 47
EServerType_Econ EServerType = 48
EServerType_Backpack EServerType = 49
EServerType_UGS EServerType = 50
EServerType_Store EServerType = 51
EServerType_MoneyStats EServerType = 52
EServerType_CRE EServerType = 53
EServerType_UMQ EServerType = 54
EServerType_Workshop EServerType = 55
EServerType_BRP EServerType = 56
EServerType_GCH EServerType = 57
EServerType_MPAS EServerType = 58
EServerType_Trade EServerType = 59
EServerType_Secrets EServerType = 60
EServerType_Logsink EServerType = 61
EServerType_Market EServerType = 62
EServerType_Quest EServerType = 63
EServerType_WDS EServerType = 64
EServerType_ACS EServerType = 65
EServerType_PNP EServerType = 66
EServerType_Max EServerType = 67
)
var EServerType_name = map[EServerType]string{
-1: "EServerType_Invalid",
0: "EServerType_First",
1: "EServerType_GM",
2: "EServerType_BUM",
3: "EServerType_AM",
4: "EServerType_BS",
5: "EServerType_VS",
6: "EServerType_ATS",
7: "EServerType_CM",
8: "EServerType_FBS",
9: "EServerType_FG",
10: "EServerType_SS",
11: "EServerType_DRMS",
12: "EServerType_HubOBSOLETE",
13: "EServerType_Console",
14: "EServerType_ASBOBSOLETE",
15: "EServerType_Client",
16: "EServerType_BootstrapOBSOLETE",
17: "EServerType_DP",
18: "EServerType_WG",
19: "EServerType_SM",
21: "EServerType_UFS",
23: "EServerType_Util",
24: "EServerType_DSS",
25: "EServerType_P2PRelayOBSOLETE",
26: "EServerType_AppInformation",
27: "EServerType_Spare",
28: "EServerType_FTS",
29: "EServerType_EPM",
30: "EServerType_PS",
31: "EServerType_IS",
32: "EServerType_CCS",
33: "EServerType_DFS",
34: "EServerType_LBS",
35: "EServerType_MDS",
36: "EServerType_CS",
37: "EServerType_GC",
38: "EServerType_NS",
39: "EServerType_OGS",
40: "EServerType_WebAPI",
41: "EServerType_UDS",
42: "EServerType_MMS",
43: "EServerType_GMS",
44: "EServerType_KGS",
45: "EServerType_UCM",
46: "EServerType_RM",
47: "EServerType_FS",
48: "EServerType_Econ",
49: "EServerType_Backpack",
50: "EServerType_UGS",
51: "EServerType_Store",
52: "EServerType_MoneyStats",
53: "EServerType_CRE",
54: "EServerType_UMQ",
55: "EServerType_Workshop",
56: "EServerType_BRP",
57: "EServerType_GCH",
58: "EServerType_MPAS",
59: "EServerType_Trade",
60: "EServerType_Secrets",
61: "EServerType_Logsink",
62: "EServerType_Market",
63: "EServerType_Quest",
64: "EServerType_WDS",
65: "EServerType_ACS",
66: "EServerType_PNP",
67: "EServerType_Max",
}
func (e EServerType) String() string {
if s, ok := EServerType_name[e]; ok {
return s
}
var flags []string
for k, v := range EServerType_name {
if e&k != 0 {
flags = append(flags, v)
}
}
if len(flags) == 0 {
return fmt.Sprintf("%d", e)
}
sort.Strings(flags)
return strings.Join(flags, " | ")
}
type EBillingType int32
const (
EBillingType_NoCost EBillingType = 0
EBillingType_BillOnceOnly EBillingType = 1
EBillingType_BillMonthly EBillingType = 2
EBillingType_ProofOfPrepurchaseOnly EBillingType = 3
EBillingType_GuestPass EBillingType = 4
EBillingType_HardwarePromo EBillingType = 5
EBillingType_Gift EBillingType = 6
EBillingType_AutoGrant EBillingType = 7
EBillingType_OEMTicket EBillingType = 8
EBillingType_RecurringOption EBillingType = 9
EBillingType_NumBillingTypes EBillingType = 10
)
var EBillingType_name = map[EBillingType]string{
0: "EBillingType_NoCost",
1: "EBillingType_BillOnceOnly",
2: "EBillingType_BillMonthly",
3: "EBillingType_ProofOfPrepurchaseOnly",
4: "EBillingType_GuestPass",
5: "EBillingType_HardwarePromo",
6: "EBillingType_Gift",
7: "EBillingType_AutoGrant",
8: "EBillingType_OEMTicket",
9: "EBillingType_RecurringOption",
10: "EBillingType_NumBillingTypes",
}
func (e EBillingType) String() string {
if s, ok := EBillingType_name[e]; ok {
return s
}
var flags []string
for k, v := range EBillingType_name {
if e&k != 0 {
flags = append(flags, v)
}
}
if len(flags) == 0 {
return fmt.Sprintf("%d", e)
}
sort.Strings(flags)
return strings.Join(flags, " | ")
}
type EActivationCodeClass uint32
const (
EActivationCodeClass_WonCDKey EActivationCodeClass = 0
EActivationCodeClass_ValveCDKey EActivationCodeClass = 1
EActivationCodeClass_Doom3CDKey EActivationCodeClass = 2
EActivationCodeClass_DBLookup EActivationCodeClass = 3
EActivationCodeClass_Steam2010Key EActivationCodeClass = 4
EActivationCodeClass_Max EActivationCodeClass = 5
EActivationCodeClass_Test EActivationCodeClass = 2147483647
EActivationCodeClass_Invalid EActivationCodeClass = 4294967295
)
var EActivationCodeClass_name = map[EActivationCodeClass]string{
0: "EActivationCodeClass_WonCDKey",
1: "EActivationCodeClass_ValveCDKey",
2: "EActivationCodeClass_Doom3CDKey",
3: "EActivationCodeClass_DBLookup",
4: "EActivationCodeClass_Steam2010Key",
5: "EActivationCodeClass_Max",
2147483647: "EActivationCodeClass_Test",
4294967295: "EActivationCodeClass_Invalid",
}
func (e EActivationCodeClass) String() string {
if s, ok := EActivationCodeClass_name[e]; ok {
return s
}
var flags []string
for k, v := range EActivationCodeClass_name {
if e&k != 0 {
flags = append(flags, v)
}
}
if len(flags) == 0 {
return fmt.Sprintf("%d", e)
}
sort.Strings(flags)
return strings.Join(flags, " | ")
}
type EChatMemberStateChange int32
const (
EChatMemberStateChange_Entered EChatMemberStateChange = 0x01
EChatMemberStateChange_Left EChatMemberStateChange = 0x02
EChatMemberStateChange_Disconnected EChatMemberStateChange = 0x04
EChatMemberStateChange_Kicked EChatMemberStateChange = 0x08
EChatMemberStateChange_Banned EChatMemberStateChange = 0x10
EChatMemberStateChange_VoiceSpeaking EChatMemberStateChange = 0x1000
EChatMemberStateChange_VoiceDoneSpeaking EChatMemberStateChange = 0x2000
)
var EChatMemberStateChange_name = map[EChatMemberStateChange]string{
1: "EChatMemberStateChange_Entered",
2: "EChatMemberStateChange_Left",
4: "EChatMemberStateChange_Disconnected",
8: "EChatMemberStateChange_Kicked",
16: "EChatMemberStateChange_Banned",
4096: "EChatMemberStateChange_VoiceSpeaking",
8192: "EChatMemberStateChange_VoiceDoneSpeaking",
}
func (e EChatMemberStateChange) String() string {
if s, ok := EChatMemberStateChange_name[e]; ok {
return s
}
var flags []string
for k, v := range EChatMemberStateChange_name {
if e&k != 0 {
flags = append(flags, v)
}
}
if len(flags) == 0 {
return fmt.Sprintf("%d", e)
}
sort.Strings(flags)
return strings.Join(flags, " | ")
}
type ERegionCode uint8
const (
ERegionCode_USEast ERegionCode = 0x00
ERegionCode_USWest ERegionCode = 0x01
ERegionCode_SouthAmerica ERegionCode = 0x02
ERegionCode_Europe ERegionCode = 0x03
ERegionCode_Asia ERegionCode = 0x04
ERegionCode_Australia ERegionCode = 0x05
ERegionCode_MiddleEast ERegionCode = 0x06
ERegionCode_Africa ERegionCode = 0x07
ERegionCode_World ERegionCode = 0xFF
)
var ERegionCode_name = map[ERegionCode]string{
0: "ERegionCode_USEast",
1: "ERegionCode_USWest",
2: "ERegionCode_SouthAmerica",
3: "ERegionCode_Europe",
4: "ERegionCode_Asia",
5: "ERegionCode_Australia",
6: "ERegionCode_MiddleEast",
7: "ERegionCode_Africa",
255: "ERegionCode_World",
}
func (e ERegionCode) String() string {
if s, ok := ERegionCode_name[e]; ok {
return s
}
var flags []string
for k, v := range ERegionCode_name {
if e&k != 0 {
flags = append(flags, v)
}
}
if len(flags) == 0 {
return fmt.Sprintf("%d", e)
}
sort.Strings(flags)
return strings.Join(flags, " | ")
}
type ECurrencyCode int32
const (
ECurrencyCode_Invalid ECurrencyCode = 0
ECurrencyCode_USD ECurrencyCode = 1
ECurrencyCode_GBP ECurrencyCode = 2
ECurrencyCode_EUR ECurrencyCode = 3
ECurrencyCode_CHF ECurrencyCode = 4
ECurrencyCode_RUB ECurrencyCode = 5
ECurrencyCode_PLN ECurrencyCode = 6
ECurrencyCode_BRL ECurrencyCode = 7
ECurrencyCode_JPY ECurrencyCode = 8
ECurrencyCode_NOK ECurrencyCode = 9
ECurrencyCode_IDR ECurrencyCode = 10
ECurrencyCode_MYR ECurrencyCode = 11
ECurrencyCode_PHP ECurrencyCode = 12
ECurrencyCode_SGD ECurrencyCode = 13
ECurrencyCode_THB ECurrencyCode = 14
ECurrencyCode_VND ECurrencyCode = 15
ECurrencyCode_KRW ECurrencyCode = 16
ECurrencyCode_TRY ECurrencyCode = 17
ECurrencyCode_UAH ECurrencyCode = 18
ECurrencyCode_MXN ECurrencyCode = 19
ECurrencyCode_CAD ECurrencyCode = 20
ECurrencyCode_AUD ECurrencyCode = 21
ECurrencyCode_NZD ECurrencyCode = 22
ECurrencyCode_CNY ECurrencyCode = 23
ECurrencyCode_INR ECurrencyCode = 24
ECurrencyCode_CLP ECurrencyCode = 25
ECurrencyCode_PEN ECurrencyCode = 26
ECurrencyCode_COP ECurrencyCode = 27
ECurrencyCode_ZAR ECurrencyCode = 28
ECurrencyCode_HKD ECurrencyCode = 29
ECurrencyCode_TWD ECurrencyCode = 30
ECurrencyCode_SAR ECurrencyCode = 31
ECurrencyCode_AED ECurrencyCode = 32
ECurrencyCode_Max ECurrencyCode = 33
)
var ECurrencyCode_name = map[ECurrencyCode]string{
0: "ECurrencyCode_Invalid",
1: "ECurrencyCode_USD",
2: "ECurrencyCode_GBP",
3: "ECurrencyCode_EUR",
4: "ECurrencyCode_CHF",
5: "ECurrencyCode_RUB",
6: "ECurrencyCode_PLN",
7: "ECurrencyCode_BRL",
8: "ECurrencyCode_JPY",
9: "ECurrencyCode_NOK",
10: "ECurrencyCode_IDR",
11: "ECurrencyCode_MYR",
12: "ECurrencyCode_PHP",
13: "ECurrencyCode_SGD",
14: "ECurrencyCode_THB",
15: "ECurrencyCode_VND",
16: "ECurrencyCode_KRW",
17: "ECurrencyCode_TRY",
18: "ECurrencyCode_UAH",
19: "ECurrencyCode_MXN",
20: "ECurrencyCode_CAD",
21: "ECurrencyCode_AUD",
22: "ECurrencyCode_NZD",
23: "ECurrencyCode_CNY",
24: "ECurrencyCode_INR",
25: "ECurrencyCode_CLP",
26: "ECurrencyCode_PEN",
27: "ECurrencyCode_COP",
28: "ECurrencyCode_ZAR",
29: "ECurrencyCode_HKD",
30: "ECurrencyCode_TWD",
31: "ECurrencyCode_SAR",
32: "ECurrencyCode_AED",
33: "ECurrencyCode_Max",
}
func (e ECurrencyCode) String() string {
if s, ok := ECurrencyCode_name[e]; ok {
return s
}
var flags []string
for k, v := range ECurrencyCode_name {
if e&k != 0 {
flags = append(flags, v)
}
}
if len(flags) == 0 {
return fmt.Sprintf("%d", e)
}
sort.Strings(flags)
return strings.Join(flags, " | ")
}
type EDepotFileFlag int32
const (
EDepotFileFlag_UserConfig EDepotFileFlag = 1
EDepotFileFlag_VersionedUserConfig EDepotFileFlag = 2
EDepotFileFlag_Encrypted EDepotFileFlag = 4
EDepotFileFlag_ReadOnly EDepotFileFlag = 8
EDepotFileFlag_Hidden EDepotFileFlag = 16
EDepotFileFlag_Executable EDepotFileFlag = 32
EDepotFileFlag_Directory EDepotFileFlag = 64
EDepotFileFlag_CustomExecutable EDepotFileFlag = 128
EDepotFileFlag_InstallScript EDepotFileFlag = 256
)
var EDepotFileFlag_name = map[EDepotFileFlag]string{
1: "EDepotFileFlag_UserConfig",
2: "EDepotFileFlag_VersionedUserConfig",
4: "EDepotFileFlag_Encrypted",
8: "EDepotFileFlag_ReadOnly",
16: "EDepotFileFlag_Hidden",
32: "EDepotFileFlag_Executable",
64: "EDepotFileFlag_Directory",
128: "EDepotFileFlag_CustomExecutable",
256: "EDepotFileFlag_InstallScript",
}
func (e EDepotFileFlag) String() string {
if s, ok := EDepotFileFlag_name[e]; ok {
return s
}
var flags []string
for k, v := range EDepotFileFlag_name {
if e&k != 0 {
flags = append(flags, v)
}
}
if len(flags) == 0 {
return fmt.Sprintf("%d", e)
}
sort.Strings(flags)
return strings.Join(flags, " | ")
}
type EWorkshopEnumerationType int32
const (
EWorkshopEnumerationType_RankedByVote EWorkshopEnumerationType = 0
EWorkshopEnumerationType_Recent EWorkshopEnumerationType = 1
EWorkshopEnumerationType_Trending EWorkshopEnumerationType = 2
EWorkshopEnumerationType_FavoriteOfFriends EWorkshopEnumerationType = 3
EWorkshopEnumerationType_VotedByFriends EWorkshopEnumerationType = 4
EWorkshopEnumerationType_ContentByFriends EWorkshopEnumerationType = 5
EWorkshopEnumerationType_RecentFromFollowedUsers EWorkshopEnumerationType = 6
)
var EWorkshopEnumerationType_name = map[EWorkshopEnumerationType]string{
0: "EWorkshopEnumerationType_RankedByVote",
1: "EWorkshopEnumerationType_Recent",
2: "EWorkshopEnumerationType_Trending",
3: "EWorkshopEnumerationType_FavoriteOfFriends",
4: "EWorkshopEnumerationType_VotedByFriends",
5: "EWorkshopEnumerationType_ContentByFriends",
6: "EWorkshopEnumerationType_RecentFromFollowedUsers",
}
func (e EWorkshopEnumerationType) String() string {
if s, ok := EWorkshopEnumerationType_name[e]; ok {
return s
}
var flags []string
for k, v := range EWorkshopEnumerationType_name {
if e&k != 0 {
flags = append(flags, v)
}
}
if len(flags) == 0 {
return fmt.Sprintf("%d", e)
}
sort.Strings(flags)
return strings.Join(flags, " | ")
}
type EPublishedFileVisibility int32
const (
EPublishedFileVisibility_Public EPublishedFileVisibility = 0
EPublishedFileVisibility_FriendsOnly EPublishedFileVisibility = 1
EPublishedFileVisibility_Private EPublishedFileVisibility = 2
)
var EPublishedFileVisibility_name = map[EPublishedFileVisibility]string{
0: "EPublishedFileVisibility_Public",
1: "EPublishedFileVisibility_FriendsOnly",
2: "EPublishedFileVisibility_Private",
}
func (e EPublishedFileVisibility) String() string {
if s, ok := EPublishedFileVisibility_name[e]; ok {
return s
}
var flags []string
for k, v := range EPublishedFileVisibility_name {
if e&k != 0 {
flags = append(flags, v)
}
}
if len(flags) == 0 {
return fmt.Sprintf("%d", e)
}
sort.Strings(flags)
return strings.Join(flags, " | ")
}
type EWorkshopFileType int32
const (
EWorkshopFileType_First EWorkshopFileType = 0
EWorkshopFileType_Community EWorkshopFileType = 0
EWorkshopFileType_Microtransaction EWorkshopFileType = 1
EWorkshopFileType_Collection EWorkshopFileType = 2
EWorkshopFileType_Art EWorkshopFileType = 3
EWorkshopFileType_Video EWorkshopFileType = 4
EWorkshopFileType_Screenshot EWorkshopFileType = 5
EWorkshopFileType_Game EWorkshopFileType = 6
EWorkshopFileType_Software EWorkshopFileType = 7
EWorkshopFileType_Concept EWorkshopFileType = 8
EWorkshopFileType_WebGuide EWorkshopFileType = 9
EWorkshopFileType_IntegratedGuide EWorkshopFileType = 10
EWorkshopFileType_Merch EWorkshopFileType = 11
EWorkshopFileType_ControllerBinding EWorkshopFileType = 12
EWorkshopFileType_SteamworksAccessInvite EWorkshopFileType = 13
EWorkshopFileType_SteamVideo EWorkshopFileType = 14
EWorkshopFileType_GameManagedItem EWorkshopFileType = 15
EWorkshopFileType_Max EWorkshopFileType = 16
)
var EWorkshopFileType_name = map[EWorkshopFileType]string{
0: "EWorkshopFileType_First",
1: "EWorkshopFileType_Microtransaction",
2: "EWorkshopFileType_Collection",
3: "EWorkshopFileType_Art",
4: "EWorkshopFileType_Video",
5: "EWorkshopFileType_Screenshot",
6: "EWorkshopFileType_Game",
7: "EWorkshopFileType_Software",
8: "EWorkshopFileType_Concept",
9: "EWorkshopFileType_WebGuide",
10: "EWorkshopFileType_IntegratedGuide",
11: "EWorkshopFileType_Merch",
12: "EWorkshopFileType_ControllerBinding",
13: "EWorkshopFileType_SteamworksAccessInvite",
14: "EWorkshopFileType_SteamVideo",
15: "EWorkshopFileType_GameManagedItem",
16: "EWorkshopFileType_Max",
}
func (e EWorkshopFileType) String() string {
if s, ok := EWorkshopFileType_name[e]; ok {
return s
}
var flags []string
for k, v := range EWorkshopFileType_name {
if e&k != 0 {
flags = append(flags, v)
}
}
if len(flags) == 0 {
return fmt.Sprintf("%d", e)
}
sort.Strings(flags)
return strings.Join(flags, " | ")
}
type EWorkshopFileAction int32
const (
EWorkshopFileAction_Played EWorkshopFileAction = 0
EWorkshopFileAction_Completed EWorkshopFileAction = 1
)
var EWorkshopFileAction_name = map[EWorkshopFileAction]string{
0: "EWorkshopFileAction_Played",
1: "EWorkshopFileAction_Completed",
}
func (e EWorkshopFileAction) String() string {
if s, ok := EWorkshopFileAction_name[e]; ok {
return s
}
var flags []string
for k, v := range EWorkshopFileAction_name {
if e&k != 0 {
flags = append(flags, v)
}
}
if len(flags) == 0 {
return fmt.Sprintf("%d", e)
}
sort.Strings(flags)
return strings.Join(flags, " | ")
}
type EEconTradeResponse int32
const (
EEconTradeResponse_Accepted EEconTradeResponse = 0
EEconTradeResponse_Declined EEconTradeResponse = 1
EEconTradeResponse_TradeBannedInitiator EEconTradeResponse = 2
EEconTradeResponse_TradeBannedTarget EEconTradeResponse = 3
EEconTradeResponse_TargetAlreadyTrading EEconTradeResponse = 4
EEconTradeResponse_Disabled EEconTradeResponse = 5
EEconTradeResponse_NotLoggedIn EEconTradeResponse = 6
EEconTradeResponse_Cancel EEconTradeResponse = 7
EEconTradeResponse_TooSoon EEconTradeResponse = 8
EEconTradeResponse_TooSoonPenalty EEconTradeResponse = 9
EEconTradeResponse_ConnectionFailed EEconTradeResponse = 10
EEconTradeResponse_AlreadyTrading EEconTradeResponse = 11
EEconTradeResponse_AlreadyHasTradeRequest EEconTradeResponse = 12
EEconTradeResponse_NoResponse EEconTradeResponse = 13
EEconTradeResponse_CyberCafeInitiator EEconTradeResponse = 14
EEconTradeResponse_CyberCafeTarget EEconTradeResponse = 15
EEconTradeResponse_SchoolLabInitiator EEconTradeResponse = 16
EEconTradeResponse_SchoolLabTarget EEconTradeResponse = 16
EEconTradeResponse_InitiatorBlockedTarget EEconTradeResponse = 18
EEconTradeResponse_InitiatorNeedsVerifiedEmail EEconTradeResponse = 20
EEconTradeResponse_InitiatorNeedsSteamGuard EEconTradeResponse = 21
EEconTradeResponse_TargetAccountCannotTrade EEconTradeResponse = 22
EEconTradeResponse_InitiatorSteamGuardDuration EEconTradeResponse = 23
EEconTradeResponse_InitiatorPasswordResetProbation EEconTradeResponse = 24
EEconTradeResponse_InitiatorNewDeviceCooldown EEconTradeResponse = 25
EEconTradeResponse_OKToDeliver EEconTradeResponse = 50
)
var EEconTradeResponse_name = map[EEconTradeResponse]string{
0: "EEconTradeResponse_Accepted",
1: "EEconTradeResponse_Declined",
2: "EEconTradeResponse_TradeBannedInitiator",
3: "EEconTradeResponse_TradeBannedTarget",
4: "EEconTradeResponse_TargetAlreadyTrading",
5: "EEconTradeResponse_Disabled",
6: "EEconTradeResponse_NotLoggedIn",
7: "EEconTradeResponse_Cancel",
8: "EEconTradeResponse_TooSoon",
9: "EEconTradeResponse_TooSoonPenalty",
10: "EEconTradeResponse_ConnectionFailed",
11: "EEconTradeResponse_AlreadyTrading",
12: "EEconTradeResponse_AlreadyHasTradeRequest",
13: "EEconTradeResponse_NoResponse",
14: "EEconTradeResponse_CyberCafeInitiator",
15: "EEconTradeResponse_CyberCafeTarget",
16: "EEconTradeResponse_SchoolLabInitiator",
18: "EEconTradeResponse_InitiatorBlockedTarget",
20: "EEconTradeResponse_InitiatorNeedsVerifiedEmail",
21: "EEconTradeResponse_InitiatorNeedsSteamGuard",
22: "EEconTradeResponse_TargetAccountCannotTrade",
23: "EEconTradeResponse_InitiatorSteamGuardDuration",
24: "EEconTradeResponse_InitiatorPasswordResetProbation",
25: "EEconTradeResponse_InitiatorNewDeviceCooldown",
50: "EEconTradeResponse_OKToDeliver",
}
func (e EEconTradeResponse) String() string {
if s, ok := EEconTradeResponse_name[e]; ok {
return s
}
var flags []string
for k, v := range EEconTradeResponse_name {
if e&k != 0 {
flags = append(flags, v)
}
}
if len(flags) == 0 {
return fmt.Sprintf("%d", e)
}
sort.Strings(flags)
return strings.Join(flags, " | ")
}
type EMarketingMessageFlags int32
const (
EMarketingMessageFlags_None EMarketingMessageFlags = 0
EMarketingMessageFlags_HighPriority EMarketingMessageFlags = 1
EMarketingMessageFlags_PlatformWindows EMarketingMessageFlags = 2
EMarketingMessageFlags_PlatformMac EMarketingMessageFlags = 4
EMarketingMessageFlags_PlatformLinux EMarketingMessageFlags = 8
EMarketingMessageFlags_PlatformRestrictions EMarketingMessageFlags = EMarketingMessageFlags_PlatformWindows | EMarketingMessageFlags_PlatformMac | EMarketingMessageFlags_PlatformLinux
)
var EMarketingMessageFlags_name = map[EMarketingMessageFlags]string{
0: "EMarketingMessageFlags_None",
1: "EMarketingMessageFlags_HighPriority",
2: "EMarketingMessageFlags_PlatformWindows",
4: "EMarketingMessageFlags_PlatformMac",
8: "EMarketingMessageFlags_PlatformLinux",
14: "EMarketingMessageFlags_PlatformRestrictions",
}
func (e EMarketingMessageFlags) String() string {
if s, ok := EMarketingMessageFlags_name[e]; ok {
return s
}
var flags []string
for k, v := range EMarketingMessageFlags_name {
if e&k != 0 {
flags = append(flags, v)
}
}
if len(flags) == 0 {
return fmt.Sprintf("%d", e)
}
sort.Strings(flags)
return strings.Join(flags, " | ")
}
type ENewsUpdateType int32
const (
ENewsUpdateType_AppNews ENewsUpdateType = 0
ENewsUpdateType_SteamAds ENewsUpdateType = 1
ENewsUpdateType_SteamNews ENewsUpdateType = 2
ENewsUpdateType_CDDBUpdate ENewsUpdateType = 3
ENewsUpdateType_ClientUpdate ENewsUpdateType = 4
)
var ENewsUpdateType_name = map[ENewsUpdateType]string{
0: "ENewsUpdateType_AppNews",
1: "ENewsUpdateType_SteamAds",
2: "ENewsUpdateType_SteamNews",
3: "ENewsUpdateType_CDDBUpdate",
4: "ENewsUpdateType_ClientUpdate",
}
func (e ENewsUpdateType) String() string {
if s, ok := ENewsUpdateType_name[e]; ok {
return s
}
var flags []string
for k, v := range ENewsUpdateType_name {
if e&k != 0 {
flags = append(flags, v)
}
}
if len(flags) == 0 {
return fmt.Sprintf("%d", e)
}
sort.Strings(flags)
return strings.Join(flags, " | ")
}
type ESystemIMType int32
const (
ESystemIMType_RawText ESystemIMType = 0
ESystemIMType_InvalidCard ESystemIMType = 1
ESystemIMType_RecurringPurchaseFailed ESystemIMType = 2
ESystemIMType_CardWillExpire ESystemIMType = 3
ESystemIMType_SubscriptionExpired ESystemIMType = 4
ESystemIMType_GuestPassReceived ESystemIMType = 5
ESystemIMType_GuestPassGranted ESystemIMType = 6
ESystemIMType_GiftRevoked ESystemIMType = 7
ESystemIMType_SupportMessage ESystemIMType = 8
ESystemIMType_SupportMessageClearAlert ESystemIMType = 9
ESystemIMType_Max ESystemIMType = 10
)
var ESystemIMType_name = map[ESystemIMType]string{
0: "ESystemIMType_RawText",
1: "ESystemIMType_InvalidCard",
2: "ESystemIMType_RecurringPurchaseFailed",
3: "ESystemIMType_CardWillExpire",
4: "ESystemIMType_SubscriptionExpired",
5: "ESystemIMType_GuestPassReceived",
6: "ESystemIMType_GuestPassGranted",
7: "ESystemIMType_GiftRevoked",
8: "ESystemIMType_SupportMessage",
9: "ESystemIMType_SupportMessageClearAlert",
10: "ESystemIMType_Max",
}
func (e ESystemIMType) String() string {
if s, ok := ESystemIMType_name[e]; ok {
return s
}
var flags []string
for k, v := range ESystemIMType_name {
if e&k != 0 {
flags = append(flags, v)
}
}
if len(flags) == 0 {
return fmt.Sprintf("%d", e)
}
sort.Strings(flags)
return strings.Join(flags, " | ")
}
type EChatFlags int32
const (
EChatFlags_Locked EChatFlags = 1
EChatFlags_InvisibleToFriends EChatFlags = 2
EChatFlags_Moderated EChatFlags = 4
EChatFlags_Unjoinable EChatFlags = 8
)
var EChatFlags_name = map[EChatFlags]string{
1: "EChatFlags_Locked",
2: "EChatFlags_InvisibleToFriends",
4: "EChatFlags_Moderated",
8: "EChatFlags_Unjoinable",
}
func (e EChatFlags) String() string {
if s, ok := EChatFlags_name[e]; ok {
return s
}
var flags []string
for k, v := range EChatFlags_name {
if e&k != 0 {
flags = append(flags, v)
}
}
if len(flags) == 0 {
return fmt.Sprintf("%d", e)
}
sort.Strings(flags)
return strings.Join(flags, " | ")
}
type ERemoteStoragePlatform int32
const (
ERemoteStoragePlatform_None ERemoteStoragePlatform = 0
ERemoteStoragePlatform_Windows ERemoteStoragePlatform = 1
ERemoteStoragePlatform_OSX ERemoteStoragePlatform = 2
ERemoteStoragePlatform_PS3 ERemoteStoragePlatform = 4
ERemoteStoragePlatform_Linux ERemoteStoragePlatform = 8
ERemoteStoragePlatform_Reserved1 ERemoteStoragePlatform = 8 // Deprecated
ERemoteStoragePlatform_Reserved2 ERemoteStoragePlatform = 16
ERemoteStoragePlatform_All ERemoteStoragePlatform = -1
)
var ERemoteStoragePlatform_name = map[ERemoteStoragePlatform]string{
0: "ERemoteStoragePlatform_None",
1: "ERemoteStoragePlatform_Windows",
2: "ERemoteStoragePlatform_OSX",
4: "ERemoteStoragePlatform_PS3",
8: "ERemoteStoragePlatform_Linux",
16: "ERemoteStoragePlatform_Reserved2",
-1: "ERemoteStoragePlatform_All",
}
func (e ERemoteStoragePlatform) String() string {
if s, ok := ERemoteStoragePlatform_name[e]; ok {
return s
}
var flags []string
for k, v := range ERemoteStoragePlatform_name {
if e&k != 0 {
flags = append(flags, v)
}
}
if len(flags) == 0 {
return fmt.Sprintf("%d", e)
}
sort.Strings(flags)
return strings.Join(flags, " | ")
}
type EDRMBlobDownloadType int32
const (
EDRMBlobDownloadType_Error EDRMBlobDownloadType = 0
EDRMBlobDownloadType_File EDRMBlobDownloadType = 1
EDRMBlobDownloadType_Parts EDRMBlobDownloadType = 2
EDRMBlobDownloadType_Compressed EDRMBlobDownloadType = 4
EDRMBlobDownloadType_AllMask EDRMBlobDownloadType = 7
EDRMBlobDownloadType_IsJob EDRMBlobDownloadType = 8
EDRMBlobDownloadType_HighPriority EDRMBlobDownloadType = 16
EDRMBlobDownloadType_AddTimestamp EDRMBlobDownloadType = 32
EDRMBlobDownloadType_LowPriority EDRMBlobDownloadType = 64
)
var EDRMBlobDownloadType_name = map[EDRMBlobDownloadType]string{
0: "EDRMBlobDownloadType_Error",
1: "EDRMBlobDownloadType_File",
2: "EDRMBlobDownloadType_Parts",
4: "EDRMBlobDownloadType_Compressed",
7: "EDRMBlobDownloadType_AllMask",
8: "EDRMBlobDownloadType_IsJob",
16: "EDRMBlobDownloadType_HighPriority",
32: "EDRMBlobDownloadType_AddTimestamp",
64: "EDRMBlobDownloadType_LowPriority",
}
func (e EDRMBlobDownloadType) String() string {
if s, ok := EDRMBlobDownloadType_name[e]; ok {
return s
}
var flags []string
for k, v := range EDRMBlobDownloadType_name {
if e&k != 0 {
flags = append(flags, v)
}
}
if len(flags) == 0 {
return fmt.Sprintf("%d", e)
}
sort.Strings(flags)
return strings.Join(flags, " | ")
}
type EDRMBlobDownloadErrorDetail int32
const (
EDRMBlobDownloadErrorDetail_None EDRMBlobDownloadErrorDetail = 0
EDRMBlobDownloadErrorDetail_DownloadFailed EDRMBlobDownloadErrorDetail = 1
EDRMBlobDownloadErrorDetail_TargetLocked EDRMBlobDownloadErrorDetail = 2
EDRMBlobDownloadErrorDetail_OpenZip EDRMBlobDownloadErrorDetail = 3
EDRMBlobDownloadErrorDetail_ReadZipDirectory EDRMBlobDownloadErrorDetail = 4
EDRMBlobDownloadErrorDetail_UnexpectedZipEntry EDRMBlobDownloadErrorDetail = 5
EDRMBlobDownloadErrorDetail_UnzipFullFile EDRMBlobDownloadErrorDetail = 6
EDRMBlobDownloadErrorDetail_UnknownBlobType EDRMBlobDownloadErrorDetail = 7
EDRMBlobDownloadErrorDetail_UnzipStrips EDRMBlobDownloadErrorDetail = 8
EDRMBlobDownloadErrorDetail_UnzipMergeGuid EDRMBlobDownloadErrorDetail = 9
EDRMBlobDownloadErrorDetail_UnzipSignature EDRMBlobDownloadErrorDetail = 10
EDRMBlobDownloadErrorDetail_ApplyStrips EDRMBlobDownloadErrorDetail = 11
EDRMBlobDownloadErrorDetail_ApplyMergeGuid EDRMBlobDownloadErrorDetail = 12
EDRMBlobDownloadErrorDetail_ApplySignature EDRMBlobDownloadErrorDetail = 13
EDRMBlobDownloadErrorDetail_AppIdMismatch EDRMBlobDownloadErrorDetail = 14
EDRMBlobDownloadErrorDetail_AppIdUnexpected EDRMBlobDownloadErrorDetail = 15
EDRMBlobDownloadErrorDetail_AppliedSignatureCorrupt EDRMBlobDownloadErrorDetail = 16
EDRMBlobDownloadErrorDetail_ApplyValveSignatureHeader EDRMBlobDownloadErrorDetail = 17
EDRMBlobDownloadErrorDetail_UnzipValveSignatureHeader EDRMBlobDownloadErrorDetail = 18
EDRMBlobDownloadErrorDetail_PathManipulationError EDRMBlobDownloadErrorDetail = 19
EDRMBlobDownloadErrorDetail_TargetLocked_Base EDRMBlobDownloadErrorDetail = 65536
EDRMBlobDownloadErrorDetail_TargetLocked_Max EDRMBlobDownloadErrorDetail = 131071
EDRMBlobDownloadErrorDetail_NextBase EDRMBlobDownloadErrorDetail = 131072
)
var EDRMBlobDownloadErrorDetail_name = map[EDRMBlobDownloadErrorDetail]string{
0: "EDRMBlobDownloadErrorDetail_None",
1: "EDRMBlobDownloadErrorDetail_DownloadFailed",
2: "EDRMBlobDownloadErrorDetail_TargetLocked",
3: "EDRMBlobDownloadErrorDetail_OpenZip",
4: "EDRMBlobDownloadErrorDetail_ReadZipDirectory",
5: "EDRMBlobDownloadErrorDetail_UnexpectedZipEntry",
6: "EDRMBlobDownloadErrorDetail_UnzipFullFile",
7: "EDRMBlobDownloadErrorDetail_UnknownBlobType",
8: "EDRMBlobDownloadErrorDetail_UnzipStrips",
9: "EDRMBlobDownloadErrorDetail_UnzipMergeGuid",
10: "EDRMBlobDownloadErrorDetail_UnzipSignature",
11: "EDRMBlobDownloadErrorDetail_ApplyStrips",
12: "EDRMBlobDownloadErrorDetail_ApplyMergeGuid",
13: "EDRMBlobDownloadErrorDetail_ApplySignature",
14: "EDRMBlobDownloadErrorDetail_AppIdMismatch",
15: "EDRMBlobDownloadErrorDetail_AppIdUnexpected",
16: "EDRMBlobDownloadErrorDetail_AppliedSignatureCorrupt",
17: "EDRMBlobDownloadErrorDetail_ApplyValveSignatureHeader",
18: "EDRMBlobDownloadErrorDetail_UnzipValveSignatureHeader",
19: "EDRMBlobDownloadErrorDetail_PathManipulationError",
65536: "EDRMBlobDownloadErrorDetail_TargetLocked_Base",
131071: "EDRMBlobDownloadErrorDetail_TargetLocked_Max",
131072: "EDRMBlobDownloadErrorDetail_NextBase",
}
func (e EDRMBlobDownloadErrorDetail) String() string {
if s, ok := EDRMBlobDownloadErrorDetail_name[e]; ok {
return s
}
var flags []string
for k, v := range EDRMBlobDownloadErrorDetail_name {
if e&k != 0 {
flags = append(flags, v)
}
}
if len(flags) == 0 {
return fmt.Sprintf("%d", e)
}
sort.Strings(flags)
return strings.Join(flags, " | ")
}
type EClientStat int32
const (
EClientStat_P2PConnectionsUDP EClientStat = 0
EClientStat_P2PConnectionsRelay EClientStat = 1
EClientStat_P2PGameConnections EClientStat = 2
EClientStat_P2PVoiceConnections EClientStat = 3
EClientStat_BytesDownloaded EClientStat = 4
EClientStat_Max EClientStat = 5
)
var EClientStat_name = map[EClientStat]string{
0: "EClientStat_P2PConnectionsUDP",
1: "EClientStat_P2PConnectionsRelay",
2: "EClientStat_P2PGameConnections",
3: "EClientStat_P2PVoiceConnections",
4: "EClientStat_BytesDownloaded",
5: "EClientStat_Max",
}
func (e EClientStat) String() string {
if s, ok := EClientStat_name[e]; ok {
return s
}
var flags []string
for k, v := range EClientStat_name {
if e&k != 0 {
flags = append(flags, v)
}
}
if len(flags) == 0 {
return fmt.Sprintf("%d", e)
}
sort.Strings(flags)
return strings.Join(flags, " | ")
}
type EClientStatAggregateMethod int32
const (
EClientStatAggregateMethod_LatestOnly EClientStatAggregateMethod = 0
EClientStatAggregateMethod_Sum EClientStatAggregateMethod = 1
EClientStatAggregateMethod_Event EClientStatAggregateMethod = 2
EClientStatAggregateMethod_Scalar EClientStatAggregateMethod = 3
)
var EClientStatAggregateMethod_name = map[EClientStatAggregateMethod]string{
0: "EClientStatAggregateMethod_LatestOnly",
1: "EClientStatAggregateMethod_Sum",
2: "EClientStatAggregateMethod_Event",
3: "EClientStatAggregateMethod_Scalar",
}
func (e EClientStatAggregateMethod) String() string {
if s, ok := EClientStatAggregateMethod_name[e]; ok {
return s
}
var flags []string
for k, v := range EClientStatAggregateMethod_name {
if e&k != 0 {
flags = append(flags, v)
}
}
if len(flags) == 0 {
return fmt.Sprintf("%d", e)
}
sort.Strings(flags)
return strings.Join(flags, " | ")
}
type ELeaderboardDataRequest int32
const (
ELeaderboardDataRequest_Global ELeaderboardDataRequest = 0
ELeaderboardDataRequest_GlobalAroundUser ELeaderboardDataRequest = 1
ELeaderboardDataRequest_Friends ELeaderboardDataRequest = 2
ELeaderboardDataRequest_Users ELeaderboardDataRequest = 3
)
var ELeaderboardDataRequest_name = map[ELeaderboardDataRequest]string{
0: "ELeaderboardDataRequest_Global",
1: "ELeaderboardDataRequest_GlobalAroundUser",
2: "ELeaderboardDataRequest_Friends",
3: "ELeaderboardDataRequest_Users",
}
func (e ELeaderboardDataRequest) String() string {
if s, ok := ELeaderboardDataRequest_name[e]; ok {
return s
}
var flags []string
for k, v := range ELeaderboardDataRequest_name {
if e&k != 0 {
flags = append(flags, v)
}
}
if len(flags) == 0 {
return fmt.Sprintf("%d", e)
}
sort.Strings(flags)
return strings.Join(flags, " | ")
}
type ELeaderboardSortMethod int32
const (
ELeaderboardSortMethod_None ELeaderboardSortMethod = 0
ELeaderboardSortMethod_Ascending ELeaderboardSortMethod = 1
ELeaderboardSortMethod_Descending ELeaderboardSortMethod = 2
)
var ELeaderboardSortMethod_name = map[ELeaderboardSortMethod]string{
0: "ELeaderboardSortMethod_None",
1: "ELeaderboardSortMethod_Ascending",
2: "ELeaderboardSortMethod_Descending",
}
func (e ELeaderboardSortMethod) String() string {
if s, ok := ELeaderboardSortMethod_name[e]; ok {
return s
}
var flags []string
for k, v := range ELeaderboardSortMethod_name {
if e&k != 0 {
flags = append(flags, v)
}
}
if len(flags) == 0 {
return fmt.Sprintf("%d", e)
}
sort.Strings(flags)
return strings.Join(flags, " | ")
}
type ELeaderboardDisplayType int32
const (
ELeaderboardDisplayType_None ELeaderboardDisplayType = 0
ELeaderboardDisplayType_Numeric ELeaderboardDisplayType = 1
ELeaderboardDisplayType_TimeSeconds ELeaderboardDisplayType = 2
ELeaderboardDisplayType_TimeMilliSeconds ELeaderboardDisplayType = 3
)
var ELeaderboardDisplayType_name = map[ELeaderboardDisplayType]string{
0: "ELeaderboardDisplayType_None",
1: "ELeaderboardDisplayType_Numeric",
2: "ELeaderboardDisplayType_TimeSeconds",
3: "ELeaderboardDisplayType_TimeMilliSeconds",
}
func (e ELeaderboardDisplayType) String() string {
if s, ok := ELeaderboardDisplayType_name[e]; ok {
return s
}
var flags []string
for k, v := range ELeaderboardDisplayType_name {
if e&k != 0 {
flags = append(flags, v)
}
}
if len(flags) == 0 {
return fmt.Sprintf("%d", e)
}
sort.Strings(flags)
return strings.Join(flags, " | ")
}
type ELeaderboardUploadScoreMethod int32
const (
ELeaderboardUploadScoreMethod_None ELeaderboardUploadScoreMethod = 0
ELeaderboardUploadScoreMethod_KeepBest ELeaderboardUploadScoreMethod = 1
ELeaderboardUploadScoreMethod_ForceUpdate ELeaderboardUploadScoreMethod = 2
)
var ELeaderboardUploadScoreMethod_name = map[ELeaderboardUploadScoreMethod]string{
0: "ELeaderboardUploadScoreMethod_None",
1: "ELeaderboardUploadScoreMethod_KeepBest",
2: "ELeaderboardUploadScoreMethod_ForceUpdate",
}
func (e ELeaderboardUploadScoreMethod) String() string {
if s, ok := ELeaderboardUploadScoreMethod_name[e]; ok {
return s
}
var flags []string
for k, v := range ELeaderboardUploadScoreMethod_name {
if e&k != 0 {
flags = append(flags, v)
}
}
if len(flags) == 0 {
return fmt.Sprintf("%d", e)
}
sort.Strings(flags)
return strings.Join(flags, " | ")
}
type EUCMFilePrivacyState int32
const (
EUCMFilePrivacyState_Invalid EUCMFilePrivacyState = -1
EUCMFilePrivacyState_Private EUCMFilePrivacyState = 2
EUCMFilePrivacyState_FriendsOnly EUCMFilePrivacyState = 4
EUCMFilePrivacyState_Public EUCMFilePrivacyState = 8
EUCMFilePrivacyState_All EUCMFilePrivacyState = EUCMFilePrivacyState_Public | EUCMFilePrivacyState_FriendsOnly | EUCMFilePrivacyState_Private
)
var EUCMFilePrivacyState_name = map[EUCMFilePrivacyState]string{
-1: "EUCMFilePrivacyState_Invalid",
2: "EUCMFilePrivacyState_Private",
4: "EUCMFilePrivacyState_FriendsOnly",
8: "EUCMFilePrivacyState_Public",
14: "EUCMFilePrivacyState_All",
}
func (e EUCMFilePrivacyState) String() string {
if s, ok := EUCMFilePrivacyState_name[e]; ok {
return s
}
var flags []string
for k, v := range EUCMFilePrivacyState_name {
if e&k != 0 {
flags = append(flags, v)
}
}
if len(flags) == 0 {
return fmt.Sprintf("%d", e)
}
sort.Strings(flags)
return strings.Join(flags, " | ")
}
type EUdpPacketType uint8
const (
EUdpPacketType_Invalid EUdpPacketType = 0
EUdpPacketType_ChallengeReq EUdpPacketType = 1
EUdpPacketType_Challenge EUdpPacketType = 2
EUdpPacketType_Connect EUdpPacketType = 3
EUdpPacketType_Accept EUdpPacketType = 4
EUdpPacketType_Disconnect EUdpPacketType = 5
EUdpPacketType_Data EUdpPacketType = 6
EUdpPacketType_Datagram EUdpPacketType = 7
EUdpPacketType_Max EUdpPacketType = 8
)
var EUdpPacketType_name = map[EUdpPacketType]string{
0: "EUdpPacketType_Invalid",
1: "EUdpPacketType_ChallengeReq",
2: "EUdpPacketType_Challenge",
3: "EUdpPacketType_Connect",
4: "EUdpPacketType_Accept",
5: "EUdpPacketType_Disconnect",
6: "EUdpPacketType_Data",
7: "EUdpPacketType_Datagram",
8: "EUdpPacketType_Max",
}
func (e EUdpPacketType) String() string {
if s, ok := EUdpPacketType_name[e]; ok {
return s
}
var flags []string
for k, v := range EUdpPacketType_name {
if e&k != 0 {
flags = append(flags, v)
}
}
if len(flags) == 0 {
return fmt.Sprintf("%d", e)
}
sort.Strings(flags)
return strings.Join(flags, " | ")
}
<file_sep>/auth/totp.go
package auth
import (
"crypto/hmac"
"crypto/sha1"
"encoding/base64"
"encoding/binary"
"encoding/json"
"net/http"
"github.com/pkg/errors"
)
const (
chars = "23456789BCDFGHJKMNPQRTVWXY"
charsLen = uint32(len(chars))
)
type TimeTip struct {
Time int64 `json:"server_time,string"`
SkewToleranceSeconds uint32 `json:"skew_tolerance_seconds,string"`
LargeTimeJink uint32 `json:"large_time_jink,string"`
ProbeFrequencySeconds uint32 `json:"probe_frequency_seconds"`
AdjustedTimeProbeFrequencySeconds uint32 `json:"adjusted_time_probe_frequency_seconds"`
HintProbeFrequencySeconds uint32 `json:"hint_probe_frequency_seconds"`
SyncTimeout uint32 `json:"sync_timeout"`
TryAgainSeconds uint32 `json:"try_again_seconds"`
MaxAttempts uint32 `json:"max_attempts"`
}
// TOTPGenerator is used to generate two factor auth code synced by time with Steam.
// TOTP = Time-based One-time Password Algorithm
type TOTPGenerator struct {
cl *http.Client
}
// NewTOTPGenerator initialize new instance of TOTPGenerator
func NewTOTPGenerator(cl *http.Client) *TOTPGenerator {
return &TOTPGenerator{cl}
}
// TwoFactorSynced fetch time from Steam and return generated two-factor code synced by time with Steam
func (gen *TOTPGenerator) TwoFactorSynced(sharedSecret string) (string, error) {
timeTip, err := gen.FetchTimeTip()
if err != nil {
return "", errors.Wrap(err, "failed to fetch time tip")
}
return gen.GenerateTwoFactorCode(sharedSecret, timeTip.Time)
}
// GenerateTwoFactorCode generate Steam two-factor code using current timestamp as parameter.
func (gen *TOTPGenerator) GenerateTwoFactorCode(sharedSecret string, currentTimestamp int64) (string, error) {
data, err := base64.StdEncoding.DecodeString(sharedSecret)
if err != nil {
return "", err
}
ful := make([]byte, 8)
binary.BigEndian.PutUint32(ful[4:], uint32(currentTimestamp/30))
hmacBuf := hmac.New(sha1.New, data)
hmacBuf.Write(ful)
sum := hmacBuf.Sum(nil)
start := sum[19] & 0x0F
slice := binary.BigEndian.Uint32(sum[start:start+4]) & 0x7FFFFFFF
buf := make([]byte, 5)
for i := 0; i < 5; i++ {
buf[i] = chars[slice%charsLen]
slice /= charsLen
}
return string(buf), nil
}
// FetchTimeTip fetch time from Steam.
func (gen *TOTPGenerator) FetchTimeTip() (*TimeTip, error) {
resp, err := gen.cl.Post(
"https://api.steampowered.com/ITwoFactorService/QueryTime/v1/",
"application/x-www-form-urlencoded",
nil,
)
if err != nil {
return nil, err
}
type Response struct {
Inner *TimeTip `json:"response"`
}
var response Response
if err = json.NewDecoder(resp.Body).Decode(&response); err != nil {
return nil, err
}
resp.Body.Close()
return response.Inner, nil
}
<file_sep>/multi/module.go
package multi
import (
"bytes"
"compress/gzip"
"encoding/binary"
"io"
"io/ioutil"
"fmt"
"github.com/golang/protobuf/proto"
"github.com/pkg/errors"
"github.com/furdarius/steamprotocol"
"github.com/furdarius/steamprotocol/messages"
"github.com/furdarius/steamprotocol/protobuf"
)
type Module struct {
eventManager *steamprotocol.EventManager
cl *steamprotocol.Client
}
func NewModule(
cl *steamprotocol.Client,
eventManager *steamprotocol.EventManager,
) *Module {
return &Module{
cl: cl,
eventManager: eventManager,
}
}
func (m *Module) Subscribe() {
m.eventManager.OnPacket(m.handlePacket)
}
func (m *Module) handlePacket(p *steamprotocol.Packet) error {
switch p.Type {
case steamprotocol.EMsg_Multi:
return m.handleMulti(p)
}
return nil
}
func (m *Module) handleMulti(p *steamprotocol.Packet) error {
var (
header *messages.HeaderProto = messages.NewHeaderProto(steamprotocol.EMsg_Invalid)
msg protobuf.CMsgMulti
)
dataBuf := bytes.NewBuffer(p.Data)
err := header.Deserialize(dataBuf)
if err != nil {
return errors.Wrap(err, "failed to deserialize multi header")
}
err = proto.Unmarshal(dataBuf.Bytes(), &msg)
if err != nil {
return errors.Wrap(err, "failed to unmarshal multi msg")
}
payload := msg.GetMessageBody()
if msg.GetSizeUnzipped() > 0 {
r, err := gzip.NewReader(bytes.NewReader(payload))
if err != nil {
return errors.Wrap(err, "failed to decompress payload")
}
payload, err = ioutil.ReadAll(r)
if err != nil {
return errors.Wrap(err, "failed to read all decompressed payload")
}
}
pr := bytes.NewReader(payload)
// Cycle body same as steamprotocol.Client.Read method,
// so, it can be better to move it to function,
// otherwise we had code duplication
// TODO: Refactor code for packet preparing
for pr.Len() > 0 {
var packetLen uint32
binary.Read(pr, binary.LittleEndian, &packetLen)
buf := make([]byte, packetLen)
_, err = io.ReadFull(pr, buf)
if err != nil {
return errors.Wrap(err, "failed to read packet data to buffer")
}
r := bytes.NewReader(buf)
var rawMsg uint32
err = binary.Read(r, binary.LittleEndian, &rawMsg)
if err != nil {
return errors.Wrap(err, "failed to read raw msg")
}
eMsg := steamprotocol.EMsg(rawMsg & steamprotocol.EMsgMask)
fmt.Println(eMsg)
packet := &steamprotocol.Packet{
Type: eMsg,
Data: buf,
}
err = m.eventManager.FirePacket(packet)
if err != nil {
return err
}
}
return nil
}
<file_sep>/crypto/aes.go
package crypto
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
)
// Aes is data encryptor
type Aes struct {
block cipher.Block
}
// NewAes initialize new instance of Aes.
func NewAes(b cipher.Block) *Aes {
return &Aes{b}
}
// Encrypt performs an encryption using AES/CBC/PKCS7
// with a random IV prepended using AES/ECB/None.
func (c *Aes) Encrypt(src []byte) ([]byte, error) {
// get a random IV and ECB encrypt it
iv := make([]byte, aes.BlockSize)
_, err := rand.Read(iv)
if err != nil {
return nil, err
}
encryptedIv := make([]byte, aes.BlockSize)
c.encryptBlocks(encryptedIv, iv)
// pad it, copy the IV to the first 16 bytes and encrypt the rest with CBC
encrypted := c.pad(src)
copy(encrypted, encryptedIv)
cipher.NewCBCEncrypter(c.block, iv).CryptBlocks(encrypted[aes.BlockSize:], encrypted[aes.BlockSize:])
return encrypted, nil
}
// Decrypts data from the reader using AES/CBC/PKCS7 with an IV
// prepended using AES/ECB/None. The src slice may not be used anymore.
func (c *Aes) Decrypt(src []byte) []byte {
iv := src[:aes.BlockSize]
c.decryptBlocks(iv, iv)
data := src[aes.BlockSize:]
cipher.NewCBCDecrypter(c.block, iv).CryptBlocks(data, data)
return c.unpad(data)
}
func (c *Aes) pad(src []byte) []byte {
missing := aes.BlockSize - (len(src) % aes.BlockSize)
newSize := len(src) + aes.BlockSize + missing
dest := make([]byte, newSize, newSize)
copy(dest[aes.BlockSize:], src)
padding := byte(missing)
for i := newSize - missing; i < newSize; i++ {
dest[i] = padding
}
return dest
}
func (c *Aes) unpad(src []byte) []byte {
padLen := src[len(src)-1]
return src[:len(src)-int(padLen)]
}
func (c *Aes) encryptBlocks(dst, src []byte) {
for len(src) > 0 {
c.block.Encrypt(dst, src[:c.block.BlockSize()])
src = src[c.block.BlockSize():]
dst = dst[c.block.BlockSize():]
}
}
func (c *Aes) decryptBlocks(dst, src []byte) {
for len(src) > 0 {
c.block.Decrypt(dst, src[:c.block.BlockSize()])
src = src[c.block.BlockSize():]
dst = dst[c.block.BlockSize():]
}
}
<file_sep>/crypto/events.go
package crypto
// ChannelReadyEvent is fired when successful EncryptResult is received, and
// channel is encrypted.
type ChannelReadyEvent struct{}
<file_sep>/heartbeat/events.go
package heartbeat
import (
"time"
)
type HeartBeatStartingEvent struct {
Timeout time.Duration
}
type HeartBeatTickedEvent struct{}
<file_sep>/messages/encrypt_request.go
package messages
import (
"encoding/binary"
"io"
"github.com/furdarius/steamprotocol"
)
const (
EncryptRequestDefaultProtocol uint32 = 1
)
type EncryptRequest struct {
ProtocolVersion uint32
Universe steamprotocol.EUniverse
}
func (m *EncryptRequest) Type() steamprotocol.EMsg {
return steamprotocol.EMsg_ChannelEncryptRequest
}
func (m *EncryptRequest) Serialize(w io.Writer) error {
err := binary.Write(w, binary.LittleEndian, m.ProtocolVersion)
if err != nil {
return err
}
err = binary.Write(w, binary.LittleEndian, m.Universe)
if err != nil {
return err
}
return nil
}
func (m *EncryptRequest) Deserialize(r io.Reader) error {
err := binary.Read(r, binary.LittleEndian, &m.ProtocolVersion)
if err != nil {
return err
}
var universe int32
err = binary.Read(r, binary.LittleEndian, &universe)
if err != nil {
return err
}
m.Universe = steamprotocol.EUniverse(universe)
return nil
}
<file_sep>/social/module.go
package social
import (
"bytes"
"github.com/golang/protobuf/proto"
"github.com/pkg/errors"
"github.com/furdarius/steamprotocol"
"github.com/furdarius/steamprotocol/auth"
"github.com/furdarius/steamprotocol/messages"
"github.com/furdarius/steamprotocol/protobuf"
)
type Module struct {
eventManager *steamprotocol.EventManager
cl *steamprotocol.Client
steamID uint64
sessionID int32
}
func NewModule(cl *steamprotocol.Client, eventManager *steamprotocol.EventManager) *Module {
return &Module{
cl: cl,
eventManager: eventManager,
}
}
func (m *Module) Subscribe() {
m.eventManager.OnEvent(m.handleEvent)
}
func (m *Module) handleEvent(e interface{}) error {
switch event := e.(type) {
case auth.SuccessfullyAuthenticatedEvent:
m.handleSuccessfullyAuthenticatedEvent(event)
}
return nil
}
func (m *Module) handleSuccessfullyAuthenticatedEvent(e auth.SuccessfullyAuthenticatedEvent) {
m.sessionID = e.SessionID
m.steamID = e.SteamID
m.SetUserOnline()
}
func (m *Module) SetUserOnline() error {
responseHeader := messages.NewHeaderProto(steamprotocol.EMsg_ClientChangeStatus)
responseHeader.Data.Steamid = proto.Uint64(m.steamID)
responseHeader.Data.ClientSessionid = proto.Int32(m.sessionID)
responseMsg := &protobuf.CMsgClientChangeStatus{
PersonaState: proto.Uint32(uint32(steamprotocol.EPersonaState_Online)),
}
buf := new(bytes.Buffer)
err := responseHeader.Serialize(buf)
if err != nil {
return errors.Wrap(err, "failed to serialize header")
}
body, err := proto.Marshal(responseMsg)
if err != nil {
return errors.Wrap(err, "failed to marshal response msg")
}
_, err = buf.Write(body)
if err != nil {
return errors.Wrap(err, "failed to append msg to buffer")
}
err = m.cl.Write(buf.Bytes())
if err != nil {
return errors.Wrap(err, "failed to write data")
}
return nil
}
<file_sep>/auth/events.go
package auth
import (
"time"
"github.com/furdarius/steamprotocol"
)
// SuccessfullyAuthenticatedEvent is fired when successful CMsgClientLogonResponse is received.
type SuccessfullyAuthenticatedEvent struct {
Heartbeat time.Duration
SteamID uint64
SessionID int32
}
// AuthenticationFailedEvent is fired when failed CMsgClientLogonResponse is received.
type AuthenticationFailedEvent struct {
Result steamprotocol.EResult
}
// LoggedOffEvent is fired when steam log off authenticated client.
type LoggedOffEvent struct {
Result steamprotocol.EResult
}
// NewLoginKeyAcceptedEvent is fired when CMsgClientNewLoginKey is received.
type NewLoginKeyAcceptedEvent struct {
UniqID uint32
Key string
}
// MachineAuthUpdateEvent is fired when CMsgClientUpdateMachineAuth is received.
type MachineAuthUpdateEvent struct {
Hash []byte
}
<file_sep>/crypto/module.go
// Package crypto used to encrypt communication channel.
//
// After establishing a connection to a CM server, the server and client go through a handshake process
// that establishes an encrypted connection.
// Client messages are encrypted using AES with a session key that is generated
// by the client during the handshake.
// There exists evidence that a connection can be unencrypted,
// because of the export restriction of strong cryptography from the US,
// but it has not been observed.
//
// Steps:
// 1. Server requests the client to encrypt traffic within the specified universe (normally Public)
// 2. Client generates a 256bit session key.
// 3. This key is encrypted by a 1024bit public RSA key for the specific universe.
// 4. The encrypted key is sent to the server, along with a 32bit crc of the encrypted key.
// 5. The server replies with an unencrypted success/failure message.
// 6. All traffic from here is AES encrypted with the session key.
//
// Symmetric crypto
// * All messages after the handshake are AES encrypted.
// * A random 16 byte IV is generated for every message.
// * This IV is AES encrypted in ECB mode using the session key generated during the handshake.
// * Message data is encrypted with AES using the generated (not encrypted) IV and session key in CBC mode.
// * The encrypted IV and encrypted message data are concatenated together and sent off.
package crypto
import (
"bytes"
"crypto/aes"
"crypto/rand"
"crypto/rsa"
"crypto/sha1"
"encoding/binary"
"fmt"
"hash/crc32"
"github.com/furdarius/steamprotocol"
"github.com/furdarius/steamprotocol/messages"
"github.com/pkg/errors"
)
// Module used to encrypt communication channel.
type Module struct {
eventManager *steamprotocol.EventManager
cl *steamprotocol.Client
sessionKey []byte
}
// NewModule initialize new instance of crypto Module.
func NewModule(cl *steamprotocol.Client, eventManager *steamprotocol.EventManager) *Module {
return &Module{
cl: cl,
eventManager: eventManager,
}
}
// Subscribe used to start listen event and packets from eventManager.
func (m *Module) Subscribe() {
m.eventManager.OnPacket(m.handlePacket)
}
func (m *Module) handlePacket(p *steamprotocol.Packet) error {
switch p.Type {
case steamprotocol.EMsg_ChannelEncryptRequest:
return m.handleChannelEncryptRequest(p)
case steamprotocol.EMsg_ChannelEncryptResult:
return m.handleChannelEncryptResult(p)
default:
return nil
}
}
func (m *Module) handleChannelEncryptRequest(p *steamprotocol.Packet) error {
var (
header messages.Header
msg messages.EncryptRequest
)
r := bytes.NewReader(p.Data)
err := header.Deserialize(r)
if err != nil {
return errors.Wrap(err, "failed to decode encrypt request header")
}
err = msg.Deserialize(r)
if err != nil {
return errors.Wrap(err, "failed to decode encrypt request")
}
if msg.Universe != steamprotocol.EUniverse_Public {
return errors.New("invalid universe")
}
if msg.ProtocolVersion != messages.EncryptRequestDefaultProtocol {
return fmt.Errorf("invalid protocol version %d", msg.ProtocolVersion)
}
pub, err := getPublicKey(steamprotocol.EUniverse_Public)
if err != nil {
return errors.Wrapf(err, "failed to get public key for universe %v", msg.Universe)
}
m.sessionKey = make([]byte, 32)
rand.Read(m.sessionKey)
encryptedKey, err := rsa.EncryptOAEP(sha1.New(), rand.Reader, pub, m.sessionKey, nil)
if err != nil {
return errors.Wrap(err, "failed to encrypt session key")
}
responseMsg := messages.NewEncryptResponse(messages.EncryptRequestDefaultProtocol, 128)
responseHeader := messages.NewHeader(responseMsg.Type(), header.SourceJobID, header.TargetJobID)
buf := new(bytes.Buffer)
err = responseHeader.Serialize(buf)
if err != nil {
return errors.Wrap(err, "failed to serialize header")
}
err = responseMsg.Serialize(buf)
if err != nil {
return errors.Wrap(err, "failed to serialize response msg")
}
n, err := buf.Write(encryptedKey)
if err != nil || len(encryptedKey) != n {
return errors.Wrap(err, "failed to write encrypted key to result buffer")
}
keyHash := crc32.ChecksumIEEE(encryptedKey)
err = binary.Write(buf, binary.LittleEndian, keyHash)
if err != nil {
return errors.Wrap(err, "failed to write key hash to result buffer")
}
err = binary.Write(buf, binary.LittleEndian, uint32(0))
if err != nil {
return errors.Wrap(err, "failed to write finish bytes to result buffer")
}
err = m.cl.Write(buf.Bytes())
if err != nil {
return errors.Wrap(err, "failed to write data")
}
return nil
}
func (m *Module) handleChannelEncryptResult(p *steamprotocol.Packet) error {
var (
header messages.Header
msg messages.EncryptResult
)
r := bytes.NewReader(p.Data)
err := header.Deserialize(r)
if err != nil {
return errors.Wrap(err, "failed to decode encrypt request header")
}
err = msg.Deserialize(r)
if err != nil {
return errors.Wrap(err, "failed to decode encrypt request")
}
if msg.Result != steamprotocol.EResult_OK {
return errors.New("encryption failed")
}
block, err := aes.NewCipher(m.sessionKey)
if err != nil {
return errors.Wrap(err, "failed to create cipher from session key")
}
encryptor := NewAes(block)
m.cl.SetEncryptor(encryptor)
return m.eventManager.FireEvent(ChannelReadyEvent{})
}
<file_sep>/heartbeat/module.go
package heartbeat
import (
"bytes"
"time"
"github.com/golang/protobuf/proto"
"github.com/pkg/errors"
"github.com/furdarius/steamprotocol"
"github.com/furdarius/steamprotocol/auth"
"github.com/furdarius/steamprotocol/messages"
"github.com/furdarius/steamprotocol/protobuf"
)
type Module struct {
eventManager *steamprotocol.EventManager
cl *steamprotocol.Client
steamID uint64
sessionID int32
errorCh chan error
doneCh chan struct{}
}
func NewModule(cl *steamprotocol.Client, eventManager *steamprotocol.EventManager) *Module {
return &Module{
cl: cl,
eventManager: eventManager,
errorCh: make(chan error),
doneCh: make(chan struct{}),
}
}
func (m *Module) ErrorChannel() <-chan error {
return m.errorCh
}
func (m *Module) Subscribe() {
m.eventManager.OnEvent(m.handleEvent)
}
func (m *Module) handleEvent(e interface{}) error {
switch event := e.(type) {
case auth.SuccessfullyAuthenticatedEvent:
m.handleSuccessfullyAuthenticatedEvent(event)
case auth.LoggedOffEvent:
m.handleLoggedOffEvent()
}
return nil
}
func (m *Module) handleSuccessfullyAuthenticatedEvent(e auth.SuccessfullyAuthenticatedEvent) {
m.sessionID = e.SessionID
m.steamID = e.SteamID
m.eventManager.FireEvent(HeartBeatStartingEvent{
Timeout: e.Heartbeat,
})
ticker := time.NewTicker(e.Heartbeat)
go m.heartbeatLoop(ticker)
}
func (m *Module) handleLoggedOffEvent() {
close(m.doneCh)
}
func (m *Module) heartbeatLoop(ticker *time.Ticker) {
// TODO: Use context for graceful shutdown
for {
select {
case <-ticker.C:
err := m.doTick()
if err != nil {
m.errorCh <- err
}
case <-m.doneCh:
ticker.Stop()
close(m.errorCh)
return
}
}
}
func (m *Module) doTick() error {
responseHeader := messages.NewHeaderProto(steamprotocol.EMsg_ClientHeartBeat)
responseHeader.Data.Steamid = proto.Uint64(m.steamID)
responseHeader.Data.ClientSessionid = proto.Int32(m.sessionID)
responseMsg := &protobuf.CMsgClientHeartBeat{}
buf := new(bytes.Buffer)
err := responseHeader.Serialize(buf)
if err != nil {
return errors.Wrap(err, "failed to serialize header")
}
body, err := proto.Marshal(responseMsg)
if err != nil {
return errors.Wrap(err, "failed to marshal response msg")
}
_, err = buf.Write(body)
if err != nil {
return errors.Wrap(err, "failed to append msg to buffer")
}
err = m.cl.Write(buf.Bytes())
if err != nil {
return errors.Wrap(err, "failed to write data")
}
err = m.eventManager.FireEvent(HeartBeatTickedEvent{})
if err != nil {
return errors.Wrap(err, "failed to fire heartbeat tick event")
}
return nil
}
<file_sep>/messages/doc.go
// Package messages has list of protocol messages structs
//
// Steam client messages normally consist of a general header,
// followed by a message structure, and end with a payload blob that is used in only a few messages.
// Messages are identified by integer constants known as an EMsg.
// There are three currently used message headers:
// MsgHdr is used before the client has an assigned session id or steamid. Used during the crypto handshake.
// ExtendedClientMsgHdr is used when the client has been assigned a session id or steamid.
// This is generally used after the crypto handshake.
// MsgHdrProtoBuf was recently introduced when Valve upgraded the Steam protocol to support protocol buffers.
// This is similar to the ExtendedClientMsgHdr, but is used when the client message is protobuf'd.
// Every client message has a structure which is normally the entire contents of the message,
// and is easily interpreted.
// The payload is only used in certain circumstances, such as the message data when sending MsgClientFriendMsg.
// There's a certain message of interest called a MsgMulti.
// This message is a wrapper message that encompasses multiple messages inside itself,
// often times compressed using PKZIP. The header of this message contains an int 'unzipped size',
// if this size is greater than 0, the message payload is compressed.
// After decompressing, the data is a stream of size and data pairs, with the data being a new client message.
//
// Read more: https://bitbucket.org/robingchan/steam/wiki/Networking/Protocol-level_messages.wiki
package messages
<file_sep>/messages/header.go
package messages
import (
"encoding/binary"
"io"
"github.com/furdarius/steamprotocol"
)
type Header struct {
Type steamprotocol.EMsg
TargetJobID uint64
SourceJobID uint64
}
func NewHeader(msgType steamprotocol.EMsg, targetJobID uint64, sourceJobID uint64) *Header {
return &Header{
Type: msgType,
TargetJobID: targetJobID,
SourceJobID: sourceJobID,
}
}
func (m *Header) Serialize(w io.Writer) error {
err := binary.Write(w, binary.LittleEndian, m.Type)
if err != nil {
return err
}
err = binary.Write(w, binary.LittleEndian, m.TargetJobID)
if err != nil {
return err
}
err = binary.Write(w, binary.LittleEndian, m.SourceJobID)
if err != nil {
return err
}
return nil
}
func (m *Header) Deserialize(r io.Reader) error {
var t int32
err := binary.Read(r, binary.LittleEndian, &t)
if err != nil {
return err
}
m.Type = steamprotocol.EMsg(t)
err = binary.Read(r, binary.LittleEndian, &m.TargetJobID)
if err != nil {
return err
}
err = binary.Read(r, binary.LittleEndian, &m.SourceJobID)
if err != nil {
return err
}
return nil
}
<file_sep>/README.md

# Furdarius\Steamprotocol
TODO: More docs!
Example of usage:
```go
rand.Seed(time.Now().Unix())
cm := cmlist.NewCMList(cl)
servAddr, err := cm.GetRandomServer()
if err != nil {
log.Error(
"failed to get random server",
zap.Error(err))
os.Exit(1)
}
d := net.Dialer{}
conn, err := d.DialContext(ctx, "tcp", servAddr)
if err != nil {
log.Error(
"Failed to connect to server",
zap.String("addr", servAddr),
zap.Error(err))
os.Exit(1)
}
log.Debug("Successfully connected to server",
zap.String("addr", servAddr))
eventManager := steamprotocol.NewEventManager()
steamClient := steamprotocol.NewClient(conn, eventManager)
cryptoModule := crypto.NewModule(steamClient, eventManager)
cryptoModule.Subscribe()
gen := auth.NewTOTPGenerator(cl)
authModule := auth.NewModule(steamClient, eventManager, gen, auth.Details{
Username: "myusername",
Password: "<PASSWORD>",
SharedSecret: "mysharedsecret",
})
authModule.Subscribe()
multiModule := multi.NewModule(steamClient, eventManager)
multiModule.Subscribe()
heartbeatModule := heartbeat.NewModule(steamClient, eventManager)
heartbeatModule.Subscribe()
socialModule := social.NewModule(steamClient, eventManager)
socialModule.Subscribe()
// TODO: Select with context for graceful shutdown
go func() {
for err := range heartbeatModule.ErrorChannel() {
log.Error(
"failed to heartbeat",
zap.Error(err))
}
log.Debug("Exit from heartbeat error checking goroutine")
}()
err = steamClient.Listen()
if err != nil {
log.Error(
"Failed to listen steam server",
zap.Error(err))
os.Exit(1)
}
```<file_sep>/messages/encrypt_result.go
package messages
import (
"encoding/binary"
"io"
"github.com/furdarius/steamprotocol"
)
type EncryptResult struct {
Result steamprotocol.EResult
}
func NewEncryptResult() *EncryptResult {
return &EncryptResult{
Result: steamprotocol.EResult_Invalid,
}
}
func (m *EncryptResult) Type() steamprotocol.EMsg {
return steamprotocol.EMsg_ChannelEncryptResult
}
func (m *EncryptResult) Serialize(w io.Writer) error {
err := binary.Write(w, binary.LittleEndian, m.Result)
if err != nil {
return err
}
return nil
}
func (m *EncryptResult) Deserialize(r io.Reader) error {
var tmp int32
err := binary.Read(r, binary.LittleEndian, &tmp)
if err != nil {
return err
}
m.Result = steamprotocol.EResult(tmp)
return nil
}
<file_sep>/eventmanager.go
package steamprotocol
// EventHandler used to catch and handle event.
// It takes event object as argument
type EventHandler func(interface{}) error
// PacketHandler used to catch and handle Packet.
// It takes Packet as argument
type PacketHandler func(*Packet) error
// NewEventManager initialize new instance of EventManager.
func NewEventManager() *EventManager {
return &EventManager{}
}
// EventManager is used to fire and broadcast events and packets to handlers.
type EventManager struct {
eventHandlers []EventHandler
packetHandlers []PacketHandler
}
// OnEvent add Event handler.
// Any event will be received by all handlers.
// Use select via interface casting to catch events you are interested in.
func (m *EventManager) OnEvent(h EventHandler) {
m.eventHandlers = append(m.eventHandlers, h)
}
// OnPacket add Packet handler.
// Any packet will be received by all handlers.
// Use select via EMsg to catch packets you are interested in.
func (m *EventManager) OnPacket(h PacketHandler) {
m.packetHandlers = append(m.packetHandlers, h)
}
// FireEvent broadcast event to handlers
func (m *EventManager) FireEvent(e interface{}) error {
for _, handler := range m.eventHandlers {
err := handler(e)
if err != nil {
return err
}
}
return nil
}
// FirePacket broadcast packet to handlers
func (m *EventManager) FirePacket(p *Packet) error {
for _, handler := range m.packetHandlers {
err := handler(p)
if err != nil {
return err
}
}
return nil
}
|
16b83740544bc1453271c7c5e2defa2fd1f86cc0
|
[
"Markdown",
"Go"
] | 22
|
Go
|
furdarius/steamprotocol
|
076394936dbff54395cc1d55880db6a4622ec234
|
46e3b5b60c8369c9f1bafab8a94fc7d0f9eb5c9f
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.