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><?php require_once('mysql_connect.php'); ?>
792fc0207c7c69a970e6be6b995b06ea407c989e
[ "PHP" ]
1
PHP
Learning-Fuze/server_mysqlconnect_example
942978a8f957575d8a1e749449b2c0c53364266e
fab8e4d02a9f686c9a7291ddce6b3d12754c97d2
refs/heads/master
<repo_name>cyversewarwick/canu<file_sep>/scripts/canu_tarwrapper.sh #!/bin/bash set -e #mark start sleep 5 touch tempfile sleep 5 #run thing bash /canu-1.3/Linux-amd64/bin/canu -p canu -d canu_out genomeSize=$1 "${@:2}" #wrap up output and kick out tempfile find . -mindepth 1 -newer tempfile -exec tar -rf FullOutput.tar {} \; rm tempfile
50e41c4f407abb7756c4ae5e47462e16b55a896d
[ "Shell" ]
1
Shell
cyversewarwick/canu
03c952bb5c14308bcb446c2d8a979d31db48e416
968343a5e4d6bc5e20a863d79ce4e143ae56a708
refs/heads/master
<repo_name>WhoSV/codestack<file_sep>/app/components/MyProfile/index.jsx import React from 'react'; // Material UI imports import IconButton from 'material-ui/IconButton'; import ActionArrow from 'material-ui/svg-icons/hardware/keyboard-arrow-right'; import ActionEdit from 'material-ui/svg-icons/image/edit'; import SadIcon from 'material-ui/svg-icons/social/sentiment-dissatisfied'; import ChartIcon from 'material-ui/svg-icons/editor/insert-chart'; import ActionDelete from 'material-ui/svg-icons/action/delete'; import FlatButton from 'material-ui/FlatButton'; import Dialog from 'material-ui/Dialog'; import LinearProgress from 'material-ui/LinearProgress'; // Import components import Navbar from '../Navbar'; // Component Style import style from './style.less'; // Import static icons import { img } from '../../static'; // Material UI Styles const muiStyle = { dialogTitleStyle: { color: '#30CFD0' } }; // Component Actions import { getUser, getCourses, deleteCourse, getOpenCourse, getSurveys, getFavorites } from './actions'; class MyProfile extends React.Component { constructor(props) { super(); this.state = { id: '', name: '', role: '', courses: [], course: {}, surveys: [], dialogDelete: false, dialogStatistics: false, favorites: [] }; } componentWillMount() { this.state.id = localStorage.id; this.activeUser(); this.updateCourses(); this.updateStatistics(); this.updateFavorites(); } updateCourses() { getCourses(data => { this.setState({ courses: data }); }); } updateFavorites() { getFavorites(data => { this.setState({ favorites: data }); }); } updateStatistics() { getSurveys(data => { this.setState({ surveys: data }); }); } activeUser() { getUser(this.state.id, data => { this.setState({ id: data.id, name: data.full_name, role: data.role }); }); } dialogClose() { this.setState({ dialogDelete: false, dialogStatistics: false }); } confirmDeleteContent() { deleteCourse(this.state.course.id, res => { this.setState({ dialogDelete: false, course: {} }); this.updateCourses(); }); } deleteCourse(course) { this.setState({ dialogDelete: true, course: course }); } navigateToCourse(course) { getOpenCourse(course.id, data => { let link = 'data:application/pdf;base64,' + data; var iframe = "<iframe width='100%' height='100%' src='" + link + "' style='border: none; margin: 0; padding: 0;'></iframe>"; var x = window.open(); x.document.open(); x.document.write(iframe); x.document.close(); }); } navigateToEditCourse(course) { localStorage.courseId = course.id; this.props.history.push('/editcourse'); } navigateToStatistics(course) { let firstStats = 0; let secondStats = 0; let thirdStats = 0; let fourthStats = 0; let fifthStats = 0; let counter = 0; this.state.surveys.map((survey, index) => { if (survey.course_id === course.id) { firstStats = firstStats + survey.first; secondStats = secondStats + survey.second; thirdStats = thirdStats + survey.third; fourthStats = fourthStats + survey.fourth; fifthStats = fifthStats + survey.fifth; counter++; } }); firstStats = firstStats * 10 / counter; secondStats = secondStats * 10 / counter; thirdStats = thirdStats * 10 / counter; fourthStats = fourthStats * 10 / counter; fifthStats = fifthStats * 10 / counter; if ( !firstStats && !secondStats && !thirdStats && !fourthStats && !fifthStats ) { this.setState({ noStats: true }); } else { this.setState({ noStats: false }); } this.setState({ dialogStatistics: true, firstStats: firstStats, secondStats: secondStats, thirdStats: thirdStats, fourthStats: fourthStats, fifthStats: fifthStats, courseName: course.name + ' Course Statistics' }); } render() { const deleteActions = [ <FlatButton label="Cancel" style={{ color: '#747374' }} primary={true} onTouchTap={this.dialogClose.bind(this)} />, <FlatButton label="Delete" style={{ color: '#ff0000' }} primary={true} onTouchTap={this.confirmDeleteContent.bind(this)} /> ]; const statisticsAction = [ <FlatButton label="OK" style={{ color: '#37bdd5' }} primary={true} onTouchTap={this.dialogClose.bind(this)} /> ]; let profileData = <div />; let role = localStorage.user_role; if (role === 'TEACHER') { profileData = ( <div className={style.coursesContainer}> <div> <h2>Added Courses</h2> </div> <div className={style.courses}> {this.state.courses.map((course, index) => { if (this.state.id.toString() === course.teacher_id) { return ( <div key={index} className={style.selectedCourseContainer}> <div className={style.selectedCourseItem}> <h4 className={style.courseNameStyle}> <img className={style.defaultIconStyle} src={img.defaultIcon} /> {course.name} </h4> <IconButton onClick={this.navigateToStatistics.bind(this, course)} tooltip="Statistics" tooltipPosition="bottom-left" touch={true} > <ChartIcon className={style.chartButton} /> </IconButton> <IconButton onClick={this.navigateToEditCourse.bind(this, course)} tooltip="Edit" tooltipPosition="bottom-left" touch={true} > <ActionEdit className={style.editButton} /> </IconButton> <IconButton onClick={this.deleteCourse.bind(this, course)} tooltip="Delete" tooltipPosition="bottom-left" touch={true} > <ActionDelete className={style.deleteButton} /> </IconButton> </div> </div> ); } })} </div> </div> ); } else if (role === 'STUDENT') { profileData = ( <div className={style.coursesContainer}> <h2>Favorite Courses</h2> <div className={style.courses}> {this.state.favorites.map((favorite, index) => { if (this.state.id === favorite.user_id) { return this.state.courses.map((course, index) => { if (favorite.course_id === course.id) { return ( <div key={index} className={style.selectedCourseContainer} > <div className={style.selectedCourseItem}> <h4 className={style.courseNameStyle}> <img className={style.defaultIconStyle} src={img.defaultIcon} /> {course.name} </h4> <IconButton onClick={this.navigateToCourse.bind(this, course)} tooltip="Open" tooltipPosition="bottom-left" touch={true} > <ActionArrow className={style.arrowButton} /> </IconButton> </div> </div> ); } }); } })} </div> </div> ); } return ( <div className={style.myProfile}> <Navbar {...this.props} /> <div className={style.headerStyle}> <img className={style.imgStyle} src={img.defaultUser} /> <h2>{this.state.name}</h2> <h4>{this.state.role}</h4> </div> {profileData} {/* Delete Content Dialog */} <Dialog className={style.dialog} title="Delete Course" actions={deleteActions} modal={false} open={this.state.dialogDelete} onRequestClose={this.dialogClose.bind(this)} > Do you realy want to delete <span className={style.highlight}>{this.state.course.name}</span> ? </Dialog> {/* Statistics Dialog */} <Dialog className={style.dialog} title={this.state.courseName} titleStyle={muiStyle.dialogTitleStyle} actions={statisticsAction} modal={false} open={this.state.dialogStatistics} onRequestClose={this.dialogClose.bind(this)} > {(() => { if (!this.state.noStats) { return ( <div> <h5>This dialog shows averrage statistics.</h5> <ol> <li> Where course objectives clear? <div className={style.progressContainer}> <LinearProgress mode="determinate" className={style.progress} value={this.state.firstStats} /> <h4>{Math.round(this.state.firstStats).toFixed(0)}%</h4> </div> </li> <li> Were the course textnotes clear and well written? <div className={style.progressContainer}> <LinearProgress mode="determinate" className={style.progress} value={this.state.secondStats} /> <h4> {Math.round(this.state.secondStats).toFixed(0)}% </h4> </div> </li> <li> Where the assignments appropriate for the level of this class? <div className={style.progressContainer}> <LinearProgress mode="determinate" className={style.progress} value={this.state.thirdStats} /> <h4>{Math.round(this.state.thirdStats).toFixed(0)}%</h4> </div> </li> <li> Have this course increased my interest in the subject? <div className={style.progressContainer}> <LinearProgress mode="determinate" className={style.progress} value={this.state.fourthStats} /> <h4> {Math.round(this.state.fourthStats).toFixed(0)}% </h4> </div> </li> <li> Is this course corresponded to my expectations? <div className={style.progressContainer}> <LinearProgress mode="determinate" className={style.progress} value={this.state.fifthStats} /> <h4>{Math.round(this.state.fifthStats).toFixed(0)}%</h4> </div> </li> </ol> </div> ); } else { return ( <div className={style.noStatsStyle}> <SadIcon className={style.sadIcon} /> <h4>Sorry, insufficient surveys passed to show statistics</h4> </div> ); } })()} </Dialog> </div> ); } } export default MyProfile; <file_sep>/app/components/AdminPanel/UserContainer/CreateUserForm/index.jsx import React from 'react'; // Material UI imports import TextField from 'material-ui/TextField'; import RaisedButton from 'material-ui/RaisedButton'; import SelectField from 'material-ui/SelectField'; import MenuItem from 'material-ui/MenuItem'; import ContentAdd from 'material-ui/svg-icons/content/add'; // Material UI Styles const muiStyle = { floatingLabelTextStyle: { fontWeight: 'normal' }, createButtonStyle: { margin: '20px 40px' }, errorStyle: { textAlign: 'center' } }; // Component Actions import { createUser } from './actions'; // Component Style import style from './style'; export default class CreateUserForm extends React.Component { constructor(props) { super(props); this.state = { full_name: '', mail: '', role: '', password: '' }; this.handleNameChange = this.handleNameChange.bind(this); this.handleMailChange = this.handleMailChange.bind(this); this.handleRoleChange = this.handleRoleChange.bind(this); this.handlePasswordChange = this.handlePasswordChange.bind(this); this.handleCreateUser = this.handleCreateUser.bind(this); } handleNameChange(event) { this.setState({ full_name: event.target.value }); } handleMailChange(event) { this.setState({ mail: event.target.value }); } handleRoleChange(event, index, value) { this.setState({ role: value }); } handlePasswordChange(event) { this.setState({ password: event.target.value }); } handleCreateUser(event) { // Call preventDefault() on the event to prevent the browser's default // action of submitting the form. event.preventDefault(); this.setState({ inputError: '', emailInputError: '' }); const full_name = this.state.full_name; const mail = this.state.mail; const role = this.state.role; const password = this.state.password; const that = this; let validateForm = function(arr) { for (var i = 0; i < arr.length; i++) { if (arr[i] == null || arr[i] == '') { return false; } } return true; }; let reqInputs = [full_name, mail, password, role]; if (validateForm(reqInputs)) { let formData = { full_name: full_name, email: mail, role: role, password: <PASSWORD> }; createUser( formData, res => { this.setState({ full_name: '', mail: '', role: '', password: '' }); this.props.changeOnUserList(); }, error => { that.setState({ emailInputError: 'Email must be unique.' }); } ); } else { this.setState({ inputError: 'All fields must be filled.', emailInputError: 'All fields must be filled.' }); } } render() { return ( <div className={style.createUserStyle}> <h3 className={style.title}>Create User</h3> <form onSubmit={this.handleCreateUser} className={style.formStyle}> <div className={style.container}> <TextField autoCorrect="none" autoCapitalize="none" hintText="<NAME>" type="text" floatingLabelText="Name & Surname" errorText={this.state.inputError} value={this.state.full_name} className={style.textFieldStyle} onChange={this.handleNameChange} floatingLabelStyle={muiStyle.floatingLabelTextStyle} /> <TextField autoCorrect="none" autoCapitalize="none" hintText="<EMAIL>" type="mail" floatingLabelText="Email" errorText={this.state.emailInputError} value={this.state.mail} className={style.textFieldStyle} onChange={this.handleMailChange} floatingLabelStyle={muiStyle.floatingLabelTextStyle} /> </div> <div className={style.container}> <TextField autoCorrect="none" autoCapitalize="none" hintText="********" type="password" floatingLabelText="Password" errorText={this.state.inputError} value={this.state.password} className={style.textFieldStyle} onChange={this.handlePasswordChange} floatingLabelStyle={muiStyle.floatingLabelTextStyle} /> <SelectField floatingLabelText="Role" value={this.state.role} className={style.selectFieldStyle} errorText={this.state.inputError} errorStyle={muiStyle.errorStyle} onChange={this.handleRoleChange} floatingLabelStyle={muiStyle.floatingLabelTextStyle} > <MenuItem value="STUDENT" primaryText="Student" /> <MenuItem value="TEACHER" primaryText="Teacher" /> <MenuItem value="ADMIN" primaryText="Admin" /> </SelectField> </div> <RaisedButton type="submit" label="Create" icon={<ContentAdd />} labelColor="#fff" backgroundColor="#37BDD5" style={muiStyle.createButtonStyle} /> </form> </div> ); } } <file_sep>/webpack.config.js const { resolve } = require('path'); const webpack = require('webpack'); module.exports = { context: resolve(__dirname, 'app'), entry: [ 'webpack-dev-server/client?http://localhost:8080', // bundle the client for webpack-dev-server // and connect to the provided endpoint './app.js' // the entry point of our app ], output: { filename: 'bundle.js', // the output bundle path: resolve(__dirname, 'public') }, devtool: 'inline-source-map', devServer: { contentBase: resolve(__dirname, 'public'), // match the output path publicPath: '/', // match the output `publicPath` historyApiFallback: true }, resolve: { extensions: ['.js', '.jsx', '.css', '.less'], modules: ['./app', './node_modules'] }, module: { rules: [ { test: /\.(js|jsx)?$/, use: ['babel-loader'], exclude: /node_modules/ }, { test: /\.(less|css)$/, use: ['style-loader', 'css-loader?modules', 'less-loader'] }, { test: /\.(jpg|png|gif)$/, use: { loader: 'file-loader', options: { publicPath: '/' } } }, { test: /\.(woff|woff2|eot|ttf|svg)$/, use: { loader: 'url-loader', options: { limit: 100000 } } } ] } }; <file_sep>/app/components/AddCourse/index.jsx import React from 'react'; // Material UI imports import TextField from 'material-ui/TextField'; import RaisedButton from 'material-ui/RaisedButton'; import Dialog from 'material-ui/Dialog'; import FlatButton from 'material-ui/FlatButton'; import ContentAdd from 'material-ui/svg-icons/content/add'; // Import components import Navbar from '../Navbar'; // Import static icons import { img } from '../../static'; // Component Actions import { getUser, createCourse } from './actions'; // Material UI Styles const muiStyle = { floatingLabelTextStyle: { fontWeight: '100', color: '#4a4a4a' }, uploadInputStyle: { cursor: 'pointer', position: 'absolute', top: 0, bottom: 0, right: 0, left: 0, width: '100%', opacity: 0 }, addButtonStyle: { width: '250px' }, dialogTitleStyle: { color: '#4A90E2' } }; // Component Style import style from './style.less'; class AddCourse extends React.Component { constructor(props) { super(); var today = new Date(), date = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate(); this.state = { id: '', teacherName: '', courseName: '', courseDescription: '', fileName: '', status: 'ACTIVE', file: '', dialogAlert: false, date: date }; this.handleCourseNameChange = this.handleCourseNameChange.bind(this); this.handleCourseDescrChange = this.handleCourseDescrChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); this.handleUploadFile = this.handleUploadFile.bind(this); this.handleBack = this.handleBack.bind(this); } componentWillMount() { this.state.id = localStorage.id; this.activeUser(); } activeUser() { getUser(this.state.id, data => { this.setState({ teacherName: data.full_name }); }); } handleCourseNameChange(event) { this.setState({ courseName: event.target.value }); } handleCourseDescrChange(event) { this.setState({ courseDescription: event.target.value }); } handleUploadFile(event) { let selectedFile = event.target.files; let file = ''; let fileName = ''; let that = this; //Check File is not Empty if (selectedFile.length > 0) { // Select the very first file from list let fileToLoad = selectedFile[0]; fileName = fileToLoad.name; // FileReader function for read the file. let fileReader = new FileReader(); // Onload of file read the file content fileReader.onload = function(fileLoadedEvent) { file = fileLoadedEvent.target.result; that.setState({ file: file }); }; // Convert data to base64 fileReader.readAsDataURL(fileToLoad); } this.setState({ fileName: fileName }); } handleSubmit(event) { // Call preventDefault() on the event to prevent the browser's default // action of submitting the form. event.preventDefault(); this.setState({ inputError: '' }); const name = this.state.courseName; const description = this.state.courseDescription; const teacher = this.state.teacherName; const teacherId = this.state.id; const status = this.state.status; const date = this.state.date; const file = this.state.file; const fileName = this.state.fileName; let validateForm = function(arr) { for (var i = 0; i < arr.length; i++) { if (arr[i] == null || arr[i] == '') { return false; } } return true; }; let reqInputs = [ name, description, teacher, status, date, file, fileName, teacherId ]; if (validateForm(reqInputs)) { let formData = { name: name, description: description, teacher: teacher, teacher_id: teacherId, status: status, created_at: date, file_body: file, file_name: fileName }; createCourse(formData, () => { this.setState({ dialogAlert: true }); }); } else { this.setState({ inputError: 'All fields must be filled.' }); } } handleBack() { this.props.history.push('/dashboard'); } render() { const alertActions = [ <FlatButton label="Continue" style={{ color: '#4A90E2' }} primary={true} onTouchTap={this.handleBack} /> ]; return ( <div className={style.addCourse}> <Navbar {...this.props} /> <div className={style.container}> <h3>Add Course</h3> <TextField autoCorrect="none" autoCapitalize="none" type="text" floatingLabelText="Course Name" floatingLabelFixed={true} value={this.state.courseName} errorText={this.state.inputError} onChange={this.handleCourseNameChange} floatingLabelStyle={muiStyle.floatingLabelTextStyle} className={style.textFieldStyle} /> <TextField autoCorrect="none" autoCapitalize="none" type="text" floatingLabelText="Description" floatingLabelFixed={true} value={this.state.courseDescription} errorText={this.state.inputError} onChange={this.handleCourseDescrChange} floatingLabelStyle={muiStyle.floatingLabelTextStyle} className={style.textFieldStyle} multiLine={true} rows={5} rowsMax={10} /> <br /> <h4>Attention!</h4> <h5> <span>-</span> All course should be in one <span>PDF</span> file! </h5> <h5> <span>-</span> Please upload a <span>PDF</span> file! </h5> <br /> <RaisedButton label="Upload file" style={muiStyle.uploadButtonStyle} icon={<ContentAdd />} containerElement="label" onChange={this.handleUploadFile} > <input type="file" style={muiStyle.uploadInputStyle} /> </RaisedButton> <br /> <br /> <h5> File name: <span className={style.fileNameStyle}> {this.state.fileName}</span> </h5> <RaisedButton type="submit" label="Add course" onClick={this.handleSubmit} style={muiStyle.addButtonStyle} className={style.addButtonStyle} primary={true} /> </div> {/* Add Course Dialog */} <Dialog title="Success" titleStyle={muiStyle.dialogTitleStyle} actions={alertActions} modal={false} open={this.state.dialogAlert} > Your course has been successfully added!. </Dialog> </div> ); } } export default AddCourse; <file_sep>/app/components/Navbar/index.jsx import React from 'react'; import { NavLink } from 'react-router-dom'; // Material UI imports import AppBar from 'material-ui/AppBar'; import MenuIcon from 'material-ui/svg-icons/navigation/menu'; import IconMenu from 'material-ui/IconMenu'; import MenuItem from 'material-ui/MenuItem'; import BackButton from 'material-ui/IconButton'; import ActionHome from 'material-ui/svg-icons/action/home'; import IconButton from 'material-ui/IconButton'; import Divider from 'material-ui/Divider'; // Material UI Styles const muiStyle = { appbar: { backgroundColor: '#37BDD5' }, homeButtonStyle: { padding: 0, verticalAlign: 'text-top' } }; // Component Style import style from './style.less'; // Import static icons import { img } from '../../static'; class Navbar extends React.Component { constructor(props) { super(props); this.state = {}; } render() { let logo = ( <p className={style.title}> <img className={style.logoStyle} src={img.logo} />CodeStack </p> ); let actionHome = ( <BackButton style={muiStyle.homeButtonStyle} tooltip="Home" tooltipPosition="bottom-right" touch={true} > <NavLink to="/dashboard" style={{ textDecoration: 'none' }}> <ActionHome className={style.homeButton} /> </NavLink> </BackButton> ); if (this.props.history.location.pathname == '/dashboard') { actionHome = <div />; } // Navigation buttons according to user role let navButtons = <div />; let role = localStorage.user_role; if (role === 'ADMIN') { navButtons = ( <div> <NavLink to="/admin" style={{ textDecoration: 'none' }}> <MenuItem primaryText="Admin Panel" /> </NavLink> <NavLink to="/account" style={{ textDecoration: 'none' }}> <MenuItem primaryText="My Account" /> </NavLink> <Divider /> <NavLink to="/signout" style={{ textDecoration: 'none' }}> <MenuItem primaryText="Log Out" /> </NavLink> </div> ); } else if (role === 'TEACHER') { navButtons = ( <div> <NavLink to="/profile" style={{ textDecoration: 'none' }}> <MenuItem primaryText="View My Profile" /> </NavLink> <Divider /> <NavLink to="/addcourse" style={{ textDecoration: 'none' }}> <MenuItem primaryText="Add New Course" /> </NavLink> <NavLink to="/account" style={{ textDecoration: 'none' }}> <MenuItem primaryText="My Account" /> </NavLink> <Divider /> <NavLink to="/signout" style={{ textDecoration: 'none' }}> <MenuItem primaryText="Log Out" /> </NavLink> </div> ); } else if (role === 'STUDENT') { navButtons = ( <div> <NavLink to="/profile" style={{ textDecoration: 'none' }}> <MenuItem primaryText="View My Profile" /> </NavLink> <Divider /> <NavLink to="/account" style={{ textDecoration: 'none' }}> <MenuItem primaryText="My Account" /> </NavLink> <Divider /> <NavLink to="/signout" style={{ textDecoration: 'none' }}> <MenuItem primaryText="Log Out" /> </NavLink> </div> ); } return ( <div className={style.navbarContainer}> <AppBar zDepth={0} className={style.appbar} style={muiStyle.appbar} title={logo} iconElementLeft={actionHome} iconElementRight={ <IconMenu iconButtonElement={ <IconButton> <MenuIcon /> </IconButton> } targetOrigin={{ horizontal: 'right', vertical: 'top' }} anchorOrigin={{ horizontal: 'right', vertical: 'top' }} > {navButtons} </IconMenu> } /> </div> ); } } export default Navbar; <file_sep>/README.md # CodeStack React.js Web Application <!-- v1.0.0 --> Online Learning Programming Languages Web Application build with React.js [![GitHub version](https://badge.fury.io/gh/WhoSV%2Fcodestack.svg)](https://badge.fury.io/gh/WhoSV%2Fcodestack) [![TeamCity CodeBetter](https://img.shields.io/teamcity/codebetter/bt428.svg)](https://github.com/WhoSV/codestack) [![license](https://img.shields.io/github/license/mashape/apistatus.svg)](ttps://github.com/WhoSV/codestack) ![alternativetext](public/img/screenshot.png) ## Getting started **Clone the repo** $ git clone <repo> $ cd codestack **Install dependencies** $ npm install **Start Run** `$ npm start` This will initiate the project at `http://localhost:8080`. ## Build Package for Production For building once for production (via minification). Builds into `public/` as `bundle.js` `$ npm run build` ## Backend for this Application [CodeStack-Api](https://github.com/WhoSV/codestack-api) <file_sep>/app/components/Dashboard/Courses/index.jsx import React from 'react'; // Material UI imports import IconButton from 'material-ui/IconButton'; import Dialog from 'material-ui/Dialog'; import FlatButton from 'material-ui/FlatButton'; // Material UI Styles const muiStyle = { underlineStyle: { border: '0.5px solid #30CFD0' }, submitButton: { minWidth: 50, width: 50 }, submitButtonLabelStyle: { padding: 0 } }; // Component Style import style from './style.less'; // Import static Resources import { img } from '../../../static'; // Component Actions import { addToFavorite, getOpenCourse } from './actions'; class Courses extends React.Component { constructor(props) { super(); this.state = { dialogAlert: false, courseName: '', surveyCourseId: null }; } navigateToCourse(course) { getOpenCourse(course.id, data => { let link = 'data:application/pdf;base64,' + data; var iframe = "<iframe width='100%' height='100%' src='" + link + "' style='border: none; margin: 0; padding: 0;'></iframe>"; var x = window.open(); x.document.open(); x.document.write(iframe); x.document.close(); }); this.setState({ dialogAlert: true, courseName: course.name, surveyCourseId: course.id }); } addFavorite(course) { const userId = this.props.activeUser; const courseId = course.id; if (userId && courseId) { let formData = { user_id: userId, course_id: courseId }; addToFavorite(formData, () => { this.props.updateDashboard(); }); } } confirmPassSurvey() { localStorage.surveyCourseId = this.state.surveyCourseId; localStorage.course_name = this.state.courseName; this.props.goToSurvey(); } dialogClose() { this.setState({ dialogAlert: false }); } render() { const alertActions = [ <FlatButton label="No" style={{ color: '#747374' }} primary={true} onTouchTap={this.dialogClose.bind(this)} />, <FlatButton label="Yes" style={{ color: '#30cfd0' }} primary={true} onTouchTap={this.confirmPassSurvey.bind(this)} /> ]; return ( <div className={style.courses}> <div className={style.titleBar}> <h3>Available Courses</h3> </div> <div className={style.courseList}> {this.props.courses.map((course, index) => { if (course.status === 'ACTIVE') { return ( <div key={index} className={style.listItem}> <div className={style.listItemTitle}> <a className={style.courseTitle} onClick={this.navigateToCourse.bind(this, course)} > <h3> <img className={style.defaultIconStyle} src={img.defaultIcon} /> {course.name} </h3> </a> <div key={index} className={style.votesContainer}> <FlatButton label="Add to Favorite" style={{ color: '#4a90e2' }} primary={true} className={style.favoriteIconStyle} onTouchTap={this.addFavorite.bind(this, course)} /> </div> </div> <h5 className={style.listItemTeacher}> By: {course.teacher} </h5> <h5 className={style.listItemDate}> Date: {course.created_at} </h5> <p className={style.listItemDescription}> {course.description} </p> </div> ); } })} </div> {/* Survey Dialog */} <Dialog className={style.dialog} title="Survey" actions={alertActions} modal={false} open={this.state.dialogAlert} onRequestClose={this.dialogClose.bind(this)} > Do you want to pass <span className={style.highlight}>{this.state.courseName}</span> course survey? </Dialog> </div> ); } } export default Courses; <file_sep>/app/components/Register/index.jsx import React from 'react'; // Material UI imports import TextField from 'material-ui/TextField'; import FlatButton from 'material-ui/FlatButton'; import Paper from 'material-ui/Paper'; import MenuItem from 'material-ui/MenuItem'; import Dialog from 'material-ui/Dialog'; // Material UI Styles const muiStyle = { floatingLabelTextStyle: { fontWeight: 'normal' }, submitButton: { marginTop: 20, width: 260, marginBottom: 50 }, submitButtonText: { color: '#4A90E2' }, backButtonText: { color: '#30CFD0' }, errorStyle: { textAlign: 'center' }, dialogTitleStyle: { color: '#4CAF50' } }; // Component Actions import { createUser } from './actions'; // Component Style import style from './style.less'; // Import static Resources import { img } from '../../static'; class Register extends React.Component { constructor(props) { super(); this.state = { full_name: '', mail: '', role: 'STUDENT', password: '', confPassword: '', dialogAlert: false }; this.handleNameChange = this.handleNameChange.bind(this); this.handleMailChange = this.handleMailChange.bind(this); this.handlePasswordChange = this.handlePasswordChange.bind(this); this.handleConfPasswordChange = this.handleConfPasswordChange.bind(this); this.handleCreateUser = this.handleCreateUser.bind(this); this.handleBack = this.handleBack.bind(this); } handleNameChange(event) { this.setState({ full_name: event.target.value }); } handleMailChange(event) { this.setState({ mail: event.target.value }); } handlePasswordChange(event) { this.setState({ password: event.target.value }); } handleConfPasswordChange(event) { this.setState({ confPassword: event.target.value }); } handleCreateUser(event) { // Call preventDefault() on the event to prevent the browser's default // action of submitting the form. event.preventDefault(); this.setState({ inputError: '', passwordError: '', emailInputError: '' }); const full_name = this.state.full_name; const mail = this.state.mail; const role = this.state.role; const password = this.state.password; const confPassword = this.state.confPassword; const that = this; let validateForm = function(arr) { for (var i = 0; i < arr.length; i++) { if (arr[i] == null || arr[i] == '') { return false; } } return true; }; if (password == confPassword) { let reqInputs = [full_name, mail, role, password]; if (validateForm(reqInputs)) { let formData = { full_name: full_name, email: mail, role: role, password: <PASSWORD> }; createUser( formData, () => { this.setState({ full_name: '', mail: '', password: '', confPassword: '', dialogAlert: true }); }, error => { that.setState({ emailInputError: 'Email must be unique.' }); } ); } else { this.setState({ inputError: 'All fields must be filled.', passwordError: 'All fields must be filled.', emailInputError: 'All fields must be filled.' }); } } else { this.setState({ passwordError: '<PASSWORD>' }); } } handleBack() { this.props.history.push('/signout'); } render() { const alertActions = [ <FlatButton label="Continue" style={{ color: '#4CAF50' }} primary={true} onTouchTap={this.handleBack} /> ]; return ( <div className={style.bgStyle}> <div className={style.register}> <Paper zDepth={5}> <img className={style.logoImg} src={img.logo} /> <h3 className={style.title}>Register New Account</h3> <form onSubmit={this.handleCreateUser}> <TextField autoCorrect="none" autoCapitalize="none" hintText="<NAME>" type="text" floatingLabelText="Name & Surname" errorText={this.state.inputError} value={this.state.full_name} className={style.textFieldStyle} onChange={this.handleNameChange} floatingLabelStyle={muiStyle.floatingLabelTextStyle} /> <TextField autoCorrect="none" autoCapitalize="none" hintText="<EMAIL>" type="mail" floatingLabelText="Email" errorText={this.state.emailInputError} value={this.state.mail} className={style.textFieldStyle} onChange={this.handleMailChange} floatingLabelStyle={muiStyle.floatingLabelTextStyle} /> <TextField autoCorrect="none" autoCapitalize="none" hintText="********" type="password" floatingLabelText="Password" errorText={this.state.passwordError} value={this.state.password} className={style.textFieldStyle} onChange={this.handlePasswordChange} floatingLabelStyle={muiStyle.floatingLabelTextStyle} /> <TextField autoCorrect="none" autoCapitalize="none" hintText="********" type="password" floatingLabelText="Confirm Password" errorText={this.state.passwordError} value={this.state.confPassword} className={style.textFieldStyle} onChange={this.handleConfPasswordChange} floatingLabelStyle={muiStyle.floatingLabelTextStyle} /> <br /> <FlatButton type="submit" label="Register" backgroundColor="#F3F3F3" style={muiStyle.submitButton} labelStyle={muiStyle.submitButtonText} /> </form> <h6> If you want to register as a Teacher, please contact <br /> <a href="mailto:<EMAIL>" target="_top"> Support Team </a> </h6> <div className={style.backContainer}> <FlatButton type="submit" label="Back" style={muiStyle.backButton} onClick={this.handleBack} labelStyle={muiStyle.backButtonText} /> </div> </Paper> </div> {/* Created User Dialog */} <Dialog title="Success" titleStyle={muiStyle.dialogTitleStyle} actions={alertActions} modal={false} open={this.state.dialogAlert} > User created successfully, please login to continue!. </Dialog> </div> ); } } export default Register; <file_sep>/app/components/Dashboard/CourseBar/index.jsx import React from 'react'; // Material UI imports import IconButton from 'material-ui/IconButton'; import ActionRemove from 'material-ui/svg-icons/content/remove-circle-outline'; // Component Style import style from './style.less'; // Import static Resources import { img } from '../../../static'; // Component Actions import { getOpenCourse, deleteFavorite } from './actions'; class CourseBar extends React.Component { constructor(props) { super(props); this.state = {}; } navigateToCourse(course) { getOpenCourse(course.id, data => { let link = 'data:application/pdf;base64,' + data; var iframe = "<iframe width='100%' height='100%' src='" + link + "' style='border: none; margin: 0; padding: 0;'></iframe>"; var x = window.open(); x.document.open(); x.document.write(iframe); x.document.close(); }); } removeFavorite(favorite) { deleteFavorite(favorite.id, res => { this.props.updateDashboard(); }); } render() { return ( <div className={style.courseBar}> <h3 className={style.title}>Favorite Courses</h3> {this.props.favorites.map((favorite, index) => { if (this.props.activeUser === favorite.user_id) { return this.props.courses.map((course, index) => { if (favorite.course_id === course.id) { return ( <div key={index} className={style.selectedCourseContainer}> <div className={style.selectedCourseItem}> <div onClick={this.navigateToCourse.bind(this, course)} className={style.imgContainer} > <img className={style.defaultIconStyle} src={img.defaultIcon} /> </div> <h4 onClick={this.navigateToCourse.bind(this, course)}> {course.name} </h4> <IconButton tooltip="Remove Favorite" tooltipPosition="bottom-left" touch={true} onClick={this.removeFavorite.bind(this, favorite)} > <ActionRemove className={style.removeButton} /> </IconButton> </div> </div> ); } }); } })} </div> ); } } export default CourseBar; <file_sep>/app/components/AdminPanel/UserContainer/index.jsx import React from 'react'; // Component's paths import CreateUserForm from './CreateUserForm'; import UsersTable from './UsersTable'; // Component Style import style from './style'; // Component Actions import { getUsers } from './actions'; export default class UserContainer extends React.Component { constructor(props) { super(props); this.state = { users: [] }; } componentWillMount() { this.updateUsers(); } changeOnUserList() { this.updateUsers(); } updateUsers() { getUsers(data => { this.setState({ users: data }); }); } render() { return ( <div className={style.userContainerStyle}> <CreateUserForm changeOnUserList={this.changeOnUserList.bind(this)} /> <UsersTable users={this.state.users} changeOnUserList={this.changeOnUserList.bind(this)} /> </div> ); } } <file_sep>/app/components/Account/index.jsx import React from 'react'; // Material UI imports import FlatButton from 'material-ui/FlatButton'; import TextField from 'material-ui/TextField'; import Dialog from 'material-ui/Dialog'; // Import components import Navbar from '../Navbar'; // Import static icons import { img } from '../../static'; // Material UI Styles const muiStyle = { floatingLabelTextStyle: { fontWeight: 'normal' }, uploadButtonStyle: { verticalAlign: 'middle' }, uploadInputStyle: { cursor: 'pointer', position: 'absolute', top: 0, bottom: 0, right: 0, left: 0, width: '100%', opacity: 0 }, uploadButtonLabelStyle: { color: '#4A4A4A' } }; // Component Style import style from './style.less'; // Component Actions import { deleteUser, updateUser, getUser, updateUserPassword } from './actions'; class Account extends React.Component { constructor(props) { super(); this.state = { id: '', name: '', email: '', password: '', confPassword: '', oldPassword: '', dialogDelete: false, deleteUser: {}, dialogSuccess: false }; this.changeAccountInfo = this.changeAccountInfo.bind(this); this.handleNameChange = this.handleNameChange.bind(this); this.handleEmailChange = this.handleEmailChange.bind(this); this.changePasswordAction = this.changePasswordAction.bind(this); this.handleDeleteAccount = this.handleDeleteAccount.bind(this); this.handleNewPasswordChange = this.handleNewPasswordChange.bind(this); this.handleNewConfPassChange = this.handleNewConfPassChange.bind(this); this.handleOldPassword = this.handleOldPassword.bind(this); this.handleSignOut = this.handleSignOut.bind(this); } componentWillMount() { this.state.id = localStorage.id; this.activeUser(); } activeUser() { getUser(this.state.id, data => { this.setState({ id: data.id, name: data.full_name, email: data.email }); }); } handleNameChange(event) { this.setState({ name: event.target.value }); } handleEmailChange(event) { this.setState({ email: event.target.value }); } handleNewPasswordChange(event) { this.setState({ password: event.target.value }); } handleNewConfPassChange(event) { this.setState({ confPassword: event.target.value }); } handleOldPassword(event) { this.setState({ oldPassword: event.target.value }); } handleDeleteAccount() { this.setState({ dialogDelete: true }); } dialogClose() { this.setState({ dialogDelete: false }); } confirmDeleteAccount() { deleteUser(this.state.id, res => { this.setState({ deleteUser: {} }); this.props.history.push('/signout'); }); } changeAccountInfo(event) { // Call preventDefault() on the event to prevent the browser's default // action of submitting the form. event.preventDefault(); this.setState({ inputAccError: '', emailInputError: '' }); const id = this.state.id; const name = this.state.name; const email = this.state.email; const that = this; let validateForm = function(arr) { for (var i = 0; i < arr.length; i++) { if (arr[i] == null || arr[i] == '') { return false; } } return true; }; let reqInputs = [id, name, email]; if (validateForm(reqInputs)) { let formData = { id: id, full_name: name, email: email }; updateUser( formData, () => {}, error => { that.setState({ emailInputError: 'Email must be unique.' }); } ); } else { this.setState({ inputAccError: 'All fields must be filled.', emailInputError: 'All fields must be filled.' }); } } changePasswordAction(event) { // Call preventDefault() on the event to prevent the browser's default // action of submitting the form. event.preventDefault(); this.setState({ inputError: '', passwordError: '', oldPasswordError: '' }); const id = this.state.id; const password = this.state.password; const confPassword = this.state.confPassword; const oldPassword = this.state.oldPassword; let validateForm = function(arr) { for (var i = 0; i < arr.length; i++) { if (arr[i] == null || arr[i] == '') { return false; } } return true; }; if (password != confPassword) { this.setState({ passwordError: 'Passwords are not identical' }); } if (!oldPassword) { this.setState({ oldPasswordError: 'All fields must be filled.' }); } let reqInputs = [id, oldPassword, password]; if (validateForm(reqInputs)) { let formData = { id: id, new_password: <PASSWORD>, password: <PASSWORD> }; updateUserPassword(formData, () => { this.setState({ dialogSuccess: true }); }); } else { this.setState({ inputError: 'All fields must be filled.', passwordError: 'All fields must be filled.', oldPasswordError: 'All fields must be filled.' }); } } handleSignOut() { this.props.history.push('/signout'); } render() { const deleteActions = [ <FlatButton label="Cancel" style={{ color: '#747374' }} primary={true} onTouchTap={this.dialogClose.bind(this)} />, <FlatButton label="Delete" style={{ color: '#ff0000' }} primary={true} onTouchTap={this.confirmDeleteAccount.bind(this)} /> ]; const successActions = [ <FlatButton label="Continue" style={{ color: '#4CAF50' }} primary={true} onTouchTap={this.handleSignOut} /> ]; return ( <div className={style.account}> <Navbar {...this.props} /> <div className={style.container}> <h3>Account Information</h3> <TextField autoCorrect="none" autoCapitalize="none" hintText="<NAME>" type="text" floatingLabelText="Name & Surname" errorText={this.state.inputAccError} value={this.state.name} className={style.textFieldStyle} onChange={this.handleNameChange} floatingLabelStyle={muiStyle.floatingLabelTextStyle} /> <TextField autoCorrect="none" autoCapitalize="none" hintText="<EMAIL>" type="email" floatingLabelText="Email" errorText={this.state.emailInputError} value={this.state.email} className={style.textFieldStyle} onChange={this.handleEmailChange} floatingLabelStyle={muiStyle.floatingLabelTextStyle} /> <FlatButton label="SAVE CHANGES" style={{ color: '#fff', marginTop: '30px' }} backgroundColor="#37BDD5" onClick={this.changeAccountInfo} /> </div> <div className={style.container}> <h3>Change Password</h3> <p> Please insert new password, confirmation and your current password. </p> <TextField autoCorrect="none" autoCapitalize="none" hintText="********" type="password" floatingLabelText="New Password" errorText={this.state.passwordError} value={this.state.password} className={style.textFieldStyle} onChange={this.handleNewPasswordChange} floatingLabelStyle={muiStyle.floatingLabelTextStyle} /> <TextField autoCorrect="none" autoCapitalize="none" hintText="********" type="password" floatingLabelText="Confirm New Password" errorText={this.state.passwordError} value={this.state.confPassword} className={style.textFieldStyle} onChange={this.handleNewConfPassChange} floatingLabelStyle={muiStyle.floatingLabelTextStyle} /> <TextField autoCorrect="none" autoCapitalize="none" hintText="********" type="password" floatingLabelText="Current Password" errorText={this.state.oldPasswordError} value={this.state.oldPassword} className={style.textFieldStyle} onChange={this.handleOldPassword} floatingLabelStyle={muiStyle.floatingLabelTextStyle} /> <FlatButton label="CHANGE PASSWORD" style={{ color: '#fff', marginTop: '30px' }} backgroundColor="#37BDD5" onClick={this.changePasswordAction} /> </div> <div className={style.container}> <h3>Delete Account</h3> <p> You may delete your account at any time. However, this action is irreversibile. </p> <FlatButton label="I UNDERSTAND, DELETE MY ACCOUNT" style={{ color: '#fff', marginTop: '20px' }} backgroundColor="#f00" onClick={this.handleDeleteAccount} /> </div> {/* Delete account dialog */} <Dialog className={style.dialog} title="Delete Account" actions={deleteActions} modal={false} open={this.state.dialogDelete} onRequestClose={this.dialogClose.bind(this)} > Do you realy want to delete your account? </Dialog> {/* Updated User Password Dialog */} <Dialog title="Success" titleStyle={muiStyle.dialogTitleStyle} actions={successActions} modal={false} open={this.state.dialogSuccess} > Your password has been updated successfully, please login to continue!. </Dialog> </div> ); } } export default Account; <file_sep>/app/components/AdminPanel/ContentContainer/index.jsx import React from 'react'; // Material UI imports import { Table, TableBody, TableHeader, TableHeaderColumn, TableRow, TableRowColumn } from 'material-ui/Table'; import IconButton from 'material-ui/IconButton'; import FlatButton from 'material-ui/FlatButton'; import Dialog from 'material-ui/Dialog'; import ActionDelete from 'material-ui/svg-icons/action/delete'; import ActionBlock from 'material-ui/svg-icons/content/block'; // Material UI Styles const muiStyle = { paper: { padding: '0px 50px 50px 50px' }, floatingLabelStyle: { fontWeight: 'normal' }, iconDeleteButton: { color: '#424242' }, iconBlockButton: { color: '#ff0000' }, iconUnblockButton: { color: '#ccc' }, iconButton: { zIndex: '9999 !important' } }; // Component Actions import { getCourses, deleteCourse, updateCourseStatus } from './actions'; // Component Style import style from './style'; export default class ContentContainer extends React.Component { constructor(props) { super(props); this.state = { dialogDelete: false, dialogBlock: false, dialogUnblock: false, courses: [], course: {} }; } componentWillMount() { this.updateCourses(); } updateCourses() { getCourses(data => { this.setState({ courses: data }); }); } dialogClose() { this.setState({ dialogDelete: false, dialogBlock: false, dialogUnblock: false }); } handleDeleteContent(course) { this.setState({ dialogDelete: true, course: course }); } handleBlockContent(course) { this.setState({ dialogBlock: true, course: course }); } handleUnblockContent(course) { this.setState({ dialogUnblock: true, course: course }); } confirmDeleteContent() { deleteCourse(this.state.course.id, res => { this.setState({ dialogDelete: false, course: {} }); this.updateCourses(); }); } confirmBlockContent() { // Call preventDefault() on the event to prevent the browser's default // action of submitting the form. event.preventDefault(); const id = this.state.course.id; let status = 'BLOCKED'; let reqInputs = [id, status]; if (reqInputs) { let formData = { id: id, status: status }; updateCourseStatus(formData, () => { this.setState({ dialogBlock: false, course: {} }); this.updateCourses(); }); } } confirmUnblockContent() { // Call preventDefault() on the event to prevent the browser's default // action of submitting the form. event.preventDefault(); const id = this.state.course.id; let status = 'ACTIVE'; let reqInputs = [id, status]; if (reqInputs) { let formData = { id: id, status: status }; updateCourseStatus(formData, () => { this.setState({ dialogUnblock: false, course: {} }); this.updateCourses(); }); } } render() { const deleteActions = [ <FlatButton label="Cancel" style={{ color: '#747374' }} primary={true} onTouchTap={this.dialogClose.bind(this)} />, <FlatButton label="Delete" style={{ color: '#ff0000' }} primary={true} onTouchTap={this.confirmDeleteContent.bind(this)} /> ]; const blockActions = [ <FlatButton label="Cancel" style={{ color: '#747374' }} primary={true} onTouchTap={this.dialogClose.bind(this)} />, <FlatButton label="Block" style={{ color: '#ff0000' }} primary={true} onTouchTap={this.confirmBlockContent.bind(this)} /> ]; const unblockActions = [ <FlatButton label="Cancel" style={{ color: '#747374' }} primary={true} onTouchTap={this.dialogClose.bind(this)} />, <FlatButton label="Unblock" style={{ color: '#ff0000' }} primary={true} onTouchTap={this.confirmUnblockContent.bind(this)} /> ]; return ( <div className={style.contentContainerStyle}> <h3 className={style.title}>Courses Table</h3> <Table selectable={false}> <TableHeader displaySelectAll={false} adjustForCheckbox={false}> <TableRow> <TableHeaderColumn>Name</TableHeaderColumn> <TableHeaderColumn>Teacher</TableHeaderColumn> <TableHeaderColumn>Status</TableHeaderColumn> <TableHeaderColumn>Options</TableHeaderColumn> </TableRow> </TableHeader> <TableBody displayRowCheckbox={false}> {this.state.courses.map((course, index) => { return ( <TableRow key={index}> <TableRowColumn>{course.name}</TableRowColumn> <TableRowColumn>{course.teacher}</TableRowColumn> <TableRowColumn> {(() => { if (course.status === 'ACTIVE') { return ( <span style={{ color: '#0080FF' }}> {course.status} </span> ); } if (course.status === 'BLOCKED') { return ( <span style={{ color: '#F44336' }}> {course.status} </span> ); } })()} </TableRowColumn> <TableRowColumn> {(() => { if (course.status == 'ACTIVE') { return ( <IconButton onTouchTap={this.handleBlockContent.bind( this, course )} style={muiStyle.iconButton} className={style.iconButtonStyle} iconStyle={muiStyle.iconUnblockButton} touch={true} tooltip="Block" tooltipPosition="bottom-left" > <ActionBlock /> </IconButton> ); } else { return ( <IconButton onTouchTap={this.handleUnblockContent.bind( this, course )} style={muiStyle.iconButton} className={style.iconButtonStyle} iconStyle={muiStyle.iconBlockButton} touch={true} tooltip="Unblock" tooltipPosition="bottom-left" > <ActionBlock /> </IconButton> ); } })()} <IconButton onTouchTap={this.handleDeleteContent.bind(this, course)} style={muiStyle.iconButton} className={style.iconButtonStyle} iconStyle={muiStyle.iconDeleteButton} touch={true} tooltip="Delete" tooltipPosition="bottom-center" > <ActionDelete /> </IconButton> </TableRowColumn> </TableRow> ); })} </TableBody> </Table> {/* Delete Content Dialog */} <Dialog className={style.dialog} title="Delete Course" actions={deleteActions} modal={false} open={this.state.dialogDelete} onRequestClose={this.dialogClose.bind(this)} > Do you realy want to delete <span className={style.highlight}>{this.state.course.name}</span> ? </Dialog> {/* Unblock Content Dialog */} <Dialog className={style.dialog} title="Unblock Course" actions={unblockActions} modal={false} open={this.state.dialogUnblock} onRequestClose={this.dialogClose.bind(this)} > Do you realy want to unblock <span className={style.highlight}>{this.state.course.name}</span> ? </Dialog> {/* Block Content Dialog */} <Dialog className={style.dialog} title="Block Course" actions={blockActions} modal={false} open={this.state.dialogBlock} onRequestClose={this.dialogClose.bind(this)} > Do you realy want to block <span className={style.highlight}>{this.state.course.name}</span> ? </Dialog> </div> ); } } <file_sep>/app/components/SignIn/actions.js import axios from 'axios'; import { AUTH_URL } from '../../config/consts'; export function authUser(email, password, scc, err) { axios({ method: 'post', headers: {}, responseType: 'json', url: AUTH_URL, data: { email: email, password: <PASSWORD> } }) .then(function(res) { localStorage.token = res.data.token; localStorage.id = res.data.id; localStorage.user_role = res.data.user_role; scc(); }) .catch(function(error) { err(error); }); } export function getToken() { return localStorage.token; } <file_sep>/app/components/Survey/index.jsx import React from 'react'; // Material UI imports import { RadioButton, RadioButtonGroup } from 'material-ui/RadioButton'; import Paper from 'material-ui/Paper'; import FlatButton from 'material-ui/FlatButton'; // Import components import Navbar from '../Navbar'; // Component Style import style from './style.less'; // Component Actions import { createSurvey } from './actions'; // Material UI Styles const muiStyle = { radioLabelStyle: { fontWeight: 'normal' }, submitButton: { marginBottom: 20, width: 260 }, submitButtonText: { color: '#4A90E2' } }; class Survey extends React.Component { constructor(props) { super(props); this.state = { isEmpty: true }; this.handleFirstChange = this.handleFirstChange.bind(this); this.handleSecondChange = this.handleSecondChange.bind(this); this.handleThirdChange = this.handleThirdChange.bind(this); this.handleFourthChange = this.handleFourthChange.bind(this); this.handleFifthChange = this.handleFifthChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } handleFirstChange(event) { this.setState({ first: event.target.value, isEmpty: false }); } handleSecondChange(event) { this.setState({ second: event.target.value, isEmpty: false }); } handleThirdChange(event) { this.setState({ third: event.target.value, isEmpty: false }); } handleFourthChange(event) { this.setState({ fourth: event.target.value, isEmpty: false }); } handleFifthChange(event) { this.setState({ fifth: event.target.value, isEmpty: false }); } handleSubmit(event) { let first = this.state.first; let second = this.state.second; let third = this.state.third; let fourth = this.state.fourth; let fifth = this.state.fifth; let courseId = localStorage.surveyCourseId; let validateForm = function(arr) { for (var i = 0; i < arr.length; i++) { if (arr[i] == null || arr[i] == '') { return false; } } return true; }; let reqInputs = [courseId, first, second, third, fourth, fifth]; if (validateForm(reqInputs)) { let formData = { course_id: parseInt(courseId, 10), first: parseInt(first, 10), second: parseInt(second, 10), third: parseInt(third, 10), fourth: parseInt(fourth, 10), fifth: parseInt(fifth, 10) }; createSurvey(formData, () => { this.props.history.push('/dashboard'); }); } } render() { return ( <div className={style.survey}> <Navbar {...this.props} /> <Paper className={style.paper} zDepth={2}> <h1>{localStorage.course_name} Course Survey</h1> <div className={style.questionContainer}> <h4>1. Where course objectives clear?</h4> <RadioButtonGroup name="q1" className={style.buttonsContainer} onChange={this.handleFirstChange} > <RadioButton value={1} label="Strongly Disgree" labelStyle={muiStyle.radioLabelStyle} className={style.radioButton} /> <RadioButton value={2} label="Disagree" labelStyle={muiStyle.radioLabelStyle} className={style.radioButton} /> <RadioButton value={3} label="Neutral" labelStyle={muiStyle.radioLabelStyle} className={style.radioButton} /> <RadioButton value={4} label="Agree" labelStyle={muiStyle.radioLabelStyle} className={style.radioButton} /> <RadioButton value={5} label="Strongly Agree" labelStyle={muiStyle.radioLabelStyle} className={style.radioButton} /> </RadioButtonGroup> </div> <div className={style.questionContainer}> <h4>2. Were the course textnotes clear and well written?</h4> <RadioButtonGroup name="q2" className={style.buttonsContainer} onChange={this.handleSecondChange} > <RadioButton value={1} label="Strongly Disgree" labelStyle={muiStyle.radioLabelStyle} className={style.radioButton} /> <RadioButton value={2} label="Disagree" labelStyle={muiStyle.radioLabelStyle} className={style.radioButton} /> <RadioButton value={3} label="Neutral" labelStyle={muiStyle.radioLabelStyle} className={style.radioButton} /> <RadioButton value={4} label="Agree" labelStyle={muiStyle.radioLabelStyle} className={style.radioButton} /> <RadioButton value={5} label="Strongly Agree" labelStyle={muiStyle.radioLabelStyle} className={style.radioButton} /> </RadioButtonGroup> </div> <div className={style.questionContainer}> <h4> 3. Where the assignments appropriate for the level of this class? </h4> <RadioButtonGroup name="q3" className={style.buttonsContainer} onChange={this.handleThirdChange} > <RadioButton value={1} label="Strongly Disgree" labelStyle={muiStyle.radioLabelStyle} className={style.radioButton} /> <RadioButton value={2} label="Disagree" labelStyle={muiStyle.radioLabelStyle} className={style.radioButton} /> <RadioButton value={3} label="Neutral" labelStyle={muiStyle.radioLabelStyle} className={style.radioButton} /> <RadioButton value={4} label="Agree" labelStyle={muiStyle.radioLabelStyle} className={style.radioButton} /> <RadioButton value={5} label="Strongly Agree" labelStyle={muiStyle.radioLabelStyle} className={style.radioButton} /> </RadioButtonGroup> </div> <div className={style.questionContainer}> <h4>4. Have this course increased my interest in the subject?</h4> <RadioButtonGroup name="q4" className={style.buttonsContainer} onChange={this.handleFourthChange} > <RadioButton value={1} label="Strongly Disgree" labelStyle={muiStyle.radioLabelStyle} className={style.radioButton} /> <RadioButton value={2} label="Disagree" labelStyle={muiStyle.radioLabelStyle} className={style.radioButton} /> <RadioButton value={3} label="Neutral" labelStyle={muiStyle.radioLabelStyle} className={style.radioButton} /> <RadioButton value={4} label="Agree" labelStyle={muiStyle.radioLabelStyle} className={style.radioButton} /> <RadioButton value={5} label="Strongly Agree" labelStyle={muiStyle.radioLabelStyle} className={style.radioButton} /> </RadioButtonGroup> </div> <div className={style.questionContainer}> <h4>5. Is this course corresponded to my expectations?</h4> <RadioButtonGroup name="q5" className={style.buttonsContainer} onChange={this.handleFifthChange} > <RadioButton value={1} label="Strongly Disgree" labelStyle={muiStyle.radioLabelStyle} className={style.radioButton} /> <RadioButton value={2} label="Disagree" labelStyle={muiStyle.radioLabelStyle} className={style.radioButton} /> <RadioButton value={3} label="Neutral" labelStyle={muiStyle.radioLabelStyle} className={style.radioButton} /> <RadioButton value={4} label="Agree" labelStyle={muiStyle.radioLabelStyle} className={style.radioButton} /> <RadioButton value={5} label="Strongly Agree" labelStyle={muiStyle.radioLabelStyle} className={style.radioButton} /> </RadioButtonGroup> </div> <FlatButton label="Submit" onClick={this.handleSubmit} primary={true} disabled={this.state.isEmpty} style={muiStyle.submitButton} /> </Paper> </div> ); } } export default Survey;
ae58b2aaff6a3622525f66b5d3274ddecc3f4f67
[ "JavaScript", "Markdown" ]
14
JavaScript
WhoSV/codestack
b59b351278381bbfecb1c0455807583fffd69df2
f5b2a7385531e1b87ece89405c10b6458a142b5e
refs/heads/master
<repo_name>Appalled/dj_blog<file_sep>/article/models.py from django.db import models class Article(models.Model): title = models.CharField(max_length = 100) #title category = models.CharField(max_length = 50, blank = True) #Cate date_time = models.DateTimeField(auto_now = True) #Date content = models.TextField(blank = True, null = True) #Content def __str__(self): return self.title class Meta: #Desending by Date order = ['-date_time']<file_sep>/article/views.py from article.models import Article from django.http import HttpResponse from django.shortcuts import render # Create your views here. def home(request): return HttpResponse("Hello World, Django") def detail(request, my_args): post = Article.objects.all()[my_args] str = ("title = %s, category = %s, date_time = %s, content = %s" % (post.title, post.category, post.date_time, post.content)) return HttpResponse(str)
3468bc2389ee63af48fb7853f14ce33863097310
[ "Python" ]
2
Python
Appalled/dj_blog
87e415fac748b9a569335422a168a9045fa8df8b
97018c3787421af320c7c927845239b6a783d921
refs/heads/master
<repo_name>Palevoda/OOTP-12<file_sep>/Лабораторная работа 12/Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; namespace Лабораторная_работа_12 { class Program { static void Main(string[] args) { Airline airline = new Airline(); Airoport port = new Airoport("Минск-2"); IPOP_NAOBOROT port1 = new Airoport("Минск-1"); port1.show(); //a Reflector.AssName(airline); Reflector.AssName(port); //b Reflector.PublicConstructorsInfo(airline); Reflector.PublicConstructorsInfo(port); //c IEnumerable<string> air_method_info = Reflector.CommonAvaliableMethods(airline); IEnumerable<string> port_method_info = Reflector.CommonAvaliableMethods(port); Console.WriteLine("\n\n"); foreach (string el in air_method_info) Console.WriteLine(el); Console.WriteLine("\n\n"); foreach (string el in port_method_info) Console.WriteLine(el); //d IEnumerable<string> air_method_and_prop = Reflector.InfoAboutMethodsAndProperties(airline); IEnumerable<string> port_method_and_prop = Reflector.InfoAboutMethodsAndProperties(port); foreach (string el in air_method_and_prop) Console.WriteLine(el); Console.WriteLine("\n\n"); foreach (string el in port_method_and_prop) Console.WriteLine(el); Console.WriteLine("\n\n"); //e IEnumerable<string> air_interfaces = Reflector.InfoAboutInterfaces(airline); IEnumerable<string> port_interfaces = Reflector.InfoAboutInterfaces(port); foreach (string el in air_interfaces) Console.WriteLine(el); Console.WriteLine("\n\n"); foreach (string el in port_interfaces) Console.WriteLine(el); Console.WriteLine("\n\n"); //f IEnumerable<string> air_param_methods = Reflector.MethodsWithUserParametrsInfo(airline); IEnumerable<string> port_param_methods = Reflector.MethodsWithUserParametrsInfo(port); foreach (string el in air_param_methods) Console.WriteLine(el); Console.WriteLine("\n\n"); foreach (string el in port_param_methods) Console.WriteLine(el); Console.WriteLine("\n\n"); // g StreamReader reader = new StreamReader("Reflector.txt"); string fname = reader.ReadLine(); string values = reader.ReadLine(); Reflector.Invoke(typeof(Reflector), fname, (typeof(string), values)); reader.Close(); // 2 var someClass = Reflector.Create<Airline>(); someClass.showObjectInfo(); } } public static class Reflector { public static void AssName(object tested_class) { Type type = tested_class.GetType(); StreamWriter stream = new StreamWriter($"Информация о классе {type.Name}.txt"); stream.WriteLine($"===>Основная информация<==="); stream.WriteLine($"Полное имя класса: {type.FullName} "); stream.WriteLine($"Информация о сборке: {type.Assembly} "); stream.WriteLine($"Globally Unique Identifier: {type.GUID}"); stream.Close(); } public static void PublicConstructorsInfo(object tested_class) { Type type = tested_class.GetType(); StreamWriter stream = new StreamWriter($"Публичные конструкторы класса {type.Name}.txt"); stream.WriteLine($"===>Основная информация<==="); foreach (MemberInfo el in type.GetConstructors()) { stream.WriteLine($" {el} "); } stream.Close(); } public static IEnumerable<string> CommonAvaliableMethods(object tested_class) { Type type = tested_class.GetType(); StreamWriter stream = new StreamWriter($"Общедоступные методы класса {type.Name}.txt"); stream.WriteLine($"===>Основная информация<==="); IEnumerable<string> AvaliableMethods = type.GetMethods().Select(n => Convert.ToString(n)); foreach (MemberInfo el in type.GetMethods()) { stream.WriteLine($" {el} "); } stream.Close(); return AvaliableMethods; } public static IEnumerable<string> InfoAboutMethodsAndProperties(object tested_class) { Type type = tested_class.GetType(); StreamWriter stream = new StreamWriter($"Методы и свойства класса {type.Name}.txt"); stream.WriteLine($"===>Информация о методах и свойствах класса {type.Name} <==="); foreach (MemberInfo el in type.GetMembers()) stream.WriteLine(el); stream.Close(); IEnumerable<string> MethodsAndProperties = type.GetMembers().Select(n => Convert.ToString(n)); return MethodsAndProperties; } public static IEnumerable<string> InfoAboutInterfaces(object tested_class) { Type type = tested_class.GetType(); StreamWriter stream = new StreamWriter($"Интерфейсы класса {type.Name}.txt"); stream.WriteLine($"===>Интерфейсы класса {type.Name} <==="); foreach (MemberInfo el in type.GetInterfaces()) stream.WriteLine(el); stream.Close(); IEnumerable<string> Interfaces = type.GetInterfaces().Select(n => Convert.ToString(n)); return Interfaces; } public static IEnumerable<string> MethodsWithUserParametrsInfo(object tested_class) { Type type = tested_class.GetType(); MethodInfo[] methodInfo = type.GetMethods(); StreamWriter stream = new StreamWriter($"Методы с парам класса {type.Name}.txt"); stream.WriteLine($"===>Основная информация<==="); IEnumerable<string> AvaliableMethods = methodInfo.Where(n => n.GetParameters().Length != 0).Select(n => Convert.ToString(n)); foreach (MethodInfo el in type.GetMethods()) { if (el.GetParameters().Length != 0) stream.WriteLine($" {el} "); } stream.Close(); return AvaliableMethods; } public static void Invoke(Type type, string methodName, params (Type type, object value)[] paramTuples) { var paramsTypes = paramTuples.Select(item => item.type).ToArray(); var paramsValues = paramTuples.Select(item => item.value).ToArray(); var method = type.GetMethod(methodName, paramsTypes); if (method == null) { Console.WriteLine("Метод не найден"); return; } method.Invoke(null, paramsValues); } public static void write(string str) { Console.WriteLine(str); } public static UserType Create<UserType>() { var type = typeof(UserType); Type[] types = new Type[0]; var constructor = type.GetConstructor(types); return (UserType)constructor.Invoke(null); } } interface IPOP_NAOBOROT { void show(); } public class Airoport : IPOP_NAOBOROT { string City; void IPOP_NAOBOROT.show() { Console.WriteLine($"Аэропорт находится в городе {City}"); } public string city { get { return City; } } public void show(Airoport kek) { Console.WriteLine(kek.City); } public Airoport(string city) { City = city; } } public partial class Airline { private static int CurrentSize = 0; private const int ArchiveMaxSize = 100; private DateTime date = new DateTime(2020, 12, 04, 0, 0, 0); public DateTime Date { get { return date; } } private int dist; public int Dist { set { dist = value; } get { return dist; } } private String Punct; public String punct { set { Punct = value; } get { return Punct; } } private int flightNumber; public int FlightNumber { private set { flightNumber = value; } get { return flightNumber; } } private String planeType; public String PlaneType { set { planeType = value; } get { return planeType; } } private String depatureTime; public String DepartureTime { set { depatureTime = value; } get { return depatureTime; } } private String WeekDay; public String weekDay { set { WeekDay = value; } get { return WeekDay; } } private const String developer = "Palevoda POIT-4"; Airline[] Archive = new Airline[ArchiveMaxSize]; static string status = "Стркутура структура не использовалась"; //обычный конструктор static Airline() { status = "Был использован приватный конструктор"; } public override bool Equals(object obj) { Airline flight = (Airline)obj; if (this.flightNumber == flight.flightNumber) return true; else return false; } public override string ToString() { return "Номер рейса: " + this.flightNumber + ", Пункт назначения: " + this.Punct + ", Время вылета: " + this.Date + " День вылета: " + this.weekDay + " дальность полета " + this.dist; } private int upgradeHashCodeRef(ref int hash) { hash /= 1000; return hash; } private void upgradeHashCodeOut(out int hash) { hash = 123456; } public Airline() { punct = "Неизвестно"; flightNumber = 0; planeType = "Неизвестно"; depatureTime = "Неизвестно"; weekDay = "Неизвестно"; CurrentSize++; } public Airline(String Punct, String DepatureTime) { punct = Punct; flightNumber = 0; planeType = "Неизвестно"; depatureTime = DepatureTime; weekDay = "Неизвестно"; CurrentSize++; } public Airline(String newPunct, ushort newFlightNumber, String newPlaneType, String newdepatureTime, String newWeekDay, int newdist) { punct = newPunct; //flightNumber = newFlightNumber; this.flightNumber = GetHashCode(); planeType = newPlaneType; depatureTime = newdepatureTime; weekDay = newWeekDay; //upgradeHashCodeOut(out this.flightNumber); upgradeHashCodeRef(ref this.flightNumber); dist = newdist; CurrentSize++; Random rand = new Random(); date = date.AddHours(Convert.ToDouble(rand.Next(0, 24))); date = date.AddMinutes(Convert.ToDouble(rand.Next(0, 60))); } public void showObjectInfo() { Console.WriteLine("\n========================================"); Console.WriteLine("::" + Airline.status); Console.WriteLine($"\nПункт назначения: {punct} \nНомер рейса: {flightNumber} \nТип рейса: { planeType} \nВремя отправления: {date} \nДень отправления: {weekDay} \nДальность полета: {dist} "); Console.WriteLine($"=============={CurrentSize}=================="); } } }
d87daf26e51e1cad088d059cb5fa55abff5bad95
[ "C#" ]
1
C#
Palevoda/OOTP-12
9da91d43d864892f3b02f23feb636b144cac43c4
7efabe9dd112bbce31623bb45a73363bf00ea853
refs/heads/master
<file_sep>import csv import operator from collections import defaultdict from copy import deepcopy import numpy from fastgp.algorithms import afpo from fastgp.utilities import symbreg class FitnessDistributionArchive(object): def __init__(self, frequency): self.fitness = [] self.generations = [] self.frequency = frequency self.generation_counter = 0 def update(self, population): if self.generation_counter % self.frequency == 0: fitnesses = [ind.fitness.values for ind in population] self.fitness.append(fitnesses) self.generations.append(self.generation_counter) self.generation_counter += 1 def save(self, log_file): fitness_distribution_file = "fitness_" + log_file with open(fitness_distribution_file, 'wb') as f: writer = csv.writer(f) for gen, ages in zip(self.generations, self.fitness): writer.writerow([gen, ages]) def pick_fitness_size_from_fitness_age_size(ind): ind.fitness.values = (ind.error, 0, len(ind)) def pick_fitness_complexity_from_fitness_age_complexity(ind): ind.fitness.values = (ind.error, 0, symbreg.calculate_order(ind)) def pick_fitness_size_complexity_from_fitness_age_size_complexity(ind): ind.fitness.values = (ind.error, 0, len(ind), symbreg.calculate_order(ind)) def pick_fitness_size_from_fitness_age(ind): ind.fitness.values = (ind.error, len(ind)) class MultiArchive(object): def __init__(self, archives): self.archives = archives def update(self, population): for archive in self.archives: archive.update(population) def save(self, log_file): for archive in self.archives: archive.save(log_file) class ParetoFrontSavingArchive(object): def __init__(self, frequency, criteria_chooser=None, simplifier=None): self.fronts = [] self.frequency = frequency self.generation_counter = 0 self.criteria_chooser = criteria_chooser self.simplifier = simplifier def update(self, population): if self.generation_counter % self.frequency == 0: pop_copy = [deepcopy(ind) for ind in population] if self.simplifier is not None: self.simplifier(pop_copy) if self.criteria_chooser is not None: map(self.criteria_chooser, pop_copy) non_dominated = afpo.find_pareto_front(pop_copy) front = [pop_copy[index] for index in non_dominated] front.sort(key=operator.attrgetter("fitness.values")) self.fronts.append(front) self.generation_counter += 1 def save(self, log_file): pareto_front_file = "pareto_" + log_file with open(pareto_front_file, 'w') as f: writer = csv.writer(f) generation = 0 for front in self.fronts: inds = [(ind.fitness.values, str(ind)) for ind in front] writer.writerow([generation, len(inds)] + inds) generation += self.frequency class MutationStatsArchive(object): def __init__(self, evaluate_function): self.stats = defaultdict(list) self.neutral_mutations = defaultdict(int) self.detrimental_mutations = defaultdict(int) self.beneficial_mutations = defaultdict(int) self.evaluate_function = evaluate_function self.generation = -1 def update(self, population): self.generation += 1 def submit(self, old_ind, new_ind): old_error = self.evaluate_function(old_ind)[0] new_error = self.evaluate_function(new_ind)[0] delta_error = new_error - old_error delta_size = len(new_ind) - len(old_ind) if delta_size == 0 and numpy.isclose([delta_error], [0.0])[0]: self.neutral_mutations[self.generation] += 1 if delta_error > 0: self.detrimental_mutations[self.generation] += 1 elif delta_error < 0: self.beneficial_mutations[self.generation] += 1 self.stats[self.generation].append((delta_error, delta_size)) def save(self, log_file): mutation_statistics_file = "mutation_stats_" + log_file fieldnames = ['generation', 'neutral_mutations', 'beneficial_mutations', 'detrimental_mutations', 'deltas'] with open(mutation_statistics_file, 'wb') as f: writer = csv.writer(f) writer.writerow(fieldnames) for gen in self.stats.keys(): writer.writerow([gen, self.neutral_mutations[gen], self.beneficial_mutations[gen], self.detrimental_mutations[gen]] + self.stats[gen]) <file_sep>import numpy from scipy.stats import pearsonr, spearmanr from fastgp.utilities.symbreg import numpy_protected_div_dividend def mean_absolute_error(vector, response): errors = numpy.abs(vector - response) mean_error = numpy.mean(errors) if not numpy.isfinite(mean_error): return numpy.inf, return mean_error.item(), def euclidean_error(vector, response): with numpy.errstate(over='ignore', divide='ignore', invalid='ignore'): squared_errors = numpy.square(vector - response) sum_squared_errors = numpy.sum(squared_errors) if not numpy.isfinite(sum_squared_errors): return numpy.inf, distance = numpy.sqrt(sum_squared_errors) return distance.item(), def root_mean_square_error(vector, response): with numpy.errstate(over='ignore', divide='ignore', invalid='ignore'): squared_errors = numpy.square(vector - response) mse = numpy.mean(squared_errors) if not numpy.isfinite(mse): return numpy.inf, rmse = numpy.sqrt(mse) return rmse.item(), def mean_squared_error(vector, response): squared_errors = numpy.square(vector - response) mse = float(numpy.mean(squared_errors)) if not numpy.isfinite(mse): return numpy.inf, return mse, def pearson_correlation(vector, response): return pearsonr(vector, response) def spearman_correlation(vector, response): return spearmanr(vector, response) def normalized_cumulative_absolute_error(vector, response, threshold=0.0): errors = numpy.abs(vector - response) raw_sum = numpy.sum(errors) if not numpy.isfinite(raw_sum): return 0.0, errors[errors < threshold] = 0 cumulative_error = numpy.sum(errors).item() return 1 / (1 + cumulative_error), def mean_absolute_percentage_error(vector, response): with numpy.errstate(over='ignore', divide='ignore', invalid='ignore'): errors = numpy_protected_div_dividend((vector - response), response) errors = numpy_protected_div_dividend(errors, float(len(response))) mean_error = numpy.sum(numpy.abs(errors)) if numpy.isnan(mean_error) or not numpy.isfinite(mean_error): return numpy.inf, return mean_error, def percentage_error(vector, response, threshold=0.0): errors = numpy.abs(vector - response) raw_sum = numpy.sum(errors) if not numpy.isfinite(raw_sum): return 0.0, errors[errors < threshold] = 0 cumulative_error = numpy.sum(errors).item() cumulative_response = numpy.sum(response).item() return numpy_protected_div_dividend(cumulative_error, cumulative_response), def cumulative_absolute_error(vector, response): errors = numpy.abs(vector - response) cumulative_error = numpy.sum(errors) if not numpy.isfinite(cumulative_error): return numpy.inf, return cumulative_error.item(), def normalized_mean_squared_error(vector, response): squared_errors = numpy.square(vector - response) mse = numpy.mean(squared_errors) if not numpy.isfinite(mse): return numpy.inf, normalized_mse = mse / numpy.var(response) return normalized_mse.item(), <file_sep>import numpy as np from fastgp.algorithms import fast_evaluate class SubsetSelectionArchive(object): def __init__(self, frequency, predictors, response, subset_size, expression_dict): self.expression_dict = expression_dict self.frequency = frequency self.predictors = predictors self.response = response self.subset_size = subset_size self.num_obs = len(predictors) selected_indices = np.random.choice(self.num_obs, self.subset_size, replace=False) self.training_subset = np.zeros(self.num_obs, np.bool) self.training_subset[selected_indices] = 1 self.subset_predictors = self.predictors[self.training_subset, :] self.subset_response = self.response[self.training_subset] self.generation_counter = 0 def update(self, population): raise NotImplementedError def set_difficulty(self, errors): pass def get_data_subset(self): return self.subset_predictors, self.subset_response def get_indices(self): return np.arange(self.num_obs)[self.training_subset] def save(self, log_file): pass class RandomSubsetSelectionArchive(SubsetSelectionArchive): def __init__(self, frequency, predictors, response, subset_size, expression_dict): SubsetSelectionArchive.__init__(self, frequency, predictors, response, subset_size, expression_dict) def update(self, population): if self.generation_counter % self.frequency == 0: selected_indices = np.random.choice(self.num_obs, self.subset_size, replace=False) self.training_subset = np.zeros(self.num_obs, np.bool) self.training_subset[selected_indices] = 1 self.subset_predictors = self.predictors[self.training_subset, :] self.subset_response = self.response[self.training_subset] self.expression_dict.clear() self.generation_counter += 1 def fast_numpy_evaluate_subset(ind, context, subset_selection_archive, get_node_semantics, inner_evaluate_function=fast_evaluate.fast_numpy_evaluate, error_function=None, expression_dict=None): predictors, response = subset_selection_archive.get_data_subset() root_semantics = inner_evaluate_function(ind, context, predictors, get_node_semantics, error_function=None, expression_dict=expression_dict) return error_function(root_semantics, response) <file_sep>import random import time import itertools from functools import partial import math import re import cachetools import numpy as np from scipy.stats import skew, moment from copy import deepcopy from deap import gp class SimpleParametrizedPrimitiveSet(gp.PrimitiveSet): def __init__(self, name, arity, variable_type_indices, variable_names, prefix="ARG"): gp.PrimitiveSet.__init__(self, name, arity, prefix) self.variable_type_indices = variable_type_indices self.variable_names = variable_names def add_parametrized_terminal(self, parametrized_terminal_class): self._add(parametrized_terminal_class) self.context[parametrized_terminal_class.__name__] = parametrized_terminal_class.call class SimpleParametrizedPrimitiveTree(gp.PrimitiveTree): def __init__(self, content): gp.PrimitiveTree.__init__(self, content) def __deepcopy__(self, memo): new = self.__class__(self) for i, node in enumerate(self): if isinstance(node, SimpleParametrizedTerminal): new[i] = deepcopy(node) new.__dict__.update(deepcopy(self.__dict__, memo)) return new @classmethod def from_string(cls, string, pset): """Try to convert a string expression into a PrimitiveTree given a PrimitiveSet *pset*. The primitive set needs to contain every primitive present in the expression. :param string: String representation of a Python expression. :param pset: Primitive set from which primitives are selected. :returns: PrimitiveTree populated with the deserialized primitives. """ tokens = re.split("[ \t\n\r\f\v(),]", string) expr = [] def get_parts(token_string): parts = tokens[i].split('_') return parts[1], parts[2], parts[3] i = 0 while i < len(tokens): if tokens[i] == '': i += 1 continue if tokens[i] in pset.mapping: primitive = pset.mapping[tokens[i]] expr.append(primitive) elif RangeOperationTerminal.NAME in tokens[i]: operation, begin_range_name, end_range_name = get_parts(tokens[i]) range_operation_terminal = RangeOperationTerminal() range_operation_terminal.initialize_parameters(pset.variable_type_indices, pset.variable_names, operation, begin_range_name, end_range_name) expr.append(range_operation_terminal) elif MomentFindingTerminal.NAME in tokens[i]: operation, begin_range_name, end_range_name = get_parts(tokens[i]) moment_operation_terminal = MomentFindingTerminal() moment_operation_terminal.initialize_parameters(pset.variable_type_indices, pset.variable_names, operation, begin_range_name, end_range_name) expr.append(moment_operation_terminal) else: try: token = eval(tokens[i]) except NameError: raise TypeError("Unable to evaluate terminal: {}.".format(tokens[i])) expr.append(gp.Terminal(token, False, gp.__type__)) i += 1 return cls(expr) class SimpleParametrizedTerminal(gp.Terminal): ret = object def __init__(self, name="SimpleParametrizedTerminal", ret_type=object): gp.Terminal.__init__(self, name, True, ret_type) def __deepcopy__(self, memo): new = self.__class__() new.__dict__.update(deepcopy(self.__dict__, memo)) return new def initialize_parameters(self, variable_type_indices, names): raise NotImplementedError def create_input_vector(self, predictors): raise NotImplementedError def call(*parameters): pass # implement this method to make the class work with standard gp.compile def name_operation(operation, name): operation.__name__ = name return operation class RangeOperationTerminal(SimpleParametrizedTerminal): NAME = 'RangeOperation' def __init__(self): SimpleParametrizedTerminal.__init__(self, RangeOperationTerminal.__name__) self.begin_range = None self.end_range = None self.operation = None self.names = None self.lower_bound = None self.upper_bound = None self.operations = { 'sum': name_operation(np.sum, 'sum'), 'min': name_operation(np.min, 'min'), 'max': name_operation(np.max, 'max') } def initialize_parameters(self, variable_type_indices, names, operation=None, begin_range_name=None, end_range_name=None, *args): """ :param variable_type_indices: A sequence of variable type indices where each entry defines the index of a variable type in the design matrix. For example a design matrix with two variable types will have indices [j,n] where variable type A spans 0 to j and variable type B spans j + 1 to n. :param names: :param args: :param operation :param begin_range_name :param end_range_name :return: """ self.names = names for r in variable_type_indices: if r[1] - r[0] < 2: raise ValueError('Invalid range provided to Range Terminal: ' + str(r)) rng = random.choice(variable_type_indices) self.lower_bound = rng[0] self.upper_bound = rng[1] if operation is not None and begin_range_name is not None and end_range_name is not None: if self.operations.get(operation) is None: raise ValueError('Invalid operation provided to Range Terminal: ' + operation) if begin_range_name not in self.names: raise ValueError('Invalid range name provided to Range Termnial: ' + str(begin_range_name)) if end_range_name not in names: raise ValueError('Invalid range name provided to Range Termnial: ' + str(end_range_name)) begin_range = self.names.index(begin_range_name) end_range = self.names.index(end_range_name) valid = False for r in variable_type_indices: if r[0] <= begin_range < end_range <= r[1]: valid = True if not valid: raise ValueError('Invalid range provided to Range Terminal: (' + str(begin_range) + ',' + str(end_range) + ')') self.operation = self.operations[operation] self.begin_range = begin_range self.end_range = end_range else: self.operation = random.choice(list(self.operations.values())) self.begin_range = np.random.randint(self.lower_bound, self.upper_bound - 1) self.end_range = np.random.randint(self.begin_range + 1, self.upper_bound) def mutate_parameters(self, stdev_calc): mutation = random.choice(['low', 'high']) span = self.end_range - self.begin_range if span == 0: span = 1 value = random.gauss(0, stdev_calc(span)) amount = int(math.ceil(abs(value))) if value < 0: amount *= -1 if mutation == 'low': location = amount + self.begin_range if location < self.lower_bound: self.begin_range = self.lower_bound elif location > self.end_range - 2: self.begin_range = self.end_range - 2 elif location > self.upper_bound - 2: self.begin_range = self.upper_bound - 2 else: self.begin_range = location elif mutation == 'high': location = amount + self.end_range if location > self.upper_bound: self.end_range = self.upper_bound elif location < self.begin_range + 2: self.end_range = self.begin_range + 2 elif location < self.lower_bound + 2: self.end_range = self.lower_bound + 2 else: self.end_range = location def create_input_vector(self, predictors): array = predictors[:, self.begin_range:self.end_range] if array.shape[1] == 0: return np.zeros((array.shape[0], 1)) else: return self.operation(array, axis=1) def format(self): return "RangeOperation_{}_{}_{}".format(self.operation.__name__, self.names[self.begin_range], self.names[self.end_range - 1]) class MomentFindingTerminal(RangeOperationTerminal): NAME = 'MomentOperation' def __init__(self): super(MomentFindingTerminal, self).__init__() self.operations = { 'mean': name_operation(np.mean, 'mean'), 'vari': name_operation(np.var, 'vari'), 'skew': name_operation(skew, 'skew') } def initialize_parameters(self, variable_type_indices, names, operation=None, begin_range_name=None, end_range_name=None, *args): if operation is None: super(MomentFindingTerminal, self).initialize_parameters(variable_type_indices, names) self.operation = random.choice(list(self.operations.values())) else: super(MomentFindingTerminal, self).initialize_parameters(variable_type_indices, names, operation, begin_range_name, end_range_name, *args) def format(self): return "MomentOperation_{}_{}_{}".format(self.operation.__name__, self.names[self.begin_range], self.names[self.end_range - 1]) class PolynomialFindingTerminal(RangeOperationTerminal): NAME = 'PolynomialOperation' def __init__(self): super(PolynomialFindingTerminal, self).__init__() self.operations = { 'first': self.first, 'second': self.second, 'third': self.third } def first(self, X, axis=1): return self.polynomial(X, 1) def second(self, X, axis=1): return self.polynomial(X, 2) def third(self, X, axis=1): return self.polynomial(X, 3) def polynomial(self, X, order, interactions=False): start = time.time() orders = [] for o in range(1, order + 1): orders.append(np.apply_along_axis(lambda x: np.power(x, o), 1, X)) matrix = np.concatenate(orders, axis=1) rows = matrix.shape[0] cols = matrix.shape[1] result = np.zeros(rows) if interactions: indices = [x for x in range(cols)] for c in range(1, cols): for comb in itertools.combinations(indices, c): M = np.ones(rows) for j in comb: M *= matrix[:, j].reshape(rows) result += M else: result = np.sum(matrix, axis=1) return result def initialize_parameters(self, variable_type_indices, names, operation=None, begin_range_name=None, end_range_name=None, *args): if operation is None: super(PolynomialFindingTerminal, self).initialize_parameters(variable_type_indices, names) self.operation = random.choice(list(self.operations.values())) else: super(PolynomialFindingTerminal, self).initialize_parameters(variable_type_indices, names, operation, begin_range_name, end_range_name, *args) def format(self): return "PolynomialOperation{}_{}_{}".format(self.operation.__name__, self.names[self.begin_range], self.names[self.end_range - 1]) def named_moment(number): def f(vector, axis=0): return moment(vector, moment=number, axis=axis) f.__name__ = "moment_" + str(number) return f def generate_parametrized_expression(generate_expression, variable_type_indices, names): expr = generate_expression() for node in expr: if isinstance(node, SimpleParametrizedTerminal): node.initialize_parameters(variable_type_indices, names) return expr def evolve_parametrized_expression(stdev_calc): def decorator(func): def wrapper(*args, **kargs): offspring = list(func(*args, **kargs)) for ind in offspring: for node in ind: if isinstance(node, SimpleParametrizedTerminal): node.mutate_parameters(stdev_calc) return offspring return wrapper return decorator def get_parametrized_nodes(ind): return list(filter(lambda node: isinstance(node, SimpleParametrizedTerminal), ind)) def mutate_parametrized_nodes(ind, stdev_calc): param_nodes = get_parametrized_nodes(ind) map(lambda node: node.mutate_parameters(stdev_calc), param_nodes) return ind, def mutate_single_parametrized_node(ind, stdev_calc): param_nodes = get_parametrized_nodes(ind) if len(param_nodes) != 0: random.choice(param_nodes).mutate_parameters(stdev_calc) return ind, def search_entire_space(node, evaluate_function): fitness = [] parameters = [] begin = node.lower_bound while begin <= node.upper_bound: end = begin + 1 while end <= node.upper_bound: node.begin_range = begin node.end_range = end fitness.append(evaluate_function()) parameters.append((begin, end)) end += 1 begin += 1 return parameters, fitness def optimize_node(node, evaluate_function, optimization_objective_function): parameters, fitness = search_entire_space(node, evaluate_function) best_value = optimization_objective_function(fitness) optimal_index = fitness.index(best_value) begin, end = parameters[optimal_index] node.begin_range = begin node.end_range = end return parameters, fitness def mutate_single_parametrized_node_optimal(ind, evaluate_function, optimization_objective_function): param_nodes = get_parametrized_nodes(ind) if len(param_nodes) != 0: node = random.choice(param_nodes) optimize_node(node, partial(evaluate_function, ind=ind), optimization_objective_function) return ind, def simple_parametrized_evaluate(ind, context, predictors, error_function=None, expression_dict=None): semantics_stack = [] expressions_stack = [] if expression_dict is None: expression_dict = cachetools.LRUCache(maxsize=100) for node in reversed(ind): expression = node.format(*[expressions_stack.pop() for _ in range(node.arity)]) subtree_semantics = [semantics_stack.pop() for _ in range(node.arity)] if expression in expression_dict: vector = expression_dict[expression] else: vector = get_node_semantics(node, subtree_semantics, predictors, context) expression_dict[expression] = vector expressions_stack.append(expression) semantics_stack.append(vector) if error_function is None: return semantics_stack.pop() else: return error_function(semantics_stack.pop()) def get_terminal_semantics(node, context, predictors): if isinstance(node, gp.Ephemeral) or isinstance(node.value, float) or isinstance(node.value, int): return np.ones(len(predictors)) * node.value if node.value in context: return np.ones(len(predictors)) * context[node.value] arg_index = re.findall('\d+', node.name) return predictors[:, int(arg_index[0])] def get_node_semantics(node, subtree_semantics, predictors, context): if isinstance(node, SimpleParametrizedTerminal): vector = node.create_input_vector(predictors) elif isinstance(node, gp.Terminal): vector = get_terminal_semantics(node, context, predictors) else: with np.errstate(over='ignore', divide='ignore', invalid='ignore'): vector = context[node.name](*list(map(lambda x: x.astype(float) if type(x) != float else x, subtree_semantics))) return vector def graph(expr): nodes = range(len(expr)) edges = list() labels = dict() stack = [] for i, node in enumerate(expr): if stack: edges.append((stack[-1][0], i)) stack[-1][1] -= 1 if isinstance(node, gp.Primitive): labels[i] = node.name elif isinstance(node, SimpleParametrizedTerminal): labels[i] = node.format() else: labels[i] = node.value stack.append([i, node.arity]) while stack and stack[-1][1] == 0: stack.pop() return nodes, edges, labels <file_sep>import warnings import random from copy import deepcopy import math import numpy as np from sklearn.linear_model import ElasticNetCV from sklearn.model_selection import TimeSeriesSplit, KFold from sklearn.preprocessing import StandardScaler from scipy.stats import pearsonr from scipy.stats import skew from fastgp.utilities.metrics import mean_squared_error from fastgp.utilities.symbreg import numpy_protected_div_dividend, numpy_protected_sqrt, numpy_protected_log_one class Statistics: def __init__(self): self.scores = [] self.generations = [] self.num_features = [] self.index = 0 def add(self, gen, score, num_features): self.generations.append(gen) self.scores.append(score) self.num_features.append(num_features) def __iter__(self): return self def next(self): self.index += 1 if self.index > len(self.num_features): raise StopIteration return self.generations[self.index], self.scores[self.index], self.num_features[self.index] class Feature: def __init__(self, value, string, infix_string, size=0, fitness=1, original_variable=False): self.value = value self.fitness = fitness self.string = string self.infix_string = infix_string self.size = size self.original_variable = original_variable def __str__(self): return self.string class Operator: def __init__(self, operation, parity, string, infix, infix_name): self.operation = operation self.parity = parity self.string = string self.infix = infix self.infix_name = infix_name def square(x): return np.power(x, 2) def cube(x): return np.power(x, 3) def is_huge(x): return x > np.finfo(np.float64).max / 100000 def numpy_safe_exp(x): with np.errstate(invalid='ignore'): result = np.exp(x) if isinstance(result, np.ndarray): result[np.isnan(x)] = 1 result[np.isinf(x)] = 1 result[is_huge(x)] = 1 elif np.isinf(result): result = 1 elif np.isnan(x): result = 1 elif is_huge(x): result = 1 return result def generate_operator_map(ops): opmap = {} for o in ops: opmap[o.infix_name] = o return opmap operators = [ Operator(np.add, 2, '({0} + {1})', 'add({0},{1})', 'add'), Operator(np.subtract, 2, '({0} - {1})', 'sub({0},{1})', 'sub'), Operator(np.multiply, 2, '({0} * {1})', 'mul({0},{1})', 'mul'), Operator(numpy_protected_div_dividend, 2, '({0} / {1})', 'div({0},{1})', 'div'), # Operator(numpy_safe_exp, 1, 'exp({0})'), Operator(numpy_protected_log_one, 1, 'log({0})', 'log({0})', 'log'), Operator(square, 1, 'sqr({0})', 'sqr({0})', 'sqr'), Operator(numpy_protected_sqrt, 1, 'sqt({0})', 'sqt({0})', 'sqt'), Operator(cube, 1, 'cbe({0})', 'cbe({0})', 'cbe'), Operator(np.cbrt, 1, 'cbt({0})', 'cbt({0})', 'cbt'), Operator(None, None, None, None, 'mutate'), Operator(None, None, None, None, 'transition') ] operators_map = generate_operator_map(operators) def init(num_additions, feature_names, predictors, seed): random.seed(seed) np.random.seed(seed) if num_additions is None: num_additions = math.ceil(predictors.shape[1] / 3) if feature_names is None: feature_names = ['x' + str(x) for x in range(len(predictors))] return num_additions, feature_names def init_features(feature_names, predictors, preserve_originals, range_operations, variable_type_indices): features = [] for i, name in enumerate(feature_names): features.append(Feature(predictors[:, i], name, name, original_variable=preserve_originals)) for _ in range(range_operations): features.append(RangeOperation(variable_type_indices, feature_names, predictors)) return features def get_basis(features): basis = np.zeros((features[0].value.shape[0], len(features))) for i, f in enumerate(features): basis[:, i] = features[i].value basis = np.nan_to_num(basis) scaler = StandardScaler() basis = scaler.fit_transform(basis) return basis, scaler def get_model(basis, response, time_series_cv, splits): if time_series_cv: cv = TimeSeriesSplit(n_splits=splits) else: cv = KFold(n_splits=splits) model = ElasticNetCV(l1_ratio=1, selection='random', cv=cv) with warnings.catch_warnings(): warnings.simplefilter('ignore') model.fit(basis, response) _, coefs, _ = model.path(basis, response, l1_ration=model.l1_ratio_, alphas=model.alphas_) return model, coefs, model.mse_path_ def get_selected_features(num_additions, features, tournament_probability): selected_features = [] for _ in range(num_additions): feature = tournament_selection(features, tournament_probability) selected_features.append(feature) return selected_features def get_coefficient_fitness(coefs, mse_path, threshold, response_variance): mse = np.mean(mse_path, axis=1) r_squared = 1 - (mse / response_variance) binary_coefs = coefs > threshold return binary_coefs.dot(r_squared) def rank_by_coefficient(features, coefs, mse_path, num_additions, threshold, response_variance, verbose): fitness = get_coefficient_fitness(coefs, mse_path, threshold, response_variance) for i, f in enumerate(features): f.fitness = fitness[i] new_features = list(filter(lambda x: x.original_variable is True, features)) possible_features = list(filter(lambda x: x.original_variable is False, features)) possible_features.sort(key=lambda x: x.fitness, reverse=True) new_features.extend(possible_features[0:num_additions + 1]) new_features.sort(key=lambda x: x.fitness, reverse=True) print('Top performing features:') for i in range(10): print(new_features[i].string + ' - ' + str(new_features[i].fitness)) return new_features def remove_zeroed_features(model, features, threshold, verbose): remove_features = [] for i, coef in enumerate(model.coef_): features[i].fitness = math.fabs(coef) if features[i].fitness <= threshold and not features[i].original_variable: remove_features.append(features[i]) for f in remove_features: features.remove(f) print('Removed ' + str(len(remove_features)) + ' features from population.') if verbose and remove_features: print(get_model_string(remove_features)) return features def update_fitness(features, response, threshold, fitness_algorithm, response_variance, num_additions, time_series_cv, splits, verbose): basis, _ = get_basis(features) model, coefs, mse_path = get_model(basis, response, time_series_cv, splits) if fitness_algorithm == 'zero_out': features = remove_zeroed_features(model, features, threshold, verbose) elif fitness_algorithm == 'coefficient_rank': features = rank_by_coefficient(features, coefs, mse_path, num_additions, threshold, response_variance, verbose) return features def uncorrelated(parents, new_feature, correlation_threshold): uncorr = True if type(parents) == list: for p in parents: r, _ = pearsonr(new_feature.value, p.value) if r > correlation_threshold: uncorr = False else: r, _ = pearsonr(new_feature.value, parents.value) if r > correlation_threshold: uncorr = False return uncorr def tournament_selection(population, probability): individuals = random.choices(population, k=2) individuals.sort(reverse=True, key=lambda x: x.fitness) if random.random() < probability: return individuals[0] else: return individuals[1] def compose_features(num_additions, features, tournament_probability, correlation_threshold, range_operators, verbose): new_feature_list = [] for _ in range(num_additions): operator = random.choice(operators) if operator.parity == 1: parent = tournament_selection(features, tournament_probability) new_feature_string = operator.string.format(parent.string) new_infix_string = operator.infix.format(parent.infix_string) new_feature_value = operator.operation(parent.value) new_feature = Feature(new_feature_value, new_feature_string, new_infix_string, size=parent.size + 1) if uncorrelated(parent, new_feature, correlation_threshold): new_feature_list.append(new_feature) elif operator.parity == 2: parent1 = tournament_selection(features, tournament_probability) parent2 = tournament_selection(features, tournament_probability) new_feature_string = operator.string.format(parent1.string, parent2.string) new_infix_string = operator.infix.format(parent1.infix_string, parent2.infix_string) new_feature_value = operator.operation(parent1.value, parent2.value) new_feature = Feature(new_feature_value, new_feature_string, new_infix_string, size=parent1.size + parent2.size + 1) if uncorrelated([parent1, parent2], new_feature, correlation_threshold): new_feature_list.append(new_feature) if range_operators: protected_range_operators = list(filter(lambda x: type(x) == RangeOperation and x.original_variable, features)) transitional_range_operators = list(filter(lambda x: type(x) == RangeOperation and not x.original_variable, features)) if operator.infix_name == 'transition' and protected_range_operators: parent = random.choice(protected_range_operators) new_feature = deepcopy(parent) new_feature.original_variable = False new_feature_list.append(new_feature) elif operator.infix_name == 'mutate' and transitional_range_operators: parent = random.choice(transitional_range_operators) new_feature = deepcopy(parent) new_feature.mutate_parameters() new_feature_list.append(new_feature) filtered_feature_list = list(filter(lambda x: x.size < 5, new_feature_list)) features.extend(filtered_feature_list) print('Adding ' + str(len(filtered_feature_list)) + ' features to population.') if verbose: print(get_model_string(new_feature_list)) return features def score_model(features, response, time_series_cv, splits): print('Scoring model with ' + str(len(features)) + ' features.') basis, scaler = get_basis(features) model, _, _ = get_model(basis, response, time_series_cv, splits) score = mean_squared_error(model.predict(basis), response)[0] return score, model, scaler def get_model_string(features): feature_strings = [] for f in features: feature_strings.append(f.string) return '[' + '] + ['.join(feature_strings) + ']' def compute_operation(num_variables, predictors, stack, feature_names): variables = [] for _ in range(num_variables): variable_name = stack.pop() variable_index = feature_names.index(variable_name) variables.append(predictors[:, variable_index]) operator = stack.pop() result = operator.operation(*variables) return result def build_operation_stack(string): stack = [] start = 0 for i, s in enumerate(string): if s == '(': substring = string[start:i] start = i + 1 stack.append(substring) elif s == ',': if i != start: substring = string[start:i] stack.append(substring) start = i + 1 elif s == ')': if i != start: substring = string[start:i] stack.append(substring) start = i + 1 return stack def get_feature_value(stack, feature_names, predictors, variable_type_indices): variables_stack = [] while len(stack) > 0: current = stack.pop() if variable_type_indices and current.startswith('RangeOperation'): range_operation = RangeOperation(variable_type_indices, feature_names, predictors, string=current) variables_stack.append(np.squeeze(range_operation.value)) elif current in feature_names: variable_index = feature_names.index(current) variables_stack.append(predictors[:, variable_index]) elif current in operators_map: operator = operators_map[current] variables = [] for _ in range(operator.parity): variables.append(variables_stack.pop()) result = operator.operation(*variables) variables_stack.append(result) return variables_stack.pop() def build_basis_from_features(infix_features, feature_names, predictors, variable_type_indices): basis = np.zeros((predictors.shape[0], len(infix_features))) for j, f in enumerate(infix_features): if variable_type_indices and f.startswith('RangeOperation'): range_operation = RangeOperation(variable_type_indices, feature_names, predictors, string=f) basis[:, j] = np.squeeze(range_operation.value) elif f in feature_names: variable_index = feature_names.index(f) basis[:, j] = predictors[:, variable_index] else: operation_stack = build_operation_stack(f) basis[:, j] = get_feature_value(operation_stack, feature_names, predictors, variable_type_indices) return basis def get_basis_from_infix_features(infix_features, feature_names, predictors, scaler=None, variable_type_indices=None): basis = build_basis_from_features(infix_features, feature_names, predictors, variable_type_indices) basis = np.nan_to_num(basis) if scaler: basis = scaler.transform(basis) return basis def optimize(predictors, response, seed, fitness_algorithm, max_gens=100, num_additions=None, preserve_originals=True, tournament_probability=.9, max_useless_steps=10, fitness_threshold=.01, correlation_threshold=0.95, reinit_range_operators=3, splits=3, time_series_cv=False, feature_names=None, range_operators=0, variable_type_indices=None, verbose=False): assert predictors.shape[1] == len(feature_names) num_additions, feature_names = init(num_additions, feature_names, predictors, seed) features = init_features(feature_names, predictors, preserve_originals, range_operators, variable_type_indices) best_models = [] best_features = [] best_scalers = [] best_validation_scores = [] statistics = Statistics() best_score = np.Inf steps_without_new_model = 0 response_variance = np.var(response) gen = 1 while gen <= max_gens and steps_without_new_model <= max_useless_steps: print('Generation: ' + str(gen)) score, model, scaler = score_model(features, response, time_series_cv, splits) statistics.add(gen, score, len(features)) if verbose: print(get_model_string(features)) print('Score: ' + str(score)) if score < best_score: best_validation_scores.append(score) steps_without_new_model = 0 best_score = score print('New best model score: ' + str(best_score)) best_models.append(model) temp_features = deepcopy(features) for f in temp_features: f.value = None best_features.append(temp_features) best_scalers.append(scaler) else: steps_without_new_model += 1 print('-------------------------------------------------------') if gen < max_gens and steps_without_new_model <= max_useless_steps: features = compose_features(num_additions, features, tournament_probability, correlation_threshold, range_operators, verbose) features = update_fitness(features, response, fitness_threshold, fitness_algorithm, response_variance, num_additions, time_series_cv, splits, verbose) if gen % reinit_range_operators == 0: features = swap_range_operators(features, range_operators, variable_type_indices, feature_names, predictors) gen += 1 return statistics, best_models, best_features, best_scalers, best_validation_scores def swap_range_operators(features, range_operations, variable_type_indices, feature_names, predictors): for f in features: if type(f) == RangeOperation and f.original_variable: features.remove(f) for _ in range(range_operations): features.append(RangeOperation(variable_type_indices, feature_names, predictors)) return features def name_operation(operation, name): operation.__name__ = name return operation class RangeOperation(Feature): def __init__(self, variable_type_indices, names, predictors, operation=None, begin_range_name=None, end_range_name=None, original_variable=True, string=None): Feature.__init__(self, None, 'RangeOperation', 'RangeOperation', original_variable=original_variable) self.predictors = predictors self.begin_range = None self.end_range = None self.operation = None self.names = None self.lower_bound = None self.upper_bound = None self.variable_type_indices = variable_type_indices self.operations = { 'sum': name_operation(np.sum, 'sum'), 'min': name_operation(np.min, 'min'), 'max': name_operation(np.max, 'max'), 'mean': name_operation(np.mean, 'mean'), 'vari': name_operation(np.var, 'vari'), 'skew': name_operation(skew, 'skew') } if string: parts = string.split('_') self.initialize_parameters(variable_type_indices, names, parts[1], parts[2], parts[3]) else: self.initialize_parameters(variable_type_indices, names, operation, begin_range_name, end_range_name) self.value = self.create_input_vector() self.string = self.format() self.infix_string = self.format() def __deepcopy__(self, memo): new = self.__class__(self.variable_type_indices, self.names, self.predictors) new.__dict__.update(deepcopy(self.__dict__, memo)) new.predictors = self.predictors new.value = self.value return new def initialize_parameters(self, variable_type_indices, names, operation=None, begin_range_name=None, end_range_name=None): """ :param variable_type_indices: A sequence of variable type indices where each entry defines the index of a variable type in the design matrix. For example a design matrix with two variable types will have indices [j,n] where variable type A spans 0 to j and variable type B spans j + 1 to n. :param names: :param operation :param begin_range_name :param end_range_name :return: """ self.names = names for r in variable_type_indices: if r[1] - r[0] < 2: raise ValueError('Invalid variable type indices: ' + str(r)) rng = random.choice(variable_type_indices) self.lower_bound = rng[0] self.upper_bound = rng[1] if operation is not None and begin_range_name is not None and end_range_name is not None: if self.operations.get(operation) is None: raise ValueError('Invalid operation provided to Range Terminal: ' + operation) if begin_range_name not in self.names: raise ValueError('Invalid range name provided to Range Termnial: ' + str(begin_range_name)) if end_range_name not in self.names: raise ValueError('Invalid range name provided to Range Terminal: ' + str(end_range_name)) begin_range = self.names.index(begin_range_name) end_range = self.names.index(end_range_name) + 1 valid = False for r in variable_type_indices: if r[0] <= begin_range < end_range <= r[1]: valid = True if not valid: raise ValueError('Invalid range provided to Range Terminal: (' + str(begin_range) + ',' + str(end_range) + ')') self.operation = self.operations[operation] self.begin_range = begin_range self.end_range = end_range else: self.operation = random.choice(list(self.operations.values())) self.begin_range = np.random.randint(self.lower_bound, self.upper_bound - 1) self.end_range = np.random.randint(self.begin_range + 1, self.upper_bound) def mutate_parameters(self): old = self.format() mutation = random.choice(['low', 'high']) span = self.end_range - self.begin_range if span == 0: span = 1 value = random.gauss(0, math.sqrt(span)) amount = int(math.ceil(abs(value))) if value < 0: amount *= -1 if mutation == 'low': location = amount + self.begin_range if location < self.lower_bound: self.begin_range = self.lower_bound elif location > self.end_range - 2: self.begin_range = self.end_range - 2 elif location > self.upper_bound - 2: self.begin_range = self.upper_bound - 2 else: self.begin_range = location elif mutation == 'high': location = amount + self.end_range if location > self.upper_bound: self.end_range = self.upper_bound elif location < self.begin_range + 2: self.end_range = self.begin_range + 2 elif location < self.lower_bound + 2: self.end_range = self.lower_bound + 2 else: self.end_range = location self.value = self.create_input_vector() self.infix_string = self.format() self.string = self.format() # print('Mutated ' + old + ' to ' + self.format()) def create_input_vector(self): array = self.predictors[:, self.begin_range:self.end_range] if array.shape[1] == 0: return np.zeros((array.shape[0], 1)) else: return self.operation(array, axis=1) def format(self): return "RangeOperation_{}_{}_{}".format(self.operation.__name__, self.names[self.begin_range], self.names[self.end_range - 1]) <file_sep>import math # 4 * x^4 + 3 * x^3 + 2 * x^2 + x def mod_quartic(x): return x * (1 + x * (2 + x * (3 + x * 4))) # Koza-1: x^4 + x^3 + x^2 + x def quartic(x): return x * (1 + x * (1 + x * (1 + x))) # Koza-2: x^5 - 2x^3 + x def quintic(x): return x * (1 - x * x * (2 - x * x)) # Koza-3: x^6 - 2x^4 + x^2 def sextic(x): return x * x * (1 - x * x * (2 - x * x)) # x^7 - 2x^6 + x^5 - x^4 + x^3 - 2x^2 + x def septic(x): return x * (1 - x * (2 - x * (1 - x * (1 - x * (1 - x * (2 - x)))))) # sum_{1}^9{x^i} def nonic(x): return x * (1 + x * (1 + x * (1 + x * (1 + x * (1 + x * (1 + x * (1 + x * (1 + x)))))))) # x^3 + x^2 + x def nguyen1(x): return x * (1 + x * (1 + x)) # x^5 + x^4 + x^3 + x^2 + x def nguyen3(x): return x * (1 + x * (1 + x * (1 + x * (1 + x)))) # x^6 + x^5 + x^4 + x^3 + x^2 + x def nguyen4(x): return x * (1 + x * (1 + x * (1 + x * (1 + x * (1 + x))))) def nguyen5(x): return math.sin(x * x) * math.cos(x) - 1 def nguyen6(x): return math.sin(x) + math.sin(x * (1 + x)) def nguyen7(x): return math.log(x + 1) + math.log(x * x + 1) def nguyen9(x, y): return math.sin(x) + math.sin(y * y) def nguyen10(x, y): return 2 * math.sin(x) * math.cos(y) def nguyen12(x, y): return x ** 4 - x ** 3 + (y ** 2 / 2.0) - y def keijzer1(x): return 0.3 * x * math.sin(2 * math.pi * x) def keijzer4(x): return x ** 3 * math.exp(-x) * math.cos(x) * math.sin(x) * (math.sin(x) ** 2 * math.cos(x) - 1) def keijzer11(x, y): return (x * y) + math.sin((x - 1) * (y - 1)) def keijzer12(x, y): return x ** 4 - x ** 3 + (y ** 2 / 2.0) - y def keijzer13(x, y): return 6 * math.sin(x) * math.cos(y) def keijzer14(x, y): return 8.0 / (2 + x ** 2 + y ** 2) def keijzer15(x, y): return (x ** 3 / 5.0) + (y ** 3 / 2.0) - x - y def r1(x): return ((x + 1) ** 3) / (x ** 2 - x + 1) def r2(x): return (x ** 5 - (3 * (x ** 3)) + 1) / (x ** 2 + 1) def r3(x): return (x ** 6 + x ** 5) / (x ** 4 + x ** 3 + x ** 2 + x + 1) def pagie1(x, y): return (1 / (1 + x ** -4)) + (1 / (1 + y ** -4)) <file_sep>import math from deap import gp import numpy def protected_div_one(left, right): try: return left / right except ZeroDivisionError: return 1 def protected_div_zero(left, right): try: return left / right except ZeroDivisionError: return 0 def protected_div_dividend(left, right): if right != 0: return left / right else: return left def aq(left, right): with numpy.errstate(divide='ignore', invalid='ignore'): x = numpy.divide(left, numpy.sqrt(1 + numpy.square(right))) if isinstance(x, numpy.ndarray): x[numpy.isinf(x)] = left[numpy.isinf(x)] x[numpy.isnan(x)] = left[numpy.isnan(x)] elif numpy.isinf(x) or numpy.isnan(x): x = left return x def numpy_protected_div_dividend(left, right): with numpy.errstate(divide='ignore', invalid='ignore'): x = numpy.divide(left, right) if isinstance(x, numpy.ndarray): x[numpy.isinf(x)] = left[numpy.isinf(x)] x[numpy.isnan(x)] = left[numpy.isnan(x)] elif numpy.isinf(x) or numpy.isnan(x): x = left return x def numpy_protected_div_zero(left, right): with numpy.errstate(divide='ignore', invalid='ignore'): x = numpy.divide(left, right) if isinstance(x, numpy.ndarray): x[numpy.isinf(x)] = 0.0 x[numpy.isnan(x)] = 0.0 elif numpy.isinf(x) or numpy.isnan(x): x = 0.0 return x def numpy_protected_div_one(left, right): with numpy.errstate(divide='ignore', invalid='ignore'): x = numpy.divide(left, right) if isinstance(x, numpy.ndarray): x[numpy.isinf(x)] = 1.0 x[numpy.isnan(x)] = 1.0 elif numpy.isinf(x) or numpy.isnan(x): x = 1.0 return x def numpy_protected_sqrt(x): with numpy.errstate(invalid='ignore'): x = numpy.sqrt(x) if isinstance(x, numpy.ndarray): x[numpy.isnan(x)] = 0 elif numpy.isnan(x): x = 0 return x def protected_log_one(x): if x > 0: return math.log(x) else: return 1 def protected_log_abs(x): if x != 0: return math.log(abs(x)) else: return 0 def cube(x): return numpy.power(x, 3.0) def numpy_protected_log_abs(x): with numpy.errstate(divide='ignore', invalid='ignore'): abs_val = numpy.abs(x) x = numpy.log(abs_val.astype(float)) if isinstance(x, numpy.ndarray): x[numpy.isinf(x)] = -1e300 x[numpy.isnan(x)] = 0 elif numpy.isinf(x): x = -1e300 elif numpy.isnan(x): x = 0 return x def numpy_protected_log_one(x): with numpy.errstate(divide='ignore', invalid='ignore'): x = numpy.log(numpy.abs(x)) if isinstance(x, numpy.ndarray): x[numpy.isinf(x)] = 1.0 x[numpy.isnan(x)] = 1.0 elif numpy.isinf(x): x = 1.0 elif numpy.isnan(x): x = 1.0 return x def get_terminal_order(node, context=None): if isinstance(node, gp.Ephemeral) or isinstance(node.value, float) \ or isinstance(node.value, int) or context is not None and node.value in context: return 0 return 1 def calculate_order(ind, context=None): order_stack = [] for node in reversed(ind): if isinstance(node, gp.Terminal): terminal_order = get_terminal_order(node, context) order_stack.append(terminal_order) elif node.arity == 1: arg_order = order_stack.pop() if node.name == numpy_protected_log_abs.__name__: order_stack.append(3 * arg_order) elif node.name == numpy.exp.__name__: order_stack.append(4 * arg_order) else: # cube or square order_stack.append(1.5 * arg_order) else: # node.arity == 2: args_order = [order_stack.pop() for _ in range(node.arity)] if node.name == numpy.add.__name__ or node.name == numpy.subtract.__name__: order_stack.append(max(args_order)) else: order_stack.append(sum(args_order)) return order_stack.pop() def get_numpy_infix_symbol_map(): symbol_map = {numpy.add.__name__: "({0} + {1})", numpy.subtract.__name__: "({0} - {1})", numpy.multiply.__name__: "({0} * {1})", numpy_protected_div_dividend.__name__: "({0} / {1})", numpy_protected_log_abs.__name__: "log({0})", numpy.abs.__name__: "abs({0})", numpy.sin.__name__: "sin({0})", numpy.cos.__name__: "cos({0})", numpy.exp.__name__: "exp({0})", numpy.square.__name__: "(({0}) ^ 2)", cube.__name__: "(({0}) ^ 3)", numpy.sqrt.__name__: "sqrt({0})", numpy.reciprocal.__name__: "(1 / {0})", aq.__name__: "({0} // {1})", numpy.power.__name__: "(({0}) ^ {1})"} return symbol_map def get_numpy_prefix_symbol_map(): symbol_map = [("+", numpy.add.__name__,), ("-", numpy.subtract.__name__), ("**", numpy.power.__name__), ("^", numpy.power.__name__), ("*", numpy.multiply.__name__), ("/", numpy_protected_div_dividend.__name__), ('abs', numpy.abs.__name__), ("log", numpy_protected_log_abs.__name__), ("sin", numpy.sin.__name__), ("cos", numpy.cos.__name__), ("exp", numpy.exp.__name__)] return symbol_map def get_numpy_commutative_set(): return {numpy.add.__name__, numpy.multiply.__name__} <file_sep>from __future__ import division import csv from deap import tools import numpy import operator import fastgp.parametrized.simple_parametrized_terminals as sp def get_fitness(ind): return ind.fitness.values[0] def get_mean(values): return numpy.mean(list(filter(numpy.isfinite, values))) def get_std(values): return numpy.std(list(filter(numpy.isfinite, values))) def get_min(values): return numpy.min(list(filter(numpy.isfinite, values))) def get_max(values): return numpy.max(list(filter(numpy.isfinite, values))) def get_size_min(values): return min(values)[1] def get_size_max(values): return max(values)[1] def get_fitness_size(ind): return ind.fitness.values[0], len(ind) def configure_inf_protected_stats(): stats_fit = tools.Statistics(get_fitness) stats_size = tools.Statistics(len) stats_height = tools.Statistics(operator.attrgetter("height")) mstats = tools.MultiStatistics(fitness=stats_fit, size=stats_size, height=stats_height) mstats.register("avg", get_mean) mstats.register("std", get_std) mstats.register("min", get_min) mstats.register("max", get_max) stats_best_ind = tools.Statistics(get_fitness_size) stats_best_ind.register("size_min", get_size_min) stats_best_ind.register("size_max", get_size_max) mstats["best_tree"] = stats_best_ind return mstats def is_parametrized_terminal(node): return isinstance(node, sp.SimpleParametrizedTerminal) def get_param_ratio(ind): parametrized = len(list(filter(is_parametrized_terminal, ind))) total = len(ind) return parametrized / total def configure_parametrized_inf_protected_stats(): stats_fit = tools.Statistics(get_fitness) stats_size = tools.Statistics(len) stats_height = tools.Statistics(operator.attrgetter("height")) stats_parametrized = tools.Statistics(get_param_ratio) mstats = tools.MultiStatistics(fitness=stats_fit, size=stats_size, height=stats_height, parametrized=stats_parametrized) mstats.register("avg", get_mean) mstats.register("std", get_std) mstats.register("min", get_min) mstats.register("max", get_max) stats_best_ind = tools.Statistics(get_fitness_size) stats_best_ind.register("size_min", get_size_min) stats_best_ind.register("size_max", get_size_max) mstats["best_tree"] = stats_best_ind return mstats def get_age(ind): return ind.age def add_age_to_stats(mstats): stats_age = tools.Statistics(get_age) stats_age.register("avg", numpy.mean) stats_age.register("std", numpy.std) stats_age.register("max", numpy.max) mstats["age"] = stats_age return mstats def save_log_to_csv(log, file_path): columns = [log.select("cpu_time")] columns_names = ["cpu_time"] for chapter_name, chapter in log.chapters.items(): for column in chapter[0].keys(): columns_names.append(str(column) + "_" + str(chapter_name)) columns.append(chapter.select(column)) rows = zip(*columns) with open(file_path + '.csv', 'w') as f: writer = csv.writer(f) writer.writerow(columns_names) for row in rows: writer.writerow(row) def save_hof(hof, test_toolbox=None): def decorator(func): def wrapper(pop, log, file_name): func(pop, log, file_name) hof_file_name = "trees_" + file_name with open(hof_file_name, 'wb') as f: writer = csv.writer(f) writer.writerow(["gen", "fitness", "tree"]) for gen, ind in enumerate(hof.historical_trees): if test_toolbox is not None: test_error = test_toolbox.test_evaluate(ind)[0] writer.writerow([gen, ind.fitness, str(ind), test_error]) else: writer.writerow([gen, ind.fitness, str(ind)]) return wrapper return decorator def save_archive(archive): def decorator(func): def wrapper(pop, log, file_name): func(pop, log, file_name) archive.save(file_name) return wrapper return decorator <file_sep>import logging import random import time from deap import tools from fastgp.utilities import symbreg def breed(parents, toolbox, xover_prob, mut_prob): offspring = [toolbox.clone(ind) for ind in parents] for i in range(1, len(offspring), 2): if random.random() < xover_prob: offspring[i - 1], offspring[i] = toolbox.mate(offspring[i - 1], offspring[i]) max_age = max(offspring[i - 1].age, offspring[i].age) offspring[i].age = offspring[i - 1].age = max_age del offspring[i - 1].fitness.values, offspring[i].fitness.values for i in range(len(offspring)): if random.random() < mut_prob: offspring[i], = toolbox.mutate(offspring[i]) del offspring[i].fitness.values return offspring def find_pareto_front(population): """Finds a subset of nondominated individuals in a given list :param population: a list of individuals :return: a set of indices corresponding to nondominated individuals """ pareto_front = set(range(len(population))) for i in range(len(population)): if i not in pareto_front: continue ind1 = population[i] for j in range(i + 1, len(population)): ind2 = population[j] # if individuals are equal on all objectives, mark one of them (the first encountered one) as dominated # to prevent excessive growth of the Pareto front if ind2.fitness.dominates(ind1.fitness) or ind1.fitness == ind2.fitness: pareto_front.discard(i) if ind1.fitness.dominates(ind2.fitness): pareto_front.discard(j) return pareto_front def reduce_population(population, tournament_size, target_popsize, nondominated_size): num_iterations = 0 new_population_indices = list(range(len(population))) stop_cond = False while len(new_population_indices) > target_popsize and len(new_population_indices) > nondominated_size: if num_iterations > 10e6: print("Pareto front size may be exceeding the size of population. Stopping the execution. Try making" "the population size larger or the number of generations smaller.") # random.sample(new_population_indices, len(new_population_indices) - target_popsize) stop_cond = True num_iterations += 1 tournament_indices = random.sample(new_population_indices, tournament_size) tournament = [population[index] for index in tournament_indices] nondominated_tournament = find_pareto_front(tournament) for i in range(len(tournament)): if i not in nondominated_tournament: new_population_indices.remove(tournament_indices[i]) population[:] = [population[i] for i in new_population_indices] return stop_cond def pareto_optimization(population, toolbox, xover_prob, mut_prob, ngen, tournament_size, num_randoms=1, archive=None, stats=None, calc_pareto_front=True, verbose=False, reevaluate_population=False, history=None, stop_time=None): start = time.time() if history is not None: history.update(population) logbook = tools.Logbook() logbook.header = ['gen', 'nevals', 'cpu_time'] + (stats.fields if stats else []) target_popsize = len(population) # calculating errors may be expensive, so we will cache the error value as an individual's attribute for ind in population: ind.error = toolbox.evaluate_error(ind)[0] toolbox.assign_fitness(population) for ind in population: history.genealogy_history[ind.history_index].error = ind.error record = stats.compile(population) if stats else {} cpu_time = time.time() - start logbook.record(gen=0, nevals=len(population), cpu_time=cpu_time, **record) if archive is not None: archive.update(population) if verbose: print(logbook.stream) gen = 0 while(gen < (ngen + 1)): # do we want to enforce re-evaluating the whole population instead of using cached erro r values if reevaluate_population: for ind in population: ind.error = toolbox.evaluate_error(ind)[0] parents = toolbox.select(population, len(population) - num_randoms) offspring = breed(parents, toolbox, xover_prob, mut_prob) offspring += toolbox.generate_randoms() # evaluate newly generated individuals which do not have cached values (or have inherited them from parents) for ind in offspring: ind.error = toolbox.evaluate_error(ind)[0] # extend the population by adding offspring - the size of population is now 2*target_popsize population.extend(offspring) toolbox.assign_fitness(population) for ind in population: history.genealogy_history[ind.history_index].error = ind.error # we may take 2 strategies of evaluating pareto-front: # - pessimistic: Pareto front may be larger than target_popsize and we want to detect it early because # if that's the case we won't be able to reduce the size of population to target_popsize # - optimistic: in practice, the above case happen extremely rarely but calculating global front is expensive # so let's assume that Pareto front is small enough try to reduce the population if calc_pareto_front: pareto_front_size = len(find_pareto_front(population)) logging.debug("Generation: %5d - Pareto Front Size: %5d", gen, pareto_front_size) if pareto_front_size > target_popsize: logging.info("Pareto front size exceeds the size of population. Try Making the population size larger" "or reducing the number of generations.") break else: pareto_front_size = 0 # perform Pareto tournament selection until the size of the population is reduced to target_popsize stop_cond = reduce_population(population, tournament_size, target_popsize, pareto_front_size) record = stats.compile(population) if stats else {} cpu_time = time.time() - start print(gen, cpu_time, stop_time) logbook.record(gen=gen, nevals=len(population), cpu_time=cpu_time, **record) if archive is not None: archive.update(population) if verbose: print(logbook.stream) for ind in population: ind.age += 1 if stop_cond: print('Stop condition reached at generation %i.' % gen) gen = ngen + 1 elif stop_time is not None and cpu_time > stop_time: print('Stop time reached at generation %i.' % gen) gen = ngen + 1 else: gen = gen + 1 return population, logbook, history def evaluate_age_fitness(ind, error_func): ind.error = error_func(ind)[0] return ind.error, ind.age def evaluate_age_fitness_size(ind, error_func): ind.size = len(ind) return evaluate_age_fitness(ind, error_func) + (ind.size,) def evaluate_fitness_size(ind, error_func): ind.error = error_func(ind)[0] ind.size = len(ind) return ind.error, ind.size def evaluate_fitness_size_complexity(ind, error_func): ind.error = error_func(ind)[0] ind.size = len(ind) ind.complexity = symbreg.calculate_order(ind) return ind.error, ind.size, ind.complexity def assign_random_fitness(population, random_range): for ind in population: ind.fitness.values = (ind.error, random.randrange(random_range)) def assign_pure_fitness(population): for ind in population: ind.fitness.values = (ind.error,) def assign_age_fitness(population): for ind in population: ind.fitness.values = (ind.error, ind.age) def assign_age_fitness_size(population): for ind in population: ind.fitness.values = (ind.error, ind.age, len(ind)) def assign_age_fitness_complexity(population): for ind in population: ind.fitness.values = (ind.error, ind.age, symbreg.calculate_order(ind)) def assign_age_fitness_size_complexity(population): for ind in population: ind.fitness.values = (ind.error, ind.age, len(ind), symbreg.calculate_order(ind)) def assign_size_fitness(population): for ind in population: ind.fitness.values = (ind.error, len(ind)) <file_sep>import time import math import random from deap import tools def generate_next_population(individuals, toolbox): """ Perform truncated selection with elitism. :param individuals: :param toolbox: :return: """ individuals = [toolbox.clone(ind) for ind in individuals] individuals.sort(key=lambda x: x.error) offspring = [] pop_size = len(individuals) num_top = math.floor(pop_size / 2) parents = individuals[0:num_top + 1] for _ in range(pop_size - 1): off = toolbox.clone(random.choice(parents)) off = toolbox.mutate(off)[0] offspring.append(off) offspring.append(individuals[0]) return offspring def render_fitness(population, toolbox, history): for ind in population: ind.error = toolbox.evaluate_error(ind)[0] ind.fitness.values = ind.error, if history is not None: history.genealogy_history[ind.history_index].error = ind.error def record_information(population, stats, start, archive, logbook, verbose): record = stats.compile(population) if stats else {} logbook.record(gen=0, nevals=len(population), cpu_time=time.time() - start, **record) if archive is not None: archive.update(population) if verbose: print(logbook.stream) def optimize(population, toolbox, ngen, archive=None, stats=None, verbose=False, history=None): """ Optimize a population of individuals. :param population: :param toolbox: :param mut_prob: :param ngen: :param archive: :param stats: :param verbose: :param history: :return: """ start = time.time() if history is not None: history.update(population) logbook = tools.Logbook() logbook.header = ['gen', 'nevals', 'cpu_time'] + (stats.fields if stats else []) render_fitness(population, toolbox, history) record_information(population, stats, start, archive, logbook, verbose) for gen in range(1, ngen + 1): offspring = generate_next_population(population, toolbox) render_fitness(offspring, toolbox, history) population = offspring record_information(population, stats, start, archive, logbook, verbose) return population, logbook, history <file_sep>__author__ = 'mszubert' <file_sep>import pytest import fastgp.parametrized.simple_parametrized_terminals as sp class TestRangeOperationTerminal: def test_initialize(self): term = sp.RangeOperationTerminal() variable_type_indices = [(1, 2)] names = ['xtdlta' + str(x) for x in range(2)] with pytest.raises(ValueError): term.initialize_parameters(variable_type_indices, names) variable_type_indices = [(2, 0)] names = ['xtdlta' + str(x) for x in range(2)] with pytest.raises(ValueError): term.initialize_parameters(variable_type_indices, names) variable_type_indices = [(1, 3)] names = ['xtdlta' + str(x) for x in range(2)] term.initialize_parameters(variable_type_indices, names) variable_type_indices = [(1, 3), (7, 30)] names = ['xtdlta' + str(x) for x in range(2)] + ['ytdlta' + str(x) for x in range(7, 30)] term.initialize_parameters(variable_type_indices, names) def test_initialize_manually(self): term = sp.RangeOperationTerminal() variable_type_indices = [(0, 2)] names = ['xtdlta' + str(x) for x in range(2)] with pytest.raises(ValueError): term.initialize_parameters(variable_type_indices, names, operation='cat', begin_range_name='xtdlta0', end_range_name='xtdlta1') with pytest.raises(ValueError): term.initialize_parameters(variable_type_indices, names, operation='cat', begin_range_name='xtlta0', end_range_name='xtdlta1') with pytest.raises(ValueError): term.initialize_parameters(variable_type_indices, names, operation='cat', begin_range_name='xtdlta0', end_range_name='xtdlt1') variable_type_indices = [(0, 2)] names = ['xtdlta' + str(x) for x in range(2)] term.initialize_parameters(variable_type_indices, names, operation='max', begin_range_name='xtdlta0', end_range_name='xtdlta1') variable_type_indices = [(0, 7)] names = ['xtdlta' + str(x) for x in range(7)] term.initialize_parameters(variable_type_indices, names, operation='max', begin_range_name='xtdlta3', end_range_name='xtdlta4') <file_sep>from setuptools import setup, find_packages setup( name='fastgp', version='0.1.0', description='Fast genetic programming.', author='<NAME>', author_email='<EMAIL>', license='GNU GPLv3', classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Science/Research', 'Topic :: Scientific/Engineering :: Artificial Intelligence', 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)', 'Programming Language :: Python :: 3' ], keywords='evolution machine learning artificial intelligence', install_requires=[ 'scipy', 'deap', 'cachetools', 'numpy', ], python_requires='>=2.7', packages=find_packages(exclude=['contrib', 'docs', 'tests']), url='https://github.com/cfusting/fastgp' ) <file_sep>scipy deap pytest cachetools numpy <file_sep># Fast Genetic Programming fastgp is a numpy implementation of [genetic programming](https://en.wikipedia.org/wiki/Genetic_programming) built on top of [deap](https://github.com/DEAP/deap). It is the core library for [fastsr](https://github.com/cfusting/fast-symbolic-regression), a symbolic regression package for Python. It's primary contribution is an implementation of AFPO<a href="#lc-1">\[1\]</a> which is compatible with any deap toolbox. fastgp was designed and developed by the [Morphology, Evolution & Cognition Laboratory](http://www.meclab.org/) at the University of Vermont. It extends research code which can be found [here](https://github.com/mszubert/gecco_2016). Installing ---------- fastgp is compatible with Python 2.7+. ```bash pip install fastgp ``` Example Usage ------------- fastgp is a core library and as such there are no examples in this repository. Check out [fastsr](https://github.com/cfusting/fast-symbolic-regression) for an example of fastgp's use in Symbolic Regression. Literature Cited ---------------- 1. <NAME> and <NAME>. 2011. Age-fitness pareto optimization. In Genetic Programming Theory and Practice VIII. Springer, 129–146.<a name="lc-2"></a> <file_sep>import random def multi_mutation(ind, mutations, probs): for mutation, probability in zip(mutations, probs): if random.random() < probability: ind = mutation(ind), return ind, def multi_mutation_exclusive(ind, mutations, probs): if len(mutations) != len(probs): raise ValueError("Must have the same number of mutations as probabilities.") if sum(probs) > 1: raise ValueError("Probabilities must sum to 1.") prob_range = [0] + probs value = random.random() i = 1 while i < len(prob_range): prob_range[i] += prob_range[i - 1] if prob_range[i - 1] <= value < prob_range[i]: mutations[i - 1](ind) return ind, i += 1 return ind, <file_sep>import copy from functools import wraps import random def static_limit(key, max_value): def decorator(func): @wraps(func) def wrapper(*args, **kwargs): keep_inds = [copy.deepcopy(ind) for ind in args] new_inds = list(func(*args, **kwargs)) for i, ind in enumerate(new_inds): if key(ind) > max_value: new_inds[i] = copy.deepcopy(random.choice(keep_inds)) return new_inds return wrapper return decorator def stats_collector(archive): def decorator(func): @wraps(func) def wrapper(*args, **kwargs): keep_inds = [copy.deepcopy(ind) for ind in args] new_inds = list(func(*args, **kwargs)) for old_ind, new_ind in zip(keep_inds, new_inds): archive.submit(old_ind, new_ind) return new_inds return wrapper return decorator def internally_biased_node_selector(individual, bias): internal_nodes = [] leaves = [] for index, node in enumerate(individual): if node.arity == 0: leaves.append(index) else: internal_nodes.append(index) if internal_nodes and random.random() < bias: return random.choice(internal_nodes) else: return random.choice(leaves) def get_node_indices_at_depth(individual, level): stack = [0] nodes_at_depth = [] for index, node in enumerate(individual): current_depth = stack.pop() if current_depth == level: nodes_at_depth.append(index) stack.extend([current_depth + 1] * node.arity) return nodes_at_depth def uniform_depth_node_selector(individual): depth = random.randint(0, individual.height) nodes_at_depth = get_node_indices_at_depth(individual, depth) return random.choice(nodes_at_depth) def uniform_depth_mutation(individual, expr, pset): node_index = uniform_depth_node_selector(individual) slice_ = individual.searchSubtree(node_index) type_ = individual[node_index].ret individual[slice_] = expr(pset=pset, type_=type_) return individual, def multi_mutation(ind, mutations, probs): for mutation, probability in zip(mutations, probs): if random.random() < probability: ind, = mutation(ind) return ind, def one_point_xover_biased(ind1, ind2, node_selector): if len(ind1) < 2 or len(ind2) < 2: return ind1, ind2 index1 = node_selector(ind1) index2 = node_selector(ind2) slice1 = ind1.searchSubtree(index1) slice2 = ind2.searchSubtree(index2) ind1[slice1], ind2[slice2] = ind2[slice2], ind1[slice1] return ind1, ind2 def mutation_biased(ind, expr, node_selector): index = node_selector(ind) slice1 = ind.searchSubtree(index) ind[slice1] = expr() return ind, def static_limit_retries(key, max_value, num_retries): def decorator(func): @wraps(func) def wrapper(*args, **kwargs): keep_inds = [copy.deepcopy(ind) for ind in args] for _ in range(num_retries): new_inds = list(func(*args, **kwargs)) all_within_limit = True for i, ind in enumerate(new_inds): if key(ind) > max_value: all_within_limit = False break if all_within_limit: return new_inds new_inds = list(func(*args, **kwargs)) for i, ind in enumerate(new_inds): if key(ind) > max_value: new_inds[i] = random.choice(keep_inds) return new_inds return wrapper return decorator <file_sep>import cachetools import numpy def fast_numpy_evaluate(ind, context, predictors, get_node_semantics, error_function=None, expression_dict=None): semantics_stack = [] expressions_stack = [] if expression_dict is None: expression_dict = cachetools.LRUCache(maxsize=100) for node in reversed(ind): expression = node.format(*[expressions_stack.pop() for _ in range(node.arity)]) subtree_semantics = [semantics_stack.pop() for _ in range(node.arity)] if expression in expression_dict: vector = expression_dict[expression] else: vector = get_node_semantics(node, subtree_semantics, predictors, context) expression_dict[expression] = vector expressions_stack.append(expression) semantics_stack.append(vector) if error_function is None: return semantics_stack.pop() else: return error_function(semantics_stack.pop()) def fast_numpy_evaluate_population(pop, context, predictors, error_func, expression_dict=None, arg_prefix="ARG"): if expression_dict is None: expression_dict = cachetools.LRUCache(maxsize=2000) results = numpy.empty(shape=(len(pop), len(predictors))) for row, ind in enumerate(pop): results[row] = fast_numpy_evaluate(ind, context, predictors, expression_dict, arg_prefix) errors = error_func(results) for ind, error in zip(pop, errors): ind.fitness.values = error,
de21fa686c30bc2ad39b067a51989a9255ae9c23
[ "Markdown", "Python", "Text" ]
18
Python
DavidBreuer/fastgp
499c72f517f026514d85ca26062be84a6c3104d4
99db4db03be69ed51caef7f0cf76c38583ff47c2
refs/heads/master
<repo_name>donalma-co/donalma-co<file_sep>/database/migrations/2021_08_23_000029_add_relationship_fields_to_events_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class AddRelationshipFieldsToEventsTable extends Migration { public function up() { Schema::table('events', function (Blueprint $table) { $table->unsignedBigInteger('organization_id')->nullable(); $table->foreign('organization_id', 'organization_fk_4699207')->references('id')->on('organizations'); }); } } <file_sep>/routes/web.php <?php Route::redirect('/', '/login'); Route::get('/home', function () { if (session('status')) { return redirect()->route('admin.home')->with('status', session('status')); } return redirect()->route('admin.home'); }); Route::get('userVerification/{token}', 'UserVerificationController@approve')->name('userVerification'); Auth::routes(); Route::group(['prefix' => 'admin', 'as' => 'admin.', 'namespace' => 'Admin', 'middleware' => ['auth', '2fa']], function () { Route::get('/', 'HomeController@index')->name('home'); // Permissions Route::delete('permissions/destroy', 'PermissionsController@massDestroy')->name('permissions.massDestroy'); Route::resource('permissions', 'PermissionsController'); // Roles Route::delete('roles/destroy', 'RolesController@massDestroy')->name('roles.massDestroy'); Route::resource('roles', 'RolesController'); // Users Route::delete('users/destroy', 'UsersController@massDestroy')->name('users.massDestroy'); Route::post('users/parse-csv-import', 'UsersController@parseCsvImport')->name('users.parseCsvImport'); Route::post('users/process-csv-import', 'UsersController@processCsvImport')->name('users.processCsvImport'); Route::resource('users', 'UsersController'); // Audit Logs Route::resource('audit-logs', 'AuditLogsController', ['except' => ['create', 'store', 'edit', 'update', 'destroy']]); // Content Category Route::delete('content-categories/destroy', 'ContentCategoryController@massDestroy')->name('content-categories.massDestroy'); Route::resource('content-categories', 'ContentCategoryController'); // Content Tag Route::delete('content-tags/destroy', 'ContentTagController@massDestroy')->name('content-tags.massDestroy'); Route::resource('content-tags', 'ContentTagController'); // Content Page Route::delete('content-pages/destroy', 'ContentPageController@massDestroy')->name('content-pages.massDestroy'); Route::post('content-pages/media', 'ContentPageController@storeMedia')->name('content-pages.storeMedia'); Route::post('content-pages/ckmedia', 'ContentPageController@storeCKEditorImages')->name('content-pages.storeCKEditorImages'); Route::resource('content-pages', 'ContentPageController'); // Departments Route::delete('departments/destroy', 'DepartmentsController@massDestroy')->name('departments.massDestroy'); Route::post('departments/parse-csv-import', 'DepartmentsController@parseCsvImport')->name('departments.parseCsvImport'); Route::post('departments/process-csv-import', 'DepartmentsController@processCsvImport')->name('departments.processCsvImport'); Route::resource('departments', 'DepartmentsController'); // Cities Route::delete('cities/destroy', 'CitiesController@massDestroy')->name('cities.massDestroy'); Route::resource('cities', 'CitiesController'); // Document Types Route::delete('document-types/destroy', 'DocumentTypesController@massDestroy')->name('document-types.massDestroy'); Route::resource('document-types', 'DocumentTypesController'); // Types Route::delete('types/destroy', 'TypesController@massDestroy')->name('types.massDestroy'); Route::post('types/media', 'TypesController@storeMedia')->name('types.storeMedia'); Route::post('types/ckmedia', 'TypesController@storeCKEditorImages')->name('types.storeCKEditorImages'); Route::resource('types', 'TypesController'); // Organizations Route::delete('organizations/destroy', 'OrganizationsController@massDestroy')->name('organizations.massDestroy'); Route::post('organizations/media', 'OrganizationsController@storeMedia')->name('organizations.storeMedia'); Route::post('organizations/ckmedia', 'OrganizationsController@storeCKEditorImages')->name('organizations.storeCKEditorImages'); Route::post('organizations/parse-csv-import', 'OrganizationsController@parseCsvImport')->name('organizations.parseCsvImport'); Route::post('organizations/process-csv-import', 'OrganizationsController@processCsvImport')->name('organizations.processCsvImport'); Route::resource('organizations', 'OrganizationsController'); // Donations Route::delete('donations/destroy', 'DonationsController@massDestroy')->name('donations.massDestroy'); Route::post('donations/media', 'DonationsController@storeMedia')->name('donations.storeMedia'); Route::post('donations/ckmedia', 'DonationsController@storeCKEditorImages')->name('donations.storeCKEditorImages'); Route::resource('donations', 'DonationsController'); // Transactions Route::delete('transactions/destroy', 'TransactionsController@massDestroy')->name('transactions.massDestroy'); Route::resource('transactions', 'TransactionsController'); // Projects Route::delete('projects/destroy', 'ProjectsController@massDestroy')->name('projects.massDestroy'); Route::post('projects/media', 'ProjectsController@storeMedia')->name('projects.storeMedia'); Route::post('projects/ckmedia', 'ProjectsController@storeCKEditorImages')->name('projects.storeCKEditorImages'); Route::resource('projects', 'ProjectsController'); // Automatic Debts Route::delete('automatic-debts/destroy', 'AutomaticDebtsController@massDestroy')->name('automatic-debts.massDestroy'); Route::resource('automatic-debts', 'AutomaticDebtsController'); // User Alerts Route::delete('user-alerts/destroy', 'UserAlertsController@massDestroy')->name('user-alerts.massDestroy'); Route::get('user-alerts/read', 'UserAlertsController@read'); Route::resource('user-alerts', 'UserAlertsController', ['except' => ['edit', 'update']]); // Global Obj Route::delete('global-objs/destroy', 'GlobalObjController@massDestroy')->name('global-objs.massDestroy'); Route::resource('global-objs', 'GlobalObjController'); // Countries Route::delete('countries/destroy', 'CountriesController@massDestroy')->name('countries.massDestroy'); Route::resource('countries', 'CountriesController'); // Events Route::delete('events/destroy', 'EventsController@massDestroy')->name('events.massDestroy'); Route::post('events/media', 'EventsController@storeMedia')->name('events.storeMedia'); Route::post('events/ckmedia', 'EventsController@storeCKEditorImages')->name('events.storeCKEditorImages'); Route::post('events/parse-csv-import', 'EventsController@parseCsvImport')->name('events.parseCsvImport'); Route::post('events/process-csv-import', 'EventsController@processCsvImport')->name('events.processCsvImport'); Route::resource('events', 'EventsController'); Route::get('system-calendar', 'SystemCalendarController@index')->name('systemCalendar'); Route::get('global-search', 'GlobalSearchController@search')->name('globalSearch'); }); Route::group(['prefix' => 'profile', 'as' => 'profile.', 'namespace' => 'Auth', 'middleware' => ['auth', '2fa']], function () { // Change password if (file_exists(app_path('Http/Controllers/Auth/ChangePasswordController.php'))) { Route::get('password', 'ChangePasswordController@edit')->name('password.edit'); Route::post('password', 'ChangePasswordController@update')->name('password.update'); Route::post('profile', 'ChangePasswordController@updateProfile')->name('password.updateProfile'); Route::post('profile/destroy', 'ChangePasswordController@destroy')->name('password.destroyProfile'); Route::post('profile/two-factor', 'ChangePasswordController@toggleTwoFactor')->name('password.toggleTwoFactor'); } }); Route::group(['namespace' => 'Auth', 'middleware' => ['auth', '2fa']], function () { // Two Factor Authentication if (file_exists(app_path('Http/Controllers/Auth/TwoFactorController.php'))) { Route::get('two-factor', 'TwoFactorController@show')->name('twoFactor.show'); Route::post('two-factor', 'TwoFactorController@check')->name('twoFactor.check'); Route::get('two-factor/resend', 'TwoFactorController@resend')->name('twoFactor.resend'); } }); <file_sep>/app/Http/Controllers/Api/V1/Admin/DocumentTypesApiController.php <?php namespace App\Http\Controllers\Api\V1\Admin; use App\Http\Controllers\Controller; use App\Http\Requests\StoreDocumentTypeRequest; use App\Http\Requests\UpdateDocumentTypeRequest; use App\Http\Resources\Admin\DocumentTypeResource; use App\Models\DocumentType; use Gate; use Illuminate\Http\Request; use Symfony\Component\HttpFoundation\Response; class DocumentTypesApiController extends Controller { public function index() { abort_if(Gate::denies('document_type_access'), Response::HTTP_FORBIDDEN, '403 Forbidden'); return new DocumentTypeResource(DocumentType::all()); } public function store(StoreDocumentTypeRequest $request) { $documentType = DocumentType::create($request->all()); return (new DocumentTypeResource($documentType)) ->response() ->setStatusCode(Response::HTTP_CREATED); } public function show(DocumentType $documentType) { abort_if(Gate::denies('document_type_show'), Response::HTTP_FORBIDDEN, '403 Forbidden'); return new DocumentTypeResource($documentType); } public function update(UpdateDocumentTypeRequest $request, DocumentType $documentType) { $documentType->update($request->all()); return (new DocumentTypeResource($documentType)) ->response() ->setStatusCode(Response::HTTP_ACCEPTED); } public function destroy(DocumentType $documentType) { abort_if(Gate::denies('document_type_delete'), Response::HTTP_FORBIDDEN, '403 Forbidden'); $documentType->delete(); return response(null, Response::HTTP_NO_CONTENT); } } <file_sep>/routes/api.php <?php Route::group(['prefix' => 'v1', 'as' => 'api.', 'namespace' => 'Api\V1\Admin', 'middleware' => ['auth:sanctum']], function () { // Permissions Route::apiResource('permissions', 'PermissionsApiController'); // Roles Route::apiResource('roles', 'RolesApiController'); // Users Route::apiResource('users', 'UsersApiController'); // Content Category Route::apiResource('content-categories', 'ContentCategoryApiController'); // Content Tag Route::apiResource('content-tags', 'ContentTagApiController'); // Content Page Route::post('content-pages/media', 'ContentPageApiController@storeMedia')->name('content-pages.storeMedia'); Route::apiResource('content-pages', 'ContentPageApiController'); // Departments Route::apiResource('departments', 'DepartmentsApiController'); // Cities Route::apiResource('cities', 'CitiesApiController'); // Document Types Route::apiResource('document-types', 'DocumentTypesApiController'); // Types Route::post('types/media', 'TypesApiController@storeMedia')->name('types.storeMedia'); Route::apiResource('types', 'TypesApiController'); // Organizations Route::post('organizations/media', 'OrganizationsApiController@storeMedia')->name('organizations.storeMedia'); Route::apiResource('organizations', 'OrganizationsApiController'); // Donations Route::post('donations/media', 'DonationsApiController@storeMedia')->name('donations.storeMedia'); Route::apiResource('donations', 'DonationsApiController'); // Transactions Route::apiResource('transactions', 'TransactionsApiController'); // Projects Route::post('projects/media', 'ProjectsApiController@storeMedia')->name('projects.storeMedia'); Route::apiResource('projects', 'ProjectsApiController'); // Automatic Debts Route::apiResource('automatic-debts', 'AutomaticDebtsApiController'); // Countries Route::apiResource('countries', 'CountriesApiController'); // Events Route::post('events/media', 'EventsApiController@storeMedia')->name('events.storeMedia'); Route::apiResource('events', 'EventsApiController'); }); <file_sep>/app/Http/Controllers/Api/V1/Admin/TypesApiController.php <?php namespace App\Http\Controllers\Api\V1\Admin; use App\Http\Controllers\Controller; use App\Http\Controllers\Traits\MediaUploadingTrait; use App\Http\Requests\StoreTypeRequest; use App\Http\Requests\UpdateTypeRequest; use App\Http\Resources\Admin\TypeResource; use App\Models\Type; use Gate; use Illuminate\Http\Request; use Symfony\Component\HttpFoundation\Response; class TypesApiController extends Controller { use MediaUploadingTrait; public function index() { abort_if(Gate::denies('type_access'), Response::HTTP_FORBIDDEN, '403 Forbidden'); return new TypeResource(Type::with(['globals'])->get()); } public function store(StoreTypeRequest $request) { $type = Type::create($request->all()); $type->globals()->sync($request->input('globals', [])); if ($request->input('image', false)) { $type->addMedia(storage_path('tmp/uploads/' . basename($request->input('image'))))->toMediaCollection('image'); } return (new TypeResource($type)) ->response() ->setStatusCode(Response::HTTP_CREATED); } public function show(Type $type) { abort_if(Gate::denies('type_show'), Response::HTTP_FORBIDDEN, '403 Forbidden'); return new TypeResource($type->load(['globals'])); } public function update(UpdateTypeRequest $request, Type $type) { $type->update($request->all()); $type->globals()->sync($request->input('globals', [])); if ($request->input('image', false)) { if (!$type->image || $request->input('image') !== $type->image->file_name) { if ($type->image) { $type->image->delete(); } $type->addMedia(storage_path('tmp/uploads/' . basename($request->input('image'))))->toMediaCollection('image'); } } elseif ($type->image) { $type->image->delete(); } return (new TypeResource($type)) ->response() ->setStatusCode(Response::HTTP_ACCEPTED); } public function destroy(Type $type) { abort_if(Gate::denies('type_delete'), Response::HTTP_FORBIDDEN, '403 Forbidden'); $type->delete(); return response(null, Response::HTTP_NO_CONTENT); } } <file_sep>/app/Http/Controllers/Admin/DonationsController.php <?php namespace App\Http\Controllers\Admin; use App\Http\Controllers\Controller; use App\Http\Controllers\Traits\MediaUploadingTrait; use App\Http\Requests\MassDestroyDonationRequest; use App\Http\Requests\StoreDonationRequest; use App\Http\Requests\UpdateDonationRequest; use App\Models\Donation; use App\Models\Organization; use App\Models\User; use Gate; use Illuminate\Http\Request; use Spatie\MediaLibrary\MediaCollections\Models\Media; use Symfony\Component\HttpFoundation\Response; class DonationsController extends Controller { use MediaUploadingTrait; public function index() { abort_if(Gate::denies('donation_access'), Response::HTTP_FORBIDDEN, '403 Forbidden'); $donations = Donation::with(['user', 'organization', 'media'])->get(); return view('admin.donations.index', compact('donations')); } public function create() { abort_if(Gate::denies('donation_create'), Response::HTTP_FORBIDDEN, '403 Forbidden'); $users = User::all()->pluck('name', 'id')->prepend(trans('global.pleaseSelect'), ''); $organizations = Organization::all()->pluck('name', 'id')->prepend(trans('global.pleaseSelect'), ''); return view('admin.donations.create', compact('users', 'organizations')); } public function store(StoreDonationRequest $request) { $donation = Donation::create($request->all()); if ($request->input('file', false)) { $donation->addMedia(storage_path('tmp/uploads/' . basename($request->input('file'))))->toMediaCollection('file'); } if ($media = $request->input('ck-media', false)) { Media::whereIn('id', $media)->update(['model_id' => $donation->id]); } return redirect()->route('admin.donations.index'); } public function edit(Donation $donation) { abort_if(Gate::denies('donation_edit'), Response::HTTP_FORBIDDEN, '403 Forbidden'); $users = User::all()->pluck('name', 'id')->prepend(trans('global.pleaseSelect'), ''); $organizations = Organization::all()->pluck('name', 'id')->prepend(trans('global.pleaseSelect'), ''); $donation->load('user', 'organization'); return view('admin.donations.edit', compact('users', 'organizations', 'donation')); } public function update(UpdateDonationRequest $request, Donation $donation) { $donation->update($request->all()); if ($request->input('file', false)) { if (!$donation->file || $request->input('file') !== $donation->file->file_name) { if ($donation->file) { $donation->file->delete(); } $donation->addMedia(storage_path('tmp/uploads/' . basename($request->input('file'))))->toMediaCollection('file'); } } elseif ($donation->file) { $donation->file->delete(); } return redirect()->route('admin.donations.index'); } public function show(Donation $donation) { abort_if(Gate::denies('donation_show'), Response::HTTP_FORBIDDEN, '403 Forbidden'); $donation->load('user', 'organization'); return view('admin.donations.show', compact('donation')); } public function destroy(Donation $donation) { abort_if(Gate::denies('donation_delete'), Response::HTTP_FORBIDDEN, '403 Forbidden'); $donation->delete(); return back(); } public function massDestroy(MassDestroyDonationRequest $request) { Donation::whereIn('id', request('ids'))->delete(); return response(null, Response::HTTP_NO_CONTENT); } public function storeCKEditorImages(Request $request) { abort_if(Gate::denies('donation_create') && Gate::denies('donation_edit'), Response::HTTP_FORBIDDEN, '403 Forbidden'); $model = new Donation(); $model->id = $request->input('crud_id', 0); $model->exists = true; $media = $model->addMediaFromRequest('upload')->toMediaCollection('ck-media'); return response()->json(['id' => $media->id, 'url' => $media->getUrl()], Response::HTTP_CREATED); } } <file_sep>/resources/lang/es/cruds.php <?php return [ 'userManagement' => [ 'title' => 'Gestión de usuarios', 'title_singular' => 'Gestión de usuarios', ], 'permission' => [ 'title' => 'Permisos', 'title_singular' => 'Permiso', 'fields' => [ 'id' => 'ID', 'id_helper' => ' ', 'title' => 'Title', 'title_helper' => ' ', 'created_at' => 'Created at', 'created_at_helper' => ' ', 'updated_at' => 'Updated at', 'updated_at_helper' => ' ', 'deleted_at' => 'Deleted at', 'deleted_at_helper' => ' ', ], ], 'role' => [ 'title' => 'Roles', 'title_singular' => 'Rol', 'fields' => [ 'id' => 'ID', 'id_helper' => ' ', 'title' => 'Title', 'title_helper' => ' ', 'permissions' => 'Permissions', 'permissions_helper' => ' ', 'created_at' => 'Created at', 'created_at_helper' => ' ', 'updated_at' => 'Updated at', 'updated_at_helper' => ' ', 'deleted_at' => 'Deleted at', 'deleted_at_helper' => ' ', ], ], 'user' => [ 'title' => 'Usuarios', 'title_singular' => 'Usuario', 'fields' => [ 'id' => 'ID', 'id_helper' => ' ', 'name' => 'Nombre', 'name_helper' => ' ', 'email' => 'Email', 'email_helper' => ' ', 'email_verified_at' => 'Email verified at', 'email_verified_at_helper' => ' ', 'password' => '<PASSWORD>', 'password_helper' => ' ', 'roles' => 'Roles', 'roles_helper' => ' ', 'remember_token' => 'Remember Token', 'remember_token_helper' => ' ', 'created_at' => 'Created at', 'created_at_helper' => ' ', 'updated_at' => 'Updated at', 'updated_at_helper' => ' ', 'deleted_at' => 'Deleted at', 'deleted_at_helper' => ' ', 'verified' => 'Verified', 'verified_helper' => ' ', 'verified_at' => 'Verified at', 'verified_at_helper' => ' ', 'verification_token' => 'Verification token', 'verification_token_helper' => ' ', 'document' => 'No. Documento', 'document_helper' => ' ', 'organization' => 'Organización', 'organization_helper' => ' ', 'phone' => 'Teléfono de contacto', 'phone_helper' => ' ', 'documenttype' => 'Tipo de documento', 'documenttype_helper' => ' ', 'two_factor' => 'Two-Factor Auth', 'two_factor_helper' => ' ', 'two_factor_code' => 'Two-factor code', 'two_factor_code_helper' => ' ', 'two_factor_expires_at' => 'Two-factor expires at', 'two_factor_expires_at_helper' => ' ', 'featured' => 'Destacado', 'featured_helper' => ' ', ], ], 'auditLog' => [ 'title' => 'Audit Logs', 'title_singular' => 'Audit Log', 'fields' => [ 'id' => 'ID', 'id_helper' => ' ', 'description' => 'Description', 'description_helper' => ' ', 'subject_id' => 'Subject ID', 'subject_id_helper' => ' ', 'subject_type' => 'Subject Type', 'subject_type_helper' => ' ', 'user_id' => 'User ID', 'user_id_helper' => ' ', 'properties' => 'Properties', 'properties_helper' => ' ', 'host' => 'Host', 'host_helper' => ' ', 'created_at' => 'Created at', 'created_at_helper' => ' ', 'updated_at' => 'Updated at', 'updated_at_helper' => ' ', ], ], 'contentManagement' => [ 'title' => 'Content management', 'title_singular' => 'Content management', ], 'contentCategory' => [ 'title' => 'Categories', 'title_singular' => 'Category', 'fields' => [ 'id' => 'ID', 'id_helper' => ' ', 'name' => 'Name', 'name_helper' => ' ', 'slug' => 'Slug', 'slug_helper' => ' ', 'created_at' => 'Created at', 'created_at_helper' => ' ', 'updated_at' => 'Updated At', 'updated_at_helper' => ' ', 'deleted_at' => 'Deleted At', 'deleted_at_helper' => ' ', ], ], 'contentTag' => [ 'title' => 'Tags', 'title_singular' => 'Tag', 'fields' => [ 'id' => 'ID', 'id_helper' => ' ', 'name' => 'Name', 'name_helper' => ' ', 'slug' => 'Slug', 'slug_helper' => ' ', 'created_at' => 'Created at', 'created_at_helper' => ' ', 'updated_at' => 'Updated At', 'updated_at_helper' => ' ', 'deleted_at' => 'Deleted At', 'deleted_at_helper' => ' ', ], ], 'contentPage' => [ 'title' => 'Pages', 'title_singular' => 'Page', 'fields' => [ 'id' => 'ID', 'id_helper' => ' ', 'title' => 'Titulo', 'title_helper' => ' ', 'category' => 'Categorias', 'category_helper' => ' ', 'tag' => 'Tags', 'tag_helper' => ' ', 'page_text' => 'Texto completo', 'page_text_helper' => ' ', 'excerpt' => 'Extracto', 'excerpt_helper' => ' ', 'created_at' => 'Created at', 'created_at_helper' => ' ', 'updated_at' => 'Updated At', 'updated_at_helper' => ' ', 'deleted_at' => 'Deleted At', 'deleted_at_helper' => ' ', 'image' => 'Imagen', 'image_helper' => ' ', 'file' => 'Archivo', 'file_helper' => ' ', 'comments' => 'Observaciones', 'comments_helper' => ' ', 'status' => 'Status', 'status_helper' => ' ', ], ], 'globalVar' => [ 'title' => 'Global Variables', 'title_singular' => 'Global Variable', ], 'department' => [ 'title' => 'Departments', 'title_singular' => 'Department', 'fields' => [ 'id' => 'ID', 'id_helper' => ' ', 'name' => 'Nombre', 'name_helper' => ' ', 'code' => 'Código', 'code_helper' => ' ', 'created_at' => 'Created at', 'created_at_helper' => ' ', 'updated_at' => 'Updated at', 'updated_at_helper' => ' ', 'deleted_at' => 'Deleted at', 'deleted_at_helper' => ' ', ], ], 'city' => [ 'title' => 'Cities', 'title_singular' => 'City', 'fields' => [ 'id' => 'ID', 'id_helper' => ' ', 'name' => 'Nombre', 'name_helper' => ' ', 'code' => 'Código', 'code_helper' => ' ', 'department' => 'Department', 'department_helper' => ' ', 'created_at' => 'Created at', 'created_at_helper' => ' ', 'updated_at' => 'Updated at', 'updated_at_helper' => ' ', 'deleted_at' => 'Deleted at', 'deleted_at_helper' => ' ', ], ], 'documentType' => [ 'title' => 'Document Types', 'title_singular' => 'Document Type', 'fields' => [ 'id' => 'ID', 'id_helper' => ' ', 'name' => 'Nombre del tipo', 'name_helper' => ' ', 'code' => 'Código', 'code_helper' => ' ', 'created_at' => 'Created at', 'created_at_helper' => ' ', 'updated_at' => 'Updated at', 'updated_at_helper' => ' ', 'deleted_at' => 'Deleted at', 'deleted_at_helper' => ' ', ], ], 'foundation' => [ 'title' => 'Foundations', 'title_singular' => 'Foundation', ], 'type' => [ 'title' => 'Organization Types', 'title_singular' => 'Organization Type', 'fields' => [ 'id' => 'ID', 'id_helper' => ' ', 'name' => 'Nombre', 'name_helper' => ' ', 'code' => 'Codigo', 'code_helper' => ' ', 'image' => 'Imagen', 'image_helper' => ' ', 'created_at' => 'Created at', 'created_at_helper' => ' ', 'updated_at' => 'Updated at', 'updated_at_helper' => ' ', 'deleted_at' => 'Deleted at', 'deleted_at_helper' => ' ', 'globals' => 'Global Objectives related', 'globals_helper' => ' ', ], ], 'organization' => [ 'title' => 'Organizations', 'title_singular' => 'Organization', 'fields' => [ 'id' => 'ID', 'id_helper' => ' ', 'name' => 'Nombre de la organización', 'name_helper' => ' ', 'short_description' => 'Short Description', 'short_description_helper' => ' ', 'long_description' => 'Long Description', 'long_description_helper' => ' ', 'email' => 'Email de contacto', 'email_helper' => ' ', 'phone' => 'Teléfono principal', 'phone_helper' => ' ', 'address' => 'Direccion Oficina principal', 'address_helper' => ' ', 'webpage' => 'Webpage', 'webpage_helper' => ' ', 'department' => 'Departamento', 'department_helper' => ' ', 'city' => 'Ciudad', 'city_helper' => ' ', 'logo' => 'Logo', 'logo_helper' => ' ', 'embed_map' => 'Embed Map', 'embed_map_helper' => ' ', 'embed_video' => 'Embed Video', 'embed_video_helper' => ' ', 'created_at' => 'Created at', 'created_at_helper' => ' ', 'updated_at' => 'Updated at', 'updated_at_helper' => ' ', 'deleted_at' => 'Deleted at', 'deleted_at_helper' => ' ', 'tags' => 'Tags (comma separate)', 'tags_helper' => ' ', 'status' => 'Status', 'status_helper' => ' ', 'nit' => 'Nit', 'nit_helper' => 'Solo numeros sin incluirel digito de verificación', 'legal_representant' => 'Representante legal', 'legal_representant_helper' => ' ', 'dcoumenttype' => 'Tipo de documento', 'dcoumenttype_helper' => ' ', 'document' => 'No. documento', 'document_helper' => ' ', 'cargo' => 'Cargo', 'cargo_helper' => ' ', 'main_phone_ext' => 'Ext.', 'main_phone_ext_helper' => ' ', 'postal_code' => 'Código postal', 'postal_code_helper' => ' ', 'finnancial_contact' => 'Contacto financiero', 'finnancial_contact_helper' => ' ', 'finnancial_contact_email' => 'CF Email', 'finnancial_contact_email_helper' => ' ', 'finnancial_contact_phone' => 'CF Teléfono', 'finnancial_contact_phone_helper' => ' ', 'finnancial_contact_ext' => 'CF Ext.', 'finnancial_contact_ext_helper' => ' ', 'contracting_contact' => 'Contacto contratación', 'contracting_contact_helper' => ' ', 'contracting_contact_email' => 'CC Email', 'contracting_contact_email_helper' => ' ', 'contracting_contact_phone' => 'CC Teléfono', 'contracting_contact_phone_helper' => ' ', 'contracting_contact_ext' => 'CC Ext.', 'contracting_contact_ext_helper' => ' ', 'electronic_invoice_contact' => 'Contacto Factura electrónica', 'electronic_invoice_contact_helper' => ' ', 'electronic_invoice_email' => 'FE Email', 'electronic_invoice_email_helper' => ' ', 'electronic_invoice_phone' => 'FE Teléfono', 'electronic_invoice_phone_helper' => ' ', 'electronic_invoice_ext' => 'FE Ext.', 'electronic_invoice_ext_helper' => ' ', 'cash_banks_contact' => 'Contacto Tesorería/Cartera', 'cash_banks_contact_helper' => ' ', 'cash_banks_email' => 'CT Email', 'cash_banks_email_helper' => ' ', 'cash_banks_phone' => 'CT Teléfono', 'cash_banks_phone_helper' => ' ', 'cash_banks_ext' => 'CT Ext.', 'cash_banks_ext_helper' => ' ', 'electronic_invoice_authorized_mail' => 'Email autorizado facturación electrónica', 'electronic_invoice_authorized_mail_helper' => ' ', 'requiere_orden_de_compra' => 'Requiere Orden de Compra', 'requiere_orden_de_compra_helper' => ' ', 'limit_day_to_invoice' => 'Día límite del mes para facturación', 'limit_day_to_invoice_helper' => ' ', 'national_tax_responsible' => 'Responsable de IVA', 'national_tax_responsible_helper' => ' ', 'local_tax_responsible' => 'Responsable ICA Bogota', 'local_tax_responsible_helper' => ' ', 'local_tax_ammount' => 'Tarifa ICA', 'local_tax_ammount_helper' => 'Escriba la tarifa por mil (Ej. 9,66)', 'big_taxpayer' => 'Gran contribuyente', 'big_taxpayer_helper' => ' ', 'big_taxpayer_resolution' => 'GC Resolución No.', 'big_taxpayer_resolution_helper' => ' ', 'seft_taxreteiner' => 'Autorretenedor', 'seft_taxreteiner_helper' => ' ', 'seft_taxreteiner_resolution' => 'AR Resolución', 'seft_taxreteiner_resolution_helper' => ' ', 'rst_tax' => 'Régimen simple de tributación RST', 'rst_tax_helper' => ' ', 'donation_certificate_issuer' => 'Habiltado para emitir certificado de donación', 'donation_certificate_issuer_helper' => ' ', 'payment_collection_time' => 'Tiempo de recaudo', 'payment_collection_time_helper' => ' ', 'disclaimer' => 'Declaracion actividad y origen fondos', 'disclaimer_helper' => ' ', 'information_privacy_check' => 'Autorización manejo datos', 'information_privacy_check_helper' => ' ', 'cc_file' => 'Certificado Existencia y Rep. Legal', 'cc_file_helper' => ' ', 'rl_file' => 'Documento Representante Legal', 'rl_file_helper' => ' ', 'tp_file' => 'Documento RUT', 'tp_file_helper' => ' ', 'ar_file' => 'Resolucion autorretenedor (Si aplica)', 'ar_file_helper' => ' ', 'bc_file' => 'Resolución Gran Contribuyente (Si aplica)', 'bc_file_helper' => ' ', 'comments' => 'Observaciones', 'comments_helper' => ' ', 'organization_type' => 'Tipo de Organización', 'organization_type_helper' => ' ', 'featured' => 'Destacada', 'featured_helper' => ' ', ], ], 'donation' => [ 'title' => 'Donations', 'title_singular' => 'Donation', 'fields' => [ 'id' => 'ID', 'id_helper' => ' ', 'user' => 'User', 'user_helper' => ' ', 'amount' => 'Amount', 'amount_helper' => ' ', 'organization' => 'Organization', 'organization_helper' => ' ', 'created_at' => 'Created at', 'created_at_helper' => ' ', 'updated_at' => 'Updated at', 'updated_at_helper' => ' ', 'deleted_at' => 'Deleted at', 'deleted_at_helper' => ' ', 'certification' => 'Certification', 'certification_helper' => ' ', 'file' => 'Certification File', 'file_helper' => ' ', ], ], 'transaction' => [ 'title' => 'Transactions Log', 'title_singular' => 'Transactions Log', 'fields' => [ 'id' => 'ID', 'id_helper' => ' ', 'merchant' => 'merchant_id', 'merchant_helper' => ' ', 'state_pol' => 'state_pol', 'state_pol_helper' => ' ', 'response_code_pol' => 'response_code_pol', 'response_code_pol_helper' => ' ', 'reference_sale' => 'reference_sale', 'reference_sale_helper' => ' ', 'reference_pol' => 'reference_pol', 'reference_pol_helper' => ' ', 'extra_1' => 'extra1', 'extra_1_helper' => ' ', 'extra_2' => 'extra2', 'extra_2_helper' => ' ', 'payment_method' => 'payment_method', 'payment_method_helper' => ' ', 'payment_method_type' => 'payment_method_type', 'payment_method_type_helper' => ' ', 'installments_number' => 'installments_number', 'installments_number_helper' => ' ', 'value' => 'value', 'value_helper' => ' ', 'tax' => 'tax', 'tax_helper' => ' ', 'transaction_date' => 'transaction_date', 'transaction_date_helper' => ' ', 'email_buyer' => 'email_buyer', 'email_buyer_helper' => ' ', 'cus' => 'cus', 'cus_helper' => ' ', 'pse_bank' => 'pse_bank', 'pse_bank_helper' => ' ', 'description' => 'description', 'description_helper' => ' ', 'billing_address' => 'billing_address', 'billing_address_helper' => ' ', 'shipping_address' => 'shipping_address', 'shipping_address_helper' => ' ', 'phone' => 'phone', 'phone_helper' => ' ', 'account_number_ach' => 'account_number_ach', 'account_number_ach_helper' => ' ', 'account_type_ach' => 'account_type_ach', 'account_type_ach_helper' => ' ', 'administrative_fee' => 'administrative_fee', 'administrative_fee_helper' => ' ', 'administrative_fee_base' => 'administrative_fee_base', 'administrative_fee_base_helper' => ' ', 'administrative_fee_tax' => 'administrative_fee_tax', 'administrative_fee_tax_helper' => ' ', 'authorization_code' => 'authorization_code', 'authorization_code_helper' => ' ', 'bank' => 'bank_id', 'bank_helper' => ' ', 'billing_city' => 'billing_city', 'billing_city_helper' => ' ', 'billing_country' => 'billing_country', 'billing_country_helper' => ' ', 'commision_pol' => 'commision_pol', 'commision_pol_helper' => ' ', 'commision_pol_currency' => 'commision_pol_currency', 'commision_pol_currency_helper' => ' ', 'customer_number' => 'customer_number', 'customer_number_helper' => ' ', 'date' => 'date', 'date_helper' => ' ', 'ip' => 'ip', 'ip_helper' => ' ', 'payment_methodid' => 'payment_method_id', 'payment_methodid_helper' => ' ', 'payment_request_state' => 'payment_request_state', 'payment_request_state_helper' => ' ', 'pse_reference_1' => 'pseReference1', 'pse_reference_1_helper' => ' ', 'pse_reference_2' => 'pseReference2', 'pse_reference_2_helper' => ' ', 'pse_reference_3' => 'pseReference3', 'pse_reference_3_helper' => ' ', 'response_message_pol' => 'response_message_pol', 'response_message_pol_helper' => ' ', 'transaction_bank' => 'transaction_bank_id', 'transaction_bank_helper' => ' ', 'transaction' => 'transaction_id', 'transaction_helper' => ' ', 'payment_method_name' => 'payment_method_name', 'payment_method_name_helper' => ' ', 'created_at' => 'Created at', 'created_at_helper' => ' ', 'updated_at' => 'Updated at', 'updated_at_helper' => ' ', 'deleted_at' => 'Deleted at', 'deleted_at_helper' => ' ', ], ], 'project' => [ 'title' => 'Projects', 'title_singular' => 'Project', 'fields' => [ 'id' => 'ID', 'id_helper' => ' ', 'name' => 'Project Name', 'name_helper' => ' ', 'organization' => 'Organization', 'organization_helper' => ' ', 'description' => 'Description', 'description_helper' => ' ', 'images' => 'Images', 'images_helper' => ' ', 'created_at' => 'Created at', 'created_at_helper' => ' ', 'updated_at' => 'Updated at', 'updated_at_helper' => ' ', 'deleted_at' => 'Deleted at', 'deleted_at_helper' => ' ', ], ], 'automaticDebt' => [ 'title' => 'Automatic Debts', 'title_singular' => 'Automatic Debt', 'fields' => [ 'id' => 'ID', 'id_helper' => ' ', 'transaction' => 'Transaction', 'transaction_helper' => ' ', 'active' => 'Active', 'active_helper' => ' ', 'created_at' => 'Created at', 'created_at_helper' => ' ', 'updated_at' => 'Updated at', 'updated_at_helper' => ' ', 'deleted_at' => 'Deleted at', 'deleted_at_helper' => ' ', ], ], 'userAlert' => [ 'title' => 'User Alerts', 'title_singular' => 'User Alert', 'fields' => [ 'id' => 'ID', 'id_helper' => ' ', 'alert_text' => 'Alert Text', 'alert_text_helper' => ' ', 'alert_link' => 'Alert Link', 'alert_link_helper' => ' ', 'user' => 'Users', 'user_helper' => ' ', 'created_at' => 'Created at', 'created_at_helper' => ' ', 'updated_at' => 'Updated at', 'updated_at_helper' => ' ', ], ], 'globalObj' => [ 'title' => 'Global Objectives', 'title_singular' => 'Global Objective', 'fields' => [ 'id' => 'ID', 'id_helper' => ' ', 'name' => 'Name', 'name_helper' => ' ', 'description' => 'Description', 'description_helper' => ' ', 'created_at' => 'Created at', 'created_at_helper' => ' ', 'updated_at' => 'Updated at', 'updated_at_helper' => ' ', 'deleted_at' => 'Deleted at', 'deleted_at_helper' => ' ', ], ], 'country' => [ 'title' => 'Countries', 'title_singular' => 'Country', 'fields' => [ 'id' => 'ID', 'id_helper' => ' ', 'name' => 'Name', 'name_helper' => ' ', 'short_code' => 'Short Code', 'short_code_helper' => ' ', 'created_at' => 'Created at', 'created_at_helper' => ' ', 'updated_at' => 'Updated at', 'updated_at_helper' => ' ', 'deleted_at' => 'Deleted at', 'deleted_at_helper' => ' ', ], ], 'event' => [ 'title' => 'Events', 'title_singular' => 'Event', 'fields' => [ 'id' => 'ID', 'id_helper' => ' ', 'title' => 'Titulo', 'title_helper' => ' ', 'created_at' => 'Created at', 'created_at_helper' => ' ', 'updated_at' => 'Updated at', 'updated_at_helper' => ' ', 'deleted_at' => 'Deleted at', 'deleted_at_helper' => ' ', 'description' => 'Descripción del evento', 'description_helper' => ' ', 'organization' => 'Organización asociada', 'organization_helper' => ' ', 'start_date' => 'Fecha inicio', 'start_date_helper' => ' ', 'start_time' => 'Hora inicio', 'start_time_helper' => ' ', 'end_date' => 'Fecha fin', 'end_date_helper' => ' ', 'end_time' => 'Hora fin', 'end_time_helper' => ' ', 'status' => 'Status', 'status_helper' => ' ', 'featured' => 'Destacada', 'featured_helper' => ' ', 'image' => 'Imagen', 'image_helper' => ' ', 'file' => 'Archivo', 'file_helper' => ' ', 'comments' => 'Observaciones', 'comments_helper' => ' ', ], ], ]; <file_sep>/database/migrations/2021_08_23_000030_add_relationship_fields_to_users_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class AddRelationshipFieldsToUsersTable extends Migration { public function up() { Schema::table('users', function (Blueprint $table) { $table->unsignedBigInteger('documenttype_id')->nullable(); $table->foreign('documenttype_id', 'documenttype_fk_4699024')->references('id')->on('document_types'); $table->unsignedBigInteger('organization_id')->nullable(); $table->foreign('organization_id', 'organization_fk_4699022')->references('id')->on('organizations'); }); } } <file_sep>/app/Models/Transaction.php <?php namespace App\Models; use \DateTimeInterface; use App\Traits\Auditable; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; class Transaction extends Model { use SoftDeletes; use Auditable; use HasFactory; public $table = 'transactions'; protected $dates = [ 'created_at', 'updated_at', 'deleted_at', ]; protected $fillable = [ 'merchant', 'state_pol', 'response_code_pol', 'reference_sale', 'reference_pol', 'extra_1', 'extra_2', 'payment_method', 'payment_method_type', 'installments_number', 'value', 'tax', 'transaction_date', 'email_buyer', 'cus', 'pse_bank', 'description', 'billing_address', 'shipping_address', 'phone', 'account_number_ach', 'account_type_ach', 'administrative_fee', 'administrative_fee_base', 'administrative_fee_tax', 'authorization_code', 'bank', 'billing_city', 'billing_country', 'commision_pol', 'commision_pol_currency', 'customer_number', 'date', 'ip', 'payment_methodid', 'payment_request_state', 'pse_reference_1', 'pse_reference_2', 'pse_reference_3', 'response_message_pol', 'transaction_bank', 'transaction', 'payment_method_name', 'created_at', 'updated_at', 'deleted_at', ]; public function transactionAutomaticDebts() { return $this->hasMany(AutomaticDebt::class, 'transaction_id', 'id'); } protected function serializeDate(DateTimeInterface $date) { return $date->format('Y-m-d H:i:s'); } } <file_sep>/database/migrations/2021_08_23_000032_add_relationship_fields_to_projects_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class AddRelationshipFieldsToProjectsTable extends Migration { public function up() { Schema::table('projects', function (Blueprint $table) { $table->unsignedBigInteger('organization_id')->nullable(); $table->foreign('organization_id', 'organization_fk_4016563')->references('id')->on('organizations'); }); } } <file_sep>/database/migrations/2021_08_23_000012_create_organizations_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateOrganizationsTable extends Migration { public function up() { Schema::create('organizations', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('name'); $table->integer('nit')->unique(); $table->string('legal_representant'); $table->integer('document'); $table->string('cargo'); $table->string('address'); $table->string('phone'); $table->string('main_phone_ext')->nullable(); $table->string('postal_code')->nullable(); $table->string('email'); $table->string('finnancial_contact')->nullable(); $table->string('finnancial_contact_email')->nullable(); $table->integer('finnancial_contact_phone')->nullable(); $table->string('finnancial_contact_ext')->nullable(); $table->string('contracting_contact')->nullable(); $table->string('contracting_contact_email')->nullable(); $table->string('contracting_contact_phone')->nullable(); $table->string('contracting_contact_ext')->nullable(); $table->string('electronic_invoice_contact')->nullable(); $table->string('electronic_invoice_email')->nullable(); $table->integer('electronic_invoice_phone')->nullable(); $table->string('electronic_invoice_ext')->nullable(); $table->string('cash_banks_contact')->nullable(); $table->string('cash_banks_email')->nullable(); $table->integer('cash_banks_phone')->nullable(); $table->string('cash_banks_ext')->nullable(); $table->string('electronic_invoice_authorized_mail')->nullable(); $table->string('requiere_orden_de_compra')->nullable(); $table->integer('limit_day_to_invoice')->nullable(); $table->boolean('national_tax_responsible')->default(0)->nullable(); $table->boolean('local_tax_responsible')->default(0)->nullable(); $table->float('local_tax_ammount', 15, 2)->nullable(); $table->boolean('big_taxpayer')->default(0)->nullable(); $table->string('big_taxpayer_resolution')->nullable(); $table->boolean('seft_taxreteiner')->default(0)->nullable(); $table->string('seft_taxreteiner_resolution')->nullable(); $table->boolean('rst_tax')->default(0)->nullable(); $table->boolean('donation_certificate_issuer')->default(0)->nullable(); $table->string('payment_collection_time')->nullable(); $table->boolean('disclaimer')->default(0)->nullable(); $table->boolean('information_privacy_check')->default(0)->nullable(); $table->string('bc_file')->nullable(); $table->longText('short_description')->nullable(); $table->string('long_description')->nullable(); $table->string('webpage')->nullable(); $table->longText('embed_map')->nullable(); $table->longText('embed_video')->nullable(); $table->string('tags')->nullable(); $table->string('status')->nullable(); $table->boolean('featured')->default(0)->nullable(); $table->longText('comments')->nullable(); $table->timestamps(); $table->softDeletes(); }); } } <file_sep>/resources/lang/es/panel.php <?php return [ 'site_title' => 'Donalma', ]; <file_sep>/app/Http/Controllers/Admin/EventsController.php <?php namespace App\Http\Controllers\Admin; use App\Http\Controllers\Controller; use App\Http\Controllers\Traits\CsvImportTrait; use App\Http\Controllers\Traits\MediaUploadingTrait; use App\Http\Requests\MassDestroyEventRequest; use App\Http\Requests\StoreEventRequest; use App\Http\Requests\UpdateEventRequest; use App\Models\Event; use App\Models\Organization; use Gate; use Illuminate\Http\Request; use Spatie\MediaLibrary\MediaCollections\Models\Media; use Symfony\Component\HttpFoundation\Response; use Yajra\DataTables\Facades\DataTables; class EventsController extends Controller { use MediaUploadingTrait; use CsvImportTrait; public function index(Request $request) { abort_if(Gate::denies('event_access'), Response::HTTP_FORBIDDEN, '403 Forbidden'); if ($request->ajax()) { $query = Event::with(['organization'])->select(sprintf('%s.*', (new Event())->table)); $table = Datatables::of($query); $table->addColumn('placeholder', '&nbsp;'); $table->addColumn('actions', '&nbsp;'); $table->editColumn('actions', function ($row) { $viewGate = 'event_show'; $editGate = 'event_edit'; $deleteGate = 'event_delete'; $crudRoutePart = 'events'; return view('partials.datatablesActions', compact( 'viewGate', 'editGate', 'deleteGate', 'crudRoutePart', 'row' )); }); $table->editColumn('id', function ($row) { return $row->id ? $row->id : ''; }); $table->editColumn('title', function ($row) { return $row->title ? $row->title : ''; }); $table->addColumn('organization_name', function ($row) { return $row->organization ? $row->organization->name : ''; }); $table->editColumn('start_time', function ($row) { return $row->start_time ? $row->start_time : ''; }); $table->editColumn('end_time', function ($row) { return $row->end_time ? $row->end_time : ''; }); $table->editColumn('status', function ($row) { return $row->status ? Event::STATUS_SELECT[$row->status] : ''; }); $table->editColumn('featured', function ($row) { return $row->featured ? $row->featured : ''; }); $table->editColumn('image', function ($row) { if ($photo = $row->image) { return sprintf( '<a href="%s" target="_blank"><img src="%s" width="50px" height="50px"></a>', $photo->url, $photo->thumbnail ); } return ''; }); $table->editColumn('file', function ($row) { return $row->file ? $row->file : ''; }); $table->editColumn('comments', function ($row) { return $row->comments ? $row->comments : ''; }); $table->rawColumns(['actions', 'placeholder', 'organization', 'image']); return $table->make(true); } return view('admin.events.index'); } public function create() { abort_if(Gate::denies('event_create'), Response::HTTP_FORBIDDEN, '403 Forbidden'); $organizations = Organization::pluck('name', 'id')->prepend(trans('global.pleaseSelect'), ''); return view('admin.events.create', compact('organizations')); } public function store(StoreEventRequest $request) { $event = Event::create($request->all()); if ($request->input('image', false)) { $event->addMedia(storage_path('tmp/uploads/' . basename($request->input('image'))))->toMediaCollection('image'); } if ($media = $request->input('ck-media', false)) { Media::whereIn('id', $media)->update(['model_id' => $event->id]); } return redirect()->route('admin.events.index'); } public function edit(Event $event) { abort_if(Gate::denies('event_edit'), Response::HTTP_FORBIDDEN, '403 Forbidden'); $organizations = Organization::pluck('name', 'id')->prepend(trans('global.pleaseSelect'), ''); $event->load('organization'); return view('admin.events.edit', compact('organizations', 'event')); } public function update(UpdateEventRequest $request, Event $event) { $event->update($request->all()); if ($request->input('image', false)) { if (!$event->image || $request->input('image') !== $event->image->file_name) { if ($event->image) { $event->image->delete(); } $event->addMedia(storage_path('tmp/uploads/' . basename($request->input('image'))))->toMediaCollection('image'); } } elseif ($event->image) { $event->image->delete(); } return redirect()->route('admin.events.index'); } public function show(Event $event) { abort_if(Gate::denies('event_show'), Response::HTTP_FORBIDDEN, '403 Forbidden'); $event->load('organization'); return view('admin.events.show', compact('event')); } public function destroy(Event $event) { abort_if(Gate::denies('event_delete'), Response::HTTP_FORBIDDEN, '403 Forbidden'); $event->delete(); return back(); } public function massDestroy(MassDestroyEventRequest $request) { Event::whereIn('id', request('ids'))->delete(); return response(null, Response::HTTP_NO_CONTENT); } public function storeCKEditorImages(Request $request) { abort_if(Gate::denies('event_create') && Gate::denies('event_edit'), Response::HTTP_FORBIDDEN, '403 Forbidden'); $model = new Event(); $model->id = $request->input('crud_id', 0); $model->exists = true; $media = $model->addMediaFromRequest('upload')->toMediaCollection('ck-media'); return response()->json(['id' => $media->id, 'url' => $media->getUrl()], Response::HTTP_CREATED); } } <file_sep>/app/Http/Controllers/Api/V1/Admin/EventsApiController.php <?php namespace App\Http\Controllers\Api\V1\Admin; use App\Http\Controllers\Controller; use App\Http\Controllers\Traits\MediaUploadingTrait; use App\Http\Requests\StoreEventRequest; use App\Http\Requests\UpdateEventRequest; use App\Http\Resources\Admin\EventResource; use App\Models\Event; use Gate; use Illuminate\Http\Request; use Symfony\Component\HttpFoundation\Response; class EventsApiController extends Controller { use MediaUploadingTrait; public function index() { abort_if(Gate::denies('event_access'), Response::HTTP_FORBIDDEN, '403 Forbidden'); return new EventResource(Event::with(['organization'])->get()); } public function store(StoreEventRequest $request) { $event = Event::create($request->all()); if ($request->input('image', false)) { $event->addMedia(storage_path('tmp/uploads/' . basename($request->input('image'))))->toMediaCollection('image'); } return (new EventResource($event)) ->response() ->setStatusCode(Response::HTTP_CREATED); } public function show(Event $event) { abort_if(Gate::denies('event_show'), Response::HTTP_FORBIDDEN, '403 Forbidden'); return new EventResource($event->load(['organization'])); } public function update(UpdateEventRequest $request, Event $event) { $event->update($request->all()); if ($request->input('image', false)) { if (!$event->image || $request->input('image') !== $event->image->file_name) { if ($event->image) { $event->image->delete(); } $event->addMedia(storage_path('tmp/uploads/' . basename($request->input('image'))))->toMediaCollection('image'); } } elseif ($event->image) { $event->image->delete(); } return (new EventResource($event)) ->response() ->setStatusCode(Response::HTTP_ACCEPTED); } public function destroy(Event $event) { abort_if(Gate::denies('event_delete'), Response::HTTP_FORBIDDEN, '403 Forbidden'); $event->delete(); return response(null, Response::HTTP_NO_CONTENT); } } <file_sep>/app/Http/Controllers/Admin/GlobalObjController.php <?php namespace App\Http\Controllers\Admin; use App\Http\Controllers\Controller; use App\Http\Requests\MassDestroyGlobalObjRequest; use App\Http\Requests\StoreGlobalObjRequest; use App\Http\Requests\UpdateGlobalObjRequest; use App\Models\GlobalObj; use Gate; use Illuminate\Http\Request; use Symfony\Component\HttpFoundation\Response; class GlobalObjController extends Controller { public function index() { abort_if(Gate::denies('global_obj_access'), Response::HTTP_FORBIDDEN, '403 Forbidden'); $globalObjs = GlobalObj::all(); return view('admin.globalObjs.index', compact('globalObjs')); } public function create() { abort_if(Gate::denies('global_obj_create'), Response::HTTP_FORBIDDEN, '403 Forbidden'); return view('admin.globalObjs.create'); } public function store(StoreGlobalObjRequest $request) { $globalObj = GlobalObj::create($request->all()); return redirect()->route('admin.global-objs.index'); } public function edit(GlobalObj $globalObj) { abort_if(Gate::denies('global_obj_edit'), Response::HTTP_FORBIDDEN, '403 Forbidden'); return view('admin.globalObjs.edit', compact('globalObj')); } public function update(UpdateGlobalObjRequest $request, GlobalObj $globalObj) { $globalObj->update($request->all()); return redirect()->route('admin.global-objs.index'); } public function show(GlobalObj $globalObj) { abort_if(Gate::denies('global_obj_show'), Response::HTTP_FORBIDDEN, '403 Forbidden'); return view('admin.globalObjs.show', compact('globalObj')); } public function destroy(GlobalObj $globalObj) { abort_if(Gate::denies('global_obj_delete'), Response::HTTP_FORBIDDEN, '403 Forbidden'); $globalObj->delete(); return back(); } public function massDestroy(MassDestroyGlobalObjRequest $request) { GlobalObj::whereIn('id', request('ids'))->delete(); return response(null, Response::HTTP_NO_CONTENT); } } <file_sep>/database/migrations/2021_08_23_000025_create_organization_type_pivot_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateOrganizationTypePivotTable extends Migration { public function up() { Schema::create('organization_type', function (Blueprint $table) { $table->unsignedBigInteger('organization_id'); $table->foreign('organization_id', 'organization_id_fk_4571548')->references('id')->on('organizations')->onDelete('cascade'); $table->unsignedBigInteger('type_id'); $table->foreign('type_id', 'type_id_fk_4571548')->references('id')->on('types')->onDelete('cascade'); }); } } <file_sep>/app/Http/Controllers/Admin/TransactionsController.php <?php namespace App\Http\Controllers\Admin; use App\Http\Controllers\Controller; use App\Http\Requests\MassDestroyTransactionRequest; use App\Http\Requests\StoreTransactionRequest; use App\Http\Requests\UpdateTransactionRequest; use App\Models\Transaction; use Gate; use Illuminate\Http\Request; use Symfony\Component\HttpFoundation\Response; use Yajra\DataTables\Facades\DataTables; class TransactionsController extends Controller { public function index(Request $request) { abort_if(Gate::denies('transaction_access'), Response::HTTP_FORBIDDEN, '403 Forbidden'); if ($request->ajax()) { $query = Transaction::query()->select(sprintf('%s.*', (new Transaction())->table)); $table = Datatables::of($query); $table->addColumn('placeholder', '&nbsp;'); $table->addColumn('actions', '&nbsp;'); $table->editColumn('actions', function ($row) { $viewGate = 'transaction_show'; $editGate = 'transaction_edit'; $deleteGate = 'transaction_delete'; $crudRoutePart = 'transactions'; return view('partials.datatablesActions', compact( 'viewGate', 'editGate', 'deleteGate', 'crudRoutePart', 'row' )); }); $table->editColumn('id', function ($row) { return $row->id ? $row->id : ''; }); $table->editColumn('merchant', function ($row) { return $row->merchant ? $row->merchant : ''; }); $table->editColumn('state_pol', function ($row) { return $row->state_pol ? $row->state_pol : ''; }); $table->editColumn('response_code_pol', function ($row) { return $row->response_code_pol ? $row->response_code_pol : ''; }); $table->editColumn('reference_sale', function ($row) { return $row->reference_sale ? $row->reference_sale : ''; }); $table->editColumn('reference_pol', function ($row) { return $row->reference_pol ? $row->reference_pol : ''; }); $table->editColumn('extra_1', function ($row) { return $row->extra_1 ? $row->extra_1 : ''; }); $table->editColumn('extra_2', function ($row) { return $row->extra_2 ? $row->extra_2 : ''; }); $table->editColumn('payment_method', function ($row) { return $row->payment_method ? $row->payment_method : ''; }); $table->editColumn('payment_method_type', function ($row) { return $row->payment_method_type ? $row->payment_method_type : ''; }); $table->editColumn('installments_number', function ($row) { return $row->installments_number ? $row->installments_number : ''; }); $table->editColumn('value', function ($row) { return $row->value ? $row->value : ''; }); $table->editColumn('tax', function ($row) { return $row->tax ? $row->tax : ''; }); $table->editColumn('transaction_date', function ($row) { return $row->transaction_date ? $row->transaction_date : ''; }); $table->editColumn('email_buyer', function ($row) { return $row->email_buyer ? $row->email_buyer : ''; }); $table->editColumn('cus', function ($row) { return $row->cus ? $row->cus : ''; }); $table->editColumn('pse_bank', function ($row) { return $row->pse_bank ? $row->pse_bank : ''; }); $table->editColumn('description', function ($row) { return $row->description ? $row->description : ''; }); $table->editColumn('billing_address', function ($row) { return $row->billing_address ? $row->billing_address : ''; }); $table->editColumn('shipping_address', function ($row) { return $row->shipping_address ? $row->shipping_address : ''; }); $table->editColumn('phone', function ($row) { return $row->phone ? $row->phone : ''; }); $table->editColumn('account_number_ach', function ($row) { return $row->account_number_ach ? $row->account_number_ach : ''; }); $table->editColumn('account_type_ach', function ($row) { return $row->account_type_ach ? $row->account_type_ach : ''; }); $table->editColumn('administrative_fee', function ($row) { return $row->administrative_fee ? $row->administrative_fee : ''; }); $table->editColumn('administrative_fee_base', function ($row) { return $row->administrative_fee_base ? $row->administrative_fee_base : ''; }); $table->editColumn('administrative_fee_tax', function ($row) { return $row->administrative_fee_tax ? $row->administrative_fee_tax : ''; }); $table->editColumn('authorization_code', function ($row) { return $row->authorization_code ? $row->authorization_code : ''; }); $table->editColumn('bank', function ($row) { return $row->bank ? $row->bank : ''; }); $table->editColumn('billing_city', function ($row) { return $row->billing_city ? $row->billing_city : ''; }); $table->editColumn('billing_country', function ($row) { return $row->billing_country ? $row->billing_country : ''; }); $table->editColumn('commision_pol', function ($row) { return $row->commision_pol ? $row->commision_pol : ''; }); $table->editColumn('commision_pol_currency', function ($row) { return $row->commision_pol_currency ? $row->commision_pol_currency : ''; }); $table->editColumn('customer_number', function ($row) { return $row->customer_number ? $row->customer_number : ''; }); $table->editColumn('date', function ($row) { return $row->date ? $row->date : ''; }); $table->editColumn('ip', function ($row) { return $row->ip ? $row->ip : ''; }); $table->editColumn('payment_methodid', function ($row) { return $row->payment_methodid ? $row->payment_methodid : ''; }); $table->editColumn('payment_request_state', function ($row) { return $row->payment_request_state ? $row->payment_request_state : ''; }); $table->editColumn('pse_reference_1', function ($row) { return $row->pse_reference_1 ? $row->pse_reference_1 : ''; }); $table->editColumn('pse_reference_2', function ($row) { return $row->pse_reference_2 ? $row->pse_reference_2 : ''; }); $table->editColumn('pse_reference_3', function ($row) { return $row->pse_reference_3 ? $row->pse_reference_3 : ''; }); $table->editColumn('response_message_pol', function ($row) { return $row->response_message_pol ? $row->response_message_pol : ''; }); $table->editColumn('transaction_bank', function ($row) { return $row->transaction_bank ? $row->transaction_bank : ''; }); $table->editColumn('transaction', function ($row) { return $row->transaction ? $row->transaction : ''; }); $table->editColumn('payment_method_name', function ($row) { return $row->payment_method_name ? $row->payment_method_name : ''; }); $table->rawColumns(['actions', 'placeholder']); return $table->make(true); } return view('admin.transactions.index'); } public function create() { abort_if(Gate::denies('transaction_create'), Response::HTTP_FORBIDDEN, '403 Forbidden'); return view('admin.transactions.create'); } public function store(StoreTransactionRequest $request) { $transaction = Transaction::create($request->all()); return redirect()->route('admin.transactions.index'); } public function edit(Transaction $transaction) { abort_if(Gate::denies('transaction_edit'), Response::HTTP_FORBIDDEN, '403 Forbidden'); return view('admin.transactions.edit', compact('transaction')); } public function update(UpdateTransactionRequest $request, Transaction $transaction) { $transaction->update($request->all()); return redirect()->route('admin.transactions.index'); } public function show(Transaction $transaction) { abort_if(Gate::denies('transaction_show'), Response::HTTP_FORBIDDEN, '403 Forbidden'); $transaction->load('transactionAutomaticDebts'); return view('admin.transactions.show', compact('transaction')); } public function destroy(Transaction $transaction) { abort_if(Gate::denies('transaction_delete'), Response::HTTP_FORBIDDEN, '403 Forbidden'); $transaction->delete(); return back(); } public function massDestroy(MassDestroyTransactionRequest $request) { Transaction::whereIn('id', request('ids'))->delete(); return response(null, Response::HTTP_NO_CONTENT); } } <file_sep>/app/Models/Organization.php <?php namespace App\Models; use \DateTimeInterface; use App\Traits\Auditable; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; use Spatie\MediaLibrary\HasMedia; use Spatie\MediaLibrary\InteractsWithMedia; use Spatie\MediaLibrary\MediaCollections\Models\Media; class Organization extends Model implements HasMedia { use SoftDeletes; use InteractsWithMedia; use Auditable; use HasFactory; public const REQUIERE_ORDEN_DE_COMPRA_RADIO = [ 'Si' => 'Si', 'No' => 'No', ]; public const STATUS_SELECT = [ 'Activo' => 'Activo', 'Inactivo' => 'Inactivo', 'Suspendido' => 'Suspendido', ]; public const PAYMENT_COLLECTION_TIME_SELECT = [ '30' => '30 días', '45' => '45 días', '60' => '60 días', '0' => 'Otro', ]; public $table = 'organizations'; protected $dates = [ 'created_at', 'updated_at', 'deleted_at', ]; protected $appends = [ 'cc_file', 'rl_file', 'tp_file', 'ar_file', 'logo', ]; protected $fillable = [ 'name', 'nit', 'legal_representant', 'dcoumenttype_id', 'document', 'cargo', 'address', 'department_id', 'city_id', 'phone', 'main_phone_ext', 'postal_code', 'email', 'finnancial_contact', 'finnancial_contact_email', 'finnancial_contact_phone', 'finnancial_contact_ext', 'contracting_contact', 'contracting_contact_email', 'contracting_contact_phone', 'contracting_contact_ext', 'electronic_invoice_contact', 'electronic_invoice_email', 'electronic_invoice_phone', 'electronic_invoice_ext', 'cash_banks_contact', 'cash_banks_email', 'cash_banks_phone', 'cash_banks_ext', 'electronic_invoice_authorized_mail', 'requiere_orden_de_compra', 'limit_day_to_invoice', 'national_tax_responsible', 'local_tax_responsible', 'local_tax_ammount', 'big_taxpayer', 'big_taxpayer_resolution', 'seft_taxreteiner', 'seft_taxreteiner_resolution', 'rst_tax', 'donation_certificate_issuer', 'payment_collection_time', 'disclaimer', 'information_privacy_check', 'bc_file', 'short_description', 'long_description', 'webpage', 'embed_map', 'embed_video', 'tags', 'status', 'featured', 'comments', 'created_at', 'updated_at', 'deleted_at', ]; public function registerMediaConversions(Media $media = null): void { $this->addMediaConversion('thumb')->fit('crop', 50, 50); $this->addMediaConversion('preview')->fit('crop', 120, 120); } public function organizationDonations() { return $this->hasMany(Donation::class, 'organization_id', 'id'); } public function organizationProjects() { return $this->hasMany(Project::class, 'organization_id', 'id'); } public function organizationUsers() { return $this->hasMany(User::class, 'organization_id', 'id'); } public function organizationEvents() { return $this->hasMany(Event::class, 'organization_id', 'id'); } public function organization_types() { return $this->belongsToMany(Type::class); } public function dcoumenttype() { return $this->belongsTo(DocumentType::class, 'dcoumenttype_id'); } public function department() { return $this->belongsTo(Department::class, 'department_id'); } public function city() { return $this->belongsTo(City::class, 'city_id'); } public function getCcFileAttribute() { return $this->getMedia('cc_file')->last(); } public function getRlFileAttribute() { return $this->getMedia('rl_file')->last(); } public function getTpFileAttribute() { return $this->getMedia('tp_file')->last(); } public function getArFileAttribute() { return $this->getMedia('ar_file')->last(); } public function getLogoAttribute() { $file = $this->getMedia('logo')->last(); if ($file) { $file->url = $file->getUrl(); $file->thumbnail = $file->getUrl('thumb'); $file->preview = $file->getUrl('preview'); } return $file; } protected function serializeDate(DateTimeInterface $date) { return $date->format('Y-m-d H:i:s'); } } <file_sep>/database/migrations/2021_08_23_000024_create_global_obj_type_pivot_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateGlobalObjTypePivotTable extends Migration { public function up() { Schema::create('global_obj_type', function (Blueprint $table) { $table->unsignedBigInteger('type_id'); $table->foreign('type_id', 'type_id_fk_4699004')->references('id')->on('types')->onDelete('cascade'); $table->unsignedBigInteger('global_obj_id'); $table->foreign('global_obj_id', 'global_obj_id_fk_4699004')->references('id')->on('global_objs')->onDelete('cascade'); }); } } <file_sep>/app/Http/Controllers/Api/V1/Admin/OrganizationsApiController.php <?php namespace App\Http\Controllers\Api\V1\Admin; use App\Http\Controllers\Controller; use App\Http\Controllers\Traits\MediaUploadingTrait; use App\Http\Requests\StoreOrganizationRequest; use App\Http\Requests\UpdateOrganizationRequest; use App\Http\Resources\Admin\OrganizationResource; use App\Models\Organization; use Gate; use Illuminate\Http\Request; use Symfony\Component\HttpFoundation\Response; class OrganizationsApiController extends Controller { use MediaUploadingTrait; public function index() { abort_if(Gate::denies('organization_access'), Response::HTTP_FORBIDDEN, '403 Forbidden'); return new OrganizationResource(Organization::with(['organization_types', 'dcoumenttype', 'department', 'city'])->get()); } public function store(StoreOrganizationRequest $request) { $organization = Organization::create($request->all()); $organization->organization_types()->sync($request->input('organization_types', [])); if ($request->input('cc_file', false)) { $organization->addMedia(storage_path('tmp/uploads/' . basename($request->input('cc_file'))))->toMediaCollection('cc_file'); } if ($request->input('rl_file', false)) { $organization->addMedia(storage_path('tmp/uploads/' . basename($request->input('rl_file'))))->toMediaCollection('rl_file'); } if ($request->input('tp_file', false)) { $organization->addMedia(storage_path('tmp/uploads/' . basename($request->input('tp_file'))))->toMediaCollection('tp_file'); } if ($request->input('ar_file', false)) { $organization->addMedia(storage_path('tmp/uploads/' . basename($request->input('ar_file'))))->toMediaCollection('ar_file'); } if ($request->input('logo', false)) { $organization->addMedia(storage_path('tmp/uploads/' . basename($request->input('logo'))))->toMediaCollection('logo'); } return (new OrganizationResource($organization)) ->response() ->setStatusCode(Response::HTTP_CREATED); } public function show(Organization $organization) { abort_if(Gate::denies('organization_show'), Response::HTTP_FORBIDDEN, '403 Forbidden'); return new OrganizationResource($organization->load(['organization_types', 'dcoumenttype', 'department', 'city'])); } public function update(UpdateOrganizationRequest $request, Organization $organization) { $organization->update($request->all()); $organization->organization_types()->sync($request->input('organization_types', [])); if ($request->input('cc_file', false)) { if (!$organization->cc_file || $request->input('cc_file') !== $organization->cc_file->file_name) { if ($organization->cc_file) { $organization->cc_file->delete(); } $organization->addMedia(storage_path('tmp/uploads/' . basename($request->input('cc_file'))))->toMediaCollection('cc_file'); } } elseif ($organization->cc_file) { $organization->cc_file->delete(); } if ($request->input('rl_file', false)) { if (!$organization->rl_file || $request->input('rl_file') !== $organization->rl_file->file_name) { if ($organization->rl_file) { $organization->rl_file->delete(); } $organization->addMedia(storage_path('tmp/uploads/' . basename($request->input('rl_file'))))->toMediaCollection('rl_file'); } } elseif ($organization->rl_file) { $organization->rl_file->delete(); } if ($request->input('tp_file', false)) { if (!$organization->tp_file || $request->input('tp_file') !== $organization->tp_file->file_name) { if ($organization->tp_file) { $organization->tp_file->delete(); } $organization->addMedia(storage_path('tmp/uploads/' . basename($request->input('tp_file'))))->toMediaCollection('tp_file'); } } elseif ($organization->tp_file) { $organization->tp_file->delete(); } if ($request->input('ar_file', false)) { if (!$organization->ar_file || $request->input('ar_file') !== $organization->ar_file->file_name) { if ($organization->ar_file) { $organization->ar_file->delete(); } $organization->addMedia(storage_path('tmp/uploads/' . basename($request->input('ar_file'))))->toMediaCollection('ar_file'); } } elseif ($organization->ar_file) { $organization->ar_file->delete(); } if ($request->input('logo', false)) { if (!$organization->logo || $request->input('logo') !== $organization->logo->file_name) { if ($organization->logo) { $organization->logo->delete(); } $organization->addMedia(storage_path('tmp/uploads/' . basename($request->input('logo'))))->toMediaCollection('logo'); } } elseif ($organization->logo) { $organization->logo->delete(); } return (new OrganizationResource($organization)) ->response() ->setStatusCode(Response::HTTP_ACCEPTED); } public function destroy(Organization $organization) { abort_if(Gate::denies('organization_delete'), Response::HTTP_FORBIDDEN, '403 Forbidden'); $organization->delete(); return response(null, Response::HTTP_NO_CONTENT); } } <file_sep>/app/Http/Controllers/Admin/DocumentTypesController.php <?php namespace App\Http\Controllers\Admin; use App\Http\Controllers\Controller; use App\Http\Requests\MassDestroyDocumentTypeRequest; use App\Http\Requests\StoreDocumentTypeRequest; use App\Http\Requests\UpdateDocumentTypeRequest; use App\Models\DocumentType; use Gate; use Illuminate\Http\Request; use Symfony\Component\HttpFoundation\Response; class DocumentTypesController extends Controller { public function index() { abort_if(Gate::denies('document_type_access'), Response::HTTP_FORBIDDEN, '403 Forbidden'); $documentTypes = DocumentType::all(); return view('admin.documentTypes.index', compact('documentTypes')); } public function create() { abort_if(Gate::denies('document_type_create'), Response::HTTP_FORBIDDEN, '403 Forbidden'); return view('admin.documentTypes.create'); } public function store(StoreDocumentTypeRequest $request) { $documentType = DocumentType::create($request->all()); return redirect()->route('admin.document-types.index'); } public function edit(DocumentType $documentType) { abort_if(Gate::denies('document_type_edit'), Response::HTTP_FORBIDDEN, '403 Forbidden'); return view('admin.documentTypes.edit', compact('documentType')); } public function update(UpdateDocumentTypeRequest $request, DocumentType $documentType) { $documentType->update($request->all()); return redirect()->route('admin.document-types.index'); } public function show(DocumentType $documentType) { abort_if(Gate::denies('document_type_show'), Response::HTTP_FORBIDDEN, '403 Forbidden'); $documentType->load('documenttypeUsers'); return view('admin.documentTypes.show', compact('documentType')); } public function destroy(DocumentType $documentType) { abort_if(Gate::denies('document_type_delete'), Response::HTTP_FORBIDDEN, '403 Forbidden'); $documentType->delete(); return back(); } public function massDestroy(MassDestroyDocumentTypeRequest $request) { DocumentType::whereIn('id', request('ids'))->delete(); return response(null, Response::HTTP_NO_CONTENT); } } <file_sep>/app/Http/Controllers/Admin/TypesController.php <?php namespace App\Http\Controllers\Admin; use App\Http\Controllers\Controller; use App\Http\Controllers\Traits\MediaUploadingTrait; use App\Http\Requests\MassDestroyTypeRequest; use App\Http\Requests\StoreTypeRequest; use App\Http\Requests\UpdateTypeRequest; use App\Models\GlobalObj; use App\Models\Type; use Gate; use Illuminate\Http\Request; use Spatie\MediaLibrary\MediaCollections\Models\Media; use Symfony\Component\HttpFoundation\Response; class TypesController extends Controller { use MediaUploadingTrait; public function index() { abort_if(Gate::denies('type_access'), Response::HTTP_FORBIDDEN, '403 Forbidden'); $types = Type::with(['globals', 'media'])->get(); return view('admin.types.index', compact('types')); } public function create() { abort_if(Gate::denies('type_create'), Response::HTTP_FORBIDDEN, '403 Forbidden'); $globals = GlobalObj::pluck('name', 'id'); return view('admin.types.create', compact('globals')); } public function store(StoreTypeRequest $request) { $type = Type::create($request->all()); $type->globals()->sync($request->input('globals', [])); foreach ($request->input('image', []) as $file) { $type->addMedia(storage_path('tmp/uploads/' . basename($file)))->toMediaCollection('image'); } if ($media = $request->input('ck-media', false)) { Media::whereIn('id', $media)->update(['model_id' => $type->id]); } return redirect()->route('admin.types.index'); } public function edit(Type $type) { abort_if(Gate::denies('type_edit'), Response::HTTP_FORBIDDEN, '403 Forbidden'); $globals = GlobalObj::pluck('name', 'id'); $type->load('globals'); return view('admin.types.edit', compact('globals', 'type')); } public function update(UpdateTypeRequest $request, Type $type) { $type->update($request->all()); $type->globals()->sync($request->input('globals', [])); if (count($type->image) > 0) { foreach ($type->image as $media) { if (!in_array($media->file_name, $request->input('image', []))) { $media->delete(); } } } $media = $type->image->pluck('file_name')->toArray(); foreach ($request->input('image', []) as $file) { if (count($media) === 0 || !in_array($file, $media)) { $type->addMedia(storage_path('tmp/uploads/' . basename($file)))->toMediaCollection('image'); } } return redirect()->route('admin.types.index'); } public function show(Type $type) { abort_if(Gate::denies('type_show'), Response::HTTP_FORBIDDEN, '403 Forbidden'); $type->load('globals'); return view('admin.types.show', compact('type')); } public function destroy(Type $type) { abort_if(Gate::denies('type_delete'), Response::HTTP_FORBIDDEN, '403 Forbidden'); $type->delete(); return back(); } public function massDestroy(MassDestroyTypeRequest $request) { Type::whereIn('id', request('ids'))->delete(); return response(null, Response::HTTP_NO_CONTENT); } public function storeCKEditorImages(Request $request) { abort_if(Gate::denies('type_create') && Gate::denies('type_edit'), Response::HTTP_FORBIDDEN, '403 Forbidden'); $model = new Type(); $model->id = $request->input('crud_id', 0); $model->exists = true; $media = $model->addMediaFromRequest('upload')->toMediaCollection('ck-media'); return response()->json(['id' => $media->id, 'url' => $media->getUrl()], Response::HTTP_CREATED); } } <file_sep>/app/Http/Requests/UpdateOrganizationRequest.php <?php namespace App\Http\Requests; use App\Models\Organization; use Gate; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Http\Response; class UpdateOrganizationRequest extends FormRequest { public function authorize() { return Gate::allows('organization_edit'); } public function rules() { return [ 'name' => [ 'string', 'required', ], 'organization_types.*' => [ 'integer', ], 'organization_types' => [ 'required', 'array', ], 'nit' => [ 'required', 'integer', 'min:-2147483648', 'max:2147483647', 'unique:organizations,nit,' . request()->route('organization')->id, ], 'legal_representant' => [ 'string', 'required', ], 'dcoumenttype_id' => [ 'required', 'integer', ], 'document' => [ 'required', 'integer', 'min:-2147483648', 'max:2147483647', ], 'cargo' => [ 'string', 'required', ], 'address' => [ 'string', 'required', ], 'department_id' => [ 'required', 'integer', ], 'city_id' => [ 'required', 'integer', ], 'phone' => [ 'string', 'required', ], 'main_phone_ext' => [ 'string', 'nullable', ], 'postal_code' => [ 'string', 'nullable', ], 'email' => [ 'required', ], 'finnancial_contact' => [ 'string', 'nullable', ], 'finnancial_contact_phone' => [ 'nullable', 'integer', 'min:-2147483648', 'max:2147483647', ], 'finnancial_contact_ext' => [ 'string', 'nullable', ], 'contracting_contact' => [ 'string', 'nullable', ], 'contracting_contact_phone' => [ 'string', 'nullable', ], 'contracting_contact_ext' => [ 'string', 'nullable', ], 'electronic_invoice_contact' => [ 'string', 'nullable', ], 'electronic_invoice_phone' => [ 'nullable', 'integer', 'min:-2147483648', 'max:2147483647', ], 'electronic_invoice_ext' => [ 'string', 'nullable', ], 'cash_banks_contact' => [ 'string', 'nullable', ], 'cash_banks_phone' => [ 'nullable', 'integer', 'min:-2147483648', 'max:2147483647', ], 'cash_banks_ext' => [ 'string', 'nullable', ], 'limit_day_to_invoice' => [ 'nullable', 'integer', 'min:-2147483648', 'max:2147483647', ], 'local_tax_ammount' => [ 'numeric', ], 'big_taxpayer_resolution' => [ 'string', 'nullable', ], 'seft_taxreteiner_resolution' => [ 'string', 'nullable', ], 'bc_file' => [ 'string', 'nullable', ], 'long_description' => [ 'string', 'nullable', ], 'webpage' => [ 'string', 'nullable', ], 'tags' => [ 'string', 'nullable', ], ]; } } <file_sep>/app/Http/Controllers/Admin/OrganizationsController.php <?php namespace App\Http\Controllers\Admin; use App\Http\Controllers\Controller; use App\Http\Controllers\Traits\CsvImportTrait; use App\Http\Controllers\Traits\MediaUploadingTrait; use App\Http\Requests\MassDestroyOrganizationRequest; use App\Http\Requests\StoreOrganizationRequest; use App\Http\Requests\UpdateOrganizationRequest; use App\Models\City; use App\Models\Department; use App\Models\DocumentType; use App\Models\Organization; use App\Models\Type; use Gate; use Illuminate\Http\Request; use Spatie\MediaLibrary\MediaCollections\Models\Media; use Symfony\Component\HttpFoundation\Response; use Yajra\DataTables\Facades\DataTables; class OrganizationsController extends Controller { use MediaUploadingTrait; use CsvImportTrait; public function index(Request $request) { abort_if(Gate::denies('organization_access'), Response::HTTP_FORBIDDEN, '403 Forbidden'); if ($request->ajax()) { $query = Organization::with(['organization_types', 'dcoumenttype', 'department', 'city'])->select(sprintf('%s.*', (new Organization())->table)); $table = Datatables::of($query); $table->addColumn('placeholder', '&nbsp;'); $table->addColumn('actions', '&nbsp;'); $table->editColumn('actions', function ($row) { $viewGate = 'organization_show'; $editGate = 'organization_edit'; $deleteGate = 'organization_delete'; $crudRoutePart = 'organizations'; return view('partials.datatablesActions', compact( 'viewGate', 'editGate', 'deleteGate', 'crudRoutePart', 'row' )); }); $table->editColumn('id', function ($row) { return $row->id ? $row->id : ''; }); $table->editColumn('name', function ($row) { return $row->name ? $row->name : ''; }); $table->editColumn('organization_type', function ($row) { $labels = []; foreach ($row->organization_types as $organization_type) { $labels[] = sprintf('<span class="label label-info label-many">%s</span>', $organization_type->name); } return implode(' ', $labels); }); $table->editColumn('nit', function ($row) { return $row->nit ? $row->nit : ''; }); $table->editColumn('legal_representant', function ($row) { return $row->legal_representant ? $row->legal_representant : ''; }); $table->addColumn('dcoumenttype_name', function ($row) { return $row->dcoumenttype ? $row->dcoumenttype->name : ''; }); $table->editColumn('document', function ($row) { return $row->document ? $row->document : ''; }); $table->editColumn('cargo', function ($row) { return $row->cargo ? $row->cargo : ''; }); $table->editColumn('address', function ($row) { return $row->address ? $row->address : ''; }); $table->addColumn('department_name', function ($row) { return $row->department ? $row->department->name : ''; }); $table->addColumn('city_name', function ($row) { return $row->city ? $row->city->name : ''; }); $table->editColumn('phone', function ($row) { return $row->phone ? $row->phone : ''; }); $table->editColumn('main_phone_ext', function ($row) { return $row->main_phone_ext ? $row->main_phone_ext : ''; }); $table->editColumn('postal_code', function ($row) { return $row->postal_code ? $row->postal_code : ''; }); $table->editColumn('email', function ($row) { return $row->email ? $row->email : ''; }); $table->editColumn('finnancial_contact', function ($row) { return $row->finnancial_contact ? $row->finnancial_contact : ''; }); $table->editColumn('finnancial_contact_email', function ($row) { return $row->finnancial_contact_email ? $row->finnancial_contact_email : ''; }); $table->editColumn('finnancial_contact_phone', function ($row) { return $row->finnancial_contact_phone ? $row->finnancial_contact_phone : ''; }); $table->editColumn('finnancial_contact_ext', function ($row) { return $row->finnancial_contact_ext ? $row->finnancial_contact_ext : ''; }); $table->editColumn('contracting_contact', function ($row) { return $row->contracting_contact ? $row->contracting_contact : ''; }); $table->editColumn('contracting_contact_email', function ($row) { return $row->contracting_contact_email ? $row->contracting_contact_email : ''; }); $table->editColumn('contracting_contact_phone', function ($row) { return $row->contracting_contact_phone ? $row->contracting_contact_phone : ''; }); $table->editColumn('contracting_contact_ext', function ($row) { return $row->contracting_contact_ext ? $row->contracting_contact_ext : ''; }); $table->editColumn('electronic_invoice_contact', function ($row) { return $row->electronic_invoice_contact ? $row->electronic_invoice_contact : ''; }); $table->editColumn('electronic_invoice_email', function ($row) { return $row->electronic_invoice_email ? $row->electronic_invoice_email : ''; }); $table->editColumn('electronic_invoice_phone', function ($row) { return $row->electronic_invoice_phone ? $row->electronic_invoice_phone : ''; }); $table->editColumn('electronic_invoice_ext', function ($row) { return $row->electronic_invoice_ext ? $row->electronic_invoice_ext : ''; }); $table->editColumn('cash_banks_contact', function ($row) { return $row->cash_banks_contact ? $row->cash_banks_contact : ''; }); $table->editColumn('cash_banks_email', function ($row) { return $row->cash_banks_email ? $row->cash_banks_email : ''; }); $table->editColumn('cash_banks_phone', function ($row) { return $row->cash_banks_phone ? $row->cash_banks_phone : ''; }); $table->editColumn('cash_banks_ext', function ($row) { return $row->cash_banks_ext ? $row->cash_banks_ext : ''; }); $table->editColumn('electronic_invoice_authorized_mail', function ($row) { return $row->electronic_invoice_authorized_mail ? $row->electronic_invoice_authorized_mail : ''; }); $table->editColumn('requiere_orden_de_compra', function ($row) { return $row->requiere_orden_de_compra ? Organization::REQUIERE_ORDEN_DE_COMPRA_RADIO[$row->requiere_orden_de_compra] : ''; }); $table->editColumn('limit_day_to_invoice', function ($row) { return $row->limit_day_to_invoice ? $row->limit_day_to_invoice : ''; }); $table->editColumn('national_tax_responsible', function ($row) { return '<input type="checkbox" disabled ' . ($row->national_tax_responsible ? 'checked' : null) . '>'; }); $table->editColumn('local_tax_responsible', function ($row) { return '<input type="checkbox" disabled ' . ($row->local_tax_responsible ? 'checked' : null) . '>'; }); $table->editColumn('local_tax_ammount', function ($row) { return $row->local_tax_ammount ? $row->local_tax_ammount : ''; }); $table->editColumn('big_taxpayer', function ($row) { return '<input type="checkbox" disabled ' . ($row->big_taxpayer ? 'checked' : null) . '>'; }); $table->editColumn('big_taxpayer_resolution', function ($row) { return $row->big_taxpayer_resolution ? $row->big_taxpayer_resolution : ''; }); $table->editColumn('seft_taxreteiner', function ($row) { return '<input type="checkbox" disabled ' . ($row->seft_taxreteiner ? 'checked' : null) . '>'; }); $table->editColumn('seft_taxreteiner_resolution', function ($row) { return $row->seft_taxreteiner_resolution ? $row->seft_taxreteiner_resolution : ''; }); $table->editColumn('rst_tax', function ($row) { return '<input type="checkbox" disabled ' . ($row->rst_tax ? 'checked' : null) . '>'; }); $table->editColumn('donation_certificate_issuer', function ($row) { return '<input type="checkbox" disabled ' . ($row->donation_certificate_issuer ? 'checked' : null) . '>'; }); $table->editColumn('payment_collection_time', function ($row) { return $row->payment_collection_time ? Organization::PAYMENT_COLLECTION_TIME_SELECT[$row->payment_collection_time] : ''; }); $table->editColumn('disclaimer', function ($row) { return '<input type="checkbox" disabled ' . ($row->disclaimer ? 'checked' : null) . '>'; }); $table->editColumn('information_privacy_check', function ($row) { return '<input type="checkbox" disabled ' . ($row->information_privacy_check ? 'checked' : null) . '>'; }); $table->editColumn('cc_file', function ($row) { return $row->cc_file ? '<a href="' . $row->cc_file->getUrl() . '" target="_blank">' . trans('global.downloadFile') . '</a>' : ''; }); $table->editColumn('rl_file', function ($row) { return $row->rl_file ? '<a href="' . $row->rl_file->getUrl() . '" target="_blank">' . trans('global.downloadFile') . '</a>' : ''; }); $table->editColumn('tp_file', function ($row) { return $row->tp_file ? '<a href="' . $row->tp_file->getUrl() . '" target="_blank">' . trans('global.downloadFile') . '</a>' : ''; }); $table->editColumn('ar_file', function ($row) { return $row->ar_file ? '<a href="' . $row->ar_file->getUrl() . '" target="_blank">' . trans('global.downloadFile') . '</a>' : ''; }); $table->editColumn('bc_file', function ($row) { return $row->bc_file ? $row->bc_file : ''; }); $table->editColumn('short_description', function ($row) { return $row->short_description ? $row->short_description : ''; }); $table->editColumn('long_description', function ($row) { return $row->long_description ? $row->long_description : ''; }); $table->editColumn('webpage', function ($row) { return $row->webpage ? $row->webpage : ''; }); $table->editColumn('logo', function ($row) { if ($photo = $row->logo) { return sprintf( '<a href="%s" target="_blank"><img src="%s" width="50px" height="50px"></a>', $photo->url, $photo->thumbnail ); } return ''; }); $table->editColumn('tags', function ($row) { return $row->tags ? $row->tags : ''; }); $table->editColumn('status', function ($row) { return $row->status ? Organization::STATUS_SELECT[$row->status] : ''; }); $table->editColumn('featured', function ($row) { return '<input type="checkbox" disabled ' . ($row->featured ? 'checked' : null) . '>'; }); $table->editColumn('comments', function ($row) { return $row->comments ? $row->comments : ''; }); $table->rawColumns(['actions', 'placeholder', 'organization_type', 'dcoumenttype', 'department', 'city', 'national_tax_responsible', 'local_tax_responsible', 'big_taxpayer', 'seft_taxreteiner', 'rst_tax', 'donation_certificate_issuer', 'disclaimer', 'information_privacy_check', 'cc_file', 'rl_file', 'tp_file', 'ar_file', 'logo', 'featured']); return $table->make(true); } $types = Type::get(); $document_types = DocumentType::get(); $departments = Department::get(); $cities = City::get(); return view('admin.organizations.index', compact('types', 'document_types', 'departments', 'cities')); } public function create() { abort_if(Gate::denies('organization_create'), Response::HTTP_FORBIDDEN, '403 Forbidden'); $organization_types = Type::pluck('name', 'id'); $dcoumenttypes = DocumentType::pluck('name', 'id')->prepend(trans('global.pleaseSelect'), ''); $departments = Department::pluck('name', 'id')->prepend(trans('global.pleaseSelect'), ''); $cities = City::pluck('name', 'id')->prepend(trans('global.pleaseSelect'), ''); return view('admin.organizations.create', compact('organization_types', 'dcoumenttypes', 'departments', 'cities')); } public function store(StoreOrganizationRequest $request) { $organization = Organization::create($request->all()); $organization->organization_types()->sync($request->input('organization_types', [])); if ($request->input('cc_file', false)) { $organization->addMedia(storage_path('tmp/uploads/' . basename($request->input('cc_file'))))->toMediaCollection('cc_file'); } if ($request->input('rl_file', false)) { $organization->addMedia(storage_path('tmp/uploads/' . basename($request->input('rl_file'))))->toMediaCollection('rl_file'); } if ($request->input('tp_file', false)) { $organization->addMedia(storage_path('tmp/uploads/' . basename($request->input('tp_file'))))->toMediaCollection('tp_file'); } if ($request->input('ar_file', false)) { $organization->addMedia(storage_path('tmp/uploads/' . basename($request->input('ar_file'))))->toMediaCollection('ar_file'); } if ($request->input('logo', false)) { $organization->addMedia(storage_path('tmp/uploads/' . basename($request->input('logo'))))->toMediaCollection('logo'); } if ($media = $request->input('ck-media', false)) { Media::whereIn('id', $media)->update(['model_id' => $organization->id]); } return redirect()->route('admin.organizations.index'); } public function edit(Organization $organization) { abort_if(Gate::denies('organization_edit'), Response::HTTP_FORBIDDEN, '403 Forbidden'); $organization_types = Type::pluck('name', 'id'); $dcoumenttypes = DocumentType::pluck('name', 'id')->prepend(trans('global.pleaseSelect'), ''); $departments = Department::pluck('name', 'id')->prepend(trans('global.pleaseSelect'), ''); $cities = City::pluck('name', 'id')->prepend(trans('global.pleaseSelect'), ''); $organization->load('organization_types', 'dcoumenttype', 'department', 'city'); return view('admin.organizations.edit', compact('organization_types', 'dcoumenttypes', 'departments', 'cities', 'organization')); } public function update(UpdateOrganizationRequest $request, Organization $organization) { $organization->update($request->all()); $organization->organization_types()->sync($request->input('organization_types', [])); if ($request->input('cc_file', false)) { if (!$organization->cc_file || $request->input('cc_file') !== $organization->cc_file->file_name) { if ($organization->cc_file) { $organization->cc_file->delete(); } $organization->addMedia(storage_path('tmp/uploads/' . basename($request->input('cc_file'))))->toMediaCollection('cc_file'); } } elseif ($organization->cc_file) { $organization->cc_file->delete(); } if ($request->input('rl_file', false)) { if (!$organization->rl_file || $request->input('rl_file') !== $organization->rl_file->file_name) { if ($organization->rl_file) { $organization->rl_file->delete(); } $organization->addMedia(storage_path('tmp/uploads/' . basename($request->input('rl_file'))))->toMediaCollection('rl_file'); } } elseif ($organization->rl_file) { $organization->rl_file->delete(); } if ($request->input('tp_file', false)) { if (!$organization->tp_file || $request->input('tp_file') !== $organization->tp_file->file_name) { if ($organization->tp_file) { $organization->tp_file->delete(); } $organization->addMedia(storage_path('tmp/uploads/' . basename($request->input('tp_file'))))->toMediaCollection('tp_file'); } } elseif ($organization->tp_file) { $organization->tp_file->delete(); } if ($request->input('ar_file', false)) { if (!$organization->ar_file || $request->input('ar_file') !== $organization->ar_file->file_name) { if ($organization->ar_file) { $organization->ar_file->delete(); } $organization->addMedia(storage_path('tmp/uploads/' . basename($request->input('ar_file'))))->toMediaCollection('ar_file'); } } elseif ($organization->ar_file) { $organization->ar_file->delete(); } if ($request->input('logo', false)) { if (!$organization->logo || $request->input('logo') !== $organization->logo->file_name) { if ($organization->logo) { $organization->logo->delete(); } $organization->addMedia(storage_path('tmp/uploads/' . basename($request->input('logo'))))->toMediaCollection('logo'); } } elseif ($organization->logo) { $organization->logo->delete(); } return redirect()->route('admin.organizations.index'); } public function show(Organization $organization) { abort_if(Gate::denies('organization_show'), Response::HTTP_FORBIDDEN, '403 Forbidden'); $organization->load('organization_types', 'dcoumenttype', 'department', 'city', 'organizationDonations', 'organizationProjects', 'organizationUsers', 'organizationEvents'); return view('admin.organizations.show', compact('organization')); } public function destroy(Organization $organization) { abort_if(Gate::denies('organization_delete'), Response::HTTP_FORBIDDEN, '403 Forbidden'); $organization->delete(); return back(); } public function massDestroy(MassDestroyOrganizationRequest $request) { Organization::whereIn('id', request('ids'))->delete(); return response(null, Response::HTTP_NO_CONTENT); } public function storeCKEditorImages(Request $request) { abort_if(Gate::denies('organization_create') && Gate::denies('organization_edit'), Response::HTTP_FORBIDDEN, '403 Forbidden'); $model = new Organization(); $model->id = $request->input('crud_id', 0); $model->exists = true; $media = $model->addMediaFromRequest('upload')->toMediaCollection('ck-media'); return response()->json(['id' => $media->id, 'url' => $media->getUrl()], Response::HTTP_CREATED); } } <file_sep>/app/Http/Controllers/Api/V1/Admin/DonationsApiController.php <?php namespace App\Http\Controllers\Api\V1\Admin; use App\Http\Controllers\Controller; use App\Http\Controllers\Traits\MediaUploadingTrait; use App\Http\Requests\StoreDonationRequest; use App\Http\Requests\UpdateDonationRequest; use App\Http\Resources\Admin\DonationResource; use App\Models\Donation; use Gate; use Illuminate\Http\Request; use Symfony\Component\HttpFoundation\Response; class DonationsApiController extends Controller { use MediaUploadingTrait; public function index() { abort_if(Gate::denies('donation_access'), Response::HTTP_FORBIDDEN, '403 Forbidden'); return new DonationResource(Donation::with(['user', 'organization'])->get()); } public function store(StoreDonationRequest $request) { $donation = Donation::create($request->all()); if ($request->input('file', false)) { $donation->addMedia(storage_path('tmp/uploads/' . basename($request->input('file'))))->toMediaCollection('file'); } return (new DonationResource($donation)) ->response() ->setStatusCode(Response::HTTP_CREATED); } public function show(Donation $donation) { abort_if(Gate::denies('donation_show'), Response::HTTP_FORBIDDEN, '403 Forbidden'); return new DonationResource($donation->load(['user', 'organization'])); } public function update(UpdateDonationRequest $request, Donation $donation) { $donation->update($request->all()); if ($request->input('file', false)) { if (!$donation->file || $request->input('file') !== $donation->file->file_name) { if ($donation->file) { $donation->file->delete(); } $donation->addMedia(storage_path('tmp/uploads/' . basename($request->input('file'))))->toMediaCollection('file'); } } elseif ($donation->file) { $donation->file->delete(); } return (new DonationResource($donation)) ->response() ->setStatusCode(Response::HTTP_ACCEPTED); } public function destroy(Donation $donation) { abort_if(Gate::denies('donation_delete'), Response::HTTP_FORBIDDEN, '403 Forbidden'); $donation->delete(); return response(null, Response::HTTP_NO_CONTENT); } } <file_sep>/app/Http/Controllers/Admin/CitiesController.php <?php namespace App\Http\Controllers\Admin; use App\Http\Controllers\Controller; use App\Http\Requests\MassDestroyCityRequest; use App\Http\Requests\StoreCityRequest; use App\Http\Requests\UpdateCityRequest; use App\Models\City; use App\Models\Department; use Gate; use Illuminate\Http\Request; use Symfony\Component\HttpFoundation\Response; use Yajra\DataTables\Facades\DataTables; class CitiesController extends Controller { public function index(Request $request) { abort_if(Gate::denies('city_access'), Response::HTTP_FORBIDDEN, '403 Forbidden'); if ($request->ajax()) { $query = City::with(['department'])->select(sprintf('%s.*', (new City())->table)); $table = Datatables::of($query); $table->addColumn('placeholder', '&nbsp;'); $table->addColumn('actions', '&nbsp;'); $table->editColumn('actions', function ($row) { $viewGate = 'city_show'; $editGate = 'city_edit'; $deleteGate = 'city_delete'; $crudRoutePart = 'cities'; return view('partials.datatablesActions', compact( 'viewGate', 'editGate', 'deleteGate', 'crudRoutePart', 'row' )); }); $table->editColumn('id', function ($row) { return $row->id ? $row->id : ''; }); $table->editColumn('name', function ($row) { return $row->name ? $row->name : ''; }); $table->editColumn('code', function ($row) { return $row->code ? $row->code : ''; }); $table->addColumn('department_name', function ($row) { return $row->department ? $row->department->name : ''; }); $table->rawColumns(['actions', 'placeholder', 'department']); return $table->make(true); } return view('admin.cities.index'); } public function create() { abort_if(Gate::denies('city_create'), Response::HTTP_FORBIDDEN, '403 Forbidden'); $departments = Department::pluck('name', 'id')->prepend(trans('global.pleaseSelect'), ''); return view('admin.cities.create', compact('departments')); } public function store(StoreCityRequest $request) { $city = City::create($request->all()); return redirect()->route('admin.cities.index'); } public function edit(City $city) { abort_if(Gate::denies('city_edit'), Response::HTTP_FORBIDDEN, '403 Forbidden'); $departments = Department::pluck('name', 'id')->prepend(trans('global.pleaseSelect'), ''); $city->load('department'); return view('admin.cities.edit', compact('departments', 'city')); } public function update(UpdateCityRequest $request, City $city) { $city->update($request->all()); return redirect()->route('admin.cities.index'); } public function show(City $city) { abort_if(Gate::denies('city_show'), Response::HTTP_FORBIDDEN, '403 Forbidden'); $city->load('department'); return view('admin.cities.show', compact('city')); } public function destroy(City $city) { abort_if(Gate::denies('city_delete'), Response::HTTP_FORBIDDEN, '403 Forbidden'); $city->delete(); return back(); } public function massDestroy(MassDestroyCityRequest $request) { City::whereIn('id', request('ids'))->delete(); return response(null, Response::HTTP_NO_CONTENT); } } <file_sep>/database/migrations/2021_08_23_000010_create_transactions_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateTransactionsTable extends Migration { public function up() { Schema::create('transactions', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('merchant')->nullable(); $table->string('state_pol')->nullable(); $table->string('response_code_pol')->nullable(); $table->string('reference_sale')->nullable(); $table->string('reference_pol')->nullable(); $table->string('extra_1')->nullable(); $table->string('extra_2')->nullable(); $table->string('payment_method')->nullable(); $table->string('payment_method_type')->nullable(); $table->string('installments_number')->nullable(); $table->string('value')->nullable(); $table->string('tax')->nullable(); $table->string('transaction_date')->nullable(); $table->string('email_buyer')->nullable(); $table->string('cus')->nullable(); $table->string('pse_bank')->nullable(); $table->string('description')->nullable(); $table->string('billing_address')->nullable(); $table->string('shipping_address')->nullable(); $table->string('phone')->nullable(); $table->string('account_number_ach')->nullable(); $table->string('account_type_ach')->nullable(); $table->string('administrative_fee')->nullable(); $table->string('administrative_fee_base')->nullable(); $table->string('administrative_fee_tax')->nullable(); $table->string('authorization_code')->nullable(); $table->string('bank')->nullable(); $table->string('billing_city')->nullable(); $table->string('billing_country')->nullable(); $table->string('commision_pol')->nullable(); $table->string('commision_pol_currency')->nullable(); $table->string('customer_number')->nullable(); $table->string('date')->nullable(); $table->string('ip')->nullable(); $table->string('payment_methodid')->nullable(); $table->string('payment_request_state')->nullable(); $table->string('pse_reference_1')->nullable(); $table->string('pse_reference_2')->nullable(); $table->string('pse_reference_3')->nullable(); $table->string('response_message_pol')->nullable(); $table->string('transaction_bank')->nullable(); $table->string('transaction')->nullable(); $table->string('payment_method_name')->nullable(); $table->timestamps(); $table->softDeletes(); }); } } <file_sep>/app/Http/Controllers/Api/V1/Admin/AutomaticDebtsApiController.php <?php namespace App\Http\Controllers\Api\V1\Admin; use App\Http\Controllers\Controller; use App\Http\Requests\StoreAutomaticDebtRequest; use App\Http\Requests\UpdateAutomaticDebtRequest; use App\Http\Resources\Admin\AutomaticDebtResource; use App\Models\AutomaticDebt; use Gate; use Illuminate\Http\Request; use Symfony\Component\HttpFoundation\Response; class AutomaticDebtsApiController extends Controller { public function index() { abort_if(Gate::denies('automatic_debt_access'), Response::HTTP_FORBIDDEN, '403 Forbidden'); return new AutomaticDebtResource(AutomaticDebt::with(['transaction'])->get()); } public function store(StoreAutomaticDebtRequest $request) { $automaticDebt = AutomaticDebt::create($request->all()); return (new AutomaticDebtResource($automaticDebt)) ->response() ->setStatusCode(Response::HTTP_CREATED); } public function show(AutomaticDebt $automaticDebt) { abort_if(Gate::denies('automatic_debt_show'), Response::HTTP_FORBIDDEN, '403 Forbidden'); return new AutomaticDebtResource($automaticDebt->load(['transaction'])); } public function update(UpdateAutomaticDebtRequest $request, AutomaticDebt $automaticDebt) { $automaticDebt->update($request->all()); return (new AutomaticDebtResource($automaticDebt)) ->response() ->setStatusCode(Response::HTTP_ACCEPTED); } public function destroy(AutomaticDebt $automaticDebt) { abort_if(Gate::denies('automatic_debt_delete'), Response::HTTP_FORBIDDEN, '403 Forbidden'); $automaticDebt->delete(); return response(null, Response::HTTP_NO_CONTENT); } } <file_sep>/app/Http/Requests/StoreTransactionRequest.php <?php namespace App\Http\Requests; use App\Models\Transaction; use Gate; use Illuminate\Foundation\Http\FormRequest; use Illuminate\Http\Response; class StoreTransactionRequest extends FormRequest { public function authorize() { return Gate::allows('transaction_create'); } public function rules() { return [ 'merchant' => [ 'string', 'nullable', ], 'state_pol' => [ 'string', 'nullable', ], 'response_code_pol' => [ 'string', 'nullable', ], 'reference_sale' => [ 'string', 'nullable', ], 'reference_pol' => [ 'string', 'nullable', ], 'extra_1' => [ 'string', 'nullable', ], 'extra_2' => [ 'string', 'nullable', ], 'payment_method' => [ 'string', 'nullable', ], 'payment_method_type' => [ 'string', 'nullable', ], 'installments_number' => [ 'string', 'nullable', ], 'value' => [ 'string', 'nullable', ], 'tax' => [ 'string', 'nullable', ], 'transaction_date' => [ 'string', 'nullable', ], 'email_buyer' => [ 'string', 'nullable', ], 'cus' => [ 'string', 'nullable', ], 'pse_bank' => [ 'string', 'nullable', ], 'description' => [ 'string', 'nullable', ], 'billing_address' => [ 'string', 'nullable', ], 'shipping_address' => [ 'string', 'nullable', ], 'phone' => [ 'string', 'nullable', ], 'account_number_ach' => [ 'string', 'nullable', ], 'account_type_ach' => [ 'string', 'nullable', ], 'administrative_fee' => [ 'string', 'nullable', ], 'administrative_fee_base' => [ 'string', 'nullable', ], 'administrative_fee_tax' => [ 'string', 'nullable', ], 'authorization_code' => [ 'string', 'nullable', ], 'bank' => [ 'string', 'nullable', ], 'billing_city' => [ 'string', 'nullable', ], 'billing_country' => [ 'string', 'nullable', ], 'commision_pol' => [ 'string', 'nullable', ], 'commision_pol_currency' => [ 'string', 'nullable', ], 'customer_number' => [ 'string', 'nullable', ], 'date' => [ 'string', 'nullable', ], 'ip' => [ 'string', 'nullable', ], 'payment_methodid' => [ 'string', 'nullable', ], 'payment_request_state' => [ 'string', 'nullable', ], 'pse_reference_1' => [ 'string', 'nullable', ], 'pse_reference_2' => [ 'string', 'nullable', ], 'pse_reference_3' => [ 'string', 'nullable', ], 'response_message_pol' => [ 'string', 'nullable', ], 'transaction_bank' => [ 'string', 'nullable', ], 'transaction' => [ 'string', 'nullable', ], 'payment_method_name' => [ 'string', 'nullable', ], ]; } } <file_sep>/app/Http/Controllers/Admin/AutomaticDebtsController.php <?php namespace App\Http\Controllers\Admin; use App\Http\Controllers\Controller; use App\Http\Requests\MassDestroyAutomaticDebtRequest; use App\Http\Requests\StoreAutomaticDebtRequest; use App\Http\Requests\UpdateAutomaticDebtRequest; use App\Models\AutomaticDebt; use App\Models\Transaction; use Gate; use Illuminate\Http\Request; use Symfony\Component\HttpFoundation\Response; class AutomaticDebtsController extends Controller { public function index() { abort_if(Gate::denies('automatic_debt_access'), Response::HTTP_FORBIDDEN, '403 Forbidden'); $automaticDebts = AutomaticDebt::with(['transaction'])->get(); return view('admin.automaticDebts.index', compact('automaticDebts')); } public function create() { abort_if(Gate::denies('automatic_debt_create'), Response::HTTP_FORBIDDEN, '403 Forbidden'); $transactions = Transaction::all()->pluck('value', 'id')->prepend(trans('global.pleaseSelect'), ''); return view('admin.automaticDebts.create', compact('transactions')); } public function store(StoreAutomaticDebtRequest $request) { $automaticDebt = AutomaticDebt::create($request->all()); return redirect()->route('admin.automatic-debts.index'); } public function edit(AutomaticDebt $automaticDebt) { abort_if(Gate::denies('automatic_debt_edit'), Response::HTTP_FORBIDDEN, '403 Forbidden'); $transactions = Transaction::all()->pluck('value', 'id')->prepend(trans('global.pleaseSelect'), ''); $automaticDebt->load('transaction'); return view('admin.automaticDebts.edit', compact('transactions', 'automaticDebt')); } public function update(UpdateAutomaticDebtRequest $request, AutomaticDebt $automaticDebt) { $automaticDebt->update($request->all()); return redirect()->route('admin.automatic-debts.index'); } public function show(AutomaticDebt $automaticDebt) { abort_if(Gate::denies('automatic_debt_show'), Response::HTTP_FORBIDDEN, '403 Forbidden'); $automaticDebt->load('transaction'); return view('admin.automaticDebts.show', compact('automaticDebt')); } public function destroy(AutomaticDebt $automaticDebt) { abort_if(Gate::denies('automatic_debt_delete'), Response::HTTP_FORBIDDEN, '403 Forbidden'); $automaticDebt->delete(); return back(); } public function massDestroy(MassDestroyAutomaticDebtRequest $request) { AutomaticDebt::whereIn('id', request('ids'))->delete(); return response(null, Response::HTTP_NO_CONTENT); } } <file_sep>/database/migrations/2021_08_23_000035_add_relationship_fields_to_organizations_table.php <?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class AddRelationshipFieldsToOrganizationsTable extends Migration { public function up() { Schema::table('organizations', function (Blueprint $table) { $table->unsignedBigInteger('dcoumenttype_id'); $table->foreign('dcoumenttype_id', 'dcoumenttype_fk_4565179')->references('id')->on('document_types'); $table->unsignedBigInteger('department_id'); $table->foreign('department_id', 'department_fk_4016452')->references('id')->on('departments'); $table->unsignedBigInteger('city_id'); $table->foreign('city_id', 'city_fk_4016453')->references('id')->on('cities'); }); } }
3421b3f0308da121816f7a29fcfb47d9165e227f
[ "PHP" ]
31
PHP
donalma-co/donalma-co
466b6b0bfcb9de429962da138a2a71949a502ab0
f7aa4d95c1264bcfe497447c234f68281c70e399
refs/heads/master
<repo_name>nstudio/typedoc<file_sep>/src/lib/output/events.ts import * as Path from "path"; import {Event} from "../utils/events"; import {ProjectReflection} from "../models/reflections/project"; import {UrlMapping} from "./models/UrlMapping"; import {NavigationItem} from "./models/NavigationItem"; /** * An event emitted by the [[Renderer]] class at the very beginning and * ending of the entire rendering process. * * @see [[Renderer.EVENT_BEGIN]] * @see [[Renderer.EVENT_END]] */ export class RendererEvent extends Event { /** * The project the renderer is currently processing. */ project:ProjectReflection; /** * The settings that have been passed to TypeDoc. */ settings:any; /** * The path of the directory the documentation should be written to. */ outputDirectory:string; /** * A list of all pages that should be generated. * * This list can be altered during the [[Renderer.EVENT_BEGIN]] event. */ urls:UrlMapping[]; /** * Triggered before the renderer starts rendering a project. * @event */ static BEGIN:string = 'beginRender'; /** * Triggered after the renderer has written all documents. * @event */ static END:string = 'endRender'; /** * Create an [[PageEvent]] event based on this event and the given url mapping. * * @internal * @param mapping The mapping that defines the generated [[PageEvent]] state. * @returns A newly created [[PageEvent]] instance. */ public createPageEvent(mapping:UrlMapping):PageEvent { const event = new PageEvent(PageEvent.BEGIN); event.project = this.project; event.settings = this.settings; event.url = mapping.url; event.model = mapping.model; event.templateName = mapping.template; event.filename = Path.join(this.outputDirectory, mapping.url); return event; } } /** * An event emitted by the [[Renderer]] class before and after the * markup of a page is rendered. * * This object will be passed as the rendering context to handlebars templates. * * @see [[Renderer.EVENT_BEGIN_PAGE]] * @see [[Renderer.EVENT_END_PAGE]] */ export class PageEvent extends Event { /** * The project the renderer is currently processing. */ project:ProjectReflection; /** * The settings that have been passed to TypeDoc. */ settings:any; /** * The filename the page will be written to. */ filename:string; /** * The url this page will be located at. */ url:string; /** * The model that should be rendered on this page. */ model:any; /** * The template that should be used to render this page. */ template:HandlebarsTemplateDelegate; /** * The name of the template that should be used to render this page. */ templateName:string; /** * The primary navigation structure of this page. */ navigation:NavigationItem; /** * The table of contents structure of this page. */ toc:NavigationItem; /** * The final html content of this page. * * Should be rendered by layout templates and can be modifies by plugins. */ contents:string; /** * Triggered before a document will be rendered. * @event */ static BEGIN:string = 'beginPage'; /** * Triggered after a document has been rendered, just before it is written to disc. * @event */ static END:string = 'endPage'; } /** * An event emitted by the [[MarkedPlugin]] on the [[Renderer]] after a chunk of * markdown has been processed. Allows other plugins to manipulate the result. * * @see [[MarkedPlugin.EVENT_PARSE_MARKDOWN]] */ export class MarkdownEvent extends Event { /** * The unparsed original text. */ originalText:string; /** * The parsed output. */ parsedText:string; /** * Triggered on the renderer when this plugin parses a markdown string. * @event */ static PARSE:string = 'parseMarkdown'; } <file_sep>/src/lib/utils/options/declaration.ts import * as ts from "typescript"; import * as Util from "util"; export enum ParameterHint { File, Directory } export enum ParameterType { String, Number, Boolean, Map, Mixed, Array } export enum ParameterScope { TypeDoc, TypeScript } export interface IOptionDeclaration { name:string; component?:string; short?:string; help:string; type?:ParameterType; hint?:ParameterHint; scope?:ParameterScope; map?:{}; mapError?:string; isArray?:boolean; defaultValue?:any; convert?:(param:OptionDeclaration, value?:any) => any; } export class OptionDeclaration { name:string; short:string; component:string; help:string; type:ParameterType; hint:ParameterHint; scope:ParameterScope; map:Object; mapError:string; isArray:boolean; defaultValue:any; constructor(data:IOptionDeclaration) { for (let key in data) { this[key] = data[key]; } this.type = this.type || ParameterType.String; this.scope = this.scope || ParameterScope.TypeDoc; } getNames():string[] { const result = [this.name.toLowerCase()]; if (this.short) { result.push(this.short.toLowerCase()); } return result; } convert(value:any, errorCallback?:Function):any { switch (this.type) { case ParameterType.Number: value = parseInt(value); break; case ParameterType.Boolean: value = (typeof value === void 0 ? true : !!value); break; case ParameterType.String: value = value || ""; break; case ParameterType.Array: if (!value) { value = []; } else if (typeof value === "string") { value = value.split(","); } break; case ParameterType.Map: if (this.map !== 'object') { const key = value ? (value + "").toLowerCase() : ''; if (key in this.map) { value = this.map[key]; } else if (errorCallback) { if (this.mapError) { errorCallback(this.mapError); } else { errorCallback('Invalid value for option "%s".', this.name); } } } break; } return value; } }
b2921cea954ef1d3da0cbbedb960f3d18be6ab5e
[ "TypeScript" ]
2
TypeScript
nstudio/typedoc
e414e6da938c07e11b041774a3a3585fa9f22f46
b0818aa1bb174a4680ab3c15083e7c098ce30e1d
refs/heads/master
<file_sep><?php namespace App\Controller; use App\Entity\Death; use App\Form\DeathType; use App\Repository\DeathRepository; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Annotation\Route; /** * @Route("/death") */ class DeathController extends AbstractController { /** * @Route("/", name="death_index", methods={"GET"}) */ public function index(DeathRepository $deathRepository): Response { return $this->render('death/index.html.twig', [ 'deaths' => $deathRepository->findAll(), ]); } /** * @Route("/new", name="death_new", methods={"GET","POST"}) */ public function new(Request $request): Response { $death = new Death(); $form = $this->createForm(DeathType::class, $death); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $entityManager = $this->getDoctrine()->getManager(); $entityManager->persist($death); $entityManager->flush(); return $this->redirectToRoute('public_user_index'); } return $this->render('death/new.html.twig', [ 'death' => $death, 'form' => $form->createView(), ]); } /** * @Route("/{id}", name="death_show", methods={"GET"}) */ public function show(Death $death): Response { return $this->render('death/show.html.twig', [ 'death' => $death, ]); } /** * @Route("/{id}/edit", name="death_edit", methods={"GET","POST"}) */ public function edit(Request $request, Death $death): Response { $form = $this->createForm(DeathType::class, $death); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $this->getDoctrine()->getManager()->flush(); return $this->redirectToRoute('public_user_index'); } return $this->render('death/edit.html.twig', [ 'death' => $death, 'form' => $form->createView(), ]); } /** * @Route("/{id}", name="death_delete", methods={"POST"}) */ public function delete(Request $request, Death $death): Response { if ($this->isCsrfTokenValid('delete' . $death->getId(), $request->request->get('_token'))) { $entityManager = $this->getDoctrine()->getManager(); $entityManager->remove($death); $entityManager->flush(); } return $this->redirectToRoute('death_index'); } } <file_sep><?php namespace App\Entity; use App\Repository\BirthRepository; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity(repositoryClass=BirthRepository::class) */ class Birth { /** * @ORM\Id * @ORM\GeneratedValue * @ORM\Column(type="integer") */ private $id; /** * @ORM\Column(type="date" , nullable = true) */ private $declarationDate; /** * @ORM\ManyToOne(targetEntity="App\Entity\PublicUser") */ private $publicUser; /** * @ORM\Column(type="string", length=255, nullable=true) */ private $officeLocation; /** * @ORM\Column(type="string", length=255, nullable=true) */ private $officier; /** * @ORM\Column(type="string", length=255, nullable=true) */ private $payment; /** * @ORM\Column(type="string", length=255, nullable=true) */ private $status; public function getId(): ?int { return $this->id; } public function getDeclarationDate(): ?\DateTimeInterface { return $this->declarationDate; } public function setDeclarationDate(?\DateTimeInterface $declarationDate): self { $this->declarationDate = $declarationDate; return $this; } public function getOfficeLocation(): ?string { return $this->officeLocation; } public function setOfficeLocation(?string $officeLocation): self { $this->officeLocation = $officeLocation; return $this; } public function getOfficier(): ?string { return $this->officier; } public function setOfficier(?string $officier): self { $this->officier = $officier; return $this; } public function getPayment(): ?string { return $this->payment; } public function setPayment(?string $payment): self { $this->payment = $payment; return $this; } public function getPublicUser(): ?PublicUser { return $this->publicUser; } public function setPublicUser(?PublicUser $publicUser): self { $this->publicUser = $publicUser; return $this; } public function getStatus(): ?string { return $this->status; } public function setStatus(?string $status): self { $this->status = $status; return $this; } } <file_sep><?php namespace App\Controller; use App\Entity\Mariage; use App\Form\MariageType; use App\Repository\MariageRepository; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Annotation\Route; use \Datetime; /** * @Route("/mariage") */ class MariageController extends AbstractController { /** * @Route("/", name="mariage_index", methods={"GET"}) */ public function index(MariageRepository $mariageRepository): Response { return $this->render('mariage/index.html.twig', [ 'mariages' => $mariageRepository->findAll(), ]); } /** * @Route("/new", name="mariage_new", methods={"GET","POST"}) */ public function new(Request $request): Response { $mariage = new Mariage(); $date = new DateTime(); $form = $this->createForm(MariageType::class, $mariage); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $entityManager = $this->getDoctrine()->getManager(); $mariage->setDeclarationDate($date); //get mariage details $mariage->getHusband()->setIsMaried(true); $mariage->getWife()->setIsMaried(true); $entityManager->persist($mariage); $entityManager->flush(); return $this->redirectToRoute('public_user_index'); } return $this->render('mariage/new.html.twig', [ 'mariage' => $mariage, 'form' => $form->createView(), ]); } /** * @Route("/{id}", name="mariage_show", methods={"GET"}) */ public function show(Mariage $mariage): Response { return $this->render('mariage/show.html.twig', [ 'mariage' => $mariage, ]); } /** * @Route("/{id}/edit", name="mariage_edit", methods={"GET","POST"}) */ public function edit(Request $request, Mariage $mariage): Response { $form = $this->createForm(MariageType::class, $mariage); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $this->getDoctrine()->getManager()->flush(); return $this->redirectToRoute('public_user_index'); } return $this->render('mariage/edit.html.twig', [ 'mariage' => $mariage, 'form' => $form->createView(), ]); } /** * @Route("/{id}/request-new-cetificate-date", name="mariage_edit_user", methods={"GET","POST"}) */ public function editUser(Request $request, Mariage $mariage): Response { $date = new DateTime(); $form = $this->createForm(MariageType::class, $mariage); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $mariage->setStatus('Pending'); $mariage->setDeclarationDate($date); $this->getDoctrine()->getManager()->flush(); return $this->redirectToRoute('public_user_index'); } return $this->render('mariage/editUser.html.twig', [ 'mariage' => $mariage, 'form' => $form->createView(), ]); } /** * @Route("/{id}", name="mariage_delete", methods={"POST"}) */ public function delete(Request $request, Mariage $mariage): Response { if ($this->isCsrfTokenValid('delete' . $mariage->getId(), $request->request->get('_token'))) { $entityManager = $this->getDoctrine()->getManager(); $entityManager->remove($mariage); $entityManager->flush(); } return $this->redirectToRoute('mariage_index'); } } <file_sep><?php namespace App\Controller; use App\Entity\ParentUser; use App\Form\ParentUserType; use App\Repository\ParentUserRepository; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Annotation\Route; /** * @Route("/parent") */ class ParentUserController extends AbstractController { /** * @Route("/", name="parent_user_index", methods={"GET"}) */ public function index(ParentUserRepository $parentUserRepository): Response { return $this->render('parent_user/index.html.twig', [ 'parent_users' => $parentUserRepository->findAll(), ]); } /** * @Route("/new", name="parent_user_new", methods={"GET","POST"}) */ public function new(Request $request): Response { $parentUser = new ParentUser(); $form = $this->createForm(ParentUserType::class, $parentUser); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $entityManager = $this->getDoctrine()->getManager(); $entityManager->persist($parentUser); $entityManager->flush(); return $this->redirectToRoute('parent_user_new'); } return $this->render('parent_user/new.html.twig', [ 'parent_user' => $parentUser, 'form' => $form->createView(), ]); } /** * @Route("/{id}", name="parent_user_show", methods={"GET"}) */ public function show(ParentUser $parentUser): Response { return $this->render('parent_user/show.html.twig', [ 'parent_user' => $parentUser, ]); } /** * @Route("/{id}/edit", name="parent_user_edit", methods={"GET","POST"}) */ public function edit(Request $request, ParentUser $parentUser): Response { $form = $this->createForm(ParentUserType::class, $parentUser); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $this->getDoctrine()->getManager()->flush(); return $this->redirectToRoute('parent_user_index'); } return $this->render('parent_user/edit.html.twig', [ 'parent_user' => $parentUser, 'form' => $form->createView(), ]); } /** * @Route("/{id}", name="parent_user_delete", methods={"POST"}) */ public function delete(Request $request, ParentUser $parentUser): Response { if ($this->isCsrfTokenValid('delete' . $parentUser->getId(), $request->request->get('_token'))) { $entityManager = $this->getDoctrine()->getManager(); $entityManager->remove($parentUser); $entityManager->flush(); } return $this->redirectToRoute('parent_user_index'); } } <file_sep><?php namespace App\Entity; use App\Repository\PublicUserRepository; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity(repositoryClass=PublicUserRepository::class) */ class PublicUser { /** * @ORM\Id * @ORM\GeneratedValue * @ORM\Column(type="integer") */ private $id; /** * @ORM\Column(type="string", length=255) */ private $FName; /** * @ORM\Column(type="string", length=255) */ private $LName; /** * @ORM\Column(type="datetime") */ private $DoB; /** * @ORM\Column(type="string", length=255) */ private $placeOfBirth; /** * @ORM\Column(type="boolean") */ private $isAlive; /** * @ORM\Column(type="date", nullable=true) */ private $DoD; /** * @ORM\Column(type="string", length=255) */ private $fatherName; /** * @ORM\Column(type="string", length=255) */ private $fatherOccupation; /** * @ORM\Column(type="string", length=255) */ private $motherName; /** * @ORM\Column(type="string", length=255) */ private $motherOccupation; /** * @ORM\OneToOne(targetEntity="App\Entity\User") */ private $user; /** * @ORM\Column(type="boolean") */ private $gender; /** * @ORM\Column(type="boolean") */ private $isMaried; public function getId(): ?int { return $this->id; } public function getFName(): ?string { return $this->FName; } public function setFName(string $FName): self { $this->FName = $FName; return $this; } public function getLName(): ?string { return $this->LName; } public function setLName(string $LName): self { $this->LName = $LName; return $this; } public function getDoB(): ?\DateTimeInterface { return $this->DoB; } public function setDoB(\DateTimeInterface $DoB): self { $this->DoB = $DoB; return $this; } public function getPlaceOfBirth(): ?string { return $this->placeOfBirth; } public function setPlaceOfBirth(string $placeOfBirth): self { $this->placeOfBirth = $placeOfBirth; return $this; } public function getIsAlive(): ?bool { return $this->isAlive; } public function setIsAlive(bool $isAlive): self { $this->isAlive = $isAlive; return $this; } public function getDoD(): ?\DateTimeInterface { return $this->DoD; } public function setDoD(?\DateTimeInterface $DoD): self { $this->DoD = $DoD; return $this; } public function getFatherName(): ?string { return $this->fatherName; } public function setFatherName(string $fatherName): self { $this->fatherName = $fatherName; return $this; } public function getFatherOccupation(): ?string { return $this->fatherOccupation; } public function setFatherOccupation(string $fatherOccupation): self { $this->fatherOccupation = $fatherOccupation; return $this; } public function getMotherName(): ?string { return $this->motherName; } public function setMotherName(string $motherName): self { $this->motherName = $motherName; return $this; } public function getMotherOccupation(): ?string { return $this->motherOccupation; } public function setMotherOccupation(string $motherOccupation): self { $this->motherOccupation = $motherOccupation; return $this; } public function getUser(): ?User { return $this->user; } public function setUser(?User $user): self { $this->user = $user; return $this; } public function getGender(): ?bool { return $this->gender; } public function setGender(bool $gender): self { $this->gender = $gender; return $this; } public function getIsMaried(): ?bool { return $this->isMaried; } public function setIsMaried(bool $isMaried): self { $this->isMaried = $isMaried; return $this; } } <file_sep><?php namespace App\Controller; use App\Entity\OfficeLocation; use App\Form\OfficeLocationType; use App\Repository\OfficeLocationRepository; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Annotation\Route; /** * @Route("/office/location") */ class OfficeLocationController extends AbstractController { /** * @Route("/", name="office_location_index", methods={"GET"}) */ public function index(OfficeLocationRepository $officeLocationRepository): Response { return $this->render('office_location/index.html.twig', [ 'office_locations' => $officeLocationRepository->findAll(), ]); } /** * @Route("/new", name="office_location_new", methods={"GET","POST"}) */ public function new(Request $request): Response { $officeLocation = new OfficeLocation(); $form = $this->createForm(OfficeLocationType::class, $officeLocation); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $entityManager = $this->getDoctrine()->getManager(); $entityManager->persist($officeLocation); $entityManager->flush(); return $this->redirectToRoute('office_location_index'); } return $this->render('office_location/new.html.twig', [ 'office_location' => $officeLocation, 'form' => $form->createView(), ]); } /** * @Route("/{id}", name="office_location_show", methods={"GET"}) */ public function show(OfficeLocation $officeLocation): Response { return $this->render('office_location/show.html.twig', [ 'office_location' => $officeLocation, ]); } /** * @Route("/{id}/edit", name="office_location_edit", methods={"GET","POST"}) */ public function edit(Request $request, OfficeLocation $officeLocation): Response { $form = $this->createForm(OfficeLocationType::class, $officeLocation); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $this->getDoctrine()->getManager()->flush(); return $this->redirectToRoute('office_location_index'); } return $this->render('office_location/edit.html.twig', [ 'office_location' => $officeLocation, 'form' => $form->createView(), ]); } /** * @Route("/{id}", name="office_location_delete", methods={"POST"}) */ public function delete(Request $request, OfficeLocation $officeLocation): Response { if ($this->isCsrfTokenValid('delete'.$officeLocation->getId(), $request->request->get('_token'))) { $entityManager = $this->getDoctrine()->getManager(); $entityManager->remove($officeLocation); $entityManager->flush(); } return $this->redirectToRoute('office_location_index'); } } <file_sep><?php namespace App\Form; use App\Entity\Death; use App\Entity\PublicUser; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; use Symfony\Bridge\Doctrine\Form\Type\EntityType; use Symfony\Component\Form\Extension\Core\Type\DateTimeType; use Symfony\Component\Form\Extension\Core\Type\ChoiceType; class DeathType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('deathDate', DateTimeType::class, [ 'widget' => 'single_text', 'required' => false, ]) ->add('declarationDate', DateTimeType::class, [ 'widget' => 'single_text', 'required' => false, ]) ->add('payment') ->add('officeLocation') ->add('officier') ->add('vadiny', EntityType::class, [ // looks for choices from this entity 'class' => PublicUser::class, 'placeholder' => 'Choose Epoux', // uses the User.username property as the visible option string 'choice_label' => function ($pu) { return $pu->getId() . " - " . $pu->getFname() . " " . $pu->getLname(); }, // used to render a select box, check boxes or radios // 'multiple' => true, // 'expanded' => true, ]) ->add('maty', EntityType::class, [ // looks for choices from this entity 'class' => PublicUser::class, 'placeholder' => 'Choose ID', // uses the User.username property as the visible option string 'choice_label' => function ($pu) { return $pu->getId() . " - " . $pu->getFname() . " " . $pu->getLname(); }, // used to render a select box, check boxes or radios // 'multiple' => true, // 'expanded' => true, ]) ->add('temoin', EntityType::class, [ // looks for choices from this entity 'class' => PublicUser::class, 'placeholder' => 'Choose ID', // uses the User.username property as the visible option string 'choice_label' => function ($pu) { return $pu->getId() . " - " . $pu->getFname() . " " . $pu->getLname(); }, // used to render a select box, check boxes or radios // 'multiple' => true, // 'expanded' => true, ]) ->add('status', ChoiceType::class, [ 'choices' => [ 'Pending' => 'Pending', 'Approved' => 'Approved', ], ]); } public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ 'data_class' => Death::class, ]); } } <file_sep><?php namespace App\Repository; use App\Entity\Birth; use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository; use Doctrine\Persistence\ManagerRegistry; /** * @method Birth|null find($id, $lockMode = null, $lockVersion = null) * @method Birth|null findOneBy(array $criteria, array $orderBy = null) * @method Birth[] findAll() * @method Birth[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null) */ class BirthRepository extends ServiceEntityRepository { public function __construct(ManagerRegistry $registry) { parent::__construct($registry, Birth::class); } // /** // * @return Birth[] Returns an array of Birth objects // */ /* public function findByExampleField($value) { return $this->createQueryBuilder('b') ->andWhere('b.exampleField = :val') ->setParameter('val', $value) ->orderBy('b.id', 'ASC') ->setMaxResults(10) ->getQuery() ->getResult() ; } */ /* public function findOneBySomeField($value): ?Birth { return $this->createQueryBuilder('b') ->andWhere('b.exampleField = :val') ->setParameter('val', $value) ->getQuery() ->getOneOrNullResult() ; } */ } <file_sep><?php namespace App\Controller; use App\Entity\Birth; use App\Entity\Death; use App\Entity\Mariage; use App\Entity\PublicUser; use App\Form\PublicUserType; use App\Repository\PublicUserRepository; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Annotation\Route; use App\Form\BirthType; use Dompdf\Dompdf; use Dompdf\Options; /** * @Route("/publicuser") */ class PublicUserController extends AbstractController { /** * @Route("/", name="public_user_index", methods={"GET"}) */ public function index(PublicUserRepository $publicUserRepository, Request $request): Response { $entityManager = $this->getDoctrine()->getManager(); $user = $this->getUser(); if ($user == null) { return $this->redirectToRoute('app_login'); } // $qb = $entityManager->createQueryBuilder(); // $selectedUserAlive = $qb->select('u') // ->from('App:PublicUser', 'u') // ->where('u.DoD IS NULL') // ->getQuery() // ->getResult(); $AllPublicUser = $entityManager->getRepository('App:PublicUser')->findAll(); //check user details $userDetails = $entityManager->getRepository('App:PublicUser')->findOneBy(['user' => $user]); //get all birth list $fecthAllBirth = $entityManager->getRepository('App:Birth')->findAll(); //fetch all birth user certificate $fecthPublicUserBirthCertificate = $entityManager->getRepository('App:Birth')->findBy(['publicUser' => $userDetails]); //get all birth list $fecthAllMariage = $entityManager->getRepository('App:Mariage')->findAll(); //get all birth list $fecthAllDeath = $entityManager->getRepository('App:Death')->findAll(); //fetch all mariage user certificate // $fecthPublicUserlMariageCertificate = $entityManager->getRepository('App:Mariage')->findBy(['publicUser' => $userDetails]); //get on mariage data $fecthUserHusbandMariage = $entityManager->getRepository('App:Mariage')->findOneBy(['husband' => $user]); //if husband is null if ($fecthUserHusbandMariage == null) { $fecthUserWifeMariage = $entityManager->getRepository('App:Mariage')->findOneBy(['wife' => $user]); $userMariageCertificate = $fecthUserWifeMariage; } else { $userMariageCertificate = $fecthUserHusbandMariage; } return $this->render('public_user/index.html.twig', [ 'public_users' => $AllPublicUser, 'birthList' => $fecthAllBirth, 'userDetails' => $userDetails, 'userBirthCertificate' => $fecthPublicUserBirthCertificate, 'mariageList' => $fecthAllMariage, 'deathList' => $fecthAllDeath, //'userMariageCertificate' => $fecthPublicUserlMariageCertificate, 'user' => $user, 'userMariageCertificate' => $userMariageCertificate ]); } /** * @Route("/new", name="public_user_new", methods={"GET","POST"}) */ public function new(Request $request): Response { $entityManager = $this->getDoctrine()->getManager(); $user = $this->getUser(); if ($user == null) { return $this->redirectToRoute('app_login'); } $publicUser = new PublicUser(); $form = $this->createForm(PublicUserType::class, $publicUser); $form->handleRequest($request); //check user details $userDetails = $entityManager->getRepository('App:PublicUser')->findOneBy(['user' => $user]); if ($form->isSubmitted() && $form->isValid()) { // $entityManager = $this->getDoctrine()->getManager(); //generate rand num $publicUser->setUser($user); $entityManager->persist($publicUser); $entityManager->flush(); return $this->redirectToRoute('public_user_index'); } return $this->render('public_user/new.html.twig', [ 'public_user' => $publicUser, 'form' => $form->createView(), 'userDetails' => $userDetails ]); } /** * @Route("/{id}", name="public_user_show", methods={"GET"}) */ public function show(PublicUser $publicUser): Response { return $this->render('public_user/show.html.twig', [ 'public_user' => $publicUser, ]); } /** * @Route("/{id}/edit", name="public_user_edit", methods={"GET","POST"}) */ public function edit(Request $request, PublicUser $publicUser): Response { $entityManager = $this->getDoctrine()->getManager(); $form = $this->createForm(PublicUserType::class, $publicUser); $form->handleRequest($request); //select all from parentUser $listeAllParent = $entityManager->getRepository('App:ParentUser')->findAll(); if ($form->isSubmitted() && $form->isValid()) { $this->getDoctrine()->getManager()->flush(); return $this->redirectToRoute('public_user_index'); } return $this->render('public_user/edit.html.twig', [ 'public_user' => $publicUser, 'form' => $form->createView(), 'allParentUser' => $listeAllParent ]); } /** * @Route("/{id}", name="public_user_delete", methods={"DELETE"}) */ public function delete(Request $request, PublicUser $publicUser): Response { if ($this->isCsrfTokenValid('delete' . $publicUser->getId(), $request->request->get('_token'))) { $entityManager = $this->getDoctrine()->getManager(); $entityManager->remove($publicUser); $entityManager->flush(); } return $this->redirectToRoute('public_user_index'); } /** * @Route("/{id}/pdf", name="make_pdf", methods={"GET"}) */ public function makePdf(Request $request, PublicUser $publicUser) { //entity manager $entityManager = $this->getDoctrine()->getManager(); // Configure Dompdf according to your needs $pdfOptions = new Options(); $pdfOptions->set('defaultFont', 'Arial'); // Instantiate Dompdf with our options $dompdf = new Dompdf($pdfOptions); // Retrieve the HTML generated in our twig file $html = $this->renderView('public_user/pdf.html.twig', [ 'title' => "Welcome to our PDF Test", 'publicUser' => $publicUser, ]); // Load HTML to Dompdf $dompdf->loadHtml($html); // (Optional) Setup the paper size and orientation 'portrait' or 'portrait' $dompdf->setPaper('A4', 'portrait'); // Render the HTML as PDF $dompdf->render(); // Output the generated PDF to Browser (inline view) $dompdf->stream("mypdf.pdf", [ "Attachment" => false ]); } /** * @Route("/{id}/pdfBirth", name="make_pdf_birth", methods={"GET"}) */ public function makeBirthPdf(Request $request, Birth $birth) { //entity manager $entityManager = $this->getDoctrine()->getManager(); // Configure Dompdf according to your needs $pdfOptions = new Options(); $pdfOptions->set('defaultFont', 'Arial'); // Instantiate Dompdf with our options $dompdf = new Dompdf($pdfOptions); // Retrieve the HTML generated in our twig file $html = $this->renderView('birth/pdfBirth.html.twig', [ 'title' => "Welcome to our PDF Test", 'birth' => $birth, ]); // Load HTML to Dompdf $dompdf->loadHtml($html); // (Optional) Setup the paper size and orientation 'portrait' or 'portrait' $dompdf->setPaper('A4', 'portrait'); // Render the HTML as PDF $dompdf->render(); // Output the generated PDF to Browser (inline view) $dompdf->stream("mypdf.pdf", [ "Attachment" => false ]); } /** * @Route("/{id}/pdfMariage", name="make_pdf_mariage", methods={"GET"}) */ public function makeMariagehPdf(Request $request, Mariage $mariage) { //entity manager $entityManager = $this->getDoctrine()->getManager(); // Configure Dompdf according to your needs $pdfOptions = new Options(); $pdfOptions->set('defaultFont', 'Arial'); // Instantiate Dompdf with our options $dompdf = new Dompdf($pdfOptions); // Retrieve the HTML generated in our twig file $html = $this->renderView('mariage/pdfMariage.html.twig', [ 'title' => "Welcome to our PDF Test", 'mariage' => $mariage, ]); // Load HTML to Dompdf $dompdf->loadHtml($html); // (Optional) Setup the paper size and orientation 'portrait' or 'portrait' $dompdf->setPaper('A4', 'portrait'); // Render the HTML as PDF $dompdf->render(); // Output the generated PDF to Browser (inline view) $dompdf->stream("mypdf.pdf", [ "Attachment" => false ]); } /** * @Route("/{id}/pdfDeath", name="make_pdf_death", methods={"GET"}) */ public function makeDeathhPdf(Request $request, Death $death) { //entity manager $entityManager = $this->getDoctrine()->getManager(); // Configure Dompdf according to your needs $pdfOptions = new Options(); $pdfOptions->set('defaultFont', 'Arial'); // Instantiate Dompdf with our options $dompdf = new Dompdf($pdfOptions); // Retrieve the HTML generated in our twig file $html = $this->renderView('death/pdfDeath.html.twig', [ 'title' => "Welcome to our PDF Test", 'death' => $death, ]); // Load HTML to Dompdf $dompdf->loadHtml($html); // (Optional) Setup the paper size and orientation 'portrait' or 'portrait' $dompdf->setPaper('A4', 'portrait'); // Render the HTML as PDF $dompdf->render(); // Output the generated PDF to Browser (inline view) $dompdf->stream("mypdf.pdf", [ "Attachment" => false ]); } } <file_sep><?php namespace App\Form; use App\Entity\PublicUser; use App\Entity\ParentUser; use phpDocumentor\Reflection\Types\Parent_; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; use Symfony\Component\Form\Extension\Core\Type\ChoiceType; use Symfony\Bridge\Doctrine\Form\Type\EntityType; use Symfony\Component\Form\Extension\Core\Type\DateTimeType; class PublicUserType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('FName') ->add('LName') ->add('placeOfBirth') ->add('DoB', DateTimeType::class, [ 'widget' => 'single_text', ]) ->add('isAlive', ChoiceType::class, [ 'choices' => [ "Alive" => true, "Dead" => false ], ]) ->add('DoD', DateTimeType::class, [ 'widget' => 'single_text', 'required' => false, ]) ->add('fatherName') ->add('fatherOccupation') ->add('motherName') ->add('motherOccupation') ->add('gender', ChoiceType::class, [ 'choices' => [ "Male" => true, "Female" => false ], ]); } public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ 'data_class' => PublicUser::class, ]); } } <file_sep><?php namespace App\Entity; use App\Repository\MariageRepository; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity(repositoryClass=MariageRepository::class) */ class Mariage { /** * @ORM\Id * @ORM\GeneratedValue * @ORM\Column(type="integer") */ private $id; /** * @ORM\Column(type="date") */ private $mariageDate; /** * @ORM\Column(type="date") */ private $declarationDate; /** * @ORM\ManyToOne(targetEntity="App\Entity\PublicUser") */ private $husband; /** * @ORM\ManyToOne(targetEntity="App\Entity\PublicUser") */ private $wife; /** * @ORM\ManyToOne(targetEntity="App\Entity\PublicUser") */ private $temoin; /** * @ORM\Column(type="string", length=255, nullable=true) */ private $officeLocation; /** * @ORM\Column(type="string", length=255, nullable=true) */ private $officier; /** * @ORM\Column(type="string", length=255, nullable=true) */ private $payment; /** * @ORM\Column(type="string", length=255, nullable=true) */ private $status; public function getId(): ?int { return $this->id; } public function getDeclarationDate(): ?\DateTimeInterface { return $this->declarationDate; } public function setDeclarationDate(\DateTimeInterface $declarationDate): self { $this->declarationDate = $declarationDate; return $this; } public function getHusband(): ?PublicUser { return $this->husband; } public function setHusband(?PublicUser $husband): self { $this->husband = $husband; return $this; } public function getWife(): ?PublicUser { return $this->wife; } public function setWife(?PublicUser $wife): self { $this->wife = $wife; return $this; } public function getOfficeLocation(): ?string { return $this->officeLocation; } public function setOfficeLocation(?string $officeLocation): self { $this->officeLocation = $officeLocation; return $this; } public function getOfficier(): ?string { return $this->officier; } public function setOfficier(?string $officier): self { $this->officier = $officier; return $this; } public function getPayment(): ?string { return $this->payment; } public function setPayment(?string $payment): self { $this->payment = $payment; return $this; } public function getStatus(): ?string { return $this->status; } public function setStatus(?string $status): self { $this->status = $status; return $this; } public function getTemoin(): ?PublicUser { return $this->temoin; } public function setTemoin(?PublicUser $temoin): self { $this->temoin = $temoin; return $this; } public function getMariageDate(): ?\DateTimeInterface { return $this->mariageDate; } public function setMariageDate(\DateTimeInterface $mariageDate): self { $this->mariageDate = $mariageDate; return $this; } } <file_sep><?php namespace App\Form; use App\Entity\Mariage; use App\Entity\PublicUser; use Doctrine\ORM\EntityRepository; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; use Symfony\Bridge\Doctrine\Form\Type\EntityType; use Symfony\Component\Form\Extension\Core\Type\DateTimeType; use Symfony\Component\Form\Extension\Core\Type\ChoiceType; class MariageType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('mariageDate', DateTimeType::class, [ 'widget' => 'single_text', 'required' => false, ]) ->add('husband', EntityType::class, [ // looks for choices from this entity 'class' => PublicUser::class, 'placeholder' => 'Choose Husband', 'query_builder' => function (EntityRepository $entityRepository) { return $entityRepository->createQueryBuilder('pu') ->where('pu.isMaried != :value') ->andWhere('pu.gender != :valueGender') ->setParameters(['value' => true, 'valueGender' => false]); }, // uses the User.username property as the visible option string 'choice_label' => function ($pu) { return $pu->getId() . " - " . $pu->getFname() . " " . $pu->getLname(); }, // used to render a select box, check boxes or radios // 'multiple' => true, //'expanded' => true, // 'query_builder' => function (EntityRepository $repository) { // $qb = $repository->createQueryBuilder('u'); // // the function returns a QueryBuilder object // return $qb // // find all users where 'deleted' is NOT '1' // ->where($qb->expr()->neq('u.deleted', '?1')) // ->setParameter('1', '1') // ->orderBy('u.username', 'ASC'); // }, ]) ->add('wife', EntityType::class, [ // looks for choices from this entity 'class' => PublicUser::class, 'placeholder' => 'Choose Wife', 'query_builder' => function (EntityRepository $entityRepository) { return $entityRepository->createQueryBuilder('pu') ->where('pu.isMaried != :value') ->andWhere('pu.gender != :valueGender') ->setParameters(['value' => true, 'valueGender' => true]); }, // uses the User.username property as the visible option string 'choice_label' => function ($pu) { return $pu->getId() . " - " . $pu->getFname() . " " . $pu->getLname(); }, // used to render a select box, check boxes or radios // 'multiple' => true, // 'expanded' => true, ]) ->add('temoin', EntityType::class, [ // looks for choices from this entity 'class' => PublicUser::class, 'placeholder' => 'Choose Temoin', // uses the User.username property as the visible option string 'choice_label' => function ($pu) { return $pu->getId() . " - " . $pu->getFname() . " " . $pu->getLname(); }, // used to render a select box, check boxes or radios // 'multiple' => true, // 'expanded' => true, ]) ->add('officeLocation') ->add('officier') ->add('payment') ->add('status', ChoiceType::class, [ 'choices' => [ 'Pending' => 'Pending', 'Approved' => 'Approved', 'Failed' => 'Failed', ], ]); } public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ 'data_class' => Mariage::class, ]); } } <file_sep><?php namespace App\Controller; use App\Entity\Birth; use App\Form\BirthType; use App\Repository\BirthRepository; use Symfony\Bundle\FrameworkBundle\Controller\AbstractController; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Annotation\Route; /** * @Route("/birth") */ class BirthController extends AbstractController { /** * @Route("/", name="birth_index", methods={"GET"}) */ public function index(BirthRepository $birthRepository): Response { return $this->render('birth/index.html.twig', [ 'births' => $birthRepository->findAll(), ]); } /** * @Route("/new", name="birth_new", methods={"GET","POST"}) */ public function new(Request $request): Response { $user = $this->getUser(); $birth = new Birth(); $form = $this->createForm(BirthType::class, $birth); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $entityManager = $this->getDoctrine()->getManager(); $birth->setOfficier($user); $entityManager->persist($birth); $entityManager->flush(); return $this->redirectToRoute('birth_index'); } return $this->render('birth/new.html.twig', [ 'birth' => $birth, 'form' => $form->createView(), ]); } /** * @Route("/{id}/users", name="birth_users", methods={"GET","POST"}) */ public function users(Request $request): Response { $user = $this->getUser(); $birth = new Birth(); $form = $this->createForm(BirthType::class, $birth); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $entityManager = $this->getDoctrine()->getManager(); //get public user details $userDetails = $entityManager->getRepository('App:PublicUser')->findOneBy(['user' => $user]); $birth->setPublicUser($userDetails); $entityManager->persist($birth); $entityManager->flush(); return $this->redirectToRoute('public_user_index'); } return $this->render('birth/newbirth.html.twig', [ 'birth' => $birth, 'form' => $form->createView(), 'user' => $user, ]); } /** * @Route("/{id}", name="birth_show", methods={"GET"}) */ public function show(Birth $birth): Response { return $this->render('birth/show.html.twig', [ 'birth' => $birth, ]); } /** * @Route("/{id}/edit", name="birth_edit", methods={"GET","POST"}) */ public function edit(Request $request, Birth $birth): Response { $form = $this->createForm(BirthType::class, $birth); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $this->getDoctrine()->getManager()->flush(); return $this->redirectToRoute('public_user_index'); } return $this->render('birth/edit.html.twig', [ 'birth' => $birth, 'form' => $form->createView(), ]); } /** * @Route("/{id}", name="birth_delete", methods={"POST"}) */ public function delete(Request $request, Birth $birth): Response { if ($this->isCsrfTokenValid('delete' . $birth->getId(), $request->request->get('_token'))) { $entityManager = $this->getDoctrine()->getManager(); $entityManager->remove($birth); $entityManager->flush(); } return $this->redirectToRoute('birth_index'); } } <file_sep><?php namespace App\Repository; use App\Entity\PublicUser; use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository; use Doctrine\Persistence\ManagerRegistry; /** * @method PublicUser|null find($id, $lockMode = null, $lockVersion = null) * @method PublicUser|null findOneBy(array $criteria, array $orderBy = null) * @method PublicUser[] findAll() * @method PublicUser[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null) */ class PublicUserRepository extends ServiceEntityRepository { public function __construct(ManagerRegistry $registry) { parent::__construct($registry, PublicUser::class); } // /** // * @return PublicUser[] Returns an array of PublicUser objects // */ /* public function findByExampleField($value) { return $this->createQueryBuilder('p') ->andWhere('p.exampleField = :val') ->setParameter('val', $value) ->orderBy('p.id', 'ASC') ->setMaxResults(10) ->getQuery() ->getResult() ; } */ /* public function findOneBySomeField($value): ?PublicUser { return $this->createQueryBuilder('p') ->andWhere('p.exampleField = :val') ->setParameter('val', $value) ->getQuery() ->getOneOrNullResult() ; } */ } <file_sep><?php namespace App\Entity; use App\Repository\DeathRepository; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity(repositoryClass=DeathRepository::class) */ class Death { /** * @ORM\Id * @ORM\GeneratedValue * @ORM\Column(type="integer") */ private $id; /** * @ORM\Column(type="date") */ private $deathDate; /** * @ORM\Column(type="date") */ private $declarationDate; /** * @ORM\ManyToOne(targetEntity="App\Entity\PublicUser") */ private $maty; /** * @ORM\ManyToOne(targetEntity="App\Entity\PublicUser") */ private $vadiny; /** * @ORM\ManyToOne(targetEntity="App\Entity\PublicUser") */ private $temoin; /** * @ORM\Column(type="string", length=255, nullable=true) */ private $payment; /** * @ORM\Column(type="string", length=255, nullable=true) */ private $officeLocation; /** * @ORM\Column(type="string", length=255, nullable=true) */ private $officier; /** * @ORM\Column(type="string", length=255, nullable=true) */ private $status; public function getId(): ?int { return $this->id; } public function getDeathDate(): ?\DateTimeInterface { return $this->deathDate; } public function setDeathDate(\DateTimeInterface $deathDate): self { $this->deathDate = $deathDate; return $this; } public function getDeclarationDate(): ?\DateTimeInterface { return $this->declarationDate; } public function setDeclarationDate(\DateTimeInterface $declarationDate): self { $this->declarationDate = $declarationDate; return $this; } public function getPayment(): ?string { return $this->payment; } public function setPayment(?string $payment): self { $this->payment = $payment; return $this; } public function getOfficeLocation(): ?string { return $this->officeLocation; } public function setOfficeLocation(?string $officeLocation): self { $this->officeLocation = $officeLocation; return $this; } public function getOfficier(): ?string { return $this->officier; } public function setOfficier(?string $officier): self { $this->officier = $officier; return $this; } public function getVadiny(): ?PublicUser { return $this->vadiny; } public function setVadiny(?PublicUser $vadiny): self { $this->vadiny = $vadiny; return $this; } public function setMother(?PublicUser $mother): self { $this->mother = $mother; return $this; } public function getTemoin(): ?PublicUser { return $this->temoin; } public function setTemoin(?PublicUser $temoin): self { $this->temoin = $temoin; return $this; } public function getMaty(): ?PublicUser { return $this->maty; } public function setMaty(?PublicUser $maty): self { $this->maty = $maty; return $this; } public function getStatus(): ?string { return $this->status; } public function setStatus(?string $status): self { $this->status = $status; return $this; } } <file_sep><?php namespace App\Form; use App\Entity\Birth; use App\Entity\OfficeLocation; use App\Entity\PublicUser; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; use Symfony\Bridge\Doctrine\Form\Type\EntityType; use Symfony\Component\Form\Extension\Core\Type\DateTimeType; use Symfony\Component\Form\Extension\Core\Type\ChoiceType; class BirthType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('declarationDate', DateTimeType::class, [ 'widget' => 'single_text', ]) ->add('officeLocation') ->add('officier') ->add('payment') ->add('status', ChoiceType::class, [ 'choices' => [ 'Pending' => 'Pending', 'Approved' => 'Approved', 'Failed' => 'Failed', ], ]); } public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ 'data_class' => Birth::class, ]); } }
8c72ad0fade18206fbf37d2e0cf11f1899b5bc27
[ "PHP" ]
16
PHP
raLita261/CivilStatus
278a6679f0723db8d54a4789d278ef2ca87605c8
3d46eab4b79c81098d1b532829fae8da15d5e2a2
refs/heads/master
<repo_name>vikasvshastry/SaarthiCareer-App<file_sep>/app/src/main/java/com/saarthicareer/saarthicareer/fragment/RegistrationFirstFragment.java package com.saarthicareer.saarthicareer.fragment; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.saarthicareer.saarthicareer.R; import com.saarthicareer.saarthicareer.activity.LoginActivity; import com.weiwangcn.betterspinner.library.material.MaterialBetterSpinner; public class RegistrationFirstFragment extends Fragment { public RegistrationFirstFragment() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_registration_first, container, false); String[] DROPDOWNLIST = {"STUDENT","TRAINER","ADMIN"}; ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(getActivity(),android.R.layout.simple_dropdown_item_1line, DROPDOWNLIST); final MaterialBetterSpinner dropDownBox = (MaterialBetterSpinner)rootView.findViewById(R.id.drop_down); dropDownBox.setAdapter(arrayAdapter); final Button buttonNext = (Button)rootView.findViewById(R.id.btn_next); final EditText editTextName = (EditText)rootView.findViewById(R.id.input_name); final EditText editTextMobileNo = (EditText)rootView.findViewById(R.id.input_mobile_no); final EditText editTextEmail = (EditText)rootView.findViewById(R.id.input_email); final EditText editTextPassword = (EditText)rootView.findViewById(R.id.input_password); final EditText editTextLinkedInUrl = (EditText)rootView.findViewById(R.id.input_linkedin_url); final TextView textLoginLink = (TextView)rootView.findViewById(R.id.login_link_text); //sending back to Login if account already exists. textLoginLink.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(getActivity(), LoginActivity.class)); getActivity().finish(); } }); //when NEXT is pressed. buttonNext.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String email = editTextEmail.getText().toString().trim(); String name = editTextName.getText().toString().trim(); String password = editTextPassword.getText().toString().trim(); String mobileNo = editTextMobileNo.getText().toString().trim(); String type = dropDownBox.getText().toString().trim(); String linkedInUrl = "-"; if(!editTextLinkedInUrl.getText().toString().trim().isEmpty()){ linkedInUrl = dropDownBox.getText().toString().trim(); } if(email.isEmpty()){ Toast.makeText(getActivity(), "Email field cannot be left empty", Toast.LENGTH_SHORT).show(); } else if(name.isEmpty()){ Toast.makeText(getActivity(), "Name field cannot be left empty", Toast.LENGTH_SHORT).show(); } else if(password.length()<6){ Toast.makeText(getActivity(), "Password field cannot be left empty", Toast.LENGTH_SHORT).show(); } else if(mobileNo.length()<10){ Toast.makeText(getActivity(), "Mobile No. field cannot be left empty", Toast.LENGTH_SHORT).show(); } else if(type.isEmpty()){ Toast.makeText(getActivity(), "Type field cannot be left empty", Toast.LENGTH_SHORT).show(); } else { Bundle bundle = new Bundle(); bundle.putString("email",email); bundle.putString("name",name); bundle.putString("password",<PASSWORD>); bundle.putString("mobileno",mobileNo); bundle.putString("type",type); bundle.putString("linkedin",linkedInUrl); Fragment fragment; if(type.equals("STUDENT")){ fragment = new RegistrationStudentFragment(); fragment.setArguments(bundle); FragmentManager fragmentManager = getActivity().getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.replace(R.id.container_body, fragment); fragmentTransaction.addToBackStack(null); fragmentTransaction.commit(); } else if(type.equals("TRAINER")||type.equals("ADMIN")){ fragment = new RegistrationTrainerFragment(); fragment.setArguments(bundle); FragmentManager fragmentManager = getActivity().getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.replace(R.id.container_body, fragment); fragmentTransaction.addToBackStack(null); fragmentTransaction.commit(); } } } }); return rootView; } @Override public void onAttach(Activity activity) { super.onAttach(activity); } @Override public void onDetach() { super.onDetach(); } }<file_sep>/app/src/main/java/com/saarthicareer/saarthicareer/classes/Trainer.java package com.saarthicareer.saarthicareer.classes; import java.util.List; /** * Created by vikas on 28-Mar-17. */ public class Trainer extends User{ private String company; private String trainingExperience; private String areasOfExpertise; public String getTrainingExperience() { return trainingExperience; } public void setTrainingExperience(String trainingExperience) { this.trainingExperience = trainingExperience; } public String getCompany() { return company; } public void setCompany(String company) { this.company = company; } public String getAreasOfExpertise() { return areasOfExpertise; } public void setAreasOfExpertise(String areasOfExpertise) { this.areasOfExpertise = areasOfExpertise; } } <file_sep>/app/src/main/java/com/saarthicareer/saarthicareer/classes/Trainee.java package com.saarthicareer.saarthicareer.classes; /** * Created by vikas on 28-Mar-17. */ public class Trainee extends User { private String usn; private String major; private String college; private String yearOfGraduation; public String getYearOfGraduation() { return yearOfGraduation; } public void setYearOfGraduation(String yearOfGraduation) { this.yearOfGraduation = yearOfGraduation; } public String getUsn() { return usn; } public void setUsn(String usn) { this.usn = usn; } public String getMajor() { return major; } public void setMajor(String major) { this.major = major; } public String getCollege() { return college; } public void setCollege(String college) { this.college = college; } } <file_sep>/app/src/main/java/com/saarthicareer/saarthicareer/activity/RegistrationActivity.java package com.saarthicareer.saarthicareer.activity; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import com.saarthicareer.saarthicareer.R; import com.saarthicareer.saarthicareer.fragment.RegistrationFirstFragment; public class RegistrationActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_registration); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); Fragment fragment = new RegistrationFirstFragment(); FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); fragmentTransaction.replace(R.id.container_body, fragment); fragmentTransaction.commit(); } }
1495d4fdf49250418db284567d496139b9cadca6
[ "Java" ]
4
Java
vikasvshastry/SaarthiCareer-App
c6fc7ea6a1d67bf0793edae5dd148ddcd6426c82
3496b1f2b3d0ffa5e048478fa85c3bfe38226556
refs/heads/master
<file_sep>class Rank::Public::Node::LastWeeksController < Cms::Controller::Public::Base include Rank::Controller::Rank def pre_dispatch @node = Page.current_node @content = Rank::Content::Rank.find_by(id: Page.current_node.content.id) return http_error(404) unless @content end def index @term = 'last_weeks' @target = 'pageviews' @ranks = rank_datas(@content, @term, @target, 20) return http_error(404) if @ranks.blank? end end <file_sep>class GpCalendar::Publisher::HolidayCallbacks < PublisherCallbacks def after_save(holiday) @holiday = holiday enqueue if enqueue? end def before_destroy(holiday) @holiday = holiday enqueue if enqueue? end def enqueue(holiday = nil) @holiday = holiday if holiday enqueue_nodes enqueue_pieces end private def enqueue? true end def enqueue_nodes Cms::Publisher.register(@holiday.content.site_id, @holiday.content.public_nodes) end def enqueue_pieces @holiday.content.public_pieces.each do |piece| Cms::Publisher::PieceCallbacks.new.enqueue(piece) end end end <file_sep>module Cms::Nodes::Preload extend ActiveSupport::Concern module ClassMethods def public_descendants_in_route_assocs(depth = 3) return nil if depth < 0 { site: nil, content: nil, parent: nil, public_children_in_route: public_descendants_in_route_assocs(depth - 1) } end end end <file_sep>require_relative 'lib/extend_form_builder' require_relative 'lib/extend_rsync' require_relative 'lib/shortcut_methods' <file_sep>class Cms::Publisher::BracketeeCallbacks < PublisherCallbacks OWNER_KLASS_NAMES = %w(Cms::Layout Cms::Piece Cms::Node GpArticle::Doc) def after_save(item) @item = item enqueue if enqueue? end def before_destroy(item) @item = item enqueue if enqueue? end def enqueue(item = nil) @item = item if item enqueue_bracketees end private def enqueue? @item.name.present? end def enqueue_bracketees bracketees = Cms::Bracket.where(site_id: @item.site_id, name: changed_bracket_names).preload(:owner).all return if bracketees.blank? owner_map = bracketees.map(&:owner).group_by { |owner| owner.class.name } OWNER_KLASS_NAMES.each do |klass_name| if klass_name != @item.class.name && owner_map[klass_name].present? owner_map[klass_name].each do |owner| "#{klass_name.sub('::', '::Publisher::')}Callbacks".constantize.new.enqueue(owner) end end end end def changed_bracket_names type = Cms::Lib::Bracket.bracket_type(@item) names = [@item.name, @item.name_was].select(&:present?).uniq names.map { |name| "#{type}/#{name}" } end end <file_sep>class Util::Qrcode require 'rqrcode_png' def self.create(text=nil, path=nil, size=8) return nil if text.blank? || path.blank? begin qr = RQRCode::QRCode.new(text, :size => size, :level => :h ) png = qr.to_img png.resize(114, 114).save(path) rescue => e warn_log "#{__FILE__}:#{__LINE__} #{e.message}" return nil end end def self.create_date(text=nil, path=nil, size=8) return nil if text.blank? || path.blank? begin qr = RQRCode::QRCode.new(text, :size => size, :level => :h ) png = qr.to_img return png.resize(114, 114).to_blob rescue => e warn_log "#{__FILE__}:#{__LINE__} #{e.message}" return nil end return nil end end <file_sep>class Cms::Publisher::ContentRelatedCallbacks < PublisherCallbacks def after_save(item) @item = item enqueue if enqueue? end def before_destroy(item) @item = item enqueue if enqueue? end def enqueue(item = nil) @item = item if item enqueue_nodes enqueue_pieces enqueue_sitemap_nodes end private def enqueue? !@item.respond_to?(:state) || [@item.state, @item.state_was].include?('public') end def enqueue_nodes Cms::Publisher.register(@item.content.site_id, @item.content.public_nodes) end def enqueue_pieces @item.content.public_pieces.each do |piece| Cms::Publisher::PieceCallbacks.new.enqueue(piece) end end def enqueue_sitemap_nodes return unless @item.respond_to?(:sitemap_state) if [@item.sitemap_state, @item.sitemap_state_was].include?('visible') site = @item.content.site Cms::Publisher.register(site.id, site.public_sitemap_nodes) end end end <file_sep>class GpArticle::SearchDocsScript < Cms::Script::Publication def self.publishable? false end end <file_sep>class Sys::Publisher < ApplicationRecord include Sys::Model::Base belongs_to :publishable, polymorphic: true before_validation :modify_path before_save :check_path before_destroy :remove_files def site_id path.scan(%r{^./sites/(\d+)}).dig(0, 0).try!(:to_i) end def site @site ||= Cms::Site.find_by(id: site_id) end def modify_path self.path = path.gsub(/^#{Rails.root.to_s}/, '.') end def remove_files(options = {}) up_path = options[:path] || path up_path = ::File.expand_path(path, Rails.root) if up_path.to_s.slice(0, 1) == '/' FileUtils.rm(up_path) if FileTest.exist?(up_path) FileUtils.rm("#{up_path}.mp3") if FileTest.exist?("#{up_path}.mp3") FileUtils.rmdir(::File.dirname(path)) rescue nil transcribe self, options if Zomeki.config.application['sys.log_closed_page'] return true end protected def check_path remove_files(:path => path_was) if !path_was.blank? && path_changed? return true end def transcribe(publisher, options={}) cl = Sys::Closer.new(publisher.attributes) cl.published_at = publisher.created_at.clone rescue nil; cl.republished_at = publisher.updated_at.clone rescue nil; cl.created_at = nil cl.updated_at = nil cl.path = options[:path] if options[:path] cl.save! rescue false end end <file_sep>class Cms::Admin::Tool::SearchController < Cms::Controller::Admin::Base include Sys::Controller::Scaffold::Base def pre_dispatch return error_auth unless Core.user.has_auth?(:creator) return redirect_to(action: :index) if params[:reset] end def index @item = [] @items = [] def @item.keyword ; @keyword ; end def @item.keyword=(v) ; @keyword = v ; end return true if params[:do] != 'search' return true if params[:item][:keyword].blank? @item.keyword = params[:item][:keyword] if params[:target] && params[:target][:node_page] && Core.user.has_auth?(:designer) group = [ "固定ページ", [] ] Cms::Node.where(site_id: Core.site.id, model: "Cms::Page", concept_id: Core.concept(:id)) .search_with_text(:title, :body, :mobile_title, :mobile_body, @item.keyword) .order(:id) .each {|c| group[1] << [c.id, c.title, c.admin_uri] } @items << group end if params[:target] && params[:target][:gp_article] Cms::Content.where(site_id: Core.site.id, model: "GpArticle::Doc", concept_id: Core.concept(:id)).order(:id).each do |content| group = [ "記事:#{content.name}", [] ] GpArticle::Doc.where(content_id: content.id) .search_with_text(:title, :subtitle, :summary, :body, :mobile_title, :mobile_body, @item.keyword) .order(:id) .each {|c| group[1] << [c.id, c.title, gp_article_doc_path(c.content, c.id)] } @items << group end end if params[:target] && params[:target][:piece] && Core.user.has_auth?(:designer) group = [ "ピース", [] ] Cms::Piece.where(site_id: Core.site.id, concept_id: Core.concept(:id)) .search_with_text(:name, :title, :view_title, :head, :body, @item.keyword) .order(:id) .each {|c| group[1] << [c.id, c.title, c.admin_uri] } @items << group end if params[:target] && params[:target][:layout] && Core.user.has_auth?(:designer) group = [ "レイアウト", [] ] Cms::Layout.where(site_id: Core.site.id, concept_id: Core.concept(:id)) .search_with_text(:name, :title, :head, :body, :mobile_head, :mobile_body, @item.keyword) .order(:id) .each {|c| group[1] << [c.id, c.title, cms_layout_path(c.concept_id, c.id)] } @items << group end if params[:target] && params[:target][:data_text] group = [ "テキスト", [] ] Cms::DataText.where(site_id: Core.site.id, concept_id: Core.concept(:id)) .search_with_text(:name, :title, :body, @item.keyword) .order(:id) .each {|c| group[1] << [c.id, c.title, cms_data_text_path(c.concept_id, c.id)] } @items << group end if params[:target] && params[:target][:data_file] group = [ "ファイル", [] ] Cms::DataFile.where(site_id: Core.site.id, concept_id: Core.concept(:id)) .search_with_text(:name, :title, @item.keyword) .order(:id) .each {|c| group[1] << [c.id, c.title, cms_data_file_path(c.concept_id, c.id)] } @items << group end end end <file_sep>class Sys::TransferableFilesScript < Cms::Script::Base include Sys::Lib::File::Transfer def push transfer_files(:logging => true) end end <file_sep>class Tag::TagsScript < Cms::Script::Publication def publish publish_more(@node, uri: @node.public_uri, path: @node.public_path, smart_phone_path: @node.public_smart_phone_path, dependent: @node.public_uri) tags = @node.content.tags tags = tags.where(id: params[:target_tag_id]) if params[:target_tag_id].present? tags.each do |tag| next if tag.public_docs.blank? publish_more(@node, uri: tag.public_uri, path: CGI::unescape(tag.public_path), smart_phone_path: CGI::unescape(tag.public_smart_phone_path), dependent: tag.public_uri) end end end <file_sep>class Cms::Controller::Public::Base < Sys::Controller::Public::Base include Cms::Controller::Layout before_action :initialize_params after_action :render_public_variables after_action :render_public_layout def initialize_params if m = Page.uri.match(/\.p(\d+)\.html(\.r)?\z/) page = m[1].to_i params[:page] = page if page > 0 end if d = Page.uri.match(/\.(\d+)\.html(\.r)?\z/) date = d[1].to_s params[:date] = date end end def pre_dispatch ## each processes before dispatch end def render_public_variables end end <file_sep>class Sys::Admin::KanaDictionariesController < Cms::Controller::Admin::Base include Sys::Controller::Scaffold::Base include Sys::Controller::Scaffold::Publication def pre_dispatch return error_auth unless Core.user.root? end def index return test if params[:do] == 'test' return make_dictionary if params[:do] == 'make_dictionary' @items = Cms::KanaDictionary.where(site_id: nil).order(:id).paginate(page: params[:page], per_page: params[:limit]) _index @items end def show @item = Cms::KanaDictionary.find(params[:id]) return error_auth unless @item.readable? _show @item end def new @item = Cms::KanaDictionary.new( :body => "" + "# コメント ... 先頭に「#」\n" + "# 辞書には登録されません。\n\n" + "# 日本語例 ... 「漢字, カタカナ」\n" + "文字, モジ\n" + "単語, タンゴ\n\n" + "# 英字例 ... 「英字, カタカナ」\n" + "CMS, シーエムエス\n" ) end def create return test if params[:do] == 'test' @item = Cms::KanaDictionary.new(kana_dictionary_params) _create @item end def update @item = Cms::KanaDictionary.find(params[:id]) @item.attributes = kana_dictionary_params _update @item end def destroy @item = Cms::KanaDictionary.find(params[:id]) _destroy @item end def make res = false Cms::Site.order(:id).each do |site| Cms::KanaDictionary.make_dic_file(site.id) end res = Cms::KanaDictionary.make_dic_file if res == true flash[:notice] = '辞書を更新しました。' else flash[:notice] = res.join('<br />') end redirect_to sys_kana_dictionaries_url end private def kana_dictionary_params params.require(:item).permit(:body, :name, :creator_attributes => [:id, :group_id, :user_id]) end end <file_sep>module Sys::Model::Rel::Publication def self.included(mod) # mod.belongs_to :publisher, :foreign_key => :path, :primary_key => :path, :class_name => 'Sys::Publisher', # :dependent => :destroy mod.belongs_to :publisher, :foreign_key => 'unid', :class_name => 'Sys::Publisher', :dependent => :destroy end def public_status return published_at ? '公開中' : '非公開' end def public_path Page.site.public_path + public_uri end def public_uri '/'#TODO end def preview_uri(options = {}) return nil unless public_uri site = options[:site] || Page.site mb = options[:mobile] ? 'm' : nil "#{Core.full_uri}_preview/#{format('%04d', site.id)}#{mb}#{public_uri}" end def publish_uri(options = {}) site = options[:site] || Page.site "#{Core.full_uri}_publish/#{format('%04d', site.id)}#{public_uri}" end def publishable editable self.and "#{self.class.table_name}.state", 'recognized' return self end def closable editable public return self end def publishable? return false unless editable? return false unless recognized? return true end def rebuildable? return false unless editable? return state == 'public'# && published_at end def closable? return false unless editable? return state == 'public'# && published_at end def mobile_page? false end def publish(content, options = {}) return false unless content @save_mode = :publish if !options[:path] #################### self.state = 'public' self.published_at ||= Core.now return false unless save(:validate => false) end if options[:path] #################### path = options[:path].gsub(/\/$/, "/index.html") Util::File.put(path, :data => content, :mkdir => true) unless mobile_page? return true end path = public_path.gsub(/\/$/, "/index.html") Util::File.put(path, :data => content, :mkdir => true) unless mobile_page? pub = publisher || Sys::Publisher.new pub.published_at = Core.now pub.published_path = public_path.gsub(/^#{Rails.root.to_s}/, '.') pub.name = ::File.basename(public_path) pub.content_type = 'text/html' pub.content_length = content.size if pub.id return false unless pub.save else pub.id = unid pub.created_at = Core.now pub.updated_at = Core.now return false unless pub.save_with_direct_sql end publisher(true) ## yomiage sound # add_publisher(:path => path, :content => content) # add_talk_task(:path => path) return true end def rebuild(content, options = {}) unless public? errors.add :base, "公開されていません。" return false end if publisher publisher.destroy publisher(true) end unless creator self.in_creator = {:user_id => '', :group_id => ''} end publish(content, options) end def close @save_mode = :close if publisher publisher.destroy publisher(true) end self.state = 'closed' if self.state == 'public' save(:validate => false) end end<file_sep>class Cms::LinkCheckLog < ApplicationRecord include Sys::Model::Base RESULT_STATE_OPTIONS = [['○','success'],['×','failure'],['-','skip']] belongs_to :site belongs_to :link_checkable, polymorphic: true after_initialize :set_defaults scope :search_with_params, ->(criteria) { rel = all rel.where!(result_state: criteria[:result_state]) if criteria && criteria[:result_state].present? rel } def result_state_mark RESULT_STATE_OPTIONS.rassoc(result_state).try(:first) end private def set_defaults self.checked = false if self.has_attribute?(:checked) && self.checked.nil? end end <file_sep>FactoryGirl.define do factory :gp_article_link, class: 'GpArticle::Link' do doc_id 1 body 'こちら' url 'http://example.com' end end <file_sep>## --------------------------------------------------------- ## cms/concepts c_site = @site.concepts.where(parent_id: 0).first c_top = @site.concepts.where(name: 'トップページ').first c_content = @site.concepts.where(name: 'コンテンツ').first c_group = @site.concepts.where(name: '組織').first ## --------------------------------------------------------- ## cms/contents l_grouop = create_cms_layout c_site, 'soshiki', '組織' l_top_grp = create_cms_layout c_site, 'soshiki-top', '組織TOP' organization = create_cms_content c_content, 'Organization::Group', '組織一覧', 'soshiki' create_cms_node c_content, organization, 120, nil, l_top_grp, 'Organization::Group', 'soshiki', '組織', nil category = GpCategory::Content::CategoryType.where(concept_id: c_content.id).first settings = Organization::Content::Setting.config(organization, 'gp_category_content_category_type_id') settings.value = category.id settings.save Sys::Group.where(Sys::Group.arel_table[:level_no].not_eq(1)).each do |g| Organization::Group.create content_id: organization.id, sort_no: g.sort_no, state: 'public', name: g.name_en, sys_group_code: g.code, sitemap_state: 'visible', docs_order: 'display_published_at DESC, published_at DESC' end ## --------------------------------------------------------- ## cms/pieces create_cms_piece c_group, organization, 'Organization::AllGroup', 'soshiki-list', '組織一覧' create_cms_piece c_group, organization, 'Organization::BusinessOutline', 'business-outline', '業務内容' create_cms_piece c_group, organization, 'Organization::Outline', 'soshiki-introduce', '組織の紹介' address = create_cms_piece c_group, organization, 'Organization::ContactInformation', 'soshiki-address', '連絡先' address.in_settings = {source: 'organization_group'} address.save <file_sep>require 'openssl' class Util::String::Crypt def self.encrypt(msg, pass = '<PASSWORD>', salt = nil) enc = OpenSSL::Cipher::Cipher.new('aes-256-cbc') enc.encrypt enc.pkcs5_keyivgen(pass, salt) Base64.encode64(enc.update(msg) + enc.final).encode(Encoding::UTF_8) rescue false end def self.decrypt(msg, pass = '<PASSWORD>', salt = nil) dec = OpenSSL::Cipher::Cipher.new('aes-256-cbc') dec.decrypt dec.pkcs5_keyivgen(pass, salt) dec.update(Base64.decode64(msg.encode(Encoding::ASCII_8BIT))) + dec.final rescue false end end <file_sep>class Map::NavigationsScript < Cms::Script::Publication def publish end end <file_sep>module GpCategory::CategoryTypes::Preload extend ActiveSupport::Concern module ClassMethods def public_node_ancestors_assocs category_type_assocs end def root_categories_and_descendants_assocs { root_categories: descendants_assocs } end def public_root_categories_and_public_descendants_assocs { public_root_categories: public_descendants_assocs } end def public_root_categories_and_public_descendants_and_public_node_ancestors_assocs { public_root_categories: public_descendants_and_public_node_ancestors_assocs } end private def descendants_assocs(depth = 3) return nil if depth < 0 { parent: nil, children: descendants_assocs(depth - 1) } end def public_descendants_assocs(depth = 3) return nil if depth < 0 { category_type: nil, parent: nil, public_children: public_descendants_assocs(depth - 1) } end def public_descendants_and_public_node_ancestors_assocs(depth = 3) return nil if depth < 0 { category_type: category_type_assocs, parent: nil, public_children: public_descendants_and_public_node_ancestors_assocs(depth - 1) } end def parent_assocs(depth = 3) return nil if depth < 0 { site: nil, parent: parent_assocs(depth - 1) } end def category_type_assocs { content: { public_node: { site: nil, parent: parent_assocs } } } end end end <file_sep>class Rank::Admin::Content::BaseController < Cms::Admin::Content::BaseController end <file_sep>class PublisherCallbacks < ApplicationCallbacks end <file_sep>class Cms::SiteBelonging < ApplicationRecord include Sys::Model::Base belongs_to :site, :class_name => 'Cms::Site' belongs_to :group, :class_name => 'Sys::Group' validates :site_id, presence: true end <file_sep>require 'spec_helper' describe Cms::OAuthUser do context 'when create using omniauth' do before do @valid_auth = { provider: 'facebook', uid: '1234567890', info_nickname: 'yamada', info_name: '<NAME>', info_image: 'http://example.com/images/yamada.jpg', info_url: 'http://example.com/yamada' } end describe 'with valid auth' do it 'does not raise error' do expect { Cms::OAuthUser.create_or_update_with_omniauth(@valid_auth) }.to_not raise_error end end describe 'with invalid auth' do it 'raise error' do @valid_auth[:provider] = nil expect { Cms::OAuthUser.create_or_update_with_omniauth(@valid_auth) }.to raise_error end end end context 'when build' do describe 'with valid arguments' do it do user = FactoryGirl.build(:valid_o_auth_user) expect(user).to be_valid end end describe 'without provider' do it do user = FactoryGirl.build(:valid_o_auth_user, provider: nil) expect(user).not_to be_valid expect(user.errors[:provider].size).to eq(1) end end describe 'without uid' do it do user = FactoryGirl.build(:valid_o_auth_user, uid: nil) expect(user).not_to be_valid expect(user.errors[:uid].size).to eq(1) end end end end <file_sep>module Cms::Model::Rel::Bracketee extend ActiveSupport::Concern def bracket_name return nil if name.blank? "#{Cms::Lib::Bracket.bracket_type(self)}/#{name}" end def bracketees bracketees_with_name(bracket_name) end def bracketees_with_name(name) Cms::Bracket.where(site_id: site_id, name: name) end end <file_sep>class GpCategory::Publisher::TemplateModuleCallbacks < PublisherCallbacks def after_save(_module) @module = _module enqueue if enqueue? end def before_destroy(_module) @module = _module enqueue if enqueue? end def enqueue(_module = nil) @module = _module if _module enqueue_templates end private def enqueue? true end def enqueue_templates names = [@module.name, @module.name_was].uniq.select(&:present?) @module.content.templates_with_name(names).each do |template| GpCategory::Publisher::TemplateCallbacks.new.enqueue(template) end end end <file_sep>class Reception::OpensScript < Cms::Script::Publication def expire_by_task if (item = params[:item]) && item.state_public? ::Script.current info_log "-- Expire: #{item.class}##{item.id}" item.expire Sys::OperationLog.script_log(item: item, site: item.content.site, action: 'expire') info_log 'OK: Expired' params[:task].destroy ::Script.success end end end <file_sep>module Feed::FeedHelper def entry_replace(entry, entry_style, date_style, time_style='') contents = { title_link: -> { entry_replace_title_link(entry) }, title: -> { entry_replace_title(entry) }, subtitle: -> { entry_replace_subtitle(entry) }, publish_date: -> { entry_replace_publish_date(entry, date_style) }, publish_time: -> { entry_replace_publish_time(entry, time_style) }, summary: -> { entry_replace_summary(entry) }, category: -> { entry_replace_category(entry) }, image_link: -> { entry_replace_image_link(entry) }, image: -> { entry_replace_image(entry) }, feed_name: -> { entry_replace_feed_name(entry) }, new_mark: -> { entry_replace_new_mark(entry) } } if Page.mobile? contents[:title_link].call else entry_style = entry_style.gsub(/@entry{{@(.+)@}}entry@/m){|m| link_to($1.html_safe, entry.public_uri, class: 'entry_link') } entry_style = entry_style.gsub(/@(\w+)@/) {|m| contents[$1.to_sym] ? contents[$1.to_sym].call : '' } entry_style.html_safe end end private def entry_image_tag(entry) unless entry.image_uri.blank? image_tag(entry.image_uri, alt: entry.title) else '' end end def entry_replace_title_link(entry) if entry.title.present? link = link_to(entry.title, entry.public_uri, :target => '_blank') content_tag(:span, link, class: 'title_link') else '' end end def entry_replace_title(entry) if entry.title.present? content_tag(:span, entry.title, class: 'title') else '' end end def entry_replace_publish_date(entry, date_style) if (dpa = entry.entry_updated) ds = localize_wday(date_style, dpa.wday) content_tag(:span, dpa.strftime(ds), class: 'publish_date') else '' end end def entry_replace_publish_time(entry, time_style) if (dpa = entry.entry_updated) content_tag(:span, dpa.strftime(time_style), class: 'publish_time') else '' end end def entry_replace_summary(entry) if entry.summary.present? content_tag(:blockquote, entry.summary, class: 'summary') else '' end end def entry_replace_category(entry) unless entry.categories.blank? category_text = entry.categories.split(/\n/).map {|category| content_tag(:span, category) }.join.html_safe content_tag(:span, category_text, class: 'category') else '' end end def entry_replace_image_link(entry) image_tag = entry_image_tag(entry) image_link = if image_tag.present? link_to image_tag, :target => '_blank' else image_tag end if image_link.present? content_tag(:span, image_link, class: 'image') else '' end end def entry_replace_image(entry) image_tag = entry_image_tag(entry) if image_tag.present? content_tag(:span, image_tag, class: 'image') else '' end end def entry_replace_new_mark(entry) if entry.new_mark content_tag(:span, 'New', class: 'new') else '' end end def entry_replace_feed_name(entry) if entry.feed entry.feed.title end end end <file_sep>##--------------------------------------------------------- ##truncate exclusions = %w(ar_internal_metadata schema_migrations) ActiveRecord::Base.connection.tables.each do |table| next if exclusions.include?(table) ActiveRecord::Base.connection.execute("TRUNCATE TABLE #{table} RESTART IDENTITY;") end <file_sep>module Sys::Model::Rel::Recognition def self.included(mod) mod.has_one :recognition, class_name: 'Sys::Recognition', dependent: :destroy, as: :recognizable mod.after_save :save_recognition end def in_recognizer_ids @in_recognizer_ids ||= recognizer_ids.to_s end def in_recognizer_ids=(ids) @_in_recognizer_ids_changed = true @in_recognizer_ids = ids.to_s end def recognizer_ids recognition ? recognition.recognizer_ids : '' end def recognizers recognition ? recognition.recognizers : [] end def join_recognition join :recognition end def recognized? return state == 'recognized' end def recognizable?(user = nil) return false unless recognition return false unless state == "recognize" recognition.recognizable?(user) end def recognize(user) return false unless recognition rs = recognition.recognize(user) if state == 'recognize' && recognition.recognized_all? sql = "UPDATE #{self.class.table_name} SET state = 'recognized', recognized_at = '#{Core.now}' WHERE id = #{id}" self.state = 'recognized' self.recognized_at = Core.now self.class.connection.execute(sql) end return rs end private def validate_recognizers errors["承認者"] = "を入力してください。" if in_recognizer_ids.blank? end def save_recognition return true unless @_in_recognizer_ids_changed return false if @sent_save_recognition @sent_save_recognition = true unless (rec = recognition) rec = Sys::Recognition.new rec.recognizable = self end rec.user_id = Core.user.id rec.recognizer_ids = in_recognizer_ids.strip rec.info_xml = nil rec.save rec.reset_info self.update_attribute(:recognized_at, nil) return true end end <file_sep>class Cms::PieceSetting < ApplicationRecord include Sys::Model::Base belongs_to :piece, :foreign_key => :piece_id, :class_name => 'Cms::Piece' validates :piece_id, :name, presence: true def extra_values=(ev) self.extra_value = YAML.dump(ev) if ev.is_a?(Hash) return ev end def extra_values return {}.with_indifferent_access unless self.extra_value.is_a?(String) ev = YAML.load(self.extra_value) return {}.with_indifferent_access unless ev.is_a?(Hash) return ev.with_indifferent_access end end <file_sep>class GpCategory::Categorization < ApplicationRecord include Sys::Model::Base default_scope { order("#{self.table_name}.sort_no IS NULL, #{self.table_name}.sort_no") } belongs_to :categorizable, polymorphic: true belongs_to :category end <file_sep>class Cms::Publisher::NodeCallbacks < PublisherCallbacks def after_save(node) @node = node enqueue if enqueue? end def enqueue(node = nil) @node = node if node enqueue_nodes enqueue_sitemap_nodes end private def enqueue? @node.name.present? && [@node.state, @node.state_was].include?('public') end def enqueue_nodes return if @node.model.in?(%w(Cms::Page Cms::Directory Cms::Sitemap)) Cms::Publisher.register(@node.site_id, @node) end def enqueue_sitemap_nodes return if @node.model == 'Cms::Sitemap' site = @node.site Cms::Publisher.register(site.id, site.public_sitemap_nodes) end end <file_sep>class Cms::Publisher::LayoutCallbacks < PublisherCallbacks def after_save(layout) @layout = layout enqueue if enqueue? end def before_destroy(layout) @layout = layout enqueue if enqueue? end def enqueue(layout = nil) @layout = layout if layout enqueue_nodes enqueue_categories enqueue_organization_groups enqueue_docs end private def enqueue? @layout.name.present? end def enqueue_nodes nodes = Cms::Node.public_state.where(layout_id: @layout.id) Cms::Publisher.register(@layout.site_id, nodes) end def enqueue_categories cat_types = GpCategory::CategoryType.public_state.where(layout_id: @layout.id).all cat_types.each do |cat_type| Cms::Publisher.register(@layout.site_id, cat_type.public_categories) end cats = GpCategory::Category.public_state.where(layout_id: @layout.id) Cms::Publisher.register(@layout.site_id, cats) end def enqueue_organization_groups ogs = Organization::Group.public_state.with_layout(@layout.id) Cms::Publisher.register(@layout.site_id, ogs) end def enqueue_docs docs = GpArticle::Doc.public_state.where(layout_id: @layout.id).select(:id) Cms::Publisher.register(@layout.site_id, docs) end end <file_sep>class Cms::Publisher < ApplicationRecord include Sys::Model::Base STATE_OPTIONS = [['待機中','queued'],['実行中','performing']] belongs_to :publishable, polymorphic: true validate :validate_queue, on: :create before_save :set_priority scope :queued_items, -> { where([ arel_table[:state].eq('queued'), [arel_table[:state].eq('performing'), arel_table[:updated_at].lt(Time.now - 3.hours)].reduce(:and) ].reduce(:or)) } private def validate_queue if self.class.where(state: 'queued', publishable_id: publishable_id, publishable_type: publishable_type) .where("extra_flag = ?", extra_flag.to_json) .exists? errors.add(:publishable_id, :taken) end end def set_priority self.priority = if publishable.is_a?(Cms::Node) && publishable.top_page? 10 elsif publishable.is_a?(GpCategory::Category) 20 else 30 end end class << self def register(site_id, items, extra_flag = {}) items = Array(items) return if items.blank? pubs = items.map do |item| pub = self.new(site_id: site_id, publishable: item, state: 'queued', extra_flag: extra_flag) pub.run_callbacks(:save) { false } pub end self.import(pubs) Cms::PublisherJob.perform_later unless Cms::PublisherJob.queued? end end end <file_sep>class GpCalendar::Public::Piece::BaseController < Sys::Controller::Public::Base private def merge_docs_into_events(docs, events) merged = events + docs.map { |doc| GpCalendar::Event.from_doc(doc, @piece.content) } merged.sort { |a, b| a.started_on <=> b.started_on } end end <file_sep>puts 'import approval flow...' ## --------------------------------------------------------- ## cms/concepts c_site = @site.concepts.where(parent_id: 0).first c_top = @site.concepts.where(name: 'トップページ').first c_content = @site.concepts.where(name: 'コンテンツ').first ## --------------------------------------------------------- ## cms/contents approval_flow = create_cms_content c_content, 'Approval::ApprovalFlow', '承認フロー', 'approval_flow' somu = Sys::User.find_by(account: "#{@code_prefix}somu3") somu_flow = Approval::ApprovalFlow.create content_id: approval_flow.id, title: Core.user_group.name, group_id: Core.user_group.id, sort_no: 10 approval = somu_flow.approvals.create(index: 0, approval_type: 'fix') approval.assignments.create(user_id: somu.id, or_group_id: 0) bosaika = @site.groups.where(code: "#{@code_prefix}1003").first bosai = Sys::User.find_by(account: "#{@code_prefix}bosai3") bosai_flow = Approval::ApprovalFlow.create content_id: approval_flow.id, title: bosaika.name, group_id: bosaika.id, sort_no: 10 approval = bosai_flow.approvals.create(index: 0, approval_type: 'fix') approval.assignments.create(user_id: bosai.id, or_group_id: 0) <file_sep>class Cms::OAuthUser < ApplicationRecord include Sys::Model::Base has_many :threads, :foreign_key => :user_id, :class_name => 'PublicBbs::Thread' validates :provider, :presence => true validates :uid, :presence => true def self.create_or_update_with_omniauth(auth) attrs = { nickname: auth[:info_nickname], name: auth[:info_name], image: auth[:info_image], url: auth[:info_url] } if (user = self.find_by(provider: auth[:provider], uid: auth[:uid])) user.update_attributes!(attrs) else user = self.create!(attrs.merge(provider: auth[:provider], uid: auth[:uid])) end return user end end <file_sep>class GpArticle::DocsScript < Cms::Script::Publication def publish uri = @node.public_uri.to_s path = @node.public_path.to_s smart_phone_path = @node.public_smart_phone_path.to_s publish_page(@node, uri: "#{uri}index.rss", path: "#{path}index.rss", dependent: :rss) publish_page(@node, uri: "#{uri}index.atom", path: "#{path}index.atom", dependent: :atom) content = @node.content common_params = { uri: uri, path: path, smart_phone_path: smart_phone_path } if content.doc_list_pagination == 'simple' publish_more(@node, common_params.merge(limit: content.doc_publish_more_pages)) else if params[:target_date].present? publish_target_dates(@node, common_params.merge( page_style: content.doc_list_pagination, first_date: date_pagination_query(content).first_page_date, target_dates: load_neighbor_dates(content, params[:target_date]))) else publish_more_dates(@node, common_params.merge( page_style: content.doc_list_pagination, page_dates: date_pagination_query(content).page_dates)) end end end def date_pagination_query(content, current_date = nil) DatePaginationQuery.new(content.public_docs_for_list, page_style: content.doc_list_pagination, column: content.docs_order_column, direction: content.docs_order_direction, current_date: current_date) end def load_neighbor_dates(content, target_date) dates = [] Array(target_date).each do |date| current_date = Time.parse(date) query = date_pagination_query(content, current_date) dates += [query.next_page_date, current_date, query.prev_page_date] end dates.compact.uniq end def publish_doc docs = @node.content.public_docs.where(id: params[:target_doc_id]) docs.find_each do |doc| ::Script.progress(doc) do uri = doc.public_uri path = doc.public_path if doc.publish(render_public_as_string(uri, site: doc.content.site)) uri_ruby = (uri =~ /\?/) ? uri.gsub(/\?/, 'index.html.r?') : "#{uri}index.html.r" path_ruby = "#{path}.r" doc.publish_page(render_public_as_string(uri_ruby, site: doc.content.site), path: path_ruby, dependent: :ruby) doc.publish_page(render_public_as_string(uri, site: doc.content.site, agent_type: :smart_phone), path: doc.public_smart_phone_path, dependent: :smart_phone) end end end end def publish_by_task if (item = params[:item]) && (item.state_approved? || item.state_prepared?) ::Script.current info_log "-- Publish: #{item.class}##{item.id}" uri = item.public_uri.to_s path = item.public_path.to_s # Renew edition before render_public_as_string item.update_attribute(:state, 'public') if item.publish(render_public_as_string(uri, site: item.content.site)) Sys::OperationLog.script_log(:item => item, :site => item.content.site, :action => 'publish') else raise item.errors.full_messages end if item.published? || !::File.exist?("#{path}.r") uri_ruby = (uri =~ /\?/) ? uri.gsub(/\?/, 'index.html.r?') : "#{uri}index.html.r" path_ruby = "#{path}.r" item.publish_page(render_public_as_string(uri_ruby, site: item.content.site), path: path_ruby, dependent: :ruby) end info_log %Q!OK: Published to "#{path}"! params[:task].destroy ::Script.success end end def close_by_task if (item = params[:item]) && item.state_public? ::Script.current info_log "-- Close: #{item.class}##{item.id}" item.close Sys::OperationLog.script_log(:item => item, :site => item.content.site, :action => 'close') info_log 'OK: Finished' params[:task].destroy ::Script.success end end end <file_sep># ========================================================================= # Based on 「旧暦計算サンプルプログラム」 # Copyright (C) 1993,1994 by H.Takano # http://www.vector.co.jp/soft/dos/personal/se016093.html # ========================================================================= module GpCalendar::QrekiHelper include Math $k = Math::PI / 180.0 # Pi $tz = - (9.0 / 24.0) # タイムゾーンオフセット $rm_sun0 = 0 # 太陽黄経 def qreki(tm, format = '旧%02d月%02d日') q = calc_kyureki(tm.year, tm.month, tm.day) return sprintf(format, q[2].to_i, q[3].to_i) end def qreki_ymd(year, mon, day) return qreki(Date.new(year, mon, day)) end # ========================================================================= # 新暦に対応する、旧暦を求める。 # # 呼び出し時にセットする変数: # year : 計算する年(JSTユリウス日) # mon : 計算する月(JSTユリウス日) # day : 計算する日(JSTユリウス日) # 戻り値: # this.year : 旧暦年 # this.uruu : 平月/閏月 flag .... 平月:false 閏月:true # this.month : 旧暦月 # this.day : 旧暦日 # ========================================================================= def calc_kyureki(year, mon, day) chu = Array.new(5, []) m = Array.new(5).map{Array.new(3,0)} saku = Array.new kyureki = Array.new tm = ymdt2jd(year, mon, day, 0, 0, 0) # ----------------------------------------------------------------------- # 計算対象の直前にあたる二分二至の時刻を求める # ----------------------------------------------------------------------- chu[0] = calc_chu(tm, 90) # ----------------------------------------------------------------------- # 上で求めた二分二至の時の太陽黄経をもとに朔日行列の先頭に月名をセット # ----------------------------------------------------------------------- m[0][0] = ( $rm_sun0 / 30.0 ).to_i + 2 # ----------------------------------------------------------------------- # 中気の時刻を計算(3回計算する) # chu[i]:中気の時刻 # ----------------------------------------------------------------------- (1..3).each do |i| chu[i] = calc_chu(chu[i - 1] + 32, 30) end # ----------------------------------------------------------------------- # 計算対象の直前にあたる二分二至の直前の朔の時刻を求める # ----------------------------------------------------------------------- saku[0] = calc_saku(chu[0]) # ----------------------------------------------------------------------- # 朔の時刻を求める # ----------------------------------------------------------------------- (1..4).each do |i| saku[i] = calc_saku(saku[i - 1] + 30) # 前と同じ時刻を計算した場合(両者の差が26日以内)には、初期値を # +33日にして再実行させる。 if (saku[i - 1].to_i.abs - saku[i].to_i) <= 26 saku[i] = calc_saku(saku[i - 1] + 35) end end # ----------------------------------------------------------------------- # saku[1]が二分二至の時刻以前になってしまった場合には、朔をさかのぼり過ぎ # たと考えて、朔の時刻を繰り下げて修正する。 # その際、計算もれ(saku[4])になっている部分を補うため、朔の時刻を計算 # する。(近日点通過の近辺で朔があると起こる事があるようだ...?) # ----------------------------------------------------------------------- if saku[1].to_i <= chu[0].to_i (0..4).each do |i| saku[i] = saku[i + 1] end saku[4] = calc_saku(saku[3] + 35) # ----------------------------------------------------------------------- # saku[0]が二分二至の時刻以後になってしまった場合には、朔をさかのぼり足 # りないと見て、朔の時刻を繰り上げて修正する。 # その際、計算もれ(saku[0])になっている部分を補うため、朔の時刻を計算 # する。(春分点の近辺で朔があると起こる事があるようだ...?) # ----------------------------------------------------------------------- elsif saku[0].to_i > chu[0].to_i [4,3,2,1].each do |i| saku[i] = saku[i - 1] end saku[0] = calc_saku(saku[0] - 27) end # ----------------------------------------------------------------------- # 閏月検索Flagセット # (節月で4ヶ月の間に朔が5回あると、閏月がある可能性がある。) # lap=false:平月 lap=true:閏月 # ----------------------------------------------------------------------- lap = (saku[4].to_i <= chu[3].to_i) # ----------------------------------------------------------------------- # 朔日行列の作成 # m[i][0] ... 月名(1:正月 2:2月 3:3月 ....) # m[i][1] .... 閏フラグ(false:平月 true:閏月) # m[i][2] ...... 朔日のjd # ----------------------------------------------------------------------- m[0][1] = false m[0][2] = saku[0].to_i (1..4).each do |i| if lap && i > 1 if (chu[i - 1] <= saku[i - 1].to_i) || (chu[i - 1] >= saku[i].to_i) m[i-1][0] = m[i-2][0] m[i-1][1] = true m[i-1][2] = saku[i - 1].to_i lap = false end end m[i][0] = m[i-1][0] + 1 m[i][0] -= 12 if m[i][0] > 12 m[i][2] = saku[i].to_i m[i][1] = false end # ----------------------------------------------------------------------- # 朔日行列から旧暦を求める。 # ----------------------------------------------------------------------- state = 0 i_tmp = 0 (1..4).each do |i| i_tmp = i if tm.to_i < m[i][2].to_i state = 1 break elsif tm.to_i == m[i][2].to_i state = 2 break end end i_tmp -= 1 if state == 0 || state == 1 i = i_tmp kyureki[1] = m[i][1] kyureki[2] = m[i][0] kyureki[3] = tm.to_i - m[i][2].to_i + 1 # ----------------------------------------------------------------------- # 旧暦年の計算 # (旧暦月が10以上でかつ新暦月より大きい場合には、 # まだ年を越していないはず...) # ----------------------------------------------------------------------- a = jd2ymdt(tm) kyureki[0] = a[0] if kyureki[2] > 9 && kyureki[2] > a[1] kyureki[0] -= 1 end return [kyureki[0], kyureki[1], kyureki[2], kyureki[3]] end # ========================================================================= # 直前の二分二至/中気の時刻を求める # # パラメータ # tm ............ 計算基準となる時刻(JSTユリウス日) # longitude ..... 求める対象(90:二分二至,30:中気)) # 戻り値 # 求めた時刻(JSTユリウス日)を返す。 # グローバル変数 $rm_sun0 に、その時の太陽黄経をセットする。 # # ※ 引数、戻り値ともユリウス日で表し、時分秒は日の小数で表す。 # 力学時とユリウス日との補正時刻=0.0secと仮定 # ========================================================================= def calc_chu(tm, longitude) # ----------------------------------------------------------------------- # 時刻引数を小数部と整数部とに分解する(精度を上げるため) # ----------------------------------------------------------------------- tm1 = tm.to_i tm2 = tm - tm1 + $tz # JST -> UTC # ----------------------------------------------------------------------- # 直前の二分二至の黄経 λsun0 を求める # ----------------------------------------------------------------------- t = (tm2 + 0.5) / 36525.0 + (tm1 - 2451545.0) / 36525.0 rm_sun = longitude_sun(t) $rm_sun0 = longitude * (rm_sun / longitude.to_f).to_i # ----------------------------------------------------------------------- # 繰り返し計算によって直前の二分二至の時刻を計算する # (誤差が±1.0 sec以内になったら打ち切る。) # ----------------------------------------------------------------------- delta_t1 ||= 0.0 delta_t2 ||= 1.0 while (delta_t1 + delta_t2).abs > (1.0 / 86400.0) # ------------------------------------------------------------------- # λsun(t) を計算 # t = (tm + .5 - 2451545) / 36525; # ------------------------------------------------------------------- t = (tm2 + 0.5) / 36525.0 + (tm1 - 2451545.0) / 36525.0 rm_sun = longitude_sun(t) # ------------------------------------------------------------------- # 黄経差 Δλ=λsun -λsun0 # ------------------------------------------------------------------- delta_rm = rm_sun - $rm_sun0 # ------------------------------------------------------------------- # Δλの引き込み範囲(±180°)を逸脱した場合には、補正を行う # ------------------------------------------------------------------- if delta_rm > 180.0 delta_rm -= 360.0 elsif delta_rm < -180.0 delta_rm += 360.0 end # ------------------------------------------------------------------- # 時刻引数の補正値 Δt # delta_t = delta_rm * 365.2 / 360; # ------------------------------------------------------------------- delta_t1 = (delta_rm * 365.2 / 360.0).to_i delta_t2 = (delta_rm * 365.2 / 360.0) - delta_t1 # ------------------------------------------------------------------- # 時刻引数の補正 # tm -= delta_t; # ------------------------------------------------------------------- tm1 = tm1 - delta_t1 tm2 = tm2 - delta_t2 if tm2 < 0 tm1 -= 1.0 tm2 += 1.0 end end # ----------------------------------------------------------------------- # 戻り値の作成 # 時刻引数を合成し、戻り値(JSTユリウス日)とする # ----------------------------------------------------------------------- return tm2 + tm1 - $tz end # ========================================================================= # 直前の朔の時刻を求める # # 呼び出し時にセットする変数 # tm ........ 計算基準の時刻(JSTユリウス日) # 戻り値 # 朔の時刻 # # ※ 引数、戻り値ともJSTユリウス日で表し、時分秒は日の小数で表す。 # 力学時とユリウス日との補正時刻=0.0secと仮定 # ========================================================================= def calc_saku(tm) # ----------------------------------------------------------------------- # ループカウンタのセット # ----------------------------------------------------------------------- lc = 1 # ----------------------------------------------------------------------- # 時刻引数を小数部と整数部とに分解する(精度を上げるため) # ----------------------------------------------------------------------- tm1 = tm.to_i tm2 = tm - tm1 + $tz # JST -> UTC # ----------------------------------------------------------------------- # 繰り返し計算によって朔の時刻を計算する # (誤差が±1.0 sec以内になったら打ち切る。) # ----------------------------------------------------------------------- delta_t1 ||= 0.0 delta_t2 ||= 1.0 while ( delta_t1 + delta_t2 ).abs > ( 1.0 / 86400.0 ) lc += 1 # ------------------------------------------------------------------- # 太陽の黄経λsun(t) ,月の黄経λmoon(t) を計算 # t = (tm + .5 - 2451545) / 36525; # ------------------------------------------------------------------- t = (tm2 + 0.5) / 36525.0 + (tm1 - 2451545.0) / 36525.0 rm_sun = longitude_sun(t) rm_moon = longitude_moon(t) # ------------------------------------------------------------------- # 月と太陽の黄経差Δλ # Δλ=λmoon-λsun # ------------------------------------------------------------------- delta_rm = rm_moon - rm_sun # ------------------------------------------------------------------- # ループの1回目(lc=1)で delta_rm < 0 の場合には引き込み範囲に # 入るように補正する # ------------------------------------------------------------------- if lc==1 && delta_rm < 0 delta_rm = normalization_angle(delta_rm) # ------------------------------------------------------------------- # 春分の近くで朔がある場合(0 ≦λsun≦ 20)で、 # 月の黄経λmoon≧300 の場合には、 # Δλ= 360 - Δλ と計算して補正する # ------------------------------------------------------------------- elsif rm_sun >= 0 && rm_sun <= 20 && rm_moon >= 300 delta_rm = normalization_angle(delta_rm) delta_rm = 360 - delta_rm # ------------------------------------------------------------------- # Δλの引き込み範囲(±40°)を逸脱した場合には、補正を行う # ------------------------------------------------------------------- elsif delta_rm.abs > 40 delta_rm = normalization_angle(delta_rm) end # ------------------------------------------------------------------- # 時刻引数の補正値 Δt # delta_t = delta_rm * 29.530589 / 360; # ------------------------------------------------------------------- delta_t1 = ( delta_rm * 29.530589 / 360.0 ).to_i delta_t2 = ( delta_rm * 29.530589 / 360.0 ) - delta_t1 # ------------------------------------------------------------------- # 時刻引数の補正 # tm -= delta_t; # ------------------------------------------------------------------- tm1 = tm1 - delta_t1 tm2 = tm2 - delta_t2 if( tm2 < 0 ) tm1 -= 1.0 tm2 += 1.0 end # ------------------------------------------------------------------- # ループ回数が15回になったら、初期値 tm を tm-26 とする。 # ------------------------------------------------------------------- if( lc == 15 && (delta_t1 + delta_t2).abs > (1 / 86400.0) ) tm1 = (tm - 26).to_i tm2 = 0 # ------------------------------------------------------------------- # 初期値を補正したにも関わらず、振動を続ける場合には初期値を答えとし # て返して強制的にループを抜け出して異常終了させる。 # ------------------------------------------------------------------- elsif( lc > 30 && (delta_t1 + delta_t2).abs > (1 / 86400.0) ) tm1 = tm tm2 = 0 break end end # ----------------------------------------------------------------------- # 戻り値の作成 # 時刻引数を合成し、戻り値(ユリウス日)とする # ----------------------------------------------------------------------- return tm2 + tm1 - $tz end # ========================================================================= # 角度の正規化を行う。すなわち引数の範囲を 0≦θ<360 にする。 # ========================================================================= def normalization_angle(angle) if angle >= 0.0 return angle - 360.0 * ( angle / 360.0 ).to_i else return 360.0 + angle - 360.0 * ( angle / 360.0 ).to_i end end # ========================================================================= # 太陽の黄経 λsun(t) を計算する(t は力学時) # ========================================================================= def longitude_sun(t) # ----------------------------------------------------------------------- # 摂動項の計算 # ----------------------------------------------------------------------- th = 0.0004 * cos( $k * normalization_angle( 31557.0 * t + 161.0 ) ) th += 0.0004 * cos( $k * normalization_angle( 29930.0 * t + 48.0 ) ) th += 0.0005 * cos( $k * normalization_angle( 2281.0 * t + 221.0 ) ) th += 0.0005 * cos( $k * normalization_angle( 155.0 * t + 118.0 ) ) th += 0.0006 * cos( $k * normalization_angle( 33718.0 * t + 316.0 ) ) th += 0.0007 * cos( $k * normalization_angle( 9038.0 * t + 64.0 ) ) th += 0.0007 * cos( $k * normalization_angle( 3035.0 * t + 110.0 ) ) th += 0.0007 * cos( $k * normalization_angle( 65929.0 * t + 45.0 ) ) th += 0.0013 * cos( $k * normalization_angle( 22519.0 * t + 352.0 ) ) th += 0.0015 * cos( $k * normalization_angle( 45038.0 * t + 254.0 ) ) th += 0.0018 * cos( $k * normalization_angle( 445267.0 * t + 208.0 ) ) th += 0.0018 * cos( $k * normalization_angle( 19.0 * t + 159.0 ) ) th += 0.0020 * cos( $k * normalization_angle( 32964.0 * t + 158.0 ) ) th += 0.0200 * cos( $k * normalization_angle( 71998.1 * t + 265.1 ) ) th -= 0.0048 * cos( $k * normalization_angle( 35999.05 * t + 267.52 ) ) * t th += 1.9147 * cos( $k * normalization_angle( 35999.05 * t + 267.52 ) ) # ----------------------------------------------------------------------- # 比例項の計算 # ----------------------------------------------------------------------- ang = normalization_angle( 36000.7695 * t ) ang = normalization_angle( ang + 280.4659 ) th = normalization_angle( th + ang ) return th end # ========================================================================= # 月の黄経 λmoon(t) を計算する(t は力学時) # ========================================================================= def longitude_moon(t) # ----------------------------------------------------------------------- # 摂動項の計算 # ----------------------------------------------------------------------- th = 0.0003 * cos( $k * normalization_angle( 2322131.0 * t + 191.0 ) ) th += 0.0003 * cos( $k * normalization_angle( 4067.0 * t + 70.0 ) ) th += 0.0003 * cos( $k * normalization_angle( 549197.0 * t + 220.0 ) ) th += 0.0003 * cos( $k * normalization_angle( 1808933.0 * t + 58.0 ) ) th += 0.0003 * cos( $k * normalization_angle( 349472.0 * t + 337.0 ) ) th += 0.0003 * cos( $k * normalization_angle( 381404.0 * t + 354.0 ) ) th += 0.0003 * cos( $k * normalization_angle( 958465.0 * t + 340.0 ) ) th += 0.0004 * cos( $k * normalization_angle( 12006.0 * t + 187.0 ) ) th += 0.0004 * cos( $k * normalization_angle( 39871.0 * t + 223.0 ) ) th += 0.0005 * cos( $k * normalization_angle( 509131.0 * t + 242.0 ) ) th += 0.0005 * cos( $k * normalization_angle( 1745069.0 * t + 24.0 ) ) th += 0.0005 * cos( $k * normalization_angle( 1908795.0 * t + 90.0 ) ) th += 0.0006 * cos( $k * normalization_angle( 2258267.0 * t + 156.0 ) ) th += 0.0006 * cos( $k * normalization_angle( 111869.0 * t + 38.0 ) ) th += 0.0007 * cos( $k * normalization_angle( 27864.0 * t + 127.0 ) ) th += 0.0007 * cos( $k * normalization_angle( 485333.0 * t + 186.0 ) ) th += 0.0007 * cos( $k * normalization_angle( 405201.0 * t + 50.0 ) ) th += 0.0007 * cos( $k * normalization_angle( 790672.0 * t + 114.0 ) ) th += 0.0008 * cos( $k * normalization_angle( 1403732.0 * t + 98.0 ) ) th += 0.0009 * cos( $k * normalization_angle( 858602.0 * t + 129.0 ) ) th += 0.0011 * cos( $k * normalization_angle( 1920802.0 * t + 186.0 ) ) th += 0.0012 * cos( $k * normalization_angle( 1267871.0 * t + 249.0 ) ) th += 0.0016 * cos( $k * normalization_angle( 1856938.0 * t + 152.0 ) ) th += 0.0018 * cos( $k * normalization_angle( 401329.0 * t + 274.0 ) ) th += 0.0021 * cos( $k * normalization_angle( 341337.0 * t + 16.0 ) ) th += 0.0021 * cos( $k * normalization_angle( 71998.0 * t + 85.0 ) ) th += 0.0021 * cos( $k * normalization_angle( 990397.0 * t + 357.0 ) ) th += 0.0022 * cos( $k * normalization_angle( 818536.0 * t + 151.0 ) ) th += 0.0023 * cos( $k * normalization_angle( 922466.0 * t + 163.0 ) ) th += 0.0024 * cos( $k * normalization_angle( 99863.0 * t + 122.0 ) ) th += 0.0026 * cos( $k * normalization_angle( 1379739.0 * t + 17.0 ) ) th += 0.0027 * cos( $k * normalization_angle( 918399.0 * t + 182.0 ) ) th += 0.0028 * cos( $k * normalization_angle( 1934.0 * t + 145.0 ) ) th += 0.0037 * cos( $k * normalization_angle( 541062.0 * t + 259.0 ) ) th += 0.0038 * cos( $k * normalization_angle( 1781068.0 * t + 21.0 ) ) th += 0.0040 * cos( $k * normalization_angle( 133.0 * t + 29.0 ) ) th += 0.0040 * cos( $k * normalization_angle( 1844932.0 * t + 56.0 ) ) th += 0.0040 * cos( $k * normalization_angle( 1331734.0 * t + 283.0 ) ) th += 0.0050 * cos( $k * normalization_angle( 481266.0 * t + 205.0 ) ) th += 0.0052 * cos( $k * normalization_angle( 31932.0 * t + 107.0 ) ) th += 0.0068 * cos( $k * normalization_angle( 926533.0 * t + 323.0 ) ) th += 0.0079 * cos( $k * normalization_angle( 449334.0 * t + 188.0 ) ) th += 0.0085 * cos( $k * normalization_angle( 826671.0 * t + 111.0 ) ) th += 0.0100 * cos( $k * normalization_angle( 1431597.0 * t + 315.0 ) ) th += 0.0107 * cos( $k * normalization_angle( 1303870.0 * t + 246.0 ) ) th += 0.0110 * cos( $k * normalization_angle( 489205.0 * t + 142.0 ) ) th += 0.0125 * cos( $k * normalization_angle( 1443603.0 * t + 52.0 ) ) th += 0.0154 * cos( $k * normalization_angle( 75870.0 * t + 41.0 ) ) th += 0.0304 * cos( $k * normalization_angle( 513197.9 * t + 222.5 ) ) th += 0.0347 * cos( $k * normalization_angle( 445267.1 * t + 27.9 ) ) th += 0.0409 * cos( $k * normalization_angle( 441199.8 * t + 47.4 ) ) th += 0.0458 * cos( $k * normalization_angle( 854535.2 * t + 148.2 ) ) th += 0.0533 * cos( $k * normalization_angle( 1367733.1 * t + 280.7 ) ) th += 0.0571 * cos( $k * normalization_angle( 377336.3 * t + 13.2 ) ) th += 0.0588 * cos( $k * normalization_angle( 63863.5 * t + 124.2 ) ) th += 0.1144 * cos( $k * normalization_angle( 966404.0 * t + 276.5 ) ) th += 0.1851 * cos( $k * normalization_angle( 35999.05 * t + 87.53 ) ) th += 0.2136 * cos( $k * normalization_angle( 954397.74 * t + 179.93 ) ) th += 0.6583 * cos( $k * normalization_angle( 890534.22 * t + 145.7 ) ) th += 1.2740 * cos( $k * normalization_angle( 413335.35 * t + 10.74 ) ) th += 6.2888 * cos( $k * normalization_angle( 477198.868 * t + 44.963) ) #----------------------------------------------------------------------- # 比例項の計算 #----------------------------------------------------------------------- ang = normalization_angle( 481267.8809 * t ) ang = normalization_angle( ang + 218.3162 ) th = normalization_angle( th + ang ) return th end #========================================================================= # 年月日、時分秒(世界時)からユリウス日(JD)を計算する # # ※ この関数では、グレゴリオ暦法による年月日から求めるものである。 # (ユリウス暦法による年月日から求める場合には使用できない。) #========================================================================= def ymdt2jd(year, mon, day, hour, min, sec) if mon < 3 year -= 1 mon += 12 end jd = ( 365.25 * year ).to_i jd += ( year / 400.0 ).to_i jd -= ( year / 100.0 ).to_i jd += ( 30.59 * ( mon - 2 ) ).to_i jd += 1721088 jd += day t = sec / 3600.0 t += min / 60.0 t += hour t = t / 24.0 jd += t return jd end #========================================================================= # ユリウス日(JD)から年月日、時分秒(世界時)を計算する # # 戻り値の配列TIME[]の内訳 # TIME[0] ... 年 TIME[1] ... 月 TIME[2] ... 日 # TIME[3] ... 時 TIME[4] ... 分 TIME[5] ... 秒 # # ※ この関数で求めた年月日は、グレゴリオ暦法によって表されている。 # #========================================================================= def jd2ymdt(jd) time = [] x0 = ( jd + 68570.0 ).to_i x1 = ( x0 / 36524.25 ).to_i x2 = x0 - ( 36524.25 * x1 + 0.75 ).to_i x3 = ( ( x2+1 ) / 365.2425 ).to_i x4 = x2 - ( 365.25 * x3 ).to_i + 31.0 x5 = ( x4.to_i / 30.59 ).to_i x6 = ( x5.to_i / 11.0 ).to_i time[2] = x4 - ( 30.59 * x5 ).to_i time[1] = x5 - 12 * x6 + 2 time[0] = 100 * ( x1 - 49 ) + x3 + x6 if time[1] == 2 && time[2] > 28 if time[0] % 100 == 0 && time[0] % 400 == 0 time[2] = 29 elsif time[0] % 4 ==0 time[2]=29 else time[2]=28 end end tm = 86400.0 * ( jd - jd.to_i ) time[3] = ( tm / 3600.0 ).to_i time[4] = ( (tm - 3600.0 * time[3] ) / 60.0 ).to_i time[5] = ( tm - 3600.0 * time[3] - 60 * time[4] ).to_i return time end #========================================================================= # 六曜算出関数 # # 引数  .... 計算対象となる年月日 $year $mon $day # 戻り値 .... 六曜 (大安 赤口 先勝 友引 先負 仏滅) #========================================================================= def get_rokuyou(year, mon, day) rokuyou = %w(大安 赤口 先勝 友引 先負 仏滅) q_yaer, uruu, q_mon, q_day = calc_kyureki(year, mon, day) return rokuyou[ (q_mon + q_day) % 6 ] end #========================================================================= # 今日が24節気かどうか調べる # # 引数  .... 計算対象となる年月日 $year $mon $day # 戻り値 .... 24節気の名称 #========================================================================= def check_24sekki(year, mon, day) #----------------------------------------------------------------------- # 24節気の定義 #----------------------------------------------------------------------- sekki24 = %w(春分 清明 穀雨 立夏 小満 芒種 夏至 小暑 大暑 立秋 処暑 白露 秋分 寒露 霜降 立冬 小雪 大雪 冬至 小寒 大寒 立春 雨水 啓蟄) tm = ymdt2jd(year, mon, day, 0, 0, 0) #----------------------------------------------------------------------- # 時刻引数を分解する #----------------------------------------------------------------------- tm1 = tm.to_i tm2 = tm - tm1 tm2 -= 9.0 / 24.0 t = (tm2 + 0.5) / 36525.0 + (tm1 - 2451545.0) / 36525.0 #今日の太陽の黄経 rm_sun_today = longitude_sun(t) tm += 1 tm1 = tm.to_i tm2 = tm - tm1 tm2 -= 9.0 / 24.0 t = (tm2 + 0.5) / 36525.0 + (tm1 - 2451545.0) / 36525.0 # 明日の太陽の黄経 rm_sun_tommorow = longitude_sun(t) # rm_sun_today0 = 15.0 * (rm_sun_today / 15.0).to_i rm_sun_tommorow0 = 15.0 * (rm_sun_tommorow / 15.0).to_i if rm_sun_today0 != rm_sun_tommorow0 return sekki24[rm_sun_tommorow0 / 15] else return '' end end end <file_sep>class Cms::Admin::Inline::DataFilesController < Cms::Admin::Data::FilesController layout 'admin/files' end <file_sep>module FormHelper ## CKEditor def init_ckeditor(options = {}) settings = [] # リードオンリーではツールバーを表示しない・リンクを動作させる unless (options[:toolbarStartupExpanded] = !options[:readOnly]) settings.push(<<-EOS) CKEDITOR.on('instanceReady', function (e) { $('#'+e.editor.id+'_top').hide(); var links = $('#'+e.editor.id+'_contents > iframe:first').contents().find('a'); for (var i = 0; i < links.length; i++) { $(links[i]).click(function (ee) { location.href = ee.target.href; }); } }); EOS end settings.concat(options.map {|k, v| %Q(CKEDITOR.config.#{k} = #{v.kind_of?(String) ? "'#{v}'" : v};) }) [ '<script type="text/javascript" src="/_common/js/ckeditor/ckeditor.js"></script>', javascript_tag(settings.join) ].join.html_safe end def submission_label(name) { :add => '追加する', :create => '作成する', :register => '登録する', :edit => '編集する', :update => '更新する', :change => '変更する', :delete => '削除する', :make => '作成する' }[name] end def submit(*args) make_tag = Proc.new do |_name, _label| _label ||= submission_label(_name) || _name.to_s.humanize submit_tag _label, :name => "commit_#{_name}" end h = '<div class="submitters">' if args[0].class == String || args[0].class == Symbol h += make_tag.call(args[0], args[1]) elsif args[0].class == Hash args[0].each {|k, v| h += make_tag.call(k, v) } elsif args[0].class == Array args[0].each {|v, k| h += make_tag.call(k, v) } end h += '</div>' h.html_safe end def observe_field(field, params) on = params[:on] ? params[:on].to_s : "change" url = url_for(params[:url]) method = params[:method] ? params[:method].to_s : 'get' with = params[:with] update = params[:update] before = params[:before] data = [] data << "#{with}=' + encodeURIComponent($('##{field}').val()) + '" if with data << "authenticity_token=' + encodeURIComponent('#{form_authenticity_token}') + '" if method == 'post' data = data.join('&') h = '<script type="text/javascript">' + "\n//<![CDATA[\n" h += "$(function() {" h += "$('##{field}').bind('#{on}', function() {" h += "#{before};" if before h += "jQuery.ajax({" h += "data:'#{data}'," h += "url:'#{url}'," h += "success:function(response){ $('##{update}').html(response) }" h += "})" h += "})" h += "});" h += "\n//]]>\n</script>" h.html_safe end end <file_sep>module Cms::Model::Rel::Site extend ActiveSupport::Concern included do has_one :site, primary_key: :site_id, foreign_key: :id, class_name: 'Cms::Site' end end <file_sep>module Reception::CourseHelper def course_replace(course, doc_style, datetime_style) contents = { title: -> { course_replace_title(course) }, subtitle: -> { course_replace_subtitle(course) }, summary: -> { course_replace_summary(course) }, total_number: -> { course_replace_total_number(course) }, charge: -> { course_replace_charge(course) }, remarks: -> { course_replace_remarks(course) }, hold_date: -> { course_replace_hold_date(course, datetime_style) }, place: -> { course_replace_place(course) }, name: -> { course_replace_name(course) }, link: -> { course_replace_link(course) }, category: -> { course_replace_category(course) }, } if Page.mobile? contents[:link].call else doc_style = doc_style.gsub(/@(\w+)@/) { |m| contents[$1.to_sym].try(:call).to_s } doc_style.html_safe end end private def course_replace_title(course) if course.title.present? content_tag(:span, course.title, class: 'title') end end def course_replace_subtitle(course) if course.subtitle.present? content_tag(:span, course.subtitle, class: 'subtitle') end end def course_replace_summary(course) if course.body.present? content_tag(:span, course.body.html_safe, class: 'summary') end end def course_replace_total_number(course) if course.capacity.present? content_tag(:span, course.capacity, class: 'total_number') end end def course_replace_charge(course) if course.fee.present? content_tag(:span, course.fee, class: 'charge') end end def course_replace_remarks(course) if course.remark.present? content_tag(:span, course.remark.html_safe, class: 'remarks') end end def course_replace_hold_date(course, datetime_style) open = course.public_opens.select(&:applicable?).first || course.public_opens.last if open && open.open_on ds = localize_wday(datetime_style, open.open_on.wday) content_tag(:span, open.open_on_start_at.strftime(ds), class: 'hold_date') end end def course_replace_place(course) open = course.public_opens.select(&:applicable?).first if open && open.place.present? content_tag(:span, open.place, class: 'place') end end def course_replace_name(course) open = course.public_opens.select(&:applicable?).first if open && open.lecturer.present? content_tag(:span, open.lecturer, class: 'name') end end def course_replace_link(course) link = link_to(course.title, course.public_uri) if link.present? content_tag(:span, link, class: 'link') end end def course_replace_category(course) categories = course.categories if categories.present? category_text = categories.map { |c| content_tag(:span, c.title, class: "#{c.category_type.name}-#{c.ancestors.map(&:name).join('-')}") }.join.html_safe content_tag(:span, category_text, class: 'category') end end end <file_sep>class Rank::Public::Piece::RanksController < Sys::Controller::Public::Base include Rank::Controller::Rank def pre_dispatch @piece = Rank::Piece::Rank.find_by(id: Page.current_piece.id) render plain: '' unless @piece end def index render plain: '' and return if @piece.ranking_target.blank? || @piece.ranking_term.blank? @term = @piece.ranking_term @target = @piece.ranking_target @ranks = rank_datas(@piece.content, @term, @target, @piece.display_count, @piece.category_option) render plain: '' if @ranks.empty? end end <file_sep>module GpCalendar::EventHelper def event_replace(event, list_style) link_to_options = if event.href.present? [event.href, target: event.target] else nil end list_style.gsub(/@\w+@/, { '@title_link@' => event_replace_title_link(event, link_to_options), '@title@' => event_replace_title(event), '@category@' => event_replace_category(event) }).html_safe end def event_table_replace(event, table_style, options={}) @content = event.content date_style = options && options[:date_style] ? options[:date_style] : @content.date_style link_to_options = if event.href.present? [event.href, target: event.target] else nil end contents = { title_link: -> { event_replace_title_link(event, link_to_options) }, title: -> { event_replace_title(event) }, subtitle: -> { event_replace_subtitle(event) }, hold_date: -> { event_replace_hold_date(event, date_style) }, summary: -> { event_replace_summary(event) }, unit: -> { event_replace_unit(event) }, category: -> { event_replace_category(event) }, image_link: -> { event_replace_image_link(event, link_to_options) }, image: -> { event_replace_image(event) }, note: -> {event_replace_note(event)} } tags = [] list_style = content_tag(:tr) do table_style.each do |t| if t[:data] =~ %r|hold_date| class_str = 'date' class_str += ' holiday' if event.holiday.present? if @date && event.started_on.month == @date.month concat content_tag(:td, t[:data].html_safe, class: class_str, id: 'day%02d' % event.started_on.day) else concat content_tag(:td, t[:data].html_safe, class: class_str) end else class_str = t[:data].delete("@") concat content_tag(:td, t[:data].html_safe, class: class_str) end end end list_style = list_style.gsub(/@event{{@(.+)@}}event@/m){|m| link_to($1.html_safe, link_to_options[0], class: 'event_link') } list_style = list_style.gsub(/@category_type_(.+?)@/){|m| event_replace_category_type(event, $1) } list_style = list_style.gsub(/@(\w+)@/) {|m| contents[$1.to_sym] ? contents[$1.to_sym].call : '' } list_style.html_safe end private def event_replace_title(event) content_tag(:span, event.title) end def event_replace_title_link(event, link_to_options) event_title = if link_to_options link_to *([event.title] + link_to_options) else h event.title end content_tag(:span, event_title) end def event_replace_subtitle(event) if doc = event.doc content_tag(:span, doc.subtitle) else '' end end def event_replace_hold_date(event, date_style) render 'gp_calendar/public/shared/event_date', event: event, date_style: date_style, holiday_disp: true end def event_replace_summary(event) content_tag(:span, hbr(event.description)) end def event_replace_unit(event) if doc = event.doc content_tag(:span, doc.creator.group.try(:name)) else content_tag(:span, event.creator.group.try(:name)) end end def event_replace_category(event) replace_cateogry(event, event.categories) end def event_replace_category_type(event, category_type_name) category_type = GpCategory::CategoryType .where(content_id: event.content.category_content_id, name: category_type_name).first if category_type category_ids = event.categories.map{|c| c.id } categories = GpCategory::Category.where(category_type_id: category_type, id: category_ids) replace_cateogry(event, categories, category_type) else nil end end def replace_cateogry(event, categories, category_type = nil) if categories.present? category_tag = ""; categories.each do |category| category_tag += content_tag(:span, category.title, class: category.name) end category_tag else '' end end def event_replace_image_link(event, link_to_options) image_tag = event_image_tag(event) image_link = if image_tag.present? if link_to_options link_to *([image_tag] + link_to_options) else image_tag end else image_tag end if image_link.present? content_tag(:span, image_link) else '' end end def event_replace_image(event) image_tag = event_image_tag(event) if image_tag.present? content_tag(:span, image_tag) else '' end end def event_image_tag(event) ei = event_image(event) ei.blank? ? '' : ei end def event_image(event) if (doc = event.doc) doc_image_tag(doc) elsif (f = event.image_files.first) image_tag("#{f.parent.content.public_node.public_uri}#{f.parent.name}/file_contents/#{url_encode f.name}", alt: f.title, title: f.title) elsif event.content.default_image.present? image_tag(event.content.default_image) end end def event_replace_note(event) if doc = event.doc content_tag(:span, hbr(doc.event_note)) else content_tag(:span, hbr(event.note)) end end end <file_sep>module Map::MapHelper def default_lat_lng if @content.default_map_position.blank? if @markers.empty? [0, 0] else [@markers.first.latitude, @markers.first.longitude] end else @content.default_map_position end end def default_latitude default_lat_lng.first end def default_longitude default_lat_lng.last end def marker_image(marker) unless (doc = marker.doc) file = marker.files.first return '' unless file.parent.content.public_node return image_tag("#{file.parent.content.public_node.public_uri}#{file.parent.name}/file_contents/#{url_encode file.name}") else return '' unless doc.content.public_node end image_file = doc.image_files.detect{|f| f.name == doc.list_image } || doc.image_files.first if doc.list_image.present? if image_file image_tag("#{doc.content.public_node.public_uri}#{doc.name}/file_contents/#{url_encode image_file.name}") else unless (img_tags = Nokogiri::HTML.parse(doc.body).css('img[src^="file_contents/"]')).empty? filename = File.basename(img_tags.first.attributes['src'].value) image_tag("#{doc.content.public_node.public_uri}#{doc.name}/file_contents/#{url_encode filename}") else '' end end end def title_replace(doc, doc_style) return unless doc contents = { title_link: content_tag(:span, link_to(doc.title, doc.public_uri), class: 'title_link'), title: content_tag(:span, doc.title, class: 'title'), subtitle: content_tag(:span, doc.subtitle, class: 'subtitle'), summary: doc.summary, } if Page.mobile? contents[:title_link] else doc_style.gsub(/@\w+@/, { '@title_link@' => contents[:title_link], '@title@' => contents[:title], '@subtitle@' => contents[:subtitle], '@summary@' => contents[:summary], }).html_safe end end end <file_sep>module GpCalendar::GpCalendarHelper def localize_wday(style, wday) style.gsub('%A', t('date.day_names')[wday]).gsub('%a', t('date.abbr_day_names')[wday]) end def nodes_for_search_events(nodes) nodes.select {|n| %w!GpCalendar::SearchEvent!.include?(n.model) } end def nodes_for_category_types(nodes) nodes.select {|n| %w!GpCalendar::Event GpCalendar::CalendarStyledEvent!.include?(n.model) } end def nodes_for_daily_links(nodes) nodes_for_category_types(nodes) end def nodes_for_monthly_links(nodes) nodes_for_category_types(nodes) end def event_images(event, count: 0) unless (doc = event.doc) count = (count > 0 ? count : event.files.size) return event.files[0...count].map{|f| image_tag("#{f.parent.content.public_node.public_uri}#{f.parent.name}/file_contents/#{url_encode f.name}") }.join.html_safe end srcs = [] if doc.list_image.present? file = doc.image_files.detect{|f| f.name == doc.list_image } || doc.image_files.first srcs << image_tag("#{doc.content.public_node.public_uri}#{doc.name}/file_contents/#{url_encode file.name}") end Nokogiri::HTML.parse(doc.body).css('img[src^="file_contents/"]').each do |img| break if count > 0 && srcs.size >= count filename = File.basename(img.attributes['src'].value) srcs << image_tag("#{doc.content.public_node.public_uri}#{doc.name}/file_contents/#{url_encode filename}") end srcs.join.html_safe end end <file_sep>class ApplicationController < ActionController::Base include Cms::Controller::Public helper FormHelper helper LinkHelper protect_from_forgery with: :exception before_action :initialize_application # rescue_from Exception, :with => :rescue_exception def initialize_application if Core.publish Page.mobile = false Page.smart_phone = false else Page.mobile = true if request.mobile? Page.smart_phone = true if request.smart_phone? request_as_mobile if Page.mobile? && !request.mobile? request_as_smart_phone if Page.smart_phone? && !request.smart_phone? end return false if Core.dispatched? return Core.dispatched end def query(params = nil) Util::Http::QueryString.get_query(params) end def send_mail(fr_addr, to_addr, subject, body) return false if fr_addr.blank? || to_addr.blank? CommonMailer.plain(from: fr_addr, to: to_addr, subject: subject, body: body).deliver_now end def send_download # end def send_data(data, options = {}) options = set_default_file_options(options) super end def send_file(path, options = {}) options = set_default_file_options(options) super end private def set_default_file_options(options) if options.include?(:filename) options[:filename] = URI::escape(options[:filename]) if request.user_agent =~ /(MSIE|Trident)/ options[:type] ||= Rack::Mime.mime_type(File.extname(options[:filename])) options[:disposition] ||= detect_disposition_from_mime(options[:type]) end options end def detect_disposition_from_mime(mime_type) if request.user_agent =~ /Android/ 'attachment' elsif mime_type.to_s =~ %r!\Aimage/|\Aapplication/pdf\z! 'inline' else 'attachment' end end def rescue_action(error) case error when ActionController::InvalidAuthenticityToken http_error(422, "Invalid Authenticity Token") else super end end ## Production && local def rescue_action_in_public(exception) http_error(500, nil) end def http_error(status, message = nil) self.response_body = nil Page.error = status if status == 404 message ||= "ページが見つかりません。" end name = Rack::Utils::HTTP_STATUS_CODES[status] name = " #{name}" if name message = " ( #{message} )" if message message = "#{status}#{name}#{message}" mode_regexp = Regexp.new("^(#{ZomekiCMS::ADMIN_URL_PREFIX.sub(/^_/, '')}|script)$") if Core.mode =~ mode_regexp && status != 404 error_log("#{status} #{request.env['REQUEST_URI']}") if status != 404 return render status: status, html: "<p>#{message}</p>".html_safe, layout: "admin/cms/error" # return respond_to do |format| # format.html { render :status => status, :text => "<p>#{message}</p>", :layout => "admin/cms/error" } # format.xml { render :status => status, :xml => "<errors><error>#{message}</error></errors>" } # end end ## Render html = nil if Page.mobile file_status = "#{status}_mobile.html" file_500 = "500_mobile.html" else file_status = "#{status}.html" file_500 = "500.html" end if Page.site && FileTest.exist?("#{Page.site.public_path}/#{file_status}") html = ::File.new("#{Page.site.public_path}/#{file_status}").read elsif Core.site && FileTest.exist?("#{Core.site.public_path}/#{file_status}") html = ::File.new("#{Core.site.public_path}/#{file_status}").read elsif FileTest.exist?("#{Rails.public_path}/#{file_status}") html = ::File.new("#{Rails.public_path}/#{file_status}").read elsif FileTest.exist?("#{Rails.public_path}/#{file_500}") html = ::File.new("#{Rails.public_path}/#{file_500}").read else html = "<html>\n<head></head>\n<body>\n<p>#{message}</p>\n</body>\n</html>\n" end if Core.mode == 'ssl' replacer = Cms::Lib::SslLinkReplacer.new html = replacer.run(html, site: Page.site, current_path: Page.current_node.public_uri) end render :status => status, :inline => html # return respond_to do |format| # format.html { render :status => status, :inline => html } # format.xml { render :status => status, :xml => "<errors><error>#{message}</error></errors>" } # end end # def rescue_exception(exception) # log = exception.to_s # log += "\n" + exception.backtrace.join("\n") if Rails.env.to_s == 'production' # error_log(log) # # if Core.mode =~ /^(admin|script)$/ # html = %Q(<div style="padding: 0px 20px 10px; color: #e00; font-weight: bold; line-height: 1.8;">) # html += %Q(エラーが発生しました。<br />#{exception} &lt;#{exception.class}&gt;) # html += %Q(</div>) # if Rails.env.to_s != 'production' # html += %Q(<div style="padding: 15px 20px; border-top: 1px solid #ccc; color: #800; line-height: 1.4;">) # html += exception.backtrace.join("<br />") # html += %Q(</div>) # end # render :inline => html, :layout => "admin/cms/error", :status => 500 # else # http_error 500 # end # end def request_as_mobile user_agent = 'DoCoMo/2.0 ISIM0808(c500;TB;W24H16)' request.env['rack.jpmobile'] = Jpmobile::Mobile::AbstractMobile.carrier('HTTP_USER_AGENT' => user_agent) end def request_as_smart_phone user_agent = 'Mozilla/5.0 (iPhone; U; CPU iPhone OS 2_0_1 like Mac OS X; ja-jp) AppleWebKit/525.18.1 (KHTML, like Gecko) Version/3.1.1 Mobile/5B108 Safari/525.20' request.env['rack.jpmobile'] = Jpmobile::Mobile::AbstractMobile.carrier('HTTP_USER_AGENT' => user_agent) end end <file_sep>class Rank::Public::Api::Piece::RanksController < Cms::Controller::Public::Api include Rank::Controller::Rank def pre_dispatch return http_error(405) unless request.get? return http_error(404) unless params[:version] == '20150401' end def index piece = Rank::Piece::Rank.where(id: params[:piece_id]).first return render(json: {}) unless piece current_item = rank_current_item(params[:current_item_class], params[:current_item_id]) return render(json: {}) unless current_item term = piece.ranking_term target = piece.ranking_target ranks = rank_datas(piece.content, term, target, piece.display_count, piece.category_option, nil, nil, nil, current_item) result = {} result[:ranks] = ranks.map do |rank| {title: rank.page_title, url: "#{request.scheme}://#{rank.hostname}#{rank.page_path}", count: piece.show_count == 0 ? nil : rank.accesses} end result[:more] = if (body = piece.more_link_body).present? && (url = piece.more_link_url).present? {body: body, url: url} end render json: result end private def rank_current_item(current_item_class, current_item_id) if current_item_class.in?(%w(GpCategory::CategoryType GpCategory::Category)) current_item_class.constantize.find_by(id: current_item_id) else nil end end end <file_sep># Use this file to easily define all of your cron jobs. # # It's helpful, but not entirely necessary to understand cron before proceeding. # http://en.wikipedia.org/wiki/Cron # Example: # # set :output, "/path/to/my/cron_log.log" # # every 2.hours do # command "/usr/bin/some_great_command" # runner "MyModel.some_method" # rake "some:great:rake:task" # end # # every 4.days do # runner "AnotherModel.prune_old_records" # end # Learn more: http://github.com/javan/whenever # set :environment, 'development' set :output, nil env :PATH, ENV['PATH'] # 音声ファイルを静的ファイルとして書き出します。 every '6-51/15 * * * *' do rake 'zomeki:cms:talks:exec' end # アンケートの回答データを取り込みます。 every '9-54/15 * * * *' do rake 'zomeki:survey:answers:pull' end # 広告バナーのクリック数を取り込みます。 every '12-57/15 * * * *' do rake 'zomeki:ad_banner:clicks:pull' end # サイトの設定を定期的に更新します。 every '25,55 * * * *' do rake 'zomeki:cms:sites:update_server_configs' end # delayed_jobプロセスを監視します。 every '26,56 * * * *' do rake 'delayed_job:monitor' end # Feedコンテンツで設定したRSS・Atomフィードを取り込みます。 every :hour do rake 'zomeki:feed:feeds:read' end # リンクチェックを実行します。 every :hour do rake 'zomeki:cms:link_checks:exec' end # 今日のイベントページを静的ファイルとして書き出します。 every :day, at: '0:30 am' do rake 'zomeki:gp_calendar:publish_todays_events' end # 今月の業務カレンダーを静的ファイルとして書き出します。 every :month, at: 'start of the month at 3:00 am' do rake 'zomeki:biz_calendar:publish_this_month' end # アクセスランキングデータを取り込みます。 every :day, at: '3:00 am' do rake 'zomeki:rank:ranks:exec' end # 不要データを削除します。 every :day, at: '2:00 am' do rake 'zomeki:sys:cleanup' end <file_sep>class Sys::Model::Base::Setting < ApplicationRecord self.table_name = "sys_settings" def self.set_config(id, params = {}) @@configs ||= {} @@configs[self] ||= [] @@configs[self] << params.merge(:id => id) end def self.configs @@configs[self].collect {|c| config(c[:id])} end def self.config(name) find_or_initialize_by(name: name) end def self.value(name, default_value = nil) st = config(name) return nil unless st return st.value.blank? ? default_value || st.default_value : st.value end def editable? true end def config return @config if @config @@configs[self.class].each {|c| return @config = c if c[:id].to_s == name.to_s} nil end def config_name config ? config[:name] : nil end def config_options config[:options] ? config[:options].collect {|e| [e[0], e[1].to_s] } : nil end def style config[:style] ? config[:style] : nil end def upper_text config[:upper_text] ? config[:upper_text] : nil end def lower_text config[:lower_text] ? config[:lower_text] : nil end def default_value config[:default] ? config[:default] : nil end def value_name if config[:options] config[:options].each {|c| return c[0] if c[1].to_s == value.to_s} else return value if !value.blank? end nil end def form_type return config[:form_type] if config[:form_type] config_options ? :select : :string end def extra_values=(ev) self.extra_value = YAML.dump(ev) if ev.is_a?(Hash) return ev end def extra_values ev_string = self.extra_value ev = ev_string.kind_of?(String) ? YAML.load(ev_string) : {}.with_indifferent_access ev = {}.with_indifferent_access unless ev.kind_of?(Hash) ev = ev.with_indifferent_access unless ev.kind_of?(ActiveSupport::HashWithIndifferentAccess) if block_given? yield ev self.extra_values = ev end return ev end def self.setting_extra_values(name) self.config(name).try(:extra_values) || {}.with_indifferent_access end def self.setting_extra_value(name, extra_name) self.setting_extra_values(name)[extra_name] end end <file_sep># Read about factories at https://github.com/thoughtbot/factory_girl FactoryGirl.define do factory :valid_o_auth_user, :class => 'Cms::OAuthUser' do provider 'provider' uid '1234567890' name '<NAME>' image 'http://example.com/images/yamada.jpg' end end <file_sep>class Cms::Tool::PagesScript < Cms::Script::Base include Cms::Controller::Layout def rebuild nodes = Cms::Node.where(id: params[:node_id]) ::Script.total nodes.size nodes.each do |node| ::Script.progress(node) do page = Cms::Node::Page.find(node.id) if page.rebuild(render_public_as_string(page.public_uri, site: node.site)) page.publish_page(render_public_as_string("#{page.public_uri}.r", site: node.site), path: "#{page.public_path}.r", dependent: :ruby) page.rebuild(render_public_as_string(page.public_uri, site: node.site, agent_type: :smart_phone), path: page.public_smart_phone_path, dependent: :smart_phone) end end end end end <file_sep>class GpCategory::Publisher::CategoryCallbacks < PublisherCallbacks def after_save(category) @category = category enqueue if enqueue? end def before_destroy(category) @category = category enqueue if enqueue? end def enqueue(category = nil) @category = category if category enqueue_pieces enqueue_categories enqueue_docs enqueue_sitemap_nodes end private def enqueue? [@category.state, @category.state_was].include?('public') end def enqueue_pieces pieces = @category.content.public_pieces.sort { |p| p.model == 'GpCategory::RecentTab' ? 1 : 9 } pieces.each do |piece| Cms::Publisher::PieceCallbacks.new.enqueue(piece) end end def enqueue_categories Cms::Publisher.register(@category.content.site_id, @category.public_ancestors) end def enqueue_docs docs = @category.public_descendants.flat_map { |c| c.docs.public_state.select(:id) } Cms::Publisher.register(@category.content.site_id, docs) end def enqueue_sitemap_nodes if [@category.sitemap_state, @category.sitemap_state_was].include?('visible') site = @category.content.site Cms::Publisher.register(site.id, site.public_sitemap_nodes) end end end <file_sep>namespace :zomeki do namespace :survey do namespace :answers do desc 'Fetch survey answers' task :pull => :environment do next if ApplicationRecordSlave.slave_configs.blank? Cms::Site.order(:id).pluck(:id).each do |site_id| Script.run('survey/answers/pull', site_id: site_id, lock_by: :site) end end end end end <file_sep>module Cms::Model::Rel::Link extend ActiveSupport::Concern included do has_many :links, class_name: 'Cms::Link', dependent: :destroy, as: :linkable after_save :save_links end def save_links lib = links_in_body links.each do |link| link.destroy unless lib.detect {|l| l[:body] == link.body && l[:url] == link.url } end lib.each do |link| links.create(body: link[:body], url: link[:url], content_id: content_id) unless links.where(body: link[:body], url: link[:url]).first end end end <file_sep>module GpCategory::GpCategoryHelper def public_docs_with_category_id(category_id) GpArticle::Doc.categorized_into(category_id).except(:order).mobile(::Page.mobile?).public_state end def category_module_more_link(template_module: nil, ct_or_c: nil, category_name: nil, group_code: nil) file = "more@#{template_module.name}" file << "@c_#{category_name}" if category_name.present? file << "@g_#{group_code}" if group_code.present? "#{ct_or_c.public_uri}#{file}.html" end def category_li(category, depth_limit: 1000, depth: 1) content_tag(:li) do result = link_to(category.title, category.public_uri) if category.public_children.empty? || depth >= depth_limit result else result << content_tag(:ul) do category.public_children.inject(''){|lis, child| lis << category_li(child, depth_limit: depth_limit, depth: depth + 1) }.html_safe end end end end def category_summary_li(category, depth_limit: 1000, depth: 1) content_tag(:li) do title_tag = content_tag(:span, category.title) title_tag << content_tag(:span, category.description, class: 'category_summary') if category.description.present? result = link_to(title_tag, category.public_uri) if category.public_children.empty? || depth >= depth_limit result else result << content_tag(:ul) do category.public_children.inject(''){|lis, child| lis << category_summary_li(child, depth_limit: depth_limit, depth: depth + 1) }.html_safe end end end end def categories_1(template_module: nil, categories: nil) return if categories.empty? content_tag(:ul) do categories.inject(''){|lis, child| lis << category_li(child) }.html_safe end end def categories_2(template_module: nil, categories: nil) end def categories_3(template_module: nil, categories: nil) return if categories.empty? content_tag(:ul) do categories.inject(''){|lis, child| lis << category_li(child, depth_limit: 1) }.html_safe end end def categories_summary_1(template_module: nil, categories: nil) return if categories.empty? content_tag(:ul) do categories.inject(''){|lis, child| lis << category_summary_li(child) }.html_safe end end def categories_summary_2(template_module: nil, categories: nil) end def categories_summary_3(template_module: nil, categories: nil) return if categories.empty? content_tag(:ul) do categories.inject(''){|lis, child| lis << category_summary_li(child, depth_limit: 1) }.html_safe end end def docs_1(template_module: nil, ct_or_c: nil, docs: nil, all_docs: nil) return '' if docs.empty? content = lambda{ html = docs.inject(''){|tags, doc| tags << content_tag(template_module.wrapper_tag) do doc_replace(doc, template_module.doc_style, @content.date_style, @content.time_style) end }.html_safe html = content_tag(:ul, html) if template_module.wrapper_tag == 'li' if ct_or_c && docs.count < all_docs.count html << content_tag(:div, link_to('一覧へ', category_module_more_link(template_module: template_module, ct_or_c: ct_or_c)), class: 'more') else html end }.call return '' if content.blank? content_tag(:section, "#{template_module.upper_text}#{content}#{template_module.lower_text}".html_safe, class: template_module.name) end def docs_2(template_module: nil, ct_or_c: nil, docs: nil, all_docs: nil) docs_1(template_module: template_module, ct_or_c: ct_or_c, docs: docs, all_docs: all_docs) end def docs_3(template_module: nil, ct_or_c: nil, categories: nil, categorizations: nil) return '' if categorizations.empty? content = categories.inject(''){|tags, category| inner_content = lambda{ cats = categorizations.where(category_id: category.public_descendants.map(&:id)) next if cats.empty? docs_order = case @content.docs_order when 'published_at_desc' 'display_published_at DESC, published_at DESC' when 'published_at_asc' 'display_published_at ASC, published_at ASC' when 'updated_at_desc' 'display_updated_at DESC, updated_at DESC' when 'updated_at_asc' 'display_updated_at ASC, updated_at ASC' else 'display_published_at DESC, published_at DESC' end docs = cats.first.categorizable_type.constantize.where(id: cats.pluck(:categorizable_id)) .limit(template_module.num_docs).order(docs_order) html = content_tag(:h2, category.title) doc_tags = docs.inject(''){|t, d| t << content_tag(template_module.wrapper_tag, doc_replace(d, template_module.doc_style, @content.date_style, @content.time_style)) }.html_safe doc_tags = content_tag(:ul, doc_tags) if template_module.wrapper_tag == 'li' html << doc_tags html << content_tag(:div, link_to('一覧へ', category_module_more_link(template_module: template_module, ct_or_c: ct_or_c, category_name: category.name)), class: 'more') }.call if inner_content.present? tags << content_tag(:section, "#{template_module.upper_text}#{inner_content}#{template_module.lower_text}".html_safe, class: category.name) else tags end } return '' if content.blank? content_tag(:section, content.html_safe, class: template_module.name) end def docs_4(template_module: nil, ct_or_c: nil, categories: nil, categorizations: nil) docs_3(template_module: template_module, ct_or_c: ct_or_c, categories: categories, categorizations: categorizations) end def docs_5(template_module: nil, ct_or_c: nil, groups: nil, docs: nil) return '' if docs.empty? docs_order = case @content.docs_order when 'published_at_desc' 'display_published_at DESC, published_at DESC' when 'published_at_asc' 'display_published_at ASC, published_at ASC' when 'updated_at_desc' 'display_updated_at DESC, updated_at DESC' when 'updated_at_asc' 'display_updated_at ASC, updated_at ASC' else 'display_published_at DESC, published_at DESC' end content = groups.inject(''){|tags, group| tags << content_tag(:section, class: group.code) do group_docs = docs.where(Sys::Group.arel_table[:id].eq(group.id)) .limit(template_module.num_docs).order(docs_order) html = content_tag(:h2, group.name) doc_tags = group_docs.inject(''){|t, d| t << content_tag(template_module.wrapper_tag, doc_replace(d, template_module.doc_style, @content.date_style, @content.time_style)) }.html_safe doc_tags = content_tag(:ul, doc_tags) if template_module.wrapper_tag == 'li' html << doc_tags html << content_tag(:div, link_to('一覧へ', category_module_more_link(template_module: template_module, ct_or_c: ct_or_c, group_code: group.code)), class: 'more') end } return '' if content.blank? content_tag(:section, "#{template_module.upper_text}#{content}#{template_module.lower_text}".html_safe, class: template_module.name) end def docs_6(template_module: nil, ct_or_c: nil, groups: nil, docs: nil) docs_5(template_module: template_module, ct_or_c: ct_or_c, groups: groups, docs: docs) end def docs_7(template_module: nil, categories: nil, categorizations: nil) return '' if categorizations.empty? docs_order = case @content.docs_order when 'published_at_desc' 'display_published_at DESC, published_at DESC' when 'published_at_asc' 'display_published_at ASC, published_at ASC' when 'updated_at_desc' 'display_updated_at DESC, updated_at DESC' when 'updated_at_asc' 'display_updated_at ASC, updated_at ASC' else 'display_published_at DESC, published_at DESC' end content = categories.inject(''){|tags, category| tags << category_section(category, template_module: template_module, categorizations: categorizations, with_child_categories: false, docs_order: docs_order) } return '' if content.blank? content_tag(:section, "#{template_module.upper_text}#{content}#{template_module.lower_text}".html_safe, class: template_module.name) end def docs_8(template_module: nil, categories: nil, categorizations: nil) return '' if categorizations.empty? docs_order = case @content.docs_order when 'published_at_desc' 'display_published_at DESC, published_at DESC' when 'published_at_asc' 'display_published_at ASC, published_at ASC' when 'updated_at_desc' 'display_updated_at DESC, updated_at DESC' when 'updated_at_asc' 'display_updated_at ASC, updated_at ASC' else 'display_published_at DESC, published_at DESC' end content = categories.inject(''){|tags, category| tags << category_section(category, template_module: template_module, categorizations: categorizations, with_child_categories: true, docs_order: docs_order) } return '' if content.blank? content_tag(:section, "#{template_module.upper_text}#{content}#{template_module.lower_text}".html_safe, class: template_module.name) end def category_section(category, template_module: nil, categorizations: nil, with_child_categories: nil, docs_order: nil) content = lambda{ cats = categorizations.where(category_id: category.public_descendants.map(&:id)) next if cats.empty? all_docs = cats.first.categorizable_type.constantize.where(id: cats.pluck(:categorizable_id)) .order(docs_order) docs = all_docs.limit(template_module.num_docs) html = content_tag(:h2, category.title) doc_tags = docs.inject(''){|t, d| t << content_tag(template_module.wrapper_tag, doc_replace(d, template_module.doc_style, @content.date_style, @content.time_style)) }.html_safe doc_tags = content_tag(:ul, doc_tags) if template_module.wrapper_tag == 'li' html << doc_tags if with_child_categories && category.children.present? html << content_tag(:section) do content_tag(:ul) do category.children.inject(''){|tags, child| tags << content_tag(:li, link_to(child.title, child.public_uri)) }.html_safe end end end if all_docs.count > template_module.num_docs html << content_tag(:div, link_to('一覧へ', category.public_uri), class: 'more') else html end }.call return '' if content.blank? content_tag(:section, content, class: category.name) end end <file_sep>class Cms::SiteSetting::FileTransfer < Cms::SiteSetting validates :value, uniqueness: { scope: :name } end <file_sep>class Map::MarkersScript < Cms::Script::Publication def publish publish_more(@node, uri: @node.public_uri, path: @node.public_path, smart_phone_path: @node.public_smart_phone_path, dependent: 'more') @node.content.public_categories.each do |top_category| top_category.public_descendants.each do |category| escaped_category = "#{category.category_type.name}/#{category.path_from_root_category}".gsub('/', '@') file = "index_#{escaped_category}" publish_more(@node, uri: @node.public_uri, file: file, path: @node.public_path, smart_phone_path: @node.public_smart_phone_path, dependent: "more_#{file}") end end @node.content.public_markers.each do |marker| file = marker.files.first next unless file && ::File.exist?(file.upload_path) Util::File.put marker.public_file_path, src: file.upload_path, mkdir: true if @node.content.site.publish_for_smart_phone? Util::File.put marker.public_smart_phone_file_path, src: file.upload_path, mkdir: true end end end end <file_sep>module GpArticle::Docs::Preload extend ActiveSupport::Concern module ClassMethods def creator_assocs { creator: { group: nil, user: nil } } end def public_index_assocs creator_assocs end def public_node_ancestors_assocs { content: { public_node: { site: nil, parent: parent_assocs } } } end def organization_groups_and_public_node_ancestors_assocs #{ content: { organization_content_group: { groups: organization_group_assocs } } } {} end private def parent_assocs(depth = 3) return nil if depth < 0 { parent: parent_assocs(depth - 1) } end def organization_group_assocs { content: { public_node: { site: nil, parent: parent_assocs } }, parent: parent_assocs } end end end <file_sep>module Sys::Model::Slave extend ActiveSupport::Concern included do self.table_name = self.to_s.underscore.sub('/slave/', '/').gsub('/', '_').downcase.pluralize end end <file_sep>namespace :zomeki do namespace :cms do desc 'Clean static files' task :clean_statics => :environment do Cms::Lib::FileCleaner.clean_files end desc 'Clean empty directories' task :clean_directories => :environment do Cms::Lib::FileCleaner.clean_directories end namespace :link_checks do desc 'Check links' task :exec => :environment do Cms::Site.order(:id).each do |site| if site.link_check_hour?(Time.now.hour) system("bundle exec rake zomeki:cms:link_checks:exec_site SITE_ID=#{site.id} RAILS_ENV=#{Rails.env} &") end end end desc 'Check links in specified site' task :exec_site => :environment do site = Cms::Site.find_by(id: ENV['SITE_ID']) Script.run('cms/link_checks/exec', site_id: site.id, lock_by: :site, kill: 12.hours.to_i) if site end end namespace :nodes do desc 'Publish nodes' task :publish => :environment do Cms::Site.order(:id).pluck(:id).each do |site_id| Script.run('cms/nodes/publish', site_id: site_id, lock_by: :site) end end end namespace :talks do desc 'Exec talk tasks' task :exec => :environment do Cms::Site.order(:id).pluck(:id).each do |site_id| Script.run('cms/talk_tasks/exec', site_id: site_id, lock_by: :global) end end end namespace :sites do desc 'Update server configs' task :update_server_configs => :environment do Rails::Generators.invoke('cms:nginx:site_config', ['--force']) Rails::Generators.invoke('cms:apache:site_config', ['--force']) end end namespace :data_files do desc 'Rebuild data files' task :rebuild => :environment do Cms::DataFile.where(state: 'public').find_each do |item| item.upload_public_file end end end namespace :brackets do desc 'Rebuild brackets' task :rebuild => :environment do [Cms::Layout, Cms::Node, Cms::Piece, GpArticle::Doc].each do |model| model.find_each do |item| item.save_brackets end end end end namespace :links do desc 'Rebuild links' task :rebuild => :environment do [Cms::Node::Page, GpArticle::Doc].each do |model| model.find_each do |item| item.save_links end end end end namespace :publish_urls do desc 'Rebuild publish urls' task :rebuild => :environment do Cms::Node::Page.public_state.find_each(&:set_public_name) GpArticle::Doc.public_state.find_each(&:set_public_name) end end end end <file_sep>class GpCalendar::Content::Event < Cms::Content default_scope { where(model: 'GpCalendar::Event') } has_one :public_node, -> { public_state.order(:id) }, foreign_key: :content_id, class_name: 'Cms::Node' has_many :settings, -> { order(:sort_no) }, foreign_key: :content_id, class_name: 'GpCalendar::Content::Setting', dependent: :destroy has_many :events, foreign_key: :content_id, class_name: 'GpCalendar::Event', dependent: :destroy has_many :holidays, foreign_key: :content_id, class_name: 'GpCalendar::Holiday', dependent: :destroy after_create :create_default_holidays def public_events events.public_state end def public_holidays holidays.public_state end def category_content_id setting_value(:gp_category_content_category_type_id).to_i end def categories setting = GpCalendar::Content::Setting.find_by(id: settings.find_by(name: 'gp_category_content_category_type_id').try(:id)) return GpCategory::Category.none unless setting setting.categories end def categories_for_option categories.map {|c| [c.title, c.id] } end def public_categories categories.public_state end def category_types setting = GpCalendar::Content::Setting.find_by(id: settings.find_by(name: 'gp_category_content_category_type_id').try(:id)) return GpCategory::CategoryType.none unless setting setting.category_types end def category_type_categories(category_type) category_type_id = (category_type.kind_of?(GpCategory::CategoryType) ? category_type.id : category_type.to_i ) categories.select {|c| c.category_type_id == category_type_id } end def category_type_categories_for_option(category_type, include_descendants: true) if include_descendants category_type_categories(category_type).map{|c| c.descendants_for_option }.flatten(1) else category_type_categories(category_type).map {|c| [c.title, c.id] } end end def list_style setting_value(:list_style) end def today_list_style setting_value(:today_list_style) end def calendar_list_style setting_value(:calendar_list_style).to_s end def search_list_style setting_value(:search_list_style) end def date_style setting_value(:date_style).to_s end def show_images? setting_value(:show_images) == 'visible' end def default_image setting_value(:default_image).to_s end def image_cnt setting_extra_value(:show_images, :image_cnt).to_i end def allowed_attachment_type 'gif,jpg,png' end def attachment_embed_link false end def public_event_docs(start_date, end_date, categories = nil) doc_content_ids = Cms::ContentSetting.where(name: 'calendar_relation', value: 'enabled') .select { |cs| cs.extra_values[:calendar_content_id] == id } .map(&:content_id) if doc_content_ids.blank? GpArticle::Doc.none else GpArticle::Doc.mobile(::Page.mobile?).public_state .where(content_id: doc_content_ids, event_state: 'visible') .event_scheduled_between(start_date, end_date, categories) end end private def create_default_holidays GpCalendar::DefaultHolidayJob.perform_now(id) end end <file_sep>class BizCalendar::PlacesScript < Cms::Script::Publication def publish uri = @node.public_uri.to_s path = @node.public_path.to_s smart_phone_path = @node.public_smart_phone_path.to_s publish_page(@node, uri: uri, path: path, smart_phone_path: smart_phone_path, dependent: uri) @node.content.places.public_state.each do |place| p_uri = place.public_uri p_path = place.public_path p_smart_phone_path = place.public_smart_phone_path publish_page(@node, uri: p_uri, path: p_path, smart_phone_path: p_smart_phone_path, dependent: p_uri) end end end <file_sep>class Sys::Base::Status < ApplicationRecord class Value attr_accessor :id def initialize(id) @id = id end def name case @id when 'enabled'; return '有効' when 'disabled'; return '無効' when 'visible'; return '表示' when 'hidden'; return '非表示' when 'draft'; return '下書き' when 'recognize'; return '承認待ち' when 'approvable'; return '承認待ち' when 'recognized'; return '公開待ち' when 'approved'; return '公開待ち' when 'prepared'; return '公開日時待ち' when 'public'; return '公開中' when 'closed'; return '非公開' when 'completed'; return '完了' when 'archived'; return '履歴' end nil end end def self.columns_hash column_defaults end def self.column_defaults cols = {} cols["id"] = ActiveRecord::ConnectionAdapters::Column.new("id", nil) cols["name"] = ActiveRecord::ConnectionAdapters::Column.new("name", nil) cols end def self.columns column_defaults.collect{|k, v| v } end def self.find_by_sql(*args) id = args[0].where_sql.to_s.gsub(/.*'(.*?)'$/, '\\1') [ Value.new(id) ] end def to_xml(options = {}) options[:builder] ||= Builder::XmlMarkup.new(:indent => options[:indent]) _root = options[:root] || 'status' xml = options[:builder] xml.tag!(_root) { |n| n.id key.to_s n.name name.to_s } end end <file_sep>class Sys::Setting < Sys::Model::Base::Setting include Sys::Model::Base set_config :common_ssl, :name => "共有SSL", :default => 'disabled', options: [['使用する', 'enabled'], ['使用しない', 'disabled']], form_type: :radio_buttons set_config :pass_reminder_mail_sender, :name => "パスワード変更メール送信元アドレス", :default => 'noreply' set_config :file_upload_max_size, :name => "添付ファイル最大サイズ", :comment => 'MB', :default => 50 set_config :maintenance_mode, :name => "メンテナンスモード", :default => 'disabled', options: [['有効にする', 'enabled'], ['無効にする', 'disabled']], form_type: :radio_buttons validates :name, presence: true def self.use_common_ssl? return false if Sys::Setting.value(:common_ssl) != 'enabled' return false if Sys::Setting.setting_extra_value(:common_ssl, :common_ssl_uri).blank? return true end def self.ext_upload_max_size_list return @ext_upload_max_size_list if @ext_upload_max_size_list csv = Sys::Setting.setting_extra_value(:file_upload_max_size, :extension_upload_max_size).to_s @ext_upload_max_size_list = {} csv.split(/(\r\n|\n)/u).each_with_index do |line, idx| line = line.to_s.gsub(/#.*/, "") line.strip! next if line.blank? data = line.split(/\s*,\s*/) ext = data[0].strip size = data[1].strip @ext_upload_max_size_list[ext.to_s] = size.to_i end return @ext_upload_max_size_list end def self.is_maintenance_mode? return false if Sys::Setting.value(:maintenance_mode) != 'enabled' #return false if Sys::Setting.setting_extra_value(:maintenance_mode).blank? return true end def self.get_maintenance_start_at return nil if Sys::Setting.setting_extra_value(:maintenance_mode, :maintenance_start_at).blank? "#{Sys::Setting.setting_extra_value(:maintenance_mode, :maintenance_start_at)} から" end def self.get_maintenance_end_at return nil if Sys::Setting.setting_extra_value(:maintenance_mode, :maintenance_end_at).blank? "#{Sys::Setting.setting_extra_value(:maintenance_mode, :maintenance_end_at)} まで" end def self.get_upload_max_size(ext) ext.gsub!(/^\./, '') list = Sys::Setting.ext_upload_max_size_list return list[ext.to_s] if list.include?(ext.to_s) return nil end end <file_sep>namespace :zomeki do namespace :sys do desc 'Delete duplicated values. (leave only latest values.)' task :clean_sequence => :environment do Sys::Sequence.transaction do before_key = {} Sys::Sequence.order(name: :asc, version: :asc, id: :desc).each do |sequence| if before_key[:name] == sequence.name && before_key[:version] == sequence.version sequence.destroy puts "[DELETED] name: #{sequence.name}, version: #{sequence.version}" else before_key[:name], before_key[:version] = sequence.name, sequence.version end end end end desc 'Cleanup unnecessary data.' task :cleanup => :environment do Sys::File.cleanup Sys::Task.cleanup end namespace :tasks do desc 'Exec tasks' task :exec => :environment do Cms::Site.order(:id).pluck(:id).each do |site_id| Script.run('sys/tasks/exec', site_id: site_id, lock_by: :site) end end end end end <file_sep>class Sys::Task < ApplicationRecord include Sys::Model::Base belongs_to :processable, polymorphic: true after_save :set_queue , if: :close_task? def publish_task? name == 'publish' end def close_task? name == 'close' end def unnecessary? return true unless processable return false unless processable.respond_to?(:state) (publish_task? && processable.state.in?(%w(public closed finish))) || (close_task? && processable.state.in?(%w(closed finish))) end def set_queue Sys::TaskJob.set(wait_until: self.process_at).perform_later(id) end class << self def cleanup tasks = self.where(self.arel_table[:process_at].lt(Time.now - 3.months)) .preload(:processable) tasks.find_each do |task| task.destroy if task.unnecessary? end end end end <file_sep>class Rank::Total < ApplicationRecord include Sys::Model::Base # Content belongs_to :content, foreign_key: :content_id, class_name: 'Rank::Content::Rank' validates :content_id, :presence => true def page_title self[:page_title].gsub(' | ' + content.site.name, '') end end <file_sep>class Cms::Lib::Mobile::Emoji @@map = nil def self.convert(name, career) return '' unless map.has_key?(name) case career when Jpmobile::Mobile::Docomo # for docomo return map[name][1] when Jpmobile::Mobile::Au # for au return '&#x' + map[name][3] + ';'; when Jpmobile::Mobile::Softbank # for SoftBank code = '1B24' + map[name][4] + '0F'; return [code].pack('H10'); when Jpmobile::Mobile::Willcom # for Willcom return map[name][1] else # for PC return map[name][1] end end def self.map return @@map if @map return @@map = I18n.t('emoji').with_indifferent_access end end <file_sep>## --------------------------------------------------------- ## cms/concepts c_site = @site.concepts.where(parent_id: 0).first c_top = @site.concepts.where(name: 'トップページ').first c_content = @site.concepts.where(name: 'コンテンツ').first ## --------------------------------------------------------- ## cms/contents l_tag = create_cms_layout c_site, 'tag', '関連ワード' tag = create_cms_content c_content, 'Tag::Tag', '関連ワード', 'tag' create_cms_node c_content, tag, 170, nil, l_tag, 'Tag::Tag', 'tags', '関連ワード', nil settings = Tag::Content::Setting.config(tag, 'date_style') settings.value = '%Y年%m月%d日 %H時%M分' settings.save Tag::Tag.create content_id: tag.id, word: '入札' create_cms_piece c_site, tag, 'Tag::Tag', 'tag-list', '関連ワード一覧'<file_sep>## --------------------------------------------------------- ## cms/concepts c_site = @site.concepts.where(parent_id: 0).first c_top = @site.concepts.where(name: 'トップページ').first c_content = @site.concepts.where(name: 'コンテンツ').first ## --------------------------------------------------------- ## cms/layouts l_gnavi = create_cms_layout c_content, 'global-navi', 'グローバルナビ' ## --------------------------------------------------------- ## cms/contents gnavi = create_cms_content c_content, 'Gnav::MenuItem', 'グローバルナビ', 'navi' create_cms_node c_content, gnavi, 10, nil, l_gnavi, 'Gnav::MenuItem', 'navi', 'ナビ', nil category = GpCategory::Content::CategoryType.where(concept_id: c_content.id).first cate_types = GpCategory::CategoryType.where(content_id: category.id).pluck(:id) settings = Gnav::Content::Setting.config(gnavi, 'gp_category_content_category_type_id') settings.value = category.id settings.save ## --------------------------------------------------------- ## gnavi/menu_items def create_menu(concept, content, layout, name, title, sort_no) Gnav::MenuItem.create concept_id: concept.id, content_id: content.id, state: 'public', name: name, title: title, sort_no: sort_no, layout_id: layout.id end kurashi = create_menu c_content, gnavi, l_gnavi, 'kurashi', '暮らしのガイド', 10 kosodate = create_menu c_content, gnavi, l_gnavi, 'kosodate', '子育て・教育', 20 kanko = create_menu c_content, gnavi, l_gnavi, 'kanko', '観光・文化', 30 jigyosha = create_menu c_content, gnavi, l_gnavi, 'jigyosha', '事業者の方へ', 40 shisei = create_menu c_content, gnavi, l_gnavi, 'shisei', '市政情報', 50 def create_category_sets(menu_item, category) Gnav::CategorySet.create menu_item_id: menu_item.id, category_id: category.id, layer: 'descendants' end ['kankyo', 'seikatsu', 'zei', 'kenko', 'hukushi', 'hoken', 'todokede',].each do |c| if category = GpCategory::Category.where(category_type_id: cate_types, name: c).first create_category_sets kurashi, category end end ['fuyo', 'ikuji'].each do |c| if category = GpCategory::Category.where(category_type_id: cate_types, name: c).first create_category_sets kosodate, category end end ['access', 'bunka_sports', 'rekishi'].each do |c| if category = GpCategory::Category.where(category_type_id: cate_types, name: c).first create_category_sets kanko, category end end ['suido', 'doro', 'toshiseibi', 'nyusatsu'].each do |c| if category = GpCategory::Category.where(category_type_id: cate_types, name: c).first create_category_sets jigyosha, category end end ['johokokai', 'kohokocho', 'gikai_senkyo', 'shisei'].each do |c| if category = GpCategory::Category.where(category_type_id: cate_types, name: c).first create_category_sets shisei, category end end <file_sep>class Rank::BaseScript < Cms::Script::Publication def publish uri = @node.public_uri.to_s path = @node.public_path.to_s smart_phone_path = @node.public_smart_phone_path.to_s publish_more(@node, uri: uri, path: path, smart_phone_path: smart_phone_path, dependent: uri) end end <file_sep>require 'digest/md5' class Cms::TalkTasksScript < Cms::Script::Publication def exec task_ids = Cms::TalkTask.order(:id) task_ids = task_ids.where(site_id: ::Script.site.id) if ::Script.site task_ids = task_ids.pluck(:id) ::Script.total task_ids.size task_ids.each do |task_id| task = Cms::TalkTask.find_by(id: task_id) next unless task begin ::Script.current clean_statics = Zomeki.config.application['sys.clean_statics'] if clean_statics if File.exist?("#{task.path}.mp3") File.delete("#{task.path}.mp3") info_log "DELETED: #{task.path}.mp3" end rs = true else if ::File.exist?(task.path) rs = make_sound(task) else rs = true end end ::Script.success if rs task.destroy raise "MakeSoundError" unless rs rescue ::Script::InterruptException => e raise e rescue Exception => e puts "#{e}: #{task.path}" ::Script.error "#{e}: #{task.path}" #error_log "#{e} #{task.path}" end end end def make_sound(task) content = ::File.new(task.path).read #hash = Digest::MD5.new.update(content.to_s).to_s #return true if hash == task.content_hash && ::File.exist?("#{task.path}.mp3") jtalk = Cms::Lib::Navi::Jtalk.new jtalk.make(content, {:site_id => task.site_id}) mp3 = jtalk.output return false unless mp3 return false if ::File.stat(mp3[:path]).size == 0 FileUtils.mv(mp3[:path], "#{task.path}.mp3") ::File.chmod(0644, "#{task.path}.mp3") return true end end <file_sep>class Sys::ObjectPrivilege < ApplicationRecord include Sys::Model::Base include Sys::Model::Base::Config include Cms::Model::Auth::Site::Role belongs_to :privilegable, polymorphic: true belongs_to :concept, class_name: 'Cms::Concept' belongs_to :role_name, :foreign_key => 'role_id', :class_name => 'Sys::RoleName' validates :role_id, :concept_id, presence: true validates :action, presence: true, if: %Q(in_actions.blank?) attr_accessor :in_actions def in_actions @in_actions ||= actions end def in_actions=(values) @_in_actions_changed = true @in_actions = if values.kind_of?(Hash) values.map{|k, v| k if v.present? }.compact else [] end end def action_labels(format = nil) list = [['閲覧','read'], ['作成','create'], ['編集','update'], ['削除','delete']] if format == :hash h = {} list.each {|c| h[c[1]] = c[0]} return h end list end def privileges self.class.where(role_id: role_id, privilegable: privilegable).order(:action) end def actions privileges.collect{|c| c.action} end def action_names names = [] _actions = actions action_labels.each do |label, key| if actions.index(key) names << label _actions.delete(key) end end names += _actions names end def save return super unless @_in_actions_changed return false unless valid? save_actions end def destroy_actions privileges.each {|priv| priv.destroy } return true end protected def save_actions actions = in_actions.map(&:to_s) privileges.each do |priv| if actions.index(priv.action) actions.delete(priv.action) else priv.destroy end end actions.each do |action| privileges.create(action: action, concept_id: concept_id) end end end <file_sep>class Cms::Bracket < ApplicationRecord include Sys::Model::Base belongs_to :owner, polymorphic: true scope :with_prefix, ->(names) { conds = names.map { |name| arel_table[:name].matches("#{name}%") } where(conds.reduce(:or)) } end <file_sep>class Cms::Admin::Tool::LinkCheckController < Cms::Controller::Admin::Base include Sys::Controller::Scaffold::Base def pre_dispatch return error_auth unless Core.user.has_auth?(:creator) return redirect_to(action: :index) if params[:reset] params[:limit] ||= '30' end def index logs = Cms::LinkCheckLog.where(site_id: Core.site.id) @logs = logs.search_with_params(params).order(:id) .paginate(page: params[:page], per_page: params[:limit]) .preload(link_checkable: { creator: :group }) if (@running = logs.where(checked: false).exists?) current = logs.where(checked: true).count total = logs.count flash.now[:notice] = "リンクチェックを実行中です。(#{current}/#{total}件)" end end end <file_sep>module Sys::Model::Rel::File extend ActiveSupport::Concern attr_accessor :in_tmp_id attr_accessor :in_file_names included do has_many :files, class_name: 'Sys::File', dependent: :destroy, as: :file_attachable before_save :make_file_path_relative before_save :fix_file_name, if: -> { in_file_names.present? } before_save :publish_files before_save :close_files after_create :fix_tmp_files, if: -> { in_tmp_id.present? } end def public_files_path "#{::File.dirname(public_path)}/files" end def publish_files return true unless @save_mode == :publish return true if Zomeki.config.application['sys.clean_statics'] return true if files.empty? public_dir = public_files_path FileUtils.mkdir_p(public_dir) unless FileTest.exist?(public_dir) files.each do |file| paths = { file.upload_path => "#{public_dir}/#{file.name}", file.upload_path(type: :thumb) => "#{public_dir}/thumb/#{file.name}" } paths.each do |fr, to| next unless FileTest.exists?(fr) next if FileTest.exists?(to) && ( ::File.mtime(to) >= ::File.mtime(fr) ) FileUtils.mkdir_p(::File.dirname(to)) unless FileTest.exists?(::File.dirname(to)) FileUtils.cp(fr, to) end end return true end def close_files return true unless @save_mode == :close dir = public_files_path FileUtils.rm_r(dir) if FileTest.exist?(dir) return true end def image_files files.select {|f| f.image_file? } end private def fix_tmp_files Sys::File.fix_tmp_files(in_tmp_id, self) return true end def make_file_path_relative self.class.columns_having_file_name.each do |column| attr = read_attribute(column) next if attr.blank? if attr.is_a?(String) self[column] = make_file_path_relative_for(attr) elsif attr.is_a?(Hash) attr.each do |key, value| self[column][key] = make_file_path_relative_for(value) end end end end def make_file_path_relative_for(text) text.gsub(%r{("|')/[^'"]+?/inline_files/\d+/(file_contents[^'"]+?)("|')}, "\\1\\2\\3") end def fix_file_name in_file_names.each do |id, name| file = files.find_by(id: id) next if file.nil? || file.name == name self.class.columns_having_file_name.each do |column| attr = read_attribute(column) next if attr.blank? if attr.is_a?(String) self[column] = fix_file_name_for(attr, name, file.name) elsif attr.is_a?(Hash) attr.each do |key, value| self[column][key] = fix_file_name_for(value, name, file.name) end end end end end def fix_file_name_for(text, from, to) text.gsub(%r{("|')file_contents/#{from}("|')}, "\\1file_contents/#{to}\\2") end class_methods do def columns_having_file_name columns.select { |c| c.type == :text }.map(&:name) end end end <file_sep>module Sys::Model::Scope extend ActiveSupport::Concern included do scope :search_with_text, ->(*args) { words = args.pop.to_s.split(/[  ]+/) columns = args where(words.map{|w| columns.map{|c| arel_table[c].matches("%#{escape_like(w)}%") }.reduce(:or) }.reduce(:and)) } scope :search_with_logical_query, ->(*args) { if (tree = LogicalQueryParser.new.parse(args.last.to_s)) args.pop where(tree.to_sql(model: self, columns: args)) else search_with_text(*args) end } end module ClassMethods def escape_like(s) s.gsub(/[\\%_]/) {|r| "\\#{r}"} end def union(relations) sql = '((' + relations.map{|rel| rel.to_sql}.join(') UNION (') + ')) AS ' + self.table_name from(sql) end def replace_for_all(column, from, to) column = connection.quote_column_name(column) update_all(["#{column} = REPLACE(#{column}, ?, ?)", from, to]) end end end <file_sep>class Sys::UsersRole < ApplicationRecord include Sys::Model::Base include Sys::Model::Base::Config include Cms::Model::Auth::Site::User belongs_to :user, :foreign_key => :user_id, :class_name => 'Sys::User' belongs_to :role_name, :foreign_key => :role_id, :class_name => 'Sys::RoleName' end <file_sep>class Cms::LinkCheck < ApplicationRecord include Sys::Model::Base end <file_sep>class Rank::Admin::RanksController < Cms::Controller::Admin::Base include Sys::Controller::Scaffold::Base include Rank::Controller::Rank def pre_dispatch @content = Rank::Content::Rank.find(params[:content]) return error_auth unless Core.user.has_priv?(:read, item: @content.concept) end def index @terms = ranking_terms @targets = ranking_targets @term = param_check(@terms, params[:term]) @target = param_check(@targets, params[:target]) options @ranks = rank_datas(@content, @term, @target, 20, nil, @gp_category, @category_type, @category) _index @ranks end def remote @options = options render :partial => 'remote' end private def option_default [['すべて', '']] end def options @gp_category = params[:gp_category].to_i @gp_categories = option_default + gp_categories @category_type = params[:category_type].to_i @category_types = option_default @category_types = @category_types + category_types(@gp_category) if @gp_category > 0 @category = params[:category].to_i @categories = option_default @categories = @categories + categories(@category_type) if @category_type > 0 @category_type != 0 ? @categories : @category_types end end<file_sep>class Tag::Tag < ApplicationRecord include Sys::Model::Base include Tag::Tags::Preload # Content belongs_to :content, :foreign_key => :content_id, :class_name => 'Tag::Content::Tag' validates :content_id, presence: true # Proper has_and_belongs_to_many :docs, -> { order(display_published_at: :desc, published_at: :desc) }, :class_name => 'GpArticle::Doc', :join_table => 'gp_article_docs_tag_tags', :after_add => :update_last_tagged_at, :after_remove => :update_last_tagged_at def public_uri=(uri) @public_uri = uri end def public_uri return @public_uri if @public_uri return '' unless node = content.public_node @public_uri = "#{node.public_uri}#{ERB::Util.url_encode(word)}/" end def public_path return '' if public_uri.blank? "#{content.public_path}#{public_uri}" end def public_smart_phone_path return '' if public_uri.blank? "#{content.public_path}/_smartphone#{public_uri}" end def preview_uri(site: ::Page.site, mobile: ::Page.mobile?, params: {}) return nil unless public_uri params = params.map{|k, v| "#{k}=#{v}" }.join('&') path = "_preview/#{format('%04d', site.id)}#{mobile ? 'm' : ''}#{public_uri}#{params.present? ? "?#{params}" : ''}" "#{site.main_admin_uri}#{path}" end def bread_crumbs(tag_node) crumbs = [] crumb = tag_node.bread_crumbs.crumbs.first crumb << [word, "#{tag_node.public_uri}#{CGI::escape(word)}/"] crumbs << crumb if crumbs.empty? tag_node.routes.each do |r| crumb = [] r.each {|r| crumb << [r.title, r.public_uri] } crumbs << crumb end end Cms::Lib::BreadCrumbs.new(crumbs) end def public_docs docs.mobile(::Page.mobile?).public_state end def update_last_tagged_at(doc=nil) update_column(:last_tagged_at, Time.now) end class << self def split_raw_string(str) str = Moji.normalize_zen_han(str).downcase str.split(/"([^"]*)"|[  ,、,]+/).select(&:present?).uniq end end end <file_sep>class Sys::TasksScript < Cms::Script::Base def exec tasks = Sys::Task.order(process_at: :desc) tasks = tasks.where(site_id: ::Script.site.id) if ::Script.site tasks = tasks.where(Sys::Task.arel_table[:process_at].lteq(Time.now)) .preload(:processable) ::Script.total tasks.size tasks.each do |task| begin unless task.processable task.destroy raise 'Processable Not Found' end script_klass = "#{task.processable_type.pluralize}Script".constantize script_klass.new(params.merge(task: task, item: task.processable)).public_send("#{task.name}_by_task") rescue => e ::Script.error e info_log "Error: #{e}" puts "Error: #{e}" end end end end <file_sep>module GpArticle::FormHelper def value_for_datepicker(object_name, attribute) if object = instance_variable_get("@#{object_name}") object.send(attribute).try(:strftime, '%Y-%m-%d') end end def enable_datepicker_script s = <<-EOS $.datepicker.regional['ja'] = { closeText: '閉じる', prevText: '前', nextText: '次', currentText: '今日', monthNames: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'], monthNamesShort: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'], dayNames: ['日曜日', '月曜日', '火曜日', '水曜日', '木曜日', '金曜日', '土曜日'], dayNamesShort: ['日', '月', '火', '水', '木', '金', '土'], dayNamesMin: ['日', '月', '火', '水', '木', '金', '土'], weekHeader: '週', dateFormat: 'yy-mm-dd', firstDay: 0, isRTL: false, showMonthAfterYear: true, yearSuffix: '年'}; $.datepicker.setDefaults($.datepicker.regional['ja']); $('.datepicker').datepicker(); EOS s.html_safe end def value_for_datetimepicker(object_name, attribute) if object = instance_variable_get("@#{object_name}") object.send(attribute).try(:strftime, '%Y-%m-%d %H:%M') end end def enable_datetimepicker_script s = <<-EOS $.datepicker.regional['ja'] = { closeText: '閉じる', prevText: '前', nextText: '次', currentText: '今日', monthNames: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'], monthNamesShort: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'], dayNames: ['日曜日', '月曜日', '火曜日', '水曜日', '木曜日', '金曜日', '土曜日'], dayNamesShort: ['日', '月', '火', '水', '木', '金', '土'], dayNamesMin: ['日', '月', '火', '水', '木', '金', '土'], weekHeader: '週', dateFormat: 'yy-mm-dd', firstDay: 0, isRTL: false, showMonthAfterYear: true, yearSuffix: '年'}; $.datepicker.setDefaults($.datepicker.regional['ja']); $.timepicker.regional['ja'] = { timeOnlyTitle: '時刻選択', timeText: '時刻', hourText: '時', minuteText: '分', secondText: '秒', millisecText: 'ミリ秒', timezoneText: 'タイムゾーン', currentText: '現在', closeText: '閉じる', timeFormat: 'HH:mm', amNames: ['AM', 'A'], pmNames: ['PM', 'P'], isRTL: false}; $.timepicker.setDefaults($.timepicker.regional['ja']); $('.datetimepicker').datetimepicker({ hourGrid: 4, minuteGrid: 10, secondGrid: 10}); EOS s.html_safe end def value_for_timepicker(object_name, attribute) if object = instance_variable_get("@#{object_name}") object.send(attribute).try(:strftime, '%H:%M') end end def enable_timepicker_script s = <<-EOS $.timepicker.regional['ja'] = { timeOnlyTitle: '時刻選択', timeText: '時刻', hourText: '時', minuteText: '分', secondText: '秒', millisecText: 'ミリ秒', timezoneText: 'タイムゾーン', currentText: '現在', closeText: '閉じる', timeFormat: 'HH:mm', amNames: ['AM', 'A'], pmNames: ['PM', 'P'], isRTL: false}; $.timepicker.setDefaults($.timepicker.regional['ja']); $('.timepicker').timepicker(); EOS s.html_safe end def disable_enter_script s = <<-EOS $('form').on('keypress', function (e) { if (e.target.type !== 'textarea' && e.which === 13) return false; }); EOS s.html_safe end end <file_sep>module Sys::Model::Rel::Task extend ActiveSupport::Concern included do has_many :tasks, class_name: 'Sys::Task', dependent: :destroy, as: :processable accepts_nested_attributes_for :tasks with_options if: :save_tasks? do before_save :prepare_tasks validate :validate_tasks, if: -> { state != 'draft' } end scope :with_task_name, ->(name) { tasks = Sys::Task.arel_table joins(:tasks).where(tasks[:name].eq(name)) } end def tasks_attributes=(val) @save_tasks = true super end def save_tasks? @save_tasks end def set_queues return if tasks.blank? if state == 'recognized' || state == 'approved' || state == 'prepared' tasks.each{|t| t.set_queue if t.publish_task? } end end private def validate_tasks publish_task = tasks.detect(&:publish_task?) close_task = tasks.detect(&:close_task?) if publish_task && publish_task.process_at && publish_task.process_at < Time.now errors.add(:base, '公開開始日時は現在日時より後の日時を入力してください。') publish_task.errors.add(:process_at) end if publish_task && close_task if publish_task.process_at && close_task.process_at && publish_task.process_at > close_task.process_at errors.add(:base, '公開開始日時は公開終了日時より前の日時を入力してください。') publish_task.errors.add(:process_at) end end end def prepare_tasks tasks.each do |task| task.site_id = Core.site.id if Core.site task.mark_for_destruction if task.name.blank? || task.process_at.blank? end end end <file_sep>class AdBanner::Tool::BannersScript < Cms::Script::Base def rebuild content = AdBanner::Content::Banner.find(params[:content_id]) content.banners.each do |banner| ::Script.progress(banner) do banner.publish_or_close_image end end end end <file_sep>class Organization::Publisher::GroupCallbacks < PublisherCallbacks def after_save(group) @group = group enqueue if enqueue? end def before_destroy(group) @group = group enqueue if enqueue? end def enqueue(group = nil) @group = group if group enqueue_groups enqueue_sitemap_nodes end private def enqueue? [@group.state, @group.state_was].include?('public') end def enqueue_groups Cms::Publisher.register(@group.content.site_id, @group.public_ancestors) end def enqueue_sitemap_nodes if [@group.sitemap_state, @group.sitemap_state_was].include?('visible') site = @group.content.site Cms::Publisher.register(site.id, site.public_sitemap_nodes) end end end <file_sep>module StateText extend ActiveSupport::Concern class Responder def self.state_text(state) case state when 'enabled'; '有効' when 'disabled'; '無効' when 'visible'; '表示' when 'hidden'; '非表示' when 'draft'; '下書き' when 'recognize'; '承認待ち' when 'approvable'; '承認待ち' when 'recognized'; '公開待ち' when 'approved'; '公開待ち' when 'prepared'; '公開日時待ち' when 'public'; '公開中' when 'closed'; '非公開' when 'finish'; '公開終了' when 'completed'; '完了' when 'archived'; '履歴' when 'synced'; '同期済' else '' end end def initialize(stateable, attribute_name=:state) @stateable = stateable @attribute_name = attribute_name end def name self.class.state_text(@stateable.send(@attribute_name)) end end def status Responder.new(self) end def web_status Responder.new(self, :web_state) end def portal_group_status Responder.new(self, :portal_group_state) end def state_text Responder.state_text(self.state) end def web_state_text Responder.state_text(self.web_state) end def portal_group_state_text Responder.state_text(self.portal_group_state) end end <file_sep>module DocHelper def doc_replace(doc, doc_style, date_style, time_style='') link_to_options = doc.link_to_options contents = { title_link: -> { doc_replace_title_link(doc, link_to_options) }, title: -> { doc_replace_title(doc) }, subtitle: -> { doc_replace_subtitle(doc) }, publish_date: -> { doc_replace_publish_date(doc, date_style) }, update_date: -> { doc_replace_update_date(doc, date_style) }, publish_time: -> { doc_replace_publish_time(doc, time_style) }, update_time: -> { doc_replace_update_time(doc, time_style) }, summary: -> { doc_replace_summary(doc) }, group: -> { doc_replace_group(doc) }, category_link: -> { doc_replace_category_link(doc) }, category: -> { doc_replace_category(doc) }, image_link: -> { doc_replace_image_link(doc, link_to_options) }, image: -> { doc_replace_image(doc) }, body_beginning: -> { doc_replace_body_beginning(doc) }, body: -> { doc_replace_body(doc) }, user: -> { doc_replace_user(doc) }, doc_no: -> {doc_replace_doc_no(doc)} } if Page.mobile? contents[:title_link].call else doc_style = doc_style.gsub(/@doc{{@(.+)@}}doc@/m){|m| link_to($1.html_safe, link_to_options[0], class: 'doc_link') } doc_style = doc_style.gsub(/@body_(\d+)@/){|m| content_tag(:span, truncate(strip_tags(doc.body), length: $1.to_i).html_safe, class: 'body') } doc_style = doc_style.gsub(/@(\w+)@/) {|m| contents[$1.to_sym] ? contents[$1.to_sym].call : '' } doc_style.html_safe end end private def file_path_expanded_body(doc) doc.body.gsub(/("|')file_contents\//){|m| %Q(#{$1}#{doc.public_uri(without_filename: true)}file_contents/) } end def doc_image_tag(doc) if doc.list_image.present? && (image_file = doc.image_files.detect { |f| f.name == doc.list_image }) image_tag("#{doc.public_uri(without_filename: true)}file_contents/#{url_encode image_file.name}", alt: image_file.alt) elsif doc.template && (attach_item = doc.template.public_items.where(item_type: 'attachment_file').first) && (image_file = doc.image_files.detect { |f| f.name == doc.template_values[attach_item.name] }) image_tag("#{doc.public_uri(without_filename: true)}file_contents/#{url_encode image_file.name}", alt: image_file.alt) else body = if doc.template rich_text_names = doc.template.public_items.where(item_type: 'rich_text').map(&:name) rich_text_names.map { |name| doc.template_values[name] }.join('') else doc.body end unless (img_tags = Nokogiri::HTML.parse(body).css('img[src^="file_contents/"]')).empty? filename = File.basename(img_tags.first.attributes['src'].value) alt = img_tags.first.attributes['alt'].value image_tag("#{doc.public_uri(without_filename: true)}file_contents/#{url_encode filename}", alt: alt) else '' end end end def doc_replace_title_link(doc, link_to_options) link = link_to_options ? link_to(*([doc.title] + link_to_options)) : h(doc.title) if link.present? content_tag(:span, link, class: 'title_link') else '' end end def doc_replace_title(doc) if doc.title.present? content_tag(:span, doc.title, class: 'title') else '' end end def doc_replace_subtitle(doc) if doc.subtitle.present? content_tag(:span, doc.subtitle, class: 'subtitle') else '' end end def doc_replace_publish_date(doc, date_style) if (dpa = doc.display_published_at) ds = localize_wday(date_style, dpa.wday) content_tag(:span, dpa.strftime(ds), class: 'publish_date') else '' end end def doc_replace_update_date(doc, date_style) if (dua = doc.display_updated_at) ds = localize_wday(date_style, dua.wday) content_tag(:span, dua.strftime(ds), class: 'update_date') else '' end end def doc_replace_publish_time(doc, time_style) if (dpa = doc.display_published_at) content_tag(:span, dpa.strftime(time_style), class: 'publish_time') else '' end end def doc_replace_update_time(doc, time_style) if (dua = doc.display_updated_at) content_tag(:span, dua.strftime(time_style), class: 'update_time') else '' end end def doc_replace_summary(doc) if doc.summary.present? content_tag(:span, doc.summary, class: 'summary') else '' end end def doc_replace_group(doc) if doc.creator && doc.creator.group content_tag(:span, doc.creator.group.name, class: 'group') else '' end end def doc_replace_category_link(doc) if doc.categories.present? category_text = doc.categories.map {|c| content_tag(:span, link_to(c.title, c.public_uri), class: "#{c.category_type.name}-#{c.ancestors.map(&:name).join('-')}") }.join.html_safe content_tag(:span, category_text, class: 'category') else '' end end def doc_replace_category(doc) if doc.categories.present? category_text = doc.categories.map {|c| content_tag(:span, c.title, class: "#{c.category_type.name}-#{c.ancestors.map(&:name).join('-')}") }.join.html_safe content_tag(:span, category_text, class: 'category') else '' end end def doc_replace_image_link(doc, link_to_options) image_tag = doc_image_tag(doc) image_link = if image_tag.present? && link_to_options link_to *([image_tag] + link_to_options) else image_tag end if image_link.present? content_tag(:span, image_link, class: 'image') else '' end end def doc_replace_image(doc) image_tag = doc_image_tag(doc) if image_tag.present? content_tag(:span, image_tag, class: 'image') else '' end end def doc_replace_body_beginning(doc) if doc.body.present? more = content_tag(:div, link_to(doc.body_more_link_text, doc.public_uri), class: 'continues') if doc.body_more.present? content_tag(:span, "#{file_path_expanded_body(doc)}#{more}".html_safe, class: 'body') else '' end end def doc_replace_body(doc) if doc.body.present? || doc.body_more.present? content_tag(:span, "#{file_path_expanded_body(doc)}#{doc.body_more}".html_safe, class: 'body') else '' end end def doc_replace_user(doc) if doc.creator && doc.creator.user content_tag(:span, doc.creator.user.name, class: 'user') else '' end end def doc_replace_doc_no(doc) if doc.serial_no content_tag(:span, doc.serial_no, class: 'docNo') else '' end end end <file_sep>class Gnav::MenuItemsScript < Cms::Script::Publication def publish uri = @node.public_uri.to_s path = @node.public_path.to_s smart_phone_path = @node.public_smart_phone_path.to_s publish_more(@node, uri: uri, path: path, smart_phone_path: smart_phone_path, dependent: uri) @node.content.public_menu_items.each do |menu_item| mi_uri = menu_item.public_uri mi_path = menu_item.public_path mi_smart_phone_path = menu_item.public_smart_phone_path publish_more(@node, uri: mi_uri, path: mi_path, smart_phone_path: mi_smart_phone_path, dependent: mi_uri) end end end <file_sep>class Cms::Public::CommonSslController < ApplicationController def index path = Core.request_uri.gsub(/^#{Regexp.escape(cms_common_ssl_path)}/, "") render_ssl(path, :mobile => Page.mobile?, :smart_phone => request.smart_phone?, :preview => true) end def render_ssl(path, options = {}) Core.publish = true unless options[:preview] Page.initialize Page.site = options[:site] || Core.site Page.uri = path Page.mobile = options[:mobile] Page.smart_phone = options[:smart_phone] return http_error(404) if Page.site.blank? # layouts if path =~ /^\/_layouts\/(\d{8})\/([^\/]*)/ ctl = 'cms/public/layouts' act = 'index' format = params[:format] params[:id] = $1 params[:file] = File.basename($2, ".*") else node = Core.search_node(path) env = {} env[:method] = :post if request.post? opt = Rails.application.routes.recognize_path(node, env) ctl = opt[:controller] act = opt[:action] opt.each {|k,v| params[k] = v } #opt[:layout_id] = params[:layout_id] if params[:layout_id] opt[:authenticity_token] = params[:authenticity_token] if params[:authenticity_token] return redirect_to ::File.join(Page.site.full_uri, path) if node !~ /^\/_public\/survey\/node_forms/ end rendered = Sys::Lib::Controller.dispatch(ctl, act, params: params, base_url: request.base_url, agent_type: Page.smart_phone? ? :smart_phone : :pc) return redirect_to(rendered.redirect_url) if rendered.redirect_url response.content_type = rendered.content_type if rendered.respond_to?(:content_type) self.response_body = rendered.body end end <file_sep>module GpArticle::Model::Rel::RelatedDoc extend ActiveSupport::Concern included do has_many :related_docs, class_name: 'GpArticle::RelatedDoc', dependent: :destroy, as: :relatable accepts_nested_attributes_for :related_docs, allow_destroy: true, reject_if: proc{|attrs| attrs['name'].blank?} end def all_related_docs related_docs.map(&:target_doc).compact end def public_related_docs @public_related_docs ||= all_related_docs.select(&:state_public?) end end <file_sep>module Sys::Model::Base::Transfer extend ActiveSupport::Concern included do belongs_to :site, :class_name => 'Cms::Site' belongs_to :user, :class_name => 'Sys::User' scope :search_with_params, ->(params = {}) { rel = all params.each do |n, v| next if v.to_s == '' case n when 's_version' rel.where!(version: v) when 's_operation' rel.where!(operation: v) when 's_file_type' rel.where!(file_type: v) when 's_path' rel.where!(arel_table[:path].matches("%#{escape_like(v)}%")) when 's_item_name' rel.where!(arel_table[:item_name].matches("%#{escape_like(v)}%")) when 's_operator_name' rel.where!(arel_table[:operator_name].matches("%#{escape_like(v)}%")) end end rel } end def operations [['作成','create'],['更新','update'],['削除','delete']] end def operation_label operations.each {|a| return a[0] if a[1] == operation } return nil end def file_types [['ディレクトリ','directory'],['ファイル','file']] end def file_type_label file_types.each {|a| return a[0] if a[1] == file_type } return nil end def file? file_type.to_s == 'file' end def operation_is?(op) operation.to_s == op.to_s end def item_info(attr) return @item_info[attr] || '-' if @item_info # cms_data_files if path =~ /^_files\/.+?$/ #data = Cms::DataFile.find_by_public_path("#{parent_dir}#{_path}") "#{parent_dir}#{_path}" =~ /sites\/.*\/(.*?)\/public\/_files\/.*\/(.*?)\/(.*?)$/i _site_id = $1.to_i rescue 0; _id = $2[0 .. -2].to_i rescue 0; if log = Sys::OperationLog.where(:site_id => _site_id, :item_id => _id, :item_model => 'Cms::DataFile').order(id: :desc).first @item_info = {} @item_info[:item_id] = log.item_id @item_info[:item_unid] = log.item_unid @item_info[:item_model] = log.item_model @item_info[:item_name] = "データファイル:#{log.item_name}"; @item_info[:operated_at] = log.created_at @item_info[:operator_id] = log.user_id @item_info[:operator_name] = log.user_name return @item_info[attr] || '-' end end _path = path _attachment = nil if path =~ /^.+?\/file_contents\/(.+?)$/ # sys_files _attachment = $1 _path = path.gsub(/\/file_contents\/.+?$/, '/index.html') end # sys_publishers pub = Sys::Publisher.where(:path => "#{parent_dir}#{_path}").order(id: :desc).first pub ||= Sys::Closer.where(:path => "#{parent_dir}#{_path}").order(id: :desc).first if pub if log = Sys::OperationLog.where(:item_unid => pub.unid).order(id: :desc).first @item_info = {} @item_info[:item_id] = log.item_id @item_info[:item_unid] = log.item_unid @item_info[:item_model] = log.item_model @item_info[:item_name] = _attachment ? "#{log.item_name}(添付ファイル:#{_attachment})" : log.item_name; if pub.updated_at - 2*60 > log.updated_at # by process @item_info[:operated_at] = pub.created_at else @item_info[:operated_at] = log.created_at @item_info[:operator_id] = log.user_id @item_info[:operator_name] = log.user_name end return @item_info[attr] || '-' end end '-' end module_function :operations module_function :file_types end <file_sep>class GpArticle::Admin::RelatedDocsController < Cms::Controller::Admin::Base include Sys::Controller::Scaffold::Base def pre_dispatch @content = GpArticle::Content::Doc.find(params[:content]) return error_auth unless Core.user.has_priv?(:read, item: @content.concept) end def show @item = GpArticle::Doc.find_by(id: params[:id]) @doc = { id: @item.id, title: @item.title, full_uri: @item.state_public? ? @item.public_full_uri : nil, name: @item.name, content: @item.content_id, updated: @item.updated_at.strftime('%Y/%m/%d %H:%M'), status: @item.status.name, user: @item.creator.user.try(:name), group: @item.creator.group.try(:name) } render xml: @doc end end <file_sep>class Sys::TransferableFile < ApplicationRecord include Sys::Model::Base include Sys::Model::Base::Transfer end <file_sep>class Survey::Answer < ApplicationRecord include Sys::Model::Base belongs_to :form_answer validates :form_answer_id, presence: true belongs_to :question validates :question_id, presence: true end <file_sep>class Cms::FeedEntry < ApplicationRecord include Sys::Model::Base include Cms::Model::Base::Page include Sys::Model::Auth::Free belongs_to :status, :foreign_key => :state, :class_name => 'Sys::Base::Status' belongs_to :feed, :foreign_key => :feed_id, :class_name => 'Cms::Feed' def public self.and "#{self.class.table_name}.state", 'public' #self.join :feed self.join "INNER JOIN `cms_feeds` ON `cms_feeds`.id = `cms_feed_entries`.feed_id" self.and "#{Cms::Feed.table_name}.state", 'public' self end def search(params) params.each do |n, v| next if v.to_s == '' case n when 's_id' self.and "#{Cms::FeedEntry.table_name}.id", v when 's_title' self.and_keywords v, :title when 's_keyword' self.and_keywords v, :title, :summary end end if params.size != 0 return self end def event_date_is(options = {}) if options[:year] && options[:month] sd = Date.new(options[:year], options[:month], 1) ed = sd >> 1 self.and :event_date, 'IS NOT', nil self.and :event_date, '>=', sd self.and :event_date, '<' , ed end end def public_uri return nil unless self.link_alternate self.link_alternate end def public_full_uri return nil unless self.link_alternate self.link_alternate end def agent_filter(agent) self end def category_is(cate) return self if cate.blank? cate = [cate] unless cate.class == Array cate.each do |c| if c.level_no == 1 cate += c.public_children end end cate = cate.uniq cond = Condition.new added = false cate.each do |c| if c.entry_categories arr = c.entry_categories.split(/\r\n|\r|\n/) arr.each do |label| label = label.gsub(/\/$/, '') cond.or :categories, 'REGEXP', "(^|\n)#{label}" added = true end end end cond.and '1', '=', '0' unless added self.and cond end def group_is(group) return self unless group conditions = [] # if group.category.size > 0 # entry = self.class.new # entry.category_is(group.category_items) # conditions << entry.condition # end entry = self.class.new entry.category_is(group) conditions << entry.condition condition = Condition.new conditions.each {|c| condition.or(c) if c.where } self.and condition if conditions.size > 0 self end end<file_sep>namespace :zomeki do namespace :db do namespace :site do desc 'Dump site (options: SITE_ID=x, DIR=x)' task :dump => :environment do site = Cms::Site.find(ENV['SITE_ID']) id_map = load_id_map(site) unless check_model_and_id_map_consistency(backup_models, id_map) raise "invalid model and ids." end puts "dumping site id: #{site.id}..." backup_models.each do |model| path = backup_file_path(site, model.table_name) puts "#{id_map[model.table_name].size} rows from #{model.table_name} to '#{path}'" data = model.unscoped.where(id: id_map[model.table_name]).copy_to_string Util::File.put(path, data: data, mkdir: true) end puts "done." end desc 'Dump all sites (options: DIR=x)' task :dump_all => :environment do Cms::Site.order(:id).each do |site| ENV['SITE_ID'] = site.id.to_s Rake::Task['zomeki:db:site:dump'].reenable Rake::Task['zomeki:db:site:dump'].invoke end end desc 'Restore site (options: SITE_ID=x, DIR=x)' task :restore => :environment do site = Cms::Site.new(id: ENV['SITE_ID']) id_map = load_id_map(site) unless check_model_and_id_map_consistency(backup_models, id_map) raise "invalid model and ids." end unless check_model_and_file_consistency(backup_models, site) raise "invalid model and file." end puts "restoring site id: #{site.id}..." backup_models.each do |model| path = backup_file_path(site, model.table_name) ids = load_ids_from_dump_file(path) puts "#{ids.size} rows from '#{path}' to #{model.table_name}" model.unscoped.where(id: id_map[model.table_name]).delete_all model.unscoped.where(id: ids).delete_all model.copy_from(path) end puts "done." end def load_ids_from_dump_file(path) require 'csv' items = CSV.parse(File.read(path), headers: true, header_converters: :symbol) items.map { |item| item[:id] } end def check_model_and_id_map_consistency(models, id_map) models.each do |model| return false unless id_map.key?(model.table_name) end true end def check_model_and_file_consistency(models, site) models.each do |model| path = backup_file_path(site, model.table_name) return false unless File.exist?(path) end true end def backup_file_path(site, table_name) base_dir = ENV['DIR'] || ENV['HOME'] || Rails.root "#{base_dir}/sites/#{format('%04d', site.id)}/db/#{table_name}.dump" end def backup_models models = [ # Sys Sys::Creator, Sys::EditableGroup, Sys::Editor, Sys::File, Sys::Group, Sys::Message, Sys::ObjectRelation, Sys::ObjectPrivilege, Sys::OperationLog, Sys::ProcessLog, Sys::Process, Sys::Publisher, Sys::Recognition, Sys::RoleName, Sys::Sequence, Sys::StorageFile, Sys::Task, Sys::User, Sys::UsersGroup, # Cms Cms::Bracket, Cms::Concept, Cms::Content, Cms::ContentSetting, Cms::DataFileNode, Cms::DataFile, Cms::DataText, Cms::Inquiry, Cms::KanaDictionary, Cms::Layout, Cms::Link, Cms::LinkCheckLog, Cms::Map, Cms::MapMarker, Cms::Node, Cms::Piece, Cms::PieceSetting, Cms::PieceLinkItem, Cms::Publisher, Cms::Site, Cms::SiteBelonging, Cms::SiteBasicAuthUser, Cms::SiteSetting, Cms::Stylesheet, Cms::TalkTask, # AdBanner AdBanner::Banner, AdBanner::Click, AdBanner::Group, # Approval Approval::ApprovalFlow, Approval::Approval, Approval::ApprovalRequest, Approval::ApprovalRequestHistory, Approval::Assignment, # BizCalendar BizCalendar::Place, BizCalendar::HolidayType, BizCalendar::BussinessHoliday, BizCalendar::BussinessHour, BizCalendar::ExceptionHoliday, # Feed Feed::Feed, Feed::FeedEntry, # Gnav Gnav::MenuItem, Gnav::CategorySet, # GpArticle GpArticle::Doc, GpArticle::DocsTagTag, GpArticle::Hold, GpArticle::RelatedDoc, # GpCategory GpCategory::CategoryType, GpCategory::Category, GpCategory::Categorization, GpCategory::TemplateModule, GpCategory::Template, # GpTemplate GpTemplate::Template, GpTemplate::Item, # Map Map::Marker, Map::MarkerIcon, # Organization Organization::Group, # Rank Rank::Rank, Rank::Category, Rank::Total, # Reception Reception::Course, Reception::Open, Reception::Applicant, Reception::ApplicantToken, # Survey Survey::Form, Survey::Question, Survey::FormAnswer, Survey::Answer, # Tag Tag::Tag ] require 'postgres-copy' models.each do |model| unless model.respond_to?(:copy_to) model.class_eval do acts_as_copy_target # postgres-copy end end end models end def load_id_map(site) id_map = HashWithIndifferentAccess.new load_ids_from_sys(site, id_map) load_ids_from_cms(site, id_map) load_ids_from_ad_banner(site, id_map) load_ids_from_approval(site, id_map) load_ids_from_biz_calendar(site, id_map) load_ids_from_feed(site, id_map) load_ids_from_gnav(site, id_map) load_ids_from_gp_article(site, id_map) load_ids_from_gp_calendar(site, id_map) load_ids_from_gp_category(site, id_map) load_ids_from_gp_template(site, id_map) load_ids_from_map(site, id_map) load_ids_from_organization(site, id_map) load_ids_from_rank(site, id_map) load_ids_from_reception(site, id_map) load_ids_from_survey(site, id_map) load_ids_from_tag(site, id_map) load_ids_from_polymorphic_tables(site, id_map) id_map end def load_ids_from_sys(site, id_map) id_map[:sys_groups] = Sys::Group.in_site(site).pluck(:id) id_map[:sys_messages] = Sys::Message.where(site_id: site.id).pluck(:id) id_map[:sys_operation_logs] = Sys::OperationLog.where(site_id: site.id).pluck(:id) id_map[:sys_process_logs] = Sys::ProcessLog.where(site_id: site.id).pluck(:id) id_map[:sys_processes] = Sys::Process.where(site_id: site.id).pluck(:id) id_map[:sys_role_names] = Sys::RoleName.where(site_id: site.id).pluck(:id) id_map[:sys_object_privileges] = Sys::ObjectPrivilege.where(role_id: id_map[:sys_role_names]).pluck(:id) id_map[:sys_sequences] = Sys::Sequence.where(site_id: site.id).pluck(:id) id_map[:sys_storage_files] = Sys::StorageFile.where(Sys::StorageFile.arel_table[:path].matches("#{Rails.root}/sites/#{format('%04d', site.id)}/%")).pluck(:id) id_map[:sys_users] = Sys::User.in_site(site).pluck(:id) id_map[:sys_users_groups] = Sys::UsersGroup.where(group_id: id_map[:sys_groups]).pluck(:id) end def load_ids_from_cms(site, id_map) id_map[:cms_brackets] = Cms::Bracket.where(site_id: site.id).pluck(:id) id_map[:cms_concepts] = Cms::Concept.where(site_id: site.id).pluck(:id) id_map[:cms_contents] = Cms::Content.where(site_id: site.id).pluck(:id) id_map[:cms_content_settings] = Cms::ContentSetting.where(content_id: id_map[:cms_contents]).pluck(:id) id_map[:cms_data_file_nodes] = Cms::DataFileNode.where(site_id: site.id).pluck(:id) id_map[:cms_data_files] = Cms::DataFile.where(site_id: site.id).pluck(:id) id_map[:cms_data_texts] = Cms::DataText.where(site_id: site.id).pluck(:id) id_map[:cms_kana_dictionaries] = Cms::KanaDictionary.where(site_id: site.id).pluck(:id) id_map[:cms_layouts] = Cms::Layout.where(site_id: site.id).pluck(:id) id_map[:cms_nodes] = Cms::Node.where(site_id: site.id).pluck(:id) id_map[:cms_pieces] = Cms::Piece.where(site_id: site.id).pluck(:id) id_map[:cms_piece_settings] = Cms::PieceSetting.where(piece_id: id_map[:cms_pieces]).pluck(:id) id_map[:cms_piece_link_items] = Cms::PieceLinkItem.where(piece_id: id_map[:cms_pieces]).pluck(:id) id_map[:cms_sites] = Cms::Site.where(id: site.id).pluck(:id) id_map[:cms_site_belongings] = Cms::SiteBelonging.where(site_id: site.id).pluck(:id) id_map[:cms_site_basic_auth_users] = Cms::SiteBasicAuthUser.where(site_id: site.id).pluck(:id) id_map[:cms_site_settings] = Cms::SiteSetting.where(site_id: site.id).pluck(:id) id_map[:cms_stylesheets] = Cms::Stylesheet.where(site_id: site.id).pluck(:id) end def load_ids_from_ad_banner(site, id_map) id_map[:ad_banner_banners] = AdBanner::Banner.where(content_id: id_map[:cms_contents]).pluck(:id) id_map[:ad_banner_clicks] = AdBanner::Click.where(banner_id: id_map[:ad_banner_banners]).pluck(:id) id_map[:ad_banner_groups] = AdBanner::Group.where(content_id: id_map[:cms_contents]).pluck(:id) end def load_ids_from_approval(site, id_map) id_map[:approval_approval_flows] = Approval::ApprovalFlow.where(content_id: id_map[:cms_contents]).pluck(:id) id_map[:approval_approvals] = Approval::Approval.where(approval_flow_id: id_map[:approval_approval_flows]).pluck(:id) id_map[:approval_approval_requests] = Approval::ApprovalRequest.where(approval_flow_id: id_map[:approval_approval_flows]).pluck(:id) id_map[:approval_approval_request_histories] = Approval::ApprovalRequestHistory.where(request_id: id_map[:approval_approval_requests]).pluck(:id) end def load_ids_from_biz_calendar(site, id_map) id_map[:biz_calendar_places] = BizCalendar::Place.where(content_id: id_map[:cms_contents]).pluck(:id) id_map[:biz_calendar_holiday_types] = BizCalendar::HolidayType.where(content_id: id_map[:cms_contents]).pluck(:id) id_map[:biz_calendar_bussiness_holidays] = BizCalendar::BussinessHoliday.where(place_id: id_map[:biz_calendar_places]).pluck(:id) id_map[:biz_calendar_bussiness_hours] = BizCalendar::BussinessHour.where(place_id: id_map[:biz_calendar_places]).pluck(:id) id_map[:biz_calendar_exception_holidays] = BizCalendar::ExceptionHoliday.where(place_id: id_map[:biz_calendar_places]).pluck(:id) end def load_ids_from_feed(site, id_map) id_map[:feed_feeds] = Feed::Feed.where(content_id: id_map[:cms_contents]).pluck(:id) id_map[:feed_feed_entries] = Feed::FeedEntry.where(content_id: id_map[:cms_contents]).pluck(:id) end def load_ids_from_gnav(site, id_map) id_map[:gnav_menu_items] = Gnav::MenuItem.where(content_id: id_map[:cms_contents]).pluck(:id) id_map[:gnav_category_sets] = Gnav::CategorySet.where(menu_item_id: id_map[:gnav_menu_items]).pluck(:id) end def load_ids_from_gp_article(site, id_map) id_map[:gp_article_docs] = GpArticle::Doc.where(content_id: id_map[:cms_contents]).pluck(:id) id_map[:gp_article_docs_tag_tags] = GpArticle::DocsTagTag.where(doc_id: id_map[:gp_article_docs]).pluck(:id) id_map[:gp_article_related_docs] = GpArticle::RelatedDoc.where(relatable_id: id_map[:gp_article_docs]).pluck(:id) end def load_ids_from_gp_calendar(site, id_map) id_map[:gp_calendar_events] = GpCalendar::Event.where(content_id: id_map[:cms_contents]).pluck(:id) id_map[:gp_calendar_holidays] = GpCalendar::Holiday.where(content_id: id_map[:cms_contents]).pluck(:id) end def load_ids_from_gp_category(site, id_map) id_map[:gp_category_category_types] = GpCategory::CategoryType.where(content_id: id_map[:cms_contents]).pluck(:id) id_map[:gp_category_categories] = GpCategory::Category.where(category_type_id: id_map[:gp_category_category_types]).pluck(:id) id_map[:gp_category_categorizations] = GpCategory::Categorization.where(category_id: id_map[:gp_category_categories]).pluck(:id) id_map[:gp_category_template_modules] = GpCategory::TemplateModule.where(content_id: id_map[:cms_contents]).pluck(:id) id_map[:gp_category_templates] = GpCategory::Template.where(content_id: id_map[:cms_contents]).pluck(:id) end def load_ids_from_gp_template(site, id_map) id_map[:gp_template_templates] = GpTemplate::Template.where(content_id: id_map[:cms_contents]).pluck(:id) id_map[:gp_template_items] = GpTemplate::Item.where(template_id: id_map[:gp_template_templates]).pluck(:id) end def load_ids_from_map(site, id_map) id_map[:map_markers] = Map::Marker.where(content_id: id_map[:cms_contents]).pluck(:id) id_map[:map_marker_icons] = Map::MarkerIcon.where(content_id: id_map[:cms_contents]).pluck(:id) end def load_ids_from_organization(site, id_map) id_map[:organization_groups] = Organization::Group.where(content_id: id_map[:cms_contents]).pluck(:id) end def load_ids_from_rank(site, id_map) id_map[:rank_ranks] = Rank::Rank.where(content_id: id_map[:cms_contents]).pluck(:id) id_map[:rank_categories] = Rank::Category.where(content_id: id_map[:cms_contents]).pluck(:id) id_map[:rank_totals] = Rank::Total.where(content_id: id_map[:cms_contents]).pluck(:id) end def load_ids_from_reception(site, id_map) id_map[:reception_courses] = Reception::Course.where(content_id: id_map[:cms_contents]).pluck(:id) id_map[:reception_opens] = Reception::Open.where(course_id: id_map[:reception_courses]).pluck(:id) id_map[:reception_applicants] = Reception::Applicant.where(open_id: id_map[:reception_opens]).pluck(:id) id_map[:reception_applicant_tokens] = Reception::ApplicantToken.where(open_id: id_map[:reception_opens]).pluck(:id) end def load_ids_from_survey(site, id_map) id_map[:survey_forms] = Survey::Form.where(content_id: id_map[:cms_contents]).pluck(:id) id_map[:survey_questions] = Survey::Question.where(form_id: id_map[:survey_forms]).pluck(:id) id_map[:survey_form_answers] = Survey::FormAnswer.where(form_id: id_map[:survey_forms]).pluck(:id) id_map[:survey_answers] = Survey::Answer.where(form_answer_id: id_map[:survey_form_answers]).pluck(:id) end def load_ids_from_tag(site, id_map) id_map[:tag_tags] = Tag::Tag.where(content_id: id_map[:cms_contents]).pluck(:id) end def load_ids_from_polymorphic_tables(site, id_map) poly_models = { Sys::Creator => [:creatable_type, :creatable_id], Sys::EditableGroup => [:editable_type, :editable_id], Sys::Editor => [:editable_type, :editable_id], Sys::File => [:file_attachable_type, :file_attachable_id], Sys::ObjectRelation => [:source_type, :source_id], Sys::Publisher => [:publishable_type, :publishable_id], Sys::Recognition => [:recognizable_type, :recognizable_id], Sys::Task => [:processable_type, :processable_id], Cms::Inquiry => [:inquirable_type, :inquirable_id], Cms::Link => [:linkable_type, :linkable_id], Cms::LinkCheckLog => [:link_checkable_type, :link_checkable_id], Cms::Map => [:map_attachable_type, :map_attachable_id], Cms::Publisher => [:publishable_type, :publishable_id], Cms::TalkTask => [:talk_processable_type, :talk_processable_id], Approval::Assignment => [:assignable_type, :assignable_id], GpArticle::Hold => [:holdable_type, :holdable_id] } poly_models.each do |model, (ptype, pkey)| types = model.group(ptype).pluck(ptype).compact id_map[model.table_name] = if types.present? model.union( types.map { |type| model.where(ptype => type, pkey => id_map[type.tableize.sub('/', '_')]) } ).pluck(:id) else [] end end id_map[:cms_map_markers] = Cms::MapMarker.where(map_id: id_map[:cms_maps]).pluck(:id) end end end end <file_sep>module BizCalendar::BizCalendarHelper def localize_ampm(style, time) style.gsub!('%H', '%I') if style =~ /%P/ style.gsub('%P', I18n.t("time.#{time.strftime('%P')}")) end end <file_sep>class CreateCmsLinks < ActiveRecord::Migration[5.0] def up create_table :cms_links do |t| t.integer :content_id t.string :linkable_type t.integer :linkable_id t.string :body t.string :url t.timestamps end GpArticle::Link.all.each do |l| Cms::Link.create({ content_id: l.doc.try(:content_id), linkable_type: 'GpArticle::Doc', linkable_id: l.doc_id, body: l.body, url: l.url }) end Cms::Node::Page.public_state.each do |p| next unless lib = p.links_in_body lib.each do |link| p.links.create(body: link[:body], url: link[:url], content_id: p.content_id) end end end def down drop_table :cms_links end end <file_sep>require 'digest/md5' module Cms::Model::Base::Page::Publisher def self.included(mod) mod.has_many :publishers, class_name: 'Sys::Publisher', dependent: :destroy, as: :publishable mod.after_save :close_page end def public_status return published_at ? '公開中' : '非公開' end def public_path return '' unless public_uri Page.site.public_path + public_uri end def public_uri '/'#TODO end def preview_uri(options = {}) return nil unless public_uri site = options[:site] || Page.site mobile = options[:mobile] ? 'm' : options[:smart_phone] ? 's' : nil params = [] options[:params].each {|k, v| params << "#{k}=#{v}" } if options[:params] params = params.size > 0 ? "?#{params.join('&')}" : "" path = "_preview/#{format('%04d', site.id)}#{mobile}#{public_uri}#{params}" "#{site.main_admin_uri}#{path}" end def publish_uri(options = {}) site = options[:site] || Page.site "#{site.full_uri}_publish/#{format('%04d', site.id)}#{public_uri}" end def publishable? return false unless editable? if respond_to?(:state_approved?) return false unless state_approved? else return false unless recognized? end return true end def rebuildable? return false unless editable? return state == 'public'# && published_at end def closable? return false unless editable? return state == 'public'# && published_at end def mobile_page? false end def published? @published end def publish_page(content, options = {}) @published = false return false if content.nil? content = content.gsub(%r!zdel_.+?/!i, '') path = (options[:path] || public_path).gsub(/\/\z/, '/index.html') hash = Digest::MD5.new.update(content).to_s pub = publishers.where(dependent: options[:dependent] ? options[:dependent].to_s : nil).first return true if mobile_page? return true if hash && pub && hash == pub.content_hash && ::File.exist?(path) clean_statics = Zomeki.config.application['sys.clean_statics'] if clean_statics if File.exist?(path) File.delete(path) info_log "DELETED: #{path}" end @published = true else if ::File.exist?(path) && ::File.new(path).read == content #FileUtils.touch([path]) else Util::File.put(path, :data => content, :mkdir => true) @published = true end end pub ||= Sys::Publisher.new pub.publishable = self pub.dependent = options[:dependent] ? options[:dependent].to_s : nil pub.path = path pub.content_hash = hash pub.save if pub.changed? return true end def close_page(options = {}) publishers.destroy_all return true end end <file_sep>class Cms::Publisher::PieceRelatedCallbacks < PublisherCallbacks def after_save(item) @item = item enqueue if enqueue? end def before_destroy(item) @item = item enqueue if enqueue? end def enqueue(item = nil) @item = item if item enqueue_pieces end private def enqueue? true end def enqueue_pieces Cms::Publisher::PieceCallbacks.new.enqueue(@item.piece) if @item.piece.state == 'public' end end <file_sep>class Rank::RanksScript < Cms::Script::Base include Rank::Controller::Rank def exec contents = Rank::Content::Rank.all contents = contents.where(site_id: ::Script.site.id) if ::Script.site ::Script.total contents.size contents.each do |content| ::Script.progress(content) do get_access(content, Time.now - 3.days) calc_access(content) end end end end <file_sep>class Cms::Admin::Inline::DataFileNodesController < Cms::Admin::Data::FileNodesController layout 'admin/files' end <file_sep>module Sys::Lib::File::Transfer require "rsync" def transfer_files(options={}) load_transfer_settings # options _logging = options[:logging] || true _trial = options.has_key?(:trial) ? options[:trial] : false; _user_id = options[:user] || Core.user.id rescue nil; _sites = options[:sites] || Cms::Site.where(:state => 'public').order(:id) _files = options[:files] _version = options[:version] || Time.now.to_i result = {:version => _version, :sites => {} } _sites.each do |site| site = Cms::Site.find_by(id: site) if site.is_a?(Integer) _settings = get_transfer_site_settings site next if _settings.size <= 0 result[:sites][site.id] = [] dest_addr = _settings[:dest_dir] dest = if _settings[:dest_user].to_s != '' && _settings[:dest_host].to_s != '' dest_addr = "#{_settings[:dest_user]}@#{_settings[:dest_host]}:#{_settings[:dest_dir]}" @opt_remote_shell ? "-e \"#{@opt_remote_shell}\" #{dest_addr}" : dest_addr; else dest_addr end _ready_options = lambda do |include_file, file_base| options = [] options << "-n" if _trial if include_file options << "--include-from=#{include_file.path}" else if file_base =='common' && @opt_include options << "--include-from=#{Rails.root}/#{@opt_include}" end if file_base =='site' && @opt_exclude options << "--exclude-from=#{Rails.root}/#{@opt_exclude}" end end options << @opts if @opts return options end _rsync = lambda do |src, dest, command_opts| rsync(src, dest, command_opts) do |res| return res unless _logging parent_dir = src.gsub(/#{Rails.root}/, '.') res.changes.each do |change| update_type = change.update_type file_type = change.file_type next if update_type == :no_update operation = if ([:sent, :recv].include?(update_type) && change.timestamp == :new) || (file_type == :directory && update_type == :change) :create elsif update_type == :message && change.summary == 'deleting' :delete elsif [change.checksum, change.size, change.timestamp].include?(:changed) :update end # save attrs = { :site_id => site.id, :user_id => _user_id, :version => _version, :operation => operation, :file_type => file_type, :parent_dir => parent_dir, :path => change.filename, :destination => dest_addr, } model = _trial ? Sys::TransferableFile : Sys::TransferredFile; model = model.new(attrs) model.user_id = _user_id if model.file? model.item_id = model.item_info :item_id model.item_unid = model.item_info :item_unid model.item_model = model.item_info :item_model model.item_name = model.item_info :item_name model.operated_at = model.item_info :operated_at model.operator_id = model.item_info :operator_id model.operator_name = model.item_info :operator_name end model.save end end end # sync common_src = "#{Rails.root}/public/" site_src = "#{site.public_path}/" if _files if common_include_file = create_include_pattern_file(_files, common_src.gsub(/#{Rails.root}/, '.')) options = _ready_options.call(common_include_file, 'common') result[:sites][site.id] << _rsync.call(common_src, dest, options).status common_include_file.unlink end if site_include_file = create_include_pattern_file(_files, site_src.gsub(/#{Rails.root}/, '.')) options = _ready_options.call(site_include_file, 'site') result[:sites][site.id] << _rsync.call(site_src, dest, options).status site_include_file.unlink end else # sync all options = _ready_options.call(nil, 'common') result[:sites][site.id] << _rsync.call(common_src, dest, options).status options = _ready_options.call(nil, 'site') result[:sites][site.id] << _rsync.call(site_src, dest, options).status end end result rescue nil end protected def load_transfer_settings @opts = Zomeki.config.application['sys.transfer_opts'] @opt_exclude = Zomeki.config.application['sys.transfer_opt_exclude'] @opt_include = Zomeki.config.application['sys.transfer_opt_include'] @opt_remote_shell = Zomeki.config.application['sys.transfer_opt_remote_shell'] end def get_transfer_site_settings(site) _settings = {} _settings[:dest_user] = site.setting_transfer_dest_user _settings[:dest_host] = site.setting_transfer_dest_host _settings[:dest_dir] = site.setting_transfer_dest_dir _settings.reject!{|key, value| value.blank? } return {} unless _settings[:dest_dir] _settings end def create_include_pattern_file(ids, node, options={}) return nil unless ids return nil if ids.size <= 0 paths = [] Sys::TransferableFile.where(:parent_dir => node, :id => ids).each do |f| nodes = f.path.split('/') nodes.each_index do |i| path = nodes[0 .. i].join('/') path = "#{path}/" unless f.path == path paths << path end end return nil if paths.size <= 0 require 'tempfile' file = Tempfile.new(['cms_rsync_include', '.lst']) begin paths.each {|path| file.print("+ #{path}\n") } file.print("- *\n") ensure file.close #file.unlink end file end def rsync(src, dest, options=[], &block) res = Rsync.run(src, dest, options) yield(res) if block_given? res end end <file_sep>class Cms::SitemapsScript < Cms::Script::Publication def publish publish_page(@node, uri: @node.public_uri, site: @node.site, path: @node.public_path) end end <file_sep>module Organization::OrganizationHelper def group_li(group, list_style, depth_limit: 1000, depth: 1) content_tag(:li) do result = group_replace(group, list_style) if group.public_children.empty? || depth >= depth_limit result else result << content_tag(:ul) do group.public_children.inject(''){|lis, child| lis << group_li(child, list_style, depth_limit: depth_limit, depth: depth + 1) }.html_safe end end end end def group_replace(group, list_style) contents = { name: -> { group_replace_name(group) }, name_link: -> { group_replace_name_link(group) }, address: -> { group_replace_address(group) }, tel: -> { group_replace_tel(group) }, tel_attend: -> { group_replace_tel_attend(group) }, fax: -> { group_replace_fax(group) }, email: -> { group_replace_email(group) }, email_link: -> { group_replace_email_link(group) }, note: -> { group_replace_note(group) }, } if Page.mobile? contents[:name_link].call else list_style = list_style.gsub(/@(\w+)@/) { |m| contents[$1.to_sym].try(:call).to_s } list_style.html_safe end end private def group_replace_name(group) if (sg = group.sys_group) && sg.name.present? content_tag :span, sg.name, class: 'name' else '' end end def group_replace_name_link(group) if (sg = group.sys_group) && sg.name.present? content_tag :span, class: 'name' do link_to sg.name, group.public_uri end else '' end end def group_replace_address(group) if (sg = group.sys_group) && sg.address.present? content_tag :span, sg.address, class: 'address' else '' end end def group_replace_tel(group) if (sg = group.sys_group) && sg.tel.present? content_tag :span, sg.tel, class: 'tel' else '' end end def group_replace_tel_attend(group) if (sg = group.sys_group) && sg.tel_attend.present? content_tag :span, sg.tel_attend, class: 'tel_attend' else '' end end def group_replace_fax(group) if (sg = group.sys_group) && sg.fax.present? content_tag :span, sg.fax, class: 'fax' else '' end end def group_replace_email(group) if (sg = group.sys_group) && sg.email.present? content_tag :span, sg.email, class: 'email' else '' end end def group_replace_email_link(group) if (sg = group.sys_group) && sg.email.present? content_tag :span, class: 'email' do mail_to sg.email end else '' end end def group_replace_note(group) if (sg = group.sys_group) && sg.note.present? content_tag :span, sg.note, class: 'note' else '' end end end <file_sep>namespace :delayed_job do def delayed_job "RAILS_ENV=#{Rails.env} bin/delayed_job" end def delayed_job_options options = [ "--pool=sys_tasks:#{task_workers}", "--pool=cms_rebuild:#{rebuild_workers}", "--pool=cms_publisher:#{publisher_workers}" ] options.join(' ') end def task_workers (ENV['TASK_WORKERS'] || 1).to_i end def rebuild_workers (ENV['REBUILD_WORKERS'] || 1).to_i end def publisher_workers (ENV['PUBLISHER_WORKERS'] || 1).to_i end def max_memory (ENV['DELAYED_JOB_MAX_MEMORY'] || 1024*512).to_i end def start sh "#{delayed_job} start #{delayed_job_options}" end def stop sh "#{delayed_job} stop #{delayed_job_options}" end def restart sh "#{delayed_job} restart #{delayed_job_options}" end def status sh "#{delayed_job} status #{delayed_job_options}" end def delayed_job_pids Dir["#{Rails.root}/tmp/pids/delayed_job*.pid"].map do |file| File.read(file).to_i end end def delayed_job_running? Delayed::Job.where.not(locked_at: nil).exists? end desc 'Start delayed job' task start: :environment do start end desc 'Stop delayed job' task stop: :environment do stop end desc 'Restart delayed job' task restart: :environment do restart end desc 'Monitor delayed job' task monitor: :environment do pids = delayed_job_pids procs = `ps uh --pid #{pids.join(',')}`.split("\n").map(&:split) if procs.size == 0 start elsif procs.size < pids.size && !delayed_job_running? restart end end desc 'Check delayed job status' task status: :environment do status end end <file_sep>class Sys::Closer < ApplicationRecord include Sys::Model::Base end <file_sep>class AdBanner::Banner < ApplicationRecord include Sys::Model::Base include Sys::Model::Base::File include Sys::Model::Rel::Creator include Cms::Model::Auth::Content include StateText STATE_OPTIONS = [['公開', 'public'], ['非公開', 'closed']] TARGET_OPTIONS = [['同一ウィンドウ', '_self'], ['別ウィンドウ', '_blank']] default_scope { order(:sort_no) } banners = self.arel_table scope :published, -> { now = Time.now where(banners[:state].eq('public') .and(banners[:published_at].eq(nil).or(banners[:published_at].lteq(now)) .and(banners[:closed_at].eq(nil).or(banners[:closed_at].gt(now))))) } scope :closed, -> { now = Time.now where(banners[:state].eq('closed') .or(banners[:published_at].gt(now)) .or(banners[:closed_at].lteq(now))) } # Content belongs_to :content, :foreign_key => :content_id, :class_name => 'AdBanner::Content::Banner' validates :content_id, presence: true # Proper validates :state, presence: true belongs_to :group, :foreign_key => :group_id, :class_name => 'AdBanner::Group' has_many :clicks, :foreign_key => :banner_id, :class_name => 'AdBanner::Click', :dependent => :destroy validates :advertiser_name, :presence => true validates :url, :presence => true after_initialize :set_defaults before_create :set_token after_save Cms::Publisher::ContentRelatedCallbacks.new, if: :changed? before_destroy Cms::Publisher::ContentRelatedCallbacks.new def image_uri return '' unless content.public_node "#{content.public_node.public_uri}#{name}" end def image_path return '' unless content.public_node "#{content.public_node.public_path}#{name}" end def image_mobile_path return '' unless content.public_node "#{content.public_node.public_mobile_path}#{name}" end def image_smart_phone_path return '' unless content.public_node "#{content.public_node.public_smart_phone_path}#{name}" end def link_uri return '' unless content.public_node "#{content.public_node.public_uri}#{token}" end def target_text TARGET_OPTIONS.detect{|o| o.last == self.target }.try(:first).to_s end def publish_or_close_image if published? [image_path, image_mobile_path, image_smart_phone_path].each do |path| next if path == image_smart_phone_path && !self.content.site.publish_for_smart_phone? FileUtils.mkdir_p ::File.dirname(path) FileUtils.cp upload_path, path end else [image_path, image_mobile_path, image_smart_phone_path].each do |path| FileUtils.rm image_path if ::File.exist?(path) FileUtils.rmdir ::File.dirname(path) end end end def published? now = Time.now (state == 'public') && (published_at.nil? || published_at <= now) && (closed_at.nil? || closed_at > now) end def closed? !published? end private def set_defaults self.state ||= STATE_OPTIONS.first.last if self.has_attribute?(:state) self.target ||= TARGET_OPTIONS.last.last if self.has_attribute?(:target) self.sort_no ||= 10 if self.has_attribute?(:sort_no) end def set_token self.token = Util::String::Token.generate_unique_token(self.class, :token) end # Override Sys::Model::Base::File#duplicated? def duplicated? banners = self.class.arel_table not self.class.where(content_id: self.content_id, name: self.name).where(banners[:id].not_eq(self.id)).empty? end end <file_sep>require 'will_paginate/array' class GpCategory::Public::Node::CategoryTypesController < GpCategory::Public::Node::BaseController def index if (template = @content.index_template) return http_error(404) if params[:page] vc = view_context rendered = template.body.gsub(/\[\[module\/([\w-]+)\]\]/) do |matched| tm = @content.template_modules.find_by(name: $1) next unless tm case tm.module_type when 'categories_1', 'categories_2', 'categories_3' if vc.respond_to?(tm.module_type) @content.public_category_types.inject(''){|tags, category_type| tags << vc.content_tag(:section, class: category_type.name) do html = vc.content_tag(:h2, vc.link_to(category_type.title, category_type.public_uri)) html << vc.send(tm.module_type, template_module: tm, categories: category_type.public_root_categories) end } end when 'categories_summary_1', 'categories_summary_2', 'categories_summary_3' if vc.respond_to?(tm.module_type) @content.public_category_types.inject(''){|tags, category_type| tags << vc.content_tag(:section, class: category_type.name) do title_tag = vc.content_tag(:h2, category_type.title) title_tag << vc.content_tag(:span, category_type.description, class: 'category_summary') if category_type.description.present? html = vc.link_to(title_tag, category_type.public_uri) html << vc.send(tm.module_type, template_module: tm, categories: category_type.public_root_categories) end } end when 'docs_1' if vc.respond_to?(tm.module_type) category_ids = @content.public_category_types.inject([]){|ids, category_type| ids.concat(category_type.public_root_categories.inject([]){|is, category| is.concat(category.public_descendants.map(&:id)) }) } docs = find_public_docs_with_category_id(category_ids) docs = docs.where(content_id: tm.gp_article_content_ids) if tm.gp_article_content_ids.present? all_docs = docs.order(display_published_at: :desc, published_at: :desc) docs = all_docs.limit(tm.num_docs) vc.send(tm.module_type, template_module: tm, ct_or_c: nil, docs: docs, all_docs: all_docs) end else '' end end render html: vc.content_tag(:div, rendered.html_safe, class: 'contentGpCategory contentGpCategoryCategoryTypes').html_safe else @category_types = @content.public_category_types.paginate(page: params[:page], per_page: 20) .preload_assocs(:public_node_ancestors_assocs) return http_error(404) if @category_types.current_page > @category_types.total_pages render :index_mobile if Page.mobile? end end def show @category_type = @content.public_category_types.find_by(name: params[:name]) return http_error(404) unless @category_type if params[:format].in?(['rss', 'atom']) case @content.category_type_style when 'all_docs' category_ids = @category_type.public_categories.pluck(:id) @docs = find_public_docs_with_category_id(category_ids).order(display_published_at: :desc, published_at: :desc) @docs = @docs.display_published_after(@content.feed_docs_period.to_i.days.ago) if @content.feed_docs_period.present? @docs = @docs.paginate(page: params[:page], per_page: @content.feed_docs_number) return render_feed(@docs) else return http_error(404) end end Page.current_item = @category_type Page.title = @category_type.title per_page = (@more ? 30 : @content.category_type_docs_number) if (template = @category_type.template) if @more @template_module = template.containing_modules.detect { |m| m.name == @more_options.first } category_ids = @category_type.public_root_categories.inject([]){|ids, category| ids.concat(category.public_descendants.map(&:id)) } @docs = find_public_docs_with_category_id(category_ids) if @template_module && @template_module.gp_article_content_ids.present? @docs.where!(content_id: @template_module.gp_article_content_ids) end if (filter = @more_options[1]) prefix, code_or_name = filter.split('_', 2) case prefix when 'c' return http_error(404) unless @category_type.internal_category_type internal_category = @category_type.internal_category_type.public_root_categories.find_by(name: code_or_name) return http_error(404) unless internal_category categorizations = GpCategory::Categorization.where(categorizable_type: 'GpArticle::Doc', categorized_as: 'GpArticle::Doc', categorizable_id: @docs.pluck(:id), category_id: internal_category.public_descendants.map(&:id)) @docs = GpArticle::Doc.where(id: categorizations.pluck(:categorizable_id)) when 'g' group = Sys::Group.in_site(Page.site).where(code: code_or_name).first return http_error(404) unless group @docs = @docs.joins(creator: :group).where(Sys::Group.arel_table[:id].eq(group.id)) end end @docs = @docs.order(display_published_at: :desc, published_at: :desc).paginate(page: params[:page], per_page: per_page) return http_error(404) if @docs.current_page > @docs.total_pages render :more else return http_error(404) if params[:page] vc = view_context rendered = template.body.gsub(/\[\[module\/([\w-]+)\]\]/) do |matched| tm = @content.template_modules.find_by(name: $1) next unless tm case tm.module_type when 'categories_1', 'categories_2', 'categories_3' if vc.respond_to?(tm.module_type) @category_type.public_root_categories.inject(''){|tags, category| tags << vc.content_tag(:section, class: category.name) do html = vc.content_tag(:h2, vc.link_to(category.title, category.public_uri)) html << vc.send(tm.module_type, template_module: tm, categories: category.public_children) end } end when 'categories_summary_1', 'categories_summary_2', 'categories_summary_3' if vc.respond_to?(tm.module_type) @category_type.public_root_categories.inject(''){|tags, category| tags << vc.content_tag(:section, class: category.name) do title_tag = vc.content_tag(:h2, category.title) title_tag << vc.content_tag(:span, category.description, class: 'category_summary') if category.description.present? html = vc.link_to(title_tag, category.public_uri) html << vc.send(tm.module_type, template_module: tm, categories: category.public_children) end } end when 'docs_1' if vc.respond_to?(tm.module_type) category_ids = @category_type.public_root_categories.inject([]){|ids, category| ids.concat(category.public_descendants.map(&:id)) } docs = find_public_docs_with_category_id(category_ids) docs = docs.where(content_id: tm.gp_article_content_ids) if tm.gp_article_content_ids.present? all_docs = docs.order(display_published_at: :desc, published_at: :desc) docs = all_docs.limit(tm.num_docs) vc.send(tm.module_type, template_module: tm, ct_or_c: @category_type, docs: docs, all_docs: all_docs) end when 'docs_3' if vc.respond_to?(tm.module_type) && @category_type.internal_category_type category_ids = @category_type.public_root_categories.inject([]){|ids, category| ids.concat(category.public_descendants.map(&:id)) } docs = find_public_docs_with_category_id(category_ids) docs = docs.where(content_id: tm.gp_article_content_ids) if tm.gp_article_content_ids.present? categorizations = GpCategory::Categorization.where(categorizable_type: 'GpArticle::Doc', categorizable_id: docs.pluck(:id), categorized_as: 'GpArticle::Doc') vc.send(tm.module_type, template_module: tm, ct_or_c: @category_type, categories: @category_type.internal_category_type.public_root_categories, categorizations: categorizations) end when 'docs_5' if vc.respond_to?(tm.module_type) category_ids = @category_type.public_root_categories.inject([]){|ids, category| ids.concat(category.public_descendants.map(&:id)) } docs = find_public_docs_with_category_id(category_ids) docs = docs.where(content_id: tm.gp_article_content_ids) if tm.gp_article_content_ids.present? docs = docs.joins(:creator => :group) groups = Sys::Group.where(id: docs.select(Sys::Group.arel_table[:id]).distinct) vc.send(tm.module_type, template_module: tm, ct_or_c: @category_type, groups: groups, docs: docs) end when 'docs_7', 'docs_8' if vc.respond_to?(tm.module_type) category_ids = @category_type.public_root_categories.inject([]){|ids, category| ids.concat(category.public_descendants.map(&:id)) } docs = find_public_docs_with_category_id(category_ids) docs = docs.where(content_id: tm.gp_article_content_ids) if tm.gp_article_content_ids.present? categorizations = GpCategory::Categorization.where(categorizable_type: 'GpArticle::Doc', categorizable_id: docs.pluck(:id), categorized_as: 'GpArticle::Doc') vc.send(tm.module_type, template_module: tm, categories: @category_type.public_root_categories, categorizations: categorizations) end else '' end end render html: vc.content_tag(:div, rendered.html_safe, class: 'contentGpCategory contentGpCategoryCategoryType').html_safe end else case @content.category_type_style when 'all_docs' category_ids = @category_type.public_categories.pluck(:id) @docs = find_public_docs_with_category_id(category_ids).order(display_published_at: :desc, published_at: :desc) .paginate(page: params[:page], per_page: @content.category_type_docs_number) .preload_assocs(:public_node_ancestors_assocs, :public_index_assocs).to_a return http_error(404) if @docs.current_page > @docs.total_pages else return http_error(404) if params[:page].to_i > 1 end if Page.mobile? render :show_mobile else render @content.category_type_style if @content.category_type_style.present? end end end end <file_sep>namespace :zomeki do namespace :ad_banner do namespace :clicks do desc 'Fetch ad_banner clicks' task :pull => :environment do next if ApplicationRecordSlave.slave_configs.blank? Cms::Site.order(:id).pluck(:id).each do |site_id| Script.run('ad_banner/clicks/pull', site_id: site_id, lock_by: :site) end end end end end <file_sep>class Cms::Feed < ApplicationRecord include Sys::Model::Base include Cms::Model::Base::Page include Sys::Model::Rel::Creator include Cms::Model::Rel::Content include Cms::Model::Rel::Concept include Cms::Model::Auth::Concept belongs_to :status, :foreign_key => :state, :class_name => 'Sys::Base::Status' has_many :entries, :foreign_key => :feed_id, :class_name => 'Cms::FeedEntry', :dependent => :destroy validates :name, :uri, :title, presence: true def public self.and "#{self.class.table_name}.state", 'public' self end def ass(alt = nil, &block) begin yield rescue NoMethodError => e if e.respond_to? :args and (e.args.nil? or (!e.args.blank? and e.args.first.nil?)) alt end end end def request_feed res = Util::Http::Request.get(uri) if res.status != 200 errors.add :base, "RequestError: #{uri}" return nil end return res.body end def update_feed unless xml = request_feed errors.add :base, "FeedRequestError: #{uri}" return false end require "rexml/document" doc = REXML::Document.new(xml) root = doc.root ## feed self.feed_id = root.elements['id'].text self.feed_type = nil self.feed_updated = root.elements['updated'].text self.feed_title = root.elements['title'].text root.each_element('link') do |l| self.link_alternate = l.attribute('href').to_s if l.attribute('rel').to_s == 'alternate' end self.entry_count ||= 20 save ## entries begin #require 'parsedate' require 'date/format' latest = [] root.get_elements('entry').each_with_index do |e, i| break if i >= self.entry_count entry_id = e.elements['id'].text entry_updated = e.elements['updated'].text if entry = Cms::FeedEntry.find_by(feed_id: self.id, entry_id: entry_id) #arr = ParseDate::parsedate(entry_updated) arr = Date._parse(entry_updated, false).values_at(:year, :mon, :mday, :hour, :min, :sec, :zone, :wday) new = Time::local(*arr[0..-3]).strftime('%s').to_i old = entry.entry_updated.strftime('%s').to_i if new <= old latest << entry.id next end else entry = Cms::FeedEntry.new end ## base entry.content_id = self.content_id entry.feed_id = self.id entry.state ||= 'public' entry.entry_id = entry_id entry.entry_updated = entry_updated entry.title = ass{e.elements['title'].text} entry.summary = ass{e.elements['summary'].text} ## links e.each_element('link') do |l| entry.link_alternate = l.attribute('href').to_s if l.attribute('rel').to_s == 'alternate' entry.link_enclosure = l.attribute('href').to_s if l.attribute('rel').to_s == 'enclosure' end ## categories, event_date categories = [] event_date = nil e.each_element('category') do |c| cate_label = c.attribute('label').to_s.gsub(/ /, '_') if c.attribute('term').to_s == 'event' _year, _month, _day = /(^|\n)イベント\/([0-9]{4})-([0-9]{2})-([0-9]{2})T/.match(cate_label).to_a.values_at(2, 3, 4) if _year && _month && _day begin event_date = Date.new(_year.to_i, _month.to_i, _day.to_i) rescue end end end categories << cate_label end entry.categories = categories.join("\n") entry.event_date = event_date ## author if author = e.elements['author'] entry.author_name = ass{author.elements['name'].text} entry.author_email = ass{author.elements['email'].text} entry.author_uri = ass{author.elements['uri'].text} end if entry.save latest << entry.id end end rescue Exception => e errors.add :base, "FeedEntryError: #{e}" end if latest.size > 0 Cms::FeedEntry.where.not(id: latest).where(feed_id: self.id).destroy_all end return errors.size == 0 rescue => e errors.add :base, "Error: #{e.class}" return false end end <file_sep>class GpArticle::Link < ApplicationRecord include Sys::Model::Base validates :doc_id, :presence => true belongs_to :doc end <file_sep>class GpCategory::Publisher::CategoryTypeCallbacks < PublisherCallbacks def after_save(category_type) @category_type = category_type enqueue if enqueue? end def before_destroy(category_type) @category_type = category_type enqueue if enqueue? end def enqueue(category_type = nil) @category_type = category_type if category_type enqueue_pieces enqueue_categories enqueue_docs enqueue_sitemap_nodes end private def enqueue? [@category_type.state, @category_type.state_was].include?('public') end def enqueue_pieces pieces = @category_type.content.public_pieces.sort { |p| p.model == 'GpCategory::RecentTab' ? 1 : 9 } pieces.each do |piece| Cms::Publisher::PieceCallbacks.new.enqueue(piece) end end def enqueue_categories Cms::Publisher.register(@category_type.content.site_id, @category_type.public_categories) end def enqueue_docs docs = @category_type.public_categories.flat_map { |c| c.docs.public_state.select(:id) } Cms::Publisher.register(@category_type.content.site_id, docs.uniq) end def enqueue_sitemap_nodes if [@category_type.sitemap_state, @category_type.sitemap_state_was].include?('visible') site = @category_type.content.site Cms::Publisher.register(site.id, site.public_sitemap_nodes) end end end <file_sep>module Tag::Tags::Preload extend ActiveSupport::Concern module ClassMethods def public_node_ancestors_assocs { content: { public_node: { site: nil, parent: parent_assocs } } } end private def parent_assocs(depth = 3) return nil if depth < 0 { parent: parent_assocs(depth - 1) } end end end <file_sep>module Cms::Model::Rel::Concept extend ActiveSupport::Concern included do belongs_to :concept, foreign_key: :concept_id, class_name: 'Cms::Concept' end end <file_sep>module Cms::Model::Rel::SiteSetting extend ActiveSupport::Concern attr_accessor :in_setting_site_basic_auth_state attr_accessor :in_setting_site_common_ssl attr_accessor :in_setting_site_admin_mail_sender attr_accessor :in_setting_site_file_upload_max_size attr_accessor :in_setting_site_extension_upload_max_size attr_accessor :in_setting_site_allowed_attachment_type attr_accessor :in_setting_site_link_check attr_accessor :in_setting_site_link_check_hour attr_accessor :in_setting_site_link_check_exclusion attr_accessor :in_setting_site_accessibility_check attr_accessor :in_setting_site_kana_talk attr_accessor :in_setting_site_map_coordinate SITE_SETTINGS = [ :basic_auth_state, :common_ssl, :allowed_attachment_type, :admin_mail_sender, :file_upload_max_size, :extension_upload_max_size, :link_check, :link_check_hour, :link_check_exclusion, :accessibility_check, :kana_talk, :map_coordinate ] included do after_save :save_site_settings end def setting_site_basic_auth_state setting = Cms::SiteSetting::BasicAuth.where(site_id: id).first setting ? setting.value : nil; end def use_basic_auth? setting_site_basic_auth_state == 'enabled' end def use_common_ssl? Sys::Setting.use_common_ssl? && setting_site_common_ssl == 'enabled' end def setting_site_common_ssl setting = Cms::SiteSetting.where(:site_id => id, :name => 'common_ssl').first setting ? setting.value : nil; end def setting_site_common_ssl_label setting = Cms::SiteSetting.where(:site_id => id, :name => 'common_ssl').first state = setting ? setting.value : nil; Cms::SiteSetting::SSL_OPTIONS.each{|a| return a[0] if a[1] == state} return nil end def setting_site_admin_mail_sender setting = Cms::SiteSetting.where(:site_id => id, :name => 'admin_mail_sender').first setting && setting.value.presence || 'noreply' end def setting_site_file_upload_max_size setting = Cms::SiteSetting.where(:site_id => id, :name => 'file_upload_max_size').first setting && setting.value.presence || 5 end def setting_site_extension_upload_max_size setting = Cms::SiteSetting.where(:site_id => id, :name => 'extension_upload_max_size').first setting ? setting.value : nil; end def setting_site_allowed_attachment_type setting = Cms::SiteSetting.where(:site_id => id, :name => 'allowed_attachment_type').first setting ? setting.value : ''; end def setting_site_link_check setting = Cms::SiteSetting.where(:site_id => id, :name => 'link_check').first setting ? setting.value : 'enabled'; end def setting_site_link_check_label Cms::SiteSetting::LINK_CHECK_OPTIONS.rassoc(setting_site_link_check).try(:first) end def setting_site_link_check_hour setting = Cms::SiteSetting.where(:site_id => id, :name => 'link_check_hour').first setting ? setting.value : nil; end def setting_site_link_check_exclusion setting = Cms::SiteSetting.where(:site_id => id, :name => 'link_check_exclusion').first setting ? setting.value : ''; end def link_check_hour?(hour) setting_site_link_check == 'enabled' && setting_site_link_check_hour == hour.to_s end def link_check_exclusion_regexp regexps = setting_site_link_check_exclusion.to_s.split(/[\r\n]+/).map { |ex| /^#{Regexp.escape(ex)}/ } regexps.present? ? Regexp.union(regexps) : nil end def setting_site_accessibility_check setting = Cms::SiteSetting.where(:site_id => id, :name => 'accessibility_check').first setting ? setting.value : 'enabled'; end def setting_site_accessibility_check_label Cms::SiteSetting::ACCESSIBILITY_CHECK_OPTIONS.rassoc(setting_site_accessibility_check).try(:first) end def setting_site_kana_talk setting = Cms::SiteSetting.where(:site_id => id, :name => 'kana_talk').first setting ? setting.value : 'enabled'; end def setting_site_kana_talk_label Cms::SiteSetting::KANA_TALK_OPTIONS.rassoc(setting_site_kana_talk).try(:first) end def setting_site_map_coordinate setting = Cms::SiteSetting.where(:site_id => id, :name => 'map_coordinate').first setting ? setting.value : nil; end def get_upload_max_size(ext) ext.gsub!(/^\./, '') list = ext_upload_max_size_list return list[ext.to_s] if list.include?(ext.to_s) return nil end def ext_upload_max_size_list return @ext_upload_max_size_list if @ext_upload_max_size_list csv = setting_site_extension_upload_max_size.to_s @ext_upload_max_size_list = {} csv.split(/(\r\n|\n)/u).each_with_index do |line, idx| line = line.to_s.gsub(/#.*/, "") line.strip! next if line.blank? data = line.split(/\s*,\s*/) ext = data[0].strip size = data[1].strip @ext_upload_max_size_list[ext.to_s] = size.to_i end if csv.present? return @ext_upload_max_size_list end def load_site_settings @in_setting_site_basic_auth_state = setting_site_basic_auth_state @in_setting_site_common_ssl = setting_site_common_ssl @in_setting_site_admin_mail_sender = setting_site_admin_mail_sender @in_setting_site_file_upload_max_size = setting_site_file_upload_max_size @in_setting_site_extension_upload_max_size = setting_site_extension_upload_max_size @in_setting_site_allowed_attachment_type = setting_site_allowed_attachment_type @in_setting_site_link_check = setting_site_link_check @in_setting_site_link_check_hour = setting_site_link_check_hour @in_setting_site_link_check_exclusion = setting_site_link_check_exclusion @in_setting_site_accessibility_check = setting_site_accessibility_check @in_setting_site_kana_talk = setting_site_kana_talk @in_setting_site_map_coordinate = setting_site_map_coordinate end private def save_site_settings SITE_SETTINGS.each do |name| v = instance_variable_get("@in_setting_site_#{name}") next unless v setting = Cms::SiteSetting.where(site_id: id, name: name).first_or_initialize setting.value = v setting.save end end end <file_sep>namespace :zomeki do namespace :biz_calendar do desc 'Publish this month' task :publish_this_month => :environment do Cms::Site.order(:id).pluck(:id).each do |site_id| node_ids = Cms::Node.public_state.where(site_id: site_id, model: 'BizCalendar::Place').pluck(:id) Script.run("cms/nodes/publish", site_id: site_id, target_node_id: node_ids, lock_by: :site) end end end end <file_sep>module Rank::Controller::Rank require 'rubygems' require 'garb' def get_access(content, start_date) if content.setting_value(:web_property_id).blank? #flash[:alert] = "トラッキングIDを設定してください。" return end begin Garb::Session.access_token = content.access_token profile = Garb::Management::Profile.all.detect {|p| p.web_property_id == content.setting_value(:web_property_id)} limit = 1000 results = google_analytics(profile, limit, nil, start_date) repeat_times = results.total_results / limit copy = results.to_a if(repeat_times != 0) repeat_times.times do |x| copy += google_analytics(profile, limit, (x+1)*limit + 1, start_date).to_a end end results = copy first_date = Date.today.strftime("%Y%m%d") ActiveRecord::Base.transaction do results.each_with_index do |result,i| next if result.page_path.length > 250 rank = Rank::Rank.where(content_id: content.id) .where(page_title: result.page_title) .where(hostname: result.hostname) .where(page_path: result.page_path) .where(date: result.date) .first_or_create rank.pageviews = result.pageviews rank.visitors = result.unique_pageviews rank.save! first_date = result.date if first_date > result.date end end Rails.logger.info "Success: #{content.id}: #{content.setting_value(:web_property_id)}" #flash[:notice] = "取り込みが完了しました。 (取り込み開始日は #{Date.parse(first_date).to_s} です)" return true rescue Garb::AuthError => e Rails.logger.warn "Error : #{content.id}: #{content.setting_value(:web_property_id)}: #{e}" #flash[:alert] = "認証エラーです。" return false rescue => e Rails.logger.warn "Error : #{content.id}: #{content.setting_value(:web_property_id)}: #{e}" #flash[:alert] = "取り込みに失敗しました。" return false end end def calc_access(content) begin ActiveRecord::Base.transaction do Rank::Total.where(content_id: content.id).delete_all t = Date.today ranking_terms.each do |termname, term| case term when 'all' from = Date.new(2005, 1, 1) to = t when 'previous_days' from = t.yesterday to = t.yesterday when 'last_weeks' wday = t.wday == 0 ? 7 : t.wday from = t - (6 + wday).days to = t - wday.days when 'last_months' from = (t - 1.month).beginning_of_month to = (t - 1.month).end_of_month when 'this_weeks' from = t.yesterday - 7.days to = t.yesterday end rank_table = Rank::Rank.arel_table Rank::Rank.select(:hostname, :page_path) .select(rank_table[:pageviews].sum.as('pageviews')) .select(rank_table[:visitors].sum.as('visitors')) .where(content_id: content.id) .where(rank_table[:date].gteq(from.strftime('%F')).and(rank_table[:date].lteq(to.strftime('%F')))) .group(:hostname, :page_path) .to_a.each do |result| latest_title = Rank::Rank.order(date: :desc).where(hostname: result.hostname, page_path: result.page_path).pluck(:page_title).first Rank::Total.create!(content_id: content.id, term: term, page_title: latest_title, hostname: result.hostname, page_path: result.page_path, pageviews: result.pageviews, visitors: result.visitors) end end end ActiveRecord::Base.transaction do Rank::Category.where(content_id: content.id).delete_all categories = [] GpCategory::CategoryType.public_state.each do |ct| categories << ct.public_root_categories end categories << GpCategory::Category.public_state categories = categories.flatten.uniq category_ids = [] categories.each do |cc| category_ids << cc.public_descendants.map(&:id) # cc.public_descendants.each do |cd| # unless cd.public_uri.blank? # Rank::Category.where(content_id: content.id) # .where(page_path: cd.public_uri) # .where(category_id: cc.id) # .first_or_create # end # end end category_ids = category_ids.flatten.uniq docs = GpArticle::Doc.categorized_into(category_ids).mobile(::Page.mobile?).public_state docs.each do |doc| doc.categories.each do |c| Rank::Category.where(content_id: content.id) .where(page_path: doc.public_uri) .where(category_id: c) .first_or_create end end end Rails.logger.info "Makeup : #{content.id}" #flash[:notice] = "集計が完了しました。" return true rescue => e Rails.logger.warn "Error : #{content.id}: #{e}" #flash[:alert] = "集計に失敗しました。" return false end end def rank_datas(content, term, target, per_page, category_option = nil, gp_category = nil, category_type = nil, category = nil, current_item = nil) hostname = URI.parse(content.site.full_uri).host exclusion = content.setting_value(:exclusion_url).strip.split(/[ |\t|\r|\n|\f]+/) rescue exclusion = '' rank_table = Rank::Total.arel_table ranks = Rank::Total.select('*') .select(rank_table[target].as('accesses')) .where(content_id: content.id) .where(term: term) .where(hostname: hostname) .where(rank_table[:page_path].not_in(exclusion)) category_ids = [] if category_option == 'on' item = current_item || Page.current_item case item when GpCategory::CategoryType category_ids = item.categories.map(&:id) when GpCategory::Category category_ids = item.descendants.map(&:id) end end if category.to_i > 0 category_ids = GpCategory::Category.find_by(id: category.to_i).descendants.map(&:id) elsif category_type.to_i > 0 category_ids = categories(category_type.to_i).map{|ca| [ca.last] } elsif gp_category.to_i > 0 gp_categories.each do |gc| category_types(gc.last.to_i).each do |ct| category_ids << categories(ct.last.to_i).map{|ca| [ca.last] } # .flatten.uniq end end end category_ids = category_ids.flatten.uniq if category_ids.size > 0 rank_cate_table = Rank::Category.arel_table ranks = ranks.where(Rank::Category.select(:page_path) .where(rank_cate_table[:content_id].eq(content.id) ) .where(rank_cate_table[:page_path].eq(rank_table[:page_path])) .where(category_id: category_ids).exists) end ranks = ranks.order('accesses DESC').paginate(page: params[:page], per_page: per_page) end def ranking_targets return Rank::Rank::TARGETS end def ranking_terms return [['すべて', 'all']] + Rank::Rank::TERMS end def param_check(ary, str) str = ary.first[1] if str.blank? || !ary.flatten.include?(str) str end def gp_categories GpCategory::Content::CategoryType.where(site_id: Core.site.id).map{|co| [co.name, co.id] } end def category_types(gp_category) GpCategory::Content::CategoryType.find_by(id: gp_category).category_types_for_option end def categories(category_type) GpCategory::CategoryType.find(category_type).categories_for_option end private def google_analytics(profile, limit, offset, start_date) start_date = Date.new(start_date.year, start_date.month, start_date.day) unless start_date.nil? start_date = Date.new(2005,01,01) if start_date.blank? || start_date < Date.new(2005,01,01) Rank::GoogleAnalytics.results(profile, :limit => limit, :offset => offset, :start_date => start_date) end end <file_sep>class GpCalendar::SearchEventsScript < Cms::Script::Base def self.publishable? false end end <file_sep>## --------------------------------------------------------- ## cms/concepts c_site = @site.concepts.where(parent_id: 0).first c_top = @site.concepts.where(name: 'トップページ').first c_content = @site.concepts.where(name: 'コンテンツ').first ## --------------------------------------------------------- ## cms/contents l_map = create_cms_layout c_content, 'map', '施設案内' map = create_cms_content c_content, 'Map::Marker', '施設案内', 'map' create_cms_node c_content, map, 160, nil, l_map, 'Map::Marker', 'map', '施設案内', nil category = GpCategory::Content::CategoryType.where(concept_id: c_content.id).first cate_types = GpCategory::CategoryType.where(content_id: category.id).pluck(:id) shisetsu = GpCategory::Category.where(category_type_id: cate_types, name: 'shisetsu').first map_category = {'0' => shisetsu.id} [ {id: 'gp_category_content_category_type_id', value: category.id, extra_values: {categories: map_category}}, {id: 'lat_lng', value: '35.402967,139.314963'}, {id: 'show_images', value: 'visible'}, {id: 'default_image', value: '/_themes/base/images/sample.gif'}, {id: 'marker_order', value: 'category'}, {id: 'title_style', value: '@title_link@'}, ].each do |conf| item = Map::Content::Setting.config(map, conf[:id]) item.value = conf[:value] item.extra_values = conf[:extra_values] if conf[:extra_values] item.save end def create(content, title, lat, lng, window_text, parent_category, category_item) category_ids = GpCategory::Category.where(parent_id: parent_category.id, name: category_item).pluck(:id) Map::Marker.create content_id: content.id, state: 'public', title: title, latitude: lat, longitude: lng, window_text: window_text, category_ids: category_ids end create map, 'ぞめき市役所', 35.69917115852184, 139.55803585056856, 'ぞめき市役所<br />〒164-0002 三鷹市上連雀2-6-7<br />0422-26-9151', shisetsu, 'shiyakusho' create map, 'ぞめき市図書館', 35.68516845714433, 139.55816459651942, 'ぞめき市図書館', shisetsu, 'bunka_sports' create map, 'ぞめき市美術館', 35.70155611615214, 139.56072995066165, 'ぞめき市美術館', shisetsu, 'bunka_sports' create map, 'ぞめき市総合保健センター', 35.68234918496953, 139.56397676467418, 'ぞめき市総合保健センター', shisetsu, 'hukushi' create map, 'ぞめき市民体育館', 35.68256730482748, 139.55904217063903, 'ぞめき市民体育館', shisetsu, 'bunka_sports' create map, '地域包括支援センター', 35.68599970017181, 139.5713474750471 , '地域包括支援センター', shisetsu, 'hukushi' create map, 'ファミリーサポートセンター', 35.69595836619496, 139.56037522851943, 'ファミリーサポートセンター', shisetsu, 'hukushi' create map, 'ぞめき消防署', 35.68289028961057, 139.56602463125705, 'ぞめき消防署', shisetsu, 'shiyakusho' <file_sep>module Cms::Lib::Layout def self.current_concept concept = defined?(Page.current_item.concept) ? Page.current_item.concept : nil concept ||= Page.current_node.inherited_concept end def self.inhertited_concepts return [] unless current_concept current_concept.ancestors.reverse end def self.inhertited_layout layout = defined?(Page.current_item.layout) ? Page.current_item.layout : nil layout ||= Page.current_node.inherited_layout end def self.concepts_order(concepts, options = {}) return 'concept_id' if concepts.blank? table = options.has_key?(:table_name) ? options[:table_name] + '.' : '' order = "CASE #{table}concept_id" concepts.each_with_index {|c, i| order += " WHEN #{c.id} THEN #{i}"} order += " ELSE 100 END, #{table}id" end def self.find_design_pieces(html, concepts, params) names = html.scan(/\[\[piece\/([^\]]+)\]\]/).map{|n| n[0] }.uniq return {} if names.blank? relations = names.map do |name| rel = Cms::Piece.where(state: 'public') name_array = name.split('#') rel = if name_array.size > 1 # [[piece/name#id]] rel.where(id: name_array[1], name: name_array[0]) else # [[piece/name]] concept_ids = concepts.map(&:id) concept_ids << nil rel.where(name: name_array[0]) .where(concept_id: concept_ids) end rel.select("*, #{Cms::DataFile.connection.quote(name)}::text as name_with_option") .order(concepts_order(concepts)).limit(1) end pieces = Cms::Piece.union(relations).index_by(&:name_with_option) if Core.mode == 'preview' && params[:piece_id] item = Cms::Piece.find_by(id: params[:piece_id]) pieces[item.name] = item if item end pieces end def self.find_data_texts(html, concepts) names = html.scan(/\[\[text\/([0-9a-zA-Z\._-]+)\]\]/).flatten.uniq return {} if names.blank? relations = names.map do |name| Cms::DataText.public_state.where(name: name, concept_id: [nil] + concepts.to_a) .order(concepts_order(concepts)).limit(1) end Cms::DataText.union(relations).index_by(&:name) end def self.find_data_files(html, concepts) names = html.scan(/\[\[file\/([^\]]+)\]\]/).flatten.uniq return {} if names.blank? relations = names.map do |name| dirname = ::File.dirname(name) basename = dirname == '.' ? name : ::File.basename(name) item = Cms::DataFile.select(Cms::DataFile.arel_table[Arel.star]) .select("#{Cms::DataFile.connection.quote(name)} as name_with_option") .public_state.where(name: basename, concept_id: [nil] + concepts.to_a) if dirname == '.' item = item.where(node_id: nil) else item = item.joins(:node).where(Cms::DataFileNode.arel_table[:name].eq(dirname)) end item.order(concepts_order(concepts, :table_name => Cms::DataFile.table_name)).limit(1) end Cms::DataFile.union(relations).index_by(&:name_with_option) end end <file_sep>class AdBanner::BannersScript < Cms::Script::Publication def publish end end <file_sep>class Cms::NodesScript < Cms::Script::Publication include Sys::Lib::File::Transfer def publish @ids = {} nodes = Cms::Node.public_state.order(:name, :id) nodes.where!(site_id: ::Script.site.id) if ::Script.site if params[:target_node_id].present? nodes.where(id: params[:target_node_id]).each do |node| publish_node(node) end else nodes.where(parent_id: 0).each do |node| publish_node(node) end end # file transfer transfer_files(logging: true) if Zomeki.config.application['sys.transfer_to_publish'] end def publish_node(node) started_at = Time.now info_log "Publish node: #{node.model} #{node.name} #{node.title}" return if @ids.key?(node.id) @ids[node.id] = true return unless node.site unless node.public? node.close_page return end ## page if node.model == 'Cms::Page' begin uri = "#{node.public_uri}?node_id=#{node.id}" publish_page(node, uri: uri, site: node.site, path: node.public_path, smart_phone_path: node.public_smart_phone_path) rescue ::Script::InterruptException => e raise e rescue => e ::Script.error "#{node.class}##{node.id} #{e}" end return end ## modules' page unless node.model == 'Cms::Directory' begin script_klass = node.script_klass return unless script_klass.publishable? publish_page(node, uri: node.public_uri, site: node.site, path: node.public_path, smart_phone_path: node.public_smart_phone_path) script_klass.new(params.merge(node: node)).publish rescue ::Script::InterruptException => e raise e rescue LoadError => e ::Script.error "#{node.class}##{node.id} #{e}" return rescue Exception => e ::Script.error "#{node.class}##{node.id} #{e}" return end end child_nodes = Cms::Node.where(parent_id: node.id) .where.not(name: [nil, '']) .order(:directory, :name, :id) child_nodes.each do |child_node| publish_node(child_node) end info_log "Published node: #{node.model} #{node.name} #{node.title} in #{(Time.now - started_at).round(2)} [secs.]" end def publish_by_task item = params[:item] if item.state == 'recognized' && item.model == 'Cms::Page' ::Script.current info_log "-- Publish: #{item.class}##{item.id}" item = Cms::Node::Page.find(item.id) uri = "#{item.public_uri}?node_id=#{item.id}" path = "#{item.public_path}" unless item.publish(render_public_as_string(uri, site: item.site)) raise item.errors.full_messages else Sys::OperationLog.script_log(:item => item, :site => item.site, :action => 'publish') end ruby_uri = (uri =~ /\?/) ? uri.gsub(/(.*\.html)\?/, '\\1.r?') : "#{uri}.r" ruby_path = "#{path}.r" if item.published? || !::File.exist?(ruby_uri) item.publish_page(render_public_as_string(ruby_uri, site: item.site), path: ruby_path, dependent: :ruby) end info_log %Q!OK: Published to "#{path}"! params[:task].destroy ::Script.success end rescue => e error_log e.message end def close_by_task item = params[:item] if item.state == 'public' && item.model == 'Cms::Page' ::Script.current info_log "-- Close: #{item.class}##{item.id}" item = Cms::Node::Page.find(item.id) if item.close Sys::OperationLog.script_log(:item => item, :site => item.site, :action => 'close') end info_log 'OK: Closed' params[:task].destroy ::Script.success end rescue => e error_log e.message end end <file_sep>class Cms::Publisher::PieceCallbacks < Cms::Publisher::BracketeeCallbacks end <file_sep>class GpCategory::Public::Node::CategoriesController < GpCategory::Public::Node::BaseController def show category_type = @content.category_types.find_by(name: params[:category_type_name]) @category = category_type.find_category_by_path_from_root_category(params[:category_names]) return http_error(404) unless @category.try(:public?) if params[:format].in?(['rss', 'atom']) docs = @category.public_docs.order(display_published_at: :desc, published_at: :desc) docs = docs.display_published_after(@content.feed_docs_period.to_i.days.ago) if @content.feed_docs_period.present? docs = docs.paginate(page: params[:page], per_page: @content.feed_docs_number) return render_feed(docs) end Page.current_item = @category Page.title = @category.title per_page = (@more ? 30 : @content.category_docs_number) if (template = @category.inherited_template) if @more @template_module = template.containing_modules.detect { |m| m.name == @more_options.first } @docs = if @template_module && @template_module.module_type.in?(%w(docs_2 docs_4 docs_6)) find_public_docs_with_category_id(@category.id) else find_public_docs_with_category_id(@category.public_descendants.map(&:id)) end if @template_module && @template_module.gp_article_content_ids.present? @docs.where!(content_id: @template_module.gp_article_content_ids) end if (filter = @more_options[1]) prefix, code_or_name = filter.split('_', 2) case prefix when 'c' return http_error(404) unless category_type.internal_category_type internal_category = category_type.internal_category_type.public_root_categories.find_by(name: code_or_name) return http_error(404) unless internal_category categorizations = GpCategory::Categorization.where(categorizable_type: 'GpArticle::Doc', categorized_as: 'GpArticle::Doc', categorizable_id: @docs.pluck(:id), category_id: internal_category.public_descendants.map(&:id)) @docs = GpArticle::Doc.where(id: categorizations.pluck(:categorizable_id)) when 'g' group = Sys::Group.in_site(Page.site).where(code: code_or_name).first return http_error(404) unless group @docs = @docs.joins(creator: :group).where(Sys::Group.arel_table[:id].eq(group.id)) end end @docs = case @content.docs_order when 'published_at_desc' @docs.order(display_published_at: :desc, published_at: :desc) when 'published_at_asc' @docs.order(display_published_at: :asc, published_at: :asc) when 'updated_at_desc' @docs.order(display_updated_at: :desc, updated_at: :desc) when 'updated_at_asc' @docs.order(display_updated_at: :asc, updated_at: :asc) else @docs.order(display_published_at: :desc, published_at: :desc) end @docs = @docs.paginate(page: params[:page], per_page: per_page) return http_error(404) if @docs.current_page > @docs.total_pages render :more else return http_error(404) if params[:page] vc = view_context rendered = template.body.gsub(/\[\[module\/([\w-]+)\]\]/) do |matched| tm = @content.template_modules.find_by(name: $1) next unless tm case tm.module_type when 'categories_1', 'categories_2', 'categories_3' if vc.respond_to?(tm.module_type) @category.public_children.inject(''){|tags, child| tags << vc.content_tag(:section, class: child.name) do html = vc.content_tag(:h2, vc.link_to(child.title, child.public_uri)) html << vc.send(tm.module_type, template_module: tm, categories: child.public_children) end } end when 'categories_summary_1', 'categories_summary_2', 'categories_summary_3' if vc.respond_to?(tm.module_type) @category.public_children.inject(''){|tags, child| tags << vc.content_tag(:section, class: child.name) do title_tag = vc.content_tag(:h2, child.title) title_tag << vc.content_tag(:span, child.description, class: 'category_summary') if child.description.present? html = vc.link_to(title_tag, child.public_uri) html << vc.send(tm.module_type, template_module: tm, categories: child.public_children) end } end when 'docs_1', 'docs_2' if vc.respond_to?(tm.module_type) docs = case tm.module_type when 'docs_1' find_public_docs_with_category_id(@category.public_descendants.map(&:id)) when 'docs_2' find_public_docs_with_category_id(@category.id) end docs = docs.where(content_id: tm.gp_article_content_ids) if tm.gp_article_content_ids.present? all_docs = case @content.docs_order when 'published_at_desc' docs.order(display_published_at: :desc, published_at: :desc) when 'published_at_asc' docs.order(display_published_at: :asc, published_at: :asc) when 'updated_at_desc' docs.order(display_updated_at: :desc, updated_at: :desc) when 'updated_at_asc' docs.order(display_updated_at: :asc, updated_at: :asc) else docs.order(display_published_at: :desc, published_at: :desc) end docs = all_docs.limit(tm.num_docs) vc.send(tm.module_type, template_module: tm, ct_or_c: @category, docs: docs, all_docs: all_docs) end when 'docs_3', 'docs_4' if vc.respond_to?(tm.module_type) && category_type.internal_category_type docs = case tm.module_type when 'docs_3' find_public_docs_with_category_id(@category.public_descendants.map(&:id)) when 'docs_4' find_public_docs_with_category_id(@category.id) end docs = docs.where(content_id: tm.gp_article_content_ids) if tm.gp_article_content_ids.present? categorizations = GpCategory::Categorization.where(categorizable_type: 'GpArticle::Doc', categorizable_id: docs.pluck(:id), categorized_as: 'GpArticle::Doc') vc.send(tm.module_type, template_module: tm, ct_or_c: @category, categories: category_type.internal_category_type.public_root_categories, categorizations: categorizations) end when 'docs_5', 'docs_6' if vc.respond_to?(tm.module_type) docs = case tm.module_type when 'docs_5' find_public_docs_with_category_id(@category.public_descendants.map(&:id)) when 'docs_6' find_public_docs_with_category_id(@category.id) end docs = docs.where(content_id: tm.gp_article_content_ids) if tm.gp_article_content_ids.present? docs = docs.joins(:creator => :group) groups = Sys::Group.where(id: docs.select(Sys::Group.arel_table[:id]).distinct) vc.send(tm.module_type, template_module: tm, ct_or_c: @category, groups: groups, docs: docs) end when 'docs_7', 'docs_8' if view_context.respond_to?(tm.module_type) docs = find_public_docs_with_category_id(@category.public_descendants.map(&:id)) docs = docs.where(content_id: tm.gp_article_content_ids) if tm.gp_article_content_ids.present? categorizations = GpCategory::Categorization.where(categorizable_type: 'GpArticle::Doc', categorizable_id: docs.pluck(:id), categorized_as: 'GpArticle::Doc') vc.send(tm.module_type, template_module: tm, categories: @category.children, categorizations: categorizations) end else '' end end render html: vc.content_tag(:div, rendered.html_safe, class: 'contentGpCategory contentGpCategoryCategory').html_safe end else @docs = @category.public_docs.order(display_published_at: :desc, published_at: :desc) .paginate(page: params[:page], per_page: per_page) .preload_assocs(:public_node_ancestors_assocs, :public_index_assocs) return http_error(404) if @docs.current_page > @docs.total_pages if Page.mobile? render :show_mobile else if @more render 'more' else if (style = @content.category_style).present? render style end end end end end end <file_sep>class Cms::Link < ApplicationRecord include Sys::Model::Base def make_absolute_url(site) uri = Addressable::URI.parse(url) if uri.absolute? uri.to_s else if uri.path =~ /^\// "#{site.full_uri.sub(/\/$/, '')}#{uri.path}" else nil end end rescue => e error_log e error_log e.backtrace.join("\n") nil end end <file_sep>class Sys::ProcessLog < ApplicationRecord include Sys::Model::Base end <file_sep>module Rsync class Change def file_type t = case raw_file_type when 'f' :file when 'd' :directory when 'L' :symlink when 'D' :device when 'S' :special end # custom return t unless t == :directory return t if filename.to_s[-1] == '/' return :file if update_type == :message && message == 'deleting' t end end class Result def status_code @exitcode end def status {:success => success?, :code => @exitcode, :message => error } end end end <file_sep>require 'csv' class Survey::Admin::FormsController < Cms::Controller::Admin::Base include Sys::Controller::Scaffold::Base def pre_dispatch @content = Survey::Content::Form.find(params[:content]) return error_auth unless Core.user.has_priv?(:read, item: @content.concept) @item = @content.forms.find(params[:id]) if params[:id].present? end def index criteria = params[:criteria] || {} case params[:target] when 'all' # No criteria when 'draft' criteria[:state] = 'draft' criteria[:touched_user_id] = Core.user.id when 'public' criteria[:state] = 'public' criteria[:touched_user_id] = Core.user.id when 'closed' criteria[:state] = 'closed' criteria[:touched_user_id] = Core.user.id when 'approvable' criteria[:approvable] = true criteria[:state] = 'approvable' when 'approved' criteria[:approvable] = true criteria[:state] = 'approved' else criteria[:editable] = true end @items = Survey::Form.all_with_content_and_criteria(@content, criteria).reorder(:sort_no) .paginate(page: params[:page], per_page: 30) .preload(content: { public_node: :site }) _index @items end def show _show @item end def new @item = @content.forms.build end def create new_state = params.keys.detect{|k| k =~ /^commit_/ }.try(:sub, /^commit_/, '') @item = @content.forms.build(form_params) @item.state = new_state if new_state.present? && @item.class::STATE_OPTIONS.any?{|v| v.last == new_state } location = ->(f){ edit_survey_form_url(@content, f) } if @item.state_draft? _create(@item, location: location) do @item.send_approval_request_mail if @item.state_approvable? end end def update new_state = params.keys.detect{|k| k =~ /^commit_/ }.try(:sub, /^commit_/, '') @item.attributes = form_params @item.state = new_state if new_state.present? && @item.class::STATE_OPTIONS.any?{|v| v.last == new_state } location = url_for(action: 'edit') if @item.state_draft? _update(@item, location: location) do @item.send_approval_request_mail if @item.state_approvable? end end def destroy _destroy @item end def download_form_answers csv_string = CSV.generate do |csv| header = [Survey::FormAnswer.human_attribute_name(:created_at), "#{Survey::FormAnswer.human_attribute_name(:answered_url)}URL", "#{Survey::FormAnswer.human_attribute_name(:answered_url)}タイトル", Survey::FormAnswer.human_attribute_name(:remote_addr), Survey::FormAnswer.human_attribute_name(:user_agent)] @item.questions.each{|q| header << q.title } csv << header @item.form_answers.each do |form_answer| line = [I18n.l(form_answer.created_at), form_answer.answered_url, form_answer.answered_url_title, form_answer.remote_addr, form_answer.user_agent] @item.questions.each{|q| line << form_answer.answers.find_by(question_id: q.id).try(:content) } csv << line end end send_data csv_string.encode(Encoding::WINDOWS_31J, :invalid => :replace, :undef => :replace), type: Rack::Mime.mime_type('.csv'), filename: 'answers.csv' end def approve if @item.state_approvable? && @item.approvers.include?(Core.user) @item.approve(Core.user) do @item.update_column(:state, 'approved') @item.set_queues Sys::OperationLog.log(request, item: @item) end end redirect_to url_for(:action => :show), notice: '承認処理が完了しました。' end def publish @item.publish if @item.state_approved? && @item.approval_participators.include?(Core.user) redirect_to url_for(:action => :show), notice: '公開処理が完了しました。' end def close @item.close if @item.state_public? && @item.approval_participators.include?(Core.user) redirect_to url_for(:action => :show), notice: '非公開処理が完了しました。' end def duplicate(item) if dupe_item = item.duplicate flash[:notice] = '複製処理が完了しました。' respond_to do |format| format.html { redirect_to url_for(:action => :index) } format.xml { head :ok } end else flash[:notice] = "複製処理に失敗しました。" respond_to do |format| format.html { redirect_to url_for(:action => :show) } format.xml { render :xml => item.errors, :status => :unprocessable_entity } end end end private def form_params params.require(:item).permit( :closed_at, :confirmation, :description, :index_link, :name, :opened_at, :receipt, :sitemap_state, :sort_no, :summary, :title, :creator_attributes => [:id, :group_id, :user_id], :tasks_attributes => [:id, :name, :process_at], :in_approval_flow_ids => [] ).tap do |permitted| [:in_approval_assignment_ids].each do |key| permitted[key] = params[:item][key].to_unsafe_h if params[:item][key] end end end end <file_sep>## --------------------------------------------------------- ## cms/concepts c_site = @site.concepts.where(parent_id: 0).first c_top = @site.concepts.where(name: 'トップページ').first c_content = @site.concepts.where(name: 'コンテンツ').first c_category = create_cms_concept c_content, 40, 'カテゴリ' c_kubun = create_cms_concept c_category, 10, '区分' c_bunya = create_cms_concept c_category, 20, '分野' c_bunya1 = create_cms_concept c_bunya, 10,'届出・登録・証明' c_bunya2 = create_cms_concept c_bunya, 20,'保険・年金・介護' c_bunya3 = create_cms_concept c_bunya, 30,'福祉' c_bunya4 = create_cms_concept c_bunya, 40,'健康・予防' c_bunya5 = create_cms_concept c_bunya, 50,'税金' c_bunya6 = create_cms_concept c_bunya, 60,'育児・教育' c_bunya7 = create_cms_concept c_bunya, 70,'生活・インフラ' c_bunya8 = create_cms_concept c_bunya, 80,'安心・安全' c_bunya9 = create_cms_concept c_bunya, 90,'環境・ごみ' c_bunya10 = create_cms_concept c_bunya, 100,'入札・契約' c_bunya11 = create_cms_concept c_bunya, 110,'都市整備' c_bunya12 = create_cms_concept c_bunya, 120,'地域産業' c_bunya13 = create_cms_concept c_bunya, 130,'市政情報' c_bunya14 = create_cms_concept c_bunya, 140,'歴史・文化財' c_bunya15 = create_cms_concept c_bunya, 150,'施設案内' c_bunya16 = create_cms_concept c_bunya, 160,'市紹介' c_bunya17 = create_cms_concept c_bunya, 170,'議会・選挙' c_bunya18 = create_cms_concept c_bunya, 180,'広報・広聴' c_bunya19 = create_cms_concept c_bunya, 190,'情報公開' c_bunya20 = create_cms_concept c_bunya, 200,'交流事業' c_lifeevent = create_cms_concept c_category, 30, 'ライフイベント' c_event = create_cms_concept c_category, 40, 'イベント情報' create_cms_concept c_category, 50, '組織' ## --------------------------------------------------------- ## cms/layouts l_category = create_cms_layout c_site, 'category','カテゴリ' l_bunya = create_cms_layout c_site, 'category-bunya', 'カテゴリ(分野)' ## --------------------------------------------------------- ## cms/contents category = create_cms_content c_content, 'GpCategory::CategoryType', 'カテゴリ', 'category' create_cms_node c_content, category, 20, nil, l_category, 'GpCategory::CategoryType', 'categories', 'カテゴリ', nil [ {id: "date_style", value: '%Y年%m月%d日'}, {id: "category_type_style", value: 'all_categories', extra_values: {category_type_doc_style: '@title_link@(@publish_date@@group@)', doc_number: 10}}, {id: "category_style", value: 'categories_with_docs', extra_values: {category_doc_style: '@title_link@(@publish_date@@group@)', category_docs_number: 10}}, {id: "doc_style", value: 'all_docs', extra_values: {doc_doc_style: '@title_link@(@publish_date@@group@)', doc_docs_number: 10}} ].each do |conf| item = GpCategory::Content::Setting.config(category, conf[:id]) item.value = conf[:value] item.extra_values = conf[:extra_values] if conf[:extra_values] item.save end ## --------------------------------------------------------- ## gp_category/category_type def create_type(concept, content, layout, name, title, sort_no) item = GpCategory::CategoryType.create concept_id: concept.id, content_id: content.id, layout_id: layout.id, name: name, title: title, sort_no: sort_no, state: 'public', docs_order: 'display_published_at DESC, published_at DESC' if category_concept = @site.concepts.where(name: title).first p = create_cms_piece category_concept, content, 'GpCategory::CategoryList', 'category-list', "#{title}から探す", "#{title}から探す" p.in_settings = {setting_state: 'enabled', layer: 'self', category_type_id: item.id} p.save end return item end kubun = create_type c_category, category, l_category, 'kubun', '区分', 10 bunya = create_type c_category, category, l_bunya, 'bunya', '分野', 20 lifeevent = create_type c_category, category, l_category, 'lifeevent', 'ライフイベント', 30 event = create_type c_category, category, l_category, 'event', 'イベント情報', 40 def create(concept, category_type, parent, layout, name, title, sort_no) item = GpCategory::Category.create concept_id: concept.id, category_type_id: category_type.id, parent_id: parent.blank? ? nil : parent.id, layout_id: layout.id, name: name, title: title, sort_no: sort_no, state: 'public', docs_order: 'display_published_at DESC, published_at DESC' if category_concept = @site.concepts.where(name: title).first p = create_cms_piece category_concept, category_type.content, 'GpCategory::CategoryList', 'category-list', "#{category_type.title}から探す", "#{category_type.title}から探す" p.in_settings = {setting_state: 'enabled', layer: 'self', category_type_id: category_type.id, category_id: item.id } p.save end return item end todokede = create c_bunya , bunya, nil, l_category, 'todokede', '届出・登録・証明', 10 hoken = create c_bunya , bunya, nil, l_category, 'hoken', '保険・年金・介護', 20 hukushi = create c_bunya , bunya, nil, l_category, 'hukushi', '福祉', 30 kenko = create c_bunya , bunya, nil, l_category, 'kenko', '健康・予防', 40 zei = create c_bunya , bunya, nil, l_category, 'zei', '税金', 50 ikuji = create c_bunya , bunya, nil, l_category, 'ikuji', '育児・教育', 60 seikatsu = create c_bunya , bunya, nil, l_category, 'seikatsu', '生活・インフラ', 70 anshin = create c_bunya , bunya, nil, l_category, 'anshin', '安心・安全', 80 kankyo = create c_bunya , bunya, nil, l_category, 'kankyo', '環境・ごみ', 90 nyusatsu = create c_bunya , bunya, nil, l_category, 'nyusatsu', '入札・契約', 100 toshiseibi = create c_bunya , bunya, nil, l_category, 'toshiseibi', '都市整備', 110 chiikisangyo = create c_bunya , bunya, nil, l_category, 'chiikisangyo', '地域産業', 120 shisei = create c_bunya , bunya, nil, l_category, 'shisei', '市政情報', 130 rekishi = create c_bunya , bunya, nil, l_category, 'rekishi', '歴史・文化財', 140 shisetsu = create c_bunya , bunya, nil, l_category, 'shisetsu', '施設案内', 150 city_shokai = create c_bunya , bunya, nil, l_category, 'city_shokai', '市紹介', 160 gikai_senkyo = create c_bunya , bunya, nil, l_category, 'gikai_senkyo', '議会・選挙', 170 kohokocho = create c_bunya , bunya, nil, l_category, 'kohokocho', '広報・広聴', 180 johokokai = create c_bunya , bunya, nil, l_category, 'johokokai', '情報公開', 190 koryu = create c_bunya , bunya, nil, l_category, 'koryu', '交流事業', 200 chumoku = create c_kubun, kubun, nil, l_category, 'chumoku', '注目情報', 10 create c_kubun, kubun, nil, l_category, 'faq', 'FAQ', 20 create c_kubun, kubun, nil, l_category, 'tetsuzuki', '手続き', 30 create c_kubun, kubun, nil, l_category, 'boshu', '募集', 40 create c_kubun, kubun, nil, l_category, 'open_data', 'オープンデータ', 50 create c_kubun, kubun, nil, l_category, 'download', 'ダウンロード', 60 create c_lifeevent, lifeevent, nil, l_category, 'ninshin', '妊娠・出産', 10 create c_lifeevent, lifeevent, nil, l_category, 'kosodate', '子育て・教育', 20 create c_lifeevent, lifeevent, nil, l_category, 'seijin', '成人・就職', 30 create c_lifeevent, lifeevent, nil, l_category, 'kekkon', '結婚・離婚', 40 create c_lifeevent, lifeevent, nil, l_category, 'hikkoshi', '引越し・住まい', 50 create c_lifeevent, lifeevent, nil, l_category, 'byoki', '病気・けが', 60 create c_lifeevent, lifeevent, nil, l_category, 'shogaisha', '障がい者', 70 create c_lifeevent, lifeevent, nil, l_category, 'shitsugyo', '失業・退職', 80 create c_lifeevent, lifeevent, nil, l_category, 'korei', '高齢・介護', 90 create c_lifeevent, lifeevent, nil, l_category, 'shibo', '死亡・相続', 100 create c_bunya1, bunya, todokede, l_bunya, 'juminhyo', '住民票', 10 create c_bunya1, bunya, todokede, l_bunya, 'inkan', '印鑑登録', 20 create c_bunya1, bunya, todokede, l_bunya, 'koseki', '戸籍', 30 create c_bunya1, bunya, todokede, l_bunya, 'gaikokujin', '外国人登録', 40 create c_bunya1, bunya, todokede, l_bunya, 'shomei', '各種証明書', 50 create c_bunya1, bunya, todokede, l_bunya, 'jukinet', '住基ネット・公的個人認証', 60 create c_bunya1, bunya, todokede, l_bunya, 'passport', 'パスポート', 70 create c_bunya1, bunya, todokede, l_bunya, 'my-number', 'マイナンバー制度', 80 create c_bunya1, bunya, todokede, l_bunya, 'procedure', '手続き・本人確認・委任', 90 create c_bunya2, bunya, hoken, l_bunya, 'kokuho', '国民健康保険', 10 create c_bunya2, bunya, hoken, l_bunya, 'nenkin', '国民年金', 20 create c_bunya2, bunya, hoken, l_bunya, 'kaigo', '介護保険', 30 create c_bunya2, bunya, hoken, l_bunya, 'kouki', '後期高齢者医療', 40 create c_bunya3, bunya, hukushi, l_bunya, 'fuyo', '児童扶養手当', 10 create c_bunya3, bunya, hukushi, l_bunya, 'hitori', 'ひとり親家庭助成', 20 create c_bunya3, bunya, hukushi, l_bunya, 'tokubetsu', '特別児童扶養手当', 30 create c_bunya3, bunya, hukushi, l_bunya, 'shogai', '障がい者助成', 40 create c_bunya3, bunya, hukushi, l_bunya, 'korei', '高齢者福祉', 50 create c_bunya3, bunya, hukushi, l_bunya, 'seikatsuhogo', '生活保護', 60 create c_bunya4, bunya, kenko, l_bunya, 'boshihoken', '母子保健', 10 create c_bunya4, bunya, kenko, l_bunya, 'yobo', '予防接種', 20 create c_bunya4, bunya, kenko, l_bunya, 'tokuteikenshin', '総合健(検)診【特定健診等】・保健指導', 30 create c_bunya4, bunya, kenko, l_bunya, 'kenko', '健康づくり', 40 create c_bunya4, bunya, kenko, l_bunya, 'sonota', 'その他', 50 create c_bunya4, bunya, zei, l_bunya, 'kobai', '公売情報', 80 create c_bunya5, bunya, zei, l_bunya, 'shikenmin', '市県民税', 10 create c_bunya5, bunya, zei, l_bunya, 'shizei_gaiyo', '市税概要', 20 create c_bunya5, bunya, zei, l_bunya, 'koteishisan', '固定資産税', 30 create c_bunya5, bunya, zei, l_bunya, 'keijidosha', '軽自動車税', 40 create c_bunya5, bunya, zei, l_bunya, 'sonota', 'その他の税', 50 create c_bunya5, bunya, zei, l_bunya, 'nofu', '納付・収納', 60 create c_bunya5, bunya, zei, l_bunya, 'shomeisho', '税務関連証明書', 70 create c_bunya6, bunya, ikuji, l_bunya, 'hoikusho', '保育所', 10 create c_bunya6, bunya, ikuji, l_bunya, 'yochien', '幼稚園', 20 create c_bunya6, bunya, ikuji, l_bunya, 'ikujishien', '育児支援', 30 create c_bunya6, bunya, ikuji, l_bunya, 'gakudohoiku', '学童保育', 40 create c_bunya6, bunya, ikuji, l_bunya, 'shochugakko', '小学校・中学校', 50 create c_bunya6, bunya, ikuji, l_bunya, 'kyushoku', '給食', 60 create c_bunya6, bunya, ikuji, l_bunya, 'shogaigakushu', '生涯学習', 70 create c_bunya6, bunya, ikuji, l_bunya, 'shugakutaiyo', '就学資金貸与', 80 create c_bunya7, bunya, seikatsu, l_bunya, 'koeijutaku', '公営住宅', 10 create c_bunya7, bunya, seikatsu, l_bunya, 'suido', '上水道', 20 create c_bunya7, bunya, seikatsu, l_bunya, 'gesuido', '下水道', 30 create c_bunya7, bunya, seikatsu, l_bunya, 'doro', '道路', 40 create c_bunya7, bunya, seikatsu, l_bunya, 'kokyo', '公共共通(電車・バスなど)', 50 create c_bunya8, bunya, anshin, l_bunya, 'kyukyu', '救急・消防', 10 create c_bunya8, bunya, anshin, l_bunya, 'kyujitsushinryo', '休日診療案内', 20 create c_bunya8, bunya, anshin, l_bunya, 'bosaigai', '防災・災害', 30 create c_bunya8, bunya, anshin, l_bunya, 'bohan', '防犯・交通安全', 40 create c_bunya8, bunya, anshin, l_bunya, 'jiko', '事故・被災支援', 50 create c_bunya9, bunya, kankyo, l_bunya, 'gomi', 'ごみ・リサイクル', 10 create c_bunya9, bunya, kankyo, l_bunya, 'pet', 'ペット・動物愛護', 20 create c_bunya9, bunya, kankyo, l_bunya, 'kogai_bochi', '公害・墓地', 30 create c_bunya9, bunya, kankyo, l_bunya, 'eco', 'エコ・環境', 40 create c_bunya10, bunya, nyusatsu, l_bunya, 'joho', '入札情報', 10 create c_bunya10, bunya, nyusatsu, l_bunya, 'kobo', '公募', 20 create c_bunya10, bunya, nyusatsu, l_bunya, 'shikakushinsei', '入札参加資格申請', 30 create c_bunya10, bunya, nyusatsu, l_bunya, 'shokibokoji', '小規模工事等業者登録', 40 create c_bunya10, bunya, nyusatsu, l_bunya, 'henko', '入札参加資格申請変更届け', 50 create c_bunya11, bunya, toshiseibi, l_bunya, 'keikaku', '都市計画・まちづくり', 10 create c_bunya11, bunya, toshiseibi, l_bunya, 'doro', '道路整備', 20 create c_bunya12, bunya, chiikisangyo, l_bunya, 'kigyoyushi', '企業融資・支援', 10 create c_bunya12, bunya, chiikisangyo, l_bunya, 'noringyo', '農業・林業', 20 create c_bunya12, bunya, chiikisangyo, l_bunya, 'shokogyo', '商業・工業', 30 create c_bunya12, bunya, chiikisangyo, l_bunya, 'koyo', '雇用', 40 create c_bunya13, bunya, shisei, l_bunya, 'aramashi', '市のあらまし', 10 create c_bunya13, bunya, shisei, l_bunya, 'kyodosankaku', '男女共同参画', 20 create c_bunya14, bunya, rekishi, l_bunya, 'bunkazai_shiseki', '歴史と文化財', 10 create c_bunya14, bunya, rekishi, l_bunya, 'bunkazaimap', '文化財マップ・リーフレット等のダウンロード', 20 create c_bunya14, bunya, rekishi, l_bunya, 'eventnews', 'イベント・ニュース', 30 create c_bunya15, bunya, shisetsu, l_bunya, 'shiyakusho', '市役所', 10 create c_bunya15, bunya, shisetsu, l_bunya, 'hukushi', '福祉・保健施設', 20 create c_bunya15, bunya, shisetsu, l_bunya, 'bunka_sports', '文化・スポーツ施設', 30 create c_bunya15, bunya, shisetsu, l_bunya, 'hoikusho', '保育所', 40 create c_bunya15, bunya, shisetsu, l_bunya, 'yochien', '幼稚園', 50 create c_bunya15, bunya, shisetsu, l_bunya, 'shochugakko', '小中学校・高校', 60 create c_bunya15, bunya, shisetsu, l_bunya, 'kominkan', '公民館', 70 create c_bunya15, bunya, shisetsu, l_bunya, 'center', '男女共同参画推進ハーモニーセンター', 80 create c_bunya15, bunya, shisetsu, l_bunya, 'chuokominkan', '中央公民館', 90 create c_bunya15, bunya, shisetsu, l_bunya, 'koen', '公園', 100 create c_bunya15, bunya, shisetsu, l_bunya, 'shieijyutaku', '市営住宅', 110 create c_bunya15, bunya, shisetsu, l_bunya, 'shisetsu_guide', '施設ガイド', 120 create c_bunya16, bunya, city_shokai, l_bunya, 'chosha', '庁舎案内', 10 create c_bunya16, bunya, city_shokai, l_bunya, 'access', '市へのアクセス', 20 create c_bunya16, bunya, city_shokai, l_bunya, 'madoguchi', '窓口対応時間', 30 create c_bunya16, bunya, city_shokai, l_bunya, 'floor_guide', '庁舎フロアガイド', 40 create c_bunya16, bunya, city_shokai, l_bunya, 'soshiki', '組織', 50 create c_bunya16, bunya, city_shokai, l_bunya, 'saiyo', '職員採用', 60 create c_bunya17, bunya, gikai_senkyo, l_bunya, 'gikai', '議会', 10 create c_bunya17, bunya, gikai_senkyo, l_bunya, 'senkyo', '選挙', 20 create c_bunya18, bunya, kohokocho, l_bunya, 'koho', '広報', 10 create c_bunya18, bunya, kohokocho, l_bunya, 'kocho', '広聴', 20 create c_bunya18, bunya, kohokocho, l_bunya, 'shiminnokoe', '市民の声', 30 create c_bunya18, bunya, kohokocho, l_bunya, 'questionnaire', '住民アンケート', 40 create c_bunya18, bunya, kohokocho, l_bunya, 'gyoseisodan', '行政相談窓口', 50 create c_bunya18, bunya, kohokocho, l_bunya, 'kokoku', '広告掲載案内', 60 create c_bunya19, bunya, johokokai, l_bunya, 'johokokai_kojinjoho', '情報公開・個人情報制度', 10 create c_bunya19, bunya, johokokai, l_bunya, 'keikaku', '計画・取り組み', 20 create c_bunya19, bunya, johokokai, l_bunya, 'zaisei', '財政状況', 30 create c_bunya19, bunya, johokokai, l_bunya, 'tokei', '統計', 40 create c_bunya19, bunya, johokokai, l_bunya, 'jorei_reiki', '条例・例規集', 50 create c_bunya19, bunya, johokokai, l_bunya, 'kyuyoteisu', '職員給与・定員管理', 60 create c_bunya20, bunya, koryu, l_bunya, 'kokusai', '国際交流', 10 create c_bunya19, bunya, koryu, l_bunya, 'heiwakoryu', '平和交流', 20 create c_bunya20, bunya, koryu, l_bunya, 'yukotoshikoryu', '友好都市交流', 30 create c_event, event, nil, l_category, 'event', 'イベント', 10 create c_event, event, nil, l_category, 'sports', 'スポーツ', 20 create c_event, event, nil, l_category, 'koza', '講座', 30 create c_event, event, nil, l_category, 'matsuri', 'お祭り', 40 ## --------------------------------------------------------- ## cms/pieces p_lifeevent = create_cms_piece c_site, category, 'GpCategory::CategoryList', 'lifeevent-list', 'ライフイベント一覧', '人生のできごとから探す' p_lifeevent.in_settings = {setting_state: 'enabled', category_type_id: lifeevent.id, layer: 'descendants'} p_lifeevent.save p_category = create_cms_piece c_site, category, 'GpCategory::CategoryList', 'category-list', 'カテゴリから探す', 'カテゴリから探す' p_category.in_settings = {setting_state: 'enabled', layer: 'descendants'} p_category.save <file_sep>class Cms::Admin::Site::SettingsController < Cms::Controller::Admin::Base include Sys::Controller::Scaffold::Base def pre_dispatch return error_auth unless Core.user.has_auth?(:manager) return redirect_to(action: :index) if params[:reset] @site = Cms::Site.find(params[:site]) @site.load_site_settings end def index @items = Cms::SiteSetting::SITE_CONFIGS _index @items end def show @item = Cms::SiteSetting.where(name: params[:id], site_id: @site.id).first_or_initialize _show @item end def new error_auth end def create error_auth end def update @item = Cms::SiteSetting.where(name: params[:id], site_id: @site.id).first_or_initialize @site.attributes = site_setting_params _update(@site) end def destroy error_auth end def site_setting_params params.require(:item).permit( :in_setting_site_admin_mail_sender, :in_setting_site_file_upload_max_size, :in_setting_site_extension_upload_max_size, :in_setting_site_common_ssl, :in_setting_site_allowed_attachment_type, :in_setting_site_link_check, :in_setting_site_link_check_hour, :in_setting_site_link_check_exclusion, :in_setting_site_accessibility_check, :in_setting_site_kana_talk, :in_setting_site_map_coordinate ) end end <file_sep>Delayed::Worker.max_run_time = 1.days Delayed::Worker.read_ahead = 1 class Delayed::Plugins::CoreInitializer < Delayed::Plugin callbacks do |lifecycle| lifecycle.before(:execute) do |worker| Core.initialize end end end Delayed::Worker.plugins << Delayed::Plugins::CoreInitializer class Delayed::Plugins::OomChecker < Delayed::Plugin callbacks do |lifecycle| lifecycle.after(:perform) do |worker| mem = GetProcessMem.new if mem.mb > 512 worker.say "restart worker process because of large memory consumption: #{mem.mb.to_i} MB." worker.stop worker_id = worker.name.scan(/delayed_job[.]{0,1}(\d*)/).flatten.first options = [] options << "--identifier=#{worker_id}" if worker_id.present? options << "--queue=#{worker.queues.join(',')}" if worker.queues.present? system("./bin/delayed_job restart #{options.join(' ')} RAILS_ENV=#{Rails.env} &") end end end end Delayed::Worker.plugins << Delayed::Plugins::OomChecker <file_sep>class GpArticle::DocsTagTag < ApplicationRecord include Sys::Model::Base end <file_sep>## --------------------------------------------------------- ## cms/concepts c_site = @site.concepts.where(parent_id: 0).first c_top = @site.concepts.where(name: 'トップページ').first c_content = @site.concepts.where(name: 'コンテンツ').first ## --------------------------------------------------------- ## cms/contents feed = create_cms_content c_content, 'Feed::Feed', 'フィード', 'feed' l_col1 = Cms::Layout.where(site_id: @site.id, name: 'col-1').first create_cms_node c_content, feed, 100, nil, l_col1, 'Feed::FeedEntry', 'feed', '新着記事一覧', nil <file_sep>module DateHelper def monthly_page_title(dates, date_style) dates.first.to_date.strftime(date_style) end def weekly_page_title(dates, date_style) %Q(#{dates.first.to_date.strftime(date_style)}~#{dates.last.to_date.strftime(date_style)}) end end <file_sep>class Cms::TalkTask < ApplicationRecord include Sys::Model::Base validates :path, presence: true end <file_sep>class GpArticle::Doc < ApplicationRecord include Sys::Model::Base include Sys::Model::Rel::Creator include Sys::Model::Rel::Editor include Sys::Model::Rel::EditableGroup include Sys::Model::Rel::File include Sys::Model::Rel::Task include Cms::Model::Base::Page include Cms::Model::Base::Page::Publisher include Cms::Model::Base::Page::TalkTask include Cms::Model::Rel::Inquiry include Cms::Model::Rel::Map include Cms::Model::Rel::Bracket include Cms::Model::Auth::Concept include Sys::Model::Auth::EditableGroup include GpArticle::Model::Rel::Doc include GpArticle::Model::Rel::Category include GpArticle::Model::Rel::Tag include Approval::Model::Rel::Approval include GpTemplate::Model::Rel::Template include GpArticle::Model::Rel::RelatedDoc include Cms::Model::Rel::PublishUrl include Cms::Model::Rel::Link include StateText include GpArticle::Docs::Preload STATE_OPTIONS = [['下書き保存', 'draft'], ['承認依頼', 'approvable'], ['即時公開', 'public']] TARGET_OPTIONS = [['無効', ''], ['同一ウィンドウ', '_self'], ['別ウィンドウ', '_blank'], ['添付ファイル', 'attached_file']] EVENT_STATE_OPTIONS = [['表示', 'visible'], ['非表示', 'hidden']] MARKER_STATE_OPTIONS = [['表示', 'visible'], ['非表示', 'hidden']] OGP_TYPE_OPTIONS = [['article', 'article']] FEATURE_1_OPTIONS = [['表示', true], ['非表示', false]] FEATURE_2_OPTIONS = [['表示', true], ['非表示', false]] QRCODE_OPTIONS = [['表示', 'visible'], ['非表示', 'hidden']] default_scope { where.not(state: 'archived') } scope :public_state, -> { where(state: 'public') } scope :mobile, ->(m) { m ? where(terminal_mobile: true) : where(terminal_pc_or_smart_phone: true) } scope :display_published_after, ->(date) { where(arel_table[:display_published_at].gteq(date)) } # Content belongs_to :content, :foreign_key => :content_id, :class_name => 'GpArticle::Content::Doc' validates :content_id, :presence => true # Page belongs_to :concept, :foreign_key => :concept_id, :class_name => 'Cms::Concept' belongs_to :layout, :foreign_key => :layout_id, :class_name => 'Cms::Layout' has_many :operation_logs, -> { where(item_model: 'GpArticle::Doc') }, foreign_key: :item_id, class_name: 'Sys::OperationLog' belongs_to :prev_edition, :class_name => self.name has_one :next_edition, :foreign_key => :prev_edition_id, :class_name => self.name belongs_to :marker_icon_category, :class_name => 'GpCategory::Category' has_many :categorizations, :class_name => 'GpCategory::Categorization', :as => :categorizable, :dependent => :destroy has_many :categories, -> { where(GpCategory::Categorization.arel_table[:categorized_as].eq('GpArticle::Doc')) }, :class_name => 'GpCategory::Category', :through => :categorizations, :after_add => proc {|d, c| d.categorizations.where(category_id: c.id, categorized_as: nil).first.update_columns(categorized_as: d.class.name) } has_many :event_categories, -> { where(GpCategory::Categorization.arel_table[:categorized_as].eq('GpCalendar::Event')) }, :class_name => 'GpCategory::Category', :through => :categorizations, :source => :category, :after_add => proc {|d, c| d.categorizations.where(category_id: c.id, categorized_as: nil).first.update_columns(categorized_as: 'GpCalendar::Event') } has_many :marker_categories, -> { where(GpCategory::Categorization.arel_table[:categorized_as].eq('Map::Marker')) }, :class_name => 'GpCategory::Category', :through => :categorizations, :source => :category, :after_add => proc {|d, c| d.categorizations.where(category_id: c.id, categorized_as: nil).first.update_columns(categorized_as: 'Map::Marker') } has_and_belongs_to_many :tags, ->(doc) { c = doc.content c && c.tag_related? && c.tag_content_tag ? where(content_id: c.tag_content_tag.id) : where(id: nil) }, class_name: 'Tag::Tag', join_table: 'gp_article_docs_tag_tags' has_many :holds, :as => :holdable, :dependent => :destroy before_save :set_name before_save :set_published_at before_save :replace_public before_save :set_serial_no after_destroy :close_page attr_accessor :link_check_results, :in_ignore_link_check attr_accessor :accessibility_check_results, :in_ignore_accessibility_check, :in_modify_accessibility_check validates :title, :presence => true, :length => {maximum: 200} validates :mobile_title, :length => {maximum: 200} validates :body, :length => {maximum: 300000} validates :mobile_body, :length => {maximum: 300000} validates :state, :presence => true validates :filename_base, :presence => true validate :name_validity, if: -> { name.present? } validate :node_existence validate :event_dates_range validate :body_limit_for_mobile validate :validate_accessibility_check, if: -> { !state_draft? && errors.blank? } validate :validate_broken_link_existence, if: -> { !state_draft? && errors.blank? } after_initialize :set_defaults after_save :set_display_attributes after_save GpArticle::Publisher::DocCallbacks.new, if: :changed? before_destroy GpArticle::Publisher::DocCallbacks.new scope :visible_in_list, -> { where(feature_1: true) } scope :event_scheduled_between, ->(start_date, end_date, category_ids) { rel = all rel = rel.where(arel_table[:event_ended_on].gteq(start_date)) if start_date.present? rel = rel.where(arel_table[:event_started_on].lt(end_date + 1)) if end_date.present? rel = rel.categorized_into_event(category_ids) if category_ids.present? rel } scope :content_and_criteria, ->(content, criteria) { rel = all rel = rel.where(arel_table[:content_id].eq(content.id)) if content rel = rel.with_target(criteria[:target]) if criteria[:target].present? rel = rel.with_target_state(criteria[:target_state]) if criteria[:target_state].present? [:state, :event_state, :marker_state].each do |key| rel = rel.where(key => criteria[key]) if criteria[key].present? end if criteria[:creator_user_name].present? rel = rel.operated_by_user_name('create', criteria[:creator_user_name]) end if criteria[:creator_group_id].present? rel = rel.operated_by_group('create', criteria[:creator_group_id]) end if criteria[:category_ids].present? && (category_ids = criteria[:category_ids].select(&:present?)).present? rel = rel.categorized_into_all(category_ids) end if criteria[:user_operation].present? rel = rel.operated_by_user_name(criteria[:user_operation], criteria[:user_name]) if criteria[:user_name].present? rel = rel.operated_by_group(criteria[:user_operation], criteria[:user_group_id]) if criteria[:user_group_id].present? end if criteria[:date_column].present? && criteria[:date_operation].present? dates = criteria[:dates].to_a.map { |date| date.present? ? (Date.parse(date) rescue nil) : nil }.compact rel = rel.search_date_column(criteria[:date_column], criteria[:date_operation], dates) end if criteria[:assocs].present? criteria[:assocs].select(&:present?).each { |assoc| rel = rel.joins(assoc.to_sym) } end if criteria[:tasks].present? criteria[:tasks].select(&:present?).each { |task| rel = rel.with_task_name(task) } end if criteria[:texts].present? criteria[:texts].select(&:present?).each do |column| rel = rel.where.not(arel_table[column].eq('')).where.not(arel_table[column].eq(nil)) end end search_columns = [:name, :title, :body, :subtitle, :summary, :mobile_title, :mobile_body] rel = rel.search_with_logical_query(*search_columns, criteria[:free_word]) if criteria[:free_word].present? rel = rel.where(serial_no: criteria[:serial_no]) if criteria[:serial_no].present? rel } scope :with_target, ->(target, user = Core.user) { case target when 'user' creators = Sys::Creator.arel_table approval_requests = Approval::ApprovalRequest.arel_table assignments = Approval::Assignment.arel_table joins(:creator).eager_load(:approval_requests => [:approval_flow => [:approvals => :assignments]]) .where( creators[:user_id].eq(user.id) .or(approval_requests[:user_id].eq(user.id) .or(assignments[:user_id].eq(user.id))) ) when 'group' editable when 'all' all else none end } scope :with_target_state, ->(target_state) { case target_state when 'processing' where(state: %w(draft approvable approved prepared)) when 'public' where(state: 'public') when 'finish' where(state: 'finish') when 'all' all else none end } scope :operated_by_user_name, ->(action, user_name) { case action when 'create' users = Sys::User.arel_table joins(creator: :user).where([ users[:name].matches("%#{user_name}%"), users[:name_en].matches("%#{user_name}%") ].reduce(:or)) else operation_logs = Sys::OperationLog.arel_table users = Sys::User.arel_table joins(operation_logs: :user) .where(operation_logs[:action].eq(action)) .where([ users[:name].matches("%#{user_name}%"), users[:name_en].matches("%#{user_name}%") ].reduce(:or)) end } scope :operated_by_group, ->(action, group_id) { case action when 'create' creators = Sys::Creator.arel_table joins(:creator).where(creators[:group_id].eq(group_id)) else operation_logs = Sys::OperationLog.arel_table users_groups = Sys::UsersGroup.arel_table joins(operation_logs: { user: :users_groups }) .where(operation_logs[:action].eq(action)) .where(users_groups[:group_id].eq(group_id)) end } scope :search_date_column, ->(column, operation, dates = nil) { dates = Array.wrap(dates) case operation when 'today' today = Date.today with_date_between(column, today, today) when 'this_week' today = Date.today with_date_between(column, today.beginning_of_week, today.end_of_week) when 'last_week' last_week = 1.week.ago with_date_between(column, last_week.beginning_of_week, last_week.end_of_week) when 'equal' with_date_between(column, dates[0], dates[0]) if dates[0] when 'before' where(arel_table[column].lteq(dates[0].end_of_day)) if dates[0] when 'after' where(arel_table[column].gteq(dates[0].beginning_of_day)) if dates[0] when 'between' with_date_between(column, dates[0], dates[1]) if dates[0] && dates[1] else none end } scope :with_date_between, ->(column, date1, date2) { where(arel_table[column].in(date1.beginning_of_day..date2.end_of_day)) } scope :categorized_into, ->(category_ids) { cats = GpCategory::Categorization.arel_table where(id: GpCategory::Categorization.select(:categorizable_id) .where(cats[:categorized_as].eq('GpArticle::Doc')) .where(cats[:category_id].in(category_ids))) } scope :categorized_into_all, ->(category_ids) { cats = GpCategory::Categorization.arel_table category_ids.inject(all) do |rel, category_id| rel = rel.where(id: GpCategory::Categorization.select(:categorizable_id) .where(cats[:categorized_as].eq('GpArticle::Doc')) .where(cats[:category_id].eq(category_id))) end } scope :categorized_into_event, ->(category_ids) { cats = GpCategory::Categorization.arel_table category_ids.inject(all) do |rel, category_id| rel = rel.where(id: GpCategory::Categorization.select(:categorizable_id) .where(cats[:categorized_as].eq('GpCalendar::Event')) .where(cats[:category_id].eq(category_id))) end } scope :organized_into, ->(group_ids) { groups = Sys::Group.arel_table joins(creator: :group).where(groups[:id].in(group_ids)) } def public_path return '' if public_uri.blank? "#{content.public_path}#{public_uri(without_filename: true)}#{filename_base}.html" end def public_smart_phone_path return '' if public_uri.blank? "#{content.public_path}/_smartphone#{public_uri(without_filename: true)}#{filename_base}.html" end def organization_content_related? organization_content = content.organization_content_group return organization_content && organization_content.article_related? && organization_content.related_article_content_id == content.id end def organization_group return @organization_group if defined? @organization_group @organization_group = if content.organization_content_group && creator.group content.organization_content_group.groups.detect{|og| og.sys_group_code == creator.group.code} else nil end end def public_uri(without_filename: false, with_closed_preview: false) uri = if organization_content_related? && organization_group "#{organization_group.public_uri}docs/#{name}/" elsif with_closed_preview && content.doc_node "#{content.doc_node.public_uri}#{name}/" elsif !with_closed_preview && content.public_node "#{content.public_node.public_uri}#{name}/" end return '' unless uri without_filename || filename_base == 'index' ? uri : "#{uri}#{filename_base}.html" end def public_full_uri(without_filename: false) uri = if organization_content_related? && organization_group "#{organization_group.public_full_uri}docs/#{name}/" elsif content.public_node "#{content.public_node.public_full_uri}#{name}/" end return '' unless uri without_filename || filename_base == 'index' ? uri : "#{uri}#{filename_base}.html" end def preview_uri(site: nil, mobile: false, smart_phone: false, without_filename: false, **params) base_uri = public_uri(without_filename: true, with_closed_preview: true) return nil if base_uri.blank? site ||= ::Page.site params = params.map{|k, v| "#{k}=#{v}" }.join('&') filename = without_filename || filename_base == 'index' ? '' : "#{filename_base}.html" page_flag = mobile ? 'm' : smart_phone ? 's' : '' path = "_preview/#{format('%04d', site.id)}#{page_flag}#{base_uri}preview/#{id}/#{filename}#{params.present? ? "?#{params}" : ''}" "#{site.main_admin_uri}#{path}" end def file_content_uri if state_public? %Q(#{public_uri}file_contents/) else %Q(#{content.admin_uri}/#{id}/file_contents/) end end def state_options options = if Core.user.has_auth?(:manager) || content.save_button_states.include?('public') STATE_OPTIONS else STATE_OPTIONS.reject{|so| so.last == 'public' } end if content.approval_related? options else options.reject{|o| o.last == 'approvable' } end end def state_draft? state == 'draft' end def state_approvable? state == 'approvable' end def state_approved? state == 'approved' end def state_prepared? state == 'prepared' end def state_public? state == 'public' end def state_closed? state == 'finish' end def close @save_mode = :close self.state = 'finish' if self.state_public? return false unless save(:validate => false) close_page return true end def close_page(options={}) return true if will_replace? return false unless super publishers.destroy_all unless publishers.empty? if p = public_path FileUtils.rm_rf(::File.dirname(public_path)) unless p.blank? end if p = public_smart_phone_path FileUtils.rm_rf(::File.dirname(public_smart_phone_path)) unless p.blank? end return true end def publish(content) @save_mode = :publish self.state = 'public' unless self.state_public? return false unless save(:validate => false) publish_page(content, path: public_path, uri: public_uri) publish_files publish_qrcode end def rebuild(content, options={}) if options[:dependent] == :smart_phone return false unless self.content.site.publish_for_smart_phone? return false unless self.content.site.spp_all? end return false unless self.state_public? @save_mode = :publish publish_page(content, options) #TODO: スマートフォン向けファイル書き出し要再検討 @public_files_path = "#{::File.dirname(public_smart_phone_path)}/file_contents" if options[:dependent] == :smart_phone @public_qrcode_path = "#{::File.dirname(public_smart_phone_path)}/qrcode.png" if options[:dependent] == :smart_phone result = publish_files publish_qrcode @public_files_path = nil if options[:dependent] == :smart_phone @public_qrcode_path = nil if options[:dependent] == :smart_phone return result end def external_link? target.present? && href.present? end def bread_crumbs(doc_node) crumbs = [] categories.public_state.each do |category| category_type = category.category_type if (node = category.content.public_node) crumb = node.bread_crumbs.crumbs.first crumb << [category_type.title, "#{node.public_uri}#{category_type.name}/"] category.ancestors.each {|a| crumb << [a.title, "#{node.public_uri}#{category_type.name}/#{a.path_from_root_category}/"] } crumbs << crumb end end if organization = content.organization_content_group if (node = organization.public_node) && (og = organization.groups.where(state: 'public', sys_group_code: creator.group.try(:code)).first) crumb = node.bread_crumbs.crumbs.first og.ancestors.each {|a| crumb << [a.sys_group.name, "#{node.public_uri}#{a.path_from_root}/"] } crumbs << crumb end end if crumbs.empty? doc_node.routes.each do |r| crumb = [] r.each {|i| crumb << [i.title, i.public_uri] } crumbs << crumb end end Cms::Lib::BreadCrumbs.new(crumbs) end def duplicate(dup_for=nil) new_attributes = self.attributes new_attributes[:state] = 'draft' new_attributes[:id] = nil new_attributes[:created_at] = nil new_attributes[:updated_at] = nil new_attributes[:recognized_at] = nil new_attributes[:prev_edition_id] = nil new_doc = self.class.new(new_attributes) case dup_for when :replace new_doc.prev_edition = self self.tasks.each do |task| new_doc.tasks.build(site_id: task.site_id, name: task.name, process_at: task.process_at) end new_doc.creator_attributes = { group_id: creator.group_id, user_id: creator.user_id } else new_doc.name = nil new_doc.title = new_doc.title.gsub(/^(【複製】)*/, '【複製】') new_doc.display_updated_at = nil new_doc.published_at = nil new_doc.display_published_at = nil new_doc.serial_no = nil end editable_groups.each do |eg| new_doc.editable_groups.build(group_id: eg.group_id) end related_docs.each do |rd| new_doc.related_docs.build(name: rd.name, content_id: rd.content_id) end inquiries.each_with_index do |inquiry, i| attrs = inquiry.attributes attrs[:id] = nil attrs[:group_id] = Core.user.group_id if i == 0 new_doc.inquiries.build(attrs) end maps.each do |map| new_map = new_doc.maps.build(map.attributes.slice('name', 'title', 'map_lat', 'map_lng', 'map_zoom')) map.markers.each do |marker| new_map.markers.build(marker.attributes.slice('name', 'lat', 'lng')) end end new_doc.save! files.each do |f| new_attributes = f.attributes new_attributes[:id] = nil Sys::File.new(new_attributes).tap do |new_file| new_file.file = Sys::Lib::File::NoUploadedFile.new(f.upload_path, :mime_type => new_file.mime_type) new_file.file_attachable = new_doc new_file.save end end new_doc.categories = self.categories new_doc.event_categories = self.event_categories new_doc.marker_categories = self.marker_categories new_doc.categorizations.each do |new_c| self_c = self.categorizations.where(category_id: new_c.category_id, categorized_as: new_c.categorized_as).first new_c.update_column(:sort_no, self_c.sort_no) end return new_doc end def editable? result = super return result unless result.nil? # See "Sys::Model::Auth::EditableGroup" return approval_participators.include?(Core.user) end def publishable? super || approval_participators.include?(Core.user) end def formated_display_published_at display_published_at.try(:strftime, content.date_style) end def formated_display_updated_at display_updated_at.try(:strftime, content.date_style) end def default_map_position [content.setting_extra_value(:map_relation, :lat_lng), content.site.setting_site_map_coordinate].lazy.each do |pos| p = pos.to_s.split(',').map(&:strip) return p if p.size == 2 end super end def links_in_body(all=false) extract_links(self.body, all) end def check_links_in_body check_links(links_in_body) end def links_in_mobile_body(all=false) extract_links(self.mobile_body, all) end def links_in_string(str, all=false) extract_links(str, all) end def backlinks return self.class.none unless state_public? || state_closed? return self.class.none if public_uri.blank? links.klass.where(links.table[:url].matches("%#{self.public_uri(without_filename: true).sub(/\/$/, '')}%")) .where(linkable_type: self.class.name) end def backlinked_docs return [] if backlinks.blank? self.class.where(id: backlinks.pluck(:linkable_id)) end def check_accessibility Util::AccessibilityChecker.check(body) end def modify_accessibility self.body = Util::AccessibilityChecker.modify(body) end def replace_words_with_dictionary dic = content.setting_value(:word_dictionary) return if dic.blank? words = [] dic.split(/\r\n|\n/).each do |line| next if line !~ /,/ data = line.split(/,/) words << [data[0].strip, data[1].strip] end if body.present? words.each {|src, dst| self.body = body.gsub(src, dst) } end if mobile_body.present? words.each {|src, dst| self.mobile_body = mobile_body.gsub(src, dst) } end end def body_for_mobile body_doc = Nokogiri::XML("<bory_root>#{self.mobile_body.presence || self.body}</bory_root>") body_doc.xpath('//img').each {|img| img.replace(img.attribute('alt').try(:value).to_s) } body_doc.xpath('//a').each {|a| a.replace(a.text) if a.attribute('href').try(:value) =~ %r!^file_contents/! } body_doc.xpath('/bory_root').to_xml.gsub(%r!^<bory_root>|</bory_root>$!, '') end def will_replace? prev_edition && (state_draft? || state_approvable? || state_approved? || state_prepared?) end def will_be_replaced? next_edition && state_public? end def qrcode_visible? return false unless content && content.qrcode_related? return false unless self.qrcode_state == 'visible' return true end def og_type_text OGP_TYPE_OPTIONS.detect{|o| o.last == self.og_type }.try(:first).to_s end def target_text TARGET_OPTIONS.detect{|o| o.last == self.target }.try(:first).to_s end def event_state_text EVENT_STATE_OPTIONS.detect{|o| o.last == self.event_state }.try(:first).to_s end def marker_state_text MARKER_STATE_OPTIONS.detect{|o| o.last == self.marker_state }.try(:first).to_s end def feature_1_text FEATURE_1_OPTIONS.detect{|o| o.last == self.feature_1 }.try(:first).to_s end def feature_2_text FEATURE_2_OPTIONS.detect{|o| o.last == self.feature_2 }.try(:first).to_s end def qrcode_state_text QRCODE_OPTIONS.detect{|o| o.last == self.qrcode_state }.try(:first).to_s end def public_files_path return @public_files_path if @public_files_path "#{::File.dirname(public_path)}/file_contents" end def qrcode_path return @public_qrcode_path if @public_qrcode_path "#{::File.dirname(public_path)}/qrcode.png" end def qrcode_uri(preview: false) if preview "#{preview_uri(without_filename: true)}qrcode.png" else "#{public_uri(without_filename: true)}qrcode.png" end end def event_state_visible? event_state == 'visible' end def send_broken_link_notification backlinked_docs.each do |doc| GpArticle::Admin::Mailer.broken_link_notification(self, doc).deliver_now end end def lang_text content.lang_options.rassoc(lang).try(:first) end def link_to_options if target.present? if href.present? if target == 'attached_file' if (file = files.find_by(name: href)) ["#{public_uri}file_contents/#{file.name}", target: '_blank'] else nil end else [href, target: target] end else nil end else [public_uri] end end private def name_validity errors.add(:name, :invalid) if name !~ /^[\-\w]*$/ doc = self.class.where(content_id: content_id, name: name) doc = doc.where.not(serial_no: serial_no) if serial_no errors.add(:name, :taken) if doc.exists? end def set_name return if self.name.present? date = if created_at created_at.strftime('%Y%m%d') else Date.strptime(Core.now, '%Y-%m-%d').strftime('%Y%m%d') end seq = Util::Sequencer.next_id('gp_article_docs', version: date, site_id: content.site_id) self.name = Util::String::CheckDigit.check(date + format('%04d', seq)) end def set_published_at self.published_at ||= Core.now if self.state == 'public' end def set_defaults self.target ||= TARGET_OPTIONS.first.last if self.has_attribute?(:target) self.event_state ||= 'hidden' if self.has_attribute?(:event_state) self.marker_state ||= 'hidden' if self.has_attribute?(:marker_state) self.terminal_pc_or_smart_phone = true if self.has_attribute?(:terminal_pc_or_smart_phone) && self.terminal_pc_or_smart_phone.nil? self.terminal_mobile = true if self.has_attribute?(:terminal_mobile) && self.terminal_mobile.nil? self.body_more_link_text ||= '続きを読む' if self.has_attribute?(:body_more_link_text) self.filename_base ||= 'index' if self.has_attribute?(:filename_base) set_defaults_from_content if new_record? end def set_defaults_from_content return unless content self.qrcode_state = content.qrcode_default_state if self.has_attribute?(:qrcode_state) && self.qrcode_state.nil? self.feature_1 = content.feature_settings[:feature_1] if self.has_attribute?(:feature_1) && self.feature_1.nil? self.feature_2 = content.feature_settings[:feature_2] if self.has_attribute?(:feature_2) && self.feature_2.nil? if !content.setting_value(:basic_setting).blank? self.layout_id ||= content.setting_extra_value(:basic_setting, :default_layout_id).to_i self.concept_id ||= content.setting_value(:basic_setting).to_i elsif (node = content.public_node) self.layout_id ||= node.layout_id self.concept_id ||= node.concept_id else self.concept_id ||= content.concept_id end end def set_display_attributes self.update_column(:display_published_at, self.published_at) unless self.display_published_at self.update_column(:display_updated_at, self.updated_at) if self.display_updated_at.blank? || !self.keep_display_updated_at end def set_serial_no return if self.serial_no.present? seq = Util::Sequencer.next_id('gp_article_doc_serial_no', version: self.content_id, site_id: content.site_id) self.serial_no = seq end def node_existence unless content.public_node case state when 'public' errors.add(:base, '記事コンテンツのディレクトリが作成されていないため、即時公開が行えません。') when 'approvable' errors.add(:base, '記事コンテンツのディレクトリが作成されていないため、承認依頼が行えません。') end end end def validate_platform_dependent_characters [:title, :body, :mobile_title, :mobile_body].each do |attr| if chars = Util::String.search_platform_dependent_characters(send(attr)) errors.add attr, :platform_dependent_characters, :chars => chars end end end def event_dates_range return if self.event_started_on.blank? && self.event_ended_on.blank? self.event_started_on = self.event_ended_on if self.event_started_on.blank? self.event_ended_on = self.event_started_on if self.event_ended_on.blank? errors.add(:event_ended_on, "が#{self.class.human_attribute_name :event_started_on}を過ぎています。") if self.event_ended_on < self.event_started_on end def extract_links(html, all) links = Nokogiri::HTML.parse(html).css('a[@href]') .map { |a| { body: a.text, url: a.attribute('href').value } } return links if all links.select do |link| uri = Addressable::URI.parse(link[:url]) !uri.absolute? || uri.scheme.to_s.downcase.in?(%w(http https)) end rescue => evar warn_log evar.message return [] end def check_links(links) links.map{|link| uri = Addressable::URI.parse(link[:url]) url = unless uri.absolute? next unless uri.path =~ /^\// "#{content.site.full_uri.sub(/\/$/, '')}#{uri.path}" else uri.to_s end res = Util::LinkChecker.check_url(url) {body: link[:body], url: url, status: res[:status], reason: res[:reason], result: res[:result]} }.compact end def validate_broken_link_existence return if content.site.setting_site_link_check != 'enabled' return if in_ignore_link_check == '1' results = check_links_in_body if results.any? {|r| !r[:result] } self.link_check_results = results errors.add(:base, 'リンクチェック結果を確認してください。') end end def publish_qrcode return true unless self.state_public? return true unless self.qrcode_visible? return true if Zomeki.config.application['sys.clean_statics'] Util::Qrcode.create(self.public_full_uri, self.qrcode_path) return true end def validate_accessibility_check return if content.site.setting_site_accessibility_check != 'enabled' modify_accessibility if in_modify_accessibility_check == '1' results = check_accessibility if (results.present? && in_ignore_accessibility_check != '1') || errors.present? self.accessibility_check_results = results errors.add(:base, 'アクセシビリティチェック結果を確認してください。') end end def body_limit_for_mobile limit = Zomeki.config.application['gp_article.body_limit_for_mobile'].to_i current_size = self.body_for_mobile.bytesize if current_size > limit target = self.mobile_body.present? ? :mobile_body : :body errors.add(target, "が携帯向け容量制限#{limit}バイトを超えています。(現在#{current_size}バイト)") end end def replace_public prev_edition.destroy if state_public? && prev_edition end end <file_sep>class Rank::Category < ApplicationRecord include Sys::Model::Base belongs_to :content, foreign_key: :content_id, class_name: 'Rank::Content::Rank' end <file_sep>## --------------------------------------------------------- ## cms/concepts c_site = @site.concepts.where(parent_id: 0).first c_top = @site.concepts.where(name: 'トップページ').first c_content = @site.concepts.where(name: 'コンテンツ').first c_event = @site.concepts.where(name: 'イベント').first ## --------------------------------------------------------- ## cms/contents calendar = create_cms_content c_content, 'GpCalendar::Event', 'イベント', 'event' category = GpCategory::Content::CategoryType.first categories = GpCategory::CategoryType.where(name: 'event').pluck(:id) setting = GpCalendar::Content::Setting.config(calendar, 'gp_category_content_category_type_id') setting.value = category.id setting.extra_values = {category_types: categories} setting.save l_event = create_cms_layout c_site, 'event-calendar', 'イベント' n_list = create_cms_node c_content, calendar, 130, nil, l_event, 'GpCalendar::Event', 'event_list', 'イベント一覧', nil n_event = create_cms_node c_content, calendar, 140, nil, l_event, 'GpCalendar::CalendarStyledEvent', 'calendar', 'イベントカレンダー', nil n_today = create_cms_node c_content, calendar, 150, nil, l_event, 'GpCalendar::TodaysEvent', 'todays_event', '今日のイベント', nil ## --------------------------------------------------------- ## cms/pieces key = create_cms_piece c_site, calendar, 'GpCalendar::DailyLink', 'calendar', 'イベントカレンダー', 'イベントカレンダー' key.in_settings = {target_node_id: n_list.id} key.save create_cms_piece c_site, calendar, 'GpCalendar::NearFutureEvent', 'todays-event', '本日・明日のイベント' create_cms_piece c_event, calendar, 'GpCalendar::NearFutureEvent', 'todays_event', '本日と明日のイベント' <file_sep>Cms::Lib::Modules::ModuleSet.draw :cms, '標準機能', 1 do |mod| ## contents ; ## directory mod.directory :directories, 'ディレクトリ' ## pages mod.page :pages, '自由形式' mod.page :sitemaps, 'サイトマップ' ## pieces mod.piece :frees, '自由形式' mod.piece :page_titles, 'ページタイトル' mod.piece :bread_crumbs, 'パンくず' mod.piece :links, 'リンク集' mod.piece :sns_parts, 'SNSパーツ' mod.piece :pickup_docs, 'ピックアップ記事' end <file_sep>module Cms::InquiryHelper def inquiry_replace(inquiry, inquiry_style) contents = { name: -> { inquiry_replace_name(inquiry) }, address: -> { inquiry_replace_address(inquiry) }, tel: -> { inquiry_replace_tel(inquiry) }, fax: -> { inquiry_replace_fax(inquiry) }, email: -> { inquiry_replace_email(inquiry) }, email_link: -> { inquiry_replace_email_link(inquiry) }, note: -> { inquiry_replace_note(inquiry) }, } inquiry_style = inquiry_style.gsub(/@(\w+)@/) { |m| contents[$1.to_sym].try(:call).to_s } inquiry_style.html_safe end private def inquiry_replace_name(inquiry) if (group = inquiry.group) && group.name.present? content_tag :div, group.name, class: 'section' else '' end end def inquiry_replace_address(inquiry) if inquiry.address.present? content_tag :div, class: 'address' do concat content_tag :span, '住所', class: 'label' concat ":#{inquiry.address}" end else '' end end def inquiry_replace_tel(inquiry) if inquiry.tel.present? content_tag :div, class: 'tel' do concat content_tag :span, 'TEL', class: 'label' concat ":#{inquiry.tel}#{inquiry.tel_attend}" end else '' end end def inquiry_replace_fax(inquiry) if inquiry.fax.present? content_tag :div, inquiry.fax, class: 'fax' do concat content_tag :span, 'FAX', class: 'label' concat ":#{inquiry.fax}" end else '' end end def inquiry_replace_email(inquiry) if inquiry.email.present? content_tag :div, class: 'email' do concat content_tag :span, 'E-Mail', class: 'label' concat ":#{inquiry.email}" end else '' end end def inquiry_replace_email_link(inquiry) if inquiry.email.present? content_tag :div, class: 'email' do concat content_tag :span, 'E-Mail', class: 'label' concat ':' concat mail_to inquiry.email end else '' end end def inquiry_replace_note(inquiry) if inquiry.note.present? content_tag :div, class: 'note' do concat content_tag :span, '備考', class: 'label' concat ":#{inquiry.note}" end else '' end end end <file_sep>class Cms::SiteSetting < ApplicationRecord include Sys::Model::Base include Cms::Model::Rel::Site include Cms::Model::Auth::Site validates :site_id, :name, presence: true SSL_OPTIONS = [['使用する', 'enabled'], ['使用しない', 'disabled']] LINK_CHECK_OPTIONS = [['使用する', 'enabled'], ['使用しない', 'disabled']] ACCESSIBILITY_CHECK_OPTIONS = [['使用する', 'enabled'], ['使用しない', 'disabled']] KANA_TALK_OPTIONS = [['ふりがなと音声を書き出し', 'enabled'], ['ふりがなのみ書き出し', 'kana_only'], ['書き出さない', 'disabled']] SITE_CONFIGS = [ { id: "common_ssl", name: "共有SSL", setting_name: :setting_site_common_ssl_label }, { id: "admin_mail_sender", name: "管理者メール送信元アドレス", setting_name: :in_setting_site_admin_mail_sender }, { id: "allowed_attachment_type", name: "添付ファイル/許可する種類", setting_name: :in_setting_site_allowed_attachment_type }, { id: "file_upload_max_size", name: "添付ファイル最大サイズ", setting_name: :in_setting_site_file_upload_max_size }, { id: "link_check", name: "リンクチェック機能", setting_name: :setting_site_link_check_label }, { id: "accessibility_check", name: "アクセシビリティチェック機能", setting_name: :setting_site_accessibility_check_label }, { id: "kana_talk", name: "ふりがな・音声", setting_name: :setting_site_kana_talk_label }, { id: "map_coordinate", name: "地図/デフォルト座標", setting_name: :setting_site_map_coordinate }, ] end <file_sep>namespace :zomeki do namespace :gp_calendar do desc 'Publish todays events' task :publish_todays_events => :environment do Cms::Site.order(:id).pluck(:id).each do |site_id| node_ids = Cms::Node.public_state.where(site_id: site_id, model: 'GpCalendar::TodaysEvent').pluck(:id) Script.run("cms/nodes/publish", site_id: site_id, target_node_id: node_ids, lock_by: :site) end end end end <file_sep>class Cms::PublishUrl < ApplicationRecord include Sys::Model::Base end <file_sep>class Sys::ObjectRelation < ApplicationRecord include Sys::Model::Base belongs_to :source, polymorphic: true, required: true belongs_to :related, polymorphic: true, required: true end <file_sep>class Survey::FormsScript < Cms::Script::Publication def publish end def publish_by_task if (item = params[:item]).try(:state_approved?) ::Script.current info_log "-- Publish: #{item.class}##{item.id}" if item.publish Sys::OperationLog.script_log(:item => item, :site => item.content.site, :action => 'publish') else raise item.errors.full_messages end info_log %Q!OK: Published to "#{item.class}##{item.id}"! params[:task].destroy ::Script.success end end def close_by_task if (item = params[:item]).try(:state_public?) ::Script.current info_log "-- Close: #{item.class}##{item.id}" item.close Sys::OperationLog.script_log(:item => item, :site => item.content.site, :action => 'close') info_log 'OK: Closed' params[:task].destroy ::Script.success end end end <file_sep>class Survey::Form < ApplicationRecord include Sys::Model::Base include Cms::Model::Base::Sitemap include Sys::Model::Rel::Creator include Sys::Model::Rel::Task include Cms::Model::Auth::Content include Approval::Model::Rel::Approval include StateText STATE_OPTIONS = [['下書き保存', 'draft'], ['承認依頼', 'approvable'], ['即時公開', 'public']] CONFIRMATION_OPTIONS = [['あり', true], ['なし', false]] INDEX_LINK_OPTIONS = [['表示', 'visible'], ['非表示', 'hidden']] default_scope { order("#{self.table_name}.sort_no IS NULL, #{self.table_name}.sort_no") } # Content belongs_to :content, :foreign_key => :content_id, :class_name => 'Survey::Content::Form' validates :content_id, presence: true has_many :operation_logs, -> { where(item_model: 'Survey::Form') }, foreign_key: :item_id, class_name: 'Sys::OperationLog' has_many :questions, :dependent => :destroy has_many :form_answers, :dependent => :destroy validates :state, presence: true validates :name, presence: true, uniqueness: { scope: :content_id }, format: { with: /\A[-\w]*\z/ } validates :title, presence: true after_initialize :set_defaults after_save Cms::Publisher::ContentRelatedCallbacks.new, if: :changed? before_destroy Cms::Publisher::ContentRelatedCallbacks.new scope :public_state, -> { where(state: 'public') } def self.all_with_content_and_criteria(content, criteria) forms = self.arel_table rel = self.where(forms[:content_id].eq(content.id)) rel = rel.where(forms[:state].eq(criteria[:state])) if criteria[:state].present? if criteria[:touched_user_id].present? || criteria[:editable].present? creators = Sys::Creator.arel_table rel = rel.joins(:creator) end if criteria[:touched_user_id].present? operation_logs = Sys::OperationLog.arel_table rel = rel.eager_load(:operation_logs).where(operation_logs[:user_id].eq(criteria[:touched_user_id]) .or(creators[:user_id].eq(criteria[:touched_user_id]))) end if criteria[:approvable].present? approval_requests = Approval::ApprovalRequest.arel_table assignments = Approval::Assignment.arel_table rel = rel.joins(:approval_requests => [:approval_flow => [:approvals => :assignments]]) .where(approval_requests[:user_id].eq(Core.user.id) .or(assignments[:user_id].eq(Core.user.id))).distinct end return rel end def public_questions questions.public_state end def automatic_reply? return true if automatic_reply_question false end def automatic_reply_question public_questions.each do |q| return q if q.email_field? end return nil end def open? now = Time.now return false if opened_at && opened_at > now return false if closed_at && closed_at < now return true end def state_options options = STATE_OPTIONS.clone options.reject!{|o| o.last == 'public' } unless Core.user.has_auth?(:manager) options.reject!{|o| o.last == 'approvable' } unless content.approval_related? return options end def state_draft? state == 'draft' end def state_approvable? state == 'approvable' end def state_approved? state == 'approved' end def state_public? state == 'public' end def duplicate item = self.class.new(self.attributes) item.id = nil item.created_at = nil item.updated_at = nil item.name = nil item.title = item.title.gsub(/^(【複製】)*/, "【複製】") item.state = "draft" return false unless item.save(validate: false) questions.each do |question| dupe_question = Survey::Question.new(question.attributes.except('id')) dupe_question.form_id = item.id dupe_question.created_at = nil dupe_question.updated_at = nil dupe_question.save(validate: false) end return item end def publish return unless state_approved? approval_requests.destroy_all update_column(:state, 'public') end def close return unless state_public? update_column(:state, 'closed') end def public_uri(with_closed_preview: false) node = if with_closed_preview content.form_node else content.public_node end return nil unless node "#{node.public_uri}#{name}" end def preview_uri(site: nil, mobile: false, smart_phone: false, params: {}) return nil unless public_uri(with_closed_preview: true) site ||= ::Page.site params = params.map{|k, v| "#{k}=#{v}" }.join('&') path = "_preview/#{format('%04d', site.id)}#{mobile ? 'm' : smart_phone ? 's' : ''}#{public_uri(with_closed_preview: true)}#{params.present? ? "?#{params}" : ''}" "#{site.main_admin_uri}#{path}" end def index_visible? self.index_link != 'hidden' end private def set_defaults self.state = STATE_OPTIONS.first.last if self.has_attribute?(:state) && self.state.nil? self.confirmation = CONFIRMATION_OPTIONS.first.last if self.has_attribute?(:confirmation) && self.confirmation.nil? self.index_link = INDEX_LINK_OPTIONS.first.last if self.has_attribute?(:index_link) && self.index_link.nil? self.sort_no = 10 if self.has_attribute?(:sort_no) && self.sort_no.nil? end end <file_sep>class Cms::SiteBasicAuthUser < ApplicationRecord include Sys::Model::Base include Sys::Model::Base::Page include Sys::Model::Rel::Creator include Cms::Model::Auth::Site include StateText belongs_to :site after_initialize :set_defaults validates :site_id, :state, :name, :password, presence: true validates :target_location, presence: {message: :blank}, format: { with: /\A[0-9A-Za-z@\.\-_\+\s]+\z/, message: :not_a_filename }, if: %Q(is_directory?) TARGET_TYPE_LIST = [['サイト全体','all'],['管理画面','_system'],['ディレクトリ','directory'],] scope :root_location, -> { where(target_type: 'all') } scope :system_location, -> { where(target_type: '_system') } scope :directory_location, -> { where(target_type: 'directory') } scope :enabled, -> { where(state: 'enabled') } scope :directory_auth, -> { select(:target_location).directory_location .enabled.group(:target_location) .except(:order).order(:target_location) } def states [['有効','enabled'],['無効','disabled']] end def target_type_label TARGET_TYPE_LIST.each{|a| return a[0] if a[1] == target_type } return nil end def is_directory? target_type == 'directory' end private def set_defaults self.target_type ||= TARGET_TYPE_LIST.first.last if self.has_attribute?(:target_type) end end <file_sep>require 'rails_helper' RSpec.describe GpArticle::Link, type: :model do it 'has a valid factory' do link = build(:gp_article_link) expect(link).to be_valid end it 'is invalid without a doc' do link = build(:gp_article_link, doc: nil) link.validate expect(link.errors[:doc_id].size).to eq 1 end end <file_sep>class Rank::Admin::Content::SettingsController < Cms::Admin::Content::SettingsController include Rank::Controller::Rank def model Rank::Content::Setting end def update @item = model.config(@content, params[:id]) @item.value = params[:item][:value] @item.extra_values = params[:item][:extra_values] if params[:item][:extra_values] _update @item do if @item.name == 'google_oauth' && @item.value.blank? return redirect_to action: :edit end end end def import get_access(@content, nil) redirect_to :action => :index end def makeup calc_access(@content) redirect_to :action => :index end end <file_sep>class GpArticle::Tool::DocsScript < Cms::Script::Base include Cms::Controller::Layout def rebuild content = GpArticle::Content::Doc.find(params[:content_id]) return unless content doc_ids = content.public_docs.order(content.docs_order_as_hash).pluck(:id) doc_ids.each_slice(100) do |sliced_doc_ids| content.public_docs.where(id: sliced_doc_ids).each do |doc| ::Script.progress(doc) do if doc.rebuild(render_public_as_string("#{doc.public_uri}index.html", site: content.site)) doc.publish_page(render_public_as_string("#{doc.public_uri}index.html.r", site: content.site), path: "#{doc.public_path}.r", dependent: :ruby) doc.rebuild(render_public_as_string("#{doc.public_uri}index.html", site: content.site, agent_type: :smart_phone), path: doc.public_smart_phone_path, dependent: :smart_phone) end end end end Cms::NodesScript.new(target_node_id: content.public_nodes.pluck(:id)).publish if content.public_nodes.present? end end <file_sep>class Cms::Admin::Tool::RebuildController < Cms::Controller::Admin::Base include Sys::Controller::Scaffold::Base def pre_dispatch return error_auth unless Core.user.has_auth?(:designer) end def index content_models = [ 'GpArticle::Doc', 'GpCategory::CategoryType', 'Organization::Group', 'AdBanner::Banner', 'Map::Marker', 'GpCalendar::Event', 'Tag::Tag', 'Rank::Rank', 'Gnav::MenuItem', 'Feed::Feed', 'BizCalendar::Place' ] @contents = Cms::Content.distinct.joins(:nodes) .where(site_id: Core.site.id, model: content_models) .where(Cms::Node.arel_table[:state].eq('public')) .order(:name) @nodes = Cms::Node.public_state .where(site_id: Core.site.id, model: ['Cms::Page', 'Cms::Sitemap']) .preload(:site, parent: { parent: { parent: nil } }) .sort_by { |n| n.public_uri } end def rebuild_contents contents = Cms::Content.where(id: params[:target_content_ids]) return redirect_to(url_for(action: 'index'), alert: '対象を選択してください。') if contents.empty? Cms::RebuildJob.perform_later(site_id: Core.site.id, target_content_ids: contents.map(&:id)) redirect_to url_for(action: 'index'), notice: '再構築を開始しました。完了までに時間がかかる場合があります。' end def rebuild_nodes nodes = Cms::Node.where(id: params[:target_node_ids]) return redirect_to(url_for(action: 'index'), alert: '対象を選択してください。') if nodes.empty? Cms::RebuildJob.perform_later(site_id: Core.site.id, target_node_ids: nodes.map(&:id)) redirect_to url_for(action: 'index'), notice: '再構築を開始しました。完了までに時間がかかる場合があります。' end def rebuild_params params.except(:concept).permit(:target_node_ids, :target_content_ids) end end
78112f22b04b29470d34944135aba9af88c02adf
[ "Ruby" ]
157
Ruby
meihaoGit/zomeki3
b455b667d79982c72df54a003e1531975c9cbfbd
8104c8c1277bb9353b6f0c858b30a2d900eb2f51
refs/heads/master
<file_sep>import {useState} from 'react' import './App.css'; /** @jsx jsx */ import { jsx } from '@emotion/core' // Local import Footer from './Footer' import Header from './Header' import Main from './Main' import Login from './Login' const styles = { root: { boxSizing: 'border-box', display: 'flex', flexDirection: 'column', backgroundColor: '#565E71', padding: '50px', }, } export default () => { const [user, setUser] = useState(null) const [drawerMobileVisible, setDrawerMobileVisible] = useState(false) const drawerToggleListener = () => { setDrawerMobileVisible(!drawerMobileVisible) } return ( <div className="App" css={styles.root}> <Header drawerToggleListener={drawerToggleListener}/> { user ? <Main drawerMobileVisible={drawerMobileVisible} /> : <Login onUser={setUser} /> } <Footer /> </div> ); } <file_sep>import {} from 'react'; /** @jsx jsx */ import { jsx } from '@emotion/core' // Layout import { useTheme } from '@material-ui/core/styles'; import Grid from '@material-ui/core/Grid'; import Typography from '@material-ui/core/Typography'; import {ReactComponent as ChannelIcon} from './icons/channel.svg'; import {ReactComponent as FriendsIcon} from './icons/friends.svg'; import {ReactComponent as SettingsIcon} from './icons/settings.svg'; const useStyles = (theme) => ({ root: { height: '100%', flex: '1 1 auto', display: 'flex', // background: 'rgba(0,0,0,.2)', }, card: { textAlign: 'center', }, icon: { width: '30%', fill: '#fff', } }) export default () => { const styles = useStyles(useTheme()) return ( <div css={styles.root}> <Grid container direction="row" justify="center" alignItems="center" spacing={5} > <Grid item xs> <div css={styles.card}> <ChannelIcon css={styles.icon} /> <Typography color="textPrimary"> Create channels </Typography> </div> </Grid> <Grid item xs> <div css={styles.card}> <FriendsIcon css={styles.icon} /> <Typography color="textPrimary"> Invite friends </Typography> </div> </Grid> <Grid item xs> <div css={styles.card}> <SettingsIcon css={styles.icon} /> <Typography color="textPrimary"> Settings </Typography> </div> </Grid> </Grid> </div> ); } <file_sep>import {useRef, useState} from 'react'; import axios from 'axios'; /** @jsx jsx */ import { jsx } from '@emotion/core' // Layout import { useTheme } from '@material-ui/core/styles'; import Fab from '@material-ui/core/Fab'; import ArrowDropDownIcon from '@material-ui/icons/ArrowDropDown'; // Local import Form from './channel/Form' import List from './channel/List' const useStyles = (theme) => ({ root: { height: '100%', flex: '1 1 auto', display: 'flex', flexDirection: 'column', position: 'relative', overflowX: 'auto', }, fab: { position: 'absolute !important', top: theme.spacing(2), right: theme.spacing(2), }, fabDisabled: { display: 'none !important', } }) export default ({ channel }) => { const styles = useStyles(useTheme()) const listRef = useRef(); const channelId = useRef() const [messages, setMessages] = useState([]) const [scrollDown, setScrollDown] = useState(false) const addMessage = (message) => { fetchMessages() } const fetchMessages = async () => { setMessages([]) const {data: messages} = await axios.get(`http://localhost:3001/channels/${channel.id}/messages`) setMessages(messages) if(listRef.current){ listRef.current.scroll() } } if(channelId.current !== channel.id){ fetchMessages() channelId.current = channel.id } const onScrollDown = (scrollDown) => { setScrollDown(scrollDown) } const onClickScroll = () => { listRef.current.scroll() } return ( <div css={styles.root}> <List channel={channel} messages={messages} onScrollDown={onScrollDown} ref={listRef} /> <Form addMessage={addMessage} channel={channel} /> <Fab color="primary" aria-label="Latest messages" css={[styles.fab, scrollDown || styles.fabDisabled]} onClick={onClickScroll} > <ArrowDropDownIcon /> </Fab> </div> ); } <file_sep>import {forwardRef, useImperativeHandle, useLayoutEffect, useRef} from 'react' /** @jsx jsx */ import { jsx } from '@emotion/core' // Layout import { useTheme } from '@material-ui/core/styles'; // Markdown import unified from 'unified' import markdown from 'remark-parse' import remark2rehype from 'remark-rehype' import html from 'rehype-stringify' // Time import dayjs from 'dayjs' import calendar from 'dayjs/plugin/calendar' import updateLocale from 'dayjs/plugin/updateLocale' dayjs.extend(calendar) dayjs.extend(updateLocale) dayjs.updateLocale('en', { calendar: { sameElse: 'DD/MM/YYYY hh:mm A' } }) const useStyles = (theme) => ({ root: { position: 'relative', flex: '1 1 auto', 'pre': { overflowY: 'auto', }, '& ul': { 'margin': 0, 'padding': 0, 'textIndent': 0, 'listStyleType': 0, }, }, message: { padding: '.2rem .5rem', ':hover': { backgroundColor: 'rgba(255,255,255,.05)', }, }, fabWrapper: { position: 'absolute', right: 0, top: 0, width: '50px', }, fab: { position: 'fixed !important', top: 0, width: '50px', }, }) export default forwardRef(({ channel, messages, onScrollDown, }, ref) => { const styles = useStyles(useTheme()) // Expose the `scroll` action useImperativeHandle(ref, () => ({ scroll: scroll })); const rootEl = useRef(null) const scrollEl = useRef(null) const scroll = () => { scrollEl.current.scrollIntoView() } // See https://dev.to/n8tb1t/tracking-scroll-position-with-react-hooks-3bbj const throttleTimeout = useRef(null) // react-hooks/exhaustive-deps useLayoutEffect( () => { const rootNode = rootEl.current // react-hooks/exhaustive-deps const handleScroll = () => { if (throttleTimeout.current === null) { throttleTimeout.current = setTimeout(() => { throttleTimeout.current = null const {scrollTop, offsetHeight, scrollHeight} = rootNode // react-hooks/exhaustive-deps onScrollDown(scrollTop + offsetHeight < scrollHeight) }, 200) } } handleScroll() rootNode.addEventListener('scroll', handleScroll) return () => rootNode.removeEventListener('scroll', handleScroll) }) return ( <div css={styles.root} ref={rootEl}> <h1>Messages for {channel.name}</h1> <ul> { messages.map( (message, i) => { const {contents: content} = unified() .use(markdown) .use(remark2rehype) .use(html) .processSync(message.content) return ( <li key={i} css={styles.message}> <p> <span>{message.author}</span> {' - '} <span>{dayjs().calendar(message.creation)}</span> </p> <div dangerouslySetInnerHTML={{__html: content}}> </div> </li> ) })} </ul> <div ref={scrollEl} /> </div> ) }) <file_sep>import {useState} from 'react' /** @jsx jsx */ import { jsx } from '@emotion/core' // Layout import { useTheme } from '@material-ui/core/styles'; import useMediaQuery from '@material-ui/core/useMediaQuery'; import Drawer from '@material-ui/core/Drawer'; // Local import Channels from './Channels' import Channel from './Channel' import Welcome from './Welcome' const useStyles = (theme) => ({ main: { backgroundColor: '#373B44', overflow: 'hidden', flex: '1 1 auto', display: 'flex', flexDirection: 'row', position: 'relative', }, drawer: { width: '200px', display: 'none', }, drawerVisible: { display: 'block', }, }) export default ({ drawerMobileVisible, }) => { const [channel, setChannel] = useState(null) const fetchChannel = async (channel) => { setChannel(channel) } const theme = useTheme() const styles = useStyles(theme) const alwaysOpen = useMediaQuery(theme.breakpoints.up('sm')) const isDrawerVisible = alwaysOpen || drawerMobileVisible return ( <main css={styles.main}> <Drawer PaperProps={{ style: { position: 'relative' } }} BackdropProps={{ style: { position: 'relative' } }} ModalProps={{ style: { position: 'relative' } }} variant="persistent" open={isDrawerVisible} css={[styles.drawer, isDrawerVisible && styles.drawerVisible]} > <Channels onChannel={fetchChannel} /> </Drawer> {channel ? <Channel channel={channel} messages={[]} /> : <Welcome />} </main> ); } <file_sep>import './App.css'; /** @jsx jsx */ import { jsx } from '@emotion/core' // Layout import { useTheme } from '@material-ui/core/styles'; import IconButton from '@material-ui/core/IconButton'; import MenuIcon from '@material-ui/icons/Menu'; const useStyles = (theme) => ({ header: { padding: theme.spacing(1), backgroundColor: 'rgba(255,255,255,.3)', flexShrink: 0, }, headerLogIn: { backgroundColor: 'red', }, headerLogOut: { backgroundColor: 'blue', }, menu: { [theme.breakpoints.up('sm')]: { display: 'none !important', }, } }) export default ({ drawerToggleListener }) => { const styles = useStyles(useTheme()) const handleDrawerToggle = (e) => { drawerToggleListener() } return ( <header css={styles.header}> <IconButton color="inherit" aria-label="open drawer" onClick={handleDrawerToggle} css={styles.menu} > <MenuIcon /> </IconButton> Header </header> ); } <file_sep>import {useState, useEffect} from 'react'; import axios from 'axios'; /** @jsx jsx */ import { jsx } from '@emotion/core' // Layout import Link from '@material-ui/core/Link' const styles = { // root: { // minWidth: '200px', // }, channel: { padding: '.2rem .5rem', whiteSpace: 'nowrap', } } export default ({ onChannel }) => { const [channels, setChannels] = useState([]) useEffect( () => { const fetch = async () => { const {data: channels} = await axios.get('http://localhost:3001/channels') setChannels(channels) } fetch() }, []) return ( <ul style={styles.root}> { channels.map( (channel, i) => ( <li key={i} css={styles.channel}> <Link href="#" onClick={ (e) => { e.preventDefault() onChannel(channel) }} > {channel.name} </Link> </li> ))} </ul> ); }
205ae82f5a39a1149b9fd051508dd96510171676
[ "JavaScript" ]
7
JavaScript
chahinaz-rdn/ece-2020-fall-webtech
6c4c42be6c3f9b0b08349e74ca50ed86eefc75e5
165e97cff90804452cd064eb7383989eef3e31d8
refs/heads/master
<repo_name>jakebfree/codemash2015<file_sep>/src/com/sample/codemash/StringCalcTest.java package com.sample.codemash; import org.junit.Test; import static org.junit.Assert.*; public class StringCalcTest { @Test public void testEmptyStringReturnsZero() throws Exception { assertEquals(0, StringCalc.add("")); } @Test public void testReturnsSingleValue() throws Exception { assertEquals(1, StringCalc.add("1")); assertEquals(2, StringCalc.add("2")); assertEquals(42, StringCalc.add("42")); } @Test public void testTwoValuesWithCommas() throws Exception { assertEquals(2, StringCalc.add("1,1")); assertEquals(3, StringCalc.add("1,2")); assertEquals(1, StringCalc.add("1,")); assertEquals(12, StringCalc.add("10,2")); } @Test public void testMultipleValuesWithCommas() throws Exception { assertEquals(3, StringCalc.add("1,1,1")); assertEquals(6, StringCalc.add("1,2,3")); assertEquals(4, StringCalc.add("4,,")); assertEquals(36, StringCalc.add("34,2")); } @Test public void testTwoValuesWithNewlines() throws Exception { assertEquals(2, StringCalc.add("1\n1")); assertEquals(3, StringCalc.add("1\n2")); assertEquals(1, StringCalc.add("1\n")); assertEquals(12, StringCalc.add("10\n2")); } @Test public void testMultipleValuesWithNewlines() throws Exception { assertEquals(3, StringCalc.add("1\n1\n1")); assertEquals(6, StringCalc.add("1\n2\n3")); assertEquals(4, StringCalc.add("4\n\n")); assertEquals(36, StringCalc.add("34\n2")); } }<file_sep>/src/com/sample/codemash/FizzBuzzer.java package com.sample.codemash; public class FizzBuzzer { //private static final String DIVISIBLE_BY_THREE_RESPONSE = "Fizz"; //private static final String DIVISIBLE_BY_FIVE_RESPONSE = "Buzz"; //private static final String DIVISIBLE_BY_THREE_AND_FIVE_RESPONSE = "FizzBuzz"; // //private Map(<int>, <String>) divisorToResponse = ; // //public FizzBuzzer( Map(<int>,<String>) ){ //} public static String fizzBuzz( Integer num ){ String response = ""; if( num % 3 == 0 ) response = response.concat("Fizz"); if( num % 5 == 0 ) response = response.concat("Buzz"); if( response.equals("")) response = response.concat( num.toString() ); return response; } } <file_sep>/GreedKata/src/com/sample/codemash/TripleOnesRule.java package com.sample.codemash; import java.util.Collections; import java.util.List; public class TripleOnesRule implements IScoringRule { @Override public int score(List<Integer> rolls) { boolean threeOnes = true; for (int i = 0; i < 3; i++) { if (rolls.get(i) != 1) { threeOnes = false; } } int x = Collections.frequency(rolls, 1); if (threeOnes) { for (int i = 0; i < 3; i++) { rolls.remove(0); } return 1000; } else return 0; } } <file_sep>/src/com/sample/codemash/ReceiptPrinter.java package com.sample.codemash; /** * Created by jake on 1/7/15. */ public class ReceiptPrinter { public printReceipt( Order order ){ } } <file_sep>/src/com/sample/codemash/HappyHourTest.java package com.sample.codemash; public class HappyHourTest { }
5f2a45254afcb2e1c0cadb3858135be71cbd7959
[ "Java" ]
5
Java
jakebfree/codemash2015
6e29f3834c30e4d863135dc9fda37573e6bfd906
9a6fc50a600ba2ca7fd68fed5345e8a590660bd7
refs/heads/master
<repo_name>Mahdi399399/djangowithblur<file_sep>/apipro/apiaap/apps.py from django.apps import AppConfig class ApiaapConfig(AppConfig): name = 'apiaap' <file_sep>/apipro/apiaap/views.py from django.shortcuts import render # Create your views here. from . import views from rest_framework import routers from django.urls import path, include router=routers.DefaultRouter() router.register('awsimage',views.awsimageview) urlpatterns=[ path('',include(router.urls)) ] <file_sep>/apipro/apiaap/serializers.py from rest_framework import serializers from .models import awsimage class awsimagesserializer(serializers.HyperlinkedModelSerializer): class Meta: model=awsimage fields=('title','images') '''def validate(self, images): """ Check that start is before finish. """ fm > 100: if images= raise serializers.ValidationError("finish must occur after start") return data'''<file_sep>/apipro/apiaap/models.py import cv2 from django.db import models from apipro import laplacian # Create your models here. class awsimage(models.Model): title=models.CharField(max_length=50) images=models.ImageField('images/') def valid(self): if laplacian.variance_of_laplacian(self.images,100)<100: Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) <file_sep>/apipro/apiaap/admin.py from django.contrib import admin # Register your models here. from .models import awsimage admin.site.register(awsimage)
3e8b781d8a0c3d88836cff4e0661a88b4f7c0e58
[ "Python" ]
5
Python
Mahdi399399/djangowithblur
15c4596bbb856546d9db3290b507ad412fcd052b
8baf551d00c827596a2dc1e4aee37ddd393a0c6a
refs/heads/master
<file_sep>package edu.polytech.busyholiday3; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.view.View; import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; import java.util.Objects; public class members extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_members); } @Override protected void onStart() { super.onStart(); } } <file_sep>package edu.polytech.busyholiday3; import android.content.Intent; import android.graphics.Color; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.text.InputType; import android.text.method.PasswordTransformationMethod; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import com.bumptech.glide.Glide; import com.bumptech.glide.load.engine.DiskCacheStrategy; import com.bumptech.glide.request.RequestOptions; import com.bumptech.glide.request.target.SimpleTarget; import com.bumptech.glide.request.transition.Transition; public class MainActivity extends AppCompatActivity { EditText idEdit, passEdit; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ImageView MAImageView1 = (ImageView)findViewById(R.id.MAImageView1); Glide.with(this).load(R.drawable.rabbit).into(MAImageView1); idEdit = (EditText) findViewById(R.id.CTWEditText1); passEdit = (EditText) findViewById(R.id.CTWEditText2); Button CTWButton1 = (Button) findViewById(R.id.CTWButton1); CTWButton1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String idStr, passStr; idStr = idEdit.getText().toString(); passStr = passEdit.getText().toString(); Intent intent1 = new Intent(getApplicationContext(), members.class); // intent.putExtra("inputID", idStr); // intent.putExtra("inputPassword", passStr);//세컨드로 던짐(세컨드에선 받아야함) final String resultText; if(idStr.equals("abc") && passStr.equals("<PASSWORD>")) { resultText = "로그인이 성공하였습니다."; } else { resultText = "ID/PW 틀린것 같네요."; } Toast.makeText(MainActivity.this, resultText,Toast.LENGTH_LONG).show(); if (resultText.equals("로그인이 성공하였습니다.")) { startActivityForResult(intent1, 1000); } } }); Button CTWButton2 = (Button) findViewById(R.id.CTWButton2); CTWButton2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent2 = new Intent(getApplicationContext(), nomembers.class); startActivity(intent2); } }); TextView CTWTextView2 = (TextView) findViewById(R.id.CTWTextView2); CTWTextView2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent3 = new Intent(getApplicationContext(), Signup.class); startActivity(intent3); } }); TextView CTWTextView4 = (TextView) findViewById(R.id.CTWTextView4); CTWTextView4.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent4 = new Intent(getApplicationContext(), FindPW.class); startActivity(intent4); } }); } // @Override // protected void onActivityResult(int requestCode, int resultCode, Intent data) { // if(resultCode == RESULT_OK) { // if(requestCode == 1000) { // // TextView errText = (TextView)findViewById(R.id.errorText); // errText.setText(data.getStringExtra("errText")); // } // } // } }
9bf561f4afd70c533d15b57b760e841abfa2a9dd
[ "Java" ]
2
Java
Kwonjoon5914/KOPO01FirstRepository2
4cdcfadb593c87b9cd79eb13089bfeb3fc04d3e0
bcef22c835ec6871c57e548cef8fb52b051d7e14
refs/heads/master
<file_sep>/* / _____) _ | | ( (____ _____ ____ _| |_ _____ ____| |__ \____ \| ___ | (_ _) ___ |/ ___) _ \ _____) ) ____| | | || |_| ____( (___| | | | (______/|_____)_|_|_| \__)_____)\____)_| |_| (C)2013 Semtech Description: Bleeper board SPI driver implementation License: Revised BSD License, see LICENSE.TXT file include in the project Maintainer: <NAME> and <NAME> */ /******************************************************************************* * @file hw_spi.c * @author MCD Application Team * @version V1.1.0 * @date 27-February-2017 * @brief manages the SPI interface ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2017 STMicroelectronics International N.V. * All rights reserved.</center></h2> * * Redistribution and use in source and binary forms, with or without * modification, are permitted, provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of STMicroelectronics nor the names of other * contributors to this software may be used to endorse or promote products * derived from this software without specific written permission. * 4. This software, including modifications and/or derivative works of this * software, must execute solely and exclusively on microcontroller or * microprocessor devices manufactured by or for STMicroelectronics. * 5. Redistribution and use of this software other than as permitted under * this license is void and will automatically terminate your rights under * this license. * * THIS SOFTWARE IS PROVIDED BY STMICROELECTRONICS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS, IMPLIED OR STATUTORY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE AND NON-INFRINGEMENT OF THIRD PARTY INTELLECTUAL PROPERTY * RIGHTS ARE DISCLAIMED TO THE FULLEST EXTENT PERMITTED BY LAW. IN NO EVENT * SHALL STMICROELECTRONICS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "hw.h" #include "utilities.h" /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ static SPI_HandleTypeDef hspi; /* Private function prototypes -----------------------------------------------*/ /*! * @brief Calculates Spi Divisor based on Spi Frequency and Mcu Frequency * * @param [IN] Spi Frequency * @retval Spi divisor */ static uint32_t SpiFrequency( uint32_t hz ); /* Exported functions ---------------------------------------------------------*/ /*! * @brief Initializes the SPI object and MCU peripheral * * @param [IN] none */ void HW_SPI_Init( void ) { GPIO_InitTypeDef initStruct={0}; /*##-1- Configure the SPI peripheral */ /* Set the SPI parameters */ hspi.Instance = SPI1; hspi.Init.BaudRatePrescaler = SpiFrequency( 10000000 ); hspi.Init.Direction = SPI_DIRECTION_2LINES; hspi.Init.Mode = SPI_MODE_MASTER; hspi.Init.CLKPolarity = SPI_POLARITY_LOW; hspi.Init.CLKPhase = SPI_PHASE_1EDGE; hspi.Init.DataSize = SPI_DATASIZE_8BIT; hspi.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE; hspi.Init.CRCPolynomial = 1; hspi.Init.FirstBit = SPI_FIRSTBIT_MSB; hspi.Init.NSS = SPI_NSS_SOFT; hspi.Init.TIMode = SPI_TIMODE_DISABLE; SPI_CLK_ENABLE(); if(HAL_SPI_Init( &hspi) != HAL_OK) { /* Initialization Error */ Error_Handler(); } /*##-2- Configure the SPI GPIOs */ initStruct.Mode =GPIO_MODE_AF_PP; initStruct.Pull = GPIO_PULLDOWN; initStruct.Speed = GPIO_SPEED_HIGH; initStruct.Alternate= SPI1_AF ; HW_GPIO_Init( RADIO_SCLK_PORT, RADIO_SCLK_PIN, &initStruct); HW_GPIO_Init( RADIO_MISO_PORT, RADIO_MISO_PIN, &initStruct); HW_GPIO_Init( RADIO_MOSI_PORT, RADIO_MOSI_PIN, &initStruct); initStruct.Mode =GPIO_MODE_OUTPUT_PP; initStruct.Pull = GPIO_PULLUP; HW_GPIO_Init( RADIO_NSS_PORT, RADIO_NSS_PIN, &initStruct ); HW_GPIO_Write ( RADIO_NSS_PORT, RADIO_NSS_PIN, 1 ); } /*! * @brief De-initializes the SPI object and MCU peripheral * * @param [IN] none */ void HW_SPI_DeInit( void ) { GPIO_InitTypeDef initStruct={0}; HAL_SPI_DeInit( &hspi); /*##-1- Reset peripherals ####*/ __HAL_RCC_SPI1_FORCE_RESET(); __HAL_RCC_SPI1_RELEASE_RESET(); initStruct.Mode =GPIO_MODE_OUTPUT_PP; initStruct.Pull =GPIO_NOPULL ; HW_GPIO_Init ( RADIO_MOSI_PORT, RADIO_MOSI_PIN, &initStruct ); HW_GPIO_Write( RADIO_MOSI_PORT, RADIO_MOSI_PIN, 0 ); initStruct.Pull =GPIO_PULLDOWN; HW_GPIO_Init ( RADIO_MISO_PORT, RADIO_MISO_PIN, &initStruct ); HW_GPIO_Write( RADIO_MISO_PORT, RADIO_MISO_PIN, 0 ); initStruct.Pull =GPIO_NOPULL ; HW_GPIO_Init ( RADIO_SCLK_PORT, RADIO_SCLK_PIN, &initStruct ); HW_GPIO_Write( RADIO_SCLK_PORT, RADIO_SCLK_PIN, 0 ); initStruct.Pull =GPIO_PULLUP ; HW_GPIO_Init ( RADIO_NSS_PORT, RADIO_NSS_PIN , &initStruct ); HW_GPIO_Write( RADIO_NSS_PORT, RADIO_NSS_PIN , 1 ); } /*! * @brief Sends outData and receives inData * * @param [IN] outData Byte to be sent * @retval inData Received byte. */ uint16_t HW_SPI_InOut( uint16_t txData ) { uint16_t rxData ; HAL_SPI_TransmitReceive( &hspi, ( uint8_t * ) &txData, ( uint8_t* ) &rxData, 1, HAL_MAX_DELAY); return rxData; } /* Private functions ---------------------------------------------------------*/ static uint32_t SpiFrequency( uint32_t hz ) { uint32_t divisor = 0; uint32_t SysClkTmp = SystemCoreClock; uint32_t baudRate; while( SysClkTmp > hz) { divisor++; SysClkTmp= ( SysClkTmp >> 1); if (divisor >= 7) break; } baudRate =((( divisor & 0x4 ) == 0 )? 0x0 : SPI_CR1_BR_2 )| ((( divisor & 0x2 ) == 0 )? 0x0 : SPI_CR1_BR_1 )| ((( divisor & 0x1 ) == 0 )? 0x0 : SPI_CR1_BR_0 ); return baudRate; } /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ <file_sep>/* / _____) _ | | ( (____ _____ ____ _| |_ _____ ____| |__ \____ \| ___ | (_ _) ___ |/ ___) _ \ _____) ) ____| | | || |_| ____( (___| | | | (______/|_____)_|_|_| \__)_____)\____)_| |_| (C)2013 Semtech Description: Target board general functions implementation License: Revised BSD License, see LICENSE.TXT file include in the project Maintainer: <NAME> and <NAME> */ /******************************************************************************* * @file stm32l0xx_hw.c * @author MCD Application Team * @version V1.1.0 * @date 27-February-2017 * @brief system hardware driver ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2017 STMicroelectronics International N.V. * All rights reserved.</center></h2> * * Redistribution and use in source and binary forms, with or without * modification, are permitted, provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of STMicroelectronics nor the names of other * contributors to this software may be used to endorse or promote products * derived from this software without specific written permission. * 4. This software, including modifications and/or derivative works of this * software, must execute solely and exclusively on microcontroller or * microprocessor devices manufactured by or for STMicroelectronics. * 5. Redistribution and use of this software other than as permitted under * this license is void and will automatically terminate your rights under * this license. * * THIS SOFTWARE IS PROVIDED BY STMICROELECTRONICS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS, IMPLIED OR STATUTORY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE AND NON-INFRINGEMENT OF THIRD PARTY INTELLECTUAL PROPERTY * RIGHTS ARE DISCLAIMED TO THE FULLEST EXTENT PERMITTED BY LAW. IN NO EVENT * SHALL STMICROELECTRONICS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************** */ #include "hw.h" #include "radio.h" #include "debug.h" #include "vcom.h" /*! * \brief Unique Devices IDs register set ( STM32L0xxx ) */ #define ID1 ( 0x1FF80050 ) #define ID2 ( 0x1FF80054 ) #define ID3 ( 0x1FF80064 ) /*! * \brief ADC Vbat measurement constants */ /* Internal voltage reference, parameter VREFINT_CAL*/ #define VREFINT_CAL ((uint16_t*) ((uint32_t) 0x1FF80078)) #define LORAWAN_MAX_BAT 254 static ADC_HandleTypeDef hadc; /*! * Flag to indicate if the ADC is Initialized */ static bool AdcInitialized = false; /*! * Flag to indicate if the MCU is Initialized */ static bool McuInitialized = false; /** * @brief This function initializes the hardware * @param None * @retval None */ void HW_Init( void ) { if( McuInitialized == false ) { #if defined( USE_BOOTLOADER ) /* Set the Vector Table base location at 0x3000 */ NVIC_SetVectorTable( NVIC_VectTab_FLASH, 0x3000 ); #endif HW_AdcInit( ); Radio.IoInit( ); HW_SPI_Init( ); HW_RTC_Init( ); vcom_Init( ); McuInitialized = true; } } /** * @brief This function Deinitializes the hardware * @param None * @retval None */ void HW_DeInit( void ) { HW_SPI_DeInit( ); Radio.IoDeInit( ); vcom_DeInit( ); McuInitialized = false; } /** * @brief System Clock Configuration * The system Clock is configured as follow : * System Clock source = PLL (HSI) * SYSCLK(Hz) = 32000000 * HCLK(Hz) = 32000000 * AHB Prescaler = 1 * APB1 Prescaler = 1 * APB2 Prescaler = 1 * HSI Frequency(Hz) = 16000000 * PLLMUL = 6 * PLLDIV = 3 * Flash Latency(WS) = 1 * @retval None */ void SystemClock_Config( void ) { RCC_ClkInitTypeDef RCC_ClkInitStruct = {0}; RCC_OscInitTypeDef RCC_OscInitStruct = {0}; /* Enable HSE Oscillator and Activate PLL with HSE as source */ RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI; RCC_OscInitStruct.HSEState = RCC_HSE_OFF; RCC_OscInitStruct.HSIState = RCC_HSI_ON; RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI; RCC_OscInitStruct.PLL.PLLMUL = RCC_PLLMUL_6; RCC_OscInitStruct.PLL.PLLDIV = RCC_PLLDIV_3; if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) { Error_Handler(); } /* Set Voltage scale1 as MCU will run at 32MHz */ __HAL_RCC_PWR_CLK_ENABLE(); __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1); /* Poll VOSF bit of in PWR_CSR. Wait until it is reset to 0 */ while (__HAL_PWR_GET_FLAG(PWR_FLAG_VOS) != RESET) {}; /* Select PLL as system clock source and configure the HCLK, PCLK1 and PCLK2 clocks dividers */ RCC_ClkInitStruct.ClockType = (RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2); RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1; RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1; if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_1) != HAL_OK) { Error_Handler(); } } /** * @brief This function return a random seed * @note based on the device unique ID * @param None * @retval see */ uint32_t HW_GetRandomSeed( void ) { return ( ( *( uint32_t* )ID1 ) ^ ( *( uint32_t* )ID2 ) ^ ( *( uint32_t* )ID3 ) ); } /** * @brief This function return a unique ID * @param unique ID * @retval none */ void HW_GetUniqueId( uint8_t *id ) { id[7] = ( ( *( uint32_t* )ID1 )+ ( *( uint32_t* )ID3 ) ) >> 24; id[6] = ( ( *( uint32_t* )ID1 )+ ( *( uint32_t* )ID3 ) ) >> 16; id[5] = ( ( *( uint32_t* )ID1 )+ ( *( uint32_t* )ID3 ) ) >> 8; id[4] = ( ( *( uint32_t* )ID1 )+ ( *( uint32_t* )ID3 ) ); id[3] = ( ( *( uint32_t* )ID2 ) ) >> 24; id[2] = ( ( *( uint32_t* )ID2 ) ) >> 16; id[1] = ( ( *( uint32_t* )ID2 ) ) >> 8; id[0] = ( ( *( uint32_t* )ID2 ) ); } /** * @brief This function return the battery level * @param none * @retval the battery level 1 (very low) to 254 (fully charged) */ uint8_t HW_GetBatteryLevel( void ) { uint8_t batteryLevel = 0; uint16_t measuredLevel = 0; uint32_t batteryLevelmV; measuredLevel = HW_AdcReadChannel( ADC_CHANNEL_VREFINT ); if (measuredLevel == 0) { batteryLevelmV = 0; } else { batteryLevelmV= (( (uint32_t) VDDA_TEMP_CAL * (*VREFINT_CAL ) )/ measuredLevel); } if (batteryLevelmV > VDD_BAT) { batteryLevel = LORAWAN_MAX_BAT; } else if (batteryLevelmV < VDD_MIN) { batteryLevel = 0; } else { batteryLevel = (( (uint32_t) (batteryLevelmV - VDD_MIN)*LORAWAN_MAX_BAT) /(VDD_BAT-VDD_MIN) ); } return batteryLevel; } /** * @brief This function initializes the ADC * @param none * @retval none */ void HW_AdcInit( void ) { if( AdcInitialized == false ) { AdcInitialized = true; GPIO_InitTypeDef initStruct; hadc.Instance = ADC1; hadc.Init.OversamplingMode = DISABLE; hadc.Init.ClockPrescaler = ADC_CLOCK_SYNC_PCLK_DIV1; hadc.Init.LowPowerAutoPowerOff = DISABLE; hadc.Init.LowPowerFrequencyMode = ENABLE; hadc.Init.LowPowerAutoWait = DISABLE; hadc.Init.Resolution = ADC_RESOLUTION_12B; hadc.Init.SamplingTime = ADC_SAMPLETIME_7CYCLES_5; hadc.Init.ScanConvMode = ADC_SCAN_DIRECTION_FORWARD; hadc.Init.DataAlign = ADC_DATAALIGN_RIGHT; hadc.Init.ContinuousConvMode = DISABLE; hadc.Init.DiscontinuousConvMode = DISABLE; hadc.Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_NONE; hadc.Init.EOCSelection = ADC_EOC_SINGLE_CONV; hadc.Init.DMAContinuousRequests = DISABLE; ADCCLK_ENABLE(); HAL_ADC_Init( &hadc ); initStruct.Mode =GPIO_MODE_ANALOG; initStruct.Pull = GPIO_NOPULL; initStruct.Speed = GPIO_SPEED_HIGH; HW_GPIO_Init( BAT_LEVEL_PORT, BAT_LEVEL_PIN, &initStruct ); } } /** * @brief This function De-initializes the ADC * @param none * @retval none */ void HW_AdcDeInit( void ) { AdcInitialized = false; } /** * @brief This function De-initializes the ADC * @param Channel * @retval Value */ uint16_t HW_AdcReadChannel( uint32_t Channel ) { ADC_ChannelConfTypeDef adcConf; uint16_t adcData = 0; if( AdcInitialized == true ) { /* wait the the Vrefint used by adc is set */ while (__HAL_PWR_GET_FLAG(PWR_FLAG_VREFINTRDY) == RESET) {}; ADCCLK_ENABLE(); /*calibrate ADC if any calibraiton hardware*/ HAL_ADCEx_Calibration_Start(&hadc, ADC_SINGLE_ENDED ); /* Deselects all channels*/ adcConf.Channel = ADC_CHANNEL_MASK; adcConf.Rank = ADC_RANK_NONE; HAL_ADC_ConfigChannel( &hadc, &adcConf); /* configure adc channel */ adcConf.Channel = Channel; adcConf.Rank = ADC_RANK_CHANNEL_NUMBER; HAL_ADC_ConfigChannel( &hadc, &adcConf); /* Start the conversion process */ HAL_ADC_Start( &hadc); /* Wait for the end of conversion */ HAL_ADC_PollForConversion( &hadc, HAL_MAX_DELAY ); /* Get the converted value of regular channel */ adcData = HAL_ADC_GetValue ( &hadc); __HAL_ADC_DISABLE( &hadc) ; ADCCLK_DISABLE(); } return adcData; } /** * @brief Enters Low Power Stop Mode * @note ARM exists the function when waking up * @param none * @retval none */ void HW_EnterStopMode( void) { BACKUP_PRIMASK(); DISABLE_IRQ( ); HW_DeInit( ); /*clear wake up flag*/ SET_BIT(PWR->CR, PWR_CR_CWUF); RESTORE_PRIMASK( ); /* Enter Stop Mode */ HAL_PWR_EnterSTOPMode ( PWR_LOWPOWERREGULATOR_ON, PWR_STOPENTRY_WFI ); } /** * @brief Exists Low Power Stop Mode * @note Enable the pll at 32MHz * @param none * @retval none */ void HW_ExitStopMode( void) { /* Disable IRQ while the MCU is not running on HSI */ BACKUP_PRIMASK(); DISABLE_IRQ( ); /* After wake-up from STOP reconfigure the system clock */ /* Enable HSI */ __HAL_RCC_HSI_ENABLE(); /* Wait till HSI is ready */ while( __HAL_RCC_GET_FLAG(RCC_FLAG_HSIRDY) == RESET ) {} /* Enable PLL */ __HAL_RCC_PLL_ENABLE(); /* Wait till PLL is ready */ while( __HAL_RCC_GET_FLAG( RCC_FLAG_PLLRDY ) == RESET ) {} /* Select PLL as system clock source */ __HAL_RCC_SYSCLK_CONFIG ( RCC_SYSCLKSOURCE_PLLCLK ); /* Wait till PLL is used as system clock source */ while( __HAL_RCC_GET_SYSCLK_SOURCE( ) != RCC_SYSCLKSOURCE_STATUS_PLLCLK ) {} /*initilizes the peripherals*/ HW_Init( ); RESTORE_PRIMASK( ); } /** * @brief Enters Low Power Sleep Mode * @note ARM exits the function when waking up * @param none * @retval none */ void HW_EnterSleepMode( void) { HAL_PWR_EnterSLEEPMode(PWR_MAINREGULATOR_ON, PWR_SLEEPENTRY_WFI); } /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ <file_sep>/* * This file is part of the µOS++ distribution. * (https://github.com/micro-os-plus) * Copyright (c) 2014 <NAME>. * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom * the Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ // ---------------------------------------------------------------------------- #include "cortexm/ExceptionHandlers.h" // ---------------------------------------------------------------------------- void __attribute__((weak)) Default_Handler(void); // Forward declaration of the specific IRQ handlers. These are aliased // to the Default_Handler, which is a 'forever' loop. When the application // defines a handler (with the same name), this will automatically take // precedence over these weak definitions void __attribute__ ((weak, alias ("Default_Handler"))) WWDG_IRQHandler(void); void __attribute__ ((weak, alias ("Default_Handler"))) PVD_IRQHandler(void); void __attribute__ ((weak, alias ("Default_Handler"))) RTC_IRQHandler(void); void __attribute__ ((weak, alias ("Default_Handler"))) FLASH_IRQHandler(void); void __attribute__ ((weak, alias ("Default_Handler"))) EXTI0_1_IRQHandler(void); void __attribute__ ((weak, alias ("Default_Handler"))) EXTI2_3_IRQHandler(void); void __attribute__ ((weak, alias ("Default_Handler"))) EXTI4_15_IRQHandler(void); void __attribute__ ((weak, alias ("Default_Handler"))) DMA1_Channel1_IRQHandler(void); void __attribute__ ((weak, alias ("Default_Handler"))) DMA1_Channel2_3_IRQHandler(void); void __attribute__ ((weak, alias ("Default_Handler"))) LPTIM1_IRQHandler(void); void __attribute__ ((weak, alias ("Default_Handler"))) TIM2_IRQHandler(void); void __attribute__ ((weak, alias ("Default_Handler"))) TIM3_IRQHandler(void); void __attribute__ ((weak, alias ("Default_Handler"))) TIM6_DAC_IRQHandler(void); void __attribute__ ((weak, alias ("Default_Handler"))) I2C1_IRQHandler(void); void __attribute__ ((weak, alias ("Default_Handler"))) I2C2_IRQHandler(void); void __attribute__ ((weak, alias ("Default_Handler"))) I2C3_IRQHandler(void); void __attribute__ ((weak, alias ("Default_Handler"))) TIM22_IRQHandler(void); void __attribute__ ((weak, alias ("Default_Handler"))) SPI1_IRQHandler(void); void __attribute__ ((weak, alias ("Default_Handler"))) SPI2_IRQHandler(void); void __attribute__ ((weak, alias ("Default_Handler"))) USART1_IRQHandler(void); void __attribute__ ((weak, alias ("Default_Handler"))) USART2_IRQHandler(void); void __attribute__ ((weak, alias ("Default_Handler"))) ADC1_COMP_IRQHandler(void); void __attribute__ ((weak, alias ("Default_Handler"))) RCC_CRS_IRQHandler(void); void __attribute__ ((weak, alias ("Default_Handler"))) TSC_IRQHandler(void); void __attribute__ ((weak, alias ("Default_Handler"))) TIM7_IRQHandler(void); void __attribute__ ((weak, alias ("Default_Handler"))) TIM21_IRQHandler(void); void __attribute__ ((weak, alias ("Default_Handler"))) USART4_5_IRQHandler(void); void __attribute__ ((weak, alias ("Default_Handler"))) RNG_LPUART1_IRQHandler(void); void __attribute__ ((weak, alias ("Default_Handler"))) LCD_IRQHandler(void); void __attribute__ ((weak, alias ("Default_Handler"))) USB_IRQHandler(void); void __attribute__ ((weak, alias ("Default_Handler"))) DMA1_Channel4_5_6_7_IRQHandler(void); // ---------------------------------------------------------------------------- extern unsigned int _estack; typedef void (* const pHandler)(void); // ---------------------------------------------------------------------------- // The vector table. // This relies on the linker script to place at correct location in memory. __attribute__ ((section(".isr_vector"),used)) pHandler g_pfnVectors[] = { // Core Level - CM0 (pHandler) &_estack, // The initial stack pointer Reset_Handler, // The reset handler NMI_Handler, // The NMI handler HardFault_Handler, // The hard fault handler #if defined(__ARM_ARCH_7M__) || defined(__ARM_ARCH_7EM__) MemManage_Handler, // The MPU fault handler BusFault_Handler, // The bus fault handler UsageFault_Handler, // The usage fault handler #else 0, 0, 0, // Reserved #endif 0, // Reserved 0, // Reserved 0, // Reserved 0, // Reserved SVC_Handler, // SVCall handler #if defined(__ARM_ARCH_7M__) || defined(__ARM_ARCH_7EM__) DebugMon_Handler, // Debug monitor handler #else 0, // Reserved #endif 0, // Reserved PendSV_Handler, // The PendSV handler SysTick_Handler, // The SysTick handler // ---------------------------------------------------------------------- #if defined(STM32F030) // Chip Level - STM32F030 WWDG_IRQHandler, // 0, // RTC_IRQHandler, // FLASH_IRQHandler, // RCC_IRQHandler, // EXTI0_1_IRQHandler, // EXTI2_3_IRQHandler, // EXTI4_15_IRQHandler, // 0, // DMA1_Channel1_IRQHandler, // DMA1_Channel2_3_IRQHandler, // DMA1_Channel4_5_IRQHandler, // ADC1_IRQHandler, // TIM1_BRK_UP_TRG_COM_IRQHandler, // TIM1_CC_IRQHandler, // 0, // TIM3_IRQHandler, // 0, // 0, // TIM14_IRQHandler, // TIM15_IRQHandler, // TIM16_IRQHandler, // TIM17_IRQHandler, // I2C1_IRQHandler, // I2C2_IRQHandler, // SPI1_IRQHandler, // SPI2_IRQHandler, // USART1_IRQHandler, // USART2_IRQHandler, // 0, // 0, // 0, // #elif defined(STM32F030xC) // Chip Level - STM32F030 WWDG_IRQHandler, // 0, // RTC_IRQHandler, // FLASH_IRQHandler, // RCC_IRQHandler, // EXTI0_1_IRQHandler, // EXTI2_3_IRQHandler, // EXTI4_15_IRQHandler, // 0, // DMA1_Channel1_IRQHandler, // DMA1_Channel2_3_IRQHandler, // DMA1_Channel4_5_IRQHandler, // ADC1_IRQHandler, // TIM1_BRK_UP_TRG_COM_IRQHandler, // TIM1_CC_IRQHandler, // 0, // TIM3_IRQHandler, // TIM6_IRQHandler, // TIM7_IRQHandler, // TIM14_IRQHandler, // TIM15_IRQHandler, // TIM16_IRQHandler, // TIM17_IRQHandler, // I2C1_IRQHandler, // I2C2_IRQHandler, // SPI1_IRQHandler, // SPI2_IRQHandler, // USART1_IRQHandler, // USART2_IRQHandler, // USART3_6_IRQHandler, // 0, // 0, // #elif defined(STM32F031) // Chip Level - STM32F031 (was STM32F0xx LD) WWDG_IRQHandler, // PVD_IRQHandler, // RTC_IRQHandler, // FLASH_IRQHandler, // RCC_IRQHandler, // EXTI0_1_IRQHandler, // EXTI2_3_IRQHandler, // EXTI4_15_IRQHandler, // 0, // DMA1_Channel1_IRQHandler, // DMA1_Channel2_3_IRQHandler, // DMA1_Channel4_5_IRQHandler, // ADC1_IRQHandler, // TIM1_BRK_UP_TRG_COM_IRQHandler, // TIM1_CC_IRQHandler, // TIM2_IRQHandler, // TIM3_IRQHandler, // 0, // 0, // TIM14_IRQHandler, // 0, // TIM16_IRQHandler, // TIM17_IRQHandler, // I2C1_IRQHandler, // 0, // SPI1_IRQHandler, // 0, // USART1_IRQHandler, // 0, // 0, // 0, // 0, // #elif defined(STM32F042) // Chip Level - STM32F042 (was STM32F0xx MD) WWDG_IRQHandler, // PVD_VDDIO2_IRQHandler, // RTC_IRQHandler, // FLASH_IRQHandler, // RCC_CRS_IRQHandler, // EXTI0_1_IRQHandler, // EXTI2_3_IRQHandler, // EXTI4_15_IRQHandler, // TSC_IRQHandler, // DMA1_Channel1_IRQHandler, // DMA1_Channel2_3_IRQHandler, // DMA1_Channel4_5_IRQHandler, // ADC1_IRQHandler, // TIM1_BRK_UP_TRG_COM_IRQHandler, // TIM1_CC_IRQHandler, // TIM2_IRQHandler, // TIM3_IRQHandler, // 0, // 0, // TIM14_IRQHandler, // 0, // TIM16_IRQHandler, // TIM17_IRQHandler, // I2C1_IRQHandler, // 0, // SPI1_IRQHandler, // SPI2_IRQHandler, // USART1_IRQHandler, // USART2_IRQHandler, // 0, // CEC_CAN_IRQHandler, // USB_IRQHandler, // #elif defined(STM32F051) // Chip Level - STM32F051 (was STM32F0xx MD) WWDG_IRQHandler, // PVD_IRQHandler, // RTC_IRQHandler, // FLASH_IRQHandler, // RCC_IRQHandler, // EXTI0_1_IRQHandler, // EXTI2_3_IRQHandler, // EXTI4_15_IRQHandler, // TS_IRQHandler, // DMA1_Channel1_IRQHandler, // DMA1_Channel2_3_IRQHandler, // DMA1_Channel4_5_IRQHandler, // ADC1_COMP_IRQHandler, // TIM1_BRK_UP_TRG_COM_IRQHandler, // TIM1_CC_IRQHandler, // TIM2_IRQHandler, // TIM3_IRQHandler, // TIM6_DAC_IRQHandler, // 0, // TIM14_IRQHandler, // TIM15_IRQHandler, // TIM16_IRQHandler, // TIM17_IRQHandler, // I2C1_IRQHandler, // I2C2_IRQHandler, // SPI1_IRQHandler, // SPI2_IRQHandler, // USART1_IRQHandler, // USART2_IRQHandler, // 0, // CEC_IRQHandler, // 0, // #elif defined (STM32F070x6) // Chip Level - STM32F070 WWDG_IRQHandler, // 0, // RTC_IRQHandler, // FLASH_IRQHandler, // RCC_IRQHandler, // EXTI0_1_IRQHandler, // EXTI2_3_IRQHandler, // EXTI4_15_IRQHandler, // 0, // DMA1_Channel1_IRQHandler, // DMA1_Channel2_3_IRQHandler, // DMA1_Channel4_5_IRQHandler, // ADC1_IRQHandler, // TIM1_BRK_UP_TRG_COM_IRQHandler, // TIM1_CC_IRQHandler, // 0, // TIM3_IRQHandler, // 0, // 0, // TIM14_IRQHandler, // 0, // TIM16_IRQHandler, // TIM17_IRQHandler, // I2C1_IRQHandler, // 0, // SPI1_IRQHandler, // 0, // USART1_IRQHandler, // USART2_IRQHandler, // 0, // 0, // USB_IRQHandler, // #elif defined (STM32F070xB) // Chip Level - STM32F070 WWDG_IRQHandler, // 0, // RTC_IRQHandler, // FLASH_IRQHandler, // RCC_IRQHandler, // EXTI0_1_IRQHandler, // EXTI2_3_IRQHandler, // EXTI4_15_IRQHandler, // 0, // DMA1_Channel1_IRQHandler, // DMA1_Channel2_3_IRQHandler, // DMA1_Channel4_5_IRQHandler, // ADC1_IRQHandler, // TIM1_BRK_UP_TRG_COM_IRQHandler, // TIM1_CC_IRQHandler, // 0, // TIM3_IRQHandler, // TIM6_DAC_IRQHandler, // TIM7_IRQHandler, // TIM14_IRQHandler, // TIM15_IRQHandler, // TIM16_IRQHandler, // TIM17_IRQHandler, // I2C1_IRQHandler, // I2C2_IRQHandler, // SPI1_IRQHandler, // SPI2_IRQHandler, // USART1_IRQHandler, // USART2_IRQHandler, // USART3_4_IRQHandler, // 0, // USB_IRQHandler, // #elif defined (STM32F072) // Chip Level - STM32F051 (was STM32F0xx MD) WWDG_IRQHandler, // PVD_VDDIO2_IRQHandler, // RTC_IRQHandler, // FLASH_IRQHandler, // RCC_CRS_IRQHandler, // EXTI0_1_IRQHandler, // EXTI2_3_IRQHandler, // EXTI4_15_IRQHandler, // TSC_IRQHandler, // DMA1_Channel1_IRQHandler, // DMA1_Channel2_3_IRQHandler, // DMA1_Channel4_5_6_7_IRQHandler, // ADC1_COMP_IRQHandler, // TIM1_BRK_UP_TRG_COM_IRQHandler, // TIM1_CC_IRQHandler, // TIM2_IRQHandler, // TIM3_IRQHandler, // TIM6_DAC_IRQHandler, // TIM7_IRQHandler, // TIM14_IRQHandler, // TIM15_IRQHandler, // TIM16_IRQHandler, // TIM17_IRQHandler, // I2C1_IRQHandler, // I2C2_IRQHandler, // SPI1_IRQHandler, // SPI2_IRQHandler, // USART1_IRQHandler, // USART2_IRQHandler, // USART3_4_IRQHandler, // CEC_CAN_IRQHandler, // USB_IRQHandler, // #elif defined (STM32L073xx) WWDG_IRQHandler, /* Window WatchDog */ PVD_IRQHandler, /* PVD through EXTI Line detection */ RTC_IRQHandler, /* RTC through the EXTI line */ FLASH_IRQHandler, /* FLASH */ RCC_CRS_IRQHandler, /* RCC and CRS */ EXTI0_1_IRQHandler, /* EXTI Line 0 and 1 */ EXTI2_3_IRQHandler, /* EXTI Line 2 and 3 */ EXTI4_15_IRQHandler, /* EXTI Line 4 to 15 */ TSC_IRQHandler, /* TSC */ DMA1_Channel1_IRQHandler, /* DMA1 Channel 1 */ DMA1_Channel2_3_IRQHandler, /* DMA1 Channel 2 and Channel 3 */ DMA1_Channel4_5_6_7_IRQHandler, /* DMA1 Channel 4, Channel 5, Channel 6 and Channel 7*/ ADC1_COMP_IRQHandler, /* ADC1, COMP1 and COMP2 */ LPTIM1_IRQHandler, /* LPTIM1 */ USART4_5_IRQHandler, /* USART4 and USART 5 */ TIM2_IRQHandler, /* TIM2 */ TIM3_IRQHandler, /* TIM3 */ TIM6_DAC_IRQHandler, /* TIM6 and DAC */ TIM7_IRQHandler, /* TIM7 */ 0, /* Reserved */ TIM21_IRQHandler, /* TIM21 */ I2C3_IRQHandler, /* I2C3 */ TIM22_IRQHandler, /* TIM22 */ I2C1_IRQHandler, /* I2C1 */ I2C2_IRQHandler, /* I2C2 */ SPI1_IRQHandler, /* SPI1 */ SPI2_IRQHandler, /* SPI2 */ USART1_IRQHandler, /* USART1 */ USART2_IRQHandler, /* USART2 */ RNG_LPUART1_IRQHandler, /* RNG and LPUART1 */ LCD_IRQHandler, /* LCD */ USB_IRQHandler, /* USB */ #elif defined (STM32F091) // Chip Level - STM32F091 WWDG_IRQHandler, // PVD_VDDIO2_IRQHandler, // RTC_IRQHandler, // FLASH_IRQHandler, // RCC_CRS_IRQHandler, // EXTI0_1_IRQHandler, // EXTI2_3_IRQHandler, // EXTI4_15_IRQHandler, // TSC_IRQHandler, // DMA1_Channel1_IRQHandler, // DMA1_Ch2_3_DMA2_Ch1_2_IRQHandler, // DMA1_Ch4_7_DMA2_Ch3_5_IRQHandler, // ADC1_COMP_IRQHandler, // TIM1_BRK_UP_TRG_COM_IRQHandler, // TIM1_CC_IRQHandler, // TIM2_IRQHandler, // TIM3_IRQHandler, // TIM6_DAC_IRQHandler, // TIM7_IRQHandler, // TIM14_IRQHandler, // TIM15_IRQHandler, // TIM16_IRQHandler, // TIM17_IRQHandler, // I2C1_IRQHandler, // I2C2_IRQHandler, // SPI1_IRQHandler, // SPI2_IRQHandler, // USART1_IRQHandler, // USART2_IRQHandler, // USART3_8_IRQHandler, // CEC_CAN_IRQHandler, // 0, // #else #error "missing vectors" #endif // @0x108. This is for boot in RAM mode for STM32F0xx devices. (pHandler) 0xF108F85F }; // ---------------------------------------------------------------------------- // Processor ends up here if an unexpected interrupt occurs or a specific // handler is not present in the application code. void __attribute__ ((section(".after_vectors"))) Default_Handler(void) { #if defined(DEBUG) __DEBUG_BKPT(); #endif while (1) { } } // ---------------------------------------------------------------------------- <file_sep># lora_di Lora digital input <file_sep>/* * This file is part of the µOS++ distribution. * (https://github.com/micro-os-plus) * Copyright (c) 2014 <NAME>. * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom * the Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ // ---------------------------------------------------------------------------- #include "cmsis/cmsis_device.h" // ---------------------------------------------------------------------------- extern unsigned int __vectors_start; // Forward declarations. void __initialize_hardware_early(void); void __initialize_hardware(void); // ---------------------------------------------------------------------------- // This is the early hardware initialisation routine, it can be // redefined in the application for more complex cases that // require early inits (before BSS init). // // Called early from _start(), right before data & bss init. // // After Reset the Cortex-M processor is in Thread mode, // priority is Privileged, and the Stack is set to Main. void __attribute__((weak)) __initialize_hardware_early(void) { // Call the CSMSIS system initialisation routine. SystemInit(); #if defined(__ARM_ARCH_7M__) || defined(__ARM_ARCH_7EM__) // Set VTOR to the actual address, provided by the linker script. // Override the manual, possibly wrong, SystemInit() setting. SCB->VTOR = (uint32_t)(&__vectors_start); #endif // The current version of SystemInit() leaves the value of the clock // in a RAM variable (SystemCoreClock), which will be cleared shortly, // so it needs to be recomputed after the RAM initialisations // are completed. #if defined(OS_INCLUDE_STARTUP_INIT_FP) || (defined (__VFP_FP__) && !defined (__SOFTFP__)) // Normally FP init is done by SystemInit(). In case this is not done // there, it is possible to force its inclusion by defining // OS_INCLUDE_STARTUP_INIT_FP. // Enable the Cortex-M4 FPU only when -mfloat-abi=hard. // Code taken from Section 7.1, Cortex-M4 TRM (DDI0439C) // Set bits 20-23 to enable CP10 and CP11 coprocessor SCB->CPACR |= (0xF << 20); #endif // (__VFP_FP__) && !(__SOFTFP__) #if defined(OS_DEBUG_SEMIHOSTING_FAULTS) SCB->SHCSR |= SCB_SHCSR_USGFAULTENA_Msk; #endif } // This is the second hardware initialisation routine, it can be // redefined in the application for more complex cases that // require custom inits (before constructors), otherwise these can // be done in main(). // // Called from _start(), right after data & bss init, before // constructors. void __attribute__((weak)) __initialize_hardware(void) { // Call the CSMSIS system clock routine to store the clock frequency // in the SystemCoreClock global RAM location. SystemCoreClockUpdate(); } // ---------------------------------------------------------------------------- <file_sep> /****************************************************************************** * @file stm32l0xx_hal_msp.c * @author MCD Application Team * @version V1.1.0 * @date 27-February-2017 * @brief msp file for HAL ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2017 STMicroelectronics International N.V. * All rights reserved.</center></h2> * * Redistribution and use in source and binary forms, with or without * modification, are permitted, provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of STMicroelectronics nor the names of other * contributors to this software may be used to endorse or promote products * derived from this software without specific written permission. * 4. This software, including modifications and/or derivative works of this * software, must execute solely and exclusively on microcontroller or * microprocessor devices manufactured by or for STMicroelectronics. * 5. Redistribution and use of this software other than as permitted under * this license is void and will automatically terminate your rights under * this license. * * THIS SOFTWARE IS PROVIDED BY STMICROELECTRONICS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS, IMPLIED OR STATUTORY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE AND NON-INFRINGEMENT OF THIRD PARTY INTELLECTUAL PROPERTY * RIGHTS ARE DISCLAIMED TO THE FULLEST EXTENT PERMITTED BY LAW. IN NO EVENT * SHALL STMICROELECTRONICS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "hw.h" #include "low_power.h" #include "delay.h" #include "timeServer.h" /* when fast wake up is enabled, the mcu wakes up in ~20us * and * does not wait for the VREFINT to be settled. THis is ok for * most of the case except when adc must be used in this case before *starting the adc, you must make sure VREFINT is settled*/ #define ENABLE_FAST_WAKEUP /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /* Private macro --------------- * * * ----------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ /* Private functions ---------------------------------------------------------*/ /** * @brief This function configures the source of the time base. * @brief don't enable systick * @param TickPriority: Tick interrupt priority. * @retval HAL status */ HAL_StatusTypeDef HAL_InitTick(uint32_t TickPriority) { /* Return function status */ return HAL_OK; } /** * @brief This function provides delay (in ms) * @param Delay: specifies the delay time length, in milliseconds. * @retval None */ void HAL_Delay(__IO uint32_t Delay) { DelayMs( Delay ); /* based on RTC */ } /** * @brief Initializes the MSP. * @retval None */ void HAL_MspInit(void) { /* Disable the Power Voltage Detector */ HAL_PWR_DisablePVD( ); /* Enables the Ultra Low Power mode */ HAL_PWREx_EnableUltraLowPower( ); __HAL_FLASH_SLEEP_POWERDOWN_ENABLE(); /*In debug mode, e.g. when DBGMCU is activated, Arm core has always clocks * And will not wait that the FLACH is ready to be read. It can miss in this * case the first instruction. To overcome this issue, the flash remain clcoked during sleep mode */ DBG( __HAL_FLASH_SLEEP_POWERDOWN_DISABLE(); ); #ifdef ENABLE_FAST_WAKEUP /*Enable fast wakeUp*/ HAL_PWREx_EnableFastWakeUp( ); #else HAL_PWREx_DisableFastWakeUp( ); #endif } /** * @brief RTC MSP Initialization * This function configures the hardware resources used in this example: * - Peripheral's clock enable * @param hrtc: RTC handle pointer * @note Care must be taken when HAL_RCCEx_PeriphCLKConfig() is used to select * the RTC clock source; in this case the Backup domain will be reset in * order to modify the RTC Clock source, as consequence RTC registers (including * the backup registers) and RCC_CSR register are set to their reset values. * @retval None */ void HAL_RTC_MspInit(RTC_HandleTypeDef *hrtc) { RCC_OscInitTypeDef RCC_OscInitStruct; RCC_PeriphCLKInitTypeDef PeriphClkInitStruct; /*##-1- Configue the RTC clock soucre ######################################*/ /* -a- Enable LSE Oscillator */ RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSE; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE; RCC_OscInitStruct.LSEState = RCC_LSE_ON; if(HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) { Error_Handler(); } /* -b- Select LSI as RTC clock source */ PeriphClkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_RTC; PeriphClkInitStruct.RTCClockSelection = RCC_RTCCLKSOURCE_LSE; if(HAL_RCCEx_PeriphCLKConfig(&PeriphClkInitStruct) != HAL_OK) { Error_Handler(); } /*##-2- Enable the RTC peripheral Clock ####################################*/ /* Enable RTC Clock */ __HAL_RCC_RTC_ENABLE(); /*##-3- Configure the NVIC for RTC Alarm ###################################*/ HAL_NVIC_SetPriority(RTC_Alarm_IRQn, 0x0, 0); HAL_NVIC_EnableIRQ(RTC_Alarm_IRQn); } /** * @brief RTC MSP De-Initialization * This function freeze the hardware resources used in this example: * - Disable the Peripheral's clock * @param hrtc: RTC handle pointer * @retval None */ void HAL_RTC_MspDeInit(RTC_HandleTypeDef *hrtc) { /* Reset peripherals */ __HAL_RCC_RTC_DISABLE(); } /** * @brief Alarm A callback. * @param hrtc: RTC handle * @retval None */ void HAL_RTC_AlarmAEventCallback(RTC_HandleTypeDef *hrtc) { TimerIrqHandler( ); } /** * @brief EXTI line detection callbacks. * @param GPIO_Pin: Specifies the pins connected to the EXTI line. * @retval None */ void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin) { HW_GPIO_IrqHandler( GPIO_Pin ); } /** * @brief Gets IRQ number as a finction of the GPIO_Pin. * @param GPIO_Pin: Specifies the pins connected to the EXTI line. * @retval IRQ number */ IRQn_Type MSP_GetIRQn( uint16_t GPIO_Pin) { switch( GPIO_Pin ) { case GPIO_PIN_0: case GPIO_PIN_1: return EXTI0_1_IRQn; case GPIO_PIN_2: case GPIO_PIN_3: return EXTI2_3_IRQn; case GPIO_PIN_4: case GPIO_PIN_5: case GPIO_PIN_6: case GPIO_PIN_7: case GPIO_PIN_8: case GPIO_PIN_9: case GPIO_PIN_10: case GPIO_PIN_11: case GPIO_PIN_12: case GPIO_PIN_13: case GPIO_PIN_14: case GPIO_PIN_15: default: return EXTI4_15_IRQn; } } /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ <file_sep>/* / _____) _ | | ( (____ _____ ____ _| |_ _____ ____| |__ \____ \| ___ | (_ _) ___ |/ ___) _ \ _____) ) ____| | | || |_| ____( (___| | | | (______/|_____)_|_|_| \__)_____)\____)_| |_| (C)2013 Semtech Description: Ping-Pong implementation License: Revised BSD License, see LICENSE.TXT file include in the project Maintainer: <NAME> and <NAME> */ /****************************************************************************** * @file main.c * @author MCD Application Team * @version V1.1.0 * @date 27-February-2017 * @brief this is the main! ****************************************************************************** * @attention * * <h2><center>&copy; Copyright (c) 2017 STMicroelectronics International N.V. * All rights reserved.</center></h2> * * Redistribution and use in source and binary forms, with or without * modification, are permitted, provided that the following conditions are met: * * 1. Redistribution of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of STMicroelectronics nor the names of other * contributors to this software may be used to endorse or promote products * derived from this software without specific written permission. * 4. This software, including modifications and/or derivative works of this * software, must execute solely and exclusively on microcontroller or * microprocessor devices manufactured by or for STMicroelectronics. * 5. Redistribution and use of this software other than as permitted under * this license is void and will automatically terminate your rights under * this license. * * THIS SOFTWARE IS PROVIDED BY STMICROELECTRONICS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS, IMPLIED OR STATUTORY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE AND NON-INFRINGEMENT OF THIRD PARTY INTELLECTUAL PROPERTY * RIGHTS ARE DISCLAIMED TO THE FULLEST EXTENT PERMITTED BY LAW. IN NO EVENT * SHALL STMICROELECTRONICS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ /*test commit 12.07.2017 */ #include <string.h> #include "hw.h" #include "radio.h" #include "timeServer.h" #include "delay.h" #include "low_power.h" #include "vcom.h" #if defined( USE_BAND_868 ) #define RF_FREQUENCY 868000000 // Hz #elif defined( USE_BAND_915 ) #define RF_FREQUENCY 915000000 // Hz #else #error "Please define a frequency band in the compiler options." #endif #define TX_OUTPUT_POWER 14 // dBm #if defined( USE_MODEM_LORA ) #define LORA_BANDWIDTH 0 // [0: 125 kHz, // 1: 250 kHz, // 2: 500 kHz, // 3: Reserved] #define LORA_SPREADING_FACTOR 7 // [SF7..SF12] #define LORA_CODINGRATE 1 // [1: 4/5, // 2: 4/6, // 3: 4/7, // 4: 4/8] #define LORA_PREAMBLE_LENGTH 8 // Same for Tx and Rx #define LORA_SYMBOL_TIMEOUT 5 // Symbols #define LORA_FIX_LENGTH_PAYLOAD_ON false #define LORA_IQ_INVERSION_ON false #elif defined( USE_MODEM_FSK ) #define FSK_FDEV 25e3 // Hz #define FSK_DATARATE 50e3 // bps #define FSK_BANDWIDTH 50e3 // Hz #define FSK_AFC_BANDWIDTH 83.333e3 // Hz #define FSK_PREAMBLE_LENGTH 5 // Same for Tx and Rx #define FSK_FIX_LENGTH_PAYLOAD_ON false #else #error "Please define a modem in the compiler options." #endif #define RX_TIMEOUT_VALUE 3000 #define BUFFER_SIZE 64 // Define the payload size here #define LED_PERIOD_MS 200 #define LEDS_OFF do{ \ LED_Off( LED_BLUE ) ; \ LED_Off( LED_RED ) ; \ LED_Off( LED_GREEN1 ) ; \ LED_Off( LED_GREEN2 ) ; \ } while(0) ; #define ONE_SEC 120000 typedef enum{ sleepSt =0, powerSt, checkWakeUpEvSt, powerWakeOnRtcSt, }fsmStates; uint8_t buffer[BUFFER_SIZE]; volatile uint32_t rxTimeoutFlag; volatile uint32_t rxDataFlag; static fsmStates states = sleepSt; /* Led Timers objects*/ static TimerEvent_t timerLed; /* Private function prototypes -----------------------------------------------*/ /*! * Radio events function pointer */ static RadioEvents_t RadioEvents; static fsmStates setFSMState(fsmStates states); /*! * \brief Function to be executed on Radio Tx Done event */ void OnTxDone(void); /*! * \brief Function to be executed on Radio Rx Done event */ void OnRxDone(uint8_t *payload, uint16_t size, int16_t rssi, int8_t snr); /*! * \brief Function executed on Radio Tx Timeout event */ void OnTxTimeout(void); /*! * \brief Function executed on Radio Rx Timeout event */ void OnRxTimeout(void); /*! * \brief Function executed on Radio Rx Error event */ void OnRxError(void); /*! * \brief Function executed on when led timer elapses */ static void OnledEvent(void); /*! * \brief Function executed on when led timer elapses */ static void OnUserButtonEvent(void); /** * @brief System Clock Configuration */ static void devSystemClock_ConfigLPM(void); /** * Main application entry point. */ int main(void) { HAL_Init(); /* Configure the system clock to 2 MHz */ devSystemClock_ConfigLPM(); /*commented to see the consumption */ //DBG_Init(); HW_Init(); /*commented to see the consumption */ /* Led Timers*/ // TimerInit(&timerLed, OnledEvent); // TimerSetValue(&timerLed, LED_PERIOD_MS); // // TimerStart(&timerLed); // Radio initialization RadioEvents.TxDone = OnTxDone; RadioEvents.RxDone = OnRxDone; RadioEvents.TxTimeout = OnTxTimeout; RadioEvents.RxTimeout = OnRxTimeout; RadioEvents.RxError = OnRxError; Radio.Init(&RadioEvents); Radio.SetChannel(RF_FREQUENCY); #if defined(USE_MODEM_LORA) Radio.SetTxConfig( MODEM_LORA, TX_OUTPUT_POWER, 0, LORA_BANDWIDTH, LORA_SPREADING_FACTOR, LORA_CODINGRATE, LORA_PREAMBLE_LENGTH, LORA_FIX_LENGTH_PAYLOAD_ON, true, 0, 0, LORA_IQ_INVERSION_ON, 3000000 ); Radio.SetRxConfig( MODEM_LORA, LORA_BANDWIDTH, LORA_SPREADING_FACTOR, LORA_CODINGRATE, 0, LORA_PREAMBLE_LENGTH, LORA_SYMBOL_TIMEOUT, LORA_FIX_LENGTH_PAYLOAD_ON, 0, true, 0, 0, LORA_IQ_INVERSION_ON, true ); #elif defined(USE_MODEM_FSK) Radio.SetTxConfig( MODEM_FSK, TX_OUTPUT_POWER, FSK_FDEV, 0, FSK_DATARATE, 0, FSK_PREAMBLE_LENGTH, FSK_FIX_LENGTH_PAYLOAD_ON, true, 0, 0, 0, 3000000 ); Radio.SetRxConfig( MODEM_FSK, FSK_BANDWIDTH, FSK_DATARATE, 0, FSK_AFC_BANDWIDTH, FSK_PREAMBLE_LENGTH, 0, FSK_FIX_LENGTH_PAYLOAD_ON, 0, true, 0, 0,false, true ); #else #error "Please define a frequency band in the compiler options." #endif //__HAL_FLASH_PREFETCH_BUFFER_DISABLE(); #define SENDER #ifdef SENDER uint32_t old_state = BSP_PB_GetState(BUTTON_USER); uint32_t state = old_state; while(true) { switch(states) { case sleepSt: { /* Insert 0.5 seconds delay */ HAL_Delay(500); /* User push-button (External lines 4 to 15) will be used to wakeup the system from SLEEP mode */ //BSP_PB_Init(BUTTON_KEY, BUTTON_MODE_EXTI); BSP_PB_Init(BUTTON_USER, BUTTON_MODE_GPIO); BSP_PB_Init(BUTTON_USER, BUTTON_MODE_EXTI); HW_GPIO_SetIrq(USER_BUTTON_GPIO_PORT, USER_BUTTON_PIN, 0, OnUserButtonEvent); /*Suspend Tick increment to prevent wakeup by Systick interrupt. Otherwise the Systick interrupt will wake up the device within 1ms (HAL time base)*/ HAL_SuspendTick(); /* Enable Power Control clock */ __HAL_RCC_PWR_CLK_ENABLE(); HW_RTC_SetAlarm(ONE_SEC); states = checkWakeUpEvSt; /* Enter Sleep Mode , wake up is done once User push-button is pressed */ HAL_PWR_EnterSLEEPMode(PWR_MAINREGULATOR_ON, PWR_SLEEPENTRY_WFI); /* Resume Tick interrupt if disabled prior to sleep mode entry*/ HAL_ResumeTick(); } break; case powerSt: { state = BSP_PB_GetState(BUTTON_USER); if(state != old_state) { if(state) { buffer[0] = 'o'; buffer[1] = 'f'; buffer[2] = 'f'; buffer[3] = 0x00; } else { buffer[0] = 'o'; buffer[1] = 'n'; buffer[2] = 0x00; buffer[3] = 0x00; } // send button state PRINTF(buffer); PRINTF("\n"); Radio.Send(buffer, BUFFER_SIZE); } else { states = sleepSt; } old_state = state; DelayMs(200); } break; case checkWakeUpEvSt: { if ( (__HAL_PWR_GET_FLAG(PWR_FLAG_WU)) == SET) { states = powerWakeOnRtcSt; } else { states = checkWakeUpEvSt; } } break; case powerWakeOnRtcSt: { if (BSP_PB_GetState(BUTTON_USER) == GPIO_PIN_RESET) { buffer[0] = 'o'; buffer[1] = 'n'; buffer[2] = 0x00; buffer[3] = 0x00; } else { buffer[0] = 'o'; buffer[1] = 'f'; buffer[2] = 'f'; buffer[3] = 0x00; } // send button state PRINTF(buffer); PRINTF("\n"); states = sleepSt; Radio.Send(buffer, BUFFER_SIZE); } break; } } #endif //#define RECEIVER #ifdef RECEIVER while(true) { rxTimeoutFlag = false; rxDataFlag = false; Radio.Rx(RX_TIMEOUT_VALUE); while(!rxTimeoutFlag && !rxDataFlag); } #endif } /* * @brief System Clock Configuration * The system Clock is configured as follow : * System Clock source = MSI * SYSCLK(Hz) = 2000000 * HCLK(Hz) = 2000000 * AHB Prescaler = 1 * APB1 Prescaler = 1 * APB2 Prescaler = 1 * Flash Latency(WS) = 0 * Main regulator output voltage = Scale3 mode * @retval None */ void devSystemClock_ConfigLPM(void) { RCC_ClkInitTypeDef RCC_ClkInitStruct = {0}; RCC_OscInitTypeDef RCC_OscInitStruct = {0}; /* Enable MSI Oscillator */ RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_MSI; RCC_OscInitStruct.MSIState = RCC_MSI_ON; RCC_OscInitStruct.MSIClockRange = RCC_MSIRANGE_5; RCC_OscInitStruct.MSICalibrationValue=0x00; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE; if (HAL_RCC_OscConfig(&RCC_OscInitStruct)!= HAL_OK) { /* Initialization Error */ while(1); } /* Select MSI as system clock source and configure the HCLK, PCLK1 and PCLK2 clocks dividers */ RCC_ClkInitStruct.ClockType = (RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2); RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_MSI; RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1; RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1; if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_0)!= HAL_OK) { /* Initialization Error */ while(1); } /* Enable Power Control clock */ __HAL_RCC_PWR_CLK_ENABLE(); /* The voltage scaling allows optimizing the power consumption when the device is clocked below the maximum system frequency, to update the voltage scaling value regarding system frequency refer to product datasheet. */ __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE3); /* Disable Power Control clock */ __HAL_RCC_PWR_CLK_DISABLE(); } void OnTxDone(void) { Radio.Sleep(); PRINTF("OnTxDone\n"); } void OnRxDone(uint8_t *payload, uint16_t size, int16_t rssi, int8_t snr) { char str[10] = {0}; uint32_t i; //check for board unique ID for(i = 0; (i < size) && (i < 9); i++) { str[i] = payload[i]; } rxDataFlag = true; PRINTF(str); PRINTF("\n"); PRINTF("OnRxDone\n"); PRINTF("RssiValue=%d dBm, SnrValue=%d\n", rssi, snr); } void OnTxTimeout( void ) { Radio.Sleep(); PRINTF("OnTxTimeout\n"); } void OnRxTimeout(void) { Radio.Sleep(); rxTimeoutFlag = true; PRINTF("OnRxTimeout\n"); } void OnRxError(void) { Radio.Sleep(); rxTimeoutFlag = true; PRINTF("OnRxError\n"); } static fsmStates setFSMState(fsmStates states) { fsmStates st; st = states; return st; } static void OnledEvent(void) { LED_Toggle( LED_BLUE ) ; LED_Toggle( LED_RED1 ) ; LED_Toggle( LED_RED2 ) ; LED_Toggle( LED_GREEN ) ; TimerStart(&timerLed ); } void OnUserButtonEvent(void) { states = setFSMState(powerSt); PRINTF("UserButton\n"); }
0ab4dbddb9398b97a89c76f1b5647ac4d27181bb
[ "Markdown", "C" ]
7
C
deyraul2003/loraDI
237ef93a134916baeaa2ffce9ac3795b2da8d87b
9110737d1aa32ac0c7f1cd35ab66928c5d624996
refs/heads/master
<file_sep>db_model.dbm - pgmodeler xml<br> lanlearn.sql - database script<br> <file_sep>const sign_up = require('../sign_up/index'); const sample = require('../tests/sample'); const remove_customer_customer_id = require('../tests/remove_customer_customer_id').remove_customer_customer_id; const vocabulary_set_translation = require('./index'); const vocabulary_get_translation = require('../vocabulary_get_translation'); const generateToken = require('../common/generateToken'); const constants = require('../common/constants'); test('set translations and get it back (vocabulary_get_translation should return 0)', async () => { const user_name = generateToken.randomAsciiString(constants.default_length); let context = {log: jest.fn()} let request = { body: sample.customer }; request.body.user_name = user_name; await sign_up(context, request); const customer_id = context.res.body.customer_id; const token = context.res.body.token; let translations = ["добро", "хороший"]; let phrase = "good"; context = {log: jest.fn()} request = { body: {customer_id:customer_id, token:token, phrase:phrase, translations:translations} }; await vocabulary_set_translation(context, request); expect(context.res.body.status).toEqual('0'); context = {log: jest.fn()} request = { body: {customer_id:customer_id, token:token} }; await vocabulary_get_translation(context, request); expect(translations.length).toEqual(context.res.body.rows.length); for (i=0; i<translations.length; i++){ expect(translations.indexOf(context.res.body.rows[i].ru)).toBeGreaterThanOrEqual(0); } expect(translations.indexOf("can't find it")).toBe(-1); await remove_customer_customer_id(customer_id); }, 30000);<file_sep> var word_hover_background = "rgba(162, 165, 58, 0.51)"; var success_color = "rgba(105,255,107,0.84)"; var fail_color = "rgba(255, 93, 103, 0.84)"; var empty_color = "rgb(140, 141, 149)"; var selected_text_color = "rgb(25, 119, 25)"; var default_text_color = "rgb(0, 0, 0)"; var main_color = "rgba(252, 255, 182, 0.99)"; var cookie_expired_date = new Date(new Date().getTime() + 180 * 24 * 60 * 60 * 1000);<file_sep>#!/bin/bash #pip install virtualenv #python3 -m virtualenv env source env/bin/activate #pip install -r requirements.txt python3 main.py deactivate<file_sep># lanlearn Simple helper for learning language (serverless version) Project structure: - backend - azure functions - static - that is client side that is keeping on static storage (static website) - database - database script, pictures of sheme, script for loading database <file_sep>function download_table() { let name="en_ru_guessed"; let type="text/json"; var a = document.getElementById("save_button"); let json = JSON.stringify(Array.from(en_ru_guessed_table)); var file = new Blob(["{en_ru_guessed:" + json + "}"], {type: type}); a.href = URL.createObjectURL(file); a.download = name; }<file_sep>src - static site<br> puppeter-mocha - tests for static<br> <file_sep>var url = window.location.href + "book/"; authors = document.getElementsByClassName("author"); for (let i=0; i<authors.length; i++){ for (let j=0; j<authors[i].children[0].children.length; j++){ authors[i].children[0].children[j].addEventListener("click", function (){ author = authors[i].innerHTML.split("<")[0].trim(); title = authors[i].children[0].children[j].children[0].innerHTML.trim(); console.log(author); console.log(title); location.replace(url + "author=" + author + "&title=" + title); }) } }<file_sep>var customer_id = getCookie("customer_id"); var token = getCookie("token"); if ((customer_id === undefined) || (token === undefined)){ window.location.pathname = "/sign_in/sign_in.html"; }else{ var data = { customer_id: customer_id, token:token } var xhttp = new XMLHttpRequest(); xhttp.open('POST', personal_area_en_ru_url, true); xhttp.setRequestHeader('Content-Type', 'application/json'); xhttp.onload = function () { console.log(JSON.stringify(data)); console.log("sent "); switch (JSON.parse(xhttp.responseText).status){ case "0": let table = document.getElementById("table"); let rows = JSON.parse(xhttp.responseText).rows; for (i=0; i < rows.length; i++){ let row = document.createElement("tr"); let en = document.createElement("td"); en.innerText = rows[i].en; row.appendChild(en); let ru = document.createElement("td"); ru.innerText = rows[i].ru; row.appendChild(ru); let guessed_number = document.createElement("td"); guessed_number.innerText = rows[i].guessed_number; row.appendChild(guessed_number); let attempts_number = document.createElement("td"); attempts_number.innerText = rows[i].attempts_number; row.appendChild(attempts_number); let last_attempt_date = document.createElement("td"); last_attempt_date.innerText = new Date(Date.parse(rows[i].last_attempt_date)).toUTCString(); row.appendChild(last_attempt_date); table.appendChild(row); } break; case "3": document.getElementById("table").remove(); document.getElementById("main_container").style.backgroundColor = "rgb(140, 141, 149)"; document.getElementById("status_container").style.flexGrow = "1"; document.getElementById("status").innerText = "Now there are no words in your vocabulary.\nAdd something..."; break; } }; xhttp.send(JSON.stringify(data)); }<file_sep>const sign_up = require('../sign_up/index'); const check_update_translations = require('./index'); const vocabulary_set_translation = require('../vocabulary_set_translation'); const vocabulary_get_translation = require('../vocabulary_get_translation'); const remove_customer_customer_id = require('../tests/remove_customer_customer_id').remove_customer_customer_id; const sample = require('../tests/sample'); const generateToken = require('../common/generateToken'); const constants = require('../common/constants'); test('set translations and replace to en_ru_guessed (vocabulary_get_translation should return 0)', async () => { const user_name = generateToken.randomAsciiString(constants.default_length); let context = {log: jest.fn()} let request = { body: sample.customer }; request.body.user_name = user_name; await sign_up(context, request); const customer_id = context.res.body.customer_id; const token = context.res.body.token; let translations = ["добро", "хороший"]; let phrase = "good"; context = {log: jest.fn()} request = { body: { customer_id:customer_id, token:token, phrase:phrase, translations:translations } }; await vocabulary_set_translation(context, request); expect(context.res.body.status).toEqual('0'); context = {log: jest.fn()} request = { body: { customer_id:customer_id, token:token } }; await vocabulary_get_translation(context, request); expect(translations.length).toEqual(context.res.body.rows.length); for (i=0; i<translations.length; i++){ expect(translations.indexOf(context.res.body.rows[i].ru)).toBeGreaterThanOrEqual(0); } context = {log: jest.fn()} request = { body: { customer_id: customer_id, en: phrase, ru: translations, attempts_number: 10 } } await check_update_translations(context, request); expect(context.res.body.status).toEqual("0"); //await remove_customer_customer_id(customer_id); }, 30000);<file_sep> var text_container = document.getElementById("text_container"); text_container.innerHTML = text_container.innerHTML.replace(/\n+/gi, "<br> "); var words = text_container.innerText.split(/ /); text_container.innerText = ""; var regexp = /\n+/gi; var paragraph = document.createElement("div"); paragraph.setAttribute("class", "paragraph"); var words_array = []; // words for translation for (var i=0; i<words.length; i++){ if (words[i].trim()){ var word = document.createElement("div"); word.setAttribute("class", "word"); word.innerHTML = words[i]; word.addEventListener("click", function () { if (this.style.backgroundColor === word_hover_background){ this.style.backgroundColor = main_color; words_array.splice(words_array.indexOf(this), 1); } else{ this.style.backgroundColor = word_hover_background; words_array.push(this); } }); paragraph.appendChild(word); if (regexp.exec(words[i])){ text_container.appendChild(paragraph); paragraph = document.createElement("div"); paragraph.setAttribute("class", "paragraph"); } } } var csrfcookie = function() { var cookieValue = null, name = 'csrftoken'; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = cookies[i].trim(); if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; }; var key; var url = window.location.href.split("author")[0] + "key"; var xhttp = new XMLHttpRequest(); xhttp.open('GET', url, true); xhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8'); xhttp.setRequestHeader('X-CSRFToken', csrfcookie()); xhttp.onload = function () { key = JSON.parse(xhttp.responseText).key; console.log("Got api key"); url = url_pattern.replace(key_pattern, key); }; xhttp.send(); var url_pattern = "https://translate.yandex.net/api/v1.5/tr.json/translate?key=#key&lang=#lang&text=#text"; var key_pattern = "#key"; var lang_pattern = "#lang"; var text_pattern = "#text"; function key_handler(e){ if (e.keyCode === 13){ if (words_array.length > 0){ var lang = "en-ru"; //todo: var xhttp = new XMLHttpRequest(); text = words_array[0].innerHTML; for (i=1; i<words_array.length; i++) text += " " + words_array[i].innerHTML; xhttp.open('GET', url.replace(lang_pattern, lang).replace(text_pattern, text, true)); xhttp.onload = function () { translation = JSON.parse(xhttp.responseText).text; for (i=0; i<words_array.length; i++) words_array[i].style.backgroundColor = main_color; words_array.splice(0, words_array.length); alert(translation); }; xhttp.send(); } } } addEventListener("keyup", key_handler); <file_sep>checkSign(); // hide elements checkRedirect(); // redirect to sign_in / sign_up load_database_translations();<file_sep>var status_container = document.getElementById("status_container"); var status = document.getElementById("status"); function transitionendListner() { status_container.style.opacity = "0"; status_container.style.transition = "opacity 1s"; status_container.style.visibility = "hidden"; } var attempts_number = 0; var check_button = document.getElementById('check_button'); function check() { if (check_button.innerText === "check") { let phrase = document.getElementById("phrase").innerText; attempts_number += 1; var input = document.getElementsByClassName("input_item"); var translation = ""; Array.prototype.filter.call(input, function(element){ translation += element.value; }); if (phrase === translation){ check_button.innerText = "next"; status_container.style.backgroundColor = success_color; status_container.children[0].innerHTML = "Success"; var transitionNodes = document.getElementById("translations_container").childNodes; var translations = []; for (i=0; i<transitionNodes.length; i++) translations.push(transitionNodes[i].innerHTML); var request_text = { customer_id:customer_id, token: token, en:phrase, ru:translations, attempts_number:attempts_number } attempts_number = 0; // async - execution of sending response to back seems to be faster than // loading new, showing its and guessing of phrase by customer var xhttp = new XMLHttpRequest(); xhttp.open("POST", check_update_translations_url, true); xhttp.onload = () => { console.log("Response text:" + JSON.stringify(xhttp.responseText)); } xhttp.send(JSON.stringify(request_text)); } else{ document.getElementById("input_wrap").childNodes[0].focus(); status_container.style.backgroundColor = ""; status_container.style.backgroundColor = fail_color; status_container.children[0].innerHTML = "Fail"; } status_container.style.visibility = "visible"; status_container.style.opacity = 1; }else{ if (!isExistTranslations){ document.getElementById("status_container").removeEventListener("transitionend", transitionendListner, true); noTranslations(); } else { check_button.innerText = "check"; set_phrase_translations(); let last_phrase = view(); load_phrase_translations(last_phrase); } } } // start load_phrase_translations(""); if (!isExistTranslations) { noTranslations(); } else { set_phrase_translations(); let ph = view(); status_container.addEventListener("transitionend", transitionendListner, true); load_phrase_translations(ph); }<file_sep>const sign_up = require('../sign_up/index'); const sample = require('../tests/sample'); const remove = require('../tests/remove_customer_user_name'); const vocabulary_get_translation = require('./index'); const generateToken = require('../common/generateToken'); const constants = require('../common/constants'); test('correct token and customer_id (vocabulary_get_translation should return 0)', async () => { let user_name = generateToken.randomAsciiString(constants.default_length); let context = {log: jest.fn()} let request = { body: sample.customer }; request.body.user_name = user_name; await sign_up(context, request); let customer_id = context.res.body.customer_id; let token = context.res.body.token; request = { body: {customer_id:customer_id, token:token} }; await vocabulary_get_translation(context, request); expect(context.res.body.status).toEqual('0'); remove.remove_customer_user_name(user_name); }, 30000); test("token is uncorrect (expired or don't match). (vocabulary_get_translation should return 2)", async () => { let context = {log: jest.fn()} let request = { body: {customer_id:"12", token:"uncorrect token"} }; await vocabulary_get_translation(context, request); expect(context.res.body.status).toEqual('2'); }, 30000); test('(vocabulary_get_translation should return 4)', async () => { let context = {log: jest.fn()} let request = { body: {customer_id:"-12", token:"uncorrect token"} }; await vocabulary_get_translation(context, request); expect(context.res.body.status).toEqual('4'); }, 30000);<file_sep>exports.remove_customer_customer_id = async function (customer_id) { const fs = require('fs'); const ini = require('ini'); let config = ini.parse(fs.readFileSync('./../private/db_connection.ini', 'utf-8')); const pg = require('pg'); const client = new pg.Client({ user: config.database.USER, host: config.database.HOST, database: config.database.database, password: <PASSWORD>, port: config.database.PORT, ssl: false }); await client.connect(); await client.query(` delete from customer where customer_id=$1`, [customer_id]); return true }<file_sep>from drop_db import drop_db from create_db import create_db if __name__ == "__main__": db_connection_file = './../private/db_connection.ini' if drop_db(db_connection_file): print("errors") else: create_db(db_connection_file) <file_sep> var max_guessed_number = 2; var timezone = 3; module.exports.max_guessed_number = max_guessed_number; module.exports.timezone = timezone; module.exports.default_length = 100;<file_sep>var input_wrap = document.getElementById("input_wrap"); function onInput(event) { event.currentTarget.value = event.data; event.currentTarget.nextSibling.focus(); } function view (){ /* Show cells for characters input. return last_translation. */ let phrase = document.getElementById("phrase"); let len = phrase.innerText.length; while (input_wrap.childNodes.length > 0) input_wrap.removeChild(input_wrap.childNodes[0]); for (i=0; i<len-1; i++){ let input_item = document.createElement("input"); input_item.setAttribute('class', 'input_item'); input_item.addEventListener('input', onInput); input_wrap.appendChild(input_item); } let input_item = document.createElement("input"); input_item.setAttribute('class', 'input_item'); input_wrap.appendChild(input_item); input_item.addEventListener('input', (event) => {event.currentTarget.value = event.data}); input_item.oninput = function(){ document.getElementById("check_button").focus(); }; input_wrap.childNodes[0].focus(); console.log("Show phrase"); return phrase.innerText; }<file_sep>function bufAsciiString (buff) { /* convert buff to string using acceptable sumbols (chars) */ let chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; let result = new Array(buff.length); for (var i = 0; i < buff.length; i++) { result[i] = chars[buff[i] % chars.length]; } return result.join(''); } exports.getHash = function (password, user_name){ /* Generate hash */ //const scrypt = require("scrypt"); //return bufAsciiString(scrypt.hashSync(password, {"N":16384,"r":8,"p":1}, 300, user_name)); let Crypto = require('crypto-js'); return Crypto.SHA256(password).toString(); }<file_sep>import configparser import psycopg2 def drop_db(db_connection_file): """ :param request: :return: """ section = 'database' conf_parser = configparser.ConfigParser() conf_parser.read(db_connection_file) if conf_parser.has_section(section): connection = None try: connection = psycopg2.connect( dbname='postgres',#conf_parser.get(section, 'database'), user=conf_parser.get(section, 'USER'), password=conf_parser.get(section, 'PASSWORD'), host=conf_parser.get(section, 'HOST'), port=conf_parser.get(section, 'PORT'), ) connection.set_isolation_level(0) cursor = connection.cursor() query_text = """ select exists(SELECT datname FROM pg_catalog.pg_database WHERE lower(datname) = lower('{0}')); """.format(conf_parser.get(section, 'database')) cursor.execute(query_text) if cursor.fetchall()[0][0]: query_text = """ SELECT pg_terminate_backend (pg_stat_activity.pid) FROM pg_stat_activity WHERE pg_stat_activity.datname = '{0}'; """.format(conf_parser.get(section, 'database')) cursor.execute(query_text) query_text = """ drop database %s; """ % conf_parser.get(section, 'database') cursor.execute(query_text) cursor.execute('create database {0} owner dmitry'.format(conf_parser.get(section, 'database'))) cursor.close() connection.commit() print('Previous database was dropped.') return 0 except (Exception, psycopg2.DatabaseError) as error: print("Exception:", error) finally: if connection is not None: connection.close() print('Database connection closed.') else: raise Exception('Section {0} not found in the {1} file'.format(section, db_connection_file)) <file_sep>to generate html report replace to package.json<br> "test": "./node_modules/.bin/mocha --reporter mocha-simple-html-reporter --reporter-options output=../src/test/client.html" <file_sep>var customer_id = getCookie("customer_id"); var token = getCookie("token"); var en_ru_guessed_table; if ((customer_id === undefined) || (token === undefined)){ window.location.pathname = "/sign_in/sign_in.html"; }else{ var data = { customer_id: customer_id, token: token } var xhttp = new XMLHttpRequest(); xhttp.open('POST', personal_area_en_ru_guessed_url, true); xhttp.setRequestHeader('Content-Type', 'application/json'); xhttp.onload = function () { console.log(JSON.stringify(data)); console.log("sent"); switch (JSON.parse(xhttp.responseText).status){ case "0": let table = document.getElementById("table"); let rows = JSON.parse(xhttp.responseText).rows; en_ru_guessed_table = rows; for (i=0; i < rows.length; i++){ let row = document.createElement("tr"); let en = document.createElement("td"); en.innerText = rows[i].en; row.appendChild(en); let ru = document.createElement("td"); ru.innerText = rows[i].ru; row.appendChild(ru); let attempts_number = document.createElement("td"); attempts_number.innerText = rows[i].attempts_number; row.appendChild(attempts_number); let guessed_date = document.createElement("td"); guessed_date.innerText = new Date(Date.parse(rows[i].guessed_date)).toUTCString(); row.appendChild(guessed_date); table.appendChild(row); } document.getElementById("save_button").style.visibility = "visible"; break; case "3": document.getElementById("container").remove(); document.getElementById("main_container").style.backgroundColor = "rgb(140, 141, 149)"; document.getElementById("status_container").style.flexGrow = "1"; document.getElementById("status").innerText = "Now there are no words in your vocabulary.\nAdd something..."; break; } }; xhttp.send(JSON.stringify(data)); }<file_sep>module.exports = async function (context, req) { const fs = require('fs'); const ini = require('ini'); const config = ini.parse(fs.readFileSync('./common/private/db_connection.ini', 'utf-8')); let token = req.body.token; let customer_id = req.body.customer_id; let phrase = req.body.phrase; let translations = req.body.translations; const pg = require('pg'); const client = new pg.Client({ user: config.database.USER, host: config.database.HOST, database: config.database.database, password: <PASSWORD>, port: config.database.PORT, ssl: false }); let status; if ((translations.length > 0)&&(token != undefined)&&(customer_id > 0)&&(phrase.length > 0)){ await client.connect() const token_res = await client.query(` select token, token_expired_date from customer where customer_id=$1`, [customer_id]) if ((token === undefined) || (customer_id < 1)) status = "4" else if (token_res.rowCount === 0) status = "2" else if ((token_res.rows[0].token != token)&&(Date.parse(token_res.rows[0].token_expired_date) < Date.now())) status = "1" else { status = "0" let text = 'INSERT INTO en_ru(customer_id, en, ru, guessed_number, attempts_number, last_attempt_date) VALUES'; for (i=0; i<translations.length-1; i++){ text += "($1,$2,'" + translations[i] + "',0,0,$3),"; } text += "($1,$2,'" + translations[translations.length - 1] + "',0,0,$3)"+ "on conflict on constraint unique_en_ru_customer_id do nothing;"; await client.query(text, [customer_id, phrase, (new Date(Date.now())).toUTCString()]) } client.end(); }else{ status = "5" } context.res = { status: 200, body: { status: status }, headers: { 'Content-Type': 'application/json' } } }<file_sep>module.exports = { customer: { "user_name":"pqgegnwkgnsdjbOUGWBEJG", "first_name":"<NAME>", "last_name":"aeoughornvaronhafhdjtj", "city":"Tula", "country":"Russia", "email":"<EMAIL>", 'password':"<PASSWORD>", "vocabulary_key":"<KEY>", "translate_key" : "trnsl.1.1.20181101T204706Z.3710d2fa6fdff9ab.e6b8d336ff2d6b6b0eaf40eed6fc5afe5cb02353" } }<file_sep>const url = require('../url'); const random_string = require('../common/random_string'); describe('sign up correct work', function () { this.timeout(60000); let page; before (async function () { page = await browser.newPage(); await page.goto(url.sign_up_url); await page.evaluate(() => removeCookie()); }) after (async function () { await page.evaluate(() => removeCookie()); await page.close(); }) it('should have the correct page title', async function () { expect(await page.title()).to.eql('Lanlearn'); }); it("assert that a div named navbar exists", async () => { let nav_bar = await page.$eval(".nav_bar", el => (el ? true : false)); expect(nav_bar).to.eql(true); }); it("assert that sign_in visible", async () => { await page.waitForSelector('#sign_in'); let sign_in = await page.$eval("#sign_in", el => {return el.style.display}); expect(sign_in).to.eql(""); }); it("assert that sign_up visible", async () => { await page.waitForSelector('#sign_up'); let sign_up = await page.$eval("#sign_up", el => {return el.style.display}); expect(sign_up).to.eql(""); }); it("assert that sign_out invisible", async () => { await page.waitForSelector('#sign_out'); let sign_out = await page.$eval("#sign_out", el => {return el.style.display}); expect(sign_out).to.eql("none"); }); it('set customer data and redirect to home page afterall', async function () { /* Sign up */ let user_name = random_string.randomAsciiString(100); await page.waitForSelector('#username'); await page.$$eval('#username', (e, user_name) => {e[0].value=user_name}, user_name); await page.waitForSelector('input[name=submit_first]'); await page.focus('input[name=submit_first]'); await page.$eval('input[name=submit_first]', e => { return e.click()}); await page.waitForSelector('input[name=submit_second]'); await page.focus('input[name=submit_second]'); await page.$eval('input[name=submit_second]', e => e.click()); await page.waitForSelector('input[name=submit_third]'); await page.focus('input[name=submit_third]'); await page.$eval('input[name=submit_third]', e => e.click()); await page.waitForSelector('input[name=submit_fourth]'); await page.focus('input[name=submit_fourth]'); await page.$eval('input[name=submit_fourth]', e => e.click()); await page.waitForNavigation(); let new_url = await page.evaluate(() => {return window.location.origin}); expect(new_url).to.eql(url.home_url); }); it("assert that sign_in invisible", async () => { await page.waitForSelector('#sign_in'); let sign_in = await page.$eval("#sign_in", el => {return el.style.display}); expect(sign_in).to.eql("none"); }); it("assert that sign_up invisible", async () => { await page.waitForSelector('#sign_up'); let sign_up = await page.$eval("#sign_up", el => {return el.style.display}); expect(sign_up).to.eql("none"); }); it("assert that sign_out visible", async () => { await page.waitForSelector('#sign_out'); let sign_out = await page.$eval("#sign_out", el => {return el.style.display}); expect(sign_out).to.eql(""); }); });<file_sep>var database_translations = []; function load_database_translations(){ /* Get translations of en that are in database already Can't return array because it will pause execution of other functions. Seems to be better to set translations implicitly... */ let xhttp = new XMLHttpRequest(); data = { customer_id: getCookie("customer_id"), token: getCookie("token") } xhttp.open('POST', vocabulary_get_translation_url, true); xhttp.setRequestHeader('Content-Type', 'application/json'); xhttp.onload = function () { switch (JSON.parse(xhttp.responseText).status){ case "0": for (i=0; i<JSON.parse(xhttp.responseText).rows.length; i++) database_translations.push(JSON.parse(xhttp.responseText).rows[i]); break; case "1": break; case "2": window.location.pathname = "/sign_in/sign_in.html"; break; } }; xhttp.send(JSON.stringify(data)); }<file_sep>$(function(){ var field_values = { 'username' : 'Логин', 'password' : '<PASSWORD>', 'cpassword' : '<PASSWORD>', 'firstname' : 'Имя', 'lastname' : 'Фамилия', 'email' : 'email' }; $('input#username').inputfocus({ value: field_values['username'] }); $('input#password').inputfocus({ value: field_values['password'] }); $('input#cpassword').inputfocus({ value: field_values['cpassword'] }); $('input#lastname').inputfocus({ value: field_values['lastname'] }); $('input#firstname').inputfocus({ value: field_values['firstname'] }); $('input#email').inputfocus({ value: field_values['email'] }); $('#progress').css('width','0'); $('#progress_text').html('0% Выполнено'); $('form').submit(function(){ return false; }); $('#submit_first').click(function(){ $('#first_step input').removeClass('error').removeClass('valid'); var fields = $('#first_step input[type=text], #first_step input[type=password]'); var error = 0; fields.each(function(){ var value = $(this).val(); if( value.length<4 || value==field_values[$(this).attr('id')]) { $(this).addClass('error'); $(this).effect("shake", { times:3 }, 50); error++; } else { $(this).addClass('valid'); } }); for (i=0; i<user_names.length; i++){ if (user_names[i] === $('#username').val()){ alert("User name is lready used. Try to select another."); $("#username").addClass('error'); $("#username").effect("shake", { times:3 }, 50); error++; break; } } if(!error) { if( $('#password').val() != $('#cpassword').val() ) { $('#first_step input[type=password]').each(function(){ $(this).removeClass('valid').addClass('error'); $(this).effect("shake", { times:3 }, 50); }); return false; } else { $('#progress_text').html('33% Выполнено'); $('#progress').css('width','113px'); $('#first_step').slideUp(200, "swing"); $('#second_step').slideDown(400, "swing"); } } else return false; }); $('#submit_second').click(function(){ $('#second_step input').removeClass('error').removeClass('valid'); let emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,20}$/; let fields = $('#second_step input[type=text]'); let error = 0; fields.each(function(){ var value = $(this).val(); if( value.length<1 || value==field_values[$(this).attr('id')] || ( $(this).attr('id')=='email' && !emailPattern.test(value) ) ) { $(this).addClass('error'); $(this).effect("shake", { times:3 }, 50); error++; } else { $(this).addClass('valid'); } }); if(!error) { $('#progress_text').html('66% Выполнено'); $('#progress').css('width','226px'); $('#second_step').slideUp(200, "swing"); $('#third_step').slideDown(400, "swing"); } else return false; }); $('#submit_third').click(function(){ $('#progress_text').html('100% Выполнено'); $('#progress').css('width','339px'); var fields = new Array( $('#username').val(), $('#password').val(), $('#email').val(), $('#firstname').val() + ' ' + $('#lastname').val(), $('#city').val(), $('#country').val(), $('#vocabulary_key').val(), $('#translate_key').val() ); var tr = $('#fourth_step tr'); tr.each(function(){ $(this).children('td:nth-child(2)').html(fields[$(this).index()]); }); $('#third_step').slideUp(200, "swing"); $('#fourth_step').slideDown(400, "swing"); }); $('#submit_fourth').click(function(){ let data = { user_name: $('#username').val(), password: $('#<PASSWORD>').val(), email: $('#email').val(), first_name: $('#firstname').val(), last_name: $('#lastname').val(), city: $('#city').val(), country: $('#country').val(), vocabulary_key: $('#vocabulary_key').val(), translate_key: $('#translate_key').val() }; let xhttp = new XMLHttpRequest(); xhttp.open('POST', sign_up_url, true); xhttp.setRequestHeader("Content-Type", "application/json"); xhttp.onload = function(){ console.log('sent to server.'); let customer_id = JSON.parse(xhttp.responseText).customer_id; let token = JSON.parse(xhttp.responseText).token; let token_expired_date = JSON.parse(xhttp.responseText).token_expired_date; let domain = window.location.href.split("/")[2]; document.cookie = "customer_id=" + customer_id + "; path=/; domain=" + domain + "; expires=" + cookie_expired_date.toUTCString(); document.cookie = "token=" + token + "; path=/; domain=" + domain + "; expires=" + cookie_expired_date.toUTCString(); document.cookie = "token_expired_date=" + token_expired_date + "; path=/; domain=" + domain + "; expires=" + cookie_expired_date.toUTCString(); document.cookie = "city=" + $('#city').val() + "; path=/; domain=" + domain + "; expires=" + cookie_expired_date.toUTCString(); document.cookie = "country=" + $('#country').val() + "; path=/; domain=" + domain + "; expires=" + cookie_expired_date.toUTCString(); document.cookie = "vocabulary_key=" + $('#vocabulary_key').val() + "; path=/; domain=" + domain + "; expires=" + cookie_expired_date.toUTCString(); document.cookie = "translate_key=" + $('#translate_key').val() + "; path=/; domain=" + domain + "; expires=" + cookie_expired_date.toUTCString(); window.location.pathname = "/home/home.html"; } xhttp.send(JSON.stringify(data)); }); });<file_sep>function randomString (length, chars) { /* Generate random string with adjusted length of acceptable chars(input parameter) using crypto. */ const crypto = require('crypto'); if (!chars) { throw new Error('Argument \'chars\' is undefined'); } let charsLength = chars.length; if (charsLength > 256) { throw new Error('Argument \'chars\' should not have more than 256 characters' + ', otherwise unpredictability will be broken'); } let randomBytes = crypto.randomBytes(length); let result = new Array(length); let cursor = 0; for (var i = 0; i < length; i++) { cursor += randomBytes[i]; result[i] = chars[cursor % charsLength]; } return result.join(''); } module.exports = { randomAsciiString : function(length) { return randomString(length,'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'); } }<file_sep>// local and remote urls var backend_url = "https://lanlearn.azurewebsites.net/"; //var backend_url = "https://languagelearn.azurewebsites.net/"; //var backend_url = "http://localhost:7071/"; var sign_in_url = backend_url + 'sign_in'; var sign_up_url = backend_url + 'sign_up'; var sign_up_get_user_names_url = backend_url + "sign_up_get_user_names"; var personal_area_en_ru_url = backend_url + 'personal_area_en_ru'; var personal_area_en_ru_guessed_url = backend_url + 'personal_area_en_ru_guessed'; var vocabulary_set_translation_url = backend_url + "vocabulary_set_translation"; var vocabulary_get_translation_url = backend_url + "vocabulary_get_translation"; var check_url = backend_url + "check_get_translations"; var check_update_translations_url = backend_url + 'check_update_translations';<file_sep>module.exports = async function (context, req) { const fs = require('fs'); const ini = require('ini'); const config = ini.parse(fs.readFileSync('./common/private/db_connection.ini', 'utf-8')); let token = req.body.token; let customer_id = req.body.customer_id; const pg = require('pg'); const client = new pg.Client({ user: config.database.USER, host: config.database.HOST, database: config.database.database, password: <PASSWORD>, port: config.database.PORT, ssl: false }); await client.connect() const token_res = await client.query(` select token, token_expired_date from customer where customer_id=$1`, [customer_id]) let status; if ((token === undefined) || (customer_id < 1)) status = "4" else if (token_res.rowCount === 0) status = "2" else if ((token_res.rows[0].token != token)&&(Date.parse(token_res.rows[0].token_expired_date) < Date.now())) status = "1" else status = "0" const res = await client.query(` select en, ru from en_ru where customer_id=$1 union select en, ru from en_ru_guessed where customer_id=$1`, [customer_id]) client.end() console.log("Get translation"); context.res = { status: 200, body: { status: status, rows: res.rows }, headers: { 'Content-Type': 'application/json' } } }<file_sep>const customer_id = getCookie("customer_id"); if (customer_id === undefined) window.location.pathname = "/sign_up/sign_up.html"; const token = getCookie("token"); if (token === undefined) window.location.pathname = "/sign_in/sign_in.html"; const token_expired_date = getCookie("token_expired_date"); if (token_expired_date === undefined) window.location.pathname = "/sign_in/sign_in.html"; else if (Date.parse(token_expired_date) < Date.now()) window.location.pathname = "/sign_in/sign_in.html"; var next_phrase; var next_translations; function load_phrase_translations(last_phrase){ /* Load new phrase and translations from backend */ var xhttp = new XMLHttpRequest(); xhttp.open('POST', check_url, false); xhttp.setRequestHeader('Content-Type', 'application/json'); var requestText = { customer_id: customer_id, token: token, last_phrase:last_phrase } xhttp.send(JSON.stringify(requestText)); console.log("Got phrase and translations:" + xhttp.responseText); switch (JSON.parse(xhttp.responseText).status){ case "0": next_phrase = JSON.parse(xhttp.responseText).phrase; next_translations = JSON.parse(xhttp.responseText).translations; isExistTranslations = true; break; case "1": window.location.pathname = "/sign_in/sign_in.html"; break; case "2": window.location.pathname = "/sign_up/sign_up.html"; break; case "3": isExistTranslations = false; break; default: console.log("Uncorrcet status"); } } function set_phrase_translations(){ /* Show translations */ document.getElementById("phrase").innerText = next_phrase; var translations_container = document.getElementById("translations_container"); while (translations_container.childNodes.length > 0) translations_container.removeChild(translations_container.childNodes[0]); for (i=0; i<next_translations.length; i++){ var translation = document.createElement('div'); translation.setAttribute('class', 'translation'); translation.innerHTML = next_translations[i]; translations_container.appendChild(translation); } console.log("Set phrase and show translations"); } var isExistTranslations = false;<file_sep>function noTranslations(){ let status_container = document.getElementById("status_container"); document.getElementById("main_container").outerHTML = ""; status_container.style.backgroundColor = empty_color; status_container.style.position = "relative"; status_container.style.top = "-16px"; //todo: document.getElementById("status").innerText = "Your vocabulary is empty...\nGood job! Let's learn something new."; status_container.style.visibility = "visible"; status_container.style.opacity = 1; }<file_sep>function get_selected_transaltions(){ /* Get translations that were seslected and are not in database and add to inner translations array (database_translations) */ let phrase = document.getElementById('input_area').value; let translations = []; let all_translations = document.getElementsByClassName("translation"); let flug; let database_translations_length = database_translations.length; Array.prototype.filter.call(all_translations, function(element){ if (element.style.color === selected_text_color) { flug = false; if (database_translations != undefined){ for (i=0; i<database_translations_length; i++){ if ((database_translations[i].ru === element.innerText)&&(database_translations[i].en === phrase)) flug = true; } } if (flug) flug = false; else { translations.push(element.innerText); database_translations.push({en:phrase, ru:element.innerText}); } } }); return translations; } function vocabulary_send_translation() { /* send translations to backend */ let send_button = document.getElementById("send_button"); document.getElementById('input_area').disabled = true; send_button.setAttribute('class', 'btn btn-default ld-ext-right running'); let phrase = document.getElementById('input_area').value; let translations = get_selected_transaltions(); let data = { customer_id: getCookie("customer_id"), token: getCookie("token"), phrase: phrase, translations: translations } let xhttp = new XMLHttpRequest(); xhttp.open('POST', vocabulary_set_translation_url, true); xhttp.setRequestHeader('Content-Type', 'application/json'); xhttp.onload = function () { console.log("sent phrase and translation"); switch (JSON.parse(xhttp.responseText).status){ case "1": break; case "2": window.location.pathname = "/sign_in/sign_in.html"; break; } document.getElementById('input_area').disabled = false; send_button.setAttribute('class', 'btn btn-default ld-ext-right nothing'); document.getElementById('input_area').value = ""; document.getElementById('input_area').focus(); }; xhttp.send(JSON.stringify(data)); }<file_sep>const sign_up = require('../sign_up/index'); const sample = require('../tests/sample'); const remove = require('../tests/remove_customer_user_name'); const check_get_translations = require('./index'); const constants = require('../common/constants'); const generateToken = require('../common/generateToken'); test('vocabulary is empty (check_get_translations should return 3)', async () => { let user_name = generateToken.randomAsciiString(constants.default_length); let context = {log: jest.fn()} let request = { body: sample.customer }; request.body.user_name = user_name; await sign_up(context, request); let customer_id = context.res.body.customer_id; let token = context.res.body.token; let data = {customer_id:customer_id, token:token} request = { body: data }; await check_get_translations(context, request); expect(context.res.body.status).toEqual('3'); remove.remove_customer_user_name(user_name); }, 30000); test("token is uncorrect (expired or don't match). (check_get_translations should return 2)", async () => { let context = {log: jest.fn()} let request = { body: {customer_id:"12", token:"uncorrect token"} }; await check_get_translations(context, request); expect(context.res.body.status).toEqual('2'); }, 30000); test('check_get_translations should return 4', async () => { let context = {log: jest.fn()} let request = { body: {customer_id:"-12", token:"uncorrect token"} }; await check_get_translations(context, request); expect(context.res.body.status).toEqual('4'); }, 30000);<file_sep>This is function app. Tests for each function are in the same folder. tests - there is common functions for tests<br> common - there is common functions for azure functions<br> <file_sep>const sign_up = require('./index'); const sample = require('../tests/sample'); const remove = require('../tests/remove_customer_user_name'); const generateToken = require('../common/generateToken'); const constants = require('../common/constants'); test('correct customer data (sign up should return 0)', async () => { let user_name = generateToken.randomAsciiString(constants.default_length); const context = {log: jest.fn()} const request = { body: sample.customer }; request.body.user_name = user_name; await sign_up(context, request); expect(context.res.body.status).toEqual('0'); remove.remove_customer_user_name(user_name); }, 30000);<file_sep>module.exports.status = { "0" : "success", "1" : "token is uncorrect (expired or don't match)", "2" : "customer not found", "3" : "vocabulary is empty", "4" : "uncorrect data" }<file_sep>const url = require('../url'); describe('home', function () { this.timeout(10000); let page; before (async function () { page = await browser.newPage(); await page.goto(url.home_url); await page.evaluate(() => removeCookie()); }); after (async function () { await page.close(); }); it('should have the correct page title', async function () { expect(await page.title()).to.eql('Lanlearn'); }); it("assert that a div named navbar exists", async () => { let nav_bar = await page.$eval(".nav_bar", el => (el ? true : false)); expect(nav_bar).to.eql(true); }); it("assert that sign_in visible", async () => { await page.waitForSelector('#sign_in'); let sign_in = await page.$eval("#sign_in", el => {return el.style.display}); expect(sign_in).to.eql(""); }); it("assert that sign_up visible", async () => { await page.waitForSelector('#sign_up'); let sign_up = await page.$eval("#sign_up", el => {return el.style.display}); expect(sign_up).to.eql(""); }); it("assert that sign_out invisible", async () => { await page.waitForSelector('#sign_out'); let sign_out = await page.$eval("#sign_out", el => {return el.style.display}); expect(sign_out).to.eql("none"); }); });<file_sep>exports.remove_customer_user_name = function (user_name) { const fs = require('fs'); const ini = require('ini'); let config = ini.parse(fs.readFileSync('./../private/db_connection.ini', 'utf-8')); const pg = require('pg'); const client = new pg.Client({ user: config.database.USER, host: config.database.HOST, database: config.database.database, password: <PASSWORD>, port: config.database.PORT, ssl: false }); client.connect(err => { if (err) { throw err; } else { client.query(` delete from customer where customer_id in( select customer_id from customer where user_name=$1 order by customer_id limit 1)`, [user_name], (err, res) => { if (err) throw err client.end(); return true; }); } }); }<file_sep>module.exports = function (context, req) { /* sign in page check existense of customer with that user_name and password_hash if exist: update token else: return status 2 */ const fs = require('fs'); const ini = require('ini'); const generateHash = require("../common/generateHash"); const generateToken = require("../common/generateToken"); const config = ini.parse(fs.readFileSync('./common/private/db_connection.ini', 'utf-8')); let user_name = req.body.user_name; let password = <PASSWORD>; let password_hash = generateHash.getHash(password, user_name); const pg = require('pg'); const client = new pg.Client({ user: config.database.USER, host: config.database.HOST, database: config.database.database, password: <PASSWORD>, port: config.database.PORT, ssl: false }); client.connect(err => { if (err) throw err; else { client.query(` select customer_id, password_hash from customer where user_name=$1 and password_hash=$2`, [user_name, password_hash], (err, res) => { if (err) throw err if (res.rowCount > 0) { console.log("select customer"); let customer_id = res.rows[0].customer_id; let token = generateToken.randomAsciiString(300); let token_expired_date = (new Date(Date.now() + 60*24*60*60*1000)).toUTCString(); client.query(` update customer set token=$1, token_expired_date=$2 where customer_id=$3`, [token, token_expired_date, customer_id], (err, res) => { // 60 days if (err) throw err console.log("insert token"); client.end(); context.res = { status: 200, body: { status: "0", message: "success", customer_id: customer_id, token: token, token_expired_date: token_expired_date }, headers: { 'Content-Type': 'application/json' } } context.done(); }); }else{ context.res = { status: 200, body: { status: "2", message: "customer not found" }, headers: { 'Content-Type': 'application/json' } } context.done(); } }); } }); }<file_sep>psycopg2==2.7.6.1 configparser==3.5.0 <file_sep>module.exports = async function (client, token, customer_id){ let res = await client.query(` select token, token_expired_date, max_guessed_number from customer where customer_id=$1`, [customer_id]) if ((token === undefined) || (customer_id < 1)) return 4 else if (res.rowCount === 0) return 2 else if ((res.rows[0].token != token)&&(Date.parse(res.rows[0].token_expired_date) < Date.now())) return 1 else return 0 }<file_sep>This is a static content of site <file_sep>module.exports = function (context, req) { var fs = require('fs'); var ini = require('ini'); const config = ini.parse(fs.readFileSync('./common/private/db_connection.ini', 'utf-8')); var customer_id = req.body.customer_id; let token = req.body.token; const pg = require('pg'); const client = new pg.Client({ user: config.database.USER, host: config.database.HOST, database: config.database.database, password: <PASSWORD>, port: config.database.PORT, ssl: false }); client.connect(err => { if (err) throw err; client.query(` select token, token_expired_date from customer where customer_id=$1`, [customer_id], (err, res) =>{ if (err) throw err if (res.rowCount === 0){ console.log("customer not found"); context.res = { status: 200, body: { status: "2", message: "customer not found" }, headers: { 'Content-Type': 'application/json' } } client.end(); context.done(); } // uncorrect token else if ((res.rows[0].token != token)&&(Date.parse(res.rows[0].token_expired_date) < Date.now())){ console.log("token is uncorrect"); context.res = { status: 200, body: { status: "1", message: "token is uncorrect or expired" }, headers: { 'Content-Type': 'application/json' } } client.end(); context.done(); }else{ console.log("token is correct"); client.query(` select en, ru, guessed_number, attempts_number, last_attempt_date from en_ru where customer_id=$1`, [customer_id], (err, res) => { if (err) throw err console.log("select translation"); client.end(); if (res.rowCount > 0){ context.res = { status: 200, body: { status: "0", rows: res.rows // send json }, headers: { 'Content-Type': 'application/json' } } context.done(); }else{ context.res = { status: 200, body: { status: "3", message: "vocabulary is empty" }, headers: { 'Content-Type': 'application/json' } } context.done(); } }); } }); }); }
affba9ae1b3c74daa6bbcd5860460a8e487359a6
[ "Markdown", "JavaScript", "Python", "Text", "Shell" ]
44
Markdown
DavydovDmitry/lanlearn
db1bc4b88e56d23f226cbdefd1e02e8756f15d1a
f62bcab446dad6bce8fdfd898428a74452aee6e0
refs/heads/main
<repo_name>anarkigotic/test<file_sep>/src/app/services/pictures.service.ts import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class PicturesService { private url ='https://rickandmortyapi.com/api/character'; constructor(private http: HttpClient) { } getPictures(){ return this.http.get(this.url); } } <file_sep>/src/app/components/offer/offer.component.ts import { Component, DoCheck, OnInit , EventEmitter} from '@angular/core'; import { Oferta , productOfferingPrices, characteristics } from '../../interfaces/ofertas' import * as ofertas from '../../..//assets/ofertas.json'; import { FormControl, FormGroup } from '@angular/forms'; @Component({ selector: 'app-offer', templateUrl: './offer.component.html', styleUrls: ['./offer.component.scss'] }) export class OfferComponent implements OnInit, DoCheck { offert: any = ofertas; listOffert: [Oferta]; opcionSeleccionado: Oferta; dataForm: FormGroup characteristics : characteristics; productOfferingPrices : productOfferingPrices; id : string; name : string; send: EventEmitter<any> = new EventEmitter<any>(); constructor() { this.listOffert = this.offert.default; this.dataForm = new FormGroup({ oferta: new FormControl(null) }); } ngOnInit(): void { console.log(this.characteristics); } ngDoCheck() { if(this.dataForm.get('oferta').value){ this.characteristics = this.dataForm.get('oferta').value.versions[0].characteristics; this.productOfferingPrices = this.dataForm.get('oferta').value.versions[0].productOfferingPrices; this.id = this.dataForm.get('oferta').value.versions[0].id; this.name = this.dataForm.get('oferta').value.versions[0].name; } } } <file_sep>/src/app/interfaces/ofertas.ts export interface Oferta { versions: [version]; id: string; href: string } interface version { characteristics: [characteristics]; productOfferingPrices: [productOfferingPrices]; name: string; id: string; } export interface characteristics { versions: [versions]; id:string } interface versions { validFor: { startDateTime: Date }, valueType: string; name: string; id: string; type: string characteristicValues: [characteristicValues]; properties : [properties] } interface characteristicValues { "displayValue": string, "isDefault": boolean, "validFor": { "startDateTime": Date "valueType": string, "value": string } } interface properties { "isSelected": boolean, "value": string } export interface productOfferingPrices { versions : [productOfferingPricesversions]; id : string } interface productOfferingPricesversions { displayValue : string validFor: { startDateTime: Date }, valueType: string; name: string; id: string; valueTypeSpecification: { "id": string }, type: string value : string properties : [properties] }<file_sep>/src/app/components/prices/prices.component.ts import { Component, DoCheck, Input } from '@angular/core'; import { productOfferingPrices } from 'src/app/interfaces/ofertas'; import { isArray } from 'util'; @Component({ selector: 'app-prices', templateUrl: './prices.component.html', styleUrls: ['./prices.component.scss'] }) export class PricesComponent implements DoCheck { @Input() price: any; ngDoCheck(): void { if (isArray(this.price)) { this.price = this.price.map(ele => { return { "name": ele.id, "monto": ele.versions[0].price.amount } }) } } } <file_sep>/src/app/components/home/home.component.ts import { Component, OnInit } from '@angular/core'; import { PicturesService } from 'src/app/services/pictures.service'; import { NgbModalConfig, NgbModal } from '@ng-bootstrap/ng-bootstrap'; @Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.component.scss'] }) export class HomeComponent implements OnInit { title = 'picture'; pictures: any = []; totalRecords: Number; page: Number = 1; infoPicture: any = { name: '', image: '', episode: 0 } constructor(private pictureService: PicturesService, config: NgbModalConfig, private modalService: NgbModal) { config.backdrop = 'static'; config.keyboard = false; } open(content, item) { this.infoPicture.name = item.name; this.infoPicture.episode = item.episode; this.infoPicture.image = item.image; this.modalService.open(content); } ngOnInit() { this.pictureService.getPictures().subscribe(data => { if (data['results']) { this.pictures = data['results']; this.totalRecords = this.pictures.length; } }) } handlePageChange(data:any){ } } <file_sep>/src/app/components/characteristics/characteristics.component.ts import { Component, DoCheck, Input } from '@angular/core'; import { characteristics } from 'src/app/interfaces/ofertas'; @Component({ selector: 'app-characteristics', templateUrl: './characteristics.component.html', styleUrls: ['./characteristics.component.scss'] }) export class CharacteristicsComponent { @Input() charac : characteristics; }
f8ef44c6c47847eb84ee4183f3437d05d8e31539
[ "TypeScript" ]
6
TypeScript
anarkigotic/test
6688e189bddf304356e3262114d3d28ec72b6eb0
2fdc30e0c093f70a5c437f02a7c55283bdccb0b1
refs/heads/master
<repo_name>destinyd/art-demo<file_sep>/README.md Android art-demo ============ art-demo apk 使用说明 --------------------- 请运行**art-demo-samples** module 依赖库 --------------------- * [destinyd/android-archetypes][android-archetypes] [android-archetypes]: https://github.com/destinyd/android-archetypes <file_sep>/art-demo-samples/src/com/mindpin/art_demo/samples/views/adapter/CoursesAdapter.java package com.mindpin.art_demo.samples.views.adapter; import android.app.Activity; import android.content.Intent; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.widget.RelativeLayout; import com.github.kevinsawicki.wishlist.SingleTypeAdapter; import com.mindpin.art_demo.samples.Constants; import com.mindpin.art_demo.samples.R; import com.mindpin.art_demo.samples.models.interfaces.ICourse; import com.mindpin.art_demo.samples.views.ChaptersActivity; import com.nostra13.universalimageloader.core.ImageLoader; import java.util.List; /** * Created by dd on 14-9-18. */ public class CoursesAdapter extends SingleTypeAdapter<ICourse> implements View.OnClickListener { private final List<ICourse> courses; private final Activity activity; public CoursesAdapter(Activity activity, final List<ICourse> items) { super(activity, R.layout.courses_list_item); this.activity = activity; courses = items; setItems(courses); } @Override protected int[] getChildViewIds() { return new int[]{ R.id.iv_cover, R.id.course_name, R.id.course_state, R.id.rl_course }; } @Override protected void update(int position, ICourse item) { ImageLoader.getInstance().displayImage(item.get_cover(), imageView(0)); setText(1, item.get_title()); setText(2, item.get_state()); // setText(2, String.format(Constants.Format.COURSE_DESC, item.get_total())); // update_btn_action(item); } // private void update_btn_action(ICourse item) { // if (Order.coursestatus.pending == item.get_status()) { // setText(3, "支付"); // getView(3, Button.class).setVisibility(View.VISIBLE); // } else if (Order.coursestatus.took_away == item.get_status()) { // setText(3, "收货"); // getView(3, Button.class).setVisibility(View.VISIBLE); // } else { // getView(3, Button.class).setVisibility(View.INVISIBLE); // } // } @Override public void onClick(View v) { // Integer position = (Integer) v.getTag(); // ICourse order = getItem(position); Log.d("onclick", v.toString()); switch (v.getId()) { // case R.id.btn_action: // action_for_order_status(order); // break; case R.id.rl_course: // go_to_course(order); go_to_course(); break; } } private void go_to_course(){ //{ICourse order) { Log.d("CoursesAdapter", "go to course"); Intent intent = new Intent(activity, ChaptersActivity.class); activity.startActivityForResult(intent, Constants.Request.COURSE); } // @Override public View getView(int position, View convertView, ViewGroup parent) { View view = super.getView(position, convertView, parent); bind_views(position); return view; } private void bind_views(int position) { RelativeLayout relativeLayout = getView(3, RelativeLayout.class); relativeLayout.setTag(position); relativeLayout.setOnClickListener(this); } } <file_sep>/art-demo-samples/src/com/mindpin/art_demo/samples/views/TakePhotoActivity.java package com.mindpin.art_demo.samples.views; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.graphics.*; import android.graphics.Bitmap.CompressFormat; import android.hardware.Camera; import android.hardware.Camera.*; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.util.DisplayMetrics; import android.util.Log; import android.view.*; import android.view.View.OnTouchListener; import android.widget.Button; import android.widget.FrameLayout; import android.widget.Toast; import com.mindpin.art_demo.samples.Constants; import com.mindpin.art_demo.samples.R; import java.io.*; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; @SuppressWarnings("deprecation") public class TakePhotoActivity extends Activity {// implements OnTouchListener { private static final String TAG = "TakePhotoActivity"; private Button take_photo_button; private SurfaceHolder mHolder; private String path; private static Camera mCamera; public File photoFile; public Handler mHandler = new Handler(); private CameraPreview mPreview; private FrameLayout preview; int displayRotation; int picRotate = 0; private DrawCaptureRect mDraw; private int width = 0; private int height = 0; private boolean isfocusing = false; private boolean isfocuseed = false; private int x = 0; private int y = 0; private int draw_width, draw_height; private int fix_top; private int mid_x, mid_y; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.take_photo_layout); //旋转监视器 new OrientationListener(TakePhotoActivity.this).enable(); // CameraPreview 重写 SurfaceView mPreview = new CameraPreview(this, mCamera); preview = (FrameLayout) findViewById(R.id.camera_preview); // preview.setOnTouchListener(this); // 将SurfaceView 添加到 FrameLayout 下 preview.addView(mPreview); init(); // DrawCaptureRect 重写 View mDraw = new DrawCaptureRect(TakePhotoActivity.this, width / 2 - draw_width / 2, height / 2 - draw_height / 2 + fix_top, draw_width, draw_height, getResources().getColor(R.color.red)); preview.addView(mDraw); take_photo_button = (Button) findViewById(R.id.take_photo_button); take_photo_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // 已经成功对焦 // if (isfocuseed) { mCamera.takePicture(shutterCallback, null, mPicture); isfocusing = false; isfocuseed = false; // } else if (isfocusing) { // Toast.makeText(TakePhotoActivity.this, "正在聚焦,请稍等", Toast.LENGTH_SHORT).show(); // } else { // Toast.makeText(TakePhotoActivity.this, "请触摸屏幕对焦后再拍照", Toast.LENGTH_SHORT).show(); // } } }); } // 2015-10-12取消变焦,修复bug private void focus() { // 自动聚焦 // isfocusing = true; // Rect focusRect = calculateTapArea(mid_x, mid_y, 1f); // Rect meteringRect = calculateTapArea(mid_x, mid_y, 1.5f); // Parameters parameters = mCamera.getParameters(); // List<String> focusModes = parameters.getSupportedFocusModes(); // System.out.println("支持的变焦模式" + focusModes); // parameters.setFocusMode(Parameters.FOCUS_MODE_AUTO); // if (parameters.getMaxNumFocusAreas() > 0) { // List<Area> focusAreas = new ArrayList<Area>(); // focusAreas.add(new Area(focusRect, 600)); // parameters.setFocusAreas(focusAreas); // } // if (parameters.getMaxNumMeteringAreas() > 0) { // List<Area> meteringAreas = new ArrayList<Area>(); // meteringAreas.add(new Area(meteringRect, 1000)); // parameters.setMeteringAreas(meteringAreas); // } // mCamera.cancelAutoFocus(); // mCamera.setParameters(parameters); // mCamera.autoFocus(new AutoFocusCallback() { // @Override // public void onAutoFocus(boolean success, Camera camera) { // Log.d(TAG, "onAutoFocus success:" + success); // // 对焦成功 // if (success) { // mDraw = new DrawCaptureRect(TakePhotoActivity.this, mid_x, mid_y, draw_width, draw_height, getResources().getColor(R.color.green)); // preview.addView(mDraw); // isfocuseed = true; // isfocusing = false; // } else { // mDraw = new DrawCaptureRect(TakePhotoActivity.this, mid_x, mid_y, draw_width, draw_height, getResources().getColor(R.color.red)); // preview.addView(mDraw); // isfocuseed = false; // isfocusing = true; // } // } // }); } private void init() { DisplayMetrics dm = getResources().getDisplayMetrics(); width = dm.widthPixels; height = dm.heightPixels; draw_width = width - 200; draw_height = (int) (draw_width * 0.75); fix_top = -200; mid_x = width / 2; mid_y = height / 2 + fix_top; } private Rect calculateTapArea(float x, float y, float coefficient) { float focusAreaSize = 200; int areaSize = Float.valueOf(focusAreaSize * coefficient).intValue(); int centerX = (int) ((x / width) * 2000 - 1000); int centerY = (int) ((y / height) * 2000 - 1000); int left = clamp(centerX - (areaSize / 2), -1000, 1000); int top = clamp(centerY - (areaSize / 2), -1000, 1000); RectF rectF = new RectF(left, top, left + areaSize, top + areaSize); return new Rect(Math.round(rectF.left), Math.round(rectF.top), Math.round(rectF.right), Math.round(rectF.bottom)); } private int clamp(int x, int min, int max) { if (x > max) { return max; } if (x < min) { return min; } return x; } //快门声音 ShutterCallback shutterCallback = new ShutterCallback() { @Override public void onShutter() { // TODO Auto-generated method stub // mCamera.enableShutterSound(true); } }; public void getCameraInstance() { try { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) { mCamera = Camera.open(0); // i=0 表示后置相机 } else mCamera = Camera.open(); } catch (Exception e) { } } //设置预览参数 public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback { public CameraPreview(Context context, Camera camera) { super(context); mHolder = getHolder(); mHolder.addCallback(this); mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); } public void surfaceCreated(SurfaceHolder holder) { try { mCamera.setPreviewDisplay(holder); mCamera.startPreview(); } catch (IOException e) { Log.d("TakePhoto", "Error setting camera preview: " + e.getMessage()); } } public void surfaceDestroyed(SurfaceHolder holder) { resetCamera(); } public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { if (mHolder.getSurface() == null) { return; } try { mCamera.stopPreview(); } catch (Exception e) { } try { mCamera.setDisplayOrientation(getCameraDisplayOrientation(0)); Camera.Parameters params = mCamera.getParameters(); Size PreviewSize = getBestSupportedSize(params.getSupportedPreviewSizes()); Size PictureSize = getBestSupportedSize(params.getSupportedPictureSizes()); params.setPictureFormat(ImageFormat.JPEG); params.setPreviewSize(PreviewSize.width, PreviewSize.height); params.setPictureSize(PictureSize.width, PictureSize.height); params.setJpegQuality(100); mCamera.setParameters(params); mCamera.setPreviewDisplay(mHolder); mCamera.startPreview(); } catch (Exception e) { resetCamera(); Log.e("takePhoto", "Error starting camera preview: " + e.getMessage()); } } } //获取图片数据 private PictureCallback mPicture = new PictureCallback() { @Override public void onPictureTaken(byte[] data, Camera camera) { // 原a part 1储存,切换 // 得全图,传出 Matrix matrix = new Matrix(); matrix.setRotate(picRotate); Bitmap bitmap = DecodeImageUtils.decodeImage(data, TakePhotoActivity.this, matrix); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_kk-mm-ss");// 转换格式 String picName = sdf.format(new Date()) + ".jpg"; path = getPicPath() + picName; File pictureFile = new File(getPicPath()); if (!pictureFile.exists()) { pictureFile.mkdirs(); } pictureFile = new File(path); // 原b 储存,切换 // 获取截屏 // View view = TakePhotoActivity.this.getWindow().getDecorView(); // view.setDrawingCacheEnabled(true); // view.buildDrawingCache(); // // // 获取状态栏高度 // Rect frame = new Rect(); // TakePhotoActivity.this.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame); // int statusBarHeight = frame.top; // 计算 // int bitmap_2_preview_fit_width = (int) (preview.getWidth() * (bitmap.getHeight() / (float)preview.getHeight() )); Bitmap scaleBitmap = Bitmap.createScaledBitmap(bitmap, preview.getHeight(), preview.getHeight(), false ); int left_fix = Math.abs(preview.getHeight() - mDraw.getMwidth()) / 2; Bitmap clipBitmap = Bitmap.createBitmap(scaleBitmap, // mDraw.getMleft(), left_fix, mDraw.getMtop(), mDraw.getMwidth(), mDraw.getMheight() ); try { BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(pictureFile)); clipBitmap.compress(CompressFormat.JPEG, 100, bos); bos.flush(); bos.close(); if (bitmap != null || clipBitmap != null) { if (bitmap != null && !bitmap.isRecycled()) { bitmap.recycle(); } if (clipBitmap != null && !clipBitmap.isRecycled()) { clipBitmap.recycle(); } System.gc(); System.out.println("图片资源已回收,控制内存占用"); } camera.stopPreview(); Log.d(TAG, "跳转到裁剪页面"); Log.d(TAG, "imgPath: " + path); Intent intent = new Intent(TakePhotoActivity.this, ResultActivity.class); intent.putExtra(Constants.Extra.IMAGE_PATH, path); startActivity(intent); } catch (FileNotFoundException e) { Log.d("TakePhoto", "File not found: " + e.getMessage()); } catch (IOException e) { Log.d("TakePhoto", "Error accessing file: " + e.getMessage()); } // 原a part 2储存,切换 // try { // BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(pictureFile)); // bitmap.compress(CompressFormat.JPEG, 100, bos); // bos.flush(); // bos.close(); // if (bitmap != null && !bitmap.isRecycled()) { // bitmap.recycle(); // System.gc(); // System.out.println("图片资源已回收,控制内存占用"); // } // camera.stopPreview(); // Log.d(TAG, "跳转到裁剪页面"); // Log.d(TAG, "imgPath: " + path); // Intent intent = new Intent(TakePhotoActivity.this, CutPhotoActivity.class); // intent.putExtra("imgPath", path); // startActivity(intent); // } catch (FileNotFoundException e) { // Log.d("TakePhoto", "File not found: " + e.getMessage()); // } catch (IOException e) { // Log.d("TakePhoto", "Error accessing file: " + e.getMessage()); // } } }; /** * 获取裁剪框内截图 * * @return */ private Bitmap getBitmap() { // 获取截屏 View view = this.getWindow().getDecorView(); view.setDrawingCacheEnabled(true); view.buildDrawingCache(); // 获取状态栏高度 Rect frame = new Rect(); this.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame); int statusBarHeight = frame.top; Bitmap finalBitmap = Bitmap.createBitmap(view.getDrawingCache(), mDraw.getLeft(), mDraw.getTop() + statusBarHeight, mDraw.getWidth(), mDraw.getHeight()); // 释放资源 view.destroyDrawingCache(); return finalBitmap; } private class OrientationListener extends OrientationEventListener { public OrientationListener(Context context) { super(context); } public OrientationListener(Context context, int rate) { super(context, rate); } @Override public void onOrientationChanged(int orientation) { if (orientation == ORIENTATION_UNKNOWN) return; android.hardware.Camera.CameraInfo info = new android.hardware.Camera.CameraInfo(); android.hardware.Camera.getCameraInfo(0, info); orientation = (orientation + 45) / 90 * 90; int rotation = 0; if (info.facing == CameraInfo.CAMERA_FACING_FRONT) { rotation = (info.orientation - orientation + 360) % 360; } else { // back-facing camera rotation = (info.orientation + orientation) % 360; } picRotate = rotation; } } public int getCameraDisplayOrientation(int cameraId) { android.hardware.Camera.CameraInfo info = new android.hardware.Camera.CameraInfo(); android.hardware.Camera.getCameraInfo(cameraId, info); int rotation = getWindowManager().getDefaultDisplay().getRotation(); int degrees = 0; switch (rotation) { case Surface.ROTATION_0: degrees = 0; break; case Surface.ROTATION_90: degrees = 90; break; case Surface.ROTATION_180: degrees = 180; break; case Surface.ROTATION_270: degrees = 270; break; } int result; if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) { result = (info.orientation + degrees) % 360; result = (360 - result) % 360; // compensate the mirror } else { // back-facing result = (info.orientation - degrees + 360) % 360; } return result; } private Size getBestSupportedSize(List<Size> sizes) { // 取能适用的最大的SIZE Size largestSize = sizes.get(0); int largestArea = sizes.get(0).height * sizes.get(0).width; for (Size s : sizes) { int area = s.width * s.height; if (area > largestArea) { largestArea = area; largestSize = s; } } return largestSize; } private void resetCamera() { if (mCamera != null) { mCamera.stopPreview(); mCamera.release(); mCamera = null; } } public static String getPicPath() { File defaultDir = Environment.getExternalStorageDirectory(); String path = defaultDir.getAbsolutePath() + File.separator + "DXM" + File.separator; return path; } @Override protected void onResume() { // TODO Auto-generated method stub super.onResume(); resetCamera(); getCameraInstance(); // focus(); } @Override protected void onRestart() { // TODO Auto-generated method stub super.onRestart(); resetCamera(); getCameraInstance(); // focus(); } @Override protected void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); resetCamera(); } } <file_sep>/art-demo-samples/src/com/mindpin/art_demo/samples/ArtDemoApplication.java package com.mindpin.art_demo.samples; import android.app.Application; import com.nostra13.universalimageloader.cache.disc.naming.HashCodeFileNameGenerator; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.ImageLoaderConfiguration; /** * Created by DD on 15/9/22. */ public class ArtDemoApplication extends Application { @Override public void onCreate() { super.onCreate(); init_image_config(); } public void init_image_config() { DisplayImageOptions options; ImageLoaderConfiguration config; options = new DisplayImageOptions.Builder() .cacheInMemory(true) .cacheOnDisk(true) .build(); config = new ImageLoaderConfiguration.Builder(getApplicationContext()) // 设置缓存图片的宽度跟高度 .memoryCacheExtraOptions(100, 100) .diskCacheExtraOptions(100, 100, null) // 通过 LruMemoryCache 实现缓存机制 // .memoryCache(new LruMemoryCache(2 * 1024 * 1024)) // .memoryCacheSize(2 * 1024 * 1024) // 限制缓存文件数量百分比 .memoryCacheSizePercentage(13) .diskCacheSize(50 * 1024 * 1024) // 硬盘缓存文件数量 .diskCacheFileCount(100) .diskCacheFileNameGenerator(new HashCodeFileNameGenerator()) .defaultDisplayImageOptions(options) .build(); ImageLoader.getInstance().init(config); } } <file_sep>/art-demo-samples/src/com/mindpin/art_demo/samples/views/DrawCaptureRect.java package com.mindpin.art_demo.samples.views; import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.PorterDuff.Mode; import android.graphics.PorterDuffXfermode; import android.view.View; public class DrawCaptureRect extends View { private int mcolorfill; private int mleft, mtop, mwidth, mheight; public DrawCaptureRect(Context context,int left, int top,int width, int height, int colorfill) { super(context); // TODO Auto-generated constructor stub this.mcolorfill = colorfill; this.mleft = left; this.mtop = top; this.mwidth = width; this.mheight = height; } @Override protected void onDraw(Canvas canvas) { Paint p = new Paint(); //���� p.setXfermode(new PorterDuffXfermode(Mode.CLEAR)); canvas.drawPaint(p); p.setXfermode(new PorterDuffXfermode(Mode.SRC)); Paint mpaint = new Paint(); mpaint.setColor(mcolorfill); mpaint.setStyle(Paint.Style.FILL); mpaint.setStrokeWidth(2.0f); canvas.drawLine(mleft, mtop, mleft+mwidth, mtop, mpaint); canvas.drawLine(mleft+mwidth, mtop, mleft+mwidth, mtop+mheight, mpaint); canvas.drawLine(mleft, mtop, mleft, mtop+mheight, mpaint); canvas.drawLine(mleft, mtop+mheight, mleft+mwidth, mtop+mheight, mpaint); super.onDraw(canvas); } public int getMleft() { return mleft; } public int getMtop() { return mtop; } public int getMwidth() { return mwidth; } public int getMheight() { return mheight; } } <file_sep>/art-demo-samples/src/com/mindpin/art_demo/samples/views/CoursesActivity.java package com.mindpin.art_demo.samples.views; import android.app.Activity; import android.app.ListActivity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.ListView; import android.widget.SimpleAdapter; import com.mindpin.android.loadingview.LoadingView; import com.mindpin.art_demo.samples.R; import com.mindpin.art_demo.samples.models.demo.Course; import com.mindpin.art_demo.samples.models.interfaces.ICourse; import com.mindpin.art_demo.samples.utils.DemoAsyncTask; import com.mindpin.art_demo.samples.views.adapter.CoursesAdapter; import roboguice.activity.RoboActivity; import roboguice.inject.InjectView; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class CoursesActivity extends RoboActivity { @InjectView(R.id.lv_courses) ListView lv_courses; @InjectView(R.id.loading_view) LoadingView loading_view; private List<ICourse> courses = new ArrayList<ICourse>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.courses); get_data(); // setListAdapter( // new SimpleAdapter( // this, getData(), android.R.layout.simple_list_item_1, new String[]{"title"}, // new int[]{android.R.id.text1} // ) // ); // getListView().setScrollbarFadingEnabled(false); } protected void get_data() { new DemoAsyncTask<Void>(this) { @Override protected void onPreExecute() throws Exception { loading_view.show(); } @Override public Void call() throws Exception { // order = DataProvider.deliveryman_order(order_id); Thread.sleep(2000); Course course = new Course(); course.title = "1. 用几何体画身边小物品"; course.cover = "http://www.mindpin.com/mockups/kc/art-camp_20150920/images/%E8%AF%BE%E7%A8%8B%E5%88%97%E8%A1%A8/u37.png"; course.state = "状态1"; courses.add(course); course = new Course(); course.title = "2. 素描简单的小物品"; course.cover = "http://www.mindpin.com/mockups/kc/art-camp_20150920/images/%E8%AF%BE%E7%A8%8B%E5%88%97%E8%A1%A8/u83.png"; course.state = "状态2"; courses.add(course); course = new Course(); course.title = "3. 充满活力的动物和植物"; course.cover = "http://www.mindpin.com/mockups/kc/art-camp_20150920/images/%E8%AF%BE%E7%A8%8B%E5%88%97%E8%A1%A8/u85.png"; course.state = "状态3"; courses.add(course); course = new Course(); course.title = "4. 可以装进画框的素描"; course.cover = "http://www.mindpin.com/mockups/kc/art-camp_20150920/images/%E8%AF%BE%E7%A8%8B%E5%88%97%E8%A1%A8/u87.png"; course.state = "状态4"; courses.add(course); return null; } @Override protected void onSuccess(Void aVoid) throws Exception { build_views(); } @Override protected void onFinally() throws RuntimeException { super.onFinally(); loading_view.hide(); } }.execute(); } private void build_views() { final CoursesAdapter adapter = new CoursesAdapter(this, courses); lv_courses.setAdapter(adapter); } // @SuppressWarnings("unchecked") // @Override // protected void onListItemClick(ListView l, View v, int position, long id) { // Map<String, Object> map = (Map<String, Object>) l.getItemAtPosition(position); // Log.d("title", (String) map.get("title")); // Log.d("id", (String) map.get("id")); //// Intent intent = new Intent(this, (Class<? extends Activity>) map.get("activity")); //// startActivity(intent); // } // private List<? extends Map<String, ?>> getData() { // List<Map<String, Object>> data = new ArrayList<Map<String, Object>>(); // addItem(data, "用几何体画身边小物品", "1"); // addItem(data, "素描简单的小物品", "2"); // addItem(data, "充满活力的动物和植物", "3"); // addItem(data, "可以装进画框的素描", "4"); //// addItem(data, "other", OtherActivity.class); // // return data; // } // // private void addItem(List<Map<String, Object>> data, String title, // String id) { // Map<String, Object> map = new HashMap<String, Object>(); // map.put("title", data.size() + ". " + title); // map.put("id", id); // data.add(map); // } }
60472b8ac7624e744326555f3e53d71db637bf62
[ "Markdown", "Java" ]
6
Markdown
destinyd/art-demo
343645fc7091fd452a298961e983462b8efd41dc
97aeffab28bf0c791abb1c18329f4a65c445f1f1
refs/heads/master
<file_sep># maze-generator A simple C++ program that creates procedurally generated mazes based on user given parameters ![Example maze](https://github.com/smoothstill/maze-generator/blob/master/MazeGenerator/Example_maze.png?raw=true) <file_sep>#include <iostream> #include <vector> #include <cassert> #include <random> // for std::mt19937 #include <ctime> // for std::time #include <algorithm> #include "lodepng.h" #include <string> std::string intToString(int value) { int multiplier{ 1 }; int num{ 1 }; while (value / (multiplier * 10) >= 1) { multiplier *= 10; ++num; } std::cout << "multiplier: " << multiplier << "\n"; std::cout << "num: " << num << "\n"; int tempVal{}; int tempDiv{}; std::string temp{}; for (int i = 0; i < num; ++i) { tempDiv = value / (multiplier * 10); tempVal = (value - (multiplier * 10 * tempDiv))/ multiplier; std::cout << tempVal << "\n"; multiplier /= 10; temp += (char)(tempVal + 48); } std::cout << temp << "\n"; return temp; } void encodeOneStep(const char* filename, std::vector<unsigned char>& image, unsigned width, unsigned height); std::mt19937 mersenne(static_cast<unsigned int>(std::time(nullptr))); unsigned int getRandomInteger(int min, int max) { //static std::mt19937 mersenne(static_cast<unsigned int>(std::time(nullptr))); std::uniform_int_distribution<> location(min, max); return location(mersenne); } struct Coordinates { int x; int y; }; class Maze { private: int m_quantity; int m_width; int m_height; int m_emptySpace; int m_numOfIsolatedEmptySpaces; float m_loopFactor; std::vector<bool> m_mazeTiles; std::vector<int> m_mazeConnectedEmptySpace; void DecrementEmptySpace() { --m_emptySpace; } public: Maze(int width, int height, float loopFactor, int quantity) : m_width(width), m_height(height), m_emptySpace((width-2)*(height-2)), m_numOfIsolatedEmptySpaces(0), m_loopFactor(loopFactor), m_quantity(quantity) { m_mazeTiles.reserve(height*width * 2); m_mazeConnectedEmptySpace.reserve(height*width*2); for (int i = 1; i <= quantity; ++i) { std::string temp = intToString(i); temp = "maze" + temp + ".png"; m_mazeTiles.clear(); m_mazeConnectedEmptySpace.clear(); m_mazeTiles.resize(height*width); m_mazeConnectedEmptySpace.resize(height*width); DrawRandomWallTilesStage1(); //DrawMazeToPng("maze_phase1.png"); createBorders(); //DrawMazeToPng("maze_phase2.png"); freeEncircledSingleWhiteSpaces(); connectLoneWallTiles(); //DrawMazeToPng("maze_phase3.png"); calculateConnectedEmptySpaces(); connectAllEmptySpace(); //DrawMazeToPng("maze_phase4.png"); addRandomWallTilesStage2(); //DrawMazeToPng("maze_phase5.png"); calculateStartAndExitLocation(); //Draw(); DrawMazeToPng(temp.c_str()); } //createBorders(); } void createBorders() { std::cout << "Creating maze borders...\n"; m_mazeTiles[0] = 1; for (int i = 1; i < m_mazeTiles.size(); ++i) { /*if (i < m_width || i > (m_width * (m_height - 1) - 1)) m_mazeTiles[i] = 1; if (i % m_width == 0) m_mazeTiles[i] = 1; if (i % m_width == 0) if (i > 0) m_mazeTiles[i - 1] = 1; */ if ((i < m_width || i >(m_width * (m_height - 1) - 1)) || (i % m_width == 0)) { m_mazeTiles[i] = 1; m_mazeTiles[i - 1] = 1; } } std::cout << "DONE\n"; } int max(int a, int b) { return (a > b ? a : b); } int tileCoordinate(int x, int y) { if ((x < m_width) && (y < m_height)) { //std::cout << "y = " << y << ", x = " << x << "\n"; //std::cout << "Index: " << (y * m_height + x) << "\n"; return (y * m_width + x); } else { assert(false && "Invalid tile coordinate!"); } return 0; } void DrawWallAtPoint(int x, int y) { m_mazeTiles[tileCoordinate(x, y)] = 1; //std::cout << "drawing wall at (" << x << ", " << y << ")\n"; DecrementEmptySpace(); for (int i = -1; i < 1; ++i) { for (int j = -1; j < 1; ++j) { if (x + i >= 0 && x + i <= m_width - 2 && y + j >= 0 && y + j <= m_height - 2) { bool temp = getRandomInteger(0, 1); if (!(m_mazeTiles[tileCoordinate(x + i + 1, y + j + 1)]) && (m_mazeTiles[tileCoordinate(x + i, y + j + 1)]) && (m_mazeTiles[tileCoordinate(x + i + 1, y + j)]) && !(m_mazeTiles[tileCoordinate(x + i, y + j)])) { if (temp) { //checkValidWallLocation if (validWallLocation(x + i + 1, y + j + 1)) { //draw again //std::cout << "drawing extra wall\n"; DrawWallAtPoint(x + i + 1, y + j + 1); } else if (validWallLocation(x + i, y + j)) { //draw again //std::cout << "drawing extra wall\n"; DrawWallAtPoint(x + i, y + j); } } else { if (validWallLocation(x + i, y + j)) { //draw again //std::cout << "drawing extra wall\n"; DrawWallAtPoint(x + i, y + j); } else if (validWallLocation(x + i + 1, y + j + 1)) { //draw again //std::cout << "drawing extra wall\n"; DrawWallAtPoint(x + i + 1, y + j + 1); } } /* if (checkValidWallLocation(x + i + 1, y + j + 1)) { //draw again std::cout << "drawing extra wall\n"; DrawWallAtPoint(x + i + 1, y + j + 1); } else if (checkValidWallLocation(x + i, y + j)) { //draw again std::cout << "drawing extra wall\n"; DrawWallAtPoint(x + i, y + j); }*/ //else //{ // assert(false && "ERROR: no valid wall locations for wb,bw formation"); //} } else if ((m_mazeTiles[tileCoordinate(x + i + 1, y + j + 1)]) && !(m_mazeTiles[tileCoordinate(x + i, y + j + 1)]) && !(m_mazeTiles[tileCoordinate(x + i + 1, y + j)]) && (m_mazeTiles[tileCoordinate(x + i, y + j)])) { if (temp) { if (validWallLocation(x + i, y + j + 1)) { //draw again //std::cout << "drawing extra wall\n"; DrawWallAtPoint(x + i, y + j + 1); } else if (validWallLocation(x + i + 1, y + j)) { //draw again //std::cout << "drawing extra wall\n"; DrawWallAtPoint(x + i + 1, y + j); } } else { if (validWallLocation(x + i + 1, y + j)) { //draw again //std::cout << "drawing extra wall\n"; DrawWallAtPoint(x + i + 1, y + j); } else if (validWallLocation(x + i, y + j + 1)) { //draw again //std::cout << "drawing extra wall\n"; DrawWallAtPoint(x + i, y + j + 1); } } /* if (checkValidWallLocation(x + i, y + j + 1)) { //draw again std::cout << "drawing extra wall\n"; DrawWallAtPoint(x + i, y + j + 1); } else if (checkValidWallLocation(x + i + 1, y + j)) { //draw again std::cout << "drawing extra wall\n"; DrawWallAtPoint(x + i + 1, y + j); }*/ //else //{ // assert(false && "ERROR: no valid wall locations for wb,bw formation"); //} } } } } } //this function returns true if: //all of blocks of 2x2 area are empty (=0) bool check2x2EmptyOnly(int x, int y) //(x, y) is the upper left coordinate of the 2x2 area { //note that x should be m_width - 1 at max //and y should be m_height - 1 at max assert(!(x == m_width || y == m_height) && "ERROR: coordinate should be one less than maximum."); return (!m_mazeTiles[tileCoordinate(x, y)] && !m_mazeTiles[tileCoordinate(x + 1, y)] && !m_mazeTiles[tileCoordinate(x, y + 1)] && !m_mazeTiles[tileCoordinate(x + 1, y + 1)]); /* if (m_mazeTiles[tileCoordinate(x, y)] == 1) ++numOfWalls; if (m_mazeTiles[tileCoordinate(x + 1, y)] == 1) ++numOfWalls; if (m_mazeTiles[tileCoordinate(x + 1, y + 1)] == 1) ++numOfWalls; if (m_mazeTiles[tileCoordinate(x + 1, y + 1)] == 1) ++numOfWalls; return !(numOfWalls == 0 || numOfWalls == 4); */ } bool checkValidWallLocation(int x, int y) { return ((check2x2LessThan3walls(x - 1, y - 1) && check2x2LessThan3walls(x, y - 1) && check2x2LessThan3walls(x - 1, y) && check2x2LessThan3walls(x, y)) && validWallLocation(x, y)); } bool checkValidWallLocationB(int x, int y) { for (int i = -1; i < 1; ++i) { for (int j = -1; j < 1; ++j) { if (x + i >= 0 && x + i <= m_width - 2 && y + j >= 0 && y + j <= m_height - 2) { if (!(m_mazeTiles[tileCoordinate(x + i + 1, y + j + 1)]) && (m_mazeTiles[tileCoordinate(x + i, y + j + 1)]) && (m_mazeTiles[tileCoordinate(x + i + 1, y + j)]) && !(m_mazeTiles[tileCoordinate(x + i, y + j)])) { return false; } else if ((m_mazeTiles[tileCoordinate(x + i + 1, y + j + 1)]) && !(m_mazeTiles[tileCoordinate(x + i, y + j + 1)]) && !(m_mazeTiles[tileCoordinate(x + i + 1, y + j)]) && (m_mazeTiles[tileCoordinate(x + i, y + j)])) { return false; } } } } return ((check2x2LessThan3walls(x - 1, y - 1) && check2x2LessThan3walls(x, y - 1) && check2x2LessThan3walls(x - 1, y) && check2x2LessThan3walls(x, y))); } bool checkValidWallLocationC(int x, int y) { int numOfWalls{}; for (int i = -1; i < 1; ++i) { for (int j = -1; j < 1; ++j) { numOfWalls = 0; for (int ii = 0; ii < 2; ++ii) { for (int jj = 0; jj < 2; ++jj) { if (m_mazeTiles[tileCoordinate(x + i + ii, y + j + jj)]) ++numOfWalls; } } if (numOfWalls + 1 > 3) return false; } } if (m_mazeTiles[tileCoordinate(x - 1, y - 1)] && !m_mazeTiles[tileCoordinate(x - 1, y)] && !m_mazeTiles[tileCoordinate(x, y - 1)]) return false; if (m_mazeTiles[tileCoordinate(x + 1, y - 1)] && !m_mazeTiles[tileCoordinate(x + 1, y)] && !m_mazeTiles[tileCoordinate(x, y - 1)]) return false; if (m_mazeTiles[tileCoordinate(x - 1, y + 1)] && !m_mazeTiles[tileCoordinate(x - 1, y)] && !m_mazeTiles[tileCoordinate(x, y + 1)]) return false; if (m_mazeTiles[tileCoordinate(x + 1, y + 1)] && !m_mazeTiles[tileCoordinate(x + 1, y)] && !m_mazeTiles[tileCoordinate(x, y + 1)]) return false; return true; } bool check2x2LessThan3walls(int x, int y) { int temp{}; for (int i = 0; i < 2; ++i) { for (int j = 0; j < 2; ++j) { //std::cout << "Does this fail: " << (x + i) << ", " << (y + j) << "?\n"; if ((x + i) >= 0 && (x + i) <= (m_width - 2) && (y + j) >= 0 && (y + j) <= (m_height - 2)) { if (m_mazeTiles[tileCoordinate(x + i, y + j)]) ++temp; } else { //std::cout << "Ignored x: " << (x + i) << ", y: " << (y + j) << ".\n"; } } } return (temp < 3); } //For the first part of adding walls, they must not be added on (x, y) locations where both x and y are (pair + 1) number. bool validWallLocation(int x, int y) { return !(((x + 1) % 2 == 0) && ((y + 1) % 2 == 0)); } void DrawRandomWallTilesStage1() { std::cout << "Adding base wall tiles...\n"; for (int i = 0; i < m_width - 1; ++i) { for (int j = 0; j < m_height - 1; ++j) { if (check2x2EmptyOnly(i, j)) { bool validLocations[2][2]{}; //[y][x] int temp{}; for (int ii = 0; ii < 2; ++ii) { for (int jj = 0; jj < 2; ++jj) { //if (check2x2LessThan3walls(i + ii - 1, j + jj - 1) && check2x2LessThan3walls(i + ii, j + jj - 1) && check2x2LessThan3walls(i + ii - 1, j + jj) && check2x2LessThan3walls(i + ii, j + jj)) //{ if (validWallLocation(i + ii, j + jj)) { validLocations[jj][ii] = 1; ++temp; } //} } } //std::cout << "validWallLocations: " << temp << "\n"; if (temp > 0) { int wallLocation = getRandomInteger(0, temp - 1); //std::cout << "Random number: " << wallLocation << "\n"; temp = 0; for (int ii = 0; ii < 2; ++ii) { for (int jj = 0; jj < 2; ++jj) { if (validLocations[jj][ii]) { if (wallLocation == temp) { //std::cout << "x: " << i + ii << ", y = " << j + jj << "\n"; DrawWallAtPoint(i + ii, j + jj); ii = 2; jj = 2; } else ++temp; } } } //Draw(); } } } } std::cout << "DONE\n"; } //this function will open up // X X X // X X // X X X //type of formations //by removing either top, bottom, left or right wall tile void freeEncircledSingleWhiteSpaces() { std::cout << "Freeing single empty spaces...\n"; for (int i = 1; i < m_width - 1; ++i) { for (int j = 1; j < m_height - 1; ++j) { if (m_mazeTiles[tileCoordinate(i - 1, j - 1)] && m_mazeTiles[tileCoordinate(i, j - 1)] && m_mazeTiles[tileCoordinate(i + 1, j - 1)] && m_mazeTiles[tileCoordinate(i - 1, j)] && m_mazeTiles[tileCoordinate(i + 1, j)] && m_mazeTiles[tileCoordinate(i - 1, j + 1)] && m_mazeTiles[tileCoordinate(i, j + 1)] && m_mazeTiles[tileCoordinate(i + 1, j + 1)]) { //next, choose which block to remove bool tempUpDownOrRightLeft = getRandomInteger(0, 1); bool temp = getRandomInteger(0, 1); if (tempUpDownOrRightLeft) //up down { if (temp) //up { if (j - 1 != 0) { m_mazeTiles[tileCoordinate(i, j - 1)] = 0; } else { m_mazeTiles[tileCoordinate(i, j + 1)] = 0; } } else //down { if (j + 1 != m_height - 1) { m_mazeTiles[tileCoordinate(i, j + 1)] = 0; } else { m_mazeTiles[tileCoordinate(i, j - 1)] = 0; } } } else // right left { if (temp) //right { if (i + 1 != m_width - 1) { m_mazeTiles[tileCoordinate(i + 1, j)] = 0; } else { m_mazeTiles[tileCoordinate(i - 1, j)] = 0; } } else //left { if (i - 1 != 0) { m_mazeTiles[tileCoordinate(i - 1, j)] = 0; } else { m_mazeTiles[tileCoordinate(i + 1, j)] = 0; } } } } } } std::cout << "DONE\n"; } //this function connects // 0 0 0 // 0 X 0 // 0 0 0 //types of formations (where X is wall and 0 is empty space) //to walls next to it. void connectLoneWallTiles() { std::cout << "Connecting lone wall tiles...\n"; for (int i = 2; i < m_width - 2; ++i) { for (int j = 2; j < m_height - 2; ++j) { if (!m_mazeTiles[tileCoordinate(i - 1, j - 1)] && !m_mazeTiles[tileCoordinate(i, j - 1)] && !m_mazeTiles[tileCoordinate(i + 1, j - 1)] && !m_mazeTiles[tileCoordinate(i - 1, j)] && !m_mazeTiles[tileCoordinate(i + 1, j)] && !m_mazeTiles[tileCoordinate(i - 1, j + 1)] && !m_mazeTiles[tileCoordinate(i, j + 1)] && !m_mazeTiles[tileCoordinate(i + 1, j + 1)]) { int randomInt = getRandomInteger(0, 3); if (randomInt == 0) //up { m_mazeTiles[tileCoordinate(i, j - 1)] = 1; if (m_mazeTiles[tileCoordinate(i, j - 2)] == 0) m_mazeTiles[tileCoordinate(i, j - 2)] = 1; } else if (randomInt == 1) //down { m_mazeTiles[tileCoordinate(i, j + 1)] = 1; if (m_mazeTiles[tileCoordinate(i, j + 2)] == 0) m_mazeTiles[tileCoordinate(i, j + 2)] = 1; } else if (randomInt == 2) //right { m_mazeTiles[tileCoordinate(i + 1, j)] = 1; if (m_mazeTiles[tileCoordinate(i + 2, j)] == 0) m_mazeTiles[tileCoordinate(i + 2, j)] = 1; } else if (randomInt == 3) //left { m_mazeTiles[tileCoordinate(i - 1, j)] = 1; if (m_mazeTiles[tileCoordinate(i - 2, j)] == 0) m_mazeTiles[tileCoordinate(i - 2, j)] = 1; } else { assert(false && "ERROR! You shouldn't see this lawl"); } } } } std::cout << "DONE\n"; } //this function will calculate which empty spaces are connected to each other. //every empty space of the maze should be connected with every other empty space! int calculateConnectedEmptySpaces() { m_numOfIsolatedEmptySpaces = 0; m_mazeConnectedEmptySpace.clear(); m_mazeConnectedEmptySpace.resize(m_height*m_width); int target{}; int newTarget{}; int newProgress{}; int currentProgress{}; std::cout << "Calculating isolated empty space regions...\n"; for (int j = 1; j < m_height - 1; ++j) { for (int i = 1; i < m_width - 1; ++i) { newProgress = static_cast<int>(static_cast<float>(100 * tileCoordinate(i, j) / tileCoordinate(m_width - 1, m_height - 1))); if (newProgress > currentProgress) { std::cout << "Calculating isolated empty space regions... (" << newProgress << "%)\n"; currentProgress = newProgress; } if (!m_mazeTiles[tileCoordinate(i, j)]) { if (m_mazeConnectedEmptySpace[tileCoordinate(i - 1, j)] != 0) { m_mazeConnectedEmptySpace[tileCoordinate(i, j)] = m_mazeConnectedEmptySpace[tileCoordinate(i - 1, j)]; if (m_mazeConnectedEmptySpace[tileCoordinate(i, j - 1)] != 0 && m_mazeConnectedEmptySpace[tileCoordinate(i, j)] != m_mazeConnectedEmptySpace[tileCoordinate(i, j - 1)]) { //target = 0; //newTarget = 0; if (m_mazeConnectedEmptySpace[tileCoordinate(i, j)] < m_mazeConnectedEmptySpace[tileCoordinate(i, j - 1)]) { target = m_mazeConnectedEmptySpace[tileCoordinate(i, j - 1)]; newTarget = m_mazeConnectedEmptySpace[tileCoordinate(i, j)]; } else { newTarget = m_mazeConnectedEmptySpace[tileCoordinate(i, j - 1)]; target = m_mazeConnectedEmptySpace[tileCoordinate(i, j)]; } --m_numOfIsolatedEmptySpaces; for (int jj = 1; jj < m_height - 1; ++jj) { for (int ii = 1; ii < m_width - 1; ++ii) { if (m_mazeConnectedEmptySpace[tileCoordinate(ii, jj)] == target) m_mazeConnectedEmptySpace[tileCoordinate(ii, jj)] = newTarget; else if (m_mazeConnectedEmptySpace[tileCoordinate(ii, jj)] > target) m_mazeConnectedEmptySpace[tileCoordinate(ii, jj)] -= 1; } } } } else if (m_mazeConnectedEmptySpace[tileCoordinate(i, j - 1)] != 0) { m_mazeConnectedEmptySpace[tileCoordinate(i, j)] = m_mazeConnectedEmptySpace[tileCoordinate(i, j - 1)]; } else { ++m_numOfIsolatedEmptySpaces; m_mazeConnectedEmptySpace[tileCoordinate(i, j)] = m_numOfIsolatedEmptySpaces; } } } } std::cout << "DONE\n"; return m_numOfIsolatedEmptySpaces; } void connectAllEmptySpace() { std::cout << "Connecting all empty space together...\n"; //struct Coordinates //{ // int x; // int y; //}; std::vector<Coordinates> coords; std::vector<Coordinates> nearbyCoords{ {-2, 0}, {2, 0}, {0, -2}, {0, 2} }; for (int k = m_numOfIsolatedEmptySpaces; k > 1; --k) { for (int i = 1; i < m_width - 1; ++i) { for (int j = 1; j < m_height - 1; ++j) { if (m_mazeConnectedEmptySpace[tileCoordinate(i, j)] == k) { coords.push_back({ i, j }); } } } //std::mt19937 mersenne2(static_cast<unsigned int>(std::time(nullptr))); std::shuffle(std::begin(coords), std::end(coords), mersenne); std::shuffle(std::begin(nearbyCoords), std::end(nearbyCoords), mersenne); for (int i = 0; i < coords.size(); ++i) { for (int j = 0; j < nearbyCoords.size(); ++j) { if (coords[i].x + nearbyCoords[j].x >= 1 && coords[i].x + nearbyCoords[j].x <= m_width - 2 && coords[i].y + nearbyCoords[j].y >= 1 && coords[i].y + nearbyCoords[j].y <= m_height - 2) { if (m_mazeConnectedEmptySpace[tileCoordinate(coords[i].x + nearbyCoords[j].x, coords[i].y + nearbyCoords[j].y)] < k && m_mazeConnectedEmptySpace[tileCoordinate(coords[i].x + nearbyCoords[j].x, coords[i].y + nearbyCoords[j].y)] > 0) { int newValue = m_mazeConnectedEmptySpace[tileCoordinate(coords[i].x + nearbyCoords[j].x, coords[i].y + nearbyCoords[j].y)]; m_mazeConnectedEmptySpace[tileCoordinate(coords[i].x + (nearbyCoords[j].x / 2), coords[i].y + (nearbyCoords[j].y / 2))] = newValue; m_mazeTiles[tileCoordinate(coords[i].x + (nearbyCoords[j].x / 2), coords[i].y + (nearbyCoords[j].y / 2))] = 0; //std::cout << k << " connected to " << newValue << " at (" << coords[i].x + (nearbyCoords[j].x / 2) << ", " << coords[i].y + (nearbyCoords[j].y / 2) << ")\n"; //std::cout << "x1: " << coords[i].x << ", y1: " << coords[i].y << "\n"; //std::cout << "x2: " << (nearbyCoords[j].x / 2) << ", y2: " << (nearbyCoords[j].y / 2) << "\n"; for (int ii = 0; ii < coords.size(); ++ii) { m_mazeConnectedEmptySpace[tileCoordinate(coords[ii].x, coords[ii].y)] = newValue; } coords.clear(); j = nearbyCoords.size(); i = coords.size(); --m_numOfIsolatedEmptySpaces; } } } } /* for (int i = 0; i < nearbyCoords.size(); ++i) { std::cout << "\n"; std::cout << k << ": (" << nearbyCoords[i].x << ", " << nearbyCoords[i].y << " )\n"; }*/ } std::cout << "DONE\n"; } //slow function void addRandomWallTilesStage2() { //struct Coordinates //{ // int x; // int y; //}; std::vector<Coordinates> coords; calculateNumOfEmptyTiles(); for (int j = 1; j < m_height - 1; ++j) { for (int i = 1; i < m_width - 1; ++i) { if (m_mazeTiles[tileCoordinate(i, j)] == 0) { coords.push_back({ i, j }); } } } std::shuffle(std::begin(coords), std::end(coords), mersenne); if (m_loopFactor > 1) m_loopFactor = 1.0f; if (m_loopFactor < 0) m_loopFactor = 0.0f; //int xdTest{}; //std::cout << "loopFactor: " << m_loopFactor << "\n"; //std::cout << "coords.size(): " << coords.size() << "\n"; //std::cout << "coords.size() * loopFactor: " << static_cast<int>(coords.size() * m_loopFactor * m_loopFactor) << "\n"; //std::cin >> xdTest; int currentProgress{}; int newProgress{}; std::cout << "Adding random wall blocks...\n"; for (int i = 0; i < static_cast<int>(coords.size() * m_loopFactor * m_loopFactor); ++i) { newProgress = static_cast<int>(static_cast<float>(100 * i / static_cast<int>(coords.size() * m_loopFactor * m_loopFactor - 1))); if (newProgress > currentProgress) { std::cout << "Adding random wall blocks... (" << newProgress << "%)\n"; currentProgress = newProgress; } if (!m_mazeTiles[tileCoordinate(coords[i].x, coords[i].y)]) { if (checkValidWallLocationC(coords[i].x, coords[i].y)) { m_mazeTiles[tileCoordinate(coords[i].x, coords[i].y)] = 1; --m_emptySpace; //if (calculateConnectedEmptySpaces() > 1) if (!checkEmptySpaceIsConnectedCheap()) { m_mazeTiles[tileCoordinate(coords[i].x, coords[i].y)] = 0; ++m_emptySpace; } } } } //calculateConnectedEmptySpaces(); std::cout << "DONE\n"; } void calculateStartAndExitLocation() { std::cout << "Creating Start and Exit location...\n"; int xStartCurrent{}; int yStartCurrent{}; int xEndCurrent{}; int yEndCurrent{}; int xStartNew{}; int yStartNew{}; int xEndNew{}; int yEndNew{}; int longestPathCurrent{}; int longestPathNew{}; int numOfDirections{}; for (int j = 1; j < m_height - 1; ++j) { xStartNew = 1; yStartNew = j; if (!m_mazeTiles[tileCoordinate(xStartNew, yStartNew)]) { numOfDirections = 0; if (!m_mazeTiles[tileCoordinate(xStartNew - 1, yStartNew)]) ++numOfDirections; if (!m_mazeTiles[tileCoordinate(xStartNew + 1, yStartNew)]) ++numOfDirections; if (!m_mazeTiles[tileCoordinate(xStartNew, yStartNew - 1)]) ++numOfDirections; if (!m_mazeTiles[tileCoordinate(xStartNew, yStartNew + 1)]) ++numOfDirections; if (numOfDirections == 1) { calculateLongestPath(xStartNew, yStartNew, xEndNew, yEndNew, longestPathNew); if (longestPathNew > longestPathCurrent) { longestPathCurrent = longestPathNew; xStartCurrent = xStartNew; yStartCurrent = yStartNew; xEndCurrent = xEndNew; yEndCurrent = yEndNew; } } } } for (int i = 2; i < m_width - 2; ++i) { xStartNew = i; yStartNew = 1; if (!m_mazeTiles[tileCoordinate(xStartNew, yStartNew)]) { numOfDirections = 0; if (!m_mazeTiles[tileCoordinate(xStartNew - 1, yStartNew)]) ++numOfDirections; if (!m_mazeTiles[tileCoordinate(xStartNew + 1, yStartNew)]) ++numOfDirections; if (!m_mazeTiles[tileCoordinate(xStartNew, yStartNew - 1)]) ++numOfDirections; if (!m_mazeTiles[tileCoordinate(xStartNew, yStartNew + 1)]) ++numOfDirections; if (numOfDirections == 1) { calculateLongestPath(xStartNew, yStartNew, xEndNew, yEndNew, longestPathNew); if (longestPathNew > longestPathCurrent) { longestPathCurrent = longestPathNew; xStartCurrent = xStartNew; yStartCurrent = yStartNew; xEndCurrent = xEndNew; yEndCurrent = yEndNew; } } } } //std::cout << "DONE\n"; //std::cout << "Start: (" << xStartCurrent << ", " << yStartCurrent << ")\n"; //std::cout << "End: (" << xEndCurrent << ", " << yEndCurrent << ")\n"; //std::cout << "Distance = " << longestPathCurrent << "\n"; if (xStartCurrent == 1) { m_mazeTiles[tileCoordinate(0, yStartCurrent)] = 0; } else if (xStartCurrent == m_width - 2) { m_mazeTiles[tileCoordinate(m_width - 1, yStartCurrent)] = 0; } else if (yStartCurrent == 1) { m_mazeTiles[tileCoordinate(xStartCurrent, 0)] = 0; } else if (yStartCurrent == m_height - 2) { m_mazeTiles[tileCoordinate(xStartCurrent, m_height - 1)] = 0; } if (xEndCurrent == 1) { m_mazeTiles[tileCoordinate(0, yEndCurrent)] = 0; } else if (xEndCurrent == m_width - 2) { m_mazeTiles[tileCoordinate(m_width - 1, yEndCurrent)] = 0; } else if (yEndCurrent == 1) { m_mazeTiles[tileCoordinate(xEndCurrent, 0)] = 0; } else if (yEndCurrent == m_height - 2) { m_mazeTiles[tileCoordinate(xEndCurrent, m_height - 1)] = 0; } std::cout << "DONE\n"; } void calculateNumOfEmptyTiles() { m_emptySpace = 0; for (int i = 1; i < m_width - 1; ++i) { for (int j = 1; j < m_height - 1; ++j) { if (!m_mazeTiles[tileCoordinate(i, j)]) ++m_emptySpace; } } } bool checkEmptySpaceIsConnectedCheap() { std::vector<Coordinates> coords1{}; std::vector<Coordinates> coords2{}; std::vector<int>distanceMap; int distance{}; int numOfEmptySpace{}; Coordinates start{ 1, 1 }; Coordinates end{}; distanceMap.resize(m_width*m_height); distanceMap[tileCoordinate(1, 1)] = distance; coords1.reserve(100); coords2.reserve(100); coords1.push_back(start); do { ++distance; for (int i = 0; i < coords1.size(); ++i) { if (!m_mazeTiles[tileCoordinate(coords1[i].x, coords1[i].y - 1)] && distanceMap[tileCoordinate(coords1[i].x, coords1[i].y - 1)] == 0) { ++numOfEmptySpace; coords2.push_back({ coords1[i].x, coords1[i].y - 1 }); distanceMap[tileCoordinate(coords1[i].x, coords1[i].y - 1)] = distance; } if (!m_mazeTiles[tileCoordinate(coords1[i].x, coords1[i].y + 1)] && distanceMap[tileCoordinate(coords1[i].x, coords1[i].y + 1)] == 0) { ++numOfEmptySpace; coords2.push_back({ coords1[i].x, coords1[i].y + 1 }); distanceMap[tileCoordinate(coords1[i].x, coords1[i].y + 1)] = distance; } if (!m_mazeTiles[tileCoordinate(coords1[i].x - 1, coords1[i].y)] && distanceMap[tileCoordinate(coords1[i].x - 1, coords1[i].y)] == 0) { ++numOfEmptySpace; coords2.push_back({ coords1[i].x - 1, coords1[i].y }); distanceMap[tileCoordinate(coords1[i].x - 1, coords1[i].y)] = distance; } if (!m_mazeTiles[tileCoordinate(coords1[i].x + 1, coords1[i].y)] && distanceMap[tileCoordinate(coords1[i].x + 1, coords1[i].y)] == 0) { ++numOfEmptySpace; coords2.push_back({ coords1[i].x + 1, coords1[i].y }); distanceMap[tileCoordinate(coords1[i].x + 1, coords1[i].y)] = distance; } } if (coords2.size() == 0) end = { coords1[0].x, coords1[0].y }; coords1.swap(coords2); coords2.clear(); } while (coords1.size() > 0); return (numOfEmptySpace == m_emptySpace); } void calculateLongestPath(int x, int y, int &xOut, int &yOut, int &valOut) //x, y is starting location { std::vector<Coordinates> coords1{}; std::vector<Coordinates> coords2{}; std::vector<int>distanceMap; int distance{}; Coordinates start{x, y}; Coordinates end{}; distanceMap.resize(m_width*m_height); distanceMap[tileCoordinate(x, y)] = distance; coords1.reserve(100); coords2.reserve(100); coords1.push_back(start); do { ++distance; for (int i = 0; i < coords1.size(); ++i) { if (!m_mazeTiles[tileCoordinate(coords1[i].x, coords1[i].y - 1)] && distanceMap[tileCoordinate(coords1[i].x, coords1[i].y - 1)] == 0) { coords2.push_back({ coords1[i].x, coords1[i].y - 1 }); distanceMap[tileCoordinate(coords1[i].x, coords1[i].y - 1)] = distance; } if (!m_mazeTiles[tileCoordinate(coords1[i].x, coords1[i].y + 1)] && distanceMap[tileCoordinate(coords1[i].x, coords1[i].y + 1)] == 0) { coords2.push_back({ coords1[i].x, coords1[i].y + 1 }); distanceMap[tileCoordinate(coords1[i].x, coords1[i].y + 1)] = distance; } if (!m_mazeTiles[tileCoordinate(coords1[i].x - 1, coords1[i].y)] && distanceMap[tileCoordinate(coords1[i].x - 1, coords1[i].y)] == 0) { coords2.push_back({ coords1[i].x - 1, coords1[i].y }); distanceMap[tileCoordinate(coords1[i].x - 1, coords1[i].y)] = distance; } if (!m_mazeTiles[tileCoordinate(coords1[i].x + 1, coords1[i].y)] && distanceMap[tileCoordinate(coords1[i].x + 1, coords1[i].y)] == 0) { coords2.push_back({ coords1[i].x + 1, coords1[i].y }); distanceMap[tileCoordinate(coords1[i].x + 1, coords1[i].y)] = distance; } } if (coords2.size() == 0) end = { coords1[0].x, coords1[0].y }; coords1.swap(coords2); coords2.clear(); } while (coords1.size() > 0); //std::cout << "The longest path from start (" << x << ", " << y << ") is to (" << end.x << ", " << end.y << ") (length = " << distance << ")\n"; /* std::vector<unsigned char> image; image.resize(m_width * m_height * 4); for (int j = 0; j < m_height; ++j) { for (int i = 0; i < m_width; ++i) { image[4 * m_width * j + 4 * i + 0] = static_cast<bool>(distanceMap[tileCoordinate(i, j)])*64 + distanceMap[tileCoordinate(i, j)]; image[4 * m_width * j + 4 * i + 1] = 0; image[4 * m_width * j + 4 * i + 2] = 0; image[4 * m_width * j + 4 * i + 3] = 255; } } encodeOneStep("maze_debug.png", image, m_width, m_height); */ Coordinates longestDistanceLocation{}; int longestDistance{}; int numOfDirections{}; for (int j = 1; j < m_height - 1; ++j) { if (!m_mazeTiles[tileCoordinate(1, j)]) { numOfDirections = 0; if (!m_mazeTiles[tileCoordinate(1 - 1, j)]) ++numOfDirections; if (!m_mazeTiles[tileCoordinate(1 + 1, j)]) ++numOfDirections; if (!m_mazeTiles[tileCoordinate(1, j - 1)]) ++numOfDirections; if (!m_mazeTiles[tileCoordinate(1, j + 1)]) ++numOfDirections; if (numOfDirections == 1) { if (distanceMap[tileCoordinate(1, j)] > longestDistance) { longestDistanceLocation = { 1, j }; longestDistance = distanceMap[tileCoordinate(1, j)]; } } } if (!m_mazeTiles[tileCoordinate(m_width - 2, j)]) { numOfDirections = 0; if (!m_mazeTiles[tileCoordinate(m_width - 2 - 1, j)]) ++numOfDirections; if (!m_mazeTiles[tileCoordinate(m_width - 2 + 1, j)]) ++numOfDirections; if (!m_mazeTiles[tileCoordinate(m_width - 2, j - 1)]) ++numOfDirections; if (!m_mazeTiles[tileCoordinate(m_width - 2, j + 1)]) ++numOfDirections; if (numOfDirections == 1) { if (distanceMap[tileCoordinate(m_width - 2, j)] > longestDistance) { longestDistanceLocation = { m_width - 2, j }; longestDistance = distanceMap[tileCoordinate(m_width - 2, j)]; } } } } for (int i = 2; i < m_width - 2; ++i) { if (!m_mazeTiles[tileCoordinate(i, 1)]) { numOfDirections = 0; if (!m_mazeTiles[tileCoordinate(i - 1, 1)]) ++numOfDirections; if (!m_mazeTiles[tileCoordinate(i + 1, 1)]) ++numOfDirections; if (!m_mazeTiles[tileCoordinate(i, 1 - 1)]) ++numOfDirections; if (!m_mazeTiles[tileCoordinate(i, 1 + 1)]) ++numOfDirections; if (numOfDirections == 1) { if (distanceMap[tileCoordinate(i, 1)] > longestDistance) { longestDistanceLocation = { i, 1 }; longestDistance = distanceMap[tileCoordinate(i, 1)]; } } } if (!m_mazeTiles[tileCoordinate(i, m_height - 2)]) { numOfDirections = 0; if (!m_mazeTiles[tileCoordinate(i - 1, m_height - 2)]) ++numOfDirections; if (!m_mazeTiles[tileCoordinate(i + 1, m_height - 2)]) ++numOfDirections; if (!m_mazeTiles[tileCoordinate(i, m_height - 2 - 1)]) ++numOfDirections; if (!m_mazeTiles[tileCoordinate(i, m_height - 2 + 1)]) ++numOfDirections; if (numOfDirections == 1) { if (distanceMap[tileCoordinate(i, m_height - 2)] > longestDistance) { longestDistanceLocation = { i, m_height - 2 }; longestDistance = distanceMap[tileCoordinate(i, m_height - 2)]; } } } } //std::cout << "Longest distance edge tile is (" << longestDistanceLocation.x << ", " << longestDistanceLocation.y << ")\n"; //std::cout << "(" << x << ", " << y << ") -> (" << longestDistanceLocation.x << ", " << longestDistanceLocation.y << "), D = " << longestDistance << "\n"; xOut = longestDistanceLocation.x; yOut = longestDistanceLocation.y; valOut = longestDistance; } void DrawMazeToPng(const char* name = "maze.png") { std::vector<unsigned char> image; image.resize(m_width * m_height * 4); for (int j = 0; j < m_height; ++j) { for (int i = 0; i < m_width; ++i) { image[4 * m_width * j + 4 * i + 0] = 255 * !m_mazeTiles[tileCoordinate(i, j)]; image[4 * m_width * j + 4 * i + 1] = 255 * !m_mazeTiles[tileCoordinate(i, j)]; image[4 * m_width * j + 4 * i + 2] = 255 * !m_mazeTiles[tileCoordinate(i, j)]; image[4 * m_width * j + 4 * i + 3] = 255; } } encodeOneStep(name, image, m_width, m_height); } void Draw() { for (int i = 0; i < m_mazeTiles.size(); ++i) { if (i % m_width == 0) std::cout << "\n"; if (m_mazeTiles[i] == 0) std::cout << " "; //change to " " when not debugging else std::cout << "X"; } } void DrawDebugConnectedWhiteSpace() { for (int i = 0; i < m_mazeConnectedEmptySpace.size(); ++i) { if (i % m_width == 0) std::cout << "\n"; if (m_mazeConnectedEmptySpace[i] == 0) std::cout << " "; //change to " " when not debugging else std::cout << m_mazeConnectedEmptySpace[i]; } } ~Maze() { } }; void encodeOneStep(const char* filename, std::vector<unsigned char>& image, unsigned width, unsigned height) { //Encode the image unsigned error = lodepng::encode(filename, image, width, height); //if there's an error, display it if (error) std::cout << "encoder error " << error << ": " << lodepng_error_text(error) << std::endl; } int main() { //intToString(0); /* unsigned int imageWidth = 512; unsigned int imageHeight = 512; std::vector<unsigned char> image; image.resize(imageWidth * imageHeight * 4); for (unsigned y = 0; y < imageHeight; y++) for (unsigned x = 0; x < imageWidth; x++) { image[4 * imageWidth * y + 4 * x + 0] = 255 * !(x & y); image[4 * imageWidth * y + 4 * x + 1] = x ^ y; image[4 * imageWidth * y + 4 * x + 2] = x | y; image[4 * imageWidth * y + 4 * x + 3] = 255; } encodeOneStep("testi.png", image, imageWidth, imageHeight); */ /* std::cout << !((8 % 2 == 0) && (10 % 2 == 0)) << "\n"; int testArray[5*5]{}; for (int i = 0; i < 5 * 5; ++i) { if (i % 5 == 0) std::cout << "\n"; std::cout << testArray[i] << " "; }*/ //max width: 119 //max height: 29 int width{}; int height{}; int quantity{}; float loopFactor{}; do { std::cout << "Enter width of the maze (odd number >= 9): "; std::cin >> width; } while ((width <= 8) || (width % 2 == 0)); do { std::cout << "Enter height of the maze (odd number >= 9): "; std::cin >> height; } while ((height <= 8) || (height % 2 == 0)); do { std::cout << "Enter loop factor (decimal number from 0 to 1. 1 = no loops, 0 = lots of loops): "; std::cin >> loopFactor; } while ((loopFactor < 0.000f) && (loopFactor > 1.000f)); do { std::cout << "Enter how many mazes you want to generate (min: 1, max: 10): "; std::cin >> quantity; } while ((quantity <= 0) || (quantity > 10)); Maze maze(width, height, loopFactor, quantity); std::cout << "Your maze(s) were saves as PNG files in the executable's folder\n"; //maze.DrawAtPoint(9, 9); /* maze.Draw(); maze.DrawRandomWallTilesStage1(); maze.Draw(); maze.createBorders(); maze.freeEncircledSingleWhiteSpaces(); maze.Draw(); maze.connectLoneWallTiles(); maze.Draw(); maze.calculateConnectedEmptySpaces(); maze.DrawDebugConnectedWhiteSpace(); maze.connectAllEmptySpace(); maze.DrawDebugConnectedWhiteSpace(); maze.Draw(); maze.calculateConnectedEmptySpaces(); maze.DrawDebugConnectedWhiteSpace(); maze.Draw(); maze.addRandomWallTilesStage2(); maze.Draw(); maze.DrawDebugConnectedWhiteSpace(); //maze.calculateLongestPath(1, 1); maze.calculateStartAndExitLocation(); maze.Draw(); maze.DrawMazeToPng();*/ int test{}; std::cin >> test; }
7826b126dd9e0936e5860534a8c3dcea2ef87738
[ "Markdown", "C++" ]
2
Markdown
smoothstill/maze-generator
c87c51c9e8c982773836b00bf9beb76af08b97bd
707049cd301faaaabd6558f07b6cb55a784fb62f
refs/heads/master
<repo_name>ArthurRbn/Corewar<file_sep>/asm/core/param_tokenizer.c /* ** EPITECH PROJECT, 2020 ** asm ** File description: ** param_tokenizer */ #include "compiler.h" #include "string_utils.h" #include "string_convert.h" #include "tokenizer.h" #include "console.h" #include <stdlib.h> static int reg(param_t *param, char *str) { param->type = T_REG; param->val.ui = stoi(str + 1); if (my_strissub(str + 1, "0123456789") == 0 || param->val.ui < 1 || param->val.ui > 16) { my_puterr("Error: "); my_puterr(str); my_puterr(" is not a valid register.\n"); return (1); } return (0); } static int direct(param_t *param, char *str) { param->type = T_DIR; if (str[1] == LABEL_CHAR) { param->type = T_DIR | T_LAB; param->val.str = my_strdup(str + 2); return (0); } param->val.ui = stoi(str + 1); if (my_strissub(str + 1, "0123456789") == 0) { my_puterr("Error: "); my_puterr(str); my_puterr(" is not a valid direct value.\n"); return (1); } return (0); } static int indirect(param_t *param, char *str) { param->type = T_IND; if (str[0] == LABEL_CHAR) { param->type = T_IND | T_LAB; param->val.str = my_strdup(str + 1); } else param->val.ui = stoi(str); if (my_strissub(str + 1, "0123456789") == 0) { my_puterr("Error: "); my_puterr(str); my_puterr(" is not a valid indirect value.\n"); return (1); } return (0); } static int handle(param_t *param, char *str) { switch (str[0]) { case REG_CHAR: return (reg(param, str)); case DIRECT_CHAR: return (direct(param, str)); default: return (indirect(param, str)); } } param_t *tokenize_param(char *str, int *error) { param_t *param = malloc(sizeof(param_t)); if (param == NULL) { free(str); return (NULL); } if (str == NULL) return (NULL); param->type = 0; *error -= handle(param, str); free(str); return (param); } <file_sep>/bonus/corewar/include/vm.h /* ** EPITECH PROJECT, 2020 ** CPE_corewar_2019 ** File description: ** vm */ #pragma once #include "op.h" #include "chain_list.h" #define INVALID_INSTRUCTION 84 #define WAITING_LIVE 0 #define LIVE 1 #define DEAD 2 typedef struct vm_s { int dump_cycle; int nb_champ; list_t *champ; unsigned char *mem; unsigned char *color_mem; } vm_t; typedef struct champion_s { char *path; unsigned char *program; int prog_size; int prog_number; int load_adress; int live; list_t *process; } champion_t; typedef struct instruction_s { char instruction_code; int params[MAX_ARGS_NUMBER]; int *arg_types; } instruction_t; typedef struct process_s { int *reg; int pc; int carry; int live; int cycles; int champ_nb; instruction_t *instruction; } process_t; //error handling void error_handling(char *argv[], int ac, vm_t *vm); void put_usage(void); //parsing vm_t *parsing(int argc, char *argv[], vm_t *vm); champion_t *create_champ(void); list_t *search_prog_number(list_t *list, char *argv[]); void set_default_load_adresses(list_t *champions, int nb_champions); list_t *search_load_adress(list_t *list, char *argv[]); void load_binaries(unsigned char *mem, int nb_champ, list_t *champions); void load_champions_to_mem(list_t *champions, vm_t *vm); //vm vm_t *vm_init(int ac, char **argv); int vm_start(vm_t *vm); void update(vm_t *vm); void execution_loop(vm_t *vm); void free_mem(vm_t *vm); //process process_t *init_process(int pid, int pc, int champ_nb); void destroy_process(process_t *process); void create_champ_processes(list_t *champions); //instruction instruction_t *init_instruction(void); void reset_instruction(instruction_t *instruction); void destroy_instruction(instruction_t *instruction); void fetch_instruction(int *arg_len, process_t *proc, unsigned char *mem); void get_next_instruction(process_t *proc, unsigned char *mem); //mem_op void load_prog_to_mem(champion_t *champ, vm_t *vm, int adress); int mem_to_int(unsigned char *mem, int adress, int read_size); void int_to_mem(vm_t *vm, int prog_number, int adress, int value); void dump_memory(unsigned char *mem); //ncurses utils void start_ncurses(list_t *champ); void print_colorized_mem(unsigned char *aff_mem, unsigned char *mem); //operations void op_live(process_t *, vm_t *); void op_ld(process_t *, vm_t *); void op_st(process_t *, vm_t *); void op_add(process_t *, vm_t *); void op_sub(process_t *, vm_t *); void op_and(process_t *, vm_t *); void op_or(process_t *, vm_t *); void op_xor(process_t *, vm_t *); void op_zjmp(process_t *, vm_t *); void op_ldi(process_t *, vm_t *); void op_sti(process_t *, vm_t *); void op_fork(process_t *, vm_t *); void op_lld(process_t *, vm_t *); void op_lldi(process_t *, vm_t *); void op_lfork(process_t *, vm_t *); void op_aff(process_t *, vm_t *); <file_sep>/bonus/asm/include/label.h /* ** EPITECH PROJECT, 2020 ** asm ** File description: ** label */ #pragma once #include "tokenizer.h" unsigned int get_label_address(token_t **tokens, char const *label); <file_sep>/corewar/src/utils/process_utils.c /* ** EPITECH PROJECT, 2020 ** CPE_corewar_2019 ** File description: ** manage process structure */ #include <stdlib.h> #include "vm.h" #include "op.h" process_t *init_process(int pid, int pc, int champ_nb) { process_t *new = malloc(sizeof(process_t)); if (!new) exit(84); new->carry = 0; new->cycles = 0; new->instruction = init_instruction(); new->live = 0; new->pc = pc; new->champ_nb = champ_nb; new->reg = malloc(sizeof(int) * REG_NUMBER); if (!new->reg) exit(84); for (int i = 0; i < REG_NUMBER; ++i) new->reg[i] = 0; new->reg[0] = pid; return (new); } void destroy_process(process_t *process) { if (!process) return; if (process->reg != NULL) free(process->reg); destroy_instruction(process->instruction); free(process); }<file_sep>/bonus/asm/include/file.h /* ** EPITECH PROJECT, 2020 ** asm ** File description: ** file */ #pragma once char **read_file(char const *path); <file_sep>/corewar/src/vm/dump_memory.c /* ** EPITECH PROJECT, 2020 ** CPE_corewar_2019 ** File description: ** functions to dump memory each dump_cycle if defined as params */ #include "vm.h" #include "console.h" #include <stdio.h> void dump_memory(unsigned char *mem) { char *hexa = "0123456789ABCDEF"; char byte[3] = {0, 0, 0}; for (int i = 0; i < MEM_SIZE; ++i) { if (i % 32 == 0) my_putstr("\n"); byte[0] = hexa[(mem[i] >> 4)]; byte[1] = hexa[(mem[i] & 0xF)]; my_putstr(byte); if ((i + 1) % 32 != 0) my_putstr(" "); } my_putstr("\n"); }<file_sep>/asm/core/validate_parameters.c /* ** EPITECH PROJECT, 2020 ** asm ** File description: ** validate_parameters */ #include "tokenizer.h" #include "output.h" #include "console.h" #include <stdlib.h> static int validate_token_parameters(token_t *token) { op_t *op = get_op(token->op); args_type_t type = 0; int error = 0; for (int i = 0; token->params[i]; i++) { type = token->params[i]->type & ~T_LAB; if ((op->types[i] & type) == 0) error++; } if (error != 0) { my_puterr("Error: invalid arguments for op '"); my_puterr(op->mnemonique); my_puterr("'.\n"); } return (error); } int validate_parameters(token_t **tokens) { int error = 0; for (int i = 0; tokens[i]; i++) if (tokens[i]->op != NULL) error -= validate_token_parameters(tokens[i]); return (error); } <file_sep>/asm/include/compiler.h /* ** EPITECH PROJECT, 2020 ** asm ** File description: ** compiler */ #pragma once int compile(char **src, char const *output); #define NAME_CMD_STRING ".name \"" #define NAME_LEN 128 #define COMMENT_CMD_STRING ".comment \"" #define COMMENT_LEN 2048 #define MAGIC_NUMBER 0xEA83F3 #define REG_CHAR 'r' #define COMMENT_CHAR '#' #define LABEL_CHAR ':' #define DIRECT_CHAR '%' #define SEPARATOR_CHAR ',' #define LABEL_CHARS "abcdefghijklmnopqrstuvwxyz_0123456789" typedef char args_type_t; #define T_REG 1 #define T_DIR 2 #define T_IND 4 #define T_LAB 8 typedef struct { args_type_t type; union { unsigned int ui; char *str; } val; } param_t; #define MAX_ARGS 4 typedef struct { char *mnemonique; char code; int args_count; args_type_t types[MAX_ARGS]; } op_t; extern op_t op_table[]; typedef struct { int magic; char name[NAME_LEN + 1]; int prog_size; char comment[COMMENT_LEN + 1]; } header_t; <file_sep>/asm/core/label.c /* ** EPITECH PROJECT, 2020 ** asm ** File description: ** label */ #include "label.h" #include "bin_utils.h" #include "prog_size.h" unsigned int get_label_address(token_t **tokens, char const *label) { return (swap_endianness(get_prog_size(tokens, label))); } <file_sep>/bonus/corewar/src/vm/load_champions.c /* ** EPITECH PROJECT, 2020 ** CPE_corewar_2019 ** File description: ** load champions binaries */ #include <stdlib.h> #include <sys/stat.h> #include <sys/types.h> #include <fcntl.h> #include <unistd.h> #include "console.h" #include "chain_list.h" #include "string_utils.h" #include "vm.h" void load_champions_to_mem(list_t *champions, vm_t *vm) { list_t *temp = champions; champion_t *handler = NULL; while (temp) { handler = temp->data; load_prog_to_mem(handler, vm, handler->load_adress); temp = temp->next; } } void set_default_load_adresses(list_t *champions, int nb_champions) { list_t *temp = champions; champion_t *handler = NULL; int offset = MEM_SIZE / nb_champions; int i = 0; while (temp) { handler = temp->data; handler->load_adress = offset * i; ++i; temp = temp->next; } } static void fetch_header(champion_t *champ, int *fd, int *prog_size) { *fd = open(champ->path, O_RDONLY); unsigned char *buff = malloc(sizeof(unsigned char *) * sizeof(header_t)); char *name = malloc(sizeof(char) * (PROG_NAME_LENGTH + 1)); if (*fd == -1 || !buff || !name) { my_puterr("Something wrong happened while reading champion file\n"); put_usage(); exit(84); } if (read(*fd, buff, sizeof(header_t)) != sizeof(header_t) || mem_to_int(buff, 0, 4) != COREWAR_EXEC_MAGIC) { my_puterr("Invalid magic number\n"); exit(84); } champ->prog_size = mem_to_int(buff, 136, 4); free(champ->path); champ->path = name; for (int i = 0; i < PROG_NAME_LENGTH; ++i) champ->path[i] = buff[i + 4]; champ->path[PROG_NAME_LENGTH] = 0; } static void fetch_program(champion_t *champ, int *fd) { champ->program = malloc(sizeof(unsigned char) * champ->prog_size); char check_empty = 0; if (!champ->program) { my_puterr("Something wrong happened while reading champion file\n"); exit(84); } for (int i = 0; i < champ->prog_size; ++i) champ->program[i] = 0; if (read(*fd, champ->program, champ->prog_size) != champ->prog_size) { my_puterr("Invalid program size\n"); exit(84); } if (read(*fd, &check_empty, 1) != 0) { my_puterr("Invalid champion file, longer program than declared\n"); exit(84); } close(*fd); } void load_binaries(unsigned char *mem, int nb_champ, list_t *champions) { list_t *temp = champions; champion_t *champ_temp = NULL; int fd = 0; int prog_size = 0; while (temp) { champ_temp = temp->data; if (!champ_temp->path) { my_puterr("Missing champion filepath\n"); put_usage(); exit(84); } fetch_header(champ_temp, &fd, &prog_size); fetch_program(champ_temp, &fd); temp = temp->next; } }<file_sep>/asm/include/output.h /* ** EPITECH PROJECT, 2020 ** asm ** File description: ** output */ #pragma once #include "tokenizer.h" op_t *get_op(char *str); void out_params(token_t *token, token_t **tokens, int fd); void out_code(token_t **tokens, int fd); <file_sep>/asm/core/prog_size.c /* ** EPITECH PROJECT, 2020 ** asm ** File description: ** prog_size */ #include "prog_size.h" #include "string_utils.h" #include <stdlib.h> static int get_coding_bytes_size(token_t *token) { char *ignored[] = {"live", "zjmp", "fork", "lfork", NULL}; int param_count = 0; for (int i = 0; ignored[i]; i++) if (my_streq(ignored[i], token->op)) return (0); for (; token->params[param_count]; param_count++); return ((param_count / 4) + (param_count % 4 == 0 ? 0 : 1)); } static int get_params_size(token_t *token) { int size = 0; for (int i = 0; token->params[i]; i++) { if (token->params[i]->type & T_IND) size += 2; if (token->params[i]->type & T_REG) size += 1; if (token->params[i]->type & T_DIR) size += 4; } return (size); } static int get_token_size(token_t *token) { int size = 1; if (token->op == NULL) return (0); size += get_coding_bytes_size(token); size += get_params_size(token); return (size); } int get_prog_size(token_t **tokens, char const *end_label) { int size = 0; for (int i = 0; tokens[i]; i++) { if (end_label != NULL && my_streq(end_label, tokens[i]->label)) return (size); size += get_token_size(tokens[i]); } return (size); } <file_sep>/corewar/src/vm/vm_start.c /* ** EPITECH PROJECT, 2020 ** CPE_corewar_2019 ** File description: ** vm_update */ #include "vm.h" #include <stdlib.h> static int check_alive(vm_t *vm) { champion_t *champ = NULL; list_t *temp = vm->champ; int nb_alive = 0; while (temp) { champ = temp->data; if (champ->live == 1) nb_alive++; } return (nb_alive); } int vm_start(vm_t *vm) { int nb_alive = vm->nb_champ; while (nb_alive) { nb_alive = check_alive(vm); update(vm); } return 0; }<file_sep>/corewar/Makefile ## ## EPITECH PROJECT, 2020 ## CPE_corewar_2019 ## File description: ## Makefile ## CFLAGS = -g -Iinclude -Wall LDFLAGS += EXEC = corewar SRC = src/main.c \ src/utils/console.c \ src/utils/string_utils.c \ src/utils/string_utils1.c \ src/utils/string_utils2.c \ src/utils/chain_list.c \ src/utils/string_convert.c \ src/utils/str_test.c \ src/utils/create_champ.c \ src/utils/instruction_utils.c \ src/utils/process_utils.c \ src/utils/my_put_nbr.c \ src/utils/my_putchar.c \ src/vm/parsing.c \ src/vm/update.c \ src/vm/error_handling.c \ src/vm/search_prog_number.c \ src/vm/search_load_adress.c \ src/vm/dump_memory.c \ src/vm/load_champions.c \ src/vm/execution_loop.c \ src/vm/vm_init.c \ src/vm/vm_start.c \ src/vm/free_vm.c \ src/operations/aff.c \ src/operations/ld.c \ src/operations/ldi.c \ src/operations/lld.c \ src/operations/lldi.c \ src/operations/op_fork.c \ src/operations/operation.c \ src/operations/operation1.c \ src/operations/live.c \ src/operations/st.c \ src/operations/sti.c \ src/operations/zjmp.c \ src/disassembler/get_next_instruction.c \ src/disassembler/fetch_params.c \ src/disassembler/mem_operations.c \ src/operations/op.c OBJ = $(SRC:.c=.o) all: $(EXEC) $(EXEC): $(OBJ) gcc -o $(EXEC) $(OBJ) $(LDFLAGS) clean: rm -f $(OBJ) fclean: clean rm -f $(EXEC) re: fclean all cdb: compiledb make re <file_sep>/corewar/src/vm/parsing.c /* ** EPITECH PROJECT, 2020 ** CPE_corewar_2019 ** File description: ** parsing */ #include <stdlib.h> #include <stdio.h> #include "vm.h" #include "str_test.h" #include "string_utils.h" #include "string_convert.h" #include "chain_list.h" #include "console.h" static list_t *create_list_champ(char **name) { list_t *list = create_list(create_champ(), name[0]); champion_t *temp = NULL; for (int i = 1; name[i] != NULL; i++) { list = list_append(list, create_champ(), name[i]); } for (list_t *l = list; l != NULL; l = l->next) { temp = l->data; temp->path = my_strdup(l->name); temp->prog_number = l->id; } return (list); } static char **champ_name(char *argv[]) { char **prog_name = malloc(sizeof(char*) * 5); int nb = 0; prog_name[4] = NULL; for (int i = 1; argv[i] != NULL; i++) { if ((argv[i][0] != '-' && !my_streq(argv[i - 1], "-dump")) && (!my_streq(argv[i - 1], "-a") && argv[i][0] != '-') && (!my_streq(argv[i - 1], "-n") && argv[i][0] != '-')) { prog_name[nb] = argv[i]; nb++; } prog_name[nb] = NULL; } return (prog_name); } static list_t *search_champ_info(char *argv[], vm_t *vm) { char **name = champ_name(argv); list_t *list_champ = create_list_champ(name); vm->nb_champ = arr_len(name); list_champ = search_prog_number(list_champ, argv); free(name); return (list_champ); } static int search_dump_cycle(char *argv[]) { for (int i = 0; argv[i] != NULL; i++) { if (my_streq("-dump", argv[i])) { if (is_number(argv[i + 1])) return (stoi(argv[i + 1])); else { my_puterr("The dumb nbr_cyle must have arithmetical type\n"); exit(84); } } } return (-1); } vm_t *parsing(int argc, char *argv[], vm_t *vm) { list_t *list_champ = search_champ_info(argv, vm); vm->dump_cycle = search_dump_cycle(argv); set_default_load_adresses(list_champ, vm->nb_champ); list_champ = search_load_adress(list_champ, argv); vm->champ = list_champ; return (vm); }<file_sep>/bonus/asm/include/array_utils.h /* ** EPITECH PROJECT, 2020 ** asm ** File description: ** array_utils */ #pragma once int array_len(void **arr); void custom_free_array(void **arr, void (*func)(void *)); void free_array(void **arr); <file_sep>/asm/core/tokenizer.c /* ** EPITECH PROJECT, 2020 ** asm ** File description: ** tokenizer */ #include "tokenizer.h" #include "array_utils.h" #include <stdlib.h> void free_param(void *p) { param_t *param = p; if ((param->type & T_LAB)) free(param->val.str); free(param); } void free_token(void *t) { token_t *token = t; if (token->label != NULL) free(token->label); if (token->op != NULL) free(token->op); custom_free_array((void **) token->params, free_param); free(token); } token_t **tokenize(char **lines) { token_t **tokens = malloc(sizeof(token_t *) * 1024); int i = 0; if (tokens == NULL) return (NULL); for (int j = 2; lines[j]; j++) tokens[i++] = tokenize_line(lines[j]); tokens[i] = 0; for (int j = 0; j < i; j++) if (tokens[j] == 0) { custom_free_array((void **) tokens, free_token); return (NULL); } if (validate_tokens(tokens) != 0) { custom_free_array((void **) tokens, free_token); return (NULL); } return (tokens); } <file_sep>/asm/core/compiler.c /* ** EPITECH PROJECT, 2020 ** asm ** File description: ** compiler */ #include "compiler.h" #include "console.h" #include "prog_size.h" #include "string_utils.h" #include "array_utils.h" #include "bin_utils.h" #include "tokenizer.h" #include "output.h" #include <fcntl.h> #include <unistd.h> op_t op_table[] = { {"live", 0x01, 1, {T_DIR}}, {"ld", 0x2, 2, {T_DIR | T_IND, T_REG}}, {"st", 0x03, 2, {T_REG, T_IND | T_REG}}, {"add", 0x04, 3, {T_REG, T_REG, T_REG}}, {"sub", 0x05, 3, {T_REG, T_REG, T_REG}}, {"and", 0x06, 3, {T_REG | T_DIR | T_IND, T_REG | T_IND | T_DIR, T_REG}}, {"or", 0x07, 3, {T_REG | T_IND | T_DIR, T_REG | T_IND | T_DIR, T_REG}}, {"xor", 0x08, 3, {T_REG | T_IND | T_DIR, T_REG | T_IND | T_DIR, T_REG}}, {"zjmp", 0x09, 1, {T_DIR}}, {"ldi", 0x0a, 3, {T_REG | T_DIR | T_IND, T_DIR | T_REG, T_REG}}, {"sti", 0x0b, 3, {T_REG, T_REG | T_DIR | T_IND, T_DIR | T_REG}}, {"fork", 0x0c, 1, {T_DIR}}, {"lld", 0x0d, 2, {T_DIR | T_IND, T_REG}}, {"lldi", 0x0e, 3, {T_REG | T_DIR | T_IND, T_DIR | T_REG, T_REG}}, {"lfork", 0x0f, 1, {T_DIR}}, {"aff", 0x10, 1, {T_REG}}, {0, 0, 0, {0}} }; static char *handle_name(char *line) { if (!my_strstartswith(line, NAME_CMD_STRING) || !my_strendswith(line, "\"")) { my_puterr("Error line 1: not a well formated name.\n"); return (NULL); } line += my_strlen(NAME_CMD_STRING); line[my_strlen(line) - 1] = 0; if (my_strlen(line) > NAME_LEN) { my_puterr("Error line 1: name is too long.\n"); return (NULL); } if (my_strlen(line) == 0) { my_puterr("Error line 1: name is too short.\n"); return (NULL); } return (line); } static char *handle_comment(char *line) { if (!my_strstartswith(line, COMMENT_CMD_STRING) || !my_strendswith(line, "\"")) { my_puterr("Error line 2: not a well formated comment.\n"); return (NULL); } line += my_strlen(COMMENT_CMD_STRING); line[my_strlen(line) - 1] = 0; if (my_strlen(line) > COMMENT_LEN) { my_puterr("Error line 2: comment is too long.\n"); return (NULL); } if (my_strlen(line) == 0) { my_puterr("Error line 2: comment is too short.\n"); return (NULL); } return (line); } static void out_header(char const *name, char const *comment, token_t ** tokens, int fd) { header_t header = {}; for (int i = 0; name[i] != 0; i++) header.name[i] = name[i]; header.name[my_strlen(name)] = 0; for (int i = 0; comment[i] != 0; i++) header.comment[i] = comment[i]; header.comment[my_strlen(comment)] = 0; header.magic = swap_endianness(MAGIC_NUMBER); header.prog_size = swap_endianness(get_prog_size(tokens, NULL)); write(fd, &header, sizeof(header_t)); } static int get_name_and_comment(char **src, char **name, char **com) { if (array_len((void **)src) < 2) { my_puterr("Error: source file should contain name and comment.\n"); return (-1); } *name = handle_name(src[0]); *com = handle_comment(src[1]); if (*name == NULL || *com == NULL) return (-1); return (0); } int compile(char **src, char const *output) { int fd; char *name; char *comment; token_t **tokens; if (get_name_and_comment(src, &name, &comment) < 0) return (84); tokens = tokenize(src); if (tokens == NULL) return (84); fd = open(output, O_WRONLY | O_CREAT, 0664); if (fd < 0) { my_puterr("Error: could not open output file."); custom_free_array((void **) tokens, free_token); return (84); } out_header(name, comment, tokens, fd); out_code(tokens, fd); close(fd); custom_free_array((void **) tokens, free_token); return (0); } <file_sep>/bonus/corewar/src/operations/operation.c /* ** EPITECH PROJECT, 2020 ** CPE_corewar_2019 ** File description: ** add */ #include "vm.h" #include "op.h" void op_add(process_t *process, vm_t *vm) { for (int i = 0; i < 3; i++) { if (process->instruction->arg_types[i] != 1 && (process->instruction->params[i] > 0 || process->instruction->params[i] < 15)) process->carry = 0; else { process->carry = 1; process->reg[2] = process->reg[0] + process->reg[1]; } } } void op_sub(process_t *process, vm_t *vm) { for (int i = 0; i < 3; i++) { if (process->instruction->arg_types[i] != 1 && (process->instruction->params[i] > 0 || process->instruction->params[i] < 15)) process->carry = 0; else { process->carry = 1; process->reg[2] = process->reg[0] - process->reg[1]; } } } static void op_and_check(process_t *process, vm_t *vm, int *info) { for (int i = 0; i < 2; i++) { if (process->instruction->arg_types[i] == 1 && (process->instruction->params[i] > 0 || process->instruction->params[i] < 15)) { process->carry = 0; return; } } if (process->instruction->arg_types[2] != 1 && (process->instruction->params[2] > 0 || process->instruction->params[2] < 15)) process->carry = 0; else { process->carry = 1; process->reg[2] = info[0] & info[1]; } } void op_and(process_t *process, vm_t *vm) { int info[] = {0, 0}; for (int i = 0; i < 2; i++) { if (process->instruction->arg_types[i] == 1) info[i] = process->reg[i]; if (process->instruction->arg_types[i] == 2) info[i] = process->instruction->params[i]; if (process->instruction->arg_types[i] == 3) info[i] = mem_to_int(vm->mem, process->pc + process->instruction->params[i], REG_SIZE); op_and_check(process, vm, info); } }<file_sep>/asm/core/output.c /* ** EPITECH PROJECT, 2020 ** asm ** File description: ** output */ #include "output.h" #include "compiler.h" #include "string_utils.h" #include <stdlib.h> #include <unistd.h> op_t *get_op(char *str) { for (int i = 0; op_table[i].mnemonique; i++) if (my_streq(op_table[i].mnemonique, str)) return (&(op_table[i])); return (NULL); } static void write_coding_byte(int fd, unsigned char *val, int *current_bit) { if (*current_bit == 0) return; write(fd, val, 1); *val = 0; *current_bit = 0; } static void write_coding_bytes(token_t *token, int fd) { unsigned char val = 0; int current_bit = 0; for (int i = 0; token->params[i]; i++) { if (token->params[i]->type & T_REG) { current_bit++; val |= 1 << (7 - current_bit); current_bit++; } else if (token->params[i]->type & T_DIR) { val |= 1 << (7 - current_bit); current_bit += 2; } else { val |= 1 << (7 - current_bit); val |= 1 << (7 - (current_bit + 1)); current_bit += 2; } if (current_bit == 8) write_coding_byte(fd, &val, &current_bit); } write_coding_byte(fd, &val, &current_bit); } static void check_write_coding_bytes(token_t *token, int fd) { char *ignored[] = {"live", "zjmp", "fork", "lfork", NULL}; for (int i = 0; ignored[i]; i++) if (my_streq(token->op, ignored[i])) return; write_coding_bytes(token, fd); } void out_code(token_t **tokens, int fd) { op_t *op; for (int i = 0; tokens[i]; i++) { if (tokens[i]->op == NULL) continue; op = get_op(tokens[i]->op); write(fd, &(op->code), 1); check_write_coding_bytes(tokens[i], fd); out_params(tokens[i], tokens, fd); } } <file_sep>/asm/utils/string_convert.c /* ** EPITECH PROJECT, 2019 ** MUL_snr_engine_2019 ** File description: ** string_convert */ #include "string_convert.h" #include "string_utils.h" #include <stdlib.h> unsigned int stoi(char const *str) { int nb = 0; int i = 0; if (str == NULL) return (0); for (; str[i]; i++) if (str[i] >= '0' && str[i] <= '9') { nb *= 10; nb += str[i] - '0'; } else break; return (nb); } <file_sep>/bonus/corewar/src/main.c /* ** EPITECH PROJECT, 2020 ** CPE_corewar_2019 ** File description: ** main.c */ #include <stdlib.h> #include <stdio.h> #include "vm.h" #include "chain_list.h" #include "console.h" int main(int argc, char **argv) { vm_t *vm = vm_init(argc, argv); execution_loop(vm); return 0; } <file_sep>/bonus/corewar/src/disassembler/get_next_instruction.c /* ** EPITECH PROJECT, 2020 ** CPE_corewar_2019 ** File description: ** get binary arguments */ #include <stdlib.h> #include "op.h" #include "vm.h" static int *get_args_type(char bytecode, int *args_len) { int default_config[MAX_ARGS_NUMBER] = {DIR_SIZE, 0, 0, 0}; char bitshift_val = 6; char val = 0; for (int i = 0; i < MAX_ARGS_NUMBER; ++i) args_len[i] = default_config[i]; if (bytecode == 0) return (args_len); for (int i = 0; bitshift_val > 0; ++i) { val = (bytecode >> bitshift_val); bitshift_val -= 2; if (val == 0x01) args_len[i] = 1; else if (val == 0x02) args_len[i] = DIR_SIZE; if (val == 0x03) args_len[i] = IND_SIZE; } return (args_len); } static int set_instruction_exec_time(process_t *proc, char code) { proc->instruction->instruction_code = code; for (int i = 0; op_tab[i].code != 0; ++i) { if (code == op_tab[i].code) { proc->cycles = op_tab[i].nbr_cycles; return (0); } } proc->cycles = 1; proc->instruction->instruction_code = INVALID_INSTRUCTION; return (1); } void get_next_instruction(process_t *proc, unsigned char *mem) { char code = mem[proc->pc++ % MEM_SIZE]; int no_bytecode[4] = {1, 9, 15, 12}; char bytecode = 0; int i = 0; proc->pc = proc->pc % MEM_SIZE; reset_instruction(proc->instruction); if (set_instruction_exec_time(proc, code) == 1) return; for (i = 0; i < 4; ++i) if (code == no_bytecode[i]) break; if (i == 4) bytecode = mem[(proc->pc++) % MEM_SIZE]; get_args_type(bytecode, proc->instruction->arg_types); fetch_instruction(proc->instruction->arg_types, proc, mem); } <file_sep>/asm/core/validate_tokens.c /* ** EPITECH PROJECT, 2020 ** asm ** File description: ** validate_tokens */ #include "tokenizer.h" #include "string_utils.h" #include "console.h" #include "output.h" #include <stdlib.h> void validate_label(char const *label, int *error) { if (label != NULL && (my_strissub(label, LABEL_CHARS) == 0 || label[0] == 0)) { my_puterr("Error: label '"); my_puterr(label); my_puterr("' is not valid.\n"); (*error)++; } } static int validate_args_count(param_t **params, op_t *op, int *error) { int args_count = 0; for (; params[args_count]; args_count++); if (args_count != op->args_count) { my_puterr("Error: parameters count for op '"); my_puterr(op->mnemonique); my_puterr("' is not valid.\n"); (*error)++; return (-1); } return (0); } int validate_token(token_t *token) { int error = 0; op_t *op = get_op(token->op); validate_label(token->label, &error); if (token->op == NULL) return (error); if (op == NULL) { my_puterr("Error: op '"); my_puterr(token->op); my_puterr("' is not valid.\n"); error++; return (error); } if (validate_args_count(token->params, op, &error) < 0) return (error); return (error); } int validate_tokens(token_t **tokens) { int error = 0; for (int i = 0; tokens[i]; i++) error -= validate_token(tokens[i]); error -= validate_labels(tokens); error -= validate_parameters(tokens); return (error); } <file_sep>/corewar/src/utils/string_utils1.c /* ** EPITECH PROJECT, 2020 ** asm ** File description: ** string_utils1 */ #include "string_utils.h" #include <stddef.h> void my_strendat(char *str, char val) { if (str == NULL) return; for (int i = 0; str[i]; i++) if (str[i] == val) { str[i] = 0; break; } } int my_strendswith(char const *str, char const *end) { int len = my_strlen(str); int len_end = my_strlen(end); if (str == NULL || end == NULL) return (-1); if (len < len_end) return (0); for (int i = 0; i < len_end; i++) if (str[len - len_end + i] != end[i]) return (0); return (1); } int my_strstartswith(char const *str, char const *start) { int len = my_strlen(str); int len_start = my_strlen(start); if (str == NULL || start == NULL) return (-1); if (len < len_start) return (0); for (int i = 0; i < len_start; i++) if (str[i] != start[i]) return (0); return (1); } static int contains(char const *allowed, char val) { for (int i = 0; allowed[i]; i++) if (val == allowed[i]) return (1); return (0); } int my_strissub(char const *str, char const *allowed) { if (str == NULL || allowed == NULL) return (-1); for (int i = 0; str[i]; i++) if (contains(allowed, str[i]) == 0) return (0); return (1); } <file_sep>/bonus/corewar/src/operations/aff.c /* ** EPITECH PROJECT, 2020 ** Epitech ** File description: ** aff */ #include "vm.h" #include "string_convert.h" #include "console.h" #include <stdlib.h> void op_aff(process_t *process, vm_t *vm) { int reg = process->instruction->params[0]; char *nb = NULL; if (process->instruction->arg_types[0] != 1 || (reg > 15 && reg < 0)) return; nb = itos(process->reg[reg], 0); my_putstr(nb); } <file_sep>/bonus/corewar/src/vm/error_handling.c /* ** EPITECH PROJECT, 2020 ** CPE_corewar_2019 ** File description: ** error_handling */ #include "chain_list.h" #include "vm.h" #include "string_utils.h" #include "console.h" #include <stdlib.h> void put_usage(void) { my_putstr("USAGE\n./corewar"); my_putstr(" [-dump nbr_cycle] [[-n prog_number] [-a load_address]"); my_putstr("prog_name] ...\nDESCRIPTION\n-dump nbr_cycle dumps the memory"); my_putstr("after the number_cycle execution (if the round isn't\nalready"); my_putstr("over) with the following format 32bytes/line\nin hexadecimal"); my_putstr("AOBCDEFE1DD3...)\n-n prog_number sets the next program's"); my_putstr("number. By default, the first , the first free number in the"); my_putstr("parameter order\n-a load_address sets the next program's"); my_putstr("loading address. When no adress is specified,\n optimize the"); my_putstr("adresses so that the processes are as far away\nfrom each"); my_putstr("other as possible. the adresses are MEM_SIZE modulo.\n"); } static void check_flags(char *argv[]) { char *triggers[] = {"-dump", "-a", "-n"}; for (int i = 0; argv[i]; i++) { if (argv[i][0] == '-') { if (my_streq(triggers[0], argv[i]) || my_streq(triggers[1], argv[i]) || my_streq(triggers[2], argv[i])) continue; else { my_puterr("Invalid Flags\n\n"); put_usage(); exit(84); } } } } void error_handling(char *argv[], int ac, vm_t *vm) { if (ac > 23) { my_puterr("Too much arguments on binairie call\n\n"); put_usage(); exit(84); } if (ac == 2 && my_streq(argv[1], "-h")) { put_usage(); exit(0); } check_flags(argv); }<file_sep>/bonus/asm/core/output_params.c /* ** EPITECH PROJECT, 2020 ** asm ** File description: ** output_params */ #include "bin_utils.h" #include "compiler.h" #include "output.h" #include "tokenizer.h" #include "label.h" #include <unistd.h> static int get_val(param_t *param, token_t **tokens) { unsigned int val = param->val.ui; if (param->type & T_LAB) return (get_label_address(tokens, param->val.str)); return (val); } static void out_param(param_t *param, token_t **tokens, int fd) { unsigned int val = get_val(param, tokens); unsigned int val_i = swap_endianness(val); unsigned short val_s = swap_endianness_short(val); unsigned char val_c = val; if (param->type & T_IND) write(fd, &val_s, 2); if (param->type & T_REG) write(fd, &val_c, 1); if (param->type & T_DIR) write(fd, &val_i, 4); } void out_params(token_t *token, token_t **tokens, int fd) { for (int i = 0; token->params[i]; i++) out_param(token->params[i], tokens, fd); } <file_sep>/corewar/src/operations/lldi.c /* ** EPITECH PROJECT, 2020 ** Epitech ** File description: ** lldi */ #include "vm.h" static int take_info(process_t *process, vm_t *vm) { int nb = process->instruction->params[0]; if (process->instruction->arg_types[0] == 1 && nb < 16 && nb >= 0) return (process->reg[nb]); else if (process->instruction->arg_types[0] == 2) return (nb); else return (mem_to_int(vm->mem, process->pc + nb % MEM_SIZE, 2)); return (-8484); } static int add_nb(int x, int y, process_t *process, vm_t *vm) { int nb = process->instruction->params[0]; if (process->instruction->arg_types[1] == 1 && (nb >= 16 || nb < 0)) return (-8484); if (process->instruction->arg_types[1] != 3) { if (process->instruction->arg_types[1] == 1) return (x + process->instruction->params[y]); else return (x + y); } return (-8484); } static int load_to_register(int x, int y, process_t *process, vm_t *vm) { if (process->instruction->arg_types[2] != 1) return (-8484); else if (process->instruction->arg_types[2] == 1 && (y >= 16 || y < 0)) return (-8484); else { process->reg[y] = mem_to_int(vm->mem, process->pc + x, 4); } return (0); } void op_lldi(process_t *process, vm_t *vm) { int nb = take_info(process, vm); int nb_two = process->instruction->params[1]; int registre = process->instruction->params[2]; int check = 0; int result = 0; if (nb == -8484) { process->carry = 0; return; } result = add_nb(nb, nb_two, process, vm); if (result == -8484) { process->carry = 0; return; } check = load_to_register(result, registre, process, vm); if (check == -8484) process->carry = 0; else process->carry = 1; } <file_sep>/bonus/corewar/src/utils/create_champ.c /* ** EPITECH PROJECT, 2020 ** CPE_corewar_2019 ** File description: ** create_champ */ #include <stdlib.h> #include "vm.h" #include "console.h" void create_champ_processes(list_t *champions) { list_t *temp = champions; champion_t *champ = NULL; process_t *new_process = NULL; while (temp) { champ = temp->data; new_process = init_process(champ->prog_number, champ->load_adress, champ->prog_number); champ->process = create_list(new_process, NULL); if (!champ->process) { my_puterr("Process initialization failed\n"); exit(84); } temp = temp->next; } } champion_t *create_champ(void) { champion_t *champ = malloc(sizeof(champion_t)); champ->load_adress = -1; champ->path = NULL; champ->prog_number = -1; champ->prog_size = -1; champ->program = NULL; champ->process = NULL; champ->live = WAITING_LIVE; return (champ); }<file_sep>/asm/utils/console.c /* ** EPITECH PROJECT, 2020 ** asm ** File description: ** console */ #include "console.h" #include "string_utils.h" #include <unistd.h> static void write_to_fd(char const *str, int fd) { int len = my_strlen(str); if (len < 0 || fd < 0) return; write(fd, str, len); } void my_putstr(char const *str) { write_to_fd(str, 1); } void my_puterr(char const *str) { write_to_fd(str, 2); } <file_sep>/bonus/asm/core/path.c /* ** EPITECH PROJECT, 2020 ** asm ** File description: ** path */ #include "path.h" #include "string_utils.h" #include <stdlib.h> char *get_output_path(char const *input_path) { int len = my_strlen(input_path); char *new = malloc(len + 4 + 1); char const *end = ".cor"; int i = 0; for (; i < len; i++) new[i] = input_path[i]; if (my_strendswith(input_path, ".s")) i -= 2; for (int j = 0; end[j]; j++) new[i++] = end[j]; new[i] = 0; return (new); } <file_sep>/corewar/src/vm/update.c /* ** EPITECH PROJECT, 2020 ** CPE_corewar_2019 ** File description: ** update champ */ #include "op.h" #include "vm.h" #include "chain_list.h" #include <stdlib.h> static void exec_instruct(process_t *process, vm_t *vm) { void (*instruct[])(process_t *, vm_t *) = {op_live, op_ld, op_st, op_add, op_sub, op_and, op_or, op_xor, op_zjmp, op_ldi, op_sti, op_fork, op_lld, op_lldi, op_lfork, op_aff}; for (int i = 0; i <= 16; i++) { if (i + 1 == process->instruction->instruction_code) instruct[i](process, vm); } } static void update_process(process_t *process, vm_t *vm) { if (process->cycles == 0) { exec_instruct(process, vm); get_next_instruction(process, vm->mem); } else process->cycles -= 1; } void update(vm_t *vm) { champion_t *champ_temp = NULL; for (list_t *champ = vm->champ; champ != NULL; champ = champ->next) { champ_temp = champ->data; for (list_t *process = champ_temp->process; process != NULL; process = process->next) update_process(process->data, vm); } } <file_sep>/bonus/corewar/src/disassembler/fetch_params.c /* ** EPITECH PROJECT, 2020 ** CPE_corewar_2019 ** File description: ** fetch params in memory or registers */ #include "op.h" #include "vm.h" static int fetch_register(process_t *proc, unsigned char *mem) { int reg_number = 0; reg_number = mem[proc->pc++ % MEM_SIZE]; reg_number -= 1; return (reg_number); } static int fetch_indirect(process_t *proc, unsigned char *mem) { int adress = 0; int bitshift_val = 8; for (int i = 0; i < IND_SIZE; ++i) { adress += mem[proc->pc++ % MEM_SIZE] << bitshift_val; bitshift_val -= 8; } return (adress); } static int fetch_direct(process_t *proc, unsigned char *mem) { int arg = 0; int bitshift_val = 24; for (int i = 0; i < DIR_SIZE; ++i) { arg += mem[proc->pc++ % MEM_SIZE] << bitshift_val; bitshift_val -= 8; } return (arg); } void fetch_instruction(int *arg_len, process_t *proc, unsigned char *mem) { for (int i = 0; arg_len[i] != 0 && i < MAX_ARGS_NUMBER; ++i) { if (arg_len[i] == 1) proc->instruction->params[i] = fetch_register(proc, mem); else if (arg_len[i] == DIR_SIZE) proc->instruction->params[i] = fetch_direct(proc, mem); if (arg_len[i] == IND_SIZE) proc->instruction->params[i] = fetch_indirect(proc, mem); } } <file_sep>/bonus/corewar/src/operations/operation1.c /* ** EPITECH PROJECT, 2020 ** CPE_corewar_2019 ** File description: ** operation1 */ #include "op.h" #include "vm.h" static void op_or_check(process_t *process, vm_t *vm, int *info) { for (int i = 0; i < 2; i++) { if (process->instruction->arg_types[i] == 1 && (process->instruction->params[i] > 0 || process->instruction->params[i] < 15)) { process->carry = 0; return; } } if (process->instruction->arg_types[2] != 1 && (process->instruction->params[2] > 0 || process->instruction->params[2] < 15)) process->carry = 0; else { process->carry = 1; process->reg[2] = info[0] | info[1]; } } void op_or(process_t *process, vm_t *vm) { int info[] = {0, 0}; for (int i = 0; i < 2; i++) { if (process->instruction->arg_types[i] == 1) info[i] = process->reg[i]; if (process->instruction->arg_types[i] == 2) info[i] = process->instruction->params[i]; if (process->instruction->arg_types[i] == 3) info[i] = mem_to_int(vm->mem, process->pc + process->instruction->params[i] % IDX_MOD, REG_SIZE); op_or_check(process, vm, info); } } static void op_xor_check(process_t *process, vm_t *vm, int *info) { for (int i = 0; i < 2; i++) { if (process->instruction->arg_types[i] == 1 && (process->instruction->params[i] > 0 || process->instruction->params[i] < 15)) { process->carry = 0; return; } } if (process->instruction->arg_types[2] != 1 && (process->instruction->params[2] > 0 || process->instruction->params[2] < 15)) process->carry = 0; else { process->carry = 1; process->reg[2] = info[0] ^ info[1]; } } void op_xor(process_t *process, vm_t *vm) { int info[] = {0, 0}; for (int i = 0; i < 2; i++) { if (process->instruction->arg_types[i] == 1) info[i] = process->reg[i]; if (process->instruction->arg_types[i] == 2) info[i] = process->instruction->params[i]; if (process->instruction->arg_types[i] == 3) info[i] = mem_to_int(vm->mem, process->pc + process->instruction->params[i] % IDX_MOD, REG_SIZE); op_xor_check(process, vm, info); } }<file_sep>/corewar/include/chain_list.h /* ** EPITECH PROJECT, 2020 ** CPE_corewar_2019 ** File description: ** chain_list */ #pragma once typedef struct list_s { struct list_s *next; char *name; void *data; int id; } list_t; list_t *create_list(void *data, char *name); list_t *list_append(list_t *list, void *data, char *name); void list_remove(list_t **list, int id); int list_find(list_t *list, char *name); void free_list(list_t *list);<file_sep>/corewar/src/utils/chain_list.c /* ** EPITECH PROJECT, 2020 ** CPE_corewar_2019 ** File description: ** chai_list */ #include <stdlib.h> #include <stdio.h> #include "chain_list.h" #include "string_utils.h" list_t *create_list(void *data, char *name) { list_t *list = malloc(sizeof(list_t)); if (list == NULL) return (NULL); list->id = 0; list->data = data; list->name = name; list->next = NULL; return (list); } list_t *list_append(list_t *list, void *data, char *name) { list_t *new = malloc(sizeof(list_t)); if (new == NULL) return (NULL); new->data = data; new->next = list; new->name = name; new->id = list->id + 1; return (new); } void list_remove(list_t **list, int id) { list_t *prev = NULL; list_t *temp = *list; if (temp->id == id) { *list = temp->next; free(temp->data); free(temp); return; } for (list_t *l = *list; l != NULL; l = l->next) { if (l->id == id) { prev->next = l->next; temp = l; free(temp->data); free(temp); return; } prev = l; } } int list_find(list_t *list, char *name) { list_t *new; for (list_t *l = list; l != NULL; l = l->next) { if (my_streq(name, l->name)) { new = l; } } return (new->id); } void free_list(list_t *list) { list_t *temp; while (list != NULL) { temp = list; list = list->next; free(temp->data); free(temp); } }<file_sep>/asm/include/bin_utils.h /* ** EPITECH PROJECT, 2020 ** asm ** File description: ** bin_utils */ #pragma once int swap_endianness(int val); short swap_endianness_short(short val); <file_sep>/bonus/corewar/src/operations/zjmp.c /* ** EPITECH PROJECT, 2020 ** Epitech ** File description: ** zjmp */ #include "vm.h" void op_zjmp(process_t *process, vm_t *vm) { int nb = process->instruction->params[0]; if (process->carry == 1 && process->instruction->arg_types[0] == 2) { process->pc = process->pc + nb % IDX_MOD; } } <file_sep>/corewar/include/str_test.h /* ** EPITECH PROJECT, 2020 ** CPE_corewar_2019 ** File description: ** str_test */ #pragma once int is_number(char *str);<file_sep>/asm/utils/bin_utils.c /* ** EPITECH PROJECT, 2020 ** asm ** File description: ** bin_utils */ #include "bin_utils.h" int swap_endianness(int val) { val = ((val << 8) & 0xFF00FF00) | ((val >> 8) & 0xFF00FF ); return (val << 16) | ((val >> 16) & 0xFFFF); } short swap_endianness_short(short val) { return ((val >> 8) | (val << 8)); } <file_sep>/asm/utils/string_utils.c /* ** EPITECH PROJECT, 2020 ** asm ** File description: ** string_utils */ #include "string_utils.h" #include <stdlib.h> int my_strlen(char const *str) { int len = 0; if (str == NULL) return (-1); for (; str[len] != 0; ++len); return (len); } int my_streq(char const *a, char const *b) { int len_a = my_strlen(a); int len_b = my_strlen(b); if (len_a == -1 && len_b == -1) return (1); if (len_a != len_b) return (0); for (int i = 0; i < len_a; i++) if (a[i] != b[i]) return (0); return (1); } char *my_strdup(char const *str) { char *new; if (str == NULL) return (NULL); new = malloc(my_strlen(str) + 1); if (new == NULL) return (NULL); for (int i = 0; str[i]; i++) new[i] = str[i]; new[my_strlen(str)] = 0; return (new); } int is_whitespace(char val) { char *whitespaces = " \t\n"; for (int i = 0; whitespaces[i]; i++) if (whitespaces[i] == val) return (1); return (0); } char *my_strtrim(char const *str) { int start = 0; int end = my_strlen(str); char *new; if (str == NULL || end <= 0) return (NULL); while (end > 0 && is_whitespace(str[end])) end--; while (start < end && is_whitespace(str[start])) start++; new = malloc(end - start + 1); if (new == NULL) return (NULL); for (int i = 0; i < end - start; i++) new[i] = str[start + i]; new[end - start] = 0; return (new); } <file_sep>/corewar/include/string_utils.h /* ** EPITECH PROJECT, 2020 ** asm ** File description: ** string_utils */ #pragma once int my_strlen(char const *str); int my_streq(char const *a, char const *b); char *my_strdup(char const *str); int is_whitespace(char val); char *my_strtrim(char const *str); void my_strendat(char *str, char val); int my_strendswith(char const *str, char const *end); int my_strstartswith(char const *str, char const *start); int my_strissub(char const *str, char const *allowed); char *my_revstr(char *str); int arr_len(char **arr);<file_sep>/bonus/asm/include/console.h /* ** EPITECH PROJECT, 2020 ** asm ** File description: ** console */ #pragma once void my_putstr(char const *str); void my_puterr(char const *str); <file_sep>/bonus/asm/core/file.c /* ** EPITECH PROJECT, 2020 ** asm ** File description: ** file */ #include "file.h" #include "compiler.h" #include "console.h" #include "string_utils.h" #include <stdlib.h> #include <stdio.h> static void handle_line(char *line, char **res, int *i) { char *trim; my_strendat(line, COMMENT_CHAR); my_strendat(line, '\n'); trim = my_strtrim(line); if (trim == NULL) return; if (my_strlen(trim) < 1) { free(trim); return; } res[*i] = trim; (*i)++; } char **read_file(char const *path) { FILE *file = fopen(path, "r"); char *line = NULL; size_t len = 0; char **res; int i = 0; if (file == NULL) return (NULL); res = malloc(sizeof(char *) * 1024); if (res == NULL) { fclose(file); return (NULL); } while (getline(&line, &len, file) != -1) handle_line(line, res, &i); res[i] = NULL; if (line != NULL) free(line); fclose(file); return (res); } <file_sep>/bonus/corewar/src/vm/execution_loop.c /* ** EPITECH PROJECT, 2020 ** CPE_corewar_2019 ** File description: ** game/execution loop */ #include "op.h" #include "vm.h" #include "console.h" #include <stdlib.h> #include <unistd.h> #include <ncurses.h> static int champions_alive(vm_t *vm) { list_t *list = vm->champ; champion_t *temp = NULL; int alive = 0; while (list) { temp = list->data; if (temp->live != DEAD) ++alive; list = list->next; } return (alive); } static void check_processes(list_t **list_process) { list_t *temp = *list_process; list_t *prev = NULL; process_t *handler = temp->data; if (temp != NULL && handler->live == 0) { *list_process = temp->next; destroy_process(handler); free(temp); return; } while (temp != NULL && handler->live != 0) { prev = temp; temp = temp->next; if (temp != NULL) handler = temp->data; } if (temp == NULL) return; prev->next = temp->next; destroy_process(handler); free(temp); } static void kill_processes(vm_t *vm, int cycle, int *cycle_to_die) { champion_t *handler = NULL; if (cycle == 0) return; else if (cycle % *cycle_to_die != 0) return; *cycle_to_die -= CYCLE_DELTA; for (list_t *champ = vm->champ; champ != NULL; champ = champ->next) { handler = champ->data; check_processes(&handler->process); if (handler->live != LIVE) handler->live = DEAD; } } static void print_winner(list_t *list) { list_t *temp = list; champion_t *handler = NULL; while (temp) { handler = temp->data; if (handler->live == LIVE) { my_putstr("The player "); my_put_nbr(handler->prog_number); my_putstr("("); my_putstr(handler->path); my_putstr(")has won.\n"); return; } temp = temp->next; } my_putstr("No one made a live, no winner\n"); } void execution_loop(vm_t *vm) { int cycle = 0; int cycles_to_die = CYCLE_TO_DIE; while (champions_alive(vm) > 1) { kill_processes(vm, cycle, &cycles_to_die); update(vm); if (vm->dump_cycle != -1 && cycle % vm->dump_cycle == 0) dump_memory(vm->mem); ++cycle; getch(); print_colorized_mem(vm->color_mem, vm->mem); usleep(1000); } print_winner(vm->champ); free_mem(vm); }<file_sep>/corewar/src/operations/sti.c /* ** EPITECH PROJECT, 2020 ** Epitech ** File description: ** sti */ #include "vm.h" static int take_info_register(process_t *process, vm_t *vm) { int nb = process->instruction->params[0]; if (process->instruction->arg_types[0] == 1 && nb < 16 && nb >= 0) return (process->reg[nb]); return (-8484); } static int take_info(process_t *process, vm_t *vm) { int nb = process->instruction->params[1]; if (process->instruction->arg_types[1] == 1 && (nb >= 16 || nb < 0)) return (-8484); if (process->instruction->arg_types[1] == 1 && nb < 16 && nb >= 0) return (process->reg[nb]); else if (process->instruction->arg_types[1] == 2) return (nb); else return (mem_to_int(vm->mem, process->pc + nb % IDX_MOD, 4)); return (-8484); } static int take_info_two(process_t *process, vm_t *vm) { int nb = process->instruction->params[2]; if (process->instruction->arg_types[1] == 1 && nb < 16 && nb >= 0) return (process->reg[nb]); else if (process->instruction->arg_types[1] == 2) return (nb); else return (-8484); return (-8484); } void op_sti(process_t *process, vm_t *vm) { int registre = take_info_register(process, vm); int nb = take_info(process, vm); int nb_two = take_info_two(process, vm); if (registre == -8484 || nb == -8484 || nb_two == -8484) return; int_to_mem(vm->mem, process->pc + (nb + nb_two) % IDX_MOD, 4); } <file_sep>/asm/Makefile ## ## EPITECH PROJECT, 2020 ## CPE_corewar_2019 ## File description: ## Makefile ## CFLAGS = -Iinclude -Wall LDFLAGS += EXEC = asm SRC = main.c \ core/compiler.c \ core/tokenizer.c \ core/line_tokenizer.c \ core/param_tokenizer.c \ core/validate_tokens.c \ core/validate_labels.c \ core/validate_parameters.c \ core/output.c \ core/output_params.c \ core/file.c \ core/path.c \ core/prog_size.c \ core/label.c \ utils/string_utils.c \ utils/string_utils1.c \ utils/string_convert.c \ utils/array_utils.c \ utils/bin_utils.c \ utils/console.c OBJ = $(SRC:.c=.o) all: $(EXEC) $(EXEC): $(OBJ) gcc -o $(EXEC) $(OBJ) $(LDFLAGS) clean: rm -f $(OBJ) fclean: clean rm -f $(EXEC) re: fclean all cdb: compiledb make re <file_sep>/corewar/src/disassembler/mem_operations.c /* ** EPITECH PROJECT, 2020 ** CPE_corewar_2019 ** File description: ** operations in memory */ #include "op.h" #include "vm.h" void load_prog_to_mem(unsigned char *program, unsigned char *mem, int adress, int prog_size) { if (adress < 0) adress *= -1; for (int i = 0; i < prog_size; ++i) mem[(adress + i) % MEM_SIZE] = program[i]; } int mem_to_int(unsigned char *mem, int adress, int read_size) { int arg = 0; int bitshift_val = 8 * (read_size - 1); if (adress < 0) adress *= -1; for (int i = 0; i < read_size; ++i) { arg += mem[adress++ % MEM_SIZE] << bitshift_val; bitshift_val -= 8; } return (arg); } void int_to_mem(unsigned char *mem, int adress, int value) { int bitshift_val = 24; if (adress < 0) adress *= -1; for (int i = 0; i < 4; ++i) { mem[adress++ % MEM_SIZE] = value >> bitshift_val & 0xFF; bitshift_val -= 8; } }<file_sep>/corewar/src/operations/live.c /* ** EPITECH PROJECT, 2020 ** Epitech ** File description: ** live */ #include "vm.h" #include "string_convert.h" #include "console.h" #include <stdlib.h> void op_live(process_t *process, vm_t *vm) { int id = process->instruction->params[0]; champion_t *tmp = NULL; for (list_t *l = vm->champ; l != NULL; l = l->next) { tmp = l->data; if (l->id == id && tmp->live != DEAD) { tmp->live = 1; my_putstr("Le joueur "); my_putstr(itos(id, 0)); my_putstr(" est en vie\n"); } } process->live = 1; } <file_sep>/bonus/asm/utils/array_utils.c /* ** EPITECH PROJECT, 2020 ** asm ** File description: ** array_utils */ #include "array_utils.h" #include <stdlib.h> int array_len(void **arr) { int len = 0; if (arr == NULL) return (-1); for (; arr[len] != NULL; len++); return (len); } void custom_free_array(void **arr, void (*func)(void *)) { if (arr == NULL) return; for (int i = 0; arr[i]; i++) if (arr[i] != NULL) func(arr[i]); free(arr); } void free_array(void **arr) { custom_free_array(arr, free); } <file_sep>/asm/include/prog_size.h /* ** EPITECH PROJECT, 2020 ** asm ** File description: ** prog_size */ #pragma once #include "tokenizer.h" int get_prog_size(token_t **tokens, char const *end_label); <file_sep>/bonus/asm/include/tokenizer.h /* ** EPITECH PROJECT, 2020 ** asm ** File description: ** tokenizer */ #pragma once #include "compiler.h" typedef struct { char *label; char *op; param_t **params; } token_t; void free_token(void *t); token_t **tokenize(char **lines); token_t *tokenize_line(char *line); param_t *tokenize_param(char *str, int *error); int validate_tokens(token_t **tokens); int validate_labels(token_t **tokens); int validate_parameters(token_t **tokens); <file_sep>/bonus/corewar/src/operations/ld.c /* ** EPITECH PROJECT, 2020 ** Epitech ** File description: ** ld */ #include "vm.h" void op_ld(process_t *process, vm_t *vm) { int registre = process->instruction->params[1]; int nb = process->instruction->params[0]; int pc = process->pc; if (process->instruction->arg_types[0] == 3) nb = mem_to_int(vm->mem, pc + nb % IDX_MOD, 4); if (process->instruction->arg_types[0] == 1 && process->instruction->arg_types[1] != 1 && (registre > 15 || registre < 0)) process->carry = 0; else { process->reg[registre] = nb; process->carry = 1; } } <file_sep>/bonus/asm/core/line_tokenizer.c /* ** EPITECH PROJECT, 2020 ** asm ** File description: ** line_tokenizer */ #include "tokenizer.h" #include "string_utils.h" #include "compiler.h" #include <stdlib.h> static int handle_label(token_t *token, char *line) { char *tmp = my_strdup(line); token->label = NULL; if (tmp == NULL) return (-1); for (int i = 0; tmp[i]; i++) if (is_whitespace(tmp[i])) { tmp[i] = 0; break; } if (tmp[my_strlen(tmp) - 1] != LABEL_CHAR) { free(tmp); return (0); } tmp[my_strlen(tmp) - 1] = 0; token->label = tmp; return (my_strlen(tmp) + 1); } static int handle_op(token_t *token, char *line) { char *op = malloc(my_strlen(line) + 1); int i = 0; if (op == NULL) return (-1); while (line[i] && !is_whitespace(line[i])) { op[i] = line[i]; i++; } op[i] = 0; token->op = op; return (my_strlen(op)); } static int handle_params(token_t *token, char *line, int *error) { char new[128]; int new_i = 0; int params_i = 0; token->params = malloc(sizeof(param_t *) * 64); if (token->params == NULL) return (-1); for (int i = 0; line[i]; i++) { if (line[i] == SEPARATOR_CHAR) { new[new_i] = 0; new_i = 0; token->params[params_i++] = tokenize_param(my_strtrim(new), error); i++; } new[new_i++] = line[i]; } new[new_i] = 0; token->params[params_i] = tokenize_param(my_strtrim(new), error); token->params[params_i + 1] = 0; return (0); } static int fill_token(token_t *token, char *line, int *error) { int start = 0; int op_len = 0; start = handle_label(token, line); if (start < 0) return (-1); while (line[start] && is_whitespace(line[start])) start++; if (my_strlen(line + start) == 0) return (0); op_len = handle_op(token, line + start); if (op_len == -1) return (-1); start += op_len; while (line[start] && is_whitespace(line[start])) start++; if (handle_params(token, line + start, error) < 0) return (-1); return (0); } token_t *tokenize_line(char *line) { token_t *token = malloc(sizeof(token_t)); int error = 0; if (token == NULL) return (NULL); token->label = NULL; token->op = NULL; token->params = NULL; if (fill_token(token, line, &error) < 0 || error != 0) { free_token(token); return (NULL); } return (token); } <file_sep>/README.md # Corewar Epitech year-end Project. ASM part is a compiler which transforms champions asm langage to binary (.cor). The virtual machine ('corewar' binary) takes between 2 and 4 .cor binaries (champions) and run them. The champions execute instructions on the same memory block (6144 bytes). Champions have to execute the live instruction at least one time per CYCLE_TO_DIE or they die. The Winner is the last one to execute live instructions. # ASM You can find some source code of asm here : ./asm/src It'll transform those .s in .cor that can be interpreted by the machine. You can create your own champ to make him fight against others champs. # VM The machine will run your champion and the others to make them fight each others. Champions programs are loaded into memory at the beginning, after this instructions are fetched and executed for each program, each instruction needs a different number of cycles to be executed. For more precisions have a look at the Corewar_subject.pdf The bonus file is an unfinished visual interface coded using the ncurses library Realised with: <NAME> <NAME> <NAME> <file_sep>/bonus/corewar/src/vm/ncurses.c /* ** EPITECH PROJECT, 2020 ** CPE_corewar_2019 ** File description: ** ncurses bonus for the corewar project */ #include <stdlib.h> #include <ncurses.h> #include "chain_list.h" #include "vm.h" #include "console.h" static void print_colors(int *x, int *y, unsigned char *aff_mem, unsigned char *mem) { char *hexa = "0123456789ABCDEF"; for (int i = 0; i < 178; ++i) mvprintw(*y - 1, *x + i, "_"); mvprintw(*y, (*x)++, "|"); attroff(COLOR_PAIR(84)); for (int i = 0; i < MEM_SIZE; ++i) { if (i % 176 == 0 && i != 0) { attron(COLOR_PAIR(84)); mvprintw(*y, *x, "|"); *y += 1; *x = 10; mvprintw(*y, (*x)++, "|"); attroff(COLOR_PAIR(84)); } attron(COLOR_PAIR(aff_mem[i])); mvprintw(*y, (*x)++, "%c%c", hexa[(mem[i] >> 4)], hexa[(mem[i] & 0xF)]); attroff(COLOR_PAIR(aff_mem[i])); } } void print_colorized_mem(unsigned char *aff_mem, unsigned char *mem) { int x = 10; int y = 9; short box[2] = {COLOR_BLACK, COLOR_WHITE}; init_pair(84, box[1], box[0]); attron(A_BOLD); attron(COLOR_PAIR(84)); print_colors(&x, &y, aff_mem, mem); ++y; x = 10; attron(COLOR_PAIR(84)); for (int i = 0; i < 178; ++i) mvprintw(y, x++, "_"); attroff(COLOR_PAIR(84)); attroff(A_BOLD); refresh(); } void start_ncurses(list_t *champ) { WINDOW *window = initscr(); short color1[4] = {COLOR_RED, COLOR_GREEN, COLOR_YELLOW, COLOR_GREEN}; short color2[4] = {COLOR_BLACK, COLOR_BLACK, COLOR_BLACK, COLOR_GREEN}; int i = 0; if (!window) { my_puterr("Failed to create window\n"); exit(84); } nodelay(window, TRUE); keypad(stdscr, TRUE); curs_set(0); noecho(); start_color(); for (list_t *temp = champ; temp != NULL && i < 4; temp = temp->next) { init_pair(temp->id, color2[i], color1[i]); ++i; } } <file_sep>/bonus/asm/include/string_convert.h /* ** EPITECH PROJECT, 2020 ** asm ** File description: ** string_convert */ #pragma once unsigned int stoi(char const *str); <file_sep>/corewar/src/utils/string_convert.c /* ** EPITECH PROJECT, 2019 ** MUL_snr_engine_2019 ** File description: ** string_convert */ #include "string_convert.h" #include "string_utils.h" #include <stdlib.h> unsigned int stoi(char const *str) { int nb = 0; int i = 0; if (str == NULL) return (0); for (; str[i]; i++) if (str[i] >= '0' && str[i] <= '9') { nb *= 10; nb += str[i] - '0'; } else break; return (nb); } char *itos(int val, int digits) { char *res = malloc(20); int res_i = 0; char *dest_base = "0123456789"; int dest_base_size = my_strlen(dest_base); for (int i = 0; i < digits; i++) res[i] = '0'; res[digits] = 0; res[res_i++] = dest_base[val % dest_base_size]; while (val != 0) res[res_i++] = dest_base[(val /= dest_base_size) % dest_base_size]; if (digits == 0) res[res_i - 1] = 0; my_revstr(res); return res; } char *my_revstr(char *str) { int str_len = my_strlen(str); char temp; for (int i = 0; i < str_len / 2; i++) { temp = str[i]; str[i] = str[str_len - i - 1]; str[str_len - i - 1] = temp; } return (str); } <file_sep>/corewar/include/console.h /* ** EPITECH PROJECT, 2020 ** CPE_corewar_2019 ** File description: ** console */ #pragma once void my_putstr(char const *str); void my_puterr(char const *str); void my_put_nbr(int nb); void my_putchar(char c);<file_sep>/asm/include/path.h /* ** EPITECH PROJECT, 2020 ** asm ** File description: ** path */ #pragma once char *get_output_path(char const *input_path); <file_sep>/bonus/corewar/src/vm/vm_init.c /* ** EPITECH PROJECT, 2020 ** CPE_corewar_2019 ** File description: ** vm_init */ #include <stdlib.h> #include "vm.h" #include "console.h" vm_t *vm_init(int ac, char **argv) { vm_t *vm = malloc(sizeof(champion_t)); unsigned char *memory = malloc(sizeof(char) * MEM_SIZE); unsigned char *color_memory = malloc(sizeof(char) * MEM_SIZE); error_handling(argv, ac, vm); if (!vm || !memory || !color_memory) { my_puterr("Memory allocation failed\n"); exit(84); } for (int i = 0; i < MEM_SIZE; ++i) { memory[i] = 0; color_memory[i] = 0; } vm->mem = memory; vm->color_mem = color_memory; parsing(ac, argv, vm); load_binaries(vm->mem, vm->nb_champ, vm->champ); load_champions_to_mem(vm->champ, vm); create_champ_processes(vm->champ); start_ncurses(vm->champ); return (vm); }<file_sep>/corewar/src/utils/instruction_utils.c /* ** EPITECH PROJECT, 2020 ** CPE_corewar_2019 ** File description: ** manage instruction structure */ #include <stdlib.h> #include "op.h" #include "vm.h" #include "console.h" instruction_t *init_instruction(void) { instruction_t *new = malloc(sizeof(instruction_t)); if (!new) { my_puterr("Memory allocation failed\n"); exit(84); } new->instruction_code = 0; new->arg_types = malloc(sizeof(int) * 4); for (int i = 0; i < 4; ++i) new->arg_types[i] = 0; for (int i = 0; i < MAX_ARGS_NUMBER; ++i) new->params[i] = 0; return (new); } void reset_instruction(instruction_t *instruction) { for (int i = 0; i < 4; ++i) instruction->arg_types[i] = 0; instruction->instruction_code = 0; for (int i = 0; i < MAX_ARGS_NUMBER; ++i) instruction->params[i] = 0; } void destroy_instruction(instruction_t *instruction) { free(instruction->arg_types); free(instruction); }<file_sep>/corewar/src/vm/free_vm.c /* ** EPITECH PROJECT, 2020 ** CPE_corewar_2019 ** File description: ** free memory */ #include <unistd.h> #include <stdlib.h> #include "chain_list.h" #include "vm.h" static void free_champ(champion_t *champ) { list_t *prev; while (champ->process != NULL) { prev = champ->process; champ->process = champ->process->next; destroy_process(prev->data); free(prev->name); free(prev); } free(champ->program); free(champ->path); free(champ); } void free_mem(vm_t *vm) { list_t *prev; free(vm->mem); while (vm->champ != NULL) { prev = vm->champ; vm->champ = vm->champ->next; free_champ(prev->data); free(prev); } free(vm); }<file_sep>/asm/main.c /* ** EPITECH PROJECT, 2020 ** CPE_corewar_2019 ** File description: ** main */ #include "array_utils.h" #include "compiler.h" #include "path.h" #include "string_utils.h" #include "console.h" #include "file.h" #include <stdlib.h> static int usage(void (*put)(char const *), char const *program, int ret) { put("USAGE\n\t"); put(program); put(" file_name[.s]\n\n" "DESCRIPTION\n" "\tfile_name" "\tfile in assembly language to be converted into file_name.cor, an\n" "\t\t\texecutable in the Virtual Machine.\n"); return (ret); } static int error(char const *msg) { my_puterr(msg); my_puterr("\n"); return (84); } int main(int ac, char **av) { char **lines; char *output; int res; if (ac != 2) return (usage(my_puterr, av[0], 84)); if (my_streq(av[1], "-h")) return (usage(my_putstr, av[0], 0)); lines = read_file(av[1]); if (lines == NULL) return (error("Error: could not read input file.")); output = get_output_path(av[1]); res = compile(lines, output); free_array((void **) lines); free(output); return (res); } <file_sep>/corewar/src/operations/op_fork.c /* ** EPITECH PROJECT, 2020 ** CPE_corewar_2019 ** File description: ** op_fork */ #include "vm.h" #include "op.h" #include "chain_list.h" #include <stdlib.h> static champion_t *find_champ(list_t *list, process_t *process) { for (list_t *l = list; l != NULL; l = l->next) { if (l->id == process->champ_nb) return (l->data); } return (NULL); } void op_fork(process_t *process, vm_t *vm) { champion_t *curr = find_champ(vm->champ, process); process_t *new = NULL; list_t *temp = NULL; if (curr == NULL) return; new = init_process(curr->prog_number, process->pc + process->instruction->params[0], curr->prog_number); temp = list_append(curr->process, new, "fork"); temp->next = curr->process; curr->process = temp; load_prog_to_mem(curr->program, vm->mem, curr->load_adress, curr->prog_size); } void op_lfork(process_t *process, vm_t *vm) { champion_t *curr = find_champ(vm->champ, process); process_t *new = NULL; list_t *temp = NULL; if (curr == NULL) return; new = init_process(curr->prog_number, process->pc + process->instruction->params[0], curr->prog_number); temp = list_append(curr->process, new, "fork"); temp->next = curr->process; curr->process = temp; load_prog_to_mem(curr->program, vm->mem, curr->load_adress, curr->prog_size); }<file_sep>/bonus/corewar/src/vm/search_load_adress.c /* ** EPITECH PROJECT, 2020 ** CPE_corewar_2019 ** File description: ** prepare_flag */ #include <stdlib.h> #include "chain_list.h" #include "string_utils.h" #include "str_test.h" #include "console.h" #include "vm.h" #include "string_convert.h" static void err(champion_t *temp) { my_puterr("champion load adress must have arithmetical type\n"); exit(84); } static void search_adress(list_t *list, champion_t *temp, char *argv[], int i) { int k = 0; int is_ok = 0; if (my_streq(argv[i], list->name)) { if (i >= 2 && my_streq(argv[i - 2], "-a")) { k = i - 1; is_ok = 1; } else if (i >= 4 && my_streq(argv[i - 4], "-a")) { k = i - 3; is_ok = 1; } } if (!is_ok) return; if (!is_number(argv[k]) && is_ok) { err(temp); } else { temp->load_adress = stoi(argv[k]) % MEM_SIZE; } } list_t *search_load_adress(list_t *list, char *argv[]) { champion_t *temp; for (list_t *l = list; l != NULL; l = l->next) { for (int i = 0; argv[i]; i++) { temp = l->data; search_adress(l, temp, argv, i); } } return (list); }<file_sep>/corewar/champions/test_corewar.c char *mem = malloc(sizeof(char) * MEM_SIZE); process_t *proc = init_process(3); if (!mem) exit(84); for (int i = 0; i < MEM_SIZE; ++i) mem[i] = 0; mem[0] = 0b00000001; mem[1] = 0b00000000; mem[2] = 0b00000000; mem[3] = 0b00000000; mem[4] = 0b00000010; mem[5] = 0b00010000; mem[6] = 0b01000000; mem[7] = 0b00000001; get_next_instruction(proc, mem); printf("proc pc = %d, cycles = %d, code = %d\n", proc->pc, proc->cycles, proc->instruction->instruction_code); for (int i = 0; i < MAX_ARGS_NUMBER; ++i) printf("instruction param = %d\n", proc->instruction->params[i]); get_next_instruction(proc, mem); printf("proc pc = %d, cycles = %d, code = %d\n", proc->pc, proc->cycles, proc->instruction->instruction_code); for (int i = 0; i < MAX_ARGS_NUMBER; ++i) printf("instruction param = %d\n", proc->instruction->params[i]); <file_sep>/asm/core/validate_labels.c /* ** EPITECH PROJECT, 2020 ** asm ** File description: ** validate_labels */ #include "string_utils.h" #include "tokenizer.h" #include "console.h" #include <stdlib.h> static int validate_label_for_param(param_t *param, char **labels) { if ((param->type & T_LAB) == 0) return (0); for (int i = 0; labels[i]; i++) if (my_streq(labels[i], param->val.str)) return (0); my_puterr("Error: label '"); my_puterr(param->val.str); my_puterr("' used but not defined.\n"); return (1); } static int validate_labels_for_token(token_t *token, char **labels) { int error = 0; for (int i = 0; token->params[i]; i++) error += validate_label_for_param(token->params[i], labels); return (error); } int validate_labels(token_t **tokens) { char *labels[256]; int labels_i = 0; int error = 0; for (int i = 0; tokens[i]; i++) if (tokens[i]->label != NULL) labels[labels_i++] = tokens[i]->label; labels[labels_i] = 0; for (int i = 0; tokens[i]; i++) if (tokens[i]->op != NULL) error += validate_labels_for_token(tokens[i], labels); return (error); } <file_sep>/Makefile ## ## EPITECH PROJECT, 2020 ## CPE_corewar_2019 ## File description: ## Makefile ## all: cd asm && $(MAKE) cd corewar && $(MAKE) clean: cd asm && $(MAKE) clean cd corewar && $(MAKE) clean fclean: cd asm && $(MAKE) fclean cd corewar && $(MAKE) fclean re: fclean all cdb: cd asm && $(MAKE) cdb cd corewar && $(MAKE) cdb <file_sep>/corewar/src/utils/string_utils2.c /* ** EPITECH PROJECT, 2020 ** CPE_corewar_2019 ** File description: ** string_utils2 */ #include <stdlib.h> int arr_len(char **arr) { int total = 0; for (int i = 0; arr[i] != NULL; i++) { total++; } return (total); }
a577fa0a0ac4fc226244da7da74a0b0ff67b0e5c
[ "Markdown", "C", "Makefile" ]
71
C
ArthurRbn/Corewar
e7e47387f5612e0019be1e4a7a84db12c541f2ba
a9fc76d8166dcf63a8a62ae6e2665ee52456de6b
refs/heads/master
<file_sep>package com.natali007.sixthsense; import java.util.ArrayList; import java.util.List; import com.natali007.sixthsense.R; import android.app.Activity; import android.os.Bundle; import android.widget.ArrayAdapter; import android.widget.ListView; public class History extends Activity { private ArrayList<String> hist; private ArrayAdapter <String> adapt; private ListView listh; private String datt, stepp, timm; @Override protected void onCreate(Bundle savedinstancestate) { super.onCreate(savedinstancestate); setContentView(R.layout.activity_list); // names of columns history table datt=(String) getText(R.string.date); stepp=(String) getText(R.string.step); timm=(String) getText(R.string.time); // list for record results of customer listh= (ListView) findViewById(R.id.list_h); hist = new ArrayList<String>(); adapt = new ArrayAdapter<String>(this, R.layout.list_history, hist); listh.setAdapter(adapt); // create a new object DatabaseHandler DatabaseHandler basa = new DatabaseHandler(this); // get all results from database List<Statistic> stat = basa.getAllStatistics(); // write all results to list for (Statistic cn: stat) { hist.add(datt + " "+ cn.getDate() + "\n"+ stepp + " "+ String.valueOf(cn.getStep())+ timm + " "+ cn.getTime()); adapt.notifyDataSetChanged(); } } } <file_sep>package com.natali007.sixthsense; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import com.natali007.sixthsense.R; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.SystemClock; import android.support.v7.app.ActionBarActivity; import android.view.Gravity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.Chronometer; import android.widget.EditText; import android.widget.ListView; import android.widget.Toast; public class MainActivity extends ActionBarActivity { // fields for writing numbers private EditText num1; private EditText num2; private EditText num3; private EditText num4; // buttons with numbers private Button but0; private Button but1; private Button but2; private Button but3; private Button but4; private Button but5; private Button but6; private Button but7; private Button but8; private Button but9; // a list for record attempts of customer private ListView listv; private ArrayList<String> numbers; private ArrayAdapter <String> adapter; // timer private Chronometer time; private CustomArray myCustomArray; //create an object of class CustomArray private NumbersArray myNumbersArray; //create an object of class NumbersArray private String aa; //number of identical numbers at the same positions private String bb; //number of identical numbers at the different positions // element of customer array int k; // counters attempts int counter; //strings for date and win private String won, calend; boolean game; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); k = 0; counter = 0; num1 = (EditText) findViewById (R.id.num1); num2 = (EditText) findViewById (R.id.num2); num3 = (EditText) findViewById (R.id.num3); num4 = (EditText) findViewById (R.id.num4); but0 = (Button)findViewById(R.id.but0); but1 = (Button)findViewById(R.id.but1); but2 = (Button)findViewById(R.id.but2); but3 = (Button)findViewById(R.id.but3); but4 = (Button)findViewById(R.id.but4); but5 = (Button)findViewById(R.id.but5); but6 = (Button)findViewById(R.id.but6); but7 = (Button)findViewById(R.id.but7); but8 = (Button)findViewById(R.id.but8); but9 = (Button)findViewById(R.id.but9); listv= (ListView) findViewById(R.id.listv); time = (Chronometer) findViewById(R.id.time); SimpleDateFormat dateFormat = new SimpleDateFormat ("dd.MM.yyyy"); Calendar c = Calendar.getInstance(); calend = dateFormat.format(c.getTime()); myCustomArray = new CustomArray(); myNumbersArray = new NumbersArray(); myNumbersArray.shuffleArray(); numbers = new ArrayList<String>(); adapter = new ArrayAdapter<String>(this, R.layout.list_item, numbers); listv.setAdapter(adapter); game=true; time.start(); } public void onClick(View view){ switch (view.getId()) { /* if hit the button, this number record to custom Array and to field, the button is not active */ case R.id.but0: { if (num1.getText().length() == 0) { myCustomArray.setCustomArray(k, 0); but0.setEnabled(false); num1.setText(String.valueOf(myCustomArray.getCustomArrayValue(k))); k++; break;} else if (num2.getText().length() == 0) {myCustomArray.setCustomArray(k, 0); but0.setEnabled(false); num2.setText(String.valueOf(myCustomArray.getCustomArrayValue(k))); k++; break;} else if (num3.getText().length() == 0) {myCustomArray.setCustomArray(k, 0); but0.setEnabled(false); num3.setText(String.valueOf(myCustomArray.getCustomArrayValue(k))); k++; break;} else if (num4.getText().length() == 0) {myCustomArray.setCustomArray(k, 0); but0.setEnabled(false); num4.setText(String.valueOf(myCustomArray.getCustomArrayValue(k))); k++; break;} else break; } case R.id.but1: { if (num1.getText().length() == 0) {myCustomArray.setCustomArray(k, 1); but1.setEnabled(false); num1.setText(String.valueOf(myCustomArray.getCustomArrayValue(k))); k++; break;} else if (num2.getText().length() == 0) {myCustomArray.setCustomArray(k, 1); but1.setEnabled(false); num2.setText(String.valueOf(myCustomArray.getCustomArrayValue(k))); k++; break;} else if (num3.getText().length() == 0) {myCustomArray.setCustomArray(k, 1); but1.setEnabled(false); num3.setText(String.valueOf(myCustomArray.getCustomArrayValue(k))); k++; break;} else if (num4.getText().length() == 0) {myCustomArray.setCustomArray(k, 1); but1.setEnabled(false); num4.setText(String.valueOf(myCustomArray.getCustomArrayValue(k))); k++; break;} else break; } case R.id.but2: { if (num1.getText().length() == 0) {myCustomArray.setCustomArray(k, 2); but2.setEnabled(false); num1.setText(String.valueOf(myCustomArray.getCustomArrayValue(k))); k++; break;} else if (num2.getText().length() == 0) { myCustomArray.setCustomArray(k, 2); but2.setEnabled(false);num2.setText(String.valueOf(myCustomArray.getCustomArrayValue(k))); k++; break;} else if (num3.getText().length() == 0) { myCustomArray.setCustomArray(k, 2); but2.setEnabled(false); num3.setText(String.valueOf(myCustomArray.getCustomArrayValue(k))); k++; break;} else if (num4.getText().length() == 0) {myCustomArray.setCustomArray(k, 2); but2.setEnabled(false); num4.setText(String.valueOf(myCustomArray.getCustomArrayValue(k))); k++; break;} else break; } case R.id.but3: { if (num1.getText().length() == 0) {myCustomArray.setCustomArray(k, 3); but3.setEnabled(false); num1.setText(String.valueOf(myCustomArray.getCustomArrayValue(k))); k++; break;} else if (num2.getText().length() == 0) {myCustomArray.setCustomArray(k, 3); but3.setEnabled(false); num2.setText(String.valueOf(myCustomArray.getCustomArrayValue(k))); k++; break;} else if (num3.getText().length() == 0) { myCustomArray.setCustomArray(k, 3); but3.setEnabled(false);num3.setText(String.valueOf(myCustomArray.getCustomArrayValue(k))); k++; break;} else if (num4.getText().length() == 0) {myCustomArray.setCustomArray(k, 3); but3.setEnabled(false); num4.setText(String.valueOf(myCustomArray.getCustomArrayValue(k))); k++; break;} else break; } case R.id.but4: { if (num1.getText().length() == 0) {myCustomArray.setCustomArray(k, 4); but4.setEnabled(false); num1.setText(String.valueOf(myCustomArray.getCustomArrayValue(k))); k++; break;} else if (num2.getText().length() == 0) {myCustomArray.setCustomArray(k, 4); but4.setEnabled(false); num2.setText(String.valueOf(myCustomArray.getCustomArrayValue(k))); k++; break;} else if (num3.getText().length() == 0) {myCustomArray.setCustomArray(k, 4); but4.setEnabled(false); num3.setText(String.valueOf(myCustomArray.getCustomArrayValue(k))); k++; break;} else if (num4.getText().length() == 0) { myCustomArray.setCustomArray(k, 4); but4.setEnabled(false); num4.setText(String.valueOf(myCustomArray.getCustomArrayValue(k))); k++; break;} else break; } case R.id.but5: { if (num1.getText().length() == 0) {myCustomArray.setCustomArray(k, 5); but5.setEnabled(false); num1.setText(String.valueOf(myCustomArray.getCustomArrayValue(k))); k++; break;} else if (num2.getText().length() == 0) {myCustomArray.setCustomArray(k, 5); but5.setEnabled(false); num2.setText(String.valueOf(myCustomArray.getCustomArrayValue(k))); k++; break;} else if (num3.getText().length() == 0) {myCustomArray.setCustomArray(k, 5); but5.setEnabled(false); num3.setText(String.valueOf(myCustomArray.getCustomArrayValue(k))); k++; break;} else if (num4.getText().length() == 0) {myCustomArray.setCustomArray(k, 5); but5.setEnabled(false); num4.setText(String.valueOf(myCustomArray.getCustomArrayValue(k))); k++; break;} else break; } case R.id.but6: { if (num1.getText().length() == 0) {myCustomArray.setCustomArray(k, 6); but6.setEnabled(false); num1.setText(String.valueOf(myCustomArray.getCustomArrayValue(k))); k++; break;} else if (num2.getText().length() == 0) {myCustomArray.setCustomArray(k, 6); but6.setEnabled(false); num2.setText(String.valueOf(myCustomArray.getCustomArrayValue(k))); k++; break;} else if (num3.getText().length() == 0) {myCustomArray.setCustomArray(k, 6); but6.setEnabled(false); num3.setText(String.valueOf(myCustomArray.getCustomArrayValue(k))); k++; break;} else if (num4.getText().length() == 0) {myCustomArray.setCustomArray(k, 6); but6.setEnabled(false); num4.setText(String.valueOf(myCustomArray.getCustomArrayValue(k))); k++; break;} else break; } case R.id.but7: { if (num1.getText().length() == 0) {myCustomArray.setCustomArray(k, 7); but7.setEnabled(false); num1.setText(String.valueOf(myCustomArray.getCustomArrayValue(k))); k++; break;} else if (num2.getText().length() == 0) {myCustomArray.setCustomArray(k, 7); but7.setEnabled(false); num2.setText(String.valueOf(myCustomArray.getCustomArrayValue(k))); k++; break;} else if (num3.getText().length() == 0) {myCustomArray.setCustomArray(k, 7); but7.setEnabled(false); num3.setText(String.valueOf(myCustomArray.getCustomArrayValue(k))); k++; break;} else if (num4.getText().length() == 0) {myCustomArray.setCustomArray(k, 7); but7.setEnabled(false); num4.setText(String.valueOf(myCustomArray.getCustomArrayValue(k))); k++; break;} else break; } case R.id.but8: { if (num1.getText().length() == 0) {myCustomArray.setCustomArray(k, 8); but8.setEnabled(false); num1.setText(String.valueOf(myCustomArray.getCustomArrayValue(k))); k++; break;} else if (num2.getText().length() == 0) {myCustomArray.setCustomArray(k, 8); but8.setEnabled(false); num2.setText(String.valueOf(myCustomArray.getCustomArrayValue(k))); k++; break;} else if (num3.getText().length() == 0) {myCustomArray.setCustomArray(k, 8); but8.setEnabled(false); num3.setText(String.valueOf(myCustomArray.getCustomArrayValue(k))); k++; break;} else if (num4.getText().length() == 0) {myCustomArray.setCustomArray(k, 8); but8.setEnabled(false); num4.setText(String.valueOf(myCustomArray.getCustomArrayValue(k))); k++; break;} else break; } case R.id.but9: { if (num1.getText().length() == 0) {myCustomArray.setCustomArray(k, 9); but9.setEnabled(false); num1.setText(String.valueOf(myCustomArray.getCustomArrayValue(k))); k++; break;} else if (num2.getText().length() == 0) {myCustomArray.setCustomArray(k, 9); but9.setEnabled(false); num2.setText(String.valueOf(myCustomArray.getCustomArrayValue(k))); k++; break;} else if (num3.getText().length() == 0) {myCustomArray.setCustomArray(k, 9); but9.setEnabled(false); num3.setText(String.valueOf(myCustomArray.getCustomArrayValue(k))); k++; break;} else if (num4.getText().length() == 0) {myCustomArray.setCustomArray(k, 9); but9.setEnabled(false); num4.setText(String.valueOf(myCustomArray.getCustomArrayValue(k))); k++; break;} else break; } } } // hit the button Dell to clean the fields public void ondellClick(View view) { if (num1.getText().length() != 0) { k=0; but0.setEnabled(true); but1.setEnabled(true); but2.setEnabled(true); but3.setEnabled(true); but4.setEnabled(true); but5.setEnabled(true); but6.setEnabled(true); but7.setEnabled(true); but8.setEnabled(true); but9.setEnabled(true); num1.setText(""); num2.setText(""); num3.setText(""); num4.setText(""); } } // hit the button Ok public void onokClick(View view){ // if all fields is full if (num4.getText().length() != 0) { k=0; counter ++; int numA = myNumbersArray.compareAarray(myNumbersArray.getNumArray(), myCustomArray.getCustomArray()); int numB = myNumbersArray.compareBarray(myNumbersArray.getNumArray(), myCustomArray.getCustomArray()); aa = String.valueOf(numA); bb = String.valueOf(numB); // if all numbers identical and on the same positions if((numA==4) && (numB==0)) { time.stop(); String t = (String) time.getText(); // to record to list attempt and congratulations words numbers.add(0, counter + "." + " " + num1.getText().toString() + num2.getText().toString() + num3.getText().toString() + num4.getText().toString() + " "+ "-" + " "+ aa + "A"+ bb +"B"); won = (String) getText(R.string.win); numbers.add(0, won ); adapter.notifyDataSetChanged(); // to record to Database: date, numbers of attempts and time DatabaseHandler dbHelper = new DatabaseHandler(this); dbHelper.insertResult(new Statistic(calend, String.valueOf(counter), t)); Context context = getApplicationContext(); Toast tot = Toast.makeText(context, R.string.congratulation, Toast.LENGTH_SHORT); tot.setGravity(Gravity.CENTER, 0, 0); tot.show(); but0.setEnabled(false); but1.setEnabled(false); but2.setEnabled(false); but3.setEnabled(false); but4.setEnabled(false); but5.setEnabled(false); but6.setEnabled(false); but7.setEnabled(false); but8.setEnabled(false); but9.setEnabled(false); num1.setText(""); num2.setText(""); num3.setText(""); num4.setText(""); game=false; } // if numbers not identical or on the different positions else { // to record to list attempt numbers.add(0, counter + "." + " " + num1.getText().toString() + num2.getText().toString() + num3.getText().toString() + num4.getText().toString() + " "+ "-" + " "+ aa + "A"+ bb +"B"); adapter.notifyDataSetChanged(); but0.setEnabled(true); but1.setEnabled(true); but2.setEnabled(true); but3.setEnabled(true); but4.setEnabled(true); but5.setEnabled(true); but6.setEnabled(true); but7.setEnabled(true); but8.setEnabled(true); but9.setEnabled(true); num1.setText(""); num2.setText(""); num3.setText(""); num4.setText(""); } } // if not all fields is full else { Context context = getApplicationContext(); Toast toast = Toast.makeText(context, R.string.fill, Toast.LENGTH_SHORT); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); } } // hit "new game" button public void onnewClick(View view){ if (!game) { numbers.clear(); adapter.notifyDataSetChanged(); myNumbersArray.shuffleArray(); k=0; counter = 0; but0.setEnabled(true); but1.setEnabled(true); but2.setEnabled(true); but3.setEnabled(true); but4.setEnabled(true); but5.setEnabled(true); but6.setEnabled(true); but7.setEnabled(true); but8.setEnabled(true); but9.setEnabled(true); num1.setText(""); num2.setText(""); num3.setText(""); num4.setText(""); time.setBase(SystemClock.elapsedRealtime()); time.start(); game=true; } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { Intent intent = new Intent(MainActivity.this, History.class ); startActivity (intent); return true; } return super.onOptionsItemSelected(item); } } <file_sep># SixthSense_guess_numbers It is a logical game. You should to guess a sequence of four numbers. This project includes work with SQLite for history of wins. <file_sep>package com.natali007.sixthsense; public class CustomArray { // array with customer's numbers private int[] customArray = new int [4]; // to assign a value of element public void setCustomArray(int k, int i){ this.customArray[k] = i; } // to get a value of element public int getCustomArrayValue(int k){ return this.customArray[k]; } // to get all values of array public int[] getCustomArray(){ return this.customArray; } }
32fc373013c3ebaeb4bd175a0d8e4678a48fba46
[ "Markdown", "Java" ]
4
Java
Natali007/SixthSense_guess_numbers
8be48a1574df59b09eb80d18575b8c1eaf0fe0ca
fe149b2c922a1ab6ba98ab098b03b8746e9e600f
refs/heads/main
<file_sep>class Rain{ constructor(x,y){ var option = { restitution: 0.1, friction: 0.1 } this.body = Bodies.circle(x,y,3,option); this.radius = 3; World.add(world,this.body); } update(){ if(this.body.position.y>height){ Matter.Body.setPosition(this.body,{x:random(0,800),y:random(0,800)}) } } display(){ ellipseMode(RADIUS); var pos = this.body.position fill('darkblue'); ellipse(pos.x,pos.y,this.radius,this.radius); } }<file_sep>class Umbrella{ constructor(x,y){ var option = { isStatic: true } this.img =loadImage ("images/Walking Frame/walking_1.png"); this.body = Bodies.circle(x,y,50,option); this.radius = 50; World.add(world,this.body); } display(){ imageMode(CENTER); var pos = this.body.position image(this.img,pos.x,pos.y+20,200,200); } }
ad3820d10e8527ab81b409f15dfa28739603a2e3
[ "JavaScript" ]
2
JavaScript
akshayaupanya/project31-batsman-
145616e8452cedb001aeb6cf76bdc016b83df53a
360df4e94768193270941df5e6665ee9daace320
refs/heads/master
<repo_name>cengizIO/cucumber-test-suite<file_sep>/README.md # A Very Simple Cucumber Test Suite ## Requirements First, install [Bundler](http://bundler.io/) if you haven't already. ``` gem install bundler ``` Then you can use Bundler to install all required gems by typing ``` bundle install ``` ## Running Place your features in `features/` directory and pass them as arguments to Cucumber ``` cucumber features/test.feature ``` ## Example Output ``` Feature: Back 2 Work In order to teach Cucumber and Capybara Scenario: Let's learn more about Cucumber # features/test.feature:4 Given I am on DuckDuckGo Home Page # features/step_definitions/test.rb:4 When I fill search field with "Cucumber" # features/step_definitions/test.rb:8 And I click Search button # features/step_definitions/test.rb:12 Then I should see search results # features/step_definitions/test.rb:16 1 scenario (1 passed) 4 steps (4 passed) 0m9.140s ``` <file_sep>/features/support/env.rb require 'capybara' require 'rspec' Capybara.configure do |config| config.run_server = false config.default_driver = :selenium end <file_sep>/features/step_definitions/test.rb require 'capybara/cucumber' require 'capybara/dsl' Given(/^I am on DuckDuckGo Home Page$/) do visit('https://www.duckduckgo.com') end When(/^I fill search field with "([^"]*)"$/) do |search_keyword| fill_in('q', with: search_keyword) end And(/^I click Search button$/) do find('#search_button_homepage').click end Then(/^I should see search results$/) do expect(page).to have_content 'Cucumber - Wikipedia, the free encyclopedia' end
da1ccbcde6d105593941ffe1208306fd37ef0f5a
[ "Markdown", "Ruby" ]
3
Markdown
cengizIO/cucumber-test-suite
bf4e216d07c1b5ae5b6261f6b35b39d4bc3a7024
9c2de32dbf9bff7e76d05da906a941497deb1904
refs/heads/master
<file_sep>json.array!(@seasons) do |season| json.extract! season, :id, :league, :type, :starts_at, :started, :finished, :games_per_team json.url season_url(season, format: :json) end <file_sep>json.array!(@games) do |game| json.extract! game, :id, :type, :starts_at, :ends_at, :location, :started, :finished, :away_team, :home_team, :away_team_runs, :home_team_runs json.url game_url(game, format: :json) end <file_sep>module DivisionsHelper end <file_sep>json.extract! @team, :id, :romaji, :kanji, :created_at, :updated_at <file_sep># This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel', city: cities.first) require 'csv' leagues = League.create(name: '<NAME>') File.open("db/divisions.txt").each do |line| Division.create(name: line.split(',')[0], league_id: 1) end class String def remove_u! if self.include? "ou" or self.include? "oo" self.gsub!(/ou|oo/, 'o') else self end end end file = CSV.read("db/players1.csv") file.each do |line| hiragana = line[3] eng = hiragana.han_to_zen.romaji.remove_u!.capitalize Player.create(kanji: line[1], kana: hiragana, romaji: eng, team_id: 0) end<file_sep>json.array!(@teams) do |team| json.extract! team, :id, :romaji, :kanji json.url team_url(team, format: :json) end <file_sep>class CreateGames < ActiveRecord::Migration def change create_table :games do |t| t.string :type t.datetime :starts_at t.datetime :ends_at t.integer :location t.boolean :started t.boolean :finished t.integer :away_team t.integer :home_team t.integer :away_team_runs t.integer :home_team_runs t.timestamps end end end <file_sep>json.extract! @player, :id, :kanji, :kana, :team_id, :created_at, :updated_at
65239ac81e2aa37459c25a60868766864b9b23ee
[ "Ruby" ]
8
Ruby
jandeha/ek
ad7ce31506d6593e9d216b178356391cc1a0a6f0
f8ff40177ea8121cceb2e650f76a337b7ca56a41
refs/heads/master
<repo_name>Rockrat2008/flask_basics<file_sep>/OnlineBookCatalog.py # AUTHOR: <NAME> # CREATED: 14 September 2018 # UPDATED: 21 September 2018 # DESCRIPTION: Online book catalog # Modules needed for application from flask import Flask, request, render_template from flask_sqlalchemy import SQLAlchemy from datetime import datetime app = Flask(__name__) app.config.update( # SECRET_KEY is used by 3rd party applications to secure things like cookies: Should be strong and complex key SECRET_KEY = 'topsecret', SQLALCHEMY_DATABASE_URI = 'postgresql://postgres:Scuba2018!@localhost/catalog_db', SQLALCHEMY_TRACK_MODIFICATIONS = False ) db = SQLAlchemy(app) # BASIC FLASK QUERY/ROUTING @app.route('/index') @app.route('/') def hello_flask(): return 'Hello Flask!' # QUERY STRINGS @app.route('/new/') def query_strings(greeting = 'Hello'): query_val = request.args.get('greeting', greeting) return '<h1> The greeting is: {0} </h1>.'.format(query_val) @app.route('/user') @app.route('/user/<name>') def no_query_strings(name='Michael'): return '<h1> Hello there {} </h1>.'.format(name) @app.route('/temp') def using_templates(): return render_template('hello.html') @app.route('/watch') def movies(): movie_list = ['Autopsy of Jane Doe', 'Neon Demon', 'Ghost in a Shell', 'Kong: Skull Islannd', '<NAME> 2', 'Spiderman - Homecoming'] return render_template('movies.html', movies = movie_list, name = 'Michael') @app.route('/tables') def movies_plus(): movie_dict = {'Autopsy of Jane Doe' : 02.14, 'Neon Demon' : 3.20, 'Ghost in a Shell' : 1.50, 'Kong: Skull Islannd' : 3.50, '<NAME>' : 02.52, 'Spiderman - Homecoming' : 1.48} return render_template('table_data.html', movies = movie_dict, name = 'Michael') @app.route('/filters') def filter_data(): movie_dict = {'Autopsy of Jane Doe' : 02.14, 'Neon Demon' : 3.20, 'Ghost in a Shell' : 1.50, 'Kong: Skull Islannd' : 3.50, '<NAME> 2' : 02.52, 'Spiderman - Homecoming' : 1.48} return render_template('filter_data.html', movies = movie_dict, name = None, film = 'A Christmas Carol') class Publication(db.Model): __tablename__ = 'publication' id = db.Column(db.Integer, primary_key = True) name = db.Column(db.String(80), nullable = False) def __init__(self, name): self.name = name def __repr__(self): return 'The Publisher is {}'.format(self.name) class Book(db.Model): __tablename__ = 'book' id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(100), nullable=False, index=True) author = db.Column(db.String(100)) avg_rating = db.Column(db.Float) format = db.Column(db.String(50)) image = db.Column(db.String(100), unique=True) num_pages = db.Column(db.Integer) pub_date = db.Column(db.DateTime, default=datetime.utcnow()) # RELATIONSHIP pub_id = db.Column(db.Integer, db.ForeignKey('publication.id')) def __init__(self, title, author, avg_rating, book_format, image, num_pages, pub_id): self.title = title self.author = author self.avg_rating = avg_rating self.format = book_format self.image = image self.num_pages = num_pages self.pub_id = pub_id def __repr__(self): return '{} by {}'.format(self.title, self.author) if __name__ == '__main__': db.create_all() app.run(debug=True)
dd36828af67f48ed72bf914fb42b0d6a6172bf1a
[ "Python" ]
1
Python
Rockrat2008/flask_basics
a58fdaf7a136b4a7aa94084c3fd58f4740fe52bb
3422f38e8a86d329b4643edf6ea3dbf21d36331b
refs/heads/master
<file_sep><?php /** * @package DW Magz Extra Widgets */ /* Plugin Name: DW Magz Extra Widgets Plugin URI: Description: Version: 1.0.0 Author: <NAME> Author URI: License: GPLv2 or later */ if ( ! defined( 'DWMZ_DIR' ) ) { define( 'DWMZ_DIR', plugin_dir_path( __FILE__ ) ); } if ( ! defined( 'DWMZ_URI' ) ) { define( 'DWMZ_URI', plugin_dir_url( __FILE__ ) ); } require_once DWMZ_DIR . 'classes/dw_slider.php'; require_once DWMZ_DIR . 'classes/dw_feature_content.php'; // require_once DWMZ_DIR . 'classes/dw_category.php'; function dwmz_init() { add_image_size( 'dw-slider-style-1', 810, 400, true ); add_image_size( 'dw-slider-style-2', 255, 132, true );; } add_action( 'init', 'dwmz_init' ); function dwmz_enqueue_scripts() { wp_enqueue_style( 'dwmz-slider-css', DWMZ_URI . '/assets/css/dwmz_slider.css' ); wp_enqueue_style( 'dwmz-feature-content-css', DWMZ_URI . '/assets/css/dwmz_feature-content.css' ); wp_enqueue_script( 'dwmz-script', DWMZ_URI . '/assets/js/script.js', array( 'jquery' ), '1.0.0', true ); } add_action( 'wp_enqueue_scripts', 'dwmz_enqueue_scripts' ); function dwmz_admin_enqueue_scripts() { wp_enqueue_script( 'dwmz-admin-script', DWMZ_URI . '/assets/js/admin.js', array( 'jquery' ), '1.0.0', true ); } add_action( 'admin_enqueue_scripts', 'dwmz_admin_enqueue_scripts' ); <file_sep><?php /** * @package DW Slider Widget * Style 2 */ ?> <div class="<?php echo esc_attr( $carousel_style ); ?>"> <?php if ( $title ) : ?> <?php echo $args['before_title']; ?> <?php if ( 0 != $cat_id ) : ?> <a href="<?php echo esc_url( get_category_link( $cat_id ) ); ?>"><?php echo wp_kses_post( $title ); ?></a> <?php else : ?> <?php echo wp_kses_post( $title ); ?> <?php endif; ?> <?php echo $args['after_title']; ?> <?php endif; ?> <div class="news-grid"> <div id="carousel-<?php echo esc_attr( $args['widget_id'] ); ?>" class="carousel slide" data-ride="carousel"><div class="carousel-inner" role="listbox"><div class="item active"> <div class="row"> <?php $col = 3 ?> <?php $row_num = 0; $i = 1; ?> <?php $item_count = $r->post_count; ?> <?php while ( $r->have_posts() ) : $r->the_post(); ?> <div class="col-sm-<?php echo esc_attr( $col ); ?>"> <article <?php post_class(); ?>> <?php if ( has_post_thumbnail() ) : ?> <div class="entry-thumbnail"><a href="<?php the_permalink(); ?>"><?php the_post_thumbnail( 'dw-slider-style-2' ); ?></a></div> <?php endif; ?> <h3 class="entry-title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3> <div class="entry-meta"> <?php if ( $show_date ) : ?> <span class="entry-date"><i class="fa fa-clock-o"></i> <?php echo get_the_date( __('F j, Y', 'dw-focus') ); ?></span> <?php endif; ?> <?php if ( $show_author ) : ?> <span class="entry-author"><i class="fa fa-user"></i> <?php the_author(); ?></span> <?php endif; ?> <?php if ( $show_comment && ! post_password_required() && ( comments_open() || '0' != get_comments_number() ) ) : ?> <span class="comments-link"><?php _e( '<i class="fa fa-comment"></i> ', 'dw-focus' ); ?><?php comments_popup_link( __( '0', 'dw-focus' ), __( '1', 'dw-focus' ), __( '%', 'dw-focus' ) ); ?></span> <?php endif; ?> </div> <?php if ( 'content' == $show_content ) : $more = 0; ?> <div class="entry-content"><?php the_content( __( 'Continue reading <span class="meta-nav">&rarr;</span>', 'dw-focus' ) ); ?></div> <?php elseif ( 'excerpt' == $show_content ) : ?> <div class="entry-summary"><?php the_excerpt(); ?></div> <?php endif; ?> </article> </div> <?php if ( ( 0 === $i % ( 4 ) ) && ( $i < $item_count ) ) : ?> </div> </div> <div class="item"> <div class="row"> <?php $row_num++; endif; ?> <?php $i++; ?> <?php endwhile; ?> </div> </div></div> <ol class="carousel-indicators"> <?php for ( $j = 0; $j <= $row_num; $j++ ) { ?> <li data-target="#carousel-<?php echo esc_attr( $args['widget_id'] ); ?>" data-slide-to="<?php echo esc_attr( $j ); ?>"<?php if ( 0 === $j ) { echo 'class="active"'; } ?>></li> <?php } ?> </ol> <!-- Controls --> <a class="left carousel-control" href="#carousel-<?php echo esc_attr( $args['widget_id'] ); ?>" role="button" data-slide="prev"> <span class="fa fa-chevron-left" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="right carousel-control" href="#carousel-<?php echo esc_attr( $args['widget_id'] ); ?>" role="button" data-slide="next"> <span class="fa fa-chevron-right" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> </div><file_sep><?php /** * @package DW Slider Widget */ add_action( 'widgets_init', 'dw_mz_carousel_widgets_init' ); function dw_mz_carousel_widgets_init() { register_widget( 'DW_mz_carousel_Widget' ); } class DW_mz_carousel_Widget extends WP_Widget { public function __construct() { $widget_ops = array( 'classname' => 'dw_mz_carousel_widget', 'description' => 'Show Your Posts as a Slider.' ); parent::__construct( 'news-slider', 'DW MagZ: Carousel Widget', $widget_ops ); add_action( 'save_post', array( $this, 'flush_widget_cache' ) ); add_action( 'deleted_post', array( $this, 'flush_widget_cache' ) ); add_action( 'switch_theme', array( $this, 'flush_widget_cache' ) ); } public function widget($args, $instance) { $cache = array(); if ( ! $this->is_preview() ) { $cache = wp_cache_get( 'dw_mz_carousel_widget', 'widget' ); } if ( ! is_array( $cache ) ) { $cache = array(); } if ( ! isset( $args['widget_id'] ) ) { $args['widget_id'] = $this->id; } if ( isset( $cache[ $args['widget_id'] ] ) ) { echo $cache[ $args['widget_id'] ]; return; } ob_start(); $title = ( ! empty( $instance['title'] ) ) ? $instance['title'] : ''; $carousel_style = ( ! empty( $instance['carousel_style'] ) ) ? $instance['carousel_style'] : 'style-1'; $title = apply_filters( 'widget_title', $title, $instance, $this->id_base ); $number = ( ! empty( $instance['number'] ) ) ? absint( $instance['number'] ) : 5; $show_content = ( ! empty( $instance['show_content'] ) ) ? $instance['show_content'] : ''; $cat_id = ( ! empty( $instance['cat_id'] ) ) ? absint( $instance['cat_id'] ) : 0; $tags = ( ! empty( $instance['tags'] ) ) ? $instance['tags'] : ''; $show_category = isset( $instance['show_category'] ) ? $instance['show_category'] : false; $show_date = isset( $instance['show_date'] ) ? $instance['show_date'] : false; $show_author = isset( $instance['show_author'] ) ? $instance['show_author'] : false; $show_comment = isset( $instance['show_comment'] ) ? $instance['show_comment'] : false; $post_format = isset( $instance['post_format'] ) ? $instance['post_format'] : ''; $query = array( 'posts_per_page' => $number, 'no_found_rows' => true, 'post_status' => 'publish', 'ignore_sticky_posts' => true, ); if ( $post_format ) { $query['post_format'] = 'post-format-'.$post_format; } if ( '' != $tags && 0 != $cat_id ) { $query['tax_query'] = array( 'relation' => 'AND', array( 'taxonomy' => 'category', 'field' => 'id', 'terms' => array( $cat_id ), ), array( 'taxonomy' => 'post_tag', 'field' => 'name', 'terms' => explode( ',', $tags ), ), ); } else { if ( '' != $tags ) { $query['tag_slug__in'] = explode( ',', $tags ); } if ( 0 != $cat_id ) { $query['cat'] = $cat_id; } } $r = new WP_Query( apply_filters( 'dw_mz_carousel_widget', $query ) ); if ( $r->have_posts() ) : ?> <?php echo $args['before_widget']; ?> <?php include DWMZ_DIR . 'templates/slider_styles/'. $carousel_style .'.php' ; ?> <?php echo $args['after_widget']; ?> <?php wp_reset_postdata(); endif; if ( ! $this->is_preview() ) { $cache[ $args['widget_id'] ] = ob_get_flush(); wp_cache_set( 'dw_mz_carousel_widget', $cache, 'widget' ); } else { ob_end_flush(); } } public function update( $new_instance, $old_instance ) { $instance = $old_instance; $instance['title'] = strip_tags( $new_instance['title'] ); $instance['carousel_style'] = strip_tags( $new_instance['carousel_style'] ); $instance['number'] = (int) $new_instance['number']; $instance['show_content'] = strip_tags( $new_instance['show_content'] ); $instance['cat_id'] = (int) $new_instance['cat_id']; $instance['tags'] = strip_tags( $new_instance['tags'] ); $instance['post_format'] = strip_tags( $new_instance['post_format'] ); $instance['show_category'] = isset( $new_instance['show_category'] ) ? (bool) $new_instance['show_category'] : false; $instance['show_date'] = isset( $new_instance['show_date'] ) ? (bool) $new_instance['show_date'] : false; $instance['show_author'] = isset( $new_instance['show_author'] ) ? (bool) $new_instance['show_author'] : false; $instance['show_comment'] = isset( $new_instance['show_comment'] ) ? (bool) $new_instance['show_comment'] : false; $this->flush_widget_cache(); $alloptions = wp_cache_get( 'alloptions', 'options' ); if ( isset( $alloptions['dw_mz_carousel_widget'] ) ) { delete_option( 'dw_mz_carousel_widget' ); } return $instance; } public function flush_widget_cache() { wp_cache_delete( 'dw_mz_carousel_widget', 'widget' ); } public function form( $instance ) { $title = isset( $instance['title'] ) ? esc_attr( $instance['title'] ) : ''; $carousel_style = isset( $instance['carousel_style'] ) ? esc_attr( $instance['carousel_style'] ) : ''; $number = isset( $instance['number'] ) ? absint( $instance['number'] ) : 5; $show_content = isset( $instance['show_content'] ) ? esc_attr( $instance['show_content'] ) : ''; $cat_id = isset( $instance['cat_id'] ) ? esc_attr( $instance['cat_id'] ) : 0; $tags = isset( $instance['tags'] ) ? esc_attr( $instance['tags'] ) : ''; $post_format = isset( $instance['post_format'] ) ? esc_attr( $instance['post_format'] ) : ''; $show_category = isset( $instance['show_category'] ) ? (bool) $instance['show_category'] : false; $show_date = isset( $instance['show_date'] ) ? (bool) $instance['show_date'] : false; $show_author = isset( $instance['show_author'] ) ? (bool) $instance['show_author'] : false; $show_comment = isset( $instance['show_comment'] ) ? (bool) $instance['show_comment'] : false; ?> <p><label for="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>"><?php _e( 'Title:', 'dw-carousel' ); ?></label> <input class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'title' ) ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>" /></p> <p><label for="<?php echo esc_attr( $this->get_field_id( 'carousel_style' ) ); ?>"><?php _e( 'Choose carousel style', 'dw-carousel' ) ?></label> <select class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'carousel_style' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'carousel_style' ) ); ?>"> <?php $styles = $this->read_styles(); for ( $i = 1; $i <= intval( $styles ); $i++) { $style = 'style-'.$i; ?> <option value="<?php echo $style; ?>" <?php selected( $carousel_style, $style ) ?>><?php _e( $style , 'dw-carousel' ); ?></option> <?php } ?> </select></p> <p><label for="<?php echo esc_attr( $this->get_field_id( 'number' ) ); ?>"><?php _e( 'Number of posts to show:', 'dw-carousel' ); ?></label> <input class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'number' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'number' ) ); ?>" type="text" value="<?php echo esc_attr( $number ); ?>" size="3" /></p> <p><label for="<?php echo esc_attr( $this->get_field_id( 'show_content' ) ); ?>"><?php _e( 'Display post content?', 'dw-carousel' ) ?></label> <select class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'show_content' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'show_content' ) ); ?>"> <option value="" <?php selected( $show_content, '' ) ?>></option> <option value="excerpt" <?php selected( $show_content, 'excerpt' ) ?>><?php _e( 'Excerpt', 'dw-carousel' ); ?></option> <option value="content" <?php selected( $show_content, 'content' ) ?>><?php _e( 'Content', 'dw-carousel' ); ?></option> </select></p> <p><label for="<?php echo esc_attr( $this->get_field_id( 'cat_id' ) ); ?>"><?php _e( 'Category:', 'dw-carousel' ); ?></label> <?php wp_dropdown_categories( 'name='.$this->get_field_name( 'cat_id' ).'&class=widefat&show_option_all=All&hide_empty=0&hierarchical=1&depth=2&selected='.$cat_id ); ?></p> <p><label for="<?php echo esc_attr( $this->get_field_id( 'tags' ) ); ?>"><?php _e( 'Tags:', 'dw-carousel' ); ?></label> <input class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'tags' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'tags' ) ); ?>" placeholder="<?php _e( 'tag 1, tag 2, tag 3','dw-carousel' )?>" type="text" value="<?php echo esc_attr( $tags ); ?>" /></p> <p><input class="checkbox" type="checkbox" <?php checked( $show_category ); ?> id="<?php echo esc_attr( $this->get_field_id( 'show_category' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'show_category' ) ); ?>" /> <label for="<?php echo esc_attr( $this->get_field_id( 'show_category' ) ); ?>"><?php _e( 'Display post categories?', 'dw-carousel' ); ?></label></p> <p><input class="checkbox" type="checkbox" <?php checked( $show_date ); ?> id="<?php echo esc_attr( $this->get_field_id( 'show_date' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'show_date' ) ); ?>" /> <label for="<?php echo esc_attr( $this->get_field_id( 'show_date' ) ); ?>"><?php _e( 'Display post date?', 'dw-carousel' ); ?></label></p> <p><input class="checkbox" type="checkbox" <?php checked( $show_author ); ?> id="<?php echo esc_attr( $this->get_field_id( 'show_author' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'show_author' ) ); ?>" /> <label for="<?php echo esc_attr( $this->get_field_id( 'show_author' ) ); ?>"><?php _e( 'Display post author?', 'dw-carousel' ); ?></label></p> <p><input class="checkbox" type="checkbox" <?php checked( $show_comment ); ?> id="<?php echo esc_attr( $this->get_field_id( 'show_comment' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'show_comment' ) ); ?>" /> <label for="<?php echo esc_attr( $this->get_field_id( 'show_comment' ) ); ?>"><?php _e( 'Display comment count?', 'dw-carousel' ); ?></label></p> <?php } function read_styles() { $dir = DWMZ_DIR . "/templates/slider_styles"; $count = 0; $files = scandir( $dir ); for ( $i = 0; $i < count( $files ) ;$i++ ){ if($files[ $i ] !='.' && $files[ $i ] !='..') { $count++; } } return $count; } } <file_sep>(function($) { "use strict"; $('.slide').on('slid.bs.carousel', function () { $(this).find('.carousel-title-indicators').find('.active').removeClass('active'); var index = $(this).find('.carousel-indicators').find('.active').data('slide-to'); $(this).find('.carousel-title-indicators li[data-slide-to=' + index + ']').addClass('active'); }); })(jQuery); <file_sep><?php /** * @package DW Slider Widget * Style 1 */ ?> <div id="carousel-<?php echo esc_attr( $args['widget_id'] ); ?>" class="carousel slide <?php echo esc_attr( $carousel_style ); ?>" data-ride="carousel"> <div class="carousel-inner" role="listbox"> <?php $i = 0; while ( $r->have_posts() ) : $r->the_post(); ?> <div class="item<?php echo $i == 0 ? ' active' : ''; ?>"> <article class="carousel-entry"> <a href="<?php the_permalink(); ?>"><?php the_post_thumbnail( 'dw-slider-style-1' ); ?></a> <?php $categories_list = get_the_category_list( __( ', ', 'dw-slider-widget' ) ); if ( $show_category && $categories_list ) { printf( '<span class="cat-links hidden-xs">' . __( '%1$s', 'dw-slider-widget' ) . '</span>', $categories_list ); } ?> <div class="carousel-caption"> <div class="entry-meta hidden-xs"> <?php if ( $show_date ) : ?> <span class="entry-date"><i class="fa fa-clock-o"></i> <?php echo get_the_date( __('F j, Y', 'dw-slider-widget') ); ?></span> <?php endif; ?> <?php if ( $show_author ) : ?> <span class="entry-author"><i class="fa fa-user"></i> <?php the_author(); ?></span> <?php endif; ?> <?php if ( $show_comment && ! post_password_required() && ( comments_open() || '0' != get_comments_number() ) ) : ?> <span class="comments-link"><?php _e( '<i class="fa fa-comment"></i> ', 'dw-slider-widget' ); ?><?php comments_popup_link( __( '0', 'dw-slider-widget' ), __( '1', 'dw-slider-widget' ), __( '%', 'dw-slider-widget' ) ); ?></span> <?php endif; ?> </div> <h2 class="entry-title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2> <?php if ( 'content' == $show_content ) : $more = 0; ?> <div class="entry-content"><?php the_content( __( 'Continue reading <span class="meta-nav">&rarr;</span>', 'dw-slider-widget' ) ); ?></div> <?php elseif ( 'excerpt' == $show_content ) : ?> <div class="entry-summary"><?php the_excerpt(); ?></div> <?php endif; ?> </div> </article> </div> <?php $i++; endwhile; ?> </div> <div class="carousel-navigation hidden-xs hidden-sm"> <?php if ( $title ) { echo $args['before_title'] . wp_kses_post( $title ) . $args['after_title']; } ?> <ol class="carousel-title-indicators"> <?php $k = 0; while ( $r->have_posts() ) : $r->the_post(); ?> <li data-target="#carousel-<?php echo esc_attr( $args['widget_id'] ); ?>" data-slide-to="<?php echo esc_attr( $k ); ?>"<?php echo $k == 0 ? ' class="active"' : ''; ?>><?php the_title(); ?></li> <?php $k++; endwhile; ?> </ol> <ol class="carousel-indicators"> <?php for ( $j = 0; $j < $i; $j++ ) : ?> <li data-target="#carousel-<?php echo esc_attr( $args['widget_id'] ); ?>" data-slide-to="<?php echo esc_attr( $j ); ?>"<?php echo $j == 0 ? ' class="active"' : ''; ?>></li> <?php endfor; ?> </ol> </div> </div><file_sep><?php /** * @package DW Slider Widget * Style 1 */ ?> 123456789--<file_sep><?php add_action( 'widgets_init', 'dw_mz_feature_content_widget_init' ); function dw_mz_feature_content_widget_init() { register_widget( 'DW_mz_feature_content' ); } class DW_mz_feature_content extends WP_Widget { public function __construct() { $widget_ops = array( 'classname' => 'dw-mz-feature-content-widget', 'description' => __( 'DW MagZ: Feature Content', 'dw-widget' ) ); parent::__construct( 'dw-mz-feature-content-widget', __( 'DW MagZ: Feature Content', 'dw-widget' ), $widget_ops ); } public function widget( $args, $instance ) { ob_start(); $cat_id = ( ! empty( $instance['cat_id'] ) ) ? absint( $instance['cat_id'] ) : 0; $tags = ( ! empty( $instance['tags'] ) ) ? $instance['tags'] : ''; $order = isset( $instance['order'] ) ? esc_attr( $instance['order'] ) : ''; $query = array( 'posts_per_page' => 6, 'no_found_rows' => true, 'post_status' => 'publish', 'ignore_sticky_posts' => true, ); if ( '' != $tags && 0 != $cat_id ) { $query['tax_query'] = array( 'relation' => 'AND', array( 'taxonomy' => 'category', 'field' => 'id', 'terms' => array( $cat_id ), ), array( 'taxonomy' => 'post_tag', 'field' => 'name', 'terms' => explode( ',', $tags ), ), ); } else { if ( '' != $tags ) { $query['tag_slug__in'] = explode( ',', $tags ); } if ( 0 != $cat_id ) { $query['cat'] = $cat_id; } } if( isset( $instance['order'] ) ) { $query['orderby'] = $instance['order']; if($query['orderby'] == 'title') { $query['order'] = 'ASC'; } else { $query['order'] = 'DESC'; } } $metro_query = new WP_Query( apply_filters( 'DW_mz_feature_content', $query ) ); if ( $metro_query->have_posts() ): ?> <?php echo $args['before_widget']; ?> <div class="feature"> <div id="metro-slide"> <?php $i = 0; while ( $metro_query->have_posts() ) : $metro_query->the_post(); $class = "gradient gradient-".$i; if ($i < 2) { $thumbnail_size = 500; $class .= " hentry-big"; } else { $thumbnail_size = 250; $class .= " hentry-small"; } if ($i == 2) { $class .= " clear-left"; } ?> <article id="post-<?php the_ID(); ?>" class="hentry-metro <?php echo $class ?>"> <div class="entry-thumbnail gradient-tran-white" > <?php if(preg_match('/(?i)msie [1-8]/',$_SERVER['HTTP_USER_AGENT'])) : ?> <!--[if IE 8]> <div class="ie8-gradient-tran-white"></div> <![endif]--> <?php endif; ?> <?php if(has_post_thumbnail()) : ?> <?php the_post_thumbnail(); ?> <?php else : ?> <img alt="<?php echo esc_attr( sprintf( __( 'Permalink to %s', 'dw-argo' ), the_title_attribute( 'echo=0' ) ) ); ?>" src="http://placehold.it/<?php echo $thumbnail_size.'x'.$thumbnail_size; ?>" /> <?php endif; ?> </div> <img class="placeholder" src="<?php echo DWMZ_URI ?>assets/img/placeholder.png" alt="<?php echo esc_attr( sprintf( __( 'Permalink to %s', 'dw-argo' ), the_title_attribute( 'echo=0' ) ) ); ?>"> <h2 class="entry-title"> <a href="<?php the_permalink(); ?>" title="<?php echo esc_attr( sprintf( __( 'Permalink to %s', 'dw-argo' ), the_title_attribute( 'echo=0' ) ) ); ?>" rel="bookmark"><?php the_title(); ?></a> </h2> <?php if(preg_match('/(?i)msie [1-8]/',$_SERVER['HTTP_USER_AGENT'])) : ?> <!--[if IE 8]> <div class="<?php echo $class ?>"> <div class="inner"></div> </div> <! [endif]--> <?php endif; ?> </article> <?php $i++; ?> <?php endwhile; ?> </div> </div> <?php echo $args['after_widget']; ?> <?php wp_reset_postdata(); ?> <?php ob_end_flush(); ?> <?php endif; } public function update( $new_instance, $old_instance ) { $instance = $old_instance; $instance['cat_id'] = (int) $new_instance['cat_id']; $instance['tags'] = strip_tags( $new_instance['tags'] ); $instance['order'] = strip_tags( $new_instance['order'] ); return $instance; } public function form( $instance ) { $cat_id = isset( $instance['cat_id'] ) ? esc_attr( $instance['cat_id'] ) : 0; $tags = isset( $instance['tags'] ) ? esc_attr( $instance['tags'] ) : ''; $order = isset( $instance['order'] ) ? esc_attr( $instance['order'] ) : ''; ?> <p><label for="<?php echo esc_attr( $this->get_field_id( 'cat_id' ) ); ?>"><?php _e( 'Category:', 'dw-feature-content' ); ?></label> <?php wp_dropdown_categories( 'name='.$this->get_field_name( 'cat_id' ).'&class=widefat&show_option_all=All&hide_empty=0&hierarchical=1&depth=2&selected='.$cat_id ); ?></p> <p><label for="<?php echo esc_attr( $this->get_field_id( 'tags' ) ); ?>"><?php _e( 'Tags:', 'dw-feature-content' ); ?></label> <input class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'tags' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'tags' ) ); ?>" placeholder="<?php _e( 'tag 1, tag 2, tag 3','dw-feature-content' )?>" type="text" value="<?php echo esc_attr( $tags ); ?>" /></p> <p><label for="<?php echo esc_attr( $this->get_field_id( 'order' ) ); ?>"><?php _e( 'Display post content?', 'dw-feature-content' ) ?></label> <select class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'order' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'order' ) ); ?>"> <option value="" <?php selected( $order, '' ) ?>></option> <option value="title" <?php selected( $order, 'title' ) ?>><?php _e( 'Title', 'dw-feature-content' ); ?></option> <option value="date" <?php selected( $order, 'date' ) ?>><?php _e( 'Date', 'dw-feature-content' ); ?></option> <option value="comment_count" <?php selected( $order, 'comment_count' ) ?>><?php _e( 'Content', 'dw-feature-content' ); ?></option> <option value="rand" <?php selected( $order, 'rand' ) ?>><?php _e( 'Random', 'dw-feature-content' ); ?></option> </select></p> <?php } }<file_sep># dw-magz-extra-widgets Extra wid Extra widget for Dw Magz
f9049f4f695a80c7925c4c5c1e46b2588d51cf6e
[ "JavaScript", "Markdown", "PHP" ]
8
PHP
Pumpkjn/dw-magz-extra-widgets
088f80935b0e45f0439911def55274cd44b65f76
07f6588e5f4c8d021d888401dc1419fc7804e094
refs/heads/master
<repo_name>s25506683/DebugDB<file_sep>/src/main/java/com/example/demo/controller/POST.java package com.example.demo.controller; public @interface POST { }
ece852b9af1b0887aedf2b63be6ffb9743c16a24
[ "Java" ]
1
Java
s25506683/DebugDB
644fb7590d12363c0b4583226c47ebc8f0879a3a
3cee941bfd037226dfc28a18a85954323b8a1ab1
refs/heads/master
<file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* checker.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: fsinged <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/08/06 13:05:21 by fsinged #+# #+# */ /* Updated: 2019/09/27 12:58:21 by fsinged ### ########.fr */ /* */ /* ************************************************************************** */ #include "push_swap.h" static void print(int num) { write(1, "\t[", 3); ft_putnbr(num); write(1, "]\t", 3); } static void ft_print(t_ar *ar) { int sa; int size; sa = -1; usleep(110000); system("clear"); size = ar->sizea + ar->sizeb; while (++sa < size) { if (sa < ar->sizea) print(ar->a[sa]); else write(1, "\t[ ]\t", 5); if (sa < ar->sizeb) print(ar->b[sa]); else write(1, "\t[ ]\t", 5); write(1, "\n", 1); } } static int check_word(char *line, t_ar *ar) { if (ft_strcmp(line, "sa") == 0) swap(ar->a, ar->sizea, 0); else if (ft_strcmp(line, "sb") == 0) swap(ar->b, ar->sizeb, 0); else if (ft_strcmp(line, "ss") == 0) swap_ab(ar, 0); else if (ft_strcmp(line, "pa") == 0) push(ar->a, ar->b, &(ar->sizea), &(ar->sizeb)); else if (ft_strcmp(line, "pb") == 0) push(ar->b, ar->a, &(ar->sizeb), &(ar->sizea)); else if (ft_strcmp(line, "ra") == 0) rotate(ar->a, ar->sizea, 0); else if (ft_strcmp(line, "rb") == 0) rotate(ar->b, ar->sizeb, 0); else if (ft_strcmp(line, "rr") == 0) rotate_ab(ar, 0); else if (ft_strcmp(line, "rra") == 0) rrotate(ar->a, ar->sizea, 0); else if (ft_strcmp(line, "rrb") == 0) rrotate(ar->b, ar->sizeb, 0); else if (ft_strcmp(line, "rrr") == 0) rrotate_ab(ar, 0); else return (0); return (1); } static int checker(t_ar *ar, int flag) { char *line; int i; while (get_next_line(0, &line)) { if (ft_strcmp(line, "") == 0) { ft_strdel(&line); break ; } i = check_word(line, ar); if (flag) ft_print(ar); ft_strdel(&line); if (i == 0) return (2); } return (issorted(ar->a, ar->sizea, 'a') && ar->sizeb == 0 ? 1 : 0); } int main(int argc, char **argv) { t_ar *ar; int i; int flag; if (argc == 1) return (0); flag = 0; ar = (t_ar*)malloc(sizeof(t_ar)); if (ft_strequ(argv[1], "-v") && argv++ && argc--) flag = 1; if (readnumbers(argc - 1, argv + 1, ar)) { ft_putnbr(ar->sizeb); i = checker(ar, flag); if (i == 0) write(1, "KO\n", 3); else if (i == 1) write(1, "OK\n", 3); else if (i == 2) write(1, "Error\n", 6); } else write(1, "Error\n", 6); free_struct(&ar); return (0); } <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* reader.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: fsinged <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/09/11 11:59:18 by fsinged #+# #+# */ /* Updated: 2019/09/16 15:12:16 by fsinged ### ########.fr */ /* */ /* ************************************************************************** */ #include "push_swap.h" static void ft_strddel(char **argv) { int i; if (argv == NULL) return ; i = 0; while (argv[i] != NULL) { free(argv[i]); i++; } free(argv); } /* ** Count words in str */ static int ft_wordcounter(char const *s, char c) { size_t count; size_t i; count = 0; i = 0; while (s[i]) { if ((s[i] == c && s[i + 1] != c && s[i + 1] != '\0') || (s[i] != c && i == 0)) count++; i++; } return (count); } /* ** Check is int or not */ static int isint(char *str) { long int num; int sign; num = 0; sign = *str == '-' ? -1 : 1; if (*str == '-' || *str == '+') str++; if (!ft_isdigit(*str)) return (0); while (*str) { if (!ft_isdigit(*str)) return (0); num = num * 10 + (*str - '0'); str++; if (!((num * sign) <= 2147483647 && (num * sign) >= -2147483648)) return (0); } return ((num * sign) <= 2147483647 && (num * sign) >= -2147483648); } /* ** Check this number was in array */ static int isduplicate(int *a, int i) { int j; j = 0; while (j < i) { if (a[i] == a[j]) return (0); j++; } return (1); } /* ** Read arguments and check it */ int readnumbers(int argc, char **argv, t_ar *ar) { int flag; int i; flag = 0; if (argc == 1) { argc = ft_wordcounter(argv[0], ' '); argv = ft_strsplit(argv[0], ' '); flag = 1; } i = -1; ar = init_ar(ar, argc); while (++i < argc) { ar->a[i] = ft_atoi(argv[i]); if (!isint(argv[i]) || !isduplicate(ar->a, i)) { if (flag) ft_strddel(argv); return (0); } } if (flag) ft_strddel(argv); return (1); } <file_sep># push_swap-42 The goal of this project is sort array of numbers using two stacks and followind rules below: sa : swap a - swap the first 2 elements at the top of stack a. Do nothing if there is only one or no elements). sb : swap b - swap the first 2 elements at the top of stack b. Do nothing if there is only one or no elements). ss : sa and sb at the same time. pa : push a - take the first element at the top of b and put it at the top of a. Do nothing if b is empty. pb : push b - take the first element at the top of a and put it at the top of b. Do nothing if a is empty. ra : rotate a - shift up all elements of stack a by 1. The first element becomes the last one. rb : rotate b - shift up all elements of stack b by 1. The first element becomes the last one. rr : ra and rb at the same time. rra : reverse rotate a - shift down all elements of stack a by 1. The last element becomes the first one. run: ARG=`ruby -e "puts (1..50).to_a.shuffle.join(' ')"`; ./push_swap $ARG | ./checker -vcat $ARG<file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* push_swap.h :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: fsinged <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/08/06 11:47:15 by fsinged #+# #+# */ /* Updated: 2019/09/26 13:14:31 by fsinged ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef PUSH_SWAP_H # define PUSH_SWAP_H # include "libft.h" typedef struct s_ar { int *a; int *b; int sizea; int sizeb; } t_ar; /* ** Rules */ void swap(int *ar, int size, int h); void swap_ab(t_ar *ar, int h); void push(int *a, int *b, int *size, int *sizeb); void push_ab(t_ar *ar, char c); void rotate(int *ar, int size, int h); void rotate_ab(t_ar *ar, int h); void rrotate(int *ar, int size, int h); void rrotate_ab(t_ar *ar, int h); /* ** functions.c */ int issorted(int *a, int size, char c); void free_struct(t_ar **ar); t_ar *init_ar(t_ar *ar, int size); int readnumbers(int argc, char **argv, t_ar *ar); void small_sort(int *a, int size); void sort(t_ar *ar); void big_sort(t_ar *ar, int avg); /* ** help.c */ int get_avg2(int *a, int size, int avg, int flag); int get_avg(int *a, int size); int get_max(int *b, int size); int get_min(int *b, int size); int *get_maxs(int *ar, int size, int *max); int *get_mins(int *ar, int size, int *min); /* ** pusher.c */ int count_avg(int *a, int size, int avg, int flag); void push_a_first(t_ar *ar, int avg, int *min, int *cnt); #endif <file_sep>#******************************************************************************# # # # ::: :::::::: # # Makefile :+: :+: :+: # # +:+ +:+ +:+ # # By: fsinged <<EMAIL>> +#+ +:+ +#+ # # +#+#+#+#+#+ +#+ # # Created: 2019/08/07 12:42:32 by fsinged #+# #+# # # Updated: 2019/09/26 12:52:12 by fsinged ### ########.fr # # # #******************************************************************************# CC = gcc -Wall -Wextra -Werror PUSH = push_swap CHECKER = checker SRCS_PATH = ./src/ SRCS_FILES = functions.c push.c rotate.c swap.c reader.c SRCS = $(addprefix $(SRCS_PATH), $(SRCS_FILES)) SWAP = $(addprefix $(SRCS_PATH), push_swap.c) $(addprefix $(SRCS_PATH), sort.c) $(addprefix $(SRCS_PATH), help.c) $(addprefix $(SRCS_PATH), big_sort.c) \ $(addprefix $(SRCS_PATH), pusher.c) $(addprefix $(SRCS_PATH), help2.c) CHECK = $(addprefix $(SRCS_PATH), checker.c) LIB_PATH = ./libft/ LIB = ./libft/libft.a HEADER = -I ./includes/ -I ./libft/ all:$(LIB) $(PUSH) $(CHECKER) $(LIB): @make -C $(LIB_PATH) $(PUSH): @$(CC) $(SRCS) $(SWAP) $(LIB) $(HEADER) -o $(PUSH) $(CHECKER): @$(CC) $(SRCS) $(CHECK) $(LIB) $(HEADER) -o $(CHECKER) clean: @make fclean -C $(LIB_PATH) fclean:clean @/bin/rm -f $(PUSH) $(CHECKER) re:fclean all<file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* test.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: fsinged <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/04/22 11:19:26 by fsinged #+# #+# */ /* Updated: 2019/04/22 13:29:38 by fsinged ### ########.fr */ /* */ /* ************************************************************************** */ #include "get_next_line.h" int read_line(const int fd, char **str) { char *tmp; char buf[BUFF_SIZE + 1]; int ret; while (!(ft_strchr(*str, '\n')) && (ret = read(fd, buf, BUFF_SIZE)) > 0) { buf[ret] = '\0'; tmp = *str; *str = ft_strjoin(*str, buf); ft_strdel(&tmp); } return (ret); } int get_next_line(const int fd, char **line) { static char *str[2147483647]; char *tmp; if (fd < 0 || !line || BUFF_SIZE < 0 || (!str[fd] && !(str[fd] = ft_strnew(1))) || read_line(fd, &str[fd]) == -1) return (-1); if (ft_strchr(str[fd], '\n')) { tmp = str[fd]; *line = ft_strsub(str[fd], 0, ft_strchr(str[fd], '\n') - str[fd]); str[fd] = ft_strsub(ft_strchr(str[fd], '\n'), 1, ft_strlen(ft_strchr(str[fd], '\n')) - 1); ft_strdel(&tmp); } else { *line = ft_strdup(str[fd]); ft_strdel(&str[fd]); } if (str[fd] || ft_strlen(*line)) return (1); return (0); } <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_strsplit.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: fsinged <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/04/08 13:57:16 by fsinged #+# #+# */ /* Updated: 2019/04/16 12:37:55 by fsinged ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" static size_t ft_count_words(char const *s, char c) { size_t count; size_t i; count = 0; i = 0; while (s[i]) { if ((s[i] == c && s[i + 1] != c && s[i + 1] != '\0') || (s[i] != c && i == 0)) count++; i++; } return (count); } static char **ft_split(char const *s, char c, char **str, size_t len) { size_t i; size_t j; size_t k; i = 0; k = 0; while (s[i]) { if ((s[i] != c && s[i - 1] == c) || (i == 0 && s[i] != c)) { j = 0; while (s[i + j] != c && s[i + j]) j++; str[k] = ft_strsub(s, i, j); if (str[k] == NULL) free(str[k]); k++; i = i + j; } if (s[i] != '\0') i++; } str[len] = NULL; return (str); } char **ft_strsplit(char const *s, char c) { char **str; size_t len; if (!s) return (NULL); len = ft_count_words(s, c); str = (char**)malloc(sizeof(char*) * (len + 1)); if (str == NULL) return (NULL); return (ft_split(s, c, str, len)); } <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* new_big_sort.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: fsinged <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/09/12 14:50:10 by fsinged #+# #+# */ /* Updated: 2019/09/27 16:10:12 by fsinged ### ########.fr */ /* */ /* ************************************************************************** */ #include "push_swap.h" /* ** Push all elements > avg + avg / 2 to stack b ** all element bigger we rotate to the and of a ** If we got minimum, then we're rotate it to the end of stack a ** if we didn't rotate anything else */ static void push_b_third(t_ar *ar, int av, int avg) { int count; int rra; int max; rra = 0; count = count_avg(ar->a, ar->sizea, avg, 2); while (count > 0) if (ar->a[0] > avg && ar->a[0] <= av && count--) push_ab(ar, 'b'); else if (++rra) rotate(ar->a, ar->sizea, 1); max = ar->b[get_max(ar->b, ar->sizeb)]; while (rra-- > 0) if (ar->b[0] != max) rrotate_ab(ar, 1); else rrotate(ar->a, ar->sizea, 1); } /* ** Push b all elememnts <= avg ** Then we're push back all elemts is bigger then avg / 2 ** if we got minimum, then we're push it to a and rotate */ static void push_b_first(t_ar *ar, int avg, int *min, int *cnt) { int count; int av; count = count_avg(ar->a, ar->sizea, avg, 0); while (count > 0) if (ar->a[0] <= avg && count--) push_ab(ar, 'b'); else rotate(ar->a, ar->sizea, 1); av = get_avg(ar->b, ar->sizeb); count = count_avg(ar->b, ar->sizeb, av, 1); while (count > 0) if (ar->b[0] > av && count--) push_ab(ar, 'a'); else if (ar->b[0] == min[0] && ++(*cnt)) { push_ab(ar, 'a'); if (ar->b[0] <= av) rotate_ab(ar, 1); else rotate(ar->a, ar->sizea, 1); min = get_mins(ar->b, ar->sizeb, min); } else rotate(ar->b, ar->sizeb, 2); } static void push_b_fourth(t_ar *ar, int avg, int flag) { while ((flag && ar->a[0] <= avg) || (!flag && ar->a[0] > avg)) push_ab(ar, 'b'); } /* ** Push all elements <= avg on the top of a ** if we got minimum, then we're rotate it to end of stack a */ static void push_b_second(t_ar *ar, int av, int avg, int flag) { int count; int max; count = 0; while ((flag && ar->a[0] <= avg) || (!flag && ar->a[0] > avg)) if (ar->a[0] > av && ++count) rotate(ar->a, ar->sizea, 1); else push_ab(ar, 'b'); max = ar->b[get_max(ar->b, ar->sizeb)]; while (count-- > 0) if (ar->b[0] == max) rrotate(ar->a, ar->sizea, 1); else rrotate_ab(ar, 1); } /* ** Sort for 10-... elements */ void big_sort(t_ar *ar, int avg) { int *min; int cnt; cnt = 0; min = (int*)malloc(sizeof(int) * 3); push_b_first(ar, avg, get_mins(ar->a, ar->sizea, min), &cnt); push_a_first(ar, get_avg(ar->b, ar->sizeb), get_mins(ar->b, ar->sizeb, min), &cnt); push_b_second(ar, get_avg2(ar->a, ar->sizea - cnt, avg, 0), avg, 1); push_a_first(ar, get_avg(ar->b, ar->sizeb), get_mins(ar->b, ar->sizeb, min), &cnt); push_b_fourth(ar, avg, 1); push_a_first(ar, get_avg(ar->b, ar->sizeb), get_mins(ar->b, ar->sizeb, min), &cnt); push_b_third(ar, get_avg2(ar->a, ar->sizea - cnt, avg, 1), avg); push_a_first(ar, get_avg(ar->b, ar->sizeb), get_mins(ar->b, ar->sizeb, min), &cnt); push_b_second(ar, get_avg2(ar->a, ar->sizea - cnt, avg, 2), avg, 0); push_a_first(ar, get_avg(ar->b, ar->sizeb), get_mins(ar->b, ar->sizeb, min), &cnt); push_b_fourth(ar, avg, 0); push_a_first(ar, get_avg(ar->b, ar->sizeb), get_mins(ar->b, ar->sizeb, min), &cnt); free(min); } <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* sort.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: fsinged <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/09/05 13:09:15 by fsinged #+# #+# */ /* Updated: 2019/09/06 14:31:44 by fsinged ### ########.fr */ /* */ /* ************************************************************************** */ #include "push_swap.h" /* ** Push all element from statck b to stack a */ static void push_a(t_ar *ar, int *max) { int flag; max = get_maxs(ar->b, ar->sizeb, max); flag = 0; while (ar->sizeb > 0) { if (ar->b[0] == max[0]) { push_ab(ar, 'a'); if (flag) swap(ar->a, ar->sizea, 1); flag = 0; max = get_maxs(ar->b, ar->sizeb, max); } else if (ar->b[0] == max[1]) { push_ab(ar, 'a'); flag = 1; } } } /* ** Push elements to stack b */ static void push_b(t_ar *ar, int *max) { while (ar->sizea > 3) if (ar->a[0] < max[2]) push_ab(ar, 'b'); else rotate(ar->a, ar->sizea, 1); } /* ** Sort for 3-10 elements */ void sort(t_ar *ar) { int *max; max = (int*)malloc(sizeof(int) * 3); max = get_maxs(ar->a, ar->sizea, max); push_b(ar, max); small_sort(ar->a, ar->sizea); push_a(ar, max); free(max); } <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* pusher.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: fsinged <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/09/13 15:45:27 by fsinged #+# #+# */ /* Updated: 2019/09/26 13:07:26 by fsinged ### ########.fr */ /* */ /* ************************************************************************** */ #include "push_swap.h" /* ** Count all elements less or bigger then avg */ int count_avg(int *a, int size, int avg, int flag) { int count; int av; count = 0; av = get_avg2(a, size, avg, 1); while (--size >= 0) if ((flag == 0 && a[size] <= avg) || (flag == 1 && a[size] > avg) || (flag == 2 && a[size] > avg && a[size] <= av)) count++; return (count); } /* ** push a all elements in stack b ** if last element of stack b is minimum ** then we're push it to a and rotate it ** if last element of statck b is maximum ** then we're push it to top of stack a */ static void push_a_second(t_ar *ar, int *min, int *cnt) { int index; int max; int ra; ra = 0; while (ar->sizeb > 0) { index = get_max(ar->b, ar->sizeb); max = ar->b[index]; while (ar->b[0] != max) if (ar->b[0] == min[0] && ++(*cnt)) { push_ab(ar, 'a'); rotate(ar->a, ar->sizea, 1); min = get_mins(ar->b, ar->sizeb, min); } else if (index != 0 && index > ar->sizeb / 2) rrotate(ar->b, ar->sizeb, 2); else rotate(ar->b, ar->sizeb, 2); push_ab(ar, 'a'); ra++; } while (ra-- > 0 && ++(*cnt)) rotate(ar->a, ar->sizea, 1); } static void push_a_recursive(t_ar *ar, int *min, int *cnt, int flag) { int count; count = count_avg(ar->b, ar->sizeb, get_avg(ar->b, ar->sizeb), 1); if ((flag && count > 9) || (flag && count > 17)) push_a_first(ar, get_avg(ar->b, ar->sizeb), min, cnt); else push_a_second(ar, min, cnt); } static void push_a_help(t_ar *ar, int *min, int *cnt, int ret) { while (ret-- > 0) if (min[0] == ar->a[0] && min[0] < ar->b[get_min(ar->b, ar->sizeb)]) { rotate(ar->a, ar->sizea, 1); ++(*cnt); min = get_mins(ar->a, ar->sizea - *cnt, min); } else push_ab(ar, 'b'); } void push_a_first(t_ar *ar, int avg, int *min, int *cnt) { int count; int ret; int flag; ret = 0; flag = (ar->sizea + ar->sizeb) > 200; while (((count = count_avg(ar->b, ar->sizeb, avg, 1)) > 9 && !flag) || (count > 17 && flag)) while ((avg = count > 0 ? avg : get_avg(ar->b, ar->sizeb)) && count > 0) if (ar->b[0] > avg && count-- && ++ret) push_ab(ar, 'a'); else if (ar->b[0] == min[0] && ++(*cnt)) { push_ab(ar, 'a'); if (ar->b[0] <= avg) rotate_ab(ar, 1); else rotate(ar->a, ar->sizea, 1); min = get_mins(ar->b, ar->sizeb, min); } else rotate(ar->b, ar->sizeb, 2); push_a_second(ar, get_mins(ar->b, ar->sizeb, min), cnt); push_a_help(ar, get_mins(ar->a, ar->sizea - *cnt, min), cnt, ret); push_a_recursive(ar, get_mins(ar->b, ar->sizeb, min), cnt, flag); } <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* help.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: fsinged <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/09/05 11:36:41 by fsinged #+# #+# */ /* Updated: 2019/09/26 12:53:05 by fsinged ### ########.fr */ /* */ /* ************************************************************************** */ #include "push_swap.h" /* ** Get average element */ int get_avg(int *a, int size) { double count; int i; i = 0; count = 0; while (i < size) count += a[i++]; return ((int)(count / size - 0.5)); } int get_max(int *b, int size) { int index; index = 0; while (--size > 0) index = b[size] > b[index] ? size : index; return (index); } /* ** Finding index of minumun element */ int get_min(int *b, int size) { int index; index = 0; while (--size > 0) index = b[size] < b[index] ? size : index; return (index); } /* ** Get 3 minimim element */ int *get_mins(int *ar, int size, int *min) { min[0] = ar[0]; min[1] = ar[get_max(ar, size)]; min[2] = min[1]; while (--size > 0) if (min[0] > ar[size]) { min[2] = min[1]; min[1] = min[0]; min[0] = ar[size]; } else if (min[1] > ar[size]) { min[2] = min[1]; min[1] = ar[size]; } else if (min[2] > ar[size]) min[2] = ar[size]; return (min); } /* ** Get 3 maximum element */ int *get_maxs(int *ar, int size, int *max) { max[0] = ar[0]; max[1] = ar[get_min(ar, size)]; max[2] = max[1]; while (--size > 0) if (max[0] < ar[size]) { max[2] = max[1]; max[1] = max[0]; max[0] = ar[size]; } else if (max[1] < ar[size]) { max[2] = max[1]; max[1] = ar[size]; } else if (max[2] < ar[size]) max[2] = ar[size]; return (max); } <file_sep>/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* push_swap.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: fsinged <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/09/03 12:16:08 by fsinged #+# #+# */ /* Updated: 2019/09/16 15:10:56 by fsinged ### ########.fr */ /* */ /* ************************************************************************** */ #include "push_swap.h" /* ** Sort for 3 elements */ void small_sort(int *a, int size) { if (size == 2 && a[0] > a[1]) swap(a, size, 1); while (!(issorted(a, size, 'a'))) { if (a[0] > a[1] && a[0] > a[2]) rotate(a, size, 1); else if (a[0] > a[1] && a[0] < a[2]) swap(a, size, 1); else rrotate(a, size, 1); } } static void push_swap(t_ar *ar) { if (issorted(ar->a, ar->sizea, 'a')) return ; if (ar->sizea < 3) small_sort(ar->a, ar->sizea); else if (ar->sizea < 10) sort(ar); else big_sort(ar, get_avg(ar->a, ar->sizea)); } int main(int argc, char **argv) { t_ar *ar; if (argc == 1) return (0); ar = (t_ar*)malloc(sizeof(t_ar)); if (readnumbers(argc - 1, argv + 1, ar)) push_swap(ar); else write(1, "Error\n", 6); free_struct(&ar); return (0); }
2de7766cb66d1bea9adf17b7bef3d9dd9843e059
[ "Markdown", "C", "Makefile" ]
12
C
brokenFdreams/push_swap-42
89e0279b82b0fccdedaa3ecc28d6c17733214bda
269d7040f68604049d6a059cb62a60ed21e0c6c0
refs/heads/master
<repo_name>dm4t/Reklama5-Scraper<file_sep>/Reklama5 Scrapper/Reklama5 Scrapper/Reklama5 Scrapper/Form1.cs using OpenQA.Selenium; using OpenQA.Selenium.Chrome; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; /* Selenium ChromeDrive treba da bide kompetabilen so Chrome na PC https://chromedriver.chromium.org/downloads moze da se simen driver i da se dodade vo bin/Debug ili da se napravi Updata na NuGet Pucket vo Visual Studio */ namespace Reklama5_Scrapper { public partial class Form1 : Form { static string titleS; static string cenaS; static int s = 0; static int end = 0; string model; string godinaOd; string godinaDo; string cenaOd; string cenaDo; string kmOd; string kmDo; static IWebDriver Driver; string Grad; string Gorivo; string Menuvac; string Registracija; Thread Car; static object lockObject = new object(); public Form1() { InitializeComponent(); // Kriiranje na koloniv vo DataGrideView dataGridView1.Columns.Add("ID", "ID"); dataGridView1.Columns.Add("Оглас", "Оглас"); dataGridView1.Columns.Add("Цена", "Цена"); } public void CarScrap() //Funkcija za kriiranje na thread { IWebElement element; //elementi Driver = new ChromeDriver(); //Dreiver //Navaigate() otvaranje an link vo chrome Driver.Navigate().GoToUrl("https://reklama5.mk/Search?q=&city=&sell=0&sell=1&buy=0&buy=1&trade=0&trade=1&includeOld=0&includeOld=1&includeNew=0&includeNew=1&f31=&priceFrom=9000&priceTo=12000&f33_from=&f33_to=&f36_from=&f36_to=&f35=&f37=&f138=&f10016_from=&f10016_to=&private=0&company=0&page=1&SortByPrice=1&zz=1&cat=24"); //Selektiranje na godinaOd prku ID HTML element if(godinaOd!=null) (new OpenQA.Selenium.Support.UI.SelectElement(Driver.FindElement(By.Id("f33_from")))).SelectByValue(godinaOd); try { //Selektiranje na godinaDo prku ID HTML element (new OpenQA.Selenium.Support.UI.SelectElement(Driver.FindElement(By.Id("f33_to")))).SelectByText(godinaDo); }catch (Exception e) { } try { //Selektiranje na modele od prku ID HTML element (new OpenQA.Selenium.Support.UI.SelectElement(Driver.FindElement(By.Id("f31")))).SelectByText(model); } catch (Exception e) { } //Selektiranje na cenaOd prku ID HTML element if (cenaOd!=null) (new OpenQA.Selenium.Support.UI.SelectElement(Driver.FindElement(By.Id("priceFrom")))).SelectByValue(cenaOd); //Selektiranje na cenaDo prku ID HTML element if (cenaDo != null) (new OpenQA.Selenium.Support.UI.SelectElement(Driver.FindElement(By.Id("priceTo")))).SelectByValue(cenaDo); //Selektiranje na pominati kilometriOd prku ID HTML element if (kmOd != null) (new OpenQA.Selenium.Support.UI.SelectElement(Driver.FindElement(By.Id("f36_from")))).SelectByValue(kmOd); //Selektiranje na pominati kilometriDo prku ID HTML element if (kmDo != null) (new OpenQA.Selenium.Support.UI.SelectElement(Driver.FindElement(By.Id("f36_to")))).SelectByValue(kmDo); //Selektiranje na grad prku ID HTML element if (Grad != null) try { (new OpenQA.Selenium.Support.UI.SelectElement(Driver.FindElement(By.Id("city")))).SelectByText(Grad); } catch (Exception ea) { } //Selektiranje na tip na gorivo prku ID HTML element if (Gorivo != null) try { (new OpenQA.Selenium.Support.UI.SelectElement(Driver.FindElement(By.Id("f35")))).SelectByText(Gorivo); } catch (Exception vb) { } //Selektiranje na tip na menuvac prku ID HTML element if (Menuvac != null) try { (new OpenQA.Selenium.Support.UI.SelectElement(Driver.FindElement(By.Id("f37")))).SelectByText(Menuvac); } catch (Exception ma) { } //Selektiranje na registracija stranska/mkedonskai preku ID HTML element if (Registracija != null) try { (new OpenQA.Selenium.Support.UI.SelectElement(Driver.FindElement(By.Id("f138")))).SelectByText(Registracija); } catch (Exception am) { } //Pronaoganje na prebaraj kopce preku cssSelector element = Driver.FindElement(By.CssSelector("input.btn.btn-xs.btn-primary")); element.Click(); //Simuliranje na kliki na button IList<IWebElement> test = Driver.FindElements(By.ClassName("OglasResults")); //Dodavanje na site formi koj imaat Class Name OglasResults vo lista IWebElement temp; Thread.Sleep(2000); //veriabli koj se kporistat da se spravat so brojot na stranici pri int pageLock = 0; int endLock = 0; try { while ((pageLock != 1)||(endLock != 1)) { string[] strana = null; try { // Se bara element vo HTML koj pokazuva kolku ima strani temp = Driver.FindElement(By.ClassName("number-of-pages")); strana = temp.Text.Split(' '); // Kastiranje na brojot an strani } catch (Exception e) { pageLock = 1; } string title; //Titie na oglas string cena; //Cena na oglas test = Driver.FindElements(By.ClassName("OglasResults")); foreach (IWebElement element1 in test) //Prelistuvanje na site oglasi koj prethodno se najdeni i dadadeni vo lista { //pronaoganje na Titlei I cena na avtompbil preku className i cssselector temp = element1.FindElement(By.ClassName("SearchAdTitle")); title = temp.Text; temp = element1.FindElement(By.CssSelector("div.text-left.text-success")); cena = temp.Text; //Koristenje Invoke za da se azurira datagridview so novite podatoci this.Invoke((MethodInvoker)delegate { dataGridView1.Rows.Add(s++, title, cena); }); } Thread.Sleep(500); //Proverka dali stranicata ja koja se naogame e posledna za da zavrsi sobiranjeto podatoci if (strana[1].Equals(strana[3]) == false) { temp = Driver.FindElement(By.ClassName("prev-nextPage")); //klikanje next page doloku ima uste strani temp.Click(); Thread.Sleep(5000); //pauza na threa 5 s za da loadira sledan stranica } else { // endLock = 1; //endlock koga e 1 zavrsuva prebaruvanje MessageBox.Show("Завршено"); break; } } } catch (Exception e) { MessageBox.Show("Завршено"); } } private void button1_Click(object sender, EventArgs e) { model = comboBox1.Text; godinaOd = comboBox2.Text; godinaDo = comboBox3.Text; cenaOd = comboBox5.Text; cenaDo = comboBox4.Text; kmOd = comboBox7.Text; kmDo = comboBox6.Text; Grad = comboBox8.Text; Gorivo = comboBox9.Text; Menuvac = comboBox10.Text; Registracija = comboBox11.Text; Car = new Thread(CarScrap); //kriiranje na thread Car.Start(); // start na thread } private void timer1_Tick(object sender, EventArgs e) { } private void panel1_Paint(object sender, PaintEventArgs e) { } private void label11_Click(object sender, EventArgs e) { } private void Form1_Load(object sender, EventArgs e) { } } }
7c11694c90b0bb5ad4a22b2c7aa76bc6d7298f26
[ "C#" ]
1
C#
dm4t/Reklama5-Scraper
fc70aaa5a02579ffd93ab55785009513a1e5edaa
87a5ac00b01047500f0382ece65e6ff2184af8ff
refs/heads/master
<repo_name>mjkern/bash-practice<file_sep>/4-arithmetic/4a-randUpTo.sh #!/bin/bash echo a random number between 0 and $1: echo "$(( $RANDOM % $1 ))" <file_sep>/6-loops/3-mastermind.sh #!/bin/bash ### SETUP ### # generate code CODE='' for I in {1..4} do CODE="$CODE$(( $RANDOM % 4 + 1 )) " done # notify user echo Welcome to mastermind! I already have thought of a secret code. echo It may contain any of the numbers 1, 2, 3, and 4, possibly more echo than once. The code is four numbers long. You may begin echo guessing by entering four \(space-separated\) numbers. echo # misc NUM_GUESSES=0 NUM_CORRECT=0 ### PLAY GAME ### until [ $NUM_CORRECT -eq 4 ] do # get the guess read -p "enter a guess: " GUESS (( NUM_GUESSES++ )) # count the correct characters NUM_CORRECT=0 for I in {1..4} do GUESS_INT=$( echo $GUESS | cut -d ' ' -f$I ) CORRECT_INT=$( echo $CODE | cut -d ' ' -f$I ) if [ $GUESS_INT -eq $CORRECT_INT ] then (( NUM_CORRECT++ )) fi done echo $NUM_CORRECT correct number and position # count the number of correct characters in the wrong position NUM_HALF_CORRECT=0 GUESS_INDEX=1 CODE_INDEX=1 while [ $GUESS_INDEX -le 4 ] && [ $CODE_INDEX -le 4 ] do GUESS_INT=$( echo $GUESS | cut -d ' ' -f 1-4 --output-delimiter=$'\n' | sort | cut -d $'\n' -f $GUESS_INDEX ) CODE_INT=$( echo $CODE | cut -d ' ' -f 1-4 --output-delimiter=$'\n' | sort | cut -d $'\n' -f $CODE_INDEX ) if [ $CODE_INT -eq $GUESS_INT ] then (( NUM_HALF_CORRECT++ )) (( CODE_INDEX++ )) (( GUESS_INDEX++ )) elif [ $CODE_INT -lt $GUESS_INT ] then (( CODE_INDEX++ )) else # [ $GUESS_INT -lt $CODE_INT ] --> must be true (( GUESS_INDEX++ )) fi done NUM_HALF_CORRECT=$(( NUM_HALF_CORRECT - NUM_CORRECT )) # don't double count echo $NUM_HALF_CORRECT correct but in the wrong position done ### GAME OVER ### echo you did it! echo "it took you $NUM_GUESSES guess(es)" <file_sep>/4-arithmetic/2-tomorrow.sh #!/bin/bash echo "tommorow's date is:" date -d @$(( $(date +%s) + (60 * 60 * 24) )) <file_sep>/3-input/4-filterLs.sh #!/bin/bash echo hopefully you piped some \'ls -l\' stuff into here... echo your filtered list: # cut skips the first line, which is always "total [#]" cat /dev/stdin | cut -d $'\n' -f 2- | awk '{print $9 " (" $3 ")"}' <file_sep>/5-ifStatements/2-fileInfo.sh #!/bin/bash if [ ! $# -eq 1 ] then echo please input exactly one string exit 1 fi if [ -e $1 ] then echo $1 exists if [ -x $1 ] then echo and is executable else echo but is not executable fi else echo $1 does not exist fi <file_sep>/6-loops/2-dirFacts.sh #!/bin/bash if [ ! $# -eq 1 ] then echo please specify a directory exit 1 elif [ ! -d $1 ] then echo $1 is not a directory exit 2 fi for thing in $(ls $1) do path="$1$thing" if [ -d $path ] then echo $thing is a directory that contains $(ls $path | wc -l) items elif [ -e $path ] then echo $thing is a $(stat -c %s $path)-byte file else echo "I don't know what $thing is..." fi done <file_sep>/4-arithmetic/1-mult.sh #!/bin/bash echo multiplying $1 and $2 with different methods: echo echo let: let A=$1*$2 echo $A echo echo expr: expr $1 \* $2 echo echo aritmetic expansion: echo $(( $1 * $2)) <file_sep>/6-loops/1-nums.sh #!/bin/bash for i in {1..10} do if [ $(( $i % 2 )) -eq 0 ] then echo $i - even else echo $i - odd fi done <file_sep>/5-ifStatements/3-messageOfTheDay.sh #!/bin/bash if [ ! $# -eq 1 ] then echo "please input exactly one lowercase weekday" exit 1 fi case $1 in sunday) echo gearing up ;; monday) echo first is the worst ;; tuesday) echo second it the best ;; wednesday) echo wacky wednesday ;; thursday) echo thrifty thursday ;; friday) echo "thank God it's friday" ;; saturday) echo "finally" ;; *) echo "sorry, don't know that day..." ;; esac <file_sep>/3-input/3-thirdLine.sh #!/bin/bash echo hopefully you piped a few lines into this... echo and the third one is: cat /dev/stdin | cut -d$'\n' -f 3 <file_sep>/4-arithmetic/3-random.sh #!/bin/bash echo a random number between 0 and 100: echo "$(( $RANDOM % 100 ))" <file_sep>/5-ifStatements/1-larger.sh #!/bin/bash if [ $# != 2 ] then echo please input exactly two integers exit 1 fi if [ $1 -gt $2 ] then echo $1 else echo $2 fi <file_sep>/6-loops/2q #!/bin/bash ### SETUP ### # welcome echo Welcome to tic tac toe! # init state BOARD=$'1|2|3 ---\n4|5|6\n---\n7|8|9' echo $BOARD <file_sep>/3-input/2-message.sh #!/bin/bash read -p "please enter your first and last name: " FNAME LNAME read -p "and your height: " HEIGHT echo "hi $LNAME, $FNAME! glad to hear that your are $HEIGHT tall. also, you added $@ to the command - why?" <file_sep>/4-arithmetic/4b-randBetween.sh #!/bin/bash echo a random number between $1 and $2: echo "$(( $RANDOM % ($2 - $1) + $1 ))" <file_sep>/6-loops/4-ticTacToe.sh #!/bin/bash ### SETUP ### # welcome echo Welcome to tic tac toe! # init state declare -A BOARD for i in {1..9} do BOARD[$(( ($i - 1) / 3)),$(( ($i - 1) % 3 ))]=$i done ### GAME LOOP ### OVER=false until $OVER do # print the board for i in {0..2} do for j in {0..2} do printf "${BOARD[$i,$j]}" if [ ! $j -eq 2 ] then printf "|" fi done echo if [ ! $i -eq 2 ] then printf -- '-+-+-\n' fi done # get a valid move VALID=false until $VALID do read -p "On which space would you like to play? " MOVE for i in {1..9} do if [ $i = $MOVE ] then VALID=true break fi done if $VALID then break else echo Please make sure your move is an interger between 1 and 9. fi done # update the board ROW=$(( ($MOVE - 1) / 3 )) COL=$(( ($MOVE - 1) % 3 )) if [ ${BOARD[$ROW,$COL]} = $MOVE ] then BOARD[$ROW,$COL]=X else echo Please make sure to select an empty space. Try again: continue fi # check for player win if ([ ${BOARD[0,0]} = X ] && [ ${BOARD[1,0]} = X ] && [ ${BOARD[2,0]} = X ]) \ || ([ ${BOARD[0,1]} = X ] && [ ${BOARD[1,1]} = X ] && [ ${BOARD[2,1]} = X ]) \ || ([ ${BOARD[0,2]} = X ] && [ ${BOARD[1,2]} = X ] && [ ${BOARD[2,2]} = X ]) \ || ([ ${BOARD[0,0]} = X ] && [ ${BOARD[0,1]} = X ] && [ ${BOARD[0,2]} = X ]) \ || ([ ${BOARD[1,0]} = X ] && [ ${BOARD[1,1]} = X ] && [ ${BOARD[1,2]} = X ]) \ || ([ ${BOARD[2,0]} = X ] && [ ${BOARD[2,1]} = X ] && [ ${BOARD[2,2]} = X ]) \ || ([ ${BOARD[0,0]} = X ] && [ ${BOARD[1,1]} = X ] && [ ${BOARD[2,2]} = X ]) \ || ([ ${BOARD[0,2]} = X ] && [ ${BOARD[1,1]} = X ] && [ ${BOARD[2,0]} = X ]) \ then echo You Win! break fi # make the computer move for i in {0..2} do for j in {0..2} do if [ ! ${BOARD[$i,$j]} = X ] && [ ! ${BOARD[$i,$j]} = O ]; then MOVE=${BOARD[$i,$j]} BOARD[$i,$j]=O break 2 fi done done echo Nice move. I will play on space $MOVE: # check for computer win if ([ ${BOARD[0,0]} = O ] && [ ${BOARD[1,0]} = O ] && [ ${BOARD[2,0]} = O ]) \ || ([ ${BOARD[0,1]} = O ] && [ ${BOARD[1,1]} = O ] && [ ${BOARD[2,1]} = O ]) \ || ([ ${BOARD[0,2]} = O ] && [ ${BOARD[1,2]} = O ] && [ ${BOARD[2,2]} = O ]) \ || ([ ${BOARD[0,0]} = O ] && [ ${BOARD[0,1]} = O ] && [ ${BOARD[0,2]} = O ]) \ || ([ ${BOARD[1,0]} = O ] && [ ${BOARD[1,1]} = O ] && [ ${BOARD[1,2]} = O ]) \ || ([ ${BOARD[2,0]} = O ] && [ ${BOARD[2,1]} = O ] && [ ${BOARD[2,2]} = O ]) \ || ([ ${BOARD[0,0]} = O ] && [ ${BOARD[1,1]} = O ] && [ ${BOARD[2,2]} = O ]) \ || ([ ${BOARD[0,2]} = O ] && [ ${BOARD[1,1]} = O ] && [ ${BOARD[2,0]} = O ]) \ then echo You Lose. break fi done ### GAME OVER ### echo Thanks for playing :\) <file_sep>/7-functions/1-evenOddCount.sh #!/bin/bash isEven () { if [ $(( $1 % 2 )) -eq 0 ]; then return 0 fi return 1 } for i in {1..10}; do if isEven $i; then echo $i is even else echo $i is odd fi done
692d82ba8eb7aaaa50c1c6ad3235752cf8ec4247
[ "Shell" ]
17
Shell
mjkern/bash-practice
3d9fb9f440ced37121ee0e3316a17e18d9b7a541
032d7d6081b2616043dc6a0271df20637dbd1ebe
refs/heads/master
<file_sep>from csv import reader from os.path import abspath, dirname, join, normpath from os import pardir from glob import glob from Cattle import Cow, Bull class InitLivSim(object): """ This class defines methods to read input data and initialize the model. The following methods are defined in this class: - compose_herd: - assign_breed_values - read_breed_data / read_feed_data / read_herd_data - select_breed_values All breed specific information is read in one big chunk from the csv-files. After the data has been read breed-specific dictionaries are defined containing the parameter values for cows and bulls separately. These separate dictionaries are passed to the constructor for the cows and bulls when they are called. """ def __init__(self, project_name='temp'): # Get path of the input-data path = abspath(join(dirname(__file__), pardir)) path = "temp\\" self.path = "temp\\" # System and management variables # feed + concentrate quantity for name in glob(join(path, "feed_quantity_*.csv")): file_path = normpath(name) forage_data, concentrate_data, pasture_data = self.read_feed_data(file_path) name = name.replace(normpath(path) + '\\', "") name = name.replace('.csv', "") name = name.replace(' ', "_") name1 = name.replace('feed_quantity', 'forage_quantity') setattr(self, name1, forage_data) name2 = name.replace('feed_quantity', 'concentrate_quantity') setattr(self, name2, concentrate_data) name3 = name.replace('feed_quantity', 'pasture_quantity') setattr(self, name3, pasture_data) # feed quality file_path = normpath(join(path, 'forage_quality.csv')) self.forage_quality = self.read_feed_quality_data(file_path) # concentrate quality file_path = normpath(join(path, 'concentrate_quality.csv')) self.concentrate_quality = self.read_feed_quality_data(file_path) # pasture quality file_path = normpath(join(path, 'pasture_quality.csv')) self.pasture_quality = self.read_feed_quality_data(file_path) # Read all afrc-related parameters for all breeds for name in glob(join(path, "*_afrc.csv")): file_path = normpath(name) breed_afrc = self.read_breed_data(file_path) name = name.replace(normpath(path) + '\\', "") name = name.replace('.csv', "") setattr(self, name, breed_afrc) # Read all other parameters for all breeds for name in glob(join(path, "*_param.csv")): file_path = normpath(name) breed_param = self.read_breed_data(file_path) name = name.replace(normpath(path) + '\\', "") name = name.replace('.csv', "") setattr(self, name, breed_param) # initial herd composition file_path = normpath(join(path, 'cow_data.csv')) self.herd_data = self.read_herd_data(file_path) # read herd management variables from the data file_path = normpath(join(path, 'HerdManagement.csv')) self.herd_vars = self.read_herd_management(file_path) @staticmethod def read_breed_data(file_name=None): with open(file_name) as csvfile: data = reader(csvfile) breed_data = {} for row in data: header = row[0] values = row[1:len(row)] try: values = [float(i) for i in values if len(i) > 0] except ValueError: continue if len(values) == 1: values = values[0] breed_data[header] = values return breed_data @staticmethod def read_feed_quality_data(file_name=None): with open(file_name) as csvfile: data = reader(csvfile) temp_data = [] # Read in the raw data from the .csv-file for row in data: temp_data.append(row) # Remove the header line from the data temp_data = temp_data[1:len(temp_data)] index = 0 # Convert the numerical data to floats for row in temp_data: row_new = [] for value in row: try: value = float(value) except ValueError: value = value row_new.append(value) temp_data[index] = row_new index += 1 max_feed = int(max([i[1] for i in temp_data])) # Select sets of data belonging to a specific feed type and store these data in a dictionary feed_quality_data = {} for feed in range(1, max_feed + 1): temp_dict = {} temp_feed = [i for i in temp_data if i[1] == feed] for row in temp_feed: header = row[0] values = row[2:len(row)] temp_dict[header] = values feed_quality_data[str(feed)] = temp_dict return feed_quality_data @staticmethod # dict: roughage --> dict: feed_ids # dict: concentrate --> dict: feed_ids def read_feed_data(file_name=None): with open(file_name) as csvfile: data = reader(csvfile) temp_data = {} # Read in the raw data from the .csv-file for row in data: header = row[0] values = row[1:len(row)] values = [float(i) for i in values] temp_data[header] = values # Pasture grasses temp_pasture = [temp_data[i][1:] for i in temp_data if temp_data[i][0] == 1] pasture_data = {} for row in temp_pasture: header = str(int(row[0])) values = row[1:] pasture_data[header] = values # Concentrates temp_concentrate = [temp_data[i][1:] for i in temp_data if temp_data[i][0] == 2] concentrate_data = {} for row in temp_concentrate: header = str(int(row[0])) values = row[1:] concentrate_data[header] = values # Forages temp_forage = [temp_data[i][1:] for i in temp_data if temp_data[i][0] == 3] forage_data = {} for row in temp_forage: header = str(int(row[0])) values = row[1:] forage_data[header] = values return forage_data, concentrate_data, pasture_data @staticmethod def read_herd_data(file_name=None): with open(file_name) as csvfile: data = reader(csvfile) herd = {} for row in data: header = row[0] values = row[1:len(row)] values_new = [] for value in values: try: value = int(value) except ValueError: try: value = float(value) except ValueError: value = value if value.lower() == 'true': value = True elif value.lower() == 'false': value = False elif value == '-': value = 0 values_new.append(value) herd[header] = values_new return herd @staticmethod def read_herd_management(file_name=None): with open(file_name) as csvfile: data = reader(csvfile) herd_management = {} for row in data: header = row[0] values = row[1:len(row)] try: values = [int(i) for i in values] except ValueError: try: values = [float(i) for i in values] except ValueError: continue if len(values) == 1: values = values[0] herd_management[header] = values return herd_management if __name__ == '__main__': init = InitLivSim() <file_sep>#!/usr/bin/env python ######## # README ######## ''' Provides the cattle (Cow and Bull) models. Developed for Python 3. ''' ######## # Header ######## __author__ = "<NAME>" __copyright__ = "Copyright 2018, PPS" __credits__ = ["<NAME>","<NAME>","<NAME>","and many others"] __license__ = "Copyleft, see http://models.pps.wur.nl/content/licence_agreement" __version__ = "2.0.0" __maintainer__ = "<NAME>" __email__ = "<EMAIL>" __status__ = "Development" ################## # Import Libraries ################## import yaml import sys import pandas as pd from math import exp from copy import deepcopy from statistics import mean from scipy.interpolate import interp1d import random DAYS_PER_MONTH = 30 from decorators import CachedProperty ######################## # Small Helper Functions ######################## def interpolate(xys): ''' Takes xy pairs xys [[x0,y0],...[xn,yn]] and returns the associated piece-wise linear function y(x). ''' xs = [xy[0] for xy in xys] ys = [xy[1] for xy in xys] return interp1d(xs,ys,fill_value='extrapolate') ################ # Implementation ################ class BaseRuminant(object): ''' The base-class modelling cattle in LivSim (see reference [2]). The cattle is modelled, over time, in terms of it's state and associated rates of change linking the state over time accordingly: a dynamic model. Important note, some rates of change are stochastic. The time-resolution of the model is a (30-day) month. Rates are expressed accordingly e.g. body weight loss/gain is expressed in kg/month. The ruminant has a state (S) in terms of - body weight (kg) - feed supply (amount, quality) - is lactating (boolean) --- if it concerns a cow - ... and associated state changes (dS/dt) - body weight change (kg/month) - feed supply next month (amount, quality) - will stop lactating (boolean) - ... Here the change is a function of the current state (S_i) dS/dt = f(S_i) simulation amounts to updating the state (S_i+1) accordingly: S_i+1 = S_i + dS/dt * dt = S_i + f(S_i) * dt For details, see the update method "update". References ---------- [1] AFRC (1993) Energy and Protein Requirements of Ruminants [2] Quantifying the contribution of crop-livestock integration to African farming, 2008, Mariana .C. Rufino. Input ----- In running the model: feed --- see the "Feed" class. In parametrizing the model: breed/activity specific parameters e.g. - energy_cost_body_position_change - body_changes_per_day - horizontal_movement_per_day - vertical_movement_per_day - maximum_body_weight - minimum_body_weight - maximum_body_weight_gain - maximum_body_weight_loss - ... --- see the variable "parameters", how to access this is shown in the examples. Output ------ The value of all the state/rate variables, most importantly the - body weight - body weight change - energy supply/demand - protein supply/demand - production rates - milk --- if it concerns a cow - manure (amount, N,P,K) - urine (amount, N,P,K) Examples -------- Instantiating a default cow (default parameters/instantiation) >>> c = Cow() Inspecting it's properties (for the moment listed A--Z) >>> c Object: Cow Version: 5-04-2018+ Property Value Unit -------------------------------------------------------------- E_demand_activity 270.0000 MJ/month E_demand_fasting 971.2099 MJ/month E_demand_gestation 32.6455 ? E_demand_gestation_A 32.6455 ? E_demand_gestation_B 32.6432 ? E_demand_growth 0.0000 MJ/month E_demand_growth_potential 0.0000 MJ/month ... + 80 more Setting the supplied feed (instances of the "Feed" class): >>> c.roughage_supply = some_roughage_supply >>> c.concentrate_supply = some_concentrate_supply The cow will "respond" accordingly i.e. it's variable values will adjust accordingly. Updating a single time-step (a month): >>> c = c.update() Running the model, for a duration of N months, outputting the results to a DataFrame (spreadsheet data-structure): >>> df = c.run(duration=N) Notes ----- Although the model is designed for a monthly time resolution, currently, the model allows for arbitrary time-step size in the updating of the continuous variables. However, updating of the boolean variables does not. We might consider making this possible as well such that the whole model allows for arbitrary time-step size. ''' MAX_ITER = 8 FASTING_Q_M = 0.3 TOL_ME = 0.1 TOL_MP = 50 DETERMINISTIC = False _variable_metadata = yaml.load(''' ME_supply_feed: unit: 'MJ/month' ME_supply_concentrate: unit: 'MJ/month' ME_supply_concentrate_potential: unit: 'MJ/month' E_demand_activity: unit: 'MJ/month' E_demand_growth: unit: 'MJ/month' ME_demand_actual: unit: 'MJ/month' E_demand_fasting: unit: 'MJ/month' ME_demand_gestation: unit: 'MJ/month' ME_demand_growth_actual: unit: 'MJ/month' ME_demand_growth_potential: unit: 'MJ/month' ME_demand_lactation: unit: 'MJ/month' ME_demand_maintenance: unit: 'MJ/month' ME_demand_potential: unit: 'MJ/month' ME_supply_roughage: unit: 'MJ' ME_supply_roughage_potential: unit: 'MJ' MP_actual: unit: 'g' MP_supply_concentrate: unit: 'g' MP_demand_activity: unit: 'g' MP_demand_actual: unit: 'g' MP_demand_gestation: unit: 'g' MP_demand_growth_actual: unit: 'g' MP_demand_growth_potential: unit: 'g' MP_demand_lactation: unit: 'g' MP_demand_maintenance: unit: 'g' MP_demand_potential: unit: 'g' MP_supply_roughage: unit: 'g' body_weight: unit: 'kg' body_weight_fasted: unit: 'kg' correction_factor_C_L: unit: '1' fraction_concentrate_supply_eaten: unit: '1' fraction_roughage_supply_eaten: unit: '1' level_of_feeding: unit: '1' weight_change: unit: 'kg/month' E_demand_growth_potential: unit: 'MJ/month' E_demand_maintenance: unit: 'MJ/month' E_value_weight_gain: unit: 'MJ/kg' ME_shortage: unit: 'MJ/month' ME_supply_total: unit: 'MJ/month' ME_supply_feed_potential: unit: 'MJ/month' ME_supply_weight_loss: unit: 'MJ/month' ME_value_weight_gain: unit: 'MJ/kg' ME_value_weight_loss: unit: 'MJ/kg' MP_demand_growth: unit: 'g/month' MP_shortage: unit: 'g/month' MP_supply_total: unit: 'g/month' MP_supply_feed: unit: 'g/month' MP_supply_weight_loss: unit: 'g/month' MP_value_weight_gain: unit: 'g MP/kg' MP_value_weight_loss: unit: 'g MP/kg' P_demand_basal_endogenous_nitrogen: unit: 'g/month' P_demand_dermal_losses: unit: 'g/month' P_demand_maintenance: unit: 'g/month' body_weight_change: unit: 'kg/month' body_weight_change_per_day: unit: 'kg/day' body_weight_change_per_day_potential: unit: 'kg/day' potential_body_weight_gain: unit: 'kg/month' body_weight_gain: unit: 'kg/month' body_weight_loss: unit: 'kg/month' efficiency_ME_growth: unit: '1' efficiency_ME_growth_growing_ruminant: unit: '1' efficiency_ME_growth_lactating_ruminant: unit: '1' efficiency_ME_lactation: unit: '1' efficiency_ME_maintenance: unit: '1' efficiency_MP_growth: unit: '1' efficiency_MP_maintenance: unit: '1' energy_cost_activity: unit: 'MJ E/kg/day' faecal_DM: unit: 'kg/month' faecal_K: unit: 'g/month' faecal_N: unit: 'g/month' faecal_P: unit: 'g/month' is_lactating: unit: 'boolean' milk_butterfat_content: unit: 'g/kg' milk_crude_protein_content: unit: 'g/kg' milk_lactose_content: unit: 'g/kg' will_gain_weight: unit: 'boolean' will_lose_weight: unit: 'boolean' dt: unit: 'month' ''') DEFAULT_PARAMETERS = yaml.load(''' C1: value: 1.0 unit: 1 info: "Value for (female) cows: 1, (bulls: 1.15), key-determinant of/scales the fasting metabolism." source: "[1] page 23" C2: value: 1.15 unit: 1 info: Value for medium maturity type heifers, co-determines the energy value of liveweight gain. source: "[1] page 28 Table 2.1" C6: value: 1.0 unit: 1 info: Value for late heifers, parametrizes the protein demand for growth source: "[1] page 36" energy_cost_horizontal_movement: value: 0.0026 unit: kJ/kg/m source: "[1] page 24" energy_cost_vertical_movement: value: 0.028 unit: kJ/kg/m source: "[1] page 24" energy_cost_standing: value: 10 unit: kJ/kg/d source: "[1] page 24" energy_cost_body_position_change: value: 0.260 unit: kJ/kg source: "[1] page 24" body_changes_per_day: value: 10 unit: 1 source: "User defined, default based on [1] page 24--25." horizontal_movement_per_day: value: 1000 unit: meter source: "User defined, default based on [1] page 24--25." vertical_movement_per_day: value: 100 unit: meter source: "User defined, default based on [1] page 24--25." maximum_body_weight: value: [[0,60],[20,300],[40,500],[80,500]] unit: "[month,kg]" source: "Eyed from [2], Appendix 2.1, Fig. A5: weight range for female cross-bred HosteilFreisian X Zebu." minimum_body_weight: value: [[0,20],[20,80],[40,120],[80,200],[140,220],[180,220]] unit: "[month,kg]" source: "Eyed from [2], Appendix 2.1, Fig. A5: weight range for female cross-bred HosteilFreisian X Zebu." potential_body_weight_gain: value: [[0.2,0.3], [0.3,0.5], [0.4,0.5], [0.5,1.0], [0.6,1.5], [0.7,2.0]] unit: "[1,kg/day]" info: "For females, the potential daily weight gain as a function of the metabolisability of the feed." source: "Taken from [2], Appendix 2.1, Table A1. After Tolkamp and Ketelaars (1994)." maximum_body_weight_loss: value: 50 unit: kg/month info: "Although not an original feature, it might be useful to have a maximum weight loss as a feature. To not use this feature, either set the value at a trivial value e.g. 200 kg/month or remove the feature altogether." source: "Ad hoc --- as a placeholder." mortality_probability: value: [[0,0], [60,0], [120,.02], [140,.02],] unit: "[month,1/month]" info: "The age-dependent mortalitity probability." ''') _name = 'BaseRuminant' _version = '5-04-2018+' ME_demand_calculation_method = "AFRC" def __init__(self,age = 0, body_weight = None): # setting the parameters self.parameters = self.DEFAULT_PARAMETERS self.set_private_state_variables() # parametrization in terms of functions self.set_parametrized_functions() # initialization of the state: # caching... --- a technical detail self._cache_id = 0 self._age = age if body_weight is None: self.body_weight = 0.5*(self.maximum_body_weight - self.minimum_body_weight) else: self.body_weight = body_weight self._dt = 1 self._roughage_supply = None self._concentrate_supply = None # If set over-rides the feed intake routine self._roughage_accepted = None self._concentrate_accepted = None self.roughage_accepted = self.get_roughage_accepted() self.concentrate_accepted = self.get_concentrate_accepted() # if set over-rides the potential body weight gain routine # a.k.a. compensatory growth (kg/month) self._potential_body_weight_gain = None self.will_die_by_chance = False #################### # Parameter related #################### @property def parameters(self): return self._parameters @parameters.setter def parameters(self, value): self._parameters = value self.set_parametrized_functions() def get_parameters(self): return deepcopy(self.parameters) def set_parametrized_functions(self): # parametrization in terms of functions self._maximum_body_weight_function = self.get_maximum_body_weight_function() self._minimum_body_weight_function = self.get_minimum_body_weight_function() self._potential_body_weight_gain_function = self.get_potential_body_weight_gain_function() self._mortalitity_probability_function = self.get_mortalitity_probability_function() ######################### # Parametrizing functions ######################### def get_potential_milk_yield_function(self): ''' Generates the function which returns the age dependent potential milk yield. ''' xys = self.parameters['milk_yield_potential']['value'] return interpolate(xys) def get_maximum_body_weight_function(self): ''' Generates the function which returns the age dependent max. body weight. ''' xys = self.parameters['maximum_body_weight']['value'] return interpolate(xys) def get_minimum_body_weight_function(self): ''' Generates the function which returns the age dependent min. body weight. ''' xys = self.parameters['minimum_body_weight']['value'] return interpolate(xys) def get_potential_body_weight_gain_function(self): ''' Generates the function which returns the qm dependent potential body weight gain (kg/day). ''' xys = self.parameters['potential_body_weight_gain']['value'] return interpolate(xys) def get_mortalitity_probability_function(self): ''' Generates the function which returns the age dependent mortality probability (1/month). ''' xys = self.parameters['mortality_probability']['value'] return interpolate(xys) ######### # General ######### def update_feed_intake(self): ''' Update the cache id and feed. ''' self.roughage_accepted = self.get_roughage_accepted() self.concentrate_accepted = self.get_concentrate_accepted() def update(self): ''' Update the model by a month. ''' if self.will_die: raise ValueError("The cow will die in this month \ (BW = {:}):\ can not update...".format(self.body_weight)) self.update_feed_intake() self.body_weight += self.body_weight_change*self.dt self._age += self.dt # Used in caching calculation results for CachedProperty descriptors self._cache_id += 1 self.will_die_by_chance = self.get_will_die_by_chance() return self def run(self,duration=1): ''' Run the model for a duration, returns a DataFrame. ''' if not isinstance(duration, int): raise ValueError if duration < 1: raise ValueError res = {} for i in range(duration): self.update() res[i] = self.to_dict() df = pd.DataFrame(res).T return df ################ # State-dynamism ################ @property def will_die(self): ''' Whether the beast will die in the coming month (bool). ''' return self.will_die_by_starvation or self.will_die_by_chance def get_will_die_by_chance(self): ''' Whether the beast will die in the coming month (bool). ''' if self.DETERMINISTIC: return False else: r = random.random() P = self.mortality_probability return r < P @property def mortality_probability(self): ''' The mortality probability in the coming month (1/month). ''' return float(self._mortalitity_probability_function(self.age)) ############ # Parameters ############ @property def _body_changes_per_day(self): ''' Part of the activity, see [1] page 24--25. ''' return self.parameters['body_changes_per_day']['value'] @property def _horizontal_movement_per_day(self): ''' Part of the activity, see [1] page 24--25. ''' return self.parameters['horizontal_movement_per_day']['value'] @property def _vertical_movement_per_day(self): ''' Part of the activity, see [1] page 24--25. ''' return self.parameters['vertical_movement_per_day']['value'] @property def age(self): ''' The ruminants age (month). ''' return self._age @property def dt(self): ''' The time-step used in updating the state (month). ''' return self._dt ###################### # Body weight related ###################### @property def will_die_by_starvation(self): ''' Whether the beast will die in the coming month (bool). ''' return self.body_weight < self.minimum_body_weight @CachedProperty def maximum_body_weight(self): ''' The age (and breed) dependent max. body weight (kg). ''' return float(self._maximum_body_weight_function(self.age)) @CachedProperty def minimum_body_weight(self): ''' The age (and breed) dependent min. body weight (kg). ''' return float(self._minimum_body_weight_function(self.age)) @property def condition_index(self): ''' The weight relative to the age-dependent bounds. I.e. 1 <--> max. weight, 0 <--> min. weight. ''' num = self.body_weight - self.minimum_body_weight denum = self.maximum_body_weight - self.minimum_body_weight return num/denum @property def body_weight_change(self): ''' The body weight change (kg/month). ''' return self.body_weight_gain - self.body_weight_loss @property def rel_body_weight_change(self): ''' The relative body weight change (%/month). ''' return 100*(self.body_weight_change/self.body_weight) @property def will_lose_weight(self): ''' A boolean (true/false) indicating whether weight loss should occur. ''' is_ME_supply_insufficient = self.ME_supply_feed < self.ME_demand_non_growth is_MP_supply_insufficient = self.MP_supply_feed < self.MP_demand_non_growth if is_ME_supply_insufficient or is_MP_supply_insufficient: return 1 else: return 0 @property def will_gain_weight(self): ''' A boolean (true/false) indicating whether weight gain should/will occur. ''' is_ME_supply_sufficient = self.ME_supply_feed > self.ME_demand_non_growth is_MP_supply_sufficient = self.MP_supply_feed > self.MP_demand_non_growth if is_ME_supply_sufficient and is_MP_supply_sufficient: return 1 else: return 0 @property def body_weight_loss(self): ''' The body weight loss (kg/month). Involves finding the weight gain which balances the ME/MP supply and demand. ''' verbose = 0 self.TOL_ME = .1 #MJ self.TOL_MP = 50 #g weight_loss_max = self.maximum_body_weight_loss # kg/month #actually function of age/breed |todo| weight_loss_min = 0 if self.will_lose_weight: body_weight = self.body_weight ME_supply_feed = self.ME_supply_feed MP_supply_feed = self.MP_supply_feed # binary search the right weight loss for i in range(self.MAX_ITER): # kg/month weight_loss_guess = mean([weight_loss_max, weight_loss_min]) body_weight_forecast = body_weight - 0.5 * weight_loss_guess ME_supply_weight_loss = self.ME_value_weight_loss * weight_loss_guess MP_supply_weight_loss = self.MP_value_weight_loss * weight_loss_guess ME_supply = ME_supply_feed + ME_supply_weight_loss MP_supply = MP_supply_feed + MP_supply_weight_loss ME_demand = self.calc_ME_demand_non_growth(body_weight_forecast) MP_demand = self.calc_MP_demand_non_growth(body_weight_forecast) is_ME_short = ME_supply < ME_demand - self.TOL_ME is_ME_abundant = ME_supply > ME_demand + self.TOL_ME is_MP_short = MP_supply < MP_demand - self.TOL_MP is_MP_abundant = MP_supply > MP_demand + self.TOL_MP more_weight_loss = is_ME_short or is_MP_short less_weight_loss = is_ME_abundant and is_MP_abundant if more_weight_loss: # continue search in upper half of the domain weight_loss_min = weight_loss_guess elif less_weight_loss: # continue search in lower half of the domain weight_loss_max = weight_loss_guess else: break return weight_loss_guess else: return 0 @property def body_weight_gain(self): ''' The body weight gain estimate (kg/month). Involves finding the weight gain which balances the ME/MP supply and demand. ''' verbose = 0 self.TOL_ME = .1 #MJ self.TOL_MP = 50 #g weight_gain_max = self.maximum_body_weight_gain weight_gain_min = 0 if self.will_gain_weight: body_weight = self.body_weight ME_supply = self.ME_supply_feed MP_supply = self.MP_supply_feed k_g = self.efficiency_ME_growth # binary search the right weight gain for i in range(self.MAX_ITER): # kg/month weight_gain_estimate = 0.5*(weight_gain_max + weight_gain_min) body_weight_forecast = body_weight + 0.5*weight_gain_estimate ME_demand_growth = self.calc_ME_demand_growth(body_weight_forecast,weight_gain_estimate) MP_demand_growth = self.calc_MP_demand_growth(body_weight_forecast,weight_gain_estimate) ME_demand_non_growth = self.calc_ME_demand_non_growth(body_weight_forecast) MP_demand_non_growth = self.calc_MP_demand_non_growth(body_weight_forecast) ME_demand = ME_demand_non_growth + ME_demand_growth MP_demand = MP_demand_non_growth + MP_demand_growth is_ME_short = ME_supply < ME_demand - self.TOL_ME is_ME_abundant = ME_supply > ME_demand + self.TOL_ME is_MP_short = MP_supply < MP_demand - self.TOL_MP is_MP_abundant = MP_supply > MP_demand + self.TOL_MP more_weight_gain = is_ME_abundant and is_MP_abundant less_weight_gain = is_ME_short or is_MP_short if more_weight_gain: # continue search in upper half of the domain weight_gain_min = weight_gain_estimate elif less_weight_gain: # continue search in lower half of the domain weight_gain_max = weight_gain_estimate else: break return weight_gain_estimate else: return 0 @property def body_weight_change_per_day(self): ''' The body weight change estimate (kg/day). ''' return self.body_weight_change/DAYS_PER_MONTH @property def maximum_body_weight_gain(self): ''' The maximum body weight gain (kg/month). ''' return max(0,self.maximum_body_weight - self.body_weight) @property def maximum_body_weight_loss(self): ''' The maximum body weight loss (kg/month). An optional feature, only emerges if a non-trivial maximum weight loss is set as a parameter. Namely, then if more weight loss is required than this limit, to meet ME/MP demands, this shows as a mis-match between ME/MP demand and supply. ''' return self.parameters['maximum_body_weight_loss']['value'] @property def potential_body_weight_gain(self): ''' The potential body weight gain (kg/month). ''' if self._potential_body_weight_gain is not None: return self._potential_body_weight_gain else: ub = self.maximum_body_weight_gain # a.k.a. "compensatory gain" daily_potential_gain = float(self._potential_body_weight_gain_function(self.q_m)) potential = DAYS_PER_MONTH*daily_potential_gain return max(0,min(potential,ub)) ############## # Feed related ############## @property def roughage_supply(self): ''' The roughage supply (a feed-object). ''' return self._roughage_supply @roughage_supply.setter def roughage_supply(self,value): ''' The roughage supply (a feed-object) setter. ''' self._roughage_supply = value self.roughage_accepted = self.get_roughage_accepted() @property def concentrate_supply(self): ''' The concentrate supply (a feed-object). ''' return self._concentrate_supply @concentrate_supply.setter def concentrate_supply(self,value): ''' The concentrate supply (a feed-object) setter. ''' self._concentrate_supply = value self.concentrate_accepted = self.get_concentrate_accepted() @property def level_of_feeding(self): ''' The level of feeding given the feed to be eaten. Is defined as the multiple of ME in the feed relative to the ME demand for maintenance: See [1] page 16: Typically 1<=L<=3 (from maintenance to pregnant). ''' return self.ME_supply_feed/self.ME_demand_maintenance @property def level_of_feeding_potential(self): ''' The potential level of feeding given the feed to be eaten. Is defined as the multiple of ME in the feed relative to the ME demand for maintenance: See [1] page 16: Typically 1<=L<=3 (from maintenance to pregnant). ''' num = self.ME_supply_feed_potential denum = self.ME_demand_maintenance return num/denum @property def correction_factor_C_L(self): ''' A correction factor co-determining the ME actually available to the animal. High levels of feeding decreases the ME available to the animal. This is taken into account via this correction factor which is a function of the level of feeding. See [1] page 4 eq. 12: "The ME actually available to the animal [...] reduced significantly at high levels of feeding due to the increased outflow rate from the rumen [...]." WARNING ------- Note, in the legacy the level of feeding (L, a continuous variable ranging in practice from around 0 to 5) is not calculated according to the AFRC manual [1] but instead set at discrete values, heuristically, e.g. at L=2 when the ruminant is lactating and L=1 otherwise. Accordingly the ME correction factor is not in line with the AFRC manual. ''' return 1 + 0.018*(self.level_of_feeding - 1) @property def body_weight_fasted(self): ''' See [1] page 23 below eq. 40. ''' return self.body_weight/1.08 ############## # Coefficients ############## @property def _C2(self): ''' Co-determines the energy value of weight gain, a coefficient (1). See [1] page 27, eq. 61. ''' return self.parameters['C2']['value'] @property def _C3(self): ''' Co-determines the energy value of weight gain, a coefficient (1). See [1] page 27, eq. 61. ''' # Note, a pretty weird parametrization by the AFRC... if self.level_of_feeding_potential <= 1: return 0 else: return 1 ############## # Efficiencies ############## @property def efficiency_ME_maintenance(self): ''' Efficiency for maintenance (MJ E/MJ ME). See [1] page 3. Denoted "k_m". ''' return 0.35*self.q_m + 0.503 @property def efficiency_ME_lactation(self): ''' Efficiency for lactation (MJ E/MJ ME). See [1] page 3. Denoted "k_l". ''' return 0.35*self.q_m + 0.420 @property def efficiency_ME_growth_growing_ruminant(self): ''' Efficiency for growth of a "growing" ruminant (MJ E/MJ ME). See [1] page 3. Denoted "k_f". ''' return 0.78*self.q_m + 0.006 @property def efficiency_ME_growth_lactating_ruminant(self): ''' Efficiency for growth of a "lactating" ruminant (MJ E/MJ ME). See [1] page 3. Denoted "k_g". ''' return 0.95*self.efficiency_ME_lactation @property def efficiency_ME_growth(self): ''' Efficiency for growth (MJ E/MJ ME). See [1] page 3. ''' if self.is_lactating: return self.efficiency_ME_growth_lactating_ruminant else: return self.efficiency_ME_growth_growing_ruminant @property def efficiency_MP_maintenance(self): ''' Efficiency for maintenance (g MP/g P). See [1] page 34. Denoted "k_nm". ''' return 1 @property def efficiency_MP_growth(self): ''' Efficiency for growth (g MP/g P). See [1] page 36. Denoted "k_nf". ''' return 0.59 ########### # ME supply ########### @property def ME_supply_total(self): ''' The total ME supply; from feed and weight loss (MJ/month). ''' return self.ME_supply_feed + self.ME_supply_weight_loss @property def ME_supply_feed(self): ''' The ME in the feed to be eaten (MJ). ''' return (self.ME_supply_roughage + self.ME_supply_concentrate) @property def ME_supply_concentrate(self): ''' The ME in the concentrate to be eaten (MJ). ''' if self.concentrate_accepted is None: return 0 else: return self.concentrate_accepted.ME_total @property def ME_supply_roughage(self): ''' The ME in the roughage to be eaten (MJ). ''' if self.roughage_accepted is None: return 0 else: return self.roughage_accepted.ME_total @property def ME_supply_weight_loss(self): ''' The ME supplied through weight loss (MJ/month). ''' dW = self.body_weight_change if dW < 0: return -self.ME_value_weight_loss*dW else: return 0 ############ # ME demands ############ @property def ME_demand_total(self): ''' The ME demand for maintenance AND production (MJ/month). See [1] page 9. ''' return self.ME_demand_non_growth + \ self.ME_demand_growth @property def ME_demand_potential(self): return self.ME_demand_non_growth + self.ME_demand_growth_potential @property def ME_demand_maintenance(self): ''' The ME demand for "maintenance" of the ruminant (MJ/month). ''' return self.calc_ME_demand_maintenance(self.body_weight) @property def ME_demand_maintenance_AFRC(self): ''' The ME demand for "maintenance" of the ruminant (MJ/month). ''' return self.calc_ME_demand_maintenance_AFRC(self.body_weight) @property def ME_demand_maintenance_MAFF(self): ''' The ME demand for "maintenance" of the ruminant (MJ/month). ''' return self.calc_ME_demand_maintenance_MAFF(self.body_weight) @property def ME_demand_non_growth(self): ''' The ME demand for non-growth (body-weight) related processes (MJ/month). ''' return self.ME_demand_maintenance @property def ME_demand_maintenance_production(self): ''' The ME demand for maintenance AND production (MJ/month). See [1] page 9. ''' return self.ME_demand_non_growth + self.ME_demand_growth @property def ME_shortage(self): ''' The difference in total ME demand and supply (g). ''' return max(0,self.ME_demand_total - self.ME_supply_total) @property def ME_demand_growth_potential(self): E = self.E_demand_growth_potential c = self.efficiency_ME_growth return E/c @property def ME_demand_growth(self): ''' The ME demand for the monthly growth (MJ/month). ''' return self.calc_ME_demand_growth(self.body_weight, self.body_weight_gain) def calc_ME_demand_growth(self,body_weight,body_weight_gain): ME_value = self.calc_ME_value_weight_gain(body_weight,body_weight_gain) return ME_value*body_weight_gain def calc_ME_demand_maintenance(self,body_weight): if self.ME_demand_calculation_method == "MAFF": return self.calc_ME_demand_maintenance_MAFF(body_weight) else: return self.calc_ME_demand_maintenance_AFRC(body_weight) def calc_ME_demand_maintenance_AFRC(self,body_weight): ''' The ME demand for maintenance (AFRC, 1993). Equals the sum of the E demand for fasting and activity, converted to ME demand via the ME use efficiency for maintenance. ''' E_demand_fasting = self.calc_E_demand_fasting(body_weight) E_demand_activity = self.calc_E_demand_activity(body_weight) return (E_demand_fasting + E_demand_activity)/self.efficiency_ME_maintenance def calc_ME_demand_maintenance_MAFF(self,body_weight): ''' The ME demand for maintenance (MAFF, 1987) (MJ/month). ''' return DAYS_PER_MONTH*(8.3 + 0.091*self.body_weight_fasted) def calc_ME_demand_non_growth(self,body_weight): ''' The ME demand for non-growth, here, maintenance (MJ/month). ''' return self.calc_ME_demand_maintenance(body_weight) @property def ME_value_weight_gain(self): ''' The ME cost of gaining weight (MJ ME/kg gain). ''' return self.calc_ME_value_weight_gain(self.body_weight,self.body_weight_gain) def calc_ME_value_weight_gain(self,body_weight,body_weight_gain): ''' Calculate the ME cost of weight gain (MJ ME/kg gain). See [1] page 27, eq. 61. ''' return self.calc_E_value_weight_gain(body_weight,body_weight_gain)/self.efficiency_ME_growth @property def ME_value_weight_loss(self): ''' ME supply through of weight loss (MJ ME/kg loss). See [1] page 31, eq. 75. ''' return 19 ########## # ME demand ########## @property def E_demand_maintenance(self): ''' The energy demand for maintenance (MJ/month). See [1] page 23 eq. 39. ''' return self.E_demand_fasting + self.E_demand_activity @CachedProperty def E_demand_fasting(self): ''' The energy demand for fasting (MJ/month). See [1] page 23 eq. 40. ''' return self.calc_E_demand_fasting(self.body_weight) def calc_E_demand_fasting(self,body_weight): ''' Calculate the energy demand for fasting (MJ/month). Is a function of the body weight (first argument). See [1] page 23 eq. 40. ''' body_weight_fasted = body_weight / 1.08 C1 = self.parameters['C1']['value'] res = C1 * 0.53 * body_weight_fasted**0.67 return DAYS_PER_MONTH*res @property def E_demand_activity(self): ''' The energy demand for activity (MJ/month). See [1] page 24. ''' return self.calc_E_demand_activity(self.body_weight) def calc_E_demand_activity(self,body_weight): ''' Calculate the energy demand for activity (MJ/month). Is a function of the body weight (first argument). See [1] page 24. ''' c = self.energy_cost_activity kJ_to_MJ = 0.001 return kJ_to_MJ*c*body_weight*DAYS_PER_MONTH @CachedProperty def E_value_weight_gain(self): ''' The energy cost of gaining weight (MJ E/kg gain). ''' return self.calc_E_value_weight_gain(self.body_weight,self.body_weight_gain) def calc_E_value_weight_gain(self,body_weight,body_weight_gain): ''' Calculate the energy cost of weight gain (MJ E/kg gain). See [1] page 27, eq. 61. Note, not ME; not (MJ ME/kg gain), see "calc_ME_value_weight_gain". ''' W = body_weight if body_weight_gain < 0: raise ValueError dW = body_weight_gain / DAYS_PER_MONTH C2 = self._C2 C3 = self._C3 num = C2 * (4.1 + 0.0332 * W - 0.000009 * W**2) denum = 1 - (C3 * 0.1475*dW) if denum != 0: return num / denum else: raise ValueError @CachedProperty def E_demand_growth(self): ''' Growth energy demand (MJ/month). See [1] page 27, eq. 61. ''' if self.will_lose_weight: return 0 else: W = self.body_weight dW = self.body_weight_change EV_g = self.calc_E_value_weight_gain(W, dW) return dW * EV_g @property def E_demand_growth_potential(self): ''' Growth energy demand (MJ/month). See [1] page 27, eq. 61. ''' W = self.body_weight dW = self.potential_body_weight_gain # Note, here we do use the mid-update weight # since the result actually determines the # feed intake; it is not solely a view # on the state of the object. W_ = W + 0.5*dW EV_g = self.calc_E_value_weight_gain(W_,dW) return dW*EV_g @CachedProperty def energy_cost_activity(self): ''' The energy cost of activity (movement/standing) (kJ/kg/d). Follows from the sum of the energy cost of 1. Standing 2. Body position changes 3. Horizontal movement 4. Vertical movement ''' # all per kg ecs = self.parameters['energy_cost_standing']['value'] ecbc = self.parameters['energy_cost_body_position_change']['value'] echm = self.parameters['energy_cost_horizontal_movement']['value'] ecvm = self.parameters['energy_cost_vertical_movement']['value'] bc = self._body_changes_per_day hm = self._horizontal_movement_per_day vm = self._vertical_movement_per_day # kJ/kg/day ec = ecs + ecbc*bc + ecvm*vm + echm*hm return ec ########### # P demand ########### @property def P_demand_basal_endogenous_nitrogen(self): ''' The protein (P) demand for basal maintenance (g/month). See [1] page 35 eq. 85. ''' return self.calc_P_demand_basal_endogenous_nitrogen(self.body_weight) @property def P_demand_dermal_losses(self): ''' The protein (P) demand for maintaining dermal losses (g/month). See [1] page 35 eq. 86. ''' return self.calc_P_demand_dermal_losses(self.body_weight) def calc_P_demand_basal_endogenous_nitrogen(self,body_weight): ''' Calculates the protein (P) demand for basal maintenance (g/month). Is a function of the body weight (first argument). See [1] page 35 eq. 85. ''' return DAYS_PER_MONTH * 6.25 * 0.35 * body_weight**(0.75) def calc_P_demand_dermal_losses(self,body_weight): ''' Calculates the protein (P) demand for maintaining dermal losses (g/month). Is a function of the body weight (first argument). See [1] page 35 eq. 86. ''' return DAYS_PER_MONTH * 6.25 * 0.018 * body_weight**(0.75) def calc_P_demand_maintenance(self,body_weight): ''' Calculates the protein (P) demand for overall maintenance. Is a function of the body weight (first argument) and amounts to the sum of the P demand for basal endogenous nitrogen and dermal losses. See [1] page 34 eq. 80. ''' return self.calc_P_demand_basal_endogenous_nitrogen(body_weight) \ + self.calc_P_demand_dermal_losses(body_weight) @property def P_demand_maintenance(self): ''' The protein (P) demand for . See [1] page 34 eq. 80. ''' return self.calc_P_demand_maintenance(self.body_weight) #region - MP demand ####################################### # demand for metabolisable protein (MP) ####################################### @property def MP_demand_total(self): return self.MP_demand_non_growth + self.MP_demand_growth @property def MP_demand_potential(self): ''' The MP demand for potential growth (g/month). ''' return self.MP_demand_non_growth \ + self.MP_demand_growth_potential @property def MP_demand_maintenance(self): ''' The MP demand for maintenance (g/month). This involves the P demand for maintenance (which depends on body weight) and the efficiency of MP use for maintenance. See [1] page 34. ''' return self.calc_MP_demand_maintenance(self.body_weight) @CachedProperty def MP_demand_non_growth(self): return self.MP_demand_maintenance def calc_MP_demand_maintenance(self,body_weight): ''' Calculates the MP demand for "maintenance" of the ruminant (g/month). Is a function of the P demand for maintenance (which depends on body weight) and the efficiency of MP use for maintenance. See [1] page 34. ''' return self.calc_P_demand_maintenance(body_weight)/self.efficiency_MP_maintenance def calc_MP_demand_non_growth(self,body_weight): return self.calc_MP_demand_maintenance(body_weight) @property def MP_demand_growth(self): ''' The MP demand for growth of the ruminant (g/month). Is a function of the body weight and potential body weight change. See [1] page 36 eq. 92. ''' return self.calc_MP_demand_growth(self.body_weight, self.body_weight_change) @property def MP_demand_growth_potential(self): ''' Calculates the MP demand for growth of the ruminant (g/month). Is a function of the body weight and potential body weight change. See [1] page 36 eq. 92. ''' return self.calc_MP_demand_growth(self.body_weight, self.potential_body_weight_gain) def calc_MP_demand_growth(self,body_weight,body_weight_change): ''' The MP demand for growth (g MP).''' W = body_weight dW = body_weight_change #kg/month if dW <= 0: return 0 else: return dW * self.calc_MP_value_weight_gain(W,dW) @property def MP_value_weight_gain(self): ''' The MP cost of making weight gain (g MP/kg gain). ''' return self.calc_MP_value_weight_gain(self.body_weight, self.body_weight_gain) def calc_MP_value_weight_gain(self,body_weight,body_weight_gain): ''' The MP cost of weight gain (g MP/g kg gain). See [1] page 36 eq. 93. Note, takes into account efficiency of protein use "k_nf". ''' if body_weight_gain < 0: raise ValueError W = body_weight #kg dW = body_weight_gain / DAYS_PER_MONTH #g/d C6 = self.parameters['C6']['value'] k_nf = self.efficiency_MP_growth return C6 * (168.07 - 0.16869 * W + 0.0001633 * W**2) * (1.12 - 0.1223 * dW) / k_nf @property def MP_value_weight_loss(self): ''' MP supply through weight loss (g/kg loss). See [1] page 40, eq. 115. ''' return 138 @property def MP_shortage(self): ''' The difference in total MP demand and supply (g). ''' return max(0,self.MP_demand_total - self.MP_supply_total) #endregion - MP demand #region - MP supply ###################################### # supply of metabolisable protein (MP) ###################################### @property def MP_supply_total(self): ''' The total MP supply available to the ruminant (g). Includes MP supply from feed and weight loss. ''' return self.MP_supply_feed + self.MP_supply_weight_loss @property def MP_supply_feed(self): ''' The MP in the feed to be eaten (g). ''' return self.MP_supply_roughage + self.MP_supply_concentrate @property def MP_supply_weight_loss(self): ''' The MP supplied through weight loss (g). ''' if self.body_weight_loss > 0: return self.MP_value_weight_loss*self.body_weight_loss else: return 0 @property def MP_supply_roughage(self): ''' The MP in the roughage to be eaten (g). ''' if self.roughage_accepted is None: return 0 else: return self.roughage_accepted.MP_total @property def MP_supply_concentrate(self): ''' The MP in the concentrate to be eaten (g). ''' if self.concentrate_accepted is None: return 0 else: return self.concentrate_accepted.MP_total @property def q_m(self): if self.roughage_supply is None: return self.FASTING_Q_M else: return self.roughage_supply.q_m @property def potential_roughage_intake(self): ''' The potential roughage intake (kg DM/month). Makes use of the model of Conrad (1964) J. Dairy Sci. 47: 54-60: Ip = 0.0107*BW/(1-DMD) where Ip is intake (kg DM/day), BW is the bodyweight (kg) and DMD is the dry-matter digestibility of the feed. See also [2], A2.3. ''' BW = self.body_weight if self.roughage_accepted is None: return 0 else: DMD = 0.001*self.roughage_accepted.DMD return DAYS_PER_MONTH*0.0107*BW/(1-DMD) @property def feed_intake(self): ''' The feed intake (kg DM/day). ''' if self.roughage_supply is None: a = 0 else: a = self.roughage_accepted.amount if self.concentrate_supply is None: b = 0 else: b = self.concentrate_supply.amount return (a+b)/DAYS_PER_MONTH @property def rel_feed_intake(self): ''' (% BW/day). ''' return 100*self.feed_intake/self.body_weight def get_concentrate_accepted(self): ''' The concentrate to be eaten --- feed (an object). Makes use of the fraction of feed to be eaten (accepted) to derive the associated accepted feed (an object). ''' if self._concentrate_accepted is not None: return self._concentrate_accepted if self.concentrate_supply is None: return None f = self.fraction_concentrate_supply_eaten if f > 0: res = self.concentrate_supply.__copy__() res.amount *= f res._ruminant = self elif f == 0: res = None else: raise ValueError return res @property def concentrate_refused(self): ''' The concentrate refused to be eaten --- feed (an object). Makes use of the fraction of feed to be eaten (accepted) to derive the associated refused feed (an object). ''' if self.concentrate_supply is None: return None # fraction refused := 1 - fraction accepted f = 1 - self.fraction_concentrate_supply_eaten if f > 0: res = self.concentrate_supply.__copy__() res.amount *= f elif f == 0: res = None else: raise ValueError return res def get_roughage_accepted(self): ''' The roughage to be eaten --- feed (an object). Makes use of the fraction of feed to be eaten (accepted) to derive the associated accepted feed (an object). ''' if self.roughage_supply is None: return None f = self.fraction_roughage_supply_eaten if f > 0: res = self.roughage_supply.__copy__() res.amount *= f res._ruminant = self elif f == 0: res = None else: raise ValueError("The fraction of roughage that is accepted is negative...") return res @property def roughage_refused(self): ''' The roughage refused to be eaten --- feed (an object). Makes use of the fraction of feed to be eaten (accepted) to derive the associated refused feed (an object). ''' if self.roughage_supply is None: return None # fraction refused := 1 - fraction accepted f = 1 - self.fraction_roughage_supply_eaten if f > 0: res = self.roughage_supply.__copy__() res.amount *= f elif f == 0: res = None else: raise ValueError return res @property def fraction_concentrate_supply_eaten(self): ''' The fraction (f) of the supplied concentrate to be eaten (1). Note, 0=>f=>1 and f is such that the ME in the accepted feed equals --- if possible the amount of available feed --- the ME demand. Here the ruminant is modelled to do so by first eating as much concentrate as possible before considering roughage. ''' ME_demand = self.ME_demand_potential ME_supply = self.ME_supply_concentrate_potential if ME_supply == 0: return 0 else: return max(min(1, ME_demand / ME_supply),0) @property def fraction_roughage_supply_eaten(self): ''' The fraction (f) of the supplied roughage to be eaten (1). Note, 0=>f=>1 and f is such that the ME in the accepted feed equals --- if possible the amount of available feed --- the ME demand. Here the ruminant is modelled to do so by first eating as much concentrate as possible before considering roughage. ''' # Note! The prioririty for concentrate is implemented here: ME_demand = self.ME_demand_potential - self.ME_supply_concentrate ME_supply = self.ME_supply_roughage_potential if ME_supply == 0: return 0 else: return max(min(1, ME_demand / ME_supply),0) #endregion - feed acceptance/refusal ############## # ME Potential ############## @property def ME_supply_concentrate_potential(self): ''' The ME in the concentrate supplied to the animal (MJ).''' if self.concentrate_supply is None: return 0 else: return self.concentrate_supply.amount * self.concentrate_supply.ME @property def ME_supply_roughage_potential(self): ''' The ME in the roughage supplied to the animal (MJ).''' if self.roughage_supply is None: return 0 else: return self.roughage_supply.amount * self.roughage_supply.ME @property def ME_supply_feed_potential(self): ''' The ME supply of all the administered feed (MJ). ''' return self.ME_supply_concentrate_potential + self.ME_supply_roughage_potential #region - excreta ################################ # production of faeces and urine ################################ @property def faecal_DM(self): ''' Manure dry-matter production (kg/month). See the associated Feed class for more information. ''' sources = [self.concentrate_accepted, self.roughage_accepted] return sum([x.amount * x.feacal_DM for x in sources if x is not None]) @property def faecal_N(self): ''' Manure N production (g/month). See [1] page 20, the flow diagram and the associated Feed class for more information. ''' sources = [self.concentrate_accepted, self.roughage_accepted] return sum([x.amount * x.feacal_N for x in sources if x is not None]) @property def faecal_P(self): ''' Manure P production (g/month). Reference --------- Efde, 1996 page 131 ''' sources = [self.concentrate_accepted, self.roughage_accepted] return sum([x.amount * x.feacal_P for x in sources if x is not None]) @property def faecal_K(self): ''' Manure N production (g/month). Reference --------- Efde, 1996 page 133-4 Table 9.5 ''' sources = [self.concentrate_accepted, self.roughage_accepted] return sum([x.amount * x.feacal_K for x in sources if x is not None]) # TODO def urine_N(self): pass def urine_P(self): pass def urine_K(self): pass ######## # Output ######## @property def units(self): ''' The units of variables. ''' return {k:v['unit'] for k,v in self._variable_metadata.items()} def to_dict(self): ''' Returns a dict of all float-like instance variables.''' attributes = [x for x in dir(self) if not x.startswith('_')] units = self.units d = {} for key in attributes: try: value = getattr(self, key) except: print(sys.exc_info()[0]) pass if isinstance(value, (float, int, str)): d[key] = value else: pass return d def __repr__(self): lines = ['Object: {:}'.format(self._name)] lines += ['Version: {:}'.format(self._version)] lines += [''] lines += ['{:<40.40} {:<9} {:<12}'.format('Property','Value','Unit')] lines += [62*'-'] attributes = self.to_dict() units = self.units for key in sorted(attributes): if key in units: unit = units[key] else: unit = '?' value = attributes[key] if isinstance(value, int): lines += ['{:<40.40} {:<9.4f} {:<12}'.format(key, value, unit)] elif isinstance(value,float): lines += ['{:<40.40} {:<9.4f} {:<12}'.format(key, value, unit)] else: pass return '\n'.join(lines) class Cow(BaseRuminant): DEFAULT_PARAMETERS = yaml.load(''' # Default values for a medium feeding level Friesian x Holstein # see Jenet et al., 2004. C1: value: 1.0 unit: 1 info: "Value for (female) cows: 1, (bulls: 1.15), key-determinant of/scales the fasting metabolism." source: "[1] page 23" C2: value: 0.85 unit: 1 info: Value for medium maturity type bulls, co-determines the energy value of liveweight gain. source: "[1] page 28 Table 2.1" C6: value: 1.1 unit: 1 info: Value for medium maturity type bulls, parametrizes the protein demand for growth source: "[1] page 36" energy_cost_horizontal_movement: value: 0.0026 unit: kJ/kg/m source: "[1] page 24" energy_cost_vertical_movement: value: 0.028 unit: kJ/kg/m source: "[1] page 24" energy_cost_standing: value: 10 unit: kJ/kg/d source: "[1] page 24" energy_cost_body_position_change: value: 0.260 unit: kJ/kg source: "[1] page 24" body_changes_per_day: value: 10 unit: 1 source: "User defined, default based on [1] page 24--25." horizontal_movement_per_day: value: 1000 unit: meter source: "User defined, default based on [1] page 24--25." vertical_movement_per_day: value: 0 unit: meter source: "User defined, default based on [1] page 24--25." maximum_body_weight: value: [[0,60],[20,300],[40,500],[80,500]] unit: "[month,kg]" source: "Eyed from [2], Appendix 2.1, Fig. A5: weight range for female cross-bred HosteilFreisian X Zebu." minimum_body_weight: value: [[0,20],[20,80],[40,120],[80,200],[140,220],[180,220]] unit: "[month,kg]" source: "Eyed from [2], appendix 2.1, fig. A5: weight range for female cross-bred HosteilFreisian X Zebu." milk_age_effect: value: [[24,0.8],[36,0.8],[60,1],[96,1],[144,0.6],[160,0.6]] unit: "[month,1]" source: "See [2], appendix 2.3, table A3." milk_body_condition_effect: value: [[0,0],[0.3,1],[1,1]] unit: "[1,1]" source: "See [2], appendix 2.3, table A4." gestation_feasibility_curve: value: [[20,320],[30,240],[50,160]] unit: "[month,kg]" info: "The (age,weight) combinations defining a threshold above which gestation is possible." source: "Eyed from [2], appendix 2.2, fig. A6." gestation_given_postpartum: value: [[0,0],[1,0],[2,0.5],[7,1],[12,1]] unit: "[month,kg]" info: "The (months after calving, coefficient) combinations defining how relatively probable conception is given the postpartum." source: "Mink, personal communication. " gestation_given_condition_index: value: [[0,0.2], [0.5,0.995], [0.9,1.45], [1,0.9]] unit: "[1,1]" info: "The (condition index, coefficients) combinations defining how (relatively) probable conception is given the condition index." source: "After the legacy code (pyLIVSIM 1.0), adapted from Wagenaar and Kontrohr (1986). " potential_body_weight_gain: value: [[0.2,0.3], [0.3,0.5], [0.4,0.5], [0.5,1.0], [0.6,1.5], [0.7,2.0]] unit: "[1,kg/day]" info: "For females, the potential daily weight gain as a function of the metabolisability of the feed." source: "Taken from [2], Appendix 2.1, Table A1. After Tolkamp and Ketelaars (1994)." maximum_body_weight_loss: value: 50 unit: kg/month info: "Although not an original feature, it might be useful to have a maximum weight loss as a feature. To not use this feature, either set the value at a trivial value e.g. 200 kg/month or remove the feature altogether." source: "Ad hoc --- as a placeholder." potential_annual_calving_rate: value: 0.75 unit: 1/year source: "" probability_female_child: value: 0.5 # User Defined milk_butterfat_content: value: 45 unit: g/kg source: "Set by user." milk_crude_protein_content: value: 28 unit: g/kg source: "Set by user." milk_lactose_content: value: 10 unit: g/kg source: "Set by user." milk_yield_potential: value: [[0,200],[2,200],[14,0],[15,0]] unit: "[month,kg/month]" source: "Set by user." calf_birthweight: value: 30 unit: kg source: "Set by user." gestation_duration: value: 10 unit: month source: "Set by user --- default based on [2] A2.2." lactation_duration: value: 12 unit: month source: "Set by user." mortality_probability: value: [[0,0], [60,0], [120,.02], [140,.02],] unit: "[month,1/month]" info: "The age-dependent mortalitity probability." ''') _name = 'Cow' _version = '30-04-2018+' sex = 'f' def __init__(self, age=0, body_weight=None): # setting the parameters self._parameters = self.DEFAULT_PARAMETERS # Initialization of the state: self.set_parametrized_functions() # Technical details self._cache_id = 0 self._dt = 1 # in months # State self._age = age # in months if body_weight is None: self.body_weight = 0.5*(self.maximum_body_weight - self.minimum_body_weight) else: self.body_weight = body_weight # Gestation related self.is_lactating = 0 self.is_gestating = 0 self.is_bull_present = 0 self.months_into_gestation = None self.months_after_calving = None self._lactation_cycle_number = 0 # Feed self._roughage_supply = None self._concentrate_supply = None # To allow over-riding the feed intake routine self._roughage_accepted = None self._concentrate_accepted = None self.roughage_accepted = self.get_roughage_accepted() self.concentrate_accepted = self.get_concentrate_accepted() # Artificial Insemination self._will_gestation_start = None # if set over-rides the potential body weight gain routine # a.k.a. compensatory growth (kg/month) self._potential_body_weight_gain = None self.will_die_by_chance = False def set_parametrized_functions(self): # parametrization in terms of functions self._maximum_body_weight_function = self.get_maximum_body_weight_function() self._minimum_body_weight_function = self.get_minimum_body_weight_function() self._potential_body_weight_gain_function = self.get_potential_body_weight_gain_function() self._potential_milk_yield_function = self.get_potential_milk_yield_function() self._milk_age_effect_function = self.get_milk_age_effect_function() self._milk_body_condition_effect_function = self.get_milk_body_condition_effect_function() self._gestation_feasibility_curve_function = self.get_gestation_feasibility_curve_function() self._gestation_given_postpartum_function = self.get_gestation_given_postpartum_function() self._gestation_given_condition_index_function = self.get_gestation_given_condition_index_function() self._mortalitity_probability_function = self.get_mortalitity_probability_function() ############################## # Piece-wise linear functions ############################## def get_potential_milk_yield_function(self): ''' Returns the age-dependent potential milk yield function. ''' xys = self.parameters['milk_yield_potential']['value'] return interpolate(xys) def get_maximum_body_weight_function(self): ''' Returns the age-dependent max. body weight function. ''' xys = self.parameters['maximum_body_weight']['value'] return interpolate(xys) def get_minimum_body_weight_function(self): ''' Returns the age-dependent min. body weight function. ''' xys = self.parameters['minimum_body_weight']['value'] return interpolate(xys) def get_milk_age_effect_function(self): ''' Returns the age-dependent milk yield factor function. ''' xys = self.parameters['milk_age_effect']['value'] return interpolate(xys) def get_milk_body_condition_effect_function(self): ''' Returns the body condition dependent milk yield factor function. ''' xys = self.parameters['milk_body_condition_effect']['value'] return interpolate(xys) def get_gestation_feasibility_curve_function(self): ''' Returns the age dependent body weight threshold for gestation. ''' xys = self.parameters['gestation_feasibility_curve']['value'] return interpolate(xys) def get_gestation_given_postpartum_function(self): ''' Returns the postpartum dependent relative conception probability. ''' xys = self.parameters['gestation_given_postpartum']['value'] return interpolate(xys) def get_gestation_given_condition_index_function(self): ''' Returns the condition index dependent relative conception probability. ''' xys = self.parameters['gestation_given_condition_index']['value'] return interpolate(xys) ########### # Updating ########### def update(self): if self.will_die: raise ValueError("The cow will die in this month (BW = {:<3.1f} kg): can not update...".format(self.body_weight)) will_lactation_start = self.will_lactation_start will_gestation_start = self.will_gestation_start will_lactation_stop = self.will_lactation_stop will_gestation_stop = self.will_gestation_stop self.update_feed_intake() self.body_weight += self.body_weight_change*self.dt ######## self._age += self.dt if self.is_gestating: self.months_into_gestation += self.dt if self.is_lactating: self.months_after_calving += self.dt ######## if will_lactation_start: self.start_lactation() if will_gestation_start: self.start_gestation() if will_lactation_stop: self.stop_lactation() if will_gestation_stop: self.stop_gestation() self._cache_id += 1 self.will_die_by_chance = self.get_will_die_by_chance() return self ################## # State dynamism ################## def start_gestation(self): ''' Starts gestation. ''' self.is_gestating = 1 self.months_into_gestation = 0 self.calf_sex = self.get_calf_sex() def stop_gestation(self): ''' Stops gestation. Note: implicitly linked to a calf birth event and start of milk production. ''' self.is_gestating = 0 self.months_after_calving = 0 self.months_into_gestation = 0 def start_lactation(self): ''' Starts lactation. ''' self.is_lactating = 1 self._lactation_cycle_number += 1 def stop_lactation(self): ''' Stops lactation. ''' self.is_lactating = 0 @CachedProperty def will_lactation_start(self): ''' Whether lactation will start (bool) in the current time-step. ''' return self.will_give_birth @CachedProperty def will_gestation_start(self): ''' Whether gestation will start (bool) in the current time-step. ''' # gestating -> nothing to start if self.is_gestating: return 0 if self._will_gestation_start is None: r = random.random() p = self.conception_probability return int(r < p) else: return self._will_gestation_start @property def will_gestation_stop(self): ''' Whether gestation will stop (bool) in the current time-step. ''' return int(self.will_gestation_stop_given_duration) @CachedProperty def will_gestation_stop_given_duration(self): ''' Whether gestation will stop (bool) in the current time-step given the duration of the gestation cycle (completion). ''' if self.is_gestating: threshold = self.parameters['gestation_duration']['value'] return int(self.months_into_gestation + self.dt > threshold) # not gestating -> nothing to stop else: return 0 @property def will_give_birth(self): '''Whether the cow will calf (bool) in the current time-step. ''' if self.is_gestating: threshold = self.parameters['gestation_duration']['value'] return int(self.months_into_gestation + self.dt > threshold) # not gestating -> nothing to stop else: return 0 @property def will_lactation_stop(self): ''' Whether lactation will stop (bool) in the current time-step. ''' return int(self.will_lactation_stop_given_duration or \ self.will_lactation_stop_given_starvation) @property def will_lactation_stop_given_starvation(self): ''' Whether lactation will stop (bool) in the current time-step given the body weight. ''' return int(self.body_weight < self.minimum_body_weight) @CachedProperty def will_lactation_stop_given_duration(self): ''' Whether lactation will stop (bool) in the current time-step given the duration of lactation. ''' # not lactating -> nothing to stop if not self.is_lactating: return 0 else: threshold = self.parameters['lactation_duration']['value'] return int(self.months_after_calving + self.dt > threshold) ################### # Conception related ################### @property def conception_probability(self): ''' The probability of conception (1/month). See [2] A2.2, eq. 3 and 4. ''' pot = self.potential_conception_probability c1 = self.can_conceive_given_maturity c2 = self.can_conceive_given_postpartum c3 = self.can_conceive_given_bull c4 = self.can_conceive_given_body_index return pot*c1*c2*c3*c4 @property def potential_conception_probability(self): ''' The potential probability of conception (1/month). See [2] A2.2, eq. 3 and 4. ''' ar = self.parameters['potential_annual_calving_rate']['value'] return 1-(1-ar)**(1/12) @CachedProperty def can_conceive_given_maturity(self): ''' Indicates (bool) whether the cow can concieve given the body weight and age. See [2] A2.2, eq. 3 and 4. ''' if self.body_weight >= float(self._gestation_feasibility_curve_function(self.age)): return 1 else: return 0 @CachedProperty def can_conceive_given_postpartum(self): ''' Indicates (0--1) whether the cow can concieve given the postpartum. See [2] A2.2, eq. 3 and 4. ''' # if has not calved if self.months_after_calving is None: return 1 else: return float(self._gestation_given_postpartum_function(self.months_after_calving)) @CachedProperty def can_conceive_given_body_index(self): ''' Indicates (0--2) whether the cow can concieve given the condition index. See pyLIVSIM 1.0, Wagenaar and Kontrohr (1986). ''' return float(self._gestation_given_condition_index_function(self.condition_index)) @property def can_conceive_given_bull(self): ''' Indicates (bool) whether the cow can concieve given the presence of a bull. See [2] A2.2, eq. 3 and 4. ''' return int(self.is_bull_present) ############## # Calf related ############## def get_calf(self): if self.calf_sex == 'f': res = Cow() res.parameters = self.get_parameters() return res else: return Bull() def get_calf_sex(self): r = random.random() P_female = self.parameters['probability_female_child']['value'] if r <= P_female: return 'f' else: return 'm' @property def calf_birthweight(self): ''' The calf birthweight (kg). ''' return self.parameters['calf_birthweight']['value'] @property def E_value_calf(self): ''' The total energy (MJ) retained in the calf, assuming a 40kg birthweight. See [1] page 29, eq. 70. ''' if not self.is_gestating: return 0 else: t = DAYS_PER_MONTH*self.months_into_gestation return self.calc_E_value_calf(t) def calc_E_value_calf(self,t): ''' The total energy (MJ) retained in the calf, assuming a 40kg birthweight. See [1] page 29, eq. 70. ''' # constants, see eq. 70 a = 151.665 b = 151.64 c = 0.0000576 res = 10**(a-b*exp(-c*t)) return res @property def P_value_calf(self): ''' The total protein (NP) retained in the calf, assuming a 40kg birthweight. See [1] page 39, eq. 109. ''' if not self.is_gestating: return 0 else: t = DAYS_PER_MONTH*self.months_into_gestation return self.calc_P_value_calf(t) def calc_P_value_calf(self,t): ''' The total protein retained in the calf (kg NP), assuming a 40kg birthweight. See [1] page 39, eq. 109. ''' return 10**(3.707-5.698*exp(-0.00262*t)) @property def P_demand_gestation(self): ''' The net protein demand (g/month) for the growth of the calf. See [1], page 39, eq. 110. ''' return self.P_demand_gestation_B @property def P_demand_gestation_A(self): ''' The net protein demand (g/month) for the growth of the calf. See [1], page 39, eq. 110. ''' if not self.is_gestating: return 0 else: t = DAYS_PER_MONTH*self.months_into_gestation Wc = self.calf_birthweight # g NP retained in calf foetus as a function of days after conception TPt = self.calc_P_value_calf(t) # in g/day res = 0.025*Wc*TPt*(34.37*exp(-0.00262*t)) return DAYS_PER_MONTH*res @property def P_demand_gestation_B(self): ''' The net protein demand (g/month) for the growth of the calf. See [1], page 39, eq. 110. ''' if not self.is_gestating: return 0 else: t = DAYS_PER_MONTH*self.months_into_gestation Wc = self.calf_birthweight # g NP retained in calf foetus as a function of days after conception calc_TP = self.calc_P_value_calf # in g/day res_ = lambda t:0.025*Wc*calc_TP(t)*(34.37*exp(-0.00262*t)) res = sum([res_(t) for t in range(t,t+DAYS_PER_MONTH)]) return res @property def E_demand_gestation(self): ''' The energy demand (MJ/month) for the growth of the calf. See [1], page 30, eq. 71. ''' return self.E_demand_gestation_B @property def E_demand_gestation_A(self): ''' The energy demand (MJ/month) for the growth of the calf. See [1], page 30, eq. 71. Note, this is (we checked) the derivative of Et the total energy retained in the calf as given by "E_value_calf", namely: Et = 10**(a - b*exp(-c*t)) (d/dt)*Et = Et*[log(10)*b*c]*exp(-c*t) = Et*[0.0201]*exp(-c*t) <- evaluated with b,c = (Wc/Wg)*Et*0.0201*exp(-c*t) <- gauge at 40 kg = 0.025*Wc*Et*0.0201*exp(-c*t) <- final form: eq. 71 [1]. where (a,b,c) = (151.6,151.6,-0.0000576). Note, the final form takes scaling with birthweight into account by gauging the value at a 40 kg birthweight "Wc" via the factor 0.025 = 1/Wg. ''' if not self.is_gestating: return 0 else: t = DAYS_PER_MONTH*self.months_into_gestation Wc = self.calf_birthweight # MJ NE retained in calf foetus as a function of days after conception Et = self.calc_E_value_calf(t) # in MJ/day res = 0.025*Wc*Et*(0.0201*exp(-0.0000576*t)) return DAYS_PER_MONTH*res @property def E_demand_gestation_B(self): ''' The energy demand (MJ/month) for the growth of the calf. See [1], page 30, eq. 71. Note, this is (we checked) the derivative of Et the total energy retained in the calf as given by "E_value_calf", namely: Et = 10**(a - b*exp(-c*t)) (d/dt)*Et = Et*[log(10)*b*c]*exp(-c*t) = Et*[0.0201]*exp(-c*t) <- evaluated with b,c = (Wc/Wg)*Et*0.0201*exp(-c*t) <- gauge at 40 kg = 0.025*Wc*Et*0.0201*exp(-c*t) <- final form: eq. 71 [1]. where (a,b,c) = (151.6,151.6,-0.0000576). Note, the final form takes scaling with birthweight into account by gauging the value at a 40 kg birthweight "Wc" via the factor 0.025 = 1/Wg. ''' if not self.is_gestating: return 0 else: # in days t = DAYS_PER_MONTH*self.months_into_gestation # kg Wc = self.calf_birthweight # MJ NE retained in calf foetus as a function of days after conception calc_Et = self.calc_E_value_calf # in MJ/day res_ = lambda t:0.025*Wc*calc_Et(t)*(0.0201*exp(-0.0000576*t)) res = sum([res_(t) for t in range(t,t+DAYS_PER_MONTH)]) return res @property def ME_demand_gestation(self): ''' The ME demand for gestation (MJ/month). See [1] page 6. ''' return self.E_demand_gestation/self.efficiency_ME_gestation @property def MP_demand_gestation(self): ''' The MP demand of gestation (g/month). ''' return self.P_demand_gestation/self.efficiency_MP_gestation ############## # Milk related ############## @property def lactation_cycle_number(self): ''' The lactation cycle number (1). ''' if self.is_lactating: return self._lactation_cycle_number else: return None @property def milk_butterfat_content(self): ''' A property of the milk, set by user via the parameters (g/kg). ''' return self.parameters['milk_butterfat_content']['value'] @property def milk_crude_protein_content(self): ''' A property of the milk, set by user via the parameters (g/kg). ''' return self.parameters['milk_crude_protein_content']['value'] @property def milk_lactose_content(self): ''' A property of the milk, set by user via the parameters (g/kg). ''' return self.parameters['milk_lactose_content']['value'] @property def E_value_milk(self): ''' The energy value (MJ/kg) of the milk. See [1] page 26. We use eq. 54.''' return self._E_value_milk_54 @property def _E_value_milk_53(self): ''' The energy value (MJ/kg) of the milk. See [1] page 26, eq. 53 --- s.e. 0.035.''' return 0.0384*self.milk_butterfat_content + \ 0.0223*self.milk_crude_protein_content + \ 0.01999*self.milk_lactose_content - 0.108 @property def _E_value_milk_54(self): ''' The energy value (MJ/kg) of the milk. See [1] page 26, eq. 54 --- s.e. 0.066.''' return 0.0376*self.milk_butterfat_content + \ 0.0209*self.milk_crude_protein_content + \ 0.948 @property def _E_value_milk_55(self): ''' The energy value (MJ/kg) of the milk. See [1] page 26, eq. 55 --- s.e. 0.089.''' return 0.0406*self.milk_butterfat_content + 1.509 @property def milk_yield(self): ''' The milk production (kg/month). ''' if self.is_lactating: c1 = self.milk_condition_factor c2 = self.milk_age_effect_factor pot = self.milk_yield_potential return max(0,c1*c2*pot) else: return 0 @CachedProperty def milk_yield_potential(self): if self.months_after_calving is None: return 0 else: return float(self._potential_milk_yield_function(self.months_after_calving)) @CachedProperty def milk_condition_factor(self): return float(self._milk_body_condition_effect_function(self.condition_index)) @CachedProperty def milk_age_effect_factor(self): return float(self._milk_age_effect_function(self.age)) @property def milk_fat_yield(self): ''' The milk fat production (g/month). ''' if self.is_lactating: content = self.parameters['milk_butterfat_content']['value'] return self.milk_yield * content else: return 0 @property def milk_protein_yield(self): ''' The milk protein production (g/month). ''' if self.is_lactating: content = self.parameters['milk_crude_protein_content']['value'] return self.milk_yield * content else: return 0 @property def E_demand_lactation(self): ''' The energy demand of milk production (MJ/month). ''' return self.milk_yield * self.E_value_milk @property def ME_demand_lactation(self): ''' The ME demand of milk production (MJ/month). ''' return self.E_demand_lactation/self.efficiency_ME_lactation @property def MP_demand_lactation(self): ''' The MP demand of lactation (g/month). ''' return self.milk_protein_yield/self.efficiency_MP_lactation ############# # MP related ############# ############# # ME related ############# @property def ME_demand_potential(self): return self.ME_demand_non_growth + \ self.ME_demand_growth_potential @property def ME_demand_maintenance_production(self): ''' The ME demand for maintenance AND production (MJ/month). See [1] page 9. ''' return self.ME_demand_non_growth + self.ME_demand_growth @CachedProperty def ME_demand_non_growth(self): ''' The ME demand for non-growth (body-weight) related processes (MJ/month). ''' return self.ME_demand_maintenance + \ self.ME_demand_lactation + \ self.ME_demand_gestation def calc_ME_demand_non_growth(self,body_weight): ''' Calc. the ME demand for non-growth (body-weight) related processes (MJ/month). ''' return self.calc_ME_demand_maintenance(body_weight) + \ self.ME_demand_lactation + \ self.ME_demand_gestation @CachedProperty def MP_demand_non_growth(self): ''' The MP demand for non-growth (body weight gain) related processes (g/month). The non-growth processes: - maintenance - fasting - activity - lactation - gestation ''' return self.calc_MP_demand_non_growth(self.body_weight) def calc_MP_demand_non_growth(self,body_weight): ''' Calculate the MP demand for non-growth (body-weight) related processes (g/month). ''' return self.calc_MP_demand_maintenance(body_weight) + self.MP_demand_lactation + self.MP_demand_gestation ############## # Efficiency ############## @property def efficiency_MP_lactation(self): ''' The efficiency of milk protein synthesis (g CP milk/g MP). ''' return 0.68 @property def efficiency_ME_gestation(self): ''' Efficiency for growth of the concepta/gestation (MJ E/MJ ME). See [1] page 4. Denoted "k_c". ''' return 0.133 @property def efficiency_MP_gestation(self): ''' Efficiency for growth of the concepta/gestation (g NP/g MP). See [1] page 39. Denoted "k_nc". ''' return 0.85 class Bull(BaseRuminant): DEFAULT_PARAMETERS = yaml.load(''' C1: value: 1.0 unit: 1 info: "Value for (female) cows: 1, (bulls: 1.15), key-determinant of/scales the fasting metabolism." source: "[1] page 23" C2: value: 1.15 unit: 1 info: Value for medium maturity type heifers, co-determines the energy value of liveweight gain. source: "[1] page 28 Table 2.1" C6: value: 1.0 unit: 1 info: Value for late heifers, parametrizes the protein demand for growth source: "[1] page 36" energy_cost_horizontal_movement: value: 0.0026 unit: kJ/kg/m source: "[1] page 24" energy_cost_vertical_movement: value: 0.028 unit: kJ/kg/m source: "[1] page 24" energy_cost_standing: value: 10 unit: kJ/kg/d source: "[1] page 24" energy_cost_body_position_change: value: 0.260 unit: kJ/kg source: "[1] page 24" body_changes_per_day: value: 10 unit: 1 source: "User defined, default based on [1] page 24--25." horizontal_movement_per_day: value: 1000 unit: meter source: "User defined, default based on [1] page 24--25." vertical_movement_per_day: value: 100 unit: meter source: "User defined, default based on [1] page 24--25." maximum_body_weight: value: [[0,60],[20,300],[40,500],[80,500]] unit: "[month,kg]" source: "Eyed from [2], Appendix 2.1, Fig. A5: weight range for female cross-bred HosteilFreisian X Zebu." minimum_body_weight: value: [[0,20],[20,80],[40,120],[80,200],[140,220],[180,220]] unit: "[month,kg]" source: "Eyed from [2], Appendix 2.1, Fig. A5: weight range for female cross-bred HosteilFreisian X Zebu." potential_body_weight_gain: value: [[0.2,0.5], [0.3,0.5], [0.4,1.0], [0.5,1.5], [0.6,2.0], [0.7,2.5]] unit: "[1,kg/day]" info: "For males, the potential daily weight gain as a function of the metabolisability of the feed." source: "Copied from [2], Appendix 2.1, Table A1. After Tolkamp and Ketelaars (1994)." maximum_body_weight_loss: value: 20 unit: kg/month source: "Ad hoc." mortality_probability: value: [[0,0], [60,0], [120,.02], [140,.02],] unit: "[month,1/month]" info: "The age-dependent mortalitity probability." ''') _name = 'Bull' _version = '30-04-2018+' sex = 'm' def __init__(self,age=0,body_weight=None): # setting the parameters self.parameters = self.DEFAULT_PARAMETERS # parametrization in terms of functions self.set_parametrized_functions() # Initialization of the state: # Technical detail self._cache_id = 0 self._dt = 1 # month # State self._age = age # month if body_weight is None: self.body_weight = 0.5*(self.maximum_body_weight - self.minimum_body_weight) else: self.body_weight = body_weight # Feed self._roughage_supply = None self._concentrate_supply = None # To allow over-riding the feed intake routine self._roughage_accepted = None self._concentrate_accepted = None self.roughage_accepted = self.get_roughage_accepted() self.concentrate_accepted = self.get_concentrate_accepted() # if set over-rides the potential body weight gain routine # a.k.a. compensatory growth (kg/month) self._potential_body_weight_gain = None self.will_die_by_chance = False @property def efficiency_ME_growth(self): ''' Efficiency for growth (MJ E/MJ ME). See [1] page 3. ''' return self.efficiency_ME_growth_growing_ruminant<file_sep>#!/usr/bin/env python ######## # README ######## ''' Provides the AFRC Feed model. Developed for Python 3. ''' ######## # Header ######## __author__ = "<NAME>" __copyright__ = "Copyright 2018, PPS" __credits__ = ["<NAME>","<NAME>","<NAME>","and many others"] __license__ = "Copyleft, see http://models.pps.wur.nl/content/licence_agreement" __version__ = "2.0.0" __maintainer__ = "<NAME>" __email__ = "<EMAIL>" __status__ = "Development" ################## # Import Libraries ################## import numpy as np import yaml import sys from copy import deepcopy #################### # Default Parameters #################### DEFAULT_PARAMETERS = yaml.load(''' DM: value: 905 unit: g DM/kg FM DMD: value: 524.0 unit: g/kg DM ME: value: 7.566 unit: MJ/kg DM CP: value: 45 unit: g/kg DM a: value: 0.22 unit: 1 b: value: 0.6 unit: 1 c: value: 0.08 unit: 1 ADIN: value: 1.23 unit: g/kg DM FME: value: 6.8 unit: MJ/kg DM GE: value: 18.4 unit: MJ/kg DM K: value: 0.017533 unit: g/kg DM NDF: value: 777.33 unit: g/kg DM P: value: 0.0018 unit: g/kg DM ''') #################### # Metadata #################### VARIABLE_METADATA = yaml.load(''' ADIN: unit: 'g/kg DM' error: '0%' CP: unit: 'g/kg DM' error: '0%' DM: unit: 'g DM/kg FM' error: '0%' DMD: unit: 'g/kg DM' error: '0%' DMTP: unit: 'g/kg DM' error: '0%' DUP: unit: 'g/kg DM' error: '0%' ERDP: unit: 'g/kg DM' error: '0%' FME: unit: 'MJ/kg DM' error: '0%' GE: unit: 'MJ/kg DM' error: '0%' K: unit: 'g/kg DM' error: '0%' L: unit: '1' error: '0%' MCP: unit: 'g/kg DM' error: '0%' ME: unit: 'MJ/kg DM' error: '0%' ME_total: unit: 'MJ' error: '0%' MP_total: unit: 'g' error: '0%' MP: unit: 'g/kg DM' error: '0%' MTP: unit: 'g/kg DM' error: '0%' NDF: unit: 'g/kg DM' error: '0%' P: unit: 'g/kg DM' error: '0%' QDP: unit: 'g/kg DM' error: '0%' RDP: unit: 'g/kg DM' error: '0%' SDP: unit: 'g/kg DM' error: '0%' UDP: unit: 'g/kg DM' error: '0%' a: unit: '1' error: '0%' amount: unit: 'kg DM' error: '0%' b: unit: '1' error: '0%' c: unit: '1' error: '0%' r: unit: '1/hr' error: '0%' y: unit: '1' error: '0%' ''') ################### # Utility functions ################### def mix(feeds): ''' Mix multiple feeds (blender method). Returns feed with the corresponding (weighted mean) feed quality. ''' mean_parameters = {} total_amount = sum([feed.amount for feed in feeds]) for feed in feeds: rel_amount = feed.amount/total_amount parameters = feed.parameters for k in parameters: if k in mean_parameters: value = parameters[k]['value'] mean_parameters[k]['value'] += rel_amount * value else: mean_parameters[k] = deepcopy(parameters[k]) mean_parameters[k]['value'] *= rel_amount return Feed(amount=total_amount,parameters=mean_parameters) class Feed(object): ''' Nutritional info on the feed quality. Primarily in terms of metabolisable energy (ME, MJ/kg DM) and metabolisable protein (MP, g/kg DM). First of all we estimate the size of 3-types of potential protein sources: - Quickly Digestible Protein (QDP) --- digested mainly in rumen. - Slowly Digestible Protein (SDP) --- digested mainly in rumen. - Undegraded Digestible Protein (UDP) --- digested in lower tract, not in rumen. Then we estimate using the ME available for rumen microbial activity (FME) the actual protein got out of the QDP and SDP to eventually get to the digestible metabolisble true protein (DMTP). Finally the UDP and DMTP combined give us the estimate for the MP, the protein actually available for the ruminant to do something with. For a somewhat nice overview of the derivation process see [1] page 20. Parameters ---------- ME Metabolisable Energy (MJ/kg) FME Fermentable Metabolisable Energy (MJ/kg DM). The ME from the non-fats, and the non-fermentation acids. The ME potentially available for the rumen microbes. See [1] page 3. References ---------- [1] AFRC(1993) Energy and Protein Requirements of Ruminants [2] https://extension.psu.edu/determining-forage-quality-understanding-feed-analysis. ''' default_parameters = DEFAULT_PARAMETERS _variable_metadata = VARIABLE_METADATA _name = 'Feed' _version = '10-4-2018+' def __init__(self, amount=1, parameters=None): self.amount = amount if parameters is None: # note, the deepcopy is very important here # otherwise A.parameters == B.parameters == x.default_parameters # for different feeds A,B and Feed class-object x...: un-expected behaviour self.parameters = deepcopy(self.default_parameters) else: self.parameters = parameters # Ruminant interface: # Reference to ruminant to possibly fetch level of feeding self._ruminant = None # Dummy value of level of feeding # --- actual level of feeding is used if linked to a ruminant self._L = 1 def __copy__(self): ''' The copy method: returns a copy of this object by making a new identical one. ''' return Feed(amount = self.amount, parameters = deepcopy(self.parameters)) def set_parameters(self,parameters): ''' Allows one to set the parameters given a reduced (no metadata) form: >>> parameters = {ME: 8, CP: 50, ...} # reduced (no metadata) form >>> feed = feed.set_parameters(parameters) ''' for k,v in parameters.items(): self.parameters[k]['value'] = v ############ # Parameters ############ @property def ADIN(self): return self.parameters['ADIN']['value'] @property def CP(self): return self.parameters['CP']['value'] @property def DM(self): return self.parameters['DM']['value'] @property def DMD(self): return self.parameters['DMD']['value'] @property def FME(self): return self.parameters['FME']['value'] @property def GE(self): return self.parameters['GE']['value'] @property def K(self): return self.parameters['K']['value'] @property def ME(self): return self.parameters['ME']['value'] @property def NDF(self): return self.parameters['NDF']['value'] @property def P(self): return self.parameters['P']['value'] @property def a(self): return self.parameters['a']['value'] @property def b(self): return self.parameters['b']['value'] @property def c(self): return self.parameters['c']['value'] @property def r(self): ''' Rumen digesta fractional outflow rate per hour (1/hr), depends on the cow. See [1] page 11, eq. 25: "Retention time is highly correlated with the level of feeding. [...] values in the range 0.02 to 0.08/hour [...] of total rumen content would leave the rumen each hour. ARC (1984) gave estimates [...] as follows 1. Animals fed at low level of feeding, about 1 x maintenance: 0.02/h 2. Calves, low yielding dairy cows [...] less than 2x maintance: 0.05/h 3. High yielding dairy cows (15kg milk/d), greater than 2x maintance: 0.08/h Although no relationship [between level of feeding (L) and retention time (r)] has been established experimentally, AFRC (1992) proposed [...] as follows" r = -0.024 + 0.179*(1-exp(-.0278*L)) ''' res = -0.024 + 0.179*(1-np.exp(-0.278*self.L)) # 0.02 <= r <= 0.08 if res < 0.02: return 0.02 elif res > 0.08: return 0.08 else: return res @property def L(self): ''' Level of feeding (1), cow relative. Actually the specific cow and diet determine the cows r. ''' if self._ruminant is None: return self._L else: return self._ruminant.level_of_feeding @property def QDP(self): ''' Fraction of Quickly Digestible Protein (DM g/kg) in the feed. The fraction of protein in the feed that is quickly digested (what is digestion!?) in the rumen (near water-soluble). ''' return self.a*self.CP @property def RDP(self): ''' Fraction of Rumen Digestible Protein (DM g/kg) in the feed. Simply the sum of quickly and slowly digestible protein in the feed. ''' return min(self.CP,self.QDP + self.SDP) @property def UDP(self): ''' Fraction of Undigestible Protien (DM g/kg) in the feed. ''' res = self.CP - self.RDP return max(0,res) @property def SDP(self): ''' Fraction of slowly Digestible Protein (DM g/kg) in the feed. The fraction of protein in the feed that is quickly digested (what is digestion here!?) in the rumen. ''' b = self.b c = self.c r = self.r return (b*c)/(c+r) * self.CP @property def DUP(self): ''' The fraction of Digestible Undegraded Protein (DM g/kg) in the feed. The protein left-alone by the microbes yet taken up in a later stage in the digestive tract !? More info !? How come ADIN is anti-correlated? ''' res = 0.9*self.UDP - 6.25*self.ADIN return max(0,res) @property def ERDP(self): ''' The fraction of Effictive Rumen Digestible Protein (DM g/kg) in the feed. An upper limit on the Microbial Crude Protein; the effective amount of protein in the rumen which can be, at most, digested. ''' return 0.8*self.QDP + self.SDP @property def MCP(self): ''' The fraction of Microbial Crude Protein (g/kg DM) in the feed. The protein the microbes can get out of the feed. Depends on the FME available for this process. Only becomes interesting once FME is relatively small. I.e. the FME requirement := ERDP/y < the FME available: Silage, concentrate, etc. ''' return min(self.y*self.FME,self.ERDP) @property def MTP(self): ''' The fraction of Microbial True Protein (g/kg DM) in the feed. The proteins the ruminant could get out of the MCP (amino-acids). See [1] page 18: Is estimated to be 70--80% of the MCP, 75% is used as a best estimate. ''' return 0.75*self.MCP @property def DMTP(self): ''' The fraction of Digestible Microbial True Protein (g/kg DM) in the feed. The proteins the ruminant is expected to get out of the MCP (amino-acids). See [1] page 18: Estimated to be a constant 85% of the MTP. ''' return 0.85*self.MTP @property def y(self): ''' The Microbial Yield (g MCP/MJ FME). The protein yield as produced by the microbes as an emperical function of the level of feeding (L). Rational (!?): High (low) L; much (little) feed passes through the digestive system, microbial yield is (is not) relatively limited by crude protein availability. See [1] page 16, eq. 34. : L = 1 --> y = 9g MCP/MJ FME . L = 3 --> y = 11g MCP/MJ FME . ''' return float(7.0 + 6.0*(1-np.exp(-0.35*self.L))) @property def MP(self): ''' The fraction of Metabolisable Protein (DM g/kg) in the feed. ''' return self.DMTP + self.DUP @property def q_m(self): ''' The ME to GE ratio of the feed (q_m); a measure of the metabolisibility. See [1] page 2 eq. 4. ''' if self.GE == 0: raise ValueError else: return self.ME/self.GE @property def feacal_N(self): ''' The associated feacal N concentration (g/kg). See [1] page 20, the flow diagram. ''' return (0.1*self.UDP + 0.25*self.MCP + 0.15*self.DMTP)/6.25 + self.ADIN @property def feacal_P(self): ''' The associated feacal N concentration (g/kg). Reference --------- Efde, 1996 page 131 ''' return 0.5*1000*self.P @property def feacal_K(self): ''' The associated feacal K concentration (g/kg). Reference --------- Efde, 1996 page 133-4 Table 9.5 ''' return 0.975 * 0.025 * 1000 * self.K @property def feacal_DM(self): ''' The associated feacal DM concentration (kg/kg). Here DMD is a measure of the digestibility of the dry-matter in the feed (g/kg). See [2] (Marianas Thesis) page 237 eq. 7. ''' return 1-0.001*self.DMD def split(self, amounts=None): ''' Divide self in a number of portions of amounts "amounts". Example: Consider 3 kg of feed and amounts a list of amounts (kg Dm) e.g. [1, 1, 1]. Calling this method divides 3 kg of feed into three times 1 kg of feed. feed = RuminantFeed(amount=3,**feed_quality) feed1, feed2, feed3 = feed.split([1,1,1]) ''' total_amount = sum(amounts) if amounts is None or total_amount != self.amount: raise ValueError('Pass an appropriate list of floats "amounts", see docstring.') to_return = [] for amount in amounts: a_copy = self.__copy__() a_copy.amount = amount to_return.append(a_copy) return to_return @property def ME_total(self): ''' ME (MJ) .''' return self.ME * self.amount @property def MP_total(self): ''' MP (g) .''' return self.MP * self.amount @property def units(self): return {k:v['unit'] for k, v in self._variable_metadata.items()} def to_dict(self): ''' Returns a dict of all float-like instance variables.''' attributes = [x for x in dir(self) if not x.startswith('_')] units = self.units d = {} for key in attributes: try: value = getattr(self, key) except: print(sys.exc_info()[0]) pass print(self.parameters) # print(getattr(self, key)) if isinstance(value, (float, int)): d[key] = value elif isinstance(value, np.ndarray): pass else: pass return d def __repr__(self): lines = ['Object: {:}'.format(self._name)] lines += ['Version: {:}'.format(self._version)] lines += [''] lines += ['{:<30.30} {:<9} {:<12}'.format('Property','Value','Unit')] lines += [52*'-'] attributes = self.to_dict() display_order = ['amount', 'ME_total', 'MP_total', 'ME', 'MP', 'GE', 'q_m', 'FME', 'CP', 'L', 'r', 'QDP', 'SDP', 'DUP', 'RDP', 'UDP', 'y', 'ERDP', 'MCP', 'MTP', 'DMTP', 'a', 'b', 'c', 'DM', 'NDF', 'ADIN', 'P', 'K', 'DMD', 'feacal_N' ] units = self.units for key in display_order: if key in units: unit = units[key] else: unit = '?' value = attributes[key] if isinstance(value,int): lines += ['{:<30.30} {:<9.4f} {:<12}'.format(key,value,unit)] elif isinstance(value,float): lines += ['{:<30.30} {:<9.4f} {:<12}'.format(key,value,unit)] else: pass return '\n'.join(lines) <file_sep> import pandas as pd class Herd(object): def __init__(self): self.max_id = 0 self._beasts = [] self.roughage_supply = None self.concentrate_supply = None self._is_bull_present = None @property def beasts(self): return self._beasts @beasts.setter def beasts(self,value): for beast in value: self.max_id += 1 beast.unique_id = self.max_id self._beasts = value @property def is_bull_present(self): if self._is_bull_present is None: for beast in self.beasts: if beast.sex == 'm': return True return False else: return self._is_bull_present def set_presence_bull(self): for beast in self.beasts: beast.is_bull_present = self.is_bull_present @property def highest_id(self): return max([x.unique_id for x in self.beasts]) def get_mortal_beasts(self): return [x for x in self.beasts if x.will_die] @property def female_beasts(self): return [x for x in self.beasts if x.sex == 'f'] @property def male_beasts(self): return [x for x in self.beasts if x.sex == 'm'] def get_vital_beasts(self): return [x for x in self.beasts if not x.will_die] def get_new_beasts(self): res = [x.get_calf() for x in self.female_beasts if x.will_give_birth] for beast in res: self.max_id += 1 beast.unique_id = self.max_id # more generally one could consider the name "get_child" return res def set_feed(self): beasts = self.beasts N = self.beasts for beast in beasts: beast.roughage_supply = self.roughage_supply.__copy__() beast.concentrate_supply = self.concentrate_supply.__copy__() def update(self): self.set_feed() self.set_presence_bull() mortal_beasts = self.get_mortal_beasts() vital_beasts = self.get_vital_beasts() #print([x.will_die for x in vital_beasts]) for beast in vital_beasts: beast.update() new_beasts = self.get_new_beasts() beasts_to_keep = [x for x in vital_beasts if not (x.sex == 'm' and x.age > 5)] beasts_to_sell = [x for x in vital_beasts if (x.sex == 'm' and x.age > 5)] self._beasts = beasts_to_keep + new_beasts def to_dict(self): res = {} for beast in self.beasts: res[beast.unique_id] = beast.to_dict() return res @staticmethod def to_dfs(A): B = {} # Swap the nesting: # A[t][id] -> vars to B[id][t] -> vars for t,vars_by_id in A.items(): for k,v in vars_by_id.items(): if k in B: B[k][t] = v else: B[k] = {t:v} C = {} for k,v in B.items(): C[k] = pd.DataFrame(v).T return C def run(self,duration=120): res = {} for i in range(duration): self.update() res[i] = self.to_dict() return self.to_dfs(res)<file_sep> ########## # LIVSIM # ########## Header ------ Maintainer: <NAME> Email: <EMAIL> Authors: <NAME>, <NAME> Credits: - <NAME> - <NAME> - <NAME> - <NAME> Version: Last date mentioned in revision history. File Guide ---------- docs: documentation: decisions, user guides, etc. submodels: Sub-Models: LIVSIM, FIELD,etc examples: use examples tests: tests of the model<file_sep>from __future__ import division # TODO: decouple feed definition from the herd # --> instead create feed object containing amounts, quality parameters and any functionality needed to define diet # TODO: investigate timesteps smaller than one month # --> this should be done both for methodological reasons (practice what you teach) # and to facilitate coupling to other models import copy from re import match, search from numpy import mean, asarray from numpy.random import random from scipy.interpolate import interp1d as lininterp from Cattle import Cow, Bull from InitLivSim import InitLivSim from HandleOutput import OutputCow, OutputBull from GHG_emissions import Tier2_livestock class Herd(object): """ This class creates a livsim-object that calls the methods defined on the cows in the herd and takes care of reading input data, calving, herd management and feed definition. @author: <NAME> """ def __init__(self, init_livsim, sim_length, GHG=False): # Get feed data from input-object feed_vars = [i for i in vars(init_livsim) if match("forage_quantity", i)] feed_vars.extend([i for i in vars(init_livsim) if match("concentrate_quantity", i)]) feed_vars.extend([i for i in vars(init_livsim) if match("pasture_quantity", i)]) for var in feed_vars: setattr(self, var, getattr(init_livsim, var)) self.forage_quality = init_livsim.forage_quality self.concentrate_quality = init_livsim.concentrate_quality self.pasture_quality = init_livsim.pasture_quality # TODO: make sure these data are added # System variables sys = {'tolly': 1E-3} self.sys = sys self.GHG = GHG # Set variables pertaining to herd management self.herd_vars = init_livsim.herd_vars self.sold_animals = [] self.dead_animals = [] # Time related variables month_step = 1 / 12 delta_t = 1 timer = dict(simulation_length=sim_length, month_step=month_step, delta_t=delta_t, y_len=365, t_factor=365 / 12, age_step=month_step * delta_t) self.timer = timer self.number_of_months = self.timer['simulation_length'] * 12 # Breed parameters afrc_vars = [i for i in vars(init_livsim) if i.endswith('_afrc')] for var in afrc_vars: setattr(self, var, getattr(init_livsim, var)) param_vars = [i for i in vars(init_livsim) if i.endswith('_param')] for var in param_vars: setattr(self, var, getattr(init_livsim, var)) # Initial herd composition self.herd_data = init_livsim.herd_data self.cows = self.compose_herd(herd_data=self.herd_data) self.herd_size = len(self.cows) # Variables involved in the switch between deterministic and stochastic simulations self.deterministic = True self.deterministic_conception = 0.17 self.tally = 1 def run_herd(self, month=None, year=None, from_field=None, end_month=None, GHG_on=False): """ Run LivSim for one timestep for every animal in the herd. month (int) : number of the current month year (int) : number of the current year from_field (dict) : object giving the amount of animal feed per crop grown on the farm end_month (int) : number of the last month in this growing season """ sim_month = month + year * 12 if from_field is not None: months_left_in_season = end_month - month # Calculate the amount of feed available this month from_field.monthly_ration(months_left=months_left_in_season) # For all animals in the herd call the methods that make up a month in the life of a # LivSim-cow. # TODO: If we want to include shoats in this model as well it might be a better idea to define a method on the animal classes that takes care of the everyday routine of the animals. for cow_nr in range(len(self.cows)): cow = self.cows[cow_nr] calf = None if cow.death < 2 and cow.replaced < 2: # Calculate probability of death due to natural causes cow.mortality(deterministic=self.deterministic) # If the cow survives random mortality we continue with the rest of the calculations if cow.death == 0 and cow.replaced == 0: # Define the diet of the animal, depending on feed availability and the # status of the animal. """ DEPRECATED --> TODO: remove diet, feed = self.feed_definition( cow=cow, month=month, from_field=from_field, feed_per_animal=feed_per_animal ) """ diet, feed = self.feed_definition( cow=cow, month=month, from_field=from_field ) cow.parameters(feed, self.timer) # Do all the stuff that needs to be done for every cow in the herd # Potential growth of the animal cow.potential_growth(self.timer) # Condition index of the animal cow.condition_index() # Potential intake of feed cow.potential_intake(cows=self.cows, diet=diet, feed=feed, timer=self.timer) # Girly things if cow.sex == 1: # Pregnancies to term end in calving if cow.preg_ind >= cow.param['pregn_length'] / 365: calf = self.calving(cow=cow, month=sim_month) # Calculate conception based on data (bw) of the last season cow.conception( timer=self.timer, deterministic=self.deterministic, deterministic_conception=self.deterministic_conception) # Gestation cow.gestation(timer=self.timer) # Lactation cow.lactation(cows=self.cows, timer=self.timer) # Energy expenditure on walking cow.energy_walking() # Calculate nutrient requirements cow.nutritive_requirements(timer=self.timer) # Actual feed intake cow.actual_intake(feed) # Manure production cow.manure(feed) # Check requirements against actual feed intake self.balance_check(cow=cow, sys=self.sys, timer=self.timer) # Urine production cow.urine(timer=self.timer) # Green house gas emissions if self.GHG: cow.GHG.enteric_CH4(cow=cow) # Update characteristics of the cow cow.update_states( age_step=self.timer['age_step'], delta_t=self.timer['delta_t'], y_len=self.timer['y_len'] ) # Update the status of the herd self.herd_management( calf=calf, cow=cow, sim_month=sim_month ) elif cow.death == 1: cow.cow_is_dead(month=sim_month, dead_animals=self.dead_animals) self.herd_size -= 1 elif cow.replaced == 1: cow.cow_is_replaced(month=sim_month, sold_animals=self.sold_animals) self.herd_size -= 1 # TOO: add replaced animals to the list of sold_animals. # When the run is finished we want to use this information to determine how many calfs and replaced # animals have been sold. --> alternative make lists calves_sold and cows_sold # Write selection of attributes to output objects for key in vars(cow.output): if key in vars(cow): # Get reference to the output-attribute of the current cow and variable out_cow = getattr(cow, 'output') out_var = getattr(out_cow, key) # Get variable to store and assign using the reference to the attribute of the output-object var = getattr(cow, key) out_var[sim_month] = var # Set the attribute on the output-object setattr(out_cow, key, out_var) if self.GHG: cow.output.enteric_CH4[sim_month] = cow.GHG.EF # The reference to cow used in the for-loop is deleted to make sure that no unintended # changes are made to any of the cows in the herd. del cow ''' Methods used to run the model - balance_check - calving - feed_definition - herd_management - interpolate ''' def compose_herd(self, herd_data=None): # initiate empty list to add cows to cows = [] for cow_nr in range(len(herd_data['id'])): cow_data = {} for key in herd_data.keys(): cow_data[key] = herd_data[key][cow_nr] sex = cow_data['sex'] breed = cow_data['breed'] # Call method to select the right sets of parameters for the current animal afrc, param = self.assign_breed_values(sex=sex, breed=breed) if sex == 1: cows.append( Cow(new_born=False, cow_data=cow_data, afrc=afrc, param=param, nb_timesteps=self.number_of_months)) elif sex == 0: cows.append( Bull(new_born=False, cow_data=cow_data, afrc=afrc, param=param, nb_timesteps=self.number_of_months)) if self.GHG: for cow in cows: cow.GHG = Tier2_livestock() return cows # TODO: Where to place this method? # Might it be better to separate the initialization of animals and the functionality of the herd? def assign_breed_values(self, sex=None, breed=None): # Get the right sets of breed parameters from the object-attributes all_breed_data = [i for i in vars(self) if match(breed, i)] data_afrc = [i for i in all_breed_data if i.endswith('_afrc')] data_param = [i for i in all_breed_data if i.endswith('_param')] # Split the lists containing the generic and sex-specific parameters afrc_all = [i for i in data_afrc if search('_all_', i)] param_all = [i for i in data_param if search('_all_', i)] if sex == 1: afrc_sex = [i for i in data_afrc if search('_female_', i)] param_sex = [i for i in data_param if search('_female_', i)] elif sex == 0: afrc_sex = [i for i in data_afrc if search('_male_', i)] param_sex = [i for i in data_param if search('_male_', i)] # Compose the afrc and param dictionaries from the generic and sex-specific bits new_afrc = copy.copy(getattr(self, afrc_all[0])) new_afrc.update(getattr(self, afrc_sex[0])) new_param = copy.copy(getattr(self, param_all[0])) new_param.update(getattr(self, param_sex[0])) return new_afrc, new_param # TODO: move to cattle class? def balance_check(self, cow=None, sys=None, timer=None): balance_pot_me = cow.input_me / cow.need_pot_growth_me balance_pot_mp = cow.input_mp / cow.need_pot_growth_mp if balance_pot_me < 1 or balance_pot_mp < 1: balance_act_me = None balance_act_mp = None # To determine whether we should use little_growth or weight_loss at this point # we need to recalculate maintenance requirement based on the current body weight and # see whether the animal has consumed an excess or shortage of energy and/or protein. cow.average_bw = cow.bw cow.nutritive_requirements(timer=self.timer) if cow.sex == 1: balance_act_me = cow.input_me / (cow.need_maint_me + cow.need_lact_me + cow.need_gest_me) balance_act_mp = cow.input_mp / (cow.need_maint_mp + cow.need_lact_mp + cow.need_gest_mp) elif cow.sex == 0: balance_act_me = cow.input_me / cow.need_maint_me balance_act_mp = cow.input_mp / cow.need_maint_mp if balance_act_me >= 1 and balance_act_mp >= 1: cow.little_growth(sys, timer) elif balance_act_me < 1 or balance_act_mp < 1: cow.weight_loss(sys, timer) cow.need_basal_maint = 0 # basal maintenance set to 0 def calving(self, cow=None, month=None): """ Jauchzet, frohlocket! """ # The newborn calf is defined breed = cow.breed if self.deterministic: sex = self.tally self.tally = 0 if self.tally == 1 else 1 else: sex = round(random()) # gender of calves # Call method to select the right sets of parameters for the current animal new_afrc, new_param = self.assign_breed_values(sex=sex, breed=breed) # Depending on the randomly selected sex of the calf the right constructor is called. calf = None if sex == 1: calf = Cow(afrc=new_afrc, param=new_param, nb_timesteps=self.number_of_months) elif sex == 0: calf = Bull(afrc=new_afrc, param=new_param, nb_timesteps=self.number_of_months) max_id_herd = max([k.id for k in self.cows]) max_id_sold = max([k.id for k in self.sold_animals]) if len(self.sold_animals) > 0 else 0 calf.id = max([max_id_herd, max_id_sold]) + 1 calf.age = cow.preg_ind - cow.param['pregn_length'] / 365 # age new cows calf.born_in_month = month calf.breed = breed calf.dam_id = cow.id if self.GHG: calf.GHG = Tier2_livestock() # Calculate condition index of the dam at calving weight_max = None weight_min = None if calf.sex == 1: weight_max = self.interpolate(calf.param['weight_max_age'], calf.param['weight_max'], calf.age) weight_min = self.interpolate(calf.param['weight_min_age'], calf.param['weight_min'], calf.age) elif calf.sex == 0: weight_max = self.interpolate(calf.param['weight_max_age'], calf.param['weight_max'], calf.age) weight_min = self.interpolate(calf.param['weight_min_age'], calf.param['weight_min'], calf.age) # TODO: check the code that calculates the weight of the calf --> link with condition index of dam? calf.change_in_bw = weight_max - calf.param['calv_birth_weight'] # new potential weight calf.bw = mean([weight_max, calf.param['calv_birth_weight']]) calf.min_bw_age_comb = weight_min # Update status of the dam cow.gestating = False cow.lactating = True cow.calv_ind = calf.age # calving index cow.lact_ind = calf.age # lactation index cow.preg_ind = 0 cow.need_gest_me = 0 cow.need_gest_mp = 0 cow.nb_calves += 1 # cumulative number of calves cow.age_last_calving = cow.age if cow.nb_calves == 1: cow.age_first_calving = cow.age # age at first calving if cow.nb_calves > 0: cow.progenitor = 1 else: cow.progenitor = 0 return calf # TODO: might this method be better placed in the cattle class? def feed_definition(self, cow=None, month=None, from_field=None): """ If there are roughages and/or concentrates in the diet the value for each quality parameter in the diet is the weighted average of the quality parameters for the individual constituents of the diet. The quantity of feed given to a particalur animal depends on the time in the year (month) and the status of the animal: - calf: animals younger than the weaning age for a particular breed - gestating/lactating: animals that are in gestation and/or lactation - default: animals that do not meet the criteria for the other animal classes returns: feed: dict diet: diet """ # Create an empty dictionary to hold the feed data feed = {} diet = {} temp_past = {} temp_for = {} forage_month = {} pasture_month = {} concentrate_month = {} animal_class = None # Select the right set of feed input data based on the current animals animal class # (i.e. calf, gestating/lactating, or default). if cow.age < cow.param['weaning_age']: animal_class = 'Calves' elif cow.sex == 0: animal_class = 'Default_cow' elif cow.lactating or cow.gestating: animal_class = 'Gestating_and_or_lactating' else: animal_class = 'Default_cow' # Get the appropriate roughage data for the current month and convert the amount of # feed from DM per day to DM per month (i.e. 30.4 days) select_forage_data = "forage_quantity_" + animal_class forage_input = getattr(self, select_forage_data) for key in forage_input.keys(): forage_month[key] = forage_input[key][month] * 30.4 external_forage = sum([forage_month[i] for i in forage_month.keys()]) # Get and convert the amount of pasture grass select_pasture_data = "pasture_quantity_" + animal_class pasture_input = getattr(self, select_pasture_data) for key in pasture_input.keys(): pasture_month[key] = pasture_input[key][month] * 30.4 # Get and convert the amount of concentrates select_concentrate_data = "concentrate_quantity_" + animal_class concentrate_input = getattr(self, select_concentrate_data) for key in concentrate_input.keys(): concentrate_month[key] = concentrate_input[key][month] * 30.4 # If there is feed grown on farm, add the different types of feed """ if from_field is not None: for feed_id in feed_per_animal: forage_month[feed_id] += feed_per_animal[feed_id] * 30.4 """ if from_field is not None: for feed_id in from_field.feed_this_month: forage_month[feed_id] += from_field.feed_feed( herd_size=self.herd_size, feed_id=feed_id ) # Calculate the total amount of roughage and concentrate in the diet. past_amount = sum([pasture_month[i] for i in pasture_input.keys()]) for_amount = sum([forage_month[i] for i in forage_input.keys()]) conc_amount = sum([concentrate_month[i] for i in concentrate_input.keys()]) # The quality parameters in the feed of the animal are the weighted averages of the # quality parameters of the constituents of the diet. for_CP = 0 for key in self.pasture_quality[str(1)].keys(): # In the feed for the animals a distinction is made between roughage (= pasture grasses # and forages) and concentrate. rough_key = "rough_" + key.lower() conc_key = "conc_" + key.lower() # The default value for the quality parameters is zero feed[rough_key] = 0 feed[conc_key] = 0 temp_past[key] = 0 temp_for[key] = 0 # Pastures if past_amount > 0: for past_id in pasture_input.keys(): temp_past[key] += (pasture_month[past_id] / past_amount) * self.pasture_quality[past_id][key][month] # Forages if for_amount > 0: for for_id in forage_input.keys(): temp_for[key] += (forage_month[for_id] / for_amount) * self.forage_quality[for_id][key][month] if key == 'CP' and external_forage > 0: for_CP += ((forage_input[for_id][month] * 30.4) / external_forage) * \ self.forage_quality[for_id][key][month] # Roughage rough_amount = past_amount + for_amount feed[rough_key] = (temp_past[key] * past_amount + temp_for[ key] * for_amount) / rough_amount if rough_amount > 0 else 0 # Concentrates if conc_amount > 0: for conc_id in concentrate_input.keys(): feed[conc_key] += (concentrate_month[conc_id] / conc_amount) * \ self.concentrate_quality[conc_id][key][month] # Dictionary with diet data for this animal diet['rough_quantity'] = past_amount + for_amount diet['conc_quantity'] = conc_amount # Forage from sources external to the farm expressed as fraction of the total roughage consumption cow.frac_ext_for = external_forage / diet['rough_quantity'] if diet['rough_quantity'] > 0 else 0 cow.ext_for_CP = for_CP # The composition of the diet for the current animal return diet, feed def herd_management(self, calf=None, cow=None, sim_month=None): # If the current animal is male and has the reached the age at which it is to be sold, sell it. if cow.sex == 0 and cow.age >= self.herd_vars['replacement_age_bulls']: cow.replaced = 1 # If there is a new cow, follow these decision rules if calf is not None: # Count the number of males in the herd counter_bulls = len([a.id for a in self.cows if a.sex == 0 and a.replaced == 0 and a.death == 0]) old_female = False unproductive_female = False index = None # Look for the first cow in the herd that needs to be replaced, if any such cow is in the herd for i in range(0, len(self.cows)): old_female = self.cows[i].sex == 1 and self.cows[i].nb_lact >= self.herd_vars['max_lact'] \ and not (self.cows[i].replaced or self.cows[i].lactating) unproductive_female = self.cows[i].sex == 1 and self.cows[i].calv_ind >= self.herd_vars['max_open'] \ and not self.cows[i].replaced if old_female or unproductive_female: index = i break # Check whether the new cow is male or female new_female = False new_male = False if calf.sex == 0: new_male = True elif calf.sex == 1: new_female = True # Decision rules for herd management # TODO: make sure that unproductive animals are replaced even when herd size is below target if new_male and self.herd_size < self.herd_vars['target_herd'] and counter_bulls < self.herd_vars[ 'max_bulls']: self.cows.append(calf) self.herd_size += 1 elif new_female and self.herd_size < self.herd_vars['target_herd']: self.cows.append(calf) self.herd_size += 1 elif new_female and (old_female or unproductive_female): # if calf is female and there is an old or unproductive cow for which there # is no replacement, keep it self.cows.append(calf) self.herd_size += 1 self.cows[index].replaced = 1 elif new_male or new_female: calf.replaced_in_month = sim_month calf.replaced = 1 calf.sold_as_calf = True self.sold_animals.append(calf) # TODO: add decision rule for bulls that are to be sold after fattening up. # TODO: add exception handler for unforeseen cases @staticmethod def interpolate(x, y, x_value): """Function to perform linear interpolation and return the result""" x = asarray(x).squeeze() y = asarray(y).squeeze() f = lininterp(x, y) res = f(x_value) return res def run_LivSim(self): for year in range(self.timer['simulation_length']): for month in range(12): self.run_herd(month=month, year=year) if __name__ == '__main__': # start = time.perf_counter() init_livsim = InitLivSim() herd = Herd(init_livsim=init_livsim, sim_length=15) herd.run_herd() output = [i.output for i in herd.cows] <file_sep>import numpy as np import yaml import sys FEED_CATALOG = yaml.load(''' fresh_grass: ME: MADF: a: 16.2 b: -0.0185 r2: .59 NDC: a: 3.24 b: .0111 r2: .68 IVD: a: .46 b: .0170 r2: .61 MP: a: .24 b: .67 c: .12 u: .09 ADIN: 1.2 dsi: .75 is_silage: False grass_hay_field_cured: ME: MADF: a: 15.86 b: -0.0189 r2: .67 NDC: a: 4.28 b: .0087 r2: .49 IVD: a: 2.67 b: .0110 r2: .83 MP: a: .22 b: .60 c: .08 u: .18 ADIN: 1.2 dsi: .70 is_silage: False grass_hay_barn_dried: ME: MADF: a: 15.86 b: -0.0189 r2: .67 NDC: a: 1.80 b: .0132 r2: .86 IVD: a: 0.61 b: .0148 r2: .90 MP: a: .22 b: .60 c: .08 u: .18 ADIN: 1.2 dsi: .70 is_silage: False ''') def make_feed(name,specs={},catalog=FEED_CATALOG): return ParametrisedRuminantFeed(**specs,params=catalog[name]) def hygienic(decorator): """ Decorates decorator such that it is hygienic i.e. preserves basic attributes. """ def new_decorator(obj): decorated_obj = decorator(obj) decorated_obj.__name__ = obj.__name__ decorated_obj.__doc__ = obj.__doc__ decorated_obj.__module__ = obj.__module__ return decorated_obj return new_decorator @hygienic def add_dumps(klass): """ Class decorator providing data dump methods and a __repr__. :param klass: :return: """ def to_simple_dict(self): """ Returns a dict of all float-like instance variables. :param self: :return: """ attributes = [attr for attr in dir(self) if not attr.startswith('_')] d = {} for key in attributes: try: value = getattr(self, key) if isinstance(value, (int, float)): d[key] = value else: pass except: print(key, sys.exc_info()) pass return d def __repr__(self): return 'Object:\n' + yaml.dump((self.to_simple_dict()), default_flow_style=False) return type( klass.__name__, (klass,), {'__repr__':__repr__, 'to_simple_dict': to_simple_dict} ) @add_dumps class ParametrisedRuminantFeed(object): ''' Nutritional info on the feed quality. Primarily in terms of metabolisable energy (ME, MJ/kg DM) and metabolisable protein (MP, g/kg DM). First of all we estimate the size of 3-types of potential protein sources: - Quickly Digestible Protein (QDP) --- digested mainly in rumen. - Slowly Digestible Protein (SDP) --- digested mainly in rumen. - Undegraded Digestible Protein (UDP) --- digested in lower tract, not in rumen. Then we estimate using the ME available for rumen microbial activity (FME) the actual protein got out of the QDP and SDP to eventually get to the digestible metabolisble true protein (DMTP). Finally the UDP and DMTP combined give us the estimate for the MP, the protein actually available for the ruminant to do something with. For a somewhat nice overview of the derivation process see [1] page 20. Parameters ---------- ME bla FME bla (1) estimators of the ME: -- fiber content -- NDC: Neutral detergent cellulase [DOMD] (DM g/kg), also called neutral detergent fibres -- the fibers being the primary components of the plant cell wall; namely, hemicellulose, cellulose, and lignin. Within a given feed, NDF is a good measure of feed quality and plant maturity. For legume forages, NDF content below 40% would be considered good quality, while above 50% would be considered poor. For grass forages, NDF < 50% would be considered high quality and > 60% as low quality. Modified from [2]. MADF: Modified Acid Detergent Fibre (DM g/kg) Acid detergent fibres are the poorly digestible cell wall components --- a sub-class of neutral detergent fibres; namely, cellulose, lignin, and other very resistant substances. Due to its nature, ADF is often used to predict energy content of feeds. Like NDF, ADF is a good indicator of feed quality; higher values within a feed suggest lower-quality feed. A goal would be to have < 35% ADF in either legume or grass forages. Modified from [2]. NDCG: Neutral detergent cellulase + gammanase [DOMD] (DM g/kg) IVD: In vitro digestibility (DOMD) (DM g/kg) DOMD: Digestible Organic Matter (DM g/kg) References ---------- [1] AFRC(1993) Energy and Protein Requirements of Ruminants [2] https://extension.psu.edu/determining-forage-quality-understanding-feed-analysis. ''' def __init__(self, ME=9, FME=4, MADF=400, NDC =600, NDCG=600, IVD =600, DOMD=600, CP=120, r=0.05, L=1, params = PARAMS ): # parameters for estimation of ME from MODMs self.params = params self.params['ME']['DOMD'] = {'a':0,'b':0.0157,'r2':.83} # Metabolisable Energy (MJ/kg) --- main nutritional quality indicator self._ME = ME # Fermentable Metabolisabe Energy (MJ/kg) --- energy in feed for rumen microbes self._FME = FME # MADF: Modified Acid Detergent Fibre self.MADF = MADF # NDC: Neutral detergent cellulase [DOMD] (DM g/kg) self.NDC = NDC # NDCG: Neutral detergent cellulase + gammanase [DOMD] (DM g/kg) self.NDCG = NDCG # IVD: In vitro digestibility (DOMD) (DM g/kg) self.IVD = IVD # DOMD: Digestible Organic Matter (DM g/kg) self.DOMD = DOMD # CP: Crude Protein (DM g/kg) self.CP = CP # Cow-interfacing: #Rumen digesta fractional outflow rate per hour (1/h) self._r = r # Level of feeding self._L = L def estimate_ME(self,variable,params_key): ''' Make an estimate (via lin. regression) := a + b*x where x is the variable, a,b associated with key. See [1] page 42. ''' # do we have the inputs for the calculation? if variable is None: return None elif params_key not in self.params['ME']: return None # if so, we can do the calculation... else: params = self.params['ME'][params_key] a = params['a'] b = params['b'] estimate = a + b*variable if estimate < 0: raise ValueError else: return estimate @property def r(self): ''' Rumen digesta fractional outflow rate per hour (1/hr), depends on the cow. Actually the specific cow and diet determine the cows r. ''' return self._r @property def L(self): ''' Level of feeding (1), cow relative. Actually the specific cow and diet determine the cows r. ''' return self._L @property def _ME_MADF(self): ''' ME (MJ/kg) estimate from the MADF (DM g/kg). ''' return self.estimate_ME(self.MADF,'MADF') @property def _ME_NDC(self): ''' ME (MJ/kg) estimate from the NDC (DM g/kg). ''' return self.estimate_ME(self.NDC,'NDC') @property def _ME_IVD(self): ''' ME (MJ/kg) estimate from the IVD (DM g/kg). ''' return self.estimate_ME(self.IVD,'IVD') @property def _ME_DOMD(self): ''' ME (MJ/kg) estimate from the 'DOMD' (DM g/kg). ''' return self.estimate_ME(self.DOMD,'DOMD') @property def ME(self): ''' Metabolisable Energy (MJ/kg) ''' return self._ME @property def QDP(self): ''' Quickly Digestible Protein (DM g/kg). ''' return self.params['MP']['a']*self.CP @property def RDP(self): ''' Rumen Digestible Protein (DM g/kg). ''' return self.QDP + self.SDP @property def UDP(self): ''' Undigestibly Protien (DM g/kg). ''' return self.CP - self.RDP @property def SDP(self): ''' Slowly Digestible Protein (DM g/kg). ''' b = self.params['MP']['a'] c = self.params['MP']['c'] r = self.r return (b*c)/(c+r) * self.CP @property def DUP(self): ''' Digestible Undegraded Protein (DM g/kg). The protein left-alone by the microbes yet taken up in a later stage in the digestive tract !? More info !? How come ADIN reduces the value? ''' return 0.9*self.UDP - 6.25*self.params['MP']['ADIN'] @property def ERDP(self): ''' Effictive Rumen Digestible Protein (DM g/kg). An upper limit on the MCP, the effective amount of protein in the rumen which can be, at most, digested. ''' return 0.8*self.QDP + self.SDP @property def FME(self): ''' Fermentable Metabolisable Energy (MJ/kg DM). The ME from the non-fats, and the non-fermentation acids. The ME potentially available for the rumen microbes. See [1] page 3. ''' return self._FME @property def MCP(self): ''' Microbial Crude Protein (g/kg DM). The protein the microbes can get out of the feed. Depends on the FME available for this process. Only becomes interesting once FME is relatively small. I.e. the FME requirement := ERDP/y < the FME available: Silage, concentrate, etc. ''' return min(self.y*self.FME,self.ERDP) @property def MTP(self): ''' Microbial True Protein (g/kg DM). The proteins the ruminant could get out of the MCP (amino-acids). Estimated to be 70--80% of the MCP. In [1] 0.75 is used as a best estimate. See [1] page 18. ''' return 0.75*self.MCP @property def DMTP(self): ''' Digestible Microbial True Protein (g/kg DM). The proteins the ruminant is expected to get out of the MCP (amino-acids). Estimated to be a constant 85% of the MTP. See [1] page 18. ''' return 0.85*self.MTP @property def y(self): ''' Microbial Yield (g MCP/MJ FME). Dependes of the level of feeding (L). See [1] page 16, eq. 34. : L = 1 --> y = 9g MCP/MJ FME . L = 3 --> y = 11g MCP/MJ FME . More feed allows for more microbial yield !? ''' return float(7.0 + 6.0*(1-np.exp(-0.35*self.L))) @property def MP(self): ''' Metabolisable Protein (DM g/kg). ''' return self.DMTP + self.DUP<file_sep>from __future__ import division ''' Created on Sat Aug 30 15:02:58 2014 @author: Zijls004 ''' from copy import copy from scipy.interpolate import interp1d as lininterp import numpy as np from numpy.random import random from numpy import mean, exp, log, abs, array, asarray from HandleOutput import OutputCow, OutputBull def interpolate(x, y, x_value): '''Function to perform linear interpolation and return the result''' x = asarray(x).squeeze() y = asarray(y).squeeze() f = lininterp(x, y) res = f(x_value) return res class EnergyCosts(object): ''' ''' def energy_walking(self): # TODO: check the calculation of the energy expenditure on walking '''Energy expenditure on walking.''' self.need_energy_walking = self.param['energy_walking'] / 1000 class Cattle(object): ''' A model of a ruminant largely based on [1]. Reference --------- [1] AFRC(1993) Energy and Protein Requirements of Ruminants ''' def __init__(self, new_born=True, cow_data=None, afrc=None, param=None): ''' This class defines the characteristics that cows and bulls have in common. The classes specifying cows and bulls inherit their base attributes and methods from this class. ''' if new_born: # Set in LivSims calving-method. self.id = None self.breed = None self.dam_id = None self.age = None self.bw = None elif not new_born: # Non new-borns attributes are read from input data. self.id = cow_data['id'] self.sex = cow_data['sex'] self.breed = cow_data['breed'] self.dam_id = cow_data['damid'] self.age = cow_data['age'] self.bw = cow_data['bw'] else: # ? pass # These attributes are set to a default value of zero. # STATE self.is_death = False self.born_in_month = None self.died_in_month = None self.replaced_in_month = None self.sold_as_calf = False self.replaced = 0 self.average_bw = 0 self.min_bw_age_comb = 0 self.change_in_bw = 0 self.max_allowed_loss = 0 self.lost_weight = 0 self.cond_index = 0 # PROPERTIES # Energy and protein supply through weight loss self.energy_supply_new = 0 self.protein_supply_new = 0 # Malnutrition indicator: increases for every month the animal loses weight self.feed_deficit1 = 0 # Metabolisable energy requirement self.need_pot_growth_me = 0 self.need_maint_me = 0 self.need_growth_me = 0 self.need_basal_maint = 0 self.need_energy_walking = 0 # Metabolisable protein requirement self.need_pot_growth_mp = 0 self.need_maint_mp = 0 self.need_growth_mp = 0 self.needs_protein = 0 self.needs_energy = 0 # Urine production self.urinary_n = 0 self.urinary_p = 0 self.urinary_k = 0 # P and K intake self.p_intake = 0 self.k_intake = 0 # Total intake self.input_dm = 0 self.input_cp = 0 self.input_me = 0 self.input_mp = 0 # Milk input self.input_milk_dm = 0 self.input_milk_me = 0 self.input_milk_mp = 0 # Concentrate input self.input_conc_dm = 0 self.input_conc_cp = 0 self.input_conc_me = 0 self.input_conc_mp = 0 # Forage input self.input_rough_dm = 0 self.input_rough_cp = 0 self.input_rough_me = 0 self.input_rough_mp = 0 # Cumulative dry matter and metabolisable energy intake and amount of dry matter offered. self.cum_dm = 0 self.cum_me = 0 self.cum_mp = 0 self.dm_offered = 0 # Dictionaries with afrc and auxiliary parameters self.afrc = afrc self.param = param self.frac_ext_for = 0 self.ext_for_CP = 0 def is_dead(self, month=None, dead_animals=None): self.died_in_month = month dead_animals.append(copy(self)) keep_values = ['id', 'breed', 'sex', 'death', 'replaced', 'output', 'born_in_month', 'died_in_month', 'GHG'] for key in vars(self): if key in keep_values: setattr(self, key, getattr(self, key)) else: setattr(self, key, 0) if key == 'death': val = getattr(self, key) val += 1 setattr(self, key, val) # Set the emission factor to zero self.GHG.EF = 0 def is_replaced(self, month=None, sold_animals=None): self.replaced_in_month = month sold_animals.append(copy(self)) keep_values = ['id', 'breed', 'sex', 'death', 'replaced', 'output', 'born_in_month', 'replaced_in_month', 'GHG'] for key in vars(self): if key in keep_values: setattr(self, key, getattr(self, key)) else: setattr(self, key, 0) if key == 'replaced': val = getattr(self, key) val += 1 setattr(self, key, val) # Set the emission factor to zero self.GHG.EF = 0 @property def weight_max(self): ''' The maximum weight of the animal ?!. 3-sentence logic behind this plus reference [#]. Reference --------- [#] ''' return interpolate(self.param['weight_max_age'],self.param['weight_max'],self.age) @property def weight_min(self): ''' The minimum weight of the animal ?!. 3-sentence logic behind this plus reference [#]. Reference --------- [#] ''' return interpolate(self.param['weight_min_age'],self.param['weight_min'],self.age) @property def condition_index(self): ''' Animal condition; weight relative to age-specific max body weight. 3-sentence logic behind this plus reference [#]. Reference --------- [#] ''' numerator = self.bw - self.weight_min denumerator = self.weight_max - self.weight_min if denumerator > 0: res = numerator / denumerator else: raise ValueError # Assure 0 <= res <= 1 if res > 1: return 1 elif res < 0: return 0 else: return res @property def faec_dm(self): ''' Manure dry-matter production (kg/year?/animal). 3-sentence logic behind this plus reference [#]. Parameters ---------- feed['rough_dmd'] Rough dry-matter ... ? (unit?) ... Reference --------- [#] ''' feed = self.feed # what is going on here? units? term1 = self.input_rough_dm * (1 - feed['rough_dmd'] / 1000) term2 = self.input_conc_dm * (1 - feed['conc_dmd'] / 1000) return term1 + term2 @property def faec_n(self): ''' Manure N production (kg/year?/animal). 3-sentence logic behind this plus reference [#]. Parameters ---------- 1st featured-parameter meaning (unit) ... Reference --------- [#] ''' feed = self.feed # what are all these constants? --- please explain in docstring faecal_n_forages = 0.1*feed['rough_udprot']/6.25 \ + 0.001*feed['rough_adin']*self.input_rough_dm \ + 0.25*feed['rough_mcprot']/6.25 \ + 0.15*feed['rough_dmtprot']/6.25 faecal_n_concentrate = 0.1*feed['conc_udprot']/6.25 \ + 0.001*feed['conc_adin']*self.input_conc_dm \ + 0.25*feed['conc_mcprot']/6.25 \ + 0.15*feed['conc_dmtprot']/6.25 conc = self.concentrate_accepted return faecal_n_forages + faecal_n_concentrate @property def faec_p(self): ''' Manure P production (kg/year?/animal). 3-sentence logic behind this plus reference [#]. Parameters ---------- 1st featured-parameter meaning (unit) ... Reference --------- Efde, 1996 page 131 ''' return self.p_intake * 0.5 @property def faec_k(self): ''' Manure N production (kg/year?/animal). 3-sentence logic behind this plus reference [#]. Parameters ---------- 1st featured-parameter meaning (unit) ... Reference --------- Efde, 1996 page 133-4 Table 9.5 ''' return self.k_intake * 0.975 * 0.025 def manure(self, feed): '''Manure dry matter , N, P, and K production (kg).''' raise NotImplementedError @property def annual_mortality_rate(self): ''' Fraction dead animals (next year) / live animals (now) (!?) (1/year). 3-sentence logic behind this plus reference [#]. Parameters ---------- 1st featured-parameter meaning (unit) ... Reference --------- [#] ''' res = interpolate(self.param['mort_rate_age'], self.param['mort_rate'], self.age) if res > 1: return 1 elif res <0: return 0 else: return res @property def monthly_mortality_rate(self): ''' Fraction dead animals (next month) / live animals (now) (!?) (1/month). Deduced/extrapolated from the annual mortality rate. For more information see the annual mortality rate method: annual_mortality_rate ''' annual_mortality_fraction = self.annual_mortality_rate annual_survival_fraction = 1 - annual_mortality_fraction monthly_survival_fraction = annual_survival_fraction**(1/12) return 1 - monthly_survival_fraction # aka mortality def set_is_death(self, deterministic=None): ''' Sets whether animal is alive/dead next month via age-specific probability. The age-specific probability of the animal dying (this month) equals the monthly mortality rate. For more information see the corresponding method: monthly_mortality_rate For prototyping purposes, allows for certain death by passing the optional argument 'deterministic=True'. ''' self.proba_death = self.monthly_mortality_rate # for proto-typing ?, what is the use? if deterministic: if self.proba_death == 1: self.is_death = True else: raise NotImplementedError # Stochastically else: r = np.random.random() if r <= self.proba_death: self.is_death = True else: pass def potential_growth(self, timer): weight_max = self.weight_max weight_min = self.weight_min compensatory_gain = interpolate(self.afrc['comp_qm'], self.afrc['comp_gr'], self.afrc['qm']) pot_weight_diff = weight_max - self.bw comp_gain = compensatory_gain * timer['month_step'] potential_growth_per_animal = min([comp_gain, pot_weight_diff]) self.change_in_bw = potential_growth_per_animal # new potential weight self.min_bw_age_comb = weight_min self.average_bw = self.bw + 0.5 * self.change_in_bw @property def is_growing(self): ''' Boolean indicating whether the animal is growing (or not). * (whatever that may mean?) ''' return (self.bw < self.param['bw_mature']) and (self.change_in_bw > 0) def nutritive_requirements(self, timer): ''' PROTEIN REQUIREMENTS MPR <- NPb/knb + NPd/knd + NPl/knl + NPc/knc + NPf/knf + NPg/kng %(g/d) Basal endogenous N(b), concepta(c), hair growth(d), accreted in gain(f), accreted or mobilized when lactating(g), secreted in milk(l), maintenance(m), Efficiencies (knx). The AFRC-calculations yield values in g/d, so the results are multiplied by y_len * month_step to convert them to g/month. ''' # For growing animals (to target potential growth) express weight gain in kg/day if growing: # Calculate nutritive requirements based on the potential growth of the animal. self.growth_requirements(timer) self.need_pot_growth_me = self.afrc['cl'] * self.afrc['mmp'] # MJ/timestep self.need_pot_growth_mp = (self.afrc['mpm'] + self.afrc['mpf']) / 1000 * timer['y_len'] * timer[ 'month_step'] # MJ/timestep both maintenance and growth else: # Calculate nutritive requirements based on only maintenance requirements of the animal. self.maintenance_requirements(timer) self.need_pot_growth_me = self.need_maint_me self.need_pot_growth_mp = self.need_maint_mp def growth_requirements(self, timer): ''' Calculate the energy and protein requirements for growing animals. The AFRC-calculations yield values in g/d, so the results are multiplied by y_len * month_step to convert them to g/month. ''' # Energy requirements self.afrc['f'] = self.afrc['c1'] * (0.53 * (self.average_bw / 1.08) ** 0.67) self.afrc['a'] = self.afrc['activity'] * self.average_bw + self.need_energy_walking * self.average_bw self.afrc['mm'] = (self.afrc['f'] + self.afrc['a']) / self.afrc['km'] self.afrc['em'] = self.afrc['mm'] * self.afrc['km'] self.afrc['evg'] = (self.afrc['c2'] * (4.1 + 0.0332 * self.average_bw - 0.000009 * self.average_bw ** 2)) / \ (1 - self.afrc['c3'] * 0.1475 * 0.5 * self.change_in_bw / timer['t_factor']) self.afrc['eg'] = self.afrc['c4'] * 0.5 * self.change_in_bw / timer['t_factor'] * self.afrc['evg'] self.afrc['r'] = self.afrc['eg'] / self.afrc['em'] self.afrc['mmp'] = ((self.afrc['em'] / self.afrc['kz']) * log(self.afrc['b'] / (self.afrc['b'] - self.afrc['r'] - 1))) * \ timer['y_len'] * timer['month_step'] self.afrc['l'] = 2 # for growing animals self.afrc['cl'] = 1 - 0.018 * (self.afrc['l'] - 1) # l is multiple of ME maintenance req$ self.need_maint_me = self.afrc['cl'] * self.afrc['mm'] * timer['y_len'] * timer['month_step'] self.need_growth_me = self.afrc['cl'] * self.afrc['mmp'] - self.need_maint_me # Protein requirements self.afrc['mpm'] = 2.30 * self.average_bw ** 0.75 self.afrc['mpf'] = self.afrc['c6'] * (168.07 - 0.16869 * self.average_bw + 0.00016338 * self.average_bw ** 2) * \ (1.12 - 0.1223 * 0.5 * self.change_in_bw / timer[ 't_factor']) * 1.695 * 0.5 * self.change_in_bw / timer[ 't_factor'] # Growth requirements, knf<- 0.59 self.need_maint_mp = self.afrc['mpm'] / 1000 * timer['y_len'] * timer['month_step'] self.need_growth_mp = self.afrc['mpf'] / 1000 * timer['y_len'] * timer['month_step'] def maintenance_requirements(self, timer): ''' Calculate the energy and protein requirements for non-growing animals (i.e. maintenance only). The AFRC-calculations yield values in g/d, so the results are multiplied by y_len * month_step to convert them to g/month. ''' # Energy requirements self.afrc['f'] = self.afrc['c1'] * ( 0.53 * (self.average_bw / 1.08) ** 0.67) # f (MJ/d) is fasting metabolism and a is activity allowance (MJ/d) self.afrc['a'] = self.afrc[ 'activity'] * self.average_bw + self.need_energy_walking * self.average_bw # for dairy cattle self.afrc['mm'] = (self.afrc['f'] + self.afrc['a']) / self.afrc['km'] # MJ/day self.afrc['l'] = 1 # animals fed at maintenance self.afrc['cl'] = 1 - 0.018 * (self.afrc['l'] - 1) # l is multiple of ME maintenance req$ self.need_maint_me = self.afrc['cl'] * ( self.afrc['mm'] * timer['y_len'] * timer['month_step']) # register only maintenance self.need_basal_maint = self.afrc['mm'] # Protein requirements self.afrc['mpm'] = 2.30 * (self.average_bw ** 0.75) # knm<- 1 --> mpm<-MPb+MPd; (basal + hair); self.need_maint_mp = self.afrc['mpm'] / 1000 * timer['y_len'] * timer['month_step'] # only maintenance ################### # AFRC Efficiencies ################### @property def efficiency_maintenance(self): ''' The efficiency of utilisation of metabolisable energy for maintenance. See [1] page 3, eq. 6. Denoted k_m. Parameters ---------- self.afrc['qm']: metabolisability of the feed (1), see [1] page 2, eq. 4. ''' return 0.35 * self.afrc['qm'] + 0.503 @property def efficiency_lactation(self): ''' The efficiency of utilisation of metabolisable energy for lactation. See [1] page 3, eq. 7. Denoted k_l. Parameters ---------- self.afrc['qm']: metabolisability of the feed (1), see [1] page 2, eq. 4. ''' return 0.35 * self.afrc['qm'] + 0.420 @property def efficiency_growth_growing_ruminants(self): ''' The efficiency of utilisation of metabolisable energy for growth of "growing ruminants". See [1] page 3, eq. 8. Denoted k_f. Parameters ---------- self.afrc['qm']: metabolisability of the feed (1), see [1] page 2, eq. 4. ''' return 0.78 * self.afrc['qm'] + 0.006 @property def efficiency_growth_lactating_ruminants(self): ''' The efficiency of utilisation of metabolisable energy for growth of "lactating ruminants". See [1] page 3, eq. 9. Denoted "k_g". Parameters ---------- self.efficiency_lactation: The efficiency of utilisation of metabolisable energy for lactation.. ''' return 0.95 * self.efficiency_lactation @property def efficiency_growth_concepta(self): ''' The efficiency of utilisation of metabolisable energy for growth of concepta. See [1] page 3, eq. 10. Denoted "k_c". ''' return 0.133 @property def efficiency_mobilization_body_tissue(self): ''' The efficiency of utilisation of metabolisable energy for "utilisation of mobilised body tissue for lactation". See [1] page 3, eq. 11. Denoted "k_t". Notes ----- NOT USED. ''' return 0.84 @property def level_of_feeding(self): ''' A multiple of metabolisable energy (ME) for maintenance (MJ/d). See [1] page xxi. Denoted "L". ''' # a function of the food intake... raise NotImplementedError @property def correction_factor_lactacting_ruminants(self): ''' Concerns adjusting the extracted metabolisable energy (ME) given the level of feeding, for lactating ruminants. See [1] page 4, eq. 12. Denoted "C_L". ''' return 1 + 0.0018*(self.level_of_feeding-1) def parameters(self, feed, timer): ''' Specify a number of parameters and afrc-related variables. This method will be extended in the classes distinguishing between cows and bulls. ''' # TODO: most of the parameters here do not vary during the simulation and need to be set only once. Move to constructor? # Condition index self.param['cond_in'] = array([0, 0.3, 1]) self.param['cond_factor'] = array([0, 1, 1]) # ---------------------------AFRC_initialisation---------------------------- self.afrc['r'] = -0.024 + 0.179 * (1 - exp(-0.278 * self.afrc['l'])) # Outflow rate determined by level of feeding # Parameter for calibration self.afrc[ 'evlo'] = 19 # MJ / kg afrc page 31 self.afrc['mpg'] = 138 # g / kg afrc page 40 # Degree of maturity as defined in afrc documentation TODO: these parameters should be if self.param['maturing_stage'] == 1: # early maturing (e.g. Mashona) self.afrc['c2'] = 1.30 self.afrc['c6'] = 0.8 elif self.param['maturing_stage'] == 2: # mid maturing (e.g. Africander) self.afrc['c2'] = 1.15 self.afrc['c6'] = 0.9 elif self.param['maturing_stage'] == 3: # late maturing (e.g. Friesian) self.afrc['c2'] = 1.30 self.afrc['c6'] = 0.8 # TODO: These parameters are feed related and depend on the feed composition if feed['rough_me'] > 0 and feed['rough_ge'] > 0: self.afrc['qm'] = feed['rough_me'] / feed[ 'rough_ge'] # Metabolisability of GE, dig$ and GE data (Ketelaars and Tolkamp (1992) eq. to predict qm else: self.afrc['qm'] = 0.2 # <-- lowest value currently defined in the input-data self.afrc['kz'] = self.afrc['km'] * log(self.afrc['km'] / self.afrc['kf']) self.afrc['b'] = self.afrc['km'] / (self.afrc['km'] - self.afrc['kf']) ''' Potential and actual intake of feed ''' def potential_intake(self, cows, diet, feed, timer): ''' Calculate the potential intake of feed (milk, roughage and concentrate) as a function of age, body weight and lactation phase. ''' if self.age < self.param['weaning_age']: calf_mere = self.dam_id > -999 and self.breed == 'mere' calf_azawak = self.dam_id > -999 and self.breed == 'azawak' dam = None if calf_mere or calf_azawak: for counter in range(0, len(cows)): # Check which Cow is the mother of the current calf if cows[counter].id == self.dam_id: dam = cows[counter] if dam is not None: # The calf gets 66# of its dam's milk, Bengaly and al 1993 for Mere (Mali) - remove for Mexico milk_intake = self.param['milk_allowance_dam'] * dam.milk_yield else: milk_all_rate_old = self.interpolate(self.param['milk_allowance_age'], self.param['milk_allowance'], self.age) # kg per month milk_all_rate = self.interpolate(self.param['milk_allowance_age'], self.param['milk_allowance'], self.age + timer['age_step']) milk_intake = mean([milk_all_rate_old, milk_all_rate]) * timer['month_step'] # kg per timestep # Milk intake expressed as the amount of dry matter. milk_dm_intake = milk_intake * self.param['milk_dm'] / 1000 # Metabolisable energy content of the milk is expressed on a dry weight basis self.input_milk_me = milk_dm_intake * self.param['milk_me'] # Protein content of the milk is expressed as a percentage of the fresh weight of the milk. self.input_milk_mp = milk_intake * self.param['milk_cp'] / 100 self.input_milk_dm = milk_dm_intake elif self.age >= self.param['weaning_age']: # animals after weaning self.input_milk_me = 0 self.input_milk_mp = 0 self.input_milk_dm = 0 # Intake of roughage according to Conrad (1964) J. Dairy Sci. 47: 54-60 roughage_intake = (0.0107 * self.bw / (1 - feed['rough_dmd'] / 1000)) * timer['t_factor'] * self.param[ 'coef_intake'] # TODO: coef_intake is only relevant for cows. feed_available = diet['rough_quantity'] self.dm_offered = feed_available # * feed['rough_dm'] / 1000 # Roughage intake self.input_rough_dm = min([self.dm_offered, roughage_intake]) self.input_rough_cp = self.input_rough_dm * feed['rough_cp'] / 1000 self.input_rough_me = self.input_rough_dm * feed['rough_me'] self.input_rough_ge = self.input_rough_dm * feed['rough_ge'] # If the amount of concentrates on offer exceeds the set maximum fraction of total DM # intake the intake of concentrates is reduced. concentrate_available = diet['conc_quantity'] if self.input_rough_dm > 0: conc_in_feed = concentrate_available / (self.input_rough_dm + concentrate_available) else: conc_in_feed = float('Inf') if conc_in_feed > self.param['max_conc']: self.input_conc_dm = self.input_rough_dm / (1 / self.param['max_conc'] - 1) else: self.input_conc_dm = diet['conc_quantity'] self.input_conc_cp = self.input_conc_dm * feed['conc_cp'] / 1000 self.input_conc_me = self.input_conc_dm * feed['conc_me'] self.input_conc_ge = self.input_conc_dm * feed['conc_ge'] # Calculate amount of protein in feed feed = self.protein_in_feed(feed) self.input_conc_mp = feed['conc_mprot'] self.input_rough_mp = feed['rough_mprot'] # Weighted average of the dry matter digestibility of the consumed feed. if (self.input_rough_dm + self.input_conc_dm) > 0: self.input_dmd = (feed['rough_dmd'] * self.input_rough_dm + feed['conc_dmd'] * self.input_conc_dm) / ( self.input_rough_dm + self.input_conc_dm) else: self.input_dmd = 0 # Total intake of dm, me and mp self.input_dm = self.input_milk_dm + self.input_rough_dm + self.input_conc_dm self.input_me = self.input_milk_me + self.input_rough_me + self.input_conc_me self.input_ge = self.input_rough_ge + self.input_conc_ge self.input_mp = self.input_milk_mp + self.input_rough_mp + self.input_conc_mp # Intake of P and K self.p_intake = self.input_rough_dm * feed['rough_p'] + self.input_conc_dm * feed['conc_p'] self.k_intake = self.input_rough_dm * feed['rough_k'] + self.input_conc_dm * feed['conc_k'] def actual_intake(self, feed): ''' If the potential feed intake exceeds nutritive requirements, the intake is limited to meet the demands. Milk and concentrates are consumed preferentially over roughage, but the amount of concentrates is limited to a fraction of the total dry matter intake to avoid rumen acidosis. ''' self.afrc['l'] = 2 self.afrc['r'] = -0.024 + 0.179 * (1 - exp(-0.278 * self.afrc['l'])) # L2 is for growing animals! # ------------------actual intake-------------------------------- if self.input_me > self.need_pot_growth_me: self.input_me = self.need_pot_growth_me # me supply if self.age < self.param['weaning_age']: # milk if self.input_milk_me > self.need_pot_growth_me: self.input_milk_me = self.need_pot_growth_me # =Milk_ME; self.input_milk_dm = self.input_milk_me / self.param['milk_me'] self.input_milk_mp = (self.input_milk_dm * 1000 / self.param['milk_dm']) * self.param[ 'milk_cp'] # =Mprot_milk; else: self.input_milk_me = 0 # =Milk_ME; self.input_milk_dm = 0 self.input_milk_mp = 0 # =Mprot_milk; me_left = self.need_pot_growth_me - self.input_milk_me # amount of me that still needs to be consumed after milk intake frac_for = (1 - self.param['max_conc']) / 0.5 frac_conc = self.param['max_conc'] / 0.5 # concentrate intake is limited to avoid rumen acidosis dry_matter_intake = me_left / mean([feed['rough_me'] * frac_for, feed['conc_me'] * frac_conc]) # concentrate self.input_conc_me = max([0, min( [self.input_conc_me, self.param['max_conc'] * dry_matter_intake * feed['conc_me']])]) # MJ per month if self.input_conc_dm > 0: self.input_conc_dm = self.input_conc_me / feed['conc_me'] self.input_conc_ge = self.input_conc_dm * feed['conc_ge'] self.input_conc_cp = self.input_conc_dm * feed['conc_cp'] / 1000 else: self.input_conc_dm = 0 self.input_conc_cp = 0 # forages self.input_rough_me = max([0, me_left - self.input_conc_me]) if feed['rough_me'] > 0: self.input_rough_dm = self.input_rough_me / feed['rough_me'] # kg dm per month <-cows(32) self.input_rough_ge = self.input_rough_dm * feed['rough_ge'] self.input_rough_cp = self.input_rough_dm * feed['rough_cp'] / 1000 # =CP_input_forages; else: self.input_rough_dm = 0 self.input_rough_cp = 0 # Calculate amount of protein in feed feed = self.protein_in_feed(feed) self.input_conc_mp = feed['conc_mprot'] self.input_rough_mp = feed['rough_mprot'] # Weighted average of the dry matter digestibility of the consumed feed. self.input_dmd = (feed['rough_dmd'] * self.input_rough_dm + feed['conc_dmd'] * self.input_conc_dm) / ( self.input_rough_dm + self.input_conc_dm) # Total intake of dm, me and mp self.input_dm = self.input_milk_dm + self.input_rough_dm + self.input_conc_dm self.input_me = self.input_milk_me + self.input_rough_me + self.input_conc_me self.input_ge = self.input_rough_ge + self.input_conc_ge self.input_mp = self.input_milk_mp + self.input_rough_mp + self.input_conc_mp # Intake of P and K self.p_intake = self.input_rough_dm * feed['rough_p'] + self.input_conc_dm * feed['conc_p'] self.k_intake = self.input_rough_dm * feed['rough_k'] + self.input_conc_dm * feed['conc_k'] def little_growth(self, sys=None, timer=None): growth_max = self.change_in_bw growth_min = 0 self.change_in_bw = mean([growth_max, growth_min]) finished = False attempt = 0 while not finished and attempt <= 50: attempt += 1 if self.age <= timer['month_step']: self.average_bw = self.param['calv_birth_weight'] else: self.average_bw = self.bw + 0.5 * self.change_in_bw # Recalculate nutritive requirements based on new bodyweight self.growth_requirements(timer) balance_energy = self.input_me / self.needs_energy balance_protein = self.input_mp / self.needs_protein tolerance_energy = sys['tolly'] * self.needs_energy tolerance_protein = sys['tolly'] * self.needs_protein if balance_energy <= balance_protein: finished = abs(self.input_me - self.needs_energy) <= tolerance_energy if not finished: if self.needs_energy > self.input_me: growth_max = self.change_in_bw self.change_in_bw = mean([growth_min, self.change_in_bw]) else: growth_min = self.change_in_bw self.change_in_bw = mean([growth_max, growth_min]) elif balance_protein < balance_energy: finished = abs(self.input_mp - self.needs_protein) <= tolerance_protein if not finished: if self.needs_protein > self.input_mp: growth_max = self.change_in_bw self.change_in_bw = mean([growth_min, self.change_in_bw]) else: growth_min = self.change_in_bw self.change_in_bw = mean([growth_max, growth_min]) def weight_loss(self, sys, timer): # The maximum amount of body weight that can be lost differs between male and female # animals and is calculated in the weight_loss method of the respective sub-classes. loss_min = 0 loss_max = self.bw - self.min_bw_age_comb self.change_in_bw = mean([loss_max, loss_min]) self.max_allowed_loss = (1 - sys['tolly']) * loss_max # If the animal is already below the minimum growth curve before weight loss, it will die. This # situation can occur when an animal is already close to the minimum body weight for its age and # continues to lose weight, while the minimum growth curve is still going up. if self.change_in_bw < 0: self.is_death = 1 self.protein_supply_new = 0 self.energy_supply_new = 0 # The animal loses weight, so growth requirements are set to zero. self.need_growth_me = 0 self.need_growth_mp = 0 # Recalculate average_bw and requirements (maintenance only). if self.age < timer['month_step']: self.average_bw = self.param['calv_birth_weight'] else: self.average_bw = self.bw - 0.5 * self.change_in_bw self.maintenance_requirements(timer) finished = False attempt = 0 while not finished and self.change_in_bw <= self.max_allowed_loss and attempt <= 50 and self.is_death == 0: attempt += 1 if self.age < timer['month_step']: self.average_bw = self.param['calv_birth_weight'] else: self.average_bw = self.bw - 0.5 * self.change_in_bw # Calculation of mobilisation of energy and protein from weight loss energy_ from_weight_loss = self.afrc['evlo'] * self.change_in_bw # 19 MJ/kg released due to weight loss self.energy_supply_new = self.input_me + energy_from_weight_loss protein_from_weight_loss = self.afrc[ 'mpg'] / 1000 * self.change_in_bw # g/kg bw loss kng <- 1$0 for cows bw loss NPg <- mpg self.protein_supply_new = self.input_mp + protein_from_weight_loss # Recalculate energy and protein requirements based on new body weight. self.maintenance_requirements(timer) # New treshold values to determine accuracy of result tolerance_energy = sys['tolly'] * self.needs_energy tolerance_protein = sys['tolly'] * self.needs_protein # Calculate balance between the input of energy and protein and the requirement of both. balance_energy = self.input_me / self.needs_energy balance_protein = self.input_mp / self.needs_protein # The most limiting resource determines when the body weight loop will be broken if balance_energy <= balance_protein: finished = abs(self.energy_supply_new - self.needs_energy) <= tolerance_energy if not finished: if self.needs_energy > self.energy_supply_new: loss_min = self.change_in_bw self.change_in_bw = mean([loss_min, loss_max]) else: loss_max = self.change_in_bw self.change_in_bw = mean([loss_max, loss_min]) elif balance_protein < balance_energy: finished = abs(self.protein_supply_new - self.needs_protein) <= tolerance_protein if not finished: if self.needs_protein > self.protein_supply_new: loss_min = self.change_in_bw self.change_in_bw = mean([loss_min, loss_max]) else: loss_max = self.change_in_bw self.change_in_bw = mean([loss_max, loss_min]) # Auxiliary variable that is needed later on. self.lost_weight = self.change_in_bw # The change in body weight is equal to the loss after the while-loop was exited self.change_in_bw *= -1 # New input of protein and energy after weight loss self.input_me = self.energy_supply_new self.input_mp = self.protein_supply_new # Cow has lost weight, so it is underfed. self.feed_deficit1 += 1 def update_states(self, age_step=None, delta_t=None, y_len=None): ''' Update the state. Uses simple Euler integration. ''' self.age += age_step # Age of the animal self.bw += self.change_in_bw * delta_t # New body weight of the animal self.cum_dm += self.input_dm * delta_t # cumulative dm intake self.cum_me += self.input_me * delta_t # cumulative me intake self.cum_mp += self.input_mp * delta_t # cumulative mp intake def update_animal(self): raise NotImplementedError() class Cow(Cattle): def __init__(self, new_born=True, cow_data=None, afrc=None, param=None, nb_timesteps=None): ''' A new cow is either initialized from data or as a new-born calf (default values). When a cow is initialized from data, the necessary information is passed to the constructor by the input function of the livsim-object. This class inherits its basic properties and methods from the Cattle-class and adds characteristics specific for cows. ''' Cattle.__init__(self, new_born=new_born, cow_data=cow_data, afrc=afrc, param=param) if new_born: self.sex = 1 self.gestating = False self.lactating = False self.preg_ind = 0 self.calv_ind = 0 self.lact_ind = 0 elif not new_born: # If the new animal is not a new-born calf, its attributes are read from input data. self.gestating = cow_data['gestating'] self.lactating = cow_data['lactating'] # The indices are specified in months in the interface and are here converted to years self.preg_ind = cow_data['pregind'] / 12 self.calv_ind = cow_data['calvind'] / 12 self.lact_ind = cow_data['lactind'] / 12 # These attributes are set to a default value of zero. self.dry = False self.progenitor = 0 self.repr_stat = 0 # Metabolisable energy requirement self.need_gest_me = 0 self.need_lact_me = 0 # Metabolisable protein requirement self.need_gest_mp = 0 self.need_lact_mp = 0 # Milk yield, conception and calving self.milk_yield = 0 self.nb_calves = 0 self.nb_lact = 0 self.cum_milk_yield = 0 self.cum_day_milk = 0 self.cum_day_open = 0 self.proba_conception = 0 self.rand_conception = 0 self.age_first_conception = 0 self.age_last_calving = 0 self.age_first_calving = 0 # Malnutrition - from mild (1) to severe (3) self.feed_deficit2 = 0 self.feed_deficit3 = 0 self.max_loss_lact = 0 self.output = OutputCow(nb_timesteps=nb_timesteps) def end_lactation(self): self.lactating = False self.lact_ind = 0 self.milk_yield = 0 self.need_lact_me = 0 self.need_lact_mp = 0 self.nb_lact += 1 self.afrc['ml'] = 0 self.afrc['mpl'] = 0 def conception(self, timer, deterministic=None, deterministic_conception=None): if not self.gestating and self.age >= self.param['repr_age'][0]: weight_limit = self.interpolate(self.param['repr_age'], self.param['repr_weight'], self.age) if self.bw >= weight_limit: # use the weight of the last month self.repr_stat = 1 else: self.repr_stat = 0 # Probability of conception from Konandreas and Anderson (1982) with free Breeding if self.repr_stat == 1 and not self.gestating: age_effect_calving_rate = self.interpolate(self.param['calv_rate_age'], self.param['calv_rate'], self.age) annual_rate = self.param['calving_rate'] * age_effect_calving_rate P = 1 - (1 - annual_rate) ** (1 / 12) # Effect of postpartum from Wagenaar and Kontrohr 1986 if self.nb_calves == 0: mn = 1 else: if 0 < self.calv_ind < 2 * timer['month_step']: mn = 0 else: postpartum_length = [2 / 12, 7 / 12, 1440 / 12] mn_estimated = [0.5, 1.0, 1.0] mn = self.interpolate(postpartum_length, mn_estimated, self.calv_ind) # TODO: is this ridiculous contraption necessary? # Presence of bull presence_bull = 1 if presence_bull == 1: mb = 1 else: mb = 0 # Effect of condition # Adapted from Wagenaar and Kontrohr (1986) mc = None if self.cond_index <= 0.2: mc = 0 elif 0.2 < self.cond_index <= 0.5: mc = 3.33 * self.cond_index - 0.67 elif 0.5 < self.cond_index <= 0.9: mc = 1.125 * self.cond_index + 0.4375 elif 0.9 < self.cond_index <= 1: mc = 6.4 - 5.5 * self.cond_index # Calculation of monthly probability # Probability of conception determined by calving rate, post-partum length, presence of a bull # and body condition self.proba_conception = P * mn * mb * mc if deterministic: self.rand_conception = deterministic_conception else: # Random number to simulate stochastic conception self.rand_conception = random() if self.rand_conception <= self.proba_conception: self.gestating = True self.preg_ind = timer['age_step'] if self.nb_calves == 0: self.age_first_conception = self.age # age at first conception else: self.gestating = False self.preg_ind = 0 def gestation(self, timer): if self.gestating: t_new = self.preg_ind * timer['y_len'] # transform to days t_old = (self.preg_ind - timer['age_step']) * timer['y_len'] et_actual = 10 ** (151.665 - 151.64 * exp( -0.0000576 * t_new)) # Energy retention (MJ) in gravid foetus, “t�? days from conception et_old = 10 ** (151.665 - 151.64 * exp(-0.0000576 * t_old)) mc = (mean([et_actual, et_old]) - et_old) / self.afrc['kc'] if self.preg_ind <= 0.65: self.need_gest_me = mc self.need_pot_growth_me += mc else: self.afrc['l'] = 1 # TODO: is this correct? Should this not be 2 or even 3? See also: AFRC-manual. self.afrc['cl'] = 1 + 0.018 * (self.afrc['l'] - 1) # l is multiple of ME maintenance req$ self.need_gest_me = self.afrc['cl'] * mc self.need_pot_growth_me += self.afrc['cl'] * mc # MP gestation requirements tpt_new = 10**(3.707 - 5.698 * exp(-0.00262 * t_new)) # Tissue protein retention (kg) at time 't_new' tpt_old = 10**(3.707 - 5.698 * exp(-0.00262 * t_old)) mpc = 1.01 * self.param['calv_birth_weight'] * mean([tpt_new, tpt_old]) * exp(-0.00262 * (t_new - t_old)) self.need_gest_mp = mpc / 1000 * timer['y_len'] * timer['month_step'] self.need_pot_growth_mp += self.need_gest_mp # kg/timestep def lactation_requirements(self): self.afrc['l'] = 2 # Level of feeding for late pregnancy and lactation self.afrc['cl'] = 1 + 0.018 * (self.afrc['l'] - 1) # l is multiple of ME maintenance req actual_milk_fat = self.interpolate(self.param['milk_fat_lp'], self.param['milk_fat'], self.lact_ind) self.afrc['evl'] = 0.0406 * actual_milk_fat + 1.509 # MJ/kg energy value of milk # ME Lactation requirements self.afrc['ml'] = self.milk_yield * self.afrc['evl'] / self.afrc['kl'] # MJ/month self.need_lact_me = self.afrc['cl'] * self.afrc['ml'] # MP Lactation requirements self.afrc['mpl'] = (self.milk_yield * self.param[ 'milk_cp'] * 13.57) / 1000 # where CP is crude protein eq$ for cattle self.need_lact_mp = self.afrc['mpl'] def lactation(self, cows, timer): lactating_mere = (len(cows) > 1) and (self.lact_ind > timer['month_step']) and (self.breed.lower() == 'mere') lactating_azawak = (len(cows) > 1) and (self.lact_ind > timer['month_step']) and ( self.breed.lower() == 'azawak') lactating_boran = (len(cows) > 1) and (self.lact_ind > timer['month_step']) and (self.breed.lower() == 'boran') lactation_stop = False if (lactating_mere or lactating_azawak or lactating_boran) and self.dam_id > 0: calf_ids = [] for cow in range(0, len(cows)): if cows[cow].dam_id == self.id: calf_ids.append(cow) if len(calf_ids) == 0: lactation_stop = True else: calf = cows[max(calf_ids)] # The check.calf variable is used to make sure that the calf that has triggered the current lactation # is still in the herd, if this calf has been sold lactation will stop. check_calf = calf.age + timer['month_step'] - self.lact_ind calf_has_died = calf.age <= self.param['lac_len'] and calf.death > 0 calf_still_alive = calf.age <= self.param['lac_len'] and calf.death == 0 if calf_has_died or check_calf > timer['month_step']: lactation_stop = True elif calf_still_alive: lactation_stop = False else: lactation_stop = False end_of_lactation = self.lact_ind > self.param['lac_len'] if self.lactating: if not lactation_stop and not end_of_lactation: # use calving index to keep tract of lactation self.dry = False # Effect of condition index and age on milk yield condition_effect = self.interpolate(self.param['cond_in'], self.param['cond_factor'], self.cond_index) effect_age = self.interpolate(self.param['lact_fraction_age'], self.param['lact_fraction'], self.age) # Potential milk yield as determined by the lactation curve and lactation index (kg per year) milk_yield = self.interpolate(self.param['milk_rate_lp'], self.param['milk_rate'], self.lact_ind) milk_yield_new = self.interpolate(self.param['milk_rate_lp'], self.param['milk_rate'], self.lact_ind + timer['month_step']) # Depending on the value of the pregnancy index and the calving index we distinguish # three scenario's: # 1. The cow is lactating and within a user-defined period from parturition and is dried off. # 2. The cow is within the first two months of lactation, where milk yield is at its peak. # 3. The lactation curve is on its downward slope and milk yield is calculated as the # average between this month and the next one. if self.preg_ind > self.param['wo_dry_period']: self.end_lactation() # Call method to end lactation self.dry = True elif self.calv_ind <= 2 * timer['month_step']: self.milk_yield = timer['month_step'] * milk_yield * effect_age * condition_effect else: self.milk_yield = mean([milk_yield_new, milk_yield]) * timer[ 'month_step'] * effect_age * condition_effect # Calculate energy and protein requirements for lactation self.lactation_requirements() elif end_of_lactation or lactation_stop: # If the end of the lactation period has been reached or the conditions determine # that lactation should end, the method to end the lactation is called. self.end_lactation() def urine(self, timer): ben = 0.35 * (self.bw ** 0.75) * timer[ 't_factor'] / 1000 # is a proportion of maintenance, expressed in g N/day if self.change_in_bw < 0: n_weight_loss = 138 / 1000 * abs(self.change_in_bw) / 6.25 else: n_weight_loss = 0 self.urinary_n = max(0.01, ((self.input_rough_cp + self.input_conc_cp) / 6.25 + n_weight_loss) - self.faec_n - ben - (self.need_lact_mp / 6.25)) self.urinary_k = self.k_intake * 0.975 * 0.975 # source Efde, 1996 page 133-4 Table 9.5 self.urinary_p = self.bw * 2.0e-6 # source Efde, 1996 page 130 def parameters(self, feed, timer): ''' Extends the set of parameters and afrc-related variables defined in the Cattle-class, with a number of variables specific for cows. ''' # Call the method in the parent class to set the parameters that cows and bulls have in common Cattle.parameters(self, feed, timer) # Set the values of parameters that are specific to cows # Pregnancy (year) self.param['pregn'] = self.param['pregn_length'] / timer['y_len'] # Lactation lenght (year) self.param['lac_len'] = self.param['max_length'] * timer['month_step'] # Lactation without dry period self.param['wo_dry_period'] = self.param['pregn'] - 2 * timer['month_step'] # Modifier for feed intake, depending on lactation phase self.param['coef_intake'] = self.interpolate(self.param['milk_fat_lp'], self.param['int_lact'], self.lact_ind) self.param['bw_mature'] = max(self.param['weight_max']) # ---------------------------AFRC_initialisation---------------------------- # Parameters values for cows self.afrc['c1'] = 1.0 self.afrc['c3'] = 1.0 self.afrc['c4'] = 1.10 self.afrc['activity'] = 0.00917 def growth_requirements(self, timer=None): Cattle.growth_requirements(self, timer) self.needs_energy = self.need_maint_me + self.need_growth_me + self.need_lact_me + self.need_gest_me self.needs_protein = self.need_maint_mp + self.need_growth_mp + self.need_lact_mp + self.need_gest_mp def maintenance_requirements(self, timer=None): Cattle.maintenance_requirements(self, timer) self.needs_energy = self.need_maint_me + self.need_lact_me + self.need_gest_me self.needs_protein = self.need_maint_mp + self.need_lact_mp + self.need_gest_mp def weight_loss(self, sys, timer): # The maximum amount of body weight the animal can lose in kg per month before # lactation stops max_loss_lact = None if self.lactating: max_change = self.interpolate(self.param['max_bw_lost_lp'], self.param['max_bw_lost'], self.lact_ind) max_loss_lact = max_change * timer['month_step'] # Call the weight loss method from the parent class Cattle.weight_loss(self, sys, timer) if self.is_death == 0: if self.lost_weight < self.max_allowed_loss: # If body weight loss exceeds a given fraction of the maximum allowed body weight loss # lactation is stopped. if self.lactating and self.lost_weight > max_loss_lact: self.end_lactation() # If the body weight loss of the animal exceeds the treshold value lactation is limited # or stops. After lactation has stopped the amount of energy required is recalculated and # if demands can not be satisfied the animal dies. elif self.lost_weight >= self.max_allowed_loss: if self.lactating: energy_for_lactation = self.energy_supply_new - (self.need_maint_me + self.need_gest_me) protein_for_lactation = self.protein_supply_new - (self.need_maint_mp + self.need_gest_mp) # If there is some energy or protein available for limited milk production calculate # this new amount if energy_for_lactation > 0 and protein_for_lactation > 0: # Calculate how much milk can be produced with the available energy and protein. energy_limited_milk = energy_for_lactation * self.afrc['kl'] / self.afrc['evl'] protein_limited_milk = protein_for_lactation * 1000 / self.param['milk_cp'] * 13.57 # Milk yield limited by either protein or energy availability self.milk_yield = min([energy_limited_milk, protein_limited_milk]) # Energy and protein requirement for lactation is recalculated based on the reduced milk yield self.lactation_requirements() # Cow is rather seriously underfed. self.feed_deficit2 += 1 else: # Call method to end lactation self.end_lactation() self.needs_energy -= self.need_lact_me # recalculate energy requirement after lactation has stopped self.needs_protein -= self.need_lact_mp # recalculate protein requirement after lactation has stopped if self.energy_supply_new < self.needs_energy or self.protein_supply_new < self.needs_protein: # if the energy or protein supply is still not enough after lactation has stopped the animal dies. self.is_death = 1 else: # Animal survives but is abysmally underfed. self.feed_deficit3 += 1 else: if self.energy_supply_new < self.needs_energy or self.protein_supply_new < self.needs_protein: # if the energy or protein supply is still not enough after lactation has stopped the animal dies. self.is_death = 1 else: # Animal survives but is abysmally underfed. self.feed_deficit3 += 1 def update_states(self, age_step=None, delta_t=None, y_len=None): Cattle.update_states(self, age_step, delta_t, y_len) self.cum_milk_yield += self.milk_yield * delta_t # Cumulative milk yield if self.gestating: self.preg_ind += age_step self.proba_conception = 0 self.rand_conception = 0 if self.lactating: self.lact_ind += age_step if self.calv_ind > 0: self.calv_ind += age_step if self.calv_ind >= self.param['lac_len']: self.end_lactation() # Cumulative days in milk if self.milk_yield > 0: self.cum_day_milk += y_len * 1 / 12 * delta_t # Cumulative days open if self.nb_calves >= 1 and not self.gestation: self.cum_day_open += y_len * 1 / 12 * delta_t def update_animal(self): pass class Bull(Cattle): def __init__(self, new_born=True, cow_data=None, afrc=None, param=None, nb_timesteps=None): Cattle.__init__(self, new_born=new_born, cow_data=cow_data, afrc=afrc, param=param) self.sex = 0 self.output = OutputBull(nb_timesteps=nb_timesteps) def growth_requirements(self, timer): Cattle.growth_requirements(self, timer) self.needs_energy = self.need_maint_me + self.need_growth_me self.needs_protein = self.need_maint_mp + self.need_growth_mp def maintenance_requirements(self, timer): Cattle.maintenance_requirements(self, timer) self.needs_energy = self.need_maint_me self.needs_protein = self.need_maint_mp def parameters(self, feed, timer): Cattle.parameters(self, feed, timer) self.param['bw_mature'] = max(self.param['weight_max']) self.param['coef_intake'] = 1 self.afrc['c1'] = 1.15 self.afrc['c3'] = 1.0 self.afrc['c4'] = 1.15 # C6<-1$2; C2<-0$7 # parameters from afrc, 1993 self.afrc['activity'] = 0.00696 def urine(self, timer): ben = 0.35 * (self.bw ** 0.75) * timer[ 't_factor'] / 1000 # is a proportion of maintenance, expressed in g N/day if self.change_in_bw < 0: n_weight_loss = 138 / 1000 * abs(self.change_in_bw) / 6.25 else: n_weight_loss = 0 self.urinary_n = max(0.01, ((self.input_rough_cp + self.input_conc_cp) / 6.25 + n_weight_loss) - self.faec_n - ben) self.urinary_k = self.k_intake * 0.975 * 0.975 # source Efde, 1996 page 133-4 Table 9.5 self.urinary_p = self.bw * 2.0e-6 # source Efde, 1996 page 130 def weight_loss(self, sys, timer): # Call the weight loss method from the parent class. Cattle.weight_loss(self, sys, timer) # If weight loss exceeds the threshold value, the animal dies. if self.lost_weight >= self.max_allowed_loss and self.is_death == 0: self.is_death = 1 if __name__ == '__main__': pass
f16710fadb731ae9a91f9c33eafb2ce6e8a74fca
[ "Python", "Text" ]
8
Python
James-Hawkins/Individual-Model
9ca6d2f315735742f7af3d225356c72da89a6155
45b7d6fa80820d94abc0c7b4c81841a878f0bda9
refs/heads/master
<repo_name>mylinyuzhi/hazelcast-jet<file_sep>/hazelcast-jet-core/src/main/java/com/hazelcast/jet/stream/impl/pipeline/TransformPipeline.java /* * Copyright (c) 2008-2017, Hazelcast, Inc. All Rights Reserved. * * 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. */ package com.hazelcast.jet.stream.impl.pipeline; import com.hazelcast.jet.DAG; import com.hazelcast.jet.Vertex; import com.hazelcast.jet.Distributed; import com.hazelcast.jet.stream.DistributedStream; import com.hazelcast.jet.stream.impl.processor.TransformP; import java.util.ArrayList; import java.util.List; import static com.hazelcast.jet.Edge.between; import static com.hazelcast.jet.stream.impl.StreamUtil.uniqueVertexName; public class TransformPipeline extends AbstractIntermediatePipeline { private final List<TransformOperation> operations = new ArrayList<>(); public TransformPipeline(StreamContext context, Pipeline upstream, TransformOperation operation) { super(context, upstream.isOrdered(), upstream); operations.add(operation); } @Override public Vertex buildDAG(DAG dag) { Vertex previous = upstream.buildDAG(dag); // required final for lambda variable capture final List<TransformOperation> ops = operations; Vertex transform = dag.newVertex(uniqueVertexName("transform"), () -> new TransformP(ops)); if (upstream.isOrdered()) { transform.localParallelism(1); } dag.edge(between(previous, transform)); return transform; } @Override public DistributedStream filter(Distributed.Predicate predicate) { operations.add(new TransformOperation(TransformOperation.Type.FILTER, predicate)); return this; } @Override public DistributedStream map(Distributed.Function mapper) { operations.add(new TransformOperation(TransformOperation.Type.MAP, mapper)); return this; } @Override public DistributedStream flatMap(Distributed.Function mapper) { operations.add(new TransformOperation(TransformOperation.Type.FLAT_MAP, mapper)); return this; } } <file_sep>/hazelcast-jet-core/src/main/java/com/hazelcast/jet/stream/impl/processor/TransformP.java /* * Copyright (c) 2008-2017, Hazelcast, Inc. All Rights Reserved. * * 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. */ package com.hazelcast.jet.stream.impl.processor; import com.hazelcast.jet.AbstractProcessor; import com.hazelcast.jet.stream.impl.pipeline.TransformOperation; import javax.annotation.Nonnull; import java.util.Iterator; import java.util.List; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Stream; public class TransformP extends AbstractProcessor { private final TransformOperation[] operations; public TransformP(List<TransformOperation> operations) { this.operations = operations.toArray(new TransformOperation[operations.size()]); } @Override protected boolean tryProcess(int ordinal, @Nonnull Object item) throws Exception { processItem(item, 0); return true; } private void processItem(Object item, int operatorIndex) { for (int i = operatorIndex; i < operations.length; i++) { TransformOperation operation = operations[i]; switch (operation.getType()) { case FILTER: if (!((Predicate) operation.getFunction()).test(item)) { return; } break; case MAP: item = ((Function) operation.getFunction()).apply(item); break; case FLAT_MAP: Stream stream = (Stream) ((Function) operation.getFunction()).apply(item); Iterator iterator = stream.iterator(); while (iterator.hasNext()) { processItem(iterator.next(), i + 1); } stream.close(); return; default: throw new IllegalArgumentException("Unknown case: " + operation.getType()); } } emit(item); } }
dd4c80da7da84262a2fa7abc0a8c1cde8644f6b5
[ "Java" ]
2
Java
mylinyuzhi/hazelcast-jet
ab3633f1b3248c268a79f0687555e0ba7d0e9131
fc3b1945015f32b4ffebed71b5f55f46aa9573d2
refs/heads/master
<repo_name>Donutellko/IkarusUtilities<file_sep>/src/main/kotlin/domain/Node.kt package domain public open class Node(val id: String) public class SCollection( sid: String, val name: String, val head: SObject, val children: MutableList<Node> = mutableListOf()) : Node(sid) public class SObject(id: String, var content: String? = null) : Node(id) <file_sep>/src/main/kotlin/at/tugraz/ikarus/utilities/UtilitiesApplication.kt package at.tugraz.ikarus.utilities import org.springframework.boot.Banner import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.runApplication import org.springframework.context.ConfigurableApplicationContext @SpringBootApplication class UtilitiesApplication private var context: ConfigurableApplicationContext? = null fun main(args: Array<String>) { context = runApplication<UtilitiesApplication>(*args) { setBannerMode(Banner.Mode.CONSOLE) } }<file_sep>/src/main/kotlin/at/tugraz/ikarus/utilities/api/BasicApi.kt @file:Suppress("unused") package at.tugraz.ikarus.utilities.api import at.tugraz.ikarus.utilities.service.BasicService import at.tugraz.ikarus.utilities.Utils.JsonUtils import org.springframework.web.bind.annotation.* import java.lang.IllegalArgumentException @RestController @RequestMapping(value = ["/", "/basic"]) class BasicApi(private val basic: BasicService) { @RequestMapping("/") fun index() = basic.hello("my friend") @RequestMapping("/hello") fun hello(@RequestParam("name") name: String) = basic.hello(name) /** * Add or replace [content] in a storage as an object. * If [id] is provided, it will replace an object with that id. Otherwise, * a new object will be added. * If [validate] is provided and is true, the [content] will be checked to * be a valid JSON string. * * * @param id id of an existing object in database to be replaced. * @param content text string to be stored. * @param validate if need to check, if it is a valid JSON. * * @return an id of stored data, or null, if json is invalid or an error occurred. */ @PostMapping("/data") fun store( @RequestParam(name = "id", required = false) id: String? = null, @RequestParam(name = "content", required = true) content: String, @RequestParam(name = "validate", required = false) validate: Boolean = false ) = if (validate && !JsonUtils.isValid(content)) { null } else if (id != null) { basic.change(id, content) } else { basic.store(content) } /** * Get a data with provided id. * * @param id of a data to get. * * @return string stored with provided id, or null, if nothing is * stored or an error occurred. */ @GetMapping("/data") fun get(@RequestParam("id") id: String) = basic.get(id) /** * Get ids of objects, which contain provided [text]. * * @param text to be searched for. * * @return a list of id's of objects which contain provided text. */ @PostMapping("/data/search") fun search(@RequestParam("text") text: String) = basic.searchObj(text) /** * Remove data with provided id from storage. * * @param id of an object to delete * * */ @DeleteMapping("/data") fun delete(@RequestParam("id") id: String) = basic.delete(id) @PostMapping("/coll") fun makeColl( @RequestParam("sid") sid: String, @RequestParam("name") name: String ) = basic.makeCol(sid, name) @GetMapping("/coll") fun getColl( @RequestParam(value = "sid") sid: String, @RequestParam(value = "name", required = false) name: String? ) = try { basic.getCol(sid = sid, name = name) } catch (e: IllegalArgumentException) { e.printStackTrace() e.message } @GetMapping("/coll/search") fun searchColl(@RequestParam("id") id: String) = basic.searchColl(id) @DeleteMapping("/coll") fun deleteColl( @RequestParam(value = "sid") sid: String, @RequestParam(value = "name", required = false) name: String? ) = basic.deleteCol(sid = sid, name = name) @PostMapping("/incoll") fun insertIntoColl( @RequestParam("sid") sid: String, @RequestParam("id") id: String ) = basic.insertCol(sid, id) @DeleteMapping("/incoll") fun removeFromColl( @RequestParam("sid") sid: String, @RequestParam("id") id: String ) = basic.removeCol(sid, id) @RequestMapping("/stat") fun stat() = basic.stat() @RequestMapping("/reset") fun reset(@RequestParam("code") code: String) = basic.reset(code) }<file_sep>/src/main/kotlin/at/tugraz/ikarus/utilities/api/ManagementApi.kt package at.tugraz.ikarus.utilities.api import at.tugraz.ikarus.utilities.service.ManagementService import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestParam import org.springframework.web.bind.annotation.RestController @RestController @RequestMapping(value = ["/management"]) class ManagementApi(private val managementService: ManagementService) { /** * Create a backup of current state of database */ @RequestMapping("/backup") fun backup() = managementService.backup() /** * Get a json of collection with provided sid, or full tree otherwise */ @RequestMapping("/fetch") fun fetch(@RequestParam(name = "sid", required = false) sid: String?): Any = if (sid == null) managementService.fetchFullTree() else managementService.fetchTree(sid) }<file_sep>/build.gradle buildscript { repositories { mavenCentral() } dependencies { classpath 'org.jetbrains.kotlin:kotlin-allopen:1.3.21' classpath 'org.springframework.boot:spring-boot-gradle-plugin:2.1.3.RELEASE' classpath 'org.springframework.boot.experimental:spring-boot-thin-gradle-plugin:1.0.21.RELEASE' } } plugins { id 'org.jetbrains.kotlin.jvm' version '1.3.21' } tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all { kotlinOptions { jvmTarget = "1.8" } } group 'at.tugraz.ikarus' version '1.1' sourceCompatibility = 1.8 apply plugin: 'war' apply plugin: 'maven' apply plugin: 'io.spring.dependency-management' apply plugin: 'org.springframework.boot' apply plugin: 'org.springframework.boot.experimental.thin-launcher' apply plugin: 'kotlin' apply plugin: 'kotlin-spring' repositories { mavenCentral() } configurations { jaxb } // tag::wsdl[] task genJaxb { ext.sourcesDir = "${buildDir}/generated-sources/jaxb" ext.classesDir = "${buildDir}/classes/jaxb" ext.schema = "http://coronet2.iicm.tugraz.at:8080/IkarusDBEngine/CoreWS?wsdl" outputs.dir classesDir doLast() { project.ant { taskdef name: "xjc", classname: "com.sun.tools.xjc.XJCTask", classpath: configurations.jaxb.asPath mkdir(dir: sourcesDir) mkdir(dir: classesDir) xjc(destdir: sourcesDir, schema: schema, package: "at.tugraz.ikarus.engine") { arg(value: "-wsdl") produces(dir: sourcesDir, includes: "**/*.java") } javac(destdir: classesDir, source: 1.8, target: 1.8, debug: true, debugLevel: "lines,vars,source", classpath: configurations.jaxb.asPath) { src(path: sourcesDir) include(name: "**/*.java") include(name: "*.java") } copy(todir: classesDir) { fileset(dir: sourcesDir, erroronmissingdir: false) { exclude(name: "**/*.java") } } } } } // end::wsdl[] jar { enabled = true } bootJar { classifier = 'boot' } thinJar { classifier = 'thin' } bootWar { excludeDevtools = true } dependencies { // test Compile group: 'junit', name: 'junit', version: '4.12' implementation 'org.jetbrains.kotlin:kotlin-reflect' compile 'org.jetbrains.kotlin:kotlin-stdlib-jdk8' compile 'org.springframework.boot:spring-boot-starter-web' compile("org.springframework.ws:spring-ws-core") compile 'com.fasterxml.jackson.module:jackson-module-kotlin' // compile 'org.springframework.boot:spring-boot-starter-test' // compile 'org.springframework.boot:spring-boot-devtools' // compile 'org.springframework.boot:spring-boot-starter-thymeleaf' // compile 'org.springframework.boot:spring-boot-starter-actuator' // compile(files(genJaxb.classesDir).builtBy(genJaxb)) providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat' // uncomment to be able to fetch files from jaxb // jaxb "com.sun.xml.bind:jaxb-xjc:2.1.7" } // http://coronet2.iicm.tugraz.at:8080/IkarusDBEngine/CoreWS?wsdl <file_sep>/src/main/kotlin/at/tugraz/ikarus/utilities/service/BasicService.kt package at.tugraz.ikarus.utilities.service import at.tugraz.ikarus.utilities.client.EngineClient import org.springframework.stereotype.Service @Service class BasicService(private val engine: EngineClient) { fun hello(name: String) = engine.hello(name = name).result fun store(s: String) = engine.store(content = s).result fun get(id: String) = engine.get(id = id).result fun delete(id: String) = engine.delete(id = id).result fun makeCol(sid: String, name: String) = engine.makeCol(sid = sid, name = name).result fun getCol(sid: String?, name: String? = null) = engine.getCol(sid = sid, name = name).result fun deleteCol(sid: String?, name: String? = null) = engine.deleteCol(sid = sid, name = name).result fun insertCol(sid: String, id: String) = engine.insertCol(sid = sid, id = id).result fun removeCol(sid: String, id: String) = engine.removeCol(sid = sid, id = id).result fun reset(code: String) = engine.reset(code = code).result fun searchObj(text: String) = engine.searchObj(text = text).result fun searchColl(id: String) = engine.searchColl(id = id).result fun stat() = engine.stat().result fun change(id: String, content: String) = engine.change(id = id, content = content).result }<file_sep>/src/main/kotlin/at/tugraz/ikarus/utilities/service/ManagementService.kt package at.tugraz.ikarus.utilities.service import com.fasterxml.jackson.databind.ObjectMapper import domain.Node import domain.SCollection import domain.SObject import org.springframework.stereotype.Service import java.io.File import java.io.FileWriter import java.lang.StringBuilder import java.time.LocalDateTime import java.time.format.DateTimeFormatter @Service class ManagementService(private val basicService: BasicService) { fun stat(): Stat { val res = basicService.stat()!! val tmp = res.split("\n") val ids = tmp[0].trim().trim('[', ']').split(", ") val cols = mutableMapOf<String, String>() for (s in tmp[1].trim().trim('[', ']').split(", ")) { val i = s.indexOf("=") cols[s.substring(0, i)] = s.substring(i + 1) } return Stat(ids, cols) } fun fetchFullTree(): Map<String, Node> { val stat = stat() val nodes = mutableMapOf<String, Node>() val rootNodes = mutableMapOf<String, Node>() // nodes that are not in other nodes for (id in stat.ids) { nodes[id] = SObject(id = id, content = basicService.get(id)) rootNodes[id] = SObject(id = id, content = basicService.get(id)) } val sids = mutableListOf<String?>().apply { for (s in stat.cols.keys) add(s) } for (i in 0 until sids.size) { val sid = sids[i] ?: continue fun fetchSColl(sid: String, name: String): SCollection { if (nodes.containsKey(sid)) { rootNodes.remove(sid) return nodes[sid] as SCollection } // head id, then ids of child objects and sids of child SCollections val res = basicService.getCol(sid)!!.split(",") val collection = SCollection(sid = sid, name = name, head = nodes[res[0]] as SObject) rootNodes.remove(collection.head.id) // head is not root for (r in 1 until res.size) { val id = res[r].substringBefore("(") rootNodes.remove(id) sids.replaceAll { t -> if (t == id) null else t } collection.children.add( if (id.startsWith("s-")) { fetchSColl(id, stat.cols.getValue(id)) } else { nodes.getValue(id) } ) } return collection } nodes[sid] = fetchSColl(sid = sid, name = stat.cols.getValue(sid)) rootNodes[sid] = nodes[sid]!! } return rootNodes } fun backup2(): String { val tree = fetchFullTree() val result = StringBuilder() fun stringify(n: Node) { if (n is SObject) { result.append(n.id).append("\t") .append( n.content ?.replace("\n", "\\n") ?.replace("\r", "\\r") ) .append("\n") } else if (n is SCollection) { result.append(n.id).append("\t").append(n.name) for (c in n.children) { result.append(n.id).append("\t").append(c) stringify(c) } } } for (n in tree.values) stringify(n) return result.toString() } /** * Fetch all data from Engine, serialize it as JSON and write to file * in "backups" folder with current time as name, and .json as extension */ fun backup(): Map<String, Node> { val tree = fetchFullTree() val json = ObjectMapper().writeValueAsString(tree) File("backups").mkdirs() val fw = FileWriter( "backups" + File.separator + DateTimeFormatter.ofPattern("uuuu-MM-dd_kk-mm-ss").format(LocalDateTime.now()) + ".json" ) fw.write(json) fw.close() return tree } data class Stat(val ids: Iterable<String>, val cols: Map<String, String>) fun get(id: String) = SObject(id, basicService.get(id)) fun fetchTree(sid: String): SCollection { val ids = basicService.getCol(sid)!!.split(",") val name = basicService.stat()!! .substringAfter(sid).substringBefore(",").trim(']', ' ', '=') val result = SCollection(sid = sid, name = name, head = get(ids[0])) for (i in 1..ids.size) { val id = ids[i] if (id.startsWith("s-")) { result.children.add(fetchTree(id)) } else { result.children.add(get(id)) } } return result } }<file_sep>/src/main/kotlin/at/tugraz/ikarus/utilities/client/EngineConfig.kt package at.tugraz.ikarus.utilities.client import org.springframework.beans.factory.annotation.Value import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.oxm.jaxb.Jaxb2Marshaller @Configuration class EngineConfig(@Value("\${engine-url}") private val url: String) { @Bean fun marshaller() = Jaxb2Marshaller().apply { contextPath = "at.tugraz.ikarus.engine" } @Bean fun client(marsh: Jaxb2Marshaller) = EngineClient().apply { defaultUri = url marshaller = marsh unmarshaller = marsh } }<file_sep>/src/main/kotlin/at/tugraz/ikarus/utilities/client/EngineClient.kt package at.tugraz.ikarus.utilities.client import at.tugraz.ikarus.engine.* import org.springframework.ws.client.core.support.WebServiceGatewaySupport import java.lang.IllegalArgumentException import javax.xml.bind.JAXBElement // https://spring.io/guides/gs/consuming-web-service/ //@Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN") class EngineClient : WebServiceGatewaySupport() { /** * Marshal and send the given object, receive and return JAXBElement * */ private fun send(request: Any): JAXBElement<*> = webServiceTemplate.marshalSendAndReceive(request) as JAXBElement<*> fun hello(name: String): HelloResponse { val response = send(Hello(name = name)) return response.value as HelloResponse } fun store(content: String): StoreResponse { val response = send(Store(content = content)) return response.value as StoreResponse } fun get(id: String): GetResponse { val response = send(Get(id = id)) return response.value as GetResponse } fun change(id: String, content: String): ChangeResponse { val response = send(Change(id = id, content = content)) return response.value as ChangeResponse } fun delete(id: String): DeleteResponse { val response = send(Delete(id = id)) return response.value as DeleteResponse } fun makeCol(sid: String, name: String): MakecollResponse { val response = send(Makecoll(id = sid, name = name)) return response.value as MakecollResponse } fun getCol(sid: String?, name: String?): GetcollResponse { if (sid == null && name == null) throw IllegalArgumentException("Both sid and name should not be null!") val response = send(Getcoll(sid = sid, name = name)) return response.value as GetcollResponse } fun deleteCol(sid: String?, name: String?): DeletecollResponse { if (sid == null && name == null) throw IllegalArgumentException("Both sid and name should not be null!") val response = send(Deletecoll(sid = sid, name = name)) return response.value as DeletecollResponse } fun insertCol(sid: String, id: String): InsertcollResponse { val response = send(Insertcoll(sid = sid, id = id)) return response.value as InsertcollResponse } fun removeCol(sid: String, id: String): RemovecollResponse { val response = send(Removecoll(sid = sid, id = id)) return response.value as RemovecollResponse } fun reset(code: String): ResetResponse { val response = send(Reset(doom = code)) return response.value as ResetResponse } fun searchColl(id: String): SearchcollResponse { val response = send(Searchcoll(id = id)) return response.value as SearchcollResponse } fun searchObj(text: String): SearchobjResponse { val response = send(Searchobj(text = text)) return response.value as SearchobjResponse } fun stat(): StatResponse { val response = send(Stat()) return response.value as StatResponse } }
ed89ff7a6136f5e3d86b716e0ce0eb6b6d256da9
[ "Kotlin", "Gradle" ]
9
Kotlin
Donutellko/IkarusUtilities
7f2f3a771e7be88f4f9f34e6245be2ca18831edb
91cea35ae4f05619db44f59b21871dc84f6ec059
refs/heads/master
<file_sep>package hometask; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.Select; import org.openqa.selenium.support.ui.WebDriverWait; public class BringItOn { public static void main(String[] args) throws InterruptedException { WebDriver driver = new ChromeDriver(); driver.get("https://paste.ubuntu.com/"); new WebDriverWait(driver,5) .until(ExpectedConditions.presenceOfElementLocated(By.id("id_poster"))); WebElement pasteName = driver.findElement(By.id("id_poster")); pasteName.sendKeys("how to gain dominance among developers"); WebElement syntax = driver.findElement(By.id("id_syntax")); Select syntaxDropdown = new Select(syntax); syntaxDropdown.selectByVisibleText("Bash"); WebElement Expiration = driver.findElement(By.id("id_expiration")); Select expirationDropdown = new Select(Expiration); expirationDropdown.selectByValue("day"); WebElement inputField = driver.findElement(By.id("id_content")); inputField.sendKeys( "git config --global user.name \"<NAME>\"\n" + "git reset $(git commit-tree HEAD^{tree} -m \"Legacy code\")\n" + "git push origin master --force" ); Thread.sleep(4000); WebElement submit = driver.findElement(By.xpath("//input[@type='submit']")); submit.click(); Thread.sleep(5000); driver.quit(); } } <file_sep>package hometask; import org.openqa.selenium.By; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; public class HurtMePlenty { public static void main(String[] args) throws InterruptedException { WebDriver driver = new ChromeDriver(); driver.get("https://cloud.google.com/"); new WebDriverWait(driver,10) .until(ExpectedConditions.presenceOfElementLocated(By.xpath("//input[@aria-label='Search box']"))); WebElement searchBox = driver.findElement(By.xpath("//input[@aria-label='Search box']")); searchBox.click(); searchBox.sendKeys("Google Cloud Platform Pricing Calculator"); searchBox.sendKeys(Keys.RETURN); new WebDriverWait(driver,10) .until(ExpectedConditions .presenceOfElementLocated(By.xpath("//div[@class='gs-title']/a[@data-ctorig='https://cloud.google.com/products/calculator']"))); WebElement searchResult = driver.findElement(By.xpath("//div[@class='gs-title']/a[@data-ctorig='https://cloud.google.com/products/calculator']")); searchResult.click(); Thread.sleep(5000); driver.quit(); } }
264f0d25875bfd12221566ebf0d279560ba7a7ad
[ "Java" ]
2
Java
artem-shcherba/webdriver_Artem_Shcherba
b53b1a7113b992b2f368feaf2592ca6ff3c6d516
64c70d58101d983dd9fae7d82d6b0a4da5a65c34
refs/heads/master
<file_sep>//index.js //获取应用实例 var app = getApp() Page({ data: { imgUrls: [ "../../res/imgs/index/mm.jpeg", "../../res/imgs/index/qm.jpeg", "../../res/imgs/index/gzt.jpeg" ], indicatorDots: true, autoplay: true, interval: 5000, duration: 1000, motto: 'Hello World', userInfo: {} }, //事件处理函数 bindViewTap: function() { console.log(this.data.userInfo) wx.navigateTo({ url: '../logs/logs' }) }, onLoad: function () { console.log('onLoad') this.setData({ userInfo: app.globalData.userInfo }) // 显示分享--分享带shareTicket wx.showShareMenu({ withShareTicket: true }) //调用应用实例的方法获取全局数据 /* app.getUserInfo(function(userInfo){ //更新数据 that.setData({ userInfo:userInfo }) }) */ }, onShareAppMessage: function () { return { title: '你转发,我送钱!不相信,别点开!', desc: '每转发一次获3元奖励,可累加!', path: 'pages/index/index?userId='+app.globalData.userInfo['id'], success: function(res) { // 转发成功 console.log('function[onShareAppMessage] success!') }, fail: function(res) { // 转发失败 console.log('function[onShareAppMessage] fail!') } } } }) <file_sep>-- 创建用户hjy,密码为hjy create user hjy identified by 'hjy'; -- 创建用户hjy管理的数据库SweetHeart; create database `SweetHeart`; -- 授权数据库SweetHeart给用户hjy grant all on SweetHeart.* to 'hjy'; -- 数据导入部分 insert into users(id,name) values(1,'hjy'); insert into users(id,name) values(2,'xjm');<file_sep>//cake.js //获取应用实例 var app = getApp(), getApiData = require("../../utils/apiData.js").getApiData Page({ data: { categories : [], cakes : [], cakeOrderNum: {}, activeIndex: 0, // 选中类型的索引 sliderOffset: 0, sliderWidth: 0 }, // 装载页面 onLoad: function(){ var storeCates = wx.getStorageSync('categories') if (storeCates){ console.log('getStoreData[onLoad] categories') this.setData({ categories : storeCates }) var cateUrl = this.data.categories[this.data.activeIndex].uri var storeCakes = wx.getStorageSync(cateUrl) console.log('getStoreData[onLoad] categories/id/cakes') this.setData({ cakes : storeCakes }) }else{ var that = this var token = app.globalData.token + ':none' console.log('token: '+token) getApiData( app.globalData.baseUrl + '/api/v1.0/categories', {}, token, function(data){ console.log('getApiData[onLoad] categories') that.setData({ categories : data.categories }) wx.setStorageSync('categories', data.categories) var these = that wx.getSystemInfo({ success: function(res) { var width = res.windowWidth / these.data.categories.length these.setData({ sliderWidth: width, sliderOffset: width * these.data.activeIndex }); } }); var cateUrl = that.data.categories[that.data.activeIndex].uri var storeCakes = wx.getStorageSync(cateUrl) if (storeCakes){ console.log('getStoreData[onLoad] categories/id/cakes') this.setData({ cakes : storeCakes }) }else{ getApiData( cateUrl + '/cakes', {}, token, function(data){ console.log('getApiData[onLoad] categories/id/cakes') these.setData({ cakes : data.cakes }) wx.setStorageSync(cateUrl, data.cakes) }) } }) } // 加载数据 /* wx.request({ url: 'https://flask.haojunyu.com/api/v1.0/categories', header: { 'content-type': 'application/json' }, success: function(res){ console.log(res.data) that.setData({ categories : res.data.categories }) } })*/ }, // 显示界面 onShow: function(){ // 加载各种蛋糕的订单数量 var that = this var token = app.globalData.token + ':none' getApiData( app.globalData.baseUrl + '/api/v1.0/orders/cakeNum', {}, token, function(data){ console.log('getApiData[onLoad] orders/cakeNum') that.setData({ cakeOrderNum : data }) }) }, tabClick: function (e) { this.setData({ sliderOffset: e.currentTarget.offsetLeft, activeIndex: e.currentTarget.id }); var cateUrl = this.data.categories[this.data.activeIndex].uri var storeCakes = wx.getStorageSync(cateUrl) if (storeCakes){ console.log('getStoreData[tabClick] categories/id/cakes') this.setData({ cakes : storeCakes }) }else{ var that = this var token = app.globalData.token + ':none' getApiData( cateUrl + '/cakes', {}, token, function(data){ console.log('getApiData[tabClick] categories/id/cakes') that.setData({ cakes : data.cakes }) wx.setStorageSync(cateUrl, data.cakes) }) } }, onShareAppMessage: function () { return { title: '你转发,我送钱!不相信,别点开!', desc: '每转发一次获3元奖励,可累加!', path: 'pages/index/index?userId='+app.globalData.userInfo['id'], success: function(res) { // 转发成功 console.log('function[onShareAppMessage] success!') }, fail: function(res) { // 转发失败 console.log('function[onShareAppMessage] fail!') } } } }) <file_sep>-- 创建用户hjy,密码为hjy create user hjy identified by 'hjy'; -- 创建用户hjy管理的数据库SweetHeart; create database SweetHeart default character set utf8 collate utf8_general_ci; create database SHTest default character set utf8 collate utf8_general_ci; -- 授权数据库SweetHeart给用户hjy grant all on SweetHeart.* to 'hjy'; use SweetHeart; -- 数据导入部分 insert into users(id,name) values(1,'hjy'); insert into users(id,name) values(2,'xjm'); insert into categories(id, name,`desc`) values(1, 'cake', '蛋糕'); insert into categories(id, name,`desc`) values(2, 'biscuit', '饼干'); insert into categories(id, name,`desc`) values(3, 'pudding', '布丁'); insert into categories(id, name,`desc`) values(4, 'chocolate', '巧克力'); insert into cakes(id, name, `desc`, detail, price, imgUrl, orders, stars, cateId) values(11, 'creamCake','鲜奶蛋糕','这是鲜奶蛋糕',58,'creamCake.jpg', 0, 3, 1); insert into cakes(id, name, `desc`, detail, price, imgUrl, orders, stars, cateId) values(12, 'fruitCake','水果蛋糕','这是水果蛋糕',58,'fruitCake.jpg', 0, 3, 1); insert into cakes(id, name, `desc`, detail, price, imgUrl, orders, stars, cateId) values(13, 'personalCake','个性蛋糕','这是个性蛋糕',118,'personalCake.jpg', 0, 3, 1); insert into cakes(id, name, `desc`, detail, price, imgUrl, orders, stars, cateId) values(14, 'mousseCake','慕斯蛋糕','这是慕斯蛋糕',78,'mousseCake.jpg', 0, 3, 1); insert into cakes(id, name, `desc`, detail, price, imgUrl, orders, stars, cateId) values(15, 'flowerCake','鲜花蛋糕','这是鲜花蛋糕',78,'flowerCake.jpg', 0, 3, 1); insert into cakes(id, name, `desc`, detail, price, imgUrl, orders, stars, cateId) values(16, 'layerCake','千层蛋糕','这是千层蛋糕',128,'layerCake.jpg', 0, 3, 1); insert into cakes(id, name, `desc`, detail, price, imgUrl, orders, stars, cateId) values(17, 'paperCake','纸杯蛋糕','这是纸杯蛋糕',32.8,'paperCake.jpg', 0, 3, 1); insert into cakes(id, name, `desc`, detail, price, imgUrl, orders, stars, cateId) values(21, 'cookies','曲奇饼干','这是曲奇饼干',32.8,'cookies.jpg', 0, 3, 2); insert into cakes(id, name, `desc`, detail, price, imgUrl, orders, stars, cateId) values(22, 'Marguerite','玛格丽特','这是玛格丽特,一点都不像饼干的名字',32.8,'Marguerite.jpg', 0, 3, 2); insert into cakes(id, name, `desc`, detail, price, imgUrl, orders, stars, cateId) values(23, 'cartoonCookies','卡通饼干','这是卡通饼干',32.8,'cartoonCookies.jpg', 0, 3, 2); insert into cakes(id, name, `desc`, detail, price, imgUrl, orders, stars, cateId) values(24, 'cranberryCookies','蔓越莓饼干','这是蔓越莓饼干,一点都不像饼干的名字',32.8,'cranberryCookies.jpg', 0, 3, 2); insert into cakes(id, name, `desc`, detail, price, imgUrl, orders, stars, cateId) values(25, 'xlkq','昔腊可球','这是昔腊可球',32.8,'xlkq.jpg', 0, 3, 2); insert into cakes(id, name, `desc`, detail, price, imgUrl, orders, stars, cateId) values(31, 'creamPudding','奶油布丁','这是奶油布丁',32.8, 'creamPudding.jpg', 0, 3, 3); insert into cakes(id, name, `desc`, detail, price, imgUrl, orders, stars, cateId) values(32, 'mangoPudding','芒果布丁','这是芒果布丁',32.8,'mangoPudding.jpg', 0, 3, 3); insert into cakes(id, name, `desc`, detail, price, imgUrl, orders, stars, cateId) values(33, 'strawberryPudding','草莓布丁','这是草莓布丁',32.8,'strawberryPudding.jpg', 0, 3, 3); insert into cakes(id, name, `desc`, detail, price, imgUrl, orders, stars, cateId) values(34, 'blueberryPudding','蓝莓布丁','这是蓝莓布丁',32.8,'blueberryPudding.jpg', 0, 3, 3); insert into cakes(id, name, `desc`, detail, price, imgUrl, orders, stars, cateId) values(41, 'strawberryChocolate','草莓味巧克力','这是草莓味巧克力',32.8, 'strawberryChocolate.jpg', 0, 3, 4); insert into cakes(id, name, `desc`, detail, price, imgUrl, orders, stars, cateId) values(42, 'lemonChocolate','柠檬味巧克力','这是柠檬味巧克力',32.8,'lemonChocolate.jpg', 0, 3, 4); insert into cakes(id, name, `desc`, detail, price, imgUrl, orders, stars, cateId) values(43, 'matchaChocolate','抹茶味巧克力','这是抹茶味巧克力',32.8, 'matchaChocolate.jpg', 0, 3, 4); insert into cakes(id, name, `desc`, detail, price, imgUrl, orders, stars, cateId) values(44, 'whiteMilkChocolate','白牛奶味巧克力','这是白牛奶味巧克力',32.8,'whiteMilkChocolate.jpg', 0, 3, 4); insert into cakes(id, name, `desc`, detail, price, imgUrl, orders, stars, cateId) values(45, 'bitterSweetChocolate','苦甜味巧克力','这是苦甜味巧克力',32.8, 'bitterSweetChocolate.jpg', 0, 3, 4); show VARIABLES like 'character%%'; <file_sep>//cake.js //获取应用实例 var app = getApp(), getApiData = require("../../utils/apiData.js").getApiData, postApiData = require("../../utils/apiData.js").postApiData, putApiData = require("../../utils/apiData.js").putApiData, md5 = require("../../utils/md5.js").hex_md5 Page({ data: { cakeDetail: {}, imgUrl: null, cakeComments: {}, cakeUri: null, ordersNum : null, location: '江苏省镇江市润州区黄山西路万达广场写字楼A座716室', phone: '18261956851' }, // 装载页面 onLoad: function(request){ console.log(request.uri) this.setData({ cakeUri:request.uri }) // 设置imgUrl this.setData({ imgUrl: app.globalData.baseUrl + '/imgs/' }) var that = this var token = app.globalData.token + ':none' console.log('token: '+token) getApiData( request.uri, {}, token, function(data){ that.setData({ cakeDetail:data }) }) // 获取甜点的订单数目 var ordUri = this.data.cakeUri + '/orderNum' console.log(ordUri) getApiData( ordUri, {}, token, function(data){ console.log(data) that.setData({ ordersNum : data.orderNum }) }) // 获取完整的评论 getApiData( request.uri+'/comments', {}, token, function(data){ that.setData({ cakeComments:data.comments }) }) }, // 定位 locate: function(e){ console.log('location') var latitude=32.19634838375969 var longitude=119.436195097602 wx.openLocation({ latitude: latitude, longitude: longitude, scale: 28 }) /* wx.chooseLocation({ success: function(res){ console.log(res) } }) */ }, // 打电话 call: function(e){ var phone = e.currentTarget.dataset['phone'] console.log(phone) wx.makePhoneCall({ phoneNumber: phone }) }, // 下单 gobuy: function(e){ var token = app.globalData.token + ':none' console.log('立即下单......') var cashbox = parseFloat(app.globalData.userInfo['cashbox']) var price = parseFloat(this.data.cakeDetail['price']) console.log(price) var fee = 0.00 var discount = 0.00 if( cashbox > 0.0){ if(cashbox <= price){ fee = price - cashbox discount = cashbox }else{ fee = 0.01 discount = price-0.01 } }else{ fee = price } fee = parseFloat(fee).toFixed(2) discount = parseFloat(discount).toFixed(2) console.log(fee) console.log(discount) var that = this // 获取预付单信息 (金额赋值为this.data.cakeDetail['price']) getApiData(app.globalData.baseUrl + '/api/v1.0/prepay', { 'body' : app.globalData.mch_name + '-' + this.data.cakeDetail['cate']['desc'], 'total_fee': fee, 'notify_url': app.globalData.baseUrl + 'api/v1.0/notify' }, token, function(data){ if(data['prepay']['return_code'] = 'SUCCESS' && data['prepay']['result_code']){ // 付款 var timeStamp = new Date().getTime().toString() var nonceStr = Math.random().toString(36).substr(2) var pack = 'prepay_id=' + data['prepay']['prepay_id'] var signData = 'appId=' + data['prepay']['appid'] signData += '&nonceStr=' + nonceStr signData += '&package=' + pack signData += '&signType=MD5&timeStamp='+timeStamp signData += '&key=666ZhangWangLuTin00SweetHeart999' wx.requestPayment({ 'timeStamp': timeStamp, 'nonceStr': nonceStr, 'package': pack, 'signType': 'MD5', 'paySign': md5(signData), 'success':function(res){ console.log('pay success......') console.log(res) // 记录单号 var orderUri = app.globalData.baseUrl + '/api/v1.0/orders' var orderData = {} orderData['userId']=app.globalData.userInfo['id'] orderData['cakeId']=that.data.cakeDetail.cakeId orderData['status']=1 orderData['prepayId']=data['prepay']['prepay_id'] // 更新数据库表orders postApiData( orderUri, orderData, token, function(data){ console.log(data) console.log('postApiData[POST] /orders') }) // 更新数据库表user.cashbox if(discount != 0.0){ var userUri = app.globalData.baseUrl + '/api/v1.0/users/' + app.globalData.userInfo['id'] + '/subCash' putApiData(userUri, { 'cash': discount }, token, function(res){ console.log('消费余额'+ discount +'元成功!') }) } // 跳转到已下单界面 wx.redirectTo({ url: '../orders/orders?status=1' }) }, 'fail':function(res){ console.log('pay fail......') console.log(res) } }) } console.log(data) }) }, // 预览图片 photoScan: function(e){ var photos = this.data.cakeComments[e.currentTarget.dataset['index']].photos var photoUrls = new Array(); for(var i=0; i<photos.length; i++ ){ photoUrls[i] = this.data.imgUrl + 'upload/' +photos[i].picName } console.log(e.currentTarget.dataset['item']) console.log(photoUrls) wx.previewImage({ current: e.currentTarget.dataset['item'], // 当前显示图片的http链接 urls: photoUrls // 需要预览的图片http链接列表 }) } }) <file_sep>//app.js App({ onLaunch: function (ops) { console.log(ops) //清空本地数据缓存 wx.clearStorageSync() console.log('clear storeage......') //登录验证 this.logIn(ops) }, logIn: function(ops){ console.log('loging.......') var that = this wx.login({ success: function(e){ console.log('wx.login successed....') var code = e.code console.log(code) wx.getUserInfo({ success: function(res){ console.log('wx.getUserInfo successed.....') console.log(res) var encryptedData = res.encryptedData // 调用服务器api that.thirdLogin(code, encryptedData, res.rawData, res.signature, res.iv, ops) // 保存用户信息到全局变量 that.globalData.userInfo = res.userInfo console.log('userInfo:......') console.log(that.globalData.userInfo) } }) } }) }, thirdLogin: function(code,encryptedData,rawData,signature,iv,ops){ var getFulApiData = require("utils/apiData.js").getFulApiData var putApiData = require("utils/apiData.js").putApiData var that = this var data = {} data['code'] = code data['encryptedData'] = encryptedData data['rawData'] = rawData data['signature'] = signature data['iv'] = iv getFulApiData( this.globalData.baseUrl + '/auth/login', data, '', function(res){ // 获取token并存储到全局变量 that.globalData.token = res['token'] that.globalData.userInfo['id'] = res['userId'] that.globalData.userInfo['is_first'] = res['is_first'] that.globalData.userInfo['cashbox'] = res['cashbox'] console.log(that.globalData.userInfo) },function(res){ // 登录成功后获取app的配置 var getApiData = require("utils/apiData.js").getApiData var token = that.globalData.token + ':none' var configUri = that.globalData.baseUrl + '/api/v1.0/initConfigs' var these = that getApiData(configUri, '', token, function(data){ // 设置配置 these.globalData.configs = data.configs console.log(data) // complete是在success完成之后 if(these.globalData.userInfo['is_first']){ console.log(these.globalData.configs) // https://mp.weixin.qq.com/debug/wxadoc/dev/framework/app-service/scene.html // 目前支持单人分享,群分享,加钱 if(ops.scene == 1007 || ops.scene == 1044){ var ds = ops.query if(ds.hasOwnProperty('userId')){ var token = these.globalData.token + ':none' var userUri = these.globalData.baseUrl + '/api/v1.0/users/' + ds['userId'] + '/addCash' var cash = parseFloat(these.globalData.configs['invalid_user_cash']) if(these.globalData.userInfo['city'] == 'Zhenjiang'){ cash = parseFloat(these.globalData.configs['valid_user_cash']) } putApiData(userUri, { 'cash': cash }, token, function(res){ console.log('领取券'+ cash +'成功!') }) } } } }) }) }, getUserInfo:function(cb){ var that = this if(this.globalData.userInfo){ typeof cb == "function" && cb(this.globalData.userInfo) }else{ //调用登录接口 wx.login({ success: function (res) { console.log(res.code) wx.getUserInfo({ success: function (res) { that.globalData.userInfo = res.userInfo typeof cb == "function" && cb(that.globalData.userInfo) } }) } }) } }, globalData:{ userInfo: null, baseUrl : 'https://flask.haojunyu.com', token: null, configs: null } }) <file_sep>//comment.js var app = getApp(), getApiData = require("../../utils/apiData.js").getApiData, postApiData = require("../../utils/apiData.js").postApiData, putApiData = require("../../utils/apiData.js").putApiData, Base64 = require('../../utils/Base64.js') Page({ data: { key: 3, cakeId : null, orderId : null, showTopTips: '', files: [] }, onLoad: function (req) { console.log(req.cakeId) console.log(req.orderId) // 设置图片前缀:userId_cakeId_* this.setData({ cakeId: req.cakeId, orderId: req.orderId }) }, //点击左边,半颗星 selectLeft: function (e) { var key = e.currentTarget.dataset.key if (this.data.key == 0.5 && e.currentTarget.dataset.key == 0.5) { //只有一颗星的时候,再次点击,变为0颗 key = 0; } console.log("得" + key + "分") this.setData({ key: key }) }, //点击右边,整颗星 selectRight: function (e) { var key = e.currentTarget.dataset.key console.log("得" + key + "分") this.setData({ key: key }) }, chooseImage: function (e) { var that = this; wx.chooseImage({ count: 8, // 最多上传的照片数 sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有 sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有 success: function (res) { if(res.tempFilePaths.length > 8){ that.setData({ showTopTips:'最多只能上传8张图片' }) } // 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片 that.setData({ files: res.tempFilePaths }); } }) }, previewImage: function(e){ wx.previewImage({ current: e.currentTarget.id, // 当前显示图片的http链接 urls: this.data.files // 需要预览的图片http链接列表 }) }, submitComment: function(e){ // 更新数据库 var that = this var token = app.globalData.token + ':none' var comUri = app.globalData.baseUrl + '/api/v1.0/comments' var data = {} data['cakeId']=this.data.cakeId data['userId']=app.globalData.userInfo['id'] data['stars']=this.data.key data['comment']=e.detail.value.txt console.log('update database table comments...') postApiData( comUri, data, token, function(data){ console.log(data) console.log('postApiData[submitComment] /comments') if(that.data.files.length!=0){ // 上传图片到服务器 that.uploadImage(that.data.files, data[2]['commentId']) wx.showToast({ title: '图片上传成功', icon: 'success', duration: 3000 }); } // 更新订单状态 var orderUri = app.globalData.baseUrl + '/api/v1.0/orders/' + that.data.orderId var ordData = {} ordData['status']=3 putApiData( orderUri, ordData, token, function(data){ console.log(data) console.log('putApiData[submitComment] /orders') }) // 跳转到已评论界面 wx.redirectTo({ url: '../orders/orders?status=3' }) }) }, // 递归上传图片到服务器 uploadImage: function(files, commentId){ console.log('function uploadImage...') console.log(files) console.log(commentId) var token = app.globalData.token + ':none' var preName = app.globalData.userInfo['id'] + '_' + this.data.cakeId + '_' // 批量上传图片到服务器 if(files.length != 0){ console.log('uploadImage '+files[0]+'....') var that = this wx.uploadFile({ url: app.globalData.baseUrl + '/api/v1.0/upload', filePath: files[0], name: 'file', formData:{ 'fileName': preName + files[0].substring(13) }, header : { 'authorization': 'Basic ' + Base64.encode(token), 'context-type' : 'multipart/form-data' }, success: function(res){ console.log(res) console.log('uploadImage '+files[0]+' successed!') var picUri = app.globalData.baseUrl + '/api/v1.0/pictures' var data = {} data['commentId']=commentId data['picName']=preName + files[0].substring(13) // 更新数据库表pictures postApiData( picUri, data, token, function(data){ console.log(data) console.log('postApiData[POST] /pictures') }) files.splice(0,1) that.uploadImage(files,commentId) }, fail: function(res){ console.log('wx.uploadFile fail...') }, complete: function(res){ console.log('wx.uploadFile complete...') console.log(res) } }) } } }) <file_sep>//cake.js //获取应用实例 var app = getApp(), getApiData = require("../../utils/apiData.js").getApiData Page({ data: { orders : [], status : null }, // 装载页面 onLoad: function(request){ console.log(request.status) this.setData({ status:request.status }) }, // 显示界面 onShow: function(){ var orderUrl = app.globalData.baseUrl + '/api/v1.0/users/' + app.globalData.userInfo['id'] + '/status/' + this.data.status var that = this var token = app.globalData.token + ':none' console.log('token: '+token) getApiData( orderUrl + '/orders', {}, token, function(data){ console.log('getApiData[onLoad] users/*/status/*/orders') that.setData({ orders : data.orders }) wx.setStorageSync(orderUrl, data.orders) }) }, goComment: function (e) { console.log(e) var cakeId = e.currentTarget.dataset.cakeid var orderId = e.currentTarget.dataset.orderid console.log(cakeId) console.log(orderId) wx.navigateTo({ url: '../comment/comment?cakeId='+cakeId+'&orderId='+orderId }) }, goCakeDetail: function(e){ var cakeUri = e.currentTarget.dataset.uri wx.navigateTo({ url: '../cake/cake?uri='+cakeUri }) } })
8803e17da9515ad34a1d1740b47853a4127bc4f7
[ "JavaScript", "SQL" ]
8
JavaScript
mn3711698/FrontSweetHeart
198408d917a30ef424c12e220c7595c10aebec44
980540af408961c6750ac432ac9a5668c83bc5e9
refs/heads/main
<file_sep>import AvatarUploader from './AvatarUploader.vue'; export default AvatarUploader; <file_sep># 一个简单的 Vue 头像选择器的实现 ## Preface 项目中需要一个头像选择器,但经过调研,市面上的头像选择器(或者图片截取器)一方面风格固定,无法所用组件库风格融合,另一方面,为了做到尽善尽美,大家为选择器预设了许许多多的属性,这对于选择器本身而言是一种增强的效果,但对于具体的项目而言有些过重。于是实现一个简单、可定制(通过 slots)的头像选择器的想法忽然诞生。 ## Example 不融入任何组件库时,头像选择器长这样: ![](assets/plain.gif) 在 vuetify 中,定制后: ![](assets/in-vuetify.gif) ## 原理 & 实现 原理上这个小组件没有任何技术含量:通过 flex 布局排列图像编辑区域与操作按钮区域、通过 boxShadow 实现遮罩层、通过更新 backgroundPosition 实现图片的移动、通过 `canvas.toDataUrl` 导出图片等等。 而定制化诸如 slider、button 等组件基于一系列 `slots` 以及组件 `props`,具体见[此文档](https://github.com/taoqingqiu/vue-plain-avatar-uploader/tree/main/src/components)。 <file_sep># Vue Plain Avatar Uploader This is a plain vue component used to help cropping image when choosing one image as avatar. ## Getting Started Firstly, install this component: ```shell npm install vue-plain-avatar-uploader ``` Secondly, import and use this component: ```vue <template> <avatar-uploader /> </template> <script> import AvatarUploader from "vue-plain-avatar-uploader"; export default { name: "App", components: { AvatarUploader } }; </script> ``` More detailed example is in [this REPO](https://github.com/taoqingqiu/vue-plain-avatar-uploader#readme). ## Component API ### Props | Name | Type | Default | Description | | --------------- | --------- | --------- | ---------------------------------------------------------------------------------------- | | height | `number` | 150 | height of this component | | maskProps | `object` | undefined | customize mask above image, details are [below](#maskProps) | | outputProps | `object` | undefined | customize mask above image, details are [below](#outputProps) | | backgroundColor | `string` | '#f2f3f8' | background color of container containing image | | maxMultiple | `number` | 2 | maximum multiple of enlarging image, the reference is container | | hideShapeGroup | `boolean` | undefined | sometimes, we don't need to change shape of preview area | | img | `string` | undefined | url that can be accepted by attribute 'src' of element 'img', to set an image in advance | ### Slots #### action.innerSelectButton When no image is selected, there should be a button used to open file manager in preview area of mask layer. This slot only provides a function `click`, an usage example in framework [vuetify](https://vuetifyjs.com) is below: ```vue <template> <avatar-uploader> <template #[`action.innerSelectButton`]="{ on }"> <v-icon v-on="on">mdi-upload</v-icon> </template> </avatar-uploader> </template> ``` #### action.slider So called slider is used to adjust image size, and also an example is below: ```vue <template> <avatar-uploader> <template #[`action.slider`]="{ on, attrs }"> <v-slider v-on="on" v-bind="attrs" step="0.01" hide-details /> </template> </avatar-uploader> </template> ``` #### action.shapeGroup Used to change shape of preview area at mask layer, an example is below: ```vue <template> <avatar-uploader> <template #[`action.shapeGroup`]="{ on, attrs, options }"> <v-radio-group @change="on.input" v-bind="attrs" row dense hide-details class="mt-0" > <v-radio :label="option.text" :value="option.value" v-for="(option, index) in options" :key="index" ></v-radio> </v-radio-group> </template> </avatar-uploader> </template> ``` <small>\* Instead of function 'input', component radio-group of vuetify use function 'change' to implement bidirectional binding</small> #### action.selectButton Similar with `action.selectInnerButton` functionally, but the position of this slot is at right side of component. Specially, this slot provides an attribute `text`, which indicates whether an image has been selected or not. ```vue <template> <avatar-uploader> <template #[`action.selectButton`]="{ on, text }"> <v-btn v-on="on" small>{{ text }}</v-btn> </template> </avatar-uploader> </template> ``` <small>\* Recklessly, value of attribute 'text' is one of '选择' and '重选'</small> #### action.confirmButton Finally, we finish adjusting and cropping image, and click one confirming button. This slot provides a function `confirm`, which we will emit function 'confirm' injected by parent component after triggering. ```vue <template> <avatar-uploader> <template #[`action.confirmButton`]="{ on, attrs }"> <v-btn v-on="on" v-bind="attrs" small>确定</v-btn> </template> </avatar-uploader> </template> ``` ### Events | Name | Description | | ------- | ------------------------------------------------------------------------------------ | | confirm | export output to parent component as an url (created by function `canvas.toDataUrl`) | ### <span id="maskProps">MaskProps</span> ```js { // color of mask layer, the default is '#00000025' // eg. '#00000025', 'rgba(255,255,255, 0.37)' shadowColor: string, // border-radius of transparent area of mask // the default is '5px' // only works when shape of transparent area is set as 'square' squareBorderRadius: string, } ``` ### <span id="outputProps">OutputProps</span> ```js { // size of output image // the default is [100, 100] outputSize: array<number>, // format of output image // the default is 'png' // eg. 'png', 'jpeg' format: string, // when selected part of image can not fill a square // we will see the background // the default is 'transparent' (when format is 'png') and '#fff' (other format) // nb. 'transparent' only works when 'png' format backgroundColor: string, } ``` ## Usage of slots in vuetify For better understanding of those slots, here's one example in vuetify: ```vue <template> <avatar-uploader @confirm="confirmAvatar" hideShapeGroup :img="avatar"> <template #[`action.innerSelectButton`]="{ on }"> <v-icon v-on="on">mdi-upload</v-icon> </template> <template #[`action.slider`]="{ on, attrs }"> <v-slider v-on="on" v-bind="attrs" step="0.01" hide-details /> </template> <template #[`action.shapeGroup`]="{ on, attrs, options }"> <v-radio-group @change="on.input" v-bind="attrs" row dense hide-details class="mt-0" > <v-radio :label="option.text" :value="option.value" v-for="(option, index) in options" :key="index" ></v-radio> </v-radio-group> </template> <template #[`action.selectButton`]="{ on, text }"> <v-btn v-on="on" small>{{ text }}</v-btn> </template> <template #[`action.confirmButton`]="{ on, attrs }"> <v-btn v-on="on" v-bind="attrs" small>确定</v-btn> </template> </avatar-uploader> </template> <script> export default { components: { AvatarUploader: () => import('vue-plain-avatar-uploader') } data() { return { avatar: 'xxx.png' }; }, }; </script> ``` Result is showing up in the second GIF of REPO README. ## Moreover CN version is [here](https://github.com/taoqingqiu/vue-plain-avatar-uploader/tree/main/src/components/README-CN.md). <file_sep># 一个简单的 Vue 头像上传器 这个简单朴素的 Vue 组件用于,帮助我们选取、裁剪图片作为头像。 ## 起步 首先下载此组件: ```shell npm install vue-plain-avatar-uploader ``` 而后,使用之: ```vue <template> <avatar-uploader /> </template> <script> import AvatarUploader from 'vue-plain-avatar-uploader'; export default { name: 'App', components: { AvatarUploader } }; </script> ``` 更详细的例子,请见[这个仓库](https://github.com/taoqingqiu/vue-plain-avatar-uploader)。 ## 组件 API ### 属性 | Name | Type | Default | Description | | --------------- | --------- | --------- | ---------------------------------------------------------------------------------- | | height | `number` | 150 | 组件的高 | | maskProps | `object` | undefined | 定制化遮罩层的种种属性,详见[这里](#maskProps) | | outputProps | `object` | undefined | 定制化输出图片的属性,详见[这里](#outputProps) | | backgroundColor | `string` | '#f2f3f8' | 放置图片的容器元素的背景色 | | maxMultiple | `number` | 2 | 图像相对于放置其的容器的最大放大倍数(初始时会有个自适应的过程,因为有所谓的放大) | | hideShapeGroup | `boolean` | undefined | 有时我们并不想切换用于切换遮罩层预览区域的形状,这时我们可以隐藏之 | | img | `string` | undefined | 此属性可为组件在初始时,预设置一个目标图片。需保证该值可以被 `img` 元素接受 | ### 插槽 #### action.innerSelectButton 当没有选择图片时,预览区域按说会有一个用来打开文件管理器、选择图片的按钮。 此插槽只提供一个 `click` 方法, 一个在 [vuetify](https://vuetifyjs.com) 中的示例用法如下: ```vue <template> <avatar-uploader> <template #[`action.innerSelectButton`]="{ on }"> <v-icon v-on="on">mdi-upload</v-icon> </template> </avatar-uploader> </template> ``` #### action.slider 众所周知,slider 用于调节选取的目标图片的尺寸。示例用法: ```vue <template> <avatar-uploader> <template #[`action.slider`]="{ on, attrs }"> <v-slider v-on="on" v-bind="attrs" step="0.01" hide-details /> </template> </avatar-uploader> </template> ``` #### action.shapeGroup 所谓的 `shapeGroup` 是指用于切换遮罩层预览区域形状的 input 组,更具体地,应该是一对 radio。 ```vue <template> <avatar-uploader> <template #[`action.shapeGroup`]="{ on, attrs, options }"> <v-radio-group @change="on.input" v-bind="attrs" row dense hide-details class="mt-0"> <v-radio :label="option.text" :value="option.value" v-for="(option, index) in options" :key="index"></v-radio> </v-radio-group> </template> </avatar-uploader> </template> ``` <small>\* 从示例中可以看出,vuetify 的 radio-group 双向绑定所使用的事件被魔改成了 `change`,这或许是符合 html 约定的 </small> #### action.selectButton 与 `action.selectInnerButton` 功能上类似, 但此插槽的目标位置位于图片调整区域右侧。 另外,此插槽提供了个 `text` 属性,用于表征目标图片是否已选择。 ```vue <template> <avatar-uploader> <template #[`action.selectButton`]="{ on, text }"> <v-btn v-on="on" small>{{ text }}</v-btn> </template> </avatar-uploader> </template> ``` <small>\* 目前 text 值被粗糙地设定为 '选择' 或者 '重选'</small> #### action.confirmButton 当我们完成了调整,需要导出给父组件时,便用到了这个插槽。 这个插槽提供了一个 `click` 方法,用来触发上述的导出。更具体而言,该方法会先通过 canvas.toDataUrl 方法生成结果图片,而后 `emit` 该结果给父组件绑定的 `confirm` 方法。 ```vue <template> <avatar-uploader> <template #[`action.confirmButton`]="{ on, attrs }"> <v-btn v-on="on" v-bind="attrs" small>确定</v-btn> </template> </avatar-uploader> </template> ``` ### 事件 | Name | Description | | ------- | ------------------------ | | confirm | 用于导出结果图片给父组件 | ### <span id="maskProps">MaskProps</span> ```js { // 遮罩层的颜色 // eg. '#00000025', 'rgba(255,255,255, 0.37)' shadowColor: string, // 遮罩层预览区域的 border-radius // 默认 '5px' // 只有在遮罩层预览区域形状为方型时生效 squareBorderRadius: string, } ``` ### <span id="outputProps">OutputProps</span> ```js { // 输出图片的尺寸 // 默认是 100x100 即 [100, 100] outputSize: array<number>, // 输出图片的格式 // 默认是 'png' // eg. 'png', 'jpeg' format: string, // 当选中的图片区域只占预览区域的一部分时, // 输出图片会出现背景, // 此属性用于定制该背景色 // 默认是 'transparent' ('png' 格式时) 和 '#fff' (其他格式) // 此外,传入 'transparent' 也只会在 'png' 格式时生效 backgroundColor: string, } ``` ## Vuetify 组件中通过插槽定制化示例 为了更好展现如何定制化,一例以蔽之: ```vue <template> <avatar-uploader @confirm="confirmAvatar" hideShapeGroup :img="avatar"> <template #[`action.innerSelectButton`]="{ on }"> <v-icon v-on="on">mdi-upload</v-icon> </template> <template #[`action.slider`]="{ on, attrs }"> <v-slider v-on="on" v-bind="attrs" step="0.01" hide-details /> </template> <template #[`action.shapeGroup`]="{ on, attrs, options }"> <v-radio-group @change="on.input" v-bind="attrs" row dense hide-details class="mt-0"> <v-radio :label="option.text" :value="option.value" v-for="(option, index) in options" :key="index"></v-radio> </v-radio-group> </template> <template #[`action.selectButton`]="{ on, text }"> <v-btn v-on="on" small>{{ text }}</v-btn> </template> <template #[`action.confirmButton`]="{ on, attrs }"> <v-btn v-on="on" v-bind="attrs" small>确定</v-btn> </template> </avatar-uploader> </template> <script> export default { components: { AvatarUploader: () => import('vue-plain-avatar-uploader') } data() { return { avatar: 'xxx.png' }; }, }; </script> ``` 其效果可见本 REPO README 的 GIF 示范。
90b41b97878d141e6bec92830b45118bac9812d9
[ "JavaScript", "Markdown" ]
4
JavaScript
taoqingqiu/vue-plain-avatar-uploader
38b462e57a5562d527a5ef5367a810d552d790a7
b6e9f9929d91da98ae3aa02cc0ff85c7e0ed65ff
refs/heads/master
<repo_name>saykaren/ColorsReduxDeploy<file_sep>/precache-manifest.9a322065558115fc2c1194cea92fb3e7.js self.__precacheManifest = (self.__precacheManifest || []).concat([ { "revision": "708c3f08ecb4fa5bc68fa23aef12e662", "url": "/ColorsReduxDeploy/index.html" }, { "revision": "70c478022587f9503f70", "url": "/ColorsReduxDeploy/static/css/main.956bc47f.chunk.css" }, { "revision": "d8ca8e428a695cf64d19", "url": "/ColorsReduxDeploy/static/js/2.b3e46991.chunk.js" }, { "revision": "70c478022587f9503f70", "url": "/ColorsReduxDeploy/static/js/main.bef00ca2.chunk.js" }, { "revision": "9042217c0557926c3a67", "url": "/ColorsReduxDeploy/static/js/runtime~main.51361773.js" } ]);
c7b426955bd603c6cfc3252681798356f6691eac
[ "JavaScript" ]
1
JavaScript
saykaren/ColorsReduxDeploy
d745e8014e9d9d12edd655e10224481937b1dd38
e4957e6a73981e0761c1abeb0299bffa305f8b65
refs/heads/main
<file_sep>--- author: "xiaoyu" authorlink: "https://github.com/yu199195" date: 2020-12-27T15:00:00.000Z title: "Apache ShenYu 梦码读书会介绍" tags: ["DreamCode", "ShenYu","GateWay"] cover: "/img/activities/apache-open-shenyu-01.jpg" descripton: "Apache ShenYu 梦码读书会介绍" --- ![ShenYu 梦码读书会介绍](/img/shenyu/activite/shenyu-xmind.png) ### Apache ShenYu 梦码读书会(ShenYu 2020 活动介绍) - 日期:2020年12月27日,星期日 ### 活动背景 - 为了提高社区参与者的积极性, 促进ShenYu社区的建设, 锻炼大家的表达能力和提升技术核心力量, 社区以源码阅读形式自发行的组织本次活动 ### 活动目的,意义和目标 - 提高积极性 - 提升技术力量,扩展大家视野 - 锻炼语言表达能力 - 促进社区的和谐、团结、共进 - 将ShenYu社区做的越来越大 ### 活动开展 - 活动分多期,先是挑选十二位组员进行为期12天的源码阅读,期间进行两次线上分享 - 为了提高大家的自觉性我们设立了惩罚制度,先交出500元/人给管理员,隔天的早上8点作业未提交,分享迟到者扣100元/次,提前请假者无需惩罚 - 每人根据每天阅读的内容,以文字形式写到各自的作业提交区 ### 活动负责人以及主要参与者 #### 负责人 - 崔,kimming,猫大人 #### 主要参与者 - ShenYu 社区组员 <file_sep>--- title: k8s Deployment keywords: Apache ShenYu Deployment description: k8s Deployment --- This article introduces the use of `k8s` to deploy the `Apache ShenYu` gateway. <file_sep>--- title: Flow Control keywords: flow-control description: flow-control --- ShenYu gateway realizes flow control through plugins, selectors and rules. For related data structure, please refer to the previous [Apache ShenYu Admin Database Design](../database-design) . ### Plugin In Apache ShenYu Admin System, each plugin uses Handle (JSON format) fields to represent different processing, and the plugin processing is used to manage and edit the custom processing fields in the JSON. The main purpose of this feature is to enable plugins to handle templated configurations. ### Selector And Rule Selector and rule are the most soul of Apache ShenYu Gateway. Master it and you can manage any traffic. A plugin has multiple selectors, and one selector corresponds to multiple rules. The selector is the first level filter of traffic, and the rule is the final filter. For a plugin, we want to meet the traffic criteria based on our configuration before the plugin will be executed. Selectors and rules are designed to allow traffic to perform what we want under certain conditions. The rules need to be understood first. The execution logic of plugin, selector and rule is as follows. When the traffic enters into ShenYu gateway, it will first judge whether there is a corresponding plugin and whether the plugin is turned on. Then determine whether the traffic matches the selector of the plugin. It then determines whether the traffic matches the rules of the selector. If the request traffic meets the matching criteria, the plugin will be executed. Otherwise, the plugin will not be executed. Process the next one. ShenYu gateway is so through layers of screening to complete the flow control. <img src="/img/shenyu/dataSync/flow-control-en.png" width="40%" height="30%" /> <file_sep># Apache ShenYu Official Website ![Website Deploy](https://github.com/apache/incubator-shenyu-website/workflows/Website%20Deploy/badge.svg) This project keeps all sources used for building up Apache ShenYu official website which's served at <https://shenyu.apache.org/>. This site was compiled using [Hugo](https://gohugo.io/). ## Requirement * [node8+](https://nodejs.org/en/) * [hugo v0.55.5 extended.](https://github.com/gohugoio/hugo/releases/tag/v0.55.5) ## Run local server ```shell npm install npm run build hugo hugo serve --bind 0.0.0.0 --disableFastRender ``` Then you will see the site running on <http://localhost:1313>. ## Contributing * Create new branch * Commit and push changes to content (e.g. The `.md` file in `/content`). * Submit pull request to `main` branch ## License [Apache 2.0 License.](/LICENSE) <file_sep>--- draft: false title: "" description: "Apache ShenYu" --- <file_sep>--- title: "Community" description: "Apache ShenYu Community" subDesc: "API Gateway" sidebar: - title: 'Subscribe Email' link: 'subscribe-email' - title: 'Code Conduct' link: 'code-conduct' - title: 'Issue And Pull Request' link: 'issue-pr' - title: 'Contributor' link: 'contributor' - title: 'Committer' link: 'committer' - title: 'Release Guide' link: 'release' - title: 'Vote Committer' link: 'vote-committer' - title: 'Two-Factor Authentication' link: '2fa' - title: 'Sign ICLA' link: 'icla' - title: 'Contributor List' link: 'contributor-list' - title: 'User Registration' link: 'user-list' # draft: true --- <file_sep>[slogan] title = "Apache ShenYu (Incubating)" description = "高性能,多协议,易扩展,响应式的API网关" quick_start_text = "快速开始" quick_start_link = "/zh/projects/shenyu/overview" github_link = "https://github.com/apache/incubator-shenyu" [[feature]] title = "开放" description = "技术栈全面开源共建,保持社区中立,兼容社区,兼容开源生态,随时欢迎参与各种贡献" img = "img/home/dromara_open.png" [[feature]] title = "高性能" description = "高性能微服务API网关,经历过大规模场景的锤炼。流量配置动态化,性能极高,网关消耗在 1~2ms" img = "img/home/dromara_gateway.png" [[feature]] title = "插件化" description = "插件化设计思想,插件热插拔,易扩展。内置丰富的插件,支持鉴权、限流、熔断、防火墙等" img = "img/home/dromara_distributed_transaction.png" [[soul_description]] title = "架构设计" description = "高性能微服务API网关,兼容各种主流框架体系,支持热插拔,用户可以定制化开发,满足用户各种场景的现状和未来需求,经历过大规模场景的锤炼" img_width = "600px" [soul_features] title = "特性一览" img = "img/home/soul_features.png" img_width = "530px" [[soul_features_sub]] title = "丰富的协议" description = "支持 Dubbo,Tars,Spring-Cloud,gRPC。" img = "img/home/cd-cloud-native-architecture.png" position = "INIT" [[soul_features_sub]] title = "插件化" description = "插件化设计思想,插件热插拔,易扩展。" position = "TR" [[soul_features_sub]] title = "流控" description = "灵活的流量筛选,能满足各种流量控制。" position = "BL" [[soul_features_sub]] title = "内置插件" description = "内置丰富的插件支持,鉴权,限流,熔断,防火墙等。" position = "TL" [[soul_features_sub]] title = "高性能" description = "流量配置动态化,性能极高,网关消耗在 1~2ms。" position = "BR" [[soul_features_sub]] title = "集群部署" description = "支持集群部署,支持 A/B Test,蓝绿发布。" position = "BR" [subscription] title = "希望订阅最新的 ShenYu 消息?" button = "订阅" <file_sep>--- title: 贡献者 description: 贡献者列表 author: "xiaoyu" loadContributorList: true categories: "Apache ShenYu" tags: ["ContributorList"] --- 目前已经有上百位小伙伴为Apache ShenYu 贡献了文章和代码,非常感谢他们! 想要参与贡献,可以直接去[Apache ShenYu](https://github.com/apache/incubator-shenyu/),并fork。 <file_sep>--- layout: singlepage title: "Awesome Apache ShenYu" --- ## 目录 - [已知用户 Known Users](#knownusers) - [贡献 Contributors](#contributors) - [用户登记 Registration](#registration) ## 已知用户{#knownusers} 此处会列出我们已知的在生产环境使用了 ShenYu 全部或者部分组件的公司或组织。以下排名不分先后: <img alt="yy" src="/img/users/yy_logo.png" width="150" height="60" /> <img alt="mihoyo" src="/img/users/mihayo_logo.png" width="150" height="60" /> <img alt="shansong" src="/img/users/shansong_logo.png" width="150" height="60" /> <img alt="sibu group" src="https://yu199195.github.io/images/soul/users/sibu.jpg" height="60" /> <img alt="cheyipai" src="/img/users/cheyipai_logo.jpg" width="120" height="60" /> <img alt="caibeike" src="/img/users/caibeike_logo.png" height="60" /> <img alt="fangfutong" src="https://yu199195.github.io/images/soul/users/fangfutong.png" height="60" /> <img alt="chinaTelecom" src="/img/users/china_telecom_logo.png" height="60" /> <img alt="kaipuyun" src="https://yu199195.github.io/images/soul/users/kaipuyun.png" height="60" /> <img alt="songda" src="https://yu199195.github.io/images/soul/users/songda.png" height="60" /> <img alt="aoyou" src="https://yu199195.github.io/images/soul/users/aoyou.jpg" height="60" /> <img alt="caomao" src="https://yu199195.github.io/images/soul/users/caomao.jpg" height="60" /> <img alt="zuyun" src="https://yu199195.github.io/images/soul/users/zuyun.jpg" height="60" /> <img alt="hezhi" src="https://yu199195.github.io/images/soul/users/hezhi.png" height="60" /> <img alt="qidianyun" src="https://yu199195.github.io/images/soul/users/qidianyun.jpg" height="60" /> <img alt="wanwei" src="/img/users/wanwei_logo.png" height="60" /> <img alt="sijibao" src="/img/users/sijibao_logo.png" height="60" /> <img alt="haokangzaijia" src="https://yu199195.github.io/images/soul/users/haokangzaijia.jpg" height="60" /> <img alt="caissa" src="https://yu199195.github.io/images/soul/users/caissa.jpg" height="60" /> <img alt="deepBule" src="/img/users/deepblue_logo.png" height="60" /> <img alt="huaxiaershouche" src="/img/users/huaxiaershouche_logo.png" height="60" /> <img alt="mingLAMP" src="https://yu199195.github.io/images/soul/users/minglamp.jpeg" height="60" /> <img alt="webuy" src="https://yu199195.github.io/images/soul/users/webuy.jpg" height="60" /> <img alt="casstime" src="/img/users/cass.png" height="60"/> <img alt="jiangsuyonggang" src="https://yu199195.github.io/images/soul/users/jiangsuyonggang.jpg" height="60" /> <img alt="kk group" src="https://yu199195.github.io/images/soul/users/keking.png" height="60" /> <img alt="songguo" src="/img/users/songguo.png" height="60" /> <img alt="lianlian" src="/img/users/lianlian.png" height="60" /> <img alt="dasouche" src="/img/users/dasouche.png" height="60" /> <img alt="weimai" src="/img/users/weimai.png" height="60" /> ## 贡献{#contributors} 目前已经有上百位小伙伴为 ShenYu 贡献了文章和代码,非常感谢他们! > 本列表每月初更新,排名不分先后,按 Github 用户 ID 首字母排序。 <table> <tbody> <tr> <td><a href="https://github.com/0x12FD16B" target="_blank"><img src="https://avatars0.githubusercontent.com/u/8335369?v=4&s=40" height="20" /> @0x12FD16B</a></td> <td><a href="https://github.com/241600489" target="_blank"><img src="https://avatars1.githubusercontent.com/u/24708262?v=4&s=40" height="20" /> @241600489</a></td> <td><a href="https://github.com/50133142" target="_blank"><img src="https://avatars2.githubusercontent.com/u/42038247?v=4&s=40" height="20" /> @50133142</a></td> <td><a href="https://github.com/Andy-86" target="_blank"><img src="https://avatars3.githubusercontent.com/u/15087636?v=4&s=40" height="20" /> @Andy-86</a></td> <td><a href="https://github.com/BetterWp" target="_blank"><img src="https://avatars4.githubusercontent.com/u/46946568?v=4&s=40" height="20" /> @BetterWp</a></td> </tr> <tr> <td><a href="https://github.com/CCLooMi" target="_blank"><img src="https://avatars0.githubusercontent.com/u/8596174?v=4&s=40" height="20" /> @CCLooMi</a></td> <td><a href="https://github.com/DaveModl" target="_blank"><img src="https://avatars1.githubusercontent.com/u/47873192?v=4&s=40" height="20" /> @DaveModl</a></td> <td><a href="https://github.com/FocusZhouGD" target="_blank"><img src="https://avatars2.githubusercontent.com/u/50652528?v=4&s=40" height="20" /> @FocusZhouGD</a></td> <td><a href="https://github.com/Gxz-NGU" target="_blank"><img src="https://avatars3.githubusercontent.com/u/19837732?v=4&s=40" height="20" /> @Gxz-NGU</a></td> <td><a href="https://github.com/HJ43" target="_blank"><img src="https://avatars4.githubusercontent.com/u/24913177?v=4&s=40" height="20" /> @HJ43</a></td> </tr> <tr> <td><a href="https://github.com/HoldDie" target="_blank"><img src="https://avatars0.githubusercontent.com/u/22816271?v=4&s=40" height="20" /> @HoldDie</a></td> <td><a href="https://github.com/JiaRG" target="_blank"><img src="https://avatars1.githubusercontent.com/u/31472350?v=4&s=40" height="20" /> @JiaRG</a></td> <td><a href="https://github.com/KevinClair" target="_blank"><img src="https://avatars2.githubusercontent.com/u/37257651?v=4&s=40" height="20" /> @KevinClair</a></td> <td><a href="https://github.com/Licoy" target="_blank"><img src="https://avatars3.githubusercontent.com/u/20410697?v=4&s=40" height="20" /> @Licoy</a></td> <td><a href="https://github.com/Lin1nGithub" target="_blank"><img src="https://avatars4.githubusercontent.com/u/25782561?v=4&s=40" height="20" /> @Lin1nGithub</a></td> </tr> <tr> <td><a href="https://github.com/LingCoder" target="_blank"><img src="https://avatars0.githubusercontent.com/u/34231795?v=4&s=40" height="20" /> @LingCoder</a></td> <td><a href="https://github.com/LiveOrange" target="_blank"><img src="https://avatars1.githubusercontent.com/u/20442302?v=4&s=40" height="20" /> @LiveOrange</a></td> <td><a href="https://github.com/MarcusJiang1306" target="_blank"><img src="https://avatars2.githubusercontent.com/u/48646601?v=4&s=40" height="20" /> @MarcusJiang1306</a></td> <td><a href="https://github.com/NemoIntellego" target="_blank"><img src="https://avatars3.githubusercontent.com/u/41360186?v=4&s=40" height="20" /> @NemoIntellego</a></td> <td><a href="https://github.com/NohnJnow" target="_blank"><img src="https://avatars4.githubusercontent.com/u/27010971?v=4&s=40" height="20" /> @NohnJnow</a></td> </tr> <tr> <td><a href="https://github.com/Redick01" target="_blank"><img src="https://avatars0.githubusercontent.com/u/15903214?v=4&s=40" height="20" /> @Redick01</a></td> <td><a href="https://github.com/SaberSola" target="_blank"><img src="https://avatars1.githubusercontent.com/u/24998393?v=4&s=40" height="20" /> @SaberSola</a></td> <td><a href="https://github.com/Severezh" target="_blank"><img src="https://avatars2.githubusercontent.com/u/12019307?v=4&s=40" height="20" /> @Severezh</a></td> <td><a href="https://github.com/Silencesk" target="_blank"><img src="https://avatars3.githubusercontent.com/u/4735494?v=4&s=40" height="20" /> @Silencesk</a></td> <td><a href="https://github.com/SteNicholas" target="_blank"><img src="https://avatars4.githubusercontent.com/u/10048174?v=4&s=40" height="20" /> @SteNicholas</a></td> </tr> <tr> <td><a href="https://github.com/Technoboy-" target="_blank"><img src="https://avatars0.githubusercontent.com/u/6297296?v=4&s=40" height="20" /> @Technoboy-</a></td> <td><a href="https://github.com/Trafalgar-YuI" target="_blank"><img src="https://avatars1.githubusercontent.com/u/13451528?v=4&s=40" height="20" /> @Trafalgar-YuI</a></td> <td><a href="https://github.com/UniverseInHeart" target="_blank"><img src="https://avatars2.githubusercontent.com/u/25877082?v=4&s=40" height="20" /> @UniverseInHeart</a></td> <td><a href="https://github.com/ViJayian" target="_blank"><img src="https://avatars3.githubusercontent.com/u/24708291?v=4&s=40" height="20" /> @ViJayian</a></td> <td><a href="https://github.com/Wincher" target="_blank"><img src="https://avatars4.githubusercontent.com/u/9314620?v=4&s=40" height="20" /> @Wincher</a></td> </tr> <tr> <td><a href="https://github.com/YarNeCn" target="_blank"><img src="https://avatars0.githubusercontent.com/u/20961044?v=4&s=40" height="20" /> @YarNeCn</a></td> <td><a href="https://github.com/Yejiajun" target="_blank"><img src="https://avatars1.githubusercontent.com/u/20715629?v=4&s=40" height="20" /> @Yejiajun</a></td> <td><a href="https://github.com/Zhoutzzz" target="_blank"><img src="https://avatars2.githubusercontent.com/u/42396616?v=4&s=40" height="20" /> @Zhoutzzz</a></td> <td><a href="https://github.com/abysscat-yj" target="_blank"><img src="https://avatars3.githubusercontent.com/u/33748845?v=4&s=40" height="20" /> @abysscat-yj</a></td> <td><a href="https://github.com/augfool" target="_blank"><img src="https://avatars4.githubusercontent.com/u/7943753?v=4&s=40" height="20" /> @augfool</a></td> </tr> <tr> <td><a href="https://github.com/bigwillc" target="_blank"><img src="https://avatars0.githubusercontent.com/u/35070155?v=4&s=40" height="20" /> @bigwillc</a></td> <td><a href="https://github.com/bitkylin" target="_blank"><img src="https://avatars1.githubusercontent.com/u/13912098?v=4&s=40" height="20" /> @bitkylin</a></td> <td><a href="https://github.com/bobzhanggmail" target="_blank"><img src="https://avatars2.githubusercontent.com/u/9858448?v=4&s=40" height="20" /> @bobzhanggmail</a></td> <td><a href="https://github.com/branchen" target="_blank"><img src="https://avatars3.githubusercontent.com/u/36290790?v=4&s=40" height="20" /> @branchen</a></td> <td><a href="https://github.com/candyYu" target="_blank"><img src="https://avatars4.githubusercontent.com/u/7844118?v=4&s=40" height="20" /> @candyYu</a></td> </tr> <tr> <td><a href="https://github.com/cchenxi" target="_blank"><img src="https://avatars0.githubusercontent.com/u/5698243?v=4&s=40" height="20" /> @cchenxi</a></td> <td><a href="https://github.com/charlesgongC" target="_blank"><img src="https://avatars1.githubusercontent.com/u/46913749?v=4&s=40" height="20" /> @charlesgongC</a></td> <td><a href="https://github.com/cherlas" target="_blank"><img src="https://avatars2.githubusercontent.com/u/15061972?v=4&s=40" height="20" /> @cherlas</a></td> <td><a href="https://github.com/cmj167" target="_blank"><img src="https://avatars3.githubusercontent.com/u/6840519?v=4&s=40" height="20" /> @cmj167</a></td> <td><a href="https://github.com/cocoZwwang" target="_blank"><img src="https://avatars4.githubusercontent.com/u/27925568?v=4&s=40" height="20" /> @cocoZwwang</a></td> </tr> <tr> <td><a href="https://github.com/coderlmm" target="_blank"><img src="https://avatars0.githubusercontent.com/u/21699517?v=4&s=40" height="20" /> @coderlmm</a></td> <td><a href="https://github.com/cottom" target="_blank"><img src="https://avatars1.githubusercontent.com/u/11937539?v=4&s=40" height="20" /> @cottom</a></td> <td><a href="https://github.com/cutieagain" target="_blank"><img src="https://avatars2.githubusercontent.com/u/5390200?v=4&s=40" height="20" /> @cutieagain</a></td> <td><a href="https://github.com/cxc222" target="_blank"><img src="https://avatars3.githubusercontent.com/u/2092566?v=4&s=40" height="20" /> @cxc222</a></td> <td><a href="https://github.com/dengliming" target="_blank"><img src="https://avatars4.githubusercontent.com/u/7796156?v=4&s=40" height="20" /> @dengliming</a></td> </tr> <tr> <td><a href="https://github.com/dependabot[bot]" target="_blank"><img src="https://avatars0.githubusercontent.com/in/29110?v=4&s=40" height="20" /> @dependabot[bot]</a></td> <td><a href="https://github.com/dmsolr" target="_blank"><img src="https://avatars1.githubusercontent.com/u/29735230?v=4&s=40" height="20" /> @dmsolr</a></td> <td><a href="https://github.com/en-o" target="_blank"><img src="https://avatars2.githubusercontent.com/u/45027672?v=4&s=40" height="20" /> @en-o</a></td> <td><a href="https://github.com/evasnowind" target="_blank"><img src="https://avatars3.githubusercontent.com/u/2696709?v=4&s=40" height="20" /> @evasnowind</a></td> <td><a href="https://github.com/fcwalker" target="_blank"><img src="https://avatars4.githubusercontent.com/u/27950366?v=4&s=40" height="20" /> @fcwalker</a></td> </tr> <tr> <td><a href="https://github.com/feixue2008" target="_blank"><img src="https://avatars0.githubusercontent.com/u/43638460?v=4&s=40" height="20" /> @feixue2008</a></td> <td><a href="https://github.com/fengzhenbing" target="_blank"><img src="https://avatars1.githubusercontent.com/u/4169359?v=4&s=40" height="20" /> @fengzhenbing</a></td> <td><a href="https://github.com/fightingting" target="_blank"><img src="https://avatars2.githubusercontent.com/u/31699402?v=4&s=40" height="20" /> @fightingting</a></td> <td><a href="https://github.com/funpad" target="_blank"><img src="https://avatars3.githubusercontent.com/u/9130564?v=4&s=40" height="20" /> @funpad</a></td> <td><a href="https://github.com/guanyushen" target="_blank"><img src="https://avatars4.githubusercontent.com/u/19588010?v=4&s=40" height="20" /> @guanyushen</a></td> </tr> <tr> <td><a href="https://github.com/hebaceous" target="_blank"><img src="https://avatars0.githubusercontent.com/u/6941544?v=4&s=40" height="20" /> @hebaceous</a></td> <td><a href="https://github.com/hellboy0621" target="_blank"><img src="https://avatars1.githubusercontent.com/u/72702359?v=4&s=40" height="20" /> @hellboy0621</a></td> <td><a href="https://github.com/huangxfchn" target="_blank"><img src="https://avatars2.githubusercontent.com/u/17267069?v=4&s=40" height="20" /> @huangxfchn</a></td> <td><a href="https://github.com/hyuk-sudo" target="_blank"><img src="https://avatars3.githubusercontent.com/u/22049351?v=4&s=40" height="20" /> @hyuk-sudo</a></td> <td><a href="https://github.com/ihenjoy" target="_blank"><img src="https://avatars4.githubusercontent.com/u/6481696?v=4&s=40" height="20" /> @ihenjoy</a></td> </tr> <tr> <td><a href="https://github.com/iqinning" target="_blank"><img src="https://avatars0.githubusercontent.com/u/18241433?v=4&s=40" height="20" /> @iqinning</a></td> <td><a href="https://github.com/itdachaoge" target="_blank"><img src="https://avatars1.githubusercontent.com/u/13128584?v=4&s=40" height="20" /> @itdachaoge</a></td> <td><a href="https://github.com/itmiwang" target="_blank"><img src="https://avatars2.githubusercontent.com/u/24636850?v=4&s=40" height="20" /> @itmiwang</a></td> <td><a href="https://github.com/jeesk" target="_blank"><img src="https://avatars3.githubusercontent.com/u/27076817?v=4&s=40" height="20" /> @jeesk</a></td> <td><a href="https://github.com/jjnnzb" target="_blank"><img src="https://avatars4.githubusercontent.com/u/58833386?v=4&s=40" height="20" /> @jjnnzb</a></td> </tr> <tr> <td><a href="https://github.com/jmwasky" target="_blank"><img src="https://avatars0.githubusercontent.com/u/3257442?v=4&s=40" height="20" /> @jmwasky</a></td> <td><a href="https://github.com/jnzhouhao" target="_blank"><img src="https://avatars1.githubusercontent.com/u/17978824?v=4&s=40" height="20" /> @jnzhouhao</a></td> <td><a href="https://github.com/kennhua" target="_blank"><img src="https://avatars2.githubusercontent.com/u/16517580?v=4&s=40" height="20" /> @kennhua</a></td> <td><a href="https://github.com/keru-s" target="_blank"><img src="https://avatars3.githubusercontent.com/u/24741256?v=4&s=40" height="20" /> @keru-s</a></td> <td><a href="https://github.com/klboke" target="_blank"><img src="https://avatars4.githubusercontent.com/u/18591662?v=4&s=40" height="20" /> @klboke</a></td> </tr> <tr> <td><a href="https://github.com/kminjava" target="_blank"><img src="https://avatars0.githubusercontent.com/u/35832954?v=4&s=40" height="20" /> @kminjava</a></td> <td><a href="https://github.com/lahmXu" target="_blank"><img src="https://avatars1.githubusercontent.com/u/31627887?v=4&s=40" height="20" /> @lahmXu</a></td> <td><a href="https://github.com/liuxx-u" target="_blank"><img src="https://avatars2.githubusercontent.com/u/7148259?v=4&s=40" height="20" /> @liuxx-u</a></td> <td><a href="https://github.com/lmhmhl" target="_blank"><img src="https://avatars3.githubusercontent.com/u/24718258?v=4&s=40" height="20" /> @lmhmhl</a></td> <td><a href="https://github.com/lw1243925457" target="_blank"><img src="https://avatars4.githubusercontent.com/u/11513436?v=4&s=40" height="20" /> @lw1243925457</a></td> </tr> <tr> <td><a href="https://github.com/lxl910128" target="_blank"><img src="https://avatars0.githubusercontent.com/u/8736745?v=4&s=40" height="20" /> @lxl910128</a></td> <td><a href="https://github.com/magicalxiaochen" target="_blank"><img src="https://avatars1.githubusercontent.com/u/54343840?v=4&s=40" height="20" /> @magicalxiaochen</a></td> <td><a href="https://github.com/marina432" target="_blank"><img src="https://avatars2.githubusercontent.com/u/16896822?v=4&s=40" height="20" /> @marina432</a></td> <td><a href="https://github.com/mcnultyboy" target="_blank"><img src="https://avatars3.githubusercontent.com/u/36916593?v=4&s=40" height="20" /> @mcnultyboy</a></td> <td><a href="https://github.com/midnight2104" target="_blank"><img src="https://avatars4.githubusercontent.com/u/13334620?v=4&s=40" height="20" /> @midnight2104</a></td> </tr> <tr> <td><a href="https://github.com/nuo-promise" target="_blank"><img src="https://avatars0.githubusercontent.com/u/46160170?v=4&s=40" height="20" /> @nuo-promise</a></td> <td><a href="https://github.com/onlyonezhongjinhui" target="_blank"><img src="https://avatars1.githubusercontent.com/u/19932240?v=4&s=40" height="20" /> @onlyonezhongjinhui</a></td> <td><a href="https://github.com/operaxxx" target="_blank"><img src="https://avatars2.githubusercontent.com/u/8800287?v=4&s=40" height="20" /> @operaxxx</a></td> <td><a href="https://github.com/patrickWuP" target="_blank"><img src="https://avatars3.githubusercontent.com/u/14297099?v=4&s=40" height="20" /> @patrickWuP</a></td> <td><a href="https://github.com/peiht" target="_blank"><img src="https://avatars4.githubusercontent.com/u/30573549?v=4&s=40" height="20" /> @peiht</a></td> </tr> <tr> <td><a href="https://github.com/plutokaito" target="_blank"><img src="https://avatars0.githubusercontent.com/u/7955473?v=4&s=40" height="20" /> @plutokaito</a></td> <td><a href="https://github.com/qdlake" target="_blank"><img src="https://avatars1.githubusercontent.com/u/1879819?v=4&s=40" height="20" /> @qdlake</a></td> <td><a href="https://github.com/qixiaobo" target="_blank"><img src="https://avatars2.githubusercontent.com/u/2881751?v=4&s=40" height="20" /> @qixiaobo</a></td> <td><a href="https://github.com/rockpig" target="_blank"><img src="https://avatars3.githubusercontent.com/u/16386766?v=4&s=40" height="20" /> @rockpig</a></td> <td><a href="https://github.com/sakiila" target="_blank"><img src="https://avatars4.githubusercontent.com/u/36431432?v=4&s=40" height="20" /> @sakiila</a></td> </tr> <tr> <td><a href="https://github.com/sccauxupei" target="_blank"><img src="https://avatars0.githubusercontent.com/u/26787757?v=4&s=40" height="20" /> @sccauxupei</a></td> <td><a href="https://github.com/sherk7monster" target="_blank"><img src="https://avatars1.githubusercontent.com/u/67529171?v=4&s=40" height="20" /> @sherk7monster</a></td> <td><a href="https://github.com/shijie666" target="_blank"><img src="https://avatars2.githubusercontent.com/u/75319679?v=4&s=40" height="20" /> @shijie666</a></td> <td><a href="https://github.com/songyuequan" target="_blank"><img src="https://avatars3.githubusercontent.com/u/9369071?v=4&s=40" height="20" /> @songyuequan</a></td> <td><a href="https://github.com/strawberry-crisis" target="_blank"><img src="https://avatars4.githubusercontent.com/u/13709330?v=4&s=40" height="20" /> @strawberry-crisis</a></td> </tr> <tr> <td><a href="https://github.com/sydgeek" target="_blank"><img src="https://avatars0.githubusercontent.com/u/31606195?v=4&s=40" height="20" /> @sydgeek</a></td> <td><a href="https://github.com/tangtian8" target="_blank"><img src="https://avatars1.githubusercontent.com/u/44994904?v=4&s=40" height="20" /> @tangtian8</a></td> <td><a href="https://github.com/tuohai666" target="_blank"><img src="https://avatars2.githubusercontent.com/u/24643893?v=4&s=40" height="20" /> @tuohai666</a></td> <td><a href="https://github.com/tydhot" target="_blank"><img src="https://avatars3.githubusercontent.com/u/27889201?v=4&s=40" height="20" /> @tydhot</a></td> <td><a href="https://github.com/tyjwan" target="_blank"><img src="https://avatars4.githubusercontent.com/u/37010206?v=4&s=40" height="20" /> @tyjwan</a></td> </tr> <tr> <td><a href="https://github.com/wanglaomo" target="_blank"><img src="https://avatars0.githubusercontent.com/u/26642224?v=4&s=40" height="20" /> @wanglaomo</a></td> <td><a href="https://github.com/wilburBlog" target="_blank"><img src="https://avatars1.githubusercontent.com/u/32635377?v=4&s=40" height="20" /> @wilburBlog</a></td> <td><a href="https://github.com/wuliendan" target="_blank"><img src="https://avatars2.githubusercontent.com/u/18097150?v=4&s=40" height="20" /> @wuliendan</a></td> <td><a href="https://github.com/wuudongdong" target="_blank"><img src="https://avatars3.githubusercontent.com/u/74701398?v=4&s=40" height="20" /> @wuudongdong</a></td> <td><a href="https://github.com/wxxy20071547" target="_blank"><img src="https://avatars4.githubusercontent.com/u/16205279?v=4&s=40" height="20" /> @wxxy20071547</a></td> </tr> <tr> <td><a href="https://github.com/wyc192273" target="_blank"><img src="https://avatars0.githubusercontent.com/u/13832598?v=4&s=40" height="20" /> @wyc192273</a></td> <td><a href="https://github.com/xiangyang-gao" target="_blank"><img src="https://avatars1.githubusercontent.com/u/15973635?v=4&s=40" height="20" /> @xiangyang-gao</a></td> <td><a href="https://github.com/xiaoshen11" target="_blank"><img src="https://avatars2.githubusercontent.com/u/15319017?v=4&s=40" height="20" /> @xiaoshen11</a></td> <td><a href="https://github.com/xiaoshuanglee" target="_blank"><img src="https://avatars3.githubusercontent.com/u/34903552?v=4&s=40" height="20" /> @xiaoshuanglee</a></td> <td><a href="https://github.com/xuziyang" target="_blank"><img src="https://avatars4.githubusercontent.com/u/8465969?v=4&s=40" height="20" /> @xuziyang</a></td> </tr> <tr> <td><a href="https://github.com/xwzwmt" target="_blank"><img src="https://avatars0.githubusercontent.com/u/22116836?v=4&s=40" height="20" /> @xwzwmt</a></td> <td><a href="https://github.com/xxl115" target="_blank"><img src="https://avatars1.githubusercontent.com/u/11749025?v=4&s=40" height="20" /> @xxl115</a></td> <td><a href="https://github.com/yangxing9" target="_blank"><img src="https://avatars2.githubusercontent.com/u/69447169?v=4&s=40" height="20" /> @yangxing9</a></td> <td><a href="https://github.com/yiwenlong" target="_blank"><img src="https://avatars3.githubusercontent.com/u/9609929?v=4&s=40" height="20" /> @yiwenlong</a></td> <td><a href="https://github.com/yu199195" target="_blank"><img src="https://avatars4.githubusercontent.com/u/9673503?v=4&s=40" height="20" /> @yu199195</a></td> </tr> <tr> <td><a href="https://github.com/yzhuomaoy" target="_blank"><img src="https://avatars0.githubusercontent.com/u/1639012?v=4&s=40" height="20" /> @yzhuomaoy</a></td> <td><a href="https://github.com/zendwang" target="_blank"><img src="https://avatars1.githubusercontent.com/u/9959839?v=4&s=40" height="20" /> @zendwang</a></td> <td><a href="https://github.com/zhaozhengping" target="_blank"><img src="https://avatars2.githubusercontent.com/u/7185847?v=4&s=40" height="20" /> @zhaozhengping</a></td> <td><a href="https://github.com/zhoubin14524" target="_blank"><img src="https://avatars3.githubusercontent.com/u/16285170?v=4&s=40" height="20" /> @zhoubin14524</a></td> <td><a href="https://github.com/zhisheng17" target="_blank"><img src="https://avatars4.githubusercontent.com/u/10086212?v=4&s=40" height="20" /> @zhisheng17</a></td> </tr> </tbody> </table> 想要参与贡献,可以直接去[Apache ShenYu](https://github.com/apache/incubator-shenyu/),并fork。 ## 用户登记{#registration} 请登记告诉我们,方便我们更好地为您服务。 * [Apache ShenYu](https://github.com/apache/incubator-shenyu/issues/68) <file_sep># Links in footer [[links]] category = "Apache" link_arr = [ ["Foundation", "https://www.apache.org/"], ["GitHub Issue Tracker", "https://github.com/apache/incubator-shenyu/issues"], ["License", "https://www.apache.org/licenses/"], ["Security", "https://www.apache.org/security/"], ["Events", "http://www.apache.org/events/current-event"], ["Sponsorship", "http://www.apache.org/foundation/sponsorship.html"], ["Thanks", "http://www.apache.org/foundation/thanks.html"], ] [[links]] category = "Resources" link_arr = [ ["Github", 'https://github.com/apache/incubator-shenyu'], ["Documentation", '/projects/shenyu/overview/'], # ["Samples", 'https://github.com/apache/incubator-shenyu-guides'], ] [[links]] category = "Get Involved" link_arr = [ ["Feedback", 'https://github.com/apache/incubator-shenyu/issues/new'], ["Community","/community"], ["News","/news"], ["Awesome","/awesome"], ] [[links]] category = "Subscribe mailing list" link_arr = [ ["How to subscribe", '/community/subscribe-email/'], ["Subscribe Mail", 'mailto://<EMAIL>'], ["Mail Archive", 'https://lists.apache.org/list.html?<EMAIL>'], ] #[[links]] # category = "Ant Financial Open Source" # link_arr = [ # ["Ant Design", 'https://ant.design/'], # ["Egg", 'https://eggjs.org/'], # ["SQLFlow", 'https://sqlflow.org'], # ["More", 'https://tech.antfin.com/open-source'], # ] # qrcode [[qrcode]] img = "img/qrcode/WechatIMG127.jpeg" description = "Wechat Official Account" <file_sep>--- title: 权限管理 keywords: 权限 description: 权限管理详解 --- ## 说明 - 管理和控制经过 `Apache ShenYu` 网关的请求的权限。 - 生成的 `AK/SK` ,配合 `sign` 插件使用,实现基于`URI`级别的精准权限管控。 ## 使用教程 第一步,我们可以直接在 `基础配置` --> `认证管理` 新增一条认证信息 <img src="/img/shenyu/basicConfig/authorityManagement/auth_manages_add_zh.jpg" width="100%" height="70%" /> 第二步,配置这条认证信息 <img src="/img/shenyu/basicConfig/authorityManagement/auth_param_zh.jpg" width="50%" height="40%"/> - 应用名称:这个账号关联的应用名称,可手动填写或下拉选择(数据来自元数据管理中配置的应用名称) - 手机号:仅作为信息记录,<font color=red>在shenyu中无实际使用逻辑</font> - APP参数:当请求的context path与应用名称相同时,向header中添加该值,键为 `appParam`。 - 用户ID:给该用户取一个名字,仅作为信息记录,<font color=red>在shenyu中无实际使用逻辑</font> - 拓展信息:仅作为信息记录,<font color=red>在shenyu中无实际使用逻辑</font> - 路径认证:开启后,该账号仅允许访问以下配置的资源路径 - 资源路径:允许访问的资源路径,支持路径匹配,如 `/order/**` 点击确认后,生成一条认证信息,该信息包含 `AppKey` 和 `加密秘钥` ,即 `Sign` 插件中的 `AK/SK` `Sign`插件的详细使用说明请参考: [Sign插件](../sign-plugin). #### 路径操作 对已创建的认证信息,可以在认证信息列表的末尾进行 `路径操作` <img src="/img/shenyu/basicConfig/authorityManagement/auth_manage_modifyPath_zh.jpg" width="90%" height="80%"/> - 左侧为<font color=red>可配置</font>的路径列表,右侧为<font color=red>允许该账号访问</font>的路径列表 - 勾选资源路径,点击中间的 `>` 或 `<` 将勾选的数据移动到对应列表中 - 左侧可配置路径列表可在账号信息行末尾点击 `编辑`,在弹框中的 `资源路径` 中进行添加 <file_sep># Links in footer [[links]] category = "Apache" link_arr = [ ["Foundation", "https://www.apache.org/"], ["GitHub Issue Tracker", "https://github.com/apache/incubator-shenyu/issues"], ["License", "https://www.apache.org/licenses/"], ["Security", "https://www.apache.org/security/"], ["Events", "http://www.apache.org/events/current-event"], ["Sponsorship", "http://www.apache.org/foundation/sponsorship.html"], ["Thanks", "http://www.apache.org/foundation/thanks.html"], ] [[links]] category = "资源" link_arr = [ ["Github", 'https://github.com/apache/incubator-shenyu'], ["文档", '/zh/projects/shenyu/overview/'], # ["示例", 'https://github.com/apache/incubator-shenyu-guides'], ] [[links]] category = "参与进来" link_arr = [ ["反馈", 'https://github.com/apache/incubator-shenyu/issues/new'], ["社区","/zh/community"], ["新闻","/zh/news"], ] [[links]] category = "订阅邮件组" link_arr = [ ["如何订阅", '/zh/community/subscribe-email/'], ["订阅邮件", 'mailto://<EMAIL>'], ["邮件归档", 'https://lists.apache.org/list.html?<EMAIL>'], ] [[qrcode]] img = "img/qrcode/WechatIMG127.jpeg" description = "微信公众号" <file_sep>--- title: "Apache ShenYu(current)" version: "current" description: "This is an asynchronous, high-performance, cross-language, responsive API gateway." subDesc: "High-performance API Gateway" feature1Img: "/img/feature/feature_transpart.png" feature1Title: "Cross-language" feature1Desc: "Support for all languages" feature2Img: "/img/feature/feature_loadbalances.png" feature2Title: "More plugins" feature2Desc: "Authentication, current limit, fuse, firewall and other plugins" feature3Img: "/img/feature/feature_service.png" feature3Title: "Dynamic Config" feature3Desc: "All of the configuration rules can be adjusted at will, taking effect dynamically, without restarting" feature4Img: "/img/feature/feature_hogh.png" feature4Title: "Plugins hot-plug, easy to expand" feature4Desc: "Plugins hot - plug, easy to expand" feature5Img: "/img/feature/feature_runtime.png" feature5Title: "Support More Rpc and REST" feature5Desc: "Dubbo,Spring Cloud,HTTP REST,GRPC,Tars" feature6Img: "/img/feature/feature_maintenance.png" feature6Title: "High availability, high concurrency" feature6Desc: "Support cluster deployment" architectureImg: "/img/architecture/shenyu-framework.png" startUp: "Start up" github: "https://github.com/apache/incubator-shenyu" gitee: "" level: "main" weight: 1 # icon: "/img/logo/apache-shenyu.png" showIntroduce: true showFeature: true sidebar: - title: 'Overview' link: 'overview' - title: 'Design' sub: - title: 'Admin Database Design' link: 'database-design' - title: 'Data Synchronization' link: 'data-sync' - title: 'Application Client Access' link: 'register-center-design' - title: 'Flow Control' link: 'flow-control' - title: 'SPI Design' link: 'spi-design' - title: 'Deployment' sub: - title: 'Local Deployment' link: 'deployment-local' - title: 'Binary Packages Deployment' link: 'deployment-package' - title: 'Docker Deployment' link: 'deployment-docker' - title: 'Kubernetes Deployment' link: 'deployment-k8s' - title: 'Helm Deployment' link: 'deployment-helm' - title: 'Custom Deployment' link: 'deployment-custom' - title: 'Quick Start' sub: - title: 'Http Proxy' link: 'quick-start-http' - title: 'Dubbo Proxy' link: 'quick-start-dubbo' - title: 'Spring Cloud Proxy' link: 'quick-start-springcloud' - title: 'Sofa Proxy' link: 'quick-start-sofa' - title: 'gRPC Proxy' link: 'quick-start-grpc' - title: 'Tars Proxy' link: 'quick-start-tars' - title: 'Motan Proxy' link: 'quick-start-motan' - title: 'User Guide' sub: - title: 'Admin Usage' sub: - title: 'Plugin Config' link: 'plugin-handle-explanation' - title: 'Selector And Rule Config' link: 'selector-and-rule' - title: 'Dictionary Management' link: 'dictionary-management' - title: 'Authority Management' link: 'authority-management' - title: 'Property Config' sub: - title: 'Admin Property Config' link: 'admin-property-config' - title: 'Client Property Config' link: 'client-property-config' - title: 'Data Synchronization Config' link: 'use-data-sync' - title: 'Application Client Access Config' link: 'register-center-access' - title: 'Http Proxy' link: 'http-proxy' - title: 'Dubbo Proxy' link: 'dubbo-proxy' - title: 'Spring Cloud Proxy' link: 'spring-cloud-proxy' - title: 'Sofa Proxy' link: 'sofa-rpc-proxy' - title: 'gRPC Proxy' link: 'grpc-proxy' - title: 'Tars Proxy' link: 'tars-proxy' - title: 'Motan Proxy' link: 'motan-proxy' - title: 'Plugin Center' sub: - title: 'Http Handle' sub: - title: 'Rewrite Plugin' link: 'rewrite-plugin' - title: 'Redirect Plugin' link: 'redirect-plugin' - title: 'Request Plugin' link: 'request-plugin' - title: 'Context-path Plugin' link: 'context-path-plugin' - title: 'Param-mapping Plugin' link: 'param-mapping-plugin' - title: 'ModifyResponse Plugin' link: 'modify-response-plugin' - title: 'WebSocket Proxy' link: 'websocket-plugin' - title: 'RPC Proxy' sub: - title: 'Divide Plugin' link: 'divide-plugin' - title: 'Dubbo Plugin' link: 'dubbo-plugin' - title: 'Spring Cloud Plugin' link: 'spring-cloud-plugin' - title: 'Sofa Plugin' link: 'sofa-plugin' - title: 'gRPC Plugin' link: 'grpc-plugin' - title: 'Tars Plugin' link: 'tars-plugin' - title: 'Motan Plugin' link: 'motan-plugin' - title: 'Fault Tolerance' sub: - title: 'Hystrix Plugin' link: 'hystrix-plugin' - title: 'Sentinel Plugin' link: 'sentinel-plugin' - title: 'Resilience4j Plugin' link: 'resilience4j-plugin' - title: 'RateLimiter Plugin' link: 'rate-limiter-plugin' - title: 'Authority And Certification' sub: - title: 'Waf Plugin' link: 'waf-plugin' - title: 'Sign Plugin' link: 'sign-plugin' - title: 'JWT Plugin' link: 'jwt-plugin' - title: 'OAuth 2 Plugin' link: 'oauth2-plugin' - title: 'Observability' sub: - title: 'Monitor Plugin' link: 'monitor-plugin' - title: 'Logging Plugin' link: 'logging-plugin' - title: 'Developer Documentation' sub: - title: 'Custom Filter' link: 'custom-filter' - title: 'Custom Plugin' link: 'custom-plugin' - title: 'File Upload And Download' link: 'file-and-image' - title: 'Custom Parsing IP And Host' link: 'custom-parsing-ip-and-host' - title: 'Custom Result' link: 'custom-result' - title: 'Custom Sign Algorithm' link: 'custom-sign-algorithm' - title: 'Multilingual Http Client Access' link: 'developer-shenyu-client' - title: 'Thread Model' link: 'thread' - title: 'Shenyu Optimize' link: 'shenyu-optimize' - title: 'SPI' sub: - title: 'Custom Condition Match' link: 'custom-condition-match' - title: 'Release Notes' link: 'release-notes' - title: 'Download' link: 'download' # draft: true --- <file_sep>--- draft: false title: "Dromara" description: "Dromara is an organization dedicated to native solutions for the microservice cloud." --- <file_sep>--- title: helm部署 keywords: Apache ShenYu Deployment description: helm部署 --- 本文介绍使用 `helm` 来部署 `Apache ShenYu` 网关。 <file_sep>--- title: 插件 keywords: Apache ShenYu description: 对ShenYu网关中插件概念进行介绍 --- to do. <file_sep>--- author: "<NAME>" authorlink: "https://github.com/JooKS-me" date: 2021-08-20T11:00:00.000Z title: "ShenYu Context-Path插件源码分析" tags: ["Plugin", "ShenYu", "GateWay"] cover: "/img/activities/apache-open-shenyu-02.jpg" descripton: "ShenYu Context-Path插件源码分析" --- ## Demo跑起来 1. 启动ShenYu Admin 2. 启动ShenYu Bootstrap 3. 修改一下shenyu-examples-http(我们这里直接用shenyu的example) **在HttpTestController.java中,将类注解@RequestMapping的path值稍作修改**,改成`"/v1/test"`,如下图所示。 ![context-path-RequestMapping](/img/activities/code-analysis-context-path-plugin/context-path-RequestMapping.png) 4. 启动shenyu-examples-http 到这里,我们的服务就都起来了。 然后我们请求接口 `http://localhost:9195/http/test/findByUserId?userId=1001` ,结果返回404。 ![context-path-404](/img/activities/code-analysis-context-path-plugin/context-path-404.png) 我们分析一下网关处理这个请求的过程的流程: 1. 请求网关的 `/http/test/findByUserId` 2. 经过各种插件的处理。。。 3. 然后到了context_path插件。 我们可以在admin里面发现有这样一条规则,将contextPath设置为`/http`,addPrefix设置为空。实际上,这样的设置使得shenyu在向目标服务发送请求前,将请求路径中的`/http`替换成了`空`。(详细内容见后续的源码分析) ![context-path-rules-without-prefix](/img/activities/code-analysis-context-path-plugin/context-path-rules-without-prefix.png) 那么你现在应该知道了,我们只需要在addPrefix的空格里填上`/v1`就能正确地请求到目标服务了! ![context-path-rules-with-prefix](/img/activities/code-analysis-context-path-plugin/context-path-rules-with-prefix.png) ![context-path-success](/img/activities/code-analysis-context-path-plugin/context-path-success.png) ## 分析源码 首先,看`ContextPathPlugin#doExecute`方法,这是这个插件的核心。 ```java protected Mono<Void> doExecute(final ServerWebExchange exchange, final ShenyuPluginChain chain, final SelectorData selector, final RuleData rule) { ... // 1. 从JVM缓存中取得contextMappingHandle ContextMappingHandle contextMappingHandle = ContextPathPluginDataHandler.CACHED_HANDLE.get().obtainHandle(CacheKeyUtils.INST.getKey(rule)); ... // 2. 根据contextMappingHandle设置shenyu上下文 buildContextPath(shenyuContext, contextMappingHandle); return chain.execute(exchange); } ``` 1. 从JVM缓存中取得`contextMappingHandle` 这里的`contextMappingHandle`是`ContextMappingHandle`类的实例,里面有两个成员变量:`contextPath`和`addPrefix` 这两个变量在之前Admin里面的Rules表单里有出现过,是在数据同步的时候更新的。 2. 根据contextMappingHandle设置shenyu上下文 下面是`ContextPathPlugin#buildContextPath`方法的源代码 ```java private void buildContextPath(final ShenyuContext context, final ContextMappingHandle handle) { String realURI = ""; // 1. 设置shenyu的context path,根据contextPath的长度将真实URI的前缀去掉 if (StringUtils.isNoneBlank(handle.getContextPath())) { context.setContextPath(handle.getContextPath()); context.setModule(handle.getContextPath()); realURI = context.getPath().substring(handle.getContextPath().length()); } // 加上前缀 if (StringUtils.isNoneBlank(handle.getAddPrefix())) { if (StringUtils.isNotBlank(realURI)) { realURI = handle.getAddPrefix() + realURI; } else { realURI = handle.getAddPrefix() + context.getPath(); } } context.setRealUrl(realURI); } ``` - 设置shenyu的context path,**根据contextPath的长度将真实URI的前缀去掉** 你可能会有疑问,**这里所谓的「根据contextPath的长度」会不会有问题呢?** 实际上这样的判断是没有问题的,因为请求在被Selector和Rules匹配到之后,才会被插件处理。所以在设置好Selector和Rules的前提下,是完全可以满足转换特定contextPath的需求的。 然后,`ContextPathPlugin`类还有一个比较重要的方法`skip`,下面展示了部分代码。我们可以发现:**如果是对RPC服务的调用,就会直接跳过context_path插件。** ```java public Boolean skip(final ServerWebExchange exchange) { ... return Objects.equals(rpcType, RpcTypeEnum.DUBBO.getName()) || Objects.equals(rpcType, RpcTypeEnum.GRPC.getName()) || Objects.equals(rpcType, RpcTypeEnum.TARS.getName()) || Objects.equals(rpcType, RpcTypeEnum.MOTAN.getName()) || Objects.equals(rpcType, RpcTypeEnum.SOFA.getName()); } ``` 最后,context_path插件还有另一个类`ContextPathPluginDataHandler`。这个类的作用是订阅插件的数据,当插件配置被修改、删除、增加时,就往JVM缓存里面修改、删除、新增数据。 <file_sep>--- title: "社区" description: "Apache ShenYu社区" subDesc: "高性能微服务API网关" sidebar: - title: '订阅邮件' link: 'subscribe-email' - title: '代码规范' link: 'code-conduct' - title: 'Issue与PR规范' link: 'issue-pr' - title: 'Contributor指南' link: 'contributor' - title: 'Committer指南' link: 'committer' - title: '发布指南' link: 'release' - title: '提名Committer' link: 'vote-committer' - title: '开通双因素认证' link: '2fa' - title: '签署ICLA' link: 'icla' - title: 'Contributor列表' link: 'contributor-list' - title: '用户登记' link: 'user-list' # draft: true ---<file_sep>--- title: "Apache ShenYu(2.3.0)" version: "2.3.0" description: "异步的,高性能的,跨语言的,响应式的API网关。" subDesc: "高性能微服务API网关" architectureImg: "/img/architecture/soul-framework.png" level: "main" weight: 2 icon: "/img/logo/soul.png" showIntroduce: true showFeature: true sidebar: - title: 'Soul 介绍' link: 'overview' - title: '团队介绍' link: 'team' - title: '设计文档' sub: - title: '数据库设计' link: 'database-design' - title: '配置流程设计' link: 'config' - title: '数据同步原理设计' link: 'data-sync' - title: '元数据设计' link: 'meta-data' - title: 'Admin使用文档' sub: - title: '字典配置' link: 'dictionary-management' - title: '插件配置模板' link: 'plugin-handle-explanation' - title: '选择器规则详解' link: 'selector-and-rule' - title: '用户文档' sub: - title: '搭建Soul网关环境' link: 'soul-set-up' - title: 'Http代理' link: 'http-proxy' - title: 'Dubbo代理' link: 'dubbo-proxy' - title: 'SpringCloud代理' link: 'spring-cloud-proxy' - title: 'Sofa代理' link: 'sofa-rpc-proxy' - title: '数据同步策略' link: 'use-data-sync' - title: '注册中心' sub: - title: '设计' link: 'register-center-design' - title: '接入' link: 'register-center-access' - title: '快速开始' sub: - title: 'Dubbo' link: 'quick-start-dubbo' - title: 'Http' link: 'quick-start-http' - title: 'Grpc' link: 'quick-start-grpc' - title: 'SpringCloud' link: 'quick-start-springcloud' - title: 'Sofa' link: 'quick-start-sofa' - title: 'Tars' link: 'quick-start-tars' - title: '插件集合' sub: - title: 'Divide插件' link: 'divide-plugin' - title: 'Dubbo插件' link: 'dubbo-plugin' - title: 'Spring Cloud插件' link: 'spring-cloud-plugin' - title: 'Sofa插件' link: 'sofa-plugin' - title: 'RateLimiter插件' link: 'rate-limiter-plugin' - title: 'Hystrix插件' link: 'hystrix-plugin' - title: 'Sentinel插件' link: 'sentinel-plugin' - title: 'Resilience4j插件' link: 'resilience4j-plugin' - title: 'Monitor插件' link: 'monitor-plugin' - title: 'Waf插件' link: 'waf-plugin' - title: 'Sign插件' link: 'sign-plugin' - title: 'Rewriter插件' link: 'rewrite-plugin' - title: 'Websocket支持' link: 'websocket-plugin' - title: 'Context-path插件' link: 'context-path-plugin' - title: 'Redirect插件' link: 'redirect-plugin' - title: 'Logging插件' link: 'logging-plugin' - title: '开发者文档' sub: - title: '自定义filter' link: 'custom-filter' - title: '自定义插件' link: 'custom-plugin' - title: '文件上传下载' link: 'file-and-image' - title: '自定义解析IP与host' link: 'custom-parsing-ip-and-host' - title: '自定义返回结果' link: 'custom-result' - title: '自定义签名插件算法与验证' link: 'custom-sign-algorithm' - title: '多语言http客户端接入' link: 'developer-soul-client' - title: '线程模型' link: 'thread' - title: 'soul调优' link: 'soul-optimize' - title: '文档下载' link: 'download' # draft: true --- <file_sep>[slogan] title = "<NAME> (Incubating)" description = "High-performance, multi-protocol, extensible, responsive API Gateway" quick_start_text = "Quick Start" quick_start_link = "/projects/shenyu/overview" github_link = "https://github.com/apache/incubator-shenyu" [[feature]] title = "Open" description = "The technology stack is fully open source construction, maintain the community neutrality, compatible with the community open source ecology, welcome to participate in various contributions at any time" img = "img/home/dromara_open.png" [[feature]] title = "High-Performance" description = "High-performance micro-service API gateway, experienced the temper of large-scale scenes.Dynamic flow configuration, high performance, gateway consumption is 1~2ms" img = "img/home/dromara_gateway.png" [[feature]] title = "Pluggable" description = "Plug-in design idea, plug-in hot plug, easy to expand.Built-in rich plugin support, authentication, limiting, fuse, firewall, etc" img = "img/home/dromara_distributed_transaction.png" [[soul_description]] title = "Architecture Diagram" description = "High-performance micro-service API gateway, compatible with a variety of mainstream framework systems, support hot plug, users can customize the development, meet the current situation and future needs of users in a variety of scenarios, experienced the temper of large-scale scenes" img_width = "600px" [soul_features] title = "Features" img = "img/home/soul_features.png" img_width = "530px" [[soul_features_sub]] title = "Rich protocols" description = "Supports Dubbo, Tars, Spring-Cloud, gRPC." img = "img/home/cd-cloud-native-architecture.png" position = "INIT" [[soul_features_sub]] title = "Pluggable" description = "Plug-in design idea, plug-in hot plug, easy to expand." position = "TR" [[soul_features_sub]] title = "Flow Control" description = "Flexible flow filtering to meet various flow control." position = "BL" [[soul_features_sub]] title = "Built-in Plug-ins" description = "Built-in rich plugin support, authentication, limiting, fuse, firewall, etc." position = "TL" [[soul_features_sub]] title = "High Performance" description = "Dynamic flow configuration, high performance, gateway consumption is 1~2ms." position = "BR" [[soul_features_sub]] title = "Cluster Deployment" description = "Support cluster deployment, A/B Test, blue-green release." position = "BR" [subscription] title = "Interested in receiving the latest ShenYu news?" button = "Subscribe" <file_sep>--- levels: - level: "网关" links: - "soul/overview/" - level: "分布式事务" links: - "hmily/overview/" - "raincat/overview/" - "myth/overview/" --- <file_sep>--- title: 配置流程介绍 keywords: Apache ShenYu description: 配置流程介绍 --- ## 说明 * 本篇是对 shenyu-admin 后台操作数据以后,同步到网关的流程介绍。 ## 使用 * 用户可以在 shenyu-admin 后台任意修改数据,并马上同步到网关的 jvm 内存中。 * 同步 ShenYu 的插件数据,选择器,规则数据,元数据,签名数据等等。 * 所有插件的选择器,规则都是动态配置,立即生效,不需要重启服务。 * 下面是数据流程图: ![](/img/shenyu/dataSync/plugin-data.png) ## 作用 * 用户所有的配置都可以动态的更新,任何修改不需要重启服务。 * 使用了本地缓存,在高并发的时候,提供高效的性能。 <file_sep>--- title: k8s部署 keywords: Apache ShenYu Deployment description: k8s部署 --- 本文介绍使用 `k8s` 来部署 `Apache ShenYu` 网关。 <file_sep>--- author: "xiaoyu" authorlink: "https://github.com/yu199195" date: 2020-12-27T15:00:00.000Z title: "Apache ShenYu Dream Code Book Club Introduction" tags: ["DreamCode", "Apache","GateWay"] cover: "/img/activities/apache-open-shenyu-01.jpg" descripton: "Apache ShenYu Dream Code Book Club Introduction" --- ![Apache ShenYu Dream Code Book Club Introduction](/img/shenyu/activite/shenyu-xmind.png) ### Apache ShenYu Dream Code Book Club(Apache ShenYu 2020 event introduction) - Date: Sunday, December 27, 2020 ### Activity background - In order to increase the enthusiasm of community participants, promote the construction of the Apache ShenYu community, exercise everyone's expressive ability and improve the core strength of technology, the community organized this event in the form of source code reading. ### Activity purpose, meaning and goal - Increase motivation - Improve technical strength and expand everyone's horizons - Exercise language skills - Promote the harmony, unity and progress of the community - Make the Apache ShenYu community bigger and bigger ### Activity development - The activity is divided into multiple phases. First, twelve members are selected for a 12-day source code reading, and two online sharing is carried out during the period. - In order to improve everyone's consciousness, we have set up a punishment system. First hand over 500 yuan to the administrator. If homework is not submitted at 8 am the next day, 100 yuan will be deducted for sharing latecomers. Those who ask for leave in advance do not need to be punished. - Each person writes to their homework submission area in text based on the content they read every day. ### Activity leader and main participants #### Principal - <NAME>, Xiaoyu #### The main participants - Apache ShenYu community member <file_sep>import { $$ } from './utils'; export default function () { if (!$$('.contributor-list')) { return; } fetch("https://api.github.com/repos/apache/incubator-shenyu/contributors?page=1&per_page=10000").then(function (response) { return response.json(); }).then(function (res) { let html = ""; if (res && Array.isArray(res)) { res.forEach((c, i) => { if (i % 5 === 0) { if (i > 0) { html += "</tr>" } html += "<tr>" } html += `<td><a href="${c.html_url}" target="_blank"><img src="${c.avatar_url}" height="20" /> @${c.login}</a></td>`; if (i === res.length - 1) { html += "</tr>" } }) } $$('.contributor-list')[0].innerHTML = html; }); }<file_sep>import { $$ } from './utils' import Particles from '../particles.min.js'; export default function() { if (!$$('.ss-project-card') || $$('.ss-project-card').length === 0) { return } $$('.ss-project-card')[0].classList.add('-selected'); $$('.feature-section')[0].classList.add('-display'); $$('.introduction-section')[0].classList.add('-display'); $$('.ss-project-card').forEach((project ,i) => { project.addEventListener('click', () => { $$('.ss-project-card').forEach(item=>{ item.classList.remove('-selected') }) $$('.introduction-section').forEach(item=>{ item.classList.remove('-display') }) $$('.feature-section').forEach(item=>{ item.classList.remove('-display') }) project.classList.add('-selected'); if($$('.introduction-section')[i].children && $$('.introduction-section')[i].children.length > 0){ $$('.introduction-section')[i].classList.add('-display'); } if($$('.feature-section')[i].children && $$('.feature-section')[i].children.length > 0){ $$('.feature-section')[i].classList.add('-display'); } }) }) Particles.init({ selector: '.particles_bg', maxParticles: 80, connectParticles: true, sizeVariations: 1, color: '#b1cef3', responsive: [ { breakpoint: 768, options: { maxParticles: 200, color: '#48F2E3', connectParticles: false } }, { breakpoint: 425, options: { maxParticles: 100, connectParticles: true } }, { breakpoint: 320, options: { maxParticles: 0 } } ] }); }<file_sep>--- title: Apache ShenYu Committer description: Apache shenyu-committer提交者指南 author: "xiaoyu" categories: "Apache ShenYu" tags: ["Committer"] date: 2019-04-09 cover: "/img/architecture/shenyu-framework.png" --- ## 提交者提名 当你做了很多贡献以后,社区会进行提名。 成为committer你会拥有 * Apache ShenYu仓库写的权限 * idea 正版使用 ## 提交者责任 - 开发新功能; - 代码重构; - 及时和可靠的评审Pull Request; - 思考和接纳新特性请求; - 解答问题; - 维护文档和代码示例; - 改进流程和工具; - 引导新的参与者融入社区。 ## 日常工作 1. committer需要每天查看社区待处理的Pull Request和issue列表,指定给合适的committer,即assignee。 2. assignee在被分配issue后,需要进行如下判断: - 判断是否是长期issue,如是,则标记为pending。 - 判断issue类型,如:bug,enhancement,discussion等。 - 判断Milestone,并标记。 **注意** 无论是否是社区issue,都必须有assignee,直到issue完成。 <file_sep>--- levels: - level: "Gateway" links: - "soul/overview/" - level: "Distributed Transactions" links: - "hmily/overview/" - "raincat/overview/" - "myth/overview/" --- <file_sep>--- title: Helm Deployment keywords: Apache ShenYu Deployment description: Helm Deployment --- This article introduces the use of `helm` to deploy the `Apache ShenYu` gateway. <file_sep>--- title: 规则 keywords: Apache ShenYu description: 对ShenYu网关中规则概念进行介绍 --- to do. <file_sep>--- title: "Apache ShenYu(2.3.0)" version: "2.3.0" description: "This is an asynchronous, high-performance, cross-language, responsive API gateway." startUp: "Start up" level: "main" weight: 2 showIntroduce: true showFeature: true sidebar: - title: 'Home' link: 'overview' - title: 'Team' link: 'team' - title: 'Design' sub: - title: 'Database Design' link: 'database-design' - title: 'Config' link: 'config' - title: 'DataSync' link: 'data-sync' - title: 'MetaData' link: 'meta-data' - title: 'Admin' sub: - title: 'Dictionary Management' link: 'dictionary-management' - title: 'Plugin Handle Explanation' link: 'plugin-handle-explanation' - title: 'Selector and Rule' link: 'selector-and-rule' - title: 'Users Guide' sub: - title: 'Set Up' link: 'soul-set-up' - title: 'Http Proxy' link: 'http-proxy' - title: 'Dubbo Proxy' link: 'dubbo-proxy' - title: 'SpringCloud Proxy' link: 'spring-cloud-proxy' - title: 'Sofa RPC Proxy' link: 'sofa-rpc-proxy' - title: 'Use Data Sync' link: 'use-data-sync' - title: 'Register Center' sub: - title: 'Design' link: 'register-center-design' - title: 'Access' link: 'register-center-access' - title: 'Quick Start' sub: - title: 'Dubbo' link: 'quick-start-dubbo' - title: 'Http' link: 'quick-start-http' - title: 'Grpc' link: 'quick-start-grpc' - title: 'SpringCloud' link: 'quick-start-springcloud' - title: 'Sofa' link: 'quick-start-sofa' - title: 'Tars' link: 'quick-start-tars' - title: 'Plugins' sub: - title: 'Divide Plugin' link: 'divide-plugin' - title: 'Dubbo Plugin' link: 'dubbo-plugin' - title: 'SpringCloud Plugin' link: 'spring-cloud-plugin' - title: 'Sofa Plugin' link: 'sofa-plugin' - title: 'RateLimiter Plugin' link: 'rate-limiter-plugin' - title: 'Hystrix Plugin' link: 'hystrix-plugin' - title: 'Sentinel Plugin' link: 'sentinel-plugin' - title: 'Resilience4j Plugin' link: 'resilience4j-plugin' - title: 'Monitor Plugin' link: 'monitor-plugin' - title: 'Waf Plugin' link: 'waf-plugin' - title: 'Sign Plugin' link: 'sign-plugin' - title: 'Rewrite Plugin' link: 'rewrite-plugin' - title: 'Websocket Plugin' link: 'websocket-plugin' - title: 'Context Path Plugin' link: 'context-path-plugin' - title: 'Redirect Plugin' link: 'redirect-plugin' - title: 'Logging Plugin' link: 'logging-plugin' - title: 'Developer Guide' sub: - title: 'Custom filter' link: 'custom-filter' - title: 'Custom Plugin' link: 'custom-plugin' - title: 'File and Image' link: 'file-and-image' - title: 'Custom parsing IP and Host' link: 'custom-parsing-ip-and-host' - title: 'Custom Result' link: 'custom-result' - title: 'Custom Sign Algorithm' link: 'custom-sign-algorithm' - title: 'Developer Soul Client' link: 'developer-soul-client' - title: 'Thread' link: 'thread' - title: 'Soul Optimize' link: 'soul-optimize' - title: 'Doc Download' link: 'download' # draft: true --- <file_sep>--- title: 文档下载 keywords: download description: Doc Download --- ## PDF * [English](/pdf/dromara_soul_docs_en.pdf) * [中文](/pdf/dromara_soul_docs_zh.pdf)
1a144d16cbc95a00781e36c82cba63ca70d21b32
[ "Markdown", "TOML", "JavaScript" ]
32
Markdown
ttttangzhen/incubator-shenyu-website
dff4a4f64867e42d3ea9c7d8e7160b642dcee33a
8bb5a03605eade190443c074bde03a697b3e64e3
refs/heads/master
<repo_name>g-goessel/RestApiMVVM<file_sep>/app/src/main/java/com/codingwithmitch/foodrecipes/requests/responses/RecipeResponse.kt package com.codingwithmitch.foodrecipes.requests.responses import com.codingwithmitch.foodrecipes.models.Recipe import com.google.gson.annotations.Expose import com.google.gson.annotations.SerializedName class RecipeResponse { @SerializedName("recipe") @Expose val recipe: Recipe? = null override fun toString(): String { return "RecipeResponse{" + "recipe=" + recipe + '}'.toString() } }<file_sep>/app/src/main/java/com/codingwithmitch/foodrecipes/RecipeListActivity.kt package com.codingwithmitch.foodrecipes import android.os.Bundle import android.view.View import com.codingwithmitch.foodrecipes.requests.ServiceGenerator import android.util.Log import com.codingwithmitch.foodrecipes.requests.responses.RecipeResponse import com.codingwithmitch.foodrecipes.requests.responses.RecipeSearchResponse import com.codingwithmitch.foodrecipes.util.Constants import retrofit2.Call import retrofit2.Callback import retrofit2.Response import java.io.IOException class RecipeListActivity : BaseActivity() { private val TAG = "RecipeListActivity" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_recipe_list) findViewById<View>(R.id.test).setOnClickListener { if (mProgressBar.visibility == View.VISIBLE) { showProgressBar(false) } else { showProgressBar(true) } testRetrofitRequest2() } } private fun testRetrofitRequest() { val recipeApi = ServiceGenerator().getRecipeApi() val responseCall = recipeApi.searchRecipe( Constants.API_KEY, "Chicken breast", "1" ) responseCall.enqueue(object : Callback<RecipeSearchResponse> { override fun onResponse(call: Call<RecipeSearchResponse>, response: Response<RecipeSearchResponse>) { if (response.code() == 200) { val recipe = response.body()?.recipes Log.d(TAG, "onResponse: " + recipe.toString()) } else{ try { Log.d(TAG, "onResponse: " + response.errorBody()) } catch (e: IOException) { e.printStackTrace() } } } override fun onFailure(call: Call<RecipeSearchResponse>, t: Throwable) { Log.d(TAG, "onFailure: " + t.message) } }) } private fun testRetrofitRequest2() { val recipeApi = ServiceGenerator().getRecipeApi() val responseCall = recipeApi.getRecipe( Constants.API_KEY, "1234" ) responseCall.enqueue(object : Callback<RecipeResponse> { override fun onResponse(call: Call<RecipeResponse>, response: Response<RecipeResponse>) { if (response.code() == 200) { val recipe = response.body()?.recipe Log.d(TAG, "onResponse: " + recipe.toString()) } else{ try { Log.d(TAG, "onResponse: " + response.errorBody()) } catch (e: IOException) { e.printStackTrace() } } } override fun onFailure(call: Call<RecipeResponse>, t: Throwable) { Log.d(TAG, "onFailure: " + t.message) } }) } } <file_sep>/app/src/main/java/com/codingwithmitch/foodrecipes/util/Constants.kt package com.codingwithmitch.foodrecipes.util object Constants { val BASE_URL = "https://www.food2fork.com" // YOU NEED YOUR OWN API KEY. Get it here: https://www.food2fork.com/about/api val API_KEY = "<KEY>" } <file_sep>/app/src/main/java/com/codingwithmitch/foodrecipes/BaseActivity.kt package com.codingwithmitch.foodrecipes import android.app.Activity import android.support.constraint.ConstraintLayout import android.support.v7.app.AppCompatActivity import android.view.View import android.view.inputmethod.InputMethodManager import android.widget.FrameLayout import android.widget.ProgressBar abstract class BaseActivity : AppCompatActivity() { lateinit var mProgressBar: ProgressBar override fun setContentView(layoutResID: Int) { val constraintLayout = layoutInflater.inflate(R.layout.activity_base, null) as ConstraintLayout val frameLayout = constraintLayout.findViewById<FrameLayout>(R.id.activity_content) mProgressBar = constraintLayout.findViewById(R.id.progress_bar) layoutInflater.inflate(layoutResID, frameLayout, true) super.setContentView(constraintLayout) } fun showProgressBar(visible: Boolean) { mProgressBar.visibility = if (visible) View.VISIBLE else View.INVISIBLE } } <file_sep>/app/src/main/java/com/codingwithmitch/foodrecipes/requests/responses/RecipeSearchResponse.kt package com.codingwithmitch.foodrecipes.requests.responses import com.codingwithmitch.foodrecipes.models.Recipe import com.google.gson.annotations.Expose import com.google.gson.annotations.SerializedName class RecipeSearchResponse { @SerializedName("count") @Expose val count: Int = 0 @SerializedName("recipes") @Expose val recipes: List<Recipe>? = null override fun toString(): String { return "RecipeSearchResponse{" + "count=" + count + ", recipes=" + recipes + '}'.toString() } }
c9b480a080c26a11a0a4d0bb99db440965503009
[ "Kotlin" ]
5
Kotlin
g-goessel/RestApiMVVM
59e1349eacd7eff33a10af5d41e03a47d56f8c23
5ae2a59a2d11eaa907415cab6dfd0e9e832be65d
refs/heads/master
<repo_name>Kamoliddin1/TestNews<file_sep>/blog/views.py from django.shortcuts import render from django.urls import reverse_lazy from django.views.generic import ListView from django.views.generic.edit import CreateView, UpdateView, DeleteView from .models import News, Tag, Author from .forms import NewsForm class IndexView(ListView): template_name = 'blog/index.html' model = News def get_context_data(self, *, object_list=None, **kwargs): context = super().get_context_data(**kwargs) context['latest_news'] = News.objects.order_by('-published') return context class NewsCreateView(CreateView): template_name = 'blog/create.html' form_class = NewsForm success_url = reverse_lazy('index') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['news'] = News.objects.all() return context class NewsUpdateView(UpdateView): model = News fields = ['title', 'description', 'tag'] success_url = reverse_lazy('index') template_name_suffix = '_update' class NewsDeleteView(DeleteView): model = News success_url = reverse_lazy('index') template_name_suffix = '_delete' <file_sep>/blog/urls.py from django.urls import path from .views import IndexView, NewsCreateView, NewsUpdateView, NewsDeleteView urlpatterns = [ path('', IndexView.as_view(), name='index'), path('create_news/', NewsCreateView.as_view(), name='create_news'), path('update_news/<int:pk>', NewsUpdateView.as_view(), name='update_news'), path('delete_news/<int:pk>', NewsDeleteView.as_view(), name='delete_news'), ] <file_sep>/blog/admin.py from django.contrib import admin from .models import Author, Tag, News class NewsAdmin(admin.ModelAdmin): list_display = ('title', 'description', 'published', 'author') search_fields = ('title', 'author') admin.site.register(Author) admin.site.register(Tag) admin.site.register(News, NewsAdmin) <file_sep>/blog/forms.py from django.forms import ModelForm from .models import News class NewsForm(ModelForm): class Meta: model = News fields = ['title', 'description', 'tag', 'author']
a9431a85a4eb3ca42f52f25754044d086c94d41a
[ "Python" ]
4
Python
Kamoliddin1/TestNews
51e38f5bb341a69bf701179fed73827cfdb875bb
e805475c8393eaec47b264ebc6eab86c8f8ee59f
refs/heads/master
<repo_name>wushi-shininggis/roadDetection<file_sep>/preprocess2.py import pandas as pd import cv2 import time import gc import numpy as np import os import math from operator import itemgetter time_start=time.time() def getAngle(x1, x2, y1, y2): if y2 == y1: if x2 > x1: a = 90 elif x1 > x2: a = 270 else: a = -1 else: a = math.atan((x2 - x1)/(y2 - y1))* 180 /math.pi if y1 > y2: a = a + 180 elif x1 > x2: a = a + 360 return a def pre(file, fl): img_main = cv2.imread('sjz_m_c14.tif', 0) img_matum = cv2.imread('shi000.tif', 0) img_matdm = cv2.imread('shi000.tif', 0) img_mats = cv2.imread('shi000.tif') mat = pd.read_csv(file, header = None, usecols=[0, 1, 2, 5, 6], chunksize=10000000) for chunk in mat: chunk = chunk.values try : chunk = sorted(chunk, key=itemgetter(0,3)) for i in range(len(chunk)): if chunk[i][0]==chunk[i+1][0] and chunk[i][4]<9 and chunk[i+1][4]<10 and (114.375< chunk[i][1] <= 114.62499)and (38.0 < chunk[i][2] <= 38.16666): x1 = int(round((chunk[i][1] - 114.375)*27830)) y1 = 4639 - int(round((chunk[i][2]-38.0)*27830)) x2 = int(round((chunk[i+1][1] - 114.375)*27830)) y2 = 4639 - int(round((chunk[i+1][2]-38.0)*27830)) if 0 < (chunk[i+1][3] - chunk[i][3]) <= 10 and 0 < (np.square(x1 - x2) + np.square(y1 - y2)) < np.square(25*(chunk[i+1][3] - chunk[i][3])): if img_main[y1][x1] > 0: ang = getAngle(chunk[i][1], chunk[i+1][1], chunk[i][2], chunk[i+1][2]) if 0 <= ang < 180: img_matum[y1][x1] = 255 elif 180 <= ang < 360: img_matdm[y1][x1] = 255 else: continue elif img_main[y2][x2] == 0: cv2.line(img_mats, (x1, y1), (x2, y2), (255, 255, 255), 1) else: continue else: continue else: continue except Exception: pass cv2.imwrite('shi_img/shi' + fl + 'u_main.tif', np.array(img_matum)) cv2.imwrite('shi_img/shi' + fl + 'd_main.tif', np.array(img_matdm)) cv2.imwrite('shi_img/shi' + fl + '_side.tif', np.array(img_mats)) def fun(path): files_mat = [] for root, dirs, files in os.walk(path): for fn in files: files_mat.append(fn) return files_mat path = 'g:/shijiazhuang_liuan/shijiazhuang' files_mat = fun(path) for fl in files_mat: file_data = path + '/' + fl pre(file_data,fl[-4:] ) time_end1=time.time() print(time_end1-time_start)<file_sep>/difference2.py import cv2 import numpy as np import time time_start=time.time() def diff(img1, img2, res1, res2): #读取待差分图像 data1 = cv2.imread(img1, 0) data2 = cv2.imread(img2, 0) #定义两幅空白图像 image_arr1 = np.zeros((len(data1), len(data1[0])), np.uint8) image_arr2 = np.zeros((len(data1), len(data1[0])), np.uint8) for i in range(len(data1)) : for j in range(len(data1[0])) : if int(data1[i][j])-int(data2[i][j]) > 0: image_arr1[i][j] = 255 elif int(data1[i][j])-int(data2[i][j]) < 0: image_arr2[i][j] = 255 else: continue #出图 cv2.imwrite(res1, image_arr1) cv2.imwrite(res2, image_arr2) img1 = 'wh_img/2/wh0627u_main.tif' img2 = 'wh_img/2/wh0704u_main.tif' res1 = 'wh_img/wh062704u.tif' res2 = 'wh_img/wh070427u.tif' diff(img1, img2, res1, res2) time_end=time.time() print(time_end-time_start) <file_sep>/ero_dil.py import os import scipy.signal as signal import cv2 import numpy as np def fun(path): files_mat = [] for root, dirs, files in os.walk(path): for fn in files: files_mat.append(fn) return files_mat def filt(img): image = cv2.imread(img, 0) kernel = np.ones((3, 3), np.uint8) erosion = cv2.erode(image, kernel, iterations = 2) # 腐蚀 dilation = cv2.dilate(erosion, kernel, iterations = 2) # 膨胀 cv2.imwrite(img[:-4] + '_f2.tif', dilation) path = 'shi_img/add/a' files_mat = fun(path) for fl in files_mat: file_data = path + '/' + fl filt(file_data)<file_sep>/filter2.py import os import scipy.signal as signal import cv2 import numpy as np def fun(path): files_mat = [] for root, dirs, files in os.walk(path): for fn in files: files_mat.append(fn) return files_mat def filt(img): data=cv2.imread(img, 0) image_arr = signal.medfilt2d(data, kernel_size = 5) cv2.imwrite(img[:-4] + '_f2.tif', image_arr) path = 'wh_img/dif/d' files_mat = fun(path) for fl in files_mat: file_data = path + '/' + fl # print(fl[-2:]) filt(file_data)<file_sep>/houghline.py import cv2 import numpy as np import skimage.transform as st import pandas as pd import os def fun(path): files_mat = [] for root, dirs, files in os.walk(path): for fn in files: files_mat.append(fn) return files_mat def hough(data_img): img = cv2.imread(data_img, 0) image = cv2.imread('wh_img/2/wh0627u_main.tif') # edges = cv2.Canny(img, 50, 150, apertureSize=3) minLineLength = 50 maxLineGap = 30 lines = cv2.HoughLinesP( img, 1.0, np.pi/180,30, 100, minLineLength,maxLineGap) line_csv = [] print(type(lines)) try: print(len(lines)) for line in lines: x1, y1, x2, y2 = line[0] lo1 = x1/27830 + 114.375 la1 = (4639 - y1)/27830 + 38.0 lo2 = x2/27830 + 114.375 la2 = (4639 - y2)/27830 + 38.0 line_csv.append([lo1, la1, lo2, la2]) cv2.line(image,(x1, y1),(x2, y2),(0,0,255),5) cv2.imwrite(data_img[:-4] + 'sg0.tif', image) line_csv = pd.DataFrame(line_csv) line_csv.to_csv(data_img[:-4] + 'sg0', index=False, header=None) except TypeError: pass path = 'wh_img/f' files_mat = fun(path) for fl in files_mat: file_data = path + '/' + fl # print(fl[-2:]) hough(file_data) <file_sep>/requirements.txt opencv_python==3.4.1.15 scikit_image==0.14.0 pandas==0.19.2 numpy==1.11.3+mkl scipy==0.19.0 skimage==0.0 <file_sep>/README.md # roadDetection Wuce trajectory data mining group difference2.py 差分 ero_dil.py 开运算 filter2.py 滤波 houghline.py 霍夫变换 preprocess2.py 预处理
0c5552b20817ba50c265b73b5ecbd6fba48e9aa0
[ "Markdown", "Python", "Text" ]
7
Python
wushi-shininggis/roadDetection
7016be6ca3b1ed29cc33e8100e9fa2f25b179ef4
c9d3a4c8da469f17a3d82bcca1243206ca1c0da2
refs/heads/main
<repo_name>monesha-goutham/Watchlist-Maker<file_sep>/src/components/Watched.js import React, { useContext } from "react"; import "./Watched.css"; import { GlobalContext } from "./../contexts/global-context"; import { Button } from "@material-ui/core"; import MovieTile from "./MovieTile"; const Watched = () => { const { watched, deleteFromWatched, moveToWatchlist } = useContext( GlobalContext ); return ( <div className="watched"> <div className="watched__heading"> <h1>Watched Movies</h1> </div> <div className="watched__grid"> {watched.map((movie) => ( <MovieTile movie={movie} type="watched" deleteAction={deleteFromWatched} moveAction={moveToWatchlist} /> ))} </div> </div> ); }; export default Watched; // TODO : // check if the api call has any returned search result and only then call for the "movie" component // add valid movie info and check for "null" returns. // start with CSS. <file_sep>/src/components/Header.js import React from "react"; import "./Header.css"; import { Button } from "@material-ui/core"; import { Link, useHistory } from "react-router-dom"; const Header = () => { const history = useHistory(); return ( <div className="header-container"> <div className="header"> <Link to="/"> <div className="header__title"> <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/e/ee/Fandom_heart-logo.svg/250px-Fandom_heart-logo.svg.png" alt="logo" className="header__logo" /> <h3>WatchList</h3> </div> </Link> <ul className="header__list"> <li className="header__item"> <Link to="/">Watchlist</Link> </li> <li className="header__item"> <Link to="/watched">Watched</Link> </li> <li> <Button variant="outlined" className="header__btn" onClick={() => history.push("/add")} > + ADD </Button> </li> </ul> </div> </div> ); }; export default Header; <file_sep>/src/components/MovieCard.js import { Button } from "@material-ui/core"; import React, { useContext } from "react"; import "./MovieCard.css"; import { GlobalContext } from "./../contexts/global-context"; const MovieCard = ({ movie }) => { const { watchlist, addToWatchlist, addToWatched, watched } = useContext( GlobalContext ); const movieExistsInWatchlist = watchlist.find( (inside) => inside.id === movie.id ) ? true : false; const movieExistsInWatched = watched.find((inside) => inside.id === movie.id) ? true : false; return ( <div className="movie-card"> {movie.poster_path ? ( <img src={`https://image.tmdb.org/t/p/original/${movie.poster_path}`} alt="none" className="movie-card__img" /> ) : ( <div className="movie-card__filler-img-container"> <div className="movie-card__filler-img"></div> </div> )} <div className="movie-card__info"> {/* many unwanted info here */} <div className="info-text"> <h2>{movie.title}</h2> <p>{movie.release_date ? movie.release_date.substring(0, 4) : "-"}</p> </div> <div className="info__rating"> {movie.vote_average > 2 ? ( <div className="rating__inner" style={{ width: `${movie.vote_average * 10}%` }} > <h3>{movie.vote_average}</h3> </div> ) : null} </div> <div className="movie-card__buttons"> {/* buttons are disabled to prevent the problem of adding the same movie twice */} <div className="btn__watchlist"> <Button variant="outlined" className="btn-watchlist btn" onClick={() => addToWatchlist(movie)} disabled={ // check if movie is first in the "watched" // if "true" : disable // if "false" : check if movie is in the "watchlist" // if "true" : disable // if "false" : enable movieExistsInWatched ? true : movieExistsInWatchlist ? true : false } > Add to watchlist </Button> </div> <div className="btn__watched "> <Button variant="outlined" className="btn-watched btn" onClick={() => addToWatched(movie)} disabled={movieExistsInWatched ? true : false} > Add to watched </Button> </div> </div> </div> </div> ); }; export default MovieCard; <file_sep>/src/firebase.js // Firebase App (the core Firebase SDK) is always required and // must be listed before other Firebase SDKs import firebase from "firebase/app"; // Add the Firebase services that you want to use import "firebase/auth"; import "firebase/firestore"; // For Firebase JS SDK v7.20.0 and later, measurementId is optional const firebaseConfig = { apiKey: "<KEY>", authDomain: "watchlist-9788a.firebaseapp.com", projectId: "watchlist-9788a", storageBucket: "watchlist-9788a.appspot.com", messagingSenderId: "901057161976", appId: "1:901057161976:web:c0d0c1a069344699faa90d", measurementId: "G-0DPV3QZZ8J", }; firebase.initializeApp(firebaseConfig); export const db = firebase.firestore(); <file_sep>/README.md # Watchlist-Maker This is a movie watch-list maker created with ❤ using React.js ## Tools used - React.js - Flexbox and Grid - Context API - Hooks used : useState, useEffect, useContext, useReducer - Material UI - React Icons - React Router - Firebase Hosting - TMDB api ## Learning Outcome This project is purely **frontend-focused**, especiallly focused on using the **top four hooks** in React.js. Also getting a hold of **global state management** using the context api. So, in its entireity, this project deals with **fetching data** from the API, **managing states** between component and changing the states using a **reducer action**. There will be a backend added to this app in the *future*. ## App Description The watch-list maker is self-explanatory. You add new movies to the watchlist by seraching for movies in the **+ADD** page. which will be stored in the watch-list. Furthermore, you can delete the movies or even toggle the movies to and fro between the **"Watch-list"** and the **"Watched-list"**. ### App website https://watchlist-9788a.web.app/ <file_sep>/src/App.js import React from "react"; import "./App.css"; import Header from "./components/Header"; import { BrowserRouter as Router, Switch, Route } from "react-router-dom"; import WatchList from "./components/WatchList"; import Watched from "./components/Watched"; import AddPage from "./components/AddPage"; import { GlobalStateProvider } from "./contexts/global-context"; function App() { return ( <GlobalStateProvider> <Router> <div className="App"> <Header /> <Switch> <Route path="/add"> <AddPage /> </Route> <Route path="/watched"> <Watched /> </Route> <Route exact path="/"> <WatchList /> </Route> </Switch> </div> </Router> </GlobalStateProvider> ); } export default App; <file_sep>/src/contexts/global-context.js import React, { createContext, useReducer, useEffect } from "react"; import reducerFunc from "./reducerFunc"; import { db } from "../firebase"; // creete the global context export const GlobalContext = createContext(); // create the initial state const initialState = { watchlist: [], watched: [], }; // create the context provider export const GlobalStateProvider = ({ children }) => { const [state, dispatch] = useReducer(reducerFunc, initialState); useEffect(() => {}, [state]); // create the action functions const addToWatchlist = (movie) => { dispatch({ type: "ADD_TO_WATCHLIST", payload: movie }); }; const addToWatched = (movie) => { dispatch({ type: "ADD_TO_WATCHED", payload: movie }); }; const deleteFromWatchlist = (id) => { dispatch({ type: "DELETE_FROM_WATCHLIST", payload: id }); }; const deleteFromWatched = (id) => { dispatch({ type: "DELETE_FROM_WATCHED", payload: id }); }; const moveToWatchlist = (movie) => { // code to move from watched to watchlist dispatch({ type: "MOVE_TO_WATCHLIST", payload: movie }); }; return ( <GlobalContext.Provider value={{ watched: state.watched, watchlist: state.watchlist, addToWatchlist, addToWatched, deleteFromWatchlist, deleteFromWatched, moveToWatchlist, }} > {children} </GlobalContext.Provider> ); }; <file_sep>/src/components/MovieTile.js import React, { useContext } from "react"; import "./MovieTile.css"; import { Button } from "@material-ui/core"; import { FaEye, FaEyeSlash } from "react-icons/fa"; const MovieTile = ({ movie, type, deleteAction, moveAction }) => { return ( <div className="movie-tile"> {movie.poster_path ? ( <img src={`https://image.tmdb.org/t/p/original/${movie.poster_path}`} alt="none" className="movie-poster" /> ) : ( <div className="movie-dummy"></div> )} <div className="control-btns"> <Button variant="outlined" size="small" className="delete-btn tile-btn" onClick={() => deleteAction(movie.id)} > X </Button> {type === "watchlist" ? ( <Button variant="outlined" size="small" className="watchlist-btn tile-btn" onClick={() => moveAction(movie)} > <FaEye></FaEye> </Button> ) : ( <Button variant="outlined" size="small" className="watched-btn tile-btn" onClick={() => moveAction(movie)} > <FaEyeSlash /> </Button> )} </div> </div> ); }; export default MovieTile; <file_sep>/src/components/WatchList.js import React, { useContext } from "react"; import "./WatchList.css"; import { GlobalContext } from "./../contexts/global-context"; import { Button } from "@material-ui/core"; import MovieTile from "./MovieTile"; const WatchList = () => { const { watchlist, deleteFromWatchlist, addToWatched } = useContext( GlobalContext ); return ( <div className="watchlist"> <div className="watchlist__heading"> <h1>Watchlist</h1> </div> <div className="watchlist__grid"> {watchlist.map((movie) => ( <MovieTile movie={movie} type="watchlist" deleteAction={deleteFromWatchlist} moveAction={addToWatched} /> ))} </div> </div> ); }; export default WatchList;
c515df799fdf13f821e2f9a002ec6b854866f44d
[ "JavaScript", "Markdown" ]
9
JavaScript
monesha-goutham/Watchlist-Maker
0c33f2b2fdb33c918b049cb0c3d9f1776bdada7c
038fb690babb6f252af902ee3ff57b112ff6e0ba
refs/heads/master
<repo_name>RicardoRomao/iselpdm<file_sep>/Source/PDM-Trabalho Final/src/storage/filter/ItemByIdFilter.java package storage.filter; import domainObjects.translator.ItemTranslator; import javax.microedition.rms.RecordFilter; public class ItemByIdFilter implements RecordFilter { private final int _id; public ItemByIdFilter(int id){ _id = id; } public boolean matches(byte[] candidate) { return ItemTranslator.byte2Item(candidate).getId() == _id; } } <file_sep>/Source/PDM-Trabalho Final/src/domainObjects/translator/ItemTranslator.java package domainObjects.translator; import constants.Constants; import domainObjects.Item; import java.util.Date; public class ItemTranslator {// implements IITemTranslator { public static byte[] item2Byte(Item item) { String itemStr = item.getId() + Constants.TRANSLATOR_SEP + item.getCategory() + Constants.TRANSLATOR_SEP + item.getTitle() + Constants.TRANSLATOR_SEP + item.getDesc() + Constants.TRANSLATOR_SEP + item.getExpiryDate().getTime(); return itemStr.getBytes(); } public static Item byte2Item(byte[] item) { String itemStr = new String(item); int index, lastIndex = 0; int sepLen = Constants.TRANSLATOR_SEP.length(); index = itemStr.indexOf(Constants.TRANSLATOR_SEP, 0); //Getting id int id = Integer.parseInt(itemStr.substring(lastIndex, index)); lastIndex = index + sepLen; index = itemStr.indexOf(Constants.TRANSLATOR_SEP, lastIndex); //Getting categoryId int categoryId = Integer.parseInt(itemStr.substring(lastIndex, index)); lastIndex = index + sepLen; index = itemStr.indexOf(Constants.TRANSLATOR_SEP, lastIndex); //Getting Title String title = itemStr.substring(lastIndex, index); lastIndex = index + sepLen; index = itemStr.indexOf(Constants.TRANSLATOR_SEP, lastIndex); //Getting Description String desc = itemStr.substring(lastIndex, index); lastIndex = index + sepLen; //Getting ExpiryDate Date expiryDate = new Date(Long.parseLong(itemStr.substring(lastIndex))); return new Item(id, categoryId, title, desc, null, expiryDate); } } <file_sep>/Source/PDMWeb/PENPalWebApp/PENPalService.ashx.cs using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data; using System.Data.SqlClient; using System.Configuration; using System.Text; using System.Threading; namespace PENPalWebApp { public class PENPalService : IHttpHandler { public void ProcessRequest(HttpContext context) { string action = context.Request["action"]; string resp = string.Empty; switch (action) { case "add": resp = AddItem(context); break; case "list": resp = ListItems(context); break; default: break; } context.Response.ContentType = "text/plain"; context.Response.AppendHeader("Content-Length", resp.Length.ToString()); context.Response.Write(resp); } private string ListItems(HttpContext ctx) { SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["bd"].ConnectionString); SqlCommand cmd = con.CreateCommand(); SqlDataReader reader; String query; SqlParameter param; String ret; Int32 numReg = 0; StringBuilder sb = new StringBuilder(25); // | // id, categoryId, Title, Description, ExpiryDate query = "SELECT * FROM Item WHERE UserId = @UserId"; cmd.CommandText = query; cmd.CommandType = CommandType.Text; // User Id param = new SqlParameter("@UserId", SqlDbType.Int); param.Value = ctx.Request["user"]; cmd.Parameters.Add(param); con.Open(); reader = cmd.ExecuteReader(); while (reader.Read()) { if (sb.Length > 0) { sb.Append("#"); } sb.Append(reader.GetInt32(0)); sb.Append("|"); sb.Append(reader.GetInt32(6)); sb.Append("|"); sb.Append(reader.GetString(1)); sb.Append("|"); sb.Append(reader.GetString(2)); sb.Append("|"); sb.Append(reader.GetInt32(4)); numReg++; } reader.Close(); con.Close(); cmd.Dispose(); con.Dispose(); sb.Insert(0, numReg + "«"); ret = sb.ToString(); sb.Length = 0; return ret; } private string AddItem(HttpContext ctx) { SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["bd"].ConnectionString); SqlCommand cmd = con.CreateCommand(); String query; SqlParameter param; String ret; query = "INSERT INTO Item(Title, Description, ExpiryDate, UserId, CategoryId) VALUES(@Title, @Description, @ExpiryDate, @UserId, @CategoryId)" + "SELECT @@IDENTITY"; cmd.CommandText = query; cmd.CommandType = CommandType.Text; // Title param = new SqlParameter("@Title", SqlDbType.VarChar); param.Value = ctx.Request["title"]; cmd.Parameters.Add(param); // Description param = new SqlParameter("@Description", SqlDbType.Text); param.Value = ctx.Request["description"]; cmd.Parameters.Add(param); // Expiry Date param = new SqlParameter("@ExpiryDate", SqlDbType.BigInt); param.Value = ctx.Request["expirydate"]; cmd.Parameters.Add(param); // User Id param = new SqlParameter("@UserId", SqlDbType.Int); param.Value = ctx.Request["user"]; cmd.Parameters.Add(param); // Category Id param = new SqlParameter("@CategoryId", SqlDbType.Int); param.Value = ctx.Request["category"]; cmd.Parameters.Add(param); con.Open(); ret = cmd.ExecuteScalar().ToString(); con.Close(); cmd.Dispose(); con.Dispose(); Thread.Sleep(2000); return ret; } public bool IsReusable { get { return false; } } } } <file_sep>/Source/PDM-Trabalho Final/src/domainObjects/Category.java package domainObjects; public class Category { private int _id; private String _desc; public Category() { } public Category(int id, String desc) { _id = id; _desc = desc; } public int getId() { return _id; } public void setId(int id) { _id = id; } public String getDesc() { return _desc; } public void setDesc(String desc) { _desc = desc; } } <file_sep>/Source/PDM-Trabalho Final/src/screens/FormScreen.java package screens; import entryPoint.PenPAL; import javax.microedition.lcdui.Command; import javax.microedition.lcdui.CommandListener; import javax.microedition.lcdui.Form; import javax.microedition.lcdui.Item; public abstract class FormScreen extends Form implements CommandListener{ protected final PenPAL owner; protected final Command cmdBack, cmdOk; public FormScreen(PenPAL owner, String title, Item[] items) { super(title, items); this.owner = owner; cmdBack = new Command("Back", Command.BACK, 1); cmdOk = new Command("Ok", Command.OK, 1); this.addCommand(cmdBack); this.addCommand(cmdOk); this.setCommandListener(this); } public abstract void cls(); } <file_sep>/Source/PDM-Trabalho Final/src/screens/ItemViewScreen.java package screens; import constants.Constants; import entryPoint.PenPAL; import javax.microedition.lcdui.Command; import javax.microedition.lcdui.Displayable; import javax.microedition.lcdui.Image; import javax.microedition.lcdui.ImageItem; import javax.microedition.lcdui.Item; import javax.microedition.lcdui.StringItem; public class ItemViewScreen extends FormScreen { private Image itemImage; private static final int IDX_ID = 0; private static final int IDX_CATEGORY = 1; private static final int IDX_TITLE = 2; private static final int IDX_DESC = 3; private static final int IDX_DATE = 4; private static final int IDX_IMAGE = 5; private final Item[] items = { new StringItem("ID", "") , new StringItem("Category", "") , new StringItem("Title", "") , new StringItem("Description", "") , new StringItem("Expiry Date", "") , new ImageItem("Item Image", null, ImageItem.LAYOUT_LEFT, "") }; public ItemViewScreen(PenPAL owner) { super(owner, Constants.APP_TITLE, null); removeCommand(cmdOk); for (int i=0; i<items.length; i++) append(items[i]); } public void setModel(domainObjects.Item item) { cls(); ((StringItem)items[IDX_ID]).setText(String.valueOf(item.getId())); ((StringItem)items[IDX_CATEGORY]).setText( Constants.CATEGORIES[Constants.CATEGORIES_NAMES[item.getCategory()]] ); ((StringItem)items[IDX_TITLE]).setText(item.getTitle()); ((StringItem)items[IDX_DESC]).setText(item.getDesc()); ((StringItem)items[IDX_DATE]).setText(item.getExpiryDate().toString()); if (item.getImage() != null) { itemImage = Image.createImage(item.getImage(), 0, item.getImage().length); ((ImageItem)items[IDX_IMAGE]).setImage(itemImage); } } public void cls() { ((StringItem)items[IDX_ID]).setText(null); ((StringItem)items[IDX_CATEGORY]).setText(null); ((StringItem)items[IDX_TITLE]).setText(null); ((StringItem)items[IDX_DESC]).setText(null); ((StringItem)items[IDX_DATE]).setText(null); ((ImageItem)items[IDX_IMAGE]).setImage(null); } public void commandAction(Command cmd, Displayable d) { if (cmd == cmdBack) { owner.backToItemListScreen(); } } } <file_sep>/Source/PDM-Trabalho Final/src/entryPoint/PenPAL.java package entryPoint; import connector.ConnectionMediator; import constants.Constants; import domainObjects.Config; import domainObjects.Item; import domainObjects.Query; import domainObjects.User; import java.util.Vector; import javax.microedition.lcdui.Alert; import javax.microedition.lcdui.AlertType; import javax.microedition.lcdui.Command; import javax.microedition.lcdui.CommandListener; import javax.microedition.lcdui.Display; import javax.microedition.lcdui.Displayable; import javax.microedition.midlet.MIDlet; import javax.microedition.midlet.MIDletStateChangeException; import screens.CategorySelectorScreen; import screens.ConfigScreen; import screens.ItemCreateScreen; import screens.ItemListScreen; import screens.ItemViewScreen; import screens.MainScreen; import screens.ProfileScreen; import screens.QueryScreen; import storage.IRepository; import storage.RecStoreRepository; public class PenPAL extends MIDlet { private boolean isInited; private Display display; private Config config; private ConnectionMediator con; private Command waitCmd; private static IRepository rep = new RecStoreRepository(); private static Displayable[] screens = new Displayable[Constants.MAX_SCREENS]; private static final int IDX_MAIN_SCREEN = 0; private static final int IDX_PROFILE_SCREEN = 1; private static final int IDX_SETTINGS_SCREEN = 2; private static final int IDX_QUERY_SCREEN = 3; private static final int IDX_SENDITEM_SCREEN = 4; private static final int IDX_SAVEDITEMS_SCREEN = 5; private static final int IDX_SENTITEMS_SCREEN = 6; private static final int IDX_CATSELECTOR_SCREEN = 7; private static final int IDX_ITEMLIST_SCREEN = 8; private static final int IDX_ITEMVIEW_SCREEN = 9; private static final int IDX_WAIT_SCREEN = 10; public PenPAL() { isInited = false; } private void init() { display = Display.getDisplay(this); config = rep.getConfig(); con = new ConnectionMediator(this); isInited = true; } protected void startApp() throws MIDletStateChangeException { if (!isInited) { init(); } showMainScreen(); } protected void pauseApp() { } protected void destroyApp(boolean unconditional) throws MIDletStateChangeException { if (screens != null) { for (int i = 0; i < screens.length; i++) { if (screens[i] != null) { screens[i] = null; } } screens = null; } rep = null; } private void addOwnItem(Item item) { rep.addOwnItem(item); } public void updateUserProfile(User user) { rep.updateUserProfile(user); con.setUser(user); } public User getUserProfile() { return rep.getUserProfile(); } public boolean hasUserProfile() { return rep.getUserProfile() != null; } public void updateConfig(Config c) { this.config = c; rep.updateConfig(config); } // SEND ITEM --- public void sendItem(Item item) { showCommunicatingScreen(); con.addItem(item); } public void sendItemComplete(Item item) { if (config.getSaveOwnItems()) { addOwnItem(item); } showMainScreen(); showWaitScreen("Item successfully sent!", AlertType.CONFIRMATION); } // --- SEND ITEM // GET SAVED ITEMS --- public void savedItems(int category) { showCommunicatingScreen(); Vector items = rep.getItemsByCat(category); if (items.size() == 0) { showCategorySelectorScreen(IDX_SENTITEMS_SCREEN); showWaitScreen( "No saved items in category '" + getCategoryName(category) + "'!", AlertType.CONFIRMATION ); } else { showItemListScreen(category, IDX_SENTITEMS_SCREEN, items); showWaitScreen( "Successfully loaded " + items.size() + " saved items!", AlertType.CONFIRMATION ); } } // --- GET SAVED ITEMS // GET SENT ITEMS --- public void sentItems(int category) { showCommunicatingScreen(); con.showSentItems(category); } public void sentItemsComplete(int category, Vector items) { if (items.size() == 0) { showCategorySelectorScreen(IDX_SENTITEMS_SCREEN); showWaitScreen( "No sent items in category '" + getCategoryName(category) + "'!", AlertType.CONFIRMATION ); } else { showItemListScreen(category, IDX_SENTITEMS_SCREEN, items); showWaitScreen( "Successfully received " + items.size() + " sent items!", AlertType.CONFIRMATION ); } } // --- GET SENT ITEMS // GET QUERY RESULT --- public void sendQuery(Query q) { showMainScreen(); showWaitScreen("Not implemented!", AlertType.WARNING); } // --- GET QUERY RESULT public void showCommunicatingScreen() { showWaitScreen("Communicating....", AlertType.INFO); waitCmd = new Command("Cancel",Command.CANCEL,1); addCommandToWaitScreen(new CommandListener() { public void commandAction(Command c, Displayable d) { con.cancel(); showWaitScreen("Communication canceled by user!", AlertType.ERROR); } }); } public void showWaitScreen() { showWaitScreen(null, AlertType.INFO); } public void showWaitScreen(String msg, AlertType type) { if (screens[IDX_WAIT_SCREEN] == null) { screens[IDX_WAIT_SCREEN] = new Alert(Constants.APP_TITLE, null, null, type); ((Alert)screens[IDX_WAIT_SCREEN]).setTimeout(Alert.FOREVER); } if (waitCmd != null) { ((Alert)screens[IDX_WAIT_SCREEN]).removeCommand(waitCmd); ((Alert)screens[IDX_WAIT_SCREEN]).setCommandListener(null); } ((Alert)screens[IDX_WAIT_SCREEN]).setString(msg); display.setCurrent(screens[IDX_WAIT_SCREEN]); } private void addCommandToWaitScreen(CommandListener listener) { if (waitCmd != null) { ((Alert)screens[IDX_WAIT_SCREEN]).addCommand(waitCmd); ((Alert)screens[IDX_WAIT_SCREEN]).setCommandListener(listener); } } public void showMainScreen() { if (screens[IDX_MAIN_SCREEN] == null) { screens[IDX_MAIN_SCREEN] = new MainScreen(this); } display.setCurrent(screens[IDX_MAIN_SCREEN]); } public void showProfileScreen() { if (screens[IDX_PROFILE_SCREEN] == null) { screens[IDX_PROFILE_SCREEN] = new ProfileScreen(this); } ((ProfileScreen) screens[IDX_PROFILE_SCREEN]).setUser(rep.getUserProfile()); display.setCurrent(screens[IDX_PROFILE_SCREEN]); } public void showSettingsScreen() { if (screens[IDX_SETTINGS_SCREEN] == null) { screens[IDX_SETTINGS_SCREEN] = new ConfigScreen(this); } ((ConfigScreen) screens[IDX_SETTINGS_SCREEN]).setConfig(config); display.setCurrent(screens[IDX_SETTINGS_SCREEN]); } public void showQueryScreen() { if (screens[IDX_QUERY_SCREEN] == null) { screens[IDX_QUERY_SCREEN] = new QueryScreen(this); } ((QueryScreen) screens[IDX_QUERY_SCREEN]).cls(); display.setCurrent(screens[IDX_QUERY_SCREEN]); } public void showSavedItemsScreen() { showCategorySelectorScreen(IDX_SAVEDITEMS_SCREEN); } public void showSentItemsScreen() { showCategorySelectorScreen(IDX_SENTITEMS_SCREEN); } public void showCategorySelectorScreen(int targetScreen) { if (screens[IDX_CATSELECTOR_SCREEN] == null) { screens[IDX_CATSELECTOR_SCREEN] = new CategorySelectorScreen(this); } screens[targetScreen] = screens[IDX_CATSELECTOR_SCREEN]; if (targetScreen == IDX_QUERY_SCREEN) { showQueryScreen(); } ((CategorySelectorScreen) screens[targetScreen]).setTargetScreen(targetScreen); display.setCurrent(screens[targetScreen]); } public void resolveCategorySelection(int category, int targetScreen) { //Ver qual é o target e direccionar para 'Sent Items' ou 'Saved Items' switch (targetScreen) { case IDX_SAVEDITEMS_SCREEN: break; case IDX_SENTITEMS_SCREEN: sentItems(category); break; case -1: break; } } public void showItemListScreen(int category, int targetScreen, Vector items) { if (screens[IDX_ITEMLIST_SCREEN] == null) { screens[IDX_ITEMLIST_SCREEN] = new ItemListScreen(this); } String sufix = null; switch (targetScreen) { case IDX_QUERY_SCREEN: sufix = "Query Result"; break; case IDX_SAVEDITEMS_SCREEN: sufix = "Saved Items"; break; case IDX_SENTITEMS_SCREEN: sufix = "Sent Items"; break; } ((ItemListScreen) screens[IDX_ITEMLIST_SCREEN]).initList(items, category); screens[IDX_ITEMLIST_SCREEN].setTitle( Constants.APP_TITLE + " - " + sufix + "(" + Constants.CATEGORIES[category] + ")"); display.setCurrent(screens[IDX_ITEMLIST_SCREEN]); } public void showItemListScreen(Vector items) { //Called after returning from 'Get Items' if (screens[IDX_ITEMLIST_SCREEN] == null) { screens[IDX_ITEMLIST_SCREEN] = new ItemListScreen(this); } ((ItemListScreen) screens[IDX_ITEMLIST_SCREEN]).initList(rep.getItemsByCat(1), -1); screens[IDX_ITEMLIST_SCREEN].setTitle(Constants.APP_TITLE + " - " + "Received items"); } public void backToItemListScreen() { display.setCurrent(screens[IDX_ITEMLIST_SCREEN]); } public void showItemViewScreen(Item item) { if (screens[IDX_ITEMVIEW_SCREEN] == null) { screens[IDX_ITEMVIEW_SCREEN] = new ItemViewScreen(this); } ((ItemViewScreen) screens[IDX_ITEMVIEW_SCREEN]).setModel(item); display.setCurrent(screens[IDX_ITEMVIEW_SCREEN]); } public void showSendItemScreen() { if (screens[IDX_SENDITEM_SCREEN] == null) { screens[IDX_SENDITEM_SCREEN] = new ItemCreateScreen(this); } ((ItemCreateScreen) screens[IDX_SENDITEM_SCREEN]).cls(); display.setCurrent(screens[IDX_SENDITEM_SCREEN]); } private String getCategoryName(int id) { return Constants.CATEGORIES[Constants.CATEGORIES_NAMES[id]]; } } <file_sep>/Source/PDM-Trabalho Final/src/connector/HttpConnector.java package connector; import java.io.*; import java.util.*; import javax.microedition.io.*; import storage.Exception.NotExpectedException; public class HttpConnector implements IConnectionDecorator, IConnectionListener { private String _url; private String _method; private Hashtable _params; private byte[] _res; private IConnectionListener _failListener; private IConnectionListener _completeListener; private Thread _worker; private HttpConnection _con; private int _responseCode; private volatile boolean bUse = false; private HttpConnector() { bUse = false; _params = new Hashtable(); _method = HttpConnection.POST; } public static IConnectionDecorator getInstance() { return new HttpConnector(); } public void addParameter(String key, Object value) { if (bUse) { return; } _params.put(key, value); } public Object removeParameter(String key) { if (bUse) { return null; } return _params.remove(key); } public void setMethod(String method) { if (bUse) { return; } _method = method; } public void setUrl(String url) { if (bUse) { return; } _url = url; } public void init() { if (bUse) { return; } bUse = true; try { String rawData = buildQueryString(); String endPoint = _url + ((_method.compareTo(HttpConnection.POST) == 0) ? "" : "?" + rawData); _con = (HttpConnection) Connector.open(endPoint); _con.setRequestMethod(_method); if (_method.compareTo(HttpConnection.POST) == 0) { _con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); _con.setRequestProperty("Content-Length ", String.valueOf(rawData.length())); OutputStream os = _con.openOutputStream(); os.write(rawData.getBytes()); os.close(); } } catch (IOException ex) { bUse = false; throw new NotExpectedException(ex.getMessage()); } } private String buildQueryString() { StringBuffer query = new StringBuffer(); Enumeration keys = _params.keys(); String key; while (keys.hasMoreElements()) { key = keys.nextElement().toString(); if (query.length() > 0) { query.append("&"); } query.append(key); query.append("="); query.append(_params.get(key).toString()); } return query.toString(); } public void send() { final IConnectionDecorator obj = this; boolean failed = false; try { _responseCode = _con.getResponseCode(); if (isResponseOk()) { InputStream is = _con.openInputStream(); long len = _con.getLength(); if (len == -1) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); int bite; while ((bite = is.read()) != -1) { bos.write(bite); } _res = bos.toByteArray(); bos.close(); } else { _res = new byte[(int) len]; is.read(_res, 0, (int) len); } is.close(); } else { failed = true; } } catch (IOException ex) { failed = true; } finally { if (_con != null) { try { _con.close(); } catch (IOException ex) { throw new NotExpectedException(ex.getMessage()); } } } if (failed) { onFail(obj); } else { onComplete(obj); } } public void cancelRequest() { if (_worker != null && _worker.isAlive()) { _worker.interrupt(); } } public boolean isResponseOk() { return _responseCode == HttpConnection.HTTP_OK; } public byte[] getResponse() { return _res; } public void setCompleteListener(IConnectionListener listener) { _completeListener = listener; } public void setFailListener(IConnectionListener listener) { _failListener = listener; } public void onFail(IConnectionDecorator con) { bUse = false; if (_failListener != null) { _failListener.onFail(this); } } public void onComplete(IConnectionDecorator con) { bUse = false; if (_completeListener != null) { _completeListener.onComplete(this); } } } <file_sep>/Source/PDM-Trabalho Final/src/storage/filter/KeyByItemIdFilter.java package storage.filter; import javax.microedition.rms.RecordFilter; import storage.recordKey.KeyTranslator; import storage.recordKey.RecordKey; public class KeyByItemIdFilter implements RecordFilter { private final String _idItem; public KeyByItemIdFilter(String idItem){ _idItem = idItem; } public boolean matches(byte[] candidate) { RecordKey key = KeyTranslator.byte2RecordKey(candidate); return key.getIdItem().equalsIgnoreCase(_idItem); } } <file_sep>/Source/PDM-Trabalho Final/src/connector/IConnectionDecorator.java package connector; public interface IConnectionDecorator { public void addParameter(String key, Object value); public Object removeParameter(String key); public void setMethod(String method); public void setUrl(String url); public void init(); public void send(); public void cancelRequest(); public boolean isResponseOk(); public byte[] getResponse(); public void setCompleteListener(IConnectionListener listener); public void setFailListener(IConnectionListener listener); } <file_sep>/Source/PDM-Trabalho Final/src/asyncDispatch/AsyncDispatcher.java package asyncDispatch; /** * Code taken from */ /** * Singleton class that performs asynchronous execution requests. */ public final class AsyncDispatcher implements Runnable { /** * Interface that specifies the contract to be supported by asynchronous * execution request items. */ public static interface IDelegate { /** * Method that contains the code to be asynchronously executed. * * @param params The asynchronously executed method parameters. * @return The asynchronously executed method result. */ Object invoke(Object[] params); } /** * Interface that specifies the contract to be supported by asynchronous * execution completion notification callbacks. */ public static interface ICallback { /** * Method that contains the asynchronous execution completion notification * code. * * @param result The asynchronously executed method result */ void invoke(Object result); } /** * Singleton instance. */ private static final AsyncDispatcher instance = new AsyncDispatcher(); /** * Internal thread used to perform asynchronous execution requests. */ private final Thread dispatcher; /** * The pending asynchronous execution request. If null, no request is pending. */ private IDelegate currentExecutionItem; /** * The pending asynchronous execution request parameters. */ private Object[] currentExecutionItemParams; /** * The pending asynchronous execution request callback for completion notification. */ private ICallback currentExecutionItemCallback; /** * Initiates the <code>AsyncDispatcher</code> instance. */ private AsyncDispatcher() { currentExecutionItem = null; dispatcher = new Thread(this); dispatcher.start(); } /** * Helper method that schedules the given request for execution. * * @param request The requested execution item. * @param requestParams The requested execution item's parameters. * @param requestCompletionCallback The requested execution item's completion notification callback. */ private void scheduleRequest(IDelegate request, Object[] requestParams, ICallback requestCompletionCallback) { currentExecutionItem = request; currentExecutionItemParams = requestParams; currentExecutionItemCallback = requestCompletionCallback; // Signal internal thread notifyAll(); } /** * Method that contains the code to be executed by the internal dispatcher thread. * * Note. Usually, and for code robustness, this method should not be public but, this * way, there is no need to define yet another class (reducing footprint and working set). */ public void run() { try { while (true) { IDelegate executionItem = null; Object[] executionItemParams = null; ICallback executionItemCallback = null; synchronized (this) { while (currentExecutionItem == null) { wait(); } executionItem = currentExecutionItem; executionItemParams = currentExecutionItemParams; executionItemCallback = currentExecutionItemCallback; // Signal waiting threads currentExecutionItem = null; notifyAll(); } // Dispatch request Object result = executionItem.invoke(executionItemParams); // Signal completion (if required) if (executionItemCallback != null) { executionItemCallback.invoke(result); } } } catch (InterruptedException ie) { // Thread termination signaled (used in dispose) } } /** * Accessor method for getting the singleton instance. * * @return The singleton instance. */ public static AsyncDispatcher getInstance() { return instance; } /** * Method that issues an asynchronous execution request with the given parameters. Completion notification * is signaled by calling the given callback. The callback execution is performed by the internal thread. * * @param executionItem The requested execution item. * @param params The requested execution item's parameters. * @param callback The requested execution item's completion notification callback. If <code>null</code> * then no completion notification is performed. The callback will be executed by the internal thread. * @param wait Flag indicating whether the caller wishes to wait for the dispatcher thread to be available. * Note that the thread may be servicing a previously made request. * @return <code>true</code> if the request was successfully scheduled for servicing, <code>false</code> otherwise. * The return value will always be <code>true</code> if the caller specifies that it is willing to wait for * request scheduling. * @throws InterruptedException If the calling thread is interrupted. */ public boolean dispatch(IDelegate executionItem, Object[] params, ICallback callback, boolean wait) throws InterruptedException { synchronized (this) { // No request is being serviced. Schedule current one. if (currentExecutionItem == null) { scheduleRequest(executionItem, params, callback); return true; } // A request is being serviced. // Don't care to wait. if (!wait) { return false; } // Wait for pending request service completion. while (currentExecutionItem != null) { wait(); } // No request is being serviced. Schedule current one. scheduleRequest(executionItem, params, callback); return true; } } /** * Disposes the <code>AsyncDispatcher</code> instance. Once called, the instance * no longer can be used. */ public void dispose() { // Terminate internal thread dispatcher.interrupt(); } } <file_sep>/Source/PDM-Trabalho Final/src/domainObjects/translator/IITemTranslator.java package domainObjects.translator; import domainObjects.Item; public interface IITemTranslator { public byte[] item2Byte(Item item); public Item byte2Item(byte[] item); } <file_sep>/Source/PDM-Trabalho Final/src/domainObjects/Query.java package domainObjects; import java.util.Date; public class Query { private int _category; private String[] _keywords; private String _location; private Date _to; private Date _from; public int getCategory() { return _category; } public void setCategory(int category) { this._category = category; } public String[] getKeywords() { return _keywords; } public void setKeywords(String[] keywords) { this._keywords = keywords; } public String getLocation() { return _location; } public void setLocation(String location) { this._location = location; } public Date getTo() { return _to; } public void setTo(Date to) { this._to = to; } public Date getFrom() { return _from; } public void setFrom(Date from) { this._from = from; } } <file_sep>/Source/PDM-Trabalho Final/src/TestPackage/ItemRecordStoreTest.java /* * RecordStoreTest.java * JMUnit based test * * Created on 18/Ago/2010, 17:32:56 */ package TestPackage; import domainObjects.Item; import java.util.Date; import java.util.Vector; import jmunit.framework.cldc10.*; import storage.IRepository; import storage.RecStoreRepository; public class ItemRecordStoreTest extends TestCase { public ItemRecordStoreTest() { //The first parameter of inherited constructor is the number of test cases super(7,"ItemRecordStoreTest"); } public void test(int testNumber) throws Throwable { switch(testNumber){ case 0: isRecordStoreNotNull(); break; case 1: canAddItem(); break; case 2: canGetItem(); break; case 3: canGetItemsByCat(); break; case 4: canDeleteItem(); break; case 5: canInsertTwicetheSameItem(); break; case 6: canUpdateItem(); break; default: break; } } //0 private void isRecordStoreNotNull(){ IRepository rep = new RecStoreRepository(); assertNotNull(rep); } //1 private void canAddItem(){ IRepository rep = new RecStoreRepository(); Item i = new Item(1, 1, "tittle", "description", null, new Date()); rep.addItem(i); assertTrue(rep.getItemsCount() == 1); } //2 private void canGetItem(){ IRepository rep = new RecStoreRepository(); Item i = new Item(1, 1, "tittle", "description", null, new Date()); rep.addItem(i); Item newItem = rep.getItemByid(i.getId()); assertEquals(i.getCategory(), newItem.getCategory()); } //3 private void canGetItemsByCat(){ Item i1 = new Item(1, 1, "tittle1", "description1", null, new Date()); Item i2 = new Item(2, 1, "tittle2", "description2", null, new Date()); Item i3 = new Item(3, 2, "tittle3", "description3", null, new Date()); Item i4 = new Item(4, 2, "tittle4", "description4", null, new Date()); Item i5 = new Item(5, 2, "tittle5", "description5", null, new Date()); Item i6 = new Item(6, 2, "tittle6", "description6", null, new Date()); Item i7 = new Item(7, 3, "tittle7", "description7", null, new Date()); Item i8 = new Item(8, 1, "tittle8", "description8", null, new Date()); IRepository rep = new RecStoreRepository(); rep.addItem(i1); rep.addItem(i2); rep.addItem(i3); rep.addItem(i4); rep.addItem(i5); rep.addItem(i6); rep.addItem(i7); rep.addItem(i8); Vector v = rep.getItemsByCat(2); assertEquals(v.size(), 4); v = rep.getItemsByCat(1); assertEquals(v.size(), 3); v = rep.getItemsByCat(3); assertEquals(v.size(), 1); } //4 private void canDeleteItem(){ IRepository rep = new RecStoreRepository(); int count = rep.getItemsCount(); Item i3 = new Item(3, 2, "tittle3", "description3", null, new Date()); rep.deleteItem(i3); assertTrue(rep.getItemsCount() == --count); } //5 private void canInsertTwicetheSameItem(){ IRepository rep = new RecStoreRepository(); Item i9 = new Item(9, 1, "tittle9", "description9", null, new Date()); int count = rep.getItemsCount(); rep.addItem(i9); assertTrue(rep.getItemsCount() == ++count); rep.addItem(i9); assertFalse(rep.getItemsCount() == ++count); } //6 private void canUpdateItem(){ IRepository rep = new RecStoreRepository(); Item i10 = new Item(10, 1, "tittle10", "description10", null, new Date()); rep.addItem(i10); i10.setDesc("description10_new"); rep.addItem(i10); Item newItem = rep.getItemByid(10); assertTrue(newItem.getDesc().equals("description10_new")); } } <file_sep>/Source/PDM-Trabalho Final/src/domainObjects/translator/ConfigTranslator.java package domainObjects.translator; import constants.Constants; import domainObjects.Config; public class ConfigTranslator { public static byte[] config2Byte(Config config) { String configStr = config.getRecordsPerPage() + Constants.TRANSLATOR_SEP + (config.getSaveOwnItems() ? 1 : 0) + Constants.TRANSLATOR_SEP; return configStr.getBytes(); } public static Config byte2Config(byte[] config) { if (config == null) return new Config( Constants.CONFIG_DEFAULT_RECORDSPERPAGE, Constants.CONFIG_DEFAULT_SAVESENTITEMS ); String configStr = new String(config); int index, lastIndex = 0; int sepLen = Constants.TRANSLATOR_SEP.length(); index = configStr.indexOf(Constants.TRANSLATOR_SEP, 0); //Getting records per page int recsPerPage = Integer.parseInt(configStr.substring(lastIndex, index)); lastIndex = index + sepLen; index = configStr.indexOf(Constants.TRANSLATOR_SEP, lastIndex); //Getting save own items flag boolean saveOwnItems = configStr.substring(lastIndex, index).equals("1") ? true : false; return new Config(recsPerPage, saveOwnItems); } } <file_sep>/Source/PDM-Trabalho Final/src/storage/Exception/NotExpectedException.java /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package storage.Exception; /** * * @author nuno.sousa */ public class NotExpectedException extends RuntimeException { public NotExpectedException(){ super(); } public NotExpectedException(String message){ super(message); } } <file_sep>/Source/PDM-Trabalho Final/src/screens/CategorySelectorScreen.java package screens; import constants.Constants; import entryPoint.PenPAL; import javax.microedition.lcdui.Choice; import javax.microedition.lcdui.ChoiceGroup; import javax.microedition.lcdui.Command; import javax.microedition.lcdui.Displayable; public class CategorySelectorScreen extends FormScreen{ private int _targetScreen; private final ChoiceGroup catSelector = new ChoiceGroup("Category", Choice.POPUP, Constants.CATEGORIES, null); public CategorySelectorScreen(PenPAL owner) { super(owner,Constants.APP_TITLE,null); append(catSelector); } public CategorySelectorScreen setTargetScreen(int targetScreen) { this._targetScreen = targetScreen; return this; } public void cls() { } public void commandAction(Command cmd, Displayable d) { if (cmd == cmdOk) { owner.resolveCategorySelection( catSelector.getSelectedIndex(), _targetScreen ); //owner.showItemListScreen(catSelector.getSelectedIndex(), _targetScreen); } else if (cmd == cmdBack) { owner.showMainScreen(); } } }
b8f453385de68fdb0a88d1db859f0761d56ad819
[ "C#", "Java" ]
17
Java
RicardoRomao/iselpdm
b9bbde3f0044391f49b5ed2ff53a0cd409d81a63
1082b60e2f46fefb8788a189a22c7522b3c5aa45
refs/heads/master
<repo_name>artsiom-sinitski/AvsTokenWallet<file_sep>/test/TestAvsTokenWallet.js const AvsToken = artifacts.require("AvsToken.sol"); contract('AvsToken', async (accounts) => { it("Checking initial contract state", async () => { let instance = await AvsToken.deployed(); let varTest = await instance.totalSupply.call(); assert.equal(varTest.valueOf(), 10000); varTest = await instance.getName.call(); assert.equal(varTest.valueOf(), "AvsToken"); varTest = await instance.getSymbol.call(); assert.equal(varTest.valueOf(), "AvS"); varTest = await instance.getDecimals.call(); assert.equal(varTest.valueOf(), 2); }); it("Checking contract getters & setters", async () => { let instance = await AvsToken.deployed(); let varRes = await instance.setDecimals(32); let varTest = await instance.getDecimals.call(); assert.equal(varTest.valueOf(), 32); await instance.setDecimals(33); varTest = await instance.getDecimals.call(); assert.equal(varTest.valueOf(), 32); await instance.setDecimals(-1); varTest = await instance.getDecimals.call(); assert.equal(varTest.valueOf(), 32); await instance.setDecimals(0); varTest = await instance.getDecimals.call(); assert.equal(varTest.valueOf(), 0); await instance.setDecimals(16); varTest = await instance.getDecimals.call(); assert.equal(varTest.valueOf(), 16); }); it("Testing basic wallet functionality", async() => { let instance = await AvsToken.deployed(); let account = AvsToken.class_defaults.from; //'0x3a1d2e87865938c0EB6CAC4a07203A96810bb78d'; let toAddress = '0xDbBA21055f74F7Be31d5a32d7acED73062071a32'; let varResult = await instance.balanceOf(account); assert.equal(varResult.valueOf(), 10000); await instance.burn(99); varResult = await instance.balanceOf(account); assert.equal(varResult.valueOf(), 9901); await instance.transfer(toAddress, 1); varResult = await instance.balanceOf(account); assert.equal(varResult.valueOf(), 9900); }); })
fc5a191165626df6c06184508252a38548eb78b2
[ "JavaScript" ]
1
JavaScript
artsiom-sinitski/AvsTokenWallet
edc732db76d7a785f5a0623ee469a0ad176d28cb
66718df142136ab6d8fb0e4d4270fdf8c5d612b6
refs/heads/master
<file_sep>############################################################################ # Created by: Prof. <NAME>, D.Sc. # UFF - Universidade Federal Fluminense (Brazil) # email: <EMAIL> # Course: Metaheuristics # Lesson: Flower Pollination Algorithm # Citation: # PEREIRA, V. (2018). Project: Metaheuristic-Flower_Pollination_Algorithm, File: Python-MH-Flower Pollination Algorithm.py, GitHub repository: <https://github.com/Valdecy/Metaheuristic-Flower_Pollination_Algorithm> ############################################################################ # Required Libraries import numpy as np import math import random import os from scipy.special import gamma # Function def target_function(): return # Function: Initialize Variables def initial_position(flowers = 3, min_values = [-5,-5], max_values = [5,5], target_function = target_function): position = np.zeros((flowers, len(min_values)+1)) for i in range(0, flowers): for j in range(0, len(min_values)): position[i,j] = random.uniform(min_values[j], max_values[j]) position[i,-1] = target_function(position[i,0:position.shape[1]-1]) return position #Function Levy Distribution def levy_flight(beta = 1.5): beta = beta r1 = int.from_bytes(os.urandom(8), byteorder = "big") / ((1 << 64) - 1) r2 = int.from_bytes(os.urandom(8), byteorder = "big") / ((1 << 64) - 1) sig_num = gamma(1+beta)*np.sin((np.pi*beta)/2.0) sig_den = gamma((1+beta)/2)*beta*2**((beta-1)/2) sigma = (sig_num/sig_den)**(1/beta) levy = (0.01*r1*sigma)/(abs(r2)**(1/beta)) return levy # Function: Global Pollination def pollination_global(position, best_global, flower = 0, gama = 0.5, lamb = 1.4, min_values = [-5,-5], max_values = [5,5], target_function = target_function): x = np.copy(best_global) for j in range(0, len(min_values)): x[j] = np.clip((position[flower, j] + gama*levy_flight(lamb)*(position[flower, j] - best_global[j])),min_values[j],max_values[j]) x[-1] = target_function(x[0:len(min_values)]) return x # Function: Local Pollination def pollination_local(position, best_global, flower = 0, nb_flower_1 = 0, nb_flower_2 = 1, min_values = [-5,-5], max_values = [5,5], target_function = target_function): x = np.copy(best_global) for j in range(0, len(min_values)): r = int.from_bytes(os.urandom(8), byteorder = "big") / ((1 << 64) - 1) x[j] = np.clip((position[flower, j] + r*(position[nb_flower_1, j] - position[nb_flower_2, j])),min_values[j],max_values[j]) x[-1] = target_function(x[0:len(min_values)]) return x # FPA Function. def flower_pollination_algorithm(flowers = 3, min_values = [-5,-5], max_values = [5,5], iterations = 50, gama = 0.5, lamb = 1.4, p = 0.8, target_function = target_function): count = 0 position = initial_position(flowers = flowers, min_values = min_values, max_values = max_values, target_function = target_function) best_global = np.copy(position[position[:,-1].argsort()][0,:]) x = np.copy(best_global) while (count <= iterations): print("Iteration = ", count, " f(x) = ", best_global[-1]) for i in range(0, position.shape[0]): nb_flower_1 = int(np.random.randint(position.shape[0], size = 1)) nb_flower_2 = int(np.random.randint(position.shape[0], size = 1)) while nb_flower_1 == nb_flower_2: nb_flower_1 = int(np.random.randint(position.shape[0], size = 1)) r = int.from_bytes(os.urandom(8), byteorder = "big") / ((1 << 64) - 1) if (r < p): x = pollination_global(position, best_global, flower = i, gama = gama, lamb = lamb, min_values = min_values, max_values = max_values, target_function = target_function) else: x = pollination_local(position, best_global, flower = i, nb_flower_1 = nb_flower_1, nb_flower_2 = nb_flower_2, min_values = min_values, max_values = max_values, target_function = target_function) if (x[-1] <= position[i,-1]): for j in range(0, position.shape[1]): position[i,j] = x[j] value = np.copy(position[position[:,-1].argsort()][0,:]) if (best_global[-1] > value[-1]): best_global = np.copy(value) count = count + 1 print(best_global) return best_global ######################## Part 1 - Usage #################################### # Function to be Minimized (Six Hump Camel Back). Solution -> f(x1, x2) = -1.0316; x1 = 0.0898, x2 = -0.7126 or x1 = -0.0898, x2 = 0.7126 def six_hump_camel_back(variables_values = [0, 0]): func_value = 4*variables_values[0]**2 - 2.1*variables_values[0]**4 + (1/3)*variables_values[0]**6 + variables_values[0]*variables_values[1] - 4*variables_values[1]**2 + 4*variables_values[1]**4 return func_value fpa = flower_pollination_algorithm(flowers = 25, min_values = [-5,-5], max_values = [5,5], iterations = 500, gama = 0.1, lamb = 1.5, p = 0.8, target_function = six_hump_camel_back) # Function to be Minimized (Rosenbrocks Valley). Solution -> f(x) = 0; xi = 1 def rosenbrocks_valley(variables_values = [0,0]): func_value = 0 last_x = variables_values[0] for i in range(1, len(variables_values)): func_value = func_value + (100 * math.pow((variables_values[i] - math.pow(last_x, 2)), 2)) + math.pow(1 - last_x, 2) return func_value fpa = flower_pollination_algorithm(flowers = 175, min_values = [-5,-5], max_values = [5,5], iterations = 1000, gama = 0.1, lamb = 1.5, p = 0.8, target_function = rosenbrocks_valley)
8b275b21461c147fdb9021d196ec7c2b3ead5c12
[ "Python" ]
1
Python
Valdecy/Metaheuristic-Flower_Pollination_Algorithm
6831340ce4e5ffddf5899c34244500dd57019f32
59e5d7ee705c63e75ed96d597e360be91f2d9d35
refs/heads/master
<file_sep>package com.example.asb.tabtest; import android.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; /** * Created by asb on 8/9/16. */ public class FragmentTwo extends Fragment { public FragmentTwo() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.layout1, container, false); TextView t1 = (TextView) view.findViewById(R.id.textView2); t1.setText("!@#"); return view; } }
40c0915402e1d95ba1853a2fd7b07ece4f623920
[ "Java" ]
1
Java
TurnerNic/TabTest
51618f0382f1dda6e1c10fccb3fca2d5f6191999
f1de201d657cfb6c2e487bfe71932dd70994ea1a
refs/heads/master
<repo_name>p8009inzynierka/Inzynierka<file_sep>/administrator/include/menu.php <div id="sidebar-wrapper"> <ul class="sidebar-nav"> <li> <a href="javascript:;" data-toggle="collapse" data-target="#demo" style="font-size:16px"><i class="fa fa-fw fa-arrows-v"></i><span class="glyphicon glyphicon-user"></span>&nbsp;Witaj, <?php echo $row['user_name']; ?>&nbsp;<span class="caret"></span><i class="fa fa-fw fa-caret-down"></i></a> <ul id="demo" class="collapse" style="list-style-type: none"> <li> <a href="profil.php"><span class="glyphicon glyphicon-user"></span>&nbsp;Zobacz profil</a> </li> <li> <a href="#"><span class="glyphicon glyphicon-cog"></span>Ustawienia</a> </li> <li> <a href="logout.php"><span class="glyphicon glyphicon-log-out"></span>&nbsp;Wyloguj</a> </li> </ul> </li> <li> <a href="zarzadzanie.php">Panel Administratora</a> </li> <li> <a href="zarzadzanie-domenami.php">Domeny</a> </li> <li> <a href="aktywnosc.php">Aktywność</a> </li> <li> <a href="kopia-zapasowa.php">Kopia zapasowa</a> </li> <li> <a href="kontakt.php">Kontakt</a> </li> </ul> </div><file_sep>/administrator/js/pie.js var randomScalingFactor = function() { return Math.round(Math.random() * 100); }; var lineChartData = { labels: ["01-06", "02-06", "03-06", "04-06", "05-06", "06-06", "07-06", "08-06", "09-06", "10-06"], datasets: [{ label: "Liczba odwiedzin", borderColor: window.chartColors.black, // kolor linii backgroundColor: window.chartColors.blue, //kolor kropek fill: true, data: [100, 210, 150, 200, 324, 321, 222, 543, 223, 432], yAxisID: "y-axis-1", }] }; var config = { type: 'pie', data: { datasets: [{ data: [100, 210, 150, 200, 324], backgroundColor: [ window.chartColors.red, window.chartColors.orange, window.chartColors.yellow, window.chartColors.green, window.chartColors.blue, ], label: 'Dataset 1' }], labels: ["eu.pl", "chartowo.pl", "suchylas.pl", "winogrady.eu", "xyz.pl"], }, options: { responsive: true } }; window.onload = function() { var ctx = document.getElementById("chart-area").getContext("2d"); window.myPie = new Chart(ctx, config); var ctx = document.getElementById("canvas").getContext("2d"); window.myLine = Chart.Line(ctx, { data: lineChartData, options: { responsive: true, hoverMode: 'index', stacked: false, title:{ display: true, text:'Statystyka odwiedzin' }, scales: { yAxes: [{ type: "linear", // only linear but allow scale type registration. This allows extensions to exist solely for log scale for instance display: true, position: "left", id: "y-axis-1", }, { // grid line settings gridLines: { drawOnChartArea: true, // only want the grid lines for one axis to show up }, }], } } }); }; document.getElementById('randomizeData').addEventListener('click', function() { config.data.datasets.forEach(function(dataset) { dataset.data = dataset.data.map(function() { return randomScalingFactor(); }); }); window.myPie.update(); }); var colorNames = Object.keys(window.chartColors); document.getElementById('addDataset').addEventListener('click', function() { var newDataset = { backgroundColor: [], data: [], label: 'New dataset ' + config.data.datasets.length, }; for (var index = 0; index < config.data.labels.length; ++index) { newDataset.data.push(randomScalingFactor()); var colorName = colorNames[index % colorNames.length];; var newColor = window.chartColors[colorName]; newDataset.backgroundColor.push(newColor); } config.data.datasets.push(newDataset); window.myPie.update(); }); document.getElementById('removeDataset').addEventListener('click', function() { config.data.datasets.splice(0, 1); window.myPie.update(); }); <file_sep>/administrator/kontakt.php <?php session_start(); if(!isset($_SESSION['user_session'])) { header("Location: index.php"); } include_once 'dbconfig.php'; $stmt = $db_con->prepare("SELECT * FROM tbl_users WHERE user_id=:uid"); $stmt->execute(array(":uid"=>$_SESSION['user_session'])); $row=$stmt->fetch(PDO::FETCH_ASSOC); ?> <!DOCTYPE html> <html lang="pl-PL"> <?php include 'include/header.php'; ?> <body> <div id="wrapper"> <?php include 'include/menu.php'; ?> <!-- Page Content --> <div id="page-content-wrapper"> <div class="container-fluid"> <div class="row"> <div class="col-lg-2"> <a href="#menu-toggle" class="btn btn-default" id="menu-toggle"><img src="img/menu-toggle.png"></img></a> </div> <div class="col-lg-8"> <h1 style="text-align: center ">Kontakt</h1> </div> <div class="col-lg-2"> </div> </div> </div> </div> </div> <!-- jQuery --> <script src="js/jquery.js"></script> <!-- Bootstrap Core JavaScript --> <script src="js/bootstrap.min.js"></script> <!-- Menu Toggle Script --> <script> $("#menu-toggle").click(function(e) { e.preventDefault(); $("#wrapper").toggleClass("toggled"); }); </script> </body> </html><file_sep>/js/check-domain.js $('#sprawdz').click(function(){ if (! $('#domain').val()) { // Puste pole $('#domain-info').html('<strong>Podaj domenę!</strong><br>'); } else { $.post( 'select.php', { domain: $('#domain').val() }, function (data) { console.log(data); if (data !== false && 'domain' in data) { $('#domain-info').html('<strong>Domena została już zarejestrowana!<strong><br>'); } else { $('#domain-info').html('<strong>Domena jest wolna!</strong><br>'); } } ) } });<file_sep>/select.php <?php /* Plik potrzebny do sprawdzania dostepnosci domeny */ include_once 'dbconfig.php'; $sth = $db_con->prepare("SELECT domain, paid FROM domeny WHERE domain = :domain"); $sth->execute(array( 'domain' => $_POST['domain'] )); header('Content-Type: application/json'); echo json_encode($sth->fetch()); <file_sep>/rejestracja.php <!DOCTYPE html> <html lang="pl"> <?php include 'include/header.php'; ?> <body> <?php include 'include/navbar.php'; ?> <div class="container"> <div class="row"> <div class="col-md-4"> <div class="signin-form"> <form class="form-signin" method="post" id="register-form"> <h2 class="form-signin-heading">Rejestracja</h2><hr /> <div id="error"></div> <div class="form-group"> <input type="text" class="form-control" placeholder="Nazwa użytkownika" name="user_name" id="user_name" /> </div> <div class="form-group"> <input type="email" class="form-control" placeholder="Adres e-mail" name="user_email" id="user_email" /> <span id="check-e"></span> </div> <div class="form-group"> <input type="<PASSWORD>" class="form-control" placeholder="<PASSWORD>" name="password" id="password" /> </div> <div class="form-group"> <input type="password" class="form-control" placeholder="<PASSWORD>ło" name="cpassword" id="cpassword" /> </div> <hr /> <div class="form-group"> <button type="submit" class="btn btn-default" name="btn-save" id="btn-submit"> <span class="glyphicon glyphicon-log-in"></span> &nbsp; Zarejestruj </button> </div> </form> </div> </div> <div class="col-md-8"> <img id="image-domain" class="img-responsive img-rounded" src="img/rejestracja.png" alt=""> </div> </div> <!-- Footer --> <?php include 'include/footer.php'; ?> </div> <!-- jQuery --> <script src="js/jquery.js"></script> <!-- Other --> <script type="text/javascript" src="js/validation.min.js"></script> <script type="text/javascript" src="js/rejestracja.js"></script> <!-- Bootstrap Core JavaScript --> <script src="js/bootstrap.min.js"></script> </body> </html><file_sep>/js/ajax_form.js <script type="text/javascript"> $(function() { $("#submit").click(function() { var login = $('#login').val(); var password = $('#<PASSWORD>').val(); var dataString = 'login='+ login + '&password=' + password; $.ajax({ type: 'POST', url: 'register.php', data: dataString, success: function(data) { if( data == "" ) alert( 'Nie uzupełniłeś wszystkich pól!' ); else window.location = window.location; } }); }); }); </script><file_sep>/administrator/zarzadzanie.php <?php session_start(); if(!isset($_SESSION['user_session'])) { header("Location: index.php"); } include_once 'dbconfig.php'; $stmt = $db_con->prepare("SELECT * FROM tbl_users WHERE user_id=:uid"); $stmt->execute(array(":uid"=>$_SESSION['user_session'])); $row=$stmt->fetch(PDO::FETCH_ASSOC); ?> <!DOCTYPE html> <html lang="pl-PL"> <?php include 'include/header.php'; ?> <body> <div id="wrapper"> <?php include 'include/menu.php'; ?> <!-- Page Content --> <div id="page-content-wrapper"> <div class="container-fluid"> <div class="row"> <div class="col-lg-2"> <a href="#menu-toggle" class="btn btn-default" id="menu-toggle"><img src="img/menu-toggle.png"></img></a> </div> <div class="col-lg-8"> <h1 style="text-align: center ">Panel Administratora</h1> </div> <div class="col-lg-2"> </div> <div class="col-lg-4"> <div style="width:100%;"> <canvas id="canvas" width="100%" height="100%"></canvas> </div> </div> <div class="col-lg-4"> <canvas id="chart-area" style="display: block; " width="100%" height="100%"> </canvas> <script src="js/pie.js"></script> </div> <div class="col-lg-4"> <div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title"><i class="glyphicon glyphicon-time"></i> Ostatnie zdarzenia</h3> </div> <div class="panel-body"> <div class="list-group"> <a href="#" class="list-group-item"> <span class="badge">teraz</span> <i class="glyphicon glyphicon-euro"></i> Odnotowano płatność </a> <a href="#" class="list-group-item"> <span class="badge">2 minuty temu</span> <i class="glyphicon glyphicon-plus"></i> Kupiono domenę </a> <a href="#" class="list-group-item"> <span class="badge">23 minuty temu</span> <i class="glyphicon glyphicon-user"></i> Dodano nowego użytkownika </a> <a href="#" class="list-group-item"> <span class="badge">46 minuty temu</span> <i class="glyphicon glyphicon-plus"></i> Kupiono domenę </a> <a href="#" class="list-group-item"> <span class="badge">1 godzina temu</span> <i class="glyphicon glyphicon-ok"></i> Wykonano automatyczny backup </a> <a href="#" class="list-group-item"> <span class="badge">2 godziny temu</span> <i class="glyphicon glyphicon-user"></i> Dodano nowego użytkownika </a> <a href="#" class="list-group-item"> <span class="badge">wczoraj</span> <i class="glyphicon glyphicon-minus"></i> Usunięto domenę </a> <a href="#" class="list-group-item"> <span class="badge">wczoraj</span> <i class="glyphicon glyphicon-remove"></i> Domena nieopłacona </a> </div> <div class="text-right"> <a href="#">Pokaż całą aktywność <i class="fa fa-arrow-circle-right"></i></a> </div> </div> </div> </div> <div class="col-lg-12"> <div class="panel panel-default"> <!-- Default panel contents --> <div class="panel-heading" style="text-align: center">Ostatnio zarejestrowane domeny</div> <!-- Table --> <table class="table"> <tbody> <tr> <td>Lp.</td><td>Domena</td><td>Użytkownik</td><td>Adres e-mail</td> </tr> <tr> <td>1</td><td>sad.chartowo.pl</td><td>maniek123</td><td><EMAIL></td> </tr> <tr> <td>2</td><td>remonty.eu.pl</td><td>domdlaciebie</td><td><EMAIL></td> </tr> <tr> <td>3</td><td>rtv.suchylas.pl</td><td>rtveuroagd</td><td><EMAIL></td> </tr> <tr> <td>4</td><td>blank</td><td>blank</td><td>blank</td> </tr> <tr> <td>5</td><td>blank</td><td>blank</td><td>blank</td> </tr> <tr> <td>6</td><td>blank</td><td>blank</td><td>blank</td> </tr> <tr> <td>7</td><td>blank</td><td>blank</td><td>blank</td> </tr> <tr> <td>8</td><td>blank</td><td>blank</td><td>blank</td> </tr> <tr> <td>9</td><td>blank</td><td>blank</td><td>blank</td> </tr> <tr> <td>10</td><td>blank</td><td>blank</td><td>blank</td> </tr> </tbody> </table> </div> </div> </div> </div> </div> </div> <!-- jQuery --> <script src="js/jquery.js"></script> <!-- Bootstrap Core JavaScript --> <script src="js/bootstrap.min.js"></script> <!-- Menu Toggle Script --> <script> $("#menu-toggle").click(function(e) { e.preventDefault(); $("#wrapper").toggleClass("toggled"); }); </script> </body> </html><file_sep>/index.php <!DOCTYPE html> <html lang="pl"> <?php include 'include/header.php'; ?> <body> <?php include 'include/navbar.php'; ?> <div class="container"> <div class="row"> <div class="col-md-6"> <h2>Sprawdź dostępność domeny</h2> <div class="form-signin"> <div class="form-group"> <input type="text" class="form-control" placeholder="Podaj domenę" id="domain"/><form action="..."> <select id="suffix"> <option>eu.pl</option> <option>chartowo.pl</option> <option>winogrady.eu</option> </select> </form> </div> <hr /> <span id="domain-info"></span> <div class="form-group"> <br> <button type="submit" class="btn btn-default" name="btn-login" id="sprawdz" > <span class="glyphicon glyphicon-log-in"></span> &nbsp; Sprawdź &nbsp; </button> </div> </div> </div> <div class="col-md-6"> <h2>Logowanie</h2> <div class="signin-form"> <form class="form-signin" method="post" id="login-form"> <div id="error"></div> <div class="form-group"> <input type="email" class="form-control" placeholder="Adres e-mail" name="user_email" id="user_email" /> <span id="check-e"></span> </div> <div class="form-group"> <input type="<PASSWORD>" class="form-control" placeholder="<PASSWORD>" name="password" id="password" /> </div> <hr /> <div class="form-group"> <button type="submit" class="btn btn-default" name="btn-login" id="btn-login"> <span class="glyphicon glyphicon-log-in"></span> &nbsp; Zaloguj &nbsp; </button> </div> </form> </div> </div> </div> <!-- Footer --> <?php include 'include/footer.php'; ?> </div> <!-- jQuery --> <script src="js/jquery.js"></script> <!-- Bootstrap Core JavaScript --> <script src="js/bootstrap.min.js"></script> <!-- Domain checker --> <script type="text/javascript" src="js/check-domain.js"></script> <!-- Other --> <script type="text/javascript" src="js/validation.min.js"></script> <script type="text/javascript" src="js/logowanie.js"></script> </body> </html><file_sep>/administrator/kopia-zapasowa.php <?php session_start(); if(!isset($_SESSION['user_session'])) { header("Location: index.php"); } include_once 'dbconfig.php'; $stmt = $db_con->prepare("SELECT * FROM tbl_users WHERE user_id=:uid"); $stmt->execute(array(":uid"=>$_SESSION['user_session'])); $row=$stmt->fetch(PDO::FETCH_ASSOC); ?> <!DOCTYPE html> <html lang="pl-PL"> <?php include 'include/header.php'; ?> <body> <div id="wrapper"> <?php include 'include/menu.php'; ?> <!-- Page Content --> <div id="page-content-wrapper"> <div class="container-fluid"> <div class="row"> <div class="col-lg-1"> <a href="#menu-toggle" class="btn btn-default" id="menu-toggle"><img src="img/menu-toggle.png"></img></a> </div> <div class="col-md-6"> <h2>Sprawdź dostępność domeny</h2> <div class="form-signin"> <div class="form-group"> <input type="text" class="form-control" placeholder="Podaj domenę" id="domain" /> </div> <hr /> <span id="domain-info"></span> <div class="form-group"> <br> <button type="submit" class="btn btn-default" name="btn-login" id="sprawdz"> <span class="glyphicon glyphicon-log-in"></span> &nbsp; Sprawdź &nbsp; </button> </div> </div> </div> <div class="col-md-5"> <h2>Logowanie</h2> <div class="signin-form"> <form class="form-signin" method="post" id="login-form"> <div id="error"></div> <div class="form-group"> <input type="email" class="form-control" placeholder="Adres e-mail" name="user_email" id="user_email" /> <span id="check-e"></span> </div> <div class="form-group"> <input type="<PASSWORD>" class="form-control" placeholder="<PASSWORD>" name="password" id="password" /> </div> <hr /> <div class="form-group"> <button type="submit" class="btn btn-default" name="btn-login" id="btn-login"> <span class="glyphicon glyphicon-log-in"></span> &nbsp; Zaloguj &nbsp; </button> </div> </form> </div> </div> </div> </div> </div> </div> <!-- jQuery --> <script src="js/jquery.js"></script> <!-- Bootstrap Core JavaScript --> <script src="js/bootstrap.min.js"></script> <!-- Menu Toggle Script --> <script> $("#menu-toggle").click(function(e) { e.preventDefault(); $("#wrapper").toggleClass("toggled"); }); </script> </body> </html><file_sep>/administrator/zarzadzanie-domenami.php <?php session_start(); if(!isset($_SESSION['user_session'])) { header("Location: index.php"); } include_once 'dbconfig.php'; $stmt = $db_con->prepare("SELECT * FROM tbl_users WHERE user_id=:uid"); $stmt->execute(array(":uid"=>$_SESSION['user_session'])); $row=$stmt->fetch(PDO::FETCH_ASSOC); ?> <!DOCTYPE html> <html lang="pl-PL"> <?php include 'include/header.php'; ?> <body> <div id="wrapper"> <?php include 'include/menu.php'; ?> <!-- Page Content --> <div id="page-content-wrapper"> <div class="container-fluid"> <div class="row"> <div class="col-lg-2"> <a href="#menu-toggle" class="btn btn-default" id="menu-toggle"><img src="img/menu-toggle.png"></img> </a> </div> <div class="col-lg-8"> <h1 style="text-align: center ">Zarządzanie domenami</h1> </div> <div class="col-lg-3"> </div> <div class="col-md-6"> <div class="form-signin"> <div class="form-group"> <input type="text" class="form-control" placeholder="Podaj domenę" id="domain" /> </div> <hr /> <span id="domain-info"></span> </div> </div> <div class="col-md-3"> </div> <div class="col-lg-12"> </div> <div class="col-lg-3"> </div> <div class="col-md-6"> <div class="form-signin"> <div class="form-group"> <input type="text" class="form-control" placeholder="Podaj e-mail - opcjonalnie przy dodawaniu/usuwaniu domeny" id="e-mail" /> </div> <hr /> <span id="domain-info"></span> </div> </div> <div class="col-md-3"> </div> <div style="text-align: center" class="col-md-12"> <div class="form-group"> <br> <button type="submit" class="btn btn-default" name="btn-login" id="sprawdz"> <span class="glyphicon glyphicon-log-in"></span> &nbsp; Sprawdź &nbsp;</button> <button type="submit" class="btn btn-default" name="btn-login" id="dodajbaza"> <span class="glyphicon glyphicon-plus"></span> &nbsp; Dodaj do bazy &nbsp;</button> <button type="submit" class="btn btn-default" name="btn-login" id="usunbaza"> <span class="glyphicon glyphicon-minus"></span> &nbsp; Usuń z bazy &nbsp;</button> <button type="submit" class="btn btn-default" name="btn-login" id="dodajhome"> <span class="glyphicon glyphicon-plus"></span> &nbsp; Dodaj do home.pl &nbsp;</button> <button type="submit" class="btn btn-default" name="btn-login" id="usunhome"> <span class="glyphicon glyphicon-minus"></span> &nbsp; Usuń z home.pl &nbsp;</button> </div> </div> <div class="col-md-12"> <h5>Sprawdź - służy do sprawdzania czy domena znajduje się w naszej bazie.</h5> <h5>Dodaj do bazy - służy do dodania domeny do naszej bazy. Użyj tej opcji jeśli zarejestrowałeś już domenę w home.pl. Podaj adres e-mail użykownika do którego ma należeć domena oraz czas wygaśnięcia domeny. Czas wygaśnięcia domeny = 0 - domena ważna 100 lat. Status domeny - opłacona.</h5> <h5>Usuń z bazy - służy do usuwania domeny z naszej bazy. Pola e-mail i data wygaśnięcia domeny nie są brane pod uwagę.</h5> <h5>Dodaj do home.pl - dodaje domenę do bazy i przypisuje do wpisanego adresu e-mail. Oznacza domenę na opłaconą do daty wygaśnięcia domeny.</h5> <h5>Usuń z home.pl - usuwa domenę z naszej bazy oraz z home.pl. Pola e-mail i data wygaśnięcia domeny nie są brane pod uwagę.</h5> </div> <div class="col-md-12"> <div class="panel-heading" style="text-align: center">Domeny Administratora</div> <!-- Table --> <table class="table"> <tbody> <tr> <td>Lp.</td><td>Domena</td><td>Data dodania domeny</td><td>Data wygaśnięcia domeny</td> </tr> <tr> <td>1</td><td>sad.chartowo.pl</td><td>05-06-2017</td><td>01-01-2100</td> </tr> </tbody> </table> </div> </div> </div> </div> <!-- jQuery --> <script src="js/jquery.js"></script> <!-- Bootstrap Core JavaScript --> <script src="js/bootstrap.min.js"></script> <!-- Menu Toggle Script --> <script> $("#menu-toggle").click(function(e) { e.preventDefault(); $("#wrapper").toggleClass("toggled"); }); </script> </body> </html><file_sep>/administrator/aktywnosc.php <?php session_start(); if(!isset($_SESSION['user_session'])) { header("Location: index.php"); } include_once 'dbconfig.php'; $stmt = $db_con->prepare("SELECT * FROM tbl_users WHERE user_id=:uid"); $stmt->execute(array(":uid"=>$_SESSION['user_session'])); $row=$stmt->fetch(PDO::FETCH_ASSOC); ?> <!DOCTYPE html> <html lang="pl-PL"> <?php include 'include/header.php'; ?> <body> <div id="wrapper"> <?php include 'include/menu.php'; ?> <!-- Page Content --> <div id="page-content-wrapper"> <div class="container-fluid"> <div class="row"> <div class="col-lg-2"> <a href="#menu-toggle" class="btn btn-default" id="menu-toggle"><img src="img/menu-toggle.png"></img> </a> </div> <div class="col-lg-8"> <h1 style="text-align: center ">Aktywność</h1> </div> <div class="col-lg-2"> </div> <div class="col-lg-12"> <div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title"><i class="glyphicon glyphicon-time"></i> Ostatnie zdarzenia</h3> </div> <div class="panel-body"> <div class="list-group"> <a href="#" class="list-group-item"> <span class="badge">teraz</span> <i class="glyphicon glyphicon-euro"></i> Odnotowano płatność </a> <a href="#" class="list-group-item"> <span class="badge">2 minuty temu</span> <i class="glyphicon glyphicon-plus"></i> Kupiono domenę </a> <a href="#" class="list-group-item"> <span class="badge">23 minuty temu</span> <i class="glyphicon glyphicon-user"></i> Dodano nowego użytkownika </a> <a href="#" class="list-group-item"> <span class="badge">46 minuty temu</span> <i class="glyphicon glyphicon-plus"></i> Kupiono domenę </a> <a href="#" class="list-group-item"> <span class="badge">1 godzina temu</span> <i class="glyphicon glyphicon-ok"></i> Wykonano automatyczny backup </a> <a href="#" class="list-group-item"> <span class="badge">2 godziny temu</span> <i class="glyphicon glyphicon-user"></i> Dodano nowego użytkownika </a> <a href="#" class="list-group-item"> <span class="badge">wczoraj</span> <i class="glyphicon glyphicon-minus"></i> Usunięto domenę </a> <a href="#" class="list-group-item"> <span class="badge">wczoraj</span> <i class="glyphicon glyphicon-remove"></i> Domena nieopłacona </a> <a href="#" class="list-group-item"> <span class="badge">2 dni temu</span> <i class="glyphicon glyphicon-euro"></i> Odnotowano płatność </a> <a href="#" class="list-group-item"> <span class="badge">2 dni temu</span> <i class="glyphicon glyphicon-plus"></i> Kupiono domenę </a> </div> </div> </div> </div> <div class="col-lg-12" style="text-align: center "> <a href="#"><i class="glyphicon glyphicon-arrow-left">&nbsp;&nbsp;&nbsp;&nbsp;</i></a> <a href="#"><i class="glyphicon glyphicon-arrow-right"></i></a> </div> </div> </div> </div> </div> <!-- jQuery --> <script src="js/jquery.js"></script> <!-- Bootstrap Core JavaScript --> <script src="js/bootstrap.min.js"></script> <!-- Menu Toggle Script --> <script> $("#menu-toggle").click(function(e) { e.preventDefault(); $("#wrapper").toggleClass("toggled"); }); </script> </body> </html><file_sep>/main.php <?php session_start(); if(!isset($_SESSION['user_session'])) { header("Location: index.php"); } include_once 'dbconfig.php'; $stmt = $db_con->prepare("SELECT * FROM tbl_users WHERE user_id=:uid"); $stmt->execute(array(":uid"=>$_SESSION['user_session'])); $row=$stmt->fetch(PDO::FETCH_ASSOC); ?> <!DOCTYPE html> <html lang="pl"> <?php include 'include/header.php'; ?> <body> <?php include 'include/navbar-logged.php'; ?> <div class="container"> <div class="row"> <div class="col-ls-2"> <div class="signin-form"> <div class="container"> <div class="alert alert-success"> <button class='close' data-dismiss='alert'>&times;</button> <strong>Sukces!</strong> Pomyślnie zalogowano. </div> </div> </div> </div> <div class="col-ls-10"> <h2>Sprawdź dostępność domeny</h2> <div class="form-signin"> <div class="form-group"> <input type="text" class="form-control" placeholder="Podaj domenę" id="domain"/><form action="..."> <select id="suffix"> <option>chartowo.pl</option> <option>winogrady.eu</option> </select> </form> </div> <hr /> <span id="domain-info"></span> <div class="form-group"> <br> <button type="submit" class="btn btn-default" name="btn-login" id="sprawdz" > <span class="glyphicon glyphicon-log-in"></span> &nbsp; Sprawdź &nbsp; </button> </div> </div> </div> </div> <!-- Footer --> <?php include 'include/footer.php'; ?> </div> <!-- jQuery --> <script src="js/jquery.js"></script> <!-- Bootstrap Core JavaScript --> <script src="js/bootstrap.min.js"></script> <!-- Domain checker --> <script type="text/javascript" src="js/check-domain.js"></script> <!-- Other --> <script type="text/javascript" src="js/validation.min.js"></script> <script type="text/javascript" src="js/logowanie.js"></script> </body> </html>
7bbef9bfdd19b04febadeff9a1cb532317f55017
[ "JavaScript", "PHP" ]
13
PHP
p8009inzynierka/Inzynierka
f16cfb481b2975a68851594ff32b849e9d3a57a0
4a6ed72eb11833b19170dab39bb916453cdfeb01
refs/heads/master
<file_sep>[![Maven Central](https://img.shields.io/maven-central/v/com.github.abejoy/DtoConverter.svg?label=Maven%20Central)](https://search.maven.org/search?q=g:%22com.github.abejoy%22%20AND%20a:%22DtoConverter%22) #DtoConverter <file_sep>package com.github.abejoy.DtoConverter; import java.util.*; public abstract class Converter<A, B> { protected abstract B doConvert(A item); public B convert(A item) { if (item != null) { return doConvert(item); } return null; } public List<B> convertAll(A[] items) { return convertAll(Arrays.asList(items)); } public List<B> convertAll(Collection<A> items) { if (items != null) { final List<B> list = new ArrayList<>(); for (A item : items) { final B converted = convert(item); if (converted != null) { list.add(converted); } } return list; } return Collections.emptyList(); } public static class ConversionFailedException extends RuntimeException { private static final long serialVersionUID = -8235837602666844270L; public ConversionFailedException(String message, Throwable cause) { super(message, cause); } public ConversionFailedException(String message) { super(message); } public ConversionFailedException(Throwable cause) { super(cause); } } }
e35a648ada45d20fba5bf6ff5c7999a406f448f1
[ "Markdown", "Java" ]
2
Markdown
abejoy/DtoConverter
e91a51b43d0121e29b0ef04e2108f16adc85ffcd
3b607cf3f827f22d9d2480363ea9e3634b71d0fc
refs/heads/master
<repo_name>enjoy-self-inquiry/day3_kadai_option<file_sep>/script.js $(function() { //「送信」ボタンの色をマウスを乗せたり外すと変えるイベント $('.btn').on('mouseenter', function(){ $(this).css('background-color', '#873955'); }) .on('mouseleave', function(){ $(this).css('background-color', '#0074bf'); }); //モーダルの表示・非表示 $('#inquire_show').on('click', function(){ $('#inquire_modal').fadeIn(); }); $('#close_modal').on('click', function(){ $('#inquire_modal').fadeOut(); }); //「送信」ボタンを押したときにアラームを表示するイベント。 //if文を使って「空欄だった時にエラーを表示」させようとしたけどうまくできず・・・。ひとまずあきらめました T_T $('.btn').on('click',function(){ window.alert("お問い合わせくださりありがとうございます!"); //送信ボタンを押したら入力内容を空欄に戻す(リセット)する設定。...しかし、定数formを定義してないのでこのままでは使えない。作りかけです^^; form.value = ""; }); });
ace0c4f613e61c7860d8591f6f5d78073b6727a2
[ "JavaScript" ]
1
JavaScript
enjoy-self-inquiry/day3_kadai_option
d11210d112627f0e166bf607fcb6a22fd0b3a05a
801982f31a4fc8e647aac8dc1a2edfef169683b4
refs/heads/main
<file_sep>// cSpell:Ignore versao bodyparser require('dotenv').config() const express = require('express') const bodyParser = require('body-parser') const InicializaMongoServer = require('./config/db') const livro = require('./routes/Livro') //Inicializamos o servidor MongoDB InicializaMongoServer() const app = express() //porta default const PORT = process.env.PORT || 4000; //Middleware básico app.use(function (req, res, next) { //Em produção, remova o * e informe a sua URL res.setHeader('Access-Control-Allow-Origin', '*') //Cabeçalhos que serão permitidos res.setHeader('Access-Control-Allow-Headers', 'Origin', 'X-Requested-With, Content-Type, Accept, x-access-token') //Métodos que serão permitidos res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE, OPTIONS') next() }) //parse JSON (validação) app.use(bodyParser.json()) app.get('/', (req, res) => { res.json({ mensagem: 'API do projeto funcionando', versao: '1.0.0' }) }) //Rotas do Livro app.use('/livro', livro) app.listen(PORT, (req, res) => { console.log(`Servidor do projeto iniciado na porta ${PORT}`) })<file_sep># crud-nodejs Projeto avaliativo desenvolvido no curso MERN (MongoDB, Express, React, Node JS), que consiste no CRUD de livros. <file_sep>//cSpell:Ignore maxlength qtde genero preco const mongoose = require('mongoose') const LivroSchema = mongoose.Schema({ ISBN: { type: String, unique: true, required: true }, titulo: { type: String, required: true }, autor: { type: String, required: true }, editora: { type: String, required: true }, idioma: { type: String, required: true }, genero: { type: String, enum: ['Ficção científica', 'Romance', 'Literatura', 'História', 'Línguas', 'Ciências Exatas'], default: 'Ficção científica', required: [true, 'O nome do gênero é obrigatório'] }, qtdePaginas: { type: Number, required: true }, foto: { type: String, required: true }, sinopse: { type: String, required: false }, preco: { type: Number, required: true } }, { timestamps: { createdAt: 'criadoEm', updatedAt: 'alteradoEm' } }) module.exports = mongoose.model('livro', LivroSchema)<file_sep>//cSpell:Ignore MONGOURI const mongoose = require('mongoose') //String de Conexão const MONGOURI = process.env.MONGODB_URL const InicializaMongoServer = async() =>{ try{ await mongoose.connect(MONGOURI, { useNewUrlParser: true, //utiliza o novo parse do mongo useCreateIndex: true, //permite a criação de índices useFindAndModify: false, //por padrão utilizará o findOneAndUpdate useUnifiedTopology: true //permite a descoberta de novos servidores }) console.log('Conectado ao banco de dados!') }catch(e){ console.log('Não foi possível se conectar ao banco de dados') console.error(e) throw e } } module.exports = InicializaMongoServer
a56e718815a0993ab193b8e137443091b9f0ed9b
[ "JavaScript", "Markdown" ]
4
JavaScript
erick-JS/crud-nodejs
47ca6ce8aa480194afb03d5bc4e0a45108ef82b7
37cefcdc00885d490f3a6655ea1e754e1b0b7b20
refs/heads/master
<file_sep>using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore.Storage; namespace ShopApi.Entities { public class UserEntity : IdentityUser { public bool IsActive { get; set; } public string Login { get; set; } public string Name { get; set; } public uint Age { get; set; } /// <summary> /// Total order count recieved this buyer. /// </summary> public uint RecievedOrderCount { get; set; } } } <file_sep>using System; using System.Linq; using System.Threading.Tasks; using ShopApi.Entities; using ShopApi.Repository; namespace ShopApi.Service { public class ShopService : IShopService { //Todo: проверка на вводимые данные private readonly IDbRepository _dbRepository; public ShopService(IDbRepository dbRepository) { _dbRepository = dbRepository; } public async Task<uint> Add(ShopEntity shop) { var result = await _dbRepository.Add(shop); // Добавляем в базу данных экземпляр модели Shop. #region ShopExtension if (shop ==null) { throw new ArgumentNullException("Пользователь не добавлен"); } else if (string.IsNullOrWhiteSpace(shop.Name)|| shop.Name.Length<=1) { throw new ArgumentOutOfRangeException("Не верно задано имя магазина"); } #endregion await _dbRepository.SaveChangesAsync(); //Сохраняем изменения. return result; } public ShopEntity Get(uint id) { var entity = _dbRepository.Get<ShopEntity>().FirstOrDefault(x => x.Id == id); //По полученному из запроса Id находим запись в БД с идентичным Id return entity; } public async Task Delete(uint id) { await _dbRepository.Delete<ShopEntity>(id); //Убираем из всех будущих подборок экземпляр с Id, полученным из запроса. await _dbRepository.SaveChangesAsync(); } public async Task<uint> Update(ShopEntity shop) { await _dbRepository.Update<ShopEntity>(shop); //Обновляем запись в БД await _dbRepository.SaveChangesAsync(); return shop.Id; } } } <file_sep>using System; namespace ShopApi.Model { public class Buyer { public uint Id { get; set; } public string Login { get; set; } public string Name { get; set; } public uint Age { get; set; } public int PhoneNumber { get; set; } public string Password { get; set; } } } <file_sep>using System.Collections.Generic; namespace ShopApi.Model { public class Cart { public Cart(ProductForBuyer product) { _product = product; } /// <summary> /// Покупатель, который оформляет заказ. /// </summary> public Buyer Buyer { get; set; } /// <summary> /// Товар, который добавляется в корзину. /// </summary> public List<ProductForBuyer> ProductCart { set => ProductCart.Add(_product); get => ProductCart; } /// <summary> /// Продавец, которому принадлежит товар. /// </summary> public ShopForBuyers Shop { get; set; } /// <summary> /// Сумма заказа. /// </summary> public decimal TotalPrice { set => _totalPrice += _product.Price; get => _totalPrice; } public string OrderStatus { get; set; } private ProductForBuyer _product; private decimal _totalPrice; } }<file_sep>using System.Threading.Tasks; using ShopApi.Model; namespace ShopApi.Service { public interface IUserService { Task<LoginResponse> Authentication(LoginRequest request); Task Registration(RegisterRequest request); } } <file_sep>namespace ShopApi.Model { public class ShopForBuyers { public string Name { get; set; } /// <summary> /// Total order count delivered to buyers from this shop. /// </summary> public uint DeliveredOrderCount { get; set; } } } <file_sep>using AutoMapper; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using ShopApi.Entities; using ShopApi.Model; using ShopApi.Service; // For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 namespace ShopApi.Controllers { [Route("shop")] [ApiController] public class ShopController : ControllerBase { private IShopService _shopService; private readonly IMapper _mapper; public ShopController(IShopService shopService, IMapper mapper) { _shopService = shopService; _mapper = mapper; } [HttpGet("{id}")] public ActionResult<ShopEntity> Get(uint id) { var shop = _shopService.Get(id); if (shop == null) { return BadRequest("Shop was not found"); } var _shopDTO = _mapper.Map<ShopForBuyers>(shop); return Ok(_shopDTO); } [HttpPost("create")] public async Task<ActionResult<ShopEntity>> Add(ShopEntity shop) { var result = await _shopService.Add(shop); return Ok(result); } [HttpPut] public async Task<ActionResult> Update(ShopEntity shop) { if (shop.Id <0 ) { return BadRequest("Id must be positive"); } var result = await _shopService.Update(shop); return Ok(result); } [HttpDelete("delete/id")] public async Task<ActionResult> Delete(uint id) { await _shopService.Delete(id); return Ok(); } #region Реализация без паттерна Репозиторий. //// GET api/<ShopControler>/{id} //[HttpGet("{id}")] //public IActionResult GetShop(int id) //{ // var ShopID = _shop.GetShopId(id); // return Ok(ShopID); //} //// POST api/<ShopControler>/create //[HttpPost("create")] //public async Task<IActionResult> Post([FromBody] ShopModel shop) // => Ok(await _shop.SetShopName(shop)); #endregion } } <file_sep>using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; using ShopApi.Entities; namespace ShopApi { public class DataContext: IdentityDbContext<UserEntity> { public DbSet <ShopEntity> Shops { get; set; } public DbSet <ProductEntity> Products { get; set; } public DbSet<OrderEntity> Orders { get; set; } public DataContext(DbContextOptions<DataContext> options) : base(options) { } } } <file_sep>using System; using AutoMapper; using ShopApi.Entities; using ShopApi.Model; namespace ShopApi.Profiles { public class ProductForBuyerProfile:Profile { public ProductForBuyerProfile() { CreateMap<ProductEntity, ProductForBuyer>(); } } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using ShopApi.Entities; namespace ShopApi.Repository { public interface IDbRepository { IQueryable<T> Get<T>() where T : class, IEntity; List<T> GetAll<T>() where T :class,IEntity; Task<uint> Add<T>(T newEntity) where T : class,IEntity; Task Delete<T>(uint id) where T : class, IEntity; Task Remove <T>(T entity) where T : class; Task Update<T>(T entity) where T : class,IEntity; Task<int> SaveChangesAsync(); } } <file_sep>using System; namespace ShopApi.Model { public class ProductForBuyer { public uint Id { get; set; } public string Name { get; set; } public decimal Price { get; set; } /// <summary> /// Product`s production date. /// </summary> /// <summary> /// Is product available for order now or not? /// </summary> public bool Availability { get; set; } /// <summary> /// Product manufacturer. /// </summary> public string Producer { get; set; } /// <summary> /// Product picture. /// </summary> public string ProductPicture { get; set; } } } <file_sep>using System; using System.Threading.Tasks; using ShopApi.Entities; namespace ShopApi.Service { public interface IOrderService { OrderEntity Get(uint id); Task<uint> Add(OrderEntity order); Task<uint> Update(OrderEntity order); Task Delete(uint id); } } <file_sep>using System; namespace ShopApi.Model { public class LoginResponse { public string Token{get;set;} public DateTime Expiration { get; set; } } }<file_sep>using System; using System.Linq; using System.Threading.Tasks; using ShopApi.Entities; using ShopApi.Repository; namespace ShopApi.Service { public class OrderService : IOrderService { private readonly IDbRepository _dbRepository; public OrderService(IDbRepository dbRepository) { _dbRepository = dbRepository; } public OrderEntity Get(uint id) { var entity = _dbRepository.Get<OrderEntity>().FirstOrDefault(x => x.Id == id); return entity; ; } public async Task<uint> Add(OrderEntity order) { #region OrderException if (order.ProductCart.Count<=0) { throw new ArgumentOutOfRangeException("Cart is empty."); } #endregion //Set order status is "Created" order.OrderStatus = order.OrderStatusVariation[0]; var result = await _dbRepository.Add(order); await _dbRepository.SaveChangesAsync(); return result; } public async Task Delete(uint id) { var CheckId = _dbRepository.Get<OrderEntity>().FirstOrDefault(x => x.Id == id); if (CheckId == null) { throw new ArgumentNullException("Order with this ID don`t exist"); } //Set order status is "Delivered" CheckId.OrderStatus = CheckId.OrderStatusVariation[2]; //Increase buyer`s recieved order counter by 1 CheckId.User.RecievedOrderCount++; //Increase shop`s successful delivered order counter by 1 CheckId.Shop.DeliveredOrderCount++; await _dbRepository.Delete<OrderEntity>(id); await _dbRepository.SaveChangesAsync(); } public async Task<uint> Update(OrderEntity order) { //Set order status is "Paid" order.OrderStatus = order.OrderStatusVariation[1]; await _dbRepository.Update<OrderEntity>(order); await _dbRepository.SaveChangesAsync(); return order.Id; } public decimal TotalPrice(OrderEntity order) { foreach (var c in order.ProductCart) { order.TotalPrice += c.Price; } return order.TotalPrice; } } } <file_sep>using System; using System.IdentityModel.Tokens.Jwt; using System.Security.Authentication; using System.Security.Claims; using System.Text; using System.Threading.Tasks; using AutoMapper; using Microsoft.AspNetCore.Identity; using Microsoft.IdentityModel.Tokens; using ShopApi.Entities; using ShopApi.Model; namespace ShopApi.Service { public class UserService : IUserService { private readonly UserManager<UserEntity> _userManager; private readonly IMapper _mapper; public UserService(UserManager<UserEntity> userManager, IMapper mapper) { _userManager = userManager; _mapper = mapper; } public async Task<LoginResponse> Authentication(LoginRequest request) { var user = await _userManager.FindByNameAsync(request.Username); if (user != null && await _userManager.CheckPasswordAsync(user, request.Password)) { var authClaims = new[] { new Claim(JwtRegisteredClaimNames.Sub, user.UserName), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()) }; var authSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("<KEY>")); var token = new JwtSecurityToken( expires: DateTime.Now.AddDays(5), claims: authClaims, signingCredentials: new SigningCredentials(authSigningKey, SecurityAlgorithms.HmacSha256) ); return new LoginResponse { Token = new JwtSecurityTokenHandler().WriteToken(token), Expiration = token.ValidTo }; } throw new AuthenticationException("login failed"); } public async Task Registration(RegisterRequest request) { var entity = _mapper.Map<UserEntity>(request); var result = await _userManager.CreateAsync(entity, request.Password); if (!result.Succeeded) { throw new AuthenticationException(); } } } } <file_sep>using System; namespace ShopApi.Entities { public interface IEntity { //TODO: Добавить автоматическое назначение уникального Id uint Id { get; set; } bool IsActive { get; set; } } } <file_sep>using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using ShopApi.Entities; namespace ShopApi.Repository { public class DbRepository : IDbRepository { private readonly DataContext _context; public DbRepository(DataContext context) { _context = context; } /// <summary> /// Get all <T> -entities from base, filtered by active-status. /// </summary> /// <typeparam name></typeparam> /// <returns></returns> public IQueryable<T> Get<T>() where T : class, IEntity { return _context.Set<T>().Where(x=>x.IsActive).AsQueryable(); } public List<T> GetAll<T>() where T : class,IEntity { return _context.Set<T>().ToList(); } /// <summary> /// Add new entity to base. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="newEntity"></param> /// <returns></returns> public async Task<uint> Add<T>(T newEntity) where T : class, IEntity { var entity = await _context.Set<T>().AddAsync(newEntity); return entity.Entity.Id; } /// <summary> /// Set unavailable status for output by id /// </summary> /// <typeparam name="T"></typeparam> /// <param name="id"></param> /// <returns></returns> public async Task Delete<T>(uint id) where T : class, IEntity { var activeEntity = await _context.Set<T>().FirstOrDefaultAsync(x => x.Id == id) ; activeEntity.IsActive = false; await Task.Run(() => _context.Update(activeEntity)); } /// <summary> /// Remove from base by id. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="entity"></param> /// <returns></returns> public async Task Remove<T>(T entity) where T : class { await Task.Run(() =>_context.Set<T>().Remove(entity)); } /// <summary> /// Update database. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="entity"></param> /// <returns></returns> public async Task Update<T>(T entity) where T : class, IEntity //для чего в принципе используется Update? { await Task.Run(() => _context.Set<T>().Update(entity)); } /// <summary> /// Save changes in database. /// </summary> /// <returns></returns> public async Task<int> SaveChangesAsync() { return await _context.SaveChangesAsync(); } } } <file_sep>using System; using System.Linq; using System.Threading.Tasks; using ShopApi.Entities; using ShopApi.Repository; namespace ShopApi.Service { public class ProductService : IProductService { private readonly IDbRepository _dbRepository; public ProductService(IDbRepository dbRepository) { _dbRepository = dbRepository; } public async Task<uint> Add(ProductEntity product) { //Set product`s category //product.ProductCategory.Products.Add(product); var result = await _dbRepository.Add(product); #region Product add exception if (product == null) { throw new ArgumentNullException("Товар не добавлен"); } else if (string.IsNullOrWhiteSpace(product.Name) || product.Name.Length <= 1) { throw new ArgumentException("Не корректно задано имя товара"); } else if (product.Price <= 0) { throw new ArgumentOutOfRangeException("Не корректно задана цена товара"); } else if (product.ProductionDate >= DateTime.Now && product.ProductionDate == null) { throw new ArgumentOutOfRangeException("Указан не верный формат даты, либо не указан совсем"); } else if (string.IsNullOrWhiteSpace(product.Manufacturer) || product.Manufacturer.Length <= 1) { throw new ArgumentOutOfRangeException("Не верно указана дата"); } #endregion await _dbRepository.SaveChangesAsync(); return result; } public ProductEntity Get(uint id) { var entity = _dbRepository.Get<ProductEntity>().FirstOrDefault(x => x.Id == id); if (entity == null) { throw new ArgumentNullException("Такого товара не существует"); } return entity; } public async Task Delete(uint id) { var CheckId = _dbRepository.Get<ProductEntity>().FirstOrDefault(x => x.Id == id); if (CheckId == null) { throw new ArgumentNullException("Order with this ID don`t exist"); } await _dbRepository.Delete<ProductEntity>(id); await _dbRepository.SaveChangesAsync(); } public async Task<uint> Update(ProductEntity product) { await _dbRepository.Update<ProductEntity>(product); await _dbRepository.SaveChangesAsync(); return product.Id; } } } <file_sep>namespace ShopApi.Model { public class RegisterRequest { public string Name { get; set; } public uint Age { get; set; } public string Username { get; set; } public string Password { get; set; } } }<file_sep>using System; using System.Collections.Generic; namespace ShopApi.Entities { public class OrderEntity : IEntity { public bool IsActive { get; set;} /// <summary> /// Order ID. /// </summary> public uint Id { get; set; } /// <summary> /// Buyer. /// </summary> public UserEntity User { get; set; } /// <summary> /// List of products in buyer cart. /// </summary> public List<ProductEntity> ProductCart = new List<ProductEntity>(); /// <summary> /// Product dealer. /// </summary> public ShopEntity Shop { get; set; } public decimal TotalPrice { get; set; } /// <summary> /// Total order amount. /// </summary> public uint OrderCount { get; set; } public string[] OrderStatusVariation = {"Created", "Paid", "Delivered"}; public string OrderStatus { get; set; } } } <file_sep>using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Threading.Tasks; namespace ShopApi.Entities { public class ShopEntity : IEntity { //TODO: сделать maper из сущности в модель контроллера public string Name { get; set; } [Column(TypeName = "integer")] public uint Id { get; set; } public bool IsActive { get; set; } /// <summary> /// Колличество заказов у данного продавца. /// </summary> public uint OrderCount { get; set; } /// <summary> /// Успешно доставленные заказы. /// </summary> public uint DeliveredOrderCount { get; set; } } } <file_sep>using System; using System.Threading.Tasks; using ShopApi.Entities; namespace ShopApi.Service { public interface IShopService { Task<uint> Add(ShopEntity shop); ShopEntity Get(uint id); Task<uint> Update(ShopEntity shop); Task Delete(uint id); } } <file_sep>using System; using System.Threading.Tasks; using ShopApi.Entities; namespace ShopApi.Service { public interface IProductService { Task<uint> Add(ProductEntity product); ProductEntity Get(uint id); Task<uint> Update(ProductEntity product); Task Delete(uint id); } } <file_sep>using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using AutoMapper; using ShopApi.Entities; using ShopApi.Model; using ShopApi.Service; namespace ShopApi.Controllers { [Route("order")] [ApiController] public class OrderController : ControllerBase { private IOrderService _orderService; private readonly IMapper _mapper; public OrderController(IOrderService orderService, IMapper mapper) { _orderService = orderService; _mapper = mapper; } [HttpGet("{id}")] public ActionResult<OrderEntity> Get(uint id) { var _order = _orderService.Get(id); if (_order == null) { return BadRequest("Order was not found"); } var _orderDTO = _mapper.Map<Cart>(_order); return Ok(_orderDTO); } [HttpPost("create")] public async Task<ActionResult<OrderEntity>> Add(Cart cart) { var _cartDTO = _mapper.Map<OrderEntity>(cart); var result = await _orderService.Add(_cartDTO); return Ok(result); } [HttpPut] public async Task<ActionResult> Update(Cart cart) { var _cartDTO = _mapper.Map<OrderEntity>(cart); if (_cartDTO.Id==null) { return BadRequest("Order not updated"); } var result = await _orderService.Update(_cartDTO); return Ok(result); } [HttpDelete("delete/id")] public async Task<ActionResult> Delete(uint id) { await _orderService.Delete(id); return Ok(); } } } <file_sep>using System.Collections.Generic; namespace ShopApi.Entities { public class ProductCategoryEntity : IEntity { public uint Id { get; set; } public bool IsActive { get; set; } public List<ProductEntity> Products = new List<ProductEntity>(); } }<file_sep>using AutoMapper; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using ShopApi.Entities; using ShopApi.Model; using ShopApi.Service; // For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 namespace ShopApi.Controllers { [Route("product")] [ApiController] public class ProductController : ControllerBase { private IProductService _productService; private readonly IMapper _mapper; public ProductController(IProductService productService,IMapper mapper) { _productService = productService; _mapper = mapper; } [HttpGet("{id}")] public ActionResult<ProductEntity> Get(uint id) { var product = _productService.Get(id); if (product == null) { return BadRequest("Product was not found"); } var _productDTO = _mapper.Map<ProductForBuyer>(product); return Ok(_productDTO); } [HttpPost("create")] public async Task<ActionResult<ProductEntity>> Add(ProductEntity product) { var result = await _productService.Add(product); return Ok(result); } [HttpPut] public async Task<ActionResult> Update(ProductEntity product) { if (product.Id<0) { return BadRequest("Product not updated"); } var result = await _productService.Update(product); return Ok(result); } [HttpDelete("delete/id")] public async Task<ActionResult> Delete(uint id) { await _productService.Delete(id); return Ok(); } #region Реализация без паттерна Репозиторий. //// GET api/<TestControler>/product/{id} .Берем id из url, применяя фильтр по ключевому слову "id". //[HttpGet("product/")] //public IActionResult GetProduct // ([FromQuery(Name = "id")] int Id, // [FromServices] IProduct product) => Ok(product.GetProductId(Id)); //// POST api/<ProductController> //[HttpPost] //public void Post([FromBody] string value) //{ //} //// PUT api/<ProductController>/5 //[HttpPut("{id}")] //public void Put(int id, [FromBody] string value) //{ //} //// DELETE api/<ProductController>/5 //[HttpDelete("{id}")] //public void Delete(int id) //{ //} #endregion } } <file_sep>using System; using System.ComponentModel.DataAnnotations.Schema; using System.Numerics; namespace ShopApi.Entities { public class ProductEntity : IEntity { [Column(TypeName = "integer")] public uint Id { get; set; } public bool IsActive { get; set; } public string Name { get; set; } public decimal Price { get; set; } /// <summary> /// Production date. /// </summary> public DateTime ProductionDate { get; set; } /// <summary> /// Is product available for order now or not? /// </summary> public bool Availability { get; set; } /// <summary> /// Product manufacturer. /// </summary> public string Manufacturer { get; set; } // public ProductCategoryEntity ProductCategory { get; set; } /// <summary> /// Product picture. /// </summary> public string ProductPicture { get; set; } } } <file_sep>using AutoMapper; using ShopApi.Entities; using ShopApi.Model; namespace ShopApi.Profiles { public class UserProfile : Profile { public UserProfile() { CreateMap<UserEntity, Buyer>().ReverseMap() .ForMember(dest => dest.Id, source => source.MapFrom(src => src.Id)); CreateMap<RegisterRequest, UserEntity>() .ReverseMap(); } } } <file_sep>using System; using AutoMapper; using ShopApi.Entities; using ShopApi.Model; namespace ShopApi.Profiles { public class ShopForBuyersProfile:Profile { public ShopForBuyersProfile() { CreateMap<ShopEntity, ShopForBuyers>().ReverseMap(); } } } <file_sep>using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using ShopApi.Entities; using ShopApi.Model; using ShopApi.Service; namespace ShopApi.Controllers { [ApiController] [Route("[controller]")] public class AccountController : ControllerBase { private readonly IUserService _userService; public AccountController(IUserService userService) { _userService = userService; } [HttpPost("login")] public async Task<IActionResult> Login([FromBody] LoginRequest model) { var result = await _userService.Authentication(model); if(result == null) { return Unauthorized(); } return Ok(result); } [HttpPost("register")] public async Task<IActionResult> Register([FromBody] RegisterRequest request) { await _userService.Registration(request); var result = await _userService.Authentication(new LoginRequest { Username = request.Username, Password = <PASSWORD> }); return Ok(result); } } }
9016d109b4b5f6cd1c6b6a3ebedf26b3cfa2cc94
[ "C#" ]
30
C#
Lummiense/ShopModel
55b527d5b46a3a732e8bda82fe980407ef2cc9ed
1b8bd02bc8072c79ef8ffbadd38cd49fc437f407
refs/heads/master
<file_sep><!Doctype html> <html> <head> <title>The Mountain Top</title> <meta name="viewport" content="width=device-width, user-scalable=no"> <meta name="description" content="Enjoy the absolute peak dining experience of your life." /> <link rel="stylesheet" type="text/css" href="css/reset.css" media="screen"> <link href="//netdna.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet"> <link rel="stylesheet" type="text/css" href="css/style.css" media="screen"> </head> <body> <nav> <ul id="menu"> <li>HOME</li> <li>ABOUT</li> <li>MENU</li> <li>CONTACT</li> </ul> </nav> <div id="page"> <header> <aside id="toggle-menu"> <i class="fa fa-bars"></i> </aside> <div class="clear"></div> </header> <div id="home" data-type="background" data-speed="20"> <article> <h2>The Mountain Top</h2> <p>Fine Dining at Earth's Peak</p> </article> </div> <div id="about"> <article> <h2>The Absolute Peak Dining Experience</h2> <p>At The Mountain Top you will experience Earth's sublime mountain scenery paired with our gourmet four star fine dining experience designed by our head chef, <NAME>.</p> <p>To book your reservation or find out more information, please visit our contact us section.</p> </article> </div> <div id="starter" data-type="background" data-speed="10"> <section> <h2>Starters</h2> <article> <h3>The Mountain Platter - $14.99</h3> <p>Integer tincidunt ultricies aliquet. Aliquam convallis sem nisi, blandit sollicitudin urna tempus vel. Maecenas mauris quam, lobortis nec magna vel, congue luctus justo.</p> </article> <article> <h3>Calamari &amp; Bacon - $10.99</h3> <p>Mauris quis ultricies nibh. Phasellus posuere sed metus venenatis blandit. Vestibulum vulputate purus turpis, sit amet sollicitudin felis congue ac.</p> </article> <article> <h3>Chicken Strips - $12.99</h3> <p>Praesent consequat mauris mi, vel commodo justo feugiat et. Phasellus ultricies sit amet erat id rhoncus.</p> </article> </section> </div> <div id="entree" data-type="background" data-speed="30"> <section> <h2>Entree</h2> <article> <h3>The Mountain Burger - $16.99</h3> <p>Suspendisse nec turpis sed eros fringilla viverra. Maecenas hendrerit mauris quis posuere suscipit</p> </article> <article> <h3>Halibut &amp; Chips - $18.99</h3> <p>Nunc tincidunt tincidunt massa nec pretium.</p> </article> <article> <h3>The Mountain Steak - $24.99</h3> <p>Vivamus at lorem massa. Maecenas fringilla at elit eu convallis. Aenean at est eu elit rhoncus ullamcorper.</p> </article> <article> <h3>Atlantic Salmon Fillet - $22.99</h3> <p>Mauris quis ultricies nibh. Phasellus posuere sed metus venenatis blandit.</p> </article> </section> </div> <div id="dessert" data-type="background" data-speed="30"> <section> <h2>Dessert</h2> <article> <h3>Pana Cotta - $7.99</h3> <p>Morbi viverra massa orci, ut suscipit purus vestibulum placerat. Morbi dolor nisi, hendrerit vitae.</p> </article> <article> <h3><NAME> - $9.99</h3> <p>In non sem ultrices, malesuada mauris quis, rhoncus quam.</p> </article> <article> <h3><NAME> - $9.99</h3> <p>Etiam in enim in nunc faucibus cursus ac vitae est. Mauris a erat eget felis euismod sagittis.</p> </article> </section> </div> <div class="clear"></div> <div id="contact" data-type="background" data-speed="20"> <section> <h2>Contact Us</h2> <p>To book your reservation at The Mountain Top please call <a href="tel:8448851255">(844) 885-1255</a> or e-mail us at <a href="mailto:<EMAIL>"><EMAIL></a> </p> <p>If you have any questions please feel free to use the form below to contact us. We will do our best to get back to you within 24 hours.</p> <article> <fieldset id="contact-form"> <div id="result"></div> <label for="name"> <h4>Name</h4> <input type="text" name="name" id="name" /> </label> <label for="email"> <h4>E-Mail</h4> <input type="email" name="email" id="email" /> </label> <label for="phone"> <h4>Phone</h4> <input type="text" name="phone" id="phone" /> </label> <label for="message"> <h4>Message</h4> <textarea name="message" id="message"></textarea> </label> <label><span>&nbsp;</span> <button class="submit_btn" id="submit_btn" type="submit">Send</button> </label> </fieldset> <aside> <p>You can also find us on social media</p> <i class="fa fa-facebook-square"></i> <i class="fa fa-twitter-square"></i> <i class="fa fa-linkedin-square"></i> </aside> </article> <div id="map_canvas"></div> </section> </div> <footer> <p>Designed + Developed by <NAME></p> </footer> </div> <script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.min.js"></script> <script src="https://maps.googleapis.com/maps/api/js"></script> <script type="text/javascript" src="js/mobileMenu.js"></script> <script type="text/javascript" src="js/parallax.js"></script> <script type="text/javascript" src="js/script.js"></script> </body> </html> <file_sep>function initialize() { var location = new google.maps.LatLng(49.4671785, -123.0048952); var map_canvas = document.getElementById('map_canvas'); var map_options = { center: location, zoom: 12, scrollwheel: false, navigationControl: false, mapTypeControl: false, scaleControl: false, draggable: false, mapTypeId: google.maps.MapTypeId.ROADMAP } var map = new google.maps.Map(map_canvas, map_options) var marker = new google.maps.Marker({ position: location, map: map }); } google.maps.event.addDomListener(window, 'load', initialize); $(document).ready(function() { $('#starter section, #entree section, #dessert section').css('height', $('#entree').height()); });
b1e98ad7634d659a626e38f53b9cb5c6533fbe65
[ "JavaScript", "HTML" ]
2
HTML
OHaiDanny/OnePager_Art
6a662bc5b0e0918891fbc46c3dfe4c48a455ac88
7c031f9674af1bb365047e5ba4a7db404fc78806
refs/heads/master
<file_sep>package com.bean; import java.util.Set; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; public class Test { public static void main(String[] args) { Configuration cfg = new Configuration().configure(); // 2.创建SessionFactory对象 SessionFactory sessionFactory = cfg.buildSessionFactory(); // 3.创建session对象 Session session = sessionFactory.openSession(); Transaction transaction=session.beginTransaction(); Employed employed = new Employed(); employed.setName("aa"); employed.setJob("clerk"); employed.setDeptno(20); employed.setEmpno(7778); session.save(employed); transaction.commit(); session.close(); sessionFactory.close(); } } <file_sep>package com.bean; public class Employed { private String name; private String job; private int deptno; private int empno; public Employed() { // TODO Auto-generated constructor stub } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getJob() { return job; } public void setJob(String job) { this.job = job; } public int getDeptno() { return deptno; } public void setDeptno(int deptno) { this.deptno = deptno; } public int getEmpno() { return empno; } public void setEmpno(int empno) { this.empno = empno; } }
a9faee29bebd7f5547406549f9a890b5320fd9dd
[ "Java" ]
2
Java
ZOTK-chaos/hibernate_example
a1d0b4848aa6dc80c5ff338406730cb73155c905
b0bd30c386dcc6bb32f2c092b401c64eab66bddb
refs/heads/master
<repo_name>KeyForce/KeyForce<file_sep>/Push.sh git add . git commit -m "Github Readme" git push<file_sep>/README.md <h1 align="center"> <img src="https://media.giphy.com/media/VgCDAzcKvsR6OM0uWg/giphy.gif" width="40"> Hi there 👋 <br/> </h1> <img align='right' src="https://cdn.jsdelivr.net/gh/KeyForce/PictureBed/NoteBook/20200809203218.jpg" width="180"> **Talking about Personal Stuffs:** - 🔭 I'm a graduate student - 🌱 I’m currently learning C++ - 😄 Fun fact: I love photography and hiking **Other Projects:** - 🏆 [Self-Balancing-Car](https://github.com/KeyForce/Self-Balancing-Car) **Languages and Tools:** <code><img height="25" src="https://raw.githubusercontent.com/github/explore/80688e429a7d4ef2fca1e82350fe8e3517d3494d/topics/cpp/cpp.png"></code> <code><img height="25" src="https://raw.githubusercontent.com/github/explore/80688e429a7d4ef2fca1e82350fe8e3517d3494d/topics/python/python.png"></code> <code><img height="25" src="https://pytorch.org/assets/images/pytorch-logo.png"></code> <code><img height="25" src="https://raw.githubusercontent.com/github/explore/80688e429a7d4ef2fca1e82350fe8e3517d3494d/topics/git/git.png"></code> <div align=center> <a href="https://github.com/KeyForce"> <img src ="https://github-readme-stats.vercel.app/api?username=KeyForce&count_private=true&hide_border=true&show_icons=true"/> </a> </div> <h2 align="center"> Show some ❤️ by starring some of the repositories! <br/> </h2>
91d97996f8ba4bcb7c1bd43f4712c2fdbf89165f
[ "Markdown", "Shell" ]
2
Shell
KeyForce/KeyForce
d03e9da8e43e270cb9c036d88928fa63200bc25f
0afe13a51615fc4bf1183b59327769be45fa979a
refs/heads/master
<repo_name>dokoto/list-files-from-folder<file_sep>/ListFilesFromFolder/ListFilesFromFolder/Form1.h #pragma once #include < stdio.h > #include < stdlib.h > #include < vcclr.h > namespace ListFilesFromFolder { using namespace System; using namespace System::ComponentModel; using namespace System::Collections; using namespace System::Windows::Forms; using namespace System::Data; using namespace System::Drawing; /// <summary> /// Resumen de Form1 /// /// ADVERTENCIA: si cambia el nombre de esta clase, deberá cambiar la /// propiedad 'Nombre de archivos de recursos' de la herramienta de compilación de recursos administrados /// asociada con todos los archivos .resx de los que depende esta clase. De lo contrario, /// los diseñadores no podrán interactuar correctamente con los /// recursos adaptados asociados con este formulario. /// </summary> public ref class Form1 : public System::Windows::Forms::Form { public: Form1(void) { this->m_fileList = gcnew System::Collections::ArrayList; InitializeComponent(); // //TODO: agregar código de constructor aquí // } protected: /// <summary> /// Limpiar los recursos que se estén utilizando. /// </summary> ~Form1() { if (components) { delete components; } } private: System::Collections::ArrayList^ m_fileList; private: System::Windows::Forms::GroupBox^ groupBox1; private: System::Windows::Forms::Label^ lb_file_save; protected: private: System::Windows::Forms::Label^ lb_folder; private: System::Windows::Forms::Button^ bt_help_save_file; private: System::Windows::Forms::Button^ bt_help_folder; private: System::Windows::Forms::Button^ bt_close; private: System::Windows::Forms::Button^ bt_list_files; private: System::Windows::Forms::TextBox^ txb_file_save; private: System::Windows::Forms::TextBox^ txb_folder; private: System::Windows::Forms::FolderBrowserDialog^ folderBrowserDialog1; private: System::Windows::Forms::SaveFileDialog^ saveFileDialog1; private: System::Windows::Forms::ProgressBar^ progressBar1; private: /// <summary> /// Variable del diseñador requerida. /// </summary> System::ComponentModel::Container ^components; #pragma region Windows Form Designer generated code /// <summary> /// Método necesario para admitir el Diseñador. No se puede modificar /// el contenido del método con el editor de código. /// </summary> void InitializeComponent(void) { System::ComponentModel::ComponentResourceManager^ resources = (gcnew System::ComponentModel::ComponentResourceManager(Form1::typeid)); this->groupBox1 = (gcnew System::Windows::Forms::GroupBox()); this->txb_file_save = (gcnew System::Windows::Forms::TextBox()); this->txb_folder = (gcnew System::Windows::Forms::TextBox()); this->lb_file_save = (gcnew System::Windows::Forms::Label()); this->lb_folder = (gcnew System::Windows::Forms::Label()); this->bt_help_save_file = (gcnew System::Windows::Forms::Button()); this->bt_help_folder = (gcnew System::Windows::Forms::Button()); this->bt_close = (gcnew System::Windows::Forms::Button()); this->bt_list_files = (gcnew System::Windows::Forms::Button()); this->folderBrowserDialog1 = (gcnew System::Windows::Forms::FolderBrowserDialog()); this->saveFileDialog1 = (gcnew System::Windows::Forms::SaveFileDialog()); this->progressBar1 = (gcnew System::Windows::Forms::ProgressBar()); this->groupBox1->SuspendLayout(); this->SuspendLayout(); // // groupBox1 // this->groupBox1->Controls->Add(this->txb_file_save); this->groupBox1->Controls->Add(this->txb_folder); this->groupBox1->Controls->Add(this->lb_file_save); this->groupBox1->Controls->Add(this->lb_folder); this->groupBox1->Controls->Add(this->bt_help_save_file); this->groupBox1->Controls->Add(this->bt_help_folder); this->groupBox1->Location = System::Drawing::Point(12, 15); this->groupBox1->Name = L"groupBox1"; this->groupBox1->Size = System::Drawing::Size(652, 110); this->groupBox1->TabIndex = 0; this->groupBox1->TabStop = false; this->groupBox1->Text = L"Parametros de Ejecución"; // // txb_file_save // this->txb_file_save->Font = (gcnew System::Drawing::Font(L"Arial", 12)); this->txb_file_save->ForeColor = System::Drawing::SystemColors::MenuHighlight; this->txb_file_save->Location = System::Drawing::Point(199, 64); this->txb_file_save->Name = L"txb_file_save"; this->txb_file_save->Size = System::Drawing::Size(410, 26); this->txb_file_save->TabIndex = 5; // // txb_folder // this->txb_folder->Font = (gcnew System::Drawing::Font(L"Arial", 12, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->txb_folder->ForeColor = System::Drawing::Color::DarkGreen; this->txb_folder->Location = System::Drawing::Point(199, 32); this->txb_folder->Name = L"txb_folder"; this->txb_folder->Size = System::Drawing::Size(410, 26); this->txb_folder->TabIndex = 4; // // lb_file_save // this->lb_file_save->AutoSize = true; this->lb_file_save->Font = (gcnew System::Drawing::Font(L"Arial", 9.75F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->lb_file_save->Location = System::Drawing::Point(15, 69); this->lb_file_save->Name = L"lb_file_save"; this->lb_file_save->Size = System::Drawing::Size(172, 16); this->lb_file_save->TabIndex = 3; this->lb_file_save->Text = L"Ruta al Fichero Resultado"; // // lb_folder // this->lb_folder->AutoSize = true; this->lb_folder->Font = (gcnew System::Drawing::Font(L"Arial", 9.75F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->lb_folder->Location = System::Drawing::Point(15, 37); this->lb_folder->Name = L"lb_folder"; this->lb_folder->Size = System::Drawing::Size(178, 16); this->lb_folder->TabIndex = 2; this->lb_folder->Text = L"Ruta del Directorio a Listar"; // // bt_help_save_file // this->bt_help_save_file->Location = System::Drawing::Point(615, 64); this->bt_help_save_file->Name = L"bt_help_save_file"; this->bt_help_save_file->Size = System::Drawing::Size(28, 26); this->bt_help_save_file->TabIndex = 1; this->bt_help_save_file->Text = L"..."; this->bt_help_save_file->UseVisualStyleBackColor = true; this->bt_help_save_file->Click += gcnew System::EventHandler(this, &Form1::bt_help_save_file_Click); // // bt_help_folder // this->bt_help_folder->Location = System::Drawing::Point(615, 32); this->bt_help_folder->Name = L"bt_help_folder"; this->bt_help_folder->Size = System::Drawing::Size(28, 26); this->bt_help_folder->TabIndex = 0; this->bt_help_folder->Text = L"..."; this->bt_help_folder->UseVisualStyleBackColor = true; this->bt_help_folder->Click += gcnew System::EventHandler(this, &Form1::bt_help_folder_Click); // // bt_close // this->bt_close->Location = System::Drawing::Point(468, 131); this->bt_close->Name = L"bt_close"; this->bt_close->Size = System::Drawing::Size(77, 31); this->bt_close->TabIndex = 1; this->bt_close->Text = L"Cerrar"; this->bt_close->UseVisualStyleBackColor = true; this->bt_close->Click += gcnew System::EventHandler(this, &Form1::bt_close_Click); // // bt_list_files // this->bt_list_files->Font = (gcnew System::Drawing::Font(L"Arial", 9.75F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, static_cast<System::Byte>(0))); this->bt_list_files->Location = System::Drawing::Point(551, 131); this->bt_list_files->Name = L"bt_list_files"; this->bt_list_files->Size = System::Drawing::Size(104, 31); this->bt_list_files->TabIndex = 2; this->bt_list_files->Text = L"Listar"; this->bt_list_files->UseVisualStyleBackColor = true; this->bt_list_files->Click += gcnew System::EventHandler(this, &Form1::bt_list_files_Click); // // progressBar1 // this->progressBar1->Location = System::Drawing::Point(12, 131); this->progressBar1->Name = L"progressBar1"; this->progressBar1->Size = System::Drawing::Size(421, 31); this->progressBar1->TabIndex = 6; // // Form1 // this->AutoScaleDimensions = System::Drawing::SizeF(6, 13); this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font; this->BackColor = System::Drawing::SystemColors::Control; this->ClientSize = System::Drawing::Size(677, 176); this->Controls->Add(this->progressBar1); this->Controls->Add(this->bt_list_files); this->Controls->Add(this->bt_close); this->Controls->Add(this->groupBox1); this->Icon = (cli::safe_cast<System::Drawing::Icon^ >(resources->GetObject(L"$this.Icon"))); this->MaximizeBox = false; this->MaximumSize = System::Drawing::Size(685, 203); this->MinimumSize = System::Drawing::Size(685, 203); this->Name = L"Form1"; this->Text = L"LIST-FILES FROM FOLDER"; this->groupBox1->ResumeLayout(false); this->groupBox1->PerformLayout(); this->ResumeLayout(false); } #pragma endregion private: System::Void bt_help_folder_Click(System::Object^ sender, System::EventArgs^ e) { txb_folder->Text = PopFolderOpenHelp(); } private: System::Void bt_help_save_file_Click(System::Object^ sender, System::EventArgs^ e) { txb_file_save->Text = PopFileSaveHelp(); } private: System::Void bt_close_Click(System::Object^ sender, System::EventArgs^ e) { Form1::Close(); } private: System::Void bt_list_files_Click(System::Object^ sender, System::EventArgs^ e) { ListFilesToFile(); } private: System::String^ PopFolderOpenHelp() { if(folderBrowserDialog1->ShowDialog() == System::Windows::Forms::DialogResult::OK) return folderBrowserDialog1->SelectedPath; return L""; } private: System::String^ PopFileSaveHelp() { SaveFileDialog^ saveFileDialog1 = gcnew SaveFileDialog; saveFileDialog1->Filter = "xls files (*.xls)|*.xls"; saveFileDialog1->FilterIndex = 2; saveFileDialog1->RestoreDirectory = true; if ( saveFileDialog1->ShowDialog() == System::Windows::Forms::DialogResult::OK ) return saveFileDialog1->FileName; return L""; } private: System::Boolean Check_FieldsInputs() { if (System::String::IsNullOrEmpty(txb_folder->Text) == true) { MessageBox::Show("La ruta del Directorio a Listar es OBLIGATORIA."); return false; } if (System::String::IsNullOrEmpty(txb_file_save->Text) == true) { MessageBox::Show("La ruta del fichero Resultado es OBLIGATORIA."); return false; } return true; } private: System::Void ProcessFile( System::String^ path ) { this->m_fileList->Add(path); } private: System::Void ProcessDirectory( System::String^ targetDirectory ) { using namespace System::IO; // Process the list of files found in the directory. array<String^>^fileEntries = Directory::GetFiles( targetDirectory ); IEnumerator^ files = fileEntries->GetEnumerator(); while ( files->MoveNext() ) { String^ fileName = safe_cast<String^>(files->Current); ProcessFile( fileName ); } // Recurse into subdirectories of this directory. array<String^>^subdirectoryEntries = Directory::GetDirectories( targetDirectory ); IEnumerator^ dirs = subdirectoryEntries->GetEnumerator(); while ( dirs->MoveNext() ) { String^ subdirectory = safe_cast<String^>(dirs->Current); ProcessDirectory( subdirectory ); } } private: System::Void ListFilesToFile() { using namespace System::Runtime::InteropServices; using namespace System::IO; System::Windows::Forms::Cursor::Current = System::Windows::Forms::Cursors::WaitCursor; if (Check_FieldsInputs()) { this->m_fileList->Clear(); progressBar1->Visible = true; progressBar1->Minimum = 1; progressBar1->Maximum = 100; progressBar1->Value = 1; progressBar1->Step = 25; progressBar1->PerformStep(); if ( Directory::Exists( txb_folder->Text ) ) ProcessDirectory(txb_folder->Text); progressBar1->PerformStep(); if (this->m_fileList->Count > 0) { StreamWriter^ sw = File::CreateText( this->txb_file_save->Text ); try { for( int i = 0; i < this->m_fileList->Count; i++ ) { sw->WriteLine(this->m_fileList[i]); } progressBar1->PerformStep(); } finally { if ( sw ) delete (IDisposable^)(sw); progressBar1->PerformStep(); MessageBox::Show("Fichero generado con exito en : " + this->txb_file_save->Text ); } } else { progressBar1->PerformStep(); MessageBox::Show("No se ha generado ningun fichero, debido a que no se han encontrado ficheros. " ); } } System::Windows::Forms::Cursor::Current = System::Windows::Forms::Cursors::Default; } }; }
1731a2c7a974625e5b4844e040798ad3fc811c17
[ "C++" ]
1
C++
dokoto/list-files-from-folder
ef6b34d2efb4ac015c422a6860c6dc6297322dd3
7888f5e869947a82e4fd4c44f7edb817761998b3
refs/heads/master
<file_sep>this is the deployed site https://frozen-brushlands-60290.herokuapp.com/ <file_sep>const express = require('express') const cors = require('cors') const app = express() app.use(cors()) const students = [{ "id": 1, "cohortName": "17-01-WD-DP", "cohortCode": "g100", "numberOfStudents": 28 },{ "id": 2, "cohortName": "17-01-DS-GT", "cohortCode": "g105", "numberOfStudents": 24 },{ "id": 3, "cohortName": "17-02-WD-PX", "cohortCode": "g109", "numberOfStudents": 30 },{ "id": 4, "cohortName": "17-03-WD-BD", "cohortCode": "g110", "numberOfStudents": 29 }] app.get('/', (request, response) =>{ response.json({data: students}) }) app.get('/:id', (request, response) =>{ let thisResponse = students[request.params.id - 1] if (!thisResponse){ response.status(404) response.json({ error: { message: "No class found!" } }) } response.json({data: thisResponse}) }) app.listen(process.env.PORT || 3000)
478fc55266cabe39ea931fef280dcb3d5de3e886
[ "Markdown", "JavaScript" ]
2
Markdown
404-kid/server-1-drill
465be9b8e0ddcfa1f11f97db020acdf4f50d2791
ba910af14fc6e1fe1199ea6be75e0927722f3cb4
refs/heads/master
<file_sep>7.2.3, a, (1): start, (6): end. Graph: (1) --> (2) (2) --> (3) (3) --> (4) (3) --> (5) (4) --> (5) (5) --> (2) (2) --> (6) b, D-U Pairs : [1,3], [1,6], [3,3], [3,6] D-U Paths : [1,2,6], [1,2,3], [3,5,2,3], [3,5,2,6], [3,4,5,2,3], [3,4,5,2,6] c, A test path p tours subpath q if q is a subpath of p Test Path: + t1 = [1,2,6] + t2 = [1,2,3,4,5,2,3,5,2,6] + t3 = [1,2,3,5,2,3,4,5,2,6] + t4 = [1,2,3,5,2,6] D-U Paths toured: + [1,2,6] + [1,2,3], [1,2,6], [3,5,2,6], [3,4,5,2,3], [3,4,5,2,6] + [1,2,3], [1,2,6], [3,5,2,3], [3,5,2,6], [3,4,5,2,6] + [1,2,3], [1,2,6], [3,5,2,6] d, t2=[1,2,3,4,5,2,3,5,2,6] This test path satisfies all defs by touring at least one path for at least one use for each def (Path toured are : [1,2,3], [3,5,2,6]) e, t1 = [1,2,6] t2 = [1,2,3,4,5,2,3,5,2,6] These two test paths together satisfy all uses coverage by touring at least one path for each def-use pair. (Paths toured are [1,2,3], [1,2,6], [3,4,5,2,3], [3,5,2,6]) f, t1 = [1,2,6] t2 = [1,2,3,4,5,2,3,5,2,6] t3 = [1,2,3,5,2,3,4,5,2,6] These three test paths together satisfy DU-paths coverage with respect to x.<file_sep>7.2.2-7, a, p2 and p3 are test paths p1, p4 and p5 is not a test path because p1 doesn't terminate at a final node, p4 does not start at an initial node and p5 includes an edge that does not exist in the graph b, TR Edge Pairs = { [1,2,1], [1,2,3], [1,3,1], [2,1,2], [2,1,3], [2,3,1], [3,1,2], [3,1,3] } c, The set of test paths does not satisfy Edge-Pair Coverage because the remaining candidate paths are not test paths neither p2 nor p3 tours either of the edge-pairs :{ [2,1,2], [3,1,3] } d, p3 does not tour the prime path directly p3 does tour the prime path with the sidetrip [1,2,1] <file_sep>7.5-1, a, The four values for elements are [ null, null ], [ obj, null ], [ null, obj ] and [ obj, obj ] [ obj, null ] and [ null, obj ] are different at the representation level b, The number of states = Element * size * front * back = 4 * 3 * 2 * 2 = 48 total states. c, Of the 48 states, only 6 are reachable. d + e, The exceptions (enqueue() on full queues and dequeue() on empty queues) as well as observer method. Result in "loop transitions from a state back to itself. These are not shown on the diagram for clarity and from a grading perspective, aren't relevant. Labels on nodes show the values of the representation state variables : Elements, size, front and back. f,Small test : Queue q = new Queue(); Object obj = new Object(); q.enqueue(obj); q.enqueue(obj); q.dequeue(); q.enqueue(obj); q.dequeue(); q.dequeue(); q.enqueue(obj); q.dequeue(); <file_sep>8.1-2, - The Predicate : (G V ((m > a) V (s <= o + n)) ^ U) - The clauses are : G, (m > a), (s < o + n) and U <file_sep>3-2, - Inheritance tree of classes could become more complex to test, because the sub classes are dependent of its father. - This affects controllability because we will need to control every super class and its sub classes, and if wee have a deep inheritance tree, it will be very complicated. - On the other hand, it affects observability because we need to observe a large number of sub classes that actually are doing the same work as the super class. <file_sep>7.4-3, a, As we can see, the code show that (2) is final and (6) may be final, nodes (1), (3), (4), (5) are not final. Graph: (1) --> (2) (1) --> (3) (2) --> (3) (3) --> (4) (3) --> (5) (4) --> (6) (5) --> (6) b, The path : t1 : [ f1, f3, f5, f6 ] t2 : [ f1, f3, f4, f6 ] t3 : [ f1, f2 ] t4 : [ f1, f3, f4, f6] t5 : [ f1, f2, f3, f4, f6] c, We have 3 minimal test set that achieves Node Coverage : + { t1, t2, t3 } + { t1, t3, t4 } + { t1, t5 } d, We have only one minimal test set that achieves Edge Coverage : { t1, t5 } e, We have 4 prime paths : { [f1, f2, f3, f4, f6], [f1, f2, f3, f5, f6], [f1, f3, f4, f6], [f1, f3, f5, f6] } Prime path is not covered : [f1, f2, f3, f5, f6]<file_sep>8.2-1, - - - i, abc + abc a, Karnaugh map for f cd\ab 00 01 11 10 0 1 1 1 - Karnaugh map for f: cd/ab 00 01 11 10 0 1 1 1 1 1 1 1 b, Nonredundant prime implicant representation for f: - f = bc - Nonredundant prime implicant representation for f : - - f = b + c - - c,Implicants { bc, b, c } Test set : { xTF, xFT} Final minimized Test Set: {xFT} d, - - - f: abc + abc MUTP = { xTF, xFF, xTT} e, - - - f: abc + abc CUTPNFP = {xTF, xFF, xTT} ---- ii, f = abcd + abcd a, Karnaugh map for f cd/ab 00 01 11 10 00 1 01 11 1 10 - Karnaugh map for f : cd/ab 00 01 11 10 00 1 1 1 01 1 1 1 1 11 1 1 1 10 1 1 1 1 b, nonredudant prime implicant representation for f: ---- f = abcd + abcd - nonredundant prime implicant representation for f : - - - - - f = ab + bc + cd + ad ---- - - - - c, Six implicant : {abcd, abcd, ab, bc, cd, ad} Test set {FFFF, TTTT, TFTF, FTFT} Final minimized test : {TFTF, FTFT} d, UTPC = {FFFF, TTTT, TTFF, TTFF, TFFF, FFTT, FFTF} e, CUTPNFP (10 test) +With FFFF we pair {TFFF, FTFF, FFTF, FFFT} +With TTTT we pair {FTTT, TFTT, TTFT, TTTF} - -- iii, f = ab + abc + abc a, Karnaugh map for f : cd/ab 00 01 11 10 0 1 1 1 1 1 - Karnaugh map for f : cd/ab 00 01 11 10 0 1 1 1 1 1 b, nonredundant prime implicant representation for f : f = ab + bc - nonredundant prime implicant representation for f : - - -- f = ab + bc - - - c, We have 4 implicants {ab,bc,ab,bc } Test set :{TTx, xFT, FTx, xFF } Final minimzed test : {TTx, xFT, FTx, xFF } d,UTPC = {TTx, xFT, FTx, xFF }, because IC test set above used nonredundant prime implicants and each test was a unique true point e, We need to choose unique true points so that all variables that yield near false points are represented. To this end, unique true points {TTF,FFT} for f pair up with near false points {FTF,TFF} and {FFF,FTT} respectively. --- - iv, f = acd + cd + bcd a, Karnuagh map for f : cd/ab 00 01 11 10 00 T T 01 T T T T 11 T T 10 - Karnaugh map for f : cd/ab 00 01 11 10 00 T T 01 11 T T 10 T T T T -- - b, Nonredundant prime implicant representation for f: ac + cd bd - - - - Nonredundant prime implicant representation for f: bc + cd + ad c, -- - - - - We have 6 implicant :{ac, cd, bd, bc, cd, ad} Test set: {F_F_,___FT,_T_T, _FT_, __TF, T___F} Final minimized Test set: {FTFT, TFTF} d, -- MUTP = { FTFF, FFFT -> ac - TFFT, FTFT -> cd TTFT, FTTT -> bd } => MUTP test set = {FTFF, FFFT, TFFT, FTFT, TTFT, FTTT} e, -- For implicant ac : UTP, NFP pair: - a -> FFFF, TFFF - c -> FTFF, FTTF - For implicant cd : UTP NFP pair: - c -> TFFT, TFTT - d -> FTFT, FTFF For implicant bd: UTP, NFP pair : - b -> TTFT, TFFT - d -> FTFT, FTFF Possible CUTPNFP Test set : {FFFF, FTFF, TFFT, TTFT, FTFT -> UTPs TFFF, FTTF, TFTT, FTFF, TFFT -> NFPs } f, -- - ac + cd + db -- For implicant ac NFPs: a -> TTFF, TFFT - c -> FTTF, FFTT For implicant !cd: NFPs: - c -> TFTT, FTTT d -> TFFF, FTFF For implicant bd: NFPs: b -> TFFT, FFTT d -> TTFF, FTTF MNFP Test Set = {TTFF, TFFT,FTTF, FFTT,TFTT, FTTT, TFFF, FTFF}. g, MUTP Test Set: {FTFF, FFFT, TFFT, FTFT, TTFT, FTTT} CUTPNFP Test set: { FFFF, FTFF, TFFT, TTFT, FTFT -> UTPs TFFF, FTTF, TFTT, FTFF, TFFT -> NFPs} MNFP Test Set = {TTFF, TFFT,FTTF, FFTT,TFTT, FTTT, TFFF, FTFF } Test set to detect all faults (MUMCUT):{FTFF, FFFT, TFFT, FTFT, TTFT, FTTT,FFFF,TFFF, FTTF, TFTT, TTFF, FFTT}<file_sep>8.3-5, a, The code to transform checkIt() to checkItExpand() : public static void checkItExpand (boolean a, boolean b, boolean c) { if (a) { if (b) { System.out.println ("1: P is true"); } else if (c) { // !b System.out.println ("2: P is true"); } else { // !b and !c System.out.println ("3: P isn't true"); } } else { // !a System.out.println ("4: P isn't true"); } } b, If we number the truth table in the usual way, we have : GACC pairs for clause a are {1,2,3} x {5,6,7} GACC pair for clause b is (2, 4). GACC pair for clause c is (3,4) So, a GACC test set T1 for checkIt() needs to have test {2,3,4} and one of {5,6,7} For edge coverage for checkItExpand(), we need Txx and Fxx for clause a, TFx and TTx for clause b, and TFT and TFF for clause c => We could pick test set T2 = {1,3,4,8}, which have Edge Coverage on checkItExpand() c,Code Run both T1 and T2 on both checkIt() and checkItExpand() publick class check { public static void checkIt (boolean a, boolean b, boolean c) { if (a && (b || c)) { System.out.println ("1: P is true"); } else { System.out.println ("3: P isnt' true"); } } public static void checkItExpand (boolean a, boolean b, boolean c) { if (a) { if (b) { System.out.println ("1: P is true"); } else if (c) { System.out.println ("2: P is true"); } else { System.out.println ("3: P isn't true"); } } else { System.out.println ("4: isn't true"); } } public static void main (String[] args) { boolean a = true; boolean b = true; boolean c = true; for (int i = 0; i < 2; i ++) { for (int j = 0; j < 2; j++) { for (int k = 0; k < 2; k++) { System.out.println (a + " " + b + " " + c); System.out.print ("checkIt(): " ); checkIt(a, b, c); System.out.print ("checkItExpand(): "); checkItExpand(a, b, c); c = !c; } b = !b; } a = !a; } } }<file_sep>Original code: Vehicle.java public class Vehicle implements Cloneable{ protected int x; public Vehicle(int y) { x=y; } public Object clone() { Object result = new Vehicle(this.x); //Location "A" return result; } } Truck.java public class Truck extends Vehicle { private int y; public Truck(int z) { super(z); y=z; } public Object clone() { Object result = super.clone(); //Location "B" ((Truck) result).y = this.y; return result; } } CloneTest.java public class Client { public static void main(String args[]) { Truck suv = new Truck(4); Truck co = suv.clone(); if(suv.x==co.x) { System.out.println("Output 1: True"+ co.x); } if(suv.getClass()==co.getClass()) { System.out.println("Output 2: True "+ co.getClass()); } } } a) Fault: Location “A” According to Bloch, Item 11, The provision that x.clone().getClass() should generally be identical to x.getClass() , however, is too weak. In practice, programmers assume that if they extend a class and invoke super.clone from the subclass, the returned object will be an instance of the subclass. The only way a superclass can provide this functionality is to return an object obtained by calling super.clone. If a clone method returns an object created by a constructor, it will have the wrong class. Therefore, if you override the clone method in a nonfinal class, you should return an object obtained by invoking super.clone. If all of a class's superclasses obey this rule, then invoking super.clone will eventually invoke Object 's clone method, creating an instance of the right class. Thus, the fault is at Location “A” in original code, as the clone method is calling constructor of the class to create a new Vehicle object. This fault does not allocate/return correct class type to the subclass’c clone method. The proposed modification to code is: public Object clone() throws CloneNotSupportedException { try{ Object result = super.clone(); ((Vehicle)result).x = this.x; //Location "A" return result; } catch (CloneNotSupportedException e) { throw e; } } Error observed: Exception in thread "main" java.lang.ClassCastException: Vehicle cannot be cast to Truck at Truck.clone(Truck.java:16) at CloneTest.main(CloneTest.java:7) b) Test case that does not execute the fault is not possible, as all uses of clone executes the fault (super class’s clone method calls constructor to create object). Anytime subclass tries to clone the object, the super class’s clone method is invoked through sub class’s clone method (super.clone) and thus the fault is executed (super class’s clone method calls constructor to create object). c) Test case that executes the fault but does not result in error is not possible as every time clone is attempted, the super class’s clone method returns incorrect object type and thus result in ClassCastException in sub class’s clone method. d) Test case that results in an error but not a failure: Vehicle suv = new Vehicle(4); Vehicle co = (Vehicle) suv.clone(); Expected: Output 1: True , value of co.x = 4 Output 2: True , value of co.getClass() = class Vehicle Actual: Output 1: True , value of co.x = 4 Output 2: True , value of co.getClass() = class Vehicle However, such test case is not possible if cloning is performed on sub class’s object. e) Error State: suv = Truck • x = 4 • y = 4 result = Vehicle • x = 4 PC: at the start of Constructor of Vehicle class f) Expected output generated after code repair: Output 1: True , value of co.x = 4 Output 2: True , value of co.getClass() = class Truck Repaired code: Vehicle.java public class Vehicle implements Cloneable{ protected int x; public Vehicle(int y) { x=y; } public Object clone() throws CloneNotSupportedException { try{ Object result = super.clone(); ((Vehicle)result).x = this.x; //Location "A" return result; } catch (CloneNotSupportedException e) { throw e; } } } Truck.java public class Truck extends Vehicle { private int y; public Truck(int z) { super(z); y=z; } public Truck clone() throws CloneNotSupportedException { try{ Truck result = (Truck) super.clone(); result.y = this.y; return result; } catch(CloneNotSupportedException e) { throw e; } } } CloneTest.java public class CloneTest { public static void main(String args[]) throws CloneNotSupportedException { Truck suv = new Truck(4); Truck co = suv.clone(); if(suv.x==co.x) { System.out.println("Output 1: True , value of co.x = "+ co.x); } if(suv.getClass()==co.getClass()) { System.out.println("Output 2: True , value of co.getClass() = "+ co.getClass()); } } } <file_sep>6.2-5, a, There are multiple testable units (1 constructor, 2 mutators, and 2 observers). There is an abstract state variable queue that represents the queue of objects. There is also an abstract state variable cap that represents the capacity of the queue. There is an abstract state variable representing the current number of objects in the queue. b, Queue is empty or full, what the current size is, what cap is, and whether there are special values (such as null) in the queue. The only obvious syntactic characteristic for x is whether it is null. In the constructor, capacity can clearly have 'illegal' values. c, -Whether queue is empty a1:true (Value queue = []) a2:false (Value queue = ["cat", "hat"]) Base -Whether queue is full b1:true (Value queue = ["cat"], cap = 1) b2:false (Value queue = ["cat", "hat"], cap = 3) Base -Size of queue c1:0 (Value queue = []) c2:1 (Value queue = ["cat"], ) c3:more than 1 (Values queue = ["cat", "hat"]) Base -Value of cap d1:negative (Value cap = -1) d2:0 (value cap = 0) d3:1 (value cap = 1) d4:more than 1 (value cap = 2) Base -Value of capacity e1:negative (value cap = -1) e2:0 (Value cap = 0) e3:1 (Value cap = 1 ) e4:more than 1 (Value cap = 2) Base -Whether x is null f1:true (value x = null) f2:false (value x = "cat" ) Base d,I have already listed one value for each block in part c, e, We should testing Enqueue for this part and it makes the parameter x relevant The variable capacity in the constructor is not relevant to this set of test, so we will skip blocks e1, e2, e3 and e4 The base test is (a2,b2,c3,d4,f2), for each partition give more 8 tests: (a1,b2,c3,d4,f2), (a2,b1,c3,d4,f2), (a2,b2,c1,d4,f2), (a2,b2,c2,d4,f2), (a2,b2,c3,d1,f2), (a2,b2,c3,d2,f2), (a2,b2,c3,d3,f2), (a2,b2,c3,d4,f1) (1)Consider (a2,b2,c3,d3,f2), where the focus is on varying d , the value of cap (2)The value for queue specified by c3 is incompatible with this choice, either a2 or b2 has to change, since, if cap is 1, the queue will always be either empty or full (1),(2)=> A feasible variant of this test is (a2,b1,c2,d3,f2) <file_sep>1-4, a, public static Vector union (Vector a, Vector b) { Vector result = new Vector (a); // get all of aís elements Iterator itr = b.iterator(); while (itr.hasNext()) { Object obj = itr.next(); if (!a.contains (obj)) { // already have aís elements result.add (obj); } } return result; } b,The choice of argument types and return types as Vector is suspect; best practice is to use the least specific type consistent with the specifierís goals. In particular, if Vector is replaced with List, this solves some, but not all of the problems above. Replacing Vector with Set is probably an even better idea, assuming the arguments are really intended to be sets. c, Test case[1] Vector v1 = new Vector(); Vector v2 = new Vector(); Test case[2] Vector v1 = new Vector(); v1.add(2) Vector v2 = new Vector(); Test case[3] Vector v1 = new Vector(); Vector v2 = new Vector(); v3.add(2) d, public static Set union (Set a, Set b) EFFECTS: if a or b is null throw NullPointerException else return a new Set that is the set union of a, b e.g. union (null,{}) is NullPointerException e.g. union ({1,2},{2,3}) is {1,2,3} e.g. union ({1,2},{cat,hat}) is {1,2,cat,hat} e.g. union ({null},{cat,hat}) is {null,cat,hat} e.g. union (a,a) is Set t st that t!=a, but t.equals(a) <file_sep>7.2.2-5, a, Graph: (1): start ; (7): end (1) --> (2) (2) --> (3) (3) --> (2) (4) --> (6) (4) --> (5) (5) --> (6) (6) --> (1) b, Edge Coverage :TR = {(1,2,3), (1,2,4), (2,3,2), (2,4,6), (2,4,5), (3,2,3), (3,2,4), (4,6,1), (4,5,6), (5,6,1), (6,1,7), (6,1,2)} c,Test path p1 = [1,2,4,5,6,1,7] => This path covers (1,2,4), (2,4,5), (4,5,6), (5,6,1), (6,1,7) Test path p2 = [1,2,3,2,4,6,1,7] =>This path covers (1,2,3), (2,3,2), (3,2,4), (2,4,6), (4,6,1), (6,1,7) Test path p3 = [1,2,3,2,4,5,6,1,7] =>This path covers (1,2,3), (2,3,2), (3,2,4), (2,4,5), (4,5,6), (5,6,1), (6,1,7) However, two edge pairs (3,2,3) and (6,1,2) are missing and not convered by any of the test path.Thus, given set of test path does not satisfy Edge-Pair Coverage. d, A test path p tours subpath q if q is a subpath of p. A test path p tours subpath q with sidetrips if every edge in q is also in p in the same order. => Test Path does not tour simple path directly => Test Path tours simple path with sidetrip {4,6,1,2,4} e, TR for Node Coverage = {1, 2, 3, 4, 5, 6, 7} Test paths: [1, 2, 3, 2, 4, 5, 6, 1, 7] TR for Edge Coverage= {(1,2), (1,7), (2,3), (2,4) ,(3,2),(4,5), (4,6),(5,6),(6,1)} Test paths: [1,2,3,2,4,6,1,7], [1,2,4, 5, 6, 1,7] TR for Prime Path Coverage = {(1,2,4,6,1), (1,2,4,5,6,1), (2,3,2), (2,4,6,1,2), (2,4,5,6,1,2), (3,2,3), (3,2,4,6,1,7), (3,2,4,5,6,1,7), (4,5,6,1,2,4), (4,5,6,1,2,3), (4,6,1,2,4), (4,6,1,2,3), (5,6,1,2,4,5), (6,1,2,4,6), (6,1,2,4,5,6)} f, Test path p3 = [1,2,3,2,4,5,6,1,7] achieves Node Coverage but not Edge Coverage. g, p1 = [1,2,4,5,6,1,7] p2 = [1,2,3,2,4,6,1,7] p1 and p2 together achieve Egde Coverage but not Prime Path Coverage p2 = [1,2,3,2,4,6,1,7] p3 = [1,2,3,2,4,5,6,1,7] p2 and p3 together achieve Egde Coverage but not Prime Path Coverage <file_sep>import java.util.*; public class PrimePathList extends SimplePathList { private List<SimplePath> ppl_candidates; public PrimePathList() { super(); ppl_candidates = new LinkedList<SimplePath>(); } // Store only the ones with asterisk('*') or exclamation('!') public void ChoosePPLCandidates(SimplePathPool _pool) { Iterator<SimplePath> iterator = _pool.iterator(); SimplePath sp; while(iterator.hasNext()) { sp = iterator.next(); if(sp.isAsterisk() || sp.isExclamation()) { ppl_candidates.add(sp); } } spl = ppl_candidates; } // Remove sub path public void RemoveSubPath() { List<SimplePath> spl_filtered = new LinkedList<SimplePath>(); SimplePath short_sp, long_sp; boolean isSubPath = false; for(int i = 0; i < spl.size(); i++) { short_sp = spl.get(i); for(int j = i+1; j < spl.size(); j++) { long_sp = spl.get(j); //System.out.println("Short SP:" + short_sp + ", Long SP:" + long_sp); if(short_sp.isSubPathOf(long_sp)) { // If any of sub paths is found, then do not add to the list //System.out.println("Sub Path Found!"); isSubPath = true; break; } } if(!isSubPath) { // If there is no sub path found, then add it to the final Prime Path List //System.out.println("Added Short SP: " + short_sp); spl_filtered.add(short_sp); } isSubPath = false; } spl = spl_filtered; } }<file_sep>1-2, -The risk may be small and the consequences unimportant, or the risk may be great and the consequences catastrophic but risk is always there: + High cost of repairing + High pressure on personnel -We reduce the risk to zero to be perfect such as Neural network and Genetic Algorithm <file_sep>9.1.2-2, They are the same, or to be precise, the mutation score is a refinement of coverage. Each mutant is a test requirement, so the mutation score counts the number of test requirements satisfied. <file_sep>8.1-6, - The example p = (a V b) ^ c =>p = ((a>b) V C) ^ y(x) - We have Clause coverage : + (a > b) = true and false + C = true and false + y(x) = true and false So, we will have 2 tests : + ((a = 5, b = 4), (C = true),y(x) = true) + ((a = 5, b = 6), (C = false),y(x) = false)<file_sep>import static org.junit.Assert.*; import org.junit.*; import java.util.*; public class PatternIndexTest { @Test public void Empty_PatternIndex { assertEquals(" Empty PatternIndex", PatternIndex.patternIndex("", "hot"), -1); } @Test public void Find_PatternIndex { assertEquals("Found PatternIndex", PatternIndex.patternIndex("Supa hot fire", "hot"), 16); } @Test public void notFound() { assertEquals("Not found", PatternIndex.patternIndex("Supa hot fire", "fires"), -1); } }<file_sep>6.4, Explain : - Iterator interface consists of three methods hasNext(), next() and remove() with different return types and return values for each of these methods - We know that the "ConcurrentModificationExceptionis thrown by" methods that have detected concurrent modification of an object when such modification is not permissible. Thus in case of iterator this exception is thrown when the object that is "ArrayList" for which iterator is defined is modified in the duration of use of iterator. - For Iterator checks for the modification, its implementation is present in "AbstractList class"(super class of ArrayList)where an int variable "modCount" is defined that provides the number of times "ArrayList" size has been changed. This value is used in every "next() call" to check for any modifications in a function "checkForComodification()". - I wanted to modify the ArrayList and yet avoid the "ConcurrentModificationException" so I try to modify the list in a way that does not change the size of the list . - The list had been modified during the "iterator" use but this modification was not in terms of change in size of list, the "remove()" call failed to throw the "ConcurrentModificationException". <file_sep>7.2.2-6, a, TR Node Coverage = {1,2,3,4,5,6,7,8,9,10} TR Edge Coverage = { (1,4), (1,5), (2,5), (3,6), (3,7), (4,8), (5,8), (5,9), (6,2), (6,10), (7,10), (9,6) } TR Prime Path Coverage = { [1,4,8], [1,5,8], [1,5,9,6,2], [1,5,9,6,10], [2,5,9,6,2], [2,5,9,6,10], [3,6,2,5,8], [3,6,2,5,9], [3,6,10], [3,7,10], [5,9,6,2,5], [6,2,5,9,6], [9,6,2,5,8], [9,6,2,5,9] } b, T Node Coverage = {[1,4,8], [2,5,9,6,10], [3,7,10]} Although T Node Coverage visits all nodes, T Node Coverage does not tour edges (1,5), (5,7), (6,1) and (3,6) c, T Edge Coverage = T Node Coverage U {[1,4,8], [3,6,2,5,8]} Although T Edge Coverage tours all edges, T Edge Coverage does not tour prime paths [1,5,9,6,2], [2,5,9,6,2], [3,6,2,5,9], [2,6,10], [5,8,5,2,5], [5,1,6,9,6], [9,6,2,5,8], or [9,6,2,5,9] <file_sep>1-5, a,The fault in findLast() is in condition of for loop -> possible modification is: for (int i=x.length-1; i >= 0; i--) The fault in lastZero() is lack of statements -> possible modification is: public static int lastZero (int[] x) { int index = 0; for (int i = 0; i < x.length; i++) { if (x[i] == 0) index = i; } return -1; } The fault in countPositive() is the redundancy in if statement in for loop -> possible modification is: if (x[i] > 0) The fault in oddOrPos() is in the if statement in for loop -> possible modification is: if (x[i] > 0) { count++; } else { if (x[i]%2 ==1 ) count++; } b) Test case for findLast() `int[] x = {1,2,3}` and `y = 2` Test case for lastZero() `int[] x = {0, 1, 1}` Test case for countPositive() `int[] x = {-2, 4, -6}` Test case for oddOrPos() `int[] x = {1, 2, 3}` c) Test case for findLast() `int[] x = {1, 1, 1}` and `y = 1` Test case for lastZero() `int[] x = {0}` Test case for countPositive() Not Possible Test case for oddOrPos() `int[] x = {1, 2, 3}` d)The test case show the error without a failure <file_sep>9.1.2-1, The mutation score is the percent of mutants killed <file_sep># Software-Testing-2020-USTH ## Guidelines to submit your homework - Make a pull request to this repo: https://github.com/truonganhhoang/Software-Testing-2020-USTH - Create a foler with your FullName, e.g., NguyenVanA - Name the file Ex1-1.md, Ex1-3.md, etc. - Homework deadlines are before the next class hours. <file_sep>5-1, a, T1 necessarily satisfy C2, because it's directly from the definition of subsumption. b, T2 doesn't necessarily C1, because Test requirements generated by C1 to be satisfied by T2 c, T2 contains that one test that reveals the fault, and T1 doesn't because subsumption is about criteria, not about test sets. There is no requirement that test set T2 be a subset of test set T1. <file_sep>8.1-3, - The predicate to present the requirement is : ((TypeofMouse = wireless) ^ ((retail > 100) V (item > 20))) V ( "negation symbol" TypeofMouse = wireless) ^ (retail > 50))<file_sep>3-10, - Replace each occurrence of a set with a list: @Theory public void removeThenAddDoesNotChangeList (List<String> list, String string) { assumeTrue (list != null); assumeTrue (list.contains (string)); List<String> copy = new ArrayList<String>(list); copy.remove (string); copy.add (string); assertTrue (list.equals (copy)); } - The resulting theory is invalid - The test that pass the precondition is 4 but the test that pass the precondition also the postcondition is 1. - The reason is the list is changed, we just changed the position in the list and that make the list is changed. <file_sep>3-5, - The assertion only checks a small part of the final state (the first element in the list). So if a test causes a fault to infect, and then propagate to another part of the final state, the failure will not berevealed. The test oracle needs to look at the entire list. <file_sep>9.2-2, a, The mutant is always reached, even if x = null b, Infection always occurs, even if x = null, because i always has the wrong value after initialization in the loop c, As long as the the last occurence of val isn't at numbers[0], the correct output is returned Example : (number, val) = ([1, 1], 1) d, Any input with val only in numbers[0] works. Example: (numbers, val) = ([1, 0], 1)<file_sep>8.3-9, The "Quadratic.java" program in chapter 7 have 1 predicate and 1 clause. The test can deal with a>0, a<0, a=0; b>0, b<0, b=0; c>0, c<0, c=0 -About : + public void testPositiveRoots() : it will covers a>0, b<0, c>0, 2 small positive roots + public void testNegativeRoots() : it will covers b>0, c<0, 2 small negative roots + public void testOppositeSignRoots() : it will covers a<0, one root positive, other root negative + public void testOneZeroRoot() : it will cover c = 0, one root zero, other root nonzero + public void testOneRoot() : it will cover one nonzero root + public void testBothZeroRoots() : it will cover b = 0, both roots zero <file_sep>import org.junit.*; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import static org.junit.Assert.*; import java.util.*; @RunWith(value = Parameterized.class) public class DataDrivenMinTest { private String a; private String b; private String expected; public DataDrivenMinTest(String a, String b, String expected) { this.a = a; this.b = b; this.expected = expected; } @Parameters public static Iterable<Object[]> data1() { return Arrays.asList(new Object[][] {{"apple", "cat", "apple"}, {"dog", "red", "dog"}}); } @Test @SuppressWarnings ("unchecked") public void testmin() { LinkedList list = new LinkedList(); list.add(a); list.add(b); assertEquals (expected, Min.min(list)); } }<file_sep>9.1.2-4, a,We have 4 Nonterminal symbols in the grammar (A, 0, B, M) b,We have 13 terminal symbols in the grammar(w, x, s, m, i, f, c, r, o, t, p, a, h) c,We have 116 possible string that are valid according to the BNF and two strings for example : "xft" and "sc" d,We have dozens valid Mutants of the string and 2 example is : wio -> wit, mio xr -> xi, sf e,We have thousands Invalid Mutants of the string and 2 example is : wio -> wir, pio xr -> fr, xm<file_sep>2-2, #Question b: If you have never worked for a software development company, which of the four test activities do you think you are best qualified for? (test design, automation, execution, evaluation) #Answer: -I think I am best qualified for Testing Execution. -The Test Execution is the process of running tests on the software and recording the results, and it required basic computer skills, and can often be assigned to interns of employees with little technical background so i can basically do all of it well.Also, all the test can be automated or can be run by hand. Hand-executed tests require the tester to be meticulous with bookkeeping and i'm very good at it, but hand execute tests wastes a valuable resource and it's may become very tidous job. However, in my opinion, it's a good start when i have never worked for a software development company. <file_sep>import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.LinkedList; import java.util.List; public class SimplePathList { protected List<SimplePath> spl; public SimplePathList() { spl = new LinkedList<SimplePath>(); } public SimplePathList(List<Node> _nodes) { spl = new LinkedList<SimplePath>(); AddInitialNodes(_nodes); } // Add simple paths with given node list public void AddInitialNodes(List<Node> _nodeList) { SimplePath sp; for(int i = 0; i < _nodeList.size(); i++) { Node node = _nodeList.get(i); sp = new SimplePath(node); spl.add(sp); } } public Iterator<SimplePath> iterator() { return spl.iterator(); } public void add(SimplePath _sp) { spl.add(_sp); } public int size() { return spl.size(); } // public String toString() { // SimplePath sp; // String res = ""; // for(int i = 0; i < spl.size(); i++) { // sp = spl.get(i); // res += sp + " "; // } // return res; // } public String toString() { // Sort SimplePath list Collections.sort(spl, new Comparator<SimplePath>() { public int compare(SimplePath _s1, SimplePath _s2) { if(_s1.len() == _s2.len()) { // If lengths are same int len = _s1.len(); for(int i = 0; i < len; i++) { // Compare node one by one if(_s1.GetNode(i).GetNodeNumber() != _s2.GetNode(i).GetNodeNumber()) { return(_s1.GetNode(i).GetNodeNumber() - _s2.GetNode(i).GetNodeNumber()); } } return 0; } else // If lengths are different, compare them return _s1.len() - _s2.len(); } }); SimplePath sp; String res = ""; for(int i = 0; i < spl.size(); i++) { sp = spl.get(i); res += sp + " "; } return res; } }<file_sep>1-1, -A factors are : +Good, technical people in testing +Amicable relationships between testers and developers +Management leadership <file_sep>9.2-3, a, If x is null or the empty array, for example : x = null or [], then the mutant is never reached b, Any input with all zeroes will reach but not infect. Example :x = [0] or [0, 0] c, Any input with nonzero entries, but with a sum of zero, is fine. Examples: x = [1, -1] or [1, -3, 2] d, Any input with a nonzero sum works Example : x = [1, 2, 3] <file_sep>6.1-1, We have four combinations of these two characteristics, and there are : - File T sorted ascending + File T sorted descending : gold - File T sorted ascending + File F sorted descending : gold, silver - File F sorted ascending + File T sorted descending : silver, gold - File F sorted ascending + File F sorted descending : gold, silver, platinum<file_sep>9.2-1, 1, The statement will always be reached. A test will infect if the variables have different values. The infection propagate if we skip the body of the if statement R: True I : A "not Equal to" B P: "Negation symbol" (B < A) "identical to" (A >= B) 2, The statement will always be reacheed. A test will infect if the entire predicate give a different result. The infection will always propagate R: True I: (B < A) "not equal to" (B > A) "identical to" A "not equal to" B P: True 3, The statement will always be reached. A test will infect if the variables have different values. The mutant is equivalent. Propagation is not relevant for and equivalent mutant. R: True I: A "not equal to" minVal "identical to" False -> equivalent P: N/A 4, The statement is reached if the predicate is true. A Bomb() mutant raises an immediate runtime exception, so it always infect. Likewise, Bomb() mutants always propagate R: B < A I: True P: True 5, The statement is reached if the predicate is true. A test will infect if the variables have different values. Since minVal has been given a different value, the infection will always propagate R: B < A I: A "not equal to" B P: True 6,The statement is reached if the predicate is true. A failonZero() mutant raises an immediate runtime exception if the expression is zero. failonZero() mutants always propagate. R: B < A I: B = A P: True<file_sep>6.1-2, - Where Made: North America, Europe, Asia, "Other" (It is not complete so i added "other") - Energy source is correct (Energy source : gas, electric, hybrid) - Side Doors should be 2-door or 4-door => Side Doors : 2, 4 - Hatch-back should be Yes or No => Hatch-back :Yes, No <file_sep>6.1-5, - The problem is what to do with empty patterns - an easy case for interface-based input domain models. - We should use the exception mechanism:@throws IllegalArgumentException if pattern is empty. - For the implementation to match, it needs an explicit check for an empty pattern, along with an explicit throws clause: if (patternLen == 0) throw new IllegalArgumentException("PatternIndex.patternIndex"). - Finally a test case should be added to PatternIndexTest.java that calls patternIndex() with an empty pattern and looks for this exception. <file_sep>package book.angry.chapter_1; import static org.junit.Assert.assertEquals; import org.junit.Test; public class TimelineTest { @Test public void setFetchCount() { Timeline timeline = new Timeline(); int expected = 5; timeline.setFetchCount( expected ); int actual = timeline.getFetchCount(); assertEquals( expected, actual ); } }
f78fa2bc303907812bfd3fb6467d5cf446af0493
[ "Markdown", "Java" ]
39
Markdown
quangLH195/Software-Testing-2020-USTH
85f6bca681bb8523e0b0cecc6f24803aaf4beb12
87836093036c0812a569d670cba9604fac633dec
refs/heads/master
<repo_name>ShobhanaMarkeshan/SampleRorProject<file_sep>/db/migrate/20200714065647_create_users.rb class CreateUsers < ActiveRecord::Migration[6.0] end <file_sep>/app/models/user.rb class User < ApplicationRecord validates_presence_of :firstName validates_presence_of :lastName validates_presence_of :userName validates_numericality_of :mobile VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i validates :email, presence: true, length: { maximum: 105 }, uniqueness: { case_sensitive: false }, format: { with: VALID_EMAIL_REGEX } validates :bio, length: { minimum:10, maximum:100, message: "invalid"} end <file_sep>/config/routes.rb Rails.application.routes.draw do # get 'products/index' # get 'products/new' # get 'products/create' # get 'products/show' # get 'products/edit' # get 'products/update' # get 'products/destroy' # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html root "welcome#home" # get 'about',to:'welcome#about' # get "user/new", to: "user#new" # post "user/new", to: "user#create" # get "user/index", to: "user#index" # get 'viewuser',to:'user#new' resources :users resources :products end
3cad120723cbd3a8853497404e009c0e448c5508
[ "Ruby" ]
3
Ruby
ShobhanaMarkeshan/SampleRorProject
145dfaf615ee0f1ee1018f57200b9814f83d15b6
addc2d0e398ca6f2d75d89827a01b039ef30787b
refs/heads/master
<file_sep> // gray #808080 window.onload = function() { var myObstacles = []; var myGameArea = { canvas : document.createElement("canvas"), frames: 100, start : function() { this.canvas.width = 480; this.canvas.height = 470; this.canvas.style.border = "thick solid #808080"; this.context = this.canvas.getContext("2d"); document.getElementById('game-board').appendChild(this.canvas); this.interval = setInterval(updateGameArea, 20); }, clear : function() { this.context.clearRect(0, 0, this.canvas.width, this.canvas.height); }, stop: function() { clearInterval(this.interval); }, score: function() { points = (Math.floor(this.frames/5)) this.context.font = '18px serif'; this.context.fillStyle = 'black'; this.context.fillText('Score: '+points, 350, 50); }, road: function() { let doce = this.canvas.width / 12 let dos = this.canvas.width / 2 ; //dot know why the ** this is not the middle. let extra = doce / 3; let top = 0; reactangle(this.context, 0 ,this.canvas.width, 0, '#808080', this.canvas.height ) //road reactangle(this.context, 0 ,doce, 0, '#008a06', this.canvas.height) //left green reactangle(this.context, 0 ,doce, (this.canvas.width - doce), '#008a06', this.canvas.height) //right green reactangle(this.context, 0 ,extra, extra + doce, '#ffffff', this.canvas.height) // left white reactangle(this.context, 0 ,extra, (this.canvas.width - (extra * 2 + doce)), '#ffffff', this.canvas.height) // right white // this should be animated for (let i = 0; i < 15; i++) { top = top + i; reactangle(this.context, top, extra, dos - extra, '#ffffff', this.canvas.height / 12) // reactangle(this.context, top + frames , extra, dos - extra, '#ffffff', frame.height / 12) top = (this.canvas.height / 12) + top + 15 ; } } } //document.getElementById("start-button").onclick = function() { myGameArea.start() //} function Component(width, height, color, x, y, image) { this.width = width; this.height = height; this.x = x; this.y = y; this.speedX = 0; this.speedY = 0; this.update = function(){ ctx = myGameArea.context; ctx.fillStyle = color; if(image){ var img = document.getElementById("car"); ctx.drawImage(img, this.x, this.y, this.width, this.height) } else{ console.log(this.x, this.y, this.width, this.height) ctx.fillRect(this.x, this.y, this.width, this.height); } } this.newPos = function() { this.x += this.speedX; this.y += this.speedY; } this.left = function() { return this.x }; this.right = function() { return (this.x + this.width) }; this.top = function() { return this.y }; this.bottom = function() { return (this.y + this.height) }; this.crashWith = function(obstacle) { return !((this.bottom() < obstacle.top()) || (this.top() > obstacle.bottom()) || (this.right() < obstacle.left()) || (this.left() > obstacle.right())) } } player = new Component(40, 70, "red", 219, 390, true); function updateGameArea() { myGameArea.clear(); myGameArea.road(); player.newPos(); player.update(); myGameArea.frames +=1; if (myGameArea.frames % 120 === 0) { y = myGameArea.canvas.width; maxWidth = 200; minWidth = 20; width = Math.floor(Math.random()*(maxWidth-minWidth+1)+minWidth); minGap = 50; maxGap = 200; gap = Math.floor(Math.random()*(maxGap-minGap+1)+minGap); myObstacles.push(new Component(width, 10, "green", gap, 0)); } for (i = 0; i < myObstacles.length; i++) { myObstacles[i].y += 1; myObstacles[i].update(); } var crashed = myObstacles.some(function(obstacle) { return player.crashWith(obstacle) }) if (crashed) { myGameArea.stop(); } myGameArea.score(); } function reactangle(ctx, top ,width, start, color, height) { ctx.beginPath(); ctx.rect(start, top, width, height); ctx.fillStyle = color; ctx.fill(); } // function moveUp() {player.speedY -= 1;} // function moveDown() {player.speedY += 1;} function moveLeft() {player.speedX -= 1;} function moveRight() {player.speedX += 1;} document.onkeydown = function(e) { switch (e.keyCode) { // case 38: // moveUp(); // break; // case 40: // moveDown(); // break; case 37: moveLeft(); break; case 39: moveRight(); break; } } document.onkeyup = function(e) { stopMove(); } function stopMove() { player.speedX = 0; player.speedY = 0; } }; <file_sep>document.getElementById("start-button").onclick = function() { startGame(); }; let frames = 0; function startGame() { document.getElementById('game-board').innerHTML = '' let canvas = document.createElement("canvas"); canvas.width = 480; canvas.height = 470; canvas.style.border = "thick solid #808080"; context = canvas.getContext("2d"); setInterval(()=>{updateGameAre(context, canvas)}, 20); document.getElementById('game-board').appendChild(canvas); } function updateGameAre (ctx, frame){ frames +=1; road(ctx, frame); carUpdate(ctx, frame); } function carUpdate (ctx, frame){ car } function road (ctx, frame){ // this is static, we dont have to paint it, over and over again. Or do I ? let doce = frame.width / 12 let dos = frame.width / 2 ; //dot know why the ** this is not the middle. let extra = doce / 3; reactangle(ctx, 0 ,frame.width, 0, '#808080', frame.height ) //road reactangle(ctx, 0 ,doce, 0, '#008a06', frame.height) //left green reactangle(ctx, 0 ,doce, (frame.width - doce), '#008a06', frame.height) //right green reactangle(ctx, 0 ,extra, extra + doce, '#ffffff', frame.height) // left white reactangle(ctx, 0 ,extra, (frame.width - (extra * 2 + doce)), '#ffffff', frame.height) // right white // I dont know how to animate this let top = 0; for (let i = 0; i < 15; i++) { top = top + i; reactangle(ctx, top, extra, dos - extra, '#ffffff', frame.height / 12) // reactangle(ctx, top + frames , extra, dos - extra, '#ffffff', frame.height / 12) top = (frame.height / 12) + top + 15 ; } } function reactangle(ctx, top ,width, start, color, height) { ctx.beginPath(); ctx.rect(start, top, width, height); ctx.fillStyle = color; ctx.fill(); }
5534c81c86ec1200c021f95c96b95033460348cb
[ "JavaScript" ]
2
JavaScript
josuevalrob/lab-canvas-race-car
b400ea2f2c2c5d17b97f0a24b7fb23426d413763
37323aac0a04b971826747db35b4ba57486f3e17
refs/heads/master
<repo_name>jle-quel/minishell<file_sep>/sources/ft_unsetenv.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_unsetenv.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: jle-quel <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/06/26 08:56:32 by jle-quel #+# #+# */ /* Updated: 2017/06/29 11:20:24 by jle-quel ### ########.fr */ /* */ /* ************************************************************************** */ #include "minishell.h" /* ** Will copy the full env, without the var that you want to delete. ** the variable is given as the occurence inside env. */ static char **ft_deletevar(char **env, int start) { size_t index1; size_t index2; size_t len; char **array; index1 = 0; index2 = 0; len = ft_arraylen(env); CHK_CC((array = (char**)malloc(sizeof(char*) * len))); while (index1 < len - 1) { if (index1 == (size_t)start) break ; array[index1++] = ft_strdup(env[index2++]); } index2++; while (index1 < len - 1) array[index1++] = ft_strdup(env[index2++]); array[index1] = NULL; return (array); } /* ** while you want to delete var it will send everything to the ERASOR. */ int ft_unsetenv(char **command, char ***address, char **env) { size_t index; int start; char **memory; index = 1; if (command[1]) { while (command[index]) { if ((start = ft_find_env(env, command[index], ft_strlen(command[index]) - 1)) >= 0) { memory = *address; *address = ft_deletevar(env, start); ft_arraydel(&memory, ft_arraylen(memory)); env = *address; } index++; } } else ft_putendl_fd("unsetenv: Too few arguments.", 2); return (1); } <file_sep>/sources/main.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* main.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: jle-quel <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/06/08 12:04:28 by jle-quel #+# #+# */ /* Updated: 2017/07/06 13:45:40 by jle-quel ### ########.fr */ /* */ /* ************************************************************************** */ #include "minishell.h" /* ** Fork the father, Execute the command, Then give back hand on the father ** If exec could not works, tell the user that the command doesnt exist. */ static void ft_execute_command(char **command, char **env) { pid_t father; father = fork(); if (father == 0) { if (execve(command[0], command, env) == -1) { ft_putstr_fd(command[0], 2); ft_putendl_fd(": command not found", 2); ft_putstr("\x1b[31m❯\x1b[0m "); exit(-1); } } else wait(&father); } /* ** If the path is unset, will test if the command is given with the full path, ** so it can be executable. */ static int ft_test(char **command) { if (access(command[0], X_OK) == 0) return (1); return (-1); } /* ** If Variable PATH is found: Create the path using all of the paths inside PATH ** Test if it's executable then execute and free. ** Else, tell the user that the command has not be found */ void ft_launch(char **command, char **env) { int start; char **paths; if ((start = ft_find_env(env, "PATH=", 5)) >= 0) { paths = ft_return_paths(start, env); command = ft_test_access(command, paths, 0); ft_execute_command(command, env); ft_arraydel(&paths, ft_arraylen(paths)); } else if (ft_test(command) == 1) ft_execute_command(command, env); else { ft_putstr_fd(*command, 2); ft_putendl_fd(": path not found", 2); } } /* ** ENV is being populated. ** Display prompt, Wait for user to write something, Get rid of tabs and space. ** Send the command from user to BUILTINS, if the command is not a BUILTINS, ** send everything to LAUNCH, Then free everything. */ int main(void) { char *line; char **command; char **env; env = ft_populate_env(); while (42) { ft_minishell(); get_next_line(0, &line); command = ft_split(line); if (ft_arraylen(command) != 0) { ft_builtins(command, &env, env) == 0 ? ft_launch(command, env) : 0; ft_arraydel(&command, ft_arraylen(command)); ft_strdel(&line); } else if (command) ft_arraydel(&command, ft_arraylen(command)); } ft_arraydel(&env, ft_arraylen(env)); return (0); } <file_sep>/README.md # MINISHELL Le projet Minishell va vous permettre de vous plonger au coeur d’un système Unix et de découvrir une partie importante de l’API d’un tel système : la création et la synchronisation de processus. Le lancement d’une commande dans un shell implique la création d’un nouveau processus dont le processus parent doit monitorer l’exécution et l’état final. Cet ensemble de fonctions sera le coeur de votre Minishell <file_sep>/sources/ft_echo.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_echo.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: jle-quel <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/06/26 10:21:04 by jle-quel #+# #+# */ /* Updated: 2017/07/06 11:07:42 by jle-quel ### ########.fr */ /* */ /* ************************************************************************** */ #include "minishell.h" /* ** Same as the function below, but will print a newline ** Default function. */ static void ft_print_with_newline(char **command) { size_t index; index = 0; while (command[index]) { ft_putstr(command[index]); if (command[index + 1]) ft_putchar(' '); index++; } ft_putchar('\n'); } /* ** Will echo with the options -n, wich is withouth newline */ static void ft_print_without_newline(char **command) { size_t index; index = 0; while (command[index]) { ft_putstr(command[index]); if (command[index + 1]) ft_putchar(' '); index++; } } /* ** Directionnal function, if the options -n is given goes one way.. etc */ int ft_echo(char **command) { if (!command[1]) ft_putendl(""); else if (ft_strcmp(command[1], "-n") == 0) ft_print_without_newline(command + 2); else ft_print_with_newline(command + 1); return (1); } <file_sep>/sources/ft_setenv.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_setenv.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: jle-quel <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/06/24 11:01:10 by jle-quel #+# #+# */ /* Updated: 2017/07/05 17:25:02 by jefferson ### ########.fr */ /* */ /* ************************************************************************** */ #include "minishell.h" /* ** Make sure that you can have "*=*=*" */ static int ft_check(char **command) { size_t index; size_t i; index = 0; while (command[index]) { i = 0; while (command[index][i]) { if (command[index][i] == '=') return (0); i++; } index++; } return (1); } /* ** As explicit as it is, just print the error for the user. */ static int ft_parsing_setenv(char **command) { if (!command[1] || !command[2]) ft_putendl_fd("unsetenv: Too few arguments.", 2); else if (command[3]) ft_putendl_fd("setenv: Too many arguments.", 2); else if (ft_isalpha(command[0][0]) == 0) ft_putendl_fd("setenv: Variable name must begin with a letter.", 2); else if (ft_check(command) == 0) ft_putendl_fd("setenv: usage: Variable Value", 2); else return (1); return (0); } /* ** Will malloc a var, copy the current env, then add one at the end. */ static char **ft_addvar(char **old, char **new) { size_t index1; size_t index2; size_t len; char **array; index1 = 0; index2 = 0; len = ft_arraylen(old) + ft_arraylen(new); CHK_CC((array = (char**)malloc(sizeof(char*) * len + 1))); while (old[index1]) { array[index1] = ft_strdup(old[index1]); index1++; } array[index1] = ft_threejoin(new[index2], "=", new[index2 + 1] ? new[index2 + 1] : ""); array[index1 + 1] = NULL; return (array); } /* ** Directionnal function, if the command from the user is valid, either Change ** or create var. */ int ft_setenv(char **command, char ***address, char **env) { int start; char **memory; memory = *address; if (ft_parsing_setenv(command) == 1) { if ((start = ft_find_env(env, command[1], ft_strlen(command[1]) - 1)) >= 0) *address = ft_change_env(env, command[1], command[2]); else { *address = ft_addvar(env, command + 1); ft_arraydel(&memory, ft_arraylen(memory)); } } return (1); } <file_sep>/sources/ft_cd.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_cd.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: jle-quel <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/06/18 15:23:36 by jle-quel #+# #+# */ /* Updated: 2017/06/29 16:56:09 by jle-quel ### ########.fr */ /* */ /* ************************************************************************** */ #include "minishell.h" /* ** Find where the value of the var start. */ static size_t ft_find_index(char *str) { size_t index; index = 0; while (str[index] != '=') index++; return (index + 1); } /* ** Find the occurence of OLDPWD, and where the value of the var start. ** Return it */ static char *ft_oldpwd(char **env) { int start; size_t index; if ((start = ft_find_env(env, "OLDPWD=", 7)) >= 0) { index = ft_find_index(env[start]); return (ft_strsub(env[start], index, ft_strlen(env[start]))); } return (NULL); } /* ** if (cd -) find the OLDPWD then change direction. ** if (cd || cd ~) change to the user root. ** if chdir didn't worked, print the error to the user. */ static int ft_change_direction(char *direction, char **env, int ret) { char *temp; if (direction && ft_strcmp(direction, "-") == 0) { if ((temp = ft_oldpwd(env))) { ret = chdir(temp); ft_strdel(&temp); } } else if (direction == NULL || ft_strcmp(direction, "~") == 0) ret = chdir("/Users/jle-quel/"); else { if ((ret = chdir(direction) == -1)) { ft_putstr_fd("cd: no such file or directory: ", 2); ft_putendl_fd(direction, 2); } } return (ret); } /* ** Create a temporary oldpwd. ** change direction, then if chdir works change the OLDPWD ** always change the PWD */ int ft_cd(char **command, char ***address, char **env) { char buf[PATH_MAX]; char *oldpwd; int ret; ret = 0; oldpwd = getcwd(buf, PATH_MAX); ret = ft_change_direction(command[1], env, ret); if (ret == 0) *address = ft_change_env(env, "OLDPWD", oldpwd); *address = ft_change_env(env, "PWD", getcwd(buf, PATH_MAX)); return (1); } <file_sep>/sources/ft_tools.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_tools.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: jle-quel <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/06/18 11:05:56 by jle-quel #+# #+# */ /* Updated: 2017/06/29 11:20:38 by jle-quel ### ########.fr */ /* */ /* ************************************************************************** */ #include "minishell.h" /* ** Directionnal function, that will test if the command from user is bultins, ** if yes send it to the right function. */ int ft_builtins(char **command, char ***address, char **env) { if (ft_strcmp(command[0], "exit") == 0) exit(0); else if (ft_strcmp(command[0], "cd") == 0 || ft_strcmp(command[0], "/usr/bin/cd") == 0) return (ft_cd(command, &env, env)); else if (ft_strcmp(command[0], "setenv") == 0) return (ft_setenv(command, address, env)); else if (ft_strcmp(command[0], "unsetenv") == 0) return (ft_unsetenv(command, address, env)); else if (ft_strcmp(command[0], "echo") == 0 || ft_strcmp(command[0], "/bin/echo") == 0) return (ft_echo(command)); else if (ft_strcmp(command[0], "env") == 0 || ft_strcmp(command[0], "/usr/bin/env") == 0) { ft_printarray(env); return (1); } return (0); } /* ** Will try all of the path is the variable PATH until it find one that command ** be executed. */ static char **ft_create_command(char **paths, char **command) { size_t index; char *path; index = 0; while (paths[index]) { path = ft_threejoin(paths[index], "/", command[0]); if (access(path, X_OK) == 0) { ft_strdel(&command[0]); command[0] = ft_strdup(path); path ? ft_strdel(&path) : 0; return (command); } path ? ft_strdel(&path) : 0; index++; } return (command); } /* ** If the command is already with the full path (/bin/ls) just say yes you ** can executed. ** Else create the path */ char **ft_test_access(char **command, char **paths, int argc) { if (access(command[argc], X_OK) == 0) return (command); else return (ft_create_command(paths, command)); } /* ** Split all the path given inside the PATH variable, to test it. */ char **ft_return_paths(size_t start, char **env) { char *str; char **paths; str = ft_strsub(env[start], 5, ft_strlen(env[start])); paths = ft_strsplit(str, ':'); ft_strdel(&str); return (paths); } <file_sep>/includes/minishell.h /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* minishell.h :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: jle-quel <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/06/08 12:06:01 by jle-quel #+# #+# */ /* Updated: 2017/06/28 19:13:41 by jle-quel ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef MINISHELL_H # define MINISHELL_H # include "../libft/libft.h" # include <signal.h> # include <fcntl.h> # define PATH_MAX 4096 /* ** BUILTINS */ int ft_cd(char **command, char ***address, char **env); int ft_echo(char **command); int ft_setenv(char **command, char ***address, char **env); int ft_unsetenv(char **command, char ***address, char **env); /* ** FT_ENV_TOOLS.C */ char **ft_populate_env(void); int ft_find_env(char **env, char *str, int len); char **ft_change_env(char **env, char *dst, char *src); /* ** FT_DISPLAY_TOOLS.C */ void ft_minishell(void); /* ** FT_TOOLS.C */ char **ft_return_paths(size_t start, char **env); char **ft_test_access(char **command, char **paths, int argc); int ft_builtins(char **command, char ***address, char **env); /* ** FT_SPLIT.C */ char **ft_split(char *s); #endif <file_sep>/sources/ft_env_tools.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_env_tools.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: jle-quel <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/06/18 12:23:51 by jle-quel #+# #+# */ /* Updated: 2017/06/29 11:21:06 by jle-quel ### ########.fr */ /* */ /* ************************************************************************** */ #include "minishell.h" /* ** Will change in the env, the variable dst, will value src. */ char **ft_change_env(char **env, char *dst, char *src) { int start; char *memory; if ((start = ft_find_env(env, dst, ft_strlen(dst) - 1)) >= 0) { memory = env[start]; env[start] = ft_threejoin(dst, "=", src); ft_strdel(&memory); } return (env); } /* ** Used to find the occurence of a given var inside env. */ int ft_find_env(char **env, char *str, int len) { size_t index; index = 0; while (env[index]) { if (ft_strncmp(str, env[index], len) == 0) return (index); index++; } return (-1); } /* ** Will populate the char* with the extern environ. */ char **ft_populate_env(void) { size_t index; size_t len; extern char **environ; char **env; index = 0; len = ft_arraylen(environ); CHK_CC((env = (char**)malloc(sizeof(char*) * len + 1))); while (index < len) { env[index] = ft_strdup(environ[index]); index++; } env[index] = NULL; return (env); } <file_sep>/sources/ft_split.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_split.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: jle-quel <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/06/24 14:41:10 by jle-quel #+# #+# */ /* Updated: 2017/07/06 13:42:14 by jle-quel ### ########.fr */ /* */ /* ************************************************************************** */ #include "minishell.h" /* ** Will return the length that we have to malloc for the string. */ static int count_length(int index, char const *s) { int len; len = index; while (s[len] != ' ' && s[len] != '\t' && s[len]) len++; return (len - index); } /* ** Will populate the array only its not a tabs or space then do it again, ** until s[index]. */ static char **do_split(int index, char const *s, char **str) { int len; int index1; int index2; index1 = 0; index2 = 0; while (s[index]) { if (s[index] == ' ' || s[index] == '\t') index++; else { len = count_length(index, s); str[index1] = (char*)malloc(sizeof(char) * (len + 1)); while (len-- > 0) str[index1][index2++] = s[index++]; str[index1++][index2] = '\0'; index2 = 0; len = 0; } } str[index1] = NULL; return (str); } /* ** Will return the number of words separated by tabs and space. */ static int ft_nwords(char const *s) { int index; int nbwords; index = 0; nbwords = 0; while (s[index]) { while (s[index] == ' ' || s[index] == '\t') index++; while (s[index] != ' ' && s[index] != '\t' && s[index]) index++; nbwords++; } return (nbwords); } /* ** Make sure that s is= not NULL, then malloc an array. ** Split it aand return it. */ char **ft_split(char *s) { int index; int nbwords; char **str; if (!s) return (NULL); index = 0; nbwords = ft_nwords(s); CHK_CC((str = (char**)malloc(sizeof(char*) * (nbwords + 1)))); str = do_split(index, s, str); return (str); } <file_sep>/sources/ft_display_tools.c /* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_display_tools.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: jle-quel <<EMAIL>> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/06/19 11:16:53 by jle-quel #+# #+# */ /* Updated: 2017/06/29 11:21:19 by jle-quel ### ########.fr */ /* */ /* ************************************************************************** */ #include "minishell.h" /* ** Will display in color the directory we are. */ static void ft_display(char *buf, size_t len) { char *tmp; char *ret; tmp = ft_strsub(buf, len, ft_strlen(buf)); ret = ft_memalloc(16 + ft_strlen(tmp) + 18); ft_strcpy(ret, "\x1b[35m"); ft_strcat(ret, tmp); ft_strcat(ret, "\x1b[0m "); ft_strcat(ret, "\x1b[32m"); ft_strcat(ret, "❯"); ft_strcat(ret, "\x1b[0m "); ft_putstr(ret); ft_strdel(&tmp); ft_strdel(&ret); } /* ** Search where the user is (PWD) then send it to print. ** If getcwd couldn't find, will print just minishell. */ void ft_minishell(void) { size_t len; char buf[PATH_MAX]; len = 0; if (getcwd(buf, PATH_MAX)) { if (ft_strcmp(buf, "/") != 0) { len = ft_strlen(buf) - 1; while (buf[len] != '/' && buf[len]) len--; len++; } ft_display(buf, len); } else ft_putstr("\x1b[35mMINISHELL\x1b[0m \x1b[32m❯\x1b[0m "); }
47ceb8888516f1bbbd95e2b5afeb82e929ea5498
[ "Markdown", "C" ]
11
C
jle-quel/minishell
6bd2a8def04973f6d7f2c267aa5cde6eb4d6bb10
70331c6fd4e182e19ad26aaad176eed721767060
refs/heads/master
<file_sep>package com.i1314i.news.HandlerInterceptor; import com.i1314i.news.po.User; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class LoginInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception { String url = httpServletRequest.getRequestURI(); if(url.indexOf("adminhtml")<0){ return true; } User user= (User) httpServletRequest.getSession().getAttribute("user_session"); if(user!=null){ return true; }else{ String urls=httpServletRequest.getContextPath(); httpServletResponse.sendRedirect(urls+"/admin/html/login/login.html"); } return false; } @Override public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception { } @Override public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception { } } <file_sep>package com.i1314i.news.controller; import com.i1314i.news.po.*; import com.i1314i.news.service.Exception.TheException; import com.i1314i.news.service.NewsService; import com.i1314i.news.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; @Controller @RequestMapping("/admin/html/adminhtml") public class UserController { @Autowired private UserService userService; @Autowired private NewsService newsService; private Msg msg=null; private User usersql; @RequestMapping(value = "/msgnotice",method = {RequestMethod.GET,RequestMethod.POST}) public ModelAndView getNewsList(ModelAndView modelAndView , @RequestParam(required = false)Integer type, @RequestParam(required = false)Integer currPage, HttpServletRequest request)throws Exception{ if(currPage==null&&type==null){ currPage=1; type=1; }else if(type==null){ type=0; }else if(currPage==null||currPage==0){ currPage=1; } int pageSzie=10; PageBean<News> pageBean= newsService.findAll(currPage,pageSzie,type); if(type==0){ pageBean.setTypename("全部"); }else { String typename=newsService.findTypeById(type); pageBean.setTypename(typename); } pageBean.setPagecode(currPage); pageBean.setTypeid(type); //页码 int totalrecord= 0; if(type==0){ totalrecord= userService.findAllCounts(); }else{ totalrecord=newsService.findAllCount(type); } //总页数 int totalpage = totalrecord/pageSzie; if(totalpage==0){ totalpage=1; }else{ totalpage+=1; } pageBean.setTotalpage(totalpage); List<Type> Types=newsService.findAllType(); User user= (User) request.getSession().getAttribute("user_session"); if(user!=null){ modelAndView.addObject("user",user); } modelAndView.addObject("types",Types); modelAndView.addObject("pageBean",pageBean); modelAndView.setViewName("msg_notice"); return modelAndView; } @RequestMapping(value = "/msgpublish",method = {RequestMethod.GET,RequestMethod.POST}) public ModelAndView InsertNews (ModelAndView modelAndView,@RequestParam(required = false) Integer id,@RequestParam(required = false) Integer type,HttpServletRequest request)throws Exception{ String url=""; List<Type> types=newsService.findAllType(); if((type==null&&id==null)||(type==null||type==0)||(id==null)){ url= "msg_publish"; }else{ News news = newsService.findNewsById(id); if(news!=null){ modelAndView.addObject("news",news); url="msg_publish"; }else{ url="redirect:msgpublish.html" ; } } User user= (User) request.getSession().getAttribute("user_session"); if(user!=null){ modelAndView.addObject("user",user); } modelAndView.addObject("types",types); modelAndView.setViewName(url); return modelAndView; } @RequestMapping(value = "/updateandaddNews",method = {RequestMethod.POST}) public @ResponseBody Msg updateandaddNews(@RequestBody News news)throws Exception{ msg=new Msg(); if((news.getTitle()==null||news.getTitle().trim().equalsIgnoreCase(""))){ msg.setSuccess(0); msg.setMsg("新闻标题不能为空"); }else if(news.getContent()==null||news.getContent().trim().equalsIgnoreCase("")){ msg.setSuccess(0); msg.setMsg("新闻内容不能为空"); } else{ if(newsService.isNews(news.getId())){ newsService.updateNews(news); msg.setSuccess(1); msg.setMsg("修改数据成功"); }else{ Date date = new Date(); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); String dates=dateFormat.format(date); news.setDates(dates); newsService.insertNews(news); msg.setSuccess(1); msg.setMsg("添加数据成功"); } } return msg; } @RequestMapping(value = "/deleteNews",method = {RequestMethod.POST}) public @ResponseBody Msg deleteNews(@RequestBody News news)throws Exception{ System.out.println(news.getId()); msg=new Msg(); int su=newsService.deleteNews(news.getId()); if(su==1){ msg.setSuccess(1); msg.setMsg("删除成功"); }else { msg.setSuccess(0); msg.setMsg("要删除的新闻不存在"); } return msg; } @RequestMapping(value = "/usercontrol") public ModelAndView Users(ModelAndView modelAndView,HttpServletRequest request)throws Exception{ User user = (User) request.getSession().getAttribute("user_session"); List<User>users=userService.findUsersList(); modelAndView.addObject("users",users); modelAndView.addObject("user",user); modelAndView.setViewName("user_control"); return modelAndView; } @RequestMapping(value = "/getUser",method = {RequestMethod.POST}) public @ResponseBody User userly(@RequestBody User user)throws Exception{ usersql=null; System.out.println(user.getUid()); if(user.getUid()!=0){ usersql=userService.findUserById(user.getUid()); System.out.println(usersql.getUsername()); if(usersql!=null){ usersql.setSuccess(1); }else{ usersql=new User(); usersql.setSuccess(0); } } System.out.println(usersql.getUid()); return usersql; } @RequestMapping(value = "/addUser",method = {RequestMethod.POST}) public @ResponseBody Msg addUser(@RequestBody User user)throws Exception{ User usersql=null; User Usersql1=null; if(user.getUid()!=0){ usersql=userService.findUserById(user.getUid()); } msg=new Msg(); msg.setSuccess(0); if(user.getPassword().trim().equalsIgnoreCase("")||user.getUsername().trim().equalsIgnoreCase("")){ msg.setSuccess(0); msg.setMsg("密码或账号不能为空"); }else if(user.getUsername().length()<=2){ msg.setSuccess(0); msg.setMsg("账号长度必须大于2"); } else{ if(usersql==null){ Usersql1=userService.findUserByName(user.getUsername()); if(Usersql1!=null){ System.out.println(user.getUsername()); if(Usersql1.getUsername().equalsIgnoreCase(user.getUsername())){ msg.setSuccess(0); msg.setMsg("账号已存在"); } }else { user.setType(0); userService.insertUser(user); System.out.println(user.getUsername()); msg.setSuccess(1); msg.setMsg("添加数据成功"); } }else{ userService.updateUser(user); msg.setSuccess(1); msg.setMsg("修改数据成功"); } } return msg; } @RequestMapping(value = "/deleteUser",method = {RequestMethod.POST}) public @ResponseBody Msg deleMsg(@RequestBody User user)throws Exception{ msg=new Msg(); usersql=null; if(user.getUid()!=0){ usersql=userService.findUserById(user.getUid()); if(usersql==null){ msg.setSuccess(0); msg.setMsg("所删除资源不存在"); }else{ userService.deleteUserById(user.getUid()); msg.setSuccess(1); msg.setMsg("删除成功"); } } return msg; } @RequestMapping(value = "/quitUser") public ModelAndView quit(ModelAndView modelAndView,HttpServletRequest request)throws Exception{ request.getSession().invalidate(); modelAndView.setViewName("redirect:/admin/html/login/login.html"); return modelAndView; } } <file_sep>package com.i1314i.news.service.Impl; import com.i1314i.news.service.Exception.TheException; import com.i1314i.news.service.UserService; import com.i1314i.news.mapper.UserMapper; import com.i1314i.news.po.User; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import javax.servlet.http.HttpServletRequest; import java.util.HashMap; import java.util.List; import java.util.Map; public class UserServiceImpl implements UserService { private static Logger logger= (Logger) LoggerFactory.getLogger(UserServiceImpl.class); @Autowired private UserMapper userMapper; public User findUserById(int uid) throws Exception { return userMapper.findUserById(uid); } public List<User> findUsersList() throws Exception { return userMapper.findUsersList(); } public void insertUser(User user) throws Exception { userMapper.insertUser(user); } @Override public boolean isadminUser(User user, HttpServletRequest request) throws TheException { User usersql= null; boolean state=false; if(user!=null&&!(user.getUsername().trim().isEmpty()||user.getPassword().trim().isEmpty())){ try { usersql = userMapper.findUserByName(user.getUsername()); } catch (Exception e) { logger.error("数据查询失败请稍后再试"); throw new TheException("数据查询失败请稍后再试"); } if(usersql!=null){ if(user.getUsername().equals(usersql.getUsername())&& user.getPassword().equals(usersql.getPassword())) { state = true; request.getSession().setAttribute("user_session",usersql); }else { logger.info("用户名:"+usersql.getUid()+":"+user.getUsername()+"| 错误信息:密码或者账号错误"); throw new TheException("密码或者账号错误"); } }else{ logger.info("用户名:"+user.getUsername()+" |错误信息:用户不存在"); throw new TheException("密码或者账号错误"); } } return state; } @Override public int findAllCounts() throws Exception { return userMapper.findAllCounts(); } public void updateUser(User user)throws Exception{ userMapper.updateUser(user); } @Override public void deleteUserById(int uid) throws Exception { userMapper.deleteUserById(uid); } @Override public User findUserByName(String username) throws Exception { return userMapper.findUserByName(username); } } <file_sep>package com.i1314i.news.po; import java.util.List; public class PageBean<T> { private int pagecode;//当前页码 private int totalpage;//总页数 private int totalrecord;//总记录数 private int pagesize;//每页记录数 private List<T> beanList; //当前页记录 private int typeid; private List<T> hot; private List<T> newsOfTime;//最新 public List<T> getHot() { return hot; } public void setHot(List<T> hot) { this.hot = hot; } public List<T> getNewsOfTime() { return newsOfTime; } public void setNewsOfTime(List<T> newsOfTime) { this.newsOfTime = newsOfTime; } private String typename; public int getTypeid() { return typeid; } public String getTypename() { return typename; } public void setTypename(String typename) { this.typename = typename; } public void setTypeid(int typeid) { this.typeid = typeid; } public int getPagecode() { return pagecode; } public void setPagecode(int pagecode) { this.pagecode = pagecode; } public int getTotalpage() { return totalpage; } public void setTotalpage(int totalpage) { this.totalpage = totalpage; } public int getTotalrecord() { return totalrecord; } public void setTotalrecord(int totalrecord) { this.totalrecord = totalrecord; } public int getPagesize() { return pagesize; } public void setPagesize(int pagesize) { this.pagesize = pagesize; } public List<T> getBeanList() { return beanList; } public void setBeanList(List<T> beanList) { this.beanList = beanList; } } <file_sep>package com.i1314i.news.service; import com.i1314i.news.po.News; import com.i1314i.news.po.PageBean; import com.i1314i.news.po.User; import com.i1314i.news.service.Exception.TheException; import javax.servlet.http.HttpServletRequest; import java.util.List; import java.util.Map; public interface UserService { public User findUserById(int uid)throws Exception; public List<User> findUsersList()throws Exception; public void insertUser(User user)throws Exception; public boolean isadminUser(User user,HttpServletRequest request) throws TheException; public int findAllCounts()throws Exception; public void updateUser(User user)throws Exception; public void deleteUserById(int uid)throws Exception; public User findUserByName(String username)throws Exception; } <file_sep>package com.i1314i.news.mapper; import com.i1314i.news.po.News; import com.i1314i.news.po.User; import java.util.List; import java.util.Map; public interface UserMapper { User findUserById(int uid)throws Exception; List<User>findUsersList()throws Exception; void insertUser(User user)throws Exception; int findAllCounts()throws Exception; void updateUser(User user)throws Exception; User findUserByName(String username)throws Exception; void deleteUserById(int uid)throws Exception; } <file_sep>package com.i1314i.news.controller; import com.i1314i.news.utils.VerifyCodeUtils; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.io.FileUtils; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.HashMap; import java.util.Map; @Controller public class ImagesController { @RequestMapping(value = "/getimages") public void getImage(HttpServletResponse response, HttpServletRequest request) throws Exception { response.setHeader("contentType", "text/html; charset=utf-8"); response.setContentType("text/html;charset=utf-8"); request.setCharacterEncoding("utf-8"); response.setHeader("Pragma", "No-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0); response.setContentType("image/jpeg"); //生成随机字串 String verifyCode = VerifyCodeUtils.generateVerifyCode(4); //存入会话session HttpSession session = request.getSession(true); //删除以前的 session.removeAttribute("verCode"); session.setAttribute("verCode", verifyCode.toLowerCase()); //生成图片 int w = 150, h = 37; VerifyCodeUtils.outputImage(w, h, response.getOutputStream(), verifyCode); } @RequestMapping(value = "/verifycodeValidate", method = {RequestMethod.GET, RequestMethod.POST}) public @ResponseBody boolean verifycode(String verifycode, HttpServletRequest request) throws Exception { HttpSession session = request.getSession(); String verify = (String) session.getAttribute("verCode"); if (verify.equals(verifycode)) { return true; } else return false; } @RequestMapping(value = "admin/html/adminhtml/uploadImage") private void uploadImage(HttpServletRequest request, HttpServletResponse response, HttpSession session, @RequestParam MultipartFile[] upload) { response.setCharacterEncoding("UTF-8"); PrintWriter out = null; try { out = response.getWriter(); } catch (IOException e1) { e1.printStackTrace(); } String callback = request.getParameter("CKEditorFuncNum"); // 获得response,request Map<String, Object> m = new HashMap<String, Object>(); if (!ServletFileUpload.isMultipartContent(request)) { m.put("error", 1); m.put("message", "请选择文件!"); } String originalFileName = null;//上传的图片文件名 String fileExtensionName = null;//上传图片的文件扩展名 for (MultipartFile file : upload) { if (file.getSize() > 10 * 1024 * 1024) { out.println("<script type=\"text/javascript\">"); out.println("window.parent.CKEDITOR.tools.callFunction(" + callback + ",''," + "'文件大小不得大于10M');"); out.println("</script>"); } originalFileName = file.getOriginalFilename(); fileExtensionName = originalFileName.substring( originalFileName.lastIndexOf("."), originalFileName.length()).toLowerCase(); String[] imageExtensionNameArray = WebsiteConstant.IMAGE_EXTENSION_NAME_ARRAY; String allImageExtensionName = ""; boolean isContain = false;//默认不包含上传图片文件扩展名 for (int i = 0; i < imageExtensionNameArray.length; i++) { if (fileExtensionName.equals(imageExtensionNameArray[i])) { isContain = true; } if (i == 0) { allImageExtensionName += imageExtensionNameArray[i]; } else { allImageExtensionName += " , " + imageExtensionNameArray[i]; } } String newFileName = java.util.UUID.randomUUID().toString() + fileExtensionName; String uploadPath = WebsiteConstant.PIC_APP_FILE_SYSTEM_CKEDITOR_LOCATION; if (isContain) {//包含 File pathFile = new File(uploadPath); if (!pathFile.exists()) { // 如果路径不存在,创建 pathFile.mkdirs(); } try { FileUtils.copyInputStreamToFile(file.getInputStream(), new File(uploadPath, newFileName)); // InputStream is=file.getInputStream(); // File toFile = new File(uploadPath, newFileName); // OutputStream os = new FileOutputStream(toFile); // byte[] buffer = new byte[1024]; // int length = 0; // while ((length = is.read(buffer)) > 0) { // os.write(buffer, 0, length); // } // is.close(); // os.close(); } catch (IOException e) { System.out.println(e.getMessage()); } String imageUrl = WebsiteConstant.PIC_APP_SERVER_URL + "images/ckeditor/" + newFileName; // 返回"图像信息"选项卡并显示图片 ,在对应的文本框中显示图片资源url out.println("<script type=\"text/javascript\">"); out.println("window.parent.CKEDITOR.tools.callFunction(" + callback + ",'" + imageUrl + "','')"); out.println("</script>"); } else { out.println("<script type=\"text/javascript\">"); out.println("window.parent.CKEDITOR.tools.callFunction(" + callback + ",''," + "'文件格式不正确(必须为" + allImageExtensionName + "文件)');"); out.println("</script>"); } } } public static class WebsiteConstant { public static String[] IMAGE_EXTENSION_NAME_ARRAY = {".jpg", ".jpeg", ".png", ".gif", ".bmp"}; public static String PIC_APP_SERVER_URL = "http://localhost:8080/Picture/"; public static String PIC_APP_FILE_SYSTEM_CKEDITOR_LOCATION = "D:/Picture/images/ckeditor/"; public final int SUCCESS = 1; // 操作成功 } }<file_sep>package com.i1314i.news.controller; import com.i1314i.news.mapper.LinkMapper; import com.i1314i.news.po.*; import com.i1314i.news.service.NewsService; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import java.util.ArrayList; import java.util.List; @Controller public class NewsController { private static Logger logger=Logger.getLogger(NewsController.class); @Autowired private NewsService newsService; @Autowired private LinkMapper linkMapper; @RequestMapping(value = "index",method = {RequestMethod.GET,RequestMethod.POST}) public String findAllTyoe(Model model)throws Exception{ List<Type> Types=newsService.findAllType(); int typenumber=newsService.findAllCountType(); for(int i=0;i<Types.size();i++){ PageBean<News> pageBean = newsService.findAll(1,8,Types.get(i).getId()); Types.get(i).setPageBean(pageBean); } List<Link>links = linkMapper.selectLinks(); model.addAttribute("links",links); model.addAttribute("typenumber",typenumber); model.addAttribute("types",Types); return "foreground/index"; } @RequestMapping(value = "/newslist",method = {RequestMethod.POST,RequestMethod.GET}) public String NewsList(Model model,@RequestParam(required = false) Integer type, @RequestParam(required = false) Integer currPage)throws Exception{ if(currPage==null&&type==null){ currPage=1; type=1; } else if(currPage==null){ currPage=1; }else if(type==null){ type=1; } //种类 List<Type> Types=newsService.findAllType(); //热门 List<News>NewsByHot=newsService.findByHot(1,8); List<News>NewsOfTime=newsService.findAllTimes(1,8); int pageSize=15; PageBean<News> pageBean = newsService.findAll(currPage,pageSize,type); int totalrecord=newsService.findAllCount(type); int totalpage = totalrecord/pageSize; if(totalpage==0){ totalpage=1; }else{ totalpage+=1; } String typename=newsService.findTypeById(type); pageBean = newsPageBean(pageBean,type,typename,currPage,pageSize,totalpage,totalrecord,NewsByHot,NewsOfTime); model.addAttribute("pageBean",pageBean); model.addAttribute("types",Types); return "foreground/newsList"; } //页面数据 public PageBean<News> newsPageBean(PageBean<News> pageBean,int typeid,String Typename,int pagecode,int pagesize, int totalpage,int totalrecord,List<News>hot,List<News>newsOfTime){ PageBean<News>newsPageBean = pageBean; newsPageBean.setPagecode(pagecode); newsPageBean.setPagesize(pagesize); //页面大小 newsPageBean.setTotalpage(totalpage); //总页数 newsPageBean.setTotalrecord(totalrecord);//总记录数 newsPageBean.setTypeid(typeid); newsPageBean.setTypename(Typename); newsPageBean.setHot(hot); newsPageBean.setNewsOfTime(newsOfTime); return newsPageBean; } @RequestMapping(value = "/content",method = {RequestMethod.POST,RequestMethod.GET}) public String NewsContent(Model model,@RequestParam(required = false) Integer id,@RequestParam(required = false)Integer type) throws Exception { if(id==null&&type==null){ id=1; type=1; } else if(id==null){ id=1; }else if(type==null){ type=1; } //浏览量 int hits=newsService.findByHits(id); hits++; newsService.updateHits(id,hits); //上一篇下一篇 News newsc = newsService.findNewsById(id); int count=newsService.findCountNews(); News lastnew=null; News nextnew=null; if(id>=1&id<count){ nextnew=newsService.findNewsById(id+1); } if(id>1&&id<=count){ lastnew=newsService.findNewsById(id-1); } List<Type> Types=newsService.findAllType(); List<News>NewsByHot=newsService.findByHot(1,8); List<News>NewsOfTime=newsService.findAllTimes(1,8); ContentBean<News>contentBean=new ContentBean<News>(); String types=newsService.findTypeByNewsd(id,type); contentBean=newsContentBean(contentBean,types,count,newsc,NewsByHot,NewsOfTime,lastnew,nextnew); model.addAttribute("contentBean",contentBean); model.addAttribute("types",Types); return "foreground/newsShow"; } public ContentBean<News>newsContentBean(ContentBean<News> contentBean,String types,int count, News newsc,List<News>NewsByHot, List<News>NewsOfTime, News lastnew,News nextnew ){ contentBean.setType(types); //类型 contentBean.setCount(count);//数量 contentBean.setNews(newsc);//new contentBean.setHot(NewsByHot);//热点新闻 contentBean.setNewsOfTime(NewsOfTime);//最新新闻 contentBean.setLastnew(lastnew);//上一条 contentBean.setNextnew(nextnew);//下一条 return contentBean; } }<file_sep>package com.i1314i.news.controller; import org.apache.log4j.Logger; import org.junit.Test; import static org.junit.Assert.*; public class logTest { private static Logger logger=Logger.getLogger(logTest.class); @Test public void test1() throws Exception { try { System.out.println(1 / 0); } catch (Exception e) { logger.error(e.getMessage()); } } }<file_sep>package com.i1314i.news.controller; import com.i1314i.news.po.Msg; import com.i1314i.news.po.User; import com.i1314i.news.service.Exception.TheException; import com.i1314i.news.service.NewsService; import com.i1314i.news.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @Controller public class LoginController { @Autowired private UserService userService; private Msg msg=null; @RequestMapping(value = "/login",method = {RequestMethod.POST}) public @ResponseBody Msg AddNewUser(@RequestBody User user, HttpServletRequest request){ msg=new Msg(); boolean isuser= false; try { isuser = userService.isadminUser(user,request); } catch (TheException e) { msg.setSuccess(0); msg.setMsg(e.getMessage()); return msg; } if(isuser){ msg.setMsg("成功"); msg.setSuccess(1); } return msg; } @RequestMapping(value = "/logins") public String lo(HttpServletRequest request, HttpServletResponse response)throws Exception{ request.getRequestDispatcher("/admin/html/login/login.html").forward(request,response); return ""; } } <file_sep>package com.i1314i.news.mapper; import com.i1314i.news.po.Link; import java.util.List; public interface LinkMapper { void insertLink(Link link) throws Exception; void updateLink(Link link) throws Exception; List<Link>selectLinks()throws Exception; Link findLinkById(int lid)throws Exception; void deleteLinkById(int lid)throws Exception; } <file_sep>package com.i1314i.news.controller; import com.i1314i.news.mapper.LinkMapper; import com.i1314i.news.po.Link; import com.i1314i.news.po.Msg; import com.i1314i.news.po.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletRequest; import java.util.List; @Controller @RequestMapping("/admin/html/adminhtml") public class LinkController { @Autowired private LinkMapper linkMapper; private Msg msg; Link linksql=null; @RequestMapping(value = "/linkcontrol") public String LinkMange(Model model,HttpServletRequest request)throws Exception{ User user = (User) request.getSession().getAttribute("user_session"); List<Link>links=linkMapper.selectLinks(); model.addAttribute("links",links); model.addAttribute("user",user); return "link_control"; } @RequestMapping(value = "/addLink",method = {RequestMethod.POST}) public @ResponseBody Msg addLink(@RequestBody Link link)throws Exception{ Link linsql = null; if(link.getLid()!=0){ linsql=linkMapper.findLinkById(link.getLid()); } msg=new Msg(); msg.setSuccess(0); if(linsql==null){ linkMapper.insertLink(link); msg.setSuccess(1); msg.setMsg("添加数据成功"); }else{ link.setLid(linsql.getLid()); linkMapper.updateLink(link); msg.setSuccess(1); msg.setMsg("修改数据成功"); } return msg; } @RequestMapping(value = "/getLink",method = {RequestMethod.POST}) public @ResponseBody Link link(@RequestBody Link link)throws Exception{ if(link.getLid()!=0){ linksql=linkMapper.findLinkById(link.getLid()); if(linksql!=null){ linksql.setSuccess(1); }else{ linksql.setSuccess(0); } } return linksql; } @RequestMapping(value = "/deleteLink",method = {RequestMethod.POST}) public @ResponseBody Msg deleMsg(@RequestBody Link link)throws Exception{ msg=new Msg(); linksql=null; if(link.getLid()!=0){ linksql=linkMapper.findLinkById(link.getLid()); if(linksql==null){ msg.setSuccess(0); msg.setMsg("所删除资源不存在"); }else{ linkMapper.deleteLinkById(link.getLid()); msg.setSuccess(1); msg.setMsg("删除成功"); } } return msg; } }
00ed17a8f5bde3607f67ad7ec0d8dbc2edc27a13
[ "Java" ]
12
Java
hkxiaoyao/news-1
dacf3c6f5a365feb63e56006cb3591084b1e1843
0b6e4e65053c2d919ac4354b263871aa7b42994f
refs/heads/master
<repo_name>hstove/bandcampbx<file_sep>/lib/bandcampbx/entities/balance.rb require_relative './base' module BandCampBX module Entities class Balance < Base def self.mappings { usd_balance: map_decimal, btc_balance: map_decimal } end def self.attribute_names { usd_balance: "Total USD", btc_balance: "Total BTC" } end setup_readers end end end <file_sep>/lib/bandcampbx/mapper.rb require_relative './entities/balance' require_relative './entities/order' module BandCampBX class Mapper def initialize end def map_balance(json) Entities::Balance.new(parsed(json)) end def map_orders(json) orders_data = parsed(json) # NOTE: This is because when there are no orders of a given type, the response looks like: {"Buy":[{"Info":"No open Buy Orders"}], ...} orders_data = { "Buy" => without_empty_results(orders_data["Buy"]), "Sell" => without_empty_results(orders_data["Sell"]) } orders = [] orders += orders_data["Buy"].map{|o| map_order(o.merge(type: :buy)) } orders += orders_data["Sell"].map{|o| map_order(o.merge(type: :sell)) } orders end def map_trade(trade) handle_error(parsed(trade)) parsed(trade)["Success"].to_i end def map_order(order) handle_error(parsed(order)) begin Entities::Order.new(parsed(order)) # NOTE: They give back {"Success"=>"1000486"} - we can't map that to an order rescue Exception => e raise StandardError.new(e.message) end end def map_cancel(result) parsed(result) == 'true' end def map_ticker(result) parsed_result = parsed(result) { ask: parsed_result["Best Ask"].to_f, bid: parsed_result["Best Bid"].to_f, trade: parsed_result["Last Trade"].to_f } end private # Allow passing either a String or anything else in. If it's not a string, # we assume we've already parsed it and just give it back to you. This # allows us to handle things like collections more easily. def parsed(json) if(json.is_a?(String)) BandCampBX::Helpers.json_parse(json) else json end end def handle_error(data) raise StandardError.new(data["Error"]) if is_error?(data) end def is_error?(data) data.has_key?("Error") end def without_empty_results(orders) orders.reject{|order| order["Info"] =~ /\ANo open/ } end end end <file_sep>/lib/bandcampbx/entities/order.rb require_relative './base' module BandCampBX module Entities class Order < Base class InvalidTypeError < StandardError; end def self.map_type ->(val) do case val.to_s when 'Quick Sell' :sell when 'Quick Buy' :buy else raise InvalidTypeError end end end def self.mappings { id: map_int, datetime: map_time, type: map_type, price: map_decimal, amount: map_decimal } end def self.attribute_names { id: "Order ID", datetime: "Order Entered", type: "Order Type", price: "Price", amount: "Quantity" } end setup_readers end end end <file_sep>/lib/bandcampbx.rb require_relative './bandcampbx/version' require_relative './bandcampbx/client' require 'multi_json' require 'json' module BandCampBX class StandardError < ::StandardError; end class InvalidTradeTypeError < StandardError; end module Helpers def self.json_parse(string) MultiJson.load(string) end end end <file_sep>/spec/unit/bandcampbx/mapper_spec.rb require_relative '../../spec_helper' describe BandCampBX::Mapper do subject(:mapper) { described_class.new } let(:json_object){ '{"foo": "bar"}' } let(:json_array){ '[{"foo": "bar"}]' } describe '#map_balance' do let(:balance) { double } before do Entities::Balance.stub(:new).and_return(balance) end it "maps a balance API response into a Balance entity" do mapper.map_balance(json_object) expect(Entities::Balance).to have_received(:new).with(json_parse(json_object)) end it "returns the mapped Balance entity" do expect(mapper.map_balance(json_object)).to eq(balance) end end describe '#map_order' do let(:order) { double } end describe '#map_orders' do let(:order) { double } it "filters out empty results appropriately" do empty_json = '{"Buy": [{"Info":"No open Buy Orders"}], "Sell": [{"Info":"No open Sell Orders"}]}' expect(mapper.map_orders(empty_json)).to eq([]) end it "returns an Order if mapped appropriately" do Entities::Order.stub(:new).and_return(order) expect(mapper.map_order(json_object)).to eq(order) end it "raises a StandardError if it doesn't know what to do with a mapping" do expect{ mapper.map_order('{}') }.to raise_error(StandardError) end it "raises an InvalidTradeTypeError if that message comes back from the API" do expect{ mapper.map_order('{"Error":"Invalid trade type."}') }.to raise_error(StandardError, "Invalid trade type.") end end describe '#map_cancel' do it "maps a cancel API response to a boolean" do expect(mapper.map_cancel('"true"')).to eq(true) expect(mapper.map_cancel('"false"')).to eq(false) end end describe "#map_ticker" do it "maps a ticker response to a JSON object" do json_string = "{\"Last Trade\":\"143.23\",\"Best Bid\":\"142.92\",\"Best Ask\":\"143.99\"}" json_object = {trade: 143.23, bid: 142.92, ask: 143.99} expect(mapper.map_ticker(json_string)).to eq(json_object) end end end <file_sep>/spec/unit/bandcampbx_spec.rb require_relative '../spec_helper' describe BandCampBX do it "should be an instance rather than a singleton" do client = BandCampBX::Client.new expect(client.key).to eq(nil) expect(client.secret).to eq(nil) client.key = '1' client.secret = '2' expect(client.key).to eq('1') expect(client.secret).to eq('2') end end <file_sep>/lib/bandcampbx/client.rb require_relative 'net' require_relative 'mapper' require 'bigdecimal/util' module BandCampBX class Client attr_accessor :key attr_accessor :secret def initialize(key = nil, secret = nil) @key = key @secret = secret end def balance mapper.map_balance(net.post("myfunds.php")) end def orders mapper.map_orders(net.post("myorders.php")) end def buy!(quantity, price, order_type) trade!("tradeenter.php", quantity, price, order_type) end def sell!(quantity, price, order_type) trade!("tradeenter.php", quantity, price, order_type) end def cancel(id, type) wrapping_standard_error do mapper.map_cancel(net.post("tradecancel.php", { id: id.to_s, type: type.to_s })) end end def ticker mapper.map_ticker(net.post("xticker.php")) end private def net @net ||= Net.new(self) end def mapper @mapper ||= Mapper.new end def trade!(endpoint, quantity, price, order_type) wrapping_standard_error do response = net.post(endpoint, { Price: price.to_digits, Quantity: quantity.to_digits, TradeMode: order_type.to_s }) mapper.map_trade(response) end end def wrapping_standard_error &block begin yield rescue ::StandardError => e raise BandCampBX::StandardError.new(e.message) end end end end <file_sep>/spec/unit/bandcampbx/net_spec.rb require_relative '../../spec_helper' describe BandCampBX::Net do let(:client){ double } subject(:net) { described_class.new(client) } before do client.stub(:secret).and_return(1) client.stub(:key).and_return(2) end it 'gets instantiated with a client' do expect(net.client).to eq(client) end it 'defers to its client for secret' do expect(net.secret).to eq(1) end it 'defers to its client for key' do expect(net.key).to eq(2) end describe '#post' do describe 'any_endpoint' do let(:example_balance) do <<-JSON { "foo": "bar" } JSON end before do FakeWeb.register_uri(:post, "https://campbx.com/api/myfunds.php", body: example_balance) end it "queries the appropriate endpoint and returns its body as a string" do expect(json_parse(net.post('myfunds.php'))).to eq(json_parse(example_balance)) end end end end <file_sep>/README.md #BandCampBX BandCampBX is a gem for accessing CampBX's Private API ## Installation Add this line to your application's Gemfile: gem 'bandcampbx', github: 'megalithic/bandcampbx' And then execute: $ bundle ## License This software is licensed under [the MIT License.](./LICENSE.md) <file_sep>/spec/integration/client_spec.rb require_relative '../spec_helper' describe "Integrating a client" do subject{ Client.new } before do subject.secret = '1' subject.key = '2' end it "handles #balance" do example_balance = <<-JSON { "Total USD":"0.20", "Total BTC":"0.10000000", "Liquid USD":"0.00", "Liquid BTC":"0.08000000", "Margin Account USD":"0.00", "Margin Account BTC":"0.00000000" } JSON FakeWeb.register_uri(:post, "https://campbx.com/api/myfunds.php", body: example_balance) bal = subject.balance expect(bal.btc_balance).to eq(BigDecimal('0.1')) expect(bal.usd_balance).to eq(BigDecimal('0.2')) end it "handles #orders" do example_orders = <<-JSON { "Buy":[ {"Info":"No open Buy Orders"} ], "Sell":[ { "Order Entered":"2013-08-13 16:06:29", "Order Expiry":"2013-11-20 15:06:29", "Order Type":"Quick Sell", "Margin Percent":"None", "Quantity":"0.01000000", "Price":"108.00", "Stop-loss":"No", "Fill Type":"Incr", "Dark Pool":"No", "Order ID":"1000486" }, { "Order Entered":"2013-08-13 16:04:33", "Order Expiry":"2013-11-20 15:04:33", "Order Type":"Quick Sell", "Margin Percent":"None", "Quantity":"0.01000000", "Price":"108.00", "Stop-loss":"No", "Fill Type":"Incr", "Dark Pool":"No", "Order ID":"1000477" } ] } JSON FakeWeb.register_uri(:post, "https://campbx.com/api/myorders.php", body: example_orders) orders = subject.orders expect(orders[0].type).to eq(:sell) end context "handling #buy!" do it "succeeds properly" do example_buy_response = <<-JSON \r\n {"Success":"1010399"} JSON FakeWeb.register_uri(:post, "https://campbx.com/api/tradeenter.php", body: example_buy_response) buy = subject.buy!(BigDecimal('1'), BigDecimal('100'), "QuickBuy") expect(buy).to eq(1010399) end it "fails properly" do example_buy_response = <<-JSON {"Error":"Minimum quantity for a trade is :1000000 Satoshis."} JSON FakeWeb.register_uri(:post, "https://campbx.com/api/tradeenter.php", body: example_buy_response) expect{ subject.buy!(BigDecimal('0.01'), BigDecimal('100'), 'QuickBuy') }.to raise_error(BandCampBX::StandardError, "Minimum quantity for a trade is :1000000 Satoshis.") end end it "handles #sell!" do example_sell_response = <<-JSON \r\n {"Success":"1010399"} JSON FakeWeb.register_uri(:post, "https://campbx.com/api/tradeenter.php", body: example_sell_response) sell = subject.sell!(BigDecimal('1'), BigDecimal('100'), "QuickSell") expect(sell).to eq(1010399) end it "handles #cancel" do example_cancel_response = <<-JSON "true" JSON FakeWeb.register_uri(:post, "https://campbx.com/api/tradecancel.php", body: example_cancel_response) cancel = subject.cancel(12345, "Buy") expect(cancel).to eq(true) end it "handles #ticker" do example_ticker_response = <<-JSON {"Last Trade":"143.23","Best Bid":"142.92","Best Ask":"143.99"} JSON FakeWeb.register_uri(:post, "https://campbx.com/api/xticker.php", body: example_ticker_response) ticker = subject.ticker expect(ticker).to eq({trade: 143.23, bid: 142.92, ask: 143.99}) end end
589a223b06c4fd67a715002bf35e95a45595e58e
[ "Markdown", "Ruby" ]
10
Ruby
hstove/bandcampbx
f2fb33794c25569843a635cca7a0fc0549b3c39c
09c6c5bb921a34018e8df4204e1b1674806265ff
refs/heads/master
<repo_name>zhoujun134/java<file_sep>/hbase/src/main/java/learm/forclass/experiment/EXP02.java package learm.forclass.experiment; import learm.forclass.utils.HBaseUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.HColumnDescriptor; import org.apache.hadoop.hbase.HTableDescriptor; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.client.*; import org.apache.hadoop.hbase.util.Bytes; import java.io.*; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; public class EXP02{ /** * 列族 f , 一个列族 * 1, 编号 id * 2, 时间 T 作为行健 * 3, 区域 L * 4, 电流 I * 5, 电压 V * 6, 功率 P */ public static void main(String[] args){ // writeData(); writeHbase(getDataToList()); } /** * 自动生成一分钟内的模拟数据 */ static void writeData(){ // file(内存)----输入流---->【程序】----输出流---->file(内存) File file = new File("E:\\git\\java\\hbase\\src\\main\\resources", "electricity.txt"); try { boolean newFile = file.createNewFile();// 创建文件 } catch (IOException e) { e.printStackTrace(); } // 向文件写入内容(输出流) String[] location = {"001","002","003","004","005","006","007", "008","009","010","011","012","013","014","015"}; String data = " "; String data2 = " "; String data3 = " "; String data4 = " "; String data5 = " "; DecimalFormat df = new DecimalFormat("######0.00"); for(int j=0; j< 60; j++){ for(int i=0; i<10000; i++){ String id = i + ""; if(i<10) id = "0000" + i; else if(i<100) id = "000" + i; else if(i<1000) id = "00" + i; else id = "0" + i; String time = System.currentTimeMillis() + ""; String electricity = (int)(Math.random() * 10) + ""; String local = location[(int)(Math.random() * 15)]; String voltage = (218+(int)(Math.random()*6)) + ""; String power = df.format(0.8 + ((int)(Math.random()*15))*0.01) + ""; String electricity2 = (int)(Math.random() * 10) + ""; String voltage2 = (218+(int)(Math.random()*6)) + ""; String power2 = df.format(0.8 + ((int)(Math.random()*15))*0.01) + ""; String electricity3 = (int)(Math.random() * 10) + ""; String voltage3 = (218+(int)(Math.random()*6)) + ""; String power3 = df.format(0.8 + ((int)(Math.random()*15))*0.01) + ""; String electricity4 = (int)(Math.random() * 10) + ""; String voltage4 = (218+(int)(Math.random()*6)) + ""; String power4 = df.format(0.8 + ((int)(Math.random()*15))*0.01) + ""; String electricity5 = (5+(int)(Math.random() * 6)) + ""; String voltage5 = (218+(int)(Math.random()*6)) + ""; String power5 = df.format(0.8 + ((int)(Math.random()*15))*0.01) + ""; data = " " + id + "," + time + "," + local + ","+electricity + ","+ voltage + "," + power + "\n\t"; data2 = " " + id + "," + time + "," + local + "," + electricity2 + ","+ voltage2 + "," + power2 + "\n\t"; data3 = " " + id + "," + time + "," + local + "," + electricity3 + ","+ voltage3 + "," + power3 + "\n\t"; data4 = " " + id + "," + time + "," + local + "," + electricity4 + ","+ voltage4 + "," + power4 + "\n\t"; data5 = " " + id + "," + time + "," + local + "," + electricity5 + ","+ voltage5 + "," + power5 + "\n\t"; // System.out.println("1----- id: = " + id + // " time: = " + time + " electricity: = " + electricity2 // + " local: = " + local + " voltage: = " + voltage2 + " power: = "+ // power2); // // System.out.println("2----- id: = " + id + // " time: = " + time + " electricity: = " + electricity3 // + " local: = " + local + " voltage: = " + voltage3 + " power: = "+ // power3); // // System.out.println("3----- id: = " + id + // " time: = " + time + " electricity: = " + electricity // + " local: = " + local + " voltage: = " + voltage + " power: = "+ // power); // // System.out.println("4----- id: = " + id + // " time: = " + time + " electricity: = " + electricity4 // + " local: = " + local + " voltage: = " + voltage4 + " power: = "+ // power4); // // System.out.println("5----- id: = " + id + // " time: = " + time + " electricity: = " + electricity5 // + " local: = " + local + " voltage: = " + voltage5 + " power: = "+ // power5); try { Thread.sleep(5); } catch (InterruptedException e) { e.printStackTrace(); } byte bt[] = new byte[1024]; byte bt2[] = new byte[1024]; byte bt3[] = new byte[1024]; byte bt4[] = new byte[1024]; byte bt5[] = new byte[1024]; bt = data.getBytes(); bt2 = data.getBytes(); bt3 = data.getBytes(); bt4 = data.getBytes(); bt5 = data.getBytes(); RandomAccessFile randomFile = null; try { // 打开一个随机访问文件流,按读写方式 randomFile = new RandomAccessFile("E:\\git\\java\\hbase\\src\\main\\resources\\electricity.txt", "rw"); // 文件长度,字节数 long fileLength = randomFile.length(); // 将写文件指针移到文件尾。 randomFile.seek(fileLength); randomFile.writeBytes(data); randomFile.writeBytes(data2); randomFile.writeBytes(data3); randomFile.writeBytes(data4); randomFile.writeBytes(data5); } catch (IOException e) { e.printStackTrace(); } finally{ if(randomFile != null){ try { randomFile.close(); } catch (IOException e) { e.printStackTrace(); } } } } System.out.println("j= " + j); } } /** * 将数据生成为List<<Put>> */ static List<List<Put>> getDataToList(){ List<List<Put>> data = new ArrayList<List<Put>>(); File file = new File("E:\\git\\java\\hbase\\src\\main\\resources\\electricity.txt"); BufferedReader reader = null; try { System.out.println("以行为单位读取文件内容,一次读一整行:"); reader = new BufferedReader(new FileReader(file)); String tempString = null; int line = 1; int index = 0; // 标识一个List的数据 List<Put> tempdata = new ArrayList<>(); String tmpid = ""; // 记录每行的 id 号 int factDataOfSeconds = 0; // 记录一个位置一秒钟的五条数据索引 // 一次读入一行,直到读入null为文件结束 while ((tempString = reader.readLine()) != null) { // 显示行号 // System.out.println("line " + line + ": " + tempString); line++; if(index < 50000) index++; else{ data.add(tempdata); // 添加到要返回的总的数据List中 if(data.size() >40) break; System.out.println(" 此时 data 的大小为:" + data.size()); tempdata = new ArrayList<Put>(); index =0 ; } String[] factData = tempString.split(","); if(factData.length == 6){ if(!tmpid.equals(factData[0])){ tmpid = factData[0]; factDataOfSeconds = 0; }else factDataOfSeconds++; /** * data = " " + id + "," + time + "," + local + "," + electricity4 + ","+ voltage4 + "," + power4 + "\n\t"; */ Put put = new Put(Bytes.toBytes(factData[1] + "--" + factDataOfSeconds)); put.addColumn(Bytes.toBytes("f"), Bytes.toBytes("id"), Bytes.toBytes(factData[0])); put.addColumn(Bytes.toBytes("f"), Bytes.toBytes("L"), Bytes.toBytes(factData[2])); put.addColumn(Bytes.toBytes("f"), Bytes.toBytes("I"), Bytes.toBytes(factData[3])); put.addColumn(Bytes.toBytes("f"), Bytes.toBytes("V"), Bytes.toBytes(factData[4])); put.addColumn(Bytes.toBytes("f"), Bytes.toBytes("P"), Bytes.toBytes(factData[5])); tempdata.add(put); } } reader.close(); } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException ignored) { ignored.printStackTrace(); } } } return data; } /** * 写入数据到 hbase 数据库中 * @param data 要写入的数据 List 的每一项为 50000条的数据 */ static void writeHbase(List<List<Put>> data){ Configuration conf = HBaseConfiguration.create(); Connection connection; try { connection = ConnectionFactory.createConnection(conf); Admin admin = connection.getAdmin(); System.out.println("原数据库中表不存在!开始创建..."); HTableDescriptor descriptor = new HTableDescriptor(TableName.valueOf("electricity")); descriptor.addFamily(new HColumnDescriptor("f".getBytes())); admin.createTable(descriptor); // if (!admin.tableExists(TableName.valueOf("electricity"))) { // System.out.println("原数据库中表不存在!开始创建..."); // HTableDescriptor descriptor = new HTableDescriptor(TableName.valueOf("electricity")); // descriptor.addFamily(new HColumnDescriptor("f".getBytes())); // admin.createTable(descriptor); // } else { // System.out.println(" 该表已经存在,不需要在创建!"); // } admin.close(); Table electricityTable = connection.getTable(TableName.valueOf("electricity")); System.out.println("开始插入数据时的时间为: " + ( new Date())); for(List<Put> tmpData: data ){ electricityTable.put(tmpData); } System.out.println("结束插入数据时的时间为: " + ( new Date())); electricityTable.close(); connection.close(); } catch (IOException e) { e.printStackTrace(); } } } <file_sep>/hadoop/src/main/java/hadoop/mr/areapartition/FlowSumArea.java package hadoop.mr.areapartition; import java.io.IOException; import hadoop.mr.flowsum.FlowBean; import org.apache.commons.lang.StringUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapred.InputFormat; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.OutputFormat; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; /** * 对流量原始日志进行流量统计,将不同省份的用户统计结果输出到不同文件 * 需要自定义改造两个机制: * 1、改造分区的逻辑,自定义一个partitioner * 2、自定义reduer task的并发任务数 * * @author <EMAIL> * */ public class FlowSumArea { public static class FlowSumAreaMapper extends Mapper<LongWritable, Text, Text, FlowBean> { @Override protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { //拿一行数据 String line = value.toString(); //切分成各个字段 String[] fields = StringUtils.split(line, "\t"); //拿到我们需要的字段 String phoneNB = fields[1]; long u_flow = Long.parseLong(fields[7]); long d_flow = Long.parseLong(fields[8]); //封装数据为kv并输出 context.write(new Text(phoneNB), new FlowBean(phoneNB,u_flow,d_flow)); } } public static class FlowSumAreaReducer extends Reducer<Text, FlowBean, Text, FlowBean> { @Override protected void reduce(Text key, Iterable<FlowBean> values, Context context) throws IOException, InterruptedException { long up_flow_counter = 0; long d_flow_counter = 0; for(FlowBean bean: values){ up_flow_counter += bean.getUp_flow(); d_flow_counter += bean.getD_flow(); } context.write(key, new FlowBean(key.toString(), up_flow_counter, d_flow_counter)); } } public static void main(String[] args) throws Exception { Configuration conf = new Configuration(); Job job = Job.getInstance(conf); job.setJarByClass(FlowSumArea.class); job.setMapperClass(FlowSumAreaMapper.class); job.setReducerClass(FlowSumAreaReducer.class); //设置我们自定义的分组逻辑定义 job.setPartitionerClass(AreaPartitioner.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(FlowBean.class); //设置reduce的任务并发数,应该跟分组的数量保持一致 job.setNumReduceTasks(5); FileInputFormat.setInputPaths(job, new Path(args[0])); FileOutputFormat.setOutputPath(job, new Path(args[1])); System.exit(job.waitForCompletion(true)?0:1); } }<file_sep>/spark/src/main/java/study/core/tmpclass/MyAccumulatorV2.java package study.core.tmpclass; import org.apache.spark.util.AccumulatorV2; public class MyAccumulatorV2 extends AccumulatorV2<String, String>{ private String result = "use0=0|user1=0|user2=0|user3=0"; /** * 当 AccumulatorV2 中存在类似数据不存在这种问题时,是否结束程序。 * @return */ @Override public boolean isZero() { return true; } /** * 拷贝一个新的 AccumulatorV2 * @return */ @Override public AccumulatorV2<String, String> copy() { MyAccumulatorV2 myAccumulatorV2 = new MyAccumulatorV2(); myAccumulatorV2.result = this.result; return myAccumulatorV2; } /** * 重置 AccumulatorV2 中的数据 */ @Override public void reset() { result = "user0=0|user1=0|user2=0|user3=0"; } /** * 操作数据累加方法实现 * @param v */ @Override public void add(String v) { String v1 = result; String v2 = v; // log.warn("v1 : " + v1 + " v2 : " + v2) if (v1 != null && v2 != null) { String newResult = ""; // 从v1中,提取v2对应的值,并累加 String oldValue = StringUtils.getFieldFromConcatString(v1, "\\|", v2); if (oldValue != null) { String newValue = (Integer.parseInt(oldValue) + 1) + ""; newResult = StringUtils.setFieldInConcatString(v1, "\\|", v2, String.valueOf(newValue)); } result = newResult; } } /** * 合并数据 * @param other */ @Override public void merge(AccumulatorV2<String, String> other) { if(other == this) result = other.value(); else throw new UnsupportedOperationException(); } /** * AccumulatorV2 对外访问的数据结果 * @return */ @Override public String value() { return result; } } <file_sep>/README.md # java java代码库 更新学习总结的代码 其中包括相关内容有: hadoop: mapreduce 程序代码 hbase: 数据库操作代码 java8: java 8 的新特性 spark: spark的基本操作 <file_sep>/hbase/src/main/java/learm/forclass/testclass/FilterListDEmo.java package learm.forclass.testclass; import learm.forclass.utils.HBaseUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.Cell; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.client.*; import org.apache.hadoop.hbase.filter.*; import org.apache.hadoop.hbase.util.Bytes; import java.io.IOException; import java.util.ArrayList; /** * Created by zhoujun on 17-10-16. */ public class FilterListDEmo { public static void main(String[] args) throws IOException { // HBaseUtils.createTable("table2","cf1,cf2"); // HBaseUtils.putDataH("table2","001","cf1","c2","1");; // HBaseUtils.putDataH("table2","001","cf1","c3","2");; // HBaseUtils.putDataH("table2","002","cf1","c1","3");; // HBaseUtils.putDataH("table2","005","cf1","c1","2");; // HBaseUtils.putDataH("table2","005","cf1","c2","1"); Configuration conf = HBaseConfiguration.create(); Connection connection = ConnectionFactory.createConnection(conf); Table table = connection.getTable(TableName.valueOf("table2")); Filter filter1 = new QualifierFilter(CompareFilter.CompareOp.NOT_EQUAL, new BinaryComparator(Bytes.toBytes("c2"))); Filter filter2 = new ValueFilter(CompareFilter.CompareOp.NOT_EQUAL, new BinaryComparator(Bytes.toBytes("3"))); FilterList filterList = new FilterList(FilterList.Operator.MUST_PASS_ALL, new ArrayList<Filter>(){{ this.add(filter1); this.add(filter2); }}); Scan scan = new Scan(); scan.setFilter(filterList); ResultScanner results = table.getScanner(scan); results.forEach(result -> { for (Cell cell : result.rawCells()) { System.out.println("Cell: " + cell + ", Value: " + Bytes.toString(cell.getValueArray(), cell.getValueOffset(), cell.getValueLength())); } }); } } <file_sep>/hbase/src/main/java/learm/forclass/experiment/Course.java package learm.forclass.experiment; import java.util.List; /** * Created by zhoujun on 17-11-9. */ public class Course { private String tilte; private String introduction; private String teacherId; private List<Student> students; public Course() { } public Course(String tilte, String introduction, String teacherId, List<Student> students) { this.tilte = tilte; this.introduction = introduction; this.teacherId = teacherId; this.students = students; } public String getTilte() { return tilte; } public void setTilte(String tilte) { this.tilte = tilte; } public String getIntroduction() { return introduction; } public void setIntroduction(String introduction) { this.introduction = introduction; } public String getTeacherId() { return teacherId; } public void setTeacherId(String teacherId) { this.teacherId = teacherId; } public List<Student> getStudents() { return students; } public void setStudents(List<Student> students) { this.students = students; } @Override public String toString() { return "Course{" + "tilte='" + tilte + '\'' + ", introduction='" + introduction + '\'' + ", teacherId='" + teacherId + '\'' + ", students=" + students + '}'; } } <file_sep>/hbase/src/main/java/learm/forclass/testclass/IncrementDemo.java package learm.forclass.testclass; import com.utils.HBaseHelper; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.client.Connection; import org.apache.hadoop.hbase.client.ConnectionFactory; import org.apache.hadoop.hbase.client.Table; import org.apache.hadoop.hbase.util.Bytes; import java.io.IOException; /** * Created by zhoujun on 17-10-16. */ public class IncrementDemo { public static void main(String[] args) throws IOException { Configuration conf = HBaseConfiguration.create(); HBaseHelper helper = HBaseHelper.getHelper(conf); helper.dropTable("testtable"); helper.createTable("testtable", "daily"); Connection connection = ConnectionFactory.createConnection(conf); Table table = connection.getTable(TableName.valueOf("testtable")); long cnt1 = table.incrementColumnValue( Bytes.toBytes("20110101"), Bytes.toBytes("daily"), Bytes.toBytes("hits"), 1); System.out.println("cnt1: " + cnt1 ); } } <file_sep>/java8/src/main/java/com/common/lambda/PersonComparator.java package com.common.lambda; import com.lambda.Person; import java.util.Comparator; /** * Created by zhoujun on 2017/9/6. */ public class PersonComparator implements Comparator<Person> { //为两个元素设定比较规则 public int compare(Person o1, Person o2){ //Person p1 = (Person)o1; //Person p2 = (Person)o2; return o1.getId() - o2.getId(); } } <file_sep>/hadoop/src/main/java/com/map/count/WordCount.java package com.map.count; import java.io.IOException; import java.util.StringTokenizer; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.util.GenericOptionsParser; public class WordCount { public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException{ Configuration conf = new Configuration(); conf.set("dfs.blocksize", "67108864"); //67108864 //配置作业名 @SuppressWarnings("deprecation") Job job = new Job(conf,"wordcount"); //配置作业的各个类 job.setJarByClass(WordCount.class); job.setMapperClass(TokenizerMapper.class); job.setCombinerClass(IntSumReducer.class); job.setReducerClass(IntSumReducer.class); job.setOutputKeyClass(Text.class); job.setOutputValueClass(IntWritable.class); FileInputFormat.setMinInputSplitSize(job, 33554432l); FileInputFormat.setMaxInputSplitSize(job, 67108864l); FileInputFormat.addInputPath(job, new Path("hdfs://zhoujun:9000/test/hly-temp-10pctl.txt")); FileOutputFormat.setOutputPath(job, new Path("hdfs://zhoujun:9000/output")); System.out.println("运行结束! "); System.exit(job.waitForCompletion(true) ? 0 : 1); } } //继承Mapper接口,设置map的输入类型为<Object,Text> //输出类型为<Text,IntWritable> class TokenizerMapper extends Mapper<Object,Text,Text,IntWritable> { //one表示单词出现一次 private final IntWritable one = new IntWritable(1); //word用于存储切下来的单词 private Text word = new Text(); public void map(Object key, Text value, Context context ) throws IOException,InterruptedException{ StringTokenizer itr = new StringTokenizer(value.toString());//对输入的行切词 System.out.println("info: " + itr.toString()); while(itr.hasMoreTokens()){ word.set(itr.nextToken());//切下的单词存入word context.write(word, one); } } } //继承Reduce接口,设置Reduce的接入类型为<Text,IntWritable> //输出类型为<Text,IntWritable> class IntSumReducer extends Reducer<Text, IntWritable, Text,IntWritable> { //result记录单词的频数 private IntWritable result = new IntWritable(); public void reduce(Text key, Iterable<IntWritable> values, Context context) throws IOException, InterruptedException{ int sum = 0; //对获取的<key,value-list>计算value的和 for(IntWritable val : values){ sum += val.get(); } //将频数设置到result中 result.set(sum); //收集结果 context.write(key, result); } }<file_sep>/java8/src/main/java/com/lambda/PanderImp.java package com.lambda; import com.interf.Pander; import java.util.function.Consumer; /** * Created by zhoujun on 2017/9/6. */ public class PanderImp implements Pander<String> { private String name; private int age; @Override public void speark(String msg) { log(msg); } @Override public void doSth(Consumer<String> consumer) { consumer.accept(name); } public String getName() { return name; } public PanderImp setName(String name) { this.name = name; return this; } public int getAge() { return age; } public PanderImp setAge(int age) { this.age = age; return this; } @Override public String toString() { return "PanderImp{" + "name='" + name + '\'' + ", age=" + age + '}'; } } <file_sep>/hbase/src/main/java/com/utils/HBaseHelper.java package com.utils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.*; import org.apache.hadoop.hbase.client.*; import org.apache.hadoop.hbase.util.Bytes; import java.io.Closeable; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Random; /** * Created by zhoujun on 2017/9/15. */ public class HBaseHelper implements Closeable { /** * zookeeper 地址 key */ public final static String ZK_QUORUM_KEY = "hbase.zookeeper.quorum"; /*** * zookeeper 集群端口地址 key */ public final static String ZK_CLIENT_PORT_KEY = "hbase.zookeeper.property.clientPort"; /** * HBase 位置 key */ public final static String HBASE_KEY = "hbase.rootdir"; /** * HBase 位置 value * 默认值是:192.168.27.132:9000 下的 hbase 数据库 */ private static String HBASE_VALUE = "hdfs://192.168.1.104:9000/hbase"; /** * ZooKeeper 位置 value * 默认值是:192.168.27.132 */ private static String ZK_VALUE = "192.168.1.104"; /** * zookeeper 服务端口 value * 默认值是:2181 */ private static String ZK_PORT_VALUE = "2181"; /** * 配置类 */ private Configuration configuration = null; /** * 连接类 */ private Connection connection = null; /** * 管理类 */ private Admin admin = null; /** * 构造函数 * @param configuration 配置信息 * @throws IOException */ protected HBaseHelper(Configuration configuration) throws IOException { this.configuration = configuration; this.connection = ConnectionFactory.createConnection(configuration); this.admin = connection.getAdmin(); } /** * 获取HBaseHelper 实例 * @param configuration 配置信息 * @return * @throws IOException */ public static HBaseHelper getHelper(Configuration configuration) throws IOException { return new HBaseHelper(configuration); } /** * 获取HBaseHelper 实例 * @return * @throws IOException */ public static HBaseHelper getHelper() throws IOException{ Configuration conf = HBaseConfiguration.create(); conf.set(HBaseHelper.ZK_CLIENT_PORT_KEY,HBaseHelper.getZkPortValue()); conf.set(HBaseHelper.ZK_QUORUM_KEY, HBaseHelper.getZkValue()); conf.set(HBaseHelper.HBASE_KEY, HBaseHelper.getHbaseValue()); return new HBaseHelper(conf); } @Override public void close() throws IOException { connection.close(); } /** * 获取连接对象 * @return */ public Connection getConnection() { return connection; } /** * 获取配置信息实例对象 * @return */ public Configuration getConfiguration() { return configuration; } /** * 创建命名空间 * @param namespace 命名空间 */ public void createNamespace(String namespace) { try { NamespaceDescriptor nd = NamespaceDescriptor.create(namespace).build(); admin.createNamespace(nd); } catch (Exception e) { System.err.println("Error: " + e.getMessage()); } } /** * 删除命名空间 * @param namespace 命名空间 * @param force 是否该命名空间下的删除所有表 */ public void dropNamespace(String namespace, boolean force) { try { if(force) { TableName[] tableNames = admin.listTableNamesByNamespace(namespace); for (TableName name : tableNames) { admin.disableTable(name); admin.deleteTable(name); } } } catch (Exception e) { // ignore } try { admin.deleteNamespace(namespace); } catch (IOException e) { System.err.println("Error: " + e.getMessage()); } } /** * 检查是否存在制定的表名 * @param table 表名 * @return * @throws IOException */ public boolean existsTable(String table) throws IOException { return existsTable(TableName.valueOf(table)); } /** * 检查是否存在制定的表名 * @param table 表名 * @return * @throws IOException */ public boolean existsTable(TableName table) throws IOException { return admin.tableExists(table); } /** * 创建一张表,默认的最大版本为:1, 不使用分区 * @param table 表名 * @param colfams 列祖成员 * @throws IOException */ public void createTable(String table, String... colfams) throws IOException { createTable(TableName.valueOf(table), 1, null, colfams); } /** * 创建一张表,默认的最大版本为:1, 不使用分区 * @param table 表名 * @param colfams 列族元素 * @throws IOException */ public void createTable(TableName table, String... colfams) throws IOException { createTable(table, 1, null, colfams); } /** * 指定最大版本创建一张表, 不使用分区 * @param table 表名 * @param maxVersions 最大版本值 * @param colfams 列族元素 * @throws IOException */ public void createTable(String table, int maxVersions, String... colfams) throws IOException { createTable(TableName.valueOf(table), maxVersions, null, colfams); } /** * 指定最大版本的创建一张表, 不使用分区 * @param table 表名 * @param maxVersions 最大版本值 * @param colfams 列族元素 * @throws IOException */ public void createTable(TableName table, int maxVersions, String... colfams) throws IOException { createTable(table, maxVersions, null, colfams); } /** * 创建一张表,最大版本数使 1, 使用分区 * @param table 表名 * @param splitKeys 分区的数组 * @param colfams 列族元素 * @throws IOException */ public void createTable(String table, byte[][] splitKeys, String... colfams) throws IOException { createTable(TableName.valueOf(table), 1, splitKeys, colfams); } /** * 指定表名,版本,分区列表,列族创建一张表 * @param table 表名 * @param maxVersions 最大版本值 * @param splitKeys 分区数 * @param colfams 列族元素 * @throws IOException */ public void createTable(TableName table, int maxVersions, byte[][] splitKeys, String... colfams) throws IOException { HTableDescriptor desc = new HTableDescriptor(table); Arrays.stream(colfams) .forEach(s -> { HColumnDescriptor coldef = new HColumnDescriptor(s); coldef.setMaxVersions(maxVersions); desc.addFamily(coldef); }); if (splitKeys != null) admin.createTable(desc, splitKeys); else admin.createTable(desc); } /** * 指定对应表失效 * @param table 表名 * @throws IOException */ public void disableTable(String table) throws IOException { disableTable(TableName.valueOf(table)); } /** * 指定对应表失效 * @param table 表名 * @throws IOException */ public void disableTable(TableName table) throws IOException { admin.disableTable(table); } /** * 删除对应表 * @param table 表名 * @throws IOException */ public void dropTable(String table) throws IOException { dropTable(TableName.valueOf(table)); } /** * 删除对应表 * @param table 表名 * @throws IOException */ public void dropTable(TableName table) throws IOException { if (existsTable(table)) { if (admin.isTableEnabled(table)) disableTable(table); admin.deleteTable(table); } } /** * 填充表的数据 * @param table * @param startRow * @param endRow * @param numCols * @param colfams * @throws IOException */ public void fillTable(String table, int startRow, int endRow, int numCols, String... colfams) throws IOException { fillTable(TableName.valueOf(table), startRow, endRow, numCols, colfams); } public void fillTable(TableName table, int startRow, int endRow, int numCols, String... colfams) throws IOException { fillTable(table, startRow, endRow, numCols, -1, false, colfams); } public void fillTable(String table, int startRow, int endRow, int numCols, boolean setTimestamp, String... colfams) throws IOException { fillTable(TableName.valueOf(table), startRow, endRow, numCols, -1, setTimestamp, colfams); } public void fillTable(TableName table, int startRow, int endRow, int numCols, boolean setTimestamp, String... colfams) throws IOException { fillTable(table, startRow, endRow, numCols, -1, setTimestamp, colfams); } public void fillTable(String table, int startRow, int endRow, int numCols, int pad, boolean setTimestamp, String... colfams) throws IOException { fillTable(TableName.valueOf(table), startRow, endRow, numCols, pad, setTimestamp, false, colfams); } public void fillTable(TableName table, int startRow, int endRow, int numCols, int pad, boolean setTimestamp, String... colfams) throws IOException { fillTable(table, startRow, endRow, numCols, pad, setTimestamp, false, colfams); } public void fillTable(String table, int startRow, int endRow, int numCols, int pad, boolean setTimestamp, boolean random, String... colfams) throws IOException { fillTable(TableName.valueOf(table), startRow, endRow, numCols, pad, setTimestamp, random, colfams); } public void fillTable(TableName table, int startRow, int endRow, int numCols, int pad, boolean setTimestamp, boolean random, String... colfams) throws IOException { Table tbl = connection.getTable(table); Random rnd = new Random(); for (int row = startRow; row <= endRow; row++) { for (int col = 1; col <= numCols; col++) { Put put = new Put(Bytes.toBytes("row-" + padNum(row, pad))); for (String cf : colfams) { String colName = "col-" + padNum(col, pad); String val = "val-" + (random ? Integer.toString(rnd.nextInt(numCols)) : padNum(row, pad) + "." + padNum(col, pad)); if (setTimestamp) { put.addColumn(Bytes.toBytes(cf), Bytes.toBytes(colName), col, Bytes.toBytes(val)); } else { put.addColumn(Bytes.toBytes(cf), Bytes.toBytes(colName), Bytes.toBytes(val)); } } tbl.put(put); } } tbl.close(); } public void fillTableRandom(String table, int minRow, int maxRow, int padRow, int minCol, int maxCol, int padCol, int minVal, int maxVal, int padVal, boolean setTimestamp, String... colfams) throws IOException { fillTableRandom(TableName.valueOf(table), minRow, maxRow, padRow, minCol, maxCol, padCol, minVal, maxVal, padVal, setTimestamp, colfams); } public void fillTableRandom(TableName table, int minRow, int maxRow, int padRow, int minCol, int maxCol, int padCol, int minVal, int maxVal, int padVal, boolean setTimestamp, String... colfams) throws IOException { Table tbl = connection.getTable(table); Random rnd = new Random(); int maxRows = minRow + rnd.nextInt(maxRow - minRow); for (int row = 0; row < maxRows; row++) { int maxCols = minCol + rnd.nextInt(maxCol - minCol); for (int col = 0; col < maxCols; col++) { int rowNum = rnd.nextInt(maxRow - minRow + 1); Put put = new Put(Bytes.toBytes("row-" + padNum(rowNum, padRow))); for (String cf : colfams) { int colNum = rnd.nextInt(maxCol - minCol + 1); String colName = "col-" + padNum(colNum, padCol); int valNum = rnd.nextInt(maxVal - minVal + 1); String val = "val-" + padNum(valNum, padCol); if (setTimestamp) { put.addColumn(Bytes.toBytes(cf), Bytes.toBytes(colName), col, Bytes.toBytes(val)); } else { put.addColumn(Bytes.toBytes(cf), Bytes.toBytes(colName), Bytes.toBytes(val)); } } tbl.put(put); } } tbl.close(); } public String padNum(int num, int pad) { String res = Integer.toString(num); if (pad > 0) { while (res.length() < pad) { res = "0" + res; } } return res; } /** * 插入一条数据 * @param table 表名 * @param row 行健 * @param fam 列族 * @param qual 列限定符 * @param val 值 * @throws IOException */ public void put(String table, String row, String fam, String qual, String val) throws IOException { put(TableName.valueOf(table), row, fam, qual, val); } /** * 插入一条数据 * @param table 表名 * @param row 行健 * @param fam 列族 * @param qual 列限定符 * @param val 值 * @throws IOException */ public void put(TableName table, String row, String fam, String qual, String val) throws IOException { Table tbl = connection.getTable(table); Put put = new Put(Bytes.toBytes(row)); put.addColumn(Bytes.toBytes(fam), Bytes.toBytes(qual), Bytes.toBytes(val)); tbl.put(put); tbl.close(); } /** * 插入一条数据,指定时间戳 * @param table 表名 * @param row 行健 * @param fam 列族 * @param qual 列限定副 * @param ts 时间戳 * @param val 值 * @throws IOException */ public void put(String table, String row, String fam, String qual, long ts, String val) throws IOException { put(TableName.valueOf(table), row, fam, qual, ts, val); } /** * 插入一条数据,指定时间戳 * @param table 表名 * @param row 行健 * @param fam 列族 * @param qual 列限定副 * @param ts 时间戳 * @param val 值 * @throws IOException */ public void put(TableName table, String row, String fam, String qual, long ts, String val) throws IOException { Table tbl = connection.getTable(table); Put put = new Put(Bytes.toBytes(row)); put.addColumn(Bytes.toBytes(fam), Bytes.toBytes(qual), ts, Bytes.toBytes(val)); tbl.put(put); tbl.close(); } /** * 插入多条条数据 * @param table 表名 * @param rows 行健 * @param fams 列族 * @param quals 列限定副 * @param ts 时间戳 * @param vals 值 * @throws IOException */ public void put(String table, String[] rows, String[] fams, String[] quals, long[] ts, String[] vals) throws IOException { put(TableName.valueOf(table), rows, fams, quals, ts, vals); } /** * 插入多条条数据 * @param table 表名 * @param rows 行健 * @param fams 列族 * @param quals 列限定副 * @param ts 时间戳 * @param vals 值 * @throws IOException */ public void put(TableName table, String[] rows, String[] fams, String[] quals, long[] ts, String[] vals) throws IOException { Table tbl = connection.getTable(table); Arrays.stream(rows).forEach(row ->{ Put put = new Put(Bytes.toBytes(row)); Arrays.stream(quals).forEach(fam ->{ final int[] v = {0}; Arrays.stream(quals).forEach(qual ->{ String val = vals[v[0] < vals.length ? v[0] : vals.length - 1]; long t = ts[v[0] < ts.length ? v[0] : ts.length - 1]; System.out.println("Adding: " + row + " " + fam + " " + qual + " " + t + " " + val); put.addColumn(Bytes.toBytes(fam), Bytes.toBytes(qual), t, Bytes.toBytes(val)); v[0]++; }); }); try { tbl.put(put); } catch (IOException e) { e.printStackTrace(); } }); tbl.close(); } /** * 删除对应的数据 * @param table 表名 * @param rows 行健 * @param fams 列族 * @param quals 列限定符 * @throws IOException */ public void dump(String table, String[] rows, String[] fams, String[] quals) throws IOException { dump(TableName.valueOf(table), rows, fams, quals); } /** * 获取对应的数据 * @param table 表名 * @param rows 行健 * @param fams 列族 * @param quals 列限定符 * @throws IOException */ public void dump(TableName table, String[] rows, String[] fams, String[] quals) throws IOException { Table tbl = connection.getTable(table); List<Get> gets = new ArrayList<Get>(); Arrays.stream(rows).forEach(row -> { Get get = new Get(Bytes.toBytes(row)); get.setMaxVersions(); if (fams != null) { Arrays.stream(fams).forEach(fam ->{ Arrays.stream(quals).forEach(qual -> get.addColumn(Bytes.toBytes(fam), Bytes.toBytes(qual))); }); } gets.add(get); }); Result[] results = tbl.get(gets); Arrays.stream(results).forEach(result -> { Arrays.stream(result.rawCells()).forEach(cell ->{ System.out.println("Cell: " + cell + ", Value: " + Bytes.toString(cell.getValueArray(), cell.getValueOffset(), cell.getValueLength())); }); }); tbl.close(); } public void dump(String table) throws IOException { dump(TableName.valueOf(table)); } public void dump(TableName table) throws IOException { try ( Table t = connection.getTable(table); ResultScanner scanner = t.getScanner(new Scan()) ){ scanner.forEach(result -> dumpResult(result)); } } public void dumpResult(Result result) { for (Cell cell : result.rawCells()) { System.out.println("Cell: " + cell + ", Value: " + Bytes.toString(cell.getValueArray(), cell.getValueOffset(), cell.getValueLength())); } } public static String getHbaseValue() { return HBASE_VALUE; } public static void setHbaseValue(String hbaseValue) { HBASE_VALUE = hbaseValue; } public static String getZkValue() { return ZK_VALUE; } public static void setZkValue(String zkValue) { ZK_VALUE = zkValue; } public static String getZkPortValue() { return ZK_PORT_VALUE; } public static void setZkPortValue(String zkPortValue) { ZK_PORT_VALUE = zkPortValue; } } <file_sep>/hadoop/src/main/java/hadoop/rpc/LoginServiceInterface.java package hadoop.rpc; public interface LoginServiceInterface { public static final long versionID=1L; public String login(String username, String password); } <file_sep>/hbase/src/main/java/learm/forclass/testclass/TestClass.java package learm.forclass.testclass; import learm.forclass.utils.HBaseUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.Cell; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.client.*; import org.apache.hadoop.hbase.filter.*; import org.apache.hadoop.hbase.util.Bytes; import java.io.IOException; /** * Created by zhoujun on 17-10-12. */ public class TestClass { public static void main(String[] args) throws IOException { // HBaseUtils.dropTable("table1"); // HBaseUtils.createTable("table1", "f1,f2"); filter(); } public static void filter() throws IOException { Configuration conf = HBaseConfiguration.create(); Connection connection = ConnectionFactory.createConnection(conf); Table table = connection.getTable(TableName.valueOf("table1")); SingleColumnValueFilter filter = new SingleColumnValueFilter( Bytes.toBytes("f2"), Bytes.toBytes("c2"), CompareFilter.CompareOp.NOT_EQUAL, new SubstringComparator("3")); Scan scan = new Scan(); FilterList filterList = new FilterList(); filterList.addFilter(filter); PageFilter pageFilter = new PageFilter(5l); filterList.addFilter(pageFilter); scan.setFilter(filterList); ResultScanner scanner = table.getScanner(scan); scanner.forEach(result -> { for (Cell cell : result.rawCells()) { System.out.println("Cell: " + cell + ", Value: " + Bytes.toString(cell.getValueArray(), cell.getValueOffset(), cell.getValueLength())); } }); } } <file_sep>/hbase/src/main/java/learm/forclass/testclass/PutDemo.java package learm.forclass.testclass; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.client.*; import org.apache.hadoop.hbase.util.Bytes; import java.io.IOException; public class PutDemo { public static void main(String[] args){ Configuration conf = HBaseConfiguration.create(); Table table = null; try { Connection connection = ConnectionFactory.createConnection(conf); table = connection.getTable(TableName.valueOf("table1")); for(int i=0; i<10; i++){ Put put = new Put(Bytes.toBytes("r"+i)); put.addColumn(Bytes.toBytes("f1"), Bytes.toBytes("c2"), Bytes.toBytes(""+i)); table.put(put); } System.out.println("插入的数据为:"); Scan scan = new Scan().addFamily(Bytes.toBytes("f1")); table.getScanner(scan).forEach(System.out::println); } catch (IOException e) { e.printStackTrace(); }finally { try { assert table != null; table.close(); } catch (IOException e) { e.printStackTrace(); } } } } <file_sep>/hbase/src/main/java/com/base/put/PutWriteBufferExample1.java package com.base.put; import com.utils.HBaseHelper; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.client.*; import org.apache.hadoop.hbase.util.Bytes; import java.io.IOException; /** * 缓存控制的写入数据 * org.apache.hadoop.hbase.client.BufferedMutator主要用来对HBase的单个表进行操作。 * 它和Put类的作用差不多,但是主要用来实现批量的异步写操作。BufferedMutator替换了HTable的setAutoFlush(false)的作用。 * 可以从Connection的实例中获取BufferedMutator的实例。 * 在使用完成后需要调用close()方法关闭连接。对BufferedMutator进行配置需要通过BufferedMutatorParams完成。 * MapReduce Job的是BufferedMutator使用的典型场景。MapReduce作业需要批量写入,但是无法找到恰当的点执行flush。 * BufferedMutator接收MapReduce作业发送来的Put数据后, * 会根据某些因素(比如接收的Put数据的总量)启发式地执行Batch Put操作, * 且会异步的提交Batch Put请求,这样MapReduce作业的执行也不会被打断。 * BufferedMutator也可以用在一些特殊的情况上。MapReduce作业的每个线程将会拥有一个独立的BufferedMutator对象。 * 一个独立的BufferedMutator也可以用在大容量的在线系统上来执行批量Put操作, * 但是这时需要注意一些极端情况比如JVM异常或机器故障,此时有可能造成数据丢失。 */ public class PutWriteBufferExample1 { public static void main(String[] args) throws IOException { Configuration conf = HBaseConfiguration.create(); conf.set(HBaseHelper.ZK_CLIENT_PORT_KEY,HBaseHelper.getZkPortValue()); conf.set(HBaseHelper.ZK_QUORUM_KEY, HBaseHelper.getZkValue()); conf.set(HBaseHelper.HBASE_KEY, HBaseHelper.getHbaseValue()); HBaseHelper helper = HBaseHelper.getHelper(conf); helper.dropTable("testtable"); helper.createTable("testtable", "colfam1"); TableName name = TableName.valueOf("testtable"); Connection connection = ConnectionFactory.createConnection(conf); Table table = connection.getTable(name); BufferedMutator mutator = connection.getBufferedMutator(name); Put put1 = new Put(Bytes.toBytes("row1")); put1.addColumn(Bytes.toBytes("colfam1"), Bytes.toBytes("qual1"), Bytes.toBytes("val1")); mutator.mutate(put1); Put put2 = new Put(Bytes.toBytes("row2")); put2.addColumn(Bytes.toBytes("colfam1"), Bytes.toBytes("qual1"), Bytes.toBytes("val2")); mutator.mutate(put2); Put put3 = new Put(Bytes.toBytes("row3")); put3.addColumn(Bytes.toBytes("colfam1"), Bytes.toBytes("qual1"), Bytes.toBytes("val3")); mutator.mutate(put3); Get get = new Get(Bytes.toBytes("row1")); Result res1 = table.get(get); System.out.println("Result: " + res1); mutator.flush(); Result res2 = table.get(get); System.out.println("Result: " + res2); mutator.close(); table.close(); connection.close(); helper.close(); } } <file_sep>/hbase/src/main/java/learm/forclass/testclass/Experment04.java package learm.forclass.testclass; import learm.forclass.utils.HBaseUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.Cell; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.client.*; import org.apache.hadoop.hbase.filter.*; import org.apache.hadoop.hbase.util.Bytes; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * Created by zhoujun on 17-10-12. * 实验四 */ public class Experment04 { /** * 获取配置信息 */ private static Configuration conf = HBaseConfiguration.create(); /** * 统计错误信息的条数 */ private static double errorCount = 0; /** * 统计 fatal 信息的条数 */ private static double fatalCount = 0; /** * 统计总信息的条数 */ private static double total = 0; public static void main(String[] args) throws IOException { usebatch(); } /** * 根据制定的条件查询数据,返回获取到的条数 * @param level 要过滤的值 * @return * @throws IOException */ private static double filterData(String level) throws IOException { double[] resultCount = {0}; // 结果 /** * 创建连接实例,获取表实例 */ Connection connection = ConnectionFactory.createConnection(conf); Table table = connection.getTable(TableName.valueOf("classtable")); /** * 添加过滤器,指定过滤条件 */ Filter filter = new ValueFilter(CompareFilter.CompareOp.EQUAL, new SubstringComparator(level)); Scan scan = new Scan(); /** * 如果不为 * 添加 filter 到 scan 中,为 * 表示查询所有数据 */ if(!level.equals("*")) scan.setFilter(filter); ResultScanner scanner = table.getScanner(scan); /** 统计获取到的行 */ scanner.forEach(result -> { resultCount[0]++; }); /** 关闭连接*/ table.close(); connection.close(); return resultCount[0]; } /** * 计算 (error + fatal)/total 的值 * @return * @throws IOException */ private static double compute() throws IOException{ double result = 0; /** 获取对应信息的数量 */ errorCount = filterData("ERROR"); fatalCount = filterData("FATAL"); total = filterData("*"); System.out.println(" total: " + total +" error: " + errorCount + " fatal: " + fatalCount ); result = (errorCount + fatalCount)/total; System.out.println("error+fatal/total = " + result); return result; } /** * 更新数据库中行中的列限定符为:class 的 value 的值,去掉后面的 “ :” * @return * @throws IOException */ private static void updateData() throws IOException { /** * 创建连接实例,获取表实例 */ Connection connection = ConnectionFactory.createConnection(conf); Table table = connection.getTable(TableName.valueOf("classtable")); /** * 添加过滤器,指定过滤条件 */ Filter filter = new QualifierFilter(CompareFilter.CompareOp.EQUAL, new SubstringComparator("class")); Scan scan = new Scan(); scan.setFilter(filter); ResultScanner scanner = table.getScanner(scan); /** 保存每行需要更新数据的 Put 实例 */ ArrayList<Put> arrayList = new ArrayList<>(); /** 遍历添加实例 */ scanner.forEach(result -> { Arrays.stream(result.rawCells()).forEach(cell -> { Put put = new Put(result.getRow()); /** 去掉 ’:‘*/ String val = Bytes.toString(cell.getValueArray(), cell.getValueOffset(), cell.getValueLength()).split(":")[0]; put.addColumn(Bytes.toBytes("f"), Bytes.toBytes("class"), Bytes.toBytes(val)); arrayList.add(put); }); }); /** 更新数据 */ table.put(arrayList); /** 关闭连接*/ table.close(); connection.close(); } /** * 使用 hbase 的 batch 操作! * @throws IOException */ public static void usebatch() throws IOException { /** * 创建连接实例,获取表实例 */ Connection connection = ConnectionFactory.createConnection(conf); Table table = connection.getTable(TableName.valueOf("test")); /** 装载 batch 的 list */ List<Row> batch = new ArrayList<Row>(); /** 添加对应的曾 删 查 实例到 batch 列表中*/ Put put = new Put(Bytes.toBytes("r-1")); put.addColumn(Bytes.toBytes("f"), Bytes.toBytes("qua-xx"), Bytes.toBytes("val-xx")); batch.add(put); Get get1 = new Get(Bytes.toBytes("r-2")); get1.addColumn(Bytes.toBytes("f"), Bytes.toBytes("qua-2")); batch.add(get1); Delete delete = new Delete(Bytes.toBytes("r-0")); delete.addColumns(Bytes.toBytes("f"), Bytes.toBytes("qua-0")); batch.add(delete); Get get2 = new Get(Bytes.toBytes("r-9")); get2.addFamily(Bytes.toBytes("f")); batch.add(get2); /** 获取返回后的结果 */ Object[] results = new Object[batch.size()]; try { /** 执行对应的 batch 操作*/ table.batch(batch, results); } catch (Exception e) { System.err.println("Error: " + e); } /** 打印结果 */ for (int i = 0; i < results.length; i++) { System.out.println("Result[" + i + "]: type = " + results[i].getClass().getSimpleName() + "; " + results[i].toString()); } /** 关闭连接*/ table.close(); connection.close(); } } <file_sep>/hadoop/src/main/java/com/learn/book/STjion.java package com.learn.book; import java.io.IOException; import java.util.Iterator; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; public class STjion { public static int time = 0; /** * Map将输入分割成child和parent,然后正序输出一次作为右表,反序输出一次作为左表,需要注意 * 的是在输出的value中必须加上左右表区别标志 * */ public static class Map extends Mapper<Object, Text, Text, Text> { public void map(Object key, Text value, Context context) throws IOException, InterruptedException{ String childname = new String(); String parentname = new String(); String relationType = new String(); String line = new String(); int i = 0; while(line.charAt(i) != ' '){ i++; } String[] values = {line.substring(0, i),line.substring(i+1)}; if(values[0].compareTo("child") != 0){ childname = values[0]; parentname = values[1]; relationType = "1"; //左右表的区别标志 context.write(new Text(values[1]), new Text(relationType + "+" + childname + "+" + parentname)); //左表 relationType = "2"; context.write(new Text(values[0]), new Text(relationType + "+" + childname + "+" + parentname)); //右表 } } } public static class Reduce extends Reducer< Text, Text, Text, Text> { public void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException{ if(time == 0){ context.write(new Text("grandchild"), new Text("grandparent")); time++; } int grandchildnum = 0; String grandchild [] = new String[10]; int grandparentnum = 0; String grandparent[] = new String[10]; Iterator ite = values.iterator(); while(ite.hasNext()){ String record = ite.next().toString(); int len = record.length(); int i = 2; if(len == 0) continue; char relationType = record.charAt(0); String childname = new String(); String parentname = new String(); //获取value-list中的value的child while(record.charAt(i) != '+'){ childname = childname + record.charAt(i); i++; } //获取value-list中的value的parent while(record.charAt(i) != '+'){ parentname = parentname + record.charAt(i); i++; } } } } public static void main(String[] args) { } } <file_sep>/spark/src/main/java/com/classstudy/SparkPartionTest.java package com.classstudy; import org.apache.commons.lang.StringUtils; import org.apache.spark.SparkConf; import org.apache.spark.api.java.JavaRDD; import org.apache.spark.api.java.JavaSparkContext; import org.apache.spark.api.java.function.FlatMapFunction; import org.eclipse.jetty.client.ContentExchange; import org.eclipse.jetty.client.HttpClient; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; public class SparkPartionTest { public static void main(String[] args){ SparkConf conf = new SparkConf().setMaster("local").setAppName("SPARKDEMO"); JavaSparkContext sc = new JavaSparkContext(conf); JavaRDD<String> rdd = sc.parallelize( Arrays.asList("KK6JKQ", "Ve3UoW", "kk6jlk", "W6BB")); JavaRDD<String> result = rdd.mapPartitions( new FlatMapFunction<Iterator<String>, String>() { public Iterator<String> call(Iterator<String> input) { ArrayList<String> content = new ArrayList<String>(); System.out.println("数据: " + input); while (input.hasNext()){ content.add(input.next()); } return content.iterator(); }}); System.out.println(StringUtils.join(result.collect(), ",")); } } <file_sep>/spark/src/main/java/com/classstudy/PartitionDemo.java package com.classstudy; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import org.apache.spark.HashPartitioner; import org.apache.spark.Partitioner; import org.apache.spark.SparkConf; import org.apache.spark.api.java.AbstractJavaRDDLike; import org.apache.spark.api.java.JavaPairRDD; import org.apache.spark.api.java.JavaRDD; import org.apache.spark.api.java.JavaSparkContext; import org.apache.spark.api.java.function.FlatMapFunction; import org.apache.spark.api.java.function.Function2; import org.apache.spark.api.java.function.PairFunction; import scala.Tuple2; public class PartitionDemo { public static void main(String[] xx){ SparkConf conf = new SparkConf(); conf.setMaster("local"); conf.setAppName("WordCounter"); JavaSparkContext ctx = new JavaSparkContext(conf); ctx.setCheckpointDir("E:\\git\\java\\spark\\src\\main\\resources"); List<String> lines = new ArrayList<String>(); lines.add("Hello How are you"); lines.add("No Fine thanks a lot ddddddddddd"); lines.add("Good are ok"); lines.add("Good is ok"); JavaRDD<String> rdd1 = ctx.parallelize(lines, 2); // System.out.println("rdd1 partitioner:" + rdd1.partitioner()); // System.out.println("rdd1: " + rdd1.getNumPartitions()); // System.out.println("rdd1 :" + rdd1.glom().collect()); JavaRDD<String> words = rdd1.flatMap(new FlatMapFunction<String, String>() { @Override public Iterator<String> call(String s) throws Exception { return Arrays.asList(s.split(" ")).iterator(); } }); System.out.println("before: " + words.toDebugString()); words.checkpoint(); System.out.println("after1: " + words.toDebugString()); // System.out.println("words partitioner:" + words.partitioner()); // System.out.println("words: " + words.getNumPartitions()); // System.out.println("words :" + words.glom().collect()); JavaPairRDD<String, Integer> mapRdd = words.mapToPair(new PairFunction<String, String, Integer>() { @Override public Tuple2<String, Integer> call(String s) throws Exception { return new Tuple2<String, Integer>(s, 1); } }); // System.out.println("mapRdd partitioner:" + mapRdd.partitioner()); // System.out.println("mapRdd :" + mapRdd.getNumPartitions()); // System.out.println("mapRdd :" + mapRdd.glom().collect()); JavaPairRDD<String, Integer> mapRdd2 = mapRdd.partitionBy(new Partitioner() { @Override public int numPartitions() { return 4; } @Override public int getPartition(Object arg0) { int hashCode = arg0.hashCode(); int index = hashCode % numPartitions(); //System.out.println("hashCode = " + hashCode + " index == " + index); if(index < 0 ){ index = 0; } return index; } }); System.out.println("after: " + mapRdd2.toDebugString()); // System.out.println("mapRdd2 partitioner:" + mapRdd2.partitioner()); // System.out.println("mapRdd2 :" + mapRdd2.getNumPartitions()); // System.out.println("mapRdd2 :" + mapRdd2.glom().collect()); /* mapRdd.reduceByKey( new Partitioner() { @Override public int numPartitions() {return 2;} @Override public int getPartition(Object o) { System.out.println("getPartition() " + o.toString()); return (o.toString()).hashCode() % numPartitions(); } }, new Function2<Integer, Integer, Integer>() { @Override public Integer call(Integer v1, Integer v2) throws Exception { return v1 + v2; } }); /* JavaPairRDD<String, Integer> mapRdd2 = mapRdd.partitionBy( new Partitioner() { @Override public int numPartitions() {return 4;} @Override public int getPartition(Object o) { int index = (o.toString()).hashCode() % numPartitions(); if(index < 0){ index = 0; } return index; } }); System.out.println(mapRdd2.getNumPartitions()); System.out.println(mapRdd2.glom().collect()); JavaPairRDD<String, Integer> mapRdd3 = mapRdd.partitionBy( new HashPartitioner(4) ); System.out.println(mapRdd3.getNumPartitions()); System.out.println(mapRdd3.glom().collect()); System.out.println(mapRdd3.partitioner()); */ } } <file_sep>/hadoop/src/main/java/com/map/splitFile/MyPartitioner.java package com.map.splitFile; import java.util.HashMap; import org.apache.hadoop.mapreduce.Partitioner; public class MyPartitioner<KEY, VALUE> extends Partitioner<KEY,VALUE> { private static HashMap<String,Integer> areaMap = new HashMap<>(); static{ areaMap.put("ERROR", 0); areaMap.put("INFO", 1); areaMap.put("WARN", 2); areaMap.put("OTHER", 3); } @Override public int getPartition(KEY key, VALUE value, int numPartitions) { int areaCoder = areaMap.get(key.toString()) == null ? 3:areaMap.get(key.toString()); return areaCoder; } } <file_sep>/java8/src/main/java/thread/syc/AbstractLoadBalancer.java package thread.syc; import java.util.Random; import java.util.logging.Logger; /** * 负载均衡算法抽象实现类,所有负载均衡算法实现类的父类 * * @author <NAME> */ public abstract class AbstractLoadBalancer implements LoadBalancer { private final static Logger LOGGER = Logger.getAnonymousLogger(); // 使用volatile变量替代锁(有条件替代) protected volatile Candidate candidate; protected final Random random; // 心跳线程 private Thread heartbeatThread; public AbstractLoadBalancer(Candidate candidate) { if (null == candidate || 0 == candidate.getEndpointCount()) { throw new IllegalArgumentException("Invalid candidate " + candidate); } this.candidate = candidate; random = new Random(); } public synchronized void init() throws Exception { if (null == heartbeatThread) { heartbeatThread = new Thread(new HeartbeatTask(), "LB_Heartbeat"); heartbeatThread.setDaemon(true); heartbeatThread.start(); } } @Override public void updateCandidate(final Candidate candidate) { if (null == candidate || 0 == candidate.getEndpointCount()) { throw new IllegalArgumentException("Invalid candidate " + candidate); } // 更新volatile变量candidate this.candidate = candidate; } /* * 留给子类实现的抽象方法 * * @see io.github.viscent.mtia.ch3.volatilecase.LoadBalancer#nextEndpoint() */ @Override public abstract Endpoint nextEndpoint(); protected void monitorEndpoints() { // 读取volatile变量 final Candidate currCandidate = candidate; boolean isTheEndpointOnline; // 检测下游部件状态是否正常 for (Endpoint endpoint : currCandidate) { isTheEndpointOnline = endpoint.isOnline(); if (doDetect(endpoint) != isTheEndpointOnline) { endpoint.setOnline(!isTheEndpointOnline); if (isTheEndpointOnline) { LOGGER.log(java.util.logging.Level.SEVERE, endpoint + " offline!"); } else { LOGGER.log(java.util.logging.Level.INFO, endpoint + " is online now!"); } } }// for循环结束 } // 检测指定的节点是否在线 private boolean doDetect(Endpoint endpoint) { boolean online = true; // 模拟待测服务器随机故障 int rand = random.nextInt(1000); if (rand <= 500) { online = false; } return online; } private class HeartbeatTask implements Runnable { @Override public void run() { try { while (true) { // 检测节点列表中所有节点是否在线 monitorEndpoints(); Thread.sleep(2000); } } catch (InterruptedException e) { // 什么也不做 } } }// HeartbeatTask类结束 }<file_sep>/hbase/src/main/java/learm/forclass/experiment/EXP01.java package learm.forclass.experiment; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.Cell; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.client.*; import org.apache.hadoop.hbase.filter.*; import org.apache.hadoop.hbase.util.Bytes; import java.io.IOException; import java.util.*; /** * Created by zhoujun on 17-11-9. */ public class EXP01 { private static Configuration conf = HBaseConfiguration.create(); private static Connection connection = null; /** * 根据学号student_id查询学生选课编号course_id和名称title * @param studentId 学生——id * @return * @throws IOException */ public static HashMap<String, String> fromStudentIdGetDate(String studentId) throws IOException{ HashMap<String, String> results = new HashMap<>(); connection = ConnectionFactory.createConnection(conf); Table student = connection.getTable(TableName.valueOf("student")); Table course = connection.getTable(TableName.valueOf("course")); Get get = new Get(Bytes.toBytes(studentId)); get.addFamily(Bytes.toBytes("course")); Result result = student.get(get); for(Cell cell: result.rawCells()){ Get getCourse = new Get(Bytes.toBytes(Bytes.toString(cell.getQualifier()).trim())); getCourse.addFamily(Bytes.toBytes("info")); System.out.println("courseId: " + Bytes.toString(cell.getQualifier())); Result result2 = course.get(getCourse); System.out.println("title: " + Bytes.toString(result2.getValue(Bytes.toBytes("info"), Bytes.toBytes("title")))); results.put(Bytes.toString(cell.getQualifier()), Bytes.toString(result2.getValue(Bytes.toBytes("info"), Bytes.toBytes("title")))); } return results; } /** * 根据课程号course_id查询选课学生学号student_id和姓名name * @param courseId 课程号id * @return * @throws IOException */ public static HashMap<String, String> fromCourseIdGetDate(String courseId) throws IOException{ HashMap<String, String> results = new HashMap<>(); connection = ConnectionFactory.createConnection(conf); Table student = connection.getTable(TableName.valueOf("student")); Table course = connection.getTable(TableName.valueOf("course")); Get get = new Get(Bytes.toBytes(courseId)); get.addFamily(Bytes.toBytes("student")); Result result = course.get(get); for(Cell cell: result.rawCells()){ Get getStudent = new Get(result.getValue(Bytes.toBytes("student"), cell.getQualifier())); getStudent.addFamily(Bytes.toBytes("info")); System.out.println("StudentId: " + Bytes.toString(result.getValue(Bytes.toBytes("student"), cell.getQualifier()))); Result result2 = student.get(getStudent); System.out.println("name: " + Bytes.toString(result2.getValue(Bytes.toBytes("info"), Bytes.toBytes("name")))); results.put(Bytes.toString(result.getValue(Bytes.toBytes("student"), cell.getQualifier())), Bytes.toString(result2.getValue(Bytes.toBytes("info"), Bytes.toBytes("name")))); } return results; } /** * 根据教员号teacher_id查询该教员所上课程编号course_id和名称title * @param teacherId teacher_Id * @return * @throws IOException */ public static HashMap<String, String> fromTeacherIdGetDate(String teacherId) throws IOException { HashMap<String, String> results = new HashMap<>(); connection = ConnectionFactory.createConnection(conf); Table courseTable = connection.getTable(TableName.valueOf("course")); ValueFilter filter = new ValueFilter(CompareFilter.CompareOp.EQUAL, new BinaryComparator(Bytes.toBytes(teacherId))); Scan scan = new Scan(); scan.setFilter(filter); ResultScanner scanner = courseTable.getScanner(scan); for(Result result: scanner){ for (Cell cell : result.rawCells()) { Get get = new Get(cell.getRow()); get.addFamily(Bytes.toBytes("info")); Result result1 = courseTable.get(get); System.out.println("courseId: " + Bytes.toString(cell.getRow()) + ", title: " + Bytes.toString(result1.getValue( Bytes.toBytes("info"),Bytes.toBytes("title")))); results.put(Bytes.toString(cell.getRow()), Bytes.toString(result1.getValue( Bytes.toBytes("info"),Bytes.toBytes("title")))); } } return results; } /** * 上课最多的学生 * @return * @throws IOException */ public static Student getMaxInCourseStudent() throws IOException{ Student student = new Student(); HashMap<String, Integer> info = new HashMap<>(); connection = ConnectionFactory.createConnection(conf); Table table = connection.getTable(TableName.valueOf("student")); Scan scan = new Scan(); ResultScanner scanner = table.getScanner(scan); int max = 0; String studentId = ""; for(Result result: scanner){ int tempCount = 0; Get get = new Get(result.getRow()); get.addFamily(Bytes.toBytes("course")); for(Cell cell: table.get(get).rawCells()){ tempCount++; } if(max < tempCount){ max = tempCount; studentId = Bytes.toString(result.getRow()); } } System.out.println("id: " + studentId + " max: " + max); table.close(); connection.close(); return student; } /** * 上课最少的学生 * @return * @throws IOException */ public static Student getMinInCourseStudent() throws IOException{ Student student = new Student(); HashMap<String, Integer> info = new HashMap<>(); connection = ConnectionFactory.createConnection(conf); Table table = connection.getTable(TableName.valueOf("student")); Scan scan = new Scan(); ResultScanner scanner = table.getScanner(scan); int min = 1; String studentId = ""; for(Result result: scanner){ int tempCount = 0; Get get = new Get(result.getRow()); get.addFamily(Bytes.toBytes("course")); for(Cell cell: table.get(get).rawCells()){ tempCount++; } if(min >= tempCount){ min = tempCount; studentId = Bytes.toString(result.getRow()); } } System.out.println("id: " + studentId + " min: " + min); table.close(); connection.close(); return student; } } <file_sep>/hadoop/src/main/java/com/map/splitFile/SplitFilesToResult.java package com.map.splitFile; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.regex.Pattern; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.mapreduce.lib.output.LazyOutputFormat; import org.apache.hadoop.mapreduce.lib.output.MultipleOutputs; import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat; public class SplitFilesToResult extends Configured { @SuppressWarnings("deprecation") public static void main(String[] args) { String in = "/SplitFilesToResult/input"; String out = "/SplitFilesToResult/output"; Job job; try { //如果输出文件存在,则删除hdfs目录 SplitFilesToResult wc2 = new SplitFilesToResult(); wc2.removeDir(out); job = new Job(new Configuration(), "split Job"); job.setOutputKeyClass(Text.class); job.setOutputValueClass(Text.class); job.setMapperClass(mapperString.class); job.setReducerClass(reduceStatistics.class); //自定义附加的输出文件 MultipleOutputs.addNamedOutput(job,"INFO",TextOutputFormat.class,Text.class,Text.class); MultipleOutputs.addNamedOutput(job,"ERROR",TextOutputFormat.class,Text.class,Text.class); MultipleOutputs.addNamedOutput(job,"WARN",TextOutputFormat.class,Text.class,Text.class); MultipleOutputs.addNamedOutput(job,"OTHER",TextOutputFormat.class,Text.class,Text.class); FileInputFormat.addInputPath(job, new Path(in)); FileOutputFormat.setOutputPath(job, new Path(out)); // 去掉job设置outputFormatClass,改为通过LazyOutputFormat设置 LazyOutputFormat.setOutputFormatClass(job, TextOutputFormat.class); job.waitForCompletion(true); } catch (IOException e) { e.printStackTrace(); } catch (URISyntaxException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } @SuppressWarnings("deprecation") public void removeDir(String filePath) throws IOException, URISyntaxException{ String url = "hdfs://localhost:9000"; FileSystem fs = FileSystem.get(new URI(url), new Configuration()); fs.delete(new Path(filePath)); } } /** * 重写maptask使用的map方法 * @author nange * */ class mapperString extends Mapper<LongWritable, Text, Text, Text> { //设置正则表达式的编译表达形式 public static Pattern PATTERN = Pattern.compile(" "); @Override protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { String[] words = PATTERN.split(value.toString()); System.out.println("********" + value.toString()); if(words.length >= 2){ if(words.length == 2){ context.write(new Text("ERROR"), new Text(value.toString())); }else if(words[0].equals("at")){ context.write(new Text("ERROR"), new Text(value.toString())); }else{ context.write(new Text(words[2]), new Text(value.toString())); } }else context.write(new Text("OTHER"), new Text(value.toString())); } } /** * 对单词做统计 * @author nange * */ class reduceStatistics extends Reducer<Text, Text, Text, Text> { //将结果输出到多个文件或多个文件夹 private MultipleOutputs<Text,Text> mos; //创建MultipleOutputs对象 protected void setup(Context context) throws IOException,InterruptedException { mos = new MultipleOutputs<Text, Text>(context); } @Override protected void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException { for(Text t: values){ //使用MultipleOutputs对象输出数据 if(key.toString().equals("INFO")){ mos.write("INFO", "", t); }else if(key.toString().equals("ERROR")){ mos.write("ERROR", "", t); }else if(key.toString().equals("WARN")){ mos.write("WARN", "", t, "WARN"); }else{ mos.write("OTHER", "", t); } } } //关闭MultipleOutputs对象 protected void cleanup(Context context) throws IOException,InterruptedException { mos.close(); } } <file_sep>/java8/src/main/java/thread/syc/WeightedRoundRobinLoadBalancer.java package thread.syc; /** * 加权轮询负载均衡算法实现类 * * @author <NAME> */ public class WeightedRoundRobinLoadBalancer extends AbstractLoadBalancer { // 私有构造器 private WeightedRoundRobinLoadBalancer(Candidate candidate) { super(candidate); } // 通过该静态方法创建该类的实例 public static LoadBalancer newInstance(Candidate candidate) throws Exception { WeightedRoundRobinLoadBalancer lb = new WeightedRoundRobinLoadBalancer(candidate); lb.init(); return lb; } // 在该方法中实现相应的负载均衡算法 @Override public Endpoint nextEndpoint() { Endpoint selectedEndpoint = null; int subWeight = 0; int dynamicTotoalWeight; final double rawRnd = super.random.nextDouble(); int rand; // 读取volatile变量candidate final Candidate candiate = super.candidate; dynamicTotoalWeight = candiate.totalWeight; for (Endpoint endpoint : candiate) { // 选取节点以及计算总权重时跳过非在线节点 if (!endpoint.isOnline()) { dynamicTotoalWeight -= endpoint.weight; continue; } rand = (int) (rawRnd * dynamicTotoalWeight); subWeight += endpoint.weight; if (rand <= subWeight) { selectedEndpoint = endpoint; break; } } return selectedEndpoint; } } <file_sep>/java8/src/main/java/com/interf/DogImp.java package com.interf; import java.util.function.Consumer; /** * Created by zhoujun on 2017/9/6. */ public class DogImp implements Dog<String>{ private String name; private int age; @Override public void speark(String msg) { log(msg); } @Override public void doSth(Consumer<String> consumer) { consumer.accept(name); } public String getName() { return name; } public DogImp setName(String name) { this.name = name; return this; } public int getAge() { return age; } public DogImp setAge(int age) { this.age = age; return this; } @Override public String toString() { return "DogImp{" + "name='" + name + '\'' + ", age=" + age + '}'; } } <file_sep>/spark/src/main/java/com/classstudy/SparkDemo.java package com.classstudy; import org.apache.spark.HashPartitioner; import org.apache.spark.Partitioner; import org.apache.spark.SparkConf; import org.apache.spark.api.java.JavaPairRDD; import org.apache.spark.api.java.JavaRDD; import org.apache.spark.api.java.JavaSparkContext; import org.apache.spark.api.java.function.*; import scala.Tuple2; import scala.math.Ordering; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.Scanner; /** * Created by zhoujun on 2017/9/18. */ public class SparkDemo { public static void main(String[] args){ SparkConf conf = new SparkConf().setMaster("local[2]").setAppName("demo"); JavaSparkContext sc = new JavaSparkContext(conf); // // sc.parallelize(new ArrayList<String>(){{ // this.add("hello java a world"); // this.add("hello scala a world"); // this.add("haha heihei"); // }}).flatMap(new FlatMapFunction<String, String>() { // public Iterator<String> call(String s) throws Exception { // return Arrays.asList(s.split(" ")).iterator(); // } // }).mapToPair(new PairFunction<String, String, Integer>() { // public Tuple2<String, Integer> call(String s) throws Exception { // return new Tuple2<String, Integer>(s,1); // } // }).reduceByKey(new Function2<Integer, Integer, Integer>() { // public Integer call(Integer integer, Integer integer2) throws Exception { // return integer+integer2; // } // }).foreach(new VoidFunction<Tuple2<String, Integer>>(){ // public void call(Tuple2<String, Integer> s) throws Exception { // System.out.println(s); // } // }); // new JavaSparkContext(new SparkConf().setMaster("local").setAppName("demo")) // .parallelize(new ArrayList<String>(){{ // this.add("hello java a world"); // this.add("hello scala a world"); // this.add("haha heihei"); // }}).flatMap(s -> Arrays.asList(s.split(" ")).iterator()) // .mapToPair(t -> new Tuple2<String,Integer>(t,1)) // .reduceByKey((v1, v2) -> v1+v2) //// .foreach(System.out :: println); // .foreach(s -> System.out.println(s)); // System.out.println("用第一个单词作为key........"); // sc.parallelize(new ArrayList<String>(){{ // this.add("hello java a world"); // this.add("No scala a world"); // this.add("haha heihei"); // }}) // .mapToPair(t -> new Tuple2<String,String>(t.split(" ")[0], t)) // .foreach(s -> System.out.println(s)); // System.out.println("长度大于3的行......."); // sc.parallelize(new ArrayList<String>(){{ // this.add("hello java a world"); // this.add("No scala a world"); // this.add("Good heihei"); // }}) //// .filter(s -> s.split(" ").length > 3) // .foreach(s -> System.out.println(s)); // System.out.println("方式二。。。。。"); // JavaRDD<String> rdd = sc.parallelize(new ArrayList<String>(){{ // this.add("hello java a world"); // this.add("No scala a world"); // this.add("haha heihei"); // }}); // JavaPairRDD<String, String> pairRDD = rdd.mapToPair(new PairFunction<String, String, String>() { // @Override // public Tuple2<String, String> call(String s) throws Exception { // return new Tuple2<String, String>(s.split("")[0], s); // } // }); // pairRDD.foreach(new VoidFunction<Tuple2<String, String>>() { // @Override // public void call(Tuple2<String, String> stringStringTuple2) throws Exception { // System.out.println(stringStringTuple2); // } // }); // JavaRDD<String> rdd = sc.parallelize(new ArrayList<String>(){{ // this.add("hello java a world"); // this.add("No scala a world"); // this.add("haha heihei"); // }}); // rdd.filter(new Function<String, Boolean>() { // @Override // public Boolean call(String v1) throws Exception { // return v1.split(" ").length > 3; // } // }).foreach(new VoidFunction<String>() { // @Override // public void call(String s) throws Exception { // System.out.println(s); // } // }); // JavaRDD<Integer> rddlist = sc.parallelize(Arrays.asList(1,2,32,232,4,2,2323,52,3,66)); JavaPairRDD<Integer, Integer> pairRDD = rddlist.mapToPair(new PairFunction<Integer, Integer, Integer>() { @Override public Tuple2<Integer, Integer> call(Integer integer) throws Exception { return new Tuple2<Integer, Integer>(integer, 1); } }); JavaPairRDD<Integer, Integer> result = pairRDD.coalesce(4,true); System.out.println("分区数1: " + pairRDD.getNumPartitions()); System.out.println("debug: " + result.toDebugString()); System.out.println("分区数2: " + result.getNumPartitions()); result.foreach(new VoidFunction<Tuple2<Integer, Integer>>() { @Override public void call(Tuple2<Integer, Integer> integerIntegerTuple2) throws Exception { System.out.println(integerIntegerTuple2); } }); Scanner scanner = new Scanner(System.in); scanner.next(); scanner.close(); } } <file_sep>/java8/src/main/java/com/interf/DogImp2.java package com.interf; import java.util.function.Consumer; /** * Created by zhoujun on 2017/9/6. */ public abstract class DogImp2<T> implements Dog<T>{ public DogImp2<? super T> dogImp2(Consumer<T> consumer){ return this; } } <file_sep>/spark/src/main/java/com/test2data/SparkJSONDemo.java package com.test2data; import java.io.Serializable; import java.util.ArrayList; import java.util.Iterator; import org.apache.spark.SparkConf; import org.apache.spark.api.java.JavaRDD; import org.apache.spark.api.java.JavaSparkContext; import org.apache.spark.api.java.function.FlatMapFunction; import com.fasterxml.jackson.databind.ObjectMapper; public class SparkJSONDemo { public static void main(String[] args){ SparkConf conf = new SparkConf().setMaster("local[2]").setAppName("SparkIO"); JavaSparkContext sc = new JavaSparkContext(conf); sc.setLogLevel("WARN"); // readJsonTest(sc); writeJsonTest(sc); sc.stop(); sc.close(); } //读JSON static void readJsonTest(JavaSparkContext sc){ JavaRDD<String> input = sc.textFile("E:\\git\\java\\spark\\src\\main\\resources\\song.json"); JavaRDD<Mp3Info> result = input.mapPartitions(new ParseJson()); result.foreach(x->System.out.println(x)); } //写JSON static void writeJsonTest(JavaSparkContext sc){ JavaRDD<String> input = sc.textFile("E:\\git\\java\\spark\\src\\main\\resources\\song.json"); JavaRDD<Mp3Info> result = input.mapPartitions(new ParseJson()). filter( x->x.getAlbum().equals("怀旧专辑") ); JavaRDD<String> formatted = result.mapPartitions(new WriteJson()); result.foreach(x->System.out.println(x)); formatted.saveAsTextFile("E:\\git\\java\\spark\\src\\main\\resources\\oldsong.json"); } } class ParseJson implements FlatMapFunction<Iterator<String>, Mp3Info>, Serializable { public Iterator<Mp3Info> call(Iterator<String> lines) throws Exception { ArrayList<Mp3Info> people = new ArrayList<Mp3Info>(); ObjectMapper mapper = new ObjectMapper(); while (lines.hasNext()) { String line = lines.next(); try { people.add(mapper.readValue(line, Mp3Info.class)); } catch (Exception e) { e.printStackTrace(); } } return people.iterator(); } } class WriteJson implements FlatMapFunction<Iterator<Mp3Info>, String> { public Iterator<String> call(Iterator<Mp3Info> song) throws Exception { ArrayList<String> text = new ArrayList<String>(); ObjectMapper mapper = new ObjectMapper(); while (song.hasNext()) { Mp3Info person = song.next(); text.add(mapper.writeValueAsString(person)); } return text.iterator(); } } class Mp3Info implements Serializable{ /* {"name":"上海滩","singer":"叶丽仪","album":"香港电视剧主题歌","path":"mp3/shanghaitan.mp3"} {"name":"一生何求","singer":"陈百强","album":"香港电视剧主题歌","path":"mp3/shanghaitan.mp3"} {"name":"红日","singer":"李克勤","album":"怀旧专辑","path":"mp3/shanghaitan.mp3"} {"name":"爱如潮水","singer":"张信哲","album":"怀旧专辑","path":"mp3/airucaoshun.mp3"} {"name":"红茶馆","singer":"陈惠嫻","album":"怀旧专辑","path":"mp3/redteabar.mp3"} */ private String name; private String album; private String path; private String singer; public String getSinger() { return singer; } public void setSinger(String singer) { this.singer = singer; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAlbum() { return album; } public void setAlbum(String album) { this.album = album; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } @Override public String toString() { return "Mp3Info [name=" + name + ", album=" + album + ", path=" + path + ", singer=" + singer + "]"; } } /* {"name":"上海滩","singer":"叶丽仪","album":"香港电视剧主题歌","path":"mp3/shanghaitan.mp3"} {"name":"一生何求","singer":"陈百强","album":"香港电视剧主题歌","path":"mp3/shanghaitan.mp3"} {"name":"红日","singer":"李克勤","album":"怀旧专辑","path":"mp3/shanghaitan.mp3"} {"name":"爱如潮水","singer":"张信哲","album":"怀旧专辑","path":"mp3/airucaoshun.mp3"} {"name":"红茶馆","singer":"陈惠嫻","album":"怀旧专辑","path":"mp3/redteabar.mp3"} */<file_sep>/hbase/src/main/java/learm/forclass/connection/HbaseConnection.java package learm.forclass.connection; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.*; import org.apache.hadoop.hbase.client.*; import org.apache.hadoop.hbase.util.Bytes; import org.apache.htrace.commons.logging.Log; import org.apache.htrace.commons.logging.LogFactory; import java.io.IOException; import java.util.*; /** * Created by zhoujun on 2017/9/9. */ public class HbaseConnection { private static Log log = LogFactory.getFactory().getInstance("log"); /** * 连接池对象 */ protected static Connection connection; private static final String ZK_QUORUM = "hbase.zookeeper.quorum"; private static final String ZK_CLIENT_PORT = "hbase.zookeeper.property.clientPort"; /** * HBase位置 */ private static final String HBASE_POS = "192.168.23.128"; /** * ZooKeeper位置 */ private static final String ZK_POS = "192.168.23.128"; /** * zookeeper服务端口 */ private final static String ZK_PORT_VALUE = "2181"; private static final Configuration configuration = HBaseConfiguration.create(); /** * 静态构造,在调用静态方法时前进行运行 * 初始化连接对象. * */ static{ configuration.set("hbase.rootdir", "hdfs://" + HBASE_POS + ":9000/hbase"); configuration.set(ZK_QUORUM, ZK_POS); configuration.set(ZK_CLIENT_PORT, ZK_PORT_VALUE); try { connection = ConnectionFactory.createConnection(configuration); } catch (IOException e) { e.printStackTrace(); }// 创建连接池 } // /** // * @param tableName 创建一个表 tableName 指定的表名 // * @param seriesStr 以字符串的形式指定表的列族,每个列族以逗号的形式隔开,(例如:"f1,f2"两个列族,分别为f1和f2) // **/ // public static boolean createTable(String tableName, String seriesStr) { // boolean isSuccess = false;// 判断是否创建成功!初始值为false // Admin admin = null; // TableName table = TableName.valueOf(tableName); // try { // admin = connection.getAdmin(); // if (!admin.tableExists(table)) { // System.out.println("INFO:Hbase:: " + tableName + "原数据库中表不存在!开始创建..."); // HTableDescriptor descriptor = new HTableDescriptor(table); // Arrays.asList(seriesStr.split(",")) // .forEach(s -> descriptor.addFamily(new HColumnDescriptor(s.getBytes()))); // admin.createTable(descriptor); // System.out.println("INFO:Hbase:: "+tableName + "新的" + tableName + "表创建成功!"); // isSuccess = true; // } else { // System.out.println("INFO:Hbase:: 该表已经存在,不需要在创建!"); // } // } catch (Exception e) { // e.printStackTrace(); // } finally { // IOUtils.closeQuietly(admin); // } // return isSuccess; // } // // /** // * 插入数据 // * @param tableName 表名 // * @param rowkey 行健 // * @param family 列族 // * @param qualifier 列描述符 // * @param value 值 // * @throws IOException 异常信息 // */ // public static void putDataH(String tableName, String rowkey, String family, // String qualifier, Object value) throws IOException { // Admin admin = null; // TableName tN = TableName.valueOf(tableName); // admin = connection.getAdmin(); // if (admin.tableExists(tN)) { // try (Table table = connection.getTable(TableName.valueOf(tableName // .getBytes()))) { // Put put = new Put(rowkey.getBytes()); // put.addColumn(family.getBytes(), qualifier.getBytes(), // value.toString().getBytes()); // table.put(put); // // } catch (Exception e) { // e.printStackTrace(); // } // } else { // System.out.println("插入数据的表不存在,请指定正确的tableName ! "); // } // } /** * 根据table查询表中的所有数据 无返回值,直接在控制台打印结果 * */ @SuppressWarnings("deprecation") public static void getValueByTable(String tableName) throws Exception { Table table = null; try { table = connection.getTable(TableName.valueOf(tableName)); ResultScanner rs = table.getScanner(new Scan()); rs.forEach(r -> { System.out.println("获得到rowkey:" + new String(r.getRow())); Arrays.stream(r.raw()).forEach(keyValue -> { System.out.println("列:" + new String(keyValue.getFamily()) + ":" + new String(keyValue.getQualifier()) + "====值:" + new String(keyValue.getValue())); }); }); } finally { IOUtils.closeQuietly(table); } } public static void main(String[] args) throws Exception { // System.out.println(createTable("testtable","data")); createTableBySplitKeys("testhbase", Arrays.asList("f")); HTable table = new HTable(configuration, "testhbase"); table.put(batchPut()); // System.out.println("***************插入一条数据:"); // putDataH("learmTest","test1","f1","age","4545"); // System.out.println("****************打印表中的数据:"); // getValueByTable("learmTest"); // HBaseUtils.getTestDate("learmTest"); } private static List<Put> batchPut(){ List<Put> list = new ArrayList<Put>(); for(int i=1; i <= 10000; i++){ byte[] rowkey = Bytes.toBytes(getRandomNumber() +"-"+System.currentTimeMillis()+"-"+i); Put put = new Put(rowkey); put.add(Bytes.toBytes("f"), Bytes.toBytes("name"), Bytes.toBytes("zs"+i)); list.add(put); } return list; } private static String getRandomNumber(){ String ranStr = Math.random()+""; int pointIndex = ranStr.indexOf("."); return ranStr.substring(pointIndex+1, pointIndex+3); } private static byte[][] getSplitKeys() { String[] keys = new String[] { "10|", "20|", "30|", "40|", "50|", "60|", "70|", "80|", "90|" }; byte[][] splitKeys = new byte[keys.length][]; TreeSet<byte[]> rows = new TreeSet<byte[]>(Bytes.BYTES_COMPARATOR);//升序排序 for (int i = 0; i < keys.length; i++) { rows.add(Bytes.toBytes(keys[i])); } Iterator<byte[]> rowKeyIter = rows.iterator(); int i=0; while (rowKeyIter.hasNext()) { byte[] tempRow = rowKeyIter.next(); rowKeyIter.remove(); splitKeys[i] = tempRow; i++; } return splitKeys; } /** * 创建预分区hbase表 * @param tableName 表名 * @param columnFamily 列簇 * @return */ @SuppressWarnings("resource") public static boolean createTableBySplitKeys(String tableName, List<String> columnFamily) { try { if (StringUtils.isBlank(tableName) || columnFamily == null || columnFamily.size() < 0) { log.error("===Parameters tableName|columnFamily should not be null,Please check!==="); } HBaseAdmin admin = new HBaseAdmin(configuration); if (admin.tableExists(tableName)) { return true; } else { HTableDescriptor tableDescriptor = new HTableDescriptor( TableName.valueOf(tableName)); for (String cf : columnFamily) { tableDescriptor.addFamily(new HColumnDescriptor(cf)); } byte[][] splitKeys = getSplitKeys(); admin.createTable(tableDescriptor, splitKeys);//指定splitkeys log.info("===Create Table " + tableName + " Success!columnFamily:" + columnFamily.toString() + "==="); } } catch (MasterNotRunningException e) { log.error(e); return false; } catch (ZooKeeperConnectionException e) { log.error(e); return false; } catch (IOException e) { log.error(e); return false; } return true; } } <file_sep>/hbase/src/main/java/learm/forclass/testclass/ScanDemo.java package learm.forclass.testclass; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.client.*; import org.apache.hadoop.hbase.util.Bytes; import java.io.IOException; public class ScanDemo { public static void main(String[] args){ Configuration conf = HBaseConfiguration.create(); Table table = null; try { Connection connection = ConnectionFactory.createConnection(conf); table = connection.getTable(TableName.valueOf("t1")); Scan scan = new Scan(); scan.setStartRow(Bytes.toBytes("3")); scan.setStopRow(Bytes.toBytes("6")); ResultScanner resultScanner = table.getScanner(scan); resultScanner.forEach(result -> System.out.println( "Scan: " + Bytes.toString(result.getRow()) + " is in class " + Bytes.toString(result.getValue(Bytes.toBytes("f"), Bytes.toBytes("name"))) )); } catch (IOException e) { e.printStackTrace(); }finally { try { assert table != null; table.close(); } catch (IOException e) { e.printStackTrace(); } } } } <file_sep>/hadoop/src/main/java/com/map/splitFile/SplitFilesToResult2.java package com.map.splitFile; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.util.regex.Pattern; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.mapreduce.lib.output.LazyOutputFormat; import org.apache.hadoop.mapreduce.lib.output.MultipleOutputs; import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat; public class SplitFilesToResult2 extends Configured { @SuppressWarnings("deprecation") public static void main(String[] args) { String in = "/SplitFilesToResult/input"; String out = "/SplitFilesToResult/output2"; Job job; try { //删除hdfs目录 SplitFilesToResult wc2 = new SplitFilesToResult(); wc2.removeDir(out); job = new Job(new Configuration(), "split Job"); job.setOutputKeyClass(Text.class); job.setOutputValueClass(Text.class); job.setMapperClass(mapperString1.class); job.setReducerClass(reduceStatistics1.class); job.setPartitionerClass(MyPartitioner.class); FileInputFormat.addInputPath(job, new Path(in)); FileOutputFormat.setOutputPath(job, new Path(out)); job.waitForCompletion(true); } catch (IOException e) { e.printStackTrace(); } catch (URISyntaxException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } @SuppressWarnings("deprecation") public void removeDir(String filePath) throws IOException, URISyntaxException{ String url = "hdfs://localhost:9000"; FileSystem fs = FileSystem.get(new URI(url), new Configuration()); fs.delete(new Path(filePath)); } } /** * 重写maptask使用的map方法 * @author nange * */ class mapperString1 extends Mapper<LongWritable, Text, Text, Text> { //设置正则表达式的编译表达形式 public static Pattern PATTERN = Pattern.compile(" "); @Override protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { String[] words = PATTERN.split(value.toString()); System.out.println("********" + value.toString()); if(words.length >= 2){ if(words.length == 2){ context.write(new Text("ERROR"), new Text(value.toString())); }else if(words[0].equals("at")){ context.write(new Text("ERROR"), new Text(value.toString())); }else{ context.write(new Text(words[2]), new Text(value.toString())); } }else context.write(new Text("OTHER"), new Text(value.toString())); } } /** * 对单词做统计 * @author nange * */ class reduceStatistics1 extends Reducer<Text, Text, Text, Text> { @Override protected void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException { for(Text t: values){ context.write(key, new Text(t.toString())); } } } <file_sep>/java8/src/main/java/com/lambda/CreatObjectUtils.java package com.lambda; import java.util.ArrayList; import java.util.Date; import java.util.function.Consumer; /** * Created by zhoujun on 2017/9/6. */ public class CreatObjectUtils<T>{ private volatile ArrayList<T> arr = new ArrayList<>(); public CreatObjectUtils<T> add(T t){ arr.add(t); log("add a elements........"); return this; } public CreatObjectUtils<T> remove(int index){ arr.remove(index); log("remove a elements........."); return this; } public void audit(T t, Consumer<T> consumer){ log("audit something........"); consumer.accept(t); } public static void log(String masg){ System.out.println( " 时间: " + new Date() + " 日志: " + masg); } public ArrayList<T> getArr() { return arr; } } <file_sep>/spark/src/main/java/com/classstudy/ReduceByKeyTest.java package com.classstudy; import org.apache.spark.HashPartitioner; import org.apache.spark.Partitioner; import org.apache.spark.SparkConf; import org.apache.spark.api.java.JavaPairRDD; import org.apache.spark.api.java.JavaRDD; import org.apache.spark.api.java.JavaSparkContext; import org.apache.spark.api.java.function.Function2; import org.apache.spark.api.java.function.PairFunction; import scala.Tuple1; import scala.Tuple2; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; public class ReduceByKeyTest { public static void main(String[] args){ SparkConf conf = new SparkConf().setAppName("demo").setMaster("local"); JavaSparkContext sc = new JavaSparkContext(conf); JavaRDD<String> rdd = sc.parallelize(new ArrayList<String>(){{ this.add("http://www.baidu.com/about.html"); this.add("http://www.ali.com/index.html"); this.add("http://www.sina.com/first.html"); this.add("http://www.sohu.com/index.html"); this.add("http://www.baidu.com/index.jsp"); this.add("http://www.sina.com/help.html"); }}); HashMap<String, Integer> dateResult = new HashMap<>(); JavaPairRDD<String, Integer> pairRDD = rdd.mapToPair(new PairFunction<String, String, Integer>() { @Override public Tuple2<String, Integer> call(String s) throws Exception { return new Tuple2<>(s,1); } }); JavaPairRDD<String, Integer> pairRDD2 = pairRDD.reduceByKey(new Partitioner() { @Override public int getPartition(Object key) { String keystr = (String)key; String[] arr = keystr.split("/"); boolean[] isr = {false}; dateResult.keySet().forEach(s -> { if(arr[2].equals(s)) isr[0] = true; }); if(isr[0]) { dateResult.put(arr[2], dateResult.get(arr[2])+1); System.out.println("true: map的长度: " + dateResult.size()); System.out.println("date: " + arr[2] + " "+ dateResult.get(arr[2])); return 0; } else { dateResult.put(arr[2], 1); System.out.println("false: map的长度: " + dateResult.size()); System.out.println("date: " + arr[2] + " "+ dateResult.get(arr[2])); return 1; } } @Override public int numPartitions() { return 2; } }, (i1, i2) -> i1 + i2); System.out.println("****** : " + pairRDD2.getNumPartitions()); System.out.println("****** : " + pairRDD2.glom().collect()); } }
55d63fe65323a86ee35c40d151cb74382b2c6124
[ "Markdown", "Java" ]
33
Java
zhoujun134/java
466722ecbe4b4caadbd510640d178018d8d91bc8
a0173f1a0246b9429ce31a33557557fea393a46c
refs/heads/master
<repo_name>JiiamingHan/6231Assignment1<file_sep>/src/Test/MTLServerTest.java package Test; import ServerFile.rmiMethodDDO; import ServerFile.rmiMethodMTL; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.rmi.RemoteException; public class MTLServerTest { ServerFile.rmiMethodMTL rmiMethodMTL; File MTLFile = new File(""); String FilePath = MTLFile.getAbsolutePath(); /** * Loading the database in DDO. */ @Before public void before(){ try { rmiMethodMTL = new rmiMethodMTL(); ObjectInputStream l_ois = new ObjectInputStream(new FileInputStream(FilePath + "\\" + "LogFile" + "\\" + "MTLFile" + "\\" + "MTLServer" + ".txt")); rmiMethodMTL = (ServerFile.rmiMethodMTL) l_ois.readObject(); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } } /** * The test is finish. */ @After public void after(){ System.out.println("This test is OK."); } /** * Test for creating the teacher record. */ @Test public void DDOServerTrecordTest(){ boolean result; try { result = rmiMethodMTL.createTRecord( "MTL11111","firstName", "lastName", "Address", "Phone", "Specialization", "mtl"); Assert.assertEquals(result, true); result = rmiMethodMTL.createTRecord( "MTL11111","firstName", "lastName", "Address", "Phone", "Specialization", "XXX"); Assert.assertEquals(result, false); } catch (RemoteException e) { e.printStackTrace(); } } /** * Test for creating the student record. */ @Test public void DDOServerSrecordTest(){ boolean result; try { result = rmiMethodMTL.createSRecord( "MTL11111","firstName", "lastName", "CoursesRegistered", "active", "StatusDate"); Assert.assertEquals(result, true); result = rmiMethodMTL.createSRecord( "MTL11111","firstName", "lastName", "CoursesRegistered", "XXX", "StatusDate"); Assert.assertEquals(result, false); } catch (RemoteException e) { e.printStackTrace(); } } /** * Test for editing record. */ @Test public void DDOServerEditrecordTest(){ boolean result; try { rmiMethodMTL.createSRecord( "MTL11111","firstName", "lastName", "CoursesRegistered", "active", "StatusDate"); rmiMethodMTL.printRecord("MTL11111"); result = rmiMethodMTL.editRecord("MTL11111", "SR10001","status","inactive"); Assert.assertEquals(result, true); } catch (RemoteException e) { e.printStackTrace(); } } /** * Test for editing record. */ @Test public void DDOServerGetCountTest(){ String result; try { rmiMethodMTL.createSRecord( "MTL11111","firstName", "lastName", "CoursesRegistered", "active", "StatusDate"); rmiMethodMTL.printRecord("MTL11111"); result = rmiMethodMTL.getRecordCounts(); System.out.println(result); } catch (RemoteException e) { e.printStackTrace(); } } } <file_sep>/src/ServerFile/RMIServerDDO.java package ServerFile; import java.io.*; import java.net.*; import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; import java.rmi.server.UnicastRemoteObject; import java.util.Scanner; public class RMIServerDDO { public static void main(String[] args) { DatagramSocket server = null; try { rmiCenterServer r_Interface = new rmiMethodDDO(); File DDOFile = new File(""); String FilePath = DDOFile.getAbsolutePath(); DDOFile = new File(FilePath + "\\" + "LogFile" + "\\" + "DDOFile" + "\\" + "DDOServer" + ".txt"); if (!DDOFile.exists()) { try { DDOFile.createNewFile(); } catch (IOException e) { //e.printStackTrace(); System.out.println("The Map is Empty!"); } } try { ObjectInputStream l_ois = null; l_ois = new ObjectInputStream(new FileInputStream(FilePath + "\\" + "LogFile" + "\\" + "DDOFile" + "\\" + "DDOServer" + ".txt")); try { r_Interface = (rmiCenterServer) l_ois.readObject(); } catch (ClassNotFoundException e) { e.printStackTrace(); System.out.println("Empty!"); } } catch (IOException e) { //e.printStackTrace(); System.out.println("The Map is Empty!"); } LocateRegistry.createRegistry(6233); java.rmi.Naming.rebind("rmi://localhost:6233/r_Interface", r_Interface); System.out.print("Server Ready! " + "\n"); try { server = new DatagramSocket(5051); byte[] recvBuf = new byte[1000]; while (true) { DatagramPacket recvPacket = new DatagramPacket(recvBuf, recvBuf.length); server.receive(recvPacket); String recvStr = new String(recvPacket.getData(), 0, recvPacket.getLength()); System.out.println("Hello World!" + recvStr); int port = recvPacket.getPort(); InetAddress addr = recvPacket.getAddress(); String sendStr = r_Interface.getRecordCounts(); byte[] sendBuf = sendStr.getBytes(); DatagramPacket sendPacket = new DatagramPacket(sendBuf, sendBuf.length, addr, port); server.send(sendPacket); } } catch (SocketException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } catch (RemoteException | MalformedURLException e) { e.printStackTrace(); } server.close(); } } <file_sep>/src/Test/LVLServerTest.java package Test; import ServerFile.rmiMethodDDO; import ServerFile.rmiMethodLVL; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.rmi.RemoteException; public class LVLServerTest { ServerFile.rmiMethodLVL rmiMethodLVL; File LVLFile = new File(""); String FilePath = LVLFile.getAbsolutePath(); /** * Loading the database in DDO. */ @Before public void before(){ try { rmiMethodLVL = new rmiMethodLVL(); ObjectInputStream l_ois = new ObjectInputStream(new FileInputStream(FilePath + "\\" + "LogFile" + "\\" + "LVLFile" + "\\" + "LVLServer" + ".txt")); rmiMethodLVL = (ServerFile.rmiMethodLVL) l_ois.readObject(); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } } /** * The test is finish. */ @After public void after(){ System.out.println("This test is OK."); } /** * Test for creating the teacher record. */ @Test public void LVLServerTrecordTest(){ boolean result; try { result = rmiMethodLVL.createTRecord( "LVL11111","firstName", "lastName", "Address", "Phone", "Specialization", "mtl"); Assert.assertEquals(result, true); result = rmiMethodLVL.createTRecord( "LVL11111","firstName", "lastName", "Address", "Phone", "Specialization", "XXX"); Assert.assertEquals(result, false); } catch (RemoteException e) { e.printStackTrace(); } } /** * Test for creating the student record. */ @Test public void LVLServerSrecordTest(){ boolean result; try { result = rmiMethodLVL.createSRecord( "LVL11111","firstName", "lastName", "CoursesRegistered", "active", "StatusDate"); Assert.assertEquals(result, true); result = rmiMethodLVL.createSRecord( "LVL11111","firstName", "lastName", "CoursesRegistered", "XXX", "StatusDate"); Assert.assertEquals(result, false); } catch (RemoteException e) { e.printStackTrace(); } } /** * Test for editing record. */ @Test public void LVLServerEditrecordTest(){ boolean result; try { rmiMethodLVL.createSRecord( "LVL11111","firstName", "lastName", "CoursesRegistered", "active", "StatusDate"); rmiMethodLVL.printRecord("LVL11111"); result = rmiMethodLVL.editRecord("LVL11111", "SR10001","status","inactive"); Assert.assertEquals(result, true); } catch (RemoteException e) { e.printStackTrace(); } } /** * Test for editing record. */ @Test public void LVLServerGetCountTest(){ String result; try { rmiMethodLVL.createSRecord( "LVL11111","firstName", "lastName", "CoursesRegistered", "active", "StatusDate"); rmiMethodLVL.printRecord("LVL11111"); result = rmiMethodLVL.getRecordCounts(); System.out.println(result); } catch (RemoteException e) { e.printStackTrace(); } } } <file_sep>/src/Test/DDOServerTest.java package Test; import ServerFile.rmiCenterServer; import ServerFile.rmiMethodDDO; import org.junit.*; import java.io.*; import java.rmi.RemoteException; public class DDOServerTest { rmiMethodDDO rmiMethodDDO; File DDOFile = new File(""); String FilePath = DDOFile.getAbsolutePath(); /** * Loading the database in DDO. */ @Before public void before(){ try { rmiMethodDDO = new rmiMethodDDO(); ObjectInputStream l_ois = new ObjectInputStream(new FileInputStream(FilePath + "\\" + "LogFile" + "\\" + "DDOFile" + "\\" + "DDOServer" + ".txt")); rmiMethodDDO = (ServerFile.rmiMethodDDO) l_ois.readObject(); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } } /** * The test is finish. */ @After public void after(){ System.out.println("This test is OK."); } /** * Test for creating the teacher record. */ @Test public void DDOServerTrecordTest(){ boolean result; try { result = rmiMethodDDO.createTRecord( "DDO11111","firstName", "lastName", "Address", "Phone", "Specialization", "mtl"); Assert.assertEquals(result, true); result = rmiMethodDDO.createTRecord( "DDO11111","firstName", "lastName", "Address", "Phone", "Specialization", "XXX"); Assert.assertEquals(result, false); } catch (RemoteException e) { e.printStackTrace(); } } /** * Test for creating the student record. */ @Test public void DDOServerSrecordTest(){ boolean result; try { result = rmiMethodDDO.createSRecord( "DDO11111","firstName", "lastName", "CoursesRegistered", "active", "StatusDate"); Assert.assertEquals(result, true); result = rmiMethodDDO.createSRecord( "DDO11111","firstName", "lastName", "CoursesRegistered", "XXX", "StatusDate"); Assert.assertEquals(result, false); } catch (RemoteException e) { e.printStackTrace(); } } /** * Test for editing record. */ @Test public void DDOServerEditrecordTest(){ boolean result; try { rmiMethodDDO.createSRecord( "DDO11111","firstName", "lastName", "CoursesRegistered", "active", "StatusDate"); rmiMethodDDO.printRecord("DDO11111"); result = rmiMethodDDO.editRecord("DDO11111", "SR10001","status","inactive"); Assert.assertEquals(result, true); } catch (RemoteException e) { e.printStackTrace(); } } /** * Test for editing record. */ @Test public void DDOServerGetCountTest(){ String result; try { rmiMethodDDO.createSRecord( "DDO11111","firstName", "lastName", "CoursesRegistered", "active", "StatusDate"); rmiMethodDDO.printRecord("DDO11111"); result = rmiMethodDDO.getRecordCounts(); System.out.println(result); } catch (RemoteException e) { e.printStackTrace(); } } }
e6fd80af256b637f5ddf0e36c1c83121f1e55eee
[ "Java" ]
4
Java
JiiamingHan/6231Assignment1
2abfef2330312ae42a3f59d78902703587d6bb6b
47f6a216fe652e02eb519a8e573154a3615069ee
refs/heads/master
<file_sep> import java.util.*; import java.util.concurrent.CyclicBarrier; public class Simulation { public static int inputMaxSeats() { int max = 0; boolean ok = false; Scanner sc = new Scanner(System.in); while (ok != true) { try { System.out.printf("%s >> Enter Maximum seats = ", Thread.currentThread().getName()); max = sc.nextInt(); if (max > 0) { ok = true; } else { System.out.println("Invalid Input"); } } catch (Exception e) { System.err.println("Wrong Format! Please Enter a Number"); sc.next(); } } return max; } public static int inputCheckPoint() { int chk = 0; Scanner sc = new Scanner(System.in); boolean ok = false; while (ok != true) { try { System.out.printf("%s >> Enter Checkpoint = ", Thread.currentThread().getName()); chk = sc.nextInt(); if (chk >= 0) { ok = true; } else { System.out.println("Invalid Input"); } } catch (Exception e) { System.out.println("Wrong Format!, Please Enter a Number"); sc.next(); } } return chk; } public static void main(String[] args) { int maxSeats; int checkPoint; maxSeats = inputMaxSeats(); checkPoint = inputCheckPoint(); ArrayList<TicketCounter> t_counter = new ArrayList<TicketCounter>(); BusLine airportBus = new BusLine(maxSeats); BusLine cityBus = new BusLine(maxSeats); for (int i = 1; i < 4; i++) { String name = "T" + i; TicketCounter temp = new TicketCounter(name, maxSeats, airportBus, cityBus, checkPoint); t_counter.add(temp); } //start the threads for (int i = 0; i < 3; i++) { t_counter.get(i).start(); } CyclicBarrier checkPt = new CyclicBarrier(4); for (int i = 0; i < 3; i++) { t_counter.get(i).setCyclicBarrier(checkPt); } do { try { Thread.sleep(100); } catch (InterruptedException ex) { } } while (checkPt.getNumberWaiting() < 3); //print Check Point System.out.printf("\n%s >> ==================== Check Point ====================\n", Thread.currentThread().getName()); System.out.printf("%s >> %d airport-bound bus have been allocated\n", Thread.currentThread().getName(),airportBus.bus_list.size()); System.out.printf("%s >> %d city-bound bus have been allocated\n", Thread.currentThread().getName(),cityBus.bus_list.size()); System.out.printf("%s >> ======================================================\n\n", Thread.currentThread().getName()); try { checkPt.await(); } catch (Exception ex) { } for (int i = 0; i < 3; i++) { try { t_counter.get(i).join(); } catch (Exception e) { System.err.println(e); } } //print Summary System.out.printf("\n%s >> ==================== Airport Bound =====================", Thread.currentThread().getName()); airportBus.printBusLine("A"); System.out.printf("\n%s >> ==================== City Bound ====================", Thread.currentThread().getName()); cityBus.printBusLine("C"); } } <file_sep>Group Project2: Bus allocation.\ =============================== Team members =============================== <NAME> 5980026 <NAME> 5980450 <NAME> 5980462 <NAME> 5981016<file_sep> import java.io.File; import java.io.FileNotFoundException; import java.util.*; import java.util.concurrent.CyclicBarrier; public class TicketCounter extends Thread { private BusLine airport; private BusLine city; private int MaxSeats; private int checkID; private CyclicBarrier barrier; public void setCyclicBarrier(CyclicBarrier bar) { barrier = bar; } TicketCounter(String n, int m, BusLine a, BusLine c, int cID) { super(n); MaxSeats = m; airport = a; city = c; checkID = cID; } @Override public void run() { try { int transaction; int people; String name; String destination; Scanner sc = new Scanner(new File(this.getName() + ".txt")); do { String line = sc.nextLine(); String[] buf = line.split(","); transaction = Integer.parseInt(buf[0].trim()); name = buf[1].trim(); people = Integer.parseInt(buf[2].trim()); destination = buf[3].trim(); try { if (transaction == checkID) { barrier.await(); } } catch (Exception e) { System.err.println(e); } if (destination.equals("A") || destination.equals("a")) { airport.allocateBus(transaction, name, people, destination, this.getName()); } else if (destination.equals("C") || destination.equals("c")) { city.allocateBus(transaction, name, people, destination, this.getName()); } } while (sc.hasNext()); } catch (FileNotFoundException | NumberFormatException e) { System.err.println(e); } } }
bdbdd2e69db48f960a1329d96bab538c1e10b023
[ "Java", "Text" ]
3
Java
stateless-x/Bus_Allocation
80c7107318970c368093676bd1ce012d054ac6fc
961007ed2021c0a81bb44920d293c53291471304
refs/heads/master
<repo_name>daniell1988/Servicos<file_sep>/Readme.MD # Estrutura: Realizei o desenvolvimento dos serviços conforme os requisitos solicitados. Ambos integram com MongoDB na mesma collection. # Resposta 4: Deadlock acontece quando o recurso de uma thread não é liberado e outra não consegue ser executada permanecendo em estado de espera. Isso pode ser evitado implementando mecanismos de prevencão em filas de execução. # Resposta 3: Ambas realizam o mesma tarefa. A parallelSreams pode ser processando em paralelo utilizando mais threads, porém pode ser muito custoso. <file_sep>/campanha/src/main/java/com/rest/campanha/dao/CampanhaRepository.java package com.rest.campanha.dao; import org.springframework.data.repository.CrudRepository; import com.rest.campanha.models.Campanha; public interface CampanhaRepository extends CrudRepository<Campanha, String>, CampanhaRepositoryCustom { @Override Campanha findOne(String id); @Override void delete(Campanha deleted); } <file_sep>/socioTorcedor/src/main/java/com/rest/sociotorcedor/models/Socio.java package com.rest.sociotorcedor.models; import java.time.LocalDate; import java.util.List; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; @Document(collection = "campanha") @JsonIgnoreProperties(ignoreUnknown = true) public class Socio { @Id String id; String nomeCompleto; String email; @JsonFormat(pattern = "dd/MM/yyyy") @JsonSerialize(using = ToStringSerializer.class) @JsonDeserialize LocalDate dataNascimento; String timeCoracao; List<Campanha> campanhas; public Socio() { } public Socio(String nomeCompleto, String email, LocalDate dataNascimento, String timeCoracao) { this.nomeCompleto = nomeCompleto; this.email = email; this.dataNascimento = dataNascimento; this.timeCoracao = timeCoracao; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getNomeCompleto() { return nomeCompleto; } public void setNomeCompleto(String nomeCompleto) { this.nomeCompleto = nomeCompleto; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public LocalDate getDataNascimento() { return dataNascimento; } public void setDataNascimento(LocalDate dataNascimento) { this.dataNascimento = dataNascimento; } public String getTimeCoracao() { return timeCoracao; } public void setTimeCoracao(String timeCoracao) { this.timeCoracao = timeCoracao; } public List<Campanha> getCampanhas() { return campanhas; } public void setCampanhas(List<Campanha> campanhas) { this.campanhas = campanhas; } }<file_sep>/socioTorcedor/src/main/java/com/rest/sociotorcedor/respositories/SocioRepositoryCustom.java package com.rest.sociotorcedor.respositories; import java.util.List; import com.rest.sociotorcedor.models.Campanha; import com.rest.sociotorcedor.models.Socio; public interface SocioRepositoryCustom { public List<Campanha> findCampanhasAtivas(); public List<Campanha> findCampanhasAtivasByTime(Socio socio); public Socio findByEMail(Socio socio); } <file_sep>/Stream/src/com/stream/teste/StreamImpl.java package com.stream.teste; import java.util.NoSuchElementException; public class StreamImpl implements Stream{ private int posicao = 0; private String palavra; public StreamImpl(String palavra) { this.palavra = palavra; } public char getNext() { if(hasNext()) { return palavra.charAt(posicao ++); } else { throw new NoSuchElementException("Não existem mais elementos " + palavra.length()); } } public boolean hasNext() { return palavra.length() == posicao ? false : true; } } <file_sep>/campanha/src/main/resources/application.properties spring.data.mongodb.database=websneakers spring.data.mongodb.host=localhost spring.data.mongodb.port=27017<file_sep>/socioTorcedor/src/main/java/com/rest/sociotorcedor/respositories/SocioRepository.java package com.rest.sociotorcedor.respositories; import org.springframework.data.repository.CrudRepository; import com.rest.sociotorcedor.models.Socio; public interface SocioRepository extends CrudRepository<Socio, String>, SocioRepositoryCustom { @Override Socio findOne(String id); @Override void delete(Socio deleted); } <file_sep>/campanha/src/main/java/com/rest/campanha/dao/CampanhaRepositoryImpl.java package com.rest.campanha.dao; import java.time.LocalDate; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.core.MongoOperations; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import com.rest.campanha.models.Campanha; public class CampanhaRepositoryImpl implements CampanhaRepositoryCustom { @Autowired private MongoOperations operations; public List<Campanha> findCampanhasMesmoPeriodo(Campanha campanha) { Query query = new Query(); query.addCriteria(new Criteria().orOperator( Criteria.where("dataInicio").lte(campanha.getDataFim()).gte(campanha.getDataInicio()), Criteria.where("dataFim").lte(campanha.getDataFim()).gte(campanha.getDataInicio()) )); return operations.find(query, Campanha.class); } @Override public List<Campanha> findCampanhasAtivas() { Query query = new Query(); query.addCriteria(new Criteria().where("dataFim").gte(LocalDate.now())); return operations.find(query, Campanha.class); } @Override public List<Campanha> findCampanhasAtivasByTime(String timeCoracao) { Query query = new Query(); query.addCriteria(new Criteria().where("dataFim").gte(LocalDate.now()).and("idTimeCoracao").is(timeCoracao)); return operations.find(query, Campanha.class); } } <file_sep>/Stream/src/com/stream/teste/AchaCaracter.java package com.stream.teste; import java.util.regex.Matcher; import java.util.regex.Pattern; public class AchaCaracter { String palavra; Stream stream ; char anteriorAnterior = ' '; char anterior = ' '; char atual = ' '; public AchaCaracter(String palavra) { this.palavra = palavra; this.stream = new StreamImpl(palavra); } public char caracter() { while(stream.hasNext()) { atualizaCaracteres(stream.getNext()); if(encontrouCaracter()) return this.atual; } return this.atual; } private boolean isVogal(String vogal) { Pattern pattern = Pattern.compile("[AEIOUaeiou]|[^\\w\\p{Punct}\\p{Space}]"); Matcher matcher = pattern.matcher(vogal); return matcher.matches(); } private void atualizaCaracteres(char atual) { this.anteriorAnterior = this.anterior; this.anterior = this.atual; this.atual = atual; } private boolean encontrouCaracter() { if(!isVogal(Character.toString(anterior))) { if(isVogal(Character.toString(anteriorAnterior)) && isVogal(Character.toString(atual))) { if(!caracterRepete(atual)) return true; } } return false; } boolean caracterRepete(char c) { int counter = 0; String s = this.palavra; for( int i=0; i< s.length(); i++ ) { if( s.charAt(i) == '$' ) { counter++; } } if(counter < 1) return true; return false; } }
db5386eec9136aa4fbb8cd9da5bfd30df8dd412c
[ "Markdown", "Java", "INI" ]
9
Markdown
daniell1988/Servicos
bd040a8595bc86bbe5f8b6c95ecb932fd555a566
d2f1bc159ba12e8389806aabf0f92b17e9166390
refs/heads/master
<repo_name>fork42541/catflap<file_sep>/README.md # catflap NTLMv2 cracking utility 1. Extracts NTLMv2 parts from a Wireshark capture file for hashcat cracking. 2. Creates a test case from a capture file or hash file plus a suppplied password to check NTLMv2 cracker working correctly. Refer to http://www.exploresecurity.com/from-csv-to-cmd-to-qwerty/ <file_sep>/catflap.sh #!/bin/bash # Extracts NTLMv2 parts from capture file for Hashcat cracking # Creates test case using suppplied password from capture file or hash file # Author: <NAME> @exploresecurity # www.exploresecurity.com # www.nccgroup.com # Version: 0.1 if [ $# -eq 0 ] || [ $# -gt 2 ] || [ "$1" == "-h" ] || [ "$1" == "--help" ]; then echo "Extracts NTLMv2 parts from capture file for Hashcat cracking:" echo " `basename $0` <capture_file>" echo "Creates test case using suppplied password from capture file or hash file:" echo " `basename $0` <capture_file | hash_file> <test_password>" exit 1 fi if [ ! -e "$1" ]; then echo "Input file $1 does not exist" exit 1 fi # function to deal with capture files cap_file() { hash tshark 2>/dev/null || { echo "This script requires tshark"; exit 1; } NUM_NTLMSSP=$(tshark -r $1 -Y "ntlmssp.identifier == NTLMSSP" 2>/dev/null | wc -l) if [[ -z $NUM_NTLMSSP ]]; then echo "Error" echo "- check the input file is a valid packet capture" echo "- check the input file contains NTLMSSP packets" exit 1 fi CHALLENGE=$(tshark -r $1 -Y "ntlmssp.messagetype == 0x00000002" -T fields -e ntlmssp.ntlmserverchallenge 2>/dev/null | sed 's/://g') if [[ -z $CHALLENGE ]]; then echo "Error" echo "- no Type 2 packet found with challenge" exit 1 fi if [[ $(echo $CHALLENGE | wc -w) -ne 1 ]]; then echo "The capture file looks to have more than 1 NTLM exchange" echo "- using the first exchange" echo "- otherwise export the packets of interest to a separate file" EXTRACT=1 CHALLENGE=$(echo $CHALLENGE|awk '{print $1}') fi DOMAIN=$(tshark -r $1 -Y "ntlmssp.messagetype == 0x00000003" -T fields -e ntlmssp.auth.domain 2>/dev/null) if [[ -z $DOMAIN ]]; then echo "Error" echo "- no Type 3 packet found with domain" exit 1 fi if [[ $(echo $DOMAIN | wc -w) -ne 1 && -z $EXTRACT ]]; then echo "The capture file looks to have more than one Type 3 message but only one Type 2 message" echo "- it's probably best to review the capture file" exit 1 fi if [[ $EXTRACT ]]; then DOMAIN=$(echo $DOMAIN|awk '{print $1}') fi USERNAME=$(tshark -r $1 -Y "ntlmssp.messagetype == 0x00000003" -T fields -e ntlmssp.auth.username 2>/dev/null) if [[ -z $USERNAME ]]; then echo "Error" echo "- no Type 3 packet found with username" exit 1 fi if [[ $EXTRACT ]]; then USERNAME=$(echo $USERNAME|awk '{print $1}') fi HMAC=$(tshark -r $1 -Y "ntlmssp.messagetype == 0x00000003" -T fields -e ntlmssp.ntlmv2_response 2>/dev/null | sed 's/://g' | cut -c 1-32) if [[ -z $HMAC ]]; then echo "Error" echo "- no Type 3 packet found with HMAC" echo "- maybe this is a LM or NTLMv1 exchange" exit 1 fi if [[ $EXTRACT ]]; then HMAC=$(echo $HMAC|awk '{print $1}') fi BLOB=$(tshark -r $1 -Y "ntlmssp.messagetype == 0x00000003" -T fields -e ntlmssp.ntlmv2_response 2>/dev/null | sed 's/://g' | cut -c 33-) if [[ -z $BLOB ]]; then echo "Error" echo "- no Type 3 packet found with blob" exit 1 fi if [[ $EXTRACT ]]; then BLOB=$(echo $BLOB|awk '{print $1}') fi echo ">> Hash format for cracking" echo $USERNAME::$DOMAIN:$CHALLENGE:$HMAC:$BLOB } # see if there's a hash in the input file HASH=$(grep -E ".*::.*:[0-9a-f]{16}:[0-9a-f]{32}:[0-9a-f]+" "$1") if [[ -z $HASH ]]; then cap_file "$1" if [ $# -eq 1 ]; then exit 0 fi else echo "Input file looks to contain a hash" if [ $# -eq 1 ]; then echo "Add a password parameter to create a test case" exit 1 fi if [[ $(echo $HASH | wc -w) -ne 1 ]]; then echo "The hash file looks to have more than 1 NTLMv2 hash" echo "- using the first hash" HASH=$(echo $HASH|awk '{print $1}') fi USERNAME=$(echo $HASH|awk -F : '{print $1}') DOMAIN=$(echo $HASH|awk -F : '{print $3}') CHALLENGE=$(echo $HASH|awk -F : '{print $4}') BLOB=$(echo $HASH|awk -F : '{print $6}') fi #NT hash of supplied password converted to little endian unicode, removing first 2 BOM bytes NTHASH=$(echo -n $2|iconv -f ascii -t utf16|tail -c +3|openssl dgst -md4 -binary|xxd -p) #convert USERNAME to uppercase and concatenate with DOMAIN INTHASH=$(echo -n ${USERNAME^^}$DOMAIN|iconv -f ascii -t utf16|tail -c +3|openssl dgst -md5 -mac HMAC -macopt hexkey:$NTHASH -binary|xxd -p) HMAC=$(echo -n $CHALLENGE$BLOB|xxd -r -p|openssl dgst -md5 -mac HMAC -macopt hexkey:$INTHASH -binary|xxd -p) echo echo -e ">> Hash format for cracking with password set to \033[1;31m$2\e[00m" echo $USERNAME::$DOMAIN:$CHALLENGE:$HMAC:$BLOB exit 0
2ce76f18cf0626783008d405c6a0f786f6d80e5d
[ "Markdown", "Shell" ]
2
Markdown
fork42541/catflap
c6b3a3719f0114dd2a9e60b7b5ab4947e992f20b
cd1978921e358be37bf4e1956cdf436455fb21e5
refs/heads/main
<file_sep>// Aperture Science CIA Breaker simulation for CIA recruits // <NAME> #include <iostream> #include <string> #include <cstdlib> #include <ctime> using namespace std; int rightanswers = 0;//intiger for rightanswer int wronganswers = 0;//intiger for wronganser int totalanswers = 0;//intiger for total attempts string wordArray[3]; int main() { //amount of words used enum fields { WORD, HINT, NUM_FIELDS }; const int NUM_WORDS = 10; const string WORDS[NUM_WORDS][NUM_FIELDS] = { //words that will be guess and their hints {"paint", "Comes in an array of colors."}, {"glasses", "These might help you see the answer."}, {"shades", "The Sun is to bright cover your eyes!"}, {"sunburn", "Thats going to hurt after a pool day."}, {"skateboard", "Just a peace of wood with 4 wheels."}, {"room", "A place you go to sleep."}, {"tesla", "Why would anyone want an electric car."}, {"nintendo", "Marios platform."}, {"gaben", "Lord of the pc master race."}, {"car", "Your fastest mode of trasportation."}, }; for (int i = 0; i < 3; ++i) { srand(time(0)); int words = (rand() % NUM_WORDS); for (int c = 0; c < 3; ++c) { while (WORDS[words][WORD] == wordArray[c]) { words = (rand() % NUM_WORDS); } } wordArray[i] = WORDS[words][WORD]; srand(static_cast<unsigned int>(time(0))); int choice = (rand() % NUM_WORDS); string theWord = WORDS[choice][WORD]; // word to guess string theHint = WORDS[choice][HINT]; // hint for word string jumble = theWord; // jumbled version of word int length = jumble.size(); for (int j = 0; j < length; ++j) { int index1 = (rand() % length); int index2 = (rand() % length); char temp = jumble[index1]; jumble[index1] = jumble[index2]; jumble[index2] = temp; } //text that will show in the start cout << "\t\t\Welcome To our Aperture Science monkey testing facility!\n\n"; cout << "Unscramble the letters to make a word.This test should be easy enough a monkey can do it.\n"; cout << "Enter hint if your dumber than a monkey and need a hint.\n"; cout << "Enter 'pass' to pass the word because your dumber than a monkey\n\n"; cout << "Keyword is: " << jumble; string guess; cout << "\n\nYour guess: "; cin >> guess; //game loop while ((guess != theWord) && (guess != "pass")) { if (guess == "hint") { cout << theHint; } else { cout << "Sorry, that's not it."; wronganswers++; totalanswers++; } cout << "\n\nYour guess: "; cin >> guess; } if (guess == theWord) { cout << "\nThat's it! You guessed it!\n"; totalanswers++; rightanswers++; } } //counter for right, wrong and amount of tries cout << "\n\t\tAperture Science Monekey Counter" << endl; cout << "." << endl; cout << "." << endl; cout << "Aperture Science counted " << rightanswers << " words correctly guessed." << endl; cout << "Aperture Science counted " << wronganswers << " words guessed incorrectly." << endl; cout << "Aperture Science counted a total " << totalanswers << " of words." << endl; //play again function string playAgain; cout << "Would you like to play again? Y/N" << endl; cin >> playAgain; while (true) { if (playAgain == "y") {//keep playing system("cls"); main(); } else if (playAgain == "n") { cout << "Thanks for playing!" << endl;//ending game exit(0); } else { cout << "Please input y or n..." << endl; cin >> playAgain; } } return 0; }
efeb9169de428f827bc919b0bd30479ecb7eba32
[ "C++" ]
1
C++
JesusGlitch/Keyword
46598d8180ab56bfbdacea57e2e50c333dde0fb3
4c65a102b4291214e67bc77d3855345d74d6fa78
refs/heads/master
<file_sep># java-util-projects<file_sep>package com.bs.java.utility.library.pdfmerger; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.image.BufferedImage; import java.util.*; import java.util.List; import javax.swing.*; import java.io.*; import java.awt.*; import org.apache.pdfbox.multipdf.PDFMergerUtility; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDPage; import org.apache.pdfbox.pdmodel.PDPageContentStream; import org.apache.pdfbox.pdmodel.common.PDRectangle; import org.apache.pdfbox.pdmodel.graphics.image.JPEGFactory; import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject; import org.apache.pdfbox.rendering.ImageType; import org.apache.pdfbox.rendering.PDFRenderer; class Result { String message; boolean status; } public class PdgMergerSWT extends JFrame implements ActionListener { /** * */ private static final long serialVersionUID = 1L; private static List<String> pdfFileList; JLabel jLabelSourceFolderPath, jLabelDestinationFileName, jOutputLabel1, jOutputLabel2; JButton jButtonMergePDF; JTextField jTextFieldSourceFOlderPath, jTextFieldDestinationFile; JTextArea jOutputTextArea; JTable jt = new JTable(); int sourcePathTextBoxX = 25, sourcePathTextBoxY = 20, destinationFileX = 25, destinationFileY = 60; int ButtonX = 25, ButtonY = 100, OutputX = 5, OutputY = 140; PdgMergerSWT(String SWTHeaderName) { super(SWTHeaderName); initialize(); } public static void main(String[] args) throws IOException { new PdgMergerSWT("PDF Merger Utility"); } public void initialize() { jLabelSourceFolderPath = new JLabel("Source Folder Path"); jLabelSourceFolderPath.setBounds(sourcePathTextBoxX, sourcePathTextBoxY, 400, 30); add(jLabelSourceFolderPath); jTextFieldSourceFOlderPath = new JTextField("c:\\pdfsource"); jTextFieldSourceFOlderPath.setBounds(sourcePathTextBoxX + 400, sourcePathTextBoxY, 400, 30); add(jTextFieldSourceFOlderPath); jLabelDestinationFileName = new JLabel("Provide Destination File Name with Complete Directory Path"); jLabelDestinationFileName.setBounds(destinationFileX, destinationFileY, 400, 30); add(jLabelDestinationFileName); jTextFieldDestinationFile = new JTextField("c:\\pdfsource\\mergedOutput.pdf"); jTextFieldDestinationFile.setBounds(destinationFileX + 400, destinationFileY, 400, 30); jButtonMergePDF = new JButton("Merge PDFs"); jButtonMergePDF.addActionListener(this); jButtonMergePDF.setBounds(ButtonX, ButtonY, 200, 30); add(jButtonMergePDF); jOutputLabel1 = new JLabel(""); jOutputLabel1.setBounds(OutputX, OutputY, 600, 150); add(jOutputLabel1); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(null); setLocation(100, 100); setVisible(true); setSize(1200, 350); } public static String convertToMultiline(String inputText) { return "<html>" + inputText.replaceAll("\n", "<br>") + "</html>"; } public static Result getAllPDFFIles(String sourceFolderPath) { Result result = new Result(); StringBuilder output = new StringBuilder("PDF Files found to be m erged \n"); boolean pdfFound = false; File directory = new File(sourceFolderPath); if (null != directory) { File[] files = directory.listFiles(); // If theis pathname does not denota a directoty, then listFiles() returns null if (null != files) { pdfFileList = new ArrayList<String>(); for (File file : files) { if (file.isFile()) { System.out.println(file.getAbsolutePath()); output.append(" ").append(file.getAbsolutePath()).append(" \n"); if (file.getName().endsWith(".pdf")) { if (!pdfFound) { pdfFound = true; } pdfFileList.add(file.getName()); } } } } else { System.out.println("No Files found"); result.message = "Folder Path is not a Directory"; } if (!pdfFound) { result.message = "No PDF FIles found to be merged"; result.status = false; } else { result.message = output.toString(); result.status = true; } } return result; } public static Result mergeAllPDFFIles(String sourceFolderPath, List<String> pdffileList, String DestinationFile) { File file = null; PDDocument doc = null; Result result = new Result(); // Instantiating PDFMerger Utility Class PDFMergerUtility PDFMerger = new PDFMergerUtility(); // setting the destination file PDFMerger.setDestinationFileName(DestinationFile); try { for (String fileName : pdfFileList) { file = new File(new StringBuilder().append(sourceFolderPath).append("\\").append(fileName).toString()); doc = PDDocument.load(file); // adding the source files PDFMerger.addSource(file); // closing the documents doc.close(); } // merging the documents PDFMerger.mergeDocuments(null); result.message = "PDF Documents merged successfull !!"; result.status = true; System.out.println(result.message); } catch (Exception e) { e.printStackTrace(); result.message = new StringBuilder("Exception Occurred: ").append(e.getClass().getSimpleName()).append(" ") .append(e.getMessage()).append(" ").append(e.getCause()).toString(); result.status = false; } return result; } // @ Override public void actionPerformed(ActionEvent arg0) { StringBuilder output = new StringBuilder("Process Completed: ").append("\n"); try { if (arg0.getSource() == jButtonMergePDF) { String sourceFolderPath = jTextFieldSourceFOlderPath.getText(); String destinationFile = jTextFieldDestinationFile.getText(); if (null == sourceFolderPath || sourceFolderPath.isEmpty()) { output.append("Folder Name cannot be empty").append("\n"); } else if (null == destinationFile || destinationFile.isEmpty()) { output.append("Destination File name cannot be empty").append("\n"); } else { jOutputLabel1.setText(""); Result result = null; result = getAllPDFFIles(sourceFolderPath); System.out.println("sourceFolderPath : " + pdfFileList.toString()); output.append("Files merged: \n").append(pdfFileList.toString()).append("\n"); if (result.status) { result = mergeAllPDFFIles(sourceFolderPath, pdfFileList, destinationFile); } output.append(result.message).append("\n"); } jOutputLabel1.setText(convertToMultiline(output.toString())); System.out.println("Merging Process Completed"); output.append("Shrinking Process Started").append("\n"); Thread.sleep(1000); Result resultOfShrink = shrinkPDF(null, null); output.append(resultOfShrink.message).append("\n"); output.append("Shrinking Process Completed").append("\n"); jOutputLabel1.setText(convertToMultiline(output.toString())); System.out.println(output.toString()); } } catch (Exception e) { e.printStackTrace(); jOutputLabel1.setText(convertToMultiline("Exception Occured:")); JOptionPane .showMessageDialog(null, new JLabel(convertToMultiline(new StringBuilder("Exception Occurred: ") .append(e.getClass().getSimpleName()).append(" ").append(e.getMessage()).append(" ") .append(e.getCause()).toString()))); } } public static Result shrinkPDF(String sourceFile, String destinationFile) { Result result = new Result(); try { PDDocument pdDocument = new PDDocument(); PDDocument oDocument = PDDocument.load(new File("c:\\pdfsource\\mergedOutput.pdf")); PDFRenderer pdfRenderer = new PDFRenderer(oDocument); int numberOfPages = oDocument.getNumberOfPages(); PDPage page = null; for (int i = 0; i < numberOfPages; i++) { page = new PDPage(PDRectangle.LETTER); BufferedImage bim = pdfRenderer.renderImageWithDPI(i, 200, ImageType.RGB); PDImageXObject pdImage = JPEGFactory.createFromImage(pdDocument, bim); PDPageContentStream contentStream = new PDPageContentStream(pdDocument, page); float newHeight = PDRectangle.LETTER.getHeight(); float newWidth = PDRectangle.LETTER.getWidth(); contentStream.drawImage(pdImage, 0, 0, newWidth, newHeight); contentStream.close(); pdDocument.addPage(page); } pdDocument.save("c:\\pdfsource\\compressedOutput.pdf"); pdDocument.close(); result.message = "PDF DOcuments merged successfull !!"; result.status = true; System.out.println(result.message); } catch (IOException e) { e.printStackTrace(); } return result; } }
4fe252da43fe04e929c07c42ae43deeaab91a92c
[ "Markdown", "Java" ]
2
Markdown
balaji13us/java-util-projects
66ee0ba254d167f53fd6d8de83818b31b870ad06
cb56efdce50867af58b8d013daa753337f632d37
refs/heads/master
<repo_name>briansw/bwi<file_sep>/app/models/client.rb class Client < ActiveRecord::Base include Concerns::CRUDTable has_heading 'Name', link: 'name', default: true has_heading 'Email', link: 'email' has_heading 'City', link: 'city' has_heading 'State', link: 'state' end <file_sep>/app/models/concerns/crud_table.rb module Concerns::CRUDTable extend ActiveSupport::Concern included do cattr_accessor :crud_headings do [] end end module ClassMethods def filter_crud_table(sort, direction, page) true_heading = crud_headings.any? do |crud_heading| crud_heading.link == sort end if sort && direction && true_heading sort = sort.downcase direction = direction.upcase direction = 'ASC' unless direction == 'ASC' || direction == 'DESC' sort += ' ' + direction else sort = crud_headings.select do |crud_heading| crud_heading.default end.first.link + ' ASC' end page(page).order(sort) end alias_method :filter_table, :filter_crud_table def has_heading(*args) options = args.extract_options! options[:parent] = self self.crud_headings << Heading.new(*args, options) end end end<file_sep>/app/controllers/admin/clients_controller.rb class Admin::ClientsController < Admin::ApplicationController private def permitted_params params.permit(client: [ :name, :email, :phone, :address_one, :address_two, :address_three, :city, :state, :zipcode ]) end end<file_sep>/app/helpers/admin_helper.rb module AdminHelper def display_notice(notice, alert) if notice content_tag(:div, notice, class: 'notice message') else content_tag(:div, alert, class: 'notice error') end end def display_dropdown_selected(name) name.capitalize end def display_dropdown_item(name, url) class_to_use = controller_name.capitalize == name ? 'selected' : 'link' link_to(name, url, class: class_to_use) end def display_active_marker(active) status = active ? 'active' : 'inactive' content_tag(:div, status, class: "active-marker #{status}") end def display_crud_headings_for(klass_name, options = {}) klass = klass_name.to_s.capitalize.constantize crud_headings = klass.crud_headings options[:target] ||= "##{klass_name.to_s.pluralize}-crud-table" crud_headings.collect do |crud_heading| classes = crud_heading_class(crud_heading) data_attributes = crud_heading_attributes(crud_heading, options[:target]) title = crud_heading_title(crud_heading).html_safe content_tag :th do content_tag :span, title, class: classes, data: data_attributes end end.join('').html_safe end def crud_heading_class(heading) if heading_selected?(heading) || show_default_heading?(heading) 'selected sorter' else 'sorter' end end def crud_heading_attributes(heading, target) klass = heading.parent next_direction = sort_direction_cycle('desc', 'asc') if heading_selected?(heading) direction = next_direction elsif show_default_heading?(heading) direction = 'asc' else direction = 'asc' end url = polymorphic_url([:admin, klass], format: :json, routing_type: :path) { url: url, direction: direction, page: params[:page] || 1, sort: heading.link, target: target } end def crud_heading_title(heading) if heading_selected?(heading) || show_default_heading?(heading) heading.title + sort_direction_cycle(' &#9660;', ' &#9650;') else heading.title end end def sort_direction_cycle(asc = '', desc = '') direction = (params[:direction] || '').downcase if direction == 'asc' asc elsif direction == 'desc' desc else asc end end def heading_selected?(heading) params[:sort].present? && params[:sort] == heading.link end def show_default_heading?(heading) params[:sort].nil? && heading.default end def new_content_block(name, block_type, button_type, f) content_block = f.object.send(:content_blocks).new id = content_block.object_id fields = f.fields_for :content_blocks, content_block do |content_block_field| render('admin/content_blocks/new', id: id, block_type: block_type, content_block: content_block, content_block_field: content_block_field, f: f, content_block_id: id) end link_to(name, '#', data: { id: id, type: block_type, fields: fields.gsub('\n', '') }, class: "new-content-block #{button_type}") end def delete_content_block(name, content_block_field, existing, content_block_id) if existing link_to(name, '#', data: { confirm: 'Are you sure?', content_block: "#content-block-#{content_block_field.object.id}-wrapper", destroy_field: "#destroy-#{content_block_field.object.id}" }, class: 'small-button delete delete-content-block') else link_to(name, '#', data: { confirm: 'Are you sure?', content_block: "#content-block-#{content_block_id}-wrapper" }, class: 'small-button delete delete-content-block') end end def resources_path polymorphic_path([:admin, resource_class]) end def resource_path(model) polymorphic_path([:admin, model]) end def edit_resource_path(model) polymorphic_path([:admin, model], action: 'edit') end def new_resource_path polymorphic_path([:admin, resource_class], action: 'new') end def link_to_new link_to("New #{resource_instance_name.capitalize}", new_resource_path, class: 'large-button action') if policy(resource_class).new? end def link_to_delete(model) link_to(raw('&#10008;'), resource_path(model), data: { confirm: 'Are you sure?' }, method: :delete, class: 'delete') if policy(model).destroy? end def link_to_edit(model) link_to(raw('&#63490;'), edit_resource_path(model), class: 'edit') if policy(model).edit? end def link_to_show(model) link_to(raw('&#9873;'), resource_path(model), class: 'show') if policy(model).edit? end def errors_for(model) if model.errors.any? content_tag(:div, class: "notice error") do notice = t('admin.resource.has_errors', count: model.errors.count) list = content_tag(:ul) do model.errors.full_messages.map do |msg| content_tag(:li, msg) end.join.html_safe end (notice + list).html_safe end end end end<file_sep>/app/models/image_block.rb class ImageBlock < ActiveRecord::Base belongs_to :content_block has_one :image, as: :parent, dependent: :destroy accepts_nested_attributes_for :image, reject_if: :attachment_unchanged def attachment_unchanged(params) params[:attachment].nil? end end <file_sep>/app/controllers/concerns/crud_methods.rb module Concerns::CRUDMethods extend ActiveSupport::Concern included do respond_to :html, :json end def index index! do |format| format.json { template = render_to_string(template: 'admin/shared/_crud_table.html', layout: false) render json: { status: 'success', template: template } } end end def show redirect_to action: :edit end def update update! { polymorphic_path([:admin, resource_class]) } end def create create! { polymorphic_path([:admin, resource_class]) } end protected # Overrides inherited_resources collection to insert Pundit scopes def collection get_collection_ivar || begin scope = Pundit.policy_scope!(current_user, resource_class) .filter_table(params[:sort], params[:direction], params[:page]) set_collection_ivar scope end end # Inject authorization into inherited_resources method def resource object = super authorize object object end # Inject authorization into inherited_resources method def build_resource object = super authorize object object end # Overrides inherited_resources update_resource to insert Pundit authorization def update_resource(object, attributes) object.assign_attributes(*attributes) authorize object object.save end end <file_sep>/app/controllers/admin/users_controller.rb class Admin::UsersController < Admin::ApplicationController private def permitted_params params.permit(user: [:first_name, :last_name, :email, :username, :is_admin, :is_sysop, :password, :password_confirmation, :active]) end end <file_sep>/app/controllers/admin/application_controller.rb class Admin::ApplicationController < InheritedResources::Base layout 'admin' before_action :authenticate_user! include Concerns::PunditLockdown include Concerns::CRUDMethods end <file_sep>/db/migrate/20131109020414_create_invoices.rb class CreateInvoices < ActiveRecord::Migration def change create_table :invoices do |t| t.string :invoice_number t.string :invoice_type t.text :description t.integer :client_id t.integer :rate t.integer :duration t.integer :subtotal t.integer :total t.float :tax, default: 0 t.date :invoice_date t.string :status t.timestamps end end end <file_sep>/spec/models/user_spec.rb require 'spec_helper' describe User do it 'is valid with a first_name, last_name, username, email, password and password_confirmation' do u = User.new( first_name: 'brian', last_name: 'watterson', username: 'briansw', email: '<EMAIL>', password: '<PASSWORD>', password_confirmation: '<PASSWORD>' ) expect(u).to be_valid end it 'is invalid without a first_name' do u = User.new(first_name: nil) expect(u).to have(1).errors_on(:first_name) end it 'is invalid without a last_name' do u = User.new(last_name: nil) expect(u).to have(1).errors_on(:last_name) end it 'is invalid without a username' do u = User.new(username: nil) expect(u).to have(1).errors_on(:username) end it 'is invalid without an email address' do u = User.new(email: nil) expect(u).to have(1).errors_on(:email) end it 'is invalid with a duplicate username' do User.create( first_name: 'brian', last_name: 'watterson', username: 'briansw', email: '<EMAIL>', password: '<PASSWORD>', password_confirmation: '<PASSWORD>' ) u = User.new( first_name: 'alex', last_name: 'hays', username: 'briansw', email: '<EMAIL>', password: '<PASSWORD>', password_confirmation: '<PASSWORD>' ) expect(u).to have(1).errors_on(:username) end it 'is invalid with a duplicate email' do User.create( first_name: 'brian', last_name: 'watterson', username: 'briansw', email: '<EMAIL>', password: '<PASSWORD>', password_confirmation: '<PASSWORD>' ) u = User.new( first_name: 'alex', last_name: 'hays', username: 'alexhays', email: '<EMAIL>', password: '<PASSWORD>', password_confirmation: '<PASSWORD>' ) expect(u).to have(1).errors_on(:email) end it 'returns a user full name as a string' do u = User.create( first_name: 'brian', last_name: 'watterson', username: 'briansw', email: '<EMAIL>', password: '<PASSWORD>', password_confirmation: '<PASSWORD>' ) expect(u.name).to eq('<NAME>') end end<file_sep>/app/models/text_block.rb class TextBlock < ActiveRecord::Base belongs_to :content_block validates_presence_of :title, :body end <file_sep>/app/assets/javascripts/admin/content_block.js $(document).on('click', '.delete-content-block', function(event) { event.preventDefault(); var content_block = $(this).data('content-block'), destroy_field = $(this).data('destroy-field'); if (typeof destroy_field === "undefined") { $(content_block).slideToggle(function() { $(content_block).remove(); }); } else { $(destroy_field).val(1); $(content_block).slideToggle(function() { $(content_block).insertAfter('#content-blocks'); }); } }); $(document).on('click', '.new-content-block', function(event) { event.preventDefault(); var id = $(this).data('id'), fields = $(this).data('fields'), type = $(this).data('type'), regexp = new RegExp($(this).data('id'), 'g'), time = new Date().getTime(), cb = '#content-block-' + time, cb_wrapper = $(this).closest('.content-block-wrapper'), options = $('#cloneable-cb-options').clone().removeAttr('id'); $(fields.replace(regexp, time)).insertBefore(cb_wrapper); $('#placeholder-options').replaceWith(options); set_text_areas(); $(cb).slideToggle(); }); $(document).on('click', '.move-block', function() { var direction = parseInt($(this).data('direction')), content_block = $(this).data('target'), current_position = $('.content-block-wrapper').index($(content_block)), next_position = current_position + direction, swap_with = $($('.content-block-wrapper').get(next_position)); $(content_block).hide(); direction == '1' ? $(content_block).insertAfter(swap_with).fadeIn(600) : $(content_block).insertBefore(swap_with).fadeIn(600); set_text_areas(); }); function update_sequence() { $('.position').each(function(x) { $(this).val(x + 1); }); } $('#submit-with-content-blocks input[type="submit"]').bind('click', function(event) { event.preventDefault(); $('#void').addClass('saving').toggleClass('hide').append('<p>Saving ...</p>'); update_sequence(); $('form').submit(); }); $('.content-block').fileupload(); <file_sep>/app/models/heading.rb class Heading attr_accessor :title, :link, :default, :parent def initialize(*args) options = args.extract_options! @title = args.shift @link = options[:link] @default = options[:default] || false @parent = options[:parent] @display = options[:display] end def display(record) @display.present? ? record.send(@display) : record.send(@link) end end <file_sep>/config/initializers/session_store.rb # Be sure to restart your server when you modify this file. Bwi::Application.config.session_store :cookie_store, key: '_bwi_session' <file_sep>/spec/unit/crud_table_spec.rb require 'spec_helper' class CRUDDummy attr_accessor :name, :last_name include Concerns::CRUDTable def initialize @name = 'Jack' @last_name = 'Jennings' end end describe Concerns::CRUDTable do it "adds headings" do CRUDDummy.has_heading 'Name' expect(CRUDDummy.crud_headings).not_to be_empty end it "stores heading shit" do CRUDDummy.has_heading 'Name', link: :last_name, display: :name, default: true heading = CRUDDummy.crud_headings.first expect(heading.title).to eq('Name') end end describe Heading do it "stores label" do heading = Heading.new 'Name', link: :last_name, display: :name, default: true expect(heading.title).not_to be_nil end it "stores link" do heading = Heading.new 'Name', link: :last_name, display: :name, default: true expect(heading.link).not_to be_nil end it "stores default" do heading = Heading.new 'Name', link: :last_name, display: :name, default: true expect(heading.default).not_to be_nil end it "stores display" do heading = Heading.new 'Name', link: :last_name, display: :name, default: true expect(heading.instance_variable_get(:@display)).not_to be_nil end end<file_sep>/config/routes.rb Bwi::Application.routes.draw do #################### ### Admin Routes ### #################### namespace :admin do root to: 'dashboard#index' resources :users resources :invoices resources :clients end get 'login', to: 'admin/sessions#new' post 'login', to: 'admin/sessions#create' get 'logout', to: 'admin/sessions#destroy' end <file_sep>/app/controllers/admin/invoices_controller.rb class Admin::InvoicesController < Admin::ApplicationController def show respond_to do |format| format.html format.pdf do render pdf: 'pdf' end end end private def permitted_params params.permit(invoice: [ :client_id, :invoice_number, :invoice_type, :description, :invoice_date, :status, :rate, :duration, :subtotal, :total, :tax ]) end end<file_sep>/app/helpers/will_paginate_helper.rb module WillPaginateHelper class WillPaginateAjaxLinkRenderer < WillPaginate::ActionView::LinkRenderer def prepare(collection, options, template) options[:params] ||= {} options[:params]['_'] = nil super(collection, options, template) end protected def link(text, target, attributes = {}) if target.is_a? Fixnum attributes[:rel] = rel_value(target) target = url(target).gsub(/[a-z\/]*[?]/, '').split('&').inject(Hash.new{|h,k| h[k]=[]}) do |h, s| k,v = s.split(/=/) h[k] = v.gsub('%23', '#') h end end @template.link_to(text.to_s.html_safe, '#', class: 'sorter', data: target) end end def ajax_will_paginate(collection, options = {}) will_paginate(collection, options.merge(renderer: WillPaginateHelper::WillPaginateAjaxLinkRenderer)) end end<file_sep>/app/helpers/application_helper.rb module ApplicationHelper def display_dollar_amount(amount_in_pennies) number_to_currency(amount_in_pennies / 100.0, precision: 2) end end <file_sep>/README.md # README ## Development - Ruby version: ```ruby 2.0.0p353``` possibly upgrade to 2.1 when stable - Rails version: ```rails 4.0.2``` - Database: ```MySQL``` - Database creation: ```rake db:create``` - Seed db with admin user: ```rake db:seed``` ## Production - ```Nginx + Passenger``` <file_sep>/app/models/concerns/has_content_blocks.rb module Concerns::HasContentBlocks extend ActiveSupport::Concern included do has_many :content_blocks, -> { order(position: :asc, created_at: :asc) }, as: :parent, dependent: :destroy accepts_nested_attributes_for :content_blocks, allow_destroy: true end end <file_sep>/app/models/image.rb class Image < ActiveRecord::Base belongs_to :parent, polymorphic: true mount_uploader :attachment, AttachmentUploader end <file_sep>/app/assets/javascripts/admin/crud_table.js $(document).on('click', '.sorter', (function() { var url = $(this).data('url'), crud_table = $(this).data('target'), direction = $(this).data('direction'), page = $(this).data('page'), sort = $(this).data('sort'); sort_crud_records(crud_table, url, direction, page, sort); })); function sort_crud_records(crud_table, url, direction, page, sort) { $.ajax({ url: url, type: 'GET', data: { direction: direction, page: page, sort: sort }, success: function(data, status, xhr) { $(document).on('page:update', $(crud_table).html(data.template)); } }); }<file_sep>/app/controllers/admin/content_blocks_controller.rb class Admin::ContentBlocksController < AdminController before_action :set_content_block, only: [:edit, :update, :destroy] def new @content_block = ContentBlock.new template = render_to_string(template: 'admin/content_blocks/_form', layout: false) render json: { status: 'success', template: template } end def edit render json: { content_block: @content_block } end def destroy @content_block.destroy render json: { content_block: @content_block } end private def set_content_block @content_block = ContentBlock.find(params[:id]) end end<file_sep>/app/models/content_block.rb class ContentBlock < ActiveRecord::Base belongs_to :parent, polymorphic: true has_one :text_block, dependent: :destroy accepts_nested_attributes_for :text_block has_one :image_block, dependent: :destroy accepts_nested_attributes_for :image_block end <file_sep>/app/models/invoice.rb class Invoice < ActiveRecord::Base include Concerns::CRUDTable belongs_to :client has_heading 'Invoice', link: 'invoice_number', default: true has_heading 'Client', link: 'client_id' has_heading 'Total', link: 'total' has_heading 'Date', link: 'invoice_date' has_heading 'Status', link: 'status' before_save :subtotal_in_pennies, :total_in_pennies after_create :set_invoice_number #validates_presence_of :client_id, :invoice_number, :invoice_type, :description, :invoice_date, :status #validates_numericality_of :rate, :duration, :subtotal, :total, :tax private def set_invoice_number invoice_number = 'BW' + zeros_to_append + self.id.to_s self.update_attributes invoice_number: invoice_number end def zeros_to_append zeros = '' if self.id.to_s.length < 4 ((4 - self.id.to_s.length) * 1).times { zeros += '0' } end zeros end def subtotal_in_pennies self.subtotal = (rate * duration) * 100 end def tax_as_decimal self.tax / 100.0 end def total_in_pennies self.total = ((subtotal_in_pennies * tax_as_decimal) + subtotal_in_pennies) end end
034b9ab23cb602ea133678e6268aaadb066d2edc
[ "JavaScript", "Ruby", "Markdown" ]
26
Ruby
briansw/bwi
6007b4b2fe9ef0c5946a9339e9325c0362b752ea
859b8a17ab9afc205b2e437d109312bf7997a2f6
refs/heads/master
<file_sep>; -*- Mode: Markdown; -*- ; vim: filetype=none tw=76 expandtab # ETORRENT ETORRENT is a bittorrent client written in Erlang. The focus is on robustness and scalability in number of torrents rather than in pure speed. ETORRENT is mostly meant for unattended operation, where one just specifies what files to download and gets a notification when they are. ## Flag days Flag days are when you need to do something to your setup * *2010-12-10* You will need a rebar with commit 618b292c3d84 as we got some fixes into rebar. * *2010-12-06* We now depend on riak_err. You will need to regrab dependencies. * *2010-12-02* The fast-resume-file format has been updated. You may have to delete your fast_resume_file though the system was configured to do a silent system upgrade. ## Why ETORRENT was mostly conceived as an experiment in how easy it would be to write a bittorrent client in Erlang. The hypothesis is that the code will be cleaner and smaller than comparative bittorrent clients. Note that the code is not yet battle scarred. It has not stood up to the testing of time and as such, it will fail - sometimes in nasty ways and maybe as a bad p2p citizen. Hence, you should put restraint in using it unless you are able to fix eventual problems. If you've noticed any bad behavior it is definitely a bug and should be reported as soon as possible so we can get it away. ## Currently supported BEPs: * BEP 03 - The BitTorrent Protocol Specification. * BEP 04 - Known Number Allocations. * BEP 05 - DHT Protocol * BEP 10 - Extension Protocol * BEP 12 - Multitracker Metadata Extension. * BEP 15 - UDP Tracker Protocol * BEP 23 - Tracker Returns Compact Peer Lists. ## Required software: * rebar - you need a working rebar installation to build etorrent. The rebar must have commit 618b292c3d84. * Erlang/OTP R13B04 or R14 - the etorrent system is written in Erlang and thus requires a working Erlang distribution to work. It may work with older versions, but has mostly been tested with newer versions. * A proper operating system (e.g., some UNIX-derivative). Windows support has never been tested (If you want to port, I'll be happy to help). ## GETTING STARTED 0. `make deps` - Pull the relevant dependencies into *deps/* 1. `make compile` - this compiles the source code 2. `make rel` - this creates an embedded release in *rel/etorrent* which can subsequently be moved to a location at your leisure. 3. edit `${EDITOR} rel/etorrent/etc/app.config` - there are a number of directories which must be set in order to make the system work. 4. check *rel/etorrent/etc/vm.args* - Erlang args to supply 5. be sure to protect the erlang cookie or anybody can connect to your erlang system! See the Erlang user manual in [distributed operation](http://www.erlang.org/doc/reference_manual/distributed.html) 6. run `rel/etorrent/bin/etorrent console` 7. drop a .torrent file in the watched dir and see what happens. 8. call `etorrent:help()`. from the Erlang CLI to get a list of available commands. 9. If you enabled the webui, you can try browsing to its location. By default the location is 'http://localhost:8080'. ## Troubleshooting If the above commands doesn't work, we want to hear about it. This is a list of known problems: * General: Many distributions are insane and pack erlang in split packages, so each part of erlang is in its own package. This *always* leads to build problems due to missing stuff. Be sure you have all relevant packages installed. And when you find which packages are needed, please send a patch to this file for the distribution and version so we can keep it up-to-date. * Ubuntu 10.10: Ubuntu has a symlink `/usr/lib/erlang/man -> /usr/share/man`. This is insane and generates problems when building a release (spec errors on missing files if a symlink points to nowhere). The easiest fix is to remove the man symlink from `/usr/lib/erlang`. A way better fix is to install a recent Erlang/OTP yourself and use **Begone(tm)** on the supplied version. ## QUESTIONS?? You can either mail them to `<EMAIL>` or you can come by on IRC #etorrent/freenode and ask. # Development ## PATCHES To submit patches, we have documentation in `documentation/git.md`, giving tips to patch submitters. ## Setting up a development environment When developing for etorrent, you might end up generating a new environment quite often. So ease the configuration, the build infrastructure support this. * Create a file `rel/vars/etorrent-dev_vars.config` based upon the file `rel/vars.config`. * run `make compile etorrent-dev` * run `make console` Notice that we `-pa` add `../../apps/etorrent/ebin` so you can l(Mod) files from the shell directly into the running system after having recompiled them. ## Documentation Read the HACKING.md file in this directory. For how the git repository is worked, see `documentation/git.md`. ## ISSUES Either mail them to `<EMAIL>` (We are currently lacking a mailing list) or use the [issue tracker](http://github.com/jlouis/etorrent/issues) ## Reading material for hacking Etorrent: - [Protocol specification - BEP0003](http://www.bittorrent.org/beps/bep_0003.html): This is the original protocol specification, tracked into the BEP process. It is worth reading because it explains the general overview and the precision with which the original protocol was written down. - [Bittorrent Enhancement Process - BEP0000](http://www.bittorrent.org/beps/bep_0000.html) The BEP process is an official process for adding extensions on top of the BitTorrent protocol. It allows implementors to mix and match the extensions making sense for their client and it allows people to discuss extensions publicly in a forum. It also provisions for the deprecation of certain features in the long run as they prove to be of less value. - [wiki.theory.org](http://wiki.theory.org/Main_Page) An alternative description of the protocol. This description is in general much more detailed than the BEP structure. It is worth a read because it acts somewhat as a historic remark and a side channel. Note that there are some commentary on these pages which can be disputed quite a lot. <file_sep>#!/bin/sh # Most of this file was taken from the ejabberd project and then changed # until it matched what we had as a goal NODE=etorrent HOST=localhost BEAMDIR=%%%BEAMDIR%%% CONFIGFILE=%%%CONFIGFILE%%% ERL_FLAGS=%%%ERL_FLAGS%%% start () { erl ${ERL_FLAGS} -sname ${NODE}@${HOST} -pa ${BEAMDIR} \ -config ${CONFIGFILE} -noshell -noinput -detached \ -s etorrent } debug () { erl -sname debug${NODE}@${HOST} \ -pa ${BEAMDIR} \ -remsh ${NODE}@${HOST} } ctl () { erl -noinput -sname etorrentctl@${HOST} \ -pa ${BEAMDIR} \ -s etorrent_ctl start ${NODE}@${HOST} $@ } usage () { echo "Usage: $0 {start|stop|debug}" } [ $# -lt 1 ] && usage case $1 in start) start;; debug) debug;; *) ctl $@;; esac <file_sep>## Etorrent Makefile ## Try to keep it so simple it can be run with BSD-make as well as ## GNU-make all: compile deps: rebar get-deps compile: rebar compile tags: cd apps/etorrent/src && $(MAKE) tags eunit: rebar skip_deps=true eunit doc: rebar skip_deps=true doc dialyze: compile rebar skip_deps=true dialyze rel: compile rebar generate relclean: rm -fr rel/etorrent clean: rebar clean rm -f depgraph.dot depgraph.png depgraph.pdf distclean: clean relclean devclean etorrent-dev: compile mkdir -p dev (cd rel && rebar generate target_dir=../dev/$@ overlay_vars=vars/$@_vars.config) dev: etorrent-dev devclean: rm -fr dev console: dev/etorrent-dev/bin/etorrent console \ -pa ../../apps/etorrent/ebin \ -pa ../../deps/riak_err/ebin remsh: erl -name 'foo@127.0.0.1' -remsh 'etorrent@127.0.0.1' -setcookie etorrent console-perf: perf record -- dev/etorrent-dev/bin/etorrent console -pa ../../apps/etorrent/ebin xref: compile rebar skip_deps=true xref graph: depgraph.png depgraph.pdf depgraph.dot: compile ./tools/graph apps/etorrent/ebin $@ etorrent .PHONY: all compile tags dialyze run tracer clean \ deps eunit rel xref dev console console-perf graph %.png: %.dot dot -Tpng $< > $@ %.pdf: %.dot dot -Tpdf $< > $@
15e788aac875541757f5d9daa2d46b03c5d243ae
[ "Markdown", "Makefile", "Shell" ]
3
Markdown
Zert/etorrent
5840ecfc8c348667edd12457664febdb5985ece6
89d3bdf0f221c678caf7c7cc57d5a8e08bfc3122
refs/heads/master
<file_sep>library(shiny) library(stringr) #library(topicmodels) #library(tm) library(dplyr) #library(elastic) library(RCurl) library(text2vec) library(gtools) library(shinydashboard) text.clean = function(x){ require("tm") x = gsub("<.*?>", " ", x) x = removeNumbers(x) x = removeWords(x, stopwords("english")) x = removeWords(x, stopwords("russian")) x = removeWords(x, stopwords) x = stemDocument(x,language="russian") x = stripWhitespace(x) x = gsub("^\\s+|\\s+$", "", x) x = removePunctuation(x) return(x) } stopwords = unique(c("div", "href", "rel", "com", "relnofollow", "про", "что","dneprcity.net","novostimira.com","depo.ua","bbc.com", "для", "relnofollow", "alt", "zero","img", "alignleft", "hspace", "vspace","studic.info","description","delo.ua", "alignleft", "hspace", "vspace", "pbrp","altновини", "hrefhttpgsfmopinionhtml", "mode","strong", "pstrong", "targetblank", "styletext-align", "justifi","altнапк", "classattachment-decosingl", "classreadmor","http:img.ura","pigua.info", "ethereum", "hrefhttpresonanceua", "hrefhttpsinforesistorg","replyua.net","newsoboz.org","mc.async","manabalss.lv", "hrefhttpblogiuaus", "hrefhttpvycherpnockua", "hrefhttpwwwkmugovuacontrolukpublisharticleartidampcatid","mid.ru", "noneimg", "solid", "start", "stylefont-s", "stylefloat", "classfield-item","cackle.me","container","dtp.kiev.ua", "classfield", "classfield-itemsdiv", "field-label-hiddendiv", "hrefhttpwwwaddthiscombookmarkphpv","replyua.netпро", "srcbmimgcomuaberlinstoragefinancexebfcbeadfdeccjpg","cackle_widget.push","document.createelement","polytics","loading", "eff", "i","classfield-item", "classfield", "classfield-itemsdiv", "field-label-hiddendiv", "datatyp","i.lb.ua", "propertyrdfslabel", "datatyp", "propertyrdfslabel", "skospreflabel", "typeofskosconcept","mc.src","erve.ua","www.pravda.com.ua", "reldcsubjecta", "classfield-tag", "field-type-taxonomy-term-refer","document.createelement","mc.type","lb.ua", "classimagecach", "classlink", "classrtejustifyspan", "classtranslation-link", "classtranslationru","goo.gl","newsru.co.il", "clearfixdiv", "data-colorbox-gallerygallery-node--ytzaljghei","document.getelementbyid","javascript","mon.gov.ua", "propertyrdfslabel", "skospreflabel","этом","это","які","від","datatyp","-tag","function","innerhtml","sevastopolnews.info", "hrefhttpkorupciyacom", "дуже", "там", "так", "але","span", "width", "classleftimgimg", "stylecolor", "stylefont-famili", "hspace", "vspace", "clearal","classback-block","tabletrtd", "valigntop","document.location.protocol","zakarpatpost.net", "hrefhttpwwwaddthiscombookmarkphpv", "even", "как", "titl","document.getelementsbytagname","text","true","sport.ua", "sea", "black", "hold", "one","stylemargin", "color", "outlin", "pad", "none","nbsp","widget.js","www.unian.net", "centerspan", "size", "stylefont-s", "font-siz", "divfont","s.nextsibling","s.parentnode.insertbefore","www.ukrinform.ru", "justifi", "center", "width", "height", "classfeed-descriptionp","window.cackle_widget","xcoal","politics","newsru.co.il", "pimg", "wp-post-imag", "margin", "sizesmax-width","justifystrong","joinfo.ua","1news","journal","unn.com.ua","newsonline24", "srchttpimageunncomuaoriginaljpg", "altновости", "centerimg","styletextalign","stylefontsize","justify","fontsize","padding", "helvetica","laquoР","raquo","httpnovostimiracomnewshtml","hrefhttprkrinuauploadspostsmatigeroyinyajpg","news_180574", "hrefhttpskeletinfoorg","pem","leaders","hstrong","development","religious","targetblankstrong","politico","news_180572", "che","glucosio","person","primarily","hrefhttpskeletinfoorg","classmetanav","clearall","newsoboz","politika","news_180571", "stylefontfamily","arial","fontfamily","outline","sansserif","textalign","border","inherit","left","pspan","naviny.by", "justifyspan","rgb","styleboxsizing","small","googleadsectionend","womenbox.net","arianespace","polityka","porfyrios", "classfielditem","classfielditemsdiv","fieldlabelhiddendiv", "also", "article", "Article","cellpadding","finanso.net", "download", "google", "figure","fig", "groups","Google", "however","high", "human", "levels","alt","feed","image","src","http", "jpg", "larger", "may", "number","class","новости","gazeta.ua","rossii.html","zn.ua","cellspacing","portal", "shown", "study", "studies", "this","img","using", "two", "the", "Scholar","pubmedncbi", "PubMedNCBI","p","photocharles", "view", "View", "the", "biol","div","via", "image", "doi", "one", "classbackblock","dubinsky.pro","posted","news_180560", "analysis","nbspap","photocharl","dharapak","pimg", "srcbmimgcomuaberlinstoragenewsxabddbdbajpg", "alignleft", "nbspnbspnbsp", "href", "fieldnamebody","fieldtypetextwithsummary","title","datatype","fieldtypeimage","typeoffoafimage","www.globallookpress.com", "classcolorbox","fieldnamefieldimage","fieldtypetaxonomytermreference","rdfsseealso","relogimage","evenidfirstp", "sizesmaxwidth","wppostimage","sizedecosingle","styledisplayblock","classattachmentdecosingle","hrefhttpspolitekanet", "httpspolitekanetwpcontentuploadsefebimagexjpeg","httpspolitekanetwpcontentuploadsgettyimageskopiyaxjpg","replyua.net.так", "httpspolitekanetwpcontentuploadsunianxjpg","httpspolitekanetwpcontentuploadsgettyimagesxjpg","joomla","slavdelo.dn.ua", "classfielditems","odd", "classfielditem","fieldtypetext","stylewidth","classimage","classimageattachteaser","imageattachnode", "medium","tahomaarialhelveticasansserif","imagethumbnail","classimagecache","pxa", "fieldfieldnewslead","fieldfieldyandexnews", "srchttpinmediakitemscachedddddbbecbesjpg","srchttpsgoroddpuapicnewsnewsimagesmjpg","srchttpwwwkanzasuauploadpicresizejpg", "ampraquo","hrefhttpelvisticomnode","hrefhttpwwwgazetamistoteualajntranslyatsiyaforumudetsentralizatsiyaosnovaformuvannyanovoyisystemyupravlinnyatamistsevogorozvytku", "forklog","hidden","hrefhttpgiuauseridurlhttpsaffnewstutbyfeconomicsfhtml","lineheight","overflow","colorspan", "pxbbrspan","sizeb", "srcbmimgcomuaacommonimgicstarsemptyvioletgif","altimg","titleСЂР","hrefhttpvideobigmirnetuser","srchttpbmimgcomuavideoimgsxjpg", "table", "mediumspan","sansarialsansserifspan","langruruspan","classfooterinfosocialitemfollows","classfooterinfosocialitemiconspan", "hrefhttpwwwpravdacomuarusnews", "classfbcommentscount","що","который","которые","также","таким","новости","несмотря","в","на","и","не", "что","у","о","по","с","про","за","з","до","і","що","экс","об","этом","из","к","от","та","для","екс","це","его","а","как","politeka","он", "від","його","новости","это","твій","года","суті","при","під","после","того","через","будет","так","липня","том","уже","більше","як","все", "но","щодо","які","которые","то","2017","против","также","далее","новостей","він","своей","також","еще","перед","который","є","под","сути", "твой","знай","михаил","со","году","року","я","видео","проти","сил","із","сейчас","чтобы","dneprcity.net","же","й","может","над","или", "стало","было","може","тому","буде","те","был","быть","между","фото","112","який","ua","только","чем","является","ли","более","21", "26.07.17","без","було","вже","где","зі","ще","19","2018","laquo","мы","raquo","вона","кто","ми","своїй","ст","яких","были","ему","их", "наших","него","особо","очень","себе","щоб","де","ее","зараз","котором","сам","своем","теперь","цього","але","если","которая","себя", "тем","эти","https","больше","був","бути","два","навіщо","нас","таки", "тогда","replyua.net","будут","йому","між","можно","ним","новость", "п","ч","чи","12","50","mc","должен","им","именно","источник","которых","меньше","стал","эту","буду","має","стоит","требует","этот","11", "http","была","высокий","день","имеет","її","мог","несколько","них","она","этого","вони","всего","вся","когда","которым","одним","почти", "разі","стала","була","всі","вы","даже","дал","дать","кого","которое","м","нет","ни","новину","оборони","один","поки","потому","свою", "стали","таким","этой","яка","якому","яку","script","the","var","ей","новини","одно","понад","проте","серед","такий","чому","вот","дати","есть", "без", "більш", "більше", "буде", "начебто", "би", "був", "була", "були", "було", "бути", "вам", "вас", "адже", "увесь", "уздовж", "раптом", "замість", "поза", "униз", "унизу", "усередині", "в", "навколо", "от", "втім", "усі", "завжди", "усього", "усіх", "усю", "ви", "де", "так", "давай", "давати", "навіть", "для", "до", "досить", "інший", "його", "йому", "її", "її", "їй", "якщо", "є", "ще", "же", "за", "за винятком", "тут", "з", "через","або", "їм", "мати", "іноді", "їх", "якось", "хто", "коли", "крім", "хто", "куди", "чи", "або", "між", "мене", "мені", "багато", "може", "моє", "мої", "мій", "ми", "на", "назавжди", "над", "треба", "нарешті", "нас", "наш", "не", "його", "ні", "небудь", "ніколи", "їм", "їх", "нічого", "але", "ну", "про", "однак", "він", "вона", "вони", "воно", "знову", "від", "тому", "дуже", "перед", "по", "під", "після", "потім", "тому", "тому що", "майже", "при", "про", "раз", "хіба", "свою", "себе", "сказати", "з", "зовсім", "так", "також", "такі", "такий", "там", "ті", "тебе", "тем", "тепер", "те", "тоді", "того", "теж", "тієї", "тільки", "тому", "той", "отут", "ти", "уже", "хоч", "хоча", "чого", "чогось", "чий", "чому", "через", "що", "щось", "щоб", "ледве", "чиє", "чия", "ця", "ці", "це", "цю", "цього", "цьому", "цей","і","у","та","я","а","й","як","які","бо","із","який","тим","нам","б","всі","ж","яку","зі","яких","всіх","цим","1997","1991","1992","1998","2008", "2009","2010","2011","2012","2013","2014","2015","2016","2017","рік","все","роком","році","нехай","хай","року","яка","них","ним","1996","то")) ui <- dashboardPage(skin = "blue", title="Corestone ML", dashboardHeader( title="Corestone ML", tags$li(class = "dropdown", tags$a(href="http://corestone.expert/", target="_blank", tags$img(height = "20px", alt="Corestone", src="http://corestone.expert/static/icons/ic-navbar-logo.svg") ) ), dropdownMenuOutput("sys"), tags$li(class = "dropdown", tags$a(href = "https://github.com/RomanKyrychenko", target = "_blank", tags$img(height = "20px", src = "https://raw.githubusercontent.com/oraza/sectarianviolencePK/master/www/github.png") ) ) ), dashboardSidebar( sidebarMenu( menuItem("Topic modeling", tabName = "Infoflow", icon = icon("vcard-o")), #menuItem("System", tabName = "sys2", icon = icon("line-chart")), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), br(), hr(), menuItem("Documentation", icon = icon("file-text-o"), href = "https://github.com/RomanKyrychenko/digest/blob/master/README.md"), menuItem("Feedback & suggestion", icon = icon("envelope-o"), href = "mailto:?<EMAIL>?subject=Feedback on Corestone work tools app"), menuItem("Source code", icon = icon("file-code-o"), href = "https://github.com/RomanKyrychenko/digest"), menuItem("Fork me @ github", icon = icon("code-fork"), href = "https://github.com/RomanKyrychenko") ) ), dashboardBody( tabItems( tabItem(tabName = "Infoflow", h2("Topic modeling"), fileInput('file1', 'Завантажте файл з даними', accept = c(".xlsx",".xlsm")), numericInput("cluster","Кількість тем",200,min=2,max=1000), selectInput("var","Оберіть колонку з текстом","Текст","Текст"), selectInput("zag","Оберіть колонку із заголовком","Заголовок","Заголовок"), tags$hr(), downloadButton('down',"Завантажити результат") ) ) ) ) server <- function(input,output,server,session){ df2 <- reactive({ inFile <- input$file1 if(is.null(inFile)) return(NULL) file.rename(inFile$datapath, paste(inFile$datapath, ".xlsx", sep="")) readxl::read_excel(paste(inFile$datapath, ".xlsx", sep=""),col_names = T,sheet = 1) }) observe({ updateSelectInput( session, "var", choices=names(df2()), selected = "Текст") }) observe({ updateSelectInput( session, "zag", choices=names(df2()), selected = "Заголовок") }) df <- reactive({ tem <- df2() sped <- data_frame(second=c(7,10,19,33,63,123,12,22,44,81,159,301),k=c(5,10,20,40,80,160,5,10,20,40,80,160),size=c(2997,2997,2997,2997,2997,2997,5722,5722,5722,5722,5722,5722)) fit<-lm(second~k+size,data=sped) time <- predict(fit, data_frame(k=input$cluster,size=nrow(tem)), interval = "prediction")[1] progress <- Progress$new(session, min=1, max=21) on.exit(progress$close()) k <- input$cluster if(is.null(tem$URL_ID)) tem$URL_ID <- openssl::md5(tem[[input$var]]) progress$set(message = 'Старт аналізу', detail = 'Це займе деякий час...') it_train = itoken(text.clean(tem[[input$var]]), preprocessor = tolower, tokenizer = word_tokenizer, ids = tem$URL_ID, progressbar = T) progress$set(value = 1, detail="Текст оброблено") vocab = create_vocabulary(it_train,stopwords = stopwords, ngram = c(1L, 3L)) progress$set(value = 2, detail="Створено словник") pruned_vocab = prune_vocabulary(vocab, term_count_min = 2, doc_proportion_max = 0.5, doc_proportion_min = 0.00001) progress$set(value = 3, detail="Словник скорочено") vectorizer = vocab_vectorizer(pruned_vocab) progress$set(value = 4, detail="Векторизовано") dtm_train = create_dtm(it_train, vectorizer) progress$set(value = 5, detail="Створено матрицю слів-документів") lda_model = LDA$new(n_topics = k) progress$set(value = 6, detail="Задано параметри моделі") progress$set(value = 7, detail=paste("Обчислення моделі, час для приготування кави","(Орієнтовно",time%/%60,"хвилин",round(time%%60),"секунд)")) doc_topic_distr = lda_model$fit_transform(x = dtm_train, n_iter = 1000, convergence_tol = 0.00001, n_check_convergence = 25, progressbar = T) progress$set(value = 19, detail="Модель створено!") gammaDF <- as_tibble(doc_topic_distr) names(gammaDF) <- c(1:k) toptopics <- tibble(URL_ID = attr(doc_topic_distr,"dimnames")[[1]], Тема = as.numeric(apply(gammaDF,1,function(x) names(gammaDF)[which(x==max(x))][1])), `Рівень відповідності` = apply(gammaDF,1,max)) tem <- left_join(tem,toptopics,by="URL_ID") zag <- as.character(input$zag) slov <- left_join((tem %>% group_by(Тема) %>% summarise(`Рівень відповідності`=max(`Рівень відповідності`)[1])), (tem %>% select(input$zag, `Рівень відповідності`,Тема)),by=c("Рівень відповідності","Тема")) slov$theme2 <- slov[[input$zag]] slov <- slov %>% select(`Рівень відповідності`,Тема,theme2) tem <- left_join(tem,(slov[!duplicated(slov[,'Тема']),] %>% select(Тема,theme2)),by=c("Тема")) %>% select(-Тема) %>% rename("Тема"="theme2") progress$set(value = 20, detail="Масив створено, створення Excel") tem %>% mutate(Тема=ifelse(`Рівень відповідності`<0.15,"Потребує додаткової класифікації",Тема)) }) output$down <- downloadHandler( filename = function() {paste0("Topics_",input$cluster,"_",as.character(Sys.Date()), '.xlsx')}, content = function(file) { xlsx::write.xlsx(as.data.frame(df()), file, sheetName = "Теми", row.names = FALSE) } )} options(shiny.maxRequestSize=30*1024^2) options(shiny.trace=TRUE) shinyApp(ui,server) <file_sep>topicmodels2LDAvis <- function(x, ...){ post <- topicmodels::posterior(x) if (ncol(post[["topics"]]) < 3) stop("The model must contain > 2 topics") mat <- x@wordassignments LDAvis::createJSON( phi = post[["terms"]], theta = post[["topics"]], vocab = colnames(post[["terms"]]), doc.length = slam::row_sums(mat, na.rm = TRUE), term.frequency = slam::col_sums(mat, na.rm = TRUE) ) } lda %>% topicmodels2LDAvis() %>% LDAvis::serVis()<file_sep>Topic modeling ================ Модель ------ Система базується на моделі **LDA** (Latent Dirichlet Allocation). Конкретно реалізовано **WarpLDA** модель, яка дозволяє достатньо швидко зробити класифікацію текстів на велику кількість тем. Код базується на бібліотеці [text2vec](http://text2vec.org/). Векторне представлення слів пришвидшує обробку масивів. Альтернатива - робота з матрицями в рамках бібліотеки **tm**, однак у неї є недоліки: - більше використання ресурсів машини - некоректна робота з кирилицею Ядро ---- Основа моделі: ``` r library(tidyverse) library(stringr) library(text2vec) data("movie_review") it = itoken(movie_review$review, progressbar = FALSE, ids=movie_review$ids) v = create_vocabulary(it) %>% prune_vocabulary(doc_proportion_max = 0.1, term_count_min = 5) vectorizer = vocab_vectorizer(v) dtm = create_dtm(it, vectorizer) lda_model = LDA$new(n_topics = 10) doc_topic_distr = lda_model$fit_transform(x = dtm, n_iter = 1000, convergence_tol = 0.001, n_check_convergence = 25,progressbar = F) ``` ## INFO [2017-09-05 08:28:50] iter 25 loglikelihood = -3287623.371 ## INFO [2017-09-05 08:28:52] iter 50 loglikelihood = -3207258.004 ## INFO [2017-09-05 08:28:54] iter 75 loglikelihood = -3176885.052 ## INFO [2017-09-05 08:28:56] iter 100 loglikelihood = -3162532.061 ## INFO [2017-09-05 08:28:59] iter 125 loglikelihood = -3154170.709 ## INFO [2017-09-05 08:29:01] iter 150 loglikelihood = -3150266.555 ## INFO [2017-09-05 08:29:03] iter 175 loglikelihood = -3149750.609 ## INFO [2017-09-05 08:29:03] early stopping at 175 iteration ``` r gammaDF <- as_tibble(doc_topic_distr) names(gammaDF) <- c(1:10) data_frame(ID = attr(doc_topic_distr,"dimnames")[[1]], Тема = as.numeric(apply(gammaDF,1,function(x) names(gammaDF)[which(x==max(x))][1])), Відповідність = apply(gammaDF,1,max)) ``` ## # A tibble: 5,000 x 3 ## ID Тема Відповідність ## <chr> <dbl> <dbl> ## 1 1 5 0.2621951 ## 2 2 6 0.3750000 ## 3 3 4 0.2822086 ## 4 4 6 0.1826087 ## 5 5 4 0.2455090 ## 6 6 5 0.1600000 ## 7 7 4 0.2857143 ## 8 8 9 0.3018868 ## 9 9 3 0.2933333 ## 10 10 1 0.2222222 ## # ... with 4,990 more rows Вхідний файл ------------ На вхід береться таблиця Excel <file_sep>Sys.sleep(3600*1.5) library(stringr) library(topicmodels) library(tm) library(dplyr) library(elastic) library(RCurl) library(text2vec) library(gtools) #Define functions stopwords = unique(c("div", "href", "rel", "com", "relnofollow", "про", "что","dneprcity.net","novostimira.com","depo.ua","bbc.com", "для", "relnofollow", "alt", "zero","img", "alignleft", "hspace", "vspace","studic.info","description","delo.ua", "alignleft", "hspace", "vspace", "pbrp","altновини", "hrefhttpgsfmopinionhtml", "mode","strong", "pstrong", "targetblank", "styletext-align", "justifi","altнапк", "classattachment-decosingl", "classreadmor","http:img.ura","pigua.info", "ethereum", "hrefhttpresonanceua", "hrefhttpsinforesistorg","replyua.net","newsoboz.org","mc.async","manabalss.lv", "hrefhttpblogiuaus", "hrefhttpvycherpnockua", "hrefhttpwwwkmugovuacontrolukpublisharticleartidampcatid","mid.ru", "noneimg", "solid", "start", "stylefont-s", "stylefloat", "classfield-item","cackle.me","container","dtp.kiev.ua", "classfield", "classfield-itemsdiv", "field-label-hiddendiv", "hrefhttpwwwaddthiscombookmarkphpv","replyua.netпро", "srcbmimgcomuaberlinstoragefinancexebfcbeadfdeccjpg","cackle_widget.push","document.createelement","polytics","loading", "eff", "i","classfield-item", "classfield", "classfield-itemsdiv", "field-label-hiddendiv", "datatyp","i.lb.ua", "propertyrdfslabel", "datatyp", "propertyrdfslabel", "skospreflabel", "typeofskosconcept","mc.src","erve.ua","www.pravda.com.ua", "reldcsubjecta", "classfield-tag", "field-type-taxonomy-term-refer","document.createelement","mc.type","lb.ua", "classimagecach", "classlink", "classrtejustifyspan", "classtranslation-link", "classtranslationru","goo.gl","newsru.co.il", "clearfixdiv", "data-colorbox-gallerygallery-node--ytzaljghei","document.getelementbyid","javascript","mon.gov.ua", "propertyrdfslabel", "skospreflabel","этом","это","які","від","datatyp","-tag","function","innerhtml","sevastopolnews.info", "hrefhttpkorupciyacom", "дуже", "там", "так", "але","span", "width", "classleftimgimg", "stylecolor", "stylefont-famili", "hspace", "vspace", "clearal","classback-block","tabletrtd", "valigntop","document.location.protocol","zakarpatpost.net", "hrefhttpwwwaddthiscombookmarkphpv", "even", "как", "titl","document.getelementsbytagname","text","true","sport.ua", "sea", "black", "hold", "one","stylemargin", "color", "outlin", "pad", "none","nbsp","widget.js","www.unian.net", "centerspan", "size", "stylefont-s", "font-siz", "divfont","s.nextsibling","s.parentnode.insertbefore","www.ukrinform.ru", "justifi", "center", "width", "height", "classfeed-descriptionp","window.cackle_widget","xcoal","politics","newsru.co.il", "pimg", "wp-post-imag", "margin", "sizesmax-width","justifystrong","joinfo.ua","1news","journal","unn.com.ua","newsonline24", "srchttpimageunncomuaoriginaljpg", "altновости", "centerimg","styletextalign","stylefontsize","justify","fontsize","padding", "helvetica","laquoР","raquo","httpnovostimiracomnewshtml","hrefhttprkrinuauploadspostsmatigeroyinyajpg","news_180574", "hrefhttpskeletinfoorg","pem","leaders","hstrong","development","religious","targetblankstrong","politico","news_180572", "che","glucosio","person","primarily","hrefhttpskeletinfoorg","classmetanav","clearall","newsoboz","politika","news_180571", "stylefontfamily","arial","fontfamily","outline","sansserif","textalign","border","inherit","left","pspan","naviny.by", "justifyspan","rgb","styleboxsizing","small","googleadsectionend","womenbox.net","arianespace","polityka","porfyrios", "classfielditem","classfielditemsdiv","fieldlabelhiddendiv", "also", "article", "Article","cellpadding","finanso.net", "download", "google", "figure","fig", "groups","Google", "however","high", "human", "levels","alt","feed","image","src","http", "jpg", "larger", "may", "number","class","новости","gazeta.ua","rossii.html","zn.ua","cellspacing","portal", "shown", "study", "studies", "this","img","using", "two", "the", "Scholar","pubmedncbi", "PubMedNCBI","p","photocharles", "view", "View", "the", "biol","div","via", "image", "doi", "one", "classbackblock","dubinsky.pro","posted","news_180560", "analysis","nbspap","photocharl","dharapak","pimg", "srcbmimgcomuaberlinstoragenewsxabddbdbajpg", "alignleft", "nbspnbspnbsp", "href", "fieldnamebody","fieldtypetextwithsummary","title","datatype","fieldtypeimage","typeoffoafimage","www.globallookpress.com", "classcolorbox","fieldnamefieldimage","fieldtypetaxonomytermreference","rdfsseealso","relogimage","evenidfirstp", "sizesmaxwidth","wppostimage","sizedecosingle","styledisplayblock","classattachmentdecosingle","hrefhttpspolitekanet", "httpspolitekanetwpcontentuploadsefebimagexjpeg","httpspolitekanetwpcontentuploadsgettyimageskopiyaxjpg","replyua.net.так", "httpspolitekanetwpcontentuploadsunianxjpg","httpspolitekanetwpcontentuploadsgettyimagesxjpg","joomla","slavdelo.dn.ua", "classfielditems","odd", "classfielditem","fieldtypetext","stylewidth","classimage","classimageattachteaser","imageattachnode", "medium","tahomaarialhelveticasansserif","imagethumbnail","classimagecache","pxa", "fieldfieldnewslead","fieldfieldyandexnews", "srchttpinmediakitemscachedddddbbecbesjpg","srchttpsgoroddpuapicnewsnewsimagesmjpg","srchttpwwwkanzasuauploadpicresizejpg", "ampraquo","hrefhttpelvisticomnode","hrefhttpwwwgazetamistoteualajntranslyatsiyaforumudetsentralizatsiyaosnovaformuvannyanovoyisystemyupravlinnyatamistsevogorozvytku", "forklog","hidden","hrefhttpgiuauseridurlhttpsaffnewstutbyfeconomicsfhtml","lineheight","overflow","colorspan", "pxbbrspan","sizeb", "srcbmimgcomuaacommonimgicstarsemptyvioletgif","altimg","titleСЂР","hrefhttpvideobigmirnetuser","srchttpbmimgcomuavideoimgsxjpg", "table", "mediumspan","sansarialsansserifspan","langruruspan","classfooterinfosocialitemfollows","classfooterinfosocialitemiconspan", "hrefhttpwwwpravdacomuarusnews", "classfbcommentscount","що","который","которые","также","таким","новости","несмотря","в","на","и","не", "что","у","о","по","с","про","за","з","до","і","що","экс","об","этом","из","к","от","та","для","екс","це","его","а","как","politeka","он", "від","його","новости","это","твій","года","суті","при","під","после","того","через","будет","так","липня","том","уже","більше","як","все", "но","щодо","які","которые","то","2017","против","также","далее","новостей","він","своей","також","еще","перед","который","є","под","сути", "твой","знай","михаил","со","году","року","я","видео","проти","сил","із","сейчас","чтобы","dneprcity.net","же","й","может","над","или", "стало","было","може","тому","буде","те","был","быть","между","фото","112","який","ua","только","чем","является","ли","более","21", "26.07.17","без","було","вже","где","зі","ще","19","2018","laquo","мы","raquo","вона","кто","ми","своїй","ст","яких","были","ему","их", "наших","него","особо","очень","себе","щоб","де","ее","зараз","котором","сам","своем","теперь","цього","але","если","которая","себя", "тем","эти","https","больше","був","бути","два","навіщо","нас","таки","тогда","replyua.net","будут","йому","між","можно","ним","новость", "п","ч","чи","12","50","mc","должен","им","именно","источник","которых","меньше","стал","эту","буду","має","стоит","требует","этот","11", "http","была","высокий","день","имеет","її","мог","несколько","них","она","этого","вони","всего","вся","когда","которым","одним","почти", "разі","стала","була","всі","вы","даже","дал","дать","кого","которое","м","нет","ни","новину","оборони","один","поки","потому","свою", "стали","таким","этой","яка","якому","яку","script","the","var","ей","новини","одно","понад","проте","серед","такий","чому","вот","дати","есть", "без", "більш", "більше", "буде", "начебто", "би", "був", "була", "були", "було", "бути", "вам", "вас", "адже", "увесь", "уздовж", "раптом", "замість", "поза", "униз", "унизу", "усередині", "в", "навколо", "от", "втім", "усі", "завжди", "усього", "усіх", "усю", "ви", "де", "так", "давай", "давати", "навіть", "для", "до", "досить", "інший", "його", "йому", "її", "її", "їй", "якщо", "є", "ще", "же", "за", "за винятком", "тут", "з", "через","або", "їм", "мати", "іноді", "їх", "якось", "хто", "коли", "крім", "хто", "куди", "чи", "або", "між", "мене", "мені", "багато", "може", "моє", "мої", "мій", "ми", "на", "назавжди", "над", "треба", "нарешті", "нас", "наш", "не", "його", "ні", "небудь", "ніколи", "їм", "їх", "нічого", "але", "ну", "про", "однак", "він", "вона", "вони", "воно", "знову", "від", "тому", "дуже", "перед", "по", "під", "після", "потім", "тому", "тому що", "майже", "при", "про", "раз", "хіба", "свою", "себе", "сказати", "з", "зовсім", "так", "також", "такі", "такий", "там", "ті", "тебе", "тем", "тепер", "те", "тоді", "того", "теж", "тієї", "тільки", "тому", "той", "отут", "ти", "уже", "хоч", "хоча", "чого", "чогось", "чий", "чому", "через", "що", "щось", "щоб", "ледве", "чиє", "чия", "ця", "ці", "це", "цю", "цього", "цьому", "цей","і","у","та","я","а","й","як","які","бо","із","який","тим","нам","б","всі","ж","яку","зі","яких","всіх","цим","1997","1991","1992","1998","2008", "2009","2010","2011","2012","2013","2014","2015","2016","2017","рік","все","роком","році","нехай","хай","року","яка","них","ним","1996","то")) q = '{ "query": { "bool": { "must": [ { "exists": { "field": "target" } } ] } } }' es <- "192.168.127.12:9200" result_date <- gsub("-","",as.character(Sys.Date()-1)) csv_to_json <- function(dat, pretty = F,na = "null",raw = "mongo",digits = 3,force = "unclass"){ dat_to_json <- jsonlite::toJSON(dat,pretty = pretty,na = "null",raw = raw,digits = digits ,force = force ) dat_to_json=substr(dat_to_json,start = 2,nchar(dat_to_json)-1) return(dat_to_json) } text.clean = function(x){ require("tm") x = gsub("<.*?>", " ", x) x = removeNumbers(x) x = removeWords(x, stopwords("english")) x = removeWords(x, stopwords("russian")) x = removeWords(x, stopwords) x = stemDocument(x,language="russian") x = stripWhitespace(x) x = gsub("^\\s+|\\s+$", "", x) x = removePunctuation(x) return(x) } download_elastic <- function(result_date,q){ res <- Search(index = paste0("urls_",result_date), body=q , type = 'news',source = paste("title","fullhtml",sep=",") ,scroll = "1m") out <- res$hits$hits hits <- 1 while(hits != 0){ res <- scroll(scroll_id = res$`_scroll_id`) hits <- length(res$hits$hits) if(hits > 0) out <- c(out, res$hits$hits) } as_tibble(do.call("smartbind",lapply(out,function(x) as.data.frame(x,stringsAsFactors=F)))) } train_lda <- function(tem,k){ it_train = itoken(text.clean(tem$X_source.fullhtml), preprocessor = tolower, ids = tem$X_id, progressbar = T) vocab = create_vocabulary(it_train,stopwords = stopwords, ngram = c(1L, 3L)) pruned_vocab = prune_vocabulary(vocab, term_count_min = 5, doc_proportion_max = 0.5, doc_proportion_min = 0.001) vectorizer = vocab_vectorizer(pruned_vocab) dtm_train = create_dtm(it_train, vectorizer) lda_model = LDA$new(n_topics = k) doc_topic_distr = lda_model$fit_transform(x = dtm_train, n_iter = 2000, convergence_tol = 0.00001, n_check_convergence = 25, progressbar = T) gammaDF <- as_tibble(doc_topic_distr) names(gammaDF) <- c(1:k) toptopics <- tibble(X_id = attr(doc_topic_distr,"dimnames")[[1]], theme = as.numeric(apply(gammaDF,1,function(x) names(gammaDF)[which(x==max(x))][1])), theme_quality = apply(gammaDF,1,max)) tem <- left_join(tem,toptopics,by="X_id") slov <- left_join((tem %>% group_by(theme) %>% summarise(theme_quality=max(theme_quality)[1])),tem[c(6:8)],by=c("theme_quality","theme")) %>% rename("theme2"="X_source.title") left_join(tem,(slov[!duplicated(slov[,'theme']),] %>% select(theme,theme2)),by=c("theme")) %>% select(-theme) %>% rename("theme"="theme2") } #Run code print(paste("Start connection",Sys.time())) connect(es_host = "192.168.127.12", es_port = 9200) print(paste("Start download",Sys.time())) out_df <- download_elastic(result_date,q) print(paste("Downloaded",Sys.time())) try(httpPUT(paste(es, paste0("urls_",result_date),"news","theme",sep="/"), csv_to_json(data.frame(dt=paste0(substr(as.character(Sys.time()),1,10),"T",substr(as.character(Sys.time()),12,20),"+0300"))))) startdate=paste0(substr(as.character(Sys.time()),1,10),"T",substr(as.character(Sys.time()),12,20),"+0300") print(paste("Start training",Sys.time())) out_df2 <- train_lda(out_df,nrow(out_df)/5) gc() print(paste("Trained",Sys.time())) names(out_df2) <- c("_index","_type","_id","_score","title","fullhtml","theme_quality","theme") print(paste("Start writing",Sys.time())) con<-file(paste0("OU",result_date,".json"),open = 'a',encoding="UTF-8") for(i in 1:nrow(out_df2)){ write(print(paste0('{"update": {"_id": "',out_df2[i,3],'", "_type" : "news", "_index" : "', out_df2[i,1],'"}}\n{"doc": {"theme": "',str_replace_all(gsub("|","", str_replace_all(out_df2[i,8], "[[:punct:]]", "")), "[\r\n]" , ""),'", "theme_quality": ',as.numeric(out_df2[i,7]),'}}')),file=con, append=TRUE) } print(paste("Start bulking",Sys.time())) closeAllConnections() res <- withRestarts(docs_bulk(paste0("OU",result_date,".json"))) httpPUT(paste(es, paste0("urls_",result_date),"news","theme",sep="/"), csv_to_json(data.frame(dt=startdate, dtpost=paste0(substr(as.character(Sys.time()),1,10),"T",substr(as.character(Sys.time()),12,20),"+0300")))) print(paste("Bulked!",Sys.time()))
aa1e69a3fec5833d996f5158a878670f5614781b
[ "Markdown", "R" ]
4
R
RomanKyrychenko/topicmodels
47defc4178dc5541e7a5884f6f252fd69eb2cac5
8173190ffc880f4ae21e8968ca122431929c2ea4
refs/heads/main
<repo_name>felipepassagem/project3-djangoapp-surgerys<file_sep>/ccip/models.py from django.db import models from django.db.models.fields import CharField, DateTimeField, DateField import datetime from django.contrib.postgres.fields import ArrayField from django.contrib.auth.models import User from django.utils import timezone # Create your models here. class Implant(models.Model): imp =[] sizes = ['4x5', '4x6', '5x5', '5x6', '6x5','6x6','3.5x8','3.5x10','3.5x11.5','3.5x13','3.5x15','4.3x8','4.3x10','4.3x11.5','4.3x13','4.3x15'] types = ['Neodent Alvim CM', 'Neodent Drive CM', 'Neodent Titamax WS CM', 'Nobel Replace CM', 'SIN SWC CM', 'SIN Strong CM', 'SIN Unitite CM'] SIZE_CHOICES = [] TYPE_CHOICES = [] for size in sizes: SIZE_CHOICES.append((str(size), str(size))) for type in types: TYPE_CHOICES.append((str(type), str(type))) user = models.ForeignKey(User, default=None, on_delete=models.CASCADE) size = models.CharField(max_length=30, choices=SIZE_CHOICES, default='3.5x8', unique=False) type = models.CharField(max_length=60, choices=TYPE_CHOICES, default='Neodent Alvim CM 3.5x8', unique=False) quantity = models.IntegerField(default=1, blank=False ) def __str__(self): return str(self.type + ' ' + self.size) class Client(models.Model): gender_choices = [('Masculino', 'Masculino'),('Feminino', 'Feminino'), ('Outro', 'Outro')] user = models.ForeignKey(User, default=None, on_delete=models.CASCADE) full_name = models.CharField(max_length=80, null=False) birth_date = models.DateField(blank=True, null=True) phone = models.CharField(max_length=20, blank=True, null=True) obs = models.TextField(max_length=1000, blank=True) gender = models.CharField(max_length=50, blank=True, choices=gender_choices) def __str__(self): return str(self.full_name) class Surgery(models.Model): imp =[] sizes = ['3.5x8','3.5x10','3.5x11.5','3.5x13','3.5x15','4.3x8','4.3x10','4.3x11.5','4.3x13','4.3x15'] SIZE_CHOICES = [] types = ['Neodent Alvim CM', 'Neodent Drive CM','Neodent Titamax WS CM', 'SIN SWC CM', 'SIN Strong CM', 'SIN Unitite CM'] TYPE_CHOICES= [] for type in types: TYPE_CHOICES.append((str(type), str(type))) for tipo in types: for size in sizes: impl = tipo + ' ' + size imp.append(impl) implantes = [] for i in imp: impla = (str(i), str(i)) implantes.append(impla) areaList = [] ini = 11 for i in range(11, 48): if i not in [19,20,29,30,39,40]: areaList.append((i, i)) areas = map(tuple, areaList) for size in sizes: SIZE_CHOICES.append((str(size), str(size))) STAGE = { ('Espera', 'Espera'), ('Andamento', 'Andamento'), ('Finalizado', 'Finalizado'), } PMU = { ('Unitária', 'Unitária'), ('Múltipla', 'Múltipla'), ('Protocolo', 'Protocolo'), } today = datetime.date.today() date = today.strftime("%d/%m/%y") user = models.ForeignKey(User, default=None, on_delete=models.CASCADE) client = models.ForeignKey(Client, null=True, on_delete=models.SET_NULL) date = models.DateField( auto_now=False, default=date) quantity = models.PositiveIntegerField(default=0) implant_type = ArrayField(models.CharField(max_length=50, choices=TYPE_CHOICES)) implant_size = ArrayField(models.CharField(max_length=50, choices=SIZE_CHOICES)) area = ArrayField(models.CharField(max_length=50, choices=areaList)) obs = models.TextField(blank=True, max_length=600) stage = models.CharField(max_length=50, choices=STAGE, default='Espera') pmu = models.CharField(max_length=20, choices=PMU, default='Unitária') def __str__(self): return str(self.client) # #prot = models.BooleanField(default=False)<file_sep>/ccip/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('quant', views.quant, name="quant"), path('add_surgery', views.add_surgery, name="add_surgery"), path('update_surgery/<surgery_id>', views.update_surgery, name="update_surgery"), path('add_implant', views.add_implant, name="add_implant"), path('stock', views.stock, name="stock"), path('delete_implant/<int:implant_id>', views.delete_implant, name="delete_implant"), path('update_implant/<int:implant_id>', views.update_implant, name="update_implant"), path('delete_surgery/<int:surgery_id>', views.delete_surgery, name="delete_surgery"), path('add_client', views.add_client, name="add_client"), path('client_list', views.client_list, name="client_list"), path('delete_client/<int:client_id>', views.delete_client, name="delete_client"), path('update_client/<int:client_id>', views.update_client, name="update_client"), ]<file_sep>/ccip/admin.py from django.contrib import admin from .models import * # Register your models here. class DisplayImplant(admin.ModelAdmin): list_display = ('id', 'type', 'size', 'quantity') list_display_links = ('id', 'type', 'size') search_fields = ('id','type', 'size') list_per_page = (10) class DisplaySurgery(admin.ModelAdmin): list_display = ('id', 'client', 'user') list_display_links = ('id', 'client', 'user') search_fields = ('id',) list_per_page = (10) class DisplayClient(admin.ModelAdmin): list_display = ('id', 'full_name', 'phone') list_display_links = ('id', 'full_name') search_fields = ('id', 'user') list_per_page = (10) admin.site.register(Implant, DisplayImplant) admin.site.register(Surgery, DisplaySurgery) admin.site.register(Client, DisplayClient)<file_sep>/ccip/migrations/0009_auto_20210628_1959.py # Generated by Django 3.2.4 on 2021-06-28 22:59 import django.contrib.postgres.fields from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('ccip', '0008_alter_surgery_stage'), ] operations = [ migrations.AddField( model_name='client', name='gender', field=models.CharField(blank=True, choices=[('Masculino', 'Masculino'), ('Feminino', 'Feminino')], max_length=50), ), migrations.AddField( model_name='surgery', name='prot', field=models.BooleanField(default=False), ), migrations.AlterField( model_name='implant', name='size', field=models.CharField(choices=[('4x5', '4x5'), ('4x6', '4x6'), ('5x5', '5x5'), ('5x6', '5x6'), ('6x5', '6x5'), ('6x6', '6x6'), ('3.5x8', '3.5x8'), ('3.5x10', '3.5x10'), ('3.5x11.5', '3.5x11.5'), ('3.5x13', '3.5x13'), ('3.5x15', '3.5x15'), ('4.3x8', '4.3x8'), ('4.3x10', '4.3x10'), ('4.3x11.5', '4.3x11.5'), ('4.3x13', '4.3x13'), ('4.3x15', '4.3x15')], default='3.5x8', max_length=30), ), migrations.AlterField( model_name='implant', name='type', field=models.CharField(choices=[('Neodent Alvim CM', 'Neodent Alvim CM'), ('Neodent Drive CM', 'Neodent Drive CM'), ('Neodent Titamax WS CM', 'Neodent Titamax WS CM'), ('SIN SWC CM', 'SIN SWC CM'), ('SIN Strong CM', 'SIN Strong CM'), ('SIN Unitite CM', 'SIN Unitite CM')], default='Neodent Alvim CM 3.5x8', max_length=60), ), migrations.AlterField( model_name='surgery', name='date', field=models.DateField(default='28/06/21'), ), migrations.AlterField( model_name='surgery', name='implant_type', field=django.contrib.postgres.fields.ArrayField(base_field=models.CharField(choices=[('Neodent Alvim CM', 'Neodent Alvim CM'), ('Neodent Drive CM', 'Neodent Drive CM'), ('Neodent Titamax WS CM', 'Neodent Titamax WS CM'), ('SIN SWC CM', 'SIN SWC CM'), ('SIN Strong CM', 'SIN Strong CM'), ('SIN Unitite CM', 'SIN Unitite CM')], max_length=50), size=None), ), migrations.AlterField( model_name='surgery', name='stage', field=models.CharField(choices=[('Andamento', 'Andamento'), ('Espera', 'Espera'), ('Finalizado', 'Finalizado')], default='Espera', max_length=50), ), ] <file_sep>/ccip/migrations/0012_auto_20210707_1701.py # Generated by Django 3.2.4 on 2021-07-07 20:01 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('ccip', '0011_auto_20210628_2215'), ] operations = [ migrations.AlterField( model_name='implant', name='type', field=models.CharField(choices=[('Neodent Alvim CM', 'Neodent Alvim CM'), ('Neodent Drive CM', 'Neodent Drive CM'), ('Neodent Titamax WS CM', 'Neodent Titamax WS CM'), ('Nobel Replace CM', 'Nobel Replace CM'), ('SIN SWC CM', 'SIN SWC CM'), ('SIN Strong CM', 'SIN Strong CM'), ('SIN Unitite CM', 'SIN Unitite CM')], default='Neodent Alvim CM 3.5x8', max_length=60), ), migrations.AlterField( model_name='surgery', name='date', field=models.DateField(default='07/07/21'), ), migrations.AlterField( model_name='surgery', name='pmu', field=models.CharField(choices=[('Múltipla', 'Múltipla'), ('Unitária', 'Unitária'), ('Protocolo', 'Protocolo')], default='Unitária', max_length=20), ), migrations.AlterField( model_name='surgery', name='stage', field=models.CharField(choices=[('Espera', 'Espera'), ('Andamento', 'Andamento'), ('Finalizado', 'Finalizado')], default='Espera', max_length=50), ), ] <file_sep>/ccip/migrations/0004_alter_surgery_stage.py # Generated by Django 3.2.4 on 2021-06-04 21:20 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('ccip', '0003_auto_20210604_1818'), ] operations = [ migrations.AlterField( model_name='surgery', name='stage', field=models.CharField(choices=[('Espera', 'Espera'), ('Andamento', 'Andamento'), ('Finalizado', 'Finalizado')], default='Espera', max_length=50), ), ] <file_sep>/busers/views.py from django.shortcuts import render, redirect from django.contrib.auth.models import User from django.contrib import auth, messages from django.contrib.auth.decorators import login_required from django.conf import settings # Create your views here. def register(request): if request.method == 'POST': username = request.POST["username"] email = request.POST["email"] password = request.POST["password"] confirmation = request.POST["confirmation"] emails = [] emails.append(list(User.objects.filter(email=email))) if is_null(username): messages.error(request, 'Nome de Usuário Inválido.') return redirect('register') if is_null(password): messages.error(request, 'Senha Invalida.') return redirect('register') if password != confirmation: messages.error(request, 'As senhas precisam ser iguais.') return redirect('register') if User.objects.filter(email=email).exists(): messages.error(request, 'Usuário já cadastrado.') return redirect('register') user = User.objects.create_user(username=username, password=<PASSWORD>, email=email) user.save() messages.success(request, "Cadastro realizado com sucesso!") return redirect('login') else: auth.logout(request) return render(request, 'busers/register.html') def login(request): if request.method == "GET": auth.logout(request) return render(request, 'busers/login.html') if request.method == 'POST': email = request.POST['email'] password = request.POST['password'] if email == "" or password =="": messages.error(request, "Usuário ou senha inválidos!") return redirect('/login') if User.objects.filter(email=email).exists(): name = User.objects.filter(email=email).values_list('username', flat=True) user = auth.authenticate(request, username=name[0], password=<PASSWORD>) if user is not None: auth.login(request, user) return redirect('index') else: return render(request, 'busers/login.html') def logout(request): auth.logout(request) #messages("Usuário Deslogado!") return redirect('login') def is_null(field): return not field.strip()<file_sep>/dashboard/views.py from django.shortcuts import render from ccip.forms import ClientForm, ImplantForm, SurgeryForm from django.shortcuts import render from django.shortcuts import render, redirect, get_object_or_404, HttpResponseRedirect from django.contrib.auth.models import User from django.contrib import auth, messages from django.contrib.auth.decorators import login_required from django.conf import settings from ccip.models import * from collections import Counter, OrderedDict from .fusioncharts import FusionCharts from datetime import datetime, timedelta, date # Create your views here. def dashboard(request): if not request.user.is_authenticated: return render(request, 'busers/register.html') else: u_email = User.objects.filter(pk = request.user.id).values_list('email', flat=True)[0] user = get_object_or_404(User, pk=request.user.id) test = Surgery.objects.values_list('date').filter(user = user).order_by('date') if test: first_surg_dates = Surgery.objects.values_list('date').filter(user = user).order_by('date')[0] first_surg_date = first_surg_dates[0].strftime('%Y-%m-%d') else: first_surg_dates = date.today() first_surg_date = first_surg_dates.strftime('%Y-%m-%d') size_type_list = [] type_list = [] size_list = [] all_sizes = [] all_types = [] if request.method == "GET": sizes = Surgery.objects.all().filter(user = user) surgerys = Surgery.objects.all().filter(user = user).order_by("-date") else: if request.POST['date_a'] < first_surg_date: try: surgerys = Surgery.objects.all().filter(user = user, date__range=(first_surg_date, request.POST['date_z'])).order_by("-date") sizes = Surgery.objects.all().filter(user = user, date__range=(first_surg_date, request.POST['date_z'])).order_by("-date") except: return redirect('index') elif request.POST['date_a'] and request.POST['date_a'] != "": try: surgerys = Surgery.objects.all().filter(user = user, date__range=(request.POST['date_a'], request.POST['date_z'])).order_by("-date") sizes = Surgery.objects.all().filter(user = user, date__range=(request.POST['date_a'], request.POST['date_z'])).order_by("-date") except: return redirect('index') elif request.POST['date_a'] >= request.POST['date_z']: try: surgerys = Surgery.objects.all().filter(user = user, date__range=(request.POST['date_z'], request.POST['date_a'])).order_by("-date") sizes = Surgery.objects.all().filter(user = user, date__range=(request.POST['date_z'], request.POST['date_a'])).order_by("-date") except: return redirect('index') else: try: sizes = Surgery.objects.all().filter(user = user) surgerys = Surgery.objects.all().filter(user = user).order_by("-date") except: return redirect('index') for i in sizes: all_sizes.extend(i.implant_size) all_types.extend(i.implant_type) imp_dict = dict(Counter(all_sizes)) type_dict = dict(Counter(all_types)) sizes = sorted(imp_dict.items(), key=lambda x: x[1], reverse=True) types = sorted(type_dict.items(), key=lambda x: x[1], reverse=True) size_chart_col = get_size_chart(sizes[0:6])[0] size_chart_pie = get_size_chart(sizes[0:6])[1] type_chart_pie = get_type_chart(types[0:6])[0] type_chart_col = get_type_chart(types[0:6])[1] for surgery in surgerys: type_list.extend(surgery.implant_type) size_list.extend(surgery.implant_size) if len(type_list) == len(size_list): for i in range(len(type_list)): size_type_list.append(str(type_list[i]) + " " + str(size_list[i])) size_type_dict = dict(Counter(size_type_list)) size_type_sorted = sorted(size_type_dict.items(), key=lambda x: x[1], reverse=True) else: size_type_sorted = [] n_surg = len(surgerys) n = 0 for i in range(n_surg): n += surgerys[i].quantity if n > 0: ratio = n / n_surg else: ratio = 0 area_list = [] for surgery in surgerys: area_list.extend(surgery.area) area_list_counter = dict(Counter(area_list)) area_list_sorted = sorted(area_list_counter.items(), key=lambda x: x[1], reverse=True) month_lists = [] for surgery in surgerys: month_number = str(surgery.date.month) datetime_object = datetime.strptime(month_number, "%m") month_name = datetime_object.strftime("%b") month_lists.append(month_name) month_list_a = dict(Counter(month_lists)) month_list = sorted(month_list_a.items(), key=lambda x: x[1], reverse=True) ages = [] gender = [] ages_ratio = 0 date_format = "%Y-%m-%d" for surgery in surgerys: date_a = datetime.strptime(str(surgery.client.birth_date), date_format ) date_b = datetime.strptime(str(surgery.date), date_format) age = (date_b - date_a) ages.append(int(age.days/365)) ages_ratio = int(sum(ages) / len(ages)) if ages_ratio > 0: ages_ratio = ages_ratio elif ages_ratio == None: ages_ratio = 0 else: ages_ratio = 0 gender.append(surgery.client.gender) genderss = dict(Counter(gender)) genders = sorted(genderss.items(), key=lambda x: x[1], reverse=True) pmus = [] for surgery in surgerys: pmus.append(surgery.pmu) pmu_counted = dict(Counter(pmus)) pmu_sorted = sorted(pmu_counted.items(), key=lambda x: x[1], reverse=True) pmu_chart_col = get_pmu_chart(pmu_sorted)[0] pmu_chart_pie = get_pmu_chart(pmu_sorted)[1] size_type_chart_col = get_individual_chart(size_type_sorted[0:10])[0] size_type_chart_pie = get_individual_chart(size_type_sorted[0:10])[1] month_chart_col = get_month_chart(month_list)[0] month_chart_pie = get_month_chart(month_list)[1] area_chart_col = get_area_chart(area_list_sorted[0:5])[0] area_chart_pie = get_area_chart(area_list_sorted[0:5])[1] gender_chart_col = get_gender_chart(genders)[0] gender_chart_pie = get_gender_chart(genders)[1] #age_chart_col = get_age_chart(ages) dates = [] surg_dates = Surgery.objects.values_list('date').filter(user = user).order_by('date') for surgery in surgerys: dates.append(surgery.date) print(dates) if dates == []: ini_date = " " final_date = " " elif len(dates) == 1: ini_date = dates[0].strftime('%d/%m/%Y') final_date = dates[1].strftime('%d/%m/%Y') else: print('aqui') dates.sort() ini_date = dates[0].strftime('%d/%m/%Y') final_date = dates[len(dates) - 1].strftime('%d/%m/%Y') return render(request, 'dashboard/dashboard.html', {'size_chart_pie': size_chart_pie.render(), 'size_chart_col': size_chart_col.render(), 'type_chart_pie': type_chart_pie.render(), 'type_chart_col': type_chart_col.render(), 'size_type_chart_col': size_type_chart_col.render(), 'size_type_chart_pie': size_type_chart_pie.render(), 'ratio': round(ratio, 2), 'n': n, 'n_surg': n_surg, 'area_chart_col': area_chart_col.render(), 'area_chart_pie': area_chart_pie.render(), 'month_chart_col': month_chart_col.render(), 'month_chart_pie': month_chart_pie.render(), 'ages_ratio': ages_ratio, 'gender_chart_col': gender_chart_col.render(), 'gender_chart_pie': gender_chart_pie.render(), 'pmu_chart_col': pmu_chart_col.render(), 'pmu_chart_pie': pmu_chart_pie.render(), 'ini_date': ini_date, 'final_date': final_date, 'u_email': u_email, }) def get_pmu_chart(pmu_sorted): dataSource0 = OrderedDict() chartConfig0 = OrderedDict() chartConfig0 = OrderedDict() chartConfig0["palettecolors"] = "3C7EDD, 1FD826,E7E422,E74C22,CC4ADE,EAA829,56DFF1,E463CD" chartConfig0["caption"] = "Tipo de Reabilitação" chartConfig0["subCaption"] = "" chartConfig0["xAxisName"] = "Tipo" chartConfig0["yAxisName"] = "Quantidade" chartConfig0["numberSuffix"] = "" chartConfig0["theme"] = "fusion" dataSource0["data"] = [] for k, v in pmu_sorted: dataSource0['data'].append({"label":'{}'.format(k), "value": '{}'.format(v)} ) dataSource0["chart"] = chartConfig0 pmu_chart_pie = FusionCharts("pie2d", "pmu_chart_pie", "100%", "350", "pmu_chart_pie-container", "json", dataSource0) pmu_chart_col = FusionCharts("column2d", "pmu_chart_col", "100%", "350", "pmu_chart_col-container", "json", dataSource0) return pmu_chart_pie, pmu_chart_col def get_month_chart(month_list): dataSource0 = OrderedDict() chartConfig0 = OrderedDict() chartConfig0 = OrderedDict() chartConfig0["palettecolors"] = "3C7EDD, 1FD826,E7E422,E74C22,CC4ADE,EAA829,56DFF1,E463CD" chartConfig0["caption"] = "Meses com Maior Incidência de Cirurgias" chartConfig0["subCaption"] = "" chartConfig0["xAxisName"] = "Mês" chartConfig0["yAxisName"] = "Quantidade" chartConfig0["numberSuffix"] = "" chartConfig0["theme"] = "fusion" chartConfig0["chartType"] = "column2d,pie2d" dataSource0["data"] = [] for k, v in month_list: dataSource0['data'].append({"label":'{}'.format(k), "value": '{}'.format(v)} ) dataSource0["chart"] = chartConfig0 month_chart_col = FusionCharts("column2d", "month_chart_col", "100%", "350", "month_chart_col-container", "json", dataSource0) month_chart_pie = FusionCharts("pie2d", "month_chart_pie", "100%", "350", "month_chart_pie-container", "json", dataSource0) return month_chart_col, month_chart_pie def get_area_chart(area_list_sorted): dataSource0 = OrderedDict() chartConfig0 = OrderedDict() chartConfig0 = OrderedDict() chartConfig0["palettecolors"] = "3C7EDD, 1FD826,E7E422,E74C22,CC4ADE,EAA829,56DFF1,E463CD" chartConfig0["caption"] = "Regiões Mais Frequentes" chartConfig0["subCaption"] = "" chartConfig0["xAxisName"] = "Região" chartConfig0["yAxisName"] = "Quantidade" chartConfig0["numberSuffix"] = "" chartConfig0["theme"] = "fusion" chartConfig0["chartType"] = "pie2d,column2d" dataSource0["data"] = [] for k, v in area_list_sorted: dataSource0['data'].append({"label":'{}'.format(k), "value": '{}'.format(v)} ) dataSource0["chart"] = chartConfig0 area_chart_col = FusionCharts("column2d", "area_chart_col", "100%", "350", "area_chart_col-container", "json", dataSource0) area_chart_pie = FusionCharts("pie2d", "area_chart_pie", "100%", "350", "area_chart_pie-container", "json", dataSource0) return area_chart_col, area_chart_pie def get_size_chart(sizes): dataSource0 = OrderedDict() chartConfig0 = OrderedDict() chartConfig0 = OrderedDict() #chartConfig0["palettecolors"] = "5d62b5,29c3be,f2726f,ff8000,990099,00ffff" chartConfig0["palettecolors"] = "3C7EDD, 1FD826,E7E422,E74C22,CC4ADE,EAA829,56DFF1,E463CD" chartConfig0["caption"] = "Tamanhos Mais Utilizados" chartConfig0["subCaption"] = "Quantidade x Dimensão" chartConfig0["xAxisName"] = "Dimensão" chartConfig0["yAxisName"] = "Quantidade" chartConfig0["numberSuffix"] = "" chartConfig0["theme"] = "fusion" dataSource0["data"] = [] for k, v in sizes: dataSource0['data'].append({"label":'{}'.format(k), "value": '{}'.format(v)} ) dataSource0["chart"] = chartConfig0 size_chart_col = FusionCharts("column2d", "size_chart_col", "100%", "350", "size_chart_col-container", "json", dataSource0) size_chart_pie = FusionCharts("pie2d", "size_chart_pie", "100%", "350", "size_chart_pie-container", "json", dataSource0) return size_chart_col, size_chart_pie def get_type_chart(types): dataSource0 = OrderedDict() chartConfig0 = OrderedDict() chartConfig0 = OrderedDict() chartConfig0["palettecolors"] = "3C7EDD, 1FD826,E7E422,E74C22,CC4ADE,EAA829,56DFF1,E463CD" chartConfig0["caption"] = "Espécies Mais Utilizadas" chartConfig0["subCaption"] = "Quantidade x Espécie" chartConfig0["xAxisName"] = "Espécie" chartConfig0["yAxisName"] = "Quantidade" chartConfig0["numberSuffix"] = "" chartConfig0["theme"] = "fusion" dataSource0["data"] = [] for k, v in types: dataSource0['data'].append({"label":'{}'.format(k), "value": '{}'.format(v)} ) dataSource0["chart"] = chartConfig0 type_chart_pie = FusionCharts("pie2d", "type_chart_pie", "100%", "350", "type_chart_pie-container", "json", dataSource0) type_chart_col = FusionCharts("column2d", "type_chart_col", "100%", "350", "type_chart_col-container", "json", dataSource0) return type_chart_pie, type_chart_col def get_individual_chart(size_type_sorted): dataSource0 = OrderedDict() chartConfig0 = OrderedDict() chartConfig0 = OrderedDict() chartConfig0["palettecolors"] = "3C7EDD, 1FD826,E7E422,E74C22,CC4ADE,EAA829,56DFF1,E463CD" chartConfig0["caption"] = "Implantes Mais Utilizados" chartConfig0["subCaption"] = "Quantidade x Implante" chartConfig0["xAxisName"] = "Dimensão" chartConfig0["yAxisName"] = "Quantidade" chartConfig0["numberSuffix"] = "" chartConfig0["theme"] = "fusion" dataSource0["data"] = [] for k, v in size_type_sorted: dataSource0['data'].append({"label":'{}'.format(k), "value": '{}'.format(v)} ) dataSource0["chart"] = chartConfig0 size_type_chart_col = FusionCharts("column2d", "size_type_chart_col", "100%", "400", "size_type_chart_col-container", "json", dataSource0) size_type_chart_pie = FusionCharts("pie2d", "size_type_chart_pie", "100%", "400", "size_type_chart_pie-container", "json", dataSource0) return size_type_chart_col, size_type_chart_pie def get_gender_chart(genders): dataSource0 = OrderedDict() chartConfig0 = OrderedDict() chartConfig0 = OrderedDict() chartConfig0["palettecolors"] = "3C7EDD, 1FD826,E7E422,E74C22,CC4ADE,EAA829,56DFF1,E463CD" chartConfig0["caption"] = "Gêneros" chartConfig0["subCaption"] = "" chartConfig0["xAxisName"] = "Gênero" chartConfig0["yAxisName"] = "Quantidade" chartConfig0["numberSuffix"] = "" chartConfig0["theme"] = "fusion" dataSource0["data"] = [] for k, v in genders: dataSource0['data'].append({"label":'{}'.format(k), "value": '{}'.format(v)} ) dataSource0["chart"] = chartConfig0 gender_chart_pie = FusionCharts("pie2d", "gender_chart_pie", "100%", "350", "gender_chart_pie-container", "json", dataSource0) gender_chart_col = FusionCharts("column2d", "gender_chart_col", "100%", "350", "gender_chart_col-container", "json", dataSource0) return gender_chart_pie, gender_chart_col<file_sep>/ccip/views.py from ccip.forms import ClientForm, ImplantForm, SurgeryForm from django.shortcuts import render from django.shortcuts import render, redirect, get_object_or_404, HttpResponseRedirect from django.contrib.auth.models import User from django.contrib import auth, messages from django.contrib.auth.decorators import login_required from django.conf import settings from .models import * # Create your views here. def index(request): if not request.user.is_authenticated: return render(request, 'busers/register.html') else: user = get_object_or_404(User, pk=request.user.id) u_email = User.objects.filter(pk = request.user.id).values_list('email', flat=True)[0] surgerys = Surgery.objects.all().filter(user = user).order_by("-date") n_surg = len(surgerys) n = 0 for i in range(n_surg): n += surgerys[i].quantity if n > 0: ratio = n / n_surg else: ratio = 0 return render(request, 'ccip/index.html', {'user': user,'u_email':u_email, 'surgerys': surgerys, 'n_surg': n_surg, 'n': n, 'ratio': round(ratio, 2)}) def quant(request): if not request.user.is_authenticated: return render(request, 'busers/register.html') else: if request.method == "GET": u_email = User.objects.filter(pk = request.user.id).values_list('email', flat=True)[0] return render(request, 'ccip/quant.html', {'u_email': u_email}) if request.method == "POST": u_email = User.objects.filter(pk = request.user.id).values_list('email', flat=True)[0] user = get_object_or_404(User, pk=request.user.id) quant = request.POST['quant'] if not quant or int(quant) <= 0: return redirect('quant') else: clients = Client.objects.filter(user = user).values('full_name') stageOpt = ['Espera','Andamento','Finalizado'] return render(request, 'ccip/add_surgery.html', {'quant': quant, 'clients': clients, 'stageOpt': stageOpt,'u_email': u_email}) def add_surgery(request): if not request.user.is_authenticated: return render(request, 'busers/register.html') else: if request.method == 'GET': u_email = User.objects.filter(pk = request.user.id).values_list('email', flat=True)[0] return render(request, 'ccip/add_surgery.html', {'u_email': u_email} ) else: u_email = User.objects.filter(pk = request.user.id).values_list('email', flat=True)[0] user = get_object_or_404(User, pk=request.user.id) client_name = request.POST['client'] clients = Client.objects.filter(full_name = client_name) client = clients[0] date = request.POST['date'] quantity = request.POST['quantity'] obs = request.POST['obs'] stage = request.POST['stage'] prot = request.POST['prot'] areaList = [] typeList = [] sizeList = [] implanteList = [] stock = list(Implant.objects.all().filter(user = user)) for i in range(int(quantity)): j = i + 1 type = request.POST['type' + str(j)] size = request.POST['size' + str(j)] areaList.append(request.POST['area' + str(j)]) typeList.append(type) sizeList.append(size) implante = str(typeList[i]) + ' ' + str(sizeList[i]) implanteList.append(implante) imp = list(Implant.objects.all().filter(user = user, type = type, size = size)) if imp == []: messages.warning(request, "Checar estoque de implantes.") else: quant = imp[0].quantity Implant.objects.filter(user = user, type = type, size = size).update(quantity = (quant - 1) ) impl = Implant.objects.filter(user = user, type = type, size = size) if impl[0].quantity <= 0: Implant.objects.filter(user = user, type = type, size = size).update(quantity = 0 ) messages.warning(request, 'Checar estoque de implantes.') user = get_object_or_404(User, pk=request.user.id) surgery = Surgery.objects.create( user = user, client = client, date = date, quantity = quantity, implant_type = typeList, implant_size = sizeList, obs = obs, area = areaList, stage = stage, pmu = prot ) try: surgery.save() except: messages.error(request, "Erro ao cadastrar nova cirurgia.") return redirect('quant') messages.success(request, "Cirurgia adicionada com sucesso!") return redirect('index') def update_surgery(request, surgery_id): if not request.user.is_authenticated: return render(request, 'busers/register.html',) else: if request.method == "GET": u_email = User.objects.filter(pk = request.user.id).values_list('email', flat=True)[0] u_email = User.objects.filter(pk = request.user.id).values_list('email', flat=True)[0] user = get_object_or_404(User, pk=request.user.id) surgery = Surgery.objects.get(user=user, pk=surgery_id) form = SurgeryForm(instance=surgery) types = surgery.implant_type sizes = surgery.implant_size areas = surgery.area return render(request, "ccip/update_surgery.html", {'form': form, 'types': types, 'sizes': sizes, 'areas': areas, 'u_email': u_email}) else: areaList = [] typeList = [] sizeList = [] user = get_object_or_404(User, pk=request.user.id) surgery = Surgery.objects.get(user=user, pk=surgery_id) client = request.POST['client'] date = request.POST['date'] quantity = request.POST['quantity'] for i in range(int(quantity)): areaList.append(request.POST["area" + str(i+1)]) typeList.append(request.POST["type" + str(i+1)]) sizeList.append(request.POST["size" + str(i+1)]) obs = request.POST['obs'] stage = request.POST['stage'] pmu = request.POST['pmu'] surgery = Surgery.objects.filter(user=user, pk=surgery_id).update(date=date, client=client, quantity=quantity, area=areaList,implant_type=typeList, implant_size=sizeList, obs=obs, stage=stage, pmu=pmu) messages.success(request, 'Cirurgia atualizada com sucesso!') return redirect('index') def delete_surgery(request, surgery_id): user = get_object_or_404(User, pk=request.user.id) surg = Surgery.objects.get(user = user, pk=surgery_id) surg.delete() return redirect('index') def add_implant(request): if not request.user.is_authenticated: return render(request, 'busers/register.html') else: if request.method == "POST": user = get_object_or_404(User, pk=request.user.id) u_email = User.objects.filter(pk = request.user.id).values_list('email', flat=True)[0] type = request.POST['type'] size = request.POST['size'] quantity = request.POST['quantity'] imp = list(Implant.objects.all().filter(user = user, type = type, size = size)) if imp == []: messages.success(request, "Implante adicionado com sucesso!") Implant.objects.create( user = user, type = type, size = size, quantity = quantity ) else: implant_to_update = Implant.objects.all().filter(user = user, type = type, size = size) add = implant_to_update[0].quantity implant_to_update.update(quantity = int(add) + int(quantity)) messages.success(request, "Implante atualizado com sucesso!") return redirect('stock') else: u_email = User.objects.filter(pk = request.user.id).values_list('email', flat=True)[0] form = ImplantForm return render(request, "ccip/add_implant.html", {'form': form, 'u_email': u_email}) def stock(request): if not request.user.is_authenticated: return render(request, 'busers/register.html') else: if request.method == "GET": u_email = User.objects.filter(pk = request.user.id).values_list('email', flat=True)[0] user = get_object_or_404(User, pk=request.user.id) stock = Implant.objects.all().filter(user = user) return render(request, 'ccip/stock.html', {'stock': stock, 'u_email': u_email}) def delete_implant(request, implant_id): if not request.user.is_authenticated: return render(request, 'busers/register.html') else: user = get_object_or_404(User, pk=request.user.id) imp_to_delete = Implant.objects.get(user = user, pk = implant_id) imp_to_delete.delete() return redirect('stock') def update_implant(request, implant_id): if not request.user.is_authenticated: return render(request, 'busers/register.html') else: if request.method == "GET": u_email = User.objects.filter(pk = request.user.id).values_list('email', flat=True)[0] user = get_object_or_404(User, pk=request.user.id) implants = Implant.objects.get(user=user, pk=implant_id) form = ImplantForm(instance=implants) return render(request, 'ccip/update_implant.html', {'form': form, 'u_email': u_email}) if request.method == "POST": user = get_object_or_404(User, pk=request.user.id) type = request.POST['type'] size = request.POST['size'] quant = request.POST['quantity'] implants = Implant.objects.all().filter(user=user, pk=implant_id).update(quantity = quant, type = type, size = size) return redirect('stock') def add_client(request): if not request.user.is_authenticated: return render(request, 'busers/register.html') else: if request.method == "GET": u_email = User.objects.filter(pk = request.user.id).values_list('email', flat=True)[0] form = ClientForm return render(request, 'ccip/add_client.html', {'form': form, 'u_email': u_email}) else: user = get_object_or_404(User, pk=request.user.id) name = request.POST['full_name'] birth = request.POST['birth_date'] gender = request.POST['gender'] phone = request.POST['phone'] obs = request.POST['obs'] client_name = list(Client.objects.all().filter(user = user, full_name = name)) if client_name == []: Client.objects.create( user = user, full_name = name, birth_date = birth, gender = gender, phone = phone, obs = obs, ) messages.success(request, "Cliente cadastrado com sucesso!") return redirect('client_list') else: Client.objects.create( user = user, full_name = name, birth_date = birth, phone = phone, obs = obs, ) messages.warning(request, "Cliente possivelmente já cadastrado.") return redirect("client_list") def client_list(request): if not request.user.is_authenticated: return render(request, 'busers/register.html') else: u_email = User.objects.filter(pk = request.user.id).values_list('email', flat=True)[0] user = get_object_or_404(User, pk=request.user.id) clients = Client.objects.all().filter(user = user).order_by('full_name') return render(request, 'ccip/client_list.html', {'clients': clients, 'u_email': u_email}) def delete_client(request, client_id): if not request.user.is_authenticated: return render(request, 'busers/register.html') else: user = get_object_or_404(User, pk=request.user.id) client = Client.objects.all().filter(user=user, pk=client_id) client.delete() messages.warning(request, "Cliente excluído.") return redirect('client_list') def update_client(request, client_id): if not request.user.is_authenticated: return render(request, 'busers/register.html') else: if request.method == "GET": u_email = User.objects.filter(pk = request.user.id).values_list('email', flat=True)[0] user = get_object_or_404(User, pk=request.user.id) clients = Client.objects.get(user=user, pk=client_id) form = ClientForm(instance=clients) return render(request, 'ccip/update_client.html', {'form': form, 'u_email': u_email}) if request.method == "POST": user = get_object_or_404(User, pk=request.user.id) name = request.POST['full_name'] birth = request.POST['birth_date'] gender = request.POST['gender'] phone = request.POST['phone'] obs = request.POST['obs'] clients = Client.objects.all().filter(user=user, pk=client_id).update(full_name = name, birth_date = birth,gender = gender, phone = phone, obs = obs) messages.success(request, "Dados do cliente atualizados com sucesso!") return redirect('client_list') <file_sep>/ccip/migrations/0011_auto_20210628_2215.py # Generated by Django 3.2.4 on 2021-06-29 01:15 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('ccip', '0010_auto_20210628_2149'), ] operations = [ migrations.AlterField( model_name='client', name='gender', field=models.CharField(blank=True, choices=[('Masculino', 'Masculino'), ('Feminino', 'Feminino'), ('Outro', 'Outro')], max_length=50), ), migrations.AlterField( model_name='surgery', name='pmu', field=models.CharField(choices=[('Protocolo', 'Protocolo'), ('Múltipla', 'Múltipla'), ('Unitária', 'Unitária')], default='Unitária', max_length=20), ), ] <file_sep>/ccip/forms.py from django import forms from django.forms import ModelForm from .models import * class SurgeryForm(ModelForm): class Meta: model = Surgery fields = ('client', 'date', 'area', 'quantity', 'implant_type', 'implant_size','obs', 'stage', 'pmu') labels = { 'client': 'Nome', 'date': 'Data', 'quantity': 'Quantidade', 'area': 'Area cirurgica', 'implant_type': 'Implante', 'implant_size': 'Size', 'obs': 'Observações', 'stage': 'Estágio', 'pmu': 'Tipo de Prótese' } #CLIENT = Client.objects.all() / choices=CLIENT STAGE = ['Espera', 'Andamento', 'Finalizado'] PMU = [' ', 'Protocolo'] widgets = { 'client': forms.Select(attrs={'class': 'form-control',},), 'date': forms.DateInput(attrs={'class': 'form-control', 'type': 'date', 'input_formats': 'DATE_FORMATS'}), 'quantity': forms.TextInput(attrs={'class': 'form-control', 'type': 'number' ,'onchange': 'GetValue()', 'min': '1' ,'max': '8', 'value': '0', }), 'area': forms.Select(attrs={'class': 'form-control'}), 'implant_type': forms.Select(attrs={'class': 'form-control',}), 'implant_size': forms.Select(attrs={'class': 'form-control',}), 'obs': forms.Textarea(attrs={'class': 'form-control', 'rows': '5','cols': '20'}), 'stage': forms.Select(attrs={'class': 'form-control'}, choices=STAGE), 'pmu': forms.Select(attrs={'class': 'form-control'}, choices=PMU), } class ClientForm(ModelForm): class Meta: model = Client fields = ('user', 'full_name', 'birth_date', 'gender', 'phone', 'obs',) labels = { 'user': '', 'full_name': 'Nome:', 'birth_date': 'Data de Nascimento:', 'gender': 'Gênero:', 'phone': 'Telefone:', 'obs': 'Obs:', } GENDER = ['Masculino', 'Feminino', 'Outro'] widgets = { 'user': forms.TextInput(attrs={'class': 'form-control', 'hidden': True}), 'full_name': forms.TextInput(attrs={'class': 'form-control',}), 'birth_date': forms.DateInput(attrs={'class': 'form-control', 'type': 'date',}), 'gender': forms.Select(attrs={'class': 'form-control'}, choices=GENDER,), 'phone': forms.TextInput(attrs={'class': 'form-control', 'type': 'text'}), 'obs': forms.Textarea(attrs={'class': 'form-control', 'rows': '3'}), } class ImplantForm(ModelForm): imp =[] sizes = ['3.5x8','3.5x10','3.5x11.5','3.5x13','3.5x15','4.3x8','4.3x10','4.3x11.5','4.3x13','4.3x15'] tipos = ['Neodent Alvim CM', 'Neodent Drive CM', 'SIN SWC CM', 'SIN Strong CM', 'SIN Unitite CM'] for tipo in tipos: for size in sizes: impl = tipo + ' ' + size imp.append(impl) implantes = [] for i in imp: impla = (str(i), str(i)) implantes.append(impla) class Meta: tipos = ['Neodent Alvim CM', 'Neodent Drive CM', 'SIN SWC CM', 'SIN Strong CM', 'SIN Unitite CM'] sizes = ['3.5x8','3.5x10','3.5x11.5','3.5x13','3.5x15','4.3x8','4.3x10','4.3x11.5','4.3x13','4.3x15'] model = Implant fields = ('type', 'size','quantity', 'user') labels = { 'type': 'Implante', 'size': 'Tamanho', 'quantity': 'Quantidade', 'user': '', } widgets = { 'type': forms.Select(attrs={'class': 'form-control', }, choices=tipos), 'size': forms.Select(attrs={'class': 'form-control',}, choices=sizes), 'quantity': forms.TextInput(attrs={'class': 'form-control', 'type': 'number'}), 'user' : forms.TextInput(attrs={'class': 'form-control', 'default': 'asd'}) } <file_sep>/ccip/migrations/0001_initial.py # Generated by Django 3.2.4 on 2021-06-04 19:16 from django.conf import settings import django.contrib.postgres.fields from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Client', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('full_name', models.CharField(max_length=80)), ('birth_date', models.DateField(blank=True, null=True)), ('phone', models.CharField(blank=True, max_length=20, null=True)), ('obs', models.TextField(blank=True, max_length=1000)), ('user', models.ForeignKey(default=None, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='Surgery', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('date', models.DateField(default='04/06/21')), ('quantity', models.PositiveIntegerField(default=0)), ('implant_type', django.contrib.postgres.fields.ArrayField(base_field=models.CharField(choices=[('Neodent Alvim CM', 'Neodent Alvim CM'), ('Neodent Drive CM', 'Neodent Drive CM'), ('SIN SWC CM', 'SIN SWC CM'), ('SIN Strong CM', 'SIN Strong CM')], max_length=50), size=None)), ('implant_size', django.contrib.postgres.fields.ArrayField(base_field=models.CharField(choices=[('3.5x8', '3.5x8'), ('3.5x10', '3.5x10'), ('3.5x11.5', '3.5x11.5'), ('3.5x13', '3.5x13'), ('3.5x15', '3.5x15'), ('4.3x8', '4.3x8'), ('4.3x10', '4.3x10'), ('4.3x11.5', '4.3x11.5'), ('4.3x13', '4.3x13'), ('4.3x15', '4.3x15')], max_length=50), size=None)), ('area', django.contrib.postgres.fields.ArrayField(base_field=models.CharField(choices=[(11, 11), (12, 12), (13, 13), (14, 14), (15, 15), (16, 16), (17, 17), (18, 18), (21, 21), (22, 22), (23, 23), (24, 24), (25, 25), (26, 26), (27, 27), (28, 28), (31, 31), (32, 32), (33, 33), (34, 34), (35, 35), (36, 36), (37, 37), (38, 38), (41, 41), (42, 42), (43, 43), (44, 44), (45, 45), (46, 46), (47, 47)], max_length=50), size=None)), ('obs', models.TextField(blank=True, max_length=600)), ('stage', models.CharField(choices=[('Finalizado', 'Finalizado'), ('Espera', 'Espera'), ('Andamento', 'Andamento')], default='Espera', max_length=50)), ('client', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='ccip.client')), ('usuario', models.ForeignKey(default=None, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='Implant', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('size', models.CharField(choices=[('3.5x8', '3.5x8'), ('3.5x10', '3.5x10'), ('3.5x11.5', '3.5x11.5'), ('3.5x13', '3.5x13'), ('3.5x15', '3.5x15'), ('4.3x8', '4.3x8'), ('4.3x10', '4.3x10'), ('4.3x11.5', '4.3x11.5'), ('4.3x13', '4.3x13'), ('4.3x15', '4.3x15')], default='3.5x8', max_length=30)), ('type', models.CharField(choices=[('Neodent Alvim CM', 'Neodent Alvim CM'), ('Neodent Drive CM', 'Neodent Drive CM'), ('SIN SWC CM', 'SIN SWC CM'), ('SIN Strong CM', 'SIN Strong CM')], default='Neodent Alvim CM 3.5x8', max_length=60)), ('quantity', models.IntegerField(default=1)), ('user', models.ForeignKey(default=None, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), ]
2c4b2e93bd6eff166468f7bfc9909f166f46856d
[ "Python" ]
12
Python
felipepassagem/project3-djangoapp-surgerys
30f0b3bccda45ff4618b05672775295c363bf07b
8e3450a526558f8086a11393f7c450d33978de74
refs/heads/master
<repo_name>jjprada/MisLugares<file_sep>/app/src/main/java/com/jjprada/mislugares/VistaLugarFragment.java package com.jjprada.mislugares; import android.app.Activity; import android.app.AlertDialog; import android.app.DatePickerDialog; import android.app.TimePickerDialog; import android.support.v4.app.Fragment; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.Environment; import android.provider.MediaStore; import android.support.annotation.Nullable; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.DatePicker; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RatingBar; import android.widget.TextView; import android.widget.TimePicker; import java.io.File; import java.text.DateFormat; import java.text.FieldPosition; import java.text.ParsePosition; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class VistaLugarFragment extends Fragment implements TimePickerDialog.OnTimeSetListener, DatePickerDialog.OnDateSetListener { public final static String TAG = "VistaLugarFragment"; private final static int REQUEST_EDITAR = 1; private final static int REQUEST_GALERIA = 2; private final static int REQUEST_FOTO = 3; private int mID; // Estar atento porque el curso usa un long, igual tengo que cambirlo despues. Si es asi cambiar el Extra trambien private View mView; private Lugar mLugar; private TextView mNombreLugar; private ImageView mLogoTipo; private TextView mTipoLugar; private TextView mDireccion; private TextView mTelefono; private TextView mUrl; private TextView mComentario; private TextView mFecha; private TextView mHora; private RatingBar mValoracion; private ImageView mFoto; private Uri mUriFotoCamara; private SimpleDateFormat mFormato; @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.activity_vista_lugar, container, false); setHasOptionsMenu(true); // LISTNER PARA MOSTRAR EL MAPA LinearLayout mapa = (LinearLayout) view.findViewById(R.id.elemento_mapa); mapa.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { verMapa(); } }); // LISTNER PARA LLAMAR AL TELEFONO LinearLayout phone = (LinearLayout) view.findViewById(R.id.elemento_phone); phone.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { llamadaTelefono(); } }); // LISTNER PARA MOSTRAR LA WEB LinearLayout url = (LinearLayout) view.findViewById(R.id.elemento_url); url.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { verWeb(); } }); // LISTNER PARA TOMAR UN FOTO ImageView ivTomaFoto = (ImageView) view.findViewById(R.id.tomar_Foto); ivTomaFoto.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { tomarFoto(); } }); // LISTNER PARA ABRIR LA GALERIA ImageView ivAbrirGaleria = (ImageView) view.findViewById(R.id.abrir_galeria); ivAbrirGaleria.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { abrirGaleria(); } }); // LISTNER PARA ELIMINAR LA FOTO ImageView ivEliminarFoto = (ImageView) view.findViewById(R.id.eliminar_foto); ivEliminarFoto.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { eliminarFoto(); } }); // LISTNER PARA CAMBIAR LA FECHA ImageView ivFecha = (ImageView) view.findViewById(R.id.logo_fecha); ivFecha.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { cambiarFecha(); } }); // LISTNER PARA CAMBIAR LA HORA ImageView ivHora = (ImageView) view.findViewById(R.id.logo_hora); ivHora.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { cambiarHora(); } }); return view; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // Obtenemos los extras pasados a la actividad Bundle extras = getActivity().getIntent().getExtras(); if(extras != null) { // Si los extras no están vacios // Obtenemos la ID del Lugar mostrado mID = extras.getInt(VistaLugarActivity.EXTRA, -1); if(mID != -1) { // Si no hay error, actualizamos los datos del Lugar mostrarLugarFragment(mID); } } } public void mostrarLugarFragment(int id) { // Actualizamos el valor de ID, ya que se puede llamar a este método desde diferentes sitios que modifiquen este valor mID = id; // Obtenemos la Vista del "layout" que muestra el "fragment" mView = getView(); // Datos Editables mNombreLugar = (TextView) mView.findViewById(R.id.lista_nombre); mLogoTipo = (ImageView) mView.findViewById(R.id.logo_tipo); mTipoLugar = (TextView) mView.findViewById(R.id.tipo_lugar); mDireccion = (TextView) mView.findViewById(R.id.lista_direccion); mTelefono = (TextView) mView.findViewById(R.id.phone); mUrl = (TextView) mView.findViewById(R.id.url); mComentario = (TextView) mView.findViewById(R.id.comentario); mFoto = (ImageView) mView.findViewById(R.id.lista_foto); actualizarDatos(); // Fecha mFecha = (TextView) mView.findViewById(R.id.fecha); mFecha.setText(DateFormat.getDateInstance().format(new Date(mLugar.getFecha()))); // Hora mHora = (TextView) mView.findViewById(R.id.hora); mFormato = new SimpleDateFormat("HH:mm", java.util.Locale.getDefault()); mHora.setText(mFormato.format(new Date(mLugar.getFecha()))); // Valoracion mValoracion = (RatingBar) mView.findViewById(R.id.lista_valoracion); mValoracion.setRating(mLugar.getValoracion()); mValoracion.setOnRatingBarChangeListener(new RatingBar.OnRatingBarChangeListener() { @Override public void onRatingChanged(RatingBar ratingBar, float valor, boolean fromUser) { mLugar.setValoracion(valor); Lugares.actualizarLugar(mID, mLugar); // Guardar datos en la BBDD } }); } // MUESTRA LOS DATOS DEL LUGAR QUE PUEDEN SER EDITABLES, POR ESO SE METEN EN UN MÉTODO APARTE private void actualizarDatos() { // Buscar el Lugar en función de la ID indicada mLugar = Lugares.elemento(mID); // Se pone aquí para cuando editemos, actualice de nuevo los datos del Lugar en mLugar //Nombre mNombreLugar.setText(mLugar.getNombre()); // Logo Tipo Lugar mLogoTipo.setImageResource(mLugar.getTipoLugar().getRecurso()); // Tipo Lugar mTipoLugar.setText(mLugar.getTipoLugar().getTexto()); // Direccion if ((mLugar.getDireccion() == null) || (mLugar.getDireccion().equals(""))){ mDireccion.setVisibility(View.GONE); mView.findViewById(R.id.logo_direccion).setVisibility(View.GONE); } else { mDireccion.setText(mLugar.getDireccion());} // Telefono if (mLugar.getTelefono() == 0){ mTelefono.setVisibility(View.GONE); mView.findViewById(R.id.logo_phone).setVisibility(View.GONE); } else { mTelefono.setText(Integer.toString(mLugar.getTelefono()));} // URL if ((mLugar.getUrl() == null) || (mLugar.getUrl().equals(""))){ mUrl.setVisibility(View.GONE); mView.findViewById(R.id.logo_url).setVisibility(View.GONE); } else { mUrl.setText(mLugar.getUrl());} // Comentario if ((mLugar.getComentario() == null) || (mLugar.getComentario().equals(""))){ mComentario.setVisibility(View.GONE); mView.findViewById(R.id.logo_comentarios).setVisibility(View.GONE); } else { mComentario.setText(mLugar.getComentario());} // Foto actualizarFoto(mLugar.getFoto()); } // MUESTRA LA FOTO DEL LUGAR // SE METE EN UN MÉTODO A PARTE PORQUE SE USA TAMBIEN CUANDO SE EDITA LA FOTO private void actualizarFoto(String uri) { if (uri != null) { mFoto.setImageURI(Uri.parse(uri)); // Actualizamos la foto en la Vista } else { mFoto.setImageBitmap(null); // No foto o Uri no valido, no mostramos imagen } Lugares.actualizarLugar(mID, mLugar); // Guardar datos en la BBDD } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.menu_vista_lugar, menu); super.onCreateOptionsMenu(menu, inflater); } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); Intent i; switch (id) { case R.id.accion_compartir: i = new Intent(Intent.ACTION_SEND); i.setType("text/plain"); i.putExtra(Intent.EXTRA_TEXT, mLugar.getNombre() + " - "+ mLugar.getUrl()); startActivity(i); return true; case R.id.accion_llegar: verMapa(); return true; case R.id.accion_editar: i = new Intent(getActivity(), EdicionLugarActivity.class); i.putExtra(EdicionLugarActivity.EXTRA, mID); startActivityForResult(i, REQUEST_EDITAR); return true; case R.id.accion_buscar: //mostrarLugar(); return true; case R.id.accion_borrar: confirmarBorrar(); return true; default: return super.onOptionsItemSelected(item); } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == Activity.RESULT_OK) { switch (requestCode) { case REQUEST_EDITAR: mID = data.getIntExtra(VistaLugarActivity.EXTRA, -1); mostrarLugarFragment(mID); //actualizarDatos(); //getView().findViewById(R.id.vista_activity).invalidate(); break; case REQUEST_GALERIA: String uri = data.getDataString(); mLugar.setFoto(uri); // Actualizamos la foto del objeto Lugar actualizarFoto(mLugar.getFoto()); // Actualizamos la foto en la Vista break; case REQUEST_FOTO: mLugar.setFoto(mUriFotoCamara.toString()); // Actualizamos la foto del objeto Lugar actualizarFoto(mLugar.getFoto()); // Actualizamos la foto en la Vista break; } } } // Muestra un Lugar en función de la ID indicada por el usuario /* AHORA NO FUNCIONA BIEN PORQUE NO CHEQUEA SI EXISTE UN LUGAR CON ESA ID POR LO QUE ROMPE LA APP ** NO LO SOLUCIONADO PORQUE UNA VEZ METIDA LA BD NO TIENE SENTIDO BUSCAR POR ID */ public void mostrarLugar(){ final EditText mensaje = new EditText(getActivity()); mensaje.setText("1"); // Lugar para mostrar por defecto, ya que ahora mismo solo tenemos defino uno new AlertDialog.Builder(getActivity()) .setTitle("Seleccion de lugar") .setMessage("Indica su ID:") .setView(mensaje) .setPositiveButton("Ok", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { int id = Integer.parseInt(mensaje.getText().toString()); // Transforma el String en un Long Intent i = new Intent(getActivity(), VistaLugarActivity.class); i.putExtra(VistaLugarActivity.EXTRA, id); startActivity(i); } }) .setNegativeButton("Cancelar", null) .show(); } // BORRAR EL LUGAR EN EL QUE NOS ENCONTRAMOS public void confirmarBorrar(){ TextView mensaje = new TextView(getActivity()); new AlertDialog.Builder(getActivity()) .setTitle("Borrado de lugar") .setMessage("¿Estas seguro que quieres eliminar este lugar?") .setView(mensaje) .setPositiveButton("Confirmar", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Lugares.borrar(mID); getActivity().setResult(Activity.RESULT_OK); SelectorFragment selectorFragment = (SelectorFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.selector_fragment); if (selectorFragment == null) { getActivity().finish(); } else { ((MainActivity) getActivity()).muestraLugar(Lugares.primerId()); ((MainActivity) getActivity()).actualizarLista(); } } }) .setNegativeButton("Cancelar", null) .show(); } // MUESTRA EL LUGAR EN UN MAPA private void verMapa() { Uri uri; double lat = mLugar.getPosicion().getLatitud(); double lon = mLugar.getPosicion().getLongitud(); if (lat != 0 || lon != 0) { uri = Uri.parse("geo:" + lat + "," + lon); } else { uri = Uri.parse("geo:0,0?q=" + mLugar.getDireccion()); } Intent i = new Intent(Intent.ACTION_VIEW, uri); startActivity(i); } // LLAMA AL TELEFONO INDICADO EN EL LUGAR private void llamadaTelefono() { startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + mLugar.getTelefono()))); } // VER WEB DEL LUGAR private void verWeb() { startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(mLugar.getUrl()))); } // METODOS PARA EL CAMBIO DE FOTO DEL LUGAR private void tomarFoto (){ Intent i = new Intent("android.media.action.IMAGE_CAPTURE"); File directorio = new File(Environment.getExternalStorageDirectory() + File.separator + "img_" + (System.currentTimeMillis()/1000) + ".jpg"); mUriFotoCamara = Uri.fromFile(directorio); i.putExtra(MediaStore.EXTRA_OUTPUT, mUriFotoCamara); startActivityForResult(i, REQUEST_FOTO); } private void abrirGaleria (){ Intent i = new Intent(Intent.ACTION_GET_CONTENT); i.addCategory(Intent.CATEGORY_OPENABLE); i.setType("image/*"); startActivityForResult(i, REQUEST_GALERIA); } private void eliminarFoto () { mLugar.setFoto(null); actualizarFoto(mLugar.getFoto()); } // METODO PARA EL CAMBIO DE FECHA DE UN LUGAR public void cambiarFecha() { DialogoSelectorFecha dialogoFecha = new DialogoSelectorFecha(); // Creamos un nuevo objeto diálogo, el cual va a extender "DialogFragment" dialogoFecha.setOnDateSetListener(this); // Asignamos el escuchador a nuestra propia clase creada. Se llamará al método "onDateSet()" cuando se cambie de fecha Bundle args = new Bundle(); // Creamos un Bundle donde almacenaremos la fecha a enviar al Dialog args.putLong("fecha", mLugar.getFecha()); dialogoFecha.setArguments(args); dialogoFecha.show(getActivity().getSupportFragmentManager(), "selectorFecha"); } // METODO NECSARIO PARA IMPLEMENTAR EL LISTNER "DatePickerDialog.OnDateSetListener" @Override public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) { Calendar calendario = Calendar.getInstance(); // Creamos un objeto "Calendar" para almacenar la información con la nueva fecha que asociacremos al lugar calendario.setTimeInMillis(mLugar.getFecha()); // Inicializamos el objeto "Calendar" con la antigua fecha que tiene almacenada el Lugar calendario.set(Calendar.YEAR, year); // Modificamos sólo el ano según los parámetros que nos han pasado calendario.set(Calendar.MONTH, month); // Modificamos sólo el mes según los parámetros que nos han pasado calendario.set(Calendar.DAY_OF_MONTH, dayOfMonth); // Modificamos sólo el día según los parámetros que nos han pasado mLugar.setFecha(calendario.getTimeInMillis()); // Actualizamos la fecha del Lugar, con la nueva fecha modificada almacenada en "calendario" Lugares.actualizarLugar(mID, mLugar); // Actualizamos la BD, para que almacene la nueva fecha TextView textHora = (TextView) getView().findViewById(R.id.fecha); // Hacemos "fetch" del UI que muestra la gecha DateFormat format = DateFormat.getDateInstance(); // Damos formato a la fecha, indicando que tome el mismo formato que usa el sistema textHora.setText(format.format(new Date(mLugar.getFecha()))); // Modifiamos el texto, con la nueva fecha formateada } // METODO PARA EL CAMBIO DE HORA DE UN LUGAR public void cambiarHora() { DialogoSelectorHora dialogoHora = new DialogoSelectorHora(); // Creamos un nuevo objeto diálogo, el cual va a extender "DialogFragment" dialogoHora.setOnTimeSetListener(this); // Asignamos el escuchador a nuestra propia clase creada. Se llamará al método "onTimeSet()" cuando se cambie de hora Bundle args = new Bundle(); // Creamos un Bundle donde almacenaremos la fecha a enviar al Dialog args.putLong("fecha", mLugar.getFecha()); dialogoHora.setArguments(args); dialogoHora.show(getActivity().getSupportFragmentManager(), "selectorHora"); } // METODO NECSARIO PARA IMPLEMENTAR EL LISTNER "TimePickerDialog.OnTimeSetListener" @Override public void onTimeSet(TimePicker view, int hourOfDay, int minute) { Calendar calendario = Calendar.getInstance(); // Creamos un objeto "Calendar" para almacenar la información con la nueva fecha que asociacremos al lugar calendario.setTimeInMillis(mLugar.getFecha()); // Inicializamos el objeto "Calendar" con la antigua fecha que tiene almacenada el Lugar calendario.set(Calendar.HOUR_OF_DAY, hourOfDay); // Modificamos sólo la hora según los parámetros que nos han pasado calendario.set(Calendar.MINUTE, minute); // Modificamos sólo los minutos según los parámetros que nos han pasado mLugar.setFecha(calendario.getTimeInMillis()); // Actualizamos la fecha del Lugar, con la nueva fecha modificada almacenada en "calendario" Lugares.actualizarLugar(mID, mLugar); // Actualizamos la BD, para que almacene la nueva hora TextView textHora = (TextView) getView().findViewById(R.id.hora); // Hacemos "fetch" del UI que muestra la hora. textHora.setText(mFormato.format(new Date(mLugar.getFecha()))); // Modifiamos el texto, con la nueva fecha formateada } } <file_sep>/app/src/main/java/com/jjprada/mislugares/VistaLugarActivity.java package com.jjprada.mislugares; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; public class VistaLugarActivity extends ActionBarActivity { private final static String TAG = "VistaLugarActivity"; public final static String EXTRA = "ID"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_vista_lugar); } } <file_sep>/app/src/main/java/com/jjprada/mislugares/EdicionLugarActivity.java package com.jjprada.mislugares; import android.content.Intent; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ImageView; import android.widget.Spinner; import android.widget.TextView; public class EdicionLugarActivity extends ActionBarActivity { public static final String EXTRA = "EXTRA"; public final static String EXTRA_NEW = "EXTRA NEW"; private final static String TAG = "EdicionLugarActivity"; private int mID; private Lugar mLugar; private EditText mNombre; private EditText mDireccion; private EditText mTelefono; private EditText mUrl; private EditText mComentario; private Spinner mTipoLugar; private boolean mIsNew; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_edicion_lugar); Log.d(TAG, "Entre en Actividad"); // Obtener EXXTRAS mID = getIntent().getIntExtra(EXTRA, -1); mIsNew = getIntent().getBooleanExtra(EXTRA_NEW, false); Log.d(TAG, "Extras: "+mID+" - "+ mIsNew); mLugar = Lugares.elemento(mID); //Nombre mNombre = (EditText) findViewById(R.id.edit_name); if ((mLugar.getNombre()!= null) && (!mLugar.getNombre().equals(""))){ mNombre.setText(mLugar.getNombre()); } // Direccion mDireccion = (EditText) findViewById(R.id.edit_direccion); if ((mLugar.getDireccion()!= null) && (!mLugar.getDireccion().equals(""))){ mDireccion.setText(mLugar.getDireccion()); } // Telefono mTelefono = (EditText) findViewById(R.id.edit_phone); if (mLugar.getTelefono() != 0){ mTelefono.setText(Integer.toString(mLugar.getTelefono())); } // URL mUrl = (EditText) findViewById(R.id.edit_web); if ((mLugar.getUrl()!= null) && (!mLugar.getUrl().equals(""))){ mUrl.setText(mLugar.getUrl()); } // Comentario mComentario = (EditText) findViewById(R.id.edit_coment); if ((mLugar.getComentario()!= null) && (!mLugar.getComentario().equals(""))){ mComentario.setText(mLugar.getComentario()); } // Tipo Lugar mTipoLugar = (Spinner) findViewById(R.id.edit_tipo_lugar); ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, TipoLugar.getNombres()); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mTipoLugar.setAdapter(adapter); mTipoLugar.setSelection(mLugar.getTipoLugar().ordinal()); Log.d(TAG, "Fin"); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_edicion_lugar, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.edit_save) { Log.d(TAG, "Save: INICIO"); // Chequeamos que no se intente acceder a valores que sean "null" o esten vacios, porque rompe la app if ((mNombre.getText() != null) && (!mNombre.getText().toString().equals(""))) { mLugar.setNombre(mNombre.getText().toString()); Log.d(TAG, "Save: Grabar nombre"); } else { mLugar.setNombre("None"); } if ((mDireccion.getText() != null) && (!mDireccion.getText().toString().equals(""))) { mLugar.setDireccion(mDireccion.getText().toString()); Log.d(TAG, "Save: Grabar Direccion"); } if ((mTelefono.getText() != null) && (!mTelefono.getText().toString().equals(""))) { mLugar.setTelefono(Integer.parseInt(mTelefono.getText().toString())); Log.d(TAG, "Save: Grabar Telefono"); } if ((mUrl.getText() != null) && (!mUrl.getText().toString().equals(""))) { mLugar.setUrl(mUrl.getText().toString()); Log.d(TAG, "Save: Grabar URL"); } if ((mComentario.getText() != null) && (!mComentario.getText().toString().equals(""))) { mLugar.setComentario(mComentario.getText().toString()); Log.d(TAG, "Save: Grabar Comentario"); System.currentTimeMillis(); } // No es necesario chequeo, porque por defecto ya tiene un valor; "Otros" mLugar.setTipoLugar(TipoLugar.values()[mTipoLugar.getSelectedItemPosition()]); Lugares.actualizarLugar(mID, mLugar); // Guardar datos en la BBDD Intent i = new Intent(); i.putExtra(VistaLugarActivity.EXTRA, mID); setResult(RESULT_OK, i); finish(); return true; } else if (id == R.id.edit_cancel){ if (mIsNew){ // Si estamos en Edición a traves de crear un Lugar nuevo // El ID que tenemos es el de la BBDD, pero como en "borrar" usamos un "id+1" aqui para igualar usamos un "id-1" Lugares.borrar(mID); } setResult(RESULT_CANCELED); finish(); return true; } return super.onOptionsItemSelected(item); } }
8608d9b3fd985e97e949854d5a8d192881f29e93
[ "Java" ]
3
Java
jjprada/MisLugares
9bd430e7bca4469329cc99f978c7bb084e98f5d7
120b73222dfff9b3c79b12d541777fc41898356b
refs/heads/master
<repo_name>aubuchcl/postgresql-news-app<file_sep>/all_files.py import psycopg2 DBNAME = "news" db = psycopg2.connect(database=DBNAME) c = db.cursor() # articles query and sort articles = '''select title, path, count(path) as visits from articles, log where log.path = CONCAT('/article/', articles.slug) group by path, title order by visits desc limit 3;''' c.execute(articles) pop_articles = c.fetchall() print('articles data') for row in pop_articles: print ('{} - {} views'.format(row[0], row[2])) print("-"*25) print("*"*25) print("-"*25) # author sort and query visitview = '''create view visitview as select name, author, title, path, count(path) as visits from articles, log, authors where log.path = CONCAT('/article/', articles.slug) and articles.author = authors.id group by path, title, name, author order by visits desc;''' c.execute(visitview) c.execute('''select name, sum(visits) as total from visitview group by name order by total desc limit 3;''') authors = c.fetchall() print('author data') for row in authors: print('{} -- {} views'.format(row[0], row[1])) print("-"*25) print("*"*25) print("-"*25) # request success rate query and sort successrate = '''CREATE VIEW successrate AS SELECT time::date, SUM( CASE WHEN status = '200 OK' THEN 1 ELSE 0 END ) AS success, SUM( CASE WHEN status = '404 NOT FOUND' THEN 1 ELSE 0 END ) AS fail FROM log group by time::date;''' c.execute(successrate) c.execute('''select *, to_char(time, 'Mon DD, YYYY'), ROUND(fail/(fail+success)::numeric*100,2) as failure_rate from successrate ''') failure_rate = c.fetchall() print('failure rate') for row in failure_rate: if int(row[4]) > 1: print('{} -- {}% errors'.format(row[3], row[4])) print("-"*25) print("*"*25) print("-"*25) print("THANK YOU!"*5)<file_sep>/README.md Vagrant setup was not working so the following command will work as long as you have some type of db server application to run (I am using postico) here is the link the the lesson that has the newsdata.zip https://classroom.udacity.com/nanodegrees/nd004-connect/parts/52f50785-064e-4221-9227-e5c076a840d0/modules/bc51d967-cb21-46f4-90ea-caf73439dc59/lessons/262a84d7-86dc-487d-98f9-648aa7ca5a0f/concepts/a9cf98c8-0325-4c68-b972-58d5957f1a91 I would have added the newsdata.sql file but git would not allow a file of this size and the large file system I researched would not work (from command line) steps 1. psql 2. CREATE DATABASE news; 3. \i newsdata.sql 4. \d articles (to make sure articles db has properly populated) 5. \d authors and \d log for the others this should have the database set up from this point please run each file as follows - from the command line and inside the directory you have cloned these files into: -- run each file as so: python 'filename' if you would like to run all queries at once you can run python all_files.py<file_sep>/topthreeauthor.py import psycopg2 DBNAME = "news" db = psycopg2.connect(database=DBNAME) c = db.cursor() # query = "select * from articles" # c.execute(query) # rows = c.fetchall() # # print("row data") # print(rows) visitview = '''create view visitview as select name, author, title, path, count(path) as visits from articles, log, authors where log.path = CONCAT('/article/', articles.slug) and articles.author = authors.id group by path, title, name, author order by visits desc;''' c.execute(visitview) c.execute('''select name, sum(visits) as total from visitview group by name order by total desc limit 3;''') authors = c.fetchall() print('author data') print(authors) for row in authors: print('{} -- {} views'.format(row[0], row[1]))<file_sep>/topthreearticle.py import psycopg2 DBNAME = "news" db = psycopg2.connect(database=DBNAME) c = db.cursor() # example of db api # query = "select * from articles" # c.execute(query) # rows = c.fetchall() # # print("row data") # print(rows) articles = '''select title, path, count(path) as visits from articles, log where log.path = CONCAT('/article/', articles.slug) group by path, title order by visits desc limit 3;''' c.execute(articles) pop_articles = c.fetchall() # print(pop_articles[0]) # print(pop_articles[0][0]) # print(pop_articles[0][1]) # print(pop_articles[0][2]) print('articles data') for row in pop_articles: print ('{} - {} views'.format(row[0], row[2])) <file_sep>/requests.py import psycopg2 DBNAME = "news" db = psycopg2.connect(database=DBNAME) c = db.cursor() # example of db api # query = "select * from articles" # c.execute(query) # rows = c.fetchall() # # print("row data") # print(rows) successrate = '''CREATE VIEW successrate AS SELECT time::date, SUM( CASE WHEN status = '200 OK' THEN 1 ELSE 0 END ) AS success, SUM( CASE WHEN status = '404 NOT FOUND' THEN 1 ELSE 0 END ) AS fail FROM log group by time::date;''' c.execute(successrate) # execute actual query # c.execute('''select # *, ROUND(fail/(fail+success)::numeric*100,2) as failure_rate # from # successrate # ''') c.execute('''select *, to_char(time, 'Mon DD, YYYY'), ROUND(fail/(fail+success)::numeric*100,2) as failure_rate from successrate ''') failure_rate = c.fetchall() print('failure rate') # print(failure_rate) # print('{} -- {}'.format(failure_rate[0][0], failure_rate[0][3])) for row in failure_rate: if int(row[4]) > 1: print('{} -- {}% errors'.format(row[3], row[4]))
ac9491033deeadb7d3b8eb54047115b811f7bf53
[ "Markdown", "Python" ]
5
Python
aubuchcl/postgresql-news-app
b5063efd3b7e470bbc95decd082b12ee8fbb8e2a
066116b76a9322275164f70318c0257744ec72af
refs/heads/master
<repo_name>Faisto/RucheConnecte<file_sep>/GestionRuche/GestionRuche/Alert.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GestionRuche { class Alert { public int Id { get; set; } public DateTime Date { get; set; } public bool AlertA { get; set; } public TypeA TypeAId { get; set; } public Hive HiveId { get; set; } } } <file_sep>/GestionRuche/GestionRuche/Test.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GestionRuche { class Test { public int Id { get; set; } public bool Result { get; set; } public User UserId { get; set; } public Image ImageId { get; set; } } } <file_sep>/GestionRuche/GestionRuche/Hive.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GestionRuche { class Hive { public int Id { get; set; } public string Name { get; set; } public string Description { get; set; } public int InitWeight { get; set; } public bool Active { get; set; } public User UserId { get; set; } } } <file_sep>/GestionRuche/GestionRuche/Wieght.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GestionRuche { class Wieght { public int Id { get; set; } public DateTime Date { get; set; } public int wieght { get; set; } public Hive HiveId { get; set; } } } <file_sep>/GestionRuche/GestionRuche/Image.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GestionRuche { class Image { public int Id { get; set; } public bool Result { get; set; } public DateTime Date { get; set; } public string ImagePos { get; set; } public User UserId { get; set; } public Hive HiveId { get; set; } } } <file_sep>/GestionRuche/GestionRuche/Statistic.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GestionRuche { class Statistic { public int Id { get; set; } public DateTime Date { get; set; } public int Temperature { get; set; } public int Humidity { get; set; } public int AirQuality { get; set; } public Hive HiveId { get; set; } } }
5b59b59dc4bc1a8a378e1c2fd172e70933e8a872
[ "C#" ]
6
C#
Faisto/RucheConnecte
44131fc090c20920369cf6f67d01bcf85c217626
4d13bd83b2ca12f18c0272fd6f900f95b9f081fc
refs/heads/master
<repo_name>DennasTrue/soalshift_modul1_A12<file_sep>/Soal1.sh a=1 for gambar in /home/insane/Downloads/nature/*.jpg do base64 -d $gambar | xxd -r > /home/insane/Downloads/nature/$a.jpg a=$((a+1)) done <file_sep>/Soal5.sh awk '/!sudo/&&/cron/||/CRON/' /var/log/syslog | awk 'NF <13' >>~/modul1/syslogno5.log <file_sep>/soal2.sh echo "No 2 A" echo " " awk -F ',' '{if($7 == '2012') a[$1]+=$10} END {for(b in a) {print b}}' ~/WA_Sales_Products_2012-14.csv | sort -nr | head -1 echo " " echo "No 2 B" echo " " awk -F ',' '$1 ~/United States/ {if($7 == '2012') a[$4]+=$10} END {for(b in a) {print a[b]" "b}}' ~/WA_Sales_Products_2012-14.csv | sort -nr | head -3 echo " " echo "No 2 C" echo " " awk -F ',' '{if($4 == "Personal Accessories" || $4 == "Camping Equipment" || $4 == "Outdoor Protection") a[$6]+=$10} END {for(b in a) {print a[b]" "b}}' WA_Sales_Products_2012-14.csv | sort -nr | head -3
0c135683e175318d113c5cdc439c8dc6a79576f0
[ "Shell" ]
3
Shell
DennasTrue/soalshift_modul1_A12
529a37f5de691d2463937aa9f1762e31d570a98c
cb95365bd6dc173c931d547b5dc8e5a3a5568b05
refs/heads/master
<file_sep>package com.naldana.ejemplo08 import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import com.naldana.ejemplo08.models.Pokemon import kotlinx.android.synthetic.main.list_item_pokemon.view.* class PokemonAdapter(val listaPokemons: List<Pokemon>) : RecyclerView.Adapter<PokemonAdapter.ViewHolder>() { // TODO: Para contar elementos creados private var countViews: Int = 0 override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view = LayoutInflater.from(parent.context) .inflate(R.layout.list_item_pokemon, parent, false) /* * TODO: Muestra el valor de contador de view creadas solo se hace aqui, para asegurar * que solo se asigne el valor aqui */ view.findViewById<TextView>(R.id.count_element).text = countViews.toString() countViews++ return ViewHolder(view) } override fun getItemCount(): Int { return listaPokemons.size } override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.bind(listaPokemons[position]) } class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { fun bind(item: Pokemon) = with(itemView) { tv_pokemon_name.text = item.name tv_pokemon_id.text = item.id.toString() } } }<file_sep>package com.naldana.ejemplo08 import android.os.AsyncTask import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import com.naldana.ejemplo08.models.Pokemon import com.naldana.ejemplo08.network.HttpHandler import kotlinx.android.synthetic.main.activity_main.* import org.json.JSONException import org.json.JSONObject class MainActivity : AppCompatActivity() { private lateinit var viewAdapter: PokemonAdapter private lateinit var viewManager: RecyclerView.LayoutManager lateinit var poke: MutableList<Pokemon> override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) initRecycler() GetPokemons().execute() } fun initRecycler(){ /** var pokemon: MutableList<Pokemon> = MutableList(100) {i -> Pokemon(i,"Name") }**/ viewManager = LinearLayoutManager(this) viewAdapter = PokemonAdapter(poke) rv_pokemon_list.apply { setHasFixedSize(true) layoutManager = viewManager adapter = viewAdapter } } private inner class GetPokemons : AsyncTask<Void, Void, Void>() { override fun onPreExecute() { super.onPreExecute() } override fun doInBackground(vararg arg0: Void): Void? { val sh = HttpHandler() val url = "https://pokeapi.co/api/v2/pokemon/?offset=0&limit=300" val jsonStr = sh.makeServiceCall(url) //Log.d(TAG,jsonStr); if (jsonStr != null) { try { //Log.d(TAG,"ENTRANDO AL TRY"); //SE OBTIENE EL JSON COMPLETO val jsonObj = JSONObject(jsonStr) //SE OBTIENE EL NOMBRE DEL ARREGLO val pokemon = jsonObj.getJSONArray("results") for (i in 0 until pokemon.length()) { //SE OBTIENE EL INDICE DEL OBJETO val c = pokemon.getJSONObject(i) //SE OBTIENE EL ATRIBUTO QUE SE QUIERE AGREGAR A LA LISTA val name = c.getString("name").toUpperCase() //Log.d(TAG,name); poke= MutableList(100) {i -> Pokemon(i,name) } //HashMap<String, String> pokeDex = new HashMap<>(); // pokeDex.put("name", name); // pokemonList.add(pokeDex); } } catch (e: JSONException) { e.printStackTrace() } } else { //Log.e(TAG, "No se pudo obtener el JSON"); } return null } override fun onPostExecute(result: Void) { super.onPostExecute(result) } } } <file_sep>package com.naldana.ejemplo08.models //data class Pokemon(val id: Int,val name: String, val type: String) data class Pokemon(val id: Int,val name: String)<file_sep>package com.naldana.ejemplo08 import android.os.AsyncTask import android.util.Log import com.naldana.ejemplo08.network.HttpHandler import org.json.JSONArray import org.json.JSONException import org.json.JSONObject class AsyncTaskClass { private inner class GetPokemons : AsyncTask<Void, Void, Void>() { override fun onPreExecute() { super.onPreExecute() } override fun doInBackground(vararg arg0: Void): Void? { val sh = HttpHandler() val url = "https://pokeapi.co/api/v2/pokemon/?offset=0&limit=300" val jsonStr = sh.makeServiceCall(url) //Log.d(TAG,jsonStr); if (jsonStr != null) { try { //Log.d(TAG,"ENTRANDO AL TRY"); //SE OBTIENE EL JSON COMPLETO val jsonObj = JSONObject(jsonStr) //SE OBTIENE EL NOMBRE DEL ARREGLO val pokemon = jsonObj.getJSONArray("results") for (i in 0 until pokemon.length()) { //SE OBTIENE EL INDICE DEL OBJETO val c = pokemon.getJSONObject(i) //SE OBTIENE EL ATRIBUTO QUE SE QUIERE AGREGAR A LA LISTA val name = c.getString("name").toUpperCase() //Log.d(TAG,name); //HashMap<String, String> pokeDex = new HashMap<>(); // pokeDex.put("name", name); // pokemonList.add(pokeDex); } } catch (e: JSONException) { e.printStackTrace() } } else { //Log.e(TAG, "No se pudo obtener el JSON"); } return null } override fun onPostExecute(result: Void) { } } }
119abf85f29c3ff059cd8e603fd8db9a75d1c49c
[ "Kotlin" ]
4
Kotlin
danielorozco14/PokedexKotlin
302437149b46c5ab9d0b8738e3a58f61bcd900f7
0fe4420d77440aa567258ea198d003d15ee8410c
refs/heads/master
<file_sep>default_app_config = 'testproj.accounts.apps.AccountsConfig' <file_sep>""" Django settings for testproj project. Generated by 'django-admin startproject' using Django 1.10.5. For more information on this file, see https://docs.djangoproject.com/en/1.10/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.10/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(__file__) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'dev_secret_key' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'grappelli', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', # third party apps 'crispy_forms', 'imagekit', 'widget_tweaks', 'django_countries', 'django_extensions', 'rest_framework', # forks 'testproj.registration', # custom apps 'testproj.accounts', 'testproj.landing', 'testproj.utils', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'testproj.urls' SITE_ID = 1 TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates'), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'testproj.wsgi.application' # Database # https://docs.djangoproject.com/en/1.10/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'db_name_testproject', 'USER': 'db_user_testproject', 'PASSWORD': '<PASSWORD>', 'HOST': '127.0.0.1', } } # Password validation # https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.10/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.10/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = '/var/webapps/testproj/www/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] # Cache CACHES = { 'default': { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': 'redis://127.0.0.1:6379/1', 'OPTIONS': { 'CLIENT_CLASS': 'django_redis.client.DefaultClient', } } } # Media MEDIA_URL = '/media/' MEDIA_ROOT = '/var/webapps/testproj/www/media/' # Grapelli Admin Theme GRAPPELLI_ADMIN_TITLE = 'TestProject Project' # Fork of Registration Redux INCLUDE_REGISTER_URL = False # for basic stuff DISABLE_REGISTRATION = False # for other stuff from registration, for example token management LOGIN_REDIRECT_URL = "landing:main_page" # Django braces LOGIN_URL = "auth_login" # it will be lazy urlresolved than # CELERY SETTINGS BROKER_URL = 'redis://localhost:6379/0' CELERY_ACCEPT_CONTENT = ['json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_RESULT_BACKEND = 'redis://localhost:6379/0' # Crispy Forms CRISPY_TEMPLATE_PACK = 'bootstrap3' # Rest Framework REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', ) } <file_sep>default_app_config = 'testproj.landing.apps.LandingConfig' <file_sep>from django.conf.urls import url, include from django.conf import settings from django.conf.urls.static import static from django.contrib import admin urlpatterns = [ url(r'^', include('testproj.landing.urls', namespace='landing')), url(r'^accounts/', include('testproj.accounts.urls', namespace='accounts')), url(r'^auth/', include('testproj.registration.backends.default.urls')), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^grappelli/', include('grappelli.urls')), url(r'^admin/', admin.site.urls), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) <file_sep>{% extends 'base.html' %} {% load i18n %} {% load static %} {% load breadcrumbs %} {% block title %} {{ block.super }} | {{ profile.user.get_full_name }} {% endblock %} {% block breadcrumb %} <div class="row wrapper border-bottom white-bg page-heading"> <div class="col-lg-9"> <h2>Profile</h2> <ol class="breadcrumb"> <li class=""> {% breadcrumb_url "Home" 'landing:main_page' %} </li> <li class="active"> <strong>{{ request.user.get_full_name }}</strong> </li> </ol> </div> </div> {% endblock breadcrumb %} {% block body %} <div class="row m-b-lg m-t-lg"> <div class="btn-group pull-right"><a class="btn btn-w-m btn-success" href="{% url 'accounts:profile_update' request.user.profile.slug %}" type="button">Edit <span class=""><i class="fa fa-cog"></i></span></a></div> <div class="col-md-2"> <div class=""> <img src="{{ profile.get_avatar_sm }}" class="img-circle circle-border m-b-md" alt="profile"> </div> </div> <div class="col-md-6"> <div class="ibox-content"> <div class=""> <div> <h2 class="no-margins"> {{ profile.user.get_full_name }} </h2> <br> <address> <strong>{{ profile.user.username|default_if_none:"-" }}</strong> <br> {{ profile.address_line1|default_if_none:"-" }} <br> {{ profile.address_line2|default_if_none:"-" }} <br> {{ profile.city|default_if_none:"-" }} <br> {{ profile.state.name|default_if_none:"-" }} <br> {{ profile.postal|default_if_none:"-" }} <br> {{ profile.dob|default_if_none:"-" }} <br> <abbr title="Phone">P:</abbr> {{ profile.phone|default_if_none:"-" }} <br> <abbr title="Cell Phone">Mobile:</abbr> {{ profile.cell|default_if_none:"-" }} </address> </div> </div> </div> </div> </div> {% endblock body %}<file_sep>from django import template register = template.Library() @register.simple_tag(takes_context = True) def toggle_menu(context): request = context['request'] result = request.COOKIES.get('menu_toggle', None) if result and result=='true': return "mini-navbar" else: return "" <file_sep>from django.conf.urls import url from .views import ( ProfileDetailView, ProfileUpdateView ) urlpatterns = [ url(r'^(?P<slug>[-\w]+)/$', ProfileDetailView.as_view(), name='profile_detail'), url(r'^(?P<slug>[-\w]+)/update/$', ProfileUpdateView.as_view(), name='profile_update'), ] <file_sep>Vagrant.configure("2") do |config| config.vm.box = "ubuntu/trusty64" # config.vm.synced_folder ".", "/var/webapps/testproj/code", # owner: "testuser_dev", group: "users" config.vm.box_check_update = false config.vm.network :private_network, ip: "172.16.0.39" config.vm.network :forwarded_port, guest: 22, host: 2322, id: "ssh" config.ssh.insert_key=false config.vm.provider "virtualbox" do |v| v.memory = 512 v.cpus = 1 v.name = "DjangoSeedProject" end end <file_sep>appdirs packaging Django Django-Select2 Faker Pillow awesome-slugify celery django-autoslug django-bootstrap3 django-braces django-celery-email django-ckeditor django-compressor django-countries django-crispy-forms django-debug-panel django-debug-toolbar django-extensions django-grappelli django-htmlmin django-imagekit django-model-utils django-recaptcha django-redis django-widget-tweaks djangorestframework flower gunicorn html5lib ipython psycopg2 redis<file_sep>from django.http import Http404 from django.conf import settings from django.contrib import messages from django.views.generic import DetailView from django.views.generic.edit import UpdateView from django.core.urlresolvers import reverse_lazy from django.utils.translation import ugettext as _ from braces.views import LoginRequiredMixin from .models import Profile from .forms import ProfileUpdateForm class ProfileDetailView(LoginRequiredMixin, DetailView): model = Profile template_name = 'accounts/profile.html' def get_object(self): if not Profile.objects.filter(slug=self.kwargs['slug']).exists(): raise Http404 elif self.request.user.profile != Profile.objects.get(slug=self.kwargs['slug']) and not self.request.user.is_staff: raise Http404 return self.get_queryset().get(slug=self.kwargs['slug']) class ProfileUpdateView(LoginRequiredMixin, UpdateView): template_name = 'accounts/profile_update.html' form_class = ProfileUpdateForm def get_object(self): return self.request.user.profile def get_context_data(self, **kwargs): context = super(ProfileUpdateView, self).get_context_data(**kwargs) return context def get_success_url(self): messages.success(self.request, _('Profile updated successfully')) return reverse_lazy('accounts:profile_detail', kwargs={'slug': self.request.user.profile.slug}) <file_sep>from django.conf import settings from django.views.generic import TemplateView from django.core.urlresolvers import reverse_lazy from braces.views import LoginRequiredMixin class MainPageView(LoginRequiredMixin, TemplateView): template_name = 'landing/main_page.html'
6a1371567c2e6143faf11a812c55b02f54559d58
[ "Text", "Python", "Ruby", "HTML" ]
11
Python
ArtemBernatskyy/Django-Seed-Project
4d25c750c40be30be21e1d03a527bcacc3e89a48
58e3aedfdfb3950b5a72b8f9c84aa72e18794a92
refs/heads/master
<file_sep><?php use block_lp\output\summary; //moodleform is defined in formslib.php require_once("$CFG->libdir/formslib.php"); require_once("$CFG->libdir/outputcomponents.php"); //moodleform is defined in formslib.php require_once("$CFG->libdir/formslib.php"); class test_form extends moodleform { //Add elements to form public function definition() { global $CFG,$DB; $mform =& $this->_form; // Don't forget the underscore! //エントリエディットフォーム //活動内容 //$mform->addElement('header', 'body', get_string('body', 'researchreport')); $mform->addElement('header', 'body', '活動内容'); //研究内容のエディター作成 // $mform->addElement('editor', 'entry', get_string('body', 'researchreport'), null, $entryoptions); $mform->addElement('editor', 'entry', '活動内容を入力'); $mform->setType('entry', PARAM_RAW); //デフォルトでエディターに表示させるテキスト $mform->setDefault('entry', array('text'=>'研究内容エディタ')); //ファイルピッカー //$mform->addElement('filemanager', 'attachment_filemanager', get_string('attachment', 'forum'), null, $attachmentoptions); //達成度の配列 $scorearray = array( 'val1' => '100', 'val2' => '80', 'val3' => '60', 'val4' => '40', 'val5' => '20', 'val6' => '0' ); //達成度セレクタ作成 $mform->addElement('header', 'score', '評価'); $mform->addElement('select','score_select', '評価',$scorearray); $timearray = array( 'val_1' => '0.5', 'val_2' => '1', 'val_3' => '1.5', 'val_4' => '2', 'val_5' => '2.5', 'val_6' => '3', 'val_7' => '3.5', 'val_8' => '4', 'val_9' => '4.5', 'val_10' => '5', 'val_11' => '5.5', 'val_12' => '6', 'val_13' => '6.5', 'val_14' => '7', 'val_15' => '7.5', 'val_16' => '8', 'val_17' => '8.5', 'val_18' => '9', 'val_19' => '9.5', 'val_20' => '10', 'val_21' => '10.5', 'val_22' => '11', 'val_23' => '11.5', 'val_24' => '12', ); //研究時間 $mform->addElement('header', 'time', '時間'); $mform->addElement('select', 'time_select', '研究時間を選択', $timearray); //講義時間 $mform->addElement('header', 'time', '時間'); $mform->addElement('select', 'time_select', '研究時間を選択', $timearray); //送信ボタン $this->add_action_buttons(); } //Custom validation should be added here function validation($data, $files) { global $CFG, $DB, $USER; return array(); } } class progress_form extends moodleform { //Add elements to form public function definition() { global $CFG,$DB; $mform =& $this->_form; // Don't forget the underscore! //エントリエディットフォーム //研究内容の作成 $mform->addElement('header', 'body', '課題'); //研究内容のエディター作成 $mform->addElement('editor', 'progress_task', '課題の入力'); $mform->setType('progress_task', PARAM_RAW); //デフォルトでエディターに表示させるテキスト $mform->setDefault('progress_task', array('text'=>'section')); //ファイルピッカー //$mform->addElement('filemanager', 'attachment_filemanager', get_string('attachment', 'forum'), null, $attachmentoptions); //達成度の配列 $scorearray = array( 'val1' => '100', 'val2' => '80', 'val3' => '60', 'val4' => '40', 'val5' => '20', 'val6' => '0' ); //達成度セレクタ作成 $mform->addElement('header', 'score', '評価'); $mform->addElement('select','score_select', '評価', $scorearray); //送信ボタン $this->add_action_buttons(); } //Custom validation should be added here function validation($data, $files) { global $CFG, $DB, $USER; return array(); } } class activity_form extends moodleform { //Add elements to form public function definition() { global $CFG,$DB; $mform =& $this->_form; // Don't forget the underscore! //エントリヘッダ $mform->addElement('header', 'body', '活動'); //エントリエディタ $mform->addElement('editor', 'summary', '今日の活動を入力して下さい'); $mform->setType('summary', PARAM_RAW); $mform->addRule('summary', '必須','required', null); //デフォルトでエディターに表示させるテキスト $mform->setDefault('summary', array('text'=>'')); $mform->addElement('header', 'body', '課題'); //エントリエディタ $mform->addElement('editor', 'task', '次にやる予定の課題を入力して下さい'); $mform->setType('task', PARAM_RAW); $mform->addRule('task', '必須','required', null); // $mform->addHelpButton('task', 'あいうえお','ここに入力'); //デフォルトでエディターに表示させるテキスト $testmessage = $USER->username; echo $testmessage; $mform->setDefault('task', array('text'=>'')); // //タスクヘッダー // $mform->addElement('header', 'body', '評価'); // //タスクエディタ // $mform->addElement('editor', 'evalution', '評価の入力'); // $mform->setType('entry', PARAM_RAW); // $mform->setDefault('evalutionk', array('text'=>'デフォルト評価')); //タイムヘッダ $mform->addElement('header', 'body', '活動時間'); //活動開始終了時間用配列 $timearray = array( '0000'=>'0:00', '0100'=>'1:00', '0200'=>'2:00', '0300'=>'3:00', '0400'=>'4:00', '0500'=>'5:00', '0600'=>'6:00', '0700'=>'7:00', '0800'=>'8:00', '0900'=>'9:00', '1000'=>'10:00', '1100'=>'11:00', '1200'=>'12:00', '1300'=>'13:00', '1400'=>'14:00', '1500'=>'15:00', '1600'=>'16:00', '1700'=>'17:00', '1800'=>'18:00', '1900'=>'19:00', '2000'=>'20:00', '2100'=>'21:00', '2200'=>'22:00', '2300'=>'23:00', '2400'=>'24:00', ); //活動開始時間セレクタ $select = $mform->addElement('select','sttime', '開始時間', $timearray); $select->setSelected('0900'); $mform->addRule('sttime', '必須','required', null); //活動開始時間セレクタ $select = $mform->addElement('select','edtime', '終了時間', $timearray); $select->setSelected('1800'); $mform->addRule('edtime', '必須','required', null); //研究時間用配列 $acttimearray = array( '0'=>'0', '1'=>'1', '2'=>'2', '3'=>'3', '4'=>'4', '5'=>'5', '6'=>'6', '7'=>'7', '8'=>'8', '9'=>'9', '10'=>'10', '11'=>'11', '12'=>'12'); //タイムセレクタ $select = $mform->addElement('select','acttime', '研究時間', $acttimearray); // $select->setSelected('5'); $mform->addRule('acttime', '必須','required', null); $select = $mform->addElement('select','studytime', '勉強時間', $acttimearray); // $select->setSelected('3'); $mform->addRule('studytime', '必須','required', null); //スコア配列 $scorearray = array( '10'=>'10', '20'=>'20', '30'=>'30', '40'=>'40', '50'=>'50', '60'=>'60', '70'=>'70', '80'=>'80', '90'=>'90', '100'=>'100' ); //スコアヘッダ $mform->addElement('header', 'body', '評価'); //スコアセレクタ $select = $mform->addElement('select','evalution', '評価', $scorearray); $select->setSelected('50'); $mform->addRule('evalution', '必須','required', null); // //スコアヘッダ // $mform->addElement('header', 'body', '評価'); // //スコアセレクタ // $mform->addElement('select','task', '評価', $scorearray); //送信ボタン $this->add_action_buttons(); } //Custom validation should be added here function validation($data, $files) { global $CFG, $DB, $USER; return array(); } } <file_sep><?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Prints a particular instance of researchreport * researchreportの特定のインスタンスを出力する。 * * You can have a rather longer description of the file as well, * if you like, and it can span multiple lines. * あなたはファイルの説明をもっと長くすることができますが、 * あなたが好きなら、複数の行にまたがることができる。 * * @package mod_researchreport * @copyright 2016 Your Name <<EMAIL>> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ // Replace researchreport with the name of your module and remove this line. require_once(dirname(dirname(dirname(__FILE__))).'/config.php'); require_once(dirname(__FILE__).'/lib.php'); require_once("$CFG->libdir/outputcomponents.php"); require_once("$CFG->libdir/navigationlib.php"); require_once('./rr_form.php'); //pChart sample include($CFG->dirroot.'/mod/researchreport/pChart/class/pData.class.php'); include($CFG->dirroot.'/mod/researchreport/pChart/class/pDraw.class.php'); include($CFG->dirroot.'/mod/researchreport/pChart/class/pImage.class.php'); // $userid = optional_param('userid', 0, PARAM_INT); $id = optional_param('id', 0, PARAM_INT); // Course Module ID $r = optional_param('n', 0, PARAM_INT); // ResearchReport ID $userid = optional_param('userid', null, PARAM_INT); if ($id) { $cm = get_coursemodule_from_id('researchreport', $id, 0, false, MUST_EXIST); $course = $DB->get_record('course', array('id' => $cm->course), '*', MUST_EXIST); $researchreport = $DB->get_record('researchreport', array('id' => $cm->instance), '*', MUST_EXIST); } else if ($r) { $researchreport = $DB->get_record('researchreport', array('id' => $r), '*', MUST_EXIST); $course = $DB->get_record('course', array('id' => $researchreport->course), '*', MUST_EXIST); $cm = get_coursemodule_from_instance('researchreport', $researchreport->id, $course->id, false, MUST_EXIST); } else { error('You must specify a course_module ID or an instance ID'); } require_login($course, true, $cm); // Conditions to show the intro can change to look for own settings or whatever. if ($researchreport->intro) { echo $OUTPUT->box(format_module_intro('researchreport', $researchreport, $cm->id), 'generalbox mod_introbox', 'researchreportintro'); } $event = \mod_researchreport\event\course_module_viewed::create(array( 'objectid' => $PAGE->cm->instance, 'context' => $PAGE->context, )); $event->add_record_snapshot('course', $PAGE->course); $event->add_record_snapshot($PAGE->cm->modname, $researchreport); $event->trigger(); // Print the page header. //$PAGE->set_pagelayout('standard'); $PAGE->set_url('/mod/researchreport/view.php', array( 'id' =>$cm->id )); //$PAGE->navbar->add('navbarsample', new moodle_url('/mod/researchreport/view.php', array('id' =>$cm->id)); $PAGE->set_title(format_string($researchreport->name)); $PAGE->set_heading(format_string($course->fullname)); /* * Other things you may want to set - remove if not needed. * $PAGE->set_cacheable(false); * $PAGE->set_focuscontrol('some-html-id'); * $PAGE->add_body_class('researchreport-'.$somevar); */ // Output starts here.ページに表示するのはここから echo $OUTPUT->header(); // Replace the following lines with you own code. //ここからmain記述 echo $OUTPUT->heading('research report'); //研究進捗フォームへのリンク // $addurl = new moodle_url("$CFG->wwwroot/mod/researchreport/progress_form.php"); // $addlink = '<div class="addentrylink">'; // $addlink .= '<a href="'.$addurl->out().'">'. '研究進捗を記録する'.'</a>'; // $addlink .= '<a href="'.$addurl->out().'">'.'</a>'; // $addlink .= '</div>'; // echo $addlink; //mixsample // echo "<div style='float:center; width:50%;'> // <p><img src='mixchartsample.png' /></div></p>"; //研究活動 フォームへのリンク $addurl = new moodle_url("$CFG->wwwroot/mod/researchreport/activity_form.php", array( 'userid' =>$USER->id )); $addlink = '<p><a href="'.$addurl->out().'">'. '個人活動を記録する'.'</a></p>'; echo $addlink; //全ての活動へのリンク $addurl = new moodle_url("$CFG->wwwroot/mod/researchreport/allactivity.php"); $addlink = '<p><a href="'.$addurl->out().'">'. '全ての活動'.'</a></p>'; echo $addlink; $addurl = new moodle_url("$CFG->wwwroot/mod/researchreport/personal_activity.php", array( 'userid' =>$USER->id )); $addlink = '<p><a href="'.$addurl->out().'">'. '個人の記録'.'</a></p>'; echo $addlink; //useridの最大値を取得 $maxuserid = $DB->get_records_sql("SELECT max(userid) FROM mdl_rrpost "); $maxuserid = key($maxuserid); //昇順比較 $alluserid = $DB->get_records_sql("SELECT DISTINCT userid FROM mdl_rrpost"); // debug_dump($alluserid); $alluserid = array_keys($alluserid); // debug_dump($alluserid); foreach($alluserid as $key_1 => $val_1){ $getdata = $DB->get_records_sql("SELECT * FROM mdl_rrpost WHERE userid = $val_1"); $getdata = array_merge($getdata,array()); foreach($getdata as $key_2 => $val_2); $cmpdata[$key_1]->date = $getdata[$key_2]->created; $cmpdata[$key_1]->userid = $getdata[$key_2]->userid; } foreach($cmpdata as $key =>$val){ $sort[$key] = $val->date; } array_merge($sort); array_multisort($sort, SORT_DESC, $cmpdata); // debug_dump($cmpdata); // debug_dump($sort); // echo 'ここまで'; //チャート生成のカウンタ $pcount=0; foreach($cmpdata as $key => $val){ // echo $key,':1st<br>'; $userid = $cmpdata[$key]->userid; $getdata = $DB->get_records_sql("SELECT * FROM mdl_rrpost WHERE userid = $userid"); $getdata = array_merge($getdata,array()); $username = $DB->get_records_sql("SELECT username FROM mdl_user WHERE id = $userid"); $username = key($username); $personalurl = new moodle_url("$CFG->wwwroot/mod/researchreport/personal_activity.php", array( 'userid' => $userid )); $personallink = '<a href="'.$personalurl->out().'">'. $username.'</a>'; //getdataから必要なデータだけ取り出す $encodedata = new stdClass(); $encodedata->userid = array(); $encodedata->acttime = array(); $encodedata->studytime = array(); $encodedata->evalution = array(); $encodedata->timemd = array(); // debug_dump($encodedata); //最新7日間の値だけ取得する // foreach($getdata as $key => $val){ foreach($getdata as $key => $val){ // echo $key,':2nd<br>'; // echo $key; array_push($encodedata->userid,$getdata[$key]->userid); array_push($encodedata->acttime,$getdata[$key]->acttime); array_push($encodedata->studytime,$getdata[$key]->studytime); array_push($encodedata->evalution,$getdata[$key]->evalution); array_push($encodedata->timemd,$getdata[$key]->timemd); } // debug_dump($encodedata); //最新の活動内容と更新時間の取得 $newestp = new stdClass(); $newestp->date = $getdata[$key]->created; $newestp->post = $getdata[$key]->summary; $newestp->task = $getdata[$key-1]->task; // debug_dump($newestp); //最新1週間分を取得 $pdrawdata = new stdClass(); $pdrawdata->userid = array(); $pdrawdata->acttime = array(); $pdrawdata->studytime = array(); $pdrawdata->sumtime = array(); $pdrawdata->evalution = array(); $pdrawdata->timemd = array(); for($i=6;$i>=0;$i--){ array_push($pdrawdata->userid,$encodedata->userid[$key-$i]); array_push($pdrawdata->acttime,$encodedata->acttime[$key-$i]); array_push($pdrawdata->studytime,$encodedata->studytime[$key-$i]); array_push($pdrawdata->sumtime,$encodedata->acttime[$key-$i] + $encodedata->studytime[$key-$i]); array_push($pdrawdata->evalution,$encodedata->evalution[$key-$i]); array_push($pdrawdata->timemd,$encodedata->timemd[$key-$i]); } //setting_activitytime_chart $myData = new pData(); $myData->addPoints($pdrawdata->acttime,"Serie1"); // $myData->setPalette("Serie1", array("R"=>51,"G"=>153,"B"=>150)); $myData->setSerieDescription("Serie1",activity); $myData->setSerieOnAxis("Serie1",0); $myData->addPoints($pdrawdata->studytime,"Serie2"); // $myData->setPalette("Serie1", array("R"=>51,"G"=>153,"B"=>150)); $myData->setSerieDescription("Serie2",study); $myData->setSerieOnAxis("Serie2",0); $myData->addPoints($pdrawdata->timemd,"Absissa"); $myData->setAbscissa("Absissa"); $myData->setAbscissaName("Date"); $myData->setAxisPosition(0,AXIS_POSITION_LEFT); $myData->setAxisName(0,"ActTime"); $myData->setAxisUnit(0,""); $myPicture = new pImage(300,250,$myData); $myPicture->Antialias = FALSE; $myPicture->setFontProperties(array("FontName"=>"fonts/Forgotte.ttf","FontSize"=>18)); $TextSettings = array("Align"=>TEXT_ALIGN_TOPLEFT , "R"=>0, "G"=>0, "B"=>0); $myPicture->drawText(50,10,"Activity",$TextSettings); $myPicture->setGraphArea(50,50,275,210); $myPicture->setFontProperties(array("R"=>0,"G"=>0,"B"=>0,"FontName"=>"fonts/pf_arma_five.ttf","FontSize"=>10)); $Settings = array("Pos"=>SCALE_POS_LEFTRIGHT , "Mode"=>SCALE_MODE_MANUAL , "ManualScale"=>array( 0=>array("Min"=>0,"Max"=>12), // 1=>array("Min"=>0,"Max"=>100) ) , "LabelingMethod"=>LABELING_ALL , "GridR"=>255, "GridG"=>255, "GridB"=>255, "GridAlpha"=>50, "TickR"=>0, "TickG"=>0, "TickB"=>0, "TickAlpha"=>50, "LabelRotation"=>0, "DrawArrows"=>1, "DrawXLines"=>0, "DrawYLines"=>NONE); $myPicture->drawScale($Settings); $Config = array("DisplayValues"=>0, "AroundZero"=>0); // $myPicture->drawBarChart($Config); $myPicture->drawStackedBarChart($Config); $Config = array("FontR"=>0, "FontG"=>0, "FontB"=>0, "FontName"=>"fonts/pf_arma_five.ttf", "FontSize"=>12, "Margin"=>0, "Alpha"=>30, "BoxSize"=>5, "Style"=>LEGEND_NOBORDER , "Mode"=>LEGEND_HORIZONTAL); $myPicture->drawLegend(180,16,$Config); $myPicture->render("$pcount.myActivity.png"); /////////////////////////////////////////////////////////////////////////////////////////////// //setting_Progeress_chart $myData = new pData(); $myData->addPoints($pdrawdata->evalution,"Serie1"); // $myData->setPalette("Serie1",array("R"=>155,"G"=>155,"B"=>155)); $myData->setSerieDescription("Serie1","evalution"); $myData->setSerieOnAxis("Serie1",0); $myData->addPoints($pdrawdata->timemd,"Absissa"); $myData->setAbscissa("Absissa"); $myData->setAbscissaName("Date"); $myData->setAxisPosition(0,AXIS_POSITION_LEFT); $myData->setAxisName(0,"Progress"); $myData->setAxisUnit(0,""); $myPicture = new pImage(300,250,$myData); $myPicture->Antialias = FALSE; $myPicture->setFontProperties(array("FontName"=>"fonts/Forgotte.ttf","FontSize"=>18)); $TextSettings = array("Align"=>TEXT_ALIGN_TOPLEFT , "R"=>0, "G"=>0, "B"=>0); $myPicture->drawText(50,10,"Progress",$TextSettings); $myPicture->setGraphArea(50,50,275,210); $myPicture->setFontProperties(array("R"=>0,"G"=>0,"B"=>0,"FontName"=>"fonts/pf_arma_five.ttf","FontSize"=>10)); $Settings = array("Pos"=>SCALE_POS_LEFTRIGHT , "Mode"=>SCALE_MODE_MANUAL , "ManualScale"=>array(0=>array("Min"=>0,"Max"=>100)) , "LabelingMethod"=>LABELING_ALL , "GridR"=>255, "GridG"=>255, "GridB"=>255, "GridAlpha"=>50, "TickR"=>0, "TickG"=>0, "TickB"=>0, "TickAlpha"=>50, "LabelRotation"=>0, "DrawArrows"=>1, "DrawXLines"=>0, "DrawYLines"=>NONE); $myPicture->drawScale($Settings); $Config = array("DisplayValues"=>0, "AroundZero"=>1); $myPicture->drawAreaChart($Config); $Config = array("FontR"=>0, "FontG"=>0, "FontB"=>0, "FontName"=>"fonts/pf_arma_five.ttf", "FontSize"=>12, "Margin"=>0, "Alpha"=>30, "BoxSize"=>5, "Style"=>LEGEND_NOBORDER , "Mode"=>LEGEND_HORIZONTAL ); $myPicture->drawLegend(200,16,$Config); $myPicture->render("$pcount.myProgress.png"); //////////////////////////////////////////////////////////////// //mix $myData = new pData(); $myData->addPoints($pdrawdata->acttime,"Serie1"); // $myData->setPalette("Serie1", array("R"=>51,"G"=>153,"B"=>150)); $myData->setSerieDescription("Serie1",activitytime); $myData->setSerieOnAxis("Serie1",0); $myData->addPoints($pdrawdata->evalution,"Serie2"); $myData->setSerieDescription("Serie2","evalution"); $myData->setPalette("Serie2", array("R"=>51,"G"=>153,"B"=>150)); $myData->setSerieOnAxis("Serie2",1); $myData->addPoints($pdrawdata->timemd,"Absissa"); $myData->setAbscissa("Absissa"); $myData->setAbscissaName("Date"); $myData->setAxisPosition(0,AXIS_POSITION_LEFT); $myData->setAxisName(0,"ActTime"); $myData->setAxisUnit(0,""); $myData->setAxisPosition(1,AXIS_POSITION_RIGHT); $myData->setAxisName(1,"test"); $myData->setAxisUnit(1,""); $myPicture = new pImage(300,250,$myData); $myPicture->Antialias = FALSE; $myPicture->setFontProperties(array("FontName"=>"fonts/Forgotte.ttf","FontSize"=>18)); $TextSettings = array("Align"=>TEXT_ALIGN_TOPLEFT , "R"=>0, "G"=>0, "B"=>0); $myPicture->drawText(50,10,"Activity",$TextSettings); $myPicture->setGraphArea(50,50,275,210); $myPicture->setFontProperties(array("R"=>0,"G"=>0,"B"=>0,"FontName"=>"fonts/pf_arma_five.ttf","FontSize"=>10)); $Settings = array("Pos"=>SCALE_POS_LEFTRIGHT , "Mode"=>SCALE_MODE_MANUAL , "ManualScale"=>array( 0=>array("Min"=>0,"Max"=>12), 1=>array("Min"=>0,"Max"=>100) ) , "LabelingMethod"=>LABELING_ALL , "GridR"=>255, "GridG"=>255, "GridB"=>255, "GridAlpha"=>50, "TickR"=>0, "TickG"=>0, "TickB"=>0, "TickAlpha"=>50, "LabelRotation"=>0, "CycleBackground"=>1, "DrawXLines"=>1, "DrawSubTicks"=>1, "SubTickR"=>255, "SubTickG"=>0, "SubTickB"=>0, "SubTickAlpha"=>0, "DrawYLines"=>ALL); $myPicture->drawScale($Settings); $Config = array("DisplayValues"=>1, "AroundZero"=>1); $myData->setSerieDrawable("Serie1",TRUE); $myData->setSerieDrawable("Serie2",FALSE); $myPicture->drawBarChart($Config); $myData->setSerieDrawable("Serie1",FALSE); $myData->setSerieDrawable("Serie2",TRUE); $myPicture->drawAreaChart($Config); $myData->setSerieDrawable("Serie1",TRUE);//TRUEに戻しておく $Config = array("FontR"=>0, "FontG"=>0, "FontB"=>0, "FontName"=>"fonts/pf_arma_five.ttf", "FontSize"=>12, "Margin"=>6, "Alpha"=>30, "BoxSize"=>5, "Style"=>LEGEND_NOBORDER , "Mode"=>LEGEND_HORIZONTAL); $myPicture->drawLegend(200,16,$Config); $myPicture->render("mixchartsample.png"); //////////////////////////////////////////////////////////////// //描画 if($pcount%2 == 0){ echo "<div style=' float:left; width:48%;word-wrap: break-word; padding: 0.5em 1em; margin: 0.5em 0; background: #f4f4f4; border-left: solid 6px #f4f1a6; box-shadow: 0px 2px 3px rgba(0, 0, 0, 0,0)''> <p>ユーザー:$personallink</p> <div style='float:left; width:50%;'> <p><img src='$pcount.myActivity.png'/></div></p> <div style='float:left; width:50%;'> <p><img src='$pcount.myProgress.png' /></div></p> <div style=' float:left; width:100%; word-wrap: break-word; padding: 0em 1em; margin: 0.5em 0; background: #f4f4f4; border-left: solid 6px #5bb7ae;; box-shadow: 0px 2px 3px rgba(0, 0, 0, 0.0)'> <p>$newestp->date</p> <p>課題:<br>$newestp->task</p> <p>活動:<br>$newestp->post</p> </div> </div>"; $pcount++; } else{ echo "<div style=' float:right; width:48%; word-wrap: break-word; padding: 0.5em 1em; margin: 0.5em 0; background: #f4f4f4; border-left: solid 6px #f4f1a6; box-shadow: 0px 2px 3px rgba(0, 0, 0, 0,0)''> <p>ユーザー:$personallink</p> <div style='float:left; width:50%;'> <p><img src='$pcount.myActivity.png'/></div></p> <div style='float:left; width:50%;'> <p><img src='$pcount.myProgress.png' /></div></p> <div style=' float:left; width:100%; word-wrap: break-word; padding: 0em 1em; margin: 0.5em 0; background: #f4f4f4; border-left: solid 6px #5bb7ae; box-shadow: 0px 2px 3px rgba(0, 0, 0, 0,0)'> <p>$newestp->date</p> <p>課題:<br>$newestp->task</p> <p>活動:<br>$newestp->post</p> </div> </div>"; $pcount++; } // echo $key,':3rd<br>'; } // } // debug_dump($cmpdata); // $sort = array(); // // $i=0; // foreach($cmpdata as $key =>$val){ // array_push($sort, $val->date); // // $sort[] = $val[date]; // // $i++; // } // echo $cmpdata->$key[date]; // debug_dump($sort); // array_merge($sort); // // debug_dump($cmpdata); // array_multisort($sort, SORT_DESC, $cmpdata); // // array_multisort($cmpdata->date, SORT_DESC); // debug_dump($cmpdata); // debug_dump($sort); // $pcount=0; // foreach($cmpdata as $key => $val){ // if($pcount%2 == 0){ // echo // "<div style=' // float:left; width:48%;'> // <p>ユーザー:$USER->username</p> // <div style='float:left; width:50%;'> // <p><img src='$.myActivity.png'/></div></p> // <div style='float:left; width:50%;'> // <p><img src='$key.myProgress.png' /></div></p> // <div style=' // float:left; width:100%; // word-wrap: break-word; // padding: 0.5em 1em; // margin: 1em 0; // background: #f4f4f4; // border-left: solid 6px #5bb7ae; // box-shadow: 0px 2px 3px rgba(0, 0, 0, 0.33)'> // <p>更新日:</p> // <p>$cmptime->summary[$key]</p> // </div> // </div>"; // $pcount++; // } // else{ // echo // "<div style=' // float:right; width:48%;'> // <p>ユーザー:$username</p> // <div style='float:left; width:50%;'> // <p><img src='$key.myActivity.png'/></div></p> // <div style='float:left; width:50%;'> // <p><img src='$key.myProgress.png' /></div></p> // <div style=' // float:left; width:100%; // word-wrap: break-word; // padding: 0.5em 1em; // margin: 1em 0; // background: #f4f4f4; // border-left: solid 6px #5bb7ae; // box-shadow: 0px 2px 3px rgba(0, 0, 0, 0.33)'> // <p>aa</p> // <p>aa</p> // </div> // </div>"; // $pcount++; // } // } //新しいエントリエントリ一覧10/3コメントアウト //$bloglisting->print_entries(); // Finish the page.フッター表示 // echo '今は何も表示してません。エラーではないので大丈夫です'; echo $OUTPUT->footer(); function debug_dump($getobject){ echo "section<br />"; //オブジェクトクラスの中身を整理し表示する関数 echo "<pre>"; echo var_dump($getobject); echo "</pre>"; } <file_sep><?php require_once('../../config.php'); require_once('./rr_form.php'); require_once("$CFG->libdir/outputcomponents.php"); require_once("$CFG->libdir/formslib.php"); require_once("$CFG->libdir/weblib.php"); require_once('./locallib.php'); global $CFG, $PAGE,$DB; $id = optional_param('id', 0, PARAM_INT); // Course Module ID $r = optional_param('n', 0, PARAM_INT); // ResearchReport ID // $PAGE->set_url($CFG->wwwroot.'//mod/researchreport/activity_form.php'); $PAGE->set_url($CFG->wwwroot.'//mod/researchreport/activity_form.php', array( 'userid' =>$userid )); $PAGE->set_context(context_system::instance()); $PAGE->set_pagelayout('standard'); $PAGE->set_title('New Activity'); $PAGE->set_heading('New Activity'); // $returnurl = new moodle_url('/mod/researchreport/view.php', array('id' =>$cm->id)); $returnurl = new moodle_url('/mod/researchreport/view.php?id=59'); $mform = new activity_form(); // $mform = new test_form(); echo $OUTPUT->header(); echo 'activity'; if ($mform->is_cancelled()) { // You need this section if you have a cancel button on your form // here you tell php what to do if your user presses cancel // probably a redirect is called for! // PLEASE NOTE: is_cancelled() should be called before get_data(); redirect($returnurl); // } else if ($entry = $mform->get_data()) { } else if ($fromform = $mform->get_data()) { // This branch is where you process validated data. // Do stuff ... // Typically you finish up by redirecting to somewhere where the user // can see what they did. //activityフォームの取得 //作成日の取得、追加 debug_dump($fromform); $insertdata = new stdClass(); $insertdata->userid = $USER->id; $insertdata->summary = $fromform->summary['text']; $insertdata->task = $fromform->task['text']; $insertdata->sttime = $fromform->sttime; $insertdata->edtime = $fromform->edtime; // $insertdata->sttime = "9"; // $insertdata->edtime = "18"; $insertdata->acttime = $fromform->acttime; $insertdata->studytime = $fromform->studytime; $insertdata->evalution = $fromform->evalution; $createdtime = new DateTime("now", core_date::get_server_timezone_object()); // $timestamp = time() ; // date()で日時を出力 $insertdata->timemd = date( "md" ) ; var_dump($createdtime); $insertdata->created = $createdtime->date; $insertdata->summaryformat = $fromform->summary['format']; debug_dump($insertdata); $DB->insert_record('rrpost', $insertdata); //モジュールトップへリダイレクト redirect($returnurl); //debug //DBに挿入されたオブジェクトを確認する場合 // redirect(); } $mform->display(); echo $OUTPUT->footer(); function debug_dump($getobject){ echo "section<br />"; //オブジェクトクラスの中身を整理し表示する関数 echo "<pre>"; echo var_dump($getobject); echo "</pre>"; } ?><file_sep><?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Internal library of functions for module researchreport * researchreport用の関数の内部ライブラリ * * All the researchreport specific functions, needed to implement the module * logic, should go here. Never include this file from your lib.php! * モジュールロジックを実装するために必要な * 全てのresearchreport固有の関数はここになければなりません。 * lib.phpからこのファイルを絶対に含めないでください。 * * @package mod_researchreport * @copyright 2016 Your Name <<EMAIL>> * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); require_once($CFG->libdir . '/filelib.php'); class rr_entry implements renderable { public $id; public $userid; public $courseid; public $groupid; public $subject; public $entry; public $acttime; public $evaluation; public $created; public $lastmodified; public function add() { global $CFG,$USER,$DB; unset($this->id); $this->module = 'researchreport'; $this->userid = (empty($this->userid)) ? $USER->id : $this->userid; $this->lastmodified = time(); $this->created = time(); //データベースに入力した値を挿入 $this->id = $DB->insert_record('rrpost', $this); } public function __construct($id=null) { global $DB, $PAGE, $CFG; } } /* * Does something really useful with the passed things * * @param array $things * @return object *function researchreport_do_something_useful(array $things) { * return new stdClass(); *} */ <file_sep><?php require_once('../../config.php'); require_once('./rr_form.php'); require_once("$CFG->libdir/outputcomponents.php"); require_once("$CFG->libdir/formslib.php"); require_once("$CFG->libdir/weblib.php"); require_once('./locallib.php'); global $CFG, $PAGE,$DB; $id = optional_param('id', 0, PARAM_INT); // Course Module ID $r = optional_param('n', 0, PARAM_INT); // ResearchReport ID $PAGE->set_url($CFG->wwwroot.'//mod/researchreport/allactivity.php'); $PAGE->set_context(context_system::instance()); $PAGE->set_pagelayout('standard'); $PAGE->set_title('All Activity'); $PAGE->set_heading('All Activity'); // $returnurl = new moodle_url('/mod/researchreport/view.php', array('id' =>$cm->id)); $returnurl = new moodle_url('/mod/researchreport/view.php?id=59'); echo $OUTPUT->header(); // debug_dump($USER); $allpost = $DB->get_records_sql("SELECT * FROM mdl_rrpost"); // debug_dump($allpost); foreach($allpost as $key => $val); for($key; $key>=0; $key--){ $userid = $allpost[$key]->userid; $username = $DB->get_records_sql("SELECT username FROM mdl_user WHERE id = $userid "); $username = key($username); $date = $allpost[$key]->created; $start = $allpost[$key]->sttime; $end = $allpost[$key]->edtime; $reserch = $allpost[$key]->acttime; $study = $allpost[$key]->studytime; $evalution = $allpost[$key]->evalution; $summary = $allpost[$key]->summary; $task = $allpost[$key]->task; echo "<div style='float:left; width: 100%;word-wrap: break-word;padding: 0.5em 1em;margin: 1em 0; background: #f4f4f4; border-left: solid 6px #5bb7ae; box-shadow: 0px 2px 3px rgba(0, 0, 0, 0.100)'> <p>ユーザー:$username <br>活動内容:$summary <br>次回課題:$task</p> <p>更新日:$date <br>活動時間:$start 〜 $end <br> 研究時間:$reserch 時間 <br>勉強時間:$study 時間<br> 1日の評価:$evalution %<br> </p> </div>"; } echo $OUTPUT->footer(); function debug_dump($getobject){ echo "section<br />"; //オブジェクトクラスの中身を整理し表示する関数 echo "<pre>"; echo var_dump($getobject); echo "</pre>"; }<file_sep><?php require_once('../../config.php'); require_once('./rr_form.php'); require_once("$CFG->libdir/outputcomponents.php"); require_once("$CFG->libdir/formslib.php"); require_once("$CFG->libdir/weblib.php"); require_once('./locallib.php'); //pChart include include($CFG->dirroot.'/mod/researchreport/pChart/class/pData.class.php'); include($CFG->dirroot.'/mod/researchreport/pChart/class/pDraw.class.php'); include($CFG->dirroot.'/mod/researchreport/pChart/class/pImage.class.php'); global $CFG, $PAGE,$DB; $userid = optional_param('userid', 0, PARAM_INT); $id = optional_param('id', 0, PARAM_INT); // Course Module ID $r = optional_param('n', 0, PARAM_INT); // ResearchReport ID $PAGE->set_url($CFG->wwwroot.'//mod/researchreport/allactivity.php', array( 'userid' =>$userid )); // echo $userid; // $userid = $USER->id; $username = $DB->get_records_sql("SELECT username FROM mdl_user WHERE id = $userid "); $username = key($username); $PAGE->set_context(context_system::instance()); $PAGE->set_pagelayout('standard'); $PAGE->set_title("$username のページ"); $PAGE->set_heading("$username のページ"); // $returnurl = new moodle_url('/mod/researchreport/view.php', array('id' =>$cm->id)); $returnurl = new moodle_url('/mod/researchreport/view.php?id=59'); echo $OUTPUT->header(); // debug_dump($userid); // $userid = $USER->id; // echo $userid; $userpost = $DB->get_records_sql("select * from mdl_rrpost where userid = $userid"); if ($userpost !=NULL){ // debug_dump($userpost); $userpost = array_merge($userpost,array()); // debug_dump($userpost); foreach($userpost as $key => $val); // echo $key; $pacttime = array(); $pevalution = array(); for($i=0;$i<=$key;$i++){ array_push($pacttime,$userpost[$i]->acttime); array_push($pevalution,$userpost[$i]->evalution); } // debug_dump($pevalution); $myData = new pData(); $myData->addPoints($pacttime,"Serie1"); $myData->setSerieDescription("Serie1","Activity Time"); $myData->setSerieOnAxis("Serie1",0); // $myData->addPoints(array("January","February","March","April","May","June","July","August"),"Absissa"); // $myData->setAbscissa("Absissa"); $myData->setAxisPosition(0,AXIS_POSITION_LEFT); $myData->setAxisName(0,"Time ( h )"); $myData->setAxisUnit(0,""); $myPicture = new pImage(1000,300,$myData,TRUE); $myPicture->Antialias = FALSE; $myPicture->setGraphArea(100,100,800,210); $myPicture->setFontProperties(array("R"=>0,"G"=>0,"B"=>0,"FontName"=>"fonts/pf_arma_five.ttf","FontSize"=>18)); $Settings = array("Pos"=>SCALE_POS_LEFTRIGHT , "Mode"=>SCALE_MODE_START0 , "LabelingMethod"=>LABELING_ALL , "GridR"=>255, "GridG"=>255, "GridB"=>255, "GridAlpha"=>50, "TickR"=>0, "TickG"=>0, "TickB"=>0, "TickAlpha"=>50, "LabelRotation"=>0, "CycleBackground"=>1, "DrawXLines"=>0, "DrawYLines"=>NONE); $myPicture->drawScale($Settings); $Config = array("DisplayValues"=>0,"AroundZero"=>1); $myPicture->drawBarChart($Config); $Config = array("FontR"=>0, "FontG"=>0, "FontB"=>0, "FontName"=>"fonts/pf_arma_five.ttf", "FontSize"=>20, "Margin"=>6, "Alpha"=>30, "BoxSize"=>5, "Style"=>LEGEND_NOBORDER , "Mode"=>LEGEND_HORIZONTAL ); $myPicture->drawLegend(200,16,$Config); $myPicture->render("personal_activity_time.png"); // echo "<div style='float:left; width:50%;'> // <p><img src='personal_activity_time.png' /></div></p>"; //////////////////////////////////////////////////////////////// //mix $myData = new pData(); $myData->addPoints($pacttime,"Serie1"); // $myData->setPalette("Serie1", array("R"=>51,"G"=>153,"B"=>150)); $myData->setSerieDescription("Serie1",Activity); $myData->setSerieOnAxis("Serie1",0); $myData->addPoints($pevalution,"Serie2"); $myData->setSerieDescription("Serie2","Evalution"); $myData->setPalette("Serie2", array("R"=>51,"G"=>153,"B"=>150)); $myData->setSerieOnAxis("Serie2",1); // $myData->addPoints($pdrawdata->timemd,"Absissa"); $myData->setAbscissa("Absissa"); $myData->setAbscissaName("Date"); $myData->setAxisPosition(0,AXIS_POSITION_LEFT); $myData->setAxisName(0,"Time( h )"); $myData->setAxisUnit(0,""); $myData->setAxisPosition(1,AXIS_POSITION_RIGHT); $myData->setAxisName(1,"percent( % )"); $myData->setAxisUnit(1,""); $myPicture = new pImage(1000,300,$myData); $myPicture->Antialias = FALSE; $myPicture->setFontProperties(array("FontName"=>"fonts/Forgotte.ttf","FontSize"=>18)); $TextSettings = array("Align"=>TEXT_ALIGN_TOPLEFT , "R"=>0, "G"=>0, "B"=>0); $myPicture->drawText(50,10,"Activity",$TextSettings); $myPicture->setGraphArea(50,50,800,210); $myPicture->setFontProperties(array("R"=>0,"G"=>0,"B"=>0,"FontName"=>"fonts/pf_arma_five.ttf","FontSize"=>16)); $Settings = array("Pos"=>SCALE_POS_LEFTRIGHT , "Mode"=>SCALE_MODE_MANUAL , "ManualScale"=>array( 0=>array("Min"=>0,"Max"=>12), 1=>array("Min"=>0,"Max"=>100) ) , "LabelingMethod"=>LABELING_ALL , "GridR"=>255, "GridG"=>255, "GridB"=>255, "GridAlpha"=>50, "TickR"=>0, "TickG"=>0, "TickB"=>0, "TickAlpha"=>50, "LabelRotation"=>0, "CycleBackground"=>1, "DrawXLines"=>1, "DrawSubTicks"=>1, "SubTickR"=>255, "SubTickG"=>0, "SubTickB"=>0, "SubTickAlpha"=>0, "DrawYLines"=>NONE); $myPicture->drawScale($Settings); $Config = array("DisplayValues"=>0, "AroundZero"=>1); $myData->setSerieDrawable("Serie1",TRUE); $myData->setSerieDrawable("Serie2",FALSE); $myPicture->drawBarChart($Config); $myData->setSerieDrawable("Serie1",FALSE); $myData->setSerieDrawable("Serie2",TRUE); $myPicture->drawAreaChart($Config); $myData->setSerieDrawable("Serie1",TRUE);//TRUEに戻しておく $Config = array("FontR"=>0, "FontG"=>0, "FontB"=>0, "FontName"=>"fonts/pf_arma_five.ttf", "FontSize"=>12, "Margin"=>6, "Alpha"=>30, "BoxSize"=>5, "Style"=>LEGEND_NOBORDER , "Mode"=>LEGEND_HORIZONTAL); $myPicture->drawLegend(200,16,$Config); $myPicture->render("mixpersonal.png"); echo "<div style='float:left; width:100%;'> <p><img src='mixpersonal.png' /></div></p>"; for($key; $key>=0; $key--){ $date = $userpost[$key]->created; $start = $userpost[$key]->sttime; $end = $userpost[$key]->edtime; $reserch = $userpost[$key]->acttime; $study = $userpost[$key]->studytime; $evalution = $userpost[$key]->evalution; $summary = $userpost[$key]->summary; $task = $userpost[$key]->task; echo "<div style='float:left; width: 100%;word-wrap: break-word;padding: 0.5em 1em;margin: 1em 0; background: #f4f4f4; border-left: solid 6px #5bb7ae; box-shadow: 0px 2px 3px rgba(0, 0, 0, 0.100)'> <p>活動内容:<br>$summary</p> <p>次回課題:<br>$task</p> <p>更新日:$date <br>活動時間:$start 〜 $end <br> 研究時間:$reserch 時間 <br>勉強時間:$study 時間<br> 1日の評価:$evalution %<br> </p> </div>"; } } else echo 'なにもないよ'; echo $OUTPUT->footer(); function debug_dump($getobject){ echo "section<br />"; //オブジェクトクラスの中身を整理し表示する関数 echo "<pre>"; echo var_dump($getobject); echo "</pre>"; }<file_sep><?php require_once('../../config.php'); require_once('./rr_form.php'); require_once("$CFG->libdir/outputcomponents.php"); require_once("$CFG->libdir/formslib.php"); require_once("$CFG->libdir/weblib.php"); require_once('./locallib.php'); global $CFG, $PAGE,$DB; $id = optional_param('id', 0, PARAM_INT); // Course Module ID $r = optional_param('n', 0, PARAM_INT); // ResearchReport ID $PAGE->set_url($CFG->wwwroot.'//mod/researchreport/activity_form.php'); $PAGE->set_context(context_system::instance()); $PAGE->set_pagelayout('standard'); $PAGE->set_title('New Activity'); $PAGE->set_heading('New Activity'); // $returnurl = new moodle_url('/mod/researchreport/view.php', array( // 'id' =>$cm->id // )); $returnurl = new moodle_url('/mod/researchreport/view.php?id=59'); $mform = new progress_form(); echo $OUTPUT->header(); echo 'progress'; $mform->display(); if ($mform->is_cancelled()) { // You need this section if you have a cancel button on your form // here you tell php what to do if your user presses cancel // probably a redirect is called for! // PLEASE NOTE: is_cancelled() should be called before get_data(); redirect($returnurl); } else if ($formdata = $mform->get_data()) { // This branch is where you process validated data. // Do stuff ... // Typically you finish up by redirecting to somewhere where the user // can see what they did. // 11/25 // $getentry = new stdClass('activity_data', $entry); // $DB->insert_record('rrpost', $getentry, true); // $DB->insert_record('rrpost', $inputs); echo "<pre>"; echo var_dump($formdata); echo "</pre>"; // redirect($returnurl); redirect(); } echo $OUTPUT->footer(); ?><file_sep># researchreport 開発したmoodleのmod <file_sep><?php require_once('../../config.php'); require_once('./rr_form.php'); require_once("$CFG->libdir/outputcomponents.php"); require_once("$CFG->libdir/formslib.php"); require_once("$CFG->libdir/weblib.php"); require_once('./locallib.php'); include($CFG->dirroot.'/mod/researchreport/pChart/class/pData.class.php'); include($CFG->dirroot.'/mod/researchreport/pChart/class/pDraw.class.php'); include($CFG->dirroot.'/mod/researchreport/pChart/class/pImage.class.php'); include($CFG->dirroot.'/mod/researchreport/pChart/class/pScatter.class.php'); global $CFG, $PAGE,$DB; // $userid = optional_param('userid', $USER->id, PARAM_INT); // Course Module ID $id = optional_param('id', 0, PARAM_INT); // Course Module ID $r = optional_param('n', 0, PARAM_INT); // ResearchReport ID $PAGE->set_url($CFG->wwwroot.'//mod/researchreport/testpage.php'); $PAGE->set_context(context_system::instance()); $PAGE->set_pagelayout('standard'); $PAGE->set_title('testpage'); $PAGE->set_heading('testpage'); // $returnurl = new moodle_url('/mod/researchreport/view.php', array('id' =>$cm->id)); $returnurl = new moodle_url('/mod/researchreport/view.php?id=59'); echo $OUTPUT->header(); // debug_dump($USER); $alluserid = $DB->get_records_sql("SELECT DISTINCT userid FROM mdl_rrpost"); // debug_dump($alluserid); $alluserid = array_keys($alluserid); debug_dump($alluserid); foreach($alluserid as $key_1 => $val_1){ $getdata = $DB->get_records_sql("SELECT * FROM mdl_rrpost WHERE userid = $val_1"); $getdata = array_merge($getdata,array()); foreach($getdata as $key_2 => $val_2); $cmpdata[$key_1]->date = $getdata[$key_2]->created; $cmpdata[$key_1]->userid = $getdata[$key_2]->userid; $cmpdata[$key_1]->sumtime = $getdata[$key_2]->acttime + $getdata[$key_2]->studytime; $cmpdata[$key_1]->acttime = $getdata[$key_2]->acttime; $cmpdata[$key_1]->studytime = $getdata[$key_2]->studytime; } foreach($cmpdata as $key =>$val){ $sort[$key] = $val->date; } array_merge($sort); array_multisort($sort, SORT_DESC, $cmpdata); debug_dump($cmpdata); $pdrawdata = new stdClass(); $pdrawdata->userid = array(); $pdrawdata->sumtime = array(); $pdrawdata->acttime = array(); $pdrawdata->studytime = array(); $pdrawdata->username = array(); foreach($cmpdata as $key => $val){ // for($key; $key>=0; $key--){ array_push($pdrawdata->userid, $cmpdata[$key]->userid); $userid = $cmpdata[$key]->userid; $username = $DB->get_records_sql("SELECT username FROM mdl_user WHERE id = $userid"); $username = key($username); array_push($pdrawdata->username, $username); array_push($pdrawdata->sumtime, $cmpdata[$key]->sumtime); array_push($pdrawdata->acttime, $cmpdata[$key]->acttime); array_push($pdrawdata->studytime, $cmpdata[$key]->studytime); } debug_dump($pdrawdata); $myData = new pData(); $myData->addPoints($pdrawdata->acttime,"Serie1"); $myData->setSerieDescription("Serie1","Serie 1"); $myData->setSerieOnAxis("Serie1",0); $myData->addPoints($pdrawdata->studytime,"Serie2"); $myData->setSerieDescription("Serie2","Serie 2"); $myData->setSerieOnAxis("Serie2",0); $myData->addPoints($pdrawdata->username,"Absissa"); $myData->setAbscissa("Absissa"); $myData->setAxisPosition(0,AXIS_POSITION_LEFT); $myData->setAxisName(0,"1st axis"); $myData->setAxisUnit(0,""); $myPicture = new pImage(900,500,$myData,TRUE); $myPicture->Antialias = FALSE; $myPicture->setGraphArea(150,50,675,400); $myPicture->setFontProperties(array("R"=>0,"G"=>0,"B"=>0,"FontName"=>"fonts/pf_arma_five.ttf","FontSize"=>16)); // $Settings = array("Pos"=>SCALE_POS_TOPBOTTOM // , "Mode"=>SCALE_MODE_MANUAL // , "ManualScale"=>array( // 0=>array("Min"=>0,"Max"=>20)) // , "LabelingMethod"=>LABELING_ALL // , "GridR"=>255, "GridG"=>255, "GridB"=>255, "GridAlpha"=>50, "TickR"=>0, "TickG"=>0, "TickB"=>0, // "TickAlpha"=>50, "LabelRotation"=>5, // "DrawArrows"=>1, "DrawXLines"=>0, "DrawSubTicks"=>0, // "SubTickR"=>255, "SubTickG"=>0, "SubTickB"=>0, "SubTickAlpha"=>0,"DrawYLines"=>ALL // ); // $myPicture->drawScale($Settings); $scatter = new pScatter($myPicture, $myData); $scatter->drawScatterScale(array( // それぞれの軸の最小値と最大値を手動で決めます。 "Mode" => SCALE_MODE_MANUAL, "ManualScale" => array( 0 => array("Min" => 0, "Max" => 15), 1 => array("Min" => -10, "Max" => 20), 2 => array("Min" => 0, "Max" => 10), ), // X軸ラベルが回転しないようにします。 "XLabelsRotation" => 0, // グリッド線の色を変えます。 "GridR" => 180, "GridG" => 180, "GridB" => 180, )); $scatter->drawScatterLineChart(); $scatter->drawScatterPlotChart(); $scatter->drawScatterLegend(720, 400, array("Mode" => LEGEND_HORIZONTAL, "Style" => LEGEND_NOBORDER)); // $Config = array("AroundZero"=>0); // // $myPicture->drawBarChart($Config); // $myPicture->drawStackedBarChart($Config); // $Config = array("FontR"=>0, "FontG"=>0, "FontB"=>0, "FontName"=>"fonts/pf_arma_five.ttf", "FontSize"=>16, "Margin"=>6, "Alpha"=>30, "BoxSize"=>5, "Style"=>LEGEND_NOBORDER // , "Mode"=>LEGEND_HORIZONTAL // ); // $myPicture->drawLegend(648,16,$Config); $myPicture->render("tatechart.png"); ////////////////////////////////////////////////////////////////////////////////////////////////// $data = new pData(); // Y軸用に2種類の適当なデータを設定します。 $data->addPoints($pdrawdata->acttime, "Y1"); $data->addPoints($pdrawdata->studytime, "Y2"); // データの色を設定します。 $data->setPalette("Y1", array("R" => 130, "G" => 200, "B" => 0)); $data->setPalette("Y2", array("R" => 0, "G" => 130, "B" => 200)); // X軸用に2種類の適当なデータを設定します。 $data->addPoints($pdrawdata->username, "X1"); // $data->addPoints(array(0, 1, 3, 3.5, 4.3, 5.7, 6.1, 7, 8, 8.5), "X2"); // 0番目の軸をY軸として設定します。 $data->setSerieOnAxis("Y1", 0); $data->setAxisName(0, "Y Axis"); $data->setAxisXY(0, AXIS_Y); $data->setAxisPosition(0, AXIS_POSITION_TOP); // 1番目の軸をX1軸として設定します。 $data->setSerieOnAxis("X1", 1); $data->setAxisName(1, "X1 Axis"); $data->setAxisXY(1, AXIS_X); $data->setAxisPosition(1, AXIS_POSITION_RIGHT); // 2番目の軸をX2軸として設定します。 // $data->setSerieOnAxis("X2", 2); // $data->setAxisName(2, "X2 Axis"); // $data->setAxisXY(2, AXIS_X); // $data->setAxisPosition(2, AXIS_POSITION_LEFT); // それぞれのデータの系列と系列名を設定します。 $data->setScatterSerie("X1", "Y1", 0); $data->setScatterSerieDescription(0, "X1 - Y1"); // $data->setScatterSerie("X2", "Y2", 1); // $data->setScatterSerieDescription(1, "X2 - Y2"); $image = new pImage(900, 450, $data); $image->setFontProperties(array("FontName" => "../fonts/pf_arma_five.ttf", "FontSize" => 18)); $image->setGraphArea(50, 50, 700, 300); $scatter = new pScatter($image, $data); $scatter->drawScatterScale(array( // それぞれの軸の最小値と最大値を手動で決めます。 "Mode" => SCALE_MODE_MANUAL, "ManualScale" => array( 0 => array("Min" => 0, "Max" => 10), 1 => array("Min" => -10, "Max" => 20), 2 => array("Min" => 0, "Max" => 10), ), // X軸ラベルが回転しないようにします。 "XLabelsRotation" => 0, // グリッド線の色を変えます。 "GridR" => 180, "GridG" => 180, "GridB" => 180, )); // 折れ線とプロットを描画します。 $scatter->drawScatterLineChart(); $scatter->drawScatterPlotChart(); // 凡例を描画します。 $scatter->drawScatterLegend(250, 180, array("Mode" => LEGEND_HORIZONTAL, "Style" => LEGEND_NOBORDER)); $image->render("tatechart.png"); echo "<div style='float:center; width:50%;'> <p><img src='tatechart.png' /></div></p>"; echo $OUTPUT->footer(); function debug_dump($getobject){ echo "section/////////////////////////////////////////////////////////////////////////////////////////////////////////////////<br />"; //オブジェクトクラスの中身を整理し表示する関数 echo "<pre>"; echo var_dump($getobject); echo "</pre>"; }
0afe92e7a806b1f3ce15caaf1446a30d9266b248
[ "Markdown", "PHP" ]
9
PHP
waaaaall/researchreport
c81974a87d820d13c0af165451ea0c368ec9a431
452350a7aea2813750555c73dae87145eedf8713
refs/heads/master
<repo_name>babidi34/PPE<file_sep>/src/NeigeEtSoleilBundle/Controller/AppartementsController.php <?php namespace NeigeEtSoleilBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; class AppartementsController extends Controller { public function AppartementsAction() { $em = $this->getDoctrine()->getManager(); $appartements = $em->getRepository('NeigeEtSoleilBundle:Appartements')->findAll(); return $this->render('NeigeEtSoleilBundle:Default:Appartements/Layout/Appartements.html.twig', array('appartements' => $appartements)); } public function PresentationAction($id) { $em = $this->getDoctrine()->getManager(); $appartement = $em->getRepository('NeigeEtSoleilBundle:Appartements')->find($id); return $this->render('NeigeEtSoleilBundle:Default:Appartements/Layout/Presentation.html.twig', array('appartement' => $appartement)); } } <file_sep>/src/NeigeEtSoleilBundle/DataFixtures/ORM/AppartementsData.php <?php namespace NeigeEtSoleilBundle\DataFixtures\ORM; use Doctrine\Common\DataFixtures\AbstractFixture; use Doctrine\Common\DataFixtures\OrderedFixtureInterface; use Doctrine\Common\Persistence\ObjectManager; use NeigeEtSoleilBundle\Entity\TypeAppartement; class TypeAppartementData extends AbstractFixture implements OrderedFixtureInterface { public function load(ObjectManager $manager) { $typeAppartement1 = new TypeAppartement(); $typeAppartement1->setDescriptif('Studio'); $manager->persist($typeAppartement1); $typeAppartement2 = new TypeAppartement(); $typeAppartement2->setDescriptif('F2'); $manager->persist($typeAppartement2); $manager->flush(); $this->addReference('typeAppartement1', $typeAppartement1); $this->addReference('typeAppartement2', $typeAppartement2); } public function getOrder() { return 1; } } <file_sep>/src/NeigeEtSoleilBundle/Entity/Appartements.php <?php namespace NeigeEtSoleilBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * Appartements * * @ORM\Table(name="appartements") * @ORM\Entity(repositoryClass="NeigeEtSoleilBundle\Repository\AppartementsRepository") */ class Appartements { /** * @var int * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @ORM\ManyToOne(targetEntity="NeigeEtSoleilBundle\Entity\TypeAppartement", inversedBy="appartements") */ private $typeAppartement; /** * @var string * * @ORM\Column(name="nomImmeubleA", type="string", length=50, nullable=true) */ private $nomImmeubleA; /** * @var string * * @ORM\Column(name="numVoieA", type="string", length=50, nullable=true) */ private $numVoieA; /** * @var string * * @ORM\Column(name="nomRueA", type="string", length=50, nullable=true) */ private $nomRueA; /** * @var string * * @ORM\Column(name="villeA", type="string", length=50, nullable=true) */ private $villeA; /** * @var int * * @ORM\Column(name="cpA", type="integer", nullable=true) */ private $cpA; /** * @var float * * @ORM\Column(name="superficie", type="float", nullable=true) */ private $superficie; /** * @var float * * @ORM\Column(name="prix", type="float", nullable=true) */ private $prix; /** * @var bool * * @ORM\Column(name="disponible", type="boolean", nullable=true) */ private $disponible; /** * Get id * * @return int */ public function getId() { return $this->id; } /** * Set nomImmeubleA * * @param string $nomImmeubleA * * @return Appartements */ public function setNomImmeubleA($nomImmeubleA) { $this->nomImmeubleA = $nomImmeubleA; return $this; } /** * Get nomImmeubleA * * @return string */ public function getNomImmeubleA() { return $this->nomImmeubleA; } /** * Set numVoieA * * @param string $numVoieA * * @return Appartements */ public function setNumVoieA($numVoieA) { $this->numVoieA = $numVoieA; return $this; } /** * Get numVoieA * * @return string */ public function getNumVoieA() { return $this->numVoieA; } /** * Set nomRueA * * @param string $nomRueA * * @return Appartements */ public function setNomRueA($nomRueA) { $this->nomRueA = $nomRueA; return $this; } /** * Get nomRueA * * @return string */ public function getNomRueA() { return $this->nomRueA; } /** * Set villeA * * @param string $villeA * * @return Appartements */ public function setVilleA($villeA) { $this->villeA = $villeA; return $this; } /** * Get villeA * * @return string */ public function getVilleA() { return $this->villeA; } /** * Set cpA * * @param integer $cpA * * @return Appartements */ public function setCpA($cpA) { $this->cpA = $cpA; return $this; } /** * Get cpA * * @return int */ public function getCpA() { return $this->cpA; } /** * Set superficie * * @param float $superficie * * @return Appartements */ public function setSuperficie($superficie) { $this->superficie = $superficie; return $this; } /** * Get superficie * * @return float */ public function getSuperficie() { return $this->superficie; } /** * Set prix * * @param float $prix * * @return Appartements */ public function setPrix($prix) { $this->prix = $prix; return $this; } /** * Get prix * * @return float */ public function getPrix() { return $this->prix; } /** * Set disponible * * @param boolean $disponible * * @return Appartements */ public function setDisponible($disponible) { $this->disponible = $disponible; return $this; } /** * Get disponible * * @return bool */ public function getDisponible() { return $this->disponible; } /** * Set typeAppartement * * @param \NeigeEtSoleilBundle\Entity\TypeAppartement $typeAppartement * * @return Appartements */ public function setTypeAppartement(\NeigeEtSoleilBundle\Entity\TypeAppartement $typeAppartement = null) { $this->typeAppartement = $typeAppartement; return $this; } /** * Get typeAppartement * * @return \NeigeEtSoleilBundle\Entity\TypeAppartement */ public function getTypeAppartement() { return $this->typeAppartement; } } <file_sep>/var/cache/dev/twig/ee/eec55c5018d0f4ec8e48dc8eb9365d53390725b579323fd8ec542cdd28f43a51.php <?php /* NeigeEtSoleilBundle:Default:Appartements/Layout/Appartements.html.twig */ class __TwigTemplate_e1e0608a9627aa8977d2bb8a4870774f25e1db603eb2e3e80f6505d21089f2d9 extends Twig_Template { public function __construct(Twig_Environment $env) { parent::__construct($env); // line 1 $this->parent = $this->loadTemplate("::layout/layout.html.twig", "NeigeEtSoleilBundle:Default:Appartements/Layout/Appartements.html.twig", 1); $this->blocks = array( 'body' => array($this, 'block_body'), ); } protected function doGetParent(array $context) { return "::layout/layout.html.twig"; } protected function doDisplay(array $context, array $blocks = array()) { $__internal_761e47fd47f2d75f0d39b2cf42552b32b143dd88cc9cd91bbc64f744f2c6a24f = $this->env->getExtension("Symfony\\Bundle\\WebProfilerBundle\\Twig\\WebProfilerExtension"); $__internal_761e47fd47f2d75f0d39b2cf42552b32b143dd88cc9cd91bbc64f744f2c6a24f->enter($__internal_761e47fd47f2d75f0d39b2cf42552b32b143dd88cc9cd91bbc64f744f2c6a24f_prof = new Twig_Profiler_Profile($this->getTemplateName(), "template", "NeigeEtSoleilBundle:Default:Appartements/Layout/Appartements.html.twig")); $__internal_540161912f6ac86acc6c4537c49a57288acd9b7df138bdf8f19a411abd8a6c92 = $this->env->getExtension("Symfony\\Bridge\\Twig\\Extension\\ProfilerExtension"); $__internal_540161912f6ac86acc6c4537c49a57288acd9b7df138bdf8f19a411abd8a6c92->enter($__internal_540161912f6ac86acc6c4537c49a57288acd9b7df138bdf8f19a411abd8a6c92_prof = new Twig_Profiler_Profile($this->getTemplateName(), "template", "NeigeEtSoleilBundle:Default:Appartements/Layout/Appartements.html.twig")); $this->parent->display($context, array_merge($this->blocks, $blocks)); $__internal_761e47fd47f2d75f0d39b2cf42552b32b143dd88cc9cd91bbc64f744f2c6a24f->leave($__internal_761e47fd47f2d75f0d39b2cf42552b32b143dd88cc9cd91bbc64f744f2c6a24f_prof); $__internal_540161912f6ac86acc6c4537c49a57288acd9b7df138bdf8f19a411abd8a6c92->leave($__internal_540161912f6ac86acc6c4537c49a57288acd9b7df138bdf8f19a411abd8a6c92_prof); } // line 3 public function block_body($context, array $blocks = array()) { $__internal_a084b187c087e0a89bbfd58e48e2bc4ee9867b195557dfd50695d514bc35bf4c = $this->env->getExtension("Symfony\\Bundle\\WebProfilerBundle\\Twig\\WebProfilerExtension"); $__internal_a084b187c087e0a89bbfd58e48e2bc4ee9867b195557dfd50695d514bc35bf4c->enter($__internal_a084b187c087e0a89bbfd58e48e2bc4ee9867b195557dfd50695d514bc35bf4c_prof = new Twig_Profiler_Profile($this->getTemplateName(), "block", "body")); $__internal_3d1cb3779f7481c1979ffef9d4b31626c5cd7b679fcfd8723a196754e728b478 = $this->env->getExtension("Symfony\\Bridge\\Twig\\Extension\\ProfilerExtension"); $__internal_3d1cb3779f7481c1979ffef9d4b31626c5cd7b679fcfd8723a196754e728b478->enter($__internal_3d1cb3779f7481c1979ffef9d4b31626c5cd7b679fcfd8723a196754e728b478_prof = new Twig_Profiler_Profile($this->getTemplateName(), "block", "body")); // line 4 echo "<div class=\"container\"> <div class=\"row\"> "; // line 6 $this->loadTemplate("::modulesUsed/navigation.html.twig", "NeigeEtSoleilBundle:Default:Appartements/Layout/Appartements.html.twig", 6)->display($context); // line 7 echo " <div class=\"span9\"> <ul class=\"thumbnails\"> "; // line 10 $context['_parent'] = $context; $context['_seq'] = twig_ensure_traversable((isset($context["appartements"]) ? $context["appartements"] : $this->getContext($context, "appartements"))); foreach ($context['_seq'] as $context["_key"] => $context["appartement"]) { // line 11 echo " <li class=\"span3\"> <div class=\"thumbnail\"> <img src=\""; // line 13 echo twig_escape_filter($this->env, $this->env->getExtension('Symfony\Bridge\Twig\Extension\AssetExtension')->getAssetUrl("img/holder.png"), "html", null, true); echo "\" alt=\"DevAndClick\" width=\"300\" height=\"300\"> <div class=\"caption\"> <h4>"; // line 15 echo twig_escape_filter($this->env, $this->getAttribute($context["appartement"], "nomImmeubleA", array()), "html", null, true); echo "</h4> <p>"; // line 16 echo twig_escape_filter($this->env, $this->getAttribute($context["appartement"], "prix", array()), "html", null, true); echo " € /nuit, "; echo twig_escape_filter($this->env, $this->getAttribute($context["appartement"], "superficie", array()), "html", null, true); echo "m2</p> <a class=\"btn btn-primary\" href=\""; // line 17 echo twig_escape_filter($this->env, $this->env->getExtension('Symfony\Bridge\Twig\Extension\RoutingExtension')->getPath("Presentation", array("id" => $this->getAttribute($context["appartement"], "id", array()))), "html", null, true); echo "\">Plus d'infos</a> <a class=\"btn btn-success\" href=\"panier.php\">Réserver !</a> </div> </div> </li> "; } $_parent = $context['_parent']; unset($context['_seq'], $context['_iterated'], $context['_key'], $context['appartement'], $context['_parent'], $context['loop']); $context = array_intersect_key($context, $_parent) + $_parent; // line 23 echo " </ul> <div class=\"pagination\"> <ul> <li class=\"disabled\"><span>Précédent</span></li> <li class=\"disabled\"><span>1</span></li> <li><a href=\"#\">2</a></li> <li><a href=\"#\">3</a></li> <li><a href=\"#\">4</a></li> <li><a href=\"#\">5</a></li> <li><a href=\"#\">Suivant</a></li> </ul> </div> </div> </div> </div> "; $__internal_3d1cb3779f7481c1979ffef9d4b31626c5cd7b679fcfd8723a196754e728b478->leave($__internal_3d1cb3779f7481c1979ffef9d4b31626c5cd7b679fcfd8723a196754e728b478_prof); $__internal_a084b187c087e0a89bbfd58e48e2bc4ee9867b195557dfd50695d514bc35bf4c->leave($__internal_a084b187c087e0a89bbfd58e48e2bc4ee9867b195557dfd50695d514bc35bf4c_prof); } public function getTemplateName() { return "NeigeEtSoleilBundle:Default:Appartements/Layout/Appartements.html.twig"; } public function isTraitable() { return false; } public function getDebugInfo() { return array ( 95 => 23, 83 => 17, 77 => 16, 73 => 15, 68 => 13, 64 => 11, 60 => 10, 55 => 7, 53 => 6, 49 => 4, 40 => 3, 11 => 1,); } /** @deprecated since 1.27 (to be removed in 2.0). Use getSourceContext() instead */ public function getSource() { @trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use getSourceContext() instead.', E_USER_DEPRECATED); return $this->getSourceContext()->getCode(); } public function getSourceContext() { return new Twig_Source("{% extends '::layout/layout.html.twig' %} {% block body %} <div class=\"container\"> <div class=\"row\"> {% include '::modulesUsed/navigation.html.twig' %} <div class=\"span9\"> <ul class=\"thumbnails\"> {% for appartement in appartements %} <li class=\"span3\"> <div class=\"thumbnail\"> <img src=\"{{ asset('img/holder.png') }}\" alt=\"DevAndClick\" width=\"300\" height=\"300\"> <div class=\"caption\"> <h4>{{ appartement.nomImmeubleA }}</h4> <p>{{ appartement.prix }} € /nuit, {{ appartement.superficie }}m2</p> <a class=\"btn btn-primary\" href=\"{{ path('Presentation', {'id' : appartement.id}) }}\">Plus d'infos</a> <a class=\"btn btn-success\" href=\"panier.php\">Réserver !</a> </div> </div> </li> {% endfor %} </ul> <div class=\"pagination\"> <ul> <li class=\"disabled\"><span>Précédent</span></li> <li class=\"disabled\"><span>1</span></li> <li><a href=\"#\">2</a></li> <li><a href=\"#\">3</a></li> <li><a href=\"#\">4</a></li> <li><a href=\"#\">5</a></li> <li><a href=\"#\">Suivant</a></li> </ul> </div> </div> </div> </div> {% endblock %} ", "NeigeEtSoleilBundle:Default:Appartements/Layout/Appartements.html.twig", "C:\\wamp\\www\\NeigeEtSoleil\\src\\NeigeEtSoleilBundle/Resources/views/Default/Appartements/Layout/Appartements.html.twig"); } } <file_sep>/src/NeigeEtSoleilBundle/DataFixtures/ORM/TypeAppartementData.php <?php namespace NeigeEtSoleilBundle\DataFixtures\ORM; use Doctrine\Common\DataFixtures\AbstractFixture; use Doctrine\Common\DataFixtures\OrderedFixtureInterface; use Doctrine\Common\Persistence\ObjectManager; use NeigeEtSoleilBundle\Entity\Appartements; class AppartementsData extends AbstractFixture implements OrderedFixtureInterface { public function load(ObjectManager $manager) { $appartement1 = new Appartements(); $appartement1->setNomImmeubleA('Test Immeuble'); $appartement1->setPrix('60'); $appartement1->setSuperficie('40'); $appartement1->setVilleA('Test Town'); $appartement1->setCpA('28500'); $appartement1->setDisponible('1'); $appartement1->setTypeAppartement($this->getReference('typeAppartement1')); $manager->persist($appartement1); $appartement2 = new Appartements(); $appartement2->setNomImmeubleA('Immeuble Neige'); $appartement2->setPrix('40'); $appartement2->setVilleA('Test City'); $appartement2->setCpA('95200'); $appartement2->setSuperficie('30'); $appartement2->setDisponible('1'); $appartement2->setTypeAppartement($this->getReference('typeAppartement2')); $manager->persist($appartement2); $manager->flush(); } public function getOrder() { return 2; } } <file_sep>/var/cache/dev/twig/d3/d381eefb4984892312dcd8164a68b6e7acb6081c4c804604d42cbc772b1874b6.php <?php /* NeigeEtSoleilBundle:Default:Appartements/Layout/Presentation.html.twig */ class __TwigTemplate_5c7b3d21802518bbe5e8512116688f0624a4ad1372f1023e840a8dddb24debaf extends Twig_Template { public function __construct(Twig_Environment $env) { parent::__construct($env); // line 1 $this->parent = $this->loadTemplate("::layout/layout.html.twig", "NeigeEtSoleilBundle:Default:Appartements/Layout/Presentation.html.twig", 1); $this->blocks = array( 'body' => array($this, 'block_body'), ); } protected function doGetParent(array $context) { return "::layout/layout.html.twig"; } protected function doDisplay(array $context, array $blocks = array()) { $__internal_533b32ca44ddbe8e7ae5f0f9b534a659781953672bcd8545025f52a489d10cb6 = $this->env->getExtension("Symfony\\Bundle\\WebProfilerBundle\\Twig\\WebProfilerExtension"); $__internal_533b32ca44ddbe8e7ae5f0f9b534a659781953672bcd8545025f52a489d10cb6->enter($__internal_533b32ca44ddbe8e7ae5f0f9b534a659781953672bcd8545025f52a489d10cb6_prof = new Twig_Profiler_Profile($this->getTemplateName(), "template", "NeigeEtSoleilBundle:Default:Appartements/Layout/Presentation.html.twig")); $__internal_493cff65169026f08589586547e95cf7dec8b5a824e19a2763e9d0d5111c5962 = $this->env->getExtension("Symfony\\Bridge\\Twig\\Extension\\ProfilerExtension"); $__internal_493cff65169026f08589586547e95cf7dec8b5a824e19a2763e9d0d5111c5962->enter($__internal_493cff65169026f08589586547e95cf7dec8b5a824e19a2763e9d0d5111c5962_prof = new Twig_Profiler_Profile($this->getTemplateName(), "template", "NeigeEtSoleilBundle:Default:Appartements/Layout/Presentation.html.twig")); $this->parent->display($context, array_merge($this->blocks, $blocks)); $__internal_533b32ca44ddbe8e7ae5f0f9b534a659781953672bcd8545025f52a489d10cb6->leave($__internal_533b32ca44ddbe8e7ae5f0f9b534a659781953672bcd8545025f52a489d10cb6_prof); $__internal_493cff65169026f08589586547e95cf7dec8b5a824e19a2763e9d0d5111c5962->leave($__internal_493cff65169026f08589586547e95cf7dec8b5a824e19a2763e9d0d5111c5962_prof); } // line 3 public function block_body($context, array $blocks = array()) { $__internal_f73680b309871ac256a909c6c3fdd32b88a4faddda2ff11f0bc364e41a14ed12 = $this->env->getExtension("Symfony\\Bundle\\WebProfilerBundle\\Twig\\WebProfilerExtension"); $__internal_f73680b309871ac256a909c6c3fdd32b88a4faddda2ff11f0bc364e41a14ed12->enter($__internal_f73680b309871ac256a909c6c3fdd32b88a4faddda2ff11f0bc364e41a14ed12_prof = new Twig_Profiler_Profile($this->getTemplateName(), "block", "body")); $__internal_932a2786c2bc50c722a70dee28c62806d20809dab091d63c0e78de0b5f07fdff = $this->env->getExtension("Symfony\\Bridge\\Twig\\Extension\\ProfilerExtension"); $__internal_932a2786c2bc50c722a70dee28c62806d20809dab091d63c0e78de0b5f07fdff->enter($__internal_932a2786c2bc50c722a70dee28c62806d20809dab091d63c0e78de0b5f07fdff_prof = new Twig_Profiler_Profile($this->getTemplateName(), "block", "body")); // line 4 echo " <div class=\"container\"> <div class=\"row\"> "; // line 7 $this->loadTemplate("::modulesUsed/navigation.html.twig", "NeigeEtSoleilBundle:Default:Appartements/Layout/Presentation.html.twig", 7)->display($context); // line 8 echo " <div class=\"span9\"> <div class=\"row\"> <div class=\"span5\"> <img src=\""; // line 11 echo twig_escape_filter($this->env, $this->env->getExtension('Symfony\Bridge\Twig\Extension\AssetExtension')->getAssetUrl("img/holder.png"), "html", null, true); echo "\" alt=\"DevAndClick\" width=\"470\" height=\"310\"> </div> <div class=\"span4\"> <h4>"; // line 15 echo twig_escape_filter($this->env, $this->getAttribute((isset($context["appartement"]) ? $context["appartement"] : $this->getContext($context, "appartement")), "nomImmeubleA", array()), "html", null, true); echo "</h4> <h5>"; // line 16 echo twig_escape_filter($this->env, $this->getAttribute((isset($context["appartement"]) ? $context["appartement"] : $this->getContext($context, "appartement")), "villeA", array()), "html", null, true); echo ", "; echo twig_escape_filter($this->env, $this->getAttribute((isset($context["appartement"]) ? $context["appartement"] : $this->getContext($context, "appartement")), "cpA", array()), "html", null, true); echo "</h5> <p>Charmant appartement de "; // line 17 echo twig_escape_filter($this->env, $this->getAttribute((isset($context["appartement"]) ? $context["appartement"] : $this->getContext($context, "appartement")), "superficie", array()), "html", null, true); echo " m2 situe a "; echo twig_escape_filter($this->env, $this->getAttribute((isset($context["appartement"]) ? $context["appartement"] : $this->getContext($context, "appartement")), "villeA", array()), "html", null, true); echo ". Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p> <h4>"; // line 21 echo twig_escape_filter($this->env, $this->getAttribute((isset($context["appartement"]) ? $context["appartement"] : $this->getContext($context, "appartement")), "prix", array()), "html", null, true); echo "€ /nuit</h4> <form action=\"panier.php\"> <div> <button class=\"btn btn-primary\">Réserver !</button> </div> </form> </div> </div> </div> </div> </div> "; $__internal_932a2786c2bc50c722a70dee28c62806d20809dab091d63c0e78de0b5f07fdff->leave($__internal_932a2786c2bc50c722a70dee28c62806d20809dab091d63c0e78de0b5f07fdff_prof); $__internal_f73680b309871ac256a909c6c3fdd32b88a4faddda2ff11f0bc364e41a14ed12->leave($__internal_f73680b309871ac256a909c6c3fdd32b88a4faddda2ff11f0bc364e41a14ed12_prof); } public function getTemplateName() { return "NeigeEtSoleilBundle:Default:Appartements/Layout/Presentation.html.twig"; } public function isTraitable() { return false; } public function getDebugInfo() { return array ( 87 => 21, 78 => 17, 72 => 16, 68 => 15, 61 => 11, 56 => 8, 54 => 7, 49 => 4, 40 => 3, 11 => 1,); } /** @deprecated since 1.27 (to be removed in 2.0). Use getSourceContext() instead */ public function getSource() { @trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use getSourceContext() instead.', E_USER_DEPRECATED); return $this->getSourceContext()->getCode(); } public function getSourceContext() { return new Twig_Source("{% extends '::layout/layout.html.twig' %} {% block body %} <div class=\"container\"> <div class=\"row\"> {% include '::modulesUsed/navigation.html.twig' %} <div class=\"span9\"> <div class=\"row\"> <div class=\"span5\"> <img src=\"{{ asset('img/holder.png') }}\" alt=\"DevAndClick\" width=\"470\" height=\"310\"> </div> <div class=\"span4\"> <h4>{{ appartement.nomImmeubleA }}</h4> <h5>{{ appartement.villeA }}, {{ appartement.cpA }}</h5> <p>Charmant appartement de {{ appartement.superficie }} m2 situe a {{ appartement.villeA }}. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p> <h4>{{ appartement.prix }}€ /nuit</h4> <form action=\"panier.php\"> <div> <button class=\"btn btn-primary\">Réserver !</button> </div> </form> </div> </div> </div> </div> </div> {% endblock %} ", "NeigeEtSoleilBundle:Default:Appartements/Layout/Presentation.html.twig", "C:\\wamp\\www\\NeigeEtSoleil\\src\\NeigeEtSoleilBundle/Resources/views/Default/Appartements/Layout/Presentation.html.twig"); } } <file_sep>/var/cache/dev/twig/63/63d82b978c2ea6f9da40f6ecc0184f5acd7c2c416a94e379b623f042ba41a2d3.php <?php /* ::layout/layout.html.twig */ class __TwigTemplate_4d1ac9bbac60a88a1e805cd32916ac7c2a0ceb235f1d35137a9d2ef51cc34f7f extends Twig_Template { public function __construct(Twig_Environment $env) { parent::__construct($env); $this->parent = false; $this->blocks = array( 'title' => array($this, 'block_title'), 'stylesheets' => array($this, 'block_stylesheets'), 'body' => array($this, 'block_body'), 'javascripts' => array($this, 'block_javascripts'), ); } protected function doDisplay(array $context, array $blocks = array()) { $__internal_283ba82a97f750483c95b6a593b1ff153a3be353b98b145fed22d0fab01ed2b5 = $this->env->getExtension("Symfony\\Bundle\\WebProfilerBundle\\Twig\\WebProfilerExtension"); $__internal_283ba82a97f750483c95b6a593b1ff153a3be353b98b145fed22d0fab01ed2b5->enter($__internal_283ba82a97f750483c95b6a593b1ff153a3be353b98b145fed22d0fab01ed2b5_prof = new Twig_Profiler_Profile($this->getTemplateName(), "template", "::layout/layout.html.twig")); $__internal_fec762a89b2f19f738d49bb54aedb6f6e0bdd67ec9b9db4454e40ab855b6b8ad = $this->env->getExtension("Symfony\\Bridge\\Twig\\Extension\\ProfilerExtension"); $__internal_fec762a89b2f19f738d49bb54aedb6f6e0bdd67ec9b9db4454e40ab855b6b8ad->enter($__internal_fec762a89b2f19f738d49bb54aedb6f6e0bdd67ec9b9db4454e40ab855b6b8ad_prof = new Twig_Profiler_Profile($this->getTemplateName(), "template", "::layout/layout.html.twig")); // line 1 echo "<!DOCTYPE html> <html> <head> <meta charset=\"UTF-8\" /> <title>"; // line 5 $this->displayBlock('title', $context, $blocks); echo "</title> <link rel=\"stylesheet\" href=\""; // line 6 echo twig_escape_filter($this->env, $this->env->getExtension('Symfony\Bridge\Twig\Extension\AssetExtension')->getAssetUrl("css/bootstrap.css"), "html", null, true); echo "\" /> <link rel=\"stylesheet\" href=\""; // line 7 echo twig_escape_filter($this->env, $this->env->getExtension('Symfony\Bridge\Twig\Extension\AssetExtension')->getAssetUrl("css/bootstrap-responsive.css"), "html", null, true); echo "\" /> <link rel=\"stylesheet\" href=\""; // line 8 echo twig_escape_filter($this->env, $this->env->getExtension('Symfony\Bridge\Twig\Extension\AssetExtension')->getAssetUrl("css/style.css"), "html", null, true); echo "\" /> <link rel=\"stylesheet\" href=\""; // line 9 echo twig_escape_filter($this->env, $this->env->getExtension('Symfony\Bridge\Twig\Extension\AssetExtension')->getAssetUrl("css/font-awesome.css"), "html", null, true); echo "\" /> "; // line 10 $this->displayBlock('stylesheets', $context, $blocks); // line 11 echo " <link rel=\"icon\" type=\"image/x-icon\" href=\""; echo twig_escape_filter($this->env, $this->env->getExtension('Symfony\Bridge\Twig\Extension\AssetExtension')->getAssetUrl("favicon.ico"), "html", null, true); echo "\" /> </head> <body> <div class=\"navbar navbar-inverse navbar-fixed-top\"> <div class=\"navbar-inner\"> <div class=\"container\"> <button class=\"btn btn-navbar\" data-target=\".nav-collapse\" data-toggle=\"collapse\" type=\"button\"> <span class=\"icon-bar\"></span> <span class=\"icon-bar\"></span> <span class=\"icon-bar\"></span> </button> <a class=\"brand\" href=\""; // line 22 echo $this->env->getExtension('Symfony\Bridge\Twig\Extension\RoutingExtension')->getPath("Appartements"); echo "\">Neige &amp; Soleil</a> <div class=\"nav-collapse collapse\"> <form class=\"navbar-form form-search pull-right\"> <input id=\"Search\" name=\"Search\" type=\"text\" class=\"input-medium search-query\"> <button type=\"submit\" class=\"btn\">Rechercher</button> </form> </div> </div> </div> </div> "; // line 32 $this->displayBlock('body', $context, $blocks); // line 33 echo "<hr /> <footer id=\"footer\" class=\"vspace20\"> <div class=\"container\"> <div class=\"row\"> <div class=\"span4 offset1\"> <h4>Informations</h4> <ul class=\"nav nav-stacked\"> <li><a href=\""; // line 40 echo $this->env->getExtension('Symfony\Bridge\Twig\Extension\RoutingExtension')->getPath("page", array("id" => 1)); echo "\">Mentions légales</a> </ul> </div> </div> <div class=\"row\"> <div class=\"span4\"> <p>&copy; Copyright 2016 - Neige & Soleil</p> </div> </div> </div> </footer>\t <script src=\""; // line 52 echo twig_escape_filter($this->env, $this->env->getExtension('Symfony\Bridge\Twig\Extension\AssetExtension')->getAssetUrl("js/jquery-1.10.0.min.js"), "html", null, true); echo "\"></script> <script src=\""; // line 53 echo twig_escape_filter($this->env, $this->env->getExtension('Symfony\Bridge\Twig\Extension\AssetExtension')->getAssetUrl("js/bootstrap.js"), "html", null, true); echo "\"></script> "; // line 54 $this->displayBlock('javascripts', $context, $blocks); // line 55 echo "</body> </html> "; $__internal_283ba82a97f750483c95b6a593b1ff153a3be353b98b145fed22d0fab01ed2b5->leave($__internal_283ba82a97f750483c95b6a593b1ff153a3be353b98b145fed22d0fab01ed2b5_prof); $__internal_fec762a89b2f19f738d49bb54aedb6f6e0bdd67ec9b9db4454e40ab855b6b8ad->leave($__internal_fec762a89b2f19f738d49bb54aedb6f6e0bdd67ec9b9db4454e40ab855b6b8ad_prof); } // line 5 public function block_title($context, array $blocks = array()) { $__internal_36edcd31aabaa5a8094b3614b2f4f49b25557f8ba176c2533c472f973f830aa7 = $this->env->getExtension("Symfony\\Bundle\\WebProfilerBundle\\Twig\\WebProfilerExtension"); $__internal_36edcd31aabaa5a8094b3614b2f4f49b25557f8ba176c2533c472f973f830aa7->enter($__internal_36edcd31aabaa5a8094b3614b2f4f49b25557f8ba176c2533c472f973f830aa7_prof = new Twig_Profiler_Profile($this->getTemplateName(), "block", "title")); $__internal_a253e5a0ac1fdd00136041997bc8f0cc9a74cc36bfa09795b93f4679924c2491 = $this->env->getExtension("Symfony\\Bridge\\Twig\\Extension\\ProfilerExtension"); $__internal_a253e5a0ac1fdd00136041997bc8f0cc9a74cc36bfa09795b93f4679924c2491->enter($__internal_a253e5a0ac1fdd00136041997bc8f0cc9a74cc36bfa09795b93f4679924c2491_prof = new Twig_Profiler_Profile($this->getTemplateName(), "block", "title")); echo "Welcome!"; $__internal_a253e5a0ac1fdd00136041997bc8f0cc9a74cc36bfa09795b93f4679924c2491->leave($__internal_a253e5a0ac1fdd00136041997bc8f0cc9a74cc36bfa09795b93f4679924c2491_prof); $__internal_36edcd31aabaa5a8094b3614b2f4f49b25557f8ba176c2533c472f973f830aa7->leave($__internal_36edcd31aabaa5a8094b3614b2f4f49b25557f8ba176c2533c472f973f830aa7_prof); } // line 10 public function block_stylesheets($context, array $blocks = array()) { $__internal_55907c235b9fa7cb98e4a631c8f5cdd461cd4a52742c669221c5483567030e8c = $this->env->getExtension("Symfony\\Bundle\\WebProfilerBundle\\Twig\\WebProfilerExtension"); $__internal_55907c235b9fa7cb98e4a631c8f5cdd461cd4a52742c669221c5483567030e8c->enter($__internal_55907c235b9fa7cb98e4a631c8f5cdd461cd4a52742c669221c5483567030e8c_prof = new Twig_Profiler_Profile($this->getTemplateName(), "block", "stylesheets")); $__internal_747dd5efc3d712ab9ed06887799b4a88542a74dea55af7693d4638b8bf54f188 = $this->env->getExtension("Symfony\\Bridge\\Twig\\Extension\\ProfilerExtension"); $__internal_747dd5efc3d712ab9ed06887799b4a88542a74dea55af7693d4638b8bf54f188->enter($__internal_747dd5efc3d712ab9ed06887799b4a88542a74dea55af7693d4638b8bf54f188_prof = new Twig_Profiler_Profile($this->getTemplateName(), "block", "stylesheets")); $__internal_747dd5efc3d712ab9ed06887799b4a88542a74dea55af7693d4638b8bf54f188->leave($__internal_747dd5efc3d712ab9ed06887799b4a88542a74dea55af7693d4638b8bf54f188_prof); $__internal_55907c235b9fa7cb98e4a631c8f5cdd461cd4a52742c669221c5483567030e8c->leave($__internal_55907c235b9fa7cb98e4a631c8f5cdd461cd4a52742c669221c5483567030e8c_prof); } // line 32 public function block_body($context, array $blocks = array()) { $__internal_8819dd5c75f684acc0cb1144131169182a292b686d81fc6841b701ad8febe2c8 = $this->env->getExtension("Symfony\\Bundle\\WebProfilerBundle\\Twig\\WebProfilerExtension"); $__internal_8819dd5c75f684acc0cb1144131169182a292b686d81fc6841b701ad8febe2c8->enter($__internal_8819dd5c75f684acc0cb1144131169182a292b686d81fc6841b701ad8febe2c8_prof = new Twig_Profiler_Profile($this->getTemplateName(), "block", "body")); $__internal_9f45ba75a075c455d993d753b0d9c524bf98e351ee619eccccc311c022e2719f = $this->env->getExtension("Symfony\\Bridge\\Twig\\Extension\\ProfilerExtension"); $__internal_9f45ba75a075c455d993d753b0d9c524bf98e351ee619eccccc311c022e2719f->enter($__internal_9f45ba75a075c455d993d753b0d9c524bf98e351ee619eccccc311c022e2719f_prof = new Twig_Profiler_Profile($this->getTemplateName(), "block", "body")); $__internal_9f45ba75a075c455d993d753b0d9c524bf98e351ee619eccccc311c022e2719f->leave($__internal_9f45ba75a075c455d993d753b0d9c524bf98e351ee619eccccc311c022e2719f_prof); $__internal_8819dd5c75f684acc0cb1144131169182a292b686d81fc6841b701ad8febe2c8->leave($__internal_8819dd5c75f684acc0cb1144131169182a292b686d81fc6841b701ad8febe2c8_prof); } // line 54 public function block_javascripts($context, array $blocks = array()) { $__internal_a3098ca3a1d6ff16ce8dd8e6c18d55d599413703bf2c8a051ab4a6b249f34bf2 = $this->env->getExtension("Symfony\\Bundle\\WebProfilerBundle\\Twig\\WebProfilerExtension"); $__internal_a3098ca3a1d6ff16ce8dd8e6c18d55d599413703bf2c8a051ab4a6b249f34bf2->enter($__internal_a3098ca3a1d6ff16ce8dd8e6c18d55d599413703bf2c8a051ab4a6b249f34bf2_prof = new Twig_Profiler_Profile($this->getTemplateName(), "block", "javascripts")); $__internal_990c41c23c5412ca040ca2437cdc45b55201e7bd13b9006e469593bba8d22da6 = $this->env->getExtension("Symfony\\Bridge\\Twig\\Extension\\ProfilerExtension"); $__internal_990c41c23c5412ca040ca2437cdc45b55201e7bd13b9006e469593bba8d22da6->enter($__internal_990c41c23c5412ca040ca2437cdc45b55201e7bd13b9006e469593bba8d22da6_prof = new Twig_Profiler_Profile($this->getTemplateName(), "block", "javascripts")); $__internal_990c41c23c5412ca040ca2437cdc45b55201e7bd13b9006e469593bba8d22da6->leave($__internal_990c41c23c5412ca040ca2437cdc45b55201e7bd13b9006e469593bba8d22da6_prof); $__internal_a3098ca3a1d6ff16ce8dd8e6c18d55d599413703bf2c8a051ab4a6b249f34bf2->leave($__internal_a3098ca3a1d6ff16ce8dd8e6c18d55d599413703bf2c8a051ab4a6b249f34bf2_prof); } public function getTemplateName() { return "::layout/layout.html.twig"; } public function isTraitable() { return false; } public function getDebugInfo() { return array ( 185 => 54, 168 => 32, 151 => 10, 133 => 5, 121 => 55, 119 => 54, 115 => 53, 111 => 52, 96 => 40, 87 => 33, 85 => 32, 72 => 22, 57 => 11, 55 => 10, 51 => 9, 47 => 8, 43 => 7, 39 => 6, 35 => 5, 29 => 1,); } /** @deprecated since 1.27 (to be removed in 2.0). Use getSourceContext() instead */ public function getSource() { @trigger_error('The '.__METHOD__.' method is deprecated since version 1.27 and will be removed in 2.0. Use getSourceContext() instead.', E_USER_DEPRECATED); return $this->getSourceContext()->getCode(); } public function getSourceContext() { return new Twig_Source("<!DOCTYPE html> <html> <head> <meta charset=\"UTF-8\" /> <title>{% block title %}Welcome!{% endblock %}</title> <link rel=\"stylesheet\" href=\"{{ asset('css/bootstrap.css') }}\" /> <link rel=\"stylesheet\" href=\"{{ asset('css/bootstrap-responsive.css') }}\" /> <link rel=\"stylesheet\" href=\"{{ asset('css/style.css') }}\" /> <link rel=\"stylesheet\" href=\"{{ asset('css/font-awesome.css') }}\" /> {% block stylesheets %}{% endblock %} <link rel=\"icon\" type=\"image/x-icon\" href=\"{{ asset('favicon.ico') }}\" /> </head> <body> <div class=\"navbar navbar-inverse navbar-fixed-top\"> <div class=\"navbar-inner\"> <div class=\"container\"> <button class=\"btn btn-navbar\" data-target=\".nav-collapse\" data-toggle=\"collapse\" type=\"button\"> <span class=\"icon-bar\"></span> <span class=\"icon-bar\"></span> <span class=\"icon-bar\"></span> </button> <a class=\"brand\" href=\"{{ path ('Appartements') }}\">Neige &amp; Soleil</a> <div class=\"nav-collapse collapse\"> <form class=\"navbar-form form-search pull-right\"> <input id=\"Search\" name=\"Search\" type=\"text\" class=\"input-medium search-query\"> <button type=\"submit\" class=\"btn\">Rechercher</button> </form> </div> </div> </div> </div> {% block body %}{% endblock %} <hr /> <footer id=\"footer\" class=\"vspace20\"> <div class=\"container\"> <div class=\"row\"> <div class=\"span4 offset1\"> <h4>Informations</h4> <ul class=\"nav nav-stacked\"> <li><a href=\"{{ path ('page', {'id' : 1 }) }}\">Mentions légales</a> </ul> </div> </div> <div class=\"row\"> <div class=\"span4\"> <p>&copy; Copyright 2016 - Neige & Soleil</p> </div> </div> </div> </footer>\t <script src=\"{{ asset('js/jquery-1.10.0.min.js') }}\"></script> <script src=\"{{ asset('js/bootstrap.js') }}\"></script> {% block javascripts %}{% endblock %} </body> </html> ", "::layout/layout.html.twig", "C:\\wamp\\www\\NeigeEtSoleil\\app/Resources\\views/layout/layout.html.twig"); } } <file_sep>/src/NeigeEtSoleilBundle/Form/testType.php <?php namespace NeigeEtSoleil\NeigeEtSoleilBundle\Form; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; class testType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { //ici dev du formulaire php $builder->add('email'); } public function getName() { return 'neigeetsoleil_neigeetsoleilbundle_test'; } } <file_sep>/src/NeigeEtSoleilBundle/Entity/contratL.php <?php namespace NeigeEtSoleilBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * contratL * * @ORM\Table(name="contrat_l") * @ORM\Entity(repositoryClass="NeigeEtSoleilBundle\Repository\contratLRepository") */ class contratL { /** * @var int * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @var \DateTime * * @ORM\Column(name="dateDebutCL", type="date", nullable=true) */ private $dateDebutCL; /** * @var \DateTime * * @ORM\Column(name="dateFinCL", type="date", nullable=true) */ private $dateFinCL; /** * @var \DateTime * * @ORM\Column(name="dateSignatureCL", type="date", nullable=true) */ private $dateSignatureCL; /** * Get id * * @return int */ public function getId() { return $this->id; } /** * Set dateDebutCL * * @param \DateTime $dateDebutCL * * @return contratL */ public function setDateDebutCL($dateDebutCL) { $this->dateDebutCL = $dateDebutCL; return $this; } /** * Get dateDebutCL * * @return \DateTime */ public function getDateDebutCL() { return $this->dateDebutCL; } /** * Set dateFinCL * * @param \DateTime $dateFinCL * * @return contratL */ public function setDateFinCP($dateFinCL) { $this->dateFinCL = $dateFinCL; return $this; } /** * Get dateFinCL * * @return \DateTime */ public function getDateFinCL() { return $this->dateFinCL; } /** * Set dateSignatureCL * * @param \DateTime $dateSignatureCL * * @return contratL */ public function setDateSignatureCL($dateSignatureCL) { $this->dateSignatureCL = $dateSignatureCL; return $this; } /** * Get dateSignatureCL * * @return \DateTime */ public function getDateSignatureCL() { return $this->dateSignatureCL; } }
30a4a90ec20526a5f85b6a8789eccccc529bdaca
[ "PHP" ]
9
PHP
babidi34/PPE
0d7f28b3689c928204d8a308d1b2f31a2f2c9dc6
8ae6eb9f96a8042f8030f51ece2a3888c809953c
refs/heads/main
<repo_name>uclibs/scholar_uc_fedora<file_sep>/README.md Configuration for Scholar@UC's Fedora Repository In addition to the files in this repo, create a file called `fcrepo_variables.sh` using the format below. Adjust each line as needed. ``` #!/bin/sh FCREPO_DATA_DIR="/mnt/hydra/fcrepo/data" FCREPO_CONFIG_DIR="/mnt/hydra/fcrepo/etc" FCREPO_TMP_DIR="/mnt/hydra/fcrepo/tmp" TOMCAT_DIR="/opt/tomcat" JRE_HOME_DIR="/usr/lib/jvm/jre" MIN_HEAP="6000" MAX_HEAP="6000" MYSQL_HOST="localhost" MYSQL_PORT="3306" MYSQL_USER="FedoraAdmin" MYSQL_PASS="<PASSWORD>" ``` <file_sep>/fcrepo_start.sh #!/bin/sh . /opt/hydra/fedora/etc/fcrepo_config.sh /opt/tomcat/bin/startup.sh <file_sep>/fcrepo_config.sh #!/bin/sh my_dir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" source $my_dir/fcrepo_variables.sh OPTS=" -Dfile.encoding=UTF-8 \ -Djava.awt.headless=true \ -Dlogback.configurationFile=$FCREPO_CONFIG_DIR/logback.xml \ -Dfcrepo.home=$FCREPO_DATA_DIR \ -Dfcrepo.modeshape.configuration=file:$FCREPO_CONFIG_DIR/repository-mysql.json \ -Dfcrepo.activemq.configuration=file:$FCREPO_CONFIG_DIR/activemq.xml \ -Dfcrepo.modeshape.index.directory=modeshape.index \ -Dfcrepo.binary.directory=binary.store \ -Dfcrepo.activemq.directory=activemq \ -Dcom.arjuna.ats.arjuna.common.ObjectStoreEnvironmentBean.default.objectStoreDir=arjuna.common.object.store \ -Dcom.arjuna.ats.arjuna.objectstore.objectStoreDir=arjuna.object.store \ -Dnet.sf.ehcache.skipUpdateCheck=true \ -Djava.io.tmpdir=$FCREPO_TMP_DIR \ -server \ " GC_CONFIG=" -XX:+DisableExplicitGC \ -XX:ConcGCThreads=5 \ -XX:MaxGCPauseMillis=200 \ -XX:ParallelGCThreads=20 \ " GC_CONFIG_LARGE_HEAP=" -XX:+UseG1GC \ " GC_CONFIG_SMALL_HEAP=" -XX:+UseConcMarkSweepGC \ -XX:+CMSClassUnloadingEnabled \ " MEMORY_CONFIG=" -XX:MaxMetaspaceSize=512m \ -Xms${MIN_HEAP}m \ -Xmx${MAX_HEAP}m \ " MYSQL_CONFIG=" -Dfcrepo.mysql.username=$MYSQL_USER \ -Dfcrepo.mysql.password=$MYSQL_PASS \ -Dfcrepo.mysql.host=$MYSQL_HOST \ -Dfcrepo.mysql.port=$MYSQL_PORT \ " if [ ${MIN_HEAP} -gt 4096 ] then export JAVA_OPTS="$OPTS $MYSQL_CONFIG $GC_CONFIG $GC_CONFIG_LARGE_HEAP $MEMORY_CONFIG" else export JAVA_OPTS="$OPTS $MYSQL_CONFIG $GC_CONFIG $GC_CONFIG_SMALL_HEAP $MEMORY_CONFIG" fi export CATALINA_BASE="$TOMCAT_DIR"; export CATALINA_HOME="$TOMCAT_DIR"; export CATALINA_TMPDIR="$FCREPO_TMP_DIR"; export CLASSPATH="$TOMCAT_DIR/bin/bootstrap.jar:$TOMCAT_DIR/bin/tomcat-juli.jar" export JRE_HOME="$JRE_HOME_DIR"
5319abbd7895679a91d49827b095c417f02ff0e2
[ "Markdown", "Shell" ]
3
Markdown
uclibs/scholar_uc_fedora
cc2c5ed06372efecef1c66d8be05fd7751af614d
71f513f3966b4a8bd6535b1db1dbcd90d8a942fd
refs/heads/master
<repo_name>JBrandy/Reloj<file_sep>/Prueba/src/prueba/prueba.java package prueba; import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.layout.VBox; import javafx.scene.text.Font; import javafx.stage.Stage; import reloj.Evento; import reloj.MetodosTareas; import reloj.Reloj; import reloj.Tarea; import java.time.LocalDate; public class prueba extends Application { @Override public void start(Stage stage) throws Exception { VBox vBox = new VBox(); Reloj reloj = new Reloj(); LocalDate fecha = LocalDate.now(); Tarea a = new Tarea("prueba",fecha, 13,25, null ); MetodosTareas.getInstance().anadirTarea(a); reloj.setFormato24Horas(false); reloj.start(); reloj.addEvento(new Evento() { @Override public void inicioTarea(Tarea tarea) { } }); reloj.setFont(new Font(42)); vBox.getChildren().add(reloj); Scene scene = new Scene(vBox); stage.setScene(scene); stage.show(); } public static void main(String [] args){ launch(args); } }<file_sep>/src/reloj/Tarea.java package reloj; import java.time.LocalDate; public class Tarea { private String tarea; private LocalDate fecha; private int hora; private int minuto; private int segundo; private String realizado; public Tarea(String tarea, LocalDate fecha, int hora, int minuto, String realizado) { this.tarea = tarea; this.fecha = fecha; this.hora = hora; this.minuto = minuto; this.segundo = 5; this.realizado = realizado; } public String getTarea() { return tarea; } public void setTarea(String tarea) { this.tarea = tarea; } public LocalDate getFecha() { return fecha; } public void setFecha(LocalDate fecha) { this.fecha = fecha; } public int getHora() { return hora; } public void setHora(Integer hora) { this.hora = hora; } public int getMinuto() { return minuto; } public void setMinuto(Integer minuto) { this.minuto = minuto; } public int getSegundo() { return segundo; } public void setSegundo(int segundo) { this.segundo = segundo; } public String getRealizado() { return realizado; } public void setRealizado(String realizado) { this.realizado = realizado; } @Override public String toString() { return "Tarea{" + "tarea='" + tarea + '\'' + ", fecha=" + fecha + ", hora=" + hora + ", minuto=" + minuto + ", realizado='" + realizado + '\'' + '}'; } }
11c040dc27d735c1f0b54cd31da2a4eeb30ed8a2
[ "Java" ]
2
Java
JBrandy/Reloj
fc5f22aaf352e7d18149f398040beae228cd517d
553a69f7d8bd94795daf46ffa37a06773c6d4639
refs/heads/master
<repo_name>spongin/dotfiles<file_sep>/Brewfile # Install GNU core utilities (those that come with OS X are outdated) # Don’t forget to add `$(brew --prefix coreutils)/libexec/gnubin` to `$PATH`. brew 'coreutils' # Install GNU `find`, `locate`, `updatedb`, and `xargs`, g-prefixed brew 'findutils' # Install wget with IRI support brew 'wget', args: ['enable-iri'] # Install more recent versions of some OS X tools brew 'vim', args: ['override-system-vi'] brew 'tmux' brew 'zsh' brew 'curl' brew 'ctags-exuberant' brew 'ack' brew 'imagemagick', args: ['with-webp'] brew 'tree' brew 'webkit2png' brew 'boot2docker' brew 'python' brew 'fontforge', args: ['use-gcc'] <file_sep>/.oh-my-zsh-custom/virtualenv.zsh autoload add-zsh-hook launch_venv() { # Automatically activate the virtualenv # if one is detected in the cwd. [[ (-d env/bin && -r env/bin/activate && "$VIRTUAL_ENV" != "$(pwd)/env") ]] && . env/bin/activate } create_venv() { [[ ! (-d env/bin && -r env/bin/activate ) ]] && virtualenv --prompt="($(basename `pwd`))" env } add-zsh-hook chpwd launch_venv add-zsh-hook precmd launch_venv <file_sep>/.osx #!/usr/bin/env bash sudo -v echo "Set standby delay to 24 hours (default is 1 hour)" sudo pmset -a standbydelay 86400 echo "Disable the sound effects on boot" sudo nvram SystemAudioVolume=" " echo "Menu bar: hide the Time Machine, Volume, and User" for domain in ~/Library/Preferences/ByHost/com.apple.systemuiserver.*; do defaults write "${domain}" dontAutoLoad -array \ "/System/Library/CoreServices/Menu Extras/TimeMachine.menu" \ "/System/Library/CoreServices/Menu Extras/Volume.menu" \ "/System/Library/CoreServices/Menu Extras/User.menu" done defaults write com.apple.systemuiserver menuExtras -array \ "/System/Library/CoreServices/Menu Extras/Bluetooth.menu" \ "/System/Library/CoreServices/Menu Extras/Displays.menu" \ "/System/Library/CoreServices/Menu Extras/AirPort.menu" \ "/System/Library/CoreServices/Menu Extras/Battery.menu" \ "/System/Library/CoreServices/Menu Extras/Clock.menu" echo "Always show scrollbars" defaults write NSGlobalDomain AppleShowScrollBars -string "Always" echo "Menu bar: disable transparency" defaults write NSGlobalDomain AppleEnableMenuBarTransparency -bool false echo "Allow text selection in Quick Look" defaults write com.apple.finder QLEnableTextSelection -bool true echo "Avoid creating .DS_Store files on network volumes" defaults write com.apple.desktopservices DSDontWriteNetworkStores -bool true echo "Remove the animation when hiding/showing the Dock" defaults write com.apple.dock autohide-time-modifier -float 0 echo "Disable opening and closing window animations" defaults write NSGlobalDomain NSAutomaticWindowAnimationsEnabled -bool false echo "Increase window resize speed for Cocoa applications" defaults write NSGlobalDomain NSWindowResizeTime -float 0.001 echo "Expand save panel by default" defaults write NSGlobalDomain NSNavPanelExpandedStateForSaveMode -bool true defaults write NSGlobalDomain PMPrintingExpandedStateForPrint -bool true defaults write NSGlobalDomain PMPrintingExpandedStateForPrint2 -bool true echo "Finder: allow quitting via ⌘ + Q; doing so will also hide desktop icons" defaults write com.apple.finder QuitMenuItem -bool true echo "Restart automatically if the computer freezes" sudo systemsetup -setrestartfreeze on echo "Never go into computer sleep mode" sudo systemsetup -setcomputersleep Off > /dev/null echo "Check for software updates every two weeks, not once per week" defaults write com.apple.SoftwareUpdate ScheduleFrequency -int 14 echo "Remove duplicates in the 'Open With' menu" /System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister -kill -r -domain local -domain system -domain user echo "Disable Notification Center and remove the menu bar icon" launchctl unload -w /System/Library/LaunchAgents/com.apple.notificationcenterui.plist 2> /dev/null echo "Reveal IP address, hostname, OS version, etc. when clicking the clock" echo "in the login window" sudo defaults write /Library/Preferences/com.apple.loginwindow AdminHostInfo HostName echo "Ability to toggle between Light and Dark mode in Yosemite using ctrl+opt+cmd+t" sudo defaults write /Library/Preferences/.GlobalPreferences.plist _HIEnableThemeSwitchHotKey -bool true echo "Disable smart quotes and smart dashes" defaults write NSGlobalDomain NSAutomaticQuoteSubstitutionEnabled -bool false defaults write NSGlobalDomain NSAutomaticDashSubstitutionEnabled -bool false echo "Disable smart dashes as they're annoying when typing code" defaults write NSGlobalDomain NSAutomaticDashSubstitutionEnabled -bool false echo "Disable local Time Machine snapshots" hash tmutil &> /dev/null && sudo tmutil disablelocal echo "Set Help Viewer windows to non-floating mode" defaults write com.apple.helpviewer DevMode -bool true echo "Disable the crash reporter" defaults write com.apple.CrashReporter DialogType -string "none" echo "Disable automatic termination of inactive apps" defaults write NSGlobalDomain NSDisableAutomaticTermination -bool true echo "Disable Resume system-wide" defaults write NSGlobalDomain NSQuitAlwaysKeepsWindows -bool false echo "Display ASCII control characters using caret notation in standard text views" # Try e.g. `cd /tmp; unidecode "\x{0000}" > cc.txt; open -e cc.txt` defaults write NSGlobalDomain NSTextShowsControlCharacters -bool true echo "Disable the “Are you sure you want to open this application?” dialog" defaults write com.apple.LaunchServices LSQuarantine -bool false echo "Automatically quit printer app once the print jobs complete" defaults write com.apple.print.PrintingPrefs "Quit When Finished" -bool true echo "Save to disk (not to iCloud) by default" defaults write NSGlobalDomain NSDocumentSaveNewDocumentsToCloud -bool false echo "Expand print panel by default" defaults write NSGlobalDomain PMPrintingExpandedStateForPrint -bool true echo "Disable press-and-hold for keys in favor of key repeat" defaults write NSGlobalDomain ApplePressAndHoldEnabled -bool false echo "Disable the sudden motion sensor as it’s not useful for SSDs" sudo pmset -a sms 0 echo "Increase sound quality for Bluetooth headphones/headsets" defaults write com.apple.BluetoothAudioAgent "Apple Bitpool Min (editable)" -int 40 echo "Enable full keyboard access for all controls" echo "(e.g. enable Tab in modal dialogs)" defaults write NSGlobalDomain AppleKeyboardUIMode -int 3 echo "Disable system-wide resume" defaults write com.apple.systempreferences NSQuitAlwaysKeepsWindows -bool false echo "Automatically illuminate built-in MacBook keyboard in low light" defaults write com.apple.BezelServices kDim -bool true echo "Turn off keyboard illumination when computer is not used for 5 minutes" echo "Speed up wake from sleep to 24 hours from an hour" echo "http://www.cultofmac.com/221392/quick-hack-speeds-up-retina-macbooks-wake-from-sleep-os-x-tips/" sudo pmset -a standbydelay 86400 echo "Turn off keyboard illumination when computer is not used for 5 minutes" defaults write com.apple.BezelServices kDimTime -int 300 echo "Set language and text formats" defaults write NSGlobalDomain AppleLanguages -array "en" defaults write NSGlobalDomain AppleLocale -string "en_US@currency=USD" defaults write NSGlobalDomain AppleMeasurementUnits -string "Inches" defaults write NSGlobalDomain AppleMetricUnits -bool true echo "Disable auto-correct" defaults write NSGlobalDomain NSAutomaticSpellingCorrectionEnabled -bool false echo "Require password immediately after sleep or screen saver begins" defaults write com.apple.screensaver askForPassword -int 1 defaults write com.apple.screensaver askForPasswordDelay -int 0 echo "Save screenshots to Downloads" SCREENSHOT_DIR="${HOME}/Downloads/Screenshots" mkdir -p $SCREENSHOT_DIR defaults write com.apple.screencapture location -string $SCREENSHOT_DIR echo "Save screenshots in PNG format (other options: BMP, GIF, JPG, PDF, TIFF)" defaults write com.apple.screencapture type -string "png" echo "Disable shadow in screenshots" defaults write com.apple.screencapture disable-shadow -bool true echo "Enable subpixel font rendering on non-Apple LCDs" defaults write NSGlobalDomain AppleFontSmoothing -int 2 echo "Enable HiDPI display modes (requires restart)" sudo defaults write /Library/Preferences/com.apple.windowserver DisplayResolutionEnabled -bool true echo "Set a blazingly fast keyboard repeat rate" defaults write NSGlobalDomain KeyRepeat -int 0 echo "Set Desktop as the default location for new Finder windows" # For other paths, use `PfLo` and `file:///full/path/here/` defaults write com.apple.finder NewWindowTarget -string "PfDe" defaults write com.apple.finder NewWindowTargetPath -string "file://${HOME}/" echo "Show icons for hard drives, servers, and removable media on the desktop" defaults write com.apple.finder ShowExternalHardDrivesOnDesktop -bool true defaults write com.apple.finder ShowHardDrivesOnDesktop -bool true defaults write com.apple.finder ShowMountedServersOnDesktop -bool true defaults write com.apple.finder ShowRemovableMediaOnDesktop -bool true echo "Finder: show hidden files by default" defaults write com.apple.finder AppleShowAllFiles -bool true echo "Finder: show all filename extensions" defaults write NSGlobalDomain AppleShowAllExtensions -bool true echo "Finder: show status bar" defaults write com.apple.finder ShowStatusBar -bool true echo "Finder: show path bar" defaults write com.apple.finder ShowPathbar -bool true echo "Finder: allow text selection in Quick Look" defaults write com.apple.finder QLEnableTextSelection -bool true echo "Display full POSIX path as Finder window title" defaults write com.apple.finder _FXShowPosixPathInTitle -bool true echo "When performing a search, search the current folder by default" defaults write com.apple.finder FXDefaultSearchScope -string "SCcf" echo "Disable the warning when changing a file extension" defaults write com.apple.finder FXEnableExtensionChangeWarning -bool false echo "Enable spring loading for directories" defaults write NSGlobalDomain com.apple.springing.enabled -bool true echo "Remove the spring loading delay for directories" defaults write NSGlobalDomain com.apple.springing.delay -float 0 echo "Disable disk image verification" defaults write com.apple.frameworks.diskimages skip-verify -bool true defaults write com.apple.frameworks.diskimages skip-verify-locked -bool true defaults write com.apple.frameworks.diskimages skip-verify-remote -bool true echo "Automatically open a new Finder window when a volume is mounted" defaults write com.apple.frameworks.diskimages auto-open-ro-root -bool true defaults write com.apple.frameworks.diskimages auto-open-rw-root -bool true defaults write com.apple.finder OpenWindowForNewRemovableDisk -bool true echo "Show item info near icons on the desktop and in other icon views" /usr/libexec/PlistBuddy -c "Set :DesktopViewSettings:IconViewSettings:showItemInfo true" ~/Library/Preferences/com.apple.finder.plist /usr/libexec/PlistBuddy -c "Set :FK_StandardViewSettings:IconViewSettings:showItemInfo true" ~/Library/Preferences/com.apple.finder.plist /usr/libexec/PlistBuddy -c "Set :StandardViewSettings:IconViewSettings:showItemInfo true" ~/Library/Preferences/com.apple.finder.plist echo "Show item info to the right of the icons on the desktop" /usr/libexec/PlistBuddy -c "Set DesktopViewSettings:IconViewSettings:labelOnBottom false" ~/Library/Preferences/com.apple.finder.plist echo "Enable snap-to-grid for icons on the desktop and in other icon views" /usr/libexec/PlistBuddy -c "Set :DesktopViewSettings:IconViewSettings:arrangeBy grid" ~/Library/Preferences/com.apple.finder.plist /usr/libexec/PlistBuddy -c "Set :FK_StandardViewSettings:IconViewSettings:arrangeBy grid" ~/Library/Preferences/com.apple.finder.plist /usr/libexec/PlistBuddy -c "Set :StandardViewSettings:IconViewSettings:arrangeBy grid" ~/Library/Preferences/com.apple.finder.plist echo "Increase grid spacing for icons on the desktop and in other icon views" /usr/libexec/PlistBuddy -c "Set :DesktopViewSettings:IconViewSettings:gridSpacing 100" ~/Library/Preferences/com.apple.finder.plist /usr/libexec/PlistBuddy -c "Set :FK_StandardViewSettings:IconViewSettings:gridSpacing 100" ~/Library/Preferences/com.apple.finder.plist /usr/libexec/PlistBuddy -c "Set :StandardViewSettings:IconViewSettings:gridSpacing 100" ~/Library/Preferences/com.apple.finder.plist echo "Increase the size of icons on the desktop and in other icon views" /usr/libexec/PlistBuddy -c "Set :DesktopViewSettings:IconViewSettings:iconSize 80" ~/Library/Preferences/com.apple.finder.plist /usr/libexec/PlistBuddy -c "Set :FK_StandardViewSettings:IconViewSettings:iconSize 80" ~/Library/Preferences/com.apple.finder.plist /usr/libexec/PlistBuddy -c "Set :StandardViewSettings:IconViewSettings:iconSize 80" ~/Library/Preferences/com.apple.finder.plist echo "Use list view in all Finder windows by default" # Four-letter codes for the other view modes: `icnv`, `clmv`, `Flwv` defaults write com.apple.finder FXPreferredViewStyle -string "Nlsv" echo "Disable the warning before emptying the Trash" defaults write com.apple.finder WarnOnEmptyTrash -bool false echo "Empty Trash securely by default" defaults write com.apple.finder EmptyTrashSecurely -bool true echo "Enable AirDrop over Ethernet and on unsupported Macs running Lion" defaults write com.apple.NetworkBrowser BrowseAllInterfaces -bool true echo "Show the ~/Library folder" chflags nohidden ~/Library echo "Remove Dropbox’s green checkmark icons in Finder" file=/Applications/Dropbox.app/Contents/Resources/emblem-dropbox-uptodate.icns [ -e "${file}" ] && mv -f "${file}" "${file}.bak" echo "Expand the following File Info panes:" echo "“General”, “Open with”, and “Sharing & Permissions”" defaults write com.apple.finder FXInfoPanesExpanded -dict \ General -bool true \ OpenWith -bool true \ Privileges -bool true echo "Enable highlight hover effect for the grid view of a stack (Dock)" defaults write com.apple.dock mouse-over-hilite-stack -bool true echo "Set the icon size of Dock items to 36 pixels" defaults write com.apple.dock tilesize -int 36 echo "Minimize windows into their application’s icon" defaults write com.apple.dock minimize-to-application -bool true echo "Enable spring loading for all Dock items" defaults write com.apple.dock enable-spring-load-actions-on-all-items -bool true echo "Show indicator lights for open applications in the Dock" defaults write com.apple.dock show-process-indicators -bool true echo "Don’t animate opening applications from the Dock" defaults write com.apple.dock launchanim -bool false echo "Speed up Mission Control animations" defaults write com.apple.dock expose-animation-duration -float 0.1 echo "Don’t group windows by application in Mission Control" echo "(i.e. use the old Exposé behavior instead)" defaults write com.apple.dock expose-group-by-app -bool false echo "Disable Dashboard" defaults write com.apple.dashboard mcx-disabled -bool true echo "Don’t show Dashboard as a Space" defaults write com.apple.dock dashboard-in-overlay -bool true echo "Don’t automatically rearrange Spaces based on most recent use" defaults write com.apple.dock mru-spaces -bool false echo "Set Dock auto-hide" defaults write com.apple.dock autohide -bool true echo "Remove the auto-hiding Dock delay" defaults write com.apple.dock autohide-delay -float 0 echo "Remove the animation when hiding/showing the Dock" defaults write com.apple.dock autohide-time-modifier -float 0 echo "Make Dock icons of hidden applications translucent" defaults write com.apple.dock showhidden -bool true echo "Reset Launchpad" find ~/Library/Application\ Support/Dock -name "*.db" -maxdepth 1 -delete echo "Add iOS Simulator to Launchpad" sudo ln -sf /Applications/Xcode.app/Contents/Applications/iPhone\ Simulator.app /Applications/iOS\ Simulator.app echo "Bottom left screen corner → Start screen saver" echo "Hide Spotlight tray-icon (and subsequent helper)" sudo chmod 600 /System/Library/CoreServices/Search.bundle/Contents/MacOS/Search echo "Disable Spotlight indexing for any volume that gets mounted and has not yet" echo "been indexed before." # Use `sudo mdutil -i off "/Volumes/foo"` to stop indexing any volume. sudo defaults write /.Spotlight-V100/VolumeConfiguration Exclusions -array "/Volumes" echo "Change indexing order and disable some file types" defaults write com.apple.spotlight orderedItems -array \ '{"enabled" = 1;"name" = "APPLICATIONS";}' \ '{"enabled" = 1;"name" = "SYSTEM_PREFS";}' \ '{"enabled" = 1;"name" = "DIRECTORIES";}' \ '{"enabled" = 1;"name" = "PDF";}' \ '{"enabled" = 1;"name" = "FONTS";}' \ '{"enabled" = 0;"name" = "DOCUMENTS";}' \ '{"enabled" = 0;"name" = "MESSAGES";}' \ '{"enabled" = 0;"name" = "CONTACT";}' \ '{"enabled" = 0;"name" = "EVENT_TODO";}' \ '{"enabled" = 0;"name" = "IMAGES";}' \ '{"enabled" = 0;"name" = "BOOKMARKS";}' \ '{"enabled" = 0;"name" = "MUSIC";}' \ '{"enabled" = 0;"name" = "MOVIES";}' \ '{"enabled" = 0;"name" = "PRESENTATIONS";}' \ '{"enabled" = 0;"name" = "SPREADSHEETS";}' \ '{"enabled" = 0;"name" = "SOURCE";}' \ '{"enabled" = 0;"name" = "MENU_DEFINITION";}' \ '{"enabled" = 0;"name" = "MENU_OTHER";}' \ '{"enabled" = 0;"name" = "MENU_CONVERSION";}' \ '{"enabled" = 0;"name" = "MENU_EXPRESSION";}' \ '{"enabled" = 0;"name" = "MENU_WEBSEARCH";}' \ '{"enabled" = 0;"name" = "MENU_SPOTLIGHT_SUGGESTIONS";}' echo "Load new settings before rebuilding the index" killall mds > /dev/null 2>&1 echo "Make sure indexing is enabled for the main volume" sudo mdutil -i on / > /dev/null echo "Rebuild the index from scratch" sudo mdutil -E / > /dev/null defaults write com.apple.dock wvous-bl-corner -int 5 echo "Only use UTF-8 in Terminal.app" defaults write com.apple.terminal StringEncodings -array 4 echo "Don’t display the annoying prompt when quitting iTerm" defaults write com.googlecode.iterm2 PromptOnQuit -bool false echo "Prevent Time Machine from prompting to use new hard drives as backup volume" defaults write com.apple.TimeMachine DoNotOfferNewDisksForBackup -bool true echo "Disable local Time Machine backups" hash tmutil &> /dev/null && sudo tmutil disablelocal echo "Show the main window when launching Activity Monitor" defaults write com.apple.ActivityMonitor OpenMainWindow -bool true echo "Visualize CPU usage in the Activity Monitor Dock icon" defaults write com.apple.ActivityMonitor IconType -int 5 echo "Show all processes in Activity Monitor" defaults write com.apple.ActivityMonitor ShowCategory -int 0 echo "Sort Activity Monitor results by CPU usage" defaults write com.apple.ActivityMonitor SortColumn -string "CPUUsage" defaults write com.apple.ActivityMonitor SortDirection -int 0 echo "Enable the debug menu in Address Book" defaults write com.apple.addressbook ABShowDebugMenu -bool true echo "Enable Dashboard dev mode (allows keeping widgets on the desktop)" defaults write com.apple.dashboard devmode -bool true echo "Enable the debug menu in iCal (pre-10.8)" defaults write com.apple.iCal IncludeDebugMenu -bool true echo "Use plain text mode for new TextEdit documents" defaults write com.apple.TextEdit RichText -int 0 echo "Open and save files as UTF-8 in TextEdit" defaults write com.apple.TextEdit PlainTextEncoding -int 4 defaults write com.apple.TextEdit PlainTextEncodingForWrite -int 4 echo "Enable the debug menu in Disk Utility" defaults write com.apple.DiskUtility DUDebugMenuEnabled -bool true defaults write com.apple.DiskUtility advanced-image-options -bool true echo "Enable the Develop menu and the Web Inspector in Safari" defaults write com.apple.Safari IncludeDevelopMenu -bool true defaults write com.apple.Safari WebKitDeveloperExtrasEnabledPreferenceKey -bool true defaults write com.apple.Safari "com.apple.Safari.ContentPageGroupIdentifier.WebKit2DeveloperExtrasEnabled" -bool true echo "Disable autoswipe in Chrome" defaults write com.google.Chrome AppleEnableSwipeNavigateWithScrolls -bool false defaults write com.google.Chrome.canary AppleEnableSwipeNavigateWithScrolls -bool false echo "Use system-native print preview in Chrome" defaults write com.google.Chrome DisablePrintPreview -bool true defaults write com.google.Chrome.canary DisablePrintPreview -bool true echo "Enable the WebKit Developer Tools in the Mac App Store" defaults write com.apple.appstore WebKitDeveloperExtras -bool true echo "Enable Debug Menu in the Mac App Store" defaults write com.apple.appstore ShowDebugMenu -bool true echo "Disable automatic emoji substitution (i.e. use plain text smileys)" defaults write com.apple.messageshelper.MessageController SOInputLineSettings -dict-add "automaticEmojiSubstitutionEnablediMessage" -bool false echo "Disable smart quotes as it’s annoying for messages that contain code" defaults write com.apple.messageshelper.MessageController SOInputLineSettings -dict-add "automaticQuoteSubstitutionEnabled" -bool false echo "Allow installing user scripts via GitHub or Userscripts.org" defaults write com.google.Chrome ExtensionInstallSources -array "https://*.github.com/*" "http://userscripts.org/*" defaults write com.google.Chrome.canary ExtensionInstallSources -array "https://*.github.com/*" "http://userscripts.org/*" <file_sep>/.zshrc # Path to your oh-my-zsh configuration. ZSH=$HOME/.oh-my-zsh # Set name of the theme to load. # Look in ~/.oh-my-zsh/themes/ # Optionally, if you set this to "random", it'll load a random theme each # time that oh-my-zsh is loaded. ZSH_THEME="agnoster" alias -g ...='../..' alias -g ....='../../..' alias -g .....='../../../..' alias -g CA="2>&1 | cat -A" alias -g C='| wc -l' alias -g DN=/dev/null alias -g EG='|& egrep' alias -g EH='|& head' alias -g EL='|& less' alias -g ELS='|& less -S' alias -g ETL='|& tail -20' alias -g ET='|& tail' alias -g F=' | fmt -' alias -g G='| egrep' alias -g H='| head' alias -g HL='|& head -20' alias -g Sk="*~(*.bz2|*.gz|*.tgz|*.zip|*.z)" alias -g LL="2>&1 | less" alias -g L="| less" alias -g LS='| less -S' alias -g MM='| most' alias -g M='| more' alias -g NE="2> /dev/null" alias -g NS='| sort -n' alias -g NUL="> /dev/null 2>&1" alias -g PIPE='|' alias -g R=' > /c/aaa/tee.txt ' alias -g RNS='| sort -nr' alias -g S='| sort' alias -g TL='| tail -20' alias -g T='| tail' alias -g US='| sort -u' alias -g VM=/var/log/messages alias -g X0G='| xargs -0 egrep' alias -g X0='| xargs -0' alias -g XG='| xargs egrep' alias -g X='| xargs' alias -g vnv='. env/bin/activate' alias -g cvnv='create_venv' # Set to this to use case-sensitive completion # CASE_SENSITIVE="true" # Comment this out to disable bi-weekly auto-update checks # DISABLE_AUTO_UPDATE="true" # Uncomment to change how often before auto-updates occur? (in days) # export UPDATE_ZSH_DAYS=13 # Uncomment following line if you want to disable colors in ls # DISABLE_LS_COLORS="true" # Uncomment following line if you want to disable autosetting terminal title. DISABLE_AUTO_TITLE="true" # Uncomment following line if you want to disable command autocorrection DISABLE_CORRECTION="true" # Uncomment following line if you want red dots to be displayed while waiting for completion COMPLETION_WAITING_DOTS="true" # Uncomment following line if you want to disable marking untracked files under # VCS as dirty. This makes repository status check for large repositories much, # much faster. DISABLE_UNTRACKED_FILES_DIRTY="true" # Which plugins would you like to load? (plugins can be found in ~/.oh-my-zsh/plugins/*) # Custom plugins may be added to ~/.oh-my-zsh/custom/plugins/ # Example format: plugins=(rails git textmate ruby lighthouse) plugins=(osx last-working-dir ssh-agent supervisor python pip history-substring-search taskwarrior tmuxinator coffee fabric celery extract virtualenv) HISTSIZE=50000 # session history size SAVEHIST=10000 # saved history HISTFILE=~/.zshistory # history file zstyle :omz:plugins:ssh-agent agent-forwarding on source $ZSH/oh-my-zsh.sh PATH=/Users/cconlin/bin:/usr/local/bin:$PATH <file_sep>/README.md dotfiles ======== Ditch that frumpy 1984 Tandy 1000HX terminal! #### Airline #### ![img](https://github.com/bling/vim-airline/wiki/screenshots/demo.gif) #### Tmuxline #### ![img](https://f.cloud.github.com/assets/1532071/1556058/d2347eea-4ea7-11e3-9393-660b2e2c143a.png) Installing ---------- #### Run installer #### bash -c "`curl -fsSL https://raw.github.com/spongin/dotfiles/master/go.sh`" #### Setup [Promptline](https://github.com/edkolev/promptline.vim) #### # Launch vim vim # Execute the command that updates the shell prompt from the # .vimrc config of [vim-airline](https://github.com/bling/vim-airline) :PromptlineSnapshot! ~/.oh-my-zsh/custom/shell_prompt.zsh # Exit vim :x #### Setup [Tmuxline](https://github.com/edkolev/tmuxline.vim) #### **Launch tmux** tmux **Launch vim (from inside tmux)** vim **Execute the command that updates the tmux prompt from the `.vimrc` config of [tmux-powerline](https://github.com/erikw/tmux-powerline)** :TmuxlineSnapshot! ~/.tmuxline.conf **Exit vim** :x **Kill the tmux window** [Ctrl] + b, x #### Activate your new shell! #### **If you're already using zsh, just source your new `.zshrc`** [ $SHELL = "/bin/zsh" ] && source ~/.zshrc **Otherwise, you should change to zsh** chsh -s /bin/zsh **Exit and open a new terminal** TODO ---- * Make updates easy! For example, `update_dotfiles`. * Speed things up by keeping the original git repo (and all those damn submodules) around. * Set aside a space for custom `.vimrc` and `.zshrc` stuff * Make it bash compatible. <file_sep>/go.sh #!/usr/bin/env bash DOTFILES_DIR=$(mktemp -d /tmp/tmp.XXXXXXXX) if [ ! -d "$DOTFILES_DIR" ]; then mkdir -p $DOTFILES_DIR fi YES=${TRUE} NO=${FALSE} # Clear stdin. function __ui_clear_stdin() { local dummy read -r -t 1 -n 100000 dummy } function __echo() { case "${2}" in red) code=31;; green) code=32;; yellow) code=33;; blue) code=34;; purple) code=35;; cyan) code=36;; white) code=37;; *) code=1;; esac printf "\e[0;${code}m${1}\e[0m\n" } function __ask() { __ui_clear_stdin local message=$1 local var="" local code=1 case "${3}" in red) code=31;; green) code=32;; yellow) code=33;; blue) code=34;; purple) code=35;; cyan) code=36;; white) code=37;; *) code=1;; esac printf "\e[0;${code}m➜ ${message}\e[0m " read echo -n if [ $# -eq 2 ]; then local default=$2 if [ -z ${REPLY} ]; then REPLY=${default} fi fi } function __confirm() { __ui_clear_stdin local message=$1 local code=1 case "${2}" in red) code=31;; green) code=32;; yellow) code=33;; blue) code=34;; purple) code=35;; cyan) code=36;; white) code=37;; *) code=1;; esac if [ $# -gt 1 ]; then local default=$2 else local default=${FALSE} fi printf "\e[0;${code}m➜ Do you want to ${message}? \e[0m[y or n] " read -n 2 echo -n if [[ $REPLY =~ ^[Yy] ]]; then return ${TRUE} else return ${FALSE} fi # Ctrl-D pressed. return ${default} } function __backup() { for FILE in "${@}"; do if [ -e ${FILE} -o -h ${FILE} ]; then rm -fr "${FILE}.bak" && mv "${FILE}" "${FILE}.bak" __good "Backed up existing $(basename $FILE) to $(basename $FILE).bak" fi sleep 1 done } function __verify_ssh_agent() { ssh-add -l > /dev/null local returncode=$? if [ $returncode = 0 ]; then __good "Your SSH agent is active!" return ${TRUE} else __uh_oh "You don't have an active SSH agent." return ${FALSE} fi } function __notify() { __echo "➜ ${1}" "white" } function __uh_oh() { __echo "✖ ${1}" "red" } function __good() { __echo "✔ ${1}" "green" } function homebrew_install() { if [ ! -x /usr/local/bin/brew ]; then __notify "Installing Homebrew..." ruby <(curl -fsSkL raw.github.com/mxcl/homebrew/go) [ $? = 0 ] && __good "Install complete!" || exit 1 fi } function install_pip() { which pip > /dev/null if [ $? != 0 ]; then __notify "Installing pip..." sudo bash -c "python <(curl -fsSL https://raw.githubusercontent.com/pypa/pip/1.5.4/contrib/get-pip.py)" fi } function homebrew_install_packages() { __notify "Installing Homebrew packages..." brew update brew tap Homebrew/brewdler brew bundle __notify "Installing some applications via Cask..." source $DOTFILES_DIR/.cask } function customize_osx() { __notify "Fine-tuning OS X preferences..." source $DOTFILES_DIR/.osx } function clone_dotfiles() { echo __notify "Fetching dotfiles...\n" git clone --recurse-submodules \ --depth 1 \ <EMAIL>:spongin/dotfiles.git $DOTFILES_DIR __good "Fetched!" } function configure_vim() { if [ ! -d "${HOME}/.vim" ]; then __notify "Creating a ~/.vim directory" mkdir -p "${HOME}/.vim" else __backup "${HOME}/.vim" fi __notify "Adding Bundles your new ~/.vim..." rsync -az "${DOTFILES_DIR}/.vim/" "${HOME}/.vim/" [ $? = 0 ] && __good "Added bundles!" || __uh_oh "Something went wrong." __notify "Adding a ~/.gvimrc and ~/.vimrc..." __backup ~/.gvimrc ~/.vimrc cp "${DOTFILES_DIR}/.gvimrc" "${HOME}/" [ -f "${HOME}/.gvimrc" ] && __good "Added ~/.gvimrc!" || __uh_oh "Something went wrong." cp "${DOTFILES_DIR}/.vimrc" "${HOME}/" [ -f "${HOME}/.vimrc" ] && __good "Added ~/.vimrc!" || __uh_oh "Something went wrong." vim +BundleInstall +qall } function configure_zsh() { local omz_dir="${HOME}/.oh-my-zsh" __notify "Adding oh-my-zsh..." if [ ! -d $omz_dir ]; then __notify "Creating a ~/.oh-my-zsh directory" mkdir -p "$omz_dir" else __backup "$omz_dir" fi rsync -az "${DOTFILES_DIR}/.oh-my-zsh/" "$omz_dir" [ $? = 0 ] && __good "Added oh-my-zsh!" || __uh_oh "Something went wrong." __notify "Adding oh-my-zsh/custom..." rsync -az "${DOTFILES_DIR}/.oh-my-zsh-custom/" "$omz_dir/custom/" [ $? = 0 ] && __good "Added oh-my-zsh/custom!" || __uh_oh "Something went wrong." mkdir -p "${HOME}/.oh-my-zsh/cache" echo $(pwd) > "${HOME}/.oh-my-zsh/cache/last-working-dir" __notify "Adding a ~/.zshrc..." __backup "${HOME}/.zshrc" cp "${DOTFILES_DIR}/.zshrc" "${HOME}/.zshrc" [ -f "${HOME}/.zshrc" ] && __good "Added ~/.zshrc!" || __uh_oh "Something went wrong." } function configure_tmux() { __notify "Adding a ~/.tmux.conf..." __backup "${HOME}/.tmux.conf" cp "${DOTFILES_DIR}/.tmux.conf" "${HOME}/.tmux.conf" touch "${HOME}/.tmuxline.conf" [ -f "${HOME}/.tmux.conf" ] && __good "Added ~/.tmux.conf!" || __uh_oh "Something went wrong." } function test_github_access() { __notify "Testing your access to Github..." GITHUB_USERNAME=$(ssh -T <EMAIL> 2>&1 | awk '{print $2}') if [ ! $GITHUB_USERNAME ]; then __uh_oh "It looks like you don't have access to Github with your key." else __good "Hello ${GITHUB_USERNAME}" fi } function delete_backups() { for file in "${@}"; do [[ -f "${file}.bak" || -d "${file}.bak" ]] && rm -rf "${file}.bak" && __good "Deleted ${file}.bak..." done } function configure_git() { __notify "Let's setup your new git config." __backup "${HOME}/.gitconfig" "${HOME}/.gitignore" cp "${DOTFILES_DIR}/.gitconfig" "${HOME}/.gitconfig" __ask "What's your full name?" "" "white" git config --global user.name "${REPLY}" __ask "What's the email address you have linked to your Github account?" "" "white" git config --global user.email "${REPLY}" __good "Setup finished." test_github_access } echo __notify "Setup dotfiles!" echo if __confirm "continue" "white"; then echo if __verify_ssh_agent; then echo if [[ $(uname -s) =~ 'Darwin' ]]; then __good "Detected OS X." homebrew_install __notify "Installing git..." brew install git else __uh_oh "Unsupported OS." fi clone_dotfiles if [[ $(uname -s) =~ 'Darwin' ]]; then homebrew_install_packages if __confirm "customize OS X" "white"; then customize_osx fi fi if __confirm "install pip" "white"; then install_pip fi if __confirm "configure git" "white"; then configure_git fi if __confirm "configure vim" "white"; then configure_vim fi if __confirm "configure zsh" "white"; then configure_zsh fi if __confirm "configure tmux" "white"; then configure_tmux fi __notify "Cleaning up..." if __confirm "delete backups" "red"; then delete_backups "${HOME}/.zshrc" "${HOME}/.vim" "${HOME}/.oh-my-zsh" "${HOME}/.tmux.conf" \ "${HOME}/.gitignore" "${HOME}/.gitconfig" fi rm -rf "${DOTFILES_DIR}" fi else echo __uh_oh "Fine then." fi
7b98c36bcb24b1a65d3048055de4958adfb669da
[ "Markdown", "Ruby", "Shell" ]
6
Ruby
spongin/dotfiles
8685ba1d20bdb774ebebe0722fad699944b057e8
8a14ef1c62f00700345ee5324b408d8a5947e09b
refs/heads/master
<repo_name>semi25nole/MyNotes<file_sep>/public/main.js function results () { $("#results").empty(); $.getJSON("/all", function(data) { for(var i = 0; i < data.length; i++) { $("#results").prepend("<p class='dataTitle' data-id=" + data[i]._id + ">" + data[i].title + "<button class='btn btn-small' id='deleter'>X</button>" + "</p>" + "<hr>"); } }); }; results(); $(document).on("click", "#makeNew", function() { $.ajax({ type: "POST", dataType: "json", url: "/submit", data: { title: $("#title").val(), note: $("#note").val(), created: Date.now() } }) .done(function(data) { $("#results").prepend("<p class='dataentry' data-id=" + data._id + "><span class='dataTitle' data-id=" + data._id + ">" + data.title + "</span><span class=deleter>X</span></p>"); $("#note").val(""); $("#title").val(""); }); results(); window.location.reload(true); }); $("#delete").on("click", function() { $.ajax({ type: "GET", dataType: "json", url: "/clear", success: function(response) { $("#results").empty(); } }); }); $(document).on("click", "#deleter", function() { // Save the p tag that encloses the button var selected = $(this).parent(); // Make an AJAX GET request to delete the specific note // this uses the data-id of the p-tag, which is linked to the specific note $.ajax({ type: "GET", url: "/delete/" + selected.attr("data-id"), // On successful call success: function(response) { // Remove the p-tag from the DOM selected.remove(); // Clear the note and title inputs $("#note").val(""); $("#title").val(""); // Make sure the #actionbutton is submit (in case it's update) $("#actionButton").html("<button class='btn btn-primary' id='makeNew'>Submit</button>"); } }); results(); window.location.reload(true); }); $(document).on("click", ".dataTitle", function() { var selected = $(this); $.ajax({ type: "GET", url: "/find/" + selected.attr("data-id"), success: function(data) { $("#note").val(data.note); $("#title").val(data.title); $("#actionButton").html("<button class='btn btn-primary' id='updater' data-id='" + data._id + "'>Update</button>"); } }); }); $(document).on("click", "#updater", function() { var selected = $(this); $.ajax({ type: "POST", url: "/update/" + selected.attr("data-id"), dataType: "json", data: { title: $("#title").val(), note: $("#note").val() }, success: function(data) { $("#note").val(""); $("#title").val(""); $("#actionButton").html("<button class= 'btn btn-primary' id='makeNew'>Submit</button>"); results(); } }); });
e96eece6e7e75489c7c567d27e5b620cb96251e0
[ "JavaScript" ]
1
JavaScript
semi25nole/MyNotes
54386a25984a46f32f337221ea0c322edff95e00
d22f5d694ec4314bb0a19bf67ff332ccfd521e1f
refs/heads/master
<file_sep><?php /** * Created by PhpStorm. * User: rofi * Date: 06-Mar-18 * Time: 6:23 PM */ // Load Config require_once 'config/config.php'; // Load Helpers require_once 'helpers/url_helper.php'; require_once 'helpers/session_helper.php'; <file_sep><!doctype html> <?php require './bootstrap.php';?> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <meta name="author" content="rofi"> <meta name="description" content="stock management system, NIC, LCB College, BSc Final Year Project, Gauhati University"> <!--link rel="stylesheet" href="./assets/bootstrap/css/bootstrap.min.css"> <link rel="stylesheet" href="./assets/bootstrap/css/bootstrap-theme.min.css"> <link rel="stylesheet" href="./assets/custom/css/style.css"> <link rel="stylesheet" href="./assets/custom/js/custom.js"> <script src="./assets/bootstrap/js/bootstrap.min.js"></script--> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> <title><?php echo SITENAME;?></title> </head> <body> <?php require 'navbar.php'; ?> <div class="container"><file_sep><?php require_once './includes/header.php';?> <h1 class="custom">this is SMS home page</h1> <?php require_once './includes/footer.php';?> <file_sep><?php /** * Created by PhpStorm. * User: rofi * Date: 06-Mar-18 * Time: 6:26 PM */<file_sep><?php /** * Created by PhpStorm. * User: rofi * Date: 06-Mar-18 * Time: 6:21 PM */ // DB Params define('DB_HOST', 'localhost'); define('DB_USER', 'root'); define('DB_PASS', ''); define('DB_NAME', 'stock'); // App Root define('APPROOT', dirname(dirname(__FILE__))); // URL Root define('URLROOT', 'http://localhost/sms'); // Site Name define('SITENAME', 'STOCK MANAGEMENT SYSTEM'); // App Version define('APPVERSION', '1.0.0');
923e03fbe100e60e894c09235edb861df334b436
[ "PHP" ]
5
PHP
roficcg12/stock
aa5de8aa6925a05f0ade4afee70c2ba15bcda646
f649174613c025da6afcead174eed23ca2353c63
refs/heads/master
<file_sep>#!/bin/sh filename="sites"; size=$(ls -l $filename | awk '{ print $5 }') #echo $size if [ $size -eq '0' ] then echo 'Running the configuration file as there is no URL to test ' python cli_param.py fi python post_xss.py<file_sep>#!/bin/sh filename="sites"; echo '\n\n What do you want to test ?' echo '\n1. GET urls (URLs were params are in url )\n' echo '2. POST urls ()\n' echo ' Your Choice' read test if [ $test -eq '2' ] then size=$(ls -l $filename | awk '{ print $5 }') #echo $size if [ $size -gt '0' ] then echo '\nThere is already some URL to test in "sites" file \n1.Do you want to test them \n2. Do you want to test a new URL ?\n' read input if [ $input -eq '1' ] then python check_domain.py a=$? if [ $a -eq '1' ] then python post_xss.py else #python cli_param.py exit 1 fi elif [ $input -eq '2' ] then #echo 'Do you want to enter parameters in CLI mode or want to edit ' echo '\n\nRunning the configuration file and removing the previous content copying all your previous content to old_sites file' cat sites>>old_sites > sites python cli_param.py #python post_xss.py #exit 1 else echo '\n Wrong Input' fi elif [ $size -eq '0' ] then echo 'Running the configuration file as there is nothing to test ' python check_domain.py python cli_param.py #python test_xss.py fi elif [ $test -eq '1' ] then python get_xss.py exit 1 else echo '\nWrong input re-run the script\n' fi python post_xss.py<file_sep>#!/usr/bin/env python # Imports import sys, re, urllib2, urlparse, json, time, httplib,cookielib,urllib #from threadpool import * i=0 # Config DEBUG = True MAX_THREAD_COUNT = 1 SITES_FILENAME = str(sys.argv[1]) #print SITES_FILENAME #sys.exit() PAYLOADS_FILENAME = 'get_payload' SCHEME_DELIMITER = '://' XSS_RESPONSE = "alert('XSS')" cj = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) intt=0 # ------------------------------------- def attack(url, payload): # ------------------------------------- t_start = time.time() #print "in attak" return_dict = dict() return_dict['url'] = url #print "..." #return_dict['url_data'] = data return_dict['vulnerability'] = False #print "\n url",url #print "\n payload" ,payload #print "going to try\n" #post_url='http://site.com ' # the url in which XSS test needs to be done and it is different from url where we posted params try: return_dict['method'] = 'GET' XSS_RESPONSE=payload #print "payload--->", payload attack= urllib2.urlopen(url).read() #print "\nURL being hit :",url print_url=url.replace("<","&lt") print "\nURL being hit :",print_url #print XSS_RESPONSE index = attack.find(XSS_RESPONSE) buffer = 20 attack = attack.split("\n"); len(attack) #print "\nurl->\n",url if index != -1: intt +=1 return_dict[' vulnerability'] = True print "\n\n--------------------------------------------------------------------------" print "\nThis url seems vulnerable\n\n",url print "--------------------------------------------------------------------------\n\n" #return_dict['vulnerability_data'] = line.strip() #print "payload found\n", attack[index-buffer:index+len(XSS_RESPONSE)+buffer] #print intt # break #print "here" t_end = time.time() return_dict['time'] = round((t_end - t_start), 2) except KeyboardInterrupt, ke: sys.exit(0) except Exception, e: return_dict['exception'] = str(e) # ------------------------------------- if __name__ == '__main__': # ------------------------------------- print "<h1>Python</h1>"; #exit(0); # Init t_global_start = time.time() sites_file = open(SITES_FILENAME) payloads_file = open(PAYLOADS_FILENAME) #threadpool = ThreadPool(MAX_THREAD_COUNT) # Load SITES and PAYLOADS files sites = [] # input = str(raw_input("\nEnter the URLS you want to test\n")) # sites = [] for site in sites_file: sites.append(site[:-1]) #print "\nsites:", sites #sites = input print "\nWorking..." sys.stdout.flush() #exit(0); payloads = [] for payload in payloads_file: payloads.append(payload[:-1]) # Loop through sites # Extract Base URL and Parameters from site #print "sites len : " + str(len(sites)) try: for site in sites: #print site parse_url = urlparse.urlparse(site) #print mode base_url = '%s%s%s%s' % (parse_url.scheme, SCHEME_DELIMITER, parse_url.netloc, parse_url.path) #print base_url param_parse_list = urlparse.urlparse(site)[4].split('&') #print "\nparam_parse_list:",param_parse_list param_dict = dict() for param_parse_entry in param_parse_list: tmp = param_parse_entry.split('=') param_dict[tmp[0]] = tmp[1] # Loop through payloads #print payloads for payload in payloads: # Loop through parameters #print i for k1, v1 in iter(sorted(param_dict.iteritems())): # Build GET param string and POST param dict get_params = '' #post_params = dict() for k2, v2 in iter(sorted(param_dict.iteritems())): if k1 == k2: get_params += '%s=%s&' % (k2, payload) #post_params[k2] = payload else: get_params += '%s=%s&' % (k2, v2) #post_params[k2] = v2 get_params = get_params[:-1] #print get_params # Enqueue GET attack #base_url=mode + base_url #print mode #print base_url get_attack_url = '%s?%s' % (base_url, get_params) print_payload=payload.replace("<","&lt") #print "Testing with payload>", print_payload; # to see what payload is being used sys.stdout.flush() #threadpool.enqueue(attack, get_attack_url, payload) #print "..." attack(get_attack_url, payload) # Enqueue POST attack #post_attack_url = '%s' % (base_url) #threadpool.enqueue(attack, post_attack_url, post_params) #attack(post_attack_url,post_params) # Wait for threadpool #threadpool.wait() except Exception,e: print "\nSome Error , \n\n Please re run the script ",e # Exit t_global_end = time.time() #if DEBUG: #print "int->",int if(intt == 0): print "\n\tNothing Found! \n" print 'Time taken : %.2f seconds' % (t_global_end - t_global_start) <file_sep>Hey Everyone, I am releasing my script to check XSS (Cross Site Scripting) in any given Url. Its a simple script with event driven menu where you can test all your GET and POST urls. I wrote the whole code in python but to make it simple for everyone to run it I wrote a small shell script which you just need to run (follow instruction) and it will take care of everything from taking inputs to testing. I tried minimum human intervention . You just run the script go have a cup of coffee and it will do the rest of work and will inform you if it finds anything suspicious. The reason I started with XSS is because its most common vulnerability in our website as well as in all other websites as well. How to use the script: 1) Unzip the attached file and change your current working directory to the folder you have unzipped in command prompt. 2) Please read the "How_to" file for making config changes. 3) In command prompt type "sh xss.sh" 4) It will take you through a event driven menu to get the URL you want to test 5) Then it will start testing the given URL ( It can take upto 1 - 5 minutes depending upon the no. of parameters and payload ) 6) If any of the parameter in URL is vulnerable then you will see it in command prompt else you will see "Nothing Found " message . Some dependencies/configuration: 1)xss.cfg file contains basic configuration please make required changes there before running the script. Hope this will make your life easier and will add extra layer of security ,so that everything can be tested with this first before being pushed to prod. Note:I would be releasing its web version soon with many changes. #Contact info:"<EMAIL>" <file_sep>__author__ = 'mohd.siddiqui' import sys, re, urllib2, json, time, cookielib, urllib from datetime import datetime #from threadpool import * from cfghlp import ConfigHelper CONFIG_FILE = 'xss.cfg' config = None config = ConfigHelper(CONFIG_FILE, False) a=config.get('general','base_url') domain=a print "\nYou will be logged in \"%s\" ,testing can only be performed on this domain\n" % domain input=str(raw_input("\nAre you sure you want to continue ?(Press N to change the testign enviornment) Y/N \t")) if input=='Y' or input =='y': exit(1) else: print "\n 1.Please make required changes in \"xss.cfg\" file . \n 2.Change the \"base_url\" to the URL (enviornment) you want to test\"\n 3.Change the login credentials \"email\" and \"password\" to valid ones \n 4.Save and re-run this script\n" exit (0)<file_sep>__author__ = 'mohd.siddiqui' #!/usr/bin/env python # Imports import sys, re, urllib2, json, time, cookielib, urllib from datetime import datetime from copy import deepcopy from threadpool import * from cfghlp import ConfigHelper # Config CONFIG_FILE = 'xss.cfg' config = None intt=0 # Vars protocol_secure = 'https://' protocol_nonsecure = 'http://' #XSS_RESPONSE="alert('XSS')" # ------------------------------------- def debug(message): # ------------------------------------- if config.get('display', 'debug').lower() == 'true': print message # ------------------------------------- def jsonPrint(json_dict): # ------------------------------------- if config.get('display', 'json_pretty_print').lower() == 'true': print json.dumps(json_dict, sort_keys=True, indent=4) else: print json.dumps(json_dict, sort_keys=True, indent=4) # ------------------------------------- def submit(opener, submit_dict): # ------------------------------------- # Init request_mode = None request_url = None request_params = None response_mode = None response_url = None response_params = None if 'request' in submit_dict: request_protocol = None if submit_dict['request'].has_key('use_ssl') and submit_dict['request']['use_ssl'].lower() == 'true': request_protocol = protocol_secure else: request_protocol = protocol_nonsecure request_mode = submit_dict['request']['mode'] request_url = request_protocol + config.get('general', 'base_url') + submit_dict['request']['url'] request_params = submit_dict['request']['params'] if 'response' in submit_dict: response_protocol = None if submit_dict['response'].has_key('use_ssl') and submit_dict['response']['use_ssl'].lower() == 'true': response_protocol = protocol_secure else: response_protocol = protocol_nonsecure response_mode = submit_dict['response']['mode'] response_url = response_protocol + config.get('general', 'base_url') + submit_dict['response']['url'] response_params = submit_dict['response']['params'] return_dict = {} return_dict['request'] = {'url': request_url, 'mode': request_mode, 'params': request_params} if response_url and response_url != request_url: return_dict['request_read'] = {'url': response_url, 'mode': response_mode, 'params': response_params} t_start = time.time() try: # Submit Request [submit_url, submit_params] = buildRequest(request_mode, request_url, request_params) check_url=submit_url+'?'+submit_params #print "\nscript url\n",check_url response = opener.open(check_url) #print response.read() # If Response URL is specified, Submit Response if response_url and response_url != request_url: [submit_url, submit_params] = buildRequest(response_mode, response_url, response_params) response = opener.open(submit_url, submit_params) if response_url != response.geturl(): return_dict['request_read']['redirect_url'] = response.geturl() # Read Response return_dict['response'] = response.readlines() except KeyboardInterrupt: sys.exit(0) except Exception, e: return_dict['exception'] = str(e) finally: t_end = time.time() return_dict['time'] = round((t_end - t_start), 5) return_dict['timestamp'] = datetime.now().isoformat(' ') return return_dict #-------------------------------------- def buildRequest(mode, url, data): # ------------------------------------- if mode == 'GET': get_url = '%s?' % (url) for k, v in data.iteritems(): get_url += '%s=%s&' % (k, v) if get_url[-1] in ['?', '&']: get_url = get_url[:-1] return [get_url, None] elif mode == 'POST': return [url, urllib.urlencode(data)] else: return [None, None] # ------------------------------------- # ------------------------------------- def login(openers): # ------------------------------------- response_protocol="https://" resp_url=response_protocol + config.get('general','base_url') + config.get('login','formkey_url') resp=openers['loggedin'].open(resp_url) #print "fk_url ",resp_url page=resp.read() form_key=config.get('general','form_key') #define the form key paramter name within quotes __FK = page[page.find(form_key):].split("\"",4)[2] #for finding FK value email=config.get('login', 'login_email') password=config.get('login', 'login_password') opener = openers['loggedin'] url=response_protocol+config.get('general', 'base_url') + config.get('login', 'login_url') login_dict = {'request': {'mode': 'POST', 'url': url, 'use_ssl': 'true', 'params': {form_key: __FK, 'email':email, 'password': <PASSWORD>}}} request_mode = login_dict['request']['mode'] request_url = login_dict['request']['url'] request_params = login_dict['request']['params'] return_dict = {} return_dict['request'] = {'url': request_url, 'mode': request_mode, 'params': request_params} [submit_url, submit_params] = buildRequest(request_mode, request_url, request_params) #print submit_params response = opener.open(submit_url,submit_params) return_dict['response'] = response.readlines() #print return_dict['response'] submit_response=return_dict submit_response['response'] = json.loads(submit_response['response'][0]) if submit_response['response']['status'].lower() != 'ok': jsonPrint(submit_response) sys.exit(0) else: print "\nYou are now logged in \n" # ------------------------------------- def attack(site_dict, good_dict ,openers): # ------------------------------------- vulnerability_dict={} #vulnerability_dict=deepcopy(site_dict) vulnerability_dict['vulnerability'] = [] opener = openers['loggedin'] [g_submit_url, g_submit_params] = buildRequest(good_dict['request']['mode'],good_dict['request']['post_url'],good_dict['request']['params']) opener.open(g_submit_url,g_submit_params) request_mode = site_dict['request']['mode'] request_url = site_dict['request']['post_url'] request_params = site_dict['request']['params'] #vulnerability_dict['url']=site_dict['response']['url'] vulnerability_dict['params']=request_params return_dict = {} return_dict['request'] = {'post_url': request_url, 'mode': request_mode, 'params': request_params} [submit_url, submit_params] = buildRequest(request_mode, request_url, request_params) response = opener.open(submit_url,submit_params) opener.open(g_submit_url,g_submit_params) #print response.read() return_dict['response'] = response.readlines() #print "attcked url",submit_url+'?'+submit_params response=opener.open(site_dict['response']['url']) #good_url=buildRequest( #jsonPrint(site_dict) #print "----------opening response url------------" attack=response.read() #print attack XSS=site_dict['response']['xss_response'] #print "\n\nPayload being used is :",XSS buf=3 xs=len(XSS) #print "good_dict['response']['xss_response']",good_dict['response']['xss_response'] XSS_RESPONSE=site_dict['response']['xss_response'] #print XSS_RESPONSE # file = open("test.txt","a") # file.write(attack); # file.close() index = attack.find(XSS_RESPONSE) buffer = 20 attack = attack.split("\n"); #print len(attack) #print "\nindex", index #print "\nurl->\n",url #print "len(vulnerability_dict['vulnerability'])",len(vulnerability_dict['vulnerability']) if index != -1: vulnerability_dict['vulnerability'] = True # else: # print str(index) + "not vulnerable" #output={} #output['param'] #Output if config.get('display', 'only_show_vulnerable').lower() == 'false' or vulnerability_dict['vulnerability'] ==True or index != -1: print "\n====================================================================================" print "Vulnerability found (Please check the parameters below) :" jsonPrint(vulnerability_dict) intt=1 print "\n\nPayload being used is :",XSS #print "\n\nPage is being searched for this much xss string :",XSS_RESPONSE print "\n====================================================================================" else: print "...." # ------------------------------------- def attackSequence(sites, payloads, openers): # ------------------------------------- # Init threadpool = ThreadPool(int(config.get('general', 'max_thread_count'))) opener=openers['loggedin'] i=0 for site in sites: site_dict = json.loads(site) #print "\n-------->",site_dict fk_url=site_dict['request']['fk_url'] #not response url instead fkurl changes need to be made #print "\nfk_url-->",fk_url resp=opener.open(fk_url) page=resp.read() form_key=config.get('general','form_key') __FK = page[page.find(form_key):].split("\"",4)[2] #for finding FormKey value print "\nWorking...." #print len(payloads) good_dict=deepcopy(site_dict) for payload in payloads: # Loop through parameters #print payload for param_k in sorted(site_dict['request']['params'].iterkeys()): #print param_k attack_dict = deepcopy(site_dict) attack_dict['response']['xss_response']=payload attack_dict['request']['params'][form_key] =__FK #print "\n ------------->",attack_dict attack_dict['request']['params'][param_k] = payload # print i # i+=1 #jsonPrint(attack_dict) #print attack_dict['response']['xss_response'] threadpool.enqueue(attack, attack_dict,good_dict, openers) #print "sites -------->\n",sites # Wait for threadpool threadpool.wait() # ------------------------------------- if __name__ == '__main__': # ------------------------------------- # Parse Config config = ConfigHelper(CONFIG_FILE, False) # Init debug('Initializing script ...') t_global_start = time.time() # Load SITES and PAYLOADS files sites = [] sites_file = open(config.get('files', 'sites_file')) for site in sites_file: site = site[:-1].strip() if site[0] != '#': sites.append(site) payloads = [] payloads_file = open(config.get('files', 'payloads_file')) # for payload in payloads_file: # payload = payload[:-1].strip() # if payload[0] != '#': # payloads.append(payload[:-1]) for payload in payloads_file: payloads.append(payload[:-1]) # Create Openers openers = dict() # print "\nYou are being logged into \"%s\" ,testing can only be performed on this domain\n" % config.get('general','base_url') # input=str(raw_input("\nAre you sure you want to continue ? Y/N\t")) #if input=='Y' or input =='y': debug('Creating guest session ...') openers['guest'] = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookielib.CookieJar())) debug('Creating logged in session ...') openers['loggedin'] = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookielib.CookieJar())) login(openers) #take_input() # Loop through SITES file debug('\nStarting attack sequence ...') attackSequence(sites, payloads, openers) # Exit t_global_end = time.time() if (intt=='0'): print "\nNo Vulnerabilities found\n" debug('Time taken : %.2f seconds' % (t_global_end - t_global_start)) <file_sep>__author__ = 'mohd.siddiqui' import sys, re, urllib2, json, time, cookielib, urllib from datetime import datetime #from threadpool import * from cfghlp import ConfigHelper fk_url = str(raw_input("\nType the URL of page where the form is: ")) ssl = fk_url[:5] #print ssl if ssl == "https": set_ssl = "true" else: set_ssl = "false" post_url = str(raw_input("\nType in th post URl: ")) try: no_of_params = int(raw_input("\nEnter the no. of parameters that will be submitted(integer only): ")) except ValueError: print "\nYou had to enter a no. please re run the script and be carefull \n" sys.exit(0) #print no_of_params a_param = 0 params = dict() while a_param < no_of_params: #print a_param key = str(raw_input("\n Enter the param: ")) value = str(raw_input("\n Enter the corresponding value: ")) params[key] = value a_param = a_param + 1 p = json.dumps(params, sort_keys=True, indent=4) login_dict = {} login_dict = {"request": {}, "response": {}} #print login_dict #login_dict["req"]={} login_dict["request"]["mode"] = 'POST' login_dict["request"]["fk_url"] = fk_url login_dict["request"]["use_ssl"] = set_ssl login_dict["request"]["params"] = params login_dict["request"]["post_url"] = post_url #print login_dict login_dict["response"]["mode"] = "GET" login_dict["response"]["url"] = fk_url login_dict["response"]["params"] = "" s = json.dumps(login_dict) f = open("sites", 'a') f.write(s + "\n") f.close() <file_sep>#!/usr/bin/env python import ConfigParser # ------------------------------------- class ConfigHelper: # ------------------------------------- _configObj = None # ------------------------------------- def __init__(self, configFile=None, debug=False): # ------------------------------------- self._configObj = ConfigParser.SafeConfigParser() self._configObj.read(configFile) if debug == True: for section in self._configObj.sections(): for option in self._configObj.options(section): print '[%s] %s = %s' % (section,option,self._configObj.get(section,option)) # ------------------------------------- def getSections(self): # ------------------------------------- return self._configObj.sections() # ------------------------------------- def getOptions(self,section): # ------------------------------------- if section not in self._configObj.sections(): return None else: return self._configObj.options(section) # ------------------------------------- def get(self,section,option): # ------------------------------------- if section not in self._configObj.sections() or option not in self._configObj.options(section): return None else: return self._configObj.get(section,option) <file_sep>#!/usr/bin/env python # Imports import sys, re, urllib2, json, time, cookielib, urllib from datetime import datetime from copy import deepcopy from threadpool import * from cfghlp import ConfigHelper # Config CONFIG_FILE = 'xss.cfg' config = None intt=0 # Vars protocol_secure = 'https://' protocol_nonsecure = 'http://' # ------------------------------------- def debug(message): # ------------------------------------- if config.get('display', 'debug').lower() == 'true': print message # ------------------------------------- def jsonPrint(json_dict): # ------------------------------------- if config.get('display', 'json_pretty_print').lower() == 'true': print json.dumps(json_dict, sort_keys=True, indent=4) else: print json.dumps(json_dict, sort_keys=True) # ------------------------------------- def submit(opener, submit_dict): # ------------------------------------- # Init request_mode = None request_url = None request_params = None response_mode = None response_url = None response_params = None if 'request' in submit_dict: request_protocol = None if submit_dict['request'].has_key('use_ssl') and submit_dict['request']['use_ssl'].lower() == 'true': request_protocol = protocol_secure else: request_protocol = protocol_nonsecure request_mode = submit_dict['request']['mode'] request_url = request_protocol + config.get('general', 'base_url') + submit_dict['request']['url'] request_params = submit_dict['request']['params'] if 'response' in submit_dict: response_protocol = None if submit_dict['response'].has_key('use_ssl') and submit_dict['response']['use_ssl'].lower() == 'true': response_protocol = protocol_secure else: response_protocol = protocol_nonsecure response_mode = submit_dict['response']['mode'] response_url = response_protocol + config.get('general', 'base_url') + submit_dict['response']['url'] response_params = submit_dict['response']['params'] return_dict = {} return_dict['request'] = {'url': request_url, 'mode': request_mode, 'params': request_params} if response_url and response_url != request_url: return_dict['request_read'] = {'url': response_url, 'mode': response_mode, 'params': response_params} t_start = time.time() try: # Submit Request [submit_url, submit_params] = buildRequest(request_mode, request_url, request_params) check_url=submit_url+'?'+submit_params #print "\nscript url\n",check_url response = opener.open(check_url) #print response.read() # If Response URL is specified, Submit Response if response_url and response_url != request_url: [submit_url, submit_params] = buildRequest(response_mode, response_url, response_params) response = opener.open(submit_url, submit_params) if response_url != response.geturl(): return_dict['request_read']['redirect_url'] = response.geturl() # Read Response return_dict['response'] = response.readlines() except KeyboardInterrupt: sys.exit(0) except Exception, e: return_dict['exception'] = str(e) finally: t_end = time.time() return_dict['time'] = round((t_end - t_start), 5) return_dict['timestamp'] = datetime.now().isoformat(' ') return return_dict #-------------------------------------- def buildRequest(mode, url, data): # ------------------------------------- if mode == 'GET': get_url = '%s?' % (url) for k, v in data.iteritems(): get_url += '%s=%s&' % (k, v) if get_url[-1] in ['?', '&']: get_url = get_url[:-1] return [get_url, None] elif mode == 'POST': return [url, urllib.urlencode(data)] else: return [None, None] # ------------------------------------- # ------------------------------------- def login(openers): # ------------------------------------- response_protocol="http://" resp_url=response_protocol + config.get('general','base_url') + config.get('login','fk_url') resp=openers['loggedin'].open(resp_url) #print "fk_url ",resp_url page=resp.read() __FK = page[page.find("__FK"):].split("\"",4)[2] #for finding FK value email=config.get('login', 'login_email') password=config.get('login', 'login_password') opener = openers['loggedin'] url=response_protocol+config.get('general', 'base_url') + config.get('login', 'login_url') login_dict = {'request': {'mode': 'POST', 'url': url, 'use_ssl': 'false', 'params': {'__FK': __FK, 'email':email, 'password': <PASSWORD>}}} request_mode = login_dict['request']['mode'] request_url = login_dict['request']['url'] request_params = login_dict['request']['params'] return_dict = {} return_dict['request'] = {'url': request_url, 'mode': request_mode, 'params': request_params} [submit_url, submit_params] = buildRequest(request_mode, request_url, request_params) response = opener.open(submit_url,submit_params) return_dict['response'] = response.readlines() submit_response=return_dict submit_response['response'] = json.loads(submit_response['response'][0]) if submit_response['response']['status'].lower() != 'ok': jsonPrint(submit_response) sys.exit(0) else: print "\nYou are now logged in \n" # ------------------------------------- def attack(site_dict, openers): # ------------------------------------- opener = openers['loggedin'] # Submit request and get response submit_response = submit(opener, site_dict) #print "\nsubmit_response\n",submit_response # Select response (in sites or default) expected_xss_responses = "alert('XSS')" #print "expected_xss_responses",expected_xss_responses # Build vulnerability dict #vulnerability_dict = deepcopy(submit_response) #print "\nvulnerability_dic",vulnerability_dic vulnerability_dict['expected_xss_responses'] = expected_xss_responses vulnerability_dict['vulnerability'] = [] #print "vulnerability_dict['response']",vulnerability_dict # Loop through response and search for vulnerabilities if vulnerability_dict.has_key('response'): a=1 print "a=====",a if vulnerability_dict.has_key('response'): del(vulnerability_dict['response']) #print "submit_response['response']---",submit_response['response'] for line_number, line in enumerate(submit_response['response']): for expected_xss_response in expected_xss_responses: if re.search(expected_xss_response.upper(), line.upper()): vulnerability_dict['vulnerability'].append({'line_number': line_number, 'line': line.strip()}) # Output if config.get('display', 'only_show_vulnerable').lower() == 'false' or len(vulnerability_dict['vulnerability']) > 0: jsonPrint(vulnerability_dict) intt=1 else: print "...." # ------------------------------------- def attackSequence(sites, payloads, openers): # ------------------------------------- # Init threadpool = ThreadPool(int(config.get('general', 'max_thread_count'))) opener=openers['loggedin'] for site in sites: site_dict = json.loads(site) #print "\n-------->",site_dict fk_url=site_dict['request']['fk_url'] #not response url instead fkurl changes need to be made #print "\nfk_url-->",fk_url resp=opener.open(fk_url) page=resp.read() __FK = page[page.find("__FK"):].split("\"",4)[2] #for finding FK value #print __FK __FK = urllib.quote_plus(__FK) #print "\n__FK ",__FK print "\nWorking...." for payload in payloads: for param_k in sorted(site_dict['request']['params'].iterkeys()): attack_dict = deepcopy(site_dict) attack_dict['request']['params']['__FK'] =__FK #print "\n ------------->",attack_dict attack_dict['request']['params'][param_k] = payload threadpool.enqueue(attack, attack_dict, openers) #print "sites -------->\n",sites # Wait for threadpool threadpool.wait() # ------------------------------------- if __name__ == '__main__': # ------------------------------------- # Parse Config config = ConfigHelper(CONFIG_FILE, False) # Init debug('Initializing script ...') t_global_start = time.time() # Load SITES and PAYLOADS files sites = [] sites_file = open(config.get('files', 'sites_file')) for site in sites_file: site = site[:-1].strip() if site[0] != '#': sites.append(site) payloads = [] payloads_file = open(config.get('files', 'payloads_file')) for payload in payloads_file: payload = payload[:-1].strip() if payload[0] != '#': payloads.append(payload[:-1]) # Create Openers openers = dict() print "\nYou are being logged into Test.com make sure you enter testbed urls (else changed config file)\n" debug('Creating guest session ...') openers['guest'] = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookielib.CookieJar())) debug('Creating logged in session ...') openers['loggedin'] = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookielib.CookieJar())) login(openers) #take_input() # Loop through SITES file debug('\nStarting attack sequence ...') attackSequence(sites, payloads, openers) # Exit t_global_end = time.time() if (intt=='0'): print "\nNo Vulnerabilities found\n" debug('Time taken : %.2f seconds' % (t_global_end - t_global_start))<file_sep>#!/usr/bin/env python # Imports import sys, re, urllib2, urlparse, json, time, httplib,cookielib,urllib from threadpool import * # Config DEBUG = True MAX_THREAD_COUNT = 10 SITES_FILENAME = 'sites' PAYLOADS_FILENAME = 'get_payload' SCHEME_DELIMITER = '://' #XSS_RESPONSE = "alert('XSS')" cj = cookielib.CookieJar() opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) intt=0 # ------------------------------------- def attack(url, payload): # ------------------------------------- t_start = time.time() print "..." return_dict = dict() return_dict['url'] = url #return_dict['url_data'] = data return_dict['vulnerability'] = False #post_url='http://test.com' # the url in which XSS test needs to be done and it is different from url where we posted params try: return_dict['method'] = 'GET' XSS_RESPONSE=payload #print "payload--->", payload attack= urllib2.urlopen(url).read() #print "\nURL being hit :", url index = attack.find(XSS_RESPONSE) buffer = 20 print_url=url.replace("<","&lt") attack = attack.split("\n"); len(attack) #print "\nurl->\n",url if index != -1: return_dict[' vulnerability'] = True print "\nThis url seems vulnerable\n\n",print_url return_dict['vulnerability_data'] = line.strip() #print "payload found\n", attack[index-buffer:index+len(XSS_RESPONSE)+buffer] intt=intt+1 print intt # break #print "here" t_end = time.time() return_dict['time'] = round((t_end - t_start), 2) except KeyboardInterrupt, ke: sys.exit(0) except Exception, e: return_dict['exception'] = str(e) # ------------------------------------- if __name__ == '__main__': # ------------------------------------- # Init t_global_start = time.time() sites_file = open(SITES_FILENAME) payloads_file = open(PAYLOADS_FILENAME) threadpool = ThreadPool(MAX_THREAD_COUNT) # Load SITES and PAYLOADS files sites = [] input = str(raw_input("\nEnter the URLS you want to test\n")) sites = [] sites = input print "\nWorking..." payloads = [] for payload in payloads_file: payloads.append(payload[:-1]) # Loop through sites # Extract Base URL and Parameters from site parse_url = urlparse.urlparse(sites) base_url = '%s%s%s%s' % (parse_url.scheme, SCHEME_DELIMITER, parse_url.netloc, parse_url.path) #print base_url param_parse_list = urlparse.urlparse(sites)[4].split('&') param_dict = dict() for param_parse_entry in param_parse_list: tmp = param_parse_entry.split('=') param_dict[tmp[0]] = tmp[1] # Loop through payloads for payload in payloads: # Loop through parameters #print payload for k1, v1 in iter(sorted(param_dict.iteritems())): # Build GET param string and POST param dict get_params = '' post_params = dict() for k2, v2 in iter(sorted(param_dict.iteritems())): if k1 == k2: get_params += '%s=%s&' % (k2, payload) post_params[k2] = payload else: get_params += '%s=%s&' % (k2, v2) post_params[k2] = v2 get_params = get_params[:-1] #print get_params # Enqueue GET attack get_attack_url = '%s?%s' % (base_url, get_params) threadpool.enqueue(attack, get_attack_url, payload) #attack(get_attack_url, payload) # Wait for threadpool threadpool.wait() # Exit t_global_end = time.time() #if DEBUG: #print "int->",int if(intt == 0): print "\n\tNothing Found! \n" print 'Time taken : %.2f seconds' % (t_global_end - t_global_start)
2a474c561e47a725bfbf55776651a025c4a71661
[ "Python", "Text", "Shell" ]
10
Shell
vah13/Automated-XSS-Finder
30d50d131bcb8415b7f575794ee080fd7b8b64c9
73bef1b13e960500e03ad44bb4f3b3df6f2807ad
refs/heads/master
<file_sep># Generated by Django 3.0.6 on 2020-05-21 14:26 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Registry', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('fio', models.CharField(max_length=255)), ('mail_response', models.CharField(blank=True, max_length=255, null=True)), ('priem_data', models.DateField()), ('priem_fio', models.CharField(max_length=255)), ('priem_doljnost', models.CharField(max_length=255)), ('priem_content', models.TextField(blank=True, null=True)), ('priem_results', models.TextField(blank=True, null=True)), ('destination', models.CharField(blank=True, max_length=255, null=True)), ('data_prinytiy', models.DateField()), ('number', models.IntegerField()), ('created_fio', models.CharField(max_length=255)), ('created_doljnost', models.CharField(max_length=255)), ('comment', models.TextField(blank=True, null=True)), ('date_created', models.DateTimeField(auto_now=True)), ], ), ] <file_sep>from django.contrib import admin from .models import Registry # Register your models here. admin.site.register(Registry)<file_sep>from django.shortcuts import render from .models import Registry from django.utils import timezone def create_record(request): rows = Registry.objects.filter(date_created__lte=timezone.now()).order_by('date_created') return render(request, 'database/create_record.html', {'rows':rows})<file_sep>from django.db import models from django.conf import settings from django.utils import timezone class Registry(models.Model): fio = models.CharField(max_length=255) mail_response=models.CharField(max_length=255,blank=True,null=True) priem_data=models.DateField(auto_now=False,auto_now_add=False) priem_fio=models.CharField(max_length=255) priem_doljnost=models.CharField(max_length=255) priem_content=models.TextField(blank=True, null=True) priem_results=models.TextField(blank=True,null=True) destination=models.CharField(max_length=255,blank=True,null=True) data_prinytiy=models.DateField(auto_now=False,auto_now_add=False) number=models.IntegerField() created_fio=models.CharField(max_length=255) created_doljnost=models.CharField(max_length=255) comment=models.TextField(blank=True,null=True) date_created=models.DateTimeField(auto_now=True) def recording(self): self.date_created=timezone.now() self.save() def __str__(self): return self.fio
9474705f13d604b6095892b59f8701f527d47991
[ "Python" ]
4
Python
Moneo46/opc_sekretar
03cb1f6c1ac57582fb4dec16f185eca9767cfd0c
4dae19c230b36010a0fe1974ff096332f796e6e4
refs/heads/master
<repo_name>emiax/emilaxelsson.se-2017<file_sep>/src/templates/stainspageheader.js /*import React from 'react'; import ReactDom from 'react-dom'; import { Link } from 'react-router'; import StainsAnimation from '../stainsAnimation'; export default class extends React.Component { constructor(props) { super(props); } componentDidMount() { this._headerAnimation = null; console.log(this.props); let gl = null; let container = ReactDom.findDOMNode(this); let canvas = document.createElement('canvas'); container.appendChild(canvas); function updateCanvasSize() { var w = container.offsetWidth; var h = container.offsetHeight; canvas.width = w; canvas.height = h; return [w, h]; } let titleVisible = true; let canvasSize = [0, 0]; try { gl = canvas.getContext('webgl'); } catch (e) { console.log('WebGL not supported.'); } if (gl) { let size = updateCanvasSize(this._headerAnimation); console.log(this.props.src); this._headerAnimation = new StainsAnimation(gl, size[0], size[1], this.props.src); window.addEventListener('resize', () => { let size = updateCanvasSize(this._headerAnimation); this._headerAnimation.setSize(size[0], size[1]); }); this._headerAnimation.start(); } let self = this; canvas.addEventListener("mousemove", function (evt) { if (!evt.buttons) return; self._headerAnimation.applyStain( [(evt.pageX - this.offsetLeft) / canvas.width, 1.0 - (evt.pageY - this.offsetTop) / canvas.height], Math.random() * 10, 0.7 + 0.2 * Math.random() ); }); var imageLoader = container.getElementsByClassName('fileUpload')[0]; imageLoader.addEventListener('change', handleImage, false); function handleImage(e) { var reader = new FileReader(); console.log(reader); reader.onload = function (event) { var image = container.getElementsByClassName('uploadedFile')[0]; console.log(image); image.src = event.target.result; } //$('.uploader img').attr('src',event.target.result); reader.readAsDataURL(e.target.files[0]); } } componentWillUnmount() { this._headerAnimation.stop(); } render() { return ( <header id="stains-page-header"> <img className="uploadedFile" src=""/> <input type="file" className="fileUpload" /> </header> ) } };*/<file_sep>/src/templates/navbar.js import React from 'react'; import { Link } from 'react-router'; export default class extends React.Component { constructor(props) { super(props); const maxHeight = 50; let self = this; let height = 50; let prevScroll = 0; this._updateNavBar = function (evt) { let newScroll = document.body.scrollTop; let diff = newScroll - prevScroll; if (newScroll < maxHeight) { height = maxHeight; } else if (diff < 0) { height = Math.max(Math.min(maxHeight, height - diff), 0); } else { height = 0; } self._navBar.style.height = height + 'px'; prevScroll = newScroll; }; } componentDidMount() { window.addEventListener("scroll", this._updateNavBar); } componentWillUnmount() { window.removeEventListener("scroll", this._updateNavBar); } render() { return ( <div> <nav ref={component => this._navBar = component} style={{height: 50}}> <div> <Link to="/">Back to start page</Link> </div> </nav> <div className="nav-placeholder"></div> </div> ) } };<file_sep>/src/templates/stainsheader.js /*import React from 'react'; import ReactDom from 'react-dom'; import { Link } from 'react-router'; import StainsAnimation from '../stainsAnimation'; let headerAnimation = null; export default class extends React.Component { constructor(props) { super(props); console.log(props); } componentDidMount() { console.log(this.props); let gl = null; let header = ReactDom.findDOMNode(this); let canvas = header.getElementsByTagName("canvas")[0]; function updateCanvasSize() { var w = header.offsetWidth; var h = header.offsetHeight; canvas.width = w; canvas.height = h; return [w, h]; } let titleVisible = true; let canvasSize = [0, 0]; try { gl = canvas.getContext('webgl'); } catch (e) { console.log('WebGL not supported.'); } if (gl) { let size = updateCanvasSize(headerAnimation); headerAnimation = new StainsAnimation(gl, size[0], size[1]); window.addEventListener('resize', function () { let size = updateCanvasSize(headerAnimation); headerAnimation.setSize(size[0], size[1]); }); headerAnimation.start(); } canvas.addEventListener("mousemove", function (evt) { if (!evt.buttons) return; headerAnimation.applyStain( [(evt.pageX - this.offsetLeft) / canvas.width, 1.0 - (evt.pageY - this.offsetTop) / canvas.height], Math.random() * 10, 0.7 + 0.2 * Math.random() ); }); } componentWillUnmount() { headerAnimation.stop(); } render() { return ( <header id="main-header"> <canvas id="main-header-canvas"></canvas> </header> ) } }*/<file_sep>/src/templates/stainspage.js import React from 'react'; import { Link } from 'react-router'; import TeX from 'react-components/js/tex.jsx'; import StainsComponent from './stainscomponent'; import NavBar from './navbar'; export default class extends React.Component { render() { let pw = "\\mathbf{p}_w"; let pd = "\\mathbf{p}_d"; let pw1 = "\\mathbf{p}_{w_1}"; let pw1Prime = "\\mathbf{p}_{w_1}^\\prime"; let pw2 = "\\mathbf{p}_{w_2}"; let pw2Prime = "\\mathbf{p}_{w_2}^\\prime"; let fAdv = "f_{\\text{adv}}"; let fDrying = "f_{\\text{dry}}"; let fDryingEq0 = "f_{\\text{dry}} = 0"; let fDryingEq1 = "f_{\\text{dry}} = 1"; let vDrying = "v_{\\text{dry}}"; let fDiffusion = "f_{\\text{dif}_i}"; let vDiffusion = "v_{\\text{dif}}"; let waterAdvectionEquation = "w_1 = w_1^\\prime \\cdot (1 - " + fAdv + "(w_1^\\prime)) + w_2^\\prime \\cdot " + fAdv + "(w_2^\\prime)"; let wetAdvectionEquation = "\\mathbf{p}_{w_1} = \\mathbf{p}_{w_1}^\\prime \\cdot (1 - " + fAdv + "(w_1^\\prime)) + \\mathbf{p}_{w_2}^\\prime \\cdot " + fAdv + "(w_2^\\prime)"; //let waterAdvectionFactorEquation = fAdv + "(w) = \\left\\{\\begin{array}{lr}0 & w < w_{threshold}\\\\3(w-w_{threshold})^2 - 2(w-w_{threshold})^3\\end{array}\\right\\}"; //let waterClamping = '[0, (\\text{lowerThreshold} + \\text{upperThreshold}) / 2]'; let evaporationEquation = "w = \\text{max}(0, w^\\prime - v_e)"; let advectionFactorImplementation = [ 'float advectionFactor(waterAmount)\n' + ' return smoothstep(lowerThreshold, upperThreshold, waterAmount);\n' + '}']; let dryingEquationDry = '\\mathbf{p}_d = \\mathbf{p}_d^\\prime + ' + fDrying + '\\cdot \\mathbf{p}_w^\\prime'; let dryingEquationWet = '\\mathbf{p}_w = \\mathbf{p}_w^\\prime - ' + fDrying + '\\cdot \\mathbf{p}_w^\\prime'; let dryingRateEquation = fDrying + ' = \\max(\\min(' + vDrying + ' \\cdot (1 + \\epsilon(x, y), 1), 0)'; let diffusionFactorEquation = fDiffusion + ' = \\text{min}(' + vDiffusion + '\\cdot w^\\prime \\cdot w_i^\\prime, \\frac{1}{4})'; let diffusionWaterEquation = 'w = (1 - \\sum_{i} ' + fDiffusion + ') \\cdot w^\\prime + \\sum_{i} ' + fDiffusion + 'w^\\prime_i'; let diffusionPigmentEquation = '\\mathbf{p}_w = (1 - \\sum_{i} ' + fDiffusion + ') \\cdot \\mathbf{p}_w^\\prime + \\sum_{i} ' + fDiffusion + '\\mathbf{p}_{w_i}^\\prime'; let finalColor = "\\mathbf{c}"; let finalColorEquation = '\\mathbf{c} = ' + pw + ' + (1 - \\mathbf{p}_{w_a})' + pd; return ( <div> <NavBar/> <div className="stains-page-header"> <StainsComponent src="input4.jpg" brushSize={15} randomPaint mousePaint backgroundColor={[0.1, 0.1, 0.1]}/> </div> <article> <h2>Stains: Interactive art in the browser</h2> <p> <em>Stains</em> is a JavaScript/WebGL library that I created to mimic the visual appearance and behaviour of aquarelle on a canvas. The library, which can procedurally generate aquarelle paintings is used to create artistic-looking elements for my personal website and allow visitors to interact with the content. It does not necessarily serve a much deeper purpose than simply looking visually appealing, but I also think it is an interesting proof-of-concept for a style of computer graphics, that could be used in other contexts, such as digital storytelling, computer games, VJing or other forms of interactive art. </p> <div className="stains-page-widget"> <StainsComponent src="input2.png" brush="stainsBrush" mousePaint backgroundColor={[0.97, 0.97, 0.97]}/> </div> <p className="caption"> Click and draw on the canvas to create your own drip painting. </p> <h3>Designing the model</h3> <p> With WebGL, the web browser has lately become a very capable platform for computer graphics, but it is still limited in comparison to native applications. Also, while it is reasonable to expect a 3D computer game to use the full potential of a computer's performance, it may not be as acceptable for a web site to drain all the available resources and make other applications run slow. There are sophisticated physical models out there that accurately approximate the behavior of a real fluid, but in order to create efficient real-time graphics applications, it is sometimes a good idea to cheat. For example, while it still makes sense to base the model on physical laws, a correct model covering all phenomena such as surface tension and pressure is not only difficult to implement: it also requires a lot of computational resources to get right. </p> <p> After experimenting with a really simple model, where paint would just be represented as a color and an amount, I realized that an important visual aspect of aquarelle is the possibility to vary the concentration of pigment in water. Hence I modified the model to be able represent both dry and wet paint separately. This allows the paint to have a variable concentration of pigment dissolved in the water. Separating dry and wet paint also makes it possible to model several important processes in aquarelle; the effects that made it into the final implementation are: </p> <ul> <li>Evaporation of water</li> <li>Simple advection (movement) of water due to external forces like gravity</li> <li>Fixation of wet pigment into the canvas (paint drying)</li> <li>Diffusion that allow colors to mix</li> </ul> <h3>A grid with values</h3> <p> At the very core of this simulation, a two-dimensional grid is used to represent the canvas. In each grid cell, a few values are stored: </p> <ul> <li>Amount of water (scalar value)</li> <li>Amount of pigment dissolved in the water (scalar value)</li> <li>Color of the dissolved pigment (<TeX>RGB</TeX>-vector)</li> <li>Amount of dried pigment (scalar value)</li> <li>Color of the dried pigment (<TeX>RGB</TeX>-vector)</li> </ul> <p>To conclude, a total of nine scalar values per grid cell are used. Typically, a grid cell's size equals the size of one pixel. In WebGL this data is represented as two floating point <TeX>RGBA</TeX>-textures and one scalar float texture. The two <TeX>RGBA</TeX> textures represent the state of wet and dry pigment respectively, with the <TeX>RGB</TeX> channels storing the pigment color and the <TeX>A</TeX> channel storing the amount of pigment. The <TeX>RGB</TeX> are premultiplied with the <TeX>A</TeX> channel. This means that instead of <TeX>R, G, B \in [0, 1]</TeX>, the values are multiplied by <TeX>A</TeX> so that <TeX>R, G, B \in [0, A]</TeX>, allowing colors to be mixed by simple vector addition. Intuitively, increasing the pigment amount (larger <TeX>A</TeX>-value) increases the contribution to a color mix. The scalar texture is used to store the amount of water in each cell. </p> <p> Manipulation of the grid, i.e. addition of new paint and simulation of existing paint, is done by feeding in the grid textures as input to a shader program, that writes new values to a new set of textures. Once the new state of the simulation has been stored in a set of textures, the old texture set can be reused for the next simulation increment. This means that in total, one canvas requires four <TeX>RGBA</TeX>-textures and two scalar ones. </p> <h3>Simulating paint on the canvas</h3> <p> The image below illustrates the flow of data between the textures. </p> <svg viewBox="0 0 410 310"> <use xlinkHref="mechanism.svg#mechanism"></use> </svg> <p className="caption"> The four components of the simulation: Evaporation of water, advection of water and pigment, drying of pigments, and diffusion of water and pigments. </p> <p> The WebGL 1.0 standard does not support multiple render targets, meaning that a framebuffer object can only have one color attachment. Hence, the implementation divides each simulation increment into three shader passes, where the first one computes the new water texture, the second one computes the new wet pigment texture and the third computes the new dry pigment texture. </p> <svg viewBox="0 0 280 100"> <use xlinkHref="shaderpasses.svg#shaderpasses"></use> </svg> <p className="caption"> The arrows indicate which values that are needed to compute new ones. For example, water data is required to advect wet pigment correctly, and the wet pigment is required to compute the new dry pigment texture.</p> <p>Let us now look closer into how the four different effects are modelled and implemented.</p> <h4>Advection</h4> <p> When observing real water drops on a vertical surface, small drops tend to stick to the surface, while bigger drops of water tend to flow down the surface as gravity overcomes the attractive forces between the drop and the canvas. To capture this effect, the amount of water stored in a cell is programmed to control the flow of paint in the direction of the external force. To compute the new amount of water in a cell, two samples are made in the old water texture. The first sample <TeX>w_1^\prime</TeX> is made on the same location as the cell itself, while the second sample <TeX>w_2^\prime</TeX> is made with an offset in the opposite direction of the force acting on the fluid. The new amount of water <TeX>w_1</TeX> in the cell is then calculated as </p> <p className="block-equation"> <TeX>{waterAdvectionEquation}</TeX>, </p> <p> where <TeX>{fAdv}</TeX> is a function, that computes a factor <TeX>\in [0, 1]</TeX> of how much of the contained water that should be transported away given the the amount of water in the cell itself. The first term in the equation corresponds to the amount of water that remains in the current cell, while the second one gathers the incoming water from the neighbor cell. After experimenting with different models, I decided to set <TeX>{fAdv}</TeX> to a monotonically growing function implemented using GLSL's <code>smoothstep</code> function, outputting values between 0 and 1: </p> <pre className="source-code"> {advectionFactorImplementation} </pre> <p>Here, both the lower and upper thresholds are user defined constants, state how much water that is required for external forces to overcome the static frictional force and how much water that is required to achieve maximum flow.</p> <p> In order to allow for wet pigment to be transported by the water, the advection factor is also required when computing the new cell values for wet pigment texture. The new wet pigment vector <TeX>{pw1}</TeX> is computed similarly as the water amount. Since pigment vectors are additive, we can calculate a cell's new pigment color given the two old pigment vectors <TeX>{pw1Prime}</TeX> and <TeX>{pw2Prime}</TeX> (sampled on the same locations as <TeX>w_1^\prime</TeX> and <TeX>w_2^\prime</TeX>). </p> <p className="block-equation"> <TeX>{wetAdvectionEquation}</TeX> </p> <h4>Evaporation</h4> <p> In reality, the water in an aquarelle painting takes quite a while to evaporate. The most prominent cause of paint drying out is probably the absorption of water into the canvas, allowing the pigment to follow and fixate into the canvas. However, the important result of this process is that the amount of water decreases over time, while the pigment amount stays the same. </p> <p> For simplicity, I decided to model this as an evaporation process. In each simulation step, the water amount of each cell is decreased by a constant factor. The idea is childishly simple to implement, but yet gives visually convincing results: the most prominent being that water drops slow down over time, as their water content decreases. </p> <p>Mathematically, this can be written as</p> <p className="block-equation"> <TeX>{evaporationEquation}</TeX> </p> <p>where <TeX>w</TeX> is the new water amount, <TeX>w^\prime</TeX> is the old water amount, and <TeX>v_e</TeX> is a global evaporation rate.</p> <h4>Drying</h4> <p> While pigment that are dissolved in water is transported along with the water, pigment that have been absorbed by the canvas is less likely to get flushed away by the water. In reality, a canvas is a quite rough surface which makes the absorption non-uniform. To achieve these effects, each simulation step contains a simple algorithm that transports pigment from the wet texture into the dry one, where no advection takes place. The factor <TeX>{fDrying}</TeX> describing how much of the pigment to remove from the wet texture and insert into the dry one during a simulations step, is calculated as </p> <p className="block-equation"> <TeX>{dryingRateEquation}</TeX>, </p> <p>where <TeX>{vDrying}</TeX> is a global drying rate, and <TeX>\epsilon</TeX> is a deterministic noise function used to modulate the drying over the canvas giving each grid cell (with coordinates <TeX>(x, y)</TeX>) a unique absorption coefficient, making the canvas less "perfect" and more realistic. The noise function is borrowed from <NAME>'s and Ashima Art's <a href="https://github.com/stegu/webgl-noise">implementation</a> of <a href="http://www.itn.liu.se/~stegu/simplexnoise/simplexnoise.pdf">simplex noise</a>. </p> <p className="block-equation"> <TeX>{dryingEquationWet}</TeX> </p> <p className="block-equation"> <TeX>{dryingEquationDry}</TeX> </p> <p> A value of <TeX>{fDryingEq1}</TeX> would mean that all the pigment is moved to the dry texture, while <TeX>{fDryingEq0}</TeX> would mean that the system remains unchanged. </p> <h4>Diffusion</h4> <p> In a real aquarelle painting, dissolved color pigments easily mix with pigments in their vicinity. Water levels also tend to smooth out, so that water drops attain round shapes when surface tension and other forces set in. While real surface tension is relatively difficult to model, it is possible to achieve a similar effect by applying diffusion on the water texture and the wet pigment texture. </p> <p> For each cell, four diffusion factors <TeX>{fDiffusion}</TeX> are computed for each of its four neighbor cells <TeX>i</TeX> - (above, below, to the left and to the right). The diffusion factors are given by </p> <p className="block-equation"> <TeX>{diffusionFactorEquation}</TeX>, </p> <p> where <TeX>w^\prime</TeX> is the water content of the current cell, <TeX>w_i^\prime</TeX> is the water content of the neighboring one and <TeX>{vDiffusion}</TeX> is a global diffusion constant. </p> <p> The diffusion factors are used to determine how much water and pigments that are exchanged between the two neighboring cells. In a simulation step, the new water amount <TeX>w</TeX> and the new wet pigment vector <TeX>p_w</TeX> are calculated as </p> <p className="block-equation"><TeX>{diffusionWaterEquation}</TeX></p> <p>and</p> <p className="block-equation"><TeX>{diffusionPigmentEquation}</TeX>.</p> <h4>Combining the components</h4> <p>In the above text, the four individual simulation components (evaporation, advection, diffusion and drying) have been described individually. New water values <TeX>w</TeX> and pigment vectors <TeX>{pw}</TeX>, <TeX>{pd}</TeX> have been expressed as functions of previous state. But what previous state? In which order the operations executed? </p> <p>One method would be to perform the operations sequentially in four shader passes per texture pair. In total, that would mean <TeX>3 \cdot 4 = 12</TeX> shader passes per simulation step. A possible order of operations would be 1) evaporation, 2) advection, 3) drying, 4) diffusion. Since an important goal is to make the simulation resource efficient, in order not to occupy the whole GPU and CPU while the user is <em>just browsing a website</em>, it would be beneficial if to minimize the number of shader passes. </p> <p> It would be desirable to merge the four simulation components into one shader pass per texture pair. However, to get the same results as if the operations were to be carried out as separate shaders, the diffusion step would need access to the output of the drying step, which would in turn need the output from the advection step, which in turn would need the output from the advection. Due to the nature of fragment shaders, to do this correctly, the program would have to sample more cells and apply the substeps to each of them, instead of tracking the state of only one cell. Texture samples are also relatively expensive, so if they could be avoided, that would speed up the simulation. </p> <p> Since the main goal is not to make visually convincing graphics, rather than a correct physical simulation, some simplifications are made in order to minimize texture accesses. When applying the diffusion step, the algorithm operates on advected values for the active cell itself, but for neighbor cells, advection is ignored. This decreases the required texture samples by four in both the water simulation and the wet pigment simulation, without causing a noticable visual difference. </p> <h3>Adding paint to the canvas</h3> <p>When using a brush to paint on a surface, color is not only released from the brush: it also gets picked up from the canvas and dragged along with the brush strokes. Modelling this would require a relatively sophisticated simulation. Drip painting on the other hand can be modelled in a much simpler way, by just adding water and pigment to the canvas. I decided to implement this, and save other brush techniques for future work. </p> <h4>Modelling drip painting</h4> <p> The act of adding paint to the canvas is implemented using two shader passes: one writing to the water texture and one writing to the wet pigment texture. The dry texture is not affected directly, but only gets filled with pigment thanks to the drying process described earlier. </p> <p> When dripping paint on a canvas, stains usually come in clusters. To create a stain, a set of points and sizes are generated with JavaScript's built in <code>Math.rand()</code> function. The set of points and sizes are fed in as a uniform vec2 array and a unfiform float array to the GPU. For each cell, a fragment shader is picking out the closest of these points, normalized by point size, using linear search. The amount of water and pigment to add to each cell on the canvas is calculated using GLSL's <code>smoothstep</code> function. </p> <pre className="source-code"> float amount = smoothstep(stainSize, stainSize * 0.5, distance); </pre> <p> Apart from being in different positions and sizes, stains can also be applied with different amount of water and pigment, and with different colors. </p> <div className="stains-page-widget-small"> <StainsComponent brush="stainsBrush" brushDemo fuzziness={0} backgroundColor={[0.98, 0.98, 0.98]}/> </div> <p className="caption"> Along each row, the stain size increases. For each stain, the amount of water and pigment increases. On the top row, the amount of water has increased to the level required for gravity to successfully pull the paint downwards. </p> <h4>Fuzzy drops</h4> <p> In reality, stains may be quite round in their shape, but they are never perfectly circular. To achieve this, the closest distance to a stain point is modulated using the same noise function that was used to modulate the drying: simplex noise. </p> <div className="stains-page-widget-small"> <StainsComponent brush="stainsBrush" brushDemo fuzziness={0.4} backgroundColor={[0.98, 0.98, 0.98]}/> </div> <p className="caption"> Noise is applied to the distance to the closest point, creating a more realistic result. </p> <h3>Selecting colors</h3> <img src="input_original_800.png" className="hang-right" style={{width: '400px', height: '400px'}}></img> <p> As an experiment, I implemented a feature to allow the library select colors from existing images, essentially making it possible to feed in a photo and turn it into a drip painting. The image is fed into wet pigment shader pass for adding stains, and colors are sampled from the center point of all the points in a stain cluster. </p> <p> This photo is taken from a path along <NAME>. I manually masked out the water in the photo, and instructed the algorithm to put more water in the color when painting in those areas. </p> <div className="stains-page-widget-square"> <StainsComponent src="input.png" randomPaint mousePaint brushSize={15} fuzziness={0.4} backgroundColor={[0.98, 0.98, 0.98]}/> </div> <h3 style={{clear: 'both'}}>Rendering the model to the screen</h3> <p> To render the data to the screen, the contents of the dry and wet pigment are both taken into account. The water is considered invisible and does not contribute to the final rendering other than dictating the flow of pigment during the simulation step. The final color vector <TeX>{finalColor}</TeX> is given by the blending equation </p> <p className="block-equation"> <TeX>{finalColorEquation}</TeX> </p> <p> where <TeX>{pw}</TeX> is the wet pigment vector, and <TeX>{pd}</TeX> is the dry pigment vector. </p> <h3>To wrap up</h3> <p>I think this project demonstrates how relatively simple physically based simulation can be combined with procedural methods for images, such as noise, to create visually convincing results. When working on this, a lot of different ideas of future improvements and use cases have popped up in my head: How about a full game with graphics based on this style? Or some kind of interactive movie? </p> <p>If you're interested in using the stuff in your own project, the source code is freely available on <a href="https://github.com/emiax/stains">Github</a> under the MIT license. </p> </article> </div> ) } }; <file_sep>/src/templates/startpage.js import React from 'react'; import { Link } from 'react-router'; import StainsComponent from './stainscomponent'; import EaLogoComponent from './ealogocomponent'; export default class extends React.Component { render() { return ( <div> <div className="start-page-header"> <StainsComponent src="input4.jpg" brushSize={20} randomPaint mousePaint backgroundColor={[0.98, 0.98, 0.98]}/> <EaLogoComponent/> <div className="fade-to-white"></div> </div> <article> <h2>Hi, I'm Emil</h2> <p className="intro">I'm a creative engineer, based in Norrköping, Sweden. I like the places where software and people meet. Luckily, that happens sort of everywhere these days. Bring music, visualizations, graphics and great teamwork into the mix, and I'm in my favorite spot. </p> <p> Currently I am working as a research engineer at Linköping University / Visualization Center C, mainly devoting my time to the open source project OpenSpace. I also get to have fun with our dome theatre: both developing tech infrastructure and creating movies and interactive content. </p> <h2>Let's talk!</h2> <p> It's probably easiest to send a message on <a href="https://www.facebook.com/nils.emil.axelsson">Facebook</a> or to drop an email to <a href="mailto:<EMAIL>"><EMAIL></a>. You may want to find me on <a href="http://github.com/emiax">Github</a> or <a href="https://www.linkedin.com/in/emiax">LinkedIn</a> as well. </p> <h2>Some of my work</h2> <h3>Stains: Interactive art in the browser</h3> <div src="enlil.jpg" className="hang-right" style={{position: 'relative', width: 400, height: 400}}> <StainsComponent src="input2.png" brushSize={10} randomPaint mousePaint backgroundColor={[0.97, 0.97, 0.97]}/> </div> <p> <Link to="stains"><em>Stains</em></Link> is a JavaScript/WebGL library that I created to mimic the visual appearance and behaviour of aquarelle on a canvas. The library, which can procedurally generate aquarelle paintings is used to create artistic-looking elements for my personal website and allow visitors to interact with the content. It does not necessarily serve a much deeper purpose than simply looking visually appealing, but I also think it is an interesting proof-of-concept for a style of computer graphics, that could be used in other contexts, such as digital storytelling, computer games, VJing or other forms of interactive art. </p> <h3>OpenSpace and Master's thesis @ NASA</h3> <img src="enlil.jpg" className="hang-left" style={{width: 500, height: 500 * 540/960}}></img> <p> Interdum et malesuada fames ac ante ipsum primis in faucibus. Suspendisse feugiat scelerisque justo, in dignissim mauris. Etiam lacinia nibh suscipit nisl imperdiet, eget sagittis sem congue. Sed eleifend leo pulvinar lacus tristique elementum. Nulla venenatis lacus id diam feugiat bibendum. Maecenas magna diam, ultricies vitae rutrum eu, porta consectetur metus. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus tempor, justo eu finibus aliquam, turpis nunc ultricies ligula, vel mattis leo ligula quis arcu. Fusce fringilla eget nibh at elementum. Etiam felis nunc, euismod id sollicitudin at, euismod et metus. Duis sed aliquet justo. Ut viverra eros id faucibus interdum. Vivamus in vestibulum nibh. </p> <h3>Best Healthcare and Medical Care @ ESH2016</h3> <img src="esh.jpg" className="hang-right" style={{width: 500, height: 500 * 1322/2048}}></img> <p> Vivamus quis malesuada nisl. Phasellus volutpat orci ut metus gravida, quis varius leo porta. Pellentesque neque diam, consequat et justo sed, finibus pretium dui. Aenean pretium massa nec ipsum maximus, vel molestie elit maximus. Nam aliquam libero eget dictum viverra. Nam eget quam vitae velit laoreet semper vitae sit amet est. Sed varius erat nec nibh euismod, at ornare nisi porttitor. Phasellus suscipit quis ipsum vel tincidunt. Fusce at dignissim nisi, sed molestie justo. Proin at varius turpis. Quisque varius, lectus in sodales varius, tellus orci consectetur turpis, sit amet rutrum magna metus vel diam. Nunc ut viverra lacus. Nam dignissim quis dui ut dapibus. Ut urna mi, convallis nec mi id, maximus posuere enim. </p> <h3>Accessibility @ Spotify</h3> <div className="hang-right" style={{width: 200, height: 200}}> <svg viewBox="-20 -20 140 140"> <use xlinkHref="spotify.svg#spotify"></use> </svg> </div> <p> Vivamus quis malesuada nisl. Phasellus volutpat orci ut metus gravida, quis varius leo porta. Pellentesque neque diam, consequat et justo sed, finibus pretium dui. Aenean pretium massa nec ipsum maximus, vel molestie elit maximus. Nam aliquam libero eget dictum viverra. Nam eget quam vitae velit laoreet semper vitae sit amet est. Sed varius erat nec nibh euismod, at ornare nisi porttitor. Phasellus suscipit quis ipsum vel tincidunt. Fusce at dignissim nisi, sed molestie justo. Proin at varius turpis. Quisque varius, lectus in sodales varius, tellus orci consectetur turpis, sit amet rutrum magna metus vel diam. Nunc ut viverra lacus. Nam dignissim quis dui ut dapibus. Ut urna mi, convallis nec mi id, maximus posuere enim. </p> <h3>Interaction design and 3D programming @ Spotscale</h3> <p>Duis interdum imperdiet ligula quis efficitur. Nam vel metus sed nunc ultrices vulputate. Etiam lobortis augue a lobortis mattis. Cras metus ligula, maximus vitae mattis sit amet, consequat sodales odio. Nulla non diam maximus, laoreet nisi vel, cursus lectus. Donec posuere sodales diam sed blandit. Ut tincidunt molestie semper.</p> <h3>Knapsack, iOS Game prototype</h3> <p> Cras feugiat enim vel viverra luctus. Pellentesque viverra nisi at justo elementum sollicitudin. Mauris hendrerit sapien tellus, vel suscipit dolor cursus eu. Nullam sit amet posuere orci, pretium ullamcorper diam. Praesent commodo leo ut risus efficitur, eu tristique mauris mattis. In hac habitasse platea dictumst. Proin non auctor tellus. Curabitur pretium sodales hendrerit. Ut non consectetur urna. In a metus ut quam tincidunt condimentum vitae ac risus. Nulla consequat ultrices velit, tincidunt tristique ipsum maximus tempor. Nulla vehicula pharetra neque non aliquet. Phasellus commodo pretium est. Duis sagittis id arcu sed tristique </p> <h3>Continuous</h3> <p>A concept for visualizing math in the browser.</p> <h3>The future of Norrköping: Dome movie production</h3> <h3>Software intern @ Configura</h3> </article> </div> ); } }; <file_sep>/src/templates/notfound.js import React from 'react'; import { Link } from 'react-router'; export default class extends React.Component { render() { return ( <div> <p>404 Not found</p> </div> ) } };
3da6e97762a192a78ca6f2449156acbe3396d5b0
[ "JavaScript" ]
6
JavaScript
emiax/emilaxelsson.se-2017
26fa271d726c033b6225771bcf2c98fac8ab18f9
917deddb2e186180d4d75dbb7846219b34205934
refs/heads/master
<repo_name>nikkyhwang/hello<file_sep>/src/pages/index.js import React from "react" export default () => <div>Nikky!</div>
5b522f3c95efdd204c1cced9ef17902182ce48a2
[ "JavaScript" ]
1
JavaScript
nikkyhwang/hello
4a7cb26dd985a36ea91ea8355bd4e399da58386c
c816cd785c33111e19684c6574fc0cee3fd06892
refs/heads/master
<file_sep>// use this to copy code snippets or use your browser's console class Event { constructor(title, keywords) { this.title = title; this.keywords = keywords; } } class User { constructor(name, interests) { this.name = name; this.interests = interests; } matchInterests(event) { return event.keywords.some( function(word) { return this.interests.includes(word); }.bind(this) // added to the and of the callback function ); } } let billy = new User('billy', ['music', 'art', 'movies']); let freeMusic = new Event('Free Music Show', ['music', 'free', 'outside']); billy.matchInterests(freeMusic); //the mathchInterests function needs the 'bind' function to be able to access the instance //of a user. matchInterests(event) { return event.keywords.some(word => this.interests.includes(word)); } //using arrow functions, this will always refer to the context the function was invoked in // for our matchInterests function, it was invoked within the User class, making //the 'this' always an instance of the User class. let sally = { name: 'Sally' }; function greet(customerOne, customerTwo) { console.log(`Hi ${customerOne} and ${customerTwo}, my name is ${this.name}!`); } greet.call(sally, 'Terry', 'George'); // Hi Terry and George, my name is Sally! greet.apply(sally, ['Terry', 'George']); // Hi Terry and George, my name is Sally! //call and apply functions are used to invoke a functoin. //call will take many arguments on a function that it is applied to. //apply can only be used with two arguments. the second will need to be an array if there // are multiple values that apply to one of our arguments // apply = may require an array //call will take multiple arguements
5033a27de8d7b5a75dbcd3e145ef5fcf5782c42a
[ "JavaScript" ]
1
JavaScript
christine1226/js-object-oriented-bind-call-apply-readme-dumbo-web-091718
0e4305c119364883c8ef9a11d326acff180aff8a
af959b41ad45d7c0451f34ccabb0762ad16935c1
refs/heads/master
<file_sep>using System.IO; using System.Collections; using System.Collections.Generic; using System.Linq; using UnityEngine; using System; using System.Text.RegularExpressions; public class ParticleGenerator : MonoBehaviour { public GameObject arrowPrefab; private Dictionary<int, List<Dictionary<string, Vector3>>> tslices = new Dictionary<int, List<Dictionary<string, Vector3>>>(); private int highestFrame = 0; private int currentFrame = 0; public int skipFactor = 200; public float maxM = 0f; private string[] separator = new string[] { ", " }; // Use this for initialization void Start() { ParseCSVS(); LoadFrame(0); } // Update is called once per frame void Update() { int f = (int)(Time.time * 10) % (highestFrame + 10); if (f != currentFrame) { Debug.Log("Loading frame: " + f); LoadFrame(f); currentFrame = f; } } void ParseCSVS() { var sw = new System.Diagnostics.Stopwatch(); sw.Start(); Debug.Log("reading csvs"); var csvs = Resources.LoadAll("animation"); foreach (TextAsset csvObject in csvs) { var s = csvObject.name; s = s.Substring(s.Length - 3); int ts = int.Parse(s) - 405; Debug.Log(ts); if (ts > highestFrame) { highestFrame = ts; } tslices[ts] = new List<Dictionary<string, Vector3>>(); var csv = csvObject.text.Split('\n'); var headers = csv[5].Split(separator, StringSplitOptions.RemoveEmptyEntries); Vector3 modelOrigin = Vector3.zero; var count = 0; for (int i = 6; i < csv.Length; i += skipFactor) { count++; var line = csv[i]; if (line.Length == 0) continue; var bits = line.Split(separator, StringSplitOptions.RemoveEmptyEntries); var d = new Dictionary<string, float>(); for (var j = 0; j < headers.Length; j++) { try { d[headers[j].Trim()] = float.Parse(bits[j]); } catch (FormatException) { } } var pos = new Vector3(d["X [ m ]"], d["Y [ m ]"], d["Z [ m ]"]); if (modelOrigin == Vector3.zero) { modelOrigin = pos; pos = Vector3.zero; } else { pos -= modelOrigin; } var direction = new Vector3(d["Velocity u [ m s^-1 ]"], d["Velocity v [ m s^-1 ]"], d["Velocity w [ m s^-1 ]"]); if (direction.magnitude > maxM) { maxM = direction.magnitude; } tslices[ts].Add(new Dictionary<string, Vector3>() { { "pos", pos }, { "direction", direction } }); } } Debug.Log(csvs.Length + " files loaded in " + sw.Elapsed + ". Maxm: " + maxM); } void LoadFrame(int frame) { var keys = tslices.Keys.ToList(); int a = 0; int b = 0; float factor = 0; if (frame < highestFrame) { for (int i = 0; i < keys.Count - 1; i++) { a = keys[i]; b = keys[i + 1]; if (a <= frame && b >= frame) { break; } } factor = 1.0f * (frame - a) / (b - a); } else { factor = (frame - highestFrame) / 10f; a = highestFrame; b = 0; } for (int i = 0; i < tslices[a].Count; i++) { var pta = tslices[a][i]; var ptb = tslices[b][i]; var pos = Vector3.Lerp(pta["pos"], ptb["pos"], factor); var direction = Vector3.Lerp(pta["direction"], ptb["direction"], factor); var m = direction.magnitude; // Arrow glyph GameObject glyph; if (gameObject.transform.childCount <= i) { glyph = Instantiate(arrowPrefab); glyph.transform.parent = gameObject.transform; } else { glyph = gameObject.transform.GetChild(i).gameObject; } glyph.transform.localPosition = pos; glyph.transform.localRotation = Quaternion.LookRotation(direction); glyph.transform.localScale = Vector3.one * m; foreach (var rend in glyph.GetComponentsInChildren<Renderer>()) { float h = 1 - m / maxM; var color = Color.HSVToRGB(h, 1, 1); //rend.material.color = color; MaterialPropertyBlock props = new MaterialPropertyBlock(); props.SetColor("_Color", color); rend.SetPropertyBlock(props); } /* try { var ps = glyph.GetComponent<ParticleSystem>(); var ma = ps.main; ma.startSpeed = direction.magnitude * 10; } catch { } */ } } } <file_sep># coronary_cfd A Unity (Vive) project visualising ANSYS results that simulate blood flow through the coronary artery <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.VR.WSA.Input; public class GazeGestureManager : MonoBehaviour { GestureRecognizer recognizer; public GameObject man; public GameObject heart; public GameObject root; public float scaleSpeed = 1.01f; public float manCutoff = 20; public float heartCutoff = 40; public bool isScaling = false; public bool scaleUp = false; // Use this for initialization private void Awake() { recognizer = new GestureRecognizer(); recognizer.TappedEvent += (source, tapCount, ray) => { Debug.Log("tap"); isScaling = true; scaleUp = !scaleUp; }; recognizer.StartCapturingGestures(); } private void TweakAlpha(GameObject go, float amount) { foreach (var r in go.GetComponentsInChildren<Renderer>()) { var mat = r.material; var c = mat.color; c.a += amount; mat.color = c; } } private void Update() { if (isScaling) { if (scaleUp) { root.transform.localScale *= scaleSpeed; if (root.transform.localScale.magnitude < manCutoff) { TweakAlpha(man, -0.01f); } else if (root.transform.localScale.magnitude >= manCutoff) { man.SetActive(false); TweakAlpha(heart, -0.01f); } if (root.transform.localScale.magnitude > heartCutoff) { heart.SetActive(false); isScaling = false; } } else { root.transform.localScale /= scaleSpeed; if (root.transform.localScale.magnitude > manCutoff) { heart.SetActive(true); TweakAlpha(heart, 0.01f); } else if (root.transform.localScale.magnitude > Vector3.one.magnitude) { man.SetActive(true); TweakAlpha(man, 0.01f); } else { isScaling = false; } } } } }
79b99f153e4af1cdc75608fd4f7423ba759db8f7
[ "Markdown", "C#" ]
3
C#
angelstudio/coronary_cfd
fda0432482a8dbe9179ac31e0d28db90d8919d7f
8cd4a29e21c51a6ee87d7a1dc417a33a944624f1
refs/heads/master
<file_sep>//Определение частоты тактового генератора #define F_CPU 8000000UL //Подключение заголовочных файлов #include <avr/io.h> #include <stdlib.h> #include <avr/interrupt.h> #include <util/delay.h> #include <avr/pgmspace.h> #include <MYLIBS/lcd.h> const unsigned char mode[27][9] PROGMEM = { {0,1,1, 0,1,1, 0,1,1}, {2,0,2, 2,30,2, 3,0,2}, {3,20,3, 3,50,3, 4,20,3}, {3,30,2, 4,0,2, 4,30,2}, {4,50,3, 5,20,3, 5,50,3}, {5,0,2, 5,30,2, 6,0,2}, {6,20,3, 6,50,3, 7,20,3}, {7,40,2, 7,0,2, 7,30,2}, {7,50,3, 8,20,3, 8,50,3}, {8,0,2, 8,30,2, 9,0,2}, {9,20,3, 9,50,3, 10,20,3}, {9,30,2, 10,0,2, 10,30,2}, {10,50,3, 11,20,3, 11,50,3}, {11,0,2, 11,30,2, 12,0,2}, {12,20,3, 12,50,3, 13,20,3}, {12,30,2, 13,0,2, 13,30,2}, {13,50,3, 14,20,3, 14,50,3}, {14,0,2, 14,30,2, 15,0,2}, {15,20,3, 15,50,3, 16,20,3}, {15,30,2, 16,0,2, 16,30,2}, {16,50,3, 17,20,3, 17,50,3}, {17,0,2, 17,30,2, 18,0,2}, {18,20,3, 18,50,3, 19,20,3}, {18,30,2, 19,0,2, 19,30,4}, {19,50,3, 20,20,3, 30,0,5}, {20,0,4, 20,30,4, 0,0,0}, {30,0,5, 30,0,5, 0,0,0} }; /* const char strmess1_en[] PROGMEM = " Choose mode "; const char strmess1_de[] PROGMEM = "Wählen sie modus"; const char strmess1_fr[] PROGMEM = " Mode choisir "; const char strmess1_sp[] PROGMEM = " Elija modo de "; const char strmess1_ru[] PROGMEM = " Выберите режим "; const char strmess2_en[] PROGMEM = " Program "; const char strmess2_de[] PROGMEM = " Programm "; const char strmess2_fr[] PROGMEM = " Programme "; const char strmess2_sp[] PROGMEM = " Programa "; const char strmess2_ru[] PROGMEM = " Программа "; const char strmess3_en[] PROGMEM = " will started "; const char strmess3_de[] PROGMEM = " gestartet "; const char strmess3_fr[] PROGMEM = " se lance "; const char strmess3_sp[] PROGMEM = " le inicio "; const char strmess3_ru[] PROGMEM = " началась "; const char strmess4_en[] PROGMEM = "Remaining"; const char strmess4_de[] PROGMEM = "Restliche"; const char strmess4_fr[] PROGMEM = "Restante"; const char strmess4_sp[] PROGMEM = "Restante"; const char strmess4_ru[] PROGMEM = "Осталось"; const char strmess5_en[] PROGMEM = " complited "; const char strmess5_de[] PROGMEM = " abgeschlossen "; const char strmess5_fr[] PROGMEM = " complété "; const char strmess5_sp[] PROGMEM = " completado "; const char strmess5_ru[] PROGMEM = " завершена "; const char strmess6_en[] PROGMEM = " Execution "; const char strmess6_de[] PROGMEM = " Ausführung "; const char strmess6_fr[] PROGMEM = " Exécution "; const char strmess6_sp[] PROGMEM = " Ejecución "; const char strmess6_ru[] PROGMEM = " Выполнение "; const char strmess7_en[] PROGMEM = " terminated "; const char strmess7_de[] PROGMEM = " beendet "; const char strmess7_fr[] PROGMEM = " terminée "; const char strmess7_sp[] PROGMEM = " terminada "; const char strmess7_ru[] PROGMEM = " прервано "; PGM_P const lang_1[] PROGMEM = {strmess1_en,strmess1_de,strmess1_fr,strmess1_sp,strmess1_ru}; PGM_P const lang_2[] PROGMEM = {strmess2_en,strmess2_de,strmess2_fr,strmess2_sp,strmess2_ru}; PGM_P const lang_3[] PROGMEM = {strmess3_en,strmess3_de,strmess3_fr,strmess3_sp,strmess3_ru}; PGM_P const lang_4[] PROGMEM = {strmess4_en,strmess4_de,strmess4_fr,strmess4_sp,strmess4_ru}; PGM_P const lang_5[] PROGMEM = {strmess5_en,strmess5_de,strmess5_fr,strmess5_sp,strmess5_ru}; PGM_P const lang_6[] PROGMEM = {strmess6_en,strmess6_de,strmess6_fr,strmess6_sp,strmess6_ru}; PGM_P const lang_7[] PROGMEM = {strmess7_en,strmess7_de,strmess7_fr,strmess7_sp,strmess7_ru}; */ //Задание структур typedef struct{ unsigned char second; unsigned char minute; }time; //Объявление переменных time t; time tmp_t; unsigned char taskminute; unsigned char tasksecond; unsigned char taskwork; unsigned char workmode; unsigned char step; bool work; bool alarm; char langsw; char buffer; /* ISR(TIMER2_OVF_vect) //Вектор прерывания по переполнению Таймера2 { t.second++; if(t.second == 60) { t.second = 0; t.minute++; } if(t.minute == 60) { t.minute = 0; } if(PINC&(1<<PINC4)){ PORTC &= ~(1<<4); } else { PORTC |= 1<<4; } } ISR(INT0_vect) //Вектор прерывания по смене логического уровня на INT0 { work=false; alarm=true; } */ int main(void) { // Ждем стабилизации внешнего резонатора _delay_ms(500); _delay_ms(500); //Конфигурируем порты DDRA=0b11111110; DDRB=0b00001111; DDRC=0b00010000; DDRD=0b10000011; _delay_ms(250); /* //Выбор языка согласно установленным свичам if((PINB&(0<<PINB0))&&(PINB&(0<<PINB1))&&(PINB&(0<<PINB2))&&(PINB&(0<<PINB3))) { langsw=0; //English - all off } if((PINB&(1<<PINB0))&&(PINB&(0<<PINB1))&&(PINB&(0<<PINB2))&&(PINB&(0<<PINB3))) { langsw=1; //Deutch } if((PINB&(0<<PINB0))&&(PINB&(1<<PINB1))&&(PINB&(0<<PINB2))&&(PINB&(0<<PINB3))) { langsw=2; //French } if((PINB&(0<<PINB0))&&(PINB&(0<<PINB1))&&(PINB&(1<<PINB2))&&(PINB&(0<<PINB3))) { langsw=3; //Espaniol } if((PINB&(0<<PINB0))&&(PINB&(0<<PINB1))&&(PINB&(0<<PINB2))&&(PINB&(1<<PINB3))) { langsw=4; //Russian } */ //Инициализация экрана LCDInit(LS_BLINK|LS_ULINE); LCDClear(); LCDWriteStringXY(5,0,"CRYOMED"); _delay_ms(200); // Отключаем прерывания Таймера 2. TIMSK &= ~(_BV(TOIE2) | _BV(OCIE2)); // Переводим Таймер 2 в асинхронный режим (тактирование от // часового кварцевого резонатора). ASSR |= _BV(AS2); TCNT2 = 0x00; TCCR2 = 0x05; //Устанавливаем коэффициент деления равным 128. OCR2 = 0x00; // Ждем готовности таймера. while (ASSR & (_BV(TCN2UB) | _BV(OCR2UB) | _BV(TCR2UB))); // Разрешаем прерывание от Таймера 2. TIMSK |= _BV(TOIE2); //Разрешаем прерывания по INT0 GICR |= (1<<INT0); MCUCR=(0<<ISC00)|(0<<ISC01); // Запрещаем прерывания глобально. cli(); menuloop: //Инициализируем переменные work=false; alarm=false; workmode=10; taskwork=0; t.minute=0; t.second=0; tmp_t.minute=99; tmp_t.second=99; //Главное меню //Включаем клавиатуру PORTD &= ~(1<<7); _delay_ms(250); // strcpy_P(buffer, (PGM_P)pgm_read_word(&(lang_1[langsw]))); LCDClear(); LCDWriteStringXY(0,0," Choose mode "); LCDWriteStringXY(0,1," Program "); // strcpy_P(buffer, (PGM_P)pgm_read_word(&(lang_2[langsw]))); while(1) //Опрос кнопок { if(PINC&(1<<PINC3)) { workmode=0; LCDWriteStringXY(10,1," #1"); } if(PINC&(1<<PINC2)) { workmode=3; LCDWriteStringXY(10,1," #2"); } if(PINC&(1<<PINC1)) { workmode=6; LCDWriteStringXY(10,1," #3"); } if((PINC&(1<<PINC0))&&(workmode<7)) { LCDClear(); LCDWriteStringXY(0,0," Program "); LCDWriteIntXY(12,0,workmode,1); LCDWriteStringXY(0,1," will started "); _delay_ms(200); _delay_ms(200); work=true; LCDClear(); goto workloop; } } workloop: //Блокируем клавиатуру PORTD |= 1<<7; //Светодиод индикации работы PORTD &= ~(1<<1); //GND PORTD |= 1<<0; //VCC //Включаем кулер PORTB |= 1<<0; GIFR |= (1<<INTF0); // Разрешаем прерывания глобально sei(); LCDWriteStringXY(0,0,"Remaining: :"); step=0; taskminute=pgm_read_byte(&(mode[step][workmode])); tasksecond=pgm_read_byte(&(mode[step][workmode+1])); taskwork=pgm_read_byte(&(mode[step][workmode+2])); while(1) { TCCR2=0x05; // Записываем "отфанарное значение" в регистр // Ждем готовности таймера 2. while (ASSR & (_BV(TCN2UB) | _BV(OCR2UB) | _BV(TCR2UB))); if(alarm==true) { goto alarm_cont; } if((taskminute==t.minute)&&(tasksecond==t.second)) { if(taskwork==1) { PORTB |= 1<<1; PORTB |= 1<<2; PORTD |= 1<<0; goto cont; } if(taskwork==2) { PORTB &= ~(1<<1); PORTB &= ~(1<<2); PORTD &= ~(1<<0); goto cont; } if(taskwork==3) { PORTB |= 1<<3; PORTD |= 1<<0; goto cont; } if(taskwork==4) { PORTB &= ~(1<<1); PORTB &= ~(1<<2); PORTB |= 1<<3; PORTD |= 1<<0; goto cont; } if(taskwork==5) { work=false; PORTB &= ~(1<<0); PORTB &= ~(1<<1); PORTB &= ~(1<<2); PORTB &= ~(1<<3); PORTD &= ~(1<<1); goto menuloop; } cont: step++; taskminute=pgm_read_byte(&(mode[step][workmode])); tasksecond=pgm_read_byte(&(mode[step][workmode+1])); taskwork=pgm_read_byte(&(mode[step][workmode+2])); //goto cont2; } cont2: if(tmp_t.minute!=t.minute) { LCDWriteIntXY(11,0,29-t.minute,2); tmp_t.minute=t.minute; } // if(t.second==00) // { // LCDWriteStringXY(14,0,"00"); // } // else // { LCDWriteIntXY(14,0,60-t.second,2); // } } alarm_cont: PORTB &= ~(1<<0); PORTB &= ~(1<<1); PORTB &= ~(1<<2); PORTB &= ~(1<<3); PORTC &= ~(1<<4); PORTD &= ~(1<<0); PORTD |= 1<<1; LCDClear(); LCDWriteStringXY(0,0," EXECUTION"); LCDWriteStringXY(0,1," TERMINATE"); return 0; }<file_sep>#include <avr/pgmspace.h> #define DATA 1 //массив во флэш-памяти для русских символов const char Decode2Rus[255-192+1] PROGMEM = { 0x41,0xA0,0x42,0xA1,0xE0,0x45,0xA3,0xA4, 0xA5,0xA6,0x4B,0xA7,0x4D,0x48,0x4F,0xA8, 0x50,0x43,0x54,0xA9,0xAA,0x58,0xE1,0xAB, 0xAC,0xE2,0xAD,0xAE,0xAD,0xAF,0xB0,0xB1, 0x61,0xB2,0xB3,0xB4,0xE3,0x65,0xB6,0xB7, 0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0x6F,0xBE, 0x70,0x63,0xBF,0x79,0xE4,0x78,0xE5,0xC0, 0xC1,0xE6,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7 }; void lcd_write(char*t) //Отображение строки символов { unsigned char i; for (i=0;i<255;i++) { if (t[i]==0) { return; } else { if (t[i]>=192) { lcd_send(DATA, pgm_read_byte(&(Decode2Rus[t[i]-192]))); } else { lcd_send(DATA, t[i]); } } } }
0ec43b3e9ede9ac6a04febf3cd5212d9dee311d5
[ "C", "C++" ]
2
C++
fleshtorment/Cryomed_salt_mixer
7b0d8eef2fcc18e0c99b5c215a6f28c086c5d6dd
8e5c444f24a254d7249668ef618c9e2d63053e04
refs/heads/master
<repo_name>guitarton/lenta<file_sep>/spiders/lenta_spider.py from scrapy.spiders import SitemapSpider from lenta.items import LentaItem class LentaSiteMapSpider(SitemapSpider): name = 'lenta-sitemap' sitemap_urls = ['http://lenta.ru/robots.txt'] # sitemap_urls = ['http://lenta.ru/news/sitemap5.xml.gz'] def parse(self, response): item = LentaItem() item['url'] = response.url item['post_body'] = response.css('div.b-topic__content').extract_first() return item <file_sep>/pipelines.py # -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html import MySQLdb con = MySQLdb.connect(host="localhost", # your host, usually localhost user="lenta", # your username passwd="<PASSWORD>", # your password db="lenta") query_url = 'INSERT INTO Pages (Url) VALUES ("{}")' query_url_id = 'SELECT LAST_INSERT_ID()' query_rank = 'INSERT INTO PersonPageRank (PersonID, PageID, Rank) VALUES ({},{},{})' # select ke.Name, per.Rank, pa.Url FROM PersonPageRank per INNER JOIN Keywords ke ON per.PersonID = ke.PersonID INNER JOIN Pages pa ON per.PageID = pa.ID WHERE Rank> 10; keywords = {u'кадыров': 2, u'немцов': 1, u'навальн': 3, u'гундяев': 5, u'лужков': 6} class LentaPipeline(object): def process_item(self, item, spider): with con: cur = con.cursor() cur.execute(query_url.format(item['url'])) cur.execute(query_url_id) page_id = cur.fetchone()[0] for person_name, person_id in keywords.items(): pr = item['post_body'].lower().count(person_name) if pr > 0: cur.execute(query_rank.format(person_id, page_id, pr)) return item
46dcecb47c47ae05d74c0c6b77260ed33eecee78
[ "Python" ]
2
Python
guitarton/lenta
c0b2c0ab415f49a1e334a202383139dc51692dda
32055aa7fb39ace72becd2f41f8be4bf89b11a37
refs/heads/master
<file_sep><!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Nissan Leaf</title> <link rel="stylesheet" href="style.css"> </head> <link rel="shortcut icon" href="img/hj.png" type="image/x-icon"> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.8.1/css/all.css" integrity="<KEY>" crossorigin="anonymous"> <body> <header> <div class="container"> <div class="row"> <div class="col"> <div class="ss"> <a href="https://www.instagram.com/s.ash_k4/" target="_blank"><i class="fab fa-instagram"></i></a> <a href="https://steamcommunity.com/id/SsBrvNsS/" target="_blank"><i class="fab fa-steam"></i></a> </div> <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <a class="navbar-brand" href="index.html"> <img src="img/niSva-4.png"></a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="index.html">Головна <span class="sr-only">(current)</span></a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Electro car </a> <div class="dropdown-menu" aria-labelledby="navbarDropdown"> <a class="dropdown-item" href="bmwi3.html">BMW i3</a> <a class="dropdown-item" href="nissan.html">Nissan Leaf</a> <a class="dropdown-item" href="renault.html">Renault Zoe</a> <a class="dropdown-item" href="TESLA.html">Tesla</a> </div> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Sport car </a> <div class="dropdown-menu" aria-labelledby="navbarDropdown"> <a class="dropdown-item" href="ferrari.html">Ferrari</a> <a class="dropdown-item" href="bugati.html">Bugati</a> <a class="dropdown-item" href="BMW.html">BMW</a> <a class="dropdown-item" href="lambo.html">Lamborghini</a> </div> </li> </ul> </div> </nav> </div> </div> </div> </header> <div class="container"> <div class="row"> <div class="col"> <h1>Nissan Leaf</h1> <p>Nissan Leaf (укр. <NAME>, також відома як «LEAF», «ЛІФ»[1]) — марка автомобіля, що випускається в Японії з 2010 року. Це перший сучасний електромобіль масового виробництва і найбільш продавана модель електромобіля у світі (стан: грудень 2015) і найпродаваніший електромобіль в Україні станом на вересень 2017 року.</p> <h2>Передісторія</h2> <P>Електрична історія Ніссана почалася ще в кінці 1940-х, коли в компанії Tokyo Electro Automobile створили два електромобіля Tama і Tama Senior на свинцевих батареях. У 1951 році фірма об'єдналася з компанією Prince Motor, яка, в свою чергу, в 1966 році стала частиною Ніссана. У 1970-х, 80-х і 90-х роках було безліч концептів, а першим дрібносерійним Ніссаном на батарейках стала Altra EV, яку показали в 1997 році на автосалоні в Лос-Анджелесі. Через пару років з'явився мікроелектрокар Hypermini, але технології масового електромобіля Nissan почав відпрацьовувати набагато пізніше. У другій половині 2000-х в тестах брали участь прототипи на основі моделей Cube і Tiida. Модифіковану платформу Тііди і отримав серійний Leaf, представлений в кінці 2010-го.Продажі почалися в Японії і США у грудні 2010 року, у деяких країнах Європи на початку 2011 року. Станом на листопад 2010, автомобіль виробляється на заводі Оппама, Японія. Потужність японського заводу становила на початку виробництва 50 тисяч одиниць на рік. Виробництво розширилося на заводи в Смирні, штат Теннесі США, у початку 2012, і в Сандерленді, <NAME> у 2013 році. Потужність тих заводів становить 150 і 50 тисяч, відповідно. Nissan Leaf — перший електромобіль, який було номіновано на звання «автомобіль року». </P> <img src="img/nissan_leaf_001.jpg"> <h3>Батарея і пробіг</h3> <P>Одна зарядка акумуляторів дає максимальний пробіг до 160 кілометрів. Повна зарядка акумуляторів займає 8 годин зі звичайною напругою в мережі. Режим швидкої зарядки дозволяє поповнити акумулятори приблизно за 30 хвилин. Електродвигун розвиває потужність 107 кінських сил і тяговий момент 280 ньютонів на метр. Nissan Leaf розганяється до 100 км/год за 10,8 секунд (до 60 км/год приблизно за 5 секунд).</P> <P>Маса батареї близько 600 фунтів (300 кг) і розташована вона у днищі автомобіля, під передніми та задніми сидіннями. Ємності батареї 24 кВт•год із можливістю рекуперативного гальмування вистачає (за оцінками представників Nissan) на 160 км пробігу. Життєвого циклу батареї, за попередніми оцінками, має вистачити мінімум на 5 років.</P> <P>Повний цикл заряду акумуляторів від електромережі з напругою 230 Вольт та електророзеткою на 16 Ампер займає від 6 до 8 годин, 80 % ємності на спеціальному зарядному пристрої Nissan (480 вольт — 125 ампер) за 30 хвилин. Автомобіль обладнаний двома гніздами для зарядних пристроїв в передній частині машини: одне для стандартної, інше — для пришвидшеної підзарядки. Для пришвидшеної зарядки передбачене використання зарядної станції, яка має з'єднувач CHAdeMO (Тип 4 за IEC 62196 ).</P> <P>Із початку виробництва електромобіля на англійському заводі Nissan в Сандерленді (паралельно із кросовером Quashqai), а також, будівництва розташованого тут же заводу із випуску акумуляторів модель 2013 року отримала більше 100 вдосконалень, і серед найважливіших — потужний і ефективний акумулятор, котрий дозволив довести пробіг до 123 миль (199 км) проти 109 миль (175 км) у моделі 2012 року. Крім того, вдвічі (до 4 годин) зменшено час підзарядки від спільного 6,6-кіловатного підзарядного пристрою. В перспективі на Leaf з'являться парковочна камера Around View кругового обзору, шкіряна оббивка салону та ін.</P> <P>Тести показують, енергоспоживання Leaf: 765 кДж/км (21 кВт•год/100 км), що еквівалентно витраті близько 99 MPG (2,4 л / 100 км). У 2016 році на модифікаціях SL і SV встановлюється нова 30-кВт батарея, яка збільшує дальність поїздки до можливих 172,2 км. Модифікація S дешевша і оснащена менш потужною батареєю з запасом ходу до 135,19 км, але цю модель також доповнено 5-дюймовим кольоровим цифровим екраном і аудіосистемою «NissanConnect» з підтримкою мобільних додатків. У модифікаціях SV і SL система «NissanConnect» входить в базову комплектацію. </P> <h4>Продаж</h4> <p>За даними компанії Nissan на початок 2013 року світовий парк електромобілів Leaf становив понад 55000 од., а їх сумарний пробіг склав 288 млн км (для транспортних засобів, зареєстрованих в CARWINGS). Найбільший національний парк Leaf перебуває в експлуатації в Норвегії (понад 3400 автомашин). За підсумками 1 кварталу 2013 року припускають, що Leaf займе в національному хіт-параді продаж легкових автомобілів 5-е місце. Електромобіль Leaf показав найвищий рейтинг задоволеності клієнтів серед всіх моделей Nissan на європейському ринку, рівний 93 %. Згідно з опитуваннями 92% власників Leaf використовують їх майже щодня, 55% власників їздять на них на роботу, 54% водіїв здійснюють в день пробіги понад 60 км.[11] Кількість дилерів, що торгують електромобілем Leaf, підскочила за рік із 150 до більш ніж 1400. Nissan за рахунок власних коштів встановив по Європі тільки в 2012 році понад 400 громадських зарядних станцій. Загальна кількість таких станцій в Європі збільшилась за 2012 рік з 12000 до 20000, крім того, кількість станцій швидкої підзарядки зросла за 2012 рік із 195 до 600 од.</p> <h5>Безпека</h5> <p>Хетчбек Nissan Leaf став першою моделлю, яку експерти EuroNCAP випробували в 2018 році. Відтепер тести проходять по розширеним протоколам. Додатково оцінюються: розпізнавання велосипедистів при автоматичному гальмуванні, виявлення пішоходів в темряві і ефективність систем стеження за розміткою. Відрадно, що жорсткість правил не завадило електрокару повторити свій успіх 2011 року та заробити максимальні п'ять зірок.</p> </div> </div> </div> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script> </body> </html><file_sep>window.onload = function(){ let jumb = document.querySelector('.jumbotron'); let overlay = document.querySelector('#overlay'); let btn = document.querySelector('.jumbotron .btn'); btn.onclick = function(){ jumb.style.display = 'none'; overlay.style.display = 'none'; } }
06f5e075d3cefa1a81cc75bbd1bb4f0f2d324cb9
[ "JavaScript", "HTML" ]
2
HTML
Sanya2112/project
8f06b85c90b182dd6eb8e2cf8fba05e7b2d33f9a
17b67da558614d6646e41b7d3307c58a2d04d0ce
refs/heads/master
<file_sep><?xml version="1.0" encoding="UTF-8"?> <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.yzf</groupId> <artifactId>visualboardtask</artifactId> <packaging>pom</packaging> <version>1.0-SNAPSHOT</version> <modules> <module>visualboardtask-web</module> <module>visualboardtask-client</module> <module>eurake</module> <module>visualboard-facade</module> </modules> <name>visualboardtask</name> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> <spring-boot.version>2.0.5.RELEASE</spring-boot.version> <spring-cloud.version>Finchley.SR1</spring-cloud.version> <yzf.framework.version>2.0.0-SNAPSHOT</yzf.framework.version> <maven-source-plugin.version>3.0.1</maven-source-plugin.version> <maven-compiler-plugin.version>3.6.0</maven-compiler-plugin.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-dependencies</artifactId> <version>${spring-boot.version}</version> <type>pom</type> <scope>import</scope> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>${spring-cloud.version}</version> <type>pom</type> <scope>import</scope> </dependency> <!--<dependency>--> <!--<groupId>com.yzf</groupId>--> <!--<artifactId>rabbitmq-spring-boot-starter</artifactId>--> <!--<version>${yzf.framework.version}</version>--> <!--</dependency>--> <!--<dependency>--> <!--<groupId>com.yzf</groupId>--> <!--<artifactId>redis-spring-boot-starter</artifactId>--> <!--<version>${yzf.framework.version}</version>--> <!--</dependency>--> <!--<dependency>--> <!--<groupId>com.yzf</groupId>--> <!--<artifactId>mybatis-spring-boot-starter</artifactId>--> <!--<version>${yzf.framework.version}</version>--> <!--</dependency>--> </dependencies> <build> <pluginManagement> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>${maven-compiler-plugin.version}</version> <configuration> <source>${java.version}</source> <target>${java.version}</target> <encoding>${project.build.sourceEncoding}</encoding> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-source-plugin</artifactId> <version>${maven-source-plugin.version}</version> <executions> <execution> <id>attach-sources</id> <goals> <goal>jar-no-fork</goal> </goals> </execution> </executions> </plugin> </plugins> </pluginManagement> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-source-plugin</artifactId> </plugin> <!--<plugin>--> <!--<groupId>org.apache.maven.plugins</groupId>--> <!--<artifactId>maven-install-plugin</artifactId>--> <!--</plugin>--> <!--<plugin>--> <!--<groupId>org.apache.maven.plugins</groupId>--> <!--<artifactId>maven-deploy-plugin</artifactId>--> <!--</plugin>--> </plugins> </build> <distributionManagement> <repository> <id>yzf-releases</id> <name>Nexus Release Repository</name> <url>http://yzf2015.imwork.net:8090/nexus/content/repositories/releases/</url> </repository> <snapshotRepository> <id>yzf-snapshots</id> <name>Nexus Snapshot Repository</name> <url>http://yzf2015.imwork.net:8090/nexus/content/repositories/snapshots/</url> </snapshotRepository> </distributionManagement> <pluginRepositories> <pluginRepository> <id>yzf</id> <name>yzf</name> <url>http://yzf2015.imwork.net:8090/nexus/content/groups/public/</url> <releases> <enabled>true</enabled> </releases> <snapshots> <enabled>true</enabled> </snapshots> </pluginRepository> </pluginRepositories> <repositories> <repository> <id>yzf</id> <url>http://yzf2015.imwork.net:8090/nexus/content/groups/public/</url> <releases> <enabled>true</enabled> <updatePolicy>always</updatePolicy> </releases> <snapshots> <enabled>true</enabled> <updatePolicy>always</updatePolicy> </snapshots> </repository> <repository> <id>yzf 3</id> <url>http://yzf2015.imwork.net:8090/nexus/content/repositories/thirdparty/</url> <releases> <enabled>true</enabled> <updatePolicy>always</updatePolicy> </releases> <snapshots> <enabled>true</enabled> <updatePolicy>always</updatePolicy> </snapshots> </repository> <repository> <id>yzf-releases</id> <url>http://yzf2015.imwork.net:8090/nexus/content/repositories/releases</url> <releases> <enabled>true</enabled> <updatePolicy>always</updatePolicy> </releases> <snapshots> <enabled>true</enabled> <updatePolicy>always</updatePolicy> </snapshots> </repository> <repository> <id>yzf-snapshots</id> <url>http://yzf2015.imwork.net:8090/nexus/content/repositories/snapshots</url> <releases> <enabled>true</enabled> <updatePolicy>always</updatePolicy> </releases> <snapshots> <enabled>true</enabled> <updatePolicy>always</updatePolicy> </snapshots> </repository> </repositories> </project> <file_sep>package com.yzf.eurake; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; /** * @author: HJL * @create: 2019-03-05 20:14 */ @EnableEurekaServer @SpringBootApplication public class EurakeServerStart { public static void main(String [] args){ SpringApplication.run(EurakeServerStart.class,args); } }
b6a07e271da3186042ecf225692cd5c0332be90e
[ "Java", "Maven POM" ]
2
Maven POM
kimihufc/springcloudAndDubbo
abe1ad99c1773caea6289ee31848ad6b49317c53
fc3caf3ffad43fd382e2b86f905405b07b2d5813
refs/heads/master
<repo_name>xiangzongliang/golang_study<file_sep>/mapgo.go package main //创建一个类型 type usreInfo struct { ID string NAME string AGE int } func init(){ } func main() { } func mapFun(){ } <file_sep>/home.go package main import ( "fmt" ) func init(){ fmt.Println("首先执行了init函数") //make } func main(){ fmt.Println("在执行了main函数") //测试数组的入参复制问题 //aguArr() //数组切片 arrSlice() //数组遍历 arrFor() //动态添加数组 arrAppend() //数组复制 arrCopy() } func arrCopy(){ arr := []int{1,2,3,4,5,6} arrB := []int{23,57,87,9} fmt.Println(arr,arrB) copy(arr,arrB) fmt.Println(arr) copy(arrB,arr) fmt.Println(arrB) } func arrAppend(){ arr := []int{22,43,64,75,33} arrB := append(arr,48,56,78,32) fmt.Println(arrB) } func arrFor(){ arr := []int{1,2,3} for key,val := range arr{ fmt.Println(key,val) } } //数组切片 func arrSlice(){ var arr [10]int = [10]int{1,2,3,4,5,6,7,8,9,0} arrB := arr[:5] arrC := arr[3:6] fmt.Println(arr) fmt.Println("切片后的数组B为:",arrB) fmt.Println("切片后的数组C为:",arrC) } //数组作为参数传入时会复制一份 func aguArr(){ arr := [7]int{2,3,4,5,6,7,8} arrFun(arr) fmt.Println("传入的参数",arr) } //如果不写多少个数组则是使用了引用类型 func arrFun(getagu [7]int){ getagu[0] = 222 fmt.Println(getagu) } <file_sep>/str.go package main import ( "strings" "fmt" ) func main(){ srt := "这是一段字符串" srt += "增加的第二段文字" //strings.HasPrefix 判断字符串是否以xxx开头 isSrtFist := strings.HasPrefix(srt,"这") //strings.HasSuffix 判断字符串是否以xxx结尾 isSrtLast := strings.HasSuffix(srt,"ha") //strings.Contains 判断字符串是否包含 isSrt := strings.Contains(srt,"一") //返回对应字符串的索引 isIndex := strings.Index(srt,"字") //返回字符串中最后出现的索引 isLastIndex := strings.LastIndex(srt,"字") //替换字符串 rep := strings.Replace(srt,"的","di",1) //统计字符串中出现的次数 cun := strings.Count(srt,"字") fmt.Println(rep) fmt.Println(srt) var newSrt string //重复字符串 newSrt = strings.Repeat(srt,3) fmt.Println("重复字符串:"+newSrt) fmt.Println(isSrtFist,isSrtLast,isSrt,isIndex,isLastIndex,cun) //ToLower 将字符串中的 Unicode 字符全部转换为相应的小写字符 //ToUpper 将字符串中的 Unicode 字符全部转换为相应的大写字符 }
6555f6129e9de7646b4afd4946817052ab04c504
[ "Go" ]
3
Go
xiangzongliang/golang_study
7099261ae71446d38a374a2d6116ac761e447055
185a9569abda32347bbd67ea3b5e00d94f541593
refs/heads/master
<file_sep># ngStore Angular.js wrapper for Store.js. <br /> ## TODO - documentation - unit tests ## Dependencies - `store.js` ## Notes Developed by <a href='http://twitter.com/ishmaelsalive'>ishmaelthedestroyer</a>. <br /> Feedback, suggestions? Tweet me <a href='http://twitter.com/ishmaelsalive'>@IshmaelsAlive</a>. <br /> <br /> ## License Licensed under the MIT license. tl;dr You can do whatever you want with it.<file_sep>/* ========================================================================== Helper functions ========================================================================== */ /** * generate random string * @param length {Number} desired length of string * @returns {String} */ function random(length) { var token = '', list = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijklmnopqrstuvwxyz0123456789'; while (token.length < length) { token += list.charAt(Math.floor(Math.random() * list.length)); } return token; }; /* ========================================================================== Store Factory ========================================================================== */ /** * factory for creating instances of Store * @return {StoreFactory} */ var StoreFactory = function() { if (!(this instanceof StoreFactory)) { return new StoreFactory(); } this.stores = {}; return this; }; /** * gets or creates a Store singleton * @param prefix {String} namespace for the store * @return {Store} */ StoreFactory.prototype.get = function(prefix) { if (!prefix) { prefix = random(10) + '::'; } if (!this.stores[prefix]) { this.stores[prefix] = new Store(prefix); } return this.stores[prefix]; }; /** * used to destroy all Store instances * @return {StoreFactory} */ StoreFactory.prototype.destroy = function() { store.clear(); for (var key in this.stores) { this.stores[key].data = {}; delete this.stores[key]; } return this; };<file_sep>angular.module("ngStore", []) .service("ngStore", [ function() { /* ========================================================================== Helper functions ========================================================================== */ /** * generate random string * @param length {Number} desired length of string * @returns {String} */ function random(length) { var token = '', list = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + 'abcdefghijkl<KEY>'; while (token.length < length) { token += list.charAt(Math.floor(Math.random() * list.length)); } return token; }; /* ========================================================================== Store Factory ========================================================================== */ /** * factory for creating instances of Store * @return {StoreFactory} */ var StoreFactory = function() { if (!(this instanceof StoreFactory)) { return new StoreFactory(); } this.stores = {}; return this; }; /** * gets or creates a Store singleton * @param prefix {String} namespace for the store * @return {Store} */ StoreFactory.prototype.get = function(prefix) { if (!prefix) { prefix = random(10) + '::'; } if (!this.stores[prefix]) { this.stores[prefix] = new Store(prefix); } return this.stores[prefix]; }; /** * used to destroy all Store instances * @return {StoreFactory} */ StoreFactory.prototype.destroy = function() { store.clear(); for (var key in this.stores) { this.stores[key].data = {}; delete this.stores[key]; } return this; }; /* ========================================================================== Store class ========================================================================== */ /** * wrapper for Store.js * @param prefix {String} prefix for keys, allows creating different store instances * @return {Store} */ var Store = function(prefix) { if (!(this instanceof Store)) { return new Store(prefix); } this.prefix = prefix; this.data = {}; // if local storage set, // find all data in store, check if has this Store's prefix // if so, load it into memory if (store.enabled) { var queue = store.getAll(); for (var key in queue) { if (key.substr(0, this.prefix.length) === this.prefix) { this.data[key] = queue[key]; } } } return this; }; /** * retrieves a value from the store * @param key {String} identifier in store * @return {*} */ Store.prototype.get = function(key) { return this.data[this.prefix + key]; }; /** * puts a value into the store * @param key {String} identifier for the store * @param value {*} value to put into the store * @returns {Store} */ Store.prototype.set = function(key, value) { this.data[this.prefix + key] = value; if (store.enabled) { store.set(this.prefix + key, value); } return this; }; /** * removes an item from the store * @param key {String} identifier of item to remove * @return {Store} */ Store.prototype.remove = function(key) { delete this.data[this.prefix + key]; store.remove(this.prefix + key); return this; }; /** * gets all the items in the store * @return {Object} */ Store.prototype.getAll = function() { var alias = this, queue = {}; for (var key in alias.data) { queue[key] = alias.data[key]; } return queue; }; /** * removes all items from the store * @return {Store} */ Store.prototype.clear = function() { var alias = this; if (store.enabled) { for (var key in alias.data) { if (key.substr(0, alias.prefix.length) === alias.prefix) { store.remove(key); } } } this.data = {}; return this; }; return new StoreFactory(); } ]);<file_sep>/* ========================================================================== Store class ========================================================================== */ /** * wrapper for Store.js * @param prefix {String} prefix for keys, allows creating different store instances * @return {Store} */ var Store = function(prefix) { if (!(this instanceof Store)) { return new Store(prefix); } this.prefix = prefix; this.data = {}; // if local storage set, // find all data in store, check if has this Store's prefix // if so, load it into memory if (store.enabled) { var queue = store.getAll(); for (var key in queue) { if (key.substr(0, this.prefix.length) === this.prefix) { this.data[key] = queue[key]; } } } return this; }; /** * retrieves a value from the store * @param key {String} identifier in store * @return {*} */ Store.prototype.get = function(key) { return this.data[this.prefix + key]; }; /** * puts a value into the store * @param key {String} identifier for the store * @param value {*} value to put into the store * @returns {Store} */ Store.prototype.set = function(key, value) { this.data[this.prefix + key] = value; if (store.enabled) { store.set(this.prefix + key, value); } return this; }; /** * removes an item from the store * @param key {String} identifier of item to remove * @return {Store} */ Store.prototype.remove = function(key) { delete this.data[this.prefix + key]; store.remove(this.prefix + key); return this; }; /** * gets all the items in the store * @return {Object} */ Store.prototype.getAll = function() { var alias = this, queue = {}; for (var key in alias.data) { queue[key] = alias.data[key]; } return queue; }; /** * removes all items from the store * @return {Store} */ Store.prototype.clear = function() { var alias = this; if (store.enabled) { for (var key in alias.data) { if (key.substr(0, alias.prefix.length) === alias.prefix) { store.remove(key); } } } this.data = {}; return this; };
55a4114a331ace7629be87f4ed7f7a94fabaf9ef
[ "Markdown", "JavaScript" ]
4
Markdown
ishmaelthedestroyer/ngStore
243ea1e417ef763c92c1f8583742884222d01d53
e6addfc29b02f1f1c10f3f5f3ad00fee4570b534
refs/heads/master
<file_sep>/* SQLyog Enterprise - MySQL GUI v6.56 MySQL - 5.1.43-community : Database - wiki ********************************************************************* */ /*!40101 SET NAMES utf8 */; /*!40101 SET SQL_MODE=''*/; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; CREATE DATABASE /*!32312 IF NOT EXISTS*/`wiki` /*!40100 DEFAULT CHARACTER SET utf8 COLLATE utf8_bin */; USE `wiki`; /*Table structure for table `article` */ DROP TABLE IF EXISTS `article`; CREATE TABLE `article` ( `id` int(7) NOT NULL AUTO_INCREMENT, `title` text COLLATE utf8_bin NOT NULL, `body` text COLLATE utf8_bin NOT NULL, `references` text COLLATE utf8_bin, `url` text COLLATE utf8_bin NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; /*Data for the table `article` */ /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; <file_sep>package com.raghav.processor.main; import com.raghav.db.ConnectionFactory; import com.raghav.model.Article; import com.raghav.processor.MainProcess; import com.raghav.processor.ProcessInfo; import java.sql.Connection; import java.util.List; public abstract class AbstractProcessor implements MainProcess { public final void process(ProcessInfo processInfo) { processInfo.getResults().addAll(this.doProcess()); } abstract List<Article> doProcess(); protected Connection getConnection() throws Exception { return ConnectionFactory.getConnection(); } } <file_sep>package com.raghav.processor.post; import com.raghav.model.Article; import com.raghav.processor.ProcessInfo; import com.raghav.processor.Processor; import com.raghav.processor.ToTextConvertor; public class PrintResultProcessor implements Processor, ToTextConvertor{ public void process(ProcessInfo info) { System.out.println("------------ RESULTS ----------"); for(Article a : info.getResults()){ System.out.println(toText(a)); } System.out.println("------------------------------"); } public String toText(Article a){ return a.toString(); } } <file_sep>package com.raghav.processor.main; import com.raghav.model.Article; import com.raghav.util.ModelUtility; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class QueryByIdProcessor extends AbstractProcessor{ public List<Article> doProcess(){ List<Article> list = new ArrayList<Article>(); final Scanner scanner = new Scanner(System.in); System.out.print("Please type the index between 1 to 10000 : "); try{ int index = scanner.nextInt(); if(index < 1 || index > 10000){ throw new RuntimeException("Invalid Value . Value should be between 1 to 1000..."); } System.out.println("Finding "+ index + " ...."); Article article = findArticle(index); if(article != null ){ list.add(article); } }catch (Exception e){ System.out.println(e.getMessage()); } return list; } public Article findArticle(int index){ Article article = null; Connection connection = null; try{ connection = getConnection(); final PreparedStatement stmt = connection.prepareStatement(getQuery()); stmt.setInt(1, index); ResultSet rs = stmt.executeQuery(); while(rs.next()){ article = ModelUtility.convert(rs); } }catch (Exception e){ System.out.printf(e.getMessage()); }finally { if(connection != null){ try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } return article; } private String getQuery(){ return "select * from article where id = ?"; } } <file_sep>url=jdbc:mysql://localhost:3306/wiki user=root password=<PASSWORD> mongo.host=localhost mongo.port=27017 mongo.user=root mongo.db=wiki mongo.collection=content mongo.password=<PASSWORD><file_sep>package com.raghav.processor.post; import com.raghav.model.Article; import com.raghav.processor.ProcessInfo; import com.raghav.processor.Processor; import com.raghav.processor.ToTextConvertor; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; public class FileResultsProcessor implements Processor , ToTextConvertor { public void process(ProcessInfo info) throws IOException { System.out.println("STORING RESULT TO FILE"); Scanner scanner = new Scanner(System.in); System.out.println("Please enter filename you want to store results"); String filename = scanner.next(); if(!info.getResults().isEmpty()){ System.out.println("Storing results in file "+ ""); FileWriter fileWriter = null; try{ fileWriter = new FileWriter(filename); for(Article article : info.getResults()){ fileWriter.write(toText(article)); } }catch (Exception e){ e.printStackTrace(); }finally { if(fileWriter != null){ fileWriter.close(); } } } } public String toText(Article article) { return article.toString(); } } <file_sep>package com.raghav.processor; import com.raghav.model.Article; import java.io.IOException; import java.util.List; public interface Processor { void process(ProcessInfo info) throws Exception; } <file_sep>package com.raghav.util; import com.raghav.model.Article; import java.sql.ResultSet; import java.sql.SQLException; public class ModelUtility { public static Article convert(ResultSet rs) throws SQLException { final Article article = new Article(); article.setId(rs.getInt("id")); article.setTitle(rs.getString("title")); article.setTitle(rs.getString("body")); article.setReferences(rs.getString("reference")); article.setUrl(rs.getString("url")); return article; } } <file_sep># This project is about importing 10,000 wikipedia articles into our dataabase and enabling them to query from our database. <file_sep>package com.raghav.db; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.Properties; public class ConnectionFactory { private static Connection connection; private static Connection createConnection() throws ClassNotFoundException, IOException, SQLException { final Properties properties = loadProp(); Class.forName("com.mysql.jdbc.Driver"); return DriverManager.getConnection(properties.getProperty("url"), properties.getProperty("user"), properties.getProperty("password")); } public static Properties loadProp() throws IOException { final Properties prop = new Properties(); prop.load(ConnectionFactory.class.getClassLoader().getResourceAsStream("db.properties")); return prop; } public synchronized static Connection getConnection() throws Exception{ if(connection == null){ connection = createConnection(); }else if(connection.isClosed()){ connection = null; return getConnection(); } return connection; } public synchronized static void close() throws Exception{ if(connection != null){ connection.close(); connection = null; } } }
6069d83e15a39dd97d3b9bdbcc4a48597e65a7e6
[ "Java", "SQL", "Markdown", "INI" ]
10
SQL
vranjithreddy/Project_Wikipedia
6cd0c7c5b3b65c5a3c8424a020a8c1650389b0a4
fe4cb6b1226dbd81d1dbfd42c302801966c3c3a2